[
  {
    "path": ".gitignore",
    "content": "_build/\n_files.qmake\n_build_parameters.pl.h\nMakefile*\n/_bin/\n/_include/\nadmin/dist/mac/dsa_priv.pem\n*.idb\n*.pdb\n*.ncb\n*.vcproj*\n*.sln\n*.suo\n.DS_Store\n*.breakpad\n*.user\n*.qm\n*.exe\n*.vscode\nGrowl\nSparkle\n"
  },
  {
    "path": ".gitmodules",
    "content": ""
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n"
  },
  {
    "path": "Last.fm.pro",
    "content": "TEMPLATE = subdirs\nCONFIG += ordered\nSUBDIRS = lib/logger \\\n          lib/unicorn \\\n          lib/listener \\\n          i18n \\\n          app/client \\\n          app/twiddly \\ \n          app/fingerprinter\n          #app/boffin\n\nunix:!mac:SUBDIRS -= app/twiddly\n\nCONFIG( tests ) {\n    SUBDIRS += \\\n        lib/lastfm/core/tests/test_libcore.pro \\\n        lib/lastfm/types/tests/test_libtypes.pro \\\n        lib/lastfm/scrobble/tests/test_libscrobble.pro \\\n        lib/listener/tests/test_liblistener.pro\n}\n"
  },
  {
    "path": "README.md",
    "content": "Join us for chats on IRC!\n\nServer: irc.last.fm\nChannel: #last.desktop\n\n# Build Dependencies\n\n* Qt >= 4.8 (http://download.qt.io/archive/qt/4.8/4.8.7/qt-opensource-windows-x86-vs2010-4.8.7.exe)\n* liblastfm >= 1.0.7\n\nYou will also need depending on your chosen platform:-\n\n## Mac OS X\n\n### Homebrew\n\nWe recommend that you use Homebrew to install most of the dependencies.\n\nWe recommend you have XCode set as your build toolchain.\n\n```\nsudo xcode-select -s /Applications/Xcode.app/Contents/Developer\n\n```\n\n```\nbrew install ffmpeg coreutils cmake fftw libsamplerate\n```\n\n\nWe recommend Qt 4.8.7, the last version with Webkit support.\n\n```\nbrew install cartr/qt4/qt@4\nbrew install cartr/qt4/qt-webkit@2.3\n```\n\n### liblastfm\n\nDownload liblastfm from https://github.com/lastfm/liblastfm parallel to the build of lastfm-desktop.\n\nAs the Desktop Client supports only Qt4 at the moment, you will need to set it to Qt4 mode.\n\nIn CMakeLists.txt, change\n```\noption(BUILD_WITH_QT4 \"Build liblastfm with Qt4\" ON)\n\n```\n\nThen build and make.\n```\ncd liblastfm\nmkdir _build && cd _build\ncmake ..\nmake -j4\nmake install\n```\n\n### Other dependencies\n\nYou'll also need the Growl and libsparkle frameworks.\n\nGet the latest Growl SDk from here http://code.google.com/p/growl/downloads/list - latest tested 1.2.2\n\nGet the latest Sparkle from here http://sparkle.andymatuschak.org/ - latest tested 1.21.3\n\nUnzip both and put their frameworks in /Library/Frameworks/ so the build will find them.\n\nYou may need to symlink the headers files into the lastfm-desktop directory:\n\n```\nln -s /Library/Frameworks/Sparkle.framework/Headers Sparkle\nln -s /Library/Frameworks/Growl.framework/Headers Growl\n```\n\n### Now you're ready!\n\n```\ncd lastfm-desktop\nrm -r _bin\nqmake -r\nmake clean\nmake -j4\n```\n\n\n## Windows\n\nWe used to build using Cygwin, but now we prefer not to.\n\nYou should get Windows version of the tool chain. Here are some recommendations.\n\n- Git: http://code.google.com/p/msysgit/downloads/list\n- CMake: http://www.cmake.org/cmake/resources/software.html\n- pkg-config: http://www.gtk.org/download/win32.php\n- Ruby: http://rubyinstaller.org/\n- Perl: http://www.perl.org/get.html\n- Win Platform SDK:http://www.microsoft.com/en-us/download/details.aspx?id=8279\n- KDE Support: http://windows.kde.org/ Install the automoc and dbus packages.\n\n### Qt\n\nInstall Qt binaries from either the Qt SDK or standalone binary package. You should be able to find everything here http://qt.nokia.com/downloads\n\nYou will also need the latest Windows SDK. We build using Visual Studio 2008.\n\n### Winsparkle\n\nThis is the library we use to check for app updates. You should download the latest dll and headers form here http://winsparkle.org\n\nThis step should be optional really as most people will not want to add the update checking.\n\nI found that I also needed to copy the dll into the lastfm-desktop/_bin folder. Create a pkg-config file for WinSparkle like this:\n\n    Name: sparkle\n    Description: Multimedia Library\n    Version: 0.3\n    Libs: -LC:/dev/Install/WinSparkle/Release -lWinSparkle\n    Cflags: -IC:/dev/Install/WinSparkle/include\n\n## Linux\n\nOn Debian or Ubuntu, you can download all the build dependencies by running:\n\n    sudo apt-get install libavformat-dev libgpod-nogtk-dev liblastfm-dev \\\n                         libqt4-dev libqtwebkit-dev pkg-config \\\n                         zlib1g-dev\n\nYou should also install the `libqt4-sql-sqlite` plugin if you want to use the\nsoftware to scrobble your iPod.\n\n# Build Instructions\n\n    qmake -r\n    make -j4\n    \n`make install` currently does not work on Windows or OSX.\n\nWindows note: use nmake on Windows\n\nLinux note: Linux users can set the install prefix like so `qmake PREFIX=/usr/local`\n\nOSX note: if you installed Qt through homebrew it will default to a release build.\n\n# Run Instructions\n\nApps are styled using stylesheets which are found in the source directory\nof the app. By default the executable path is checked for the css file on\nWindows and on OSX the bundle Resource directory is checked otherwise you'll\nneed to tell the app where the stylesheet is, like this: \n\n    ./Last.fm.exe -stylesheet path/to/Last.fm.css\n    \nOn Linux, if you have not run `make install`, you can run the app like this\nfrom the root of the source directory:\n\n    _bin/lastfm-scrobbler -stylesheet app/client/Last.fm\\ Scrobbler.css\n\n# Build Support\n\nWe support developers trying to build the source on any platform. \n\nSeeing as we don't provide many varieties of binary package on Linux, we also\nsupport non-developers building from source there. However within reason!\nPlease check around the net a little first. Ask your friends. Demand help\nfrom people standing at bus-stops.\n\nMaybe check the official forum: http://getsatisfaction.com/lastfm\n\n# Bugs\n\nIf you find a bug in the software, please let us know about it.\n\nMichael Coffey<michaelc@last.fm>\nDesktop App Lead Developer, Last.fm\n"
  },
  {
    "path": "admin/Doxyfile",
    "content": "# Doxyfile 1.6.1\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project\n#\n# All text after a hash (#) is considered a comment and will be ignored\n# The format is:\n#       TAG = value [value, ...]\n# For lists items can also be appended using:\n#       TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\" \")\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the config file \n# that follow. The default is UTF-8 which is also the encoding used for all \n# text before the first occurrence of this tag. Doxygen uses libiconv (or the \n# iconv built into libc) for the transcoding. See \n# http://www.gnu.org/software/libiconv for the list of possible encodings.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded \n# by quotes) that should identify the project.\n\nPROJECT_NAME           = lastfm-desktop\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. \n# This could be handy for archiving the generated documentation or \n# if some version control system is used.\n\nPROJECT_NUMBER         = \n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) \n# base path where the generated documentation will be put. \n# If a relative path is entered, it will be relative to the location \n# where doxygen was started. If left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       = /Users/jono/dev/lastfm-desktop/_docs\n\n# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create \n# 4096 sub-directories (in 2 levels) under the output directory of each output \n# format and will distribute the generated files over these directories. \n# Enabling this option can be useful when feeding doxygen a huge amount of \n# source files, where putting all generated files in the same directory would \n# otherwise cause performance problems for the file system.\n\nCREATE_SUBDIRS         = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all \n# documentation generated by doxygen is written. Doxygen will use this \n# information to generate all constant output in the proper language. \n# The default language is English, other supported languages are: \n# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, \n# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, \n# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English \n# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, \n# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, \n# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.\n\nOUTPUT_LANGUAGE        = English\n\n# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will \n# include brief member descriptions after the members that are listed in \n# the file and class documentation (similar to JavaDoc). \n# Set to NO to disable this.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend \n# the brief description of a member or function before the detailed description. \n# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the \n# brief descriptions will be completely suppressed.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator \n# that is used to form the text in various listings. Each string \n# in this list, if found as the leading text of the brief description, will be \n# stripped from the text and the result after processing the whole list, is \n# used as the annotated text. Otherwise, the brief description is used as-is. \n# If left blank, the following values are used (\"$name\" is automatically \n# replaced with the name of the entity): \"The $name class\" \"The $name widget\" \n# \"The $name file\" \"is\" \"provides\" \"specifies\" \"contains\" \n# \"represents\" \"a\" \"an\" \"the\"\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then \n# Doxygen will generate a detailed section even if there is only a brief \n# description.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all \n# inherited members of a class in the documentation of that class as if those \n# members were ordinary class members. Constructors, destructors and assignment \n# operators of the base classes will not be shown.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full \n# path before files name in the file list and in the header files. If set \n# to NO the shortest path that makes the file name unique will be used.\n\nFULL_PATH_NAMES        = YES\n\n# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag \n# can be used to strip a user-defined part of the path. Stripping is \n# only done if one of the specified strings matches the left-hand part of \n# the path. The tag can be used to show relative paths in the file list. \n# If left blank the directory from which doxygen is run is used as the \n# path to strip.\n\nSTRIP_FROM_PATH        = /Users/dimitri/doxygen/mail/1.5.7/doxywizard/\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of \n# the path mentioned in the documentation of a class, which tells \n# the reader which header file to include in order to use a class. \n# If left blank only the name of the header file containing the class \n# definition is used. Otherwise one should specify the include paths that \n# are normally passed to the compiler using the -I flag.\n\nSTRIP_FROM_INC_PATH    = \n\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter \n# (but less readable) file names. This can be useful is your file systems \n# doesn't support long names like on DOS, Mac, or CD-ROM.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen \n# will interpret the first line (until the first dot) of a JavaDoc-style \n# comment as the brief description. If set to NO, the JavaDoc \n# comments will behave just like regular Qt-style comments \n# (thus requiring an explicit @brief command for a brief description.)\n\nJAVADOC_AUTOBRIEF      = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then Doxygen will \n# interpret the first line (until the first dot) of a Qt-style \n# comment as the brief description. If set to NO, the comments \n# will behave just like regular Qt-style comments (thus requiring \n# an explicit \\brief command for a brief description.)\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen \n# treat a multi-line C++ special comment block (i.e. a block of //! or /// \n# comments) as a brief description. This used to be the default behaviour. \n# The new default is to treat a multi-line C++ comment block as a detailed \n# description. Set this tag to YES if you prefer the old behaviour instead.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented \n# member inherits the documentation from any documented member that it \n# re-implements.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce \n# a new page for each member. If set to NO, the documentation of a member will \n# be part of the file/class/namespace that contains it.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. \n# Doxygen uses this value to replace tabs by spaces in code fragments.\n\nTAB_SIZE               = 8\n\n# This tag can be used to specify a number of aliases that acts \n# as commands in the documentation. An alias has the form \"name=value\". \n# For example adding \"sideeffect=\\par Side Effects:\\n\" will allow you to \n# put the command \\sideeffect (or @sideeffect) in the documentation, which \n# will result in a user-defined paragraph with heading \"Side Effects:\". \n# You can put \\n's in the value part of an alias to insert newlines.\n\nALIASES                = \n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C \n# sources only. Doxygen will then generate output that is more tailored for C. \n# For instance, some of the names that are used will be different. The list \n# of all members will be omitted, etc.\n\nOPTIMIZE_OUTPUT_FOR_C  = NO\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java \n# sources only. Doxygen will then generate output that is more tailored for \n# Java. For instance, namespaces will be presented as packages, qualified \n# scopes will look different, etc.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran \n# sources only. Doxygen will then generate output that is more tailored for \n# Fortran.\n\nOPTIMIZE_FOR_FORTRAN   = NO\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL \n# sources. Doxygen will then generate output that is tailored for \n# VHDL.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it parses. \n# With this tag you can assign which parser to use for a given extension. \n# Doxygen has a built-in mapping, but you can override or extend it using this tag. \n# The format is ext=language, where ext is a file extension, and language is one of \n# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, \n# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat \n# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), \n# use: inc=Fortran f=C. Note that for custom extensions you also need to set\n# FILE_PATTERNS otherwise the files are not read by doxygen.\n\nEXTENSION_MAPPING      = \n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want \n# to include (a tag file for) the STL sources as input, then you should \n# set this tag to YES in order to let doxygen match functions declarations and \n# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. \n# func(std::string) {}). This also make the inheritance and collaboration \n# diagrams that involve STL classes more complete and accurate.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to \n# enable parsing support.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. \n# Doxygen will parse them like normal C++ but will assume all classes use public \n# instead of private inheritance when no explicit protection keyword is present.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate getter \n# and setter methods for a property. Setting this option to YES (the default) \n# will make doxygen to replace the get and set methods by a property in the \n# documentation. This will only work if the methods are indeed getting or \n# setting a simple type. If this is not the case, or you want to show the \n# methods anyway, you should set this option to NO.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC \n# tag is set to YES, then doxygen will reuse the documentation of the first \n# member in the group (if any) for the other members of the group. By default \n# all members of a group must be documented explicitly.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# Set the SUBGROUPING tag to YES (the default) to allow class member groups of \n# the same type (for instance a group of public functions) to be put as a \n# subgroup of that type (e.g. under the Public Functions section). Set it to \n# NO to prevent subgrouping. Alternatively, this can be done per class using \n# the \\nosubgrouping command.\n\nSUBGROUPING            = YES\n\n# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum \n# is documented as struct, union, or enum with the name of the typedef. So \n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct \n# with name TypeT. When disabled the typedef will appear as a member of a file, \n# namespace, or class. And the struct will be named TypeS. This can typically \n# be useful for C code in case the coding convention dictates that all compound \n# types are typedef'ed and only the typedef is referenced, never the tag name.\n\nTYPEDEF_HIDES_STRUCT   = NO\n\n# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to \n# determine which symbols to keep in memory and which to flush to disk. \n# When the cache is full, less often used symbols will be written to disk. \n# For small to medium size projects (<1000 input files) the default value is \n# probably good enough. For larger projects a too small cache size can cause \n# doxygen to be busy swapping symbols to and from disk most of the time \n# causing a significant performance penality. \n# If the system has enough physical memory increasing the cache will improve the \n# performance by keeping more symbols in memory. Note that the value works on \n# a logarithmic scale so increasing the size by one will rougly double the \n# memory usage. The cache size is given by this formula: \n# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, \n# corresponding to a cache size of 2^16 = 65536 symbols\n\nSYMBOL_CACHE_SIZE      = 0\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in \n# documentation are documented, even if no documentation was available. \n# Private class members and static file members will be hidden unless \n# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES all private members of a class \n# will be included in the documentation.\n\nEXTRACT_PRIVATE        = NO\n\n# If the EXTRACT_STATIC tag is set to YES all static members of a file \n# will be included in the documentation.\n\nEXTRACT_STATIC         = NO\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) \n# defined locally in source files will be included in the documentation. \n# If set to NO only classes defined in header files are included.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. When set to YES local \n# methods, which are defined in the implementation section but not in \n# the interface are included in the documentation. \n# If set to NO (the default) only methods in the interface are included.\n\nEXTRACT_LOCAL_METHODS  = NO\n\n# If this flag is set to YES, the members of anonymous namespaces will be \n# extracted and appear in the documentation as a namespace called \n# 'anonymous_namespace{file}', where file will be replaced with the base \n# name of the file that contains the anonymous namespace. By default \n# anonymous namespace are hidden.\n\nEXTRACT_ANON_NSPACES   = NO\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all \n# undocumented members of documented classes, files or namespaces. \n# If set to NO (the default) these members will be included in the \n# various overviews, but no documentation section is generated. \n# This option has no effect if EXTRACT_ALL is enabled.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all \n# undocumented classes that are normally visible in the class hierarchy. \n# If set to NO (the default) these classes will be included in the various \n# overviews. This option has no effect if EXTRACT_ALL is enabled.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all \n# friend (class|struct|union) declarations. \n# If set to NO (the default) these declarations will be included in the \n# documentation.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any \n# documentation blocks found inside the body of a function. \n# If set to NO (the default) these blocks will be appended to the \n# function's detailed documentation block.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation \n# that is typed after a \\internal command is included. If the tag is set \n# to NO (the default) then the documentation will be excluded. \n# Set it to YES to include the internal documentation.\n\nINTERNAL_DOCS          = NO\n\n# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate \n# file names in lower-case letters. If set to YES upper-case letters are also \n# allowed. This is useful if you have classes or files whose names only differ \n# in case and if your file system supports case sensitive file names. Windows \n# and Mac users are advised to set this option to NO.\n\nCASE_SENSE_NAMES       = NO\n\n# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen \n# will show members with their full class and namespace scopes in the \n# documentation. If set to YES the scope will be hidden.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen \n# will put a list of the files that are included by a file in the documentation \n# of that file.\n\nSHOW_INCLUDE_FILES     = YES\n\n# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] \n# is inserted in the documentation for inline members.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen \n# will sort the (detailed) documentation of file and class members \n# alphabetically by member name. If set to NO the members will appear in \n# declaration order.\n\nSORT_MEMBER_DOCS       = YES\n\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the \n# brief documentation of file, namespace and class members alphabetically \n# by member name. If set to NO (the default) the members will appear in \n# declaration order.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen\n# will sort the (brief and detailed) documentation of class members so that\n# constructors and destructors are listed first. If set to NO (the default)\n# the constructors will appear in the respective orders defined by\n# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.\n# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO\n# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the \n# hierarchy of group names into alphabetical order. If set to NO (the default) \n# the group names will appear in their defined order.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be \n# sorted by fully-qualified names, including namespaces. If set to \n# NO (the default), the class list will be sorted only by class name, \n# not including the namespace part. \n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. \n# Note: This option applies only to the class list, not to the \n# alphabetical list.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or \n# disable (NO) the todo list. This list is created by putting \\todo \n# commands in the documentation.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or \n# disable (NO) the test list. This list is created by putting \\test \n# commands in the documentation.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or \n# disable (NO) the bug list. This list is created by putting \\bug \n# commands in the documentation.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or \n# disable (NO) the deprecated list. This list is created by putting \n# \\deprecated commands in the documentation.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional \n# documentation sections, marked by \\if sectionname ... \\endif.\n\nENABLED_SECTIONS       = \n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines \n# the initial value of a variable or define consists of for it to appear in \n# the documentation. If the initializer consists of more lines than specified \n# here it will be hidden. Use a value of 0 to hide initializers completely. \n# The appearance of the initializer of individual variables and defines in the \n# documentation can be controlled using \\showinitializer or \\hideinitializer \n# command in the documentation regardless of this setting.\n\nMAX_INITIALIZER_LINES  = 26\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated \n# at the bottom of the documentation of classes and structs. If set to YES the \n# list will mention the files that were used to generate the documentation.\n\nSHOW_USED_FILES        = YES\n\n# If the sources in your project are distributed over multiple directories \n# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy \n# in the documentation. The default is NO.\n\nSHOW_DIRECTORIES       = NO\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. \n# This will remove the Files entry from the Quick Index and from the \n# Folder Tree View (if specified). The default is YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the \n# Namespaces page.  This will remove the Namespaces entry from the Quick Index \n# and from the Folder Tree View (if specified). The default is YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that \n# doxygen should invoke to get the current version for each file (typically from \n# the version control system). Doxygen will invoke the program by executing (via \n# popen()) the command <command> <input-file>, where <command> is the value of \n# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file \n# provided by doxygen. Whatever the program writes to standard output \n# is used as the file version. See the manual for examples.\n\nFILE_VERSION_FILTER    = \n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by \n# doxygen. The layout file controls the global structure of the generated output files \n# in an output format independent way. The create the layout file that represents \n# doxygen's defaults, run doxygen with the -l option. You can optionally specify a \n# file name after the option, if omitted DoxygenLayout.xml will be used as the name \n# of the layout file.\n\nLAYOUT_FILE            = \n\n#---------------------------------------------------------------------------\n# configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated \n# by doxygen. Possible values are YES and NO. If left blank NO is used.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are \n# generated by doxygen. Possible values are YES and NO. If left blank \n# NO is used.\n\nWARNINGS               = YES\n\n# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings \n# for undocumented members. If EXTRACT_ALL is set to YES then this flag will \n# automatically be disabled.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for \n# potential errors in the documentation, such as not documenting some \n# parameters in a documented function, or documenting parameters that \n# don't exist or using markup commands wrongly.\n\nWARN_IF_DOC_ERROR      = YES\n\n# This WARN_NO_PARAMDOC option can be abled to get warnings for \n# functions that are documented, but have no documentation for their parameters \n# or return value. If set to NO (the default) doxygen will only warn about \n# wrong or incomplete parameter documentation, but not about the absence of \n# documentation.\n\nWARN_NO_PARAMDOC       = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that \n# doxygen can produce. The string should contain the $file, $line, and $text \n# tags, which will be replaced by the file and line number from which the \n# warning originated and the warning text. Optionally the format may contain \n# $version, which will be replaced by the version of the file (if it could \n# be obtained via FILE_VERSION_FILTER)\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning \n# and error messages should be written. If left blank the output is written \n# to stderr.\n\nWARN_LOGFILE           = \n\n#---------------------------------------------------------------------------\n# configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag can be used to specify the files and/or directories that contain \n# documented source files. You may enter file names like \"myfile.cpp\" or \n# directories like \"/usr/src/myproject\". Separate the files or directories \n# with spaces.\n\nINPUT                  = /Users/jono/dev/lastfm-desktop\n\n# This tag can be used to specify the character encoding of the source files \n# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is \n# also the default input encoding. Doxygen uses libiconv (or the iconv built \n# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for \n# the list of possible encodings.\n\nINPUT_ENCODING         = UTF-8\n\n# If the value of the INPUT tag contains directories, you can use the \n# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp \n# and *.h) to filter out the source-files in the directories. If left \n# blank the following patterns are tested: \n# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx \n# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90\n\nFILE_PATTERNS          = *.c \\\n                         *.cc \\\n                         *.cxx \\\n                         *.cpp \\\n                         *.c++ \\\n                         *.d \\\n                         *.java \\\n                         *.ii \\\n                         *.ixx \\\n                         *.ipp \\\n                         *.i++ \\\n                         *.inl \\\n                         *.h \\\n                         *.hh \\\n                         *.hxx \\\n                         *.hpp \\\n                         *.h++ \\\n                         *.idl \\\n                         *.odl \\\n                         *.cs \\\n                         *.php \\\n                         *.php3 \\\n                         *.inc \\\n                         *.m \\\n                         *.mm \\\n                         *.dox \\\n                         *.py \\\n                         *.f90 \\\n                         *.f \\\n                         *.vhd \\\n                         *.vhdl\n\n# The RECURSIVE tag can be used to turn specify whether or not subdirectories \n# should be searched for input files as well. Possible values are YES and NO. \n# If left blank NO is used.\n\nRECURSIVE              = YES\n\n# The EXCLUDE tag can be used to specify files and/or directories that should \n# excluded from the INPUT source files. This way you can easily exclude a \n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n\nEXCLUDE                = /Users/jono/dev/lastfm-desktop/plugins \\\n                         /Users/jono/dev/lastfm-desktop/lib/3rdparty\n\n# The EXCLUDE_SYMLINKS tag can be used select whether or not files or \n# directories that are symbolic links (a Unix filesystem feature) are excluded \n# from the input.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the \n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude \n# certain files from those directories. Note that the wildcards are matched \n# against the file with absolute path, so to exclude all test directories \n# for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       = moc_* \\\n                         qrc_* \\\n                         ui_*\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names \n# (namespaces, classes, functions, etc.) that should be excluded from the \n# output. The symbol name can be a fully qualified name, a word, or if the \n# wildcard * is used, a substring. Examples: ANamespace, AClass, \n# AClass::ANamespace, ANamespace::*Test\n\nEXCLUDE_SYMBOLS        = \n\n# The EXAMPLE_PATH tag can be used to specify one or more files or \n# directories that contain example code fragments that are included (see \n# the \\include command).\n\nEXAMPLE_PATH           = \n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the \n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp \n# and *.h) to filter out the source-files in the directories. If left \n# blank all files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be \n# searched for input files to be used with the \\include or \\dontinclude \n# commands irrespective of the value of the RECURSIVE tag. \n# Possible values are YES and NO. If left blank NO is used.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or \n# directories that contain image that are included in the documentation (see \n# the \\image command).\n\nIMAGE_PATH             = \n\n# The INPUT_FILTER tag can be used to specify a program that doxygen should \n# invoke to filter for each input file. Doxygen will invoke the filter program \n# by executing (via popen()) the command <filter> <input-file>, where <filter> \n# is the value of the INPUT_FILTER tag, and <input-file> is the name of an \n# input file. Doxygen will then use the output that the filter program writes \n# to standard output.  If FILTER_PATTERNS is specified, this tag will be \n# ignored.\n\nINPUT_FILTER           = \n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern \n# basis.  Doxygen will compare the file name with each pattern and apply the \n# filter if there is a match.  The filters are a list of the form: \n# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further \n# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER \n# is applied to all files.\n\nFILTER_PATTERNS        = \n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using \n# INPUT_FILTER) will be used to filter the input files when producing source \n# files to browse (i.e. when SOURCE_BROWSER is set to YES).\n\nFILTER_SOURCE_FILES    = NO\n\n#---------------------------------------------------------------------------\n# configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will \n# be generated. Documented entities will be cross-referenced with these sources. \n# Note: To get rid of all source code in the generated output, make sure also \n# VERBATIM_HEADERS is set to NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body \n# of functions and classes directly in the documentation.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct \n# doxygen to hide any special comment blocks from generated source code \n# fragments. Normal C and C++ comments will always remain visible.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES \n# then for each documented function all documented \n# functions referencing it will be listed.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES \n# then for each documented function all documented entities \n# called/used by that function will be listed.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) \n# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from \n# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will \n# link to the source code.  Otherwise they will link to the documentation.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code \n# will point to the HTML generated by the htags(1) tool instead of doxygen \n# built-in source browser. The htags tool is part of GNU's global source \n# tagging system (see http://www.gnu.org/software/global/global.html). You \n# will need version 4.8.6 or higher.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen \n# will generate a verbatim copy of the header file for each class for \n# which an include is specified. Set to NO to disable this.\n\nVERBATIM_HEADERS       = YES\n\n#---------------------------------------------------------------------------\n# configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index \n# of all compounds will be generated. Enable this if the project \n# contains a lot of classes, structs, unions or interfaces.\n\nALPHABETICAL_INDEX     = NO\n\n# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then \n# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns \n# in which this list will be split (can be a number in the range [1..20])\n\nCOLS_IN_ALPHA_INDEX    = 5\n\n# In case all classes in a project start with a common prefix, all \n# classes will be put under the same header in the alphabetical index. \n# The IGNORE_PREFIX tag can be used to specify one or more prefixes that \n# should be ignored while generating the index headers.\n\nIGNORE_PREFIX          = \n\n#---------------------------------------------------------------------------\n# configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES (the default) Doxygen will \n# generate HTML output.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. \n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \n# put in front of it. If left blank `html' will be used as the default path.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for \n# each generated HTML page (for example: .htm,.php,.asp). If it is left blank \n# doxygen will generate files with .html extension.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a personal HTML header for \n# each generated HTML page. If it is left blank doxygen will generate a \n# standard header.\n\nHTML_HEADER            = \n\n# The HTML_FOOTER tag can be used to specify a personal HTML footer for \n# each generated HTML page. If it is left blank doxygen will generate a \n# standard footer.\n\nHTML_FOOTER            = \n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading \n# style sheet that is used by each HTML page. It can be used to \n# fine-tune the look of the HTML output. If the tag is left blank doxygen \n# will generate a default style sheet. Note that doxygen will try to copy \n# the style sheet file to the HTML output directory, so don't put your own \n# stylesheet in the HTML output directory as well, or it will be erased!\n\nHTML_STYLESHEET        = \n\n# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, \n# files or namespaces will be aligned in HTML using tables. If set to \n# NO a bullet list will be used.\n\nHTML_ALIGN_MEMBERS     = YES\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML \n# documentation will contain sections that can be hidden and shown after the \n# page has loaded. For this to work a browser that supports \n# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox \n# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files \n# will be generated that can be used as input for Apple's Xcode 3 \n# integrated development environment, introduced with OSX 10.5 (Leopard). \n# To create a documentation set, doxygen will generate a Makefile in the \n# HTML output directory. Running make will produce the docset in that \n# directory and running \"make install\" will install the docset in \n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find \n# it at startup. \n# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.\n\nGENERATE_DOCSET        = NO\n\n# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the \n# feed. A documentation feed provides an umbrella under which multiple \n# documentation sets from a single provider (such as a company or product suite) \n# can be grouped.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that \n# should uniquely identify the documentation set bundle. This should be a \n# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen \n# will append .docset to the name.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# If the GENERATE_HTMLHELP tag is set to YES, additional index files \n# will be generated that can be used as input for tools like the \n# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) \n# of the generated HTML documentation.\n\nGENERATE_HTMLHELP      = NO\n\n# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can \n# be used to specify the file name of the resulting .chm file. You \n# can add a path in front of the file if the result should not be \n# written to the html output directory.\n\nCHM_FILE               = \n\n# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can \n# be used to specify the location (absolute path including file name) of \n# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run \n# the HTML help compiler on the generated index.hhp.\n\nHHC_LOCATION           = \n\n# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag \n# controls if a separate .chi index file is generated (YES) or that \n# it should be included in the master .chm file (NO).\n\nGENERATE_CHI           = NO\n\n# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING \n# is used to encode HtmlHelp index (hhk), content (hhc) and project file \n# content.\n\nCHM_INDEX_ENCODING     = \n\n# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag \n# controls whether a binary table of contents is generated (YES) or a \n# normal table of contents (NO) in the .chm file.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members \n# to the contents of the HTML help documentation and to the tree view.\n\nTOC_EXPAND             = NO\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER \n# are set, an additional index file will be generated that can be used as input for \n# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated \n# HTML documentation.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can \n# be used to specify the file name of the resulting .qch file. \n# The path specified is relative to the HTML output folder.\n\nQCH_FILE               = \n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating \n# Qt Help Project output. For more information please see \n# http://doc.trolltech.com/qthelpproject.html#namespace\n\nQHP_NAMESPACE          = \n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating \n# Qt Help Project output. For more information please see \n# http://doc.trolltech.com/qthelpproject.html#virtual-folders\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. \n# For more information please see \n# http://doc.trolltech.com/qthelpproject.html#custom-filters\n\nQHP_CUST_FILTER_NAME   = \n\n# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see \n# <a href=\"http://doc.trolltech.com/qthelpproject.html#custom-filters\">Qt Help Project / Custom Filters</a>.\n\nQHP_CUST_FILTER_ATTRS  = \n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's \n# filter section matches. \n# <a href=\"http://doc.trolltech.com/qthelpproject.html#filter-attributes\">Qt Help Project / Filter Attributes</a>.\n\nQHP_SECT_FILTER_ATTRS  = \n\n# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can \n# be used to specify the location of Qt's qhelpgenerator. \n# If non-empty doxygen will try to run qhelpgenerator on the generated \n# .qhp file.\n\nQHG_LOCATION           = \n\n# The DISABLE_INDEX tag can be used to turn on/off the condensed index at \n# top of each HTML page. The value NO (the default) enables the index and \n# the value YES disables it.\n\nDISABLE_INDEX          = NO\n\n# This tag can be used to set the number of enum values (range [1..20]) \n# that doxygen will group on one line in the generated HTML documentation.\n\nENUM_VALUES_PER_LINE   = 4\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index \n# structure should be generated to display hierarchical information. \n# If the tag value is set to YES, a side panel will be generated \n# containing a tree-like index structure (just like the one that \n# is generated for HTML Help). For this to work a browser that supports \n# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). \n# Windows users are probably better off using the HTML help feature.\n\nGENERATE_TREEVIEW      = NO\n\n# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, \n# and Class Hierarchy pages using a tree view instead of an ordered list.\n\nUSE_INLINE_TREES       = NO\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be \n# used to set the initial width (in pixels) of the frame in which the tree \n# is shown.\n\nTREEVIEW_WIDTH         = 250\n\n# Use this tag to change the font size of Latex formulas included \n# as images in the HTML documentation. The default is 10. Note that \n# when you change the font size after a successful doxygen run you need \n# to manually remove any form_*.png images from the HTML output directory \n# to force them to be regenerated.\n\nFORMULA_FONTSIZE       = 10\n\n# When the SEARCHENGINE tag is enable doxygen will generate a search box\n# for the HTML output. The underlying search engine uses javascript \n# and DHTML and should work on any modern browser. Note that when using\n# HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP) \n# there is already a search function so this one should typically \n# be disabled.\n\nSEARCHENGINE           = NO\n\n#---------------------------------------------------------------------------\n# configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will \n# generate Latex output.\n\nGENERATE_LATEX         = NO\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. \n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \n# put in front of it. If left blank `latex' will be used as the default path.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be \n# invoked. If left blank `latex' will be used as the default command name.\n\nLATEX_CMD_NAME         = latex\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to \n# generate index for LaTeX. If left blank `makeindex' will be used as the \n# default command name.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact \n# LaTeX documents. This may be useful for small projects and may help to \n# save some trees in general.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used \n# by the printer. Possible values are: a4, a4wide, letter, legal and \n# executive. If left blank a4wide will be used.\n\nPAPER_TYPE             = a4wide\n\n# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX \n# packages that should be included in the LaTeX output.\n\nEXTRA_PACKAGES         = \n\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for \n# the generated latex document. The header should contain everything until \n# the first chapter. If it is left blank doxygen will generate a \n# standard header. Notice: only use this tag if you know what you are doing!\n\nLATEX_HEADER           = \n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated \n# is prepared for conversion to pdf (using ps2pdf). The pdf file will \n# contain links (just like the HTML output) instead of page references \n# This makes the output suitable for online browsing using a pdf viewer.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of \n# plain latex in the generated Makefile. Set this option to YES to get a \n# higher quality PDF documentation.\n\nUSE_PDFLATEX           = YES\n\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\\\batchmode. \n# command to the generated LaTeX files. This will instruct LaTeX to keep \n# running if errors occur, instead of asking the user for help. \n# This option is also used when generating formulas in HTML.\n\nLATEX_BATCHMODE        = NO\n\n# If LATEX_HIDE_INDICES is set to YES then doxygen will not \n# include the index chapters (such as File Index, Compound Index, etc.) \n# in the output.\n\nLATEX_HIDE_INDICES     = NO\n\n# If LATEX_SOURCE_CODE is set to YES then doxygen will include\n# source code with syntax highlighting in the LaTeX output.\n# Note that which sources are shown also depends on other settings\n# such as SOURCE_BROWSER.\n\nLATEX_SOURCE_CODE      = NO\n\n#---------------------------------------------------------------------------\n# configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output \n# The RTF output is optimized for Word 97 and may not look very pretty with \n# other RTF readers or editors.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. \n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \n# put in front of it. If left blank `rtf' will be used as the default path.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES Doxygen generates more compact \n# RTF documents. This may be useful for small projects and may help to \n# save some trees in general.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated \n# will contain hyperlink fields. The RTF file will \n# contain links (just like the HTML output) instead of page references. \n# This makes the output suitable for online browsing using WORD or other \n# programs which support those fields. \n# Note: wordpad (write) and others do not support links.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to doxygen's \n# config file, i.e. a series of assignments. You only have to provide \n# replacements, missing definitions are set to their default value.\n\nRTF_STYLESHEET_FILE    = \n\n# Set optional variables used in the generation of an rtf document. \n# Syntax is similar to doxygen's config file.\n\nRTF_EXTENSIONS_FILE    = \n\n#---------------------------------------------------------------------------\n# configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES (the default) Doxygen will \n# generate man pages\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. \n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \n# put in front of it. If left blank `man' will be used as the default path.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to \n# the generated man pages (default is the subroutine's section .3)\n\nMAN_EXTENSION          = .3\n\n# If the MAN_LINKS tag is set to YES and Doxygen generates man output, \n# then it will generate one additional man file for each entity \n# documented in the real man page(s). These additional files \n# only source the real man page, but without them the man command \n# would be unable to find the correct page. The default is NO.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES Doxygen will \n# generate an XML file that captures the structure of \n# the code including all documentation.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. \n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \n# put in front of it. If left blank `xml' will be used as the default path.\n\nXML_OUTPUT             = xml\n\n# The XML_SCHEMA tag can be used to specify an XML schema, \n# which can be used by a validating XML parser to check the \n# syntax of the XML files.\n\nXML_SCHEMA             = \n\n# The XML_DTD tag can be used to specify an XML DTD, \n# which can be used by a validating XML parser to check the \n# syntax of the XML files.\n\nXML_DTD                = \n\n# If the XML_PROGRAMLISTING tag is set to YES Doxygen will \n# dump the program listings (including syntax highlighting \n# and cross-referencing information) to the XML output. Note that \n# enabling this will significantly increase the size of the XML output.\n\nXML_PROGRAMLISTING     = YES\n\n#---------------------------------------------------------------------------\n# configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will \n# generate an AutoGen Definitions (see autogen.sf.net) file \n# that captures the structure of the code including all \n# documentation. Note that this feature is still experimental \n# and incomplete at the moment.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES Doxygen will \n# generate a Perl module file that captures the structure of \n# the code including all documentation. Note that this \n# feature is still experimental and incomplete at the \n# moment.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES Doxygen will generate \n# the necessary Makefile rules, Perl scripts and LaTeX code to be able \n# to generate PDF and DVI output from the Perl module output.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be \n# nicely formatted so it can be parsed by a human reader.  This is useful \n# if you want to understand what is going on.  On the other hand, if this \n# tag is set to NO the size of the Perl module output will be much smaller \n# and Perl will parse it just the same.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file \n# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. \n# This is useful so different doxyrules.make files included by the same \n# Makefile don't overwrite each other's variables.\n\nPERLMOD_MAKEVAR_PREFIX = \n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will \n# evaluate all C-preprocessor directives found in the sources and include \n# files.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro \n# names in the source code. If set to NO (the default) only conditional \n# compilation will be performed. Macro expansion can be done in a controlled \n# way by setting EXPAND_ONLY_PREDEF to YES.\n\nMACRO_EXPANSION        = NO\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES \n# then the macro expansion is limited to the macros specified with the \n# PREDEFINED and EXPAND_AS_DEFINED tags.\n\nEXPAND_ONLY_PREDEF     = NO\n\n# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files \n# in the INCLUDE_PATH (see below) will be search if a #include is found.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that \n# contain include files that are not input files but should be processed by \n# the preprocessor.\n\nINCLUDE_PATH           = \n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard \n# patterns (like *.h and *.hpp) to filter out the header-files in the \n# directories. If left blank, the patterns specified with FILE_PATTERNS will \n# be used.\n\nINCLUDE_FILE_PATTERNS  = \n\n# The PREDEFINED tag can be used to specify one or more macro names that \n# are defined before the preprocessor is started (similar to the -D option of \n# gcc). The argument of the tag is a list of macros of the form: name \n# or name=definition (no spaces). If the definition and the = are \n# omitted =1 is assumed. To prevent a macro definition from being \n# undefined via #undef or recursively expanded use the := operator \n# instead of the = operator.\n\nPREDEFINED             = \n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then \n# this tag can be used to specify a list of macro names that should be expanded. \n# The macro definition that is found in the sources will be used. \n# Use the PREDEFINED tag if you want to use a different macro definition.\n\nEXPAND_AS_DEFINED      = \n\n# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then \n# doxygen's preprocessor will remove all function-like macros that are alone \n# on a line, have an all uppercase name, and do not end with a semicolon. Such \n# function macros are typically used for boiler-plate code, and will confuse \n# the parser if not removed.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration::additions related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES option can be used to specify one or more tagfiles. \n# Optionally an initial location of the external documentation \n# can be added for each tagfile. The format of a tag file without \n# this location is as follows: \n#   TAGFILES = file1 file2 ... \n# Adding location for the tag files is done as follows: \n#   TAGFILES = file1=loc1 \"file2 = loc2\" ... \n# where \"loc1\" and \"loc2\" can be relative or absolute paths or \n# URLs. If a location is present for each tag, the installdox tool \n# does not have to be run to correct the links. \n# Note that each tag file must have a unique name \n# (where the name does NOT include the path) \n# If a tag file is not located in the directory in which doxygen \n# is run, you must also specify the path to the tagfile here.\n\nTAGFILES               = \n\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create \n# a tag file that is based on the input files it reads.\n\nGENERATE_TAGFILE       = \n\n# If the ALLEXTERNALS tag is set to YES all external classes will be listed \n# in the class index. If set to NO only the inherited external classes \n# will be listed.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed \n# in the modules index. If set to NO, only the current project's groups will \n# be listed.\n\nEXTERNAL_GROUPS        = YES\n\n# The PERL_PATH should be the absolute path and name of the perl script \n# interpreter (i.e. the result of `which perl').\n\nPERL_PATH              = /usr/bin/perl\n\n#---------------------------------------------------------------------------\n# Configuration options related to the dot tool\n#---------------------------------------------------------------------------\n\n# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will \n# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base \n# or super classes. Setting the tag to NO turns the diagrams off. Note that \n# this option is superseded by the HAVE_DOT option below. This is only a \n# fallback. It is recommended to install and use dot, since it yields more \n# powerful graphs.\n\nCLASS_DIAGRAMS         = NO\n\n# You can define message sequence charts within doxygen comments using the \\msc \n# command. Doxygen will then run the mscgen tool (see \n# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the \n# documentation. The MSCGEN_PATH tag allows you to specify the directory where \n# the mscgen tool resides. If left empty the tool is assumed to be found in the \n# default search path.\n\nMSCGEN_PATH            = \n\n# If set to YES, the inheritance and collaboration graphs will hide \n# inheritance and usage relations if the target is undocumented \n# or is not a class.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is \n# available from the path. This tool is part of Graphviz, a graph visualization \n# toolkit from AT&T and Lucent Bell Labs. The other options in this section \n# have no effect if this option is set to NO (the default)\n\nHAVE_DOT               = YES\n\n# By default doxygen will write a font called FreeSans.ttf to the output \n# directory and reference it in all dot files that doxygen generates. This \n# font does not include all possible unicode characters however, so when you need \n# these (or just want a differently looking font) you can specify the font name \n# using DOT_FONTNAME. You need need to make sure dot is able to find the font, \n# which can be done by putting it in a standard location or by setting the \n# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory \n# containing the font.\n\nDOT_FONTNAME           = FreeSans\n\n# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. \n# The default size is 10pt.\n\nDOT_FONTSIZE           = 10\n\n# By default doxygen will tell dot to use the output directory to look for the \n# FreeSans.ttf font (which doxygen will put there itself). If you specify a \n# different font using DOT_FONTNAME you can set the path where dot \n# can find it using this tag.\n\nDOT_FONTPATH           = \n\n# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen \n# will generate a graph for each documented class showing the direct and \n# indirect inheritance relations. Setting this tag to YES will force the \n# the CLASS_DIAGRAMS tag to NO.\n\nCLASS_GRAPH            = YES\n\n# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen \n# will generate a graph for each documented class showing the direct and \n# indirect implementation dependencies (inheritance, containment, and \n# class references variables) of the class with other documented classes.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen \n# will generate a graph for groups, showing the direct groups dependencies\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES doxygen will generate inheritance and \n# collaboration diagrams in a style similar to the OMG's Unified Modeling \n# Language.\n\nUML_LOOK               = NO\n\n# If set to YES, the inheritance and collaboration graphs will show the \n# relations between templates and their instances.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT \n# tags are set to YES then doxygen will generate a graph for each documented \n# file showing the direct and indirect include dependencies of the file with \n# other documented files.\n\nINCLUDE_GRAPH          = YES\n\n# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and \n# HAVE_DOT tags are set to YES then doxygen will generate a graph for each \n# documented header file showing the documented files that directly or \n# indirectly include this file.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH and HAVE_DOT options are set to YES then \n# doxygen will generate a call dependency graph for every global function \n# or class method. Note that enabling this option will significantly increase \n# the time of a run. So in most cases it will be better to enable call graphs \n# for selected functions only using the \\callgraph command.\n\nCALL_GRAPH             = YES\n\n# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then \n# doxygen will generate a caller dependency graph for every global function \n# or class method. Note that enabling this option will significantly increase \n# the time of a run. So in most cases it will be better to enable caller \n# graphs for selected functions only using the \\callergraph command.\n\nCALLER_GRAPH           = YES\n\n# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen \n# will graphical hierarchy of all classes instead of a textual one.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES \n# then doxygen will show the dependencies a directory has on other directories \n# in a graphical way. The dependency relations are determined by the #include \n# relations between the files in the directories.\n\nDIRECTORY_GRAPH        = YES\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images \n# generated by dot. Possible values are png, jpg, or gif \n# If left blank png will be used.\n\nDOT_IMAGE_FORMAT       = png\n\n# The tag DOT_PATH can be used to specify the path where the dot tool can be \n# found. If left blank, it is assumed the dot tool can be found in the path.\n\nDOT_PATH               = \n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that \n# contain dot files that are included in the documentation (see the \n# \\dotfile command).\n\nDOTFILE_DIRS           = \n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of \n# nodes that will be shown in the graph. If the number of nodes in a graph \n# becomes larger than this value, doxygen will truncate the graph, which is \n# visualized by representing a node as a red box. Note that doxygen if the \n# number of direct children of the root node in a graph is already larger than \n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note \n# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the \n# graphs generated by dot. A depth value of 3 means that only nodes reachable \n# from the root by following a path via at most 3 edges will be shown. Nodes \n# that lay further from the root node will be omitted. Note that setting this \n# option to 1 or 2 may greatly reduce the computation time needed for large \n# code bases. Also note that the size of a graph can be further restricted by \n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n\nMAX_DOT_GRAPH_DEPTH    = 0\n\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent \n# background. This is disabled by default, because dot on Windows does not \n# seem to support this out of the box. Warning: Depending on the platform used, \n# enabling this option may lead to badly anti-aliased labels on the edges of \n# a graph (i.e. they become hard to read).\n\nDOT_TRANSPARENT        = NO\n\n# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output \n# files in one run (i.e. multiple -o and -T options on the command line). This \n# makes dot run faster, but since only newer versions of dot (>1.8.10) \n# support this, this feature is disabled by default.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will \n# generate a legend page explaining the meaning of the various boxes and \n# arrows in the dot generated graphs.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will \n# remove the intermediate dot files that are used to generate \n# the various graphs.\n\nDOT_CLEANUP            = YES\n"
  },
  {
    "path": "admin/dist/mac/AppleScriptSuite.sdef",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE dictionary SYSTEM \"file://localhost/System/Library/DTDs/sdef.dtd\">\n<dictionary xmlns:xi=\"http://www.w3.org/2001/XInclude\" title=\"Last.fm Terminology\">\n\t<!-- <xi:include href=\"file:///System/Library/ScriptingDefinitions/CocoaStandard.sdef\" xpointer=\"xpointer(/dictionary/suite)\"/> -->\n\t<suite name=\"Last.fm Suite\" code=\"Last\" description=\"Last.fm Scripting Suite\">\n\t\t<value-type name=\"Lastfm image\" code=\"aImg\" description=\"Image data in TIFF format\">\n\t\t\t<cocoa class=\"NSData\"/>\n\t\t</value-type>\n\t\t<class name=\"application\" code=\"capp\" description=\"The application&apos;s top-level scripting object.\">\n\t\t\t<cocoa class=\"NSApplication\"/>\n\t\t\t<property name=\"track title\" code=\"aTtl\" description=\"Title of currently playing track.\" type=\"text\" access=\"r\">\n\t\t\t\t<cocoa key=\"trackTitle\"/>\n\t\t\t</property>\n\t\t\t<property name=\"artist\" code=\"aArt\" description=\"Artist of currently playing track.\" type=\"text\" access=\"r\"/>\n\t\t\t<property name=\"album\" code=\"aAlb\" description=\"Album of currently playing track.\" type=\"text\" access=\"r\"/>\n\t\t\t<property name=\"duration\" code=\"aDur\" description=\"Duration of currently playing track.\" type=\"integer\" access=\"r\"/>\n\t\t\t<property name=\"loved\" code=\"aLov\" description=\"The loved status of currently playing track.\" type=\"boolean\" access=\"r\"/>\n\t\t\t<property name=\"artwork\" code=\"aAwk\" description=\"Artwork for the currently playing track.\" access=\"r\">\n\t\t\t\t<type type=\"Lastfm image\"/>\n\t\t\t</property>\n\t\t</class>\n\t\t<command name=\"playpause\" code=\"Lastplpa\" description=\"Toggle playback between playing and paused.\">\n\t\t\t<cocoa class=\"LastfmPlayPauseCommand\"/>\n\t\t</command>\n\t\t<command name=\"next\" code=\"Lastnext\" description=\"Play the next track.\">\n\t\t\t<cocoa class=\"LastfmNextCommand\"/>\n\t\t</command>\n\t\t<command name=\"previous\" code=\"Lastprev\" description=\"Play the previous track.\">\n\t\t\t<cocoa class=\"LastfmPrevCommand\"/>\n\t\t</command>\n\t\t<command name=\"love\" code=\"Lastlove\" description=\"Love the current track.\">\n\t\t\t<cocoa class=\"LastfmLoveCommand\"/>\n\t\t</command>\n\t\t<command name=\"ban\" code=\"Lastbann\" description=\"Ban the current track.\">\n\t\t\t<cocoa class=\"LastfmBanCommand\"/>\n\t\t</command>\n\t</suite>\n</dictionary>"
  },
  {
    "path": "admin/dist/mac/Growl Registration Ticket.growlRegDict",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs/PropertyList.dtd\">\n<plist version=\"0.9\">\n<dict>\n    <key>TicketVersion</key>\n    <integer>1</integer>\n    <key>AllNotifications</key>\n    <array>\n\t\t<string>New track</string>\n\t</array>\n\t<key>DefaultNotifications</key>\n    <array>\n\t\t<string>New track</string>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "admin/dist/mac/Standard.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleIconFile</key>\n\t<string>@ICON@</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleExecutable</key>\n\t<string>@EXECUTABLE@</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>fm.last.Scrobbler</string>\n\t<key>CFBundleVersion</key>\n\t<string>2.1.39</string>\n\t<key>SUFeedURL</key>\n\t<string>https://cdn.last.fm/client/Mac/updates.xml</string>\n\t<key>SUEnableAutomaticChecks</key>\n\t<true/>\n\t<key>SUEnableSystemProfiling</key>\n\t<false/>\n\t<key>SUShowReleaseNotes</key>\n\t<true/>\n\t<key>SUScheduledCheckInterval</key>\n\t<integer>86400</integer>\n\t<key>SUAllowsAutomaticUpdates</key>\n\t<false/>\n\t<key>SUPublicDSAKeyFile</key>\n\t<string>dsa_pub.pem</string>\n\t<key>CFBundleDisplayName</key>\n\t<string>@EXECUTABLE@</string>\n\t<key>OSAScriptingDefinition</key>\n\t<string>AppleScriptSuite.sdef</string>\n\t<key>NSAppleScriptEnabled</key>\n\t<true/>\n\t<key>NSAppleEventsUsageDescription</key>\n\t<string>For Music and iTunes, this enables scrobbling. For Spotify, this lets you see Last.fm info about the currently playing song.</string>\n\t<key>BreakpadProduct</key>\n\t<string>@EXECUTABLE@</string>\n\t<key>BreakpadVendor</key>\n\t<string>@EXECUTABLE@</string>\n\t<key>BreakpadURL</key>\n\t<string>http://oops.last.fm/report/add</string>\n\t<key>BreakpadReportInterval</key>\n\t<string>30</string>\n\t<key>BreakpadRequestComments</key>\n\t<string>YES</string>\n\t<key>CFBundleName</key>\n\t<string>Last.fm Scrobbler</string>\n\t<key>NSHighResolutionCapable</key>\n\t<true/>\n    <key>CFBundleURLTypes</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>CFBundleURLName</key>\n\t\t\t<string>Last.fm</string>\n\t\t\t<key>CFBundleURLSchemes</key>\n\t\t\t<array>\n\t\t\t\t<string>lastfm</string>\n\t\t\t</array>\n\t\t</dict>\n\t</array>\n\t<key>LSUIElement</key>\n\t<true/>\n</dict>\n</plist>\n"
  },
  {
    "path": "admin/dist/mac/build-release.rb",
    "content": "### Usage build-release.rb --deltas <version> <version> [--no-build] [--no-package]\n# the deltas should be in a zip in the filder under bin with the expected filename format\n# example /_bin/<version>/Last.fm-<version>\n# TODO: download the previous versions from cdn and use that for the delta\n#       there's no chance they'll be wrong then\n\nrequire 'rexml/document'\n\n# find the app version from the app's Info.plist\nxml_data = File::read( \"admin/dist/mac/Standard.plist\" )\n\n# extract event information\ndoc = REXML::Document.new(xml_data)\n\ndoc.elements.each('plist/dict/key') do |ele|\n\tif ele.text == \"CFBundleVersion\"\n\t\t$version = ele.next_element().text\n\tend\nend\n\nprint \"Building version #{$version}\\n\"\n\n# get the delta versions from the command line\n$deltas = []\ndeltasIndex = ARGV.index(\"--deltas\")\n\nif deltasIndex != nil\n\twhile deltasIndex + 1 < ARGV.length and not ARGV.at( deltasIndex + 1 ).start_with?(\"--\")\n\t\tdeltasIndex = deltasIndex + 1\n\t\tprint \"Creating binary delta for version #{ARGV.at(deltasIndex)}\\n\"\n\t\t$deltas << ARGV.at(deltasIndex)\n\tend\nend\n\n\n\n$upload_folder = '/tmp/desktop_client_app_release/'\n$download_folder = 'http://users.last.fm/~michael/client/Mac'\n\n## Check that we are running from the root of the lastfm-desktop project\n# ?\n\ndef clean\n\t## clean everything\n\tsystem 'make clean'\n\tsystem 'make distclean'\nend\n\ndef build\n\t## build everything\n\tDir.chdir(\"../liblastfm\") do\n\t\tsystem \"rm -rf _release\"\n\t\tDir.mkdir(\"_release\")\n\t\tDir.chdir(\"_release\") do\n\t\t\tsystem 'cmake -D CMAKE_BUILD_TYPE:STRING=Release ..'\n\t\t\tsystem 'make -j8 install'\n\t\tend\n\tend\n\n\tsystem 'qmake -r CONFIG+=release'\n\t# Hack to fix the /Library/Framework includes\n\tsystem 'sed -i -e \"s/-I-F/-F/g\" lib/unicorn/Makefile'\n\tsystem 'make'\n\n\tsystem 'rm -rf _bin/Last.fm.app'\n\tsystem 'mv \"_bin/Last.fm Scrobbler.app\" _bin/Last.fm.app'\nend\n\ndef copy_plugin\n\t## copy the iTunes plugin into the bundle\n\tsystem \"cp -R _bin/Audioscrobbler.bundle '_bin/Last.fm.app/Contents/MacOS/'\"\nend\n\ndef sign_app\n\t# We need to fix the QT dependencies, as they are not in a state to be signed in El Capitan\n\t# and we're not upgrading to QT5 at the moment\n\tputs \"======= Fixing Qt Framework and Codesigning ===========\"\n\tDir.foreach('_bin/Last.fm.app/Contents/Frameworks') do |framework|\n\t\tif framework.start_with?('Qt')\n\t\t\tputs \"fixing #{framework} for codesigning\"\n\t\t\tsystem \"mkdir -p _bin/Last.fm.app/Contents/Frameworks/#{framework}/Versions/Current/Resources\"\n\t\t\tsystem \"mv _bin/Last.fm.app/Contents/Frameworks/#{framework}/Contents/Info.plist _bin/Last.fm.app/Contents/Frameworks/#{framework}/Versions/Current/Resources/Info.plist\"\n\t\t\tsystem \"rmdir _bin/Last.fm.app/Contents/Frameworks/#{framework}/Contents\"\n\t\t\tsystem \"rm _bin/Last.fm.app/Contents/Frameworks/#{framework}/*.prl\"\n\t\tend\n\tend\n\tputs \"signing application and bundled frameworks\"\n\tsystem 'codesign -f --deep -s \"Developer ID Application: Last.fm\" -i fm.last.Scrobbler _bin/Last.fm.app'\nend\n\ndef create_zip\n\t## create a zip file\n\tDir.chdir(\"_bin\") do\n\t\tsystem \"rm -rf #{$version}\"\n\t\tsystem \"mkdir #{$version}\"\n\t\tsystem \"tar cjf #{$version}/Last.fm-#{$version}.tar.bz2 'Last.fm.app'\"\n\t\tDir.chdir(\"Last.fm.app/Contents\") do\n\t\t\tsystem \"tar cjf ../../#{$version}/Last.fm_Mac_Update_#{$version}.tar.bz2 *\"\n\t\tend\n\t\tsystem \"zip -ry #{$version}/Last.fm-#{$version}.zip 'Last.fm.app'\"\n\tend\nend\n\ndef create_deltas\n\t## create any deltas\n\tDir.chdir(\"_bin\") do\n\t\t# unzip the new app\n\t\tputs \"unzipping #{$version}\"\n\t\tsystem \"unzip -q #{$version}/Last.fm-#{$version}.zip -d #{$version}\"\n\n\t\t$deltas.each do |delta|\n\t\t\t# unzip the old version (try both compression formats)\n\t\t\tputs \"unzipping #{delta}\"\n\t\t\t#system 'tar -xjf Last.fm-#{delta}.tar.bz2 -C #{delta}'\n\t\t\tsystem \"unzip -q #{delta}/Last.fm-#{delta}.zip -d #{delta}\"\n\t\t\t# create the delta\n\t\t\tsystem \"./BinaryDelta create #{delta}/Last.fm.app #{$version}/Last.fm.app #{$version}/Last.fm-#{$version}-#{delta}.delta\"\n\t\t\t# check that it worked\n\t\t\tsystem \"./BinaryDelta apply #{delta}/Last.fm.app #{$version}/Last.fm.app #{$version}/Last.fm-#{$version}-#{delta}.delta\"\n\t\t\t# remove the unzipped old version\n\t\t\tsystem \"rm -rf #{delta}/Last.fm.app\"\n\t\tend\n\n\t\t# delete the unzipped new app\n\t\tsystem \"rm -rf #{$version}/Last.fm.app\"\n\tend\nend\n\ndef upload_files\n\t# scp the main zip file\n\t# scp all the deltas\n\t# put them in my userhome if we are doing a test update\n\n\tsystem \"cp _bin/#{$version}/Last.fm-#{$version}.tar.bz2 #{$upload_folder}\"\n\tsystem \"cp _bin/#{$version}/Last.fm_Mac_Update_#{$version}.tar.bz2 #{$upload_folder}\"\n\tsystem \"cp _bin/#{$version}/Last.fm-#{$version}.zip #{$upload_folder}\"\n\n\t$deltas.each do |delta|\n\t\tsystem \"scp _bin/#{$version}/Last.fm-#{$version}-#{delta}.delta badger:#{$upload_folder}\"\n\tend\nend\n\ndef generate_appcast_xml\n\t## sign the zip file and deltas\n\n\tFile.open(\"update.xml\", 'w') do |f|\n\n\t\titem = \"<item>\\n\"\n\t\titem << \"\\t<title>#{$version}</title>\\n\"\n\t\titem << \"\\t<pubDate></pubDate>\\n\"\n\n\t\tversion_sig = `ruby admin/dist/mac/sign_update.rb _bin/#{$version}/Last.fm-#{$version}.tar.bz2 admin/dist/mac/dsa_priv.pem`.strip\n\t\tversion_size = `du _bin/#{$version}/Last.fm-#{$version}.tar.bz2`.split[0]\n\n\t\titem << \"\\t<enclosure\\n\\t\\tsparkle:version=\\\"#{$version}\\\"\\n\\t\\turl=\\\"#{$download_folder}/Last.fm-#{$version}.tar.bz2\\\"\\n\\t\\tlength=\\\"#{version_size}\\\"\\n\\t\\ttype=\\\"application/octet-stream\\\"\\n\\t\\tsparkle:dsaSignature=\\\"#{version_sig}\\\"/>\\n\"\n\t\titem << \"\\t<sparkle:deltas>\\n\"\n\n\t\t$deltas.each do |delta|\n\t\t\tdelta_sig = `ruby admin/dist/mac/sign_update.rb _bin/#{$version}/Last.fm-#{$version}-#{delta}.delta admin/dist/mac/dsa_priv.pem`.strip\n\t\t\tdelta_du = `du _bin/#{$version}/Last.fm-#{$version}-#{delta}.delta`.split[0]\n\t\t\titem << \"\\t\\t<enclosure\\n\\t\\t\\turl=\\\"#{$download_folder}/Last.fm-#{$version}-#{delta}.delta\\\"\\n\\t\\t\\tsparkle:version=\\\"#{$version}\\\"\\n\\t\\t\\tsparkle:deltaFrom=\\\"#{delta}\\\"\\n\\t\\t\\tlength=\\\"#{delta_du}\\\"\\n\\t\\t\\ttype=\\\"application/octet-stream\\\"\\n\\t\\t\\tsparkle:dsaSignature=\\\"#{delta_sig}\\\"/>\\n\"\n\t\tend\n\n\t\titem << \"\\t</sparkle:deltas>\\n\"\n\t\titem << \"\\t<description></description>\\n\"\n\t\titem << \"</item>\\n\"\n\n\t\tf.syswrite item\n\tend\nend\n\nif not ARGV.include?( \"--no-build\" )\n\t# build the app\n\tclean\n\tbuild\n\tcopy_plugin\n\tsign_app\nend\nif not ARGV.include?( \"--no-package\" )\n\t# package and upload the app\n\tcreate_zip\n\tcreate_deltas\n\tupload_files\n\tgenerate_appcast_xml\nend\n\n"
  },
  {
    "path": "admin/dist/mac/bundleFrameworks.sh",
    "content": "#!/bin/bash\n# Author: Jono Cole <jono@last.fm>\n#\n# A tool for distributing Mac OSX bundles.\n#\n# Finds and copies dependant frameworks and local dylibs \n# not installed on stardard systems.\n# Also ensures that all binaries have the correct paths \n# installed relative to the bundle's @executable_path\n\nfunction getBundleBin {\n    if echo $1|grep -q framework; then\n        echo $1/`cat \"$1/Contents/Info.plist\" | sed -n '/CFBundleExecutable<\\/key>/,/<\\/string>/ s/.*<string>\\(.*\\)<.*/\\1/p'|sed s/_debug//`\n    else\n        echo $1/Contents/MacOS/`cat \"$1/Contents/Info.plist\" | sed -n '/CFBundleExecutable<\\/key>/,/<\\/string>/ s/.*<string>\\(.*\\)<.*/\\1/p'`\n    fi\n}\n\nfunction fixFrameworks {\n    echo -n F\n    if [ -d \"$1\" ]; then\n        local bin=\"`getBundleBin \"$1\"`\"\n    else\n        local bin=\"$1\"\n    fi\n\n    # echo Fixing Frameworks for $bin\n\n    libs=`otool -L \"$bin\"|sed -n '/\\/usr\\/local.*/ s/^[^\\/]*\\([^(]*\\) [^(]*([^)]*)/\\1/p'`\n    \n    mkdir -p \"$bundlePath/Contents/Frameworks\"\n\n    local lib\n    for lib in $libs; do\n        #ignore non-frameworks\n        if echo $lib | grep -vq framework; then continue; fi\n\n        #examples for /opt/qt/lib/QtXml.framework/Contents/QtXml\n\n        #framework=/opt/qt/qt.git/lib/QtXml.framework\n        framework=`echo $lib |sed -n 's/\\(\\.framework\\).*/\\1/p'`\n        \n        #frameworkLib=/Contents/QtXml\n        frameworkLib=`echo $lib |sed -n 's/^.*\\.framework//p'`\n\n        #frameworkName=QtXml.framework\n        frameworkName=`basename $framework`\n        \n        destFramework=$bundlePath/Contents/Frameworks/$frameworkName\n        installFramework=@executable_path/../Frameworks/$frameworkName\n        \n        if [ \"`basename $lib`\" == \"`basename $bin`\" ]; then continue; fi\n\n        if [ ! -e \"$bundlePath/Contents/Frameworks/$frameworkName\" ]; then \n            #cp -Rf -P /opt/qt/qt.git/lib/QtXml.framework (app name.app)/Contents/Frameworks\n            cp -R -H -f $framework \"$bundlePath/Contents/Frameworks\"\n            chmod -R u+w \"$bundlePath/Contents/Frameworks\"\n\n            #install_name_tool -id /opt/qt/qt.git/lib/QtXml.framework/Contents/QtXml\n            install_name_tool -id $installFramework$frameworkLib \"$destFramework$frameworkLib\"\n        fi\n        #install_name_tool -change /opt/qt/qt.git/lib/QtXml.framework/Contents/QtXml @executable_path/../Frameworks/QtXml.framework/Contents/QtXml (bin)\n        install_name_tool -change $lib $installFramework$frameworkLib \"$bin\"\n        fixLocalLibs \"$destFramework\"\n        fixFrameworks \"$destFramework\"\n    done\n}\n\nfunction fixLocalLibs {\n    echo -n L\n    if [ -d \"$1\" ]; then\n        local bin=`getBundleBin \"$1\"`\n    else\n        local bin=\"$1\"\n    fi\n    echo Fixing Local Lib for $bin\n\n    local libs=`otool -L \"$bin\" | sed -n '/^[^\\/]*$/ s/^[[:space:]]*\\(.*\\) (com.*/\\1/p'`\n    local extralibs=`otool -L \"$bin\" | sed -n '/\\/usr\\/local.*/ s/^[^\\/]*\\([^(]*\\) [^(]*([^)]*)/\\1/p'|grep -v framework`\n    local moreExtralibs=`otool -L \"$bin\" | sed -n '/\\/usr\\/X11.*/ s/^[^\\/]*\\([^(]*\\) [^(]*([^)]*)/\\1/p'|grep -v framework`\n    local libs=\"$libs $extralibs $moreExtralibs\"\n    local lib\n    local cpPath\n    for lib in $libs; do\n        local libPath=$lib\n        if [ ! -e $lib ]; then\n            cpPath=`locateLib $lib`\n        else\n            cpPath=$lib\n        fi\n\n        resolvedLib=`/usr/local/bin/greadlink -f $cpPath`\n        basenameLib=`basename $resolvedLib`\n\n\t\techo $cpPath \"$bundlePath/Contents/MacOS\"\n\n        cp -RLf $resolvedLib \"$bundlePath/Contents/MacOS/\"\n\n        chmod -R u+w \"$bundlePath/Contents/MacOS\"\n\n        install_name_tool -id @executable_path/../MacOS/$basenameLib \"$bundlePath/Contents/MacOS/$basenameLib\"\n        install_name_tool -change $libPath @executable_path/../MacOS/$basenameLib \"$bin\"\n        \n        fixFrameworks \"$bundlePath/Contents/MacOS/$basenameLib\"\n        fixLocalLibs \"$bundlePath/Contents/MacOS/$basenameLib\"\n    done\n}\n\nfunction locateLib {\n    for p in {$rootdir,/usr/local/lib}; do\n        if [ -e $p/$1 ]; then\n            echo $p/$1\n            return 0\n        fi\n    done\n    return 1\n}\n\nif [ -d '$1' ]; then\n    bundlePath=\"$1\"\nelse\n    bundlePath=$(echo $1 | sed -E \"s|^(.*)\\.app.*$|\\1\\.app|g\")\nfi\n\nrootdir=`dirname \"$bundlePath\"`\nbinPath=$bundlePath/Contents/MacOS\n\necho =========== Fix Local Libs ==============\nif [ -d '$1' ]; then\n    fixLocalLibs \"$bundlePath\"\nelse\n    fixLocalLibs \"$1\"\nfi\n\necho\n\necho =========== Fix Frameworks ==============\nif [ -d '$1' ]; then\n    fixFrameworks \"$bundlePath\"\nelse\n    fixFrameworks \"$1\"\nfi\n\necho\n\necho ======= Copying 3rd party frameworks ===========\n\ncp -R -H -f /Library/Frameworks/Growl.framework \"$bundlePath/Contents/Frameworks\"\ncp -R -H -f /Library/Frameworks/Sparkle.framework \"$bundlePath/Contents/Frameworks\"\n#cp -R -L -f /Library/Frameworks/Breakpad.framework \"$bundlePath/Contents/Frameworks\"\n\necho\n\necho ======= Copying Qt plugins ===========\nmkdir -p \"$bundlePath/Contents/plugins\"\n\nplugins=\"imageformats sqldrivers bearer\"\n\nfor plugin in $plugins; do\n    if [ -d /Developer/Applications/Qt/plugins/ ]; then\n        pluginDir=/Developer/Applications/Qt/plugins\n    elif [ -d /usr/local/lib/qt4/plugins/ ]; then\n        # Qt installed using Homebrew will be found in your local lib.\n        # Currently we only support qt v4.8.7.\n        pluginDir=/usr/local/lib/qt4/plugins\n    else\n        pluginDir=`qmake --version |sed -n 's/^.*in \\(\\/.*$\\)/\\1/p'`/../plugins\n    fi\n    cp -v -R -L -f $pluginDir/$plugin \"$bundlePath/Contents/plugins\"\n    chmod -R -v u+w \"$bundlePath/Contents/plugins\"\n    for i in \"$bundlePath\"/Contents/plugins/$plugin/*; do\n        fixFrameworks \"$i\"\n        fixLocalLibs \"$i\"\n        echo -n P\n    done\n    echo\ndone\n\necho ======= Copying Qt translations ===========\nmkdir -p \"$bundlePath/Contents/Resources/qm\"\n\ntranslations=\"qt_de.qm\n                qt_es.qm \n                qt_fr.qm \n                qt_ja.qm \n                qt_pl.qm \n                qt_pt.qm \n                qt_ru.qm \n                qt_sv.qm \n                qt_zh_CN.qm\"\n\nfor translation in $translations; do\n    if [ -d /Developer/Applications/Qt/plugins/ ]; then\n        translationDir=/Developer/Applications/Qt/translations\n    elif [ -d /usr/local/Cellar/qt@4/4.8.7_5/translations/ ]; then\n        # Qt installed using Homebrew will be found in the Homebrew Cellar.\n        # Currently we only support qt v4.8.7.\n        translationDir=/usr/local/Cellar/qt@4/4.8.7_5/translations\n    else\n        translationDir=`qmake --version |sed -n 's/^.*in \\(\\/.*$\\)/\\1/p'`/../translations\n    fi\n\n    cp -v -f $translationDir/$translation \"$bundlePath/Contents/Resources/qm\"\n    echo\ndone\n\n\necho ======= creating qt.conf ===========\nqtconf=$bundlePath/Contents/Resources/qt.conf\necho [Paths] > \"$qtconf\"\necho Plugins = ../plugins >> \"$qtconf\"\n"
  },
  {
    "path": "admin/dist/mac/dsa_pub.pem",
    "content": "-----BEGIN PUBLIC KEY-----\nMIIDPDCCAi4GByqGSM44BAEwggIhAoIBAQDagjvSe6+JNNvHjB6aWriA6YXnVdqS\ns//YkmhwiCwkHGk0set/4P4IZbl2xkpd/hyo9qQnnhjou0llHOaljU8Yp6g61lt9\nn/BhlhPt7tvBkTtsugJ4YIRkaakzscLUIoeHneF8D3B3Ej2xoZ734Rq/LDc9jZgd\nUNjS+sZec69waEp2ikcmkvfAbZ0yPHHhl0xftaA0A9OqaBBDUyxiBOqWfLQexj9L\nDHlx38kGy3lsuqY9DQQ0BbIv24QKDWDFf9GD/TEXgVOBAiIC4cGVUh2JgQVAZ0nk\n86pwavc1uIPynTyje902MI0ojFPLuhuod7QAO9NNBFD3024n+uv7mPi5AhUAqo2v\nmsdlE3NsONzW4uBVGujvNNUCggEBANlg+4w6ikFI8agyolAl9YepP0dcwk33MSXY\n2Plwqp/41yIpFzb9qp0QKjfmtwy+cAdWcVcN8xKM9MghVgTukttdV9Rz8fwnfHAa\nQMoYVhHBNDaipR0RRpx+NPnMkKPrYiH1+J4C8/MYAsDEB0xa7Vv/EasA0yWD3mhK\nydm9O2Njj1J2ZEQ4Nz+9ba7wDLpZVM/P9fitZalVyWxFVPxhYs3ifUSCgE+fYGR2\nVBiwBZiQ8uKf+yJpmYQkUA4/h54S2hiCQHrSS9A9L0Ekdj+Jy07lPGv6IAlhzcfQ\nOyiNzmbEgsR8LLo6H54/JxTwElt/TsdpWP8n83l4KFVN00eAZSgDggEGAAKCAQEA\nus92grNvv1zRXmBpsEPPhy5hGhcslBy5ZWygUytgwupjq8MkpkD3yez649qVTUAt\nE4SJUW+6EKbcLZSBRBdMWZNwudrHCly4n6OMOh4ZqHDA2YQFqMFnLaOHMBxHDU7b\nYiBPYxjHlm7yBXTnXIVqOnts3yRPRfHUCvNdiMvNzLQaDtP343jew2W4R8arwFpC\nU01NbHWoOiQ6GggTJEfGIxTHhjkd5Xd0hB97KccPF4YvOTGnXpNiHN+hGteF2CrZ\npZAyYIqshyeijR9ipbOpYxdrYOGKfA5nUSDjeGpG2Yqg6R6eJrrBw49JsJP6VqhD\nVM0wmv7fyfPZHD/g9CAx0w==\n-----END PUBLIC KEY-----\n"
  },
  {
    "path": "admin/dist/mac/sign_update.rb",
    "content": "#!/usr/bin/ruby\nif ARGV.length < 2\n  puts \"Usage: ruby sign_update.rb update_archive private_key\"\n  exit\nend\nopenssl = \"/usr/bin/openssl\"\nputs `#{openssl} dgst -sha1 -binary < \"#{ARGV[0]}\" | #{openssl} dgst -dss1 -sign \"#{ARGV[1]}\" | #{openssl} enc -base64`"
  },
  {
    "path": "admin/dist/updates/Changelog.txt",
    "content": "The changelog is publicly places into the update files, which live on cdn.last.fm. Add your changes there.\n\nNote that build-release.rb will output a stub Sparkle update XML block (called update.xml in the project root) to be added to various files here (beta, then release versions) which is correctly signed with our dsa_priv.pem key. You must incorporate this into the update XMLs."
  },
  {
    "path": "admin/dist/updates/Mac/updates.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>https://cdn.last.fm/client/Mac/updates.xml</link>\n\t<description>Last.fm Scrobbler Updates - Mac</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.39</title>\n\t\t<pubDate>Wed, 18 Sep 2019 16:26:00 +0100</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.39\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.39.tar.bz2\"\n\t\t\tlength=\"76296\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFQCmOcvAMz+PoMNOsNMP22ggfjFyzgIUVgXjj2WdaQmM/S7HFxsXR3iAHGQ=\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This update ensures that scrobbling continues to work with Mac OS Catalina. It is now compatible with the Music app, which was formerly known as iTunes.</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug Fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>The link to activate scrobbling in Spotify has been fixed. You can add scrobbling for Spotify through your Last.fm <a href=\"https://www.last.fm/settings/applications\">settings page</a>.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.37</title>\n\t\t<pubDate>Tue, 22 Mar 2016 15:31:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.37\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.37.tar.bz2\"\n\t\t\tlength=\"56792\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFQ7XARhNXoLR504/gd+D5gXazP0AhUAkjA63yXEafvxMm+PH07DYwlOm1I=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This is mainly a security update for OSX El Capitan to allow loading of all future updates over HTTPS.</li>\n\t\t\t\t\t<li>This update also removes some unused functions of the client.</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug Fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some users were experiencing crashes on sleep/wake. This should be fixed.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.36\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36.tar.bz2\"\n\t\t\tlength=\"51752\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFZ5FiReyWRw5dPD42JBuv/R6dJZAhUAqTyhf6TS6ITk+bKOFBxPRlpmKBg=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36-2.1.35.delta\"\n\t\t\t\tsparkle:version=\"2.1.36\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.35\"\n\t\t\t\tlength=\"14048\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFAWzRcmOvVQYogpm82Mp1fM1ITCcAhR1McMEgB5xCNv4LnOdHFrzFB6tjA==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 10:43:00 +0000</pubDate>\n\t\t<enclosure\n\t\tsparkle:version=\"2.1.35\"\n\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35.tar.bz2\"\n\t\tlength=\"38768\"\n\t\ttype=\"application/octet-stream\"\n\t\tsparkle:dsaSignature=\"MCwCFFG28YT06hPjBcVJMIfevbCA9VZ7AhQ4aA9lp8cIv3HcPA7Smtvzz/mAyA==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35-2.1.34.delta\"\n\t\t\t\tsparkle:version=\"2.1.35\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.34\"\n\t\t\t\tlength=\"904\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFCtPKeOs9zB2edu4OD9mQlt/za2UAhQ6U9LMoWL0I3znzVBSlILIDCoaew==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>Users can now hide both the dock icon and the menu bar icon (restart only required when hiding dock icon on 10.6)</li>\n\t\t\t\t<li>Binary delta updates will be supported from the release after this one</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Fixed an issue where it was possible to get two running versions of the applications after an update. <b>Please note</b> that as this fix was to the update mechanism it will only be corrected in the update after this one so please make sure you don't have two versions of the app running after this update.</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Don't crash if Airfoil is connected during the first run wizard</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t\t<p><a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html>Full changelog</a></p>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\tsparkle:version=\"2.1.33\"\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.33.tar.bz2\"\n\t\t\t\tlength=\"51496\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFDb/I9Bxyigl2lBJw+JiFwmvnzZnAhQf/Ua3boCkXB1uH2eLpJEC83Zhlg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Users that only authenticated with 2.1.32 will be asked to authenticate again. Sorry!</li>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes from 2.1.32</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n<!--\n \t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32 BROKEN! DOWNLOAD DISABLED!</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<description><![CDATA[\n\t\t\tThis block was commented out as it breaks later versions of Sparkle.\n\t\t]]></description>\n\t</item>\n -->\n \t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.30\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.30.tar.bz2\"\n\t\t\tlength=\"51488\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFB81slNAjFgUeLzRzduBcPn5Gf4pAhUApgKlc0e88mKviG7b7Sv8l96FooQ=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for an device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\t\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.29\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.29.tar.bz2\"\n\t\t\tlength=\"51496\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFHT3/y44rhssHuDtfmt5rL+3Ww6eAhRXpdFTCf731RywSz2rK0ItHCmuzA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enableing/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.28\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.28.tar.bz2\"\n\t\t\tlength=\"51480\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFDwayTlkMI06J0RSHrRulFniTT3VAhRq4XJxuw8oVXBXTZkBb6Lt8nR57g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash caused by VLC when monitors plugged in, etc</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.27\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.27.tar.bz2\"\n\t\t\tlength=\"51280\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFdVhVVxkTyH7dcmJD+OLXACK5kgAhQcLYsjGQSRxcONf6VGPUrxPRKUqg==\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.26\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.26.tar.bz2\"\n\t\t\tlength=\"50456\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFEB1oHQYNVi+HQXxSt6xGn/mzsr4AhR+vrS/dxoDvCqQyN51HypLawcucw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>Text should now look nicer on Retina screens</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling - fixed a problem where non-local tracks (iTunes Match) would not get their playcounts synced and lead to duplicates scrobbles</li>\n\t\t\t\t\t<li>Media keys are now ignored if you last listened to audio through another app</li>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.25</title>\n\t\t<pubDate>Thr, 25 Oct 2012 13:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.25\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.25.tar.bz2\"\n\t\t\tlength=\"49704\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFCX24RpRaDjf5+luL4aSX7Uqhz/gAhRulwjHFesGWsIJrSNoRCrvixbiUg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now called \"Last.fm Scrobbler\"</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync - Scrobble your device before updating so you don't lose scrobbles</li>\n\t\t\t\t\t<li>The app is now partially translated with translations from the old app. A fully translated version will be coming soon</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some CPU usage fixes</li>\n\t\t\t\t\t<li>Fingerprinting backend has changed, fixing a rare crash</li>\n\t\t\t\t\t<li>Other minor bugs</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Mon, 10 Sep 2012 10:26:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.21\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.21.tar.bz2\"\n\t\t\tlength=\"28528\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFQ3ZyY6bowbSgQHih7rwDP/zasoAhRJrKkzhmeV/hrOIP+qVmmxPn1svw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to hide app icon from the dock (also has to hide app's menu bar, and icon in tab switcher)</li>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detected you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.20</title>\n        <pubDate>Fri, 01 Jun 2012 14:20:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.20\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.20.tar.bz2\"\n                length=\"24088\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MCwCFDXdsIAA9RR+fm1HASw9Wj9faEENAhQcojkXrhPuK3a19Pc1vyOLfGRRiA==\"/>\n        <description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n        <title>Last.fm Scrobbler 2.1.19</title>\n        <pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.19\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.19.tar.bz2\"\n                length=\"28480\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MC0CFQCnoxk6NB25D6bS7pjvj5zV1qqvFwIULUJgTSO3kIKxdeJz7xV9kV7xT5U=\"/>\n        <description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Media keys on your keyboard now control the radio - play/pause and skip</li>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed radio playback issue - some users had trouble skipping between songs</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Updated Phonon library from 4.4 to 4.6</li>\n\t\t\t\t\t\t<li>Switched to VLC as the audio backend</li>\n\t\t\t\t\t\t<li>Note: for users that didn't have this problem, they should notice some general playback performace improvements</li>\n\t\t\t\t\t\t<li>Also note: we made these changes for Windows too - there wasn't this specific bug, but you may still notice a performance improvement</li>\n\t\t\t\t\t</ul>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t<pubDate>Thu, 26 Apr 2012 19:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18.tar.bz2\"\n\t\t\t\t length=\"23368\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFGjp/NirSPRth1LDL77QPCPmkQAyAhQfUM6JKHUD5X2EUJ6wWwdhhXG0fg==\"/>\n\t\t<sparkle:deltas>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.16.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.16\"\n\t\t\t\t length=\"1688\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MC0CFQCRB1VjXyXaUpOVBsbDx1Rd8Hc68AIUPxqzKj34I8SeOLRiJmzyCPWjWLA=\"/>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.17.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.17\"\n\t\t\t\t length=\"2064\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFHOvbrgU7ttfYmhVk40FguibWWWYAhQQ+ezGEWuOPCeV4gVTK5Q3KXZ1Fg==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t<pubDate>Tue, 10 Apr 2012 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17.tar.bz2\" \n\t\t\t length=\"22920\" \n\t\t\t type=\"application/octet-stream\" \n\t\t\t sparkle:dsaSignature=\"MC0CFFTxxxig47d43vfUk0cazGJneKVEAhUAjhtrQMpb3dCxr2QG+IAQa8UidiY=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17-2.1.16.delta\" \n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t sparkle:deltaFrom=\"2.1.16\" \n\t\t\t\t length=\"936\" \n\t\t\t\t type=\"application/octet-stream\" \n\t\t\t\t sparkle:dsaSignature=\"MCwCFD5bA6NPhtof5kQSbnywYqUK9wvOAhRGkOuC+rDdpl1z5OTJCMTYFbZFtw==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thu, 15 Mar 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.16\"\n\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.16.tar.bz2\"\n\t\t length=\"22960\"\n\t\t type=\"application/octet-stream\"\n\t\t sparkle:dsaSignature=\"MC0CFQCEQyJvAbR7S4wVhJaUZ92yqeB40AIUe1N1zKt3QnW6pkbMP8gpKw9HxRk=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.15\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15.zip\"\n\t\t           length=\"59032\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHWXu3Odz1EEYnpTRHLZUoc8KKO5AhRqmaZ50QhLxIpATrwkCk1clzQzyw==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15-2.1.14.delta\"\n\t\t\t\t\t\tsparkle:version=\"2.1.15\"\n\t\t\t\t\t\tsparkle:deltaFrom=\"2.1.14\"\n\t\t\t\t\t\tlength=\"3384\"\n\t\t\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\t\t\tsparkle:dsaSignature=\"MC0CFGEcpucDQFUoe7EQaFM1Z9VgLp2FAhUAgPgQIud6T+CP/XG8igI0MrkdW2c=\" />\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>Don't ask where Spotify is, if it isn't installed</li>\n\t\t\t\t\t<li>Extra dock icons no longer appear</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.14\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.14.zip\"\n\t\t           length=\"58976\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MC0CFQCm/tD1PCjr4Mi1/qvLOG1OoaKNxQIUI+WsnFViB0P9lDF/sMm8KroUSHw=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version!!!</h3>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.13\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.13.zip\"\n\t\t           length=\"59176\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHHXLm4vnHA/163VDxm8s4qQssgvAhRbwKVMPS63OImXmO5mMkapIeU8MA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Now opens lastfm:// radio urls from the web site</li>\n\t\t\t\t\t<li>Upgraded to Qt 4.8.0</li>\n\t\t\t\t\t<li>Now tells you to close iTunes when there is a new plugin to install</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t\t<li>Friend list trackpad scrolling is now smooth (Qt 4.8.0)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thu, 02 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.12\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.12.zip\"\n\t\t           length=\"53848\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFFmYvxQ1+8M06EI1AhtsJDETVrO/AhRTInZ6JAM93MPe6o/UaKIK9uyU3w==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 19:46:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.11\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.11.zip\"\n\t\t           length=\"54408\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFDdv1lLNaTRPJTaHIoZLvqI2klD2AhQ+uQJOYHyM9kFsshbkkW0ALtHkOQ==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly thought some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 16:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.10\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.10.zip\"\n\t\t           length=\"54496\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFEQAxtXPwDtGHruTYrx04PP8FROxAhQwVpzAFN8X297zXXvTyQqn5K6quw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 10:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.9\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.9.zip\"\n\t\t           length=\"52088\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFBtr5ldX6tmaqfn7RL//XLJPZqdWAhQu5HFQXpNtd4QoDatlNBfzOrNASA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 10:55:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.8\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.8.zip\" length=\"51896\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFBuMoqm2G0qlrCyFygeLf6e5e05ZAhQB/hQ067CDeqJsv1LyaDMtRIqU1g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features/Improvements</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Stops from iTunes are picked up - end of a playlist, quit iTunes, etc</li>\n\t\t\t\t\t<li>Resume iTunes track after playing and pausing radio is now picked up</li>\n\t\t\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.7\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.7.zip\" length=\"50344\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFFlKwnxI0WAcCBHYPRp9IvNywXvMAhREH2R5d5IUZK+bULZ3u8XFgwt+dA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.6\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.6.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MC0CFQCGwuA+Sd2RvbtWK3xrjCf3i+eJBgIULgTgtcvxYt3xX3etnF7ZvhXeUwA=\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>New friends list</li>\n\t\t\t\t\t<li>Now installs media player plugins on Windows</li>\n\t\t\t\t\t<li>Bootstrapping for all media players now works</li>\n\t\t\t\t\t<li>Many other bug fixes and improvements</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.5</title>\n\t\t<pubDate>Thu, 17 Nov 2011 16:57:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.5\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.5.zip\" length=\"50368\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFCi+YjPJ2yvXKXoh/S/Z/B/c8PO7AhRG53S7/K3fMeBChE58OyuPht3oxA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Lots of UI changes - welcome screen changed, metadata view improved, etc etc</li>\n\t\t\t\t\t<li>Supports updates with libsparkle!</li>\n\t\t\t\t\t<li>Uses the Growl framework to show notifications with album art</li>\n\t\t\t\t\t<li>Airfoil metadata support</li>\n\t\t\t\t\t<li>Scriptable with AppleScript (see the dictionary)</li>\n\t\t\t\t\t<li>Campaign tracking when linking to the website</li>\n\t\t\t\t\t<li>Radio quick start widget now shows artist and tag suggestions</li>\n\t\t\t\t\t<li>Big play buttons now resume the last radio</li>\n\t\t\t\t\t<li>Friends list now sorted by most recently listened</li>\n\t\t\t\t\t<li>Switching tabs now has a slide animation</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.4</title>\n\t\t<pubDate>Tue, 08 Nov 2011 15:30:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.4\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.4.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFB+JR/g7HGKNroRRj7PStc2aH0j4AhR7vlzYCGxVgcdO0pmi7vO2vss0Vg==\"/>\n\t\t<description><![CDATA[\n\t\t        <h3>Embedded release notes!</h3>\n\t\t        ...\n\t\t    ]]></description>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/Win/updates.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>http://cdn.last.fm/client/Win/updates.xml</link>\n\t<description>Last.fm Scrobbler Updates - Windows</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.36\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.36.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 11:29:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.35\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.35.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>New updating framework - currently just looks better and is smaller, but it's the first step in better Windows updating</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t\t<li>Tracks are now identified by persistent id rather then filename - fixes a few problems and should be more robust</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Windows Media Player scrobbles now include 'album artist' (just like other media players already do)</li>\n\t\t\t\t<li>Only show 'Open iTunes' if it has been installed</li>\n\t\t\t\t<li>Settings dialog resizing improved</li>\n\t\t\t\t<li>Correctly display track metatdata that has characters such as &lt; in it</li>\n\t\t\t\t<li>The prompt to restart now actually restarts the app</li>\n\t\t\t\t<li>When installing a plugin from the file menu the full installer is shown - user can select install location, if not default, etc</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.33\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t\t<li>iTunes plugin update for XP scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"http://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.32\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Now runs on Windows XP</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30 (First full release!)</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.30\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.30.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for a device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.29\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.29.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.28\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.28.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash when fingerprinting some audio files</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.27\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.27.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.26\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.26.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>iTunes plugin and app now both use the same playcounts db (they didn't before!?)</li>\n\t\t\t\t\t\t<li>Tracks that end within 20 seconds of starting (user skipped to near the end) now get their playcounts synced (was leading to duplicate scrobbles)</li>\n\t\t\t\t\t\t<li>iTunes no longer kept open by us not releasing a handle to it</li>\n\t\t\t\t\t\t<li>Fixed a problem where the iTunes plugin would stop communicating with the app so scrobbling stopped (this also caused the plays to be picked up as iTunes device scrobbles)</li>\n\t\t\t\t\t\t<li>Fixed a problem where the last track of a playlist would not get it's playcount synced leading to it being picked up as an iTunes device scrobble</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.24</title>\n\t\t<pubDate>Wed, 26 Sep 2012 11:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.24\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.24.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.24</h3>\n\t\t\t\t<h3>Windows only bug fix release</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed an issue where iTunes devices (iPod/iPhone) wouldn't scrobble if the app was not installed to the default location</li>\n\t\t\t\t\t<li>Fixed a crash with iTunes device scrobbling introduced with the 'album artist' scrobble changes</li>\n\t\t\t\t\t<li>Fixed a crash caused by fingerprinting .flac files</li>\n\t\t\t\t\t<li>Fixed an issue where the volume would reset to maximum at the start of every radio track</li>\n\t\t\t\t\t<li>Fixed a CPU usage issue</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Tue, 04 Sep 2012 14:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.21\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.21.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.21</h3>\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detcted you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.20</title>\n\t\t\t<pubDate>Fri, 01 Jun 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.20\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.20.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t\t<li>Fixed iPod scrobbling (was broken in 2.1.19)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.19</title>\n\t\t<pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.19\" \n\t\t\t url=\"\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t\t<pubDate>Thr, 26 Apr 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.18\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.18.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t\t<pubDate>Mon, 14 Mar 2012 18:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.17.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Features</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thr, 15 Mar 2012 11:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.16\"\n\t\t\turl=\"http://cdn.last.fm/client/Win/Last.fm-2.1.16.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.15\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.15.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>iPod scrobbling should now work</li>\n\t\t\t\t\t<li>'Close' and 'Apply' buttons now work correctly</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 13:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.14\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.14.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version</h3>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 18:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.13\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.13.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thr, 02 Feb 2012 18:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.12\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.12.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling should now work (as well as it does on mac)! The installer was incorrect</li>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 20:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.11\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.11.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly though some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 17:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.10\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.10.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 11:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.9\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.9.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>New iTunes plugin was not working due to a change in Qt</li>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 11:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.8\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.8.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t<h3>Features/Improvements</h3>\n\t\t<ul>\n\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t</ul>\n\t\t<h3>Bug fixes</h3>\n\t\t<ul>\n\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t</ul>\n\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.0.7\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.7.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t\t<description><![CDATA[\n\t\t\t<ul>\n\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.6\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.6.exe\"\n\t\t\t/>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.1</title>\n\t\t<pubDate>Wed, 02 Nov 2011 11:11:11 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.1\"\n\t\t\turl=\"http://cdn.last.fm/20111102WIN.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/updates.html",
    "content": "<html>\n  <head>\n    <title>Last.fm Scrobbler Changelog</title>\n    <style type=\"text/css\">\n\n      html {\n        background: #f2f2f2;\n      }\n\n      body {\n        margin: 0;\n        padding: 0;\n        font-family: \"Lucida Grande\", \"Helvetica Neue\", Arial, sans-serif;\n        line-height: 18px;\n        color: #333;\n      }\n\n      h1, h2, h3 {\n        font-size: 18px;\n        color: #333;\n        line-height: 24px;\n      }\n\n      .branding {\n        background: -webkit-linear-gradient(#e31d2a, #bf0623);\n        background:    -moz-linear-gradient(#e31d2a, #bf0623);\n        background:       -o-liear-gradient(#e31d2a, #bf0623);\n        background:         linear-gradient(#e31d2a, #bf0623);\n        border-bottom: 1px solid #9f081e;\n        height: 60px;\n        box-shadow: rgba(0,0,0,0.3) 0 1px 1px;\n        width: 100%;\n        text-align: center;\n        position: relative;\n      }\n\n      .logo {\n        display: inline-block;\n        width: 100px;\n        height: 35px;\n        margin-top: 18px;\n        text-indent: -9999px;\n        background: url('../images/lastfm.png') no-repeat;    \n      }\n\n      .options {\n        margin: 20px 0px 0px;\n      }\n\n      .platforms,\n      .releasestates {\n        margin-left: 30px;\n      }\n\n      article {\n        border-top: 1px solid #ccc;\n        text-shadow: #fff 0 1px 0;\n        min-height: 100%;\n        max-width: 940px;\n        margin: 0 auto;\n        position: relative;\n      }\n\n      .update {\n        padding: 10px;\n      }\n\n      .title {\n        padding: 0px 20px 0px;\n      }\n\n      a {\n        color: inherit; \n      }\n\n      a:hover {\n        text-decoration: none;\n      }\n\n      .description {\n        border: solid 1px #ddd;\n        padding: 0px 20px 0px;\n      }\n\n      .more {\n        visibility: hidden;\n      }\n\n    </style>\n    <script type=\"text/javascript\">\n\n      var BrowserDetect = {\n        init: function () {\n          this.OS = this.searchString(this.dataOS) || \"an unknown OS\";\n        },\n        searchString: function (data) {\n          for (var i=0;i<data.length;i++) {\n            var dataString = data[i].string;\n            var dataProp = data[i].prop;\n            this.versionSearchString = data[i].versionSearch || data[i].identity;\n            if (dataString) {\n              if (dataString.indexOf(data[i].subString) != -1)\n                return data[i].identity;\n            }\n            else if (dataProp)\n              return data[i].identity;\n          }\n        },\n        dataOS : [\n          {\n            string: navigator.platform,\n            subString: \"Win\",\n            identity: \"Windows\"\n          },\n          {\n            string: navigator.platform,\n            subString: \"Mac\",\n            identity: \"Mac\"\n          },\n          {\n               string: navigator.userAgent,\n               subString: \"iPhone\",\n               identity: \"iPhone/iPod\"\n            },\n          {\n            string: navigator.platform,\n            subString: \"Linux\",\n            identity: \"Linux\"\n          }\n        ]\n\n      };\n      BrowserDetect.init();\n\n      function getParameterByName(name)\n      {\n        name = name.replace(/[\\[]/, \"\\\\\\[\").replace(/[\\]]/, \"\\\\\\]\");\n        var regexS = \"[\\\\?&]\" + name + \"=([^&#]*)\";\n        var regex = new RegExp(regexS);\n        var results = regex.exec(window.location.search);\n        if(results == null || results==\"\")\n          return null;\n        else\n          return decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n      }\n\n      function onload_cb()\n      {\n        // format the update descriptions properly\n        var divElements = document.getElementsByTagName('div');\n        for (var i = 0; i < divElements.length; i++)\n        {\n          var el = divElements[i];\n          if (el.className == 'description') {\n            el.innerHTML = el.firstChild ? el.firstChild.textContent : \"\";\n          }\n        }\n\n        var platform = getParameterByName(\"platform\");\n        var releasestate = getParameterByName(\"releasestate\");\n\n        // pass on the query parameters to the relevant links\n        var aElements = document.getElementsByTagName('a');\n        for (var i = 0; i < aElements.length; i++)\n        {\n          var el = aElements[i];\n          if (el.className == \"releasestate\" && platform) {\n            el.setAttribute( \"href\", el.getAttribute(\"href\") + \"&platform=\" + platform );\n          } else if (el.className == \"platform\" && releasestate) {\n            el.setAttribute( \"href\", el.getAttribute(\"href\") + \"&releasestate=\" + releasestate );\n          }\n        }\n      }\n\n      function loadXMLDoc(dname)\n      {\n        if (window.XMLHttpRequest) \n        {\n          xhttp=new XMLHttpRequest();\n        }\n        else\n        {\n          xhttp=new ActiveXObject(\"Microsoft.XMLHTTP\");\n        }\n        xhttp.open(\"GET\",dname,false);\n        xhttp.send(\"\");\n        return xhttp.responseXML;\n      }\n\n      function displayResult()\n      {\n        OS = getParameterByName(\"platform\") || BrowserDetect.OS;\n\n        if ( OS == \"Mac\" ) {\n          xml=loadXMLDoc( getParameterByName(\"releasestate\") == \"beta\" ? \"updates.mac.beta.xml\" : \"updates.mac.xml\");\n          document.getElementById(\"mac\").style.fontWeight=\"bold\";\n        } else if ( OS == \"Linux\" ) {\n          xml=loadXMLDoc(\"updates.linux.xml\");\n          document.getElementById(\"linux\").style.fontWeight=\"bold\";\n        } else {\n          xml=loadXMLDoc( getParameterByName(\"releasestate\") == \"beta\" ? \"updates.win.beta.xml\" : \"updates.win.xml\");\n          document.getElementById(\"win\").style.fontWeight=\"bold\";\n        }\n\n        if ( getParameterByName(\"releasestate\") == \"beta\" ) {\n          document.getElementById(\"beta\").style.fontWeight=\"bold\";\n        } else {\n          document.getElementById(\"production\").style.fontWeight=\"bold\";\n        }\n\n        xsl=loadXMLDoc(\"updates.xsl\");\n        // code for IE\n        if (window.ActiveXObject)\n        {\n          ex=xml.transformNode(xsl);\n          document.getElementById(\"wrapper\").innerHTML=ex;\n        }\n        // code for Mozilla, Firefox, Opera, etc.\n        else if (document.implementation && document.implementation.createDocument)\n        {\n          xsltProcessor=new XSLTProcessor();\n          xsltProcessor.importStylesheet(xsl);\n          resultDocument = xsltProcessor.transformToFragment(xml,document);\n          document.getElementById(\"wrapper\").appendChild(resultDocument);\n        }\n      }\n\n    </script>\n  </head>\n  <body onload=\"displayResult(); onload_cb();\">\n    <header>\n      <div class=\"branding\">\n        <a href=\"http://www.last.fm\">\n          <div class=\"logo\">Last.fm</div>\n        </a>\n      </div>\n    </header>\n    <article>\n      <div class=\"options\">\n        <span class=\"platforms\">Platform: <a class=\"platform\" id=\"win\" href=\"updates.html?platform=Win\">Windows</a> <a class=\"platform\" id=\"mac\" href=\"updates.html?platform=Mac\">Mac</a> <a class=\"platform\" id=\"linux\" href=\"updates.html?platform=Linux\">Linux</a></span>\n        <span class=\"releasestates\">Release state: <a class=\"releasestate\" id=\"production\" href=\"updates.html?releasestate=production\">Production</a> <a class=\"releasestate\" id=\"beta\" href=\"updates.html?releasestate=beta\">Beta</a></span>\n      </div>\n      <div id=\"wrapper\"></div>\n    </article>\n  </body>\n</html>"
  },
  {
    "path": "admin/dist/updates/updates.linux.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>http://cdn.last.fm/client/updates/updates.lin.xml</link>\n\t<description>Last.fm Scrobbler Updates - Linux</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for a device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.24</title>\n\t\t<pubDate>Wed, 26 Sep 2012 11:50:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Windows only bug fix release</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed an issue where iTunes devices (iPod/iPhone) wouldn't scrobble if the app was not installed to the default location</li>\n\t\t\t\t\t<li>Fixed a crash with iTunes device scrobbling introduced with the 'album artist' scrobble changes</li>\n\t\t\t\t\t<li>Fixed a crash caused by fingerprinting .flac files</li>\n\t\t\t\t\t<li>Fixed an issue where the volume would reset to maximum at the start of every radio track</li>\n\t\t\t\t\t<li>Fixed a CPU usage issue</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Tue, 04 Sep 2012 14:20:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detcted you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.20</title>\n\t\t<pubDate>Fri, 01 Jun 2012 16:30:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n    \t\t<h3>Bug fixes</h3>\n    \t\t<ul>\n\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t</ul>\n\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.19</title>\n\t\t<pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>[Mac] Media keys on your keyboard now control the radio - play/pause and skip</li>\n\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>[Mac] Fixed radio playback issue - some users had trouble skipping between songs</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updated Phonon library from 4.4 to 4.6</li>\n\t\t\t\t\t<li>Switched to VLC as the audio backend</li>\n\t\t\t\t\t<li>Note: for users that didn't have this problem, they should notice some general playback performace improvements</li>\n\t\t\t\t\t<li>Also note: we made these changes for Windows too - there wasn't this specific bug, but you may still notice a performance improvement</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t\t<pubDate>Thr, 26 Apr 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t\t<pubDate>Mon, 14 Mar 2012 18:30:00 +0000</pubDate>\n\t\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Features</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thr, 15 Mar 2012 11:10:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>[Win] iPod scrobbling should now work</li>\n\t\t\t\t\t<li>[Win] 'Close' and 'Apply' buttons now work correctly</li>\n\t\t\t\t\t<li>[Mac] Don't ask where Spotify is, if it isn't installed</li>\n\t\t\t\t\t<li>[Mac] Extra dock icons no longer appear</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 13:30:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version</h3>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 18:50:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>[Mac] Now opens lastfm:// radio urls from the web site</li>\n\t\t\t\t\t<li>[Mac] Upgraded to Qt 4.8.0</li>\n\t\t\t\t\t<li>[Mac] Now tells you to close iTunes when there is a new plugin to install</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t\t<li>[Mac] Friend list trackpad scrolling is now smooth (Qt 4.8.0)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thr, 02 Feb 2012 18:20:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>[Win] iPod scrobbling should now work (as well as it does on mac)! The installer was incorrect</li>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 20:10:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly though some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>[Win] Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>[Mac] Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>[Mac] Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 17:30:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>[Win] Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>[Mac] Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>[Mac] Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 11:20:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>[Win] New iTunes plugin was not working due to a change in Qt</li>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 11:45:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t<h3>Features/Improvements</h3>\n\t\t<ul>\n\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t</ul>\n\t\t<h3>Bug fixes</h3>\n\t\t<ul>\n\t\t\t<li>[Mac] Stops from iTunes are picked up - end of a playlist, quit iTunes, etc</li>\n\t\t\t<li>[Mac] Resume iTunes track after playing and pausing radio is now picked up</li>\n\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t</ul>\n\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:45:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t\t<description><![CDATA[\n\t\t\t<ul>\n\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.1</title>\n\t\t<pubDate>Wed, 02 Nov 2011 11:11:11 +0000</pubDate>\n\t\t<enclosure url=\"http://apt.last.fm\" />\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/updates.mac.beta.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>https://cdn.last.fm/client/updates/updates.mac.beta.xml</link>\n\t<description>Last.fm Scrobbler Updates - Mac Beta</description>\n\t<language>en</language>\n\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.39</title>\n\t\t<pubDate>Wed, 18 Sep 2019 16:26:00 +0100</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.39\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.39.tar.bz2\"\n\t\t\tlength=\"76296\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFQCmOcvAMz+PoMNOsNMP22ggfjFyzgIUVgXjj2WdaQmM/S7HFxsXR3iAHGQ=\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This update is for compatibility with MacOS Catalina, where iTunes has been renamed to Music.</li>\n\t\t\t\t\t<li>In this final update we have also fixed the iTunes / Apple Music now-playing text, and Apple Music sends a different player ID to Last.fm.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.38-beta2</title>\n\t\t<pubDate>Tue, 17 Sep 2019 10:52:00 +0100</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.38-beta2\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.38-beta2.tar.bz2\"\n\t\t\tlength=\"78096\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFAjwkQ92UC2BAOa0tT7Tv70vCKYzAhQZeVrhveeC8WdAGEhhR4XNr9b9Yg==\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This update is for compatibility with MacOS Catalina, where iTunes has been renamed to Music.</li>\n\t\t\t\t\t<li>In this beta update we have also fixed the iTunes / Apple Music launch buttons and the links Spotify Scrobbling.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.38-beta1</title>\n\t\t<pubDate>Mon, 16 Sep 2019 12:29:00 +0100</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.38-beta1\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.38-beta1.tar.bz2\"\n\t\t\tlength=\"76296\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFfQzsnAc5zU+y44twZk2+g55l4FAhUAkbWYW51YYTrKfFAWtA2BqZdthqM=\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This update is for compatibility with MacOS Catalina, where iTunes has been renamed to Music.</li>\n\t\t\t\t\t<li>Please enjoy this beta update and address your kindest words to Stephen and Maciek for figuring out the issues involved in making this update possible.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.37</title>\n\t\t<pubDate>Tue, 22 Mar 2016 15:31:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.37\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.37.tar.bz2\"\n\t\t\tlength=\"56792\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFQ7XARhNXoLR504/gd+D5gXazP0AhUAkjA63yXEafvxMm+PH07DYwlOm1I=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This is mainly a security update for OSX El Capitan to allow loading of all future updates over HTTPS.</li>\n\t\t\t\t\t<li>This update also removes some unused functions of the client.</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug Fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some users were experiencing crashes on sleep/wake. This should be fixed.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.36\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36.tar.bz2\"\n\t\t\tlength=\"51752\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFZ5FiReyWRw5dPD42JBuv/R6dJZAhUAqTyhf6TS6ITk+bKOFBxPRlpmKBg=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36-2.1.35.delta\"\n\t\t\t\tsparkle:version=\"2.1.36\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.35\"\n\t\t\t\tlength=\"14048\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFAWzRcmOvVQYogpm82Mp1fM1ITCcAhR1McMEgB5xCNv4LnOdHFrzFB6tjA==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 10:43:00 +0000</pubDate>\n\t\t<enclosure\n\t\tsparkle:version=\"2.1.35\"\n\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35.tar.bz2\"\n\t\tlength=\"38768\"\n\t\ttype=\"application/octet-stream\"\n\t\tsparkle:dsaSignature=\"MCwCFFG28YT06hPjBcVJMIfevbCA9VZ7AhQ4aA9lp8cIv3HcPA7Smtvzz/mAyA==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35-2.1.34.delta\"\n\t\t\t\tsparkle:version=\"2.1.35\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.34\"\n\t\t\t\tlength=\"904\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFCtPKeOs9zB2edu4OD9mQlt/za2UAhQ6U9LMoWL0I3znzVBSlILIDCoaew==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>Users can now hide both the dock icon and the menu bar icon (restart only required when hiding dock icon on 10.6)</li>\n\t\t\t\t<li>Binary delta updates will be supported from the release after this one</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Fixed an issue where it was possible to get two running versions of the applications after an update. <b>Please note</b> that as this fix was to the update mechanism it will only be corrected in the update after this one so please make sure you don't have two versions of the app running after this update.</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Don't crash if Airfoil is connected during the first run wizard</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t\t<p><a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html>Full changelog</a></p>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\tsparkle:version=\"2.1.33\"\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.33.tar.bz2\"\n\t\t\t\tlength=\"51496\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFDb/I9Bxyigl2lBJw+JiFwmvnzZnAhQf/Ua3boCkXB1uH2eLpJEC83Zhlg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Users that only authenticated with 2.1.32 will be asked to authenticate again. Sorry!</li>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes from 2.1.32</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n<!-- \t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32 BROKEN! DOWNLOAD DISABLED!</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<description><![CDATA[\n\t\t\tThis block was commented out as it breaks later versions of Sparkle.\n\t\t]]></description>\n\t</item>\n -->\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.30\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.30.tar.bz2\"\n\t\t\tlength=\"51488\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFB81slNAjFgUeLzRzduBcPn5Gf4pAhUApgKlc0e88mKviG7b7Sv8l96FooQ=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for an device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\t\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.29\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.29.tar.bz2\"\n\t\t\tlength=\"51496\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFHT3/y44rhssHuDtfmt5rL+3Ww6eAhRXpdFTCf731RywSz2rK0ItHCmuzA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enableing/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.28\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.28.tar.bz2\"\n\t\t\tlength=\"51480\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFDwayTlkMI06J0RSHrRulFniTT3VAhRq4XJxuw8oVXBXTZkBb6Lt8nR57g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash caused by VLC when monitors plugged in, etc</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.27\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.27.tar.bz2\"\n\t\t\tlength=\"51280\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFdVhVVxkTyH7dcmJD+OLXACK5kgAhQcLYsjGQSRxcONf6VGPUrxPRKUqg==\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.26\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.26.tar.bz2\"\n\t\t\tlength=\"50456\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFEB1oHQYNVi+HQXxSt6xGn/mzsr4AhR+vrS/dxoDvCqQyN51HypLawcucw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>Text should now look nicer on Retina screens</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling - fixed a problem where non-local tracks (iTunes Match) would not get their playcounts synced and lead to duplicates scrobbles</li>\n\t\t\t\t\t<li>Media keys are now ignored if you last listened to audio through another app</li>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.25</title>\n\t\t<pubDate>Thr, 25 Oct 2012 13:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.25\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.25.tar.bz2\"\n\t\t\tlength=\"49704\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFCX24RpRaDjf5+luL4aSX7Uqhz/gAhRulwjHFesGWsIJrSNoRCrvixbiUg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now called \"Last.fm Scrobbler\"</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync - Scrobble your device before updating so you don't lose scrobbles</li>\n\t\t\t\t\t<li>The app is now partially translated with translations from the old app. A fully translated version will be coming soon</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some CPU usage fixes</li>\n\t\t\t\t\t<li>Fingerprinting backend has changed, fixing a rare crash</li>\n\t\t\t\t\t<li>Other minor bugs</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Mon, 10 Sep 2012 10:26:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.21\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.21.tar.bz2\"\n\t\t\tlength=\"28528\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFQ3ZyY6bowbSgQHih7rwDP/zasoAhRJrKkzhmeV/hrOIP+qVmmxPn1svw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to hide app icon from the dock (also has to hide app's menu bar, and icon in tab switcher)</li>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detected you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.20</title>\n        <pubDate>Fri, 01 Jun 2012 14:20:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.20\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.20.tar.bz2\"\n                length=\"24088\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MCwCFDXdsIAA9RR+fm1HASw9Wj9faEENAhQcojkXrhPuK3a19Pc1vyOLfGRRiA==\"/>\n        <description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n        <title>Last.fm Scrobbler 2.1.19</title>\n        <pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.19\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.19.tar.bz2\"\n                length=\"28480\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MC0CFQCnoxk6NB25D6bS7pjvj5zV1qqvFwIULUJgTSO3kIKxdeJz7xV9kV7xT5U=\"/>\n        <description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Media keys on your keyboard now control the radio - play/pause and skip</li>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed radio playback issue - some users had trouble skipping between songs</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Updated Phonon library from 4.4 to 4.6</li>\n\t\t\t\t\t\t<li>Switched to VLC as the audio backend</li>\n\t\t\t\t\t\t<li>Note: for users that didn't have this problem, they should notice some general playback performace improvements</li>\n\t\t\t\t\t\t<li>Also note: we made these changes for Windows too - there wasn't this specific bug, but you may still notice a performance improvement</li>\n\t\t\t\t\t</ul>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t<pubDate>Thu, 26 Apr 2012 19:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18.tar.bz2\"\n\t\t\t\t length=\"23368\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFGjp/NirSPRth1LDL77QPCPmkQAyAhQfUM6JKHUD5X2EUJ6wWwdhhXG0fg==\"/>\n\t\t<sparkle:deltas>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.16.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.16\"\n\t\t\t\t length=\"1688\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MC0CFQCRB1VjXyXaUpOVBsbDx1Rd8Hc68AIUPxqzKj34I8SeOLRiJmzyCPWjWLA=\"/>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.17.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.17\"\n\t\t\t\t length=\"2064\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFHOvbrgU7ttfYmhVk40FguibWWWYAhQQ+ezGEWuOPCeV4gVTK5Q3KXZ1Fg==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t<pubDate>Tue, 10 Apr 2012 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17.tar.bz2\" \n\t\t\t length=\"22920\" \n\t\t\t type=\"application/octet-stream\" \n\t\t\t sparkle:dsaSignature=\"MC0CFFTxxxig47d43vfUk0cazGJneKVEAhUAjhtrQMpb3dCxr2QG+IAQa8UidiY=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17-2.1.16.delta\" \n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t sparkle:deltaFrom=\"2.1.16\" \n\t\t\t\t length=\"936\" \n\t\t\t\t type=\"application/octet-stream\" \n\t\t\t\t sparkle:dsaSignature=\"MCwCFD5bA6NPhtof5kQSbnywYqUK9wvOAhRGkOuC+rDdpl1z5OTJCMTYFbZFtw==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thu, 15 Mar 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.16\"\n\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.16.tar.bz2\"\n\t\t length=\"22960\"\n\t\t type=\"application/octet-stream\"\n\t\t sparkle:dsaSignature=\"MC0CFQCEQyJvAbR7S4wVhJaUZ92yqeB40AIUe1N1zKt3QnW6pkbMP8gpKw9HxRk=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.15\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15.zip\"\n\t\t           length=\"59032\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHWXu3Odz1EEYnpTRHLZUoc8KKO5AhRqmaZ50QhLxIpATrwkCk1clzQzyw==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15-2.1.14.delta\"\n\t\t\t\t\t\tsparkle:version=\"2.1.15\"\n\t\t\t\t\t\tsparkle:deltaFrom=\"2.1.14\"\n\t\t\t\t\t\tlength=\"3384\"\n\t\t\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\t\t\tsparkle:dsaSignature=\"MC0CFGEcpucDQFUoe7EQaFM1Z9VgLp2FAhUAgPgQIud6T+CP/XG8igI0MrkdW2c=\" />\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>Don't ask where Spotify is, if it isn't installed</li>\n\t\t\t\t\t<li>Extra dock icons no longer appear</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.14\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.14.zip\"\n\t\t           length=\"58976\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MC0CFQCm/tD1PCjr4Mi1/qvLOG1OoaKNxQIUI+WsnFViB0P9lDF/sMm8KroUSHw=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version!!!</h3>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.13\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.13.zip\"\n\t\t           length=\"59176\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHHXLm4vnHA/163VDxm8s4qQssgvAhRbwKVMPS63OImXmO5mMkapIeU8MA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Now opens lastfm:// radio urls from the web site</li>\n\t\t\t\t\t<li>Upgraded to Qt 4.8.0</li>\n\t\t\t\t\t<li>Now tells you to close iTunes when there is a new plugin to install</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t\t<li>Friend list trackpad scrolling is now smooth (Qt 4.8.0)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thu, 02 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.12\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.12.zip\"\n\t\t           length=\"53848\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFFmYvxQ1+8M06EI1AhtsJDETVrO/AhRTInZ6JAM93MPe6o/UaKIK9uyU3w==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 19:46:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.11\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.11.zip\"\n\t\t           length=\"54408\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFDdv1lLNaTRPJTaHIoZLvqI2klD2AhQ+uQJOYHyM9kFsshbkkW0ALtHkOQ==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly thought some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 16:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.10\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.10.zip\"\n\t\t           length=\"54496\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFEQAxtXPwDtGHruTYrx04PP8FROxAhQwVpzAFN8X297zXXvTyQqn5K6quw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 10:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.9\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.9.zip\"\n\t\t           length=\"52088\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFBtr5ldX6tmaqfn7RL//XLJPZqdWAhQu5HFQXpNtd4QoDatlNBfzOrNASA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 10:55:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.8\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.8.zip\" length=\"51896\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFBuMoqm2G0qlrCyFygeLf6e5e05ZAhQB/hQ067CDeqJsv1LyaDMtRIqU1g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features/Improvements</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Stops from iTunes are picked up - end of a playlist, quit iTunes, etc</li>\n\t\t\t\t\t<li>Resume iTunes track after playing and pausing radio is now picked up</li>\n\t\t\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.7\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.7.zip\" length=\"50344\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFFlKwnxI0WAcCBHYPRp9IvNywXvMAhREH2R5d5IUZK+bULZ3u8XFgwt+dA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.6\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.6.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MC0CFQCGwuA+Sd2RvbtWK3xrjCf3i+eJBgIULgTgtcvxYt3xX3etnF7ZvhXeUwA=\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>New friends list</li>\n\t\t\t\t\t<li>Now installs media player plugins on Windows</li>\n\t\t\t\t\t<li>Bootstrapping for all media players now works</li>\n\t\t\t\t\t<li>Many other bug fixes and improvements</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.5</title>\n\t\t<pubDate>Thu, 17 Nov 2011 16:57:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.5\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.5.zip\" length=\"50368\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFCi+YjPJ2yvXKXoh/S/Z/B/c8PO7AhRG53S7/K3fMeBChE58OyuPht3oxA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Lots of UI changes - welcome screen changed, metadata view improved, etc etc</li>\n\t\t\t\t\t<li>Supports updates with libsparkle!</li>\n\t\t\t\t\t<li>Uses the Growl framework to show notifications with album art</li>\n\t\t\t\t\t<li>Airfoil metadata support</li>\n\t\t\t\t\t<li>Scriptable with AppleScript (see the dictionary)</li>\n\t\t\t\t\t<li>Campaign tracking when linking to the website</li>\n\t\t\t\t\t<li>Radio quick start widget now shows artist and tag suggestions</li>\n\t\t\t\t\t<li>Big play buttons now resume the last radio</li>\n\t\t\t\t\t<li>Friends list now sorted by most recently listened</li>\n\t\t\t\t\t<li>Switching tabs now has a slide animation</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.4</title>\n\t\t<pubDate>Tue, 08 Nov 2011 15:30:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.4\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.4.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFB+JR/g7HGKNroRRj7PStc2aH0j4AhR7vlzYCGxVgcdO0pmi7vO2vss0Vg==\"/>\n\t\t<description><![CDATA[\n\t\t        <h3>Embedded release notes!</h3>\n\t\t        ...\n\t\t    ]]></description>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/updates.mac.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>https://cdn.last.fm/client/Mac/updates.xml</link>\n\t<description>Last.fm Scrobbler Updates - Mac</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.39</title>\n\t\t<pubDate>Wed, 18 Sep 2019 16:26:00 +0100</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.39\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.39.tar.bz2\"\n\t\t\tlength=\"76296\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFQCmOcvAMz+PoMNOsNMP22ggfjFyzgIUVgXjj2WdaQmM/S7HFxsXR3iAHGQ=\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This update ensures that scrobbling continues to work with Mac OS Catalina. It is now compatible with the Music app, which was formerly known as iTunes.</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug Fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>The link to activate scrobbling in Spotify has been fixed. You can add scrobbling for Spotify through your Last.fm <a href=\"https://www.last.fm/settings/applications\">settings page</a>.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.37</title>\n\t\t<pubDate>Tue, 22 Mar 2016 15:31:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.37\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.37.tar.bz2\"\n\t\t\tlength=\"56792\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFQ7XARhNXoLR504/gd+D5gXazP0AhUAkjA63yXEafvxMm+PH07DYwlOm1I=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>This is mainly a security update for OSX El Capitan to allow loading of all future updates over HTTPS.</li>\n\t\t\t\t\t<li>This update also removes some unused functions of the client.</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug Fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some users were experiencing crashes on sleep/wake. This should be fixed.</li>\n\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.36\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36.tar.bz2\"\n\t\t\tlength=\"51752\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFFZ5FiReyWRw5dPD42JBuv/R6dJZAhUAqTyhf6TS6ITk+bKOFBxPRlpmKBg=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.36-2.1.35.delta\"\n\t\t\t\tsparkle:version=\"2.1.36\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.35\"\n\t\t\t\tlength=\"14048\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFAWzRcmOvVQYogpm82Mp1fM1ITCcAhR1McMEgB5xCNv4LnOdHFrzFB6tjA==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 10:43:00 +0000</pubDate>\n\t\t<enclosure\n\t\tsparkle:version=\"2.1.35\"\n\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35.tar.bz2\"\n\t\tlength=\"38768\"\n\t\ttype=\"application/octet-stream\"\n\t\tsparkle:dsaSignature=\"MCwCFFG28YT06hPjBcVJMIfevbCA9VZ7AhQ4aA9lp8cIv3HcPA7Smtvzz/mAyA==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.35-2.1.34.delta\"\n\t\t\t\tsparkle:version=\"2.1.35\"\n\t\t\t\tsparkle:deltaFrom=\"2.1.34\"\n\t\t\t\tlength=\"904\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFCtPKeOs9zB2edu4OD9mQlt/za2UAhQ6U9LMoWL0I3znzVBSlILIDCoaew==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>Users can now hide both the dock icon and the menu bar icon (restart only required when hiding dock icon on 10.6)</li>\n\t\t\t\t<li>Binary delta updates will be supported from the release after this one</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Fixed an issue where it was possible to get two running versions of the applications after an update. <b>Please note</b> that as this fix was to the update mechanism it will only be corrected in the update after this one so please make sure you don't have two versions of the app running after this update.</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Don't crash if Airfoil is connected during the first run wizard</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t\t<p><a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html>Full changelog</a></p>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\tsparkle:version=\"2.1.33\"\n\t\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.33.tar.bz2\"\n\t\t\t\tlength=\"51496\"\n\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\tsparkle:dsaSignature=\"MCwCFDb/I9Bxyigl2lBJw+JiFwmvnzZnAhQf/Ua3boCkXB1uH2eLpJEC83Zhlg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Users that only authenticated with 2.1.32 will be asked to authenticate again. Sorry!</li>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes from 2.1.32</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"https://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n<!--\n \t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32 BROKEN! DOWNLOAD DISABLED!</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<description><![CDATA[\n\t\t\tThis block was commented out as it breaks later versions of Sparkle.\n\t\t]]></description>\n\t</item>\n -->\n \t<item>\n \t\t<title>Last.fm Scrobbler 2.1.30</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.30\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.30.tar.bz2\"\n\t\t\tlength=\"51488\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MC0CFB81slNAjFgUeLzRzduBcPn5Gf4pAhUApgKlc0e88mKviG7b7Sv8l96FooQ=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for an device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\t\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.29\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.29.tar.bz2\"\n\t\t\tlength=\"51496\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFHT3/y44rhssHuDtfmt5rL+3Ww6eAhRXpdFTCf731RywSz2rK0ItHCmuzA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enableing/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.28\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.28.tar.bz2\"\n\t\t\tlength=\"51480\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFDwayTlkMI06J0RSHrRulFniTT3VAhRq4XJxuw8oVXBXTZkBb6Lt8nR57g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash caused by VLC when monitors plugged in, etc</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.27\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.27.tar.bz2\"\n\t\t\tlength=\"51280\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFdVhVVxkTyH7dcmJD+OLXACK5kgAhQcLYsjGQSRxcONf6VGPUrxPRKUqg==\"/>\n\t\t<sparkle:deltas>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.26\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.26.tar.bz2\"\n\t\t\tlength=\"50456\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFEB1oHQYNVi+HQXxSt6xGn/mzsr4AhR+vrS/dxoDvCqQyN51HypLawcucw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>Text should now look nicer on Retina screens</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling - fixed a problem where non-local tracks (iTunes Match) would not get their playcounts synced and lead to duplicates scrobbles</li>\n\t\t\t\t\t<li>Media keys are now ignored if you last listened to audio through another app</li>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.25</title>\n\t\t<pubDate>Thr, 25 Oct 2012 13:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.25\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.25.tar.bz2\"\n\t\t\tlength=\"49704\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFCX24RpRaDjf5+luL4aSX7Uqhz/gAhRulwjHFesGWsIJrSNoRCrvixbiUg==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now called \"Last.fm Scrobbler\"</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync - Scrobble your device before updating so you don't lose scrobbles</li>\n\t\t\t\t\t<li>The app is now partially translated with translations from the old app. A fully translated version will be coming soon</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some CPU usage fixes</li>\n\t\t\t\t\t<li>Fingerprinting backend has changed, fixing a rare crash</li>\n\t\t\t\t\t<li>Other minor bugs</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Mon, 10 Sep 2012 10:26:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.1.21\"\n\t\t\turl=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.21.tar.bz2\"\n\t\t\tlength=\"28528\"\n\t\t\ttype=\"application/octet-stream\"\n\t\t\tsparkle:dsaSignature=\"MCwCFFQ3ZyY6bowbSgQHih7rwDP/zasoAhRJrKkzhmeV/hrOIP+qVmmxPn1svw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to hide app icon from the dock (also has to hide app's menu bar, and icon in tab switcher)</li>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detected you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.20</title>\n        <pubDate>Fri, 01 Jun 2012 14:20:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.20\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.20.tar.bz2\"\n                length=\"24088\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MCwCFDXdsIAA9RR+fm1HASw9Wj9faEENAhQcojkXrhPuK3a19Pc1vyOLfGRRiA==\"/>\n        <description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n        <title>Last.fm Scrobbler 2.1.19</title>\n        <pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n        <enclosure\n                sparkle:version=\"2.1.19\"\n                url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.19.tar.bz2\"\n                length=\"28480\"\n                type=\"application/octet-stream\"\n                sparkle:dsaSignature=\"MC0CFQCnoxk6NB25D6bS7pjvj5zV1qqvFwIULUJgTSO3kIKxdeJz7xV9kV7xT5U=\"/>\n        <description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Media keys on your keyboard now control the radio - play/pause and skip</li>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed radio playback issue - some users had trouble skipping between songs</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Updated Phonon library from 4.4 to 4.6</li>\n\t\t\t\t\t\t<li>Switched to VLC as the audio backend</li>\n\t\t\t\t\t\t<li>Note: for users that didn't have this problem, they should notice some general playback performace improvements</li>\n\t\t\t\t\t\t<li>Also note: we made these changes for Windows too - there wasn't this specific bug, but you may still notice a performance improvement</li>\n\t\t\t\t\t</ul>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t<pubDate>Thu, 26 Apr 2012 19:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18.tar.bz2\"\n\t\t\t\t length=\"23368\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFGjp/NirSPRth1LDL77QPCPmkQAyAhQfUM6JKHUD5X2EUJ6wWwdhhXG0fg==\"/>\n\t\t<sparkle:deltas>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.16.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.16\"\n\t\t\t\t length=\"1688\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MC0CFQCRB1VjXyXaUpOVBsbDx1Rd8Hc68AIUPxqzKj34I8SeOLRiJmzyCPWjWLA=\"/>\n\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.18-2.1.17.delta\"\n\t\t\t\t sparkle:version=\"2.1.18\"\n\t\t\t\t sparkle:deltaFrom=\"2.1.17\"\n\t\t\t\t length=\"2064\"\n\t\t\t\t type=\"application/octet-stream\"\n\t\t\t\t sparkle:dsaSignature=\"MCwCFHOvbrgU7ttfYmhVk40FguibWWWYAhQQ+ezGEWuOPCeV4gVTK5Q3KXZ1Fg==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t<pubDate>Tue, 10 Apr 2012 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17.tar.bz2\" \n\t\t\t length=\"22920\" \n\t\t\t type=\"application/octet-stream\" \n\t\t\t sparkle:dsaSignature=\"MC0CFFTxxxig47d43vfUk0cazGJneKVEAhUAjhtrQMpb3dCxr2QG+IAQa8UidiY=\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure\n\t\t\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.17-2.1.16.delta\" \n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t sparkle:deltaFrom=\"2.1.16\" \n\t\t\t\t length=\"936\" \n\t\t\t\t type=\"application/octet-stream\" \n\t\t\t\t sparkle:dsaSignature=\"MCwCFD5bA6NPhtof5kQSbnywYqUK9wvOAhRGkOuC+rDdpl1z5OTJCMTYFbZFtw==\"/>\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thu, 15 Mar 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.16\"\n\t\t url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.16.tar.bz2\"\n\t\t length=\"22960\"\n\t\t type=\"application/octet-stream\"\n\t\t sparkle:dsaSignature=\"MC0CFQCEQyJvAbR7S4wVhJaUZ92yqeB40AIUe1N1zKt3QnW6pkbMP8gpKw9HxRk=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.15\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15.zip\"\n\t\t           length=\"59032\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHWXu3Odz1EEYnpTRHLZUoc8KKO5AhRqmaZ50QhLxIpATrwkCk1clzQzyw==\"/>\n\t\t<sparkle:deltas>\n\t\t\t<enclosure url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.15-2.1.14.delta\"\n\t\t\t\t\t\tsparkle:version=\"2.1.15\"\n\t\t\t\t\t\tsparkle:deltaFrom=\"2.1.14\"\n\t\t\t\t\t\tlength=\"3384\"\n\t\t\t\t\t\ttype=\"application/octet-stream\"\n\t\t\t\t\t\tsparkle:dsaSignature=\"MC0CFGEcpucDQFUoe7EQaFM1Z9VgLp2FAhUAgPgQIud6T+CP/XG8igI0MrkdW2c=\" />\n\t\t</sparkle:deltas>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>Don't ask where Spotify is, if it isn't installed</li>\n\t\t\t\t\t<li>Extra dock icons no longer appear</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.1.14\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.1.14.zip\"\n\t\t           length=\"58976\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MC0CFQCm/tD1PCjr4Mi1/qvLOG1OoaKNxQIUI+WsnFViB0P9lDF/sMm8KroUSHw=\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version!!!</h3>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.13\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.13.zip\"\n\t\t           length=\"59176\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFHHXLm4vnHA/163VDxm8s4qQssgvAhRbwKVMPS63OImXmO5mMkapIeU8MA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Now opens lastfm:// radio urls from the web site</li>\n\t\t\t\t\t<li>Upgraded to Qt 4.8.0</li>\n\t\t\t\t\t<li>Now tells you to close iTunes when there is a new plugin to install</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t\t<li>Friend list trackpad scrolling is now smooth (Qt 4.8.0)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thu, 02 Feb 2012 17:10:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.12\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.12.zip\"\n\t\t           length=\"53848\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFFmYvxQ1+8M06EI1AhtsJDETVrO/AhRTInZ6JAM93MPe6o/UaKIK9uyU3w==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 19:46:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.11\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.11.zip\"\n\t\t           length=\"54408\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFDdv1lLNaTRPJTaHIoZLvqI2klD2AhQ+uQJOYHyM9kFsshbkkW0ALtHkOQ==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly thought some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 16:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.10\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.10.zip\"\n\t\t           length=\"54496\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFEQAxtXPwDtGHruTYrx04PP8FROxAhQwVpzAFN8X297zXXvTyQqn5K6quw==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixed iTunes plugin crashing iTunes for some Snow Leopard people</li>\n\t\t\t\t\t<li>Fixed the menubar not showing sometimes at startup</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 10:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.9\"\n\t\t           url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.9.zip\"\n\t\t           length=\"52088\" \n\t\t           type=\"application/octet-stream\" \n\t\t           sparkle:dsaSignature=\"MCwCFBtr5ldX6tmaqfn7RL//XLJPZqdWAhQu5HFQXpNtd4QoDatlNBfzOrNASA==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 10:55:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.8\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.8.zip\" length=\"51896\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFBuMoqm2G0qlrCyFygeLf6e5e05ZAhQB/hQ067CDeqJsv1LyaDMtRIqU1g==\"/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features/Improvements</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Stops from iTunes are picked up - end of a playlist, quit iTunes, etc</li>\n\t\t\t\t\t<li>Resume iTunes track after playing and pausing radio is now picked up</li>\n\t\t\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:20:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.7\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.7.zip\" length=\"50344\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFFlKwnxI0WAcCBHYPRp9IvNywXvMAhREH2R5d5IUZK+bULZ3u8XFgwt+dA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.6\" url=\"https://cdn.last.fm/client/Mac/Last.fm-2.0.6.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MC0CFQCGwuA+Sd2RvbtWK3xrjCf3i+eJBgIULgTgtcvxYt3xX3etnF7ZvhXeUwA=\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>New friends list</li>\n\t\t\t\t\t<li>Now installs media player plugins on Windows</li>\n\t\t\t\t\t<li>Bootstrapping for all media players now works</li>\n\t\t\t\t\t<li>Many other bug fixes and improvements</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.5</title>\n\t\t<pubDate>Thu, 17 Nov 2011 16:57:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.5\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.5.zip\" length=\"50368\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFCi+YjPJ2yvXKXoh/S/Z/B/c8PO7AhRG53S7/K3fMeBChE58OyuPht3oxA==\"/>\n\t\t<description><![CDATA[\n\t\t        <ul>\n\t\t\t\t\t<li>Lots of UI changes - welcome screen changed, metadata view improved, etc etc</li>\n\t\t\t\t\t<li>Supports updates with libsparkle!</li>\n\t\t\t\t\t<li>Uses the Growl framework to show notifications with album art</li>\n\t\t\t\t\t<li>Airfoil metadata support</li>\n\t\t\t\t\t<li>Scriptable with AppleScript (see the dictionary)</li>\n\t\t\t\t\t<li>Campaign tracking when linking to the website</li>\n\t\t\t\t\t<li>Radio quick start widget now shows artist and tag suggestions</li>\n\t\t\t\t\t<li>Big play buttons now resume the last radio</li>\n\t\t\t\t\t<li>Friends list now sorted by most recently listened</li>\n\t\t\t\t\t<li>Switching tabs now has a slide animation</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.4</title>\n\t\t<pubDate>Tue, 08 Nov 2011 15:30:00 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.4\" url=\"https://cdn.last.fm/client/Mac/Last.fm.2.0.4.zip\" length=\"50496\" type=\"application/octet-stream\" sparkle:dsaSignature=\"MCwCFB+JR/g7HGKNroRRj7PStc2aH0j4AhR7vlzYCGxVgcdO0pmi7vO2vss0Vg==\"/>\n\t\t<description><![CDATA[\n\t\t        <h3>Embedded release notes!</h3>\n\t\t        ...\n\t\t    ]]></description>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/updates.win.beta.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>http://cdn.last.fm/client/updates/updates.win.beta.xml</link>\n\t<description>Last.fm Scrobbler Updates - Windows Beta</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.36\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.36.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 11:29:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.35\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.35.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>New updating framework - currently just looks better and is smaller, but it's the first step in better Windows updating</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t\t<li>Tracks are now identified by persistent id rather then filename - fixes a few problems and should be more robust</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Windows Media Player scrobbles now include 'album artist' (just like other media players already do)</li>\n\t\t\t\t<li>Only show 'Open iTunes' if it has been installed</li>\n\t\t\t\t<li>Settings dialog resizing improved</li>\n\t\t\t\t<li>Correctly display track metatdata that has characters such as &lt; in it</li>\n\t\t\t\t<li>The prompt to restart now actually restarts the app</li>\n\t\t\t\t<li>When installing a plugin from the file menu the full installer is shown - user can select install location, if not default, etc</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.33\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t\t<li>iTunes plugin update for XP scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"http://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.32\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Now runs on Windows XP</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30 (First full release!)</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.30\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.30.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for a device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.29\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.29.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.28\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.28.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash when fingerprinting some audio files</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.27\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.27.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.26\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.26.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>iTunes plugin and app now both use the same playcounts db (they didn't before!?)</li>\n\t\t\t\t\t\t<li>Tracks that end within 20 seconds of starting (user skipped to near the end) now get their playcounts synced (was leading to duplicate scrobbles)</li>\n\t\t\t\t\t\t<li>iTunes no longer kept open by us not releasing a handle to it</li>\n\t\t\t\t\t\t<li>Fixed a problem where the iTunes plugin would stop communicating with the app so scrobbling stopped (this also caused the plays to be picked up as iTunes device scrobbles)</li>\n\t\t\t\t\t\t<li>Fixed a problem where the last track of a playlist would not get it's playcount synced leading to it being picked up as an iTunes device scrobble</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.24</title>\n\t\t<pubDate>Wed, 26 Sep 2012 11:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.24\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.24.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.24</h3>\n\t\t\t\t<h3>Windows only bug fix release</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed an issue where iTunes devices (iPod/iPhone) wouldn't scrobble if the app was not installed to the default location</li>\n\t\t\t\t\t<li>Fixed a crash with iTunes device scrobbling introduced with the 'album artist' scrobble changes</li>\n\t\t\t\t\t<li>Fixed a crash caused by fingerprinting .flac files</li>\n\t\t\t\t\t<li>Fixed an issue where the volume would reset to maximum at the start of every radio track</li>\n\t\t\t\t\t<li>Fixed a CPU usage issue</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Tue, 04 Sep 2012 14:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.21\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.21.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.21</h3>\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detcted you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.20</title>\n\t\t\t<pubDate>Fri, 01 Jun 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.20\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.20.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t\t<li>Fixed iPod scrobbling (was broken in 2.1.19)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.19</title>\n\t\t<pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.19\" \n\t\t\t url=\"\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t\t<pubDate>Thr, 26 Apr 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.18\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.18.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t\t<pubDate>Mon, 14 Mar 2012 18:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.17.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Features</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thr, 15 Mar 2012 11:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.16\"\n\t\t\turl=\"http://cdn.last.fm/client/Win/Last.fm-2.1.16.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.15\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.15.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>iPod scrobbling should now work</li>\n\t\t\t\t\t<li>'Close' and 'Apply' buttons now work correctly</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 13:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.14\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.14.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version</h3>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 18:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.13\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.13.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thr, 02 Feb 2012 18:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.12\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.12.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling should now work (as well as it does on mac)! The installer was incorrect</li>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 20:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.11\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.11.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly though some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 17:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.10\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.10.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 11:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.9\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.9.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>New iTunes plugin was not working due to a change in Qt</li>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 11:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.8\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.8.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t<h3>Features/Improvements</h3>\n\t\t<ul>\n\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t</ul>\n\t\t<h3>Bug fixes</h3>\n\t\t<ul>\n\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t</ul>\n\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.0.7\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.7.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t\t<description><![CDATA[\n\t\t\t<ul>\n\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.6\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.6.exe\"\n\t\t\t/>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.1</title>\n\t\t<pubDate>Wed, 02 Nov 2011 11:11:11 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.1\"\n\t\t\turl=\"http://cdn.last.fm/20111102WIN.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/updates/updates.win.xml",
    "content": "<rss version=\"2.0\" xmlns:sparkle=\"http://www.andymatuschak.org/xml-namespaces/sparkle\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n<channel>\n\t<title>Last.fm Scrobbler Updates</title>\n\t<link>http://cdn.last.fm/client/updates/updates.win.xml</link>\n\t<description>Last.fm Scrobbler Updates - Windows</description>\n\t<language>en</language>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.36</title>\n\t\t<pubDate>Tue, 03 Sep 2013 12:14:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.36\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.36.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>New playback controls and progress bar design!</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>iPod scrobbles with multiple plays are now submitted at 1 second intervals instead of all at the same time</li>\n\t\t\t\t<li>Fingerprinting is fixed and back - it's now also in a different process so fingerprinting problems don't bring down the whole app (just a precaution)</li>\n\t\t\t\t<li>Fixed some memory leaks</li>\n\t\t\t\t<li>Scrobble count on profile tab now updated correctly (unless you scrobble elsewhere)</li>\n\t\t\t\t<li>Do not display corrections in the client (it wasn't respecting the website setting and was causing a few issues)</li>\n\t\t\t\t<li>'Similar Artist' header in the track metadata view is now a link to more similar artists on the site</li>\n\t\t\t\t<li>There is now a warning/explanation in the iPod scrobble confirmation dialog when you have red/invalid iPod scrobbles</li>\n\t\t\t\t<li>Now shows the correct modifier keys on Windows for the raise/hide Scrobbler option</li>\n\t\t\t\t<li>Mute now works from the system tray and menu option</li>\n\t\t\t\t<li>The last page of the wizard now doesn't say we've imported your listening history, if we haven't</li>\n\t\t\t\t<li>Fixed an issue where the tray icon would be invisible if the first run wizard tour was skipped</li>\n\t\t\t\t<li>Less logging (there was an issue with log file sizes getting very big)</li>\n\t\t\t</ul>\n\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.35</title>\n\t\t<pubDate>Wed, 06 Mar 2013 11:29:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.35\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.35.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t<h3>Features</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Exclude directories! You can now exclude music in certain directories from being scrobbled</li>\n\t\t\t\t<li>Systray/menu bar icon is greyed out when scrobbling is disabled</li>\n\t\t\t\t<li>New updating framework - currently just looks better and is smaller, but it's the first step in better Windows updating</li>\n\t\t\t\t<li>[Experimental] Added the ability to use SSL for all web services calls</li>\n\t\t\t</ul>\n\t\t\t<h3>Bug fixes</h3>\n\t\t\t<ul>\n\t\t\t\t<li>Fingerprinting was causing crashes so has been temporarily disabled until we find a proper fix</li>\n\t\t\t\t<li>Device scrobbling improvements</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now force that a compatible iTunes plugin version is installed before trying to device scrobble</li>\n\t\t\t\t\t<li>Prompt to install the new plugin has been improved</li>\n\t\t\t\t\t<li>Tracks are now identified by persistent id rather then filename - fixes a few problems and should be more robust</li>\n\t\t\t\t</ul>\n\t\t\t\t<li>Windows Media Player scrobbles now include 'album artist' (just like other media players already do)</li>\n\t\t\t\t<li>Only show 'Open iTunes' if it has been installed</li>\n\t\t\t\t<li>Settings dialog resizing improved</li>\n\t\t\t\t<li>Correctly display track metatdata that has characters such as &lt; in it</li>\n\t\t\t\t<li>The prompt to restart now actually restarts the app</li>\n\t\t\t\t<li>When installing a plugin from the file menu the full installer is shown - user can select install location, if not default, etc</li>\n\t\t\t\t<li>Tracks now get their scrobble and loved status updated when the scrobble list is refreshed</li>\n\t\t\t\t<li>Fixed scrobbling problems associated with setting the scrobble point to 100%</li>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed double scrobble and missed scrobbles</li>\n\t\t\t\t\t<li>There's now a setting to turn of the maximum scrobble point being 4 minutes</li>\n\t\t\t\t\t<li>Scrobble point and max scrobble turn off now take effect during the current track</li>\n\t\t\t\t</ul>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.33</title>\n\t\t<pubDate>Thr, 24 Jan 2013 11:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.33\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>First run wizard's continue button no longer gets stuck</li>\n\t\t\t\t\t\t<li>iTunes plugin update for XP scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<a class=\"more\" href=\"http://cdn.last.fm/client/updates/updates.html\">Full changelog</a>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.32</title>\n\t\t<pubDate>Tue, 22 Jan 2013 13:48:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.32\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.33.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>All users should now be able to authenticate - changed to a simpler authentication mechanism</li>\n\t\t\t\t\t\t<li>Now runs on Windows XP</li>\n\t\t\t\t\t\t<li>Added a beta updates option - warning: only for the brave!</li>\n\t\t\t\t\t\t<li>Fixed some minor account bootstrap issues</li>\n\t\t\t\t\t\t<li>Open 'media player' links now work on Windows</li>\n\t\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.30 (First full release!)</title>\n\t\t<pubDate>Mon, 14 Jan 2013 16:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.30\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.30.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t\t<li>A temporary workaround for a device scrobbling error</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.29</title>\n\t\t<pubDate>Mon, 14 Jan 2013 12:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.29\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.29.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations updated and complete</li>\n\t\t\t\t\t<li>Don't fingerprint files from audio CDs</li>\n\t\t\t\t\t<li>Fixed some problems upgrading from The Scrobbler 1.x</li>\n\t\t\t\t\t<li>Fixed a crash when enabling/disabling device scrobbling</li>\n\t\t\t\t\t<li>Fixed a crash when switching user accounts</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.28</title>\n\t\t<pubDate>Tue, 08 Jan 2013 11:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.28\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.28.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Changes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Side bar images updated slightly</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Restore the main window size and position correctly after restart</li>\n\t\t\t\t\t<li>Fixed a crash when fingerprinting some audio files</li>\n\t\t\t\t\t<li>Fixed spurious device scrobbles caused by a race condition</li>\n\t\t\t\t\t<li>Fixed triple scrobbling when scrobbling offline cached scrobbles</li>\n\t\t\t\t\t<li>Don't run the device scrobble checker so often - it was running almost all the time on Windows</li>\n\t\t\t\t\t<li>Device scrobble performance improvements</li>\n\t\t\t\t\t<li>Minimize and Zoom menu options now work</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.27</title>\n\t\t<pubDate>Fri, 21 Dec 2012 15:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.27\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.27.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed a crash on startup for new users</li>\n\t\t\t\t\t<li>Fixed iTunes plays being picked up as device scrobbles Windows (may improve Mac too)</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.26</title>\n\t\t<pubDate>Mon, 17 Dec 2012 12:15:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.26\"\n\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.26.exe\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Translations! (almost complete)</li>\n\t\t\t\t\t<li>Proxy settings - you can set them from the advanced settings tab and the first step of first run wizard</li>\n\t\t\t\t\t<li>iPod scrobbling has been reworked to allow for WiFi sync</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling</li>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>iTunes plugin and app now both use the same playcounts db (they didn't before!?)</li>\n\t\t\t\t\t\t<li>Tracks that end within 20 seconds of starting (user skipped to near the end) now get their playcounts synced (was leading to duplicate scrobbles)</li>\n\t\t\t\t\t\t<li>iTunes no longer kept open by us not releasing a handle to it</li>\n\t\t\t\t\t\t<li>Fixed a problem where the iTunes plugin would stop communicating with the app so scrobbling stopped (this also caused the plays to be picked up as iTunes device scrobbles)</li>\n\t\t\t\t\t\t<li>Fixed a problem where the last track of a playlist would not get it's playcount synced leading to it being picked up as an iTunes device scrobble</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<li>Don't divide by zero (crash) for users that are using the app on the same day as they registered</li>\n\t\t\t\t\t<li>Fixed restarting the app in Mac, still not working on Windows.</li>\n\t\t\t\t\t<li>Radio now goes into the stopped state correctly</li>\n\t\t\t\t\t<li>Device scrobble Window is now a child of the main window (it appears positioned on top of it nicely now)</li>\n\t\t\t\t\t<li>Fixed a double delete crash when the fingerprinter failed</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.24</title>\n\t\t<pubDate>Wed, 26 Sep 2012 11:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.24\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.24.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.24</h3>\n\t\t\t\t<h3>Windows only bug fix release</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed an issue where iTunes devices (iPod/iPhone) wouldn't scrobble if the app was not installed to the default location</li>\n\t\t\t\t\t<li>Fixed a crash with iTunes device scrobbling introduced with the 'album artist' scrobble changes</li>\n\t\t\t\t\t<li>Fixed a crash caused by fingerprinting .flac files</li>\n\t\t\t\t\t<li>Fixed an issue where the volume would reset to maximum at the start of every radio track</li>\n\t\t\t\t\t<li>Fixed a CPU usage issue</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.21</title>\n\t\t<pubDate>Tue, 04 Sep 2012 14:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.21\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.21.exe\"\n\t\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>2.1.21</h3>\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>We now scrobble 'album artist' as well as 'artist' for cleaner album pages on the website (all plugins have been updated)</li>\n\t\t\t\t\t<li>Fingerprinting local tracks has been added (can be turned off in preferences)</li>\n\t\t\t\t\t<li>\"Scrobbling is off\" message has been added to the status bar</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Better album images in the scrobble list</li>\n\t\t\t\t\t<li>We now only ask you to install plugins for apps we've detcted you've installed</li>\n\t\t\t\t\t<li>We now make sure you close your media players before plugins are installed</li>\n\t\t\t\t\t<li>We now make sure you close WMP or Winamp before bootstrapping (won't bootstrap if they are left open)</li>\n\t\t\t\t\t<li>Profile widget now refreshed when you switch to it so data doesn't get as out of date</li>\n\t\t\t\t\t<li>Fixed some bugs in the preferences dialog</li>\n\t\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.20</title>\n\t\t\t<pubDate>Fri, 01 Jun 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.20\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.20.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n        \t\t<h3>Bug fixes</h3>\n        \t\t<ul>\n\t\t\t\t\t<li>Fixed some radio playback issues introduced with the switch to VLC</li>\n\t\t\t\t\t<li>Fixed iPod scrobbling (was broken in 2.1.19)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.19</title>\n\t\t<pubDate>Wed, 30 May 2012 14:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\t sparkle:os=\"windows\"\n\t\t\t sparkle:version=\"2.1.19\" \n\t\t\t url=\"\"\n\t\t\t />\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>More scrobble tab design improvements</li>\n\t\t\t\t</ul>\n\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.18</title>\n\t\t\t<pubDate>Thr, 26 Apr 2012 16:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.18\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.18.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Scrobble tab design improvements</li>\n\t\t\t\t\t<li>Can now delete scrobbles from the list through the right click menu</li>\n\t\t\t\t\t<li>Added a licenses dialog for third party software</li>\n\t\t\t\t\t<li>About box now has the Last.fm logo</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Quit dialog now asks a question</li>\n\t\t\t\t\t<li>Scrobble repeated tracks</li>\n\t\t\t\t\t<li>Now restores same size and position when reopening</li>\n\t\t\t\t\t<li>Initial window size adjusts for very small/low resolution screens</li>\n\t\t\t\t\t<li>Doesn't filter other user's personal stations from your recent stations anymore</li>\n\t\t\t\t\t<li>Windows installer now has updated images</li>\n\t\t\t\t\t<li>Doesn't need to fetch track info when refreshing the scrobbles list anymore</li>\n\t\t\t\t\t<li>Should now run on Mac OSX 10.5.x</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.17</title>\n\t\t\t<pubDate>Mon, 14 Mar 2012 18:30:00 +0000</pubDate>\n\t\t\t<enclosure\n\t\t\t\t sparkle:os=\"windows\"\n\t\t\t\t sparkle:version=\"2.1.17\" \n\t\t\t\t url=\"http://cdn.last.fm/client/Win/Last.fm-2.1.17.exe\"\n\t\t\t\t />\n\t\t\t<description><![CDATA[\n\t\t\t\t\t<h3>Features</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Can now set the language - the app itself isn't translated yet, but this affects artist bios, etc</li>\n\t\t\t\t\t\t<li>Scrobbles list rewritten and improved</li>\n\t\t\t\t\t\t<ul>\n\t\t\t\t\t\t\t<li>Corrections asterisk with hover over now shown</li>\n\t\t\t\t\t\t\t<li>Displays if the scrobble is cached and yet to be submitted</li>\n\t\t\t\t\t\t\t<li>Displays if their was an error when submitting the scrobble - i.e. bad metadata</li>\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t<li>Profile, Friends, and Radio tab design improvements</li>\n\t\t\t\t\t</ul>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t\t<ul>\n\t\t\t\t\t\t<li>Always start on the scrobble list when switching to that tab, not the previous track info view</li>\n\t\t\t\t\t\t<li>Less calls made to track.getInfo</li>\n\t\t\t\t\t\t<li>If app is closed to tray and notifications turned off, the only web services called are for scrobbling</li>\n\t\t\t\t\t</ul>\n\t\t\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler 2.1.16</title>\n\t\t<pubDate>Thr, 15 Mar 2012 11:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.16\"\n\t\t\turl=\"http://cdn.last.fm/client/Win/Last.fm-2.1.16.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now has a max width of 800px</li>\n\t\t\t\t\t<li>Use app icon for all radio stations</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Fixed the now playing display bug</li>\n\t\t\t\t\t<li>Fixed a crash that manifested itself in several places (cancelling getting info for a track)</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.15</title>\n\t\t<pubDate>Tue, 28 Feb 2012 16:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.15\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.15.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Radio controls are now in the sys tray too</li>\n\t\t\t\t\t<li>Buy links now in the scrobble list view</li>\n\t\t\t\t\t<li>There's now a diagnostics dialog - only one tab with the ability to force a check for iPod scrobbles and see the log so far</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Dialogs, like preferences, are now brought to the front if reopened</li>\n\t\t\t\t\t<li>Many copy changes around the app</li>\n\t\t\t\t\t<li>Doesn't erroneously display two now playing tracks anymore</li>\n\t\t\t\t\t<li>iPod scrobbles are submitted immeditaly instead of just cached</li>\n\t\t\t\t\t<li>Doesn't fetch track info as much</li>\n\t\t\t\t\t<li>The loved state of the current track is now reliable</li>\n\t\t\t\t\t<li>iPod scrobbling should now work</li>\n\t\t\t\t\t<li>'Close' and 'Apply' buttons now work correctly</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Beta Version 2.1.14</title>\n\t\t<pubDate>Tue, 14 Feb 2012 13:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.1.14\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.1.14.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>This is the first public beta version</h3>\n\t\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Updates to the wizard copy</li>\n\t\t\t\t\t<li>Buy links now work for uk, us, and de users (was only ever doing uk links)</li>\n\t\t\t\t\t<li>Other very minor fixes</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Alpha Version 2.0.13</title>\n\t\t<pubDate>Fri, 10 Feb 2012 18:50:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.13\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.13.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Changed the API key. Everyone will have to go through the wizard again</li>\n\t\t\t\t\t<li>Message bar now styles nicely</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Doesn't show two now playing tracks in the scrobble list any more</li>\n\t\t\t\t\t<li>Fixed quite a few bugs in the frist run wizard</li>\n\t\t\t\t\t<li>Fixed some bugs with the account management settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.12</title>\n\t\t<pubDate>Thr, 02 Feb 2012 18:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.12\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.12.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Now branded as a beta version!</li>\n\t\t\t\t\t<li>Tag dialog now implemented to similar standard as the share dialog</li>\n\t\t\t\t\t<li>Only fetches track metadata if the window is visable</li>\n\t\t\t\t\t<li>Scrobble toggle now in preferences</li>\n\t\t\t\t\t<li>'Play' menu option is now not checkable, but has 'play', 'pause' and 'resume' states</li>\n\t\t\t\t\t<li>Progress bar now reports the state correctly for podcasts and videos</li>\n\t\t\t\t\t<li>Don't display metadata for Spotify ads</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>iPod scrobbling should now work (as well as it does on mac)! The installer was incorrect</li>\n\t\t\t\t\t<li>iTunes plugin now handles device names with ' and \\ in them correctly</li>\n\t\t\t\t\t<li>Device names are now interpreted as utf-8 by the app</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.11</title>\n\t\t<pubDate>Wed, 25 Jan 2012 20:10:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.11\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.11.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes 2.0.11</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Incorrectly though some radio tracks were podcasts or videos</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Features - 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes 2.0.10</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.10</title>\n\t\t<pubDate>Wed, 25 Jan 2012 17:30:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.10\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.10.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Features</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Added option to turn off podcast scrobbling</li>\n\t\t\t\t\t<li>Now doesn't scrobble videos from iTunes, that aren't music videos</li>\n\t\t\t\t\t<li>Added option to disable desktop notifications</li>\n\t\t\t\t\t<li>Added option to disable launching the app with media players</li>\n\t\t\t\t</ul>\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>Some user setting fixes, you will have to go through the wizard again</li>\n\t\t\t\t\t<li>Fixes to iTunes plugin communication problems (named pipe type incompatibilities)</li>\n\t\t\t\t\t<li>If the app is started with --tray option (i.e. from a media player) it now doesn't show the main window</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.9</title>\n\t\t<pubDate>Mon, 16 Jan 2012 11:20:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.9\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.9.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t\t\t<h3>Bug fixes</h3>\n\t\t\t\t<ul>\n\t\t\t\t\t<li>New iTunes plugin was not working due to a change in Qt</li>\n\t\t\t\t\t<li>iPod scrobble device associations were getting corrupted</li>\n\t\t\t\t\t<li>Cleaned up and fixed some bugs in the apps user settings</li>\n\t\t\t\t</ul>\n\t\t    ]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.8</title>\n\t\t<pubDate>Thu, 12 Jan 2012 11:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.8\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.8.exe\"\n\t\t\t/>\n\t\t<description><![CDATA[\n\t\t<h3>Features/Improvements</h3>\n\t\t<ul>\n\t\t\t<li>Settings toolbar now looks better and has assets </li>\n\t\t\t<li>Crash Reporting implemented in client, but disabled. (needs oops server set up by ops)</li>\n\t\t</ul>\n\t\t<h3>Bug fixes</h3>\n\t\t<ul>\n\t\t\t<li>Spacebar now works again as a global shortcut</li>\n\t\t</ul>\n\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.7</title>\n\t\t<pubDate>Wed, 04 Jan 2012 12:45:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:version=\"2.0.7\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.7.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t\t<description><![CDATA[\n\t\t\t<ul>\n\t\t\t\t<li>Fixed a major bug with batch scrobbling</li>\n\t\t\t\t<li>Fixed a crash for unkown length tracks (iTunes radio streams)</li>\n\t\t\t</ul>\n\t\t]]></description>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.6</title>\n\t\t<pubDate>Fri, 23 Dec 2011 17:00:00 +0000</pubDate>\n\t\t<enclosure\n\t\t\tsparkle:os=\"windows\"\n\t\t\tsparkle:version=\"2.0.6\"\n\t\t\turl=\"http://static.last.fm/client/Win/Last.fm-2.0.6.exe\"\n\t\t\t/>\n\t</item>\n\t<item>\n\t\t<title>Last.fm Scrobbler Version 2.0.1</title>\n\t\t<pubDate>Wed, 02 Nov 2011 11:11:11 +0000</pubDate>\n\t\t<enclosure sparkle:version=\"2.0.1\"\n\t\t\turl=\"http://cdn.last.fm/20111102WIN.exe\"\n\t\t\tsparkle:os=\"windows\"/>\n\t</item>\n</channel>\n</rss>\n"
  },
  {
    "path": "admin/dist/win/Last.fm.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=2.1.36\r\n\r\n\r\n[Setup]\r\nOutputBaseFilename=Last.fm-2.1.36\r\nVersionInfoVersion=2.1.36\r\nVersionInfoTextVersion=2.1.36\r\nAppName=\"Last.fm Scrobbler\"\r\nAppVerName=\"Last.fm Scrobbler {cm:Version}\"\r\nVersionInfoDescription=Last.fm Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright 2012 Last.fm Ltd. (C)\r\nDefaultDirName={pf}\\Last.fm\r\nUsePreviousAppDir=yes\r\nDefaultGroupName=Last.fm\r\nOutputDir=.\r\nAllowNoIcons=yes\r\nCompression=lzma\r\nSolidCompression=yes\r\nDisableReadyPage=yes\r\nDirExistsWarning=no\r\nDisableFinishedPage=no\r\nShowLanguageDialog=yes\r\nWizardImageFile=wizard.bmp\r\nWizardSmallImageFile=wizard_small.bmp\r\nSetupIconFile=installer.ico\r\nUninstallDisplayIcon=\"{app}\\Last.fm Scrobbler.exe\"\r\nAppModifyPath=\"{app}\\UninsHs.exe\" /m0=LastFM\r\nWizardImageBackColor=$ffffff\r\nWizardImageStretch=no\r\nAppMutex=Lastfm-F396D8C8-9595-4f48-A319-48DCB827AD8F, Audioscrobbler-7BC5FBA0-A70A-406e-A50B-235D5AFE67FB\r\n\r\n; This should stay the same across versions for the installer to treat it as the same program.\r\n; It will then work to install however many updates and then run the uninstall script for\r\n; the first version.\r\nAppId=LastFM\r\n\r\n[Languages]\r\n; The first string is an internal code that we can set to whatever we feel like\r\nName: \"en\"; MessagesFile: \"compiler:Default.isl\"\r\n;Name: \"fr\"; MessagesFile: \"compiler:French.isl\"\r\n;Name: \"it\"; MessagesFile: \"compiler:Italian.isl\"\r\n;Name: \"de\"; MessagesFile: \"compiler:Deutsch.isl\"\r\n;Name: \"es\"; MessagesFile: \"compiler:Spanish.isl\"\r\n;Name: \"pt\"; MessagesFile: \"compiler:Portuguese - Brasil.isl\"\r\n;Name: \"pl\"; MessagesFile: \"compiler:Polish.isl\"\r\n;Name: \"ru\"; MessagesFile: \"compiler:Russian.isl\"\r\n;Name: \"jp\"; MessagesFile: \"compiler:Japanese.isl\"\r\n;Name: \"chs\"; MessagesFile: \"compiler:Simplified Chinese.isl\"\r\n;Name: \"tr\"; MessagesFile: \"compiler:Turkish.isl\"\r\n;Name: \"se\"; MessagesFile: \"compiler:Swedish.isl\"\r\n\r\n\r\n[Tasks]\r\nName: \"desktopicon\"; Description: \"{cm:CreateDesktopIcon}\"; GroupDescription: \"{cm:AdditionalIcons}\"\r\n\r\n; The OnlyBelowVersion flag disables this on Vista as an admin-run installer can't install a quick launch\r\n; icon to the standard user's folder location. Sucks.\r\nName: \"quicklaunchicon\"; Description: \"{cm:CreateQuickLaunchIcon}\"; GroupDescription: \"{cm:AdditionalIcons}\"; Flags: unchecked; OnlyBelowVersion: 0, 6;\r\n\r\n[Dirs]\r\nName: \"{localappdata}\\Last.fm\\Client\"\r\n\r\n[Files]\r\n; Main files\r\nSource: \"..\\..\\..\\_bin\\Last.fm Scrobbler.exe\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\iPodScrobbler.exe\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;libraries\r\nSource: \"..\\..\\..\\_bin\\lastfm.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\lastfm_fingerprint.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\unicorn.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\listener.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\logger.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;Visual Studio 2010 redistributable packages\r\nSource: \"%VSDIR%\\VC\\redist\\x86\\Microsoft.VC100.CRT\\*\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%VSDIR%\\VC\\redist\\x86\\Microsoft.VC100.ATL\\*\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;Qt binaries\r\nSource: \"%QTDIR%\\bin\\QtCore4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\bin\\QtGui4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\bin\\QtNetwork4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\bin\\QtXml4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\bin\\QtSql4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\bin\\QtWebKit4.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\phonon.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;image formats plugins\r\nSource: \"%QTDIR%\\plugins\\imageformats\\qjpeg4.dll\"; DestDir: \"{app}\\plugins\\imageformats\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\plugins\\imageformats\\qgif4.dll\"; DestDir: \"{app}\\plugins\\imageformats\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\plugins\\imageformats\\qmng4.dll\"; DestDir: \"{app}\\plugins\\imageformats\"; Flags: ignoreversion\r\n\r\n;phonon backend plugin\r\nSource: \"..\\..\\..\\_bin\\plugins\\phonon_backend\\phonon_vlc.dll\"; DestDir: \"{app}\\plugins\\phonon_backend\"; Flags: ignoreversion\r\n\r\n;sqlite plugin\r\nSource: \"%QTDIR%\\plugins\\sqldrivers\\qsqlite4.dll\"; DestDir: \"{app}\\plugins\\sqldrivers\"; Flags: ignoreversion\r\n\r\n; vlc libraries\r\nSource: \"..\\..\\..\\_bin\\libvlccore.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\libvlc.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n; vlc plugins\r\nSource: \"..\\..\\..\\_bin\\plugins\\access\\libaccess_http_plugin.dll\"; DestDir: \"{app}\\plugins\\access\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\liba52tofloat32_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\liba52tospdif_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libaudio_format_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libconverter_fixed_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libdolby_surround_decoder_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libdtstofloat32_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libdtstospdif_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libmpgatofixed32_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libsamplerate_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libscaletempo_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libsimple_channel_mixer_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libspeex_resampler_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libtrivial_channel_mixer_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_filter\\libugly_resampler_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_filter\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_mixer\\libfloat32_mixer_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_mixer\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\audio_output\\libaout_directx_plugin.dll\"; DestDir: \"{app}\\plugins\\audio_output\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\codec\\libmpeg_audio_plugin.dll\"; DestDir: \"{app}\\plugins\\codec\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\demux\\libes_plugin.dll\"; DestDir: \"{app}\\plugins\\demux\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\misc\\liblogger_plugin.dll\"; DestDir: \"{app}\\plugins\\misc\"; Flags: ignoreversion\r\n\r\n;media player plugin installers\r\nSource: \"..\\..\\..\\_bin\\plugins\\FooPlugin0.9.4Setup_2.3.1.3.exe\"; DestDir: \"{app}\\plugins\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\iTunesPluginWinSetup_6.0.5.4.exe\"; DestDir: \"{app}\\plugins\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\WinampPluginSetup_2.1.0.11.exe\"; DestDir: \"{app}\\plugins\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\plugins\\WmpPluginSetup_2.1.0.8.exe\"; DestDir: \"{app}\\plugins\"; Flags: ignoreversion\r\n\r\n;3rd party\r\nSource: \"..\\..\\..\\_bin\\libfftw3f-3.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\libsamplerate-0.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\avcodec-54.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\avformat-54.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\avutil-52.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\swresample-0.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\libeay32.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"..\\..\\..\\_bin\\ssleay32.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;The stylesheets\r\nSource: \"..\\..\\..\\app\\client\\Last.fm Scrobbler.css\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n;The translations\r\nSource: \"..\\..\\..\\i18n\\*.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_de.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_es.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_fr.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_ja.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_pl.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_pt.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_ru.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_sv.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\nSource: \"%QTDIR%\\translations\\qt_zh_CN.qm\"; DestDir: \"{app}\\i18n\"; Flags: ignoreversion\r\n\r\n;The add/modify/remove file\r\nSource: \"UninsHs.exe\"; DestDir: \"{app}\"; Flags: onlyifdoesntexist\r\n\r\n;Text files?\r\n\r\n[Registry]\r\n; The Path is looked for in both places by plugins\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Client\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Client\"; ValueType: string; ValueName: \"Path\"; ValueData: \"{app}\\Last.fm Scrobbler.exe\"; Flags: uninsdeletekey\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Last.fm\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Last.fm\"; ValueType: string; ValueName: \"Path\"; ValueData: \"{app}\\Last.fm Scrobbler.exe\"; Flags: uninsdeletekey\r\n\r\n; Register last.fm protocol only if it isn't already\r\nRoot: HKCR; Subkey: \"lastfm\"; ValueType: string; ValueName: \"\"; ValueData: \"URL:lastfm\"; Flags: uninsdeletekey\r\nRoot: HKCR; Subkey: \"lastfm\"; ValueType: string; ValueName: \"URL Protocol\"; ValueData: \"\"; Flags: uninsdeletekey\r\nRoot: HKCR; Subkey: \"lastfm\\shell\\open\\command\"; ValueType: string; ValueName: \"\"; ValueData: \"\"\"{app}\\Last.fm Scrobbler.exe\"\" \"\"%1\"\"\"; Flags: uninsdeletekey\r\n\r\n; qtsparkle - This stop it asking the user if they want to check for updates on first run.\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Last.fm Scrobbler\\QtSparkle\"; ValueType: string; ValueName: \"asked_permission\"; ValueData: \"true\"; Flags: uninsdeletekey\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Last.fm Scrobbler\\QtSparkle\"; ValueType: string; ValueName: \"check_automatically\"; ValueData: \"true\"; Flags: uninsdeletekey createvalueifdoesntexist\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Last.fm Scrobbler\\QtSparkle\"; ValueType: string; ValueName: \"first_boot\"; ValueData: \"false\"; Flags: uninsdeletekey\r\n\r\n; This is just for deleting keys at uninstall\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\"; Flags: dontcreatekey uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\"; Flags: dontcreatekey uninsdeletekey\r\n\r\n[Icons]\r\nName: \"{group}\\Last.fm Scrobbler\"; Filename: \"{app}\\Last.fm Scrobbler.exe\"\r\nName: \"{commondesktop}\\Last.fm Scrobbler\"; Filename: \"{app}\\Last.fm Scrobbler.exe\"; Tasks: desktopicon\r\n\r\n;Uninstall\r\nName: \"{group}\\Uninstall Last.fm Scrobbler\"; Filename: \"{app}\\UninsHs.exe\"; Parameters: \"/u0=LastFM\"\r\n\r\n; The OnlyBelowVersion flag disables this on Vista as an admin-run installer can't install a quick launch\r\n; icon to the standard user's folder location. Sucks.\r\nName: \"{userappdata}\\Microsoft\\Internet Explorer\\Quick Launch\\Last.fm Scrobbler\"; Filename: \"{app}\\Last.fm Scrobbler.exe\"; OnlyBelowVersion: 0,6; Tasks: quicklaunchicon\r\n\r\n\r\n[Run]\r\nFilename: \"{app}\\Last.fm Scrobbler.exe\"; Description: \"Start Last.fm Scrobbler now?\"; Flags: nowait postinstall\r\nFilename: \"{app}\\UninsHs.exe\"; Parameters: \"/r0=LastFM,{language},{srcexe},{app}\\Installer.exe\"; Flags: runminimized runhidden nowait\r\n\r\n[InstallDelete]\r\n;All the files that are not in fixed components (so the Radio compontent is actually removed on modify)\r\nType: Files; Name: \"{app}\\libFLAC_dynamic.dll\"\r\nType: Files; Name: \"{app}\\libogg.dll\"\r\nType: Files; Name: \"{app}\\libvorbis.dll\"\r\nType: Files; Name: \"{app}\\libvorbisfile.dll\"\r\n\r\nType: Files; Name: \"{app}\\WinSparkle.dll\"\r\n\r\nType: Files; Name: \"{app}\\avutil-51.dll\";\r\nType: Files; Name: \"{app}\\Last.fm.exe\"\r\nType: Files; Name: \"{app}\\Last.fm Scrobbler.exe\"\r\nType: Files; Name: \"{app}\\phonon4.dll\"\r\nType: Files; Name: \"{app}\\phonon.dll\"\r\nType: Files; Name: \"{app}\\Last.fm.css\"\r\nType: filesandordirs; Name: \"{app}\\phonon_backend\"\r\nType: filesandordirs; Name: \"{app}\\sqldrivers\"\r\nType: dirifempty; Name: \"{app}\\imageformats\"\r\nType: dirifempty; Name: \"{app}\\phonon_backend\"\r\nType: dirifempty; Name: \"{app}\\sqldrivers\"\r\nType: filesandordirs; Name: \"{app}\\plugins\"\r\n\r\n;Visual Studio 2008 redistributable packages\r\nType: Files; Name: \"{app}\\msvcp90.dll\"\r\nType: Files; Name: \"{app}\\msvcm90.dll\"\r\nType: Files; Name: \"{app}\\Microsoft.VC90.CRT.manifest\"\r\nType: Files; Name: \"{app}\\Microsoft.VC90.ATL.manifest\"\r\nType: Files; Name: \"{app}\\atl90.dll\"\r\n\r\nType: Files; Name: \"{app}\\Last.fm.css\"\r\nType: Files; Name: \"{app}\\Last.fm Scrobbler.css\"\r\nType: Files; Name: \"{commondesktop}\\Last.fm\"\r\nType: Files; Name: \"{commondesktop}\\Last.fm.lnk\"\r\nType: Files; Name: \"{commondesktop}\\Last.fm Scrobbler\"\r\nType: Files; Name: \"{commondesktop}\\Last.fm Scrobbler.lnk\"\r\nType: Files; Name: \"{userappdata}\\Microsoft\\Internet Explorer\\Quick Launch\\Last.fm\"\r\nType: Files; Name: \"{userappdata}\\Microsoft\\Internet Explorer\\Quick Launch\\Last.fm Scrobbler\"\r\nType: Files; Name: \"{userappdata}\\Microsoft\\Internet Explorer\\Quick Launch\\Last.fm.lnk\"\r\nType: Files; Name: \"{userappdata}\\Microsoft\\Internet Explorer\\Quick Launch\\Last.fm Scrobbler.lnk\"\r\nType: filesandordirs; Name: \"{group}\"\r\n\r\n;Files from the olde app\r\nType: Files; Name: \"{app}\\Cleaner.exe\"\r\nType: Files; Name: \"{app}\\CrashReporter.exe\"\r\nType: Files; Name: \"{app}\\killer.exe\"\r\nType: Files; Name: \"{app}\\LastFM.exe\"\r\nType: Files; Name: \"{app}\\LastFM.exe.config\"\r\nType: Files; Name: \"{app}\\Updater.exe\"\r\nType: Files; Name: \"{app}\\ChangeLog.txt\"\r\nType: Files; Name: \"{app}\\Moose1.dll\"\r\nType: Files; Name: \"{app}\\LastFmFingerprint1.dll\"\r\nType: Files; Name: \"{app}\\LastFmTools1.dll\"\r\nType: Files; Name: \"{app}\\breakpad.dll\"\r\nType: Files; Name: \"{app}\\srv_httpinput.dll\"\r\nType: Files; Name: \"{app}\\srv_madtranscode.dll\"\r\nType: Files; Name: \"{app}\\srv_rtaudioplayback.dll\"\r\nType: Files; Name: \"{app}\\unins000.dat\"\r\nType: Files; Name: \"{app}\\unins000.exe\"\r\nType: Files; Name: \"{app}\\zlibwapi.dll\"\r\nType: Files; Name: \"{app}\\VistaLib32.dll\"\r\nType: Files; Name: \"{app}\\VistaLib64.dll\"\r\nType: filesandordirs; Name: \"{app}\\data\"\r\nType: filesandordirs; Name: \"{app}\\imageformats\"\r\nType: filesandordirs; Name: \"{app}\\Microsoft.VC80.CRT\"\r\n\r\n; This is the LAST step of uninstallation\r\n[UninstallDelete]\r\n;remove folders, if they are empty\r\nType: files; Name: \"{app}\\Installer.exe\"\r\nType: dirifempty; Name: \"{app}\"\r\n\r\nType: filesandordirs; Name: \"{localappdata}\\Last.fm\"\r\n\r\n; This should be possible to delete as we're waiting until all the plugin uninstallers have been run.\r\nType: files; Name: \"{commonappdata}\\Last.fm\\Client\\uninst.bat\"\r\nType: files; Name: \"{commonappdata}\\Last.fm\\Client\\uninst2.bat\"\r\nType: filesandordirs; Name: \"{commonappdata}\\Last.fm\\Client\"\r\nType: dirifempty; Name: \"{commonappdata}\\Last.fm\"\r\n\r\n\r\n; This is the FIRST step of uninstallation\r\n[UninstallRun]\r\nFilename: \"{app}\\Last.fm.exe\"; Parameters: \"--exit\"; Flags: skipifdoesntexist\r\nFilename: \"{app}\\Last.fm Scrobbler.exe\"; Parameters: \"--exit\"; Flags: skipifdoesntexist\r\n\r\n[Code]\r\n// Global variables\r\nvar g_firstRun: Boolean;\r\n\r\n// This must be called before the install and its value stored\r\nfunction IsUpgrade(): Boolean;\r\nvar\r\n  sPrevPath: String;\r\nbegin\r\n  sPrevPath := '';\r\n  if not RegQueryStringValue(HKLM, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\LastFM_is1', 'UninstallString', sPrevpath) then\r\n    RegQueryStringValue(HKCU, 'Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\LastFM_is1', 'UninstallString', sPrevpath);\r\n  Result := (sPrevPath <> '');\r\nend;\r\n\r\nfunction ShouldSkipPage(PageID: Integer): Boolean;\r\nbegin\r\n  if PageID = wpFinished then\r\n  begin\r\n    // We skip the final screen if it's first run and go straight into config wizard\r\n    if g_firstRun then\r\n      Result := TRUE\r\n  end;\r\n  \r\n  // This skip page code is for add/modify/remove\r\n  if Pos('/SP-', UpperCase(GetCmdTail)) > 0 then\r\n    case PageID of\r\n      wpLicense, wpPassword, wpInfoBefore, wpUserInfo,\r\n      wpSelectDir, wpSelectProgramGroup, wpInfoAfter:\r\n        Result := True;\r\n  end;\r\nend;\r\n\r\n\r\nprocedure ExitApp(FileName: String);\r\nvar\r\n  processExitCode: Integer;\r\nbegin\r\n  if ExecAsOriginalUser( ExpandConstant(FileName), '--exit', '', SW_SHOW, ewWaitUntilTerminated, processExitCode) then\r\n  begin\r\n    // *high five*\r\n  end\r\n  else begin\r\n    //MsgBox( 'Failed to stop ' + ExpandConstant(FileName), mbInformation, MB_OK );\r\n  end;\r\nend;\r\n\r\n\r\nprocedure CurStepChanged(CurStep: TSetupStep);\r\nbegin\r\n  if CurStep = ssInstall then\r\n    begin\r\n      ExitApp( '{app}\\Last.fm.exe' );\r\n      ExitApp( '{app}\\Last.fm Scrobbler.exe' );\r\n    end;\r\nend;\r\n\r\nfunction InitializeSetup(): Boolean;\r\nbegin\r\n  // Need to evaluate and store this before any installation has been done\r\n  g_firstRun := not IsUpgrade();\r\n\r\n  // Run setup\r\n  Result := TRUE;\r\nend;\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "admin/dist/win/build-release-win.pl",
    "content": "#!/usr/bin/perl\r\n#\r\n# brief: This script builds a release build from scratch and packages it\r\n#        into an installer. You need %QTDIR% and %VSDIR% set in your environment\r\n#\r\n#        Must be run from trunk.\r\n#\r\n# pre-requisites: perl, svn, tar, bzip2, \r\n#                 Inno Setup 5 (install to default location or set %ISDIR%)\r\n#\r\n\r\nuse File::Path;\r\nuse File::Copy;\r\nuse File::Find;\r\n\r\n\r\n########################################################################\r\n\r\n# copy the input file to a temp location and use that instead\r\ncopy('Last.fm.iss', 'Last.fm.tmp.iss') or die;\r\nmy $ISSFILE = 'Last.fm.tmp.iss';\r\n\r\nmy $QTDIR = quotemeta( $ENV{'QTDIR'} or die $! );\r\nmy $VSDIR = quotemeta( $ENV{'VSDIR'} or die $! );\r\n#$QTDIR =~ s/\\\\/\\\\\\\\/g; #double escape \\s for the shell :(\r\n#$VSDIR =~ s/\\\\/\\\\\\\\/g;\r\n\r\n########################################################################\r\nheader( \"Building release and installer for Last.fm-$VERSION\" );\r\n\r\n########################################################################\r\n\r\nheader( \"Substituting strings in various files\" );\r\n    #sub findVersionFiles()\r\n    #{\r\n    #    if ($_ =~ /\\.rc$/i || $_ =~ /\\.manifest$/i || $_ =~ /\\.iss$/i)\r\n    #    {\r\n    #        push( @versionFiles, $File::Find::name );\r\n    #    }\r\n    #}\r\n\t#find( \\&findVersionFiles, \".\" );\r\n\t\r\n\tpush( @versionFiles, $ISSFILE );\r\n\r\n    system( 'perl -pi\".bak\" -e \"s/\\%QTDIR\\%/' . $QTDIR . '/g\" ' . $ISSFILE );\r\n    system( 'perl -pi\".bak\" -e \"s/\\%VSDIR\\%/' . $VSDIR . '/g\" ' . $ISSFILE );\r\n\r\nheader( \"Translations\" );\r\n    system( \"lrelease  -removeidentical ../../../Last.fm.pro\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_de.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_en.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_es.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_fr.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_it.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_ja.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_pl.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_pt.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_ru.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_sv.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_tr.ts\" );\r\n    system( \"lrelease  -removeidentical ../../../i18n/lastfm_zh_CN.ts\" );\r\n\r\n\r\nheader( \"Installer\" );\r\n    #my $ISDIR = $ENV{'ISDIR'} or \"c:\\\\Program Files\\\\Inno Setup 5\";\r\n    #$ISDIR =~ s/\\\\/\\//g;\r\n    #run( \"$ISDIR\\\\iscc.exe\", \"$ISSFILE\" ) or die $!;\r\n\t\r\n\tmy $output = qx/\"c:\\/Program Files (x86)\\/Inno Setup 5\\/iscc.exe\" $ISSFILE/  or die $!;\r\n\tprint $output;\r\n\tmy @lines = split(/\\n/, $output);\r\n\tmy $installer = @lines[-1..-1];\r\n\tprint $installer;\r\n\r\n#header( \"Building symbolstore\" );\r\n#    dumpSyms( \"bin\" );\r\n#    dumpSyms( \"$ENV{QTDIR}/lib\" );\r\n#    chdir( \"build/syms\" );\r\n#    run( \"tar\", \"cjf\", \"../../dist/Last.fm-$VERSION-win.symbols.tar.bz2\", \".\" );\r\n\r\nheader( \"Signing\" );\r\n\tsystem( 'signtool sign /a /d \"Last.fm Scrobbler\" /du http://www.last.fm/download ' . $installer );\r\n\r\n\t\r\nheader( \"done!\" );\r\n    print \"To upload the symbols, issue the following command:\\n\";\r\n    print \"       perl dist\\\\build-release-win.pl --upload\";\r\n\r\n\r\n\r\n########################################################################\r\nsub header\r\n{\r\n    print \"\\n==> $_[0]\\n\";\r\n}\r\n\r\nsub run\r\n{\r\n    return system( @_ ) == 0;\r\n}\r\n########################################################################\r\n"
  },
  {
    "path": "admin/dist/win/isspp",
    "content": "use File::Copy;\n\nopen FILE, '_build/build_parameters.pl.h' or die $!;\nwhile ($line = <FILE>) {\n    $str .= $line;\n}\neval $str;\nclose FILE;\n\n\n$root_dir = `cygpath -m '$ROOT_DIR'`;\n$qt_dir   = `cygpath -m '$QMAKE_LIBDIR_QT\\\\..'`;\n\n\ncopy( $ARGV[0], $ARGV[1] ) or die $!;\nopen FILE, $ARGV[1] or die $!;\nwhile (<>) {\n    s/@VERSION@/$VERSION-$REVISION/g;\n    s/@SHORT_VERSION@/$VERSION/g;\n    s/@ROOT_DIR@/$ROOT_DIR/g;\n    s/@QT_DIR@/$qt_dir/g;\n    s/@BIN_DIR@/$root_dir\\\\_bin/g;\n}\nclose FILE;\n"
  },
  {
    "path": "admin/dist/win/wix/boffin.wxs",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\n  <Product\n\t\tId=\"C57A8E40-FE11-480c-9C61-22E325FDAD45\"\n\t\tName=\"Boffin\" Language=\"1033\" Version=\"0.0.7.0\" Manufacturer=\"Last.fm\" \n\t\tUpgradeCode=\"835A5BD7-58E3-40a5-959C-1FB316053472\">\n    \n\t\t<Package \n        Description=\"Boffin\" \n        Manufacturer=\"Last.fm Ltd.\" \n        InstallerVersion=\"300\"\n        Compressed=\"yes\" />\n\n    <Upgrade Id=\"835A5BD7-58E3-40a5-959C-1FB316053472\" />\n\n    <Media Id=\"1\" Cabinet=\"media1.cab\" EmbedCab=\"yes\" />\n\n    <Property Id=\"WIXUI_INSTALLDIR\" Value=\"INSTALLDIR\" />\n    <UIRef Id=\"WixUI_InstallDir\" />\n    <UIRef Id=\"WixUI_ErrorProgressText\" />\n\n    <WixVariable Id=\"WixUILicenseRtf\" Value=\"eula.rtf\" />\n\n    <Directory Id=\"TARGETDIR\" Name=\"SourceDir\">\n\n      <!-- start menu items -->\n      <Directory Id=\"ProgramMenuFolder\">\n        <Directory Id=\"boffinMenuFolder\" Name=\"Last.fm Boffin\">\n          \n          <Component Id=\"boffinShortcutComponent\" Guid=\"AA45A306-B9DC-4ca4-8F0B-95FB5F41AF86\">\n            <RegistryKey Root=\"HKCU\" Key=\"Software\\Last.fm\\Boffin\\shortcut\">\n              <RegistryValue Value=\"\" Type=\"string\" KeyPath=\"yes\"/>\n            </RegistryKey>\n            <Shortcut Id=\"launchBoffin\"\n                      Name=\"Boffin\"\n                      Target=\"[INSTALLDIR]boffin.exe\"\n                      Arguments=\"/x C57A8E40-FE11-480c-9C61-22E325FDAD45\"\n                      Directory=\"boffinMenuFolder\"\n                      Description=\"Starts Boffin\" />\n            <RemoveFolder Id=\"removeShortcutFolder\" On=\"uninstall\" />\n          </Component>\n          \n          <Component Id=\"uninstallShortcutComponent\" Guid=\"4A724AFE-7C2E-4258-BF90-F13DEB95B5C9\">\n            <RegistryKey Root=\"HKCU\" Key=\"Software\\Last.fm\\Boffin\\uninstall\">\n              <RegistryValue Value=\"\" Type=\"string\" KeyPath=\"yes\"/>\n            </RegistryKey>\n            <Shortcut Id=\"uninstallBoffin\"\n                      Name=\"Uninstall Boffin\"\n                      Target=\"[System64Folder]msiexec.exe\"\n                      Arguments=\"/x {C57A8E40-FE11-480c-9C61-22E325FDAD45}\"\n                      Directory=\"boffinMenuFolder\"\n                      Description=\"Uninstalls Boffin\" />\n          </Component>\n          \n        </Directory>\n      </Directory>\n\n      <!-- program files items -->\n      <Directory Id=\"ProgramFilesFolder\">\n\t\t\t\t<Directory Id=\"INSTALLDIR\" Name=\"Boffin\">\n\t\t\t\t\t<Component Id=\"MainBit\" Guid=\"56F99AE3-1859-4677-B4D8-F4A173FD12D8\">\n            <File Id=\"boffinexe\" Name=\"boffin.exe\" Source=\"boffin.exe\" />\n<!--            <File Id=\"boffinexemanifest\" Name=\"boffin.exe.manifest\" Source=\"boffin.exe.manifest\" /> -->\n            <File Id=\"qtconf\" Name=\"qt.conf\" Source=\"qt.conf\" />\n            <File Id=\"coredll\" Name=\"core.dll\" Source=\"core.dll\" />\n            <File Id=\"radiodll\" Name=\"radio.dll\" Source=\"radio.dll\" />\n            <File Id=\"sqlite3dll\" Name=\"sqlite3.dll\" Source=\"sqlite3.dll\" />\n            <File Id=\"tagdll\" Name=\"tag.dll\" Source=\"tag.dll\" />\n            <File Id=\"typesdll\" Name=\"types.dll\" Source=\"types.dll\" />\n            <File Id=\"unicorndll\" Name=\"unicorn.dll\" Source=\"unicorn.dll\" />\n            <File Id=\"wsdll\" Name=\"ws.dll\" Source=\"ws.dll\" />\n\n            <RegistryKey Root=\"HKLM\" Key=\"Software\">\n              <RegistryKey Key=\"Last.fm\" Action=\"create\">\n                <RegistryValue Key=\"Boffin\" Name=\"Path\" Action=\"write\" Type=\"string\" Value=\"[INSTALLDIR]boffin.exe\" />\n              </RegistryKey>\n            </RegistryKey>\n\n            <!-- register association and icon for .xspf -->\n<!--\t\t\t\n            <ProgId Id=\"Boffin.xspf\" Description=\"XML Shareable Playlist Format\">\n              <Extension Id=\"xspf\" ContentType=\"application/xspf+xml\">\n                <Verb Id='open' Command='Open' TargetFile='boffinexe' Argument='\"%1\"' />\n              </Extension>\n            </ProgId>\n            <RegistryValue Id='icon' Root=\"HKCR\" Key='Boffin.xspf\\DefaultIcon' Action='write' Type='string' Value='[INSTALLDIR]boffin.exe,0' />\n-->\n          </Component>\n\n          <Component Id=\"Qt4\" Guid=\"0A0987A0-8CB1-491d-A074-2A8005DA326A\">\n<!--            <File Id=\"qtwebkit4dll\" Name=\"qtwebkit4.dll\" Source=\"qtwebkit4.dll\" DefaultLanguage=\"0\" /> -->\n<!--            <File Id=\"qtsvg4dll\" Name=\"qtsvg4.dll\" Source=\"qtsvg4.dll\" DefaultLanguage=\"0\" /> -->\n            <File Id=\"phonon4dll\" Name=\"phonon4.dll\" Source=\"phonon4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtsql4dll\" Name=\"qtsql4.dll\" Source=\"qtsql4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtxml4dll\" Name=\"qtxml4.dll\" Source=\"qtxml4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtgui4dll\" Name=\"qtgui4.dll\" Source=\"qtgui4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtnetwork4dll\" Name=\"qtnetwork4.dll\" Source=\"qtnetwork4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtcore4dll\" Name=\"qtcore4.dll\" Source=\"qtcore4.dll\" DefaultLanguage=\"0\" />\n            <File Id=\"qtopengl4dll\" Name=\"qtopengl4.dll\" Source=\"qtopengl4.dll\" DefaultLanguage=\"0\" />\n          </Component>\n\n          <Directory Id=\"imageformatsDir\" Name=\"imageformats\">\n            <Component Id=\"imageformatsComponent\" Guid=\"52944572-8766-4a99-8207-5F110EA00705\">\n              <File Id=\"qjpeg4dll\" Name=\"qjpeg4.dll\" Source=\"imageformats\\qjpeg4.dll\" />\n              <File Id=\"qgif4dll\" Name=\"qgif4.dll\" Source=\"imageformats\\qgif4.dll\" />\n              <File Id=\"qmng4dll\" Name=\"qmng4.dll\" Source=\"imageformats\\qmng4.dll\" />\n            </Component>\n          </Directory>\n\n          <Directory Id=\"sqldriversDir\" Name=\"sqldrivers\">\n            <Component Id=\"sqldriversComponent\" Guid=\"97429E06-A2EC-489d-8672-79385F85E804\">\n              <File Id=\"qsqlite4dll\" Name=\"qsqlite4.dll\" Source=\"sqldrivers\\qsqlite4.dll\" />\n            </Component>\n          </Directory>\n\n          <Directory Id=\"phononBackendDir\" Name=\"phonon_backend\">\n            <Component Id=\"phononBackendComponent\" Guid=\"9E1C98AB-52E8-4ca6-86A8-FDF6B3C23DE0\">\n              <File Id=\"phonon_ds94dll\" Name=\"phonon_ds94.dll\" Source=\"phonon_backend\\phonon_ds94.dll\" />\n            </Component>\n          </Directory>\n\n          <Merge Id=\"crt1\" Language=\"0\" SourceFile=\"Microsoft_VC80_CRT_x86.msm\" DiskId=\"1\" />\n          <Merge Id=\"crt2\" Language=\"0\" SourceFile=\"policy_8_0_Microsoft_VC80_CRT_x86.msm\" DiskId=\"1\" />\n          \n        </Directory>\n      </Directory>\n    </Directory>\n\n    <!-- clean up: \n    ideally we'd remove ..\\AppData\\Local\\Last.fm for each user,\n    but the msi doesn't provide any mechanism to help us with that -->\n<!--    \n    <Directory Id=\"\" Name=\"AppData\">\n    </Directory>\n-->\n\n    <Feature Id=\"Complete\" Title=\"feature\" Level=\"1\">\n\t\t\t<ComponentRef Id=\"MainBit\" />\n      <ComponentRef Id=\"Qt4\" />\n      <ComponentRef Id=\"imageformatsComponent\" />\n      <ComponentRef Id=\"sqldriversComponent\" />\n      <ComponentRef Id=\"phononBackendComponent\" />\n      <ComponentRef Id=\"boffinShortcutComponent\" />\n      <ComponentRef Id=\"uninstallShortcutComponent\" />\n      <MergeRef Id=\"crt1\" />\n      <MergeRef Id=\"crt2\" />\n    </Feature>\n\n    <InstallExecuteSequence>\n      <Custom Action=\"launchAppAction\" After=\"InstallFinalize\" />\n    </InstallExecuteSequence>\n    <CustomAction Id=\"launchAppAction\" FileKey=\"boffinexe\" ExeCommand=\"\" Return=\"asyncNoWait\" />\n\n  </Product>\n</Wix>\n"
  },
  {
    "path": "admin/dist/win/wix/client.wxs",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\">\r\n\t<Product \r\n    Id=\"AC9C3551-7256-45e3-BDAB-D2BA00A9FB45\" \r\n    Name=\"Last.fm\" \r\n    Language=\"1033\" \r\n    Manufacturer=\"Last.fm\" \r\n    Version=\"2.0.0\" \r\n    UpgradeCode=\"2b30baf0-ec7d-48fd-b5e6-cedf588c53fd\">\r\n    \r\n\t\t<Package \r\n        Description=\"Last.fm\" \r\n        Manufacturer=\"Last.fm Ltd.\" \r\n        InstallerVersion=\"300\"\r\n        Compressed=\"yes\" />\r\n        \r\n        <Upgrade Id=\"2b30baf0-ec7d-48fd-b5e6-cedf588c53fd\">\r\n            <UpgradeVersion \r\n            Minimum=\"1.0.0\"\r\n            IncludeMinimum=\"yes\"\r\n            Maximum=\"2.0.0\"\r\n            Property=\"THISMUSTBEALLCAPS\" />\r\n        </Upgrade>\r\n        \r\n        <Upgrade Id=\"2b30baf0-ec7d-48fd-b5e6-cedf588c53fd\">\r\n            <UpgradeVersion \r\n            Minimum=\"1.0.0\"\r\n            OnlyDetect=\"yes\"\r\n            Property=\"NEWERVERSIONDETECTED\" />\r\n        </Upgrade>\r\n        \r\n        <InstallExecuteSequence>\r\n            <RemoveExistingProducts After=\"InstallInitialize\"/>\r\n        </InstallExecuteSequence>\r\n        \r\n        <Condition Message=\"A later version of [ProductName] is already installed. Kthxbai.\">\r\n            NOT NEWERVERSIONDETECTED OR Installed\r\n        </Condition>\r\n\r\n        <Media Id=\"1\" Cabinet=\"media1.cab\" EmbedCab=\"yes\" />\r\n\r\n        <Property Id=\"WIXUI_INSTALLDIR\" Value=\"INSTALLDIR\" />\r\n        <UIRef Id=\"WixUI_InstallDir\" />\r\n        <UIRef Id=\"WixUI_ErrorProgressText\" />\r\n        <WixVariable Id=\"WixUILicenseRtf\" Value=\"eula.rtf\" />        \r\n        <WixVariable Id=\"WixUIDialogBmp\" Value=\"..\\installer1_icon.bmp\" />\r\n        <WixVariable Id=\"WixUIBannerBmp\" Value=\"..\\installer2_icon.bmp\" />\r\n        \r\n        <Directory Id=\"TARGETDIR\" Name=\"SourceDir\">\r\n        \r\n            <!-- start menu items -->\r\n            <Directory Id=\"ProgramMenuFolder\">\r\n                <Directory Id=\"lastfmMenuFolder\" Name=\"Last.fm v2\">\r\n                    <Component Id=\"lastfmShortcutComponent\" Guid=\"*\">\r\n                        <RegistryKey Root=\"HKCU\" Key=\"Software\\Last.fm\\Last.fm\\shortcut\">\r\n                            <RegistryValue Value=\"\" Type=\"string\" KeyPath=\"yes\"/>\r\n                        </RegistryKey>\r\n                        <Shortcut Id=\"launchLastfmRadio\"\r\n                                  Name=\"Last.fm Radio\"\r\n                                  Target=\"[INSTALLDIR]radio.exe\"\r\n                                  Arguments=\"&quot;-stylesheet=[INSTALLDIR]radio.css&quot;\"\r\n                                  Directory=\"lastfmMenuFolder\" />\r\n                        <Shortcut Id=\"launchAudioscrobbler\"\r\n                                  Name=\"Audioscrobbler\"\r\n                                  Target=\"[INSTALLDIR]audioscrobbler.exe\"\r\n                                  Arguments=\"&quot;-stylesheet=[INSTALLDIR]audioscrobbler.css&quot;\"\r\n                                  Directory=\"lastfmMenuFolder\" />\r\n                        <Shortcut Id=\"uninstallBoffin\"\r\n                                  Name=\"Uninstall Last.fm\"\r\n                                  Target=\"[System64Folder]msiexec.exe\"\r\n                                  Arguments=\"/x {AC9C3551-7256-45e3-BDAB-D2BA00A9FB45}\"\r\n                                  Directory=\"lastfmMenuFolder\"\r\n                                  Description=\"Uninstalls Last.fm\" />\r\n                        <RemoveFolder Id=\"removeShortcutFolder\" On=\"uninstall\" />\r\n                    </Component>\r\n                </Directory>\r\n            </Directory>\r\n        \r\n        \r\n\t\t\t<Directory Id=\"ProgramFilesFolder\">\r\n\t\t\t\t<Directory Id=\"INSTALLDIR\" Name=\"Last.fm v2\">\r\n\t\t\t\t\t<Component Id=\"MainBit\" Guid=\"d8f98724-51fe-4398-96df-2e156b19fc21\">\r\n                        <File Id=\"qtconf\" Name=\"qt.conf\" Source=\"qt.conf\" /> \r\n                        <File Id=\"radioexe\" Name=\"radio.exe\" Source=\"radio.exe\" />\r\n                        <File Id=\"audioscrobblerexe\" Name=\"audioscrobbler.exe\" Source=\"audioscrobbler.exe\" />\r\n                        <File Id=\"twiddlyexe\" Name=\"twiddly.exe\" Source=\"twiddly.exe\" DefaultLanguage=\"0\" />\r\n                        <File Id=\"lastfmdll\" Name=\"lastfm.dll\" Source=\"lastfm.dll\" />\r\n                        <File Id=\"lastfm_fingerprintdll\" Name=\"lastfm_fingerprint.dll\" Source=\"lastfm_fingerprint.dll\" />\r\n                        <File Id=\"libfftw3f3dll\" Name=\"libfftw3f-3.dll\" Source=\"libfftw3f-3.dll\" />\r\n                        <File Id=\"listenerdll\" Name=\"listener.dll\" Source=\"listener.dll\" />\r\n                        <File Id=\"unicorndll\" Name=\"unicorn.dll\" Source=\"unicorn.dll\" />\r\n                        \r\n                        <File Id=\"radiocss\" Name=\"radio.css\" Source=\"app\\radio\\radio.css\" />\r\n                        <File Id=\"audioscrobblercss\" Name=\"audioscrobbler.css\" Source=\"app\\audioscrobbler\\audioscrobbler.css\" />\r\n                        \r\n                        <RegistryKey Root=\"HKLM\" Key=\"Software\">\r\n                            <RegistryKey Key=\"Last.fm\" Action=\"create\">\r\n                                <RegistryValue Key=\"Client\" Name=\"Path\" Action=\"write\" Type=\"string\" Value=\"[INSTALLDIR]radio.exe\" />\r\n                            </RegistryKey>\r\n                        </RegistryKey>\r\n\r\n                    </Component>\r\n\r\n                    <Component Id=\"Qt4\" Guid=\"0A0987A0-8CB1-491d-A074-2A8005DA326A\">\r\n                        <!-- <File Id=\"qtwebkit4dll\" Name=\"qtwebkit4.dll\" Source=\"qtwebkit4.dll\" /> -->\r\n                        <!-- <File Id=\"qtsvg4dll\" Name=\"qtsvg4.dll\" Source=\"qtsvg4.dll\" /> -->\r\n                        <File Id=\"phonon4dll\" Name=\"phonon4.dll\" Source=\"phonon4.dll\" />\r\n                        <!-- <File Id=\"qtsql4dll\" Name=\"qtsql4.dll\" Source=\"qtsql4.dll\" /> -->\r\n                        <File Id=\"qtxml4dll\" Name=\"qtxml4.dll\" Source=\"qtxml4.dll\" />\r\n                        <File Id=\"qtgui4dll\" Name=\"qtgui4.dll\" Source=\"qtgui4.dll\" />\r\n                        <File Id=\"qtnetwork4dll\" Name=\"qtnetwork4.dll\" Source=\"qtnetwork4.dll\" />\r\n                        <File Id=\"qtcore4dll\" Name=\"qtcore4.dll\" Source=\"qtcore4.dll\" />\r\n                        <File Id=\"qtopengl4dll\" Name=\"qtopengl4.dll\" Source=\"qtopengl4.dll\" />\r\n                    </Component>\r\n\r\n                    <Directory Id=\"imageformatsDir\" Name=\"imageformats\">\r\n                        <Component Id=\"imageformatsComponent\" Guid=\"52944572-8766-4a99-8207-5F110EA00705\">\r\n                        <File Id=\"qjpeg4dll\" Name=\"qjpeg4.dll\" Source=\"imageformats\\qjpeg4.dll\" />\r\n                        <File Id=\"qgif4dll\" Name=\"qgif4.dll\" Source=\"imageformats\\qgif4.dll\" />\r\n                        <File Id=\"qmng4dll\" Name=\"qmng4.dll\" Source=\"imageformats\\qmng4.dll\" />\r\n                        </Component>\r\n                    </Directory>\r\n\r\n                    <!-- <Directory Id=\"sqldriversDir\" Name=\"sqldrivers\">\r\n                        <Component Id=\"sqldriversComponent\" Guid=\"97429E06-A2EC-489d-8672-79385F85E804\">\r\n                            <File Id=\"qsqlite4dll\" Name=\"qsqlite4.dll\" Source=\"sqldrivers\\qsqlite4.dll\" />\r\n                        </Component>\r\n                    </Directory> -->\r\n\r\n                    <Directory Id=\"phononBackendDir\" Name=\"phonon_backend\">\r\n                        <Component Id=\"phononBackendComponent\" Guid=\"9E1C98AB-52E8-4ca6-86A8-FDF6B3C23DE0\">\r\n                            <File Id=\"phonon_ds94dll\" Name=\"phonon_ds94.dll\" Source=\"phonon_backend\\phonon_ds94.dll\" />\r\n                        </Component>\r\n                    </Directory>\r\n\r\n                    <Merge Id=\"crt1\" Language=\"0\" SourceFile=\"Microsoft_VC80_CRT_x86.msm\" DiskId=\"1\" />\r\n                    <Merge Id=\"crt2\" Language=\"0\" SourceFile=\"policy_8_0_Microsoft_VC80_CRT_x86.msm\" DiskId=\"1\" />\r\n                    <Merge Id=\"atl1\" Language=\"0\" SourceFile=\"Microsoft_VC80_ATL_x86.msm\" DiskId=\"1\" />\r\n                    <Merge Id=\"atl2\" Language=\"0\" SourceFile=\"policy_8_0_Microsoft_VC80_ATL_x86.msm\" DiskId=\"1\" />\r\n                    \r\n                </Directory>\r\n            </Directory>\r\n        </Directory>\r\n\r\n<!-- clean up: \r\n    ideally we'd remove ..\\AppData\\Local\\Last.fm for each user,\r\n    but thee msi doesn't provide any mechanism to help us with that -->\r\n<!--    \r\n    <Directory Id=\"\" Name=\"AppData\">\r\n    </Directory>\r\n-->\r\n\r\n        <Feature Id=\"Complete\" Title=\"feature\" Level=\"1\">\r\n            <ComponentRef Id=\"MainBit\" />\r\n            <ComponentRef Id=\"Qt4\" />\r\n            <ComponentRef Id=\"imageformatsComponent\" />\r\n            <!-- <ComponentRef Id=\"sqldriversComponent\" /> -->\r\n            <ComponentRef Id=\"phononBackendComponent\" />\r\n            <ComponentRef Id=\"lastfmShortcutComponent\" />\r\n            <MergeRef Id=\"crt1\" />\r\n            <MergeRef Id=\"crt2\" />\r\n            <MergeRef Id=\"atl1\" />\r\n            <MergeRef Id=\"atl2\" />\r\n        </Feature>\r\n        \r\n\t</Product>\r\n</Wix>\r\n"
  },
  {
    "path": "admin/dist/win/wix/qt.conf",
    "content": ""
  },
  {
    "path": "admin/dist/win/wix/wixboff.cmd",
    "content": "rem @echo off\nrem Requires Wix 3.0.x\nrem Run with current directory same as .cmd location\n\nrem set VCREDISTDIR=C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\BootStrapper\\Packages\\vcredist_x86\\\nset VCREDISTDIR=C:\\Program Files\\Common Files\\Merge Modules\\\n\necho WIX = %WIX%\necho QTDIR = %QTDIR%\necho VCREDISTDIR = %VCREDISTDIR%\n\n\"%WIX%\"\\bin\\candle boffin.wxs\nif ERRORLEVEL 1 goto ERROR\n\n\"%WIX%\"\\bin\\light -ext WixUIExtension boffin.wixobj -b ..\\..\\..\\..\\_bin\\ -b %QTDIR%\\bin -b %QTDIR%\\plugins -b \"%VCREDISTDIR%\\\"\nif ERRORLEVEL 1 goto ERROR\n\ngoto END\n\n:ERROR\necho \"***Fail\"\n\n:END"
  },
  {
    "path": "admin/dist/win/wix/wixclient.cmd",
    "content": "@echo off\r\nrem Requires Wix 3.0.x\r\nrem Run with current directory same as .cmd location\r\n\r\nrem set VCREDISTDIR=C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\BootStrapper\\Packages\\vcredist_x86\\\r\nset VCREDISTDIR=C:\\Program Files\\Common Files\\Merge Modules\\\r\n\r\necho WIX = %WIX%\r\necho QTDIR = %QTDIR%\r\necho VCREDISTDIR = %VCREDISTDIR%\r\n\r\n\"%WIX%\"\\bin\\candle client.wxs\r\nif ERRORLEVEL 1 goto ERROR\r\n\r\n\"%WIX%\"\\bin\\light -ext WixUIExtension client.wixobj -b ..\\..\\..\\..\\ -b ..\\..\\..\\..\\_bin\\ -b %QTDIR%\\bin -b %QTDIR%\\plugins -b \"%VCREDISTDIR%\\\"\r\nif ERRORLEVEL 1 goto ERROR\r\n\r\ngoto END\r\n\r\n:ERROR\r\necho \"***Fail\"\r\n\r\n:END\r\n"
  },
  {
    "path": "admin/include.qmake",
    "content": "\nROOT_DIR = $$PWD/..\n\nmacx-xcode {\n    BUILD_DIR = _build\n} else {\n    # With Xcode we generate a bundle\n    BUILD_DIR = _build\n    DESTDIR = $$ROOT_DIR/_bin\n    LIBS += -L$$DESTDIR\n}\nOBJECTS_DIR = $$BUILD_DIR\nMOC_DIR = $$BUILD_DIR\nUI_DIR = $$BUILD_DIR\nRCC_DIR = $$BUILD_DIR\nINCLUDEPATH = $$ROOT_DIR\n\nwin32:DEFINES += _CRT_SECURE_NO_WARNINGS WIN32_LEAN_AND_MEAN\n\nunix:!mac:QMAKE_CXXFLAGS += -fno-operator-names\n\nmacx* {\n    QMAKE_PKGINFO_TYPEINFO = last\n    QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.6\n}\n\ninclude( qmake/debug.pro.inc )\ninclude( qmake/QtOverride.pro.inc )\ninclude( qmake/3rdparty.pro.inc )\ninclude( qmake/1stparty.pro.inc )\n\nunix:!mac {\n\tCONFIG += link_pkgconfig\n\t# use KDE phonon if installed in preference\n\tcontains( QT, phonon ):LIBS += -L$$system( kde4-config --prefix 2> /dev/null )/lib\n\n    isEmpty(PREFIX) {\n        PREFIX = /usr/local\n    }\n    DEFINES += PREFIX=\\\\\\\"$$PREFIX\\\\\\\"\n    BINDIR = $$PREFIX/bin\n    DATADIR = $$PREFIX/share\n}\n\n#default install target\ntarget.path = $$INSTALL_DIR/lib\n\nCONFIG += silent\n\nmacx:CONFIG( app_bundle ): contains( TEMPLATE, app ) {\n    DISTDIR = $$ROOT_DIR/admin/dist/mac\n    BUNDLE_DIR = $$DESTDIR/$$TARGET$$quote(.app)\n    \n    ## copy any css file if it exists\n    CSS_PATH=$$_PRO_FILE_PWD_/$$TARGET$$quote(.css)\n    exists( $$CSS_PATH ) {\n        # if we are in debug mode just symlink it so that we can edit in place and refresh the stylesheet\n        CONFIG( debug, debug|release ) {\n            QMAKE_POST_LINK += echo Symlinking css file..; \\\n                                rm \\\"$$BUNDLE_DIR/Contents/Resources/$$TARGET$$quote(.css)\\\"; \\\n                                ln -s \\\"$$CSS_PATH\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n        } else {\n            QMAKE_POST_LINK += echo Copying css file..; \\\n                                rm \\\"$$BUNDLE_DIR/Contents/Resources/$$TARGET$$quote(.css)\\\"; \\\n                                cp -f \\\"$$CSS_PATH\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n        }\n    }\n\n    QMAKE_POST_LINK += echo Symlink olde exe to new; \\\n                        rm \\\"$${DESTDIR}/$${TARGET}.app/Contents/MacOS/Last.fm\\\"; \\\n                        ln -s \\\"$${TARGET}\\\" \\\"$${DESTDIR}/$${TARGET}.app/Contents/MacOS/Last.fm\\\";\n\n    QMAKE_POST_LINK += echo Symlink olde .icns to new; rm \\\"$$BUNDLE_DIR/Contents/Resources/lastfm.icns\\\"; \\\n                        ln -s \\\"audioscrobbler.icns\\\" \\\"$$BUNDLE_DIR/Contents/Resources/lastfm.icns\\\";\n\n    QMAKE_POST_LINK += echo Breakpad dump sys \\\"$${DESTDIR}/$${TARGET}.app/Contents/MacOS/$${TARGET}\\\".; \\\n                        \\\"$$ROOT_DIR/admin/dist/mac/dump_syms\\\" -a x86_64 \\\"$${DESTDIR}/$${TARGET}.app/Contents/MacOS/$${TARGET}\\\" > \\\"$${TARGET} x86_64.breakpad\\\";\n\n    ## copy the public key for updates\n    QMAKE_POST_LINK += echo Copying dsa_pub.pem file..; \\\n                        cp \\\"$$ROOT_DIR/admin/dist/mac/dsa_pub.pem\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n    \n    ## copy the growl registration file\n    QMAKE_POST_LINK += echo Copying growl registration file..; \\\n                        cp \\\"$$ROOT_DIR/admin/dist/mac/Growl Registration Ticket.growlRegDict\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n\n    ## copy the apple script suite definition\n    QMAKE_POST_LINK += echo Copying apple script suite definition file..; \\\n                        cp \\\"$$ROOT_DIR/admin/dist/mac/AppleScriptSuite.sdef\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n\n    QMAKE_POST_LINK += echo Copying airfoil remote file..; \\\n                        cp \\\"$$ROOT_DIR/admin/dist/mac/dacp.fm.last.Scrobbler.scpt\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n    QMAKE_POST_LINK += echo Copying airfoil tracks file..; \\\n                        cp \\\"$$ROOT_DIR/admin/dist/mac/fm.last.Scrobbler.scpt\\\" \\\"$$BUNDLE_DIR/Contents/Resources\\\";\n\n    ## add the translations\n    QMAKE_POST_LINK += mkdir -p \\\"$${BUNDLE_DIR}/Contents/Resources/qm/\\\"; \\\n                        mv -f \\\"$${ROOT_DIR}/i18n/\\\"*.qm \\\"$${BUNDLE_DIR}/Contents/Resources/qm/\\\";\n\n    ## install_name_tool / copy frameworks, dylibs etc\n    QMAKE_POST_LINK += $$DISTDIR/bundleFrameworks.sh \\'$$BUNDLE_DIR\\';\n\n    QMAKE_POST_LINK += find \\'$$BUNDLE_DIR\\' -iname \\\\*Headers -print0| xargs -0 rm -rf; \\\n                        find \\'$$BUNDLE_DIR\\' -iname \\\\*_debug -print0|xargs -0 rm\n    \n    QMAKE_INFO_PLIST = $$DISTDIR/Standard.plist\n}\n\ndefineTest( generateBuildParameters ) {\n\tsystem( echo \\'$DESTDIR = \\\"$$DESTDIR\\\";\\' > _build_parameters.pl.h )\n\tsystem( echo \\'$VERSION = \\\"$$VERSION\\\";\\' >> _build_parameters.pl.h )\n\tsystem( echo \\'$QT_FRAMEWORKS_DIR = \\\"$$QMAKE_LIBDIR_QT\\\";\\' >> _build_parameters.pl.h )\n\tsystem( echo \\'$QMAKE_LIBDIR_QT = \\\"$$QMAKE_LIBDIR_QT\\\";\\' >> _build_parameters.pl.h )\n\tsystem( echo \\'$ROOT_DIR = \\\"$$ROOT_DIR\\\";\\' >> _build_parameters.pl.h )\n\tsystem( echo \\'$QT = \\\"$$QT\\\";\\' >> _build_parameters.pl.h )\n\tsystem( echo \\'$REVISION = \\\"\\'`svn info | grep \\\"Last Changed Rev\\\" | cut -d\\' \\' -f4`\\'\\\";\\' >> _build_parameters.pl.h )\n}\n"
  },
  {
    "path": "admin/qmake/1stparty.pro.inc",
    "content": "CONFIG( unicorn ) {\n    LIBS += -lunicorn\n    QT += gui\n    CONFIG += lastfm\n}\nCONFIG( listener ) {\n    LIBS += -llistener\n    CONFIG += lastfm\n}\nCONFIG( fingerprint ) {\n    LIBS += -llastfm_fingerprint\n    CONFIG += lastfm\n}\nCONFIG( logger ) {\n    LIBS += -llogger\n    CONFIG += lastfm\n}\nCONFIG( lastfm ) {\n    QT += core network xml\n    LIBS += -llastfm\n    win32 {\n        CONFIG += link_pkgconfig\n\n        CONFIG(debug, debug|release) {\n            PKGCONFIG += lastfm-debug\n        }\n        else {\n            PKGCONFIG += lastfm-release\n        }\n\n    }\n    mac{\n        CONFIG( notifications ) {\n            MAC_SDK  = $$system(xcode-select --print-path)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk\n\n            if( !exists( $$MAC_SDK) ) {\n                message(\"You do not have the MacOSX10.8 SDK installed. User Notifications will not be built.\")\n            }\n            else {\n                macx:QMAKE_MAC_SDK = $$MAC_SDK\n                DEFINES += LASTFM_USER_NOTIFICATIONS\n            }\n        }\n\n        LIBS += -weak_framework Carbon -weak_framework CoreFoundation -weak_framework Foundation\n    }\n}\n"
  },
  {
    "path": "admin/qmake/3rdparty.pro.inc",
    "content": "mac {\n    LIBS += -L/usr/local/lib\n    INCLUDEPATH += /usr/local/include\n}\n\nCONFIG( taglib ) {\n    CONFIG += link_pkgconfig\n    PKGCONFIG += taglib\n    win32:debug:LIBS += tagd.lib    # tagd.lib will precede PKGCONFIG added libs\n}\n\nCONFIG( ffmpeg ) {\n    mac {\n        LIBS += /usr/local/lib/libavcodec.dylib\n        LIBS += /usr/local/lib/libavformat.dylib\n        LIBS += /usr/local/lib/libavutil.dylib\n        LIBS += /usr/local/lib/libswresample.dylib\n        DEFINES += HAVE_SWRESAMPLE\n    } else {\n        CONFIG += link_pkgconfig\n        PKGCONFIG += libavformat libavcodec libavutil\n        packagesExist(libswresample) {\n            PKGCONFIG += libswresample\n            DEFINES += HAVE_SWRESAMPLE\n        }\n        packagesExist(libavresample) {\n            PKGCONFIG += libavresample\n            DEFINES += HAVE_AVRESAMPLE\n        }\n    }\n}\n\nCONFIG( analytics ) {\n    QT += webkit\n    DEFINES += LASTFM_ANALYTICS\n}\n\nCONFIG( boost ) {\n    mac:CONFIG(app_bundle){\n        LIBS += /usr/local/lib/libboost_thread-mt.a\n    }\n    else:unix {\n        LIBS += -lboost_thread-mt\n    }\n}\n\nCONFIG( break ) {\n    win32{\n        CONFIG += link_pkgconfig\n        PKGCONFIG += breakpad\n        LIBS += wininet.lib\n    }\n    else:mac{\n        LIBS += -framework Breakpad\n    }\n}\n\nCONFIG( growl ) {\n    mac {\n        INCLUDEPATH += -F/Library/Frameworks\n        LIBS += -F/Library/Frameworks -framework Growl\n    }\n}\n\nCONFIG( sparkle ) {\n    win32{\n        CONFIG += link_pkgconfig\n\n        CONFIG(debug, debug|release) {\n            PKGCONFIG += qtsparkle-debug\n        }\n        else {\n            PKGCONFIG += qtsparkle-release\n        }\n    }\n    else:mac{\n        INCLUDEPATH += -F/Library/Frameworks\n        LIBS += -F/Library/Frameworks -framework Sparkle -Wl -rpath @loader_path/../Frameworks\n    }\n}\n\nCONFIG( sqlite3 ) {\n    win32 {\n        CONFIG += link_pkgconfig\n        PKGCONFIG += sqlite3\n    }\n    else:LIBS += -lsqlite3\n}\n\nCONFIG( yajl ) {\n\twin32 {\n\t\tCONFIG += link_pkgconfig\n\t\tdebug:PKGCONFIG += yajl-debug\n\t\trelease:PKGCONFIG += yajl-release\n\t}\n\telse:CONFIG(app_bundle) {\n                LIBS += /usr/local/lib/libyajl_s.a\n\t}\n\telse:LIBS += -lyajl\n}\n\n"
  },
  {
    "path": "admin/qmake/QtOverride.pro.inc",
    "content": "!CONFIG( no_override ) {\n    win32:QMAKE_INCDIR_QT = $$ROOT_DIR/common/qt/override $$QMAKE_INCDIR_QT\n    else:!macx-xcode::QMAKE_CXX = $$QMAKE_CXX -I$$ROOT_DIR/common/qt/override\n}\n"
  },
  {
    "path": "admin/qmake/debug.pro.inc",
    "content": "CONFIG( debug, debug|release ) {\n    mac* {\n        #speeds up debug builds by only compiling x86\n        CONFIG -= ppc\n    }\n\n    unix:!mac {\n        QMAKE_CXXFLAGS_DEBUG = -ggdb\n    }\n\n    VERSION_UPDATE_PATTERN = *.*.*.*\n}\nelse {\n    CONFIG += warn_off\n    DEFINES += NDEBUG\n    #macx*:CONFIG += ppc x86\n}\n"
  },
  {
    "path": "admin/tests/QtTest_to_JUnit.xslt",
    "content": "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n\n<xsl:output method=\"xml\" indent=\"yes\" />\n<xsl:decimal-format decimal-separator=\".\" grouping-separator=\",\" />\n\n<!-- misc variables -->\n<xsl:variable name=\"classname\" select=\"/TestCase/@name\" />\n<xsl:variable name=\"total-tests\" select=\"count(/TestCase/TestFunction)\" />\n<xsl:variable name=\"total-failures\" select=\"count(/TestCase/TestFunction/Incident[@type='fail'])\" />\n\n<!-- main template call -->\n<xsl:template match=\"/\">\n    <xsl:apply-templates select=\"TestCase\"/>\n</xsl:template>\n\n<xsl:template match=\"TestCase\">\n        <testsuite name=\"{$classname}\" tests=\"{$total-tests}\" failures=\"{$total-failures}\" errors=\"0\" time=\"0.0\">\n        <xsl:apply-templates select=\"Environment\"/>\n        <xsl:apply-templates select=\"TestFunction\" />\n                <xsl:call-template name=\"display-system-out\" />\n                <xsl:call-template name=\"display-system-err\" />\n    </testsuite>\n</xsl:template>\n\n<xsl:template match=\"Environment\">\n    <properties>\n        <xsl:for-each select=\"*\">\n            <property name=\"{name()}\" value=\"{text()}\" />\n        </xsl:for-each>\n    </properties>\n</xsl:template>\n\n<xsl:template match=\"TestFunction\">\n            <!-- TODO: set time-parameter properly -->\n    <testcase classname=\"{$classname}\" name=\"{@name}\" time=\"0.0\">\n        <!-- handle fail -->\n        <xsl:if test=\"Incident/@type = 'fail' or Incident/@type = 'xpass'\">\n                        <!-- will be used to generate \"nice\" error message -->\n                        <xsl:variable name=\"file\" select=\"Incident/@file\" />\n                        <xsl:variable name=\"line\" select=\"Incident/@line\" />\n                        <xsl:variable name=\"description\">\n                                <xsl:value-of select=\"Incident/Description\" />\n                        </xsl:variable>\n\n                        <!-- display a reasonable error message -->\n            <xsl:element name=\"failure\">\n                <xsl:if test=\"Incident/@type='fail'\">\n                        <xsl:attribute name=\"type\">Standard</xsl:attribute>\n                </xsl:if>\n                <xsl:if test=\"Incident/@type='xpass'\">\n                        <xsl:attribute name=\"type\">Unexpected Pass</xsl:attribute>\n                </xsl:if>\n                \n                \n                <xsl:attribute name=\"message\">\n                                        <xsl:value-of select=\"concat($file,':',$line,' :: ',$description)\" />\n                </xsl:attribute>\n            </xsl:element>\n\n        </xsl:if>\n\n                <!-- handle skip -->\n        <xsl:if test=\"Incident/@type = 'skip'\">\n\n        </xsl:if>\n        \n                <!-- TODO: handle warnings -->\n    </testcase>\n</xsl:template>\n\n<xsl:template name=\"display-system-out\">\n        <system-out>\n                <xsl:for-each select=\"/TestCase/TestFunction/Incident[@type='fail'] | /TestCase/TestFunction/Message[@type='skip']\">\n                        <!--><xsl:choose>\n                                <xsl:when test=\"@type='fail'\">\n                                        <xsl:value-of select=\"Description\"/>\n                                </xsl:when>\n                                <xsl:when test=\"@type='skip'\">\n                                        <xsl:value-of select=\"Description\"/>\n                                </xsl:when>\n                        </xsl:choose>-->\n                </xsl:for-each>\n        </system-out>\n</xsl:template>\n\n<xsl:template name=\"display-system-err\">\n        <!-- do nothing for now -->\n        <system-err />\n</xsl:template>\n\n\n</xsl:stylesheet>\n"
  },
  {
    "path": "admin/tests/log_test.sh",
    "content": "#!/bin/bash\n# author <pete@last.fm>\n# meant to be run from the /tests dir\n\nRUNDIR=`pwd`\nmkdir $RUNDIR/output\n\nTOTERRORS=0\n\npushd ../_bin > /dev/null\n\nfor i in $*\ndo\n    BINDIR=`dirname $i`\n    LEN=${#BINDIR}\n    let LEN=$LEN+1\n    OUTPUTDIR=${i:$LEN}\n    OUTPUTFILE=$RUNDIR/output/$OUTPUTDIR.output\n    \n    $i  -xml > \"$OUTPUTFILE\"\n    \n    # check for program errors\n    RETURNCODE=$?\n    if [[ RETURNCODE -gt 0 ]];\n    then\n        echo \"Bailing out - bad return code: $RETURNCODE\"\n        echo \"$i\"\n        exit\n    fi\n    \n    # count number of test failures\n    NUMERRORS=`grep -c \\\"fail\\\" $OUTPUTFILE`\n    XPASS=`grep -c \\\"xpass\\\" $OUTPUTFILE`\n    let NUMERRORS=$NUMERRORS+$XPASS\n    let TOTERRORS=TOTERRORS+NUMERRORS\n    \n    if [[ NUMERRORS -gt 0 ]];\n    then\n        echo \"$NUMERRORS errors where encountered in $i\"\n    fi\n    \n    # transform outputted xml into junit-xml\n    xsltproc $RUNDIR/QtTest_to_JUnit.xslt $OUTPUTFILE > \"$OUTPUTFILE.junit.xml\"\ndone\n\npopd > /dev/null\n\n\nif [[ TOTERRORS -gt 0 ]];\nthen\n    echo \"Total: $TOTERRORS errors\"\nfi\n"
  },
  {
    "path": "admin/tests/run_tests.sh",
    "content": "#!/bin/bash\n# @author <max@last.fm>\n# expects to located in _bin, otherwise it doesn't work\n\nd=`dirname $0`\n\nsource $d/../admin/utils.bash\n\n\ncase `uname` in\n    Darwin) export DYLD_LIBRARY_PATH=$d:DYLD_LIBRARY_PATH;;\n    Linux)  export LD_LIBRARY_PATH=$d:$LD_LIBRARY_PATH;;\nesac\n\n# reverse sorted because test_client takes 3 minutes and it is boring to wait\nfor x in `find . -type f -perm +1 -name test_\\* | sort -r`\ndo\n    header $x\n    $x\ndone\n"
  },
  {
    "path": "app/boffin/App.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <boost/bind.hpp>\n#include <QFileDialog>\n#include <QMenu>\n#include <QLabel>\n#include <QTimer>\n#include <QShortcut>\n#include <QComboBox>\n#include <QStatusBar>\n#include <QVBoxLayout>\n#include <phonon/audiooutput.h>\n#include <phonon/backendcapabilities.h>\n#include <lastfm/NetworkAccessManager>\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"App.h\"\n#include \"MainWindow.h\"\n#include \"MediaPipeline.h\"\n#include \"PickDirsDialog.h\"\n#include \"ScanProgressWidget.h\"\n#include \"ScrobSocket.h\"\n#include \"TrackSource.h\"\n#include \"Shuffler.h\"\n#include \"LocalCollectionScanner.h\"\n#include \"playdar/PlaydarConnection.h\"\n#include \"PlaydarTagCloudModel.h\"\n#include \"Playlist.h\"\n#include \"XspfDialog.h\"\n\n\n#define OUTPUT_DEVICE_KEY \"OutputDevice\"\n#define PLAYDAR_AUTHTOKEN_KEY \"PlaydarAuth\"\n#define PLAYDAR_URLBASE_KEY \"PlaydarUrlBase\"\n\nApp::App( int& argc, char** argv )\n   : unicorn::Application( argc, argv )\n   , m_mainwindow( 0 )\n   , m_tagcloud( 0 )\n   , m_scrobsocket( 0 )\n   , m_pipe( 0 )\n   , m_playlist( 0 )\n   , m_audioOutput( 0 )\n   , m_playing( false )\n   , m_req( 0 )\n   , m_api( \n        unicorn::UserSettings().value(PLAYDAR_URLBASE_KEY, \"http://localhost:8888\").toString(), \n        unicorn::UserSettings().value(PLAYDAR_AUTHTOKEN_KEY, \"\").toString() )\n{\n    m_wam = new lastfm::NetworkAccessManager( this );\n    m_playdar = new PlaydarConnection(m_wam, m_api);\n    connect(m_playdar, SIGNAL(authed(QString)), SLOT(onPlaydarAuth(QString)));\n\n    m_shuffler = new Shuffler(this);\n    m_tracksource = new TrackSource(m_shuffler, this);\n}\n\n\nApp::~App()\n{\n    cleanup();\n    if (m_audioOutput) QSettings().setValue( OUTPUT_DEVICE_KEY, m_audioOutput->outputDevice().name() );\n    delete m_pipe;\n}\n\n\nvoid\nApp::cleanup()\n{\n}\n\n\nvoid\nApp::init( MainWindow* window ) throw( int /*exitcode*/ )\n{\n    m_mainwindow = window;\n\n    window->ui.play->setEnabled( false );\n    window->ui.pause->setEnabled( false );\n    window->ui.skip->setEnabled( false );\n    window->ui.wordle->setEnabled( false );\n\n////// radio\n    QString const name = QSettings().value( OUTPUT_DEVICE_KEY ).toString();\n    m_audioOutput = new Phonon::AudioOutput( Phonon::MusicCategory, this );\n\n    QActionGroup* actiongroup = new QActionGroup( window->ui.outputdevice );\n\n    foreach (Phonon::AudioOutputDevice d, Phonon::BackendCapabilities::availableAudioOutputDevices())\n    {\n        QAction* a = window->ui.outputdevice->addAction( d.name() );\n        a->setCheckable( true );\n        if (name == d.name())\n            m_audioOutput->setOutputDevice( d );\n        if (m_audioOutput->outputDevice().name() == d.name())\n            a->setChecked( true );\n\n        actiongroup->addAction( a );\n    }\n\n\tm_audioOutput->setVolume( 1.0 /* Settings().volume() */ );\n\n    connect( actiongroup, SIGNAL(triggered( QAction* )), SLOT(onOutputDeviceActionTriggered( QAction* )) );\n\n\tm_pipe = new MediaPipeline( m_audioOutput, this );\n    connect( m_pipe, SIGNAL(preparing()), SLOT(onPreparing()) );\n    connect( m_pipe, SIGNAL(started( Track )), SLOT(onStarted( Track )) );\n    connect( m_pipe, SIGNAL(paused()), SLOT(onPaused()) );\n    connect( m_pipe, SIGNAL(resumed()), SLOT(onResumed()) );\n    connect( m_pipe, SIGNAL(stopped()), SLOT(onStopped()) );\n    connect( m_pipe, SIGNAL(error( QString )), SLOT(onPlaybackError( QString )) );\n\n    m_scrobsocket = new ScrobSocket( this );\n    connect( m_pipe, SIGNAL(started( Track )), m_scrobsocket, SLOT(start( Track )) );\n    connect( m_pipe, SIGNAL(paused()), m_scrobsocket, SLOT(pause()) );\n    connect( m_pipe, SIGNAL(resumed()), m_scrobsocket, SLOT(resume()) );\n    connect( m_pipe, SIGNAL(stopped()), m_scrobsocket, SLOT(stop()) );\n\n/// parts of the scanning stuff\n    //m_trackTagUpdater = TrackTagUpdater::create(\n    //        \"http://musiclookup.last.fm/trackresolve\",\n    //        100,        // number of days track tags are good\n    //        5);         // 5 minute delay between web requests\n\n/// connect\n    connect( window->ui.play, SIGNAL(triggered()), SLOT(play()) );\n    connect( window->ui.pause, SIGNAL(toggled( bool )), m_pipe, SLOT(setPaused( bool )) );\n    connect( window->ui.skip, SIGNAL(triggered()), m_pipe, SLOT(skip()) );\n    connect( window->ui.rescan, SIGNAL(triggered()), SLOT(onRescan()) );\n    connect( window->ui.xspf, SIGNAL(triggered()), SLOT(xspf()) );\n    connect( m_mainwindow->ui.wordle, SIGNAL( triggered()), SLOT( onWordle()));\n\n    QShortcut* cut = new QShortcut( Qt::Key_Space, window );\n    connect( cut, SIGNAL(activated()), SLOT(playPause()) );\n    cut->setContext( Qt::ApplicationShortcut );\n\n    m_mainwindow->ui.play->setEnabled( true );\n    m_mainwindow->ui.pause->setEnabled( false );\n    m_mainwindow->ui.skip->setEnabled( false );\n    m_mainwindow->ui.rescan->setEnabled( true );\n    m_mainwindow->ui.wordle->setEnabled( true );\n    \n    connect(m_playdar->hostsModel(), SIGNAL(modelReset()), m_mainwindow, SLOT(onSourcesReset()));\n    connect(m_playdar, SIGNAL(changed(QString)), m_mainwindow->ui.playdarStatus, SLOT(setText(QString)));\n    connect(m_playdar, SIGNAL(connected()), SLOT(newTagcloud()));\n    m_playdar->start();\n}\n\n\nvoid\nApp::onOutputDeviceActionTriggered( QAction* a )\n{\n    //FIXME for some reason setOutputDevice just returns false! :(\n\n    QString const name = a->text();\n\n    foreach (Phonon::AudioOutputDevice d, Phonon::BackendCapabilities::availableAudioOutputDevices())\n        if (d.name() == name) {\n            qDebug() << m_audioOutput->setOutputDevice( d );\n            qDebug() << m_audioOutput->outputDevice().name();\n            return;\n        }\n}\n\n#include \"TagBrowserWidget.h\"\n//#include \"TagCloudView.h\"\n//#include \"TagDelegate.h\"\n//#include \"PlaydarTagCloudModel.h\"\n//#include \"PlaydarStatRequest.h\"\n//#include \"PlaydarConnection.h\"\n\n\nvoid\nApp::onScanningFinished()\n{\n    if (sender())\n        disconnect( sender(), 0, this, 0 ); //only once pls\n\n}\n\nvoid\nApp::newTagcloud()\n{\n    delete m_tagcloud;\n    m_tagcloud = new TagBrowserWidget( m_playdar );\n    connect( m_tagcloud, SIGNAL( selectionChanged()), SLOT( tagsChanged() ));\n    m_mainwindow->setCentralWidget( m_tagcloud );\n}\n\nvoid\nApp::play()\n{\n    delete m_req;\n\n    if (m_tagcloud) {\n        m_req = m_playdar->boffinRql(m_tagcloud->rql());\n        if (m_req) {\n            m_shuffler->clear();\n            connect(m_req, SIGNAL(playableItem(BoffinPlayableItem)), m_shuffler, SLOT(receivePlayableItem(BoffinPlayableItem)));\n            connect(m_req, SIGNAL(playableItem(BoffinPlayableItem)), SLOT(onPlaydarTracksReady(BoffinPlayableItem)));\n            onPreparing();\n        }\n    }\n}\n\nvoid\nApp::tagsChanged()\n{\n}\n\n\nvoid\nApp::onPlaydarTracksReady( BoffinPlayableItem )\n{\n    // just interested in the first one\n    disconnect(m_req, SIGNAL(playableItem(BoffinPlayableItem)), this, SLOT(onPlaydarTracksReady(BoffinPlayableItem)));\n    // then delay for a little bit (to let a few more tracks dribble in) before playing\n    QTimer::singleShot(500, this, SLOT(onReadyToPlay()));\n}\n\n\nvoid\nApp::onReadyToPlay()\n{\n    m_pipe->play(m_tracksource);\n}\n\n\nvoid\nApp::playPause()\n{\n    if (m_playing)\n        m_mainwindow->ui.pause->toggle();\n    else\n        play();\n}\n\n\nvoid\nApp::xspf()\n{\n    QString path = QFileDialog::getOpenFileName( m_mainwindow, \"Open XSPF File\", \"*.xspf\" );\n    if (path.size())\n    {\n        XspfDialog *pDlg = new XspfDialog(path, m_playdar, m_mainwindow);\n        pDlg->show();\n //       m_mainwindow->QMainWindow::setWindowTitle( \"Resolving XSPF...\" );\n //       m_pipe->playXspf( path );\n    }\n}\n\n\nvoid\nApp::onPreparing() //MediaPipeline is preparing to play a new station\n{\n    m_mainwindow->QMainWindow::setWindowTitle( \"Boffing up...\" );\n\n    QAction* a = m_mainwindow->ui.play;\n    a->setIcon( QPixmap(\":/stop.png\") );\n    disconnect( a, SIGNAL(triggered()), this, 0 );\n    connect( a, SIGNAL(triggered()), m_pipe, SLOT(stop()) );\n}\n\n\nvoid\nApp::onStarted( const Track& t )\n{\n    m_playing = true; // because phonon is shit and we can't rely on its state\n\n    m_mainwindow->setWindowTitle( t );\n    m_mainwindow->ui.play->blockSignals( true );\n    m_mainwindow->ui.play->setChecked( true );\n    m_mainwindow->ui.play->blockSignals( false );\n    m_mainwindow->ui.pause->blockSignals( true );\n    m_mainwindow->ui.pause->setChecked( false );\n    m_mainwindow->ui.pause->setEnabled( true );\n    m_mainwindow->ui.pause->blockSignals( false );\n\n    m_mainwindow->ui.skip->setEnabled( true );\n}\n\n\nvoid\nApp::onPaused()\n{\n    m_mainwindow->ui.pause->blockSignals( true );\n    m_mainwindow->ui.pause->setChecked( true );\n    m_mainwindow->ui.pause->blockSignals( false );\n}\n\n\nvoid\nApp::onResumed()\n{\n    m_mainwindow->ui.pause->blockSignals( true );\n    m_mainwindow->ui.pause->setChecked( false );\n    m_mainwindow->ui.pause->blockSignals( false );\n}\n\n\nvoid\nApp::onStopped()\n{\n    m_mainwindow->setWindowTitle( Track() );\n    m_mainwindow->ui.play->blockSignals( true );\n    m_mainwindow->ui.play->setChecked( false );\n    m_mainwindow->ui.play->blockSignals( false );\n    m_mainwindow->ui.pause->blockSignals( true );\n    m_mainwindow->ui.pause->setChecked( false );\n    m_mainwindow->ui.pause->setEnabled( false );\n    m_mainwindow->ui.pause->blockSignals( false );\n\n    m_mainwindow->ui.skip->setEnabled( false );\n\n    QAction* a = m_mainwindow->ui.play;\n    a->setIcon( QPixmap(\":/play.png\") );\n    disconnect( a, SIGNAL(triggered()), m_pipe, 0 );\n    connect( a, SIGNAL(triggered()), SLOT(play()) );\n\n    m_playing = false;\n}\n\n\nvoid\nApp::onPlaybackError( const QString& msg )\n{\n    //TODO: need to make this more like client 2's subtle yellow box.\n    QMessageBoxBuilder( m_mainwindow )\n            .setTitle( \"Playback Error\" )\n            .setText( msg )\n            .exec();\n}\n\n\n#include \"WordleDialog.h\"\nvoid\nApp::onWordle()\n{\n    static OneDialogPointer<WordleDialog> d;\n    if(!d) {\n        d = new WordleDialog( m_mainwindow );\n        QString output;\n        //TagCloudModel model( this, 0 );\n        //for(int i = 0; i < model.rowCount(); ++i) {\n        //    QModelIndex index = model.index( i, 0 );\n        //    QString weight = index.data( TagCloudModel::WeightRole ).toString();\n        //    QString tag = index.data().toString().trimmed().simplified().replace( ' ', '~' );\n        //    output += tag + ':' + weight + '\\n';\n        //}\n        d->setText( output );\n    }\n    d.show();\n}\n\nvoid\nApp::onPlaydarAuth(const QString& auth)\n{\n    unicorn::UserSettings().setValue(PLAYDAR_AUTHTOKEN_KEY, auth);\n}\n\nvoid \nApp::onRescan()\n{\n    PickDirsDialog* dlg = new PickDirsDialog(m_mainwindow);\n    if (QDialog::Accepted == dlg->exec()) {\n        QStringList directories = dlg->dirs();\n        if (directories.size()) {\n            LocalCollectionScanner *scanner = new LocalCollectionScanner(this);\n            m_scanWidget = new ScanProgressWidget();\n            connect(scanner, SIGNAL(track(Track)), m_scanWidget, SLOT(onNewTrack(Track)));\n            connect(scanner, SIGNAL(directory(QString)), m_scanWidget, SLOT(onNewDirectory(QString)));\n            connect(scanner, SIGNAL(finished()), m_scanWidget, SLOT(onFinished()));\n            connect(scanner, SIGNAL(finished()), SLOT(newTagcloud()));\n            connect(m_scanWidget, SIGNAL(statusMessage(QString)), m_mainwindow->statusBar(), SLOT(showMessage(QString)));\n\n            // TODO: fix hard coded paths here!\n            scanner->run(\n                QDir(\"c:\\\\cygwin\\\\home\\\\doug\\\\src\\\\playdar\\\\win32\\\\debug\\\\bin\\\\\"), \n                \"c:\\\\cygwin\\\\home\\\\doug\\\\src\\\\playdar\\\\win32\\\\collection.db\", \n                directories);\n\n            m_mainwindow->setCentralWidget(m_scanWidget);\n        }\n    }\n}\n"
  },
  {
    "path": "app/boffin/App.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef APP_H\n#define APP_H\n\n#include \"playdar/PlaydarApi.h\"\n#include \"playdar/BoffinPlayableItem.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include <lastfm/global.h>\n#include <QPointer>\n#include <types/Track.h>\n\n\nnamespace Phonon { class AudioOutput; }\n\nclass TagCloudView;\nclass QItemSelection;\nclass PlaydarTagCloudModel;\nclass Shuffler;\nclass TrackSource;\nclass ScanProgressWidget;\n\nnamespace lastfm{ class Track; }\n\nclass App : public unicorn::Application\n{\n    Q_OBJECT\n\npublic:\n    App( int& argc, char* argv[] );\n    ~App();\n\n    void init( class MainWindow* ) throw( int /*exitcode*/ );\n    void play( class TrackSource *);\n\npublic slots:\n    void play();\n    void xspf(); //prompts to choose a xspf to resolve\n\n    void playPause();\n\nprivate slots:\n    void onOutputDeviceActionTriggered( class QAction* );\n\n    void tagsChanged();\n    void onReadyToPlay();\n    void onPlaydarTracksReady( BoffinPlayableItem );\n    void onPlaydarAuth(const QString&);\n    void onPreparing();\n    void onStarted( const Track& );\n    void onResumed();\n    void onPaused();\n    void onStopped();\n    void onRescan();\n    void newTagcloud();\n\n    void onScanningFinished();\n    void onPlaybackError( const QString& );\n    void onWordle();\n\nprivate:\n    void cleanup();\n\n    class MainWindow* m_mainwindow;\n    class TagBrowserWidget* m_tagcloud;\n    class ScanProgressWidget* m_scanWidget;\n    class ScrobSocket* m_scrobsocket;\n    class MediaPipeline* m_pipe;        // pipe pulls from tracksource\n    class TrackSource* m_tracksource;   // tracksource pulls from shuffler\n    class Shuffler* m_shuffler;         // shuffler is fed from \n    class PlaydarConnection* m_playdar;\n    class Playlist* m_playlist;\n    class BoffinRqlRequest* m_req;      // current boffin rql request\n\n    Phonon::AudioOutput* m_audioOutput;\n\n    bool m_playing;\n\n    PlaydarApi m_api;\n    lastfm::NetworkAccessManager* m_wam;\n\n};\n\n#endif //APP_H\n"
  },
  {
    "path": "app/boffin/HistoryWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QHBoxLayout>\n#include <QPushButton>\n#include \"HistoryWidget.h\"\n\nHistoryWidget::HistoryWidget(QWidget* parent)\n    : QWidget(parent)\n{\n    m_layout = new QHBoxLayout(this);\n    m_layout->setAlignment( Qt::AlignLeft );\n}\n\nHistoryWidget::~HistoryWidget()\n{}\n\nbool \nHistoryWidget::pop()\n{\n    if (m_labels.count()) {\n        QPushButton* label = m_labels.pop();\n        m_layout->removeWidget(label);\n        delete label;\n        return true;\n    }\n    return false;\n}\n\n\nvoid \nHistoryWidget::newItem(const QString& text)\n{\n    QPushButton* label = new QPushButton(text, this);\n    m_layout->addWidget(label, 0, Qt::AlignLeft);\n    m_labels.push(label);\n    connect(label, SIGNAL(clicked()), SLOT(onItemClicked()));\n}\n\nvoid \nHistoryWidget::onItemClicked()\n{\n    QPushButton* label = static_cast<QPushButton*>(sender());\n    for (int i = 0; i < m_labels.count(); i++) {\n        if (m_labels[i] == label) {\n            emit clicked(i, label->text());\n            return;\n        }\n    }\n}\n"
  },
  {
    "path": "app/boffin/HistoryWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef HISTORY_WIDGET_H\n#define HISTORY_WIDGET_H\n\n#include <QWidget>\n#include <QStack>\n\nclass QPushButton;\nclass QHBoxLayout;\n\nclass HistoryWidget : public QWidget\n{\n    Q_OBJECT\n\npublic:\n    HistoryWidget(QWidget* parent = 0);\n    ~HistoryWidget();\n\n    bool pop();\n\nsignals:\n    void clicked(int position, const QString& text);\n\npublic slots:\n    void newItem(const QString& text);\n\nprivate slots:\n    void onItemClicked();\n\nprivate:\n    QHBoxLayout* m_layout;\n    QStack<QPushButton*> m_labels;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/Info.plist.in",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleIconFile</key>\n\t<string>@ICON@</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleSignature</key>\n\t<string>last</string>\n\t<key>CFBundleExecutable</key>\n\t<string>@EXECUTABLE@</string>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>fm.last.Boffin</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleVersion</key>\n\t<string>@VERSION@</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>@SHORT_VERSION@</string>\n\t<key>CFBundleName</key>\n\t<string>Last.fm Boffin</string>\n\t<key>LSMinimumSystemVersion</key>\n    <string>10.4.0</string>\n\t<key>CFBundleDocumentTypes</key>\n\t<array>    \n\t    <dict>\n    \t\t<key>CFBundleTypeExtensions</key>\n    \t\t<array>\n    \t\t\t<string>xspf</string>\n    \t\t</array>\n    \t\t<key>CFBundleTypeIconFile</key>\n    \t\t<string>client.icns</string>\n    \t\t<key>CFBundleTypeMIMETypes</key>\n    \t\t<array>\n    \t\t\t<string>application/xspf+xml</string>\n    \t\t</array>\n    \t\t<key>CFBundleTypeName</key>\n    \t\t<string>XSPF Playlist</string>\n    \t\t<key>CFBundleTypeRole</key>\n    \t\t<string>Viewer</string>\n\t    </dict>\n\t</array>\n</dict>\n</plist>\n"
  },
  {
    "path": "app/boffin/LocalCollectionScanner.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"LocalCollectionScanner.h\"\n\n#include <QDebug>\n\nusing namespace std;\n\nLocalCollectionScanner::LocalCollectionScanner(QObject* parent)\n    : QObject(parent)\n{\n}\n\nvoid \nLocalCollectionScanner::run(QDir playdarBinDir, QString collectionDbFilename, QStringList directories)\n{\n    QStringList args;\n    args << collectionDbFilename;\n    args << directories;\n\n    m_proc = new QProcess(this);\n    connect(m_proc, SIGNAL(readyReadStandardOutput()), SLOT(onReadyReadStandardOutput()));\n    connect(m_proc, SIGNAL(readyReadStandardError()), SLOT(onReadyReadStandardError()));\n    connect(m_proc, SIGNAL(finished(int, QProcess::ExitStatus)), SLOT(onFinished(int, QProcess::ExitStatus)));\n    connect(m_proc, SIGNAL(error(QProcess::ProcessError)), SLOT(onError(QProcess::ProcessError)));\n    m_proc->start(playdarBinDir.filePath(\"scanner.exe\"), args);\n}\n\nvoid\nLocalCollectionScanner::onReadyReadStandardOutput()\n{\n    QByteArray ba = m_proc->readAllStandardOutput();\n    m_buffer.write(ba.constData(), ba.size());\n    while (true) {\n        string line;\n        getline(m_buffer, line);\n        if (m_buffer.fail()) {\n            // the line is incomplete (for now)\n            m_buffer.clear(); // clears the failbit\n            return;\n        } \n        LocalCollectionScanner::line(line);\n    }\n}\n\nvoid\nLocalCollectionScanner::onReadyReadStandardError()\n{\n}\n\nvoid  \nLocalCollectionScanner::onFinished(int /*exitCode*/, QProcess::ExitStatus /*exitStatus*/)\n{\n    emit finished();\n}\n\nvoid\nLocalCollectionScanner::onError(QProcess::ProcessError)\n{\n    emit finished();\n}\n\nvoid\nLocalCollectionScanner::line(const string& s)\n{\n    QString line = QString::fromUtf8(s.data(), s.length()).trimmed();\n    QStringList fields = line.split(QChar('\\t'), QString::KeepEmptyParts, Qt::CaseInsensitive);\n    if (fields.size()) {\n        if (fields[0] == \"DIR:\") {\n            if (fields.size() > 1) {\n                emit directory(fields[1]);\n            }\n        } else if (fields[0] == \"TRACK:\") {\n            if (fields.size() > 4) {\n                lastfm::Track t;\n                lastfm::MutableTrack mt(t);\n                mt.setArtist(fields[1]);\n                mt.setAlbum(fields[2]);\n                mt.setTitle(fields[3]);\n                mt.setUrl(fields[4]);\n                emit track(t);\n            }\n        }\n    }\n}\n\n"
  },
  {
    "path": "app/boffin/LocalCollectionScanner.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LOCAL_COLLECTION_SCANNER_H\n#define LOCAL_COLLECTION_SCANNER_H\n\n#include <sstream>\n#include <QDir>\n#include <QProcess>\n#include <QStringList>\n#include <types/Track.h>\n\n\nclass LocalCollectionScanner : public QObject\n{\n    Q_OBJECT;\n\npublic:\n    LocalCollectionScanner(QObject* parent);\n    void run(QDir playdarBinDir, QString collectionDbFilename, QStringList directories);\n\nsignals:\n    void track(Track);\n    void directory(QString);\n    void finished();\n\nprivate slots:\n    void onReadyReadStandardOutput();\n    void onReadyReadStandardError();\n    void onFinished(int, QProcess::ExitStatus);\n    void onError(QProcess::ProcessError);\n\nprivate:\n    void line(const std::string& line);\n\n    QProcess* m_proc;\n    QString m_collectionDbFilename;\n    QDir m_playdarBinDir;\n    std::stringstream m_buffer;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/MainWindow.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"MainWindow.h\"\n#include <QLabel>\n#include <QMenuBar>\n#include <QToolBar>\n#include <QComboBox>\n#include <QStatusBar>\n#include <QPushButton>\n#include <types/Track.h>\n#include \"PlaydarHostsModel.h\"\n#include \"playdar/PlaydarConnection.h\"\n\nMainWindow::MainWindow()\n{   \n    ui.outputdevice = menuBar()->addMenu( tr(\"Output Device\") );\n\n    QMenu* tools = menuBar()->addMenu( tr(\"Tools\") );\n    ui.xspf = tools->addAction( \"Resolve XSPF\" );\n    ui.rescan = tools->addAction( tr(\"&Scan Music Again\") );\n    tools->addAction( tr(\"Show &Log\"), this, SLOT(openLog()) );\n    ui.wordle = tools->addAction( tr(\"Wordlize\"));\n\n    QToolBar* toolbar = new QToolBar;\n    toolbar->setIconSize( QSize( 41, 41 ) );\n    ui.play = toolbar->addAction( tr(\"Play\") );\n    ui.play->setIcon( QPixmap(\":/play.png\") );\n    ui.pause = toolbar->addAction( tr(\"Pause\") );\n    ui.pause->setIcon( QPixmap(\":/pause.png\") );\n    ui.pause->setCheckable( true );\n    ui.skip = toolbar->addAction( tr(\"Skip\") );\n    ui.skip->setIcon( QPixmap(\":/skip.png\") );\n    addToolBar( toolbar );\n\n    setWindowTitle( Track() );\n    setUnifiedTitleAndToolBarOnMac( true );\n    resize( 750, 550 );\n    \n    QStatusBar* status = new QStatusBar();\n    ui.sourcesMenu = new QMenu();\n    ui.sourcesButton = new QPushButton(\"Sources\");\n    ui.sourcesButton->setMenu(ui.sourcesMenu);\n    ui.playdarStatus = new QLabel();\n    status->addPermanentWidget(ui.playdarStatus);\n    status->addPermanentWidget(ui.sourcesButton);\n    status->setStyleSheet( \"QStatusBar::item{ border: none; }\" );\n    setStatusBar(status);\n\n    finishUi();\n}\n\n\nvoid\nMainWindow::onSourcesReset()\n{\n    QStringList sources = ((QStringListModel*)sender())->stringList();\n    sources.sort();\n\n    ui.sourcesMenu->clear();\n    foreach(const QString& s, sources) {\n        QAction* action = ui.sourcesMenu->addAction(s);\n        action->setCheckable(true);\n        action->setChecked(true);\n    }\n}\n\n\nvoid\nMainWindow::setWindowTitle( const Track& t )\n{\n    if (t.isNull())\n        QMainWindow::setWindowTitle( tr(\"Last.fm Boffin\") );\n    else\n        QMainWindow::setWindowTitle( t.toString() );\n}\n"
  },
  {
    "path": "app/boffin/MainWindow.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QModelIndex>\n#include <lastfm/global.h>\n#include \"lib/unicorn/UnicornMainWindow.h\"\n\n\nclass MainWindow : public unicorn::MainWindow\n{\n    Q_OBJECT\n\n    friend class App;\n\n    struct Ui\n    {\n        QMenu* outputdevice;\n        QAction* play;\n        QAction* pause;\n        QAction* skip;    \n        QAction* xspf;\n        QAction* rescan;\n        QAction* wordle;\n        class QPushButton* sourcesButton;\n        class QMenu* sourcesMenu;\n        class QLabel* playdarStatus;\n    } ui;\n\npublic:\n    MainWindow();\n\n    void setWindowTitle( const Track& );\n\npublic slots:\n    void onSourcesReset();\n};\n"
  },
  {
    "path": "app/boffin/MediaPipeline.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <cmath>\n#include <QEventLoop>\n#include <QStringList>\n#include <QThread>\n#include <phonon/mediaobject.h>\n#include <phonon/audiooutput.h>\n#include \"MediaPipeline.h\"\n#include \"TrackSource.h\"\n\n\nMediaPipeline::MediaPipeline( Phonon::AudioOutput* ao, QObject* parent )\n             : QObject( parent )\n             , mo( 0 )\n             , ao( ao )\n             , m_source( 0 )\n             , m_errorRecover( false )\n             , m_phonon_sucks( false )\n{\n    mo = new Phonon::MediaObject;\n    connect( mo, SIGNAL(stateChanged( Phonon::State, Phonon::State )), SLOT(onPhononStateChanged( Phonon::State, Phonon::State )) );\n    connect( mo, SIGNAL(aboutToFinish()), SLOT(enqueue()) ); // fires just before track finishes\n    connect( mo, SIGNAL(currentSourceChanged( Phonon::MediaSource )), SLOT(onPhononSourceChanged( Phonon::MediaSource )) ); \n    Phonon::createPath( mo, ao );\n}\n\n\nMediaPipeline::~MediaPipeline()\n{    \n    // I'm not confident about the sleep code on Windows --mxcl\n#ifndef WIN32\n\tif (mo->state() != Phonon::PlayingState)\n        return;\n\n    qreal starting_volume = ao->volume();\n    //sigmoid curve\n    for (int x = 18; x >= -60; --x)\n    {\n        qreal y = x;\n        y /= 10;\n        y = qreal(1) / (qreal(1) + std::exp( -y ));\n        y *= starting_volume;\n        ao->setVolume( y );\n\n\t\tstruct Thread : QThread { using QThread::msleep; };\n\t\tThread::msleep( 7 );\n    }\n#endif\n\n    //delete mo; //don't as crashes often\n}\n\n\nvoid\nMediaPipeline::play( TrackSource* trackSource )\n{\n//\tdelete m_source;\n    m_source = trackSource;\n    enqueue();\n}\n\n\nvoid\nMediaPipeline::setPaused( bool b )\n{\n    if (b)\n        mo->pause();\n    else if (mo->state() == Phonon::PausedState)\n        mo->play();\n}\n\n\nvoid\nMediaPipeline::skip()\n{    \n    using namespace Phonon;\n        \n    enqueue();\n        \n    QList<MediaSource> q = mo->queue();\n    if (q.isEmpty()) { stop(); return; } // oh well :( enqueue() fails\n    \n    m_phonon_sucks = true; // phonon is broken hack\n    mo->setCurrentSource( q.takeFirst() );\n    Q_ASSERT( q.isEmpty() );\n    mo->setQueue( q ); //now empty\n    mo->play();\n}\n\n\nvoid\nMediaPipeline::stop()\n{\n    using namespace Phonon;\n    \n    qDebug() << mo->state();\n    \n    m_tracks.clear();\n    \n    if (mo->state() != Phonon::StoppedState)\n    {\n        // lol @ Phonon's shit API. We're 99% sure we're using it right\n        mo->stop();\n        mo->setCurrentSource( MediaSource() );\n        mo->setQueue( QList<MediaSource>() );\n        \n        if (mo->state() == Phonon::LoadingState)\n            emit stopped(); //phonon is broken and shit\n    }\n    else if (m_source)\n    {\n        // otherwise we have a source and it is doing something, but it could be\n        // slow. Slow enough that the user wants to push the stop() button. So\n        // the user did push the stop button. So tell the GUI that we stopped.\n        emit stopped();\n        m_source->clear();\n    }\n}\n\n\nvoid\nMediaPipeline::onPhononStateChanged( Phonon::State newstate, Phonon::State oldstate )\n{\n    using namespace Phonon;\n    \n    // this is a HACK because Phonon docs lie that after you setCurrentSource\n    // and call play() it will go to PlayingState. Actually it ALWAYS goes to\n    // StoppedState. Phonon is absolute shit. With a shit API. And a bunch of\n    // shit like the inability to play all mp3s and support all sound cards and\n    // not hang the soding GUI whenever we call a function on MediaObject.\n    // We're fucking unimpressed.\n    if (m_phonon_sucks)\n        switch (newstate)\n        {\n            case PlayingState:\n            case ErrorState:\n            case PausedState:\n                m_phonon_sucks = false;\n                break;\n            default:\n                return;\n        }\n    \n    qDebug() << newstate << \"was\" << oldstate;\n        \n    switch (newstate)\n    {\n        case StoppedState:\n            if (m_errorRecover) {\n                m_errorRecover = false;\n                skip();\n            } else {\n                m_tracks.clear();\n                emit stopped();\n            }\n            break;\n            \n        case ErrorState:\n            qWarning() << mo->errorString();\n            // need to request a stop to clear the error state before we trying to play the next track\n            m_errorRecover = true;\n            mo->stop();\n            emit error( \"There was an error during playback.\" );\n            break;\n            \n        case PausedState:\n            emit paused();\n            break;\n            \n        case PlayingState:\n            if (oldstate == PausedState)\n                emit resumed();\n            else\n                enqueue();\n            break;\n\n        default:\n            break;\n    }\n}\n\n\nvoid\nMediaPipeline::onPhononSourceChanged( const Phonon::MediaSource& source )\n{\n    emit started( m_tracks.value( source.url() ) );\n}\n\n\nvoid\nMediaPipeline::enqueue()\n{    \n    if (mo->queue().size() || !m_source)    // queue is already full (or no source)\n        return;\n\n    // Loop until we get a null url or a valid url.\n    for (;;)\n    {\n        // consume next track from the track source. a null track \n        // response means wait until the trackAvailable signal\n        if( !m_source) {\n            qDebug() << \"source is null\";\n            break;\n        }\n\n        Track t = m_source->takeNextTrack();\n        if (t.isNull()) {\n            qDebug() << \"tracksource empty\";\n            break;\n        }\n\n        // Invalid urls won't trigger the correct phonon\n        // state changes, so we must prefilter them.\n        if (!t.url().isValid()) {\n            qDebug() << \"invalid url (\" << t << \") skipped\";\n            continue;\n        }\n\n        m_tracks[t.url()] = t;\n\n        // if we are playing a track now, enqueue, otherwise start now!\n        if (mo->currentSource().url().isValid()) {\n            qDebug() << \"enqueuing \" << t;\n            mo->enqueue( Phonon::MediaSource( t.url() ) );\n        } else {\n            qDebug() << \"starting \" << t;\n            m_phonon_sucks = true; //Phonon is shit and broken\n            mo->setCurrentSource( Phonon::MediaSource( t.url() ) );\n            mo->play();\n        }\n        break;\n    }\n}\n\n\nvoid\nMediaPipeline::onSourceError( lastfm::ws::Error e )\n{\n    qCritical() << e;\n    emit error( \"There was an error generating the playlist.\" );\n}\n\n\nPhonon::State\nMediaPipeline::state() const\n{\n    return mo->state(); \n}\n"
  },
  {
    "path": "app/boffin/MediaPipeline.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <lastfm/global.h>\n#include <types/Track.h>\n#include <lastfm/ws.h>\n#include <QPointer>\n#include <QObject>\n#include <phonon/phononnamespace.h>\n\n\nnamespace Phonon\n{\n\tclass MediaObject;\n \tclass AudioOutput;\n    class MediaSource;\n}\n\n\n\nclass MediaPipeline : public QObject\n{\n    Q_OBJECT\n\npublic: \n    MediaPipeline( Phonon::AudioOutput*, QObject* parent );\n    ~MediaPipeline();\n\n    Phonon::State state() const;\n\n    void play( class TrackSource* );\n\npublic slots:\n    void setPaused( bool );\n    void stop();\n    void skip();\n\nsignals:\n    void started( const Track& );\n    void paused();\n    void resumed();\n    void stopped();\n    void error( const QString& );\n\nprivate slots:\n    void onPhononSourceChanged( const Phonon::MediaSource& );\n    void onPhononStateChanged( Phonon::State, Phonon::State );\n    void onSourceError( lastfm::ws::Error );\n    void enqueue();\n\nprivate:\n\tPhonon::MediaObject* mo;    \n    Phonon::AudioOutput* ao;\n    TrackSource* m_source;\n\n    QMap<QUrl, Track> m_tracks;\n\n    bool m_errorRecover;\n    bool m_phonon_sucks;\n};\n"
  },
  {
    "path": "app/boffin/PickDirsDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PickDirsDialog.h\"\n#include <QtGui>\n\n#define kBlurb \"Boffin creates Last.fm radio from the music on your computer.\"\n\n\nPickDirsDialog::PickDirsDialog( QWidget* parent )\n              : QDialog( parent, Qt::Sheet )\n{\n    ui.group = new QGroupBox( tr(\"Where is your music?\") );\n    ui.buttons = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel );\n    ui.add = new QPushButton( tr(\"Add Another Folder\") );\n    ui.add->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::Fixed );\n\n    QLabel* blurb;\n\n    QVBoxLayout* v = new QVBoxLayout( ui.group );\n    v->addStretch();\n    v->setMargin( 10 );\n\n    v = new QVBoxLayout( this );\n    v->addWidget( blurb = new QLabel( kBlurb ) );\n    v->addSpacing( 18 );\n    v->addWidget( ui.group );\n    v->addSpacing( 8 );\n    v->addWidget( ui.add );\n    v->setAlignment( ui.add, Qt::AlignLeft );\n    v->addSpacing( 25 );\n    v->addWidget( ui.buttons );\n    v->setSpacing( 0 );\n\n    connect( ui.buttons, SIGNAL(rejected()), SLOT(reject()) );\n    connect( ui.buttons, SIGNAL(accepted()), SLOT(accept()) );\n\n    connect( ui.add, SIGNAL(clicked()), SLOT(prompt()) );\n    \n    ui.group->setMinimumHeight( 78 );\n\n//////\n    setMinimumWidth( 400 );\n\n#ifdef Q_OS_MAC\n    ui.group->setTitle( \"\" );\n    QLabel* label;\n    v->insertSpacing( 2, 6 );\n    v->insertWidget( 2, label = new QLabel( \"<b>Where is your music?\") );\n    v->insertSpacing( 0, 12 );\n    label->setAttribute( Qt::WA_MacSmallSize );\n#endif\n}\n\n\nvoid\nPickDirsDialog::add( const QString& path )\n{\n    if (path.isEmpty()) return;\n\n    QCheckBox* check = new QCheckBox( QDir::toNativeSeparators( path ) );\n    check->setChecked( true );\n    connect( check, SIGNAL(toggled( bool )), SLOT(enableDisableOk()) );\n    \n    QVBoxLayout* v = (QVBoxLayout*)ui.group->layout();\n    v->insertWidget( v->count()-1, check );\n    \n    enableDisableOk();\n}\n\n\nvoid\nPickDirsDialog::prompt()\n{\n    add( QFileDialog::getExistingDirectory( this ) );\n}\n\n\nQStringList\nPickDirsDialog::dirs() const\n{\n    QStringList dirs;\n    foreach (QCheckBox* check, ui.group->findChildren<QCheckBox*>())\n        if (check->isChecked())\n            dirs += check->text();\n    dirs.removeAll( \"\" );\n    return dirs;\n}\n\n\nvoid\nPickDirsDialog::setDirs(QStringList dirs)\n{\n    qDebug() << dirs;\n    \n    if (dirs.isEmpty())\n#ifdef __APPLE__\n        dirs << QDir::home().filePath( \"Music\" );\n#else\n        dirs << QDir::homePath();\n#endif\n    \n    foreach (QString dir, dirs)\n        add( dir );\n}\n\n\nvoid\nPickDirsDialog::enableDisableOk()\n{\n    QPushButton* ok = ui.buttons->button( QDialogButtonBox::Ok );\n    ok->setEnabled( true );\n    foreach (QCheckBox* check, ui.group->findChildren<QCheckBox*>())\n        if (check->isChecked()) \n            return;\n    ok->setEnabled( false );\n}\n"
  },
  {
    "path": "app/boffin/PickDirsDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QDialog>\n\n \nclass PickDirsDialog : public QDialog\n{\n    Q_OBJECT\n\n    struct Ui\n    {\n        class QDialogButtonBox* buttons;\n        class QGroupBox* group;\n        class QPushButton* add;\n        \n    } ui;\n    \n    void add( const QString& path );\n\nprivate slots:\n    void prompt();\n    void enableDisableOk();\n\npublic:\n    PickDirsDialog( QWidget* parent );\n    \n    QStringList dirs() const;\n    void setDirs(QStringList dirs);\n};\n"
  },
  {
    "path": "app/boffin/PlaydarHostsModel.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlaydarHostsModel.h\"\n\n\n//virtual \nQVariant \nPlaydarHostsModel::data(const QModelIndex &index, int /*role  = Qt::DisplayRole */) const\n{\n    return (index.row() < m_hosts.size()) ? m_hosts[index.row()] : QVariant();\n}\n\n//virtual \nint \nPlaydarHostsModel::rowCount(const QModelIndex& /*parent  = QModelIndex() */) const\n{\n    return m_hosts.size();\n}\n\nvoid \nPlaydarHostsModel::onHosts(const QStringList& hosts)\n{\n    m_hosts = hosts;\n    reset();\n}\n"
  },
  {
    "path": "app/boffin/PlaydarHostsModel.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYDAR_HOSTS_MODEL_H\n#define PLAYDAR_HOSTS_MODEL_H\n\n#include <QAbstractListModel>\n#include <QStringList>\n\nclass PlaydarHostsModel : public QAbstractListModel\n{\n    Q_OBJECT\n\npublic:\n    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;\n    virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;\n\npublic slots:\n    void onHosts(const QStringList& hosts);\n\nprivate:\n    QStringList m_hosts;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/PlaydarTagCloudModel.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <float.h>\n#include <math.h>\n#include \"PlaydarTagCloudModel.h\"\n#include \"playdar/PlaydarConnection.h\"\n#include <QTimer>\n\nPlaydarTagCloudModel::PlaydarTagCloudModel(PlaydarConnection* playdar)\n:m_playdar(playdar)\n,m_loadingTimer( 0 )\n{\n}\n\nPlaydarTagCloudModel::~PlaydarTagCloudModel()\n{\n}\n\nvoid\nPlaydarTagCloudModel::startGetTags(const QString& rql)\n{\n    m_hosts.clear();\n    m_tagListBuffer.clear();\n    m_tagList.clear();\n\n    m_maxWeight = 0;\n    m_maxLogCount = FLT_MIN;\n    m_minLogCount = FLT_MAX;\n    m_maxTrackCount = 0;\n    m_totalTracks = 0;\n    m_totalDuration = 0;\n\n    BoffinTagRequest* req = m_playdar->boffinTagcloud(rql);\n    connect(req, SIGNAL(tagItem(BoffinTagItem)), SLOT(onTag(BoffinTagItem)));\n    connect(req, SIGNAL(tagItem(BoffinTagItem)), SIGNAL(tagItem(BoffinTagItem)));\n    connect(req, SIGNAL(error()), this, SLOT(onTagError()));\n    if( m_loadingTimer )\n    {\n    \tdelete( m_loadingTimer );\n    \tm_loadingTimer = 0;\n    }\n    qDebug() << \"Fetching rql: \" << rql;\n}\n\nvoid\nPlaydarTagCloudModel::onTag(BoffinTagItem tag)\n{\n\tif( m_loadingTimer )\n\t\tm_loadingTimer->stop();\n\n    // check if the host is being filtered.\n    if (!m_hostFilter.contains(tag.m_host)) {\n        m_hosts.insert(tag.m_host);\n\n\t\tif( int i = m_tagListBuffer.indexOf( tag ) >= 0 )\n\t\t{\n    \t\t// merge into existing tag\n\t\t\tm_tagListBuffer[ i ].m_weight += tag.m_weight;\n            m_tagListBuffer[ i ].m_count += tag.m_count;\n\t\t\tm_tagListBuffer[ i ].m_logCount = log( (float) m_tagListBuffer[i].m_count );\n\t\t\tm_maxWeight = qMax( m_tagListBuffer[i].m_weight, m_maxWeight);\n\t\t\tm_maxLogCount = qMax( m_tagListBuffer[i].m_logCount, m_maxLogCount);\n        }\n        else\n        {\n            // new tag\n\t\t    tag.m_logCount = log( (float) tag.m_count );\n\t\t    m_tagListBuffer << tag;\n\t\t    m_maxTrackCount = qMax( tag.m_count, m_maxTrackCount );\n\t\t    m_maxWeight = qMax( tag.m_weight, m_maxWeight );\n\t\t    m_maxLogCount = qMax( m_maxLogCount, tag.m_logCount );\n\t\t    m_minLogCount = qMin( m_minLogCount, tag.m_logCount );\n        }\n\t}\n\n    // fire onFetchedTags after 1 second of idle-ness\n\tif( !m_loadingTimer )\n\t{\n\t\tm_loadingTimer = new QTimer();\n\t\tm_loadingTimer->setSingleShot( true );\n\t\tconnect( m_loadingTimer, SIGNAL( timeout()), SLOT(onFetchedTags()));\n\t}\n    m_loadingTimer->start( 1000 );\n\n}\n\nvoid\nPlaydarTagCloudModel::onFetchedTags()\n{\n\tm_loadingTimer->deleteLater();\n\tm_loadingTimer = 0;\n//\tbeginInsertRows( QModelIndex(), m_tagList.size(), m_tagListBuffer.size() );\n\t\tm_tagList = m_tagListBuffer;\n\t\tqSort( m_tagList.begin(), m_tagList.end(), qGreater<BoffinTagItem >() );\n//\tendInsertRows();\n    reset();\n\temit fetchedTags();\n}\n\nvoid\nPlaydarTagCloudModel::onTagError()\n{\n}\n\n// virtual\nQVariant\nPlaydarTagCloudModel::data( const QModelIndex& index, int role ) const\n{\n\tif( index.row() >= m_tagList.count() )\n\t\treturn QVariant();\n\n    QList< BoffinTagItem >::const_iterator i = m_tagList.constBegin();\n    i += index.row();\n\n\tswitch( role )\n    {\n        case Qt::DisplayRole:\n            return i->m_name;\n\n        case PlaydarTagCloudModel::WeightRole:\n            return QVariant::fromValue<float>((i->m_weight / m_maxWeight));\n\n        case PlaydarTagCloudModel::LinearWeightRole:\n            if (m_maxLogCount == m_minLogCount) {\n                return 1;\n            }\n            return QVariant::fromValue<float>( ( i->m_logCount - m_minLogCount ) / (m_maxLogCount - m_minLogCount));\n\n        case PlaydarTagCloudModel::CountRole:\n            return QVariant::fromValue<int>(i->m_count);\n\n        case PlaydarTagCloudModel::SecondsRole:\n            return QVariant::fromValue<int>(i->m_seconds);\n\n        default:\n            return QVariant();\n    }\n}\n\n\n// virtual\nQModelIndex\nPlaydarTagCloudModel::index( int row, int column, const QModelIndex& parent /*= QModelIndex()*/) const\n{\n    return parent.isValid() || row > m_tagList.count() ?\n        QModelIndex() :\n        createIndex( row, column );\n}\n\nQModelIndex\nPlaydarTagCloudModel::indexOf( const BoffinTagItem& tag )\n{\n\treturn createIndex( m_tagList.indexOf( tag ), 0 );\n}\n\n//virtual\nQModelIndex\nPlaydarTagCloudModel::parent( const QModelIndex& ) const\n{\n    return QModelIndex();\n}\n\n//virtual\nint\nPlaydarTagCloudModel::rowCount( const QModelIndex& p ) const\n{\n    if( p.isValid())\n        return 0;\n\n    return m_tagList.count();\n}\n\n//virtual\nint\nPlaydarTagCloudModel::columnCount( const QModelIndex& p ) const\n{\n    if( p.isValid() )\n        return 0;\n    return 1;\n}\n\nvoid\nPlaydarTagCloudModel::setHostFilter(QSet<QString> hosts)\n{\n    m_hostFilter = hosts;\n//    onTags(m_tags);         // recalc things...\n}\n\nvoid\nPlaydarTagCloudModel::addToHostFilter(const QString& hostname)\n{\n    m_hostFilter.insert(hostname);\n//    onTags(m_tags);\n}\n\nvoid\nPlaydarTagCloudModel::setTagMapping(QMap<QString, QString> tagMap)\n{\n//    m_tagMap = tagMap;\n//    onTags(m_tags);\n}\n\n\nint\nPlaydarTagCloudModel::maxTrackCount() const\n{\n\treturn m_maxTrackCount;\n}\n\n"
  },
  {
    "path": "app/boffin/PlaydarTagCloudModel.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYDAR_TAG_CLOUD_MODEL_H\n#define PLAYDAR_TAG_CLOUD_MODEL_H\n\n#include \"playdar/BoffinTagRequest.h\"\n#include \"playdar/PlaydarApi.h\"\n#include <lastfm/global.h>\n#include <QAbstractItemModel>\n#include <QAbstractTableModel>\n#include <QSet>\n#include <QMap>\n#include <QList>\n#include <QMultiMap>\n\nclass PlaydarConnection;\n\nclass PlaydarTagCloudModel : public QAbstractTableModel\n{\n    Q_OBJECT\n\npublic:\n    enum CustomRoles { WeightRole = Qt::UserRole, LinearWeightRole, CountRole, SecondsRole, RelevanceRole };\n\n    PlaydarTagCloudModel(PlaydarConnection *playdar);\n    ~PlaydarTagCloudModel(void);\n\n    void startGetTags(const QString& rql = QString());\n\n    void setHostFilter(QSet<QString> hosts);            // exclude hosts from tagcloud\n    void addToHostFilter(const QString& hostname);\n    void setTagMapping(QMap<QString, QString> tagMap);  // map tagname -> preferred tagname\n\n    int maxTrackCount() const;\n\n    virtual QModelIndex index( int row, int column, const QModelIndex& parent = QModelIndex()) const;\n    QModelIndex indexOf( const BoffinTagItem& t );\n    virtual QModelIndex parent( const QModelIndex& ) const;\n    virtual int rowCount( const QModelIndex& = QModelIndex() ) const;\n    virtual int columnCount( const QModelIndex& = QModelIndex() ) const;\n    virtual QVariant data( const QModelIndex&, int role = Qt::DisplayRole ) const;\n    virtual bool hasChildren( const QModelIndex& = QModelIndex()) const{ return false; }\n\nsignals:\n\tvoid fetchedTags();\n\tvoid tagItem( const BoffinTagItem& );\n\nprivate slots:\n    void onTag(BoffinTagItem tag);\n    void onTagError();\n    void onFetchedTags();\n\nprivate:\n    PlaydarConnection* m_playdar;\n\n    QSet<QString> m_hostFilter;     // hosts to filter from this tag cloud\n    QSet<QString> m_hosts;          // hosts contributing to this tag cloud\n\n    QList< BoffinTagItem > m_tagListBuffer;\n    QList< BoffinTagItem > m_tagList;\n\n    BoffinTagItem m_tag;    // the last tag provided via onTags\n\n    int m_maxTrackCount;\n    int m_totalTracks;\n    int m_totalDuration;\n\n    float m_maxWeight;\n    float m_maxLogCount;\n    float m_minLogCount;\n//    float m_minLogWeight, m_maxLogWeight;\n\n    class QTimer* m_loadingTimer;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/Playlist.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QTimer>\n#include \"Playlist.h\"\n#include \"playdar/PlaydarConnection.h\"\n#include \"sample/SampleFromDistribution.h\"\n\n\nPlaylist::Playlist(QObject *parent /* = 0 */)\n: QObject(parent)\n{\n}\n\nvoid \nPlaylist::startRequest(const QString& rql, PlaydarConnection* pc)\n{\n    BoffinRqlRequest* req = pc->boffinRql(rql);\n    if (req) {\n        connect(req, SIGNAL(playableItem(BoffinPlayableItem)), SLOT(onItem(BoffinPlayableItem)));\n    }\n}\n\nvoid\nPlaylist::onItem(const BoffinPlayableItem& /*item*/)\n{\n}\n\nvoid\nPlaylist::onAfterDelay()\n{\n}\n\n\n"
  },
  {
    "path": "app/boffin/Playlist.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAY_LIST_H\n#define PLAY_LIST_H\n\n#include <QList>\n#include <QString>\n#include <QObject>\n#include \"playdar/BoffinRqlRequest.h\"\n\nclass PlaydarConnection;\n\ntypedef QList<BoffinPlayableItem> ItemList;\n\nclass Playlist : public QObject\n{\n    Q_OBJECT\n\npublic:\n    Playlist(QObject *parent = 0);\n    void startRequest(const QString& rql, PlaydarConnection* pc);\n\nprivate slots:\n    void onItem(const BoffinPlayableItem& item);\n    void onAfterDelay();\n\nprivate:\n    int m_lastSize;\n\n    ItemList m_playlist;       // shuffled into here\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/PlaylistModel.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlaylistModel.h\"\n\nPlaylistModel::PlaylistModel( QObject* p )\n              :QAbstractItemModel( p ),\n               m_tracks()\n{}\n\n\nint\nPlaylistModel::columnCount( const QModelIndex& parent ) const\n{\n    if( parent.isValid())\n        return 0;\n    else\n        return 4;\n}\n\nint\nPlaylistModel::rowCount( const QModelIndex& parent ) const\n{\n    if( parent.isValid() )\n        return 0;\n    else\n        return m_tracks.size();\n}\n\nQVariant\nPlaylistModel::headerData( int section, Qt::Orientation, int role ) const\n{\n    if( role != Qt::DisplayRole ) return QVariant();\n\n    switch( section )\n    {\n        case 1: return tr( \"Artist\" );\n        case 2: return tr( \"Title\" );\n        case 3: return tr( \"Url\" );\n    }\n\n    return QVariant();\n}\n\n\nQVariant\nPlaylistModel::data( const QModelIndex& index, int role ) const\n{\n    if( index.row() >= m_tracks.size() ||\n        index.column() >= columnCount( index.parent()))\n        return QVariant();\n\n\n    Track t = m_tracks[ index.row() ];\n\n    if( role == UrlRole )\n        return t.url();\n\n    if( role == Qt::DisplayRole ) {\n        switch( index.column() )\n        {\n            case 1: return QString(t.artist());\n            case 2: return t.title();\n            case 3: return t.url().toString();\n        }\n    }\n\n    return QVariant();\n}\n\nQModelIndex\nPlaylistModel::index( int row, int column, const QModelIndex& p) const\n{\n    if ( row < m_tracks.size() &&\n         column < columnCount(p) &&\n         !p.isValid() )\n    {\n        return createIndex( row, column );\n    }\n    else\n    {\n        return  QModelIndex();\n    }\n\n}\n\nvoid\nPlaylistModel::addTracks( QList< Track > tracks )\n{\n    if( !tracks.isEmpty() )\n    {\n        beginInsertRows( QModelIndex(), m_tracks.size(), m_tracks.size() + tracks.size() -1 );\n        m_tracks <<  tracks;\n        endInsertRows();\n    }\n}\n\nvoid\nPlaylistModel::addTrack( Track t )\n{\n\tQList< Track > tl;\n\ttl << t;\n\taddTracks( tl );\n}\n\nvoid\nPlaylistModel::clear()\n{\n    if (m_tracks.size()) {\n        beginRemoveRows( QModelIndex(), 0, m_tracks.size() -1 );\n        m_tracks.clear();\n        endRemoveRows();\n    }\n}\n\n"
  },
  {
    "path": "app/boffin/PlaylistModel.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYLIST_MODEL_H_\n#define PLAYLIST_MODEL_H_\n\n#include <QAbstractItemModel>\n#include <types/Track.h>\n\nclass PlaylistModel : public QAbstractItemModel\n{\nQ_OBJECT\npublic:\n    enum ItemDataRole{ UrlRole = Qt::UserRole };\n\n    PlaylistModel( QObject* p = 0 );\n    virtual int columnCount( const QModelIndex& parent = QModelIndex()) const;\n    virtual int rowCount( const QModelIndex& parent = QModelIndex() ) const;\n\n    virtual QVariant headerData( int section, Qt::Orientation, int role = Qt::DisplayRole ) const;\n    virtual QVariant data( const QModelIndex& index, int role ) const;\n\n    virtual QModelIndex index( int row, int column, const QModelIndex& p = QModelIndex()) const;\n\n    virtual QModelIndex parent( const QModelIndex& ) const\n    { return QModelIndex(); }\n\n\npublic slots:\n    void addTracks( QList< Track > tracks );\n    void addTrack( Track t );\n    void clear();\n\n\nprivate:\n    QList< Track > m_tracks;\n};\n\n#endif //PLAYLIST_MODEL_H_\n"
  },
  {
    "path": "app/boffin/PlaylistWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYLIST_WIDGET_H_\n#define PLAYLIST_WIDGET_H_\n\n#include <QTreeView>\n#include \"PlaylistModel.h\"\n#include \"playdar/PlaydarConnection.h\"\n#include \"playdar/BoffinTagRequest.h\"\n#include \"TrackSource.h\"\n\nclass PlaylistWidget: public QTreeView {\n\n    Q_OBJECT\n\npublic:\n\tPlaylistWidget(PlaydarConnection* playdar, QWidget* p = 0) :\n\t\tQTreeView(p), m_playdar(playdar) {\n\t\tsetModel(&m_model);\n\t\tsetAlternatingRowColors(true);\n\t\tconnect(this, SIGNAL( doubleClicked(QModelIndex)),\n\t\t\t\tSLOT( onDoubleClicked(QModelIndex)));\n\t}\n\npublic slots:\n\tvoid loadFromRql(QString rql) {\n\t}\n\nsignals:\n\tvoid play(const QUrl&);\n\nprivate slots:\n\tvoid onDoubleClicked(const QModelIndex& index) {\n\t\tqDebug() << \"Play: \"\n\t\t\t\t<< index.data(PlaylistModel::UrlRole).toUrl().toString();\n\t\temit play(index.data(PlaylistModel::UrlRole).toUrl());\n\t}\n\nprivate:\n\tPlaydarConnection* m_playdar;\n\tPlaylistModel m_model;\n};\n\n#endif //PLAYLIST_WIDGET_H_\n"
  },
  {
    "path": "app/boffin/ScanProgressWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ScanProgressWidget.h\"\n#include <lastfm/ws.h>\n#include <types/Track.h>\n#include <QtGui>\n#include <QtNetwork>\n\n/** all quite messy, apologies --mxcl */\n\n#define MAX_IMAGE_COUNT 15\n\n\nScanProgressWidget::ScanProgressWidget()\n{\n    m_done = false;\n    m_artist_count = 0;\n    m_track_count = 0;\n\n    (new QBasicTimer)->start( 20, this );\n    \n    setBackgroundRole( QPalette::Base );\n    setAutoFillBackground( true );\n    setAttribute( Qt::WA_MacShowFocusRect, false );\n    setAttribute( Qt::WA_MacSmallSize );\n}\n\n\nvoid\nScanProgressWidget::onNewDirectory( const QString& directory )\n{\n    paths += directory;\n    if (paths.size() > 60) paths.pop_front();\n    update();\n}\n\n\nvoid\nScanProgressWidget::onNewTrack( const Track& t )\n{\n    int& i = count( t.artist() );\n    i++;\n\n    m_artist_count = track_counts.size();\n    m_track_count++;\n\n    updateStatusMessage();\n\n    if (t.url().isValid()) {\n        paths += t.url().path();\n        // so this is a time saving way to keep the list the size of the screen\n        // it goes over a bit almost certainly, but it's ok\n        if (paths.size() > 60)\n            paths.pop_front();\n    }\n    \n    if (i == 1 && images.size() < MAX_IMAGE_COUNT) {\n        QObject* o = new ImageFucker( t.artist() );\n        connect( o, SIGNAL(fucked()), SLOT(onImageFucked()) );\n        o->setParent( this );\n    }\n}\n\nvoid\nScanProgressWidget::onFinished()\n{\n    m_done = true;\n    updateStatusMessage();\n    repaint();\n}\n\n\nvoid\nScanProgressWidget::paintEvent( QPaintEvent* )\n{\n    QPainter p( this );    \n    int y = height() - 6;\n\n    p.setPen( Qt::lightGray );\n    foreach (QString const path, paths)\n    {\n        y -= 18;\n        p.drawText( 6, y, path );\n    }\n\n    for (int i = 0; i < images.count(); ++i)\n    {\n        p.setRenderHint( QPainter::Antialiasing );\n        p.setRenderHint( QPainter::SmoothPixmapTransform );\n\n        int y = (images[i]->y * (height() - images[i]->pixmap.height())) / 1000;\n\n        QPointF pt( width() - images[i]->x, y );\n\n        p.setOpacity( images[i]->opacity );\n        p.drawImage( pt, images[i]->pixmap );\n\n        QRectF rect( pt.x(), y + (images[i]->pixmap.height() * 0.75) + 4, images[i]->pixmap.width(), height() );\n        QString text = images[i]->artist;\n        text = p.fontMetrics().elidedText( text, Qt::ElideRight, rect.width() );\n\n        int const n = count( images[i]->artist );\n        text += \"\\n\" + (n == 1 ? tr(\"1 track\") : tr( \"%L1 tracks\" ).arg( n ));\n\n        p.setPen( Qt::black );\n        p.drawText( rect, Qt::AlignTop | Qt::AlignHCenter, text );\n    }\n}\n\n\nvoid\nScanProgressWidget::timerEvent( QTimerEvent* )\n{\n    QList<int> remove;\n    \n    for (int i = 0; i < images.count(); ++i)\n    {   \n        int steps = images[i]->steps;\n        \n        images[i]->opacity = float(steps > 100 ? 200 - steps : steps) / 100.0f;        \n\n#ifdef Q_WS_WIN\n        // 0.5 pixel movements chug on windows\n        images[i]->x += 1;\n#else\n        // 0.5 pixel movements look great on mac\n        images[i]->x += 0.5;\n#endif\n\n        images[i]->steps++;\n\n        if (steps == 200) remove.prepend( i );\n    }\n    \n    bool needUpdate = images.count();\n\n    foreach (int i, remove)\n        images.takeAt( i )->deleteLater();\n\n    if (needUpdate)\n        update();\n}\n\n\nvoid\nScanProgressWidget::onImageFucked()\n{\n    ImageFucker* fucker = (ImageFucker*)sender();\n    fucker->x = rand() % width();\n    images += fucker;\n}\n\nvoid\nScanProgressWidget::updateStatusMessage()\n{\n    QString text;\n\n    if (m_artist_count != 0 && m_track_count != 0)\n    {\n        text = tr(\"Found %L1 artists and %L2 tracks\").arg( m_artist_count ).arg( m_track_count );\n        if (m_done) text.prepend( tr(\"Scanning complete. \") );\n    }\n    else\n        text = tr(\"Scanning...\");\n\n    emit statusMessage(text);\n    //p.drawText( 6, height() - 6, text );\n}\n\n\nvoid\nImageFucker::onArtistGotInfo()\n{\n    QUrl url = Artist::getInfo( (QNetworkReply*)sender() ).imageUrl();\n    QNetworkReply* reply = lastfm::nam()->get( QNetworkRequest(url) );\n    connect( reply, SIGNAL(finished()), SLOT(onImageDownloaded()) );\n}\n\n\nstatic inline QImage reflect0rize( const QImage& in )\n{\n    const int H = in.height() / 3;\n    \n    QImage r = QImage( in.width(), in.height() + H, QImage::Format_ARGB32_Premultiplied );\n    \n\tQImage in2 = in;\n\tin2.convertToFormat( QImage::Format_ARGB32_Premultiplied );\n    \n    QImage reflection = in.copy( 0, in.height() - H, in.width(), H );\n    reflection = reflection.mirrored( false, true /*vertical only*/ );\n    \n    QPainter p( &r );\n    p.drawImage( 0, 0, in2 );\n    p.drawImage( 0, in.height(), reflection );\n\n    QLinearGradient g( QPointF( 0, 0 ), QPointF( 0, 1 ) );\n    g.setCoordinateMode( QGradient::ObjectBoundingMode );\n    g.setColorAt( 0, QColor(0, 0, 0, 100) );\n    g.setColorAt( 1, Qt::transparent );\n\n    p.setRenderHint( QPainter::Antialiasing );\n    p.setRenderHint( QPainter::SmoothPixmapTransform );\n\n    p.setCompositionMode( QPainter::CompositionMode_DestinationIn );\n    p.fillRect( QRectF( QPointF( 0, in.height() ), QSizeF( r.width(), H ) ), g );\n    return r;\n}\n\n\nvoid\nImageFucker::onImageDownloaded()\n{\n    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());\n    QByteArray const data = reply->readAll();\n\n    QImage in;\n    in.loadFromData( data );\n\n    height = in.height();\n    pixmap = reflect0rize( in );\n\n    y = rand() % 1000;\n\n    emit fucked();\n}\n\n"
  },
  {
    "path": "app/boffin/ScanProgressWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QWidget>\n#include <types/Track.h>\n#include <QGLWidget>\n#include <QHash>\n/** @author Max Howell <max@last.fm> */\n\n\nclass ImageFucker : public QObject\n{\n    Q_OBJECT\n\npublic:\n    ImageFucker( const Artist& artist )\n    {\n        this->steps = 0;\n        this->height = 0;\n        this->x = this->opacity = 0;\n        this->artist = artist;\n        \n        connect( (QObject*)artist.getInfo(), SIGNAL(finished()), SLOT(onArtistGotInfo()) );\n    }\n    \n    QImage pixmap;\n    QString artist;\n    qreal x;\n    qreal opacity;\n    uint height;\n    int y;\n    int steps;\n\nsignals:\n    void fucked();\n\nprivate slots:\n    void onArtistGotInfo();\n    void onImageDownloaded();\n};\n\n \nclass ScanProgressWidget :\n#ifdef Q_WS_WIN\n    public QWidget\n#else\n    public QGLWidget\n#endif\n{\n    Q_OBJECT\n\n    bool m_done;\n    uint m_artist_count;\n    uint m_track_count;\n\n    QList<ImageFucker*> images;\n    QStringList paths;\n    QHash<QString, int> track_counts;\n\n    int& count( const Artist& artist ) { return track_counts[ artist.name().toLower() ]; }\n\npublic:\n    ScanProgressWidget();\n\n    virtual void paintEvent( QPaintEvent* );\n    virtual void timerEvent( QTimerEvent* );\n\nsignals:\n    void statusMessage( QString );\n\npublic slots:\n    void onNewDirectory( const QString& );\n    void onNewTrack( const Track& );\n    void onFinished();\n\nprivate slots:\n    void onImageFucked();\n\nprivate:\n    void updateStatusMessage();\n};\n"
  },
  {
    "path": "app/boffin/ScrobSocket.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ScrobSocket.h\"\n#include <QThread>\n#include <QHostAddress>\n#include <QUrl>\n#include <QTextStream>\n\nstatic int const kDefaultPort = 33367;\n \n\nScrobSocket::ScrobSocket( QObject* parent ) : QTcpSocket( parent )\n{\n    connect( this, SIGNAL(readyRead()), SLOT(onReadyRead()) );    \n    connect( this, SIGNAL(error( QAbstractSocket::SocketError )), SLOT(onError( QAbstractSocket::SocketError )) );\n    connect( this, SIGNAL(connected()), SLOT(onConnected()) );\n    connect( this, SIGNAL(disconnected()), SLOT(onDisconnected()) );\n    transmit( \"INIT c=bof\\n\" );\n}\n\n\nScrobSocket::~ScrobSocket()\n{\n    if (!m_track.isNull()) stop();\n}\n\n\nvoid\nScrobSocket::transmit( const QString& data )\n{\n    m_msgQueue.enqueue( data );\n    qDebug() << \"Connection state == \" << state();\n    if( state() == QAbstractSocket::UnconnectedState )\n        connectToHost( QHostAddress::LocalHost, kDefaultPort );\n}\n\n\nvoid \nScrobSocket::onConnected()\n{\n    if( !m_msgQueue.empty() )\n    {\n        qDebug() << m_msgQueue.head().trimmed();\n        write( m_msgQueue.takeFirst().toUtf8());\n    }\n}\n\n\nvoid \nScrobSocket::onDisconnected()\n{\n    if( !m_msgQueue.empty())\n        connectToHost( QHostAddress::LocalHost, kDefaultPort );\n}\n\n\nvoid\nScrobSocket::onError( SocketError error )\n{\n    switch (error)\n    {\n        case SocketTimeoutError:\n            // TODO look, really we should store at least one start message forever\n            // then if last time we didn't connect and this time it's a pause we \n            // send the start first\n            m_msgQueue.clear();\n            break;\n        \n        case RemoteHostClosedError:\n            // expected\n            break;\n        \n        default: // may as well\n            qDebug() << lastfm::qMetaEnumString<QAbstractSocket>( error, \"SocketError\" );\n        case ConnectionRefusedError: // happens if client isn't running\n            break;\n    }\n}\n\n\nstatic inline QString encodeAmp( QString data )\n{ \n    return data.replace( '&', \"&&\" );\n}\n\n\nvoid\nScrobSocket::start( const Track& t )\n{\n    m_track = t;\n    transmit( \"START c=bof\" \"&\"\n                    \"a=\" + encodeAmp( t.artist() ) + \"&\"\n                    \"t=\" + encodeAmp( t.title() ) + \"&\"\n                    \"b=\" + encodeAmp( t.album() ) + \"&\"\n                    \"l=\" + QString::number( t.duration() ) + \"&\"\n                    \"p=\" + encodeAmp( t.url().path() ) + '\\n' );\n}\n\n\nvoid\nScrobSocket::pause()\n{\n    transmit( \"PAUSE c=bof\\n\" );\n}\n\n\nvoid\nScrobSocket::resume()\n{\n    transmit( \"RESUME c=bof\\n\" );\n}\n\n\nvoid\nScrobSocket::stop()\n{\n    transmit( \"STOP c=bof\\n\" );\n}\n\n\nvoid\nScrobSocket::onReadyRead()\n{\n    QByteArray bytes = readAll();\n    if (bytes != \"OK\\n\") qWarning() << bytes.trimmed();\n    disconnectFromHost();\n}\n"
  },
  {
    "path": "app/boffin/ScrobSocket.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SCROB_SOCKET_H\n#define SCROB_SOCKET_H\n\n#include <lastfm/global.h>\n#include <types/Track.h>\n#include <QTcpSocket>\n#include <QQueue>\n\n/** @author Christian Muehlhaeuser <chris@last.fm>\n  * @contributor Erik Jaelevik <erik@last.fm>\n  * @rewrite Max Howell <max@last.fm>\n  */\nclass ScrobSocket : public QTcpSocket\n{\n    Q_OBJECT\n\npublic:\n    ScrobSocket( QObject* parent );\n    ~ScrobSocket();\n\npublic slots:\n    void start( const Track& );\n    void pause();\n    void resume();\n    void stop();\n\nprivate slots:\n    void transmit( const QString& data );\n    void onError( QAbstractSocket::SocketError );\n    void onReadyRead();\n    void onConnected();\n    void onDisconnected();\n\nprivate:    \n    Track m_track;\n    QQueue<QString> m_msgQueue;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/Shuffler.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"Shuffler.h\"\n\n\n////////////////////////////////////////////////////////////////////////\n\n\n// lifted from playdar\nint levenshtein(const QString& source, const QString& target) \n{\n  // Step 1\n  const int n = source.length();\n  const int m = target.length();\n  if (n == 0) {\n    return m;\n  }\n  if (m == 0) {\n    return n;\n  }\n  // Good form to declare a TYPEDEF\n  typedef std::vector< std::vector<int> > Tmatrix; \n  Tmatrix matrix(n+1);\n  // Size the vectors in the 2.nd dimension. Unfortunately C++ doesn't\n  // allow for allocation on declaration of 2.nd dimension of vec of vec\n  for (int i = 0; i <= n; i++) {\n    matrix[i].resize(m+1);\n  }\n  // Step 2\n  for (int i = 0; i <= n; i++) {\n    matrix[i][0]=i;\n  }\n  for (int j = 0; j <= m; j++) {\n    matrix[0][j]=j;\n  }\n  // Step 3\n  for (int i = 1; i <= n; i++) {\n    const QChar s_i = source[i-1];\n    // Step 4\n    for (int j = 1; j <= m; j++) {\n      const QChar t_j = target[j-1];\n      // Step 5\n      int cost;\n      if (s_i == t_j) {\n        cost = 0;\n      }\n      else {\n        cost = 1;\n      }\n      // Step 6\n      const int above = matrix[i-1][j];\n      const int left = matrix[i][j-1];\n      const int diag = matrix[i-1][j-1];\n      //int cell = min( above + 1, min(left + 1, diag + cost));\n      int cell = (((left+1)>(diag+cost))?diag+cost:left+1);\n      if(above+1 < cell) cell = above+1;\n      // Step 6A: Cover transposition, in addition to deletion,\n      // insertion and substitution. This step is taken from:\n      // Berghel, Hal ; Roach, David : \"An Extension of Ukkonen's \n      // Enhanced Dynamic Programming ASM Algorithm\"\n      // (http://www.acm.org/~hlb/publications/asm/asm.html)\n      if (i>2 && j>2) {\n        int trans=matrix[i-2][j-2]+1;\n        if (source[i-2]!=t_j) trans++;\n        if (s_i!=target[j-2]) trans++;\n        if (cell>trans) cell=trans;\n      }\n      matrix[i][j]=cell;\n    }\n  }\n  // Step 7\n  return matrix[n][m];\n}\n\n\nfloat\nnormalisedLevenshtein(const BoffinPlayableItem& a, const BoffinPlayableItem& b)\n{\n    // logic lifted from playdar's Resolver::calculate_score\n    // not yet comparing album titles\n\n    using namespace boost;\n    // original names from the query:\n    QString o_art = a.artist().simplified().toLower();\n    QString o_trk = a.track().simplified().toLower();\n\n    // names from candidate result:\n    QString art = b.artist().simplified().toLower();\n    QString trk = b.track().simplified().toLower();\n\n    // short-circuit for exact match\n    if (o_art == art && o_trk == trk) return 1.0;\n\n    // the real deal, with edit distances:\n    int trked = levenshtein(trk, o_trk);\n    int arted = levenshtein(art, o_art);\n\n    // tolerances:\n    const float tol_art = 1.5;\n    const float tol_trk = 1.5;\n    \n    // names less than this many chars aren't dismissed based on % edit-dist:\n    const int grace_len = 6; \n    \n    // if % edit distance is greater than tolerance, fail them outright:\n    if( o_art.length() > grace_len && arted > o_art.length()/tol_art )\n        return 0.0;\n\n    if( o_trk.length() > grace_len && trked > o_trk.length()/tol_trk )\n        return 0.0;\n\n    // if edit distance longer than original name, fail them outright:\n    if( arted >= o_art.length() )\n        return 0.0;\n\n    if( trked >= o_trk.length() )\n        return 0.0;\n    \n    // combine the edit distance of artist & track into a final score:\n    float artdist_pc = (o_art.length()-arted) / (float) o_art.length();\n    float trkdist_pc = (o_trk.length()-trked) / (float) o_trk.length();\n    return artdist_pc * trkdist_pc;\n}\n\n\n////////////////////////////////////////////////////////////////////////\n\n\nShuffler::Shuffler(QObject* parent /* = 0 */)\n: QObject(parent)\n, m_artistHistorySize(4)        // to mix up the artists\n, m_songHistorySize(100)        // to suppress dup songs\n{\n}\n\nBoffinPlayableItem \nShuffler::sampleOne()\n{\n    BoffinPlayableItem result = sample();\n    if (result.isValid()) {\n        // artist memory\n        m_artistHistory.push_back(result.artist());\n        while (m_artistHistory.size() > m_artistHistorySize) {\n            m_artistHistory.pop_front();\n        }\n        // track memory\n        m_songHistory.push_back(result);\n        while (m_songHistory.size() > m_songHistorySize) {\n            m_songHistory.pop_front();\n        }\n    }\n    return result;\n}\n\nconst Shuffler::ItemList& \nShuffler::items()\n{\n    return m_items;\n}\n\nvoid \nShuffler::setArtistHistorySize(unsigned size)\n{\n    m_artistHistorySize = size;\n}\n\nvoid\nShuffler::clear()\n{\n    m_items.clear();\n}\n\nvoid\nShuffler::clearHistory()\n{\n    m_artistHistory.clear();\n    m_songHistory.clear();\n}\n\nbool orderByWorkingWeightDesc(const BoffinPlayableItem& a, const BoffinPlayableItem& b)\n{\n    return a.workingweight() > b.workingweight();\n}\n\n// pull out a single item\nBoffinPlayableItem\nShuffler::sample()\n{\n    BoffinPlayableItem result;\n\n    if (m_items.size()) {\n        ItemList::iterator begin = m_items.begin();\n        ItemList::iterator end = m_items.end();\n        ItemList::iterator it;\n\n        // reweight:\n        float totalWeight = 0;\n        for (it = begin; it != end; it++) {\n            it->workingweight() = it->weight() * pushdown(*it);\n            totalWeight += it->workingweight();\n        }\n        // normalise weights, sum to 1\n        for (it = begin; it != end; it++) {\n            it->workingweight() /= totalWeight;\n        }\n        qSort(begin, end, orderByWorkingWeightDesc);\n\n        ItemList::iterator sample = m_sampler.singleSample(begin, end, true);\n        result = *sample;\n        m_items.removeAt(sample - begin);\n    }\n\n    return result;\n}\n\n\nfloat \nShuffler::pushdown(const BoffinPlayableItem& item)\n{\n    return pushdownSong(item) * \n        (m_artistHistory.contains(item.artist(), Qt::CaseInsensitive) ? 0.00001 : 1.0);\n}\n\n\nfloat\nShuffler::pushdownSong(const BoffinPlayableItem& item)\n{\n    int i = 1;\n    float result = 1.0;\n    foreach(const BoffinPlayableItem& historicItem, m_songHistory) {\n        float nl = normalisedLevenshtein(item,  historicItem);\n        // levenshtein values not very reliable when less than 0.5\n        if (nl > 0.5) {\n            float score = 0.1 * (nl * i / (float) m_songHistorySize);\n            if (score < result) {\n                result = score;\n            }\n        }\n        i++;\n    }\n    return result;\n}\n\nvoid \nShuffler::receivePlayableItem(BoffinPlayableItem item)\n{\n    m_items.push_back(item);\n}"
  },
  {
    "path": "app/boffin/Shuffler.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SHUFFLER_H\n#define SHUFFLER_H\n\n#include <QStringList>\n#include \"playdar/BoffinPlayableItem.h\"\n#include \"sample/SampleFromDistribution.h\"\n\n\nclass Shuffler : public QObject\n{\n    Q_OBJECT\n\npublic:\n    typedef QList<BoffinPlayableItem> ItemList;\n\n    Shuffler(QObject* parent = 0);\n    BoffinPlayableItem sampleOne();\n    const ItemList& items();\n    void setArtistHistorySize(unsigned size);\n    void setSongHistorySize(unsigned size);\n    void clear();\n    void clearHistory();\n\npublic slots:\n    void receivePlayableItem(BoffinPlayableItem item);\n\nprivate:\n    BoffinPlayableItem sample();\n    void result(const BoffinPlayableItem& item);\n    float pushdown(const BoffinPlayableItem& item);\n    float pushdownSong(const BoffinPlayableItem& item);\n\n    struct AccessPolicy\n    {\n        float operator()(const QList<BoffinPlayableItem>::const_iterator& el) const\n        { \n            return el->workingweight(); \n        }\n    };\n\n    struct CopyPolicy\n    {\n       template <typename IT>\n       BoffinPlayableItem operator()(IT& it) const\n       {\n          return *it;\n       }\n\n       template <typename IT>\n       const BoffinPlayableItem operator()(const IT& it) const\n       {\n          return *it;\n       }\n    };\n\n\n    fm::last::algo::ListBasedSampler<AccessPolicy, CopyPolicy> m_sampler;\n    ItemList m_items;               // items arrive here\n    QStringList m_artistHistory;\n    int m_artistHistorySize;\n    QList<BoffinPlayableItem> m_songHistory;\n    int m_songHistorySize;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/TagBrowserWidget.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QWidget>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QItemSelectionModel>\n#include <QSlider>\n#include <QLabel>\n#include \"TagBrowserWidget.h\"\n#include \"TagCloudView.h\"\n#include \"PlaydarTagCloudModel.h\"\n#include \"TagDelegate.h\"\n#include \"HistoryWidget.h\"\n#include \"PlaylistWidget.h\"\n#include \"PlaylistModel.h\"\n\nTagBrowserWidget::TagBrowserWidget(PlaydarConnection* playdar, QWidget* parent) :\n\tQWidget(parent),\n    m_playdar(playdar)\n{\n\tm_tagCloudModel = new PlaydarTagCloudModel(playdar);\n    m_filter = new RelevanceFilter();\n    m_filter->setSourceModel(m_tagCloudModel);\n\n\tQVBoxLayout* vlayout = new QVBoxLayout(this);\n\n\tQWidget* w = new QWidget(this);\n\n\tm_rqlSentence = new QLabel( this );\n\tvlayout->addWidget( m_rqlSentence );\n\t\n\tm_view = new TagCloudView(w);\n\tm_view->setModel(m_filter);\n\n    connect(m_tagCloudModel, SIGNAL(tagItem(BoffinTagItem)), m_view, SLOT(onTag(BoffinTagItem)));\n    connect(m_tagCloudModel, SIGNAL(fetchedTags()), m_view, SLOT(onFetchedTags()));\n\n\tm_view->setItemDelegate(new TagDelegate);\n\tconnect(m_view->selectionModel(),\n\t\t\tSIGNAL(selectionChanged(QItemSelection, QItemSelection)),\n\t\t\tSLOT(onSelectionChanged(QItemSelection, QItemSelection)));\n\tvlayout->addWidget(m_view);\n\n\tm_tagCloudModel->startGetTags();\n\n\tthis->setLayout(vlayout);\n}\n\nQStringList\nTagBrowserWidget::selectedTags() const\n{\n\tQStringList tags;\n    foreach(const QModelIndex& i, m_view->selectionModel()->selectedIndexes()) {\n    \ttags << i.data().toString();\n    }\n    return tags;\n}\n\nQString \nTagBrowserWidget::rql() const\n{\n    QString r;\n    foreach( QString s, m_rql )\n    {\n        if( s == \"and\" || s == \"or\" ) {\n            r += \" \" + s + \" \";\n            continue;\n        }\n        r += \"tag:\\\"\" + s + \"\\\"\";\n    }\n    return r;\n}\n\nQString\nTagBrowserWidget::human() const\n{\n    return m_rql.join( \" \" );\n}\n\nvoid TagBrowserWidget::onSelectionChanged(const QItemSelection& selected,\n\t\tconst QItemSelection& deselected)\n{\n\n    if( !selected.isEmpty() )\n    {\n        //New Tag Selected\n        \n        const QModelIndex selectedIndex = selected.last().topLeft();\n        \n        if( !m_rql.isEmpty() ) {\n            if( qFuzzyCompare( 0.0f, selectedIndex.data( PlaydarTagCloudModel::RelevanceRole ).value<float>() ) ) {\n                m_rql << \"or\";\n            } else {\n                m_rql << \"and\";\n            }\n        }\n        m_rql << selectedIndex.data().toString();\n    }\n    \n    else if( !deselected.isEmpty() )\n    {\n        //Tag DeSelected\n        \n        const QModelIndex deSelectedIndex = deselected.last().topLeft();\n        \n        int i = m_rql.indexOf( deSelectedIndex.data().toString() );\n        if( i == 0 ) {\n            m_rql.removeAt( 0 );\n            m_rql.removeAt( 0 );\n        } else {\n            m_rql.removeAt( i );\n            m_rql.removeAt( i-1 );\n        }\n        \n        qDebug() << \"Deselecting: \" << deSelectedIndex.data().toString();\n    }\n\n    qDebug() << \"filtering: \" << rql();\n        \n    m_filter->setRqlFilter(m_playdar, rql(), m_view->selectionModel()->selectedIndexes());\n \n    m_rqlSentence->setText( human() );\n    \n//    ((PlaylistModel*)m_playlistWidget->model())->clear();\n//    m_playlistWidget->loadFromRql(rql);\n\n    emit selectionChanged();\n}\n\nvoid\nTagBrowserWidget::onFilterClicked()\n{\n    // toggle the filter:\n    m_filter->showRelevant(m_filter->showingAll());\n}\n\nvoid\nTagBrowserWidget::onSliderChanged( int val )\n{\n\tm_filter->setMinimumTrackCountFilter( val );\n}\n"
  },
  {
    "path": "app/boffin/TagBrowserWidget.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TAG_BROWSER_WIDGET_H\n#define TAG_BROWSER_WIDGET_H\n\n#include <math.h>\n#include <float.h>\n#include <boost/function.hpp>\n#include <QStringList>\n#include <QWidget>\n\nclass QItemSelection;\nclass TagCloudView;\nclass PlaydarTagCloudModel;\nclass SideBySideLayout;\nclass HistoryWidget;\nclass PlaydarConnection;\nclass PlaylistModel;\nclass PlaylistWidget;\n\n#include \"playdar/PlaydarConnection.h\"\n#include \"PlaydarTagCloudModel.h\"\n#include <QSortFilterProxyModel>\n#include <float.h>\n#include <math.h>\n\nclass RelevanceFilter : public QSortFilterProxyModel\n{\n    Q_OBJECT;\n\npublic:\n    RelevanceFilter()\n        :m_req(0)\n        ,m_showAll( true )\n        ,m_minimumTrackCountFilter( 0 )\n        ,m_maxTrackCount( 0 )\n    {\n    }\n\n    void resetFilter()\n    {\n        m_logCountMap.clear();\n        m_showAll = true;\n        invalidateFilter();\n    }\n\n    void setRqlFilter(PlaydarConnection* playdar, QString rql, QModelIndexList selected)\n    {\n        if (rql.length() == 0) {\n            resetFilter();\n            return;\n        }\n\n        m_countMap.clear();\n        m_logCountMap.clear();\n\n\n        m_minTrackCount = FLT_MAX;\n        m_maxTrackCount = FLT_MIN;\n        \n        if (m_req) {\n            m_req->disconnect(this);\n        }\n        m_req = playdar->boffinTagcloud( rql );\n        connect(m_req, SIGNAL(tagItem(BoffinTagItem)), SLOT(onTagItem(BoffinTagItem)));\n\n        invalidateFilter();\n    }\n\n    void setMinimumTrackCountFilter( int i = 0 )\n    {\n        m_minimumTrackCountFilter = i;\n        invalidateFilter();\n    }\n\n    void showRelevant(bool bShowRelevant)\n    {\n        if (bShowRelevant == m_showAll) {\n            m_showAll = !m_showAll;\n            invalidateFilter();\n        }\n    }\n\n    bool showingRelevant()\n    {\n        return !m_showAll;\n    }\n\n    bool showingAll()\n    {\n        return m_showAll;\n    }\n\nprotected:\n    virtual bool filterAcceptsRow(int source_row, const QModelIndex & source_parent) const\n    {\n        if( m_logCountMap.isEmpty() && sourceModel()->index(source_row, 0, source_parent)\n                                    .data( PlaydarTagCloudModel::CountRole ).toInt() < m_minimumTrackCountFilter )\n            return false;\n\n        if( !m_logCountMap.isEmpty() &&\n            m_logCountMap[sourceModel()->index(source_row, 0, source_parent)\n                                    .data().toString()] < m_minimumTrackCountFilter )\n            return false;\n\n\n        if (m_showAll)\n            return true;\n\n        QModelIndex i = sourceModel()->index(source_row, 0, source_parent);\n        const QString tagname = i.data().toString();\n        return m_logCountMap.contains(tagname);\n    }\n\n    // we own the RelevanceRole.  :)\n    virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const\n    {\n        if (role == PlaydarTagCloudModel::RelevanceRole) {\n          if( m_logCountMap.isEmpty()) return 0.0;\n\n            const QString tagname = mapToSource(index).data().toString();\n            QMap<QString, qreal>::const_iterator i = m_logCountMap.find(tagname);\n            \n            qreal result;\n            \n            // A relevance weight will be returned with a value of min < result < max \n            // or 0.0 if there is absolutely no relevance.\n            const float min = 0.2f;\n            const float max = 0.8f;\n            \n            //TODO: relevance = 0 where trackCount >= current selected trackCount\n            if (i == m_logCountMap.end()) {\n                result = 0;\n            } else if (m_maxTrackCount == m_minTrackCount) {\n                result = max;\n            } else {\n                const qreal lc = i.value();\n                result = min + (( lc - m_minTrackCount ) / ( m_maxTrackCount - m_minTrackCount ) * (max - min));\n            }\n            return QVariant::fromValue<float>(result);\n            \n        } else if( role == Qt::ToolTipRole ) {\n            int count = 0;\n            int duration = 0;\n\n            QModelIndex srcindex( mapToSource(index) );\n\n            //if no tags are selected then display the total track count per tag\n            if( m_logCountMap.isEmpty() )\n            {\n                count = srcindex.data( PlaydarTagCloudModel::CountRole ).toInt();\n                duration = srcindex.data( PlaydarTagCloudModel::SecondsRole ).toInt();\n            }\n\n            //otherwise calculate the resultant track count based on currently selected tags\n            const QString tagname = mapToSource(index).data().toString();\n            QMap<QString, int>::const_iterator i = m_countMap.find(tagname);\n\n            if( i != m_countMap.end()) {\n                count = i.value();\n            }\n\n            return count > 0 ? tr( \"%L1 tracks\" ).arg( count ) + formatDuration(duration)\n                             : tr( \"no tracks\" );\n        }\n\n        return QSortFilterProxyModel::data(index, role);\n    }\n\n    static QString formatDuration(int seconds)\n    {\n        if (seconds == 0)\n            return QString();\n\n        int mins = seconds / 60;\n        int hours = mins / 60;\n        if (hours >= 48) {\n            return QString(\" : %1 days %2:%3:%4\")\n                .arg(hours / 24)\n                .arg(hours % 24)\n                .arg(mins % 60, 2, 10, QChar('0'))\n                .arg(seconds % 60, 2, 10, QChar('0'));\n        } else if (hours >= 24) {\n            return QString(\" : 1 day %1:%2:%3\")\n                .arg(hours % 24)\n                .arg(mins % 60, 2, 10, QChar('0'))\n                .arg(seconds % 60, 2, 10, QChar('0'));\n        } else if (hours >= 1) {\n            return QString(\" : %1:%2:%3\")\n                .arg(hours)\n                .arg(mins % 60, 2, 10, QChar('0'))\n                .arg(seconds % 60, 2, 10, QChar('0'));\n        }\n\n        return QString(\" : %1:%2\")\n            .arg(mins)\n            .arg(seconds % 60, 2, 10, QChar('0'));\n    }\n\nprivate slots:\n    void onTagItem(const BoffinTagItem& tagitem)\n    {\n        const QString& tag = tagitem.m_name;\n        if( tagitem.m_count == 0 )\n            return;\n        \n        if (insertTag(tag, tagitem.m_count)) {\n            invalidateFilter();\n        }\n\n        // potentially, all our data (ie: the RelevanceRole) has changed\n        emit dataChanged(\n            this->mapFromSource(sourceModel()->index(0, 0)),\n            this->mapFromSource(sourceModel()->index(sourceModel()->rowCount(), 0)));\n    }\n\n    // returns true if the tag is new, false if the tag already existed\n    bool insertTag(const QString& tag, int count)\n    {\n        bool result;\n        if (m_logCountMap.contains(tag)) {\n            m_countMap[tag] += count;\n            //log is not a distributive function so need to log total count\n            m_logCountMap[tag] = log( (float) m_countMap[tag] );\n            result = false;\n        } else {\n            m_logCountMap[tag] = log( (float) count );\n            m_countMap[ tag ] = count;\n            result = true;\n        }\n\n        m_minTrackCount = qMin( m_minTrackCount, m_logCountMap[ tag ] );\n        m_maxTrackCount = qMax( m_maxTrackCount, m_logCountMap[ tag ] );\n        \n        return result;\n    }\n\nprivate:\n    BoffinTagRequest* m_req;\n    bool m_showAll;\n    int m_minimumTrackCountFilter;\n    qreal m_maxTrackCount;\n    qreal m_minTrackCount;\n    QMap<QString, int> m_countMap;\n    QMap<QString, qreal> m_logCountMap;\n};\n\n\nclass TagBrowserWidget : public QWidget\n{\n    Q_OBJECT\n\npublic:\n    TagBrowserWidget(PlaydarConnection*, QWidget* parent = 0);\n\n    QString human() const;\n    QString rql() const;\n    QStringList selectedTags() const;\n\nsignals:\n    void selectionChanged();\n\nprivate slots:\n    void onSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected);\n    void onFilterClicked();\n    void onSliderChanged( int );\n\nprivate:\n    class QStringList m_rql;\n    class QLabel* m_rqlSentence;\n\n    TagCloudView* m_view;\n    class QSlider* m_trackCountSlider;\n    RelevanceFilter* m_filter;              // sits between model and view\n    PlaydarTagCloudModel* m_tagCloudModel;\n\n    PlaylistWidget* m_playlistWidget;\n    PlaylistModel* m_playlistModel;\n\n    QStringList m_tags;\n    PlaydarConnection* m_playdar;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/TagCloudView.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <boost/timer.hpp>\n#include \"TagCloudView.h\"\n#include \"PlaydarTagCloudModel.h\"\n#include <QApplication>\n#include <QMouseEvent>\n#include <QPainter>\n#include <QScrollBar>\n#include <limits.h>\n\n\nTagCloudView::TagCloudView( QWidget* parent )\n             : QAbstractItemView( parent )\n             , m_fetched( false )\n{\n    QFont f = font();\n\n#ifdef Q_WS_WIN\n    f.setPointSize( 10 );\n#else\n    f.setPointSize( 14 );\n#endif\n\n    setFont( f );\n    viewport()->setMouseTracking( true );\n\n    setSelectionMode( QAbstractItemView::MultiSelection );\n    setSelectionBehavior( QAbstractItemView::SelectItems );\n}\n\nvoid\nTagCloudView::onTag( const BoffinTagItem& tag )\n{\n\tif( m_fetched )\n\t\treturn;\n\n\tm_loadedTag = tag.m_name;\n\tviewport()->update();\n}\n\nvoid\nTagCloudView::setSelection( const QRect& rect, QItemSelectionModel::SelectionFlags f )\n{\n    if (state() == DragSelectingState)\n        return;\n\n    QRect r = rect.translated( 0, verticalScrollBar()->value());\n    RectsConstIt it = m_rects.constBegin();\n    for (int c = 0; it != m_rects.constEnd(); it++, c++) {\n        if (it->intersects(r)) {\n            selectionModel()->select(model()->index(c, 0), f);\n        }\n    }\n}\n\n\nQStringList\nTagCloudView::currentTags() const\n{\n    QStringList ret;\n    foreach( QModelIndex i, selectionModel()->selectedIndexes() )\n        ret << i.data( Qt::DisplayRole ).toString();\n\n    return ret;\n}\n\n\nvoid\nTagCloudView::paintEvent( QPaintEvent* e )\n{\n    QPainter p( viewport() );\n    p.setClipRect( e->rect());\n\n    if (!m_fetched) {\n\t\tp.drawText( viewport()->rect(), Qt::AlignCenter, \"Fetching tags..\" + m_loadedTag );\n\t\treturn;\n    }\n\n    if (m_dirty) {\n        updateGeometries();\n        m_dirty = false;\n    }\n\n    if (m_rects.isEmpty()) {\n        p.drawText( viewport()->rect(), Qt::AlignCenter,  \"No tags have been found!\" );\n        return;\n    }\n\n    QStyleOptionViewItem opt = viewOptions();\n    RectsConstIt it = m_rects.constBegin();\n    for (int c = 0; it != m_rects.constEnd(); it++, c++) \n    {\n        opt.rect = it->translated( 0, -verticalScrollBar()->value() );\n\n        if( e->rect().intersects( opt.rect )) {\n            const QModelIndex& index = model()->index(c, 0);\n\n            opt.state = QStyle::State_None;\n            if( m_hoverIndex == index && isEnabled() )\n                opt.state = qApp->mouseButtons() == Qt::NoButton\n                        ? QStyle::State_MouseOver\n                        : QStyle::State_Active;\n\n            if( selectionModel()->isSelected( index ) )\n                opt.state |= QStyle::State_Selected;\n\n            if( isEnabled() )\n                opt.state |= QStyle::State_Enabled;\n\n            itemDelegate()->paint( &p, opt, index );\n        }\n    }\n}\n\n\nvoid\nTagCloudView::onFetchedTags()\n{\n\tm_fetched = true;\n\n}\n\nvoid\nTagCloudView::setModel(QAbstractItemModel *model)\n{\n    QAbstractItemView::setModel(model);\n    connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)), SLOT(onRows(QModelIndex, int, int)));\n    connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)), SLOT(onRows(QModelIndex, int, int)));\n//    connect(model, SIGNAL(modelReset()), SLOT(onModelReset()));\n}\n\nvoid\nTagCloudView::onRows(const QModelIndex & parent, int start, int end)\n{\n    qDebug() << \".\";\n\tQ_UNUSED(parent);\n    Q_UNUSED(start);\n    Q_UNUSED(end);\n    // the model has changed (row inserted or deleted)\n    // which means our rects are now rubbish \n    // (they will get refreshed in paintEvent()\n    //  ...which will happen eventually)\n    m_dirty = true;\n    viewport()->update();\n}\n\nint gBaseline, gLeftMargin; //filthy but easiest\nvoid\nTagCloudView::rectcalc()\n{\n    QStyleOptionViewItem const opt = viewOptions();\n    int baseline = 0;\n\n    m_rects.clear();\n    for (int j = 0; j < model()->rowCount(); ++j)\n    {\n        QModelIndex const i = model()->index( j, 0 );\n        QRect r( QPoint(), itemDelegate()->sizeHint( opt, i ) );\n        if (baseline == 0)\n            baseline = gBaseline;\n\n        r.moveTo( gLeftMargin, baseline-gBaseline );\n\n        m_rects.insert(j, r);\n    }\n}\n\n\nvoid\nTagCloudView::updateGeometries()\n{\n    boost::timer bt;\n\n    if (!model())\n        return;\n\n    rectcalc(); //TODO only needs to be done once when data is set!\n\n    const int VIEWPORT_MARGIN = 10;\n\n    int y = VIEWPORT_MARGIN;\n    int left_margin = 0; // the left baseline to align text against\n\n    // iterate in model-order to lay the tags out left to right\n    for (int j = 0; j < model()->rowCount(); ++j)\n    {\n        QRect r = m_rects[j];\n        if (left_margin == 0) \n            left_margin = r.x();\n\n        // do new row\n        int x = VIEWPORT_MARGIN + (left_margin - r.x());\n        int tallest = 0;\n        for (; j < model()->rowCount(); ++j)\n        {\n            QRect r = m_rects[j];\n            r.moveTo( x, y + r.y() );\n\n            x += r.width();\n            if (tallest != 0 //need at least one thing per row\n                && x > viewport()->width() - VIEWPORT_MARGIN) \n            { \n                --j; break; \n            }\n\n            m_rects[j] = r;\n            tallest = qMax( tallest, r.bottom() - y );\n        }\n\n        y += tallest;\n    }\n\n    verticalScrollBar()->setRange( 0, y + VIEWPORT_MARGIN - viewport()->height() );\n    verticalScrollBar()->setPageStep( viewport()->height() );\n    verticalScrollBar()->setSingleStep( 20 /*TODO*/ );\n\n    viewport()->update();\n    QAbstractItemView::updateGeometries();\n}\n\n\nvoid\nTagCloudView::selectAll()\n{\n    QItemSelection allSelection( model()->index( 0 , 0 ), model()->index( model()->rowCount()-1, 0 ));\n    selectionModel()->select( allSelection, QItemSelectionModel::Toggle );\n    viewport()->update();\n}\n\n\nQModelIndex\nTagCloudView::indexAt( const QPoint& pos ) const\n{\n    QPoint p = pos + QPoint( 0, verticalScrollBar()->value());\n    RectsConstIt it = m_rects.constBegin();\n    for (int c = 0; it != m_rects.constEnd(); it++, c++) {\n        if( it->contains( p )) {\n            return model()->index(c, 0);\n        }\n    }\n    return QModelIndex();\n}\n\n\nQRect\nTagCloudView::visualRect( const QModelIndex& i ) const\n{\n    return m_rects[ i.row() ].translated( 0, -verticalScrollBar()->value());\n}\n\n\nbool\nTagCloudView::viewportEvent( QEvent* event )\n{\n    switch( event->type() )\n    {\n        case QEvent::Wheel:\n            {\n                // do first so it moves the view\n                bool b = QAbstractItemView::viewportEvent( event );\n                // then calculate the new tag under the mouse\n                m_hoverIndex = indexAt( viewport()->mapFromGlobal( QCursor::pos() ) );\n                return b;\n            }\n\n        case QEvent::MouseMove:\n        {\n            QMouseEvent* e = static_cast< QMouseEvent* >( event );\n            QModelIndex const oldindex = m_hoverIndex;\n            m_hoverIndex = indexAt( e->pos() );\n            if (oldindex != m_hoverIndex)\n                viewport()->update();\n            break;\n        }\n\n        case QEvent::MouseButtonPress:\n        case QEvent::MouseButtonRelease:\n            if (m_hoverIndex.isValid())\n                viewport()->update();\n            break;\n\n        case QEvent::KeyPress:\n        case QEvent::KeyRelease:\n            return false;\n\n        default:\n            break;\n    }\n    return QAbstractItemView::viewportEvent( event );\n}\n\n\n\n"
  },
  {
    "path": "app/boffin/TagCloudView.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TAG_CLOUD_VIEW_H\n#define TAG_CLOUD_VIEW_H\n\n#include <QAbstractItemView>\n#include \"playdar/BoffinTagRequest.h\"\n\nclass TagCloudView : public QAbstractItemView\n{\n    Q_OBJECT\npublic:\n    TagCloudView( QWidget* parent = 0 );\n\n    // QAbstractItemView pure virtual functions:\n    virtual QModelIndex indexAt( const QPoint& ) const;\n    virtual void scrollTo( const QModelIndex&, ScrollHint ) {};\n    virtual QRect visualRect( const QModelIndex& ) const;\n\n    void setModel(QAbstractItemModel *model);\n    QStringList currentTags() const;\n\npublic slots:\n    virtual void selectAll();\n\nprotected slots:\n    virtual void updateGeometries();\n    void onRows(const QModelIndex & parent, int start, int end);\n    void onFetchedTags();\n    void onTag( const BoffinTagItem& );\n\nprotected:\n    void rectcalc();\n\n    virtual void paintEvent( QPaintEvent* );\n    virtual bool isIndexHidden( const QModelIndex& ) const{ return false; }\n    virtual void setSelection( const QRect&, QItemSelectionModel ){};\n    virtual QRegion visualRegionForSelection( const QItemSelection& ) const{ return QRegion(); }\n    virtual QModelIndex moveCursor( CursorAction, Qt::KeyboardModifiers ) { return QModelIndex(); }\n    virtual int horizontalOffset() const{ return 0; }\n    virtual int verticalOffset() const{ return 0; }\n    virtual void setSelection( const QRect&, QItemSelectionModel::SelectionFlags );\n\n    virtual bool viewportEvent(QEvent *event);\n\n    QModelIndex m_hoverIndex;\n    QHash<int, QRect> m_rects;      // row -> QRect\n\n    typedef QHash<int, QRect>::const_iterator RectsConstIt;\n    typedef QHash<int, QRect>::iterator RectsIt;\n\n    bool m_dirty;\n    bool m_fetched;\n    QString m_loadedTag;\n};\n\n#endif //TAG_CLOUD_VIEW_H\n"
  },
  {
    "path": "app/boffin/TagDelegate.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"TagDelegate.h\"\n#include \"PlaydarTagCloudModel.h\"\n#include <QPainter>\n\n\nstatic inline QFont font( QFont f, float const weight )\n{\n    static const float k_factor = 16;\n\n    f.setPointSize( f.pointSize() + (k_factor * weight ));\n    f.setWeight( 99 * weight );\n    return f;\n}\n\n\nstatic inline QSize margins( float const weight )\n{\n    return QSize( 17 + (11*weight), 20 - (10*weight) );\n}\n\n\nTagDelegate::TagDelegate( QObject* parent )\n            : QAbstractItemDelegate( parent )\n{}\n\n\nvoid\nTagDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const\n{\n    QPen p( Qt::NoPen );\n    QBrush b( Qt::NoBrush );\n    int alpha = 255;\n    float tagRelevance = index.data( PlaydarTagCloudModel::RelevanceRole ).value<float>() * 0.8;\n    QColor bc(54,115,213);\n    QColor borderColor = bc;\n\n    bc.setAlphaF( tagRelevance * 0.5 );\n    borderColor.setAlphaF( tagRelevance );\n    b = QBrush( bc );\n    p = QPen( borderColor );\n\n\n    QColor const dark = option.palette.color( QPalette::Highlight ).darker();\n\n    if( option.state & (QStyle::State_Selected | QStyle::State_Active) )\n    {\n        b = option.state & QStyle::State_Enabled\n                ? option.palette.highlight()\n                : QColor(0x64, 0x64, 0x64, alpha );\n    }\n    \n    if( option.state & QStyle::State_MouseOver )\n        p = option.palette.color( QPalette::Highlight );\n\n    if( option.state & QStyle::State_Active )\n        p = dark;\n\n\n    p.setWidth( 3 );\n    painter->setPen( p );\n    painter->setBrush( b );\n    painter->setRenderHint( QPainter::Antialiasing, true );\n    painter->drawRoundedRect( option.rect.adjusted( 2, 2, -2, -2 ), 5.0f, 5.0f );\n\n    const float weight = index.data( PlaydarTagCloudModel::LinearWeightRole ).value<float>();\n    painter->setFont( font( option.font, weight ) );\n\n    painter->setRenderHint( QPainter::Antialiasing, false );\n    QColor textColor = option.state & (QStyle::State_Selected|QStyle::State_Active)\n \t\t\t\t\t ? option.palette.color( QPalette::HighlightedText )\n\t\t\t\t\t : option.palette.color( QPalette::Text );\n \ttextColor.setAlpha( alpha );\n    painter->setPen( textColor );\n\n    QString const text = index.data().toString();\n    QFontMetrics const metrics = painter->fontMetrics();\n\n    QPoint pt;\n    pt.setX( option.rect.x() + (option.rect.width() - metrics.width( text ))/2 );\n    pt.setY( option.rect.y() + margins( weight ).height()/2 + metrics.ascent() );\n    painter->drawText( pt, text );\n}\n\n\nextern int gBaseline;\nextern int gLeftMargin;\nQSize\nTagDelegate::sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const\n{\n    const float weight = index.data( PlaydarTagCloudModel::LinearWeightRole ).value<float>();\n    QFontMetrics fm( font( option.font, weight ) );\n\n    const QSize margin = margins( weight );\n    gBaseline = margin.height()/2 + fm.ascent();\n    gLeftMargin = margin.width()/2;\n    return fm.size( Qt::TextSingleLine, index.data().toString() ) + margin;\n}\n"
  },
  {
    "path": "app/boffin/TagDelegate.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TAG_DELEGATE_H\n#define TAG_DELEGATE_H\n\n#include <QAbstractItemDelegate>\n\nclass TagDelegate: public QAbstractItemDelegate\n{\npublic:\n    TagDelegate( QObject* parent = 0 );\n    virtual void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const;\n    virtual QSize sizeHint( const QStyleOptionViewItem& option, const QModelIndex& index ) const;\n    \n};\n\n#endif //TAG_DELEGATE_H\n\n"
  },
  {
    "path": "app/boffin/TrackSource.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"TrackSource.h\"\n#include \"Shuffler.h\"\n\nstatic Track toTrack(const BoffinPlayableItem& item)\n{\n    Track t;\n    MutableTrack mt(t);\n    mt.setArtist(item.artist());\n    mt.setAlbum(item.album());\n    mt.setTitle(item.track());\n    mt.setDuration(item.duration());\n    mt.setUrl(QUrl(item.url()));\n    mt.setSource(Track::Player);\n    return t;\n}\n\nTrackSource::TrackSource(Shuffler* shuffler, QObject *parent)\n: QObject(parent)\n, m_shuffler(shuffler)\n, m_maxSize(1)\n{\n}\n\nTrack\nTrackSource::takeNextTrack()\n{\n    fillBuffer();\n    if (m_buffer.isEmpty()) \n        return Track();\n\n    Track result = toTrack(m_buffer.takeFirst());\n    fillBuffer();\n    emit changed();\n    return result;\n}\n\nvoid\nTrackSource::fillBuffer()\n{\n    while (m_buffer.size() < m_maxSize) {\n        BoffinPlayableItem item = m_shuffler->sampleOne();\n        if (item.isValid())\n            m_buffer.append(item);\n        else\n            break;\n    }\n}\n\nBoffinPlayableItem\nTrackSource::peek(unsigned index)\n{\n    return (index >= 0 && index < (unsigned) m_buffer.size()) ? m_buffer[index] : BoffinPlayableItem();\n}\n\nint\nTrackSource::size()\n{\n    return m_buffer.size();\n}\n\nvoid\nTrackSource::setSize(unsigned maxSize)\n{\n    m_maxSize = maxSize;\n}\n\nvoid\nTrackSource::clear()\n{\n    if (!m_buffer.isEmpty()) {\n        m_buffer.clear();\n        emit changed();\n    }\n}\n"
  },
  {
    "path": "app/boffin/TrackSource.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TRACK_SOURCE_H\n#define TRACK_SOURCE_H\n\n#include <QList>\n#include <types/Track.h>\n#include \"playdar/BoffinPlayableItem.h\"\n\nclass Shuffler;\n\n// Tracksource samples BoffinPlayableItem objects from the Shuffler, \n// maintains a small buffer of them (for upcoming-track feature).\n// MediaPipeline then takes Track objects from us.\nclass TrackSource\n    : public QObject\n{\n    Q_OBJECT\n\npublic:\n    TrackSource(Shuffler* shuffler, QObject *parent);\n\n    Track takeNextTrack();\n    BoffinPlayableItem peek(unsigned index);\n    int size();\n    void setSize(unsigned maxSize);\n    void clear();\n\nsignals:\n    void changed();     // the buffer has changed somehow.\n\nprivate:\n    void fillBuffer();\n\n    Shuffler* m_shuffler;\n    QList<BoffinPlayableItem> m_buffer;\n    int m_maxSize;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/WordleDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef WORDLE_DIALOG_H\n#define WORDLE_DIALOG_H\n\n#include <QTextEdit>\n#include <QVBoxLayout>\n#include <QDialog>\n#include <QLabel>\n#include <QClipboard>\n#include <QDialogButtonBox>\n#include <QPushButton>\n\n\nclass WordleDialog : public QDialog\n{\n    QTextEdit* output;\n\npublic:\n    WordleDialog( QWidget* parent = 0 ) : QDialog( parent )\n    {\n        new QVBoxLayout( this );\n        \n        layout()->addWidget( output = new QTextEdit());\n        output->setReadOnly( true );\n\n        QLabel* hint;        \n        layout()->addWidget( hint = new QLabel);\n        hint->setOpenExternalLinks( true );\n        hint->setTextFormat( Qt::RichText );\n        hint->setText( tr(\"<p>We copied the wordlist to your clipboard already.<br>\"\n                      \"So just visit <a href='http://www.wordle.net/advanced'>Wordle Advanced</a> and paste!</p>\"\n                      \"<p>Why not save your Wordle with username \\\"boffin\\\" and your<br>\"\n                      \"Last.fm username as the title so we can start a <a href='http://www.wordle.net/gallery?username=Boffin'>community</a>?</p>\") );\n        \n        QDialogButtonBox* buttons;\n        layout()->addWidget( buttons = new QDialogButtonBox( QDialogButtonBox::Ok ));\n        connect( buttons, SIGNAL(accepted()), SLOT( accept()));\n        buttons->button( QDialogButtonBox::Ok )->setText( tr(\"Close\") );\n        \n        setWindowTitle( tr(\"Your Wordlized Tags\") );\n    }\n\n    void setText( const QString& t )\n    {\n        output->setText( t );\n        //output->selectAll(); //looks wrong\n        QApplication::clipboard()->setText( t );\n    }\n};\n\n#endif //WORDLE_DIALOG_H\n"
  },
  {
    "path": "app/boffin/XspfDialog.cpp",
    "content": "/***************************************************************************\n *   Copyright 2009 Last.fm Ltd.                                           *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *\n ***************************************************************************/\n\n#include <QLayout>\n#include <QTreeWidget>\n#include <QHBoxLayout>\n#include \"XspfDialog.h\"\n#include \"XspfReader.h\"\n#include \"playdar/PlaydarConnection.h\"\n#include \"playdar/TrackResolveRequest.h\"\n#include \"playdar/BoffinPlayableItem.h\"\n\n\nXspfDialog::XspfDialog(QString path, PlaydarConnection* playdar, QWidget *parent)\n:QDialog(parent)\n,m_playdar(playdar)\n{\n    QLayout* layout = new QHBoxLayout();\n    m_treewidget = new QTreeWidget();\n    m_treewidget->setColumnCount(12);\n    QStringList labels;\n    labels << \"Position\" << \"Artist\" << \"Album\" << \"Title\" << \"Length\" << \"Url\"\n        << \"Score\" << \"Pref\" << \"Source\" << \"Bitrate\" << \"Size\" << \"Mimetype\";\n    m_treewidget->setHeaderLabels(labels);\n    layout->addWidget(m_treewidget);\n    setLayout(layout);\n    setSizeGripEnabled(true);\n\n    m_reader = new XspfReader(path);\n    connect(m_reader, SIGNAL(xspf(lastfm::Xspf)), SLOT(onXspf(lastfm::Xspf)));\n}\n\nvoid\nXspfDialog::onXspf(const lastfm::Xspf& xspf)\n{\n    setWindowTitle(xspf.title());\n    int i = 0;\n    foreach(const lastfm::Track& t, xspf.tracks()) {\n        TrackResolveRequest* req = m_playdar->trackResolve(t.artist(), t.album(), t.title());\n\n        QTreeWidgetItem* item = new QTreeWidgetItem();\n        m_reqmap[req->qid()] = item;\n        item->setData(0, Qt::DisplayRole, QString::number(i));\n        item->setData(1, Qt::DisplayRole, (QString)t.artist());\n        item->setData(2, Qt::DisplayRole, (QString)t.album());\n        item->setData(3, Qt::DisplayRole, (QString)t.title());\n        item->setData(4, Qt::DisplayRole, t.duration());\n        item->setData(5, Qt::DisplayRole, t.url().toString());\n        m_treewidget->addTopLevelItem(item);\n\n        connect(req, SIGNAL(result(BoffinPlayableItem)), SLOT(onResolveResult(BoffinPlayableItem)));\n        i++;\n    }\n}\n\nvoid\nXspfDialog::onResolveResult(const BoffinPlayableItem& item)\n{\n    TrackResolveRequest* req = qobject_cast<TrackResolveRequest*>(sender());\n    if (req) {\n        QMap<QString, QTreeWidgetItem*>::const_iterator it = m_reqmap.constFind(req->qid());\n        if (it != m_reqmap.constEnd()) {\n            QTreeWidgetItem* child = new QTreeWidgetItem();\n            child->setFirstColumnSpanned(true);\n            child->setData(1, Qt::DisplayRole, item.artist());\n            child->setData(2, Qt::DisplayRole, item.album());\n            child->setData(3, Qt::DisplayRole, item.track());\n            child->setData(4, Qt::DisplayRole, item.duration());\n            child->setData(5, Qt::DisplayRole, item.url());\n            child->setData(6, Qt::DisplayRole, item.score());\n            child->setData(7, Qt::DisplayRole, item.preference());\n            child->setData(8, Qt::DisplayRole, item.source());\n            child->setData(9, Qt::DisplayRole, item.bitrate());\n            child->setData(10, Qt::DisplayRole, item.size());\n            child->setData(11, Qt::DisplayRole, item.mimetype());\n            it.value()->addChild(child);\n        } else {\n            qDebug() << \"unknown qid \" << req->qid();\n        }\n    }\n}"
  },
  {
    "path": "app/boffin/XspfDialog.h",
    "content": "/***************************************************************************\n *   Copyright 2009 Last.fm Ltd.                                           *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *\n ***************************************************************************/\n#ifndef XSPF_DIALOG_H\n#define XSPF_DIALOG_H\n\n#include <QDialog>\n#include <QMap>\n#include <lastfm/Xspf>\n\nclass QTreeWidget;\nclass QTreeWidgetItem;\nclass XspfReader;\nclass PlaydarConnection;\nclass BoffinPlayableItem;\n\nclass XspfDialog : public QDialog\n{\n    Q_OBJECT\n\npublic:\n    XspfDialog(QString url, PlaydarConnection* playdar, QWidget *parent = 0);\n\nprivate slots:\n    void onXspf(const lastfm::Xspf& xspf);\n    void onResolveResult(const BoffinPlayableItem& item);\n\nprivate:\n    XspfReader* m_reader;\n    QTreeWidget* m_treewidget;\n    PlaydarConnection* m_playdar;\n    QMap<QString, QTreeWidgetItem*> m_reqmap;    // map request qid to index\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/XspfReader.cpp",
    "content": "/***************************************************************************\n *   Copyright 2005-2009 Last.fm Ltd.                                      *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *    This program is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *\n ***************************************************************************/\n\n#include \"XspfReader.h\"\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include <lastfm/NetworkAccessManager>\n\n\n XspfReader::XspfReader(QUrl url)\n: m_url(url)\n{\n    m_reply = (new lastfm::NetworkAccessManager(this))->get(QNetworkRequest(m_url));\n    connect(m_reply, SIGNAL(finished()), SLOT(onFinished()));\n}\n\nvoid\nXspfReader::onFinished()\n{\n    QDomDocument xmldoc;\n    xmldoc.setContent(m_reply);\n    QDomElement docElement(xmldoc.documentElement());\n    if (docElement.tagName() == \"playlist\") {\n        handleXspf(docElement);\n    } else if (docElement.tagName() == \"lfm\") {\n        handleXspf(docElement.firstChildElement(\"playlist\"));\n    } else {\n        // todo\n    }\n    m_reply->deleteLater();\n    m_reply = 0;\n}\n\nvoid \nXspfReader::handleXspf(const QDomElement& playlistElement)\n{\n    Xspf xspf(playlistElement);\n    emit XspfReader::xspf(xspf);\n}\n"
  },
  {
    "path": "app/boffin/XspfReader.h",
    "content": "/***************************************************************************\n *   Copyright 2005-2009 Last.fm Ltd.                                      *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *    This program is distributed in the hope that it will be useful,      *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *\n ***************************************************************************/\n\n#ifndef XSPF_READER\n#define XSPF_READER\n \n#include <QList>\n#include <lastfm/Xspf>\n\n\nclass XspfReader : public QObject\n{\n    Q_OBJECT\n\n    QUrl m_url;\n    class QNetworkReply *m_reply;\n    QList<Track> m_queue;\n\n    void handleXspf(const QDomElement& playlistElement);\n\nsignals:\n    void xspf(lastfm::Xspf);\n\nprivate slots:\n    void onFinished();\n\npublic:\n    XspfReader(QUrl);\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/boffin.pro",
    "content": "CONFIG += unicorn boost yajl\nQT += opengl sql phonon\nVERSION = 1.0.0\nDEFINES += LASTFM_COLLAPSE_NAMESPACE\n\ninclude( $$ROOT_DIR/admin/include.qmake )\n\nmac{\n    release{\n        QMAKE_INFO_PLIST = Info.plist.in\n        system( $$ROOT_DIR/admin/dist/mac/Makefile.dmg.pl $$LIBS > Makefile.dmg )\n        QMAKE_EXTRA_INCLUDES += Makefile.dmg\n        ICON = ../client/mac/client.icns\n        CONFIG += app_bundle\n    }\n}\n\nSOURCES += \\\n\tXspfReader.cpp \\\n\tXspfDialog.cpp \\\n\tTrackSource.cpp \\\n\tTagDelegate.cpp \\\n\tTagCloudView.cpp \\\n\tTagBrowserWidget.cpp \\\n\tShuffler.cpp \\\n\tScrobSocket.cpp \\\n\tScanProgressWidget.cpp \\\n\tPlaylistModel.cpp \\\n\tPlaylist.cpp \\\n\tPlaydarTagCloudModel.cpp \\\n\tPlaydarHostsModel.cpp \\\n\tplaydar/TrackResolveRequest.cpp \\\n\tplaydar/PlaydarStatRequest.cpp \\\n\tplaydar/PlaydarRosterRequest.cpp \\\n\tplaydar/PlaydarConnection.cpp \\\n\tplaydar/PlaydarCometRequest.cpp \\\n\tplaydar/PlaydarAuthRequest.cpp \\\n\tplaydar/jsonGetMember.cpp \\\n\tplaydar/CometRequest.cpp \\\n\tplaydar/BoffinTagRequest.cpp \\\n\tplaydar/BoffinRqlRequest.cpp \\\n\tplaydar/BoffinPlayableItem.cpp \\\n\tPickDirsDialog.cpp \\\n\tMediaPipeline.cpp \\\n\tMainWindow.cpp \\\n\tmain.cpp \\\n\tLocalCollectionScanner.cpp \\\n\tlayouts/SideBySideLayout.cpp \\\n\tjson_spirit/json_spirit_writer.cpp \\\n\tjson_spirit/json_spirit_value.cpp \\\n\tjson_spirit/json_spirit_reader.cpp \\\n\tHistoryWidget.cpp \\\n\tcomet/CometParser.cpp \\\n\tApp.cpp\n    \nHEADERS += \\\n\tXspfReader.h \\\n\tXspfDialog.h \\\n\tWordleDialog.h \\\n\tTrackSource.h \\\n\tTagDelegate.h \\\n\tTagCloudView.h \\\n\tTagBrowserWidget.h \\\n\tShuffler.h \\\n\tScrobSocket.h \\\n\tScanProgressWidget.h \\\n\tsample/SampleFromDistribution.h \\\n\tPlaylistWidget.h \\\n\tPlaylistModel.h \\\n\tPlaylist.h \\\n\tPlaydarTagCloudModel.h \\\n\tPlaydarHostsModel.h \\\n\tplaydar/TrackResolveRequest.h \\\n\tplaydar/PlaydarStatRequest.h \\\n\tplaydar/PlaydarRosterRequest.h \\\n\tplaydar/PlaydarConnection.h \\\n\tplaydar/PlaydarCometRequest.h \\\n\tplaydar/PlaydarAuthRequest.h \\\n\tplaydar/PlaydarApi.h \\\n\tplaydar/jsonGetMember.h \\\n\tplaydar/CometRequest.h \\\n\tplaydar/BoffinTagRequest.h \\\n\tplaydar/BoffinRqlRequest.h \\\n\tplaydar/BoffinPlayableItem.h \\\n\tPickDirsDialog.h \\\n\tMediaPipeline.h \\\n\tMainWindow.h \\\n\tLocalCollectionScanner.h \\\n\tlayouts/SideBySideLayout.h \\\n\tjson_spirit/json_spirit_writer.h \\\n\tjson_spirit/json_spirit_value.h \\\n\tjson_spirit/json_spirit_utils.h \\\n\tjson_spirit/json_spirit_reader.h \\\n\tjson_spirit/json_spirit.h \\\n\tHistoryWidget.h \\\n\tcomet/CometParser.h \\\n\tApp.h\n    \nRESOURCES += \\\n\tqrc/boffin.qrc\n"
  },
  {
    "path": "app/boffin/comet/CometParser.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"CometParser.h\"\n\nCometParser::CometParser(QObject *parent)\n: QObject(parent)\n{\n    yajl_parser_config cfg = { 1 /* allow comments */, 0 /* don't check the incoming utf8 */ };\n    m_handle = yajl_alloc(&CometCallbacks::callbacks, &cfg, NULL, (void *) this);\n}\n\nCometParser::~CometParser()\n{\n    if (m_handle)\n        yajl_free(m_handle);\n}\n\nbool\nCometParser::push(const QByteArray& ba)\n{\n    const yajl_status status = yajl_parse(m_handle, (const unsigned char*) ba.constData(), ba.length());\n    return status == yajl_status_ok || status == yajl_status_insufficient_data;\n}\n\n\n//static\nvoid\nCometParser::objectInserter(CometParser::Object* o, const QString& name, const QVariant& value)\n{\n    o->insert(name, value);\n}\n\n//static\nvoid\nCometParser::arrayInserter(CometParser::Array* a, const QString&, const QVariant& value)\n{\n    a->push_back(value);\n}\n\n//static\nvoid\nCometParser::postObjectInserter(CometParser::Inserter i, const QString& name, Object* o)\n{\n    i(name, *o);\n    delete o;\n}\n\n//static\nvoid\nCometParser::postArrayInserter(CometParser::Inserter i, const QString& name, Array* a)\n{\n    i(name, *a);\n    delete a;\n}\n\nvoid\nCometParser::haveObject(const QString&, const QVariant& v)\n{\n    if (v.type() == QVariant::Map) {\n        emit haveObject(v.toMap());\n    }\n}\n\n//static\nvoid\nCometParser::nop()\n{\n}\n\n////////////////////////////////\n\n// yajl callbacks:\nint\nCometParser::json_null()\n{\n    m_insertStack.top()( m_key, QVariant() );\n    return 1;\n}\n\nint\nCometParser::json_boolean(int boolVal)\n{\n    m_insertStack.top()( m_key, QVariant(boolVal ? true : false) );\n    return 1;\n}\n\nint\nCometParser::json_number(const QString& s)\n{\n    bool ok;\n    qlonglong l;\n    double d;\n\n    if ((l = s.toLongLong(&ok), ok)) {\n        m_insertStack.top()( m_key, QVariant(l) );\n    } else if ((d = s.toDouble(&ok), ok)) {\n        m_insertStack.top()( m_key, QVariant(d) );\n    }\n    return 1;\n}\n\nint\nCometParser::json_string(const QString& s)\n{\n    m_insertStack.top()( m_key, QVariant(s) );\n    return 1;\n}\n\nint\nCometParser::json_start_map()\n{\n    if (m_insertStack.size() == 0)\n        return 0;       // the comet stream we expect has objects wrapped in an array, thx.\n\n    Object *o = new Object();\n    m_atEndStack.push( boost::bind(&CometParser::postObjectInserter, m_insertStack.top(), m_key, o) );\n    m_insertStack.push( boost::bind(&CometParser::objectInserter, o, _1, _2) );\n    return 1;\n}\n\nint\nCometParser::json_map_key(const QString& s)\n{\n    m_key = s;\n    return 1;\n}\n\nint\nCometParser::json_start_array()\n{\n    Array *a = new Array();\n    if (m_insertStack.size() == 0) {\n        // the first enclosing array...\n        // has a special inserter to call the function to emit the haveObject signal\n        m_atEndStack.push( boost::bind(&CometParser::nop) );\n        m_insertStack.push( boost::bind(&CometParser::haveObject, this, _1, _2) );\n    } else {\n        m_atEndStack.push( boost::bind(&CometParser::postArrayInserter, m_insertStack.top(), m_key, a) );\n        m_insertStack.push( boost::bind(&CometParser::arrayInserter, a, _1, _2) );\n    }\n    return 1;\n}\n\nint\nCometParser::json_end_map()\n{\n    m_insertStack.pop();\n    m_atEndStack.pop()();\n    return 1;\n}\n\nint\nCometParser::json_end_array()\n{\n    m_insertStack.pop();\n    m_atEndStack.pop()();\n    return 1;\n}\n\n"
  },
  {
    "path": "app/boffin/comet/CometParser.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef COMET_PARSER_H\n#define COMET_PARSER_H\n\n#include <QMap>\n#include <QList>\n#include <QStack>\n#include <QVariant>\n\n#include <boost/function.hpp>\n#include <boost/bind.hpp>\n\n#include \"YajlCallbacks.hpp\"\n\n// parses a neverending json comet stream like:\n//      \"[ {}, {}, ....\"\n//\n// signal emitted for each top-level object\n//\n// yajl does the json (developed using yajl 1.0.5)\n// this class transforms the tokens into QVariantMap types\n//\nclass CometParser : public QObject\n{\n    Q_OBJECT;\n    Q_DISABLE_COPY(CometParser);\n\n    struct QStringPolicy\n    {\n        static QString stringize(const char* s, unsigned int len)\n        {\n            return QString::fromUtf8(s, len);\n        }\n    };\n\n    typedef TYajlCallbacks<CometParser, QStringPolicy> CometCallbacks;\n    typedef QVariantMap Object;\n    typedef QVariantList Array;\n    typedef boost::function<void(const QString&, const QVariant&)> Inserter;\n    typedef boost::function<void()> AtEnd;\n\n    friend class TYajlCallbacks<CometParser, QStringPolicy>;\n\npublic:\n    CometParser(QObject *parent = 0);\n    ~CometParser();\n\n    bool push(const QByteArray& ba);        // push data in...\n\nsignals:\n    void haveObject(QVariantMap o);         // ...and objects pop out\n\nprivate:\n\n    // inserters and post-inserters\n\n    static void objectInserter(Object* o, const QString& name, const QVariant& value);\n    static void arrayInserter(Array* a, const QString&, const QVariant& value);\n    static void postObjectInserter(Inserter i, const QString& name, Object* o);\n    static void postArrayInserter(Inserter i, const QString& name, Array* a);\n    void haveObject(const QString&, const QVariant& v);\n    static void nop();\n\n    ////////////////////////////////\n    // yajl callbacks\n\n    int json_null();\n    int json_boolean(int boolVal);\n    int json_number(const QString& s);\n    int json_string(const QString& s);\n    int json_start_map();\n    int json_map_key(const QString& s);\n    int json_start_array();\n    int json_end_map();\n    int json_end_array();\n\n    /////////////////\n\n    QString m_key;                      // the last key we saw\n    QStack<Inserter> m_insertStack;     // inserters are used to put values into objects and arrays\n    QStack<AtEnd> m_atEndStack;         // we call these at the end of an object or array\n\n    yajl_handle m_handle;\n};\n\n\n#endif\n\n"
  },
  {
    "path": "app/boffin/comet/YajlCallbacks.hpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef YAJL_CALLBACKS_HPP\n#define YAJL_CALLBACKS_HPP\n\n#include <yajl/yajl_parse.h>\n\n// trampoline yajl callbacks to \"json_\" method calls on class T\n// strings are converted using Policy::stringize(const char*, unsigned int len)\n// we use the 'number' callback instead of the integer/double callbacks.\n\ntemplate <typename T, typename Policy>\nclass TYajlCallbacks \n    : private Policy\n{\nprivate:\n    static int _null(void *ctx)\n    {\n        return ((T*)ctx)->json_null();\n    }\n\n    static int _boolean(void *ctx, int boolVal)\n    {\n        return ((T*)ctx)->json_boolean(boolVal);\n    }\n\n    static int _number(void *ctx, const char *numberVal, unsigned int numberLen)\n    {\n        return ((T*)ctx)->json_number(Policy::stringize(numberVal, numberLen));\n    }\n\n    static int _string(void *ctx, const unsigned char *stringVal, unsigned int stringLen)\n    {\n        return ((T*)ctx)->json_string(Policy::stringize((const char *)stringVal, stringLen));\n    }\n\n    static int _start_map(void *ctx)\n    {\n        return ((T*)ctx)->json_start_map();\n    }\n\n    static int _map_key(void *ctx, const unsigned char *key, unsigned int stringLen)\n    {\n        return ((T*)ctx)->json_map_key(Policy::stringize((const char *)key, stringLen));\n    }\n\n    static int _end_map(void *ctx)\n    {\n        return ((T*)ctx)->json_end_map();\n    }\n\n    static int _start_array(void *ctx)\n    {\n        return ((T*)ctx)->json_start_array();\n    }\n\n    static int _end_array(void *ctx)\n    {\n        return ((T*)ctx)->json_end_array();\n    }\n\npublic:\n    static yajl_callbacks callbacks;\n    \n};\n\n\ntemplate <typename T, typename Policy>\nyajl_callbacks TYajlCallbacks<T, Policy>::callbacks = {\n    TYajlCallbacks<T, Policy>::_null,\n    TYajlCallbacks<T, Policy>::_boolean,\n    0,      // integer\n    0,      // double\n    TYajlCallbacks<T, Policy>::_number,\n    TYajlCallbacks<T, Policy>::_string,\n    TYajlCallbacks<T, Policy>::_start_map,\n    TYajlCallbacks<T, Policy>::_map_key,\n    TYajlCallbacks<T, Policy>::_end_map,\n    TYajlCallbacks<T, Policy>::_start_array,\n    TYajlCallbacks<T, Policy>::_end_array\n};\n\n\n#endif\n\n"
  },
  {
    "path": "app/boffin/json_spirit/README",
    "content": "json spirit v3.0\nFrom:\nhttp://www.codeproject.com/KB/recipes/JSON_Spirit.aspx\n\n\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit.h",
    "content": "#ifndef JASON_SPIRIT\n#define JASON_SPIRIT\n\n/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include \"json_spirit_value.h\"\n#include \"json_spirit_reader.h\"\n#include \"json_spirit_writer.h\"\n#include \"json_spirit_utils.h\"\n\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_reader.cpp",
    "content": "/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#include \"json_spirit_reader.h\"\n#include \"json_spirit_value.h\"\n\n#define BOOST_SPIRIT_THREADSAFE  // uncomment for multithreaded use, requires linking to boost.thead\n\n#include <boost/bind.hpp>\n#include <boost/function.hpp>\n#include <boost/spirit/core.hpp>\n#include <boost/spirit/utility/confix.hpp>\n#include <boost/spirit/utility/escape_char.hpp>\n#include <boost/spirit/iterator/multi_pass.hpp>\n#include <boost/spirit/iterator/position_iterator.hpp>\n\nusing namespace json_spirit;\nusing namespace std;\nusing namespace boost;\nusing namespace boost::spirit;\n\n//\n\nError_position::Error_position()\n:   line_( 0 )\n,   column_( 0 )\n{\n}\n\nError_position::Error_position( unsigned int line, unsigned int column, const std::string& reason )\n:   line_( line )\n,   column_( column )\n,   reason_( reason )\n{\n}\n\nbool Error_position::operator==( const Error_position& lhs ) const\n{\n    if( this == &lhs ) return true;\n\n    return ( reason_ == lhs.reason_ ) &&\n           ( line_   == lhs.line_ ) &&\n           ( column_ == lhs.column_ ); \n}\n\n//\n\nnamespace\n{\n    const int_parser< int64_t > int64_p = int_parser< int64_t >();\n\n    template< class Iter_t >\n    bool is_eq( Iter_t first, Iter_t last, const char* c_str )\n    {\n        for( Iter_t i = first; i != last; ++i, ++c_str )\n        {\n            if( *c_str == 0 ) return false;\n\n            if( *i != *c_str ) return false;\n        }\n\n        return true;\n    }\n\n    template< class Char_t >\n    Char_t hex_to_num( const Char_t c )\n    {\n        if( ( c >= '0' ) && ( c <= '9' ) ) return c - '0';\n        if( ( c >= 'a' ) && ( c <= 'f' ) ) return c - 'a' + 10;\n        if( ( c >= 'A' ) && ( c <= 'F' ) ) return c - 'A' + 10;\n        return 0;\n    }\n\n    template< class Char_t, class Iter_t >\n    Char_t hex_str_to_char( Iter_t& begin )\n    {\n        const Char_t c1( *( ++begin ) );\n        const Char_t c2( *( ++begin ) );\n\n        return ( hex_to_num( c1 ) << 4 ) + hex_to_num( c2 );\n    }       \n\n    template< class Char_t, class Iter_t >\n    Char_t unicode_str_to_char( Iter_t& begin )\n    {\n        const Char_t c1( *( ++begin ) );\n        const Char_t c2( *( ++begin ) );\n        const Char_t c3( *( ++begin ) );\n        const Char_t c4( *( ++begin ) );\n\n        return ( hex_to_num( c1 ) << 12 ) + \n               ( hex_to_num( c2 ) <<  8 ) + \n               ( hex_to_num( c3 ) <<  4 ) + \n               hex_to_num( c4 );\n    }\n\n    template< class String_t >\n    void append_esc_char_and_incr_iter( String_t& s, \n                                        typename String_t::const_iterator& begin, \n                                        typename String_t::const_iterator end )\n    {\n        typedef typename String_t::value_type Char_t;\n             \n        const Char_t c2( *begin );\n\n        switch( c2 )\n        {\n            case 't':  s += '\\t'; break;\n            case 'b':  s += '\\b'; break;\n            case 'f':  s += '\\f'; break;\n            case 'n':  s += '\\n'; break;\n            case 'r':  s += '\\r'; break;\n            case '\\\\': s += '\\\\'; break;\n            case '/':  s += '/';  break;\n            case '\"':  s += '\"';  break;\n            case 'x':  \n            {\n                if( end - begin >= 3 )  //  expecting \"xHH...\"\n                {\n                    s += hex_str_to_char< Char_t >( begin );  \n                }\n                break;\n            }\n            case 'u':  \n            {\n                if( end - begin >= 5 )  //  expecting \"uHHHH...\"\n                {\n                    s += unicode_str_to_char< Char_t >( begin );  \n                }\n                break;\n            }\n        }\n    }\n\n    template< class String_t >\n    String_t substitute_esc_chars( typename String_t::const_iterator begin, \n                                   typename String_t::const_iterator end )\n    {\n        typedef typename String_t::const_iterator Iter_t;\n\n        if( end - begin < 2 ) return String_t( begin, end );\n\n        String_t result;\n        \n        result.reserve( end - begin );\n\n        const Iter_t end_minus_1( end - 1 );\n\n        Iter_t substr_start = begin;\n        Iter_t i = begin;\n\n        for( ; i < end_minus_1; ++i )\n        {\n            if( *i == '\\\\' )\n            {\n                result.append( substr_start, i );\n\n                ++i;  // skip the '\\'\n             \n                append_esc_char_and_incr_iter( result, i, end );\n\n                substr_start = i + 1;\n            }\n        }\n\n        result.append( substr_start, end );\n\n        return result;\n    }\n\n    template< class String_t >\n    String_t get_str_( typename String_t::const_iterator begin, \n                       typename String_t::const_iterator end )\n    {\n        assert( end - begin >= 2 );\n\n        typedef typename String_t::const_iterator Iter_t;\n\n        Iter_t str_without_quotes( ++begin );\n        Iter_t end_without_quotes( --end );\n\n        return substitute_esc_chars< String_t >( str_without_quotes, end_without_quotes );\n    }\n\n    string get_str( string::const_iterator begin, string::const_iterator end )\n    {\n        return get_str_< string >( begin, end );\n    }\n\n    wstring get_str( wstring::const_iterator begin, wstring::const_iterator end )\n    {\n        return get_str_< wstring >( begin, end );\n    }\n    \n    template< class String_t, class Iter_t >\n    String_t get_str( Iter_t begin, Iter_t end )\n    {\n        const String_t tmp( begin, end );  // convert multipass iterators to string iterators\n\n        return get_str( tmp.begin(), tmp.end() );\n    }\n\n    // this class's methods get called by the spirit parse resulting\n    // in the creation of a JSON object or array\n    //\n    // NB Iter_t could be a std::string iterator, wstring iterator, a position iterator or a multipass iterator\n    //\n    template< class String_t, class Iter_t >\n    class Semantic_actions \n    {\n    public:\n\n        typedef Value_impl< String_t >        Value_t;\n        typedef Pair_impl < String_t >        Pair_t;\n        typedef typename Value_t::Object      Object_t;\n        typedef typename Value_t::Array       Array_t;\n        typedef typename String_t::value_type Char_t;\n\n        Semantic_actions( Value_t& value )\n        :   value_( value )\n        ,   current_p_( 0 )\n        {\n        }\n\n        void begin_obj( Char_t c )\n        {\n            assert( c == '{' );\n\n            begin_compound< Object_t >();\n        }\n\n        void end_obj( Char_t c )\n        {\n            assert( c == '}' );\n\n            end_compound();\n        }\n\n        void begin_array( Char_t c )\n        {\n            assert( c == '[' );\n     \n            begin_compound< Array_t >();\n       }\n\n        void end_array( Char_t c )\n        {\n            assert( c == ']' );\n\n            end_compound();\n        }\n\n        void new_name( Iter_t begin, Iter_t end )\n        {\n            assert( current_p_->type() == obj_type );\n\n            name_ = get_str< String_t >( begin, end );\n        }\n\n        void new_str( Iter_t begin, Iter_t end )\n        {\n            add_to_current( get_str< String_t >( begin, end ) );\n        }\n\n        void new_true( Iter_t begin, Iter_t end )\n        {\n            assert( is_eq( begin, end, \"true\" ) );\n\n            add_to_current( true );\n        }\n\n        void new_false( Iter_t begin, Iter_t end )\n        {\n            assert( is_eq( begin, end, \"false\" ) );\n\n            add_to_current( false );\n        }\n\n        void new_null( Iter_t begin, Iter_t end )\n        {\n            assert( is_eq( begin, end, \"null\" ) );\n\n            add_to_current( Value_t() );\n        }\n\n        void new_int( int64_t i )\n        {\n            add_to_current( i );\n        }\n\n        void new_real( double d )\n        {\n            add_to_current( d );\n        }\n\n    private:\n\n        void add_first( const Value_t& value )\n        {\n            assert( current_p_ == 0 );\n\n            value_ = value;\n            current_p_ = &value_;\n        }\n\n        template< class Array_or_obj >\n        void begin_compound()\n        {\n            if( current_p_ == 0 )\n            {\n                add_first( Array_or_obj() );\n            }\n            else\n            {\n                stack_.push_back( current_p_ );\n\n                Array_or_obj new_array_or_obj;   // avoid copy by building new array or object in place\n\n                add_to_current( new_array_or_obj );\n\n                if( current_p_->type() == array_type )\n                {\n                    current_p_ = &current_p_->get_array().back(); \n                }\n                else\n                {\n                    current_p_ = &current_p_->get_obj().back().value_; \n                }\n            }\n        }\n\n        void end_compound()\n        {\n            if( current_p_ != &value_ )\n            {\n                current_p_ = stack_.back();\n                \n                stack_.pop_back();\n            }    \n        }\n\n        void add_to_current( const Value_t& value )\n        {\n            if( current_p_ == 0 )\n            {\n                add_first( value );\n            }\n            else if( current_p_->type() == array_type )\n            {\n                current_p_->get_array().push_back( value );\n            }\n            else  if( current_p_->type() == obj_type )\n            {\n                current_p_->get_obj().push_back( Pair_t( name_, value ) );\n            }\n        }\n\n        Value_t& value_;             // this is the object or array that is being created\n        Value_t* current_p_;         // the child object or array that is currently being constructed\n\n        vector< Value_t* > stack_;   // previous child objects and arrays\n\n        String_t name_;              // of current name/value pair\n    };\n\n    template< typename Iter_t >\n    void throw_error( position_iterator< Iter_t > i, const std::string& reason )\n    {\n        throw Error_position( i.get_position().line, i.get_position().column, reason );\n    }\n\n    template< typename Iter_t >\n    void throw_error( Iter_t i, const std::string& reason )\n    {\n       throw reason;\n    }\n\n    // the spirit grammer \n    //\n    template< class String_t, class Iter_t >\n    class Json_grammer : public grammar< Json_grammer< String_t, Iter_t > >\n    {\n    public:\n\n        typedef Semantic_actions< String_t, Iter_t > Semantic_actions_t;\n\n        Json_grammer( Semantic_actions_t& semantic_actions )\n        :   actions_( semantic_actions )\n        {\n        }\n\n        static void throw_not_value( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"not a value\" );\n        }\n\n        static void throw_not_array( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"not an array\" );\n        }\n\n        static void throw_not_object( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"not an object\" );\n        }\n\n        static void throw_not_pair( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"not a pair\" );\n        }\n\n        static void throw_not_colon( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"no colon in pair\" );\n        }\n\n        static void throw_not_string( Iter_t begin, Iter_t end )\n        {\n    \t    throw_error( begin, \"not a string\" );\n        }\n\n        template< typename ScannerT >\n        struct definition\n        {\n            definition( const Json_grammer& self )\n            {\n                typedef typename String_t::value_type Char_t;\n\n                // first we convert the semantic action class methods to functors with the \n                // parameter signature expected by spirit\n\n                typedef function< void( Char_t )         > Char_action;\n                typedef function< void( Iter_t, Iter_t ) > Str_action;\n                typedef function< void( double )         > Real_action;\n                typedef function< void( int64_t )        > Int_action;\n\n                Char_action begin_obj  ( bind( &Semantic_actions_t::begin_obj,   &self.actions_, _1 ) );\n                Char_action end_obj    ( bind( &Semantic_actions_t::end_obj,     &self.actions_, _1 ) );\n                Char_action begin_array( bind( &Semantic_actions_t::begin_array, &self.actions_, _1 ) );\n                Char_action end_array  ( bind( &Semantic_actions_t::end_array,   &self.actions_, _1 ) );\n                Str_action  new_name   ( bind( &Semantic_actions_t::new_name,    &self.actions_, _1, _2 ) );\n                Str_action  new_str    ( bind( &Semantic_actions_t::new_str,     &self.actions_, _1, _2 ) );\n                Str_action  new_true   ( bind( &Semantic_actions_t::new_true,    &self.actions_, _1, _2 ) );\n                Str_action  new_false  ( bind( &Semantic_actions_t::new_false,   &self.actions_, _1, _2 ) );\n                Str_action  new_null   ( bind( &Semantic_actions_t::new_null,    &self.actions_, _1, _2 ) );\n                Real_action new_real   ( bind( &Semantic_actions_t::new_real,    &self.actions_, _1 ) );\n                Int_action  new_int    ( bind( &Semantic_actions_t::new_int,     &self.actions_, _1 ) );\n\n                // actual grammer\n\n                json_\n                    = value_ | eps_p[ &throw_not_value ]\n                    ;\n\n                value_\n                    = string_[ new_str ] \n                    | number_ \n                    | object_ \n                    | array_ \n                    | str_p( \"true\" ) [ new_true  ] \n                    | str_p( \"false\" )[ new_false ] \n                    | str_p( \"null\" ) [ new_null  ]\n                    ;\n\n                object_ \n                    = ch_p('{')[ begin_obj ]\n                    >> !members_\n                    >> ( ch_p('}')[ end_obj ] | eps_p[ &throw_not_object ] )\n                    ;\n\n                members_\n                    = pair_ >> *( ',' >> pair_ )\n                    ;\n\n                pair_\n                    = string_[ new_name ]\n                    >> ( ':' | eps_p[ &throw_not_colon ] )\n                    >> ( value_ | eps_p[ &throw_not_value ] )\n                    ;\n\n                array_\n                    = ch_p('[')[ begin_array ]\n                    >> !elements_\n                    >> ( ch_p(']')[ end_array ] | eps_p[ &throw_not_array ] )\n                    ;\n\n                elements_\n                    = value_ >> *( ',' >> value_ )\n                    ;\n\n                string_ \n                    = lexeme_d // this causes white space inside a string to be retained\n                      [\n                          confix_p\n                          ( \n                              '\"', \n                              *lex_escape_ch_p,\n                              '\"'\n                          ) \n                      ]\n                    ;\n\n                number_\n                    = strict_real_p[ new_real ] \n                    | int64_p      [ new_int  ]\n                    ;\n            }\n\n            rule< ScannerT > json_, object_, members_, pair_, array_, elements_, value_, string_, number_;\n\n            const rule< ScannerT >& start() const { return json_; }\n        };\n\n        Semantic_actions_t& actions_;\n    };\n\n    template< class Iter_t, class Value_t >\n    Iter_t read_range_or_throw( Iter_t begin, Iter_t end, Value_t& value )\n    {\n        typedef typename Value_t::String_type String_t;\n\n        Semantic_actions< String_t, Iter_t > semantic_actions( value );\n     \n        const parse_info< Iter_t > info = parse( begin, end, \n                                                 Json_grammer< String_t, Iter_t >( semantic_actions ), \n                                                 space_p );\n\n        if( !info.hit )\n        {\n            assert( false ); // in theory exception should already have been thrown\n            throw_error( info.stop, \"error\" );\n        }\n\n        return info.stop;\n    }\n\n    template< class Iter_t, class Value_t >\n    void add_posn_iter_and_read_range_or_throw( Iter_t begin, Iter_t end, Value_t& value )\n    {\n        typedef position_iterator< Iter_t > Posn_iter_t;\n\n        const Posn_iter_t posn_begin( begin, end );\n        const Posn_iter_t posn_end( end, end );\n     \n        read_range_or_throw( posn_begin, posn_end, value );\n    }\n\n    template< class Iter_t, class Value_t >\n    bool read_range( Iter_t& begin, Iter_t end, Value_t& value )\n    {\n        try\n        {\n            begin = read_range_or_throw( begin, end, value );\n\n            return true;\n        }\n        catch( ... )\n        {\n            return false;\n        }\n    }\n\n    template< class String_t, class Value_t >\n    void read_string_or_throw( const String_t& s, Value_t& value )\n    {\n        add_posn_iter_and_read_range_or_throw( s.begin(), s.end(), value );\n    }\n\n    template< class String_t, class Value_t >\n    bool read_string( const String_t& s, Value_t& value )\n    {\n        typename String_t::const_iterator begin = s.begin();\n\n        return read_range( begin, s.end(), value );\n    }\n\n    template< class Istream_t >\n    struct Multi_pass_iters\n    {\n        typedef typename Istream_t::char_type Char_t;\n        typedef istream_iterator< Char_t, Char_t > istream_iter;\n        typedef multi_pass< istream_iter > multi_pass_iter;\n\n        Multi_pass_iters( Istream_t& is )\n        {\n            is.unsetf( ios::skipws );\n\n            begin_ = make_multi_pass( istream_iter( is ) );\n            end_   = make_multi_pass( istream_iter() );\n        }\n\n        multi_pass_iter begin_;\n        multi_pass_iter end_;\n    };\n\n    template< class Istream_t, class Value_t >\n    bool read_stream( Istream_t& is, Value_t& value )\n    {\n        Multi_pass_iters< Istream_t > mp_iters( is );\n\n        return read_range( mp_iters.begin_, mp_iters.end_, value );\n    }\n\n    template< class Istream_t, class Value_t >\n    void read_stream_or_throw( Istream_t& is, Value_t& value )\n    {\n        const Multi_pass_iters< Istream_t > mp_iters( is );\n\n        add_posn_iter_and_read_range_or_throw( mp_iters.begin_, mp_iters.end_, value );\n    }\n}\n\nbool json_spirit::read( const std::string& s, Value& value )\n{\n    return read_string( s, value );\n}\n\nvoid json_spirit::read_or_throw( const std::string& s, Value& value )\n{\n    read_string_or_throw( s, value );\n}\n\nbool json_spirit::read( std::istream& is, Value& value )\n{\n    return read_stream( is, value );\n}\n\nvoid json_spirit::read_or_throw( std::istream& is, Value& value )\n{\n    read_stream_or_throw( is, value );\n}\n\nbool json_spirit::read( std::string::const_iterator& begin, std::string::const_iterator end, Value& value )\n{\n    return read_range( begin, end, value );\n}\n\nvoid json_spirit::read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, Value& value )\n{\n    begin = read_range_or_throw( begin, end, value );\n}\n\n#ifndef BOOST_NO_STD_WSTRING\n\nbool json_spirit::read( const std::wstring& s, wValue& value )\n{\n    return read_string( s, value );\n}\n\nvoid json_spirit::read_or_throw( const std::wstring& s, wValue& value )\n{\n    read_string_or_throw( s, value );\n}\n\nbool json_spirit::read( std::wistream& is, wValue& value )\n{\n    return read_stream( is, value );\n}\n\nvoid json_spirit::read_or_throw( std::wistream& is, wValue& value )\n{\n    read_stream_or_throw( is, value );\n}\n\nbool json_spirit::read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value )\n{\n    return read_range( begin, end, value );\n}\n\nvoid json_spirit::read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value )\n{\n    begin = read_range_or_throw( begin, end, value );\n}\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_reader.h",
    "content": "#ifndef JASON_SPIRIT_READER\n#define JASON_SPIRIT_READER\n\n/* Copyright (c) 2007-2009 John W Wilkinson\n\n   json spirit version 3.00\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include \"json_spirit_value.h\"\n#include <iostream>\n\nnamespace json_spirit\n{\n    // functions to reads a JSON values\n\n    bool read( const std::string& s, Value& value );\n    bool read( std::istream&  is,    Value& value );\n    bool read( std::string::const_iterator& begin, std::string::const_iterator end, Value& value );\n\n#ifndef BOOST_NO_STD_WSTRING\n\n    bool read( const std::wstring& s, wValue& value );\n    bool read( std::wistream&  is,    wValue& value );\n    bool read( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value );    \n\n#endif\n\n    // the following functions read a JSON values as per the standard functions above but throw an\n    // Error_position on finding an error, they are around 3 times slower than the standard functions\n\n    struct Error_position\n    {\n        Error_position();\n        Error_position( unsigned int line, unsigned int column, const std::string& reason );\n        bool operator==( const Error_position& lhs ) const;\n        unsigned int line_;\n        unsigned int column_;\n        std::string reason_;\n    };\n\n    void read_or_throw( const std::string& s, Value& value );  \n    void read_or_throw( std::istream&  is,    Value& value );\n    void read_or_throw( std::string::const_iterator& begin, std::string::const_iterator end, Value& value );\n\n#ifndef BOOST_NO_STD_WSTRING\n\n    void read_or_throw( const std::wstring& s, wValue& value );\n    void read_or_throw( std::wistream&  is,    wValue& value );\n    void read_or_throw( std::wstring::const_iterator& begin, std::wstring::const_iterator end, wValue& value );\n\n#endif\n\n}\n\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_utils.h",
    "content": "#ifndef JASON_SPIRIT_UTILS\n#define JASON_SPIRIT_UTILS\n\n/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include \"json_spirit_value.h\"\n#include <map>\n\nnamespace json_spirit\n{ \n    //template< class Object_t, class String_t >\n    //Value_impl< String_t >& find_value( const Object_t& obj, const String_t &name );\n\n    template< class Obj_t, class Map_t >\n    void obj_to_map( const Obj_t& obj, Map_t& mp_obj )\n    {\n        mp_obj.clear();\n\n        for( typename Obj_t::const_iterator i = obj.begin(); i != obj.end(); ++i )\n        {\n            mp_obj[ i->name_ ] = i->value_;\n        }\n    }\n\n    template< class Obj_t, class Map_t >\n    void map_to_obj( const Map_t& mp_obj, Obj_t& obj )\n    {\n        obj.clear();\n\n        for( typename Map_t::const_iterator i = mp_obj.begin(); i != mp_obj.end(); ++i )\n        {\n            obj.push_back( typename Obj_t::value_type( i->first, i->second ) );\n        }\n    }\n\n    typedef std::map< std::string, Value > Mapped_obj;\n\n#ifndef BOOST_NO_STD_WSTRING\n    typedef std::map< std::wstring, wValue > wMapped_obj;\n#endif\n\n    template< class Object_t, class String_t >\n    const Value_impl< String_t >& find_value( const Object_t& obj, const String_t& name )\n    {\n        for( typename Object_t::const_iterator i = obj.begin(); i != obj.end(); ++i )\n        {\n            if( i->name_ == name )\n            {\n                return i->value_;\n            }\n        }\n\n        return Value_impl< String_t >::null;\n    }\n}\n\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_value.cpp",
    "content": "/* Copyright (c) 2007 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 2.00\n\n#include \"json_spirit_value.h\"\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_value.h",
    "content": "#ifndef JASON_SPIRIT_VALUE\n#define JASON_SPIRIT_VALUE\n\n/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include <boost/config.hpp> \n#include <boost/cstdint.hpp> \n#include <boost/shared_ptr.hpp> \n#include <vector>\n#include <string>\n#include <cassert>\n\nnamespace json_spirit\n{\n    enum Value_type{ obj_type, array_type, str_type, bool_type, int_type, real_type, null_type };\n\n    template< class String > struct Pair_impl;\n\n    template< class String >        // eg std::string or std::wstring\n    class Value_impl\n    {\n    public:\n\n        typedef String                              String_type;\n        typedef Pair_impl< String >                 Pair;\n        typedef std::vector< Pair >                 Object;\n        typedef std::vector< Value_impl< String > > Array;\n        typedef typename String::const_pointer      Const_str_ptr;  // eg const char*\n\n        Value_impl();  // creates null value\n        Value_impl( Const_str_ptr  value ); \n        Value_impl( const String&  value );\n        Value_impl( const Object&  value );\n        Value_impl( const Array&   value );\n        Value_impl( bool           value );\n        Value_impl( int            value );\n        Value_impl( boost::int64_t value );\n        Value_impl( double         value );\n\n        Value_impl( const Value_impl& other );\n\n        bool operator==( const Value_impl& lhs ) const;\n\n        Value_impl& operator=( const Value_impl& lhs );\n\n        Value_type type() const;\n\n        const String&  get_str()   const;\n        const Object&  get_obj()   const;\n        const Array&   get_array() const;\n        bool           get_bool()  const;\n        int            get_int()   const;\n        boost::int64_t get_int64() const;\n        double         get_real()  const;\n\n        Object& get_obj();\n        Array&  get_array();\n\n        template< typename T > T get_value() const;  // example usage: int    i = value.get_value< int >();\n                                                     // or             double d = value.get_value< double >();\n\n        static const Value_impl null;\n\n    private:\n\n        Value_type type_;\n\n        typedef boost::shared_ptr< Object > Object_ptr;\n        typedef boost::shared_ptr< Array > Array_ptr;\n\n        String str_;\n        Object_ptr obj_p_;\n        Array_ptr array_p_;\n        union\n        {\n           bool bool_;\n           boost::int64_t i_;\n           double d_;\n        };    \n    };\n\n    template< class String >\n    struct Pair_impl\n    {\n        typedef String String_type;\n        typedef Value_impl< String > Value_type;\n\n        Pair_impl( const String& name, const Value_type& value );\n\n        bool operator==( const Pair_impl< String >& lhs ) const;\n\n        String name_;\n        Value_type value_;\n    };\n\n    // typedefs for ASCII, compatible with JSON Spirit v1.02\n\n    typedef Value_impl< std::string > Value;\n    typedef Pair_impl < std::string > Pair;\n    typedef Value::Object Object;\n    typedef Value::Array Array;\n\n    // typedefs for Unicode, new for JSON Spirit v2.00\n\n#ifndef BOOST_NO_STD_WSTRING\n    typedef Value_impl< std::wstring > wValue;\n    typedef Pair_impl < std::wstring > wPair;\n    typedef wValue::Object wObject;\n    typedef wValue::Array wArray;\n#endif\n\n    ///////////////////////////////////////////////////////////////////////////////////////////////\n    //\n    // implementation\n\n    template< class String >\n    const Value_impl< String > Value_impl< String >::null;\n\n    template< class String >\n    Value_impl< String >::Value_impl()\n    :   type_( null_type )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( const Const_str_ptr value )\n    :   type_( str_type )\n    ,   str_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( const String& value )\n    :   type_( str_type )\n    ,   str_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( const Object& value )\n    :   type_( obj_type )\n    ,   obj_p_( new Object( value ) )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( const Array& value )\n    :   type_( array_type )\n    ,   array_p_( new Array( value ) )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( bool value )\n    :   type_( bool_type )\n    ,   bool_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( int value )\n    :   type_( int_type )\n    ,   i_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( boost::int64_t value )\n    :   type_( int_type )\n    ,   i_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( double value )\n    :   type_( real_type )\n    ,   d_( value )\n    {\n    }\n\n    template< class String >\n    Value_impl< String >::Value_impl( const Value_impl< String >& other )\n    :   type_( other.type() )\n    {\n        switch( type_ )\n        {\n            case str_type:   str_     = other.get_str();                               break;\n            case obj_type:   obj_p_   = Object_ptr( new Object( other.get_obj() ) );   break;\n            case array_type: array_p_ = Array_ptr ( new Array ( other.get_array() ) ); break;\n            case bool_type:  bool_    = other.get_bool();                              break;\n            case int_type:   i_       = other.get_int64();                             break;\n            case real_type:  d_       = other.get_real();                              break;\n            case null_type:                                                            break;\n            default: assert( false );\n        };\n    }\n\n    template< class String >\n    Value_impl< String >& Value_impl< String >::operator=( const Value_impl& lhs )\n    {\n        Value_impl tmp( lhs );\n\n        std::swap( type_, tmp.type_ );\n        str_    .swap( tmp.str_ );\n        obj_p_  .swap( tmp.obj_p_ );\n        array_p_.swap( tmp.array_p_ );\n\n        switch( type_ )\n        {\n            case bool_type:  std::swap( bool_, tmp.bool_ ); break;\n            case int_type:   std::swap( i_,    tmp.i_ );    break;\n            case real_type:  std::swap( d_,    tmp.d_ );    break;\n            default: ;\n\n        };\n\n        return *this;\n    }\n\n    template< class String >\n    bool Value_impl< String >::operator==( const Value_impl& lhs ) const\n    {\n        if( this == &lhs ) return true;\n\n        if( type() != lhs.type() ) return false;\n\n        switch( type_ )\n        {\n            case str_type:   return get_str()   == lhs.get_str();\n            case obj_type:   return get_obj()   == lhs.get_obj();\n            case array_type: return get_array() == lhs.get_array();\n            case bool_type:  return get_bool()  == lhs.get_bool();\n            case int_type:   return get_int64() == lhs.get_int64();\n            case real_type:  return get_real()  == lhs.get_real();\n            case null_type:  return true;\n        };\n\n        assert( false );\n\n        return false; \n    }\n\n    template< class String >\n    Value_type Value_impl< String >::type() const\n    {\n        return type_;\n    }\n\n    template< class String >\n    const String& Value_impl< String >::get_str() const\n    {\n        assert( type() == str_type );\n\n        return str_;\n    }\n\n    template< class String >\n    const typename Value_impl< String >::Object& Value_impl< String >::get_obj() const\n    {\n        assert( type() == obj_type );\n\n        return *obj_p_;\n    }\n     \n    template< class String >\n    const typename Value_impl< String >::Array& Value_impl< String >::get_array() const\n    {\n        assert( type() == array_type );\n\n        return *array_p_;\n    }\n     \n    template< class String >\n    bool Value_impl< String >::get_bool() const\n    {\n        assert( type() == bool_type );\n\n        return bool_;\n    }\n     \n    template< class String >\n    int Value_impl< String >::get_int() const\n    {\n        assert( type() == int_type );\n\n        return static_cast< int >( i_ );\n    }\n    \n    template< class String >\n    boost::int64_t Value_impl< String >::get_int64() const\n    {\n        assert( type() == int_type );\n\n        return i_;\n    }\n\n    template< class String >\n    double Value_impl< String >::get_real() const\n    {\n        assert( type() == real_type );\n\n        return d_;\n    }\n\n    template< class String >\n    typename Value_impl< String >::Object& Value_impl< String >::get_obj()\n    {\n        assert( type() == obj_type );\n\n        return *obj_p_;\n    }\n\n    template< class String >\n    typename Value_impl< String >::Array& Value_impl< String >::get_array()\n    {\n        assert( type() == array_type );\n\n        return *array_p_;\n    }\n\n    template< class String >\n    Pair_impl< String >::Pair_impl( const String& name, const Value_impl< String >& value )\n    :   name_( name )\n    ,   value_( value )\n    {\n    }\n\n    template< class String >\n    bool Pair_impl< String >::operator==( const Pair_impl& lhs ) const\n    {\n        if( this == &lhs ) return true;\n\n        return ( name_ == lhs.name_ ) && ( value_ == lhs.value_ );\n    }\n\n    // converts a C string, ie. 8 bit char array, to a string object\n    //\n    template < class String_t >\n    String_t to_str( const char* c_str )\n    {\n        String_t result;\n\n        for( const char* p = c_str; *p != 0; ++p )\n        {\n            result += *p;\n        }\n\n        return result;\n    }\n\n    //\n\n    namespace internal_\n    {\n        template< typename T >\n        struct Type_to_type\n        {\n        };\n\n        template< class Value > \n        int get_value( const Value& value, Type_to_type< int > )\n        {\n            return value.get_int();\n        }\n       \n        template< class Value > \n        boost::int64_t get_value( const Value& value, Type_to_type< boost::int64_t > )\n        {\n            return value.get_int64();\n        }\n       \n        template< class Value > \n        double get_value( const Value& value, Type_to_type< double > )\n        {\n            return value.get_real();\n        }\n       \n        template< class Value > \n        typename Value::String_type get_value( const Value& value, Type_to_type< typename Value::String_type > )\n        {\n            return value.get_str();\n        }\n       \n        template< class Value > \n        typename Value::Array get_value( const Value& value, Type_to_type< typename Value::Array > )\n        {\n            return value.get_array();\n        }\n       \n        template< class Value > \n        typename Value::Object get_value( const Value& value, Type_to_type< typename Value::Object > )\n        {\n            return value.get_obj();\n        }\n       \n        template< class Value > \n        bool get_value( const Value& value, Type_to_type< bool > )\n        {\n            return value.get_bool();\n        }\n    }\n\n    template< class String >\n    template< typename T > \n    T Value_impl< String >::get_value() const\n    {\n        return internal_::get_value( *this, internal_::Type_to_type< T >() );\n    }\n}\n\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_writer.cpp",
    "content": "/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#include \"json_spirit_writer.h\"\n#include \"json_spirit_value.h\"\n\n#include <cassert>\n#include <sstream>\n#include <iomanip>\n\nusing namespace json_spirit;\nusing namespace std;\n\nnamespace\n{\n    // this class solely allows its inner classes and methods to\n    // be conveniently templatised by Value type and dependent types\n    //\n    template< class Value_t >\n    struct Writer\n    {\n        typedef typename Value_t::String_type     String_t;\n        typedef typename Value_t::Object          Object_t;\n        typedef typename Value_t::Array           Array_t;\n        typedef typename String_t::value_type     Char_t;\n        typedef typename String_t::const_iterator Iter_t;\n        typedef Pair_impl< String_t >             Pair_t;\n        typedef std::basic_ostream< Char_t >      Ostream_t;\n\n        // this class generates the JSON text,\n        // it keeps track of the indentation level etc.\n        //\n        class Generator\n        {\n        public:\n\n            Generator( const Value_t& value, Ostream_t& os, bool pretty )\n            :   os_( os )\n            ,   indentation_level_( 0 )\n            ,   pretty_( pretty )\n            {\n                output( value );\n            }\n\n        private:\n\n            void output( const Value_t& value )\n            {\n                switch( value.type() )\n                {\n                    case obj_type:   output( value.get_obj() );   break;\n                    case array_type: output( value.get_array() ); break;\n                    case str_type:   output( value.get_str() );   break;\n                    case bool_type:  output( value.get_bool() );  break;\n                    case int_type:   os_ << value.get_int64();    break;\n                    case real_type:  os_ << showpoint << setprecision( 16 ) \n                                         << value.get_real();     break;\n                    case null_type:  os_ << \"null\";               break;\n                    default: assert( false );\n                }\n            }\n\n            void output( const Object_t& obj )\n            {\n                output_array_or_obj( obj, '{', '}' );\n            }\n\n            void output( const Array_t& arr )\n            {\n                output_array_or_obj( arr, '[', ']' );\n            }\n\n            void output( const Pair_t& pair )\n            {\n                output( pair.name_ ); space(); os_ << ':'; space(); output( pair.value_ );\n            }\n\n            void output( const String_t& s )\n            {\n                os_ << '\"' << add_esc_chars( s ) << '\"';\n            }\n\n            void output( bool b )\n            {\n                os_ << to_str( b ? \"true\" : \"false\" );\n            }\n\n            template< class T >\n            void output_array_or_obj( const T& t, Char_t start_char, Char_t end_char )\n            {\n                os_ << start_char; new_line();\n\n                ++indentation_level_;\n                \n                for( typename T::const_iterator i = t.begin(); i != t.end(); ++i )\n                {\n                    indent(); output( *i );\n\n                    if( i != t.end() - 1 )\n                    {\n                        os_ << ',';\n                    }\n\n                    new_line();\n                }\n\n                --indentation_level_;\n\n                indent(); os_ << end_char;\n            }\n            \n            void indent()\n            {\n                if( !pretty_ ) return;\n\n                for( int i = 0; i < indentation_level_; ++i )\n                { \n                    os_ << \"    \";\n                }\n            }\n\n            void space()\n            {\n                if( pretty_ ) os_ << ' ';\n            }\n\n            void new_line()\n            {\n                if( pretty_ ) os_ << '\\n';\n            }\n\n            String_t to_str( const char* c_str )\n            {\n                return ::to_str< String_t >( c_str );\n            }\n\n            Char_t to_hex( Char_t c )\n            {\n                assert( c <= 0xF );\n\n                if( c < 10 ) return '0' + c;\n\n                return 'A' + c - 10;\n            }\n\n            String_t non_printable_to_string( unsigned int c )\n            {\n                String_t result( 6, '\\\\' );\n\n                result[1] = 'u';\n\n                result[ 5 ] = to_hex( c & 0x000F ); c >>= 4;\n                result[ 4 ] = to_hex( c & 0x000F ); c >>= 4;\n                result[ 3 ] = to_hex( c & 0x000F ); c >>= 4;\n                result[ 2 ] = to_hex( c & 0x000F );\n\n                return result;\n            }\n\n            bool add_esc_char( Char_t c, String_t& s )\n            {\n                switch( c )\n                {\n                    case '\"':  s += to_str( \"\\\\\\\"\" ); return true;\n                    case '\\\\': s += to_str( \"\\\\\\\\\" ); return true;\n                    case '\\b': s += to_str( \"\\\\b\"  ); return true;\n                    case '\\f': s += to_str( \"\\\\f\"  ); return true;\n                    case '\\n': s += to_str( \"\\\\n\"  ); return true;\n                    case '\\r': s += to_str( \"\\\\r\"  ); return true;\n                    case '\\t': s += to_str( \"\\\\t\"  ); return true;\n                }\n\n                return false;\n            }\n\n            String_t add_esc_chars( const String_t& s )\n            {\n                String_t result;\n\n                const Iter_t end( s.end() );\n\n                for( Iter_t i = s.begin(); i != end; ++i )\n                {\n                    const Char_t c( *i );\n\n                    if( add_esc_char( c, result ) ) continue;\n\n                    const wint_t unsigned_c( ( c >= 0 ) ? c : 256 + c );\n\n                    if( iswprint( unsigned_c ) )\n                    {\n                        result += c;\n                    }\n                    else\n                    {\n                        result += non_printable_to_string( unsigned_c );\n                    }\n                }\n\n                return result;\n            }\n\n            Ostream_t& os_;\n            int indentation_level_;\n            bool pretty_;\n        };\n\n        static void write( const Value_t& value, Ostream_t& os, bool pretty )\n        {\n            Generator( value, os, pretty );\n        }\n\n        static String_t write( const Value_t& value, bool pretty )\n        {\n            basic_ostringstream< Char_t > os;\n\n            write( value, os, pretty );\n\n            return os.str();\n        }\n    };\n}\n\nvoid json_spirit::write( const Value& value, std::ostream& os )\n{\n    Writer< Value >::write( value, os, false );\n}\n\nvoid json_spirit::write_formatted( const Value& value, std::ostream& os )\n{\n    Writer< Value >::write( value, os, true );\n}\n\nstd::string json_spirit::write( const Value& value )\n{\n    return Writer< Value >::write( value, false );\n}\n\nstd::string json_spirit::write_formatted( const Value& value )\n{\n    return Writer< Value >::write( value, true );\n}\n\n#ifndef BOOST_NO_STD_WSTRING\n\nvoid json_spirit::write( const wValue& value, std::wostream& os )\n{\n    Writer< wValue >::write( value, os, false );\n}\n\nvoid json_spirit::write_formatted( const wValue& value, std::wostream& os )\n{\n    Writer< wValue >::write( value, os, true );\n}\nstd::wstring json_spirit::write( const wValue&  value )\n{\n    return Writer< wValue >::write( value, false );\n}\n\nstd::wstring json_spirit::write_formatted( const wValue&  value )\n{\n    return Writer< wValue >::write( value, true );\n}\n\n#endif\n"
  },
  {
    "path": "app/boffin/json_spirit/json_spirit_writer.h",
    "content": "#ifndef JASON_SPIRIT_WRITER\n#define JASON_SPIRIT_WRITER\n\n/* Copyright (c) 2007-2009 John W Wilkinson\n\n   This source code can be used for any purpose as long as\n   this comment is retained. */\n\n// json spirit version 3.00\n\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\n# pragma once\n#endif\n\n#include \"json_spirit_value.h\"\n#include <iostream>\n\nnamespace json_spirit\n{\n    // functions to convert JSON Values to text, \n    // the \"formatted\" versions add whitespace to format the output nicely\n\n    void         write          ( const Value&   value, std::ostream&  os );\n    void         write_formatted( const Value&   value, std::ostream&  os );\n    std::string  write          ( const Value&   value );\n    std::string  write_formatted( const Value&   value );\n\n#ifndef BOOST_NO_STD_WSTRING\n    std::wstring write          ( const wValue&  value );\n    std::wstring write_formatted( const wValue&  value );\n    void         write          ( const wValue&  value, std::wostream& os );\n    void         write_formatted( const wValue&  value, std::wostream& os );\n#endif\n}\n\n#endif\n"
  },
  {
    "path": "app/boffin/layouts/SideBySideLayout.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"SideBySideLayout.h\"\n#include <QWidget>\n#include <QLayoutItem>\n#include <QTimeLine>\n\nSideBySideLayout::SideBySideLayout( QWidget* parent )\n           : QLayout( parent ), m_currentItem( 0 ), m_timeLine( new QTimeLine( 1500, this ) )\n{\n    m_timeLine->setUpdateInterval( 25 );\n    connect( m_timeLine, SIGNAL( frameChanged( int )), SLOT( onFrameChanged( int )));\n    connect( m_timeLine, SIGNAL( finished() ), SIGNAL( animationFinished() ));\n}\n\n\nSideBySideLayout::~SideBySideLayout()\n{\n    while( QLayoutItem* i = takeAt( 0 ) )\n        delete i;\n}\n\n\nvoid \nSideBySideLayout::addItem(QLayoutItem *item)\n{\n    m_itemList.push_back( item );\n    if( !m_currentItem )\n        m_currentItem = item;\n}\n\n\nQt::Orientations \nSideBySideLayout::expandingDirections() const\n{\n    return (Qt::Horizontal | Qt::Vertical);\n}\n\n\nbool \nSideBySideLayout::hasHeightForWidth() const\n{\n    return false;\n}\n\n\nint\nSideBySideLayout::count() const\n{\n    return m_itemList.count();\n}\n\n\nQLayoutItem* \nSideBySideLayout::itemAt( int index ) const\n{\n    if( index >= m_itemList.count() || index < 0 || m_itemList.isEmpty() )\n        return 0;\n    \n    return m_itemList.at( index );\n}\n\n\nQSize \nSideBySideLayout::minimumSize() const\n{\n    QSize minSize;\n    \n    foreach( QLayoutItem* i, m_itemList )\n        minSize = minSize.expandedTo( i->minimumSize() );\n    \n    return minSize;\n}\n\n\nvoid \nSideBySideLayout::setGeometry(const QRect &rect)\n{\n    QLayout::setGeometry( rect );\n    if( !m_currentItem || m_timeLine->state() == QTimeLine::Running )\n        return;\n    \n    doLayout( rect );\n}\n\n\nvoid \nSideBySideLayout::doLayout( const QRect& rect, int hOffset )\n{\n    m_currentItem->setGeometry( rect );\n    \n    foreach( QLayoutItem* i, m_itemList )\n    {\n        const int hUnits = m_itemList.indexOf( i ) - m_itemList.indexOf( m_currentItem );\n        i->setGeometry( rect.translated( ( rect.width() * hUnits ) + hOffset, 0 ));\n    }\n}\n\n\nQSize \nSideBySideLayout::sizeHint() const\n{\n    QSize sh;\n    foreach( QLayoutItem* i, m_itemList )\n        sh = sh.expandedTo( i->sizeHint() );\n    \n    return sh;\n}\n\n\nQLayoutItem* \nSideBySideLayout::takeAt( int index )\n{\n    if( index >= m_itemList.count() || index < 0 || m_itemList.isEmpty() )\n        return 0;\n    \n    return m_itemList.takeAt( index );\n}\n\n\nvoid\nSideBySideLayout::moveForward()\n{\n    int nextIndex = m_itemList.indexOf( m_currentItem ) + 1;\n    if( nextIndex >= m_itemList.count() )\n        return;\n\n    m_currentItem = m_itemList.at( nextIndex );\n    \n    if( m_timeLine->state() == QTimeLine::Running && \n        m_timeLine->direction() == QTimeLine::Backward )\n        m_timeLine->setDirection( QTimeLine::Forward );\n    else\n    {\n        m_timeLine->setDirection( QTimeLine::Forward );\n        m_timeLine->setStartFrame( geometry().width() );\n        m_timeLine->setEndFrame( 0 );\n        m_timeLine->start();\n    }\n \n}\n\n\nvoid \nSideBySideLayout::moveBackward()\n{\n    int nextIndex = m_itemList.indexOf( m_currentItem ) - 1;\n    if( nextIndex < 0 )\n        return;\n    \n    m_currentItem = m_itemList.at( nextIndex );\n\n    if( m_timeLine->state() == QTimeLine::Running && \n       m_timeLine->direction() == QTimeLine::Forward )\n        m_timeLine->setDirection( QTimeLine::Backward );\n    else\n    {\n        m_timeLine->setDirection( QTimeLine::Backward );\n        m_timeLine->setStartFrame( 0 );\n        m_timeLine->setEndFrame( -geometry().width() );\n        m_timeLine->start();\n    }\n}\n\n\nvoid \nSideBySideLayout::onFrameChanged( int frame )\n{\n    doLayout( geometry(), frame );\n}\n\n\nQWidget* \nSideBySideLayout::currentWidget()\n{\n    return m_currentItem->widget();\n}\n\nint\nSideBySideLayout::currentItemIndex()\n{\n    return m_itemList.indexOf( m_currentItem );\n}"
  },
  {
    "path": "app/boffin/layouts/SideBySideLayout.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SIDE_BY_SIDE_LAYOUT_H\n#define SIDE_BY_SIDE_LAYOUT_H\n\n#include <QLayout>\n\n/** @brief: A layout that allows 2 or more widgets to be laid out side by side\n  *         and scroll forwards and backwards with nice animation.\n  */\n\n/** still to implement: scrollToWidget method\n  *                     handle wrapping around the last/first widgets more nicely \n  *                     make sure it's robust \n  */\n\nclass SideBySideLayout : public QLayout\n{\n    Q_OBJECT\npublic:\n    SideBySideLayout( class QWidget* parent = 0 );\n    ~SideBySideLayout();\n    \n    void addItem(QLayoutItem *item);\n    Qt::Orientations expandingDirections() const;\n    bool hasHeightForWidth() const;\n    int count() const;\n    QLayoutItem *itemAt(int index) const;\n    QSize minimumSize() const;\n    void setGeometry(const QRect &rect);\n    QSize sizeHint() const;\n    QLayoutItem *takeAt(int index);\n    QWidget* currentWidget();\n    int currentItemIndex();\n    \nsignals:\n    void animationFinished();\n\npublic slots:\n    void moveForward();\n    void moveBackward();\n    \nprivate slots:\n    void onFrameChanged( int frame );\n\nprivate:\n    void doLayout( const QRect &rect, int hOffset = 0 );\n    QList<QLayoutItem *> m_itemList;\n    QLayoutItem* m_currentItem;\n    class QTimeLine* m_timeLine;\n};\n\n#endif //SIDE_BY_SIDE_LAYOUT_H"
  },
  {
    "path": "app/boffin/main.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"App.h\"\n#include \"MainWindow.h\"\n#include \"_version.h\"\n\n\nint main( int argc, char* argv[] )\n{\n    QCoreApplication::setApplicationName( \"Boffin\" );\n    QCoreApplication::setApplicationVersion( VERSION );\n\n    try\n    {\n        App app( argc, argv );\n\n        MainWindow window;\n        window.show();\n        app.init( &window );\n\n        return app.exec();\n    }\n    catch (int i)\n    {\n        return i;\n    }\n}\n"
  },
  {
    "path": "app/boffin/playdar/BoffinPlayableItem.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"BoffinPlayableItem.h\"\n#include \"jsonGetMember.h\"\n\nBoffinPlayableItemData::BoffinPlayableItemData()\n    :size(-1)\n    ,bitrate(-1)\n    ,duration(-1)\n    ,weight(0)\n    ,score(0)\n    ,preference(0)\n    ,workingweight(0)\n    ,artistId(0)\n{\n}\n\nBoffinPlayableItem::BoffinPlayableItem()\n{\n    d = new BoffinPlayableItemData;\n}\n\n//static\nBoffinPlayableItem \nBoffinPlayableItem::fromTrackResolveResult(const QVariantMap& map)\n{\n    BoffinPlayableItem result;\n    jsonGetMember(map, \"album\", result.d->album);\n    jsonGetMember(map, \"artist\", result.d->artist);\n    jsonGetMember(map, \"bitrate\", result.d->bitrate);\n    jsonGetMember(map, \"duration\", result.d->duration);\n    jsonGetMember(map, \"mimetype\", result.d->mimetype);\n    jsonGetMember(map, \"preference\", result.d->preference);\n    jsonGetMember(map, \"score\", result.d->score);\n    jsonGetMember(map, \"source\", result.d->source);\n    jsonGetMember(map, \"size\", result.d->size);\n    jsonGetMember(map, \"track\", result.d->track);\n    jsonGetMember(map, \"url\", result.d->url);\n    return result;\n}\n\n//static\nBoffinPlayableItem \nBoffinPlayableItem::fromBoffinRqlResult(const QVariantMap& map)\n{\n    BoffinPlayableItem result;\n    jsonGetMember(map, \"album\", result.d->album);\n    jsonGetMember(map, \"artist\", result.d->artist);\n    jsonGetMember(map, \"bitrate\", result.d->bitrate);\n    jsonGetMember(map, \"duration\", result.d->duration);\n    jsonGetMember(map, \"mimetype\", result.d->mimetype);\n    jsonGetMember(map, \"preference\", result.d->preference);\n    jsonGetMember(map, \"source\", result.d->source);\n    jsonGetMember(map, \"size\", result.d->size);\n    jsonGetMember(map, \"track\", result.d->track);\n    jsonGetMember(map, \"url\", result.d->url);\n    jsonGetMember(map, \"weight\", result.d->weight);\n    return result;\n}\n"
  },
  {
    "path": "app/boffin/playdar/BoffinPlayableItem.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef BOFFIN_PLAYABLE_ITEM_H\n#define BOFFIN_PLAYABLE_ITEM_H\n\n#include <QSharedData>\n#include <QVariant>\n#include <QString>\n\nstruct BoffinPlayableItemData : QSharedData\n{\n    BoffinPlayableItemData();\n\n    QString artist;\n    QString album;\n    QString track;\n    QString source;\n    QString mimetype;\n    QString url;\n    int size;           // file size in bytes\n    int bitrate;        // nominal kb/sec of encoding\n    int duration;       // track length in seconds\n    float weight;       // boffin rql items have a weight\n    float score;        // resolved items have a score\n    int preference;     // plugin preference weighting (percentage?)\n\n    float workingweight;\n    int artistId;\n};\n\nclass BoffinPlayableItem\n{\npublic:\n    BoffinPlayableItem();\n\n    // we set the bar low; if it has a url we can try to play it:\n    bool isValid() const { return d->url.length() > 0; }\n\n    QString artist() const { return d->artist; }\n    QString album() const { return d->album; }\n    QString track() const { return d->track; }\n    QString source() const { return d->source; }\n    QString mimetype() const { return d->mimetype; }\n    QString url() const { return d->url; }\n    int size() const { return d->size; }\n    int bitrate() const { return d->bitrate; }\n    int duration() const { return d->duration; }\n    float weight() const { return d->weight; }\n    float score() const { return d->score; }\n    int preference() const { return d->preference; }\n\n    float workingweight() const { return d->workingweight; }\n    int artistId() const { return d->artistId; }\n\n    // mutable:\n    float& workingweight() { return d->workingweight; }\n    int& artistId() { return d->artistId; }\n\n    static BoffinPlayableItem fromTrackResolveResult(const QVariantMap& map);\n    static BoffinPlayableItem fromBoffinRqlResult(const QVariantMap& map);\n\nprotected:\n    QExplicitlySharedDataPointer<BoffinPlayableItemData> d;\n};\n\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/BoffinRqlRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkReply>\n#include <lastfm/NetworkAccessManager>\n#include \"BoffinRqlRequest.h\"\n#include \"jsonGetMember.h\"\n\n\nvoid\nBoffinRqlRequest::onFinished()\n{\n    sender()->deleteLater();\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        QString queryId;\n        if (getQueryId(reply->readAll(), queryId)) {\n            if (queryId == qid()) {\n                // all is good\n                return;\n            }\n            fail(\"qid mismatch\");            // we can't handle this\n        }\n        fail(\"bad response\");\n    }\n    fail(\"\");\n}\n\nvoid\nBoffinRqlRequest::issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, const QString& rql, const QString& session)\n{\n    QNetworkReply *reply = wam->get(QNetworkRequest(api.boffinTracks(session, qid(), rql)));\n    if (reply) {\n        connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));\n        emit requestMade( qid());\n    } else {\n        fail(\"couldn't issue boffin rql request\");\n    }\n}\n\n//virtual\nvoid\nBoffinRqlRequest::receiveResult(const QVariantMap& o)\n{\n    emit playableItem( BoffinPlayableItem::fromBoffinRqlResult(o) );\n}\n\nvoid\nBoffinRqlRequest::fail(const char *message)\n{\n    qDebug() << message;\n\temit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/BoffinRqlRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BOFFIN_RQL_REQUEST_H\n#define BOFFIN_RQL_REQUEST_H\n\n#include <lastfm/global.h>\n#include \"PlaydarApi.h\"\n#include \"CometRequest.h\"\n#include \"BoffinPlayableItem.h\"\n\nclass BoffinRqlRequest : public CometRequest\n{\n    Q_OBJECT\n\npublic:\n    void issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, const QString& rql, const QString& session);\n    virtual void receiveResult(const QVariantMap& o);\n\nsignals:\n    void error();\n    void playableItem(BoffinPlayableItem item);\n    void requestMade( const QString );\n\nprivate slots:\n    void onFinished();\n\nprivate:\n    void fail(const char* message);\n};\n\n#endif\n\n"
  },
  {
    "path": "app/boffin/playdar/BoffinTagRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkReply>\n#include <lastfm/NetworkAccessManager>\n#include \"PlaydarApi.h\"\n#include \"BoffinTagRequest.h\"\n#include \"jsonGetMember.h\"\n\n\n\n// virtual \nvoid \nBoffinTagRequest::issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, const QString& rql, const QString& session)\n{\n    QNetworkReply* reply = wam->get(QNetworkRequest(api.boffinTags(session, qid(), rql)));\n    if (reply) {\n        connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));\n        emit requestMade( qid());\n    } else {\n        fail(\"couldn't issue boffin request\");\n    }\n}\n\n\nvoid \nBoffinTagRequest::onFinished()\n{\n    sender()->deleteLater();\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        QString queryId;\n        if (getQueryId(reply->readAll(), queryId)) {\n            if (queryId == qid()) {\n                // all is good\n                return; \n            }\n            fail(\"qid mismatch\");            // we can't handle this\n        }\n        fail(\"bad response\");\n    }\n    fail(\"\");\n}\n\n\n// virtual\nvoid\nBoffinTagRequest::receiveResult(const QVariantMap& o)\n{\n    QString tagName, hostName;\n    int count;\n    double weight;\n    int seconds;\n    if (jsonGetMember(o, \"name\", tagName) &&\n        jsonGetMember(o, \"source\", hostName) &&\n        jsonGetMember(o, \"count\", count) &&\n        jsonGetMember(o, \"weight\", weight) && \n        jsonGetMember(o, \"seconds\", seconds))\n    {\n        emit tagItem(BoffinTagItem(tagName, hostName, count, static_cast<float>(weight), seconds));\n    }\n}\n\nvoid \nBoffinTagRequest::fail(const char* message)\n{\n    qDebug() << message;\n    emit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/BoffinTagRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BOFFIN_REQUEST_H\n#define BOFFIN_REQUEST_H\n\n#include <lastfm/global.h>\n#include \"PlaydarApi.h\"\n#include \"CometRequest.h\"\n\n\nstruct BoffinTagItem\n{\n\tBoffinTagItem()\n\t{}\n\n\tBoffinTagItem( const QString& name ): m_name( name ) {};\n\n    BoffinTagItem(const QString& name, const QString& host, int count, float weight, int seconds)\n        : m_name(name)\n        , m_host(host)\n        , m_count(count)\n        , m_weight(weight)\n        , m_seconds(seconds)\n    {\n    }\n\n    bool operator==( const BoffinTagItem& that)\n    {\n    \treturn m_name == that.m_name;\n    }\n\n    bool operator <( const BoffinTagItem& that ) const\n    {\n    \treturn m_count < that.m_count;\n    }\n\n    QString m_name;\n    QString m_host;\n    int m_count;\n    float m_weight;\n    float m_logWeight;\n    float m_logCount;\n    int m_seconds;          // the total duration of tracks with this tag\n};\n\nclass BoffinTagRequest : public CometRequest\n{\n    Q_OBJECT\n\npublic:\n    void issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, const QString& rql, const QString& session);\n    virtual void receiveResult(const QVariantMap& o);\n\nsignals:\n    void error();\n    void tagItem(BoffinTagItem item);\n    void requestMade( const QString );\nprivate slots:\n    void onFinished();\n\nprivate:\n    void fail(const char* message);\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/CometRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"CometRequest.h\"\n#include <QUuid>\n#include \"jsonGetMember.h\"\n\nCometRequest::CometRequest()\n:m_qid(QUuid::createUuid().toString().mid(1, 36))\n{\n}\n\nconst QString& \nCometRequest::qid() const\n{\n    return m_qid;\n}\n\nbool \nCometRequest::getQueryId(const QByteArray& data, QString& out)\n{\n    json_spirit::Value v;\n    if (json_spirit::read(std::string(data.constData(), data.size()), v)) {\n        std::string qid;\n        if (jsonGetMember(v, \"qid\", qid)) {\n            out = QString::fromStdString(qid);\n            return true;\n        }\n    }\n    return false;\n}\n\n"
  },
  {
    "path": "app/boffin/playdar/CometRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef COMET_REQUEST_H\n#define COMET_REQUEST_H\n\n#include <QString>\n#include <QVariant>\n#include <QByteArray>\n\nclass CometRequest : public QObject\n{\n    Q_OBJECT\n\npublic:\n    CometRequest();\n    const QString& qid() const;\n    virtual void receiveResult(const QVariantMap& o) = 0;\n\nprotected:\n    bool getQueryId(const QByteArray& data, QString& out);\n\n    QString m_qid;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarApi.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_API_H\n#define PLAYDAR_API_H\n\n#include \"TPlaydarApi.hpp\"\n#include <QUrl>\n#include <QString>\n\ntypedef QList< QPair<QString,QString> > ParamList;\n\nclass PlaydarApiQtPolicy\n{\npublic:\n    static void paramsAdd(ParamList& params, const QString& name, const QString& value)\n    {\n        params.append(QPair< QString, QString>(name, value));\n    }\n\n    static QUrl createUrl(const QString& base, const QString& path, const ParamList& params)\n    {\n        QUrl url(base + path);\n        url.setQueryItems(params);\n        return url;\n    }\n};\n\n\ntypedef TPlaydarApi<QString, QUrl, ParamList, PlaydarApiQtPolicy> PlaydarApi;\n\n#endif\n\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarAuthRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkReply>\n#include \"PlaydarAuthRequest.h\"\n#include <lastfm/NetworkAccessManager>\n#include \"jsonGetMember.h\"\n\nPlaydarAuthRequest::PlaydarAuthRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api)\n:m_wam(wam)\n,m_api(api)\n{\n}\n\nvoid \nPlaydarAuthRequest::start(QString applicationName)\n{\n    m_applicationName = applicationName;\n\n    QNetworkReply* auth1Reply = m_wam->get( QNetworkRequest( m_api.auth1(applicationName) ) );\n    if (auth1Reply) {\n        connect(auth1Reply, SIGNAL(finished()), SLOT(onAuth1Finished()));\n    } else {\n        fail(\"couldn't issue auth_1 request\");\n    }\n}\n\nvoid \nPlaydarAuthRequest::onAuth1Finished()\n{\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        using namespace std;\n\n        json_spirit::Value v;\n        QByteArray ba( reply->readAll() );\n        if (json_spirit::read( string( ba.constData(), ba.size() ), v) ) {\n            string formtoken;\n            if (jsonGetMember(v, \"formtoken\", formtoken)) {\n                ParamList params;\n                QUrl url = m_api.auth2( m_applicationName, QString::fromStdString(formtoken), params );\n\n                // form encode:\n\t\t\t    QByteArray form;\n                typedef QPair<QString,QString> Param;\n\t\t\t    foreach (Param p, params) {\n                    if (form.size()) {\n                        form += \"&\";\n                    }\n\t\t\t\t    form += QUrl::toPercentEncoding( p.first ) + \"=\"\n\t\t\t\t\t      + QUrl::toPercentEncoding( p.second );\n\t\t\t    }\n\n                QNetworkReply* auth2Reply = m_wam->post(QNetworkRequest(url), form);\n                if (auth2Reply) {\n                    connect(auth2Reply, SIGNAL(finished()), SLOT(onAuth2Finished()));\n                    return;\n                }\n                fail(\"couldn't issue auth_2 request\");\n            }\n        }\n        fail(\"bad json in auth1 response\");\n    }\n    fail(\"\");\n\n}\n\nvoid\nPlaydarAuthRequest::onAuth2Finished()\n{\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        using namespace std;\n\n        json_spirit::Value v;\n        QByteArray ba( reply->readAll() );\n        if (json_spirit::read( string( ba.constData(), ba.size() ), v) ) {\n            string authtoken;\n            if (jsonGetMember(v, \"authtoken\", authtoken)) {\n                emit authed(QString::fromStdString(authtoken));\n                return;\n            }\n        }\n        fail(\"bad json in auth2 response\");\n    }\n    fail(\"\");\n}\n\nvoid \nPlaydarAuthRequest::fail(const char*)\n{\n    emit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarAuthRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_AUTH_REQUEST_H\n#define PLAYDAR_AUTH_REQUEST_H\n\n#include \"PlaydarApi.h\"\n#include <lastfm/global.h>\n#include <QObject>\n\n\nclass PlaydarAuthRequest\n    : public QObject\n{\n    Q_OBJECT\n\npublic:\n    PlaydarAuthRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api);\n    void start(QString applicationName);\n\nsignals:\n    void error();\n    void authed(QString token);\n\nprivate slots:\n    void onAuth1Finished();\n    void onAuth2Finished();\n\nprivate:\n    void fail(const char* message);\n\n    lastfm::NetworkAccessManager* m_wam;\n    PlaydarApi m_api;\n    QString m_applicationName;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarCometRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QUuid>\n#include <QNetworkReply>\n#include \"PlaydarCometRequest.h\"\n#include <lastfm/NetworkAccessManager>\n#include \"../comet/CometParser.h\"\n\n\nPlaydarCometRequest::PlaydarCometRequest()\n:m_parser(0)\n,m_sessionId( QUuid::createUuid().toString().mid(1, 36) )\n{\n}\n\n// returns the sessionId, empty string if request fails\nbool\nPlaydarCometRequest::issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api)\n{\n    QNetworkReply* reply = wam->get(QNetworkRequest(api.comet(m_sessionId)));\n    if (!reply) {\n        return false;\n    }\n\n    m_parser = new CometParser(this);\n    connect(m_parser, SIGNAL(haveObject(QVariantMap)), SIGNAL(receivedObject(QVariantMap)));\n    connect(reply, SIGNAL(readyRead()), SLOT(onFirstReadyRead()));\n    connect(reply, SIGNAL(readyRead()), SLOT(onReadyRead()));\n    connect(reply, SIGNAL(finished()), SLOT(onFinished()));\n    connect(reply, SIGNAL(error( QNetworkReply::NetworkError )), SIGNAL( error()));\n    return true;\n}\n\nvoid\nPlaydarCometRequest::onReadyRead()\n{\n    QNetworkReply* reply = (QNetworkReply*) sender();\n    QByteArray ba = reply->readAll();\n    if (!m_parser->push(ba)) {\n        qDebug() << \"json comet parse problem\";\n        qDebug() << ba;\n        reply->abort();     // can't recover from this\n        onFinished();       // assuming abort() doesn't emit finished\n    }\n}\n\nvoid\nPlaydarCometRequest::onFirstReadyRead()\n{\n    sender()->disconnect(this, SLOT(onFirstReadyRead()));\n    emit connected(m_sessionId);\n}\n\nvoid\nPlaydarCometRequest::onFinished()\n{\n    sender()->deleteLater();\n    emit finished();\n}\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarCometRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_COMET_REQUEST_H\n#define PLAYDAR_COMET_REQUEST_H\n\n#include \"PlaydarApi.h\"\n#include <lastfm/global.h>\n#include <QVariant>\n\nclass CometParser;\n\n// makes a request to playdar for comet results, \n// emits signals as result objects arrive\n//\nclass PlaydarCometRequest : public QObject\n{\n    Q_OBJECT\n\npublic:\n    PlaydarCometRequest();\n\n    // returns the sessionId, empty string if request fails\n    bool issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api);\n\nsignals:\n    void receivedObject(QVariantMap);\n    void connected(QString);\n    void finished();\n    void error();\n\nprivate slots:\n    void onReadyRead();\n    void onFirstReadyRead();\n    void onFinished();\n\nprivate:\n    CometParser *m_parser;\n    QString m_sessionId;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarConnection.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QTimer>\n#include \"PlaydarConnection.h\"\n#include \"PlaydarStatRequest.h\"\n#include \"PlaydarAuthRequest.h\"\n#include \"PlaydarRosterRequest.h\"\n#include \"PlaydarCometRequest.h\"\n#include \"TrackResolveRequest.h\"\n#include \"BoffinRqlRequest.h\"\n#include \"BoffinTagRequest.h\"\n#include <lastfm/NetworkAccessManager>\n\n\nPlaydarConnection::PlaydarConnection(lastfm::NetworkAccessManager* wam, PlaydarApi& api)\n: m_comet(0)\n, m_wam(wam)\n, m_api(api)\n, m_state(Querying)\n{\n    updateText();\n}\n\nvoid\nPlaydarConnection::start()\n{\n    PlaydarStatRequest* stat = new PlaydarStatRequest(m_wam, m_api);\n    connect(stat, SIGNAL(stat(QString, QString, QString, bool)), SLOT(onStat(QString, QString, QString, bool)));\n    connect(stat, SIGNAL(error()), SLOT(onError()));\n    stat->start();\n}\n\nvoid\nPlaydarConnection::onStat(QString name, QString version, QString hostname, bool bAuthenticated)\n{\n    m_name = name;\n    m_version = version;\n    m_hostname = hostname;\n    m_state = bAuthenticated ? Connecting : Authorising;\n    if (!bAuthenticated) {\n        PlaydarAuthRequest* auth = new PlaydarAuthRequest(m_wam, m_api);\n        connect(auth, SIGNAL(authed(QString)), SLOT(onAuth(QString)));\n        connect(auth, SIGNAL(authed(QString)), SIGNAL(authed(QString)));\n        connect(auth, SIGNAL(error()), SLOT(onError()));\n        auth->start(\"Boffin\");\n    } else {\n        makeCometRequest();\n    }\n\n    updateText();\n}\n\nvoid\nPlaydarConnection::onError()\n{\n    sender()->deleteLater();\n    switch (m_state) {\n        case Querying :\n            m_state = NotPresent;\n            break;\n        case Authorising :\n            m_state = NotAuthorised;\n            break;\n        case Connecting:\n            m_state = Connecting;\n            break;\n        case Connected :\n            m_state = Querying;\n            start();\n            break;\n        default:\n            break;\n    }\n    updateText();\n}\n\nvoid\nPlaydarConnection::onAuth(QString authToken)\n{\n    sender()->deleteLater();\n    m_api.setAuthToken(authToken);\n    m_state = Connecting;\n    updateText();\n\n    makeCometRequest();\n}\n\nvoid\nPlaydarConnection::onLanRoster(const QStringList& roster)\n{\n    sender()->deleteLater();\n    m_hostsModel.setStringList(roster);\n    QTimer::singleShot(60 * 1000, this, SLOT(makeRosterRequest()));\n}\n\nvoid\nPlaydarConnection::makeRosterRequest()\n{\n    PlaydarRosterRequest* req = new PlaydarRosterRequest(m_wam, m_api);\n    connect(req, SIGNAL(roster(QStringList)), SLOT(onLanRoster(QStringList)));\n    connect(req, SIGNAL(error()), SLOT(onError()));\n    req->start();\n}\n\nvoid\nPlaydarConnection::makeCometRequest()\n{\n    m_comet = new PlaydarCometRequest();\n    if (m_comet->issueRequest(m_wam, m_api)) {\n        connect(m_comet, SIGNAL(connected(QString)), SLOT(onCometConnected(QString)));\n        connect(m_comet, SIGNAL(error()), SLOT(onError()));\n        connect(m_comet, SIGNAL(receivedObject(QVariantMap)), SLOT(receivedCometObject(QVariantMap)));\n    }\n}\n\nvoid\nPlaydarConnection::onCometConnected(const QString& sessionId)\n{\n    m_cometSession = sessionId;\n    m_state = Connected;\n    updateText();\n    emit connected();\n}\n\nvoid\nPlaydarConnection::updateText()\n{\n    QString s;\n    switch (m_state) {\n        case Querying: s = \"Looking for Playdar\"; break;\n        case NotPresent: s = \"Playdar not available\"; break;\n        case Authorising: s = \"Authorising with Playdar\"; break;\n        case NotAuthorised: s = \"Couldn't authorise with Playdar\"; break;\n        case Connecting: s = \"Connecting to Playdar\"; break;\n        case Connected: s = \"Connected to Playdar\"; break;\n        default:\n            s = \"PlaydarConnection::updateText is broken!\";\n    }\n    emit changed(s);\n}\n\nQStringListModel*\nPlaydarConnection::hostsModel()\n{\n    return &m_hostsModel;\n}\n\nTrackResolveRequest* \nPlaydarConnection::trackResolve(const QString& artist, const QString& album, const QString& track)\n{\n    if (!m_cometSession.length()) {\n        return 0;\n    }\n    TrackResolveRequest* r = new TrackResolveRequest();\n    connect(r, SIGNAL(requestMade(QString)), SLOT(onRequestMade(QString)));\n    connect(r, SIGNAL(destroyed(QObject*)), SLOT(onRequestDestroyed(QObject*)));\n    r->issueRequest(m_wam, m_api, artist, album, track, m_cometSession);\n    return r;\n}\n\nBoffinRqlRequest*\nPlaydarConnection::boffinRql(const QString& rql)\n{\n    if (!m_cometSession.length()) {\n        return 0;\n    }\n    BoffinRqlRequest* r = new BoffinRqlRequest();\n    connect(r, SIGNAL(requestMade(QString)), SLOT(onRequestMade(QString)));\n    connect(r, SIGNAL(destroyed(QObject*)), SLOT(onRequestDestroyed(QObject*)));\n    r->issueRequest(m_wam, m_api, rql, m_cometSession);\n    return r;\n}\n\nBoffinTagRequest*\nPlaydarConnection::boffinTagcloud(const QString& rql)\n{\n    if (!m_cometSession.length()) {\n        return 0;\n    }\n    BoffinTagRequest* r = new BoffinTagRequest();\n    connect(r, SIGNAL(requestMade(QString)), SLOT(onRequestMade(QString)));\n    connect(r, SIGNAL(destroyed(QObject*)), SLOT(onRequestDestroyed(QObject*)));\n    r->issueRequest(m_wam, m_api, rql, m_cometSession);\n    return r;\n}\n\nvoid\nPlaydarConnection::onRequestMade(const QString& qid)\n{\n    m_cometReqMap[qid] = (CometRequest*) sender();\n}\n\nvoid\nPlaydarConnection::onRequestDestroyed(QObject* o)\n{\n    m_cometReqMap.remove(((CometRequest*)o)->qid());\n}\n\nvoid\nPlaydarConnection::receivedCometObject(const QVariantMap& obj)\n{\n    QVariantMap::const_iterator qit = obj.find(\"query\");\n    if (qit != obj.end() && qit->type() == QVariant::String) {\n        QVariantMap::const_iterator rit = obj.find(\"result\");\n        if (rit != obj.end() && rit->type() == QVariant::Map) {\n            // obj is the right shape, find it in\n            // the request map and emit the callback\n            QMap<QString, CometRequest*>::const_iterator reqIt = m_cometReqMap.find(qit->toString());\n            if (reqIt != m_cometReqMap.end()) {\n                reqIt.value()->receiveResult(rit->toMap());\n            } else {\n                // unknown query id.\n                qDebug() << \"warning: result for unknown query \" << qit->toString() << \" was discarded\";\n            }\n        }\n    }\n}\n\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarConnection.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_CONNECTION_H\n#define PLAYDAR_CONNECTION_H\n\n#include \"PlaydarApi.h\"\n#include <lastfm/global.h>\n#include <QStringListModel>\n\nclass PlaydarCometRequest;\nclass CometRequest;\nclass TrackResolveRequest;\nclass BoffinTagRequest;\nclass BoffinRqlRequest;\n\nclass PlaydarConnection : public QObject\n{\n    Q_OBJECT\n\npublic:\n    PlaydarConnection(lastfm::NetworkAccessManager* wam, PlaydarApi& api);\n\n    void start();\n    QStringListModel* hostsModel();\n\n    TrackResolveRequest* trackResolve(const QString& artist, const QString& album, const QString& track);\n    BoffinTagRequest* boffinTagcloud(const QString& rql);\n    BoffinRqlRequest* boffinRql(const QString& rql);\n\nsignals:\n    void changed(QString newStatusMessage);\n    void authed(QString authtoken);\n    void connected();\n\nprivate slots:\n    void onStat(QString name, QString version, QString hostname, bool bAuthenticated);\n    void onAuth(QString authToken);\n    void onLanRoster(const QStringList& roster);\n    void onError();\n    void makeRosterRequest();\n\n    void onCometConnected(const QString& sessionId);\n    void receivedCometObject(const QVariantMap&);\n    void onRequestMade(const QString& qid);\n    void onRequestDestroyed(QObject* o);\n\nprivate:\n    void updateText();\n    void makeCometRequest();\n    QString cometSession();\n\n    enum State\n    {\n        Querying, NotPresent, Authorising, NotAuthorised, Connecting, Connected\n    };\n\n    QString m_name;\n    QString m_version;\n    QString m_hostname;\n\n    QStringListModel m_hostsModel;\n\n    PlaydarCometRequest* m_comet;\n    QString m_cometSession;\n    QMap<QString, CometRequest*> m_cometReqMap;\n\n    lastfm::NetworkAccessManager* m_wam;\n    PlaydarApi& m_api;\n    State m_state;\n};\n\n#endif\n\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarRosterRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"PlaydarRosterRequest.h\"\n#include <lastfm/NetworkAccessManager>\n#include <QStringList>\n#include <QNetworkReply>\n#include <QNetworkRequest>\n#include \"jsonGetMember.h\"\n\n\nPlaydarRosterRequest::PlaydarRosterRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api)\n:m_wam(wam)\n,m_api(api)\n{\n}\n\nvoid \nPlaydarRosterRequest::start()\n{\n    QNetworkReply* reply = m_wam->get(QNetworkRequest(m_api.lanRoster()));\n    if (reply) {\n        connect(reply, SIGNAL(finished()), SLOT(onFinished()));\n    } else {\n        fail(\"couldn't issue lan roster request\");\n    }\n}\n\nvoid \nPlaydarRosterRequest::onFinished()\n{\n    sender()->deleteLater();\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        using namespace std;\n\n        json_spirit::Value v;\n        QByteArray ba( reply->readAll() );\n        string sReply( ba.constData(), ba.size() );\n        if (json_spirit::read(sReply, v) &&\n            v.type() == json_spirit::array_type) \n        {\n            QStringList result;\n\n            for (size_t i = 0; i < v.get_array().size(); i++) {\n                string name;\n                if (jsonGetMember(v.get_array()[i], \"name\", name)) {\n                    result.append(QString::fromStdString(name));\n                }\n            }\n\n            if (result.size()) {\n                emit roster(result);\n            }\n            return;\n        }\n        fail(\"bad json in poll response\");\n    }\n    fail(\"\");\n}\n\nvoid \nPlaydarRosterRequest::fail(const char* )\n{\n    emit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarRosterRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_ROSTER_REQUEST_H\n#define PLAYDAR_ROSTER_REQUEST_H\n\n#include \"PlaydarApi.h\"\n#include <lastfm/global.h>\n#include <QObject>\n\n\nclass PlaydarRosterRequest\n    : public QObject\n{\n    Q_OBJECT\n\npublic:\n    PlaydarRosterRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api);\n    void start();\n\nsignals:\n    void error();\n    void roster(const QStringList&);\n\nprivate slots:\n    void onFinished();\n\nprivate:\n    void fail(const char* message);\n\n    lastfm::NetworkAccessManager* m_wam;\n    PlaydarApi m_api;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarStatRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkReply>\n#include \"PlaydarStatRequest.h\"\n#include <lastfm/NetworkAccessManager>\n#include \"jsonGetMember.h\"\n\nPlaydarStatRequest::PlaydarStatRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api)\n:m_wam(wam)\n,m_api(api)\n,m_statReply(0)\n{\n}\n\nvoid \nPlaydarStatRequest::start()\n{\n    delete m_statReply;\n    m_statReply = 0;\n\n    m_statReply = m_wam->get( QNetworkRequest( m_api.stat() ) );\n    if (m_statReply) {\n        connect(m_statReply, SIGNAL(finished()), SLOT(onReqFinished()));\n        connect(m_statReply, SIGNAL(error( QNetworkReply::NetworkError )), SLOT(onError( QNetworkReply::NetworkError )));\n    } else {\n        fail(\"couldn't issue stat request\");\n    }\n}\n\nvoid \nPlaydarStatRequest::onReqFinished()\n{\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        using namespace std;\n\n        json_spirit::Value v;\n        QByteArray ba( reply->readAll() );\n        if (json_spirit::read( string( ba.constData(), ba.size() ), v) ) {\n            // note: hostname is only present when authenticated is true\n            string name, version, hostname;\n            bool authenticated;\n            if (jsonGetMember(v, \"name\", name) &&\n                jsonGetMember(v, \"version\", version) &&\n                jsonGetMember(v, \"authenticated\", authenticated) &&\n                (!authenticated || jsonGetMember(v, \"hostname\", hostname)) )\n            {\n                emit stat(QString::fromStdString(name), \n                    QString::fromStdString(version), \n                    QString::fromStdString(hostname), \n                    authenticated);\n                return;\n            }\n        }\n        fail(\"bad json in poll response\");\n    }\n    fail(\"\");\n}\n\nvoid \nPlaydarStatRequest::onError( QNetworkReply::NetworkError code )\n{\n    //QObject* s = sender();\n    qDebug() << \"StatRequest error: \" << code << endl;\n}\n\nvoid \nPlaydarStatRequest::fail(const char* /*message*/)\n{\n    emit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/PlaydarStatRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYDAR_STAT_REQUEST_H\n#define PLAYDAR_STAT_REQUEST_H\n\n#include <lastfm/global.h>\n#include <QPointer>\n#include <QObject>\n#include \"PlaydarApi.h\"\n#include <QNetworkReply>\nclass PlaydarStatRequest\n    : public QObject\n{\n    Q_OBJECT\n\npublic:\n    PlaydarStatRequest(lastfm::NetworkAccessManager*, PlaydarApi&);\n    void start();\n\nsignals:\n    void error();\n    void stat(QString name, QString version, QString hostname, bool bAuthenticated);\n\nprivate slots:\n    void onReqFinished();\n    void onError( QNetworkReply::NetworkError code );\n    \nprivate:\n    void fail(const char* message);\n\n    lastfm::NetworkAccessManager* m_wam;\n    PlaydarApi m_api;\n    QPointer<QNetworkReply> m_statReply;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/TPlaydarApi.hpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TPLAYDAR_API_HPP\n#define TPLAYDAR_API_HPP\n\n// Policy provides:\n//\n// void paramsAdd(ParamsT& p, StringT name, StringT value)\n// UrlT createUrl(StringT base, StringT path, ParamsT p)\n\ntemplate <typename StringT, typename UrlT, typename ParamsT, typename Policy>\nclass TPlaydarApi : public Policy\n{\npublic:\n    TPlaydarApi(const StringT& baseUrl, const StringT& token)\n        : m_baseUrl(baseUrl)\n        , m_token(token)\n    {\n    }\n\n    void setAuthToken(const StringT& token)\n    {\n        m_token = token;\n    }\n\n    UrlT apiCall(const ParamsT& params)\n    {\n        return makeUrl(\"/api/\", params);\n    }\n\n    UrlT stat()\n    {\n        ParamsT params;\n        paramsAdd(params, \"method\", \"stat\");\n        paramsAdd(params, \"auth\", m_token);\n        return apiCall(params);\n    }\n\n    UrlT auth1(const StringT& applicationName)\n    {\n        ParamsT params;\n        paramsAdd(params, \"name\", applicationName);\n        paramsAdd(params, \"website\", \"\");\n        paramsAdd(params, \"json\", \"\");\n        return makeUrl(\"/auth_1/\", params);\n    }\n\n    UrlT auth2(const StringT& applicationName, const StringT& formtoken, ParamsT& outPostParams)\n    {\n        paramsAdd(outPostParams, \"name\", applicationName);\n        paramsAdd(outPostParams, \"website\", \"\");\n        paramsAdd(outPostParams, \"formtoken\", formtoken);\n        paramsAdd(outPostParams, \"json\", \"\");\n        return makeUrl(\"/auth_2/\");\n    }\n\n    UrlT getResults(const StringT& qid)\n    {\n        ParamsT params;\n        paramsAdd(params, \"method\", \"get_results\");\n        paramsAdd(params, \"qid\", qid);\n        paramsAdd(params, \"auth\", m_token);\n        return apiCall(params);\n    }\n\n    UrlT lanRoster()\n    {\n        return makeUrl(\"/lan/roster\");\n    }\n\n    // cometsession optional\n    // qid optional\n    UrlT trackResolve(const StringT& artist, const StringT& album, const StringT& track, \n        const StringT& cometSession = StringT(), const StringT& qid = StringT())\n    {\n        ParamsT params;\n        paramsAdd(params, \"method\", \"resolve\");\n        paramsAdd(params, \"artist\", artist);\n        paramsAdd(params, \"album\", album);\n        paramsAdd(params, \"track\", track);\n        paramsAdd(params, \"auth\", m_token);\n        if (cometSession != \"\") {\n            paramsAdd(params, \"comet\", cometSession);\n        }\n        if (qid != \"\") {\n            paramsAdd(params, \"qid\", qid);\n        }\n        return apiCall(params);\n    }\n\n    // boffinTags to obtain tags and weights for a query\n    // qid optional\n    // rql optional\n    UrlT boffinTags(const StringT& cometSession, const StringT& qid = StringT(), const StringT& rql = StringT())\n    {\n        ParamsT params;\n        paramsAdd(params, \"auth\", m_token);\n        paramsAdd(params, \"comet\", cometSession);\n        if (qid != \"\") {\n            paramsAdd(params, \"qid\", qid);\n        }\n        return makeUrl(\"/boffin/tags/\" + rql, params);\n    }\n\n    // boffinTracks to obtain playable items matching a query\n    // qid optional\n    UrlT boffinTracks(const StringT& cometSession, const StringT& qid, const StringT& rql)\n    {\n        ParamsT params;\n        paramsAdd(params, \"auth\", m_token);\n        paramsAdd(params, \"comet\", cometSession);\n        if (qid != \"\") {\n            paramsAdd(params, \"qid\", qid);\n        }\n        return makeUrl(\"/boffin/tracks/\" + rql, params);\n    }\n\n    // boffinSummary provides file count and total play time for a query\n    // qid optional\n    UrlT boffinSummary(const StringT& cometSession, const StringT& qid, const StringT& rql)\n    {\n        ParamsT params;\n        paramsAdd(params, \"auth\", m_token);\n        paramsAdd(params, \"comet\", cometSession);\n        if (qid != \"\") {\n            paramsAdd(params, \"qid\", qid);\n        }\n        return makeUrl(\"/boffin/summary/\" + rql, params);\n    }\n\n    UrlT comet(const StringT& session)\n    {\n        ParamsT params;\n        paramsAdd(params, \"session\", session);\n        paramsAdd(params, \"auth\", m_token);\n        return makeUrl(\"/comet/\", params);\n    }\n\nprivate:\n    UrlT makeUrl(const StringT& path, const ParamsT& params = ParamsT())\n    {\n        return createUrl(m_baseUrl, path, params);\n    }\n\n    StringT m_baseUrl;\n    StringT m_token;\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/TrackResolveRequest.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkReply>\n#include <lastfm/NetworkAccessManager>\n#include \"TrackResolveRequest.h\"\n#include \"BoffinPlayableItem.h\"\n\nvoid \nTrackResolveRequest::issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, \n    const QString& artist, const QString& album, const QString& track, const QString& session)\n{\n    QNetworkReply* reply = wam->get(QNetworkRequest(api.trackResolve(artist, album, track, session, qid())));\n    if (reply) {\n        connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));\n        emit requestMade( qid());\n    } else {\n        fail(\"couldn't issue boffin request\");\n    }\n}\n\n//virtual \nvoid \nTrackResolveRequest::receiveResult(const QVariantMap& o)\n{\n    emit result(BoffinPlayableItem::fromTrackResolveResult(o));\n}\n\nvoid \nTrackResolveRequest::onFinished()\n{\n    sender()->deleteLater();\n    QNetworkReply *reply = (QNetworkReply*) sender();\n    if (reply->error() == QNetworkReply::NoError) {\n        QString queryId;\n        if (getQueryId(reply->readAll(), queryId)) {\n            if (queryId == qid()) {\n                // all is good\n                return; \n            }\n            fail(\"qid mismatch\");            // we can't handle this\n        }\n        fail(\"bad response\");\n    }\n    fail(\"\");\n}\n\nvoid \nTrackResolveRequest::fail(const char* message)\n{\n    qDebug() << message;\n\temit error();\n}\n"
  },
  {
    "path": "app/boffin/playdar/TrackResolveRequest.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TRACK_RESOLVE_REQUEST_H\n#define TRACK_RESOLVE_REQUEST_H\n\n#include <lastfm/global.h>\n#include \"PlaydarApi.h\"\n#include \"CometRequest.h\"\n#include \"BoffinPlayableItem.h\"\n\nclass TrackResolveRequest : public CometRequest\n{\n    Q_OBJECT\n\npublic:\n    void issueRequest(lastfm::NetworkAccessManager* wam, PlaydarApi& api, const QString& artist, const QString& album, const QString& track, const QString& session);\n    virtual void receiveResult(const QVariantMap& o);\n\nsignals:\n    void error();\n    void result( BoffinPlayableItem );\n    void requestMade( const QString );\n\nprivate slots:\n    void onFinished();\n\nprivate:\n    void fail(const char* message);\n};\n\n#endif\n"
  },
  {
    "path": "app/boffin/playdar/jsonGetMember.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"jsonGetMember.h\"\n\nbool jsonGetMember(const QVariantMap& o, const char* key, QString& out)\n{\n    QVariantMap::const_iterator it = o.find(key);\n    if (it != o.end() && it->type() == QVariant::String) {\n        out = it->toString();\n        return true;\n    }\n    return false;\n}\n\nbool jsonGetMember(const QVariantMap& o, const char* key, int& out)\n{\n    QVariantMap::const_iterator it = o.find(key);\n    if (it != o.end() && it->type() == QVariant::LongLong) {\n        out = it->toLongLong();\n        return true;\n    }\n    return false;\n}\n\nbool jsonGetMember(const QVariantMap& o, const char* key, double& out)\n{\n    QVariantMap::const_iterator it = o.find(key);\n    if (it != o.end() && it->type() == QVariant::Double) {\n        out = it->toDouble();\n        return true;\n    }\n    return false;\n}\n\nbool jsonGetMember(const QVariantMap& o, const char* key, float& out)\n{\n    QVariantMap::const_iterator it = o.find(key);\n    if (it != o.end() && it->type() == QVariant::Double) {\n        out = (float) it->toDouble();\n        return true;\n    }\n    return false;\n}\n"
  },
  {
    "path": "app/boffin/playdar/jsonGetMember.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef JSON_GET_MEMBER_H\n#define JSON_GET_MEMBER_H\n\n// gets the named property from the json value\n//\n// returns true if it's got ok.\n//\n// todo: support nested objects,    eg: \"playable.result.id\"\n// todo: support arrays,            eg: \"results[1].id\"\n\n\n// for json_spirit:\n// ( T can be any type acceptable to json_spirit's get_value method )\n//\n\n#include <boost/foreach.hpp>\n#include \"../json_spirit/json_spirit.h\"\n\n\ntemplate <typename T>\nbool\njsonGetMember(const json_spirit::Value& value, const char* name, T& out)\n{\n    using namespace json_spirit;\n\n    if (value.type() == obj_type) {\n        // yeah, only objects have values.\n        BOOST_FOREACH(const Pair& pair, value.get_obj()) {\n            if (pair.name_ == name) {\n                out = pair.value_.get_value<T>();\n                return true;\n            }\n        }\n    }\n    return false;\n}\n\n// for QVariantMaps:\n#include <QVariant>\nbool jsonGetMember(const QVariantMap& o, const char* key, QString& out);\nbool jsonGetMember(const QVariantMap& o, const char* key, int& out);\nbool jsonGetMember(const QVariantMap& o, const char* key, double& out);\nbool jsonGetMember(const QVariantMap& o, const char* key, float& out);\n\n\n#endif\n"
  },
  {
    "path": "app/boffin/qrc/boffin.qrc",
    "content": "<RCC>\n  <qresource>\n    <file>pause.png</file>\n\t<file>play.png</file>\n\t<file>skip.png</file>\n\t<file>stop.png</file>\n  </qresource>\n</RCC>\n"
  },
  {
    "path": "app/boffin/sample/SampleFromDistribution.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n// this file courtesy norman and mir\n\n// Sample from EMPIRICAL (given) distribution.\n// There are three types of sampling here:\n// linear: uses a simple linear search that does not guarantee\n//         that the number of requested samples will be found.\n//         Use it for LARGE distributions\n// tree: Simple tree balanced on probability. The best solution for\n//       small/medium distributions\n// justrandom: simply pull random samples\n\n#ifndef __SAMPLE_FROM_DISTRIBUTION_H\n#define __SAMPLE_FROM_DISTRIBUTION_H\n\n#include <algorithm>\n#include <vector>\n#include <ctime>\n#include <limits>\n\n#include <boost/random.hpp>\n\nnamespace fm { namespace last { namespace algo {\n\n// -----------------------------------------------------------------------------\n// -----------------------------------------------------------------------------\n\ntemplate < typename AccessPolicy, typename CopyPolicy >\nclass ListBasedSampler\n{\n   const CopyPolicy   m_copyElement;\n   const AccessPolicy m_accessElement;\n\n   boost::mt19937                            m_randomGenerator;\n   // be very careful with this!! even if the methods are const\n   // they are NOT thread safe due to this variable!\n   mutable boost::uniform_01<boost::mt19937> m_uniform01Distr;\n\npublic:\n\n   ListBasedSampler() :\n      m_copyElement(),\n      m_accessElement(),\n      m_randomGenerator(),\n      m_uniform01Distr(m_randomGenerator)\n      {\n         boost::uint32_t localSeed = time(0);\n            //static_cast<boost::uint32_t>( reinterpret_cast<boost::int64_t>(this) %\n            //(std::numeric_limits<boost::uint32_t>::max)() );\n\n         m_uniform01Distr.base().seed(localSeed);\n      }\n\n   // -----------------------------------------------------------------------------\n\n   // sample just one element from the distribution\n   // isPDF assumes that the passed data is a probability distribution\n   // function, and therefore the sum of all it's elements is = 1\n   template <typename IT>\n   IT\n      singleSample( IT first, IT last,\n                    bool isPDF = false ) const\n   {\n      double sum;\n      if ( isPDF )\n         sum = 1;\n      else\n      {\n         sum = 0;\n         for ( IT it = first; it != last; ++it )\n            sum += m_accessElement(it);\n      }\n\n      double randPos = m_uniform01Distr() * sum;\n      double summedPos = sum;\n\n      IT foundIt;\n      for ( foundIt = first; foundIt != last ; ++foundIt )\n      {\n         summedPos -= m_accessElement(foundIt);\n         if ( randPos > summedPos )\n            break;\n      }\n\n      if ( foundIt == last )\n         return first;\n      else\n         return foundIt;\n   }\n\n};\n\n\n// -----------------------------------------------------------------------------\n// -----------------------------------------------------------------------------\n// -----------------------------------------------------------------------------\n\n}}} // end of namespaces\n\n#endif // __SAMPLE_FROM_DISTRIBUTION_H\n\n"
  },
  {
    "path": "app/client/Application.cpp",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QRegExp>\n#include <QShortcut>\n#include <QFileDialog>\n#include <QDesktopServices>\n#include <QNetworkDiskCache>\n#include <QMenu>\n#include <QMenuBar>\n#include <QDebug>\n#include <QProcess>\n#include <QShortcut>\n#include <QTcpSocket>\n#include <QAction>\n#include <QNetworkProxy>\n\n#include <lastfm/UrlBuilder.h>\n#include <lastfm/InternetConnectionMonitor.h>\n#include <lastfm/XmlQuery.h>\n#include <lastfm/misc.h>\n#include <lastfm/NetworkAccessManager.h>\n\n#include \"lib/listener/State.h\"\n#include \"lib/listener/PlayerConnection.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/dialogs/AboutDialog.h\"\n#include \"lib/unicorn/dialogs/ShareDialog.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/dialogs/TagDialog.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/widgets/UserMenu.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n#include \"lib/unicorn/dialogs/UserManagerDialog.h\"\n#ifdef Q_OS_MAC\n#include \"lib/unicorn/notify/Notify.h\"\n#include \"CommandReciever/CommandReciever.h\"\n#endif\n\n#include \"Dialogs/LicensesDialog.h\"\n#include \"MediaDevices/DeviceScrobbler.h\"\n#include \"Services/ScrobbleService.h\"\n#include \"Services/AnalyticsService.h\"\n#include \"Widgets/PointyArrow.h\"\n#include \"Widgets/ScrobbleControls.h\"\n#include \"Widgets/MetadataWidget.h\"\n#include \"Wizard/FirstRunWizard.h\"\n#include \"Application.h\"\n#include \"MainWindow.h\"\n#include \"AudioscrobblerSettings.h\"\n\n#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)\n#include \"Mpris2/Mpris2.h\"\n#endif\n\n#ifdef Q_OS_WIN32\n#include \"windows.h\"\n#endif\n\nusing audioscrobbler::Application;\n\n#define ELLIPSIS QString::fromUtf8(\"…\")\n#define CONTROL_KEY_CHAR QString::fromUtf8(\"⌃\")\n#define APPLE_KEY_CHAR QString::fromUtf8(\"⌘\")\n#define SKIP_LIMIT 6\n\n#ifdef Q_WS_X11\n#define AS_TRAY_ICON \":/22x22.png\"\n#define AS_TRAY_ICON_OFF \":/lastfm_icon_22_grayscale.png\"\n#elif defined( Q_WS_WIN )\n#define AS_TRAY_ICON \":/16x16.png\"\n#define AS_TRAY_ICON_OFF \":/lastfm_icon_16_grayscale.png\"\n#elif defined( Q_WS_MAC )\n#define AS_TRAY_ICON \":/systray_icon_rest_mac.png\"\n#define AS_TRAY_ICON_OFF \":/mac_control_bar_as_OFF.png\"\n#endif\n\nApplication::Application(int& argc, char** argv) \n    :unicorn::Application( \"fm.last.Scrobbler\", argc, argv )\n    , m_raiseHotKeyId( (void*)-1 )\n    , m_reauthenticating( false )\n{\n    setAttribute( Qt::AA_DontShowIconsInMenus );\n\n    unicorn::AppSettings appSettings;\n    int proxyType = appSettings.value( \"proxyType\", 0 ).toInt();\n    QString proxyHost = appSettings.value( \"proxyHost\", \"\" ).toString();\n    QString proxyPort = appSettings.value( \"proxyPort\", \"\" ).toString();\n    QString proxyUsername = appSettings.value( \"proxyUsername\", \"\" ).toString();\n    QString proxyPassword = appSettings.value( \"proxyPassword\", \"\" ).toString();\n\n    // set this new proxy\n    QNetworkProxy::ProxyType type = QNetworkProxy::DefaultProxy;\n\n    if ( proxyType == 1 )\n        type = QNetworkProxy::NoProxy;\n    else if ( proxyType == 2 )\n        type = QNetworkProxy::HttpProxy;\n    else if ( proxyType == 3 )\n        type = QNetworkProxy::Socks5Proxy;\n\n    QNetworkProxy proxy( type, proxyHost, proxyPort.toInt(), proxyUsername, proxyPassword );\n    lastfm::NetworkAccessManager* nam = qobject_cast<lastfm::NetworkAccessManager*>( lastfm::nam() );\n\n    if ( nam )\n        nam->setUserProxy( proxy );\n\n    AudioscrobblerSettings settings;\n    lastfm::ws::setScheme( settings.value( \"enableSsl\", false ).toBool() ? lastfm::ws::Https : lastfm::ws::Http );\n}\n\nvoid\nApplication::initiateLogin( bool forceWizard ) throw( StubbornUserException )\n{\n    closeAllWindows();\n\n    if( forceWizard || !unicorn::Settings().firstRunWizardCompleted() )\n    {\n        setWizardRunning( true );\n\n        FirstRunWizard w;\n        if( w.exec() != QDialog::Accepted )\n        {\n            setWizardRunning( false );\n            throw StubbornUserException();\n        }\n\n        setWizardRunning( false );\n    }\n\n    //this covers the case where the last user was removed\n    //and the main window was closed.\n    if ( m_mw )\n        m_mw->show();\n\n    if ( m_tray )\n    {\n        //HACK: turns out when all the windows are closed, the tray stops working\n        //unless you call the following methods.\n        m_tray->hide();\n        m_tray->show();\n    }\n}\n\nvoid\nApplication::init()\n{\n    // Initialise the unicorn base class first!\n    unicorn::Application::init();\n\n#ifdef Q_WS_X11\n    setWindowIcon( QIcon( \":/as.png\" ) );\n#endif\n\n    if ( !currentSession().isValid() )\n    {\n        // there won't be a current session if one wasn't created by the wizard\n\n        QMap<QString, QString> lastSession = unicorn::Session::lastSessionData();\n        if ( lastSession.contains( \"username\" ) && lastSession.contains( \"sessionKey\" ) )\n            changeSession( lastSession[ \"username\" ], lastSession[ \"sessionKey\" ] );\n    }\n\n    initiateLogin( !currentSession().isValid() );\n\n    onSessionChanged( currentSession() );\n\n//    QNetworkDiskCache* diskCache = new QNetworkDiskCache(this);\n//    diskCache->setCacheDirectory( lastfm::dir::cache().path() );\n//    lastfm::nam()->setCache( diskCache );\n\n/// tray\n    tray(); // this will initialise m_tray if it doesn't already exist\n\n    /// tray menu\n    QMenu* menu = new QMenu;\n    m_tray->setContextMenu(menu);\n\n    menu->addMenu( new UserMenu() )->setText( tr( \"Accounts\" ) );\n\n    m_show_window_action = menu->addAction( tr(\"Show Scrobbler\"));\n    m_show_window_action->setShortcut( Qt::CTRL + Qt::META + Qt::Key_S );\n    menu->addSeparator();\n\n    {\n        m_love_action = new QAction( tr(\"Love\"), this );\n        m_love_action->setIconVisibleInMenu( false );\n        m_love_action->setCheckable( true );\n#ifdef Q_OS_WIN\n        QIcon loveIcon;\n        loveIcon.addFile( \":/controls_love_OFF_REST.png\", QSize( 16, 16 ), QIcon::Normal, QIcon::Off );\n        loveIcon.addFile( \":/controls_love_ON_REST.png\", QSize( 16, 16 ), QIcon::Normal, QIcon::On );\n        m_love_action->setIcon( loveIcon );\n#endif\n        m_love_action->setEnabled( false );\n        connect( m_love_action, SIGNAL(triggered(bool)), SLOT(changeLovedState(bool)));\n    }\n    {\n        m_play_action = new QAction( tr( \"Play\" ), this );\n        m_play_action->setIconVisibleInMenu( false );\n        m_play_action->setCheckable( true );\n#ifdef Q_OS_WIN\n        QIcon playIcon;\n        playIcon.addFile( \":/controls_pause_REST.png\", QSize(), QIcon::Normal, QIcon::On );\n        playIcon.addFile( \":/controls_play_REST.png\", QSize(), QIcon::Normal, QIcon::Off );\n        m_play_action->setIcon( playIcon );\n#endif\n    }\n    {\n        m_tag_action = new QAction( tr( \"Tag\" ) + ELLIPSIS, this );\n        m_tag_action->setIconVisibleInMenu( false );\n#ifdef Q_OS_WIN\n        m_tag_action->setIcon( QIcon( \":/controls_tag_REST.png\" ) );\n#endif\n        m_tag_action->setEnabled( false );\n        connect( m_tag_action, SIGNAL(triggered()), SLOT(onTagTriggered()));\n    }\n    {\n        m_share_action = new QAction( tr( \"Share\" ) + ELLIPSIS, this );\n        m_share_action->setIconVisibleInMenu( false );\n#ifdef Q_OS_WIN\n        m_share_action->setIcon( QIcon( \":/controls_share_REST.png\" ) );\n#endif\n        m_share_action->setEnabled( false );\n        connect( m_share_action, SIGNAL(triggered()), SLOT(onShareTriggered()));\n    }\n\n\n#ifdef Q_WS_X11\n    menu->addSeparator();\n    m_scrobble_ipod_action = menu->addAction( tr( \"Scrobble iPod...\" ) );\n    connect( m_scrobble_ipod_action, SIGNAL( triggered() ), ScrobbleService::instance().deviceScrobbler(), SLOT( onScrobbleIpodTriggered() ) );\n#endif\n\n    menu->addSeparator();\n\n    m_visit_profile_action = menu->addAction( tr( \"Visit Last.fm profile\" ) );\n    connect( m_visit_profile_action, SIGNAL( triggered() ), SLOT( onVisitProfileTriggered() ) );\n\n    menu->addSeparator();\n\n    m_submit_scrobbles_toggle = menu->addAction( tr(\"Enable Scrobbling\") );\n    m_submit_scrobbles_toggle->setCheckable( true );\n    bool scrobblingOn = unicorn::UserSettings().value( \"scrobblingOn\", true ).toBool();\n    m_submit_scrobbles_toggle->setChecked( scrobblingOn );\n    ScrobbleService::instance().scrobbleSettingsChanged();\n\n    connect( m_submit_scrobbles_toggle, SIGNAL(toggled(bool)), SLOT(onScrobbleToggled(bool)) );\n    connect( this, SIGNAL(scrobbleToggled(bool)), &ScrobbleService::instance(), SLOT(scrobbleSettingsChanged()) );\n\n    menu->addSeparator();\n\n    QAction* quit = menu->addAction(tr(\"Quit %1\").arg( applicationName()));\n    connect(quit, SIGNAL(triggered()), SLOT(quit()));\n\n    m_menuBar = new QMenuBar( 0 );\n\n/// MainWindow\n    m_mw = new MainWindow( m_menuBar );\n    m_mw->addWinThumbBarButton( m_love_action );\n    m_mw->addWinThumbBarButton( m_play_action );\n\n    m_toggle_window_action = new QAction( this ), SLOT( trigger());\n#ifndef Q_WS_X11\n     AudioscrobblerSettings settings;\n     setRaiseHotKey( settings.raiseShortcutModifiers(), settings.raiseShortcutKey() );\n#endif\n    m_tag_action->setShortcut( Qt::CTRL + Qt::Key_T );\n    m_share_action->setShortcut( Qt::CTRL + Qt::Key_S );\n    m_love_action->setShortcut( Qt::CTRL + Qt::Key_L );\n\n    // make the love buttons sychronised\n    connect(this, SIGNAL(lovedStateChanged(bool)), m_love_action, SLOT(setChecked(bool)));\n\n    // tell everyone that is interested that data about the current track has been fetched\n    connect( m_mw, SIGNAL(trackGotInfo(XmlQuery)), SIGNAL(trackGotInfo(XmlQuery)));\n    connect( m_mw, SIGNAL(albumGotInfo(XmlQuery)), SIGNAL(albumGotInfo(XmlQuery)));\n    connect( m_mw, SIGNAL(artistGotInfo(XmlQuery)), SIGNAL(artistGotInfo(XmlQuery)));\n    connect( m_mw, SIGNAL(artistGotEvents(XmlQuery)), SIGNAL(artistGotEvents(XmlQuery)));\n    connect( m_mw, SIGNAL(trackGotTopFans(XmlQuery)), SIGNAL(trackGotTopFans(XmlQuery)));\n    connect( m_mw, SIGNAL(trackGotTags(XmlQuery)), SIGNAL(trackGotTags(XmlQuery)));\n    connect( m_mw, SIGNAL(finished()), SIGNAL(finished()));\n\n    connect( m_mw, SIGNAL(trackGotInfo(XmlQuery)), this, SLOT(onTrackGotInfo(XmlQuery)));\n\n    connect( m_show_window_action, SIGNAL( triggered()), SLOT( showWindow()), Qt::QueuedConnection );\n    connect( m_toggle_window_action, SIGNAL( triggered()), SLOT( toggleWindow()), Qt::QueuedConnection );\n\n    connect( this, SIGNAL(messageReceived(QStringList)), SLOT(onMessageReceived(QStringList)) );\n    connect( this, SIGNAL(sessionChanged(unicorn::Session)), &ScrobbleService::instance(), SLOT(onSessionChanged(unicorn::Session)) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(onTrackStarted(lastfm::Track,lastfm::Track)));\n    connect( &ScrobbleService::instance(), SIGNAL(paused(bool)), SLOT(onTrackPaused(bool)));\n\n    // clicking on a system tray message should show the scrobbler\n    connect( m_tray, SIGNAL(messageClicked()), m_show_window_action, SLOT(trigger()));\n\n    // make sure cached scrobbles get submitted when the connection comes back online\n    connect( m_icm, SIGNAL(up(QString)), &ScrobbleService::instance(), SLOT(submitCache()) );\n\n#ifdef Q_OS_WIN32\n    QStringList args = arguments();\n#else\n    QStringList args = arguments().mid( 1 );\n#endif\n    emit messageReceived( args );\n\n#ifdef Q_OS_MAC\n    m_notify = new Notify( this );\n    connect( m_notify, SIGNAL(clicked()), SLOT(showWindow()) );\n    connect( &ScrobbleService::instance(), SIGNAL(paused()), m_notify, SLOT(paused()) );\n    connect( &ScrobbleService::instance(), SIGNAL(resumed()), m_notify, SLOT(resumed()) );\n    connect( &ScrobbleService::instance(), SIGNAL(stopped()), m_notify, SLOT(stopped()) );\n\n    new CommandReciever( this );\n#endif\n\n#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)\n    new Mpris2( this );\n#endif\n}\n\nQWidget*\nApplication::mainWindow() const\n{\n    return m_mw;\n}\n\nQSystemTrayIcon*\nApplication::tray()\n{\n    if ( !m_tray )\n    {\n        m_tray = new QSystemTrayIcon(this);\n        setTrayIcon();\n\n#if defined(Q_OS_WIN) || defined(Q_WS_X11)\n        connect( m_tray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT( onTrayActivated(QSystemTrayIcon::ActivationReason)) );\n#endif\n        showAs( unicorn::Settings().showAS() );\n        connect( this, SIGNAL( aboutToQuit()), m_tray, SLOT( hide()));\n    }\n\n    return m_tray;\n}\n\nvoid\nApplication::setTrayIcon()\n{\n    if ( m_tray )\n    {\n        bool scrobblingOn = unicorn::UserSettings().value( \"scrobblingOn\", true ).toBool();\n\n        QIcon trayIcon( scrobblingOn ? AS_TRAY_ICON : AS_TRAY_ICON_OFF );\n#ifdef Q_WS_MAC\n        trayIcon.addFile( \":systray_icon_pressed_mac.png\", QSize(), QIcon::Selected );\n#endif\n\n        m_tray->setIcon(trayIcon);\n    }\n}\n\nvoid\nApplication::showAs( bool showAs )\n{\n    m_tray->setVisible( showAs  );\n#ifdef Q_OS_MAC\n    setQuitOnLastWindowClosed( false );\n#else\n    setQuitOnLastWindowClosed( !showAs && !QSystemTrayIcon::isSystemTrayAvailable() );\n#endif\n}\n\nvoid\nApplication::setRaiseHotKey( Qt::KeyboardModifiers mods, int key )\n{\n    if( m_raiseHotKeyId >= (void *)0 )\n        unInstallHotKey( m_raiseHotKeyId );\n\n    m_raiseHotKeyId = installHotKey( mods, key, m_toggle_window_action, SLOT(trigger()));\n}\n\nvoid\nApplication::setBetaUpdates( bool betaUpdates )\n{\n    m_mw->setBetaUpdates( betaUpdates );\n}\n\nvoid\nApplication::startBootstrap( const QString& pluginId )\n{\n    if ( pluginId == \"itw\"\n         || pluginId == \"osx\" )\n        m_bootstrapper = new iTunesBootstrapper( this );\n    else\n        m_bootstrapper = new PluginBootstrapper( pluginId, this );\n\n    connect( m_bootstrapper, SIGNAL(done(AbstractBootstrapper::BootstrapStatus)), SIGNAL(bootstrapDone(AbstractBootstrapper::BootstrapStatus)) );\n    emit bootstrapStarted( pluginId );\n    m_bootstrapper->bootStrap();\n}\n\nQString\nApplication::currentCategory() const\n{\n    return m_mw->currentCategory();\n}\n\nvoid\nApplication::onTrackGotInfo( const XmlQuery& lfm )\n{\n    MutableTrack( ScrobbleService::instance().currentConnection()->track() ).setFromLfm( lfm );\n}\n\n\nvoid\nApplication::onCorrected(QString /*correction*/)\n{\n    onTrackStarted( ScrobbleService::instance().currentTrack(), ScrobbleService::instance().currentTrack());\n}\n\n\nvoid\nApplication::onTrackStarted( const lastfm::Track& track, const Track& oldTrack )\n{\n    disconnect( oldTrack.signalProxy(), 0, this, 0 );\n\n    if ( track != m_currentTrack )\n    {\n        m_currentTrack = track;\n\n        if ( ScrobbleService::instance().scrobblableTrack( m_currentTrack )\n             && unicorn::Settings().notifications() )\n        {\n#ifdef Q_OS_MAC\n            m_notify->newTrack( track );\n#else\n            tray()->showMessage( track.toString(), tr(\"from %1\").arg( track.album() ) );\n#endif\n        }\n    }\n\n    if ( unicorn::UserSettings().value( \"fingerprint\", true ).toBool()\n#if QT_VERSION >= 0x040800\n         && track.url().isLocalFile()\n#endif\n       )\n    {       \n        QFileInfo trackFileInfo( track.url().toLocalFile() );\n\n        if ( trackFileInfo.exists()\n             && trackFileInfo.isWritable() ) // this stops us fingerprinting CDs (but maybe other things)\n        {\n            QProcess* fpProcess = new QProcess( this );\n            connect( fpProcess, SIGNAL(finished(int)), fpProcess, SLOT(deleteLater()) );\n\n            QStringList arguments;\n            arguments << \"--username\" << User().name();\n            arguments << \"--filename\" << track.url().toLocalFile();\n            arguments << \"--title\" << track.title();\n            arguments << \"--album\" << track.album();\n            arguments << \"--artist\" << track.artist();\n\n#ifdef Q_OS_WIN\n            QString fpExe = QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( \"fingerprinter.exe\" );\n#elif defined( Q_OS_MAC )\n            QString fpExe = QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( \"../Helpers/fingerprinter\" );\n#else\n            QString fpExe = QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( \"fingerprinter\" );\n#endif\n            fpProcess->start( fpExe, arguments );\n        }\n    }\n\n    m_tray->setToolTip( track.toString() );\n\n    m_love_action->setEnabled( true );\n    m_tag_action->setEnabled( true );\n    m_share_action->setEnabled( true );\n\n    // make sure that if the love state changes we update all the buttons\n    connect( track.signalProxy(), SIGNAL(loveToggled(bool)), SIGNAL(lovedStateChanged(bool)) );\n    connect( track.signalProxy(), SIGNAL(corrected(QString)), SLOT(onCorrected(QString)));\n}\n\nvoid\nApplication::onSessionChanged( unicorn::Session& session )\n{\n}\n\nvoid\nApplication::onTrackSpooled( const Track& /*track*/ )\n{\n}\n\nvoid\nApplication::onTrackPaused( bool )\n{\n}\n\nvoid \nApplication::onTagTriggered()\n{\n    TagDialog* td = new TagDialog( m_currentTrack, m_mw );\n    td->raise();\n    td->show();\n    td->activateWindow();\n}\n\nvoid \nApplication::onShareTriggered()\n{\n    ShareDialog* sd = new ShareDialog( m_currentTrack, m_mw );\n    sd->raise();\n    sd->show();\n    sd->activateWindow();\n}\n\nvoid\nApplication::onVisitProfileTriggered()\n{\n    unicorn::DesktopServices::openUrl( User().www() );\n}\n\nvoid\nApplication::onFaqTriggered()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"help\" ).slash( \"faq\" ).url() );\n}\n\nvoid\nApplication::onForumsTriggered()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"forum\" ).slash( \"34905\" ).url() );\n}\n\nvoid\nApplication::onTourTriggered()\n{\n    FirstRunWizard w( true, m_mw );\n    w.exec();\n}\n\nvoid\nApplication::onAboutTriggered()\n{\n    if ( !m_aboutDialog )\n        m_aboutDialog = new AboutDialog( m_mw );\n    m_aboutDialog->show();\n}\n\nvoid\nApplication::onLicensesTriggered()\n{\n    if ( !m_licensesDialog )\n        m_licensesDialog = new LicensesDialog( m_mw );\n    m_licensesDialog->show();\n}\n\nvoid \nApplication::changeLovedState(bool loved)\n{\n    MutableTrack track( m_currentTrack );\n\n    if (loved)\n        track.love();\n    else\n        track.unlove();\n}\n\nvoid\nApplication::onScrobbleToggled( bool scrobblingOn )\n{\n    if ( unicorn::UserSettings().value( \"scrobblingOn\", true ) != scrobblingOn )\n    {\n        unicorn::UserSettings().setValue( \"scrobblingOn\", scrobblingOn );\n        AnalyticsService::instance().sendEvent(SETTINGS_CATEGORY, SCROBBLING_SETTINGS, scrobblingOn ? \"ScrobbleTurnedOn\" : \"ScrobbleTurnedOff\" );\n    }\n\n    m_submit_scrobbles_toggle->setChecked( scrobblingOn );\n\n    setTrayIcon();\n\n    emit scrobbleToggled( scrobblingOn );\n}\n\nvoid\nApplication::onBusLovedStateChanged( bool loved )\n{\n    MutableTrack( m_currentTrack ).setLoved( loved );\n}\n\nvoid \nApplication::onTrayActivated( QSystemTrayIcon::ActivationReason reason ) \n{\n    if( reason == QSystemTrayIcon::Context ) return;\n#ifdef Q_WS_WIN\n    if( reason != QSystemTrayIcon::DoubleClick ) return;\n#endif\n    m_show_window_action->trigger();\n}\n\nvoid\nApplication::showWindow()\n{\n    m_mw->showNormal();\n    m_mw->setFocus();\n    m_mw->raise();\n    m_mw->activateWindow();\n}\n\nvoid\nApplication::toggleWindow()\n{\n    if( activeWindow() )\n        m_mw->hide();\n    else\n        showWindow();\n}\n  \n\n// lastfmlib invokes this directly, for some errors:\nvoid\nApplication::onWsError( lastfm::ws::Error e )\n{\n    switch (e)\n    {\n        case lastfm::ws::InvalidSessionKey:\n\n        if ( !m_reauthenticating )\n        {\n            m_reauthenticating = true;\n\n            QString unauthedUser = aApp->currentSession().user().name();\n\n            unicorn::Settings us;\n            us.beginGroup( \"Users\" );\n            us.remove( unauthedUser );\n            us.endGroup();\n\n            us.setFirstRunWizardCompleted( false );\n\n            // Tell them that there was an error\n            QMessageBoxBuilder( m_mw )\n                    .setIcon( QMessageBox::Critical )\n                    .setTitle( tr(\"Authentication Required\") )\n                    .setText( tr( \"<p>The user account <strong>%1</strong> is no longer authenticated with Last.fm.</p>\"\n                                  \"<p>Click OK to start the setup process and reauthenticate this account.</p>\" ).arg( unauthedUser ) )\n                    .setButtons( QMessageBox::Ok )\n                    .exec();\n\n\n            qobject_cast<unicorn::Application*>( qApp )->restart();\n\n\n            m_reauthenticating = false;\n        }\n\n            break;\n        default:\n            break;\n    }\n}\n\n  \nApplication::Argument Application::argument( const QString& arg )\n{\n    if (arg == \"--exit\") return Exit;\n    if (arg == \"--twiddly\") return Twiddly;\n    if (arg == \"--settings\") return Settings;\n\n    return ArgUnknown;\n}\n\nvoid\nApplication::onPrefsTriggered()\n{\n    m_mw->onPrefsTriggered();\n}\n\nvoid\nApplication::onDiagnosticsTriggered()\n{\n    m_mw->onDiagnosticsTriggered();\n}\n    \nvoid\nApplication::onMessageReceived( const QStringList& message )\n{\n    parseArguments( message );\n\n    qDebug() << \"Messages: \" << message;\n\n    if ( !( message.contains( \"--tray\" )\n           || message.contains( \"--twiddly\" )\n           || message.contains( \"--new-ipod-detected\" )\n           || message.contains( \"--ipod-detected\" )\n           || message.contains( \"--settings\" ) ) )\n    {\n        // raise the app\n        m_show_window_action->trigger();\n#ifdef Q_OS_WIN32\n        SetForegroundWindow(m_mw->winId());\n#endif\n    }\n\n}\n\n\nvoid\nApplication::parseArguments( const QStringList& args )\n{\n    qDebug() << args;\n\n    foreach ( QString const arg, args )\n    {\n        switch ( argument( arg ) )\n        {\n        case Exit:\n            exit();\n            break;\n\n        case Twiddly:\n            ScrobbleService::instance().handleTwiddlyMessage( args );\n            break;\n\n        case Settings:\n            m_mw->onPrefsTriggered();\n            break;\n\n        case ArgUnknown:\n            break;\n        }\n    }\n}\n\nvoid \nApplication::quit()\n{\n    if( activeWindow() )\n        activeWindow()->raise();\n\n    if( unicorn::AppSettings().value( \"quitDontAsk\", false ).toBool()) {\n        actuallyQuit();\n        return;\n    }\n\n    bool dontAsk = false;\n    int result = 1;\n    if( !unicorn::AppSettings().value( \"quitDontAsk\", false ).toBool())\n      result =\n          QMessageBoxBuilder( activeWindow()).setTitle( tr(\"Are you sure you want to quit %1?\").arg(applicationName()))\n                                             .setText( tr(\"%1 is about to quit. Tracks played will not be scrobbled if you continue.\" ).arg(applicationName()) )\n                                             .dontAskAgain()\n                                             .setIcon( QMessageBox::Question )\n                                             .setButtons( QMessageBox::Yes | QMessageBox::No )\n                                             .exec(&dontAsk);\n    if( result == QMessageBox::Yes )\n    {\n        unicorn::AppSettings().setValue( \"quitDontAsk\", dontAsk );\n        QCoreApplication::quit();\n    }\n\n}\n\nvoid \nApplication::actuallyQuit()\n{\n    QDialog* d = qobject_cast<QDialog*>( sender());\n    if( d ) {\n        QCheckBox* dontAskCB = d->findChild<QCheckBox*>();\n        if( dontAskCB ) {\n            unicorn::AppSettings().setValue( \"quitDontAsk\", ( dontAskCB->checkState() == Qt::Checked ));\n        }\n    }\n    QCoreApplication::quit();\n}\n\n"
  },
  {
    "path": "app/client/Application.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef AUDIOSCROBBLER_APPLICATION_H_\n#define AUDIOSCROBBLER_APPLICATION_H_\n\n#include <QPointer>\n#include <QQueue>\n#include <QSystemTrayIcon>\n\n#include <lastfm/global.h>\n#include <lastfm/Track.h>\n#include <lastfm/ws.h>\n\n#include \"lib/unicorn/UnicornApplication.h\"\n\n#include \"Bootstrapper/iTunesBootstrapper.h\"\n#include \"Bootstrapper/PluginBootstrapper.h\"\n\nclass AboutDialog;\nclass LicensesDialog;\nclass MainWindow;\nclass QAction;\nclass ScrobbleInfoFetcher;\nclass Drawer;\nclass QMenuBar;\nclass UserManagerDialog;\n\nnamespace unicorn { class Notify; }\nusing unicorn::Notify;\n\n#ifdef Q_WS_X11\n    class IpodDeviceLinux;\n#endif\n\n#if defined(aApp)\n#undef aApp\n#endif\n#define aApp (static_cast<audioscrobbler::Application*>(QCoreApplication::instance()))\n\nnamespace audioscrobbler\n{\n    \n    /**\n      * @brief Main application logic for the audioscrobbler app.\n      *\n      * This class contains the core components of the application\n      * (ie Audioscrobbler, PlayerConnection etc), top-level gui widgets and the system tray.\n      */\n    class Application : public unicorn::Application\n    {\n        Q_OBJECT\n\n        enum Argument\n        {\n            Exit,\n            Twiddly,\n            Settings,\n            ArgUnknown\n        };\n\n        // we delete these so QPointers\n        QPointer<QSystemTrayIcon> m_tray;\n        QPointer<MainWindow> m_mw;\n        QPointer<QMenuBar> m_menuBar;\n        QPointer<Notify> m_notify;\n        QPointer<UserManagerDialog> m_userManager;\n\n        QPointer<AbstractBootstrapper> m_bootstrapper;\n\n        Track m_currentTrack;\n        Track m_trackToScrobble;\n\n        void* m_raiseHotKeyId;\n\n        QPointer<AboutDialog> m_aboutDialog;\n        QPointer<LicensesDialog> m_licensesDialog;\n        \n        QAction* m_submit_scrobbles_toggle;\n        QAction* m_love_action;\n        QAction* m_tag_action;\n        QAction* m_share_action;\n        QAction* m_play_action;\n        QAction* m_show_window_action;\n        QAction* m_toggle_window_action;\n        QAction* m_scrobble_ipod_action;\n        QAction* m_visit_profile_action;\n        QAction* m_mute_action;\n\n        bool m_reauthenticating;\n        \n    public:\n        Application(int& argc, char** argv);\n\n        void init();\n        \n        QAction* loveAction() const { return m_love_action; }\n        QAction* tagAction() const { return m_tag_action; }\n        QAction* shareAction() const { return m_share_action; }\n        QAction* playAction() const { return m_play_action; }\n        QAction* muteAction() const { return m_mute_action; }\n        QAction* scrobbleToggleAction() const { return m_submit_scrobbles_toggle; }\n        QSystemTrayIcon* tray();\n\n        QWidget* mainWindow() const;\n\n        void setBetaUpdates( bool betaUpdates );\n\n        void setRaiseHotKey( Qt::KeyboardModifiers mods, int key );\n\n        void startBootstrap( const QString& pluginId );\n\n        void showAs( bool showAs );\n\n        QString currentCategory() const;\n        \n    signals:\n        void lovedStateChanged(bool loved);\n\n        // re-route all the info fetchers singals\n        void trackGotInfo(const XmlQuery& lfm);\n        void albumGotInfo(const XmlQuery& lfm);\n        void artistGotInfo(const XmlQuery& lfm);\n        void artistGotEvents(const XmlQuery& lfm);\n        void trackGotTopFans(const XmlQuery& lfm);\n        void trackGotTags(const XmlQuery& lfm);\n\n        void finished();\n\n\t\t\n        void error( const QString& message );\n        void status( const QString& message, const QString& id );\n        void showMessage( const QString& message, const QString& id );\n\n        void bootstrapStarted( const QString& pluginId );\n        void bootstrapDone( AbstractBootstrapper::BootstrapStatus status );\n\n        void scrobbleToggled( bool on );\n\n    public slots:\n        void showWindow();\n        void quit();\n        void actuallyQuit();\n\n        void changeLovedState(bool loved);\n        void onBusLovedStateChanged(bool);\n\n        void onTrackGotInfo(const XmlQuery& );\n        void parseArguments( const QStringList& args );\n\n        void onPrefsTriggered();\n        void onDiagnosticsTriggered();\n\n        void onScrobbleToggled( bool scrobblingOn );\n\n    protected:\n        virtual void initiateLogin( bool forceWizard ) throw( StubbornUserException );\n\n    private:\n        static Argument argument( const QString& arg );\n\n    private slots:\n        void onTrayActivated(QSystemTrayIcon::ActivationReason);\n        void onCorrected(QString correction);\n\n        void onTagTriggered();\n        void onShareTriggered();\n\n        void onVisitProfileTriggered();\n        void onFaqTriggered();\n        void onForumsTriggered();\n        void onAboutTriggered();\n        void onTourTriggered();\n        void onLicensesTriggered();\n\n        void toggleWindow();\n\n        void onTrackStarted( const lastfm::Track&, const lastfm::Track& );\n        void onTrackPaused( bool );\n\n        void onTrackSpooled( const Track& );\n\n        void onSessionChanged( unicorn::Session& );\n\n        void onMessageReceived(const QStringList& message);\n\n        void setTrayIcon();\n\t\t\n        /** all webservices connect to this and emit in the case of bad errors that\n\t     * need to be handled at a higher level */\n        void onWsError( lastfm::ws::Error );\n    };\n}\n\n#endif //AUDIOSCROBBER_APPLICATION_H_\n"
  },
  {
    "path": "app/client/AudioscrobblerSettings.cpp",
    "content": "/*\n   Copyright 2005-2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"AudioscrobblerSettings.h\"\n\nAudioscrobblerSettings::AudioscrobblerSettings()\n{\n}\n\nQt::KeyboardModifiers\nAudioscrobblerSettings::raiseShortcutModifiers() const\n{\n    return (Qt::KeyboardModifiers)value( \"raiseShortcutModifiers\", (int)(Qt::ControlModifier | Qt::MetaModifier) ).toInt();\n}\n\nint\nAudioscrobblerSettings::raiseShortcutKey() const\n{\n#ifdef Q_WS_MAC\n    const int sKeyCode = 1;\n    return value( \"raiseShortcutKey\", sKeyCode ).toInt();\n#elif defined Q_WS_WIN\n    const int sKeyCode = 83;\n    return value( \"raiseShortcutKey\", sKeyCode ).toInt();\n#endif\n\n}\n\nQString\nAudioscrobblerSettings::raiseShortcutDescription() const\n{\n    return value( \"raiseShortcutDescription\", QString::fromUtf8(\n#ifdef Q_OS_MAC\n    \"⌃⌘ S\"\n#else\n    \"Ctrl+Shift+S\"\n#endif\n     ) ).toString();\n}\n\nvoid\nAudioscrobblerSettings::setRaiseShortcutKey( int key )\n{\n    setValue( \"raiseShortcutKey\", key );\n}\n\nvoid\nAudioscrobblerSettings::setRaiseShortcutModifiers( Qt::KeyboardModifiers m )\n{\n    setValue( \"raiseShortcutModifiers\", (int)m );\n}\n\nvoid\nAudioscrobblerSettings::setRaiseShortcutDescription( QString d )\n{\n    setValue( \"raiseShortcutDescription\", d );\n}\n"
  },
  {
    "path": "app/client/AudioscrobblerSettings.h",
    "content": "/*\n   Copyright 2005-2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef AUDIOSCROBBLER_SETTINGS_H\n#define AUDIOSCROBBLER_SETTINGS_H\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\nclass AudioscrobblerSettings : public unicorn::AppSettings\n{\npublic:\n    AudioscrobblerSettings();\n\n    Qt::KeyboardModifiers raiseShortcutModifiers() const;\n    int raiseShortcutKey() const;\n    QString raiseShortcutDescription() const;\n\n    void setRaiseShortcutKey( int key );\n    void setRaiseShortcutModifiers( Qt::KeyboardModifiers m );\n    void setRaiseShortcutDescription( QString d );\n};\n\n#endif // AUDIOSCROBBLER_SETTINGS_H\n"
  },
  {
    "path": "app/client/Bootstrapper/AbstractBootstrapper.cpp",
    "content": "/***************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#include \"AbstractBootstrapper.h\"\n\n#include <lastfm/ws.h>\n#include <lastfm/misc.h>\n\n#include <QDebug>\n#include <QNetworkRequest>\n#include <QUrl>\n#include <QFile>\n#include <QDir>\n#include <QTextStream>\n\n#include \"zlib.h\"\n\nAbstractBootstrapper::AbstractBootstrapper( QObject* parent )\n                     :QObject( parent )\n{\n}\n\n\nAbstractBootstrapper::~AbstractBootstrapper(void)\n{\n}\n\n\nbool\nAbstractBootstrapper::zipFiles( const QString& inFileName, const QString& outFileName ) const\n{\n    QDir temp = QDir::temp();\n\n    temp.remove( outFileName );\n\n    gzFile outFile = gzopen( outFileName.toLocal8Bit(), \"wb\" );\n    if ( !outFile )\n        return false;\n\n    QFile inFile( inFileName );\n    if ( !inFile.open( QIODevice::ReadOnly | QIODevice::Text ) )\n        return false;\n\n    if ( gzputs( outFile, inFile.readAll().data() ) < 1 )\n        return false;\n\n    gzclose( outFile );\n    inFile.close();\n\n    return true;\n}\n\n\nvoid\nAbstractBootstrapper::sendZip( const QString& inFile )\n{\n    QString username = lastfm::ws::Username;\n    QString timestamp = QString::number( QDateTime::currentDateTime().toUTC().toTime_t() );\n\n    QMap<QString, QString> params;\n    params[\"user\"] = username;\n    params[\"time\"] = timestamp;\n    params[\"auth\"] = lastfm::md5( QString( QString( lastfm::ws::SharedSecret ) + timestamp ).toUtf8() );\n    params[\"api_key\"] = lastfm::ws::ApiKey;\n    params[\"sk\"] = lastfm::ws::SessionKey;\n\n    //lastfm::ws::sign( params, true );\n    //params[\"auth\"] = params.take( \"api_sig\" );\n\n    QUrl url( \"http://bootstrap.last.fm/bootstrap/index.php\" );\n\n    QMapIterator<QString, QString> i( params );\n    while ( i.hasNext() )\n    {\n        i.next();\n        QByteArray const key = QUrl::toPercentEncoding( i.key() );\n        QByteArray const value = QUrl::toPercentEncoding( i.value() );\n        url.addEncodedQueryItem( key, value );\n    }\n\n    QFile* zipFile = new QFile( this );\n    zipFile->setFileName( inFile );\n    zipFile->open( QIODevice::ReadOnly );\n\n    QNetworkRequest request( url );\n    request.setRawHeader( \"Content-type\", \"multipart/form-data, boundary=AaB03x\" );\n    request.setRawHeader( \"Cache-Control\", \"no-cache\" );\n    request.setRawHeader( \"Accept\", \"*/*\" );\n\n    QByteArray bytes;\n    bytes.append( \"--AaB03x\\r\\n\" );\n    bytes.append( \"content-disposition: \" );\n    bytes.append( \"form-data; name=\\\"agency\\\"\\r\\n\" );\n    bytes.append( \"\\r\\n\" );\n    bytes.append( \"0\\r\\n\" );\n    bytes.append( \"--AaB03x\\r\\n\" );\n    bytes.append( \"content-disposition: \" );\n    bytes.append( \"form-data; name=\\\"bootstrap\\\"; filename=\\\"\" + zipFile->fileName() + \"\\\"\\r\\n\" );\n    bytes.append( \"Content-Transfer-Encoding: binary\\r\\n\" );\n    bytes.append( \"\\r\\n\" );\n\n    bytes.append( zipFile->readAll() );\n    zipFile->close();\n\n    bytes.append( \"\\r\\n\" );\n    bytes.append( \"--AaB03x--\" );\n    request.setHeader( QNetworkRequest::ContentLengthHeader, bytes.length() );\n\n    qDebug() << \"Sending \" << url;\n\n    emit percentageUploaded( 0 );\n\n    QNetworkReply* reply = lastfm::nam()->post( request, bytes );\n    connect( reply, SIGNAL(uploadProgress(qint64,qint64)), SLOT( onUploadProgress(qint64,qint64)));\n    connect( reply, SIGNAL(finished()), SLOT(onUploadDone()));\n}\n\n\nvoid\nAbstractBootstrapper::onUploadProgress( qint64 done, qint64 total )\n{\n    emit percentageUploaded( int( float(done / total) * 100.0 ) );\n}\n\n\nvoid\nAbstractBootstrapper::onUploadDone()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>( sender() );\n\n    qDebug() << reply->readAll();\n\n    if( reply->error() == QNetworkReply::ContentAccessDenied ||\n        reply->error() == QNetworkReply::ContentOperationNotPermittedError )\n    {\n        emit done( Bootstrap_Denied );\n        return;\n    }\n\n    if( reply->error() != QNetworkReply::NoError )\n    {\n        qDebug() << reply->errorString();\n        emit done( Bootstrap_UploadError );\n        return;\n    }\n\n    qDebug() << \"Bootstrap.zip sent to last.fm!\";\n    emit done( Bootstrap_Ok );\n}\n"
  },
  {
    "path": "app/client/Bootstrapper/AbstractBootstrapper.h",
    "content": "/**************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#ifndef ABSTRACTBOOTSTRAPPER_H\n#define ABSTRACTBOOTSTRAPPER_H\n#include <QObject>\n\nclass QString;\n\n/**\n  * @author Jono Cole <jono@last.fm>\n  *\n  * @brief The AbstractBootstrapper class is the abstract base class of\n  *        bootstrapper implementations, providing common functionality.\n  *\n  * Subclasses of this class can implement the bootStrap method to perform\n  * the bootstrapping operation and then call the zipFile / sendZip methods\n  * to submit the bootstrap.\n  */\nclass AbstractBootstrapper : public QObject\n{\n    Q_OBJECT\n\npublic:\n\n    enum BootstrapStatus\n    {\n        Bootstrap_Ok = 0,\n        Bootstrap_UploadError,\n        Bootstrap_Denied,\n        Bootstrap_Spam, /* eg. 1 billion plays for Bjork */\n        Bootstrap_Cancelled\n    };\n\n    AbstractBootstrapper( QObject* parent = NULL );\n    virtual ~AbstractBootstrapper(void);\n\n    bool zipFiles( const QString& inFileName, const QString& outFileName ) const;\n    void sendZip( const QString& inFile );\n    virtual void bootStrap() = 0;\n\nsignals:\n    void percentageUploaded( int );\n    void done( AbstractBootstrapper::BootstrapStatus status );\n\nprotected slots:\n    void onUploadDone();\n    void onUploadProgress( qint64 done, qint64 total );\n};\n\n#endif //ABSTRACTBOOTSTRAPPER_H\n\n"
  },
  {
    "path": "app/client/Bootstrapper/AbstractFileBootstrapper.cpp",
    "content": "/**************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#include \"AbstractFileBootstrapper.h\"\n#include <lastfm/misc.h>\n#include <QFile>\n#include <QTextStream>\n\nstatic const int k_maxPlaysPerTrack = 10000;\nstatic const int k_maxTotalPlays = 300000;\n\nstatic const QString XML_VERSION = \"1.0\";\n\n\nAbstractFileBootstrapper::AbstractFileBootstrapper( QString product, QObject* parent )\n                         : AbstractBootstrapper( parent ),\n                           m_runningPlayCount( 0 )\n{\n    m_bootstrapElement = m_xmlDoc.createElement( \"bootstrap\" );\n    m_xmlDoc.appendChild( m_bootstrapElement );\n    m_bootstrapElement.setAttribute( \"product\", product );\n    m_bootstrapElement.setAttribute( \"version\", XML_VERSION );\n\n    m_savePath = lastfm::dir::runtimeData().path() + \"/\" +  product + \"_bootstrap.xml\";\n}\n\n\nAbstractFileBootstrapper::~AbstractFileBootstrapper(void)\n{\n}\n\n\nstatic QDomElement\ntrackToDom( const Track& t, QDomDocument& d )\n{\n    QDomElement item = d.createElement( \"item\" );\n    QDomElement artist = d.createElement( \"artist\" );\n    QDomElement album = d.createElement( \"album\" );\n    QDomElement track = d.createElement( \"track\" );\n    QDomElement duration = d.createElement( \"duration\" );\n    QDomElement timestamp = d.createElement( \"timestamp\" );\n    QDomElement playcount = d.createElement( \"playcount\" );\n    QDomElement filename = d.createElement( \"filename\" );\n    QDomElement uniqueid = d.createElement( \"uniqueID\" );\n\n    artist.appendChild( d.createTextNode( t.artist()));\n    album.appendChild( d.createTextNode( t.album()));\n    track.appendChild( d.createTextNode( t.title()));\n    duration.appendChild( d.createTextNode( QString::number( t.duration())));\n    timestamp.appendChild( d.createTextNode( QString::number( t.timestamp().toTime_t())));\n    playcount.appendChild( d.createTextNode( t.extra( \"playcount\" )));\n    filename.appendChild( d.createTextNode( t.url().toString()));\n    uniqueid.appendChild( d.createTextNode( t.extra( \"unique_id\" )));\n    \n    item.appendChild( artist );\n    item.appendChild( album );\n    item.appendChild( track );\n    item.appendChild( duration );\n    item.appendChild( timestamp );\n    item.appendChild( playcount );\n    item.appendChild( filename );\n    item.appendChild( uniqueid );\n    return item;\n}\n\n\nbool\nAbstractFileBootstrapper::appendTrack(Track& track)\n{\n    int playCount = track.extra( \"playcount\" ).toInt();\n    m_runningPlayCount += playCount;\n    if ( playCount > k_maxPlaysPerTrack ||\n        m_runningPlayCount > k_maxTotalPlays )\n    {\n//        LOGL( 2, \"Playcount for bootstrap exceeded maximum allowed. Track: \" <<\n//            track.playCount() << \", total: \" << m_runningPlayCount );\n\n        emit done( Bootstrap_Spam );\n        return false;\n    }\n    const QDomElement& i = trackToDom( track,  m_xmlDoc );\n    m_bootstrapElement.appendChild( i );\n    return true;\n}\n\n\nvoid\nAbstractFileBootstrapper::zipAndSend()\n{\n    QFile file( m_savePath );\n    file.open( QIODevice::WriteOnly | QIODevice::Text );\n    QTextStream stream( &file );\n\n    stream.setCodec( \"UTF-8\" );\n    stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\n\";\n    stream << m_xmlDoc.toString();\n\n    file.close();\n\n    QString zipPath = m_savePath + \".gz\";\n    zipFiles( m_savePath, zipPath );\n\n    sendZip( zipPath );\n}\n\n"
  },
  {
    "path": "app/client/Bootstrapper/AbstractFileBootstrapper.h",
    "content": "/**************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#ifndef ABSTRACTFILEBOOTSTRAPPER_H\n#define ABSTRACTFILEBOOTSTRAPPER_H\n\n#include \"AbstractBootstrapper.h\"\n#include <lastfm/Track.h>\n\n/**\n  * @author Jono Cole <jono@last.fm>\n  * @brief AbstractFileBootstrapper is an Abstract class which provides\n  *        common functionality for bootstrappers which read library /\n  *        playcount information from the filesystem.\n  *\n  * Bootstrapping classes using this base class should call the appendTrack\n  * method for each track that it has processed from the file before calling\n  * the zipAndSend method to submit the bootstrap.\n  */\nclass AbstractFileBootstrapper : public AbstractBootstrapper\n{\n    Q_OBJECT\n\n    public:\n\n    AbstractFileBootstrapper( QString product, QObject* parent = NULL );\n    virtual ~AbstractFileBootstrapper( void );\n\nprotected:\n    bool appendTrack( Track& track );\n    void zipAndSend();\n\nsignals:\n    void trackProcessed( int percentDone, const Track track );\n\nprivate:\n    QDomDocument m_xmlDoc;\n    QDomElement  m_bootstrapElement;\n    QString m_savePath;\n\n    int m_runningPlayCount;\n};\n\n#endif //ABSTRACTFILEBOOTSTRAPPER_H\n\n"
  },
  {
    "path": "app/client/Bootstrapper/ITunesDevice/ITunesParser.h",
    "content": "/***************************************************************************\n *   Copyright 2005 - 2008 Last.fm Ltd.                                    *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n#ifndef ITUNES_PARSER_H\n#define ITUNES_PARSER_H\n\n#include <QXmlContentHandler>\n#include <QXmlSimpleReader>\n\n/**\n  * @brief XML Event handler for parsing the iTunes Library xml\n  * file. \n  *\n  * @todo this should probably be renamed to something more appropriate. \n  */\nclass ITunesParser : public QXmlContentHandler\n{\n    public:\n        ITunesParser()\n        {\n            m_nextIsKey = false;\n        }\n\n        Track peekTrack()\n        {\n            if ( m_tracks.size() )\n                return m_tracks.at( 0 );\n            else\n                return Track();\n        }\n\n        Track takeTrack()\n        {\n            if ( m_tracks.size() )\n                return m_tracks.takeAt( 0 );\n            else\n                return Track();\n        }\n\n        int trackCount()\n        {\n            return m_tracks.size();\n        }\n\n        bool startElement( const QString & /*namespaceURI*/, const QString & localName, const QString & /*qName*/, const QXmlAttributes & /*atts*/ )\n        {\n//             qDebug() << \"stEl\" << localName;\n\n            if ( localName == \"key\" )\n                m_nextIsKey = true;\n            else\n                m_nextIsKey = false;\n\n\n            return true;\n        }\n\n        bool characters ( const QString & ch )\n        {\n//             qDebug() << \"strings\" << ch;\n\n            if ( ch.trimmed().isEmpty() )\n                return true;\n\n            if ( m_nextIsKey )\n            {\n//                 qDebug() << \"New Key:\" << ch.trimmed();\n\n                m_lastKey = ch.trimmed();\n                m_nextIsKey = false;\n            }\n            else\n            {\n//                 qDebug() << \"New Value:\" << ch.trimmed();\n\n                if ( m_lastKey == \"Name\" )\n                    MutableTrack( m_track ).setTitle( ch.trimmed() );\n\n                if ( m_lastKey == \"Artist\" )\n                    MutableTrack( m_track ).setArtist( ch.trimmed() );\n\n                if ( m_lastKey == \"Album\" )\n                    MutableTrack( m_track ).setAlbum( ch.trimmed() );\n\n                if ( m_lastKey == \"Total Time\" )\n                    MutableTrack( m_track ).setDuration( ch.trimmed().toInt() / 1000 );\n\n                if ( m_lastKey == \"Play Count\" )\n                    MutableTrack( m_track ).setExtra( \"playcount\", ch.trimmed() );\n\n                if ( m_lastKey == \"Location\" )\n                    MutableTrack( m_track ).setUrl( QUrl( ch.trimmed() ) );\n\n                if ( m_lastKey == \"Persistent ID\" )\n                    MutableTrack( m_track ).setExtra( \"unique_id\", ch.trimmed() );\n\n                if ( m_lastKey == \"Play Date UTC\" )\n                {\n                    QDateTime dt = QDateTime::fromString( ch.trimmed(), Qt::ISODate );\n                    MutableTrack( m_track ).setTimeStamp( dt );\n                }\n            }\n\n            return true;\n        }\n\n        bool endElement ( const QString & /*namespaceURI*/, const QString & localName, const QString & /*qName*/ )\n        {\n//             qDebug() << \"enEl\" << localName;\n\n            if ( localName == \"dict\" )\n            {\n                if ( !m_track.isNull() && m_track.extra( \"playcount\" ).toInt() > 0 )\n                {\n                    MutableTrack( m_track ).setSource( Track::MediaDevice );\n                    m_tracks << m_track;\n                }\n\n                m_track = Track();\n            }\n\n            return true;\n        }\n\n        bool endDocument () { return true; }\n        bool endPrefixMapping ( const QString & /*prefix*/ ) { return true; }\n        QString errorString () const { return QString(); }\n        bool ignorableWhitespace ( const QString & /*ch*/ ) { return true; }\n        bool processingInstruction ( const QString & /*target*/, const QString & /*data*/ ) { return true; }\n        void setDocumentLocator ( QXmlLocator * /*locator*/ ) {}\n        bool skippedEntity ( const QString & /*name*/ ) { return true; }\n        bool startDocument () { return true; }\n        bool startPrefixMapping ( const QString & /*prefix*/, const QString & /*uri*/ ) { return true; }\n\n    private:\n        QString m_lastKey;\n        bool m_nextIsKey;\n\n        Track m_track;\n        QList<Track> m_tracks;\n};\n\n#endif //ITUNES_PARSER_H\n"
  },
  {
    "path": "app/client/Bootstrapper/ITunesDevice/MediaDeviceInterface.h",
    "content": "/***************************************************************************\n *   Copyright (C) 2005 - 2007 by                                          *\n *      Christian Muehlhaeuser, Last.fm Ltd <chris@last.fm>                *\n *      Erik Jaelevik, Last.fm Ltd <erik@last.fm>                          *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n\n#ifndef MEDIADEVICE_INTERFACE_H\n#define MEDIADEVICE_INTERFACE_H\n\n#include <lastfm/Track.h>\n#include <QDateTime>\n\n/**\n  * @brief The MediaDeviceInterface is a base class for classes\n  * representing a mediaplayer (currently only iTunes/iPod). This\n  * code has not been properly migrated into client 2.0 yet.\n  *\n  */\nclass MediaDeviceInterface : public QObject\n{\n    public:\n        virtual ~MediaDeviceInterface() {}\n\n        virtual QString LibraryPath() = 0;\n\n        virtual Track firstTrack( const QString& file ) = 0;\n        virtual Track nextTrack() = 0;\n\n        virtual void forceDetection( const QString& path ) = 0;\n        virtual void setupWatchers() = 0;\n\n    signals:\n        void deviceAdded( const QString& uid );\n        void deviceChangeStart( const QString& uid, QDateTime lastItunesUpdateTime );\n        void deviceChangeEnd( const QString& uid );\n        void progress( int percentage, const Track& track );\n\n        void trackChanged( const Track& track, int playCounter );\n};\n\nQ_DECLARE_INTERFACE( MediaDeviceInterface, \"fm.last.MediaDevice/1.0\" )\n\n#endif\n"
  },
  {
    "path": "app/client/Bootstrapper/ITunesDevice/itunesdevice.cpp",
    "content": "/***************************************************************************\n *   Copyright 2005 - 2008 Last.fm Ltd.                                    *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n\n#include <QCoreApplication>\n#include <QDebug>\n#include <QDir>\n#include <QSettings>\n#include \"itunesdevice.h\"\n#include \"ITunesParser.h\"\n\n#ifdef WIN32\n    #include \"windows.h\"\n    #include \"shlobj.h\"\n#endif\n\n\nQString\nITunesDevice::LibraryPath()\n{\n    if ( !m_iTunesLibraryPath.isEmpty() )\n        return m_iTunesLibraryPath;\n\n    QString path;\n    QString confPath;\n\n#ifdef Q_WS_MAC\n    QSettings ist( \"apple.com\", \"iTunes\" );\n    path = ist.value( \"AppleNavServices:ChooseObject:0:Path\" ).toString();\n    path = path.remove( \"file://localhost\" );\n    qDebug() << \"Found iTunes Library in:\" << path;\n\n    QFileInfo fi( path + \"iTunes Music Library.xml\" );\n    if ( fi.exists() )\n        m_iTunesLibraryPath = fi.absoluteFilePath();\n    else\n        m_iTunesLibraryPath = QFileInfo( QDir::homePath() + \"/Music/iTunes/iTunes Music Library.xml\" ).absoluteFilePath();\n\n    return m_iTunesLibraryPath;\n#endif\n\n#ifdef WIN32\n    {\n        // Get path to My Music\n        char acPath[MAX_PATH];\n        HRESULT h = SHGetFolderPathA( NULL, CSIDL_MYMUSIC,\n                                      NULL, 0, acPath );\n\n        if ( h == S_OK )\n            path = QString::fromLocal8Bit( acPath );\n//        else\n//            LOG( 1, \"Couldn't get My Music path\\n\" );\n\n        qDebug() << \"CSIDL_MYMUSIC path: \" << path;\n    }\n\n    {\n        // Get path to Local App Data\n        char acPath[MAX_PATH];\n        HRESULT h = SHGetFolderPathA( NULL, CSIDL_LOCAL_APPDATA,\n                                      NULL, 0, acPath );\n\n        if ( h == S_OK )\n            confPath = QString::fromLocal8Bit( acPath );\n//        else\n//            LOG( 1, \"Couldn't get Local Application Data path\\n\" );\n\n        qDebug() << \"CSIDL_LOCAL_APPDATA path: \" << confPath;\n    }\n\n    // Try reading iTunesPrefs.xml for custom library path\n    QFile f( confPath + \"/Apple Computer/iTunes/iTunesPrefs.xml\" );\n    if ( f.open( QIODevice::ReadOnly | QIODevice::Text ) )\n    {\n        qDebug() << \"Found iTunesPrefs.xml\";\n\n        QByteArray content = f.readAll();\n\n        int tagStart = content.indexOf( \"iTunes Library XML Location:1\" );\n\n        if ( tagStart != -1 )\n        {\n            // TODO: this could fail if the XML is broken\n            int dataTagStart = content.indexOf( \"<data>\", tagStart );\n            int dataTagEnd = dataTagStart + 6;\n            int dataEndTagStart = content.indexOf( \"</data>\", dataTagStart );\n            QByteArray lp = content.mid( dataTagEnd, dataEndTagStart - dataTagEnd );\n\n            qDebug() << \"lp before trim: \" << lp;\n\n            // The file contains whitespace and linebreaks in the middle of\n            // the data so need to squeeze all that out\n            lp = lp.simplified();\n            lp = lp.replace( ' ', \"\" );\n\n            qDebug() << \"lp after simplified: \" << lp;\n\n            lp = QByteArray::fromBase64( lp );\n\n            qDebug() << \"lp after base64: \" << lp;\n\n            QString sp = QString::fromUtf16( (ushort*)lp.data() );\n\n            qDebug() << \"Found iTunes Library path (after conversion to QString):\" << sp;\n\n            QFileInfo fi( sp );\n            if ( fi.exists() )\n            {\n                qDebug() << \"file exists, returning: \" << fi.absoluteFilePath();\n                m_iTunesLibraryPath = fi.absoluteFilePath();\n                return m_iTunesLibraryPath;\n            }\n        }\n        else\n        {\n            qDebug() << \"No custom library location found in iTunesPrefs.xml\";\n        }\n    }\n\n    // Fall back to default path otherwise\n    m_iTunesLibraryPath = path + \"/iTunes/iTunes Music Library.xml\";\n\n    qDebug() << \"Will use default iTunes Library path: \" << m_iTunesLibraryPath;\n\n    return m_iTunesLibraryPath;\n\n#endif\n\n    // Fallback for testing\n//    m_iTunesLibraryPath = \"/tmp/iTunes Music Library.xml\";\n//    return m_iTunesLibraryPath;\n}\n\nITunesDevice::ITunesDevice() :\n      m_totalSize( 0 ),\n      m_file( 0 ),\n      m_handler( 0 ),\n      m_xmlReader( 0 ),\n      m_xmlInput( 0 )\n{\n\n}\n\n\nTrack\nITunesDevice::firstTrack( const QString& file )\n{\n    m_database = file;\n\n    if ( !m_file )\n    {\n        m_file = new QFile( file );\n        if ( !m_file->open( QIODevice::ReadOnly | QIODevice::Text ) )\n        {\n            qDebug() << \"Could not open iTunes Library\" << m_database;\n            return Track();\n        }\n\n        m_totalSize = m_file->size();\n        m_xmlReader = new QXmlSimpleReader();\n        m_xmlInput = new QXmlInputSource();\n\n        m_handler = new ITunesParser();\n        m_xmlReader->setContentHandler( m_handler );\n\n        m_xmlInput->setData( m_file->read( 32768 ) );\n        if ( !m_xmlReader->parse( m_xmlInput, true ) )\n        {\n            qDebug() << \"Couldn't read file: \" << m_database;\n            return Track();\n        }\n    }\n\n    return nextTrack();\n}\n\n\nTrack\nITunesDevice::nextTrack()\n{\n    while ( m_handler->trackCount() < 20 && !m_file->atEnd() )\n    {\n        m_xmlInput->setData( m_file->read( 32768 ) );\n        m_xmlReader->parseContinue();\n\n        emit progress( (float)( (float)m_file->pos() / (float)m_file->size() ) * 100.0, m_handler->peekTrack() );\n    }\n\n    Track t = m_handler->takeTrack();\n    if ( !t.isNull() )\n    {\n        return t;\n    }\n\n    if ( m_file->atEnd() )\n    {\n        // Finished with the database, let's close our stuff\n        qDebug() << \"Finished reading\";\n\n        m_file->close();\n        delete m_file;\n        m_file = 0;\n    }\n\n    return Track();\n}\n"
  },
  {
    "path": "app/client/Bootstrapper/ITunesDevice/itunesdevice.h",
    "content": "/***************************************************************************\n *   Copyright 2005 - 2008 Last.fm Ltd.                                    *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n\n/** @author Christian Muehlhaeuser <chris@last.fm>\n  * @contributor Erik Jaelevik <erik@last.fm>\n  * @contributor Max Howell <max@last.fm>\n  */\n#ifndef ITUNES_DEVICE_H\n#define ITUNES_DEVICE_H\n\n#include \"MediaDeviceInterface.h\"\n#include <lastfm/Track.h>\n\n/** \n  * @brief The ITunesDevice class parses the iTunes Music Library.xml file\n  * and allows iterating over the Track information.\n  *\n  * @todo Rename this to something more descriptive.\n  */\nclass ITunesDevice : public QObject\n{\n    Q_OBJECT\n\npublic:\n    ITunesDevice();\n\n    QString LibraryPath();\n\n    Track firstTrack( const QString& file );\n    Track nextTrack();\n\nsignals:\n    void progress( int percentage, const Track& track );\n\nprivate:\n    QString m_iTunesLibraryPath;\n    QString m_database;\n    int m_totalSize;\n\n    class QFile* m_file;\n    class ITunesParser* m_handler;\n    class QXmlSimpleReader* m_xmlReader;\n    class QXmlInputSource* m_xmlInput;\n};\n\n#endif //ITUNES_DEVICE_H\n"
  },
  {
    "path": "app/client/Bootstrapper/PluginBootstrapper.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QSettings>\n#include <QFile>\n#include <QProcess>\n#include <QTimer>\n#include <QFileDialog>\n\n#include <lastfm/misc.h>\n#include <lastfm/ws.h>\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"PluginBootstrapper.h\"\n\n\nPluginBootstrapper::PluginBootstrapper( QString pluginId, QObject* parent )\n                   :AbstractBootstrapper( parent ),\n                    m_pluginId( pluginId )\n{\n    connect( this, SIGNAL( done( int ) ), SLOT( onUploadCompleted( int ) ) );\n}\n\n\nvoid\nPluginBootstrapper::bootStrap()\n{\n    QSettings bootstrap( QSettings::NativeFormat, QSettings::UserScope, \"Last.fm\", \"Bootstrap\", this );\n\n    bootstrap.setValue( m_pluginId, lastfm::ws::Username );\n    bootstrap.setValue( \"data_path\", lastfm::dir::runtimeData().path() );\n\n    bootstrap.setValue( \"Strings/progress_label\",       tr(\"Last.fm is importing your current media library...\") );\n    bootstrap.setValue( \"Strings/complete_label\",       tr(\"Last.fm has imported your media library.\\n\\n Click OK to continue.\") );\n    bootstrap.setValue( \"Strings/progress_title\",       tr(\"Last.fm Library Import\") );\n    bootstrap.setValue( \"Strings/cancel_confirmation\",  tr(\"Are you sure you want to cancel the import?\") );\n    bootstrap.setValue( \"Strings/no_tracks_found\",      tr(\"Last.fm couldn't find any played tracks in your media library.\\n\\n Click OK to continue.\") );\n\n    // start the media player\n    QProcess* process = new QProcess( this );\n    QString mediaPlayer = \"\";\n\n    if ( m_pluginId == \"wa2\" )\n    {\n        mediaPlayer = QString( qgetenv( \"ProgramFiles(x86)\" ) ).append( \"/Winamp/winamp.exe\" );\n        if ( !QFile::exists( mediaPlayer ) )\n            mediaPlayer = QString( qgetenv( \"ProgramFiles\" ) ).append( \"/Winamp/winamp.exe\" );\n    }\n    else\n    {\n        mediaPlayer = QString( qgetenv( \"ProgramFiles(x86)\" ) ).append( \"/Windows Media Player/wmplayer.exe\" );\n        if ( !QFile::exists( mediaPlayer ) )\n            mediaPlayer = QString( qgetenv( \"ProgramFiles\" ) ).append( \"/Windows Media Player/wmplayer.exe\" );\n    }\n\n    qDebug() << mediaPlayer;\n\n    if ( !QFile::exists( mediaPlayer ) )\n    {\n        mediaPlayer = QFileDialog::getOpenFileName( 0,\n                                               m_pluginId == \"wa2\" ? tr( \"Where is Winamp?\" ) : tr( \"Where is Windows Media Player?\" ),\n                                               QString( getenv( \"ProgramFiles(x86)\" ) ),\n                                               m_pluginId == \"wa2\" ? \"winamp.exe\" : \"wmplayer.exe\" );\n\n\n    }\n\n    qDebug() << mediaPlayer;\n\n    mediaPlayer = QString( \"\\\"%1\\\"\" ).arg( mediaPlayer );\n\n    if ( !process->startDetached( mediaPlayer ) )\n    {\n        qDebug() << process->error() << process->errorString();\n\n        // We were unable to start the bootstrap so don't tell the media\n        // player to do the bootstrap on it's next launch anymore\n        bootstrap.setValue( m_pluginId, \"\" );\n        emit done( Bootstrap_Cancelled );\n    }\n    else\n    {\n        // wait for it to do its stuff\n        QTimer::singleShot( 1000, this, SLOT(checkBootstrapped()) );\n    }\n}\n\n\nvoid\nPluginBootstrapper::checkBootstrapped()\n{\n    // check if the file exists\n\n    QString savePath = lastfm::dir::runtimeData().filePath( lastfm::ws::Username + \"_\" + m_pluginId + \"_bootstrap.xml\" );\n\n    if ( QFile::exists( savePath ) )\n    {\n        // make sure winamp doesn't create the bootstrap file again\n        QSettings bootstrap( QSettings::NativeFormat, QSettings::UserScope, \"Last.fm\", \"Bootstrap\", this );\n        bootstrap.remove( m_pluginId );\n\n        submitBootstrap();\n    }\n    else\n        QTimer::singleShot( 1000, this, SLOT(checkBootstrapped()) );\n}\n\n\nvoid\nPluginBootstrapper::submitBootstrap()\n{\n    QString savePath = lastfm::dir::runtimeData().filePath( lastfm::ws::Username + \"_\" + m_pluginId + \"_bootstrap.xml\" );\n    QString zipPath = savePath + \".gz\";\n\n    zipFiles( savePath, zipPath );\n    sendZip( zipPath );\n}\n\n\nvoid\nPluginBootstrapper::onUploadCompleted( int status )\n{\n    QString savePath = lastfm::dir::runtimeData().filePath( lastfm::ws::Username + \"_\" + m_pluginId + \"_bootstrap.xml\" );\n    QString zipPath = savePath + \".gz\";\n\n    if( status == Bootstrap_Ok  )\n    {\n        QMessageBoxBuilder( 0 )\n                .setIcon( QMessageBox::Information )\n                .setTitle( tr(\"Media Library Import Complete\") )\n                .setText( tr( \"Last.fm has submitted your listening history to the server.\\n\"\n                              \"Your profile will be updated with the new tracks in a few minutes.\") );\n    }\n    else if( status == Bootstrap_Denied )\n    {\n        QMessageBoxBuilder( 0 )\n            .setIcon( QMessageBox::Warning )\n            .setTitle( tr(\"Library Import Failed\") )\n            .setText( tr( \"Sorry, Last.fm was unable to import your listening history. \"\n                          \"This is probably because you've already scrobbled too many tracks. \"\n                          \"Listening history can only be imported to brand new profiles.\") );\n\n        QFile::remove( savePath );\n        QFile::remove( zipPath );\n    }\n}\n"
  },
  {
    "path": "app/client/Bootstrapper/PluginBootstrapper.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLUGIN_BOOTSTRAPPER_H_\n#define PLUGIN_BOOTSTRAPPER_H_\n\n#include \"AbstractBootstrapper.h\"\n\nclass PluginBootstrapper :  public AbstractBootstrapper\n{\n    Q_OBJECT\n\npublic:\n    PluginBootstrapper( QString pluginId, QObject* parent = NULL );\n\n    void bootStrap();\n    void submitBootstrap();\n\nprivate:\n    QString m_pluginId;\n\nprivate slots:\n    void onUploadCompleted( int status );\n    void checkBootstrapped();\n\n};\n\n#endif //PLUGIN_BOOTSTRAPPER_H_\n"
  },
  {
    "path": "app/client/Bootstrapper/iTunesBootstrapper.cpp",
    "content": "/***************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#include \"iTunesBootstrapper.h\"\n\n#include \"ITunesDevice/itunesdevice.h\"\n\n#include <QApplication>\n#include <QDebug>\n\n\niTunesBootstrapper::iTunesBootstrapper( QObject* parent )\n                   : AbstractFileBootstrapper( \"iTunes\", parent )\n{\n    m_iTunesDatabase = new ITunesDevice;\n\n    connect( m_iTunesDatabase, SIGNAL(progress(int,Track)), SIGNAL(trackProcessed(int,Track)));\n}\n\n\nvoid\niTunesBootstrapper::bootStrap()\n{\n    Track track;\n    if ( m_iTunesDatabase )\n    {\n        qDebug() << \"Reading iTunes database...\";\n        track = m_iTunesDatabase->firstTrack( m_iTunesDatabase->LibraryPath() );\n    }\n\n    while ( !track.isNull() )\n    {\n        qApp->processEvents();\n\n        if ( !appendTrack( track ) )\n        {\n            return;\n        }\n\n       track =  m_iTunesDatabase->nextTrack();\n    }\n\n    zipAndSend();\n}\n\n"
  },
  {
    "path": "app/client/Bootstrapper/iTunesBootstrapper.h",
    "content": "/***************************************************************************\n*   Copyright (C) 2005 - 2007 by                                          *\n*      Jono Cole, Last.fm Ltd <jono@last.fm>                              *\n*                                                                         *\n*   This program is free software; you can redistribute it and/or modify  *\n*   it under the terms of the GNU General Public License as published by  *\n*   the Free Software Foundation; either version 2 of the License, or     *\n*   (at your option) any later version.                                   *\n*                                                                         *\n*   This program is distributed in the hope that it will be useful,       *\n*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n*   GNU General Public License for more details.                          *\n*                                                                         *\n*   You should have received a copy of the GNU General Public License     *\n*   along with this program; if not, write to the                         *\n*   Free Software Foundation, Inc.,                                       *\n*   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n***************************************************************************/\n\n#ifndef ITUNES_BOOTSTRAPPER_H\n#define ITUNES_BOOTSTRAPPER_H\n\n#include \"AbstractFileBootstrapper.h\"\n\n/** \n  * @author Jono Cole <jono@last.fm>\n  * @brief Bootstrap using information from the iTunes Music Library.xml\n  * file.\n  */\nclass iTunesBootstrapper : public AbstractFileBootstrapper\n{\n    Q_OBJECT\n\npublic:\n    iTunesBootstrapper( QObject* parent = NULL );\n    void bootStrap();\n\nsignals:\n    void trackProcessed( int, Track );\n\nprivate:\n    class ITunesDevice* m_iTunesDatabase;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/CommandReciever/CommandReciever.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef COMMANDRECIEVER_H\n#define COMMANDRECIEVER_H\n\n#include <QObject>\n#include <QPointer>\n#include <QPixmap>\n\n#include <lib/unicorn/TrackImageFetcher.h>\n#include <lib/unicorn/UnicornApplicationDelegate.h>\n\nclass CommandReciever : public QObject, public unicorn::UnicornApplicationDelegateCommandObserver\n{\n    Q_OBJECT\npublic:\n    explicit CommandReciever(QObject *parent = 0);\n    ~CommandReciever();\n\n    bool artworkDownloaded() const;\n    QPixmap getArtwork() const;\n    Track track() const;\n\nprivate:\n    QString trackTitle() const;\n    QString artist() const;\n    QString album() const;\n    int duration();\n    QPixmap artwork();\n    bool loved();\n\nprivate slots:\n    void onFinished( const class QPixmap& image );\n\n    void onTrackSpooled( const Track& track );\n    void onStopped();\n\nprivate:\n    QPointer<TrackImageFetcher> m_trackImageFetcher;\n    QPixmap m_pixmap;\n    bool m_artworkDownloaded;\n};\n\n#endif // COMMANDRECIEVER_H\n"
  },
  {
    "path": "app/client/CommandReciever/CommandReciever.mm",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QAction>\n#include <QBuffer>\n\n#include <lastfm/Track.h>\n\n#include \"../Application.h\"\n\n#include \"CommandReciever.h\"\n\n#import <Cocoa/Cocoa.h>\n\n@interface LastfmPlayPauseCommand: NSScriptCommand { } @end\n@interface LastfmNextCommand: NSScriptCommand { } @end\n@interface LastfmPrevCommand: NSScriptCommand { } @end\n@interface LastfmLoveCommand: NSScriptCommand { } @end\n\n@implementation LastfmPlayPauseCommand\n\n- (id)performDefaultImplementation\n{\n    aApp->playAction()->trigger();\n    return nil;\n}\n\n@end\n\n@implementation LastfmNextCommand\n\n- (id)performDefaultImplementation\n{\n    return nil;\n}\n\n@end\n\n@implementation LastfmPrevCommand\n\n- (id)performDefaultImplementation\n{\n    // do nothing for the back button\n    return nil;\n}\n\n@end\n\n@implementation LastfmLoveCommand\n\n- (id)performDefaultImplementation\n{\n    aApp->loveAction()->trigger();\n    return nil;\n}\n\n@end\n\n@implementation LastfmBanCommand\n\n- (id)performDefaultImplementation\n{\n    return nil;\n}\n\n@end\n\n@implementation NSData (LastfmAdditions)\n\n+ (id)scriptingLastfmImageWithDescriptor:(NSAppleEventDescriptor *)descriptor\n{\n    if ( [descriptor descriptorType] == typeType && [descriptor typeCodeValue] == 'msng' )\n    {\n        return nil;\n    }\n\n    if ( [descriptor descriptorType] != typeTIFF )\n    {\n        descriptor = [descriptor coerceToDescriptorType: typeTIFF];\n        if (descriptor == nil)\n        {\n            return nil;\n        }\n    }\n\n    return [descriptor data];\n}\n\n- (id)scriptingLastfmImageDescriptor\n{\n    return [NSAppleEventDescriptor descriptorWithDescriptorType: typeTIFF data: self];\n}\n\n@end\n\nCommandReciever::CommandReciever( QObject *parent )\n    :QObject( parent ), m_artworkDownloaded( false )\n{\n    bool success = QDir::home().mkdir( \"Library/Application Support/Airfoil/\" );\n    success = QDir::home().mkdir( \"Library/Application Support/Airfoil/RemoteControl/\" );\n    success = QDir::home().mkdir( \"Library/Application Support/Airfoil/TrackTitles/\" );\n\n    // make sure the scripts are copied\n    success = QFile::copy( QApplication::applicationDirPath() + \"/../Resources/dacp.fm.last.Scrobbler.scpt\",\n                                    QDir::home().filePath( \"Library/Application Support/Airfoil/RemoteControl/dacp.fm.last.Scrobbler.scpt\" ) );\n\n    success = QFile::copy( QApplication::applicationDirPath() + \"/../Resources/fm.last.Scrobbler.scpt\",\n                                    QDir::home().filePath( \"Library/Application Support/Airfoil/TrackTitles/fm.last.Scrobbler.scpt\" ) );\n\n    aApp->delegate()->setCommandObserver( this );\n}\n\nbool\nCommandReciever::artworkDownloaded() const\n{\n    return m_artworkDownloaded;\n}\n\nTrack\nCommandReciever::track() const\n{\n    if ( m_trackImageFetcher )\n        return m_trackImageFetcher->track();\n\n    return Track();\n}\n\nvoid\nCommandReciever::onTrackSpooled( const Track& track )\n{\n    // if the track has changed or stopped playing get rid of the track fetcher\n    if ( m_trackImageFetcher )\n    {\n        if ( m_trackImageFetcher->track() != track || track.isNull() )\n        {\n            delete m_trackImageFetcher;\n            m_pixmap = QPixmap();\n        }\n    }\n\n    // if we haven't fetched the new track image yet then do it now\n    if ( !m_trackImageFetcher && !track.isNull() )\n    {\n        m_artworkDownloaded = false;\n        m_trackImageFetcher = new TrackImageFetcher( track, Track::MegaImage );\n        connect( m_trackImageFetcher, SIGNAL(finished(QPixmap)), SLOT(onFinished(QPixmap)));\n        m_trackImageFetcher->startAlbum();\n    }\n}\n\nvoid\nCommandReciever::onStopped()\n{\n    delete m_trackImageFetcher;\n}\n\nvoid\nCommandReciever::onFinished( const QPixmap& pixmap )\n{  \n    m_artworkDownloaded = true;\n    m_pixmap = pixmap;\n}\n\nQPixmap\nCommandReciever::getArtwork() const\n{\n    return m_pixmap;\n}\n\nQString\nCommandReciever::trackTitle() const\n{\n    Track t = track();\n    QString string;\n\n    if ( !t.isNull() && artworkDownloaded() )\n        string = t.title();\n\n    return string;\n}\n\nQString\nCommandReciever::artist() const\n{\n    Track t = track();\n    QString string;\n\n    if ( !t.isNull() && artworkDownloaded() )\n        string = t.artist();\n\n    return string;\n}\n\nQString\nCommandReciever::album() const\n{\n    Track t = track();\n    QString string;\n\n    if ( !t.isNull() && artworkDownloaded() )\n        string = t.album();\n\n    return string;\n}\n\nint\nCommandReciever::duration()\n{\n    Track t = track();\n\n    if ( !t.isNull() && artworkDownloaded() )\n        return t.duration();\n\n    return 0;\n}\n\nQPixmap\nCommandReciever::artwork()\n{\n    Track t = track();\n\n    if ( !t.isNull() )\n    {\n        QPixmap pixmap = getArtwork();\n\n        if ( !pixmap.isNull() && artworkDownloaded() )\n            return pixmap;\n    }\n\n    return QPixmap();\n}\n\nbool\nCommandReciever::loved()\n{\n    Track t = track();\n\n    if ( !t.isNull() && artworkDownloaded() )\n        return t.isLoved();\n\n    return false;\n}\n\nCommandReciever::~CommandReciever()\n{\n}\n"
  },
  {
    "path": "app/client/Dialogs/BetaDialog.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <lastfm/User.h>\n\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"../Application.h\"\n\n#include \"BetaDialog.h\"\n#include \"ui_BetaDialog.h\"\n\nBetaDialog::BetaDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::BetaDialog)\n{\n    ui->setupUi(this);\n\n    setAttribute( Qt::WA_DeleteOnClose );\n\n    ui->description->setText( \"This is a beta version of the new Last.fm Desktop App. Please be gentle!\" );\n\n    if ( aApp->currentSession().user().type() == lastfm::User::TypeStaff )\n    {\n        ui->feedback->setText( \"If you've' noticed a problem, create a Jira issue and we'll fix it immediately. Thanks!\" );\n\n    }\n    else\n    {\n        ui->createIssue->setText( tr( \"Visit Audioscrobbler Beta group\" ) );\n        ui->feedback->setText( \"If you've noticed a problem, please visit our group and leave us some feedback. Thanks!\" );\n    }\n\n    connect( ui->createIssue, SIGNAL(clicked()), SLOT(createIssue()) );\n}\n\nvoid\nBetaDialog::createIssue()\n{\n    if ( aApp->currentSession().user().type() == lastfm::User::TypeStaff )\n        unicorn::DesktopServices::openUrl( QUrl( \"https://jira.last.fm/secure/CreateIssue.jspa?pid=10011&issuetype=1&Create=Create\" ) );\n    else\n        unicorn::DesktopServices::openUrl( QUrl( \"http://www.last.fm/group/Audioscrobbler+Beta\" ) );\n}\n\nBetaDialog::~BetaDialog()\n{\n    delete ui;\n}\n\n"
  },
  {
    "path": "app/client/Dialogs/BetaDialog.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BETADIALOG_H\n#define BETADIALOG_H\n\n#include <QDialog>\n\nnamespace Ui {\nclass BetaDialog;\n}\n\nclass BetaDialog : public QDialog\n{\n    Q_OBJECT\n    \npublic:\n    explicit BetaDialog(QWidget *parent = 0);\n    ~BetaDialog();\n    \nprivate slots:\n    void createIssue();\n\nprivate:\n    Ui::BetaDialog *ui;\n};\n\n#endif // BETADIALOG_H\n"
  },
  {
    "path": "app/client/Dialogs/BetaDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>BetaDialog</class>\n <widget class=\"QDialog\" name=\"BetaDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>352</width>\n    <height>290</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Beta</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"QLabel\" name=\"description\">\n     <property name=\"text\">\n      <string notr=\"true\">TextLabel</string>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"feedback\">\n     <property name=\"text\">\n      <string notr=\"true\">TextLabel</string>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QPushButton\" name=\"createIssue\">\n     <property name=\"text\">\n      <string>Create Issue</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <spacer name=\"verticalSpacer\">\n     <property name=\"orientation\">\n      <enum>Qt::Vertical</enum>\n     </property>\n     <property name=\"sizeHint\" stdset=\"0\">\n      <size>\n       <width>20</width>\n       <height>0</height>\n      </size>\n     </property>\n    </spacer>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Dialogs/DiagnosticsDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"lib/unicorn/UnicornCoreApplication.h\"\n\n#include \"ui_DiagnosticsDialog.h\"\n#include \"DiagnosticsDialog.h\"\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n#include \"../MediaDevices/DeviceScrobbler.h\"\n\n#include \"common/c++/Logger.h\"\n\n#include <lastfm/Audioscrobbler.h>\n#include <lastfm/misc.h>\n#include <lastfm/ScrobbleCache.h>\n#include <lastfm/ws.h>\n\n#include <QByteArray>\n#include <QDebug>\n#include <QHeaderView>\n#include <QProcess>\n\nDiagnosticsDialog::DiagnosticsDialog( QWidget *parent )\n        : QDialog( parent ),\n          ui( new Ui::DiagnosticsDialog ),\n          m_ipod_log( 0 )\n{    \n    ui->setupUi( this );\n\n    setAttribute( Qt::WA_DeleteOnClose );\n\n    ui->cached->header()->setResizeMode( QHeaderView::Stretch );\n    ui->fingerprints->header()->setResizeMode( QHeaderView::Stretch );\n    \n    m_delay = new DelayedLabelText( ui->subs_status );\n\n    ui->tabs->removeTab( 0 );\n    ui->tabs->removeTab( 0 );\n\n#ifdef Q_WS_X11\n    ui->tabs->removeTab( 0 );\n#endif\n\n#ifdef Q_OS_MAC\n    ui->subs_status->setAttribute( Qt::WA_MacSmallSize );\n    ui->subs_cache_count->setAttribute( Qt::WA_MacSmallSize );\n    ui->fingerprints_title->setAttribute( Qt::WA_MacSmallSize );\n    ui->cached->setAttribute( Qt::WA_MacSmallSize );\n    ui->cached->setAttribute( Qt::WA_MacShowFocusRect, false );\n    ui->fingerprints->setAttribute( Qt::WA_MacSmallSize );\n    ui->fingerprints->setAttribute( Qt::WA_MacShowFocusRect, false );\n    \n    QFont f = ui->ipod_log->font();\n    f.setPixelSize( 10 );\n    ui->ipod_log->setFont( f );\n#endif\n    \n    connect( qApp, SIGNAL(scrobblePointReached( Track )), SLOT(onScrobblePointReached()), Qt::QueuedConnection ); // queued because otherwise cache isn't filled yet\n    connect( ui->ipod_scrobble_button, SIGNAL(clicked()), SLOT(onScrobbleIPodClicked()) );\n    connect( ui->logs_button, SIGNAL(clicked()), SLOT(onSendLogsClicked()) );\n\n    onScrobblePointReached();\n\n#ifndef Q_WS_X11\n    QString path = unicorn::CoreApplication::log( \"iPodScrobbler\" ).absoluteFilePath();\n\n    // we seek to the end below, but then twiddly's logger pretruncates the file\n    // which then means our seeked position is beyond the file's end, and we\n    // thus don't show any log output\n#ifdef WIN32\n    Logger::truncate( (wchar_t*) path.utf16() );\n#else\n    QByteArray const cpath = QFile::encodeName( path );\n    Logger::truncate( cpath.data() );\n#endif\n\n    m_ipod_log = new QFile( path, this );\n    m_ipod_log->open( QIODevice::ReadOnly );\n    m_ipod_log->seek( m_ipod_log->size() );\n    ui->ipod_log->clear();\n\n    QTimer* timer = new QTimer( this );\n    timer->setInterval( 10 );\n    connect( timer, SIGNAL(timeout()), SLOT(poll()) );\n    timer->start();\n#endif\n}\n\nDiagnosticsDialog::~DiagnosticsDialog()\n{\n    delete ui;\n}\n    /*\nstatic QString scrobblerStatusText( int const i )\n{\n    using lastfm::Audioscrobbler;\n\n    #define tr QObject::tr\n    switch (i)\n    {\n        case Audioscrobbler::ErrorBadSession: return tr( \"Your session expired, it is being renewed.\" );\n        case Audioscrobbler::ErrorBannedClientVersion: return tr( \"Your client too old, you must upgrade.\" );\n        case Audioscrobbler::ErrorInvalidSessionKey: return tr( \"Your username or password is incorrect\" );\n        case Audioscrobbler::ErrorBadTime: return tr( \"Your timezone or date are incorrect\" );\n        case Audioscrobbler::ErrorThreeHardFailures: return tr( \"The submissions server is down\" );\n\n        case Audioscrobbler::Connecting: return tr( \"Connecting to Last.fm...\" );\n        case Audioscrobbler::Scrobbling: return tr( \"Scrobbling...\" );\n\n        case Audioscrobbler::TracksScrobbled:\n        case Audioscrobbler::Handshaken:\n            return tr( \"Ready\" );\n    }\n    #undef tr\n\n    return \"\";\n}\n*/\n\nvoid\nDiagnosticsDialog::scrobbleActivity( int /*msg*/ )\n{\n    /*\n    m_delay->add( scrobblerStatusText( msg ) );\n\n    if (msg == Audioscrobbler::TracksScrobbled)\n        QTimer::singleShot( 1000, this, SLOT(onScrobblePointReached()) );\n\n    switch (msg)\n    {\n        case Audioscrobbler::ErrorBadSession:\n            //TODO flashing\n        case Audioscrobbler::Connecting:\n            //NOTE we only get this on startup\n            ui->subs_light->setColor( Qt::yellow );\n            break;\n        case Audioscrobbler::Handshaken:\n        case Audioscrobbler::Scrobbling:\n        case Audioscrobbler::TracksScrobbled:\n            ui->subs_light->setColor( Qt::green );\n            break;\n        \n        case Audioscrobbler::ErrorBannedClientVersion:\n        case Audioscrobbler::ErrorInvalidSessionKey:\n        case Audioscrobbler::ErrorBadTime:\n        case Audioscrobbler::ErrorThreeHardFailures:\n            ui->subs_light->setColor( Qt::red );\n            break;\n    }\n    */\n}\n\n\nvoid\nDiagnosticsDialog::onScrobblePointReached()\n{    \n    ScrobbleCache cache( lastfm::ws::Username );\n\n    QList<QTreeWidgetItem *> items;\n    foreach (Track t, cache.tracks())\n        items.append( new QTreeWidgetItem( QStringList() << t.artist() << t.title() << t.album() ) );\n    ui->cached->clear();\n    ui->cached->insertTopLevelItems( 0, items );\n\n    if (items.count())\n        ui->subs_cache_count->setText( tr(\"%n locally cached track(s)\", \"\", items.count() ) );\n    else\n        ui->subs_cache_count->clear();\n}\n\nvoid\nDiagnosticsDialog::fingerprinted( const Track& t )\n{\n    new QTreeWidgetItem( ui->fingerprints,\n                         QStringList() << t.artist() << t.title() << t.album() );\n}\n\n\nvoid \nDiagnosticsDialog::poll()\n{    \n    QTextStream s( m_ipod_log );\n    while (!s.atEnd())\n        ui->ipod_log->appendPlainText( s.readLine() );\n}\n\nvoid\nDiagnosticsDialog::onScrobbleIPodClicked()\n{\n    bool const isManual = ( ui->ipod_type->currentIndex() == 1 );\n    DeviceScrobbler::DoTwiddlyResult doTwiddlyResult = ScrobbleService::instance().deviceScrobbler()->doTwiddle( isManual );\n\n    switch ( doTwiddlyResult )\n    {\n    case DeviceScrobbler::AlreadyRunning:\n        ui->ipod_log->appendPlainText( \"ALREADY SCROBBLING IPOD...\" );\n        break;\n    case DeviceScrobbler::ITunesNotRunning:\n        ui->ipod_log->appendPlainText( \"ITUNES NOT RUNNING!\" );\n        break;\n    case DeviceScrobbler::ITunesPluginNotInstalled:\n        ui->ipod_log->appendPlainText( \"ITUNES PLUGIN NOT INSTALLED!\" );\n        break;\n    default:\n        // don't say anything; it was DoTwiddlyResult::Started\n        break;\n    }\n}\n\n\nvoid \nDiagnosticsDialog::onSendLogsClicked()\n{\n//TODO    SendLogsDialog( this ).exec();\n}\n"
  },
  {
    "path": "app/client/Dialogs/DiagnosticsDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef DIAGNOSTICS_DIALOG_H\n#define DIAGNOSTICS_DIALOG_H\n\n#include <lastfm/Track.h>\n\n#include <QDialog>\n#include <QLabel>\n#include <QDateTime>\n#include <QPointer>\n#include <QProcess> //Qt enums\n#include <QFile>\n\nnamespace Ui { class DiagnosticsDialog; }\n\nclass DiagnosticsDialog : public QDialog\n{\n    Q_OBJECT\npublic:\n    DiagnosticsDialog( QWidget *parent = 0 );\n    ~DiagnosticsDialog();\n    \npublic slots:\n    void fingerprinted( const Track& );\n    void scrobbleActivity( int );\n\nprivate slots:\n    void onScrobblePointReached();\n    \nprivate:\n\tvoid scrobbleIPod( bool isManual = false );\n\tQString diagnosticInformation();\n\nprivate slots:\n\tvoid onScrobbleIPodClicked();\n\tvoid onSendLogsClicked();\n\tvoid poll();\n\nprivate:\n    Ui::DiagnosticsDialog* ui;\n    class DelayedLabelText* m_delay;\n    QFile* m_ipod_log;\n};\n\n\n#include <QTimer>\nclass DelayedLabelText : public QObject\n{\n    Q_OBJECT\n    \n    QList<QString> texts;\n    QTimer m_timer;\n    \npublic:\n    DelayedLabelText( QLabel* parent ) : QObject( parent )\n    {\n        m_timer.setInterval( 2000 );\n        connect( &m_timer, SIGNAL(timeout()), SLOT(timeout()) );\n    }\n    \n    void add( QString text )\n    {       \n        QLabel* label = static_cast<QLabel*>(parent());\n\n        if (m_timer.isActive()) {\n            if (texts.isEmpty() || texts.last() != text)\n                texts += text;\n            return;\n        }\n        \n        label->setText( text );\n        m_timer.start();\n    }\n    \nprivate slots:\n    void timeout()\n    {\n        if (texts.size())\n            static_cast<QLabel*>(parent())->setText( texts.takeFirst() );\n        if (texts.isEmpty())\n            m_timer.stop();\n    }\n};\n\n\n#endif //DIAGNOSTICS_DIALOG_H\n"
  },
  {
    "path": "app/client/Dialogs/DiagnosticsDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>DiagnosticsDialog</class>\n <widget class=\"QDialog\" name=\"DiagnosticsDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>502</width>\n    <height>485</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Diagnostics</string>\n  </property>\n  <layout class=\"QVBoxLayout\">\n   <item>\n    <widget class=\"QTabWidget\" name=\"tabs\">\n     <property name=\"minimumSize\">\n      <size>\n       <width>0</width>\n       <height>0</height>\n      </size>\n     </property>\n     <property name=\"autoFillBackground\">\n      <bool>false</bool>\n     </property>\n     <property name=\"currentIndex\">\n      <number>0</number>\n     </property>\n     <widget class=\"QWidget\" name=\"subs_tab\">\n      <attribute name=\"title\">\n       <string>Scrobbling</string>\n      </attribute>\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n       <property name=\"spacing\">\n        <number>5</number>\n       </property>\n       <item>\n        <layout class=\"QHBoxLayout\">\n         <property name=\"spacing\">\n          <number>-1</number>\n         </property>\n         <item>\n          <widget class=\"StatusLight\" name=\"subs_light\" native=\"true\">\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Maximum\" vsizetype=\"Maximum\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QLabel\" name=\"subs_status\">\n           <property name=\"toolTip\">\n            <string>This is an easter egg!</string>\n           </property>\n           <property name=\"text\">\n            <string/>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <spacer>\n           <property name=\"orientation\">\n            <enum>Qt::Horizontal</enum>\n           </property>\n           <property name=\"sizeHint\" stdset=\"0\">\n            <size>\n             <width>20</width>\n             <height>2</height>\n            </size>\n           </property>\n          </spacer>\n         </item>\n         <item>\n          <widget class=\"QLabel\" name=\"subs_cache_count\">\n           <property name=\"enabled\">\n            <bool>false</bool>\n           </property>\n           <property name=\"text\">\n            <string/>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </item>\n       <item>\n        <widget class=\"QTreeWidget\" name=\"cached\">\n         <property name=\"sizePolicy\">\n          <sizepolicy hsizetype=\"Expanding\" vsizetype=\"Expanding\">\n           <horstretch>0</horstretch>\n           <verstretch>0</verstretch>\n          </sizepolicy>\n         </property>\n         <property name=\"rootIsDecorated\">\n          <bool>false</bool>\n         </property>\n         <property name=\"uniformRowHeights\">\n          <bool>true</bool>\n         </property>\n         <property name=\"itemsExpandable\">\n          <bool>false</bool>\n         </property>\n         <property name=\"allColumnsShowFocus\">\n          <bool>true</bool>\n         </property>\n         <property name=\"columnCount\">\n          <number>3</number>\n         </property>\n         <column>\n          <property name=\"text\">\n           <string>Artist</string>\n          </property>\n         </column>\n         <column>\n          <property name=\"text\">\n           <string>Track</string>\n          </property>\n         </column>\n         <column>\n          <property name=\"text\">\n           <string>Album</string>\n          </property>\n         </column>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n     <widget class=\"QWidget\" name=\"fingerprintingTab\">\n      <attribute name=\"title\">\n       <string>Fingerprinting</string>\n      </attribute>\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n       <item>\n        <widget class=\"QLabel\" name=\"fingerprints_title\">\n         <property name=\"font\">\n          <font>\n           <weight>75</weight>\n           <bold>true</bold>\n          </font>\n         </property>\n         <property name=\"text\">\n          <string>Recently Fingerprinted Tracks</string>\n         </property>\n        </widget>\n       </item>\n       <item>\n        <widget class=\"QTreeWidget\" name=\"fingerprints\">\n         <property name=\"sizePolicy\">\n          <sizepolicy hsizetype=\"Expanding\" vsizetype=\"Expanding\">\n           <horstretch>0</horstretch>\n           <verstretch>0</verstretch>\n          </sizepolicy>\n         </property>\n         <property name=\"rootIsDecorated\">\n          <bool>false</bool>\n         </property>\n         <property name=\"uniformRowHeights\">\n          <bool>true</bool>\n         </property>\n         <property name=\"itemsExpandable\">\n          <bool>false</bool>\n         </property>\n         <property name=\"allColumnsShowFocus\">\n          <bool>true</bool>\n         </property>\n         <property name=\"columnCount\">\n          <number>3</number>\n         </property>\n         <column>\n          <property name=\"text\">\n           <string>Artist</string>\n          </property>\n         </column>\n         <column>\n          <property name=\"text\">\n           <string>Track</string>\n          </property>\n         </column>\n         <column>\n          <property name=\"text\">\n           <string>Album</string>\n          </property>\n         </column>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n     <widget class=\"QWidget\" name=\"iPodTab\">\n      <attribute name=\"title\">\n       <string>iPod Scrobbling</string>\n      </attribute>\n      <layout class=\"QVBoxLayout\">\n       <item>\n        <layout class=\"QHBoxLayout\">\n         <item>\n          <widget class=\"QComboBox\" name=\"ipod_type\">\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Expanding\" vsizetype=\"Fixed\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <item>\n            <property name=\"text\">\n             <string>iTunes automatically manages my iPod</string>\n            </property>\n           </item>\n           <item>\n            <property name=\"text\">\n             <string>I manually manage my iPod</string>\n            </property>\n           </item>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QPushButton\" name=\"ipod_scrobble_button\">\n           <property name=\"text\">\n            <string>Scrobble iPod</string>\n           </property>\n           <property name=\"autoRepeatDelay\">\n            <number>300</number>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </item>\n       <item>\n        <widget class=\"QPlainTextEdit\" name=\"ipod_log\">\n         <property name=\"font\">\n          <font>\n           <family>Courier New</family>\n          </font>\n         </property>\n         <property name=\"readOnly\">\n          <bool>true</bool>\n         </property>\n         <property name=\"maximumBlockCount\">\n          <number>0</number>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n    </widget>\n   </item>\n   <item>\n    <layout class=\"QHBoxLayout\">\n     <item>\n      <widget class=\"QPushButton\" name=\"logs_button\">\n       <property name=\"text\">\n        <string>Logs</string>\n       </property>\n       <property name=\"autoDefault\">\n        <bool>false</bool>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QLabel\" name=\"label\">\n       <property name=\"text\">\n        <string notr=\"true\">&lt;a href='http://status.last.fm'&gt;http://status.last.fm&lt;/a&gt;</string>\n       </property>\n       <property name=\"textFormat\">\n        <enum>Qt::RichText</enum>\n       </property>\n       <property name=\"openExternalLinks\">\n        <bool>true</bool>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <spacer>\n       <property name=\"orientation\">\n        <enum>Qt::Horizontal</enum>\n       </property>\n       <property name=\"sizeType\">\n        <enum>QSizePolicy::Expanding</enum>\n       </property>\n       <property name=\"sizeHint\" stdset=\"0\">\n        <size>\n         <width>0</width>\n         <height>0</height>\n        </size>\n       </property>\n      </spacer>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"close_button\">\n       <property name=\"text\">\n        <string>&amp;Close</string>\n       </property>\n       <property name=\"default\">\n        <bool>true</bool>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>StatusLight</class>\n   <extends>QWidget</extends>\n   <header>lib/unicorn/widgets/StatusLight.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections>\n  <connection>\n   <sender>close_button</sender>\n   <signal>clicked()</signal>\n   <receiver>DiagnosticsDialog</receiver>\n   <slot>accept()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>471</x>\n     <y>476</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>502</x>\n     <y>336</y>\n    </hint>\n   </hints>\n  </connection>\n </connections>\n</ui>\n"
  },
  {
    "path": "app/client/Dialogs/LicensesDialog.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"lib/unicorn/widgets/Label.h\"\n\n#include \"LicensesDialog.h\"\n#include \"ui_LicensesDialog.h\"\n\nLicensesDialog::LicensesDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::LicensesDialog)\n{\n    ui->setupUi(this);\n\n    setAttribute( Qt::WA_DeleteOnClose );\n\n    QString licenseText;\n    licenseText.append( \"<div id=\\\"content\\\">\" );\n\n    licenseText.append( \"<h3>Third-Party Licenses</h3>\" );\n    licenseText.append( \"<p>The Last.fm Desktop App wouldn't be such a thing of beauty without the frameworks and software listed below. A big shoutout from everyone at Last.HQ, and a tip-of-the-hat to all the developers involved in bringing these great open source projects to life.</p>\" );\n\n    // Qt\n    licenseText.append( \"<hr>\" );\n    licenseText.append( \"<h3>Qt</h3>\" );\n    licenseText.append( \"<ul>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://qt.nokia.com\", \"Qt\" ) + \"</li>\");\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://qt.nokia.com/products/licensing/\", \"Qt License\" ) + \"</li>\");\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html\", \"GNU Lesser General Public License (LGPL) version 2.1\" ) + \"</li>\");\n    licenseText.append( \"</ul>\" );\n\n#ifdef Q_OS_MAC\n    // Sparkle (updating framework)\n    licenseText.append( \"<hr>\" );\n    licenseText.append( \"<h3>Sparkle</h3>\" );\n    licenseText.append( \"<ul>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://sparkle.andymatuschak.org/\", \"Sparkle\" ) + \"</li>\");\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"https://github.com/andymatuschak/Sparkle/blob/master/License.txt\", \"Sparkle License\" ) + \"</li>\");\n    licenseText.append( \"</ul>\" );\n    licenseText.append( \"<p>Copyright (c) 2006 Andy Matuschak</p>\" );\n    licenseText.append( \"<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \\\"Software\\\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p>\" );\n    licenseText.append( \"<p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p>\" );\n    licenseText.append( \"<p>THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>\" );\n#endif\n\n#ifdef Q_OS_WIN\n    // Winsparkle\n    licenseText.append( \"<hr>\" );\n    licenseText.append( \"<h3>winsparkle</h3>\" );\n    licenseText.append( \"<ul>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"https://github.com/vslavik/winsparkle/blob/master/COPYING\", \"Winsparkle License\" ) + \"</li>\" );\n    licenseText.append( \"</ul>\" );\n    licenseText.append( \"<p>Copyright (c) 2009-2010 Vaclav Slavik</p>\" );\n    licenseText.append( \"<p>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \\\"Software\\\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</p>\" );\n    licenseText.append( \"<p>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</p>\" );\n    licenseText.append( \"<p>THE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>\" );\n#endif\n\n#ifdef Q_OS_MAC\n    // Growl\n    licenseText.append( \"<hr>\" );\n    licenseText.append( \"<h3>Growl</h3>\" );\n    licenseText.append( \"<ul>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://growl.info\", \"Growl\" ) + \"<li>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://growl.info/documentation/developer/bsd-license.txt\", \"Growl License\" ) + \"<li>\" );\n    licenseText.append( \"</ul>\" );\n    licenseText.append( \"<p>Copyright (c) The Growl Project, 2004</p>\" );\n    licenseText.append( \"<p>All rights reserved.</p>\" );\n    licenseText.append( \"<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>\" );\n    licenseText.append( \"<ol>\" );\n    licenseText.append( \"<li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li>\" );\n    licenseText.append( \"<li>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</li>\" );\n    licenseText.append( \"<li>Neither the name of Growl nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</li>\" );\n    licenseText.append( \"</ol>\" );\n    licenseText.append( \"<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>\" );\n#endif\n    // Breakpad\n    licenseText.append( \"<hr>\" );\n    licenseText.append( \"<h3>Breakpad</h3>\" );\n    licenseText.append( \"<ul>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://code.google.com/p/google-breakpad/\", \"Breakpad\" ) + \"<li>\" );\n    licenseText.append( \"<li>\" + unicorn::Label::anchor( \"http://code.google.com/p/google-breakpad/source/browse/trunk/COPYING\", \"Breakpad License\" ) + \"<li>\" );\n    licenseText.append( \"</ul>\" );\n    licenseText.append( \"<p>Copyright (c) 2006, Google Inc.</p>\" );\n    licenseText.append( \"<p>All rights reserved.</p>\" );\n    licenseText.append( \"<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>\" );\n    licenseText.append( \"<ol>\" );\n    licenseText.append( \"<li>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</li>\" );\n    licenseText.append( \"<li>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</li>\" );\n    licenseText.append( \"<li>Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.</li>\" );\n    licenseText.append( \"</ol>\" );\n    licenseText.append( \"<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \\\"AS IS\\\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>\" );\n\n    licenseText.append( \"</div>\" );\n\n    licenseText = QString( \"<html><head><style type=text/css>\\n\"\n                     \"#content {margin: 20px;}\"\n                     \"a:link {color:%1; font-weight: bold; text-decoration:none;}\"\n                     \"a:hover {color:%1; font-weight: bold; text-decoration:none;}\"\n                     \"</style></head><body>%2</body></html>\" ).arg( QColor( 0xd71005 ).name(), licenseText );\n\n    ui->textBrowser->setText( licenseText );\n}\n\nLicensesDialog::~LicensesDialog()\n{\n    delete ui;\n}\n"
  },
  {
    "path": "app/client/Dialogs/LicensesDialog.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LICENCEDIALOG_H\n#define LICENCEDIALOG_H\n\n#include <QDialog>\n\nnamespace Ui {\nclass LicensesDialog;\n}\n\nclass LicensesDialog : public QDialog\n{\n    Q_OBJECT\n    \npublic:\n    explicit LicensesDialog(QWidget *parent = 0);\n    ~LicensesDialog();\n    \nprivate:\n    Ui::LicensesDialog *ui;\n};\n\n#endif // LICENCEDIALOG_H\n"
  },
  {
    "path": "app/client/Dialogs/LicensesDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>LicensesDialog</class>\n <widget class=\"QDialog\" name=\"LicensesDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>480</width>\n    <height>503</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Licenses</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QTextBrowser\" name=\"textBrowser\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"openExternalLinks\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Fingerprinter/AacSource.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n   Portions Copyright 2003-2005 M. Bakker, Nero AG, http://www.nero.com\n      - Adapted from main.c found in the FAAD2 source tarball.\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"AacSource.h\"\n#include \"AacSource_p.h\"\n\n#include <QFile>\n#include <algorithm>\n#include <cassert>\n#include <limits>\n#include <iostream>\n#include <stdexcept>\n#include <errno.h>\n#include <string.h>\n\n\n////////////////////////////////////////////////////////////////////////\n//\n// AAC_File\n//\n////////////////////////////////////////////////////////////////////////\nAAC_File::AAC_File(const QString& fileName, int headerType)\n    : m_fileName(fileName)\n    , m_inBuf(NULL)\n    , m_inBufSize(0)\n    , m_decoder(0)\n    , m_overflow(static_cast<unsigned char*>(malloc( sizeof(unsigned char) * 1024 )))\n    , m_overflowSize(0)\n    , m_header(headerType)\n{\n}\n\n\nAAC_File::~AAC_File()\n{\n    // common\n    if ( m_decoder )\n    {\n        NeAACDecClose( m_decoder );\n        m_decoder = NULL;\n    }\n    if ( m_inBuf )\n    {\n        free( m_inBuf );\n        m_inBufSize = 0;\n        m_inBuf = NULL;\n    }\n    if ( m_overflow )\n    {\n        free( m_overflow );\n        m_overflowSize = 0;\n        m_overflow = NULL;\n    }\n}\n\n\n\n////////////////////////////////////////////////////////////////////////\n//\n// AAC with ADTS or ADIF headers\n//\n////////////////////////////////////////////////////////////////////////\n\n\n#define MAX_CHANNELS 6 // Output will get mixed down to 2 channels\n#define ADTS_HEADER_SIZE 8\n\nstatic int adts_sample_rates[] =\n{\n    96000,\n    88200,\n    64000,\n    48000,\n    44100,\n    32000,\n    24000,\n    22050,\n    16000,\n    12000,\n    11025,\n     8000,\n     7350,\n        0,\n        0,\n        0\n};\n\nAAC_ADTS_File::AAC_ADTS_File( const QString& fileName, int headerType ) : AAC_File(fileName, headerType)\n    , m_file( NULL )\n    , m_adifSamplerate( 0 )\n    , m_adifChannels( 0 )\n{\n}\n\n\nAAC_ADTS_File::~AAC_ADTS_File()\n{\n    if ( m_file )\n    {\n        fclose( m_file );\n    }\n}\n\n\nvoid AAC_ADTS_File::fillBuffer( FILE*& fp, unsigned char*& buf, size_t& bufSize, const size_t bytesConsumed )\n{\n    size_t bread;\n\n    if ( bytesConsumed > 0 )\n    {\n        if ( bufSize )\n            memmove( (void*)buf, (void*)(buf + bytesConsumed), bufSize*sizeof(unsigned char) );\n\n        bread = fread( (void*)(buf + bufSize), 1, bytesConsumed, fp );\n        bufSize += bread;\n\n        if ( bufSize > 3 )\n        {\n            if ( memcmp( buf, \"TAG\", 3 ) == 0 )\n                bufSize = 0;\n        }\n        if ( bufSize > 11 )\n        {\n            if ( memcmp( buf, \"LYRICSBEGIN\", 11 ) == 0 )\n                bufSize = 0;\n        }\n        if ( bufSize > 8 )\n        {\n            if ( memcmp( buf, \"APETAGEX\", 8 ) == 0 )\n                bufSize = 0;\n        }\n    }\n}\n\n\nvoid AAC_ADTS_File::parse( FILE*& fp, unsigned char*& buf, size_t& bufSize, int &bitrate, double &length )\n{\n    unsigned int frames, frame_length = 0;\n    int t_framelength = 0;\n    int samplerate = 0;\n    double frames_per_sec, bytes_per_frame;\n\n    // Read all frames to ensure correct time and bitrate\n    for ( frames = 0; /* */; frames++ )\n    {\n        fillBuffer( fp, buf, bufSize, frame_length );\n\n        if ( bufSize > 7 )\n        {\n            /* check syncword */\n            if ( !( (buf[0] == 0xFF) && ((buf[1] & 0xF6) == 0xF0) ) )\n                break;\n\n            if ( frames == 0 )\n                samplerate = adts_sample_rates[ (buf[2] & 0x3c) >> 2 ];\n\n            frame_length = (  ((buf[3] & 0x3) << 11)\n                            | ((buf[4]) << 3)\n                            | (buf[5] >> 5) );\n\n            t_framelength += frame_length - ADTS_HEADER_SIZE;\n\n            if ( frame_length > bufSize )\n                break;\n\n            bufSize -= frame_length;\n        }\n        else\n        {\n            break;\n        }\n    }\n\n    frames_per_sec = samplerate / 1024.0;\n\n    if ( frames != 0 )\n        bytes_per_frame = t_framelength / frames;\n    else\n        bytes_per_frame = 0;\n\n    bitrate = static_cast<int>(8 * bytes_per_frame * frames_per_sec + 0.5);\n\n    if ( frames_per_sec != 0 )\n        length = frames / frames_per_sec;\n    else\n        length = 1;\n}\n\n\nint32_t AAC_ADTS_File::commonSetup( FILE*& fp, NeAACDecHandle& decoder, unsigned char*& buf, size_t& bufSize, unsigned long& samplerate, unsigned char& channels )\n{\n    samplerate = 0;\n    channels = 0;\n\n    fp = fopen(QFile::encodeName(m_fileName), \"rb\" );\n    if( !fp )\n    {\n        std::cerr << \"ERROR: Failed to open \" << strerror( errno ) << std::endl;\n        return -1;\n    }\n\n    if ( !(buf = static_cast<unsigned char*>( malloc(FAAD_MIN_STREAMSIZE*MAX_CHANNELS)) ) )\n    {\n        std::cerr << \"Memory allocation error\" << std::endl;\n        fclose ( fp );\n        return -1;\n    }\n\n    memset( buf, 0, FAAD_MIN_STREAMSIZE*MAX_CHANNELS );\n\n    bufSize = fread( buf, 1, FAAD_MIN_STREAMSIZE * MAX_CHANNELS, fp );\n\n    int tagsize = 0;\n    if ( !memcmp( buf, \"ID3\", 3 ) )\n    {\n        /* high bit is not used */\n        tagsize = (buf[6] << 21) | (buf[7] << 14) |\n            (buf[8] <<  7) | (buf[9] <<  0);\n\n        tagsize += 10;\n        bufSize -= tagsize;\n        fillBuffer( fp, buf, bufSize, tagsize );\n    }\n\n    decoder = NeAACDecOpen();\n\n    /* Set configuration */\n    NeAACDecConfigurationPtr config;\n    config = NeAACDecGetCurrentConfiguration(decoder);\n    config->outputFormat = FAAD_FMT_16BIT;\n    config->downMatrix = 1; // Turn 5.1 channels into 2\n    NeAACDecSetConfiguration( decoder, config);\n\n    int32_t initval = 0;\n    if ((initval = NeAACDecInit(decoder, buf,\n        FAAD_MIN_STREAMSIZE*MAX_CHANNELS, &samplerate, &channels)) < 0)\n    {\n        std::cerr << \"Error: could not set up AAC decoder\" << std::endl;\n        if ( buf )\n            free( buf );\n        buf = NULL;\n        NeAACDecClose( decoder );\n        decoder = NULL;\n        fclose( fp );\n        fp = NULL;\n    }\n    return initval;\n}\n\n\nbool AAC_ADTS_File::init()\n{\n    unsigned long initSamplerate = 0;\n    unsigned char initChannels = 0;\n    int32_t initval = commonSetup( m_file, m_decoder, m_inBuf, m_inBufSize, initSamplerate, initChannels );\n\n     if ( initval >= 0 )\n     {\n        m_inBufSize -= initval;\n        fillBuffer( m_file, m_inBuf, m_inBufSize, initval );\n\n        // These two only needed for skipping AAC ADIF files\n        m_adifSamplerate = initSamplerate;\n        m_adifChannels = initChannels;\n\n        return true;\n     }\n\n     throw std::runtime_error( \"ERROR: Could not initialize AAC file reader!\" );\n     return false;\n}\n\n\n/*QString AAC_ADTS_File::getMbid()\n{\n    char out[MBID_BUFFER_SIZE];\n    int const r = getMP3_MBID(QFile::encodeName(m_fileName), out);\n    if ( r == 0 )\n        return QString::fromLatin1( out );\n    return QString();\n}*/\n\nvoid AAC_ADTS_File::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )\n{\n    long fileread;\n    unsigned long initSamplerate;\n    unsigned char initChannels;\n    double initLength = 0;\n    unsigned char *tempBuf = NULL;\n    size_t tempBufSize;\n    FILE *fp = NULL;\n    NeAACDecHandle decoder = NULL;\n    commonSetup( fp, decoder, tempBuf, tempBufSize, initSamplerate, initChannels );\n\n    long origpos = ftell( fp );\n    fseek( fp, 0, SEEK_END );\n    fileread = ftell( fp );\n    fseek( fp, origpos, SEEK_SET );\n\n    if ( (tempBuf[0] == 0xFF) && ((tempBuf[1] & 0xF6) == 0xF0) )\n    {\n        parse( fp, tempBuf, tempBufSize, bitrate, initLength );\n    }\n    else if (memcmp(tempBuf, \"ADIF\", 4) == 0)\n    {\n        int skip_size = (tempBuf[4] & 0x80) ? 9 : 0;\n        bitrate = ((tempBuf[4 + skip_size] & 0x0F)<<19) |\n            (tempBuf[5 + skip_size]<<11) |\n            (tempBuf[6 + skip_size]<<3) |\n            (tempBuf[7 + skip_size] & 0xE0);\n\n        if ( fileread != 0)\n        {\n            initLength = static_cast<double>(fileread) * 8 / bitrate + 0.5;\n        }\n    }\n\n    lengthSecs = static_cast<int>(initLength);\n    nchannels = initChannels;\n    samplerate = initSamplerate;\n\n    if ( decoder )\n        NeAACDecClose( decoder );\n    if ( fp )\n        fclose( fp );\n    if ( tempBuf )\n        free( tempBuf );\n}\n\n\nvoid AAC_ADTS_File::skip( const int mSecs )\n{\n    if ( m_header == AAC_ADTS )\n    {\n        // As AAC is VBR we need to check all ADTS headers to enable seeking...\n        // There is no other solution\n        unsigned char header[8];\n        unsigned int frameCount, frameLength;\n        double seconds = 0;\n\n        // We need to find the ATDS syncword so rewind to the beginning\n        // of the unprocessed data.\n        if ( m_inBufSize > 0 )\n        {\n            fseek ( m_file, -m_inBufSize, SEEK_CUR );\n            m_inBufSize = 0;\n        }\n\n        for( frameCount = 1; seconds * 1000 < mSecs; frameCount++ )\n        {\n            if ( fread( header, 1, ADTS_HEADER_SIZE, m_file ) != ADTS_HEADER_SIZE )\n            {\n                break;\n            }\n            if ( !strncmp( (char*)header, \"ID3\", 3 ) )\n            {\n                // high bit is not used\n                unsigned char rest[2];\n                fread( rest, 1, 2, m_file );\n                int tagsize = (header[6] << 21) | (header[7] << 14) |\n                    (rest[0] <<  7) | (rest[1] <<  0);\n\n                fseek( m_file, tagsize, SEEK_CUR );\n                fread( header, 1, ADTS_HEADER_SIZE, m_file );\n            }\n            if ( !((header[0] == 0xFF) && ((header[1] & 0xF6) == 0xF0)) )\n            {\n                std::cerr << \"Error: Bad frame header; file may be corrupt!\" << std::endl;\n                break;\n            }\n\n            int samplerate = adts_sample_rates[ (header[2] & 0x3c) >> 2 ];\n            frameLength = ( ( header[3] & 0x3 ) << 11 )\n                          | ( header[4] << 3 )\n                          | ( header[5] >> 5 );\n\n            if ( samplerate > 0 )\n                seconds += 1024.0 / samplerate;\n            else\n            {\n                std::cerr << \"Error: Bad frame header; file may be corrupt!\" << std::endl;\n                break;\n            }\n\n            if ( fseek( m_file, frameLength - ADTS_HEADER_SIZE, SEEK_CUR ) == -1 )\n                break;\n        }\n        m_inBufSize = fread( m_inBuf, 1, FAAD_MIN_STREAMSIZE * MAX_CHANNELS, m_file );\n    }\n    else if ( m_header == AAC_ADIF )\n    {\n        // AAC ADIF is even worse.  There's only the one header at the\n        // beginning of the file.  If you want to skip forward, you have to\n        // decode block by block and check how far along you are.  Lovely, eh?\n\n        unsigned long totalSamples = 0;\n        void *sampleBuffer = NULL;\n\n        do\n        {\n            NeAACDecFrameInfo frameInfo;\n            sampleBuffer = NeAACDecDecode(m_decoder, &frameInfo, m_inBuf, static_cast<uint32_t>(m_inBufSize) );\n            totalSamples += frameInfo.samples;\n            if ( frameInfo.bytesconsumed > 0 )\n            {\n                m_inBufSize -= frameInfo.bytesconsumed;\n                fillBuffer( m_file, m_inBuf, m_inBufSize, frameInfo.bytesconsumed );\n            }\n            if ( totalSamples >= ( mSecs * m_adifSamplerate * m_adifChannels / 1000 ) )\n                break;\n        } while ( sampleBuffer != NULL );\n    }\n}\n\n\nvoid AAC_ADTS_File::postDecode(unsigned long bytesConsumed)\n{\n    m_inBufSize -= bytesConsumed;\n    fillBuffer( m_file, m_inBuf, m_inBufSize, bytesConsumed );\n}\n\n\n////////////////////////////////////////////////////////////////////////\n//\n// AAC in an MP4 wrapper\n//\n////////////////////////////////////////////////////////////////////////\n\n\nuint32_t read_callback( void *user_data, void *buffer, uint32_t length )\n{\n    return static_cast<uint32_t>(fread( buffer, 1, length, static_cast<FILE*>(user_data) ));\n}\n\n\nuint32_t seek_callback( void *user_data, uint64_t position )\n{\n    return fseek( static_cast<FILE*>(user_data), static_cast<long>(position), SEEK_SET );\n}\n\nAAC_MP4_File::AAC_MP4_File( const QString& fileName, int headerType ) : AAC_File(fileName, headerType)\n    , m_mp4AudioTrack( -1 )\n    , m_mp4SampleId( 0 )\n    , m_mp4File ( NULL )\n    , m_mp4cb ( NULL )\n{\n}\n\nint32_t AAC_MP4_File::readSample()\n{\n    unsigned int bsize;\n    int32_t rc = mp4ff_read_sample( m_mp4File, m_mp4AudioTrack, m_mp4SampleId, &m_inBuf,  &bsize );\n    m_inBufSize = bsize;\n    // Not necessarily an error.  Could just mean end of file.\n    //if ( rc == 0 )\n    //    std::cerr << \"Reading samples failed.\" << std::endl;\n    return rc;\n}\n\n\nint32_t AAC_MP4_File::getTrack( const mp4ff_t *f )\n{\n    // find AAC track\n    int32_t numTracks = mp4ff_total_tracks( f );\n\n    for ( int32_t i = 0; i < numTracks; i++ )\n    {\n        unsigned char *buff = NULL;\n        unsigned int buff_size = 0;\n        mp4AudioSpecificConfig mp4ASC;\n\n        mp4ff_get_decoder_config( f, i, &buff, &buff_size );\n\n        if ( buff )\n        {\n            int8_t rc = NeAACDecAudioSpecificConfig( buff, buff_size, &mp4ASC );\n            free( buff );\n\n            if ( rc < 0 )\n                continue;\n            return i;\n        }\n    }\n\n    // can't decode this, probably DRM\n    return -1;\n}\n\n\nbool AAC_MP4_File::commonSetup( NeAACDecHandle& decoder, mp4ff_callback_t*& cb, FILE*& fp, mp4ff_t*& mp4, int32_t& audioTrack )\n{\n    fp = fopen(QFile::encodeName(m_fileName), \"rb\");\n    if ( !fp )\n    {\n        throw std::runtime_error( \"Error: failed to open AAC file!\" );\n        return false;\n    }\n\n    decoder = NeAACDecOpen();\n\n    // Set configuration\n    NeAACDecConfigurationPtr config;\n    config = NeAACDecGetCurrentConfiguration( decoder );\n    config->outputFormat = FAAD_FMT_16BIT;\n    config->downMatrix = 1; // Turn 5.1 channels into 2\n    NeAACDecSetConfiguration( decoder, config );\n\n    // initialise the callback structure\n    cb = static_cast<mp4ff_callback_t*>( malloc( sizeof(mp4ff_callback_t) ) );\n\n    cb->read = read_callback;\n    cb->seek = seek_callback;\n    cb->user_data = fp;\n\n    mp4 = mp4ff_open_read( cb );\n\n    if ( !mp4 )\n    {\n        // unable to open file\n        free( cb );\n        cb = NULL;\n        NeAACDecClose( decoder );\n        decoder = NULL;\n        fclose( fp );\n        fp = NULL;\n        throw std::runtime_error( \"Error: failed to set up AAC decoder!\" );\n        return false;\n    }\n\n    if ( ( audioTrack = getTrack( mp4 )) < 0 )\n    {\n        free( cb );\n        cb = NULL;\n        NeAACDecClose( decoder );\n        decoder = NULL;\n        fclose( fp );\n        fp = NULL;\n        mp4ff_close( mp4 );\n        mp4 = NULL;\n        audioTrack = 0;\n        throw std::runtime_error( \"Error: Unable to find an audio track. Is the file DRM protected?\" );\n        return false;\n    }\n    return true;\n}\n\n\n/*QString AAC_MP4_File::getMbid()\n{\n    int j = mp4ff_meta_get_num_items( m_mp4File );\n    if ( j > 0 )\n    {\n        int k;\n        for ( k = 0; k < j; k++ )\n        {\n            char *tag = NULL, *item = NULL;\n            if ( mp4ff_meta_get_by_index( m_mp4File, k, &item, &tag ) )\n            {\n                if ( item != NULL && tag != NULL )\n                {\n                    QString key(item);\n                    if ( key.toLower() == \"musicbrainz track id\" )\n                    {\n                        QString ret(tag);\n                        free( item );\n                        free( tag );\n                        return ret;\n                    }\n                    free( item );\n                    free( tag );\n                }\n            }\n        }\n    }\n    return QString();\n}*/\n\n\nvoid AAC_MP4_File::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )\n{\n    FILE* fp = NULL;\n    mp4ff_callback_t *cb = NULL;\n    NeAACDecHandle decoder = NULL;\n    mp4ff_t* mp4 = NULL;\n    int32_t audioTrack;\n\n    bool success = commonSetup( decoder, cb, fp, mp4, audioTrack );\n\n    if ( success )\n    {\n        // get basic file info\n        mp4AudioSpecificConfig mp4ASC;\n        unsigned char* buffer = NULL;\n        unsigned int buffer_size = 0;\n        double f = 1024.0;\n        unsigned int framesize = 1024;\n\n        int32_t samples = mp4ff_num_samples( mp4, audioTrack );\n\n        if ( buffer )\n        {\n            if ( NeAACDecAudioSpecificConfig(buffer, buffer_size, &mp4ASC) >= 0 )\n            {\n                if ( mp4ASC.frameLengthFlag == 1 )\n                    framesize = 960;\n                if ( mp4ASC.sbr_present_flag == 1 )\n                    framesize *= 2;\n                if ( mp4ASC.sbr_present_flag == 1 )\n                    f = f * 2.0;\n            }\n            free( buffer );\n        }\n\n        samplerate = mp4ff_get_sample_rate( mp4, audioTrack );\n        if ( samplerate > 0 )\n            lengthSecs = static_cast<int>(samples * f / samplerate + 0.5);\n        bitrate = mp4ff_get_avg_bitrate( mp4, audioTrack );\n        nchannels = mp4ff_get_channel_count( mp4, audioTrack );\n\n        mp4ff_close( mp4 );\n        NeAACDecClose( decoder );\n        free( cb );\n        fclose( fp );\n    }\n}\n\n\nbool AAC_MP4_File::init()\n{\n    FILE* fp = NULL;\n\n    bool success = commonSetup( m_decoder, m_mp4cb, fp, m_mp4File, m_mp4AudioTrack );\n    if ( !success )\n        return false;\n\n    unsigned char* buffer = NULL;\n    unsigned int buffer_size = 0;\n    unsigned long samplerate;\n    unsigned char channels;\n\n    mp4ff_get_decoder_config( m_mp4File, m_mp4AudioTrack, &buffer, &buffer_size );\n\n    if( NeAACDecInit2( m_decoder, buffer, buffer_size, &samplerate, &channels) < 0 )\n    {\n        // If some error initializing occured, skip the file\n        if ( fp )\n            fclose( fp );\n        throw std::runtime_error( \"Error: unable to initialize AAC decoder library!\" );\n        return false;\n    }\n\n    if ( buffer )\n        free( buffer );\n\n    return true;\n}\n\n\nvoid AAC_MP4_File::postDecode(unsigned long)\n{\n            free( m_inBuf );\n            m_inBuf = NULL;\n            m_mp4SampleId++;\n}\n\nvoid AAC_MP4_File::skip( const int mSecs )\n{\n    double dur = 0.0;\n    int f = 1;\n    unsigned char *buff = NULL;\n    unsigned int buff_size = 0;\n    uint32_t totalSamples = mp4ff_num_samples( m_mp4File, m_mp4AudioTrack );\n    mp4AudioSpecificConfig mp4ASC;\n\n    mp4ff_get_decoder_config( m_mp4File, m_mp4AudioTrack, &buff, &buff_size );\n\n    if ( buff )\n    {\n        int8_t rc = NeAACDecAudioSpecificConfig( buff, buff_size, &mp4ASC );\n        free( buff );\n        if ( rc >= 0 && mp4ASC.sbr_present_flag == 1 )\n            f = 2;\n\n        // I think the f multiplier is needed here.\n        while ( dur * 1000.0 * f / static_cast<double>(mp4ASC.samplingFrequency) < mSecs && m_mp4SampleId < totalSamples )\n        {\n            dur += mp4ff_get_sample_duration( m_mp4File, m_mp4AudioTrack, m_mp4SampleId );\n            m_mp4SampleId++;\n        }\n    }\n    else\n        std::cerr << \"Error: could not skip \" << mSecs << \" milliseconds\" << std::endl;\n}\n\n\nAAC_MP4_File::~AAC_MP4_File()\n{\n    if ( m_mp4File )\n        mp4ff_close( m_mp4File );\n    if ( m_mp4cb )\n    {\n        free( m_mp4cb );\n    }\n}\n\n\n////////////////////////////////////////////////////////////////////////\n//\n// AacSource\n//\n////////////////////////////////////////////////////////////////////////\n\nAacSource::AacSource()\n    : m_eof( false )\n    , m_aacFile( NULL )\n{}\n\n\nAacSource::~AacSource()\n{\n    delete m_aacFile;\n}\n\n\nint AacSource::checkHeader()\n{\n    FILE *fp = NULL;\n    unsigned char header[10];\n\n    // check for mp4 file\n    fp = fopen(QFile::encodeName(m_fileName), \"rb\");\n    if ( !fp )\n    {\n        std::cerr << \"Error: failed to open \" << strerror( errno ) << std::endl;\n        return AAC_File::AAC_UNKNOWN;\n    }\n\n    fread( header, 1, 10, fp );\n\n    // MP4 headers\n    if ( !memcmp( &header[4], \"ftyp\", 4 ) )\n    {\n        fclose( fp );\n        return AAC_File::AAC_MP4;\n    }\n\n    // Skip id3 tags\n    int tagsize = 0;\n    if ( !memcmp( header, \"ID3\", 3 ) )\n    {\n        /* high bit is not used */\n        tagsize = (header[6] << 21) | (header[7] << 14) |\n            (header[8] <<  7) | (header[9] <<  0);\n\n        tagsize += 10;\n        fseek( fp, tagsize, SEEK_SET );\n        fread( header, 1, 10, fp );\n    }\n\n    // Check for ADTS OR ADIF headers\n    if ( (header[0] == 0xFF) && ((header[1] & 0xF6) == 0xF0) )\n    {\n        fclose( fp );\n        return AAC_File::AAC_ADTS;\n    }\n    else if (memcmp(header, \"ADIF\", 4) == 0)\n    {\n        fclose( fp );\n        return AAC_File::AAC_ADIF;\n    }\n\n    fclose( fp );\n    return AAC_File::AAC_UNKNOWN;\n}\n\n\nvoid AacSource::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )\n{\n    // get the header plus some other stuff..\n\n    m_aacFile->getInfo( lengthSecs, samplerate, bitrate, nchannels );\n}\n\n\nvoid AacSource::init(const QString& fileName)\n{\n    m_fileName = fileName;\n    \n    int headerType = checkHeader();\n    if ( headerType != AAC_File::AAC_UNKNOWN )\n    {\n        if ( headerType == AAC_File::AAC_MP4 )\n            m_aacFile = new AAC_MP4_File(m_fileName, headerType);\n        else\n            m_aacFile = new AAC_ADTS_File( m_fileName, headerType );\n    }    \n    \n    if ( m_aacFile )\n        m_aacFile->init();\n    else\n        throw std::runtime_error( \"ERROR: No suitable AAC decoder found!\" );\n}\n\n\n/*QString AacSource::getMbid()\n{\n    QString mbid = m_aacFile->getMbid();\n    return mbid;\n}*/\n\n\nvoid AacSource::skip( const int mSecs )\n{\n    if ( mSecs < 0 || !m_aacFile->m_decoder )\n        return;\n\n        m_aacFile->skip( mSecs );\n}\n\n\nvoid AacSource::skipSilence(double silenceThreshold /* = 0.0001 */)\n{\n    if ( !m_aacFile->m_decoder )\n        return;\n\n    silenceThreshold *= static_cast<double>( std::numeric_limits<short>::max() );\n\n    for (;;)\n    {\n        if ( m_aacFile->m_header == AAC_File::AAC_MP4 )\n        {\n            if ( !static_cast<AAC_MP4_File*>(m_aacFile)->readSample() )\n                break;\n        }\n        NeAACDecFrameInfo frameInfo;\n\n        void* sampleBuffer = NeAACDecDecode(m_aacFile->m_decoder, &frameInfo, m_aacFile->m_inBuf, static_cast<uint32_t>(m_aacFile->m_inBufSize) );\n\n        m_aacFile->postDecode( frameInfo.bytesconsumed );\n\n        if ( frameInfo.error > 0 )\n        {\n            break;\n        }\n        else if ( frameInfo.samples > 0 )\n        {\n            double sum = 0;\n            int16_t *buf = static_cast<int16_t*>(sampleBuffer);\n            switch ( frameInfo.channels )\n            {\n                case 1:\n                    for (size_t j = 0; j < frameInfo.samples; ++j)\n                        sum += abs( buf[j] );\n                    break;\n                case 2:\n                    for (size_t j = 0; j < frameInfo.samples; j+=2)\n                        sum += abs( (buf[j] >> 1) + (buf[j+1] >> 1) );\n                    break;\n            }\n            if ( (sum >= silenceThreshold * static_cast<short>(frameInfo.samples/frameInfo.channels) ) )\n                break;\n        }\n    }\n}\n\n\nint AacSource::updateBuffer( signed short *pBuffer, size_t bufferSize )\n{\n    size_t nwrit = 0; //number of samples written to the output buffer\n\n    if ( m_aacFile->m_overflowSize > 0 )\n    {\n        size_t samples_to_use = bufferSize < m_aacFile->m_overflowSize ? bufferSize : m_aacFile->m_overflowSize;\n        memcpy( pBuffer, m_aacFile->m_overflow, samples_to_use * sizeof(signed short) );\n        nwrit += samples_to_use;\n        m_aacFile->m_overflowSize -= samples_to_use;\n        memmove( (void*)(m_aacFile->m_overflow), (void*)(m_aacFile->m_overflow + samples_to_use*sizeof(signed short)), samples_to_use*sizeof(signed short) );\n    }\n\n    if ( !m_aacFile->m_decoder )\n        return 0;\n\n    for (;;)\n    {\n        signed short* pBufferIt = pBuffer + nwrit;\n        void* sampleBuffer;\n\n        assert( nwrit <= bufferSize );\n\n        if ( m_aacFile->m_header == AAC_File::AAC_MP4 )\n        {\n            if ( !static_cast<AAC_MP4_File*>(m_aacFile)->readSample() )\n            {\n                m_eof = true;\n                return static_cast<int>(nwrit);\n            }\n        }\n        NeAACDecFrameInfo frameInfo;\n\n        sampleBuffer = NeAACDecDecode(m_aacFile->m_decoder, &frameInfo, m_aacFile->m_inBuf, static_cast<uint32_t>(m_aacFile->m_inBufSize) );\n        size_t samples_to_use = (bufferSize - nwrit) < frameInfo.samples ? bufferSize-nwrit : frameInfo.samples;\n\n        if ( samples_to_use > 0 && sampleBuffer != NULL )\n        {\n            memcpy( pBufferIt, sampleBuffer, samples_to_use * sizeof(signed short) );\n            nwrit += samples_to_use;\n        }\n\n        if ( samples_to_use < frameInfo.samples )\n        {\n            m_aacFile->m_overflow = static_cast<unsigned char*>(realloc( m_aacFile->m_overflow, (frameInfo.samples - samples_to_use) * sizeof(signed short) ) );\n            memcpy( m_aacFile->m_overflow, static_cast<signed short*>(sampleBuffer) + samples_to_use, (frameInfo.samples - samples_to_use) * sizeof(signed short) );\n            m_aacFile->m_overflowSize = frameInfo.samples - samples_to_use;\n        }\n\n        m_aacFile->postDecode( frameInfo.bytesconsumed );\n\n        if ( sampleBuffer == NULL )\n        {\n            m_eof = true;\n            break;\n        }\n\n        if ( frameInfo.error > 0 )\n        {\n            std::cerr << \"Error: \" << NeAACDecGetErrorMessage(frameInfo.error) << std::endl;\n            break;\n        }\n\n        if ( nwrit == bufferSize )\n            break;\n   }\n\n   return static_cast<int>(nwrit);\n}\n"
  },
  {
    "path": "app/client/Fingerprinter/AacSource.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef __AAC_SOURCE_H__\n#define __AAC_SOURCE_H__\n\n#include <lastfm/FingerprintableSource.h>\n\nclass AacSource : public lastfm::FingerprintableSource\n{\npublic:\n    AacSource();\n    ~AacSource();\n\n    virtual void getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels);\n    virtual void init(const QString& fileName);\n    virtual int updateBuffer(signed short* pBuffer, size_t bufferSize);\n    virtual void skip(const int mSecs);\n    virtual void skipSilence(double silenceThreshold = 0.0001);\n    virtual bool eof() const { return m_eof; }\n\nprivate:\n    int checkHeader();\n    QString m_fileName;\n    bool m_eof;\n    class AAC_File *m_aacFile;\n};\n\n#endif\n\n"
  },
  {
    "path": "app/client/Fingerprinter/AacSource_p.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <faad.h>\n#include <mp4ff.h>\n\nclass AAC_File\n{\npublic:\n    AAC_File(const QString&, int headerType);\n    virtual ~AAC_File();\n    virtual void getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels ) = 0;\n    virtual bool init() = 0;\n    //virtual QString getMbid() = 0;\n    virtual void skip( const int mSecs ) = 0;\n    virtual void postDecode(unsigned long) = 0;\n\n    enum HeaderType\n    {\n        AAC_UNKNOWN = 0,\n        AAC_ADIF,\n        AAC_ADTS,\n        AAC_MP4\n    };\n\n    QString m_fileName;\n    unsigned char *m_inBuf;\n    size_t m_inBufSize;\n    NeAACDecHandle m_decoder;\n    unsigned char *m_overflow;\n    size_t m_overflowSize;\n    int m_header;\n};\n\n\nclass AAC_MP4_File : public AAC_File\n{\npublic:\n    AAC_MP4_File(const QString&, int headerType = AAC_MP4 );\n    ~AAC_MP4_File();\n    virtual void getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels );\n    virtual bool init();\n    //virtual QString getMbid();\n    virtual void skip( const int mSecs );\n    virtual void postDecode(unsigned long);\n    int32_t readSample();\n\nprivate:\n    bool commonSetup( NeAACDecHandle& handle, mp4ff_callback_t*& cb, FILE*& fp, mp4ff_t*& mp4, int32_t& audioTrack );\n    virtual int32_t getTrack( const mp4ff_t* f );\n    int32_t m_mp4AudioTrack;\n    uint32_t m_mp4SampleId;\n    mp4ff_t *m_mp4File;\n    mp4ff_callback_t *m_mp4cb;\n};\n\n\nclass AAC_ADTS_File : public AAC_File\n{\npublic:\n    AAC_ADTS_File( const QString& fileName, int headerType );\n    ~AAC_ADTS_File();\n    virtual void getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels );\n    virtual bool init();\n    //virtual QString getMbid();\n    virtual void skip( const int mSecs );\n    virtual void postDecode(unsigned long bytesconsumed );\n\nprivate:\n    int32_t commonSetup( FILE*& fp, NeAACDecHandle& decoder, unsigned char*& buf, size_t& bufSize, unsigned long& samplerate, unsigned char& channels );\n    void parse( FILE*& fp, unsigned char*& buf, size_t& bufSize, int &bitrate, double &length );\n    void fillBuffer( FILE*& fp, unsigned char*& buf, size_t& bufSize, const size_t m_bytesConsumed );\n\n    FILE* m_file;\n    // These two only needed for skipping AAC ADIF files\n    uint32_t m_adifSamplerate;\n    int m_adifChannels;\n};\n"
  },
  {
    "path": "app/client/Fingerprinter/FlacSource.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"FlacSource.h\"\n#include <algorithm>\n#include <cassert>\n#include <errno.h>\n#include <iostream>\n#include <limits>\n#include <algorithm>\n#include <stdexcept>\n\n#include <QFile>\n\n\nFLAC__StreamDecoderWriteStatus FlacSource::_write_callback(const FLAC__StreamDecoder *, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)\n{\n    assert(client_data != NULL);\n    FlacSource *instance = reinterpret_cast<FlacSource *>(client_data);\n    assert(instance != NULL);\n    return instance->write_callback(frame, buffer);\n}\n\nFLAC__StreamDecoderWriteStatus FlacSource::write_callback(const FLAC__Frame *frame, const FLAC__int32 * const buffer[])\n{\n    m_outBufLen = 0;\n\n    if ( m_outBuf )\n    {\n        size_t i;\n        for(i = 0; i < frame->header.blocksize; i++)\n        {\n            switch ( m_channels )\n            {\n                case 1:\n                    m_outBuf[m_outBufLen] = (FLAC__int16)buffer[0][i]; // mono\n                    m_outBufLen++;\n                    break;\n                case 2:\n                    m_outBuf[m_outBufLen] = (FLAC__int16)buffer[0][i]; // left channel\n                    m_outBuf[m_outBufLen+1] = (FLAC__int16)buffer[1][i]; // right channel\n                    m_outBufLen += 2;\n                    break;\n            }\n        }\n        m_samplePos += frame->header.blocksize;\n    }\n\n    return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;\n}\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::_metadata_callback(const FLAC__StreamDecoder *, const FLAC__StreamMetadata *metadata, void *client_data)\n{\n    assert(client_data != NULL);\n    FlacSource *instance = reinterpret_cast<FlacSource *>(client_data);\n    assert(instance != NULL);\n    instance->metadata_callback(metadata);\n}\n\nvoid FlacSource::metadata_callback( const FLAC__StreamMetadata *metadata )\n{\n    switch ( metadata->type )\n    {\n        case FLAC__METADATA_TYPE_STREAMINFO:\n            m_channels = metadata->data.stream_info.channels;\n            m_totalSamples = metadata->data.stream_info.total_samples;\n            m_samplerate = metadata->data.stream_info.sample_rate;\n            m_bps = metadata->data.stream_info.bits_per_sample;\n            m_maxFrameSize = metadata->data.stream_info.max_framesize;\n            break;\n        case FLAC__METADATA_TYPE_VORBIS_COMMENT:\n            m_commentData = FLAC__metadata_object_clone(metadata);\n            break;\n        default:\n            break;\n    }\n}\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::_error_callback(const FLAC__StreamDecoder *, FLAC__StreamDecoderErrorStatus status, void *client_data)\n{\n    assert(client_data != NULL);\n    FlacSource *instance = reinterpret_cast<FlacSource *>(client_data);\n    assert(instance != NULL);\n    instance->error_callback(status);\n}\n\nvoid FlacSource::error_callback(FLAC__StreamDecoderErrorStatus status)\n{\n    std::cerr << \"Got FLAC error: \" << FLAC__StreamDecoderErrorStatusString[status] << std::endl;\n}\n\n// ---------------------------------------------------------------------\n\nFlacSource::FlacSource()\n    : m_decoder( 0 )\n    , m_fileSize( 0 )\n    , m_outBuf( 0 )\n    , m_outBufLen( 0 )\n    , m_outBufPos( 0 )\n    , m_samplePos( 0 )\n    , m_maxFrameSize( 0 )\n    , m_commentData( 0 )\n    , m_bps( 0 )\n    , m_channels( 0 )\n    , m_samplerate( 0 )\n    , m_totalSamples( 0 )\n    , m_eof( false )\n{\n}\n\n// ---------------------------------------------------------------------\n\nFlacSource::~FlacSource()\n{\n    if ( m_decoder )\n    {\n        FLAC__stream_decoder_finish( m_decoder );\n        FLAC__stream_decoder_delete( m_decoder );\n    }\n    if ( m_commentData )\n        FLAC__metadata_object_delete( m_commentData );\n    if ( m_outBuf )\n        free( m_outBuf );\n}\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::init(const QString& fileName)\n{\n    m_fileName = fileName;\n    \n    if ( !m_decoder )\n    {\n        FILE *f = fopen(QFile::encodeName(m_fileName), \"rb\" );\n        if ( f )\n        {\n            // Need to check which init call to use; flac doesn't do that for us\n            unsigned char header[35];\n            bool isOgg = false;\n            fread( header, 1, 35, f );\n            if ( memcmp(header, \"OggS\", 4) == 0 &&\n                 memcmp(&header[29], \"FLAC\", 4) == 0 )\n                isOgg = true;\n\n            // getInfo() will need this to calculate bitrate\n            fseek( f, 0, SEEK_END );\n            m_fileSize = ftell(f);\n\n            rewind( f );\n\n            m_decoder = FLAC__stream_decoder_new();\n            FLAC__stream_decoder_set_metadata_respond(m_decoder, FLAC__METADATA_TYPE_STREAMINFO);\n            FLAC__stream_decoder_set_metadata_respond(m_decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT);\n\n            int init_status;\n            if ( FLAC_API_SUPPORTS_OGG_FLAC && isOgg )\n                init_status = FLAC__stream_decoder_init_ogg_FILE( m_decoder, f, _write_callback, _metadata_callback, _error_callback, this );\n            else\n                init_status = FLAC__stream_decoder_init_FILE( m_decoder, f, _write_callback, _metadata_callback, _error_callback, this );\n\n            if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK)\n                return;\n\n            FLAC__stream_decoder_process_until_end_of_metadata( m_decoder );\n            m_outBuf = static_cast<signed short*>(malloc( sizeof(signed short)*m_maxFrameSize));\n\n            if ( m_bps != 16 )\n            {\n                FLAC__stream_decoder_finish( m_decoder );\n                FLAC__stream_decoder_delete( m_decoder );\n                FLAC__metadata_object_delete( m_commentData );\n                m_decoder = 0;\n                m_commentData = 0;\n                throw std::runtime_error( \"ERROR: only 16 bit FLAC files are currently supported!\" );\n            }\n        }\n        else\n            throw std::runtime_error( \"ERROR: cannot load FLAC file!\" );\n    }\n}\n\n// ---------------------------------------------------------------------\n\n/*QString FlacSource::getMbid()\n{\n    if ( m_commentData )\n    {\n        FLAC__StreamMetadata_VorbisComment *vc;\n        vc = &m_commentData->data.vorbis_comment;\n        for ( unsigned int i = 0; i < vc->num_comments; ++i )\n        {\n            QByteArray key( (char*)(vc->comments[i].entry), vc->comments[i].length );\n            if ( key.left(20).toLower() == \"musicbrainz_trackid=\" )\n            {\n                QString val = key.mid(20);\n                return val;\n            }\n        }\n    }\n\n    return QString();\n}*/\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels)\n{\n    lengthSecs = 0;\n    samplerate = 0;\n    bitrate = 0;\n    nchannels = 0;\n\n    if ( m_decoder )\n    {\n        samplerate = m_samplerate;\n        nchannels = m_channels;\n        if ( samplerate > 0 )\n            lengthSecs = static_cast<int>( static_cast<double>(m_totalSamples)/m_samplerate + 0.5);\n\n        // Calcuate bitrate\n        if ( lengthSecs > 0 )\n        {\n            FLAC__Metadata_SimpleIterator *it = FLAC__metadata_simple_iterator_new();\n            FLAC__metadata_simple_iterator_init( it, QFile::encodeName(m_fileName), true, true );\n            while( !FLAC__metadata_simple_iterator_is_last( it ) )\n            {\n                FLAC__metadata_simple_iterator_next( it );\n            }\n            off_t audioOffset = FLAC__metadata_simple_iterator_get_block_offset( it ) +\n                FLAC__metadata_simple_iterator_get_block_length( it );\n            FLAC__metadata_simple_iterator_delete( it );\n            bitrate = static_cast<int>( static_cast<double>(m_fileSize - audioOffset) * 8 / lengthSecs + 0.5 );\n        }\n    }\n}\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::skip( const int mSecs )\n{\n    FLAC__uint64 absSample = mSecs * m_samplerate / 1000 + m_samplePos;\n    if ( !FLAC__stream_decoder_seek_absolute(m_decoder, absSample) )\n        FLAC__stream_decoder_reset( m_decoder );\n    m_outBufLen = 0;\n}\n\n// ---------------------------------------------------------------------\n\nvoid FlacSource::skipSilence(double silenceThreshold /* = 0.0001 */)\n{\n    silenceThreshold *= static_cast<double>( std::numeric_limits<short>::max() );\n    for ( ;; )\n    {\n        double sum = 0;\n        bool result = FLAC__stream_decoder_process_single( m_decoder );\n        // there was a fatal read\n        if ( !result )\n            break;\n\n        switch ( m_channels )\n        {\n            case 1:\n                for (size_t j = 0; j < m_outBufLen; ++j)\n                    sum += abs( m_outBuf[j] );\n                break;\n            case 2:\n                for ( size_t j = 0; j < m_outBufLen; j+=2 )\n                    sum += abs( (m_outBuf[j] >> 1)\n                                + (m_outBuf[j+1] >> 1) );\n                break;\n        }\n        if ( (sum >= silenceThreshold * static_cast<double>(m_outBufLen) ) )\n            break;\n    }\n    m_outBufLen = 0;\n}\n\n// ---------------------------------------------------------------------\n\nint FlacSource::updateBuffer( signed short *pBuffer, size_t bufferSize )\n{\n    size_t nwrit = 0;\n\n    for ( ;; )\n    {\n        size_t samples_to_use = std::min (bufferSize - nwrit, m_outBufLen - m_outBufPos);\n        signed short* pBufferIt = pBuffer + nwrit;\n\n        nwrit += samples_to_use;\n        assert( nwrit <= bufferSize );\n        memcpy( pBufferIt, m_outBuf + m_outBufPos, sizeof(signed short)*samples_to_use );\n\n        if ( samples_to_use < m_outBufLen - m_outBufPos )\n            m_outBufPos = samples_to_use;\n        else\n        {\n            m_outBufPos = 0;\n            bool result = FLAC__stream_decoder_process_single( m_decoder );\n            // there was a fatal read\n            if ( !result )\n            {\n                std::cerr << \"Fatal error decoding FLAC\" << std::endl;\n                return 0;\n            }\n            else if ( FLAC__stream_decoder_get_state( m_decoder ) == FLAC__STREAM_DECODER_END_OF_STREAM )\n            {\n                m_eof = true;\n                break;\n            }\n        }\n\n        if ( nwrit == bufferSize )\n            return static_cast<int>(nwrit);\n    }\n    return static_cast<int>(nwrit);\n}\n\n// -----------------------------------------------------------------------------\n\n"
  },
  {
    "path": "app/client/Fingerprinter/FlacSource.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef __FLAC_SOURCE_H__\n#define __FLAC_SOURCE_H__\n\n#include <lastfm/FingerprintableSource.h>\n#include <FLAC/stream_decoder.h>\n#include <FLAC/metadata.h>\n\n\nclass FlacSource : public lastfm::FingerprintableSource\n{\npublic:\n    FlacSource();\n    virtual ~FlacSource();\n\n    virtual void getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels);\n    virtual void init(const QString& fileName);\n\n    // return a chunk of PCM data from the FLAC file\n    virtual int updateBuffer(signed short* pBuffer, size_t bufferSize);\n\n    virtual void skip(const int mSecs);\n    virtual void skipSilence(double silenceThreshold = 0.0001);\n\n    //QString getMbid();\n\n    bool eof() const { return m_eof; }\n\nprivate:\n    static FLAC__StreamDecoderWriteStatus _write_callback(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);\n    static void _metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);\n    static void _error_callback(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data);\n\n    FLAC__StreamDecoderWriteStatus write_callback(const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);\n    void metadata_callback( const FLAC__StreamMetadata *metadata );\n    void error_callback(FLAC__StreamDecoderErrorStatus status);\n\n    FLAC__StreamDecoder *m_decoder;\n    QString m_fileName;\n    size_t m_fileSize;\n    short *m_outBuf;\n    size_t m_outBufLen;\n    size_t m_outBufPos;\n    FLAC__uint64 m_samplePos;\n    unsigned m_maxFrameSize;\n    FLAC__StreamMetadata* m_commentData;\n    unsigned m_bps;\n    unsigned m_channels;\n    unsigned m_samplerate;\n    FLAC__uint64 m_totalSamples;\n\n    bool m_eof;\n};\n\n#endif\n\n"
  },
  {
    "path": "app/client/Fingerprinter/MadSource.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n\n#include <iostream>\n#include <fstream>\n#include <limits>\n#include <climits>\n#include <cstdlib>\n#include <sstream>\n#include <cassert>\n#include <stdexcept>\n#include \"MadSource.h\"\n\n#undef max // was definded in mad\n\nusing namespace std;\n\n\n// -----------------------------------------------------------\n\nMadSource::MadSource()\n          : m_pMP3_Buffer ( new unsigned char[m_MP3_BufferSize+MAD_BUFFER_GUARD] )\n{}\n\n// -----------------------------------------------------------\n\nMadSource::~MadSource()\n{\n   if ( m_inputFile.isOpen() )\n   {\n      m_inputFile.close();\n      mad_synth_finish(&m_mad_synth);\n      mad_frame_finish(&m_mad_frame);\n      mad_stream_finish(&m_mad_stream);\n   }\n   if (m_pMP3_Buffer) delete[] m_pMP3_Buffer;\n}\n\n// ---------------------------------------------------------------------\n\ninline short f2s(mad_fixed_t f)\n{\n   /* A fixed point number is formed of the following bit pattern:\n   *\n   * SWWWFFFFFFFFFFFFFFFFFFFFFFFFFFFF\n   * MSB                          LSB\n   * S ==> Sign (0 is positive, 1 is negative)\n   * W ==> Whole part bits\n   * F ==> Fractional part bits\n   *\n   * This pattern contains MAD_F_FRACBITS fractional bits, one\n   * should alway use this macro when working on the bits of a fixed\n   * point number. It is not guaranteed to be constant over the\n   * different platforms supported by libmad.\n   *\n   * The signed short value is formed, after clipping, by the least\n   * significant whole part bit, followed by the 15 most significant\n   * fractional part bits. Warning: this is a quick and dirty way to\n   * compute the 16-bit number, madplay includes much better\n   * algorithms.\n   */\n\n   /* Clipping */\n   if(f >= MAD_F_ONE)\n      return(SHRT_MAX);\n   if(f <= -MAD_F_ONE)\n      return(-SHRT_MAX);\n\n   /* Conversion. */\n   f = f >> (MAD_F_FRACBITS-15);\n   return (signed short)f;\n}\n\n// ---------------------------------------------------------------------\n\nstring MadSource::MadErrorString(const mad_error& error)\n{\n   switch(error)\n   {\n      /* Generic unrecoverable errors. */\n   case MAD_ERROR_BUFLEN:\n      return(\"input buffer too small (or EOF)\");\n   case MAD_ERROR_BUFPTR:\n      return(\"invalid (null) buffer pointer\");\n   case MAD_ERROR_NOMEM:\n      return(\"not enough memory\");\n\n      /* Frame header related unrecoverable errors. */\n   case MAD_ERROR_LOSTSYNC:\n      return(\"lost synchronization\");\n   case MAD_ERROR_BADLAYER:\n      return(\"reserved header layer value\");\n   case MAD_ERROR_BADBITRATE:\n      return(\"forbidden bitrate value\");\n   case MAD_ERROR_BADSAMPLERATE:\n      return(\"reserved sample frequency value\");\n   case MAD_ERROR_BADEMPHASIS:\n      return(\"reserved emphasis value\");\n\n      /* Recoverable errors */\n   case MAD_ERROR_BADCRC:\n      return(\"CRC check failed\");\n   case MAD_ERROR_BADBITALLOC:\n      return(\"forbidden bit allocation value\");\n   case MAD_ERROR_BADSCALEFACTOR:\n      return(\"bad scalefactor index\");\n   case MAD_ERROR_BADFRAMELEN:\n      return(\"bad frame length\");\n   case MAD_ERROR_BADBIGVALUES:\n      return(\"bad big_values count\");\n   case MAD_ERROR_BADBLOCKTYPE:\n      return(\"reserved block_type\");\n   case MAD_ERROR_BADSCFSI:\n      return(\"bad scalefactor selection info\");\n   case MAD_ERROR_BADDATAPTR:\n      return(\"bad main_data_begin pointer\");\n   case MAD_ERROR_BADPART3LEN:\n      return(\"bad audio data length\");\n   case MAD_ERROR_BADHUFFTABLE:\n      return(\"bad Huffman table select\");\n   case MAD_ERROR_BADHUFFDATA:\n      return(\"Huffman data overrun\");\n   case MAD_ERROR_BADSTEREO:\n      return(\"incompatible block_type for JS\");\n\n      /* Unknown error. This switch may be out of sync with libmad's\n      * defined error codes.\n      */\n   default:\n      return(\"Unknown error code\");\n   }\n}\n\n\n// -----------------------------------------------------------------------------\n\nbool MadSource::isRecoverable(const mad_error& error, bool log)\n{\n   if (MAD_RECOVERABLE (error))\n   {\n      /* Do not print a message if the error is a loss of\n      * synchronization and this loss is due to the end of\n      * stream guard bytes. (See the comments marked {3}\n      * supra for more informations about guard bytes.)\n      */\n      if (error != MAD_ERROR_LOSTSYNC   /*|| mad_stream.this_frame != pGuard */ && log)\n      {\n          qWarning() << \"Recoverable frame level error: \"\n              << QString::fromStdString( MadErrorString(error) );\n      }\n\n      return true;\n   }\n   else\n   {\n      if (error == MAD_ERROR_BUFLEN)\n         return true;\n      else\n      {\n         QDataStream ss;\n\n         ss << \"Unrecoverable frame level error: \"\n            << QString::fromStdString( MadErrorString (error) );\n\n         throw \"ss.\";\n      }\n   }\n\n   return false;\n}\n\n// -----------------------------------------------------------\n\nvoid MadSource::init(const QString& fileName)\n{\n   m_inputFile.setFileName( m_fileName = fileName );\n   bool fine = m_inputFile.open( QIODevice::ReadOnly );\n\n   if ( !fine )\n   {\n      throw std::runtime_error (\"Cannot load mp3 file!\");\n   }\n\n   mad_stream_init(&m_mad_stream);\n   mad_frame_init (&m_mad_frame);\n   mad_synth_init (&m_mad_synth);\n   mad_timer_reset(&m_mad_timer);\n\n   m_pcmpos = m_mad_synth.pcm.length;\n}\n\n// -----------------------------------------------------------------------------\n\n/*QString MadSource::getMbid()\n{\n    char out[MBID_BUFFER_SIZE];\n    int const r = getMP3_MBID( QFile::encodeName( m_fileName ), out );\n    if (r == 0)\n        return QString::fromLatin1( out );\n    return QString();\n}*/\n\nvoid MadSource::getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )\n{\n   // get the header plus some other stuff..\n   QFile inputFile(m_fileName);\n   bool fine = inputFile.open( QIODevice::ReadOnly );\n\n   if ( !fine )\n   {\n      throw std::runtime_error (\"ERROR: Cannot load file for getInfo!\");\n      return;\n   }\n\n   unsigned char* pMP3_Buffer  = new unsigned char[m_MP3_BufferSize+MAD_BUFFER_GUARD];\n\n   mad_stream   madStream;\n   mad_header  madHeader;\n   mad_timer_t  madTimer;\n\n   mad_stream_init(&madStream);\n   mad_timer_reset(&madTimer);\n\n   double avgSamplerate = 0;\n   double avgBitrate = 0;\n   double avgNChannels = 0;\n   int nFrames = 0;\n\n   while ( fetchData( inputFile, pMP3_Buffer, m_MP3_BufferSize, madStream) )\n   {\n      if ( mad_header_decode(&madHeader, &madStream) != 0 )\n      {\n         if ( isRecoverable(madStream.error) )\n            continue;\n         else\n            break;\n      }\n\n      mad_timer_add(&madTimer, madHeader.duration);\n\n      avgSamplerate += madHeader.samplerate;\n      avgBitrate += madHeader.bitrate;\n\n      if ( madHeader.mode == MAD_MODE_SINGLE_CHANNEL )\n         ++avgNChannels;\n      else\n         avgNChannels += 2;\n\n      ++nFrames;\n   }\n\n   inputFile.close();\n   mad_stream_finish(&madStream);\n   mad_header_finish(&madHeader);\n   delete[] pMP3_Buffer;\n\n\n   lengthSecs = static_cast<int>(madTimer.seconds);\n   samplerate = static_cast<int>( (avgSamplerate/nFrames) + 0.5 );\n   bitrate = static_cast<int>( (avgBitrate/nFrames) + 0.5 );\n   nchannels = static_cast<int>( (avgNChannels/nFrames) + 0.5 );\n}\n\n// -----------------------------------------------------------\n\n\nbool MadSource::fetchData( QFile& mp3File,\n                            unsigned char* pMP3_Buffer,\n                            const int MP3_BufferSize,\n                            mad_stream& madStream )\n{\n   unsigned char *pReadStart = NULL;\n   unsigned char *pGuard = NULL;\n\n   if ( madStream.buffer == NULL || \n        madStream.error == MAD_ERROR_BUFLEN )\n   {\n\n      size_t readSize;\n      size_t remaining;\n\n      /* {2} libmad may not consume all bytes of the input\n      * buffer. If the last frame in the buffer is not wholly\n      * contained by it, then that frame's start is pointed by\n      * the next_frame member of the Stream structure. This\n      * common situation occurs when mad_frame_decode() fails,\n      * sets the stream error code to MAD_ERROR_BUFLEN, and\n      * sets the next_frame pointer to a non NULL value. (See\n      * also the comment marked {4} bellow.)\n      *\n      * When this occurs, the remaining unused bytes must be\n      * put back at the beginning of the buffer and taken in\n      * account before refilling the buffer. This means that\n      * the input buffer must be large enough to hold a whole\n      * frame at the highest observable bit-rate (currently 448\n      * kb/s). XXX=XXX Is 2016 bytes the size of the largest\n      * frame? (448000*(1152/32000))/8\n      */\n      if (madStream.next_frame != NULL)\n      {\n         remaining = madStream.bufend - madStream.next_frame;\n         memmove (pMP3_Buffer, madStream.next_frame, remaining);\n\n         pReadStart = pMP3_Buffer + remaining;\n         readSize = MP3_BufferSize - remaining;\n      }\n      else\n      {\n         readSize = MP3_BufferSize;\n         pReadStart = pMP3_Buffer;\n         remaining = 0;\n      }\n\n      readSize = mp3File.read( reinterpret_cast<char*>(pReadStart), readSize );\n\n      // nothing else to read!\n      if (readSize <= 0) \n         return false;\n\n      if ( mp3File.atEnd() )\n      {\n         pGuard = pReadStart + readSize;\n\n         memset (pGuard, 0, MAD_BUFFER_GUARD);\n         readSize += MAD_BUFFER_GUARD;\n      }\n\n      // Pipe the new buffer content to libmad's stream decoder facility.\n      mad_stream_buffer( &madStream, pMP3_Buffer,\n                         static_cast<unsigned int>(readSize + remaining));\n\n      madStream.error = MAD_ERROR_NONE;\n   }\n\n   return true;\n}\n\n// -----------------------------------------------------------------------------\n\nvoid MadSource::skipSilence(double silenceThreshold /* = 0.0001 */)\n{\n   mad_frame  madFrame;\n   mad_synth    madSynth;\n\n   mad_frame_init(&madFrame);\n   mad_synth_init (&madSynth);\n\n   silenceThreshold *= static_cast<double>( numeric_limits<short>::max() );\n\n   for (;;)\n   {\n      if ( !fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream) )\n         break;\n\n      if ( mad_frame_decode(&madFrame, &m_mad_stream) != 0 )\n      {\n         if ( isRecoverable(m_mad_stream.error) )\n            continue;\n         else\n            break;\n      }\n\n      mad_synth_frame (&madSynth, &madFrame);\n\n      double sum = 0;\n\n      switch (madSynth.pcm.channels)\n      {\n      case 1:\n         for (size_t j = 0; j < madSynth.pcm.length; ++j)\n            sum += abs(f2s(madSynth.pcm.samples[0][j]));\n         break;\n      case 2:\n         for (size_t j = 0; j < madSynth.pcm.length; ++j)\n            sum += abs(f2s(\n                     (madSynth.pcm.samples[0][j] >> 1)\n                   + (madSynth.pcm.samples[1][j] >> 1)));\n         break;\n      }\n\n      if ( (sum >= silenceThreshold * madSynth.pcm.length) )\n         break;\n   }\n\n   mad_frame_finish(&madFrame);\n}\n\n// -----------------------------------------------------------------------------\n\nvoid MadSource::skip(const int mSecs)\n{\n   if ( mSecs <= 0 )\n      return;\n\n   mad_header  madHeader;\n   mad_header_init(&madHeader);\n\n   for (;;)\n   {\n      if (!fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream))\n         break;\n\n      if ( mad_header_decode(&madHeader, &m_mad_stream) != 0 )\n      {\n         if ( isRecoverable(m_mad_stream.error) )\n            continue;\n         else\n            break;\n      }\n \n      mad_timer_add(&m_mad_timer, madHeader.duration);\n\n      if ( mad_timer_count(m_mad_timer, MAD_UNITS_MILLISECONDS) >= mSecs )\n         break;\n   }\n\n   mad_header_finish(&madHeader);\n}\n\n// -----------------------------------------------------------\n\nint MadSource::updateBuffer(signed short* pBuffer, size_t bufferSize)\n{\n   size_t nwrit = 0; //number of samples written to the output buffer\n\n   for (;;)\n   {\n      // get a (valid) frame\n      // m_pcmpos == 0 could mean two things\n      // - we have completely decoded a frame, but the output buffer is still\n      //   not full (it would make more sense for pcmpos == pcm.length(), but\n      //   the loop assigns pcmpos = 0 at the end and does it this way!\n      // - we are starting a stream\n      if ( m_pcmpos == m_mad_synth.pcm.length )\n      {\n         if ( !fetchData( m_inputFile, m_pMP3_Buffer, m_MP3_BufferSize, m_mad_stream) )\n         {\n            break; // nothing else to read\n         }\n\n         // decode the frame\n         if (mad_frame_decode (&m_mad_frame, &m_mad_stream))\n         {\n            if ( isRecoverable(m_mad_stream.error) )\n               continue;\n            else\n               break;\n         } // if (mad_frame_decode (&madFrame, &madStream))\n\n         mad_timer_add (&m_mad_timer, m_mad_frame.header.duration);\n         mad_synth_frame (&m_mad_synth, &m_mad_frame);\n\n         m_pcmpos = 0;\n      }\n\n      size_t samples_for_mp3 = m_mad_synth.pcm.length - m_pcmpos;\n      size_t samples_for_buf = bufferSize - nwrit;\n      signed short* pBufferIt = pBuffer + nwrit;\n      size_t i = 0, j = 0;\n\n      switch( m_mad_synth.pcm.channels )\n      {\n      case 1:\n         {\n            size_t samples_to_use = min (samples_for_mp3, samples_for_buf);\n            for (i = 0; i < samples_to_use; ++i )\n               pBufferIt[i] = f2s( m_mad_synth.pcm.samples[0][i+m_pcmpos] );\n         }\n         j = i;\n         break;\n\n      case 2:\n         for (; i < samples_for_mp3 && j < samples_for_buf ; ++i, j+=2 )\n         {\n            pBufferIt[j]   = f2s( m_mad_synth.pcm.samples[0][i+m_pcmpos] );\n            pBufferIt[j+1] = f2s( m_mad_synth.pcm.samples[1][i+m_pcmpos] );\n         }\n         break;\n\n      default:\n         cerr << \"wtf kind of mp3 has \" << m_mad_synth.pcm.channels << \" channels??\\n\";\n         break;\n      }\n\n      m_pcmpos += i;\n      nwrit += j;\n\n      assert( nwrit <= bufferSize );\n\n      if (nwrit == bufferSize) \n         return static_cast<int>(nwrit);\n   }\n\n   return static_cast<int>(nwrit);\n}\n\n// -----------------------------------------------------------------------------\n\n"
  },
  {
    "path": "app/client/Fingerprinter/MadSource.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef __MP3_SOURCE_H__\n#define __MP3_SOURCE_H__\n\n#include <lastfm/FingerprintableSource.h>\n#include <QFile>\n#include <string>\n#include <vector>\n#include <fstream>\n#include <mad.h>\n\n\nclass MadSource : public lastfm::FingerprintableSource\n{\npublic:\n    MadSource();\n    ~MadSource();\n\n    virtual void getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels);\n    virtual void init(const QString& fileName);\n    virtual int updateBuffer(signed short* pBuffer, size_t bufferSize);\n    virtual void skip(const int mSecs);\n    virtual void skipSilence(double silenceThreshold = 0.0001);\n    virtual bool eof() const { return m_inputFile.atEnd(); }\n\nprivate:\n    static bool fetchData( QFile& mp3File,\n                           unsigned char* pMP3_Buffer,\n                           const int MP3_BufferSize,\n                           mad_stream& madStream );\n\n    static bool isRecoverable(const mad_error& error, bool log = false);\n\n    static std::string MadErrorString(const mad_error& error);\n\n    struct mad_stream    m_mad_stream;\n    struct mad_frame     m_mad_frame;\n    mad_timer_t          m_mad_timer;\n    struct mad_synth     m_mad_synth;\n\n    QFile                m_inputFile;\n\n    unsigned char*       m_pMP3_Buffer;\n    static const int     m_MP3_BufferSize = (5*8192);\n    QString              m_fileName;\n\n    size_t               m_pcmpos;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Fingerprinter/VorbisSource.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"VorbisSource.h\"\n#include <QFile>\n#include <cassert>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n#include <errno.h>\n\n// These specify the output format\nstatic const int wordSize = 2; // 16 bit output\nstatic const int isSigned = 1;\n#if __BIG_ENDIAN__\nstatic const int isBigEndian = 1;\n#else\nstatic const int isBigEndian = 0;\n#endif\n\n\nVorbisSource::VorbisSource()\n    : m_channels( 0 )\n    , m_samplerate( 0 )\n    , m_eof( false )\n{\n    memset( &m_vf, 0, sizeof(m_vf) );\n}\n\n// ---------------------------------------------------------------------\n\nVorbisSource::~VorbisSource()\n{\n    // ov_clear() also closes the file\n    ov_clear( &m_vf );\n}\n\n// ---------------------------------------------------------------------\n\nvoid VorbisSource::init(const QString& fileName)\n{\n    m_fileName = fileName;\n    \n    if ( m_vf.datasource )\n    {\n        std::cerr << \"Warning: file already appears to be open\";\n        return;\n    }\n\n    FILE *fp = fopen(QFile::encodeName(m_fileName), \"rb\" );\n    if( !fp )\n        throw std::runtime_error( \"ERROR: Cannot open ogg file!\" );\n\n    // See the warning about calling ov_open on Windows\n    if ( ov_test_callbacks( fp, &m_vf, NULL, 0, OV_CALLBACKS_DEFAULT ) < 0 )\n    {\n        fclose( fp );\n        throw std::runtime_error( \"ERROR: This is not an ogg vorbis file!\" );\n    }\n\n    ov_test_open( &m_vf );\n\n    // Don't fingerprint files with more than one logical bitstream\n    // They most likely contain more than one track\n    if ( ov_streams( &m_vf ) != 1 )\n        throw std::runtime_error( \"ERROR: ogg file contains multiple bitstreams\" );\n\n    m_channels = ov_info( &m_vf, 0 )->channels;\n    m_samplerate = static_cast<int>(ov_info( &m_vf, 0 )->rate);\n    m_eof = false;\n}\n\nvoid VorbisSource::getInfo( int& lengthSecs, int& samplerate, int& bitrate, int& nchannels)\n{\n    // stream info\n    nchannels = ov_info( &m_vf, -1 )->channels;\n    samplerate = static_cast<int>(ov_info( &m_vf, -1 )->rate);\n    lengthSecs = static_cast<int>(ov_time_total( &m_vf, -1 ) + 0.5);\n    bitrate = static_cast<int>(ov_bitrate( &m_vf, -1 ));\n}\n\n// ---------------------------------------------------------------------\n\nvoid VorbisSource::skip( const int mSecs )\n{\n    if ( mSecs < 0 )\n        return;\n\n    double ts = mSecs / 1000.0 + ov_time_tell( &m_vf );\n    ov_time_seek( &m_vf, ts );\n}\n\n// ---------------------------------------------------------------------\n\nvoid VorbisSource::skipSilence(double silenceThreshold /* = 0.0001 */)\n{\n    silenceThreshold *= static_cast<double>( std::numeric_limits<short>::max() );\n\n    char sampleBuffer[4096];\n    int bs = 0;\n    for (;;)\n    {\n        long charReadBytes = ov_read( &m_vf, sampleBuffer, 4096, isBigEndian, wordSize, isSigned, &bs );\n\n        // eof\n        if ( !charReadBytes )\n        {\n            m_eof = true;\n            break;\n        }\n        if ( charReadBytes < 0 )\n        {\n            // a bad bit of data: OV_HOLE || OV_EBADLINK\n            continue;\n        }\n        else if ( charReadBytes > 0 )\n        {\n            double sum = 0;\n            char *buf = sampleBuffer;\n            switch ( m_channels )\n            {\n                case 1:\n                    for (long j = 0; j < charReadBytes/wordSize; j++)\n                        sum += abs( buf[j] );\n                    break;\n                case 2:\n                    for (long j = 0; j < charReadBytes/wordSize; j+=2)\n                        sum += abs( (buf[j] >> 1) + (buf[j+1] >> 1) );\n                    break;\n            }\n            if ( sum >= silenceThreshold * static_cast<double>(charReadBytes/wordSize/m_channels) )\n                break;\n        }\n    }\n}\n\n// ---------------------------------------------------------------------\n\nint VorbisSource::updateBuffer( signed short *pBuffer, size_t bufferSize )\n{\n    char* buf = new char[ bufferSize * wordSize ];\n    int bs = 0;\n    size_t charwrit = 0; //number of samples written to the output buffer\n\n    for (;;)\n    {\n        long charReadBytes = ov_read( &m_vf, buf, static_cast<int>(bufferSize * wordSize - charwrit),\n                                      isBigEndian, wordSize, isSigned, &bs );\n        if ( !charReadBytes )\n        {\n            m_eof = true;\n            break; // nothing else to read\n        }\n\n        // Don't really need this though since we're excluding files that have\n        // more than one logical bitstream\n        if ( bs != 0 )\n        {\n            vorbis_info *vi = ov_info( &m_vf, -1 );\n            if ( m_channels != vi->channels || m_samplerate != vi->rate )\n            {\n                std::cerr << \"Files that change channel parameters or samplerate are currently not supported\" << std::endl;\n                return 0;\n            }\n        }\n\n        if( charReadBytes < 0 )\n        {\n            std::cerr << \"Warning: corrupt section of data, attempting to continue...\" << std::endl;\n            continue;\n        }\n\n        char* pBufferIt = reinterpret_cast<char*>(pBuffer) + charwrit;\n        charwrit += charReadBytes;\n\n        assert( charwrit <= bufferSize * wordSize );\n        memcpy( pBufferIt, buf, charReadBytes );\n\n      if (charwrit == bufferSize * wordSize)\n         return static_cast<int>(charwrit/wordSize);\n   }\n\n   delete[] buf;\n\n   return static_cast<int>(charwrit/wordSize);\n}\n\n// -----------------------------------------------------------------------------\n\n"
  },
  {
    "path": "app/client/Fingerprinter/VorbisSource.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef __VORBIS_SOURCE_H__\n#define __VORBIS_SOURCE_H__\n\n#include <lastfm/FingerprintableSource.h>\n#include <vorbis/vorbisfile.h>\n\n\nclass VorbisSource : public lastfm::FingerprintableSource\n{\npublic:\n    VorbisSource();\n    ~VorbisSource();\n    virtual void getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels);\n    virtual void init(const QString& fileName);\n    virtual int updateBuffer(signed short* pBuffer, size_t bufferSize);\n    virtual void skip(const int mSecs);\n    virtual void skipSilence(double silenceThreshold = 0.0001);\n    virtual bool eof() const { return m_eof; }\n\nprivate:\n    OggVorbis_File m_vf;\n    QString m_fileName;\n    int m_channels;\n    int m_samplerate;\n    bool m_eof;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Last.fm Scrobbler.css",
    "content": "\nSlidingStackedWidget {\n\tqproperty-speed: 200;\n\tqproperty-easingCurve: OutCirc;\n}\n\nFirstRunWizard {\n\tbackground-repeat: none;\n\tbackground-color: white;\n\tbackground-image: url(\":/bg_clouds.png\");\n}\n\nFirstRunWizard QLabel#welcome {\n\tcolor: #333;\n\tfont-size: 14px;\n\tmargin: 30px 30px 0px;\n}\n\nFirstRunWizard QLabel#title {\n\tcolor: #d51007;\n\tfont-size: 16px;\n\tfont-weight: bold;\n\tmargin: 30px;\n}\n\nWizardPage QLabel {\n\tcolor: #333;\n\tfont-size: 14px;\n}\n\nFirstRunWizard QStackedWidget {\n  margin: 0px 40px;\n}\n\nFirstRunWizard QAbstractButton {\nbackground-color: transparent;\nborder: none;\nfont-size: 11px;\ncolor: #333;\n}\n\nFirstRunWizard #authUrl {\n\tborder: none;\n\tbackground: transparent;\n\tcolor: #333;\n}\n\n/* QWizard::NextButton */\n/* QWizard::FinishButton */\n/* QWizard::CommitButton */\nFirstRunWizard QAbstractButton#next,\nFirstRunWizard QAbstractButton#finish {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #cc4d25, stop:1 #a02b1e);\n\tfont-size: 14px;\n\tcolor: white;\n\tpadding: 10px;\n\tborder: 1px solid #711a11;\n\tborder-radius: 3px;\n}\n\nFirstRunWizard QAbstractButton#next:hover,\nFirstRunWizard QAbstractButton#finish:hover {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #e34729, stop:1 #b23d21);\n}\n\nFirstRunWizard QAbstractButton#next:pressed,\nFirstRunWizard QAbstractButton#finish:pressed {\n\tbackground-color: #9f2a1d;\n}\n\n/* QWizard::BackButton */\n/* QWizard::CancelButton */\n/* QWizard::HelpButton */\n/* QWizard::CustomButton1 */\nFirstRunWizard QAbstractButton#custom {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #b8b8b8, stop:1 #a3a3a3);\n\tfont-size: 14px;\n\tcolor: white;\n\tpadding: 10px;\n\tborder: 1px solid #888;\n\tborder-radius: 3px;\n}\n\nFirstRunWizard QAbstractButton#custom:hover {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #cdcdcd, stop:1 #b6b6b6);\n}\n\t\nFirstRunWizard QAbstractButton#custom:pressed {\n\tbackground-color: #a2a2a2;\n}\n\nLoginPage QLabel#image { qproperty-pixmap: url(\":/graphic_connect.png\"); }\nAccessPage QLabel#image { qproperty-pixmap: url(\":/graphic_access.png\"); }\nPluginsPage QLabel#image { qproperty-pixmap: url(\":/graphic_plugins.png\"); }\nPluginsInstallPage QLabel#image { qproperty-pixmap: url(\":/graphic_plugins.png\"); }\nPluginsBootstrapPage QLabel#image { qproperty-pixmap: url(\":/graphic_connect.png\"); }\nPluginsBootstrapProgressPage QLabel#image { qproperty-pixmap: url(\":/graphic_connect.png\"); }\nTourScrobblesPage QLabel#image { qproperty-pixmap: url(\":/graphic_scrobbles.png\"); }\nTourMetadataPage QLabel#image { qproperty-pixmap: url(\":/graphic_metadata.png\"); }\nTourRadioPage QLabel#image { qproperty-pixmap: url(\":/graphic_radio.png\"); }\nTourLocationPage QLabel#image { qproperty-pixmap: url(\":/graphic_access.png\"); }\nTourFinishPage QLabel#image { qproperty-pixmap: url(\":/graphic_finish.png\"); }\n\nPluginsPage QCheckBox,\nBootstrapPage QRadioButton { qproperty-iconSize: 44px; }\nPluginsPage QCheckBox#itw,\nBootstrapPage QRadioButton#itw { qproperty-icon: url(\":/player_itunes_64.png\"); }\nPluginsPage QCheckBox#wa2,\nBootstrapPage QRadioButton#wa2 { qproperty-icon: url(\":/player_winamp_64.png\"); }\nPluginsPage QCheckBox#wmp,\nBootstrapPage QRadioButton#wmp { qproperty-icon: url(\":/player_wmp_64.png\"); }\nPluginsPage QCheckBox#foo3,\nBootstrapPage QRadioButton#foo3 { qproperty-icon: url(\":/player_foobar_64.png\"); }\n\n\nMessageBar {\n\tborder: none;\n}\n\nMessageBar {\n  background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #E4F1FF, stop:1 #C3CEDA);\n  border-bottom: 1px solid #3A3D41;\n}\n\nMessageBar#radio {\n  background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #FFF7CA, stop:1 #DAD3AD);  \n  border-bottom: 1px solid #413F33;\n}\n\nMessageBar QLabel#icon {\n  background-repeat: none;\n  background-color: transparent;\n  background-repeat: no-repeat;\n  background-position: center;\n  color: transparent;\n  min-width: 19px;\n  min-height: 19px;\n}\n\nMessageBar QLabel#icon {\n  background-image: url(\":/message_info.png\");\n}\n\nMessageBar#radio QLabel#icon {\n  background-image: url(\":/message_error.png\");\n}\n\nMessageBar QPushButton#close {\n  background-repeat: none;\n  background-color: transparent;\n  background-repeat: no-repeat;\n  background-position: center;\n  color: transparent;\n  background-image: url(\":/message_close.png\");\n  min-width: 17px;\n  min-height: 17px;\n}\n\nSideBar {\n\tborder: none;\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:1, y2:0, stop:0 #2d2d2d, stop:0.925 #2d2d2d, stop:1 #232323);\n\tpadding: 0px;\n\tmargin: 0px;\n\tmin-width: 76px;\n}\n\nSideBar QAbstractButton {\n\ttext-align: bottom;\n\tbackground-color: transparent;\n\tbackground-repeat: no-repeat;\n\tbackground-position: center;\n\tfont-size: 11px;\n\tcolor: #888888;\n\tborder: none;\n\theight: 67px;\n\twidth: 70px;\n\tpadding-bottom: 13px;\n\t/* the height and bottom-padding should add up to 80px */\n}\n\nSideBar QAbstractButton:hover,\nSideBar QAbstractButton:checked {\ncolor: #ffffff;\n}\n\nSideBar QAbstractButton#nowPlaying {\nbackground-image: url(\":/tab_now_playing_REST.png\");\n}\nSideBar QAbstractButton#nowPlaying:hover {\nbackground-image: url(\":/tab_now_playing_HOVER.png\");\n}\nSideBar QAbstractButton#nowPlaying:checked {\nbackground-image: url(\":/tab_now_playing_ACTIVE.png\");\n}\n\nSideBar QAbstractButton#scrobbles {\nbackground-image: url(\":/tab_scrobbles_REST.png\");\n}\nSideBar QAbstractButton#scrobbles:hover {\nbackground-image: url(\":/tab_scrobbles_HOVER.png\");\n}\nSideBar QAbstractButton#scrobbles:checked {\nbackground-image: url(\":/tab_scrobbles_ACTIVE.png\");\n}\n\nSideBar QAbstractButton#profile {\nbackground-image: url(\":/tab_profile_REST.png\");\n}\nSideBar QAbstractButton#profile:hover {\nbackground-image: url(\":/tab_profile_HOVER.png\");\n}\nSideBar QAbstractButton#profile:checked {\nbackground-image: url(\":/tab_profile_ACTIVE.png\");\n}\n\nSideBar QAbstractButton#friends {\nbackground-image: url(\":/tab_friends_REST.png\");\n}\nSideBar QAbstractButton#friends:hover {\nbackground-image: url(\":/tab_friends_HOVER.png\");\n}\nSideBar QAbstractButton#friends:checked {\nbackground-image: url(\":/tab_friends_ACTIVE.png\");\n}\n\nSideBar QAbstractButton#radio {\nbackground-image: url(\":/tab_radio_REST.png\");\n}\nSideBar QAbstractButton#radio:hover {\nbackground-image: url(\":/tab_radio_HOVER.png\");\n}\nSideBar QAbstractButton#radio:checked {\nbackground-image: url(\":/tab_radio_ACTIVE.png\");\n}\n\nQFrame#splitter1,\nQFrame#splitter2,\nQFrame#splitter3,\nQFrame#splitter4,\nQFrame#splitter5 {\n\tborder: none;\n\tborder-right: 1px solid white;\n\tborder-left: 1px solid #cdcdcd;\n\tmin-width: 0px;\n\tmax-width: 0px;\n\tmargin: 0px 20px;\n}\n\nQFrame#volumeSplitter1,\nQFrame#volumeSplitter2 {\n\tborder: none;\n\tborder-right: 1px solid #eee;\n\tborder-left: 1px solid #bbb;\n\tmin-width: 0px;\n\tmax-width: 0px;\n\tmargin: 0px 20px;\n}\n\nPlaybackControlsWidget QFrame#progressFrame QFrame#volumeSplitter1,\nPlaybackControlsWidget QFrame#progressFrame QFrame#volumeSplitter2 {\n\tmargin: 0px;\n}\n\nPlaybackControlsWidget QPushButton#volume {\n\tpadding: 0px 3px;\n}\n\n\nQFrame#splitter,\nQFrame#hsplitter1,\nQFrame#hsplitter2 {\n\tborder: none;\n\tborder-bottom: 1px solid white;\n\tborder-top: 1px solid #cdcdcd;\n\tmin-height: 0px;\n\tmax-height: 0px;\n\tmargin: 10px 0px;\n}\n\nMetadataWidget QFrame#hsplitter1,\nMetadataWidget QFrame#hsplitter2 {\n\tmargin: 0px;\n}\n\nNothingPlayingWidget {\n\tborder: none;\n}\n\nNothingPlayingWidget QLabel {\ncolor: #333;\nfont-size: 12px;\n}\n\nNothingPlayingWidget QFrame#contents {\n\tborder: none;\n\tbackground-image: url(\":/start_bg.png\");\n\tbackground-repeat: none;\n\tpadding: 20px;\n\tmargin: 0px;\n}\n\nNothingPlayingWidget QLabel#start {\n\tfont-size: 16px;\n\tfont-weight: bold;\n}\n\nNothingPlayingWidget QLabel#top {\n\tcolor: #333;\n\tfont-size: 12px;\n\tfont-weight: bold;\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #dbdbdb, stop:1 #c1c1c1);\n\tborder: none;\n\tborder-bottom: 1px solid #989898;\n\tmin-height: 38px;\n\tmargin: 0px;\n\tpadding-left: 20px;\n}\n\nNothingPlayingWidget QLabel#scrobble {\n\tmargin: 10px 0px 20px;\n}\n\nNothingPlayingWidget QAbstractButton#itunes,\nNothingPlayingWidget QAbstractButton#applemusic,\nNothingPlayingWidget QAbstractButton#wmp,\nNothingPlayingWidget QAbstractButton#winamp,\nNothingPlayingWidget QAbstractButton#foobar {\nbackground-color: transparent;\nbackground-repeat: no-repeat;\nbackground-position: left;\ntext-align: center left;\nborder: none;\nheight: 44px;\nwidth: 44px;\nmargin: 0px;\npadding-left: 50px;\n}\n\nNothingPlayingWidget QAbstractButton#itunes {\nbackground-image: url(\":/control_bar_scrobble_itunes.png\");\n}\n\nNothingPlayingWidget QAbstractButton#applemusic {\nbackground-image: url(\":/control_bar_scrobble_applemusic.png\");\n}\n\nNothingPlayingWidget QAbstractButton#wmp {\nbackground-image: url(\":/control_bar_scrobble_wmp.png\");\n}\n\nNothingPlayingWidget QAbstractButton#winamp {\nbackground-image: url(\":/control_bar_scrobble_winamp.png\");\n}\n\nNothingPlayingWidget QAbstractButton#foobar {\nbackground-image: url(\":/control_bar_scrobble_foobar.png\");\n}\n\nMetadataWidget QLabel#context {\nmargin: 20px 20px;\npadding: 15px 15px;\nbackground-color: #ffffff;\nborder: 1px solid #cdcdcd;\nborder-radius: 5px;\nfont-size: 12px;\n}\n\nProfileWidget QLabel#userBlurb {\nmargin: 12px 0px;\npadding: 15px 15px;\nbackground-color: #ffffff;\nborder: 1px solid #cdcdcd;\nborder-radius: 5px;\nfont-size: 12px;\n}\n\nQuickStartWidget {\nborder: none;\nmargin: 14px 0px 10px 0px;\n}\n\nMetadataWidget {\nborder: none;\n}\n\nMetadataWidget  QFrame#scrollAreaWidgetContents {\nborder: none;\n}\n\nMetadataWidget QPushButton#back {\nbackground-image: url(\":/control_bar_back.png\");\nbackground-repeat: none;\nbackground-position: center left;\nbackground-origin: padding;\ncolor: #333;\nfont-size: 12px;\ntext-align: center left;\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #dbdbdb, stop:1 #c1c1c1);\nborder: none;\nborder-bottom: 1px solid #989898;\nborder-left: 20px solid transparent;\nmin-height: 38px;\nmax-height: 38px;\npadding: 0px 0px 0px 25px;\n}\n\nMetadataWidget QFrame#trackDetails {\n\tborder: none;\n\tmargin: 20px 20px 0px 20px;\n}\n\nMetadataWidget HttpImageWidget#albumImage {\ncolor: transparent;\nbackground-color: white;\nqproperty-scaledContents: true;\nborder: 1px solid #aaaaaa;\nmin-width: 126px;\nmin-height: 126px;\nmax-width: 126px;\nmax-height: 126px;\npadding: 4px;\nmargin-right: 20px;\n}\n\t\nMetadataWidget QLabel#trackTitle {\ncolor: #333;\nfont-size: 16px;\nfont-weight: bold;\n}\n\nMetadataWidget QLabel#trackArtist {\ncolor: #333;\n}\n\nMetadataWidget ScrobbleControls {\nborder: none;\n}\n\nMetadataWidget QLabel#trackAlbum {\nfont-size: 12px;\n}\n\nMetadataWidget QFrame#trackTagsFrame {\n\tmargin: 0px 25px 10px;\n}\n\nMetadataWidget QFrame#artistTagsFrame {\n\tmargin: 0px 5px 10px;\n}\n\nMetadataWidget QLabel#trackPopTags,\nMetadataWidget QLabel#artistPopTags,\nMetadataWidget QLabel#trackYourTags,\nMetadataWidget QLabel#artistYourTags {\nfont-size: 11px;\n}\n\nMetadataWidget QLabel#similarArtists {\nfont-size: 16px;\nfont-weight: bold;\npadding: 0px 2px 10px;\nborder: none;\n}\n\nMetadataWidget QFrame#artistStats {\npadding: 20px 40px 20px 5px;\n}\n\nMetadataWidget QLabel#trackPlays,\nMetadataWidget QLabel#trackListeners,\nMetadataWidget QLabel#trackUserPlays,\nMetadataWidget QLabel#artistPlays,\nMetadataWidget QLabel#artistListeners,\nMetadataWidget QLabel#artistUserPlays {\ncolor: #333;\nfont-size: 16px;\nfont-weight: bold;\n}\n\nMetadataWidget QLabel#trackPlaysLabel,\nMetadataWidget QLabel#trackListenersLabel,\nMetadataWidget QLabel#trackUserPlaysLabel,\nMetadataWidget QLabel#artistPlaysLabel,\nMetadataWidget QLabel#artistListenersLabel,\nMetadataWidget QLabel#artistUserPlaysLabel {\ncolor: #898989;\nfont-size: 10px;\nfont-weight: normal;\n}\n\nMetadataWidget QFrame#content {\n\tbackground-color: red;\n}\n\nMetadataWidget QFrame#artistFrame {\n\tbackground-color: #dedede;\n\tpadding: 20px 20px 20px;\n\tmargin: 0px;\n}\n\nMetadataWidget QLabel#artistArtist {\nfont-size: 16px;\nfont-weight: bold;\ncolor: #333;\npadding: 0px 0px 5px;\n}\n\nMetadataWidget BioWidget#artistBio {\nbackground-color: #dedede;\nborder: none;\nfont-size: 12px;\ncolor: #333;\n}\n\nMetadataWidget QFrame#similarArtistFrame {\n\tmargin-right: 20px;\n}\n\nMetadataWidget QFrame#similarArtistFrame QLabel {\npadding: 2px;\nborder: 1px solid #aaaaaa;\nbackground-color: white;\nmargin: 0px 10px 30px;\ncolor: #333;\ntext-align: bottom left;\nfont-size: 10px;\nbackground-origin: margin;\nmin-width: 64px;\nmax-width: 64px;\nmax-height: 64px;\nmax-height: 64px;\n}\n\nMetadataWidget PlayableItemWidget {\ncolor: white;\nbackground-color: transparent;\nmin-height: 49px;\nmax-height: 49px;\nqproperty-style: ThreePart;\n}\n\nScrobblesListWidget {\nborder: none;\n}\n\nScrobblesWidget #noScrobbles {\nborder: none;\n}\n\nScrobblesWidget #noScrobbles QLabel {\ncolor: #333;\n}\n\nScrobblesWidget #noScrobbles QLabel#title {\nfont-weight: bold;\nfont-size: 16px;\n}\n\nScrobblesWidget #noScrobbles QLabel#description {\nfont-size: 12px;\n}\n\n\nRefreshButton,\nQPushButton#more {\nbackground-position: center left;\nbackground-repeat: none;\npadding: 0px 10%;\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #eeeeee, stop:1 #e2e2e2);\ncolor: #777;\nborder: none;\nborder-bottom: 1px solid #a6a6a6;\nmin-height: 38px;\nmax-height: 38px;\n}\n\nRefreshButton:hover,\nQPushButton#more:hover {\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #fcfcfc, stop:1 #e5e5e5);\n}\n\nRefreshButton:pressed,\nQPushButton#more:pressed {\nbackground-color: #d6d6d6;\n}\n\nTrackWidget {\n\tborder: none;\n\tborder-top: 1px solid white;\n\tborder-bottom: 1px solid #aaa;\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #eeeeee, stop:1 #dddddd);\n}\n\nTrackWidget QFrame#frame {\n\tborder: none;\n\tpadding: 10px 20px;\n}\n\nTrackWidget:hover {\n\tbackground-color: #eeeeee;\n}\n\nTrackWidget:pressed {\n\t\tborder-top: 1px solid #d6d6d6;\n\t\tbackground-color: #d6d6d6;\n}\n\nTrackWidget#nowPlaying {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #f2efc0, stop:1 #fffcca);\n}\n\nTrackWidget#nowPlaying:hover {\n\tbackground-color: #fffcca;\n}\n\nTrackWidget QLabel#trackTitle {\n\tfont-weight: bold;\n\tfont-size: 13px;\n}\n\nTrackWidget QLabel#artist {\n\tfont-size: 13px;\n}\n\nTrackWidget QLabel#timestamp {\n\tfont-size: 11px;\n}\n\nTrackWidget QPushButton#love,\nTrackWidget QPushButton#tag,\nTrackWidget QPushButton#share,\nTrackWidget QPushButton#buy {\n\tcolor: transparent;\n\tborder: none;\n\tbackground-repeat: no-repeat;\n\tbackground-color: transparent;\n\tmargin: 1px 0px 0px 0px;\n}\n\nTrackWidget QPushButton#love {\n\tbackground-image: url(\":/meta_love_OFF_REST.png\");\n\twidth: 21px;\n\theight: 18px;\n}\nTrackWidget QPushButton#love:hover { background-image: url(\":/meta_love_OFF_HOVER.png\"); }\nTrackWidget QPushButton#love:pressed { background-image: url(\":/meta_love_OFF_PRESS.png\"); }\nTrackWidget QPushButton#love:checked { background-image: url(\":/meta_love_ON_REST.png\"); }\nTrackWidget QPushButton#love:checked:hover { background-image: url(\":/meta_love_ON_HOVER.png\"); }\nTrackWidget QPushButton#love:checked:pressed { background-image: url(\":/meta_love_ON_PRESS.png\"); }\n\nTrackWidget QPushButton#tag {\n\tbackground-image: url(\":/meta_tag_REST.png\");\n\twidth: 18px;\n\theight: 18px;\n}\nTrackWidget QPushButton#tag:hover { background-image: url(\":/meta_tag_HOVER.png\"); }\nTrackWidget QPushButton#tag:pressed { background-image: url(\":/meta_tag_PRESS.png\"); }\n\nTrackWidget QPushButton#share {\n\tbackground-image: url(\":/meta_share_REST.png\");\n\twidth: 21px;\n\theight: 18px;\n}\nTrackWidget QPushButton#share:hover { background-image: url(\":/meta_share_HOVER.png\"); }\nTrackWidget QPushButton#share:pressed { background-image: url(\":/meta_share_PRESS.png\"); }\n\nTrackWidget QPushButton#buy {\n\tbackground-image: url(\":/meta_buy_REST.png\");\n\twidth: 21px;\n\theight: 18px;\n}\nTrackWidget QPushButton#buy:hover { background-image: url(\":/meta_buy_HOVER.png\"); }\nTrackWidget QPushButton#buy:pressed { background-image: url(\":/meta_buy_PRESS.png\"); }\nTrackWidget QPushButton#buy::menu-indicator { image: none; }\n\nFriendListWidget QListWidget {\nbackground-color: #eeeeee;\nborder: none;\n}\n\nFriendListWidget QListWidget::item {\nborder: none;\n}\n\nFriendListWidget QListWidget::item:first {\nborder: none;\n}\n\nFriendListWidget QListWidget::item:last {\nborder: none;\n}\n\nFriendListWidget QWidget#filterBackground {\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #dbdbdb, stop:1 #c1c1c1);\nborder-bottom: 1px solid #989898;\n}\n\nFriendListWidget QLineEdit {\nmargin: 16px;\nborder: 1px solid #989898;\nborder-radius: 5px;\npadding: 5px;\nselection-background-color: darkgray;\nfont-size: 14px;\n}\n\nFriendListWidget QListView::item:selected {\n  background-color: #dddddd;\n}\n\nScrobbleConfirmationDialog QLabel#invalidScrobbleWarning {\n\tcolor: red;\n}\n\nQuickStartWidget QLineEdit {\nborder: 1px solid #cdcdcd;\nborder-radius: 5px;\npadding: 10px 10px;\nselection-background-color: darkgray;\nfont-size: 17px;\n}\n\nQuickStartWidget QPushButton {\nbackground-image: url(\":/radio_play_large_REST.png\");\nbackground-color: transparent;\nbackground-repeat: no-repeat;\ncolor: transparent;\nborder: none;\nheight: 58px;\nwidth: 58px;\nmargin: 0px 0px 0px 10px;\n}\n\nQuickStartWidget QPushButton:hover { background-image: url(\":/radio_play_large_HOVER.png\"); }\nQuickStartWidget QPushButton:pressed { background-image: url(\":/radio_play_large_PRESS.png\"); }\n\nQuickStartWidget QLabel#whyNotTry {\n\tmargin: 2px 0px 2px 1px;\n\tfont-size: 12px;\n}\n\nQScrollArea {\nborder: none;\n}\n\nProfileWidget {\nborder: none;\nmargin: 0px 20px;\n}\n\nRadioWidget QFrame#section {\nborder: none;\n}\n\nProfileWidget QFrame#user {\nborder: none;\nmargin: 20px 0px 10px;\n}\n\nFriendWidget {\nmargin: 0px 20px;\npadding: 10px 0px;\nborder: none;\nborder-top: 1px solid white;\nborder-bottom: 1px solid #cdcdcd;\n}\n\nFriendWidget QFrame#nowListening,\nFriendWidget QFrame#groupBox {\n\tborder: 1px solid lightgray;\n\tborder-radius: 5px;\n\tpadding: 6px 10px;\n}\n\nFriendWidget QFrame#nowListening {\n\tbackground-color: #fffcca;\n}\n\nFriendWidget QFrame#groupBox {\n\tbackground-color: #dedede;\n}\n\nFriendWidget AvatarWidget#avatar,\nProfileWidget AvatarWidget#avatar,\nProfileArtistWidget QLabel#artistImage,\nShareDialog HttpImageWidget#icon,\nTagDialog HttpImageWidget#icon,\nUserManagerWidget AvatarWidget#image,\nTrackWidget HttpImageWidget#albumArt{\npadding: 2px;\nbackground-color: white;\ncolor: transparent;\nborder: 1px solid #aaaaaa;\nmin-width: 64px;\nmin-height: 64px;\nmax-width: 64px;\nmax-height: 64px;\nmargin: 0px 20px 8px 0px;\n}\n\nTrackWidget HttpImageWidget#albumArt {\nmargin: 0px 10px 0px 0px;\n}\n\nProfileWidget AvatarWidget#avatar {\n\tpadding: 4px;\n\tmin-width: 126px;\n\tmin-height: 126px;\n\tmax-width: 126px;\n\tmax-height: 126px;\n}\n\nProfileArtistWidget QLabel#artistImage {\n\tmax-height: 52px;\n\tmin-height: 52px;\n}\n\nFriendWidget QLabel#lastTrack {\n\tfont-weight: bold;\n\tfont-size: 12px;\n\tcolor: #333;\n}\n\nProfileWidget QLabel#name {\n\tfont-size: 16px;\n\tcolor: #333;\n}\n\n\nProfileWidget QLabel#scrobbleCount,\nProfileWidget QLabel#lovedCount {\n\tfont-size: 14px;\n\tcolor: #333;\n}\n\nProfileWidget QLabel#scrobbles,\nProfileWidget QLabel#loved,\nProfileWidget QLabel#infoString {\n\tfont-size: 11px;\n\tcolor: #898989;\n}\n\n\nFriendWidget QLabel#username {\nfont-weight: bold;\nfont-size: 14px;\ncolor: #333;\n}\n\nFriendWidget QLabel#userDetails {\nfont-size: 11px;\ncolor: #898989;\n}\n\nFriendWidget QLabel#timestamp {\nfont-size: 11px;\ncolor: #333;\n}\n\nFriendListWidget QLabel#noFriends {\n\tcolor: #333;\n}\n\nFriendListWidget QWidget#noFriendsPage {\n\tborder: none;\n\tmargin: 20px;\n}\n\nFriendListWidget PushButton {\ncolor: #333;\ntext-align: center center;\nfont-weight: bold;\nbackground-color: transparent;\nmin-height: 49px;\nmax-height: 49px;\n}\n\nFriendWidget QLabel#equaliser,\nTrackWidget QLabel#equaliser {\nmargin-right: 5px;\n}\n\nRadioWidget {\nborder: none;\nmargin: 0px 20px;\n}\n\nRadioWidget PlayableItemWidget,\nFriendWidget PlayableItemWidget,\nProfileWidget PlayableItemWidget {\nbackground-color: transparent;\nbackground-repeat: no-repeat;\nborder: none;\ntext-align: top left;\nfont-weight: bold;\nfont-size: 14px;\ncolor: #333;\nheight: 40px;\npadding: 3px 0px 3px 54px;\nmargin: 5px 0px;\n}\n\nProfileArtistWidget {\n  border: none;\n  margin: 10px 0px;\n}\n\nProfileArtistWidget QLabel#artistImage {\n  margin: 0px 20px 0px 0px;\n}\n\nProfileArtistWidget QLabel#artistName {\n  color: #333;\n  font-size: 14px;\n  font-weight: bold;\n}\n\nProfileArtistWidget QLabel#plays {\n  color: white;\n  font-size: 11px;\n  font-weight: bold;\n  min-height: 20px;\n  max-height: 20px;\n  padding-left: 5px;\n}\n\nRadioWidget PlayableItemWidget#library {\nbackground-image: url(\":/radio_library_REST.png\");\n}\nRadioWidget PlayableItemWidget#library:hover {\nbackground-image: url(\":/radio_library_HOVER.png\");\n}\nRadioWidget PlayableItemWidget#library:pressed {\nbackground-image: url(\":/radio_library_PRESS.png\");\n}\n\t\t\nRadioWidget PlayableItemWidget#mix {\nbackground-image: url(\":/radio_mix_REST.png\");\n}\nRadioWidget PlayableItemWidget#mix:hover {\nbackground-image: url(\":/radio_mix_HOVER.png\");\n}\nRadioWidget PlayableItemWidget#mix:pressed {\nbackground-image: url(\":/radio_mix_PRESS.png\");\n}\n\t\t\nRadioWidget PlayableItemWidget#rec {\nbackground-image: url(\":/radio_rec_REST.png\");\n}\nRadioWidget PlayableItemWidget#rec:hover {\nbackground-image: url(\":/radio_rec_HOVER.png\");\n}\nRadioWidget PlayableItemWidget#rec:pressed {\nbackground-image: url(\":/radio_rec_PRESS.png\");\n}\n\t\t\nRadioWidget PlayableItemWidget#friends,\nRadioWidget PlayableItemWidget#neighbours {\nbackground-image: url(\":/radio_friends_REST.png\");\n}\nRadioWidget PlayableItemWidget#friends:hover,\nRadioWidget PlayableItemWidget#neighbours:hover {\nbackground-image: url(\":/radio_friends_HOVER.png\");\n}\nRadioWidget PlayableItemWidget#friends:pressed,\nRadioWidget PlayableItemWidget#neighbours:pressed {\nbackground-image: url(\":/radio_friends_PRESS.png\");\n}\n\nRadioWidget PlayableItemWidget#station,\nFriendWidget PlayableItemWidget,\nProfileWidget PlayableItemWidget {\n\tbackground-image: url(\":/radio_play_small_REST.png\");\n\tfont-size: 12px;\n\tmax-height: 24px;\n\tmargin: 0px;\n\tpadding: 0px;\n}\n\nRadioWidget PlayableItemWidget#station {\n\tqproperty-style: DescriptionElide;\n\tpadding-left: 30px;\n\ttext-align: left center;\n}\n\nFriendWidget PlayableItemWidget,\nProfileWidget PlayableItemWidget {\n\tqproperty-style: DescriptionNone;\n\tcolor: transparent;\n\tmax-width: 24px;\n}\n\nRadioWidget PlayableItemWidget#station:hover,\nFriendWidget PlayableItemWidget:hover,\nProfileWidget PlayableItemWidget:hover {\nbackground-image: url(\":/radio_play_small_HOVER.png\");\n}\nRadioWidget PlayableItemWidget#station:pressed,\nFriendWidget PlayableItemWidget:pressed,\nProfileWidget PlayableItemWidget :pressed {\nbackground-image: url(\":/radio_play_small_PRESS.png\");\n}\n\nRadioWidget QLabel#title,\nProfileWidget QLabel#weekTitle,\nProfileWidget QLabel#overallTitle {\ncolor: #333;\npadding: 0px 0px 10px;\nborder: none;\nfont-weight: bold;\nfont-size: 15px;\n}\n\nRadioWidget QFrame#nonSubFrame {\n\tpadding: 20px 10px 0px;\n\tbackground-repeat: none;\n\tbackground-image: url(\":/subscribe_bg.png\");\n\tbackground-position: center top;\n}\n\nRadioWidget QFrame#nonSubFrame QLabel#title {\n\tcolor: #333;\n\tfont-size: 18px;\n}\n\nRadioWidget QLabel#headphones {\n\tcolor: transparent;\n\tbackground-repeat: none;\n\tbackground-image: url(\":/subscribe_radio.png\");\n\tmin-width: 218px;\n\tmin-height: 144px;\n\tmargin: 20px 0px 30px;\n}\n\nRadioWidget QLabel#description {\n\tcolor: #333;\n\tfont-weight: bold;\n\tfont-size: 13px;\n\tmargin-bottom: 20px;\n}\n\nRadioWidget PushButton {\ncolor: #333;\ntext-align: center center;\nfont-weight: bold;\nfont-size: 14px;\nbackground-color: transparent;\nmin-height: 49px;\nmax-height: 49px;\n}\n\nRadioWidget PushButton#subscribe {\n\tcolor: #fff;\n\tqproperty-dark: true;\n}\n\nPlaybackControlsWidget {\nborder: none;\n}\n\nPlaybackControlsWidget QLabel#icon {\ncolor: transparent;\nmin-width: 44px;\nmin-height: 44px;\nmargin: 0px 14px;\nqproperty-alignment: AlignCenter;\n}\n\nPlaybackControlsWidget QFrame#statusFrame {\npadding: 13px 0px;\n}\n\nPlaybackControlsWidget QFrame#statusFrame QLabel {\ncolor: white;\nfont-size: 12px;\n}\n\nPlaybackControlsWidget QFrame#statusFrame QLabel#device {\nfont-weight: bold;\nfont-size: 14px;\n}\n\nPlaybackControlsWidget[scrobbleTrack=\"false\"] QFrame#details {\n\tmax-height: 64px;\n\tmin-height: 64px;\n}\n\nPlaybackControlsWidget[scrobbleTrack=\"false\"] QFrame#details {\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:1 #3B3B3B, stop:0 #545454);\nborder: none;\nborder-bottom: 1px solid #272727;\n\n}\n\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QFrame#details {\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:1 #c1c1c1, stop:0 #dbdbdb);\nborder: none;\nborder-bottom: 1px solid #9f9f9f;\n}\n\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QFrame#statusFrame QLabel {\ncolor: #333;\n}\n\nPlaybackControlsWidget QFrame#buttons {\n\tmargin: 0px 20px 0px 0px;\n}\n\nPlaybackControlsWidget QPushButton {\nbackground-color: transparent;\nbackground-repeat: no-repeat;\nborder: none;\ncolor: transparent;\nheight: 28px;\n}\n\nPlaybackControlsWidget QPushButton#love {\nbackground-image: url(\":/controls_love_OFF_REST.png\");\nmax-width: 29px;\nmin-width: 29px;\n}\n\nPlaybackControlsWidget QPushButton#love:hover {background-image: url(\":/controls_love_OFF_HOVER.png\");}\nPlaybackControlsWidget QPushButton#love:pressed {background-image: url(\":/controls_love_OFF_PRESS.png\");}\nPlaybackControlsWidget QPushButton#love:checked {background-image: url(\":/controls_love_ON_REST.png\");}\nPlaybackControlsWidget QPushButton#love:checked:hover {background-image: url(\":/controls_love_ON_HOVER.png\");}\nPlaybackControlsWidget QPushButton#love:checked:pressed {background-image: url(\":/controls_love_ON_PRESS.png\");}\n\t\t\nPlaybackControlsWidget QPushButton#ban {\nbackground-image: url(\":/controls_ban_REST.png\");\nmax-width: 28px;\nmin-width: 28px;\n}\nPlaybackControlsWidget QPushButton#ban:hover {background-image: url(\":/controls_ban_HOVER.png\");}\nPlaybackControlsWidget QPushButton#ban:pressed {background-image: url(\":/controls_ban_PRESS.png\");}\n\t\t\nPlaybackControlsWidget QPushButton#play {\nbackground-image: url(\":/controls_play_REST.png\");\nmax-width: 25px;\nmin-width: 25px;\n}\nPlaybackControlsWidget QPushButton#play:hover {background-image: url(\":/controls_play_HOVER.png\");}\nPlaybackControlsWidget QPushButton#play:pressed {background-image: url(\":/controls_play_PRESS.png\");}\nPlaybackControlsWidget QPushButton#play:checked {background-image: url(\":/controls_pause_REST.png\");}\nPlaybackControlsWidget QPushButton#play:checked:hover {background-image: url(\":/controls_pause_HOVER.png\");}\nPlaybackControlsWidget QPushButton#play:checked:pressed {background-image: url(\":/controls_pause_PRESS.png\");}\n\t\t\nPlaybackControlsWidget QPushButton#skip {\nbackground-image: url(\":/controls_skip_REST.png\");\nmax-width: 39px;\nmin-width: 39px;\n}\nPlaybackControlsWidget QPushButton#skip:hover { background-image: url(\":/controls_skip_HOVER.png\"); }\nPlaybackControlsWidget QPushButton#skip:pressed { background-image: url(\":/controls_skip_PRESS.png\"); }\n\nPlaybackControlsWidget QPushButton#back {\nbackground-image: url(\":/controls_playlist_skip_back_REST.png\");\nmax-width: 39px;\nmin-width: 39px;\n}\nPlaybackControlsWidget QPushButton#back:hover { background-image: url(\":/controls_playlist_skip_back_HOVER.png\"); }\nPlaybackControlsWidget QPushButton#back:pressed { background-image: url(\":/controls_playlist_skip_back_PRESS.png\"); }\n\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love {background-image: url(\":/controls_playlist_love_OFF_REST.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love:hover {background-image: url(\":/controls_playlist_love_OFF_HOVER.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love:pressed {background-image: url(\":/controls_playlist_love_OFF_PRESS.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love:checked {background-image: url(\":/controls_playlist_love_ON_REST.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love:checked:hover {background-image: url(\":/controls_playlist_love_ON_HOVER.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#love:checked:pressed {background-image: url(\":/controls_playlist_love_ON_PRESS.png\");}\n\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play {background-image: url(\":/controls_playlist_play_REST.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play:hover {background-image: url(\":/controls_playlist_play_HOVER.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play:pressed {background-image: url(\":/controls_playlist_play_PRESS.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play:checked {background-image: url(\":/controls_playlist_pause_REST.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play:checked:hover {background-image: url(\":/controls_playlist_pause_HOVER.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#play:checked:pressed {background-image: url(\":/controls_playlist_pause_PRESS.png\");}\n\t\t\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#skip {background-image: url(\":/controls_playlist_skip_REST.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#skip:hover { background-image: url(\":/controls_playlist_skip_HOVER.png\"); }\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#skip:pressed { background-image: url(\":/controls_playlist_skip_PRESS.png\"); }\n\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#playlist {\n\tbackground-image: url(\":/controls_playlist_playlist_HOVER.png\");\n\tmax-width: 28px;\n\tmin-width: 28px;\n}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#playlist:hover {background-image: url(\":/controls_playlist_playlist_PRESS.png\");}\nPlaybackControlsWidget[scrobbleTrack=\"true\"] QPushButton#playlist:pressed {background-image: url(\":/controls_playlist_playlist_REST.png\");}\n\nPlaybackControlsWidget QFrame#progressFrame {\n\tborder: none;\n\tborder-top: 1px solid #e5e5e5;\n\tborder-bottom: 1px solid #9b9b9b;\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:1 #cccccc, stop:0 #e5e5e5);\n\tpadding: 0px 20px;\n\tmax-height: 24px;\n\tmin-height: 24px;\n}\n\nPlaybackControlsWidget QFrame#progressFrame QLabel#message,\nPlaybackControlsWidget QFrame#progressFrame QLabel#time {\n\tfont-size: 11px;\n\tcolor: #333;\n}\n\nScrobbleControls QPushButton {\nbackground-color: transparent;\ncolor: transparent;\nbackground-repeat: no-repeat;\nbackground-position: center;\nmargin: 0px;\npadding: 3px 0px;\nwidth: 20px;\n}\n\nScrobbleControls QPushButton#love {\nbackground-image: url(\":/meta_love_OFF_REST.png\");\n}\nScrobbleControls QPushButton#love:hover {\nbackground-image: url(\":/meta_love_OFF_HOVER.png\");\n}\nScrobbleControls QPushButton#love:pressed {\nbackground-image: url(\":/meta_love_OFF_PRESS.png\");\n}\nScrobbleControls QPushButton#love:checked {\nbackground-image: url(\":/meta_love_ON_REST.png\");\n}\nScrobbleControls QPushButton#love:checked:hover {\nbackground-image: url(\":/meta_love_ON_HOVER.png\");\n}\nScrobbleControls QPushButton#love:checked:pressed {\nbackground-image: url(\":/meta_love_ON_PRESS.png\");\n}\n\nScrobbleControls QPushButton#tag {\nbackground-image: url(\":/meta_tag_REST.png\");\n}\nScrobbleControls QPushButton#tag:hover {\nbackground-image: url(\":/meta_tag_HOVER.png\");\n}\nScrobbleControls QPushButton#tag:pressed {\nbackground-image: url(\":/meta_tag_PRESS.png\");\n}\n\nScrobbleControls QPushButton#share {\nbackground-image: url(\":/meta_share_REST.png\");\n}\nScrobbleControls QPushButton#share:menu-indicator {\nbackground: transparent;\n}\nScrobbleControls QPushButton#share:hover {\nbackground-image: url(\":/meta_share_HOVER.png\");\n}\nScrobbleControls QPushButton#share:pressed {\nbackground-image: url(\":/meta_share_PRESS.png\");\n}\n\nScrobbleControls QPushButton#buy {\nbackground-image: url(\":/meta_buy_REST.png\");\n}\nScrobbleControls QPushButton#buy:menu-indicator {\nbackground: transparent;\n}\nScrobbleControls QPushButton#buy:hover {\nbackground-image: url(\":/meta_buy_HOVER.png\");\n}\nScrobbleControls QPushButton#buy:pressed {\nbackground-image: url(\":/meta_buy_PRESS.png\");\n}\n\nBannerWidget {\nbackground-color: #dedede;\nmargin: 6px 7px 0px 3px;\n}\n\nBannerWidget HttpImageWidget {\n  border: 1px solid #aaaaaa;\n  background-color: white;\n  padding: 4px;\n}\n\nBannerWidgetPrivate {\nbackground-color: red;\ncolor: white;\nfont-size: 11px;\n}\n\nShareDialog QFrame#what,\nTagDialog QFrame#what {\nborder: 1px solid #DBDBDB;\nborder-radius: 5px;\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #ABABAB, stop:0.04 #E6E6E6, stop:1 #E6E6E6);\npadding: 18px;\nmargin: 18px 0px;\n}\n\nShareDialog > QRadioButton {\nmargin-left: 10px;\nfont-weight: bold;\n}\n\nShareDialog > QLabel,\nShareDialog > QCheckBox,\nShareDialog > QRadioButton,\nTagDialog > QLabel,\nTagDialog > QCheckBox,\nTagDialog > QRadioButton {\nfont-size: 12px;\nfont-weight: bold;\n}\n\nShareDialog QLabel#with {\nmargin-bottom: 10px;\nfont-size: 12px;\n}\n\nShareDialog QLabel#messageTitle {\nmargin-top: 16px;\nmargin-bottom: 10px;\n}\n\nItemSelectorWidget {\nbackground-color: white;\n}\n\nItemSelectorWidget QLineEdit {\npadding: 1px 2px 2px 3px;\nmargin: 2px;\n}\n\nItemSelectorWidget QLabel {\npadding: 2px 3px;\nmargin: 2px 0px 2px 2px;\nbackground-color: #DAE7F9;\nfont-weight: bold;\nborder: 1px solid #99BEEE;\nborder-radius: 9px;\nmin-width: 12px;\n}\n\nShareDialog QTextEdit {\nmargin-bottom: 16px;\n}\n\nShareDialog QLabel#characterLimit {\nfont-size: 11px;\nfont-weight: normal;\n}\n\nShareDialog QLabel#characterLimit[xerror=\"true\"] {\ncolor: red;\n}\n\nShareDialog QLabel#characterLimit,\nShareDialog QCheckBox {\nmargin-bottom: 16px;\n}\n\nStatusBar QFrame {\nborder: none;\nbackground-color: transparent;\nmargin: 1px 0px 2px;\n}\n\nStatusBar QPushButton#cog {\nborder: 1px solid #cdcdcd;\nborder-radius: 3px;\nbackground-repeat: no-repeat;\nbackground-position: center;\nbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #ffffff, stop:1 #e5e5e5);\nbackground-image: url(\":/settings_REST.png\");\nwidth: 30px;\nheight: 22px;\nmargin: 0px 10px;\n}\n\nStatusBar QPushButton#cog:hover {\nbackground-image: url(\":/settings_HOVER.png\");\n}\nStatusBar QPushButton#cog:pressed {\nbackground-image: url(\":/settings_PRESS.png\");\n}\n\nStatusBar QLabel#scrobbleIcon { qproperty-pixmap: url(\":/scrobble_OFF.png\"); }\n\nPlaybackControlsWidget QSlider {\n\tpadding: 0px 2px;\n}\n\nPlaybackControlsWidget VolumeSlider {\n\tbackground-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:1 #cccccc, stop:0 #e5e5e5);\n}\n\nPlaybackControlsWidget Phonon--VolumeSlider {\n\tmin-width: 60px;\n\tmax-width: 60px;\n\tbackground-image: none;\n\tbackground-repeat: none;\n\tqproperty-muteVisible: false;\n\theight: 16px;\n}\n\nPlaybackControlsWidget QSlider::groove:horizontal {\n\tpadding: 0px -7px;\n\theight: 16px;\n\tborder-image: url(\":/progress_slot_OFF.png\") 0px 3px 0px 3px stretch;\n\tborder-left-width: 3px;\n\tborder-right-width: 3px;\n}\n\nPlaybackControlsWidget QSlider::sub-page:horizontal {\n\tborder-image: url(\":/progress_slot_ON.png\") 0px 3px 0px 3px stretch;\n\tborder-left-width: 3px;\n\tborder-right-width: 3px;\n}\n\nPlaybackControlsWidget QProgressBar#progress {\n\tborder-image: url(\":/progress_slot_OFF.png\") 0px 3px 0px 3px stretch;\n\tborder-left-width: 3px;\n\tborder-right-width: 3px;\n\tpadding: 0px -3px;\n\tmax-height: 16px;\n}\n\nPlaybackControlsWidget QProgressBar#progress::chunk {\n\tborder-image: url(\":/progress_slot_ON.png\") 0px 3px 0px 3px stretch;\n\tborder-left-width: 3px;\n\tborder-right-width: 3px;\n}\n\nPlaybackControlsWidget QFrame#progressFrame QProgressBar#scrobbleMeter {\n\tbackground-image: url(\":/scrobble_progress_OFF.png\");\n\tbackground-repeat: none;\n\tbackground-color: transparent;\n\tbackground-position: inherit center;\n\tmin-height: 16px;\n\tmax-height: 16px;\n\twidth: 30px;\n\tborder: none;\n\tqproperty-textVisible: false;\n}\n\nPlaybackControlsWidget QFrame#progressFrame QProgressBar#scrobbleMeter:chunk {\n\tbackground-image: url(\":/scrobble_progress_ON.png\");\n\tmin-height: 16px;\n\tmax-height: 16px;\n\tbackground-repeat: none;\n}\n\nPlaybackControlsWidget QSlider::handle:horizontal {\nbackground-repeat: no-repeat;\nbackground-position: center;\nwidth: 16px;\nheight: 16px;\nbackground-image: url(\":/volume_knob_REST.png\");\n}\n\nPlaybackControlsWidget QSlider::handle:horizontal:pressed {\nbackground-image: url(\":/volume_knob_PRESS.png\");\n}\n\nStatusBar QFrame#permanentWidget {\nmargin: 0px 10px;\n}\n\nQDialog#AboutDialog QFrame#frame {\n\tmargin: 10px 20px 20px;\n}\n\nQDialog#AboutDialog QLabel {\n\tfont-size: 11px;\n}\n\nQDialog#AboutDialog QLabel#as {\n\tborder: none;\n\tbackground-repeat: no-repeat;\n\tbackground-position: center;\n\tqproperty-pixmap: url(\":/as.png\");\n\tqproperty-scaledContents: true;\n\tmax-height: 64px;\n\tmax-width: 64px;\n}\n\nIpodSettingsWidget unicorn--Label {\n\tfont-size: 12px;\n\tcolor: #333;\n}"
  },
  {
    "path": "app/client/MainWindow.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QLabel>\n#include <QPushButton>\n#include <QStackedWidget>\n#include <QStatusBar>\n#include <QSizeGrip>\n#include <QTimer>\n#include <QMenuBar>\n#include <QShortcut>\n#include <QToolBar>\n#include <QDockWidget>\n#include <QScrollArea>\n#include <QNetworkReply>\n\n#include \"MainWindow.h\"\n\n\n#include \"Application.h\"\n#include \"Services/ScrobbleService.h\"\n#include \"Services/AnalyticsService.h\"\n#include \"MediaDevices/DeviceScrobbler.h\"\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\n#include \"../Widgets/ProfileWidget.h\"\n#include \"../Widgets/FriendListWidget.h\"\n#include \"../Widgets/ScrobbleControls.h\"\n#include \"../Widgets/NowPlayingStackedWidget.h\"\n#include \"../Widgets/ScrobblesWidget.h\"\n#include \"../Widgets/SideBar.h\"\n#include \"../Widgets/StatusBar.h\"\n#include \"../Widgets/TitleBar.h\"\n#include \"../Widgets/PlaybackControlsWidget.h\"\n#include \"../Widgets/NowPlayingWidget.h\"\n#include \"lib/unicorn/widgets/DataBox.h\"\n#include \"lib/unicorn/widgets/MessageBar.h\"\n#include \"lib/unicorn/widgets/GhostWidget.h\"\n#include \"lib/unicorn/widgets/UserToolButton.h\"\n#include \"lib/unicorn/widgets/MessageBar.h\"\n#include \"lib/unicorn/widgets/UserMenu.h\"\n#include \"lib/unicorn/qtwin.h\"\n#include \"lib/unicorn/widgets/SlidingStackedWidget.h\"\n#include \"lib/listener/PlayerConnection.h\"\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n#include \"lib/unicorn/Updater/Updater.h\"\n#endif\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#ifdef Q_OS_WIN32\n#include \"lib/unicorn/plugins/PluginList.h\"\n#endif\n\n#ifdef Q_OS_MAC\nvoid qt_mac_set_dock_menu(QMenu *menu);\n#endif\n\nconst QString CONFIG_URL = \"https://cdn.last.fm/client/config.xml\";\n\nMainWindow::MainWindow( QMenuBar* menuBar )\n    :unicorn::MainWindow( menuBar )\n{\n    hide();\n\n#ifdef Q_OS_MAC\n    setUnifiedTitleAndToolBarOnMac( true );\n#else\n    setMenuBar( menuBar );\n#endif\n    \n    setCentralWidget(new QWidget);\n\n    QVBoxLayout* layout = new QVBoxLayout( centralWidget() );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 0 );\n\n    layout->addWidget( ui.messageBar = new MessageBar( this ) );\n\n    QHBoxLayout* h = new QHBoxLayout();\n    h->setContentsMargins( 0, 0, 0, 0 );\n    h->setSpacing( 0 );\n\n    layout->addLayout( h );\n\n    h->addWidget( ui.sideBar = new SideBar( this ) );\n\n    h->addWidget( ui.stackedWidget = new unicorn::SlidingStackedWidget( this ) );\n\n    connect( ui.sideBar, SIGNAL(currentChanged(int)), ui.stackedWidget, SLOT(slide(int)));\n\n    ui.stackedWidget->addWidget( ui.nowPlaying = new NowPlayingStackedWidget(this) );\n    ui.nowPlaying->setObjectName( \"nowPlaying\" );\n\n    ui.stackedWidget->addWidget( ui.scrobbles = new ScrobblesWidget( this ) );\n    ui.scrobbles->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::MinimumExpanding );\n\n    connect( ui.stackedWidget, SIGNAL(currentChanged(int)), ui.scrobbles, SLOT(onCurrentChanged(int)) );\n\n    ui.stackedWidget->addWidget( ui.profileScrollArea = new QScrollArea( this ) );\n    ui.profileScrollArea->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );\n    ui.profileScrollArea->setWidget( ui.profile = new ProfileWidget(this) );\n    ui.profileScrollArea->setWidgetResizable( true );\n    ui.profile->setObjectName( \"profile\" );\n\n    connect( ui.stackedWidget, SIGNAL(currentChanged(int)), ui.profile, SLOT(onCurrentChanged(int)) );\n\n    ui.stackedWidget->addWidget( ui.friends = new FriendListWidget(this) );\n    ui.friends->setObjectName( \"friends\" );\n\n    connect( ui.stackedWidget, SIGNAL(currentChanged(int)), ui.friends, SLOT(onCurrentChanged(int)) );\n\n\n    ui.statusBar = new StatusBar( this );\n    ui.statusBar->setObjectName( \"StatusBar\" );\n\n    ui.statusBar->setSizeGripEnabled( false );\n\n    setWindowTitle( applicationName() );\n    setUnifiedTitleAndToolBarOnMac( true );\n\n    connect( &ScrobbleService::instance(), SIGNAL( trackStarted(lastfm::Track, lastfm::Track) ), SLOT( onTrackStarted(lastfm::Track, lastfm::Track) ) );\n    connect( &ScrobbleService::instance(), SIGNAL( paused() ), SLOT( onPaused() ) );\n    connect( &ScrobbleService::instance(), SIGNAL( resumed() ), SLOT( onResumed() ) );\n    connect( &ScrobbleService::instance(), SIGNAL( stopped() ), SLOT( onStopped() ) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(foundIPodScrobbles(QList<lastfm::Track>)), SLOT(onFoundScrobbles(QList<lastfm::Track>)));\n\n    new QShortcut( Qt::Key_Space, this, SLOT(onSpace()) );\n\n    //for some reason some of the stylesheet is not being applied properly unless reloaded\n    //here. StyleSheets see very flaky to me. :s\n    aApp->refreshStyleSheet();\n\n    setMinimumWidth( 540 );\n    setMaximumWidth( 800 );\n\n    setStatusBar( ui.statusBar );\n\n    // This is the default window size it will get changed\n    // by finishUi if the app has ever been opened before\n    resize( 565, 710 );\n    finishUi();\n\n#ifdef Q_OS_WIN32\n    m_pluginList = new unicorn::PluginList( this );\n\n    QTimer::singleShot( 1000, this, SLOT(checkUpdatedPlugins()) );\n\n#endif\n\n    setupMenuBar();\n\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n    m_updater = new Updater( this );\n#endif\n\n#ifdef Q_OS_MAC\n    QMenu* dockMenu = new QMenu();\n    ui.nowPlaying->nowPlaying()->playbackControls()->addToMenu( *dockMenu  );\n    qt_mac_set_dock_menu( dockMenu );\n#endif\n\n    if (aApp->tray())\n    {\n        ui.nowPlaying->nowPlaying()->playbackControls()->addToMenu( *aApp->tray()->contextMenu(), aApp->tray()->contextMenu()->actions()[3] );\n    }\n\n    connect( lastfm::nam()->get( QNetworkRequest( CONFIG_URL ) ), SIGNAL(finished()), SLOT(onConfigRetrieved()) );\n}\n\nvoid\nMainWindow::showMessage( const QString& message, const QString& id, int timeout )\n{\n    ui.messageBar->show( message, id, timeout );\n}\n\nQString\nMainWindow::applicationName()\n{\n    return QCoreApplication::applicationName();\n}\n\n#ifdef Q_OS_WIN32\nvoid\nMainWindow::checkUpdatedPlugins()\n{\n    if ( m_pluginList->updatedList().count() > 0 )\n    {\n        // one of the plugins has been updated so ask if they want to install them\n\n        if ( QMessageBoxBuilder( this ).setText( tr( \"There are updates to your media player plugins. Would you like to install them now?\" ) )\n             .setTitle( \"Updates to media player plugins\" )\n             .setButtons( QMessageBox::Yes | QMessageBox::No )\n             .exec() == QMessageBox::Yes )\n        {\n            unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( m_pluginList->updatedList(), this );\n\n            if ( closeApps->result() != QDialog::Accepted )\n                closeApps->exec();\n            else\n                closeApps->deleteLater();\n\n            if ( closeApps->result() == QDialog::Accepted )\n            {\n                bool error = false;\n\n                foreach ( unicorn::IPluginInfo* info, m_pluginList->updatedList() )\n                {\n                    info->setVerbose( false );\n                    if ( !info->doInstall() )\n                        error = true;\n                    info->setVerbose( true );\n                }\n\n                if ( error )\n                {\n                    // Tell the user that\n                    QMessageBoxBuilder( this ).setTitle( tr( \"Plugin install error\", \"\", m_pluginList->updatedList().count() ) )\n                            .setIcon( QMessageBox::Information )\n                            .setText( tr( \"<p>There was an error updating your plugin(s).</p>\"\n                                          \"<p>Please try again later.</p>\", \"\", m_pluginList->updatedList().count() ) )\n                            .setButtons( QMessageBox::Ok )\n                            .exec();\n                }\n                else\n                {\n                    // Tell the user that\n                    QMessageBoxBuilder( this ).setTitle( tr( \"Plugin(s) installed!\", \"\", m_pluginList->updatedList().count() ) )\n                            .setIcon( QMessageBox::Information )\n                            .setText( tr( \"<p>Your plugin(s) ha(s|ve) been installed.</p>\"\n                                          \"<p>You're now ready to scrobble with your media player(s)</p>\", \"\", m_pluginList->updatedList().count() ) )\n                            .setButtons( QMessageBox::Ok )\n                            .exec();\n                }\n            }\n            else\n            {\n                // The user didn't close their media players\n                QMessageBoxBuilder( this ).setTitle( tr( \"Your plugins haven't been installed\" ) )\n                        .setIcon( QMessageBox::Warning )\n                        .setText( tr( \"You can install them later through the file menu\" ) )\n                        .setButtons( QMessageBox::Ok )\n                        .exec();\n            }\n        }\n    }\n}\n#endif\n\nQString MainWindow::currentCategory() const\n{\n    return ui.sideBar->currentCategory();\n}\n\nvoid\nMainWindow::setupMenuBar()\n{\n    /// File menu (should only show on non-mac)\n    QMenu* fileMenu = appMenuBar()->addMenu( tr( \"File\" ) );\n\n#ifdef Q_OS_WIN32\n    QMenu* pluginMenu = fileMenu->addMenu( tr( \"Install plugins\" ) );\n\n    foreach ( unicorn::IPluginInfo* info, m_pluginList->supportedList() )\n    {\n        info->setVerbose( true );\n        pluginMenu->addAction( info->name(), info, SLOT(doInstall()));\n    }\n#endif\n\n    QAction* quit = fileMenu->addAction( tr(\"&Quit\"), qApp, SLOT(quit()) );\n    quit->setMenuRole( QAction::QuitRole );\n#ifdef Q_OS_WIN\n    quit->setShortcut( Qt::ALT + Qt::Key_F4 );\n#else\n    quit->setShortcut( Qt::CTRL + Qt::Key_Q );\n#endif\n\n    /// View\n    QMenu* viewMenu = appMenuBar()->addMenu( tr(\"View\") );\n    ui.sideBar->addToMenu( *viewMenu );\n    viewMenu->addSeparator();\n    viewMenu->addAction( tr( \"My Last.fm Profile\" ), this, SLOT(onVisitProfile()), Qt::CTRL + Qt::Key_P );\n\n    /// Scrobbles\n    QMenu* scrobblesMenu = appMenuBar()->addMenu( tr(\"Scrobbles\") );\n    scrobblesMenu->addAction( tr( \"Refresh\" ), ui.scrobbles, SLOT(refresh()), Qt::CTRL + Qt::SHIFT + Qt::Key_R );\n\n    /// Controls\n    QMenu* controlsMenu = appMenuBar()->addMenu( tr(\"Controls\") );\n    ui.nowPlaying->nowPlaying()->playbackControls()->addToMenu( *controlsMenu  );\n\n    /// Account\n    appMenuBar()->addMenu( new UserMenu( this ) )->setText( tr( \"Account\" ) );\n\n    /// Tools (should only show on non-mac)\n    QMenu* toolsMenu = appMenuBar()->addMenu( tr(\"Tools\") );\n#ifndef Q_WS_X11\n    QAction* c4u = toolsMenu->addAction( tr(\"Check for Updates\"), this, SLOT(checkForUpdates()) );\n    c4u->setMenuRole( QAction::ApplicationSpecificRole );\n#endif\n    QAction* prefs = toolsMenu->addAction( tr(\"Options\"), this, SLOT(onPrefsTriggered()) );\n    prefs->setMenuRole( QAction::PreferencesRole );\n\n    /// Window\n    QMenu* windowMenu = appMenuBar()->addMenu( tr(\"Window\") );\n    windowMenu->addAction( tr( \"Minimize\" ), this, SLOT(onMinimizeTriggered()), Qt::CTRL + Qt::Key_M );\n    windowMenu->addAction( tr( \"Zoom\" ), this, SLOT(onZoomTriggered()) );\n    //windowMenu->addSeparator();\n    //windowMenu->addAction( tr( \"Last.fm\" ), this, SLOT(onZoomTriggered()) );\n    windowMenu->addSeparator();\n    windowMenu->addAction( tr( \"Bring All to Front\" ), this, SLOT(onBringAllToFrontTriggered()) );\n\n    /// Help\n    QMenu* helpMenu = appMenuBar()->addMenu( tr(\"Help\") );\n    QAction* about = helpMenu->addAction( tr(\"About\"), aApp, SLOT(onAboutTriggered()) );\n    about->setMenuRole( QAction::AboutRole );\n    helpMenu->addSeparator();\n    helpMenu->addAction( tr(\"FAQ\"), aApp, SLOT(onFaqTriggered()) );\n    helpMenu->addAction( tr(\"Forums\"), aApp, SLOT(onForumsTriggered()) );\n    helpMenu->addSeparator();\n    helpMenu->addAction( tr(\"Tour\"), aApp, SLOT(onTourTriggered()) );\n    helpMenu->addSeparator();\n    helpMenu->addAction( tr(\"Show Licenses\"), aApp, SLOT(onLicensesTriggered()) );\n#ifndef Q_WS_X11 // it's only the scrobble log tab at the moment so no use on linux\n    helpMenu->addSeparator();\n    helpMenu->addAction( tr(\"Diagnostics\"), aApp, SLOT(onDiagnosticsTriggered()) );\n#endif\n}\n\nvoid\nMainWindow::onSpace()\n{\n    aApp->playAction()->trigger();\n}\n\nvoid\nMainWindow::onConfigRetrieved()\n{\n}\n\nvoid\nMainWindow::onVisitProfile()\n{\n    unicorn::DesktopServices::openUrl( aApp->currentSession().user().www() );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), LINK_CLICKED, \"ProfileURLClicked\");\n}\n\nvoid\nMainWindow::showEvent(QShowEvent *)\n{\n    if ( m_preferences )\n        m_preferences->show();\n\n    m_menuBar->show();\n    m_menuBar->activateWindow();\n\n#ifdef Q_OS_MAC\n    if ( !m_installer )\n    {\n        m_installer = new unicorn::ITunesPluginInstaller( this );\n        QTimer::singleShot( 1000, m_installer, SLOT(install()) );\n    }\n#endif\n}\n\nvoid\nMainWindow::hideEvent(QHideEvent *)\n{\n    if ( m_preferences )\n        m_preferences->hide();\n}\n\nvoid\nMainWindow::onPrefsTriggered()\n{\n    if ( !m_preferences )\n        m_preferences = new PreferencesDialog( 0, this );\n\n    m_preferences->show();\n    m_preferences->activateWindow();\n    m_preferences->adjustSize();\n\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), BASIC_SETTINGS, \"SettingsOpened\");\n}\n\nvoid\nMainWindow::onDiagnosticsTriggered()\n{\n    if ( !m_diagnostics )\n        m_diagnostics = new DiagnosticsDialog( this );\n\n    m_diagnostics->show();\n    m_diagnostics->activateWindow();\n}\n\nvoid\nMainWindow::setBetaUpdates( bool betaUpdates )\n{\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n    if ( m_updater )\n        m_updater->setBetaUpdates( betaUpdates );\n#endif\n}\n\nvoid\nMainWindow::onMinimizeTriggered()\n{\n    setWindowState( Qt::WindowMinimized );\n}\n\nvoid\nMainWindow::onZoomTriggered()\n{\n    setWindowState( Qt::WindowMaximized );\n}\n\nvoid\nMainWindow::onBringAllToFrontTriggered()\n{\n\treturn;\n}\n\nvoid\nMainWindow::checkForUpdates()\n{\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n    m_updater->checkForUpdates();\n#endif\n}\n\nvoid\nMainWindow::onTrackStarted( const lastfm::Track& t, const lastfm::Track& /*previous*/ )\n{\n    m_currentTrack = t;\n    setWindowTitle( tr( \"%1 - %2\" ).arg( t.toString(), applicationName() ) );\n}\n\nvoid\nMainWindow::onStopped()\n{\n    m_currentTrack = Track();\n    setWindowTitle( applicationName() );\n}\n\nvoid\nMainWindow::onResumed()\n{\n    setWindowTitle( tr( \"%1 - %2\" ).arg( m_currentTrack.toString(), applicationName() ) );\n}\n\nvoid\nMainWindow::onPaused()\n{\n    setWindowTitle( tr( \"%1\" ).arg( applicationName() ) );\n}\n\nvoid\nMainWindow::onFoundScrobbles( const QList<lastfm::Track>& tracks )\n{\n    if ( tracks.count() > 0 )\n    {\n        ui.messageBar->addTracks( tracks );\n\n        int count = 0;\n\n        foreach ( const lastfm::Track& track, ui.messageBar->tracks() )\n            count += track.extra( \"playCount\" ).toInt();\n\n        ui.messageBar->show( tr( \"<a href=\\\"tracks\\\">%n play(s)</a> ha(s|ve) been scrobbled from a device\", \"\", count ), \"ipod\" );\n    }\n}\n\nvoid\nMainWindow::addWinThumbBarButton( QAction* thumbButtonAction )\n{\n    m_buttons.append( thumbButtonAction );\n}\n\nvoid\nMainWindow::addWinThumbBarButtons( QList<QAction*>& thumbButtonActions )\n{\n    foreach ( QAction* button, m_buttons )\n        thumbButtonActions.append( button );\n}\n\n"
  },
  {
    "path": "app/client/MainWindow.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef METADATA_WINDOW_H_\n#define METADATA_WINDOW_H_\n\n#include <QResizeEvent>\n\n#include <lastfm/Track.h>\n#include <lastfm/XmlQuery.h>\n\n#include \"lib/unicorn/UnicornMainWindow.h\"\n\n#ifdef  Q_OS_MAC\n#include \"lib/unicorn/plugins/ITunesPluginInstaller.h\"\n#endif\n\n#include \"Settings/PreferencesDialog.h\"\n#include \"Dialogs/DiagnosticsDialog.h\"\n\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\nnamespace unicorn\n{\n    class Updater;\n    class PluginList;\n}\nusing unicorn::Updater;\n#endif\n\nusing lastfm::XmlQuery;\n\nclass QAbstractButton;\nclass QTabBar;\nclass QLabel;\nclass ScrobbleControls;\nclass FirstRunWizard;\nclass MessageBar;\nclass SlideOverLayout;\nclass UserToolButton;\n\nclass IpodDevice;\n\nclass MainWindow : public unicorn::MainWindow\n{\n    Q_OBJECT\n\n    struct{\n        class TitleBar* titleBar;\n        class StatusBar* statusBar;\n\n        class MessageBar* messageBar;\n\n        class SideBar* sideBar;\n        class QStackedWidget* stackedWidget;\n\n        class NowPlayingStackedWidget* nowPlaying;\n        class ScrobblesWidget* scrobbles;\n\n        class QScrollArea* profileScrollArea;\n        QWidget* profile;\n        class QScrollArea* friendsScrollArea;\n        QWidget* friends;\n\n    } ui;\n\npublic:\n    MainWindow( QMenuBar* );\n    const Track& currentTrack() const{ return m_currentTrack; }\n\n    void addWinThumbBarButton( QAction* );\n    void setBetaUpdates( bool betaUpdates );\n\n    QString currentCategory() const;\n\nsignals:\n    void trackGotInfo(XmlQuery);\n    void albumGotInfo(XmlQuery);\n    void artistGotInfo(XmlQuery);\n    void artistGotEvents(XmlQuery);\n    void trackGotTopFans(XmlQuery);\n    void trackGotTags(XmlQuery);\n    void finished();\n\npublic slots:\n    void onPrefsTriggered();\n    void onDiagnosticsTriggered();\n    void onMinimizeTriggered();\n    void onZoomTriggered();\n    void onBringAllToFrontTriggered();\n    void showMessage( const QString& message, const QString& id = \"\", int timeout = -1 /*seconds*/ );\n\nprivate slots:\n    void onVisitProfile();\n\n    void onTrackStarted(const lastfm::Track&, const lastfm::Track&);\n    void onStopped();\n    void onPaused();\n    void onResumed();\n\n    void checkForUpdates();\n\n    void onSpace();\n\n    void onConfigRetrieved();\n\n#ifdef Q_OS_WIN32\n    void checkUpdatedPlugins();\n#endif\n\n    // iPod scrobbling things\n    void onFoundScrobbles( const QList<lastfm::Track>& tracks );\n\nprivate:\n    void setCurrentWidget( QWidget* );\n    void addWinThumbBarButtons( QList<QAction*>& );\n    void setupMenuBar();\n\n    void showEvent(QShowEvent *);\n    void hideEvent(QHideEvent *);\n\n    static QString applicationName();\n\nprivate:\n    Track m_currentTrack;\n    class ActivityListItem* m_currentActivity;\n    QList<QAction*> m_buttons;\n\n    QPointer<PreferencesDialog> m_preferences;\n    QPointer<DiagnosticsDialog> m_diagnostics;\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n    QPointer<Updater> m_updater;\n#endif\n\n#ifdef Q_OS_WIN\n    QPointer<unicorn::PluginList> m_pluginList;\n#endif\n\n#ifdef Q_WS_MAC\n    QPointer<unicorn::ITunesPluginInstaller> m_installer;\n#endif\n};\n\n#endif //METADATA_WINDOW_H_\n\n"
  },
  {
    "path": "app/client/MediaDevices/DeviceScrobbler.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"lib/unicorn/dialogs/ScrobbleConfirmationDialog.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include \"../Application.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\n#include \"IpodDevice.h\"\n#include \"DeviceScrobbler.h\"\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n\n#ifdef Q_WS_X11\n#include <QFileDialog>\n#endif\n#include <QDebug>\n#include <QDirIterator>\n#include <QTimer>\n\n#ifdef Q_OS_MAC\n// Check for iTunes playcount difference once every 3 minutes\n// (usually takes about 1 sec on Mac)\n#define BACKGROUND_CHECK_INTERVAL 3 * 60 * 1000\n#else\n// On Windows the iPod scrobble check can take around 90 seconds\n// for a fairly large library, so only run it every 30 minutes\n#define BACKGROUND_CHECK_INTERVAL 30 * 60 * 1000\n#endif\n\nQString getIpodMountPath();\n\nDeviceScrobbler::DeviceScrobbler( QObject *parent )\n    :QObject( parent )\n{\n    connect( this, SIGNAL(error(QString)), aApp, SIGNAL(error(QString)));\n\n    m_twiddlyTimer = new QTimer( this );\n    connect( m_twiddlyTimer, SIGNAL(timeout()), SLOT(twiddle()) );\n    m_twiddlyTimer->start( BACKGROUND_CHECK_INTERVAL );\n\n    // run once 3 seconds after starting up\n    QTimer::singleShot( 3 * 1000, this, SLOT(twiddle()) );\n}\n\nDeviceScrobbler::~DeviceScrobbler()\n{\n    if ( m_confirmDialog )\n        m_confirmDialog->deleteLater();\n\n    // make sure we terminate twiddly we could be clsoed due\n    // to the installer and twiddly would stop install working\n    if ( m_twiddly )\n        m_twiddly->deleteLater();\n}\n\nbool\nDeviceScrobbler::isITunesPluginInstalled()\n{\n#ifdef Q_OS_WIN\n    QSettings settings( \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Last.fm\\\\Client\\\\Plugins\\\\itw\", QSettings::NativeFormat );\n    QFile pluginFile( settings.value( \"Path\" ).toString() );\n    return pluginFile.exists();\n#else\n    return true;\n#endif\n}\n\nvoid\nDeviceScrobbler::twiddle()\n{\n    doTwiddle( false );\n}\n\nDeviceScrobbler::DoTwiddlyResult\nDeviceScrobbler::doTwiddle( bool manual )\n{\n#ifndef Q_WS_X11\n    if ( unicorn::CloseAppsDialog::isITunesRunning() )\n    {\n        if ( isITunesPluginInstalled() )\n        {\n            if ( m_twiddly )\n            {\n                qWarning() << \"m_twiddly already running. Early out.\";\n                return AlreadyRunning;\n            }\n\n            //\"--device diagnostic --vid 0000 --pid 0000 --serial UNKNOWN\n\n            QStringList args;\n\n            if ( sender() )\n                args << \"--device\" << \"background\";\n            else\n                args << \"--device\" << \"diagnostic\";\n\n            args << \"--vid\" << \"0000\";\n            args << \"--pid\" << \"0000\";\n\n            if ( manual )\n            {\n                args << \"--serial\" << \"manual\";\n                args += \"--manual\";\n            }\n            else\n                args << \"--serial\" << \"automatic\";\n\n            m_twiddly = new QProcess( this );\n            connect( m_twiddly, SIGNAL(finished( int, QProcess::ExitStatus )), SLOT(onTwiddlyFinished( int, QProcess::ExitStatus )) );\n            connect( m_twiddly, SIGNAL(error( QProcess::ProcessError )), SLOT(onTwiddlyError( QProcess::ProcessError )) );\n#ifdef Q_OS_WIN\n            m_twiddly->start( QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( \"iPodScrobbler.exe\" ), args );\n#else\n            m_twiddly->start( QDir( QCoreApplication::applicationDirPath() ).absoluteFilePath( \"../Helpers/iPodScrobbler\" ), args );\n#endif\n            return Started;\n        }\n        else\n            return ITunesPluginNotInstalled;\n    }\n#endif //  Q_WS_X11\n    return ITunesNotRunning;\n}\n\nvoid\nDeviceScrobbler::onTwiddlyFinished( int exitCode, QProcess::ExitStatus exitStatus )\n{\n    qDebug() << exitCode << exitStatus;\n    m_twiddly->deleteLater();\n}\n\nvoid\nDeviceScrobbler::onTwiddlyError( QProcess::ProcessError error )\n{\n    qDebug() << error;\n    m_twiddly->deleteLater();\n}\n\nvoid \nDeviceScrobbler::checkCachedIPodScrobbles()\n{\n    QStringList files;\n\n    // check if there are any iPod scrobbles in its folder\n    QDir scrobblesDir = lastfm::dir::runtimeData();\n\n    if ( scrobblesDir.cd( \"devices\" ) )\n    {\n        QDirIterator iterator( scrobblesDir, QDirIterator::Subdirectories );\n\n        while ( iterator.hasNext() )\n        {\n            iterator.next();\n\n            if ( iterator.fileInfo().isFile() )\n            {\n                QString filename = iterator.fileName();\n\n                if ( filename.endsWith(\".xml\") )\n                    files << iterator.fileInfo().absoluteFilePath();\n            }\n        }\n    }\n\n    scrobbleIpodFiles( files );\n}\n\n\n\nvoid \nDeviceScrobbler::handleMessage( const QStringList& message )\n{\n    int pos = message.indexOf( \"--twiddly\" );\n    const QString& action = message[ pos + 1 ];\n    \n    if( action == \"complete\" )\n        twiddled( message );\n    else if ( action == \"incompatible-plugin\" )\n        emit error( tr( \"Device scrobbling disabled - incompatible iTunes plugin - %1\" )\n                    .arg( unicorn::Label::anchor( \"plugin\", tr(\"please update\" ) ) ) );\n}\n\n\nvoid \nDeviceScrobbler::iPodDetected( const QStringList& /*arguments*/ )\n{\n}\n\nvoid \nDeviceScrobbler::twiddled( const QStringList& arguments )\n{\n    // iPod scrobble time!\n    QString iPodPath = arguments[ arguments.indexOf( \"--ipod-path\" ) + 1 ];\n\n    if ( !arguments.contains( \"no-tracks-found\" ) )\n        scrobbleIpodFiles( QStringList( iPodPath ) );\n}\n\n\n\nvoid \nDeviceScrobbler::scrobbleIpodFiles( const QStringList& files )\n{\n    qDebug() << files;\n\n    bool removeFiles = false;\n\n    if ( unicorn::OldeAppSettings().deviceScrobblingEnabled() )\n    {\n        QList<lastfm::Track> scrobbles = scrobblesFromFiles( files );\n\n        // TODO: fix the root cause of this problem\n        // If there are more than 4000 scrobbles we assume there was an error with the\n        // iPod scrobbling diff checker so discard these scrobbles.\n        // 4000 because 16 waking hours a day, for two weeks, with 3.5 minute songs\n        if ( scrobbles.count() >= 4000 )\n            removeFiles = true;\n        else\n        {\n            if ( scrobbles.count() > 0 )\n            {\n                if ( unicorn::AppSettings().alwaysAsk()\n                     || scrobbles.count() >= 200 ) // always get them to check scrobbles over 200\n                {\n                    if ( !m_confirmDialog )\n                    {\n                        m_confirmDialog = new ScrobbleConfirmationDialog( scrobbles, aApp->mainWindow() );\n                        connect( m_confirmDialog, SIGNAL(finished(int)), SLOT(onScrobblesConfirmationFinished(int)) );\n                    }\n                    else\n                        m_confirmDialog->addTracks( scrobbles );\n\n                    // add the files so it can delete them when the user has decided what to do\n                    m_confirmDialog->addFiles( files );\n                    m_confirmDialog->show();\n                }\n                else\n                {\n                    // sort the iPod scrobbles before caching them\n                    if ( scrobbles.count() > 1 )\n                        qSort ( scrobbles.begin(), scrobbles.end() );\n\n                    emit foundScrobbles( scrobbles );\n\n                    // we're scrobbling them so remove the source files\n                    removeFiles = true;\n                }\n            }\n            else\n                // there were no scrobbles in the files so remove them\n                removeFiles = true;\n        }\n    }\n    else\n        // device scrobbling is disabled so remove these files\n        removeFiles = true;\n\n    if ( removeFiles )\n        foreach ( QString file, files )\n            QFile::remove( file );\n\n}\n\nQList<lastfm::Track>\nDeviceScrobbler::scrobblesFromFiles( const QStringList& files  )\n{\n    QList<lastfm::Track> scrobbles;\n\n    foreach ( const QString file, files )\n    {\n        QFile iPodScrobbleFile( file );\n\n        if ( iPodScrobbleFile.open( QIODevice::ReadOnly | QIODevice::Text ) )\n        {\n            QDomDocument iPodScrobblesDoc;\n            iPodScrobblesDoc.setContent( &iPodScrobbleFile );\n            QDomNodeList tracks = iPodScrobblesDoc.elementsByTagName( \"track\" );\n\n            for ( int i(0) ; i < tracks.count() ; ++i )\n            {\n                lastfm::Track track( tracks.at(i).toElement() );\n\n                // don't add tracks to the list if they don't have an artist\n                // don't add podcasts to the list if podcast scrobbling is off\n                // don't add videos to the list (well, videos that aren't \"music video\")\n                // don't add tracks if they are in excluded folders\n\n                if ( !track.artist().isNull()\n                     && ( unicorn::UserSettings().value( \"podcasts\", true ).toBool() || !track.isPodcast() )\n                     && !track.isVideo()\n                     && !ScrobbleService::isDirExcluded( track ) )\n                    scrobbles << track;\n            }\n        }\n    }\n\n    return scrobbles;\n}\n\nvoid\nDeviceScrobbler::onScrobblesConfirmationFinished( int result )\n{\n    if ( result == QDialog::Accepted )\n    {\n        QList<lastfm::Track> scrobbles = m_confirmDialog->tracksToScrobble();\n\n        // sort the iPod scrobbles before caching them\n        if ( scrobbles.count() > 1 )\n            qSort ( scrobbles.begin(), scrobbles.end() );\n\n        emit foundScrobbles( scrobbles );\n\n        unicorn::AppSettings().setAlwaysAsk( !m_confirmDialog->autoScrobble() );\n    }\n\n    // delete all the iPod scrobble files whether it was accepted or not\n    foreach ( const QString file, m_confirmDialog->files() )\n        QFile::remove( file );\n\n    m_confirmDialog->deleteLater();\n}\n\n#ifdef Q_WS_X11\nvoid \nDeviceScrobbler::onScrobbleIpodTriggered() {\n    if ( iPod )\n    {\n        qDebug() << \"deleting ipod...\";\n        delete iPod;\n    }\n    qDebug() << \"here\";\n    iPod = new IpodDeviceLinux;\n    QString path;\n    bool autodetectionSuceeded = true;\n\n    if ( !iPod->autodetectMountPath() )\n    {\n        path = getIpodMountPath();\n        iPod->setMountPath( path );\n        autodetectionSuceeded = false;\n    }\n\n    if ( autodetectionSuceeded || !path.isEmpty() )\n    {\n        connect( iPod, SIGNAL( scrobblingCompleted( int ) ), this, SLOT( scrobbleIpodTracks( int ) ) );\n        connect( iPod, SIGNAL( calculatingScrobbles( int ) ), this, SLOT( onCalculatingScrobbles( int ) ) );\n        connect( iPod, SIGNAL( errorOccurred() ), this, SLOT( onIpodScrobblingError() ) );\n        iPod->fetchTracksToScrobble();\n    }\n}\n\n\nQString getIpodMountPath()\n{\n    QString path = \"\";\n    QFileDialog dialog( 0, QObject::tr( \"Where is your iPod mounted?\" ), \"/\" );\n    dialog.setOption( QFileDialog::ShowDirsOnly, true );\n    dialog.setFileMode( QFileDialog::Directory );\n\n    //The following lines are to make sure the QFileDialog looks native.\n    QString backgroundColor( \"transparent\" );\n    dialog.setStyleSheet( \"QDockWidget QFrame{ background-color: \" + backgroundColor + \"; }\" );\n\n    if ( dialog.exec() )\n    {\n       path = dialog.selectedFiles()[ 0 ];\n    }\n    return path;\n}\n\nvoid \nDeviceScrobbler::onCalculatingScrobbles( int trackCount )\n{\n    qApp->setOverrideCursor( Qt::WaitCursor );\n}\n\nvoid \nDeviceScrobbler::scrobbleIpodTracks( int trackCount )\n{\n    qApp->restoreOverrideCursor();\n    qDebug() << trackCount << \" new tracks to scrobble.\";\n\n    bool bootStrapping = false;\n    if ( iPod->lastError() != IpodDeviceLinux::NoError && !iPod->isDeviceKnown() )\n    {\n        bootStrapping = true;\n        qDebug() << \"Should we save it?\";\n        int result = QMessageBoxBuilder( 0 )\n            .setIcon( QMessageBox::Question )\n            .setTitle( tr( \"Scrobble iPod\" ) )\n            .setText( tr( \"Do you want to associate the device %1 to your audioscrobbler user account?\" ).arg( iPod->deviceName() ) )\n            .setButtons( QMessageBox::Yes | QMessageBox::No )\n            .exec();\n\n        if ( result == QMessageBox::Yes )\n        {\n            iPod->associateDevice();\n            QMessageBoxBuilder( 0 )\n                .setIcon( QMessageBox::Information )\n                .setTitle( tr( \"Scrobble iPod\" ) )\n                .setText( tr( \"Device successfully associated to your user account. \"\n                            \"From now on you can scrobble the tracks you listen on this device.\" ) )\n                .exec();\n\n        }\n        else\n        {\n            IpodDeviceLinux::deleteDeviceHistory( qobject_cast<unicorn::Application*>( qApp )->currentSession().user().name(), iPod->deviceId() );\n        }\n    }\n\n    QList<lastfm::Track> tracks = iPod->tracksToScrobble();\n\n    if ( tracks.count() )\n    {\n        if ( !bootStrapping )\n        {\n            if( unicorn::UserSettings().value( \"confirmIpodScrobbles\", false ).toBool() )\n            {\n                qDebug() << \"showing confirm dialog\";\n                ScrobbleConfirmationDialog confirmDialog( tracks );\n                if ( confirmDialog.exec() == QDialog::Accepted )\n                {\n                    tracks = confirmDialog.tracksToScrobble();\n\n                    // sort the iPod scrobbles before caching them\n                    if ( tracks.count() > 1 )\n                        qSort ( tracks.begin(), tracks.end() );\n\n                    emit foundScrobbles( tracks );\n                }\n            }\n            else\n            {\n                // sort the iPod scrobbles before caching them\n                if ( tracks.count() > 1 )\n                    qSort ( tracks.begin(), tracks.end() );\n\n                emit foundScrobbles( tracks );\n                QMessageBoxBuilder( 0 )\n                    .setIcon( QMessageBox::Information )\n                    .setTitle( tr( \"Scrobble iPod\" ) )\n                    .setText( tr( \"%1 tracks scrobbled.\" ).arg( tracks.count() ) )\n                    .exec();\n            }\n        }\n    }\n    else if ( !iPod->lastError() )\n    {\n        QMessageBoxBuilder( 0 )\n            .setIcon( QMessageBox::Information )\n            .setTitle( tr( \"Scrobble iPod\" ) )\n            .setText( tr( \"No tracks to scrobble since your last sync.\" ) )\n            .exec();\n        qDebug() << \"No tracks to scrobble\";\n    }\n    delete iPod;\n    iPod = 0;\n}\n\nvoid \nDeviceScrobbler::onIpodScrobblingError()\n{\n    qDebug() << \"iPod Error\";\n    qApp->restoreOverrideCursor();\n    QString path;\n    switch( iPod->lastError() )\n    {\n        case IpodDeviceLinux::AutodetectionError: //give it another try\n            qDebug() << \"giving another try\";\n            path = getIpodMountPath();\n            if ( !path.isEmpty() )\n            {\n                iPod->setMountPath( path );\n                iPod->fetchTracksToScrobble();\n            }\n            break;\n\n        case IpodDeviceLinux::AccessError:\n            QMessageBoxBuilder( 0 )\n                .setIcon( QMessageBox::Critical )\n                .setTitle( tr( \"Scrobble iPod\" ) )\n                .setText( tr( \"The iPod database could not be opened.\" ) )\n                .exec();\n            delete iPod;\n            iPod = 0;\n            break;\n        case IpodDeviceLinux::UnknownError:\n            QMessageBoxBuilder( 0 )\n                .setIcon( QMessageBox::Critical )\n                .setTitle( tr( \"Scrobble iPod\" ) )\n                .setText( tr( \"An unknown error occurred while trying to access the iPod database.\" ) )\n                .exec();\n            delete iPod;\n            iPod = 0;\n            break;\n        default:\n            qDebug() << \"untracked error:\" << iPod->lastError();\n    }\n}\n\n#endif\n\n\n"
  },
  {
    "path": "app/client/MediaDevices/DeviceScrobbler.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef DEVICE_SCROBBLER_H_\n#define DEVICE_SCROBBLER_H_\n\n#include <QDialogButtonBox>\n#include <QProcess>\n\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include <lastfm/User.h>\n#include \"IpodDevice.h\"\n\n#ifdef Q_WS_X11\n#include <QPointer>\n#include \"IpodDevice_linux.h\"\n#endif\n\nusing unicorn::Session;\n\nclass ScrobbleConfirmationDialog;\n\nclass DeviceScrobbler : public QObject\n{\n    Q_OBJECT\npublic:\n    enum DoTwiddlyResult\n    {\n        Started,\n        AlreadyRunning,\n        ITunesNotRunning,\n        ITunesPluginNotInstalled\n    };\n\npublic:\n    explicit DeviceScrobbler( QObject* parent = 0 );\n    ~DeviceScrobbler();\n\n    DoTwiddlyResult doTwiddle( bool manual );\n\nsignals:\n    void foundScrobbles( const QList<lastfm::Track>& tracks );\n    void error( const QString& message );\n\npublic slots:\n#ifdef Q_WS_X11\n    void onScrobbleIpodTriggered();\n#endif\n\nprivate slots:\n#ifdef Q_WS_X11\n    void onCalculatingScrobbles( int trackCount );\n    void scrobbleIpodTracks( int trackCount );\n    void onIpodScrobblingError();\n#endif\n    void twiddle();\n    void onTwiddlyFinished( int, QProcess::ExitStatus );\n    void onTwiddlyError( QProcess::ProcessError );\n\n    void onScrobblesConfirmationFinished( int result );\n    void checkCachedIPodScrobbles();\n\npublic:\n    void handleMessage( const QStringList& );\n    void iPodDetected( const QStringList& arguments );\n\nprivate:\n#ifdef Q_WS_X11\n    QPointer<IpodDeviceLinux> iPod;\n#endif\n    bool isITunesPluginInstalled();\n\n    void twiddled( const QStringList& arguments );\n    void scrobbleIpodFiles( const QStringList& files );\n    QList<lastfm::Track> scrobblesFromFiles( const QStringList& files );\n\n    lastfm::User associatedUser( QString deviceId );\n\nprivate:\n    QPointer<QProcess> m_twiddly;\n    QTimer* m_twiddlyTimer;\n    QPointer<ScrobbleConfirmationDialog> m_confirmDialog;\n};\n\n#endif //DEVICE_SCROBBLER_H_\n"
  },
  {
    "path": "app/client/MediaDevices/IpodDevice.cpp",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\n#include <QApplication>\n#include <QByteArray>\n#include <QFile>\n#include <QSqlError>\n#include <QSqlQuery>\n#include <QStringList>\n\n#include \"IpodDevice.h\"\n\nIpodDevice::IpodDevice( const QString& deviceId, const QString& deviceName )\n    : m_deviceId( deviceId ), m_deviceName( deviceName )\n{}\n\nQString\nIpodDevice::deviceId() const\n{\n    return m_deviceId;\n}\n\nQString\nIpodDevice::deviceName() const\n{\n    return m_deviceName;\n}\n\nvoid\nIpodDevice::setSetting( QString key, QVariant value )\n{\n    // Find the setting for this\n    QList<lastfm::User> roster = unicorn::Settings().userRoster();\n\n    bool found = false;\n\n    foreach( lastfm::User user, roster )\n    {\n        unicorn::UserSettings us( user.name() );\n        int count = us.beginReadArray( \"associatedDevices\" );\n\n        for ( int i = 0; i < count; i++ )\n        {\n            us.setArrayIndex( i );\n\n            if ( us.value( \"deviceId\" ).toString() == m_deviceId )\n            {\n                us.setValue( key, value );\n                found = true;\n                break;\n            }\n        }\n        us.endArray();\n\n        if ( found ) break;\n    }\n}\n\nQVariant\nIpodDevice::setting( QString key, QVariant defaultValue )\n{\n    QVariant value;\n\n    // Find the setting for this\n    QList<lastfm::User> roster = unicorn::Settings().userRoster();\n\n    bool found = false;\n\n    foreach( lastfm::User user, roster )\n    {\n        unicorn::UserSettings us( user.name() );\n        int count = us.beginReadArray( \"associatedDevices\" );\n\n        for ( int i = 0; i < count; i++ )\n        {\n            us.setArrayIndex( i );\n\n            if ( us.value( \"deviceId\" ).toString() == m_deviceId )\n            {\n                value = us.value( key, defaultValue );\n                found = true;\n                break;\n            }\n        }\n        us.endArray();\n\n        if ( found ) break;\n    }\n\n    return value;\n}\n"
  },
  {
    "path": "app/client/MediaDevices/IpodDevice.h",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IPOD_DEVICE_H\n#define IPOD_DEVICE_H\n\n#include \"MediaDevice.h\"\n\nclass IpodDevice: public MediaDevice\n{\n    Q_OBJECT\npublic:\n    // DO NOT CHANGE THIS: IT WILL MESS UP IPOD SCROBBLE SETTINGS\n    IpodDevice( const QString& deviceId, const QString& deviceName);\n\n    virtual QString deviceId() const;\n    virtual QString deviceName() const;\n\n#ifdef Q_WS_X11\n    /**\n     * @return The mount path of the device.\n     */\n    virtual QString mountPath() const{ return QString(); }\n#endif\n\nprivate:\n    void setSetting( QString key, QVariant value );\n    QVariant setting( QString key, QVariant defaultValue );\n\nprivate:\n    QString m_deviceId;\n    QString m_deviceName;\n};\n\n#endif // IPOD_DEVICE_H\n"
  },
  {
    "path": "app/client/MediaDevices/IpodDevice_linux.cpp",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Application.h\"\n#include \"IpodDevice_linux.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\n#include <QApplication>\n#include <QByteArray>\n#include <QFile>\n#include <QSqlError>\n#include <QSqlQuery>\n#include <QStringList>\n\nextern \"C\"\n{\n    #include <gpod/itdb.h>\n    #include <glib.h>\n}\n\nIpodTracksFetcher::IpodTracksFetcher( Itdb_iTunesDB *itdb, QSqlDatabase scrobblesdb,\n                                      const QString& tableName, const QString& ipodModel )\n{\n    m_itdb = itdb;\n    m_tableName = tableName;\n    m_scrobblesdb = scrobblesdb;\n    m_ipodModel = ipodModel;\n}\n\nvoid\nIpodTracksFetcher::run()\n{\n    fetchTracks();\n    exec();\n}\n\nvoid\nIpodTracksFetcher::fetchTracks()\n{\n    GList *cur;\n    for ( cur = m_itdb->tracks; cur; cur = cur->next )\n    {\n        Itdb_Track *iTrack = ( Itdb_Track * )cur->data;\n        if ( !iTrack )\n            continue;\n\n        int newPlayCount = iTrack->playcount - previousPlayCount( iTrack );\n        QDateTime time;\n        time.setTime_t( iTrack->time_played );\n\n        if ( time.toTime_t() == 0 )\n            continue;\n\n        QDateTime prevPlayTime = previousPlayTime( iTrack );\n\n        //this logic takes into account that sometimes the itdb track play count is not\n        //updated correctly (or libgpod doesn't get it right),\n        //so we rely on the track play time too, which seems to be right most of the time\n        if ( ( iTrack->playcount > 0 && newPlayCount > 0 ) || time > prevPlayTime )\n        {\n            Track lstTrack;\n            setTrackInfo( lstTrack, iTrack );\n\n            if ( newPlayCount == 0 )\n                newPlayCount++;\n\n            //add the track to the list as many times as the updated playcount.\n            for ( int i = 0; i < newPlayCount; i++ )\n            {\n                m_tracksToScrobble.append( lstTrack );\n            }\n\n            commit( iTrack );\n        }\n    }\n    qDebug() << \"tracks fetching finished\";\n    exit();\n}\n\nvoid\nIpodTracksFetcher::setTrackInfo( Track& lstTrack, Itdb_Track* iTrack )\n{\n    MutableTrack( lstTrack ).setArtist( QString::fromUtf8( iTrack->artist ) );\n    MutableTrack( lstTrack ).setAlbum( QString::fromUtf8( iTrack->album ) );\n    MutableTrack( lstTrack ).setTitle( QString::fromUtf8( iTrack->title ) );\n    MutableTrack( lstTrack ).setSource( Track::MediaDevice );\n    if ( iTrack->mediatype & ITDB_MEDIATYPE_PODCAST )\n        MutableTrack( lstTrack ).setPodcast( true );\n\n    QDateTime t;\n    t.setTime_t( iTrack->time_played );\n    MutableTrack( lstTrack ).setTimeStamp( t );\n    MutableTrack( lstTrack ).setDuration( iTrack->tracklen / 1000 ); // set duration in seconds\n\n    MutableTrack( lstTrack ).setExtra( \"playerName\", \"iPod \" + m_ipodModel );\n}\n\nvoid\nIpodTracksFetcher::commit( Itdb_Track* iTrack )\n{\n    QSqlQuery query( m_scrobblesdb );\n    QString sql = \"REPLACE INTO \" + m_tableName + \" ( playcount, lastplaytime, id ) VALUES( %1, %2, %3 )\";\n\n    query.exec( sql.arg( iTrack->playcount ).arg( iTrack->time_played ).arg( iTrack->id  ) );\n    if( query.lastError().type() != QSqlError::NoError )\n        qWarning() << query.lastError().text();\n}\n\nuint\nIpodTracksFetcher::previousPlayCount( Itdb_Track* track ) const\n{\n    QSqlQuery query( m_scrobblesdb );\n    QString sql = \"SELECT playcount FROM \" + m_tableName + \" WHERE id=\" + QString::number( track->id );\n\n    query.exec( sql );\n\n    if( query.next() )\n        return query.value( 0 ).toUInt();\n    return 0;\n}\n\nQDateTime\nIpodTracksFetcher::previousPlayTime( Itdb_Track* track ) const\n{\n    QSqlQuery query( m_scrobblesdb );\n    QString sql = \"SELECT lastplaytime FROM \" + m_tableName  + \" WHERE id=\" + QString::number( track->id );\n\n    query.exec( sql );\n\n    if( query.next() )\n        return QDateTime::fromTime_t( query.value( 0 ).toUInt() );\n    return QDateTime::fromTime_t( 0 );\n}\n\nIpodDeviceLinux::IpodDeviceLinux()\n    : m_itdb( 0 )\n    , m_mpl( 0 )\n    , m_tf( 0 )\n    , m_autodetected( false )\n    , m_error( NoError )\n{}\n\n\nIpodDeviceLinux::~IpodDeviceLinux()\n{\n    if ( m_itdb )\n    {\n        itdb_free( m_itdb );\n        itdb_playlist_free( m_mpl );\n    }\n\n    delete m_tf;\n}\n\nbool\nIpodDeviceLinux::deleteDeviceHistory( QString username, QString deviceId )\n{\n    QString const name = DB_NAME;\n    QSqlDatabase db = QSqlDatabase::database( name );\n    bool b = false;\n\n    if ( !db.isValid() )\n    {\n        db = QSqlDatabase::addDatabase( \"QSQLITE\", name );\n        db.setDatabaseName( lastfm::dir::runtimeData().filePath( name + \".db\" ) );\n    }\n\n    db.open();\n\n    QSqlQuery q( db );\n    b = q.exec( \"DROP TABLE \" + username + \"_\" + deviceId );\n\n    if ( !b )\n        qWarning() << q.lastError().text();\n\n    return b;\n}\n\nbool\nIpodDeviceLinux::deleteDevicesHistory()\n{\n    QString const name = DB_NAME;\n    QString filePath = lastfm::dir::runtimeData().filePath( name + \".db\" );\n    return QFile::remove( filePath );\n}\n\n\nQSqlDatabase\nIpodDeviceLinux::database() const\n{\n    QString const name = DB_NAME;\n    QSqlDatabase db = QSqlDatabase::database( name );\n\n    if ( !db.isValid() )\n    {\n        db = QSqlDatabase::addDatabase( \"QSQLITE\", name );\n        db.setDatabaseName( lastfm::dir::runtimeData().filePath( name + \".db\" ) );\n\n        db.open();\n\n\n    }\n\n    if( !db.tables().contains( tableName() ) )\n    {\n        QSqlQuery q( db );\n        qDebug() << \"table name: \" << tableName();\n        bool b = q.exec( \"CREATE TABLE \" + tableName() + \" ( \"\n                         \"id           INTEGER PRIMARY KEY, \"\n                         \"playcount    INTEGER, \"\n                         \"lastplaytime INTEGER )\" );\n        if ( !b )\n            qWarning() << q.lastError().text();\n    }\n\n    return db;\n}\n\nvoid\nIpodDeviceLinux::open()\n{\n    QByteArray _mountpath = QFile::encodeName( mountPath() );\n    const char* mountpath = _mountpath.data();\n\n    qDebug() << \"mount path: \" << mountPath();\n\n    m_itdb = itdb_new();\n    itdb_set_mountpoint( m_itdb, mountpath );\n    m_mpl = itdb_playlist_new( \"iPod\", false );\n    itdb_playlist_set_mpl( m_mpl );\n    GError* err = 0;\n    m_itdb = itdb_parse( mountpath, &err );\n\n    if ( err )\n        throw tr( \"The iPod database could not be opened.\" );\n\n    if( m_deviceId.isEmpty() )\n    {\n        const Itdb_IpodInfo* iPodInfo = itdb_device_get_ipod_info( m_itdb->device );\n        const gchar* ipodModel = itdb_info_get_ipod_model_name_string( iPodInfo->ipod_model );\n        m_ipodModel = QString( ipodModel );\n        m_deviceId = m_ipodModel.section( ' ', 0, 0 ) + \"_\" + QString::number( m_itdb->id );\n    }\n\n}\n\nconst QList<Track>&\nIpodDeviceLinux::tracksToScrobble() const\n{\n    return m_tracksToScrobble;\n}\n\nvoid\nIpodDeviceLinux::fetchTracksToScrobble()\n{\n    try\n    {\n        open();\n    }\n    catch ( QString &error )\n    {\n        qDebug() << \"Error initializing the device:\" << error;\n        if ( m_autodetected )\n        {\n            m_error = AutodetectionError;\n        }\n        else\n        {\n            m_error = AccessError;\n        }\n        emit errorOccurred();\n        return;\n    }\n    \n    emit calculatingScrobbles( itdb_tracks_number( m_itdb ) );\n    m_tf = new IpodTracksFetcher( m_itdb, database(), tableName(), m_ipodModel );\n    connect( m_tf, SIGNAL( finished() ), this, SLOT( onFinished() ) );\n    m_tf->start();\n\n}\n\n\nvoid\nIpodDeviceLinux::onFinished()\n{\n    m_error = NoError;\n    m_tracksToScrobble = m_tf->tracksToScrobble();\n    emit scrobblingCompleted( m_tracksToScrobble.count() );\n}\n\nQString\nIpodDeviceLinux::deviceName() const\n{\n    QStringList devPath = mountPath().split( \"/\", QString::SkipEmptyParts );\n    if ( !devPath.isEmpty() )\n        return devPath.last();\n    return QString();\n}\n\nQString\nIpodDeviceLinux::tableName() const\n{\n    audioscrobbler::Application* app = qobject_cast<audioscrobbler::Application* >( qApp );\n    if ( app )\n    {\n        return app->currentSession().user().name() + \"_\" + m_deviceId;\n    }\n    return QString();\n}\n\nbool\nIpodDeviceLinux::autodetectMountPath()\n{\n    unicorn::UserSettings us;\n    int count = us.beginReadArray( \"associatedDevices\" );\n\n    if ( !count )\n        return false;\n\n    m_detectedDevices.clear();\n\n    DeviceInfo deviceInfo;\n    QString deviceId;\n    for ( int i = 0; i < count; i++ )\n    {\n        us.setArrayIndex( i );\n        deviceId = us.value( \"deviceId\" ).toString();\n        deviceInfo.prettyName = us.value( \"deviceName\" ).toString();\n        deviceInfo.mountPath = us.value( \"mountPath\" ).toString();\n        if ( QFile::exists( deviceInfo.mountPath ) )\n        {\n            m_detectedDevices[ deviceId ] = deviceInfo;\n        }\n    }\n    us.endArray();\n\n    //No device detected or many, so user has to choose.\n    if ( m_detectedDevices.count() == 0 || m_detectedDevices.count() > 1 )\n    {\n        return false;\n    }\n\n    setMountPath( m_detectedDevices.values()[ 0 ].mountPath, true );\n    return true;\n}\n\nvoid\nIpodDeviceLinux::setMountPath( const QString &path, bool autodetected )\n{\n    m_mountPath = path;\n    m_autodetected = autodetected;\n}\n"
  },
  {
    "path": "app/client/MediaDevices/IpodDevice_linux.h",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IPOD_DEVICE_LINUX_H\n#define IPOD_DEVICE_LINUX_H\n\n#include \"MediaDevice.h\"\n\n#include <QThread>\n\ntypedef struct _Itdb_iTunesDB Itdb_iTunesDB;\ntypedef struct _Itdb_Track Itdb_Track;\ntypedef struct _Itdb_Playlist Itdb_Playlist;\n\nclass IpodTracksFetcher: public QThread\n{\npublic:\n    IpodTracksFetcher( Itdb_iTunesDB* itdb, QSqlDatabase scrobblesdb,\n                       const QString& tableName, const QString& ipodModel );\n    const QList<lastfm::Track>& tracksToScrobble() const{ return m_tracksToScrobble; }\n    void run();\nprivate:\n    void fetchTracks();\n    void commit( Itdb_Track* iTrack );\n    void setTrackInfo( Track& lstTrack, Itdb_Track* iTrack );\n    uint previousPlayCount( Itdb_Track* iTrack ) const;\n    QDateTime previousPlayTime( Itdb_Track* track ) const;\n\nprivate:\n    Itdb_iTunesDB* m_itdb;\n    QSqlDatabase m_scrobblesdb;\n    QString m_tableName;\n    QString m_ipodModel;\n    QList<Track> m_tracksToScrobble;\n};\n\nclass IpodDeviceLinux: public MediaDevice\n{\n    Q_OBJECT\n\npublic:\n\n    enum Error\n    {\n        NoError,\n        AutodetectionError,\n        AccessError,\n        UnknownError\n    };\n\n    IpodDeviceLinux();\n    ~IpodDeviceLinux();\n\n    /**\n     * Deletes the table with the device scrobbled tracks information.\n     * @return true on success.\n     */\n    static bool deleteDeviceHistory( QString username, QString deviceId );\n\n    /**\n     * Delete the database containing all the devices scrobbled tracks tables.\n     * @return true on success.\n     */\n    static bool deleteDevicesHistory();\n\n    /**\n     * @return the database to sync tracks to be scrobbled.\n     */\n    QSqlDatabase database() const;\n\n\n    /**\n     * Try to detect if there is any of the user associated devices already mounted and use it.\n     * If more than one device is detected then nothing would be done.\n     * @return true if there was just one of the user's devices mounted, otherwise returns false.\n     */\n    bool autodetectMountPath();\n\n    /**\n     * Sets the mount path where the device is mounted.\n     * @param path The mount path of the mounted device.\n     */\n    void setMountPath( const QString& path, bool autodetected = false );\n\n    /**\n     * @return The mount path of the device.\n     */\n    QString mountPath() const { return m_mountPath; }\n\n    virtual QString deviceId() const { return m_deviceId; }\n    virtual QString deviceName() const;\n\n    /**\n     * @return an unique table name to store the device scrobbled tracks.\n     */\n    QString tableName() const;\n\n    /**\n     * @return a list of tracks to be scrobbled.\n     */\n    const QList<Track>& tracksToScrobble() const;\n\n    Error lastError() const{ return m_error; }\n\npublic slots:\n    /**\n     * Fetches the tracks from the iPod.\n     */\n    void fetchTracksToScrobble();\n\nprivate:\n    void open();\n\nprivate slots:\n    void onFinished();\n\nprivate:\n    struct DeviceInfo\n    {\n        QString mountPath;\n        QString prettyName;\n    };\n\nprivate:\n    Itdb_iTunesDB* m_itdb;\n    Itdb_Playlist* m_mpl;\n    QString m_deviceId;\n    QMap<QString, DeviceInfo> m_detectedDevices;\n    QString m_mountPath;\n    QString m_ipodModel;\n    QList<Track> m_tracksToScrobble;\n    IpodTracksFetcher* m_tf;\n    bool m_autodetected;\n    Error m_error;\n};\n\n#endif // IPOD_DEVICE_H\n"
  },
  {
    "path": "app/client/MediaDevices/MediaDevice.cpp",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"MediaDevice.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include <lastfm/misc.h>\n\n#include <QDebug>\n#include <QSqlQuery>\n#include <QSqlError>\n\nMediaDevice::MediaDevice()\n{\n}\n\nbool\nMediaDevice::associateDevice( QString username )\n{\n    if ( deviceId().isEmpty() || deviceName().isEmpty() )\n        return false;\n\n#ifdef Q_WS_X11\n    if ( mountPath().isEmpty() || !QFile::exists( mountPath() ) )\n        return false;\n#endif\n\n    unicorn::UserSettings us( username );\n    int count = us.beginReadArray( \"associatedDevices\" );\n    int index = count;\n\n    QString devId;\n    for ( int i = 0; i < count; i++ )\n    {\n        us.setArrayIndex( i );\n        devId = us.value( \"deviceId\", \"\" ).toString();\n        if ( devId == deviceId() )\n        {\n            index = i;\n            break;\n        }\n    }\n\n    us.endArray();\n\n    us.beginWriteArray( \"associatedDevices\" );\n    us.setArrayIndex( index );\n    us.setValue( \"deviceId\", deviceId() );\n    us.setValue( \"deviceName\", deviceName() );\n\n#ifdef Q_WS_X11\n    us.setValue( \"mountPath\", QDir::toNativeSeparators( mountPath() ) );\n#endif\n\n    us.endArray();\n    return true;\n}\n\nbool\nMediaDevice::isDeviceKnown() const\n{\n    unicorn::UserSettings us;\n    int count = us.beginReadArray( \"associatedDevices\" );\n    QString devId;\n    bool isKnown = false;\n    for ( int i = 0; i < count; i++ )\n    {\n        us.setArrayIndex( i );\n        devId = us.value( \"deviceId\", \"\" ).toString();\n        if ( devId == deviceId() )\n        {\n            isKnown = true;\n        }\n    }\n    us.endArray();\n    return isKnown;\n}\n\nlastfm::User\nMediaDevice::associatedUser( const QString deviceId )\n{\n    lastfm::User associatedUser( \"\" );\n\n    // Check if the device has been associated with a user\n    // and then if it is with the current user\n    QList<lastfm::User> roster = unicorn::Settings().userRoster();\n    foreach( lastfm::User user, roster )\n    {\n        unicorn::UserSettings us( user.name() );\n        int count = us.beginReadArray( \"associatedDevices\" );\n\n        for ( int i = 0; i < count; i++ )\n        {\n            us.setArrayIndex( i );\n\n            QString tempDeviceId = us.value( \"deviceId\" ).toString();\n\n            qDebug() << tempDeviceId;\n\n            if ( tempDeviceId == deviceId )\n            {\n                associatedUser = user;\n                break;\n            }\n        }\n        us.endArray();\n\n        if ( !associatedUser.name().isEmpty() ) break;\n    }\n\n    return associatedUser;\n}\n"
  },
  {
    "path": "app/client/MediaDevices/MediaDevice.h",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef MEDIA_DEVICE_H\n#define MEDIA_DEVICE_H\n\n#include <QObject>\n#include <QSqlDatabase>\n#include <lastfm/Track.h>\n#include <lastfm/User.h>\n\n#define DB_NAME \"MediaDevicesScrobbles\"\n\nclass MediaDevice: public QObject\n{\n    Q_OBJECT\n\npublic:\n    MediaDevice();\n\n    /**\n     * Associates the device to an user account.\n     * @param username the user name to associate the device to. If no user name is provided the\n     * device gets associated to the current user logged in.\n     * @return true if it succeeds, false otherwise.\n     */\n    bool associateDevice( QString username = \"\" );\n\n    /**\n     * @return the last error ocurred or empty string if there wasn't any.\n     */\n    QString lastError() const { return m_error; }\n\n    /**\n     * @return an unique ID for the device.\n     */\n    virtual QString deviceId() const = 0;\n\n    /**\n     * @return the device name.\n     */\n    virtual QString deviceName() const = 0;\n\n\n#ifdef Q_WS_X11\n    /**\n     * @return The mount path of the device.\n     */\n    virtual QString mountPath() const = 0;\n#endif\n\n    /**\n     * @return true if the device is already associated with the user account, false otherwise.\n     */\n    bool isDeviceKnown() const;\n\n    static lastfm::User associatedUser( const QString deviceId );\n\nsignals:\n    void deviceScrobblingStarted();\n    void calculatingScrobbles( int trackCount );\n    void scrobblingCompleted( int trackCount );\n    void errorOccurred();\n\nprotected:\n    QString m_error;\n};\n\n\n#endif // MEDIA_DEVICE_H\n"
  },
  {
    "path": "app/client/Mpris2/DBusAbstractAdaptor.cpp",
    "content": "/*\n * Copyright 2012  Alex Merry <alex.merry@kdemail.net>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"DBusAbstractAdaptor.h\"\n\n#include <QtCore/QDebug>\n#include <QtCore/QMetaClassInfo>\n#include <QtDBus/QDBusMessage>\n\nDBusAbstractAdaptor::DBusAbstractAdaptor( QObject *parent )\n    : QDBusAbstractAdaptor( parent )\n    , m_connection( QDBusConnection::sessionBus() )\n{\n}\n\nQDBusConnection DBusAbstractAdaptor::connection() const\n{\n    return m_connection;\n}\n\nvoid DBusAbstractAdaptor::setConnection( const QDBusConnection &conn )\n{\n    m_connection = conn;\n}\n\nQString DBusAbstractAdaptor::dBusPath() const\n{\n    return m_path;\n}\n\nvoid DBusAbstractAdaptor::setDBusPath( const QString &path )\n{\n    m_path = path;\n}\n\nvoid DBusAbstractAdaptor::signalPropertyChange( const QString &property, const QVariant &value )\n{\n    if ( m_updatedProperties.isEmpty() && m_invalidatedProperties.isEmpty() ) {\n        QMetaObject::invokeMethod( this, \"_m_emitPropertiesChanged\", Qt::QueuedConnection );\n        qDebug() << \"MPRIS2: Queueing up a PropertiesChanged signal:\" << property << value;\n    }\n\n    m_updatedProperties[property] = value;\n}\n\nvoid DBusAbstractAdaptor::signalPropertyChange( const QString &property )\n{\n    if ( !m_invalidatedProperties.contains( property ) ) {\n        if ( m_updatedProperties.isEmpty() && m_invalidatedProperties.isEmpty() ) {\n            QMetaObject::invokeMethod( this, \"_m_emitPropertiesChanged\", Qt::QueuedConnection );\n            qDebug() << \"MPRIS2: Queueing up a PropertiesChanged signal:\" << property;\n        }\n\n        m_invalidatedProperties << property;\n    }\n}\n\nvoid DBusAbstractAdaptor::_m_emitPropertiesChanged()\n{\n    Q_ASSERT( !m_path.isEmpty() );\n\n    if( m_updatedProperties.isEmpty() && m_invalidatedProperties.isEmpty() ) {\n        qDebug() << \"MPRIS2: Nothing to do\";\n        return;\n    }\n\n    int ifaceIndex = metaObject()->indexOfClassInfo( \"D-Bus Interface\" );\n    if ( ifaceIndex < 0 ) {\n        qDebug() << \"MPRIS2: No D-Bus interface given (missing Q_CLASSINFO)\";\n    } else {\n        QDBusMessage signal = QDBusMessage::createSignal( m_path,\n             \"org.freedesktop.DBus.Properties\",\n             \"PropertiesChanged\" );\n        signal << metaObject()->classInfo( ifaceIndex ).value();\n        signal << m_updatedProperties;\n        signal << m_invalidatedProperties;\n        m_connection.send( signal );\n    }\n\n    m_updatedProperties.clear();\n    m_invalidatedProperties.clear();\n}\n\n"
  },
  {
    "path": "app/client/Mpris2/DBusAbstractAdaptor.h",
    "content": "/*\n * Copyright 2012  Alex Merry <alex.merry@kdemail.net>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef DBUSABSTRACTADAPTOR_H\n#define DBUSABSTRACTADAPTOR_H\n\n#include <QtDBus/QDBusAbstractAdaptor>\n#include <QtDBus/QDBusConnection>\n\n#include <QtCore/QStringList>\n#include <QtCore/QVariantMap>\n\nclass PropertiesChangedAdaptor : public QDBusAbstractAdaptor\n{\n    Q_OBJECT\n    Q_CLASSINFO(\"D-Bus Interface\", \"org.freedesktop.DBus.Properties\")\n\npublic:\n    explicit PropertiesChangedAdaptor( QObject *parent );\n    void emitPropertiesChanged( const QString &interface,\n                                const QVariantMap &updatedProperties,\n                                const QStringList &invalidatedProperties );\n\nQ_SIGNALS:\n    void propertiesChanged( const QString &interface,\n                            const QVariantMap &updatedProperties,\n                            const QStringList &invalidatedProperties );\n};\n\n/**\n * Hack for property notification support\n */\nclass DBusAbstractAdaptor : public QDBusAbstractAdaptor\n{\n    Q_OBJECT\n\npublic:\n    explicit DBusAbstractAdaptor( QObject *parent );\n\n    // These are hackish methods that are necessary because\n    // of the way QtDBus is implemented; it is impossible to\n    // find out what bus or path this adaptor is at, and adding\n    // another adaptor for the properties interface prevents\n    // Qt's internal properties implementation from working\n    QDBusConnection connection() const;\n    void setConnection( const QDBusConnection &conn );\n    QString dBusPath() const;\n    void setDBusPath( const QString &path );\n\nprotected:\n    void signalPropertyChange( const QString &property, const QVariant &value );\n    void signalPropertyChange( const QString &property );\n\nprivate Q_SLOTS:\n    void _m_emitPropertiesChanged();\n\nprivate:\n    QStringList     m_invalidatedProperties;\n    QVariantMap     m_updatedProperties;\n    QString         m_path;\n    QDBusConnection m_connection;\n};\n\n#endif // DBUSABSTRACTADAPTOR_H\n"
  },
  {
    "path": "app/client/Mpris2/MediaPlayer2.cpp",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"MediaPlayer2.h\"\n\n#include \"Application.h\"\n\nMediaPlayer2::MediaPlayer2( QObject* parent ) : DBusAbstractAdaptor( parent )\n{\n}\n\n\nbool\nMediaPlayer2::CanQuit() const\n{\n    return true;\n}\n\n\nbool\nMediaPlayer2::CanRaise() const\n{\n    return true;\n}\n\n\nvoid\nMediaPlayer2::Raise()\n{\n    aApp->showWindow();\n}\n\n\nvoid\nMediaPlayer2::Quit()\n{\n    aApp->quit();\n}\n\n\nbool\nMediaPlayer2::HasTrackList() const\n{\n    return false;\n}\n\n\nQString\nMediaPlayer2::Identity() const\n{\n    return aApp->applicationName();\n}\n\n\nQString\nMediaPlayer2::DesktopEntry() const\n{\n    return \"lastfm-scrobbler\";\n}\n\n\nQStringList\nMediaPlayer2::SupportedUriSchemes() const\n{\n    return QStringList() << \"lastfm\";\n}\n\n\nQStringList\nMediaPlayer2::SupportedMimeTypes() const\n{\n    return QStringList();\n}\n"
  },
  {
    "path": "app/client/Mpris2/MediaPlayer2.h",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef MEDIAPLAYER2_H\n#define MEDIAPLAYER2_H\n\n#include \"DBusAbstractAdaptor.h\"\n\nclass MediaPlayer2 : public DBusAbstractAdaptor\n{\n    Q_OBJECT\n    Q_CLASSINFO(\"D-Bus Interface\", \"org.mpris.MediaPlayer2\");\n\n    Q_PROPERTY( bool CanQuit READ CanQuit )\n    Q_PROPERTY( bool CanRaise READ CanRaise )\n    Q_PROPERTY( bool HasTrackList READ HasTrackList )\n    Q_PROPERTY( QString Identity READ Identity )\n    Q_PROPERTY( QString DesktopEntry READ DesktopEntry )\n    Q_PROPERTY( QStringList SupportedUriSchemes READ SupportedUriSchemes )\n    Q_PROPERTY( QStringList SupportedMimeTypes READ SupportedMimeTypes )\n\npublic:\n    MediaPlayer2( QObject* parent );\n\n    bool CanQuit() const;\n    bool CanRaise() const;\n    bool HasTrackList() const;\n    QString Identity() const;\n    QString DesktopEntry() const;\n    QStringList SupportedUriSchemes() const;\n    QStringList SupportedMimeTypes() const;\n\npublic slots:\n    void Raise();\n    void Quit();\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Mpris2/MediaPlayer2Player.cpp",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"MediaPlayer2Player.h\"\n#include \"Application.h\"\n\n#include <lastfm/AbstractType.h>\n#include <lastfm/User.h>\n#include <phonon/mediaobject.h>\n\n#include \"../Services/RadioService.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n\nMediaPlayer2Player::MediaPlayer2Player( QObject* parent ) : DBusAbstractAdaptor( parent )\n{\n    m_playbackState = Stopped;\n    connect( &RadioService::instance(), SIGNAL(paused()),  SLOT(onPlaybackStateChanged()) );\n    connect( &RadioService::instance(), SIGNAL(buffering(int)),  SLOT(onPlaybackStateChanged()) );\n    connect( &RadioService::instance(), SIGNAL(stopped()), SLOT(onPlaybackStateChanged()) );\n    connect( &RadioService::instance(), SIGNAL(resumed()), SLOT(onPlaybackStateChanged()) );\n    connect( &RadioService::instance(), SIGNAL(trackSpooled( const Track& )), SLOT(onTrackChanged( const Track& )) );\n    connect( &aApp->currentSession(), SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionInfo()) );\n    if ( RadioService::instance().audioOutput() )\n    {\n        connect( RadioService::instance().audioOutput(), SIGNAL(volumeChanged( qreal )), SLOT(onVolumeChanged( qreal )) );\n    }\n}\n\n\n// Properties\n\nQString\nMediaPlayer2Player::PlaybackStatus() const\n{\n    switch (m_playbackState)\n    {\n        case Playing:\n            return \"Playing\";\n        case Paused:\n            return \"Paused\";\n        default:\n            return \"Stopped\";\n    }\n}\n\n\ndouble\nMediaPlayer2Player::Rate() const\n{\n    return 1.0;\n}\n\n\nvoid\nMediaPlayer2Player::SetRate( double )\n{\n}\n\n\nQVariantMap\nMediaPlayer2Player::Metadata() const\n{\n    QVariantMap metaData;\n    if ( m_track.isNull() )\n        return metaData;\n\n    metaData[\"mpris:trackid\"] = QVariant::fromValue<QDBusObjectPath>(\n                                    QDBusObjectPath( \"/fm/last/scrobbler/\" + QString::number( m_track.timestamp().toTime_t() ) ) );\n    metaData[\"mpris:length\"] = static_cast<qint64>(m_track.duration() * 1000000);\n    if ( !m_track.imageUrl( AbstractType::LargeImage, true ).toString().isEmpty() )\n        metaData[\"mpris:artUrl\"] = m_track.imageUrl( AbstractType::LargeImage, true ).toString();\n    if ( !m_track.album().title().isEmpty() )\n        metaData[\"xesam:album\"] = m_track.album().title();\n    if ( ! m_track.albumArtist().name().isEmpty() )\n        metaData[\"xesam:albumArtist\"] = QStringList() << m_track.albumArtist().name();\n    metaData[\"xesam:artist\"] = QStringList() << m_track.artist().name();\n    // xesam:asText\n    // xesam:audioBPM\n    // xesam:autoRating\n    // xesam:comment\n    // xesam:composer\n    // xesam:contentCreated\n    // xesam:discNumber\n    // xesam:firstUsed\n    // xesam:genre\n    // xesam:lastUsed\n    // xesam:lyricist\n    metaData[\"xesam:title\"] = m_track.title();\n    if ( m_track.trackNumber() > 0 )\n        metaData[\"xesam:trackNumber\"] = m_track.trackNumber();\n    metaData[\"xesam:url\"] = m_track.url().toString();\n    // xesam:useCount\n    // xesam:userRating\n\n    return metaData;\n}\n\n\ndouble\nMediaPlayer2Player::Volume() const\n{\n    if ( RadioService::instance().audioOutput() )\n        return RadioService::instance().audioOutput()->volume();\n    else\n        return 0;\n}\n\n\nvoid\nMediaPlayer2Player::SetVolume( double vol )\n{\n    if ( vol < 0.0 )\n        vol = 0.0;\n    else if ( vol > 1.0 )\n        vol = 1.0;\n    if ( RadioService::instance().audioOutput() )\n        RadioService::instance().audioOutput()->setVolume( vol );\n}\n\n\nqlonglong\nMediaPlayer2Player::Position() const\n{\n    if ( RadioService::instance().mediaObject() )\n        return RadioService::instance().mediaObject()->currentTime() * 1000;\n    else\n        return 0;\n}\n\n\ndouble\nMediaPlayer2Player::MinimumRate() const\n{\n    return 1.0;\n}\n\n\ndouble\nMediaPlayer2Player::MaximumRate() const\n{\n    return 1.0;\n}\n\n\nbool\nMediaPlayer2Player::CanGoNext() const\n{\n    if ( m_playbackState == Playing || m_playbackState == Paused )\n        return true;\n    else\n        return false;\n}\n\n\nbool\nMediaPlayer2Player::CanGoPrevious() const\n{\n    return false;\n}\n\n\nbool\nMediaPlayer2Player::CanPlay() const\n{\n    if ( !aApp->currentSession().youRadio() )\n        return false;\n    else\n        return true;\n}\n\n\nbool\nMediaPlayer2Player::CanPause() const\n{\n    if ( m_playbackState == Playing || m_playbackState == Paused )\n        return true;\n    else\n        return false;\n}\n\n\nbool\nMediaPlayer2Player::CanSeek() const\n{\n    return false;\n}\n\n\nbool\nMediaPlayer2Player::CanControl() const\n{\n    return true;\n}\n\n\n// Methods\n\nvoid\nMediaPlayer2Player::Next() const\n{\n    RadioService::instance().skip();\n}\n\n\nvoid\nMediaPlayer2Player::Previous() const\n{\n}\n\n\nvoid\nMediaPlayer2Player::Pause() const\n{\n    RadioService::instance().pause();\n}\n\n\nvoid\nMediaPlayer2Player::PlayPause() const\n{\n    if ( RadioService::instance().state() == Playing )\n        RadioService::instance().pause();\n    else if ( !RadioService::instance().state() != Buffering )\n        Play();\n}\n\n\nvoid\nMediaPlayer2Player::Stop() const\n{\n    RadioService::instance().stop();\n}\n\n\nvoid\nMediaPlayer2Player::Play() const\n{\n    if ( RadioService::instance().state() == Stopped )\n        RadioService::instance().play( RadioStation( \"\" ) );\n    else if ( !RadioService::instance().state() != Buffering )\n        RadioService::instance().resume();\n}\n\n\nvoid\nMediaPlayer2Player::Seek( qlonglong ) const\n{\n}\n\n\nvoid\nMediaPlayer2Player::SetPosition( const QDBusObjectPath&, qlonglong ) const\n{\n}\n\n\nvoid\nMediaPlayer2Player::OpenUri( QString uri ) const\n{\n    RadioService::instance().play( uri );\n}\n\n\n// Private slots\n\nvoid\nMediaPlayer2Player::onTrackChanged( const Track& track )\n{\n    if ( m_playbackState != Stopped )\n    {\n        m_playbackState = Stopped;\n        signalPropertyChange( \"PlaybackStatus\", PlaybackStatus() );\n        signalPropertyChange( \"CanPause\", CanPause() );\n    }\n\n    m_track = track;\n    signalPropertyChange( \"Metadata\", Metadata() );\n}\n\n\nvoid\nMediaPlayer2Player::onVolumeChanged( qreal vol )\n{\n    signalPropertyChange( \"Volume\", Volume() );\n}\n\n\nvoid\nMediaPlayer2Player::onPlaybackStateChanged()\n{\n    State teststate = RadioService::instance().state();\n    switch ( teststate )\n    {\n        case Playing:\n        case Paused:\n            break;\n        case Buffering:\n            teststate = Paused;\n            break;\n        default:\n            teststate = Stopped;\n    }\n    if ( teststate != m_playbackState )\n    {\n        m_playbackState = teststate;\n        if ( m_playbackState == Stopped )\n        {\n            m_track = Track();\n            signalPropertyChange( \"Metadata\", Metadata() );\n        }\n        signalPropertyChange( \"PlaybackStatus\", PlaybackStatus() );\n        signalPropertyChange( \"CanPause\", CanPause() );\n        signalPropertyChange( \"CanGoNext\", CanGoNext() );\n    }\n}\n\n\nvoid\nMediaPlayer2Player::onSessionInfo()\n{\n    signalPropertyChange( \"CanPlay\", CanPlay() );\n    signalPropertyChange( \"CanPause\", CanPause() );\n}\n"
  },
  {
    "path": "app/client/Mpris2/MediaPlayer2Player.h",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef MEDIAPLAYER2PLAYER_H\n#define MEDIAPLAYER2PLAYER_H\n\n#include \"DBusAbstractAdaptor.h\"\n#include \"lib/listener/State.h\"\n\n#include <QDBusObjectPath>\n#include <lastfm/Track.h>\n\nclass MediaPlayer2Player : public DBusAbstractAdaptor\n{\n    Q_OBJECT\n    Q_CLASSINFO(\"D-Bus Interface\", \"org.mpris.MediaPlayer2.Player\");\n\n    Q_PROPERTY( QString PlaybackStatus READ PlaybackStatus )\n    Q_PROPERTY( double Rate READ Rate WRITE SetRate )\n    Q_PROPERTY( QVariantMap Metadata READ Metadata )\n    Q_PROPERTY( double Volume READ Volume WRITE SetVolume )\n    Q_PROPERTY( qlonglong Position READ Position )\n    Q_PROPERTY( double MinimumRate READ MinimumRate )\n    Q_PROPERTY( double MaximumRate READ MaximumRate )\n    Q_PROPERTY( bool CanGoNext READ CanGoNext )\n    Q_PROPERTY( bool CanGoPrevious READ CanGoPrevious )\n    Q_PROPERTY( bool CanPlay READ CanPlay )\n    Q_PROPERTY( bool CanPause READ CanPause )\n    Q_PROPERTY( bool CanSeek READ CanSeek )\n    Q_PROPERTY( bool CanControl READ CanControl )\n\npublic:\n    MediaPlayer2Player( QObject* parent = 0 );\n\n    QString PlaybackStatus() const;\n    double Rate() const;\n    void SetRate(double value);\n    QVariantMap Metadata() const;\n    double Volume() const;\n    void SetVolume(double value);\n    qlonglong Position() const;\n    double MinimumRate() const;\n    double MaximumRate() const;\n    bool CanGoNext() const;\n    bool CanGoPrevious() const;\n    bool CanPlay() const;\n    bool CanPause() const;\n    bool CanSeek() const;\n    bool CanControl() const;\n\npublic slots:\n    void Next() const;\n    void Previous() const;\n    void Pause() const;\n    void PlayPause() const;\n    void Stop() const;\n    void Play() const;\n    void Seek( qlonglong Offset ) const;\n    void SetPosition( const QDBusObjectPath& TrackId, qlonglong Position ) const;\n    void OpenUri( QString Uri ) const;\n\nsignals:\n    void Seeked( qlonglong Position ) const;\n\nprivate slots:\n    void onTrackChanged( const Track& track );\n    void onVolumeChanged( qreal vol );\n    void onPlaybackStateChanged();\n    void onSessionInfo();\n\nprivate:\n    Track m_track;\n    State m_playbackState;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Mpris2/Mpris2.cpp",
    "content": "/***********************************************************************\n * Copyright 2012  Eike Hein <hein@kde.org>\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License or (at your option) version 3 or any later version\n * accepted by the membership of KDE e.V. (or its successor approved\n * by the membership of KDE e.V.), which shall act as a proxy\n * defined in Section 14 of version 3 of the license.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n ***********************************************************************/\n\n#include \"Mpris2.h\"\n\n#include \"MediaPlayer2.h\"\n#include \"MediaPlayer2Player.h\"\n\n#include <unistd.h>\n\n#include <QDBusConnection>\n\nMpris2::Mpris2( QObject *parent )\n    : QObject( parent )\n{\n    QString mpris2Name( \"org.mpris.MediaPlayer2.lastfm-scrobbler\" );\n\n    bool success = QDBusConnection::sessionBus().registerService( mpris2Name );\n\n    // If the above failed, it's likely because we're not the first instance\n    // and the name is already taken. In that event the MPRIS2 spec wants the\n    // following:\n    if (!success) {\n        mpris2Name = mpris2Name + \".instance\" + QString::number( getpid() );\n        success = QDBusConnection::sessionBus().registerService( mpris2Name );\n    }\n\n    if ( success )\n    {\n        DBusAbstractAdaptor *adaptor = new MediaPlayer2( this );\n        adaptor->setDBusPath( \"/org/mpris/MediaPlayer2\" );\n        adaptor = new MediaPlayer2Player( this );\n        adaptor->setDBusPath( \"/org/mpris/MediaPlayer2\" );\n        QDBusConnection::sessionBus().registerObject( \"/org/mpris/MediaPlayer2\", this, QDBusConnection::ExportAdaptors );\n    }\n}\n\nMpris2::~Mpris2()\n{\n}\n\n"
  },
  {
    "path": "app/client/Mpris2/Mpris2.h",
    "content": "/***********************************************************************\n * Copyright 2012  Eike Hein <hein@kde.org>\n *\n * This program is free software; you can redistribute it and/or\n * modify it under the terms of the GNU General Public License as\n * published by the Free Software Foundation; either version 2 of\n * the License or (at your option) version 3 or any later version\n * accepted by the membership of KDE e.V. (or its successor approved\n * by the membership of KDE e.V.), which shall act as a proxy\n * defined in Section 14 of version 3 of the license.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n ***********************************************************************/\n\n#ifndef MPRIS2_H\n#define MPRIS2_H\n\n#include <QObject>\n\nclass Mpris2 : public QObject\n{\n    Q_OBJECT\n\n    public:\n        explicit Mpris2( QObject *parent = 0 );\n        ~Mpris2();\n};\n\n#endif // MPRIS2_H\n"
  },
  {
    "path": "app/client/PrefPane/English.lproj/MainWindow.xib",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<archive type=\"com.apple.InterfaceBuilder3.Cocoa.XIB\" version=\"7.03\">\n\t<data>\n\t\t<int key=\"IBDocument.SystemTarget\">1050</int>\n\t\t<string key=\"IBDocument.SystemVersion\">9L31a</string>\n\t\t<string key=\"IBDocument.InterfaceBuilderVersion\">677</string>\n\t\t<string key=\"IBDocument.AppKitVersion\">949.54</string>\n\t\t<string key=\"IBDocument.HIToolboxVersion\">353.00</string>\n\t\t<object class=\"NSMutableArray\" key=\"IBDocument.EditedObjectIDs\">\n\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t<integer value=\"372\"/>\n\t\t</object>\n\t\t<object class=\"NSArray\" key=\"IBDocument.PluginDependencies\">\n\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t<string>com.apple.InterfaceBuilderKit</string>\n\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t</object>\n\t\t<object class=\"NSMutableDictionary\" key=\"IBDocument.Metadata\">\n\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t<object class=\"NSArray\" key=\"dict.sortedKeys\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t</object>\n\t\t\t<object class=\"NSMutableArray\" key=\"dict.values\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t</object>\n\t\t</object>\n\t\t<object class=\"NSMutableArray\" key=\"IBDocument.RootObjects\" id=\"1048\">\n\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t<object class=\"NSCustomObject\" id=\"1021\">\n\t\t\t\t<string key=\"NSClassName\">FmLastPrefPane</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSCustomObject\" id=\"1014\">\n\t\t\t\t<string key=\"NSClassName\">FirstResponder</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSCustomObject\" id=\"1050\">\n\t\t\t\t<string key=\"NSClassName\">NSApplication</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSWindowTemplate\" id=\"972006081\">\n\t\t\t\t<int key=\"NSWindowStyleMask\">15</int>\n\t\t\t\t<int key=\"NSWindowBacking\">2</int>\n\t\t\t\t<string key=\"NSWindowRect\">{{335, 244}, {668, 506}}</string>\n\t\t\t\t<int key=\"NSWTFlags\">1946157056</int>\n\t\t\t\t<string key=\"NSWindowTitle\">Window</string>\n\t\t\t\t<string key=\"NSWindowClass\">NSWindow</string>\n\t\t\t\t<nil key=\"NSViewClass\"/>\n\t\t\t\t<string key=\"NSWindowContentMaxSize\">{3.40282e+38, 3.40282e+38}</string>\n\t\t\t\t<object class=\"NSView\" key=\"NSWindowView\" id=\"439893737\">\n\t\t\t\t\t<reference key=\"NSNextResponder\"/>\n\t\t\t\t\t<int key=\"NSvFlags\">256</int>\n\t\t\t\t\t<object class=\"NSMutableArray\" key=\"NSSubviews\">\n\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t<object class=\"NSCustomView\" id=\"890190615\">\n\t\t\t\t\t\t\t<reference key=\"NSNextResponder\" ref=\"439893737\"/>\n\t\t\t\t\t\t\t<int key=\"NSvFlags\">45</int>\n\t\t\t\t\t\t\t<string key=\"NSFrame\">{{20, 20}, {628, 466}}</string>\n\t\t\t\t\t\t\t<reference key=\"NSSuperview\" ref=\"439893737\"/>\n\t\t\t\t\t\t\t<string key=\"NSClassName\">FmLastPrefPaneQtView</string>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t</object>\n\t\t\t\t\t<string key=\"NSFrameSize\">{668, 506}</string>\n\t\t\t\t\t<reference key=\"NSSuperview\"/>\n\t\t\t\t\t<bool key=\"NSViewIsLayerTreeHost\">YES</bool>\n\t\t\t\t</object>\n\t\t\t\t<string key=\"NSScreenRect\">{{0, 0}, {1440, 878}}</string>\n\t\t\t\t<string key=\"NSMaxSize\">{3.40282e+38, 3.40282e+38}</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSCustomObject\" id=\"755631768\">\n\t\t\t\t<string key=\"NSClassName\">NSFontManager</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSCustomObject\" id=\"492520238\">\n\t\t\t\t<string key=\"NSClassName\">AppDelegate</string>\n\t\t\t</object>\n\t\t\t<object class=\"NSCustomObject\" id=\"48424499\">\n\t\t\t\t<string key=\"NSClassName\">FmLastPrefPane</string>\n\t\t\t</object>\n\t\t</object>\n\t\t<object class=\"IBObjectContainer\" key=\"IBDocument.Objects\">\n\t\t\t<object class=\"NSMutableArray\" key=\"connectionRecords\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"IBConnectionRecord\">\n\t\t\t\t\t<object class=\"IBOutletConnection\" key=\"connection\">\n\t\t\t\t\t\t<string key=\"label\">delegate</string>\n\t\t\t\t\t\t<reference key=\"source\" ref=\"1050\"/>\n\t\t\t\t\t\t<reference key=\"destination\" ref=\"492520238\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<int key=\"connectionID\">454</int>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"IBConnectionRecord\">\n\t\t\t\t\t<object class=\"IBOutletConnection\" key=\"connection\">\n\t\t\t\t\t\t<string key=\"label\">_window</string>\n\t\t\t\t\t\t<reference key=\"source\" ref=\"1021\"/>\n\t\t\t\t\t\t<reference key=\"destination\" ref=\"972006081\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<int key=\"connectionID\">460</int>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"IBConnectionRecord\">\n\t\t\t\t\t<object class=\"IBOutletConnection\" key=\"connection\">\n\t\t\t\t\t\t<string key=\"label\">_window</string>\n\t\t\t\t\t\t<reference key=\"source\" ref=\"48424499\"/>\n\t\t\t\t\t\t<reference key=\"destination\" ref=\"972006081\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<int key=\"connectionID\">462</int>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"IBConnectionRecord\">\n\t\t\t\t\t<object class=\"IBOutletConnection\" key=\"connection\">\n\t\t\t\t\t\t<string key=\"label\">qtView</string>\n\t\t\t\t\t\t<reference key=\"source\" ref=\"48424499\"/>\n\t\t\t\t\t\t<reference key=\"destination\" ref=\"890190615\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<int key=\"connectionID\">463</int>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<object class=\"IBMutableOrderedSet\" key=\"objectRecords\">\n\t\t\t\t<object class=\"NSArray\" key=\"orderedObjects\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">0</int>\n\t\t\t\t\t\t<object class=\"NSArray\" key=\"object\" id=\"1049\">\n\t\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t\t<reference key=\"children\" ref=\"1048\"/>\n\t\t\t\t\t\t<nil key=\"parent\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">-2</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"1021\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t\t<string type=\"base64-UTF8\" key=\"objectName\">RmlsZSdzIE93bmVyA</string>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">-1</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"1014\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t\t<string key=\"objectName\">First Responder</string>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">-3</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"1050\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t\t<string key=\"objectName\">Application</string>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">371</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"972006081\"/>\n\t\t\t\t\t\t<object class=\"NSMutableArray\" key=\"children\">\n\t\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t\t<reference ref=\"439893737\"/>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">372</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"439893737\"/>\n\t\t\t\t\t\t<object class=\"NSMutableArray\" key=\"children\">\n\t\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t\t<reference ref=\"890190615\"/>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"972006081\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">420</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"755631768\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">456</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"890190615\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"439893737\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">453</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"492520238\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBObjectRecord\">\n\t\t\t\t\t\t<int key=\"objectID\">461</int>\n\t\t\t\t\t\t<reference key=\"object\" ref=\"48424499\"/>\n\t\t\t\t\t\t<reference key=\"parent\" ref=\"1049\"/>\n\t\t\t\t\t</object>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<object class=\"NSMutableDictionary\" key=\"flattenedProperties\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.sortedKeys\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t<string>-1.IBPluginDependency</string>\n\t\t\t\t\t<string>-2.IBPluginDependency</string>\n\t\t\t\t\t<string>-3.IBPluginDependency</string>\n\t\t\t\t\t<string>371.IBEditorWindowLastContentRect</string>\n\t\t\t\t\t<string>371.IBWindowTemplateEditedContentRect</string>\n\t\t\t\t\t<string>371.NSWindowTemplate.visibleAtLaunch</string>\n\t\t\t\t\t<string>371.editorWindowContentRectSynchronizationRect</string>\n\t\t\t\t\t<string>371.windowTemplate.maxSize</string>\n\t\t\t\t\t<string>372.IBPluginDependency</string>\n\t\t\t\t\t<string>420.IBPluginDependency</string>\n\t\t\t\t\t<string>453.IBPluginDependency</string>\n\t\t\t\t\t<string>456.IBPluginDependency</string>\n\t\t\t\t\t<string>456.IBViewIntegration.shadowBlurRadius</string>\n\t\t\t\t\t<string>456.IBViewIntegration.shadowColor</string>\n\t\t\t\t\t<string>456.IBViewIntegration.shadowOffsetHeight</string>\n\t\t\t\t\t<string>456.IBViewIntegration.shadowOffsetWidth</string>\n\t\t\t\t\t<string>461.IBPluginDependency</string>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.values\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilderKit</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilderKit</string>\n\t\t\t\t\t<string>{{392, 455}, {668, 506}}</string>\n\t\t\t\t\t<string>{{392, 455}, {668, 506}}</string>\n\t\t\t\t\t<integer value=\"1\"/>\n\t\t\t\t\t<string>{{33, 99}, {480, 360}}</string>\n\t\t\t\t\t<string>{3.40282e+38, 3.40282e+38}</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t\t<real value=\"0.000000e+00\"/>\n\t\t\t\t\t<object class=\"NSColor\">\n\t\t\t\t\t\t<int key=\"NSColorSpace\">3</int>\n\t\t\t\t\t\t<bytes key=\"NSWhite\">MAA</bytes>\n\t\t\t\t\t</object>\n\t\t\t\t\t<real value=\"0.000000e+00\"/>\n\t\t\t\t\t<real value=\"0.000000e+00\"/>\n\t\t\t\t\t<string>com.apple.InterfaceBuilder.CocoaPlugin</string>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<object class=\"NSMutableDictionary\" key=\"unlocalizedProperties\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"NSArray\" key=\"dict.sortedKeys\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.values\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<nil key=\"activeLocalization\"/>\n\t\t\t<object class=\"NSMutableDictionary\" key=\"localizations\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"NSArray\" key=\"dict.sortedKeys\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.values\">\n\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<nil key=\"sourceID\"/>\n\t\t\t<int key=\"maxID\">463</int>\n\t\t</object>\n\t\t<object class=\"IBClassDescriber\" key=\"IBDocument.Classes\">\n\t\t\t<object class=\"NSMutableArray\" key=\"referencedPartialClassDescriptions\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"IBPartialClassDescription\">\n\t\t\t\t\t<string key=\"className\">FmLastPrefPane</string>\n\t\t\t\t\t<string key=\"superclassName\">NSPreferencePane</string>\n\t\t\t\t\t<object class=\"NSMutableDictionary\" key=\"outlets\">\n\t\t\t\t\t\t<string key=\"NS.key.0\">qtView</string>\n\t\t\t\t\t\t<string key=\"NS.object.0\">FmLastPrefPaneQtView</string>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBClassDescriptionSource\" key=\"sourceIdentifier\">\n\t\t\t\t\t\t<string key=\"majorKey\">IBProjectSource</string>\n\t\t\t\t\t\t<string key=\"minorKey\">FmLastPrefPane.h</string>\n\t\t\t\t\t</object>\n\t\t\t\t</object>\n\t\t\t\t<object class=\"IBPartialClassDescription\">\n\t\t\t\t\t<string key=\"className\">FmLastPrefPaneQtView</string>\n\t\t\t\t\t<string key=\"superclassName\">NSView</string>\n\t\t\t\t\t<object class=\"IBClassDescriptionSource\" key=\"sourceIdentifier\">\n\t\t\t\t\t\t<string key=\"majorKey\">IBProjectSource</string>\n\t\t\t\t\t\t<string key=\"minorKey\">FmLastPrefPaneQtView.h</string>\n\t\t\t\t\t</object>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t\t<object class=\"NSMutableArray\" key=\"referencedPartialClassDescriptionsV3.1+\">\n\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t<object class=\"IBPartialClassDescription\">\n\t\t\t\t\t<string key=\"className\">NSPreferencePane</string>\n\t\t\t\t\t<string key=\"superclassName\">NSObject</string>\n\t\t\t\t\t<object class=\"NSMutableDictionary\" key=\"outlets\">\n\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.sortedKeys\">\n\t\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t\t<string>_firstKeyView</string>\n\t\t\t\t\t\t\t<string>_initialKeyView</string>\n\t\t\t\t\t\t\t<string>_lastKeyView</string>\n\t\t\t\t\t\t\t<string>_window</string>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t\t<object class=\"NSMutableArray\" key=\"dict.values\">\n\t\t\t\t\t\t\t<bool key=\"EncodedWithXMLCoder\">YES</bool>\n\t\t\t\t\t\t\t<string>NSView</string>\n\t\t\t\t\t\t\t<string>NSView</string>\n\t\t\t\t\t\t\t<string>NSView</string>\n\t\t\t\t\t\t\t<string>NSWindow</string>\n\t\t\t\t\t\t</object>\n\t\t\t\t\t</object>\n\t\t\t\t\t<object class=\"IBClassDescriptionSource\" key=\"sourceIdentifier\">\n\t\t\t\t\t\t<string key=\"majorKey\">IBDocumentRelativeSource</string>\n\t\t\t\t\t\t<string key=\"minorKey\">../../../../../../../../../System/Library/Frameworks/PreferencePanes.framework/Versions/A/Headers/NSPreferencePane.h</string>\n\t\t\t\t\t</object>\n\t\t\t\t</object>\n\t\t\t</object>\n\t\t</object>\n\t\t<int key=\"IBDocument.localizationMode\">0</int>\n\t\t<string key=\"IBDocument.LastKnownRelativeProjectPath\">../PrefPane.xcodeproj</string>\n\t\t<int key=\"IBDocument.defaultPropertyAccessControl\">3</int>\n\t</data>\n</archive>\n"
  },
  {
    "path": "app/client/PrefPane/FmLastPrefPane.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#import <Cocoa/Cocoa.h>\n#import <PreferencePanes/PreferencePanes.h>\n#import \"FmLastPrefPaneQtView.h\"\n\n@interface FmLastPrefPane : NSPreferencePane {\n    IBOutlet FmLastPrefPaneQtView* qtView;\n}\n\n- (void)mainViewDidLoad;\n- (void)didSelect;\n@end\n"
  },
  {
    "path": "app/client/PrefPane/FmLastPrefPanePrefWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PREF_WIDGET_H_\n#define PREF_WIDGET_H_\n\n#include <Cocoa/Cocoa.h>\n#include <QtGui/QMacNativeWidget>\n\nclass FmLastPrefPanePrefWidget {\npublic:\n    FmLastPrefPanePrefWidget();\n    NSView* view();\n    QMacNativeWidget* qWidget(){ return widget; }\n    void updateGeometry();\n    \nprivate:\n    QMacNativeWidget* widget;\n    class SettingsDialog* dialog;\n};\n\n#endif //PREF_WIDGET_H_\n"
  },
  {
    "path": "app/client/PrefPane/FmLastPrefPanePrefWidget.mm",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"FmLastPrefPanePrefWidget.h\"\n#include <QApplication>\n#include <QMacNativeWidget>\n#include <QLabel>\n#include <QVBoxLayout>\n#include <QPalette>\n#include <QColorDialog>\n#include <QListWidget>\n#include \"../Dialogs/SettingsDialog.h\"\n#include <lastfm/ws.h>\n#include \"../../../lib/unicorn/UnicornApplication.h\"\n#include <QDebug>\n\nclass MySettingsDialog : public SettingsDialog {\npublic:\n    MySettingsDialog( QWidget* p = 0 )\n    :SettingsDialog( p ){ setWindowFlags( Qt::Widget ); ui.pageList->setCurrentRow( 2 ); setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed);}\n    \n//    virtual QSize sizeHint() const {\n//        NSView* nsv = reinterpret_cast<NSView*>(winId());\n//        return QSize( [[[nsv superview] superview] frame].size.width, [[[nsv superview] superview] frame].size.height );\n//    }\n    \nprotected:\n    virtual bool eventFilter(QObject *obj, QEvent *ev) {\n        \n        if( ev->type() == QEvent::Resize ) {\n//            updateGeometry();\n            NSView* nsv = reinterpret_cast<NSView*>(winId());\n            layout()->update();\n            if( [nsv window] )\n                [nsv setFrameSize: [[[nsv superview] superview] frame].size ];\n        }\n        return false;\n    }\n};\n\nFmLastPrefPanePrefWidget::FmLastPrefPanePrefWidget()\n                         :dialog( 0 ), \n                          widget( 0 )\n{\n    char* argv;\n    int argc = 0;\n    unicorn::Application* app = new unicorn::Application( argc, &argv );\n    QCoreApplication::arguments();\n    widget = new QMacNativeWidget();\n    QBoxLayout* layout = new QVBoxLayout( widget );\n\n    layout->addWidget( dialog = new MySettingsDialog( widget ) );\n    \n    foreach( QWidget* w, dialog->findChildren<QWidget*>()) {\n        w->installEventFilter( dialog );\n        w->show();\n    }\n    \n    NSWindow *systemPrefsWindow = [[NSApplication sharedApplication] mainWindow];\n    [reinterpret_cast<NSView*>(dialog->winId()) setFrame: [systemPrefsWindow contentRectForFrameRect:[systemPrefsWindow frame]]];\n    [reinterpret_cast<NSView*>(widget->winId()) setAutoresizingMask: NSViewWidthSizable ];\n\n    widget->layout()->setContentsMargins( 0, 0, 0, 0 );\n    widget->layout()->setSpacing( 0 );\n\n    dialog->setAutoFillBackground( true );\n    \n    \n    widget->show();\n}\n\nNSView* \nFmLastPrefPanePrefWidget::view()\n{\n    qDebug() << \"Getting view..\";\n    \n    const WId id = widget->winId();\n    const NSView* ret = reinterpret_cast<NSView*>(id);\n    \n//    widget->layout()->update();\n    return ret;\n}\n\nvoid \nFmLastPrefPanePrefWidget::updateGeometry()\n{\n    if( this && dialog )\n        dialog->updateGeometry();\n}\n"
  },
  {
    "path": "app/client/PrefPane/FmLastPrefPaneQtView.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#import <Cocoa/Cocoa.h>\n\n@interface FmLastPrefPaneQtView : NSView {\n    class FmLastPrefPanePrefWidget* pw;\n}\n\n- (id) initWithFrame:(NSRect)frameRect;\n- (void) drawRect:(NSRect)rect;\n- (FmLastPrefPanePrefWidget*) prefWidget;\n\n@end\n"
  },
  {
    "path": "app/client/PrefPane/FmLastPrefPaneQtView.mm",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#import \"FmLastPrefPaneQtView.h\"\n#include \"FmLastPrefPanePrefWidget.h\"\n\n@implementation FmLastPrefPaneQtView\n\n- (id) initWithFrame:(NSRect)frameRect {\n    [super initWithFrame: frameRect];\n    \n    pw = new FmLastPrefPanePrefWidget;\n    NSView* pwView = pw->view();\n    [self addSubview: pwView positioned:NSWindowAbove relativeTo:nil];\n//    [pwView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];\n//    [pwView setAutoresizesSubviews:YES];\n\n    [self drawRect: [self frame]];\n    return self;\n}\n\n- (void) drawRect:(NSRect)rect {\n    NSView* pwView = pw->view();\n    [pwView setFrameOrigin: NSMakePoint( 0, [self frame].size.height - [pwView frame].size.height)];\n    [pwView setFrameSize: [self frame].size];    \n    \n    [super drawRect: rect];\n}\n\n- (FmLastPrefPanePrefWidget*) prefWidget {\n    return pw;\n}\n\n@end\n"
  },
  {
    "path": "app/client/PrefPane/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>fm.last.prefpane</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>${PRODUCT_NAME}</string>\n\t<key>CFBundlePackageType</key>\n\t<string>BNDL</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1.0</string>\n\t<key>NSPrefPaneIconLabel</key>\n\t<string>Last.fm</string>\n\t<key>NSPrefPaneIconFile</key>\n\t<string>icon.png</string>\n\t<key>NSMainNibFile</key>\n\t<string>MainWindow</string>\n\t<key>NSPrincipalClass</key>\n\t<string>FmLastPrefPane</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "app/client/PrefPane/PrefPane.pro",
    "content": "TEMPLATE = app\n\ndebug {\n    pp.commands = xcodebuild -project PrefPane.xcodeproj -configuration Debug\n}\n\nrelease {\n    pp.commands = xcodebuild -project PrefPane.xcodeproj -configuration Release\n}\n\npp.target=PrefPane.prefpane\n\nQMAKE_CLEAN = -r build\n\n# Disable the linker:\nQMAKE_LINK=@\\\\$$LITERAL_HASH\n\nCONFIG-=app_bundle\nCONFIG+=lib_bundle\nOBJECTS_DIR=.\n\nQMAKE_BUNDLE_EXTENSION=.prefpane\ndebug:TARGET=Scrobbler_debug.prefpane\nrelease:TARGET=Scrobbler.prefpane\n\nQMAKE_EXTRA_TARGETS = pp\nPRE_TARGETDEPS = $$pp.target\n\n"
  },
  {
    "path": "app/client/PrefPane/PrefPane.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 45;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C167DFE841241C02AAC07 /* InfoPlist.strings */; };\n\t\t8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */; };\n\t\tFB2089DD11ECD211004CA2E5 /* icon.png in Resources */ = {isa = PBXBuildFile; fileRef = FB2089DC11ECD211004CA2E5 /* icon.png */; };\n\t\tFB208A0C11EF15A8004CA2E5 /* FmLastPrefPane.mm in Sources */ = {isa = PBXBuildFile; fileRef = FB208A0A11EF15A8004CA2E5 /* FmLastPrefPane.mm */; };\n\t\tFBA446ED11EC9EDF005DA6BB /* FmLastPrefPaneQtView.mm in Sources */ = {isa = PBXBuildFile; fileRef = FBA446EA11EC9EDF005DA6BB /* FmLastPrefPaneQtView.mm */; };\n\t\tFBA446EE11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.mm in Sources */ = {isa = PBXBuildFile; fileRef = FBA446EC11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.mm */; };\n\t\tFBA446F211EC9F46005DA6BB /* PreferencePanes.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FBA446F111EC9F46005DA6BB /* PreferencePanes.framework */; };\n\t\tFBA446FB11ECBFC8005DA6BB /* MainWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = FBA446F911ECBFC8005DA6BB /* MainWindow.xib */; };\n\t\tFBA4470211ECBFE9005DA6BB /* QtCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FBA4470011ECBFE9005DA6BB /* QtCore.framework */; };\n\t\tFBA4470311ECBFE9005DA6BB /* QtGui.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FBA4470111ECBFE9005DA6BB /* QtGui.framework */; };\n\t\tFBD4837111FA088F00B21E5A /* moc_SettingsDialog.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD4837011FA088F00B21E5A /* moc_SettingsDialog.cpp */; };\n\t\tFBD4838111FA09DC00B21E5A /* SettingsDialog.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD4838011FA09DC00B21E5A /* SettingsDialog.cpp */; };\n\t\tFBD4838611FA0A0D00B21E5A /* AccountSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD4838311FA0A0D00B21E5A /* AccountSettingsWidget.cpp */; };\n\t\tFBD4838711FA0A0D00B21E5A /* IpodSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD4838411FA0A0D00B21E5A /* IpodSettingsWidget.cpp */; };\n\t\tFBD4838811FA0A0D00B21E5A /* ScrobbleSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD4838511FA0A0D00B21E5A /* ScrobbleSettingsWidget.cpp */; };\n\t\tFBD483AE11FA0CC300B21E5A /* moc_AccountSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD483AB11FA0CC300B21E5A /* moc_AccountSettingsWidget.cpp */; };\n\t\tFBD483AF11FA0CC300B21E5A /* moc_IpodSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD483AC11FA0CC300B21E5A /* moc_IpodSettingsWidget.cpp */; };\n\t\tFBD483B011FA0CC300B21E5A /* moc_ScrobbleSettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD483AD11FA0CC300B21E5A /* moc_ScrobbleSettingsWidget.cpp */; };\n\t\tFBD483B411FA0CFE00B21E5A /* moc_SettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD483B311FA0CFE00B21E5A /* moc_SettingsWidget.cpp */; };\n\t\tFBD483B711FA0D4700B21E5A /* SettingsWidget.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FBD483B611FA0D4700B21E5A /* SettingsWidget.cpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXFileReference section */\n\t\t089C1672FE841209C02AAC07 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = \"<absolute>\"; };\n\t\t089C167EFE841241C02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = \"<group>\"; };\n\t\t089C167FFE841241C02AAC07 /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = \"<absolute>\"; };\n\t\t1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = \"<absolute>\"; };\n\t\t8D5B49B6048680CD000E48DA /* Scrobbler_debug.prefpane */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = Scrobbler_debug.prefpane; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t8D5B49B7048680CD000E48DA /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = \"<group>\"; };\n\t\tD2F7E65807B2D6F200F64583 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = /System/Library/Frameworks/CoreData.framework; sourceTree = \"<absolute>\"; };\n\t\tFB2089DC11ECD211004CA2E5 /* icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = icon.png; sourceTree = \"<group>\"; };\n\t\tFB208A0A11EF15A8004CA2E5 /* FmLastPrefPane.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FmLastPrefPane.mm; sourceTree = \"<group>\"; };\n\t\tFB208A0B11EF15A8004CA2E5 /* FmLastPrefPane.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FmLastPrefPane.h; sourceTree = \"<group>\"; };\n\t\tFBA446E911EC9EDF005DA6BB /* FmLastPrefPaneQtView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FmLastPrefPaneQtView.h; sourceTree = \"<group>\"; };\n\t\tFBA446EA11EC9EDF005DA6BB /* FmLastPrefPaneQtView.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FmLastPrefPaneQtView.mm; sourceTree = \"<group>\"; };\n\t\tFBA446EB11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FmLastPrefPanePrefWidget.h; sourceTree = \"<group>\"; };\n\t\tFBA446EC11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = FmLastPrefPanePrefWidget.mm; sourceTree = \"<group>\"; };\n\t\tFBA446F111EC9F46005DA6BB /* PreferencePanes.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = PreferencePanes.framework; path = /System/Library/Frameworks/PreferencePanes.framework; sourceTree = \"<absolute>\"; };\n\t\tFBA446FA11ECBFC8005DA6BB /* English */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = English; path = English.lproj/MainWindow.xib; sourceTree = \"<group>\"; };\n\t\tFBA4470011ECBFE9005DA6BB /* QtCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QtCore.framework; path = /opt/qt/qt.git/lib/QtCore.framework; sourceTree = \"<absolute>\"; };\n\t\tFBA4470111ECBFE9005DA6BB /* QtGui.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QtGui.framework; path = /opt/qt/qt.git/lib/QtGui.framework; sourceTree = \"<absolute>\"; };\n\t\tFBCB815F11ECCA780019E4C7 /* PrefPane_prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PrefPane_prefix.pch; sourceTree = \"<group>\"; };\n\t\tFBD4837011FA088F00B21E5A /* moc_SettingsDialog.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = moc_SettingsDialog.cpp; path = ../_build/moc_SettingsDialog.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD4838011FA09DC00B21E5A /* SettingsDialog.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SettingsDialog.cpp; path = ../Dialogs/SettingsDialog.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD4838311FA0A0D00B21E5A /* AccountSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = AccountSettingsWidget.cpp; path = ../Widgets/AccountSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD4838411FA0A0D00B21E5A /* IpodSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = IpodSettingsWidget.cpp; path = ../Widgets/IpodSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD4838511FA0A0D00B21E5A /* ScrobbleSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = ScrobbleSettingsWidget.cpp; path = ../Widgets/ScrobbleSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD483AB11FA0CC300B21E5A /* moc_AccountSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = moc_AccountSettingsWidget.cpp; path = ../_build/moc_AccountSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD483AC11FA0CC300B21E5A /* moc_IpodSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = moc_IpodSettingsWidget.cpp; path = ../_build/moc_IpodSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD483AD11FA0CC300B21E5A /* moc_ScrobbleSettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = moc_ScrobbleSettingsWidget.cpp; path = ../_build/moc_ScrobbleSettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD483B311FA0CFE00B21E5A /* moc_SettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = moc_SettingsWidget.cpp; path = ../_build/moc_SettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n\t\tFBD483B611FA0D4700B21E5A /* SettingsWidget.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = SettingsWidget.cpp; path = ../Widgets/SettingsWidget.cpp; sourceTree = SOURCE_ROOT; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t8D5B49B3048680CD000E48DA /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t8D5B49B4048680CD000E48DA /* Cocoa.framework in Frameworks */,\n\t\t\t\tFBA446F211EC9F46005DA6BB /* PreferencePanes.framework in Frameworks */,\n\t\t\t\tFBA4470211ECBFE9005DA6BB /* QtCore.framework in Frameworks */,\n\t\t\t\tFBA4470311ECBFE9005DA6BB /* QtGui.framework in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t089C166AFE841209C02AAC07 /* PrefPane */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tFBD483B611FA0D4700B21E5A /* SettingsWidget.cpp */,\n\t\t\t\tFBD4837011FA088F00B21E5A /* moc_SettingsDialog.cpp */,\n\t\t\t\tFBD483B311FA0CFE00B21E5A /* moc_SettingsWidget.cpp */,\n\t\t\t\tFBD483AB11FA0CC300B21E5A /* moc_AccountSettingsWidget.cpp */,\n\t\t\t\tFBD483AC11FA0CC300B21E5A /* moc_IpodSettingsWidget.cpp */,\n\t\t\t\tFBD483AD11FA0CC300B21E5A /* moc_ScrobbleSettingsWidget.cpp */,\n\t\t\t\t08FB77AFFE84173DC02AAC07 /* Classes */,\n\t\t\t\t32C88E010371C26100C91783 /* Other Sources */,\n\t\t\t\t089C167CFE841241C02AAC07 /* Resources */,\n\t\t\t\t089C1671FE841209C02AAC07 /* Frameworks and Libraries */,\n\t\t\t\t19C28FB8FE9D52D311CA2CBB /* Products */,\n\t\t\t);\n\t\t\tname = PrefPane;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t089C1671FE841209C02AAC07 /* Frameworks and Libraries */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */,\n\t\t\t\t1058C7AEFEA557BF11CA2CBB /* Other Frameworks */,\n\t\t\t);\n\t\t\tname = \"Frameworks and Libraries\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t089C167CFE841241C02AAC07 /* Resources */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tFB2089DC11ECD211004CA2E5 /* icon.png */,\n\t\t\t\tFBA446F911ECBFC8005DA6BB /* MainWindow.xib */,\n\t\t\t\t8D5B49B7048680CD000E48DA /* Info.plist */,\n\t\t\t\t089C167DFE841241C02AAC07 /* InfoPlist.strings */,\n\t\t\t);\n\t\t\tname = Resources;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t08FB77AFFE84173DC02AAC07 /* Classes */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tFBD4838311FA0A0D00B21E5A /* AccountSettingsWidget.cpp */,\n\t\t\t\tFBD4838411FA0A0D00B21E5A /* IpodSettingsWidget.cpp */,\n\t\t\t\tFBD4838511FA0A0D00B21E5A /* ScrobbleSettingsWidget.cpp */,\n\t\t\t\tFBD4838011FA09DC00B21E5A /* SettingsDialog.cpp */,\n\t\t\t\tFBA446E911EC9EDF005DA6BB /* FmLastPrefPaneQtView.h */,\n\t\t\t\tFBA446EA11EC9EDF005DA6BB /* FmLastPrefPaneQtView.mm */,\n\t\t\t\tFBA446EB11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.h */,\n\t\t\t\tFBA446EC11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.mm */,\n\t\t\t\tFB208A0A11EF15A8004CA2E5 /* FmLastPrefPane.mm */,\n\t\t\t\tFB208A0B11EF15A8004CA2E5 /* FmLastPrefPane.h */,\n\t\t\t);\n\t\t\tname = Classes;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t1058C7ACFEA557BF11CA2CBB /* Linked Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tFBA4470011ECBFE9005DA6BB /* QtCore.framework */,\n\t\t\t\tFBA4470111ECBFE9005DA6BB /* QtGui.framework */,\n\t\t\t\tFBA446F111EC9F46005DA6BB /* PreferencePanes.framework */,\n\t\t\t\t1058C7ADFEA557BF11CA2CBB /* Cocoa.framework */,\n\t\t\t);\n\t\t\tname = \"Linked Frameworks\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t1058C7AEFEA557BF11CA2CBB /* Other Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t089C167FFE841241C02AAC07 /* AppKit.framework */,\n\t\t\t\tD2F7E65807B2D6F200F64583 /* CoreData.framework */,\n\t\t\t\t089C1672FE841209C02AAC07 /* Foundation.framework */,\n\t\t\t);\n\t\t\tname = \"Other Frameworks\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t19C28FB8FE9D52D311CA2CBB /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t8D5B49B6048680CD000E48DA /* Scrobbler_debug.prefpane */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t32C88E010371C26100C91783 /* Other Sources */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tFBCB815F11ECCA780019E4C7 /* PrefPane_prefix.pch */,\n\t\t\t);\n\t\t\tname = \"Other Sources\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXNativeTarget section */\n\t\t8D5B49AC048680CD000E48DA /* PrefPane */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 1DEB913A08733D840010E9CD /* Build configuration list for PBXNativeTarget \"PrefPane\" */;\n\t\t\tbuildPhases = (\n\t\t\t\t8D5B49AF048680CD000E48DA /* Resources */,\n\t\t\t\t8D5B49B1048680CD000E48DA /* Sources */,\n\t\t\t\t8D5B49B3048680CD000E48DA /* Frameworks */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = PrefPane;\n\t\t\tproductInstallPath = \"$(HOME)/Library/Bundles\";\n\t\t\tproductName = PrefPane;\n\t\t\tproductReference = 8D5B49B6048680CD000E48DA /* Scrobbler_debug.prefpane */;\n\t\t\tproductType = \"com.apple.product-type.bundle\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t089C1669FE841209C02AAC07 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tbuildConfigurationList = 1DEB913E08733D840010E9CD /* Build configuration list for PBXProject \"PrefPane\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.1\";\n\t\t\thasScannedForEncodings = 1;\n\t\t\tmainGroup = 089C166AFE841209C02AAC07 /* PrefPane */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t8D5B49AC048680CD000E48DA /* PrefPane */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t8D5B49AF048680CD000E48DA /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t8D5B49B0048680CD000E48DA /* InfoPlist.strings in Resources */,\n\t\t\t\tFBA446FB11ECBFC8005DA6BB /* MainWindow.xib in Resources */,\n\t\t\t\tFB2089DD11ECD211004CA2E5 /* icon.png in Resources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t8D5B49B1048680CD000E48DA /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\tFBA446ED11EC9EDF005DA6BB /* FmLastPrefPaneQtView.mm in Sources */,\n\t\t\t\tFBA446EE11EC9EDF005DA6BB /* FmLastPrefPanePrefWidget.mm in Sources */,\n\t\t\t\tFB208A0C11EF15A8004CA2E5 /* FmLastPrefPane.mm in Sources */,\n\t\t\t\tFBD4837111FA088F00B21E5A /* moc_SettingsDialog.cpp in Sources */,\n\t\t\t\tFBD4838111FA09DC00B21E5A /* SettingsDialog.cpp in Sources */,\n\t\t\t\tFBD4838611FA0A0D00B21E5A /* AccountSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD4838711FA0A0D00B21E5A /* IpodSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD4838811FA0A0D00B21E5A /* ScrobbleSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD483AE11FA0CC300B21E5A /* moc_AccountSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD483AF11FA0CC300B21E5A /* moc_IpodSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD483B011FA0CC300B21E5A /* moc_ScrobbleSettingsWidget.cpp in Sources */,\n\t\t\t\tFBD483B411FA0CFE00B21E5A /* moc_SettingsWidget.cpp in Sources */,\n\t\t\t\tFBD483B711FA0D4700B21E5A /* SettingsWidget.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin PBXVariantGroup section */\n\t\t089C167DFE841241C02AAC07 /* InfoPlist.strings */ = {\n\t\t\tisa = PBXVariantGroup;\n\t\t\tchildren = (\n\t\t\t\t089C167EFE841241C02AAC07 /* English */,\n\t\t\t);\n\t\t\tname = InfoPlist.strings;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tFBA446F911ECBFC8005DA6BB /* MainWindow.xib */ = {\n\t\t\tisa = PBXVariantGroup;\n\t\t\tchildren = (\n\t\t\t\tFBA446FA11ECBFC8005DA6BB /* English */,\n\t\t\t);\n\t\t\tname = MainWindow.xib;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXVariantGroup section */\n\n/* Begin XCBuildConfiguration section */\n\t\t1DEB913B08733D840010E9CD /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t/opt/qt/qt.git/lib,\n\t\t\t\t);\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_ENABLE_FIX_AND_CONTINUE = YES;\n\t\t\t\tGCC_MODEL_TUNING = G5;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PRECOMPILE_PREFIX_HEADER = YES;\n\t\t\t\tGCC_PREFIX_HEADER = PrefPane_Prefix.pch;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t\"/opt/qt/qt-current/include/**\",\n\t\t\t\t\t/opt/local/include,\n\t\t\t\t\t../../..,\n\t\t\t\t);\n\t\t\t\tINFOPLIST_FILE = Info.plist;\n\t\t\t\tINSTALL_PATH = \"$(HOME)/Library/Bundles\";\n\t\t\t\tLIBRARY_SEARCH_PATHS = /opt/local/lib;\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"-llastfm\",\n\t\t\t\t\t\"-lunicorn\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_NAME = Scrobbler_debug;\n\t\t\t\tWRAPPER_EXTENSION = prefpane;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t1DEB913C08733D840010E9CD /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t/opt/qt/qt.git/lib,\n\t\t\t\t);\n\t\t\t\tGCC_MODEL_TUNING = G5;\n\t\t\t\tGCC_PRECOMPILE_PREFIX_HEADER = YES;\n\t\t\t\tGCC_PREFIX_HEADER = PrefPane_Prefix.pch;\n\t\t\t\tINFOPLIST_FILE = Info.plist;\n\t\t\t\tINSTALL_PATH = \"$(HOME)/Library/Bundles\";\n\t\t\t\tPRODUCT_NAME = Scrobbler;\n\t\t\t\tWRAPPER_EXTENSION = prefpane;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t1DEB913F08733D840010E9CD /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\n\t\t\t\tBUNDLE_LOADER = \"/Applications/System Preferences.app/Contents/MacOS/System Preferences\";\n\t\t\t\tCONFIGURATION_BUILD_DIR = ../../../_bin;\n\t\t\t\tEXECUTABLE_EXTENSION = \"\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = c99;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tINFOPLIST_PREPROCESS = YES;\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.4;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tPREBINDING = NO;\n\t\t\t\tPRELINK_LIBS = \"\";\n\t\t\t\tPRODUCT_NAME = Audioscrobbler;\n\t\t\t\tSDKROOT = macosx10.4;\n\t\t\t\tWRAPPER_EXTENSION = prefpane;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t1DEB914008733D840010E9CD /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\n\t\t\t\tCONFIGURATION_BUILD_DIR = ../../../_bin;\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = c99;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = (\n\t\t\t\t\t../../../,\n\t\t\t\t\t\"/opt/qt/qt-current/include/QtGui\",\n\t\t\t\t);\n\t\t\t\tPREBINDING = NO;\n\t\t\t\tSDKROOT = macosx10.4;\n\t\t\t\tUSER_HEADER_SEARCH_PATHS = \"\";\n\t\t\t\tWRAPPER_EXTENSION = prefpane;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t1DEB913A08733D840010E9CD /* Build configuration list for PBXNativeTarget \"PrefPane\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t1DEB913B08733D840010E9CD /* Debug */,\n\t\t\t\t1DEB913C08733D840010E9CD /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t1DEB913E08733D840010E9CD /* Build configuration list for PBXProject \"PrefPane\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t1DEB913F08733D840010E9CD /* Debug */,\n\t\t\t\t1DEB914008733D840010E9CD /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 089C1669FE841209C02AAC07 /* Project object */;\n}\n"
  },
  {
    "path": "app/client/PrefPane/PrefPane_prefix.pch",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n"
  },
  {
    "path": "app/client/ScrobSocket.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ScrobSocket.h\"\n#include <QThread>\n#include <QHostAddress>\n#include <QUrl>\n#include <QTextStream>\n\n#ifdef WIN32\n    #include \"common/c++/win/scrobSubPipeName.cpp\"\n#endif\n\n\nScrobSocket::ScrobSocket( const QString& clientId, QObject* parent ) \n: QLocalSocket( parent )\n, m_bInConnect( false )\n, m_clientId( clientId )\n{\n    connect( this, SIGNAL(readyRead()), SLOT(onReadyRead()) );    \n    connect( this, SIGNAL(error( QLocalSocket::LocalSocketError )), SLOT(onError( QLocalSocket::LocalSocketError )) );\n    connect( this, SIGNAL(connected()), SLOT(onConnected()) );\n    connect( this, SIGNAL(disconnected()), SLOT(onDisconnected()) );\n    transmit( \"INIT c=\" + clientId + \"\\n\" );\n}\n\n\nScrobSocket::~ScrobSocket()\n{\n    if (!m_track.isNull()) stop();\n}\n\n\nvoid\nScrobSocket::transmit( const QString& data )\n{\n    m_msgQueue.enqueue( data );\n    qDebug() << \"Connection state == \" << state();\n    if( state() == QLocalSocket::UnconnectedState ) {\n        doConnect();\n    }\n}\n\n\nvoid \nScrobSocket::onConnected()\n{\n    if( !m_msgQueue.empty() )\n    {\n        qDebug() << m_msgQueue.head().trimmed();\n        write( m_msgQueue.takeFirst().toUtf8());\n        flush();\n    }\n}\n\nvoid\nScrobSocket::doConnect()\n{\n    if (!m_bInConnect) {\n        #ifdef WIN32\n            std::string s;\n            DWORD r = scrobSubPipeName( &s );\n            if (r != 0) throw std::runtime_error( formatWin32Error( r ) );\n            QString const name = QString::fromStdString( s );\n        #else\n            QString const name = \"lastfm_scrobsub\";\n        #endif\n\n        // avoid stack-overflow connect/disconnect loop with m_bInConnect\n        m_bInConnect = true;\n        connectToServer( name );\n        m_bInConnect = false;\n    }\n}\n\nvoid \nScrobSocket::onDisconnected()\n{\n    if( !m_msgQueue.empty())\n        doConnect();\n}\n\n\nvoid\nScrobSocket::onError( QLocalSocket::LocalSocketError error )\n{\n    switch (error)\n    {\n        case SocketTimeoutError:\n            // TODO look, really we should store at least one start message forever\n            // then if last time we didn't connect and this time it's a pause we \n            // send the start first\n            m_msgQueue.clear();\n            break;\n        \n        case PeerClosedError:\n            // expected\n            break;\n        \n        case ConnectionRefusedError: // happens if client isn't running\n            break;\n\n        default: // may as well\n            qDebug() << lastfm::qMetaEnumString<QAbstractSocket>( error, \"SocketError\" );\n    }\n}\n\n\nstatic inline QString encodeAmp( QString data )\n{ \n    return data.replace( '&', \"&&\" );\n}\n\n\nvoid\nScrobSocket::start( const Track& t )\n{\n    m_track = t;\n    transmit( \"START c=\" + m_clientId + \"&\"\n                    \"a=\" + encodeAmp( t.artist() ) + \"&\"\n                    \"t=\" + encodeAmp( t.title() ) + \"&\"\n                    \"b=\" + encodeAmp( t.album().title() == \"[unknown]\" ? QString(\"\") : t.album().title() ) + \"&\"     // todo: and when album.isNull?\n                    \"l=\" + QString::number( t.duration() ) + \"&\"\n                    \"p=\" + encodeAmp( t.url().path() ) + '\\n' );\n}\n\n\nvoid\nScrobSocket::pause()\n{\n    transmit( \"PAUSE c=\" + m_clientId + \"\\n\" );\n}\n\n\nvoid\nScrobSocket::resume()\n{\n    transmit( \"RESUME c=\" + m_clientId + \"\\n\" );\n}\n\n\nvoid\nScrobSocket::stop()\n{\n    transmit( \"STOP c=\" + m_clientId + \"\\n\" );\n}\n\n\nvoid\nScrobSocket::onReadyRead()\n{\n    QByteArray bytes = readAll();\n    if (bytes != \"OK\\n\") \n        qWarning() << bytes.trimmed();\n    disconnectFromServer();\n}\n"
  },
  {
    "path": "app/client/ScrobSocket.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SCROB_SOCKET_H\n#define SCROB_SOCKET_H\n\n#include <lastfm/global.h>\n#include <lastfm/Track.h>\n#include <QLocalSocket>\n#include <QQueue>\n\n/** @author Christian Muehlhaeuser <chris@last.fm>\n  * @contributor Erik Jaelevik <erik@last.fm>\n  * @rewrite Max Howell <max@last.fm>\n  */\nclass ScrobSocket : public QLocalSocket\n{\n    Q_OBJECT\n\npublic:\n    ScrobSocket( const QString& clientId, QObject* parent = 0);\n    ~ScrobSocket();\n\npublic slots:\n    void start( const Track& );\n    void pause();\n    void resume();\n    void stop();\n\nprivate slots:\n    void transmit( const QString& data );\n    void onError( QLocalSocket::LocalSocketError );\n    void onReadyRead();\n    void onConnected();\n    void onDisconnected();\n\nprivate:\n    void doConnect();\n\n    Track m_track;\n    QQueue<QString> m_msgQueue;\n    bool m_bInConnect;\n    QString m_clientId;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Services/AnalyticsService/AnalyticsService.cpp",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Frantz Joseph\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifdef LASTFM_ANALYTICS\n#include <QWebView>\n#endif\n#include <QString>\n#include <QNetworkCookieJar>\n#include <QCoreApplication>\n\n#include <lastfm/ws.h>\n#include <lastfm/User.h>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"../Application.h\"\n#include \"PersistentCookieJar.h\"\n#include \"AnalyticsService.h\"\n\nAnalyticsService::AnalyticsService()\n    :m_customVarsSet( false ), m_pageLoaded( false )\n{\n#ifdef LASTFM_ANALYTICS\n    m_webView = new QWebView();\n    m_cookieJar = new PersistentCookieJar( this );\n    m_webView->page()->networkAccessManager()->setCookieJar( m_cookieJar );\n\n    connect( m_webView, SIGNAL(loadFinished(bool)), m_cookieJar, SLOT(save()) );\n    connect( m_webView, SIGNAL(loadFinished(bool)), SLOT(onLoadFinished()) );\n    connect( aApp, SIGNAL(gotUserInfo(lastfm::User)), SLOT(onGotUserInfo(lastfm::User)) );\n\n    m_webView->load( QString( \"https://cdn.last.fm/client/ga.html\" ) );\n#endif\n}\n\nvoid\nAnalyticsService::sendEvent( const QString& category, const QString& action, const QString& label, const QString& value )\n{\n#ifdef LASTFM_ANALYTICS\n    m_queue.enqueue( QString( \"https://cdn.last.fm/client/ga.html#event?category=%1&action=%2&label=%3&value=%4\" ).arg( category, action, label, value ) );\n    loadPages();\n#endif\n}\n\nvoid\nAnalyticsService::sendPageView( const QString& url )\n{\n#ifdef LASTFM_ANALYTICS\n    m_queue.enqueue( QString( \"https://cdn.last.fm/client/ga.html#pageview?url=%1\" ).arg( url ) );\n    loadPages();\n#endif\n}\n\nvoid\nAnalyticsService::loadPages()\n{\n#ifdef LASTFM_ANALYTICS\n    if ( m_pageLoaded && m_customVarsSet )\n    {\n        while ( !m_customVars.isEmpty() )\n            m_webView->load( m_customVars.dequeue() );\n\n        while ( !m_queue.isEmpty() )\n            m_webView->load( m_queue.dequeue() );\n    }\n#endif\n}\n\nvoid\nAnalyticsService::onLoadFinished()\n{\n#ifdef LASTFM_ANALYTICS\n    m_pageLoaded = true;\n    loadPages();\n#endif\n}\n\nQString userTypeToString( lastfm::User::Type type )\n{\n    if ( type == lastfm::User::TypeUser ) return \"user\";\n    else if ( type == lastfm::User::TypeSubscriber ) return \"subscriber\";\n    else if ( type == lastfm::User::TypeModerator ) return \"moderator\";\n    else if ( type == lastfm::User::TypeStaff ) return \"staff\";\n    else if ( type == lastfm::User::TypeAlumni ) return \"alumni\";\n    return \"unknown\";\n}\n\nvoid\nAnalyticsService::onGotUserInfo( const lastfm::User& user )\n{\n    // set all the session level custom vars\n    m_customVars.clear();\n    m_customVars.enqueue( QString( \"https://cdn.last.fm/client/ga.html#custom?version=%1&usertype=%2\" ).arg( QCoreApplication::applicationVersion(), userTypeToString( user.type() ) ) );\n    m_customVarsSet = true;\n\n    loadPages();\n}\n\n"
  },
  {
    "path": "app/client/Services/AnalyticsService/AnalyticsService.h",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Frantz Joseph\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#pragma once\n\n#include <QObject>\n#include <QQueue>\n\nnamespace lastfm { class User; }\n\n// -- Categories and their associated actions\n#define NOW_PLAYING_CATEGORY \"NowPlaying\"\n#define SCROBBLES_CATEGORY \"Scrobbles\"\n#define PROFILE_CATEGORY \"Profile\"\n#define FRIENDS_CATEGORY \"Friends\"\n#define RADIO_CATEGORY \"Radio\"\n\n#define SETTINGS_CATEGORY \"Settings\"\n\n#define LOVE_TRACK \"LoveTrack\"\n#define BAN_TRACK \"BanTrack\"\n#define LINK_CLICKED \"LinkClicked\"\n#define PLAY_CLICKED \"PlayClicked\"\n#define PLAY_NEXT_CLICKED \"PlayNextClicked\"\n#define PLAY_MULTI_CLICKED \"PlayMultiClicked\"\n#define PLAY_MULTI_NEXT_CLICKED \"PlayMultiNextClicked\"\n#define QUICKSTART_PLAY_CLICKED \"QuickstartPlayClicked\"\n#define QUICKSTART_PLAY_NEXT_CLICKED \"QuickstartPlayNextClicked\"\n#define SHARE_CLICKED \"ShareClicked\"\n#define TAG_CLICKED \"TagClicked\"\n#define SIDE_BAR_CLICKED \"SideBarClicked\"\n#define SKIP_CLICKED \"SkipClicked\"\n#define BUY_CLICKED \"BuyClicked\"\n\n#define SETTINGS_CLICKED \"SettingsClicked\"\n#define BASIC_SETTINGS \"Basic\"\n#define SCROBBLING_SETTINGS \"Scrobbling\"\n\nclass AnalyticsService : public QObject\n{\n    Q_OBJECT\n\npublic:\n    AnalyticsService();\n\n    static AnalyticsService& instance(){ static AnalyticsService a; return a; }\n\npublic:\n    void sendEvent( const QString& category, const QString& action, const QString& label, const QString& value = \"\" );\n    void sendPageView( const QString& url );\n\nprivate:\n    void loadPages();\n\nprivate slots:\n    void onGotUserInfo( const lastfm::User& user );\n    void onLoadFinished();\n\nprivate:\n    class QWebView* m_webView;\n    class PersistentCookieJar* m_cookieJar;\n    QQueue<QString> m_queue;\n    QQueue<QString> m_customVars;\n    bool m_customVarsSet;\n    bool m_pageLoaded;\n};\n"
  },
  {
    "path": "app/client/Services/AnalyticsService/PersistentCookieJar.cpp",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Frantz Joseph\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkCookieJar>\n#include <QDebug>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"PersistentCookieJar.h\"\n\n\nPersistentCookieJar::PersistentCookieJar(QObject *parent)\n    :QNetworkCookieJar(parent)\n{\n    load();\n}\n\nPersistentCookieJar::~PersistentCookieJar()\n{\n    save();\n}\n\nbool\nPersistentCookieJar::setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url)\n{\n    // save every time some cookies are set\n    bool oneOrMoreSet = QNetworkCookieJar::setCookiesFromUrl( cookieList, url );\n    save();\n    return oneOrMoreSet;\n}\n\nvoid\nPersistentCookieJar::save()\n{   \n    QList<QNetworkCookie> list = allCookies();\n    QByteArray data;\n\n    foreach (QNetworkCookie cookie, list)\n    {\n        // don't save session cookies\n        if (!cookie.isSessionCookie())\n        {\n            data.append(cookie.toRawForm());\n            data.append(\"\\n\");\n        }\n    }\n\n    unicorn::AppSettings settings;\n    settings.setValue(\"Cookies\", data);\n}\n\nvoid\nPersistentCookieJar::load()\n{\n    unicorn::AppSettings settings;\n    QByteArray data = settings.value(\"Cookies\").toByteArray();\n    setAllCookies( QNetworkCookie::parseCookies( data ) );\n}\n"
  },
  {
    "path": "app/client/Services/AnalyticsService/PersistentCookieJar.h",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Frantz Joseph\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#pragma once\n\n#include <QNetworkCookieJar>\n\nclass PersistentCookieJar : public QNetworkCookieJar\n{\n    Q_OBJECT\npublic:\n    PersistentCookieJar(QObject *parent);\n    ~PersistentCookieJar();\n\n    void load();\n\nprivate:\n    bool setCookiesFromUrl(const QList<QNetworkCookie> &cookieList, const QUrl &url);\n\npublic slots:\n    void save();\n};\n"
  },
  {
    "path": "app/client/Services/AnalyticsService.h",
    "content": "#include \"AnalyticsService/AnalyticsService.h\"\n"
  },
  {
    "path": "app/client/Services/RadioService/RadioService.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QThread>\n#include <QTimer>\n#include <QDesktopServices>\n#include <QCoreApplication>\n\n#include <phonon/mediaobject.h>\n#include <phonon/backendcapabilities.h>\n\n#include <lastfm/RadioTuner.h>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"../../Application.h\"\n#include \"RadioService.h\"\n\nRadioService::RadioService()\n     : m_audioOutput( 0 ),\n       m_mediaObject( 0 ),\n       m_state( Stopped ),\n       m_bErrorRecover( false ),\n       m_maxUsageCount( 180 )\n{\n    initRadio();\n\n    QDesktopServices::setUrlHandler( \"lastfm\", this, \"onLastFmUrl\" );\n\n    onSessionChanged( aApp->currentSession() );\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n}\n\nvoid\nRadioService::onSessionChanged( const unicorn::Session& session )\n{\n    if ( session.user().name() != m_currentUser )\n    {\n        m_currentUser = session.user().name();\n\n        // if they change user, make sure we stop the radio\n        if ( m_mediaObject && m_mediaObject->state() != Phonon::StoppedState )\n            stop();\n    }\n}\n\nvoid\nRadioService::onLastFmUrl( const QUrl& url )\n{\n    RadioStation rs( url.toString() );\n    play( rs );\n}\n\n// fixme:\n// todo:\n// note:\n// if the station is the same as current station (ie: the user hit stop then start)\n// then we *don't* retune.  norman is quite emphatic about this.  :)\nvoid\nRadioService::play( const RadioStation& station )\n{  \n    if ( !aApp->currentSession().youRadio() )\n    {\n        // they are not a subscriber so don't let them start the radio\n        emit error( lastfm::ws::SubscribersOnly, tr( \"You need to be a subscriber to listen to radio\" ) );\n        return;\n    }\n\n    if( m_state == Paused\n            && (station.url() == \"\" || station.url() == m_station.url() ) )\n    {\n        m_mediaObject->play();\n        return;\n    }\n\n    if( m_state != Stopped\n            && ( station.url() == \"\" || station.url() == m_station.url() ) )\n    {\n        // do nothing\n        return;\n    }\n\n    if (m_state != Stopped)\n    {\n        //FIXME filthy! get us to a clean slate\n        State oldstate = m_state;\n        m_state = Stopped;    //prevents stateChanged() doing anything\n        stop();\n        clear();\n        m_state = oldstate;\n    }\n\n    delete m_tuner;\n\n    if (0 == m_audioOutput)  {\n        if (!initRadio()) {\n            changeState( Stopped );\n            return;\n        }\n    }\n\n    m_station = station;\n\n    if ( m_station.url() == \"\" )\n    {\n        unicorn::UserSettings us;\n        QString stationUrl = us.value( \"lastStationUrl\", \"\" ).toString();\n        QString stationTitle = us.value( \"lastStationTitle\", tr( \"A Radio Station\" ) ).toString();\n\n        m_station.setUrl( stationUrl );\n        m_station.setTitle( stationTitle );\n    }\n\n    // Make sure the radio station has the radio options from the settings\n    bool ok;\n    m_station.setRep( unicorn::AppSettings().value( \"rep\", 0.5 ).toDouble( &ok ) );\n    m_station.setMainstr( unicorn::AppSettings().value( \"mainstr\", 0.5 ).toDouble( &ok ) );\n    m_station.setDisco( unicorn::AppSettings().value( \"disco\", false ).toBool() );\n\n    m_tuner = new lastfm::RadioTuner( m_station );\n\n    connect( m_tuner, SIGNAL(title( QString )), SLOT(setStationName( QString )) );\n    connect( m_tuner, SIGNAL(supportsDisco( bool )), SLOT(setSupportsDisco( bool )) );\n    connect( m_tuner, SIGNAL(trackAvailable()), SLOT(enqueue()) );\n    connect( m_tuner, SIGNAL(error( lastfm::ws::Error, QString )), SLOT(onTunerError( lastfm::ws::Error, QString )) );\n\n    changeState( TuningIn );\n}\n\n// play this radio station after the current track has finished\nvoid\nRadioService::playNext( const RadioStation& station )\n{\n    if (m_state == Playing)\n    {\n        m_station = station;\n\n        if ( m_station.url() == \"\" )\n        {\n            unicorn::UserSettings us;\n            QString stationUrl = us.value( \"lastStationUrl\", \"\" ).toString();\n            QString stationTitle = us.value( \"lastStationTitle\", tr( \"A Radio Station\" ) ).toString();\n\n            m_station.setUrl( stationUrl );\n            m_station.setTitle( stationTitle );\n        }\n\n        // Make sure the radio station has the radio options from the settings\n        bool ok;\n        m_station.setRep( unicorn::AppSettings().value( \"rep\", 0.5 ).toDouble( &ok ) );\n        m_station.setMainstr( unicorn::AppSettings().value( \"mainstr\", 0.5 ).toDouble( &ok ) );\n        m_station.setDisco( unicorn::AppSettings().value( \"disco\", false ).toBool() );\n\n        m_tuner->retune( m_station );\n    }\n}\n\n\nvoid\nRadioService::enqueue()\n{  \n    qDebug() << \"enqueue\";\n    if (m_state == Stopped) {\n        // this should be impossible. If we are stopped, then the GUI looks\n        // stopped too, and receiving tracks to play will result in a playing\n        // radio and a stopped GUI. NICE.\n        Q_ASSERT( 0 );\n        return;\n    }\n\t\n    phononEnqueue();\n}\n\nvoid\nRadioService::skip()\n{\n    if (!m_mediaObject)\n        return;\n    \n    // attempt to refill the phonon queue if it's empty\n    if (m_mediaObject->queue().isEmpty())\n        phononEnqueue();\n    \n    QList<Phonon::MediaSource> q = m_mediaObject->queue();\n\n    if ( q.size() )\n    {\n        m_mediaObject->setCurrentSource( q[0] );\n\n        //if the error returns a 403 permission denied error, the mediaObject is uninitialised\n        if( m_mediaObject )\n            m_mediaObject->play();\n        else {\n            initRadio();\n            play( RadioStation());\n        }\n    }\n    else if (m_state != Stopped)\n    {\n        qDebug() << \"queue empty\";\n        // we are still waiting for a playlist to come back from the tuner\n        m_mediaObject->blockSignals( true );    //don't tell outside world that we stopped\n        m_mediaObject->stop();\n        m_mediaObject->setCurrentSource( QUrl() );\n        m_mediaObject->blockSignals( false );\n        changeState( TuningIn );\n    }\n}\n\n\nvoid\nRadioService::onTunerError( lastfm::ws::Error e, const QString& message )\n{\n    // otherwise leave things be, we'll stop when we run out of content\n    if (m_state == TuningIn)\n        stop();\n\n    emit error( e, message );\n}\n\n\nvoid\nRadioService::stop()\n{\n    delete m_tuner;\n    \n    m_mediaObject->blockSignals( true ); //prevent the error state due to setting current source to null\n    m_mediaObject->stop();\n    m_mediaObject->clearQueue();\n    m_mediaObject->setCurrentSource( QUrl() );\n    m_mediaObject->blockSignals( false );\n\n    clear();\n    \n    changeState( Stopped );\n}\n\n\nvoid\nRadioService::pause()\n{\n    Q_ASSERT( m_mediaObject );\n\n    if ( m_mediaObject )\n    {\n        m_mediaObject->pause();\n        changeState( Paused );\n    }\n}\n\nvoid\nRadioService::resume()\n{\n    Q_ASSERT( m_mediaObject );\n\n    if ( m_mediaObject )\n    {\n        m_mediaObject->play();\n        changeState( Playing );\n    }\n}\n\n\nvoid\nRadioService::clear()\n{\n    m_track = Track();\n    m_station = RadioStation();\n    delete m_tuner;\n}\n\nvoid\nRadioService::volumeUp()\n{\n\n}\n\nvoid\nRadioService::volumeDown()\n{\n}\n\nvoid\nRadioService::mute()\n{\n    m_audioOutput->setMuted( !m_audioOutput->isMuted() );\n}\n\nvoid\nRadioService::onPhononStateChanged( Phonon::State newstate, Phonon::State oldstate )\n{\n    qDebug() << (int)oldstate << \" -> \" << (int)newstate;\n    if (m_mediaObject == 0) {\n        qDebug() << \"m_mediaObject is null!\";\n        return;\n    }\n\n    switch (newstate)\n    {\n        case Phonon::ErrorState:\n            qWarning() << m_mediaObject->errorType() << m_mediaObject->errorString();\n            emit error( lastfm::ws::UnknownError, QVariant( m_mediaObject->errorString() ));\n            deInitRadio();\n            changeState( Stopped );\n            break;\n\t\t\t\n        case Phonon::PausedState:\n            // if the play queue runs out we get this for some reason\n            // this means we are fetching new tracks still, we should show a\n            // tuning in state;\n            if (m_mediaObject->queue().size() == 0)\n            {\n                qDebug() << \"queue empty, going to TuningIn\";\n                changeState( Paused );\n            }\n            break;\n\t\t\t\n        case Phonon::StoppedState:\n            if (m_bErrorRecover)\n            {\n                m_bErrorRecover = false;\n                skip();\n            }\n            break;\n\t\t\t\n        case Phonon::BufferingState:\n            changeState( Buffering );\n            restoreVolume();\n            break;\n\n        case Phonon::PlayingState:\n            changeState( Playing );\n            break;\n\n        case Phonon::LoadingState:\n            break;\n    }\n}\n\nvoid\nRadioService::restoreVolume()\n{\n    // restore the last volume\n    if ( unicorn::AppSettings().contains(\"Volume\") )\n    {\n        bool ok;\n        double volume = unicorn::AppSettings().value( \"Volume\", 1 ).toReal(&ok);\n        if (ok)\n            m_audioOutput->setVolume(volume);\n        else\n            m_audioOutput->setVolume( 1 );\n    }\n    else\n        m_audioOutput->setVolume( 1 );\n\n    m_audioOutput->setMuted(unicorn::AppSettings().value(\"Muted\", false).toBool());\n}\n\nvoid\nRadioService::phononEnqueue()\n{\n    qDebug() << \"phononEnqueue\";\n    qDebug() << \"queue size: \" << m_mediaObject->queue().size();\n\n    if (m_mediaObject->queue().size() || !m_tuner)\n        return;\n\n    // keep only one track in the phononQueue\n    // Loop until we get a null url or a valid url.\n    forever\n    {\n        // consume next track from the track source. a null track \n        // response means wait until the trackAvailable signal\n        Track t = m_tuner->takeNextTrack();\n\n        if (t.isNull())\n        {\n            m_track = t;\n            changeState( TuningIn );\n            break;\n        }\n\n        // Invalid urls won't trigger the correct phonon\n        // state changes, so we must filter them.\n        if (!t.url().isValid())\n            continue;\n        \n        m_track = t;\n        Phonon::MediaSource ms( t.url() );\n\n        qDebug() << \"enqueuing \" << t;\n        try\n        {\n            m_mediaObject->enqueue( ms );\n            m_mediaObject->play();\n        }\n        catch (...)\n        {\n            continue;\n        }\n\n        break;\n    }\n}\n\n\n// onPhononCurrentSourceChanged happens always (even if the source is\n// unplayable), so we use it to update our now playing track.\nvoid\nRadioService::onPhononCurrentSourceChanged( const Phonon::MediaSource& )\n{\n    if (m_mediaObject == 0) {\n        qDebug() << \"m_mediaObject is null!\";\n        return;\n    }\n\n    if ( !m_track.isNull() )\n    {\n        MutableTrack( m_track ).stamp();\n\n        if (m_mediaObject->state() != Phonon::PlayingState)\n            changeState( Buffering );\n\n        emit trackSpooled( m_track );\n    }\n}\n\n\nvoid\nRadioService::changeState( State const newstate )\n{\n    State const oldstate = m_state;\n\n    if (oldstate == newstate) \n        return;\n\n    qDebug().nospace() << newstate << \" (was \" << oldstate << ')';\n     \n    m_state = newstate; // always assign state properties before you tell other\n                        // objects about it\n    \n    switch (newstate)\n\t{\n    case TuningIn:\n        qDebug() << \"Tuning to:\" << m_station;\n        emit tuningIn( m_station );\n        break;\n\n    default:\n    case Buffering:\n        break;\n    case Playing:\n        emit resumed();\n        break;\n\n    case Stopped:\n        emit stopped();\n        break;\n\n    case Paused:\n        emit paused();\n        break;\n\t}\n}\n\nvoid\nRadioService::setStationName( const QString& s )\n{\n    m_station.setTitle( s );\n\n    unicorn::UserSettings us;\n    us.setValue( \"lastStationUrl\", m_station.url() );\n    us.setValue( \"lastStationTitle\", m_station.title() );\n}\n\nvoid\nRadioService::setSupportsDisco( bool supportsDiscovery )\n{\n    emit supportsDisco( supportsDiscovery );\n}\n\nvoid\nRadioService::setMaxUsageCount(int count)\n{\n    m_maxUsageCount = count;\n}\n\nvoid\nRadioService::onBuffering( int percent_filled )\n{\n    Q_UNUSED(percent_filled);\n    emit buffering( percent_filled );\n}\n\nvoid\nRadioService::onMutedChanged(bool muted)\n{\n    unicorn::AppSettings().setValue(\"Muted\", muted);\n}\n\nvoid\nRadioService::onOutputDeviceChanged(const Phonon::AudioOutputDevice& newDevice)\n{\n    qDebug() << \"name: \" << newDevice.name() << \" description: \" << newDevice.description();\n}\n\nvoid\nRadioService::onVolumeChanged(qreal vol)\n{\n    unicorn::AppSettings().setValue( \"Volume\", vol );\n}\n\nvoid\nRadioService::onFinished()\n{\n    // A track has finished and there is nothing else in the queue\n    // try to go to the next track\n    skip();\n}\n\n\n// returns true on successful initialisation\nbool \nRadioService::initRadio()\n{\n    qDebug() << \"initRadio\";\n    Phonon::AudioOutput* audioOutput = new Phonon::AudioOutput( Phonon::MusicCategory );\n\n    qDebug() << audioOutput->name();\n    qDebug() << audioOutput->outputDevice().description();\n    qDebug() << audioOutput->outputDevice().name();\n    qDebug() << (audioOutput->isMuted() ? \"muted,\": \"not-muted,\") <<\n                (audioOutput->isValid() ? \"valid,\": \"not-valid,\") <<\n                audioOutput->volumeDecibel() << \"db \" <<\n                audioOutput->volume();\n    foreach (QByteArray a, audioOutput->outputDevice().propertyNames()) {\n        qDebug() << a << \":\" << audioOutput->outputDevice().property(a);\n    }\n\n    QString audioOutputDeviceName = \"\";//TODO moose::Settings().audioOutputDeviceName();\n    if (audioOutputDeviceName.size())\n    {\n        foreach (Phonon::AudioOutputDevice d, Phonon::BackendCapabilities::availableAudioOutputDevices())\n            if (d.name() == audioOutputDeviceName) {\n                audioOutput->setOutputDevice( d );\n                break;\n            }\n    }\n\n    Phonon::MediaObject* mediaObject = new Phonon::MediaObject;\n    m_path = Phonon::createPath( mediaObject, audioOutput );\n    if (!m_path.isValid()) {\n        qDebug() << \"Phonon::createPath failed\";\n// can't delete the mediaObject after a failed Phonon::createPath without a crash in phonon...  (Qt 4.4.3)\n// so, we leak it:\n//        mediaObject->deleteLater();\n        audioOutput->deleteLater();\n        return false;\n    } \n\n    mediaObject->setTickInterval( 500 );\n    connect( mediaObject, SIGNAL(stateChanged( Phonon::State, Phonon::State )), SLOT(onPhononStateChanged( Phonon::State, Phonon::State )) );\n    connect( mediaObject, SIGNAL(bufferStatus(int)), SLOT(onBuffering(int)));\n    connect( mediaObject, SIGNAL(currentSourceChanged( Phonon::MediaSource )), SLOT(onPhononCurrentSourceChanged( Phonon::MediaSource )) );\n    connect( mediaObject, SIGNAL(aboutToFinish()), SLOT(phononEnqueue()) ); // this fires when the whole queue is about to finish\n    connect( mediaObject, SIGNAL(finished()), SLOT(onFinished()));\n    connect( mediaObject, SIGNAL(tick(qint64)), SIGNAL(tick(qint64)));\n    connect( audioOutput, SIGNAL(mutedChanged(bool)), SLOT(onMutedChanged(bool)));\n    connect( audioOutput, SIGNAL(outputDeviceChanged(Phonon::AudioOutputDevice)), SLOT(onOutputDeviceChanged(Phonon::AudioOutputDevice)));\n    connect( audioOutput, SIGNAL(volumeChanged(qreal)), SLOT(onVolumeChanged(qreal)));\n\n    m_audioOutput = audioOutput;\n    m_mediaObject = mediaObject;\n\n    restoreVolume();\n\n    return true;\n}\n\nvoid\nRadioService::deInitRadio()\n{\n    qDebug() << \"deInitRadio\";\n    // try to deleteLater and phonon crashes. poo.\n    // leak em...  :(\n    \n    m_audioOutput->deleteLater();\n    m_audioOutput = 0;\n    m_mediaObject->deleteLater();\n    m_mediaObject = 0;\n}\n"
  },
  {
    "path": "app/client/Services/ScrobbleService/ScrobbleService.cpp",
    "content": "/*\n   Copyright 2005-2010 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"ScrobbleService.h\"\n#include <lastfm/ws.h>\n\n#include \"../../Application.h\"\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n#include \"lib/listener/legacy/LegacyPlayerListener.h\"\n#else\n#include \"lib/listener/mpris2/Mpris2Listener.h\"\n#endif\n#include \"lib/listener/PlayerConnection.h\"\n#include \"lib/listener/PlayerListener.h\"\n#include \"lib/listener/PlayerMediator.h\"\n#include \"../MediaDevices/DeviceScrobbler.h\"\n#include \"StopWatch.h\"\n#ifdef Q_WS_MAC\n#include \"lib/listener/mac/SpotifyListener.h\"\n#include \"lib/listener/mac/ITunesListener.h\"\n#endif\n#ifdef Q_OS_WIN\n#include \"lib/listener/win/SpotifyListener.h\"\n#endif\n\nScrobbleService::ScrobbleService()\n{\n    qRegisterMetaType<Track>(\"Track\");\n\n/// mediator\n    m_mediator = new PlayerMediator(this);\n    connect( m_mediator, SIGNAL(activeConnectionChanged( PlayerConnection* )), SLOT(setConnection( PlayerConnection* )) );\n    \n/// listeners\n    try{\n#ifdef Q_OS_MAC\n        ITunesListener* itunes = new ITunesListener(m_mediator);\n        connect(itunes, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n\n        SpotifyListenerMac* spotify = new SpotifyListenerMac(m_mediator);\n        connect(spotify, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n#endif\n#ifdef Q_OS_WIN\n        SpotifyListenerWin* spotify = new SpotifyListenerWin(m_mediator);\n        connect(spotify, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n#endif\n\n        QObject* o = new PlayerListener(m_mediator);\n        connect(o, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n        o = new LegacyPlayerListener(m_mediator);\n        connect(o, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n#else\n        Mpris2Listener* mpris2 = new Mpris2Listener(m_mediator);\n        connect(mpris2, SIGNAL(newConnection(PlayerConnection*)), m_mediator, SLOT(follow(PlayerConnection*)));\n        mpris2->createConnection();\n#endif\n    }\n    catch(std::runtime_error& e){\n        qWarning() << e.what();\n        //TODO user visible warning\n    }\n\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n    resetScrobbler();\n}\n\nScrobbleService&\nScrobbleService::instance()\n{\n    static ScrobbleService s;\n    return s;\n}\n\n\nbool\nScrobbleService::isDirExcluded( const lastfm::Track& track )\n{\n    QString pathToTest = track.url().toLocalFile();\n\n#ifdef Q_OS_WIN\n    pathToTest = pathToTest.toLower();\n#endif\n\n    if ( pathToTest.isEmpty() )\n        return false;\n\n    unicorn::UserSettings us;\n    QStringList exculsionDirs = us.value( \"ExclusionDirs\" ).toStringList();\n\n    foreach ( QString bannedPath, exculsionDirs )\n    {\n        bannedPath = QDir( bannedPath ).absolutePath();\n#ifdef Q_OS_WIN\n        bannedPath = bannedPath.toLower();\n#endif\n\n        qDebug() << pathToTest << bannedPath;\n\n        // Try and match start of given path with banned dir\n        if ( pathToTest.startsWith( bannedPath ) )\n        {\n            // Found, this path is from a banned dir\n            return true;\n        }\n    }\n\n    // The path wasn't found in exclusions list\n    return false;\n}\n\nbool\nScrobbleService::scrobblableTrack( const lastfm::Track& track ) const\n{\n    unicorn::UserSettings userSettings;\n\n    return userSettings.scrobblingOn()\n            && ( track.extra( \"playerId\" ) != \"spt\" && track.extra( \"playerId\" ) != \"mpris2\" )\n            && !track.artist().isNull()\n            && ( userSettings.podcasts() || !track.isPodcast() )\n            && !track.isVideo()\n            && !isDirExcluded( track );\n}\n\nbool\nScrobbleService::scrobblingOn() const\n{\n    return scrobblableTrack( m_currentTrack );\n}\n\nvoid\nScrobbleService::scrobbleSettingsChanged()\n{\n    if ( m_watch )\n    {\n        ScrobblePoint timeout( ( m_currentTrack.duration() * unicorn::UserSettings().scrobblePoint() ) / 100.0 );\n        timeout.setEnforceScrobbleTimeMax( unicorn::UserSettings().enforceScrobbleTimeMax() );\n        m_watch->setScrobblePoint( timeout );\n    }\n\n    bool scrobblingOn = scrobblableTrack( m_currentTrack );\n\n    // Check if the current track now meets the requirements\n    // and scrobble it straight away if so\n    if ( m_as\n         && m_watch\n         && m_watch->elapsed() >= (m_watch->scrobblePoint() * 1000)\n         && m_currentTrack.scrobbleStatus() == Track::Null\n         && scrobblingOn )\n        m_as->cache( m_currentTrack );\n\n    emit scrobblingOnChanged( scrobblingOn );\n}\n\nvoid\nScrobbleService::submitCache()\n{\n    if ( m_as ) m_as->submit();\n}\n\nvoid \nScrobbleService::onSessionChanged( const unicorn::Session& )\n{\n    resetScrobbler();\n}\n\nvoid\nScrobbleService::resetScrobbler()\n{\n    if ( !aApp->currentSession().user().name().isEmpty()\n         && aApp->currentSession().user().name() != m_currentUsername)\n    {\n        // only create the scrobble cache, etc if we have a user\n        // we won't have a user during the first run wizard\n\n        m_currentUsername = aApp->currentSession().user().name();\n\n        /// audioscrobbler\n        delete m_as;\n        m_as = new Audioscrobbler( \"ass\" );\n        connect( m_as, SIGNAL(scrobblesCached(QList<lastfm::Track>)), SIGNAL(scrobblesCached(QList<lastfm::Track>)));\n        connect( m_as, SIGNAL(scrobblesSubmitted(QList<lastfm::Track>)), SIGNAL(scrobblesSubmitted(QList<lastfm::Track>)));\n\n        /// DeviceScrobbler\n        delete m_deviceScrobbler;\n        m_deviceScrobbler = new DeviceScrobbler( this );\n        connect( m_deviceScrobbler, SIGNAL(foundScrobbles(QList<lastfm::Track>)), SLOT(onFoundScrobbles(QList<lastfm::Track>)));\n        connect( m_deviceScrobbler, SIGNAL(foundScrobbles(QList<lastfm::Track>)), SIGNAL(foundIPodScrobbles(QList<lastfm::Track>)));\n\n        // Do this a bit later to as it's nicer for the user and\n        // it gives the main window time to be diplayed on boot\n        QTimer::singleShot( 3000, m_deviceScrobbler, SLOT(checkCachedIPodScrobbles()) );\n    }\n}\n\nvoid\nScrobbleService::onFoundScrobbles( QList<lastfm::Track> tracks )\n{\n    m_as->cacheBatch( tracks );\n    m_as->submit();\n}\n\n\nvoid\nScrobbleService::setConnection(PlayerConnection*c)\n{\n    if( m_connection )\n    {\n        // disconnect from all the objects that we connect to below\n        disconnect( m_connection, 0, this, 0);\n        if(m_watch)\n            m_connection->setElapsed(m_watch->elapsed());\n    }\n\n    //\n    connect(c, SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), this, SLOT(onTrackStarted(lastfm::Track,lastfm::Track)), Qt::QueuedConnection);\n    connect(c, SIGNAL(paused()), this, SLOT(onPaused()), Qt::QueuedConnection);\n    connect(c, SIGNAL(resumed()), this, SLOT(onResumed()), Qt::QueuedConnection);\n    connect(c, SIGNAL(stopped()), this, SLOT(onStopped()), Qt::QueuedConnection);\n    connect(c, SIGNAL(bootstrapReady(QString)), SIGNAL( bootstrapReady(QString)));\n\n    m_connection = c;\n\n    if(c->state() == Playing || c->state() == Paused)\n        c->forceTrackStarted(Track());\n\n    if( c->state() == Paused )\n        c->forcePaused();\n}\n\nvoid\nScrobbleService::onTrackStarted( const lastfm::Track& t, const lastfm::Track& ot )\n{\n    Q_ASSERT(m_connection);\n\n    //TODO move to playerconnection\n    if(t.isNull())\n    {\n        qWarning() << \"Can't start null track!\";\n        return;\n    }\n\n    Track oldtrack = ot.isNull() ? m_currentTrack : ot;\n\n    if ( unicorn::UserSettings().scrobblePoint() == 100.0 && !oldtrack.isNull() )\n    {\n        // was the last track at 100%? Should we scrobble it?\n\n        if ( m_watch )\n        {\n            /** At this point, we can't tell for ceratin if a track was played until the end.\n             * The next lowest percentage the user can set is 95% which means a 30 second track\n             * will scrobble at 28.5 seconds. As long as we're above this, I think we're fine.\n             * Here we'rechecking if the track got within 1 second of the end point At 30 seconds.\n             * At 30 seconds this equates to 96.66%, which is tolerable. Assuming an average 3\n             * minute track length, the actual percentage we will at is 99.44% which is close\n             * enough to 100% for me. As this is timing based, things can go slightly off, it's\n             * still possible that scrobbles will be missed, but these are the perils of setting\n             * your scrobble point to 100%.\n             * TODO: really the plugins should be able to tell us if the track got to 100% and\n             * we just use that, but I'm not sure if that's possible and that would be a rather\n             * big change. This should be enough for now.\n             */\n            if ( !m_watch->paused() // the watch is running (if we scrobble after the user paused and skipped, it would give away we're not actually scrobbling at 100%)\n                 && oldtrack.duration() == m_watch->duration() // the duration of the track and the stop watch duration is the same (double checking it's the same track)\n                 && m_watch->elapsed() > (m_watch->duration() * 1000) - 1000 ) // it's within a second so assume it got to 100% (see above)\n                onScrobble(); // we should scrobble the last track\n        }\n\n    }\n\n    m_state = Playing;\n    m_currentTrack = t;\n\n    ScrobblePoint timeout( ( m_currentTrack.duration() * unicorn::UserSettings().scrobblePoint() ) / 100.0 );\n    timeout.setEnforceScrobbleTimeMax( unicorn::UserSettings().enforceScrobbleTimeMax() );\n    delete m_watch;\n    m_watch = new StopWatch(m_currentTrack.duration(), timeout);\n    m_watch->start();\n\n    connect( m_watch, SIGNAL(scrobble()), SLOT(onScrobble()));\n    connect( m_watch, SIGNAL(paused(bool)), SIGNAL(paused(bool)));\n    connect( m_watch, SIGNAL(frameChanged( int )), SIGNAL(frameChanged( int )));\n    connect( m_watch, SIGNAL(timeout()), SIGNAL(timeout()));\n\n    qDebug() << \"********** AS = \" << m_as;\n    if( m_as )\n    {\n        m_as->submit();\n\n        if ( scrobblableTrack( t ) )\n        {\n            qDebug() << \"************** Now Playing..\";\n            m_as->nowPlaying( t );\n        }\n    }\n\n    emit trackStarted( t, oldtrack );\n}\n\nvoid\nScrobbleService::onPaused()\n{\n    // We can sometimes get a stopped before a play when the\n    // media player is playing before the scrobbler is started\n    if ( m_state == Unknown ) return;\n\n    m_state = Paused;\n\n    //m_currentTrack.removeNowPlaying();\n\n    Q_ASSERT(m_connection);\n    Q_ASSERT(m_watch);\n    if(m_watch) m_watch->pause();\n    \n    emit paused();\n}\n\nvoid\nScrobbleService::onStopped()\n{\n    // We can sometimes get a stopped before a play when the\n    // media player is playing before the scrobbler is started\n    if ( m_state == Unknown ) return;\n\n    m_state = Stopped;\n\n    Q_ASSERT(m_watch);\n    Q_ASSERT(m_connection);\n        \n    delete m_watch;\n    if( m_as )\n        m_as->submit();\n\n    emit stopped();\n}\n\nvoid\nScrobbleService::onResumed()\n{\n    // We can sometimes get a stopped before a play when the\n    // media player is playing before the scrobbler is started\n    if ( m_state == Unknown ) return;\n\n    m_state = Playing;\n\n    Q_ASSERT(m_watch);\n    Q_ASSERT(m_connection);\n\n    //m_currentTrack.updateNowPlaying( m_currentTrack.duration() - (m_watch->elapsed()/1000) );\n\n    if (m_watch)\n        m_watch->resume();\n\n    emit resumed();\n}\n\nvoid\nScrobbleService::onScrobble()\n{\n    Q_ASSERT(m_connection);\n\n    if( m_as\n            && scrobblableTrack( m_currentTrack )\n            && m_currentTrack.scrobbleStatus() == Track::Null )\n        m_as->cache( m_currentTrack );\n}\n\nvoid \nScrobbleService::handleIPodDetectedMessage( const QStringList& message )\n{\n    m_deviceScrobbler->iPodDetected( message );\n}\n\nvoid \nScrobbleService::handleTwiddlyMessage( const QStringList& message )\n{\n    m_deviceScrobbler->handleMessage( message );\n}\n\n"
  },
  {
    "path": "app/client/Services/ScrobbleService/ScrobbleService.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SCROBBLE_SERVICE_H\n#define SCROBBLE_SERVICE_H\n\n#include <QObject>\n#include <QPointer>\n\n#include \"lib/listener/State.h\"\n\n#include <lastfm/Audioscrobbler.h>\n#include <lastfm/Track.h>\n\nnamespace unicorn { class Session; }\nclass PlayerMediator;\nclass PlayerConnection;\nclass StopWatch;\nclass DeviceScrobbler;\n\nclass ScrobbleService : public QObject\n{\n    Q_OBJECT\n\npublic:\n    ScrobbleService();\n\n    bool scrobblableTrack( const lastfm::Track& track ) const;\n    static bool isDirExcluded( const lastfm::Track& track );\n\n    Track currentTrack() const { return m_currentTrack; }\n    QPointer<DeviceScrobbler> deviceScrobbler() { return m_deviceScrobbler; }\n    QPointer<PlayerConnection> currentConnection() { return m_connection; }\n    QPointer<StopWatch> stopWatch() { return m_watch; }\n\n    void handleTwiddlyMessage( const QStringList& message );\n    void handleIPodDetectedMessage( const QStringList& message );\n    \n    static ScrobbleService& instance();\n\npublic slots:\n    void onSessionChanged( const unicorn::Session& session );\n    void onScrobble();\n    void scrobbleSettingsChanged();\n\nsignals:\n    void trackStarted( const lastfm::Track& newTrack, const lastfm::Track& oldTrack );\n    void resumed();\n    void paused();\n    void stopped();\n    void scrobblingOnChanged( bool scrobblingOn );\n    void scrobblesCached( const QList<lastfm::Track>& tracks );\n    void scrobblesSubmitted( const QList<lastfm::Track>& tracks );\n\n    void foundIPodScrobbles( const QList<lastfm::Track>& tracks );\n    void bootstrapReady( const QString& playerId );\n\n    void paused( bool );\n    void frameChanged( int );\n    void timeout();\n\npublic slots:\n    void submitCache();\n\nprotected slots:\n    void setConnection( PlayerConnection* );\n    void onTrackStarted( const lastfm::Track&, const lastfm::Track& );\n    void onPaused();\n    void onResumed(); \n    void onStopped();\n\n    void onFoundScrobbles( QList<lastfm::Track> tracks );\n\nprivate:\n    void resetScrobbler();\n    bool scrobblingOn() const;\n\nprotected:\n    State m_state;\n\n    QPointer <StopWatch> m_watch;\n    QPointer <PlayerMediator> m_mediator;\n    QPointer <PlayerConnection> m_connection;\n    QPointer <Audioscrobbler> m_as;\n    QPointer <DeviceScrobbler> m_deviceScrobbler;\n    Track m_currentTrack;\n    QString m_currentUsername;\n};\n\n\n#endif //SCROBBLE_SERVICE_H_\n"
  },
  {
    "path": "app/client/Services/ScrobbleService/StopWatch.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"StopWatch.h\"\n#include <QTimeLine>\n\n\nStopWatch::StopWatch( uint duration, ScrobblePoint timeout )\n    : m_duration( duration ), m_point( timeout ), m_scrobbled(false)\n{    \n    m_timeline = new QTimeLine( duration * 1000, this );\n    m_timeline->setFrameRange( 0, duration * 2 );\n    m_timeline->setEasingCurve( QEasingCurve::Linear );\n    m_timeline->setUpdateInterval( 50 );\n    m_timeline->setCurrentTime( 0 );\n\n    connect( m_timeline, SIGNAL(finished()), SIGNAL(timeout()) );\n    connect( m_timeline, SIGNAL(frameChanged(int)), SLOT(onFrameChanged(int)));\n}\n\nScrobblePoint\nStopWatch::scrobblePoint() const\n{\n    return m_point;\n}\n\nvoid\nStopWatch::setScrobblePoint( const ScrobblePoint& timeout_in_seconds )\n{\n    m_point = timeout_in_seconds;\n}\n\nuint\nStopWatch::duration() const\n{\n    return m_duration;\n}\n\nbool\nStopWatch::scrobbled() const\n{\n    return m_scrobbled;\n}\n\nvoid\nStopWatch::onFrameChanged( int /*frame*/ )\n{\n    emit frameChanged( m_timeline->currentTime() );\n\n    if ( !m_scrobbled && elapsed() >= (m_point * 1000) )\n    {\n        emit scrobble();\n        m_scrobbled = true;\n    }\n}\n\nbool\nStopWatch::paused()\n{\n    return (m_timeline->state() == QTimeLine::Paused);\n}\n\nvoid\nStopWatch::start()\n{\n    m_timeline->start();\n    emit paused( false );\n}\n\nvoid\nStopWatch::pause()\n{\n    m_timeline->setPaused( true );\n    emit paused( true );\n}\n\nvoid\nStopWatch::resume()\n{\n    // Only resume if we are already running\n    if ( m_timeline->state() == QTimeLine::Paused )\n        m_timeline->resume();\n    emit paused( false );\n}\n\nuint\nStopWatch::elapsed() const\n{\n    return m_timeline->currentTime();\n}\n"
  },
  {
    "path": "app/client/Services/ScrobbleService/StopWatch.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef STOP_WATCH_H\n#define STOP_WATCH_H\n\n#include <lastfm/ScrobblePoint.h>\n#include <QDateTime>\n#include <QObject>\n\nnamespace audioscrobbler { class Application; }\n\n/** Emits timeout() after seconds specified to start. \n  * Continues to measure time after that point until object death.\n  */\nclass StopWatch : public QObject\n{\n    Q_OBJECT\n    Q_DISABLE_COPY( StopWatch )\n\n    friend class audioscrobbler::Application; //for access to timeout() signal \n    friend class TestStopWatch; //for testing, duh!\n    \npublic:\n    /** The StopWatch starts off paused, call resume() to start.\n      * The watch will not timeout() if elapsed is greater that the \n      * scrobble point */\n    StopWatch( uint duration_in_seconds, ScrobblePoint timeout_in_seconds );\n\n    void start();\n    void pause();\n    void resume();\n\n    bool paused();\n    \n    /** in milliseconds */\n    uint elapsed() const;\n\n    ScrobblePoint scrobblePoint() const;\n    void setScrobblePoint( const ScrobblePoint& timeout_in_seconds );\n\n    uint duration() const;\n    \nsignals:\n    void paused( bool );\n    void frameChanged( int millisecs );\n    void scrobble();\n    void timeout();\n\nprivate slots:\n    void onFrameChanged( int frame );\n\nprivate:\n    bool scrobbled() const;\n\nprivate: \n    class QTimeLine* m_timeline;\n    uint m_duration;\n    ScrobblePoint m_point;\n    bool m_scrobbled;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Services/ScrobbleService.h",
    "content": "#include \"ScrobbleService/ScrobbleService.h\"\n#include \"ScrobbleService/StopWatch.h\"\n"
  },
  {
    "path": "app/client/Settings/AccountSettingsWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"ui_AccountSettingsWidget.h\"\n#include \"AccountSettingsWidget.h\"\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include <lastfm/User.h>\n\n#include <QApplication>\n#include <QComboBox>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QVBoxLayout>\n\nusing lastfm::User;\n\n\nAccountSettingsWidget::AccountSettingsWidget( QWidget* parent )\n    : SettingsWidget( parent ),\n      ui( new Ui::AccountSettingsWidget )\n{\n    ui->setupUi( this );\n    \n    connect( ui->users, SIGNAL(userChanged() ), SLOT(onSettingsChanged() ) );\n    connect( ui->users, SIGNAL(rosterUpdated() ), qApp, SIGNAL(rosterUpdated() ) );\n}\n\nvoid\nAccountSettingsWidget::saveSettings()\n{\n    qDebug() << \"has unsaved changes?\" << hasUnsavedChanges();\n\n    if ( hasUnsavedChanges() )\n    {\n        UserRadioButton* urb = qobject_cast<UserRadioButton*>( ui->users->checkedButton() );\n\n        if ( urb && urb->user() != User().name() )\n        {\n            unicorn::Settings s;\n            s.setValue( \"Username\", urb->user() );\n\n            unicorn::UserSettings us( urb->user() );\n            QString sessionKey = us.sessionKey();\n            qobject_cast<unicorn::Application *>( qApp )->changeSession( urb->user(), sessionKey, true );\n        }\n\n        onSettingsSaved();\n    }\n}\n"
  },
  {
    "path": "app/client/Settings/AccountSettingsWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ACCOUNT_SETTINGS_WIDGET_H_\n#define ACCOUNT_SETTINGS_WIDGET_H_\n\n#include \"SettingsWidget.h\"\n\nnamespace Ui { class AccountSettingsWidget; }\n\nclass AccountSettingsWidget: public SettingsWidget\n{\nQ_OBJECT\npublic:\n    AccountSettingsWidget( QWidget* parent = 0 );\n\npublic slots:\n    virtual void saveSettings();\n\nprivate:\n    void setupUi();\n    void populateLanguages();\n\nprivate:\n    Ui::AccountSettingsWidget* ui;\n};\n\n#endif //ACCOUNT_SETTINGS_WIDGET_H_\n"
  },
  {
    "path": "app/client/Settings/AccountSettingsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>AccountSettingsWidget</class>\n <widget class=\"QWidget\" name=\"AccountSettingsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>400</width>\n    <height>300</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"UserManagerWidget\" name=\"users\" native=\"true\"/>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>UserManagerWidget</class>\n   <extends>QWidget</extends>\n   <header>lib/unicorn/widgets/UserManagerWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/AdvancedSettingsWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QApplication>\n#include <QComboBox>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QLineEdit>\n#include <QComboBox>\n#include <QVBoxLayout>\n#include <QKeyEvent>\n#include <QStringListModel>\n#include <QNetworkProxy>\n#include <QSslSocket>\n\n#include <lastfm/User.h>\n#include <lastfm/ws.h>\n#include <lastfm/NetworkAccessManager.h>\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/widgets/UserManagerWidget.h\"\n\n#include \"../Widgets/ShortcutEdit.h\"\n#include \"../AudioscrobblerSettings.h\"\n#include \"../Application.h\"\n#include \"ui_AdvancedSettingsWidget.h\"\n#include \"AdvancedSettingsWidget.h\"\n\nusing lastfm::User;\n\nAdvancedSettingsWidget::AdvancedSettingsWidget( QWidget* parent )\n    : SettingsWidget( parent ),\n      ui( new Ui::AdvancedSettingsWidget )\n{\n    ui->setupUi( this );\n\n    AudioscrobblerSettings settings;\n\n#ifdef Q_WS_X11\n    ui->shortcuts->hide();\n#else\n\n    ui->sce->setTextValue( settings.raiseShortcutDescription() );\n    ui->sce->setModifiers( settings.raiseShortcutModifiers() );\n    ui->sce->setKey( settings.raiseShortcutKey() );\n\n    connect( ui->sce, SIGNAL(editTextChanged(QString)), this, SLOT(onSettingsChanged()));\n#endif\n\n    ui->cache->hide();\n\n    ui->ssl->setVisible( QSslSocket::supportsSsl() );\n    ui->ssl->setChecked( settings.value( \"enableSsl\", false ).toBool() );\n    connect( ui->ssl, SIGNAL(clicked()), SLOT(onSettingsChanged()));\n    connect( ui->proxySettings, SIGNAL(changed()), SLOT(onSettingsChanged()));\n}\n\nvoid\nAdvancedSettingsWidget::saveSettings()\n{\n    qDebug() << \"has unsaved changes?\" << hasUnsavedChanges();\n\n    if ( hasUnsavedChanges() )\n    {\n        AudioscrobblerSettings settings;\n        settings.setRaiseShortcutKey( ui->sce->key() );\n        settings.setRaiseShortcutModifiers( ui->sce->modifiers() );\n        settings.setRaiseShortcutDescription( ui->sce->textValue() );\n\n        aApp->setRaiseHotKey( ui->sce->modifiers(), ui->sce->key() );\n\n        ui->proxySettings->save();\n\n        settings.setValue( \"enableSsl\", ui->ssl->isChecked() );\n\n        lastfm::ws::setScheme( ui->ssl->isChecked() ? lastfm::ws::Https : lastfm::ws::Http );\n    }\n}\n"
  },
  {
    "path": "app/client/Settings/AdvancedSettingsWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ADVANCED_SETTINGS_WIDGET_H_\n#define ADVANCED_SETTINGS_WIDGET_H_\n\n#include \"SettingsWidget.h\"\n\nnamespace Ui { class AdvancedSettingsWidget; }\n\nclass AdvancedSettingsWidget: public SettingsWidget\n{\nQ_OBJECT\npublic:\n    AdvancedSettingsWidget( QWidget* parent = 0 );\n\npublic slots:\n    virtual void saveSettings();\n\nprivate:\n    Ui::AdvancedSettingsWidget* ui;\n};\n\n#endif //KEYBOARD_SETTINGS_WIDGET_H_\n"
  },
  {
    "path": "app/client/Settings/AdvancedSettingsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>AdvancedSettingsWidget</class>\n <widget class=\"QWidget\" name=\"AdvancedSettingsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>461</width>\n    <height>398</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"QGroupBox\" name=\"shortcuts\">\n     <property name=\"title\">\n      <string>Keyboard Shortcuts:</string>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n      <item>\n       <widget class=\"QCheckBox\" name=\"open\">\n        <property name=\"enabled\">\n         <bool>false</bool>\n        </property>\n        <property name=\"text\">\n         <string>Raise/Hide Last.fm</string>\n        </property>\n        <property name=\"checked\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"ShortcutEdit\" name=\"sce\"/>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QGroupBox\" name=\"cache\">\n     <property name=\"enabled\">\n      <bool>false</bool>\n     </property>\n     <property name=\"title\">\n      <string>Cache Size:</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QGroupBox\" name=\"proxy\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"title\">\n      <string>Proxy:</string>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n      <item>\n       <widget class=\"unicorn::ProxyWidget\" name=\"proxySettings\" native=\"true\"/>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QCheckBox\" name=\"ssl\">\n     <property name=\"text\">\n      <string>Enable SSL</string>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::ProxyWidget</class>\n   <extends>QWidget</extends>\n   <header>lib/unicorn/widgets/ProxyWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>ShortcutEdit</class>\n   <extends>QComboBox</extends>\n   <header>../Widgets/ShortcutEdit.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/CheckFileSystemModel.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"CheckFileSystemModel.h\"\n\nCheckFileSystemModel::CheckFileSystemModel( QObject *parent )\n    :QFileSystemModel( parent )\n{\n}\n\nQt::ItemFlags\nCheckFileSystemModel::flags( const QModelIndex& index) const\n{\n    return QFileSystemModel::flags(index) | Qt::ItemIsUserCheckable;\n}\n\nQVariant\nCheckFileSystemModel::data( const QModelIndex& index, int role) const\n{\n    if (role == Qt::CheckStateRole)\n    {\n        qint64 id = index.internalId();\n        return m_checkTable.contains(id) ? m_checkTable.value(id) : Qt::Unchecked;\n    }\n    else\n    {\n        return QFileSystemModel::data(index, role);\n    }\n}\n\nbool\nCheckFileSystemModel::setData( const QModelIndex& index, const QVariant& value, int role )\n{\n    if (role == Qt::CheckStateRole)\n    {\n        m_checkTable.insert(index.internalId(), (Qt::CheckState)value.toInt());\n\n        emit dataChanged(index, index);\n        emit dataChangedByUser(index);\n\n        return true;\n    }\n    else\n    {\n        return QFileSystemModel::setData(index, value, role);\n    }\n}\n\nvoid\nCheckFileSystemModel::setCheck( const QModelIndex& index, const QVariant& value)\n{\n    m_checkTable.insert(index.internalId(), (Qt::CheckState)value.toInt());\n    emit dataChanged(index, index);\n}\n\nQt::CheckState\nCheckFileSystemModel::getCheck( const QModelIndex& index )\n{\n    return (Qt::CheckState)data(index, Qt::CheckStateRole).toInt();\n}\n"
  },
  {
    "path": "app/client/Settings/CheckFileSystemModel.h",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef CHECKFILESYSTEMMODEL_H\n#define CHECKFILESYSTEMMODEL_H\n\n#include <QFileSystemModel>\n\nclass CheckFileSystemModel : public QFileSystemModel\n{\n    Q_OBJECT\npublic:\n    explicit CheckFileSystemModel( QObject *parent = 0 );\n    \n    virtual Qt::ItemFlags flags( const QModelIndex& index ) const;\n    virtual QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const;\n    virtual bool setData( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);\n    void setCheck( const QModelIndex& index, const QVariant& value);\n    Qt::CheckState getCheck( const QModelIndex& index );\n\nsignals:\n    void dataChangedByUser( const QModelIndex & index);\n\nprivate:\n    QHash<qint64, Qt::CheckState> m_checkTable;\n};\n\n#endif // CHECKFILESYSTEMMODEL_H\n"
  },
  {
    "path": "app/client/Settings/CheckFileSystemView.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"CheckFileSystemView.h\"\n\n#include <QDesktopServices>\n\nCheckFileSystemView::CheckFileSystemView( QWidget* parent )\n    :QTreeView( parent )\n{\n    m_fsModel = new CheckFileSystemModel( this );\n    m_fsModel->setRootPath( \"\" );\n    m_fsModel->setFilter( QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks );\n    setModel( m_fsModel );\n\n    setRootIndex( m_fsModel->index( \"\" ) );\n\n    setColumnHidden(1, true);\n    setColumnHidden(2, true);\n    setColumnHidden(3, true);\n    //header()->hide();\n\n    connect( m_fsModel, SIGNAL(dataChangedByUser(const QModelIndex&)), SLOT(updateNode(const QModelIndex&)));\n    connect( m_fsModel, SIGNAL(dataChangedByUser(const QModelIndex&)), SIGNAL(dataChanged()));\n    connect( this, SIGNAL(collapsed(const QModelIndex&)), SLOT(onCollapse(const QModelIndex&)));\n    connect( this, SIGNAL(expanded(const QModelIndex&)), SLOT(onExpand(const QModelIndex&)));\n}\n\n\nvoid\nCheckFileSystemView::checkPath( const QString& path, Qt::CheckState state )\n{\n    QModelIndex index = m_fsModel->index(path);\n    m_fsModel->setCheck(index, state);\n    updateNode(index);\n}\n\nvoid\nCheckFileSystemView::setExclusions( const QStringList& list )\n{\n    foreach(QString path, list)\n    {\n        checkPath(path, Qt::Checked);\n    }\n}\n\nQStringList\nCheckFileSystemView::getExclusions()\n{\n    QStringList exclusions;\n    QModelIndex root = rootIndex();\n\n    getExclusionsForNode(root, exclusions);\n\n    return exclusions;\n}\n\nvoid\nCheckFileSystemView::getExclusionsForNode( const QModelIndex& index, QStringList& exclusions)\n{\n    // Look at first node\n    // Is it unchecked?\n    //  - move on to next node\n    // Is it checked?\n    //  - add to list\n    //  - move to next node\n    // Is it partially checked?\n    //  - recurse\n\n    int numChildren = m_fsModel->rowCount(index);\n    for (int i = 0; i < numChildren; ++i)\n    {\n        QModelIndex kid = m_fsModel->index(i, 0, index);\n        Qt::CheckState check = m_fsModel->getCheck(kid);\n        if (check == Qt::Unchecked)\n        {\n            continue;\n        }\n        else if (check == Qt::Checked)\n        {\n            exclusions.append(m_fsModel->filePath(kid));\n        }\n        else if (check == Qt::PartiallyChecked)\n        {\n            getExclusionsForNode(kid, exclusions);\n        }\n        else\n        {\n            Q_ASSERT(false);\n        }\n    }\n}\n\nvoid\nCheckFileSystemView::onCollapse( const QModelIndex& /*idx*/ )\n{\n\n}\n\nvoid\nCheckFileSystemView::onExpand( const QModelIndex& idx )\n{\n    // If the node is partially checked, that means we have been below it\n    // setting some stuff, so only fill down if we are unchecked.\n    if (m_fsModel->getCheck(idx) != Qt::PartiallyChecked)\n    {\n        fillDown(idx);\n    }\n}\n\nvoid\nCheckFileSystemView::updateNode( const QModelIndex& idx )\n{\n    // Start by recursing down to the bottom and then work upwards\n    fillDown(idx);\n    updateParent(idx);\n}\n\nvoid\nCheckFileSystemView::fillDown( const QModelIndex& parent )\n{\n    // Recursion stops when we reach a directory which has never been expanded\n    // or one that has no children.\n    if (!isExpanded(parent) ||\n        !m_fsModel->hasChildren(parent))\n    {\n        return;\n    }\n\n    Qt::CheckState state = m_fsModel->getCheck(parent);\n    int numChildren = m_fsModel->rowCount(parent);\n    for (int i = 0; i < numChildren; ++i)\n    {\n        QModelIndex kid = m_fsModel->index(i, 0, parent);\n        m_fsModel->setCheck(kid, state);\n        fillDown(kid);\n    }\n}\n\nvoid\nCheckFileSystemView::updateParent( const QModelIndex& index )\n{\n    QModelIndex parent = index.parent();\n\n    if (!parent.isValid())\n    {\n        // We have reached the root\n        return;\n    }\n\n    // Initialise overall state to state of first child\n    QModelIndex kid = m_fsModel->index(0, 0, parent);\n    Qt::CheckState overall = m_fsModel->getCheck(kid);\n\n    int numChildren = m_fsModel->rowCount(parent);\n    for (int i = 1; i <= numChildren; ++i)\n    {\n        kid = m_fsModel->index(i, 0, parent);\n        Qt::CheckState state = m_fsModel->getCheck(kid);\n        if (state != overall)\n        {\n            // If we ever come across a state different than the first child,\n            // we are partially checked\n            overall = Qt::PartiallyChecked;\n            break;\n        }\n    }\n\n    m_fsModel->setCheck(parent, overall);\n\n    updateParent(parent);\n}\n"
  },
  {
    "path": "app/client/Settings/CheckFileSystemView.h",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef CHECKFILESYSTEMVIEW_H\n#define CHECKFILESYSTEMVIEW_H\n\n#include \"CheckFileSystemModel.h\"\n\n#include <QTreeView>\n\nclass CheckFileSystemView : public QTreeView\n{\n    Q_OBJECT\npublic:\n    explicit CheckFileSystemView( QWidget* parent = 0 );\n\n    void checkPath( const QString& path, Qt::CheckState state );\n    void setExclusions( const QStringList& list );\n    QStringList getExclusions();\n\nsignals:\n    void dataChanged();\n\nprivate:\n    void fillDown( const QModelIndex& index);\n    void updateParent( const QModelIndex& index );\n    void getExclusionsForNode( const QModelIndex& index, QStringList&exclusions);\n\nprivate slots:\n    void onCollapse( const QModelIndex& idx );\n    void onExpand( const QModelIndex& idx);\n    void updateNode( const QModelIndex& idx);\n\nprivate:\n    CheckFileSystemModel* m_fsModel;\n    QSet<qint64>  m_expandedSet;\n};\n\n#endif // CHECKFILESYSTEMVIEW_H\n"
  },
  {
    "path": "app/client/Settings/GeneralSettingsWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QComboBox>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include \"../Application.h\"\n\n#include \"ui_GeneralSettingsWidget.h\"\n#include \"GeneralSettingsWidget.h\"\n\nGeneralSettingsWidget::GeneralSettingsWidget( QWidget* parent )\n    :SettingsWidget( parent ),\n      ui( new Ui::GeneralSettingsWidget )\n{\n    ui->setupUi( this );\n\n    populateLanguages();\n\n    ui->notifications->setChecked( unicorn::Settings().notifications() );\n    ui->sendCrashReports->setChecked( unicorn::Settings().sendCrashReports() );\n    ui->beta->setChecked( unicorn::Settings().betaUpdates() );\n\n#if !defined( Q_OS_WIN ) && !defined( Q_OS_MAC )\n    ui->beta->hide(); // only have a beta update setting in mac and windows\n#endif\n\n#ifdef Q_OS_MAC\n\n    ui->showAs->setChecked( unicorn::Settings().showAS() );\n    ui->showDock->setChecked( unicorn::Settings().showDock() );\n\n#else\n    ui->showDock->hide();\n\n    ui->showAs->setChecked( unicorn::Settings().showAS() );\n#endif\n\n#ifndef Q_WS_X11\n    ui->launch->setChecked( unicorn::OldeAppSettings().launchWithMediaPlayers() );\n    ui->updates->setChecked( unicorn::Settings().checkForUpdates() );\n#else\n    ui->launch->hide();\n    ui->updates->hide();\n#endif\n\n    connect( ui->languages, SIGNAL( currentIndexChanged( int ) ), SLOT( onSettingsChanged() ) );\n    connect( ui->notifications, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n    connect( ui->sendCrashReports, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n    connect( ui->beta, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n    connect( ui->showAs, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n    connect( ui->showDock, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n    connect( ui->updates, SIGNAL(stateChanged(int)), SLOT( onSettingsChanged() ) );\n}\n\nvoid\nGeneralSettingsWidget::populateLanguages()\n{\n    ui->languages->addItem( tr( \"System Language\" ), \"\" );\n    ui->languages->addItem( \"English\", QLocale( QLocale::English, QLocale::UnitedKingdom ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"français\" ), QLocale( QLocale::French ).name() );\n    ui->languages->addItem( \"Italiano\", QLocale( QLocale::Italian ).name() );\n    ui->languages->addItem( \"Deutsch\", QLocale( QLocale::German ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"Español\" ), QLocale( QLocale::Spanish ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"Português\" ), QLocale( QLocale::Portuguese, QLocale::Brazil ).name() );\n    ui->languages->addItem( \"Polski\", QLocale( QLocale::Polish ).name() );\n    ui->languages->addItem( \"Svenska\", QLocale( QLocale::Swedish ).name());\n    ui->languages->addItem( QString::fromUtf8( \"Türkçe\" ), QLocale( QLocale::Turkish ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"Pусский\" ), QLocale( QLocale::Russian ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"简体中文\" ), QLocale( QLocale::Chinese, QLocale::China ).name() );\n    ui->languages->addItem( QString::fromUtf8( \"日本語\" ), QLocale( QLocale::Japanese ).name());\n\n    QString currLanguage = unicorn::AppSettings().value( \"language\", \"\" ).toString();\n    int index = ui->languages->findData( currLanguage );\n    if ( index != -1 )\n    {\n        ui->languages->setCurrentIndex( index );\n    }\n}\n\nvoid\nGeneralSettingsWidget::saveSettings()\n{\n    qDebug() << \"has unsaved changes?\" << hasUnsavedChanges();\n    if ( hasUnsavedChanges() )\n    {\n        bool restartNeeded = false;\n\n        int currIndex = ui->languages->currentIndex();\n        QString currLanguage = ui->languages->itemData( currIndex ).toString();\n\n        if ( unicorn::AppSettings().value( \"language\", \"\" ) != currLanguage )\n        {\n            if ( currLanguage == \"\"  )\n                QLocale::setDefault( QLocale::system() );\n            else\n                QLocale::setDefault( QLocale( currLanguage ) );\n\n            unicorn::AppSettings().setValue( \"language\", currLanguage );\n\n#ifdef Q_OS_MAC\n            aApp->translate();\n#endif\n\n            restartNeeded = true;\n        }\n\n        // setting is for the 'Client' aplication for compatibility with old media player plugins\n        unicorn::OldeAppSettings().setLaunchWithMediaPlayers( ui->launch->isChecked() );\n\n        unicorn::Settings().setNotifications( ui->notifications->isChecked() );\n        unicorn::Settings().setSendCrashReports( ui->sendCrashReports->isChecked() );\n        unicorn::Settings().setCheckForUpdates( ui->updates->isChecked() );\n        unicorn::Settings().setBetaUpdates( ui->beta->isChecked() );\n\n        aApp->setBetaUpdates( ui->beta->isChecked() );\n\n#ifdef Q_OS_MAC\n\n        /// dock hiding\n        bool showDockOld = unicorn::Settings().showDock();\n        unicorn::Settings().setShowDock( ui->showDock->isChecked() );\n\n        if ( showDockOld != ui->showDock->isChecked() )\n        {\n            // the setting has changed\n            aApp->showDockIcon( ui->showDock->isChecked() );\n\n            // Hiding the dock icon while the app is running is not supported on Snow Leopard\n            if ( QSysInfo::MacintoshVersion <= QSysInfo::MV_10_6 && !ui->showDock->isChecked() )\n                restartNeeded = true;\n        }\n#endif\n\n        unicorn::Settings().setShowAS( ui->showAs->isChecked() );\n        aApp->showAs( ui->showAs->isChecked() );\n\n        onSettingsSaved();\n\n        if ( restartNeeded )\n        {\n            int button = QMessageBoxBuilder( this )\n                            .setIcon( QMessageBox::Question )\n                            .setTitle( tr( \"Restart now?\" ) )\n                            .setText( tr( \"An application restart is required for the change to take effect. Would you like to restart now?\" ) )\n                            .setButtons( QMessageBox::Yes | QMessageBox::No )\n                            .exec();\n\n            if ( button == QMessageBox::Yes )\n                aApp->restart();\n        }\n    }\n}\n"
  },
  {
    "path": "app/client/Settings/GeneralSettingsWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef GENERALSETTINGSWIDGET_H\n#define GENERALSETTINGSWIDGET_H\n\n#include \"SettingsWidget.h\"\n\nnamespace Ui {\n    class GeneralSettingsWidget;\n}\n\nclass GeneralSettingsWidget : public SettingsWidget\n{\n    Q_OBJECT\n\npublic:\n    GeneralSettingsWidget( QWidget* parent = 0 );\n\nprivate:\n    void saveSettings();\n    void populateLanguages();\n\nprivate:\n    Ui::GeneralSettingsWidget* ui;\n};\n\n#endif // GENERALSETTINGSWIDGET_H\n"
  },
  {
    "path": "app/client/Settings/GeneralSettingsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>GeneralSettingsWidget</class>\n <widget class=\"QWidget\" name=\"GeneralSettingsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>491</width>\n    <height>311</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QGridLayout\" name=\"gridLayout\" columnstretch=\"0,1\">\n   <item row=\"7\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"updates\">\n     <property name=\"enabled\">\n      <bool>false</bool>\n     </property>\n     <property name=\"text\">\n      <string>Check for updates automatically</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"3\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"launch\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"text\">\n      <string>Launch application with media players</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"8\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"sendCrashReports\">\n     <property name=\"enabled\">\n      <bool>false</bool>\n     </property>\n     <property name=\"text\">\n      <string>Send crash reports to Last.fm</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"1\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"showAs\">\n     <property name=\"text\">\n      <string>Show application icon in menu bar</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"11\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"beta\">\n     <property name=\"text\">\n      <string>Update to beta versions - Warning: only for the brave!</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"2\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"showDock\">\n     <property name=\"text\">\n      <string>Show dock icon</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"4\" column=\"1\">\n    <widget class=\"QCheckBox\" name=\"notifications\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"text\">\n      <string>Show desktop notifications</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"0\" column=\"1\">\n    <widget class=\"QComboBox\" name=\"languages\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item row=\"0\" column=\"0\">\n    <widget class=\"QLabel\" name=\"languageLabel\">\n     <property name=\"text\">\n      <string>Language:</string>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/IpodSettingsWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"ui_IpodSettingsWidget.h\"\n#include \"IpodSettingsWidget.h\"\n\n#ifdef Q_WS_X11\n#include \"../MediaDevices/IpodDevice_linux.h\"\n#endif\n\n#ifdef Q_OS_WIN\n#include \"lib/unicorn/plugins/ITunesPluginInfo.h\"\n#endif\n\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include \"../MediaDevices/IpodDevice.h\"\n\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n\n#include <lastfm/User.h>\n\n#include <QCheckBox>\n#include <QComboBox>\n#include <QDebug>\n#include <QFrame>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QHeaderView>\n#include <QLabel>\n#include <QPushButton>\n#include <QSpacerItem>\n#include <QTreeWidget>\n#include <QVBoxLayout>\n\nIpodSettingsWidget::IpodSettingsWidget( QWidget* parent )\n    : SettingsWidget( parent ),\n      ui( new Ui::IpodSettingsWidget )\n{\n    ui->setupUi( this );\n\n    ui->alwaysAsk->setChecked( unicorn::AppSettings().alwaysAsk() );\n    connect( ui->alwaysAsk, SIGNAL(clicked(bool)), SLOT(onSettingsChanged()));\n\n#ifdef Q_WS_X11\n    ui->deviceScrobblingEnabled->hide();\n#else\n    ui->deviceScrobblingEnabled->setChecked( unicorn::OldeAppSettings().deviceScrobblingEnabled() );\n    connect( ui->deviceScrobblingEnabled, SIGNAL(clicked(bool)), SLOT(onSettingsChanged()));\n#endif\n\n    ui->note->setText( unicorn::Label::boldLinkStyle( tr( \"<p>Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.</p>\"\n                                                          \"<p>iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.</p>\" ).arg( unicorn::Label::anchor( \"itmss://itunes.apple.com/gb/app/scrobbler-for-ios/id585235199\", \"Scrobbler for iOS\" ) ), Qt::black ) );\n    ui->note->adjustSize();\n    ui->noteBox->adjustSize();\n}\n\nvoid\nIpodSettingsWidget::saveSettings()\n{\n    if ( hasUnsavedChanges() )\n    {\n        // save settings\n        qDebug() << \"Saving settings...\";\n\n        unicorn::AppSettings().setAlwaysAsk( ui->alwaysAsk->isChecked() );\n\n        // we need to restart iTunes for this setting to take affect\n        bool currentlyEnabled = unicorn::OldeAppSettings().deviceScrobblingEnabled();\n\n#ifndef Q_WS_X11\n        if ( currentlyEnabled != ui->deviceScrobblingEnabled->isChecked() )\n        {\n#ifdef Q_OS_WIN\n            QList<unicorn::IPluginInfo*> plugins;\n            unicorn::ITunesPluginInfo* iTunesPluginInfo = new unicorn::ITunesPluginInfo;\n            plugins << iTunesPluginInfo;\n            unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( plugins, this );\n            closeApps->setOwnsPlugins( true );\n#else\n            unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( this );\n#endif\n            if ( closeApps->result() != QDialog::Accepted )\n                closeApps->exec();\n            else\n                closeApps->deleteLater();\n\n            if ( closeApps->result() == QDialog::Accepted )\n            {\n                unicorn::OldeAppSettings().setDeviceScrobblingEnabled( ui->deviceScrobblingEnabled->isChecked() );\n            }\n            else\n            {\n                ui->deviceScrobblingEnabled->setChecked( currentlyEnabled );\n\n                // The user didn't close their media players\n                QMessageBoxBuilder( this ).setTitle( tr( \"Setting not changed\" ) )\n                        .setIcon( QMessageBox::Warning )\n                        .setText( tr( \"You did not close iTunes for this setting to change\" ) )\n                        .setButtons( QMessageBox::Ok )\n                        .exec();\n            }\n        }\n#endif\n\n        onSettingsSaved();\n    }\n}\n"
  },
  {
    "path": "app/client/Settings/IpodSettingsWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef IPOD_SETTINGS_H\n#define IPOD_SETTINGS_H\n\n#include \"SettingsWidget.h\"\n\nnamespace Ui { class IpodSettingsWidget; }\n\nclass IpodSettingsWidget: public SettingsWidget\n{\n    Q_OBJECT\n\npublic:\n    IpodSettingsWidget( QWidget* parent = 0 );\n\npublic slots:\n    virtual void saveSettings();\n\nprivate:\n    Ui::IpodSettingsWidget* ui;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Settings/IpodSettingsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>IpodSettingsWidget</class>\n <widget class=\"QWidget\" name=\"IpodSettingsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>418</width>\n    <height>365</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"QCheckBox\" name=\"deviceScrobblingEnabled\">\n     <property name=\"text\">\n      <string>Enable Device Scrobbling</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QCheckBox\" name=\"alwaysAsk\">\n     <property name=\"text\">\n      <string>Confirm Device Scrobbles</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QGroupBox\" name=\"noteBox\">\n     <property name=\"title\">\n      <string>Please note</string>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n      <item>\n       <widget class=\"unicorn::Label\" name=\"note\">\n        <property name=\"text\">\n         <string notr=\"true\"/>\n        </property>\n        <property name=\"textFormat\">\n         <enum>Qt::RichText</enum>\n        </property>\n        <property name=\"wordWrap\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <spacer name=\"verticalSpacer\">\n     <property name=\"orientation\">\n      <enum>Qt::Vertical</enum>\n     </property>\n     <property name=\"sizeHint\" stdset=\"0\">\n      <size>\n       <width>20</width>\n       <height>0</height>\n      </size>\n     </property>\n    </spacer>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header location=\"global\">lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/PreferencesDialog.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QToolBar>\n#include <QToolButton>\n#include <QPushButton>\n#include <QShortcut>\n\n#include \"PreferencesDialog.h\"\n#include \"ui_PreferencesDialog.h\"\n\nPreferencesDialog::PreferencesDialog( QMenuBar* menuBar, QWidget* parent )\n    :unicorn::MainWindow( menuBar, parent ),\n    ui( new Ui::PreferencesDialog )\n{\n    // Disable the minimize and maximize buttons.\n    Qt::WindowFlags flags = this->windowFlags();\n    flags &= ~Qt::WindowMinMaxButtonsHint;\n    setWindowFlags(flags);\n\n    ui->setupUi( this );\n\n    setAttribute( Qt::WA_DeleteOnClose, true );\n\n    static_cast<QAbstractButton*>( ui->toolBar->widgetForAction( ui->actionGeneral ) )->setAutoExclusive( true );\n    static_cast<QAbstractButton*>( ui->toolBar->widgetForAction( ui->actionScrobbling ) )->setAutoExclusive( true );\n    static_cast<QAbstractButton*>( ui->toolBar->widgetForAction( ui->actionDevices ) )->setAutoExclusive( true );\n    static_cast<QAbstractButton*>( ui->toolBar->widgetForAction( ui->actionAccounts ) )->setAutoExclusive( true );\n    static_cast<QAbstractButton*>( ui->toolBar->widgetForAction( ui->actionAdvanced ) )->setAutoExclusive( true );\n\n    connect( ui->toolBar->widgetForAction( ui->actionGeneral ), SIGNAL(toggled(bool)), ui->actionGeneral, SLOT(setChecked(bool)) );\n    connect( ui->toolBar->widgetForAction( ui->actionScrobbling ), SIGNAL(toggled(bool)), ui->actionScrobbling, SLOT(setChecked(bool)) );\n    connect( ui->toolBar->widgetForAction( ui->actionDevices ), SIGNAL(toggled(bool)), ui->actionDevices, SLOT(setChecked(bool)) );\n    connect( ui->toolBar->widgetForAction( ui->actionAccounts ), SIGNAL(toggled(bool)), ui->actionAccounts, SLOT(setChecked(bool)) );\n    connect( ui->toolBar->widgetForAction( ui->actionAdvanced ), SIGNAL(toggled(bool)), ui->actionAdvanced, SLOT(setChecked(bool)) );\n\n    connect( this, SIGNAL( saveNeeded() ), ui->general, SLOT( saveSettings() ) );\n    connect( this, SIGNAL( saveNeeded() ), ui->scrobbling, SLOT( saveSettings() ) );\n    connect( this, SIGNAL( saveNeeded() ), ui->ipod, SLOT( saveSettings() ) );\n    connect( this, SIGNAL( saveNeeded() ), ui->accounts, SLOT( saveSettings() ) );\n    connect( this, SIGNAL( saveNeeded() ), ui->advanced, SLOT( saveSettings() ) );\n\n    connect( ui->general, SIGNAL( settingsChanged() ), SLOT( onSettingsChanged() ) );\n    connect( ui->scrobbling, SIGNAL( settingsChanged() ), SLOT( onSettingsChanged() ) );\n    connect( ui->ipod, SIGNAL( settingsChanged() ), SLOT( onSettingsChanged() ) );\n    connect( ui->accounts, SIGNAL( settingsChanged() ), SLOT( onSettingsChanged() ) );\n    connect( ui->advanced, SIGNAL( settingsChanged() ), SLOT( onSettingsChanged() ) );\n\n    connect( ui->actionGeneral, SIGNAL(triggered()), SLOT(onTabButtonClicked()));\n    connect( ui->actionScrobbling, SIGNAL(triggered()), SLOT(onTabButtonClicked()));\n    connect( ui->actionDevices, SIGNAL(triggered()), SLOT(onTabButtonClicked()));\n    connect( ui->actionAccounts, SIGNAL(triggered()), SLOT(onTabButtonClicked()));\n    connect( ui->actionAdvanced, SIGNAL(triggered()), SLOT(onTabButtonClicked()));\n\n    connect( ui->stackedWidget, SIGNAL(currentChanged(int)), this, SLOT(onStackCurrentChanged(int)), Qt::QueuedConnection );\n\n#ifdef Q_OS_MAC\n    ui->buttonBox->hide();\n#endif\n    connect( ui->buttonBox, SIGNAL( accepted() ), SLOT( onAccepted() ) );\n    connect( ui->buttonBox, SIGNAL( rejected() ), SLOT( onRejected() ) );\n\n    QAbstractButton* applyButton = ui->buttonBox->button( QDialogButtonBox::Apply );\n    applyButton->setEnabled( false );\n    connect( applyButton, SIGNAL( clicked() ), SLOT( onApplyButtonClicked() ) );\n\n    setFixedWidth( 550 );\n\n    ui->stackedWidget->setCurrentWidget( ui->accounts );\n    ui->actionGeneral->trigger();\n}\n\nPreferencesDialog::~PreferencesDialog()\n{\n    delete ui;\n}\n\nvoid\nPreferencesDialog::onTabButtonClicked()\n{\n    QAction* clickedButton = qobject_cast<QAction*>(sender());\n\n    setWindowTitle( clickedButton->text() );\n\n    if ( clickedButton == ui->actionGeneral )\n        ui->stackedWidget->setCurrentWidget( ui->general );\n    else if ( clickedButton == ui->actionAccounts )\n        ui->stackedWidget->setCurrentWidget( ui->accounts );\n    else if ( clickedButton == ui->actionDevices )\n        ui->stackedWidget->setCurrentWidget( ui->ipod );\n    else if ( clickedButton == ui->actionAdvanced )\n        ui->stackedWidget->setCurrentWidget( ui->advanced );\n    else if ( clickedButton == ui->actionScrobbling )\n        ui->stackedWidget->setCurrentWidget( ui->scrobbling );\n}\n\nvoid\nPreferencesDialog::onStackCurrentChanged( int /*index*/ )\n{\n    adjustSize();\n}\n\nvoid\nPreferencesDialog::onAccepted()\n{\n    emit saveNeeded();\n    close();\n}\n\nvoid\nPreferencesDialog::onRejected()\n{\n    close();\n}\n\nvoid\nPreferencesDialog::onSettingsChanged()\n{\n    ui->buttonBox->button( QDialogButtonBox::Apply )->setEnabled( true );\n}\n\nvoid\nPreferencesDialog::onApplyButtonClicked()\n{\n    emit saveNeeded();\n    ui->buttonBox->button( QDialogButtonBox::Apply )->setEnabled( false );\n}\n"
  },
  {
    "path": "app/client/Settings/PreferencesDialog.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PREFERENCESDIALOG_H\n#define PREFERENCESDIALOG_H\n\n#include <QDialog>\n\n#include \"lib/unicorn/dialogs/UnicornDialog.h\"\n\nnamespace Ui {\n    class PreferencesDialog;\n}\n\nclass PreferencesDialog : public unicorn::MainWindow\n{\n    Q_OBJECT\n\npublic:\n    explicit PreferencesDialog( QMenuBar* menuBar, QWidget* parent = 0 );\n    ~PreferencesDialog();\n\nsignals:\n    void saveNeeded();\n\nprivate slots:\n    void onTabButtonClicked();\n\n    void onAccepted();\n    void onRejected();\n\n    void onSettingsChanged();\n    void onApplyButtonClicked();\n\n    void onStackCurrentChanged( int index );\n\nprivate:\n    Ui::PreferencesDialog *ui;\n};\n\n#endif // PREFERENCESDIALOG_H\n"
  },
  {
    "path": "app/client/Settings/PreferencesDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>PreferencesDialog</class>\n <widget class=\"QMainWindow\" name=\"PreferencesDialog\">\n  <property name=\"windowModality\">\n   <enum>Qt::NonModal</enum>\n  </property>\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>583</width>\n    <height>466</height>\n   </rect>\n  </property>\n  <property name=\"sizePolicy\">\n   <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Expanding\">\n    <horstretch>0</horstretch>\n    <verstretch>0</verstretch>\n   </sizepolicy>\n  </property>\n  <property name=\"focusPolicy\">\n   <enum>Qt::StrongFocus</enum>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">MainWindow</string>\n  </property>\n  <property name=\"unifiedTitleAndToolBarOnMac\">\n   <bool>true</bool>\n  </property>\n  <widget class=\"QWidget\" name=\"centralwidget\">\n   <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n    <item>\n     <widget class=\"unicorn::StackedWidget\" name=\"stackedWidget\">\n      <property name=\"sizePolicy\">\n       <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n        <horstretch>0</horstretch>\n        <verstretch>0</verstretch>\n       </sizepolicy>\n      </property>\n      <widget class=\"GeneralSettingsWidget\" name=\"general\"/>\n      <widget class=\"AccountSettingsWidget\" name=\"accounts\"/>\n      <widget class=\"ScrobbleSettingsWidget\" name=\"scrobbling\"/>\n      <widget class=\"IpodSettingsWidget\" name=\"ipod\"/>\n      <widget class=\"AdvancedSettingsWidget\" name=\"advanced\"/>\n     </widget>\n    </item>\n    <item>\n     <widget class=\"QDialogButtonBox\" name=\"buttonBox\">\n      <property name=\"standardButtons\">\n       <set>QDialogButtonBox::Apply|QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>\n      </property>\n     </widget>\n    </item>\n   </layout>\n  </widget>\n  <widget class=\"QToolBar\" name=\"toolBar\">\n   <property name=\"sizePolicy\">\n    <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n     <horstretch>0</horstretch>\n     <verstretch>0</verstretch>\n    </sizepolicy>\n   </property>\n   <property name=\"windowTitle\">\n    <string notr=\"true\">toolBar</string>\n   </property>\n   <property name=\"movable\">\n    <bool>false</bool>\n   </property>\n   <property name=\"allowedAreas\">\n    <set>Qt::TopToolBarArea</set>\n   </property>\n   <property name=\"toolButtonStyle\">\n    <enum>Qt::ToolButtonTextUnderIcon</enum>\n   </property>\n   <property name=\"floatable\">\n    <bool>false</bool>\n   </property>\n   <attribute name=\"toolBarArea\">\n    <enum>TopToolBarArea</enum>\n   </attribute>\n   <attribute name=\"toolBarBreak\">\n    <bool>false</bool>\n   </attribute>\n   <addaction name=\"actionGeneral\"/>\n   <addaction name=\"actionAccounts\"/>\n   <addaction name=\"actionScrobbling\"/>\n   <addaction name=\"actionDevices\"/>\n   <addaction name=\"actionAdvanced\"/>\n  </widget>\n  <action name=\"actionGeneral\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"checked\">\n    <bool>true</bool>\n   </property>\n   <property name=\"icon\">\n    <iconset resource=\"../qrc/audioscrobbler.qrc\">\n     <normaloff>:/preferences_general.png</normaloff>:/preferences_general.png</iconset>\n   </property>\n   <property name=\"text\">\n    <string>General</string>\n   </property>\n  </action>\n  <action name=\"actionAccounts\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"icon\">\n    <iconset resource=\"../qrc/audioscrobbler.qrc\">\n     <normaloff>:/preferences_accounts.png</normaloff>:/preferences_accounts.png</iconset>\n   </property>\n   <property name=\"text\">\n    <string>Accounts</string>\n   </property>\n  </action>\n  <action name=\"actionScrobbling\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"icon\">\n    <iconset resource=\"../qrc/audioscrobbler.qrc\">\n     <normaloff>:/preferences_scrobbling.png</normaloff>:/preferences_scrobbling.png</iconset>\n   </property>\n   <property name=\"text\">\n    <string>Scrobbling</string>\n   </property>\n  </action>\n  <action name=\"actionDevices\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"icon\">\n    <iconset resource=\"../qrc/audioscrobbler.qrc\">\n     <normaloff>:/preferences_devices.png</normaloff>:/preferences_devices.png</iconset>\n   </property>\n   <property name=\"text\">\n    <string>Devices</string>\n   </property>\n  </action>\n  <action name=\"actionAdvanced\">\n   <property name=\"checkable\">\n    <bool>true</bool>\n   </property>\n   <property name=\"icon\">\n    <iconset resource=\"../qrc/audioscrobbler.qrc\">\n     <normaloff>:/preferences_advanced.png</normaloff>:/preferences_advanced.png</iconset>\n   </property>\n   <property name=\"text\">\n    <string>Advanced</string>\n   </property>\n  </action>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::StackedWidget</class>\n   <extends>QStackedWidget</extends>\n   <header>lib/unicorn/widgets/StackedWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>AccountSettingsWidget</class>\n   <extends>QWidget</extends>\n   <header>../Settings/AccountSettingsWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>ScrobbleSettingsWidget</class>\n   <extends>QWidget</extends>\n   <header>../Settings/ScrobbleSettingsWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>IpodSettingsWidget</class>\n   <extends>QWidget</extends>\n   <header>../Settings/IpodSettingsWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>GeneralSettingsWidget</class>\n   <extends>QWidget</extends>\n   <header>../Settings/GeneralSettingsWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>AdvancedSettingsWidget</class>\n   <extends>QWidget</extends>\n   <header>../Settings/AdvancedSettingsWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources>\n  <include location=\"../qrc/audioscrobbler.qrc\"/>\n </resources>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/ScrobbleSettingsWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QCheckBox>\n#include <QDebug>\n#include <QFrame>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QSlider>\n#include <QVBoxLayout>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"../Application.h\"\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"ui_ScrobbleSettingsWidget.h\"\n#include \"ScrobbleSettingsWidget.h\"\n\nScrobbleSettingsWidget::ScrobbleSettingsWidget( QWidget* parent )\n    : SettingsWidget( parent ),\n      ui( new Ui::ScrobbleSettingsWidget )\n{\n    ui->setupUi( this );\n\n    unicorn::UserSettings userSettings;\n\n    double scrobblePointValue = userSettings.scrobblePoint();\n    ui->scrobblePoint->setValue( scrobblePointValue );\n    ui->percentText->setText( QString::number(scrobblePointValue) );\n    ui->percentText->setFixedWidth( ui->percentText->fontMetrics().width( \"100\" ) );\n    m_initialScrobblePercentage = scrobblePointValue;\n\n    ui->allowFingerprint->setChecked( userSettings.fingerprinting() );\n\n    ui->enfocreScrobbleTimeMax->setChecked( userSettings.enforceScrobbleTimeMax() );\n    ui->scrobblingOn->setChecked( userSettings.scrobblingOn() );\n    ui->podcasts->setChecked( userSettings.podcasts() );\n\n    QStringList exclusionDirs = userSettings.exclusionDirs();\n    exclusionDirs.removeAll( \"\" );\n    ui->exclusionDirs->setExclusions( exclusionDirs );\n\n    connect( ui->scrobblePoint, SIGNAL(sliderMoved(int)), SLOT(onSliderMoved(int)) );\n    connect( ui->scrobblePoint, SIGNAL(valueChanged(int)), SLOT(onSliderMoved(int)) );\n    connect( ui->scrobblePoint, SIGNAL(valueChanged(int)), SLOT(onSettingsChanged()) );\n    connect( ui->allowFingerprint, SIGNAL(stateChanged(int)), SLOT(onSettingsChanged()) );\n\n    connect( aApp, SIGNAL(scrobbleToggled(bool)), ui->scrobblingOn, SLOT(setChecked(bool)));\n    connect( ui->scrobblingOn, SIGNAL(clicked(bool)), SLOT(onSettingsChanged()) );\n    connect( ui->podcasts, SIGNAL(stateChanged(int)), SLOT(onSettingsChanged()) );\n    connect( ui->enfocreScrobbleTimeMax, SIGNAL(stateChanged(int)), SLOT(onSettingsChanged()) );\n\n    connect( ui->exclusionDirs, SIGNAL(dataChanged()), SLOT(onSettingsChanged()) );\n}\n\nScrobbleSettingsWidget::~ScrobbleSettingsWidget()\n{\n    if ( unicorn::UserSettings().scrobblePoint() != m_initialScrobblePercentage )\n        AnalyticsService::instance().sendEvent(SETTINGS_CATEGORY, SCROBBLING_SETTINGS, \"ScrobblePercentageChanged\", QString::number( ui->scrobblePoint->value() ) );\n}\n\nvoid\nScrobbleSettingsWidget::onSliderMoved( int value )\n{\n    ui->percentText->setText( QString::number( value ) );\n}\n\nvoid\nScrobbleSettingsWidget::saveSettings()\n{\n    if ( hasUnsavedChanges() )\n    {\n        qDebug() << \"Saving settings...\";\n\n        aApp->onScrobbleToggled( ui->scrobblingOn->isChecked() );\n\n        unicorn::UserSettings userSettings;\n        userSettings.setScrobblePoint( ui->scrobblePoint->value() );\n        userSettings.setFingerprinting( ui->allowFingerprint->isChecked() );\n        userSettings.setPodcasts( ui->podcasts->isChecked() );\n        userSettings.setEnforceScrobbleTimeMax( ui->enfocreScrobbleTimeMax->isChecked() );\n\n        QStringList exclusionDirs = ui->exclusionDirs->getExclusions();\n        exclusionDirs.removeAll( \"\" );\n        qDebug() << exclusionDirs;\n        userSettings.setExclusionDirs( exclusionDirs );\n\n        userSettings.sync();\n\n        ScrobbleService::instance().scrobbleSettingsChanged();\n\n        onSettingsSaved();\n    }\n}\n"
  },
  {
    "path": "app/client/Settings/ScrobbleSettingsWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SCROBBLE_SETTINGS_WIDGET_H\n#define SCROBBLE_SETTINGS_WIDGET_H\n\n#include \"SettingsWidget.h\"\n\nnamespace Ui { class ScrobbleSettingsWidget; }\n\nclass ScrobbleSettingsWidget: public SettingsWidget\n{\n    Q_OBJECT\n\npublic:\n    ScrobbleSettingsWidget( QWidget* parent = 0 );\n    ~ScrobbleSettingsWidget();\n\npublic slots:\n    virtual void saveSettings();\n\nprivate slots:\n    void onSliderMoved( int value );\n\nprivate:\n    Ui::ScrobbleSettingsWidget* ui;\n    double m_initialScrobblePercentage;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Settings/ScrobbleSettingsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ScrobbleSettingsWidget</class>\n <widget class=\"QWidget\" name=\"ScrobbleSettingsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>400</width>\n    <height>361</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>10</number>\n   </property>\n   <item>\n    <widget class=\"QGroupBox\" name=\"scrobblingOn\">\n     <property name=\"title\">\n      <string>Enable scrobbling</string>\n     </property>\n     <property name=\"checkable\">\n      <bool>true</bool>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_4\">\n      <item>\n       <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n        <item>\n         <widget class=\"QLabel\" name=\"label\">\n          <property name=\"text\">\n           <string>Scrobble at</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QSlider\" name=\"scrobblePoint\">\n          <property name=\"minimum\">\n           <number>50</number>\n          </property>\n          <property name=\"maximum\">\n           <number>100</number>\n          </property>\n          <property name=\"singleStep\">\n           <number>1</number>\n          </property>\n          <property name=\"tracking\">\n           <bool>false</bool>\n          </property>\n          <property name=\"orientation\">\n           <enum>Qt::Horizontal</enum>\n          </property>\n          <property name=\"tickPosition\">\n           <enum>QSlider::TicksBelow</enum>\n          </property>\n          <property name=\"tickInterval\">\n           <number>10</number>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"percentText\">\n          <property name=\"text\">\n           <string notr=\"true\">50</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"label_3\">\n          <property name=\"text\">\n           <string>percent of the track</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"horizontalSpacer\">\n          <property name=\"orientation\">\n           <enum>Qt::Horizontal</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>40</width>\n            <height>20</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n       </layout>\n      </item>\n      <item>\n       <widget class=\"QCheckBox\" name=\"enfocreScrobbleTimeMax\">\n        <property name=\"text\">\n         <string>...or at 4 minutes (whichever comes first)</string>\n        </property>\n        <property name=\"checked\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QCheckBox\" name=\"podcasts\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"text\">\n      <string>Scrobble podcasts</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QCheckBox\" name=\"allowFingerprint\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"text\">\n      <string>Allow Last.fm to fingerprint my tracks</string>\n     </property>\n     <property name=\"checked\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QGroupBox\" name=\"directoriesBox\">\n     <property name=\"title\">\n      <string>Selected directories will not be scrobbled</string>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n      <property name=\"spacing\">\n       <number>10</number>\n      </property>\n      <property name=\"topMargin\">\n       <number>12</number>\n      </property>\n      <item>\n       <widget class=\"CheckFileSystemView\" name=\"exclusionDirs\">\n        <property name=\"headerHidden\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>CheckFileSystemView</class>\n   <extends>QTreeView</extends>\n   <header>../Settings/CheckFileSystemView.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Settings/SettingsWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"SettingsWidget.h\"\n\nSettingsWidget::SettingsWidget( QWidget* parent )\n    : QWidget( parent )\n    , m_settingsChanged( false )\n{\n}\n\nvoid\nSettingsWidget::onSettingsChanged()\n{\n    m_settingsChanged = true;\n#ifdef Q_OS_MAC\n    saveSettings();\n#else\n    emit settingsChanged();\n#endif\n}\n\nvoid\nSettingsWidget::onSettingsSaved()\n{\n    m_settingsChanged = false;\n}\n\nbool\nSettingsWidget::hasUnsavedChanges()\n{\n    return m_settingsChanged;\n}\n"
  },
  {
    "path": "app/client/Settings/SettingsWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole, Michael Coffey, and William Viana\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SETTINGS_WIDGET_H\n#define SETTINGS_WIDGET_H\n\n#include <QDialog>\n\nclass SettingsWidget : public QWidget\n{\n    Q_OBJECT\n\npublic:\n    SettingsWidget( QWidget* parent = 0 );\n    bool hasUnsavedChanges();\n\npublic slots:\n    virtual void saveSettings() = 0;\n\nsignals:\n    void settingsChanged();\n    void settingsSaved();\n\nprotected slots:\n    void onSettingsChanged();\n    void onSettingsSaved();\n\nprivate:\n    bool m_settingsChanged;\n};\n\n\n#endif\n"
  },
  {
    "path": "app/client/Widgets/BioWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QEventLoop>\n#include <QApplication>\n#include <QToolTip>\n#include <QTimer>\n#include <QDebug>\n\n#include \"lib/unicorn/widgets/BannerWidget.h\"\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"../Services/AnalyticsService.h\"\n#include \"../Application.h\"\n#include \"WidgetTextObject.h\"\n#include \"BioWidget.h\"\n\nBioWidget::BioWidget( QWidget* p ) \n    :QTextBrowser( p ),\n      m_currentHoverWidget(0)\n{\n    setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );\n    connect(document()->documentLayout(), SIGNAL( documentSizeChanged(QSizeF)), SLOT( onBioChanged(QSizeF)));\n\n    connect(this, SIGNAL(anchorClicked(QUrl)), SLOT(onAnchorClicked(QUrl)));\n\n    m_widgetTextObject = new WidgetTextObject;\n    viewport()->installEventFilter( this );\n    document()->documentLayout()->registerHandler( WidgetImageFormat, m_widgetTextObject );\n\n    ui.image = new HttpImageWidget(this);\n    ui.image->setFixedWidth( 160 );\n    ui.image->setAlignment( Qt::AlignTop );\n    \n    ui.onTour = new BannerWidget( tr(\"On Tour\" ) );\n    ui.onTour->setBannerVisible( false );\n    ui.onTour->setWidget( ui.image );\n\n    ui.onTour->setFixedWidth( 170 );\n    ui.onTour->setObjectName( \"onTour\" );\n\n    connect( ui.image, SIGNAL(loaded()), SLOT(onImageLoaded()));\n    connect( ui.image, SIGNAL(loaded()), SLOT(update()));\n\n    connect( this, SIGNAL(highlighted(QString)), SLOT(onHighlighted(QString)) );\n}\n\nBioWidget::~BioWidget()\n{\n    delete m_widgetTextObject;\n}\n\nvoid\nBioWidget::setBioText( const QString& bioText )\n{\n    m_bioText = bioText;\n}\n\nvoid\nBioWidget::onHighlighted( const QString& url )\n{\n    QUrl displayUrl( url );\n    QToolTip::showText( cursor().pos(), displayUrl.toString(), this, QRect() );\n}\n\nvoid\nBioWidget::onImageLoaded()\n{\n    insertWidget( ui.onTour );\n\n    append( m_bioText );\n\n    updateGeometry();\n    emit finished();\n}\n\n\nvoid \nBioWidget::insertWidget( QWidget* w ) \n{\n    w->installEventFilter( this );\n    m_widgetImageFormat.setObjectType( WidgetImageFormat );\n    m_widgetImageFormat.setProperty( WidgetData, QVariant::fromValue<QWidget*>( w ) );\n    m_widgetImageFormat.setName( w->objectName() );\n    \n    QTextCursor cursor = textCursor();\n    cursor.insertImage( m_widgetImageFormat, QTextFrameFormat::FloatLeft );\n    setTextCursor( cursor );\n}\n\nbool \nBioWidget::eventFilter( QObject* o, QEvent* e )\n{\n    QWidget* w = qobject_cast<QWidget*>( o );\n\n    if ( viewport() == w )\n    {\n        if ( QEvent::MouseMove != e->type() )\n            return false;\n\n        QMouseEvent* event = static_cast<QMouseEvent*>(e);\n        //respect child widget cursor\n        QWidget* w = m_widgetTextObject->widgetAtPoint(event->pos() );\n\n        if ( w != m_currentHoverWidget )\n        {\n            m_currentHoverWidget = w;\n\n            if( 0 == w )\n                viewport()->unsetCursor();\n            else\n            {\n                QWidget* c = w->childAt(event->pos());\n                c = c ? c : w;\n                viewport()->setCursor( c->cursor());\n            }\n        }\n\n        return false;\n    }\n    return false;\n}\n\n\nvoid\nBioWidget::mousePressEvent( QMouseEvent* event )\n{\n    update();\n    if ( !sendMouseEvent(event) )\n        QTextBrowser::mousePressEvent( event );\n}\n\n\nvoid\nBioWidget::mouseReleaseEvent( QMouseEvent* event )\n{\n    if ( !sendMouseEvent(event) )\n        QTextBrowser::mouseReleaseEvent( event );\n}\n\n\nvoid\nBioWidget::mouseMoveEvent( QMouseEvent* event ) \n{\n    if (!sendMouseEvent(event))\n        QTextBrowser::mouseMoveEvent( event );\n}\n\nbool \nBioWidget::sendMouseEvent( QMouseEvent* event ) \n{\n    QWidget* w = m_widgetTextObject->widgetAtPoint( event->pos());\n\n    if ( !w )\n        return false;\n\n    QRectF wRect = m_widgetTextObject->widgetRect( w );\n    QPoint pos = event->pos() - wRect.toRect().topLeft();\n\n    QWidget* childWidget = w->childAt( event->pos());\n\n    if( !childWidget )\n        childWidget = w;\n    else\n        pos = childWidget->mapTo( w, pos );\n\n    QMouseEvent* widgetMouseEvent = new QMouseEvent( event->type(), pos, event->button(), event->buttons(), event->modifiers());\n\n    QCoreApplication::postEvent( childWidget, widgetMouseEvent );\n    event->accept();\n\n    return true;\n}\n\nvoid\nBioWidget::showEvent( QShowEvent* /*event*/ )\n{\n    // HACK: onBioChanged reports the wrong size for the document\n    // and id we polish it a bit later it gets set correctly.\n    // Polish very soon after being shown so that it gets\n    // the right height quickly if you're looking at it.\n    // Do another polish a bit later as for the case when you\n    // switch to that tab as the first one won't work.\n    QTimer::singleShot( 1, this, SLOT(polish()));\n    QTimer::singleShot( 200, this, SLOT(polish()));\n}\n\nvoid \nBioWidget::onAnchorClicked( const QUrl& link )\n{\n    unicorn::DesktopServices::openUrl( link );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), LINK_CLICKED, \"BioPageLinkClicked\");\n}\n\n\nvoid\nBioWidget::onDocumentLayoutChanged()\n{\n    setFixedHeight( document()->size().height() );\n}\n\nvoid \nBioWidget::onBioChanged( const QSizeF& /*size*/ )\n{\n    updateGeometry();\n\n    onDocumentLayoutChanged();\n}\n\nvoid\nBioWidget::polish()\n{\n    if ( isVisible() )\n        style()->polish( this );\n    else\n        QTimer::singleShot( 20, this, SLOT(polish()));\n}\n\nvoid\nBioWidget::setPixmap( const QPixmap& pixmap )\n{\n    ui.image->setPixmap( pixmap );\n}\n\nvoid \nBioWidget::loadImage( const QUrl& url, HttpImageWidget::ScaleType scale )\n{\n    ui.image->loadUrl( url, scale );\n}\n\nvoid\nBioWidget::setImageHref( const QUrl& href )\n{\n    ui.image->setHref( href );\n}\n\nvoid \nBioWidget::setOnTourVisible( bool visible, const QUrl& url )\n{\n    ui.onTour->setBannerVisible( visible );\n\n    if ( url.isValid())\n        ui.onTour->setHref( url );\n\n    update();\n}\n"
  },
  {
    "path": "app/client/Widgets/BioWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BIO_WIDGET_H_\n#define BIO_WIDGET_H_\n\n#include <QTextBrowser>\n#include <QTextObjectInterface>\n#include <QDebug>\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n\n/** A specialized QTextBrowser which can insert widgets inline */\n#include <QPlainTextDocumentLayout>\nclass BioWidget : public QTextBrowser\n{\n    Q_OBJECT\npublic:\n    BioWidget( QWidget* parent );\n    ~BioWidget();\n\n    bool eventFilter( QObject* o, QEvent* e );\n    \n    void setBioText( const QString& bioText );\n\n    void setPixmap( const QPixmap& pixmap );\n    void loadImage( const QUrl&, HttpImageWidget::ScaleType scale = HttpImageWidget::ScaleAuto );\n    void setImageHref( const QUrl& );\n    \n    void setOnTourVisible( bool, const QUrl& = QUrl());\n\nsignals:\n    void finished();\n\nprotected slots:\n    void onBioChanged( const QSizeF& size );\n    void onAnchorClicked( const QUrl& link );\n\n    void onHighlighted( const QString& url );\n\n    void onImageLoaded();\n\n    void onDocumentLayoutChanged();\n    void polish();\n\nprotected:\n    void insertWidget( QWidget* w );\n    class WidgetTextObject* m_widgetTextObject;\n\n    void mousePressEvent( QMouseEvent* event );\n    void mouseReleaseEvent( QMouseEvent* event );\n    void mouseMoveEvent( QMouseEvent* event );\n    void showEvent(QShowEvent *);\n\n    bool sendMouseEvent( QMouseEvent* event );\n\n    enum WidgetProperties { WidgetData = 1 };\n    enum { WidgetImageFormat = QTextFormat::UserObject + 1 };\n    QWidget* m_currentHoverWidget;\n\n    QString m_bioText;\n\n    QTextImageFormat m_widgetImageFormat;\n\n    struct {\n        class BannerWidget* onTour;\n        class HttpImageWidget* image;\n    } ui;\n};\n\n\n#endif //BIO_WIDGET_H_\n"
  },
  {
    "path": "app/client/Widgets/ContextLabel.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QPainter>\n#include <QDebug>\n\n#include \"ContextLabel.h\"\n\nContextLabel::ContextLabel( QWidget* parent )\n    :unicorn::Label( parent )\n{\n}\n\nvoid\nContextLabel::paintEvent( QPaintEvent* event )\n{\n    QLabel::paintEvent( event );\n\n    // draw the arrow on the context\n    QPainter p;\n    p.begin( this );\n\n    static QPixmap arrow( \":/meta_context_arrow.png\" );\n\n    // these values match the ones in the stylesheet\n    int topMargin = 20;\n    int leftMargin = 20;\n\n    if ( this->objectName() == \"userBlurb\" )\n    {\n        topMargin = 12;\n        leftMargin = 0;\n    }\n\n    QPoint arrowPoint = QPoint( leftMargin + (( 126 + 10 - arrow.size().width() )  / 2 ), topMargin + 1 - arrow.size().height() );\n    p.drawPixmap( arrowPoint, arrow );\n\n    p.end();\n}\n"
  },
  {
    "path": "app/client/Widgets/ContextLabel.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef CONTEXTLABEL_H\n#define CONTEXTLABEL_H\n\n#include \"lib/unicorn/widgets/Label.h\"\n\nclass ContextLabel : public unicorn::Label\n{\n    Q_OBJECT\npublic:\n    explicit ContextLabel( QWidget *parent = 0);\n\nprivate:\n    void paintEvent( QPaintEvent* event );\n\n};\n\n#endif // CONTEXTLABEL_H\n"
  },
  {
    "path": "app/client/Widgets/FriendListWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QLabel>\n#include <QVBoxLayout>\n#include <QLineEdit>\n#include <QScrollArea>\n#include <QListWidget>\n#include <QListWidgetItem>\n#include <QMovie>\n#include <QNetworkReply>\n#include <QScrollBar>\n\n#include <lastfm/User.h>\n#include <lastfm/XmlQuery.h>\n#include <lastfm/UrlBuilder.h>\n\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"../Application.h\"\n#include \"FriendWidget.h\"\n#include \"FriendListWidget.h\"\n#include \"RefreshButton.h\"\n#include \"ui_FriendListWidget.h\"\n\n\nclass FriendWidgetItem : public QListWidgetItem\n{\npublic:\n    FriendWidgetItem( QListWidget* parent );\n    bool operator<( const QListWidgetItem& that ) const;\n};\n\nFriendWidgetItem::FriendWidgetItem( QListWidget* parent )\n    :QListWidgetItem( parent )\n{\n}\n\nbool\nFriendWidgetItem::operator<( const QListWidgetItem& that ) const\n{\n    if ( !qobject_cast<FriendWidget*>(listWidget()->itemWidget( const_cast<QListWidgetItem*>(&that) )) )\n        return false;\n\n    if ( !qobject_cast<FriendWidget*>(listWidget()->itemWidget( const_cast<FriendWidgetItem*>(this) )) )\n        return true;\n\n    return *qobject_cast<FriendWidget*>(listWidget()->itemWidget( const_cast<FriendWidgetItem*>(this) )) <\n            *qobject_cast<FriendWidget*>(listWidget()->itemWidget( const_cast<QListWidgetItem*>(&that) ));\n}\n\nFriendListWidget::FriendListWidget(QWidget *parent) :\n    QWidget(parent),\n    ui( new Ui::FriendListWidget )\n{\n    ui->setupUi( this );\n\n#ifdef Q_OS_MAC\n    connect( ui->friends->verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(scroll()) );\n#endif\n\n    ui->noFriends->setText( tr( \"<h3>You haven't made any friends on Last.fm yet.</h3>\"\n                                \"<p>Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.</p>\" ) );\n\n    connect( ui->findFriends, SIGNAL(clicked()), SLOT(onFindFriends()) );\n\n#if QT_VERSION >= 0x040700\n    // The placeholder property was introduced in Qt 4.7\n    ui->filter->setPlaceholderText( tr( \"Search for a friend by username or real name\" ) );\n#endif\n    ui->filter->setAttribute( Qt::WA_MacShowFocusRect, false );\n\n    ui->friends->setObjectName( \"friends\" );\n    ui->friends->setAttribute( Qt::WA_MacShowFocusRect, false );\n\n    connect( ui->filter, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n\n    m_movie = new QMovie( \":/loading_meta.gif\", \"GIF\", this );\n    m_movie->setCacheMode( QMovie::CacheAll );\n    ui->spinner->setMovie( m_movie );\n\n    ui->stackedWidget->setCurrentWidget( ui->spinnerPage );\n    m_movie->start();\n\n    onSessionChanged( aApp->currentSession() );\n}\n\n#ifdef Q_OS_MAC\nvoid\nFriendListWidget::scroll()\n{\n    // KLUDGE: The friend list widgets don't move unless we do this\n    ui->friends->sortItems( Qt::AscendingOrder );\n}\n#endif\n\nvoid\nFriendListWidget::onSessionChanged( const unicorn::Session& session )\n{\n    if ( session.user().name() != m_currentUser )\n    {\n        m_currentUser = session.user().name();\n\n        if ( m_reply )\n            m_reply->abort();\n\n        ui->friends->clear();\n\n        // add the refresh button\n        FriendWidgetItem* item = new FriendWidgetItem( ui->friends );\n        RefreshButton* refresh = new RefreshButton( this );\n        refresh->setText( tr( \"Refresh Friends\" ) );\n        ui->friends->setItemWidget( item, refresh );\n        item->setSizeHint( refresh->sizeHint() );\n\n        connect( refresh, SIGNAL(clicked()) , SLOT(refresh()));\n\n        ui->stackedWidget->setCurrentWidget( ui->spinnerPage );\n        m_movie->start();\n\n        m_reply = session.user().getFriends( true, 50, 1 );\n        connect( m_reply, SIGNAL(finished()), SLOT(onGotFriends()));\n    }\n}\n\nvoid\nFriendListWidget::onFindFriends()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"findfriends\" ).url() );\n}\n\nvoid\nFriendListWidget::onTextChanged( const QString& text )\n{\n    QString trimmedText = text.trimmed();\n\n    setUpdatesEnabled( false );\n\n    if ( text.isEmpty() )\n    {\n        // special case an empty string so it's a bit zippier\n        for ( int i = 1 ; i < ui->friends->count() ; ++i )\n            ui->friends->item( i )->setHidden( false );\n    }\n    else\n    {\n        QRegExp re( QString( \"^%1\" ).arg( trimmedText ), Qt::CaseInsensitive );\n\n        for ( int i = 1 ; i < ui->friends->count() ; ++i )\n        {\n            FriendWidget* user = static_cast<FriendWidget*>( ui->friends->itemWidget( ui->friends->item( i ) ) );\n\n            ui->friends->item( i )->setHidden( !( user->name().startsWith( trimmedText, Qt::CaseInsensitive )\n                                                       || user->realname().startsWith( trimmedText, Qt::CaseInsensitive )\n                                                       || user->realname().split( ' ' ).filter( re ).count() > 0 ) );\n        }\n    }\n\n    setUpdatesEnabled( true );\n}\n\n\nvoid FriendListWidget::onCurrentChanged( int index )\n{\n    if ( index == 3 )\n        refresh();\n}\n\nvoid\nFriendListWidget::refresh()\n{\n    if ( !m_reply\n         || ( m_reply && m_reply->isFinished() ) )\n    {\n        RefreshButton* refresh = qobject_cast<RefreshButton*>(ui->friends->itemWidget( ui->friends->item( 0 ) ) );\n        refresh->setEnabled( false );\n        refresh->setText( tr( \"Refreshing...\" ) );\n\n        m_reply = User().getFriendsListeningNow( 50, 1 );\n        connect( m_reply, SIGNAL(finished()), SLOT(onGotFriendsListeningNow()));\n    }\n}\n\nvoid\nFriendListWidget::onGotFriends()\n{\n    // add this set of users to the list\n    lastfm::XmlQuery lfm;\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n\n        foreach( const lastfm::XmlQuery& user, lfm[\"friends\"].children( \"user\" ) )\n        {\n            FriendWidgetItem* item = new FriendWidgetItem( ui->friends );\n            FriendWidget* friendWidget = new FriendWidget( user, this );\n            ui->friends->setItemWidget( item, friendWidget );\n            item->setSizeHint( friendWidget->sizeHint() );\n        }\n\n        int page = lfm[\"friends\"].attribute( \"page\" ).toInt();\n        int perPage = lfm[\"friends\"].attribute( \"perPage\" ).toInt();\n        int totalPages = lfm[\"friends\"].attribute( \"totalPages\" ).toInt();\n        //int total = lfm[\"friends\"].attribute( \"total\" ).toInt();\n\n        // Check if we need to fetch another page of users\n        if ( page != totalPages )\n        {\n            m_reply = lastfm::User().getFriends( true, perPage, page + 1 );\n            connect( m_reply, SIGNAL(finished()), SLOT(onGotFriends()) );\n        }\n        else\n        {\n            // we have fetched all the pages!\n            onTextChanged( ui->filter->text() );\n\n            m_reply = User().getFriendsListeningNow( 50, 1 );\n            connect( m_reply, SIGNAL(finished()), SLOT(onGotFriendsListeningNow()));\n        }\n    }\n    else\n    {\n        showList();\n    }\n}\n\n\nvoid\nFriendListWidget::onGotFriendsListeningNow()\n{\n    // update the users in the list\n    lastfm::XmlQuery lfm;\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        // reset all the friends to have the same order of max unsigned int\n        for ( int i = 1 ; i < ui->friends->count() ; ++i )\n            static_cast<FriendWidget*>( ui->friends->itemWidget( ui->friends->item( i ) ) )->setOrder( 0 - 1 );\n\n        QList<XmlQuery> users = lfm[\"friendslisteningnow\"].children( \"user\" );\n\n        for ( int i = 0 ; i < users.count() ; ++i )\n        {\n            XmlQuery& user = users[i];\n\n            for ( int j = 1 ; j < ui->friends->count() ; ++j )\n            {\n                FriendWidget* friendWidget = static_cast<FriendWidget*>( ui->friends->itemWidget( ui->friends->item( j ) ) );\n\n                if ( friendWidget->name().compare( user[\"name\"].text(),Qt::CaseInsensitive ) == 0 )\n                    friendWidget->update( user, i );\n            }\n\n        }\n\n        int page = lfm[\"friends\"].attribute( \"page\" ).toInt();\n        int perPage = lfm[\"friends\"].attribute( \"perPage\" ).toInt();\n        int totalPages = lfm[\"friends\"].attribute( \"totalPages\" ).toInt();\n        //int total = lfm[\"friends\"].attribute( \"total\" ).toInt();\n\n        // Check if we need to fetch another page of users\n        if ( page != totalPages )\n        {\n            m_reply = lastfm::User().getFriends( true, perPage, page + 1 );\n            connect( m_reply, SIGNAL(finished()), SLOT(onGotFriends()) );\n        }\n        else\n        {\n            // we have fetched all the pages!\n            showList();\n        }\n    }\n    else\n    {\n        // there was an error downloading a page\n        showList();\n    }\n\n}\n\nvoid\nFriendListWidget::showList()\n{\n    onTextChanged( ui->filter->text() );\n\n    ui->friends->sortItems( Qt::AscendingOrder );\n\n    if ( ui->friends->count() == 1 )\n        ui->stackedWidget->setCurrentWidget( ui->noFriendsPage );\n    else\n        ui->stackedWidget->setCurrentWidget( ui->friendsPage );\n\n    m_movie->stop();\n\n    RefreshButton* refresh = qobject_cast<RefreshButton*>(ui->friends->itemWidget( ui->friends->item( 0 ) ) );\n    refresh->setEnabled( true );\n    refresh->setText( tr( \"Refresh Friends\" ) );\n}\n"
  },
  {
    "path": "app/client/Widgets/FriendListWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef FRIENDLISTWIDGET_H\n#define FRIENDLISTWIDGET_H\n\n#include <QWidget>\n#include <QPointer>\n\nclass QNetworkReply;\n\nnamespace unicorn { class Session; }\nnamespace lastfm { class XmlQuery; }\nnamespace lastfm { class User; }\n\nnamespace Ui { class FriendListWidget; }\n\nclass FriendListWidget : public QWidget\n{\n    Q_OBJECT\npublic:\n    explicit FriendListWidget( QWidget *parent = 0 );\n\npublic slots:\n    void onCurrentChanged(int);\n\nprivate slots:\n    void onSessionChanged( const unicorn::Session& session );\n\n    void onGotFriends();\n    void onGotFriendsListeningNow();\n    void onTextChanged( const QString& text );\n\n    void onFindFriends();\n\n    void refresh();\n\n#ifdef Q_OS_MAC\n    void scroll();\n#endif\n\nprivate:\n    void showList();\n\nprivate:\n    QString m_currentUser;\n\n    Ui::FriendListWidget* ui;\n    QPointer<QMovie> m_movie;\n\n    QPointer<QNetworkReply> m_reply;\n};\n\n#endif // FRIENDLISTWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/FriendListWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>FriendListWidget</class>\n <widget class=\"QWidget\" name=\"FriendListWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>446</width>\n    <height>595</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QStackedWidget\" name=\"stackedWidget\">\n     <property name=\"currentIndex\">\n      <number>1</number>\n     </property>\n     <widget class=\"QWidget\" name=\"friendsPage\">\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n       <property name=\"spacing\">\n        <number>0</number>\n       </property>\n       <property name=\"margin\">\n        <number>0</number>\n       </property>\n       <item>\n        <widget class=\"QWidget\" name=\"filterBackground\" native=\"true\">\n         <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n          <property name=\"spacing\">\n           <number>0</number>\n          </property>\n          <property name=\"margin\">\n           <number>0</number>\n          </property>\n          <item>\n           <widget class=\"QLineEdit\" name=\"filter\"/>\n          </item>\n         </layout>\n        </widget>\n       </item>\n       <item>\n        <widget class=\"QListWidget\" name=\"friends\">\n         <property name=\"horizontalScrollBarPolicy\">\n          <enum>Qt::ScrollBarAlwaysOff</enum>\n         </property>\n         <property name=\"selectionMode\">\n          <enum>QAbstractItemView::NoSelection</enum>\n         </property>\n         <property name=\"verticalScrollMode\">\n          <enum>QAbstractItemView::ScrollPerPixel</enum>\n         </property>\n         <property name=\"uniformItemSizes\">\n          <bool>false</bool>\n         </property>\n         <property name=\"sortingEnabled\">\n          <bool>false</bool>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n     <widget class=\"QFrame\" name=\"noFriendsPage\">\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout_4\">\n       <property name=\"margin\">\n        <number>0</number>\n       </property>\n       <item>\n        <widget class=\"unicorn::Label\" name=\"noFriends\">\n         <property name=\"text\">\n          <string/>\n         </property>\n         <property name=\"textFormat\">\n          <enum>Qt::RichText</enum>\n         </property>\n         <property name=\"wordWrap\">\n          <bool>true</bool>\n         </property>\n        </widget>\n       </item>\n       <item>\n        <widget class=\"PushButton\" name=\"findFriends\">\n         <property name=\"text\">\n          <string>Find your friends on Last.fm</string>\n         </property>\n        </widget>\n       </item>\n       <item>\n        <spacer name=\"verticalSpacer\">\n         <property name=\"orientation\">\n          <enum>Qt::Vertical</enum>\n         </property>\n         <property name=\"sizeHint\" stdset=\"0\">\n          <size>\n           <width>20</width>\n           <height>0</height>\n          </size>\n         </property>\n        </spacer>\n       </item>\n      </layout>\n     </widget>\n     <widget class=\"QWidget\" name=\"spinnerPage\">\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout_3\">\n       <property name=\"spacing\">\n        <number>0</number>\n       </property>\n       <property name=\"margin\">\n        <number>0</number>\n       </property>\n       <item>\n        <widget class=\"QLabel\" name=\"spinner\">\n         <property name=\"text\">\n          <string notr=\"true\">Spinner</string>\n         </property>\n         <property name=\"alignment\">\n          <set>Qt::AlignCenter</set>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>PushButton</class>\n   <extends>QPushButton</extends>\n   <header>../Widgets/PushButton.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/FriendWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QMovie>\n#include <QTimer>\n\n#include <lastfm/RadioStation.h>\n\n#include \"lib/unicorn/widgets/AvatarWidget.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n\n#include \"../Application.h\"\n\n#include \"FriendWidget.h\"\n#include \"ui_FriendWidget.h\"\n\n\n\nFriendWidget::FriendWidget( const lastfm::XmlQuery& user, QWidget* parent)\n    :QFrame( parent ),\n      ui( new Ui::FriendWidget ),\n      m_user( user ),\n      m_order( 0 - 1 ),\n      m_listeningNow( false )\n{   \n    ui->setupUi( this );\n\n    layout()->setAlignment( ui->avatar, Qt::AlignTop );\n\n    m_movie = new QMovie( \":/icon_eq.gif\", \"GIF\", this );\n    m_movie->setCacheMode( QMovie::CacheAll );\n    ui->equaliser->setMovie( m_movie );\n    ui->equaliser->hide();\n\n    update( user, -1 );\n\n    QRegExp re( \"/serve/(\\\\d*)s?/\" );\n    ui->avatar->loadUrl( user[\"image size=medium\"].text().replace( re, \"/serve/\\\\1s/\" ), HttpImageWidget::ScaleNone );\n    ui->avatar->setHref( user[\"url\"].text() );\n\n    ui->avatar->setUser( m_user );\n}\n\nvoid\nFriendWidget::update( const lastfm::XmlQuery& user, unsigned int order )\n{\n    m_order = order;\n\n    m_track.setTitle( user[\"recenttrack\"][\"name\"].text() );\n    m_track.setAlbum( user[\"recenttrack\"][\"album\"][\"name\"].text() );\n    m_track.setArtist( user[\"recenttrack\"][\"artist\"][\"name\"].text() );\n    m_track.setExtra( \"playerName\", user[\"scrobblesource\"][\"name\"].text() );\n    m_track.setExtra( \"playerURL\", user[\"scrobblesource\"][\"url\"].text() );\n\n    QString recentTrackDate = user[\"recenttrack\"].attribute( \"uts\" );\n\n    bool hasListened = m_track != lastfm::Track();\n    ui->trackFrame->setVisible( hasListened );\n\n    m_listeningNow = recentTrackDate.isEmpty() && hasListened;\n\n    if ( !recentTrackDate.isEmpty() )\n        m_track.setTimeStamp( QDateTime::fromTime_t( recentTrackDate.toUInt() ) );\n\n    setDetails();\n}\n\nvoid\nFriendWidget::setOrder( int order )\n{\n    m_order = order;\n}\n\nvoid\nFriendWidget::setListeningNow( bool listeningNow )\n{\n    m_listeningNow = listeningNow;\n}\n\nbool\nFriendWidget::operator<( const FriendWidget& that ) const\n{\n    // sort by most recently listened and then by name\n\n    if ( this->m_listeningNow && !that.m_listeningNow )\n        return true;\n\n    if ( !this->m_listeningNow && that.m_listeningNow )\n        return false;\n\n    if ( this->m_listeningNow && that.m_listeningNow )\n        return this->name().toLower() < that.name().toLower();\n\n    if ( !this->m_track.timestamp().isNull() && that.m_track.timestamp().isNull() )\n        return true;\n\n    if ( this->m_track.timestamp().isNull() && !that.m_track.timestamp().isNull() )\n        return false;\n\n    if ( this->m_track.timestamp().isNull() && that.m_track.timestamp().isNull() )\n        return this->name().toLower() < that.name().toLower();\n\n    // both timestamps are valid!\n\n    if ( this->m_track.timestamp() == that.m_track.timestamp() )\n    {\n        if ( this->m_order == that.m_order )\n            return this->name().toLower() < that.name().toLower();\n\n        return this->m_order < that.m_order;\n    }\n\n    // this is the other way around because a higher time means it's lower in the list\n    return this->m_track.timestamp() > that.m_track.timestamp();\n}\n\nQString\nFriendWidget::genderString( const lastfm::Gender& gender )\n{\n    QString result;\n\n    if ( gender.male() )\n        result = tr( \"Male\" );\n    else if ( gender.female() )\n        result = tr( \"Female\" );\n    else\n        result = tr( \"Neuter\" );\n\n    return result;\n}\n\nQString\nFriendWidget::userString( const lastfm::User& user )\n{\n    QString text;\n\n    text = QString(\"%1\").arg( user.realName().isEmpty() ? user.name() : user.realName() );\n    if ( user.age() ) text.append( QString(\", %1\").arg( user.age() ) );\n    if ( user.gender().known() ) text.append( QString(\", %1\").arg( genderString( user.gender() ) ) );\n    if ( !user.country().isEmpty() ) text.append( QString(\", %1\").arg( user.country() ) );\n\n    return text;\n}\n\nvoid\nFriendWidget::setDetails()\n{\n    ui->userDetails->setText( userString( m_user ) );\n    ui->username->setText( Label::boldLinkStyle( Label::anchor( m_user.www().toString(), name() ), Qt::black ) );\n    ui->lastTrack->setText( m_track.toString() );\n\n    if ( m_listeningNow )\n    {\n        // show the\n        m_movie->start();\n        ui->equaliser->show();\n\n        ui->trackFrame->setObjectName( \"nowListening\" );\n        style()->polish( ui->trackFrame );\n\n        if ( !m_track.extra( \"playerName\" ).isEmpty() )\n            ui->timestamp->setText( tr( \"Scrobbling now from %1\" ).arg( m_track.extra( \"playerName\" ) ) );\n        else\n            ui->timestamp->setText( tr( \"Scrobbling now\" ) );\n\n        if ( m_timestampTimer ) m_timestampTimer->stop();\n    }\n    else\n    {\n        m_movie->stop();\n        ui->equaliser->hide();\n\n        ui->trackFrame->setObjectName( \"groupBox\" );\n        style()->polish( ui->trackFrame );\n\n        updateTimestamp();\n    }\n}\n\nvoid\nFriendWidget::updateTimestamp()\n{\n    if ( !m_timestampTimer )\n    {\n        m_timestampTimer = new QTimer( this );\n        m_timestampTimer->setSingleShot( true );\n        connect( m_timestampTimer, SIGNAL(timeout()), SLOT(updateTimestamp()));\n    }\n\n    unicorn::Label::prettyTime( *ui->timestamp, m_track.timestamp(), m_timestampTimer );\n}\n\nQString\nFriendWidget::name() const\n{\n    return m_user.name();\n}\n\nQString\nFriendWidget::realname() const\n{\n    return m_user.realName();\n}\n"
  },
  {
    "path": "app/client/Widgets/FriendWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef FRIENDWIDGET_H\n#define FRIENDWIDGET_H\n\n#include <QFrame>\n#include <QPointer>\n\n#include <lastfm/XmlQuery.h>\n#include <lastfm/User.h>\n#include <lastfm/Track.h>\n\nnamespace Ui { class FriendWidget; }\nnamespace unicorn { class Label; }\nusing unicorn::Label;\n\nclass FriendWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    explicit FriendWidget( const lastfm::XmlQuery& user, QWidget *parent = 0 );\n\n    void update( const lastfm::XmlQuery& user, unsigned int order );\n    void setOrder( int order );\n\n    QString name() const;\n    QString realname() const;\n\n    void setListeningNow( bool listeningNow );\n\n    bool operator<( const FriendWidget& that ) const;\n\n    static QString genderString( const lastfm::Gender& gender );\n    static QString userString( const lastfm::User& user );\n\nprivate:\n    void setDetails();\n\nprivate slots:\n    void updateTimestamp();\n\nprivate:\n    Ui::FriendWidget* ui;\n\n    lastfm::User m_user;\n    lastfm::MutableTrack m_track;\n    unsigned int m_order;\n    bool m_listeningNow;\n\n    QPointer<QMovie> m_movie;\n    QPointer<QTimer> m_timestampTimer;\n};\n\n#endif // FRIENDWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/FriendWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>FriendWidget</class>\n <widget class=\"QWidget\" name=\"FriendWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>423</width>\n    <height>130</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QHBoxLayout\" name=\"horizontalLayout\" stretch=\"0,1\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"AvatarWidget\" name=\"avatar\">\n     <property name=\"text\">\n      <string/>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <layout class=\"QVBoxLayout\" name=\"verticalLayout\" stretch=\"0,0,0,0\">\n     <property name=\"spacing\">\n      <number>3</number>\n     </property>\n     <item>\n      <widget class=\"QFrame\" name=\"usernameFrame\">\n       <layout class=\"QHBoxLayout\" name=\"horizontalLayout_3\" stretch=\"1,0\">\n        <property name=\"spacing\">\n         <number>0</number>\n        </property>\n        <property name=\"margin\">\n         <number>0</number>\n        </property>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"username\">\n          <property name=\"text\">\n           <string notr=\"true\">Username</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n       </layout>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"unicorn::Label\" name=\"userDetails\">\n       <property name=\"text\">\n        <string notr=\"true\">User details</string>\n       </property>\n       <property name=\"textFormat\">\n        <enum>Qt::PlainText</enum>\n       </property>\n       <property name=\"wordWrap\">\n        <bool>true</bool>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <spacer name=\"verticalSpacer\">\n       <property name=\"orientation\">\n        <enum>Qt::Vertical</enum>\n       </property>\n       <property name=\"sizeHint\" stdset=\"0\">\n        <size>\n         <width>20</width>\n         <height>6</height>\n        </size>\n       </property>\n      </spacer>\n     </item>\n     <item>\n      <widget class=\"QFrame\" name=\"trackFrame\">\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout_3\">\n        <property name=\"spacing\">\n         <number>4</number>\n        </property>\n        <property name=\"margin\">\n         <number>0</number>\n        </property>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"lastTrack\">\n          <property name=\"text\">\n           <string notr=\"true\">Artist - Title</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::PlainText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\" stretch=\"0,1\">\n          <property name=\"spacing\">\n           <number>0</number>\n          </property>\n          <item>\n           <widget class=\"QLabel\" name=\"equaliser\">\n            <property name=\"text\">\n             <string notr=\"true\">e</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <widget class=\"unicorn::Label\" name=\"timestamp\">\n            <property name=\"text\">\n             <string notr=\"true\">Timestamp</string>\n            </property>\n            <property name=\"textFormat\">\n             <enum>Qt::PlainText</enum>\n            </property>\n            <property name=\"wordWrap\">\n             <bool>true</bool>\n            </property>\n           </widget>\n          </item>\n         </layout>\n        </item>\n       </layout>\n      </widget>\n     </item>\n    </layout>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>AvatarWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/AvatarWidget.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/MetadataWidget.cpp",
    "content": "/*\n  Copyright 2005-2009 Last.fm Ltd.\n     - Primarily authored by Jono Cole and Doug Mansell\n\n  This file is part of the Last.fm Desktop Application Suite.\n\n  lastfm-desktop is free software: you can redistribute it and/or modify\n  it under the terms of the GNU General Public License as published by\n  the Free Software Foundation, either version 3 of the License, or\n  (at your option) any later version.\n\n  lastfm-desktop is distributed in the hope that it will be useful,\n  but WITHOUT ANY WARRANTY; without even the implied warranty of\n  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n  GNU General Public License for more details.\n\n  You should have received a copy of the GNU General Public License\n  along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n#include \"MetadataWidget.h\"\n#include \"ui_MetadataWidget.h\"\n\n#include \"../Application.h\"\n#include \"../Services/ScrobbleService.h\"\n#include \"../Services/AnalyticsService.h\"\n#include \"ScrobbleControls.h\"\n#include \"BioWidget.h\"\n#include \"TagWidget.h\"\n\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n#include \"lib/unicorn/widgets/DataBox.h\"\n#include \"lib/unicorn/widgets/DataListWidget.h\"\n#include \"lib/unicorn/widgets/BannerWidget.h\"\n#include \"lib/unicorn/widgets/LfmListViewWidget.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n#include \"lib/unicorn/layouts/FlowLayout.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include <lastfm/XmlQuery.h>\n#include <lastfm/ws.h>\n#include <lastfm/User.h>\n#include <lastfm/Track.h>\n#include <lastfm/Artist.h>\n\n#include <QDebug>\n#include <QVBoxLayout>\n#include <QGridLayout>\n#include <QLabel>\n#include <QTextBrowser>\n#include <QDesktopServices>\n#include <QNetworkReply>\n#include <QApplication>\n#include <QScrollArea>\n#include <QListView>\n#include <QPushButton>\n#include <QDesktopServices>\n#include <QAbstractTextDocumentLayout>\n#include <QTextFrame>\n#include <QScrollBar>\n#include <QMenu>\n#include <QMovie>\n\nusing unicorn::Label;\n\nMetadataWidget::MetadataWidget( const Track& track, QWidget* p )\n   :QFrame( p ),\n    ui( new Ui::MetadataWidget ),\n    m_track( track ),\n    m_globalTrackScrobbles( 0 ),\n    m_userTrackScrobbles( 0 ),\n    m_userArtistScrobbles( 0 ),\n    m_fetchedTrackInfo( false )\n{\n    ui->setupUi( this );\n\n    ui->artistBioEdit->hide();\n\n    m_movie = new QMovie( \":/loading_meta.gif\", \"GIF\", this );\n    m_movie->setCacheMode( QMovie::CacheAll );\n    ui->spinnerLabel->setMovie (m_movie );\n\n    ui->loadingStack->setCurrentWidget( ui->spinner );\n\n    ui->scrollArea->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->back->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->trackTagsFrame->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    ui->artistPlays->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->artistPlaysLabel->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->artistUserPlays->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->artistUserPlaysLabel->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->artistListeners->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->artistListenersLabel->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    ui->trackYourTags->setLinkColor( QRgb( 0x008AC7 ) );\n    ui->trackPopTags->setLinkColor( QRgb( 0x008AC7 ) );\n    ui->artistYourTags->setLinkColor( QRgb( 0x008AC7 ) );\n    ui->artistPopTags->setLinkColor( QRgb( 0x008AC7 ) );\n\n    ui->artist1->setPixmap( QPixmap( \":/meta_artist_no_photo.png\" ) );\n    ui->artist2->setPixmap( QPixmap( \":/meta_artist_no_photo.png\" ) );\n    ui->artist3->setPixmap( QPixmap( \":/meta_artist_no_photo.png\" ) );\n    ui->artist4->setPixmap( QPixmap( \":/meta_artist_no_photo.png\" ) );\n\n    ui->scrobbleControls->setTrack( track );\n\n    setTrackDetails( track );\n\n    ui->albumImage->setPixmap( QPixmap( \":/meta_album_no_art.png\" ) );\n    ui->artistBio->setPixmap( QPixmap( \":/meta_artist_no_photo.png\" ) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(scrobblesCached(QList<lastfm::Track>)), SLOT(onScrobblesCached(QList<lastfm::Track>)));\n    connect( ui->back, SIGNAL(clicked()), SIGNAL(backClicked()));\n}\n\nMetadataWidget::~MetadataWidget()\n{\n    delete ui;\n}\n\nvoid\nMetadataWidget::fetchTrackInfo( bool force )\n{\n    if ( ( force || isVisible() ) && !m_fetchedTrackInfo )\n    {\n        m_fetchedTrackInfo = true;\n\n        m_numCalls = m_track.album().isNull() ? 6: 7;\n\n        QString username = User().name();\n\n        qWarning() << username;\n\n        // fetch Track info\n        m_track.getInfo( this, \"onTrackGotInfo\", username );\n\n        if( !m_track.album().isNull() )\n            connect( m_track.album().getInfo( username ), SIGNAL(finished()), SLOT(onAlbumGotInfo()));\n\n        connect( m_track.artist().getInfo( username ), SIGNAL(finished()), SLOT(onArtistGotInfo()));\n\n        connect( m_track.getTags(), SIGNAL(finished()), SLOT(onTrackGotYourTags()));\n        connect( m_track.artist().getTags(), SIGNAL(finished()), SLOT(onArtistGotYourTags()));\n        connect( m_track.artist().getEvents(), SIGNAL(finished()), SLOT(onArtistGotEvents()));\n\n        QString country = aApp->currentSession().user().country();\n        connect( m_track.getBuyLinks( country ), SIGNAL(finished()), SLOT(onTrackGotBuyLinks()) );\n    }\n}\n\nvoid\nMetadataWidget::showEvent( QShowEvent* /*e*/ )\n{\n    if ( !m_fetchedTrackInfo )\n        m_movie->start();\n    fetchTrackInfo( false );\n}\n\nvoid\nMetadataWidget::checkFinished()\n{\n    Q_ASSERT( m_numCalls > 0 );\n\n    if ( --m_numCalls == 0 )\n    {\n        ui->loadingStack->setCurrentWidget( ui->content );\n        m_movie->stop();\n\n        emit finished();\n    }\n}\n\nScrobbleControls*\nMetadataWidget::scrobbleControls() const\n{\n    return ui->scrobbleControls;\n}\n\nvoid\nMetadataWidget::setTrackDetails( const Track& track )\n{\n    if ( ui->scrollArea->verticalScrollBar()->isVisible() )\n        ui->scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );\n\n    ui->trackTitle->setText( Label::anchor( track.www().toString(), track.title() ) );\n    ui->trackArtist->setText( tr(\"by %1\").arg( Label::anchor( track.artist().www().toString(), track.artist())));\n    ui->artistArtist->setText( Label::anchor( track.artist().www().toString(),track.artist()));\n    ui->similarArtists->setText( Label::anchor( \"http://www.last.fm/music/\" + track.artist() + \"/+similar\", tr( \"Similar Artists\" ) ) );\n\n    if ( !m_albumGuess.isNull() )\n        ui->trackAlbum->setText( tr(\"from %1\").arg( Label::anchor( m_albumGuess.www().toString(), m_albumGuess)));\n    else\n    {\n        if ( m_track.album().isNull() )\n            ui->trackAlbum->hide();\n        else\n            ui->trackAlbum->setText( tr(\"from %1\").arg( Label::anchor( track.album().www().toString(), track.album())));\n    }\n\n    connect( track.signalProxy(), SIGNAL(loveToggled(bool)), ui->scrobbleControls, SLOT(setLoveChecked(bool)));\n}\n\nvoid\nMetadataWidget::onArtistGotInfo()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n\n    XmlQuery lfm;\n\n    if ( lfm.parse( reply ) )\n    {\n        m_globalArtistScrobbles = lfm[\"artist\"][\"stats\"][\"playcount\"].text().toInt();\n        m_artistListeners = lfm[\"artist\"][\"stats\"][\"listeners\"].text().toInt();\n        m_userArtistScrobbles = lfm[\"artist\"][\"stats\"][\"userplaycount\"].text().toInt();\n\n        ui->artistPlays->setText( tr( \"%L1\" ).arg( m_globalArtistScrobbles ) );\n        ui->artistUserPlays->setText( tr( \"%L1\" ).arg( m_userArtistScrobbles ) );\n        ui->artistListeners->setText( tr( \"%L1\" ).arg( m_artistListeners ) );\n\n        ui->artistPlaysLabel->setText( tr( \"Play(s)\", \"\", m_globalArtistScrobbles ) );\n        ui->artistUserPlaysLabel->setText( tr( \"Play(s) in your library\", \"\", m_userArtistScrobbles ) );\n        ui->artistListenersLabel->setText( tr( \"Listener(s)\", \"\", m_artistListeners ) );\n\n        // Update the context now that we have the user track listens\n        ui->context->setText( contextString( m_track ) );\n\n        {\n            // Similar artists!\n            QList<XmlQuery> artists = lfm[\"artist\"][\"similar\"].children(\"artist\").mid( 0, 4 );\n\n            if ( artists.count() != 0 )\n            {\n                ui->similarArtistFrame->show();\n                ui->similarArtists->show();\n\n                QList<SimilarArtistWidget*> widgets;\n                widgets << ui->artist1 << ui->artist2 << ui->artist3 << ui->artist4;\n\n                QRegExp re( \"/serve/(\\\\d*)s?/\" );\n\n                for ( int i = 0 ; i < artists.count() ; ++i )\n                {\n                    widgets[i]->setArtist( artists[i][\"name\"].text() );\n                    widgets[i]->setToolTip( artists[i][\"name\"].text() );\n                    widgets[i]->loadUrl( artists[i][\"image size=medium\"].text().replace( re, \"/serve/\\\\1s/\" ), HttpImageWidget::ScaleNone );\n                    widgets[i]->setHref( artists[i][\"url\"].text() );\n                }\n            }\n\n        }\n\n        QList<XmlQuery> tags =  lfm[\"artist\"][\"tags\"].children(\"tag\");\n\n        if ( tags.count() == 0 )\n            ui->artistTagsFrame->hide();\n        else\n        {\n            QString tagString = tr( \"Popular tags:\" );\n\n            for ( int i = 0 ; i < tags.count() ; ++i )\n            {\n                if ( i == 0 )\n                    tagString.append( QString( \" %1\" ).arg( Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n                else\n                    tagString.append( QString( \" %1 %2\" ).arg( QString::fromUtf8( \"·\" ), Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n            }\n\n            ui->artistPopTags->setText( tagString );\n        }\n\n        //TODO if empty suggest they edit it\n        QString bio;\n        {\n            QStringList bioList = lfm[\"artist\"][\"bio\"][\"summary\"].text().trimmed().split( \"\\r\" );\n            foreach( const QString& p, bioList ) {\n                QString pTrimmed = p.trimmed();\n                if( pTrimmed.isEmpty()) continue;\n                bio += \"<p>\" + pTrimmed + \"</p>\";\n            }\n        }\n\n        bio = Label::boldLinkStyle( bio, Qt::black );\n\n        ui->artistBio->setBioText( bio );\n        ui->artistBio->updateGeometry();\n        QUrl url = lfm[\"artist\"][\"image size=extralarge\"].text();\n        ui->artistBio->loadImage( url, HttpImageWidget::ScaleWidth );\n        ui->artistBio->setImageHref( QUrl(lfm[\"artist\"][\"url\"].text()));\n        ui->artistBio->setOnTourVisible( false, QUrl(lfm[\"artist\"][\"url\"].text()+\"/+events\"));\n\n        // Sat, 11 Dec 2010 23:49:01 +0000\n\n        QDateTime published;\n        published.fromString( lfm[\"artist\"][\"bio\"][\"published\"].text(), \"ddd, d MMM yyyy HH:mm:ss\" );\n\n        ui->artistBioEdit->setText( tr( \"Edited on %1 | %2 Edit\" ).arg( published.toString( \"\" ), QString::fromUtf8( \"✎\" ) ) );\n\n        connect( ui->artistBio, SIGNAL(finished()), SLOT(checkFinished()) );\n        ++m_numCalls;\n   }\n   else\n   {\n       // TODO: what happens when we fail?\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n   }\n\n\n    checkFinished();\n}\n\n\n\nvoid\nMetadataWidget::onArtistGotYourTags()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n\n    XmlQuery lfm;\n\n    if ( lfm.parse( reply ) )\n    {\n        QList<XmlQuery> tags = lfm[\"tags\"].children(\"tag\").mid(0, 5);\n\n        if ( tags.count() == 0 )\n            ui->artistYourTags->hide();\n        else\n        {\n            QString tagString = tr( \"Your tags:\" );\n\n            for ( int i = 0 ; i < tags.count() ; ++i )\n            {\n                if ( i ==0 )\n                    tagString.append( tr( \" %1\" ).arg( Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n                else\n                    tagString.append( tr( \" %1 %2\" ).arg( QString::fromUtf8( \"·\" ), Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n            }\n\n            ui->artistYourTags->setText( tagString );\n        }\n    }\n    else\n    {\n       // TODO: what happens when we fail?\n       qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n\n    checkFinished();\n}\n\nvoid\nMetadataWidget::onArtistGotEvents()\n{\n   QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());\n\n   XmlQuery lfm;\n   if ( lfm.parse( reply ) )\n   {\n\n       if (lfm[\"events\"].children(\"event\").count() > 0)\n       {\n           // Display an on tour notification\n           ui->artistBio->setOnTourVisible( true );\n       }\n   }\n   else\n   {\n       // TODO: what happens when we fail?\n       qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n   }\n\n   checkFinished();\n}\n\nvoid\nMetadataWidget::onAlbumGotInfo()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n//        int scrobbles = lfm[\"album\"][\"playcount\"].text().toInt();\n//        int listeners = lfm[\"album\"][\"listeners\"].text().toInt();\n//        int userListens = lfm[\"album\"][\"userplaycount\"].text().toInt();\n\n        ui->albumImage->loadUrl( lfm[\"album\"][\"image size=large\"].text() );\n    }\n    else\n    {\n       // TODO: what happens when we fail?\n       qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n\n    checkFinished();\n}\n\nvoid\nMetadataWidget::onTrackGotBuyLinks()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        bool thingsToBuy = false;\n\n        QMenu* menu = new QMenu( this );\n\n        menu->addAction( tr(\"Downloads\") )->setEnabled( false );\n\n        // USD EUR GBP\n\n        foreach ( const XmlQuery& affiliation, lfm[\"affiliations\"][\"downloads\"].children( \"affiliation\" ) )\n        {\n            bool isSearch = affiliation[\"isSearch\"].text() == \"1\";\n\n            QAction* buyAction = 0;\n\n            if ( isSearch )\n                buyAction = menu->addAction( tr(\"Search on %1\").arg( affiliation[\"supplierName\"].text() ) );\n            else\n                buyAction = menu->addAction( tr(\"Buy on %1 %2\").arg( affiliation[\"supplierName\"].text(), unicorn::Label::price( affiliation[\"price\"][\"amount\"].text(), affiliation[\"price\"][\"currency\"].text() ) ) );\n\n            buyAction->setData( affiliation[\"buyLink\"].text() );\n\n            thingsToBuy = true;\n        }\n\n        menu->addSeparator();\n        menu->addAction( tr(\"Physical\") )->setEnabled( false );\n\n        foreach ( const XmlQuery& affiliation, lfm[\"affiliations\"][\"physicals\"].children( \"affiliation\" ) )\n        {\n            bool isSearch = affiliation[\"isSearch\"].text() == \"1\";\n\n            QAction* buyAction = 0;\n\n            if ( isSearch )\n                buyAction = menu->addAction( tr(\"Search on %1\").arg( affiliation[\"supplierName\"].text() ) );\n            else\n                buyAction = menu->addAction( tr(\"Buy on %1 %2\").arg( affiliation[\"supplierName\"].text(), unicorn::Label::price( affiliation[\"price\"][\"amount\"].text(), affiliation[\"price\"][\"currency\"].text() ) ) );\n\n            buyAction->setData( affiliation[\"buyLink\"].text() );\n\n            thingsToBuy = true;\n        }\n\n        ui->scrobbleControls->ui.buy->setVisible( thingsToBuy );\n        ui->scrobbleControls->ui.buy->setMenu( menu );\n\n        connect( menu, SIGNAL(triggered(QAction*)), SLOT(onBuyActionTriggered(QAction*)) );\n    }\n    else\n    {\n        // TODO: what happens when we fail?\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n\n    checkFinished();\n}\n\nvoid\nMetadataWidget::onBuyActionTriggered( QAction* buyAction )\n{\n    unicorn::DesktopServices::openUrl( buyAction->data().toString() );\n    AnalyticsService::instance().sendEvent(NOW_PLAYING_CATEGORY, LINK_CLICKED, \"BuyLinkClicked\" );\n}\n\nvoid\nMetadataWidget::onTrackGotInfo( const QByteArray& data )\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( data ) )\n    {\n        m_globalTrackScrobbles = lfm[\"track\"][\"playcount\"].text().toInt();\n        //int listeners = lfm[\"track\"][\"listeners\"].text().toInt();\n        if ( lfm[\"track\"][\"userplaycount\"].text().length() > 0 )\n            m_userTrackScrobbles = lfm[\"track\"][\"userplaycount\"].text().toInt();\n\n        // Update the context now that we have the user track listens\n        ui->context->setText( contextString( m_track ) );\n\n        ui->albumImage->setHref( lfm[\"track\"][\"url\"].text());\n\n        if ( lfm[\"track\"][\"userloved\"].text().length() > 0 )\n            ui->scrobbleControls->setLoveChecked( lfm[\"track\"][\"userloved\"].text() == \"1\" );\n\n        // get the popular tags\n        QList<XmlQuery> tags = lfm[\"track\"][\"toptags\"].children(\"tag\").mid( 0, 5 );\n\n        if ( tags.count() == 0 )\n            ui->trackTagsFrame->hide();\n        else\n        {\n            QString tagString = tr( \"Popular tags:\" );\n\n            for ( int i = 0 ; i < tags.count() ; ++i )\n            {\n                if ( i ==0 )\n                    tagString.append( tr( \" %1\" ).arg( Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n                else\n                    tagString.append( tr( \" %1 %2\" ).arg( QString::fromUtf8( \"·\" ), Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n            }\n\n            ui->trackPopTags->setText( tagString );\n\n            // If we don't know the album then set the track image\n            if ( m_track.album().isNull() )\n            {\n                ui->albumImage->loadUrl( lfm[\"track\"][\"album\"][\"image size=medium\"].text() );\n            }\n        }\n    }\n    else\n    {\n        // TODO: what happens when we fail?\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n\n    checkFinished();\n}\n\n\nvoid\nMetadataWidget::onTrackGotYourTags()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        QList<XmlQuery> tags = lfm[\"tags\"].children(\"tag\").mid(0, 5);\n\n        if ( tags.count() == 0 )\n            ui->trackYourTags->hide();\n        else\n        {\n            QString tagString = tr( \"Your tags:\" );\n\n            for ( int i = 0 ; i < tags.count() ; ++i )\n            {\n                if ( i ==0 )\n                    tagString.append( tr( \" %1\" ).arg( Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n                else\n                    tagString.append( tr( \" %1 %2\" ).arg( QString::fromUtf8( \"·\" ), Label::anchor( tags.at(i)[\"url\"].text(), tags.at(i)[\"name\"].text() ) ) );\n            }\n\n            ui->trackYourTags->setText( tagString );\n        }\n    }\n    else\n    {\n        // TODO: what happens when we fail?\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n\n    checkFinished();\n}\n\n\nvoid\nMetadataWidget::listItemClicked( const QModelIndex& i )\n{\n   const QUrl& url = i.data( LfmListModel::WwwRole ).toUrl();\n   unicorn::DesktopServices::openUrl( url );\n}\n\nvoid\nMetadataWidget::onScrobblesCached( const QList<lastfm::Track>& tracks )\n{\n   foreach ( lastfm::Track track, tracks )\n       connect( track.signalProxy(), SIGNAL(scrobbleStatusChanged( short )), SLOT(onScrobbleStatusChanged( short )));\n}\n\nvoid\nMetadataWidget::onScrobbleStatusChanged( short scrobbleStatus )\n{\n\n   if (scrobbleStatus == lastfm::Track::Submitted)\n   {\n       // update total scrobbles and your scrobbles!\n       ++m_userTrackScrobbles;\n       ++m_globalTrackScrobbles;\n       ui->artistUserPlays->setText( QString(\"%L1\").arg( ++m_userArtistScrobbles ) );\n       ui->artistPlays->setText( QString(\"%L1\").arg( ++m_globalArtistScrobbles ) );\n       if ( m_userTrackScrobbles == 1 )\n               ui->artistListeners->setText( QString(\"%L1\").arg( ++m_artistListeners ) );\n\n       ui->artistPlaysLabel->setText( tr( \"Play(s)\", \"\", m_globalArtistScrobbles ) );\n       ui->artistUserPlaysLabel->setText( tr( \"Play(s) in your library\", \"\", m_userArtistScrobbles ) );\n       ui->artistListenersLabel->setText( tr( \"Listener(s)\", \"\", m_artistListeners ) );\n\n       //ui->context->setText( contextString( m_track ) );\n   }\n}\n\nQString userLibraryLink( const QString& user, const lastfm::Artist& artist )\n{\n    return QString(\"http://www.last.fm/user/%1/library/music/%2\").arg( user, artist.name() );\n}\n\nQString userLibraryLink( const QString& user, const lastfm::Track& track )\n{\n    return QString(\"http://www.last.fm/user/%1/library/music/%2/_/%3\").arg( user, track.artist().name(), track.title() );\n}\n\nQString userLibrary( const QString& user, const lastfm::Artist& artist )\n{\n   return Label::anchor( userLibraryLink( user, artist ), user );\n}\n\nQString\nMetadataWidget::getContextString( const Track& track )\n{\n   QString contextString;\n   return contextString;\n}\n\n\nQString\nMetadataWidget::contextString( const Track& track )\n{\n   QString context = getContextString( track );\n\n   if ( context.isEmpty() )\n       context = scrobbleString( track );\n\n   return context;\n}\n\nQString\nMetadataWidget::scrobbleString( const Track& track )\n{\n    QString artistString = Label::anchor( userLibraryLink( User().name(), track.artist().toString()  ), track.artist()  );\n    QString trackString = Label::anchor( userLibraryLink( User().name(), track  ), track.title()  );\n\n    QString userArtistScrobblesString = tr( \"%L1 time(s)\", \"\", m_userArtistScrobbles ).arg( m_userArtistScrobbles );\n    QString userTrackScrobblesString = tr( \"%L1 time(s)\", \"\",  m_userTrackScrobbles ).arg( m_userTrackScrobbles );\n\n    QString scrobbleString;\n\n    if ( m_userTrackScrobbles != 0 )\n        scrobbleString = tr( \"You've listened to %1 %2 and %3 %4.\" ).arg( artistString, userArtistScrobblesString, trackString, userTrackScrobblesString );\n    else\n    {\n        if ( m_userArtistScrobbles != 0 )\n            scrobbleString = tr( \"You've listened to %1 %2, but not this track.\" ).arg( artistString, userArtistScrobblesString );\n        else\n            scrobbleString = tr( \"This is the first time you've listened to %1.\" ).arg( artistString );\n    }\n\n    return scrobbleString;\n}\n\nvoid\nMetadataWidget::setBackButtonVisible( bool visible )\n{\n   ui->context->setText( contextString( m_track ) );\n   ui->back->setVisible( visible );\n   ui->scrobbleControls->ui.love->setVisible( true );\n}\n"
  },
  {
    "path": "app/client/Widgets/MetadataWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef METADATAWIDGET_H\n#define METADATAWIDGET_H\n\n#include <QWidget>\n#include <QPointer>\n\n#include <lastfm/Album.h>\n#include <lastfm/Track.h>\n\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n\nnamespace Ui { class MetadataWidget; }\n\nclass DataListWidget;\nclass HttpImageWidget;\nclass QLabel;\nclass QGroupBox;\nclass BioWidget;\nclass QMovie;\n\n\nclass MetadataWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    MetadataWidget( const Track& track, QWidget* p = 0 );\n    ~MetadataWidget();\n\n    void fetchTrackInfo( bool force );\n\n    class ScrobbleControls* scrobbleControls() const;\n\n    QWidget* basicInfoWidget();\n    void setBackButtonVisible( bool );\n\n    static QString getContextString( const Track& track );\n\nprivate slots:\n    void onTrackGotInfo(const QByteArray& data);\n    void onAlbumGotInfo();\n    void onArtistGotInfo();\n    void onArtistGotEvents();\n    void onTrackGotBuyLinks();\n    void onBuyActionTriggered( QAction* buyAction );\n\n    void onTrackGotYourTags();\n    void onArtistGotYourTags();\n\n    void listItemClicked( const class QModelIndex& );\n\n    void onScrobblesCached( const QList<lastfm::Track>& tracks );\n    void onScrobbleStatusChanged( short scrobbleStatus );\n\n    void checkFinished();\n\nsignals:\n    void lovedStateChanged(bool loved);\n    void backClicked();\n    void finished();\n\nprivate:\n    void setTrackDetails( const Track& track );\n\n    QString contextString( const Track& track );\n    QString scrobbleString( const Track& track );\n\n    void showEvent( QShowEvent *e );\n\nprivate:\n    Ui::MetadataWidget *ui;\n\n    Track m_track;\n\n    int m_globalTrackScrobbles;\n    int m_userTrackScrobbles;\n    int m_globalArtistScrobbles;\n    int m_userArtistScrobbles;\n    int m_artistListeners;\n\n    Album m_albumGuess;\n\n    int m_numCalls;\n    bool m_fetchedTrackInfo;\n\n    QPointer<QMovie> m_movie;\n};\n\n#endif // METADATAWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/MetadataWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MetadataWidget</class>\n <widget class=\"QWidget\" name=\"MetadataWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>445</width>\n    <height>590</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QPushButton\" name=\"back\">\n     <property name=\"text\">\n      <string>Back to Scrobbles</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QScrollArea\" name=\"scrollArea\">\n     <property name=\"enabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"horizontalScrollBarPolicy\">\n      <enum>Qt::ScrollBarAlwaysOff</enum>\n     </property>\n     <property name=\"widgetResizable\">\n      <bool>true</bool>\n     </property>\n     <widget class=\"QFrame\" name=\"scrollAreaWidgetContents\">\n      <property name=\"geometry\">\n       <rect>\n        <x>0</x>\n        <y>0</y>\n        <width>445</width>\n        <height>567</height>\n       </rect>\n      </property>\n      <property name=\"autoFillBackground\">\n       <bool>true</bool>\n      </property>\n      <layout class=\"QVBoxLayout\" name=\"verticalLayout_3\" stretch=\"0,1\">\n       <property name=\"spacing\">\n        <number>0</number>\n       </property>\n       <property name=\"margin\">\n        <number>0</number>\n       </property>\n       <item>\n        <widget class=\"QFrame\" name=\"trackDetails\">\n         <property name=\"frameShape\">\n          <enum>QFrame::NoFrame</enum>\n         </property>\n         <property name=\"frameShadow\">\n          <enum>QFrame::Raised</enum>\n         </property>\n         <layout class=\"QHBoxLayout\" name=\"horizontalLayout\" stretch=\"0,1\">\n          <property name=\"spacing\">\n           <number>0</number>\n          </property>\n          <property name=\"margin\">\n           <number>0</number>\n          </property>\n          <item>\n           <widget class=\"HttpImageWidget\" name=\"albumImage\">\n            <property name=\"text\">\n             <string notr=\"true\">Album</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n            <property name=\"spacing\">\n             <number>10</number>\n            </property>\n            <item>\n             <widget class=\"unicorn::Label\" name=\"trackTitle\">\n              <property name=\"text\">\n               <string notr=\"true\">Track title</string>\n              </property>\n              <property name=\"textFormat\">\n               <enum>Qt::RichText</enum>\n              </property>\n              <property name=\"wordWrap\">\n               <bool>true</bool>\n              </property>\n              <property name=\"openExternalLinks\">\n               <bool>false</bool>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <widget class=\"unicorn::Label\" name=\"trackArtist\">\n              <property name=\"text\">\n               <string notr=\"true\">Artist</string>\n              </property>\n              <property name=\"textFormat\">\n               <enum>Qt::RichText</enum>\n              </property>\n              <property name=\"wordWrap\">\n               <bool>true</bool>\n              </property>\n              <property name=\"openExternalLinks\">\n               <bool>false</bool>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <widget class=\"QFrame\" name=\"hsplitter2\">\n              <property name=\"frameShape\">\n               <enum>QFrame::StyledPanel</enum>\n              </property>\n              <property name=\"frameShadow\">\n               <enum>QFrame::Raised</enum>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <widget class=\"ScrobbleControls\" name=\"scrobbleControls\">\n              <property name=\"frameShape\">\n               <enum>QFrame::StyledPanel</enum>\n              </property>\n              <property name=\"frameShadow\">\n               <enum>QFrame::Raised</enum>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <widget class=\"QFrame\" name=\"hsplitter1\">\n              <property name=\"frameShape\">\n               <enum>QFrame::StyledPanel</enum>\n              </property>\n              <property name=\"frameShadow\">\n               <enum>QFrame::Raised</enum>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <widget class=\"unicorn::Label\" name=\"trackAlbum\">\n              <property name=\"text\">\n               <string notr=\"true\">Album</string>\n              </property>\n              <property name=\"textFormat\">\n               <enum>Qt::RichText</enum>\n              </property>\n              <property name=\"wordWrap\">\n               <bool>true</bool>\n              </property>\n              <property name=\"openExternalLinks\">\n               <bool>false</bool>\n              </property>\n             </widget>\n            </item>\n            <item>\n             <spacer name=\"verticalSpacer\">\n              <property name=\"orientation\">\n               <enum>Qt::Vertical</enum>\n              </property>\n              <property name=\"sizeHint\" stdset=\"0\">\n               <size>\n                <width>20</width>\n                <height>0</height>\n               </size>\n              </property>\n             </spacer>\n            </item>\n           </layout>\n          </item>\n         </layout>\n        </widget>\n       </item>\n       <item>\n        <widget class=\"unicorn::StackedWidget\" name=\"loadingStack\">\n         <property name=\"currentIndex\">\n          <number>1</number>\n         </property>\n         <widget class=\"QWidget\" name=\"content\">\n          <layout class=\"QVBoxLayout\" name=\"verticalLayout_8\">\n           <property name=\"spacing\">\n            <number>0</number>\n           </property>\n           <property name=\"margin\">\n            <number>0</number>\n           </property>\n           <item>\n            <widget class=\"ContextLabel\" name=\"context\">\n             <property name=\"text\">\n              <string notr=\"true\">Context</string>\n             </property>\n             <property name=\"textFormat\">\n              <enum>Qt::RichText</enum>\n             </property>\n             <property name=\"wordWrap\">\n              <bool>true</bool>\n             </property>\n            </widget>\n           </item>\n           <item>\n            <widget class=\"QFrame\" name=\"trackTagsFrame\">\n             <property name=\"frameShape\">\n              <enum>QFrame::NoFrame</enum>\n             </property>\n             <property name=\"frameShadow\">\n              <enum>QFrame::Raised</enum>\n             </property>\n             <layout class=\"QVBoxLayout\" name=\"verticalLayout_5\">\n              <property name=\"spacing\">\n               <number>0</number>\n              </property>\n              <property name=\"margin\">\n               <number>0</number>\n              </property>\n              <item>\n               <widget class=\"unicorn::Label\" name=\"trackPopTags\">\n                <property name=\"text\">\n                 <string>Popular tags:</string>\n                </property>\n                <property name=\"textFormat\">\n                 <enum>Qt::RichText</enum>\n                </property>\n                <property name=\"wordWrap\">\n                 <bool>true</bool>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"unicorn::Label\" name=\"trackYourTags\">\n                <property name=\"text\">\n                 <string>Your tags:</string>\n                </property>\n                <property name=\"textFormat\">\n                 <enum>Qt::RichText</enum>\n                </property>\n                <property name=\"wordWrap\">\n                 <bool>true</bool>\n                </property>\n               </widget>\n              </item>\n             </layout>\n            </widget>\n           </item>\n           <item>\n            <widget class=\"QFrame\" name=\"artistFrame\">\n             <property name=\"frameShape\">\n              <enum>QFrame::NoFrame</enum>\n             </property>\n             <property name=\"frameShadow\">\n              <enum>QFrame::Raised</enum>\n             </property>\n             <layout class=\"QVBoxLayout\" name=\"verticalLayout_4\" stretch=\"0,0,0,0,0,0,0,0,0,0\">\n              <property name=\"spacing\">\n               <number>0</number>\n              </property>\n              <property name=\"margin\">\n               <number>0</number>\n              </property>\n              <item>\n               <widget class=\"unicorn::Label\" name=\"artistArtist\">\n                <property name=\"text\">\n                 <string notr=\"true\">Artist</string>\n                </property>\n                <property name=\"textFormat\">\n                 <enum>Qt::RichText</enum>\n                </property>\n                <property name=\"openExternalLinks\">\n                 <bool>false</bool>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"BioWidget\" name=\"artistBio\">\n                <property name=\"frameShape\">\n                 <enum>QFrame::NoFrame</enum>\n                </property>\n                <property name=\"openExternalLinks\">\n                 <bool>false</bool>\n                </property>\n                <property name=\"openLinks\">\n                 <bool>false</bool>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"QLabel\" name=\"artistBioEdit\">\n                <property name=\"text\">\n                 <string notr=\"true\">Edited</string>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"QFrame\" name=\"artistStats\">\n                <property name=\"frameShape\">\n                 <enum>QFrame::NoFrame</enum>\n                </property>\n                <property name=\"frameShadow\">\n                 <enum>QFrame::Raised</enum>\n                </property>\n                <layout class=\"QGridLayout\" name=\"gridLayout_2\">\n                 <property name=\"margin\">\n                  <number>0</number>\n                 </property>\n                 <property name=\"spacing\">\n                  <number>0</number>\n                 </property>\n                 <item row=\"0\" column=\"0\">\n                  <widget class=\"QLabel\" name=\"artistListeners\">\n                   <property name=\"text\">\n                    <string notr=\"true\">0</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"1\" column=\"0\">\n                  <widget class=\"QLabel\" name=\"artistListenersLabel\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Listeners</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"0\" column=\"2\">\n                  <widget class=\"QLabel\" name=\"artistPlays\">\n                   <property name=\"text\">\n                    <string notr=\"true\">0</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"0\" column=\"4\">\n                  <widget class=\"QLabel\" name=\"artistUserPlays\">\n                   <property name=\"text\">\n                    <string notr=\"true\">0</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"1\" column=\"2\">\n                  <widget class=\"QLabel\" name=\"artistPlaysLabel\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Plays</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"1\" column=\"4\">\n                  <widget class=\"QLabel\" name=\"artistUserPlaysLabel\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Plays in your library</string>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"0\" column=\"1\" rowspan=\"2\">\n                  <widget class=\"QFrame\" name=\"splitter3\">\n                   <property name=\"frameShape\">\n                    <enum>QFrame::NoFrame</enum>\n                   </property>\n                   <property name=\"frameShadow\">\n                    <enum>QFrame::Raised</enum>\n                   </property>\n                  </widget>\n                 </item>\n                 <item row=\"0\" column=\"3\" rowspan=\"2\">\n                  <widget class=\"QFrame\" name=\"splitter4\">\n                   <property name=\"frameShape\">\n                    <enum>QFrame::NoFrame</enum>\n                   </property>\n                   <property name=\"frameShadow\">\n                    <enum>QFrame::Raised</enum>\n                   </property>\n                  </widget>\n                 </item>\n                </layout>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"QFrame\" name=\"artistTagsFrame\">\n                <property name=\"frameShape\">\n                 <enum>QFrame::NoFrame</enum>\n                </property>\n                <property name=\"frameShadow\">\n                 <enum>QFrame::Raised</enum>\n                </property>\n                <layout class=\"QVBoxLayout\" name=\"verticalLayout_6\">\n                 <property name=\"spacing\">\n                  <number>0</number>\n                 </property>\n                 <property name=\"margin\">\n                  <number>0</number>\n                 </property>\n                 <item>\n                  <widget class=\"unicorn::Label\" name=\"artistPopTags\">\n                   <property name=\"text\">\n                    <string>Popular tags:</string>\n                   </property>\n                   <property name=\"textFormat\">\n                    <enum>Qt::RichText</enum>\n                   </property>\n                   <property name=\"wordWrap\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                 <item>\n                  <widget class=\"unicorn::Label\" name=\"artistYourTags\">\n                   <property name=\"text\">\n                    <string>Your tags:</string>\n                   </property>\n                   <property name=\"textFormat\">\n                    <enum>Qt::RichText</enum>\n                   </property>\n                   <property name=\"wordWrap\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                </layout>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"QFrame\" name=\"splitter\">\n                <property name=\"frameShape\">\n                 <enum>QFrame::StyledPanel</enum>\n                </property>\n                <property name=\"frameShadow\">\n                 <enum>QFrame::Raised</enum>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"unicorn::Label\" name=\"similarArtists\">\n                <property name=\"text\">\n                 <string>Similar Artists</string>\n                </property>\n                <property name=\"textFormat\">\n                 <enum>Qt::RichText</enum>\n                </property>\n               </widget>\n              </item>\n              <item>\n               <widget class=\"QFrame\" name=\"similarArtistFrame\">\n                <property name=\"frameShape\">\n                 <enum>QFrame::NoFrame</enum>\n                </property>\n                <property name=\"frameShadow\">\n                 <enum>QFrame::Raised</enum>\n                </property>\n                <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\">\n                 <property name=\"spacing\">\n                  <number>0</number>\n                 </property>\n                 <property name=\"margin\">\n                  <number>0</number>\n                 </property>\n                 <item>\n                  <widget class=\"SimilarArtistWidget\" name=\"artist1\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Artist</string>\n                   </property>\n                   <property name=\"scaledContents\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                 <item>\n                  <spacer name=\"horizontalSpacer_7\">\n                   <property name=\"orientation\">\n                    <enum>Qt::Horizontal</enum>\n                   </property>\n                   <property name=\"sizeHint\" stdset=\"0\">\n                    <size>\n                     <width>0</width>\n                     <height>20</height>\n                    </size>\n                   </property>\n                  </spacer>\n                 </item>\n                 <item>\n                  <widget class=\"SimilarArtistWidget\" name=\"artist2\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Artist</string>\n                   </property>\n                   <property name=\"scaledContents\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                 <item>\n                  <spacer name=\"horizontalSpacer_6\">\n                   <property name=\"orientation\">\n                    <enum>Qt::Horizontal</enum>\n                   </property>\n                   <property name=\"sizeHint\" stdset=\"0\">\n                    <size>\n                     <width>0</width>\n                     <height>20</height>\n                    </size>\n                   </property>\n                  </spacer>\n                 </item>\n                 <item>\n                  <widget class=\"SimilarArtistWidget\" name=\"artist3\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Artist</string>\n                   </property>\n                   <property name=\"scaledContents\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                 <item>\n                  <spacer name=\"horizontalSpacer_5\">\n                   <property name=\"orientation\">\n                    <enum>Qt::Horizontal</enum>\n                   </property>\n                   <property name=\"sizeHint\" stdset=\"0\">\n                    <size>\n                     <width>0</width>\n                     <height>20</height>\n                    </size>\n                   </property>\n                  </spacer>\n                 </item>\n                 <item>\n                  <widget class=\"SimilarArtistWidget\" name=\"artist4\">\n                   <property name=\"text\">\n                    <string notr=\"true\">Artist</string>\n                   </property>\n                   <property name=\"scaledContents\">\n                    <bool>true</bool>\n                   </property>\n                  </widget>\n                 </item>\n                </layout>\n               </widget>\n              </item>\n              <item>\n               <spacer name=\"verticalSpacer_2\">\n                <property name=\"orientation\">\n                 <enum>Qt::Vertical</enum>\n                </property>\n                <property name=\"sizeHint\" stdset=\"0\">\n                 <size>\n                  <width>20</width>\n                  <height>0</height>\n                 </size>\n                </property>\n               </spacer>\n              </item>\n             </layout>\n            </widget>\n           </item>\n          </layout>\n         </widget>\n         <widget class=\"QWidget\" name=\"spinner\">\n          <layout class=\"QHBoxLayout\" name=\"horizontalLayout_3\">\n           <property name=\"spacing\">\n            <number>0</number>\n           </property>\n           <property name=\"margin\">\n            <number>0</number>\n           </property>\n           <item>\n            <widget class=\"QLabel\" name=\"spinnerLabel\">\n             <property name=\"text\">\n              <string notr=\"true\">TextLabel</string>\n             </property>\n             <property name=\"alignment\">\n              <set>Qt::AlignCenter</set>\n             </property>\n            </widget>\n           </item>\n          </layout>\n         </widget>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>HttpImageWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/HttpImageWidget.h</header>\n  </customwidget>\n  <customwidget>\n   <class>ScrobbleControls</class>\n   <extends>QFrame</extends>\n   <header>../Widgets/ScrobbleControls.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>BioWidget</class>\n   <extends>QTextBrowser</extends>\n   <header>../Widgets/BioWidget.h</header>\n  </customwidget>\n  <customwidget>\n   <class>ContextLabel</class>\n   <extends>QLabel</extends>\n   <header>../Widgets/ContextLabel.h</header>\n  </customwidget>\n  <customwidget>\n   <class>SimilarArtistWidget</class>\n   <extends>QLabel</extends>\n   <header>../Widgets/SimilarArtistWidget.h</header>\n  </customwidget>\n  <customwidget>\n   <class>unicorn::StackedWidget</class>\n   <extends>QStackedWidget</extends>\n   <header>lib/unicorn/widgets/StackedWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/NothingPlayingWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QLabel>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QProcess>\n\n#include \"../Application.h\"\n\n#include \"lib/unicorn/widgets/Label.h\"\n\n#ifdef Q_OS_WIN\n#include \"lib/unicorn/plugins/IPluginInfo.h\"\n#include \"lib/unicorn/plugins/PluginList.h\"\n#endif\n\n#ifdef Q_OS_MAC\n// the iTunes listener has a static method we can use to tell if iTunes is installed\n#include \"lib/listener/mac/ITunesListener.h\"\n#endif\n\n#include \"NothingPlayingWidget.h\"\n#include \"ui_NothingPlayingWidget.h\"\n\nNothingPlayingWidget::NothingPlayingWidget( QWidget* parent )\n    :QFrame( parent ),\n      ui( new Ui::NothingPlayingWidget )\n{   \n    ui->setupUi( this );\n\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->top->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    ui->contents->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    onSessionChanged( aApp->currentSession() );\n\n    ui->scrobble->setText( tr( \"<h2>Scrobble from your music player</h2>\"\n                               \"<p>Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.</p>\") );\n\n    ui->itunes->hide();\n    ui->applemusic->hide();\n    ui->wmp->hide();\n    ui->winamp->hide();\n    ui->foobar->hide();\n\n#if defined( Q_OS_MAC ) \n    QString MusicOrItunesId = ITunesListener::getPlayerAppId();\n\n    ui->applemusic->setVisible( MusicOrItunesId.compare(\"com.apple.Music\") == 0 );\n    ui->applemusic->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    connect( ui->applemusic, SIGNAL(clicked()), SLOT(onAppleMusicClicked()));    \n\n    ui->itunes->setVisible( MusicOrItunesId.compare(\"com.apple.iTunes\") == 0 );\n    ui->itunes->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    connect( ui->itunes, SIGNAL(clicked()), SLOT(oniTunesClicked()));\n#endif\n\n#if defined( Q_OS_WIN )\n    unicorn::PluginList pluginList;\n\n    ui->itunes->setVisible( pluginList.pluginById( \"itw\" )->isAppInstalled() );\n    ui->itunes->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    connect( ui->itunes, SIGNAL(clicked()), SLOT(oniTunesClicked()));\n\n    ui->wmp->setVisible( pluginList.pluginById( \"wmp\" )->isAppInstalled() );\n    ui->wmp->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->winamp->setVisible( pluginList.pluginById( \"wa2\" )->isAppInstalled() );\n    ui->winamp->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->foobar->setVisible( pluginList.pluginById( \"foo3\" )->isAppInstalled() );\n    ui->foobar->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    connect( ui->wmp, SIGNAL(clicked()), SLOT(onWMPClicked()));\n    connect( ui->winamp, SIGNAL(clicked()), SLOT(onWinampClicked()));\n    connect( ui->foobar, SIGNAL(clicked()), SLOT(onFoobarClicked()));\n#endif\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n}\n\nvoid\nNothingPlayingWidget::onSessionChanged( const unicorn::Session& session )\n{\n    if ( !session.user().name().isEmpty() )\n        ui->top->setText( tr(  \"Hello, %1!\" ).arg( session.user().name() ) );\n}\n\n#ifdef Q_OS_WIN\nvoid\nNothingPlayingWidget::startApp( const QString& app )\n{\n    QString mediaPlayer = QString( qgetenv( \"ProgramFiles(x86)\" ) ).append( app );\n\n    if ( !QFile::exists( mediaPlayer ) )\n        mediaPlayer = QString( qgetenv( \"ProgramFiles\" ) ).append( app );\n\n    if ( QFile::exists( mediaPlayer ) )\n    {\n        mediaPlayer = QString( \"\\\"%1\\\"\" ).arg( mediaPlayer );\n        QProcess::startDetached( mediaPlayer );\n    }\n}\n\nvoid\nNothingPlayingWidget::oniTunesClicked()\n{\n    startApp( \"/iTunes/iTunes.exe\" );\n}\n\nvoid\nNothingPlayingWidget::onAppleMusicClicked()\n{\n    // doesn't yet exist on Windows\n}\n\nvoid\nNothingPlayingWidget::onWinampClicked()\n{\n    startApp( \"/Winamp/winamp.exe\" );\n}\n\nvoid\nNothingPlayingWidget::onWMPClicked()\n{\n    startApp( \"/Windows Media Player/wmplayer.exe\" );\n}\n\nvoid\nNothingPlayingWidget::onFoobarClicked()\n{\n    startApp( \"/foobar2000/foobar2000.exe\" );\n}\n#endif\n\n\n\n"
  },
  {
    "path": "app/client/Widgets/NothingPlayingWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef NOTHINGPLAYINGWIDGET_H\n#define NOTHINGPLAYINGWIDGET_H\n\n#include <QFrame>\n\nnamespace lastfm { class User; }\nnamespace unicorn { class Session; }\n\nnamespace Ui { class NothingPlayingWidget; }\n\nclass NothingPlayingWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    explicit NothingPlayingWidget( QWidget* parent = 0 );\n\nprivate:\n    void setUser( const lastfm::User& user );\n#ifdef Q_OS_WIN\n    void startApp( const QString& app );\n#endif\n\nprivate slots:\n    void onSessionChanged( const unicorn::Session& session );\n\n#if defined( Q_OS_MAC )\n    void onAppleMusicClicked();\n#endif\n#if defined( Q_OS_MAC ) || defined( Q_OS_WIN )\n    void oniTunesClicked();\n#endif\n#ifdef Q_OS_WIN\n    void onWinampClicked();\n    void onWMPClicked();\n    void onFoobarClicked();\n#endif\n\nprivate:\n    Ui::NothingPlayingWidget* ui;\n};\n\n#endif // NOTHINGPLAYINGWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/NothingPlayingWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>NothingPlayingWidget</class>\n <widget class=\"QFrame\" name=\"NothingPlayingWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>482</width>\n    <height>688</height>\n   </rect>\n  </property>\n  <property name=\"focusPolicy\">\n   <enum>Qt::StrongFocus</enum>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QLabel\" name=\"top\">\n     <property name=\"text\">\n      <string>Hello!</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"contents\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"QFrame\" name=\"splitter\">\n        <property name=\"frameShape\">\n         <enum>QFrame::StyledPanel</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"scrobble\">\n        <property name=\"text\">\n         <string/>\n        </property>\n        <property name=\"wordWrap\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"itunes\">\n        <property name=\"text\">\n         <string>Open iTunes</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"applemusic\">\n        <property name=\"text\">\n         <string>Open Music</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"wmp\">\n        <property name=\"text\">\n         <string>Open Windows Media Player</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"winamp\">\n        <property name=\"text\">\n         <string>Open Winamp</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"foobar\">\n        <property name=\"text\">\n         <string>Open Foobar</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <spacer name=\"verticalSpacer\">\n        <property name=\"orientation\">\n         <enum>Qt::Vertical</enum>\n        </property>\n        <property name=\"sizeHint\" stdset=\"0\">\n         <size>\n          <width>20</width>\n          <height>0</height>\n         </size>\n        </property>\n       </spacer>\n      </item>\n     </layout>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/NothingPlayingWidget_mac.mm",
    "content": "\n\n#include \"NothingPlayingWidget.h\"\n\nvoid\nNothingPlayingWidget::oniTunesClicked()\n{\n    // launch iTunes!  \n    [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@\"com.apple.iTunes\" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:NULL];\n}\n\nvoid\nNothingPlayingWidget::onAppleMusicClicked()\n{\n    // launch Apple Music!  \n    [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@\"com.apple.Music\" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:NULL];\n}\n"
  },
  {
    "path": "app/client/Widgets/NowPlayingStackedWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QPushButton>\n#include <QLabel>\n#include <QImage>\n#include <QPixmap>\n#include <QStackedLayout>\n\n#include <lastfm/Track.h>\n\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n\n#include \"NowPlayingStackedWidget.h\"\n#include \"NowPlayingWidget.h\"\n#include \"NothingPlayingWidget.h\"\n\nNowPlayingStackedWidget::NowPlayingStackedWidget( QWidget* parent )\n    :unicorn::SlidingStackedWidget( parent )\n{\n    addWidget( ui.nothingPlaying = new NothingPlayingWidget( this ) );\n    addWidget( ui.nowPlaying = new NowPlayingWidget( this ) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(showNowPlaying()));\n    connect( &ScrobbleService::instance(), SIGNAL(stopped()), SLOT(showNothingPlaying()));\n}\n\nvoid\nNowPlayingStackedWidget::showNowPlaying()\n{\n    slide( 1 );\n}\n\nvoid\nNowPlayingStackedWidget::showNothingPlaying()\n{\n    slide( 0 );\n}\n\n\n"
  },
  {
    "path": "app/client/Widgets/NowPlayingStackedWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef NOWPLAYINGSTACKEDWIDGET_H\n#define NOWPLAYINGSTACKEDWIDGET_H\n\n#include <QWidget>\n#include <lastfm/Track.h>\n\n#include \"lib/unicorn/widgets/SlidingStackedWidget.h\"\n\nclass TrackItem;\nclass QLabel;\nclass QImage;\n\nclass NowPlayingStackedWidget : public unicorn::SlidingStackedWidget\n{\n    Q_OBJECT\n\nprivate:\n    struct {\n        class NothingPlayingWidget* nothingPlaying;\n        class NowPlayingWidget* nowPlaying;\n    } ui;\n\npublic:\n    NowPlayingStackedWidget( QWidget* parent = 0 );\n\n    class NowPlayingWidget* nowPlaying() const { return ui.nowPlaying; }\n\nprivate slots:\n    void showNowPlaying();\n    void showNothingPlaying();\n};\n\n#endif // NOWPLAYINGSTACKEDWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/NowPlayingWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QVBoxLayout>\n#include <QStackedWidget>\n#include <QMovie>\n\n#include \"NowPlayingWidget.h\"\n#include \"PlaybackControlsWidget.h\"\n#include \"MetadataWidget.h\"\n\n#include \"../Services/ScrobbleService.h\"\n\nNowPlayingWidget::NowPlayingWidget(QWidget *parent)\n    :QWidget(parent)\n{\n    QVBoxLayout* layout = new QVBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 0 );\n\n    layout->addWidget( ui.playbackControls = new PlaybackControlsWidget( this ) );\n    layout->addWidget( ui.stack = new QStackedWidget( this ) );\n\n    ui.stack->addWidget( ui.spinner = new QLabel() );\n    ui.spinner->setObjectName( \"spinner\" );\n    ui.spinner->setAlignment( Qt::AlignCenter );\n\n    m_movie = new QMovie( \":/loading_meta.gif\", \"GIF\", this );\n    m_movie->setCacheMode( QMovie::CacheAll );\n    ui.spinner->setMovie ( m_movie );\n\n    ui.metadata = 0;\n\n    connect( &ScrobbleService::instance(), SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(onTrackStarted(lastfm::Track,lastfm::Track)) );\n    connect( &ScrobbleService::instance(), SIGNAL(stopped()), SLOT(onStopped()) );\n}\n\nPlaybackControlsWidget*\nNowPlayingWidget::playbackControls() const\n{\n    return ui.playbackControls;\n}\n\nvoid\nNowPlayingWidget::onTrackStarted( const lastfm::Track& track, const lastfm::Track& )\n{\n    if ( track != Track() )\n    {\n        setUpdatesEnabled( false );\n\n        if ( ui.metadata )\n        {\n            ui.stack->removeWidget( ui.metadata );\n            ui.metadata->deleteLater();\n        }\n\n        ui.stack->addWidget( ui.metadata = new MetadataWidget( track, this ) );\n        ui.metadata->setBackButtonVisible( false );\n\n        ui.stack->setCurrentWidget( ui.metadata );\n        m_movie->stop();\n\n        setUpdatesEnabled( true );\n    }\n}\n\nvoid\nNowPlayingWidget::onStopped()\n{\n    ui.stack->setCurrentWidget( ui.spinner );\n    m_movie->stop();\n}\n"
  },
  {
    "path": "app/client/Widgets/NowPlayingWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef NOW_PLAYING_WIDGET_H\n#define NOW_PLAYING_WIDGET_H\n\n#include <QWidget>\n\n#include <lastfm/Track.h>\n\nclass NowPlayingWidget : public QWidget\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class PlaybackControlsWidget* playbackControls;\n        class QStackedWidget* stack;\n        class QLabel* spinner;\n        class MetadataWidget* metadata;\n    } ui;\n\npublic:\n    explicit NowPlayingWidget(QWidget *parent = 0);\n\n    class PlaybackControlsWidget* playbackControls() const;\n\nprivate slots:\n    void onTrackStarted( const lastfm::Track& track, const lastfm::Track& );\n    void onStopped();\n\nprivate:\n    class QMovie* m_movie;\n};\n\n#endif\n"
  },
  {
    "path": "app/client/Widgets/PlaybackControlsWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"../Application.h\"\n#include \"../Services/ScrobbleService.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"PlaybackControlsWidget.h\"\n#include \"ui_PlaybackControlsWidget.h\"\n\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n\n#include <QShortcut>\n#include <QMenu>\n#include <QMovie>\n#include <QTimer>\n\n\nvoid\nsetLayoutUsesWidgetRect( QWidget* widget )\n{\n    foreach ( QObject* object, widget->children() )\n    {\n        if ( object->isWidgetType() )\n        {\n            QWidget* widget = qobject_cast<QWidget*>( object );\n            widget->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n            setLayoutUsesWidgetRect( widget );\n        }\n    }\n}\n\n\nPlaybackControlsWidget::PlaybackControlsWidget(QWidget *parent) :\n    QFrame(parent),\n    ui(new Ui::PlaybackControlsWidget),\n    m_scrobbleTrack( false )\n{\n    ui->setupUi(this);\n\n    setLayoutUsesWidgetRect( this );\n\n    ui->love->setAttribute( Qt::WA_MacNoClickThrough );\n\n    // make sure this widget updates if the actions are changed elsewhere\n    connect( aApp->loveAction(), SIGNAL(changed()), SLOT(onActionsChanged()) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(onTrackStarted(lastfm::Track,lastfm::Track)) );\n    connect( &ScrobbleService::instance(), SIGNAL(stopped()), SLOT(onStopped()));\n    connect( &ScrobbleService::instance(), SIGNAL(scrobblingOnChanged(bool)), SLOT(update()));\n\n    onActionsChanged();\n\n\n    // if our buttons are pressed we should trigger the actions\n    connect( ui->love, SIGNAL(clicked()), aApp->loveAction(), SLOT(trigger()));\n\n    connect( &ScrobbleService::instance(), SIGNAL(frameChanged(int)), SLOT(onFrameChanged(int)) );\n}\n\nvoid\nPlaybackControlsWidget::addToMenu( QMenu& menu, QAction* before )\n{\n    menu.insertAction( before, m_playAction );\n\n    menu.insertSeparator( before );\n\n    menu.insertSeparator( before );\n\n    menu.insertAction( before, aApp->loveAction() );\n\n    menu.insertSeparator( before );\n\n    menu.insertAction( before, aApp->tagAction() );\n    menu.insertAction( before, aApp->shareAction() );\n\n    menu.insertSeparator( before );\n\n    //menu.addAction( tr( \"Volume Up\" ), &RadioService::instance(), SLOT(volumeUp()), QKeySequence( Qt::CTRL + Qt::Key_Up ));\n    //menu.addAction( tr( \"Volume Down\" ), &RadioService::instance(), SLOT(volumeDown()), QKeySequence( Qt::CTRL + Qt::Key_Down ));\n}\n\n\nPlaybackControlsWidget::~PlaybackControlsWidget()\n{\n    delete ui;\n}\n\n\nvoid\nPlaybackControlsWidget::setScrobbleTrack( bool scrobbleTrack )\n{\n    m_scrobbleTrack = scrobbleTrack;\n    style()->polish( this );\n    style()->polish( ui->details );\n    style()->polish( ui->status );\n    style()->polish( ui->device );\n    style()->polish( ui->love );\n}\n\nvoid\nPlaybackControlsWidget::onActionsChanged()\n{\n   ui->love->setChecked( aApp->loveAction()->isChecked() );\n\n   ui->love->setEnabled( aApp->loveAction()->isEnabled() );\n\n   ui->love->setToolTip( ui->love->isChecked() ? tr(\"Unlove\") : tr(\"Love\") );\n\n   ui->love->setText( ui->love->isChecked() ? tr(\"Unlove\") : tr(\"Love\") );\n}\n\n\nvoid\nPlaybackControlsWidget::onSpace()\n{\n    aApp->playAction()->trigger();\n}\n\n\nvoid\nPlaybackControlsWidget::onPlayClicked( bool checked )\n{\n    if ( checked )\n    {\n        AnalyticsService::instance().sendEvent(NOW_PLAYING_CATEGORY, PLAY_CLICKED, \"PlayButtonPressed\");\n    }\n    else\n    {\n        AnalyticsService::instance().sendEvent(NOW_PLAYING_CATEGORY, PLAY_CLICKED, \"PauseButtonPressed\");\n    }\n}\n\nvoid\nPlaybackControlsWidget::onLoveClicked( bool loved )\n{\n    if ( loved )\n    {\n        AnalyticsService::instance().sendEvent(NOW_PLAYING_CATEGORY, LOVE_TRACK, \"TrackLoved\");\n    }\n    else\n    {\n        AnalyticsService::instance().sendEvent(NOW_PLAYING_CATEGORY, LOVE_TRACK, \"TrackUnLoved\");\n    }\n}\n\n\nvoid\nPlaybackControlsWidget::onLoveTriggered( bool loved )\n{\n    ui->love->setChecked( loved );\n    onLoveClicked( loved );\n}\n\n\nvoid\nPlaybackControlsWidget::onTrackStarted( const lastfm::Track& track, const lastfm::Track& /*oldTrack*/ )\n{\n    setTrack( track );\n}\n\nvoid\nPlaybackControlsWidget::onError( int /*error*/, const QVariant& /*errorText*/ )\n{\n}\n\nvoid\nPlaybackControlsWidget::onStopped()\n{\n    aApp->playAction()->setChecked( false );\n    aApp->playAction()->setEnabled( true );\n    aApp->loveAction()->setEnabled( false );\n    aApp->tagAction()->setEnabled( false );\n    aApp->shareAction()->setEnabled( false );\n}\n\nvoid\nPlaybackControlsWidget::setTrack( const Track& track )\n{\n    // we're about to change loads of stuff to don't update until the end\n    setUpdatesEnabled( false );\n\n    disconnect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), ui->love, SLOT(setChecked(bool)));\n    disconnect( m_track.signalProxy(), SIGNAL(scrobbleStatusChanged(short)), this, SLOT(onScrobbleStatusChanged(short)) );\n    m_track = track;\n    connect( m_track.signalProxy(), SIGNAL(scrobbleStatusChanged(short)), this, SLOT(onScrobbleStatusChanged(short)) );\n\n    ui->as->setPixmap( QPixmap( \":/scrobble_marker_OFF.png\" ) );\n    ui->as->setToolTip( \"\" );\n\n    if ( track != Track() )\n    {\n        // you can love tag and share all tracks\n        aApp->loveAction()->setEnabled( true );\n        aApp->tagAction()->setEnabled( true );\n        aApp->shareAction()->setEnabled( true );\n\n        // play is always enabled as you should always\n        // be able to start the radio\n        aApp->playAction()->setEnabled( true );\n\n        aApp->playAction()->setChecked( false );\n\n        aApp->loveAction()->setChecked( track.isLoved() );\n\n        bool externalPlayer = track.extra( \"playerId\" ) == \"spt\" || track.extra( \"playerId\" ) == \"mpris2\";\n        bool scrobbleTrack = !externalPlayer;\n\n        ui->love->setVisible( true ); // you can always love a track\n\n        ui->as->setVisible( scrobbleTrack );\n        ui->as->setToolTip( tr( \"Not scrobbled\" ) );\n\n        ui->scrobbleMeter->setVisible( scrobbleTrack );\n        ui->scrobbleMeter->setRange( 0, ScrobbleService::instance().stopWatch()->scrobblePoint() * 1000 );\n        ui->scrobbleMeter->setValue( 0 );\n        ui->scrobbleMeter->setToolTip( tr( \"Scrobble meter: %1%\" ).arg( 0 ) );\n\n        ui->progressSpacer->setVisible( true );\n\n        connect( track.signalProxy(), SIGNAL(loveToggled(bool)), ui->love, SLOT(setChecked(bool)));\n\n        ui->status->setText( externalPlayer ? tr(\"Listening to\") : tr(\"Scrobbling from\") );\n\n        setScrobbleTrack( true );\n\n        ui->message->setVisible( externalPlayer );\n        ui->message->setText( track.extra( \"playerId\" ) == \"spt\" ?\n                                  unicorn::Label::boldLinkStyle( tr( \"Enable scrobbling by getting the %1.\" ).arg( unicorn::Label::anchor( \"https://www.last.fm/settings/applications\", tr( \"Last.fm app for Spotify\" ) ) ), Qt::black ):\n                                  \"\" );\n\n        ui->device->setText( track.extra( \"playerName\" ) );\n\n        // Set the icon!\n        QString id = track.extra( \"playerId\" );\n\n        if ( id == \"osx\" || id == \"itw\" )\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_itunes.png\" ) );\n        else if (id == \"mac\")\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_applemusic.png\" ) );\n        else if (id == \"foo\")\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_foobar.png\" ) );\n        else if (id == \"wa2\")\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_winamp.png\" ) );\n        else if (id == \"wmp\")\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_wmp.png\" ) );\n        else if (id == \"spt\")\n            ui->icon->setPixmap( QPixmap( \":/control_bar_scrobble_spotify.png\" ) );\n        else if ( id == \"mpris2\" )\n        {\n            if ( QIcon::hasThemeIcon( track.extra( \"desktopEntry\" ) ) )\n                ui->icon->setPixmap( QIcon::fromTheme( track.extra( \"desktopEntry\" ) ).pixmap( 44, 44 ) );\n            else if ( QIcon::hasThemeIcon( track.extra( \"serviceName\" ) ) )\n                ui->icon->setPixmap( QIcon::fromTheme( track.extra( \"serviceName\" ) ).pixmap( 44, 44 ) );\n            else if ( QIcon::hasThemeIcon( track.extra( \"playerName\" ) ) )\n                ui->icon->setPixmap( QIcon::fromTheme( track.extra( \"playerName\" ) ).pixmap( 44, 44 ) );\n            else\n                ui->icon->setPixmap( QPixmap( \":/control_bar_radio_as.png\" ) );\n        }\n        else\n            ui->icon->setPixmap( QPixmap( \":/control_bar_radio_as.png\" ) );\n    }\n    else\n    {\n        // what do we do with a null track???\n    }\n\n    setUpdatesEnabled( true );\n}\n\nbool\nPlaybackControlsWidget::eventFilter( QObject *obj, QEvent *event )\n{\n    return QFrame::eventFilter( obj, event );\n}\n\nvoid\nPlaybackControlsWidget::onFrameChanged( int frame )\n{\n    if ( ui->scrobbleMeter->maximum() != 1 )\n    {\n        int scrobbleValue = frame >= ui->scrobbleMeter->maximum() ? ui->scrobbleMeter->maximum() : frame;\n        ui->scrobbleMeter->setRange( 0, ScrobbleService::instance().stopWatch()->scrobblePoint() * 1000 );\n        ui->scrobbleMeter->setValue( scrobbleValue );\n        ui->scrobbleMeter->setToolTip( tr( \"Scrobble meter: %1%\" ).arg( qRound( ( 100 * scrobbleValue ) / ui->scrobbleMeter->maximum() ) )  );\n    }\n}\n\n\nvoid\nPlaybackControlsWidget::onScrobbleStatusChanged( short scrobbleStatus )\n{\n    if ( scrobbleStatus != Track::Null )\n        ui->as->setPixmap( QPixmap( \":/scrobble_marker_ON.png\" ) );\n\n    if ( scrobbleStatus == Track::Null ) ui->as->setToolTip( tr( \"Not scrobbled\" ) );\n    else if ( scrobbleStatus == Track::Cached || scrobbleStatus == Track::Submitted ) ui->as->setToolTip( tr( \"Scrobbled\" ) );\n    else if ( scrobbleStatus == Track::Error ) ui->as->setToolTip( tr( \"Error: \\\"%1\\\"\" ).arg( m_track.scrobbleErrorText() ) );\n}\n"
  },
  {
    "path": "app/client/Widgets/PlaybackControlsWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLAYBACKCONTROLS_H\n#define PLAYBACKCONTROLS_H\n\n#include <QAction>\n#include <QFrame>\n#include <QPointer>\n#include <QTimer>\n#include <lastfm/Track.h>\n\nnamespace unicorn { class Session; }\nnamespace Ui { class PlaybackControlsWidget; }\n\nclass QMovie;\n\nclass PlaybackControlsWidget : public QFrame\n{\n    Q_OBJECT\n\npublic:\n    explicit PlaybackControlsWidget(QWidget* parent = 0);\n    ~PlaybackControlsWidget();\n\npublic:\n    Q_PROPERTY( bool scrobbleTrack READ scrobbleTrack WRITE setScrobbleTrack )\n\n    bool scrobbleTrack() { return m_scrobbleTrack; }\n    void setScrobbleTrack( bool scrobbleTrack );\n\n    void addToMenu( class QMenu& menu, QAction* before = 0 );\n\nprivate:\n    bool eventFilter( QObject *obj, QEvent *event );\n\nprivate slots:\n    void onActionsChanged();\n    void onSpace();\n    void onPlayClicked( bool checked );\n    void onLoveClicked( bool loved );\n    void onLoveTriggered( bool loved );\n\n    void onTrackStarted( const lastfm::Track& track, const lastfm::Track& oldTrack );\n    void onError( int error , const QVariant& errorData );\n    void onStopped();\n\n    void onFrameChanged( int frame );\n    void onScrobbleStatusChanged( short scrobbleStatus );\n\nprivate:\n    void setTrack( const Track& track );\n\nprivate:\n    Ui::PlaybackControlsWidget *ui;\n\n    QPointer<QAction> m_playAction;\n\n    bool m_scrobbleTrack;\n\n    lastfm::Track m_track;\n};\n\n#endif // PLAYBACKCONTROLS_H\n"
  },
  {
    "path": "app/client/Widgets/PlaybackControlsWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>PlaybackControlsWidget</class>\n <widget class=\"QFrame\" name=\"PlaybackControlsWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>550</width>\n    <height>120</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QFrame\" name=\"details\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\" stretch=\"0,1,0\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"QLabel\" name=\"icon\">\n        <property name=\"text\">\n         <string notr=\"true\">Icon</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QFrame\" name=\"statusFrame\">\n        <property name=\"frameShape\">\n         <enum>QFrame::NoFrame</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n        <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n         <property name=\"spacing\">\n          <number>0</number>\n         </property>\n         <property name=\"margin\">\n          <number>0</number>\n         </property>\n         <item>\n          <widget class=\"unicorn::Label\" name=\"status\">\n           <property name=\"text\">\n            <string notr=\"true\">Status</string>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"unicorn::Label\" name=\"device\">\n           <property name=\"text\">\n            <string notr=\"true\">Device</string>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QFrame\" name=\"buttons\">\n        <property name=\"frameShape\">\n         <enum>QFrame::NoFrame</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n        <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n         <property name=\"spacing\">\n          <number>3</number>\n         </property>\n         <property name=\"margin\">\n          <number>0</number>\n         </property>\n         <item>\n          <widget class=\"QPushButton\" name=\"love\">\n           <property name=\"enabled\">\n            <bool>false</bool>\n           </property>\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Fixed\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"toolTip\">\n            <string>Love</string>\n           </property>\n           <property name=\"text\">\n            <string>Love</string>\n           </property>\n           <property name=\"checkable\">\n            <bool>true</bool>\n           </property>\n           <property name=\"flat\">\n            <bool>true</bool>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"progressFrame\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout_4\" stretch=\"0,0,1,1,0,0\">\n      <property name=\"spacing\">\n       <number>10</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"QLabel\" name=\"time\">\n        <property name=\"text\">\n         <string/>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"unicorn::Label\" name=\"message\">\n        <property name=\"text\">\n         <string/>\n        </property>\n        <property name=\"textFormat\">\n         <enum>Qt::RichText</enum>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QWidget\" name=\"progressSpacer\" native=\"true\"/>\n      </item>\n      <item>\n       <widget class=\"QProgressBar\" name=\"progress\">\n        <property name=\"value\">\n         <number>24</number>\n        </property>\n        <property name=\"visible\">\n          <bool>false</bool>\n        </property>\n        <property name=\"textVisible\">\n         <bool>false</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QFrame\" name=\"frame\">\n        <property name=\"frameShape\">\n         <enum>QFrame::NoFrame</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n        <layout class=\"QHBoxLayout\" name=\"horizontalLayout_5\">\n         <property name=\"spacing\">\n          <number>5</number>\n         </property>\n         <property name=\"margin\">\n          <number>0</number>\n         </property>\n         <item>\n          <widget class=\"QProgressBar\" name=\"scrobbleMeter\">\n           <property name=\"value\">\n            <number>24</number>\n           </property>\n           <property name=\"textVisible\">\n            <bool>false</bool>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QLabel\" name=\"as\">\n           <property name=\"text\">\n            <string/>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/PointyArrow.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"PointyArrow.h\"\n#include <QDebug>\n#include <QPixmap>\n#include <QPainter>\n#include <QTimeLine>\n#include <QApplication>\n#include <QDesktopWidget>\n\nPointyArrow::PointyArrow()\n{\n    setAttribute( Qt::WA_TranslucentBackground );\n    setWindowFlags( Qt::CustomizeWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint );\n    \n    m_timeline = new QTimeLine( 1000 );\n\n\n    connect( m_timeline, SIGNAL( frameChanged( int )), SLOT( onFrameChanged( int )));\n    connect( m_timeline, SIGNAL( finished()), SLOT( onFinished()));\n}\n\nPointyArrow::~PointyArrow()\n{\n    disconnect( m_timeline, 0, this, 0 );\n    delete m_timeline;\n}\n\nvoid \nPointyArrow::paintEvent( QPaintEvent* /*event*/ )\n{\n    QPainter p( this );\n    p.drawPixmap( QPoint( 0, 0 ), m_pm );\n}\n\nvoid \nPointyArrow::onFrameChanged( int frame )\n{\n    if( m_currentDirection == DirectionUp ||\n        m_currentDirection == DirectionDown ) \n    {\n        move( geometry().left(), frame );\n    } else {\n        move( frame, geometry().top() );\n    }\n}\n\nvoid \nPointyArrow::onFinished()\n{\n    m_timeline->toggleDirection();\n    m_timeline->start();\n}\n\nvoid\nPointyArrow::pointAt( const QPoint& point )\n{ \n    m_timeline->stop();\n    QRect availRect = qApp->desktop()->availableGeometry( point );\n    QRect screenRect = qApp->desktop()->screenGeometry( point );\n\n    const bool autoHideSysTray = (availRect == screenRect);\n\n    QRect taskbarRect;\n    if( !autoHideSysTray ) {\n        taskbarRect = (QRegion(screenRect) - QRegion(availRect)).rects().first();\n    }\n\n    if( point.x() < availRect.left() ) {\n        //taskbar is left\n        m_currentDirection = DirectionLeft;\n        m_pm = QPixmap( \":/pointyarrow.png\" ).transformed(QTransform().rotate(270.0));\n        resize( m_pm.size());\n        move( taskbarRect.right(), point.y() - (height() / 2.0f));\n        m_timeline->setFrameRange( geometry().left(), geometry().left() + 40 );\n    } else if( point.y() < availRect.top() ) {\n        //taskbar is top\n        m_currentDirection = DirectionUp;\n        m_pm = QPixmap( \":/pointyarrow.png\" );\n        resize( m_pm.size());\n        move( point.x() - (width() / 2.0f), taskbarRect.bottom() );\n        m_timeline->setFrameRange( geometry().top(), geometry().top() + 40 );\n    } else if( point.x() > availRect.right() ) {\n        //taskbar is right\n        m_currentDirection = DirectionRight;\n        m_pm = QPixmap( \":/pointyarrow.png\" ).transformed(QTransform().rotate(90.0));\n        resize( m_pm.size());\n        move( taskbarRect.left()-width(), point.y() - (height() / 2.0f));\n        m_timeline->setFrameRange( geometry().left(), geometry().left() - 40 );\n    } else {\n        //presume that taskbar is at the bottom\n        m_currentDirection = DirectionDown;\n        m_pm = QPixmap( \":/pointyarrow.png\" ).transformed(QTransform().rotate(180.0));\n        resize( m_pm.size());\n        move( point.x() - (width() / 2.0f), taskbarRect.top()-height() );\n        m_timeline->setFrameRange( geometry().top(), geometry().top() - 40 );\n    }\n\n    m_timeline->setCurveShape( QTimeLine::EaseInOutCurve );\n    m_timeline->start();\n    show();\n}\n"
  },
  {
    "path": "app/client/Widgets/PointyArrow.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef POINTY_ARROW_H\n#define POINTY_ARROW_H\n\n#include <QWidget>\n#include <QPixmap>\n\nclass PointyArrow : public QWidget {\n    Q_OBJECT\n\npublic:\n    PointyArrow();\n    ~PointyArrow();\n\n    void pointAt( const QPoint& );\n\nprotected:\n    virtual void paintEvent( QPaintEvent* );\n    QPixmap m_pm;\n    class QTimeLine* m_timeline;\n\n\tenum { DirectionUp, DirectionDown, DirectionLeft, DirectionRight } m_currentDirection;\n\nprotected slots:\n    void onFrameChanged( int );\n    void onFinished();\n};\n\n#endif //POINTY_ARROW_H\n\n"
  },
  {
    "path": "app/client/Widgets/ProfileArtistWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n\n#include <lastfm/XmlQuery.h>\n#include <lastfm/Artist.h>\n\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n\n#include \"../Application.h\"\n\n#include \"ProfileArtistWidget.h\"\n\n\nclass PlaysLabel : public QLabel\n{\npublic:\n    explicit PlaysLabel( const QString& text, int plays, int maxPlays, QWidget* parent = 0 )\n        :QLabel( text, parent ),\n          m_plays( plays ),\n          m_maxPlays( maxPlays )\n    {}\n\nprivate:\n    void paintEvent( QPaintEvent* event )\n    {\n        QPainter p;\n        p.begin( this );\n\n        QFontMetrics fm( font() );\n\n        p.setPen( QColor( 0xa6a6a6 ) );\n        p.setBrush( QColor( 0xdedede ) );\n        p.drawRoundedRect( rect().adjusted( 0, 0, -1, -1 ), 4, 4 );\n\n        int indent = fm.width( tr( \"%L1 play(s)\", \"\", 999999 ).arg( 999999 ) );\n        int chunk = ( (width() - indent ) * m_plays ) / m_maxPlays;\n        int adjust = indent + chunk - width();\n        p.setPen( QColor( 0x2a8bad ) );\n        p.setBrush( QColor( 0x34bae8 ) );\n        p.drawRoundedRect( rect().adjusted( 0, 0, adjust - 1, -1 ), 4, 4 );\n\n        p.end();\n\n        QLabel::paintEvent( event );\n    }\n\nprivate:\n    int m_plays;\n    int m_maxPlays;\n};\n\n\nProfileArtistWidget::ProfileArtistWidget( const lastfm::XmlQuery& artist, int maxPlays, QWidget* parent)\n    :QFrame( parent )\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 0 );\n\n    HttpImageWidget* artistImage = new HttpImageWidget( this );\n    layout->addWidget( artistImage );\n    artistImage->setObjectName( \"artistImage\" );\n\n    QRegExp re( \"/serve/(\\\\d*)s?/\" );\n\n    artistImage->loadUrl( artist[\"image size=medium\"].text().replace( re, \"/serve/\\\\1s/\" ), HttpImageWidget::ScaleNone );\n    artistImage->setHref( artist[\"url\"].text() );\n\n    QVBoxLayout* vl = new QVBoxLayout();\n    vl->setContentsMargins( 0, 0, 0, 0 );\n    vl->setSpacing( 6 );\n    layout->addLayout( vl, 1 );\n\n    QHBoxLayout * hl = new QHBoxLayout();\n    hl->setContentsMargins( 0, 0, 0, 0 );\n    hl->setSpacing( 0 );\n\n    unicorn::Label* artistName = new unicorn::Label( this );\n    artistName->setTextFormat( Qt::RichText );\n    artistName->setText( unicorn::Label::boldLinkStyle( unicorn::Label::anchor( artist[\"url\"].text(), artist[\"name\"].text() ), Qt::black ) );\n    hl->addWidget( artistName, 1 );\n    artistName->setObjectName( \"artistName\" );\n\n    vl->addLayout( hl );\n\n    int playcount = artist[\"playcount\"].text().toInt();\n    PlaysLabel* plays = new PlaysLabel( tr( \"%L1 play(s)\", \"\", playcount ).arg( playcount ), playcount, maxPlays, this );\n    vl->addWidget( plays );\n    plays->setObjectName( \"plays\" );\n\n    vl->addStretch();\n}\n\n"
  },
  {
    "path": "app/client/Widgets/ProfileArtistWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ProfileArtistWidget_H\n#define ProfileArtistWidget_H\n\n#include <QFrame>\n\nnamespace lastfm { class XmlQuery; }\n\nclass ProfileArtistWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    explicit ProfileArtistWidget( const lastfm::XmlQuery& artist, int maxPlays, QWidget *parent = 0);\n\n};\n\n#endif // ProfileArtistWidget_H\n"
  },
  {
    "path": "app/client/Widgets/ProfileWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QBoxLayout>\n#include <QLabel>\n\n#include <lastfm/Library.h>\n#include <lastfm/XmlQuery.h>\n\n#include \"lib/unicorn/widgets/Label.h\"\n#include \"lib/unicorn/widgets/AvatarWidget.h\"\n\n#include \"ProfileArtistWidget.h\"\n#include \"ContextLabel.h\"\n#include \"FriendWidget.h\"\n\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n#include \"../Application.h\"\n\n#include \"ProfileWidget.h\"\n\n#include \"ui_ProfileWidget.h\"\n\nProfileWidget::ProfileWidget(QWidget *parent)\n    :QFrame(parent), ui( new Ui::ProfileWidget )\n{\n    ui->setupUi( this );\n\n    ui->scrobbles->setText( tr( \"Scrobble(s)\", \"\", 0 ) );\n    ui->loved->setText( tr( \"Loved track(s)\", \"\", 0 ) );\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n    connect( aApp, SIGNAL(gotUserInfo(lastfm::User)), SLOT(onGotUserInfo(lastfm::User)) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(scrobblesCached(QList<lastfm::Track>)), SLOT(onScrobblesCached(QList<lastfm::Track>)));\n\n    onSessionChanged( aApp->currentSession() );\n}\n\nProfileWidget::~ProfileWidget()\n{\n    delete ui;\n}\n\nvoid\nProfileWidget::onSessionChanged( const unicorn::Session& session )\n{  \n    if ( session.user().name() != m_currentUser )\n    {\n        m_currentUser = session.user().name();\n        ui->avatar->setPixmap( QPixmap( \":/user_default.png\" ) );\n        onGotUserInfo( session.user() );\n\n        refresh();\n    }\n}\n\n\nvoid\nProfileWidget::onGotUserInfo( const lastfm::User& user )\n{\n     ui->avatar->setAlignment( Qt::AlignCenter );\n\n     ui->avatar->setUser( user );\n     ui->avatar->loadUrl( user.imageUrl( User::LargeImage, true ), HttpImageWidget::ScaleNone );\n     ui->avatar->setHref( user.www() );\n\n     ui->infoString->setText( FriendWidget::userString( user ) );\n\n     ui->scrobbles->setText( tr( \"Scrobble(s) since %1\", \"\", user.scrobbleCount() ).arg( user.dateRegistered().toString( Qt::DefaultLocaleShortDate ) ) );\n\n     m_scrobbleCount = user.scrobbleCount();\n     setScrobbleCount();\n\n     ui->name->setText( unicorn::Label::boldLinkStyle( unicorn::Label::anchor( user.www().toString(), user.name() ), Qt::black ) );\n}\n\nvoid\nProfileWidget::refresh()\n{\n    // Make sure we don't recieve any updates about the last session\n    disconnect( this, SLOT(onGotLovedTracks()));\n    disconnect( this, SLOT(onGotTopOverallArtists()));\n    disconnect( this, SLOT(onGotTopWeeklyArtists()));\n    disconnect( this, SLOT(onGotLibraryArtists()));\n\n    connect( aApp->currentSession().user().getLovedTracks( 1 ), SIGNAL(finished()), SLOT(onGotLovedTracks()) );\n    connect( aApp->currentSession().user().getTopArtists( \"overall\", 5, 1 ), SIGNAL(finished()), SLOT(onGotTopOverallArtists()));\n    connect( aApp->currentSession().user().getTopArtists( \"7day\", 5, 1 ), SIGNAL(finished()), SLOT(onGotTopWeeklyArtists()));\n    connect( lastfm::Library::getArtists( aApp->currentSession().user().name(), 1 ), SIGNAL(finished()), SLOT(onGotLibraryArtists()));\n}\n\nvoid\nProfileWidget::onCurrentChanged( int index )\n{\n    if ( index == 2 )\n        refresh();\n}\n\nvoid\nProfileWidget::onGotLibraryArtists()\n{\n    lastfm::XmlQuery lfm;\n\n    if ( lfm.parse( static_cast<QNetworkReply*>(sender()) ) )\n    {\n        int scrobblesPerDay = aApp->currentSession().user().scrobbleCount() / (aApp->currentSession().user().dateRegistered().daysTo( QDateTime::currentDateTime() ) + 1 );\n        int totalArtists = lfm[\"artists\"].attribute( \"total\" ).toInt();\n\n        QString artistsString = tr( \"%L1 artist(s)\", \"\", totalArtists ).arg( totalArtists );\n        QString tracksString = tr( \"%L1 track(s)\", \"\", scrobblesPerDay ).arg( scrobblesPerDay );\n\n        ui->userBlurb->setText( tr( \"You have %1 in your library and on average listen to %2 per day.\" ).arg( artistsString , tracksString ) );\n        ui->userBlurb->show();\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\n\nvoid\nProfileWidget::onGotTopWeeklyArtists()\n{\n    lastfm::XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        ui->weekFrame->setUpdatesEnabled( false );\n\n        ui->weekFrame->layout()->takeAt( 0 )->widget()->deleteLater();\n\n        QFrame* temp = new QFrame( this );\n        ui->weekFrame->layout()->addWidget( temp );\n        QVBoxLayout* layout = new QVBoxLayout( temp );\n        layout->setContentsMargins( 0, 0, 0, 0 );\n        layout->setSpacing( 0 );\n\n        int maxPlays = lfm[\"topartists\"][\"artist\"][\"playcount\"].text().toInt();\n\n        foreach ( const lastfm::XmlQuery& artist, lfm[\"topartists\"].children(\"artist\") )\n            layout->addWidget( new ProfileArtistWidget( artist, maxPlays, this ) );\n\n        ui->weekFrame->setUpdatesEnabled( true );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\n\nvoid\nProfileWidget::onGotTopOverallArtists()\n{\n    lastfm::XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        ui->overallFrame->setUpdatesEnabled( false );\n\n        ui->overallFrame->layout()->takeAt( 0 )->widget()->deleteLater();\n\n        QFrame* temp = new QFrame( this );\n        ui->overallFrame->layout()->addWidget( temp );\n        QVBoxLayout* layout = new QVBoxLayout( temp );\n        layout->setContentsMargins( 0, 0, 0, 0 );\n        layout->setSpacing( 0 );\n\n        int maxPlays = lfm[\"topartists\"][\"artist\"][\"playcount\"].text().toInt();\n\n        foreach ( const lastfm::XmlQuery& artist, lfm[\"topartists\"].children(\"artist\") )\n            layout->addWidget( new ProfileArtistWidget( artist, maxPlays, this ) );\n\n        ui->overallFrame->setUpdatesEnabled( true );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\nvoid\nProfileWidget::onGotLovedTracks()\n{\n    lastfm::XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        int lovedTrackCount = lfm[\"lovedtracks\"].attribute( \"total\" ).toInt();\n        ui->loved->setText( tr( \"Loved track(s)\", \"\", lovedTrackCount ) );\n        ui->lovedCount->setText( QString( \"%L1\" ).arg( lovedTrackCount ) );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\n\nvoid\nProfileWidget::onScrobblesCached( const QList<lastfm::Track>& tracks )\n{\n    foreach ( lastfm::Track track, tracks )\n        connect( track.signalProxy(), SIGNAL(scrobbleStatusChanged( short )), SLOT(onScrobbleStatusChanged( short )));\n}\n\nvoid\nProfileWidget::onScrobbleStatusChanged( short scrobbleStatus )\n{\n    if (scrobbleStatus == lastfm::Track::Submitted)\n    {\n        disconnect( sender(), SIGNAL(scrobbleStatusChanged( short )), this, SLOT(onScrobbleStatusChanged( short )));\n        ++m_scrobbleCount;\n        setScrobbleCount();\n    }\n}\n\nvoid\nProfileWidget::setScrobbleCount()\n{\n    ui->scrobbles->setText( tr( \"Scrobble(s) since %1\", \"\", aApp->currentSession().user().scrobbleCount() ).arg( aApp->currentSession().user().dateRegistered().toString( \"d MMMM yyyy\" ) ) );\n    ui->scrobbleCount->setText( QString( \"%L1\" ).arg( m_scrobbleCount ) );\n}\n"
  },
  {
    "path": "app/client/Widgets/ProfileWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PROFILEWIDGET_H\n#define PROFILEWIDGET_H\n\n#include <QPointer>\n#include <QFrame>\n\n#include <lastfm/Track.h>\n\n#include \"lib/unicorn/UnicornSession.h\"\n\nnamespace unicorn { class Label; }\n\nnamespace Ui { class ProfileWidget; }\n\nclass ProfileWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    explicit ProfileWidget(QWidget *parent = 0);\n    ~ProfileWidget();\n\npublic slots:\n    void onCurrentChanged( int index );\n    void refresh();\n\nprivate slots:\n    void onSessionChanged( const unicorn::Session& session );\n    void onGotUserInfo( const lastfm::User& userDetails );\n\n    void onGotTopWeeklyArtists();\n    void onGotTopOverallArtists();\n\n    void onGotLibraryArtists();\n\n    void onGotLovedTracks();\n\n    void onScrobblesCached( const QList<lastfm::Track>& tracks );\n    void onScrobbleStatusChanged( short scrobbleStatus );\n    void setScrobbleCount();\n\nprivate:\n    Ui::ProfileWidget* ui;\n\n    QString m_currentUser;\n    int m_scrobbleCount;\n};\n\n#endif // PROFILEWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/ProfileWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ProfileWidget</class>\n <widget class=\"QWidget\" name=\"ProfileWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>485</width>\n    <height>685</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\" stretch=\"0,0,0,0,0,0,0,0,1\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QFrame\" name=\"user\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout\" stretch=\"0,1\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"AvatarWidget\" name=\"avatar\">\n        <property name=\"text\">\n         <string/>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\" stretch=\"0,0,3,0,0,1,0,0,0\">\n        <property name=\"spacing\">\n         <number>3</number>\n        </property>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"name\">\n          <property name=\"text\">\n           <string/>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"infoString\">\n          <property name=\"text\">\n           <string/>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer_2\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>0</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"scrobbleCount\">\n          <property name=\"text\">\n           <string notr=\"true\">0</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"scrobbles\">\n          <property name=\"text\">\n           <string notr=\"true\">Scrobbles</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer_3\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>0</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"lovedCount\">\n          <property name=\"text\">\n           <string notr=\"true\">0</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QLabel\" name=\"loved\">\n          <property name=\"text\">\n           <string notr=\"true\">Loved tracks</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer_4\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>12</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n       </layout>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"ContextLabel\" name=\"userBlurb\">\n     <property name=\"text\">\n      <string notr=\"true\">context</string>\n     </property>\n     <property name=\"textFormat\">\n      <enum>Qt::RichText</enum>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"hsplitter1\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"weekTitle\">\n     <property name=\"text\">\n      <string>Top Artists This Week</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"weekFrame\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_3\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"QFrame\" name=\"weekFrameTemp\">\n        <property name=\"frameShape\">\n         <enum>QFrame::StyledPanel</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"hsplitter2\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"overallTitle\">\n     <property name=\"text\">\n      <string>Top Artists Overall</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"overallFrame\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_4\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"QFrame\" name=\"overallFrameTemp\">\n        <property name=\"frameShape\">\n         <enum>QFrame::StyledPanel</enum>\n        </property>\n        <property name=\"frameShadow\">\n         <enum>QFrame::Raised</enum>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <spacer name=\"verticalSpacer\">\n     <property name=\"orientation\">\n      <enum>Qt::Vertical</enum>\n     </property>\n     <property name=\"sizeHint\" stdset=\"0\">\n      <size>\n       <width>20</width>\n       <height>0</height>\n      </size>\n     </property>\n    </spacer>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>ContextLabel</class>\n   <extends>QLabel</extends>\n   <header>../Widgets/ContextLabel.h</header>\n  </customwidget>\n  <customwidget>\n   <class>AvatarWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/AvatarWidget.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/PushButton.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QPixmap>\n#include <QPainter>\n#include <QEvent>\n#include <QStyle>\n\n#include \"PushButton.h\"\n\nPushButton::PushButton(QWidget *parent) :\n    QPushButton(parent),\n    m_hovered( false ),\n    m_dark( false )\n{\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    setAttribute( Qt::WA_Hover );\n    setAttribute( Qt::WA_MacNoClickThrough );\n\n    setCursor( Qt::PointingHandCursor );\n}\n\nbool\nPushButton::dark() const\n{\n    return m_dark;\n}\n\nvoid\nPushButton::setDark( bool dark )\n{\n    m_dark = dark;\n    //style()->polish( this );\n}\n\nbool\nPushButton::event( QEvent* e )\n{\n    switch ( e->type() )\n    {\n    case QEvent::HoverEnter:\n        m_hovered = true;\n        update();\n        break;\n    case QEvent::HoverLeave:\n        m_hovered = false;\n        update();\n        break;\n    default:\n        break;\n    }\n\n    return QPushButton::event( e );\n}\n\nvoid\nPushButton::paintEvent(QPaintEvent *)\n{\n    static QPixmap leftHoverLight( \":/button_LEFT_HOVER.png\" );\n    static QPixmap leftPressLight( \":/button_LEFT_PRESS.png\" );\n    static QPixmap leftRestLight( \":/button_LEFT_REST.png\" );\n    static QPixmap middleHoverLight( \":/button_MIDDLE_HOVER.png\" );\n    static QPixmap middlePressLight( \":/button_MIDDLE_PRESS.png\" );\n    static QPixmap middleRestLight( \":/button_MIDDLE_REST.png\" );\n    static QPixmap rightHoverLight( \":/button_RIGHT_HOVER.png\" );\n    static QPixmap rightPressLight( \":/button_RIGHT_PRESS.png\" );\n    static QPixmap rightRestLight( \":/button_RIGHT_REST.png\" );\n\n    static QPixmap leftHoverDark( \":/button_dark_LEFT_HOVER.png\" );\n    static QPixmap leftPressDark( \":/button_dark_LEFT_PRESS.png\" );\n    static QPixmap leftRestDark( \":/button_dark_LEFT_REST.png\" );\n    static QPixmap middleHoverDark( \":/button_dark_MIDDLE_HOVER.png\" );\n    static QPixmap middlePressDark( \":/button_dark_MIDDLE_PRESS.png\" );\n    static QPixmap middleRestDark( \":/button_dark_MIDDLE_REST.png\" );\n    static QPixmap rightHoverDark( \":/button_dark_RIGHT_HOVER.png\" );\n    static QPixmap rightPressDark( \":/button_dark_RIGHT_PRESS.png\" );\n    static QPixmap rightRestDark( \":/button_dark_RIGHT_REST.png\" );\n\n    QPixmap* leftHover = m_dark ? &leftHoverDark : &leftHoverLight;\n    QPixmap* leftPress = m_dark ? &leftPressDark : &leftPressLight;\n    QPixmap* leftRest = m_dark ? &leftRestDark : &leftRestLight;\n    QPixmap* middleHover = m_dark ? &middleHoverDark : &middleHoverLight;\n    QPixmap* middlePress = m_dark ? &middlePressDark : &middlePressLight;\n    QPixmap* middleRest = m_dark ? &middleRestDark : &middleRestLight;\n    QPixmap* rightHover = m_dark ? &rightHoverDark : &rightHoverLight;\n    QPixmap* rightPress = m_dark ? &rightPressDark : &rightPressLight;\n    QPixmap* rightRest = m_dark ? &rightRestDark : &rightRestLight;\n\n    QPainter p( this );\n\n    QRect middleRect = QRect( leftRest->width(), 0, rect().width() - leftRest->width() - rightRest->width(), 49 );\n\n    if ( isDown() )\n    {\n        p.drawPixmap( rect().topLeft(), *leftPress );\n        p.drawPixmap( middleRect, *middlePress );\n        p.drawPixmap( rect().topLeft() + QPoint( rect().width() - rightPress->width(), 0 ), *rightPress );\n    }\n    else if ( m_hovered )\n    {\n        p.drawPixmap( rect().topLeft(), *leftHover );\n        p.drawPixmap( middleRect, *middleHover );\n        p.drawPixmap( rect().topLeft() + QPoint( rect().width() - rightHover->width(), 0 ), *rightHover );\n    }\n    else\n    {\n        p.drawPixmap( rect().topLeft(), *leftRest );\n        p.drawPixmap( middleRect, *middleRest );\n        p.drawPixmap( rect().topLeft() + QPoint( rect().width() - rightRest->width(), 0 ), *rightRest );\n    }\n\n    QFontMetrics fmText( font() );\n    QRect textRect = contentsRect();\n    p.drawText( textRect, Qt::AlignCenter, fmText.elidedText( text(), Qt::ElideRight, textRect.width() ) );\n}\n"
  },
  {
    "path": "app/client/Widgets/PushButton.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PUSHBUTTON_H\n#define PUSHBUTTON_H\n\n#include <QPushButton>\n\nclass PushButton : public QPushButton\n{\n    Q_OBJECT\npublic:\n    Q_PROPERTY(bool dark READ dark WRITE setDark)\n\n    explicit PushButton(QWidget *parent = 0);\n\n    bool dark() const;\n    void setDark( bool dark );\n    \nprivate:\n    bool event(QEvent *e);\n    void paintEvent(QPaintEvent *);\n\nprivate:\n    bool m_hovered;\n    bool m_dark;\n};\n\n#endif // PUSHBUTTON_H\n"
  },
  {
    "path": "app/client/Widgets/RefreshButton.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QPainter>\n\n#include \"RefreshButton.h\"\n\nRefreshButton::RefreshButton(QWidget *parent) :\n    QPushButton(parent), m_pixmap( \":/scrobbles_refresh.png\" )\n{\n}\n\nvoid\nRefreshButton::paintEvent( QPaintEvent* e )\n{\n    QPushButton::paintEvent( e );\n\n    QPainter p( this );\n    QFontMetrics fm( font() );\n    p.drawPixmap( rect().center() - QPoint( ( fm.width( text() ) / 2 ) + m_pixmap.width() + 10, ( m_pixmap.height() / 2 ) - 1 ), m_pixmap );\n}\n"
  },
  {
    "path": "app/client/Widgets/RefreshButton.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef REFRESHBUTTON_H\n#define REFRESHBUTTON_H\n\n#include <QPushButton>\n#include <QPixmap>\n\nclass RefreshButton : public QPushButton\n{\n    Q_OBJECT\npublic:\n    explicit RefreshButton(QWidget *parent = 0);\n\nprivate:\n    void paintEvent(QPaintEvent *);\n\nprivate:\n    QPixmap m_pixmap;\n};\n\n#endif // REFRESHBUTTON_H\n"
  },
  {
    "path": "app/client/Widgets/ScrobbleControls.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QPushButton>\n#include <QToolButton>\n#include <QAction>\n#include <QShortcut>\n#include <QMenu>\n\n#include \"lib/unicorn/dialogs/ShareDialog.h\"\n#include \"lib/unicorn/dialogs/TagDialog.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"ScrobbleControls.h\"\n\n#include \"../Application.h\"\n\nScrobbleControls::ScrobbleControls( QWidget* parent )\n    :QFrame( parent )\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 5 );\n\n    layout->addWidget(ui.love = new QPushButton(tr(\"Love\")), 0, Qt::AlignCenter);\n    ui.love->setObjectName(\"love\");\n    ui.love->setCheckable( true );\n    ui.love->setToolTip( tr( \"Love track\" ) );\n    connect( ui.love, SIGNAL( clicked(bool) ), SLOT( onLoveChanged( bool ) ) );\n \n    layout->addWidget(ui.tag = new QPushButton(tr(\"Tag\")), 0, Qt::AlignCenter);\n    ui.tag->setObjectName(\"tag\");\n    ui.tag->setToolTip( tr( \"Add tags\" ) );\n\n    layout->addWidget(ui.share = new QPushButton(tr(\"Share\")), 0, Qt::AlignCenter);\n    ui.share->setObjectName(\"share\");\n    ui.share->setToolTip( tr( \"Share\" ) );\n\n    QMenu* shareMenu = new QMenu( this );\n    shareMenu->addAction( tr( \"Share on Last.fm\" ), this, SLOT(onShareLastFm()) );\n    shareMenu->addAction( tr( \"Share on Twitter\" ), this, SLOT(onShareTwitter()) );\n    shareMenu->addAction( tr( \"Share on Facebook\" ), this, SLOT(onShareFacebook()) );\n    ui.share->setMenu( shareMenu );\n\n    layout->addWidget(ui.buy = new QPushButton(tr(\"Buy\")), 0, Qt::AlignCenter);\n    ui.buy->setObjectName(\"buy\");\n    ui.buy->setToolTip( tr( \"Buy\" ) );\n    ui.buy->setVisible( false );\n\n    ui.love->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui.tag->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui.share->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui.buy->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui.love->setAttribute( Qt::WA_MacNoClickThrough );\n    ui.tag->setAttribute( Qt::WA_MacNoClickThrough );\n    ui.share->setAttribute( Qt::WA_MacNoClickThrough );\n    ui.buy->setAttribute( Qt::WA_MacNoClickThrough );\n\n    layout->addStretch( 1 );\n\n    new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_S ), ui.share, SLOT( click() ) );\n    new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_T ), ui.tag, SLOT( click() ) );\n    new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_L ), ui.love, SLOT( toggle() ) );\n    new QShortcut( QKeySequence( Qt::CTRL + Qt::Key_B ), ui.buy, SLOT( click() ) );\n\n    connect( ui.tag, SIGNAL( clicked()), SLOT( onTag()));\n    //connect( ui.share, SIGNAL( clicked()), SLOT( onShare()));\n}\n\n\nvoid\nScrobbleControls::setTrack( const Track& track )\n{\n    disconnect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), this, SLOT(setLoveChecked(bool)));\n    m_track = track;\n    connect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), SLOT(setLoveChecked(bool)));\n}\n\n\nvoid\nScrobbleControls::setLoveChecked( bool checked )\n{\n    /// This just changes the state of the love button\n\n    ui.love->setChecked( checked );\n\n    if ( checked )\n        ui.love->setToolTip( tr( \"Unlove track\" ) );\n    else\n        ui.love->setToolTip( tr( \"Love track\" ) );\n}\n\n\nvoid\nScrobbleControls::onLoveChanged( bool checked )\n{\n    /// This changes the state of the love button and\n    /// loves the track on Last.fm\n\n    // change the button state to the new state. Don't worry\n    // it'll get changed back if the web service request fails\n    setLoveChecked( checked );\n\n    MutableTrack track( m_track );\n\n    if ( checked )\n        track.love();\n    else\n        track.unlove();\n}\n\nvoid \nScrobbleControls::onShareLastFm()\n{\n    ShareDialog* sd = new ShareDialog( m_track, window() );\n    sd->raise();\n    sd->show();\n    sd->activateWindow();\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"ShareDialog\");\n}\n\nvoid\nScrobbleControls::onShareTwitter()\n{\n    ShareDialog::shareTwitter( m_track );\n\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"TwitterShare\");\n}\n\nvoid\nScrobbleControls::onShareFacebook()\n{\n    ShareDialog::shareFacebook( m_track );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"FacebookShare\");\n}\n\nvoid\nScrobbleControls::onTag()\n{\n    TagDialog* td = new TagDialog( m_track, window() );\n    td->raise();\n    td->show();\n    td->activateWindow();\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), TAG_CLICKED, \"TagButtonPressed\");\n}\n"
  },
  {
    "path": "app/client/Widgets/ScrobbleControls.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SCROBBLE_CONTROLS_H\n#define SCROBBLE_CONTROLS_H\n\n#include <QFrame>\n\n#include <lastfm/Track.h>\n#include <lastfm/XmlQuery.h>\n\nnamespace unicorn{ class Session; }\nnamespace lastfm{ class User; }\n\nclass QPushButton;\n\nclass ScrobbleControls : public QFrame\n{\n    Q_OBJECT\npublic:\n    struct {\n        QPushButton* love;\n        QPushButton* tag;\n        QPushButton* share;\n        QPushButton* buy;\n    } ui;\n\npublic:\n    ScrobbleControls( QWidget* parent = 0 );\n\n    void setTrack( const Track& track );\n\npublic slots:\n    void setLoveChecked( bool checked );\n\nprivate slots:\n    void onLoveChanged( bool checked );\n\n    void onShareLastFm();\n    void onShareTwitter();\n    void onShareFacebook();\n\n    void onTag();\n\nprivate:\n    Track m_track;\n};\n\n#endif //SCROBBLE_CONTROLS_H\n"
  },
  {
    "path": "app/client/Widgets/ScrobblesListWidget.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QApplication>\n#include <QHeaderView>\n#include <QScrollBar>\n#include <QTimer>\n\n#include <lastfm/Track.h>\n#include <lastfm/UrlBuilder.h>\n\n#include \"lib/unicorn/dialogs/ShareDialog.h\"\n#include \"lib/unicorn/dialogs/TagDialog.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"../Services/ScrobbleService.h\"\n#include \"../Application.h\"\n\n#include \"RefreshButton.h\"\n#include \"TrackWidget.h\"\n#include \"ScrobblesListWidget.h\"\n\n#define kScrobbleLimit 30\n\nclass ScrobblesListWidgetItem : public QListWidgetItem\n{\npublic:\n    ScrobblesListWidgetItem( QListWidget* parent );\n    bool operator<( const QListWidgetItem& that ) const;\n\n    bool isNowPlaying() const;\n    void setNowPlaying( bool nowPlaying );\n\n    void setTrack( lastfm::Track& track );\n\nprivate:\n    bool m_nowPlaying;\n};\n\nScrobblesListWidgetItem::ScrobblesListWidgetItem( QListWidget* parent )\n    :QListWidgetItem( parent ), m_nowPlaying( false )\n{\n}\n\nbool\nScrobblesListWidgetItem::isNowPlaying() const\n{\n    return m_nowPlaying;\n}\n\nvoid\nScrobblesListWidgetItem::setNowPlaying( bool nowPlaying )\n{\n    m_nowPlaying = nowPlaying;\n    static_cast<TrackWidget*>( listWidget()->itemWidget( this ) )->setNowPlaying( true );\n}\n\nvoid\nScrobblesListWidgetItem::setTrack( lastfm::Track& track )\n{\n    static_cast<TrackWidget*>( listWidget()->itemWidget( this ) )->setTrack( track );\n}\n\nbool\nScrobblesListWidgetItem::operator<( const QListWidgetItem& that ) const\n{\n    if ( !qobject_cast<TrackWidget*>(listWidget()->itemWidget( const_cast<ScrobblesListWidgetItem*>(this) )) )\n    {\n        // this isn't a track widget\n\n        if ( qobject_cast<RefreshButton*>(listWidget()->itemWidget( const_cast<ScrobblesListWidgetItem*>(this) )) )\n            return true; // this is a refresh button\n        else\n            return false; // more button goes at the bottom\n    }\n\n    if ( qobject_cast<RefreshButton*>(listWidget()->itemWidget( const_cast<QListWidgetItem*>(&that) )) )\n        return false; // that is a refresh button so this is not less than. refresh button goes at the top\n\n    if ( !qobject_cast<TrackWidget*>(listWidget()->itemWidget( const_cast<QListWidgetItem*>(&that) )) )\n        return true; // that is the more push button. everything else is less than it\n\n    // at this point both this and that are of type TrackWidget\n\n    // check if it's the now playing track\n    if ( m_nowPlaying )\n        return true; // now playing goes at the top of the tracks\n    else if ( static_cast<const ScrobblesListWidgetItem*>(&that)->m_nowPlaying )\n        return false;\n\n    // now order by timestamp\n    return static_cast<TrackWidget*>( listWidget()->itemWidget( const_cast<ScrobblesListWidgetItem*>( this ) ) )->track().timestamp().toTime_t()\n            > static_cast<TrackWidget*>( listWidget()->itemWidget( const_cast<QListWidgetItem*>( &that ) ) )->track().timestamp().toTime_t();\n}\n\nScrobblesListWidget::ScrobblesListWidget( QWidget* parent )\n    :QListWidget( parent ), m_trackItem( 0 )\n{\n    setVerticalScrollMode( QAbstractItemView::ScrollPerPixel );\n\n#ifdef Q_OS_MAC\n    connect( verticalScrollBar(), SIGNAL(valueChanged(int)), SLOT(scroll()) );\n#endif\n\n    setAttribute( Qt::WA_MacNoClickThrough );\n    setAttribute( Qt::WA_MacShowFocusRect, false );\n\n    setUniformItemSizes( false );\n    setSortingEnabled( false );\n    setSelectionMode( QAbstractItemView::NoSelection );\n    setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );\n\n    connect( qApp, SIGNAL( sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)));\n\n    connect( &ScrobbleService::instance(), SIGNAL(scrobblesCached(QList<lastfm::Track>)), SLOT(onScrobblesSubmitted(QList<lastfm::Track>) ) );\n    connect( &ScrobbleService::instance(), SIGNAL(scrobblesSubmitted(QList<lastfm::Track>)), SLOT(onScrobblesSubmitted(QList<lastfm::Track>) ) );\n\n    connect( &ScrobbleService::instance(), SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(onTrackStarted(lastfm::Track,lastfm::Track)));\n    connect( &ScrobbleService::instance(), SIGNAL(paused()), SLOT(onPaused()));\n    connect( &ScrobbleService::instance(), SIGNAL(resumed()), SLOT(onResumed()));\n    connect( &ScrobbleService::instance(), SIGNAL(stopped()), SLOT(onStopped()));\n\n    onSessionChanged( aApp->currentSession() );\n}\n\n#ifdef Q_OS_MAC\nvoid\nScrobblesListWidget::scroll()\n{\n    // KLUDGE: The friend list widgets don't move unless we do this\n    sortItems( Qt::AscendingOrder );\n}\n#endif\n\nvoid\nScrobblesListWidget::showEvent(QShowEvent *)\n{\n    QList<lastfm::Track> tracks;\n\n    for ( int i = 0 ; i < count() ; ++i )\n    {\n        TrackWidget* trackWidget = qobject_cast<TrackWidget*>( itemWidget( item( i ) ) );\n\n        if ( trackWidget && !item( i )->isHidden() )\n            tracks << trackWidget->track();\n    }\n\n    fetchTrackInfo( tracks );\n}\n\nvoid\nScrobblesListWidget::fetchTrackInfo( const QList<lastfm::Track>& tracks )\n{\n    if ( isVisible() )\n    {\n        // Make sure we fetch info for any tracks with unknown loved status\n        foreach ( const lastfm::Track& track, tracks )\n            if ( track.loveStatus() == lastfm::Track::UnknownLoveStatus )\n                track.getInfo(  this, \"write\", User().name() );\n    }\n}\n\nvoid\nScrobblesListWidget::mousePressEvent( QMouseEvent* event )\n{\n    event->setAccepted( false );\n}\n\nvoid\nScrobblesListWidget::mouseReleaseEvent( QMouseEvent* event )\n{\n    event->setAccepted( false );\n}\n\nvoid \nScrobblesListWidget::onItemClicked( TrackWidget& trackWidget )\n{\n    emit trackClicked( trackWidget );\n}\n\nvoid\nScrobblesListWidget::onMoreClicked()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"user\" ).slash( User().name() ).slash( \"tracks\" ).url() );\n}\n\nvoid\nScrobblesListWidget::onSessionChanged( const unicorn::Session& session )\n{\n    if ( !session.user().name().isEmpty() )\n    {\n        QString path = lastfm::dir::runtimeData().filePath( session.user().name() + \"_recent_tracks.xml\" );\n\n        if ( m_path != path )\n        {\n            m_path = path;\n            read();\n            refresh();\n        }\n    }\n}\n\n\nvoid\nScrobblesListWidget::read()\n{\n    clear();\n\n    // always have a now playing item in the list\n    m_trackItem = new ScrobblesListWidgetItem( this );\n    TrackWidget* trackWidget = new TrackWidget( m_track, this );\n    trackWidget->setObjectName( \"nowPlaying\" );\n    setItemWidget( m_trackItem, trackWidget );\n    m_trackItem->setSizeHint( trackWidget->sizeHint() );\n    m_trackItem->setHidden( true );\n    m_trackItem->setNowPlaying( true );\n\n    connect( trackWidget, SIGNAL(clicked(TrackWidget&)), SLOT(onItemClicked(TrackWidget&)) );\n\n    // always have the refresh button in the list\n    m_refreshItem = new ScrobblesListWidgetItem( this );\n    RefreshButton* refreshButton = new RefreshButton( this );\n    refreshButton->setObjectName( \"refresh\" );\n    setItemWidget( m_refreshItem, refreshButton );\n    m_refreshItem->setSizeHint( refreshButton->sizeHint() );\n\n    connect( refreshButton, SIGNAL(clicked()), SLOT(refresh()) );\n\n    onRefreshing( false );\n\n    // always have a view more item in the list\n    m_moreItem = new ScrobblesListWidgetItem( this );\n    QPushButton* moreButton = new QPushButton( tr( \"More Scrobbles at Last.fm\" ), this );\n    moreButton->setObjectName( \"more\" );\n    setItemWidget( m_moreItem, moreButton );\n    m_moreItem->setSizeHint( moreButton->sizeHint() );\n\n    connect( moreButton, SIGNAL(clicked()), SLOT(onMoreClicked()) );\n\n    QFile file( m_path );\n    file.open( QFile::Text | QFile::ReadOnly );\n    QTextStream stream( &file );\n    stream.setCodec( \"UTF-8\" );\n\n    QDomDocument xml;\n    xml.setContent( stream.readAll() );\n\n    QList<Track> tracks;\n\n    for (QDomNode n = xml.documentElement().lastChild(); !n.isNull(); n = n.previousSibling())\n        tracks << Track( n.toElement() );\n\n    addTracks( tracks );\n    fetchTrackInfo( tracks );\n\n    limit( kScrobbleLimit );\n}\n\nvoid\nScrobblesListWidget::write()\n{\n    if ( !m_writeTimer )\n    {\n        m_writeTimer = new QTimer( this );\n        connect( m_writeTimer, SIGNAL(timeout()), this, SLOT(doWrite()) );\n        m_writeTimer->setSingleShot( true );\n    }\n\n    m_writeTimer->start( 500 );\n}\n\nvoid\nScrobblesListWidget::doWrite()\n{\n    if ( count() == 0 )\n        QFile::remove( m_path );\n    else\n    {\n        QDomDocument xml;\n        QDomElement e = xml.createElement( \"recent_tracks\" );\n        e.setAttribute( \"product\", QCoreApplication::applicationName() );\n        e.setAttribute( \"version\", \"2\" );\n\n        for ( int i = 0 ; i < count() ; ++i )\n        {\n            TrackWidget* trackWidget = qobject_cast<TrackWidget*>( itemWidget( item( i ) ) );\n\n            if ( trackWidget && !static_cast<ScrobblesListWidgetItem*>( item( i ) )->isNowPlaying() )\n                e.appendChild( static_cast<TrackWidget*>( itemWidget( item( i ) ) )->track().toDomElement( xml ) );\n        }\n\n        xml.appendChild( e );\n\n        QFile file( m_path );\n        file.open( QIODevice::WriteOnly | QIODevice::Text );\n\n        QTextStream stream( &file );\n        stream.setCodec( \"UTF-8\" );\n        stream << \"<?xml version='1.0' encoding='utf-8'?>\\n\";\n        stream << xml.toString( 2 );\n    }\n}\n\nvoid\nScrobblesListWidget::onTrackStarted( const Track& track, const Track& )\n{\n    // Don't display Spotify here as we don't know if the current user is the one scrobbling\n    // If it is the current user it will be fetch by user.getRecentTracks\n    if ( track.extra( \"playerId\" ) != \"spt\" )\n    {\n        m_track = track;\n        m_trackItem->setTrack( m_track );\n        m_trackItem->setHidden( false );\n\n        connect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), SLOT(write()));\n\n        QList<lastfm::Track> tracks;\n        tracks << track;\n        fetchTrackInfo( tracks );\n    }\n\n    hideScrobbledNowPlaying();\n}\n\nvoid\nScrobblesListWidget::onResumed()\n{\n    m_trackItem->setHidden( false );\n\n    hideScrobbledNowPlaying();\n}\n\nvoid\nScrobblesListWidget::onPaused()\n{\n    m_trackItem->setHidden( true );\n\n    hideScrobbledNowPlaying();\n}\n\nvoid\nScrobblesListWidget::onStopped()\n{\n    m_trackItem->setHidden( true );\n\n    hideScrobbledNowPlaying();\n}\n\nvoid\nScrobblesListWidget::hideScrobbledNowPlaying()\n{\n    for ( int i = 0 ; i < count() ; ++i )\n    {\n        if ( item( i ) != m_trackItem )\n        {\n            TrackWidget* trackWidget = qobject_cast<TrackWidget*>( itemWidget( item( i ) ) );\n\n            item( i )->setHidden( trackWidget\n                                    && !m_trackItem->isHidden()\n                                    && ( trackWidget->track().timestamp().toTime_t() == m_track.timestamp().toTime_t()\n                                    || trackWidget->track().timestamp().toTime_t() == ScrobbleService::instance().currentTrack().timestamp().toTime_t() ) );\n        }\n    }\n}\n\nvoid\nScrobblesListWidget::refresh()\n{\n    if ( !m_recentTrackReply )\n    {\n        m_recentTrackReply = User().getRecentTracks( kScrobbleLimit, 1 );\n        connect( m_recentTrackReply, SIGNAL(finished()), SLOT(onGotRecentTracks()) );\n        onRefreshing( true );\n    }\n}\n\n\nvoid\nScrobblesListWidget::onRefreshing( bool refreshing )\n{\n    RefreshButton* refreshButton = qobject_cast<RefreshButton*>( itemWidget( m_refreshItem ) );\n\n    refreshButton->setText( refreshing ? tr( \"Refreshing...\" ) : tr( \"Refresh Scrobbles\" ) );\n    refreshButton->setEnabled( !refreshing );\n}\n\nvoid\nScrobblesListWidget::onGotRecentTracks()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        m_trackItem->setHidden( true );\n\n        QList<lastfm::Track> tracks;\n        lastfm::MutableTrack nowPlayingTrack;\n\n        bool checkedFirstScrobble( false );\n\n        foreach ( const XmlQuery& trackXml, lfm[\"recenttracks\"].children(\"track\") )\n        {\n            if ( trackXml.attribute( \"nowplaying\" ) == \"true\" )\n            {\n                nowPlayingTrack.setTitle( trackXml[\"name\"].text() );\n                nowPlayingTrack.setArtist( trackXml[\"artist\"][\"name\"].text() );\n                nowPlayingTrack.setAlbum( trackXml[\"album\"].text() );\n\n                if ( nowPlayingTrack != m_track )\n                {\n                    // This is a different track so change to it\n                    nowPlayingTrack.setTimeStamp( QDateTime::fromTime_t( trackXml[\"date\"].attribute(\"uts\").toUInt() ) );\n\n                    nowPlayingTrack.setImageUrl( Track::SmallImage, trackXml[\"image size=small\"].text() );\n                    nowPlayingTrack.setImageUrl( Track::MediumImage, trackXml[\"image size=medium\"].text() );\n                    nowPlayingTrack.setImageUrl( Track::LargeImage, trackXml[\"image size=large\"].text() );\n                    nowPlayingTrack.setImageUrl( Track::ExtraLargeImage, trackXml[\"image size=extralarge\"].text() );\n\n                    m_track = nowPlayingTrack;\n                    m_trackItem->setTrack( m_track );\n\n                    connect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), SLOT(write()));\n\n                    QString loved = trackXml[\"loved\"].text();\n\n                    if ( !loved.isEmpty() )\n                        nowPlayingTrack.setLoved( loved == \"1\" );\n                    else\n                        m_track.getInfo( this, \"write\", User().name() );\n                }\n\n                m_trackItem->setHidden( false );\n            }\n            else\n            {\n                MutableTrack track;\n                track.setTitle( trackXml[\"name\"].text() );\n                track.setArtist( trackXml[\"artist\"][\"name\"].text() );\n                track.setAlbum( trackXml[\"album\"].text() );\n\n                track.setTimeStamp( QDateTime::fromTime_t( trackXml[\"date\"].attribute(\"uts\").toUInt() ) );\n\n                if ( checkedFirstScrobble ||\n                      (!checkedFirstScrobble && ( track != nowPlayingTrack || (track == nowPlayingTrack && track.timestamp().secsTo( QDateTime::currentDateTime() ) > 10 * 60 ) ) ) )\n                {\n                    track.setImageUrl( Track::SmallImage, trackXml[\"image size=small\"].text() );\n                    track.setImageUrl( Track::MediumImage, trackXml[\"image size=medium\"].text() );\n                    track.setImageUrl( Track::LargeImage, trackXml[\"image size=large\"].text() );\n                    track.setImageUrl( Track::ExtraLargeImage, trackXml[\"image size=extralarge\"].text() );\n\n                    QString loved = trackXml[\"loved\"].text();\n\n                    if ( !loved.isEmpty() )\n                        track.setLoved( loved == \"1\" );\n\n                    tracks << track;\n                }\n\n                checkedFirstScrobble = true;\n            }\n        }\n\n        QList<lastfm::Track> addedTracks = addTracks( tracks );\n\n        // get info for track if we don't know the loved state. This is so it will\n        // work before and after the loved field is added to user.getRecentTracks\n        fetchTrackInfo( addedTracks );\n\n        write();\n    }\n\n    onRefreshing( false );\n\n    m_recentTrackReply->deleteLater();\n\n    hideScrobbledNowPlaying();\n}\n\n\nvoid\nScrobblesListWidget::onScrobblesSubmitted( const QList<lastfm::Track>& tracks )\n{\n    // We need to find out if info has already been fetched for this track or not.\n    // If the now playing view wasn't visible it won't have been.\n    // Also, should also only fetch if the scrobbles list is visible too\n\n    QList<lastfm::Track> addedTracks = addTracks( tracks );\n\n    fetchTrackInfo( addedTracks );\n}\n\nvoid\nScrobblesListWidget::onTrackWidgetRemoved()\n{\n    for ( int i = 0 ; i < count() ; ++i )\n    {\n        if ( itemWidget( item( i ) ) == sender() )\n        {\n            itemWidget( takeItem( i ) )->deleteLater();\n            refresh();\n            break;\n        }\n    }\n}\n\nQList<lastfm::Track>\nScrobblesListWidget::addTracks( const QList<lastfm::Track>& tracks )\n{\n    QList<lastfm::Track> addedTracks;\n\n    for ( int i = 0 ; i < tracks.count() ; ++i )\n    {\n        if ( tracks[i].scrobbleError() != Track::Invalid  )\n        {\n            // the track was not filtered client side for being invalid\n            int pos = -1;\n\n            for ( int j = 0 ; j < count() ; ++j )\n            {\n                TrackWidget* trackWidget = qobject_cast<TrackWidget*>( itemWidget( item( j ) ) );\n\n                if ( trackWidget\n                     && !static_cast<ScrobblesListWidgetItem*>( item( j ) )->isNowPlaying()\n                     && tracks[i].timestamp().toTime_t() == trackWidget->track().timestamp().toTime_t() )\n                {\n                    pos = j;\n                    break;\n                }\n            }\n\n            if ( pos == -1 )\n            {\n                // the track was not in the list\n                ScrobblesListWidgetItem* item = new ScrobblesListWidgetItem( this );\n                Track track = tracks[i];\n                TrackWidget* trackWidget = new TrackWidget( track, this );\n                setItemWidget( item, trackWidget );\n                item->setSizeHint( trackWidget->sizeHint() );\n\n                connect( trackWidget, SIGNAL(removed()), SLOT(onTrackWidgetRemoved()));\n                connect( trackWidget, SIGNAL(clicked(TrackWidget&)), SLOT(onItemClicked(TrackWidget&)) );\n\n                connect( track.signalProxy(), SIGNAL(loveToggled(bool)), SLOT(write()));\n                connect( track.signalProxy(), SIGNAL(scrobbleStatusChanged(short)), SLOT(write()));\n            }\n            else\n            {\n                // update the track in the list with the new infos!\n                TrackWidget* trackWidget = qobject_cast<TrackWidget*>( itemWidget( item( pos ) ) );\n                trackWidget->update( tracks[i] );\n            }\n        }\n    }\n\n    limit( kScrobbleLimit );\n\n    write();\n\n    hideScrobbledNowPlaying();\n\n    return addedTracks;\n}\n\n\nvoid\nScrobblesListWidget::limit( int limit )\n{\n    sortItems();\n\n    // we add three to the limit here to account for the refresh button,\n    // the now playing track (usually hidden), and the more button\n    if ( count() > limit + 3 )\n    {\n        while ( count() > limit + 3 )\n        {\n            QListWidgetItem* item = takeItem( count() - 2 );\n            itemWidget( item )->deleteLater();\n            delete item;\n        }\n\n        write();\n    }\n}\n\n"
  },
  {
    "path": "app/client/Widgets/ScrobblesListWidget.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SCROBBLES_LIST_WIDGET_H\n#define SCROBBLES_LIST_WIDGET_H\n\n#include <QListWidget>\n#include <QMouseEvent>\n#include <QPoint>\n#include <QPointer>\n\n#include <lastfm/Track.h>\n\nnamespace lastfm { class Track; }\nusing lastfm::Track;\n\nnamespace unicorn { class Session; }\n\nclass QNetworkReply;\n\nclass ScrobblesListWidget : public QListWidget\n{\n    Q_OBJECT\npublic:\n    ScrobblesListWidget( QWidget* parent = 0 );\n\nsignals:\n    void trackClicked( class TrackWidget& );\n\npublic slots:\n    void refresh();\n\nprivate slots: \n    void onItemClicked( class TrackWidget& index );\n    void onMoreClicked();\n\n    void onTrackStarted( const lastfm::Track& track, const lastfm::Track& );\n\n    void onSessionChanged( const unicorn::Session& session );\n\n    void onResumed();\n    void onPaused();\n    void onStopped();\n\n    void onGotRecentTracks();\n\n    void onScrobblesSubmitted( const QList<lastfm::Track>& tracks );\n\n    void onTrackWidgetRemoved();\n\n    void write();\n    void doWrite();\n\n#ifdef Q_OS_MAC\n    void scroll();\n#endif\n\nprivate:\n    QString price( const QString& price, const QString& currency ) const;\n\n    void read();\n\n    QList<lastfm::Track> addTracks( const QList<lastfm::Track>& tracks );\n    void limit( int limit );\n\n    void hideScrobbledNowPlaying();\n\n    void showEvent(QShowEvent *);\n\n    void fetchTrackInfo( const QList<lastfm::Track>& tracks );\n\n    void mousePressEvent( QMouseEvent* event );\n    void mouseReleaseEvent( QMouseEvent* event );\n\n    void onRefreshing( bool refreshing );\n\nprivate:\n    QString m_path;\n\n    QPointer<QTimer> m_writeTimer;\n    QPointer<QNetworkReply> m_recentTrackReply;\n\n    lastfm::Track m_track;\n    class ScrobblesListWidgetItem* m_refreshItem;\n    class ScrobblesListWidgetItem* m_trackItem;\n    class ScrobblesListWidgetItem* m_moreItem;\n};\n\n\n#endif //ACTIVITY_LIST_WIDGET_H\n\n"
  },
  {
    "path": "app/client/Widgets/ScrobblesWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QWidget>\n#include <QLayoutItem>\n#include <QDebug>\n\n#include <lastfm/Track.h>\n\n#include \"../Services/AnalyticsService/AnalyticsService.h\"\n#include \"ScrobblesListWidget.h\"\n#include \"TrackWidget.h\"\n#include \"MetadataWidget.h\"\n#include \"ScrobblesWidget.h\"\n#include \"ui_ScrobblesWidget.h\"\n\nScrobblesWidget::ScrobblesWidget( QWidget* parent )\n    :QWidget( parent ), ui( new Ui::ScrobblesWidget ), m_lastIndex( 0 )\n{\n    ui->setupUi( this );\n\n    connect( ui->scrobbles, SIGNAL( trackClicked(TrackWidget&)), SLOT( onTrackClicked(TrackWidget&)));\n    connect( ui->slidingWidget, SIGNAL( animationFinished()), SLOT(onMoveFinished()));\n\n    ui->stackedWidget->setCurrentWidget( ui->scrobbles );\n}\n\nScrobblesWidget::~ScrobblesWidget()\n{\n    delete ui;\n}\n\nvoid\nScrobblesWidget::refresh()\n{\n    ui->scrobbles->refresh();\n}\n\nvoid\nScrobblesWidget::onCurrentChanged( int index )\n{\n    if ( index == 1 && (m_lastIndex != index || ui->slidingWidget->currentWidget() != ui->stackedWidget ) )\n    {\n        // We've switch to this tab OR are moving back from Scrobble to ScrobbleList\n        ui->scrobbles->refresh();\n        AnalyticsService::instance().sendPageView( \"Scrobbles\" );\n    }\n\n    m_lastIndex = index;\n\n    ui->slidingWidget->slide( ui->slidingWidget->indexOf( ui->stackedWidget ) );\n}\n\nvoid\nScrobblesWidget::onTrackClicked( TrackWidget& trackWidget )\n{\n    MetadataWidget* w;\n    ui->slidingWidget->addWidget( w = new MetadataWidget( trackWidget.track() ));\n    w->fetchTrackInfo( true );\n    w->setBackButtonVisible( true );\n\n    trackWidget.startSpinner();\n    connect( ui->slidingWidget, SIGNAL( animationFinished()), &trackWidget, SLOT(clearSpinner()) );\n\n    connect( w, SIGNAL(finished()), SLOT(onMetadataWidgetFinished()));\n    connect( w, SIGNAL(backClicked()), SLOT(onBackClicked()));\n}\n\nvoid\nScrobblesWidget::onMetadataWidgetFinished()\n{\n    ui->slidingWidget->slide( ui->slidingWidget->currentIndex() + 1 );\n    AnalyticsService::instance().sendPageView( \"Scrobbles/Scrobble\" );\n}\n\nvoid\nScrobblesWidget::onBackClicked()\n{\n    ui->slidingWidget->slide( ui->slidingWidget->indexOf( ui->stackedWidget ) );\n    AnalyticsService::instance().sendPageView( \"Scrobbles\" );\n}\n\nvoid\nScrobblesWidget::onMoveFinished()\n{\n    if( ui->slidingWidget->currentWidget() == ui->stackedWidget )\n    {\n        while ( ui->slidingWidget->count() > 1 )\n        {\n            QWidget* widget = ui->slidingWidget->widget( 1 );\n            ui->slidingWidget->removeWidget( widget );\n            delete widget;\n        }\n    }\n}\n"
  },
  {
    "path": "app/client/Widgets/ScrobblesWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef RECENT_TRACKS_WIDGET_H_\n#define RECENT_TRACKS_WIDGET_H_\n\n#include <QWidget>\n\nnamespace lastfm { class Track; }\nusing lastfm::Track;\n\nnamespace Ui { class ScrobblesWidget; }\n\nclass ScrobblesWidget : public QWidget\n{\nQ_OBJECT\npublic:\n    explicit ScrobblesWidget( QWidget* parent = 0 );\n    ~ScrobblesWidget();\n\npublic slots:\n    void onCurrentChanged( int index );\n    void refresh();\n\nprotected slots:\n    void onTrackClicked( class TrackWidget& trackWidget );\n    void onBackClicked();\n    void onMoveFinished();\n    void onMetadataWidgetFinished();\n\nprotected:\n    Ui::ScrobblesWidget* ui;\n    int m_lastIndex;\n};\n\n#endif //RECENT_TRACKS_WIDGET_H_\n"
  },
  {
    "path": "app/client/Widgets/ScrobblesWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ScrobblesWidget</class>\n <widget class=\"QWidget\" name=\"ScrobblesWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>429</width>\n    <height>519</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n   <property name=\"leftMargin\">\n    <number>0</number>\n   </property>\n   <property name=\"topMargin\">\n    <number>0</number>\n   </property>\n   <property name=\"rightMargin\">\n    <number>0</number>\n   </property>\n   <property name=\"bottomMargin\">\n    <number>12</number>\n   </property>\n   <item>\n    <widget class=\"unicorn::SlidingStackedWidget\" name=\"slidingWidget\">\n      <widget class=\"QStackedWidget\" name=\"stackedWidget\">\n       <property name=\"geometry\">\n        <rect>\n         <x>0</x>\n         <y>60</y>\n         <width>405</width>\n         <height>242</height>\n        </rect>\n       </property>\n       <widget class=\"QWidget\" name=\"spinnerPage\">\n        <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n         <item>\n          <widget class=\"QLabel\" name=\"spinner\">\n           <property name=\"text\">\n            <string notr=\"true\">TextLabel</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignCenter</set>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n       <widget class=\"QWidget\" name=\"noScrobbles\">\n        <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n         <property name=\"spacing\">\n          <number>12</number>\n         </property>\n         <property name=\"margin\">\n          <number>20</number>\n         </property>\n         <item>\n          <widget class=\"QLabel\" name=\"title\">\n           <property name=\"text\">\n            <string>You haven't scrobbled any music to Last.fm yet.</string>\n           </property>\n           <property name=\"wordWrap\">\n            <bool>true</bool>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QLabel\" name=\"description\">\n           <property name=\"text\">\n            <string>Start listening to some music in your media player:</string>\n           </property>\n           <property name=\"wordWrap\">\n            <bool>true</bool>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <spacer name=\"verticalSpacer\">\n           <property name=\"orientation\">\n            <enum>Qt::Vertical</enum>\n           </property>\n           <property name=\"sizeHint\" stdset=\"0\">\n            <size>\n             <width>20</width>\n             <height>40</height>\n            </size>\n           </property>\n          </spacer>\n         </item>\n        </layout>\n       </widget>\n       <widget class=\"ScrobblesListWidget\" name=\"scrobbles\"/>\n      </widget>\n      </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>ScrobblesListWidget</class>\n   <extends>QWidget</extends>\n   <header>../Widgets/ScrobblesListWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>unicorn::SlidingStackedWidget</class>\n   <extends>QStackedWidget</extends>\n   <header>lib/unicorn/widgets/SlidingStackedWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/ShortcutEdit.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringListModel>\n#include <QLineEdit>\n#include <QKeyEvent>\n\n#include \"ShortcutEdit.h\"\n\nShortcutEdit::ShortcutEdit( QWidget* parent )\n    :QComboBox( parent )\n{\n    setEditable( true );\n    QStringList keys;\n#ifdef Q_OS_MAC\n    keys << QString::fromUtf8(\"⌃⌘ S\")\n#else\n    keys << QString::fromUtf8(\"Ctrl+Shift+S\")\n#endif\n         << \"F1\"\n         << \"F3\"\n         << \"F2\"\n         << \"F4\"\n         << \"F5\"\n         << \"F6\"\n         << \"F7\"\n         << \"F8\"\n         << \"F9\";\n    QStringListModel* model = new QStringListModel(keys, this);\n    setModel(model);\n}\n\nvoid\nShortcutEdit::setTextValue( QString str )\n{\n    setCurrentIndex( findText(str));\n    lineEdit()->setText( str );\n}\n\nQt::KeyboardModifiers\nShortcutEdit::modifiers() const\n{\n    return m_modifiers;\n}\n\nvoid\nShortcutEdit::setModifiers( Qt::KeyboardModifiers modifiers )\n{\n    m_modifiers = modifiers;\n}\n\n\nint\nShortcutEdit::key() const\n{\n    return m_key;\n}\n\nvoid\nShortcutEdit::setKey( int key )\n{\n    m_key = key;\n}\n\nvoid\nShortcutEdit::keyPressEvent( QKeyEvent* e )\n{\n    QString text;\n\n    Qt::KeyboardModifiers modifiers;\n\n    //Modifier to symbol\n    if( e->modifiers() & Qt::ControlModifier )\n    {\n#ifdef Q_OS_MAC\n        text += QString::fromUtf8( \"⌘\" );\n#else\n        text += \"Ctrl+\";\n#endif\n        modifiers |= Qt::ControlModifier;\n    }\n    if( e->modifiers() & Qt::AltModifier )\n    {\n#ifdef Q_OS_MAC\n        text += QString::fromUtf8( \"⌥\" );\n#else\n        text += \"Alt+\";\n#endif\n        modifiers |= Qt::AltModifier;\n    }\n    if( e->modifiers() & Qt::ShiftModifier )\n    {\n#ifdef Q_OS_MAC\n        text += QString::fromUtf8( \"⇧\" );\n#else\n        text += \"Shift+\";\n#endif\n        modifiers |= Qt::ShiftModifier;\n    }\n    if( e->modifiers() & Qt::MetaModifier )\n    {\n#ifdef Q_OS_MAC\n        text += QString::fromUtf8( \"⌃\" );\n#else\n        text += \"Win+\";\n#endif\n        modifiers |= Qt::MetaModifier;\n    }\n\n    //Backspace key to clear shortcut\n    if( !e->modifiers() && e->key() == Qt::Key_Backspace)\n    {\n        lineEdit()->clear();\n        m_modifiers = 0;\n        m_key = 0;\n        return;\n    }\n\n    //Don't allow shortcuts with no modifier unless they're F keys\n    if( !e->modifiers() && !( e->key() >= 0x01000030 && e->key() <= 0x01000052 ))\n        return;\n\n    //Don't allow pure modifier shortcuts\n    switch(e->key())\n    {\n        case Qt::Key_Control:\n        case Qt::Key_Alt:\n        case Qt::Key_Meta:\n        case Qt::Key_Shift:\n            return;\n    }\n\n    //Literal Space to Space text\n    if( e->key() == Qt::Key_Space)\n        text += \" Space\" ;\n    else if( e->key() == Qt::Key_Escape )\n        text += QString::fromUtf8(\" ⎋\");\n    else if( e->key() == Qt::Key_Backspace )\n        text += QString::fromUtf8(\" ⌫\");\n    else if( e->key() >= 0x01000030 && e->key() <= 0x01000052 )\n        text += QString( \" F%1\" ).arg(((int)e->key() - 0x0100002F) );\n    else\n        text = text + \" \" + e->key();\n\n    m_key = e->nativeVirtualKey();\n    m_modifiers = e->modifiers();\n\n    setCurrentIndex( findText( text, Qt::MatchFixedString ) );\n    lineEdit()->setText( text );\n}\n\nQString\nShortcutEdit::textValue() const\n{\n    return lineEdit()->text();\n}\n\n"
  },
  {
    "path": "app/client/Widgets/ShortcutEdit.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SHORTCUTEDIT_H\n#define SHORTCUTEDIT_H\n\n#include <QComboBox>\n\nclass ShortcutEdit : public QComboBox\n{\n    Q_OBJECT\n\npublic:\n    ShortcutEdit( QWidget* parent = 0 );\n\n    void setTextValue( QString str );\n    void keyPressEvent( QKeyEvent* e );\n    QString textValue() const;\n\n    Qt::KeyboardModifiers modifiers() const;\n    void setModifiers( Qt::KeyboardModifiers modifiers );\n    int key() const;\n    void setKey( int key );\n\nprivate:\n    Qt::KeyboardModifiers m_modifiers;\n    int m_key;\n};\n\n#endif // SHORTCUTEDIT_H\n"
  },
  {
    "path": "app/client/Widgets/SideBar.cpp",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QButtonGroup>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QLabel>\n#include <QShortcut>\n#include <QMenu>\n\n#include <lastfm/User.h>\n\n#include \"lib/unicorn/widgets/AvatarWidget.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"../Application.h\"\n#include \"SideBar.h\"\n\nQAbstractButton* newButton( const QString& text, QButtonGroup* buttonGroup, QWidget* parent = 0 )\n{\n    QAbstractButton* pushButton = new QPushButton( parent );\n    pushButton->setText( text );\n    pushButton->setCheckable( true );\n    pushButton->setAutoExclusive( true );\n    pushButton->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );\n    pushButton->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    pushButton->setAttribute( Qt::WA_MacNoClickThrough );\n    buttonGroup->addButton( pushButton );\n    return pushButton;\n}\n\n\nSideBar::SideBar(QWidget *parent)\n    :QFrame(parent), m_lastButton( 0 )\n{\n    QVBoxLayout* layout = new QVBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 0 );\n\n    m_buttonGroup = new QButtonGroup( this );\n    m_buttonGroup->setExclusive( true );\n\n    layout->addWidget( ui.nowPlaying = newButton( tr( \"Now Playing\" ), m_buttonGroup, this ), Qt::AlignHCenter );\n    ui.nowPlaying->setObjectName( \"nowPlaying\" );\n    layout->addWidget( ui.scrobbles = newButton( tr( \"Scrobbles\" ), m_buttonGroup, this ), Qt::AlignHCenter);\n    ui.scrobbles->setObjectName( \"scrobbles\" ); \n    layout->addWidget( ui.profile = newButton( tr( \"Profile\" ), m_buttonGroup, this ), Qt::AlignHCenter);\n    ui.profile->setObjectName( \"profile\" );\n    layout->addWidget( ui.friends = newButton( tr( \"Friends\" ), m_buttonGroup, this ), Qt::AlignHCenter);\n    ui.friends->setObjectName( \"friends\" );\n    layout->addWidget( ui.radio = newButton( tr( \"Radio\" ), m_buttonGroup, this ), Qt::AlignHCenter);\n    ui.radio->setObjectName( \"radio\" );\n    layout->addStretch( 1 );\n\n    connect( m_buttonGroup, SIGNAL(buttonClicked(QAbstractButton*)), SLOT(onButtonClicked(QAbstractButton*)));\n\n    ui.nowPlaying->click();\n\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n\n    onSessionChanged( aApp->currentSession() );\n}\n\nvoid\nSideBar::onSessionChanged( const unicorn::Session& session )\n{\n    if ( session.isValid() )\n    {\n        ui.radio->setVisible( session.subscriberRadio() );\n\n        if ( m_radioAction )\n            m_radioAction->setVisible( session.subscriberRadio() );\n\n        if ( !session.subscriberRadio() && m_buttonGroup->checkedButton() == ui.radio )\n            ui.nowPlaying->click();\n    }\n}\n\nQString\nSideBar::currentCategory() const\n{\n    if ( m_buttonGroup->checkedButton() == ui.nowPlaying ) return NOW_PLAYING_CATEGORY;\n    else if ( m_buttonGroup->checkedButton() == ui.scrobbles ) return SCROBBLES_CATEGORY;\n    else if ( m_buttonGroup->checkedButton() == ui.profile ) return PROFILE_CATEGORY;\n    else if ( m_buttonGroup->checkedButton() == ui.friends ) return FRIENDS_CATEGORY;\n    else if ( m_buttonGroup->checkedButton() == ui.radio ) return RADIO_CATEGORY;\n    return \"Unknown\";\n}\n\nvoid\nSideBar::addToMenu( QMenu& menu )\n{\n    menu.addAction( ui.nowPlaying->text(), ui.nowPlaying, SLOT(click()), Qt::CTRL + Qt::Key_1);\n    menu.addAction( ui.scrobbles->text(), ui.scrobbles, SLOT(click()), Qt::CTRL + Qt::Key_2);\n    menu.addAction( ui.profile->text(), ui.profile, SLOT(click()), Qt::CTRL + Qt::Key_3);\n    menu.addAction( ui.friends->text(), ui.friends, SLOT(click()), Qt::CTRL + Qt::Key_4);\n    m_radioAction = menu.addAction( ui.radio->text(), ui.radio, SLOT(click()), Qt::CTRL + Qt::Key_5);\n    m_radioAction->setVisible( !aApp->currentSession().isValid() || aApp->currentSession().subscriberRadio() );\n\n    menu.addSeparator();\n\n    menu.addAction( tr(\"Next Section\"), this, SLOT(onDown()), Qt::CTRL + Qt::Key_BracketRight);\n    menu.addAction( tr(\"Previous Section\"), this, SLOT(onUp()), Qt::CTRL + Qt::Key_BracketLeft);\n}\n\nvoid\nSideBar::onUp()\n{\n    if ( ui.nowPlaying->isChecked() )\n    {\n        if ( !aApp->currentSession().isValid() || aApp->currentSession().subscriberRadio() )\n            ui.radio->click();\n        else\n            ui.friends->click();\n    }\n    else if ( ui.scrobbles->isChecked() ) ui.nowPlaying->click();\n    else if ( ui.profile->isChecked() ) ui.scrobbles->click();\n    else if ( ui.friends->isChecked() ) ui.profile->click();\n    else if ( ui.radio->isChecked() ) ui.friends->click();\n}\n\nvoid\nSideBar::onDown()\n{\n    if ( ui.nowPlaying->isChecked() ) ui.scrobbles->click();\n    else if ( ui.scrobbles->isChecked() ) ui.profile->click();\n    else if ( ui.profile->isChecked() ) ui.friends->click();\n    else if ( ui.friends->isChecked() )\n    {\n        if ( !aApp->currentSession().isValid() || aApp->currentSession().subscriberRadio() )\n            ui.radio->click();\n        else\n             ui.nowPlaying->click();\n    }\n    else if ( ui.radio->isChecked() ) ui.nowPlaying->click();\n}\n\nvoid\nSideBar::click( int index )\n{\n    qobject_cast<QAbstractButton*>( layout()->itemAt( index )->widget() )->click();\n}\n\n\nvoid\nSideBar::onButtonClicked( QAbstractButton* button )\n{\n    int index = layout()->indexOf( button );\n\n    if ( button != m_lastButton )\n    {\n        if ( button == ui.nowPlaying ) AnalyticsService::instance().sendPageView( NOW_PLAYING_CATEGORY );\n        // the scrobble tab is a bit more complicataed so it sends its own for now\n        //else if ( button == ui.scrobbles ) AnalyticsService::instance().sendPageView( SCROBBLES_CATEGORY );\n        else if ( button == ui.profile ) AnalyticsService::instance().sendPageView( PROFILE_CATEGORY );\n        else if ( button == ui.friends ) AnalyticsService::instance().sendPageView( FRIENDS_CATEGORY );\n        else if ( button == ui.radio ) AnalyticsService::instance().sendPageView( RADIO_CATEGORY );\n    }\n\n    m_lastButton = button;\n\n    emit currentChanged( index );\n}\n"
  },
  {
    "path": "app/client/Widgets/SideBar.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SIDEBAR_H\n#define SIDEBAR_H\n\n#include <QFrame>\n#include <QPointer>\n\nnamespace lastfm { class User; }\nnamespace unicorn { class Session; }\n\nclass SideBar : public QFrame\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QAbstractButton* nowPlaying;\n        class QAbstractButton* scrobbles;\n        class QAbstractButton* profile;\n        class QAbstractButton* friends;\n        class QAbstractButton* radio;\n        class QAbstractButton* sash;\n    } ui;\n\npublic:\n    explicit SideBar(QWidget *parent = 0);\n\n    void addToMenu( class QMenu& menu );\n    void click( int index );\n    QString currentCategory() const;\n\nsignals:\n    void currentChanged( int index );\n\npublic slots:\n    void onButtonClicked( class QAbstractButton* button );\n\n    void onUp();\n    void onDown();\n\nprivate slots:\n    void onSessionChanged( const unicorn::Session& session );\n\nprivate:\n    class QButtonGroup* m_buttonGroup;\n    class QAbstractButton* m_lastButton;\n    QPointer<QAction> m_radioAction;\n};\n\n#endif // SIDEBAR_H\n"
  },
  {
    "path": "app/client/Widgets/SimilarArtistWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"SimilarArtistWidget.h\"\n\nSimilarArtistWidget::SimilarArtistWidget(QWidget *parent) :\n    HttpImageWidget(parent)\n{\n}\n\nvoid\nSimilarArtistWidget::setArtist( const QString& artist )\n{\n    m_artist = artist;\n}\n\nvoid\nSimilarArtistWidget::paintEvent( QPaintEvent* event )\n{\n    HttpImageWidget::paintEvent( event );\n\n    QPainter p;\n    p.begin( this );\n\n    QTextOption to;\n\n    to.setAlignment( Qt::AlignBottom | Qt::AlignLeft );\n\n    QFontMetrics fm( font() );\n\n    QRect rect = contentsRect().adjusted( -3, 0, 13, 22 );\n\n    p.drawText( rect, fm.elidedText( m_artist, Qt::ElideRight, rect.width() ), to );\n\n    p.end();\n}\n"
  },
  {
    "path": "app/client/Widgets/SimilarArtistWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SIMILARARTISTWIDGET_H\n#define SIMILARARTISTWIDGET_H\n\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n\nclass SimilarArtistWidget : public HttpImageWidget\n{\n    Q_OBJECT\npublic:\n    explicit SimilarArtistWidget(QWidget *parent = 0);\n\n    void setArtist( const QString& artist );\n    \nprivate:\n    void paintEvent(QPaintEvent * event);\n\nprivate:\n    QString m_artist;\n};\n\n#endif // SIMILARARTISTWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/StatusBar.cpp",
    "content": "/*\r\n   Copyright 2010 Last.fm Ltd.\r\n      - Primarily authored by Jono Cole and Micahel Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QAction>\r\n#include <QHBoxLayout>\r\n#include <QPushButton>\r\n#include <QLabel>\r\n#include <QSizeGrip>\r\n\r\n#include \"lib/unicorn/widgets/Label.h\"\r\n\r\n#include \"StatusBar.h\"\r\n\r\n#include \"../Services/ScrobbleService.h\"\r\n#include \"../MediaDevices/DeviceScrobbler.h\"\r\n#include \"../Application.h\"\r\n\r\nStatusBar::StatusBar( QWidget* parent )\r\n    :QStatusBar( parent ),\r\n      m_online( false )\r\n{\r\n    addWidget( ui.widget = new QFrame( this) );\r\n    QHBoxLayout* widgetLayout = new QHBoxLayout( ui.widget );\r\n    widgetLayout->setContentsMargins( 0, 0, 0, 0 );\r\n    widgetLayout->setSpacing( 0 );\r\n\r\n    widgetLayout->addWidget( ui.cog = new QPushButton(this), 0, Qt::AlignVCenter);\r\n    ui.cog->setObjectName( \"cog\" );\r\n    ui.cog->setAttribute( Qt::WA_LayoutUsesWidgetRect );\r\n\r\n    widgetLayout->addWidget( ui.message = new unicorn::Label(this), 1, Qt::AlignVCenter);\r\n    ui.message->setObjectName( \"message\" );\r\n    ui.message->setAttribute( Qt::WA_LayoutUsesWidgetRect );\r\n    ui.message->setAlignment( Qt::AlignRight | Qt::AlignVCenter );\r\n\r\n    setStatus();\r\n\r\n    addPermanentWidget( ui.scrobbleWidget = new QFrame( this ));\r\n    ui.scrobbleWidget->setObjectName(\"scrobbleWidget\");\r\n    QHBoxLayout* scrobbleWidgetLayout = new QHBoxLayout( ui.scrobbleWidget );\r\n    scrobbleWidgetLayout->setContentsMargins( 50, 0, 0, 0 );\r\n    scrobbleWidgetLayout->setSpacing( 0 );\r\n\r\n    bool isScrobblingOff = unicorn::UserSettings().value(\"scrobblingOn\", true).toBool();\r\n\r\n    scrobbleWidgetLayout->addWidget( ui.scrobbleIcon = new QLabel(this) );\r\n    ui.scrobbleIcon->setObjectName(\"scrobbleIcon\");\r\n    ui.scrobbleIcon->setHidden(isScrobblingOff);\r\n\r\n    scrobbleWidgetLayout->addWidget( ui.scrobbleMessage = new unicorn::Label(this), 1, Qt::AlignVCenter);\r\n    ui.scrobbleMessage->setObjectName(\"scrobbleMessage\");\r\n    ui.scrobbleMessage->setAttribute(Qt::WA_LayoutUsesWidgetRect);\r\n    ui.scrobbleMessage->setAlignment(Qt::AlignRight | Qt::AlignVCenter );\r\n    ui.scrobbleMessage->setStyleSheet(\"QLabel { color : red; }\");\r\n    ui.scrobbleMessage->setText( tr(\"Scrobbling is off\") );\r\n    ui.scrobbleMessage->setHidden(isScrobblingOff);\r\n\r\n    aApp->isInternetConnectionUp() ? onConnectionUp() : onConnectionDown();\r\n\r\n    connect( aApp, SIGNAL( internetConnectionDown() ), SLOT( onConnectionDown() ) );\r\n    connect( aApp, SIGNAL( internetConnectionUp() ), SLOT( onConnectionUp() ) );\r\n\r\n    connect( this, SIGNAL(messageChanged(QString)), SLOT(onMessagedChanged(QString)));\r\n    connect( aApp, SIGNAL(scrobbleToggled(bool)), ui.scrobbleMessage, SLOT(setHidden(bool)));\r\n    connect( aApp, SIGNAL(scrobbleToggled(bool)), ui.scrobbleIcon, SLOT(setHidden(bool)));\r\n\r\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)));\r\n\r\n    connect( ui.cog, SIGNAL(clicked()), aApp, SLOT(onPrefsTriggered()));\r\n}\r\n\r\n\r\nvoid\r\nStatusBar::onSessionChanged( const unicorn::Session& /*session*/ )\r\n{\r\n    setStatus();\r\n}\r\n\r\nvoid\r\nStatusBar::onMessagedChanged( const QString& message )\r\n{\r\n    if ( message.isEmpty() )\r\n        setStatus();\r\n}\r\n\r\nvoid\r\nStatusBar::setStatus()\r\n{\r\n    ui.message->setText( tr(\"%1 (%2)\").arg( lastfm::ws::Username, m_online ? tr( \"Online\" ) : tr( \"Offline\" ) ));\r\n}\r\n\r\nvoid\r\nStatusBar::onConnectionUp()\r\n{\r\n    m_online = true;\r\n    setStatus();\r\n}\r\n\r\nvoid\r\nStatusBar::onConnectionDown()\r\n{\r\n    m_online = false;\r\n    setStatus();\r\n}\r\n\r\n"
  },
  {
    "path": "app/client/Widgets/StatusBar.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Micahel Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStatusBar>\n\n#include <lastfm/Track.h>\n#include <lastfm/User.h>\n\nclass QLabel;\n\nnamespace Phonon { class VolumeSlider; }\nnamespace unicorn { class Session; }\nnamespace unicorn { class Label; }\n\nclass StatusBar : public QStatusBar\n{\n    Q_OBJECT\n    public:\n        StatusBar( QWidget* parent = 0);\n\n    private slots:\n        void onMessagedChanged( const QString& text );\n        void setStatus();\n\n        void onConnectionUp();\n        void onConnectionDown();\n\n        void onSessionChanged( const unicorn::Session& session );\n\n    private:\n        struct\n        {\n            class QFrame* widget;\n            class QPushButton* cog;\n            unicorn::Label* message;\n\n            class QFrame* scrobbleWidget;\n            unicorn::Label* scrobbleMessage;\n            class QLabel* scrobbleIcon;\n        } ui;\n\n        bool m_online;\n};\n"
  },
  {
    "path": "app/client/Widgets/TagWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QPushButton>\n#include <QDesktopServices>\n#include <QPainter>\n#include <QFontMetrics>\n#include <QEvent>\n\n#include \"../Application.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"TagWidget.h\"\n\nTagWidget::TagWidget( const QString& tag, const QString& url, QWidget *parent )\n    :QPushButton( tag, parent ),\n      m_url( url ),\n      m_hovered( false ),\n      m_left_rest( \":/meta_tag_LEFT_REST.png\" ),\n      m_middle_rest( \":/meta_tag_MIDDLE_REST.png\" ),\n      m_right_rest( \":/meta_tag_RIGHT_REST.png\" ),\n      m_left_hover( \":/meta_tag_LEFT_HOVER.png\" ),\n      m_middle_hover( \":/meta_tag_MIDDLE_HOVER.png\" ),\n      m_right_hover( \":/meta_tag_RIGHT_HOVER.png\" )\n{    \n    connect( this, SIGNAL(clicked()), SLOT(onClicked()));\n\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    setAttribute( Qt::WA_Hover );\n\n    this->setCursor( Qt::PointingHandCursor );\n}\n\nbool\nTagWidget::event( QEvent* e )\n{\n    switch ( e->type())\n    {\n    case QEvent::HoverEnter:\n        m_hovered = true;\n        update();\n        break;\n    case QEvent::HoverLeave:\n        m_hovered = false;\n        update();\n        break;\n    default:\n        break;\n    }\n\n    return QPushButton::event( e );\n}\n\nvoid\nTagWidget::paintEvent( QPaintEvent* /*event*/ )\n{\n    QPainter p( this );\n\n    QFontMetrics fm = fontMetrics();\n\n    QRect middleRect = rect();\n    middleRect.adjust( m_left_rest.width(), 0, 0, 0 );\n    middleRect.setWidth( fm.width( text() ) + 8 );\n\n    if ( !m_hovered )\n    {\n        p.drawPixmap( rect().topLeft(), m_left_rest );\n        p.drawPixmap( middleRect, m_middle_rest );\n        p.drawPixmap( QPoint( m_left_rest.width() + middleRect.width(), 0 ), m_right_rest );\n    }\n    else\n    {\n        p.drawPixmap( rect().topLeft(), m_left_hover );\n        p.drawPixmap( middleRect, m_middle_hover );\n        p.drawPixmap( QPoint( m_left_hover.width() + middleRect.width(), 0 ), m_right_hover );\n    }\n\n    QTextOption to;\n    to.setAlignment( Qt::AlignCenter );\n\n    p.drawText( middleRect.adjusted( 0, 0, 0, -1 ), text(), to );\n}\n\nQSize\nTagWidget::sizeHint() const\n{\n    QFontMetrics fm = fontMetrics();\n    QSize size = QPushButton::sizeHint();\n    size.setWidth( m_left_rest.width() + m_right_rest.width() + fm.width( text() ) + 8 );\n    size.setHeight( 19 );\n    return size;\n}\n\nvoid\nTagWidget::onClicked()\n{\n    unicorn::DesktopServices::openUrl( m_url );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), TAG_CLICKED, \"TagButtonPressed\");\n\n}\n"
  },
  {
    "path": "app/client/Widgets/TagWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TAGWIDGET_H\n#define TAGWIDGET_H\n\n#include <QWidget>\n#include <QPixmap>\n#include <QPushButton>\n#include <QUrl>\n\nclass TagWidget : public QPushButton\n{\n    Q_OBJECT\npublic:\n    explicit TagWidget( const QString& tag, const QString& url, QWidget *parent = 0);\n\nprivate:\n    void paintEvent( QPaintEvent* event );\n    QSize sizeHint() const;\n    bool event( QEvent* e );\n\nprivate slots:\n    void onClicked();\n\nprivate:\n    QUrl m_url;\n\n    bool m_hovered;\n\n    QPixmap m_left_rest;\n    QPixmap m_middle_rest;\n    QPixmap m_right_rest;\n\n    QPixmap m_left_hover;\n    QPixmap m_middle_hover;\n    QPixmap m_right_hover;\n};\n\n#endif // TAGWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/TitleBar.cpp",
    "content": "/*\r\n   Copyright 2010 Last.fm Ltd.\r\n      - Primarily authored by Jono Cole and Micahel Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QHBoxLayout>\r\n#include <QPushButton>\r\n#include <QLabel>\r\n\r\n#include \"lib/unicorn/widgets/GhostWidget.h\"\r\n\r\n#include \"TitleBar.h\"\r\n\r\n#include \"../Application.h\"\r\n\r\nTitleBar::TitleBar( QWidget* parent )\r\n    :QFrame( parent )\r\n{\r\n    QHBoxLayout* layout = new QHBoxLayout( this );\r\n    layout->setContentsMargins( 0, 0, 0, 0 );\r\n    layout->setSpacing( 0 );\r\n\r\n    QPushButton* pb = new QPushButton( \"Close\" );\r\n    pb->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\r\n    pb->setCheckable( true );\r\n    connect( pb, SIGNAL(clicked()), SIGNAL( closeClicked()));\r\n\r\n#ifdef Q_OS_MAC\r\n    pb->setShortcut( Qt::CTRL + Qt::Key_H );\r\n    layout->addWidget( pb );\r\n#else\r\n    GhostWidget* ghost = new GhostWidget( this );\r\n    ghost->setOrigin( pb );\r\n    layout->addWidget( ghost );\r\n#endif\r\n\r\n    layout->addStretch( 1 );\r\n    QLabel* title = new QLabel( QApplication::applicationName(), this );\r\n    title->setMargin( 0 );\r\n    layout->addWidget( title, 0 );\r\n    layout->addStretch( 1 );\r\n\r\n#ifndef Q_OS_MAC\r\n    layout->addWidget( pb );\r\n#else\r\n    GhostWidget* gw;\r\n    layout->addWidget( gw = new GhostWidget( this ) );\r\n    gw->setOrigin( pb );\r\n#endif\r\n}\r\n\r\n"
  },
  {
    "path": "app/client/Widgets/TitleBar.h",
    "content": "/*\r\n   Copyright 2010 Last.fm Ltd.\r\n      - Primarily authored by Jono Cole and Micahel Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QFrame>\r\n\r\nclass QLabel;\r\n\r\nclass TitleBar : public QFrame\r\n{\r\n    Q_OBJECT\r\n    public:\r\n        TitleBar( QWidget* parent = 0 );\r\n\r\n    signals:\r\n        void closeClicked();\r\n};\r\n"
  },
  {
    "path": "app/client/Widgets/TrackWidget.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QMovie>\n#include <QTimer>\n\n#include <lastfm/Library.h>\n\n#include <lib/unicorn/dialogs/ShareDialog.h>\n#include <lib/unicorn/dialogs/TagDialog.h>\n#include <lib/unicorn/DesktopServices.h>\n#include <lib/unicorn/TrackImageFetcher.h>\n\n#include \"../Application.h\"\n#include \"../Services/ScrobbleService/ScrobbleService.h\"\n#include \"../Services/AnalyticsService.h\"\n\n#include \"TrackWidget.h\"\n#include \"ui_TrackWidget.h\"\n\nTrackWidget::TrackWidget( Track& track, QWidget *parent )\n    :QPushButton(parent),\n    ui( new Ui::TrackWidget ),\n    m_nowPlaying( false ),\n    m_triedFetchAlbumArt( false )\n{\n    ui->setupUi( this );\n\n    m_spinner = new QLabel( this );\n    m_spinner->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter );\n    m_spinner->hide();\n\n    m_movie = new QMovie( \":/icon_eq.gif\", \"GIF\", this );\n    m_movie->setCacheMode( QMovie::CacheAll );\n    ui->equaliser->setMovie( m_movie );\n\n    ui->buttonLayout->setAlignment( ui->love, Qt::AlignTop );\n    ui->buttonLayout->setAlignment( ui->tag, Qt::AlignTop );\n    ui->buttonLayout->setAlignment( ui->share, Qt::AlignTop );\n    ui->buttonLayout->setAlignment( ui->buy, Qt::AlignTop );\n\n    ui->albumArt->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->love->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->tag->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->share->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    ui->buy->setAttribute( Qt::WA_LayoutUsesWidgetRect );\n\n    setAttribute( Qt::WA_MacNoClickThrough );\n    ui->albumArt->setAttribute( Qt::WA_MacNoClickThrough );\n    ui->love->setAttribute( Qt::WA_MacNoClickThrough );\n    ui->tag->setAttribute( Qt::WA_MacNoClickThrough );\n    ui->share->setAttribute( Qt::WA_MacNoClickThrough );\n    ui->buy->setAttribute( Qt::WA_MacNoClickThrough );\n\n    connect( ui->love, SIGNAL(clicked(bool)), SLOT(onLoveClicked(bool)));\n    connect( ui->tag, SIGNAL(clicked()), SLOT(onTagClicked()));\n    connect( ui->share, SIGNAL(clicked()), SLOT(onShareClicked()));\n    connect( ui->buy, SIGNAL(clicked()), SLOT(onBuyClicked()));\n\n    connect( this, SIGNAL(clicked()), SLOT(onClicked()) );\n\n    setTrack( track );\n}\n\nTrackWidget::~TrackWidget()\n{\n    delete ui;\n}\n\nQSize\nTrackWidget::sizeHint() const\n{\n    QSize sizeHint = ui->frame->sizeHint();\n    sizeHint.setWidth( QPushButton::sizeHint().width() );\n    return sizeHint;\n}\n\nvoid\nTrackWidget::onClicked()\n{\n    emit clicked( *this );\n}\n\nvoid\nTrackWidget::contextMenuEvent( QContextMenuEvent* event )\n{\n    QMenu* contextMenu = new QMenu( this );\n\n    if ( ! m_nowPlaying )\n    {\n        contextMenu->addAction( tr( \"Delete this scrobble from your profile\" ), this, SLOT(onRemoveClicked()));\n        contextMenu->addSeparator();\n    }\n\n    if ( contextMenu->actions().count() )\n        contextMenu->exec( event->globalPos() );\n}\n\nvoid\nTrackWidget::startSpinner()\n{\n    m_spinner->setGeometry( rect() );\n\n    if ( !m_spinnerMovie )\n    {\n        m_spinnerMovie = new QMovie( \":/loading_meta.gif\", \"GIF\", this );\n        m_spinnerMovie->setCacheMode( QMovie::CacheAll );\n        m_spinner->setMovie( m_spinnerMovie );\n    }\n\n    setEnabled( false );\n\n    m_spinnerMovie->start();\n    m_spinner->show();\n}\n\nvoid\nTrackWidget::clearSpinner()\n{\n    if ( !m_spinnerMovie )\n    {\n        m_spinnerMovie = new QMovie( \":/loading_meta.gif\", \"GIF\", this );\n        m_spinnerMovie->setCacheMode( QMovie::CacheAll );\n        m_spinner->setMovie( m_spinnerMovie );\n    }\n\n    setEnabled( true );\n\n    m_spinnerMovie->stop();\n    m_spinner->hide();\n}\n\nvoid\nTrackWidget::showEvent(QShowEvent *)\n{\n    if ( m_nowPlaying )\n        m_movie->start();\n    fetchAlbumArt();\n}\n\nvoid\nTrackWidget::hideEvent( QHideEvent * )\n{\n    m_movie->stop();\n}\n\nvoid\nTrackWidget::fetchAlbumArt()\n{\n    if ( isVisible() && !m_triedFetchAlbumArt )\n    {\n        m_triedFetchAlbumArt = true;\n\n        delete m_trackImageFetcher;\n        m_trackImageFetcher = new TrackImageFetcher( m_track, Track::MediumImage );\n        connect( m_trackImageFetcher, SIGNAL(finished(QPixmap)), ui->albumArt, SLOT(setPixmap(QPixmap)) );\n        m_trackImageFetcher->startAlbum();\n    }\n}\n\nvoid\nTrackWidget::resizeEvent(QResizeEvent *)\n{\n    setTrackTitleWidth();\n}\n\nvoid\nTrackWidget::setTrackTitleWidth()\n{\n    int width = qMin( ui->trackTitleFrame->width(), ui->trackTitle->fontMetrics().width( ui->trackTitle->text() ) + 1 );\n    ui->trackTitle->setFixedWidth( width );\n}\n\nvoid\nTrackWidget::update( const lastfm::Track& track )\n{\n    // we're getting an update from a track fetched from user.getRecentTracks\n    MutableTrack mt( m_track );\n    mt.setScrobbleStatus( Track::Submitted ); // it's definitely been scrobbled\n    mt.setLoved( track.isLoved() ); // make sure the love state is consistent with Last.fm\n}\n\nvoid\nTrackWidget::setTrack( lastfm::Track& track )\n{\n    disconnect( m_track.signalProxy(), 0, this, 0 );\n\n    m_track = track;\n\n    connect( m_track.signalProxy(), SIGNAL(loveToggled(bool)), SLOT(onLoveToggled(bool)) );\n    connect( m_track.signalProxy(), SIGNAL(scrobbleStatusChanged(short)), SLOT(onScrobbleStatusChanged()));\n    connect( m_track.signalProxy(), SIGNAL(corrected(QString)), SLOT(onCorrected(QString)));\n\n    m_movie->stop();\n    ui->equaliser->hide();\n\n    setTrackDetails();\n\n    ui->albumArt->setPixmap( QPixmap( \":/meta_album_no_art.png\" ) );\n    ui->albumArt->setHref( track.www() );\n\n    m_triedFetchAlbumArt = false;\n    fetchAlbumArt();\n}\n\nvoid\nTrackWidget::setTrackDetails()\n{\n    ui->trackTitle->setText( m_track.title() );\n    ui->artist->setText( m_track.artist().name() );\n\n    if ( m_timestampTimer ) m_timestampTimer->stop();\n\n    if ( m_track.scrobbleStatus() == lastfm::Track::Cached && !m_nowPlaying )\n        ui->timestamp->setText( tr( \"Cached\" ) );\n    else if ( m_track.scrobbleStatus() == lastfm::Track::Error && !m_nowPlaying )\n        ui->timestamp->setText( tr( \"Error: %1\" ).arg( m_track.scrobbleErrorText() ) );\n    else\n        updateTimestamp();\n\n    ui->love->setChecked( m_track.isLoved() );\n\n    setTrackTitleWidth();\n}\n\nvoid\nTrackWidget::onLoveToggled( bool loved )\n{\n    ui->love->setChecked( loved );\n}\n\nvoid\nTrackWidget::onScrobbleStatusChanged()\n{\n    setTrackDetails();\n}\n\nvoid\nTrackWidget::onCorrected( QString /*correction*/ )\n{\n    setTrackDetails();\n}\n\n\n\nlastfm::Track\nTrackWidget::track() const\n{\n    return m_track;\n}\n\nvoid\nTrackWidget::onLoveClicked( bool loved )\n{\n    if ( loved )\n    {\n        MutableTrack( m_track ).love();\n        AnalyticsService::instance().sendEvent( aApp->currentCategory(), LOVE_TRACK, \"TrackLoved\");\n    }\n    else\n    {\n        MutableTrack( m_track ).unlove();\n        AnalyticsService::instance().sendEvent( aApp->currentCategory(), LOVE_TRACK, \"TrackUnLoved\");\n    }\n}\n\nvoid\nTrackWidget::onTagClicked()\n{\n    TagDialog* td = new TagDialog( m_track, window() );\n    td->raise();\n    td->show();\n    td->activateWindow();\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), TAG_CLICKED, \"TagButtonPressed\");\n}\n\nvoid\nTrackWidget::onShareClicked()\n{\n    QMenu* shareMenu = new QMenu( this );\n\n    shareMenu->addAction( tr( \"Share on Last.fm\" ), this, SLOT(onShareLastFm()) );\n    shareMenu->addAction( tr( \"Share on Twitter\" ), this, SLOT(onShareTwitter()) );\n    shareMenu->addAction( tr( \"Share on Facebook\" ), this, SLOT(onShareFacebook()) );\n\n    shareMenu->exec( cursor().pos() );\n}\n\nvoid\nTrackWidget::onBuyClicked()\n{\n    if ( !ui->buy->menu() )\n    {\n        // show the buy links please!\n        QString country = aApp->currentSession().user().country();\n        connect( m_track.getBuyLinks( country ), SIGNAL(finished()), SLOT(onGotBuyLinks()));\n    }\n}\n\nvoid\nTrackWidget::onRemoveClicked()\n{\n    connect( lastfm::Library::removeScrobble( m_track ), SIGNAL(finished()), SLOT(onRemovedScrobble()));\n}\n\nvoid\nTrackWidget::onRemovedScrobble()\n{\n   lastfm::XmlQuery lfm;\n\n   if ( lfm.parse( static_cast<QNetworkReply*>( sender() ) ) )\n   {\n       emit removed();\n   }\n   else\n   {\n       qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n   }\n\n\n}\n\nvoid\nTrackWidget::setNowPlaying( bool nowPlaying )\n{\n    m_nowPlaying = nowPlaying;\n    updateTimestamp();\n}\n\nvoid\nTrackWidget::updateTimestamp()\n{\n    if ( !m_timestampTimer )\n    {\n        m_timestampTimer = new QTimer( this );\n        m_timestampTimer->setSingleShot( true );\n        connect( m_timestampTimer, SIGNAL(timeout()), SLOT(updateTimestamp()));\n    }\n\n    if ( m_nowPlaying )\n    {\n        if ( isVisible() )\n            m_movie->start();\n        ui->equaliser->show();\n\n        ui->timestamp->setText( tr( \"Now listening\" ) );\n        ui->timestamp->setToolTip( \"\" );\n    }\n    else\n    {        \n        m_movie->stop();\n        ui->equaliser->hide();\n\n        unicorn::Label::prettyTime( *ui->timestamp, m_track.timestamp(), m_timestampTimer );\n    }\n}\n\nvoid\nTrackWidget::onGotBuyLinks()\n{\n    if ( !ui->buy->menu() )\n    {\n        // make sure we don't process this again if the button was clicked twice\n\n        XmlQuery lfm;\n\n        if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n        {\n            bool thingsToBuy = false;\n\n            QMenu* menu = new QMenu( this );\n\n            menu->addAction( tr(\"Downloads\") )->setEnabled( false );\n\n            // USD EUR GBP\n\n            foreach ( const XmlQuery& affiliation, lfm[\"affiliations\"][\"downloads\"].children( \"affiliation\" ) )\n            {\n                bool isSearch = affiliation[\"isSearch\"].text() == \"1\";\n\n                QAction* buyAction = 0;\n\n                if ( isSearch )\n                    buyAction = menu->addAction( tr(\"Search on %1\").arg( affiliation[\"supplierName\"].text() ) );\n                else\n                    buyAction = menu->addAction( tr(\"Buy on %1 %2\").arg( affiliation[\"supplierName\"].text(), unicorn::Label::price( affiliation[\"price\"][\"amount\"].text(), affiliation[\"price\"][\"currency\"].text() ) ) );\n\n                buyAction->setData( affiliation[\"buyLink\"].text() );\n\n                thingsToBuy = true;\n            }\n\n            menu->addSeparator();\n            menu->addAction( tr(\"Physical\") )->setEnabled( false );\n\n            foreach ( const XmlQuery& affiliation, lfm[\"affiliations\"][\"physicals\"].children( \"affiliation\" ) )\n            {\n                bool isSearch = affiliation[\"isSearch\"].text() == \"1\";\n\n                QAction* buyAction = 0;\n\n                if ( isSearch )\n                    buyAction = menu->addAction( tr(\"Search on %1\").arg( affiliation[\"supplierName\"].text() ) );\n                else\n                    buyAction = menu->addAction( tr(\"Buy on %1 %2\").arg( affiliation[\"supplierName\"].text(), unicorn::Label::price( affiliation[\"price\"][\"amount\"].text(), affiliation[\"price\"][\"currency\"].text() ) ) );\n\n                buyAction->setData( affiliation[\"buyLink\"].text() );\n\n                thingsToBuy = true;\n            }\n\n            ui->buy->setMenu( menu );\n            connect( menu, SIGNAL(triggered(QAction*)), SLOT(onBuyActionTriggered(QAction*)) );\n\n            ui->buy->click();\n        }\n        else\n        {\n            // TODO: what happens when we fail?\n            qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n        }\n    }\n}\n\nvoid\nTrackWidget::onBuyActionTriggered( QAction* buyAction )\n{\n    unicorn::DesktopServices::openUrl( buyAction->data().toString() );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), BUY_CLICKED, \"BuyButtonPressed\" );\n}\n\nvoid\nTrackWidget::onShareLastFm()\n{\n    ShareDialog* sd = new ShareDialog( m_track, window() );\n    sd->raise();\n    sd->show();\n    sd->activateWindow();\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"LastfmShare\" );\n}\n\nvoid\nTrackWidget::onShareTwitter()\n{\n    ShareDialog::shareTwitter( m_track );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"TwitterShare\" );\n}\n\nvoid\nTrackWidget::onShareFacebook()\n{\n    ShareDialog::shareFacebook( m_track );\n    AnalyticsService::instance().sendEvent( aApp->currentCategory(), SHARE_CLICKED, \"FacebookShare\" );\n}\n\n"
  },
  {
    "path": "app/client/Widgets/TrackWidget.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TRACKWIDGET_H\n#define TRACKWIDGET_H\n\n#include <QPushButton>\n\n#include <lastfm/Track.h>\n\nnamespace Ui { class TrackWidget; }\n\nclass QMovie;\nclass TrackImageFetcher;\n\nclass TrackWidget : public QPushButton\n{\n    Q_OBJECT\n    \npublic:\n    explicit TrackWidget( Track& track, QWidget *parent = 0 );\n    ~TrackWidget();\n\n    void update( const lastfm::Track& track );\n\n    void setTrack( lastfm::Track& track );\n    lastfm::Track track() const;\n\n    void setNowPlaying( bool nowPlaying );\n\npublic slots:\n    void startSpinner();\n    void clearSpinner();\n\nsignals:\n    void clicked( TrackWidget& trackWidget );\n    void removed();\n\nprivate slots:\n    void onClicked();\n    void onLoveClicked( bool loved );\n    void onTagClicked();\n    void onShareClicked();\n\n    void onBuyClicked();\n    void onGotBuyLinks();\n\n    void onRemoveClicked();\n    void onRemovedScrobble();\n\n    void onBuyActionTriggered( QAction* buyAction );\n\n    void onShareLastFm();\n    void onShareTwitter();\n    void onShareFacebook();\n\n    // signals from the track\n    void onLoveToggled( bool loved );\n    void onScrobbleStatusChanged();\n    void onCorrected( QString correction );\n\n    void updateTimestamp();\n\npublic:\n    QSize sizeHint() const;\n\nprivate:\n    void setTrackDetails();\n    void setTrackTitleWidth();\n\n    void resizeEvent(QResizeEvent *);\n    void showEvent(QShowEvent *);\n    void hideEvent(QHideEvent *);\n    void contextMenuEvent( QContextMenuEvent* event );\n\n    void fetchAlbumArt();\n\nprivate:\n    Ui::TrackWidget* ui;\n\n    lastfm::Track m_track;\n\n    QPointer<QMovie> m_movie;\n    QPointer<QTimer> m_timestampTimer;\n    QPointer<TrackImageFetcher> m_trackImageFetcher;\n\n    bool m_nowPlaying;\n    bool m_triedFetchAlbumArt;\n\n    QPointer<QMovie> m_spinnerMovie;\n    class QLabel* m_spinner;\n};\n\n#endif // TRACKWIDGET_H\n"
  },
  {
    "path": "app/client/Widgets/TrackWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>TrackWidget</class>\n <widget class=\"QWidget\" name=\"TrackWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>526</width>\n    <height>119</height>\n   </rect>\n  </property>\n  <property name=\"sizePolicy\">\n   <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n    <horstretch>0</horstretch>\n    <verstretch>0</verstretch>\n   </sizepolicy>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\" stretch=\"0\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QFrame\" name=\"frame\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"HttpImageWidget\" name=\"albumArt\">\n        <property name=\"text\">\n         <string notr=\"true\">TextLabel</string>\n        </property>\n        <property name=\"scaledContents\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n        <property name=\"spacing\">\n         <number>0</number>\n        </property>\n        <item>\n         <widget class=\"QFrame\" name=\"trackTitleFrame\">\n          <property name=\"sizePolicy\">\n           <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n            <horstretch>0</horstretch>\n            <verstretch>0</verstretch>\n           </sizepolicy>\n          </property>\n          <layout class=\"QHBoxLayout\" name=\"trackTitleLayout\" stretch=\"0,0\">\n           <property name=\"spacing\">\n            <number>0</number>\n           </property>\n           <property name=\"margin\">\n            <number>0</number>\n           </property>\n           <item>\n            <widget class=\"unicorn::Label\" name=\"trackTitle\">\n             <property name=\"sizePolicy\">\n              <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Preferred\">\n               <horstretch>0</horstretch>\n               <verstretch>0</verstretch>\n              </sizepolicy>\n             </property>\n             <property name=\"text\">\n              <string notr=\"true\">Title</string>\n             </property>\n            </widget>\n           </item>\n           <item>\n            <spacer name=\"horizontalSpacer\">\n             <property name=\"orientation\">\n              <enum>Qt::Horizontal</enum>\n             </property>\n             <property name=\"sizeType\">\n              <enum>QSizePolicy::Expanding</enum>\n             </property>\n             <property name=\"sizeHint\" stdset=\"0\">\n              <size>\n               <width>0</width>\n               <height>20</height>\n              </size>\n             </property>\n            </spacer>\n           </item>\n          </layout>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"artist\">\n          <property name=\"text\">\n           <string notr=\"true\">Artist</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>0</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n        <item>\n         <layout class=\"QHBoxLayout\" name=\"horizontalLayout_3\" stretch=\"0,1\">\n          <property name=\"spacing\">\n           <number>0</number>\n          </property>\n          <item>\n           <widget class=\"QLabel\" name=\"equaliser\">\n            <property name=\"text\">\n             <string notr=\"true\">e</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <widget class=\"unicorn::Label\" name=\"timestamp\">\n            <property name=\"text\">\n             <string notr=\"true\">Timestamp</string>\n            </property>\n           </widget>\n          </item>\n         </layout>\n        </item>\n       </layout>\n      </item>\n      <item>\n       <layout class=\"QHBoxLayout\" name=\"buttonLayout\">\n        <property name=\"spacing\">\n         <number>5</number>\n        </property>\n        <item>\n         <widget class=\"QPushButton\" name=\"love\">\n          <property name=\"toolTip\">\n           <string>Love</string>\n          </property>\n          <property name=\"text\">\n           <string>Love</string>\n          </property>\n          <property name=\"checkable\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"tag\">\n          <property name=\"toolTip\">\n           <string>Tag</string>\n          </property>\n          <property name=\"text\">\n           <string>Tag</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"share\">\n          <property name=\"toolTip\">\n           <string>Share</string>\n          </property>\n          <property name=\"text\">\n           <string>Share</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"QPushButton\" name=\"buy\">\n          <property name=\"toolTip\">\n           <string>Buy</string>\n          </property>\n          <property name=\"text\">\n           <string>Buy</string>\n          </property>\n         </widget>\n        </item>\n       </layout>\n      </item>\n     </layout>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>HttpImageWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/HttpImageWidget.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Widgets/WidgetTextObject.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QWidget>\n\n#include \"WidgetTextObject.h\"\n\nWidgetTextObject::WidgetTextObject()\n    :kMargin( 10, 5 )\n{\n}\n\nQSizeF\nWidgetTextObject::intrinsicSize(QTextDocument*, int /*posInDocument*/, const QTextFormat& format)\n{\n    QWidget* widget = qVariantValue<QWidget*>(format.property(1));\n    return QSizeF( widget->size() + kMargin );\n}\n\nvoid\nWidgetTextObject::drawObject(QPainter *painter, const QRectF &rect, QTextDocument * /*doc*/, int /*posInDocument*/, const QTextFormat &format)\n{\n    QWidget* widget = qVariantValue<QWidget*>(format.property( 1 ));\n    widget->render( painter, QPoint( 0, 0 ));\n\n    //Adjusted to allow for the margin\n    QRect contentsRect = rect.toRect().adjusted(0, 0, -kMargin.width(), -kMargin.height());\n    m_widgetRects[widget] = contentsRect;\n}\n\nQWidget*\nWidgetTextObject::widgetAtPoint( const QPoint& p )\n{\n    QMapIterator<QWidget*, QRect> i(m_widgetRects);\n    while (i.hasNext())\n    {\n        i.next();\n        if( i.value().contains(p))\n            return i.key();\n    }\n    return 0;\n}\n\nQRectF\nWidgetTextObject::widgetRect( QWidget* w )\n{\n    return m_widgetRects[w];\n}\n"
  },
  {
    "path": "app/client/Widgets/WidgetTextObject.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef WIDGETTEXTOBJECT_H\n#define WIDGETTEXTOBJECT_H\n\n#include <QObject>\n#include <QTextObjectInterface>\n\n/** An embeddable widget text object wrapper */\nclass WidgetTextObject : public QObject, QTextObjectInterface {\n    Q_OBJECT\n    Q_INTERFACES(QTextObjectInterface)\n    const QSize kMargin;\n\npublic:\n    WidgetTextObject();\n    QSizeF intrinsicSize(QTextDocument*, int /*posInDocument*/, const QTextFormat& format);\n    void drawObject(QPainter *painter, const QRectF &rect, QTextDocument * /*doc*/, int /*posInDocument*/, const QTextFormat &format);\n\n    QWidget* widgetAtPoint( const QPoint& p );\n\n    QRectF widgetRect( QWidget* w );\n\nprotected:\n    QMap<QWidget*, QRect> m_widgetRects;\n};\n\n#endif // WIDGETTEXTOBJECT_H\n"
  },
  {
    "path": "app/client/Wizard/AccessPage.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QVBoxLayout>\n#include <QLabel>\n#include <QStyle>\n#include <QAbstractButton>\n#include <QTextEdit>\n\n#include \"lib/unicorn/LoginProcess.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\n#include \"../Application.h\"\n\n#include \"FirstRunWizard.h\"\n\n#include \"AccessPage.h\"\n\nAccessPage::AccessPage()\n    :m_valid( false ),\n      m_gotUserInfo( false )\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n    \n    layout->addWidget( ui.image = new QLabel(), 1, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n\n    QVBoxLayout* rL = new QVBoxLayout( this );\n    rL->setContentsMargins( 0, 0, 0, 0 );\n    rL->setSpacing( 20 );\n\n    layout->addLayout( rL, 1 );\n\n    rL->addWidget( ui.description = new QLabel( \"\" ), 1, Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n\n    rL->addWidget( ui.authUrl = new QTextEdit( \"\" ) );\n    ui.authUrl->setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard );\n    ui.authUrl->setObjectName( \"authUrl\" );\n}\n\nvoid\nAccessPage::initializePage()\n{\n    setTitle( tr( \"We're waiting for you to connect to Last.fm\" ));\n\n    ui.description->setText( tr( \"<p>Please click the <strong>Yes, Allow Access</strong> button in your web browser to connect your Last.fm account to the Last.fm Desktop App.</p>\"\n                                 \"<p>If you haven't connected because you closed the browser window or you clicked cancel, please try again.</p>\" ) );\n\n    wizard()->setCommitPage( true );\n\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    QAbstractButton* custom = wizard()->setButton( FirstRunWizard::CustomButton, tr( \"Try Again\" ) );\n\n    connect( custom, SIGNAL(clicked()), SLOT(tryAgain()));\n\n    disconnect( aApp, SIGNAL(sessionChanged(unicorn::Session)), this, SLOT(onSessionChanged(unicorn::Session)));\n    disconnect( aApp, SIGNAL(gotUserInfo(lastfm::User)), this, SLOT(onGotUserInfo(lastfm::User)));\n    connect( aApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)));\n    connect( aApp, SIGNAL(gotUserInfo(lastfm::User)), SLOT(onGotUserInfo(lastfm::User)));\n\n    tryAgain();\n}\n\nvoid\nAccessPage::tryAgain()\n{\n    if ( !m_loginProcess )\n    {\n        m_loginProcess = new unicorn::LoginProcess( this );\n        connect( m_loginProcess, SIGNAL(authUrlChanged(QString)), SLOT(onAuthUrlChanged(QString)));\n    }\n\n    m_loginProcess->authenticate();\n\n    // disable the try again and coninue buttons\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) )->setEnabled( false );\n    wizard()->setButton( FirstRunWizard::CustomButton, tr( \"Try Again\" ) )->setEnabled( false );\n}\n\nvoid\nAccessPage::onAuthUrlChanged( const QString& authUrl )\n{\n    ui.description->setText( tr( \"<p>Please click the <strong>Yes, Allow Access</strong> button in your web browser to connect your Last.fm account to the Last.fm Desktop App.</p>\"\n                                                       \"<p>If you haven't connected because you closed the browser window or you clicked cancel, please try again.</p>\" )\n                                                   + tr( \"<p>If your web browser didn't open, copy and paste the link below into your address bar.</p>\" ) );\n\n    ui.authUrl->setText( authUrl );\n\n    wizard()->setButton( FirstRunWizard::CustomButton, tr( \"Try Again\" ) )->setEnabled( true );\n\n    if ( !authUrl.isEmpty() )\n        wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) )->setEnabled( true );\n}\n\nvoid\nAccessPage::onGotUserInfo( const lastfm::User& /*user*/ )\n{\n    m_gotUserInfo = true;\n\n    checkComplete();\n}\n\nvoid\nAccessPage::onSessionChanged( const unicorn::Session& session )\n{\n    if ( session.isValid() )\n        checkComplete();\n}\n\nvoid\nAccessPage::checkComplete()\n{\n    if ( aApp->currentSession().isValid() && m_gotUserInfo && !m_valid )\n    {\n        disconnect( aApp, SIGNAL(sessionChanged(unicorn::Session)), this, SLOT(onSessionChanged(unicorn::Session)));\n        disconnect( aApp, SIGNAL(gotUserInfo(lastfm::User)), this, SLOT(onGotUserInfo(lastfm::User)));\n\n        // we've now got both the session info and the user info\n        m_valid = true;\n\n        wizard()->showWelcome();\n        wizard()->next();\n\n        m_loginProcess->deleteLater();\n    }\n}\n\nvoid\nAccessPage::cleanupPage()\n{\n    ui.description->clear();\n    ui.authUrl->clear();\n}\n\n\nbool\nAccessPage::validatePage()\n{\n    if ( m_valid )\n        return true;\n\n    // try to get the session key!\n    m_loginProcess->getSession();\n\n    return false;\n}\n\n"
  },
  {
    "path": "app/client/Wizard/AccessPage.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ACCESS_PAGE_H\n#define ACCESS_PAGE_H\n\n#include \"WizardPage.h\"\n#include <QPointer>\n\nnamespace lastfm { class User; }\n\nnamespace unicorn{ \n    class LoginProcess;\n    class Session;\n}\n\nclass AccessPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n        class QTextEdit* authUrl;\n    } ui;\n\npublic:\n    AccessPage();\n\n    void initializePage();\n    bool validatePage();\n    void cleanupPage();\n\nprivate:\n    void checkComplete();\n\nprivate slots:\n    void tryAgain();\n\n    void onGotUserInfo( const lastfm::User& user );\n    void onSessionChanged( const unicorn::Session& session );\n    void onAuthUrlChanged( const QString& authUrl );\n\nprotected:\n    QPointer<unicorn::LoginProcess> m_loginProcess;\n    bool m_valid;\n    bool m_gotUserInfo;\n};\n\n#endif //AUTH_IN_PROGRESS_PAGE_H\n\n"
  },
  {
    "path": "app/client/Wizard/BootstrapInProgressPage.h",
    "content": "/*\n   Copyright 2010-2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BOOTSTRAP_IN_PROGRESS_PAGE_H\n#define BOOTSTRAP_IN_PROGRESS_PAGE_H\n\n#include <QWizardPage>\n#include <types/Track.h>\n\n#ifdef Q_OS_WIN\n#include \"lib/unicorn/Updater/PluginList.h\"\n#endif\n\nclass BootstrapInProgressPage : public QWizardPage {\n    Q_OBJECT\npublic:\n    BootstrapInProgressPage( QWizard* p );\n\n    void initializePage();\n\n    virtual bool isComplete() const;\n\nprotected slots:\n    void startBootstrap();\n    void onTrackProcessed( int percentage, const Track& );\n    void onPercentageUpload( int percentage );\n    void onBootstrapDone( int );\n    void onTrackStarted( const Track& );\n\nprotected:\n    class QProgressBar* m_progressBar;\n    class QLabel* m_label;\n\n    bool m_isComplete;\n    class AbstractBootstrapper* m_bootstrapper;\n#ifdef Q_OS_WIN\n    PluginList m_pluginList;\n#endif\n};\n\n#endif //BOOTSTRAP_IN_PROGRESS_PAGE_H\n\n"
  },
  {
    "path": "app/client/Wizard/BootstrapPage.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Jono Cole\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\r\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\r\n\r\n#include \"FirstRunWizard.h\"\r\n#include \"BootstrapPage.h\"\r\n\r\nBootstrapPage::BootstrapPage()\r\n{ \r\n    QHBoxLayout* layout = new QHBoxLayout( this );\r\n    layout->setContentsMargins( 0, 0, 0, 0 );\r\n    layout->setSpacing( 20 );\r\n\r\n    m_pluginsLayout = new QVBoxLayout();\r\n    m_pluginsLayout->setContentsMargins( 0, 0, 0, 0 );\r\n    m_pluginsLayout->setSpacing( 6 );\r\n\r\n    layout->addLayout( m_pluginsLayout );\r\n\r\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.</p>\"\r\n                                                        \"<p>Please select your preferred media player and click <strong>Start Import</strong></p>\" ) ),\r\n                       0,\r\n                       Qt::AlignTop);\r\n    ui.description->setObjectName( \"description\" );\r\n    ui.description->setWordWrap( true );\r\n}\r\n\r\nvoid\r\nBootstrapPage::playerSelected()\r\n{\r\n    m_playerId = qobject_cast<QRadioButton*>(sender())->objectName();\r\n    emit playerChanged();\r\n}\r\n\r\nbool\r\nBootstrapPage::validatePage()\r\n{\r\n#ifdef Q_OS_WIN\r\n    // make sure the user has closed their chosen plugin (except iTunes)\r\n    unicorn::IPluginInfo* plugin = wizard()->pluginList()->pluginById( m_playerId );\r\n\r\n    if ( plugin->bootstrapType() == unicorn::IPluginInfo::PluginBootstrap )\r\n    {\r\n        QList<unicorn::IPluginInfo*> plugins;\r\n        plugins << plugin;\r\n\r\n        unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( plugins, this );\r\n\r\n        if ( closeApps->result() != QDialog::Accepted )\r\n            closeApps->exec();\r\n        else\r\n            closeApps->deleteLater();\r\n\r\n        if ( closeApps->result() == QDialog::Accepted )\r\n            aApp->startBootstrap( m_playerId );\r\n        else\r\n        {\r\n            // The user didn't close their media players\r\n            QMessageBoxBuilder( this ).setTitle( tr( \"Your plugins haven't been installed\" ) )\r\n                    .setText( tr( \"You can install them later through the file menu\" ) )\r\n                    .setButtons( QMessageBox::Ok )\r\n                    .exec();\r\n        }\r\n    }\r\n    else\r\n#endif\r\n        aApp->startBootstrap( m_playerId );\r\n\r\n    // once you start importing you can't go back\r\n    // if they didn't click \"Start Import\" they won't get here\r\n    // so we allow them to go back and bootstrap\r\n    wizard()->setCommitPage( true );\r\n\r\n    return true;\r\n}\r\n\r\n\r\nvoid \r\nBootstrapPage::initializePage()\r\n{\r\n    QRadioButton* rb;\r\n#ifdef Q_OS_WIN\r\n    QList<unicorn::IPluginInfo*> plugins = wizard()->pluginList()->bootstrappablePlugins();\r\n\r\n    bool first = true;\r\n\r\n    foreach ( unicorn::IPluginInfo* plugin, plugins )\r\n    {\r\n        m_pluginsLayout->addWidget( rb = new QRadioButton( plugin->name()));\r\n        rb->setObjectName( plugin->id() );\r\n\r\n        rb->style()->polish( rb );\r\n\r\n        connect( rb, SIGNAL(clicked()), SLOT(playerSelected()));\r\n\r\n        if ( first )\r\n        {\r\n            rb->setChecked( true );\r\n            m_playerId = plugin->id();\r\n        }\r\n\r\n        first = false;\r\n    }\r\n#else\r\n    m_pluginsLayout->addWidget( rb = new QRadioButton( tr( \"iTunes\" ) ) );\r\n    rb->setChecked( true );\r\n    m_playerId = \"osx\";\r\n#endif\r\n\r\n    m_pluginsLayout->addStretch();\r\n\r\n    setTitle( tr( \"Now let's import your listening history\" ) );\r\n\r\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Start Import\" ) );\r\n    if ( wizard()->canGoBack() )\r\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\r\n    wizard()->setButton( FirstRunWizard::SkipButton, tr( \"Skip >>\" ) );\r\n}\r\n\r\nvoid\r\nBootstrapPage::cleanupPage()\r\n{\r\n    while ( m_pluginsLayout->count() > 0 )\r\n        m_pluginsLayout->takeAt( 0 )->widget()->deleteLater();\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "app/client/Wizard/BootstrapPage.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Jono Cole\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef BOOTSTRAP_WIZARD_H\r\n#define BOOTSTRAP_WIZARD_H\r\n\r\n#include \"WizardPage.h\"\r\n#include <QVBoxLayout>\r\n#include <QLabel>\r\n#include <QGroupBox>\r\n#include <QRadioButton>\r\n#include <QNetworkReply>\r\n#include <QPointer>\r\n\r\n#ifdef Q_OS_WIN32\r\n#include \"lib/unicorn/plugins/PluginList.h\"\r\n#endif\r\n#include \"../Application.h\"\r\n\r\nclass BootstrapPage: public WizardPage\r\n{\r\n    Q_OBJECT\r\n\r\nprivate:\r\n    Q_PROPERTY( QString playerId READ playerId WRITE setPlayerId )\r\n\r\n    struct\r\n    {\r\n        class QLabel* description;\r\n    } ui;\r\n\r\npublic:\r\n    BootstrapPage();\r\n\r\n    QString playerId() const { return m_playerId; }\r\n    void setPlayerId( const QString& playerId ) { m_playerId = playerId; }\r\n\r\nprivate:\r\n    void initializePage();\r\n    bool validatePage();\r\n    void cleanupPage();\r\n\r\nsignals:\r\n    void playerChanged();\r\n\r\nprivate slots:\r\n    void playerSelected();\r\n    \r\nprotected:\r\n    QString m_playerId;\r\n    QVBoxLayout* m_pluginsLayout;\r\n};\r\n\r\n#endif //BOOTSTRAP_WIZARD_H\r\n"
  },
  {
    "path": "app/client/Wizard/BootstrapProgressPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n\n#include \"../Application.h\"\n\n#include \"FirstRunWizard.h\"\n#include \"BootstrapProgressPage.h\"\n\nBootstrapProgressPage::BootstrapProgressPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>Don't worry, the upload process shouldn't take more than a couple of minutes, depending on the size of your music library.</p>\"\n                                                          \"<p>While we're hard at work adding your listening history to your Last.fm profile, why don't you check out the main features of the Last.fm Desktop App. Click <strong>Continue</strong> to take the tour.</p>\"), this ),\n                         0,\n                         Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\nvoid\nBootstrapProgressPage::setPluginId( const QString& pluginId )\n{\n    if ( pluginId == \"itw\"\n         || pluginId == \"osx\" )\n        ui.image->setPixmap( QPixmap( \":/graphic_import_itunes.png\" ) );\n    else if ( pluginId == \"wmp\" )\n        ui.image->setPixmap( QPixmap( \":/graphic_import_wmp.png\" ) );\n    else if ( pluginId == \"wa2\" )\n        ui.image->setPixmap( QPixmap( \":/graphic_import_winamp.png\" ) );\n    else if ( pluginId == \"foo2\"\n              || pluginId == \"foo3\" )\n        ui.image->setPixmap( QPixmap( \":/graphic_import_foobar.png\" ) );\n}\n\nvoid\nBootstrapProgressPage::initializePage()\n{\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n}\n\nvoid\nBootstrapProgressPage::cleanupPage()\n{\n}\n"
  },
  {
    "path": "app/client/Wizard/BootstrapProgressPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BOOTSTRAPPROGRESSPAGE_H\n#define BOOTSTRAPPROGRESSPAGE_H\n\n#include \"WizardPage.h\"\n\nclass BootstrapProgressPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    explicit BootstrapProgressPage();\n\n    void setPluginId( const QString& pluginId );\n\nprivate:\n    void initializePage();\n    void cleanupPage();\n};\n\n#endif // BOOTSTRAPPROGRESSPAGE_H\n"
  },
  {
    "path": "app/client/Wizard/FirstRunWizard.cpp",
    "content": "\n/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QPalette>\n#include <QStyle>\n#include <QMovie>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"../Application.h\"\n\n#include \"LoginPage.h\"\n#include \"AccessPage.h\"\n#include \"PluginsPage.h\"\n#include \"PluginsInstallPage.h\"\n#include \"BootstrapPage.h\"\n#include \"TourMetadataPage.h\"\n#include \"TourFinishPage.h\"\n#include \"TourScrobblesPage.h\"\n#include \"TourLocationPage.h\"\n\n#include \"ui_FirstRunWizard.h\"\n#include \"FirstRunWizard.h\"\n\nFirstRunWizard::FirstRunWizard( bool startFromTour, QWidget* parent )\n    :QDialog( parent ),\n      ui( new Ui::FirstRunWizard ),\n      m_commitPage( false ),\n      m_showWelcome( false ),\n      m_bootstrapState( NoBootstrap )\n{\n#ifdef Q_OS_WIN32\n    m_plugins = new unicorn::PluginList;\n#endif\n\n    ui->setupUi( this );\n\n    ui->welcome->hide();\n\n    for ( int i = 0 ; i < ui->stackedWidget->count() ; ++i )\n    {\n        qobject_cast<WizardPage*>(ui->stackedWidget->widget( i ))->setWizard( this );\n    }\n\n    connect( ui->next, SIGNAL(clicked()), SLOT(next()));\n    connect( ui->back, SIGNAL(clicked()), SLOT(back()));\n    connect( ui->skip, SIGNAL(clicked()), SLOT(skip()));\n    connect( ui->finish, SIGNAL(clicked()), SLOT(accept()));\n\n    connect( this, SIGNAL( rejected() ), this, SLOT( onRejected() ) );\n    connect( this, SIGNAL( accepted() ), this, SLOT( onWizardCompleted() ) );\n\n    connect( aApp, SIGNAL(bootstrapStarted(QString)), SLOT(onBootstrapStarted(QString)));\n    connect( aApp, SIGNAL(bootstrapDone(AbstractBootstrapper::BootstrapStatus)), SLOT(onBootstrapDone(AbstractBootstrapper::BootstrapStatus)));\n\n    if ( startFromTour )\n        ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n    else\n        ui->stackedWidget->setCurrentWidget( ui->loginPage );\n\n    initializePage( ui->stackedWidget->currentWidget() );\n\n    setFixedSize( 750, 450 );\n}\n\nFirstRunWizard::~FirstRunWizard()\n{\n#ifdef Q_OS_WIN32\n    delete m_plugins;\n#endif\n}\n\nFirstRunWizard::BootstrapState\nFirstRunWizard::bootstrapState() const\n{\n    return m_bootstrapState;\n}\n\nAbstractBootstrapper::BootstrapStatus\nFirstRunWizard::bootstrapStatus() const\n{\n    return m_bootstrapStatus;\n}\n\nvoid\nFirstRunWizard::setTitle( const QString& title )\n{\n    ui->title->setText( title );\n}\n\nvoid\nFirstRunWizard::setCommitPage( bool commitPage )\n{\n    m_commitPage = commitPage;\n}\n\nbool\nFirstRunWizard::canGoBack() const\n{\n    return m_pages.count() > 0;\n}\n\nvoid\nFirstRunWizard::showWelcome()\n{\n    m_showWelcome = true;\n}\n\nQAbstractButton*\nFirstRunWizard::setButton( Button button, const QString& text )\n{\n    QAbstractButton* returnButton;\n\n    switch ( button )\n    {\n    case CustomButton:\n        returnButton = ui->custom;\n        break;\n    case BackButton:\n        returnButton = ui->back;\n        break;\n    case SkipButton:\n        returnButton = ui->skip;\n        break;\n    case NextButton:\n        returnButton = ui->next;\n        break;\n    case FinishButton:\n        returnButton = ui->finish;\n        break;\n    }\n\n    returnButton->setText( text );\n    returnButton->show();\n\n    return returnButton;\n}\n\nvoid\nFirstRunWizard::next()\n{\n    setUpdatesEnabled( false );\n\n    QWidget* currentPage = ui->stackedWidget->currentWidget();\n\n    if ( qobject_cast<WizardPage*>(currentPage)->validatePage() )\n    {\n        // go to the next page\n        cleanupPage( currentPage );\n\n        // remember what the last page was so we can go back()\n        m_pages << currentPage;\n\n        if ( m_commitPage )\n        {\n            m_commitPage = false;\n            m_pages.clear();\n        }\n\n        if ( currentPage == ui->loginPage )\n            ui->stackedWidget->setCurrentWidget( ui->accessPage );\n        else if ( currentPage == ui->accessPage )\n#ifdef Q_OS_WIN32\n            ui->stackedWidget->setCurrentWidget( ui->pluginsPage );\n        else if ( currentPage == ui->pluginsPage )\n            ui->stackedWidget->setCurrentWidget( ui->pluginsInstallPage );\n        else if ( currentPage == ui->pluginsInstallPage )\n            if( aApp->currentSession().user().canBootstrap() && (m_plugins->bootstrappablePlugins().count() > 0) )\n                ui->stackedWidget->setCurrentWidget( ui->bootstrapPage );\n            else\n                ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#elif defined Q_OS_MAC\n            if( aApp->currentSession().user().canBootstrap() )\n                ui->stackedWidget->setCurrentWidget( ui->bootstrapPage );\n            else\n                ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#elif defined Q_WS_X11\n            ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#endif\n        else if ( currentPage == ui->bootstrapPage )\n            ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n        else if ( currentPage == ui->tourScrobblesPage )\n            ui->stackedWidget->setCurrentWidget( ui->tourMetadataPage );\n        // only show the radio page if you can subscribe to get radio\n        else if ( currentPage == ui->tourMetadataPage )\n        {\n#ifndef Q_WS_X11 // don't show the sys tray page on linux because there isn't one\n            ui->stackedWidget->setCurrentWidget( ui->tourLocationPage );\n#else\n            ui->stackedWidget->setCurrentWidget( ui->tourFinishPage );\n#endif\n        }\n        else if ( currentPage == ui->tourLocationPage )\n#ifndef Q_WS_X11 // don't show the sys tray page on linux because there isn't one\n            ui->stackedWidget->setCurrentWidget( ui->tourFinishPage );\n#endif\n\n        ui->welcome->hide();\n\n        if ( m_showWelcome )\n        {\n            m_showWelcome = false;\n            ui->welcome->setText( tr( \"Thanks <strong>%1</strong>, your account is now connected!\" ).arg( aApp->currentSession().user().name() ) );\n            ui->welcome->show();\n        }\n\n        initializePage( ui->stackedWidget->currentWidget() );\n    }\n\n    setUpdatesEnabled( true );\n}\n\nvoid\nFirstRunWizard::back()\n{\n    if ( canGoBack() )\n    {\n        setCommitPage( false );\n\n        ui->welcome->hide();\n\n        cleanupPage( ui->stackedWidget->currentWidget() );\n        ui->stackedWidget->setCurrentWidget( m_pages.takeLast() );\n        initializePage( ui->stackedWidget->currentWidget() );\n    }\n}\n\nvoid\nFirstRunWizard::skip()\n{\n    // skip is mostly the same as next but we don't call validatePage()\n    // and the tour pages all go ot the last page\n\n    QWidget* currentPage = ui->stackedWidget->currentWidget();\n\n    // go to the next page\n    cleanupPage( currentPage );\n\n    // remember what the last page was so we can go back()\n    m_pages << currentPage;\n\n    if ( currentPage == ui->loginPage )\n        ui->stackedWidget->setCurrentWidget( ui->accessPage );\n    else if ( currentPage == ui->accessPage )\n#ifdef Q_OS_WIN\n        ui->stackedWidget->setCurrentWidget( ui->pluginsPage );\n    else if ( currentPage == ui->pluginsPage )\n        ui->stackedWidget->setCurrentWidget( ui->pluginsInstallPage );\n    else if ( currentPage == ui->pluginsInstallPage )\n        if( aApp->currentSession().user().canBootstrap() && (m_plugins->bootstrappablePlugins().count() > 0) )\n            ui->stackedWidget->setCurrentWidget( ui->bootstrapPage );\n        else\n            ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#elif defined Q_OS_MAC\n        if( aApp->currentSession().user().canBootstrap() )\n            ui->stackedWidget->setCurrentWidget( ui->bootstrapPage );\n        else\n            ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#elif defined Q_WS_X11\n        ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n#endif\n    else if ( currentPage == ui->bootstrapPage )\n        ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n    else if ( currentPage == ui->bootstrapProgressPage )\n        ui->stackedWidget->setCurrentWidget( ui->tourScrobblesPage );\n    else if ( currentPage == ui->tourScrobblesPage\n              || currentPage == ui->tourMetadataPage\n              || currentPage == ui->tourLocationPage )\n        ui->stackedWidget->setCurrentWidget( ui->tourFinishPage );\n\n    ui->welcome->hide();\n\n    initializePage( ui->stackedWidget->currentWidget() );\n}\n\nvoid\nFirstRunWizard::cleanupPage( QWidget* widget )\n{\n    WizardPage* page = qobject_cast<WizardPage*>(widget);\n\n    // disconect any buttons from page\n    disconnect( ui->next, 0, page, 0 );\n    disconnect( ui->back, 0, page, 0 );\n    disconnect( ui->finish, 0, page, 0 );\n    disconnect( ui->custom, 0, page, 0 );\n    disconnect( ui->skip, 0, page, 0 );\n\n    page->cleanupPage();\n}\n\nvoid\nFirstRunWizard::initializePage( QWidget* widget )\n{\n    WizardPage* page = qobject_cast<WizardPage*>(widget);\n\n    // hide all the buttons\n    ui->next->hide();\n    ui->back->hide();\n    ui->finish->hide();\n    ui->custom->hide();\n    ui->skip->hide();\n\n    page->initializePage();\n}\n\n\nvoid\nFirstRunWizard::onBootstrapStarted( const QString& pluginId )\n{\n    m_bootstrapState = BootstrapStarted;\n\n    ui->bootstrapProgressPage->setPluginId( pluginId );\n\n    ui->importLabel->setText( tr( \"Importing...\" ) );\n\n    QMovie* movie = new QMovie( \":/graphic_import.gif\", \"GIF\", this );\n    movie->setCacheMode( QMovie::CacheAll );\n    ui->importIcon->setMovie( movie );\n    movie->start();\n\n    ui->importIcon->show();\n    ui->importLabel->show();\n}\n\nvoid\nFirstRunWizard::onBootstrapDone( AbstractBootstrapper::BootstrapStatus status )\n{\n    m_bootstrapState = BootstrapFinished;\n    m_bootstrapStatus = status;\n\n    ui->importIcon->setPixmap( QPixmap( \":/lastfm_icon_32.png\" ) );\n    ui->importLabel->setText( tr( \"Import complete!\" ) );\n}\n\nvoid\nFirstRunWizard::onWizardCompleted()\n{\n    unicorn::Settings().setFirstRunWizardCompleted( true );\n}\n\n\nvoid\nFirstRunWizard::onRejected()\n{\n}\n"
  },
  {
    "path": "app/client/Wizard/FirstRunWizard.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef FIRST_RUN_WIZARD_H_\n#define FIRST_RUN_WIZARD_H_\n\n#include <QDialog>\n#include <QAbstractButton>\n#include <QList>\n#include <QPointer>\n\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"../Bootstrapper/AbstractBootstrapper.h\"\n\n#ifdef Q_OS_WIN32\n#include \"lib/unicorn/plugins/PluginList.h\"\n#endif\n\nnamespace Ui { class FirstRunWizard; }\n\nclass FirstRunWizard : public QDialog\n{\n    Q_OBJECT\npublic:\n    enum Button\n    {\n        CustomButton,\n        BackButton,\n        SkipButton,\n        NextButton,\n        FinishButton\n    };\n\n    enum BootstrapState\n    {\n        NoBootstrap,\n        BootstrapStarted,\n        BootstrapFinished\n    };\n\npublic:\n    FirstRunWizard( bool startFromTour = false, QWidget* parent = 0 );\n    ~FirstRunWizard();\n\n    void setTitle( const QString& title );\n\n    QAbstractButton* setButton( Button button, const QString& text );\n\n    void setCommitPage( bool commitPage );\n    bool canGoBack() const;\n\n    void showWelcome();\n\n    BootstrapState bootstrapState() const;\n    AbstractBootstrapper::BootstrapStatus bootstrapStatus() const;\n\n#ifdef Q_OS_WIN32\n    class unicorn::PluginList* pluginList() const { return m_plugins; }\n#endif\n\npublic slots:\n    void next();\n    void back();\n    void skip();\n\nprivate slots:\n    void onWizardCompleted();\n    void onRejected();\n\n    void onBootstrapStarted( const QString& pluginId );\n    void onBootstrapDone( AbstractBootstrapper::BootstrapStatus status );\n\nprivate:\n    void initializePage( QWidget* page );\n    void cleanupPage( QWidget* page );\n\nprivate:\n    Ui::FirstRunWizard* ui;\n#ifdef Q_OS_WIN32\n    QPointer<unicorn::PluginList> m_plugins;\n#endif\n\n    QList<QWidget*> m_pages;\n\n    bool m_commitPage;\n    bool m_showWelcome;\n\n    BootstrapState m_bootstrapState;\n    AbstractBootstrapper::BootstrapStatus m_bootstrapStatus;\n};\n\n#endif //FIRST_RUN_WIZARD_H_\n"
  },
  {
    "path": "app/client/Wizard/FirstRunWizard.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>FirstRunWizard</class>\n <widget class=\"QDialog\" name=\"FirstRunWizard\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>725</width>\n    <height>390</height>\n   </rect>\n  </property>\n  <property name=\"sizePolicy\">\n   <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n    <horstretch>0</horstretch>\n    <verstretch>0</verstretch>\n   </sizepolicy>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Last.fm Desktop App</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QLabel\" name=\"welcome\">\n     <property name=\"text\">\n      <string notr=\"true\">Welcome</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"title\">\n     <property name=\"text\">\n      <string notr=\"true\">Title</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QStackedWidget\" name=\"stackedWidget\">\n     <widget class=\"LoginPage\" name=\"loginPage\"/>\n     <widget class=\"AccessPage\" name=\"accessPage\"/>\n     <widget class=\"PluginsPage\" name=\"pluginsPage\"/>\n     <widget class=\"PluginsInstallPage\" name=\"pluginsInstallPage\"/>\n     <widget class=\"BootstrapPage\" name=\"bootstrapPage\"/>\n     <widget class=\"BootstrapProgressPage\" name=\"bootstrapProgressPage\"/>\n     <widget class=\"TourScrobblesPage\" name=\"tourScrobblesPage\"/>\n     <widget class=\"TourMetadataPage\" name=\"tourMetadataPage\"/>\n     <widget class=\"TourFinishPage\" name=\"tourFinishPage\"/>\n     <widget class=\"TourLocationPage\" name=\"tourLocationPage\"/>\n    </widget>\n   </item>\n   <item>\n    <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n     <property name=\"spacing\">\n      <number>40</number>\n     </property>\n     <property name=\"margin\">\n      <number>40</number>\n     </property>\n     <item>\n      <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\">\n       <property name=\"spacing\">\n        <number>0</number>\n       </property>\n       <item>\n        <widget class=\"QLabel\" name=\"importIcon\">\n         <property name=\"text\">\n          <string/>\n         </property>\n        </widget>\n       </item>\n       <item>\n        <widget class=\"QLabel\" name=\"importLabel\">\n         <property name=\"text\">\n          <string/>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </item>\n     <item>\n      <spacer name=\"horizontalSpacer\">\n       <property name=\"orientation\">\n        <enum>Qt::Horizontal</enum>\n       </property>\n       <property name=\"sizeHint\" stdset=\"0\">\n        <size>\n         <width>0</width>\n         <height>20</height>\n        </size>\n       </property>\n      </spacer>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"back\">\n       <property name=\"text\">\n        <string notr=\"true\">Back</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"skip\">\n       <property name=\"text\">\n        <string notr=\"true\">Skip</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"custom\">\n       <property name=\"text\">\n        <string notr=\"true\">Custom</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"next\">\n       <property name=\"text\">\n        <string notr=\"true\">Next</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QPushButton\" name=\"finish\">\n       <property name=\"text\">\n        <string notr=\"true\">Finish</string>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>LoginPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/LoginPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>AccessPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/AccessPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>PluginsPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/PluginsPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>PluginsInstallPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/PluginsInstallPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>BootstrapPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/BootstrapPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>TourScrobblesPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/TourScrobblesPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>TourMetadataPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/TourMetadataPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>TourFinishPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/TourFinishPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>TourLocationPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/TourLocationPage.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>BootstrapProgressPage</class>\n   <extends>QWidget</extends>\n   <header>../Wizard/BootstrapProgressPage.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "app/client/Wizard/LoginPage.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QDebug>\n#include <QGridLayout>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QLineEdit>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QDesktopServices>\n#include <QStyle>\n\n#include <lastfm/UrlBuilder.h>\n\n#include \"lib/unicorn/LoginProcess.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"FirstRunWizard.h\"\n#include \"LoginPage.h\"\n#include \"../Application.h\"\n#include \"lib/unicorn/dialogs/ProxyDialog.h\"\n\nLoginPage::LoginPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n    \n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>Already a Last.fm user? Connect your account with the Last.fm Desktop App and it'll update your profile with the music you're listening to.</p>\"\n                                                        \"<p>If you don't have an account you can sign up now for free now.</p>\" ) ),\n                       0,\n                       Qt::AlignTop );\n    \n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nvoid\nLoginPage::initializePage()\n{\n    setTitle( tr( \"Let's get started by connecting your Last.fm account\" ) );\n\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Connect Your Account\" ) )->setEnabled( true );\n    QAbstractButton* custom = wizard()->setButton( FirstRunWizard::CustomButton, tr( \"Sign up\" ) );\n    custom->setEnabled( true );\n    QAbstractButton* proxy = wizard()->setButton( FirstRunWizard::BackButton, tr( \"Proxy?\" ) );\n    proxy->setEnabled( true );\n\n    connect( custom, SIGNAL(clicked()), SLOT(onSignUpClicked()));\n    connect( proxy, SIGNAL(clicked()), SLOT(onProxyClicked()));\n}\n\n\nvoid\nLoginPage::cleanupPage()\n{\n}\n\nvoid \nLoginPage::onSignUpClicked()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"join\" ).url() );\n}\n\nvoid\nLoginPage::onProxyClicked()\n{\n    unicorn::ProxyDialog proxy;\n    proxy.exec();\n}\n"
  },
  {
    "path": "app/client/Wizard/LoginPage.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef LOGIN_PAGE_H_\n#define LOGIN_PAGE_H_\n\n#include \"WizardPage.h\"\n#include <QAbstractButton>\n\nclass LoginPage : public WizardPage\n{\n    Q_OBJECT\n\nprivate:\n    struct {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    LoginPage();\n\n    void initializePage();\n    void cleanupPage();\n \nprivate slots:\n    void onSignUpClicked();\n    void onProxyClicked();\n};\n\n#endif //LOGIN_PAGE_H_\n"
  },
  {
    "path": "app/client/Wizard/PluginsInstallPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QTimer>\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\n\n#include \"FirstRunWizard.h\"\n#include \"PluginsInstallPage.h\"\n\nPluginsInstallPage::PluginsInstallPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop );\n    ui.image->setObjectName( \"image\" );\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>Please follow the instructions that appear from your operating system to install the plugins.</p>\"\n                                                          \"<p>Once the plugins have been installed on you computer, click <strong>Continue</strong>.</p>\"), this ),\n                         0,\n                         Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nvoid\nPluginsInstallPage::initializePage()\n{\n    setTitle( tr( \"Your plugins are now being installed\" ) );\n\n    wizard()->setCommitPage( true );\n\n#ifdef Q_OS_WIN32\n    QAbstractButton* continueButton = wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n\n\n    if ( wizard()->pluginList()->installList().count() > 0 )\n    {\n        // get the install to happen a bit later so that\n        // we actually show this page of the wizard\n        // and the user has time to read what's happening\n        QTimer::singleShot( 1000, this, SLOT(install()) );\n        continueButton->setEnabled( false );\n    }\n    else\n    {\n        continueButton->click();\n    }\n#endif\n}\n\nvoid\nPluginsInstallPage::install()\n{\n#ifdef Q_OS_WIN32\n    // Tell the user to close any aplications we are about to install\n    // plugins for\n\n    unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( wizard()->pluginList()->installList(), this );\n\n    if ( closeApps->result() != QDialog::Accepted )\n        closeApps->exec();\n    else\n        closeApps->deleteLater();\n\n    if ( closeApps->result() == QDialog::Accepted )\n    {\n        foreach( unicorn::IPluginInfo* plugin, wizard()->pluginList()->installList() )\n        {\n            if ( !plugin->doInstall() )\n            {\n                // The plugin failed to install\n                // should probably do something\n            }\n        }\n    }\n    else\n    {\n        // The user didn't close their media players\n        QMessageBoxBuilder( this ).setTitle( tr( \"Your plugins haven't been installed\" ) )\n                .setIcon( QMessageBox::Warning )\n                .setText( tr( \"You can install them later through the file menu\" ) )\n                .setButtons( QMessageBox::Ok )\n                .exec();\n    }\n#endif\n\n    QAbstractButton* continueButton = wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    continueButton->setEnabled( true );\n    QTimer::singleShot( 1000, continueButton, SLOT(click()) );\n}\n\n\nvoid\nPluginsInstallPage::cleanupPage()\n{\n}\n"
  },
  {
    "path": "app/client/Wizard/PluginsInstallPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLUGINSINSTALLPAGE_H\n#define PLUGINSINSTALLPAGE_H\n\n#include \"WizardPage.h\"\n\nclass PluginsInstallPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    explicit PluginsInstallPage();\n\nprivate slots:\n    void install();\n\nprivate:\n    void initializePage();\n    void cleanupPage();\n};\n\n#endif // PLUGINSINSTALLPAGE_H\n"
  },
  {
    "path": "app/client/Wizard/PluginsPage.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QCheckBox>\n#include <QProcess>\n#include <QDebug>\n#include <QStyle>\n\n#ifdef Q_OS_WIN32\n#include \"lib/unicorn/plugins/PluginList.h\"\n#endif\n\n#include \"FirstRunWizard.h\"\n#include \"PluginsPage.h\"\n\nPluginsPage::PluginsPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    // add the radio buttons\n    m_pluginsLayout = new QVBoxLayout();\n    m_pluginsLayout->setContentsMargins( 0, 0, 0, 0 );\n    m_pluginsLayout->setSpacing( 6 );\n\n    layout->addLayout( m_pluginsLayout );\n\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.</p>\"\n                                                       \"<p>Please select the media players that you would like to scrobble your music from and click <strong>Install Plugins</strong></p>\"), this ),\n                                                       0,\n                                                       Qt::AlignTop );\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nbool\nPluginsPage::validatePage()\n{\n    return true;\n}\n\nvoid\nPluginsPage::cleanupPage()\n{\n}\n\nvoid\nPluginsPage::initializePage()\n{\n#ifdef Q_OS_WIN32\n    QList<unicorn::IPluginInfo*> supportedPlugins = wizard()->pluginList()->supportedList();\n    foreach( unicorn::IPluginInfo* plugin, supportedPlugins )\n    {\n        QCheckBox* cb;\n        m_pluginsLayout->addWidget( cb = new QCheckBox( plugin->name(), this ));\n        connect( cb, SIGNAL(toggled(bool)), plugin, SLOT(install(bool)));\n        connect( cb, SIGNAL(toggled(bool)), SLOT(checkPluginsSelected()));\n\n        cb->setObjectName( plugin->id() );\n        cb->setChecked( plugin->isAppInstalled() );\n        cb->style()->polish( cb );\n\n        if ( plugin->isInstalled() )\n        {\n            if ( plugin->version() > plugin->installedVersion() )\n            {\n                cb->setChecked( true );\n                cb->setText( cb->text() + \" \" + tr( \"(newer version)\" ));\n            }\n            else\n            {\n                cb->setChecked( false );\n                cb->setText( cb->text() + \" \" + tr( \"(Plugin installed tick to reinstall)\" ));\n            }\n        }\n    }\n\n\n    m_pluginsLayout->addStretch();\n\n    setTitle( tr( \"Next step, install the Last.fm plugins to be able to scrobble the music you listen to.\" ));\n\n    checkPluginsSelected();\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n#endif\n}\n\nvoid\nPluginsPage::checkPluginsSelected()\n{\n#ifdef Q_OS_WIN32\n    wizard()->setButton( FirstRunWizard::SkipButton, tr( \"Skip >>\" ) )->setVisible( wizard()->pluginList()->installList().count() > 0 );\n    wizard()->setButton( FirstRunWizard::NextButton,\n                         wizard()->pluginList()->installList().count() > 0 ?\n                             tr( \"Install Plugins\" ):\n                             tr( \"Continue\" ) );\n#endif\n}\n"
  },
  {
    "path": "app/client/Wizard/PluginsPage.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Jono Cole\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef PLUGINS_PAGE_H\r\n#define PLUGINS_PAGE_H\r\n\r\n#include \"WizardPage.h\"\r\n\r\nclass PluginsPage : public WizardPage\r\n{\r\n    Q_OBJECT\r\nprivate:\r\n    struct\r\n    {\r\n        class QCheckBox* iTunes;\r\n        class QCheckBox* iWMP;\r\n        class QCheckBox* iWinAmp;\r\n        class QCheckBox* iFoo;\r\n\r\n        class QLabel* description;\r\n    } ui;\r\n\r\npublic:\r\n    PluginsPage();\r\n\r\nprivate:\r\n    bool validatePage();\r\n    void cleanupPage();\r\n    void initializePage();\r\n\r\nprivate slots:\r\n    void checkPluginsSelected();\r\n\r\nprivate:\r\n    class QVBoxLayout* m_pluginsLayout;\r\n};\r\n\r\n#endif //PLUGINS_PAGE_H\r\n"
  },
  {
    "path": "app/client/Wizard/TourFinishPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n\n#include \"TourFinishPage.h\"\n\n#include \"../Application.h\"\n#include \"../Bootstrapper/AbstractBootstrapper.h\"\n\nTourFinishPage::TourFinishPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n    layout->addWidget( ui.description = new QLabel( this ), 0, Qt::AlignTop );\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n\n    connect( aApp, SIGNAL(bootstrapDone(AbstractBootstrapper::BootstrapStatus)), SLOT(onBootstrapDone(AbstractBootstrapper::BootstrapStatus)));\n}\n\nvoid\nTourFinishPage::setDescription( FirstRunWizard::BootstrapState state, AbstractBootstrapper::BootstrapStatus status )\n{\n    if ( state == FirstRunWizard::BootstrapFinished )\n    {\n        if ( status == AbstractBootstrapper::Bootstrap_Ok )\n        {\n            ui.description->setText( tr( \"<p>Now you're ready to get started! Just click <strong>Finish</strong> and start exploring.</p>\"\n                                         \"<p>We've also finished importing your listening history and have added it to your Last.fm profile.</p>\"\n                                         \"<p>Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!</p>\") );\n        }\n        else\n        {\n            QMap<AbstractBootstrapper::BootstrapStatus, QString> reasons;\n            reasons[AbstractBootstrapper::Bootstrap_UploadError] = tr( \"there was an upload error\" );\n            reasons[AbstractBootstrapper::Bootstrap_Denied] = tr( \"the submission was denied by Last.fm\" );\n            reasons[AbstractBootstrapper::Bootstrap_Spam] = tr( \"it was detected as spam (too high playcounts?)\" );\n            reasons[AbstractBootstrapper::Bootstrap_Cancelled] = tr( \"the submission was cancelled\" );\n\n            ui.description->setText( tr( \"<p>Now you're ready to get started! Just click <strong>Finish</strong> and start exploring.</p>\"\n                                         \"<p>Importing your listening history to Last.fm failed because %1. Sorry about that!</p>\"\n                                         \"<p>Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!</p>\").arg( reasons[status] ) );\n        }\n    }\n    else if ( state == FirstRunWizard::BootstrapStarted )\n    {\n        ui.description->setText( tr( \"<p>Now you're ready to get started! Just click <strong>Finish</strong> and start exploring.</p>\"\n                                     \"<p>We're still importing your listening history and it will be added to your Last.fm profile soon.</p>\"\n                                     \"<p>Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!</p>\") );\n    }\n    else\n    {\n        ui.description->setText( tr( \"<p>Now you're ready to get started! Just click <strong>Finish</strong> and start exploring.</p>\"\n                                     \"<p>Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!</p>\") );\n    }\n}\n\nvoid\nTourFinishPage::initializePage()\n{\n    setTitle( tr( \"That's it, you're good to go!\" ) );\n\n    setDescription( wizard()->bootstrapState(), wizard()->bootstrapStatus() );\n\n    wizard()->setButton( FirstRunWizard::FinishButton, tr( \"Finish\" ) );\n\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n}\n\nvoid\nTourFinishPage::cleanupPage()\n{\n}\n\n\nvoid\nTourFinishPage::onBootstrapDone( AbstractBootstrapper::BootstrapStatus status )\n{\n    setDescription( FirstRunWizard::BootstrapFinished, status);\n}\n\n\n"
  },
  {
    "path": "app/client/Wizard/TourFinishPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TOURFINISHPAGE_H\n#define TOURFINISHPAGE_H\n\n#include \"WizardPage.h\"\n#include \"../Bootstrapper/AbstractBootstrapper.h\"\n#include \"FirstRunWizard.h\"\n\nclass TourFinishPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    explicit TourFinishPage();\n\nprivate slots:\n    void onBootstrapDone( AbstractBootstrapper::BootstrapStatus status );\n\nprivate:\n    void setDescription( FirstRunWizard::BootstrapState state, AbstractBootstrapper::BootstrapStatus status );\n    void initializePage();\n    void cleanupPage();\n};\n\n#endif // TOURFINISHPAGE_H\n"
  },
  {
    "path": "app/client/Wizard/TourLocationPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"TourLocationPage.h\"\n#include <QTimer>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QBoxLayout>\n\n#include \"FirstRunWizard.h\"\n#include \"../Application.h\"\n#include \"../Widgets/PointyArrow.h\"\n\nTourLocationPage::TourLocationPage()\n    :m_flash( true )\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n#ifdef Q_OS_MAC\n    ui.image->setObjectName( \"imagemac\" );\n#else\n    ui.image->setObjectName( \"imagewin\" );\n#endif\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.</p>\"\n                                                        \"<p>Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.</p>\" ), this ),\n                         0,\n                         Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nTourLocationPage::~TourLocationPage()\n{\n    if ( m_flashTimer )\n        m_flashTimer->stop();\n\n    if ( !m_normalIcon.isNull() )\n        aApp->tray()->setIcon( m_normalIcon );\n\n    delete m_arrow;\n}\n\n\nvoid\nTourLocationPage::initializePage()\n{\n    delete m_arrow;\n    m_arrow = new PointyArrow;\n    delete m_flashTimer;\n    m_flashTimer = new QTimer(this);\n    m_flashTimer->setInterval( 300 );\n    connect( m_flashTimer, SIGNAL(timeout()), SLOT(flashSysTray()));\n\n#ifdef Q_OS_MAC\n    setTitle( tr( \"The Last.fm Desktop App in your menu bar\" ) );\n    ui.image->setPixmap( QPixmap( \":/graphic_location_MAC.png\" ) );\n#else\n    setTitle( tr( \"The Last.fm Desktop App in your system tray\" ) );\n    ui.image->setPixmap( QPixmap( \":/graphic_location_WIN.png\" ) );\n#endif\n\n    QSystemTrayIcon* tray = aApp->tray();\n    m_arrow->pointAt( QPoint( tray->geometry().left() + (tray->geometry().width() / 2.0f ), tray->geometry().top() + (tray->geometry().height() / 2.0f ) ));\n    m_flashTimer->start();\n    m_normalIcon = tray->icon();\n    m_transparentIcon = QPixmap( \":22x22_transparent.png\" ).scaled( m_normalIcon.availableSizes().first());\n    m_flash = false;\n\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n}\n\nvoid\nTourLocationPage::cleanupPage()\n{\n    delete m_arrow;\n    delete m_flashTimer;\n    aApp->tray()->setIcon( m_normalIcon );\n}\n\nvoid\nTourLocationPage::flashSysTray()\n{\n    QSystemTrayIcon* tray = aApp->tray();\n\n    if( m_flash )\n        tray->setIcon( m_transparentIcon );\n    else\n        tray->setIcon( m_normalIcon );\n\n    m_flash = !m_flash;\n}\n"
  },
  {
    "path": "app/client/Wizard/TourLocationPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TOUR_LOCATION_PAGE_H\n#define TOUR_LOCATION_PAGE_H\n\n#include \"WizardPage.h\"\n#include <QIcon>\n#include <QPointer>\n\nclass PointyArrow;\n\nclass TourLocationPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    TourLocationPage();\n    ~TourLocationPage();\n\n    void initializePage();\n    void cleanupPage();\n\nprotected slots:\n    void flashSysTray();\n\nprivate:\n    QPointer<PointyArrow> m_arrow;\n    QPointer<QTimer> m_flashTimer;\n    QIcon m_transparentIcon;\n    QIcon m_normalIcon;\n    bool m_flash;\n};\n\n#endif // TOUR_METADATA_PAGE_H\n\n"
  },
  {
    "path": "app/client/Wizard/TourMetadataPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"TourMetadataPage.h\"\n#include <QTimer>\n#include <QLabel>\n#include <QLayout>\n#include <QPixmap>\n#include <QBoxLayout>\n\n#include \"FirstRunWizard.h\"\n#include \"../Application.h\"\n#include \"../Widgets/PointyArrow.h\"\n\nTourMetadataPage::TourMetadataPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>Find out more about the music you're listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.</p>\"\n                                                          \"<p>Check out the <strong>Now Playing</strong> tab, or simply click on any track in your <strong>Scrobbles</strong> tab to learn more.</p>\"), this ),\n                         0,\n                         Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nvoid \nTourMetadataPage::initializePage()\n{\n    setTitle( tr( \"Discover more about the artists you love\" ) );\n\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n    wizard()->setButton( FirstRunWizard::SkipButton, tr( \"Skip Tour >>\" ) );\n}\n\nvoid\nTourMetadataPage::cleanupPage()\n{\n}\n"
  },
  {
    "path": "app/client/Wizard/TourMetadataPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TOUR_METADATA_PAGE_H\n#define TOUR_METADATA_PAGE_H\n\n#include \"WizardPage.h\"\n#include <QIcon>\n\nclass TourMetadataPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    TourMetadataPage();\n\nprivate:\n    void initializePage();\n    void cleanupPage();\n};\n\n#endif // TOUR_METADATA_PAGE_H\n\n"
  },
  {
    "path": "app/client/Wizard/TourScrobblesPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QHBoxLayout>\n#include <QLabel>\n\n#include \"FirstRunWizard.h\"\n#include \"TourScrobblesPage.h\"\n\nTourScrobblesPage::TourScrobblesPage()\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 20 );\n\n    layout->addWidget( ui.image = new QLabel( this ), 0, Qt::AlignTop | Qt::AlignHCenter );\n    ui.image->setObjectName( \"image\" );\n    layout->addWidget( ui.description = new QLabel( tr( \"<p>The desktop client runs in the background, quietly updating your Last.fm profile with the music you're playing, which you can use to get music recommendations, gig tips and more. </p>\"\n                                                        \"<p>You can also use the Last.fm Desktop App to find out more about the artist you're listening to, and to play personalised radio.</p>\"), this ),\n                         0,\n                         Qt::AlignTop);\n    ui.description->setObjectName( \"description\" );\n    ui.description->setWordWrap( true );\n}\n\n\nvoid\nTourScrobblesPage::initializePage()\n{\n    setTitle( tr( \"Welcome to the Last.fm Desktop App!\" ) );\n\n    wizard()->setButton( FirstRunWizard::NextButton, tr( \"Continue\" ) );\n    if ( wizard()->canGoBack() )\n        wizard()->setButton( FirstRunWizard::BackButton, tr( \"<< Back\" ) );\n    wizard()->setButton( FirstRunWizard::SkipButton, tr( \"Skip Tour >>\" ) );\n}\n\nvoid\nTourScrobblesPage::cleanupPage()\n{\n}\n"
  },
  {
    "path": "app/client/Wizard/TourScrobblesPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef TOURSCROBBLESPAGE_H\n#define TOURSCROBBLESPAGE_H\n\n#include \"WizardPage.h\"\n\nclass TourScrobblesPage : public WizardPage\n{\n    Q_OBJECT\nprivate:\n    struct\n    {\n        class QLabel* image;\n        class QLabel* description;\n    } ui;\n\npublic:\n    explicit TourScrobblesPage();\n\nprivate:\n    void initializePage();\n    void cleanupPage();\n};\n\n#endif // TOURSCROBBLESPAGE_H\n"
  },
  {
    "path": "app/client/Wizard/WizardPage.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"FirstRunWizard.h\"\n\n#include \"WizardPage.h\"\n\nWizardPage::WizardPage()\n{\n}\n\nbool\nWizardPage::validatePage()\n{\n    return true;\n}\n\n\nvoid\nWizardPage::setTitle( const QString &title )\n{\n    wizard()->setTitle( title );\n}\n\nvoid\nWizardPage::setWizard( FirstRunWizard* wizard )\n{\n    m_wizard = wizard;\n}\n\nFirstRunWizard*\nWizardPage::wizard() const\n{\n    return m_wizard;\n}\n"
  },
  {
    "path": "app/client/Wizard/WizardPage.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef WIZARDPAGE_H\n#define WIZARDPAGE_H\n\n#include <QWidget>\n\nclass FirstRunWizard;\n\nclass WizardPage : public QWidget\n{\n    Q_OBJECT\npublic:\n    explicit WizardPage();\n\n    void setWizard( FirstRunWizard* wizard );\n\n    virtual void initializePage() = 0;\n    virtual bool validatePage();\n    virtual void cleanupPage() = 0;\n\n    void setTitle( const QString& title );\n\nprotected:\n    FirstRunWizard* wizard() const;\n\nprivate:\n    FirstRunWizard* m_wizard;\n};\n\n#endif // WIZARDPAGE_H\n"
  },
  {
    "path": "app/client/audioscrobbler.rc",
    "content": "IDI_ICON1  ICON DISCARDABLE \"audioscrobbler.ico\"\n\n#include <winver.h>\n\n// Get updates from this appcast feed:\nFeedURL     APPCAST     {\"https://cdn.last.fm/client/Win/updates.xml\"}\n\n// Version information; this, too, is used by WinSparkle\n1 VERSIONINFO\n FILEVERSION     2,1,36,0\n PRODUCTVERSION  2,1,36,0\n FILEFLAGSMASK   VS_FFI_FILEFLAGSMASK\n FILEFLAGS       0\n FILEOS          VOS_NT_WINDOWS32\n FILETYPE        VFT_APP\n FILESUBTYPE     VFT2_UNKNOWN\nBEGIN\n    BLOCK \"StringFileInfo\"\n    BEGIN\n        BLOCK \"040904B0\" // US English, Unicode\n        BEGIN\n            VALUE \"Comments\", \"Last.fm\\0\"\n            VALUE \"CompanyName\", \"Last.fm\\0\"\n            VALUE \"FileDescription\", \"Last.fm\\0\"\n            VALUE \"FileVersion\", \"2.1.36\\0\"\n            VALUE \"InternalName\", \"Last.fm\\0\"\n            VALUE \"OriginalFilename\", \"Last.fm.exe\\0\"\n            VALUE \"LegalCopyright\", \"Public Domain\\0\"\n            VALUE \"ProductName\", \"Last.fm\\0\"\n            VALUE \"ProductVersion\", \"2.1.36\\0\"\n        END\n    END\n\n    BLOCK \"VarFileInfo\"\n    BEGIN\n        VALUE \"Translation\", 0x0409, 0x04B0\n    END\nEND"
  },
  {
    "path": "app/client/client.pro",
    "content": "TEMPLATE = app\nTARGET = \"Last.fm Scrobbler\"\nunix:!mac {\n    TARGET = lastfm-scrobbler\n}\nVERSION = 2.1.39\nDEFINES += APP_VERSION=\\\\\\\"$$VERSION\\\\\\\"\nQT = core gui xml network sql\nCONFIG += lastfm unicorn listener logger phonon analytics\nwin32:LIBS += user32.lib kernel32.lib psapi.lib\nDEFINES += LASTFM_COLLAPSE_NAMESPACE\n\nmacx:LIBS += -weak_framework Cocoa\nwin32:release {\n        LIBS += -lAdvAPI32\n}\n\ninclude( ../../admin/include.qmake )\n\nDEFINES += LASTFM_COLLAPSE_NAMESPACE\nSOURCES -= LegacyTuner.cpp\nHEADERS -= LegacyTuner.h\n\nmacx:ICON = ./audioscrobbler.icns\n!win32:LIBS += -lz\nwin32:LIBS += shell32.lib User32.lib\n\nRC_FILE = audioscrobbler.rc\nunix:!mac {\n        CONFIG += link_pkgconfig\n        PKGCONFIG += libgpod-1.0\n}\n\nSUBDIRS=PrefPane\n\nSOURCES += \\\n    AudioscrobblerSettings.cpp \\\n    Application.cpp \\\n    ScrobSocket.cpp \\\n    MediaDevices/MediaDevice.cpp \\\n    MediaDevices/IpodDevice.cpp \\\n    MediaDevices/DeviceScrobbler.cpp \\\n    MainWindow.cpp \\\n    main.cpp \\\n    Settings/SettingsWidget.cpp \\\n    Settings/ScrobbleSettingsWidget.cpp \\\n    Settings/IpodSettingsWidget.cpp \\\n    Settings/AccountSettingsWidget.cpp \\\n    Settings/PreferencesDialog.cpp \\\n    Settings/AdvancedSettingsWidget.cpp \\\n    Settings/GeneralSettingsWidget.cpp \\\n    Services/ScrobbleService/StopWatch.cpp \\\n    Services/ScrobbleService/ScrobbleService.cpp \\\n    Dialogs/DiagnosticsDialog.cpp \\\n    Bootstrapper/PluginBootstrapper.cpp \\\n    Bootstrapper/ITunesDevice/itunesdevice.cpp \\\n    Bootstrapper/iTunesBootstrapper.cpp \\\n    Bootstrapper/AbstractFileBootstrapper.cpp \\\n    Bootstrapper/AbstractBootstrapper.cpp \\\n    Widgets/TitleBar.cpp \\\n    Widgets/StatusBar.cpp \\\n    Widgets/SideBar.cpp \\\n    Widgets/NothingPlayingWidget.cpp \\\n    Widgets/NowPlayingStackedWidget.cpp \\\n    Widgets/ProfileWidget.cpp \\\n    Widgets/FriendListWidget.cpp \\\n    Widgets/FriendWidget.cpp \\\n    Widgets/BioWidget.cpp \\\n    Widgets/MetadataWidget.cpp \\\n    Widgets/TagWidget.cpp \\\n    Widgets/ShortcutEdit.cpp \\\n    Widgets/ProfileArtistWidget.cpp \\\n    Widgets/ScrobbleControls.cpp \\\n    Widgets/PointyArrow.cpp \\\n    Widgets/PlaybackControlsWidget.cpp \\\n    Widgets/NowPlayingWidget.cpp \\\n    Widgets/RefreshButton.cpp \\\n    Widgets/WidgetTextObject.cpp \\\n    Wizard/LoginPage.cpp \\\n    Wizard/BootstrapPage.cpp \\\n    Wizard/FirstRunWizard.cpp \\\n    Wizard/AccessPage.cpp \\\n    Wizard/TourMetadataPage.cpp \\\n    Wizard/PluginsPage.cpp \\\n    Wizard/TourFinishPage.cpp \\\n    Wizard/PluginsInstallPage.cpp \\\n    Wizard/BootstrapProgressPage.cpp \\\n    Wizard/TourScrobblesPage.cpp \\\n    Wizard/TourLocationPage.cpp \\\n    Wizard/WizardPage.cpp \\\n    Widgets/ContextLabel.cpp \\\n    Widgets/SimilarArtistWidget.cpp \\\n    Widgets/PushButton.cpp \\\n    Widgets/TrackWidget.cpp \\\n    Dialogs/LicensesDialog.cpp \\\n    Widgets/ScrobblesWidget.cpp \\\n    Widgets/ScrobblesListWidget.cpp \\\n    Services/AnalyticsService/AnalyticsService.cpp \\\n    Services/AnalyticsService/PersistentCookieJar.cpp \\\n    Settings/CheckFileSystemModel.cpp \\\n    Settings/CheckFileSystemView.cpp \\\n\nHEADERS += \\\n    ScrobSocket.h \\\n    AudioscrobblerSettings.h \\\n    Application.h \\\n    MainWindow.h \\\n    Services/ScrobbleService.h \\\n    Services/ScrobbleService/StopWatch.h \\\n    Services/ScrobbleService/ScrobbleService.h \\\n    MediaDevices/MediaDevice.h \\\n    MediaDevices/IpodDevice.h \\\n    MediaDevices/DeviceScrobbler.h \\\n    Dialogs/DiagnosticsDialog.h \\\n    Bootstrapper/PluginBootstrapper.h \\\n    Bootstrapper/ITunesDevice/MediaDeviceInterface.h \\\n    Bootstrapper/ITunesDevice/ITunesParser.h \\\n    Bootstrapper/ITunesDevice/itunesdevice.h \\\n    Bootstrapper/iTunesBootstrapper.h \\\n    Bootstrapper/AbstractFileBootstrapper.h \\\n    Bootstrapper/AbstractBootstrapper.h \\\n    Settings/SettingsWidget.h \\\n    Settings/ScrobbleSettingsWidget.h \\\n    Settings/PreferencesDialog.h \\\n    Settings/AdvancedSettingsWidget.h \\\n    Settings/GeneralSettingsWidget.h \\\n    Settings/IpodSettingsWidget.h \\\n    Settings/AccountSettingsWidget.h \\\n    Widgets/ShortcutEdit.h \\\n    Widgets/TitleBar.h \\\n    Widgets/StatusBar.h \\\n    Widgets/SideBar.h \\\n    Widgets/ScrobbleControls.h \\\n    Widgets/PointyArrow.h \\\n    Widgets/PlaybackControlsWidget.h \\\n    Widgets/NowPlayingWidget.h \\\n    Widgets/NothingPlayingWidget.h \\\n    Widgets/NowPlayingStackedWidget.h \\\n    Widgets/ProfileWidget.h \\\n    Widgets/FriendListWidget.h \\\n    Widgets/FriendWidget.h \\\n    Widgets/BioWidget.h \\\n    Widgets/MetadataWidget.h \\\n    Widgets/TagWidget.h \\\n    Widgets/ProfileArtistWidget.h \\\n    Widgets/RefreshButton.h \\\n    Widgets/WidgetTextObject.h \\\n    Wizard/AccessPage.h \\\n    Wizard/TourMetadataPage.h \\\n    Wizard/PluginsPage.h \\\n    Wizard/TourFinishPage.h \\\n    Wizard/PluginsInstallPage.h \\\n    Wizard/BootstrapProgressPage.h \\\n    Wizard/TourScrobblesPage.h \\\n    Wizard/TourLocationPage.h \\\n    Wizard/LoginPage.h \\\n    Wizard/FirstRunWizard.h \\\n    Wizard/BootstrapPage.h \\\n    Wizard/WizardPage.h \\\n    Widgets/ContextLabel.h \\\n    Widgets/SimilarArtistWidget.h \\\n    Widgets/PushButton.h \\\n    Widgets/TrackWidget.h \\\n    Dialogs/LicensesDialog.h \\\n    Widgets/ScrobblesListWidget.h \\\n    Widgets/ScrobblesWidget.h \\\n    Services/AnalyticsService.h \\\n    Services/AnalyticsService/AnalyticsService.h \\\n    Services/AnalyticsService/PersistentCookieJar.h \\\n    Settings/CheckFileSystemModel.h \\\n    Settings/CheckFileSystemView.h \\\n\nmac:HEADERS += CommandReciever/CommandReciever.h \\\n\nmac:OBJECTIVE_SOURCES += CommandReciever/CommandReciever.mm \\\n                            Widgets/NothingPlayingWidget_mac.mm \\\n\nFORMS += \\\n    Widgets/PlaybackControlsWidget.ui \\\n    Dialogs/DiagnosticsDialog.ui \\\n    Widgets/MetadataWidget.ui \\\n    Settings/PreferencesDialog.ui \\\n    Settings/GeneralSettingsWidget.ui \\\n    Settings/AccountSettingsWidget.ui \\\n    Settings/IpodSettingsWidget.ui \\\n    Settings/ScrobbleSettingsWidget.ui \\\n    Settings/AdvancedSettingsWidget.ui \\\n    Wizard/FirstRunWizard.ui \\\n    Widgets/NothingPlayingWidget.ui \\\n    Widgets/FriendWidget.ui \\\n    Widgets/FriendListWidget.ui \\\n    Widgets/TrackWidget.ui \\\n    Dialogs/LicensesDialog.ui \\\n    Widgets/ScrobblesWidget.ui \\\n    Widgets/ProfileWidget.ui \\\n\nunix:!mac {\n    CONFIG += qdbus\n\n    SOURCES += MediaDevices/IpodDevice_linux.cpp \\\n               Mpris2/Mpris2.cpp \\\n               Mpris2/DBusAbstractAdaptor.cpp \\\n               Mpris2/MediaPlayer2.cpp \\\n               Mpris2/MediaPlayer2Player.cpp\n\n    HEADERS += MediaDevices/IpodDevice_linux.h \\\n               Mpris2/Mpris2.h \\\n               Mpris2/DBusAbstractAdaptor.h \\\n               Mpris2/MediaPlayer2.h \\\n               Mpris2/MediaPlayer2Player.h\n}\n\nRESOURCES += \\\n    qrc/audioscrobbler.qrc\n\nunix:!mac {\n        target.path = $$BINDIR\n\n        css.files = 'Last.fm Scrobbler.css'\n        css.path  = $$DATADIR/lastfm-scrobbler\n\n        desktop.files += lastfm-scrobbler.desktop\n        desktop.path = $$DATADIR/applications\n\n        icon16.files += icons/16x16/lastfm-scrobbler.png\n        icon16.path = $$DATADIR/icons/hicolor/16x16/apps\n        icon22.files += icons/22x22/lastfm-scrobbler.png\n        icon22.path = $$DATADIR/icons/hicolor/22x22/apps\n        icon32.files += icons/32x32/lastfm-scrobbler.png\n        icon32.path = $$DATADIR/icons/hicolor/32x32/apps\n        icon48.files += icons/48x48/lastfm-scrobbler.png\n        icon48.path = $$DATADIR/icons/hicolor/48x48/apps\n        icon64.files += icons/64x64/lastfm-scrobbler.png\n        icon64.path = $$DATADIR/icons/hicolor/64x64/apps\n        icon128.files += icons/128x128/lastfm-scrobbler.png\n        icon128.path = $$DATADIR/icons/hicolor/128x128/apps\n\n        INSTALLS += target css icon16 icon22 icon32 icon48 icon64 icon128 desktop\n}\n"
  },
  {
    "path": "app/client/lastfm-scrobbler.desktop",
    "content": "[Desktop Entry]\nVersion=1.0\nName=Last.fm Scrobbler\nComment=Listen to Last.fm radio\nExec=lastfm-scrobbler %u\nIcon=lastfm-scrobbler\nTerminal=false\nType=Application\nMimeType=x-scheme-handler/lastfm;\nCategories=Qt;AudioVideo;Audio;Player;\nX-KDE-Protocols=lastfm\nStartupNotify=true\nKeywords=Player;Audio;\n"
  },
  {
    "path": "app/client/main.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QtGlobal>\n\n#ifdef Q_OS_MAC64\n    #include <Carbon/Carbon.h>\n    static pascal OSErr appleEventHandler( const AppleEvent*, AppleEvent*, void* );\n#elif defined Q_OS_MAC32\n    #include </System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/AE.framework/Versions/A/Headers/AppleEvents.h>\n    static pascal OSErr appleEventHandler( const AppleEvent*, AppleEvent*, long );\n#endif\n\n#include <QShortcut>\n#include <QKeySequence>\n#include <QStringList>\n#include <QRegExp>\n\n#include \"Application.h\"\n#include \"ScrobSocket.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/qtsingleapplication/qtsinglecoreapplication.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"Services/ScrobbleService.h\"\n\n#include \"lib/unicorn/CrashReporter/CrashReporter.h\"\n\nvoid cleanup();\n\n\nnamespace lastfm\n{\n    extern LASTFM_DLLEXPORT QByteArray UserAgent;\n}\n\nint main( int argc, char** argv )\n{\n    //unicorn::CrashReporter* crashReporter = new unicorn::CrashReporter;\n\n    QtSingleCoreApplication::setApplicationName( \"Last.fm Scrobbler\" );\n    QtSingleCoreApplication::setOrganizationName( \"Last.fm\" );\n    QtSingleCoreApplication::setApplicationVersion( APP_VERSION );\n\n    // ATTENTION! Under no circumstance change these strings! --mxcl\n#ifdef WIN32\n    lastfm::UserAgent = \"Last.fm Client \" APP_VERSION \" (Windows)\";\n#elif __APPLE__\n    lastfm::UserAgent = \"Last.fm Client \" APP_VERSION \" (OS X)\";\n#elif defined (Q_WS_X11)\n    lastfm::UserAgent = \"Last.fm Client \" APP_VERSION \" (X11)\";\n#endif\n\n    try\n    {\n        audioscrobbler::Application app( argc, argv );\n\n#ifdef Q_OS_WIN32\n        QStringList args = app.arguments();\n#else\n        QStringList args = app.arguments().mid( 1 );\n#endif\n\n        if ( !args.contains( \"--new\" ) )\n        {\n            if ( app.sendMessage( args ) || args.contains(\"--exit\") )\n                return 0;\n\n            // It's possible that we were unable to send the\n            // message, but the app is actually running\n            if ( app.isRunning() )\n                return 0;\n\n        }\n\n        qAddPostRoutine(cleanup);\n\n#ifdef Q_OS_MAC\n        AEEventHandlerUPP h = NewAEEventHandlerUPP( appleEventHandler );\n        AEInstallEventHandler( 'GURL', 'GURL', h, 0, false );\n#endif\n\n        app.init();\n        app.parseArguments( args );\n        return app.exec();\n    }\n    catch (std::exception& e)\n    {\n        qDebug() << \"unhandled exception \" << e.what();\n    }\n    catch (unicorn::Application::StubbornUserException&)\n    {\n        // user wouldn't log in\n        return 0;\n    }\n\n    //delete crashReporter;\n}\n\n#ifdef Q_OS_MAC\n#ifdef Q_OS_MAC64\nstatic pascal OSErr appleEventHandler( const AppleEvent* e, AppleEvent*, void* )\n#elif defined Q_OS_MAC32\nstatic pascal OSErr appleEventHandler( const AppleEvent* e, AppleEvent*, long )\n#endif //Q_OS_MAC64/32\n\n{\n    OSType id = typeWildCard;\n    AEGetAttributePtr( e, keyEventIDAttr, typeType, 0, &id, sizeof(id), 0 );\n    \n    switch (id)\n    {       \n        default:\n            return unimpErr;\n    }\n}\n#endif //Q_OS_MAC\n\n\nvoid cleanup()\n{\n}\n"
  },
  {
    "path": "app/client/qrc/audioscrobbler.qrc",
    "content": "<RCC>\n    <qresource prefix=\"/\">\n        <file>loading_meta.gif</file>\n        <file>icon_eq.gif</file>\n        <file>radio_eq_small.gif</file>\n        <file alias=\"pointyarrow.png\">wizard/arrow_even_bigger_than_dropbox.png</file>\n        <file alias=\"bg_clouds.png\">wizard/bg_clouds.png</file>\n        <file alias=\"button_grey_LEFT_HOVER.png\">wizard/button_grey_LEFT_HOVER.png</file>\n        <file alias=\"button_grey_LEFT_REST.png\">wizard/button_grey_LEFT_REST.png</file>\n        <file alias=\"button_grey_MIDDLE_HOVER.png\">wizard/button_grey_MIDDLE_HOVER.png</file>\n        <file alias=\"button_grey_MIDDLE_REST.png\">wizard/button_grey_MIDDLE_REST.png</file>\n        <file alias=\"button_grey_RIGHT_HOVER.png\">wizard/button_grey_RIGHT_HOVER.png</file>\n        <file alias=\"button_grey_RIGHT_REST.png\">wizard/button_grey_RIGHT_REST.png</file>\n        <file alias=\"button_red_LEFT_HOVER.png\">wizard/button_red_LEFT_HOVER.png</file>\n        <file alias=\"button_red_LEFT_REST.png\">wizard/button_red_LEFT_REST.png</file>\n        <file alias=\"button_red_MIDDLE_HOVER.png\">wizard/button_red_MIDDLE_HOVER.png</file>\n        <file alias=\"button_red_MIDDLE_REST.png\">wizard/button_red_MIDDLE_REST.png</file>\n        <file alias=\"button_red_RIGHT_HOVER.png\">wizard/button_red_RIGHT_HOVER.png</file>\n        <file alias=\"button_red_RIGHT_REST.png\">wizard/button_red_RIGHT_REST.png</file>\n        <file alias=\"graphic_access.png\">wizard/graphic_access.png</file>\n        <file alias=\"graphic_connect.png\">wizard/graphic_connect.png</file>\n        <file alias=\"graphic_finish.png\">wizard/graphic_finish.png</file>\n        <file alias=\"graphic_import_foobar.png\">wizard/graphic_import_foobar.png</file>\n        <file alias=\"graphic_import_itunes.png\">wizard/graphic_import_itunes.png</file>\n        <file alias=\"graphic_import_winamp.png\">wizard/graphic_import_winamp.png</file>\n        <file alias=\"graphic_import_wmp.png\">wizard/graphic_import_wmp.png</file>\n        <file alias=\"graphic_importing.png\">wizard/graphic_importing.gif</file>\n        <file alias=\"graphic_location_MAC.png\">wizard/graphic_location_MAC.png</file>\n        <file alias=\"graphic_location_WIN.png\">wizard/graphic_location_WIN.png</file>\n        <file alias=\"graphic_metadata.png\">wizard/graphic_metadata.png</file>\n        <file alias=\"graphic_plugins.png\">wizard/graphic_plugins.png</file>\n        <file alias=\"graphic_radio.png\">wizard/graphic_radio.png</file>\n        <file alias=\"graphic_scrobbles.png\">wizard/graphic_scrobbles.png</file>\n        <file alias=\"player_foobar_64.png\">wizard/player_foobar_64.png</file>\n        <file alias=\"player_itunes_64.png\">wizard/player_itunes_64.png</file>\n        <file alias=\"player_winamp_64.png\">wizard/player_winamp_64.png</file>\n        <file alias=\"player_wmp_64.png\">wizard/player_wmp_64.png</file>\n        <file alias=\"scrobbler_32.png\">wizard/lastfm_icon_32.png</file>\n        <file alias=\"scrobbler_64.png\">wizard/lastfm_icon_64.png</file>\n        <file>button_LEFT_HOVER.png</file>\n        <file>button_LEFT_PRESS.png</file>\n        <file>button_LEFT_REST.png</file>\n        <file>button_MIDDLE_HOVER.png</file>\n        <file>button_MIDDLE_PRESS.png</file>\n        <file>button_MIDDLE_REST.png</file>\n        <file>button_RIGHT_HOVER.png</file>\n        <file>button_RIGHT_PRESS.png</file>\n        <file>button_RIGHT_REST.png</file>\n        <file>message_close.png</file>\n        <file>message_error.png</file>\n        <file>message_info.png</file>\n        <file>start_bg.png</file>\n        <file>user_default.png</file>\n        <file>meta_album_no_art.png</file>\n        <file>meta_artist_no_photo.png</file>\n        <file>scrobbles_refresh.png</file>\n        <file>tab_now_playing_REST.png</file>\n        <file>tab_now_playing_HOVER.png</file>\n        <file>tab_now_playing_ACTIVE.png</file>\n        <file>tab_scrobbles_REST.png</file>\n        <file>tab_scrobbles_HOVER.png</file>\n        <file>tab_scrobbles_ACTIVE.png</file>\n        <file>tab_profile_REST.png</file>\n        <file>tab_profile_HOVER.png</file>\n        <file>tab_profile_ACTIVE.png</file>\n        <file>tab_friends_REST.png</file>\n        <file>tab_friends_HOVER.png</file>\n        <file>tab_friends_ACTIVE.png</file>\n        <file>tab_radio_REST.png</file>\n        <file>tab_radio_HOVER.png</file>\n        <file>tab_radio_ACTIVE.png</file>\n        <file>radio_play_small_REST.png</file>\n        <file>radio_play_small_HOVER.png</file>\n        <file>radio_play_small_PRESS.png</file>\n        <file>radio_play_large_REST.png</file>\n        <file>radio_play_large_HOVER.png</file>\n        <file>radio_play_large_PRESS.png</file>\n        <file>radio_library_REST.png</file>\n        <file>radio_library_HOVER.png</file>\n        <file>radio_library_PRESS.png</file>\n        <file>radio_mix_REST.png</file>\n        <file>radio_mix_HOVER.png</file>\n        <file>radio_mix_PRESS.png</file>\n        <file>radio_rec_REST.png</file>\n        <file>radio_rec_HOVER.png</file>\n        <file>radio_rec_PRESS.png</file>\n        <file>radio_friends_REST.png</file>\n        <file>radio_friends_HOVER.png</file>\n        <file>radio_friends_PRESS.png</file>\n        <file>control_bar_back.png</file>\n        <file>control_bar_scrobble_foobar.png</file>\n        <file>control_bar_scrobble_itunes.png</file>\n        <file>control_bar_scrobble_applemusic.png</file>\n        <file>control_bar_scrobble_winamp.png</file>\n        <file>control_bar_scrobble_wmp.png</file>\n        <file>control_bar_scrobble_spotify.png</file>\n        <file>controls_love_OFF_REST.png</file>\n        <file>controls_love_OFF_HOVER.png</file>\n        <file>controls_love_OFF_PRESS.png</file>\n        <file>controls_love_ON_REST.png</file>\n        <file>controls_love_ON_HOVER.png</file>\n        <file>controls_love_ON_PRESS.png</file>\n        <file>scrobble_marker_OFF.png</file>\n        <file>scrobble_marker_ON.png</file>\n        <file>controls_ban_REST.png</file>\n        <file>controls_ban_HOVER.png</file>\n        <file>controls_ban_PRESS.png</file>\n        <file>controls_play_REST.png</file>\n        <file>controls_play_HOVER.png</file>\n        <file>controls_play_PRESS.png</file>\n        <file>controls_pause_REST.png</file>\n        <file>controls_pause_HOVER.png</file>\n        <file>controls_pause_PRESS.png</file>\n        <file>controls_skip_REST.png</file>\n        <file>controls_skip_HOVER.png</file>\n        <file>controls_skip_PRESS.png</file>\n        <file>meta_context_arrow.png</file>\n        <file>meta_buy_HOVER.png</file>\n        <file>meta_buy_PRESS.png</file>\n        <file>meta_buy_REST.png</file>\n        <file>meta_love_OFF_HOVER.png</file>\n        <file>meta_love_OFF_PRESS.png</file>\n        <file>meta_love_OFF_REST.png</file>\n        <file>meta_love_ON_HOVER.png</file>\n        <file>meta_love_ON_PRESS.png</file>\n        <file>meta_love_ON_REST.png</file>\n        <file>meta_share_HOVER.png</file>\n        <file>meta_share_PRESS.png</file>\n        <file>meta_share_REST.png</file>\n        <file>meta_tag_HOVER.png</file>\n        <file>meta_tag_PRESS.png</file>\n        <file>meta_tag_REST.png</file>\n        <file>meta_tag_LEFT_HOVER.png</file>\n        <file>meta_tag_LEFT_REST.png</file>\n        <file>meta_tag_MIDDLE_HOVER.png</file>\n        <file>meta_tag_MIDDLE_REST.png</file>\n        <file>meta_tag_RIGHT_HOVER.png</file>\n        <file>meta_tag_RIGHT_REST.png</file>\n        <file>meta_radio_LEFT_HOVER.png</file>\n        <file>meta_radio_LEFT_PRESS.png</file>\n        <file>meta_radio_LEFT_REST.png</file>\n        <file>meta_radio_MIDDLE_HOVER.png</file>\n        <file>meta_radio_MIDDLE_PRESS.png</file>\n        <file>meta_radio_MIDDLE_REST.png</file>\n        <file>meta_radio_RIGHT_HOVER.png</file>\n        <file>meta_radio_RIGHT_PRESS.png</file>\n        <file>meta_radio_RIGHT_REST.png</file>\n        <file>16x16.png</file>\n        <file>22x22.png</file>\n        <file>22x22_transparent.png</file>\n        <file>systray_icon_rest_mac.png</file>\n        <file>systray_icon_pressed_mac.png</file>\n        <file alias=\"tag-rest.png\">tag_29x29_rest.png</file>\n        <file alias=\"tag-onhover.png\">tag_29x29_hover.png</file>\n        <file alias=\"tag-onpress.png\">tag_29x29_pressed.png</file>\n        <file alias=\"tag-disabled.png\">tag_29x29_disabled.png</file>\n        <file alias=\"share-rest.png\">share_29x29_rest.png</file>\n        <file alias=\"share-onhover.png\">share_29x29_hover.png</file>\n        <file alias=\"share-onpress.png\">share_29x29_pressed.png</file>\n        <file alias=\"share-disabled.png\">share_29x29_disabled.png</file>\n        <file alias=\"delete.png\">delete.png</file>\n        <file>asterisk_small.png</file>\n        <file>as.png</file>\n        <file>highlight.png</file>\n        <file>titlebar_highlight.png</file>\n        <file>slider_nubbin.png</file>\n        <file>settings_HOVER.png</file>\n        <file>settings_PRESS.png</file>\n        <file>settings_REST.png</file>\n        <file>volume_knob_REST.png</file>\n        <file>volume_knob_PRESS.png</file>\n        <file alias=\"on-tour.png\">on_tour.png</file>\n        <file alias=\"now-playing.png\">now-playing-REST.png</file>\n        <file alias=\"now-playing-onpress.png\">now-playing-PRESS.png</file>\n        <file alias=\"taskbar-love.png\">taskbar-love-OFF-16x16.png</file>\n        <file alias=\"taskbar-love-on.png\">taskbar-love-ON-16x16.png</file>\n        <file alias=\"taskbar-ban.png\">taskbar-ban-16x16.png</file>\n        <file alias=\"taskbar-info.png\">taskbar-info-16x16.png</file>\n        <file alias=\"taskbar-play.png\">taskbar-play-16x16.png</file>\n        <file alias=\"taskbar-skip.png\">taskbar-skip-16x16.png</file>\n        <file>preferences_devices.png</file>\n        <file>preferences_advanced.png</file>\n        <file>preferences_general.png</file>\n        <file>preferences_scrobbling.png</file>\n        <file>preferences_accounts.png</file>\n        <file>control_bar_radio_as.png</file>\n        <file>scrobble_OFF.png</file>\n        <file>subscribe_bg.png</file>\n        <file>subscribe_radio.png</file>\n        <file>button_dark_LEFT_HOVER.png</file>\n        <file>button_dark_LEFT_PRESS.png</file>\n        <file>button_dark_LEFT_REST.png</file>\n        <file>button_dark_MIDDLE_HOVER.png</file>\n        <file>button_dark_MIDDLE_PRESS.png</file>\n        <file>button_dark_MIDDLE_REST.png</file>\n        <file>button_dark_RIGHT_HOVER.png</file>\n        <file>button_dark_RIGHT_PRESS.png</file>\n        <file>button_dark_RIGHT_REST.png</file>\n        <file>meta_ban_REST.png</file>\n        <file>meta_skip_REST.png</file>\n        <file>lastfm_icon_16_grayscale.png</file>\n        <file>mac_control_bar_as_OFF.png</file>\n        <file>lastfm_icon_22_grayscale.png</file>\n        <file>scrobble_progress_OFF.png</file>\n        <file>scrobble_progress_ON.png</file>\n        <file>volume_high.png</file>\n        <file>volume_low.png</file>\n        <file>volume_mid.png</file>\n        <file>volume_mute.png</file>\n        <file>progress_slot_OFF.png</file>\n        <file>progress_slot_ON.png</file>\n    </qresource>\n</RCC>\n"
  },
  {
    "path": "app/fingerprinter/Fingerprinter.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QCoreApplication>\n#include <QFile>\n#include <QStringList>\n#include <QNetworkReply>\n#include <QEventLoop>\n#include <QDebug>\n#include <QTimer>\n\n#include <lastfm/Fingerprint.h>\n#include <lastfm/FingerprintableSource.h>\n#include <lastfm/Track.h>\n\n#include \"LAV_Source.h\"\n#include \"Fingerprinter.h\"\n\n\nFingerprinter::Fingerprinter( const lastfm::Track& track, QObject* parent )\n    :QObject( parent ), m_fp( track ), m_fpSource( 0 )\n{\n    if ( m_fp.id().isNull() )\n    {\n        m_fpSource = new LAV_Source();\n\n        if ( m_fpSource )\n        {\n            try\n            {\n                m_fp.generate( m_fpSource );\n                connect( m_fp.submit(), SIGNAL(finished()), SLOT(onFingerprintSubmitted()) );\n            }\n            catch ( const lastfm::Fingerprint::Error& error )\n            {\n                qWarning() << \"Fingerprint error: \" << error;\n                QTimer::singleShot(250, qApp, SLOT(quit()));\n            }\n        }\n    }\n    else\n    {\n        qDebug() << \"Already Fingerprinted: \" << m_fp.id();\n\n#ifndef NDEBUG\n        // This code will fetch the suggestions from the fingerprint id, one\n        // day we might do something with this info, like offer corrections\n        connect( m_fp.id().getSuggestions(), SIGNAL(finished()), SLOT(onGotSuggestions()) );\n#else\n        QTimer::singleShot(250, qApp, SLOT(quit()));\n#endif\n    }\n}\n\nFingerprinter::~Fingerprinter()\n{\n    delete m_fpSource;\n}\n\nvoid\nFingerprinter::onFingerprintSubmitted()\n{\n    try\n    {\n        m_fp.decode( static_cast<QNetworkReply*>( sender() ) );\n        qDebug() << \"Fingerprint success: \" << m_fp.id();\n    }\n    catch ( const lastfm::Fingerprint::Error& error )\n    {\n        qWarning() << \"Fingerprint error: \" << error;\n        QTimer::singleShot(250, qApp, SLOT(quit()));\n        return;\n    }\n\n#ifndef NDEBUG\n    // This code will fetch the suggestions from the fingerprint id, one\n    // day we might do something with this info, like offer corrections\n    connect( m_fp.id().getSuggestions(), SIGNAL(finished()), SLOT(onGotSuggestions()) );\n#else\n    QTimer::singleShot(250, qApp, SLOT(quit()));\n#endif\n\n}\n\nvoid\nFingerprinter::onGotSuggestions()\n{\n    QMap<float, Track> suggestions = lastfm::FingerprintId::getSuggestions( static_cast<QNetworkReply*>( sender() ) );\n    qDebug() << suggestions;\n    QTimer::singleShot(250, qApp, SLOT(quit()));\n}\n"
  },
  {
    "path": "app/fingerprinter/Fingerprinter.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd. \n   Copyright 2009 John Stamp <jstamp@users.sourceforge.net>\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QObject>\n\n#include <lastfm/Track.h>\n#include <lastfm/Fingerprint.h>\n\nnamespace lastfm { class FingerprintableSource; }\n\nclass Fingerprinter : public QObject\n{\n    Q_OBJECT\npublic:\n    explicit Fingerprinter( const lastfm::Track& track, QObject* parent = 0 );\n    ~Fingerprinter();\n\nprivate slots:\n    void onFingerprintSubmitted();\n    void onGotSuggestions();\n\nprivate:\n    lastfm::Fingerprint m_fp;\n    lastfm::FingerprintableSource* m_fpSource;\n    lastfm::Track m_track;\n};\n\n\n"
  },
  {
    "path": "app/fingerprinter/LAV_Source.cpp",
    "content": "/*\n * LAV_Source: use FFmpeg/Libav to extract audio for Last.fm fingerprinting\n * Copyright (C) 2012 John Stamp <jstamp@mehercule.net>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"LAV_Source.h\"\n\n// Needed by libavutil/common.h\n#ifndef __STDC_CONSTANT_MACROS\n#define __STDC_CONSTANT_MACROS 1\n#endif\n\n#ifndef AVCODEC_MAX_AUDIO_FRAME_SIZE\n#define AVCODEC_MAX_AUDIO_FRAME_SIZE 192000\n#endif\n\nextern \"C\" {\n#include <libavformat/avformat.h>\n#include <libavutil/mathematics.h>\n#include <libavutil/mem.h>\n\n#if defined(HAVE_SWRESAMPLE)\n# include <libswresample/swresample.h>\n#elif defined (HAVE_AVRESAMPLE)\n# include <libavresample/avresample.h>\n# include <libavutil/opt.h>\n#endif\n}\n\n#include <iostream>\n#include <limits>\n#include <stdexcept>\n\n#include <QFile>\n\n/*\n defining the constant here to avoid using deprecated AVCODEC_MAX_AUDIO_FRAME_SIZE\n*/\n#define MAX_AUDIO_FRAME_SIZE 192000\n\nusing namespace std;\n\n\n/*\n   Don't change these values!\n   The fingerprinter expects signed 16 bit pcm w/ 1 or 2 channels\n*/\nconst AVSampleFormat outSampleFmt = AV_SAMPLE_FMT_S16;\nconst int outSampleSize           = av_get_bytes_per_sample(outSampleFmt);\nconst int outMaxChannels          = 2;\n\n\nclass LAV_SourcePrivate\n{\npublic:\n    LAV_SourcePrivate()\n        : inFormatContext(NULL)\n        , inCodecContext(NULL)\n#if defined(HAVE_SWRESAMPLE) || defined(HAVE_AVRESAMPLE)\n        , resampleContext(NULL)\n#endif\n        , streamIndex(-1)\n        , duration(0)\n        , timestamp(0)\n        , bitrate(0)\n        , eof(false)\n        , overflowSize(0)\n    {\n        outBuffer = (uint8_t*)av_malloc(sizeof(uint8_t)*MAX_AUDIO_FRAME_SIZE*4);\n        outBufferSize = sizeof(uint8_t)*MAX_AUDIO_FRAME_SIZE*4;\n        overflow = (uint8_t*)av_malloc(sizeof(uint8_t)*MAX_AUDIO_FRAME_SIZE*4);\n    }\n\n    ~LAV_SourcePrivate()\n    {\n        av_free(outBuffer);\n        av_free(overflow);\n    }\n\n    uint8_t * decodeOneFrame(int &dataSize, int &channels, int& nSamples);\n\n    AVFormatContext *inFormatContext;\n    AVCodecContext *inCodecContext;\n#if defined(HAVE_SWRESAMPLE)\n    SwrContext *resampleContext;\n#elif defined(HAVE_AVRESAMPLE)\n    AVAudioResampleContext *resampleContext;\n#endif\n    int streamIndex;\n    int duration;\n    double timestamp;\n    int bitrate;\n    bool eof;\n    uint8_t *outBuffer;\n    size_t outBufferSize;\n    uint8_t *overflow;\n    size_t overflowSize;\n};\n\n\n/** This reads the audio data from one frame, converts it to an acceptable\n * format (if needed), and returns a pointer to the the decoded data.\n *\n * @param dataSize bytes of decoded data\n * @param channels number of decoded channels\n * @param nSamples number of decoded samples\n */\nuint8_t * LAV_SourcePrivate::decodeOneFrame(int &dataSize, int &channels, int& nSamples)\n{\n    char buf[256];\n    AVPacket packet;\n    AVFrame *decodedFrame = av_frame_alloc();\n    av_init_packet(&packet);\n\n    int frameFinished = 0;\n    dataSize = 0;\n    channels = 0;\n    nSamples = 0;\n\n    while (!frameFinished)\n    {\n        int ret = av_read_frame(inFormatContext, &packet);\n        if ( ret < 0)\n        {\n            if (ret == AVERROR_EOF || inFormatContext->pb->eof_reached)\n            {\n                eof = true;\n            }\n            else\n            {\n                av_strerror(ret, buf, sizeof(buf));\n                cerr << \"Error reading frame: \" << buf << endl;\n            }\n            av_free_packet(&packet);\n            break;\n        }\n        if ( packet.stream_index != streamIndex )\n        {\n            // Not the frame we're looking for; just read another\n            av_free_packet(&packet);\n            continue;\n        }\n\n        // Just skip this frame if there's a decode error\n        ret = avcodec_decode_audio4(inCodecContext, decodedFrame, &frameFinished, &packet);\n        if (ret < 0)\n        {\n            av_strerror(ret, buf, sizeof(buf));\n            cerr << \"Error decoding audio: \" << buf << endl;\n            av_free_packet(&packet);\n            break;\n        }\n\n        if (frameFinished) {\n            dataSize = av_samples_get_buffer_size(NULL, inCodecContext->channels,\n                                                       decodedFrame->nb_samples,\n                                                       inCodecContext->sample_fmt, 1);\n            channels = inCodecContext->channels;\n\n            // As necessary, convert to outSampleFmt and outMaxChannels\n#if defined(HAVE_SWRESAMPLE)\n            if (channels > outMaxChannels)\n                channels = outMaxChannels;\n            if (!resampleContext &&\n                (inCodecContext->sample_fmt != outSampleFmt || inCodecContext->channels != channels))\n            {\n                int64_t inChannelLayout =\n                    (inCodecContext->channel_layout && inCodecContext->channels == av_get_channel_layout_nb_channels(inCodecContext->channel_layout)) ?\n                    inCodecContext->channel_layout : av_get_default_channel_layout(inCodecContext->channels);\n                int64_t outChannelLayout = av_get_default_channel_layout(channels);\n\n                resampleContext = swr_alloc_set_opts(NULL,\n                                                 outChannelLayout, outSampleFmt, decodedFrame->sample_rate,\n                                                 inChannelLayout, inCodecContext->sample_fmt, inCodecContext->sample_rate,\n                                                 0, NULL);\n                if (!resampleContext || swr_init(resampleContext) < 0)\n                {\n                    cerr << \"Cannot create sample rate converter from \"\n                         << inCodecContext->sample_rate << \" Hz \"\n                         << av_get_sample_fmt_name(inCodecContext->sample_fmt) << \" \"\n                         << inCodecContext->channels << \" channels to \"\n                         << inCodecContext->sample_rate << \" Hz \"\n                         << av_get_sample_fmt_name(outSampleFmt) << \" \"\n                         << channels << \" channels.\" << endl;\n                    av_free_packet(&packet);\n                    break;\n                }\n            }\n\n            if (resampleContext)\n            {\n                int maxOutSamples = outBufferSize / channels / outSampleSize;\n                int nSamplesOut = swr_convert(resampleContext,\n                                              &outBuffer,\n                                              maxOutSamples,\n                                              const_cast<const uint8_t **>(decodedFrame->extended_data),\n                                              decodedFrame->nb_samples);\n                if (nSamplesOut < 0)\n                {\n                    cerr << \"swr_convert failed\" << endl;\n                    av_free_packet(&packet);\n                    break;\n                }\n                nSamples = nSamplesOut;\n                dataSize = nSamplesOut * channels * outSampleSize;\n            }\n            else\n#elif defined(HAVE_AVRESAMPLE)\n            if (channels > outMaxChannels)\n                channels = outMaxChannels;\n            if (!resampleContext &&\n                (inCodecContext->sample_fmt != outSampleFmt || inCodecContext->channels != channels))\n            {\n                int64_t inChannelLayout =\n                    (inCodecContext->channel_layout && inCodecContext->channels == av_get_channel_layout_nb_channels(inCodecContext->channel_layout)) ?\n                    inCodecContext->channel_layout : av_get_default_channel_layout(inCodecContext->channels);\n                int64_t outChannelLayout = av_get_default_channel_layout(channels);\n\n                resampleContext = avresample_alloc_context();\n                if ( ! resampleContext )\n                {\n                    cerr << \"Cannot allocate AVAudioResampleContext\" << endl;\n                    av_free_packet(&packet);\n                    break;\n                }\n\n                av_opt_set_int(resampleContext, \"in_channel_layout\",  inChannelLayout,             0);\n                av_opt_set_int(resampleContext, \"in_sample_fmt\",      inCodecContext->sample_fmt,  0);\n                av_opt_set_int(resampleContext, \"in_sample_rate\",     inCodecContext->sample_rate, 0);\n                av_opt_set_int(resampleContext, \"out_channel_layout\", outChannelLayout,            0);\n                av_opt_set_int(resampleContext, \"out_sample_fmt\",     outSampleFmt,                0);\n                av_opt_set_int(resampleContext, \"out_sample_rate\",    inCodecContext->sample_rate, 0);\n\n                // If both the input and output formats are s16 or u8, use s16\n                // as the internal sample format\n                if (av_get_bytes_per_sample(inCodecContext->sample_fmt) <= 2 &&\n                    av_get_bytes_per_sample(outSampleFmt) <= 2)\n                {\n                    av_opt_set_int(resampleContext, \"internal_sample_fmt\", AV_SAMPLE_FMT_S16P, 0);\n                }\n\n                ret = avresample_open(resampleContext);\n                if (ret < 0)\n                {\n                    cerr << \"Error opening libavresample\" << endl;\n                    av_free_packet(&packet);\n                    break;\n                }\n            }\n\n            if (resampleContext)\n            {\n                int outLinesize;\n                int maxOutSamples = outBufferSize / channels / outSampleSize;\n                av_samples_get_buffer_size(&outLinesize,\n                                            channels,\n                                            decodedFrame->nb_samples,\n                                            outSampleFmt, 0);\n                int nSamplesOut = avresample_convert(resampleContext,\n                                            &outBuffer,\n                                            outLinesize,\n                                            maxOutSamples,\n                                            decodedFrame->extended_data,\n                                            decodedFrame->linesize[0],\n                                            decodedFrame->nb_samples);\n                if (nSamplesOut < 0)\n                {\n                    cerr << \"avresample_convert failed\" << endl;\n                    av_free_packet(&packet);\n                    break;\n                }\n                nSamples = nSamplesOut;\n                dataSize = nSamplesOut * channels * outSampleSize;\n            }\n            else\n#endif\n            {\n                nSamples = decodedFrame->nb_samples;\n                memcpy(outBuffer, decodedFrame->data[0], dataSize);\n            }\n        }\n        if ( packet.pts != AV_NOPTS_VALUE )\n            timestamp = av_q2d(inFormatContext->streams[streamIndex]->time_base)*packet.pts;\n        av_free_packet(&packet);\n    }\n    timestamp += (double)nSamples / decodedFrame->sample_rate;\n    av_frame_free(&decodedFrame);\n    return outBuffer;\n}\n\n\nLAV_Source::LAV_Source()\n    : d(new LAV_SourcePrivate())\n{\n    av_register_all();\n    avformat_network_init();\n}\n\n\nLAV_Source::~LAV_Source()\n{\n    release();\n    avformat_network_deinit();\n    delete d;\n}\n\nbool LAV_Source::eof() const\n{\n    return (d->eof || d->inFormatContext->pb->eof_reached);\n}\n\n\nvoid LAV_Source::init(const QString& fileName)\n{\n    // Assume that we want to start fresh\n    if ( d->inFormatContext || d->inCodecContext )\n        release();\n\n    if ( avformat_open_input(&d->inFormatContext, QFile::encodeName(fileName), NULL, NULL ) < 0 )\n    {\n        throw std::runtime_error (\"Cannot open the media file!\");\n    }\n    if( avformat_find_stream_info(d->inFormatContext, NULL) < 0)\n    {\n        release();\n        throw std::runtime_error (\"Cannot find stream info in the file!\");\n    }\n\n    // If there's a default video stream, we want the audio associated with it.\n    // Otherwise just get the default audio stream.\n    AVCodec* codec;\n    int videoIndex = av_find_best_stream(d->inFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0);\n    if ( videoIndex < 0 )\n        videoIndex = -1;\n    d->streamIndex = av_find_best_stream(d->inFormatContext, AVMEDIA_TYPE_AUDIO, -1, videoIndex, &codec, 0);\n\n    if ( d->streamIndex < 0 )\n    {\n        release();\n        throw std::runtime_error (\"No audio streams found in the file!\");\n    }\n\n    int64_t duration = d->inFormatContext->streams[d->streamIndex]->duration;\n\n    // If the stream duration isn't available, get the duration from\n    // AVFormatContext.  This should give us the right duration for 99 point\n    // whatever percent of cases.\n    if ( duration < 1 )\n    {\n        d->duration = d->inFormatContext->duration / AV_TIME_BASE;\n    }\n    else\n    {\n        AVRational timeBase = d->inFormatContext->streams[d->streamIndex]->time_base;\n        d->duration = duration * timeBase.num / timeBase.den;\n    }\n\n    d->inCodecContext = d->inFormatContext->streams[d->streamIndex]->codec;\n\n    // MP3 decodes to S16P, but we always want S16, so request it\n    d->inCodecContext->request_sample_fmt = outSampleFmt;\n\n    if ( !avcodec_open2(d->inCodecContext, codec, NULL) < 0 )\n    {\n        release();\n        throw std::runtime_error (\"Unable to open a compatible audio codec for the file!\");\n    }\n\n    if ( d->inCodecContext->bit_rate > 0 )\n    {\n        d->bitrate = d->inCodecContext->bit_rate;\n    }\n\n#if !defined(HAVE_SWRESAMPLE) && !defined(HAVE_AVRESAMPLE)\n    if (d->inCodecContext->sample_fmt != outSampleFmt\n        || d->inCodecContext->channels < 1\n        || d->inCodecContext->channels > 2)\n    {\n        release();\n        throw std::runtime_error (\"The file has an incompatible sample format!\");\n    }\n#endif\n\n}\n\n\nvoid LAV_Source::getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels )\n{\n    lengthSecs = d->duration;\n    samplerate = d->inCodecContext->sample_rate;\n    bitrate = d->bitrate;\n\n    nchannels = d->inCodecContext->channels;\n#if defined(HAVE_SWRESAMPLE) || defined(HAVE_AVRESAMPLE)\n    // What we promise to have if we need to convert the audio\n    if (nchannels > outMaxChannels)\n        nchannels = outMaxChannels;\n#endif\n}\n\n\nvoid LAV_Source::release()\n{\n    if ( d->inCodecContext && d->inCodecContext->codec_id != AV_CODEC_ID_NONE )\n    {\n        avcodec_close(d->inCodecContext);\n    }\n    if ( d->inFormatContext)\n    {\n        avformat_close_input(&d->inFormatContext);\n    }\n#if defined(HAVE_SWRESAMPLE) || defined(HAVE_AVRESAMPLE)\n    if ( d->resampleContext)\n    {\n#if defined(HAVE_SWRESAMPLE)\n        swr_free(&d->resampleContext);\n#elif defined(HAVE_AVRESAMPLE)\n        avresample_free(&d->resampleContext);\n#endif\n    }\n#endif\n    d->inCodecContext = NULL;\n    d->inFormatContext = NULL;\n    d->streamIndex = -1;\n    d->duration = 0;\n    d->bitrate = 0;\n    d->eof = false;\n    d->overflowSize = 0;\n}\n\n\nvoid LAV_Source::skipSilence(double silenceThreshold /* = 0.0001 */)\n{\n    silenceThreshold *= static_cast<double>( numeric_limits<short>::max() );\n\n    int dataSize, channels, nSamples;\n    uint8_t *out = d->decodeOneFrame(dataSize, channels, nSamples);\n    while(dataSize > 0)\n    {\n        double sum = 0;\n        int16_t *buf = (int16_t*)out;\n        switch ( channels )\n        {\n            case 1:\n                for (int j = 0; j < nSamples; j++)\n                    sum += abs( buf[j] );\n                break;\n            case 2:\n                for (int j = 0; j < nSamples; j+=2)\n                    sum += abs( (buf[j] >> 1) + (buf[j+1] >> 1) );\n                break;\n        }\n        if ( sum >= silenceThreshold * static_cast<double>(nSamples) )\n        {\n            break;\n        }\n        out = d->decodeOneFrame(dataSize, channels, nSamples);\n    }\n\n    avcodec_flush_buffers(d->inCodecContext);\n}\n\n\nvoid LAV_Source::skip(const int mSecs)\n{\n    double targetTimestamp = d->timestamp + mSecs/1000.0;\n    int dataSize, channels, nSamples;\n    for (;;)\n    {\n        d->decodeOneFrame(dataSize, channels, nSamples);\n        if ( d->timestamp > targetTimestamp || d->eof )\n           return;\n    }\n}\n\n\nint LAV_Source::updateBuffer(signed short* pBuffer, size_t bufferSize)\n{\n    size_t bufferFill = 0;\n    int dataSize;\n\n    if ( d->overflowSize )\n    {\n        memcpy( pBuffer, d->overflow, d->overflowSize );\n        bufferFill = d->overflowSize/outSampleSize;\n        d->overflowSize = 0;\n    }\n\n    uint8_t * out;\n    while(bufferFill < bufferSize)\n    {\n        int channels, nb_samples;\n\n        out = d->decodeOneFrame(dataSize, channels, nb_samples);\n        if (!dataSize)\n            break;\n\n        // Only put as many bytes in pBuffer as will fit; save the rest for the\n        // next call to updateBuffer\n        int bytesToBuffer = (bufferSize - bufferFill)*outSampleSize;\n\n        if ( bytesToBuffer < dataSize )\n        {\n            d->overflowSize = dataSize - bytesToBuffer;\n            memcpy( d->overflow, out + bytesToBuffer, d->overflowSize);\n        }\n        else\n        {\n            bytesToBuffer = dataSize;\n        }\n        memcpy( pBuffer + bufferFill, out, bytesToBuffer );\n\n        bufferFill += bytesToBuffer/outSampleSize;\n    }\n\n    return bufferFill;\n}\n"
  },
  {
    "path": "app/fingerprinter/LAV_Source.h",
    "content": "/*\n * LAV_Source: use FFmpeg/Libav to extract audio for Last.fm fingerprinting\n * Copyright (C) 2012 John Stamp <jstamp@mehercule.net>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#ifndef LAV_SOURCE_H\n#define LAV_SOURCE_H\n\n#include <lastfm/FingerprintableSource.h>\n\nusing namespace std;\n\nclass LAV_Source : public lastfm::FingerprintableSource\n{\npublic:\n    LAV_Source();\n    ~LAV_Source();\n\n    void getInfo(int& lengthSecs, int& samplerate, int& bitrate, int& nchannels);\n    void init(const QString& fileName);\n    void release();\n\n    int updateBuffer(signed short* pBuffer, size_t bufferSize);\n\n    void skip(const int mSecs);\n    void skipSilence(double silenceThreshold = 0.0001);\n\n    bool eof() const;\n\nprivate:\n    class LAV_SourcePrivate * const d;\n};\n\n#endif\n"
  },
  {
    "path": "app/fingerprinter/fingerprinter.pro",
    "content": "TARGET = fingerprinter\nQT = core network xml sql\n\nCONFIG += lastfm unicorn logger fingerprint ffmpeg\nCONFIG -= app_bundle\n\ninclude( ../../admin/include.qmake )\n\n# TODO: FIX THIS: I think this means that we can only build bundles\nmac {\n    DESTDIR = \"../../_bin/Last.fm Scrobbler.app/Contents/Helpers\"\n    QMAKE_POST_LINK += ../../admin/dist/mac/bundleFrameworks.sh \\\"$$DESTDIR/$$TARGET\\\"\n}\n\nSOURCES += main.cpp \\\n            Fingerprinter.cpp \\\n            LAV_Source.cpp\n\nHEADERS += LAV_Source.h \\\n            Fingerprinter.h\n\n\n\n\n\nDEFINES += LASTFM_COLLAPSE_NAMESPACE LASTFM_FINGERPRINTER\n\n"
  },
  {
    "path": "app/fingerprinter/main.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of liblastfm.\n\n   liblastfm is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   liblastfm is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with liblastfm.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Fingerprinter.h\"\n\n#include \"lib/unicorn/UnicornCoreApplication.h\"\n\n#include <lastfm/ws.h>\n\n#include <QStringList>\n#include <QCoreApplication>\n#include <QDebug>\n\n// ./fingerprinter --username <username> --filename <filename> --title <title> --album <album> --artist <artist>\n\nint main(int argc, char *argv[])\n{\n    int exitCode = -1;\n\n    QtSingleCoreApplication::setApplicationName( \"Last.fm Fingerprinter\" );\n    QtSingleCoreApplication::setOrganizationName( \"Last.fm\" );\n\n    unicorn::CoreApplication a(argc, argv);\n\n    qDebug() << a.arguments();\n\n    int usernameIndex = a.arguments().indexOf( \"--username\" );\n    int filenameIndex = a.arguments().indexOf( \"--filename\" );\n\n    if ( usernameIndex != -1 && filenameIndex != -1 )\n    {\n        // username and filename are required fields\n        lastfm::ws::Username = a.arguments().at( usernameIndex + 1 );\n\n        // create the track from the command line arguments\n        MutableTrack track;\n        track.setUrl( QUrl::fromLocalFile( a.arguments().at( filenameIndex + 1 ) ) );\n\n        int titleIndex = a.arguments().indexOf( \"--title\" );\n        int albumIndex = a.arguments().indexOf( \"--album\" );\n        int artistIndex = a.arguments().indexOf( \"--artist\" );\n\n        if ( titleIndex != -1 ) track.setTitle( a.arguments().at( titleIndex + 1 ) );\n        if ( albumIndex != -1 ) track.setAlbum( a.arguments().at( albumIndex + 1 ) );\n        if ( artistIndex != -1 ) track.setTitle( a.arguments().at( artistIndex + 1 ) );\n\n        Fingerprinter* fingerprinter = new Fingerprinter( track );\n        exitCode = a.exec();\n        delete fingerprinter;\n    }\n    else\n    {\n        qWarning() << \"Usage: fingerprinter --username <username> --filename <filename> --title <title> --album <album> --artist <artist>\";\n    }\n\n    return exitCode;\n}\n"
  },
  {
    "path": "app/twiddly/IPod.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"lib/unicorn/mac/AppleScript.h\"\n#include \"IPod.h\"\n#include \"IPodScrobble.h\"\n#include \"ITunesLibrary.h\"\n#include \"PlayCountsDatabase.h\"\n#include \"common/qt/msleep.cpp\"\n#include \"plugins/iTunes/ITunesExceptions.h\"\n#include <lastfm/misc.h>\n#include <lastfm/Track.h>\n#include <QtCore>\n#include <QtXml>\n#include <iostream>\n\n\nIPod* //static\nIPod::fromCommandLineArguments( const QStringList& args )\n{\n#if 0\n    // handy for debug\n    QStringList myArgs = QString( \"--device ipod --connection usb --pid 4611 --vid 1452 --serial 000000C8B035\" ).split( ' ' );\n    //QStringList myArgs = QString( \"--bootstrap\" ).split( ' ' );\n    #define args myArgs\n#endif\n\n\n\n    QMap<QString, QString> map;\n    QListIterator<QString> i( args );\n    while (i.hasNext())\n    {\n        QString arg = i.next();\n        if (!arg.startsWith( \"--\" ) || !i.hasNext() || i.peekNext().startsWith( \"--\" ))\n            continue;\n        arg = arg.mid( 2 );\n\n        // get all the strings up until the end or the next --\n        QString value = i.next();\n        while ( i.hasNext() && !i.peekNext().startsWith(\"--\") )\n            value.append( \" \" + i.next() );\n\n        map[arg] = value;\n    }\n\n    IPod* ipod;\n    if (args.contains( \"--manual\" ))\n        ipod = new ManualIPod;\n    else\n        ipod = new AutomaticIPod;\n\n    #define THROW_IF_EMPTY( x ) ipod->x = map[#x]; if (ipod->x.isEmpty()) throw \"Could not resolve argument: --\" #x;\n\n    THROW_IF_EMPTY( device );\n    THROW_IF_EMPTY( vid );\n    THROW_IF_EMPTY( pid );\n    THROW_IF_EMPTY( serial );\n\n    // use device for name if name wasn't sent\n    ipod->name = map[\"name\"];\n    if (ipod->name.isEmpty())\n        ipod->name = ipod->serial;\n    \n    #undef THROW_IF_EMPTY\n    \n    return ipod;\n}\n\n\nQString\nIPod::scrobbleId() const\n{\n#ifdef Q_OS_MAC\n    const char* os = \"Macintosh\";\n#elif defined Q_OS_WIN\n    const char* os = \"Windows\";\n#else\n    #error What kind of operating system are you?! \\\n           I am a home-made one.\n#endif\n\n    return vid + '-' + pid + '-' + device + '-' + os;\n}\n\n\nQDir\nIPod::saveDir() const \n{\n    QDir d = lastfm::dir::runtimeData().filePath( \"devices/\" + uid() );\n    d.mkpath( \".\" );\n    return d;\n}\n\n\nQDomDocument\nIPod::ScrobbleList::xml() const\n{    \n    QDomDocument xml;\n    QDomElement root = xml.createElement( \"submissions\" );\n    root.setAttribute( \"product\", \"Twiddly\" );\n\n    QListIterator<Track> i( *this );\n    while (i.hasNext())\n        root.appendChild( i.next().toDomElement( xml ) );\n    \n    xml.appendChild( root );\n    \n    return xml;\n}\n\n\n/** iPod plays are determined using our iTunes Plays sqlite database and\n  * comparing that with the actual state of the iTunes Library database after\n  * an iPod is synced with it\n  */\nvoid\nIPod::twiddle()\n{\n    PlayCountsDatabase& db = *playCountsDatabase();\n    ITunesLibrary& library = *iTunesLibrary();\n\n    QList<ITunesLibrary::Track> tracksToUpdate;\n    QList<ITunesLibrary::Track> tracksToInsert;\n    QList<ITunesLibrary::Track> tracksToScrobble;\n\n    int nullTrackCount = 0;\n\n    // If creation of the library class failed due to a dialog showing in iTunes\n    // or COM not responding for some other reason, hasTracks will just return false\n    // and we will quit this run.\n    while ( library.hasTracks() )\n    {\n        try\n        {\n            ITunesLibrary::Track track = library.nextTrack();\n\n            if ( track.isNull() )\n            {\n                // Failed to read current iTunes track. Either something went wrong,\n                // or the track was not found on the disk despite being in the iTunes library.\n\n                // Don't log every error as this could be a library full of iTunes Match tracks\n                // just count how many failed and say at the end\n\n                ++nullTrackCount;\n                continue;\n            }\n\n            QString id = track.uniqueId();\n\n            // We don't know about this track yet, this means either:-\n            //   1. The track was added to iTunes since the last sync. thus it is\n            //      impossible for it to have been played on the iPod\n            //   2. On Windows, the path of the track changed since the last sync.\n            //      Since we don't have persistent IDs on Windows we have no way of \n            //      matching up this track up with its previous incarnation. Thus\n            //      we don't scrobble it as we have no idea if it was played or not\n            //      chances are, it wasn't\n            PlayCountsDatabase::Track dbTrack = db[id];\n\n            if ( dbTrack.isNull() )\n            {\n                tracksToInsert << track;\n                continue;\n            }\n\n            const int diff = track.playCount() - dbTrack.playCount(); // can throw\n        \n            if ( diff > 0 )\n                tracksToScrobble << track;\n\n            // a worthwhile optimisation since updatePlayCount() is really slow\n            // NOTE negative diffs *are* possible\n            if ( diff < 0 )\n                tracksToUpdate << track; // can throw\n        }\n        catch ( ITunesException& )\n        {\n            // Carry on...\n        }\n    }\n\n    qDebug() << \"There were \" << nullTrackCount << \" null tracks\";\n\n    if ( tracksToUpdate.count() + tracksToInsert.count() + tracksToScrobble.count() > 0 )\n    {\n        // We've got some updates and inserts to do so lock the database and do them\n\n        db.beginTransaction();\n\n        foreach ( const ITunesLibrary::Track& track, tracksToScrobble )\n        {\n            try\n            {\n                ::Track t = track.lastfmTrack(); // can throw\n\n                // Because we take a snapshot of our playcounts db there is a possible race condition.\n                // use db.track here to fetch the latest playcount now that we've locked the database\n                const int diff = track.playCount() - db.track( track.uniqueId() ).playCount();\n\n                if ( !t.isNull() )\n                {\n                    if ( t.timestamp().secsTo( QDateTime::currentDateTime() ) > 30 )\n                    {\n                        // we only scrobble tracks with a timestamp older than 30 seconds\n                        // to give the iTunes plugin time so update the playcount db\n                        // after a track change - bit of a hack, but it stops spurious iPod scrobbles\n\n                        // update the playcount db to the current playcount for this track\n                        // this means that we won't try to scrobble the track again\n                        db.update( track );\n\n                        IPodScrobble t2( t );\n                        t2.setPlayCount( diff );\n                        t2.setMediaDeviceId( scrobbleId() );\n                        t2.setUniqueId( track.uniqueId() );\n                        m_scrobbles += t2;\n                        qDebug() << diff << \"scrobbles found for\" << t;\n                    }\n                    else\n                    {\n                        qDebug() << \"Timestamp less than 30 seconds. Don't scrobble yet.\";\n                    }\n                }\n                else\n                {\n                    qWarning() << \"Couldn't get Track for\" << track.uniqueId();\n\n                    // We get here if COM fails to populate the Track for whatever reason.\n                    // Therefore we continue and don't let the local db update. That way we\n                    // maintain the diff and we should be picking up on it next time twiddly\n                    // runs.\n                    continue;\n                }\n            }\n            catch ( ITunesException& )\n            {\n                // Carry on...\n            }\n        }\n\n        // this should just be tracks with negative playcount diffs\n        foreach ( const ITunesLibrary::Track& track, tracksToUpdate )\n            db.update( track );\n\n        // insert all the new tracks we've found\n        foreach ( const ITunesLibrary::Track& track, tracksToInsert )\n            db.insert( track );\n\n        db.endTransaction();\n    }\n\n    delete &db;\n    delete &library;\n}\n\n\n#ifdef Q_OS_MAC\n    ManualIPod::ManualIPod()\n               : m_pid( firstPid() )\n    {}\n\n\n    QString //static\n    ManualIPod::firstPid()\n    {\n        AppleScript script;\n        script << \"tell application 'iTunes' to \"\n                  \"return persistent ID of some source whose kind is iPod\";\n                  \n        // wait for iPod to exist, since we're launched early by the plugin\n        // and it may not be in iTunes yet, 10 seconds is more than enough\n        // without being excessive\n        QString pid;\n        for( int x = 0; x < 20 && (pid = script.exec()).isEmpty(); ++x )\n        {\n            Qt::msleep( 500 );\n        }\n                \n        return pid;\n    }\n\n\n#else\n    ManualIPod::ManualIPod()\n    {}\n#endif\n"
  },
  {
    "path": "app/twiddly/IPod.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesLibrary.h\"\n#include \"IPodScrobble.h\"\n#include \"IPodSettings.h\"\n#include \"PlayCountsDatabase.h\"\n#include <QDir>\n#include <QDomDocument>\n#include <QStringList>\n\n\n/** @author <max@last.fm>\n  */\nclass IPod\n{\npublic:   \n    virtual ~IPod()\n    {}\n    \n    /** you own the memory */\n    static IPod* fromCommandLineArguments( const QStringList& );\n    \n    /** figures out the iPod scrobbles */\n    void twiddle();\n\n    /** allows us to encapsulate the real scrobble count() */\n    class ScrobbleList : private QList<Track>\n    {\n        int m_realCount;\n\n    public:\n        ScrobbleList() : m_realCount( 0 )\n        {}\n        using QList<Track>::isEmpty;\n        QDomDocument xml() const;\n        int count() const { return m_realCount; }\n        ScrobbleList& operator+=( const Track& t )\n        {\n            m_realCount += IPodScrobble(t).playCount();\n            append( t );\n            return *this;\n        }\n    #ifdef WIN32\n        /** verbose, but named to make it clear you're expected to set uniqueIDs\n          * on tracks added to the ScrobbleList on Windows, at least if you want\n          * to remove them */\n        void removeAllWithUniqueId( const QString& uniqueId );\n    #endif\n        void clear()\n        {\n            m_realCount = 0;\n            QList<Track>::clear();\n        }\n    };\n    \n    /** this must be writable by Qt as a path on all platforms */\n    QString uid() const { return device + '/' + serial; }\n\n    ScrobbleList scrobbles() const { return m_scrobbles; }\n    ScrobbleList& scrobbles() { return m_scrobbles; } //so we can clear()\n\n    IPodSettings settings() const \n\t{\n\t\treturn IPodSettings( device + '/' + serial );\n\t}\n\n    /** assigned to the mediaDeviceId on TrackInfo objects */\n    QString scrobbleId() const;\n    \n    /** every device has its own directory for storing stuff */\n    QDir saveDir() const;\n\n    QString device;\n    QString vid;\n    QString pid; //product id, not persistent id\n    QString serial;\n    QString name;\n\nprotected:    \n    ScrobbleList m_scrobbles;\n\n    /** heap allocate and return those relevent to your iPod type */\n    virtual class PlayCountsDatabase* playCountsDatabase() = 0;\n    virtual class ITunesLibrary* iTunesLibrary() = 0;\n\n};\n\n\n\nclass AutomaticIPod : public IPod\n{\npublic:\n    class PlayCountsDatabase : public ::PlayCountsDatabase\n    {\n    public:\n        PlayCountsDatabase();\n\n        /** duplicates the contents of the iTunes Library into our database */\n        void bootstrap();\n        bool isBootstrapNeeded() const;\n    };\n\nprivate:\n    virtual PlayCountsDatabase* playCountsDatabase() { return new PlayCountsDatabase; }\n    virtual ITunesLibrary* iTunesLibrary() { return new ITunesLibrary; }\n};\n\n\n\nclass ManualIPod : public IPod\n{\npublic:\n    ManualIPod();\n\n    class PlayCountsDatabase : public ::PlayCountsDatabase\n    {\n    public:\n        PlayCountsDatabase( class IPod const * const ipod )\n                : ::PlayCountsDatabase( ipod->saveDir().filePath( \"playcounts.db\" ) )\n        {}\n    };\n\n    class Library : public ITunesLibrary\n    {\n    public:\n        Library( const QString& pid ) : ITunesLibrary( pid, true )\n        {}\n    };\n\nprivate:\n    virtual PlayCountsDatabase* playCountsDatabase() { return new PlayCountsDatabase( this ); }\n    virtual ITunesLibrary* iTunesLibrary() { return new Library( m_pid ); }\n\n    /** persistent ID of the iPod source, mac only */\n    QString const m_pid;\n\n  #ifdef Q_OS_MAC    \n    static QString firstPid();\n  #endif\n};\n"
  },
  {
    "path": "app/twiddly/IPodScrobble.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IPOD_SCROBBLE_H\n#define IPOD_SCROBBLE_H\n\n#include <lastfm/Track.h>\n\n\nstruct IPodScrobble : public MutableTrack\n{\n    IPodScrobble()\n    {}\n    \n    IPodScrobble( const Track& that ) : MutableTrack( that )\n    {}\n\n    QString uniqueId() const { return extra( \"uniqueId\" ); }\n    int playCount() const { return extra( \"playCount\" ).toInt(); }\n\n    void setPlayCount( int const i ) { setExtra( \"playCount\", QString::number( i ) ); }\n    void setMediaDeviceId( const QString& id ) { setExtra( \"deviceId\", id ); }\n    void setUniqueId( const QString& id ) { setExtra( \"uniqueId\", id ); }\n};\n\n#endif\n"
  },
  {
    "path": "app/twiddly/IPodSettings.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"lib/unicorn/UnicornSettings.h\"\n\nenum IPodType { IPodUnknownType, IPodAutomaticType, IPodManualType };\n\n\n/** Used by app/client so don't add anything specific to Twiddly \n  * <max@last.fm>\n  */\nclass IPodSettings\n{\n    class Settings : public unicorn::AppSettings\n    {\n    public:\n        Settings( IPodSettings const * const s )\n        {\n            beginGroup( \"device/\" + s->m_uid );\n        }\n    };\n\n\tfriend class IPod;\n\tfriend class IPodScrobbleCache;\n    friend class Settings;\n\n    QString m_uid;\n    \n    IPodSettings( const QString& uid ) : m_uid( uid )\n    {}\n    \npublic:\n    IPodType type() const { return (IPodType)Settings( this ).value( \"type\" ).toInt(); }\n    void setType( IPodType t ) { Settings( this ).setValue( \"type\", (int)t ); }\n    \n    QDateTime lastSync() const { return Settings( this ).value( \"LastSync\" ).toDateTime(); }\n    void setLastSync( const QDateTime& time ) { Settings( this ).setValue( \"LastSync\", time ); }\n};\n"
  },
  {
    "path": "app/twiddly/ITunesLibrary.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ITUNES_LIBRARY_H\n#define ITUNES_LIBRARY_H\n\n#include \"ITunesLibraryTrack.h\"\n#include <lastfm/Track.h>\n#include <QList>\n\n\n/** @author Max Howell <max@last.fm> - Mac\n  * @author <erik@last.fm> - Win\n  *\n  * This class offers easy access to the iTunes Library database\n  * It uses AppleScript and COM to access and query iTunes\n  */\nclass ITunesLibrary\n{\npublic:\n    /** the isIPod bool is for Windows only, the source, mac :( */\n    ITunesLibrary( const QString& source = \"\", bool isIPod = false ); // throws\n    ~ITunesLibrary();\n\n    typedef ITunesLibraryTrack Track;\n\n    bool hasTracks() const;\n    Track nextTrack();\n    int trackCount() const;\n\nprivate:\n    uint m_currentIndex;\n\n  #ifdef WIN32\n    class ITunesComWrapper* m_com;\n    long m_trackCount;\n    bool const m_isIPod;\n  #else\n    QList<Track> m_tracks;\n  #endif\n\nprivate:\n    Q_DISABLE_COPY( ITunesLibrary );\n};\n\n#endif\n"
  },
  {
    "path": "app/twiddly/ITunesLibraryTrack.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ITUNES_LIBRARY_TRACK_H\n#define ITUNES_LIBRARY_TRACK_H\n\n#ifdef WIN32\n\n#include <lastfm/Track.h>\n#include \"plugins/iTunes/ITunesTrack.h\"\n#include <QSharedData>\n#include <QSharedDataPointer>\n\nnamespace COM\n{\n    using ::ITunesTrack;\n}\n\n\n/** @author <max@last.fm>\n  *\n  * We are QSharedData to use polymorphism but still allow\n  * ITunesLibraryTracks to be passed by value.\n  *\n  * It would be nicer to derive ITunesTrack, but ITunesComWrapper is not\n  * designed for it, and ITunesTrack is not virtual enough, so we have this\n  * mess instead \n  */\nstruct ITunesLibraryTrackData : public QSharedData\n{\n    ITunesLibraryTrackData( const ITunesTrack& t ) : i( t )\n    {}\n\n    virtual ~ITunesLibraryTrackData()\n    {}\n\n    /** the path is the uniqueId for iTunes library tracks on Windows */\n    virtual QString uniqueId() const { return QString::fromStdWString( i.persistentId() ); }\n\n    /** @returns false if the track doesn't exist in the iTunes Library */\n    virtual bool isNull() const { return i.isNull(); }\n\n    /** @returns -1 if COM failure or isNull() */\n    int playCount() const { return i.playCount(); }\n\n    COM::ITunesTrack i;\n};\n\n\n/** @author <max@last.fm> \n  * @brief represents a track from an iPod source\n  *\n  * NOTE only used for manual iPod scrobbling, since iPods have no path, this\n  * is the only unique ID we have available :(\n  */\nstruct IPodLibraryTrackData : public ITunesLibraryTrackData\n{\n    IPodLibraryTrackData( const ITunesTrack& t ) : ITunesLibraryTrackData( t )\n    {}\n\n    /** isNull from COM::ITunesTrack returns true if m_path is null too *\n    * so we can't rely on that at all :( */\n    virtual bool isNull() const { return uniqueId().remove( '\\t' ).isEmpty(); }\n\n    /** iTunes returns empty paths for tracks stored on the iPod */\n    virtual QString uniqueId() const\n    {\n        return QString::fromStdWString( i.artist() + L'\\t' + i.track() + L'\\t' + i.album() );\n    }\n};\n\n\n    /** @author <max@last.fm> \n      */\n    class ITunesLibraryTrack\n    {\n        friend class ITunesLibrary;\n        \n        ITunesLibraryTrack()\n        {}\n\n        QSharedDataPointer<ITunesLibraryTrackData> d;\n\n    public:\n        bool isNull()      const { return !d || d->isNull(); }\n        QString uniqueId() const { Q_ASSERT( d ); return d->uniqueId(); }\n        QString persistentId() const { return uniqueId(); }\n        int playCount()    const { Q_ASSERT( d ); return d->playCount(); }\n\n        /** @returns a TrackInfo object filled out with minimal information,\n          * check to see if  what you want is assigned before assuming so!\n          * It gets the data from iTunes using AppleScript/COM \n          *\n          * @defined ITunesLibrary.cpp\n          */\n        lastfm::Track lastfmTrack() const;\n    };\n\n\n#else //MAC\n    #include <lastfm/Track.h>\n    #include \"PlayCountsDatabase.h\"\n    \n    template <typename T> class QList;\n    \n    /** @author <max@last.fm>\n      * private because there is no \"isA\" relationship \n      */\n    class ITunesLibraryTrack : private PlayCountsDatabase::Track\n    {\n        friend class ITunesLibrary;\n        friend class QList<ITunesLibraryTrack>;\n        \n        ITunesLibraryTrack() // for QList only\n        {}\n        \n    public:\n        ITunesLibraryTrack( const QString& uid, int c ) : PlayCountsDatabase::Track( uid, c )\n        {}\n        \n        lastfm::Track lastfmTrack() const;\n\n        using PlayCountsDatabase::Track::isNull;\n        using PlayCountsDatabase::Track::uniqueId;\n        using PlayCountsDatabase::Track::playCount;\n\n        QString persistentId() const { return uniqueId(); }\n\n    private:\n        /** the persistent ID of the source for this track, if empty, we use\n          * the default iTunes library */\n        QString m_sourcePersistentId;\n    };\n#endif\n\n#endif\n"
  },
  {
    "path": "app/twiddly/ITunesLibrary_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesLibrary.h\"\n#include \"IPodScrobble.h\"\n#include \"lib/unicorn/mac/AppleScript.h\"\n#include <QDateTime>\n#include <QFileInfo>\n#include <QStringList>\n#include <QDebug>\n\nITunesLibrary::ITunesLibrary( const QString& pid, bool )\n        : m_currentIndex( 0 )\n{\n    QString source;\n    if (!pid.isEmpty())\n        source = \"tell first source whose persistent ID is \\\"\" + pid + \"\\\" to \";\n\n    AppleScript script( \"tell application \\\"iTunes\\\" to \"\n                        + source + \n                        \"get {persistent ID, played count } of every track in library playlist 1\" );\n    QString out = script.exec();\n    \n    if (out.isEmpty())\n        throw \"Failed to get iTunes library contents\";\n    \n    out.chop( 2 ); //remove encapsulating }}\n    out.remove( 0, 2 ); //remove encapsulating {{\n    \n    QStringList parts = out.split( \", \" );\n    const int N = parts.count() / 2;\n    parts[N-1].chop( 1 ); //remove encapsulating }\n    parts[N].remove( 0, 1 ); //remove encapsulating {\n    \n    for (int i = 0; i < N; ++i)\n    {\n        QString const uid = parts[i].remove( '\"' );\n        QString const plays = parts[N+i];\n        \n        ITunesLibrary::Track t( uid, plays.toInt() );\n        t.m_sourcePersistentId = pid;\n        m_tracks += t;\n    }\n    \n    qDebug() << \"Found\" << m_tracks.count() << \"tracks\";\n}\n\n\nITunesLibrary::~ITunesLibrary()\n{}\n\n\nbool\nITunesLibrary::hasTracks() const\n{\n    return m_currentIndex < (uint)m_tracks.count();\n}\n\n\nITunesLibrary::Track\nITunesLibrary::nextTrack()\n{\n    return m_tracks.value( m_currentIndex++ );\n}\n\n\nint \nITunesLibrary::trackCount() const\n{\n    return m_tracks.count();\n}\n\n\nstatic QDateTime\nqDateTimeFromScriptString( const QString& s )\n{\n    QList<int> parts;\n    foreach (const QString& part, s.split( ':' ))\n        parts += part.toInt();\n\n    if (parts.count() < 4)\n        return QDateTime();\n\n    QDate d( parts[0], parts[1], parts[2] );\n\n    QTime t;\n    t = t.addSecs( parts[3] );\n\n    return QDateTime( d, t );\n}\n\n\n::Track\nITunesLibrary::Track::lastfmTrack() const\n{\n    // NOTE we only what data we require for scrobbling, though we could fill in\n    // more of the Track object\n    IPodScrobble t;\n    t.setSource( ::Track::MediaDevice );\n\n    QString source;\n    if (!m_sourcePersistentId.isEmpty())\n        source = \"tell first source whose persistent ID is '\" + m_sourcePersistentId + \"' to \";\n\n    // TODO compile once and pass pid as argument\n    // NOTE trust me, the code is ugly, but doesn't work any other way, don't clean it up!\n    AppleScript script;\n    script << \"tell application 'iTunes'\"\n        <<     source + \"set lib to library playlist 1\"\n        <<     \"set t to first track of lib whose persistent ID is '\" + persistentId() + \"'\"\n        <<     \"set d to played date of t\"\n        << \"end tell\"\n\n        << \"try\"\n        <<     \"set d to (year of d) & ':' & \"\n        \"((month of d) as integer) & ':' & \"\n        \"(day of d) & ':' & \"\n        \"(time of d)\"\n        << \"end try\"\n\n        << \"tell application 'iTunes' to tell t\"\n        <<     \"set l to \\\"\\\"\"\n        <<     \"try\"\n        <<          \"set l to location\"\n        <<          \"set l to POSIX path of l\"\n        <<     \"end try\"\n        <<     \"return artist & '\\n' & album artist & '\\n' & name & '\\n' & (duration as integer)  & '\\n' & album & '\\n' & played count  & '\\n' & d & '\\n' & l  & '\\n' & podcast & '\\n' & video kind\"\n        << \"end tell\";\n\n    QString out = script.exec();\n    QTextStream s( &out, QIODevice::ReadOnly );\n\n    t.setArtist( s.readLine() );\n    t.setAlbumArtist( s.readLine() );\n    t.setTitle( s.readLine() );\n    t.setDuration( (uint) s.readLine().toFloat() );\n    t.setAlbum( s.readLine() );\n    t.setPlayCount( s.readLine().toInt() );\n    t.setTimeStamp( qDateTimeFromScriptString( s.readLine() ) );\n\n    QFileInfo fileinfo( s.readLine() );\n    t.setUrl( QUrl::fromLocalFile( fileinfo.absolutePath() ) );\n\n    t.setPodcast( s.readLine() == \"true\" );\n    QString videoKind = s.readLine();\n    t.setVideo( videoKind != \"none\" && videoKind != \"music video\" );\n\n    return t;\n}\n"
  },
  {
    "path": "app/twiddly/ITunesLibrary_win.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesLibrary.h\"\n#include \"IPodScrobble.h\"\n#include \"common/qt/msleep.cpp\"\n#include \"plugins/iTunes/ITunesComWrapper.h\"\n#include <cassert>\n#include <QDateTime>\n#include <QFileInfo>\n#include <QDebug>\n\nusing namespace std;\n\n\nITunesLibrary::ITunesLibrary( const QString&, bool const iPod ) :\n    m_currentIndex( 0 ),\n    m_isIPod( iPod ),\n    m_trackCount( -1 )\n{\n    m_com = new ITunesComWrapper();\n\n    // This will throw if it fails\n    if ( !iPod )\n        m_trackCount = m_com->libraryTrackCount();\n    else\n    {\n        // loop 20 twenty times as sometimes the iPod isn't in iTunes yet and\n        // the plugin has called us prematurely\n        for( int x = 0; x < 20 && m_trackCount == -1; x++)\n        {\n            if (x) Qt::msleep( 500 );\n            // the first ipod is used, which isn't perfect, but oh well\n            m_trackCount = m_com->iPodLibraryTrackCount();\n        }\n    }\n\n    qDebug() << \"Found \" << m_trackCount << \" tracks in iTunes library\";\n\n}\n\n\nITunesLibrary::~ITunesLibrary()\n{\n    delete m_com;\n}\n    \n\nbool\nITunesLibrary::hasTracks() const\n{\n    return (int)m_currentIndex < m_trackCount;\n}\n\n\nint\nITunesLibrary::trackCount() const\n{\n    return m_trackCount;\n}\n\n\nITunesLibrary::Track\nITunesLibrary::nextTrack()\n{\n    // Weird increment is because if this call throws we still want to\n    // have increased m_currentIndex. Otherwise we can get stuck in an\n    // infinite loop calling this function over and over.\n    COM::ITunesTrack it = m_com->track( (++m_currentIndex) - 1 );\n\n    ITunesLibrary::Track t;\n    t.d = (m_isIPod)\n            ? new IPodLibraryTrackData( it )\n            : new ITunesLibraryTrackData( it );\n    return t;\n}\n\n\nTrack\nITunesLibrary::Track::lastfmTrack() const\n{\n    // TODO: why are we doing this? It will return true for manual tracks as it checks the path.\n    if ( isNull() )\n        return Track();\n\n    COM::ITunesTrack i = d->i;\n\n    // These will throw if something goes wrong\n    IPodScrobble t;\n    t.setArtist( QString::fromStdWString( i.artist() ) );\n    t.setAlbumArtist( QString::fromStdWString( i.albumArtist() ) );\n    t.setTitle( QString::fromStdWString( i.track() ) );\n    t.setDuration( i.duration() );\n    t.setAlbum( QString::fromStdWString( i.album() ) );\n    t.setPlayCount( i.playCount() );\n    t.setPodcast( i.podcast() );\n    t.setVideo( i.video() );\n\n    QDateTime stamp = QDateTime::fromString( QString::fromStdWString( i.lastPlayed() ), \"yyyy-MM-dd hh:mm:ss\" );\n    if ( stamp.isValid() )\n    {\n        uint unixTime = stamp.toTime_t();\n\n        // This is to prevent the spurious scrobble bug that can happen if iTunes is\n        // shut during twiddling. The timestamp returned in that case was FFFFFFFF\n        // so let's check for that.\n        if ( unixTime == 0xFFFFFFFF )\n        {\n\t\t\tqWarning() << \"Caught a 0xFFFFFFFF timestamp, assume it's the scrobble of spury:\" << QString::fromStdWString( i.toString() );\n            return Track();\n        } \n        \n        t.setTimeStamp( stamp );\n    }\n    else\n    {\n        // If we don't have a valid timestamp, set to current time. Should work. We hope.\n        qWarning() << \"Invalid timestamp, set to 60 seconds ago:\" << QString::fromStdWString( i.toString() );\n        t.setTimeStamp( QDateTime::currentDateTime().addSecs( -60 ) );\n    }\n\n    const QString path = QString::fromStdWString( i.path() );\n\n\tt.setUrl( QUrl::fromLocalFile( QFileInfo( path ).absoluteFilePath() ) );\n    t.setSource( Track::MediaDevice );\n\n    return t;\n}\n"
  },
  {
    "path": "app/twiddly/PlayCountsDatabase.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlayCountsDatabase.h\"\n#include \"TwiddlyApplication.h\"\n#include \"IPod.h\"\n#include \"ITunesLibrary.h\"\n#include \"common/qt/msleep.cpp\"\n#include \"common/c++/fileCreationTime.cpp\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/mac/AppleScript.h\"\n#include <lastfm/misc.h>\n#include <QSqlDatabase>\n#include <QSqlError>\n#include <QSqlQuery>\n#include <QTemporaryFile>\n#include <iostream>\n#include <QDebug>\n\n#define TABLE_NAME_OLD \"itunes_db\"\n#define TABLE_NAME \"playcounts\"\n#define SCHEMA \"persistent_id   VARCHAR( 32 ) PRIMARY KEY,\" \\\n               \"play_count      INTEGER\"\n#define INDEX \"persistent_id\"\n\n\n/** @author Max Howell <max@last.fm>\n  * @brief automatically log sql errors */\nnamespace QtOverrides\n{\n    class SqlQuery : public ::QSqlQuery\n    {\n        // this is called arse because both check and verify wouldn't compile!\n        bool arse( bool success )\n        {\n            if (!success)\n                qWarning() << lastError().text() << \"in query:\\n\" << lastQuery();\n            return success;\n        }\n        \n    public:\n        SqlQuery( QSqlDatabase db ) : QSqlQuery( db )\n        {}\n                \n        bool exec()\n        {\n            return arse( QSqlQuery::exec() );\n        }\n        \n        bool exec( const QString& sql )\n        {\n            return arse( QSqlQuery::exec( sql ) );\n        }\n    };\n}\n\n#define QSqlQuery QtOverrides::SqlQuery\n\n\nPlayCountsDatabase::PlayCountsDatabase( const QString& path )\n                   : m_path( path )\n{\n    qDebug() << path;\n\n    m_db = QSqlDatabase::addDatabase( \"QSQLITE\", path /*connection-name*/ );\n    m_db.setDatabaseName( path );\n    m_db.open();\n\n    if ( !m_db.isValid() )\n        throw \"Could not open \" + path;\n\n    // rename the old table name if it exists\n    if ( m_db.tables().contains(TABLE_NAME_OLD) )\n    {\n\n        QSqlQuery deleteQuery( m_db );\n        deleteQuery.exec( QString( \"ALTER TABLE itunes_db RENAME TO itunes_db_%1\" ).arg( QDateTime::currentDateTimeUtc().toString( \"yyyyMMddhhmmsszzz\" ) ) );\n    }\n\n    // create the playcounts table if it doesn't already exist\n    if ( !m_db.tables().contains( TABLE_NAME ) )\n    {\n        QSqlQuery query( m_db );\n        query.exec( \"CREATE TABLE \" TABLE_NAME \" ( \" SCHEMA \" );\" );\n        query.exec( \"CREATE INDEX \" INDEX \"_idx ON \" TABLE_NAME \" ( \" INDEX \" );\" );\n    }\n\n    m_query = new QSqlQuery( m_db );\n    m_query->prepare( \"SELECT play_count FROM \" TABLE_NAME \" WHERE persistent_id = :pid LIMIT 1\" );\n\n    QSqlQuery snapshotQuery( m_db );\n    snapshotQuery.exec( \"SELECT persistent_id, play_count FROM \" TABLE_NAME \" ORDER BY persistent_id ASC\" );\n\n    if ( snapshotQuery.first() )\n    {\n        do {\n            bool ok;\n            int count = snapshotQuery.value( 1 ).toInt( &ok );\n\n            if ( ok )\n                m_snapshot[snapshotQuery.value(0).toString()] = count;\n\n        } while ( snapshotQuery.next() );\n    }\n}\n\n\nPlayCountsDatabase::~PlayCountsDatabase()\n{\n    // NOTE don't do this! It closes any copies too, but if we let Qt handle it\n    // it only closes the connection for the last db instance\n    //m_db.close();\n\n    delete m_query;\n\n}\n\n\nPlayCountsDatabase::Track\nPlayCountsDatabase::operator[]( const QString& uid )\n{\n    if ( m_snapshot.contains( uid ) )\n        return Track( uid, m_snapshot[uid] );\n\n    return Track();\n}\n\nPlayCountsDatabase::Track\nPlayCountsDatabase::track( const QString& uid )\n{\n    m_query->bindValue( \":pid\", uid );\n    m_query->exec();\n\n    Q_ASSERT( m_query->size() < 2 );\n\n    if ( m_query->first() )\n    {\n        bool ok;\n        int count = m_query->value( 0 ).toInt( &ok );\n        \n        if ( ok )\n        {\n            return Track( uid, count );\n        }\n    }\n\n    return Track();\n}\n\n\nvoid\nPlayCountsDatabase::beginTransaction()\n{\n    qDebug() << \"beginTransaction\";\n\n    // we try until blue in the face to begin the transaction, as we really,\n    // really want db lock\n    \n    QSqlQuery q( m_db );\n    q.exec( \"BEGIN TRANSACTION\" );\n            \n    for (int i = 5; q.lastError().type() == QSqlError::ConnectionError && i; i--)\n    {\n        // we only try 5 times since SQLITE_BUSY is just one of the\n        // possible things that ConnectionError might mean\n        LOG( 3, \"SQLite might be busy trying again in 25ms...\" );\n        Qt::msleep( 25 );\n\n        q.exec();\n    }\n}\n\n\nvoid\nPlayCountsDatabase::endTransaction()\n{\n    qDebug() << \"endTransaction\";\n\n    // FIXME: what happens if exec returns false?\n    QSqlQuery( m_db ).exec( \"END TRANSACTION;\" );\n}\n\nbool\nPlayCountsDatabase::insert( const ITunesLibrary::Track& track )\n{\n    QString playCount = QString::number( track.playCount() );  \n    QString sql = \"INSERT OR ROLLBACK INTO \" TABLE_NAME \" ( persistent_id, play_count ) \"\n                  \"VALUES ( '\" + track.persistentId() + \"', '\" + playCount + \"' )\";\n    return QSqlQuery( m_db ).exec( sql );\n}\n\nbool\nPlayCountsDatabase::update( const ITunesLibrary::Track& track )\n{\n    QString playCount = QString::number( track.playCount() );  \n    QString sql = \"UPDATE OR ROLLBACK \" TABLE_NAME \" \"\n                  \"SET play_count='\" + playCount + \"' \"\n                  \"WHERE persistent_id='\" + track.persistentId() + \"'\";\n    return QSqlQuery( m_db ).exec( sql );\n}\n\nAutomaticIPod::PlayCountsDatabase::PlayCountsDatabase() \n#ifdef Q_OS_MAC\n              : ::PlayCountsDatabase( lastfm::dir::runtimeData().filePath( \"iTunesPlays.db\" ) )\n#else\n              : ::PlayCountsDatabase( lastfm::dir::runtimeData().filePath( \"Client/iTunesPlays.db\" ) )\n#endif\n{}\n\n\nbool\nAutomaticIPod::PlayCountsDatabase::isBootstrapNeeded() const\n{\n    QSqlQuery q( m_db );\n    q.exec( \"SELECT value FROM metadata WHERE key='bootstrap_complete'\" );\n    if (q.next() && q.value( 0 ).toString() == \"true\")\n        return false;\n        \n    return true;\n}\n\n\nstatic QString\npluginPath()\n{\n  #ifdef Q_OS_MAC\n    QString path = std::getenv( \"HOME\" );\n    path += \"/Library/iTunes/iTunes Plug-ins/AudioScrobbler.bundle/Contents/MacOS/AudioScrobbler\";\n    return path;\n  #else\n    QSettings settings( \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Last.fm\\\\Client\\\\Plugins\\\\\", QSettings::NativeFormat );\n    QString path = settings.value( \"itw/Path\" ).toString();\n    if (path.isEmpty())\n        throw \"Unknown iTunes plugin path\";\n    return path;\n  #endif\n}\n\nvoid\nAutomaticIPod::PlayCountsDatabase::bootstrap()\n{\n    qDebug() << \"Starting bootstrapping...\";\n    \n    static_cast<TwiddlyApplication*>(qApp)->sendBusMessage( \"container://Notification/Twiddly/Bootstrap/Started\" );\n\n    beginTransaction();    \n    \n    QSqlQuery query( m_db );\n    // this will fail if the metadata table doesn't exist, which is fine\n    query.exec( \"DELETE FROM metadata WHERE key='bootstrap_complete'\" );\n    query.exec( \"DELETE FROM metadata WHERE key='plugin_ctime'\" );\n    query.exec( \"DELETE FROM \" TABLE_NAME_OLD );\n    query.exec( \"DELETE FROM \" TABLE_NAME );\n\n    ITunesLibrary lib;\n    \n    // for wizard progress screen\n    std::cout << lib.trackCount() << std::endl;\n    \n    int i = 0;\n\n    while (lib.hasTracks())\n    {\n        try\n        {\n            ITunesLibrary::Track const t = lib.nextTrack();\n            QString const plays = QString::number( t.playCount() );\n\n            query.exec( \"INSERT OR IGNORE INTO \" TABLE_NAME \" ( persistent_id, play_count ) \"\n                        \"VALUES ( '\" + t.uniqueId() + \"', '\" + plays + \"' )\" );\n\n        }\n        catch ( ... )\n        {\n            // Move on...\n        }\n\n        std::cout << ++i << std::endl;\n    }\n\n    // if either INSERTS fail we'll rebootstrap next time\n    query.exec( \"CREATE TABLE metadata (key VARCHAR( 32 ), value VARCHAR( 32 ))\" );\n    query.exec( \"INSERT INTO metadata (key, value) VALUES ('bootstrap_complete', 'true')\" );\n    \n    QString const t = QString::number( common::fileCreationTime( pluginPath() ) );\n    query.exec( \"INSERT INTO metadata (key, value) VALUES ('plugin_ctime', '\"+t+\"')\" );\n\n\n    endTransaction();\n\n    static_cast<TwiddlyApplication*>(qApp)->sendBusMessage( \"container://Notification/Twiddly/Bootstrap/Finished\" );\n}\n"
  },
  {
    "path": "app/twiddly/PlayCountsDatabase.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAY_COUNT_DATABASE_H\n#define PLAY_COUNT_DATABASE_H\n\n#include <QString>\n#include <QSqlDatabase>\n#include <QHash>\n\nclass QSqlQuery;\n\nclass ITunesLibraryTrack;\n\n\n/** @author Jono Cole <jono@last.fm>\n  * @refactor Max Howell <max@last.fm>\n  * @contributor Christian Muehlhaeuser <chris@last.fm>\n  *\n  * Derived by ManualIPodDatabase and AutomaticIPodDatabase \n  */\nclass PlayCountsDatabase\n{\nprotected:\n    /** pass the path for the db, you need to make sure the directory exists */\n    PlayCountsDatabase( const QString& path );\n\npublic:\n    virtual ~PlayCountsDatabase();\n\n    class Track\n    {\n    public:\n        Track() : m_playCount( 0 )\n        {}\n\n        Track( const QString& uid, int c )\n        {\n            m_playCount = c;\n            m_id = uid;\n        }\n\n        bool isNull() const { return m_id.isEmpty(); }\n        QString uniqueId() const { return m_id; }\n        int playCount() const { return m_playCount; }\n \n    private:\n        QString m_id;\n        int m_playCount;\n    };\n\n    /** the uid is path on Windows, persistentId on mac */\n    Track operator[]( const QString& uid ); // gets the snapshot value\n    Track track( const QString& uid ); // this actually fetchs the current value\n\n    // NOTE never put these in the ctor/dtor, as if exception is thrown we \n    // mustn't commit the transaction!\n    void beginTransaction();\n    void endTransaction();\n\n    /** the justification for INSERT is manual ipod scrobbling, since we have\n      * no bootstrap step, which is unavoidable, the first diff effectively\n      * bootstraps the device */\n    bool insert( const ITunesLibraryTrack& track );\n    bool remove( const ITunesLibraryTrack& track );\n    bool update( const ITunesLibraryTrack& track );\n\n    QString path() const { return m_path; }\n\nprotected:\n  #ifdef Q_OS_WIN32\n    bool exec( const QString& sql, const ITunesLibraryTrack& );\n  #endif\n\nprotected:\n    QSqlDatabase m_db;\n    QSqlQuery* m_query;\n    QHash<QString,int> m_snapshot;\n\nprivate:\n    Q_DISABLE_COPY( PlayCountsDatabase )\n\n    QString m_path;\n};\n\n#endif //PLAY_COUNT_DATABASE_H\n"
  },
  {
    "path": "app/twiddly/README",
    "content": "Twiddly is coupled to the iPod handling component of the iTunes plugin and the\nLast.fm Client software.\n\nIt is launched when an iPod has finished syncing with iTunes and compares the\niTunesPlaysDatabase with the iTunes Library Database, and thus determines what\nhas been played by an iPod.\n\nIt is a separate process for the purpose of writing simpler code, and the\nuse-case where the client is not running.\n"
  },
  {
    "path": "app/twiddly/Twiddly.rc",
    "content": "IDI_ICON1 ICON DISCARDABLE \"..\\\\..\\\\admin\\\\dist\\\\win\\\\installer.ico\"\r\n\r\n// The first entry ('1') on the below line is normally written as the define\r\n// VS_VERSION_INFO, but we can't always be sure that value has been included\r\n// in a Qt build so we just hardcode 1 in.\r\n1 VERSIONINFO\r\n FILEVERSION 0,0,0,0\r\n PRODUCTVERSION 0,0,0,0\r\n FILEFLAGSMASK 0x3fL\r\n#ifdef _DEBUG\r\n FILEFLAGS 0x1L\r\n#else\r\n FILEFLAGS 0x0L\r\n#endif\r\n FILEOS 0x4L\r\n FILETYPE 0x1L\r\n FILESUBTYPE 0x0L\r\nBEGIN\r\n    BLOCK \"StringFileInfo\"\r\n    BEGIN\r\n        BLOCK \"040904b0\"\r\n        BEGIN\r\n            VALUE \"Comments\", \"http://www.last.fm\"\r\n            VALUE \"CompanyName\", \"Last.fm\"\r\n            VALUE \"FileDescription\", \"Last.fm iPodScrobbler\"\r\n            VALUE \"FileVersion\", \"0.0.0.0\\0\"\r\n            VALUE \"InternalName\", \"Last.fm iPodScrobbler\"\r\n            VALUE \"LegalCopyright\", \"Copyright (C) 2008\"\r\n            VALUE \"OriginalFilename\", \"iPodScrobbler.exe\"\r\n            VALUE \"ProductName\", \"Last.fm iPodScrobbler\"\r\n            VALUE \"ProductVersion\", \"0.0.0.0\\0\"\r\n        END\r\n    END\r\nEND\r\n"
  },
  {
    "path": "app/twiddly/TwiddlyApplication.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd.\r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik,\r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include \"TwiddlyApplication.h\"\r\n\r\nTwiddlyApplication::TwiddlyApplication( int& argc, char** argv )\r\n    :unicorn::CoreApplication( \"fm.last.Twiddly\", argc, argv )\r\n{\r\n}\r\n\r\nvoid\r\nTwiddlyApplication::sendBusMessage( const QByteArray& /*msg*/ )\r\n{\r\n    //m_bus.sendMessage( msg );\r\n}\r\n\r\n"
  },
  {
    "path": "app/twiddly/TwiddlyApplication.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd.\r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik,\r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include \"lib/unicorn/UnicornCoreApplication.h\"\r\n\r\nclass TwiddlyApplication : public unicorn::CoreApplication\r\n{\r\n    Q_OBJECT\r\npublic:\r\n    TwiddlyApplication(int& argc, char** argv);\r\n\r\n    void sendBusMessage( const QByteArray& msg );\r\n};\r\n"
  },
  {
    "path": "app/twiddly/Utils.cpp",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n\n\n#include <QProcess>\n#include <QSettings>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n#include <lastfm/misc.h>\n\n#include \"Utils.h\"\n\n#ifndef Q_OS_MAC\nvoid\nUtils::startAudioscrobbler( QStringList& vargs )\n{\n    QString path = unicorn::AppSettings( \"Client\" ).value( \"Path\" ).toString();\n    if ( path.size() == 0 )\n    {\n        path = unicorn::AppSettings( \"Last.fm\" ).value( \"Path\" ).toString();\n\n        if ( path.size() == 0 )\n        {\n            path = lastfm::dir::programFiles().filePath( \"Last.fm/Last.fm.exe\" );\n        }\n    }\n\n    QProcess::startDetached( path, vargs );\n}\n\n#endif // Q_OS_MAC\n"
  },
  {
    "path": "app/twiddly/Utils.h",
    "content": "/*\n   Copyright 2005-2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#include <QStringList>\n\nclass Utils\n{\npublic:\n    static void startAudioscrobbler( QStringList& vargs );\n};\n\n#endif // UTILS_H\n"
  },
  {
    "path": "app/twiddly/Utils_mac.mm",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Utils.h\"\n\n#define AUDIOSCROBBLER_BUNDLEID \"fm.last.Scrobbler\"\n#include <ApplicationServices/ApplicationServices.h>\n\n//This macro clashes with Qt headers\n#undef check\n\nvoid\nUtils::startAudioscrobbler( QStringList& vargs )\n{\n    FSRef appRef;\n    LSFindApplicationForInfo( kLSUnknownCreator, CFSTR( AUDIOSCROBBLER_BUNDLEID ), NULL, &appRef, NULL );\n\n    const void* arg[vargs.size()];\n\n    int index(0);\n\n    AEDescList argAEList;\n    AECreateList( NULL, 0, FALSE, &argAEList );\n\n    foreach( QString i, vargs ) {\n        arg[index++] = CFStringCreateWithCString( NULL, i.toUtf8().data(), kCFStringEncodingUTF8 );\n        AEPutPtr( &argAEList, 0, typeChar, i.toUtf8().data(), i.toUtf8().length());\n    }\n\n    LSApplicationParameters params;\n    params.version = 0;\n    params.flags = kLSLaunchAndHide | kLSLaunchDontSwitch | kLSLaunchAsync;\n    params.application = &appRef;\n    params.asyncLaunchRefCon = NULL;\n    params.environment = NULL;\n\n    CFArrayRef args = CFArrayCreate( NULL, ((const void**)arg), vargs.size(), NULL);\n    params.argv = args;\n\n\n    AEAddressDesc target;\n    AECreateDesc( typeApplicationBundleID, CFSTR( AUDIOSCROBBLER_BUNDLEID ), 16, &target);\n\n    AppleEvent event;\n    AECreateAppleEvent ( kCoreEventClass,\n            kAEReopenApplication ,\n            &target,\n            kAutoGenerateReturnID,\n            kAnyTransactionID,\n            &event );\n\n    AEPutParamDesc( &event, keyAEPropData, &argAEList );\n\n    params.initialEvent = &event;\n\n    LSOpenApplication( &params, NULL );\n    //AEDisposeDesc( &argAEList );\n    //AEDisposeDesc( &target );\n}\n"
  },
  {
    "path": "app/twiddly/main.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"IPod.h\"\n#include \"TwiddlyApplication.h\"\n#include \"Utils.h\"\n\n#include \"plugins/iTunes/ITunesExceptions.h\"\n#include \"common/c++/Logger.h\"\n#include \"lib/unicorn/UnicornCoreApplication.h\"\n\n#ifdef Q_OS_MAC\n#include \"lib/unicorn/plugins/Version.h\"\n#include \"lib/unicorn/plugins/ITunesPluginInstaller.h\"\n#else\n#include \"lib/unicorn/plugins/ITunesPluginInfo.h\"\n#endif\n\n#include <lastfm/misc.h>\n\n#include <QtCore>\n#include <QtXml>\n#include <iostream>\n\nvoid writeXml( const QDomDocument&, const QString& path );\nvoid logException( QString );\n\n\n/**\n  *\n  * Fake params: --device ipod --connection usb --pid 4611 --vid 1452 --serial 000000C8B035\n  */\nint\nmain( int argc, char** argv )\n{\n    // Make sure the logger exists in this binary\n#ifdef Q_OS_WIN\n    QString bytes = TwiddlyApplication::log( TwiddlyApplication::applicationName() ).absoluteFilePath();\n    const wchar_t* path = bytes.utf16();\n#else\n    QByteArray bytes = TwiddlyApplication::log( TwiddlyApplication::applicationName() ).absoluteFilePath().toLocal8Bit();\n    const char* path = bytes.data();\n#endif\n    new Logger( path );\n\n    TwiddlyApplication::setApplicationName( \"iPodScrobbler\" );\n    TwiddlyApplication::setApplicationVersion( \"2\" );\n\n    TwiddlyApplication app( argc, argv );\n\n    if ( app.isRunning() )\n    {\n        qDebug() << \"The iPod Scrobbler is already running. Shutting down\" << app.arguments();\n        return 1;\n    }\n\n    // check we're using a compatible version of the plugin\n    unicorn::Version compatibleVersion( 6, 0, 5, 4 );\n    unicorn::Version installedVersion;\n#ifdef Q_OS_WIN\n    unicorn::ITunesPluginInfo* iTunesPluginInfo = new unicorn::ITunesPluginInfo;\n    installedVersion = iTunesPluginInfo->installedVersion();\n    delete iTunesPluginInfo;\n#else\n    // TODO: get the actual installed version\n    installedVersion = unicorn::ITunesPluginInstaller::installedVersion();\n#endif\n\n    if ( installedVersion < compatibleVersion )\n    {\n        // tell the app that the plugin is incompatible\n        QStringList args;\n        args << \"--tray\";\n        args << \"--twiddly\";\n        args << \"incompatible-plugin\";\n\n        Utils::startAudioscrobbler( args );\n\n        qDebug() << \"The iTunes pluggin is old and incompatible. Please update. Shutting down\" << app.arguments();\n        return 1;\n    }\n\n    try\n    {\n        if ( app.arguments().contains( \"--bootstrap-needed?\" ) )\n        {\n            return AutomaticIPod::PlayCountsDatabase().isBootstrapNeeded();\n        }        \n\n        QDateTime start_time = QDateTime::currentDateTime();\n        QTime time;\n        time.start();\n\n        if ( app.arguments().contains( \"--bootstrap\" ) )\n        {\n            AutomaticIPod::PlayCountsDatabase().bootstrap();\n        }\n        else // twiddle!\n        {\n            app.sendBusMessage( \"--twiddling\" );\n\n            IPod* ipod = IPod::fromCommandLineArguments( app.arguments() );\n\n            {\n                QStringList args;\n                args << \"--tray\";\n                args << \"--twiddly\";\n                args << \"starting\";\n                args << \"--deviceId\";\n                args << ipod->uid();\n                args << \"--deviceName\";\n                args << ipod->name;\n\n                Utils::startAudioscrobbler( args );\n            }\n\n            qDebug() << \"Twiddling device: \" << ipod->serial;\n            ipod->twiddle();\n\n            //------------------------------------------------------------------\n            IPodType previousType = ipod->settings().type();\n            IPodType currentType = app.arguments().contains( \"--manual\" ) ? IPodManualType : IPodAutomaticType;\n\n            if ( previousType == IPodManualType && currentType == IPodAutomaticType )\n            {\n                qDebug() << \"iPod switched from manual to automatic - deleting manual db and ignoring scrobbles\";\n\n                // The iPod was manual, but is now automatic, we must:\n                // 1. remove the manual db, to avoid misscrobbles if it ever becomes\n                //    manual again\n                QString path = ManualIPod::PlayCountsDatabase( ipod ).path();\n                QFile( path ).remove();\n\n                // 2. not scrobble this time :( because any tracks that were on the\n                //    the iPod and are also in the iTunes library will be merged\n                //    and if they ever played on the iPod, will increase the iTunes\n                //    library playcounts. We need to sync the Automatic playcountsdb\n                //    but not scrobble anything.\n                ipod->scrobbles().clear();\n            }\n\n            ipod->settings().setType( currentType );\n            //------------------------------------------------------------------\n\n            if (ipod->scrobbles().count())\n            {\n                // create a unique storage location for the XML\n                QDir dir = ipod->saveDir().filePath( \"scrobbles\" );\n                QString filename = QDateTime::currentDateTime().toString( \"yyyyMMddhhmmss\" ) + \".xml\";\n                QString path = dir.filePath( filename );\n                dir.mkpath( \".\" );\n\n                QDomDocument xml = ipod->scrobbles().xml();\n                xml.documentElement().setAttribute( \"uid\", ipod->uid() );\n                writeXml( xml, path );\n\n                QStringList args;\n                args << \"--tray\";\n                args << \"--twiddly\";\n                args << \"complete\";\n                args << \"--ipod-path\";\n                args << path;\n                args << \"--deviceId\";\n                args << ipod->uid();\n                args << \"--deviceName\";\n                args << ipod->name;\n\n                Utils::startAudioscrobbler( args );\n            }\n            else\n            {\n                QStringList args;\n                args << \"--tray\";\n                args << \"--twiddly\";\n                args << \"no-tracks-found\";\n                args << \"--deviceId\";\n                args << ipod->uid();\n                args << \"--deviceName\";\n                args << ipod->name;\n\n                Utils::startAudioscrobbler( args );\n            }\n\n            // do last so we don't record a sync if we threw and thus it \"didn't\" happen\n            ipod->settings().setLastSync( start_time );\n            delete ipod;           \n        }\n        \n        qDebug() << \"Procedure took:\" << time.elapsed() << \"milliseconds\";\n    }\n    catch( QString& s )\n    {\n        logException( s );\n    }\n    catch( std::string& s )\n    {\n        logException( QString::fromStdString( s ) );\n    }\n    catch( const char* s )\n    {\n        logException( s );\n    }\n    catch( ITunesException& e )\n    {\n        logException( e.what() );\n    }\n    \n    return 0;\n}\n\n\nvoid\nwriteXml( const QDomDocument& xml, const QString& path )\n{\n    // we write to a temporary file, and then do an atomic move\n    // this prevents the client from potentially reading a corrupt XML file\n    QTemporaryFile f;\n\n    f.setAutoRemove( false );\n    \n    if (!f.open())\n        throw \"Couldn't write XML\";\n\n    QTextStream s( &f );\n    xml.save( s, 2 );\n    \n    if ( !f.rename( path ) )\n        throw QString(\"Couldn't move to \") + path;\n}\n\n\nvoid\nlogException( QString message )\n{\n    qCritical() << \"FATAL ERROR:\" << message;\n    \n    // we do this because LfmApp splits on spaces in parseMessage()\n    message.replace( ' ', '_' );\n    static_cast<TwiddlyApplication*>(qApp)->sendBusMessage( QString( \"container://Notification/Twiddly/Error/\" + message ).toAscii() );\n}\n"
  },
  {
    "path": "app/twiddly/twiddly.pro",
    "content": "TARGET = iPodScrobbler\nLIBS += -lunicorn -llastfm\nQT = core xml sql\n\nCONFIG += lastfm logger\nCONFIG -= app_bundle\n\ninclude( ../../admin/include.qmake )\n\n# TODO: FIX THIS: I think this means that we can only build bundles\nmac {\n    DESTDIR = \"../../_bin/Last.fm Scrobbler.app/Contents/Helpers\"\n    QMAKE_POST_LINK += ../../admin/dist/mac/bundleFrameworks.sh \\\"$$DESTDIR/$$TARGET\\\"\n}\n\nDEFINES += LASTFM_COLLAPSE_NAMESPACE\nSOURCES = main.cpp \\\n          TwiddlyApplication.cpp \\\n          PlayCountsDatabase.cpp \\\n          IPod.cpp \\\n          Utils.cpp\n\nHEADERS = TwiddlyApplication.h \\\n          PlayCountsDatabase.h \\\n          IPod.h \\\n          Utils.h\n\nmac {\n    SOURCES += ITunesLibrary_mac.cpp\n    OBJECTIVE_SOURCES += Utils_mac.mm\n}\n\nwin32 {\n    # Would prefer to refer to ITunesTrack.cpp and ITunesComWrapper.cpp in-situ\n    # in the ../../plugins/iTunes/ directory, but that triggers bugs in nmake\n    # causing it to compile the wrong main.cpp and IPod.cpp!\n    # So here we are copying them and their dependencies.\n    # Oh, and for some reason, cygwin mutilates their permissions.\n    \n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesTrack.cpp . /Y /Q )\n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesTrack.h . /Y /Q )\n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesExceptions.h . /Y /Q )\n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesComWrapper.cpp . /Y /Q )\n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesComWrapper.h . /Y /Q )\n    system( xcopy ..\\\\..\\\\plugins\\\\iTunes\\\\ITunesEventInterface.h . /Y /Q )\n\n    SOURCES += ITunesLibrary_win.cpp \\\n               ITunesTrack.cpp \\\n               ITunesComWrapper.cpp \\\n               $$ROOT_DIR/plugins/scrobsub/EncodingUtils.cpp \\\n               $$ROOT_DIR/lib/3rdparty/iTunesCOMAPI/iTunesCOMInterface_i.c\n\n    HEADERS += ITunesTrack.h \\\n               ITunesComWrapper.h \\\n               ITunesEventInterface.h \\\n               ITunesExceptions.h \\\n               $$ROOT_DIR/plugins/scrobsub/EncodingUtils.h\n\n    LIBS += -lcomsuppw\n\n    DEFINES += _WIN32_DCOM\n    RC_FILE = Twiddly.rc\n}\n"
  },
  {
    "path": "common/HideStupidWarnings.h",
    "content": "#ifdef Q_CC_MSVC //prevent gcc issuing warning about the pragma! lol ;)\r\n// ms admits its lousy compiler doesn't care about throw declarations\r\n#pragma warning( disable : 4290 )\r\n#endif\r\n"
  },
  {
    "path": "common/c++/Logger.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"Logger.h\"\n#include <ctime>\n#include <iostream>\n#include <iomanip>\n#include <cstdlib>\n\n#ifndef WIN32\n    #include <sys/stat.h>\n    #include <pthread.h>\n#endif\n\nLogger* instance = 0;\n\nLogger::Logger( const COMMON_CHAR* path, Severity severity ) \n      : mLevel( severity )\n{\n    using namespace std;\n    \n    instance = this;\n\n#ifdef WIN32\n    InitializeCriticalSection( &mMutex );\n#else\n    pthread_mutexattr_t attr;\n    pthread_mutexattr_init( &attr );\n    pthread_mutex_init( &mMutex, &attr );\n#endif\n\n#ifdef WIN32\n    HANDLE hFile = CreateFileW( path,\n                               GENERIC_READ,\n                               0, \n                               NULL,\n                               OPEN_EXISTING, \n                               FILE_ATTRIBUTE_NORMAL, \n                               NULL);\n    long const fileSize = GetFileSize( hFile, NULL );\n    CloseHandle( hFile );\n#else\n    struct stat st;\n    long const fileSize = stat( path, &st ) == 0 ? st.st_size : 0;\n#endif\n\n    if ( fileSize > 500000 )\n        truncate( path );\n\n    ios::openmode flags = ios::out | ios::app;\n    mFileOut.open( path, flags );\n\n    if (!mFileOut)\n    {\n\t#ifdef WIN32\n\t\tOutputDebugStringA( \"Could not open log file:\" );\n\t\tOutputDebugStringW( path );\n\t#else\n\t\tcerr << \"Could not open log file\" << path;\n\t#endif\n        return;\n    }\n    \n    mFileOut << endl << endl;\n    mFileOut << \"==========================================================================lastfm\" << endl;\n}\n\n\nLogger::~Logger()\n{\n    mFileOut.close();\n#ifdef WIN32\n    DeleteCriticalSection( &mMutex );\n#else\n    pthread_mutex_destroy( &mMutex );\n#endif\n}\n\n\nstatic inline std::string time()\n{\n    time_t now;\n    time( &now );\n    char s[128];\n    strftime( s, 127, \"%y%m%d %H:%M:%S\", gmtime( &now ) );\n    return std::string( s);\n}\n\n\nvoid\nLogger::log( const char* message )\n{\n    if (!mFileOut.is_open())\n        return;\n\n#ifdef WIN32\n    EnterCriticalSection( &mMutex );\n#else\n    pthread_mutex_lock( &mMutex );\n#endif\n    mFileOut << \"[\" << time() << \"] \" << message << std::endl;\n\n#ifdef WIN32\n    LeaveCriticalSection( &mMutex );\n#else\n    pthread_mutex_unlock( &mMutex );\n#endif\n}\n\n\nvoid\nLogger::log( Severity level, const std::string& message, const char* function, int line )\n{\n    if (level > mLevel)\n        return;\n\n    std::ostringstream s;\n    s << function << \"()\";\n    if (level < mLevel)\n        s << line << \": L\" << level;\n    s << std::endl;\n    s << message << std::endl;\n\n    log( s.str().c_str() );\n}\n\n\n#ifdef WIN32\nvoid\nLogger::log( Severity level, const std::wstring& in, const char* function, int line )\n{\n    // first call works out required buffer length\n    int recLen = WideCharToMultiByte( CP_ACP, 0, in.c_str(), (int)in.size(), NULL, NULL, NULL, NULL );\n\n    char* buffer = new char[recLen + 1];\n    memset(buffer,0,recLen+1);\n\n    // second call actually converts\n    WideCharToMultiByte( CP_ACP, 0, in.c_str(), (int)in.size(), buffer, recLen, NULL, NULL );\n    std::string message = buffer;\n    delete[] buffer;\n\n    log( level, message, function, line );\n}\n#endif\n\n\nvoid\nLogger::truncate( const COMMON_CHAR* path ) //static\n{\n    using namespace std;\n    \n    ifstream inFile( path );\n    inFile.seekg( -400000, std::ios_base::end );\n    istreambuf_iterator<char> bufReader( inFile ), end;\n    string sFile;\n    sFile.reserve( 400005 );\n    sFile.assign( bufReader, end );\n    inFile.close();\n    ofstream outFile( path );\n    outFile << sFile << flush;\n    outFile.close();\n}\n\nLogger&  //static\nLogger::the() {\n    return *instance;\n}\n"
  },
  {
    "path": "common/c++/Logger.h",
    "content": " /*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LOGGER_H\n#define LOGGER_H\n\n#include \"lib/DllExportMacro.h\"\n\n#include \"common/c++/string.h\"\n#include <fstream>\n#include <sstream>\n#ifdef WIN32\n#include <windows.h> //for CRITICAL_SECTION\n#pragma warning(disable: 4251)\n#endif\n\n\nclass LOGGER_DLLEXPORT Logger\n{\npublic:\n    enum Severity\n    {\n        Critical = 1,\n        Warning,\n        Info,\n        Debug\n    };\n\n    /** Sets the Logger instance to this, so only call once, and make it exist\n      * as long as the application does */\n    explicit Logger( const COMMON_CHAR* filename, Severity severity = Info );\n    ~Logger();\n\n    static Logger& the();\n\n    void log( Severity level, const std::string& message, const char* function, int line );\n    void log( Severity level, const std::wstring& message, const char* function, int line );\n    \n    /** plain write + flush, we suggest utf8 */\n    void log( const char* message );\n\n    static void truncate( const COMMON_CHAR* path );\n    \nprivate:\n    const Severity mLevel;\n#ifdef WIN32\n    CRITICAL_SECTION mMutex;\n#else\n    pthread_mutex_t mMutex;\n#endif\n    std::ofstream mFileOut;\n};\n\n\n/** use these to log */\n#define LOG( level, msg ) { \\\n    std::ostringstream ss; \\\n    ss << msg; \\\n    Logger::the().log( (Logger::Severity) level, ss.str(), __FUNCTION__, __LINE__ ); }\n#define LOGL LOG\n#define LOGW( level, msg ) { \\\n\tstd::wostringstream ss; \\\n\tss << msg; \\\n        Logger::the().log( (Logger::Severity) level, ss.str(), __FUNCTION__, __LINE__ ); }\n#define LOGWL LOGW\n#endif\n"
  },
  {
    "path": "common/c++/fileCreationTime.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"Logger.h\"\n#include <sys/stat.h>\n\n\n/** @author Max Howell \n  * @brief Used by Twiddly and iTunesPlugin\n  */\nnamespace common\n{\n    #if WIN32\n        #define STRING wstring\n        #define STAT _stat\n        #define stat _wstat\n        #define COMMON_LOG LOGW\n    #else\n        #define STAT stat\n        #define STRING string\n        #define COMMON_LOG LOG\n    #endif\n\n    static time_t\n    fileCreationTime( const std::STRING& path )\n    {\n        struct STAT st;\n        if (stat( path.c_str(), &st ) != 0)\n        {\n            //COMMON_LOG( 3, \"Couldn\\'t stat\" << path );\n            return 0;\n        }\n        else\n            return st.st_ctime ? st.st_ctime : st.st_mtime;\n    }\n\n    #undef STAT\n    #undef stat\n    #undef STRING\n    #undef COMMON_LOG\n\n#ifdef QT_CORE_LIB\n    static inline time_t\n    fileCreationTime( const QString& path )\n    {\n    #ifdef Q_OS_WIN32\n        return fileCreationTime( path.toStdWString() );\n    #else\n        return fileCreationTime( path.toStdString() );\n    #endif\n    }\n#endif\n}\n"
  },
  {
    "path": "common/c++/mac/getBsdProcessList.c",
    "content": "// public domain\n// http://developer.apple.com/qa/qa2001/qa1123.html\n\n#include <sys/sysctl.h>\n#include <cerrno>\n\n\n/** Returns a list of all BSD processes on the system.  This routine\n  * allocates the list and puts it in *procList and a count of the\n  * number of entries in *procCount.  You are responsible for freeing\n  * this list (use \"free\" from System framework).\n  * On success, the function returns 0.\n  * On error, the function returns a BSD errno value. \n  */\nstatic int\ngetBsdProcessList( kinfo_proc **procList, size_t *procCount )\n{\n    int                 err;\n    kinfo_proc *        result;\n    bool                done;\n    static const int    name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };\n    // Declaring name as const requires us to cast it when passing it to\n    // sysctl because the prototype doesn't include the const modifier.\n    size_t              length;\n\n    // We start by calling sysctl with result == NULL and length == 0.\n    // That will succeed, and set length to the appropriate length.\n    // We then allocate a buffer of that size and call sysctl again\n    // with that buffer.  If that succeeds, we're done.  If that fails\n    // with ENOMEM, we have to throw away our buffer and loop.  Note\n    // that the loop causes use to call sysctl with NULL again; this\n    // is necessary because the ENOMEM failure case sets length to\n    // the amount of data returned, not the amount of data that\n    // could have been returned.\n    result = NULL;\n    done = false;\n    *procCount = 0;\n\n    do\n    {\n        // Call sysctl with a NULL buffer.\n        length = 0;\n        err = sysctl( (int *) name, ( sizeof( name ) / sizeof( *name ) ) - 1, NULL, &length, NULL, 0 );\n        if (err == -1)\n        {\n            err = errno;\n        }\n\n        // Allocate an appropriately sized buffer based on the results\n        // from the previous call.\n        if ( err == 0 )\n        {\n            result = (kinfo_proc*)malloc( length );\n            if ( result == NULL )\n            {\n                err = ENOMEM;\n            }\n        }\n\n        // Call sysctl again with the new buffer.  If we get an ENOMEM\n        // error, toss away our buffer and start again.\n        if ( err == 0 )\n        {\n            err = sysctl( (int *) name, ( sizeof( name ) / sizeof( *name ) ) - 1, result, &length, NULL, 0 );\n            if ( err == -1 )\n            {\n                err = errno;\n            }\n            if (err == 0)\n            {\n                done = true;\n            } else if ( err == ENOMEM )\n            {\n                free( result );\n                result = NULL;\n                err = 0;\n            }\n        }\n    } while ( err == 0 && !done );\n\n    // Clean up and establish post conditions.\n    if ( err != 0 && result != NULL )\n    {\n        free( result );\n        result = NULL;\n    }\n\n    *procList = result;\n    if ( err == 0 )\n    {\n        *procCount = length / sizeof( kinfo_proc );\n    }\n\n    return err;\n}"
  },
  {
    "path": "common/c++/string.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifdef WIN32\n    #define COMMON_STD_STRING std::wstring\n    #define COMMON_CHAR wchar_t\n#else\n    #define COMMON_STD_STRING std::string\n    #define COMMON_CHAR char\n#endif\n\n#include <string>\n"
  },
  {
    "path": "common/c++/win/scrobSubPipeName.cpp",
    "content": "/* Copyright 2005-2009, Last.fm Ltd. <client@last.fm>                       \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"windows.h\"\n#include \"Sddl.h\"       // for ConvertSidToString (_WIN32_WINNT = 0x0500)\n#include <string>\n#include <sstream>\n#include <iomanip>\n\nusing namespace std;\n\n\nstring\nformatWin32Error(DWORD error)\n{\n    LPSTR buffer;\n    if (FormatMessageA(\n        FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,\n        0,      // ignored\n        error,\n        0,      // default langid behaviour\n        (LPSTR) &buffer,   // yay win32!\n        0,      // min chars alloc'd in buffer\n        0       // no arguments!\n        ))\n    {\n        // got message\n        string result;\n        result.assign(buffer);\n        LocalFree(buffer);\n        return result;\n    }\n\n    ostringstream os;\n    os << \"0x\" << setfill('0') << setw(8) << setbase(16) << error;\n    return os.str();\n}\n\n// create a name (for the scrobsub pipe) based on the SID of the user running this process\n// return win32 error code (0 == success)\nDWORD\nscrobSubPipeName(string* pipeName)\n{\n    #define PIPE_PREFIX \"\\\\\\\\.\\\\pipe\\\\lastfm_scrobsub_\"\n\n    bool ok = false;\n\n    HANDLE hToken;\n    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))\n    {\n        DWORD outLen;\n        #define BUFFER_SIZE 256\n        char buffer[BUFFER_SIZE] = { 0 } ;  // init just to suppress warning \n        if (GetTokenInformation(hToken, TokenOwner, buffer, BUFFER_SIZE, &outLen))\n        {\n            LPSTR sidstring;\n            TOKEN_OWNER* tokenOwner = (TOKEN_OWNER*) buffer;\n            if (ConvertSidToStringSidA(tokenOwner->Owner, &sidstring))\n            {\n                ostringstream os;\n                os << PIPE_PREFIX << sidstring;\n                *pipeName = os.str();\n                LocalFree(sidstring);\n                ok = true;\n            }\n        }\n        CloseHandle(hToken);\n    }\n\n    return ok ? 0 : GetLastError();\n}\n\n"
  },
  {
    "path": "common/precompiled.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QtCore>\n#include <QtGui>\n#include <QtNetwork>\n#include <QtXml>\n"
  },
  {
    "path": "common/qt/README",
    "content": "These functions are small utility functions that only depend on Qt.\n"
  },
  {
    "path": "common/qt/msleep.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QThread>\n\n\nnamespace Qt\n{\n\tstatic inline void msleep( uint ms )\n\t{\n\t\tstruct Thread : QThread { using QThread::msleep; };\n\t\tThread::msleep( ms );\n\t}\n}\n"
  },
  {
    "path": "common/qt/override/QDebug",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef QT_OVERRIDE_QDEBUG\n#define QT_OVERRIDE_QDEBUG\n\n#include <QtCore/QDebug>\n#include <QTime>\n\n#ifdef WIN32\n    #define __PRETTY_FUNCTION__ __FUNCTION__\n#endif\n\n\nstruct StampedDebug : QDebug\n{\n\tStampedDebug( QtMsgType type, const QByteArray& file, uint line, QByteArray function ) : QDebug( type )\n\t{\n\t\tQ_UNUSED( line );\n        Q_UNUSED( file );\n\n\t\tQByteArray out;\n\n\t\t#if __GNUG__\n        int const k = function.indexOf( '(' );\n\t\tint const m = function.mid( 0, k ).lastIndexOf( \"::\" ); // work with ctors and dtors\n\t\tint const n = m == -1 ? 0 : function.lastIndexOf( ' ', m ) + 1;\n\t\tfunction = function.mid( n, k - n );\n\t\t#endif\n\n\t\tout += function + \"()\";\n        \n        *this << out.data();\n\t}\n};\n\n#define qDebug() StampedDebug( QtDebugMsg, __FILE__, __LINE__, __PRETTY_FUNCTION__ )\n#define qWarning() StampedDebug( QtWarningMsg, __FILE__, __LINE__, __PRETTY_FUNCTION__ )\n#define qCritical() StampedDebug( QtCriticalMsg, __FILE__, __LINE__, __PRETTY_FUNCTION__ )\n\n#endif\n"
  },
  {
    "path": "common/qt/override/QHttp",
    "content": "#error Use QNetworkManager instead.\n"
  },
  {
    "path": "common/qt/override/QMessageBox",
    "content": "#error Use lib/unicorn/QMessageBoxBuilder.h instead.\n"
  },
  {
    "path": "common/qt/override/QNetworkAccessManager",
    "content": "#error Use lib/ws/WsNetworkManager instead.\n"
  },
  {
    "path": "common/qt/override/README",
    "content": "Brief\n=====\nForce this directory first in the -I g++ directives to use these overrides.\n\nWith QMake: CXX = $$CXX -IlibMoose/QtOverrides\n\nThere is danger with this system. But it beats the system where developers\ncould accidentally use the Qt version of a class or function and for some\nreason it is absolutely essential our override is used.\n\nNOTE, the cpp files are named without the Q as this seems to break qmake, heh :)\n\nNOTE, new classes should be as minimal as possible, even Qt will use your versions of the classes, but only if they are used in inline functions in headers, so you should be mostly safe. Still be careful. If you change more than a tiny amount of the class do '#error include \"blah.h\" instead' and write a separate class.\n\nNOTE Beware overriding non virtual functions if the base class may use that function.\n\nImplementations\n===============\nQSystemTrayIcon\n---------------\nFor sendMessage() on mac, to show a notification when Growl is not installed.\n"
  },
  {
    "path": "common/qt/reverse.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QList>\n\nnamespace Qt\n{\n    template <class T> static inline QList<T> reverse( QList<T> list )\n    {\n        const int N = list.size();\n        const int n = N/2;\n        for (int x = 0; x < n; ++x)\n            list.swap( x, N-1-x );\n        return list;\n    }\n    \n    //\"specialise\" for QStringList\n    static inline QStringList reverse( QList<QString> strings )\n    {\n        return (QStringList)reverse<QString>( strings );\n    }\n}\n"
  },
  {
    "path": "common/qt/sort.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QMap>\n#include <QStringList>\n\n\nnamespace Qt\n{\n\tQStringList sort( QStringList input, Qt::CaseSensitivity s )\n\t{\n\t\tif (sensitivity = Qt::CaseSensitive)\n\t\t\treturn input.sort();\n\t\t\n\t    // This cumbersome bit of code here is how the Qt docs suggests you sort\n\t    // a string list case-insensitively\n\t    QMap<QString, QString> map;\n\t    foreach (QString s, input)\n\t        map.insert( s.toLower(), s );\n\n\t    QStringList output;\n\t    QMapIterator<QString, QString> i( map );\n\t    while (i.hasNext())\n\t        output += i.next().value();\n\n\t    return output;\n\t}\t\n}\n"
  },
  {
    "path": "i18n/i18n.pro",
    "content": "CONFIG -= app_bundle\n\ninclude( ../admin/include.qmake )\n\nTRANSLATIONS = lastfm_de.ts \\\n               lastfm_en.ts \\\n               lastfm_es.ts \\\n               lastfm_fr.ts \\\n               lastfm_it.ts \\\n               lastfm_ja.ts \\\n               lastfm_pl.ts \\\n               lastfm_pt.ts \\\n               lastfm_ru.ts \\\n               lastfm_sv.ts \\\n               lastfm_tr.ts \\\n               lastfm_zh_CN.ts\n\nisEmpty(vcproj) {\n    QMAKE_LINK = @: IGNORE THIS LINE\n    OBJECTS_DIR =\n    win32:CONFIG -= embed_manifest_exe\n} else {\n    CONFIG += console\n    PHONY_DEPS = .\n    phony_src.input = PHONY_DEPS\n    phony_src.output = phony.c\n    phony_src.variable_out = GENERATED_SOURCES\n    phony_src.commands = echo int main() { return 0; } > phony.c\n    phony_src.name = CREATE phony.c\n    phony_src.CONFIG += combine\n    QMAKE_EXTRA_COMPILERS += phony_src\n}\n\nisEmpty(QMAKE_LRELEASE) {\n    win32|os2:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]\\\\lrelease.exe\n    else:QMAKE_LRELEASE = $$[QT_INSTALL_BINS]/lrelease\n    unix {\n        !exists($$QMAKE_LRELEASE) { QMAKE_LRELEASE = lrelease-qt4 }\n    } else {\n        !exists($$QMAKE_LRELEASE) { QMAKE_LRELEASE = lrelease }\n    }\n}\n\nupdateqm.input = TRANSLATIONS\nupdateqm.output = ${QMAKE_FILE_BASE}.qm\nupdateqm.commands = $$QMAKE_LRELEASE -silent -removeidentical ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_BASE}.qm\nupdateqm.CONFIG += no_link target_predeps\nQMAKE_EXTRA_COMPILERS += updateqm\n\nunix:!mac {\n        i18n.files += *.qm\n        i18n.path = $$DATADIR/lastfm-scrobbler/i18n\n        i18n.CONFIG += no_check_exist\n\n        INSTALLS += i18n\n}\n"
  },
  {
    "path": "i18n/lastfm_de.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"de\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Über Last.fm</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (erstellt mit Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Klicke in deinem Webbrowser auf die Schaltfläche &lt;strong&gt;Ja, Zugang gestatten&lt;/strong&gt;, um dein Last.fm-Konto mit der Last.fm-Desktop-App zu verbinden.&lt;/p&gt;&lt;p&gt;Versuche es bitte noch einmal, wenn keine Verbindung hergestellt werden konnte, weil du das Browserfenster geschlossen oder auf Abbrechen geklickt hast.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Wir warten darauf, dass du dich mit Last.fm verbindest</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Erneut versuchen</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Wenn sich dein Webbrowser nicht geöffnet hat, kopiere den unten stehenden Link bitte in deine Adressleiste.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Tastaturkürzel:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Last.fm ein-/ausblenden</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>SSL aktivieren</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Cachegröße:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Abonnent</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderator</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Mitarbeiter</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Absolventin</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Absolvent</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>Auf Tour</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Um die bestmöglichen Empfehlungen auf Basis deines Musikgeschmacks zu erhalten, empfehlen wir, dass du deinen Hörverlauf aus deinem Mediaplayer importierst.&lt;/p&gt;&lt;p&gt;Wähle deinen bevorzugten Mediaplayer aus und klicke auf &lt;strong&gt;Import starten&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Deine Plugins wurden nicht installiert</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kannst sie später über das Dateimenü installieren</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Lass uns nun deinen Hörverlauf importieren</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Import starten</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Überspringen &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Keine Sorge! Das Hochladen dürfte, je nach Umfang deiner Musiksammlung, höchstens ein paar Minuten dauern.&lt;/p&gt;&lt;p&gt;Sieh dir doch einige der Hauptfunktionen der Last.fm-Desktop-App an, während wir daran arbeiten, deinen Hörverlauf in dein Last.fm-Profil einzutragen. Durch Klick auf &lt;strong&gt;Weiter&lt;/strong&gt; gelangst du zur Tour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Apps schließen</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Geräte-Scrobbeln deaktiviert - inkompatibles iTunes-Plugin - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>bitte aktualisieren</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod scrobbeln</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Möchtest du das Gerät %1 mit deinem Audioscrobbler-Benutzerkonto verknüpfen?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Das Gerät ist nun mit deinem Benutzerkonto verknüpft. Ab jetzt kannst du die auf diesem Gerät gehörten Titel scrobbeln.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 Titel gescrobbelt.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Keine zu scrobbelnden Titel seit deiner letzten Synchronisierung.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Die iPod-Datenbank konnte nicht geöffnet werden.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Beim Versuch, auf die iPod-Datenbank zuzugreifen, ist ein unbekannter Fehler aufgetreten.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Fehlerdiagnose</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbels</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Das ist ein Easter Egg!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Künstler</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Titel</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingerprinting</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Titel, deren &quot;Fingerabdrücke&quot; kürzlich genommen wurden</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod-Scrobbeln</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes verwaltet meinen iPod automatisch</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Ich verwalte meinen iPod manuell</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod scrobbeln</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Protokolle</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Schließen</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n lokal zwischengespeicherter Titel</numerusform>\n            <numerusform>%n lokal zwischengespeicherte Titel</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm-Desktop-App</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Danke, &lt;strong&gt;%1&lt;/strong&gt;! Dein Konto ist jetzt verbunden.</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importvorgang läuft ...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Import wurde abgeschlossen!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Finde deine Freunde auf Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Du hast noch keine Freundschaften auf Last.fm geschlossen.&lt;/h3&gt;&lt;p&gt;Mit dem Freundefinder kannst du schnell und einfach deine Facebook-Freunde und E-Mail-Kontakte auf Last.fm finden.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Freunde nach Benutzer- oder echten Namen suchen</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Freunde aktualisieren</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Aktualisierung läuft ...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Musiksammlungs-Radio von %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Männlich</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Scrobbelt jetzt von %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Weiblich</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Scrobbelt jetzt</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neutral</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Suche deine Freunde</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Freunde suchen</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Sprache:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Anwendungsicon in der Menüleiste anzeigen</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Anwendung mit Mediaplayern starten</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Dock-Symbol anzeigen</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Desktop-Benachrichtungen anzeigen</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Absturzberichte an Last.fm schicken</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Automatisch nach Updates suchen</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Medientasten aktivieren</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Systemsprache</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Jetzt neu starten?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Damit die Änderungen übernommen werden können, muss die Anwendung neu gestartet werden. Willst du sie jetzt neu starten?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Update zu Beta-Versionen – Warnung: nur für Mutige!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Die iPod-Datenbank konnte nicht geöffnet werden.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Die Nutzung einer Scrobbel-App mit iOS, z.B. %1, kann zu doppelten Scrobbels führen. Bitte aktiviere Scrobbeln nur in einer App.&lt;/p&gt;&lt;p&gt;iTunes Match synchronisiert Wiedergabezähler für mehrere Geräte, aber nicht die Zeiten der letzten Wiedergabe. Dies führt zu doppelten Scrobbels mit falschen Zeiten. Wir empfehlen Benutzern von iTunes Match vorläufig, das Geräte-Scrobbeln auf Desktop-Geräten zu deaktivieren und iPhones/iPods mithilfe einer iOS-Scrobbel-App zu scrobbeln, z.B. %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Einstellung nicht geändert</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Du hast iTunes nicht geschlossen, um diese Einstellung zu ändern</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Geräte-Scrobbeln aktivieren</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Geräte-Scrobbeln bestätigen</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Hinweis</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Lizenzen</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Sind wir fertig?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Klicke auf OK, sobald du diese App genehmigt hast.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm benötigt zuerst deine Erlaubnis!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Diese Anwendung benötigt deine Erlaubnis, um sich mit deinem Last.fm-Profil zu verbinden. Klicke auf OK, um zur Last.fm-Website zu gehen und dies zu tun.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Du bist bereits Last.fm-Nutzer? Verbinde dein Konto mit der Last.fm-Desktop-App und sie aktualisiert dein Profil mit der von dir gehörten Musik.&lt;/p&gt;&lt;p&gt;Wenn du kein Konto hast, kannst du dich jetzt kostenlos registrieren.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Fangen wir an, indem wir dein Last.fm-Konto verbinden</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Verbinde dein Konto</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Registrieren</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Für deine Mediaplayer-Plugins stehen Updates bereit. Willst du diese jetzt installieren?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Fehler bei der Installation des Plugins</numerusform>\n            <numerusform>Fehler bei der Installation des Plugins</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Beim Aktualisieren Ihres Plugins ist ein Fehler aufgetreten.&lt;/p&gt;&lt;p&gt;Bitte versuchen Sie es später erneut.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Beim Aktualisieren Ihrer Plugins ist ein Fehler aufgetreten.&lt;/p&gt;&lt;p&gt;Bitte versuchen Sie es später erneut.&lt;/p&gt;\n</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plugin installiert!</numerusform>\n            <numerusform>Plugins installiert!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Dein Plugin wurden installiert.&lt;/p&gt;&lt;p&gt;Du kannst jetzt mit deinem Mediaplayer scrobbeln&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Deine Plugins wurden installiert.&lt;/p&gt;&lt;p&gt;Du kannst jetzt mit deinen Mediaplayern scrobbeln&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Deine Plugins wurden nicht installiert</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kannst sie später über das Dateimenü installieren</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Datei</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Plugins installieren</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Beenden</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Ansehen</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Mein Last.fm-Profil</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbels</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Aktualisieren</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Steuerung</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Benutzerkonto</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Tools</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Nach Updates suchen</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Optionen</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Fenster</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimieren</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Alle in den Vordergrund</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Hilfe</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Über</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Foren</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tour</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Lizenzen anzeigen</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnose</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n Wiedergabe&lt;/a&gt; wurde von einem Gerät gescrobbelt</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n Wiedergaben&lt;/a&gt; wurden von einem Gerät gescrobbelt</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Zurück zu Scrobbels</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Beliebte Tags:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Deine Tags:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Ähnliche Künstler</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>von %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>von %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1-Radio abspielen</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Wiedergabe</numerusform>\n            <numerusform>Wiedergaben</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Wiedergabe in deiner Musiksammlung</numerusform>\n            <numerusform>Wiedergaben in deiner Musiksammlung</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Hörer</numerusform>\n            <numerusform>Hörer</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Mit %1 und mehr.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Mit %1, %2 und mehr.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Bearbeitet am %1 | %2 Bearbeiten</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Suche auf %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Auf %1 %2 kaufen</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physikalisch</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Empfohlen, weil du %1 hörst.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Empfohlen, weil du %1 und %2 hörst.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Empfohlen, weil du %1, %2 und %3 hörst.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Empfohlen, weil du %1, %2, %3 und %4 hörst.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Empfohlen, weil du %1, %2, %3, %4 und %5 hörst.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Aus der Musiksammlung von %1</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Aus den Musiksammlungen von %1 und %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 Mal</numerusform>\n            <numerusform>%L1 Mal</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Aus den Musiksammlungen von %1, %2 und %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Du hast %1 %2 und %3 %4 gehört.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Aus den Musiksammlungen von %1, %2, %3 und %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Du hast %1 %2 gehört, aber nicht diesen Titel.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Aus den Musiksammlungen von %1, %2, %3, %4 und %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Du hast zum ersten Mal %1 gehört.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Hallo!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Eine Radiostation starten</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>iTunes öffnen</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Music öffnen</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Windows Media Player öffnen</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Winamp öffnen</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Foobar öffnen</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Von deinem Musikplayer scrobbeln&lt;/h2&gt;&lt;p&gt;Höre Musik auf deinem Mediaplayer. Im Register „Gerade läuft“ findest du weitere Informationen zu den gespielten Titeln.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Hallo %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Eine Radiostation</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>%1 wiedergeben</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Multi-Musiksammlungs-Radio</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>%1 in die Warteschleife aufnehmen</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Musiksammlungs-Radio %1 und %2 abspielen</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Musiksammlungs-Radio %1 und %2 in die Warteschleife aufnehmen</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Lieben</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Bannen</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Wiedergeben</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Überspringen</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pause</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Fortsetzen</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Als Lieblingslied entfernen</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Tuning</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Eine Radiostation</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Gerade läuft</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbelt von</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 Wiedergabe</numerusform>\n            <numerusform>%L1 Wiedergaben</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm hat deinen Mediaplayer-Hörverlauf importiert.\n\n Klicke OK, um fortzufahren.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Import des Mediaplayer-Hörverlaufs</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Bist du sicher, dass du den Import abbrechen möchtest?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm konnte keine Plays in deiner Mediensammlung finden.\n\n Klicke OK, um fortzufahren.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm importiert gerade deine aktuelle Mediensammlung ...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Wo ist Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Wo ist Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Import der Mediensammlung abgeschlossen</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm hat deinen Hörverlauf an den Server übermittelt.\nDein Profil wird in ein paar Minuten mit den neuen Titeln aktualisiert.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Import der Mediensammlung fehlgeschlagen</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Entschuldigung, Last.fm konnte deinen Hörverlauf leider nicht importieren. Du hast wahrscheinlich schon zu viele Titel gescrobbelt. Hörverläufe können nur zu ganz neuen Profilen hinzugefügt werden.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Befolge bitte die von deinem Betriebssystem angezeigten Anweisungen zur Installation der Plugins.&lt;/p&gt;&lt;p&gt;Klicke auf &lt;strong&gt;Weiter&lt;/strong&gt;, sobald die Plugins auf deinem Computer installiert worden sind.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Deine Plugins werden jetzt installiert</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Deine Plugins wurden nicht installiert</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kannst sie später über das Dateimenü installieren</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Dein Mediaplayer benötigt ein spezielles Last.fm-Plugin, um die von dir gehörte Musik scrobbeln zu können.&lt;/p&gt;&lt;p&gt;Wähle bitte die Mediaplayer, von denen du deine Musik scrobbeln möchtest, und klicke auf &lt;strong&gt;Plugins installieren.&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(neuere Version)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plugin installiert. Zum Deinstallieren markieren.)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Installiere als nächstes die Last.fm-Plugins, damit du deine gehörte Musik scrobbeln kannst.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Plugins installieren</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Überspringen &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Allgemein</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Konten</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbels</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Geräte</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Erweitert</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>1%-Radio</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 Wiedergabe</numerusform>\n            <numerusform>%L1 Wiedergaben</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Top-Künstler diese Woche</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Top-Künstler insgesamt</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobbel</numerusform>\n            <numerusform>Scrobbels</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Lieblingslied</numerusform>\n            <numerusform>Lieblingslieder</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 Künstler</numerusform>\n            <numerusform>%L1 Künstler</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 Titel</numerusform>\n            <numerusform>%L1 Titel</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Du hast %1 in deiner Musiksammlung und hörst durchschnittlich %2 pro Tag.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobbel seit %1</numerusform>\n            <numerusform>Scrobbels seit %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Proxy-Einstellungen</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Benutzername:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Passwort:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>unbekannter Mediaplayer</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Wo ist dein iPod angeschlossen?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Künstler/Tag eingeben und abspielen</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Wiedergabe</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Probiere es doch einmal mit %1, %2, %3 oder %4.</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Danach wiedergeben</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Eine Radiostation</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Du brauchst ein Abonnement, um Radio hören zu können</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Letzte Station</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Eine Radiostation</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Persönliche Stationen</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Mein Musiksammlungs-Radio</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Musik, die du kennst und liebst</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Mein Mix-Radio</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Deine Musiksammlung plus neue Musik</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Mein Empfehlungs-Radio</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Abo abschließen und Radio hören</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Neue Musik von Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Du brauchst ein Abonnement bei Last.fm, um in dieser App Radio hören zu können. Schließe ein Abo ab und komm in den Genuss von toller Musik und anderer toller Vorteile!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Netzwerkstationen</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Last.fm abonnieren</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Kostenlos hören auf www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Radio meiner Freunde</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Musik, die deinen Freunden gefällt</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Mein Nachbar-Radio</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Musik von Hörern wie dir</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Letzte Stationen</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Gerade läuft</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Werde Abonnent, um Radio hören zu können - für nur %1 im Monat</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Geräte-Scrobbeln</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Sieht so aus, als hättest du diese Titel abgespielt. Möchtest du sie scrobbeln?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Geräte automatisch scrobbeln</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Auswahl umkehren</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n Wiedergabe wurde von einem Gerät gescrobbelt</numerusform>\n            <numerusform>%n Wiedergaben wurden von einem Gerät gescrobbelt</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Zu Lieblingsliedern hinzufügen</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Tags hinzufügen</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Lieben</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Taggen</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Empfehlen</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Auf Last.fm empfehlen</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Auf Twitter empfehlen</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Auf Facebok empfehlen</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Kaufen</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Aus Lieblingsliedern entfernen</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobbeln bei</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>Prozent des Titels</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Scrobbeln aktivieren</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...oder bei 4 Minuten (je nachdem, was zuerst eintritt)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Podcasts scrobbeln</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Fingerprinting meiner Titel durch Last.fm zulassen</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Ausgewählte Verzeichnisse werden nicht gescrobbelt</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Mehr Scrobbels auf Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Aktualisierung läuft ...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Scrobbels aktualisieren</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Künstler</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Titel</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Wiedergaben</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Zuletzt wiedergegeben</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Lieblingslied</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Dieser Titel ist weniger als 30 Sekunden lang</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Der Künstlername fehlt</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Ungültiger Titelname</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Ungültiger Künstler</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Es gibt keine Zeitmarkierung</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Dieser Titel liegt zu weit in der Zukunft</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Dieser Titel wurde vor über zwei Wochen wiedergegeben</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Du hast noch keine Musik zu Last.fm gescrobbelt.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Höre Musik in deinem Mediaplayer oder starte eine Radiostation:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Freunden empfehlen</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>An:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Nachricht (optional):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>in meine letzten Aktivitäten aufnehmen</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Ein Titel von %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Ein Titel von %1 aus der Veröffentlichung %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Schau dir mal %1 an</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Gerade läuft</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbels</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Freunde</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Nächster Abschnitt</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Vorheriger Abschnitt</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Konnte Radio nicht starten: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>keine Ergebnisse für &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobbeln ist deaktiviert</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Online</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Offline</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Wähle etwas zum Taggen aus:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Titel</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Künstler</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>Symbol</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Tags hinzufügen:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Ein Titel von %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Ein Titel von %1 aus der Veröffentlichung %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Gib oben ein Tag ein\noder wähle unten eines aus</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Nach Beliebtheit sortieren</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Alphabetisch sortieren</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Last.fm-Seite für dieses Tag öffnen</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Jetzt kannst du loslegen! Klicke einfach auf &lt;strong&gt;Fertigstellen&lt;/strong&gt; und fange an, die App zu erkunden.&lt;/p&gt;&lt;p&gt;Wir haben auch deinen Hörverlauf importiert und in dein Last.fm-Profil eingetragen.&lt;/p&gt;&lt;p&gt;Vielen Dank, dass du die Last.fm-Desktop-App installiert hast! Wir wünschen dir viel Spaß damit.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Das wars, du kannst loslegen!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Fertigstellen</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Der rote Pfeil auf deinem Bildschirm zeigt dir die Position der Last.fm-Desktop-App in deiner Taskleiste.&lt;/p&gt;&lt;p&gt;Klicke auf das Symbol, um Zugriff auf Radiosteuerungen zu erhalten, Titel zu empfehlen und zu taggen, deine Einstellungen zu bearbieten und dein Last.fm-Profil zu besuchen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Die Last.fm-Desktop-App in deiner Menüleiste</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Die Last.fm-Desktop-App in deiner Taskleiste</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Erfahre mehr über die Musik, die du hörst. Dazu gehören Biographien, Hörstatistiken, Fotos und ähnliche Künstler sowie die Tags, die andere Hörer zum Beschreiben vergeben haben.&lt;/p&gt;&lt;p&gt;Sieh dir unser Register &lt;strong&gt;Gerade läuft&lt;/strong&gt; an oder klicke einfach auf einen Titel in deinem Register &lt;strong&gt;Scrobbels&lt;/strong&gt;, um mehr zu erfahren.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Erfahre mehr über deine Lieblingskünstler</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Tour überspringen &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Höre ununterbrochenes, personalisiertes Radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Mit der Last.fm-Desktop-App kannst du personalisiertes Radio auf Basis deiner Lieblingsmusik hören.&lt;/p&gt;&lt;p&gt;Jede Wiedergabe in jeder Last.fm-Station ist komplett unterschiedlich – von Stationen, die auf Künstlern oder Tags basieren bis hin zu topaktuellen Empfehlungen anhand deines Musikgeschmacks.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Werde Abonnent und höre ununterbrochenes, personalisiertes Radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Werde Last.fm-Abonnent und nutze die Last.fm-Desktop-App, um personalisiertes Radio auf Basis deiner Lieblingsmusik zu hören.&lt;/p&gt;&lt;p&gt;Jede Wiedergabe in jeder Last.fm-Station ist komplett unterschiedlich – von Stationen, die auf Künstlern oder Tags basieren bis hin zu topaktuellen Empfehlungen anhand deines Musikgeschmacks.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abonnieren</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Tour überspringen &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Der Desktop-Client läuft im Hintergrund und aktualisiert dein Last.fm-Profil mit der Musik, die du abspielst. Dadurch kannst du Musikempfehlungen, Konzerttipps und mehr bekommen. &lt;/p&gt;&lt;p&gt;Du kannst die Last.fm-Desktop-App auch verwenden, um mehr über die Künstler zu erfahren, die du gerade hörst, und um personalisiertes Radio abzuspielen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Herzlich willkommen bei der Last.fm-Desktop-App!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Weiter</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Zurück</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Tour überspringen &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Titel</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Künstler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Lieben</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Empfehlen</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Kaufen</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Diesen Scrobbel aus deinem Profil entfernen</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1-Radio abspielen</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>%1-Radio in die Warteschleife aufnehmen</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>1%-Radio</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Zwischengespeichert</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Fehler: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Auf Last.fm empfehlen</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Auf Twitter empfehlen</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Auf Facebok empfehlen</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Aktuelle Hörer</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Suche auf %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Auf %1 %2 kaufen</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physikalisch</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Verbundene Benutzerkonten:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Neues Benutzerkonto hinzufügen</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Fehler beim Hinzufügen des Benutzers</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Dieser Benutzer wurde bereits hinzugefügt.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>%1 wird entfernt</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Willst du diesen Benutzer wirklich entfernen? Dadurch gehen alle Benutzereinstellungen verloren und du musst eine erneute Authentifizierung durchführen, um künftig wieder scrobbeln zu können.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abonnieren</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Entfernen</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(zurzeit angemeldet)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Konten</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Scrobbler anzeigen</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Lieben</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Abspielen</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Überspringen</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Empfehlen</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Bannen</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Stumm</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>iPod scrobbeln...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Last.fm-Profil besuchen</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Scrobbeln aktivieren</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>%1 wird beendet</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>von %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Du hast die maximale Anzahl an Titeln, die du überspringen kannst, für diese Station erreicht. In %n Minute kannst du wieder überspringen.</numerusform>\n            <numerusform>Du hast die maximale Anzahl an Titeln, die du überspringen kannst, für diese Station erreicht. In %n Minuten kannst du wieder überspringen.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Du kannst in dieser Station noch %n Mal überspringen.</numerusform>\n            <numerusform>Du kannst in dieser Station noch %n Mal überspringen.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Authentifizierung erforderlich</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Das Benutzerkonto &lt;strong&gt;%1&lt;/strong&gt; ist nicht mehr bei Last.fm authentifiziert.&lt;/p&gt;&lt;p&gt;Klicke auf OK, um das Setup zu starten und dieses Konto erneut zu authentifizieren.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Willst du %1 wirklich beenden?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 wird gleich beendet. Wenn du fortfährst, werden wiedergegebene Titel nicht gescrobbelt.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Benutzer wird gewechselt</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 wird beim Scrobbler und bei Last.fm-Radio eingeloggt. Sämtliche Musik wird jetzt zu diesem Konto gescrobbelt. Willst du fortfahren?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Schließe bitte folgende Apps, um fortzufahren.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Fehler bei der Installation des Plugins</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Beim Update deines Plugins ist ein Fehler aufgetreten.&lt;/p&gt;&lt;p&gt;Versuche es bitte später noch einmal.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plugin installiert!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Das %1-Plugin wurde installiert.&lt;/p&gt;&lt;p&gt;Du kannst jetzt mit %1 scrobbeln.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Das %1-Plugin wurde nicht installiert</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Du hast %1 nicht geschlossen, deshalb wurde das zugehörige Plugin nicht installiert.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Schließe iTunes für ein Plugin-Update!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Dein iTunes-Plugin (%2) unterscheidet sich von demjenigen, das mit dieser Version der App (%1) ausgeliefert wurde.&lt;/p&gt;&lt;p&gt;Schließe iTunes bitte jetzt für das Update.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>nicht installiert</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Dein Plugin wurde nicht installiert</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Beim Entfernen des alten Plugins ist ein Fehler aufgetreten</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes-Plugin installiert!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Dein iTunes-Plugin wurde installiert.&lt;/p&gt;&lt;p&gt;Du kannst jetzt mit dem Geräte-Scrobbeln beginnen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Beim Kopieren des neuen Plugins ist ein Fehler aufgetreten</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Du hast iTunes nicht geschlossen</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Mit der Zeit stimmt etwas nicht</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>vor %n Minute</numerusform>\n            <numerusform>vor %n Minuten</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>vor %n Stunde</numerusform>\n            <numerusform>vor %n Stunden</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Es gab einen Netzwerkfehler: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Du hast diese Anwendung nicht autorisiert</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Authentifizierungsfehler</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Stylesheet aktualisieren</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Nicht mehr danach fragen</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Autom. Erkennung</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Kein Proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_en.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"en\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>About</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (built on Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>We&apos;re waiting for you to connect to Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Try Again</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Keyboard Shortcuts:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Raise/Hide Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Enable SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Cache Size:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Subscriber</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderator</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Staff</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Alumna</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Alumnus</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>On Tour</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Your plugins haven&apos;t been installed</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>You can install them later through the file menu</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Now let&apos;s import your listening history</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Start Import</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Skip &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Close Apps</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Device scrobbling disabled - incompatible iTunes plugin - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>please update</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobble iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Do you want to associate the device %1 to your audioscrobbler user account?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 tracks scrobbled.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>No tracks to scrobble since your last sync.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>The iPod database could not be opened.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>An unknown error occurred while trying to access the iPod database.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostics</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>This is an easter egg!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Track</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingerprinting</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Recently Fingerprinted Tracks</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod Scrobbling</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes automatically manages my iPod</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>I manually manage my iPod</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobble iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Logs</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Close</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n locally cached track</numerusform>\n            <numerusform>%n locally cached tracks</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm Desktop App</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importing...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Import complete!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Find your friends on Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Search for a friend by username or real name</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Refresh Friends</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Refreshing...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>%1&apos;s Library Radio</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Male</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Scrobbling now from %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Female</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Scrobbling now</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neuter</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Search your friends</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Browse Friends</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Language:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Show application icon in menu bar</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Launch application with media players</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Show dock icon</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Show desktop notifications</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Send crash reports to Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Check for updates automatically</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Enable media keys</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>System Language</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Restart now?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>An application restart is required for the change to take effect. Would you like to restart now?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Update to beta versions - Warning: only for the brave!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>The iPod database could not be opened.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Setting not changed</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>You did not close iTunes for this setting to change</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Enable Device Scrobbling</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Confirm Device Scrobbles</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Please note</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licenses</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Are we done?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Click OK once you have approved this app.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm needs your permission first!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Let&apos;s get started by connecting your Last.fm account</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Connect Your Account</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Sign up</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>There are updates to your media player plugins. Would you like to install them now?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation type=\"unfinished\">\n            <numerusform>Plugin install error</numerusform>\n            <numerusform>Plugin install error</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation type=\"unfinished\">\n            <numerusform>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;There was an error updating your plugins.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plugin installed!</numerusform>\n            <numerusform>Plugins installed!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Your plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Your plugins have been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media players&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Your plugins haven&apos;t been installed</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>You can install them later through the file menu</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>File</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Install plugins</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Quit</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>View</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>My Last.fm Profile</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Refresh</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Controls</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Account</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Tools</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Check for Updates</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Options</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Window</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimize</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Bring All to Front</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Help</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>About</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Forums</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tour</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Show Licenses</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostics</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n play&lt;/a&gt; has been scrobbled from a device</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n plays&lt;/a&gt; have been scrobbled from a device</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Back to Scrobbles</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Popular tags:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Your tags:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Similar Artists</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>by %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>from %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Play %1 Radio</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Play</numerusform>\n            <numerusform>Plays</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Play in your library</numerusform>\n            <numerusform>Plays in your library</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Listener</numerusform>\n            <numerusform>Listeners</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>With %1 and more.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>With %1, %2 and more.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Edited on %1 | %2 Edit</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Search on %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Buy on %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physical</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Recommended because you listen to %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Recommended because you listen to %1 and %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Recommended because you listen to %1, %2, and %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Recommended because you listen to %1, %2, %3, and %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Recommended because you listen to %1, %2, %3, %4, and %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>From %1&apos;s library.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>From %1 and %2&apos;s libraries.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 time</numerusform>\n            <numerusform>%L1 times</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>From %1, %2, and %3&apos;s libraries.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>You&apos;ve listened to %1 %2 and %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>From %1, %2, %3, and %4&apos;s libraries.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>You&apos;ve listened to %1 %2, but not this track.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>From %1, %2, %3, %4, and %5&apos;s libraries.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>This is the first time you&apos;ve listened to %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Hello!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Start a radio station</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Open iTunes</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Open Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Open Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Open Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Hello, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>A Radio Station</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Play %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Multi-Library Radio</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Cue %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Play %1 and %2 Library Radio</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Cue %1 and %2 Library Radio</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Ban</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Play</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Skip</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pause</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Resume</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Unlove</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Tuning</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>A Radio Station</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Listening to</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbling from</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 play</numerusform>\n            <numerusform>%L1 plays</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm has imported your media library.\n\n Click OK to continue.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Last.fm Library Import</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Are you sure you want to cancel the import?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm is importing your current media library...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Where is Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Where is Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Media Library Import Complete</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Library Import Failed</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Your plugins are now being installed</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Your plugins haven&apos;t been installed</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>You can install them later through the file menu</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(newer version)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plugin installed tick to reinstall)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Install Plugins</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Skip &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>General</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Accounts</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Devices</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Advanced</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 Radio</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 play</numerusform>\n            <numerusform>%L1 plays</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Top Artists This Week</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Top Artists Overall</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobble</numerusform>\n            <numerusform>Scrobbles</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Loved track</numerusform>\n            <numerusform>Loved tracks</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artist</numerusform>\n            <numerusform>%L1 artists</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 track</numerusform>\n            <numerusform>%L1 tracks</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>You have %1 in your library and on average listen to %2 per day.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobble since %1</numerusform>\n            <numerusform>Scrobbles since %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Proxy Settings</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Username:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Password:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>unknown media player</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Where is your iPod mounted?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Type an artist or tag and press play</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Play</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Why not try %1, %2, %3 or %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Play next</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>A Radio Station</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>You need to be a subscriber to listen to radio</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Last Station</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>A Radio Station</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Personal Stations</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>My Library Radio</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Music you know and love</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>My Mix Radio</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Your library plus new music</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>My Recommended Radio</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Subscribe to listen to radio</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>New music from Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Network Stations</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Subscribe to Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Listen free on www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>My Friends&apos; Radio</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Music your friends like</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>My Neighbourhood Radio</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Music from listeners like you</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Recent Stations</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Now Playing</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Subscribe to listen to radio, only %1 a month</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Device Scrobbles</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Scrobble devices automatically</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Toggle selection</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n play has been scrobbled from a device</numerusform>\n            <numerusform>%n plays have been scrobbled from a device</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Love track</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Add tags</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Share</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Share on Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Share on Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Share on Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Buy</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Unlove track</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobble at</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>percent of the track</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Enable scrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...or at 4 minutes (whichever comes first)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Scrobble podcasts</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Allow Last.fm to fingerprint my tracks</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Selected directories will not be scrobbled</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>More Scrobbles at Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Refreshing...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Refresh Scrobbles</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Title</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Plays</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Last Played</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Loved</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>This track is under 30 seconds</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>The artist name is missing</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Invalid track title</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Invalid artist</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>There is no timestamp</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>This track is too far in the future</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>This track was played over two weeks ago</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>You haven&apos;t scrobbled any music to Last.fm yet.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Start listening to some music in your media player or start a radio station:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Share with Friends</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>With:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Message (optional):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>include in my recent activity</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>A track by %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>A track by %1 from the release %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Check out %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Now Playing</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profile</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Friends</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Next Section</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Previous Section</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Could not start radio: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>no results for &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobbling is off</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Online</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Offline</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Choose something to tag:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Track</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>icon</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Add tags:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>A track by %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>A track by %1 from the release %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Type a tag above,\nor choose from below</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Sort by Popularity</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Sort Alphabetically</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Open Last.fm Page for this Tag</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>That&apos;s it, you&apos;re good to go!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Finish</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>The Last.fm Desktop App in your menu bar</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>The Last.fm Desktop App in your system tray</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Discover more about the artists you love</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Skip Tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Listen to non-stop, personalised radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Subscribe and listen to non-stop, personalised radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Subscribe</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Skip Tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Welcome to the Last.fm Desktop App!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continue</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Back</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Skip Tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Track</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Share</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Buy</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Delete this scrobble from your profile</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Play %1 Radio</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Cue %1 Radio</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 Radio</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Cached</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Error: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Share on Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Share on Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Share on Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Now listening</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Search on %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Buy on %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physical</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Connected User Accounts:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Add New User Account</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Add User Error</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>This user has already been added.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Removing %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Subscribe</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Remove</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(currently logged in)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Accounts</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Show Scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Play</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Skip</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Share</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Ban</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Mute</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Scrobble iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Visit Last.fm profile</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Enable Scrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Quit %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>from %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute.</numerusform>\n            <numerusform>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minutes.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>You have %n skip remaining on this station.</numerusform>\n            <numerusform>You have %n skips remaining on this station.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Authentication Required</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Are you sure you want to quit %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 is about to quit. Tracks played will not be scrobbled if you continue.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Changing User</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Please close the following apps to continue.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Plugin install error</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plugin installed!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>The %1 plugin hasn&apos;t been installed</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Close iTunes for plugin update!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>not installed</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Your plugin hasn&apos;t been installed</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>There was an error while removing the old plugin</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes Plugin installed!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>There was an error while copying the new plugin into place</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>You didn&apos;t close iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Time is broken</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n minute ago</numerusform>\n            <numerusform>%n minutes ago</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n hour ago</numerusform>\n            <numerusform>%n hours ago</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>There was a network error: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>You have not authorised this application</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Authentication Error</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Refresh Stylesheet</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Don&apos;t ask this again</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Auto-detect</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>No-proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_es.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"es\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Acerca de</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (desarrollado en Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Haz clic en el botón &lt;strong&gt;Sí, permitir el acceso&lt;/strong&gt; de tu explorador web para conectar tu cuenta de Last.fm con Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;Si no la has conectado porque cerraste la ventana del explorador o hiciste clic en Cancelar, inténtalo de nuevo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Solo tienes que conectarte a Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Intentar de nuevo</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Si tu explorador web no se ha abierto, copia y pega el vínculo en la barra de direcciones.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Atajos de teclado</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Mostrar/Ocultar Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Activar SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Tamaño de caché:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Suscriptor</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderador</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Personal Last.fm</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Veterana</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Veterano</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>De gira</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Para obtener las mejores recomendaciones posibles de acuerdo con la música que te gusta, te sugerimos que importes el historial de reproducción del reproductor de medios.&lt;/p&gt;&lt;p&gt;Selecciona tu reproductor de medios de preferencia y haz clic en &lt;strong&gt;Iniciar la importación&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>No se instalaron tus plugins</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puedes instalarlos después a través del menú Archivo</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Ahora importaremos tu historial de reproducción</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Iniciar la importación</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Omitir &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;No te preocupes, el proceso de carga tardará solo un par de minutos, en función del tamaño de tu colección de música.&lt;/p&gt;&lt;p&gt;Mientras trabajamos duro para agregar el historial de reproducción a tu perfil de Last.fm, ¿por qué no echas un vistazo a las características de Last.fm Desktop App? Haz clic en &lt;strong&gt;Continuar&lt;/strong&gt; para realizar el tour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Cerrar aplicaciones</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Scrobbling de dispositivo desactivado - Plugin no compatible - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>Actualizar</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbling del iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>¿Quieres asociar el dispositivo %1 a tu cuenta de usuario de Audioscrobbler?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>El dispositivo se asoció correctamente a tu cuenta de usuario. A partir de ahora, puedes hacer el scrobbling de los temas que escuches en este dispositivo.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 scrobblings de temas.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>No hay temas para el scrobbling desde la última sincronización.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>No se pudo abrir la base de datos del iPod.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Se produjo un error desconocido al acceder a la base de datos del iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnóstico</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>¡Esta es una pequeña sorpresa!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Tema</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Asignar código (Fingerprinting)</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Temas recientes con código</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Scrobbling del iPod</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes administra mi iPod automáticamente</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Administro mi iPod manualmente</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbling del iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Registros</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Cerrar</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n tema en caché local</numerusform>\n            <numerusform>%n temas en caché local</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm Desktop App</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>¡Gracias, &lt;strong&gt;%1&lt;/strong&gt;! Tu cuenta ya está conectada.</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importando...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Importación finalizada.</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Busca a tus amigos en Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Por ahora no tienes amigos en Last.fm.&lt;/h3&gt;&lt;p&gt;Usa el Buscador de amigos para buscar a tus contactos de correo electrónico o a tus amigos de Facebook en Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Busca a un amigo por su nombre de usuario o nombre real</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Actualizar amigos</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Actualizando...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Radio de la colección de %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Hombre</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Scrobbling en curso desde %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Mujer</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Scrobbling en curso</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neutral</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Busca a tus amigos</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Explorar amigos</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Idioma:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Mostrar el icono de la aplicación en la barra de menús</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Ejecutar la aplicación con los reproductores de medios</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Mostrar icono del dock</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Mostrar las notificaciones</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Enviar los informes de errores a Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Comprobar automáticamente las actualizaciones</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Activar claves de medios</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Idioma del sistema</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>¿Reiniciar ahora?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Para que los cambios surtan efecto, es necesario reiniciar la aplicación. ¿Quieres reiniciar ahora?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Actualizar a versiones beta - Advertencia: ¡solo para valientes!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>No se pudo abrir la base de datos del iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;El uso de una aplicación de scrobbling de iOS, como %1, puede generar la duplicación de los scrobblings. Activa el scrobbling solo en una aplicación.&lt;/p&gt;&lt;p&gt;iTunes Match puede sincronizar el recuento de las reproducciones en varios dispositivos, pero no la hora de las últimas reproducciones. Esto causará que se dupliquen los scrobblings, con horas incorrectas. Por ahora, recomendamos a los usuarios de iTunes Match que desactiven el scrobbling en los dispositivos de escritorio y hagan scrobbling desde iPhones/iPods con una aplicación de scrobbling de iOS, como %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Configuración sin cambios</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>No cerraste iTunes para cambiar la configuración.</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Activar el scrobbling del dispositivo</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Confirmar el scrobbling del dispositivo</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Recuerda:</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licencias</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>¿Listo?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Cuando hayas aprobado esta aplicación, haz clic en Aceptar.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Primero, Last.fm necesita tu permiso.</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Esta aplicación necesita tu permiso para conectar con tu perfil de Last.fm.  Haz clic en Aceptar para ir al sitio web de Last.fm y otorgar el permiso.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;¿Ya eres usuario de Last.fm? Conecta tu cuenta con Last.fm Desktop App y tu perfil se actualizará con la música que escuches.&lt;/p&gt;&lt;p&gt;Si todavía no tienes una cuenta, puedes registrarte gratuitamente ahora mismo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Para empezar, conectaremos con tu cuenta de Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Conectar con tu cuenta</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Registrarse</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>¿Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Hay actualizaciones de los plugins de tus reproductores de medios. ¿Quieres instalarlas ahora?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Error en la instalación del plugin</numerusform>\n            <numerusform>Error en la instalación de los plugins</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Se produjo un error al actualizar el plugin.&lt;/p&gt;&lt;p&gt;Inténtalo de nuevo más tarde.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Se produjo un error al actualizar los plugins.&lt;/p&gt;&lt;p&gt;Inténtalo de nuevo más tarde.&lt;/p&gt; </numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plugin instalado.</numerusform>\n            <numerusform>Plugins instalados.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Se instaló el plugin.&lt;/p&gt;&lt;p&gt;Ahora estás listo para hacer scrobbling con tu reproductor de medios&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Se instalaron los plugins.&lt;/p&gt;&lt;p&gt;Ahora estás listo para hacer scrobbling con tus reproductores de medios&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>No se instalaron tus plugins</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puedes instalarlos después a través del menú Archivo</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Archivo</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Instalar plugins</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Salir</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Ver</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Mi perfil de Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobblings</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Actualizar</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Controles</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Cuenta</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Herramientas</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Comprobar actualizaciones</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Opciones</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Ventana</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimizar</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Traer todo al frente</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Ayuda</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Acerca de</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>P+F</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Foros</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tour</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Mostrar licencias</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnóstico</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n scrobbling&lt;/a&gt; desde un dispositivo</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n scrobblings&lt;/a&gt; desde un dispositivo</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Volver a Scrobblings</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Tags populares:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Tus tags:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Artistas similares</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Escuchar la radio de %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>scrobbling</numerusform>\n            <numerusform>scrobblings</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>scrobbling en tu colección</numerusform>\n            <numerusform>scrobblings en tu colección</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>oyente</numerusform>\n            <numerusform>oyentes</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Con %1 y otros más.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Con %1, %2 y otros más.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Editado el %1 | %2 Editar</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Descargas</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Buscar en %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Comprar en %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Recomendado porque escuchaste a %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Recomendado porque escuchaste a %1 y %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Recomendado porque escuchaste a %1, %2 y %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Recomendado porque escuchaste a %1, %2, %3 y %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Recomendado porque escuchaste a %1, %2, %3, %4 y %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>De la colección de %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>De las colecciones de %1 y %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 vez</numerusform>\n            <numerusform>%L1 veces</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>De las colecciones de %1, %2 y %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Has escuchado a %1 %2 y %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>De las colecciones de %1, %2, %3 y %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Has escuchado a %1 %2, pero no este tema.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>De las colecciones de %1, %2, %3, %4 y %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Es la primera vez que escuchas a %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>¡Hola!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Escuchar una emisora</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Abrir Music</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Abrir iTunes</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Abrir Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Abrir Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Abrir Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Haz scrobbling desde tu reproductor de música&lt;/h2&gt;&lt;p&gt;Solo tienes que escuchar algo de música en tu reproductor de medios. Encontrarás más información sobre los temas que escuchas en la pestaña Escuchando.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>¡Hola, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una emisora</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Escuchar %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Radio multicolección</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Seguir con %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Escuchar la radio de la colección de %1 y %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Seguir con la radio de las colecciones de %1 y %2</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Favorito</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Vetar</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Escuchar</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Saltar</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pausa</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Reanudar</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Quitar de favoritos</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Sintonizando</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una emisora</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Escuchando</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbling desde</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 scrobbling</numerusform>\n            <numerusform>%L1 scrobblings</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm ha importado tu biblioteca de medios.\n\n Haz clic en Aceptar para continuar.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Importación de la colección de Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>¿Realmente quieres cancelar la importación?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm no encontró temas escuchados en tu biblioteca de medios.\n\n Haz clic en Aceptar para continuar.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm está importando tu biblioteca de medios...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>¿Dónde está Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>¿Dónde está Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Importación de la biblioteca de medios finalizada</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm ha enviado tu historial de reproducción al servidor.\nTu perfil se actualizará con los nuevos temas en unos minutos.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Error en la importación de la biblioteca</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Last.fm no pudo importar tu historial de reproducción. Esto se puede deber a que ya hayas hecho el scrobbling de un buen número de temas. El historial solo se puede importar a perfiles nuevos.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Sigue las instrucciones de tu sistema operativo para la instalación de los plugins.&lt;/p&gt;&lt;p&gt;Una vez que los plugins se hayan instalado en tu equipo, haz clic en &lt;strong&gt;Continuar&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Tus plugins se están instalando</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>No se instalaron tus plugins</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puedes instalarlos después a través del menú Archivo</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Tus reproductores de medios necesitan un plugin especial de Last.fm para hacer el scrobbling de la música que escuchas.&lt;/p&gt;&lt;p&gt;Selecciona los reproductores de medios para el scrobbling y haz clic en &lt;strong&gt;Instalar plugins&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(versión más reciente)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plugin instalado. Márcalo para volver a instalar.)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Ahora instala los plugins de Last.fm para hacer scrobbling de la música que escuchas.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Instalar plugins</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Omitir &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>General</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Cuentas</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Dispositivos</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Avanzadas</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio de %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 scrobbling</numerusform>\n            <numerusform>%L1 scrobblings</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Artistas más escuchados esta semana</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Artistas más escuchados de todos los tiempos</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>scrobbling</numerusform>\n            <numerusform>scrobblings</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>tema favorito</numerusform>\n            <numerusform>temas favoritos</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artista</numerusform>\n            <numerusform>%L1 artistas</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 tema</numerusform>\n            <numerusform>%L1 temas</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Tienes %1 en tu colección y escuchas una media de %2 al día.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>scrobbling desde %1</numerusform>\n            <numerusform>scrobblings desde %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Ajustes del proxy</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Nombre de usuario:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Puerto:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Contraseña:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>Reproductor de medios desconocido</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>¿Dónde está montado tu iPod?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Pon un artista o tag y pulsa Escuchar</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Escuchar</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>¿Por qué no pruebas con %1, %2, %3 o %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Escuchar el siguiente</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una emisora</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Para escuchar la radio, tienes que suscribirte.</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Última emisora</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una emisora</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Emisoras personales</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Radio de tu colección</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Música que conoces y te gusta</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Tu emisora Mix</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Tu colección + nueva música</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Tu radio recomendada</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Suscríbete para escuchar la radio</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Nueva música de Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Para escuchar la radio en esta aplicación, tienes que suscribirte. ¡Suscríbete ahora para empezar a escuchar música y disfrutar de otras ventajas!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Emisoras de red</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Suscríbete a Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Escucha música gratis en www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Radio de tus amigos</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Música que escuchan tus amigos</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Radio de tus vecinos</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Música de oyentes como tú</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Emisoras recientes</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Escuchando</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Suscríbete para escuchar la radio, ¡solo %1 al mes!</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Scrobblings de dispositivos</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Parece que has escuchados estos temas. ¿Quieres agregarlos como scrobblings?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Scrobbling automático de dispositivos</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Alternar selección</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>Se hizo %n scrobbling desde un dispositivo</numerusform>\n            <numerusform>Se hicieron %n scrobblings desde un dispositivo</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Tema favorito</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Agregar tags</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favorito</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartir</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Compartir en Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Compartir en Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Compartir en Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Comprar</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Quitar de mis favoritos</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobbling al</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>% del tema</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Activar el scrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...o a los 4 minutos (lo que suceda primero)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Scrobbling de podcasts</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Permitir a Last.fm que asigne códigos a mis temas</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>No se hará scrobbling en las carpetas seleccionadas.</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Más scrobblings en Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Actualizando...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Actualizar scrobblings</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Título</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Reproducciones</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Última reproducción</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Favorito</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Este tema no llega a los 30 segundos</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Falta el nombre del artista</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Título de tema no válido</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Artista no válido</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>No hay marca de tiempo</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Tema con marca de tiempo en el futuro</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>El tema se escuchó hace más de dos semanas</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Todavía no has hecho scrobbling de música en Last.fm.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Para empezar, pon algo de música en tu reproductor de medios o escucha una emisora:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Compartir con amigos</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Compartir con:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Mensaje (opcional):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>Incluir en mi actividad reciente</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un tema de %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un tema de %1, del álbum %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Echa un vistazo a %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Escuchando</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobblings</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Perfil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Amigos</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Sección siguiente</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Sección anterior</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>No se pudo iniciar la radio: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>No hay resultados para &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>El scrobbling está desactivado</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Conectado</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Desconectado</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Poner tag a:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Tema</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>Icono</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Agregar tags:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un tema de %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un tema de %1, del álbum %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Escribe un tag arriba\no selecciónalo abajo</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Ordenar por popularidad</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Ordenar alfabéticamente</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Abrir la página de Last.fm de este tag</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;¡Ya estás listo para empezar! Haz clic en &lt;strong&gt;Finalizar&lt;/strong&gt; y explora un poco.&lt;/p&gt;&lt;p&gt;También hemos terminado de importar tu historial de reproducción y lo hemos agregado a tu perfil de Last.fm.&lt;/p&gt;&lt;p&gt;Gracias por instalar Last.fm Desktop App, ¡esperamos que los disfrutes!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Es todo, ¡ya puedes empezar!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Finalizar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;La flecha roja en la pantalla indica la ubicación de Last.fm Desktop App en la bandeja del sistema.&lt;/p&gt;&lt;p&gt;Haz clic en el icono para tener un acceso rápido a los controles de la radio, compartir un tema o ponerle un tag, editar tus preferencias y visitar tu perfil de Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Last.fm Desktop App en la barra de menús</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Last.fm Desktop App en la bandeja del sistema</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Puedes obtener más información sobre la música que escuchas: biografías, estadísticas de reproducción, fotos y artistas similares, así como los tags que los oyentes aplican a esa música.&lt;/p&gt;&lt;p&gt;Solo tienes que echar un vistazo a la pestaña &lt;strong&gt;Escuchando&lt;/strong&gt; o hacer clic en cualquier tema de la pestaña &lt;strong&gt;Scrobblings&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Descubre más sobre los artistas que te gustan</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Omitir el tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Escucha una radio inagotable y personalizada</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Usa Last.fm Desktop App para escuchar una radio personalizada, basada en la música que te gusta.&lt;/p&gt;&lt;p&gt;Cada reproducción de la radio de Last.fm es única: desde emisoras basadas en artistas o tags, hasta recomendaciones inéditas a la medida de tus preferencias musicales.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Suscríbete y escucha una radio inagotable y personalizada</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Suscríbete a Last.fm y usa Last.fm Desktop App para escuchar una radio personalizada, basada en la música que te gusta.&lt;/p&gt;&lt;p&gt;Cada reproducción de la radio de Last.fm es única: desde emisoras basadas en artistas o tags, hasta recomendaciones inéditas a la medida de tus preferencias musicales.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Suscribirse</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Omitir el tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;El software cliente se ejecutará en segundo plano y actualizará en silencio tu perfil de Last.fm con la música que escuchas. Después, utilizará esa información para hacerte recomendaciones, sugerirte conciertos, etc. &lt;/p&gt;&lt;p&gt;También puedes usar Last.fm Desktop App para obtener más información sobre los artistas que escuchas y reproducir una radio personalizada.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>¡Bienvenido a Last.fm Desktop App!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Atrás</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Omitir el tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Tema</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favorito</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartir</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Comprar</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Eliminar este scrobbling de tu perfil</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Escuchar la radio de %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Seguir con la radio de %1</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio de %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>En caché</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Error: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Compartir en Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Compartir en Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Compartir en Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>En reproducción</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Descargas</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Buscar en %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Comprar en %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Cuentas de usuario conectadas:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Agregar una nueva cuenta de usuario</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Error al agregar un usuario</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Este usuario ya está agregado.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Eliminando %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>¿Seguro que quieres eliminar este usuario? Se perderán todos los ajustes de usuario y tendrás que volver a autenticarte para hacer nuevos scrobblings.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Suscribirse</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Eliminar</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(conectado)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Cuentas</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Mostrar Scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favorito</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Escuchar</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Saltar</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartir</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Vetar</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Silencio</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Scrobbling del iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Ir al perfil de Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Activar el scrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Salir de %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Has llegado al límite de saltos de esta emisora. Podrás saltar de nuevo en %n minuto.</numerusform>\n            <numerusform>Has llegado al límite de saltos de esta emisora. Podrás saltar de nuevo en %n minutos.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Te queda %n salto en esta emisora.</numerusform>\n            <numerusform>Te quedan %n saltos en esta emisora.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Requiere autenticación</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;La cuenta de usuario &lt;strong&gt;%1&lt;/strong&gt; ya no está validada en Last.fm.&lt;/p&gt;&lt;p&gt;Haz clic en Aceptar para iniciar el proceso de instalación y volver a autenticar esta cuenta.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>¿Seguro que quieres salir de %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 está a punto de cerrarse. Si continúas, los temas reproducidos no se agregarán como scrobblings.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Cambiando usuario</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 se conectará al Scrobbler y a la radio de Last.fm. Toda la música se agregará como scrobblings de esta cuenta. ¿Quieres continuar?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Para continuar, cierra las siguientes aplicaciones.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Error en la instalación del plugin</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se produjo un error al actualizar el plugin.&lt;/p&gt;&lt;p&gt;Inténtalo de nuevo más tarde.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plugin instalado.</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se instaló el plugin de %1.&lt;/p&gt;&lt;p&gt;Ahora estás listo para hacer scrobbling con %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>No se instaló el plugin de %1.</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>El plugin no se instaló porque no cerraste %1.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Cierra iTunes para actualizar el plugin.</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;El plugin de iTunes (%2) es diferente al que lanzamos con esta versión de la aplicación (%1).&lt;/p&gt;&lt;p&gt;Cierra iTunes para actualizarlo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>no instalado</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>El plugin no se ha instalado.</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Se produjo un error al eliminar el antiguo plugin.</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Plugin de iTunes instalado.</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se instaló el plugin de iTunes.&lt;/p&gt;&lt;p&gt;Ahora estás listo para hacer scrobbling con tu dispositivo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Se produjo un error al copiar el nuevo plugin en la ubicación correspondiente.</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>No cerraste iTunes.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Marca de tiempo errónea</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>Hace %n minuto</numerusform>\n            <numerusform>Hace %n minutos</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>Hace %n hora</numerusform>\n            <numerusform>Hace %n horas</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Se produjo un error de red: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>No has autorizado a la aplicación.</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Error de autenticación</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Actualizar hoja de estilos</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>No volver a preguntar</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Detección automática</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Sin proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_fr.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"fr\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>À propos de</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (réalisé avec Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Veuillez cliquer sur le bouton &lt;strong&gt;Oui, autoriser l&apos;accès&lt;/strong&gt; dans votre navigateur Web pour associer votre compte Last.fm à l&apos;application de bureau Last.fm.&lt;/p&gt;&lt;p&gt;Si vous ne vous êtes pas connecté car vous avez fermé la fenêtre du navigateur ou cliqué sur Annuler, veuillez réessayer.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Nous attendons que vous vous connectiez à Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Poursuivre </translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Réessayer</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Si votre navigateur ne s&apos;ouvre pas, copiez et collez le lien ci-dessous dans votre barre d&apos;adresse.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Raccourcis clavier :</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Afficher/Masquer Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy :</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Activer SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Taille du cache :</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Abonné</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Modérateur</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>L&apos;équipe</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Ancienne élève</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Ancien élève</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>En tournée</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Pour les meilleures recommandations sur base de vos goûts musicaux, nous vous conseillons d&apos;importer votre historique d&apos;écoute depuis votre lecteur média.&lt;/p&gt;&lt;p&gt;Veuillez sélectionner votre lecteur média préféré et cliquer sur &lt;strong&gt;Démarrer l&apos;importation&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Vos plug-ins n&apos;ont pas été installés</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Vous pourrez les installer ultérieurement depuis le menu Fichier</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Maintenant, importons votre historique d&apos;écoute</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Commencer l&apos;importation</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Passer &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ne vous inquiétez pas, le processus de téléchargement ne devrait pas prendre plus de quelques minutes, selon la taille de votre bibliothèque musicale.&lt;/p&gt;&lt;p&gt;Pendant que nous travaillons d&apos;arrache-pied pour ajouter votre historique d&apos;écoute à votre profil Last.fm, pourquoi ne jetteriez-vous pas un œil aux principales fonctionnalités de l&apos;app de bureau Last.fm. Cliquez sur &lt;strong&gt;Continuer&lt;/strong&gt; pour démarrer la présentation&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Fermer les apps</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Scrobbling depuis le périphérique désactivé - plug-in iTunes incompatible - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>veuillez procéder à la mise à jour</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbler l&apos;iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Souhaitez-vous associer l&apos;appareil %1 au scrobbler audio de votre compte d&apos;utilisateur ?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Appareil bien associé à votre compte d&apos;utilisateur. Vous pouvez désormais scrobbler les titres que vous écoutez sur celui-ci.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 titres scrobblés.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Aucun titre à scrobbler depuis votre dernière synchronisation.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Impossible d&apos;ouvrir la base de données de l&apos;iPod.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Une erreur inconnue est survenue lors de la tentative d&apos;accès à la base de données de l&apos;iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostics</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>C&apos;est un œuf de Pâques !</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artiste</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Titre</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Réaliser l&apos;empreinte acoustique</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Titres dont l&apos;empreinte acoustique a été réalisée récemment</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Scrobbling de l&apos;iPod</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes gère mon iPod automatiquement</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Je gère mon iPod manuellement</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbler l&apos;iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Connexions</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Fermer</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n titre dans la mémoire cache locale</numerusform>\n            <numerusform>%n titres dans la mémoire cache locale</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>App de bureau Last.fm</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Merci &lt;strong&gt;%1&lt;/strong&gt;, votre compte est désormais associé !</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importation en cours</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Importation terminée !</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Trouvez vos amis sur Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Vous ne vous êtes pas encore fait d&apos;amis sur Last.fm.&lt;/h3&gt;&lt;p&gt;Trouvez vos amis Facebook et contactez-les par e-mail facilement et rapidement depuis Last.fm en utilisant l&apos;outil de recherche d&apos;amis.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Rechercher un ami par son nom ou son pseudo</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Rafraîchir vos amis</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Rafraîchissement en cours</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Radio de la bibliothèque de %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Homme</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Scrobbling en cours depuis %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Femme</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Scrobbling en cours</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neutre</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Chercher vos amis</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Parcourir vos amis</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Langue :</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Afficher l&apos;icône de l&apos;app dans la barre de menu</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Lancer l&apos;app depuis des lecteurs média</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Afficher l&apos;icône du Dock</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Afficher les notifications de bureau</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Envoyer les rapports d&apos;incident à Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Chercher automatiquement des mises à jour</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Activer les clés média</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Langue du système</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Redémarrer maintenant ?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Un redémarrage de l&apos;application est requis pour que les modifications soient appliquées. Aimeriez-vous la redémarrer maintenant ?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Passer aux versions bêta. Attention, réservé aux intrépides !</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Impossible d&apos;ouvrir la base de données de l&apos;iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Utiliser une app de scrobbling sous iOS, comme %1, peut entraîner une duplication des scrobbles. Veuillez n&apos;activer le scrobbling que sur l&apos;une d&apos;elles.&lt;/p&gt;&lt;p&gt;iTunes Match synchronise le nombre de lectures sur de multiples appareils mais pas les dernières lectures. Une duplication des scrobbles pourrait dès lors avoir lieu à des moments inopportuns. Nous recommandons, pour l&apos;instant, aux utilisateurs d&apos;iTunes Match de désactiver le scrobbling d&apos;appareils sur les dispositifs de bureau et de ne scrobbler des iPhones/iPods qu&apos;en utilisant une app de scrobbling sous iOS comme %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Configuration non changée</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Vous n&apos;avez pas fermé iTunes pour que cette configuration soit modifiée</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Activer le scrobbling sur cet appareil</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Confirmation de scrobbling depuis cet appareil</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Veuillez noter</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licences</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>C&apos;est tout ?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Cliquez sur OK une fois l&apos;app approuvée.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm a d&apos;abord besoin de votre autorisation !</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>L&apos;application a besoin de votre autorisation pour associer votre profil Last.fm. Cliquez sur OK pour vous rendre sur le site Web de Last.fm et le faire.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Vous êtes déjà utilisateur de Last.fm ? Associez votre compte à l&apos;app de bureau Last.fm et mettez à jour votre profil en renseignant la musique que vous écoutez.&lt;/p&gt;&lt;p&gt;Si vous n&apos;avez pas encore de compte, inscrivez-vous gratuitement maintenant.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Commençons par associer votre compte Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Associer votre compte</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>S&apos;inscrire</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy ?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Des mises à jour relatives aux plug-ins de votre lecteur média sont disponibles. Aimeriez-vous les installer maintenant ?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Error d&apos;installation du plug-in</numerusform>\n            <numerusform>Error d&apos;installation des plug-ins</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Une erreur est survenue lors de la mise à jour de votre plug-in.&lt;/p&gt;&lt;p&gt;Veuillez réessayer ultérieurement.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Une erreur est survenue lors de la mise à jour de vos plug-ins.&lt;/p&gt;&lt;p&gt;Veuillez réessayer ultérieurement.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plug-in installé !</numerusform>\n            <numerusform>Plug-ins installés !</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Votre plug-in a bien été installé.&lt;/p&gt;&lt;p&gt;Vous pouvez désormais scrobbler depuis votre lecteur média.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Vos plug-ins ont bien été installés.&lt;/p&gt;&lt;p&gt;Vous pouvez désormais scrobbler depuis votre lecteur média.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Vos plug-ins n&apos;ont pas été installés</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Vous pourrez les installer ultérieurement depuis le menu Fichier</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Fichier</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Installer les plug-ins</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Quitter</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Voir</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Mon profil Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Rafraîchir</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Commandes</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Compte</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Outils</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Chercher des mises à jour</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Options</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Fenêtre</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Réduire</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Tout ramener au premier plan</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Aide</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>À propos</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Forums</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Présentation</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Afficher les licences</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostics</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1 : %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;titres&quot;&gt;%n écoute&lt;/a&gt; a été scrobblée depuis cet appareil</numerusform>\n            <numerusform>&lt;a href=&quot;titres&quot;&gt;%n écoutes&lt;/a&gt; ont été scrobblées depuis cet appareil</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Revenir aux Scrobbles</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Tags populaires :</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Vos tags :</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Artistes similaires</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>par %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Lecture de la radio %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Écoute</numerusform>\n            <numerusform>Écoutes</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Écoute dans votre bibliothèque</numerusform>\n            <numerusform>Écoutes dans votre bibliothèque</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Auditeur</numerusform>\n            <numerusform>Auditeurs</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Avec %1 et plus.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Avec %1, %2 et plus.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Modifié le %1 | %2 Modifier</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Téléchargements</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Chercher sur %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Acheter sur %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physique</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Recommandé car vous écoutez %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Recommandé car vous écoutez %1 et %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Recommandé car vous écoutez %1, %2 et %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Recommandé car vous écoutez %1, %2, %3 et %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Recommandé car vous écoutez %1, %2, %3, %4 et %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Depuis la bibliothèque de %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Depuis les bibliothèques de %1 et %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 fois</numerusform>\n            <numerusform>%L1 fois</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Depuis les bibliothèques de %1, %2 et %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Vous avez écouté %1, %2 et %3, %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Depuis les bibliothèques de %1, %2, %3 et %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Vous avez écouté %1, %2, mais pas ce titre.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Depuis les bibliothèques de %1, %2, %3, %4 et %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>C&apos;est la première fois que vous écoutez %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Salut !</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Lancer une station de radio</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Ouvrir Music</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Ouvrir iTunes</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Ouvrir Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Ouvrir Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Ouvrir Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Scrobbler depuis votre lecteur média&lt;/h2&gt;&lt;p&gt;Commencez à écouter de la musique depuis votre lecteur média. Vous pouvez découvrir plus d&apos;informations sur les titres que vous écoutez en consultant l&apos;onglet En écoute.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Salut, %1 !</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Une station de radio</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Écouter %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Radio multi-bibliothèque</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Mettre %1 en file d&apos;attente</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Écouter les radios des bibliothèques %1 et %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Mettre les radios des bibliothèques %1 et %2 en file d&apos;attente</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Aimer</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Bannir</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Lire</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Passer</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Suspendre</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Reprendre</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Ne plus aimer</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Réglage</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Une station de radio</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Écouter</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbler depuis</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 écoute</numerusform>\n            <numerusform>%L1 écoutes</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm a importé votre bibiothèque media. \n\n Cliquez sur OK pour continuer.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Importation de bibliothèque de Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Êtes-vous sûr de vouloir annuler cette importation ?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm n&apos;a trouvé aucun titre diffusé dans votre bibliothèque média.\n\n Cliquez sur OK pour continuer.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm est en train d&apos;importer votre bibliothèque média actuelle.</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Où est Winamp ?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Où est le lecteur Windows Media ?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Importation de la bibliothèque média terminée</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm a envoyé votre historique d&apos;écoute au serveur.\nLes nouveaux titres seront ajoutés à votre profil dans quelques minutes.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Échec de l&apos;importation de la bibliothèque</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Désolé, Last.fm n&apos;a pu importer votre historique d&apos;écoute. Vous avez sans doute déjà scrobblé un trop grand nombre de titres. L&apos;historique ne peut être importé que sur les nouveaux profils.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Veuillez suivre les instructions qui apparaissent sur votre système d&apos;exploitation pour installer les plug-ins.&lt;/p&gt;&lt;p&gt;Une fois ceux-ci installés sur votre ordinateur, cliquez sur &lt;strong&gt;Continuer&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Vos plug-ins sont en cours d&apos;installation</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Vos plug-ins n&apos;ont pas été installés</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Vous pourrez les installer ultérieurement depuis le menu Fichier</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Vos lecteurs média ont besoin d&apos;un plug-in spécial Last.fm pour être en mesure de scrobbler la musique que vous écoutez.&lt;/p&gt;&lt;p&gt;Veuillez sélectionner les lecteurs média depuis lesquels vous aimeriez scrobbler et cliquez sur &lt;strong&gt;Installer les plug-ins&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(version plus récente)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plug-in installé, cochez pour réinstaller)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Ensuite, installez les plug-ins Last.fm pour pouvoir scrobbler la musique que vous écoutez.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Installer les plug-ins</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Passer &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Général</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Comptes</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Appareils</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Avancé</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 écoute</numerusform>\n            <numerusform>%L1 écoutes</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Les top artistes de la semaine</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Les top artistes de tous les temps</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobble</numerusform>\n            <numerusform>Scrobbles</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Coup de cœur</numerusform>\n            <numerusform>Coups de cœur</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artiste</numerusform>\n            <numerusform>%L1 artistes </numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 titre</numerusform>\n            <numerusform>%L1 titres</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Vous avez %1 dans votre bibliothèque et écoutez %2 en moyenne par jour.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobble depuis %1</numerusform>\n            <numerusform>Scrobbles depuis %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Paramètres du proxy</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Hôte :</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Nom d&apos;utilisateur :</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port :</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Mot de passe :</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>lecteur média inconnu</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Où votre iPod est-il installé ?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Saisir un artiste ou son tag puis I&gt;</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Lire</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Pourquoi ne pas essayer %1, %2, %3 ou %4 ?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Écouter le suivant</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Une station de radio</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Vous devez être abonné pour pouvoir écouter la radio.</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>La dernière station</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Une station de radio</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Radios personnelles</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>La radio de ma bibliothèque</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>La musique que vous connaissez et que vous adorez</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Ma Radio Mix</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Votre bibliothèque et de la nouvelle musique</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Ma radio recommandée</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Abonnez-vous pour pouvoir écouter la radio.</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>De la nouvelle musique de Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Vous devez être abonné pour pouvoir écouter la radio avec cette app. Abonnez-vous maintenant pour commencer à écouter et bénéficiez d&apos;une multitude d&apos;autres avantages !</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Stations du réseau</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Abonnez-vous à Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Écoutez gratuitement sur www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>La radio de mes amis</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>La musique que vos amis apprécient</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Ma radio de proximité</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>La musique d&apos;auditeurs qui vous ressemblent</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Stations récentes</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>En écoute</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Abonnez-vous pour écouter la radio pour seulement %1 par mois.</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Les scrobbles depuis cet appareil</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>On dirait que vous avez écouté ces titres. Aimeriez-vous les scrobbler ?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Scrobbler ces appareils automatiquement</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Basculer entre les sélections</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n écoute a été scrobblée depuis cet appareil</numerusform>\n            <numerusform>%n écoutes ont été scrobblées depuis cet appareil</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Aimer le titre</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Ajouter des tags</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favori</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Partager</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Partager sur Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Partager sur Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Partager sur Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Acheter</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Ne plus aimer le titre</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobblé à</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>pourcent du titre</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Activer le scrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...ou à 4 minutes (selon ce qui se produit en premier)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Scrobbler les podcasts</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Permettre à Last.fm d&apos;effectuer une empreinte acoustique de mes titres</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Les répertoires sélectionnés ne seront pas scrobblés</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Plus de scrobbles sur Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Rafraîchissement en cours</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Rafraîchir les scrobbles</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artiste</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Titre</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>En lecture</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Dernière lecture</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Aimé</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Ce titre fait moins de 30 secondes</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Le nom de l&apos;artiste est manquant</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Intitulé de titre non valide</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Artiste non valide</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Il n&apos;existe aucun horadatage</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Ce titre est trop éloigné dans le futur</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Ce titre a été lu il y a plus de deux semaines</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Vous n&apos;avez scrobblé encore aucune musique de Last.fm.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Commencez à écouter de la musique de votre lecteur média ou lancez une station de radio :</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Partager avec des amis</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Avec :</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Message (facultatif) :</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>à reprendre dans mes activités récentes</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un titre par %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un titre par %1 de la sortie %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Jetez un coup d&apos;œil à %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>En écoute</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Amis </translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Section suivante</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Section précédente</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Impossible de lancer la radio : %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>aucun résultat pour &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobbling désactivé</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>En ligne</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Hors ligne</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Choisissez quelque chose à taguer :</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Titre</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artiste</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>Icône</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Ajouter des tags :</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un titre par %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un titre par %1 de la sortie %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Saisissez un tag ci-dessus,\nou choisissez-en un ci-dessous</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Classer par popularité</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Classer par ordre alphabétique</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Ouvrir la page Last.fm de ce tag</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Vous voilà désormais fin prêt à commencer ! Cliquez simplement sur &lt;strong&gt;Terminer&lt;/strong&gt; et commencez à explorer.&lt;/p&gt;&lt;p&gt;Nous avons également terminé l&apos;importation de votre historique d&apos;écoute et l&apos;avons ajouté à votre profil Last.fm.&lt;/p&gt;&lt;p&gt;Merci d&apos;avoir installé l&apos;app de bureau Last.fm, nous espérons qu&apos;elle vous plaira !&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Vous voilà fin prêt !</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Terminer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;La flèche rouge sur votre écran indique où se trouve l&apos;app de bureau Last.fm dans la barre d&apos;état de votre système.&lt;/p&gt;&lt;p&gt;Cliquez sur l&apos;icône pour accéder rapidement aux commandes de lecture de la radio, pour partager et taguer des titres, pour modifier vos préférences et vous rendre sur votre profil Last.fm&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>L&apos;app de bureau Last.fm dans votre barre de menu</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>L&apos;app de bureau Last.fm dans la barre d&apos;état de votre système</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Découvrez-en plus sur la musique que vous écoutez, y compris les biographies, les stats d&apos;écoute, les photos et les artistes similaires, ainsi que les tags que les auditeurs utilisent pour les décrire.&lt;/p&gt;&lt;p&gt;Découvrez l&apos;onglet &lt;strong&gt;En écoute&lt;/strong&gt; et cliquez simplement sur n&apos;importe quel titre repris sous l&apos;onglet &lt;strong&gt;Scrobbles&lt;/strong&gt; pour en savoir plus.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Découvrez-en plus sur les artistes que vous aimez</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Passer la présentation</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Écouter votre radio personnalisée sans interruption</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Utilisez l&apos;app de bureau Last.fm pour écouter une radio personnalisée, basée sur la musique que vous préférez.&lt;/p&gt;&lt;p&gt;Chaque écoute de chaque station radio de Last.fm est complètement différente car les stations se basent sur des artistes, des tags voire des recommandations afin de répondre au mieux à vos goûts musicaux.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Abonnez-vous et écoutez votre radio personnalisée sans interruption</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Abonnez-vous à Last.fm et utilisez l&apos;app de bureau Last.fm pour écouter une radio personnalisée, basée sur la musique que vous préférez.&lt;/p&gt;&lt;p&gt;Chaque écoute de chaque station radio de Last.fm est complètement différente car les stations se basent sur des artistes, des tags voire des recommandations afin de répondre au mieux à vos goûts musicaux&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>S&apos;abonner</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Passer la présentation &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Le client de bureau fonctionne en arrière-plan, mettant à jour discrètement votre profil Last.fm et la musique que vous jouez. Vous pouvez l&apos;utiliser pour découvrir des recommandations musicales, des actus concerts et bien plus encore. &lt;/p&gt;&lt;p&gt;Vous pouvez également utiliser l&apos;app de bureau Last.fm pour en apprendre davantage sur l&apos;artiste que vous écoutez et écouter votre radio personnalisée.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Bienvenue sur l&apos;app de bureau Last.fm !</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuer</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Retour</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Passer la présentation &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Titre</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artiste</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favori</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Taguer</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Partager</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Acheter</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Supprimer ce scrobble de votre profil</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Lecture de la radio %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Mettre la radio %1 en file d&apos;attente</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Mis dans la mémoire cache</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Erreur : %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Partager sur Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Partager sur Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Partager sur Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>En écoute</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Téléchargements</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Chercher sur %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Acheter sur %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Physique</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Comptes d&apos;utilisateur associés :</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Ajouter un nouveau compte d&apos;utilisateur</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Ajouter une erreur d&apos;utilisateur</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>L&apos;utilisateur a déjà été ajouté</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Suppression en cours de %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Êtes-vous sûr de vouloir supprimer cet utilisateur ? Tous les paramètres de cet utilisateur seront perdus et vous devrez vous authentifier à nouveau pour scrobbler à l&apos;avenir.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Actions</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Supprimer</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(connecté actuellement)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Comptes</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Afficher le scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Favori</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Lire</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Passer</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Taguer</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Partager</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Bannir</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Muet</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Scrobbler l&apos;iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Visiter le profil Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Activer le scrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Quitter %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform> Vous avez cliqué sur Suivant le maximum de fois autorisé pour le moment pour cette radio. Veuillez attendre %n minute avant de cliquer sur Suivant à nouveau.</numerusform>\n            <numerusform> Vous avez cliqué sur Suivant le maximum de fois autorisé pour le moment pour cette radio. Veuillez attendre %n minutes avant de cliquer sur Suivant à nouveau.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Vous pouvez encore cliquer %n fois sur Suivant pour cette radio.</numerusform>\n            <numerusform>Vous pouvez encore cliquer %n fois sur Suivant pour cette radio.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Authentification requise</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Le compte d&apos;utilisateur &lt;strong&gt;%1&lt;/strong&gt; n&apos;est plus authentifié avec Last.fm.&lt;/p&gt;&lt;p&gt;Cliquez sur OK pour commencer le processus d&apos;authentification et authentifier à nouveau ce compte.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Êtes-vous sûr de vouloir quitter %1 ?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>Sur le point de quitter %1. Si vous continuez, les titres lus ne seront plus scrobblés.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Changement d&apos;utilisateur en cours</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 sera connecté au scrobbler et à la radio Last.fm. Toute la musique sera désormais scrobblée sur ce compte. Voulez-vous continuer ?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Veuillez fermer les apps suivantes pour continuer.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Erreur d&apos;installation du plug-in</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Une erreur est survenue lors de la mise à jour du plug-in.&lt;/p&gt;&lt;p&gt;Veuillez réessayer ultérieurement.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plug-in installé !</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Le plug-in %1 a bien été installé.&lt;/p&gt;&lt;p&gt;Vous êtes désormais prêt à scrobbler avec %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Le plug-in %1 n&apos;a pas été installé</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Vous n&apos;avez pas fermé %1 donc son plug-in n&apos;a pas été installé.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Fermez iTunes pour la mise à jour du plug-in !</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Votre plug-in iTunes (%2) est différent de celui expédié avec cette version de l&apos;app (%1).&lt;/p&gt;&lt;p&gt;Veuillez fermer iTunes maintenant pour le mettre à jour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>pas installé</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Votre plug-in n&apos;a pas été installé</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Une erreur est survenue lors de la suppression de l&apos;ancien plug-in</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Plug-in iTunes installé !</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Votre plug-in iTunes est bien installé.&lt;/p&gt;&lt;p&gt;Vous pouvez désormais scrobbler depuis votre périphérique.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Une erreur est survenue lors de la copie du nouveau plug-in à son nouvel emplacement</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Vous n&apos;avez pas fermé iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Le temps s&apos;est fait la malle</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>Il y a %n minute</numerusform>\n            <numerusform>Il y a %n minutes</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>Il y a %n heure</numerusform>\n            <numerusform>Il y a %n heures</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Une erreur réseau est survenue : %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Vous n&apos;avez pas autorisé cette application</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Erreur d’authentification</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Rafraîchir la feuille de style</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Ne plus me le demander</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Détection automatique</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Aucun proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_it.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"it\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Informazioni</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (basato su Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Fai clic sul pulsante &lt;strong&gt;Sì, consenti l&apos;accesso&lt;/strong&gt; nel browser Web per collegare il tuo account di Last.fm all&apos;app Last.fm per desktop.&lt;/p&gt;&lt;p&gt;Se non hai effettuato il collegamento perché hai chiuso la finestra del browser o hai fatto clic su &quot;annulla&quot;, riprova.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Stiamo aspettando che ti colleghi a Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Riprova</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se il browser non si è aperto, copia e incolla il collegamento qui sotto nella barra degli indirizzi.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Scorciatoie da tastiera:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Mostra/Nascondi Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Attiva SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Dimensioni cache:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Abbonato</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderatore</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Staff</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Ex dipendente</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Ex dipendente</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>In tour</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Per ottenere i migliori consigli possibili in base ai tuoi gusti musicali, importa la cronologia di ascolto dal tuo lettore multimediale.&lt;/p&gt;&lt;p&gt;Seleziona il lettore che preferisci e fai clic su &lt;strong&gt;Avvia importazione&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>I plug-in non sono stati installati</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puoi installarli in seguito dal menu File</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Ora importiamo la tua cronologia di ascolto</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Avvia importazione</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Ignora &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Il processo di caricamento non dovrebbe richiedere più di qualche minuto, in base alle dimensioni della tua libreria musicale.&lt;/p&gt;&lt;p&gt;Mentre aggiungiamo la cronologia di ascolto al tuo profilo di Last.fm, dai un&apos;occhiata alle principali funzioni dell&apos;app Last.fm per desktop. Fai clic su &lt;strong&gt;Continua&lt;/strong&gt; per iniziare il tour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Chiudi applicazioni</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Scrobbling dai dispositivi disattivato. Plug-in di iTunes non compatibile. %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>Aggiorna</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbling dall&apos;iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Vuoi associare il dispositivo %1 al tuo account utente di Audioscrobbler?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Il dispositivo è stato associato al tuo account utente. Ora puoi eseguire lo scrobbling dei brani che ascolti sul dispositivo.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 scrobbling di brani.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Nessun brano di cui eseguire lo scrobbling dall&apos;ultima sincronizzazione.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Impossibile accedere al database dell&apos;iPod.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Si è verificato un errore sconosciuto durante il tentativo di accesso al database dell&apos;iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostica</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Sorpresa!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Brano</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingerprinting</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Brani recenti di cui è stato eseguito il fingerprinting</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Scrobbling dall&apos;iPod</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iPod gestito automaticamente da iTunes</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>iPod gestito manualmente</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbling dall&apos;iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Log</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Chiudi</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n brano memorizzato nella cache locale</numerusform>\n            <numerusform>%n brani memorizzati nella cache locale</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>App Last.fm per desktop</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Grazie &lt;strong&gt;%1&lt;/strong&gt;, il tuo account è collegato!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importazione in corso...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Importazione completata!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Trova i tuoi amici su Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Non hai ancora amici su Last.fm.&lt;/h3&gt;&lt;p&gt;Trova i tuoi amici di Facebook e contatti e-mail su Last.fm in modo semplice e rapido con la funzione Trova amici.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Cerca un amico per nome utente o nome reale</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Aggiorna amici</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Aggiornamento in corso...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>La libreria di %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Maschio</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Scrobbling in corso da %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Femmina</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Scrobbling in corso</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Sconosciuto</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Cerca i tuoi amici</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Cerca amici</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Lingua:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Mostra l&apos;icona dell&apos;applicazione sulla barra dei menu</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Avvia applicazione con lettori multimediali</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Mostra icona del Dock</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Mostra notifiche sul desktop</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Invia segnalazioni di arresto anomalo a Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Controlla aggiornamenti automaticamente</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Attiva tasti multimediali</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Lingua del sistema</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Riavviare ora?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>È necessario riavviare l&apos;applicazione per rendere effettiva la modifica. Vuoi riavviare ora?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Aggiorna le versioni beta</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Impossibile accedere al database dell&apos;iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se usi un&apos;app di scrobbling per iOS come %1 potresti creare scrobbling duplicati. Attiva lo scrobbling in una sola app.&lt;/p&gt;&lt;p&gt;iTunes Match sincronizza tra più dispositivi il numero di ascolti, ma non la data dell&apos;ultimo ascolto. Ciò comporta la creazione di scrobbling duplicati con date errate. Per ora, consigliamo agli utenti di iTunes Match di disattivare lo scrobbling dai dispositivi sui dispositivi per desktop e di eseguire lo scrobbling da iPhone/iPod con un&apos;app di scrobbling per iOS come %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Impostazione non modificata</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Non hai chiuso iTunes, quindi l&apos;impostazione non è stata modificata</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Attiva scrobbling dai dispositivi</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Conferma scrobbling dai dispositivi</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Nota</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licenze</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Fatto?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Una volta autorizzata l&apos;applicazione, fai clic su OK.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm ha bisogno della tua autorizzazione!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Devi autorizzazione questa applicazione a collegarsi al tuo profilo di Last.fm. Fai clic su OK per accedere al sito di Last.fm e fornire l&apos;autorizzazione.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Sei già un utente di Last.fm? Collega il tuo account all&apos;app Last.fm per desktop e aggiorneremo il tuo profilo con la musica che ascolti.&lt;/p&gt;&lt;p&gt;Se non hai un account, puoi registrarti ora. È gratis!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Per iniziare, collega il tuo account di Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Collega il tuo account</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Registrati</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Sono disponibili aggiornamenti per i plug-in dei tuoi lettori multimediali. Vuoi installarli ora?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Errore di installazione del plug-in</numerusform>\n            <numerusform>Errore di installazione dei plug-in</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Si è verificato un errore durante l&apos;aggiornamento del plug-in.&lt;/p&gt;&lt;p&gt;Riprova più tardi.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Si è verificato un errore durante l&apos;aggiornamento dei plug-in.&lt;/p&gt;&lt;p&gt;Riprova più tardi.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plug-in installato!</numerusform>\n            <numerusform>Plug-in installati!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Il plug-in è stato installato.&lt;/p&gt;&lt;p&gt;Ora puoi eseguire lo scobbling con il tuo lettore multimediale&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;I plug-in sono stati installati.&lt;/p&gt;&lt;p&gt;Ora puoi eseguire lo scobbling con i tuoi lettori multimediali&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>I plug-in non sono stati installati</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puoi installarli in seguito dal menu File</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>File</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Installa plug-in</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Chiudi</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Visualizza</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Il mio profilo di Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Aggiorna</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Controlli</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Account</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Strumenti</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Controlla aggiornamenti</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Opzioni</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Finestra</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Riduci a icona</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Ingrandisci</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Porta in primo piano</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Guida</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Informazioni</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Forum</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tour</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Visualizza licenze</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostica</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n scrobbling&lt;/a&gt; da un dispositivo</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n scrobbling&lt;/a&gt; da un dispositivo</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Torna agli scrobbling</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Tag più usati:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>I tuoi tag:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Artisti simili</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>di %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>da %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Ascolta radio di %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Ascolto</numerusform>\n            <numerusform>Ascolti</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Ascolto nella tua libreria</numerusform>\n            <numerusform>Ascolti nella tua libreria</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Ascoltatore</numerusform>\n            <numerusform>Ascoltatori</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Con %1 e altri.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Con %1, %2 e altri.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Modificato il %1 | %2 Modifica</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Download</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Cerca su %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Acquista su %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Supporto fisico</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Consigliato perché ascolti %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Consigliato perché ascolti %1 e %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Consigliato perché ascolti %1, %2 e %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Consigliato perché ascolti %1, %2, %3 e %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Consigliato perché ascolti %1, %2, %3, %4 e %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Dalla libreria di %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Dalle librerie di %1 e %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 volta</numerusform>\n            <numerusform>%L1 volte</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Dalle librerie di %1, %2 e %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Hai ascoltato %1 %2 e %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Dalle librerie di %1, %2, %3 e %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Hai ascoltato %1 %2, ma non questo brano.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Dalle librerie di %1, %2, %3, %4 e %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Questa è la prima volta che ascolti %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Ciao!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Avvia una stazione radio</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Apri iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Apri Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Apri Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Apri Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Apri Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Esegui lo scrobbling dal tuo lettore musicale&lt;/h2&gt;&lt;p&gt;Inizia ad ascoltare musica nel lettore. Puoi vedere ulteriori informazioni sui brani che ascolti nella scheda In ascolto.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Ciao %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una stazione radio</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Ascolta %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Radio di diverse librerie</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Metti in coda %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Ascolta libreria di %1 e %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Metti in coda libreria di %1 e %2</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Aggiungi ai preferiti</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Escludi</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Ascolta</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Brano successivo</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pausa</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Riprendi</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Elimina dai preferiti</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Sintonizzazione</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una stazione radio</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>In ascolto di</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbling in corso da</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 ascolto</numerusform>\n            <numerusform>%L1 ascolti</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>La tua libreria multimediale è stata importata.\n\n Fai clic su OK per continuare.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Importazione della libreria su Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Vuoi annullare l&apos;importazione?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Impossibile trovare brani ascoltati nella libreria multimediale.\n\n Fai clic su OK per continuare.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm sta importando la tua libreria multimediale...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Dov&apos;è Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Dov&apos;è Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Importazione della libreria multimediale completata</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>La tua cronologia di ascolto è stata inviata al server.\nIl tuo profilo verrà aggiornato con i nuovi brani tra qualche minuto.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Importazione della libreria non riuscita</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Impossibile importare la tua cronologia di ascolto. Probabilmente hai già eseguito lo scrobbling di troppi brani. Le cronologie di ascolto possono essere importate solo nei profili appena creati.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Segui le istruzioni visualizzate nel tuo sistema operativo per installare i plug-in.&lt;/p&gt;&lt;p&gt;Una volta completata l&apos;installazione, fai clic su &lt;strong&gt;Continua&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>I plug-in verranno installati</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>I plug-in non sono stati installati</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Puoi installarli in seguito dal menu File</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Per eseguire lo scrobbling con i tuoi lettori multimediali, sono necessari appositi plug-in di Last.fm.&lt;/p&gt;&lt;p&gt;Seleziona i lettori che vorresti utilizzare per lo scrobbling e fai clic su &lt;strong&gt;Installa plug-in&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(versione più recente)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plug-in installato. Seleziona per reinstallarlo)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Ora installa i plug-in di Last.fm per eseguire lo scrobbling della musica che ascolti.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Installa plug-in</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Ignora &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Generale</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Account</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Dispositivi</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Avanzate</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio di %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 ascolto</numerusform>\n            <numerusform>%L1 ascolti</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Artisti più ascoltati questa settimana</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Artisti più ascoltati in generale</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobbling</numerusform>\n            <numerusform>Scrobbling</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Brano preferito</numerusform>\n            <numerusform>Brani preferiti</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artista</numerusform>\n            <numerusform>%L1 artisti</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 brano</numerusform>\n            <numerusform>%L1 brani</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Hai %1 nella tua libreria e in media ascolti %2 al giorno.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobbling dal %1</numerusform>\n            <numerusform>Scrobbling dal %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Impostazioni proxy</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Nome utente:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Porta:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Password:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>lettore multimediale sconosciuto</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Dove è connesso il tuo iPod?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Digita artista/tag e fai clic su Ascolta</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Ascolta</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Perché non provi %1, %2, %3 o %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Ascolta successivo</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una stazione radio</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Devi essere abbonato per ascoltare la radio</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Ultima stazione</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Una stazione radio</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Stazioni personali</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>La mia libreria</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Musica che conosci e ami</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>La mia radio mixata</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>La tua libreria e nuova musica</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>La radio dei miei consigli</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Abbonati per ascoltare la radio</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Nuova musica da Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Devi essere abbonato a Last.fm per ascoltare la radio in questa app. Abbonati ora per iniziare ad ascoltare e approfittare di altri fantastici vantaggi!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Stazioni del network</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Abbonati a Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Ascolta gratis su www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>La radio dei miei amici</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Musica che piace ai tuoi amici</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>La radio dei miei vicini</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Musica di ascoltatori come te</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Stazioni recenti</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>In ascolto</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Abbonati per ascoltare la radio, solo %1 al mese</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Scrobbling dai dispositivi</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Hai ascoltato questi brani. Vuoi eseguirne lo scrobbling?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Esegui automaticamente lo scrobbling dai dispositivi</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Attiva/Disattiva selezione</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n scrobbling da un dispositivo</numerusform>\n            <numerusform>%n scrobbling da un dispositivo</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Aggiungi brano ai preferiti</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Aggiungi tag</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Aggiungi ai preferiti</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Aggiungi tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Condividi</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Condividi su Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Condividi su Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Condividi su Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Acquista</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Elimina dai preferiti</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobbling al</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>percento del brano</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Attiva scrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...o a 4 minuti (a seconda della condizione che si verifica prima)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Esegui scrobbling dei podcast</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Consenti a Last.fm di eseguire il fingerprinting dei brani</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Lo scrobbling non verrà eseguito nelle directory selezionate.</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Altri scrobbling su Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Aggiornamento in corso...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Aggiorna scrobbling</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Titolo</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Ascolti</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Ultimo ascolto</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Aggiunto ai preferiti</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Questo brano dura meno di 30 secondi</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Nome dell&apos;artista mancante</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Titolo del brano non valido</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Artista non valido</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Timestamp mancante</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Questo brano è in un futuro lontano</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Questo brano è stato ascoltato più di due settimane fa</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Non hai ancora eseguito scrobbling su Last.fm.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Inizia ad ascoltare musica nel tuo lettore o avvia una stazione radio:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Condividi con amici</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Con:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Messaggio (opzionale):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>includi nelle mie attività recenti</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un brano di %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un brano di %1 dall&apos;album %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Dai un&apos;occhiata a %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>In ascolto</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profilo</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Amici</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Sezione successiva</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Sezione precedente</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Impossibile avviare la radio: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>nessun risultato per &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobbling disattivato</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Online</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Offline</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Aggiungi tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Scegli a cosa aggiungere i tag:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Brano</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>icona</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Aggiungi tag:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Un brano di %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Un brano di %1 dall&apos;album %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Digita un tag qui sopra,\no scegli tra i seguenti</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Ordina per popolarità</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Ordina alfabeticamente</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Apri la pagina Last.fm di questo tag</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Sei pronto per iniziare! Fai clic su &lt;strong&gt;Fine&lt;/strong&gt; e comincia a esplorare.&lt;/p&gt;&lt;p&gt;La tua cronologia di ascolto è già stata importata e aggiunta al tuo profilo di Last.fm.&lt;/p&gt;&lt;p&gt;Grazie per aver installato l&apos;app Last.fm per desktop, buon divertimento!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Questo è tutto!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Fine</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;La freccia rossa sullo schermo indica la posizione dell&apos;app Last.fm per desktop nell&apos;area di notifica.&lt;/p&gt;&lt;p&gt;Fai clic sull&apos;icona per accedere ai controlli della radio, condividere i brani e aggiungervi tag, modificare le tue preferenze e visitare il tuo profilo di Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>App Last.fm per desktop nella barra dei menu</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>App Last.fm per desktop nell&apos;area di notifica</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Puoi ottenere maggiori informazioni sulla musica che ascolti, tra cui biografie, statistiche di ascolto, foto, artisti simili e tag aggiunti dagli ascoltatori.&lt;/p&gt;&lt;p&gt;Dai un&apos;occhiata alla scheda &lt;strong&gt;In ascolto&lt;/strong&gt; o fai clic su qualsiasi brano nella scheda &lt;strong&gt;Scrobbling&lt;/strong&gt; per saperne di più.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Ottieni informazioni sugli artisti che ami</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Ignora tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Ascolta una radio personalizzata senza interruzioni</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Usa l&apos;app Last.fm per desktop per ascoltare una radio personalizzata, basata sulla musica che preferisci.&lt;/p&gt;&lt;p&gt;Ogni riproduzione della radio di Last.fm è unica, dalle stazioni basate su artisti e tag ai nuovi consigli personalizzati in base ai tuoi gusti musicali.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Abbonati e ascolta una radio personalizzata senza interruzioni</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Abbonati a Last.fm e usa l&apos;app Last.fm per desktop per ascoltare una radio personalizzata, basata sulla musica che preferisci.&lt;/p&gt;&lt;p&gt;Ogni riproduzione della radio di Last.fm è unica, dalle stazioni basate su artisti e tag ai nuovi consigli personalizzati in base ai tuoi gusti musicali.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abbonati</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Ignora tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Il client desktop aggiorna in background il tuo profilo di Last.fm con la musica che ascolti, così puoi ricevere consigli musicali, suggerimenti sui concerti e molto altro. &lt;/p&gt;&lt;p&gt;Puoi usare l&apos;app Last.fm per desktop anche per ottenere maggiori informazioni sull&apos;artista che stai ascoltando e per riprodurre una radio personalizzata.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Benvenuto nell&apos;app Last.fm per desktop!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continua</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Indietro</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Ignora tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Brano</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Aggiungi ai preferiti</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Aggiungi tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Condividi</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Acquista</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Elimina questo scrobbling dal tuo profilo</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Ascolta radio di %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Metti in coda radio di %1</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio di %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Nella cache</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Errore: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Condividi su Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Condividi su Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Condividi su Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>In ascolto</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Download</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Cerca su %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Acquista su %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Supporto fisico</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Account utente collegati:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Aggiungi nuovo account</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Errore durante l&apos;aggiunta dell&apos;utente</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Questo utente è già stato aggiunto.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Rimozione di %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Vuoi davvero rimuovere questo utente? Tutte le impostazioni dell&apos;utente andranno perse e dovrai effettuare nuovamente l&apos;autenticazione per eseguire lo scrobbling in futuro.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abbonati</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Rimuovi</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(attualmente connesso)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Account</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Mostra Scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Aggiungi ai preferiti</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Ascolta</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Brano successivo</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Aggiungi tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Condividi</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Escludi</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Disattiva audio</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Scrobbling dei brani sull&apos;iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Visita profilo di Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Attiva scrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Chiudi %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>da %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Hai raggiunto il limite massimo di passaggi al brano successivo per questa stazione. Riprova tra %n minuto.</numerusform>\n            <numerusform>Hai raggiunto il limite massimo di passaggi al brano successivo per questa stazione. Riprova tra %n minuti.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Hai ancora %n passaggio al brano successivo per questa stazione.</numerusform>\n            <numerusform>Hai ancora %n passaggi al brano successivo per questa stazione.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>È richiesta l&apos;autenticazione</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;L&apos;account utente &lt;strong&gt;%1&lt;/strong&gt; non è più autenticato con Last.fm.&lt;/p&gt;&lt;p&gt;Fai clic su OK per avviare il processo di configurazione ed effettuare nuovamente l&apos;autenticazione dell&apos;account.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Vuoi davvero chiudere %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 verrà chiuso. Se continui, non verrà eseguito lo scrobbling dei brani che ascolti.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Cambio utente</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 verrà connesso allo Scrobbler e alla radio di Last.fm. Lo scrobbling di tutta la musica verrà eseguito in questo account. Vuoi continuare?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Devi chiudere le seguenti applicazioni per continuare.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Errore di installazione del plug-in</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Si è verificato un errore durante l&apos;aggiornamento del plug-in.&lt;/p&gt;&lt;p&gt;Riprova più tardi.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plug-in installato!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Il plug-in di %1 è stato installato.&lt;/p&gt;&lt;p&gt;Ora puoi eseguire lo scobbling con %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Il plug-in di %1 non è stato installato</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Non hai chiuso %1, quindi il plug-in corrispondente non è stato installato.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Chiudi iTunes per aggiornare il plug-in!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Il plug-in di iTunes (%2) è diverso da quello fornito con questa versione dell&apos;app (%1).&lt;/p&gt;&lt;p&gt;Chiudi iTunes per aggiornarlo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>non installato</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Il plug-in non è stato installato</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Si è verificato un errore durante la rimozione del plug-in precedente</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Plug-in di iTunes installato!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Il plug-in di iTunes è stato installato.&lt;/p&gt;&lt;p&gt;Ora puoi eseguire lo scrobbling dai dispositivi.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Si è verificato un errore durante la copia del nuovo plug-in</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Non hai chiuso iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Tempo errato</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n minuto fa</numerusform>\n            <numerusform>%n minuti fa</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n ora fa</numerusform>\n            <numerusform>%n ore fa</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Si è verificato un errore di rete: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Non hai autorizzato l&apos;applicazione</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Errore di autenticazione</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Aggiorna foglio di stile</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Non visualizzare più questo messaggio</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Rilevamento automatico</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Nessun proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_ja.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"ja\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>バージョン情報</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (built on Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;ウェブブラウザ上の&lt;strong&gt;｢アクセスを許可する｣&lt;/strong&gt;ボタンをクリックし、Last.fm アカウントを Last.fm デスクトップ・アプリに接続してください。&lt;/p&gt;&lt;p&gt;ブラウザ・ウインドウを閉じたもしくはキャンセルをクリックしたため接続していない場合は、もう一度試してください。&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Last.fm への接続をお待ちしています</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>再実行</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;ウェブ・ブラウザが開かなかった場合、以下のリンクをアドレスバーにコピー＆ペーストしてください。&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>キーボードショートカット：</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Last.fm 表示/非表示</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>プロキシ：</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>SSL を有効にする</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>キャッシュサイズ：</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>有料メンバー</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>モデレータ</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>スタッフ</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>OG</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>OB</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>ツアー中</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;あなたの音楽テイストに基づいた最高のおすすめ情報を入手するには、お使いのメディアプレイヤーから再生履歴をインポートすることをお勧めします。&lt;/p&gt;&lt;p&gt;優先するメディアプレイヤーを選択して&lt;strong&gt;インポート開始&lt;/strong&gt;をクリックしてください&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>マイ プラグインはインストールされませんでした</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>後でファイルメニューからインストール可能です</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>再生履歴をインポートしましょう</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>インポート開始</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>スキップ &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;ご安心ください。マイ ライブラリのサイズにもよりますが、アップロード処理にかかる時間は数分です。&lt;/p&gt;&lt;p&gt;再生履歴を Last.fm プロフィールに追加している間、Last.fm デスクトップ・アプリのメイン機能をチェックしてみませんか？&lt;strong&gt;続行&lt;/strong&gt;をクリックしてサイトツアー開始。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>アプリを閉じる</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>デバイス Scrobble 無効 - iTunes プラグイン互換性なし - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>アップデートしてください</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod を Scrobble</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>デバイス %1 を audioscrobbler ユーザーアカウントに関連付けますか？</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>デバイスをユーザーアカウントに関連付けるのに成功しました。今後はこのデバイスで再生したトラックを Scrobble できます。</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 トラック Scrobble 済。</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>最終同期から Scrobble されたトラックはありません。</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod データベースを開くことができませんでした。</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>iPod データベースにアクセスしようとした際、原因不明のエラーが発生しました。</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>診断</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobble 中</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>これはイースターエッグ(隠しメッセージ)です！</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>アーティスト</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>トラック</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>アルバム</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>フィンガープリント中</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>最近フィンガープリントされたトラック</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod Ｓcrobble 中</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes で iPod を自動管理</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>iPod を手動管理</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod を Scrobble</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>ログ</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>閉じる（&amp;C）</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n ローカルキャッシュ・トラック</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm デスクトップ・アプリ</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>ありがとう、&lt;strong&gt;%1&lt;/strong&gt; さん。現在アカウントは接続されています！</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>インポート中…</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>インポート完了！</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Last.fm で友だち検索</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;まだ Last.fm 上に友だちはいません。&lt;/h3&gt;&lt;p&gt;友だち検索機能で素早く簡単に Facebook の友だちを探して Last.fm 上でメールしてみましょう。&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>ユーザー名もしくは本名で友だち検索</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>友だちを再読込</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>再読込中…</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>%1 さんのライブラリ・ラジオ</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>男性</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>%1 からただ今 Scrobble 中</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>女性</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>ただ今 Scrobble 中</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>中性</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>友だちを検索</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>友だちをブラウズ</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>言語:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>メニューバーにアプリケーションアイコンを表示</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>メディアプレイヤーでアプリケーションを起動</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Dock アイコン表示</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>デスクトップ通知を表示</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>クラッシュレポートを Last.fm に送信</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>自動的にアップデートをチェック</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>メディアキーを有効にする</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>システム言語</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>今すぐ再起動しますか？</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>変更を有効にするにはアプリケーションの再起動が必要です。今すぐ再起動しますか？</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>ベータ版にアップデート - 注：勇敢な人限定！</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod データベースを開くことができませんでした。</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;%1 のような iOS Scrobble アプリを使用すると、二重 Scrobble の可能性があります。Scrobble アプリは一つだけ有効にしてご利用ください。&lt;/p&gt;&lt;p&gt;iTunes Match では再生回数は同期されますが、複数のデバイスにわたる最新の再生回数は同期されません。このため Scrobble が重複し、不正確な回数につながる場合があります。さしあたり iTunes Match ユーザーの皆さんには、デスクトップ・デバイス上での Scrobble を無効にし、%1 のような iOS Scrobble アプリで iPhones/iPods を Scrobble することをおすすめします。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>設定は変更されていません</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>この設定変更のために iTunes を閉じませんでした</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>デバイスでの Scrobble を有効にする</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>デバイス Scrobble を確認する</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>注意：</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>ライセンス</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>終わりましたか？</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>このアプリ承認後、OK をクリック</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm はまずあなたの許可が必要です！</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>このアプリケーション使用には、Last.fm マイ プロフィールに接続する許可が必要です。OK をクリックして Last.fm ウェブサイトにアクセス後、実行してください。</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;すでに Last.fm ユーザーですか？アカウントを Last.fm デスクトップ・アプリに接続すると、再生した音楽でマイ プロフィールが更新されます。&lt;/p&gt;&lt;p&gt;アカウントをお持ちでな場合、今すぐ無料で登録できます。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Last.fm アカウントと接続してスタート</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>マイ アカウントを接続</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>登録</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>プロキシですか？</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>メディア・プレイヤー プラグインのアップデートがあります。今すぐインストールしますか？</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>プラグイン　インストールエラー</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;プラグイン更新時にエラーが発生しました。&lt;/p&gt;&lt;p&gt;後でもう一度試してください。&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>プラグインインストール完了！</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;プラグインのインストール完了です。&lt;/p&gt;&lt;p&gt;お使いのメディア・プレイヤーで Scrobble する準備ができました。&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>マイ プラグインはインストールされませんでした</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>後でファイルメニューからインストール可能です</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>ファイル</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>プラグインのインストール</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>中止(&amp;Q)</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>表示</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Last.fm マイ プロフィール</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobble</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>更新</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>コントロール</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>アカウント</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>ツール</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>更新のチェック</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>オプション</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>ウインドウ</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>最小化</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>拡大</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>すべて前面に移動</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>ヘルプ</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>バージョン情報</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>フォーラム</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>サイトツアー</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>ライセンス表示</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>診断</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>デバイスから &lt;a href=&quot;tracks&quot;&gt;%n 回&lt;/a&gt; Scrobble</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Scrobble に戻る</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>人気のタグ：</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>マイ タグ：</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>似てるアーティスト</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>by %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>from %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1 ラジオを再生</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>再生回数</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>マイ ライブラリでの再生回数</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>リスナー</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>With %1 など</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>With %1, %2 など</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>編集日 %1 | %2 編集</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>ダウンロード</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>%1 で検索</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>%1 %2 で購入</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>%1 を再生しているのでオススメ。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>%1, %2 を再生しているのでオススメ。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>%1, %2, %3 を再生しているのオススメ。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>%1, %2, %3, %4 を再生しているのオススメ。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>%1, %2, %3, %4, %5 を再生しているのでオススメ。</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>%1 さんのライブラリから。</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>%1 ＆ %2 さんのライブラリから。</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 回</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>%1, %2, ＆ %3 さんのライブラリから。</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>%1 %2 と %3 %4 を再生しました。</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>%1, %2, %3, ＆ %4 さんのライブラリから。</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>%1 %2 は再生しましたが、このトラックは再生していません。</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>%1, %2, %3, %4, ＆ %5 さんのライブラリから。</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>%1 の初回再生です。</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>こんにちは！</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>ラジオステーションを開始</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>iTunes を開く</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Music を開く</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Windows Media Player を開く</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Winamp を開く</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Foobar を開く</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;お使いの音楽プレイヤーから Scrobble&lt;/h2&gt;&lt;p&gt;メディアプレイヤーで音楽再生をスタートしましょう。｢ただ今再生中｣タブで再生トラックの詳細情報をチェックできます。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>こんにちは %1 さん！</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>ラジオステーション</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>%1 を再生</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>マルチライブラリ・ラジオ</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>%1 を続けて再生</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>%1 &amp; %2 ライブラリ・ラジオを再生</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>%1 &amp; %2 ライブラリ・ラジオを続けて再生</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>禁止</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>再生</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>スキップ</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>一時停止</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>再開</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Love じゃない</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>チューニング</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>ラジオステーション</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>再生：</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobble 中：</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 回再生</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm はメディアプレイヤーをインポートしました。\n\n OK をクリックして次に進んでください。</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Last.fm ライブラリ・インポート</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>本当にインポートをキャンセルしますか?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm はメディアプレイヤーで再生されたトラックを検出できませんでした。\n\n OK をクリックして次に進んでください。</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm は現在ご利用のメディアライブラリをインポートしています...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Winamp はどこ？</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Windows Media Player はどこ？</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>メディアライブラリ・インポート完了</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm は再生履歴をサーバーに送信しました。\n新しいトラック情報は数分でプロフィールページに更新されます。</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>ライブラリ・インポート失敗</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Sorry! Last.fm は再生履歴をインポートできませんでした。Scrobble 済みのトラック数が多すぎるようです。再生履歴は、新しいプロフィールページにのみインポート可能です。</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;プラグインをインストールするには、お使いの OS で表示される手順に従ってください。&lt;/p&gt;&lt;p&gt;コンピュータにプラグインがインストールされたら、&lt;strong&gt;続行&lt;/strong&gt;をクリックしてください。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>現在プラグインをインストール中です。</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>マイ プラグインはインストールされませんでした</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>後でファイルメニューからインストール可能です</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;再生する音楽の Scrobble をお使いのメディアプレイヤーで可能にするには、Last.fm の特別なプラグインが必要です。&lt;/p&gt;&lt;p&gt;Scrobble に利用したいメディアプレイヤーを選択し、&lt;strong&gt;プラグインをインストール&lt;/strong&gt;をクリックしてください&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>（新バージョン）</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>（プラグインはインストール済み。クリックして再インストール）</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>次に Last.fm プラグインをインストールし、再生音楽の Scrobble を可能にします。</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>プラグインをインストール</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>スキップ &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>全般</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>アカウント</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobble 中</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>デバイス</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>拡張</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 ラジオ</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 回再生</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>今週の Top アーティスト</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>総合 Top アーティスト</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobble</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Love トラック</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 アーティスト</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 トラック</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>マイ ライブラリに %1 があります。1日平均 %2 再生。</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>%1 から Scrobble </numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>プロキシ設定</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>ホスト：</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>ユーザー名：</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>ポート：</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>パスワード：</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>不明なメディアプレイヤー</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>iPod はどこに取り付けましたか?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>アーティスト名もしくはタグ名を入力して再生ボタンをプッシュ</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>再生</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>%1, %2, %3 もしくは %4 を試してみませんか？</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>次を再生</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>ラジオステーション</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>ラジオ再生には有料メンバー登録が必要です。</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>最終ステーション</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>ラジオステーション</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>パーソナル・ステーション</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>マイ ライブラリ・ラジオ</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>知ってる ＆ Love な音楽</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>マイ Mix ラジオ</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>マイ ライブラリ +  新しい音楽</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>おすすめ マイ ラジオ</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>有料メンバー登録してラジオを再生</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Last.fm から新しい音楽</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>このアプリでラジオ再生するには Last.fm 有料メンバー登録が必要です。今すぐメンバー登録してラジオ再生をスタートしましょう。その他素敵な特典もご利用ください。</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>ネットワーク・ステーション</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Last.fm に有料メンバー登録</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>www.last.fm で無料再生</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>マイ 友だちラジオ</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>友だちの好きな音楽</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>マイ ご近所さんラジオ</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>あなたに似たリスナーからの音楽</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>最近のステーション</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>再生中</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>有料メンバー登録してラジオ再生 月額わずか %1</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>デバイス Scrobble</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>これらのトラックを再生したようです。Scrobble しますか？</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>デバイスを自動的に Scrobble</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>選択を切り替える</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>デバイスから %n 回 Scrobble</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Love トラック</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>タグを追加</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>タグ</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>シェア</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Last.fm でシェア</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Twitter でシェア</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Facebook でシェア</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>購入</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Love じゃないトラック</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobble メディア</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>トラック%</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Scrobble を有効</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...または4分で（いずれか早い方）</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>ポッドキャストを Scrobble</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>マイ トラックの Last.fm フィンガープリントを許可</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>選択したディレクトリは Scrobble できません</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Last.fm でもっと Scrobble</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>再読込中…</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Scrobble をリフレッシュ</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>アーティスト</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>タイトル</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>アルバム</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>再生</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>最終再生</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>このトラックは30秒以内です</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>アーティスト名は不明です</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>無効なトラック名</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>無効なアーティスト</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>タイムスタンプがありません</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>このトラックはずっと先のものです</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>このトラックは2週間以上前に再生されました</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>まだ Last.fm で音楽を Scrobble していません。</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>お使いのメディアプレイヤーで音楽再生を開始するかラジオステーションをスタート：</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>友だちとシェア</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>シェア with:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>メッセージ（オプション）</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>最近のマイ アクティビティに組み込む</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>トラック by %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>トラック by %1, %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>%1 をチェック</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>ただ今再生中</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobble</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>プロフィール</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>友だち</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>ラジオ</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>次項</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>前項</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>ラジオを開始できませんでした：%1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>&quot;%1&quot; の検索結果はありません</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobble オフ</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>オンライン</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>オフライン</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>タグ</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>何かを選択してタグ付け：</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>トラック</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>アーティスト</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>アルバム</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>アイコン</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>タグを追加：</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>トラック by %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>トラック by %1, %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>上にタグを入力するか以下から選択</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>人気順にソート</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>アルファベット順にソート</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>このタグの Last.fm ページを開く</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;スタート準備ができました！&lt;strong&gt;終了&lt;/strong&gt;をクリックして探索を開始してください。&lt;/p&gt;&lt;p&gt;再生履歴もインポート完了、Last.fm マイ プロフィールに追加しました。&lt;/p&gt;&lt;p&gt;Last.fm デスクトップ・アプリをインストールしていただきありがとうございます。Last.fm を楽しんでご利用ください！&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>これで終了、いよいよスタートです！</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>終了</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;スクリーン上の赤い矢印はシステムトレイでの Last.fm デスクトップ・アプリ位置を指しています。&lt;/p&gt;&lt;p&gt;アイコンをクリックすると、ラジオ再生コントロールへの素早いアクセス、トラックのシェア＆タグ付け、設定の編集や Last.fm マイ プロフィールへのアクセスができます。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>メニューバーに Last.fm デスクトップ・アプリ</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>システムトレイに Last.fm デスクトップ・アプリ</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;バイオ、再生統計データ、写真や似てるアーティスト、さらにリスナーが分類に利用するタグなど、再生中の音楽について詳細情報を見つけてください。&lt;/p&gt;&lt;p&gt;&lt;strong&gt;ただ今再生中&lt;/strong&gt;タブをチェックするか &lt;strong&gt;Scrobble&lt;/strong&gt; タブ上のトラックをクリックするだけで詳細をご覧いただけます。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>大好きなアーティスト情報の発見</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>サイトツアーをスキップ&gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>ノンストップラジオ、カスタムラジオを再生</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;聴きたい音楽に基づいたカスタムラジオを再生するには、Last.fm デスクトップ・アプリをお使いください。&lt;/p&gt;&lt;p&gt;アーティストやタグベースのステーションからあなたの音楽テイストにピッタリの最新おすすめ情報まで、Last.fm のステーションはすべて再生ごとに異なる音楽をお届けします。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>有料メンバー登録してノンストップラジオ、カスタムラジオを再生</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;聴きたい音楽に基づいたカスタムラジオを再生するには、Last.fm に有料メンバー登録して Last.fm デスクトップ・アプリをお使いください。&lt;/p&gt;&lt;p&gt;アーティストやタグベースのステーションからあなたの音楽テイストにピッタリの最新おすすめ情報まで、Last.fm ステーションはすべて再生ごとに異なる音楽をお届けします。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>有料メンバー登録</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>サイトツアーをスキップ&gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;デスクトップ・クライアントは、再生している音楽で Last.fm マイ プロフィールをひそかにアップデートしながら、バックグラウンドで動作し、おすすめ音楽やライブの内部情報などの入手に活用できます。&lt;/p&gt;&lt;p&gt;また Last.fm デスクトップ・アプリも再生中のアーティスト詳細情報チェックやカスタムラジオ再生にご利用いただけます。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>ようこそ Last.fm デスクトップ・アプリへ！</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>続行</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 戻る</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>サイトツアーをスキップ&gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>トラック</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>アルバム</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>アーティスト</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>タグ</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>共有</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>購入</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>この Scrobble をマイ プロフィールから削除する</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1 ラジオを再生</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>%1 ラジオを続けて再生</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 ラジオ</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>キャッシュ済み</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>エラー：%1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Last.fm でシェア</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Twitter でシェア</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Facebook でシェア</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>ただ今再生中</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>ダウンロード</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>%1 で検索</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>%1 %2 で購入</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>ユーザーアカウントに接続済み</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>新しいユーザーアカウントを追加</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>ユーザーエラーを追加</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>このユーザーはすでに追加済みです。</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>%1 削除中</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>このユーザーを本当に削除しますか？ユーザー設定はすべて失われ、今後 Scrobble するには再度認証が必要になります。</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>有料メンバー登録</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>削除</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>（現在ログイン中）</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>アカウント</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Scrobbler 表示</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Love</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>再生</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>スキップ</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>タグ</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>シェア</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>禁止</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>ミュート</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>iPod を Scrobble...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Last.fm プロフィールにアクセス</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Scrobble を有効</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>%1 を終了</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>from %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>このステーションのスキップ制限に達しました。%n 分後にもう一度スキップしてください。</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>このステーション上でのスキップはあと %n 回です。</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>認証が必要です</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;ユーザーアカウント &lt;strong&gt;%1&lt;/strong&gt; は Last.fm ではもはや認証されません。&lt;/p&gt;&lt;p&gt;OK をクリックしして設定手順を開始し、このアカウントを再度認証してください。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>本当に %1 を終了しますか？</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 は終了しようとしています。続行すると再生したトラックは Scrobble されません。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>ユーザー変更</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 で Scrobbler および Last.fm ラジオにログインします。今後すべての音楽はこのアカウントに Scrobble されます。続行しますか？</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>続行するには以下のアプリを閉じてください。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>プラグイン インストール・エラー</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;プラグイン更新中にエラーが発生しました。&lt;/p&gt;&lt;p&gt;後でもう一度試してください。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>プラグイン インストール完了！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;%1 プラグインのインストール完了です。&lt;/p&gt;&lt;p&gt;%1 で Scrobble する準備ができました。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>%1 プラグインはインストールされていません。</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>%1 を閉じなかったためプラグインはインストールされませんでした。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>プラグイン更新には iTunes を閉じてください！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;お使いの iTunes プラグイン (%2) は当該アプリ (%1) の本バージョンに対応するものと異なります。.&lt;/p&gt;&lt;p&gt;iTunes を閉じて今すぐアップデートしてください。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>インストールされていません</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>プラグインはインストールされていません</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>古いプラグインの削除中にエラーが発生しました</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes プラグイン インストール完了！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;iTunes プラグインのインストール完了です。&lt;/p&gt;&lt;p&gt;お使いのメディア・プレイヤーで Scrobble する準備ができました。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>新しいプラグインを所定の位置にコピー中、エラーが発生しました</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>iTunes を閉じませんでした</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>時間表示エラー</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n 分前</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n 時間前</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>ネットワークエラー発生：%1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>このアプリケーションは許可されていません</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>認証エラー</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>スタイルシートを更新</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>次回以降確認しない</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>自動検出</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>プロキシなし</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_pl.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"pl\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Informacje</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (utworzone za pomocą Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Kliknij przycisk &lt;strong&gt;Tak, pozwól na dostęp&lt;/strong&gt; w swojej przeglądarce, aby połączyć swoje konto Last.fm z aplikacją Last.fm.&lt;/p&gt;&lt;p&gt;Jeśli ich nie połączyłeś, ponieważ zamknąłeś okno przeglądarki lub kliknąłeś anuluj, spróbuj ponownie.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Czekamy, aż połączysz się z Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wstecz</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Kontynuuj</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Spróbuj ponownie</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Jeśli twoja przeglądarka nie otwarła się, skopiuj i wklej poniższy link do paska adresu.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Skróty klawiszowe</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Pokaż/Ukryj Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proksy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Włącz SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Rozmiar cache:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Subskrybent</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderator</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Pracownicy</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Alumna</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Alumnus</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>W trasie</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Aby uzyskać najlepsze, możliwe propozycje w oparciu o swój muzyczny gust zalecamy importowanie swojej historii odsłuchanych utworów z odtwarzacza multimediów.&lt;/p&gt;&lt;p&gt;Wybierz preferowany odtwarzacz i kliknij &lt;strong&gt;Rozpocznij importowanie&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Twoje wtyczki nie zostały zainstalowane</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Możesz zainstalować je później przez menu Plik</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Teraz importujmy twoją historię odsłuchanych utworów</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Rozpocznij importowanie</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Pomiń &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Nie martw się, proces wysyłania danych nie powinien trwać dłużej niż kilka minut, w zależności od wielkości twojej biblioteki muzycznej.&lt;/p&gt;&lt;p&gt;W czasie, gdy twoja historia będzie przetwarzana i porządkowana w profilu Last.fm, może chciałbyś odbyć krótką wycieczkę po aplikacji Last.fm. Kliknij &lt;strong&gt;Kontynuuj&lt;/strong&gt;, aby rozpocząć zwiedzanie.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Zamknij aplikację</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Włączone scrobblowanie urządzenia - niekompatybilna wtyczka iTunes - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>zaktualizuj</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbluj iPoda</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Czy chcesz powiązać urządzenie %1 ze swoim kontem użytkownika audioscrobblera?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Urządzenie zostało pomyślne połączone z twoim kontem użytkownika. Od teraz możesz scrobblować utwory, których słuchasz na tym urządzeniu.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 utworów przescrobblowanych.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Brak utworów do przescrobblowania od ostatniej synchronizacji.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Nie udało się otworzyć bazy danych iPoda.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Wystąpił nieznany błąd w czasie próby uzyskania dostępu do bazy danych iPoda.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostyka</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobblowanie</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>To ukryta niespodzianka!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Wykonawca</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Utwór</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingerprinting</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Ostatnio fingerprintowane utwory.</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Scrobblowanie iPoda</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes automatycznie zarządza moim iPodem</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Zarządzam ręcznie moim iPodem</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Scrobbluj iPoda</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Logi</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Zamknij</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n lokalnie zbuforowany utwór</numerusform>\n            <numerusform>%n lokalnie zbuforowane utwory</numerusform>\n            <numerusform>%n lokalnie zbuforowanych utworów</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Aplikacja Last.fm</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Dziękujemy &lt;strong&gt;%1&lt;/strong&gt;, twoje konto jest teraz podłączone!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importowanie...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Import zakończony!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Znajdź znajomych w Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Nie masz jeszcze żadnych znajomych w Last.fm.&lt;/h3&gt;&lt;p&gt;Znajdź swoich znajomych z Facebooka oraz z listy kontaktów mailowych w Last.fm wykorzystując wyszukiwarkę znajomych.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Szukaj znajomego podając nazwę użytkownika lub nazwisko</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Odśwież znajomych</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Odświeżanie...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Radio biblioteki %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Mężczyzna</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Teraz scrobblowane z %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Kobieta</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Teraz scrobblowane</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Nieokreślona</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Wyszukaj swoich znajomych</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Przeglądaj znajomych</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Język:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Pokaż ikonę aplikacji w pasku</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Uruchom aplikację wraz z odtwarzaczem multimediów</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Pokaż ikonę dokowania</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Pokaż powiadomienia na pulpicie</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Wyślij raport o błędzie do Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Sprawdź automatycznie dostępność aktualizacji</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Aktywuj klucz dla mediów</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Język systemu</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Uruchomić ponownie teraz?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Wymagane jest ponowne uruchomienia aplikacji, w celu wprowadzenia zmian. Czy chcesz uruchomić ponownie teraz?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Aktualizuj do wersji Beta - Ostrzeżenie: tylko dla odważnych!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Nie udało się otworzyć bazy danych iPoda.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Korzystanie z aplikacji scrobblującej dla iOS, na przykład %1, może powodować powstawanie podwójnych scrobbli. Włącz scrobblowanie tylko w jednej z nich. &lt;/p&gt;&lt;p&gt;iTunes Match synchronizuje ilość odtworzeń, ale nie ilość odsłuchań pomiędzy wieloma urządzeniami. Powoduje to powstawanie podwójnych scrobbli o nieprawidłowych datach. Na chwilę obecną, zalecamy użytkownikom iTunes Match wyłączenie scrobblowania na urządzeniach stacjonarnych, a na iPhonach/iPodach scrobblowanie za pomocą aplikacji dla iOS, na przykład %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Nie zmieniono ustawienia</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Nie zamknięto iTunes, aby zmienić to ustawienia</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Włącz scrobblowanie urządzenia</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Potwierdź scrobble urządzenia</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Pamiętaj</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licencje</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>To już wszystko?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Po zatwierdzeniu aplikacji, kliknij OK.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm wymaga najpierw twojej zgody!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Aplikacja wymaga twojej zgody na podłączenie do twojego konta profilu Last.fm. Kliknij OK, aby przejść na stronę Last.fm i wyrazić zgodę.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Jesteś już użytkownikiem Last.fm? Powiąż swoje konto z aplikacją Last.fm, a twój profil będzie automatycznie aktualizowany o muzykę, której słuchasz.&lt;/p&gt;&lt;p&gt;Jeśli nie masz jeszcze konta, możesz je utworzyć teraz za darmo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Zacznij od powiązania twojego konta Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Powiąż swoje konto</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Zarejestruj się</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proksy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Pojawiły się aktualizacje wtyczek do twoich odtwarzaczy. Czy chcesz je teraz zainstalować?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Błąd instalacji wtyczki</numerusform>\n            <numerusform>Błędy instalacji wtyczki</numerusform>\n            <numerusform>Błędy instalacji wtyczki</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Wystąpił błąd w czasie aktualizacji wtyczki.&lt;/p&gt;&lt;p&gt;Spróbuj ponownie później.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Wystąpił błąd w czasie aktualizacji wtyczek.&lt;/p&gt;&lt;p&gt;Spróbuj ponownie później.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Wystąpił błąd w czasie aktualizacji wtyczek.&lt;/p&gt;&lt;p&gt;Spróbuj ponownie później.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Wtyczka zainstalowana!</numerusform>\n            <numerusform>Wtyczki zainstalowane!</numerusform>\n            <numerusform>Wtyczki zainstalowane!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Twoja wtyczka została zainstalowana.&lt;/p&gt;&lt;p&gt;Jesteś gotowy do scrobblowania za pomocą odtwarzacza multimediów&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Twoje wtyczki zostały zainstalowane.&lt;/p&gt;&lt;p&gt;Jesteś gotowy do scrobblowania za pomocą odtwarzacza multimediów&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Twoje wtyczki zostały zainstalowane.&lt;/p&gt;&lt;p&gt;Jesteś gotowy do scrobblowania za pomocą odtwarzacza multimediów&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Twoje wtyczki nie zostały zainstalowane</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Możesz zainstalować je później przez menu Plik</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Plik</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Zainstaluj wtyczki</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Wyjdź</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Widok</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Mój profil Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobble</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Odśwież</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Opcje</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Konto</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Narzędzia</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Sprawdź czy są dostępne aktualizacje</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Opcje</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Okno</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimalizuj</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zbliż</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Pokaż wszystko na wierzchu</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Pomoc</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>O</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Fora</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Przewodnik</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Pokaż licencje</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostyka</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n odtworzenie&lt;/a&gt; zostało przescrobblowane na tym urządzeniu</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n odtworzenia&lt;/a&gt; zostały przescrobblowane na tym urządzeniu</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n odtworzeń&lt;/a&gt; zostało przescrobblowanych na tym urządzeniu</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Cofnij do Scrobbli</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Popularne tagi:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Twoje tagi:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Podobni wykonawcy</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>przez %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>z %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Odtwórz radio %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Odtworzenie</numerusform>\n            <numerusform>Odtworzenia</numerusform>\n            <numerusform>Odtworzeń</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Odtworzenie w twojej bibliotece</numerusform>\n            <numerusform>Odtworzenia w twojej bibliotece</numerusform>\n            <numerusform>Odtworzeń w twojej bibliotece</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Słuchacz</numerusform>\n            <numerusform>Słuchaczy</numerusform>\n            <numerusform>Słuchaczy</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Z %1 i innymi.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Z %1, %2 i innymi.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Edytowane %1 | %2 Edytuj</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Pobrań</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Wyszukaj w %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Kup w %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Płyta CD</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Polecane ponieważ słuchałeś %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Polecane ponieważ słuchałeś %1 oraz %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Polecane ponieważ słuchałeś %1, %2 oraz %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Polecane ponieważ słuchałeś %1, %2, %3 oraz %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Polecane ponieważ słuchałeś %1, %2, %3, %4 oraz %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Z biblioteki %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Z bibliotek %1 oraz %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 raz</numerusform>\n            <numerusform>%L1 razy</numerusform>\n            <numerusform>%L1 razy</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Z bibliotek %1, %2 oraz %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Słuchałeś %1 %2 i %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Z bibliotek %1, %2, %3 oraz %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Słuchałeś %1 %2, ale nie tego utworu.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Z bibliotek %1, %2, %3, %4 oraz %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Po raz pierwszy słuchasz %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Witaj</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Uruchom stację radiową</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Uruchom iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Uruchom Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Uruchom Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Uruchom Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Uruchom Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Scrobbluj ze swojego odtwarzacza muzyki&lt;/h2&gt;&lt;p&gt;Rozpocznij słuchanie swojej muzyki w odtwarzaczu. Więcej informacji o utworach znajdziesz w zakładce Odtwarzane.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Witaj %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Stacja radiowa</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Odtwórz %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Radio wielu bibliotek</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Przestaw na %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Odtwórz radio biblioteki %1 oraz %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Przestaw na radio biblioteki %1 oraz %2</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Polub</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Zablokuj</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Odtwórz</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Pomiń</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pauza</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Wznów</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Nie lubię</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Dostrajanie</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Stacja radiowa</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Słucha</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Scrobbluje z</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 odtworzenie</numerusform>\n            <numerusform>%L1 odtworzenia</numerusform>\n            <numerusform>%L1 odtworzeń</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm zaimportował twoją bibliotekę utworów.\n\n  Kliknij OK, aby kontynuować.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Import biblioteki Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Czy na pewno chcesz anulować importowanie?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm nie mógł znaleźć żadnych odtworzonych utworów w twojej bibliotece.\n\n Kliknij OK, aby kontynuować.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm importuje twoją, bieżącą bibliotekę mediów...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Gdzie jest Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Gdzie jest Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Importowanie biblioteki zakończone</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm właśnie wysłał historię twoich odsłuchanych utworów na serwer.\nTwój profil zostanie zaktualizowany o nowe utwory w ciągu kilku minut.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Import biblioteki nie powiódł się</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Last.fm nie był w stanie zaimportować twojej historii odsłuchanych utworów. Może być to spowodowane przescrobblowaniem zbyt dużej liczby utworów. Historia odsłuchanych utworów może być importowana tylko do nowych profili.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Zastosuj się do wskazówek pojawiających się w twoim systemie operacyjnym, aby zainstalować wtyczki.&lt;/p&gt;&lt;p&gt;Po zainstalowaniu wtyczek na komputerze, kliknij &lt;strong&gt;Kontynuuj&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Trwa instalacja twoich wtyczek</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Twoje wtyczki nie zostały zainstalowane</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Możesz zainstalować je później przez menu Plik</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Twoje odtwarzacze multimediów wymagają specjalnej wtyczki Last.fm, aby móc scrobblować muzykę, której słuchasz.&lt;/p&gt;&lt;p&gt;Wybierz odtwarzacz, z którego chciałbyś scrobblować muzykę i kliknij &lt;strong&gt;Zainstaluj wtyczki&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(nowsza wersja)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Wtyczka zainstalowana, zaznacz, aby przeinstalować)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Kolejny krok, zainstaluj wtyczki Last.fm, aby móc scrobblować muzykę, której słuchasz.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Zainstaluj wtyczki</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Kontynuuj</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Pomiń &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Ogólne</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Konta</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobblowanie</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Urządzenia</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Zaawansowane</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 odtworzenie</numerusform>\n            <numerusform>%L1 odtworzenia</numerusform>\n            <numerusform>%L1 odtworzeń</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Ulubieni wykonawcy tygodnia</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Ulubieni wykonawcy</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobble</numerusform>\n            <numerusform>Scrobble</numerusform>\n            <numerusform>Scrobbli</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Ulubiony utwór</numerusform>\n            <numerusform>Ulubione utwory</numerusform>\n            <numerusform>Ulubionych utworów</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 wykonawca</numerusform>\n            <numerusform>%L1 wykonawców</numerusform>\n            <numerusform>%L1 wykonawców</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 utwór</numerusform>\n            <numerusform>%L1 utwory</numerusform>\n            <numerusform>%L1 utworów</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Masz %1 w swojej bibliotece i słuchasz średnio %2 na dzień.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobble od %1</numerusform>\n            <numerusform>Scrobble od %1</numerusform>\n            <numerusform>Scrobbli od %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Ustawienia proksy</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Nazwa użytkownika:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Hasło:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>nieznany odtwarzacz multimediów</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Gdzie jest podłączony Twój iPod?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Wpisz wykonawcę, tag i naciśnij Odtwórz</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Odtwórz</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Być może warto posłuchać również %1, %2, %3 lub %4.</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Odtwórz następny</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Stacja radiowa</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Musisz być subskrybentem, aby słuchać radia</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Ostatnia stacja</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Stacja radiowa</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Stacje osobiste</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Radio mojej biblioteki</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Muzyka, którą znasz i lubisz</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Moje radio mix</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Twoja biblioteka wraz z nową muzyką</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Moje polecane radio</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Subskrybuj, aby słuchać radia.</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Nowa muzyka z Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Musisz być subskrybentem Last.fm, aby słuchać radia w tej aplikacji.\nSubskrybuj teraz, aby słuchać i korzystać z dodatkowych możliwości!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Stacje sieciowe</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Subskrybuj Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Słuchaj za darmo na www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Radio moich znajomych</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Muzyka, którą lubią twoi znajomi</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Radio moich sąsiadów</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Muzyka słuchaczy, których lubisz</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Ostatnio odtwarzane stacje</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Odtwarzane</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Subskrybuj, aby słuchać radia, tylko za %1 na miesiąc</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Scrobble urządzenia</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Wygląda na to, że odtwarzałeś już te utwory. Czy chcesz je przescrobblować?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Scrobbluj urządzenia automatycznie</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Przełącz wybrane</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n odtworzenie zostało przescrobblowane na tym urządzeniu</numerusform>\n            <numerusform>%n odtworzenia zostały przescrobblowane na tym urządzeniu</numerusform>\n            <numerusform>%n odtworzeń zostało przescrobblowanych na tym urządzeniu</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Ulubiony utwór</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Dodaj tagi</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Polub</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Udostępnij</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Udostępnij w Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Udostępnij na Twitterze</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Udostępnij na Facebooku</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Kup</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Usuń z ulubionych</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Scrobbluj na</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>procent utworu</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Włącz scrobblowanie</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...lub po 4 minutach (zależnie co nastąpi pierwsze)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Scrobbluj podcasty</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Pozwól Last.fm na fingerprinting moich utworów</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Zaznaczone katalogi nie będą scrobblowane</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Więcej scrobbli w Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Odświeżanie...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Odśwież scrobble</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Wykonawca</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Tytuł</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Odtworzeń</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Ostatnio odtwarzany</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Ulubiony</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Utwór ma mniej niż 30 sekund</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Brakuje nazwy wykonawcy</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Nieprawidłowa nazwa utworu</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Nieprawidłowy wykonawca</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Brak oznaczenia czasowego</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Ten utwór jest z przyszłości</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Utwór był odtwarzany ponad dwa tygodnie temu</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Nie scrobblowałeś jeszcze żadnej muzyki w Last.fm</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Zacznij słuchać muzyki w swoim odtwarzaczu lub uruchom stację radiową:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Poleć znajomym</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Z:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Wiadomość (opcjonalnie):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>dodaj do mojej ostatniej aktywności</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Utwór w wykonaniu %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Utwór w wykonaniu %1 z wydania %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Sprawdź %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Odtwarzane</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobble</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Znajomi</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Następna sekcja</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Poprzednia sekcja</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Nie można uruchomić radia: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>brak wyników dla &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Scrobblowanie jest wyłączone</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Dostępny</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Niedostępny</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Wybierz coś do otagowania:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Utwór</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Wykonawca</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>ikona</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Dodaj tagi:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Utwór w wykonaniu %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Utwór w wykonaniu %1 z wydania %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Wpisz tag powyżej\nlub wybierz z poniższych</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Sortuj wg popularności</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Sortuj alfabetycznie</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Otwórz stronę Last.fm dla tego tagu</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Teraz już możesz zacząć! Kliknij &lt;strong&gt;Zakończ&lt;/strong&gt; i rozpocznij odkrywanie aplikacji.&lt;/p&gt;&lt;p&gt;Zakończył się także import twojej historii odsłuchanych utworów, co znaczy, że dodano je do twojego profilu Last.fm.&lt;/p&gt;&lt;p&gt;Dziękujemy za instalację aplikacji Last.fm, mamy nadzieję, że ci się spodoba!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Gotowe, możesz zaczynać!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Zakończ</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Czerwona strzałka na twoim ekranie wskazuje lokalizację ikony aplikacji Last.fm w zasobniku systemowym.&lt;/p&gt;&lt;p&gt;Kliknij ikonę, aby szybko uzyskać dostęp do opcji odtwarzania, udostępniania lub tagowania utworów, edytowania swoich ustawień lub aby odwiedzić swój profil Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Aplikacja Last.fm w twoim pasku menu</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Aplikacja Last.fm w twoim zasobniku systemowym</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Dowiedz się więcej o muzyce, której słuchasz, włączając biografie, statystki odsłuchań, zdjęcia i podobnych wykonawców, jak również tagi stosowane przez innych słuchaczy opisujące to, czego słuchasz.&lt;/p&gt;&lt;p&gt;Zobacz zakładkę &lt;strong&gt;Odtwarzane&lt;/strong&gt; lub  kliknij dowolny utwór w zakładce &lt;strong&gt;Scrobble&lt;/strong&gt;, aby dowiedzieć się więcej.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Odkryj więcej informacji o wykonawcy, którego lubisz</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pomiń przewodnik &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Słuchaj non-stop spersonalizowanego radia</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Korzystaj z aplikacji Last.fm, aby słuchać spersonalizowanego radia opartego na muzyce, której chcesz słuchać.&lt;/p&gt;&lt;p&gt;Każde odtworzenie, każdej stacji radiowej Last.fm jest zupełnie inne, zaczynając od stacji opartych na wykonawcach i tagach, po zupełnie nowe propozycje dostosowane do twojego muzycznego gustu.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Subskrybuj i słuchaj non-stop spersonalizowanego radia</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Subskrybuj Last.fm, aby korzystać z aplikacji Last.fm umożliwiającej słuchanie spersonalizowanego radia opartego na muzyce, której chcesz słuchać.&lt;/p&gt;&lt;p&gt;Każde odtworzenie, każdej stacji radiowej Last.fm jest zupełnie inne, zaczynając od stacji opartych na wykonawcach i tagach, po zupełnie nowe propozycje dostosowane do twojego muzycznego gustu.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Subskrybuj</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wróć</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pomiń przewodnik &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Aplikacja działa w tle, bezgłośnie aktualizując twój profil Last.fm muzyką, której słuchasz, dzięki czemu możesz otrzymać propozycje muzyczne, informacje o występach i wiele więcej. &lt;/p&gt;&lt;p&gt;Możesz również wykorzystać aplikację Last.fm, do odszukiwania informacji o wykonawcach, których słuchasz oraz do odtwarzania spersonalizowanego radia.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Witaj w aplikacji Last.fm</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Dalej</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Wstecz</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pomiń przewodnik &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Utwór</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Wykonawca</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Polub</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Poleć</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Kup</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Usuń ten scrobble z profilu</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Odtwórz radio %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Przestaw na radio %1</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Radio %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Buforowane</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Błąd: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Poleć w Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Poleć na Twitterze</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Poleć na Facebooku</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Teraz słucha</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Pobrań</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Wyszukaj w %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Kup w %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Nośnik</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Powiązane konta użytkownika:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Dodaj nowe konto użytkownika</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Błąd dodawania użytkownika</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Ten użytkownik został już dodany.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Usuwanie %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Czy na pewno chcesz usunąć tego użytkownika? Wszystkie ustawienia użytkownika zostaną usunięte i będziesz musiał ponownie autoryzować konto, aby móc scrobblować.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Subskrybuj</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Usuń</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(aktualnie zalogowany)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Konta</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Pokaż scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Polub</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Odtwórz</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Pomiń</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Poleć</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Zablokuj</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Wycisz</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Scrobbluj iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Odwiedź profil Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Włącz scrobblowanie</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Wyłącz %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>z %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Osiągnąłeś limit pominięć dla tej stacji. Będziesz mógł pominąć ponownie za %n minutę.</numerusform>\n            <numerusform>Osiągnąłeś limit pominięć dla tej stacji. Będziesz mógł pominąć ponownie za %n minuty.</numerusform>\n            <numerusform>Osiągnąłeś limit pominięć dla tej stacji. Będziesz mógł pominąć ponownie za %n minut.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Pozostało %n pominięcie dla tej stacji.</numerusform>\n            <numerusform>Pozostały %n pominięcia dla tej stacji.</numerusform>\n            <numerusform>Pozostało %n pominięć dla tej stacji.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Wymagana autoryzacja</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Konto użytkownika &lt;strong&gt;%1&lt;/strong&gt; nie posiada autoryzacji w Last.fm.&lt;/p&gt;&lt;p&gt;Kliknij OK, aby rozpocząć proces konfiguracji i ponownie autoryzować to konto.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Czy na pewno chcesz wyłączyć %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 zostanie wyłączony. Odtwarzane utwory nie będą scrobblowane, jeśli będziesz kontynuować.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Zmiana użytkownika</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 będzie zalogowany w Scrobblerze oraz radiu Last.fm. Muzyka będzie teraz scrobblowana dla tego konta. Czy na pewno chcesz kontynuować?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Zamknij następujące aplikacje, aby kontynuować.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Błąd instalacji wtyczki</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Wystąpił błąd podczas aktualizacji wtyczki.&lt;/p&gt;&lt;p&gt;Spróbuj ponownie później.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Wtyczka zainstalowana!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Wtyczka dla %1 została zainstalowana.&lt;/p&gt;&lt;p&gt;Jesteś gotowy na scrobblowanie z %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Wtyczka dla %1 nie została zainstalowana</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Nie zamknięto %1, w wyniku czego nie zainstalowano wtyczki.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Zamknij iTunes, aby zaktualizować wtyczkę!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Twoja wtyczka iTunes (%2) jest inna niż dostarczona z tą wersją aplikacji (%1).&lt;/p&gt;&lt;p&gt;Zamknij iTunes, aby aktualizować teraz.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>nie zainstalowana</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Twoja wtyczka nie została zainstalowana</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Wystąpił błąd w czasie usuwania starej wtyczki</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Wtyczka iTunes została zainstalowana!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Twoja wtyczka iTunes została zainstalowana.&lt;/p&gt;&lt;p&gt;Można scrobblować na tym urządzeniu.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Wystąpił błąd w czasie kopiowania nowej wtyczki do jej lokalizacji</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Nie zamknięto iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Nastąpiła podróż w czasie</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n minutę temu</numerusform>\n            <numerusform>%n minuty temu</numerusform>\n            <numerusform>%n minut temu</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n godzinę temu</numerusform>\n            <numerusform>%n godziny temu</numerusform>\n            <numerusform>%n godzin temu</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Wystąpił błąd sieci: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Nie uwierzytelniono tej aplikacji</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Błąd autoryzacji</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Odśwież arkusz</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Nie pytaj ponownie</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Wykryj automatycznie</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Brak proksy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_pt.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"pt\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Sobre</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (criado no Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Clique no botão &lt;strong&gt;Sim, permitir acesso&lt;/strong&gt; no seu navegador para conectar sua conta Last.fm ao Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;Caso não tenha se conectado porque fechou a janela ou clicou em Cancelar, tente novamente.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Estamos esperando você conectar-se à Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Tentar novamente</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Se o navegador não abrir, copie e cole o link abaixo na barra de endereços.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Atalhos de teclado:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Mostrar/Ocultar Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Habilitar SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Tamanho do cache:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Assinante</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderador</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Equipe</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Ex-equipe</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Ex-equipe</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>Em tour</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Para obter as melhores recomendações possíveis com base no seu gosto musical, sugerimos que você importe o histórico de músicas do seu media player.&lt;/p&gt;&lt;p&gt;Selecione o seu player preferido e clique em &lt;strong&gt;Iniciar importação&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Seus plug-ins ainda não foram instalados</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Você poderá instalá-los mais tarde por meio do menu Arquivo</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Agora vamos importar o seu histórico de músicas</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Iniciar importação</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Pular &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Não se preocupe, o processo de carregamento não deve levar mais do que alguns minutos, dependendo do tamanho da sua biblioteca de músicas.&lt;/p&gt;&lt;p&gt;Enquanto trabalhamos duro para adicionar o histórico de músicas ao seu perfil na Last.fm, por que você não aproveita para conferir os principais recursos do Last.fm Desktop App? Clique em &lt;strong&gt;Continuar&lt;/strong&gt; para fazer um tour.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Fechar aplicativos</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Scobbling de dispositivo desativado - plug-in do iTunes incompatível - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>Atualize</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Fazer scrobble do iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Deseja associar o dispositivo %1 à sua conta de usuário do audioscrobbler?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Dispositivo associado com sucesso à sua conta de usuário. A partir de agora você pode fazer o scrobble das faixas que ouvir neste dispositivo.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 faixas incluídas no scrobble.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Não foi incluída nenhuma faixa no scrobble desde a sua última sincronização.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Não foi possível abrir o banco de dados do iPod.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Ocorreu um erro desconhecido ao tentar acessar o banco de dados do iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnóstico</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Isto é um ovo de Páscoa!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Faixa</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingerprinting</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Faixas com fingerprints recentes</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Scrobbling do iPod</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>O iTunes gerencia automaticamente meu iPod</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Eu gerencio manualmente meu iPod</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Fazer scrobble do iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Registros</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Fechar</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n faixa no cache local</numerusform>\n            <numerusform>%n faixas no cache local</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm Desktop App</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Obrigado &lt;strong&gt;%1&lt;/strong&gt;, a sua conta está agora conectada!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importando...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Importação concluída!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Encontre seus amigos na Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Você ainda não fez nenhum amigo na Last.fm.&lt;/h3&gt;&lt;p&gt;Encontre facilmente seus contatos e amigos do Facebook na Last.fm por meio do Localizador de amigos.&lt;p /&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Pesquisar por nome de usuário ou nome real</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Atualizar amigos</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Atualizando...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Rádio da biblioteca de %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Masculino</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Fazendo scrobble - %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Feminino</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Fazendo scrobble</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neutro</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Procure seus amigos</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Procurar amigos</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Idioma:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Mostrar ícone do aplicativo na barra de menus</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Abrir o aplicativo junto com media players</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Mostrar ícone de doca</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Mostrar notificações na área de trabalho</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Enviar relatórios de falha para a Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Procurar atualizações automaticamente</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Habilitar chaves de mídia</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Idioma do sistema</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Reinicializar agora?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>É necessário reinicializar o aplicativo para que a alteração tenha efeito. Deseja reinicializar agora?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Atualização para versões beta - Aviso: somente para os corajosos!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Não foi possível abrir o banco de dados do iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;O uso de um aplicativo de scrobbling no iOS, como %1, pode resultar em scrobbles duplicados. Permita o scrobble em apenas um deles.&lt;/p&gt;\n&lt;p&gt;O iTunes Match sincroniza as contagens de execução, mas não os horários das últimas execuções entre os vários dispositivos. Isso levará a scrobbles duplicados, em horários incorretos. Por enquanto, recomendamos que os usuários do iTunes Match desativem o scrobbling de dispositivo nos dispositivos desktop e façam o scrobble de iPhones/iPods usando um aplicativo de scrobbling de iOS, como o %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>A configuração não foi alterada</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Você não fechou o iTunes para que esta configuração fosse alterada</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Habilitar scrobbling do dispositivo</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Confirmar scrobbles do dispositivo</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Observação</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licenças</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Terminamos?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Se você aprovou o aplicativo, clique em OK.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>A Last.fm precisa primeiro de sua permissão!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Este aplicativo precisa de permissão para se conectar ao seu perfil Last.fm.  Clique em OK para ir ao site da Last.fm e fazer isso.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Você já é um usuário da Last.fm? Conecte a sua conta ao Last.fm Desktop App para que o seu perfil seja atualizado com as músicas que você ouve.&lt;/p&gt;&lt;p&gt;Se não tiver uma conta, você pode se registrar gratuitamente.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Para começar, vamos conectar a sua conta Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Conecte sua conta</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Registre-se</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Existem atualizações para os plug-ins dos seus media players. Gostaria de instalá-las agora?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Erro de instalação de plug-in</numerusform>\n            <numerusform>Erro de instalação de plug-ins</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Ocorreu um erro durante a atualização do plug-in.&lt;/p&gt;&lt;p&gt;Tente novamente mais tarde.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Ocorreu um erro durante a atualização dos plug-ins.&lt;/p&gt;&lt;p&gt;Tente novamente mais tarde.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Plug-in instalado!</numerusform>\n            <numerusform>Plug-ins instalados!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;O plug-in foi instalado.&lt;/p&gt;&lt;p&gt;Você agora está pronto para fazer scrobble com o seu media player&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Os plug-ins foram instalados.&lt;/p&gt;&lt;p&gt;Você agora está pronto para fazer scrobble com os seus media players&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Seus plug-ins ainda não estão instalados</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Você poderá instalá-los mais tarde por meio do menu Arquivo</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Arquivo</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Instalar plug-ins</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Sair</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Exibir</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Meu perfil na Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Atualizar</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Controles</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Conta</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Ferramentas</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Verificar atualizações</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Opções</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Janela</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimizar</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Trazer todos para frente</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Ajuda</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Sobre</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>Perguntas frequentes</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Fóruns</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tour</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Mostrar licenças</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnóstico</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n execução&lt;/a&gt; incluída no scrobble a partir de um dispositivo</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n execuções&lt;/a&gt; incluídas no scrobble a partir de um dispositivo</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Voltar para os scrobbles</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Tags populares:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Suas tags:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Artistas similares</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>por %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Executar rádio %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Execução</numerusform>\n            <numerusform>Execuções</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Execução na sua biblioteca</numerusform>\n            <numerusform>Execuções na sua biblioteca</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Ouvinte</numerusform>\n            <numerusform>Ouvintes</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Com %1 e mais.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Com %1, %2 e mais.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Editado em %1 | %2 Editar.</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Pesquisar em %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Comprar em %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Físico</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Recomendado porque você ouve %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Recomendado porque você ouve %1 e %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Recomendado porque você ouve %1, %2 e %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Recomendado porque você ouve %1, %2, %3 e %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Recomendado porque você ouve %1, %2, %3, %4 e %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Da biblioteca de %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Das bibliotecas de %1 e %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 vez</numerusform>\n            <numerusform>%L1 vezes</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Das bibliotecas de %1, %2 e %3</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Você ouviu %1 %2 e %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Das bibliotecas de %1, %2, %3 e %4.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Você ouviu %1 %2, mas nunca esta faixa.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Das bibliotecas de %1, %2, %3, %4 e %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Esta é a primeira vez que você ouve %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Olá!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Iniciar uma estação de rádio</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Abrir o iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Abrir o Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Abrir o Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Abrir o Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Abrir o Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Faça o scrobble do seu player de músicas&lt;/h2&gt;&lt;p&gt;Comece a ouvir músicas no seu media player. Você pode ver mais informações sobre as faixas que ouve na guia Em execução.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Olá, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Uma estação de rádio</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Executar %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Rádio de várias bibliotecas</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Programar %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Executar rádio de bibliotecas %1 e %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Programar rádio de bibliotecas %1 e %2</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Adicionar como preferida</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Banir</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Executar</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Pular</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pausa</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Retomar</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Excluir das preferidas</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Sintonizando</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Uma estação de rádio</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Ouvindo</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Fazendo o scrobble de</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 execução</numerusform>\n            <numerusform>%L1 execuções</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>A Last.fm importou sua bilioteca de mídias.\n\n Clique em OK para continuar.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Importar biblioteca Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Tem certeza de que deseja cancelar a importação?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>A Last.fm não encontrou nenhuma faixa executada na sua biblioteca de mídias.\n\n Clique em OK para continuar.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>A Last.fm está importando a sua biblioteca de mídias atual...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Onde está o Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Onde está o Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Importação de biblioteca de mídias concluída</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>A Last.fm enviou seu histórico de músicas para o servidor.\nO seu perfil será atualizado com as novas faixas em alguns instantes.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Falha ao importar a biblioteca</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Desculpe, a Last.fm não conseguiu importar o seu histórico de músicas. Provavelmente isso ocorreu porque você já fez o scrobble de muitas faixas. O histórico de músicas somente poderá ser importado para perfis recém-criados.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Siga as instruções exibidas no seu sistema operacional para instalar os plug-ins.&lt;/p&gt;&lt;p&gt;Uma vez instalados os plug-ins no computador, clique em &lt;strong&gt;Continuar&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Os plug-ins estão agora sendo instalados</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Seus plug-ins ainda não estão instalados</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Você poderá instalá-los mais tarde por meio do menu Arquivo</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Os seus media players precisam de um plug-in especial da Last.fm para poder fazer o scrobble das músicas que você ouve.&lt;/p&gt;&lt;p&gt;Selecione os media players dos quais você gostaria de incluir as músicas e clique em &lt;strong&gt;Instalar plug-ins&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(versão mais recente)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Plug-in instalado, marque para reinstalar)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Em seguida, instale os plug-ins da Last.fm para poder fazer o scrobble das músicas que você ouve.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Instalar plug-ins</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Pular &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Geral</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Contas</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Scrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Dispositivos</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Avançado</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Rádio %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 execução</numerusform>\n            <numerusform>%L1 execuções</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Principais artistas desta semana</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Principais artistas - Geral</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Scrobble</numerusform>\n            <numerusform>Scrobbles</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Faixa preferida</numerusform>\n            <numerusform>Faixas preferidas</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artista</numerusform>\n            <numerusform>%L1 artistas</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 faixa</numerusform>\n            <numerusform>%L1 faixas</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Você tem %1 na sua biblioteca e, em média, ouve %2 por dia.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Scrobble desde %1</numerusform>\n            <numerusform>Scrobbles desde %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Configurações do Proxy</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Host:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Nome do usuário:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Porta:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Senha:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>Media player desconhecido</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Onde está montado seu iPod?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Digite artista ou tag e aperte Executar</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Executar</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Por que não experimenta %1, %2, %3 ou %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Executar próxima</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Uma estação de rádio</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Você precisa ser assinante para ouvir as rádios</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Última estação</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Uma estação de rádio</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Estações pessoais</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Rádio da minha biblioteca</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Músicas que você conhece e gosta</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Minha Rádio Mix</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Sua biblioteca acompanhada de novas músicas</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Minha Rádio de Recomendações</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Assine para ouvir as rádios</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Novas músicas da Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Você precisa ser assinante da Last.fm para ouvir a rádio neste aplicativo. Assine agora para começar a ouvir e aproveitar as vantagens dos outros excelentes benefícios!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Estações da sua rede</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Assine a Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Ouça gratuitamente no site www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Rádio dos meus amigos</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Músicas de que seus amigos gostam</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Rádio dos meus vizinhos</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Músicas de ouvintes como você</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Estações recentes</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Em execução</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Assine para ouvir rádios, apenas %1 por mês</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Scrobbles do dispositivo</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Aparentemente você já ouviu essas faixas. Gostaria de fazer o scrobble delas?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Fazer automaticamente o scrobble dos dispositivos</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Alternar seleção</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n execução foi incluída no scrobble de um dispositivo</numerusform>\n            <numerusform>%n execuções foram incluídas no scrobble de um dispositivo</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Adicionar faixa às preferidas</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Adicionar tags</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Adicionar às preferidas</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartilhar</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Compartilhar na Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Compartilhar no Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Compartilhar no Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Comprar</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Excluir faixa da lista de preferidas</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Fazer scrobble em</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>porcentagem da faixa</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Habilitar scrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...ou aos 4 minutos (o que ocorrer primeiro)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Fazer scrobble de podcasts</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Permitir que a Last.fm gere fingerprints das minhas faixas</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Os diretórios selecionados não serão incluídos no scrobble</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Mais scrobbles na Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Atualizando...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Atualizar scrobbles</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Título</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Execuções</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Executada pela última vez em</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Preferida</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Esta faixa tem menos de 30 segundos</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Falta o nome do artista</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Título de faixa inválido</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Artista inválido</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Não existe registro de data/hora</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Esta faixa foi executada muito no futuro</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Esta faixa foi executada há mais de duas semanas</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Você ainda não fez o scrobble de nenhuma música para a Last.fm.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Comece a ouvir músicas no seu media player ou inicie uma estação de rádio:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Compartilhe com amigos</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Com:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Mensagem (opcional):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>Incluir em minha atividade recente</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Uma faixa de %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Uma faixa de %1 do álbum %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Confira %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Em execução</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Scrobbles</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Perfil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Amigos</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Rádio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Próxima seção</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Seção anterior</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Não foi possível iniciar a rádio: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>Não existem resultados para &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>O scrobbling está desativado</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>On-line</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Off-line</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Escolha um item para receber a tag:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Faixa</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>ícone</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Adicionar tags:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Uma faixa de %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Uma faixa de %1 do álbum %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Digite uma tag acima\nou escolha abaixo</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Classificar por popularidade</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Classificar por ordem alfabética</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Abrir a página Last.fm correspondente a esta tag</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Você está pronto para começar! Clique em &lt;strong&gt;Concluir&lt;/strong&gt; e comece a explorar.&lt;/p&gt;&lt;p&gt;Também terminamos de importar o histórico de músicas e o adicionamos ao seu perfil na Last.fm.&lt;/p&gt;&lt;p&gt;Obrigado por instalar o Last.fm Desktop App, esperamos que você goste de usá-lo!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Isso é tudo, você está pronto para prosseguir!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Concluir</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;A seta vermelha na tela aponta para a localização do Last.fm Desktop App na bandeja do sistema.&lt;/p&gt;&lt;p&gt;Clique no ícone para acessar rapidamente os controles de execução da rádio, compartilhar faixas e adicionar tags a elas, editar suas preferências e visitar o seu perfil Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Last.fm Desktop App na sua barra de menus</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Last.fm Desktop App na bandeja do sistema</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Saiba mais sobre as músicas que você ouve, incluindo biografias, estatísticas musicais, fotos e artistas similares, bem como as tags que os ouvintes usam para descrevê-las.&lt;/p&gt;&lt;p&gt;Confira a guia &lt;strong&gt;Em execução&lt;/strong&gt; ou simplesmente clique em qualquer faixa na guia &lt;strong&gt;Scrobbles&lt;/strong&gt; para saber mais.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Descubra mais sobre os seus artistas preferidos</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pular tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Ouça rádios personalizadas ininterruptamente</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Use o Last.fm Desktop App para ouvir rádios personalizadas de acordo com as músicas que você gosta.&lt;/p&gt;&lt;p&gt;As faixas de cada estação Last.fm são totalmente diferentes e incluem desde estações baseadas em artistas e tags até recomendações totalmente novas, adaptadas ao seu gosto musical.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Assine e ouça rádios personalizadas, ininterruptamente</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Assine a Last.fm e use o Last.fm Desktop App para ouvir rádios personalizadas de acordo com as músicas que você gosta.&lt;/p&gt;\n&lt;p&gt;As faixas de cada estação Last.fm são totalmente diferentes e incluem desde estações baseadas em artistas e tags até recomendações totalmente novas, adaptadas ao seu gosto musical.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Assinar</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pular tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;O cliente desktop é executado em segundo plano e atualiza silenciosamente o seu perfil Last.fm com as músicas que você ouve, o que lhe permite receber recomendações de músicas, dicas de shows e muito mais. &lt;/p&gt;&lt;p&gt;Você também pode usar o Last.fm Desktop App para saber mais sobre o artista que está ouvindo e para executar a rádio personalizada.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Bem-vindo ao Last.fm Desktop App!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Continuar</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Voltar</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Pular tour &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Faixa</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Álbum</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artista</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Adicionar às preferidas</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartilhar</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Comprar</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Excluir este scrobble do seu perfil</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Executar rádio %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Programar rádio %1</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Rádio %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Em cache</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Erro: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Compartilhar na Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Compartilhar no Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Compartilhar no Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Ouvindo no momento</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Downloads</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Pesquisar em %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Comprar em %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Físico</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Contas de usuário conectadas:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Adicionar nova conta de usuário</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Adicionar erro de usuário</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Esse usuário já foi adicionado.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Removendo %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Tem certeza de que deseja remover este usuário? Todas as configurações de usuário serão perdidas e você precisará refazer a autenticação para voltar a fazer o scrobbling.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Assinar</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Remover</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(conectado no momento)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Contas</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Mostrar Scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Adicionar às preferidas</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Executar</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Pular</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tag</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Compartilhar</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Banir</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Mudo</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Fazer scrobble do iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Visitar perfil Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Habilitar scrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Fechar %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>de %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Você atingiu o limite de pulos de faixas desta estação. Pule novamente em %n minuto.</numerusform>\n            <numerusform>Você atingiu o limite de pulos de faixas desta estação. Pule novamente em %n minutos.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Você tem %n pulo de faixa restante nesta estação.</numerusform>\n            <numerusform>Você tem %n pulos de faixas restantes nesta estação.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>É necessário autenticar</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;A conta do usuário &lt;strong&gt;%1&lt;/strong&gt; não está mais autenticada na Last.fm.&lt;/p&gt;&lt;p&gt;Clique em OK para iniciar o processo de configuração e autenticar novamente essa conta.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Tem certeza de que deseja fechar %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 está prestes a fechar. As faixas executadas não serão incluídas no scrobble se você continuar.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Alterando o usuário</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 será conectado ao Scrobbler e à Rádio Last.fm. Todas as músicas serão agora direcionadas a esta conta. Deseja continuar?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Para continuar, feche os aplicativos a seguir.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Ocorreu um erro ao instalar o plug-in.</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ocorreu um erro durante a atualização do plug-in.&lt;/p&gt;&lt;p&gt;Tente novamente mais tarde.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Plug-in instalado!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;O plug-in %1 foi instalado.&lt;/p&gt;&lt;p&gt;Você agora está pronto para fazer o scrobble com %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>O plug-in %1 não foi instalado</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Você não fechou o %1, por isso o plug-in não foi instalado.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Feche o iTunes para atualizar o plug-in!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;O plug-in do iTunes (%2) é diferente do plug-in enviado para esta versão do aplicativo (%1).&lt;/p&gt;&lt;p&gt;Feche o iTunes agora para atualizar.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>Não instalado</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>O seu plug-in não foi instalado</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Ocorreu um erro durante a remoção do plug-in antigo</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Plug-in do iTunes instalado!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;O plug-in do iTunes foi instalado.&lt;/p&gt;&lt;p&gt;Você está pronto para fazer o scrobble do dispositivo.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Ocorreu um erro ao copiar o novo plug-in para o local de destino</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Você não fechou o iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Data/hora inválidos</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n minuto atrás</numerusform>\n            <numerusform>%n minutos atrás</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n hora atrás</numerusform>\n            <numerusform>%n horas atrás</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Ocorreu um erro na rede: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Você não autorizou este aplicativo</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Erro de autenticação</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Atualizar folha de estilos</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Não perguntar novamente</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Detectar automaticamente</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Sem proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_ru.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"ru\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>О программе</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (на базе Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Нажми кнопку &lt;strong&gt;Да, разрешить доступ&lt;/strong&gt; в браузере, чтобы привязать аккаунт Last.fm к скробблеру Last.fm.&lt;/p&gt;&lt;p&gt;Если не удалось привязать аккаунт из-за того, что ты нажал(а) кнопку &quot;Отмена&quot; или закрыл(а) окно браузера, попробуй еще раз.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Необходимо подключиться к Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Повторить попытку</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Если окно браузера не открылось, скопируй и вставь ссылку, опубликованную ниже, в строку адреса.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Сочетания клавиш:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Показать/скрыть Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Прокси-сервер:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Включить SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Объем кэша:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Подписчик</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Модератор</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Сотрудник</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Выпускница</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Выпускник</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>В турне</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ты можешь получать рекомендации, соответствующие твоему вкусу. Для этого рекомендуем импортировать историю воспроизведения из медиаплеера.&lt;/p&gt;&lt;p&gt;Выбери медиаплеер и нажми &lt;strong&gt;Начать импорт&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Модули не установлены</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Их можно установить позднее из меню &quot;Файл&quot;</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Теперь мы импортируем твою историю воспроизведения</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Начать импорт</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Пропустить &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Не волнуйся, загрузка займет не более двух минут в зависимости от размера твоей музыкальной библиотеки.&lt;/p&gt;&lt;p&gt;Пока мы работаем над добавлением твоей истории воспроизведения в профиль Last.fm, ты можешь ознакомиться со списком возможностей скробблера Last.fm. Нажми &lt;strong&gt;Продолжить&lt;/strong&gt; для ознакомления.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Необходимо закрыть приложения</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Скробллинг с устройства отключен - несовместимый модуль iTunes - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>требуется обновление</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Скробблинг iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Связать устройство %1 с твоим аккаунтом в аудиоскробблере?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Устройство зарегистрировано в аккаунте. Теперь ты можешь скробблить композиции, прослушанные на этом устройстве.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>Число заскроббленных композиций: %1</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Нет композиций, прослушанных после последней синхронизации</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Не удалось открыть базу данных iPod.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Неизвестная ошибка при обращении к базе данных iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Диагностика</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Скробблинг</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Это пасхальное яйцо!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Исполнитель</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Композиция</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Альбом</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Опознание музыки (Fingerprinting)</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Недавно опознанные композиции</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>Скробблинг iPod</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iPod автоматически синхронизируется с iTunes</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Синхронизировать iPod вручную</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Скробблинг iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Журналы</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Закрыть</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n композиция сохранена в локальном кэше</numerusform>\n            <numerusform>%n композиции сохранены в локальном кэше</numerusform>\n            <numerusform>%n композиций сохранены в локальном кэше</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Скробблер Last.fm</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Большое спасибо, &lt;strong&gt;%1&lt;/strong&gt;, твой аккаунт привязан!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Импорт...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Импорт завершен!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Найти друзей на Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;У тебя пока нет друзей на Last.fm.&lt;/h3&gt;&lt;p&gt;Используй Friend Finder, чтобы найти своих друзей по Facebook и почтовые контакты на Last.fm.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Поиск по имени пользователя или реальному имени</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Обновить список друзей</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Обновление...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>Радио библиотеки %1</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Муж</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Выполняется скробблинг из %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Жен</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Выполняется сробблинг</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Не определен</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Поиск друзей</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Просмотр списка друзей</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Язык:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Показывать значок приложения в строке меню</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Запускать приложение одновременно с музыкальным проигрывателем</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Показать значок на панели Dock</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Показывать уведомления на рабочем столе</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Отправлять отчеты об ошибках в Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Автоматически проверять наличие обновлений</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Включить кнопки мультимедиа</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Язык системы</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Перезапустить приложение?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Чтобы изменения вступили в силу, необходимо перезапустить приложение. Перезапустить приложение сейчас?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Обновление до бета-версий (только для храбрых!)</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>Не удалось открыть базу данных iPod.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Использование приложения для скробблинга под iOS, например %1, может привести к дублированию скробблинга. Скробблинг следует активировать только в одном приложении.&lt;/p&gt;\n&lt;p&gt;iTunes Match синхронизирует между устройствами информацию о количестве воспроизведений, но не о времени последнего воспроизведения. Это приводит к появлению повторяющихся записей и сохранению ошибочных временных меток. В настоящее время мы рекомендуем пользователям iTunes Match отключить скробблинг на компьютерах и использовать для скробблинга на iPhone/iPod скробблер для iOS, например %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Настройка не была изменена</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Чтобы изменить настройку, необходимо закрыть приложение iTunes</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Включить скробблинг с устройства</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Подтвердить скробблинг с устройства</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Обрати внимание</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Лицензии</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Готово?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Нажмите кнопку ОК после того, как подтвердите это приложение.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Сначала Last.fm требуется твое разрешение!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Этому приложению требуется разрешение для подключения к твоему профилю Last.fm.  Нажми кнопку OK, чтобы перейти на сайт Last.fm и предоставить разрешение.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ты уже являешься пользователем Last.fm? Подключи свой аккаунт к скробблеру Last.fm для того, чтобы сохранить в твоем профиле музыку, которую ты слушаешь.&lt;/p&gt;&lt;p&gt;Если у тебя нет аккаунта, можешь зарегистрироваться прямо сейчас. Это бесплатно!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Давай начнем с подключения твоего аккаунта Last.fm</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Подключить аккаунт</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Регистрация</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Прокси-сервер?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Доступны обновления для модулей медиаплееров. Установить обновления?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>В ходе установки модуля возникла ошибка</numerusform>\n            <numerusform>В ходе установки модулей возникла ошибка</numerusform>\n            <numerusform>В ходе установки модулей возникла ошибка</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;При обновлении модуля возникла ошибка.&lt;/p&gt;&lt;p&gt;Повтори попытку позже.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;При обновлении модулей возникла ошибка.&lt;/p&gt;&lt;p&gt;Повтори попытку позже.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;При обновлении модулей возникла ошибка.&lt;/p&gt;&lt;p&gt;Повтори попытку позже.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Модуль установлен!</numerusform>\n            <numerusform>Модули установлены!</numerusform>\n            <numerusform>Модули установлены!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Модуль установлен.&lt;/p&gt;&lt;p&gt;Проигрыватель готов для скробблинга&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Модули установлены.&lt;/p&gt;&lt;p&gt;Проигрыватель готов для скробблинга&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Подключаемые модули установлены.&lt;/p&gt;&lt;p&gt;Все готово для скробблинга в вашем плеере&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Модули не установлены</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Их можно установить позднее из меню &quot;Файл&quot;</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Файл</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Установить модули</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Выход</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Вид</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Мой профиль Last.fm</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Композиции</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Обновить</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Элементы управления</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Аккаунт</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Инструменты</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Проверить наличие обновлений</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Настройки</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Окно</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Свернуть</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Масштаб</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Все окна на передний план</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Справка</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>О программе</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>Вопросы и ответы</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Форумы</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Обзор</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Показать лицензии</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Диагностика</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n композиция&lt;/a&gt; заскробблена с этого устройства</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n композиции&lt;/a&gt; заскробблены с этого устройства</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n композиций&lt;/a&gt; заскробблены с этого устройства</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Вернуться к композициям</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Популярные теги:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Твои теги:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Похожие исполнители</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>с альбома %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Слушать радио %1</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>воспроизведение</numerusform>\n            <numerusform>воспроизведения</numerusform>\n            <numerusform>воспроизведений</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>воспроизведение в твоей библиотеке</numerusform>\n            <numerusform>воспроизведения в твоей библиотеке</numerusform>\n            <numerusform>воспроизведений в твоей библиотеке</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>слушатель</numerusform>\n            <numerusform>слушателя</numerusform>\n            <numerusform>слушателей</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>%1 и более.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>%1, %2 и более.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Дата изменения %1 | %2 Изменить</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Загрузки</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Поиск в %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Купить в %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>На носителе</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Рекомендуется, так как ты слушаешь %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Рекомендуется, так как ты слушаешь %1 и %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Рекомендуется, так как ты слушаешь %1, %2 и %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Рекомендуется, так как ты слушаешь %1, %2, %3 и %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Рекомендуется, так как ты слушаешь %1, %2, %3, %4 и %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Из библиотеки %1.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Из библиотек %1 и %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 раз</numerusform>\n            <numerusform>%L1 раза</numerusform>\n            <numerusform>%L1 раз</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Из библиотек %1, %2 и %3.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Ты слушал(а) %1 %2 и %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Из библиотек %1, %2, %3 и %4&apos;.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Ты слушал(а) %1 %2, но не эту композицию</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Из библиотек %1, %2, %3, %4 и %5.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Это твое первое прослушивание %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Привет!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Включить радиостанцию</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Открыть iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Открыть Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Открыть проигрыватель Windows Media</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Открыть Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Открыть Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Скробблинг из твоего музыкального проигрывателя&lt;/h2&gt;&lt;p&gt;Начни слушать музыку со своего проигрывателя. Дополнительная информация о воспроизводимых композициях будет отображаться на вкладке &quot;Ты слушаешь&quot;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Привет, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Радиостанция</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Слушать %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Радио нескольких библиотек</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Поставить в очередь %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Слушать радио библиотек %1 и %2</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Поставить в очередь радио библиотеки %1 и %2</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>В любимые</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Запретить</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Слушать</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Пропустить</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Пауза</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Возобновить</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Удалить из списка любимых</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Настройка</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Радиостанция</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Воспроизведение</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Скробблинг из</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 воспроизведение</numerusform>\n            <numerusform>%L1 воспроизведения</numerusform>\n            <numerusform>%L1 воспроизведений</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Клиент Last.fm завершил импорт твоей библиотеки. \n \n Нажми OK для продолжения.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Импорт библиотеки Last.fm</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Отменить импорт?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm не удалось найти композиции в твоей библиотеке.\n\n Нажми OK для продолжения.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm выполняет импорт твоей библиотеки...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Где находится Winamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Где находится проигрыватель Windows Media?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Импорт библиотеки завершен</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Приложение Last.fm передало журнал прослушенной музыки на сервер.\nЧерез несколько минут твой профиль будет обновлен, и в нем появятся новые композиции.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Не удалось импортировать библиотеку</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Не удалось импортировать журнал прослушанной музыки. Вероятно, в твоем профиле уже заскробблено некоторое количество композиций. Журнал прослушиваний можно импортировать только в новые профили.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Чтобы установить модули, следуй инструкциям операционной системы.&lt;/p&gt;&lt;p&gt;После установки модулей нажми кнопку &lt;strong&gt;Продолжить&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Выполняется установка модулей</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Модули не установлены</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Их можно установить позднее из меню &quot;Файл&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Чтобы скробблить музыку, которую ты слушаешь, необходимо установить специальные модули Last.fm для медиапроигрывателей.&lt;/p&gt;&lt;p&gt;Выбери медиапроигрыватели, с помощью которых ты хочешь  скробблить музыку, и нажми &lt;strong&gt;Установить модули&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(более новая версия)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Модуль установлен, щелкни флажок, чтобы переустановить)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Следующий шаг — установка модулей Last.fm для скробблинга музыки.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Установить модули</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Пропустить &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Общие</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Аккаунты</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Скробблинг</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Устройства</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Дополнительно</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Радио %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 воспроизведение</numerusform>\n            <numerusform>%L1 воспроизведения</numerusform>\n            <numerusform>%L1 воспроизведений</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Лучшие исполнители этой недели</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Лучшие исполнители за все время</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>заскроббленная композиция</numerusform>\n            <numerusform>заскроббленные композиции</numerusform>\n            <numerusform>заскроббленных композиций</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>любимая композиция</numerusform>\n            <numerusform>любимые композиции</numerusform>\n            <numerusform>любимых композиций</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 исполнитель</numerusform>\n            <numerusform>%L1 исполнителя</numerusform>\n            <numerusform>%L1 исполнителей</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 композиция</numerusform>\n            <numerusform>%L1 композиции</numerusform>\n            <numerusform>%L1 композиций</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>%1 в твоей библиотеке, число прослушиваний в день: %2.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Композиция с %1</numerusform>\n            <numerusform>Композиции с %1</numerusform>\n            <numerusform>Композиций с %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Параметры прокси-сервера</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Сервер:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Имя пользователя:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Порт:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Пароль:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>неизвестный медиаплеер</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Как подключен твой iPod?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Укажи исполнителя/тег и нажми Слушать</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Воспр.</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Может попробуешь %1, %2, %3 или %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Следующая композиция</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Радиостанция</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Слушать радио могут только подписчики</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Последняя станция</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Радиостанция</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Персональные станции</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Радио моей библиотеки</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Музыка, которую ты знаешь и любишь</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Мой радиомикс</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Твоя библиотека и новая музыка</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Радио &quot;Мои рекомендации&quot;</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Подпишись, чтобы получить доступ к радио</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Новая музыка на Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Радио в этом приложении доступно только для подписчиков Last.fm. Подпишись, и ты сможешь слушать радио и получишь доступ к другим функциям.</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Сетевые станции</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Стать подписчиком Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Слушать бесплатно на www.lastfm.ru</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Радио моих друзей</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Музыка, которую любят твои друзья</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Радио соседей</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Музыка пользователей, похожих на тебя</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Последние станции</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Ты слушаешь</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Стань подписчиком, чтобы слушать радио. Всего %1 в месяц!</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Скробблинг с устройства</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Ты слушал(а) эти композиции. Хочешь их заскробблить?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Автоматический сробблинг с устройства</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Переключить</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n композиция заскробблена с устройства</numerusform>\n            <numerusform>%n композиции заскробблено с устройства</numerusform>\n            <numerusform>%n композиций заскробблено с устройства</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>В любимые</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Добавить теги</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>В любимые</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Тег</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Поделиться</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Поделиться на Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Поделиться в Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Поделиться в Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Купить</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Удалить композицию из списка любимых</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Скробблиниг на</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>% композиции</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Включить скробблинг</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...или через 4 минуты (в зависимости от того, какое событие наступит раньше)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Скробблинг подкастов</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Разрешить Last.fm опознавать композиции</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Не удалось выполнить скробблинг для выбранных каталогов</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Другие заскроббленные композиции на Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Обновление...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Обновить заскроббленные композиции</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Исполнитель</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Название</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Альбом</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Воспроизведение</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Последнее воспроизведение</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Любимые</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Эта композиция короче 30 секунд</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Имя исполнителя отсутствует</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Недопустимое название композиции</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Недопустимый исполнитель</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Временная метка отсутствует</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Эта композиция слишком далеко в будущем</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Эта композиция воспроизводилась более двух недель назад</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Ты еще не заскробблил(а) музыку на Last.fm</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Начни слушать музыку в медиаплеере или запусти радиостанцию:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Поделиться с друзьями</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Кому:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Сообщение (необязательно):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>Включить в мои последние действия</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Композиция %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Композиция %1 из альбома %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Оцени %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Ты слушаешь</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Композиции</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Профиль</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Друзья</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Радио</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Следующий раздел</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Предыдущий раздел</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Не удалось включить радио: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>нет результатов для &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Скробблинг выключен</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>В сети</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Не в сети</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Тег</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Выбери, что нужно отметить тегом:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Композиция</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Исполнитель</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Альбом</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>значок</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Добавить теги:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>Композиция %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>Композиция %1 из альбома %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Введи тег выше\nили выбери его из списка внизу</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Сортировать по популярности</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Сортировать по алфавиту</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Открыть страницу этого тега на Last.fm</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Все готово, можешь приступать! Просто нажми кнопку &lt;strong&gt;Готово&lt;/strong&gt; и начинай изучать возможности приложения.&lt;/p&gt;&lt;p&gt;Мы также завершили импорт твоей истории воспроизведения и добавили ее в твой профиль Last.fm.&lt;/p&gt;&lt;p&gt;Благодарим за установку скробблера Last.fm, надеемся он тебе понравится!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Все готово, можешь приступать!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Готово</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Красной стрелкой на экране отмечено расположение скробблера Last.fm в панели задач.&lt;/p&gt;&lt;p&gt;Щелкни по этому значку, чтобы получить быстрый доступ к элементам управления радио, опубликовать композиции, добавить теги, изменить настройки и открыть профиль Last.fm.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Скробблер Last.fm в строке меню</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Скробблер Last.fm в панели задач</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Узнай больше о музыке, которую слушаешь: в твоем распоряжении  биографии, статистика воспроизведения, фотографии, рекомендации похожих исполнителей, а также теги, добавленные слушателями.&lt;/p&gt;&lt;p&gt;Открой вкладку &lt;strong&gt;Ты слушаешь&lt;/strong&gt; или щелкни любую композицию на вкладке &lt;strong&gt;Композиции&lt;/strong&gt;, чтобы узнать больше.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Узнай больше о своих любимых исполнителях</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Пропустить обзор &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Слушай персональное радио в режиме нон-стоп</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Используй Скробблер Last.fm для прослушивания персонального радио, соответствующего твоим предпочтениям.&lt;/p&gt;&lt;p&gt;Выбери любую станцию Last.fm - исполнителей, тегов или твоих рекомендаций, - и слушай каждый раз новое радио.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Стань подписчиком и слушай персональное радио в режиме нон-стоп</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Стань подписчиком Last.fm и используй Скробблер Last.fm для прослушивания персонального радио, соответствующего твоим предпочтениям.&lt;/p&gt;&lt;p&gt;Выбери любую станцию Last.fm - исполнителей, тегов или твоих рекомендаций, - и слушай каждый раз новое радио.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Подписка</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Пропустить обзор &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Скробблер работает в фоновом режиме и обновляет твой профиль Last.fm музыкой, которую ты слушаешь. В дальнейшем эта информация используется для составления рекомендаций по музыке и концертам и др. &lt;/p&gt;&lt;p&gt;Кроме того, скробблер Last.fm можно использовать для поиска информации об исполнителе и прослушивания персональных радиостанций.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Добро пожаловать в скробблер Last.fm!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Продолжить</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Назад</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Пропустить обзор &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Композиция</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Альбом</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Исполнитель</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>В любимые</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Тег</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Поделиться</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Купить</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Удалить эту композицию из твоего профиля</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Слушать радио %1</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Поставить в очередь радио %1</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>Радио %1</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Сохранено в кэше</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Ошибка: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Поделиться на Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Поделиться в Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Поделиться в Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Ты слушаешь</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Загрузки</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Поиск в %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Купить в %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>На носителе</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Подключенные аккаунты</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Добавить аккаунт</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>При добавлении пользователя возникла ошибка</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Пользователь уже добавлен.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Удаление %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Действительно удалить пользователя? Все настройки этого пользователя будут потеряны, и тебе придется ввести имя пользователя или пароль, чтобы активировать скробблинг в будущем.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Подписаться</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Удалить</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(в системе)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Аккаунты</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Показать скробблер</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>В любимые</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Воспр.</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Пропустить</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Тег</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Поделиться</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Запретить</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Выключить звук</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Скробблиниг iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Открыть профиль Last.fm</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Включить скробблинг</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Закрыть %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>с альбома %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Достигнуто ограничение станции по числу переходов между композициями. Повтори попытку через %n минуту.</numerusform>\n            <numerusform>Достигнуто ограничение станции по числу переходов между композициями. Повтори попытку через %n минуты.</numerusform>\n            <numerusform>Достигнуто ограничение станции по числу переходов между композициями. Повтори попытку через %n минут.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Для этой станции доступен %n переход между композициями.</numerusform>\n            <numerusform>Для этой станции доступно %n перехода между композициями.</numerusform>\n            <numerusform>Для этой станции доступно %n переходов между композициями.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Требуется аутентификация</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Аккаунт &lt;strong&gt;%1&lt;/strong&gt; больше не аутентифицирован на Last.fm.&lt;/p&gt;&lt;p&gt;Нажми кнопку OK, чтобы запустить процесс установки и заново аутентифицировать аккаунт.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Закрыть %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>Приложение %1 будет закрыто. Композиции не будут скробблиться, если ты продолжишь.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Смена пользователя</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 зарегистрируется в скробблере и радио Last.fm. Вся музыка будет скробблиться в этот аккаунт. Продолжить?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Чтобы продолжить, закрой следующие приложения.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>В ходе установки модуля возникла ошибка</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;В ходе установки модуля возникла ошибка.&lt;/p&gt;&lt;p&gt;Повтори попытку позже.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Модуль установлен.</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Модуль %1 установлен.&lt;/p&gt;&lt;p&gt;Все готово для скробблинга в %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Модуль %1 не установлен</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Ты не закрыл(а) приложение %1, поэтому модуль для него не был установлен.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Закрой iTunes для обновления модуля!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Версия установленного модуля iTunes (%2) отличается от версии, которая поставляется с этой версией приложения (%1).&lt;/p&gt;&lt;p&gt;Закрой iTunes для обновления.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>не установлено</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Модуль не установлен</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Ошибка удаления старого модуля</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>Модуль iTunes не установлен!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Установка модуля iTunes завершена.&lt;/p&gt;&lt;p&gt;Все готово для скробблинга с этого устройства.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Ошибка копирования нового модуля</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Ты не закрыл(а) iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Ошибка отсчета времени</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n мин. назад</numerusform>\n            <numerusform>%n мин. назад</numerusform>\n            <numerusform>%n мин. назад</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n ч. назад</numerusform>\n            <numerusform>%n ч. назад</numerusform>\n            <numerusform>%n ч. назад</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Ошибка сети: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Ты не авторизовал(а) это приложение</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Ошибка аутентификации</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Обновить таблицу стилей</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Больше не спрашивать</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Определять автоматически</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Без прокси-сервера</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_sv.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"sv\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Om</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 (byggt på Qt %2)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Klicka på knappen &lt;strong&gt;Ja, tillåt åtkomst&lt;/strong&gt; i din webbläsare för att ansluta ditt Last.fm-konto till Last.fm-programmet.&lt;/p&gt;&lt;p&gt;Om du inte har anslutit eftersom du har stängt din webbläsare eller klickat på avbryt, försök igen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Vi väntar på att du ska ansluta dig till Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Försök igen</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Om din webbläsare inte öppnades, kopiera och klistra in länken nedan i ditt adressfält.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Tangentbordsgenvägar</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Visa/dölj Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>Aktivera SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Cachestorlek:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Abonnent</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderator</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Personal</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Alumni</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Alumni</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>På turné</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;För de bästa möjliga rekommendationerna baserat på din musiksmak rekommenderar vi att du importerar din lyssningshistorik från din mediaspelare.&lt;/p&gt;&lt;p&gt;Välj den mediaspelare du föredrar och klicka på &lt;strong&gt;Starta import&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Dina insticksprogram har inte installerats</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kan installera dem senare genom filmenyn</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Låt oss nu importera din lyssningshistorik</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>Starta import</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Hoppa över &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Oroa dig inte, uppladdningsprocessen bör inte ta mer än några minuter beroende på storleken på ditt musikbibliotek.&lt;/p&gt;&lt;p&gt;Medan vi jobbar hårt med att lägga till din lyssningshistorik till din Last.fm-profil kan du kolla in Last.fm-programmets huvudfunktioner. Klicka på &lt;strong&gt;Fortsätt&lt;/strong&gt; för att ta turen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Stäng program</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Enhetsskrobbling aktiverad - inkompatibelt iTunes-insticksprogram - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>vänligen uppdatera</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Skrobbla iPod</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>Vill du associera enheten %1 till ditt audioscrobbler-användarkonto?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Enheten har framgångsrikt associerats till ditt användarkonto. Från och med nu kan du skrobbla låtarna du lyssnar på på denna enhet.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 låtar skrobblade.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Inga låtar att skrobbla sedan din senaste synkning.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod-databasen kunde inte öppnas.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>Ett okänt fel uppstod vid försöket att komma åt iPod-databasen.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostik</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Skrobbling</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Detta är ett påskägg!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Låt</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Fingeravtryck</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Nyligen fingerprintade låtar</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod-skrobbling</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes hanterar min iPod automatiskt</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>Jag hanterar min iPod manuellt</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>Skrobbla iPod</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Loggar</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Stäng</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n lokalt cachad låt  </numerusform>\n            <numerusform>%n lokalt cachade låtar</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm-programmet</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Tack &lt;strong&gt;%1&lt;/strong&gt;, ditt konto är nu anslutet!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>Importerar ...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>Import slutförd!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Hitta dina vänner på Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Du har inga vänner på Last.fm än.&lt;/h3&gt;&lt;p&gt;Hitta dina Facebook-vänner och e-postkontakter på Last.fm snabbt och enkelt med vänsökaren.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Sök efter en vän med användarnamn eller riktigt namn</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Uppdatera vänner</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Uppdaterar ...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>%1s biblioteksradio</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Man</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Skrobblar nu från %1</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Kvinna</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Skrobblar nu</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Neutral</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Sök dina vänner</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Sök vänner</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Språk:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Visa programikon i menylistan</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Starta program med mediaspelare</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Visa dockikon</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Visa skrivbordsmeddelanden</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Skicka kraschrapporter till Last.fm</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Leta automatiskt efter uppdateringar</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Aktivera mediaknappar</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Systemspråk</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Starta om nu?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Det krävs en omstart av programmet för att ändringen ska börja gälla. Vill du starta om nu?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Uppdatera till betaversioner - varning: endast för de modiga!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod-databasen kunde inte öppnas.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Användningen av en iOS-skrobblingsapp som %1 kan resultera i dubbla skrobblingar. Aktivera endast skrobbling i en av dem.&lt;/p&gt;&lt;p&gt;iTunes Match synkroniserar antalet spelade låtar, men inte senaste gången det har spelats från flera enheter. Detta leder till dubbla skrobblingar vid fel tider. För tillfället rekommenderar vi därför att iTunes Match-användare avaktiverar enheter som skrobblar på datorenheter och att de skrobblar iPhones/iPods med en iOS-skrobblingsapp som %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Inställningen har inte ändrats</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Du stängde inte iTunes så denna inställning kunde ändras</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Aktivera enhetsskrobbling</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Bekräfta enhetsskrobbling</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Observera</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Licenser</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Är vi klara?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Klicka på OK när du har godkänt denna app.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm behöver din tillåtelse först!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Detta program behöver din tillåtelse för att ansluta till din Last.fm-profil. Klicka på OK för att gå till Last.fm-webbsidan och göra detta.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Redan Last.fm-användare? Anslut ditt konto till Last.fm-programmet så kommer din profil att uppdateras med den musik du lyssnar på.&lt;/p&gt;&lt;p&gt;Om du inte har ett konto kan du registrera dig gratis nu.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Kom igång genom att ansluta ditt Last.fm-konto</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Anslut ditt konto</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Registrera dig</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Det finns uppdateringar för insticksprogrammen för dina mediaspelare. Vill du installera dem nu?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Insticksprogram installationsfel</numerusform>\n            <numerusform>Insticksprogram installationsfel</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Det uppstod ett fel vid uppdateringen av ditt insticksprogram.&lt;/p&gt;&lt;p&gt;Vänligen försök igen senare.&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Det uppstod ett fel vid uppdateringen av dina insticksprogram.&lt;/p&gt;&lt;p&gt;Vänligen försök igen senare.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Insticksprogram installerat!</numerusform>\n            <numerusform>Insticksprogram installerade!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Ditt insticksprogram har installerats.&lt;/p&gt;&lt;p&gt;Du kan nu skrobbla med din mediaspelare&lt;/p&gt;</numerusform>\n            <numerusform>&lt;p&gt;Dina insticksprogram har installerats.&lt;/p&gt;&lt;p&gt;Du kan nu skrobbla med dina mediaspelare&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Dina insticksprogram har inte installerats</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kan installera dem senare genom filmenyn</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Fil</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Installera insticksprogram</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Avsluta</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Visa</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Min Last.fm-profil</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Skrobblingar</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Uppdatera</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Kontroller</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Konto</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Verktyg</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Kontrollera om det finns uppdateringar</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Alternativ</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Fönster</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Minimera</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Zoom</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Ta fram alla</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Hjälp</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Om</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>FAQ</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Forum</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Guide</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Visa licenser</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Diagnostik</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n spelad låt&lt;/a&gt; har skrobblats från enheten</numerusform>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n spelade låtar&lt;/a&gt; har skrobblats från enheten</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Tillbaka till skrobblingar</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Populära taggar:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Dina taggar:</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Liknande artister</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>av %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>från %1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Spela %1-radio</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Spelad låt</numerusform>\n            <numerusform>Spelade låtar</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Spelad låt i ditt bibliotek</numerusform>\n            <numerusform>Spelade låtar i ditt bibliotek</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Lyssnare</numerusform>\n            <numerusform>Lyssnare</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>Med %1 och mer.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>Med %1, %2 och mer.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>Redigerat den %1 | %2 Redigera</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Nedladdningar</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Sök på %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Köp på %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Fysiskt</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>Rekommenderat eftersom du lyssnar på %1.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>Rekommenderat eftersom du lyssnar på %1 och %2.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>Rekommenderat eftersom du lyssnar på %1, %2 och %3.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>Rekommenderat eftersom du lyssnar på %1, %2, %3 och %4.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>Rekommenderat eftersom du lyssnar på %1, %2, %3, %4 och %5.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>Från %1s bibliotek.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>Från %1 och %2s bibliotek.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 gång</numerusform>\n            <numerusform>%L1 gånger</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>Från %1, %2 och %3s bibliotek.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>Du har lyssnat på %1 %2 och %3 %4.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>Från %1, %2, %3 och %4s bibliotek.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>Du har lyssnat på %1 %2, men inte denna låt.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>Från %1, %2, %3, %4 och %5s bibliotek.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>Detta är första gången du lyssnar på %1.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Hej!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Starta en radiostation</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>Öppna iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>Öppna Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Öppna Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Öppna Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Öppna Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Skrobbla från din musikspelare&lt;/h2&gt;&lt;p&gt;Börja lyssna på musik i din musikspelare. Du kan se mer information om låtarna du spelar under fliken Spelas nu.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Hej, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>En radiostation</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>Spela %1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Radio från flera bibliotek</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>Köa %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>Spela %1 och %2 biblioteksradio</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>Köa %1 och %2 biblioteksradio</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Älska</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Blockera</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Spela</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Hoppa över</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Pausa</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Återuppta</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Sluta älska</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Inställning</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>En radiostation</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Lyssnar på</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Skrobblar från</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 spelad låt</numerusform>\n            <numerusform>%L1 spelade låtar</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm har importerat ditt mediabibliotek.\n\n Klicka på OK för att fortsätta.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Last.fm-biblioteksimport</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>Är du säker på att du vill avbryta importen?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm kunde inte hitta några spelade låtar i ditt mediabibliotek.\n\n Klicka på OK för att fortsätta.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm importerar ditt aktuella mediabibliotek ...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Var är Wimamp?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Var är Windows Media Player?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Import av mediabibliotek slutförd</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm har skickat din lyssningshistorik till servern.\nDin profil kommer att uppdateras med de nya låtarna om några minuter.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Kunde inte importera bibliotek</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Ledsen, Last.fm kunde inte importera din lyssningshistorik. Du har förmodligen redan skrobblat för många låtar. Lyssningshistoriken kan bara importeras till nya profiler.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Följ instruktionerna som ditt operativsystem visar för att installera insticksprogrammen.&lt;/p&gt;&lt;p&gt;När insticksprogrammen har installerats på din dator, klicka på &lt;strong&gt;Fortsätt&lt;/strong&gt;.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Dina insticksprogram installeras nu</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Dina insticksprogram har inte installerats</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Du kan installera dem senare genom filmenyn</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Dina mediaspelare behöver ett speciellt Last.fm-insticksprogram så att du kan skrobbla musiken du lyssnar på.&lt;/p&gt;&lt;p&gt;Vänligen välj de mediaspelare som du vill skrobbla din musik från och klicka på &lt;strong&gt;Installera insticksprogram&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(nyare version)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Insticksprogram installerade, klicka för att installera om)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Nästa steg, installera Last.fm-insticksprogrammen för att skrobbla musiken du lyssnar på.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Installera insticksprogram</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Hoppa över &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Allmänt</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Konton</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Skrobbling</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Enheter</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Avancerat</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 radio</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 spelad låt</numerusform>\n            <numerusform>%L1 spelade låtar</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Toppartister denna vecka</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Toppartister generellt</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Skrobbling</numerusform>\n            <numerusform>Skrobblingar</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Älskad låt</numerusform>\n            <numerusform>Älskade låtar</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 artist</numerusform>\n            <numerusform>%L1 artister</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 låt</numerusform>\n            <numerusform>%L1 låtar</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Du har %1 i ditt bibliotek och lyssnar i genomsnitt på %2 per dag.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>Skrobbling sedan %1</numerusform>\n            <numerusform>Skrobblingar sedan %1</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Proxy-inställningar</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Värd:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Användarnamn:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Lösenord:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>okänd mediaspelare</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>Var är din iPod placerad?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Ange en artist eller tagg och tryck play</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Spela</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>Försök med %1, %2, %3 eller %4?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Spela nästa</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>En radiostation</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Du måste vara abonnent för att lyssma på radio</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Senaste station</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>En radiostation</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Personliga stationer</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Min biblioteksradio</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Musik du känner till och älskar</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Min blandradio</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Ditt bibliotek plus ny musik</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Min rekommenderade radio</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Abonnera för att lyssna på radio</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Ny musik från Last.fm</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Du måste vara Last.fm-abonnent för att lyssna på radio i detta program. Abonnera nu för att börja lyssna och utnyttja andra bra fördelar!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Nätverksstationer</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Abonnera på Last.fm</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>Lyssna gratis på www.last.fm</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Mina vänners radio</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Musik dina vänner gillar</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Min grannradio</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Musik från lyssnare som du</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Senaste stationer</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Nu spelas</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Abonnera för att lyssna på radio, endast %1 i månaden</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Enhetsskrobblingar</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Det ser ut som om du har spelat dessa låtar. Vill du skrobbla dem?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Skrobbla enheter automatiskt</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Växla urval</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>%n spelad låt har skrobblats från en enhet  </numerusform>\n            <numerusform>%n spelade låtar har skrobblats från en enhet  </numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Älska låt</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Lägg till taggar</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Älska</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tagga</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Dela</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Dela på Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Dela på Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Dela på Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Köp</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Sluta älska låt</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Skrobbla vid</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>procent av låten</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Aktivera skrobbling</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>...eller vid 4 minuter (beroende på vad som kommer först)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Skrobbla podcasts</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Tillåt Last.fm att fingerprinta mina låtar</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Valda kataloger kommer inte att skrobblas</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Mer skrobblingar på Last.fm</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Uppdaterar ...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Uppdatera skrobblingar</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Titel</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Spelade låtar</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Senast spelad</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Älskad</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Denna låt är under 30 sekunder</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Artistnamnet saknas</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Ogiltig låttitel</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Ogiltig artist</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Detta är inte en tidstämpel</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Denna låt är för långt in i framtiden</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Denna låt spelades för över två veckor sedan</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Du har inte skrobblat någon musik till Last.fm än.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Börja lyssna på musik i din mediaspelare eller starta en radiostation:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Dela med vänner</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Med:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Meddelande (valfritt):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>inkludera i min senaste aktivitet</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>En låt av %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>En låt av %1 från utgåvan %2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>Kolla in %1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Nu spelas</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Skrobblingar</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Vänner</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radio</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Nästa sektion</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Föregående sektion</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>Kunde inte starta radio: %1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>inga resultat för &quot;%1&quot;</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Skrobbling är av</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Online</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Offline</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Tagg</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Välj något att tagga:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Låt</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>ikon</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Lägg till taggar:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>En låt av %1</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>En låt av %1 från utgåvan %2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Skriv in en tagg ovan\neller välj från nedanstående</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Sortera efter popularitet</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Sortera alfabetiskt</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Öppna Last.fm-sidan för denna tagg</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Nu kan du komma igång! Klicka bara på &lt;strong&gt;Avsluta&lt;/strong&gt; och börja utforska.&lt;/p&gt;&lt;p&gt;Vi är också klara med importen av din lyssningshistorik och har lagt till den i din Last.fm-profil.&lt;/p&gt;&lt;p&gt;Tack för att du har installerat Last.fm-programmet, vi hoppas att du kommer att ha glädje av den!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Det var det, du är klar att börja!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Avsluta</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Den röda pilen på din skärm visar var Last.fm-programmet finns i ditt aktivitetsfält.&lt;/p&gt;&lt;p&gt;Klicka på ikonen för att få snabb tillgång till radioknapparna, dela och tagga låt, redigera dina inställningar och besöka din last.fm-profil.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Last.fm-programmet i ditt menyfält</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Last.fm-programmet i ditt aktivitetsfält.</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Få mer information om musiken du lyssnar på, inklusive biografier, lyssningsstatistik, foton och liknande artister samt taggar som lyssnare använder för att beskriva dem.&lt;/p&gt;&lt;p&gt;Kolla in fliken &lt;strong&gt;Spelas nu&lt;/strong&gt; eller klicka bara på en låt på din flik &lt;strong&gt;Skrobblingar&lt;/strong&gt; för mer information.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Läs mer om artisterna du älskar</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Hoppa över tur &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Lyssna på nonstop, personlig radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Använd Last.fm-programmet för att lyssna på personlig radio baserat på musiken du vill höra.&lt;/p&gt;&lt;p&gt;Alla uppspelningar av alla Last.fm-stationer är helt olika, allt från stationer baserat på artister och taggar till helt nya rekommendationer skräddarsydda efter din musiksmak.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Abonnera och lyssna på nonstop personlig radio</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Abonnera på Last.fm och använd Last.fm-programmet för att lyssna på personlig radio baserat på musiken du hör.&lt;/p&gt;&lt;p&gt;Alla uppspelningar av alla Last.fm-stationer är helt olika, allt från stationer baserat på artister och taggar till helt nya rekommendationer skräddarsydda efter din musiksmak.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abonnera</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Hoppa över tur &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Programmet körs i bakgrunden och uppdaterar tyst din Last.fm-profil i bakgrunden med musiken du spelar, vilket du kan använda för att få musikrekommendationer, spelningstips med mera. &lt;/p&gt;&lt;p&gt;Du kan också använda Last.fm-programmet för att få mer information om artisten du lyssnar på och spela personlig radio.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Välkommen till Last.fm-programmet!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Fortsätt</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; Tillbaka</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Hoppa över tur &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>Låt</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Album</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Artist</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Älska</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tagga</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Dela</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Köp</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Radera denna skrobbling från din profil</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>Spela %1-radio</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>Köa %1 radio</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1-radio</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Cachat</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Fel: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Dela på Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Dela på Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Dela på Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Lyssnar nu</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>Hämtningar</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>Sök på %1</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>Köp på %1 %2</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Fysisk</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Anslutna användarkonton:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Lägg till nytt användarkonto</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Lägg till användarfel</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Användaren har redan lagts till.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>Tar bort %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Är du säker på att du vill ta bort denna användare? Alla användarinställningar kommer att gå förlorade och du måste ge tillstånd igen för att skrobbla i framtiden.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abonnera</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Ta bort</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(inloggad för tillfället)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Konton</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Visa skrobblare</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Älska</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Spela</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Hoppa över</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Tagga</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Dela</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Blockera</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Stäng av ljud</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>Skrobbla iPod ...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Besök Last.fm-profil</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Aktivera skrobbling</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>Avsluta %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>från %1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Du har nått denna stations gräns för antalet gånger du får hoppa över en låt. Hoppa över igen om %n minut.</numerusform>\n            <numerusform>Du har nått denna stations gräns för antalet gånger du får hoppa över en låt. Hoppa över igen om %n minuter.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Du får hoppa över %n låt till på denna station.</numerusform>\n            <numerusform>Du får hoppa över %n låtar till på denna station.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Verifiering krävs</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Användarkontot &lt;strong&gt;%1&lt;/strong&gt; är inte längre verifierat med Last.fm.&lt;/p&gt;&lt;p&gt;Klicka på OK för att starta inställningsprocessen och verifiera detta konto igen.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>Är du säker på att du vill avsluta %1?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 håller på att avslutas. Låtar som spelas kommer inte att skrobblas om du fortsätter.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Ändra användare</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 kommer att loggas in i skrobblaren och Last.fm-radio. All musik kommer nu att skrobblas till detta konto. Vill du fortsätta?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Stäng följande appar för att fortsätta.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Insticksprogram installationsfel</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Det uppstod ett fel vid uppdateringen av ditt insticksprogram.&lt;/p&gt;&lt;p&gt;Försök igen senare.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Insticksprogram installerat!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Insticksprogrammet %1 har installerats.&lt;/p&gt;&lt;p&gt;Du kan nu skrobbla med %1.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>Insticksprogrammet %1 har inte installerats</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>Du stängde inte %1 så dess insticksprogram har inte installerats.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Stäng iTunes för uppdatering av insticksprogrammet!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ditt iTunes-insticksprogram (%2) skiljer sig från det som levereras med denna version av appen (%1).&lt;/p&gt;&lt;p&gt;Stäng iTunes nu för att uppdatera.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>inte installerat</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Ditt insticksprogram har inte installerats</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Det uppstod ett fel när det gamla insticksprogrammet skulle tas bort</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes-insticksprogram installerat!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ditt iTunes-insticksprogram har installerats.&lt;/p&gt;&lt;p&gt;Du kan nu skrobbla från enheten.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Det uppstod ett fel vid kopieringen av det nya insticksprogrammet</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>Du stängde inte iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Tiden är avbruten</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>för %n minut sedan</numerusform>\n            <numerusform>för %n minuter sedan</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>för %n timme sedan</numerusform>\n            <numerusform>för %n timmar sedan</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Det uppstod ett nätverksfel: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Du har inte verifierat detta program</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Verifieringsfel</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Uppdatera Stylesheet</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Fråga inte detta igen</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Automatisk igenkänning</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Ingen proxy</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_tr.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"tr\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>Hakkında</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1 ( Qt %2 üzerinde oluşturuldu)</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Lütfen Last.fm hesabını Last.fm Masaüstü Uygulaması&apos;na bağlamak için web tarayıcında &lt;strong&gt;Evet, Erişime İzin Ver&lt;/strong&gt; düğmesine tıkla.&lt;/p&gt;&lt;p&gt;Tarayıcı penceresini kapattığın veya iptal seçeneğine tıkladığın için bağlanamadıysan, lütfen yeniden dene.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>Last.fm&apos;e bağlanmanızı bekliyoruz</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt;Geri</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>Yeniden Dene</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Web tarayıcınız açılmadıysa, aşağıdaki bağlantıyı adres çubuğunuza kopyalayıp yapıştırın.&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>Klavye Kısayolları:</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>Last.fm&apos;i Göster/Gizle</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>Proxy:</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>SSL Etkinleştir</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>Önbellek Boyutu:</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>Abone</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>Moderatör</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>Görevli</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>Eski eleman</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>Eski eleman</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>Turnede</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Müzik zevkine göre olası en iyi öneriler için, medya çalarından dinleme geçmişini indirmeni öneriyoruz.&lt;/p&gt;&lt;p&gt;Lütfen tercih ettiğin medya çaları seç ve &lt;strong&gt;İçe Aktarmayı Başlat&lt;/strong&gt;&lt;/p&gt;&apos;a tıkla.</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Eklentilerin kurulmamış</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Dosya menüsü üzerinden onları daha sonra yükleyebilirsin</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>Şimdi dinleme geçmişini içeri aktaralım</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>İçe Aktarmayı Başlat</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Atla &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Merak etme, karşıya yükleme süreci müzik arşivinin boyutuna bağlı olarak birkaç dakikadan daha uzun sürmeyecektir.&lt;/p&gt;&lt;p&gt;Biz dinleme geçmişini Last.fm profiline eklemek için çalışırken, neden sen de Last.fm Masaüstü Uygulaması&apos;nın ana özelliklerine göz atmıyorsun? Bir tur atmak için &lt;strong&gt;Devam&lt;/strong&gt;&apos;a tıkla.</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>Uygulamaları Kapat</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>Cihaz skroplama devre dışı - uyumsuz iTunes eklentisi - %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>lütfen güncelleştirin</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod&apos;u skropla</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>%1 cihazının audioscrobbler kullanıcı hesabınla ilişkilendirilmesini istiyor musun?</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>Cihaz başarıyla kullanıcı hesabınla ilişkilendirildi. Şu andan itibaren bu cihazda dinlediğiniz parçaları skroplayabilirsin.</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>%1 parça skroplandı.</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>Son senkronizasyondan bu yana skroplanacak parça yok.</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod veritabanı açılamadı.</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>iPod veritabanına ulaşmaya çalışırken istenmeyen bir hata oluştu.</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Tanı</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Skroplama</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>Bu bir paskalya yumurtası!</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Sanatçı</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>Parça</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Albüm</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>Parmak İzi Kontrolü</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>Son Parmak İzi Kontrolü Yapılmış Parçalar</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod Skroplaması</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>iTunes iPod&apos;umu otomatik olarak yönetiyor</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>iPod&apos;umu manuel olarak yönetiyorum</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod&apos;u skropla</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>Kayıtlar</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>&amp;Kapat</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n yerel önbellekteki parça</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm Masaüstü Uygulaması</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>Teşekkürler &lt;strong&gt;%1&lt;/strong&gt;, hesabın artık bağlandı!</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>İçe aktarılıyor...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>İçe aktarma tamamlandı!</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>Last.fm&apos;de arkadaşlarını bul</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;Henüz Last.fm&apos;de hiç arkadaşınız yok.&lt;/h3&gt;&lt;p&gt;Arkadaş bulucu ile Last.fm kullanan Facebook arkadaşlarını ve e-posta bağlantılarını kolayca ve hızla bul.&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>Kullanıcı adı veya gerçek adıyla bir arkadaşını ara</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>Arkadaşları Yenile</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Yenileniyor...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>%1 Kişisel Radyosu</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>Erkek</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>Şimdi %1 üzerinden skroplanıyor</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>Kadın</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>Şimdi skroplanıyor</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>Cinsiyetsiz</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>Arkadaşlarını ara</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>Arkadaşlarına Göz At</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>Dil:</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>Uygulama simgesini menü çubuğunda göster</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>Uygulamayı medya çalarlarla başlat</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>Yuva simgesini göster</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>Masaüstü bildirimlerini göster</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>Hata raporlarını Last.fm&apos;e gönder</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>Güncellemeleri otomatik olarak denetle</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>Medya tuşlarını etkinleştir</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>Sistem Dili</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>Şİmdi yeniden başlatmak istiyor musun?</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>Değişikliğin etkili olması için uygulamanın yeniden başlatılması gerekiyor. Şimdi yeniden başlatmak istiyor musun?</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>Beta sürümlerine yükselt - Uyarı: Yalnızca cesurlar için!</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>iPod veritabanı açılamadı.</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;%1 gibi bir iOS skroplama uygulamasını kullanmak çifte skroplamaya neden olabilir. Lütfen bunlardan yalnızca birinde skroplamayı etkinleştirin.&lt;/p&gt;&lt;p&gt;iTunes Match çalış sayısını senkronize eder ancak çok sayıda cihaz arasındaki son çalınmaları kaydetmez. Bu yanlış saatlerde ikili skroplamalara neden olur. Şimdilik, iTunes Match kullanıcılarına masaüstü cihazlarda cihaz skroplamasını devre dışı bırakmalarını ve %1 gibi bir iOS skroplama uygulaması kullanarak iPhone/iPod&apos;larını skroplamalarını öneriyoruz.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>Ayarlar değiştirilmedi</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>Bu ayarın değişmesi için iTunes&apos;u kapatmadın</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>Cihaz Skroplamayı Etkinleştir</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>Cihaz Skroplamalarını Onayla</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>Lütfen dikkat</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>Lisanslar</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>Tamam mı?</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>Bu uygulamayı onayladığında Tamam&apos;a bas.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm&apos;in önce senin iznine ihtiyacı var!</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>Bu uygulamanın Last.fm profiline bağlanmak için senin iznine ihtiyacı var. Last.fm web sitesine gitmek için Tamam&apos;a tıkla ve bunu yap.</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Zaten bir Last.fm kullanıcısı mısın? Hesabını Masaüstü Uygulaması ile bağlarsan profilini dinlediğin müziğe göre güncelleyecektir.&lt;/p&gt;&lt;p&gt;Hesabın yoksa, şimdi ücretsiz kayıt olabilirsin.</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>Last.fm hesabını bağlamakla başlayalım</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>Hesabını Bağla</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>Kayıt Ol</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>Proxy?</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>Medya çalar eklentilerin için güncellemeler var. Onları şimdi indirmek ister misin?</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>Eklenti yükleme hatası</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Eklenti(ler)inizi yüklerken bir hata oluştu.&lt;/p&gt;Lütfen daha sonra tekrar deneyin.&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>Eklenti(ler) yüklendi!</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;Eklentiniz yüklendi.&lt;/p&gt;&lt;p&gt;Artık medya oynatıcınızla skroplamaya hazırsınız&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Eklentilerin kurulmamış</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Dosya menüsü üzerinden onları daha sonra yükleyebilirsin</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>Dosya</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>Eklentileri yükle</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>&amp;Çık</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>Görüntüle</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>Last.fm Profilim</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Skroplamalar</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>Yenile</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>Denetimler</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>Hesap</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>Araçlar</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>Güncellemeleri Denetle</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>Tercihler</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>Pencere</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>Küçült</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>Yakınlaştır</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>Tümünü Öne Getir</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>Yardım</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>Hakkında</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>SSS</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>Forumlar</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>Tur</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>Lisansları Göster</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>Tanı</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>&lt;a href=&quot;tracks&quot;&gt;%n çalış&lt;/a&gt; bir cihazdan skroplandı.</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>Skroplamalara Geri Dön</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>Popüler etiketler:</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>Etiketlerin</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>Benzer Sanatçılar</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>%1 tarafından</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>%1 üzerinden</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1 Radyosunu Çal</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>Çalış</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>Arşivindeki çalış</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>Dinleyici</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>%1 veya daha fazlası ile.</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>%1, %2 ve daha fazlası ile.</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>%1 tarihinde düzenlendi | %2 Düzenleme</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>İndirilenler</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>%1 üzerinde ara</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>%1 %2 üzerinden satın al</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Fiziksel</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>%1 dinlediğin için önerildi.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>%1 ve %2 dinlediğiniz için önerildi.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>%1, %2 ve %3 dinlediğiniz için önerildi.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>%1, %2, %3 ve %4 dinlediğiniz için önerildi.</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>%1, %2, %3, %4 ve %5 dinlediğiniz için önerildi.</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>%1 arşivinden.</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>%1 ve %2 arşivlerinden.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 kere</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>%1, %2 ve %3 arşivlerinden.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>%1 %2 ve %3 %4 dinledin.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>%1, %2, %3 ve %4 arşivlerinden.</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>%1 %2 dinledin ama bu parçayı dinlemedin.</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>%1, %2, %3, %4 ve %5 arşivlerinden.</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>İlk defa %1 dinliyorsun.</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>Merhaba!</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>Bir radyo istasyonu başlat</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>iTunes&apos;u Aç</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>Windows Media Player&apos;ı Aç</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>Winamp&apos;ı Aç</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>Foobar&apos;ı Aç</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;Müzik çalarından skropla&lt;/h2&gt;&lt;p&gt;Medya çalarında bazı müzikleri dinlemeye başla. Şimdi Çalıyor sekmesinde çaldığın parçalarla ilgili daha fazla bilgi bulabilirsin.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>Merhaba, %1!</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Radyo İstasyonu</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>%1 Çal</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>Çok Arşivli Radyo</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>İşaret %1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>%1 ve %2 Arşiv Radyosunu Çal</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>%1 ve %2 Arşiv Radyosunu İşaretle</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>Sev</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Engelle</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Çal</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Atla</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>Duraklat</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>Devam et</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>Sevmekten Vazgeç</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>Bağlanıyor</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Radyo İstasyonu</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>Dinliyor</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>Skropluyor</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 çalış</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm medya arşivini aktardı.\n\n Devam etmek için Tamam&apos;a tıkla.</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Last.fm Kütüphane Aktarımı</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>İçe aktarma işlemini iptal etmek istediğinden emin misin?</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm arşivinde çalınmış parça bulamadı.\n\n Devam etmek için Tamam&apos;a tıkla.</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm güncel medya arşivini içe aktarıyor...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Winamp nerede?</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Windows Media Player nerede?</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>Medya Arşivi Aktarımı Tamamlandı</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm dinleme geçmişini sunucuya iletti.\nProfilin, yeni parçalarla birkaç dakika içinde güncellenecek.</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>Kütüphane Aktarımı Başarısız</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>Üzgünüz, Last.fm dinleme geçmişini aktaramadı. Bunun nedeni büyük olasılıkla bugüne kadar zaten çok parça skroplamış olman. Dinleme geçmişi sadece yeni profillere aktarılabilir.</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Lütfen işletim sisteminizde eklentileri yüklemek için görünen talimatları izleyin.&lt;/p&gt;&lt;p&gt;Eklentiler bilgisayarınıza yüklendikten sonra &lt;strong&gt;Devam&lt;/strong&gt;&apos;a tıklayın.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>Eklentileriniz şu anda yükleniyor</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>Eklentilerin kurulmamış</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>Dosya menüsü üzerinden onları daha sonra yükleyebilirsin</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Medya çalarlarının, dinlediğin müziği skroplamak için özel bir Last.fm eklentisine ihtiyacı var.&lt;/p&gt;&lt;p&gt;Lütfen müziğinin skroplanmasını istediğin medya çaları seç ve &lt;strong&gt;Eklentileri Yükle&lt;/strong&gt;&apos;ye tıkla&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>(daha yeni sürüm)</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>(Yeniden yüklemek için eklenti yüklendi işareti)</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>Bir sonraki adımda, dinlediğin müziği skroplayabilmek için Last.fm eklentilerini yükle.</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>Eklentileri Yükle</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>Atla &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>Genel</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>Hesaplar</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>Skroplama</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>Cihazlar</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>Gelişmiş</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 Radyosu</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 çalış</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>Bu Haftanın En Sevilen Sanatçıları</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>Genelde En Sevilen Sanatçılar</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>Skroplama</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>Sevilen parçalar</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 sanatçı</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 parça</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>Arşivinde %1 var ve her gün ortalama %2 dinliyorsun.</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>%1 tarihinden bu yana skroplamalar</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>Proxy Ayarları</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>Ana Bilgisayar:</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>Kullanıcı adı:</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>Port:</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>Parola:</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>bilinmeyen medya çalar</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>iPod&apos;un nereye bağlı?</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>Sanatçı veya etiket yaz ve çal&apos;a tıkla</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Çal</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>%1, %2, %3 veya %4&apos;ü neden denemiyorsun?</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>Bir sonrakini çal</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Radyo İstasyonu</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>Radyo dinlemek için abone olman lazım</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>Son İstasyon</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>Radyo İstasyonu</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>Kişisel İstasyonlar</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>Arşiv Radyom</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>Bildiğin ve sevdiğin müzik</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>Karışık Radyom</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>Arşivin artı yeni müzik</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>Önerilen Radyom</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>Radyo dinlemek için abone ol</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>Last.fm&apos;den yeni müzik</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>Bu uygulamada radyo dinlemek için Last.fm abonesi olman gerekir. Dinlemeye başlamak için şimdi abone ol ve diğer muhteşem imkanlardan da yararlan!</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>Ağ İstasyonları</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>Last.fm&apos;e abone ol</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>www.last.fm sitesinde ücretsiz dinle</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>Arkadaşlarımın Radyosu</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>Arkadaşlarının sevdiği müzik</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>Komşumun Radyosu</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>Sana benzeren dinleyicilerin müzikleri</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>Son İstasyonlar</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>Çalıyor</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>Ayda yalnızca %1 karşılığında radyo dinlemek için abone ol</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>Cihaz Skroplamaları</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>Bu parçaları çalmış gibi görünüyorsun. Onları skroplamak ister misin?</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>Cihazları otomatik olarak skropla</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>Seçimi değiştir</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>Bir cihazdan %n çalış skroplandı</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>Parçayı sev</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>Etiket ekle</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Sev</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Etiket</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Paylaş</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Last.fm&apos;de paylaş</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Twitter&apos;da paylaş</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Facebook&apos;ta paylaş</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Satın al</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>Parçayı Sevmekten Vazgeç</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>Şurada skropla:</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>parçanın yüzdesi</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>Skroplamayı etkinleştir</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>... veya 4 dakikada (hangisi önce gelirse)</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>Podcast&apos;ları skropla</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>Last.fm&apos;in parçalarıma parmak izi kontrolü yapmasına izin ver</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>Seçili dizinler skroplanmayacak</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>Last.fm&apos;de daha fazla skroplama</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>Yenileniyor...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>Skroplamaları Yenile</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>Sanatçı</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>Başlık</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Albüm</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>Çalış</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>Son Çalınma</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>Sevildi</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>Bu parça 30 saniyeden kısa</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>Sanatçı adı eksik</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>Geçersiz parça başlığı</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>Geçersiz sanatçı</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>Zaman etiketi yok</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>Parça çok uzak gelecekte</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>Bu parça iki haftadan önce çalınmış</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>Last.fm&apos;de henüz hiçbir müziği skroplamadın.</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>Medya çalarında biraz müzik dinlemeye başla veya bir radyo istasyonu başlat:</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>Arkadaşlarınla Paylaş</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>Birlikte:</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>Mesaj (isteğe bağlı):</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>son etkinliklerimi dahil et</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>%1 tarafından bir parça</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>%2 yayımından %1 tarafından bir parça</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>%1 öğesine göz at</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>Çalıyor</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>Skroplamalar</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>Profil</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>Arkadaşlar</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>Radyo</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>Sonraki Bölüm</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>Önceki Bölüm</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>%1 radyosu başlatılamadı</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>&quot;%1&quot; için sonuç yok</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>Skroplama kapalı</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>Çevrimiçi</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>Çevrimdışı</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>Etiket</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>Etiketlemek için bir şey seç:</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>İz</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Sanatçı</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Albüm</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>simge</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>Etiket ekle:</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>%1 tarafından bir parça</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>%2 yayımından %1 tarafından bir parça</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>Yukarıya bir etiket yaz.\nveya aşağıdan seç</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>Popülerliğe Göre Sırala</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>Alfabetik Olarak Sırala</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>Bu Etiketin Last.fm Sayfasını Aç</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Artık başlamaya hazırsın! Sadece &lt;strong&gt;Bitir&lt;/strong&gt;&apos;e tıkla ve keşfetmeye başla.&lt;/p&gt;&lt;p&gt;Dinleme geçmişini içe aktarmayı da başardık ve Last.fm profiline ekledik.&lt;/p&gt;&lt;p&gt;Last.fm Masaüstü Uygulamasını yüklediğin için teşekkürler, umarız kullanmaktan zevk alırsın!&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>Bu kadar, başlamaya hazırsın!</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>Son</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Ekranındaki kırmızı ok, sistem tepsindeki Last.fm Masaüstü Uygulaması&apos;nın yerini işaret eder.&lt;/p&gt;&lt;p&gt;Radyo çalma denetimlerine erişmek, parça paylaşmak ve etiketlemek, tercihlerini düzenlemek ve Last.fm profilini ziyaret etmek için simgeye tıkla.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>Menü çubuğundaki Last.fm Masaüstü Uygulaması</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>Sistem tepsindeki Last.fm Masaüstü Uygulaması</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Biyografiler, dinleme istatistikleri, fotoğraflar, benzer sanatçılar ve aynı zamanda dinleyicilerin onları açıklamak için kullandığı etiketler de dahil olmak üzere dinlediğin müzik hakkında daha fazla bilgi edin.&lt;/p&gt;&lt;p&gt;&lt;strong&gt;Şimdi Çalıyor&lt;/strong&gt; sekmesini kontrol et veya daha fazla bilgi için &lt;strong&gt;Skroplamalar&lt;/strong&gt; sekmesindeki herhangi bir parçaya tıkla.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>Sevdiğin daha fazla sanatçıyı keşfet</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Turu Atla &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>Kesintisiz, kişiselleştirilmiş radyo dinle</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Duymak istediğiniz müziği esas alan kişiselleştirilmiş radyo dinlemek için Last.fm Masaüstü Uygulaması&apos;nı kullanın.&lt;/p&gt;&lt;p&gt;Last.fm istasyonunun her çalışı, sanatçılara ve etiketlere dayalı istasyonlardan müzik zevkinize uygun yepyeni önerileri bulunan istasyonlara kadar bambaşkadır.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>Abone olun ve kesintisiz, kişiselleştirilmiş radyo dinleyin</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Last.fm&apos;e abone olun ve duymak istediğiniz müziği esas alan kişiselleştirilmiş radyoyu dinlemek için Last.fm Masaüstü Uygulaması&apos;nı kullanın.&lt;/p&gt;&lt;p&gt;Her bir Last.fm istasyonunun tüm çalışları, sanatçılara ve etiketlere dayalı istasyonlardan müzik zevkinize uygun yepyeni önerileri bulunan istasyonlara kadar bambaşkadır.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abone ol</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>Geri</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Turu Atla &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Masaüstü istemcisi; müzik önerileri, konser ipuçları ve daha fazlasını öğrenmek için kullanabileceğin dinlediğin müzikle Last.fm profilini sessizce güncelleyerek arka planda çalışır.&lt;/p&gt;&lt;p&gt;Last.fm masaüstü uygulamasını, dinlediğin sanatçılar hakkında daha fazla bilgi edinmek ve kişiselleştirilmiş radyonu çalmak için de kullanabilirsin.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>Last.fm Masaüstü Uygulamasına hoş geldin!</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>Devam</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt;Geri</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>Turu Atla &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>İz</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>Albüm</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>Sanatçı</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Sev</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Etiket</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Paylaş</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>Satın al</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>Bu skroplamayı profilinden sil</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>%1 Radyosunu Çal</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>İpucu %1 Radyosu</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1 Radyosu</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>Önbellekte</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>Hata: %1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>Last.fm&apos;de paylaş</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>Twitter&apos;da paylaş</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>Facebook&apos;ta paylaş</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>Şimdi Dinleniyor</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>İndirilenler</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>%1 üzerinde ara</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>%1 %2 üzerinden satın al</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>Fiziksel</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>Bağlı Kullanıcı Hesapları:</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>Yeni Kullanıcı Hesabı Ekle</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>Kullanıcı Hatası Ekle</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>Bu kullanıcı zaten eklendi.</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>%1 Kaldırılıyor</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>Bu kullanıcıyı kaldırmak istediğinden emin misin? Tüm kullanıcı ayarları kaybolacak ve gelecekte skroplama yapabilmek için yeniden kimlik doğrulaması yapman gerekecek.</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>Abone ol</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>Kaldır</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>(şu anda oturum açık)</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>Hesaplar</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>Skroplayıcıyı Göster</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>Sev</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>Çal</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>Atla</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>Etiket</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>Paylaş</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>Engelle</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>Sessiz</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>iPod&apos;u Skropla...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>Last.fm profilini ziyaret et</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>Skroplamayı Etkinleştir</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>%1 Uygulamasından Çık</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>%1 üzerinden</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>Bu istasyonun atlama sınırına eriştin. %n dakika içinde yeniden atla.</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>Bu istasyon için %n atlama kaldı.</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>Kimlik Denetimi Gerekli</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Kullanıcı hesabı&lt;strong&gt;%1&lt;/strong&gt; artık Last.fm&apos;de izinli değil.&lt;/p&gt;&lt;p&gt;Kurulum işlemine başlamak için Tamam&apos;a tıklayın ve bu hesabı yeniden yetkilendirin.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>%1 uygulamasından çıkmak istediğine emin misin?</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 uygulamasından çıkılmak üzere. Devam edersen çalınan parçalar skroplanmayacak.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>Kullanıcı Değiştiriliyor</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 Skroplayıcıda ve Last.fm Radyosunda oturum açacak. Tüm müzikler artık bu hesaba skroplanacak. Devam etmek istiyor musun?</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>Lütfen devam etmek için aşağıdaki uygulamaları kapatın.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>Eklenti yükleme hatası</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;Eklentinizi güncellerken bir hata oluştu.&lt;/p&gt;&lt;p&gt;Lütfen daha sonra tekrar deneyin.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>Eklenti yüklendi!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;%1 eklentisi yüklendi.&lt;/p&gt;&lt;p&gt;Artık %1 ile skroplamaya hazırsınız.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>%1 eklentisi yüklenmedi</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>%1 öğesini kapatmadığından eklentisi yüklenmedi.</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>Eklentiyi güncellemek için iTunes&apos;u kapatın!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;iTunes eklentin (%2), uygulamanın bu sürümüyle gönderilenden (%1) farklı.&lt;/p&gt;&lt;p&gt;Lütfen güncelleştirmek için iTunes&apos;u şimdi kapatın.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>kurulu değil</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>Eklentiniz kurulmamış</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>Eski eklentiyi kaldırırken bir hata oluştu</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes Eklentisi yüklendi!</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;iTunes eklentin yüklendi.&lt;/p&gt;&lt;p&gt;Cihazınızda skroplamaya hazırsınız.&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>Yeni eklentiyi yerine kopyalarken bir hata oluştu</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>iTunes&apos;u kapatmadınız</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>Süre kesildi</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n dakika önce</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n saat önce</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>Ağ hatası oluştu: %1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>Bu uygulamaya izin vermedin</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>Yetkilendirme hatası</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>Stil Sayfasını Yenile</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>Bunu bir daha sorma</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>Otomatik algıla</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>Proxy yok</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "i18n/lastfm_zh_CN.ts",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE TS>\n<TS version=\"2.0\" language=\"zh-CN\">\n<context>\n    <name>AboutDialog</name>\n    <message>\n        <source>About</source>\n        <translation>关于</translation>\n    </message>\n    <message>\n        <source>%1 (built on Qt %2)</source>\n        <translation>%1（基于 Qt %2 制作）</translation>\n    </message>\n</context>\n<context>\n    <name>AccessPage</name>\n    <message>\n        <source>&lt;p&gt;Please click the &lt;strong&gt;Yes, Allow Access&lt;/strong&gt; button in your web browser to connect your Last.fm account to the Last.fm Desktop App.&lt;/p&gt;&lt;p&gt;If you haven&apos;t connected because you closed the browser window or you clicked cancel, please try again.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;请点击浏览器中的&lt;strong&gt;允许访问&lt;/strong&gt;按钮，将您的 Last.fm 帐户连接到 Last.fm 桌面程序。&lt;/p&gt;&lt;p&gt;如果您已关闭浏览器窗口或点击取消而未能连接，请再试一次。&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>We&apos;re waiting for you to connect to Last.fm</source>\n        <translation>我们正等待您连接到 Last.fm</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation> &lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>Try Again</source>\n        <translation>再试一次</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;If your web browser didn&apos;t open, copy and paste the link below into your address bar.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;如果浏览器未启动，请复制以下链接并将其粘贴到浏览器地址栏。&lt;/p&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>AdvancedSettingsWidget</name>\n    <message>\n        <source>Keyboard Shortcuts:</source>\n        <translation>键盘快捷方式：</translation>\n    </message>\n    <message>\n        <source>Raise/Hide Last.fm</source>\n        <translation>显示/隐藏 Last.fm</translation>\n    </message>\n    <message>\n        <source>Proxy:</source>\n        <translation>代理：</translation>\n    </message>\n    <message>\n        <source>Enable SSL</source>\n        <translation>启用 SSL</translation>\n    </message>\n    <message>\n        <source>Cache Size:</source>\n        <translation>缓存大小：</translation>\n    </message>\n</context>\n<context>\n    <name>AvatarWidget</name>\n    <message>\n        <source>Subscriber</source>\n        <translation>付费用户</translation>\n    </message>\n    <message>\n        <source>Moderator</source>\n        <translation>管理员</translation>\n    </message>\n    <message>\n        <source>Staff</source>\n        <translation>员工</translation>\n    </message>\n    <message>\n        <source>Alumna</source>\n        <translation>老友</translation>\n    </message>\n    <message>\n        <source>Alumnus</source>\n        <translation>老友</translation>\n    </message>\n</context>\n<context>\n    <name>BioWidget</name>\n    <message>\n        <source>On Tour</source>\n        <translation>巡演中</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapPage</name>\n    <message>\n        <source>&lt;p&gt;For the best possible recommendations based on your music taste we advise that you import your listening history from your media player.&lt;/p&gt;&lt;p&gt;Please select your preferred media player and click &lt;strong&gt;Start Import&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;要获得最适合您音乐品味的推荐，建议您从媒体播放器导入收听历史。&lt;/p&gt;&lt;p&gt;请选择您最常用的媒体播放器，然后点击&lt;strong&gt;开始导入&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>插件尚未安装</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>稍后可从文件菜单安装插件</translation>\n    </message>\n    <message>\n        <source>iTunes</source>\n        <translation>iTunes</translation>\n    </message>\n    <message>\n        <source>Now let&apos;s import your listening history</source>\n        <translation>现在导入收听历史</translation>\n    </message>\n    <message>\n        <source>Start Import</source>\n        <translation>开始导入</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>跳过 &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>BootstrapProgressPage</name>\n    <message>\n        <source>&lt;p&gt;Don&apos;t worry, the upload process shouldn&apos;t take more than a couple of minutes, depending on the size of your music library.&lt;/p&gt;&lt;p&gt;While we&apos;re hard at work adding your listening history to your Last.fm profile, why don&apos;t you check out the main features of the Last.fm Desktop App. Click &lt;strong&gt;Continue&lt;/strong&gt; to take the tour.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;别担心，上传过程至多只需要几分钟，具体取决于您的音乐库大小，。&lt;/p&gt;&lt;p&gt;趁我们忙着将收听历史添加到您的 Last.fm 专页，去看看 Last.fm 桌面程序有什么主要功能吧。点击&lt;strong&gt;继续&lt;/strong&gt;观看功能介绍。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n</context>\n<context>\n    <name>CloseAppsDialog</name>\n    <message>\n        <source>Close Apps</source>\n        <translation>关闭程序</translation>\n    </message>\n</context>\n<context>\n    <name>DeviceScrobbler</name>\n    <message>\n        <source>Device scrobbling disabled - incompatible iTunes plugin - %1</source>\n        <translation>设备音乐记录已停用 － iTunes 插件不兼容 － %1</translation>\n    </message>\n    <message>\n        <source>please update</source>\n        <translation>请更新</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>iPod 音乐记录</translation>\n    </message>\n    <message>\n        <source>Do you want to associate the device %1 to your audioscrobbler user account?</source>\n        <translation>要将 %1 设备关联到 audioscrobbler 帐户吗？</translation>\n    </message>\n    <message>\n        <source>Device successfully associated to your user account. From now on you can scrobble the tracks you listen on this device.</source>\n        <translation>设备与帐户成功关联。从现在起，在这台设备上收听的内容可以记录到帐户了。</translation>\n    </message>\n    <message>\n        <source>%1 tracks scrobbled.</source>\n        <translation>记录了 %1 首单曲。</translation>\n    </message>\n    <message>\n        <source>No tracks to scrobble since your last sync.</source>\n        <translation>上次同步后还未记录任何单曲。</translation>\n    </message>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>无法打开 iPod 数据库。</translation>\n    </message>\n    <message>\n        <source>An unknown error occurred while trying to access the iPod database.</source>\n        <translation>访问 iPod 数据库时发生未知错误。</translation>\n    </message>\n</context>\n<context>\n    <name>DiagnosticsDialog</name>\n    <message>\n        <source>Diagnostics</source>\n        <translation>诊断</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>音乐记录</translation>\n    </message>\n    <message>\n        <source>This is an easter egg!</source>\n        <translation>发现新大陆！</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>艺术家</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>曲目</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>专辑</translation>\n    </message>\n    <message>\n        <source>Fingerprinting</source>\n        <translation>指纹识别</translation>\n    </message>\n    <message>\n        <source>Recently Fingerprinted Tracks</source>\n        <translation>最近经过指纹识别的曲目</translation>\n    </message>\n    <message>\n        <source>iPod Scrobbling</source>\n        <translation>iPod 音乐记录</translation>\n    </message>\n    <message>\n        <source>iTunes automatically manages my iPod</source>\n        <translation>由 iTunes 自动管理 iPod</translation>\n    </message>\n    <message>\n        <source>I manually manage my iPod</source>\n        <translation>手动管理 iPod</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod</source>\n        <translation>从 iPod 记录歌曲</translation>\n    </message>\n    <message>\n        <source>Logs</source>\n        <translation>日志</translation>\n    </message>\n    <message>\n        <source>&amp;Close</source>\n        <translation>关闭(&amp;C)</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n locally cached track(s)</source>\n        <translation>\n            <numerusform>%n 首在本地缓存的单曲</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>FirstRunWizard</name>\n    <message>\n        <source>Last.fm Desktop App</source>\n        <translation>Last.fm 桌面程序</translation>\n    </message>\n    <message>\n        <source>Thanks &lt;strong&gt;%1&lt;/strong&gt;, your account is now connected!</source>\n        <translation>谢谢您，&lt;strong&gt;%1&lt;/strong&gt;，帐户已连接！</translation>\n    </message>\n    <message>\n        <source>Importing...</source>\n        <translation>导入中...</translation>\n    </message>\n    <message>\n        <source>Import complete!</source>\n        <translation>导入完成！</translation>\n    </message>\n</context>\n<context>\n    <name>FriendListWidget</name>\n    <message>\n        <source>Find your friends on Last.fm</source>\n        <translation>在 Last.fm 上寻找好友</translation>\n    </message>\n    <message>\n        <source>&lt;h3&gt;You haven&apos;t made any friends on Last.fm yet.&lt;/h3&gt;&lt;p&gt;Find your Facebook friends and email contacts on Last.fm quickly and easily using the friend finder.&lt;/p&gt;</source>\n        <translation>&lt;h3&gt;您尚未在 Last.fm 上结交任何好友。&lt;/h3&gt;&lt;p&gt;使用好友搜索功能，可以在 Last.fm 上轻松找到 Facebook 好友和电邮联系人。&lt;p /&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Search for a friend by username or real name</source>\n        <translation>通过用户名或真名搜索好友</translation>\n    </message>\n    <message>\n        <source>Refresh Friends</source>\n        <translation>刷新好友</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>正在刷新...</translation>\n    </message>\n</context>\n<context>\n    <name>FriendWidget</name>\n    <message>\n        <source>%1&apos;s Library Radio</source>\n        <translation>%1的音乐库电台</translation>\n    </message>\n    <message>\n        <source>Male</source>\n        <translation>男</translation>\n    </message>\n    <message>\n        <source>Scrobbling now from %1</source>\n        <translation>正从 %1 记录音乐</translation>\n    </message>\n    <message>\n        <source>Female</source>\n        <translation>女</translation>\n    </message>\n    <message>\n        <source>Scrobbling now</source>\n        <translation>正在记录音乐</translation>\n    </message>\n    <message>\n        <source>Neuter</source>\n        <translation>中性</translation>\n    </message>\n</context>\n<context>\n    <name>FriendsPicker</name>\n    <message>\n        <source>Search your friends</source>\n        <translation>搜索好友</translation>\n    </message>\n    <message>\n        <source>Browse Friends</source>\n        <translation>浏览好友</translation>\n    </message>\n</context>\n<context>\n    <name>GeneralSettingsWidget</name>\n    <message>\n        <source>Language:</source>\n        <translation>语言：</translation>\n    </message>\n    <message>\n        <source>Show application icon in menu bar</source>\n        <translation>在菜单栏中显示应用程序图标</translation>\n    </message>\n    <message>\n        <source>Launch application with media players</source>\n        <translation>随媒体播放器启动程序</translation>\n    </message>\n    <message>\n        <source>Show dock icon</source>\n        <translation>显示 Dock 图标</translation>\n    </message>\n    <message>\n        <source>Show desktop notifications</source>\n        <translation>显示桌面通知</translation>\n    </message>\n    <message>\n        <source>Send crash reports to Last.fm</source>\n        <translation>向 Last.fm 发送程序崩溃报告</translation>\n    </message>\n    <message>\n        <source>Check for updates automatically</source>\n        <translation>自动检查更新</translation>\n    </message>\n    <message>\n        <source>Enable media keys</source>\n        <translation>启用媒体密钥</translation>\n    </message>\n    <message>\n        <source>System Language</source>\n        <translation>系统语言</translation>\n    </message>\n    <message>\n        <source>Restart now?</source>\n        <translation>现在重启？</translation>\n    </message>\n    <message>\n        <source>An application restart is required for the change to take effect. Would you like to restart now?</source>\n        <translation>要使更改生效，需要重启程序。要现在重启程序？</translation>\n    </message>\n    <message>\n        <source>Update to beta versions - Warning: only for the brave!</source>\n        <translation>更新到测试版 － 注意：这是勇敢者的游戏！</translation>\n    </message>\n</context>\n<context>\n    <name>IpodDeviceLinux</name>\n    <message>\n        <source>The iPod database could not be opened.</source>\n        <translation>无法打开 iPod 数据库。</translation>\n    </message>\n</context>\n<context>\n    <name>IpodSettingsWidget</name>\n    <message>\n        <source>&lt;p&gt;Using an iOS scrobbling app, like %1, may result in double scrobbles. Please only enable scrobbling in one of them.&lt;/p&gt;&lt;p&gt;iTunes Match synchronises play counts, but not last played times, across multiple devices. This will lead to duplicate scrobbles, at incorrect times. For now, we recommend iTunes Match users disable device scrobbling on desktop devices and scrobble iPhones/iPods using an iOS scrobbling app, like %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;使用 iOS 音乐记录程序（如 %1）可能导致双重记录。请仅在其中一个程序中启用音乐记录。&lt;/p&gt;\n&lt;p&gt;iTunes Match 在多部设备上同步播放次数，但不同步上次播放时间，因此会造成时间不正确的重复记录。目前我们建议 iTunes Match 用户在桌面设备上停用设备记录功能，然后使用一款 iOS 音乐记录程序（如 %1）记录 iPhone/iPod 上播放的音乐。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Setting not changed</source>\n        <translation>设置未更改</translation>\n    </message>\n    <message>\n        <source>You did not close iTunes for this setting to change</source>\n        <translation>您未关闭 iTunes，因此设置未更改</translation>\n    </message>\n    <message>\n        <source>Enable Device Scrobbling</source>\n        <translation>启用设备音乐记录</translation>\n    </message>\n    <message>\n        <source>Confirm Device Scrobbles</source>\n        <translation>确认设备音乐记录</translation>\n    </message>\n    <message>\n        <source>Please note</source>\n        <translation>请注意</translation>\n    </message>\n</context>\n<context>\n    <name>LicensesDialog</name>\n    <message>\n        <source>Licenses</source>\n        <translation>许可</translation>\n    </message>\n</context>\n<context>\n    <name>LoginContinueDialog</name>\n    <message>\n        <source>Are we done?</source>\n        <translation>好了吗？</translation>\n    </message>\n    <message>\n        <source>Click OK once you have approved this app.</source>\n        <translation>请在授权此程序后点击“确定”。</translation>\n    </message>\n</context>\n<context>\n    <name>LoginDialog</name>\n    <message>\n        <source>Last.fm needs your permission first!</source>\n        <translation>Last.fm 需要您的许可！</translation>\n    </message>\n    <message>\n        <source>This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.</source>\n        <translation>在连接到您的 Last.fm 专页前，此程序需要获得您的许可。请点击“确认”前往 Last.fm 网站进行相关操作。</translation>\n    </message>\n</context>\n<context>\n    <name>LoginPage</name>\n    <message>\n        <source>&lt;p&gt;Already a Last.fm user? Connect your account with the Last.fm Desktop App and it&apos;ll update your profile with the music you&apos;re listening to.&lt;/p&gt;&lt;p&gt;If you don&apos;t have an account you can sign up now for free now.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;已经是 Last.fm 用户了？将 Last.fm 桌面程序连接到帐户吧，这样您收听的音乐就会更新到专页。&lt;/p&gt;&lt;p&gt;还没有帐户？马上免费注册。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Let&apos;s get started by connecting your Last.fm account</source>\n        <translation>我们首先来连接您的 Last.fm 帐户</translation>\n    </message>\n    <message>\n        <source>Connect Your Account</source>\n        <translation>连接帐户</translation>\n    </message>\n    <message>\n        <source>Sign up</source>\n        <translation>注册</translation>\n    </message>\n    <message>\n        <source>Proxy?</source>\n        <translation>代理？</translation>\n    </message>\n</context>\n<context>\n    <name>MainWindow</name>\n    <message>\n        <source>There are updates to your media player plugins. Would you like to install them now?</source>\n        <translation>您的媒体播放器插件有更新，想现在安装吗？</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin install error</source>\n        <translation>\n            <numerusform>插件安装错误</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;There was an error updating your plugin(s).&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;更新插件时发生错误。&lt;/p&gt;&lt;p&gt;请稍后再试。&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Plugin(s) installed!</source>\n        <translation>\n            <numerusform>插件安装完毕！</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;p&gt;Your plugin(s) ha(s|ve) been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with your media player(s)&lt;/p&gt;</source>\n        <translation>\n            <numerusform>&lt;p&gt;插件安装完毕。&lt;/p&gt;&lt;p&gt;现在可以用媒体播放器记录音乐了。&lt;/p&gt;</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>还没安装插件</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>稍后可从文件菜单安装插件</translation>\n    </message>\n    <message>\n        <source>File</source>\n        <translation>文件</translation>\n    </message>\n    <message>\n        <source>Install plugins</source>\n        <translation>安装插件</translation>\n    </message>\n    <message>\n        <source>&amp;Quit</source>\n        <translation>退出(&amp;Q)</translation>\n    </message>\n    <message>\n        <source>View</source>\n        <translation>视图</translation>\n    </message>\n    <message>\n        <source>My Last.fm Profile</source>\n        <translation>我的 Last.fm 专页</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>音乐记录</translation>\n    </message>\n    <message>\n        <source>Refresh</source>\n        <translation>刷新</translation>\n    </message>\n    <message>\n        <source>Controls</source>\n        <translation>控制</translation>\n    </message>\n    <message>\n        <source>Account</source>\n        <translation>帐户</translation>\n    </message>\n    <message>\n        <source>Tools</source>\n        <translation>工具</translation>\n    </message>\n    <message>\n        <source>Check for Updates</source>\n        <translation>检查更新</translation>\n    </message>\n    <message>\n        <source>Options</source>\n        <translation>选项</translation>\n    </message>\n    <message>\n        <source>Window</source>\n        <translation>窗口</translation>\n    </message>\n    <message>\n        <source>Minimize</source>\n        <translation>最小化</translation>\n    </message>\n    <message>\n        <source>Zoom</source>\n        <translation>缩放</translation>\n    </message>\n    <message>\n        <source>Bring All to Front</source>\n        <translation>前置全部窗口</translation>\n    </message>\n    <message>\n        <source>Help</source>\n        <translation>帮助</translation>\n    </message>\n    <message>\n        <source>About</source>\n        <translation>关于</translation>\n    </message>\n    <message>\n        <source>FAQ</source>\n        <translation>常见问题</translation>\n    </message>\n    <message>\n        <source>Forums</source>\n        <translation>论坛</translation>\n    </message>\n    <message>\n        <source>Tour</source>\n        <translation>功能介绍</translation>\n    </message>\n    <message>\n        <source>Show Licenses</source>\n        <translation>显示许可证</translation>\n    </message>\n    <message>\n        <source>Diagnostics</source>\n        <translation>诊断</translation>\n    </message>\n    <message>\n        <source>%1 - %2 - %3</source>\n        <translation>%1 - %2 - %3</translation>\n    </message>\n    <message>\n        <source>%1 - %2</source>\n        <translation>%1 - %2</translation>\n    </message>\n    <message>\n        <source>%1</source>\n        <translation>%1</translation>\n    </message>\n    <message>\n        <source>%1: %2</source>\n        <translation>%1: %2</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>&lt;a href=&quot;tracks&quot;&gt;%n play(s)&lt;/a&gt; ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>已从设备记录 &lt;a href=&quot;tracks&quot;&gt;%n 次播放&lt;/a&gt;</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>MetadataWidget</name>\n    <message>\n        <source>Back to Scrobbles</source>\n        <translation>返回音乐记录</translation>\n    </message>\n    <message>\n        <source>Popular tags:</source>\n        <translation>热门标签：</translation>\n    </message>\n    <message>\n        <source>Your tags:</source>\n        <translation>您的标签：</translation>\n    </message>\n    <message>\n        <source>Similar Artists</source>\n        <translation>相似艺术家</translation>\n    </message>\n    <message>\n        <source>by %1</source>\n        <translation>艺术家：%1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>专辑：%1</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>播放%1电台</translation>\n    </message>\n    <message>\n        <source>%L1</source>\n        <translation>%L1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s)</source>\n        <translation>\n            <numerusform>次播放</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Play(s) in your library</source>\n        <translation>\n            <numerusform>次播放（在音乐库中）</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Listener(s)</source>\n        <translation>\n            <numerusform>位听众</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>With %1 and more.</source>\n        <translation>包括%1等艺术家。</translation>\n    </message>\n    <message>\n        <source>With %1, %2 and more.</source>\n        <translation>包括%1、%2等艺术家。</translation>\n    </message>\n    <message>\n        <source> %1</source>\n        <translation> %1</translation>\n    </message>\n    <message>\n        <source> %1 %2</source>\n        <translation> %1 %2</translation>\n    </message>\n    <message>\n        <source>Edited on %1 | %2 Edit</source>\n        <translation>编辑时间 %1 | %2 编辑</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>下载</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>在 %1 上搜索</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>到 %1 %2 购买</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1.</source>\n        <translation>因为您收听%1，所以向您推荐这位艺术家。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1 and %2.</source>\n        <translation>因为您收听%1和%2，所以向您推荐这位艺术家。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, and %3.</source>\n        <translation>因为您收听%1、%2和%3，所以向您推荐这位艺术家。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, and %4.</source>\n        <translation>因为您收听%1、%2、%3和%4，所以向您推荐这位艺术家。</translation>\n    </message>\n    <message>\n        <source>Recommended because you listen to %1, %2, %3, %4, and %5.</source>\n        <translation>因为您收听%1、%2、%3、%4和%5，所以向您推荐这位艺术家。</translation>\n    </message>\n    <message>\n        <source>From %1&apos;s library.</source>\n        <translation>选自%1的音乐库。</translation>\n    </message>\n    <message>\n        <source>From %1 and %2&apos;s libraries.</source>\n        <translation>选自%1和%2的音乐库。</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 time(s)</source>\n        <translation>\n            <numerusform>%L1 次</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>From %1, %2, and %3&apos;s libraries.</source>\n        <translation>选自%1、%2和%3的音乐库。</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2 and %3 %4.</source>\n        <translation>您收听过%1 %2，%3 %4。</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, and %4&apos;s libraries.</source>\n        <translation>选自%1、%2、%3和%4的音乐库。</translation>\n    </message>\n    <message>\n        <source>You&apos;ve listened to %1 %2, but not this track.</source>\n        <translation>您收听过%1 %2，但不是这首单曲。</translation>\n    </message>\n    <message>\n        <source>From %1, %2, %3, %4, and %5&apos;s libraries.</source>\n        <translation>选自%1、%2、%3、%4和%5的音乐库。</translation>\n    </message>\n    <message>\n        <source>This is the first time you&apos;ve listened to %1.</source>\n        <translation>这是您第一次收听%1。</translation>\n    </message>\n</context>\n<context>\n    <name>NothingPlayingWidget</name>\n    <message>\n        <source>Hello!</source>\n        <translation>您好！</translation>\n    </message>\n    <message>\n        <source>Start a radio station</source>\n        <translation>开始收听电台</translation>\n    </message>\n    <message>\n        <source>Open iTunes</source>\n        <translation>打开 iTunes</translation>\n    </message>\n    <message>\n        <source>Open Music</source>\n        <translation>打开 Music</translation>\n    </message>\n    <message>\n        <source>Open Windows Media Player</source>\n        <translation>打开 Windows Media Player</translation>\n    </message>\n    <message>\n        <source>Open Winamp</source>\n        <translation>打开 Winamp</translation>\n    </message>\n    <message>\n        <source>Open Foobar</source>\n        <translation>打开 Foobar</translation>\n    </message>\n    <message>\n        <source>&lt;h2&gt;Scrobble from your music player&lt;/h2&gt;&lt;p&gt;Start listening to some music in your media player. You can see more information about the tracks you play on the Now Playing tab.&lt;/p&gt;</source>\n        <translation>&lt;h2&gt;从您的音乐播放器记录音乐&lt;/h2&gt;&lt;p&gt;在媒体播放器中播放些音乐，其详细信息会显示在“正在播放”页面。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Hello, %1!</source>\n        <translation>%1，您好！</translation>\n    </message>\n</context>\n<context>\n    <name>PlayableItemWidget</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>电台</translation>\n    </message>\n    <message>\n        <source>Play %1</source>\n        <translation>播放%1</translation>\n    </message>\n    <message>\n        <source>Multi-Library Radio</source>\n        <translation>多音乐库电台</translation>\n    </message>\n    <message>\n        <source>Cue %1</source>\n        <translation>接下来播放%1</translation>\n    </message>\n    <message>\n        <source>Play %1 and %2 Library Radio</source>\n        <translation>播放 %1 和 %2 音乐库电台</translation>\n    </message>\n    <message>\n        <source>Cue %1 and %2 Library Radio</source>\n        <translation>接下来播放%1和%2音乐库电台</translation>\n    </message>\n</context>\n<context>\n    <name>PlaybackControlsWidget</name>\n    <message>\n        <source>Love</source>\n        <translation>喜欢</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>禁止</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>播放</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>跳过</translation>\n    </message>\n    <message>\n        <source>Pause</source>\n        <translation>暂停</translation>\n    </message>\n    <message>\n        <source>Resume</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>Unlove</source>\n        <translation>不喜欢</translation>\n    </message>\n    <message>\n        <source>Tuning</source>\n        <translation>正在找台</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>某电台</translation>\n    </message>\n    <message>\n        <source>Listening to</source>\n        <translation>正在收听</translation>\n    </message>\n    <message>\n        <source>Scrobbling from</source>\n        <translation>记录自</translation>\n    </message>\n    <message>\n        <source>Scrobble meter: %1%</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Not scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Enable scrobbling by getting the %1.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Last.fm app for Spotify</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Scrobbled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>Error: &quot;%1&quot;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>PlaysLabel</name>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 次播放</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>PluginBootstrapper</name>\n    <message>\n        <source>Last.fm has imported your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm 已经导入了您的媒体库。\n\n单击“确定”继续。</translation>\n    </message>\n    <message>\n        <source>Last.fm Library Import</source>\n        <translation>Last.fm 媒体库导入</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to cancel the import?</source>\n        <translation>确定要取消导入吗？</translation>\n    </message>\n    <message>\n        <source>Last.fm couldn&apos;t find any played tracks in your media library.\n\n Click OK to continue.</source>\n        <translation>Last.fm 无法在媒体库中找到任何已播放曲目。\n\n单击“确定”继续。</translation>\n    </message>\n    <message>\n        <source>Last.fm is importing your current media library...</source>\n        <translation>Last.fm 正在导入当前媒体库...</translation>\n    </message>\n    <message>\n        <source>Where is Winamp?</source>\n        <translation>Winamp 在何处？</translation>\n    </message>\n    <message>\n        <source>Where is Windows Media Player?</source>\n        <translation>Windows Media Player 在何处？</translation>\n    </message>\n    <message>\n        <source>Media Library Import Complete</source>\n        <translation>媒体库导入完毕</translation>\n    </message>\n    <message>\n        <source>Last.fm has submitted your listening history to the server.\nYour profile will be updated with the new tracks in a few minutes.</source>\n        <translation>Last.fm 已将您的收听历史提交到服务器。\n新曲目将在几分钟后更新到您的专页。</translation>\n    </message>\n    <message>\n        <source>Library Import Failed</source>\n        <translation>媒体库导入失败</translation>\n    </message>\n    <message>\n        <source>Sorry, Last.fm was unable to import your listening history. This is probably because you&apos;ve already scrobbled too many tracks. Listening history can only be imported to brand new profiles.</source>\n        <translation>真遗憾，Last.fm 未能导入您的收听历史。这可能是由于您已经记录了太多的歌曲。收听历史只能导入到新注册的专页。</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsInstallPage</name>\n    <message>\n        <source>&lt;p&gt;Please follow the instructions that appear from your operating system to install the plugins.&lt;/p&gt;&lt;p&gt;Once the plugins have been installed on you computer, click &lt;strong&gt;Continue&lt;/strong&gt;.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;请按操作系统的提示安装插件。&lt;/p&gt;&lt;p&gt;安装完毕后，点击&lt;strong&gt;继续&lt;/strong&gt;。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Your plugins are now being installed</source>\n        <translation>正在安装插件</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Your plugins haven&apos;t been installed</source>\n        <translation>还没安装插件</translation>\n    </message>\n    <message>\n        <source>You can install them later through the file menu</source>\n        <translation>稍后可从文件菜单安装插件</translation>\n    </message>\n</context>\n<context>\n    <name>PluginsPage</name>\n    <message>\n        <source>&lt;p&gt;Your media players need a special Last.fm plugin to be able to scrobble the music you listen to.&lt;/p&gt;&lt;p&gt;Please select the media players that you would like to scrobble your music from and click &lt;strong&gt;Install Plugins&lt;/strong&gt;&lt;/p&gt;</source>\n        <translation>&lt;p&gt;要记录播放的音乐，您的媒体播放器需要一个 Last.fm 专用插件。&lt;/p&gt;&lt;p&gt;请选择要用来记录音乐的媒体播放器，然后点击&lt;strong&gt;安装插件&lt;/strong&gt;&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>(newer version)</source>\n        <translation>（更新版本）</translation>\n    </message>\n    <message>\n        <source>(Plugin installed tick to reinstall)</source>\n        <translation>（插件已安装，选择后重新安装）</translation>\n    </message>\n    <message>\n        <source>Next step, install the Last.fm plugins to be able to scrobble the music you listen to.</source>\n        <translation>下一步，请安装 Last.fm 插件，以便记录您收听的音乐。</translation>\n    </message>\n    <message>\n        <source>Install Plugins</source>\n        <translation>安装插件</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Skip &gt;&gt;</source>\n        <translation>跳过 &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>PreferencesDialog</name>\n    <message>\n        <source>General</source>\n        <translation>常规</translation>\n    </message>\n    <message>\n        <source>Accounts</source>\n        <translation>帐户</translation>\n    </message>\n    <message>\n        <source>Scrobbling</source>\n        <translation>音乐记录</translation>\n    </message>\n    <message>\n        <source>Devices</source>\n        <translation>设备</translation>\n    </message>\n    <message>\n        <source>Advanced</source>\n        <translation>高级</translation>\n    </message>\n</context>\n<context>\n    <name>ProfileArtistWidget</name>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1电台</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 play(s)</source>\n        <translation>\n            <numerusform>%L1 次播放</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProfileWidget</name>\n    <message>\n        <source>Top Artists This Week</source>\n        <translation>本周最佳艺术家</translation>\n    </message>\n    <message>\n        <source>Top Artists Overall</source>\n        <translation>整体最佳艺术家</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s)</source>\n        <translation>\n            <numerusform>次记录</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Loved track(s)</source>\n        <translation>\n            <numerusform>首喜爱曲目</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 artist(s)</source>\n        <translation>\n            <numerusform>%L1 位艺术家</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%L1 track(s)</source>\n        <translation>\n            <numerusform>%L1 首曲目</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>You have %1 in your library and on average listen to %2 per day.</source>\n        <translation>您的音乐库中有 %1，平均每天收听 %2。</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>Scrobble(s) since %1</source>\n        <translation>\n            <numerusform>次记录（自 %1）</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>ProxyDialog</name>\n    <message>\n        <source>Proxy Settings</source>\n        <translation>代理设置</translation>\n    </message>\n</context>\n<context>\n    <name>ProxyWidget</name>\n    <message>\n        <source>Host:</source>\n        <translation>主机：</translation>\n    </message>\n    <message>\n        <source>Username:</source>\n        <translation>用户名：</translation>\n    </message>\n    <message>\n        <source>Port:</source>\n        <translation>端口：</translation>\n    </message>\n    <message>\n        <source>Password:</source>\n        <translation>密码：</translation>\n    </message>\n</context>\n<context>\n    <name>QObject</name>\n    <message>\n        <source>unknown media player</source>\n        <translation>无法识别的媒体播放器</translation>\n    </message>\n    <message>\n        <source>Where is your iPod mounted?</source>\n        <translation>您的 iPod 安装在何处？</translation>\n    </message>\n</context>\n<context>\n    <name>QuickStartWidget</name>\n    <message>\n        <source>Type an artist or tag and press play</source>\n        <translation>输入艺术家名称或标签，然后按右边的播放按钮</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>播放</translation>\n    </message>\n    <message>\n        <source>Why not try %1, %2, %3 or %4?</source>\n        <translation>试试%1、%2、%3或%4吧！</translation>\n    </message>\n    <message>\n        <source>Play next</source>\n        <translation>播放下一首</translation>\n    </message>\n</context>\n<context>\n    <name>RadioService</name>\n    <message>\n        <source>A Radio Station</source>\n        <translation>某电台</translation>\n    </message>\n    <message>\n        <source>You need to be a subscriber to listen to radio</source>\n        <translation>付费用户才能收听电台</translation>\n    </message>\n</context>\n<context>\n    <name>RadioWidget</name>\n    <message>\n        <source>Last Station</source>\n        <translation>上次收听的电台</translation>\n    </message>\n    <message>\n        <source>A Radio Station</source>\n        <translation>某电台</translation>\n    </message>\n    <message>\n        <source>Personal Stations</source>\n        <translation>个人电台</translation>\n    </message>\n    <message>\n        <source>My Library Radio</source>\n        <translation>音乐库电台</translation>\n    </message>\n    <message>\n        <source>Music you know and love</source>\n        <translation>您收听过的和喜爱的音乐</translation>\n    </message>\n    <message>\n        <source>My Mix Radio</source>\n        <translation>混合电台</translation>\n    </message>\n    <message>\n        <source>Your library plus new music</source>\n        <translation>音乐库与新音乐</translation>\n    </message>\n    <message>\n        <source>My Recommended Radio</source>\n        <translation>推荐电台</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio</source>\n        <translation>成为付费用户以收听电台</translation>\n    </message>\n    <message>\n        <source>New music from Last.fm</source>\n        <translation>来自 Last.fm 的新音乐</translation>\n    </message>\n    <message>\n        <source>You need to be a Last.fm subscriber to listen to radio in this app. Subscribe now to start listening and take advantage of other great benefits too!</source>\n        <translation>只有 Last.fm 付费用户才能通过此应用程序收听电台。现在就订购服务吧，马上可以收听电台，同时获得其它更酷的功能！</translation>\n    </message>\n    <message>\n        <source>Network Stations</source>\n        <translation>社交圈电台</translation>\n    </message>\n    <message>\n        <source>Subscribe to Last.fm</source>\n        <translation>成为 Last.fm 付费用户</translation>\n    </message>\n    <message>\n        <source>Listen free on www.last.fm</source>\n        <translation>在 www.last.fm 免费收听</translation>\n    </message>\n    <message>\n        <source>My Friends&apos; Radio</source>\n        <translation>好友电台</translation>\n    </message>\n    <message>\n        <source>Music your friends like</source>\n        <translation>好友喜欢的音乐</translation>\n    </message>\n    <message>\n        <source>My Neighbourhood Radio</source>\n        <translation>邻居电台</translation>\n    </message>\n    <message>\n        <source>Music from listeners like you</source>\n        <translation>来自相似听众的音乐</translation>\n    </message>\n    <message>\n        <source>Recent Stations</source>\n        <translation>最近收听的电台</translation>\n    </message>\n    <message>\n        <source>Now Playing</source>\n        <translation>正在播放</translation>\n    </message>\n    <message>\n        <source>Subscribe to listen to radio, only %1 a month</source>\n        <translation>成为付费用户以收听电台，每月只需 %1</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleConfirmationDialog</name>\n    <message>\n        <source>Device Scrobbles</source>\n        <translation>设备音乐记录</translation>\n    </message>\n    <message>\n        <source>It looks like you&apos;ve played these tracks. Would you like to scrobble them?</source>\n        <translation>您好像播放了这些歌曲，想记录到专页吗？</translation>\n    </message>\n    <message>\n        <source>Scrobble devices automatically</source>\n        <translation>自动记录设备播放的音乐</translation>\n    </message>\n    <message>\n        <source>Toggle selection</source>\n        <translation>切换选择</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n play(s) ha(s|ve) been scrobbled from a device</source>\n        <translation>\n            <numerusform>已从设备记录过 %n 次播放</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleControls</name>\n    <message>\n        <source>Love track</source>\n        <translation>标为喜爱</translation>\n    </message>\n    <message>\n        <source>Add tags</source>\n        <translation>添加标签</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>喜欢</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>标签</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>分享</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>分享到 Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>分享到 Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>分享到 Facebook</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>购买</translation>\n    </message>\n    <message>\n        <source>Unlove track</source>\n        <translation>取消喜爱</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobbleSettingsWidget</name>\n    <message>\n        <source>Scrobble at</source>\n        <translation>记录开始于</translation>\n    </message>\n    <message>\n        <source>percent of the track</source>\n        <translation>（占歌曲总长度的百分比）</translation>\n    </message>\n    <message>\n        <source>Enable scrobbling</source>\n        <translation>启用音乐记录</translation>\n    </message>\n    <message>\n        <source>...or at 4 minutes (whichever comes first)</source>\n        <translation>... 或在 4 分钟时（以先到者为准）</translation>\n    </message>\n    <message>\n        <source>Scrobble podcasts</source>\n        <translation>记录播客</translation>\n    </message>\n    <message>\n        <source>Allow Last.fm to fingerprint my tracks</source>\n        <translation>允许 Last.fm 对曲目进行指纹识别</translation>\n    </message>\n    <message>\n        <source>Selected directories will not be scrobbled</source>\n        <translation>不会记录选中目录中的音乐</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesListWidget</name>\n    <message>\n        <source>More Scrobbles at Last.fm</source>\n        <translation>在 Last.fm 查看更多音乐记录</translation>\n    </message>\n    <message>\n        <source>Refreshing...</source>\n        <translation>正在刷新...</translation>\n    </message>\n    <message>\n        <source>Refresh Scrobbles</source>\n        <translation>刷新音乐记录</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesModel</name>\n    <message>\n        <source>Artist</source>\n        <translation>艺术家</translation>\n    </message>\n    <message>\n        <source>Title</source>\n        <translation>标题</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>专辑</translation>\n    </message>\n    <message>\n        <source>Plays</source>\n        <translation>次播放</translation>\n    </message>\n    <message>\n        <source>Last Played</source>\n        <translation>上次播放</translation>\n    </message>\n    <message>\n        <source>Loved</source>\n        <translation>已标为喜爱</translation>\n    </message>\n    <message>\n        <source>This track is under 30 seconds</source>\n        <translation>该曲不足 30 秒</translation>\n    </message>\n    <message>\n        <source>The artist name is missing</source>\n        <translation>缺少艺术家名称</translation>\n    </message>\n    <message>\n        <source>Invalid track title</source>\n        <translation>歌曲名错误</translation>\n    </message>\n    <message>\n        <source>Invalid artist</source>\n        <translation>艺术家无效</translation>\n    </message>\n    <message>\n        <source>There is no timestamp</source>\n        <translation>缺少时间信息</translation>\n    </message>\n    <message>\n        <source>This track is too far in the future</source>\n        <translation>记录时间不应在未来日期</translation>\n    </message>\n    <message>\n        <source>This track was played over two weeks ago</source>\n        <translation>这首歌曲两周前播放过</translation>\n    </message>\n</context>\n<context>\n    <name>ScrobblesWidget</name>\n    <message>\n        <source>You haven&apos;t scrobbled any music to Last.fm yet.</source>\n        <translation>您还未向 Last.fm 记录过音乐。</translation>\n    </message>\n    <message>\n        <source>Start listening to some music in your media player or start a radio station:</source>\n        <translation>用媒体播放器收听些歌曲，或开始播放电台：</translation>\n    </message>\n</context>\n<context>\n    <name>ShareDialog</name>\n    <message>\n        <source>Share with Friends</source>\n        <translation>同好友分享</translation>\n    </message>\n    <message>\n        <source>With:</source>\n        <translation>分享给：</translation>\n    </message>\n    <message>\n        <source>Message (optional):</source>\n        <translation>附言（可选）：</translation>\n    </message>\n    <message>\n        <source>include in my recent activity</source>\n        <translation>更新到我的最近活动</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>由%1演唱的单曲</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>由%1演唱的单曲，来自专辑%2</translation>\n    </message>\n    <message>\n        <source>Check out %1</source>\n        <translation>快来听听%1</translation>\n    </message>\n</context>\n<context>\n    <name>SideBar</name>\n    <message>\n        <source>Now Playing</source>\n        <translation>正在播放</translation>\n    </message>\n    <message>\n        <source>Scrobbles</source>\n        <translation>音乐记录</translation>\n    </message>\n    <message>\n        <source>Profile</source>\n        <translation>我</translation>\n    </message>\n    <message>\n        <source>Friends</source>\n        <translation>好友</translation>\n    </message>\n    <message>\n        <source>Radio</source>\n        <translation>电台</translation>\n    </message>\n    <message>\n        <source>Next Section</source>\n        <translation>下一视图</translation>\n    </message>\n    <message>\n        <source>Previous Section</source>\n        <translation>上一视图</translation>\n    </message>\n</context>\n<context>\n    <name>StationSearch</name>\n    <message>\n        <source>Could not start radio: %1</source>\n        <translation>无法启动电台：%1</translation>\n    </message>\n    <message>\n        <source>no results for &quot;%1&quot;</source>\n        <translation>未找到有关“%1”的结果</translation>\n    </message>\n</context>\n<context>\n    <name>StatusBar</name>\n    <message>\n        <source>Scrobbling is off</source>\n        <translation>音乐记录已关闭</translation>\n    </message>\n    <message>\n        <source>%1 (%2)</source>\n        <translation>%1 (%2)</translation>\n    </message>\n    <message>\n        <source>Online</source>\n        <translation>已连接</translation>\n    </message>\n    <message>\n        <source>Offline</source>\n        <translation>已断开</translation>\n    </message>\n</context>\n<context>\n    <name>TagDialog</name>\n    <message>\n        <source>Tag</source>\n        <translation>标签</translation>\n    </message>\n    <message>\n        <source>Choose something to tag:</source>\n        <translation>选择要添加标签的对象：</translation>\n    </message>\n    <message>\n        <source>Track</source>\n        <translation>单曲</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>艺术家</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>专辑</translation>\n    </message>\n    <message>\n        <source>icon</source>\n        <translation>图标</translation>\n    </message>\n    <message>\n        <source>Add tags:</source>\n        <translation>添加标签：</translation>\n    </message>\n    <message>\n        <source>A track by %1</source>\n        <translation>由%1演唱的单曲</translation>\n    </message>\n    <message>\n        <source>A track by %1 from the release %2</source>\n        <translation>由%1演唱的单曲，来自专辑%2</translation>\n    </message>\n</context>\n<context>\n    <name>TagIconView</name>\n    <message>\n        <source>Type a tag above,\nor choose from below</source>\n        <translation>在上面输入标签，\n或在下面作出选择</translation>\n    </message>\n</context>\n<context>\n    <name>TagListWidget</name>\n    <message>\n        <source>Sort by Popularity</source>\n        <translation>按流行程度排序</translation>\n    </message>\n    <message>\n        <source>Sort Alphabetically</source>\n        <translation>按字母顺序排列</translation>\n    </message>\n    <message>\n        <source>Open Last.fm Page for this Tag</source>\n        <translation>打开此标签的 Last.fm 页面</translation>\n    </message>\n</context>\n<context>\n    <name>TourFinishPage</name>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;ve also finished importing your listening history and have added it to your Last.fm profile.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation>&lt;p&gt;现在一切就绪，可以使用了！请点击&lt;strong&gt;完成&lt;/strong&gt;，开始音乐之旅吧。&lt;/p&gt;&lt;p&gt;我们还导入了您的收听历史，并更新了您的 Last.fm 专页。&lt;/p&gt;&lt;p&gt;感谢您安装 Last.fm 桌面程序，祝您使用愉快！&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>That&apos;s it, you&apos;re good to go!</source>\n        <translation>好了，一切就绪！</translation>\n    </message>\n    <message>\n        <source>Finish</source>\n        <translation>完成</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>there was an upload error</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was denied by Last.fm</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>it was detected as spam (too high playcounts?)</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>the submission was cancelled</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Importing your listening history to Last.fm failed because %1. Sorry about that!&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;We&apos;re still importing your listening history and it will be added to your Last.fm profile soon.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Now you&apos;re ready to get started! Just click &lt;strong&gt;Finish&lt;/strong&gt; and start exploring.&lt;/p&gt;&lt;p&gt;Thanks for installing the Last.fm Desktop App, we hope you enjoy using it!&lt;/p&gt;</source>\n        <translation type=\"unfinished\"></translation>\n    </message>\n</context>\n<context>\n    <name>TourLocationPage</name>\n    <message>\n        <source>&lt;p&gt;The red arrow on your screen points to the location of the Last.fm Desktop App in your system tray.&lt;/p&gt;&lt;p&gt;Click the icon to quickly access radio play controls, share and tag track, edit your preferences and visit your Last.fm profile.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;屏幕上的红色箭头指向 Last.fm 桌面程序在系统栏中的位置。&lt;/p&gt;&lt;p&gt;点击此图标可快速访问电台播放控制、分享和单曲标签等功能。您还可以编辑偏好设置和访问 Last.fm 专页。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your menu bar</source>\n        <translation>菜单栏上的 Last.fm 桌面程序</translation>\n    </message>\n    <message>\n        <source>The Last.fm Desktop App in your system tray</source>\n        <translation>系统托盘中的 Last.fm 桌面程序</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n</context>\n<context>\n    <name>TourMetadataPage</name>\n    <message>\n        <source>&lt;p&gt;Find out more about the music you&apos;re listening to, including biographies, listening stats, photos and similar artists, as well as the tags listeners use to describe them.&lt;/p&gt;&lt;p&gt;Check out the &lt;strong&gt;Now Playing&lt;/strong&gt; tab, or simply click on any track in your &lt;strong&gt;Scrobbles&lt;/strong&gt; tab to learn more.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;进一步了解您在收听的音乐，包括人物传记、收听数据、照片、相似艺术家及听众使用哪些标签来描述这些音乐等。&lt;/p&gt;&lt;p&gt;请在&lt;strong&gt;正在播放&lt;/strong&gt;或&lt;strong&gt;音乐记录&lt;/strong&gt;页面点击任何单曲查看更多信息。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Discover more about the artists you love</source>\n        <translation>深入了解您喜欢的艺术家</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>跳过介绍 &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourRadioPage</name>\n    <message>\n        <source>Listen to non-stop, personalised radio</source>\n        <translation>无间断收听个性化电台</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;使用 Last.fm 桌面程序收听个性化电台，根据您的喜好播放音乐。&lt;/p&gt;&lt;p&gt;从艺术家和标签电台，到随您的音乐品味变换的全新推荐，每个 Last.fm 电台播放的音乐都不尽相同。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe and listen to non-stop, personalised radio</source>\n        <translation>成为付费用户，无间断地收听个性化电台</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Subscribe to Last.fm and use the Last.fm Desktop App to listen to personalised radio based on the music you want to hear.&lt;/p&gt;&lt;p&gt;Every play of every Last.fm station is totally different, from stations based on artists and tags to brand new recommendations tailored to your music taste.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;订购 Last.fm 服务，使用 Last.fm 桌面程序收听个性化电台，根据您的喜好播放音乐。&lt;/p&gt;&lt;p&gt;从艺术家和标签电台，到随您的音乐品味变换的全新推荐，每个 Last.fm 电台播放的音乐都不尽相同。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Subscribe</source>\n        <translation>订购</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation>&lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>跳过介绍 &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TourScrobblesPage</name>\n    <message>\n        <source>&lt;p&gt;The desktop client runs in the background, quietly updating your Last.fm profile with the music you&apos;re playing, which you can use to get music recommendations, gig tips and more. &lt;/p&gt;&lt;p&gt;You can also use the Last.fm Desktop App to find out more about the artist you&apos;re listening to, and to play personalised radio.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;桌面程序在后台运行，将您播放的音乐更新到 Last.fm 专页，通过这些数据，您可以获得音乐推荐、音乐会信息和其他精彩内容。&lt;/p&gt;&lt;p&gt;您还可以在收听某位艺术家的同时，使用 Last.fm 桌面程序获取更多相关信息，并可播放个性化电台。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Welcome to the Last.fm Desktop App!</source>\n        <translation>欢迎使用 Last.fm 桌面程序！</translation>\n    </message>\n    <message>\n        <source>Continue</source>\n        <translation>继续</translation>\n    </message>\n    <message>\n        <source>&lt;&lt; Back</source>\n        <translation> &lt;&lt; 返回</translation>\n    </message>\n    <message>\n        <source>Skip Tour &gt;&gt;</source>\n        <translation>跳过介绍 &gt;&gt;</translation>\n    </message>\n</context>\n<context>\n    <name>TrackWidget</name>\n    <message>\n        <source>Track</source>\n        <translation>单曲</translation>\n    </message>\n    <message>\n        <source>Album</source>\n        <translation>专辑</translation>\n    </message>\n    <message>\n        <source>Artist</source>\n        <translation>艺术家</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>喜欢</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>标签</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>分享</translation>\n    </message>\n    <message>\n        <source>Buy</source>\n        <translation>购买</translation>\n    </message>\n    <message>\n        <source>Delete this scrobble from your profile</source>\n        <translation>删除这条音乐记录</translation>\n    </message>\n    <message>\n        <source>Play %1 Radio</source>\n        <translation>播放%1电台</translation>\n    </message>\n    <message>\n        <source>Cue %1 Radio</source>\n        <translation>接下来播放%1电台</translation>\n    </message>\n    <message>\n        <source>%1 Radio</source>\n        <translation>%1电台</translation>\n    </message>\n    <message>\n        <source>Cached</source>\n        <translation>已缓存</translation>\n    </message>\n    <message>\n        <source>Error: %1</source>\n        <translation>错误：%1</translation>\n    </message>\n    <message>\n        <source>Share on Last.fm</source>\n        <translation>分享到 Last.fm</translation>\n    </message>\n    <message>\n        <source>Share on Twitter</source>\n        <translation>分享到 Twitter</translation>\n    </message>\n    <message>\n        <source>Share on Facebook</source>\n        <translation>分享到 Facebook</translation>\n    </message>\n    <message>\n        <source>Now listening</source>\n        <translation>正在收听</translation>\n    </message>\n    <message>\n        <source>Downloads</source>\n        <translation>下载</translation>\n    </message>\n    <message>\n        <source>Search on %1</source>\n        <translation>在 %1 上搜索</translation>\n    </message>\n    <message>\n        <source>Buy on %1 %2</source>\n        <translation>到 %1 %2 购买</translation>\n    </message>\n    <message>\n        <source>Physical</source>\n        <translation>CD</translation>\n    </message>\n</context>\n<context>\n    <name>UserManagerWidget</name>\n    <message>\n        <source>Connected User Accounts:</source>\n        <translation>已连接用户帐户：</translation>\n    </message>\n    <message>\n        <source>Add New User Account</source>\n        <translation>添加新帐户</translation>\n    </message>\n    <message>\n        <source>Add User Error</source>\n        <translation>添加用户出错</translation>\n    </message>\n    <message>\n        <source>This user has already been added.</source>\n        <translation>该用户已被加入。</translation>\n    </message>\n    <message>\n        <source>Removing %1</source>\n        <translation>删除 %1</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.</source>\n        <translation>确定要删除此用户吗？删除后，用户设置信息均将清除，以后要进行音乐记录时，需要重新验证。</translation>\n    </message>\n</context>\n<context>\n    <name>UserMenu</name>\n    <message>\n        <source>Subscribe</source>\n        <translation>订购</translation>\n    </message>\n</context>\n<context>\n    <name>UserRadioButton</name>\n    <message>\n        <source>Remove</source>\n        <translation>删除</translation>\n    </message>\n    <message>\n        <source>(currently logged in)</source>\n        <translation>（当前为登录状态）</translation>\n    </message>\n</context>\n<context>\n    <name>audioscrobbler::Application</name>\n    <message>\n        <source>Accounts</source>\n        <translation>帐户</translation>\n    </message>\n    <message>\n        <source>Show Scrobbler</source>\n        <translation>显示 Scrobbler</translation>\n    </message>\n    <message>\n        <source>Love</source>\n        <translation>喜欢</translation>\n    </message>\n    <message>\n        <source>Play</source>\n        <translation>播放</translation>\n    </message>\n    <message>\n        <source>Skip</source>\n        <translation>跳过</translation>\n    </message>\n    <message>\n        <source>Tag</source>\n        <translation>标签</translation>\n    </message>\n    <message>\n        <source>Share</source>\n        <translation>分享</translation>\n    </message>\n    <message>\n        <source>Ban</source>\n        <translation>禁止</translation>\n    </message>\n    <message>\n        <source>Mute</source>\n        <translation>静音</translation>\n    </message>\n    <message>\n        <source>Scrobble iPod...</source>\n        <translation>记录 iPod...</translation>\n    </message>\n    <message>\n        <source>Visit Last.fm profile</source>\n        <translation>访问 Last.fm 专页</translation>\n    </message>\n    <message>\n        <source>Enable Scrobbling</source>\n        <translation>启用音乐记录</translation>\n    </message>\n    <message>\n        <source>Quit %1</source>\n        <translation>退出 %1</translation>\n    </message>\n    <message>\n        <source>from %1</source>\n        <translation>专辑：%1</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You&apos;ve reached this station&apos;s skip limit. Skip again in %n minute(s).</source>\n        <translation>\n            <numerusform>您已达到该电台的跳过次数上限，请在 %n 分钟后再使用跳过功能。</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>You have %n skip(s) remaining on this station.</source>\n        <translation>\n            <numerusform>您还可以在该电台跳过 %n 首曲目。</numerusform>\n        </translation>\n    </message>\n    <message>\n        <source>Authentication Required</source>\n        <translation>需要验证</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The user account &lt;strong&gt;%1&lt;/strong&gt; is no longer authenticated with Last.fm.&lt;/p&gt;&lt;p&gt;Click OK to start the setup process and reauthenticate this account.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;用户帐户 &lt;strong&gt;%1&lt;/strong&gt; 需要 Last.fm 重新验证。&lt;/p&gt;&lt;p&gt;请点击“确定”开始设置流程，重新验证该帐户。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Are you sure you want to quit %1?</source>\n        <translation>确定要退出 %1 吗？</translation>\n    </message>\n    <message>\n        <source>%1 is about to quit. Tracks played will not be scrobbled if you continue.</source>\n        <translation>%1 即将退出，如果继续，播放的曲目不会得到记录。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Application</name>\n    <message>\n        <source>Changing User</source>\n        <translation>切换用户</translation>\n    </message>\n    <message>\n        <source>%1 will be logged into the Scrobbler and Last.fm Radio. All music will now be scrobbled to this account. Do you want to continue?</source>\n        <translation>%1 将登录到 Scrobbler 和 Last.fm 电台。所有音乐将记录到该帐户，要继续吗？</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::CloseAppsDialog</name>\n    <message>\n        <source>Please close the following apps to continue.</source>\n        <translation>要继续，请先关闭以下应用程序。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::IPluginInfo</name>\n    <message>\n        <source>Plugin install error</source>\n        <translation>插件安装错误</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;There was an error updating your plugin.&lt;/p&gt;&lt;p&gt;Please try again later.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;更新插件时发生错误。&lt;/p&gt;&lt;p&gt;请稍后再试。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>Plugin installed!</source>\n        <translation>插件安装完毕！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;The %1 plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to scrobble with %1.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;%1 插件已安装。&lt;/p&gt;&lt;p&gt;可以用 %1 记录音乐了。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>The %1 plugin hasn&apos;t been installed</source>\n        <translation>%1 插件未安装</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close %1 so its plugin hasn&apos;t been installed.</source>\n        <translation>您未关闭 %1，因此其插件未能安装。</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ITunesPluginInstaller</name>\n    <message>\n        <source>Close iTunes for plugin update!</source>\n        <translation>请关闭 iTunes 以更新插件！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).&lt;/p&gt;&lt;p&gt;Please close iTunes now to update.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;您的 iTunes 插件 (%2) 与该版本程序 (%1) 随附的插件不同。&lt;/p&gt;&lt;p&gt;请关闭 iTunes 进行更新。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>not installed</source>\n        <translation>未安装</translation>\n    </message>\n    <message>\n        <source>Your plugin hasn&apos;t been installed</source>\n        <translation>插件未安装</translation>\n    </message>\n    <message>\n        <source>There was an error while removing the old plugin</source>\n        <translation>移除旧插件时出错</translation>\n    </message>\n    <message>\n        <source>iTunes Plugin installed!</source>\n        <translation>iTunes 插件安装完成！</translation>\n    </message>\n    <message>\n        <source>&lt;p&gt;Your iTunes plugin has been installed.&lt;/p&gt;&lt;p&gt;You&apos;re now ready to device scrobble.&lt;/p&gt;</source>\n        <translation>&lt;p&gt;iTunes 插件已安装。&lt;/p&gt;&lt;p&gt;可以用设备记录音乐了。&lt;/p&gt;</translation>\n    </message>\n    <message>\n        <source>There was an error while copying the new plugin into place</source>\n        <translation>复制新插件时发生错误</translation>\n    </message>\n    <message>\n        <source>You didn&apos;t close iTunes</source>\n        <translation>尚未关闭 iTunes</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::Label</name>\n    <message>\n        <source>Time is broken</source>\n        <translation>时间错乱</translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n minute(s) ago</source>\n        <translation>\n            <numerusform>%n 分钟前</numerusform>\n        </translation>\n    </message>\n    <message numerus=\"yes\">\n        <source>%n hour(s) ago</source>\n        <translation>\n            <numerusform>%n 小时前</numerusform>\n        </translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::LoginProcess</name>\n    <message>\n        <source>There was a network error: %1</source>\n        <translation>发生网络错误：%1</translation>\n    </message>\n    <message>\n        <source>You have not authorised this application</source>\n        <translation>您尚未授权该程序</translation>\n    </message>\n    <message>\n        <source>Authentication Error</source>\n        <translation>验证错误</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MainWindow</name>\n    <message>\n        <source>Refresh Stylesheet</source>\n        <translation>刷新样式表</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::MessageDialog</name>\n    <message>\n        <source>Don&apos;t ask this again</source>\n        <translation>不再询问</translation>\n    </message>\n</context>\n<context>\n    <name>unicorn::ProxyWidget</name>\n    <message>\n        <source>Auto-detect</source>\n        <translation>自动检测</translation>\n    </message>\n    <message>\n        <source>No-proxy</source>\n        <translation>无代理</translation>\n    </message>\n    <message>\n        <source>HTTP</source>\n        <translation>HTTP</translation>\n    </message>\n    <message>\n        <source>SOCKS5</source>\n        <translation>SOCKS5</translation>\n    </message>\n</context>\n</TS>\n"
  },
  {
    "path": "lib/3rdparty/README",
    "content": "Windows\n=======\n\nYou need to install:\n* mad\n* fftw3 (single precision)\n* libsamplerate\n* taglib\n\nThe fetch.sh will attempt to fetch and build them all. But you need to use\nMinGW in order to compile fftw and libsamplerate.\n\nWe have binaries at /svn/clientside/bin/win.\nMinimal headers are also in lib/3rdparty, though we don't keep these up to date.\n\n\nMac OS X\n========\nUse macports to install:\n\n* taglib\n* fftw3-3\n* libsamplerate\n* taglib\n\nLinux\n=====\nInstall the same as for the Mac with your package manager.\n"
  },
  {
    "path": "lib/3rdparty/fetch.sh",
    "content": "source ../../common/bash/utils.sh.inc\n\nfunction go\n{\n    tar=`basename $1`\n    dir=`basename $1 .tar.gz`\n    \n    shift\n \n    header $dir\n    \n    test -f $tar || wget $1\n#    test -d $dir || tar xzf $tar\n}\n\nfunction co\n{\n    svn co $1 $2\n    pushd $2\n    ./configure\n    make\n    popd\n}\n\n\n################################################################################\n\ncase `uname`\nCYGWIN_NT_5.1)\n    which make || die \"You need to install GNU make\"\n    which ld || die \"You need to install cygwin binutils\"\n    which wget || die \"You need to install wget\"\n\n    go http://surfnet.dl.sourceforge.net/sourceforge/mad/libmad-0.15.1b.tar.gz --disable-debug\n    go http://www.fftw.org/fftw-3.1.3.tar.gz --enable-float --disable-debug\n    go http://www.mega-nerd.com/SRC/libsamplerate-0.1.4.tar.gz --disable-debug\n    go http://developer.kde.org/~wheeler/files/src/taglib-1.5.tar.gz --disable-debug\n    ;;\n*)\n    echo Please refer to the README file.\n    ;;\nesac\n\n#co http://google-breakpad.googlecode.com/svn/trunk/ breakpad\n\n\nheader Done!\necho \"Now do make install in each directory or something\"\necho"
  },
  {
    "path": "lib/3rdparty/fftw3.h",
    "content": "/*\n * Copyright (c) 2003, 2006 Matteo Frigo\n * Copyright (c) 2003, 2006 Massachusetts Institute of Technology\n *\n * The following statement of license applies *only* to this header file,\n * and *not* to the other files distributed with FFTW or derived therefrom:\n * \n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n *    notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n *    notice, this list of conditions and the following disclaimer in the\n *    documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/***************************** NOTE TO USERS *********************************\n *\n *                 THIS IS A HEADER FILE, NOT A MANUAL\n *\n *    If you want to know how to use FFTW, please read the manual,\n *    online at http://www.fftw.org/doc/ and also included with FFTW.\n *    For a quick start, see the manual's tutorial section.\n *\n *   (Reading header files to learn how to use a library is a habit\n *    stemming from code lacking a proper manual.  Arguably, it's a\n *    *bad* habit in most cases, because header files can contain\n *    interfaces that are not part of the public, stable API.)\n *\n ****************************************************************************/\n\n/* header file for fftw3 */\n/* (The following is the CVS ID for this file, *not* the version\n   number of FFTW:) */\n/* $Id: fftw3.h,v 1.90 2006-01-17 04:03:33 stevenj Exp $ */\n\n#ifndef FFTW3_H\n#define FFTW3_H\n\n#include <stdio.h>\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#endif /* __cplusplus */\n\n/* If <complex.h> is included, use the C99 complex type.  Otherwise\n   define a type bit-compatible with C99 complex */\n#if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I)\n#  define FFTW_DEFINE_COMPLEX(R, C) typedef R _Complex C\n#else\n#  define FFTW_DEFINE_COMPLEX(R, C) typedef R C[2]\n#endif\n\n#define FFTW_CONCAT(prefix, name) prefix ## name\n#define FFTW_MANGLE_DOUBLE(name) FFTW_CONCAT(fftw_, name)\n#define FFTW_MANGLE_FLOAT(name) FFTW_CONCAT(fftwf_, name)\n#define FFTW_MANGLE_LONG_DOUBLE(name) FFTW_CONCAT(fftwl_, name)\n\n/* IMPORTANT: for Windows compilers, you should add a line\n        #define FFTW_DLL\n   here and in kernel/ifftw.h if you are compiling/using FFTW as a\n   DLL, in order to do the proper importing/exporting, or\n   alternatively compile with -DFFTW_DLL or the equivalent\n   command-line flag.  This is not necessary under MinGW/Cygwin, where\n   libtool does the imports/exports automatically. */\n#if defined(FFTW_DLL) && (defined(_WIN32) || defined(__WIN32__))\n   /* annoying Windows syntax for shared-library declarations */\n#  if defined(COMPILING_FFTW) /* defined in api.h when compiling FFTW */\n#    define FFTW_EXTERN extern __declspec(dllexport) \n#  else /* user is calling FFTW; import symbol */\n#    define FFTW_EXTERN extern __declspec(dllimport) \n#  endif\n#else\n#  define FFTW_EXTERN extern\n#endif\n\nenum fftw_r2r_kind_do_not_use_me {\n     FFTW_R2HC=0, FFTW_HC2R=1, FFTW_DHT=2,\n     FFTW_REDFT00=3, FFTW_REDFT01=4, FFTW_REDFT10=5, FFTW_REDFT11=6,\n     FFTW_RODFT00=7, FFTW_RODFT01=8, FFTW_RODFT10=9, FFTW_RODFT11=10\n};\n\nstruct fftw_iodim_do_not_use_me {\n     int n;                     /* dimension size */\n     int is;\t\t\t/* input stride */\n     int os;\t\t\t/* output stride */\n};\n\n/*\n  huge second-order macro that defines prototypes for all API\n  functions.  We expand this macro for each supported precision\n \n  X: name-mangling macro\n  R: real data type\n  C: complex data type\n*/\n\n#define FFTW_DEFINE_API(X, R, C)\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_DEFINE_COMPLEX(R, C);\t\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\ntypedef struct X(plan_s) *X(plan);\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\ntypedef struct fftw_iodim_do_not_use_me X(iodim);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\ntypedef enum fftw_r2r_kind_do_not_use_me X(r2r_kind);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(execute)(const X(plan) p);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft)(int rank, const int *n,\t\t\t   \\\n\t\t    C *in, C *out, int sign, unsigned flags);\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_1d)(int n, C *in, C *out, int sign,\t   \\\n\t\t       unsigned flags);\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_2d)(int nx, int ny,\t\t\t   \\\n\t\t       C *in, C *out, int sign, unsigned flags);\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_3d)(int nx, int ny, int nz,\t\t   \\\n\t\t       C *in, C *out, int sign, unsigned flags);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_many_dft)(int rank, const int *n,\t\t   \\\n                         int howmany,\t\t\t\t\t   \\\n                         C *in, const int *inembed,\t\t\t   \\\n                         int istride, int idist,\t\t\t   \\\n                         C *out, const int *onembed,\t\t\t   \\\n                         int ostride, int odist,\t\t\t   \\\n                         int sign, unsigned flags);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_dft)(int rank, const X(iodim) *dims,\t   \\\n\t\t\t int howmany_rank,\t\t\t\t   \\\n\t\t\t const X(iodim) *howmany_dims,\t\t\t   \\\n\t\t\t C *in, C *out,\t\t\t\t\t   \\\n\t\t\t int sign, unsigned flags);\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_split_dft)(int rank, const X(iodim) *dims, \\\n\t\t\t int howmany_rank,\t\t\t\t   \\\n\t\t\t const X(iodim) *howmany_dims,\t\t\t   \\\n\t\t\t R *ri, R *ii, R *ro, R *io,\t\t\t   \\\n\t\t\t unsigned flags);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(execute_dft)(const X(plan) p, C *in, C *out);\t   \\\nFFTW_EXTERN void X(execute_split_dft)(const X(plan) p, R *ri, R *ii,\t   \\\n                                      R *ro, R *io);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_many_dft_r2c)(int rank, const int *n,\t   \\\n                             int howmany,\t\t\t\t   \\\n                             R *in, const int *inembed,\t\t\t   \\\n                             int istride, int idist,\t\t\t   \\\n                             C *out, const int *onembed,\t\t   \\\n                             int ostride, int odist,\t\t\t   \\\n                             unsigned flags);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_r2c)(int rank, const int *n,\t\t   \\\n                        R *in, C *out, unsigned flags);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_r2c_1d)(int n,R *in,C *out,unsigned flags); \\\nFFTW_EXTERN X(plan) X(plan_dft_r2c_2d)(int nx, int ny,\t\t\t   \\\n\t\t\t   R *in, C *out, unsigned flags);\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_r2c_3d)(int nx, int ny,\t\t\t   \\\n\t\t\t   int nz,\t\t\t\t\t   \\\n\t\t\t   R *in, C *out, unsigned flags);\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_many_dft_c2r)(int rank, const int *n,\t   \\\n\t\t\t     int howmany,\t\t\t\t   \\\n\t\t\t     C *in, const int *inembed,\t\t\t   \\\n\t\t\t     int istride, int idist,\t\t\t   \\\n\t\t\t     R *out, const int *onembed,\t\t   \\\n\t\t\t     int ostride, int odist,\t\t\t   \\\n\t\t\t     unsigned flags);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_c2r)(int rank, const int *n,\t\t   \\\n                        C *in, R *out, unsigned flags);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_c2r_1d)(int n,C *in,R *out,unsigned flags); \\\nFFTW_EXTERN X(plan) X(plan_dft_c2r_2d)(int nx, int ny,\t\t\t   \\\n\t\t\t   C *in, R *out, unsigned flags);\t\t   \\\nFFTW_EXTERN X(plan) X(plan_dft_c2r_3d)(int nx, int ny,\t\t\t   \\\n\t\t\t   int nz,\t\t\t\t\t   \\\n\t\t\t   C *in, R *out, unsigned flags);\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_dft_r2c)(int rank, const X(iodim) *dims,   \\\n\t\t\t     int howmany_rank,\t\t\t\t   \\\n\t\t\t     const X(iodim) *howmany_dims,\t\t   \\\n\t\t\t     R *in, C *out,\t\t\t\t   \\\n\t\t\t     unsigned flags);\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_dft_c2r)(int rank, const X(iodim) *dims,   \\\n\t\t\t     int howmany_rank,\t\t\t\t   \\\n\t\t\t     const X(iodim) *howmany_dims,\t\t   \\\n\t\t\t     C *in, R *out,\t\t\t\t   \\\n\t\t\t     unsigned flags);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_split_dft_r2c)(\t\t\t\t   \\\n                             int rank, const X(iodim) *dims,\t\t   \\\n\t\t\t     int howmany_rank,\t\t\t\t   \\\n\t\t\t     const X(iodim) *howmany_dims,\t\t   \\\n\t\t\t     R *in, R *ro, R *io,\t\t\t   \\\n\t\t\t     unsigned flags);\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_split_dft_c2r)(\t\t\t\t   \\\n                             int rank, const X(iodim) *dims,\t\t   \\\n\t\t\t     int howmany_rank,\t\t\t\t   \\\n\t\t\t     const X(iodim) *howmany_dims,\t\t   \\\n\t\t\t     R *ri, R *ii, R *out,\t\t\t   \\\n\t\t\t     unsigned flags);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(execute_dft_r2c)(const X(plan) p, R *in, C *out);\t   \\\nFFTW_EXTERN void X(execute_dft_c2r)(const X(plan) p, C *in, R *out);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(execute_split_dft_r2c)(const X(plan) p,\t\t   \\\n                                          R *in, R *ro, R *io);\t\t   \\\nFFTW_EXTERN void X(execute_split_dft_c2r)(const X(plan) p, \t\t   \\\n                                          R *ri, R *ii, R *out);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_many_r2r)(int rank, const int *n,\t\t   \\\n                         int howmany,\t\t\t\t\t   \\\n                         R *in, const int *inembed,\t\t\t   \\\n                         int istride, int idist,\t\t\t   \\\n                         R *out, const int *onembed,\t\t\t   \\\n                         int ostride, int odist,\t\t\t   \\\n                         const X(r2r_kind) *kind, unsigned flags);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_r2r)(int rank, const int *n, R *in, R *out,\t   \\\n                    const X(r2r_kind) *kind, unsigned flags);\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_r2r_1d)(int n, R *in, R *out,\t\t   \\\n                       X(r2r_kind) kind, unsigned flags);\t\t   \\\nFFTW_EXTERN X(plan) X(plan_r2r_2d)(int nx, int ny, R *in, R *out,\t   \\\n                       X(r2r_kind) kindx, X(r2r_kind) kindy,\t\t   \\\n                       unsigned flags);\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_r2r_3d)(int nx, int ny, int nz,\t\t   \\\n                       R *in, R *out, X(r2r_kind) kindx,\t\t   \\\n                       X(r2r_kind) kindy, X(r2r_kind) kindz,\t\t   \\\n                       unsigned flags);\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN X(plan) X(plan_guru_r2r)(int rank, const X(iodim) *dims,\t   \\\n                         int howmany_rank,\t\t\t\t   \\\n                         const X(iodim) *howmany_dims,\t\t\t   \\\n                         R *in, R *out,\t\t\t\t\t   \\\n                         const X(r2r_kind) *kind, unsigned flags);\t   \\\nFFTW_EXTERN void X(execute_r2r)(const X(plan) p, R *in, R *out);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(destroy_plan)(X(plan) p);\t\t\t\t   \\\nFFTW_EXTERN void X(forget_wisdom)(void);\t\t\t\t   \\\nFFTW_EXTERN void X(cleanup)(void);\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(set_timelimit)(double);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(plan_with_nthreads)(int nthreads);\t\t\t   \\\nFFTW_EXTERN int X(init_threads)(void);\t\t\t\t\t   \\\nFFTW_EXTERN void X(cleanup_threads)(void);\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(export_wisdom_to_file)(FILE *output_file);\t\t   \\\nFFTW_EXTERN char *X(export_wisdom_to_string)(void);\t\t\t   \\\nFFTW_EXTERN void X(export_wisdom)(void (*write_char)(char c, void *),\t   \\\n                                  void *data);\t\t\t\t   \\\nFFTW_EXTERN int X(import_system_wisdom)(void);\t\t\t\t   \\\nFFTW_EXTERN int X(import_wisdom_from_file)(FILE *input_file);\t\t   \\\nFFTW_EXTERN int X(import_wisdom_from_string)(const char *input_string);\t   \\\nFFTW_EXTERN int X(import_wisdom)(int (*read_char)(void *), void *data);\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(fprint_plan)(const X(plan) p, FILE *output_file);\t   \\\nFFTW_EXTERN void X(print_plan)(const X(plan) p);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void *X(malloc)(size_t n);\t\t\t\t\t   \\\nFFTW_EXTERN void X(free)(void *p);\t\t\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN void X(flops)(const X(plan) p,\t\t\t\t   \\\n                          double *add, double *mul, double *fmas);\t   \\\nFFTW_EXTERN double X(estimate_cost)(const X(plan) p);\t\t\t   \\\n\t\t\t\t\t\t\t\t\t   \\\nFFTW_EXTERN const char X(version)[];\t\t\t\t\t   \\\nFFTW_EXTERN const char X(cc)[];\t\t\t\t\t\t   \\\nFFTW_EXTERN const char X(codelet_optim)[];\n\n\n/* end of FFTW_DEFINE_API macro */\n\nFFTW_DEFINE_API(FFTW_MANGLE_DOUBLE, double, fftw_complex)\nFFTW_DEFINE_API(FFTW_MANGLE_FLOAT, float, fftwf_complex)\nFFTW_DEFINE_API(FFTW_MANGLE_LONG_DOUBLE, long double, fftwl_complex)\n\n#define FFTW_FORWARD (-1)\n#define FFTW_BACKWARD (+1)\n\n#define FFTW_NO_TIMELIMIT (-1.0)\n\n/* documented flags */\n#define FFTW_MEASURE (0U)\n#define FFTW_DESTROY_INPUT (1U << 0)\n#define FFTW_UNALIGNED (1U << 1)\n#define FFTW_CONSERVE_MEMORY (1U << 2)\n#define FFTW_EXHAUSTIVE (1U << 3) /* NO_EXHAUSTIVE is default */\n#define FFTW_PRESERVE_INPUT (1U << 4) /* cancels FFTW_DESTROY_INPUT */\n#define FFTW_PATIENT (1U << 5) /* IMPATIENT is default */\n#define FFTW_ESTIMATE (1U << 6)\n\n/* undocumented beyond-guru flags */\n#define FFTW_ESTIMATE_PATIENT (1U << 7)\n#define FFTW_BELIEVE_PCOST (1U << 8)\n#define FFTW_NO_DFT_R2HC (1U << 9)\n#define FFTW_NO_NONTHREADED (1U << 10)\n#define FFTW_NO_BUFFERING (1U << 11)\n#define FFTW_NO_INDIRECT_OP (1U << 12)\n#define FFTW_ALLOW_LARGE_GENERIC (1U << 13) /* NO_LARGE_GENERIC is default */\n#define FFTW_NO_RANK_SPLITS (1U << 14)\n#define FFTW_NO_VRANK_SPLITS (1U << 15)\n#define FFTW_NO_VRECURSE (1U << 16)\n#define FFTW_NO_SIMD (1U << 17)\n#define FFTW_NO_SLOW (1U << 18)\n#define FFTW_NO_FIXED_RADIX_LARGE_N (1U << 19)\n#define FFTW_ALLOW_PRUNING (1U << 20)\n\n#ifdef __cplusplus\n}  /* extern \"C\" */\n#endif /* __cplusplus */\n\n#endif /* FFTW3_H */\n"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/LicenseAgreement.rtf",
    "content": "{\\rtf1\\mac\\ansicpg10000\\cocoartf102\n{\\fonttbl\\f0\\fnil\\fcharset77 LucidaGrande-Bold;\\f1\\fnil\\fcharset77 LucidaGrande;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\margl1440\\margr1440\\vieww14340\\viewh11900\\viewkind0\n\\pard\\tx560\\tx1120\\tx1680\\tx2240\\tx2800\\tx3360\\tx3920\\tx4480\\tx5040\\tx5600\\tx6160\\tx6720\\ql\\qnatural\n\n\\f0\\b\\fs20 \\cf0 ENGLISH\n\\f1\\b0 \\\n\\\n\n\\f0\\b Apple Computer, Inc.\\\nSoftware Developer Kit (SDK) Software License Agreement\\\n\\\nPLEASE READ THIS SOFTWARE LICENSE AGREEMENT (\"LICENSE\") BEFORE USING THE SOFTWARE.  BY USING THE SOFTWARE, YOU ARE AGREEING TO BE BOUND BY THE TERMS OF THIS LICENSE.  IF YOU ARE ACCESSING THE SOFTWARE ELECTRONICALLY, SIGNIFY YOUR AGREEMENT TO BE BOUND BY THE TERMS OF THIS LICENSE BY CLICKING THE \"AGREE/ACCEPT\" BUTTON. IF YOU DO NOT AGREE TO THE TERMS OF THIS LICENSE, RETURN THE APPLE SOFTWARE TO THE PLACE WHERE YOU OBTAINED IT FOR A REFUND OR, IF THE SOFTWARE WAS ACCESSED ELECTRONICALLY, CLICK \"DISAGREE/DECLINE\".\\\n\\\nIMPORTANT NOTE: To the extent this software may be used to reproduce materials, it is licensed to you only for reproduction of materials you are authorized or legally permitted to reproduce.  \\\n\n\\f1\\b0 \\\n\n\\f0\\b 1. License.\n\\f1\\b0   Any software, tools, utilities, sample code, documentation, fonts and other materials accompanying this License, whether on disk, print or electronic documentation, in read only memory, or any other media, (collectively, the \"Apple Software\") are licensed, not sold, to you by Apple Computer, Inc. (\"Apple\") for use only under the terms of this License, and Apple reserves all rights not expressly granted to you.  The rights granted herein are limited to Apple's and its licensors' intellectual property rights in the Apple Software and do not include any other patents or intellectual property rights.   You own the media on which the Apple Software is recorded but Apple and/or Apple's licensor(s) retain  ownership of the Apple Software itself.  The Apple Software in this package and any copies, modifications and derivative works which this License authorizes you to make are subject to this License.  \\\n\\\n\n\\f0\\b 2. Permitted Uses and Restrictions.\n\\f1\\b0   You may use the Apple Software to (i) test the Apple Software, and (ii) to develop application software that is compatible with, and runs on the same platform as, the Apple Software.  You have no right to modify, incorporate into or compile in combination with your own programs, license or otherwise distribute any portion of the Apple Software unless the Licensing Info folder (if any) included with the Apple Software expressly authorizes you to do so.  Any terms in the Licensing Info folder shall be deemed to be terms of this License.  Any distribution of any portion of the Apple Software authorized by the Licensing Info folder must be done pursuant to a valid agreement that is at least as protective of Apple's rights in the Apple Software as this License and the terms in the Licensing Info folder.  You may make only as many internal use copies of the Apple Software as reasonably necessary to use the Apple Software as permitted in this paragraph and distribute such copies only to your employees whose job duties require them to so use the Apple Software.  You must reproduce on each copy of the Apple Software or portion thereof, the Apple copyright notice and any other proprietary legends that were on the original copy of the Apple Software.  Except as expressly permitted in this License, you may not decompile, reverse engineer, disassemble, modify, rent, lease, loan, sublicense, distribute or create derivative works based upon the Apple Software in whole or part or transmit the Apple Software over a network or from one computer to another.  Your rights under this License will terminate automatically without notice from Apple if you fail to comply with any term(s) of this License. In addition, Apple reserves the right to terminate this License if a new version of Apple's operating system software or the Apple Software is released which is incompatible with the Apple Software.\\\n\\\n\n\\f0\\b 3. Limited Warranty on Media (if applicable). \n\\f1\\b0  Apple warrants the media on which the Apple Software is recorded and delivered by Apple to be free from defects in materials and workmanship under normal use for a period of ninety (90) days from the date of original retail purchase.  Your exclusive remedy under this Section shall be, at Apple\\'d5s option, a refund of the purchase price of the product containing the Apple Software or replacement of the Apple Software which is returned to Apple or an Apple authorized representative with a copy of the receipt.  THIS LIMITED WARRANTY AND ANY IMPLIED WARRANTIES ON THE MEDIA INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND OF FITNESS FOR A PARTICULAR PURPOSE, ARE LIMITED IN DURATION TO NINETY (90) DAYS FROM THE DATE OF ORIGINAL RETAIL PURCHASE.  SOME JURISDICTIONS DO NOT ALLOW LIMITATIONS ON HOW LONG AN IMPLIED WARRANTY LASTS, SO THE ABOVE LIMITATION MAY NOT APPLY TO YOU.  THE LIMITED WARRANTY SET FORTH HEREIN IS THE ONLY WARRANTY MADE TO YOU AND IS PROVIDED IN LIEU OF ANY OTHER WARRANTIES (IF ANY) CREATED BY ANY DOCUMENTATION OR PACKAGING.  THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS, AND YOU MAY ALSO HAVE OTHER RIGHTS WHICH VARY BY JURISDICTION.\\\n\\\n\n\\f0\\b 4. Disclaimer Of Warranty. \n\\f1\\b0  The Apple Software may be \"alpha\", \"beta\", \"development\", pre-release, untested, and/or not fully tested and may contain errors that could cause failures or loss of data, be incomplete or contain inaccuracies.  YOU EXPRESSLY ACKNOWLEDGE AND AGREE THAT USE OF THE APPLE SOFTWARE IS AT YOUR SOLE RISK AND THAT THE ENTIRE RISK AS TO SATISFACTORY QUALITY, PERFORMANCE, ACCURACY AND EFFORT IS WITH YOU. EXCEPT FOR THE LIMITED WARRANTY ON MEDIA SET FORTH ABOVE AND TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE APPLE SOFTWARE IS PROVIDED \"AS IS\", WITH ALL FAULTS AND WITHOUT WARRANTY OF ANY KIND, AND APPLE AND APPLE'S LICENSORS (COLLECTIVELY REFERRED TO AS \"APPLE\" FOR THE PURPOSES OF SECTIONS 4 AND 5) HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH RESPECT TO THE APPLE SOFTWARE, EITHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES AND/OR CONDITIONS OF MERCHANTABILITY, OF SATISFACTORY QUALITY, OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY, OF QUIET ENJOYMENT, AND NON-INFRINGEMENT OF THIRD PARTY RIGHTS.  APPLE DOES NOT WARRANT AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE APPLE SOFTWARE, THAT THE FUNCTIONS CONTAINED IN THE APPLE SOFTWARE WILL MEET YOUR REQUIREMENTS, THAT THE OPERATION OF THE APPLE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT DEFECTS IN THE APPLE SOFTWARE WILL BE CORRECTED. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY APPLE OR AN APPLE AUTHORIZED REPRESENTATIVE SHALL CREATE A WARRANTY.  SHOULD THE APPLE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE ENTIRE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.  SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES OR LIMITATIONS ON APPLICABLE STATUTORY RIGHTS OF A CONSUMER, SO THE ABOVE EXCLUSION AND LIMITATIONS MAY NOT APPLY TO YOU.  \\\n\\\n\n\\f0\\b 5. Limitation Of Liability. \n\\f1\\b0 TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT SHALL APPLE BE LIABLE FOR PERSONAL INJURY, OR ANY INCIDENTAL, SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, LOSS OF DATA, BUSINESS INTERRUPTION OR ANY OTHER COMMERCIAL DAMAGES OR LOSSES, ARISING OUT OF OR RELATED TO YOUR USE OR INABILITY TO USE THE APPLE SOFTWARE, HOWEVER CAUSED, REGARDLESS OF THE THEORY OF LIABILITY (CONTRACT, TORT OR OTHERWISE) AND EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OF LIABILITY FOR PERSONAL INJURY, OR OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS LIMITATION MAY NOT APPLY TO YOU.  In no event shall Apple's total liability to you for all damages (other than as may be required by applicable law in cases involving personal injury) exceed the amount of fifty dollars ($50.00).  The foregoing limitations will apply even if the above stated remedy fails of its essential purpose.\\\n\\\n\n\\f0\\b 6. Export Law Assurances.\n\\f1\\b0   You may not use or otherwise export or reexport the Apple Software except as authorized by United States law and the laws of the jurisdiction in which the Apple Software was obtained.  In particular, but without limitation, the Apple Software may not be exported or re-exported (a) into (or to a national or resident of) any U.S. embargoed countries (currently Cuba, Iran, Iraq, Libya, North Korea, Sudan, and Syria), or (b) to anyone on the U.S. Treasury Department's list of Specially Designated Nationals or the U.S. Department of Commerce Denied Person\\'d5s List or Entity List.  By using the Apple Software, you represent and warrant that you are not located in, under control of, or a national or resident of any such country or on any such list.\\\n\n\\f0\\b \\\n7. Government End Users. \n\\f1\\b0  The Apple Software and related documentation are \"Commercial Items\", as that term is defined at 48 C.F.R. \\'a42.101, consisting of \"Commercial Computer Software\" and \"Commercial Computer Software Documentation\", as such terms are used in 48 C.F.R. \\'a412.212 or 48 C.F.R. \\'a4227.7202, as applicable.  Consistent with 48 C.F.R. \\'a412.212 or 48 C.F.R. \\'a4227.7202-1through 227.7202-4, as applicable, the Commercial Computer Software and Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights as are granted to all other end users pursuant to the terms and conditions herein.  Unpublished-rights reserved under the copyright laws of the United States.\\\n\\\n\n\\f0\\b 8. Controlling Law and Severability.\n\\f1\\b0   This License will be governed by and construed in accordance with the laws of the State of California, as applied to agreements entered into and to be performed entirely within California between California residents. This License shall not be governed by the United Nations Convention on Contracts for the International Sale of Goods, the application of which is expressly excluded. If for any reason a court of competent jurisdiction finds any provision, or portion thereof, to be unenforceable, the remainder of this License shall continue in full force and effect.  \\\n\\\n\n\\f0\\b 9. Complete Agreement.\n\\f1\\b0   This License constitutes the entire agreement between the parties with respect to the use of the Apple Software licensed hereunder and supersedes all prior or contemporaneous understandings regarding such subject matter.  No amendment to or modification of this License will be binding unless in writing and signed by Apple. Any translation of this License is done for local requirements and in the event of a dispute between the English and any non-English versions, the English version of this License shall govern.\\\n\\\nEA0139}"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/ReadMe.rtf",
    "content": "{\\rtf1\\mac\\ansicpg10000\\cocoartf102\n{\\fonttbl\\f0\\fswiss\\fcharset77 Helvetica;}\n{\\colortbl;\\red255\\green255\\blue255;}\n\\margl1440\\margr1440\\vieww10620\\viewh12220\\viewkind0\n\\pard\\tx720\\tx1440\\tx2160\\tx2880\\tx3600\\tx4320\\tx5040\\tx5760\\tx6480\\tx7200\\tx7920\\tx8640\\ql\\qnatural\n\n\\f0\\fs24 \\cf0 iTunesCOM.chm\\\n\\\nCompressed HTML help file containing the documentation on the iTunes COM\\\ninterface.  It's built directly from the IDL files, so anything you see\\\ndocumented is guaranteed to be available in iTunes.\\\n\\\niTunesCOMInterface.h\\\niTunesCOMInterface_i.c\\\n\\\nThe iTunes COM header file (along with IID constants), needed for building clients in a high level\\\nlanguage like C++.  Note that the type library is built into iTunes.exe,\\\nyou can browse it using OLEView or similar tools.\\\n\\\nSampleScripts folder\\\n\\\nA few sample JScripts that use the iTunes COM interface:\\\n\\\nCreateAlbumPlaylists.js\\\n\\\nIterates over all tracks in your library, creates a new playlist for\\\neach album, and adds the tracks for that album to the playlist.\\\n\\\nRemoveDeadTracks.js\\\n\\\nIterates over your library and removes any tracks that can no longer be\\\nfound on disk.\\\n\\\nRemoveUserPlaylists.js\\\n\\\nDeletes all non-smart user playlists your library.\\\n}"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/SampleScripts/CreateAlbumPlaylists.js",
    "content": "/* \r\n    File: CreateAlbumPlaylists.js\r\n     \r\n    Version: 1.0 \r\n\r\n    Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. \r\n                (\"Apple\") in consideration of your agreement to the following terms, and your \r\n                use, installation, modification or redistribution of this Apple software \r\n                constitutes acceptance of these terms.  If you do not agree with these terms, \r\n                please do not use, install, modify or redistribute this Apple software. \r\n\r\n                In consideration of your agreement to abide by the following terms, and subject \r\n                to these terms, Apple grants you a personal, non-exclusive license, under Apples \r\n                copyrights in this original Apple software (the \"Apple Software\"), to use, \r\n                reproduce, modify and redistribute the Apple Software, with or without \r\n                modifications, in source and/or binary forms; provided that if you redistribute \r\n                the Apple Software in its entirety and without modifications, you must retain \r\n                this notice and the following text and disclaimers in all such redistributions of \r\n                the Apple Software.  Neither the name, trademarks, service marks or logos of \r\n                Apple Computer, Inc. may be used to endorse or promote products derived from the \r\n                Apple Software without specific prior written permission from Apple.  Except as \r\n                expressly stated in this notice, no other rights or licenses, express or implied, \r\n                are granted by Apple herein, including but not limited to any patent rights that \r\n                may be infringed by your derivative works or by other works in which the Apple \r\n                Software may be incorporated. \r\n\r\n                The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO \r\n                WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED \r\n                WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR \r\n                PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN \r\n                COMBINATION WITH YOUR PRODUCTS. \r\n\r\n                IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR \r\n                CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \r\n                GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \r\n                ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION \r\n                OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT \r\n                (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN \r\n                ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \r\n\r\n    Copyright  2004 Apple Computer, Inc., All Rights Reserved \r\n*/ \r\n\r\n\r\nvar\tiTunesApp = WScript.CreateObject(\"iTunes.Application\");\r\nvar\tmainLibrary = iTunesApp.LibraryPlaylist;\r\nvar\tmainLibrarySource = iTunesApp.LibrarySource;\r\nvar\ttracks = mainLibrary.Tracks;\r\nvar\tnumTracks = tracks.Count;\r\nvar numPlaylistsCreated = 0;\r\nvar\ti;\r\n\r\n// FIXME take a -v parameter eventually\r\nvar verbose = false;\r\n\r\n// first, make an array indexed by album name\r\nvar\talbumArray = new Array();\r\n\r\nfor (i = 1; i <= numTracks; i++)\r\n{\r\n\tvar\tcurrTrack = tracks.Item(i);\r\n\tvar\talbum = currTrack.Album;\r\n\t\r\n\tif ((album != undefined) && (album != \"\"))\r\n\t{\r\n\t\tif (albumArray[album] == undefined)\r\n\t\t{\r\n\t\t\tif (verbose)\r\n\t\t\t\tWScript.Echo(\"Adding album \" + album);\r\n\t\t\talbumArray[album] = new Array();\r\n\t\t}\r\n\t\t\r\n\t\t// add the track to the entry for this album\r\n\t\talbumArray[album].push(currTrack);\r\n\t}\r\n}\r\n\r\nfor (var albumNameKey in albumArray)\r\n{\r\n\tvar albumPlayList;\r\n\tvar trackArray = albumArray[albumNameKey];\r\n\r\n\tif (verbose)\r\n\t\tWScript.Echo(\"Creating playlist \" + albumNameKey);\r\n\t\r\n\tnumPlaylistsCreated++;\r\n\t\r\n\talbumPlaylist = iTunesApp.CreatePlaylist(albumNameKey);\r\n\t\r\n\tfor (var trackIndex in trackArray)\r\n\t{\r\n\t\tvar\t\tcurrTrack = trackArray[trackIndex];\r\n\t\t\r\n\t\tif (verbose)\r\n\t\t\tWScript.Echo(\"   Adding \" + currTrack.Name);\r\n\t\t\r\n\t\talbumPlaylist.AddTrack(currTrack);\r\n\t}\r\n}\r\n\r\nif (numPlaylistsCreated == 0)\r\n{\r\n\tWScript.Echo(\"No playlists created.\");\r\n}\r\nelse if (numPlaylistsCreated == 1)\r\n{\r\n\tWScript.Echo(\"Created 1 playlist.\");\r\n}\r\nelse\r\n{\r\n\tWScript.Echo(\"Created \" + numPlaylistsCreated + \" playlists.\");\r\n}\r\n"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/SampleScripts/RemoveDeadTracks.js",
    "content": "/* \r\n    File: RemoveDeadTracks.js \r\n     \r\n    Version: 1.0 \r\n\r\n    Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. \r\n                (\"Apple\") in consideration of your agreement to the following terms, and your \r\n                use, installation, modification or redistribution of this Apple software \r\n                constitutes acceptance of these terms.  If you do not agree with these terms, \r\n                please do not use, install, modify or redistribute this Apple software. \r\n\r\n                In consideration of your agreement to abide by the following terms, and subject \r\n                to these terms, Apple grants you a personal, non-exclusive license, under Apples \r\n                copyrights in this original Apple software (the \"Apple Software\"), to use, \r\n                reproduce, modify and redistribute the Apple Software, with or without \r\n                modifications, in source and/or binary forms; provided that if you redistribute \r\n                the Apple Software in its entirety and without modifications, you must retain \r\n                this notice and the following text and disclaimers in all such redistributions of \r\n                the Apple Software.  Neither the name, trademarks, service marks or logos of \r\n                Apple Computer, Inc. may be used to endorse or promote products derived from the \r\n                Apple Software without specific prior written permission from Apple.  Except as \r\n                expressly stated in this notice, no other rights or licenses, express or implied, \r\n                are granted by Apple herein, including but not limited to any patent rights that \r\n                may be infringed by your derivative works or by other works in which the Apple \r\n                Software may be incorporated. \r\n\r\n                The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO \r\n                WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED \r\n                WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR \r\n                PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN \r\n                COMBINATION WITH YOUR PRODUCTS. \r\n\r\n                IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR \r\n                CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \r\n                GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \r\n                ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION \r\n                OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT \r\n                (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN \r\n                ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \r\n\r\n    Copyright  2004 Apple Computer, Inc., All Rights Reserved \r\n*/ \r\n\r\n\r\nvar ITTrackKindFile\t= 1;\r\nvar\tiTunesApp = WScript.CreateObject(\"iTunes.Application\");\r\nvar\tdeletedTracks = 0;\r\nvar\tmainLibrary = iTunesApp.LibraryPlaylist;\r\nvar\ttracks = mainLibrary.Tracks;\r\nvar\tnumTracks = tracks.Count;\r\nvar\ti;\r\n\r\nwhile (numTracks != 0)\r\n{\r\n\tvar\tcurrTrack = tracks.Item(numTracks);\r\n\t\r\n\t// is this a file track?\r\n\tif (currTrack.Kind == ITTrackKindFile)\r\n\t{\r\n\t\t// yes, does it have an empty location?\r\n\t\tif (currTrack.Location == \"\")\r\n\t\t{\r\n\t\t\t// yes, delete it\r\n\t\t\tcurrTrack.Delete();\r\n\t\t\tdeletedTracks++;\r\n\t\t}\r\n\t}\r\n\t\r\n\tnumTracks--;\r\n}\r\n\r\nif (deletedTracks > 0)\r\n{\r\n\tif (deletedTracks == 1)\r\n\t{\r\n\t\tWScript.Echo(\"Removed 1 dead track.\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tWScript.Echo(\"Removed \" + deletedTracks + \" dead tracks.\");\r\n\t}\r\n}\r\nelse\r\n{\r\n\tWScript.Echo(\"No dead tracks were found.\");\r\n}\r\n"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/SampleScripts/RemoveUserPlaylists.js",
    "content": "/* \r\n    File: RemoveUserPlaylists.js \r\n     \r\n    Version: 1.0 \r\n\r\n    Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. \r\n                (\"Apple\") in consideration of your agreement to the following terms, and your \r\n                use, installation, modification or redistribution of this Apple software \r\n                constitutes acceptance of these terms.  If you do not agree with these terms, \r\n                please do not use, install, modify or redistribute this Apple software. \r\n\r\n                In consideration of your agreement to abide by the following terms, and subject \r\n                to these terms, Apple grants you a personal, non-exclusive license, under Apples \r\n                copyrights in this original Apple software (the \"Apple Software\"), to use, \r\n                reproduce, modify and redistribute the Apple Software, with or without \r\n                modifications, in source and/or binary forms; provided that if you redistribute \r\n                the Apple Software in its entirety and without modifications, you must retain \r\n                this notice and the following text and disclaimers in all such redistributions of \r\n                the Apple Software.  Neither the name, trademarks, service marks or logos of \r\n                Apple Computer, Inc. may be used to endorse or promote products derived from the \r\n                Apple Software without specific prior written permission from Apple.  Except as \r\n                expressly stated in this notice, no other rights or licenses, express or implied, \r\n                are granted by Apple herein, including but not limited to any patent rights that \r\n                may be infringed by your derivative works or by other works in which the Apple \r\n                Software may be incorporated. \r\n\r\n                The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO \r\n                WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED \r\n                WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR \r\n                PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN \r\n                COMBINATION WITH YOUR PRODUCTS. \r\n\r\n                IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR \r\n                CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE \r\n                GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) \r\n                ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION \r\n                OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT \r\n                (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN \r\n                ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \r\n\r\n    Copyright  2004 Apple Computer, Inc., All Rights Reserved \r\n*/ \r\n\r\n\r\nvar ITPlaylistKindUser = 2;\r\nvar\tiTunesApp = WScript.CreateObject(\"iTunes.Application\");\r\nvar\tdeletedPlaylists = 0;\r\nvar\tmainLibrary = iTunesApp.LibrarySource;\r\nvar\tplaylists = mainLibrary.Playlists;\r\nvar\tnumPlaylists = playlists.Count;\r\n\r\nwhile (numPlaylists != 0)\r\n{\r\n\tvar\tcurrPlaylist = playlists.Item(numPlaylists);\r\n\t\r\n\t// is this a user playlist?\r\n\tif (currPlaylist.Kind == ITPlaylistKindUser)\r\n\t{\r\n\t\t// yes, is it a dumb playlist?\r\n\t\tif (!currPlaylist.Smart)\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\t// yes, delete it\r\n\t\t\t\tcurrPlaylist.Delete();\r\n\t\t\t\tdeletedPlaylists++;\r\n\t\t\t}\r\n\t\t\tcatch (exception)\r\n\t\t\t{\r\n\t\t\t\t// ignore errors (e.g. trying to delete a locked playlist)\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tnumPlaylists--;\r\n}\r\n\r\nif (deletedPlaylists > 0)\r\n{\r\n\tif (deletedPlaylists == 1)\r\n\t{\r\n\t\tWScript.Echo(\"Removed 1 user playlist.\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tWScript.Echo(\"Removed \" + deletedPlaylists + \" user playlists.\");\r\n\t}\r\n}\r\nelse\r\n{\r\n\tWScript.Echo(\"No user playlists were removed.\");\r\n}\r\n"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/iTunesCOMInterface.h",
    "content": "\r\n\r\n/* this ALWAYS GENERATED file contains the definitions for the interfaces */\r\n\r\n\r\n /* File created by MIDL compiler version 6.00.0366 */\r\n/* at Wed Jun 25 17:02:20 2008\r\n */\r\n/* Compiler settings for iTunesCOMInterface.idl:\r\n    Oicf, W1, Zp8, env=Win32 (32b run)\r\n    protocol : dce , ms_ext, c_ext, robust\r\n    error checks: allocation ref bounds_check enum stub_data \r\n    VC __declspec() decoration level: \r\n         __declspec(uuid()), __declspec(selectany), __declspec(novtable)\r\n         DECLSPEC_UUID(), MIDL_INTERFACE()\r\n*/\r\n//@@MIDL_FILE_HEADING(  )\r\n\r\n#pragma warning( disable: 4049 )  /* more than 64k source lines */\r\n\r\n\r\n/* verify that the <rpcndr.h> version is high enough to compile this file*/\r\n#ifndef __REQUIRED_RPCNDR_H_VERSION__\r\n#define __REQUIRED_RPCNDR_H_VERSION__ 475\r\n#endif\r\n\r\n#include \"rpc.h\"\r\n#include \"rpcndr.h\"\r\n\r\n#ifndef __RPCNDR_H_VERSION__\r\n#error this stub requires an updated version of <rpcndr.h>\r\n#endif // __RPCNDR_H_VERSION__\r\n\r\n\r\n#ifndef __iTunesCOMInterface_h__\r\n#define __iTunesCOMInterface_h__\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n/* Forward Declarations */ \r\n\r\n#ifndef __IITObject_FWD_DEFINED__\r\n#define __IITObject_FWD_DEFINED__\r\ntypedef interface IITObject IITObject;\r\n#endif \t/* __IITObject_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITSource_FWD_DEFINED__\r\n#define __IITSource_FWD_DEFINED__\r\ntypedef interface IITSource IITSource;\r\n#endif \t/* __IITSource_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITSourceCollection_FWD_DEFINED__\r\n#define __IITSourceCollection_FWD_DEFINED__\r\ntypedef interface IITSourceCollection IITSourceCollection;\r\n#endif \t/* __IITSourceCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEncoder_FWD_DEFINED__\r\n#define __IITEncoder_FWD_DEFINED__\r\ntypedef interface IITEncoder IITEncoder;\r\n#endif \t/* __IITEncoder_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEncoderCollection_FWD_DEFINED__\r\n#define __IITEncoderCollection_FWD_DEFINED__\r\ntypedef interface IITEncoderCollection IITEncoderCollection;\r\n#endif \t/* __IITEncoderCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEQPreset_FWD_DEFINED__\r\n#define __IITEQPreset_FWD_DEFINED__\r\ntypedef interface IITEQPreset IITEQPreset;\r\n#endif \t/* __IITEQPreset_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEQPresetCollection_FWD_DEFINED__\r\n#define __IITEQPresetCollection_FWD_DEFINED__\r\ntypedef interface IITEQPresetCollection IITEQPresetCollection;\r\n#endif \t/* __IITEQPresetCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylist_FWD_DEFINED__\r\n#define __IITPlaylist_FWD_DEFINED__\r\ntypedef interface IITPlaylist IITPlaylist;\r\n#endif \t/* __IITPlaylist_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITOperationStatus_FWD_DEFINED__\r\n#define __IITOperationStatus_FWD_DEFINED__\r\ntypedef interface IITOperationStatus IITOperationStatus;\r\n#endif \t/* __IITOperationStatus_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITConvertOperationStatus_FWD_DEFINED__\r\n#define __IITConvertOperationStatus_FWD_DEFINED__\r\ntypedef interface IITConvertOperationStatus IITConvertOperationStatus;\r\n#endif \t/* __IITConvertOperationStatus_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITLibraryPlaylist_FWD_DEFINED__\r\n#define __IITLibraryPlaylist_FWD_DEFINED__\r\ntypedef interface IITLibraryPlaylist IITLibraryPlaylist;\r\n#endif \t/* __IITLibraryPlaylist_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITUserPlaylist_FWD_DEFINED__\r\n#define __IITUserPlaylist_FWD_DEFINED__\r\ntypedef interface IITUserPlaylist IITUserPlaylist;\r\n#endif \t/* __IITUserPlaylist_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITTrack_FWD_DEFINED__\r\n#define __IITTrack_FWD_DEFINED__\r\ntypedef interface IITTrack IITTrack;\r\n#endif \t/* __IITTrack_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITTrackCollection_FWD_DEFINED__\r\n#define __IITTrackCollection_FWD_DEFINED__\r\ntypedef interface IITTrackCollection IITTrackCollection;\r\n#endif \t/* __IITTrackCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITVisual_FWD_DEFINED__\r\n#define __IITVisual_FWD_DEFINED__\r\ntypedef interface IITVisual IITVisual;\r\n#endif \t/* __IITVisual_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITVisualCollection_FWD_DEFINED__\r\n#define __IITVisualCollection_FWD_DEFINED__\r\ntypedef interface IITVisualCollection IITVisualCollection;\r\n#endif \t/* __IITVisualCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITWindow_FWD_DEFINED__\r\n#define __IITWindow_FWD_DEFINED__\r\ntypedef interface IITWindow IITWindow;\r\n#endif \t/* __IITWindow_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITBrowserWindow_FWD_DEFINED__\r\n#define __IITBrowserWindow_FWD_DEFINED__\r\ntypedef interface IITBrowserWindow IITBrowserWindow;\r\n#endif \t/* __IITBrowserWindow_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITWindowCollection_FWD_DEFINED__\r\n#define __IITWindowCollection_FWD_DEFINED__\r\ntypedef interface IITWindowCollection IITWindowCollection;\r\n#endif \t/* __IITWindowCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IiTunes_FWD_DEFINED__\r\n#define __IiTunes_FWD_DEFINED__\r\ntypedef interface IiTunes IiTunes;\r\n#endif \t/* __IiTunes_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef ___IiTunesEvents_FWD_DEFINED__\r\n#define ___IiTunesEvents_FWD_DEFINED__\r\ntypedef interface _IiTunesEvents _IiTunesEvents;\r\n#endif \t/* ___IiTunesEvents_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef ___IITConvertOperationStatusEvents_FWD_DEFINED__\r\n#define ___IITConvertOperationStatusEvents_FWD_DEFINED__\r\ntypedef interface _IITConvertOperationStatusEvents _IITConvertOperationStatusEvents;\r\n#endif \t/* ___IITConvertOperationStatusEvents_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __iTunesApp_FWD_DEFINED__\r\n#define __iTunesApp_FWD_DEFINED__\r\n\r\n#ifdef __cplusplus\r\ntypedef class iTunesApp iTunesApp;\r\n#else\r\ntypedef struct iTunesApp iTunesApp;\r\n#endif /* __cplusplus */\r\n\r\n#endif \t/* __iTunesApp_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __iTunesConvertOperationStatus_FWD_DEFINED__\r\n#define __iTunesConvertOperationStatus_FWD_DEFINED__\r\n\r\n#ifdef __cplusplus\r\ntypedef class iTunesConvertOperationStatus iTunesConvertOperationStatus;\r\n#else\r\ntypedef struct iTunesConvertOperationStatus iTunesConvertOperationStatus;\r\n#endif /* __cplusplus */\r\n\r\n#endif \t/* __iTunesConvertOperationStatus_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITArtwork_FWD_DEFINED__\r\n#define __IITArtwork_FWD_DEFINED__\r\ntypedef interface IITArtwork IITArtwork;\r\n#endif \t/* __IITArtwork_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITArtworkCollection_FWD_DEFINED__\r\n#define __IITArtworkCollection_FWD_DEFINED__\r\ntypedef interface IITArtworkCollection IITArtworkCollection;\r\n#endif \t/* __IITArtworkCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITURLTrack_FWD_DEFINED__\r\n#define __IITURLTrack_FWD_DEFINED__\r\ntypedef interface IITURLTrack IITURLTrack;\r\n#endif \t/* __IITURLTrack_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITAudioCDPlaylist_FWD_DEFINED__\r\n#define __IITAudioCDPlaylist_FWD_DEFINED__\r\ntypedef interface IITAudioCDPlaylist IITAudioCDPlaylist;\r\n#endif \t/* __IITAudioCDPlaylist_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylistCollection_FWD_DEFINED__\r\n#define __IITPlaylistCollection_FWD_DEFINED__\r\ntypedef interface IITPlaylistCollection IITPlaylistCollection;\r\n#endif \t/* __IITPlaylistCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITIPodSource_FWD_DEFINED__\r\n#define __IITIPodSource_FWD_DEFINED__\r\ntypedef interface IITIPodSource IITIPodSource;\r\n#endif \t/* __IITIPodSource_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITFileOrCDTrack_FWD_DEFINED__\r\n#define __IITFileOrCDTrack_FWD_DEFINED__\r\ntypedef interface IITFileOrCDTrack IITFileOrCDTrack;\r\n#endif \t/* __IITFileOrCDTrack_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylistWindow_FWD_DEFINED__\r\n#define __IITPlaylistWindow_FWD_DEFINED__\r\ntypedef interface IITPlaylistWindow IITPlaylistWindow;\r\n#endif \t/* __IITPlaylistWindow_FWD_DEFINED__ */\r\n\r\n\r\n/* header files for imported files */\r\n#include \"oaidl.h\"\r\n#include \"ocidl.h\"\r\n#include \"DispEx.h\"\r\n\r\n#ifdef __cplusplus\r\nextern \"C\"{\r\n#endif \r\n\r\nvoid * __RPC_USER MIDL_user_allocate(size_t);\r\nvoid __RPC_USER MIDL_user_free( void * ); \r\n\r\n/* interface __MIDL_itf_iTunesCOMInterface_0000 */\r\n/* [local] */ \r\n\r\ntypedef /* [public][v1_enum][uuid] */  DECLSPEC_UUID(\"4B73428D-2F56-4833-8E5D-65590E45FEAD\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0000_0001\r\n    {\tkITTypeLibrary_MajorVersion\t= 1,\r\n\tkITTypeLibrary_MinorVersion\t= 11\r\n    } \tITVersion;\r\n\r\ntypedef /* [public][v1_enum][uuid] */  DECLSPEC_UUID(\"4C25623B-F990-4ebd-8970-F29A70084B8C\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0000_0002\r\n    {\tITUNES_E_USERCANCEL\t= 0xa0040201,\r\n\tITUNES_E_OBJECTDELETED\t= 0xa0040202,\r\n\tITUNES_E_OBJECTLOCKED\t= 0xa0040203,\r\n\tITUNES_E_CONVERSIONINPROGRESS\t= 0xa0040204,\r\n\tITUNES_E_MUSICSTOREDISABLED\t= 0xa0040205,\r\n\tITUNES_E_OBJECTEXISTS\t= 0xa0040206,\r\n\tITUNES_E_PODCASTSDISABLED\t= 0xa0040207\r\n    } \tITErrors;\r\n\r\n\r\n\r\nextern RPC_IF_HANDLE __MIDL_itf_iTunesCOMInterface_0000_v0_0_c_ifspec;\r\nextern RPC_IF_HANDLE __MIDL_itf_iTunesCOMInterface_0000_v0_0_s_ifspec;\r\n\r\n\r\n#ifndef __iTunesLib_LIBRARY_DEFINED__\r\n#define __iTunesLib_LIBRARY_DEFINED__\r\n\r\n/* library iTunesLib */\r\n/* [helpstring][uuid][version] */ \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"3D502ACA-B474-4640-A2A4-C149538345EC\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0001\r\n    {\tITPlayerStateStopped\t= 0,\r\n\tITPlayerStatePlaying\t= ITPlayerStateStopped + 1,\r\n\tITPlayerStateFastForward\t= ITPlayerStatePlaying + 1,\r\n\tITPlayerStateRewind\t= ITPlayerStateFastForward + 1\r\n    } \tITPlayerState;\r\n\r\ntypedef /* [public][public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"5319FADA-0F39-4015-82A0-48B8B871C63C\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0002\r\n    {\tITVisualSizeSmall\t= 0,\r\n\tITVisualSizeMedium\t= ITVisualSizeSmall + 1,\r\n\tITVisualSizeLarge\t= ITVisualSizeMedium + 1\r\n    } \tITVisualSize;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"C8128C8D-EDE0-4f0e-AEB1-08D24A91C551\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0003\r\n    {\tITCOMDisabledReasonOther\t= 0,\r\n\tITCOMDisabledReasonDialog\t= ITCOMDisabledReasonOther + 1,\r\n\tITCOMDisabledReasonQuitting\t= ITCOMDisabledReasonDialog + 1\r\n    } \tITCOMDisabledReason;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"6B1BD814-CA6E-4063-9EDA-4128D31068C1\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0004\r\n    {\tITPlayButtonStatePlayDisabled\t= 0,\r\n\tITPlayButtonStatePlayEnabled\t= ITPlayButtonStatePlayDisabled + 1,\r\n\tITPlayButtonStatePauseEnabled\t= ITPlayButtonStatePlayEnabled + 1,\r\n\tITPlayButtonStatePauseDisabled\t= ITPlayButtonStatePauseEnabled + 1,\r\n\tITPlayButtonStateStopEnabled\t= ITPlayButtonStatePauseDisabled + 1,\r\n\tITPlayButtonStateStopDisabled\t= ITPlayButtonStateStopEnabled + 1\r\n    } \tITPlayButtonState;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"8AF85488-2154-4e46-B65B-1972A43493EF\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0005\r\n    {\tITPlayerButtonPrevious\t= 0,\r\n\tITPlayerButtonPlay\t= ITPlayerButtonPrevious + 1,\r\n\tITPlayerButtonNext\t= ITPlayerButtonPlay + 1\r\n    } \tITPlayerButton;\r\n\r\ntypedef /* [public][v1_enum][uuid] */  DECLSPEC_UUID(\"2129AB11-F23F-485e-B15A-3F8573294F9A\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0272_0006\r\n    {\tITPlayerButtonModifierKeyNone\t= 0,\r\n\tITPlayerButtonModifierKeyShift\t= 1,\r\n\tITPlayerButtonModifierKeyControl\t= 2,\r\n\tITPlayerButtonModifierKeyAlt\t= 4,\r\n\tITPlayerButtonModifierKeyCapsLock\t= 8\r\n    } \tITPlayerButtonModifierKey;\r\n\r\ntypedef /* [public][v1_enum][uuid] */  DECLSPEC_UUID(\"3194F5F4-8F52-41e6-AB8E-4221CFE29550\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0275_0001\r\n    {\tITEventDatabaseChanged\t= 1,\r\n\tITEventPlayerPlay\t= 2,\r\n\tITEventPlayerStop\t= 3,\r\n\tITEventPlayerPlayingTrackChanged\t= 4,\r\n\tITEventUserInterfaceEnabled\t= 5,\r\n\tITEventCOMCallsDisabled\t= 6,\r\n\tITEventCOMCallsEnabled\t= 7,\r\n\tITEventQuitting\t= 8,\r\n\tITEventAboutToPromptUserToQuit\t= 9,\r\n\tITEventSoundVolumeChanged\t= 10\r\n    } \tITEvent;\r\n\r\ntypedef /* [public][v1_enum][uuid] */  DECLSPEC_UUID(\"2E4D55FA-1CD3-4831-8751-0C11EC4FF6FD\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0276_0001\r\n    {\tITConvertOperationStatusChanged\t= 1,\r\n\tITConvertOperationComplete\t= 2\r\n    } \tITConvertOperationStatusEvent;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"269E36A5-1728-46e4-BF04-93032C3DD51C\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0277_0001\r\n    {\tITArtworkFormatUnknown\t= 0,\r\n\tITArtworkFormatJPEG\t= ITArtworkFormatUnknown + 1,\r\n\tITArtworkFormatPNG\t= ITArtworkFormatJPEG + 1,\r\n\tITArtworkFormatBMP\t= ITArtworkFormatPNG + 1\r\n    } \tITArtworkFormat;\r\n\r\n\r\n\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"DDE76D6E-5F8C-4bda-AFA6-69E82218CFF3\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0283_0001\r\n    {\tITPlaylistKindUnknown\t= 0,\r\n\tITPlaylistKindLibrary\t= ITPlaylistKindUnknown + 1,\r\n\tITPlaylistKindUser\t= ITPlaylistKindLibrary + 1,\r\n\tITPlaylistKindCD\t= ITPlaylistKindUser + 1,\r\n\tITPlaylistKindDevice\t= ITPlaylistKindCD + 1,\r\n\tITPlaylistKindRadioTuner\t= ITPlaylistKindDevice + 1\r\n    } \tITPlaylistKind;\r\n\r\ntypedef /* [public][public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"4E1D67A4-6C7A-4c7d-821C-03AF7EB10C35\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0283_0002\r\n    {\tITPlaylistRepeatModeOff\t= 0,\r\n\tITPlaylistRepeatModeOne\t= ITPlaylistRepeatModeOff + 1,\r\n\tITPlaylistRepeatModeAll\t= ITPlaylistRepeatModeOne + 1\r\n    } \tITPlaylistRepeatMode;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"BB8E7701-1E77-4972-B6C4-C70AC216F468\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0283_0003\r\n    {\tITPlaylistPrintKindPlaylist\t= 0,\r\n\tITPlaylistPrintKindAlbumlist\t= ITPlaylistPrintKindPlaylist + 1,\r\n\tITPlaylistPrintKindInsert\t= ITPlaylistPrintKindAlbumlist + 1\r\n    } \tITPlaylistPrintKind;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"58765E77-E34A-4d67-AC12-5B5BA33EA08F\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0283_0004\r\n    {\tITPlaylistSearchFieldAll\t= 0,\r\n\tITPlaylistSearchFieldVisible\t= ITPlaylistSearchFieldAll + 1,\r\n\tITPlaylistSearchFieldArtists\t= ITPlaylistSearchFieldVisible + 1,\r\n\tITPlaylistSearchFieldAlbums\t= ITPlaylistSearchFieldArtists + 1,\r\n\tITPlaylistSearchFieldComposers\t= ITPlaylistSearchFieldAlbums + 1,\r\n\tITPlaylistSearchFieldSongNames\t= ITPlaylistSearchFieldComposers + 1\r\n    } \tITPlaylistSearchField;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"62BC24E6-5C77-4fb7-AA6C-B7FA40C6095D\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0285_0001\r\n    {\tITUserPlaylistSpecialKindNone\t= 0,\r\n\tITUserPlaylistSpecialKindPurchasedMusic\t= ITUserPlaylistSpecialKindNone + 1,\r\n\tITUserPlaylistSpecialKindPartyShuffle\t= ITUserPlaylistSpecialKindPurchasedMusic + 1,\r\n\tITUserPlaylistSpecialKindPodcasts\t= ITUserPlaylistSpecialKindPartyShuffle + 1,\r\n\tITUserPlaylistSpecialKindFolder\t= ITUserPlaylistSpecialKindPodcasts + 1,\r\n\tITUserPlaylistSpecialKindVideos\t= ITUserPlaylistSpecialKindFolder + 1,\r\n\tITUserPlaylistSpecialKindMusic\t= ITUserPlaylistSpecialKindVideos + 1,\r\n\tITUserPlaylistSpecialKindMovies\t= ITUserPlaylistSpecialKindMusic + 1,\r\n\tITUserPlaylistSpecialKindTVShows\t= ITUserPlaylistSpecialKindMovies + 1,\r\n\tITUserPlaylistSpecialKindAudiobooks\t= ITUserPlaylistSpecialKindTVShows + 1\r\n    } \tITUserPlaylistSpecialKind;\r\n\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"5F35912B-E633-4930-9E25-09489BAED75A\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0288_0001\r\n    {\tITSourceKindUnknown\t= 0,\r\n\tITSourceKindLibrary\t= ITSourceKindUnknown + 1,\r\n\tITSourceKindIPod\t= ITSourceKindLibrary + 1,\r\n\tITSourceKindAudioCD\t= ITSourceKindIPod + 1,\r\n\tITSourceKindMP3CD\t= ITSourceKindAudioCD + 1,\r\n\tITSourceKindDevice\t= ITSourceKindMP3CD + 1,\r\n\tITSourceKindRadioTuner\t= ITSourceKindDevice + 1,\r\n\tITSourceKindSharedLibrary\t= ITSourceKindRadioTuner + 1\r\n    } \tITSourceKind;\r\n\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"ACA133C5-4697-4d5f-98B1-D9881B85FE98\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0291_0001\r\n    {\tITTrackKindUnknown\t= 0,\r\n\tITTrackKindFile\t= ITTrackKindUnknown + 1,\r\n\tITTrackKindCD\t= ITTrackKindFile + 1,\r\n\tITTrackKindURL\t= ITTrackKindCD + 1,\r\n\tITTrackKindDevice\t= ITTrackKindURL + 1,\r\n\tITTrackKindSharedLibrary\t= ITTrackKindDevice + 1\r\n    } \tITTrackKind;\r\n\r\ntypedef /* [public][public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"735ECC17-38CC-4d4d-A838-24AF7DCB440E\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0291_0002\r\n    {\tITVideoKindNone\t= 0,\r\n\tITVideoKindMovie\t= ITVideoKindNone + 1,\r\n\tITVideoKindMusicVideo\t= ITVideoKindMovie + 1,\r\n\tITVideoKindTVShow\t= ITVideoKindMusicVideo + 1\r\n    } \tITVideoKind;\r\n\r\ntypedef /* [public][public][public][public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"5C75B72C-D066-4faa-8732-D9ED71A6CBD9\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0291_0003\r\n    {\tITRatingKindUser\t= 0,\r\n\tITRatingKindComputed\t= ITRatingKindUser + 1\r\n    } \tITRatingKind;\r\n\r\ntypedef /* [public][public][v1_enum][uuid] */  DECLSPEC_UUID(\"C20CE920-EFD9-4c1a-8036-95A895741214\") \r\nenum __MIDL___MIDL_itf_iTunesCOMInterface_0297_0001\r\n    {\tITWindowKindUnknown\t= 0,\r\n\tITWindowKindBrowser\t= ITWindowKindUnknown + 1,\r\n\tITWindowKindPlaylist\t= ITWindowKindBrowser + 1,\r\n\tITWindowKindEQ\t= ITWindowKindPlaylist + 1,\r\n\tITWindowKindArtwork\t= ITWindowKindEQ + 1,\r\n\tITWindowKindNowPlaying\t= ITWindowKindArtwork + 1\r\n    } \tITWindowKind;\r\n\r\n\r\nEXTERN_C const IID LIBID_iTunesLib;\r\n\r\n#ifndef __IITObject_INTERFACE_DEFINED__\r\n#define __IITObject_INTERFACE_DEFINED__\r\n\r\n/* interface IITObject */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITObject;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"9FAB0E27-70D7-4e3a-9965-B0C8B8869BB6\")\r\n    IITObject : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetITObjectIDs( \r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Name( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Name( \r\n            /* [in] */ BSTR name) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Index( \r\n            /* [retval][out] */ long *index) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SourceID( \r\n            /* [retval][out] */ long *sourceID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlaylistID( \r\n            /* [retval][out] */ long *playlistID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_TrackID( \r\n            /* [retval][out] */ long *trackID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_TrackDatabaseID( \r\n            /* [retval][out] */ long *databaseID) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITObjectVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITObject * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITObject * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITObject * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITObject * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITObject * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITObject * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITObject * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITObject * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITObject * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITObject * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITObject * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITObject * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITObject * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITObject * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITObject * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        END_INTERFACE\r\n    } IITObjectVtbl;\r\n\r\n    interface IITObject\r\n    {\r\n        CONST_VTBL struct IITObjectVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITObject_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITObject_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITObject_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITObject_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITObject_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITObject_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITObject_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITObject_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITObject_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITObject_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITObject_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITObject_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITObject_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITObject_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITObject_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITObject_GetITObjectIDs_Proxy( \r\n    IITObject * This,\r\n    /* [out] */ long *sourceID,\r\n    /* [out] */ long *playlistID,\r\n    /* [out] */ long *trackID,\r\n    /* [out] */ long *databaseID);\r\n\r\n\r\nvoid __RPC_STUB IITObject_GetITObjectIDs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_Name_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITObject_put_Name_Proxy( \r\n    IITObject * This,\r\n    /* [in] */ BSTR name);\r\n\r\n\r\nvoid __RPC_STUB IITObject_put_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_Index_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ long *index);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_Index_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_SourceID_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ long *sourceID);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_SourceID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_PlaylistID_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ long *playlistID);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_PlaylistID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_TrackID_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ long *trackID);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_TrackID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITObject_get_TrackDatabaseID_Proxy( \r\n    IITObject * This,\r\n    /* [retval][out] */ long *databaseID);\r\n\r\n\r\nvoid __RPC_STUB IITObject_get_TrackDatabaseID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITObject_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITSource_INTERFACE_DEFINED__\r\n#define __IITSource_INTERFACE_DEFINED__\r\n\r\n/* interface IITSource */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITSource;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"AEC1C4D3-AEF1-4255-B892-3E3D13ADFDF9\")\r\n    IITSource : public IITObject\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Kind( \r\n            /* [retval][out] */ ITSourceKind *kind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Capacity( \r\n            /* [retval][out] */ double *capacity) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_FreeSpace( \r\n            /* [retval][out] */ double *freespace) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Playlists( \r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITSourceVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITSource * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITSource * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITSource * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITSource * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITSource * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITSource * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITSource * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITSource * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITSource * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITSource * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITSource * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITSource * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITSource * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITSource * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITSource * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITSource * This,\r\n            /* [retval][out] */ ITSourceKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Capacity )( \r\n            IITSource * This,\r\n            /* [retval][out] */ double *capacity);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FreeSpace )( \r\n            IITSource * This,\r\n            /* [retval][out] */ double *freespace);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlists )( \r\n            IITSource * This,\r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITSourceVtbl;\r\n\r\n    interface IITSource\r\n    {\r\n        CONST_VTBL struct IITSourceVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITSource_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITSource_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITSource_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITSource_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITSource_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITSource_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITSource_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITSource_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITSource_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITSource_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITSource_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITSource_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITSource_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITSource_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITSource_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITSource_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITSource_get_Capacity(This,capacity)\t\\\r\n    (This)->lpVtbl -> get_Capacity(This,capacity)\r\n\r\n#define IITSource_get_FreeSpace(This,freespace)\t\\\r\n    (This)->lpVtbl -> get_FreeSpace(This,freespace)\r\n\r\n#define IITSource_get_Playlists(This,iPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_Playlists(This,iPlaylistCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSource_get_Kind_Proxy( \r\n    IITSource * This,\r\n    /* [retval][out] */ ITSourceKind *kind);\r\n\r\n\r\nvoid __RPC_STUB IITSource_get_Kind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSource_get_Capacity_Proxy( \r\n    IITSource * This,\r\n    /* [retval][out] */ double *capacity);\r\n\r\n\r\nvoid __RPC_STUB IITSource_get_Capacity_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSource_get_FreeSpace_Proxy( \r\n    IITSource * This,\r\n    /* [retval][out] */ double *freespace);\r\n\r\n\r\nvoid __RPC_STUB IITSource_get_FreeSpace_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSource_get_Playlists_Proxy( \r\n    IITSource * This,\r\n    /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n\r\n\r\nvoid __RPC_STUB IITSource_get_Playlists_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITSource_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITSourceCollection_INTERFACE_DEFINED__\r\n#define __IITSourceCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITSourceCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITSourceCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"2FF6CE20-FF87-4183-B0B3-F323D047AF41\")\r\n    IITSourceCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITSource **iSource) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITSource **iSource) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByPersistentID( \r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITSource **iSource) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITSourceCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITSourceCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITSourceCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITSourceCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITSourceCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITSourceCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByPersistentID )( \r\n            IITSourceCollection * This,\r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        END_INTERFACE\r\n    } IITSourceCollectionVtbl;\r\n\r\n    interface IITSourceCollection\r\n    {\r\n        CONST_VTBL struct IITSourceCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITSourceCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITSourceCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITSourceCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITSourceCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITSourceCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITSourceCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITSourceCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITSourceCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITSourceCollection_get_Item(This,index,iSource)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iSource)\r\n\r\n#define IITSourceCollection_get_ItemByName(This,name,iSource)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iSource)\r\n\r\n#define IITSourceCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#define IITSourceCollection_get_ItemByPersistentID(This,highID,lowID,iSource)\t\\\r\n    (This)->lpVtbl -> get_ItemByPersistentID(This,highID,lowID,iSource)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSourceCollection_get_Count_Proxy( \r\n    IITSourceCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITSourceCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITSourceCollection_get_Item_Proxy( \r\n    IITSourceCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITSource **iSource);\r\n\r\n\r\nvoid __RPC_STUB IITSourceCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSourceCollection_get_ItemByName_Proxy( \r\n    IITSourceCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITSource **iSource);\r\n\r\n\r\nvoid __RPC_STUB IITSourceCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITSourceCollection_get__NewEnum_Proxy( \r\n    IITSourceCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITSourceCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITSourceCollection_get_ItemByPersistentID_Proxy( \r\n    IITSourceCollection * This,\r\n    /* [in] */ long highID,\r\n    /* [in] */ long lowID,\r\n    /* [retval][out] */ IITSource **iSource);\r\n\r\n\r\nvoid __RPC_STUB IITSourceCollection_get_ItemByPersistentID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITSourceCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEncoder_INTERFACE_DEFINED__\r\n#define __IITEncoder_INTERFACE_DEFINED__\r\n\r\n/* interface IITEncoder */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITEncoder;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"1CF95A1C-55FE-4f45-A2D3-85AC6C504A73\")\r\n    IITEncoder : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Name( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Format( \r\n            /* [retval][out] */ BSTR *format) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITEncoderVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITEncoder * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITEncoder * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITEncoder * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITEncoder * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITEncoder * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITEncoder * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITEncoder * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITEncoder * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Format )( \r\n            IITEncoder * This,\r\n            /* [retval][out] */ BSTR *format);\r\n        \r\n        END_INTERFACE\r\n    } IITEncoderVtbl;\r\n\r\n    interface IITEncoder\r\n    {\r\n        CONST_VTBL struct IITEncoderVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITEncoder_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITEncoder_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITEncoder_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITEncoder_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITEncoder_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITEncoder_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITEncoder_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITEncoder_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITEncoder_get_Format(This,format)\t\\\r\n    (This)->lpVtbl -> get_Format(This,format)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEncoder_get_Name_Proxy( \r\n    IITEncoder * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITEncoder_get_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEncoder_get_Format_Proxy( \r\n    IITEncoder * This,\r\n    /* [retval][out] */ BSTR *format);\r\n\r\n\r\nvoid __RPC_STUB IITEncoder_get_Format_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITEncoder_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEncoderCollection_INTERFACE_DEFINED__\r\n#define __IITEncoderCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITEncoderCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITEncoderCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"8862BCA9-168D-4549-A9D5-ADB35E553BA6\")\r\n    IITEncoderCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITEncoder **iEncoder) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITEncoder **iEncoder) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITEncoderCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITEncoderCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITEncoderCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITEncoderCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITEncoderCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITEncoder **iEncoder);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITEncoderCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITEncoder **iEncoder);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITEncoderCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        END_INTERFACE\r\n    } IITEncoderCollectionVtbl;\r\n\r\n    interface IITEncoderCollection\r\n    {\r\n        CONST_VTBL struct IITEncoderCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITEncoderCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITEncoderCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITEncoderCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITEncoderCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITEncoderCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITEncoderCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITEncoderCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITEncoderCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITEncoderCollection_get_Item(This,index,iEncoder)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iEncoder)\r\n\r\n#define IITEncoderCollection_get_ItemByName(This,name,iEncoder)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iEncoder)\r\n\r\n#define IITEncoderCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEncoderCollection_get_Count_Proxy( \r\n    IITEncoderCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITEncoderCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITEncoderCollection_get_Item_Proxy( \r\n    IITEncoderCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITEncoder **iEncoder);\r\n\r\n\r\nvoid __RPC_STUB IITEncoderCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEncoderCollection_get_ItemByName_Proxy( \r\n    IITEncoderCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITEncoder **iEncoder);\r\n\r\n\r\nvoid __RPC_STUB IITEncoderCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITEncoderCollection_get__NewEnum_Proxy( \r\n    IITEncoderCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITEncoderCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITEncoderCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEQPreset_INTERFACE_DEFINED__\r\n#define __IITEQPreset_INTERFACE_DEFINED__\r\n\r\n/* interface IITEQPreset */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITEQPreset;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"5BE75F4F-68FA-4212-ACB7-BE44EA569759\")\r\n    IITEQPreset : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Name( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Modifiable( \r\n            /* [retval][out] */ VARIANT_BOOL *isModifiable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Preamp( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Preamp( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band1( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band1( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band2( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band2( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band3( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band3( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band4( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band4( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band5( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band5( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band6( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band6( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band7( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band7( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band8( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band8( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band9( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band9( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Band10( \r\n            /* [retval][out] */ double *level) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Band10( \r\n            /* [in] */ double level) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Delete( \r\n            /* [in] */ VARIANT_BOOL updateAllTracks) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Rename( \r\n            /* [in] */ BSTR newName,\r\n            /* [in] */ VARIANT_BOOL updateAllTracks) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITEQPresetVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITEQPreset * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITEQPreset * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITEQPreset * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITEQPreset * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITEQPreset * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITEQPreset * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITEQPreset * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Modifiable )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isModifiable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Preamp )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Preamp )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band1 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band1 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band2 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band2 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band3 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band3 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band4 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band4 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band5 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band5 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band6 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band6 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band7 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band7 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band8 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band8 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band9 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band9 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Band10 )( \r\n            IITEQPreset * This,\r\n            /* [retval][out] */ double *level);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Band10 )( \r\n            IITEQPreset * This,\r\n            /* [in] */ double level);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITEQPreset * This,\r\n            /* [in] */ VARIANT_BOOL updateAllTracks);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Rename )( \r\n            IITEQPreset * This,\r\n            /* [in] */ BSTR newName,\r\n            /* [in] */ VARIANT_BOOL updateAllTracks);\r\n        \r\n        END_INTERFACE\r\n    } IITEQPresetVtbl;\r\n\r\n    interface IITEQPreset\r\n    {\r\n        CONST_VTBL struct IITEQPresetVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITEQPreset_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITEQPreset_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITEQPreset_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITEQPreset_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITEQPreset_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITEQPreset_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITEQPreset_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITEQPreset_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITEQPreset_get_Modifiable(This,isModifiable)\t\\\r\n    (This)->lpVtbl -> get_Modifiable(This,isModifiable)\r\n\r\n#define IITEQPreset_get_Preamp(This,level)\t\\\r\n    (This)->lpVtbl -> get_Preamp(This,level)\r\n\r\n#define IITEQPreset_put_Preamp(This,level)\t\\\r\n    (This)->lpVtbl -> put_Preamp(This,level)\r\n\r\n#define IITEQPreset_get_Band1(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band1(This,level)\r\n\r\n#define IITEQPreset_put_Band1(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band1(This,level)\r\n\r\n#define IITEQPreset_get_Band2(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band2(This,level)\r\n\r\n#define IITEQPreset_put_Band2(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band2(This,level)\r\n\r\n#define IITEQPreset_get_Band3(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band3(This,level)\r\n\r\n#define IITEQPreset_put_Band3(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band3(This,level)\r\n\r\n#define IITEQPreset_get_Band4(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band4(This,level)\r\n\r\n#define IITEQPreset_put_Band4(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band4(This,level)\r\n\r\n#define IITEQPreset_get_Band5(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band5(This,level)\r\n\r\n#define IITEQPreset_put_Band5(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band5(This,level)\r\n\r\n#define IITEQPreset_get_Band6(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band6(This,level)\r\n\r\n#define IITEQPreset_put_Band6(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band6(This,level)\r\n\r\n#define IITEQPreset_get_Band7(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band7(This,level)\r\n\r\n#define IITEQPreset_put_Band7(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band7(This,level)\r\n\r\n#define IITEQPreset_get_Band8(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band8(This,level)\r\n\r\n#define IITEQPreset_put_Band8(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band8(This,level)\r\n\r\n#define IITEQPreset_get_Band9(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band9(This,level)\r\n\r\n#define IITEQPreset_put_Band9(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band9(This,level)\r\n\r\n#define IITEQPreset_get_Band10(This,level)\t\\\r\n    (This)->lpVtbl -> get_Band10(This,level)\r\n\r\n#define IITEQPreset_put_Band10(This,level)\t\\\r\n    (This)->lpVtbl -> put_Band10(This,level)\r\n\r\n#define IITEQPreset_Delete(This,updateAllTracks)\t\\\r\n    (This)->lpVtbl -> Delete(This,updateAllTracks)\r\n\r\n#define IITEQPreset_Rename(This,newName,updateAllTracks)\t\\\r\n    (This)->lpVtbl -> Rename(This,newName,updateAllTracks)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Name_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Modifiable_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isModifiable);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Modifiable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Preamp_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Preamp_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Preamp_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Preamp_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band1_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band1_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band1_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band1_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band2_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band2_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band3_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band3_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band3_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band3_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band4_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band4_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band4_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band4_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band5_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band5_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band5_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band5_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band6_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band6_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band6_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band6_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band7_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band7_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band7_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band7_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band8_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band8_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band8_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band8_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band9_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band9_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band9_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band9_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPreset_get_Band10_Proxy( \r\n    IITEQPreset * This,\r\n    /* [retval][out] */ double *level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_get_Band10_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITEQPreset_put_Band10_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ double level);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_put_Band10_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITEQPreset_Delete_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ VARIANT_BOOL updateAllTracks);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_Delete_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITEQPreset_Rename_Proxy( \r\n    IITEQPreset * This,\r\n    /* [in] */ BSTR newName,\r\n    /* [in] */ VARIANT_BOOL updateAllTracks);\r\n\r\n\r\nvoid __RPC_STUB IITEQPreset_Rename_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITEQPreset_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITEQPresetCollection_INTERFACE_DEFINED__\r\n#define __IITEQPresetCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITEQPresetCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITEQPresetCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"AEF4D111-3331-48da-B0C2-B468D5D61D08\")\r\n    IITEQPresetCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITEQPresetCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITEQPresetCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITEQPresetCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITEQPresetCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITEQPresetCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITEQPresetCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITEQPresetCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        END_INTERFACE\r\n    } IITEQPresetCollectionVtbl;\r\n\r\n    interface IITEQPresetCollection\r\n    {\r\n        CONST_VTBL struct IITEQPresetCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITEQPresetCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITEQPresetCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITEQPresetCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITEQPresetCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITEQPresetCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITEQPresetCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITEQPresetCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITEQPresetCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITEQPresetCollection_get_Item(This,index,iEQPreset)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iEQPreset)\r\n\r\n#define IITEQPresetCollection_get_ItemByName(This,name,iEQPreset)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iEQPreset)\r\n\r\n#define IITEQPresetCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPresetCollection_get_Count_Proxy( \r\n    IITEQPresetCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITEQPresetCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITEQPresetCollection_get_Item_Proxy( \r\n    IITEQPresetCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITEQPreset **iEQPreset);\r\n\r\n\r\nvoid __RPC_STUB IITEQPresetCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITEQPresetCollection_get_ItemByName_Proxy( \r\n    IITEQPresetCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITEQPreset **iEQPreset);\r\n\r\n\r\nvoid __RPC_STUB IITEQPresetCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITEQPresetCollection_get__NewEnum_Proxy( \r\n    IITEQPresetCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITEQPresetCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITEQPresetCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylist_INTERFACE_DEFINED__\r\n#define __IITPlaylist_INTERFACE_DEFINED__\r\n\r\n/* interface IITPlaylist */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITPlaylist;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"3D5E072F-2A77-4b17-9E73-E03B77CCCCA9\")\r\n    IITPlaylist : public IITObject\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Delete( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PlayFirstTrack( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Print( \r\n            /* [in] */ VARIANT_BOOL showPrintDialog,\r\n            /* [in] */ ITPlaylistPrintKind printKind,\r\n            /* [in] */ BSTR theme) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Search( \r\n            /* [in] */ BSTR searchText,\r\n            /* [in] */ ITPlaylistSearchField searchFields,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Kind( \r\n            /* [retval][out] */ ITPlaylistKind *kind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Source( \r\n            /* [retval][out] */ IITSource **iSource) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Duration( \r\n            /* [retval][out] */ long *duration) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Shuffle( \r\n            /* [retval][out] */ VARIANT_BOOL *isShuffle) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Shuffle( \r\n            /* [in] */ VARIANT_BOOL shouldShuffle) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Size( \r\n            /* [retval][out] */ double *size) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SongRepeat( \r\n            /* [retval][out] */ ITPlaylistRepeatMode *repeatMode) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SongRepeat( \r\n            /* [in] */ ITPlaylistRepeatMode repeatMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Time( \r\n            /* [retval][out] */ BSTR *time) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Visible( \r\n            /* [retval][out] */ VARIANT_BOOL *isVisible) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Tracks( \r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITPlaylistVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITPlaylist * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITPlaylist * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITPlaylist * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITPlaylist * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITPlaylist * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITPlaylist * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITPlaylist * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayFirstTrack )( \r\n            IITPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Print )( \r\n            IITPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL showPrintDialog,\r\n            /* [in] */ ITPlaylistPrintKind printKind,\r\n            /* [in] */ BSTR theme);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Search )( \r\n            IITPlaylist * This,\r\n            /* [in] */ BSTR searchText,\r\n            /* [in] */ ITPlaylistSearchField searchFields,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Source )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Shuffle )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isShuffle);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Shuffle )( \r\n            IITPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL shouldShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ double *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SongRepeat )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistRepeatMode *repeatMode);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SongRepeat )( \r\n            IITPlaylist * This,\r\n            /* [in] */ ITPlaylistRepeatMode repeatMode);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITPlaylist * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITPlaylistVtbl;\r\n\r\n    interface IITPlaylist\r\n    {\r\n        CONST_VTBL struct IITPlaylistVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITPlaylist_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITPlaylist_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITPlaylist_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITPlaylist_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITPlaylist_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITPlaylist_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITPlaylist_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITPlaylist_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITPlaylist_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITPlaylist_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITPlaylist_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITPlaylist_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITPlaylist_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITPlaylist_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITPlaylist_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITPlaylist_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITPlaylist_PlayFirstTrack(This)\t\\\r\n    (This)->lpVtbl -> PlayFirstTrack(This)\r\n\r\n#define IITPlaylist_Print(This,showPrintDialog,printKind,theme)\t\\\r\n    (This)->lpVtbl -> Print(This,showPrintDialog,printKind,theme)\r\n\r\n#define IITPlaylist_Search(This,searchText,searchFields,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> Search(This,searchText,searchFields,iTrackCollection)\r\n\r\n#define IITPlaylist_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITPlaylist_get_Source(This,iSource)\t\\\r\n    (This)->lpVtbl -> get_Source(This,iSource)\r\n\r\n#define IITPlaylist_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITPlaylist_get_Shuffle(This,isShuffle)\t\\\r\n    (This)->lpVtbl -> get_Shuffle(This,isShuffle)\r\n\r\n#define IITPlaylist_put_Shuffle(This,shouldShuffle)\t\\\r\n    (This)->lpVtbl -> put_Shuffle(This,shouldShuffle)\r\n\r\n#define IITPlaylist_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITPlaylist_get_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> get_SongRepeat(This,repeatMode)\r\n\r\n#define IITPlaylist_put_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> put_SongRepeat(This,repeatMode)\r\n\r\n#define IITPlaylist_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITPlaylist_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITPlaylist_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITPlaylist_Delete_Proxy( \r\n    IITPlaylist * This);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_Delete_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITPlaylist_PlayFirstTrack_Proxy( \r\n    IITPlaylist * This);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_PlayFirstTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITPlaylist_Print_Proxy( \r\n    IITPlaylist * This,\r\n    /* [in] */ VARIANT_BOOL showPrintDialog,\r\n    /* [in] */ ITPlaylistPrintKind printKind,\r\n    /* [in] */ BSTR theme);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_Print_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITPlaylist_Search_Proxy( \r\n    IITPlaylist * This,\r\n    /* [in] */ BSTR searchText,\r\n    /* [in] */ ITPlaylistSearchField searchFields,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_Search_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Kind_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ ITPlaylistKind *kind);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Kind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Source_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ IITSource **iSource);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Source_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Duration_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ long *duration);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Duration_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Shuffle_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isShuffle);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Shuffle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITPlaylist_put_Shuffle_Proxy( \r\n    IITPlaylist * This,\r\n    /* [in] */ VARIANT_BOOL shouldShuffle);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_put_Shuffle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Size_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ double *size);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Size_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_SongRepeat_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ ITPlaylistRepeatMode *repeatMode);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_SongRepeat_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITPlaylist_put_SongRepeat_Proxy( \r\n    IITPlaylist * This,\r\n    /* [in] */ ITPlaylistRepeatMode repeatMode);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_put_SongRepeat_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Time_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ BSTR *time);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Time_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Visible_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Visible_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylist_get_Tracks_Proxy( \r\n    IITPlaylist * This,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylist_get_Tracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITPlaylist_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITOperationStatus_INTERFACE_DEFINED__\r\n#define __IITOperationStatus_INTERFACE_DEFINED__\r\n\r\n/* interface IITOperationStatus */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITOperationStatus;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"206479C9-FE32-4f9b-A18A-475AC939B479\")\r\n    IITOperationStatus : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_InProgress( \r\n            /* [retval][out] */ VARIANT_BOOL *isInProgress) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Tracks( \r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITOperationStatusVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITOperationStatus * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITOperationStatus * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITOperationStatus * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITOperationStatus * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITOperationStatus * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITOperationStatus * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITOperationStatus * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_InProgress )( \r\n            IITOperationStatus * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isInProgress);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITOperationStatus * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITOperationStatusVtbl;\r\n\r\n    interface IITOperationStatus\r\n    {\r\n        CONST_VTBL struct IITOperationStatusVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITOperationStatus_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITOperationStatus_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITOperationStatus_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITOperationStatus_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITOperationStatus_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITOperationStatus_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITOperationStatus_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITOperationStatus_get_InProgress(This,isInProgress)\t\\\r\n    (This)->lpVtbl -> get_InProgress(This,isInProgress)\r\n\r\n#define IITOperationStatus_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITOperationStatus_get_InProgress_Proxy( \r\n    IITOperationStatus * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isInProgress);\r\n\r\n\r\nvoid __RPC_STUB IITOperationStatus_get_InProgress_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITOperationStatus_get_Tracks_Proxy( \r\n    IITOperationStatus * This,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IITOperationStatus_get_Tracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITOperationStatus_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITConvertOperationStatus_INTERFACE_DEFINED__\r\n#define __IITConvertOperationStatus_INTERFACE_DEFINED__\r\n\r\n/* interface IITConvertOperationStatus */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITConvertOperationStatus;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"7063AAF6-ABA0-493b-B4FC-920A9F105875\")\r\n    IITConvertOperationStatus : public IITOperationStatus\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetConversionStatus( \r\n            /* [out] */ BSTR *trackName,\r\n            /* [out] */ long *progressValue,\r\n            /* [out] */ long *maxProgressValue) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE StopConversion( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_TrackName( \r\n            /* [retval][out] */ BSTR *trackName) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ProgressValue( \r\n            /* [retval][out] */ long *progressValue) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_MaxProgressValue( \r\n            /* [retval][out] */ long *maxProgressValue) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITConvertOperationStatusVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITConvertOperationStatus * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITConvertOperationStatus * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITConvertOperationStatus * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITConvertOperationStatus * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITConvertOperationStatus * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITConvertOperationStatus * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITConvertOperationStatus * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_InProgress )( \r\n            IITConvertOperationStatus * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isInProgress);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITConvertOperationStatus * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetConversionStatus )( \r\n            IITConvertOperationStatus * This,\r\n            /* [out] */ BSTR *trackName,\r\n            /* [out] */ long *progressValue,\r\n            /* [out] */ long *maxProgressValue);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *StopConversion )( \r\n            IITConvertOperationStatus * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackName )( \r\n            IITConvertOperationStatus * This,\r\n            /* [retval][out] */ BSTR *trackName);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ProgressValue )( \r\n            IITConvertOperationStatus * This,\r\n            /* [retval][out] */ long *progressValue);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_MaxProgressValue )( \r\n            IITConvertOperationStatus * This,\r\n            /* [retval][out] */ long *maxProgressValue);\r\n        \r\n        END_INTERFACE\r\n    } IITConvertOperationStatusVtbl;\r\n\r\n    interface IITConvertOperationStatus\r\n    {\r\n        CONST_VTBL struct IITConvertOperationStatusVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITConvertOperationStatus_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITConvertOperationStatus_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITConvertOperationStatus_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITConvertOperationStatus_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITConvertOperationStatus_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITConvertOperationStatus_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITConvertOperationStatus_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITConvertOperationStatus_get_InProgress(This,isInProgress)\t\\\r\n    (This)->lpVtbl -> get_InProgress(This,isInProgress)\r\n\r\n#define IITConvertOperationStatus_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n\r\n#define IITConvertOperationStatus_GetConversionStatus(This,trackName,progressValue,maxProgressValue)\t\\\r\n    (This)->lpVtbl -> GetConversionStatus(This,trackName,progressValue,maxProgressValue)\r\n\r\n#define IITConvertOperationStatus_StopConversion(This)\t\\\r\n    (This)->lpVtbl -> StopConversion(This)\r\n\r\n#define IITConvertOperationStatus_get_TrackName(This,trackName)\t\\\r\n    (This)->lpVtbl -> get_TrackName(This,trackName)\r\n\r\n#define IITConvertOperationStatus_get_ProgressValue(This,progressValue)\t\\\r\n    (This)->lpVtbl -> get_ProgressValue(This,progressValue)\r\n\r\n#define IITConvertOperationStatus_get_MaxProgressValue(This,maxProgressValue)\t\\\r\n    (This)->lpVtbl -> get_MaxProgressValue(This,maxProgressValue)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITConvertOperationStatus_GetConversionStatus_Proxy( \r\n    IITConvertOperationStatus * This,\r\n    /* [out] */ BSTR *trackName,\r\n    /* [out] */ long *progressValue,\r\n    /* [out] */ long *maxProgressValue);\r\n\r\n\r\nvoid __RPC_STUB IITConvertOperationStatus_GetConversionStatus_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITConvertOperationStatus_StopConversion_Proxy( \r\n    IITConvertOperationStatus * This);\r\n\r\n\r\nvoid __RPC_STUB IITConvertOperationStatus_StopConversion_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITConvertOperationStatus_get_TrackName_Proxy( \r\n    IITConvertOperationStatus * This,\r\n    /* [retval][out] */ BSTR *trackName);\r\n\r\n\r\nvoid __RPC_STUB IITConvertOperationStatus_get_TrackName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITConvertOperationStatus_get_ProgressValue_Proxy( \r\n    IITConvertOperationStatus * This,\r\n    /* [retval][out] */ long *progressValue);\r\n\r\n\r\nvoid __RPC_STUB IITConvertOperationStatus_get_ProgressValue_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITConvertOperationStatus_get_MaxProgressValue_Proxy( \r\n    IITConvertOperationStatus * This,\r\n    /* [retval][out] */ long *maxProgressValue);\r\n\r\n\r\nvoid __RPC_STUB IITConvertOperationStatus_get_MaxProgressValue_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITConvertOperationStatus_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITLibraryPlaylist_INTERFACE_DEFINED__\r\n#define __IITLibraryPlaylist_INTERFACE_DEFINED__\r\n\r\n/* interface IITLibraryPlaylist */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITLibraryPlaylist;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"53AE1704-491C-4289-94A0-958815675A3D\")\r\n    IITLibraryPlaylist : public IITPlaylist\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddFile( \r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddFiles( \r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddURL( \r\n            /* [in] */ BSTR url,\r\n            /* [retval][out] */ IITURLTrack **iURLTrack) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddTrack( \r\n            /* [in] */ VARIANT *iTrackToAdd,\r\n            /* [retval][out] */ IITTrack **iAddedTrack) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITLibraryPlaylistVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITLibraryPlaylist * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITLibraryPlaylist * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITLibraryPlaylist * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITLibraryPlaylist * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITLibraryPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayFirstTrack )( \r\n            IITLibraryPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Print )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL showPrintDialog,\r\n            /* [in] */ ITPlaylistPrintKind printKind,\r\n            /* [in] */ BSTR theme);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Search )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ BSTR searchText,\r\n            /* [in] */ ITPlaylistSearchField searchFields,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Source )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Shuffle )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isShuffle);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Shuffle )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL shouldShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ double *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SongRepeat )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistRepeatMode *repeatMode);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SongRepeat )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ ITPlaylistRepeatMode repeatMode);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITLibraryPlaylist * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddFile )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddFiles )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddURL )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ BSTR url,\r\n            /* [retval][out] */ IITURLTrack **iURLTrack);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddTrack )( \r\n            IITLibraryPlaylist * This,\r\n            /* [in] */ VARIANT *iTrackToAdd,\r\n            /* [retval][out] */ IITTrack **iAddedTrack);\r\n        \r\n        END_INTERFACE\r\n    } IITLibraryPlaylistVtbl;\r\n\r\n    interface IITLibraryPlaylist\r\n    {\r\n        CONST_VTBL struct IITLibraryPlaylistVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITLibraryPlaylist_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITLibraryPlaylist_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITLibraryPlaylist_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITLibraryPlaylist_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITLibraryPlaylist_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITLibraryPlaylist_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITLibraryPlaylist_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITLibraryPlaylist_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITLibraryPlaylist_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITLibraryPlaylist_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITLibraryPlaylist_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITLibraryPlaylist_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITLibraryPlaylist_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITLibraryPlaylist_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITLibraryPlaylist_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITLibraryPlaylist_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITLibraryPlaylist_PlayFirstTrack(This)\t\\\r\n    (This)->lpVtbl -> PlayFirstTrack(This)\r\n\r\n#define IITLibraryPlaylist_Print(This,showPrintDialog,printKind,theme)\t\\\r\n    (This)->lpVtbl -> Print(This,showPrintDialog,printKind,theme)\r\n\r\n#define IITLibraryPlaylist_Search(This,searchText,searchFields,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> Search(This,searchText,searchFields,iTrackCollection)\r\n\r\n#define IITLibraryPlaylist_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITLibraryPlaylist_get_Source(This,iSource)\t\\\r\n    (This)->lpVtbl -> get_Source(This,iSource)\r\n\r\n#define IITLibraryPlaylist_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITLibraryPlaylist_get_Shuffle(This,isShuffle)\t\\\r\n    (This)->lpVtbl -> get_Shuffle(This,isShuffle)\r\n\r\n#define IITLibraryPlaylist_put_Shuffle(This,shouldShuffle)\t\\\r\n    (This)->lpVtbl -> put_Shuffle(This,shouldShuffle)\r\n\r\n#define IITLibraryPlaylist_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITLibraryPlaylist_get_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> get_SongRepeat(This,repeatMode)\r\n\r\n#define IITLibraryPlaylist_put_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> put_SongRepeat(This,repeatMode)\r\n\r\n#define IITLibraryPlaylist_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITLibraryPlaylist_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITLibraryPlaylist_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n\r\n#define IITLibraryPlaylist_AddFile(This,filePath,iStatus)\t\\\r\n    (This)->lpVtbl -> AddFile(This,filePath,iStatus)\r\n\r\n#define IITLibraryPlaylist_AddFiles(This,filePaths,iStatus)\t\\\r\n    (This)->lpVtbl -> AddFiles(This,filePaths,iStatus)\r\n\r\n#define IITLibraryPlaylist_AddURL(This,url,iURLTrack)\t\\\r\n    (This)->lpVtbl -> AddURL(This,url,iURLTrack)\r\n\r\n#define IITLibraryPlaylist_AddTrack(This,iTrackToAdd,iAddedTrack)\t\\\r\n    (This)->lpVtbl -> AddTrack(This,iTrackToAdd,iAddedTrack)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITLibraryPlaylist_AddFile_Proxy( \r\n    IITLibraryPlaylist * This,\r\n    /* [in] */ BSTR filePath,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IITLibraryPlaylist_AddFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITLibraryPlaylist_AddFiles_Proxy( \r\n    IITLibraryPlaylist * This,\r\n    /* [in] */ VARIANT *filePaths,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IITLibraryPlaylist_AddFiles_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITLibraryPlaylist_AddURL_Proxy( \r\n    IITLibraryPlaylist * This,\r\n    /* [in] */ BSTR url,\r\n    /* [retval][out] */ IITURLTrack **iURLTrack);\r\n\r\n\r\nvoid __RPC_STUB IITLibraryPlaylist_AddURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITLibraryPlaylist_AddTrack_Proxy( \r\n    IITLibraryPlaylist * This,\r\n    /* [in] */ VARIANT *iTrackToAdd,\r\n    /* [retval][out] */ IITTrack **iAddedTrack);\r\n\r\n\r\nvoid __RPC_STUB IITLibraryPlaylist_AddTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITLibraryPlaylist_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITUserPlaylist_INTERFACE_DEFINED__\r\n#define __IITUserPlaylist_INTERFACE_DEFINED__\r\n\r\n/* interface IITUserPlaylist */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITUserPlaylist;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"0A504DED-A0B5-465a-8A94-50E20D7DF692\")\r\n    IITUserPlaylist : public IITPlaylist\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddFile( \r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddFiles( \r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddURL( \r\n            /* [in] */ BSTR url,\r\n            /* [retval][out] */ IITURLTrack **iURLTrack) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddTrack( \r\n            /* [in] */ VARIANT *iTrackToAdd,\r\n            /* [retval][out] */ IITTrack **iAddedTrack) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Shared( \r\n            /* [retval][out] */ VARIANT_BOOL *isShared) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Shared( \r\n            /* [in] */ VARIANT_BOOL shouldBeShared) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Smart( \r\n            /* [retval][out] */ VARIANT_BOOL *isSmart) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SpecialKind( \r\n            /* [retval][out] */ ITUserPlaylistSpecialKind *specialKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Parent( \r\n            /* [retval][out] */ IITUserPlaylist **iParentPlayList) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreatePlaylist( \r\n            /* [in] */ BSTR playlistName,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreateFolder( \r\n            /* [in] */ BSTR folderName,\r\n            /* [retval][out] */ IITPlaylist **iFolder) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Parent( \r\n            /* [in] */ VARIANT *iParent) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Reveal( void) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITUserPlaylistVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITUserPlaylist * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITUserPlaylist * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITUserPlaylist * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITUserPlaylist * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITUserPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayFirstTrack )( \r\n            IITUserPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Print )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL showPrintDialog,\r\n            /* [in] */ ITPlaylistPrintKind printKind,\r\n            /* [in] */ BSTR theme);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Search )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR searchText,\r\n            /* [in] */ ITPlaylistSearchField searchFields,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Source )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Shuffle )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isShuffle);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Shuffle )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL shouldShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ double *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SongRepeat )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistRepeatMode *repeatMode);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SongRepeat )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ ITPlaylistRepeatMode repeatMode);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddFile )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddFiles )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddURL )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR url,\r\n            /* [retval][out] */ IITURLTrack **iURLTrack);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddTrack )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT *iTrackToAdd,\r\n            /* [retval][out] */ IITTrack **iAddedTrack);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Shared )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isShared);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Shared )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeShared);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Smart )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isSmart);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SpecialKind )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ ITUserPlaylistSpecialKind *specialKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Parent )( \r\n            IITUserPlaylist * This,\r\n            /* [retval][out] */ IITUserPlaylist **iParentPlayList);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreatePlaylist )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR playlistName,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreateFolder )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ BSTR folderName,\r\n            /* [retval][out] */ IITPlaylist **iFolder);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Parent )( \r\n            IITUserPlaylist * This,\r\n            /* [in] */ VARIANT *iParent);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Reveal )( \r\n            IITUserPlaylist * This);\r\n        \r\n        END_INTERFACE\r\n    } IITUserPlaylistVtbl;\r\n\r\n    interface IITUserPlaylist\r\n    {\r\n        CONST_VTBL struct IITUserPlaylistVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITUserPlaylist_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITUserPlaylist_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITUserPlaylist_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITUserPlaylist_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITUserPlaylist_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITUserPlaylist_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITUserPlaylist_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITUserPlaylist_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITUserPlaylist_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITUserPlaylist_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITUserPlaylist_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITUserPlaylist_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITUserPlaylist_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITUserPlaylist_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITUserPlaylist_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITUserPlaylist_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITUserPlaylist_PlayFirstTrack(This)\t\\\r\n    (This)->lpVtbl -> PlayFirstTrack(This)\r\n\r\n#define IITUserPlaylist_Print(This,showPrintDialog,printKind,theme)\t\\\r\n    (This)->lpVtbl -> Print(This,showPrintDialog,printKind,theme)\r\n\r\n#define IITUserPlaylist_Search(This,searchText,searchFields,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> Search(This,searchText,searchFields,iTrackCollection)\r\n\r\n#define IITUserPlaylist_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITUserPlaylist_get_Source(This,iSource)\t\\\r\n    (This)->lpVtbl -> get_Source(This,iSource)\r\n\r\n#define IITUserPlaylist_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITUserPlaylist_get_Shuffle(This,isShuffle)\t\\\r\n    (This)->lpVtbl -> get_Shuffle(This,isShuffle)\r\n\r\n#define IITUserPlaylist_put_Shuffle(This,shouldShuffle)\t\\\r\n    (This)->lpVtbl -> put_Shuffle(This,shouldShuffle)\r\n\r\n#define IITUserPlaylist_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITUserPlaylist_get_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> get_SongRepeat(This,repeatMode)\r\n\r\n#define IITUserPlaylist_put_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> put_SongRepeat(This,repeatMode)\r\n\r\n#define IITUserPlaylist_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITUserPlaylist_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITUserPlaylist_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n\r\n#define IITUserPlaylist_AddFile(This,filePath,iStatus)\t\\\r\n    (This)->lpVtbl -> AddFile(This,filePath,iStatus)\r\n\r\n#define IITUserPlaylist_AddFiles(This,filePaths,iStatus)\t\\\r\n    (This)->lpVtbl -> AddFiles(This,filePaths,iStatus)\r\n\r\n#define IITUserPlaylist_AddURL(This,url,iURLTrack)\t\\\r\n    (This)->lpVtbl -> AddURL(This,url,iURLTrack)\r\n\r\n#define IITUserPlaylist_AddTrack(This,iTrackToAdd,iAddedTrack)\t\\\r\n    (This)->lpVtbl -> AddTrack(This,iTrackToAdd,iAddedTrack)\r\n\r\n#define IITUserPlaylist_get_Shared(This,isShared)\t\\\r\n    (This)->lpVtbl -> get_Shared(This,isShared)\r\n\r\n#define IITUserPlaylist_put_Shared(This,shouldBeShared)\t\\\r\n    (This)->lpVtbl -> put_Shared(This,shouldBeShared)\r\n\r\n#define IITUserPlaylist_get_Smart(This,isSmart)\t\\\r\n    (This)->lpVtbl -> get_Smart(This,isSmart)\r\n\r\n#define IITUserPlaylist_get_SpecialKind(This,specialKind)\t\\\r\n    (This)->lpVtbl -> get_SpecialKind(This,specialKind)\r\n\r\n#define IITUserPlaylist_get_Parent(This,iParentPlayList)\t\\\r\n    (This)->lpVtbl -> get_Parent(This,iParentPlayList)\r\n\r\n#define IITUserPlaylist_CreatePlaylist(This,playlistName,iPlaylist)\t\\\r\n    (This)->lpVtbl -> CreatePlaylist(This,playlistName,iPlaylist)\r\n\r\n#define IITUserPlaylist_CreateFolder(This,folderName,iFolder)\t\\\r\n    (This)->lpVtbl -> CreateFolder(This,folderName,iFolder)\r\n\r\n#define IITUserPlaylist_put_Parent(This,iParent)\t\\\r\n    (This)->lpVtbl -> put_Parent(This,iParent)\r\n\r\n#define IITUserPlaylist_Reveal(This)\t\\\r\n    (This)->lpVtbl -> Reveal(This)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_AddFile_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ BSTR filePath,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_AddFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_AddFiles_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ VARIANT *filePaths,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_AddFiles_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_AddURL_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ BSTR url,\r\n    /* [retval][out] */ IITURLTrack **iURLTrack);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_AddURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_AddTrack_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ VARIANT *iTrackToAdd,\r\n    /* [retval][out] */ IITTrack **iAddedTrack);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_AddTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_get_Shared_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isShared);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_get_Shared_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_put_Shared_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeShared);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_put_Shared_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_get_Smart_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isSmart);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_get_Smart_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_get_SpecialKind_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [retval][out] */ ITUserPlaylistSpecialKind *specialKind);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_get_SpecialKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_get_Parent_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [retval][out] */ IITUserPlaylist **iParentPlayList);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_get_Parent_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_CreatePlaylist_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ BSTR playlistName,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_CreatePlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_CreateFolder_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ BSTR folderName,\r\n    /* [retval][out] */ IITPlaylist **iFolder);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_CreateFolder_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_put_Parent_Proxy( \r\n    IITUserPlaylist * This,\r\n    /* [in] */ VARIANT *iParent);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_put_Parent_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITUserPlaylist_Reveal_Proxy( \r\n    IITUserPlaylist * This);\r\n\r\n\r\nvoid __RPC_STUB IITUserPlaylist_Reveal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITUserPlaylist_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITTrack_INTERFACE_DEFINED__\r\n#define __IITTrack_INTERFACE_DEFINED__\r\n\r\n/* interface IITTrack */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITTrack;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"4CB0915D-1E54-4727-BAF3-CE6CC9A225A1\")\r\n    IITTrack : public IITObject\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Delete( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Play( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE AddArtworkFromFile( \r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITArtwork **iArtwork) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Kind( \r\n            /* [retval][out] */ ITTrackKind *kind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Playlist( \r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Album( \r\n            /* [retval][out] */ BSTR *album) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Album( \r\n            /* [in] */ BSTR album) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Artist( \r\n            /* [retval][out] */ BSTR *artist) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Artist( \r\n            /* [in] */ BSTR artist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_BitRate( \r\n            /* [retval][out] */ long *bitrate) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_BPM( \r\n            /* [retval][out] */ long *beatsPerMinute) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_BPM( \r\n            /* [in] */ long beatsPerMinute) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Comment( \r\n            /* [retval][out] */ BSTR *comment) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Comment( \r\n            /* [in] */ BSTR comment) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Compilation( \r\n            /* [retval][out] */ VARIANT_BOOL *isCompilation) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Compilation( \r\n            /* [in] */ VARIANT_BOOL shouldBeCompilation) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Composer( \r\n            /* [retval][out] */ BSTR *composer) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Composer( \r\n            /* [in] */ BSTR composer) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_DateAdded( \r\n            /* [retval][out] */ DATE *dateAdded) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_DiscCount( \r\n            /* [retval][out] */ long *discCount) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_DiscCount( \r\n            /* [in] */ long discCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_DiscNumber( \r\n            /* [retval][out] */ long *discNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_DiscNumber( \r\n            /* [in] */ long discNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Duration( \r\n            /* [retval][out] */ long *duration) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Enabled( \r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Enabled( \r\n            /* [in] */ VARIANT_BOOL shouldBeEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EQ( \r\n            /* [retval][out] */ BSTR *eq) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_EQ( \r\n            /* [in] */ BSTR eq) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Finish( \r\n            /* [in] */ long finish) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Finish( \r\n            /* [retval][out] */ long *finish) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Genre( \r\n            /* [retval][out] */ BSTR *genre) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Genre( \r\n            /* [in] */ BSTR genre) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Grouping( \r\n            /* [retval][out] */ BSTR *grouping) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Grouping( \r\n            /* [in] */ BSTR grouping) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_KindAsString( \r\n            /* [retval][out] */ BSTR *kind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ModificationDate( \r\n            /* [retval][out] */ DATE *dateModified) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlayedCount( \r\n            /* [retval][out] */ long *playedCount) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_PlayedCount( \r\n            /* [in] */ long playedCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlayedDate( \r\n            /* [retval][out] */ DATE *playedDate) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_PlayedDate( \r\n            /* [in] */ DATE playedDate) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlayOrderIndex( \r\n            /* [retval][out] */ long *index) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Rating( \r\n            /* [retval][out] */ long *rating) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Rating( \r\n            /* [in] */ long rating) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SampleRate( \r\n            /* [retval][out] */ long *sampleRate) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Size( \r\n            /* [retval][out] */ long *size) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Start( \r\n            /* [retval][out] */ long *start) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Start( \r\n            /* [in] */ long start) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Time( \r\n            /* [retval][out] */ BSTR *time) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_TrackCount( \r\n            /* [retval][out] */ long *trackCount) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_TrackCount( \r\n            /* [in] */ long trackCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_TrackNumber( \r\n            /* [retval][out] */ long *trackNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_TrackNumber( \r\n            /* [in] */ long trackNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_VolumeAdjustment( \r\n            /* [retval][out] */ long *volumeAdjustment) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_VolumeAdjustment( \r\n            /* [in] */ long volumeAdjustment) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Year( \r\n            /* [retval][out] */ long *year) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Year( \r\n            /* [in] */ long year) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Artwork( \r\n            /* [retval][out] */ IITArtworkCollection **iArtworkCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITTrackVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITTrack * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITTrack * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITTrack * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITTrack * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITTrack * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITTrack * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Play )( \r\n            IITTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddArtworkFromFile )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITArtwork **iArtwork);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ ITTrackKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlist )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Album )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *album);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Album )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR album);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artist )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *artist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Artist )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR artist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRate )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *bitrate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BPM )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *beatsPerMinute);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BPM )( \r\n            IITTrack * This,\r\n            /* [in] */ long beatsPerMinute);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Comment )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *comment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Comment )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR comment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Compilation )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompilation);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Compilation )( \r\n            IITTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeCompilation);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Composer )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *composer);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Composer )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR composer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DateAdded )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ DATE *dateAdded);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscCount )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *discCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscCount )( \r\n            IITTrack * This,\r\n            /* [in] */ long discCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscNumber )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *discNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscNumber )( \r\n            IITTrack * This,\r\n            /* [in] */ long discNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Enabled )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Enabled )( \r\n            IITTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeEnabled);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQ )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EQ )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Finish )( \r\n            IITTrack * This,\r\n            /* [in] */ long finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Finish )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Genre )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *genre);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Genre )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR genre);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Grouping )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *grouping);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Grouping )( \r\n            IITTrack * This,\r\n            /* [in] */ BSTR grouping);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_KindAsString )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ModificationDate )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ DATE *dateModified);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedCount )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *playedCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedCount )( \r\n            IITTrack * This,\r\n            /* [in] */ long playedCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedDate )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ DATE *playedDate);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedDate )( \r\n            IITTrack * This,\r\n            /* [in] */ DATE playedDate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayOrderIndex )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Rating )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *rating);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Rating )( \r\n            IITTrack * This,\r\n            /* [in] */ long rating);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SampleRate )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *sampleRate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Start )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *start);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Start )( \r\n            IITTrack * This,\r\n            /* [in] */ long start);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackCount )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *trackCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackCount )( \r\n            IITTrack * This,\r\n            /* [in] */ long trackCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackNumber )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *trackNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackNumber )( \r\n            IITTrack * This,\r\n            /* [in] */ long trackNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VolumeAdjustment )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *volumeAdjustment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VolumeAdjustment )( \r\n            IITTrack * This,\r\n            /* [in] */ long volumeAdjustment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Year )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ long *year);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Year )( \r\n            IITTrack * This,\r\n            /* [in] */ long year);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artwork )( \r\n            IITTrack * This,\r\n            /* [retval][out] */ IITArtworkCollection **iArtworkCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITTrackVtbl;\r\n\r\n    interface IITTrack\r\n    {\r\n        CONST_VTBL struct IITTrackVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITTrack_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITTrack_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITTrack_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITTrack_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITTrack_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITTrack_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITTrack_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITTrack_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITTrack_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITTrack_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITTrack_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITTrack_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITTrack_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITTrack_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITTrack_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITTrack_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITTrack_Play(This)\t\\\r\n    (This)->lpVtbl -> Play(This)\r\n\r\n#define IITTrack_AddArtworkFromFile(This,filePath,iArtwork)\t\\\r\n    (This)->lpVtbl -> AddArtworkFromFile(This,filePath,iArtwork)\r\n\r\n#define IITTrack_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITTrack_get_Playlist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_Playlist(This,iPlaylist)\r\n\r\n#define IITTrack_get_Album(This,album)\t\\\r\n    (This)->lpVtbl -> get_Album(This,album)\r\n\r\n#define IITTrack_put_Album(This,album)\t\\\r\n    (This)->lpVtbl -> put_Album(This,album)\r\n\r\n#define IITTrack_get_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> get_Artist(This,artist)\r\n\r\n#define IITTrack_put_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> put_Artist(This,artist)\r\n\r\n#define IITTrack_get_BitRate(This,bitrate)\t\\\r\n    (This)->lpVtbl -> get_BitRate(This,bitrate)\r\n\r\n#define IITTrack_get_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> get_BPM(This,beatsPerMinute)\r\n\r\n#define IITTrack_put_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> put_BPM(This,beatsPerMinute)\r\n\r\n#define IITTrack_get_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> get_Comment(This,comment)\r\n\r\n#define IITTrack_put_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> put_Comment(This,comment)\r\n\r\n#define IITTrack_get_Compilation(This,isCompilation)\t\\\r\n    (This)->lpVtbl -> get_Compilation(This,isCompilation)\r\n\r\n#define IITTrack_put_Compilation(This,shouldBeCompilation)\t\\\r\n    (This)->lpVtbl -> put_Compilation(This,shouldBeCompilation)\r\n\r\n#define IITTrack_get_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> get_Composer(This,composer)\r\n\r\n#define IITTrack_put_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> put_Composer(This,composer)\r\n\r\n#define IITTrack_get_DateAdded(This,dateAdded)\t\\\r\n    (This)->lpVtbl -> get_DateAdded(This,dateAdded)\r\n\r\n#define IITTrack_get_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> get_DiscCount(This,discCount)\r\n\r\n#define IITTrack_put_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> put_DiscCount(This,discCount)\r\n\r\n#define IITTrack_get_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> get_DiscNumber(This,discNumber)\r\n\r\n#define IITTrack_put_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> put_DiscNumber(This,discNumber)\r\n\r\n#define IITTrack_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITTrack_get_Enabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_Enabled(This,isEnabled)\r\n\r\n#define IITTrack_put_Enabled(This,shouldBeEnabled)\t\\\r\n    (This)->lpVtbl -> put_Enabled(This,shouldBeEnabled)\r\n\r\n#define IITTrack_get_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> get_EQ(This,eq)\r\n\r\n#define IITTrack_put_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> put_EQ(This,eq)\r\n\r\n#define IITTrack_put_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> put_Finish(This,finish)\r\n\r\n#define IITTrack_get_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> get_Finish(This,finish)\r\n\r\n#define IITTrack_get_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> get_Genre(This,genre)\r\n\r\n#define IITTrack_put_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> put_Genre(This,genre)\r\n\r\n#define IITTrack_get_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> get_Grouping(This,grouping)\r\n\r\n#define IITTrack_put_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> put_Grouping(This,grouping)\r\n\r\n#define IITTrack_get_KindAsString(This,kind)\t\\\r\n    (This)->lpVtbl -> get_KindAsString(This,kind)\r\n\r\n#define IITTrack_get_ModificationDate(This,dateModified)\t\\\r\n    (This)->lpVtbl -> get_ModificationDate(This,dateModified)\r\n\r\n#define IITTrack_get_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> get_PlayedCount(This,playedCount)\r\n\r\n#define IITTrack_put_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> put_PlayedCount(This,playedCount)\r\n\r\n#define IITTrack_get_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> get_PlayedDate(This,playedDate)\r\n\r\n#define IITTrack_put_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> put_PlayedDate(This,playedDate)\r\n\r\n#define IITTrack_get_PlayOrderIndex(This,index)\t\\\r\n    (This)->lpVtbl -> get_PlayOrderIndex(This,index)\r\n\r\n#define IITTrack_get_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> get_Rating(This,rating)\r\n\r\n#define IITTrack_put_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> put_Rating(This,rating)\r\n\r\n#define IITTrack_get_SampleRate(This,sampleRate)\t\\\r\n    (This)->lpVtbl -> get_SampleRate(This,sampleRate)\r\n\r\n#define IITTrack_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITTrack_get_Start(This,start)\t\\\r\n    (This)->lpVtbl -> get_Start(This,start)\r\n\r\n#define IITTrack_put_Start(This,start)\t\\\r\n    (This)->lpVtbl -> put_Start(This,start)\r\n\r\n#define IITTrack_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITTrack_get_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> get_TrackCount(This,trackCount)\r\n\r\n#define IITTrack_put_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> put_TrackCount(This,trackCount)\r\n\r\n#define IITTrack_get_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> get_TrackNumber(This,trackNumber)\r\n\r\n#define IITTrack_put_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> put_TrackNumber(This,trackNumber)\r\n\r\n#define IITTrack_get_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> get_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITTrack_put_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> put_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITTrack_get_Year(This,year)\t\\\r\n    (This)->lpVtbl -> get_Year(This,year)\r\n\r\n#define IITTrack_put_Year(This,year)\t\\\r\n    (This)->lpVtbl -> put_Year(This,year)\r\n\r\n#define IITTrack_get_Artwork(This,iArtworkCollection)\t\\\r\n    (This)->lpVtbl -> get_Artwork(This,iArtworkCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITTrack_Delete_Proxy( \r\n    IITTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_Delete_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITTrack_Play_Proxy( \r\n    IITTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_Play_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITTrack_AddArtworkFromFile_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR filePath,\r\n    /* [retval][out] */ IITArtwork **iArtwork);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_AddArtworkFromFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Kind_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ ITTrackKind *kind);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Kind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Playlist_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Playlist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Album_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *album);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Album_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Album_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR album);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Album_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Artist_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *artist);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Artist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Artist_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR artist);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Artist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_BitRate_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *bitrate);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_BitRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_BPM_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *beatsPerMinute);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_BPM_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_BPM_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long beatsPerMinute);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_BPM_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Comment_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *comment);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Comment_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Comment_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR comment);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Comment_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Compilation_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isCompilation);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Compilation_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Compilation_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeCompilation);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Compilation_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Composer_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *composer);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Composer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Composer_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR composer);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Composer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_DateAdded_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ DATE *dateAdded);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_DateAdded_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_DiscCount_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *discCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_DiscCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_DiscCount_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long discCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_DiscCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_DiscNumber_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *discNumber);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_DiscNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_DiscNumber_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long discNumber);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_DiscNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Duration_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *duration);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Duration_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Enabled_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Enabled_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeEnabled);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_EQ_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *eq);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_EQ_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_EQ_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR eq);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_EQ_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Finish_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long finish);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Finish_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Finish_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *finish);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Finish_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Genre_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *genre);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Genre_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Genre_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR genre);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Genre_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Grouping_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *grouping);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Grouping_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Grouping_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ BSTR grouping);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Grouping_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_KindAsString_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *kind);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_KindAsString_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_ModificationDate_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ DATE *dateModified);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_ModificationDate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_PlayedCount_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *playedCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_PlayedCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_PlayedCount_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long playedCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_PlayedCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_PlayedDate_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ DATE *playedDate);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_PlayedDate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_PlayedDate_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ DATE playedDate);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_PlayedDate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_PlayOrderIndex_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *index);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_PlayOrderIndex_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Rating_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *rating);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Rating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Rating_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long rating);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Rating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_SampleRate_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *sampleRate);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_SampleRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Size_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *size);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Size_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Start_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *start);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Start_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Start_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long start);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Start_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Time_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ BSTR *time);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Time_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_TrackCount_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *trackCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_TrackCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_TrackCount_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long trackCount);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_TrackCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_TrackNumber_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *trackNumber);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_TrackNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_TrackNumber_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long trackNumber);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_TrackNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_VolumeAdjustment_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *volumeAdjustment);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_VolumeAdjustment_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_VolumeAdjustment_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long volumeAdjustment);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_VolumeAdjustment_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Year_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ long *year);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Year_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITTrack_put_Year_Proxy( \r\n    IITTrack * This,\r\n    /* [in] */ long year);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_put_Year_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrack_get_Artwork_Proxy( \r\n    IITTrack * This,\r\n    /* [retval][out] */ IITArtworkCollection **iArtworkCollection);\r\n\r\n\r\nvoid __RPC_STUB IITTrack_get_Artwork_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITTrack_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITTrackCollection_INTERFACE_DEFINED__\r\n#define __IITTrackCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITTrackCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITTrackCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"755D76F1-6B85-4ce4-8F5F-F88D9743DCD8\")\r\n    IITTrackCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITTrack **iTrack) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByPlayOrder( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITTrack **iTrack) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITTrack **iTrack) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByPersistentID( \r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITTrack **iTrack) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITTrackCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITTrackCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITTrackCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITTrackCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITTrackCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITTrack **iTrack);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByPlayOrder )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITTrack **iTrack);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITTrack **iTrack);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITTrackCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByPersistentID )( \r\n            IITTrackCollection * This,\r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITTrack **iTrack);\r\n        \r\n        END_INTERFACE\r\n    } IITTrackCollectionVtbl;\r\n\r\n    interface IITTrackCollection\r\n    {\r\n        CONST_VTBL struct IITTrackCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITTrackCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITTrackCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITTrackCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITTrackCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITTrackCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITTrackCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITTrackCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITTrackCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITTrackCollection_get_Item(This,index,iTrack)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iTrack)\r\n\r\n#define IITTrackCollection_get_ItemByPlayOrder(This,index,iTrack)\t\\\r\n    (This)->lpVtbl -> get_ItemByPlayOrder(This,index,iTrack)\r\n\r\n#define IITTrackCollection_get_ItemByName(This,name,iTrack)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iTrack)\r\n\r\n#define IITTrackCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#define IITTrackCollection_get_ItemByPersistentID(This,highID,lowID,iTrack)\t\\\r\n    (This)->lpVtbl -> get_ItemByPersistentID(This,highID,lowID,iTrack)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get_Count_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get_Item_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITTrack **iTrack);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get_ItemByPlayOrder_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITTrack **iTrack);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get_ItemByPlayOrder_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get_ItemByName_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITTrack **iTrack);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get__NewEnum_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITTrackCollection_get_ItemByPersistentID_Proxy( \r\n    IITTrackCollection * This,\r\n    /* [in] */ long highID,\r\n    /* [in] */ long lowID,\r\n    /* [retval][out] */ IITTrack **iTrack);\r\n\r\n\r\nvoid __RPC_STUB IITTrackCollection_get_ItemByPersistentID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITTrackCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITVisual_INTERFACE_DEFINED__\r\n#define __IITVisual_INTERFACE_DEFINED__\r\n\r\n/* interface IITVisual */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITVisual;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"340F3315-ED72-4c09-9ACF-21EB4BDF9931\")\r\n    IITVisual : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Name( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITVisualVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITVisual * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITVisual * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITVisual * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITVisual * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITVisual * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITVisual * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITVisual * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITVisual * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        END_INTERFACE\r\n    } IITVisualVtbl;\r\n\r\n    interface IITVisual\r\n    {\r\n        CONST_VTBL struct IITVisualVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITVisual_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITVisual_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITVisual_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITVisual_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITVisual_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITVisual_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITVisual_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITVisual_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITVisual_get_Name_Proxy( \r\n    IITVisual * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITVisual_get_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITVisual_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITVisualCollection_INTERFACE_DEFINED__\r\n#define __IITVisualCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITVisualCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITVisualCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"88A4CCDD-114F-4043-B69B-84D4E6274957\")\r\n    IITVisualCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITVisual **iVisual) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITVisual **iVisual) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITVisualCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITVisualCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITVisualCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITVisualCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITVisualCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITVisual **iVisual);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITVisualCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITVisual **iVisual);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITVisualCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        END_INTERFACE\r\n    } IITVisualCollectionVtbl;\r\n\r\n    interface IITVisualCollection\r\n    {\r\n        CONST_VTBL struct IITVisualCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITVisualCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITVisualCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITVisualCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITVisualCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITVisualCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITVisualCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITVisualCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITVisualCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITVisualCollection_get_Item(This,index,iVisual)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iVisual)\r\n\r\n#define IITVisualCollection_get_ItemByName(This,name,iVisual)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iVisual)\r\n\r\n#define IITVisualCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITVisualCollection_get_Count_Proxy( \r\n    IITVisualCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITVisualCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITVisualCollection_get_Item_Proxy( \r\n    IITVisualCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITVisual **iVisual);\r\n\r\n\r\nvoid __RPC_STUB IITVisualCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITVisualCollection_get_ItemByName_Proxy( \r\n    IITVisualCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITVisual **iVisual);\r\n\r\n\r\nvoid __RPC_STUB IITVisualCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITVisualCollection_get__NewEnum_Proxy( \r\n    IITVisualCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITVisualCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITVisualCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITWindow_INTERFACE_DEFINED__\r\n#define __IITWindow_INTERFACE_DEFINED__\r\n\r\n/* interface IITWindow */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITWindow;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"370D7BE0-3A89-4a42-B902-C75FC138BE09\")\r\n    IITWindow : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Name( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Kind( \r\n            /* [retval][out] */ ITWindowKind *kind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Visible( \r\n            /* [retval][out] */ VARIANT_BOOL *isVisible) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Visible( \r\n            /* [in] */ VARIANT_BOOL shouldBeVisible) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Resizable( \r\n            /* [retval][out] */ VARIANT_BOOL *isResizable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Minimized( \r\n            /* [retval][out] */ VARIANT_BOOL *isMinimized) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Minimized( \r\n            /* [in] */ VARIANT_BOOL shouldBeMinimized) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Maximizable( \r\n            /* [retval][out] */ VARIANT_BOOL *isMaximizable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Maximized( \r\n            /* [retval][out] */ VARIANT_BOOL *isMaximized) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Maximized( \r\n            /* [in] */ VARIANT_BOOL shouldBeMaximized) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Zoomable( \r\n            /* [retval][out] */ VARIANT_BOOL *isZoomable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Zoomed( \r\n            /* [retval][out] */ VARIANT_BOOL *isZoomed) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Zoomed( \r\n            /* [in] */ VARIANT_BOOL shouldBeZoomed) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Top( \r\n            /* [retval][out] */ long *top) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Top( \r\n            /* [in] */ long top) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Left( \r\n            /* [retval][out] */ long *left) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Left( \r\n            /* [in] */ long left) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Bottom( \r\n            /* [retval][out] */ long *bottom) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Bottom( \r\n            /* [in] */ long bottom) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Right( \r\n            /* [retval][out] */ long *right) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Right( \r\n            /* [in] */ long right) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Width( \r\n            /* [retval][out] */ long *width) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Width( \r\n            /* [in] */ long width) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Height( \r\n            /* [retval][out] */ long *height) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Height( \r\n            /* [in] */ long height) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITWindowVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITWindow * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITWindow * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITWindow * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITWindow * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITWindow * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ ITWindowKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Visible )( \r\n            IITWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Resizable )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isResizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Minimized )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMinimized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Minimized )( \r\n            IITWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMinimized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximizable )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximized )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Maximized )( \r\n            IITWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMaximized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomable )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomed )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomed);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Zoomed )( \r\n            IITWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeZoomed);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Top )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *top);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Top )( \r\n            IITWindow * This,\r\n            /* [in] */ long top);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Left )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *left);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Left )( \r\n            IITWindow * This,\r\n            /* [in] */ long left);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Bottom )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *bottom);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Bottom )( \r\n            IITWindow * This,\r\n            /* [in] */ long bottom);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Right )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *right);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Right )( \r\n            IITWindow * This,\r\n            /* [in] */ long right);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Width )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *width);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Width )( \r\n            IITWindow * This,\r\n            /* [in] */ long width);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Height )( \r\n            IITWindow * This,\r\n            /* [retval][out] */ long *height);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Height )( \r\n            IITWindow * This,\r\n            /* [in] */ long height);\r\n        \r\n        END_INTERFACE\r\n    } IITWindowVtbl;\r\n\r\n    interface IITWindow\r\n    {\r\n        CONST_VTBL struct IITWindowVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITWindow_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITWindow_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITWindow_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITWindow_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITWindow_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITWindow_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITWindow_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITWindow_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITWindow_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITWindow_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITWindow_put_Visible(This,shouldBeVisible)\t\\\r\n    (This)->lpVtbl -> put_Visible(This,shouldBeVisible)\r\n\r\n#define IITWindow_get_Resizable(This,isResizable)\t\\\r\n    (This)->lpVtbl -> get_Resizable(This,isResizable)\r\n\r\n#define IITWindow_get_Minimized(This,isMinimized)\t\\\r\n    (This)->lpVtbl -> get_Minimized(This,isMinimized)\r\n\r\n#define IITWindow_put_Minimized(This,shouldBeMinimized)\t\\\r\n    (This)->lpVtbl -> put_Minimized(This,shouldBeMinimized)\r\n\r\n#define IITWindow_get_Maximizable(This,isMaximizable)\t\\\r\n    (This)->lpVtbl -> get_Maximizable(This,isMaximizable)\r\n\r\n#define IITWindow_get_Maximized(This,isMaximized)\t\\\r\n    (This)->lpVtbl -> get_Maximized(This,isMaximized)\r\n\r\n#define IITWindow_put_Maximized(This,shouldBeMaximized)\t\\\r\n    (This)->lpVtbl -> put_Maximized(This,shouldBeMaximized)\r\n\r\n#define IITWindow_get_Zoomable(This,isZoomable)\t\\\r\n    (This)->lpVtbl -> get_Zoomable(This,isZoomable)\r\n\r\n#define IITWindow_get_Zoomed(This,isZoomed)\t\\\r\n    (This)->lpVtbl -> get_Zoomed(This,isZoomed)\r\n\r\n#define IITWindow_put_Zoomed(This,shouldBeZoomed)\t\\\r\n    (This)->lpVtbl -> put_Zoomed(This,shouldBeZoomed)\r\n\r\n#define IITWindow_get_Top(This,top)\t\\\r\n    (This)->lpVtbl -> get_Top(This,top)\r\n\r\n#define IITWindow_put_Top(This,top)\t\\\r\n    (This)->lpVtbl -> put_Top(This,top)\r\n\r\n#define IITWindow_get_Left(This,left)\t\\\r\n    (This)->lpVtbl -> get_Left(This,left)\r\n\r\n#define IITWindow_put_Left(This,left)\t\\\r\n    (This)->lpVtbl -> put_Left(This,left)\r\n\r\n#define IITWindow_get_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> get_Bottom(This,bottom)\r\n\r\n#define IITWindow_put_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> put_Bottom(This,bottom)\r\n\r\n#define IITWindow_get_Right(This,right)\t\\\r\n    (This)->lpVtbl -> get_Right(This,right)\r\n\r\n#define IITWindow_put_Right(This,right)\t\\\r\n    (This)->lpVtbl -> put_Right(This,right)\r\n\r\n#define IITWindow_get_Width(This,width)\t\\\r\n    (This)->lpVtbl -> get_Width(This,width)\r\n\r\n#define IITWindow_put_Width(This,width)\t\\\r\n    (This)->lpVtbl -> put_Width(This,width)\r\n\r\n#define IITWindow_get_Height(This,height)\t\\\r\n    (This)->lpVtbl -> get_Height(This,height)\r\n\r\n#define IITWindow_put_Height(This,height)\t\\\r\n    (This)->lpVtbl -> put_Height(This,height)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Name_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Kind_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ ITWindowKind *kind);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Kind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Visible_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Visible_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Visible_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeVisible);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Visible_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Resizable_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isResizable);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Resizable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Minimized_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isMinimized);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Minimized_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Minimized_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeMinimized);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Minimized_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Maximizable_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isMaximizable);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Maximizable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Maximized_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isMaximized);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Maximized_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Maximized_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeMaximized);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Maximized_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Zoomable_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isZoomable);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Zoomable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Zoomed_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isZoomed);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Zoomed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Zoomed_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeZoomed);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Zoomed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Top_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *top);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Top_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Top_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long top);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Top_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Left_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *left);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Left_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Left_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long left);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Left_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Bottom_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *bottom);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Bottom_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Bottom_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long bottom);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Bottom_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Right_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *right);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Right_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Right_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long right);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Right_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Width_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *width);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Width_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Width_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long width);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Width_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindow_get_Height_Proxy( \r\n    IITWindow * This,\r\n    /* [retval][out] */ long *height);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_get_Height_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITWindow_put_Height_Proxy( \r\n    IITWindow * This,\r\n    /* [in] */ long height);\r\n\r\n\r\nvoid __RPC_STUB IITWindow_put_Height_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITWindow_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITBrowserWindow_INTERFACE_DEFINED__\r\n#define __IITBrowserWindow_INTERFACE_DEFINED__\r\n\r\n/* interface IITBrowserWindow */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITBrowserWindow;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"C999F455-C4D5-4aa4-8277-F99753699974\")\r\n    IITBrowserWindow : public IITWindow\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_MiniPlayer( \r\n            /* [retval][out] */ VARIANT_BOOL *isMiniPlayer) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_MiniPlayer( \r\n            /* [in] */ VARIANT_BOOL shouldBeMiniPlayer) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SelectedTracks( \r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SelectedPlaylist( \r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SelectedPlaylist( \r\n            /* [in] */ VARIANT *iPlaylist) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITBrowserWindowVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITBrowserWindow * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITBrowserWindow * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITBrowserWindow * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ ITWindowKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Visible )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Resizable )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isResizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Minimized )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMinimized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Minimized )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMinimized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximizable )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximized )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Maximized )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMaximized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomable )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomed )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomed);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Zoomed )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeZoomed);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Top )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *top);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Top )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long top);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Left )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *left);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Left )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long left);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Bottom )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *bottom);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Bottom )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long bottom);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Right )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *right);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Right )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long right);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Width )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *width);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Width )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long width);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Height )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ long *height);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Height )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ long height);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_MiniPlayer )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMiniPlayer);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_MiniPlayer )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMiniPlayer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SelectedTracks )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SelectedPlaylist )( \r\n            IITBrowserWindow * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SelectedPlaylist )( \r\n            IITBrowserWindow * This,\r\n            /* [in] */ VARIANT *iPlaylist);\r\n        \r\n        END_INTERFACE\r\n    } IITBrowserWindowVtbl;\r\n\r\n    interface IITBrowserWindow\r\n    {\r\n        CONST_VTBL struct IITBrowserWindowVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITBrowserWindow_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITBrowserWindow_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITBrowserWindow_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITBrowserWindow_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITBrowserWindow_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITBrowserWindow_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITBrowserWindow_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITBrowserWindow_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITBrowserWindow_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITBrowserWindow_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITBrowserWindow_put_Visible(This,shouldBeVisible)\t\\\r\n    (This)->lpVtbl -> put_Visible(This,shouldBeVisible)\r\n\r\n#define IITBrowserWindow_get_Resizable(This,isResizable)\t\\\r\n    (This)->lpVtbl -> get_Resizable(This,isResizable)\r\n\r\n#define IITBrowserWindow_get_Minimized(This,isMinimized)\t\\\r\n    (This)->lpVtbl -> get_Minimized(This,isMinimized)\r\n\r\n#define IITBrowserWindow_put_Minimized(This,shouldBeMinimized)\t\\\r\n    (This)->lpVtbl -> put_Minimized(This,shouldBeMinimized)\r\n\r\n#define IITBrowserWindow_get_Maximizable(This,isMaximizable)\t\\\r\n    (This)->lpVtbl -> get_Maximizable(This,isMaximizable)\r\n\r\n#define IITBrowserWindow_get_Maximized(This,isMaximized)\t\\\r\n    (This)->lpVtbl -> get_Maximized(This,isMaximized)\r\n\r\n#define IITBrowserWindow_put_Maximized(This,shouldBeMaximized)\t\\\r\n    (This)->lpVtbl -> put_Maximized(This,shouldBeMaximized)\r\n\r\n#define IITBrowserWindow_get_Zoomable(This,isZoomable)\t\\\r\n    (This)->lpVtbl -> get_Zoomable(This,isZoomable)\r\n\r\n#define IITBrowserWindow_get_Zoomed(This,isZoomed)\t\\\r\n    (This)->lpVtbl -> get_Zoomed(This,isZoomed)\r\n\r\n#define IITBrowserWindow_put_Zoomed(This,shouldBeZoomed)\t\\\r\n    (This)->lpVtbl -> put_Zoomed(This,shouldBeZoomed)\r\n\r\n#define IITBrowserWindow_get_Top(This,top)\t\\\r\n    (This)->lpVtbl -> get_Top(This,top)\r\n\r\n#define IITBrowserWindow_put_Top(This,top)\t\\\r\n    (This)->lpVtbl -> put_Top(This,top)\r\n\r\n#define IITBrowserWindow_get_Left(This,left)\t\\\r\n    (This)->lpVtbl -> get_Left(This,left)\r\n\r\n#define IITBrowserWindow_put_Left(This,left)\t\\\r\n    (This)->lpVtbl -> put_Left(This,left)\r\n\r\n#define IITBrowserWindow_get_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> get_Bottom(This,bottom)\r\n\r\n#define IITBrowserWindow_put_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> put_Bottom(This,bottom)\r\n\r\n#define IITBrowserWindow_get_Right(This,right)\t\\\r\n    (This)->lpVtbl -> get_Right(This,right)\r\n\r\n#define IITBrowserWindow_put_Right(This,right)\t\\\r\n    (This)->lpVtbl -> put_Right(This,right)\r\n\r\n#define IITBrowserWindow_get_Width(This,width)\t\\\r\n    (This)->lpVtbl -> get_Width(This,width)\r\n\r\n#define IITBrowserWindow_put_Width(This,width)\t\\\r\n    (This)->lpVtbl -> put_Width(This,width)\r\n\r\n#define IITBrowserWindow_get_Height(This,height)\t\\\r\n    (This)->lpVtbl -> get_Height(This,height)\r\n\r\n#define IITBrowserWindow_put_Height(This,height)\t\\\r\n    (This)->lpVtbl -> put_Height(This,height)\r\n\r\n\r\n#define IITBrowserWindow_get_MiniPlayer(This,isMiniPlayer)\t\\\r\n    (This)->lpVtbl -> get_MiniPlayer(This,isMiniPlayer)\r\n\r\n#define IITBrowserWindow_put_MiniPlayer(This,shouldBeMiniPlayer)\t\\\r\n    (This)->lpVtbl -> put_MiniPlayer(This,shouldBeMiniPlayer)\r\n\r\n#define IITBrowserWindow_get_SelectedTracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_SelectedTracks(This,iTrackCollection)\r\n\r\n#define IITBrowserWindow_get_SelectedPlaylist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_SelectedPlaylist(This,iPlaylist)\r\n\r\n#define IITBrowserWindow_put_SelectedPlaylist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> put_SelectedPlaylist(This,iPlaylist)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITBrowserWindow_get_MiniPlayer_Proxy( \r\n    IITBrowserWindow * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isMiniPlayer);\r\n\r\n\r\nvoid __RPC_STUB IITBrowserWindow_get_MiniPlayer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITBrowserWindow_put_MiniPlayer_Proxy( \r\n    IITBrowserWindow * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeMiniPlayer);\r\n\r\n\r\nvoid __RPC_STUB IITBrowserWindow_put_MiniPlayer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITBrowserWindow_get_SelectedTracks_Proxy( \r\n    IITBrowserWindow * This,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IITBrowserWindow_get_SelectedTracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITBrowserWindow_get_SelectedPlaylist_Proxy( \r\n    IITBrowserWindow * This,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITBrowserWindow_get_SelectedPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITBrowserWindow_put_SelectedPlaylist_Proxy( \r\n    IITBrowserWindow * This,\r\n    /* [in] */ VARIANT *iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITBrowserWindow_put_SelectedPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITBrowserWindow_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITWindowCollection_INTERFACE_DEFINED__\r\n#define __IITWindowCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITWindowCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITWindowCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"3D8DE381-6C0E-481f-A865-E2385F59FA43\")\r\n    IITWindowCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITWindow **iWindow) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITWindow **iWindow) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITWindowCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITWindowCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITWindowCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITWindowCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITWindowCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITWindow **iWindow);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITWindowCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITWindow **iWindow);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITWindowCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        END_INTERFACE\r\n    } IITWindowCollectionVtbl;\r\n\r\n    interface IITWindowCollection\r\n    {\r\n        CONST_VTBL struct IITWindowCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITWindowCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITWindowCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITWindowCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITWindowCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITWindowCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITWindowCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITWindowCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITWindowCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITWindowCollection_get_Item(This,index,iWindow)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iWindow)\r\n\r\n#define IITWindowCollection_get_ItemByName(This,name,iWindow)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iWindow)\r\n\r\n#define IITWindowCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindowCollection_get_Count_Proxy( \r\n    IITWindowCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITWindowCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITWindowCollection_get_Item_Proxy( \r\n    IITWindowCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITWindow **iWindow);\r\n\r\n\r\nvoid __RPC_STUB IITWindowCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITWindowCollection_get_ItemByName_Proxy( \r\n    IITWindowCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITWindow **iWindow);\r\n\r\n\r\nvoid __RPC_STUB IITWindowCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITWindowCollection_get__NewEnum_Proxy( \r\n    IITWindowCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITWindowCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITWindowCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IiTunes_INTERFACE_DEFINED__\r\n#define __IiTunes_INTERFACE_DEFINED__\r\n\r\n/* interface IiTunes */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\n\r\n\r\nEXTERN_C const IID IID_IiTunes;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"9DD6680B-3EDC-40db-A771-E6FE4832E34A\")\r\n    IiTunes : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE BackTrack( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE FastForward( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE NextTrack( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Pause( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Play( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PlayFile( \r\n            /* [in] */ BSTR filePath) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PlayPause( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PreviousTrack( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Resume( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Rewind( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Stop( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertFile( \r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertFiles( \r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertTrack( \r\n            /* [in] */ VARIANT *iTrackToConvert,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertTracks( \r\n            /* [in] */ VARIANT *iTracksToConvert,\r\n            /* [retval][out] */ IITOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CheckVersion( \r\n            /* [in] */ long majorVersion,\r\n            /* [in] */ long minorVersion,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompatible) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetITObjectByID( \r\n            /* [in] */ long sourceID,\r\n            /* [in] */ long playlistID,\r\n            /* [in] */ long trackID,\r\n            /* [in] */ long databaseID,\r\n            /* [retval][out] */ IITObject **iObject) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreatePlaylist( \r\n            /* [in] */ BSTR playlistName,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE OpenURL( \r\n            /* [in] */ BSTR url) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GotoMusicStoreHomePage( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdateIPod( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Authorize( \r\n            /* [in] */ long numElems,\r\n            /* [size_is][in] */ VARIANT data[  ],\r\n            /* [size_is][in] */ BSTR names[  ]) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Quit( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Sources( \r\n            /* [retval][out] */ IITSourceCollection **iSourceCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Encoders( \r\n            /* [retval][out] */ IITEncoderCollection **iEncoderCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EQPresets( \r\n            /* [retval][out] */ IITEQPresetCollection **iEQPresetCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Visuals( \r\n            /* [retval][out] */ IITVisualCollection **iVisualCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Windows( \r\n            /* [retval][out] */ IITWindowCollection **iWindowCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SoundVolume( \r\n            /* [retval][out] */ long *volume) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SoundVolume( \r\n            /* [in] */ long volume) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Mute( \r\n            /* [retval][out] */ VARIANT_BOOL *isMuted) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Mute( \r\n            /* [in] */ VARIANT_BOOL shouldMute) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlayerState( \r\n            /* [retval][out] */ ITPlayerState *playerState) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PlayerPosition( \r\n            /* [retval][out] */ long *playerPos) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_PlayerPosition( \r\n            /* [in] */ long playerPos) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentEncoder( \r\n            /* [retval][out] */ IITEncoder **iEncoder) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_CurrentEncoder( \r\n            /* [in] */ IITEncoder *iEncoder) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_VisualsEnabled( \r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_VisualsEnabled( \r\n            /* [in] */ VARIANT_BOOL shouldEnable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_FullScreenVisuals( \r\n            /* [retval][out] */ VARIANT_BOOL *isFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_FullScreenVisuals( \r\n            /* [in] */ VARIANT_BOOL shouldUseFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_VisualSize( \r\n            /* [retval][out] */ ITVisualSize *visualSize) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_VisualSize( \r\n            /* [in] */ ITVisualSize visualSize) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentVisual( \r\n            /* [retval][out] */ IITVisual **iVisual) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_CurrentVisual( \r\n            /* [in] */ IITVisual *iVisual) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EQEnabled( \r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_EQEnabled( \r\n            /* [in] */ VARIANT_BOOL shouldEnable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentEQPreset( \r\n            /* [retval][out] */ IITEQPreset **iEQPreset) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_CurrentEQPreset( \r\n            /* [in] */ IITEQPreset *iEQPreset) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentStreamTitle( \r\n            /* [retval][out] */ BSTR *streamTitle) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentStreamURL( \r\n            /* [retval][out] */ BSTR *streamURL) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_BrowserWindow( \r\n            /* [retval][out] */ IITBrowserWindow **iBrowserWindow) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EQWindow( \r\n            /* [retval][out] */ IITWindow **iEQWindow) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_LibrarySource( \r\n            /* [retval][out] */ IITSource **iLibrarySource) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_LibraryPlaylist( \r\n            /* [retval][out] */ IITLibraryPlaylist **iLibraryPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentTrack( \r\n            /* [retval][out] */ IITTrack **iTrack) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CurrentPlaylist( \r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SelectedTracks( \r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Version( \r\n            /* [retval][out] */ BSTR *version) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetOptions( \r\n            /* [in] */ long options) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertFile2( \r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertFiles2( \r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertTrack2( \r\n            /* [in] */ VARIANT *iTrackToConvert,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE ConvertTracks2( \r\n            /* [in] */ VARIANT *iTracksToConvert,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AppCommandMessageProcessingEnabled( \r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_AppCommandMessageProcessingEnabled( \r\n            /* [in] */ VARIANT_BOOL shouldEnable) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ForceToForegroundOnDialog( \r\n            /* [retval][out] */ VARIANT_BOOL *forceToForegroundOnDialog) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_ForceToForegroundOnDialog( \r\n            /* [in] */ VARIANT_BOOL forceToForegroundOnDialog) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreateEQPreset( \r\n            /* [in] */ BSTR eqPresetName,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreatePlaylistInSource( \r\n            /* [in] */ BSTR playlistName,\r\n            /* [in] */ VARIANT *iSource,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetPlayerButtonsState( \r\n            /* [out] */ VARIANT_BOOL *previousEnabled,\r\n            /* [out] */ ITPlayButtonState *playPauseStopState,\r\n            /* [out] */ VARIANT_BOOL *nextEnabled) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE PlayerButtonClicked( \r\n            /* [in] */ ITPlayerButton playerButton,\r\n            /* [in] */ long playerButtonModifierKeys) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CanSetShuffle( \r\n            /* [in] */ VARIANT *iPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *canSetShuffle) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_CanSetSongRepeat( \r\n            /* [in] */ VARIANT *iPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *canSetSongRepeat) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ConvertOperationStatus( \r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SubscribeToPodcast( \r\n            /* [in] */ BSTR url) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdatePodcastFeeds( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreateFolder( \r\n            /* [in] */ BSTR folderName,\r\n            /* [retval][out] */ IITPlaylist **iFolder) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE CreateFolderInSource( \r\n            /* [in] */ BSTR folderName,\r\n            /* [in] */ VARIANT *iSource,\r\n            /* [retval][out] */ IITPlaylist **iFolder) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SoundVolumeControlEnabled( \r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_LibraryXMLPath( \r\n            /* [retval][out] */ BSTR *filePath) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ITObjectPersistentIDHigh( \r\n            /* [in] */ VARIANT *iObject,\r\n            /* [retval][out] */ long *highID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ITObjectPersistentIDLow( \r\n            /* [in] */ VARIANT *iObject,\r\n            /* [retval][out] */ long *lowID) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE GetITObjectPersistentIDs( \r\n            /* [in] */ VARIANT *iObject,\r\n            /* [out] */ long *highID,\r\n            /* [out] */ long *lowID) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IiTunesVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IiTunes * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IiTunes * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IiTunes * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IiTunes * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IiTunes * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IiTunes * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IiTunes * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *BackTrack )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *FastForward )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *NextTrack )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Pause )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Play )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayFile )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR filePath);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayPause )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PreviousTrack )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Resume )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Rewind )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Stop )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertFile )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertFiles )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertTrack )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iTrackToConvert,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertTracks )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iTracksToConvert,\r\n            /* [retval][out] */ IITOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CheckVersion )( \r\n            IiTunes * This,\r\n            /* [in] */ long majorVersion,\r\n            /* [in] */ long minorVersion,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompatible);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectByID )( \r\n            IiTunes * This,\r\n            /* [in] */ long sourceID,\r\n            /* [in] */ long playlistID,\r\n            /* [in] */ long trackID,\r\n            /* [in] */ long databaseID,\r\n            /* [retval][out] */ IITObject **iObject);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreatePlaylist )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR playlistName,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *OpenURL )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR url);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GotoMusicStoreHomePage )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdateIPod )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Authorize )( \r\n            IiTunes * This,\r\n            /* [in] */ long numElems,\r\n            /* [size_is][in] */ VARIANT data[  ],\r\n            /* [size_is][in] */ BSTR names[  ]);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Quit )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Sources )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITSourceCollection **iSourceCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Encoders )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITEncoderCollection **iEncoderCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQPresets )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITEQPresetCollection **iEQPresetCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visuals )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITVisualCollection **iVisualCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Windows )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITWindowCollection **iWindowCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SoundVolume )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ long *volume);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SoundVolume )( \r\n            IiTunes * This,\r\n            /* [in] */ long volume);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Mute )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMuted);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Mute )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL shouldMute);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayerState )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ ITPlayerState *playerState);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayerPosition )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ long *playerPos);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayerPosition )( \r\n            IiTunes * This,\r\n            /* [in] */ long playerPos);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentEncoder )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITEncoder **iEncoder);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CurrentEncoder )( \r\n            IiTunes * This,\r\n            /* [in] */ IITEncoder *iEncoder);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VisualsEnabled )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VisualsEnabled )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL shouldEnable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FullScreenVisuals )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isFullScreen);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_FullScreenVisuals )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL shouldUseFullScreen);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VisualSize )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ ITVisualSize *visualSize);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VisualSize )( \r\n            IiTunes * This,\r\n            /* [in] */ ITVisualSize visualSize);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentVisual )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITVisual **iVisual);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CurrentVisual )( \r\n            IiTunes * This,\r\n            /* [in] */ IITVisual *iVisual);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQEnabled )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EQEnabled )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL shouldEnable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentEQPreset )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_CurrentEQPreset )( \r\n            IiTunes * This,\r\n            /* [in] */ IITEQPreset *iEQPreset);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentStreamTitle )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ BSTR *streamTitle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentStreamURL )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ BSTR *streamURL);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BrowserWindow )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITBrowserWindow **iBrowserWindow);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQWindow )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITWindow **iEQWindow);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LibrarySource )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITSource **iLibrarySource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LibraryPlaylist )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITLibraryPlaylist **iLibraryPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentTrack )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITTrack **iTrack);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CurrentPlaylist )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SelectedTracks )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Version )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ BSTR *version);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetOptions )( \r\n            IiTunes * This,\r\n            /* [in] */ long options);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertFile2 )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertFiles2 )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *filePaths,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertTrack2 )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iTrackToConvert,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *ConvertTracks2 )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iTracksToConvert,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AppCommandMessageProcessingEnabled )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_AppCommandMessageProcessingEnabled )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL shouldEnable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ForceToForegroundOnDialog )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *forceToForegroundOnDialog);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ForceToForegroundOnDialog )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT_BOOL forceToForegroundOnDialog);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreateEQPreset )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR eqPresetName,\r\n            /* [retval][out] */ IITEQPreset **iEQPreset);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreatePlaylistInSource )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR playlistName,\r\n            /* [in] */ VARIANT *iSource,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetPlayerButtonsState )( \r\n            IiTunes * This,\r\n            /* [out] */ VARIANT_BOOL *previousEnabled,\r\n            /* [out] */ ITPlayButtonState *playPauseStopState,\r\n            /* [out] */ VARIANT_BOOL *nextEnabled);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayerButtonClicked )( \r\n            IiTunes * This,\r\n            /* [in] */ ITPlayerButton playerButton,\r\n            /* [in] */ long playerButtonModifierKeys);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanSetShuffle )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *canSetShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_CanSetSongRepeat )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *canSetSongRepeat);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ConvertOperationStatus )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SubscribeToPodcast )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR url);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdatePodcastFeeds )( \r\n            IiTunes * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreateFolder )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR folderName,\r\n            /* [retval][out] */ IITPlaylist **iFolder);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *CreateFolderInSource )( \r\n            IiTunes * This,\r\n            /* [in] */ BSTR folderName,\r\n            /* [in] */ VARIANT *iSource,\r\n            /* [retval][out] */ IITPlaylist **iFolder);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SoundVolumeControlEnabled )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LibraryXMLPath )( \r\n            IiTunes * This,\r\n            /* [retval][out] */ BSTR *filePath);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ITObjectPersistentIDHigh )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iObject,\r\n            /* [retval][out] */ long *highID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ITObjectPersistentIDLow )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iObject,\r\n            /* [retval][out] */ long *lowID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectPersistentIDs )( \r\n            IiTunes * This,\r\n            /* [in] */ VARIANT *iObject,\r\n            /* [out] */ long *highID,\r\n            /* [out] */ long *lowID);\r\n        \r\n        END_INTERFACE\r\n    } IiTunesVtbl;\r\n\r\n    interface IiTunes\r\n    {\r\n        CONST_VTBL struct IiTunesVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IiTunes_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IiTunes_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IiTunes_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IiTunes_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IiTunes_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IiTunes_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IiTunes_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IiTunes_BackTrack(This)\t\\\r\n    (This)->lpVtbl -> BackTrack(This)\r\n\r\n#define IiTunes_FastForward(This)\t\\\r\n    (This)->lpVtbl -> FastForward(This)\r\n\r\n#define IiTunes_NextTrack(This)\t\\\r\n    (This)->lpVtbl -> NextTrack(This)\r\n\r\n#define IiTunes_Pause(This)\t\\\r\n    (This)->lpVtbl -> Pause(This)\r\n\r\n#define IiTunes_Play(This)\t\\\r\n    (This)->lpVtbl -> Play(This)\r\n\r\n#define IiTunes_PlayFile(This,filePath)\t\\\r\n    (This)->lpVtbl -> PlayFile(This,filePath)\r\n\r\n#define IiTunes_PlayPause(This)\t\\\r\n    (This)->lpVtbl -> PlayPause(This)\r\n\r\n#define IiTunes_PreviousTrack(This)\t\\\r\n    (This)->lpVtbl -> PreviousTrack(This)\r\n\r\n#define IiTunes_Resume(This)\t\\\r\n    (This)->lpVtbl -> Resume(This)\r\n\r\n#define IiTunes_Rewind(This)\t\\\r\n    (This)->lpVtbl -> Rewind(This)\r\n\r\n#define IiTunes_Stop(This)\t\\\r\n    (This)->lpVtbl -> Stop(This)\r\n\r\n#define IiTunes_ConvertFile(This,filePath,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertFile(This,filePath,iStatus)\r\n\r\n#define IiTunes_ConvertFiles(This,filePaths,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertFiles(This,filePaths,iStatus)\r\n\r\n#define IiTunes_ConvertTrack(This,iTrackToConvert,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertTrack(This,iTrackToConvert,iStatus)\r\n\r\n#define IiTunes_ConvertTracks(This,iTracksToConvert,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertTracks(This,iTracksToConvert,iStatus)\r\n\r\n#define IiTunes_CheckVersion(This,majorVersion,minorVersion,isCompatible)\t\\\r\n    (This)->lpVtbl -> CheckVersion(This,majorVersion,minorVersion,isCompatible)\r\n\r\n#define IiTunes_GetITObjectByID(This,sourceID,playlistID,trackID,databaseID,iObject)\t\\\r\n    (This)->lpVtbl -> GetITObjectByID(This,sourceID,playlistID,trackID,databaseID,iObject)\r\n\r\n#define IiTunes_CreatePlaylist(This,playlistName,iPlaylist)\t\\\r\n    (This)->lpVtbl -> CreatePlaylist(This,playlistName,iPlaylist)\r\n\r\n#define IiTunes_OpenURL(This,url)\t\\\r\n    (This)->lpVtbl -> OpenURL(This,url)\r\n\r\n#define IiTunes_GotoMusicStoreHomePage(This)\t\\\r\n    (This)->lpVtbl -> GotoMusicStoreHomePage(This)\r\n\r\n#define IiTunes_UpdateIPod(This)\t\\\r\n    (This)->lpVtbl -> UpdateIPod(This)\r\n\r\n#define IiTunes_Authorize(This,numElems,data,names)\t\\\r\n    (This)->lpVtbl -> Authorize(This,numElems,data,names)\r\n\r\n#define IiTunes_Quit(This)\t\\\r\n    (This)->lpVtbl -> Quit(This)\r\n\r\n#define IiTunes_get_Sources(This,iSourceCollection)\t\\\r\n    (This)->lpVtbl -> get_Sources(This,iSourceCollection)\r\n\r\n#define IiTunes_get_Encoders(This,iEncoderCollection)\t\\\r\n    (This)->lpVtbl -> get_Encoders(This,iEncoderCollection)\r\n\r\n#define IiTunes_get_EQPresets(This,iEQPresetCollection)\t\\\r\n    (This)->lpVtbl -> get_EQPresets(This,iEQPresetCollection)\r\n\r\n#define IiTunes_get_Visuals(This,iVisualCollection)\t\\\r\n    (This)->lpVtbl -> get_Visuals(This,iVisualCollection)\r\n\r\n#define IiTunes_get_Windows(This,iWindowCollection)\t\\\r\n    (This)->lpVtbl -> get_Windows(This,iWindowCollection)\r\n\r\n#define IiTunes_get_SoundVolume(This,volume)\t\\\r\n    (This)->lpVtbl -> get_SoundVolume(This,volume)\r\n\r\n#define IiTunes_put_SoundVolume(This,volume)\t\\\r\n    (This)->lpVtbl -> put_SoundVolume(This,volume)\r\n\r\n#define IiTunes_get_Mute(This,isMuted)\t\\\r\n    (This)->lpVtbl -> get_Mute(This,isMuted)\r\n\r\n#define IiTunes_put_Mute(This,shouldMute)\t\\\r\n    (This)->lpVtbl -> put_Mute(This,shouldMute)\r\n\r\n#define IiTunes_get_PlayerState(This,playerState)\t\\\r\n    (This)->lpVtbl -> get_PlayerState(This,playerState)\r\n\r\n#define IiTunes_get_PlayerPosition(This,playerPos)\t\\\r\n    (This)->lpVtbl -> get_PlayerPosition(This,playerPos)\r\n\r\n#define IiTunes_put_PlayerPosition(This,playerPos)\t\\\r\n    (This)->lpVtbl -> put_PlayerPosition(This,playerPos)\r\n\r\n#define IiTunes_get_CurrentEncoder(This,iEncoder)\t\\\r\n    (This)->lpVtbl -> get_CurrentEncoder(This,iEncoder)\r\n\r\n#define IiTunes_put_CurrentEncoder(This,iEncoder)\t\\\r\n    (This)->lpVtbl -> put_CurrentEncoder(This,iEncoder)\r\n\r\n#define IiTunes_get_VisualsEnabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_VisualsEnabled(This,isEnabled)\r\n\r\n#define IiTunes_put_VisualsEnabled(This,shouldEnable)\t\\\r\n    (This)->lpVtbl -> put_VisualsEnabled(This,shouldEnable)\r\n\r\n#define IiTunes_get_FullScreenVisuals(This,isFullScreen)\t\\\r\n    (This)->lpVtbl -> get_FullScreenVisuals(This,isFullScreen)\r\n\r\n#define IiTunes_put_FullScreenVisuals(This,shouldUseFullScreen)\t\\\r\n    (This)->lpVtbl -> put_FullScreenVisuals(This,shouldUseFullScreen)\r\n\r\n#define IiTunes_get_VisualSize(This,visualSize)\t\\\r\n    (This)->lpVtbl -> get_VisualSize(This,visualSize)\r\n\r\n#define IiTunes_put_VisualSize(This,visualSize)\t\\\r\n    (This)->lpVtbl -> put_VisualSize(This,visualSize)\r\n\r\n#define IiTunes_get_CurrentVisual(This,iVisual)\t\\\r\n    (This)->lpVtbl -> get_CurrentVisual(This,iVisual)\r\n\r\n#define IiTunes_put_CurrentVisual(This,iVisual)\t\\\r\n    (This)->lpVtbl -> put_CurrentVisual(This,iVisual)\r\n\r\n#define IiTunes_get_EQEnabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_EQEnabled(This,isEnabled)\r\n\r\n#define IiTunes_put_EQEnabled(This,shouldEnable)\t\\\r\n    (This)->lpVtbl -> put_EQEnabled(This,shouldEnable)\r\n\r\n#define IiTunes_get_CurrentEQPreset(This,iEQPreset)\t\\\r\n    (This)->lpVtbl -> get_CurrentEQPreset(This,iEQPreset)\r\n\r\n#define IiTunes_put_CurrentEQPreset(This,iEQPreset)\t\\\r\n    (This)->lpVtbl -> put_CurrentEQPreset(This,iEQPreset)\r\n\r\n#define IiTunes_get_CurrentStreamTitle(This,streamTitle)\t\\\r\n    (This)->lpVtbl -> get_CurrentStreamTitle(This,streamTitle)\r\n\r\n#define IiTunes_get_CurrentStreamURL(This,streamURL)\t\\\r\n    (This)->lpVtbl -> get_CurrentStreamURL(This,streamURL)\r\n\r\n#define IiTunes_get_BrowserWindow(This,iBrowserWindow)\t\\\r\n    (This)->lpVtbl -> get_BrowserWindow(This,iBrowserWindow)\r\n\r\n#define IiTunes_get_EQWindow(This,iEQWindow)\t\\\r\n    (This)->lpVtbl -> get_EQWindow(This,iEQWindow)\r\n\r\n#define IiTunes_get_LibrarySource(This,iLibrarySource)\t\\\r\n    (This)->lpVtbl -> get_LibrarySource(This,iLibrarySource)\r\n\r\n#define IiTunes_get_LibraryPlaylist(This,iLibraryPlaylist)\t\\\r\n    (This)->lpVtbl -> get_LibraryPlaylist(This,iLibraryPlaylist)\r\n\r\n#define IiTunes_get_CurrentTrack(This,iTrack)\t\\\r\n    (This)->lpVtbl -> get_CurrentTrack(This,iTrack)\r\n\r\n#define IiTunes_get_CurrentPlaylist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_CurrentPlaylist(This,iPlaylist)\r\n\r\n#define IiTunes_get_SelectedTracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_SelectedTracks(This,iTrackCollection)\r\n\r\n#define IiTunes_get_Version(This,version)\t\\\r\n    (This)->lpVtbl -> get_Version(This,version)\r\n\r\n#define IiTunes_SetOptions(This,options)\t\\\r\n    (This)->lpVtbl -> SetOptions(This,options)\r\n\r\n#define IiTunes_ConvertFile2(This,filePath,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertFile2(This,filePath,iStatus)\r\n\r\n#define IiTunes_ConvertFiles2(This,filePaths,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertFiles2(This,filePaths,iStatus)\r\n\r\n#define IiTunes_ConvertTrack2(This,iTrackToConvert,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertTrack2(This,iTrackToConvert,iStatus)\r\n\r\n#define IiTunes_ConvertTracks2(This,iTracksToConvert,iStatus)\t\\\r\n    (This)->lpVtbl -> ConvertTracks2(This,iTracksToConvert,iStatus)\r\n\r\n#define IiTunes_get_AppCommandMessageProcessingEnabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_AppCommandMessageProcessingEnabled(This,isEnabled)\r\n\r\n#define IiTunes_put_AppCommandMessageProcessingEnabled(This,shouldEnable)\t\\\r\n    (This)->lpVtbl -> put_AppCommandMessageProcessingEnabled(This,shouldEnable)\r\n\r\n#define IiTunes_get_ForceToForegroundOnDialog(This,forceToForegroundOnDialog)\t\\\r\n    (This)->lpVtbl -> get_ForceToForegroundOnDialog(This,forceToForegroundOnDialog)\r\n\r\n#define IiTunes_put_ForceToForegroundOnDialog(This,forceToForegroundOnDialog)\t\\\r\n    (This)->lpVtbl -> put_ForceToForegroundOnDialog(This,forceToForegroundOnDialog)\r\n\r\n#define IiTunes_CreateEQPreset(This,eqPresetName,iEQPreset)\t\\\r\n    (This)->lpVtbl -> CreateEQPreset(This,eqPresetName,iEQPreset)\r\n\r\n#define IiTunes_CreatePlaylistInSource(This,playlistName,iSource,iPlaylist)\t\\\r\n    (This)->lpVtbl -> CreatePlaylistInSource(This,playlistName,iSource,iPlaylist)\r\n\r\n#define IiTunes_GetPlayerButtonsState(This,previousEnabled,playPauseStopState,nextEnabled)\t\\\r\n    (This)->lpVtbl -> GetPlayerButtonsState(This,previousEnabled,playPauseStopState,nextEnabled)\r\n\r\n#define IiTunes_PlayerButtonClicked(This,playerButton,playerButtonModifierKeys)\t\\\r\n    (This)->lpVtbl -> PlayerButtonClicked(This,playerButton,playerButtonModifierKeys)\r\n\r\n#define IiTunes_get_CanSetShuffle(This,iPlaylist,canSetShuffle)\t\\\r\n    (This)->lpVtbl -> get_CanSetShuffle(This,iPlaylist,canSetShuffle)\r\n\r\n#define IiTunes_get_CanSetSongRepeat(This,iPlaylist,canSetSongRepeat)\t\\\r\n    (This)->lpVtbl -> get_CanSetSongRepeat(This,iPlaylist,canSetSongRepeat)\r\n\r\n#define IiTunes_get_ConvertOperationStatus(This,iStatus)\t\\\r\n    (This)->lpVtbl -> get_ConvertOperationStatus(This,iStatus)\r\n\r\n#define IiTunes_SubscribeToPodcast(This,url)\t\\\r\n    (This)->lpVtbl -> SubscribeToPodcast(This,url)\r\n\r\n#define IiTunes_UpdatePodcastFeeds(This)\t\\\r\n    (This)->lpVtbl -> UpdatePodcastFeeds(This)\r\n\r\n#define IiTunes_CreateFolder(This,folderName,iFolder)\t\\\r\n    (This)->lpVtbl -> CreateFolder(This,folderName,iFolder)\r\n\r\n#define IiTunes_CreateFolderInSource(This,folderName,iSource,iFolder)\t\\\r\n    (This)->lpVtbl -> CreateFolderInSource(This,folderName,iSource,iFolder)\r\n\r\n#define IiTunes_get_SoundVolumeControlEnabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_SoundVolumeControlEnabled(This,isEnabled)\r\n\r\n#define IiTunes_get_LibraryXMLPath(This,filePath)\t\\\r\n    (This)->lpVtbl -> get_LibraryXMLPath(This,filePath)\r\n\r\n#define IiTunes_get_ITObjectPersistentIDHigh(This,iObject,highID)\t\\\r\n    (This)->lpVtbl -> get_ITObjectPersistentIDHigh(This,iObject,highID)\r\n\r\n#define IiTunes_get_ITObjectPersistentIDLow(This,iObject,lowID)\t\\\r\n    (This)->lpVtbl -> get_ITObjectPersistentIDLow(This,iObject,lowID)\r\n\r\n#define IiTunes_GetITObjectPersistentIDs(This,iObject,highID,lowID)\t\\\r\n    (This)->lpVtbl -> GetITObjectPersistentIDs(This,iObject,highID,lowID)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_BackTrack_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_BackTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_FastForward_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_FastForward_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_NextTrack_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_NextTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Pause_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Pause_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Play_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Play_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_PlayFile_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR filePath);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_PlayFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_PlayPause_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_PlayPause_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_PreviousTrack_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_PreviousTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Resume_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Resume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Rewind_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Rewind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Stop_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Stop_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertFile_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR filePath,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertFiles_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *filePaths,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertFiles_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertTrack_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iTrackToConvert,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertTracks_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iTracksToConvert,\r\n    /* [retval][out] */ IITOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertTracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CheckVersion_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long majorVersion,\r\n    /* [in] */ long minorVersion,\r\n    /* [retval][out] */ VARIANT_BOOL *isCompatible);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CheckVersion_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_GetITObjectByID_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long sourceID,\r\n    /* [in] */ long playlistID,\r\n    /* [in] */ long trackID,\r\n    /* [in] */ long databaseID,\r\n    /* [retval][out] */ IITObject **iObject);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_GetITObjectByID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CreatePlaylist_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR playlistName,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CreatePlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_OpenURL_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR url);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_OpenURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_GotoMusicStoreHomePage_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_GotoMusicStoreHomePage_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_UpdateIPod_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_UpdateIPod_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Authorize_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long numElems,\r\n    /* [size_is][in] */ VARIANT data[  ],\r\n    /* [size_is][in] */ BSTR names[  ]);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Authorize_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_Quit_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_Quit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Sources_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITSourceCollection **iSourceCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Sources_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Encoders_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITEncoderCollection **iEncoderCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Encoders_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_EQPresets_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITEQPresetCollection **iEQPresetCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_EQPresets_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Visuals_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITVisualCollection **iVisualCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Visuals_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Windows_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITWindowCollection **iWindowCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Windows_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_SoundVolume_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ long *volume);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_SoundVolume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_SoundVolume_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long volume);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_SoundVolume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Mute_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isMuted);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Mute_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_Mute_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL shouldMute);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_Mute_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_PlayerState_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ ITPlayerState *playerState);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_PlayerState_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_PlayerPosition_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ long *playerPos);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_PlayerPosition_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_PlayerPosition_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long playerPos);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_PlayerPosition_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentEncoder_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITEncoder **iEncoder);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentEncoder_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_CurrentEncoder_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ IITEncoder *iEncoder);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_CurrentEncoder_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_VisualsEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_VisualsEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_VisualsEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL shouldEnable);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_VisualsEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_FullScreenVisuals_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_FullScreenVisuals_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_FullScreenVisuals_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL shouldUseFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_FullScreenVisuals_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_VisualSize_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ ITVisualSize *visualSize);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_VisualSize_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_VisualSize_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ ITVisualSize visualSize);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_VisualSize_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentVisual_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITVisual **iVisual);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentVisual_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_CurrentVisual_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ IITVisual *iVisual);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_CurrentVisual_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_EQEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_EQEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_EQEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL shouldEnable);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_EQEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentEQPreset_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITEQPreset **iEQPreset);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentEQPreset_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_CurrentEQPreset_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ IITEQPreset *iEQPreset);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_CurrentEQPreset_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentStreamTitle_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ BSTR *streamTitle);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentStreamTitle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentStreamURL_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ BSTR *streamURL);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentStreamURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_BrowserWindow_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITBrowserWindow **iBrowserWindow);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_BrowserWindow_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_EQWindow_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITWindow **iEQWindow);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_EQWindow_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_LibrarySource_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITSource **iLibrarySource);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_LibrarySource_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_LibraryPlaylist_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITLibraryPlaylist **iLibraryPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_LibraryPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentTrack_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITTrack **iTrack);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentTrack_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CurrentPlaylist_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CurrentPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_SelectedTracks_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_SelectedTracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_Version_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ BSTR *version);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_Version_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_SetOptions_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ long options);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_SetOptions_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertFile2_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR filePath,\r\n    /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertFile2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertFiles2_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *filePaths,\r\n    /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertFiles2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertTrack2_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iTrackToConvert,\r\n    /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertTrack2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_ConvertTracks2_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iTracksToConvert,\r\n    /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_ConvertTracks2_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_AppCommandMessageProcessingEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_AppCommandMessageProcessingEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_AppCommandMessageProcessingEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL shouldEnable);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_AppCommandMessageProcessingEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_ForceToForegroundOnDialog_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *forceToForegroundOnDialog);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_ForceToForegroundOnDialog_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IiTunes_put_ForceToForegroundOnDialog_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT_BOOL forceToForegroundOnDialog);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_put_ForceToForegroundOnDialog_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CreateEQPreset_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR eqPresetName,\r\n    /* [retval][out] */ IITEQPreset **iEQPreset);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CreateEQPreset_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CreatePlaylistInSource_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR playlistName,\r\n    /* [in] */ VARIANT *iSource,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CreatePlaylistInSource_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_GetPlayerButtonsState_Proxy( \r\n    IiTunes * This,\r\n    /* [out] */ VARIANT_BOOL *previousEnabled,\r\n    /* [out] */ ITPlayButtonState *playPauseStopState,\r\n    /* [out] */ VARIANT_BOOL *nextEnabled);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_GetPlayerButtonsState_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_PlayerButtonClicked_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ ITPlayerButton playerButton,\r\n    /* [in] */ long playerButtonModifierKeys);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_PlayerButtonClicked_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CanSetShuffle_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iPlaylist,\r\n    /* [retval][out] */ VARIANT_BOOL *canSetShuffle);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CanSetShuffle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_CanSetSongRepeat_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iPlaylist,\r\n    /* [retval][out] */ VARIANT_BOOL *canSetSongRepeat);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_CanSetSongRepeat_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_ConvertOperationStatus_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ IITConvertOperationStatus **iStatus);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_ConvertOperationStatus_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_SubscribeToPodcast_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR url);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_SubscribeToPodcast_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_UpdatePodcastFeeds_Proxy( \r\n    IiTunes * This);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_UpdatePodcastFeeds_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CreateFolder_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR folderName,\r\n    /* [retval][out] */ IITPlaylist **iFolder);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CreateFolder_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_CreateFolderInSource_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ BSTR folderName,\r\n    /* [in] */ VARIANT *iSource,\r\n    /* [retval][out] */ IITPlaylist **iFolder);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_CreateFolderInSource_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_SoundVolumeControlEnabled_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_SoundVolumeControlEnabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_LibraryXMLPath_Proxy( \r\n    IiTunes * This,\r\n    /* [retval][out] */ BSTR *filePath);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_LibraryXMLPath_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_ITObjectPersistentIDHigh_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iObject,\r\n    /* [retval][out] */ long *highID);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_ITObjectPersistentIDHigh_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IiTunes_get_ITObjectPersistentIDLow_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iObject,\r\n    /* [retval][out] */ long *lowID);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_get_ITObjectPersistentIDLow_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IiTunes_GetITObjectPersistentIDs_Proxy( \r\n    IiTunes * This,\r\n    /* [in] */ VARIANT *iObject,\r\n    /* [out] */ long *highID,\r\n    /* [out] */ long *lowID);\r\n\r\n\r\nvoid __RPC_STUB IiTunes_GetITObjectPersistentIDs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IiTunes_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef ___IiTunesEvents_DISPINTERFACE_DEFINED__\r\n#define ___IiTunesEvents_DISPINTERFACE_DEFINED__\r\n\r\n/* dispinterface _IiTunesEvents */\r\n/* [helpstring][uuid] */ \r\n\r\n\r\nEXTERN_C const IID DIID__IiTunesEvents;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n\r\n    MIDL_INTERFACE(\"5846EB78-317E-4b6f-B0C3-11EE8C8FEEF2\")\r\n    _IiTunesEvents : public IDispatch\r\n    {\r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct _IiTunesEventsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            _IiTunesEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            _IiTunesEvents * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            _IiTunesEvents * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            _IiTunesEvents * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            _IiTunesEvents * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            _IiTunesEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            _IiTunesEvents * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        END_INTERFACE\r\n    } _IiTunesEventsVtbl;\r\n\r\n    interface _IiTunesEvents\r\n    {\r\n        CONST_VTBL struct _IiTunesEventsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define _IiTunesEvents_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define _IiTunesEvents_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define _IiTunesEvents_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define _IiTunesEvents_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define _IiTunesEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define _IiTunesEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define _IiTunesEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n#endif \t/* ___IiTunesEvents_DISPINTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef ___IITConvertOperationStatusEvents_DISPINTERFACE_DEFINED__\r\n#define ___IITConvertOperationStatusEvents_DISPINTERFACE_DEFINED__\r\n\r\n/* dispinterface _IITConvertOperationStatusEvents */\r\n/* [helpstring][uuid] */ \r\n\r\n\r\nEXTERN_C const IID DIID__IITConvertOperationStatusEvents;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n\r\n    MIDL_INTERFACE(\"5C47A705-8E8A-45a1-9EED-71C993F0BF60\")\r\n    _IITConvertOperationStatusEvents : public IDispatch\r\n    {\r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct _IITConvertOperationStatusEventsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            _IITConvertOperationStatusEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            _IITConvertOperationStatusEvents * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            _IITConvertOperationStatusEvents * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            _IITConvertOperationStatusEvents * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            _IITConvertOperationStatusEvents * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            _IITConvertOperationStatusEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            _IITConvertOperationStatusEvents * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        END_INTERFACE\r\n    } _IITConvertOperationStatusEventsVtbl;\r\n\r\n    interface _IITConvertOperationStatusEvents\r\n    {\r\n        CONST_VTBL struct _IITConvertOperationStatusEventsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define _IITConvertOperationStatusEvents_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define _IITConvertOperationStatusEvents_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define _IITConvertOperationStatusEvents_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define _IITConvertOperationStatusEvents_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define _IITConvertOperationStatusEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define _IITConvertOperationStatusEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define _IITConvertOperationStatusEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n#endif \t/* ___IITConvertOperationStatusEvents_DISPINTERFACE_DEFINED__ */\r\n\r\n\r\nEXTERN_C const CLSID CLSID_iTunesApp;\r\n\r\n#ifdef __cplusplus\r\n\r\nclass DECLSPEC_UUID(\"DC0C2640-1415-4644-875C-6F4D769839BA\")\r\niTunesApp;\r\n#endif\r\n\r\nEXTERN_C const CLSID CLSID_iTunesConvertOperationStatus;\r\n\r\n#ifdef __cplusplus\r\n\r\nclass DECLSPEC_UUID(\"D06596AD-C900-41b2-BC68-1B486450FC56\")\r\niTunesConvertOperationStatus;\r\n#endif\r\n\r\n#ifndef __IITArtwork_INTERFACE_DEFINED__\r\n#define __IITArtwork_INTERFACE_DEFINED__\r\n\r\n/* interface IITArtwork */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITArtwork;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"D0A6C1F8-BF3D-4cd8-AC47-FE32BDD17257\")\r\n    IITArtwork : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Delete( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SetArtworkFromFile( \r\n            /* [in] */ BSTR filePath) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE SaveArtworkToFile( \r\n            /* [in] */ BSTR filePath) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Format( \r\n            /* [retval][out] */ ITArtworkFormat *format) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_IsDownloadedArtwork( \r\n            /* [retval][out] */ VARIANT_BOOL *isDownloadedArtwork) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Description( \r\n            /* [retval][out] */ BSTR *description) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Description( \r\n            /* [in] */ BSTR description) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITArtworkVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITArtwork * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITArtwork * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITArtwork * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITArtwork * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITArtwork * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITArtwork * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITArtwork * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITArtwork * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SetArtworkFromFile )( \r\n            IITArtwork * This,\r\n            /* [in] */ BSTR filePath);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *SaveArtworkToFile )( \r\n            IITArtwork * This,\r\n            /* [in] */ BSTR filePath);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Format )( \r\n            IITArtwork * This,\r\n            /* [retval][out] */ ITArtworkFormat *format);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsDownloadedArtwork )( \r\n            IITArtwork * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isDownloadedArtwork);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( \r\n            IITArtwork * This,\r\n            /* [retval][out] */ BSTR *description);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Description )( \r\n            IITArtwork * This,\r\n            /* [in] */ BSTR description);\r\n        \r\n        END_INTERFACE\r\n    } IITArtworkVtbl;\r\n\r\n    interface IITArtwork\r\n    {\r\n        CONST_VTBL struct IITArtworkVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITArtwork_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITArtwork_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITArtwork_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITArtwork_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITArtwork_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITArtwork_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITArtwork_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITArtwork_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITArtwork_SetArtworkFromFile(This,filePath)\t\\\r\n    (This)->lpVtbl -> SetArtworkFromFile(This,filePath)\r\n\r\n#define IITArtwork_SaveArtworkToFile(This,filePath)\t\\\r\n    (This)->lpVtbl -> SaveArtworkToFile(This,filePath)\r\n\r\n#define IITArtwork_get_Format(This,format)\t\\\r\n    (This)->lpVtbl -> get_Format(This,format)\r\n\r\n#define IITArtwork_get_IsDownloadedArtwork(This,isDownloadedArtwork)\t\\\r\n    (This)->lpVtbl -> get_IsDownloadedArtwork(This,isDownloadedArtwork)\r\n\r\n#define IITArtwork_get_Description(This,description)\t\\\r\n    (This)->lpVtbl -> get_Description(This,description)\r\n\r\n#define IITArtwork_put_Description(This,description)\t\\\r\n    (This)->lpVtbl -> put_Description(This,description)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITArtwork_Delete_Proxy( \r\n    IITArtwork * This);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_Delete_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITArtwork_SetArtworkFromFile_Proxy( \r\n    IITArtwork * This,\r\n    /* [in] */ BSTR filePath);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_SetArtworkFromFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITArtwork_SaveArtworkToFile_Proxy( \r\n    IITArtwork * This,\r\n    /* [in] */ BSTR filePath);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_SaveArtworkToFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITArtwork_get_Format_Proxy( \r\n    IITArtwork * This,\r\n    /* [retval][out] */ ITArtworkFormat *format);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_get_Format_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITArtwork_get_IsDownloadedArtwork_Proxy( \r\n    IITArtwork * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isDownloadedArtwork);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_get_IsDownloadedArtwork_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITArtwork_get_Description_Proxy( \r\n    IITArtwork * This,\r\n    /* [retval][out] */ BSTR *description);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_get_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITArtwork_put_Description_Proxy( \r\n    IITArtwork * This,\r\n    /* [in] */ BSTR description);\r\n\r\n\r\nvoid __RPC_STUB IITArtwork_put_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITArtwork_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITArtworkCollection_INTERFACE_DEFINED__\r\n#define __IITArtworkCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITArtworkCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITArtworkCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"BF2742D7-418C-4858-9AF9-2981B062D23E\")\r\n    IITArtworkCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITArtwork **iArtwork) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITArtworkCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITArtworkCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITArtworkCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITArtworkCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITArtworkCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITArtworkCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITArtworkCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITArtworkCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITArtworkCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITArtworkCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITArtwork **iArtwork);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITArtworkCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        END_INTERFACE\r\n    } IITArtworkCollectionVtbl;\r\n\r\n    interface IITArtworkCollection\r\n    {\r\n        CONST_VTBL struct IITArtworkCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITArtworkCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITArtworkCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITArtworkCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITArtworkCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITArtworkCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITArtworkCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITArtworkCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITArtworkCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITArtworkCollection_get_Item(This,index,iArtwork)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iArtwork)\r\n\r\n#define IITArtworkCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITArtworkCollection_get_Count_Proxy( \r\n    IITArtworkCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITArtworkCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITArtworkCollection_get_Item_Proxy( \r\n    IITArtworkCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITArtwork **iArtwork);\r\n\r\n\r\nvoid __RPC_STUB IITArtworkCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITArtworkCollection_get__NewEnum_Proxy( \r\n    IITArtworkCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITArtworkCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITArtworkCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITURLTrack_INTERFACE_DEFINED__\r\n#define __IITURLTrack_INTERFACE_DEFINED__\r\n\r\n/* interface IITURLTrack */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITURLTrack;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"1116E3B5-29FD-4393-A7BD-454E5E327900\")\r\n    IITURLTrack : public IITTrack\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_URL( \r\n            /* [retval][out] */ BSTR *url) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_URL( \r\n            /* [in] */ BSTR url) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Podcast( \r\n            /* [retval][out] */ VARIANT_BOOL *isPodcast) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdatePodcastFeed( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE DownloadPodcastEpisode( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Category( \r\n            /* [retval][out] */ BSTR *category) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Category( \r\n            /* [in] */ BSTR category) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Description( \r\n            /* [retval][out] */ BSTR *description) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Description( \r\n            /* [in] */ BSTR description) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_LongDescription( \r\n            /* [retval][out] */ BSTR *longDescription) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_LongDescription( \r\n            /* [in] */ BSTR longDescription) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Reveal( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AlbumRating( \r\n            /* [retval][out] */ long *rating) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_AlbumRating( \r\n            /* [in] */ long rating) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AlbumRatingKind( \r\n            /* [retval][out] */ ITRatingKind *ratingKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_RatingKind( \r\n            /* [retval][out] */ ITRatingKind *ratingKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Playlists( \r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITURLTrackVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITURLTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITURLTrack * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITURLTrack * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITURLTrack * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITURLTrack * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITURLTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITURLTrack * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITURLTrack * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITURLTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Play )( \r\n            IITURLTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddArtworkFromFile )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITArtwork **iArtwork);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ ITTrackKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlist )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Album )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *album);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Album )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR album);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artist )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *artist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Artist )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR artist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRate )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *bitrate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BPM )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *beatsPerMinute);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BPM )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long beatsPerMinute);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Comment )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *comment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Comment )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR comment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Compilation )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompilation);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Compilation )( \r\n            IITURLTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeCompilation);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Composer )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *composer);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Composer )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR composer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DateAdded )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ DATE *dateAdded);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscCount )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *discCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscCount )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long discCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscNumber )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *discNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscNumber )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long discNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Enabled )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Enabled )( \r\n            IITURLTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeEnabled);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQ )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EQ )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Finish )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Finish )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Genre )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *genre);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Genre )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR genre);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Grouping )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *grouping);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Grouping )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR grouping);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_KindAsString )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ModificationDate )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ DATE *dateModified);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedCount )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *playedCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedCount )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long playedCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedDate )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ DATE *playedDate);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedDate )( \r\n            IITURLTrack * This,\r\n            /* [in] */ DATE playedDate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayOrderIndex )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Rating )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *rating);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Rating )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long rating);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SampleRate )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *sampleRate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Start )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *start);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Start )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long start);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackCount )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *trackCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackCount )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long trackCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackNumber )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *trackNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackNumber )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long trackNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VolumeAdjustment )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *volumeAdjustment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VolumeAdjustment )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long volumeAdjustment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Year )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *year);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Year )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long year);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artwork )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ IITArtworkCollection **iArtworkCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *url);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR url);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Podcast )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isPodcast);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdatePodcastFeed )( \r\n            IITURLTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *DownloadPodcastEpisode )( \r\n            IITURLTrack * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Category )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *category);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Category )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR category);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *description);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Description )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR description);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LongDescription )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ BSTR *longDescription);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_LongDescription )( \r\n            IITURLTrack * This,\r\n            /* [in] */ BSTR longDescription);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Reveal )( \r\n            IITURLTrack * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AlbumRating )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ long *rating);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_AlbumRating )( \r\n            IITURLTrack * This,\r\n            /* [in] */ long rating);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AlbumRatingKind )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ ITRatingKind *ratingKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_RatingKind )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ ITRatingKind *ratingKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlists )( \r\n            IITURLTrack * This,\r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITURLTrackVtbl;\r\n\r\n    interface IITURLTrack\r\n    {\r\n        CONST_VTBL struct IITURLTrackVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITURLTrack_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITURLTrack_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITURLTrack_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITURLTrack_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITURLTrack_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITURLTrack_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITURLTrack_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITURLTrack_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITURLTrack_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITURLTrack_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITURLTrack_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITURLTrack_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITURLTrack_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITURLTrack_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITURLTrack_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITURLTrack_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITURLTrack_Play(This)\t\\\r\n    (This)->lpVtbl -> Play(This)\r\n\r\n#define IITURLTrack_AddArtworkFromFile(This,filePath,iArtwork)\t\\\r\n    (This)->lpVtbl -> AddArtworkFromFile(This,filePath,iArtwork)\r\n\r\n#define IITURLTrack_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITURLTrack_get_Playlist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_Playlist(This,iPlaylist)\r\n\r\n#define IITURLTrack_get_Album(This,album)\t\\\r\n    (This)->lpVtbl -> get_Album(This,album)\r\n\r\n#define IITURLTrack_put_Album(This,album)\t\\\r\n    (This)->lpVtbl -> put_Album(This,album)\r\n\r\n#define IITURLTrack_get_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> get_Artist(This,artist)\r\n\r\n#define IITURLTrack_put_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> put_Artist(This,artist)\r\n\r\n#define IITURLTrack_get_BitRate(This,bitrate)\t\\\r\n    (This)->lpVtbl -> get_BitRate(This,bitrate)\r\n\r\n#define IITURLTrack_get_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> get_BPM(This,beatsPerMinute)\r\n\r\n#define IITURLTrack_put_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> put_BPM(This,beatsPerMinute)\r\n\r\n#define IITURLTrack_get_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> get_Comment(This,comment)\r\n\r\n#define IITURLTrack_put_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> put_Comment(This,comment)\r\n\r\n#define IITURLTrack_get_Compilation(This,isCompilation)\t\\\r\n    (This)->lpVtbl -> get_Compilation(This,isCompilation)\r\n\r\n#define IITURLTrack_put_Compilation(This,shouldBeCompilation)\t\\\r\n    (This)->lpVtbl -> put_Compilation(This,shouldBeCompilation)\r\n\r\n#define IITURLTrack_get_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> get_Composer(This,composer)\r\n\r\n#define IITURLTrack_put_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> put_Composer(This,composer)\r\n\r\n#define IITURLTrack_get_DateAdded(This,dateAdded)\t\\\r\n    (This)->lpVtbl -> get_DateAdded(This,dateAdded)\r\n\r\n#define IITURLTrack_get_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> get_DiscCount(This,discCount)\r\n\r\n#define IITURLTrack_put_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> put_DiscCount(This,discCount)\r\n\r\n#define IITURLTrack_get_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> get_DiscNumber(This,discNumber)\r\n\r\n#define IITURLTrack_put_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> put_DiscNumber(This,discNumber)\r\n\r\n#define IITURLTrack_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITURLTrack_get_Enabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_Enabled(This,isEnabled)\r\n\r\n#define IITURLTrack_put_Enabled(This,shouldBeEnabled)\t\\\r\n    (This)->lpVtbl -> put_Enabled(This,shouldBeEnabled)\r\n\r\n#define IITURLTrack_get_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> get_EQ(This,eq)\r\n\r\n#define IITURLTrack_put_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> put_EQ(This,eq)\r\n\r\n#define IITURLTrack_put_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> put_Finish(This,finish)\r\n\r\n#define IITURLTrack_get_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> get_Finish(This,finish)\r\n\r\n#define IITURLTrack_get_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> get_Genre(This,genre)\r\n\r\n#define IITURLTrack_put_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> put_Genre(This,genre)\r\n\r\n#define IITURLTrack_get_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> get_Grouping(This,grouping)\r\n\r\n#define IITURLTrack_put_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> put_Grouping(This,grouping)\r\n\r\n#define IITURLTrack_get_KindAsString(This,kind)\t\\\r\n    (This)->lpVtbl -> get_KindAsString(This,kind)\r\n\r\n#define IITURLTrack_get_ModificationDate(This,dateModified)\t\\\r\n    (This)->lpVtbl -> get_ModificationDate(This,dateModified)\r\n\r\n#define IITURLTrack_get_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> get_PlayedCount(This,playedCount)\r\n\r\n#define IITURLTrack_put_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> put_PlayedCount(This,playedCount)\r\n\r\n#define IITURLTrack_get_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> get_PlayedDate(This,playedDate)\r\n\r\n#define IITURLTrack_put_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> put_PlayedDate(This,playedDate)\r\n\r\n#define IITURLTrack_get_PlayOrderIndex(This,index)\t\\\r\n    (This)->lpVtbl -> get_PlayOrderIndex(This,index)\r\n\r\n#define IITURLTrack_get_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> get_Rating(This,rating)\r\n\r\n#define IITURLTrack_put_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> put_Rating(This,rating)\r\n\r\n#define IITURLTrack_get_SampleRate(This,sampleRate)\t\\\r\n    (This)->lpVtbl -> get_SampleRate(This,sampleRate)\r\n\r\n#define IITURLTrack_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITURLTrack_get_Start(This,start)\t\\\r\n    (This)->lpVtbl -> get_Start(This,start)\r\n\r\n#define IITURLTrack_put_Start(This,start)\t\\\r\n    (This)->lpVtbl -> put_Start(This,start)\r\n\r\n#define IITURLTrack_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITURLTrack_get_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> get_TrackCount(This,trackCount)\r\n\r\n#define IITURLTrack_put_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> put_TrackCount(This,trackCount)\r\n\r\n#define IITURLTrack_get_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> get_TrackNumber(This,trackNumber)\r\n\r\n#define IITURLTrack_put_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> put_TrackNumber(This,trackNumber)\r\n\r\n#define IITURLTrack_get_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> get_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITURLTrack_put_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> put_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITURLTrack_get_Year(This,year)\t\\\r\n    (This)->lpVtbl -> get_Year(This,year)\r\n\r\n#define IITURLTrack_put_Year(This,year)\t\\\r\n    (This)->lpVtbl -> put_Year(This,year)\r\n\r\n#define IITURLTrack_get_Artwork(This,iArtworkCollection)\t\\\r\n    (This)->lpVtbl -> get_Artwork(This,iArtworkCollection)\r\n\r\n\r\n#define IITURLTrack_get_URL(This,url)\t\\\r\n    (This)->lpVtbl -> get_URL(This,url)\r\n\r\n#define IITURLTrack_put_URL(This,url)\t\\\r\n    (This)->lpVtbl -> put_URL(This,url)\r\n\r\n#define IITURLTrack_get_Podcast(This,isPodcast)\t\\\r\n    (This)->lpVtbl -> get_Podcast(This,isPodcast)\r\n\r\n#define IITURLTrack_UpdatePodcastFeed(This)\t\\\r\n    (This)->lpVtbl -> UpdatePodcastFeed(This)\r\n\r\n#define IITURLTrack_DownloadPodcastEpisode(This)\t\\\r\n    (This)->lpVtbl -> DownloadPodcastEpisode(This)\r\n\r\n#define IITURLTrack_get_Category(This,category)\t\\\r\n    (This)->lpVtbl -> get_Category(This,category)\r\n\r\n#define IITURLTrack_put_Category(This,category)\t\\\r\n    (This)->lpVtbl -> put_Category(This,category)\r\n\r\n#define IITURLTrack_get_Description(This,description)\t\\\r\n    (This)->lpVtbl -> get_Description(This,description)\r\n\r\n#define IITURLTrack_put_Description(This,description)\t\\\r\n    (This)->lpVtbl -> put_Description(This,description)\r\n\r\n#define IITURLTrack_get_LongDescription(This,longDescription)\t\\\r\n    (This)->lpVtbl -> get_LongDescription(This,longDescription)\r\n\r\n#define IITURLTrack_put_LongDescription(This,longDescription)\t\\\r\n    (This)->lpVtbl -> put_LongDescription(This,longDescription)\r\n\r\n#define IITURLTrack_Reveal(This)\t\\\r\n    (This)->lpVtbl -> Reveal(This)\r\n\r\n#define IITURLTrack_get_AlbumRating(This,rating)\t\\\r\n    (This)->lpVtbl -> get_AlbumRating(This,rating)\r\n\r\n#define IITURLTrack_put_AlbumRating(This,rating)\t\\\r\n    (This)->lpVtbl -> put_AlbumRating(This,rating)\r\n\r\n#define IITURLTrack_get_AlbumRatingKind(This,ratingKind)\t\\\r\n    (This)->lpVtbl -> get_AlbumRatingKind(This,ratingKind)\r\n\r\n#define IITURLTrack_get_RatingKind(This,ratingKind)\t\\\r\n    (This)->lpVtbl -> get_RatingKind(This,ratingKind)\r\n\r\n#define IITURLTrack_get_Playlists(This,iPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_Playlists(This,iPlaylistCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_URL_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ BSTR *url);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_URL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITURLTrack_put_URL_Proxy( \r\n    IITURLTrack * This,\r\n    /* [in] */ BSTR url);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_put_URL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_Podcast_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isPodcast);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_Podcast_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITURLTrack_UpdatePodcastFeed_Proxy( \r\n    IITURLTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_UpdatePodcastFeed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITURLTrack_DownloadPodcastEpisode_Proxy( \r\n    IITURLTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_DownloadPodcastEpisode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_Category_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ BSTR *category);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_Category_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITURLTrack_put_Category_Proxy( \r\n    IITURLTrack * This,\r\n    /* [in] */ BSTR category);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_put_Category_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_Description_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ BSTR *description);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITURLTrack_put_Description_Proxy( \r\n    IITURLTrack * This,\r\n    /* [in] */ BSTR description);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_put_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_LongDescription_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ BSTR *longDescription);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_LongDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITURLTrack_put_LongDescription_Proxy( \r\n    IITURLTrack * This,\r\n    /* [in] */ BSTR longDescription);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_put_LongDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITURLTrack_Reveal_Proxy( \r\n    IITURLTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_Reveal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_AlbumRating_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ long *rating);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_AlbumRating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITURLTrack_put_AlbumRating_Proxy( \r\n    IITURLTrack * This,\r\n    /* [in] */ long rating);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_put_AlbumRating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_AlbumRatingKind_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ ITRatingKind *ratingKind);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_AlbumRatingKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_RatingKind_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ ITRatingKind *ratingKind);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_RatingKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITURLTrack_get_Playlists_Proxy( \r\n    IITURLTrack * This,\r\n    /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n\r\n\r\nvoid __RPC_STUB IITURLTrack_get_Playlists_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITURLTrack_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITAudioCDPlaylist_INTERFACE_DEFINED__\r\n#define __IITAudioCDPlaylist_INTERFACE_DEFINED__\r\n\r\n/* interface IITAudioCDPlaylist */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITAudioCDPlaylist;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"CF496DF3-0FED-4d7d-9BD8-529B6E8A082E\")\r\n    IITAudioCDPlaylist : public IITPlaylist\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Artist( \r\n            /* [retval][out] */ BSTR *artist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Compilation( \r\n            /* [retval][out] */ VARIANT_BOOL *isCompiliation) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Composer( \r\n            /* [retval][out] */ BSTR *composer) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_DiscCount( \r\n            /* [retval][out] */ long *discCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_DiscNumber( \r\n            /* [retval][out] */ long *discNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Genre( \r\n            /* [retval][out] */ BSTR *genre) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Year( \r\n            /* [retval][out] */ long *year) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Reveal( void) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITAudioCDPlaylistVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITAudioCDPlaylist * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITAudioCDPlaylist * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITAudioCDPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *PlayFirstTrack )( \r\n            IITAudioCDPlaylist * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Print )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL showPrintDialog,\r\n            /* [in] */ ITPlaylistPrintKind printKind,\r\n            /* [in] */ BSTR theme);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Search )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ BSTR searchText,\r\n            /* [in] */ ITPlaylistSearchField searchFields,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Source )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ IITSource **iSource);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Shuffle )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isShuffle);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Shuffle )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ VARIANT_BOOL shouldShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ double *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SongRepeat )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ ITPlaylistRepeatMode *repeatMode);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SongRepeat )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [in] */ ITPlaylistRepeatMode repeatMode);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracks )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artist )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ BSTR *artist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Compilation )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompiliation);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Composer )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ BSTR *composer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscCount )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *discCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscNumber )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *discNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Genre )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ BSTR *genre);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Year )( \r\n            IITAudioCDPlaylist * This,\r\n            /* [retval][out] */ long *year);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Reveal )( \r\n            IITAudioCDPlaylist * This);\r\n        \r\n        END_INTERFACE\r\n    } IITAudioCDPlaylistVtbl;\r\n\r\n    interface IITAudioCDPlaylist\r\n    {\r\n        CONST_VTBL struct IITAudioCDPlaylistVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITAudioCDPlaylist_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITAudioCDPlaylist_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITAudioCDPlaylist_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITAudioCDPlaylist_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITAudioCDPlaylist_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITAudioCDPlaylist_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITAudioCDPlaylist_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITAudioCDPlaylist_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITAudioCDPlaylist_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITAudioCDPlaylist_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITAudioCDPlaylist_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITAudioCDPlaylist_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITAudioCDPlaylist_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITAudioCDPlaylist_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITAudioCDPlaylist_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITAudioCDPlaylist_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITAudioCDPlaylist_PlayFirstTrack(This)\t\\\r\n    (This)->lpVtbl -> PlayFirstTrack(This)\r\n\r\n#define IITAudioCDPlaylist_Print(This,showPrintDialog,printKind,theme)\t\\\r\n    (This)->lpVtbl -> Print(This,showPrintDialog,printKind,theme)\r\n\r\n#define IITAudioCDPlaylist_Search(This,searchText,searchFields,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> Search(This,searchText,searchFields,iTrackCollection)\r\n\r\n#define IITAudioCDPlaylist_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITAudioCDPlaylist_get_Source(This,iSource)\t\\\r\n    (This)->lpVtbl -> get_Source(This,iSource)\r\n\r\n#define IITAudioCDPlaylist_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITAudioCDPlaylist_get_Shuffle(This,isShuffle)\t\\\r\n    (This)->lpVtbl -> get_Shuffle(This,isShuffle)\r\n\r\n#define IITAudioCDPlaylist_put_Shuffle(This,shouldShuffle)\t\\\r\n    (This)->lpVtbl -> put_Shuffle(This,shouldShuffle)\r\n\r\n#define IITAudioCDPlaylist_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITAudioCDPlaylist_get_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> get_SongRepeat(This,repeatMode)\r\n\r\n#define IITAudioCDPlaylist_put_SongRepeat(This,repeatMode)\t\\\r\n    (This)->lpVtbl -> put_SongRepeat(This,repeatMode)\r\n\r\n#define IITAudioCDPlaylist_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITAudioCDPlaylist_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITAudioCDPlaylist_get_Tracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_Tracks(This,iTrackCollection)\r\n\r\n\r\n#define IITAudioCDPlaylist_get_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> get_Artist(This,artist)\r\n\r\n#define IITAudioCDPlaylist_get_Compilation(This,isCompiliation)\t\\\r\n    (This)->lpVtbl -> get_Compilation(This,isCompiliation)\r\n\r\n#define IITAudioCDPlaylist_get_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> get_Composer(This,composer)\r\n\r\n#define IITAudioCDPlaylist_get_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> get_DiscCount(This,discCount)\r\n\r\n#define IITAudioCDPlaylist_get_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> get_DiscNumber(This,discNumber)\r\n\r\n#define IITAudioCDPlaylist_get_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> get_Genre(This,genre)\r\n\r\n#define IITAudioCDPlaylist_get_Year(This,year)\t\\\r\n    (This)->lpVtbl -> get_Year(This,year)\r\n\r\n#define IITAudioCDPlaylist_Reveal(This)\t\\\r\n    (This)->lpVtbl -> Reveal(This)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_Artist_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ BSTR *artist);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_Artist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_Compilation_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isCompiliation);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_Compilation_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_Composer_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ BSTR *composer);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_Composer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_DiscCount_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ long *discCount);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_DiscCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_DiscNumber_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ long *discNumber);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_DiscNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_Genre_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ BSTR *genre);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_Genre_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_get_Year_Proxy( \r\n    IITAudioCDPlaylist * This,\r\n    /* [retval][out] */ long *year);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_get_Year_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITAudioCDPlaylist_Reveal_Proxy( \r\n    IITAudioCDPlaylist * This);\r\n\r\n\r\nvoid __RPC_STUB IITAudioCDPlaylist_Reveal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITAudioCDPlaylist_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylistCollection_INTERFACE_DEFINED__\r\n#define __IITPlaylistCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IITPlaylistCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITPlaylistCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"FF194254-909D-4437-9C50-3AAC2AE6305C\")\r\n    IITPlaylistCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Count( \r\n            /* [retval][out] */ long *count) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Item( \r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByName( \r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum( \r\n            /* [retval][out] */ IUnknown **iEnumerator) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ItemByPersistentID( \r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITPlaylistCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITPlaylistCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITPlaylistCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITPlaylistCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )( \r\n            IITPlaylistCollection * This,\r\n            /* [retval][out] */ long *count);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Item )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ long index,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByName )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ BSTR name,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][restricted][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )( \r\n            IITPlaylistCollection * This,\r\n            /* [retval][out] */ IUnknown **iEnumerator);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ItemByPersistentID )( \r\n            IITPlaylistCollection * This,\r\n            /* [in] */ long highID,\r\n            /* [in] */ long lowID,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        END_INTERFACE\r\n    } IITPlaylistCollectionVtbl;\r\n\r\n    interface IITPlaylistCollection\r\n    {\r\n        CONST_VTBL struct IITPlaylistCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITPlaylistCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITPlaylistCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITPlaylistCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITPlaylistCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITPlaylistCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITPlaylistCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITPlaylistCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITPlaylistCollection_get_Count(This,count)\t\\\r\n    (This)->lpVtbl -> get_Count(This,count)\r\n\r\n#define IITPlaylistCollection_get_Item(This,index,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_Item(This,index,iPlaylist)\r\n\r\n#define IITPlaylistCollection_get_ItemByName(This,name,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_ItemByName(This,name,iPlaylist)\r\n\r\n#define IITPlaylistCollection_get__NewEnum(This,iEnumerator)\t\\\r\n    (This)->lpVtbl -> get__NewEnum(This,iEnumerator)\r\n\r\n#define IITPlaylistCollection_get_ItemByPersistentID(This,highID,lowID,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_ItemByPersistentID(This,highID,lowID,iPlaylist)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistCollection_get_Count_Proxy( \r\n    IITPlaylistCollection * This,\r\n    /* [retval][out] */ long *count);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistCollection_get_Count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistCollection_get_Item_Proxy( \r\n    IITPlaylistCollection * This,\r\n    /* [in] */ long index,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistCollection_get_Item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistCollection_get_ItemByName_Proxy( \r\n    IITPlaylistCollection * This,\r\n    /* [in] */ BSTR name,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistCollection_get_ItemByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][restricted][id][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistCollection_get__NewEnum_Proxy( \r\n    IITPlaylistCollection * This,\r\n    /* [retval][out] */ IUnknown **iEnumerator);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistCollection_get__NewEnum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistCollection_get_ItemByPersistentID_Proxy( \r\n    IITPlaylistCollection * This,\r\n    /* [in] */ long highID,\r\n    /* [in] */ long lowID,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistCollection_get_ItemByPersistentID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITPlaylistCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITIPodSource_INTERFACE_DEFINED__\r\n#define __IITIPodSource_INTERFACE_DEFINED__\r\n\r\n/* interface IITIPodSource */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITIPodSource;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"CF4D8ACE-1720-4fb9-B0AE-9877249E89B0\")\r\n    IITIPodSource : public IITSource\r\n    {\r\n    public:\r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdateIPod( void) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE EjectIPod( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SoftwareVersion( \r\n            /* [retval][out] */ BSTR *softwareVersion) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITIPodSourceVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITIPodSource * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITIPodSource * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITIPodSource * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITIPodSource * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITIPodSource * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITIPodSource * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITIPodSource * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITIPodSource * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITIPodSource * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ ITSourceKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Capacity )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ double *capacity);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FreeSpace )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ double *freespace);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlists )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdateIPod )( \r\n            IITIPodSource * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *EjectIPod )( \r\n            IITIPodSource * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SoftwareVersion )( \r\n            IITIPodSource * This,\r\n            /* [retval][out] */ BSTR *softwareVersion);\r\n        \r\n        END_INTERFACE\r\n    } IITIPodSourceVtbl;\r\n\r\n    interface IITIPodSource\r\n    {\r\n        CONST_VTBL struct IITIPodSourceVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITIPodSource_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITIPodSource_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITIPodSource_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITIPodSource_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITIPodSource_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITIPodSource_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITIPodSource_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITIPodSource_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITIPodSource_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITIPodSource_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITIPodSource_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITIPodSource_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITIPodSource_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITIPodSource_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITIPodSource_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITIPodSource_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITIPodSource_get_Capacity(This,capacity)\t\\\r\n    (This)->lpVtbl -> get_Capacity(This,capacity)\r\n\r\n#define IITIPodSource_get_FreeSpace(This,freespace)\t\\\r\n    (This)->lpVtbl -> get_FreeSpace(This,freespace)\r\n\r\n#define IITIPodSource_get_Playlists(This,iPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_Playlists(This,iPlaylistCollection)\r\n\r\n\r\n#define IITIPodSource_UpdateIPod(This)\t\\\r\n    (This)->lpVtbl -> UpdateIPod(This)\r\n\r\n#define IITIPodSource_EjectIPod(This)\t\\\r\n    (This)->lpVtbl -> EjectIPod(This)\r\n\r\n#define IITIPodSource_get_SoftwareVersion(This,softwareVersion)\t\\\r\n    (This)->lpVtbl -> get_SoftwareVersion(This,softwareVersion)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITIPodSource_UpdateIPod_Proxy( \r\n    IITIPodSource * This);\r\n\r\n\r\nvoid __RPC_STUB IITIPodSource_UpdateIPod_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITIPodSource_EjectIPod_Proxy( \r\n    IITIPodSource * This);\r\n\r\n\r\nvoid __RPC_STUB IITIPodSource_EjectIPod_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITIPodSource_get_SoftwareVersion_Proxy( \r\n    IITIPodSource * This,\r\n    /* [retval][out] */ BSTR *softwareVersion);\r\n\r\n\r\nvoid __RPC_STUB IITIPodSource_get_SoftwareVersion_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITIPodSource_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITFileOrCDTrack_INTERFACE_DEFINED__\r\n#define __IITFileOrCDTrack_INTERFACE_DEFINED__\r\n\r\n/* interface IITFileOrCDTrack */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITFileOrCDTrack;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"00D7FE99-7868-4cc7-AD9E-ACFD70D09566\")\r\n    IITFileOrCDTrack : public IITTrack\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Location( \r\n            /* [retval][out] */ BSTR *location) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdateInfoFromFile( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Podcast( \r\n            /* [retval][out] */ VARIANT_BOOL *isPodcast) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE UpdatePodcastFeed( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_RememberBookmark( \r\n            /* [retval][out] */ VARIANT_BOOL *rememberBookmark) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_RememberBookmark( \r\n            /* [in] */ VARIANT_BOOL shouldRememberBookmark) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_ExcludeFromShuffle( \r\n            /* [retval][out] */ VARIANT_BOOL *excludeFromShuffle) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_ExcludeFromShuffle( \r\n            /* [in] */ VARIANT_BOOL shouldExcludeFromShuffle) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Lyrics( \r\n            /* [retval][out] */ BSTR *lyrics) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Lyrics( \r\n            /* [in] */ BSTR lyrics) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Category( \r\n            /* [retval][out] */ BSTR *category) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Category( \r\n            /* [in] */ BSTR category) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Description( \r\n            /* [retval][out] */ BSTR *description) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Description( \r\n            /* [in] */ BSTR description) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_LongDescription( \r\n            /* [retval][out] */ BSTR *longDescription) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_LongDescription( \r\n            /* [in] */ BSTR longDescription) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_BookmarkTime( \r\n            /* [retval][out] */ long *bookmarkTime) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_BookmarkTime( \r\n            /* [in] */ long bookmarkTime) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_VideoKind( \r\n            /* [retval][out] */ ITVideoKind *videoKind) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_VideoKind( \r\n            /* [in] */ ITVideoKind videoKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SkippedCount( \r\n            /* [retval][out] */ long *skippedCount) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SkippedCount( \r\n            /* [in] */ long skippedCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SkippedDate( \r\n            /* [retval][out] */ DATE *skippedDate) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SkippedDate( \r\n            /* [in] */ DATE skippedDate) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_PartOfGaplessAlbum( \r\n            /* [retval][out] */ VARIANT_BOOL *partOfGaplessAlbum) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_PartOfGaplessAlbum( \r\n            /* [in] */ VARIANT_BOOL shouldBePartOfGaplessAlbum) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AlbumArtist( \r\n            /* [retval][out] */ BSTR *albumArtist) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_AlbumArtist( \r\n            /* [in] */ BSTR albumArtist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Show( \r\n            /* [retval][out] */ BSTR *showName) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Show( \r\n            /* [in] */ BSTR showName) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SeasonNumber( \r\n            /* [retval][out] */ long *seasonNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SeasonNumber( \r\n            /* [in] */ long seasonNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EpisodeID( \r\n            /* [retval][out] */ BSTR *episodeID) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_EpisodeID( \r\n            /* [in] */ BSTR episodeID) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_EpisodeNumber( \r\n            /* [retval][out] */ long *episodeNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_EpisodeNumber( \r\n            /* [in] */ long episodeNumber) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Size64High( \r\n            /* [retval][out] */ long *sizeHigh) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Size64Low( \r\n            /* [retval][out] */ long *sizeLow) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Unplayed( \r\n            /* [retval][out] */ VARIANT_BOOL *isUnplayed) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_Unplayed( \r\n            /* [in] */ VARIANT_BOOL shouldBeUnplayed) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortAlbum( \r\n            /* [retval][out] */ BSTR *album) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortAlbum( \r\n            /* [in] */ BSTR album) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortAlbumArtist( \r\n            /* [retval][out] */ BSTR *albumArtist) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortAlbumArtist( \r\n            /* [in] */ BSTR albumArtist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortArtist( \r\n            /* [retval][out] */ BSTR *artist) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortArtist( \r\n            /* [in] */ BSTR artist) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortComposer( \r\n            /* [retval][out] */ BSTR *composer) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortComposer( \r\n            /* [in] */ BSTR composer) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortName( \r\n            /* [retval][out] */ BSTR *name) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortName( \r\n            /* [in] */ BSTR name) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SortShow( \r\n            /* [retval][out] */ BSTR *showName) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_SortShow( \r\n            /* [in] */ BSTR showName) = 0;\r\n        \r\n        virtual /* [helpstring] */ HRESULT STDMETHODCALLTYPE Reveal( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AlbumRating( \r\n            /* [retval][out] */ long *rating) = 0;\r\n        \r\n        virtual /* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE put_AlbumRating( \r\n            /* [in] */ long rating) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_AlbumRatingKind( \r\n            /* [retval][out] */ ITRatingKind *ratingKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_RatingKind( \r\n            /* [retval][out] */ ITRatingKind *ratingKind) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Playlists( \r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITFileOrCDTrackVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *GetITObjectIDs )( \r\n            IITFileOrCDTrack * This,\r\n            /* [out] */ long *sourceID,\r\n            /* [out] */ long *playlistID,\r\n            /* [out] */ long *trackID,\r\n            /* [out] */ long *databaseID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Name )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Index )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SourceID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *sourceID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlaylistID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *playlistID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *trackID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackDatabaseID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *databaseID);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Delete )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Play )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *AddArtworkFromFile )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR filePath,\r\n            /* [retval][out] */ IITArtwork **iArtwork);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ ITTrackKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Album )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *album);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Album )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR album);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *artist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Artist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR artist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BitRate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *bitrate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BPM )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *beatsPerMinute);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BPM )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long beatsPerMinute);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Comment )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *comment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Comment )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR comment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Compilation )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isCompilation);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Compilation )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeCompilation);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Composer )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *composer);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Composer )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR composer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DateAdded )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ DATE *dateAdded);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *discCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long discCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_DiscNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *discNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_DiscNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long discNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Duration )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *duration);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Enabled )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isEnabled);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Enabled )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeEnabled);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EQ )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EQ )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR eq);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Finish )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Finish )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *finish);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Genre )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *genre);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Genre )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR genre);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Grouping )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *grouping);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Grouping )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR grouping);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_KindAsString )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ModificationDate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ DATE *dateModified);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *playedCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long playedCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayedDate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ DATE *playedDate);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PlayedDate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ DATE playedDate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PlayOrderIndex )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *index);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Rating )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *rating);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Rating )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long rating);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SampleRate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *sampleRate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *size);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Start )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *start);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Start )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long start);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Time )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *time);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *trackCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long trackCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TrackNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *trackNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_TrackNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long trackNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VolumeAdjustment )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *volumeAdjustment);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VolumeAdjustment )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long volumeAdjustment);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Year )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *year);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Year )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long year);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Artwork )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ IITArtworkCollection **iArtworkCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Location )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *location);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdateInfoFromFile )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Podcast )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isPodcast);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *UpdatePodcastFeed )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_RememberBookmark )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *rememberBookmark);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_RememberBookmark )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldRememberBookmark);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_ExcludeFromShuffle )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *excludeFromShuffle);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_ExcludeFromShuffle )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldExcludeFromShuffle);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Lyrics )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *lyrics);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Lyrics )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR lyrics);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Category )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *category);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Category )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR category);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Description )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *description);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Description )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR description);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_LongDescription )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *longDescription);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_LongDescription )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR longDescription);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BookmarkTime )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *bookmarkTime);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_BookmarkTime )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long bookmarkTime);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_VideoKind )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ ITVideoKind *videoKind);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_VideoKind )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ ITVideoKind videoKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SkippedCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *skippedCount);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SkippedCount )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long skippedCount);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SkippedDate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ DATE *skippedDate);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SkippedDate )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ DATE skippedDate);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_PartOfGaplessAlbum )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *partOfGaplessAlbum);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_PartOfGaplessAlbum )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBePartOfGaplessAlbum);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AlbumArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *albumArtist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_AlbumArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR albumArtist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Show )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *showName);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Show )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR showName);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SeasonNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *seasonNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SeasonNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long seasonNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EpisodeID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *episodeID);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EpisodeID )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR episodeID);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_EpisodeNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *episodeNumber);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_EpisodeNumber )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long episodeNumber);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size64High )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *sizeHigh);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Size64Low )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *sizeLow);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Unplayed )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isUnplayed);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Unplayed )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeUnplayed);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortAlbum )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *album);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortAlbum )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR album);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortAlbumArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *albumArtist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortAlbumArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR albumArtist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *artist);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortArtist )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR artist);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortComposer )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *composer);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortComposer )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR composer);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortName )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortName )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SortShow )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ BSTR *showName);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_SortShow )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ BSTR showName);\r\n        \r\n        /* [helpstring] */ HRESULT ( STDMETHODCALLTYPE *Reveal )( \r\n            IITFileOrCDTrack * This);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AlbumRating )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ long *rating);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_AlbumRating )( \r\n            IITFileOrCDTrack * This,\r\n            /* [in] */ long rating);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_AlbumRatingKind )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ ITRatingKind *ratingKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_RatingKind )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ ITRatingKind *ratingKind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlists )( \r\n            IITFileOrCDTrack * This,\r\n            /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n        \r\n        END_INTERFACE\r\n    } IITFileOrCDTrackVtbl;\r\n\r\n    interface IITFileOrCDTrack\r\n    {\r\n        CONST_VTBL struct IITFileOrCDTrackVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITFileOrCDTrack_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITFileOrCDTrack_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITFileOrCDTrack_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITFileOrCDTrack_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITFileOrCDTrack_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITFileOrCDTrack_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITFileOrCDTrack_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITFileOrCDTrack_GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\t\\\r\n    (This)->lpVtbl -> GetITObjectIDs(This,sourceID,playlistID,trackID,databaseID)\r\n\r\n#define IITFileOrCDTrack_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITFileOrCDTrack_put_Name(This,name)\t\\\r\n    (This)->lpVtbl -> put_Name(This,name)\r\n\r\n#define IITFileOrCDTrack_get_Index(This,index)\t\\\r\n    (This)->lpVtbl -> get_Index(This,index)\r\n\r\n#define IITFileOrCDTrack_get_SourceID(This,sourceID)\t\\\r\n    (This)->lpVtbl -> get_SourceID(This,sourceID)\r\n\r\n#define IITFileOrCDTrack_get_PlaylistID(This,playlistID)\t\\\r\n    (This)->lpVtbl -> get_PlaylistID(This,playlistID)\r\n\r\n#define IITFileOrCDTrack_get_TrackID(This,trackID)\t\\\r\n    (This)->lpVtbl -> get_TrackID(This,trackID)\r\n\r\n#define IITFileOrCDTrack_get_TrackDatabaseID(This,databaseID)\t\\\r\n    (This)->lpVtbl -> get_TrackDatabaseID(This,databaseID)\r\n\r\n\r\n#define IITFileOrCDTrack_Delete(This)\t\\\r\n    (This)->lpVtbl -> Delete(This)\r\n\r\n#define IITFileOrCDTrack_Play(This)\t\\\r\n    (This)->lpVtbl -> Play(This)\r\n\r\n#define IITFileOrCDTrack_AddArtworkFromFile(This,filePath,iArtwork)\t\\\r\n    (This)->lpVtbl -> AddArtworkFromFile(This,filePath,iArtwork)\r\n\r\n#define IITFileOrCDTrack_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITFileOrCDTrack_get_Playlist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_Playlist(This,iPlaylist)\r\n\r\n#define IITFileOrCDTrack_get_Album(This,album)\t\\\r\n    (This)->lpVtbl -> get_Album(This,album)\r\n\r\n#define IITFileOrCDTrack_put_Album(This,album)\t\\\r\n    (This)->lpVtbl -> put_Album(This,album)\r\n\r\n#define IITFileOrCDTrack_get_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> get_Artist(This,artist)\r\n\r\n#define IITFileOrCDTrack_put_Artist(This,artist)\t\\\r\n    (This)->lpVtbl -> put_Artist(This,artist)\r\n\r\n#define IITFileOrCDTrack_get_BitRate(This,bitrate)\t\\\r\n    (This)->lpVtbl -> get_BitRate(This,bitrate)\r\n\r\n#define IITFileOrCDTrack_get_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> get_BPM(This,beatsPerMinute)\r\n\r\n#define IITFileOrCDTrack_put_BPM(This,beatsPerMinute)\t\\\r\n    (This)->lpVtbl -> put_BPM(This,beatsPerMinute)\r\n\r\n#define IITFileOrCDTrack_get_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> get_Comment(This,comment)\r\n\r\n#define IITFileOrCDTrack_put_Comment(This,comment)\t\\\r\n    (This)->lpVtbl -> put_Comment(This,comment)\r\n\r\n#define IITFileOrCDTrack_get_Compilation(This,isCompilation)\t\\\r\n    (This)->lpVtbl -> get_Compilation(This,isCompilation)\r\n\r\n#define IITFileOrCDTrack_put_Compilation(This,shouldBeCompilation)\t\\\r\n    (This)->lpVtbl -> put_Compilation(This,shouldBeCompilation)\r\n\r\n#define IITFileOrCDTrack_get_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> get_Composer(This,composer)\r\n\r\n#define IITFileOrCDTrack_put_Composer(This,composer)\t\\\r\n    (This)->lpVtbl -> put_Composer(This,composer)\r\n\r\n#define IITFileOrCDTrack_get_DateAdded(This,dateAdded)\t\\\r\n    (This)->lpVtbl -> get_DateAdded(This,dateAdded)\r\n\r\n#define IITFileOrCDTrack_get_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> get_DiscCount(This,discCount)\r\n\r\n#define IITFileOrCDTrack_put_DiscCount(This,discCount)\t\\\r\n    (This)->lpVtbl -> put_DiscCount(This,discCount)\r\n\r\n#define IITFileOrCDTrack_get_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> get_DiscNumber(This,discNumber)\r\n\r\n#define IITFileOrCDTrack_put_DiscNumber(This,discNumber)\t\\\r\n    (This)->lpVtbl -> put_DiscNumber(This,discNumber)\r\n\r\n#define IITFileOrCDTrack_get_Duration(This,duration)\t\\\r\n    (This)->lpVtbl -> get_Duration(This,duration)\r\n\r\n#define IITFileOrCDTrack_get_Enabled(This,isEnabled)\t\\\r\n    (This)->lpVtbl -> get_Enabled(This,isEnabled)\r\n\r\n#define IITFileOrCDTrack_put_Enabled(This,shouldBeEnabled)\t\\\r\n    (This)->lpVtbl -> put_Enabled(This,shouldBeEnabled)\r\n\r\n#define IITFileOrCDTrack_get_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> get_EQ(This,eq)\r\n\r\n#define IITFileOrCDTrack_put_EQ(This,eq)\t\\\r\n    (This)->lpVtbl -> put_EQ(This,eq)\r\n\r\n#define IITFileOrCDTrack_put_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> put_Finish(This,finish)\r\n\r\n#define IITFileOrCDTrack_get_Finish(This,finish)\t\\\r\n    (This)->lpVtbl -> get_Finish(This,finish)\r\n\r\n#define IITFileOrCDTrack_get_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> get_Genre(This,genre)\r\n\r\n#define IITFileOrCDTrack_put_Genre(This,genre)\t\\\r\n    (This)->lpVtbl -> put_Genre(This,genre)\r\n\r\n#define IITFileOrCDTrack_get_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> get_Grouping(This,grouping)\r\n\r\n#define IITFileOrCDTrack_put_Grouping(This,grouping)\t\\\r\n    (This)->lpVtbl -> put_Grouping(This,grouping)\r\n\r\n#define IITFileOrCDTrack_get_KindAsString(This,kind)\t\\\r\n    (This)->lpVtbl -> get_KindAsString(This,kind)\r\n\r\n#define IITFileOrCDTrack_get_ModificationDate(This,dateModified)\t\\\r\n    (This)->lpVtbl -> get_ModificationDate(This,dateModified)\r\n\r\n#define IITFileOrCDTrack_get_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> get_PlayedCount(This,playedCount)\r\n\r\n#define IITFileOrCDTrack_put_PlayedCount(This,playedCount)\t\\\r\n    (This)->lpVtbl -> put_PlayedCount(This,playedCount)\r\n\r\n#define IITFileOrCDTrack_get_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> get_PlayedDate(This,playedDate)\r\n\r\n#define IITFileOrCDTrack_put_PlayedDate(This,playedDate)\t\\\r\n    (This)->lpVtbl -> put_PlayedDate(This,playedDate)\r\n\r\n#define IITFileOrCDTrack_get_PlayOrderIndex(This,index)\t\\\r\n    (This)->lpVtbl -> get_PlayOrderIndex(This,index)\r\n\r\n#define IITFileOrCDTrack_get_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> get_Rating(This,rating)\r\n\r\n#define IITFileOrCDTrack_put_Rating(This,rating)\t\\\r\n    (This)->lpVtbl -> put_Rating(This,rating)\r\n\r\n#define IITFileOrCDTrack_get_SampleRate(This,sampleRate)\t\\\r\n    (This)->lpVtbl -> get_SampleRate(This,sampleRate)\r\n\r\n#define IITFileOrCDTrack_get_Size(This,size)\t\\\r\n    (This)->lpVtbl -> get_Size(This,size)\r\n\r\n#define IITFileOrCDTrack_get_Start(This,start)\t\\\r\n    (This)->lpVtbl -> get_Start(This,start)\r\n\r\n#define IITFileOrCDTrack_put_Start(This,start)\t\\\r\n    (This)->lpVtbl -> put_Start(This,start)\r\n\r\n#define IITFileOrCDTrack_get_Time(This,time)\t\\\r\n    (This)->lpVtbl -> get_Time(This,time)\r\n\r\n#define IITFileOrCDTrack_get_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> get_TrackCount(This,trackCount)\r\n\r\n#define IITFileOrCDTrack_put_TrackCount(This,trackCount)\t\\\r\n    (This)->lpVtbl -> put_TrackCount(This,trackCount)\r\n\r\n#define IITFileOrCDTrack_get_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> get_TrackNumber(This,trackNumber)\r\n\r\n#define IITFileOrCDTrack_put_TrackNumber(This,trackNumber)\t\\\r\n    (This)->lpVtbl -> put_TrackNumber(This,trackNumber)\r\n\r\n#define IITFileOrCDTrack_get_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> get_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITFileOrCDTrack_put_VolumeAdjustment(This,volumeAdjustment)\t\\\r\n    (This)->lpVtbl -> put_VolumeAdjustment(This,volumeAdjustment)\r\n\r\n#define IITFileOrCDTrack_get_Year(This,year)\t\\\r\n    (This)->lpVtbl -> get_Year(This,year)\r\n\r\n#define IITFileOrCDTrack_put_Year(This,year)\t\\\r\n    (This)->lpVtbl -> put_Year(This,year)\r\n\r\n#define IITFileOrCDTrack_get_Artwork(This,iArtworkCollection)\t\\\r\n    (This)->lpVtbl -> get_Artwork(This,iArtworkCollection)\r\n\r\n\r\n#define IITFileOrCDTrack_get_Location(This,location)\t\\\r\n    (This)->lpVtbl -> get_Location(This,location)\r\n\r\n#define IITFileOrCDTrack_UpdateInfoFromFile(This)\t\\\r\n    (This)->lpVtbl -> UpdateInfoFromFile(This)\r\n\r\n#define IITFileOrCDTrack_get_Podcast(This,isPodcast)\t\\\r\n    (This)->lpVtbl -> get_Podcast(This,isPodcast)\r\n\r\n#define IITFileOrCDTrack_UpdatePodcastFeed(This)\t\\\r\n    (This)->lpVtbl -> UpdatePodcastFeed(This)\r\n\r\n#define IITFileOrCDTrack_get_RememberBookmark(This,rememberBookmark)\t\\\r\n    (This)->lpVtbl -> get_RememberBookmark(This,rememberBookmark)\r\n\r\n#define IITFileOrCDTrack_put_RememberBookmark(This,shouldRememberBookmark)\t\\\r\n    (This)->lpVtbl -> put_RememberBookmark(This,shouldRememberBookmark)\r\n\r\n#define IITFileOrCDTrack_get_ExcludeFromShuffle(This,excludeFromShuffle)\t\\\r\n    (This)->lpVtbl -> get_ExcludeFromShuffle(This,excludeFromShuffle)\r\n\r\n#define IITFileOrCDTrack_put_ExcludeFromShuffle(This,shouldExcludeFromShuffle)\t\\\r\n    (This)->lpVtbl -> put_ExcludeFromShuffle(This,shouldExcludeFromShuffle)\r\n\r\n#define IITFileOrCDTrack_get_Lyrics(This,lyrics)\t\\\r\n    (This)->lpVtbl -> get_Lyrics(This,lyrics)\r\n\r\n#define IITFileOrCDTrack_put_Lyrics(This,lyrics)\t\\\r\n    (This)->lpVtbl -> put_Lyrics(This,lyrics)\r\n\r\n#define IITFileOrCDTrack_get_Category(This,category)\t\\\r\n    (This)->lpVtbl -> get_Category(This,category)\r\n\r\n#define IITFileOrCDTrack_put_Category(This,category)\t\\\r\n    (This)->lpVtbl -> put_Category(This,category)\r\n\r\n#define IITFileOrCDTrack_get_Description(This,description)\t\\\r\n    (This)->lpVtbl -> get_Description(This,description)\r\n\r\n#define IITFileOrCDTrack_put_Description(This,description)\t\\\r\n    (This)->lpVtbl -> put_Description(This,description)\r\n\r\n#define IITFileOrCDTrack_get_LongDescription(This,longDescription)\t\\\r\n    (This)->lpVtbl -> get_LongDescription(This,longDescription)\r\n\r\n#define IITFileOrCDTrack_put_LongDescription(This,longDescription)\t\\\r\n    (This)->lpVtbl -> put_LongDescription(This,longDescription)\r\n\r\n#define IITFileOrCDTrack_get_BookmarkTime(This,bookmarkTime)\t\\\r\n    (This)->lpVtbl -> get_BookmarkTime(This,bookmarkTime)\r\n\r\n#define IITFileOrCDTrack_put_BookmarkTime(This,bookmarkTime)\t\\\r\n    (This)->lpVtbl -> put_BookmarkTime(This,bookmarkTime)\r\n\r\n#define IITFileOrCDTrack_get_VideoKind(This,videoKind)\t\\\r\n    (This)->lpVtbl -> get_VideoKind(This,videoKind)\r\n\r\n#define IITFileOrCDTrack_put_VideoKind(This,videoKind)\t\\\r\n    (This)->lpVtbl -> put_VideoKind(This,videoKind)\r\n\r\n#define IITFileOrCDTrack_get_SkippedCount(This,skippedCount)\t\\\r\n    (This)->lpVtbl -> get_SkippedCount(This,skippedCount)\r\n\r\n#define IITFileOrCDTrack_put_SkippedCount(This,skippedCount)\t\\\r\n    (This)->lpVtbl -> put_SkippedCount(This,skippedCount)\r\n\r\n#define IITFileOrCDTrack_get_SkippedDate(This,skippedDate)\t\\\r\n    (This)->lpVtbl -> get_SkippedDate(This,skippedDate)\r\n\r\n#define IITFileOrCDTrack_put_SkippedDate(This,skippedDate)\t\\\r\n    (This)->lpVtbl -> put_SkippedDate(This,skippedDate)\r\n\r\n#define IITFileOrCDTrack_get_PartOfGaplessAlbum(This,partOfGaplessAlbum)\t\\\r\n    (This)->lpVtbl -> get_PartOfGaplessAlbum(This,partOfGaplessAlbum)\r\n\r\n#define IITFileOrCDTrack_put_PartOfGaplessAlbum(This,shouldBePartOfGaplessAlbum)\t\\\r\n    (This)->lpVtbl -> put_PartOfGaplessAlbum(This,shouldBePartOfGaplessAlbum)\r\n\r\n#define IITFileOrCDTrack_get_AlbumArtist(This,albumArtist)\t\\\r\n    (This)->lpVtbl -> get_AlbumArtist(This,albumArtist)\r\n\r\n#define IITFileOrCDTrack_put_AlbumArtist(This,albumArtist)\t\\\r\n    (This)->lpVtbl -> put_AlbumArtist(This,albumArtist)\r\n\r\n#define IITFileOrCDTrack_get_Show(This,showName)\t\\\r\n    (This)->lpVtbl -> get_Show(This,showName)\r\n\r\n#define IITFileOrCDTrack_put_Show(This,showName)\t\\\r\n    (This)->lpVtbl -> put_Show(This,showName)\r\n\r\n#define IITFileOrCDTrack_get_SeasonNumber(This,seasonNumber)\t\\\r\n    (This)->lpVtbl -> get_SeasonNumber(This,seasonNumber)\r\n\r\n#define IITFileOrCDTrack_put_SeasonNumber(This,seasonNumber)\t\\\r\n    (This)->lpVtbl -> put_SeasonNumber(This,seasonNumber)\r\n\r\n#define IITFileOrCDTrack_get_EpisodeID(This,episodeID)\t\\\r\n    (This)->lpVtbl -> get_EpisodeID(This,episodeID)\r\n\r\n#define IITFileOrCDTrack_put_EpisodeID(This,episodeID)\t\\\r\n    (This)->lpVtbl -> put_EpisodeID(This,episodeID)\r\n\r\n#define IITFileOrCDTrack_get_EpisodeNumber(This,episodeNumber)\t\\\r\n    (This)->lpVtbl -> get_EpisodeNumber(This,episodeNumber)\r\n\r\n#define IITFileOrCDTrack_put_EpisodeNumber(This,episodeNumber)\t\\\r\n    (This)->lpVtbl -> put_EpisodeNumber(This,episodeNumber)\r\n\r\n#define IITFileOrCDTrack_get_Size64High(This,sizeHigh)\t\\\r\n    (This)->lpVtbl -> get_Size64High(This,sizeHigh)\r\n\r\n#define IITFileOrCDTrack_get_Size64Low(This,sizeLow)\t\\\r\n    (This)->lpVtbl -> get_Size64Low(This,sizeLow)\r\n\r\n#define IITFileOrCDTrack_get_Unplayed(This,isUnplayed)\t\\\r\n    (This)->lpVtbl -> get_Unplayed(This,isUnplayed)\r\n\r\n#define IITFileOrCDTrack_put_Unplayed(This,shouldBeUnplayed)\t\\\r\n    (This)->lpVtbl -> put_Unplayed(This,shouldBeUnplayed)\r\n\r\n#define IITFileOrCDTrack_get_SortAlbum(This,album)\t\\\r\n    (This)->lpVtbl -> get_SortAlbum(This,album)\r\n\r\n#define IITFileOrCDTrack_put_SortAlbum(This,album)\t\\\r\n    (This)->lpVtbl -> put_SortAlbum(This,album)\r\n\r\n#define IITFileOrCDTrack_get_SortAlbumArtist(This,albumArtist)\t\\\r\n    (This)->lpVtbl -> get_SortAlbumArtist(This,albumArtist)\r\n\r\n#define IITFileOrCDTrack_put_SortAlbumArtist(This,albumArtist)\t\\\r\n    (This)->lpVtbl -> put_SortAlbumArtist(This,albumArtist)\r\n\r\n#define IITFileOrCDTrack_get_SortArtist(This,artist)\t\\\r\n    (This)->lpVtbl -> get_SortArtist(This,artist)\r\n\r\n#define IITFileOrCDTrack_put_SortArtist(This,artist)\t\\\r\n    (This)->lpVtbl -> put_SortArtist(This,artist)\r\n\r\n#define IITFileOrCDTrack_get_SortComposer(This,composer)\t\\\r\n    (This)->lpVtbl -> get_SortComposer(This,composer)\r\n\r\n#define IITFileOrCDTrack_put_SortComposer(This,composer)\t\\\r\n    (This)->lpVtbl -> put_SortComposer(This,composer)\r\n\r\n#define IITFileOrCDTrack_get_SortName(This,name)\t\\\r\n    (This)->lpVtbl -> get_SortName(This,name)\r\n\r\n#define IITFileOrCDTrack_put_SortName(This,name)\t\\\r\n    (This)->lpVtbl -> put_SortName(This,name)\r\n\r\n#define IITFileOrCDTrack_get_SortShow(This,showName)\t\\\r\n    (This)->lpVtbl -> get_SortShow(This,showName)\r\n\r\n#define IITFileOrCDTrack_put_SortShow(This,showName)\t\\\r\n    (This)->lpVtbl -> put_SortShow(This,showName)\r\n\r\n#define IITFileOrCDTrack_Reveal(This)\t\\\r\n    (This)->lpVtbl -> Reveal(This)\r\n\r\n#define IITFileOrCDTrack_get_AlbumRating(This,rating)\t\\\r\n    (This)->lpVtbl -> get_AlbumRating(This,rating)\r\n\r\n#define IITFileOrCDTrack_put_AlbumRating(This,rating)\t\\\r\n    (This)->lpVtbl -> put_AlbumRating(This,rating)\r\n\r\n#define IITFileOrCDTrack_get_AlbumRatingKind(This,ratingKind)\t\\\r\n    (This)->lpVtbl -> get_AlbumRatingKind(This,ratingKind)\r\n\r\n#define IITFileOrCDTrack_get_RatingKind(This,ratingKind)\t\\\r\n    (This)->lpVtbl -> get_RatingKind(This,ratingKind)\r\n\r\n#define IITFileOrCDTrack_get_Playlists(This,iPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_Playlists(This,iPlaylistCollection)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Location_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *location);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Location_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_UpdateInfoFromFile_Proxy( \r\n    IITFileOrCDTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_UpdateInfoFromFile_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Podcast_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isPodcast);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Podcast_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_UpdatePodcastFeed_Proxy( \r\n    IITFileOrCDTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_UpdatePodcastFeed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_RememberBookmark_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *rememberBookmark);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_RememberBookmark_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_RememberBookmark_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldRememberBookmark);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_RememberBookmark_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_ExcludeFromShuffle_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *excludeFromShuffle);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_ExcludeFromShuffle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_ExcludeFromShuffle_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldExcludeFromShuffle);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_ExcludeFromShuffle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Lyrics_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *lyrics);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Lyrics_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_Lyrics_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR lyrics);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_Lyrics_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Category_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *category);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Category_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_Category_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR category);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_Category_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Description_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *description);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_Description_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR description);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_Description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_LongDescription_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *longDescription);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_LongDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_LongDescription_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR longDescription);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_LongDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_BookmarkTime_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *bookmarkTime);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_BookmarkTime_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_BookmarkTime_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ long bookmarkTime);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_BookmarkTime_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_VideoKind_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ ITVideoKind *videoKind);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_VideoKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_VideoKind_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ ITVideoKind videoKind);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_VideoKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SkippedCount_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *skippedCount);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SkippedCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SkippedCount_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ long skippedCount);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SkippedCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SkippedDate_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ DATE *skippedDate);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SkippedDate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SkippedDate_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ DATE skippedDate);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SkippedDate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_PartOfGaplessAlbum_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *partOfGaplessAlbum);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_PartOfGaplessAlbum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_PartOfGaplessAlbum_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldBePartOfGaplessAlbum);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_PartOfGaplessAlbum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_AlbumArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *albumArtist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_AlbumArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_AlbumArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR albumArtist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_AlbumArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Show_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *showName);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Show_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_Show_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR showName);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_Show_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SeasonNumber_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *seasonNumber);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SeasonNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SeasonNumber_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ long seasonNumber);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SeasonNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_EpisodeID_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *episodeID);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_EpisodeID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_EpisodeID_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR episodeID);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_EpisodeID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_EpisodeNumber_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *episodeNumber);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_EpisodeNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_EpisodeNumber_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ long episodeNumber);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_EpisodeNumber_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Size64High_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *sizeHigh);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Size64High_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Size64Low_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *sizeLow);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Size64Low_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Unplayed_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ VARIANT_BOOL *isUnplayed);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Unplayed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_Unplayed_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ VARIANT_BOOL shouldBeUnplayed);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_Unplayed_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortAlbum_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *album);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortAlbum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortAlbum_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR album);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortAlbum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortAlbumArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *albumArtist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortAlbumArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortAlbumArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR albumArtist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortAlbumArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *artist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortArtist_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR artist);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortArtist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortComposer_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *composer);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortComposer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortComposer_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR composer);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortComposer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortName_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *name);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortName_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR name);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_SortShow_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ BSTR *showName);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_SortShow_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_SortShow_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ BSTR showName);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_SortShow_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_Reveal_Proxy( \r\n    IITFileOrCDTrack * This);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_Reveal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_AlbumRating_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ long *rating);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_AlbumRating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_put_AlbumRating_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [in] */ long rating);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_put_AlbumRating_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_AlbumRatingKind_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ ITRatingKind *ratingKind);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_AlbumRatingKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_RatingKind_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ ITRatingKind *ratingKind);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_RatingKind_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITFileOrCDTrack_get_Playlists_Proxy( \r\n    IITFileOrCDTrack * This,\r\n    /* [retval][out] */ IITPlaylistCollection **iPlaylistCollection);\r\n\r\n\r\nvoid __RPC_STUB IITFileOrCDTrack_get_Playlists_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITFileOrCDTrack_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IITPlaylistWindow_INTERFACE_DEFINED__\r\n#define __IITPlaylistWindow_INTERFACE_DEFINED__\r\n\r\n/* interface IITPlaylistWindow */\r\n/* [hidden][unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IITPlaylistWindow;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"349CBB45-2E5A-4822-8E4A-A75555A186F7\")\r\n    IITPlaylistWindow : public IITWindow\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_SelectedTracks( \r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE get_Playlist( \r\n            /* [retval][out] */ IITPlaylist **iPlaylist) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IITPlaylistWindowVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IITPlaylistWindow * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IITPlaylistWindow * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IITPlaylistWindow * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Name )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ BSTR *name);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Kind )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ ITWindowKind *kind);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Visible )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isVisible);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Visible )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeVisible);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Resizable )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isResizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Minimized )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMinimized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Minimized )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMinimized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximizable )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximizable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Maximized )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isMaximized);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Maximized )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeMaximized);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomable )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomable);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Zoomed )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ VARIANT_BOOL *isZoomed);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Zoomed )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ VARIANT_BOOL shouldBeZoomed);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Top )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *top);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Top )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long top);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Left )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *left);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Left )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long left);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Bottom )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *bottom);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Bottom )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long bottom);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Right )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *right);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Right )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long right);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Width )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *width);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Width )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long width);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Height )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ long *height);\r\n        \r\n        /* [helpstring][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Height )( \r\n            IITPlaylistWindow * This,\r\n            /* [in] */ long height);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SelectedTracks )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n        \r\n        /* [helpstring][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Playlist )( \r\n            IITPlaylistWindow * This,\r\n            /* [retval][out] */ IITPlaylist **iPlaylist);\r\n        \r\n        END_INTERFACE\r\n    } IITPlaylistWindowVtbl;\r\n\r\n    interface IITPlaylistWindow\r\n    {\r\n        CONST_VTBL struct IITPlaylistWindowVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IITPlaylistWindow_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IITPlaylistWindow_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IITPlaylistWindow_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IITPlaylistWindow_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IITPlaylistWindow_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IITPlaylistWindow_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IITPlaylistWindow_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IITPlaylistWindow_get_Name(This,name)\t\\\r\n    (This)->lpVtbl -> get_Name(This,name)\r\n\r\n#define IITPlaylistWindow_get_Kind(This,kind)\t\\\r\n    (This)->lpVtbl -> get_Kind(This,kind)\r\n\r\n#define IITPlaylistWindow_get_Visible(This,isVisible)\t\\\r\n    (This)->lpVtbl -> get_Visible(This,isVisible)\r\n\r\n#define IITPlaylistWindow_put_Visible(This,shouldBeVisible)\t\\\r\n    (This)->lpVtbl -> put_Visible(This,shouldBeVisible)\r\n\r\n#define IITPlaylistWindow_get_Resizable(This,isResizable)\t\\\r\n    (This)->lpVtbl -> get_Resizable(This,isResizable)\r\n\r\n#define IITPlaylistWindow_get_Minimized(This,isMinimized)\t\\\r\n    (This)->lpVtbl -> get_Minimized(This,isMinimized)\r\n\r\n#define IITPlaylistWindow_put_Minimized(This,shouldBeMinimized)\t\\\r\n    (This)->lpVtbl -> put_Minimized(This,shouldBeMinimized)\r\n\r\n#define IITPlaylistWindow_get_Maximizable(This,isMaximizable)\t\\\r\n    (This)->lpVtbl -> get_Maximizable(This,isMaximizable)\r\n\r\n#define IITPlaylistWindow_get_Maximized(This,isMaximized)\t\\\r\n    (This)->lpVtbl -> get_Maximized(This,isMaximized)\r\n\r\n#define IITPlaylistWindow_put_Maximized(This,shouldBeMaximized)\t\\\r\n    (This)->lpVtbl -> put_Maximized(This,shouldBeMaximized)\r\n\r\n#define IITPlaylistWindow_get_Zoomable(This,isZoomable)\t\\\r\n    (This)->lpVtbl -> get_Zoomable(This,isZoomable)\r\n\r\n#define IITPlaylistWindow_get_Zoomed(This,isZoomed)\t\\\r\n    (This)->lpVtbl -> get_Zoomed(This,isZoomed)\r\n\r\n#define IITPlaylistWindow_put_Zoomed(This,shouldBeZoomed)\t\\\r\n    (This)->lpVtbl -> put_Zoomed(This,shouldBeZoomed)\r\n\r\n#define IITPlaylistWindow_get_Top(This,top)\t\\\r\n    (This)->lpVtbl -> get_Top(This,top)\r\n\r\n#define IITPlaylistWindow_put_Top(This,top)\t\\\r\n    (This)->lpVtbl -> put_Top(This,top)\r\n\r\n#define IITPlaylistWindow_get_Left(This,left)\t\\\r\n    (This)->lpVtbl -> get_Left(This,left)\r\n\r\n#define IITPlaylistWindow_put_Left(This,left)\t\\\r\n    (This)->lpVtbl -> put_Left(This,left)\r\n\r\n#define IITPlaylistWindow_get_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> get_Bottom(This,bottom)\r\n\r\n#define IITPlaylistWindow_put_Bottom(This,bottom)\t\\\r\n    (This)->lpVtbl -> put_Bottom(This,bottom)\r\n\r\n#define IITPlaylistWindow_get_Right(This,right)\t\\\r\n    (This)->lpVtbl -> get_Right(This,right)\r\n\r\n#define IITPlaylistWindow_put_Right(This,right)\t\\\r\n    (This)->lpVtbl -> put_Right(This,right)\r\n\r\n#define IITPlaylistWindow_get_Width(This,width)\t\\\r\n    (This)->lpVtbl -> get_Width(This,width)\r\n\r\n#define IITPlaylistWindow_put_Width(This,width)\t\\\r\n    (This)->lpVtbl -> put_Width(This,width)\r\n\r\n#define IITPlaylistWindow_get_Height(This,height)\t\\\r\n    (This)->lpVtbl -> get_Height(This,height)\r\n\r\n#define IITPlaylistWindow_put_Height(This,height)\t\\\r\n    (This)->lpVtbl -> put_Height(This,height)\r\n\r\n\r\n#define IITPlaylistWindow_get_SelectedTracks(This,iTrackCollection)\t\\\r\n    (This)->lpVtbl -> get_SelectedTracks(This,iTrackCollection)\r\n\r\n#define IITPlaylistWindow_get_Playlist(This,iPlaylist)\t\\\r\n    (This)->lpVtbl -> get_Playlist(This,iPlaylist)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistWindow_get_SelectedTracks_Proxy( \r\n    IITPlaylistWindow * This,\r\n    /* [retval][out] */ IITTrackCollection **iTrackCollection);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistWindow_get_SelectedTracks_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget] */ HRESULT STDMETHODCALLTYPE IITPlaylistWindow_get_Playlist_Proxy( \r\n    IITPlaylistWindow * This,\r\n    /* [retval][out] */ IITPlaylist **iPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IITPlaylistWindow_get_Playlist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IITPlaylistWindow_INTERFACE_DEFINED__ */\r\n\r\n#endif /* __iTunesLib_LIBRARY_DEFINED__ */\r\n\r\n/* Additional Prototypes for ALL interfaces */\r\n\r\n/* end of Additional Prototypes */\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n\r\n\r\n"
  },
  {
    "path": "lib/3rdparty/iTunesCOMAPI/iTunesCOMInterface_i.c",
    "content": "\r\n\r\n/* this ALWAYS GENERATED file contains the IIDs and CLSIDs */\r\n\r\n/* link this file in with the server and any clients */\r\n\r\n\r\n /* File created by MIDL compiler version 6.00.0366 */\r\n/* at Wed Jun 25 17:02:20 2008\r\n */\r\n/* Compiler settings for iTunesCOMInterface.idl:\r\n    Oicf, W1, Zp8, env=Win32 (32b run)\r\n    protocol : dce , ms_ext, c_ext, robust\r\n    error checks: allocation ref bounds_check enum stub_data \r\n    VC __declspec() decoration level: \r\n         __declspec(uuid()), __declspec(selectany), __declspec(novtable)\r\n         DECLSPEC_UUID(), MIDL_INTERFACE()\r\n*/\r\n//@@MIDL_FILE_HEADING(  )\r\n\r\n#pragma warning( disable: 4049 )  /* more than 64k source lines */\r\n\r\n\r\n#ifdef __cplusplus\r\nextern \"C\"{\r\n#endif \r\n\r\n\r\n#include <rpc.h>\r\n#include <rpcndr.h>\r\n\r\n#ifdef _MIDL_USE_GUIDDEF_\r\n\r\n#ifndef INITGUID\r\n#define INITGUID\r\n#include <guiddef.h>\r\n#undef INITGUID\r\n#else\r\n#include <guiddef.h>\r\n#endif\r\n\r\n#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \\\r\n        DEFINE_GUID(name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8)\r\n\r\n#else // !_MIDL_USE_GUIDDEF_\r\n\r\n#ifndef __IID_DEFINED__\r\n#define __IID_DEFINED__\r\n\r\ntypedef struct _IID\r\n{\r\n    unsigned long x;\r\n    unsigned short s1;\r\n    unsigned short s2;\r\n    unsigned char  c[8];\r\n} IID;\r\n\r\n#endif // __IID_DEFINED__\r\n\r\n#ifndef CLSID_DEFINED\r\n#define CLSID_DEFINED\r\ntypedef IID CLSID;\r\n#endif // CLSID_DEFINED\r\n\r\n#define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \\\r\n        const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}\r\n\r\n#endif !_MIDL_USE_GUIDDEF_\r\n\r\nMIDL_DEFINE_GUID(IID, LIBID_iTunesLib,0x9E93C96F,0xCF0D,0x43f6,0x8B,0xA8,0xB8,0x07,0xA3,0x37,0x07,0x12);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITObject,0x9FAB0E27,0x70D7,0x4e3a,0x99,0x65,0xB0,0xC8,0xB8,0x86,0x9B,0xB6);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITSource,0xAEC1C4D3,0xAEF1,0x4255,0xB8,0x92,0x3E,0x3D,0x13,0xAD,0xFD,0xF9);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITSourceCollection,0x2FF6CE20,0xFF87,0x4183,0xB0,0xB3,0xF3,0x23,0xD0,0x47,0xAF,0x41);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITEncoder,0x1CF95A1C,0x55FE,0x4f45,0xA2,0xD3,0x85,0xAC,0x6C,0x50,0x4A,0x73);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITEncoderCollection,0x8862BCA9,0x168D,0x4549,0xA9,0xD5,0xAD,0xB3,0x5E,0x55,0x3B,0xA6);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITEQPreset,0x5BE75F4F,0x68FA,0x4212,0xAC,0xB7,0xBE,0x44,0xEA,0x56,0x97,0x59);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITEQPresetCollection,0xAEF4D111,0x3331,0x48da,0xB0,0xC2,0xB4,0x68,0xD5,0xD6,0x1D,0x08);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITPlaylist,0x3D5E072F,0x2A77,0x4b17,0x9E,0x73,0xE0,0x3B,0x77,0xCC,0xCC,0xA9);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITOperationStatus,0x206479C9,0xFE32,0x4f9b,0xA1,0x8A,0x47,0x5A,0xC9,0x39,0xB4,0x79);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITConvertOperationStatus,0x7063AAF6,0xABA0,0x493b,0xB4,0xFC,0x92,0x0A,0x9F,0x10,0x58,0x75);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITLibraryPlaylist,0x53AE1704,0x491C,0x4289,0x94,0xA0,0x95,0x88,0x15,0x67,0x5A,0x3D);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITUserPlaylist,0x0A504DED,0xA0B5,0x465a,0x8A,0x94,0x50,0xE2,0x0D,0x7D,0xF6,0x92);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITTrack,0x4CB0915D,0x1E54,0x4727,0xBA,0xF3,0xCE,0x6C,0xC9,0xA2,0x25,0xA1);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITTrackCollection,0x755D76F1,0x6B85,0x4ce4,0x8F,0x5F,0xF8,0x8D,0x97,0x43,0xDC,0xD8);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITVisual,0x340F3315,0xED72,0x4c09,0x9A,0xCF,0x21,0xEB,0x4B,0xDF,0x99,0x31);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITVisualCollection,0x88A4CCDD,0x114F,0x4043,0xB6,0x9B,0x84,0xD4,0xE6,0x27,0x49,0x57);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITWindow,0x370D7BE0,0x3A89,0x4a42,0xB9,0x02,0xC7,0x5F,0xC1,0x38,0xBE,0x09);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITBrowserWindow,0xC999F455,0xC4D5,0x4aa4,0x82,0x77,0xF9,0x97,0x53,0x69,0x99,0x74);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITWindowCollection,0x3D8DE381,0x6C0E,0x481f,0xA8,0x65,0xE2,0x38,0x5F,0x59,0xFA,0x43);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IiTunes,0x9DD6680B,0x3EDC,0x40db,0xA7,0x71,0xE6,0xFE,0x48,0x32,0xE3,0x4A);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, DIID__IiTunesEvents,0x5846EB78,0x317E,0x4b6f,0xB0,0xC3,0x11,0xEE,0x8C,0x8F,0xEE,0xF2);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, DIID__IITConvertOperationStatusEvents,0x5C47A705,0x8E8A,0x45a1,0x9E,0xED,0x71,0xC9,0x93,0xF0,0xBF,0x60);\r\n\r\n\r\nMIDL_DEFINE_GUID(CLSID, CLSID_iTunesApp,0xDC0C2640,0x1415,0x4644,0x87,0x5C,0x6F,0x4D,0x76,0x98,0x39,0xBA);\r\n\r\n\r\nMIDL_DEFINE_GUID(CLSID, CLSID_iTunesConvertOperationStatus,0xD06596AD,0xC900,0x41b2,0xBC,0x68,0x1B,0x48,0x64,0x50,0xFC,0x56);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITArtwork,0xD0A6C1F8,0xBF3D,0x4cd8,0xAC,0x47,0xFE,0x32,0xBD,0xD1,0x72,0x57);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITArtworkCollection,0xBF2742D7,0x418C,0x4858,0x9A,0xF9,0x29,0x81,0xB0,0x62,0xD2,0x3E);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITURLTrack,0x1116E3B5,0x29FD,0x4393,0xA7,0xBD,0x45,0x4E,0x5E,0x32,0x79,0x00);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITAudioCDPlaylist,0xCF496DF3,0x0FED,0x4d7d,0x9B,0xD8,0x52,0x9B,0x6E,0x8A,0x08,0x2E);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITPlaylistCollection,0xFF194254,0x909D,0x4437,0x9C,0x50,0x3A,0xAC,0x2A,0xE6,0x30,0x5C);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITIPodSource,0xCF4D8ACE,0x1720,0x4fb9,0xB0,0xAE,0x98,0x77,0x24,0x9E,0x89,0xB0);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITFileOrCDTrack,0x00D7FE99,0x7868,0x4cc7,0xAD,0x9E,0xAC,0xFD,0x70,0xD0,0x95,0x66);\r\n\r\n\r\nMIDL_DEFINE_GUID(IID, IID_IITPlaylistWindow,0x349CBB45,0x2E5A,0x4822,0x8E,0x4A,0xA7,0x55,0x55,0xA1,0x86,0xF7);\r\n\r\n#undef MIDL_DEFINE_GUID\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n\r\n\r\n"
  },
  {
    "path": "lib/3rdparty/mad.h",
    "content": "/*\n * libmad - MPEG audio decoder library\n * Copyright (C) 2000-2004 Underbit Technologies, Inc.\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n *\n * If you would like to negotiate alternate licensing terms, you may do\n * so by contacting: Underbit Technologies, Inc. <info@underbit.com>\n */\n\n# ifdef __cplusplus\nextern \"C\" {\n# endif\n\n# define FPM_INTEL\n\n\n\n# define SIZEOF_INT 4\n# define SIZEOF_LONG 4\n# define SIZEOF_LONG_LONG 8\n\n\n/* Id: version.h,v 1.26 2004/01/23 09:41:33 rob Exp */\n\n# ifndef LIBMAD_VERSION_H\n# define LIBMAD_VERSION_H\n\n# define MAD_VERSION_MAJOR\t0\n# define MAD_VERSION_MINOR\t15\n# define MAD_VERSION_PATCH\t1\n# define MAD_VERSION_EXTRA\t\" (beta)\"\n\n# define MAD_VERSION_STRINGIZE(str)\t#str\n# define MAD_VERSION_STRING(num)\tMAD_VERSION_STRINGIZE(num)\n\n# define MAD_VERSION\t\tMAD_VERSION_STRING(MAD_VERSION_MAJOR) \".\"  \\\n\t\t\t\tMAD_VERSION_STRING(MAD_VERSION_MINOR) \".\"  \\\n\t\t\t\tMAD_VERSION_STRING(MAD_VERSION_PATCH)  \\\n\t\t\t\tMAD_VERSION_EXTRA\n\n# define MAD_PUBLISHYEAR\t\"2000-2004\"\n# define MAD_AUTHOR\t\t\"Underbit Technologies, Inc.\"\n# define MAD_EMAIL\t\t\"info@underbit.com\"\n\nextern char const mad_version[];\nextern char const mad_copyright[];\nextern char const mad_author[];\nextern char const mad_build[];\n\n# endif\n\n/* Id: fixed.h,v 1.38 2004/02/17 02:02:03 rob Exp */\n\n# ifndef LIBMAD_FIXED_H\n# define LIBMAD_FIXED_H\n\n# if SIZEOF_INT >= 4\ntypedef   signed int mad_fixed_t;\n\ntypedef   signed int mad_fixed64hi_t;\ntypedef unsigned int mad_fixed64lo_t;\n# else\ntypedef   signed long mad_fixed_t;\n\ntypedef   signed long mad_fixed64hi_t;\ntypedef unsigned long mad_fixed64lo_t;\n# endif\n\n# if defined(_MSC_VER)\n#  define mad_fixed64_t  signed __int64\n# elif 1 || defined(__GNUC__)\n#  define mad_fixed64_t  signed long long\n# endif\n\n# if defined(FPM_FLOAT)\ntypedef double mad_sample_t;\n# else\ntypedef mad_fixed_t mad_sample_t;\n# endif\n\n/*\n * Fixed-point format: 0xABBBBBBB\n * A == whole part      (sign + 3 bits)\n * B == fractional part (28 bits)\n *\n * Values are signed two's complement, so the effective range is:\n * 0x80000000 to 0x7fffffff\n *       -8.0 to +7.9999999962747097015380859375\n *\n * The smallest representable value is:\n * 0x00000001 == 0.0000000037252902984619140625 (i.e. about 3.725e-9)\n *\n * 28 bits of fractional accuracy represent about\n * 8.6 digits of decimal accuracy.\n *\n * Fixed-point numbers can be added or subtracted as normal\n * integers, but multiplication requires shifting the 64-bit result\n * from 56 fractional bits back to 28 (and rounding.)\n *\n * Changing the definition of MAD_F_FRACBITS is only partially\n * supported, and must be done with care.\n */\n\n# define MAD_F_FRACBITS\t\t28\n\n# if MAD_F_FRACBITS == 28\n#  define MAD_F(x)\t\t((mad_fixed_t) (x##L))\n# else\n#  if MAD_F_FRACBITS < 28\n#   warning \"MAD_F_FRACBITS < 28\"\n#   define MAD_F(x)\t\t((mad_fixed_t)  \\\n\t\t\t\t (((x##L) +  \\\n\t\t\t\t   (1L << (28 - MAD_F_FRACBITS - 1))) >>  \\\n\t\t\t\t  (28 - MAD_F_FRACBITS)))\n#  elif MAD_F_FRACBITS > 28\n#   error \"MAD_F_FRACBITS > 28 not currently supported\"\n#   define MAD_F(x)\t\t((mad_fixed_t)  \\\n\t\t\t\t ((x##L) << (MAD_F_FRACBITS - 28)))\n#  endif\n# endif\n\n# define MAD_F_MIN\t\t((mad_fixed_t) -0x80000000L)\n# define MAD_F_MAX\t\t((mad_fixed_t) +0x7fffffffL)\n\n# define MAD_F_ONE\t\tMAD_F(0x10000000)\n\n# define mad_f_tofixed(x)\t((mad_fixed_t)  \\\n\t\t\t\t ((x) * (double) (1L << MAD_F_FRACBITS) + 0.5))\n# define mad_f_todouble(x)\t((double)  \\\n\t\t\t\t ((x) / (double) (1L << MAD_F_FRACBITS)))\n\n# define mad_f_intpart(x)\t((x) >> MAD_F_FRACBITS)\n# define mad_f_fracpart(x)\t((x) & ((1L << MAD_F_FRACBITS) - 1))\n\t\t\t\t/* (x should be positive) */\n\n# define mad_f_fromint(x)\t((x) << MAD_F_FRACBITS)\n\n# define mad_f_add(x, y)\t((x) + (y))\n# define mad_f_sub(x, y)\t((x) - (y))\n\n# if defined(FPM_FLOAT)\n#  error \"FPM_FLOAT not yet supported\"\n\n#  undef MAD_F\n#  define MAD_F(x)\t\tmad_f_todouble(x)\n\n#  define mad_f_mul(x, y)\t((x) * (y))\n#  define mad_f_scale64\n\n#  undef ASO_ZEROCHECK\n\n# elif defined(FPM_64BIT)\n\n/*\n * This version should be the most accurate if 64-bit types are supported by\n * the compiler, although it may not be the most efficient.\n */\n#  if defined(OPT_ACCURACY)\n#   define mad_f_mul(x, y)  \\\n    ((mad_fixed_t)  \\\n     ((((mad_fixed64_t) (x) * (y)) +  \\\n       (1L << (MAD_F_SCALEBITS - 1))) >> MAD_F_SCALEBITS))\n#  else\n#   define mad_f_mul(x, y)  \\\n    ((mad_fixed_t) (((mad_fixed64_t) (x) * (y)) >> MAD_F_SCALEBITS))\n#  endif\n\n#  define MAD_F_SCALEBITS  MAD_F_FRACBITS\n\n/* --- Intel --------------------------------------------------------------- */\n\n# elif defined(FPM_INTEL)\n\n#  if defined(_MSC_VER)\n#   pragma warning(push)\n#   pragma warning(disable: 4035)  /* no return value */\nstatic __forceinline\nmad_fixed_t mad_f_mul_inline(mad_fixed_t x, mad_fixed_t y)\n{\n  enum {\n    fracbits = MAD_F_FRACBITS\n  };\n\n  __asm {\n    mov eax, x\n    imul y\n    shrd eax, edx, fracbits\n  }\n\n  /* implicit return of eax */\n}\n#   pragma warning(pop)\n\n#   define mad_f_mul\t\tmad_f_mul_inline\n#   define mad_f_scale64\n#  else\n/*\n * This Intel version is fast and accurate; the disposition of the least\n * significant bit depends on OPT_ACCURACY via mad_f_scale64().\n */\n#   define MAD_F_MLX(hi, lo, x, y)  \\\n    asm (\"imull %3\"  \\\n\t : \"=a\" (lo), \"=d\" (hi)  \\\n\t : \"%a\" (x), \"rm\" (y)  \\\n\t : \"cc\")\n\n#   if defined(OPT_ACCURACY)\n/*\n * This gives best accuracy but is not very fast.\n */\n#    define MAD_F_MLA(hi, lo, x, y)  \\\n    ({ mad_fixed64hi_t __hi;  \\\n       mad_fixed64lo_t __lo;  \\\n       MAD_F_MLX(__hi, __lo, (x), (y));  \\\n       asm (\"addl %2,%0\\n\\t\"  \\\n\t    \"adcl %3,%1\"  \\\n\t    : \"=rm\" (lo), \"=rm\" (hi)  \\\n\t    : \"r\" (__lo), \"r\" (__hi), \"0\" (lo), \"1\" (hi)  \\\n\t    : \"cc\");  \\\n    })\n#   endif  /* OPT_ACCURACY */\n\n#   if defined(OPT_ACCURACY)\n/*\n * Surprisingly, this is faster than SHRD followed by ADC.\n */\n#    define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed64hi_t __hi_;  \\\n       mad_fixed64lo_t __lo_;  \\\n       mad_fixed_t __result;  \\\n       asm (\"addl %4,%2\\n\\t\"  \\\n\t    \"adcl %5,%3\"  \\\n\t    : \"=rm\" (__lo_), \"=rm\" (__hi_)  \\\n\t    : \"0\" (lo), \"1\" (hi),  \\\n\t      \"ir\" (1L << (MAD_F_SCALEBITS - 1)), \"ir\" (0)  \\\n\t    : \"cc\");  \\\n       asm (\"shrdl %3,%2,%1\"  \\\n\t    : \"=rm\" (__result)  \\\n\t    : \"0\" (__lo_), \"r\" (__hi_), \"I\" (MAD_F_SCALEBITS)  \\\n\t    : \"cc\");  \\\n       __result;  \\\n    })\n#   elif defined(OPT_INTEL)\n/*\n * Alternate Intel scaling that may or may not perform better.\n */\n#    define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed_t __result;  \\\n       asm (\"shrl %3,%1\\n\\t\"  \\\n\t    \"shll %4,%2\\n\\t\"  \\\n\t    \"orl %2,%1\"  \\\n\t    : \"=rm\" (__result)  \\\n\t    : \"0\" (lo), \"r\" (hi),  \\\n\t      \"I\" (MAD_F_SCALEBITS), \"I\" (32 - MAD_F_SCALEBITS)  \\\n\t    : \"cc\");  \\\n       __result;  \\\n    })\n#   else\n#    define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed_t __result;  \\\n       asm (\"shrdl %3,%2,%1\"  \\\n\t    : \"=rm\" (__result)  \\\n\t    : \"0\" (lo), \"r\" (hi), \"I\" (MAD_F_SCALEBITS)  \\\n\t    : \"cc\");  \\\n       __result;  \\\n    })\n#   endif  /* OPT_ACCURACY */\n\n#   define MAD_F_SCALEBITS  MAD_F_FRACBITS\n#  endif\n\n/* --- ARM ----------------------------------------------------------------- */\n\n# elif defined(FPM_ARM)\n\n/* \n * This ARM V4 version is as accurate as FPM_64BIT but much faster. The\n * least significant bit is properly rounded at no CPU cycle cost!\n */\n# if 1\n/*\n * This is faster than the default implementation via MAD_F_MLX() and\n * mad_f_scale64().\n */\n#  define mad_f_mul(x, y)  \\\n    ({ mad_fixed64hi_t __hi;  \\\n       mad_fixed64lo_t __lo;  \\\n       mad_fixed_t __result;  \\\n       asm (\"smull\t%0, %1, %3, %4\\n\\t\"  \\\n\t    \"movs\t%0, %0, lsr %5\\n\\t\"  \\\n\t    \"adc\t%2, %0, %1, lsl %6\"  \\\n\t    : \"=&r\" (__lo), \"=&r\" (__hi), \"=r\" (__result)  \\\n\t    : \"%r\" (x), \"r\" (y),  \\\n\t      \"M\" (MAD_F_SCALEBITS), \"M\" (32 - MAD_F_SCALEBITS)  \\\n\t    : \"cc\");  \\\n       __result;  \\\n    })\n# endif\n\n#  define MAD_F_MLX(hi, lo, x, y)  \\\n    asm (\"smull\t%0, %1, %2, %3\"  \\\n\t : \"=&r\" (lo), \"=&r\" (hi)  \\\n\t : \"%r\" (x), \"r\" (y))\n\n#  define MAD_F_MLA(hi, lo, x, y)  \\\n    asm (\"smlal\t%0, %1, %2, %3\"  \\\n\t : \"+r\" (lo), \"+r\" (hi)  \\\n\t : \"%r\" (x), \"r\" (y))\n\n#  define MAD_F_MLN(hi, lo)  \\\n    asm (\"rsbs\t%0, %2, #0\\n\\t\"  \\\n\t \"rsc\t%1, %3, #0\"  \\\n\t : \"=r\" (lo), \"=r\" (hi)  \\\n\t : \"0\" (lo), \"1\" (hi)  \\\n\t : \"cc\")\n\n#  define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed_t __result;  \\\n       asm (\"movs\t%0, %1, lsr %3\\n\\t\"  \\\n\t    \"adc\t%0, %0, %2, lsl %4\"  \\\n\t    : \"=&r\" (__result)  \\\n\t    : \"r\" (lo), \"r\" (hi),  \\\n\t      \"M\" (MAD_F_SCALEBITS), \"M\" (32 - MAD_F_SCALEBITS)  \\\n\t    : \"cc\");  \\\n       __result;  \\\n    })\n\n#  define MAD_F_SCALEBITS  MAD_F_FRACBITS\n\n/* --- MIPS ---------------------------------------------------------------- */\n\n# elif defined(FPM_MIPS)\n\n/*\n * This MIPS version is fast and accurate; the disposition of the least\n * significant bit depends on OPT_ACCURACY via mad_f_scale64().\n */\n#  define MAD_F_MLX(hi, lo, x, y)  \\\n    asm (\"mult\t%2,%3\"  \\\n\t : \"=l\" (lo), \"=h\" (hi)  \\\n\t : \"%r\" (x), \"r\" (y))\n\n# if defined(HAVE_MADD_ASM)\n#  define MAD_F_MLA(hi, lo, x, y)  \\\n    asm (\"madd\t%2,%3\"  \\\n\t : \"+l\" (lo), \"+h\" (hi)  \\\n\t : \"%r\" (x), \"r\" (y))\n# elif defined(HAVE_MADD16_ASM)\n/*\n * This loses significant accuracy due to the 16-bit integer limit in the\n * multiply/accumulate instruction.\n */\n#  define MAD_F_ML0(hi, lo, x, y)  \\\n    asm (\"mult\t%2,%3\"  \\\n\t : \"=l\" (lo), \"=h\" (hi)  \\\n\t : \"%r\" ((x) >> 12), \"r\" ((y) >> 16))\n#  define MAD_F_MLA(hi, lo, x, y)  \\\n    asm (\"madd16\t%2,%3\"  \\\n\t : \"+l\" (lo), \"+h\" (hi)  \\\n\t : \"%r\" ((x) >> 12), \"r\" ((y) >> 16))\n#  define MAD_F_MLZ(hi, lo)  ((mad_fixed_t) (lo))\n# endif\n\n# if defined(OPT_SPEED)\n#  define mad_f_scale64(hi, lo)  \\\n    ((mad_fixed_t) ((hi) << (32 - MAD_F_SCALEBITS)))\n#  define MAD_F_SCALEBITS  MAD_F_FRACBITS\n# endif\n\n/* --- SPARC --------------------------------------------------------------- */\n\n# elif defined(FPM_SPARC)\n\n/*\n * This SPARC V8 version is fast and accurate; the disposition of the least\n * significant bit depends on OPT_ACCURACY via mad_f_scale64().\n */\n#  define MAD_F_MLX(hi, lo, x, y)  \\\n    asm (\"smul %2, %3, %0\\n\\t\"  \\\n\t \"rd %%y, %1\"  \\\n\t : \"=r\" (lo), \"=r\" (hi)  \\\n\t : \"%r\" (x), \"rI\" (y))\n\n/* --- PowerPC ------------------------------------------------------------- */\n\n# elif defined(FPM_PPC)\n\n/*\n * This PowerPC version is fast and accurate; the disposition of the least\n * significant bit depends on OPT_ACCURACY via mad_f_scale64().\n */\n#  define MAD_F_MLX(hi, lo, x, y)  \\\n    do {  \\\n      asm (\"mullw %0,%1,%2\"  \\\n\t   : \"=r\" (lo)  \\\n\t   : \"%r\" (x), \"r\" (y));  \\\n      asm (\"mulhw %0,%1,%2\"  \\\n\t   : \"=r\" (hi)  \\\n\t   : \"%r\" (x), \"r\" (y));  \\\n    }  \\\n    while (0)\n\n#  if defined(OPT_ACCURACY)\n/*\n * This gives best accuracy but is not very fast.\n */\n#   define MAD_F_MLA(hi, lo, x, y)  \\\n    ({ mad_fixed64hi_t __hi;  \\\n       mad_fixed64lo_t __lo;  \\\n       MAD_F_MLX(__hi, __lo, (x), (y));  \\\n       asm (\"addc %0,%2,%3\\n\\t\"  \\\n\t    \"adde %1,%4,%5\"  \\\n\t    : \"=r\" (lo), \"=r\" (hi)  \\\n\t    : \"%r\" (lo), \"r\" (__lo),  \\\n\t      \"%r\" (hi), \"r\" (__hi)  \\\n\t    : \"xer\");  \\\n    })\n#  endif\n\n#  if defined(OPT_ACCURACY)\n/*\n * This is slower than the truncating version below it.\n */\n#   define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed_t __result, __round;  \\\n       asm (\"rotrwi %0,%1,%2\"  \\\n\t    : \"=r\" (__result)  \\\n\t    : \"r\" (lo), \"i\" (MAD_F_SCALEBITS));  \\\n       asm (\"extrwi %0,%1,1,0\"  \\\n\t    : \"=r\" (__round)  \\\n\t    : \"r\" (__result));  \\\n       asm (\"insrwi %0,%1,%2,0\"  \\\n\t    : \"+r\" (__result)  \\\n\t    : \"r\" (hi), \"i\" (MAD_F_SCALEBITS));  \\\n       asm (\"add %0,%1,%2\"  \\\n\t    : \"=r\" (__result)  \\\n\t    : \"%r\" (__result), \"r\" (__round));  \\\n       __result;  \\\n    })\n#  else\n#   define mad_f_scale64(hi, lo)  \\\n    ({ mad_fixed_t __result;  \\\n       asm (\"rotrwi %0,%1,%2\"  \\\n\t    : \"=r\" (__result)  \\\n\t    : \"r\" (lo), \"i\" (MAD_F_SCALEBITS));  \\\n       asm (\"insrwi %0,%1,%2,0\"  \\\n\t    : \"+r\" (__result)  \\\n\t    : \"r\" (hi), \"i\" (MAD_F_SCALEBITS));  \\\n       __result;  \\\n    })\n#  endif\n\n#  define MAD_F_SCALEBITS  MAD_F_FRACBITS\n\n/* --- Default ------------------------------------------------------------- */\n\n# elif defined(FPM_DEFAULT)\n\n/*\n * This version is the most portable but it loses significant accuracy.\n * Furthermore, accuracy is biased against the second argument, so care\n * should be taken when ordering operands.\n *\n * The scale factors are constant as this is not used with SSO.\n *\n * Pre-rounding is required to stay within the limits of compliance.\n */\n#  if defined(OPT_SPEED)\n#   define mad_f_mul(x, y)\t(((x) >> 12) * ((y) >> 16))\n#  else\n#   define mad_f_mul(x, y)\t((((x) + (1L << 11)) >> 12) *  \\\n\t\t\t\t (((y) + (1L << 15)) >> 16))\n#  endif\n\n/* ------------------------------------------------------------------------- */\n\n# else\n#  error \"no FPM selected\"\n# endif\n\n/* default implementations */\n\n# if !defined(mad_f_mul)\n#  define mad_f_mul(x, y)  \\\n    ({ register mad_fixed64hi_t __hi;  \\\n       register mad_fixed64lo_t __lo;  \\\n       MAD_F_MLX(__hi, __lo, (x), (y));  \\\n       mad_f_scale64(__hi, __lo);  \\\n    })\n# endif\n\n# if !defined(MAD_F_MLA)\n#  define MAD_F_ML0(hi, lo, x, y)\t((lo)  = mad_f_mul((x), (y)))\n#  define MAD_F_MLA(hi, lo, x, y)\t((lo) += mad_f_mul((x), (y)))\n#  define MAD_F_MLN(hi, lo)\t\t((lo)  = -(lo))\n#  define MAD_F_MLZ(hi, lo)\t\t((void) (hi), (mad_fixed_t) (lo))\n# endif\n\n# if !defined(MAD_F_ML0)\n#  define MAD_F_ML0(hi, lo, x, y)\tMAD_F_MLX((hi), (lo), (x), (y))\n# endif\n\n# if !defined(MAD_F_MLN)\n#  define MAD_F_MLN(hi, lo)\t\t((hi) = ((lo) = -(lo)) ? ~(hi) : -(hi))\n# endif\n\n# if !defined(MAD_F_MLZ)\n#  define MAD_F_MLZ(hi, lo)\t\tmad_f_scale64((hi), (lo))\n# endif\n\n# if !defined(mad_f_scale64)\n#  if defined(OPT_ACCURACY)\n#   define mad_f_scale64(hi, lo)  \\\n    ((((mad_fixed_t)  \\\n       (((hi) << (32 - (MAD_F_SCALEBITS - 1))) |  \\\n\t((lo) >> (MAD_F_SCALEBITS - 1)))) + 1) >> 1)\n#  else\n#   define mad_f_scale64(hi, lo)  \\\n    ((mad_fixed_t)  \\\n     (((hi) << (32 - MAD_F_SCALEBITS)) |  \\\n      ((lo) >> MAD_F_SCALEBITS)))\n#  endif\n#  define MAD_F_SCALEBITS  MAD_F_FRACBITS\n# endif\n\n/* C routines */\n\nmad_fixed_t mad_f_abs(mad_fixed_t);\nmad_fixed_t mad_f_div(mad_fixed_t, mad_fixed_t);\n\n# endif\n\n/* Id: bit.h,v 1.12 2004/01/23 09:41:32 rob Exp */\n\n# ifndef LIBMAD_BIT_H\n# define LIBMAD_BIT_H\n\nstruct mad_bitptr {\n  unsigned char const *byte;\n  unsigned short cache;\n  unsigned short left;\n};\n\nvoid mad_bit_init(struct mad_bitptr *, unsigned char const *);\n\n# define mad_bit_finish(bitptr)\t\t/* nothing */\n\nunsigned int mad_bit_length(struct mad_bitptr const *,\n\t\t\t    struct mad_bitptr const *);\n\n# define mad_bit_bitsleft(bitptr)  ((bitptr)->left)\nunsigned char const *mad_bit_nextbyte(struct mad_bitptr const *);\n\nvoid mad_bit_skip(struct mad_bitptr *, unsigned int);\nunsigned long mad_bit_read(struct mad_bitptr *, unsigned int);\nvoid mad_bit_write(struct mad_bitptr *, unsigned int, unsigned long);\n\nunsigned short mad_bit_crc(struct mad_bitptr, unsigned int, unsigned short);\n\n# endif\n\n/* Id: timer.h,v 1.16 2004/01/23 09:41:33 rob Exp */\n\n# ifndef LIBMAD_TIMER_H\n# define LIBMAD_TIMER_H\n\ntypedef struct {\n  signed long seconds;\t\t/* whole seconds */\n  unsigned long fraction;\t/* 1/MAD_TIMER_RESOLUTION seconds */\n} mad_timer_t;\n\nextern mad_timer_t const mad_timer_zero;\n\n# define MAD_TIMER_RESOLUTION\t352800000UL\n\nenum mad_units {\n  MAD_UNITS_HOURS\t =    -2,\n  MAD_UNITS_MINUTES\t =    -1,\n  MAD_UNITS_SECONDS\t =     0,\n\n  /* metric units */\n\n  MAD_UNITS_DECISECONDS\t =    10,\n  MAD_UNITS_CENTISECONDS =   100,\n  MAD_UNITS_MILLISECONDS =  1000,\n\n  /* audio sample units */\n\n  MAD_UNITS_8000_HZ\t =  8000,\n  MAD_UNITS_11025_HZ\t = 11025,\n  MAD_UNITS_12000_HZ\t = 12000,\n\n  MAD_UNITS_16000_HZ\t = 16000,\n  MAD_UNITS_22050_HZ\t = 22050,\n  MAD_UNITS_24000_HZ\t = 24000,\n\n  MAD_UNITS_32000_HZ\t = 32000,\n  MAD_UNITS_44100_HZ\t = 44100,\n  MAD_UNITS_48000_HZ\t = 48000,\n\n  /* video frame/field units */\n\n  MAD_UNITS_24_FPS\t =    24,\n  MAD_UNITS_25_FPS\t =    25,\n  MAD_UNITS_30_FPS\t =    30,\n  MAD_UNITS_48_FPS\t =    48,\n  MAD_UNITS_50_FPS\t =    50,\n  MAD_UNITS_60_FPS\t =    60,\n\n  /* CD audio frames */\n\n  MAD_UNITS_75_FPS\t =    75,\n\n  /* video drop-frame units */\n\n  MAD_UNITS_23_976_FPS\t =   -24,\n  MAD_UNITS_24_975_FPS\t =   -25,\n  MAD_UNITS_29_97_FPS\t =   -30,\n  MAD_UNITS_47_952_FPS\t =   -48,\n  MAD_UNITS_49_95_FPS\t =   -50,\n  MAD_UNITS_59_94_FPS\t =   -60\n};\n\n# define mad_timer_reset(timer)\t((void) (*(timer) = mad_timer_zero))\n\nint mad_timer_compare(mad_timer_t, mad_timer_t);\n\n# define mad_timer_sign(timer)\tmad_timer_compare((timer), mad_timer_zero)\n\nvoid mad_timer_negate(mad_timer_t *);\nmad_timer_t mad_timer_abs(mad_timer_t);\n\nvoid mad_timer_set(mad_timer_t *, unsigned long, unsigned long, unsigned long);\nvoid mad_timer_add(mad_timer_t *, mad_timer_t);\nvoid mad_timer_multiply(mad_timer_t *, signed long);\n\nsigned long mad_timer_count(mad_timer_t, enum mad_units);\nunsigned long mad_timer_fraction(mad_timer_t, unsigned long);\nvoid mad_timer_string(mad_timer_t, char *, char const *,\n\t\t      enum mad_units, enum mad_units, unsigned long);\n\n# endif\n\n/* Id: stream.h,v 1.20 2004/02/05 09:02:39 rob Exp */\n\n# ifndef LIBMAD_STREAM_H\n# define LIBMAD_STREAM_H\n\n\n# define MAD_BUFFER_GUARD\t8\n# define MAD_BUFFER_MDLEN\t(511 + 2048 + MAD_BUFFER_GUARD)\n\nenum mad_error {\n  MAD_ERROR_NONE\t   = 0x0000,\t/* no error */\n\n  MAD_ERROR_BUFLEN\t   = 0x0001,\t/* input buffer too small (or EOF) */\n  MAD_ERROR_BUFPTR\t   = 0x0002,\t/* invalid (null) buffer pointer */\n\n  MAD_ERROR_NOMEM\t   = 0x0031,\t/* not enough memory */\n\n  MAD_ERROR_LOSTSYNC\t   = 0x0101,\t/* lost synchronization */\n  MAD_ERROR_BADLAYER\t   = 0x0102,\t/* reserved header layer value */\n  MAD_ERROR_BADBITRATE\t   = 0x0103,\t/* forbidden bitrate value */\n  MAD_ERROR_BADSAMPLERATE  = 0x0104,\t/* reserved sample frequency value */\n  MAD_ERROR_BADEMPHASIS\t   = 0x0105,\t/* reserved emphasis value */\n\n  MAD_ERROR_BADCRC\t   = 0x0201,\t/* CRC check failed */\n  MAD_ERROR_BADBITALLOC\t   = 0x0211,\t/* forbidden bit allocation value */\n  MAD_ERROR_BADSCALEFACTOR = 0x0221,\t/* bad scalefactor index */\n  MAD_ERROR_BADMODE        = 0x0222,\t/* bad bitrate/mode combination */\n  MAD_ERROR_BADFRAMELEN\t   = 0x0231,\t/* bad frame length */\n  MAD_ERROR_BADBIGVALUES   = 0x0232,\t/* bad big_values count */\n  MAD_ERROR_BADBLOCKTYPE   = 0x0233,\t/* reserved block_type */\n  MAD_ERROR_BADSCFSI\t   = 0x0234,\t/* bad scalefactor selection info */\n  MAD_ERROR_BADDATAPTR\t   = 0x0235,\t/* bad main_data_begin pointer */\n  MAD_ERROR_BADPART3LEN\t   = 0x0236,\t/* bad audio data length */\n  MAD_ERROR_BADHUFFTABLE   = 0x0237,\t/* bad Huffman table select */\n  MAD_ERROR_BADHUFFDATA\t   = 0x0238,\t/* Huffman data overrun */\n  MAD_ERROR_BADSTEREO\t   = 0x0239\t/* incompatible block_type for JS */\n};\n\n# define MAD_RECOVERABLE(error)\t((error) & 0xff00)\n\nstruct mad_stream {\n  unsigned char const *buffer;\t\t/* input bitstream buffer */\n  unsigned char const *bufend;\t\t/* end of buffer */\n  unsigned long skiplen;\t\t/* bytes to skip before next frame */\n\n  int sync;\t\t\t\t/* stream sync found */\n  unsigned long freerate;\t\t/* free bitrate (fixed) */\n\n  unsigned char const *this_frame;\t/* start of current frame */\n  unsigned char const *next_frame;\t/* start of next frame */\n  struct mad_bitptr ptr;\t\t/* current processing bit pointer */\n\n  struct mad_bitptr anc_ptr;\t\t/* ancillary bits pointer */\n  unsigned int anc_bitlen;\t\t/* number of ancillary bits */\n\n  unsigned char (*main_data)[MAD_BUFFER_MDLEN];\n\t\t\t\t\t/* Layer III main_data() */\n  unsigned int md_len;\t\t\t/* bytes in main_data */\n\n  int options;\t\t\t\t/* decoding options (see below) */\n  enum mad_error error;\t\t\t/* error code (see above) */\n};\n\nenum {\n  MAD_OPTION_IGNORECRC      = 0x0001,\t/* ignore CRC errors */\n  MAD_OPTION_HALFSAMPLERATE = 0x0002\t/* generate PCM at 1/2 sample rate */\n# if 0  /* not yet implemented */\n  MAD_OPTION_LEFTCHANNEL    = 0x0010,\t/* decode left channel only */\n  MAD_OPTION_RIGHTCHANNEL   = 0x0020,\t/* decode right channel only */\n  MAD_OPTION_SINGLECHANNEL  = 0x0030\t/* combine channels */\n# endif\n};\n\nvoid mad_stream_init(struct mad_stream *);\nvoid mad_stream_finish(struct mad_stream *);\n\n# define mad_stream_options(stream, opts)  \\\n    ((void) ((stream)->options = (opts)))\n\nvoid mad_stream_buffer(struct mad_stream *,\n\t\t       unsigned char const *, unsigned long);\nvoid mad_stream_skip(struct mad_stream *, unsigned long);\n\nint mad_stream_sync(struct mad_stream *);\n\nchar const *mad_stream_errorstr(struct mad_stream const *);\n\n# endif\n\n/* Id: frame.h,v 1.20 2004/01/23 09:41:32 rob Exp */\n\n# ifndef LIBMAD_FRAME_H\n# define LIBMAD_FRAME_H\n\n\nenum mad_layer {\n  MAD_LAYER_I   = 1,\t\t\t/* Layer I */\n  MAD_LAYER_II  = 2,\t\t\t/* Layer II */\n  MAD_LAYER_III = 3\t\t\t/* Layer III */\n};\n\nenum mad_mode {\n  MAD_MODE_SINGLE_CHANNEL = 0,\t\t/* single channel */\n  MAD_MODE_DUAL_CHANNEL\t  = 1,\t\t/* dual channel */\n  MAD_MODE_JOINT_STEREO\t  = 2,\t\t/* joint (MS/intensity) stereo */\n  MAD_MODE_STEREO\t  = 3\t\t/* normal LR stereo */\n};\n\nenum mad_emphasis {\n  MAD_EMPHASIS_NONE\t  = 0,\t\t/* no emphasis */\n  MAD_EMPHASIS_50_15_US\t  = 1,\t\t/* 50/15 microseconds emphasis */\n  MAD_EMPHASIS_CCITT_J_17 = 3,\t\t/* CCITT J.17 emphasis */\n  MAD_EMPHASIS_RESERVED   = 2\t\t/* unknown emphasis */\n};\n\nstruct mad_header {\n  enum mad_layer layer;\t\t\t/* audio layer (1, 2, or 3) */\n  enum mad_mode mode;\t\t\t/* channel mode (see above) */\n  int mode_extension;\t\t\t/* additional mode info */\n  enum mad_emphasis emphasis;\t\t/* de-emphasis to use (see above) */\n\n  unsigned long bitrate;\t\t/* stream bitrate (bps) */\n  unsigned int samplerate;\t\t/* sampling frequency (Hz) */\n\n  unsigned short crc_check;\t\t/* frame CRC accumulator */\n  unsigned short crc_target;\t\t/* final target CRC checksum */\n\n  int flags;\t\t\t\t/* flags (see below) */\n  int private_bits;\t\t\t/* private bits (see below) */\n\n  mad_timer_t duration;\t\t\t/* audio playing time of frame */\n};\n\nstruct mad_frame {\n  struct mad_header header;\t\t/* MPEG audio header */\n\n  int options;\t\t\t\t/* decoding options (from stream) */\n\n  mad_fixed_t sbsample[2][36][32];\t/* synthesis subband filter samples */\n  mad_fixed_t (*overlap)[2][32][18];\t/* Layer III block overlap data */\n};\n\n# define MAD_NCHANNELS(header)\t\t((header)->mode ? 2 : 1)\n# define MAD_NSBSAMPLES(header)  \\\n  ((header)->layer == MAD_LAYER_I ? 12 :  \\\n   (((header)->layer == MAD_LAYER_III &&  \\\n     ((header)->flags & MAD_FLAG_LSF_EXT)) ? 18 : 36))\n\nenum {\n  MAD_FLAG_NPRIVATE_III\t= 0x0007,\t/* number of Layer III private bits */\n  MAD_FLAG_INCOMPLETE\t= 0x0008,\t/* header but not data is decoded */\n\n  MAD_FLAG_PROTECTION\t= 0x0010,\t/* frame has CRC protection */\n  MAD_FLAG_COPYRIGHT\t= 0x0020,\t/* frame is copyright */\n  MAD_FLAG_ORIGINAL\t= 0x0040,\t/* frame is original (else copy) */\n  MAD_FLAG_PADDING\t= 0x0080,\t/* frame has additional slot */\n\n  MAD_FLAG_I_STEREO\t= 0x0100,\t/* uses intensity joint stereo */\n  MAD_FLAG_MS_STEREO\t= 0x0200,\t/* uses middle/side joint stereo */\n  MAD_FLAG_FREEFORMAT\t= 0x0400,\t/* uses free format bitrate */\n\n  MAD_FLAG_LSF_EXT\t= 0x1000,\t/* lower sampling freq. extension */\n  MAD_FLAG_MC_EXT\t= 0x2000,\t/* multichannel audio extension */\n  MAD_FLAG_MPEG_2_5_EXT\t= 0x4000\t/* MPEG 2.5 (unofficial) extension */\n};\n\nenum {\n  MAD_PRIVATE_HEADER\t= 0x0100,\t/* header private bit */\n  MAD_PRIVATE_III\t= 0x001f\t/* Layer III private bits (up to 5) */\n};\n\nvoid mad_header_init(struct mad_header *);\n\n# define mad_header_finish(header)  /* nothing */\n\nint mad_header_decode(struct mad_header *, struct mad_stream *);\n\nvoid mad_frame_init(struct mad_frame *);\nvoid mad_frame_finish(struct mad_frame *);\n\nint mad_frame_decode(struct mad_frame *, struct mad_stream *);\n\nvoid mad_frame_mute(struct mad_frame *);\n\n# endif\n\n/* Id: synth.h,v 1.15 2004/01/23 09:41:33 rob Exp */\n\n# ifndef LIBMAD_SYNTH_H\n# define LIBMAD_SYNTH_H\n\n\nstruct mad_pcm {\n  unsigned int samplerate;\t\t/* sampling frequency (Hz) */\n  unsigned short channels;\t\t/* number of channels */\n  unsigned short length;\t\t/* number of samples per channel */\n  mad_fixed_t samples[2][1152];\t\t/* PCM output samples [ch][sample] */\n};\n\nstruct mad_synth {\n  mad_fixed_t filter[2][2][2][16][8];\t/* polyphase filterbank outputs */\n  \t\t\t\t\t/* [ch][eo][peo][s][v] */\n\n  unsigned int phase;\t\t\t/* current processing phase */\n\n  struct mad_pcm pcm;\t\t\t/* PCM output */\n};\n\n/* single channel PCM selector */\nenum {\n  MAD_PCM_CHANNEL_SINGLE = 0\n};\n\n/* dual channel PCM selector */\nenum {\n  MAD_PCM_CHANNEL_DUAL_1 = 0,\n  MAD_PCM_CHANNEL_DUAL_2 = 1\n};\n\n/* stereo PCM selector */\nenum {\n  MAD_PCM_CHANNEL_STEREO_LEFT  = 0,\n  MAD_PCM_CHANNEL_STEREO_RIGHT = 1\n};\n\nvoid mad_synth_init(struct mad_synth *);\n\n# define mad_synth_finish(synth)  /* nothing */\n\nvoid mad_synth_mute(struct mad_synth *);\n\nvoid mad_synth_frame(struct mad_synth *, struct mad_frame const *);\n\n# endif\n\n/* Id: decoder.h,v 1.17 2004/01/23 09:41:32 rob Exp */\n\n# ifndef LIBMAD_DECODER_H\n# define LIBMAD_DECODER_H\n\n\nenum mad_decoder_mode {\n  MAD_DECODER_MODE_SYNC  = 0,\n  MAD_DECODER_MODE_ASYNC\n};\n\nenum mad_flow {\n  MAD_FLOW_CONTINUE = 0x0000,\t/* continue normally */\n  MAD_FLOW_STOP     = 0x0010,\t/* stop decoding normally */\n  MAD_FLOW_BREAK    = 0x0011,\t/* stop decoding and signal an error */\n  MAD_FLOW_IGNORE   = 0x0020\t/* ignore the current frame */\n};\n\nstruct mad_decoder {\n  enum mad_decoder_mode mode;\n\n  int options;\n\n  struct {\n    long pid;\n    int in;\n    int out;\n  } async;\n\n  struct {\n    struct mad_stream stream;\n    struct mad_frame frame;\n    struct mad_synth synth;\n  } *sync;\n\n  void *cb_data;\n\n  enum mad_flow (*input_func)(void *, struct mad_stream *);\n  enum mad_flow (*header_func)(void *, struct mad_header const *);\n  enum mad_flow (*filter_func)(void *,\n\t\t\t       struct mad_stream const *, struct mad_frame *);\n  enum mad_flow (*output_func)(void *,\n\t\t\t       struct mad_header const *, struct mad_pcm *);\n  enum mad_flow (*error_func)(void *, struct mad_stream *, struct mad_frame *);\n  enum mad_flow (*message_func)(void *, void *, unsigned int *);\n};\n\nvoid mad_decoder_init(struct mad_decoder *, void *,\n\t\t      enum mad_flow (*)(void *, struct mad_stream *),\n\t\t      enum mad_flow (*)(void *, struct mad_header const *),\n\t\t      enum mad_flow (*)(void *,\n\t\t\t\t\tstruct mad_stream const *,\n\t\t\t\t\tstruct mad_frame *),\n\t\t      enum mad_flow (*)(void *,\n\t\t\t\t\tstruct mad_header const *,\n\t\t\t\t\tstruct mad_pcm *),\n\t\t      enum mad_flow (*)(void *,\n\t\t\t\t\tstruct mad_stream *,\n\t\t\t\t\tstruct mad_frame *),\n\t\t      enum mad_flow (*)(void *, void *, unsigned int *));\nint mad_decoder_finish(struct mad_decoder *);\n\n# define mad_decoder_options(decoder, opts)  \\\n    ((void) ((decoder)->options = (opts)))\n\nint mad_decoder_run(struct mad_decoder *, enum mad_decoder_mode);\nint mad_decoder_message(struct mad_decoder *, void *, unsigned int *);\n\n# endif\n\n# ifdef __cplusplus\n}\n# endif\n"
  },
  {
    "path": "lib/3rdparty/patches/README",
    "content": "tbytevector_cpp.patch is for Taglib 1.5 to fix v.slow parsing of \r\nsome rare MP3 files, see: http://bugs.kde.org/show_bug.cgi?id=159821\r\n\r\n****"
  },
  {
    "path": "lib/3rdparty/patches/tbytevector_cpp.patch",
    "content": "Index: tbytevector.cpp\r\n===================================================================\r\n--- tbytevector.cpp\t(revision 789815)\r\n+++ tbytevector.cpp\t(working copy)\r\n@@ -432,24 +432,62 @@\r\n   const int patternSize = pattern.size();\n   const int withSize = with.size();\n \n-  int offset = find(pattern);\n+  if(withSize<=patternSize){\n+\t  int cpyOffset(0);\n+\t  int cpySize(0);\n+\t  int srcOffset(0);\n \n-  while(offset >= 0) {\n+\t  while( srcOffset < size()-patternSize ){\n+\t\t  if( memcmp(pattern.data(),data()+srcOffset,patternSize)==0 ){\n+\t\t\t  // Match, lets move the memory\n \n-    const int originalSize = size();\n+\t\t\t  // Move \n+\t\t\t  if(cpySize){\n+\t\t\t\t  memmove(data()+cpyOffset,data()+srcOffset-cpySize,cpySize);\n+\t\t\t\t  cpyOffset\t+= cpySize;\n+\t\t\t\t  cpySize=0;\n+\t\t\t  }\n \n-    if(withSize > patternSize)\n-      resize(originalSize + withSize - patternSize);\n+\t\t\t  // Copy the replacement\n+\t\t\t  memcpy(data()+cpyOffset,with.data(),withSize);\n+\t\t\t  cpyOffset\t+= withSize;\n \n-    if(patternSize != withSize)\n-      ::memcpy(data() + offset + withSize, mid(offset + patternSize).data(), originalSize - offset - patternSize);\n+\t\t\t  // Jump ahead the patternSize\n+\t\t\t  srcOffset+=patternSize;\n+\t\t\t\n+\t\t  }else{\n+\t\t\t  // No match, step ahead\n+\t\t\t  ++cpySize;\n+\t\t\t  ++srcOffset;\n+\t\t  }\n+\t  }\n \n-    if(withSize < patternSize)\n-      resize(originalSize + withSize - patternSize);\n+\t\tmemmove(data()+cpyOffset,data()+srcOffset-cpySize,cpySize+patternSize);\n+\t\tcpyOffset\t+= cpySize+patternSize;\n \n-    ::memcpy(data() + offset, with.data(), withSize);\n+\t\tresize(cpyOffset);\n \n-    offset = find(pattern, offset + withSize);\n+  }else{\n+\n+\t  int offset = find(pattern);\n+\n+\t  while(offset >= 0) {\n+\n+\t\tconst int originalSize = size();\n+\n+\t\tif(withSize > patternSize)\n+\t\t  resize(originalSize + withSize - patternSize);\n+\n+\t\tif(patternSize != withSize)\n+\t\t  ::memcpy(data() + offset + withSize, mid(offset + patternSize).data(), originalSize - offset - patternSize);\n+\n+\t\tif(withSize < patternSize)\n+\t\t  resize(originalSize + withSize - patternSize);\n+\n+\t\t::memcpy(data() + offset, with.data(), withSize);\n+\n+\t\toffset = find(pattern, offset + withSize);\n+\t  }\n   }\n \n   return *this;\n"
  },
  {
    "path": "lib/3rdparty/samplerate.h",
    "content": "/*\n** Copyright (C) 2002-2004 Erik de Castro Lopo <erikd@mega-nerd.com>\n**\n** This program is free software; you can redistribute it and/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program; if not, write to the Free Software\n** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.\n*/\n\n/*\n** API documentation is available here:\n**     http://www.mega-nerd.com/SRC/api.html\n*/\n\n#ifndef SAMPLERATE_H\n#define SAMPLERATE_H\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\t/* __cplusplus */\n\n\n/* Opaque data type SRC_STATE. */\ntypedef struct SRC_STATE_tag SRC_STATE ;\n\n/* SRC_DATA is used to pass data to src_simple() and src_process(). */\ntypedef struct\n{\tfloat\t*data_in, *data_out ;\n\n\tlong\tinput_frames, output_frames ;\n\tlong\tinput_frames_used, output_frames_gen ;\n\n\tint\t\tend_of_input ;\n\n\tdouble\tsrc_ratio ;\n} SRC_DATA ;\n\n/* SRC_CB_DATA is used with callback based API. */\ntypedef struct\n{\tlong\tframes ;\n\tfloat\t*data_in ;\n} SRC_CB_DATA ;\n\n/*\n** User supplied callback function type for use with src_callback_new()\n** and src_callback_read(). First parameter is the same pointer that was\n** passed into src_callback_new(). Second parameter is pointer to a\n** pointer. The user supplied callback function must modify *data to\n** point to the start of the user supplied float array. The user supplied\n** function must return the number of frames that **data points to.\n*/\n\ntypedef long (*src_callback_t) (void *cb_data, float **data) ;\n\n/*\n**\tStandard initialisation function : return an anonymous pointer to the\n**\tinternal state of the converter. Choose a converter from the enums below.\n**\tError returned in *error.\n*/\n\nSRC_STATE* src_new (int converter_type, int channels, int *error) ;\n\n/*\n**\tInitilisation for callback based API : return an anonymous pointer to the\n**\tinternal state of the converter. Choose a converter from the enums below.\n**\tThe cb_data pointer can point to any data or be set to NULL. Whatever the\n**\tvalue, when processing, user supplied function \"func\" gets called with\n**\tcb_data as first parameter.\n*/\n\nSRC_STATE* src_callback_new (src_callback_t func, int converter_type, int channels,\n\t\t\t\tint *error, void* cb_data) ;\n\n/*\n**\tCleanup all internal allocations.\n**\tAlways returns NULL.\n*/\n\nSRC_STATE* src_delete (SRC_STATE *state) ;\n\n/*\n**\tStandard processing function.\n**\tReturns non zero on error.\n*/\n\nint src_process (SRC_STATE *state, SRC_DATA *data) ;\n\n/*\n**\tCallback based processing function. Read up to frames worth of data from\n**\tthe converter int *data and return frames read or -1 on error.\n*/\nlong src_callback_read (SRC_STATE *state, double src_ratio, long frames, float *data) ;\n\n/*\n**\tSimple interface for performing a single conversion from input buffer to\n**\toutput buffer at a fixed conversion ratio.\n**\tSimple interface does not require initialisation as it can only operate on\n**\ta single buffer worth of audio.\n*/\n\nint src_simple (SRC_DATA *data, int converter_type, int channels) ;\n\n/*\n** This library contains a number of different sample rate converters,\n** numbered 0 through N.\n**\n** Return a string giving either a name or a more full description of each\n** sample rate converter or NULL if no sample rate converter exists for\n** the given value. The converters are sequentially numbered from 0 to N.\n*/\n\nconst char *src_get_name (int converter_type) ;\nconst char *src_get_description (int converter_type) ;\nconst char *src_get_version (void) ;\n\n/*\n**\tSet a new SRC ratio. This allows step responses\n**\tin the conversion ratio.\n**\tReturns non zero on error.\n*/\n\nint src_set_ratio (SRC_STATE *state, double new_ratio) ;\n\n/*\n**\tReset the internal SRC state.\n**\tDoes not modify the quality settings.\n**\tDoes not free any memory allocations.\n**\tReturns non zero on error.\n*/\n\nint src_reset (SRC_STATE *state) ;\n\n/*\n** Return TRUE if ratio is a valid conversion ratio, FALSE\n** otherwise.\n*/\n\nint src_is_valid_ratio (double ratio) ;\n\n/*\n**\tReturn an error number.\n*/\n\nint src_error (SRC_STATE *state) ;\n\n/*\n**\tConvert the error number into a string.\n*/\nconst char* src_strerror (int error) ;\n\n/*\n** The following enums can be used to set the interpolator type\n** using the function src_set_converter().\n*/\n\nenum\n{\n\tSRC_SINC_BEST_QUALITY\t\t= 0,\n\tSRC_SINC_MEDIUM_QUALITY\t\t= 1,\n\tSRC_SINC_FASTEST\t\t\t= 2,\n\tSRC_ZERO_ORDER_HOLD\t\t\t= 3,\n\tSRC_LINEAR\t\t\t\t\t= 4\n} ;\n\n/*\n** Extra helper functions for converting from short to float and\n** back again.\n*/\n\nvoid src_short_to_float_array (const short *in, float *out, int len) ;\nvoid src_float_to_short_array (const float *in, short *out, int len) ;\n\n\n#ifdef __cplusplus\n}\t\t/* extern \"C\" */\n#endif\t/* __cplusplus */\n\n#endif\t/* SAMPLERATE_H */\n\n/*\n** Do not edit or modify anything in this comment block.\n** The arch-tag line is a file identity tag for the GNU Arch\n** revision control system.\n**\n** arch-tag: 5421ef3e-c898-4ec3-8671-ea03d943ee00\n*/\n\n"
  },
  {
    "path": "lib/DllExportMacro.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef DLL_EXPORT_MACRO_H\n#define DLL_EXPORT_MACRO_H\n\n/** Exports symbols when compiled as part of the lib\n  * Imports when included from some other target */\n#if defined(_WIN32) || defined(WIN32)\n    #ifdef _UNICORN_DLLEXPORT\n        #define UNICORN_DLLEXPORT __declspec(dllexport)\n    #else\n        #define UNICORN_DLLEXPORT __declspec(dllimport)\n    #endif\n    #ifdef _LISTENER_DLLEXPORT\n        #define LISTENER_DLLEXPORT __declspec(dllexport)\n    #else\n        #define LISTENER_DLLEXPORT __declspec(dllimport)\n    #endif\n\t#ifndef ITUNES_PLUGIN\n\t\t#ifdef _LOGGER_DLLEXPORT\n\t\t\t#define LOGGER_DLLEXPORT __declspec(dllexport)\n\t\t#else\n\t\t\t#define LOGGER_DLLEXPORT __declspec(dllimport)\n\t\t#endif\n\t#else\n\t\t#define LOGGER_DLLEXPORT\n\t#endif\n#else\n    #define UNICORN_DLLEXPORT\n    #define LISTENER_DLLEXPORT\n    #define LOGGER_DLLEXPORT\n#endif\n\n#endif\n"
  },
  {
    "path": "lib/listener/PlayerCommand.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYER_COMMAND_H\n#define PLAYER_COMMAND_H\n\nenum PlayerCommand\n{\n    CommandInit,\n    CommandStart,\n    CommandPause,\n    CommandResume,\n    CommandStop,\n    CommandTerm,\n    \n    CommandBootstrap\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/PlayerCommandParser.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n#include <QStringList>\n#include <QUrl>\n#ifdef Q_OS_WIN\n#include <windows.h>\n#endif\n\n#include \"plugins/iTunes/ITunesComWrapper.h\"\n\n#include \"PlayerCommandParser.h\"\n\nusing std::invalid_argument;\n\nPlayerCommandParser::PlayerCommandParser( QString line ) throw( std::invalid_argument )\n{\n    line = line.trimmed();\n    if (line.isEmpty()) throw invalid_argument( \"Command string seems to be empty\" );\n\n    qDebug() << line;\n\n    m_command = extractCommand( line ); //removes the command string from line\n\n    line = line.trimmed();\n\n    QMap<QChar, QString> const args = extractArgs( line );\n    QString const required = requiredArgs( m_command );\n\n    for (int i = 0; i < required.length(); ++i)\n    {\n        QChar const c = required[i];\n        if (!args.contains( c ))\n            throw invalid_argument( \"Mandatory argument unspecified: \" + c.toAscii() );\n    }\n\n    m_playerId = args['c'];\n    \n    if (m_playerId.isEmpty())\n        throw invalid_argument( \"Player ID cannot be zero length\" );\n\n    switch (m_command)\n    {\n        case CommandStart:\n            m_track = extractTrack( args );\n            break;\n        case CommandBootstrap:\n            m_username = args['u'];\n            break;\n        case CommandInit:\n            m_applicationPath = args['f'];\n        default:\n            break;\n    }\n}\n\n\nPlayerCommand\nPlayerCommandParser::extractCommand( QString& line )\n{\n    int const n = line.indexOf( ' ' );\n    if (n == -1) throw invalid_argument( \"Unable to parse\" );\n\n    QString const command = line.left( n ).toUpper();\n\n    // Trim off command from passed in string\n    line = line.mid( n + 1 );\n\n    if (command == \"START\") return CommandStart;\n    if (command == \"STOP\") return CommandStop;\n    if (command == \"PAUSE\") return CommandPause;\n    if (command == \"RESUME\") return CommandResume;\n    if (command == \"BOOTSTRAP\") return CommandBootstrap;\n    if (command == \"INIT\") return CommandInit;\n    if (command == \"TERM\") return CommandTerm;\n\n    throw invalid_argument( \"Invalid command\" );\n}\n\n\nnamespace mxcl\n{\n    /** replaces '&&' and splits on remaining single '&' */\n    QStringList static inline split( QString line )\n    {\n        QStringList parts;\n        int start = 0, i = 0;\n        int end = 0;\n        while ((end = line.indexOf( '&', i )) != -1)\n        {\n            i = end + 1;\n            if (line[i] == '&') {\n                line.remove( end, 1 ); //convert && to &\n                continue;\n            }\n            parts += line.mid( start, end - start );\n            start = i;\n        }\n        return parts << line.mid( start );\n    }\n}\n\n\nstruct Pair\n{\n    Pair( const QString& s )\n    {\n        if (s[1] == '=')\n        {\n            key = s[0];\n            value = s.mid( 2 );\n        }\n    }\n    \n    QChar key;\n    QString value;\n};\n\n\nQMap<QChar, QString>\nPlayerCommandParser::extractArgs( const QString& line )\n{\n    QMap<QChar, QString> map;\n\n    // split by single & only, doubles are in fact &\n    foreach (Pair pair, mxcl::split( line ))\n    {\n        if (pair.key == QChar()) \n            throw invalid_argument( \"Invalid pair: \" + pair.key.toAscii() + '=' + std::string(pair.value.toUtf8().data()) );\n\n        if (map.contains( pair.key ))\n            throw invalid_argument( \"Field identifier occurred twice in request: \" + pair.key.toAscii() );\n\n        map[pair.key] = pair.value.trimmed();\n    }\n\n    return map;\n}\n\n\nQString\nPlayerCommandParser::requiredArgs( PlayerCommand c )\n{\n    switch (c)\n    {   \n        case CommandStart: \n            return \"catblp\";\n        case CommandBootstrap:\n            return \"cu\";\n        case CommandInit:\n            return \"cf\";\n        case CommandStop:\n        case CommandPause:\n        case CommandResume:\n        case CommandTerm:\n        default: // gcc 4.2 is stupid\n            return \"c\";\n    }\n}\n\n\nTrack\nPlayerCommandParser::extractTrack( const QMap<QChar, QString>& args )\n{\n    lastfm::MutableTrack track;\n    track.setArtist( args['a'] );\n    track.setAlbumArtist( args['d'] );\n    track.setTitle( args['t'] );\n    track.setAlbum( args['b'] );\n    track.setMbid( Mbid( args['m'] ) );\n    track.setDuration( args['l'].toInt() );\n    track.setUrl( QUrl::fromLocalFile( QUrl::fromPercentEncoding( args['p'].toUtf8() ) ) );\n    track.setSource( Track::Player );\n    track.setExtra( \"playerId\", args['c'] );\n    track.setExtra( \"playerName\", playerName() );\n\n#ifdef Q_OS_WIN\n\n    if ( args['c'] == \"itw\" )\n    {\n        ITunesComWrapper* com = new ITunesComWrapper;\n        ITunesTrack comTrack = com->currentTrack();\n        bool podcast = comTrack.podcast();\n        bool video = comTrack.video();\n        QUrl path = QUrl::fromLocalFile( QString::fromStdWString( comTrack.path() ) );\n\n        qDebug() << QString::fromStdWString( comTrack.artist() )\n                 << QString::fromStdWString( comTrack.track() )\n                 << podcast\n                 << video\n                 << path;\n\n        track.setUrl( path );\n        track.setPodcast( podcast );\n        track.setVideo( video );\n        delete com;\n    }\n\n#endif\n\n    //TODO should be done earlier, NOTE don't get the plugin to send a stamp \n    // time as this is prolly unecessary, and I bet you get new bugs!\n    track.stamp();\n    \n    return track;\n}\n"
  },
  {
    "path": "lib/listener/PlayerCommandParser.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYER_COMMAND_PARSER_H\n#define PLAYER_COMMAND_PARSER_H\n\n#include \"common/HideStupidWarnings.h\"\n#include \"PlayerCommand.h\"\n#include <lastfm/Track.h>\n#include <stdexcept>\n\n// ignore the warning about the exception specification\n#ifdef Q_OS_WIN\n#pragma warning( disable : 4290 )\n#endif\n\nclass PlayerCommandParser\n{\npublic:\n    PlayerCommandParser( QString line ) throw( std::invalid_argument );\n\n    PlayerCommand command() const { return m_command; }\n    QString playerId() const { return m_playerId; }\n    Track track() const { return m_track; }\n    QString username() const { return m_username; }\n\t/** we use this to get a pretty name for the player, and its icon \n\t  * Use the full path for the .exe file on Windows and Linux, and the bundle\n\t  * directory on Mac OS X */\n    QString applicationPath() const { return m_applicationPath; }\n\n    QString playerName()\n    {\n        QString& id = m_playerId;\n        \n        if (id == \"osx\") return \"iTunes\";\n        if (id == \"itw\") return \"iTunes\";\n        if (id == \"foo\") return \"foobar2000\";\n        if (id == \"wa2\") return \"Winamp\";\n        if (id == \"wmp\") return \"Windows Media Player\";\n        if (id == \"ass\") return \"Last.fm Radio\";\n        if (id == \"bof\") return \"Last.fm Boffin\";\n        return QObject::tr( \"unknown media player\" );\n    }    \n    \nprivate:\n    PlayerCommand extractCommand( QString& line );\n    QMap<QChar, QString> extractArgs( const QString& line );\n    QString requiredArgs( PlayerCommand );\n    Track extractTrack( const QMap<QChar, QString>& args );\n\n    PlayerCommand m_command;\n    QString m_playerId;\n    Track m_track;\n    QString m_username;\n    QString m_applicationPath;\n};\n\n#endif // PLAYER_COMMAND_PARSER_H\n"
  },
  {
    "path": "lib/listener/PlayerConnection.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlayerConnection.h\"\n#include <QtAlgorithms>\n#include <QDebug>\n#include <QTimer>\n\n\nclass Error\n{   \n    const char* m_msg;\nprotected:\n    Error( const char* msg ) : m_msg( msg ) {}\n    virtual ~Error() {}\npublic:\n    const char* message() const { return m_msg; }\n    \n    virtual bool isFatal() const { return false; }\n};\n\nstruct NonFatalError : public Error\n{\n    NonFatalError( const char* msg ) : Error( msg ) {}    \n};\n\nstruct FatalError : public Error\n{\n    FatalError( const char* msg ) : Error( msg ) {}\n    virtual bool isFatal() const { return true; }\n};\n\nPlayerConnection::PlayerConnection()\n    : m_elapsed( 0 ), m_state( Stopped )\n{\n}\n\nPlayerConnection::PlayerConnection( const QString& id, const QString& name, QObject* parent )\n    :QObject( parent )\n    , m_id( id )\n    , m_name( name )\n    , m_elapsed( 0 )\n    , m_state( Stopped )\n{\n    Q_ASSERT( id.size() );\n}\n\n\nvoid PlayerConnection::forceTrackStarted( const Track& t )\n{\n    emit trackStarted( track(), t );\n}\n\nvoid PlayerConnection::forcePaused()\n{\n    emit paused();\n}\n\nvoid\nPlayerConnection::handleCommand( PlayerCommand command, Track t )\n{\n    qDebug() << command;\n\n    try\n    {\n        switch (command)\n        {\n            case CommandStart:\n                if (t.isNull()) throw FatalError(\"Can't start a null track\");\n                m_state = Playing;\n                if ( m_stoppedTimer ) m_stoppedTimer->stop();\n                if (t == m_track\n                        && t.timestamp() == m_track.timestamp())\n                {\n                    emit resumed();\n                    throw NonFatalError(\"Already playing this track\");\n                }\n                qSwap(m_track, t);\n                m_elapsed = 0;\n                emit trackStarted( m_track, t );\n                break;\n                \n            case CommandPause:\n                if (m_track.isNull()) throw FatalError(\"Cannot pause a null track\");\n                if (m_state == Paused) throw NonFatalError(\"Already paused\");\n                m_state = Paused;\n                emit paused();\n                break;\n\n            case CommandResume:\n                if (m_track.isNull()) throw FatalError(\"Can't resume null track\");\n                if (m_state == Playing) throw NonFatalError(\"Already playing\");\n                m_state = Playing;\n                emit resumed();\n                break;\n\n            case CommandTerm:\n            case CommandInit:\n            case CommandStop:\n                // don't process the stop straight away because we could be skipping\n                // track so wait a second to make sure we don't get a start command\n                if ( !m_stoppedTimer )\n                {\n                    m_stoppedTimer = new QTimer( this );\n                    m_stoppedTimer->setSingleShot( true );\n                    m_stoppedTimer->setInterval( 1000 );\n                    connect( m_stoppedTimer, SIGNAL(timeout()), this, SLOT(onStopped()) );\n                }\n\n                m_stoppedTimer->start();\n                break;\n                \n            case CommandBootstrap:\n\t\t\t\temit bootstrapReady( id() );\n                break;\n        }\n        \n    }\n    catch (Error& error)\n    {\n        qWarning() << error.message();\n\n        if (error.isFatal())\n        {\n            m_state = Stopped;\n            m_track = Track();\n            emit stopped();\n        }\n    }\n}\n\nvoid\nPlayerConnection::onStopped()\n{\n    m_track = Track();\n\n    if (m_state == Stopped)\n    {\n        qWarning() << \"Already stopped\";\n    }\n    else\n    {\n        m_state = Stopped;\n        m_elapsed = 0;\n        emit stopped();\n    }\n}\n"
  },
  {
    "path": "lib/listener/PlayerConnection.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYER_CONNECTION_H\n#define PLAYER_CONNECTION_H\n\n#include \"lib/DllExportMacro.h\"\n#include \"PlayerCommand.h\"\n#include \"State.h\"\n#include <lastfm/Track.h>\n#include <QTimer>\n#include <QPointer>\n\n\n/** delete yourself when the player closes/quits */\nclass LISTENER_DLLEXPORT PlayerConnection : public QObject\n{\n    Q_OBJECT\nprotected:\n    QPointer<QTimer> m_stoppedTimer;\n    QString const m_id;\n    QString const m_name;   \n    uint m_elapsed;\n\n    PlayerConnection();\n    \n    State m_state;\n    Track m_track;\n    \npublic:    \n    PlayerConnection( const QString& id, const QString& name, QObject* parent = 0 );\n    \n    ~PlayerConnection()\n    {\n        bool const wasStopped = m_state == Stopped;\n        clear();\n        if (!wasStopped)\n            emit stopped();\n    }\n\n    QString name() const { return m_name; }\n    QString id() const { return m_id; }\n    virtual Track track() const { return m_track; }\n    virtual State state() const { return m_state; }\n\n    /** 0 until we are paused and made non-current by the mediator\n     * then we store elapsed_scrobble_time */\n    void setElapsed( uint i ) { m_elapsed = i; }\n    uint elapsed() const { return m_elapsed; }\n    \n    void clear() { m_state = Stopped; m_track = Track(); m_elapsed = 0; }\n    \n    /** only pass the track for CommandStart */\n    void handleCommand( PlayerCommand, Track = Track() );    \n\n    void forceTrackStarted( const Track& );\n    void forcePaused();\n    \nsignals:\n    void trackStarted( const lastfm::Track&, const lastfm::Track& );\n    void paused();\n    void resumed();\n    void stopped();\n\tvoid bootstrapReady( const QString& playerId );\n\nprivate slots:\n    void onStopped();\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/PlayerListener.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlayerListener.h\"\n#include \"PlayerCommandParser.h\"\n#include \"PlayerConnection.h\"\n#include <QLocalSocket>\n#include <QDir>\n#include <QFile>\n#include <QThread>\n\n#ifdef Q_OS_WIN\n#include \"win/NamedPipeServer.h\"\n#else\n#include <lastfm/misc.h>\n#endif\n\nPlayerListener::PlayerListener( QObject* parent )\n              : QLocalServer( parent )\n{\n    connect( this, SIGNAL(newConnection()), SLOT(onNewConnection()) );\n\n    // Create a user-unique name to listen on.\n    // User-unique so that different logged-on users \n    // can run their own scrobbler instances.\n\n#ifdef Q_OS_WIN\n\n    NamedPipeServer* namedPipeServer = new NamedPipeServer( this );\n    connect( namedPipeServer, SIGNAL(lineReady(QString)), this, SLOT(processLine(QString)), Qt::BlockingQueuedConnection );\n    namedPipeServer->start();\n\n#else\n    QString const name = \"lastfm_scrobsub\";\n\n    // on windows we use named pipes which auto-delete\n    // *nix platforms need more help:\n\n    QString fullPath = lastfm::dir::runtimeData().absolutePath() + \"/\" + name;\n    if( QFile::exists( fullPath ))\n        QFile::remove( fullPath );\n\n    bool success = listen( fullPath );\n    Q_ASSERT( success );\n#endif\n}\n\nvoid\nPlayerListener::onNewConnection()\n{\n    qDebug() << hasPendingConnections();\n\n    while (hasPendingConnections())\n    {\n        QObject* o = nextPendingConnection();\n        connect( o, SIGNAL(readyRead()), SLOT(onDataReady()) );\n        connect( o, SIGNAL(disconnected()), o, SLOT(deleteLater()) );\n    }\n}\n\nvoid\nPlayerListener::onDataReady()\n{\n    QLocalSocket* socket = qobject_cast<QLocalSocket*>(sender());\n    if (!socket) return;\n\n    while (socket->canReadLine())\n    {\n        QString const line = QString::fromUtf8( socket->readLine() );\n        QString response = processLine( line );\n        socket->write( response.toUtf8() );\n    }\n}\n\nQString\nPlayerListener::processLine( const QString& line )\n{\n    QString response = \"OK\\n\";\n\n    try\n    {\n        PlayerCommandParser parser( line );\n        QString const id = parser.playerId();\n        PlayerConnection* connection = 0;\n\n        if (!m_connections.contains( id ))\n        {\n            connection = m_connections[id] = new PlayerConnection( parser.playerId(), parser.playerName() );\n            emit newConnection( connection );\n        }\n        else\n            connection = m_connections[id];\n\n        switch (parser.command())\n        {\n            case CommandBootstrap:\n                emit bootstrapCompleted( parser.playerId() );\n                break;\n\n            case CommandTerm:\n                delete connection;\n                m_connections.remove( parser.playerId() );\n                break;\n\n            default:\n                connection->handleCommand( parser.command(), parser.track() );\n                break;\n        }\n    }\n    catch (std::invalid_argument& e)\n    {\n        qWarning() << e.what();\n        response = \"ERROR: \" + QString::fromStdString(e.what()) + \"\\n\";\n    }\n\n    return response;\n}\n"
  },
  {
    "path": "lib/listener/PlayerListener.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYER_LISTENER_H\n#define PLAYER_LISTENER_H\n\n#include <QLocalServer>\n#include <QMap>\n\n#include \"common/HideStupidWarnings.h\"\n#include \"PlayerConnection.h\"\n#include \"lib/DllExportMacro.h\"\n\n/** listens to external clients via a TcpSocket and notifies a receiver to their\n  * commands */\nclass LISTENER_DLLEXPORT PlayerListener : public QLocalServer\n{\n    Q_OBJECT\n\npublic:\n    explicit PlayerListener( QObject* parent = 0 );\n\nsignals:\n    void newConnection( class PlayerConnection* );\n    void bootstrapCompleted( const QString& playerId );\n\nprivate slots:\n    void onNewConnection();\n    void onDataReady();\n\n    QString processLine( const QString& line );\n\nprivate:    \n    QMap<QString, PlayerConnection*> m_connections;\n};\n\n\n#endif\n"
  },
  {
    "path": "lib/listener/PlayerMediator.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"PlayerMediator.h\"\n\n\nPlayerMediator::PlayerMediator( QObject* parent )\n              : QObject( parent )\n{}\n\n\nvoid\nPlayerMediator::follow( PlayerConnection* connection )\n{\n    if (m_connections.contains( connection )) { qWarning() << \"Already following:\" << connection; return; }\n    \n    m_connections += connection;\n\n    connect( connection, SIGNAL(trackStarted(lastfm::Track,lastfm::Track)), SLOT(onActivity()) );\n    connect( connection, SIGNAL(resumed()), SLOT(onActivity()) );\n    connect( connection, SIGNAL(stopped()), SLOT(onActivity()) );\n    connect( connection, SIGNAL(bootstrapReady(QString)), SLOT(onActivity()) );\n    connect( connection, SIGNAL(destroyed()), SLOT(onDestroyed()) );\n\n    assess( connection );\n}\n\n\nvoid\nPlayerMediator::onActivity()\n{\n    PlayerConnection* connection = qobject_cast<PlayerConnection*>(sender());\n\n    if (m_active == connection)\n    {\n        if (connection->state() == Stopped)\n        {\n            foreach (PlayerConnection* connection, m_connections)\n                if (connection != m_active && assess( connection ))\n                        return;\n        }\n    }\n    else\n        assess( connection );\n}\n\n\nbool\nPlayerMediator::assess( PlayerConnection* connection )\n{\n    Q_ASSERT( connection );\n    \n    if (!m_active)\n        goto set_active;\n    \n    if ( m_active->state() == Stopped || m_active->state() == Paused\n         || connection->id() == \"ass\" ) // the radio connection steals from all other sources\n    {\n        switch ( connection->state() )\n        {\n            case Playing:\n                goto set_active;\n\n            case TuningIn:\n            case Buffering:\n                qWarning() << \"Unsupported state for PlayerConnection\";\n                break;                \n\n            default:\n            case Stopped:\n            case Paused:\n                break;\n        }\n    }\n    \n    return false;\n    \nset_active:\n    if (!connection)\n        return false;\n\n    m_active = connection;\n    emit activeConnectionChanged( connection );\n\n    return true;\n}\n\n\nvoid \nPlayerMediator::onDestroyed()\n{\n    m_connections.removeAll( (PlayerConnection*) this->sender() );\n}\n"
  },
  {
    "path": "lib/listener/PlayerMediator.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QList>\n#include <QPointer>\n\n#include \"lib/DllExportMacro.h\"\n#include \"PlayerConnection.h\"\n\nclass PlayerConnection;\n\n\n/** Usage, add PlayerConnections, seek() for the active one, when active \n  * connection is available the newActiveConnection() signal will be emitted\n  * the ActionConnection will then stop seeking until you next call seek() */\nclass LISTENER_DLLEXPORT PlayerMediator : public QObject\n{\n    Q_OBJECT\n\n    QList<PlayerConnection*> m_connections;\n\nprotected:\n    QPointer<PlayerConnection> m_active;\n    virtual bool assess( PlayerConnection* );\n\npublic:\n    PlayerMediator( QObject* parent );\n        \n    PlayerConnection* activeConnection() const { return m_active; }\n\npublic slots:\n    void follow( PlayerConnection* );\n    \nsignals:\n    void activeConnectionChanged( PlayerConnection* );\n\nprivate slots:\n    void onActivity();\n    void onDestroyed();\n};\n"
  },
  {
    "path": "lib/listener/State.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYER_STATE_H\n#define PLAYER_STATE_H\n\nenum State\n{\n    Unknown,\n    Stopped,\n    TuningIn,\n    Buffering,\n    Playing,\n    Paused\n};\n\n\n#include <QDebug>\ninline QDebug operator<<( QDebug d, State state )\n{\n    #define _( x ) x: return d << #x\n\tswitch (state)\n\t{\n        case _(Unknown);\n\t\tcase _(Stopped);\n\t\tcase _(TuningIn);\n\t\tcase _(Playing);\n        case _(Buffering);\n        case _(Paused);\n\t}\n    return d;\n}\n\n#endif\n"
  },
  {
    "path": "lib/listener/legacy/LegacyPlayerListener.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"LegacyPlayerListener.h\"\n#include \"../PlayerCommandParser.h\"\n#include \"../PlayerConnection.h\"\n#include <QTcpSocket>\n\n\nLegacyPlayerListener::LegacyPlayerListener( QObject* parent )\n                    : QTcpServer( parent )\n{\n    connect( this, SIGNAL(newConnection()), SLOT(onNewConnection()) );\n    if (!listen( QHostAddress::LocalHost, port() ))\n        qWarning() << \"Couldn't start legacy player listener\";\n}\n\n\nvoid\nLegacyPlayerListener::onNewConnection()\n{\n    while (hasPendingConnections())\n    {\n        QTcpSocket* socket = nextPendingConnection();\n        connect( socket, SIGNAL(readyRead()), SLOT(onDataReady()) );\n    }\n}\n\n\nvoid\nLegacyPlayerListener::onDataReady()\n{\n    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());\n    if (!socket) return;\n\n    connect( socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()) );    \n    \n    while (socket->canReadLine())\n    {\n        QString line = QString::fromUtf8( socket->readLine() );\n        \n\t\ttry\n        {\n            PlayerCommandParser parser( line );\n\n            QString const id = parser.playerId();\n            PlayerConnection* connection = 0;\n\n            if (!m_connections.contains( id )) {\n                connection = m_connections[id] = new PlayerConnection( parser.playerId(), parser.playerName() );\n                emit newConnection( connection );\n            }\n            else\n                connection = m_connections[id];\n            \n            switch (parser.command())\n            {\n                case CommandTerm:\n                    m_connections.remove( id );\n                    // FALL THROUGH\n                    \n                default:\n                    connection->handleCommand( parser.command(), parser.track() );\n                    break;\n            }\n            \n            socket->write( \"OK\\n\" );\n        }\n        catch (std::invalid_argument& e)\n        {\n            QString const error = QString::fromUtf8( e.what() );\n            qWarning() << line << error;\n            QString s = \"ERROR: \" + error + \"\\n\";\n            socket->write( s.toUtf8() );\n        }\n    }\n    \n    socket->close();\n}\n"
  },
  {
    "path": "lib/listener/legacy/LegacyPlayerListener.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef LEGACY_PLAYER_LISTENER_H\n#define LEGACY_PLAYER_LISTENER_H\n\n#include \"lib/DllExportMacro.h\"\n#include \"../PlayerConnection.h\"\n#include <QTcpServer>\n#include <QMap>\nclass PlayerConnection;\n\n\n/** listens to external clients via a TcpSocket and notifies a receiver to their\n  * commands */\nclass LISTENER_DLLEXPORT LegacyPlayerListener : public QTcpServer\n{\n    Q_OBJECT\n\npublic:\n    LegacyPlayerListener( QObject* parent );\n    \n    static uint port() { return 33367; }\n    \nsignals:\n    void newConnection( class PlayerConnection* );\n    \nprivate slots:\n    void onNewConnection();\n    void onDataReady();\n\nprivate:\n    /** handles the TERM command as conecerning this class */\n    void term( QTcpSocket* );\n\n    QMap<QString, PlayerConnection*> m_connections;\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/listener.pro",
    "content": "TARGET = listener\nTEMPLATE = lib\nQT = core xml network\nCONFIG += unicorn logger\nunix:!mac {\n    CONFIG += staticlib\n    QMAKE_DISTCLEAN += -f ../../_bin/liblistener.a\n}\n\ninclude( ../../admin/include.qmake )\n\nDEFINES += _LISTENER_DLLEXPORT LASTFM_COLLAPSE_NAMESPACE\n\nwin32:LIBS += Advapi32.lib User32.lib\n\nSOURCES += \\\n\tPlayerMediator.cpp \\\n\tPlayerListener.cpp \\\n\tPlayerConnection.cpp \\\n\tPlayerCommandParser.cpp \\\n        legacy/LegacyPlayerListener.cpp\n\nHEADERS += \\\n\tState.h \\\n\tPlayerMediator.h \\\n\tPlayerListener.h \\\n\tPlayerConnection.h \\\n\tPlayerCommandParser.h \\\n\tPlayerCommand.h \\\n        legacy/LegacyPlayerListener.h\n\nunix:!mac {\n    QT += dbus\n    SOURCES -= legacy/LegacyPlayerListener.cpp\n    HEADERS -= legacy/LegacyPlayerListener.h\n    SOURCES += mpris2/Mpris2Listener.cpp \\\n               mpris2/Mpris2Service.cpp\n    HEADERS += mpris2/Mpris2Listener.h \\\n               mpris2/Mpris2Service.h\n}\n\nmac {\n    SOURCES += mac/ITunesListener.cpp\n\n    OBJECTIVE_SOURCES += mac/SpotifyListener.mm\n\n    HEADERS += mac/ITunesListener.h \\\n                    mac/SpotifyListener.h\n\n    LIBS += -weak_framework AppKit\n}\n\nwin32 {\n    SOURCES += win/SpotifyListener.cpp \\\n               win/NamedPipeServer.cpp \\\n               ../../plugins/iTunes/ITunesTrack.cpp \\\n               ../../plugins/iTunes/ITunesComWrapper.cpp \\\n               $$ROOT_DIR/plugins/scrobsub/EncodingUtils.cpp \\\n               $$ROOT_DIR/lib/3rdparty/iTunesCOMAPI/iTunesCOMInterface_i.c\n\n    HEADERS += win/SpotifyListener.h \\\n               win/NamedPipeServer.h \\\n               ../../plugins/iTunes/ITunesTrack.h \\\n               ../../plugins/iTunes/ITunesComWrapper.h \\\n               ../../plugins/iTunes/ITunesEventInterface.h \\\n               ../../plugins/iTunes/ITunesExceptions.h \\\n               $$ROOT_DIR/plugins/scrobsub/EncodingUtils.h\n\n    LIBS += -lcomsuppw\n\n    DEFINES += _WIN32_DCOM\n}\n"
  },
  {
    "path": "lib/listener/mac/ITunesListener.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <lastfm/misc.h>\n\n#include \"ITunesListener.h\"\n#include \"../PlayerConnection.h\"\n\nstruct ITunesConnection : PlayerConnection\n{\n    // PlayerConnection has compile-time constants for these.\n    QString const m_runtime_name;\n    QString const m_runtime_id;\n\n    QString runtimeName() const { return m_runtime_name; }\n    QString runtimeId() const { return m_runtime_id; }\n\n    ITunesConnection(bool isAppleMusic) : PlayerConnection( \"osx\", \"iTunes\" )\n    , m_runtime_name( isAppleMusic ? \"Apple Music\" : \"iTunes\" )\n    , m_runtime_id(   isAppleMusic ? \"mac\"         : \"osx\" )\n    {}\n\n    void start( const Track& t )\n    {\n        MutableTrack mt( t );\n        mt.setSource( Track::Player );\n        mt.setExtra( \"playerId\", runtimeId() );\n        mt.setExtra( \"playerName\", runtimeName() );\n        mt.stamp();\n        handleCommand( CommandStart, t ); \n    }\n\n    void pause() { handleCommand( CommandPause ); }\n    void resume() { handleCommand( CommandResume ); }\n    void stop() { handleCommand( CommandStop ); }\n};\n\nITunesListener::ITunesListener( QObject* parent )\n    : QObject( parent )\n    , m_previousPid()\n    , m_playerAppId( getPlayerAppId() )\n    , m_connection( 0 ) \n{\n    qDebug() << \"Detected player app ID: \" << m_playerAppId;\n    qRegisterMetaType<Track>(\"Track\");\n\n    QString mediaTypeFields = isAppleMusic()\n        ? \"\\\"false\\\" & \\\"\\n\\\" & \\\"none\\\"\\n\"\n        : \"podcast & \\\"\\n\\\" & video kind\\n\";\n\n    m_currentTrackScript = AppleScript(\n        \"tell application id \\\"\" + m_playerAppId + \"\\\" to tell current track\\n\"\n            \"try\\n\"\n                \"set L to location\\n\"\n                \"set L to POSIX path of L\\n\"\n            \"on error\\n\"\n                \"set L to \\\"\\\"\\n\"\n            \"end try\\n\"\n            \"return artist & \\\"\\n\\\" & \"\n                    \"album artist & \\\"\\n\\\" & \"\n                    \"album & \\\"\\n\\\" & \"\n                    \"name & \\\"\\n\\\" & \"\n                    \"(duration as integer) & \\\"\\n\\\" & \"\n                    \"L & \\\"\\n\\\" & \"\n                    \"persistent ID & \\\"\\n\\\" & \" +\n                    mediaTypeFields +\n        \"end tell\"\n    );\n\n    QString name = m_playerAppId + \".playerInfo\";\n    CFNotificationCenterAddObserver(\n        CFNotificationCenterGetDistributedCenter(),\n        this,\n        callback,\n        CFStringCreateWithCString( NULL, name.toStdString().c_str(), kCFStringEncodingASCII ),\n        NULL,\n        CFNotificationSuspensionBehaviorDeliverImmediately\n    );\n\n    QMetaObject::invokeMethod( this, \"setupCurrentTrack\", Qt::QueuedConnection );\n}\n\n\nITunesListener::~ITunesListener()\n{\n    delete m_connection;\n}\n\n\nbool\nITunesListener::isAppleMusic()\n{\n    return m_playerAppId == \"com.apple.Music\";\n}\n\n    \nvoid\nITunesListener::callback( CFNotificationCenterRef, void* observer, CFStringRef, const void*, CFDictionaryRef info )\n{    \n    static_cast<ITunesListener*>(observer)->callback( info );\n}\n\n\n/*******************************************************************************\n  * code-clarity-class used by callback() */\nclass ITunesDictionaryHelper\n{   \n    CFDictionaryRef const m_info; // leave here or risk an initialisation bug\n    \npublic:\n    ITunesDictionaryHelper( CFDictionaryRef info ) \n            : m_info( info ), \n              state( getState() )\n    {}\n\n    void determineTrackInformation();\n        \n    QString artist, name, album, path, pid;\n    int duration;\n    ITunesListener::State const state; // *MUST* be after m_info\n    \nprivate:\n    template <typename T> T\n    token( CFStringRef t )\n    {\n        return (T) CFDictionaryGetValue( m_info, t );\n    }\n\n    ITunesListener::State\n    getState()\n    {\n        CFStringRef state = token<CFStringRef>( CFSTR(\"Player State\") );\n\n        #define compare( x ) if (CFStringCompare( state, CFSTR( #x ), 0 ) == kCFCompareEqualTo) return ITunesListener::x\n        compare( Playing );\n        compare( Paused );\n        compare( Stopped );\n        #undef compare\n        \n        return ITunesListener::Unknown;\n    }\n};\n\n\ntemplate <> QString\nITunesDictionaryHelper::token<QString>( CFStringRef t )\n{\n    CFStringRef s = token<CFStringRef>( t );\n    return lastfm::CFStringToQString( s );\n}   \n\n\ntemplate <> int\nITunesDictionaryHelper::token<int>( CFStringRef t )\n{\n    int i = 0;\n    CFNumberRef n = token<CFNumberRef>( t );\n    if (n) CFNumberGetValue( n, kCFNumberIntType, &i );\n    return i;\n}\n\n\nvoid\nITunesDictionaryHelper::determineTrackInformation()\n{\n    duration = token<int>( CFSTR(\"Total Time\") ) / 1000;\n    artist = token<QString>( CFSTR(\"Artist\") );\n    album = token<QString>( CFSTR(\"Album\") );\n    name = token<QString>( CFSTR(\"Name\") );\n    pid = QString::number( token<int>( CFSTR(\"PersistentID\") ) );\n    \n    // Get path decoded - iTunes encodes the file location as URL\n    CFStringRef location = token<CFStringRef>( CFSTR(\"Location\") );\n    QUrl url = QUrl::fromEncoded( lastfm::CFStringToUtf8( location ) );\n    path = url.toString().remove( \"file://localhost\" );\n}\n/******************************************************************************/\n\n\nstatic inline QString\nencodeAmp( QString data ) \n{ \n    return data.replace( '&', \"&&\" );\n}\n\n\nvoid\nITunesListener::callback( CFDictionaryRef info )\n{\n    if ( !m_connection )\n        emit newConnection( m_connection = new ITunesConnection(isAppleMusic()) );\n\n    ITunesDictionaryHelper dict( info );\n    State const previousState = m_state;\n    m_state = dict.state;\n    \n    if ( m_state == Paused )\n        m_connection->pause();\n    else if ( m_state == Stopped )\n        m_connection->stop();\n    else if ( m_state == Playing )\n    {\n        QString output = m_currentTrackScript.exec();\n\n        qDebug() << output;\n\n        if ( !output.isEmpty() )\n        {\n            QTextStream s( &output, QIODevice::ReadOnly | QIODevice::Text );\n\n            QString artist = s.readLine();\n            QString albumArtist = s.readLine();\n            QString album = s.readLine();\n            QString track = s.readLine();\n            QString duration = s.readLine();\n            QString path = s.readLine();\n            QString pid = s.readLine();\n            bool podcast = s.readLine() == \"true\";\n            QString videoKind = s.readLine();\n            bool video = videoKind != \"none\" && videoKind != \"music video\";\n\n            // if the track is restarted it has the same pid\n            if ( m_previousPid == pid && previousState == Paused )\n                m_connection->resume();\n            else\n            {\n                MutableTrack t;\n                t.setArtist( artist );\n                t.setAlbumArtist( albumArtist );\n                t.setTitle( track );\n                t.setAlbum( album );\n                t.setDuration( duration.toInt() );\n                t.setUrl( QUrl::fromLocalFile( path ) );\n                t.setPodcast( podcast );\n                t.setVideo( video );\n                m_connection->start( t );\n            }\n\n            m_previousPid = pid;\n        }\n        else\n            m_connection->stop();\n    }\n    else\n          qWarning() << \"Unknown state.\";\n\n}\n\nQString //static\nITunesListener::getPlayerAppId()\n{\n    const char* code = \n    \"try\\n\"\n        \"tell me to get application id \\\"com.apple.Music\\\"\\n\"\n        \"return \\\"com.apple.Music\\\"\\n\"\n    \"on error\\n\"\n        \"return \\\"com.apple.iTunes\\\"\\n\"\n    \"end try\\n\";\n    return AppleScript( code ).exec();\n}\n\nbool //static\nITunesListener::isPlaying()\n{\n    QString code = \"tell application id \\\"\" + m_playerAppId + \"\\\" to if running then return player state is playing\";\n    return AppleScript( code ).exec() == \"true\";\n}\n\nvoid\nITunesListener::setupCurrentTrack()\n{  \n    if ( !isPlaying() )\n        return;\n\n    QString output = m_currentTrackScript.exec();\n\n    qDebug() << output;\n\n    if ( !output.isEmpty() )\n    {\n        QTextStream s( &output, QIODevice::ReadOnly | QIODevice::Text );\n\n        QString artist = s.readLine();\n        QString albumArtist = s.readLine();\n        QString album = s.readLine();\n        QString track = s.readLine();\n        QString duration = s.readLine();\n        QString path = s.readLine();\n        QString persistentID = s.readLine();\n        bool podcast = s.readLine() == \"true\";\n        QString videoKind = s.readLine();\n        bool video = videoKind != \"none\" && videoKind != \"music video\";\n\n        m_previousPid = persistentID;\n\n        MutableTrack t;\n        t.setArtist( artist );\n        t.setAlbumArtist( albumArtist );\n        t.setTitle( track );\n        t.setAlbum( album );\n        t.setDuration( duration.toInt() );\n        t.setUrl( QUrl::fromLocalFile( path ) );\n        t.setPodcast( podcast );\n        t.setVideo( video );\n\n        if ( !m_connection )\n            emit newConnection( m_connection = new ITunesConnection(isAppleMusic()) );\n\n        m_connection->start( t );\n    }\n}\n"
  },
  {
    "path": "lib/listener/mac/ITunesListener.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ITUNES_SCRIPT_H\n#define ITUNES_SCRIPT_H\n\n#include <QThread>\n#include <CoreFoundation/CoreFoundation.h>\n\n#include \"lib/unicorn/mac/AppleScript.h\"\n\n/** @author Max Howell <max@last.fm> */\nclass ITunesListener : public QObject\n{\n    Q_OBJECT\npublic:\n    ITunesListener( QObject* parent );\n    ~ITunesListener();\n\n    enum State { Unknown = -1, Playing, Paused, Stopped };\n\n    static QString getPlayerAppId();\n\nsignals:\n    void newConnection( class PlayerConnection* );\n    \nprivate:\n\n    /** iTunes notification center callback */\n    static void callback( CFNotificationCenterRef, \n                          void*, \n                          CFStringRef, \n                          const void*, \n                          CFDictionaryRef );\n\n    void callback( CFDictionaryRef );\n\n    bool isPlaying();\n\n    bool isAppleMusic();\n\nprivate slots:\n    void setupCurrentTrack();\n\nprivate:\n    State m_state;\n    QString m_previousPid;\n    QString m_playerAppId;\n    struct ITunesConnection* m_connection;\n\n    AppleScript m_currentTrackScript;\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/mac/SpotifyListener.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SPOTIFY_LISTENER_H\n#define SPOTIFY_LISTENER_H\n\n#include <QObject>\n#include <QPointer>\n\n#include <lastfm/Track.h>\n\nclass SpotifyListenerMac : public QObject\n{\n    Q_OBJECT\npublic:\n    SpotifyListenerMac( QObject* parent );\n    ~SpotifyListenerMac();\n\nsignals:\n    void newConnection( class PlayerConnection* );\n\nprivate slots:\n    void loop();\n\nprivate:\n    QString m_lastPlayerState;\n    lastfm::Track m_lastTrack;\n    QPointer<struct SpotifyConnection> m_connection;\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/mac/SpotifyListener.mm",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <AppKit/NSWorkspace.h>\n\n#include <lastfm/Track.h>\n#include <lastfm/misc.h>\n\n#include \"lib/unicorn/mac/AppleScript.h\"\n\n#include \"../PlayerConnection.h\"\n#include \"SpotifyListener.h\"\n\nstruct SpotifyConnection : public PlayerConnection\n{\n    SpotifyConnection() : PlayerConnection( \"spt\", \"Spotify\" )\n    {}\n\n    void start( const Track& t )\n    {\n        MutableTrack mt( t );\n        mt.setSource( Track::Player );\n        mt.setExtra( \"playerId\", this->id() );\n        mt.setExtra( \"playerName\", name() );\n        mt.stamp();\n        handleCommand( CommandStart, t );\n    }\n\n    void pause() { handleCommand( CommandPause ); }\n    void resume() { handleCommand( CommandResume ); }\n    void stop() { handleCommand( CommandStop ); }\n};\n\n\nSpotifyListenerMac::SpotifyListenerMac( QObject* parent )\n    :QObject( parent )\n{\n    if ( [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@\"com.spotify.client\"] != nil )\n    {\n        QTimer* timer = new QTimer( this );\n        timer->start( 1000 );\n        connect( timer, SIGNAL(timeout()), SLOT(loop()));\n    }\n}\n\nSpotifyListenerMac::~SpotifyListenerMac()\n{\n    delete m_connection;\n}\n\nvoid\nSpotifyListenerMac::loop()\n{\n    static AppleScript playerStateScript( \"tell application id \\\"com.spotify.client\\\" to if running then return player state\" );\n    QString playerState = playerStateScript.exec();\n\n    if ( playerState == \"playing\"\n         || playerState == \"stopped\"\n         || playerState == \"paused\" )\n    {\n        if ( !m_connection )\n            emit newConnection( m_connection = new SpotifyConnection );\n\n        static AppleScript titleScript( \"tell application id \\\"com.spotify.client\\\" to return name of current track\" );\n        static AppleScript albumScript( \"tell application id \\\"com.spotify.client\\\" to return album of current track\" );\n        static AppleScript artistScript( \"tell application id \\\"com.spotify.client\\\" to return artist of current track\" );\n        static AppleScript albumArtistScript( \"tell application id \\\"com.spotify.client\\\" to return album artist of current track\" );\n        static AppleScript durationScript( \"tell application id \\\"com.spotify.client\\\" to return duration of current track\" );\n\n        if ( playerState == \"playing\" )\n        {\n            lastfm::MutableTrack t;\n            t.setTitle( titleScript.exec() );\n            t.setAlbum( albumScript.exec() );\n            t.setArtist( artistScript.exec() );\n            t.setAlbumArtist( albumArtistScript.exec() );\n            t.setDuration( durationScript.exec().toInt() );\n\n            if ( t != m_lastTrack )\n            {\n                if ( t.album().title().startsWith( \"http://\" )\n                     || t.album().title().startsWith( \"https://\" )\n                     || t.album().title().startsWith( \"spotify:\" ) )\n                {\n                    // this is an advert so don't try to display metadata\n                    // and stop any currently playing track\n                    if ( m_lastPlayerState == \"playing\" || m_lastPlayerState == \"paused\" )\n                        m_connection->stop();\n                }\n                else\n                {\n                    m_connection->start( t );\n                }\n            }\n            else if ( m_lastPlayerState == \"paused\" )\n                m_connection->resume();\n\n            m_lastTrack = t;\n        }\n        else if ( m_lastPlayerState != playerState )\n        {\n            if ( playerState == \"stopped\" )\n            {\n                m_connection->stop();\n                m_lastTrack = Track();\n            }\n            else if ( playerState == \"paused\" )\n                m_connection->pause();\n        }\n    }\n    else\n    {\n        if ( m_lastPlayerState == \"playing\" || m_lastPlayerState == \"paused\" )\n            m_connection->stop();\n\n        delete m_connection;\n    }\n\n    m_lastPlayerState = playerState;\n}\n\n\n"
  },
  {
    "path": "lib/listener/mpris2/Mpris2Listener.cpp",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Mpris2Listener.h\"\n#include \"Mpris2Service.h\"\n#include \"../PlayerConnection.h\"\n\n#include <QDBusConnectionInterface>\n#include <QRegExp>\n\n\nclass Mpris2Connection : public PlayerConnection\n{\npublic:\n    Mpris2Connection() : PlayerConnection( \"mpris2\", \"\" )\n    {}\n\n    void start( const Track& t )\n    {\n        MutableTrack mt( t );\n        mt.setSource( Track::Player );\n        mt.setExtra( \"playerId\", id() );\n        mt.stamp();\n        handleCommand( CommandStart, t );\n    }\n\n    void pause() { handleCommand( CommandPause ); }\n    void resume() { handleCommand( CommandResume ); }\n    void stop() { handleCommand( CommandStop ); }\n};\n\n\nMpris2Listener::Mpris2Listener( QObject * parent ) : QObject( parent )\n{\n\n    stop();\n\n    QStringList serviceNames = QDBusConnection::sessionBus().interface()->registeredServiceNames().value().filter(QLatin1String(\"org.mpris.MediaPlayer2.\"));\n    foreach( const QString& name, serviceNames )\n    {\n        if ( !name.startsWith( \"org.mpris.MediaPlayer2.\") ||\n             name.endsWith( \"lastfm-scrobbler\" ) )\n            continue;\n        addService( name );\n    }\n    connect( QDBusConnection::sessionBus().interface(),\n            SIGNAL(serviceOwnerChanged(QString,QString,QString)),\n            this,\n            SLOT(onServiceOwnerChanged(QString,QString,QString)));\n}\n\nMpris2Listener::~Mpris2Listener()\n{\n}\n\n\nvoid\nMpris2Listener::createConnection()\n{\n    if ( !m_connection )\n        emit newConnection( m_connection = new Mpris2Connection );\n}\n\n\nvoid\nMpris2Listener::addService( const QString& name )\n{\n    if ( m_services.keys().contains( name ) )\n        return;\n\n    Mpris2Service* service = new Mpris2Service( name, this );\n    m_services.insert( name, service );\n    connect( service,\n             SIGNAL( stateChanged( const QString& )),\n             this,\n             SLOT(onChangedState( const QString& )) );\n}\n\n\nvoid\nMpris2Listener::stop()\n{\n    if ( m_connection )\n        m_connection->stop();\n    m_currentService = QString();\n    m_lastPlayerState = \"Stopped\";\n    m_lastTrack = lastfm::Track();\n}\n\n\nvoid\nMpris2Listener::removeService(const QString& name )\n{\n    if ( m_services.keys().contains( name ) )\n    {\n        if ( name == m_currentService )\n            stop();\n        Mpris2Service * service = m_services.take( name );\n        delete service;\n    }\n}\n\n\nvoid\nMpris2Listener::onServiceOwnerChanged( const QString& name, const QString& oldOwner, const QString& newOwner )\n{\n    if ( !name.startsWith( \"org.mpris.MediaPlayer2.\") ||\n         name.endsWith( \"lastfm-scrobbler\" ) )\n        return;\n\n    if ( oldOwner.isEmpty() && !newOwner.isEmpty() )\n        addService( name );\n    else if ( newOwner.isEmpty() )\n        removeService( name );\n}\n\n\nvoid\nMpris2Listener::onChangedState( const QString& state )\n{\n    Mpris2Service* service = static_cast<Mpris2Service*>(sender());\n\n    // Once a player enters the Playing state, we keep monitoring it until it's\n    // Stopped.  That way players running simultaneously don't fight for the\n    // scrobbler's attention.\n    if ( m_currentService.isEmpty() && state == \"Playing\" )\n        m_currentService = service->name();\n\n    if ( service->name() == m_currentService )\n    {\n        if ( state == \"Playing\" )\n        {\n            MutableTrack t;\n            t.setTitle( service->title() );\n            t.setArtist( service->artist() );\n            if ( service->length() == 0 )\n                t.setDuration( 320 );\n            else\n                t.setDuration( service->length() );\n            if ( !service->url().isEmpty() )\n                t.setUrl( service->url() );\n\n            // Let PlaybackControlsWidget & ProgressBar know the friendly app name\n            t.setExtra( \"playerName\", service->identity() );\n\n            // We also want to add info from the optional DesktopEntry property\n            // and a hint from the service name itself.  This will help\n            // PlaybackControlsWidget find the right application icon to use.\n            if ( !service->desktopEntry().isEmpty() )\n                t.setExtra( \"desktopEntry\", service->desktopEntry() );\n\n            QRegExp rx( \"^org\\\\.mpris\\\\.MediaPlayer2\\\\.([^.]+)\" );\n            if ( rx.indexIn( service->name() ) >= 0 )\n                t.setExtra( \"serviceName\", rx.cap( 1 ) );\n\n            if ( m_lastPlayerState == \"Paused\" && t == m_lastTrack )\n            {\n                m_connection->resume();\n            }\n            else\n            {\n                m_connection->start( t );\n                m_lastTrack = t;\n            }\n        }\n        else if ( state == \"Paused\" )\n        {\n            m_connection->pause();\n        }\n        else if ( state == \"Stopped\" )\n        {\n            stop();\n        }\n        m_lastPlayerState = state;\n    }\n}\n"
  },
  {
    "path": "lib/listener/mpris2/Mpris2Listener.h",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef MPRIS2LISTENER_H\n#define MPRIS2LISTENER_H\n\n#include <QHash>\n#include <QPointer>\n#include <lastfm/Track.h>\n\nclass Mpris2Service;\nclass Mpris2Connection;\nclass PlayerConnection;\n\nclass Mpris2Listener : public QObject\n{\n    Q_OBJECT\npublic:\n    Mpris2Listener( QObject * parent );\n    ~Mpris2Listener();\n    void createConnection();\n\nsignals:\n    void newConnection( PlayerConnection* );\n\nprivate:\n    QHash<QString, Mpris2Service*> m_services;\n    QString m_currentService;\n    QPointer<Mpris2Connection> m_connection;\n    lastfm::Track m_lastTrack;\n    QString m_lastPlayerState;\n\n    void addService( const QString& name );\n    void removeService( const QString& name );\n    void stop();\n\nprivate slots:\n    void onServiceOwnerChanged( const QString& name,\n            const QString& oldOwner,\n            const QString& newOwner );\n    void onChangedState( const QString& state );\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/mpris2/Mpris2Service.cpp",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Mpris2Service.h\"\n\n#include <QDBusInterface>\n#include <QDBusReply>\n#include <QDBusMetaType>\n\n#define MPRIS2_PATH         \"/org/mpris/MediaPlayer2\"\n#define MPRIS2_ROOT_IFACE   \"org.mpris.MediaPlayer2\"\n#define MPRIS2_PLAYER_IFACE \"org.mpris.MediaPlayer2.Player\"\n#define DBUS_PROPS_IFACE    \"org.freedesktop.DBus.Properties\"\n\n\nstatic\nQVariantMap demarshallMetadata(const QVariant &value)\n{\n    if ( !value.canConvert<QDBusArgument>() )\n        return QVariantMap();\n\n    QVariantMap metadata;\n    QDBusArgument arg = value.value<QDBusArgument>();\n    arg >> metadata;\n    return metadata;\n}\n\n\nMpris2Service::Mpris2Service( const QString& name, QObject * parent )\n    : QObject( parent )\n{\n    m_state = \"Stopped\";\n\n    m_propsIface = new QDBusInterface( name,\n            MPRIS2_PATH,\n            DBUS_PROPS_IFACE,\n            QDBusConnection::sessionBus(),\n            this );\n\n    QDBusConnection::sessionBus().connect( name,\n            MPRIS2_PATH,\n            DBUS_PROPS_IFACE,\n            \"PropertiesChanged\",\n            this,\n            SLOT( propsChanged( QString, QVariantMap, QStringList ) )\n            );\n}\n\n\nMpris2Service::~Mpris2Service()\n{\n}\n\n\nQVariant\nMpris2Service::getProp( const QString& interface, const QString& prop ) const\n{\n    QDBusReply<QDBusVariant> reply = m_propsIface->call( \"Get\", interface, prop );\n    if ( !reply.isValid() )\n        return QVariant();\n\n    return reply.value().variant();\n}\n\n\nQString\nMpris2Service::name() const\n{\n    return m_propsIface->service();\n}\n\n\nQString\nMpris2Service::identity() const\n{\n    return getProp( MPRIS2_ROOT_IFACE, \"Identity\" ).toString();\n}\n\n\nQString\nMpris2Service::desktopEntry() const\n{\n    return getProp( MPRIS2_ROOT_IFACE, \"DesktopEntry\" ).toString();\n}\n\n\nQString\nMpris2Service::artist() const\n{\n    QStringList entries = m_metadata.value( \"xesam:artist\" ).toStringList();\n    if ( !entries.isEmpty() )\n        return entries.first();\n    return QString();\n}\n\n\nQString\nMpris2Service::title() const\n{\n    return m_metadata.value( \"xesam:title\" ).toString();\n}\n\n\nuint\nMpris2Service::length() const\n{\n    return m_metadata.value( \"mpris:length\" ).toLongLong() / 1000000;\n}\n\n\nQString\nMpris2Service::url() const\n{\n    return m_metadata.value( \"xesam:url\" ).toString();\n}\n\n\nvoid\nMpris2Service::propsChanged( const QString& str,\n                                  const QVariantMap& changedProperties,\n                                  const QStringList& invalidatedProperties )\n{\n    if ( changedProperties.contains( \"Metadata\" ) )\n        m_metadata = demarshallMetadata( changedProperties.value( \"Metadata\" ) );\n    else if ( invalidatedProperties.contains( \"Metadata\" ) )\n        m_metadata = demarshallMetadata( getProp( MPRIS2_PLAYER_IFACE, \"Metadata\" ) );\n\n    if ( changedProperties.contains( \"PlaybackStatus\" ) &&\n         changedProperties.value( \"PlaybackStatus\" ).toString() != m_state )\n    {\n        m_state = changedProperties.value( \"PlaybackStatus\" ).toString();\n        emit stateChanged( m_state );\n    }\n    else if ( invalidatedProperties.contains( \"PlaybackStatus\" ) )\n    {\n        m_state = getProp( MPRIS2_PLAYER_IFACE, \"PlaybackStatus\" ).toString();\n    }\n}\n"
  },
  {
    "path": "lib/listener/mpris2/Mpris2Service.h",
    "content": "/*\n   Copyright (C) 2013 John Stamp <jstamp@mehercule.net>\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef MPRIS2SERVICE_H\n#define MPRIS2SERVICE_H\n\n#include <QString>\n#include <QVariantMap>\n\nclass QDBusInterface;\n\nclass Mpris2Service : public QObject\n{\n    Q_OBJECT\npublic:\n    Mpris2Service( const QString& name, QObject * parent );\n    ~Mpris2Service();\n\n    QString name() const;\n    QString identity() const;\n    QString desktopEntry() const;\n\n    QString artist() const;\n    QString title() const;\n    uint length() const;\n    QString url() const;\n\nsignals:\n    void stateChanged( const QString& );\n\nprivate:\n    QString m_state;\n    QDBusInterface* m_propsIface;\n    QVariantMap m_metadata;\n\n    QVariant getProp( const QString& interface, const QString& prop ) const;\n\nprivate slots:\n    void propsChanged( const QString& interface,\n            const QVariantMap& changedProperties,\n            const QStringList& invalidatedProperties );\n};\n\n#endif\n"
  },
  {
    "path": "lib/listener/tests/TestPlayerCommandParser.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include <QtTest>\n#include \"PlayerCommandParser.h\"\n\n\nclass TestPlayerCommandParser : public QObject\n{\n    Q_OBJECT\n\nprivate slots:\n    void testStart();\n    void testStop();\n    void testResume();\n    void testPause();\n    void testBootstrap();\n    void testEmptyLine();\n    void testMissingArgument();\n    void testInvalidCommand();\n    void testDuplicatedArgument();\n    void testUnicode();\n};\n\n\nvoid\nTestPlayerCommandParser::testStart()\n{\n    PlayerCommandParser pcp ( \"START c=testapp\"\n                                   \"&a=Test Artist\"\n                                   \"&t=Test Title\"\n                                   \"&b=Test Album\"\n                                   \"&l=100\"\n                                   \"&p=/home/tester/test.mp3\" );\n\n    QCOMPARE( pcp.command(), CommandStart );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n    QCOMPARE( pcp.track().artist(), Artist( \"Test Artist\" ) );\n    QCOMPARE( pcp.track().title(), QString( \"Test Title\" ) );\n    QCOMPARE( pcp.track().album().title(), QString( \"Test Album\" ) );\n    QCOMPARE( pcp.track().duration(), 100u );\n    QCOMPARE( pcp.track().url().path(), QString( \"/home/tester/test.mp3\" ) );\n}\n\nvoid\nTestPlayerCommandParser::testStop()\n{\n    PlayerCommandParser pcp ( \"STOP c=testapp\" );\n\n    QCOMPARE( pcp.command(), CommandStop );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n}\n\nvoid\nTestPlayerCommandParser::testResume()\n{\n    PlayerCommandParser pcp ( \"RESUME c=testapp\" );\n\n    QCOMPARE( pcp.command(), CommandResume );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n}\n\nvoid\nTestPlayerCommandParser::testPause()\n{\n    PlayerCommandParser pcp ( \"PAUSE c=testapp\" );\n\n    QCOMPARE( pcp.command(), CommandPause );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n}\n\nvoid\nTestPlayerCommandParser::testBootstrap()\n{\n    PlayerCommandParser pcp ( \"BOOTSTRAP c=testapp&u=TestUser\" );\n\n    QCOMPARE( pcp.command(), CommandBootstrap );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n    QCOMPARE( pcp.username(), QString( \"TestUser\" ) );\n}\n\nvoid\nTestPlayerCommandParser::testEmptyLine()\n{\n    // The PlayerCommandParser should throw an exception on empty lines\n    try\n    {\n        PlayerCommandParser pcp ( \"\" );\n        \n        QFAIL( \"PlayerCommandParser did not throw an exception on an empty line.\" );\n    }\n    catch ( PlayerCommandParser::Exception e )\n    {\n        // Success\n    }\n}\n\nvoid\nTestPlayerCommandParser::testMissingArgument()\n{\n    // The PlayerCommandParser should throw an exception when arguments are missing\n    try\n    {\n        PlayerCommandParser pcp ( \"START c=testap\" );\n        \n        QFAIL( \"PlayerCommandParser did not throw an exception when arguments are missing.\" );\n    }\n    catch ( PlayerCommandParser::Exception e )\n    {\n        // Success\n    }\n}\n\nvoid\nTestPlayerCommandParser::testInvalidCommand()\n{\n    // The PlayerCommandParser should throw an exception when passed a invalid command\n    try\n    {\n        PlayerCommandParser pcp ( \"SUPERSTART c=testap\" );\n        \n        QFAIL( \"PlayerCommandParser did not throw an exception when passed a invalid command.\" );\n    }\n    catch ( PlayerCommandParser::Exception e )\n    {\n        // Success\n    }\n}\n\nvoid\nTestPlayerCommandParser::testDuplicatedArgument()\n{\n    // The PlayerCommandParser should throw an exception when arguments are duplicated\n    try\n    {\n        PlayerCommandParser pcp ( \"START c=testap&c=testapp2\" );\n        \n        QFAIL( \"PlayerCommandParser did not throw an exception when arguments are duplicated.\" );\n    }\n    catch ( PlayerCommandParser::Exception e )\n    {\n        // Success\n    }\n}\n\nvoid\nTestPlayerCommandParser::testUnicode()\n{\n    PlayerCommandParser pcp( \"START c=testapp\"\n                                   \"&a=佐橋俊彦\"\n                                   \"&t=対峙\"\n                                   \"&b=TV Animation ジパング original Soundtrack\"\n                                   \"&l=123\"\n                                   \"&p=/home/tester/15 対峙.mp3\" );\n\n    QCOMPARE( pcp.command(), CommandStart );\n    QCOMPARE( pcp.playerId(), QString( \"testapp\" ) );\n    QCOMPARE( pcp.track().artist(), Artist( \"佐橋俊彦\" ) );\n    QCOMPARE( pcp.track().title(), QString( \"対峙\" ) );\n    QCOMPARE( pcp.track().album().title(), QString( \"TV Animation ジパング original Soundtrack\" ) );\n    QCOMPARE( pcp.track().duration(), 123u );\n    QCOMPARE( pcp.track().url().path(), QString( \"/home/tester/15 対峙.mp3\" ) );\n}\n\nQTEST_APPLESS_MAIN(TestPlayerCommandParser)\n#include \"TestPlayerCommandParser.moc\"\n\n"
  },
  {
    "path": "lib/listener/tests/test_liblistener.pro",
    "content": "TEMPLATE = app\nQT = testlib\nCONFIG += core types\nINCLUDEPATH += ..\ninclude( admin/include.qmake )\n\nDEFINES += LASTFM_COLLAPSE_NAMESPACE\nSOURCES = TestPlayerCommandParser.cpp ../PlayerCommandParser.cpp\n"
  },
  {
    "path": "lib/listener/win/NamedPipeServer.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n\n#include <windows.h>\n#include <stdio.h>\n#include <tchar.h>\n#include <strsafe.h>\n\n#include \"NamedPipeServer.h\"\n\n#include \"common/c++/win/scrobSubPipeName.cpp\"\n\n#define CONNECTING_STATE 0\n#define READING_STATE 1\n#define WRITING_STATE 2\n#define INSTANCES 8\n#define PIPE_TIMEOUT 5000\n#define BUFSIZE 4096\n\ntypedef struct\n{\n   OVERLAPPED oOverlap;\n   HANDLE hPipeInst;\n   TCHAR chRequest[BUFSIZE];\n   DWORD cbRead;\n   TCHAR chReply[BUFSIZE];\n   DWORD cbToWrite;\n   DWORD dwState;\n   BOOL fPendingIO;\n} PIPEINST, *LPPIPEINST;\n\nPIPEINST Pipe[INSTANCES];\nHANDLE hEvents[INSTANCES];\n\nVOID DisconnectAndReconnect(DWORD i);\nBOOL ConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo);\n\nNamedPipeServer::NamedPipeServer(QObject *parent)\n    :QThread(parent)\n{\n}\n\nvoid\nNamedPipeServer::run()\n{\n   DWORD i, dwWait, cbRet, dwErr;\n   BOOL fSuccess;\n   QByteArray response;\n\n   std::string s;\n   DWORD r = scrobSubPipeName( &s );\n   if (r != 0) throw std::runtime_error( formatWin32Error( r ) );\n   QString const name = QString::fromStdString( s );\n\n// The initial loop creates several instances of a named pipe\n// along with an event object for each instance.  An\n// overlapped ConnectNamedPipe operation is started for\n// each instance.\n\n   for (i = 0; i < INSTANCES; i++)\n   {\n\n   // Create an event object for this instance.\n\n      hEvents[i] = CreateEvent(\n         NULL,    // default security attribute\n         TRUE,    // manual-reset event\n         TRUE,    // initial state = signaled\n         NULL);   // unnamed event object\n\n      if (hEvents[i] == NULL)\n      {\n         printf(\"CreateEvent failed with %d.\\n\", GetLastError());\n         return;\n      }\n\n      Pipe[i].oOverlap.hEvent = hEvents[i];\n\n      Pipe[i].hPipeInst = CreateNamedPipe(\n         (const wchar_t *)name.utf16(),            // pipe name\n         PIPE_ACCESS_DUPLEX |     // read/write access\n         FILE_FLAG_OVERLAPPED,    // overlapped mode\n         PIPE_TYPE_MESSAGE |      // message-type pipe\n         PIPE_READMODE_MESSAGE |  // message-read mode\n         PIPE_WAIT,               // blocking mode\n         INSTANCES,               // number of instances\n         BUFSIZE*sizeof(TCHAR),   // output buffer size\n         BUFSIZE*sizeof(TCHAR),   // input buffer size\n         PIPE_TIMEOUT,            // client time-out\n         NULL);                   // default security attributes\n\n      if (Pipe[i].hPipeInst == INVALID_HANDLE_VALUE)\n      {\n         printf(\"CreateNamedPipe failed with %d.\\n\", GetLastError());\n         return;\n      }\n\n   // Call the subroutine to connect to the new client\n\n      Pipe[i].fPendingIO = ConnectToNewClient(\n         Pipe[i].hPipeInst,\n         &Pipe[i].oOverlap);\n\n      Pipe[i].dwState = Pipe[i].fPendingIO ?\n         CONNECTING_STATE : // still connecting\n         READING_STATE;     // ready to read\n   }\n\n   while (1)\n   {\n   // Wait for the event object to be signaled, indicating\n   // completion of an overlapped read, write, or\n   // connect operation.\n\n      dwWait = WaitForMultipleObjects(\n         INSTANCES,    // number of event objects\n         hEvents,      // array of event objects\n         FALSE,        // does not wait for all\n         INFINITE);    // waits indefinitely\n\n   // dwWait shows which pipe completed the operation.\n\n      i = dwWait - WAIT_OBJECT_0;  // determines which pipe\n      if (i < 0 || i > (INSTANCES - 1))\n      {\n         printf(\"Index out of range.\\n\");\n         return;\n      }\n\n   // Get the result if the operation was pending.\n\n      if (Pipe[i].fPendingIO)\n      {\n         fSuccess = GetOverlappedResult(\n            Pipe[i].hPipeInst, // handle to pipe\n            &Pipe[i].oOverlap, // OVERLAPPED structure\n            &cbRet,            // bytes transferred\n            FALSE);            // do not wait\n\n         switch (Pipe[i].dwState)\n         {\n         // Pending connect operation\n            case CONNECTING_STATE:\n               if (! fSuccess)\n               {\n                   printf(\"Error %d.\\n\", GetLastError());\n                   return;\n               }\n               Pipe[i].dwState = READING_STATE;\n               break;\n\n         // Pending read operation\n            case READING_STATE:\n               if (! fSuccess || cbRet == 0)\n               {\n                  DisconnectAndReconnect(i);\n                  continue;\n               }\n               Pipe[i].cbRead = cbRet;\n               Pipe[i].dwState = WRITING_STATE;\n               break;\n\n         // Pending write operation\n            case WRITING_STATE:\n               if (! fSuccess || cbRet != Pipe[i].cbToWrite)\n               {\n                  DisconnectAndReconnect(i);\n                  continue;\n               }\n               Pipe[i].dwState = READING_STATE;\n               break;\n\n            default:\n            {\n               printf(\"Invalid pipe state.\\n\");\n               return;\n            }\n         }\n      }\n\n   // The pipe state determines which operation to do next.\n\n      switch (Pipe[i].dwState)\n      {\n      // READING_STATE:\n      // The pipe instance is connected to the client\n      // and is ready to read a request from the client.\n\n         case READING_STATE:\n            fSuccess = ReadFile(\n               Pipe[i].hPipeInst,\n               Pipe[i].chRequest,\n               BUFSIZE*sizeof(TCHAR),\n               &Pipe[i].cbRead,\n               &Pipe[i].oOverlap);\n\n         // The read operation completed successfully.\n\n            if (fSuccess && Pipe[i].cbRead != 0)\n            {\n               Pipe[i].fPendingIO = FALSE;\n               Pipe[i].dwState = WRITING_STATE;\n               continue;\n            }\n\n         // The read operation is still pending.\n\n            dwErr = GetLastError();\n            if (! fSuccess && (dwErr == ERROR_IO_PENDING))\n            {\n               Pipe[i].fPendingIO = TRUE;\n               continue;\n            }\n\n         // An error occurred; disconnect from the client.\n\n            DisconnectAndReconnect(i);\n            break;\n\n      // WRITING_STATE:\n      // The request was successfully read from the client.\n      // Get the reply data and write it to the client.\n\n         case WRITING_STATE:\n            response = emit lineReady( QString::fromUtf8( (char*)Pipe[i].chRequest, Pipe[i].cbRead ) ).toUtf8();\n            StringCchCopy( Pipe[i].chReply, BUFSIZE, (LPCTSTR)response.data() );\n            Pipe[i].cbToWrite = response.size();\n\n            fSuccess = WriteFile(\n               Pipe[i].hPipeInst,\n               Pipe[i].chReply,\n               Pipe[i].cbToWrite,\n               &cbRet,\n               &Pipe[i].oOverlap);\n\n         // The write operation completed successfully.\n\n            if (fSuccess && cbRet == Pipe[i].cbToWrite)\n            {\n               Pipe[i].fPendingIO = FALSE;\n               Pipe[i].dwState = READING_STATE;\n               continue;\n            }\n\n         // The write operation is still pending.\n\n            dwErr = GetLastError();\n            if (! fSuccess && (dwErr == ERROR_IO_PENDING))\n            {\n               Pipe[i].fPendingIO = TRUE;\n               continue;\n            }\n\n         // An error occurred; disconnect from the client.\n\n            DisconnectAndReconnect(i);\n            break;\n\n         default:\n         {\n            printf(\"Invalid pipe state.\\n\");\n            return;\n         }\n      }\n  }\n}\n\n\n// DisconnectAndReconnect(DWORD)\n// This function is called when an error occurs or when the client\n// closes its handle to the pipe. Disconnect from this client, then\n// call ConnectNamedPipe to wait for another client to connect.\n\nVOID\nDisconnectAndReconnect(DWORD i)\n{\n// Disconnect the pipe instance.\n\n   if (! DisconnectNamedPipe(Pipe[i].hPipeInst) )\n   {\n      printf(\"DisconnectNamedPipe failed with %d.\\n\", GetLastError());\n   }\n\n// Call a subroutine to connect to the new client.\n\n   Pipe[i].fPendingIO = ConnectToNewClient(\n      Pipe[i].hPipeInst,\n      &Pipe[i].oOverlap);\n\n   Pipe[i].dwState = Pipe[i].fPendingIO ?\n      CONNECTING_STATE : // still connecting\n      READING_STATE;     // ready to read\n}\n\n// ConnectToNewClient(HANDLE, LPOVERLAPPED)\n// This function is called to start an overlapped connect operation.\n// It returns TRUE if an operation is pending or FALSE if the\n// connection has been completed.\n\nBOOL\nConnectToNewClient(HANDLE hPipe, LPOVERLAPPED lpo)\n{\n   BOOL fConnected, fPendingIO = FALSE;\n\n// Start an overlapped connection for this pipe instance.\n   fConnected = ConnectNamedPipe(hPipe, lpo);\n\n// Overlapped ConnectNamedPipe should return zero.\n   if (fConnected)\n   {\n      printf(\"ConnectNamedPipe failed with %d.\\n\", GetLastError());\n      return 0;\n   }\n\n   switch (GetLastError())\n   {\n   // The overlapped connection in progress.\n      case ERROR_IO_PENDING:\n         fPendingIO = TRUE;\n         break;\n\n   // Client is already connected, so signal an event.\n\n      case ERROR_PIPE_CONNECTED:\n         if (SetEvent(lpo->hEvent))\n            break;\n\n   // If an error occurs during the connect operation...\n      default:\n      {\n         printf(\"ConnectNamedPipe failed with %d.\\n\", GetLastError());\n         return 0;\n      }\n   }\n\n   return fPendingIO;\n}\n\n"
  },
  {
    "path": "lib/listener/win/NamedPipeServer.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef NAMEDPIPESERVER_H\n#define NAMEDPIPESERVER_H\n\n#include <QThread>\n\nclass NamedPipeServer : public QThread\n{\n    Q_OBJECT\npublic:\n    explicit NamedPipeServer( QObject* parent = 0 );\n\nprivate:\n    void run();\n\nsignals:\n    QString lineReady( const QString& line );\n};\n\n#endif // NAMEDPIPESERVER_H\n"
  },
  {
    "path": "lib/listener/win/SpotifyListener.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <lastfm/Track.h>\n#include \"SpotifyListener.h\"\n#include \"../PlayerConnection.h\"\n#include <lastfm/misc.h>\n\nclass SpotifyConnection : public PlayerConnection\n{\npublic:\n    SpotifyConnection() : PlayerConnection( \"spt\", \"Spotify\" )\n    {}\n\n    void start( const Track& t )\n    {\n        MutableTrack mt( t );\n        mt.setSource( Track::Player );\n        mt.setExtra( \"playerId\", id() );\n        mt.setExtra( \"playerName\", name() );\n        mt.stamp();\n        handleCommand( CommandStart, t );\n    }\n\n    void pause() { handleCommand( CommandPause ); }\n    void resume() { handleCommand( CommandResume ); }\n    void stop() { handleCommand( CommandStop ); }\n};\n\n\nSpotifyListenerWin::SpotifyListenerWin( QObject* parent )\n    :QObject( parent ), m_lastPlayerState( Stopped )\n{\n    QTimer* timer = new QTimer( this );\n    timer->start( 1000 );\n    connect( timer, SIGNAL(timeout()), SLOT(loop()));\n}\n\nSpotifyListenerWin::~SpotifyListenerWin()\n{\n    delete m_connection;\n}\n\nBOOL CALLBACK\nSpotifyListenerWin::callback( HWND hWnd, LPARAM lParam )\n{\n    SpotifyListenerWin* self = reinterpret_cast<SpotifyListenerWin*>(lParam);\n\n///    Getting the filename of the app would be more robust\n    //wchar_t filename[256];\n    //GetWindowModuleFileName( hWnd, filename, 256 );\n\n    //if ( QString::fromWCharArray( filename ).contains( \"spotify.exe\" ) )\n    {\n        wchar_t title[256];\n        GetWindowText( hWnd, title, 256 );\n\n        QString windowTitle = QString::fromWCharArray( title );\n\n        if ( windowTitle.startsWith( \"Spotify\" ) )\n        {\n            QRegExp re( QString( \"^Spotify - (.+) %1 (.+)\").arg( QChar( 0x2013 )  ), Qt::CaseSensitive, QRegExp::RegExp2 );\n\n            // A window that follows the Spotify track playing format takes priority\n            if ( re.indexIn( windowTitle ) == 0 )\n                self->m_windowTitle = windowTitle;\n\n            if ( self->m_windowTitle.isEmpty() )\n                self->m_windowTitle = windowTitle;\n\n        }\n    }\n\n    return TRUE;\n}\n\nvoid\nSpotifyListenerWin::loop()\n{\n    m_windowTitle.clear();\n\n    EnumWindows( SpotifyListenerWin::callback, reinterpret_cast<LPARAM>(this) );\n\n    // stopped =\n    // paused = Spotify\n    // playing = Spotify - Allo, Darlin'  Kiss Your Lips\n\n    State playerState = Stopped;\n\n    if ( m_windowTitle.startsWith( \"Spotify\" ) )\n    {\n        if ( !m_connection )\n            emit newConnection( m_connection = new SpotifyConnection );\n\n        QRegExp re( QString( \"^Spotify - (.+) %1 (.+)\").arg( QChar( 0x2013 )  ), Qt::CaseSensitive, QRegExp::RegExp2 );\n\n        playerState = re.indexIn( m_windowTitle ) == 0 ? Playing : Paused;\n\n        if ( m_lastPlayerState != playerState )\n        {\n            if ( playerState == Stopped )\n            {\n                m_connection->stop();\n                m_lastTrack = Track();\n            }\n            else if ( playerState == Paused )\n            {\n                if ( m_lastPlayerState == Playing )\n                    m_connection->pause();\n            }\n            else if ( playerState == Playing )\n            {\n                MutableTrack t;\n                t.setTitle( re.capturedTexts().at( 2 ) );\n                t.setArtist( re.capturedTexts().at( 1 ) );\n                // we don't know the duration, but we don't display it so just guess\n                t.setDuration( 320 );\n\n                if ( m_lastPlayerState == Paused && t == m_lastTrack )\n                    m_connection->resume();\n                else\n                    m_connection->start( t );\n\n                m_lastTrack = t;\n            }\n        }\n        else if ( playerState == Playing )\n        {\n            // when going from one song to the next we stay in the play state\n            MutableTrack t;\n            t.setTitle( re.capturedTexts().at( 2 ) );\n            t.setArtist( re.capturedTexts().at( 1 ) );\n            // we don't know the duration, but we don't display it so just guess\n            t.setDuration( 320 );\n\n            if ( t != m_lastTrack )\n                m_connection->start( t );\n\n            m_lastTrack = t;\n        }\n    }\n    else\n    {\n        if ( m_lastPlayerState == Playing || m_lastPlayerState == Paused )\n            m_connection->stop();\n\n        delete m_connection;\n    }\n\n    m_lastPlayerState = playerState;\n}\n\n\n//void\n//SpotifyListener::blah()\n//{\n//    static AppleScript playerStateScript( \"tell application \\\"Spotify\\\" to if running then return player state\" );\n//    QString playerState = playerStateScript.exec();\n\n//    if ( !playerState.isEmpty() )\n//    {\n//        if ( !m_connection )\n//            emit newConnection( m_connection = new SpotifyConnection );\n\n//        static AppleScript titleScript( \"tell application \\\"Spotify\\\" to return name of current track\" );\n//        static AppleScript albumScript( \"tell application \\\"Spotify\\\" to return album of current track\" );\n//        static AppleScript artistScript( \"tell application \\\"Spotify\\\" to return artist of current track\" );\n//        static AppleScript durationScript( \"tell application \\\"Spotify\\\" to return duration of current track\" );\n\n//        if ( playerState == \"playing\" )\n//        {\n//            lastfm::MutableTrack t;\n//            t.setTitle( titleScript.exec() );\n//            t.setAlbum( albumScript.exec() );\n//            t.setArtist( artistScript.exec() );\n//            t.setDuration( durationScript.exec().toInt() );\n\n//            if ( t != m_lastTrack )\n//                m_connection->start( t );\n\n//            m_lastTrack = t;\n//        }\n//        else if ( m_lastPlayerState != playerState )\n//        {\n//            if ( playerState == \"stopped\" )\n//            {\n//                m_connection->stop();\n//                m_lastTrack = Track();\n//            }\n//            else if ( playerState == \"paused\" )\n//                m_connection->pause();\n//            else if ( playerState == \"playing\" )\n//            {\n//                lastfm::MutableTrack t;\n//                t.setTitle( titleScript.exec() );\n//                t.setAlbum( albumScript.exec() );\n//                t.setArtist( artistScript.exec() );\n//                t.setDuration( durationScript.exec().toInt() );\n\n//                if ( m_lastPlayerState == \"paused\" && t == m_lastTrack )\n//                    m_connection->resume();\n//                else\n//                    m_connection->start( t );\n\n//                m_lastTrack = t;\n//            }\n//        }\n//    }\n//    else\n//    {\n//        if ( m_lastPlayerState == \"playing\" || m_lastPlayerState == \"paused\" )\n//            m_connection->stop();\n\n//        delete m_connection;\n//    }\n\n//    m_lastPlayerState = playerState;\n//}\n"
  },
  {
    "path": "lib/listener/win/SpotifyListener.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SPOTIFY_LISTENER_H\n#define SPOTIFY_LISTENER_H\n\n#include <Windows.h>\n\n#include <QObject>\n#include <QPointer>\n\n#include <lastfm/Track.h>\n\n#include \"lib/DllExportMacro.h\"\n\nclass LISTENER_DLLEXPORT SpotifyListenerWin : public QObject\n{\n    Q_OBJECT\nprivate:\n    enum State\n    {\n        Playing,\n        Paused,\n        Stopped\n    };\n\npublic:\n    SpotifyListenerWin( QObject* parent );\n    ~SpotifyListenerWin();\n\nsignals:\n    void newConnection( class PlayerConnection* );\n\nprivate slots:\n    void loop();\n\nprivate:\n    static BOOL CALLBACK callback( HWND hWnd, LPARAM lParam );\n\nprivate:\n    State m_lastPlayerState;\n    lastfm::Track m_lastTrack;\n    QPointer<class SpotifyConnection> m_connection;\n    QString m_windowTitle;\n};\n\n#endif\n"
  },
  {
    "path": "lib/logger/logger.pro",
    "content": "TARGET = logger\nTEMPLATE = lib\nQT -= gui\nCONFIG += dll\nunix:!mac {\n    CONFIG -= dll\n    CONFIG += staticlib\n    QMAKE_DISTCLEAN += -f ../../_bin/liblogger.a\n}\n\ninclude( ../../admin/include.qmake )\n\nDEFINES += _LOGGER_DLLEXPORT LASTFM_COLLAPSE_NAMESPACE\n\nSOURCES += $$ROOT_DIR/common/c++/Logger.cpp\n\nHEADERS += $$ROOT_DIR/common/c++/Logger.h\n\n\n\n"
  },
  {
    "path": "lib/unicorn/AnimatedPushButton.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ANIMATED_PUSHBUTTON_H\n#define ANIMATED_PUSHBUTTON_H\n\n#include <QPushButton>\n#include <QMovie>\n#include <QDebug>\n#include <iostream>\nclass AnimatedPushButton : public QPushButton\n{\npublic:\n    AnimatedPushButton( QMovie* movie, const QString& text, QWidget* parent = 0 )\n    :QPushButton( text, parent ),\n     m_movie( movie )\n    {\n        m_movie->start();\n        setIcon(QIcon( m_movie->currentPixmap()));\n        m_movie->stop();\n    }\n\nprivate:\n    QMovie* m_movie;\n};\n\n#endif //ANIMATED_PUSHBUTTON_H\n"
  },
  {
    "path": "lib/unicorn/AnimatedStatusBar.cpp",
    "content": "/*\n   Copyright 2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"AnimatedStatusBar.h\"\n\n#include <QTimeLine>\n#include \"qtwin.h\"\n#include <QDebug>\n\nAnimatedStatusBar::AnimatedStatusBar( QWidget* parent )\n                  :QStatusBar( parent )\n{\n    m_timeline = new QTimeLine( 50, this );\n    m_timeline->setUpdateInterval( 20 );\n    m_timeline->setCurveShape( QTimeLine::EaseInCurve );\n    connect( m_timeline, SIGNAL( frameChanged(int)), SLOT(onFrameChanged(int)));\n    connect( m_timeline, SIGNAL( finished()), SLOT(onFinished()));\n}\n\n\nvoid\nAnimatedStatusBar::showAnimated()\n{\n    if( isVisible() && height() > 0 ) return;\n    \n    window()->setMinimumHeight( window()->height());\n    m_timeline->setFrameRange( 0, sizeHint().height());\n    m_timeline->setDirection( QTimeLine::Forward );\n    setFixedHeight( 0 );\n    show();\n    m_windowHeight = window()->height();\n    m_timeline->start();\n}\n\n\nvoid \nAnimatedStatusBar::hideAnimated()\n{\n    if( !isVisible() || height() == 0 ) return;\n    \n    window()->setMaximumHeight( window()->height());\n    m_timeline->setFrameRange( 0, sizeHint().height());\n    m_timeline->setDirection( QTimeLine::Backward );\n    \n    m_windowHeight = window()->height();\n    m_timeline->start();\n}\n\nvoid \nAnimatedStatusBar::onFinished()\n{\n    if( m_timeline->direction() == QTimeLine::Backward ) {\n        hide();\n    }\n\n    setMaximumHeight( QWIDGETSIZE_MAX );\n    setMinimumHeight( 0 );\n    window()->setMinimumHeight( 0 );\n    window()->setMaximumHeight( QWIDGETSIZE_MAX );\n}\n\n\nvoid \nAnimatedStatusBar::onFrameChanged( int f )\n{\n    setFixedHeight( f );\n    if( m_timeline->direction() == QTimeLine::Forward )\n        window()->resize( window()->width(), m_windowHeight + f );\n    else\n        window()->resize( window()->width(), m_windowHeight - (sizeHint().height() - f ) );\n}\n"
  },
  {
    "path": "lib/unicorn/AnimatedStatusBar.h",
    "content": "/*\n   Copyright 2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ANIMATED_STATUS_BAR_H\n#define ANIMATED_STATUS_BAR_H\n\n#include <lib/DllExportMacro.h>\n#include <QStatusBar>\n\nclass UNICORN_DLLEXPORT AnimatedStatusBar: public QStatusBar {\n    Q_OBJECT\npublic:\n    AnimatedStatusBar( QWidget* parent = 0 );\n\npublic slots:\n    void showAnimated();\n    void hideAnimated();\n\nprivate slots:\n    void onFrameChanged(int);\n    void onFinished();\n\nprivate:\n    class QTimeLine* m_timeline;\n    int m_windowHeight;\n};\n\n#endif //ANIMATED_STATUS_BAR_H\n"
  },
  {
    "path": "lib/unicorn/CrashReporter/CrashReporter.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QCoreApplication>\n\n#ifndef Q_OS_MAC\n\n#ifdef Q_OS_WIN\n#include <client/windows/handler/exception_handler.h>\n#include <client/windows/sender/crash_report_sender.h>\n#endif\n\n#include <lastfm/misc.h>\n\n#include \"CrashReporter.h\"\n\n#ifdef Q_OS_WIN32\nbool\nFilterCallback(void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion)\n{\n    return true;\n}\n\n\nbool\nMinidumpCallback(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded)\n{\n    google_breakpad::CrashReportSender* crashReportSender = new google_breakpad::CrashReportSender( QString( \"\" ).toStdWString() );\n\n    std::map<std::wstring, std::wstring> parameters;\n\n    std::wstring yeah;\n\n    google_breakpad::ReportResult result = crashReportSender->SendCrashReport( QString( \"http://oops.last.fm/report/add\" ).toStdWString(), parameters, dump_path, &yeah);\n\n    return true;\n}\n#endif\n\nunicorn::CrashReporter::CrashReporter(QObject *parent) :\n    QObject(parent)\n{\n#ifdef Q_OS_WIN32\n    google_breakpad::ExceptionHandler* handler = new google_breakpad::ExceptionHandler( lastfm::dir::logs().absolutePath().toStdWString(),\n                                                                                       FilterCallback,\n                                                                                       MinidumpCallback,\n                                                                                       this,\n                                                                                       google_breakpad::ExceptionHandler::HANDLER_ALL);\n#endif\n}\n\n\nunicorn::CrashReporter::~CrashReporter()\n{\n\n}\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/CrashReporter/CrashReporter.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef CRASHREPORTER_H\n#define CRASHREPORTER_H\n\n#include <QObject>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT CrashReporter : public QObject\n{\n    Q_OBJECT\npublic:\n    explicit CrashReporter(QObject *parent = 0);\n    ~CrashReporter();\n};\n\n}\n\n#endif // CRASHREPORTER_H\n"
  },
  {
    "path": "lib/unicorn/CrashReporter/CrashReporter_mac.mm",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <Cocoa/Cocoa.h>\n\n#include <Breakpad/Breakpad.h>\n\n#include \"CrashReporter.h\"\n\nBreakpadRef gBreakpad;\n\nunicorn::CrashReporter::CrashReporter(QObject *parent) :\n    QObject(parent)\n{\n    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n    gBreakpad = 0;\n\n    NSDictionary *plist = [[NSBundle mainBundle] infoDictionary];\n\n    if (plist)\n    {\n      // Note: version 1.0.0.4 of the framework changed the type of the argument\n      // from CFDictionaryRef to NSDictionary * on the next line:\n      gBreakpad = BreakpadCreate(plist);\n    }\n\n    [pool release];\n}\n\nunicorn::CrashReporter::~CrashReporter()\n{\n    BreakpadRelease( gBreakpad );\n}\n"
  },
  {
    "path": "lib/unicorn/DesktopServices.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDesktopServices>\n#include <QCoreApplication>\n#include <QUrl>\n\n#include <lastfm/UrlBuilder.h>\n\n#include \"DesktopServices.h\"\n\nunicorn::DesktopServices::DesktopServices()\n{\n}\n\n\nvoid\nunicorn::DesktopServices::openUrl( QUrl url )\n{\n    if ( lastfm::UrlBuilder::isHost( url ) )\n    {\n        url.addQueryItem( \"utm_source\", \"last.fm\" );\n        url.addQueryItem( \"utm_medium\", \"application\" );\n        url.addQueryItem( \"utm_campaign\", \"last.fm_desktop_application\" );\n        url.addQueryItem( \"utm_content\", QCoreApplication::applicationVersion() );\n#ifdef WIN32\n        url.addQueryItem( \"utm_term\", \"WIN\" );\n#elif __APPLE__\n        url.addQueryItem( \"utm_term\", \"OSX\" );\n#elif defined (Q_WS_X11)\n        url.addQueryItem( \"utm_term\", \"X11\" );\n#endif\n    }\n\n    QDesktopServices::openUrl( url );\n}\n"
  },
  {
    "path": "lib/unicorn/DesktopServices.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef DESKTOPSERVICES_H\n#define DESKTOPSERVICES_H\n\n#include <QUrl>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT DesktopServices\n{\npublic:\n    DesktopServices();\n\n    static void openUrl( QUrl url );\n};\n\n}\n\n#endif // DESKTOPSERVICES_H\n"
  },
  {
    "path": "lib/unicorn/LoginProcess.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by William Viana Soares and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"LoginProcess.h\"\n#include \"QMessageBoxBuilder.h\"\n#include \"UnicornApplication.h\"\n\n#include <lastfm/ws.h>\n#include <lastfm/misc.h>\n#include <lastfm/XmlQuery.h>\n\n#include <QApplication>\n#include <QDesktopServices>\n#include <QUrl>\n#include <QTcpServer>\n#include <QTcpSocket>\n\n#include \"lib/unicorn/dialogs/ProxyDialog.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#ifdef WIN32\n#include <windows.h>\n#endif\n\nnamespace unicorn\n{\n\nLoginProcess::LoginProcess( QObject* parent )\n    : QObject( parent )\n{\n}\n\nLoginProcess::~LoginProcess()\n{\n}\n\nvoid\nLoginProcess::authenticate()\n{\n    connect( unicorn::Session::getToken(), SIGNAL( finished() ), SLOT( onGotToken() ) );\n}\n\nvoid\nLoginProcess::onGotToken()\n{\n    lastfm::XmlQuery lfm;\n\n    QUrl authUrl;\n\n    if ( lfm.parse( static_cast<QNetworkReply*>( sender() ) ) )\n    {\n        m_token = lfm[\"token\"].text();\n\n        authUrl.setUrl( \"http://www.last.fm/api/auth/\" );\n        authUrl.addQueryItem( \"api_key\", lastfm::ws::ApiKey );\n        authUrl.addQueryItem( \"token\", m_token );\n        QDesktopServices::openUrl( authUrl );\n    }\n    else\n    {\n        handleError( lfm );\n    }\n\n\n    emit authUrlChanged( authUrl.toString() );\n}\n\n\nvoid\nLoginProcess::getSession()\n{\n    connect( unicorn::Session::getSession( m_token ), SIGNAL( finished() ), SLOT( onGotSession() ) );\n}\n\n\nvoid\nLoginProcess::onGotSession()\n{\n    lastfm::XmlQuery lfm;\n\n    if ( lfm.parse( static_cast<QNetworkReply*>( sender() ) ) )\n    {\n        QString username = lfm[\"session\"][\"name\"].text();\n        QString sessionKey = lfm[\"session\"][\"key\"].text();\n\n        unicorn::Application* app = qobject_cast<unicorn::Application*>( qApp );\n        app->changeSession( username, sessionKey );\n    }\n    else\n    {\n        handleError( lfm );\n    }\n}\n\nvoid\nLoginProcess::handleError( const lastfm::XmlQuery& lfm )\n{\n    qWarning() << lfm.parseError().message() << lfm.parseError().enumValue();\n\n    if ( lfm.parseError().enumValue() == lastfm::ws::MalformedResponse )\n    {\n        // ask for proxy settings\n        unicorn::ProxyDialog proxy;\n        proxy.exec();\n    }\n    else\n    {\n        QString errorText;\n\n        if ( lfm.parseError().enumValue() == lastfm::ws::UnknownError )\n            errorText = tr( \"There was a network error: %1\" ).arg( QString::number( static_cast<QNetworkReply*>( sender() )->error() ) );\n        else if ( lfm.parseError().enumValue() == lastfm::ws::TokenNotAuthorised )\n            errorText = tr( \"You have not authorised this application\" );\n        else\n            errorText = lfm.parseError().message().trimmed() + \": \" + QString::number( lfm.parseError().enumValue() );\n\n        QMessageBoxBuilder( 0 )\n                .setIcon( QMessageBox::Critical )\n                .setTitle( tr(\"Authentication Error\") )\n                .setText( errorText )\n                .exec();\n    }\n}\n\n}// namespace unicorn\n"
  },
  {
    "path": "lib/unicorn/LoginProcess.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by William Viana Soares and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LOGIN_PROCESS_H\n#define LOGIN_PROCESS_H\n\n#include <QObject>\n#include <QPointer>\n\n#include <lastfm/ws.h>\n\n#include \"UnicornSession.h\"\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn\n{\n/**\n * This class encapsulates the whole login process.\n *\n * Call the authenticate function to start the login process\n * and connect to the gotSession signal to be notified when\n * the process finishes.\n */\nclass UNICORN_DLLEXPORT LoginProcess : public QObject\n{\n    Q_OBJECT\npublic:\n    LoginProcess( QObject* parent = 0 );\n    ~LoginProcess();\n\nprivate:\n    void handleError( const lastfm::XmlQuery& lfm );\n\nsignals:\n    void authUrlChanged( const QString& authUrl );\n\npublic slots:\n    void authenticate();\n    void getSession();\n\nprivate slots:\n    void onGotToken();\n    void onGotSession();\n\nprivate: \n    QString m_token;\n};\n\n}// namespace unicorn\n\n#endif // LOGIN_PROCESS_H\n"
  },
  {
    "path": "lib/unicorn/PlayBus/Bus.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Bus.h\"\n\nunicorn::Bus::Bus( QObject* parent )\n    :PlayBus( \"unicorn\", parent )\n{\n    connect( this, SIGNAL( message(QByteArray)), SLOT( onMessage(QByteArray)));\n    connect( this, SIGNAL( queryRequest( QString, QByteArray )), SLOT( onQuery( QString, QByteArray )));\n}\n\nbool\nunicorn::Bus::isWizardRunning()\n{\n    return sendQuery( \"WIZARDRUNNING\" ) == \"TRUE\";\n}\n\nQMap<QString, QString>\nunicorn::Bus::getSessionData()\n{\n    QByteArray ba = sendQuery( \"SESSION\" );\n    QMap<QString, QString> sessionData;\n\n    if( ba.length() > 0 )\n    {\n        QDataStream ds( ba );\n        ds >> sessionData;\n    }\n\n    return sessionData;\n}\n\nvoid\nunicorn::Bus::announceSessionChange( unicorn::Session& s )\n{\n    qDebug() << \"Session change, let's spread the message through the bus!\";\n    QByteArray ba;\n    QDataStream ds( &ba, QIODevice::WriteOnly | QIODevice::Truncate );\n\n    ds << QString( \"SESSIONCHANGED\" );\n    ds << ( s );\n\n    sendMessage( ba );\n}\n\nvoid\nunicorn::Bus::onMessage( const QByteArray& message )\n{\n    qDebug() << \"Message received\";\n    qDebug() << \"Message: \" << message;\n    QDataStream ds( message );\n    QString stringMessage;\n\n    ds >> stringMessage;\n\n    qDebug() << stringMessage;\n\n    if( stringMessage == \"SESSIONCHANGED\" )\n    {\n        qDebug() << \"and it's a session change alert\";\n        unicorn::Session* session = new unicorn::Session( ds );\n        emit sessionChanged( *session );\n        delete session;\n    }\n    else if( message.startsWith( \"LOVED=\" ))\n    {\n        QByteArray sessionData = message.right( message.size() - 6);\n        emit lovedStateChanged( sessionData == \"true\" );\n    }\n}\n\nvoid\nunicorn::Bus::onQuery( const QString& uuid, const QByteArray& message )\n{\n    qDebug() << \"query received\" << message;\n    if( message == \"WIZARDRUNNING\" )\n        emit wizardRunningQuery( uuid );\n    else if( message == \"SESSION\" )\n        emit sessionQuery( uuid );\n}\n\n"
  },
  {
    "path": "lib/unicorn/PlayBus/Bus.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#include \"../UnicornSession.h\"\n#include \"PlayBus.h\"\n\nnamespace unicorn\n{\n\nclass Bus : public PlayBus\n{\n    Q_OBJECT\npublic:\n    Bus( QObject* parent = 0 );\n\n    bool isWizardRunning();\n    QMap<QString, QString> getSessionData();\n    void announceSessionChange( unicorn::Session& s );\n\nprivate slots:\n    void onMessage( const QByteArray& message );\n    void onQuery( const QString& uuid, const QByteArray& message );\n\nsignals:\n    void wizardRunningQuery( const QString& uuid );\n    void sessionQuery( const QString& uuid );\n    void sessionChanged( const unicorn::Session& s );\n    void rosterUpdated();\n    void lovedStateChanged(bool loved);\n};\n\n}\n"
  },
  {
    "path": "lib/unicorn/PlayBus/PlayBus.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"PlayBus.h\"\n\nunicorn::PlayBus::PlayBus( const QString& name, QObject* parent )\n    :QObject( parent ),\n     m_busName( name ),\n     m_queryMessages( false )\n#ifdef Q_OS_WIN\n\t ,m_sharedMemory( name )\n#endif\n{\n#ifndef Q_OS_WIN\n    m_busName = lastfm::dir::runtimeData().absolutePath() + \"/\" + m_busName;\n#endif\n    connect( &m_server, SIGNAL( newConnection()), SLOT( onIncomingConnection()));\n}\n\nunicorn::PlayBus::~PlayBus()\n{\n    m_server.close();\n#ifdef Q_OS_WIN\n    m_sharedMemory.detach();\n#endif\n}\n\nvoid\nunicorn::PlayBus::board()\n{\n    reinit();\n}\n\nconst QByteArray&\nunicorn::PlayBus::lastMessage() const\n{\n    return m_lastMessage;\n}\n\nvoid\nunicorn::PlayBus::setQueryMessages( bool b )\n{\n    m_queryMessages = b;\n}\n\nQByteArray\nunicorn::PlayBus::sendQuery( QByteArray request, int timeout )\n{\n    QUuid quuid = QUuid::createUuid();\n    QString uuid = quuid;\n    m_dispatchedQueries << uuid;\n    sendMessage( (uuid + \" \" + request).toUtf8() );\n\n    SignalBlocker blocker( this, SIGNAL( queryRequest(QString,QByteArray)), timeout );\n\n    while( blocker.start() )\n        if( m_lastQueryUuid == uuid )\n            return m_lastQueryResponse;\n\n    return QByteArray();\n}\n\nvoid\nunicorn::PlayBus::sendQueryResponse( QString uuid, QByteArray message )\n{\n    sendMessage( ( uuid + \" \" ).toUtf8() + message );\n}\n\n/** send the message around the bus */\nvoid\nunicorn::PlayBus::sendMessage( const QByteArray& msg )\n{\n    foreach( QLocalSocket* socket, m_sockets )\n    {\n        socket->write( msg + \"\\n\" );\n        socket->flush();\n    }\n\n}\n\nvoid\nunicorn::PlayBus::onSocketConnected()\n{\n    //WIN32 supports GUIDs which almost certainly will be unique according to Qt.\n#ifndef WIN32\n    //throw-away uuid generation to initialize random seed\n    QUuid::createUuid();\n#endif\n\n    QLocalSocket* socket = qobject_cast<QLocalSocket*>(sender());\n    addSocket( socket );\n}\n\nvoid\nunicorn::PlayBus::reinit()\n{\n    if( m_server.isListening())\n        return;\n\n    foreach( QLocalSocket* socket, m_sockets ) {\n        m_sockets.removeAll(socket);\n        socket->disconnect();\n        socket->close();\n        socket->deleteLater();\n    }\n\n#ifndef Q_OS_WIN\n    if( m_server.listen( m_busName )) {\n        return;\n    }\n#else\n    if( m_sharedMemory.create( 1 ))\n    {\n        emit message( \"Now Listening\" );\n        m_server.listen( m_busName );\n        return;\n    }\n    else\n    {\n        emit message( \"Connecting to server\" );\n    }\n#endif\n\n    m_server.close();\n    QLocalSocket* socket = new QLocalSocket( this );\n    connect( socket, SIGNAL( connected()), SLOT( onSocketConnected()));\n    connect( socket, SIGNAL( disconnected()), SLOT( reinit()));\n    connect( socket, SIGNAL( error(QLocalSocket::LocalSocketError)), SLOT( onError(QLocalSocket::LocalSocketError)));\n    socket->connectToServer( m_busName );\n}\n\nvoid\nunicorn::PlayBus::onError( const QLocalSocket::LocalSocketError& e )\n{\n#ifdef Q_OS_WIN\n    Q_UNUSED( e )\n#endif\n\n    if( e == QLocalSocket::ConnectionRefusedError )\n    {\n        QFile::remove( m_busName );\n    }\n\n    QLocalSocket* s = qobject_cast<QLocalSocket*>(sender());\n    s->close();\n    s->deleteLater();\n    QTimer::singleShot( 10, this, SLOT(reinit()));\n}\n\nvoid\nunicorn::PlayBus::onIncomingConnection()\n{\n    QLocalSocket* socket = 0;\n    while( (socket = m_server.nextPendingConnection()) )\n    {\n        socket->setParent( this );\n        addSocket( socket );\n    }\n}\n\nvoid\nunicorn::PlayBus::processCommand( const QByteArray& data )\n{\n    m_lastMessage = data;\n    QRegExp queryRE(\"^(\\\\{.{8}-.{4}-.{4}-.{4}-.{12}\\\\}) .*$\");\n\n    if( queryRE.indexIn( data ) > -1 )\n    {\n        QString uuid = queryRE.cap(1);\n\n        // ignore any queries that have already been seen\n        if( !m_dispatchedQueries.contains( uuid ) &&\n             m_servicedQueries.contains( uuid ))\n        {\n             if( m_queryMessages )\n                emit message( data );\n\n             return;\n        }\n\n        m_lastQueryUuid = uuid;\n        m_lastQueryResponse = data.mid( 39 ); //remove uuid and seperator\n        m_servicedQueries << m_lastQueryUuid;\n\n        emit queryRequest( m_lastQueryUuid, m_lastQueryResponse);\n\n        if( !m_queryMessages )\n            return;\n    }\n\n    emit message( data );\n}\n\nvoid\nunicorn::PlayBus::onSocketData()\n{\n    QLocalSocket* socket = qobject_cast<QLocalSocket*>(sender());\n\n    while( socket->canReadLine() )\n    {\n        QByteArray data = socket->readLine();\n        data.chop( 1 ); // remove trailing /n\n\n        foreach( QLocalSocket* aSocket, m_sockets )\n        {\n            if( aSocket == socket )\n                continue;\n\n            aSocket->write( data + \"\\n\" );\n            aSocket->flush();\n        }\n\n        processCommand( data );\n\n    }\n}\n\nvoid\nunicorn::PlayBus::onSocketDestroyed( QObject* o )\n{\n    QLocalSocket* s = dynamic_cast<QLocalSocket*>(o);\n\n    if( !s )\n        return;\n\n    s->blockSignals(true);\n    m_sockets.removeAll( s );\n}\n\nvoid\nunicorn::PlayBus::addSocket( QLocalSocket* socket )\n{\n    connect( socket, SIGNAL(readyRead()), SLOT(onSocketData()));\n    QSignalMapper* mapper = new QSignalMapper(socket);\n    mapper->setMapping( socket, socket );\n    connect( mapper, SIGNAL(mapped(QObject*)), SLOT(onSocketDestroyed(QObject*)));\n    connect( socket, SIGNAL(disconnected()), mapper, SLOT( map()));\n    connect( socket, SIGNAL(destroyed(QObject*)), SLOT(onSocketDestroyed(QObject*)));\n    m_sockets << socket;\n}\n\nconst QStringList\nunicorn::PlayBus::nodeList( const QString& data )\n{\n    QString str( data );\n    str = str.mid( 7 ); // remove NODES [\n    str.chop( 1 ); // remove ]\n    return str.split( \",\" );\n}\n\n"
  },
  {
    "path": "lib/unicorn/PlayBus/PlayBus.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#include <QLocalServer>\n#include <QLocalSocket>\n#include <QList>\n#include <QString>\n#include <QDir>\n#include <QFile>\n#include <QUuid>\n#include <QCoreApplication>\n#include <QDateTime>\n#include <QSignalMapper>\n\n#include \"../SignalBlocker.h\"\n\n#ifdef Q_OS_WIN\n#include <QSharedMemory>\n#else\n#include <lastfm/misc.h>\n#endif\n\nnamespace unicorn\n{\n\n/** @author Jono Cole <jono@last.fm>\n  * @brief An interprocess message bus.\n  *\n  * This is a client side implemented bus, meaning that \n  * if no bus is running then a client will become the master node.\n  * \n  * If the master node drops it's connection then another client node\n  * will become the master and all other clients will connect to this.\n  *\n  * This bus is designed to be run on a single host using local servers.\n  * the server mediation is handled at the kernel level by exploiting the \n  * logic that allows only one process to listen on a named pipe.\n  *\n  * This code will not work across distributed hosts as no master node\n  * mediation is carried out. This could be extended by using a known\n  * mediation algorithm.\n  */\nclass PlayBus : public QObject\n{\nQ_OBJECT\npublic:\n    /** @param name The name of the bus to connect to or create */\n    PlayBus( const QString& name, QObject* parent = 0 );\n    ~PlayBus();\n\n    void board();\n\n    const QByteArray& lastMessage() const;\n\n    void setQueryMessages( bool b );\n\npublic slots:\n    QByteArray sendQuery( QByteArray request, int timeout = 200 );\n    void sendQueryResponse( QString uuid, QByteArray message );\n\n   /** send the message around the bus */\n    void sendMessage( const QByteArray& msg );\n\nsignals:\n    /** a new message has been received from the bus */\n    void message( const QByteArray& msg );\n    void queryRequest( const QString& uuid, const QByteArray& message);\n\nprivate slots:\n    void onSocketConnected();\n    void reinit();\n    void onError( const QLocalSocket::LocalSocketError& e );\n    void onIncomingConnection();\n    void processCommand( const QByteArray& data );\n    void onSocketData();\n    void onSocketDestroyed( QObject* o );\n\nprivate:\n    void addSocket( QLocalSocket* socket );\n\n    const QStringList nodeList( const QString& data );\n\n    QString m_busName;\n    QLocalServer m_server;\n    QList<QLocalSocket*> m_sockets;\n    QByteArray m_lastMessage;\n    QList<QString> m_dispatchedQueries;\n    QList<QString> m_servicedQueries;\n    QByteArray m_lastQueryResponse;\n    QString m_lastQueryUuid;\n    bool m_queryMessages;\n#ifdef Q_OS_WIN\n\tQSharedMemory m_sharedMemory;\n#endif\n};\n\n}\n\n"
  },
  {
    "path": "lib/unicorn/QMessageBoxBuilder.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"QMessageBoxBuilder.h\"\n#include <QApplication>\n\n#include <QGridLayout>\n#include <QLabel>\n\nunicorn::MessageDialog::MessageDialog( QWidget* parent )\n        :QDialog( parent ? ( parent->isVisible() ? parent : 0 ) : 0 ),\n         m_clickedButton( QDialogButtonBox::NoButton )\n{\n    setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n    setSizeGripEnabled( false );\n    //setFixedWidth( 500 );\n\n    setWindowFlags( Qt::Dialog );\n\n    QGridLayout* l = new QGridLayout( this );\n\n    l->addWidget( icon = new QLabel, 0, 0, 3, 1, Qt::AlignTop | Qt::AlignLeft );\n    l->addWidget( label = new QLabel, 0, 1, 1, 1, Qt::AlignTop );\n    label->setAlignment( Qt::AlignLeft | Qt::AlignTop );\n    l->addWidget( informativeText = new QLabel, 1, 1, 1, 1, Qt::AlignTop );\n\n    label->setWordWrap( true );\n    informativeText->setWordWrap( true );\n    informativeText->setAttribute( Qt::WA_MacSmallSize );\n\n    QFont f = label->font();\n    f.setBold( true ); \n    label->setFont( f );\n\n    l->setColumnStretch( 1, 1 );\n    l->setRowStretch( 3, 1 );\n\n    l->addWidget( checkbox = new QCheckBox( tr( \"Don't ask this again\" )), 2, 1, 1, 1 );\n    checkbox->setVisible( false );\n    checkbox->setFocusPolicy( Qt::NoFocus );\n    l->addWidget( buttons = new QDialogButtonBox, 3, 0, 1, 2 );\n    buttons->setStandardButtons( QDialogButtonBox::Ok );\n    connect( buttons, SIGNAL( clicked(QAbstractButton*)), SLOT( onButtonClicked(QAbstractButton*)));\n    buttons->setFocus( Qt::ActiveWindowFocusReason );\n}\n\n\nvoid\nunicorn::MessageDialog::onButtonClicked(QAbstractButton* b)\n{\n    m_clickedButton = int(buttons->standardButton( b ));\n    switch( buttons->buttonRole( b )) {\n        case QDialogButtonBox::AcceptRole:\n        case QDialogButtonBox::YesRole:\n            accept();\n            break;\n\n        case QDialogButtonBox::RejectRole:\n        case QDialogButtonBox::NoRole:\n            reject();\n            break;\n        default:\n            break;\n    }\n}\n\n\nQMessageBoxBuilder& \nQMessageBoxBuilder::setTitle( const QString& title )\n{\n#ifdef Q_WS_MAC\n    box.setText( title + \"\\t\\t\\t\" );\n#else\n    box.setWindowTitle( title );\n#endif\n    return *this;\n}\n\n\nQMessageBoxBuilder&\nQMessageBoxBuilder::setText( const QString& text )\n{\n#ifdef Q_WS_MAC\n    box.setInformativeText( text );\n#else\n    box.setText( text );\n#endif\n    return *this;\n}\n\n\nint\nQMessageBoxBuilder::exec( bool* dontAskAgain )\n{\n    QApplication::setOverrideCursor( Qt::ArrowCursor );\n    box.activateWindow();\n    box.exec();\n    QApplication::restoreOverrideCursor();\n    \n    if( dontAskAgain )\n        *dontAskAgain = box.isDontShowAgainChecked();\n\n    return box.clickedButton();\n}\n"
  },
  {
    "path": "lib/unicorn/QMessageBoxBuilder.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef MESSAGE_BOX_BUILDER_H\n#define MESSAGE_BOX_BUILDER_H\n\n#include <lib/DllExportMacro.h>\n#include <QtGui/QMessageBox>\n#include <QAbstractButton>\n#include <QPushButton>\n\n#include <QDialogButtonBox>\n#include <QBoxLayout>\n#include <QCheckBox>\n#include <QStyle>\n#include <QDebug>\n#include <QLabel>\n#include <QDebug>\n\nnamespace unicorn {\n    class UNICORN_DLLEXPORT MessageDialog : public QDialog {\n        Q_OBJECT\n    public:\n        MessageDialog( QWidget* parent );\n        void setStandardButtons( QMessageBox::StandardButtons b )\n        { \n            buttons->setStandardButtons( QDialogButtonBox::StandardButtons(int(b) )); \n        }\n\n        void setIcon( QMessageBox::Icon x )\n        { \n            QIcon pm;\n            switch( x ) {\n                case QMessageBox::NoIcon:\n                    break;\n                case QMessageBox::Information:\n                    pm = style()->standardIcon( QStyle::SP_MessageBoxInformation );\n                    break;\n                case QMessageBox::Warning:\n                    pm = style()->standardIcon( QStyle::SP_MessageBoxWarning );\n                    break;\n                case QMessageBox::Critical:\n                    pm = style()->standardIcon( QStyle::SP_MessageBoxCritical );\n                    break;\n                case QMessageBox::Question:\n                    pm = style()->standardIcon( QStyle::SP_MessageBoxQuestion );\n                    break;\n            }\n            icon->setPixmap( pm.pixmap( 32, 32 ) );\n        }\n\n        QAbstractButton* button( QMessageBox::StandardButton b )\n        {\n            QAbstractButton* ret = buttons->button( QDialogButtonBox::StandardButton(int(b) ));\n            return ret;\n        }\n\n        void addButton( QAbstractButton* b, QMessageBox::ButtonRole r )\n        {\n            buttons->addButton( b, QDialogButtonBox::ButtonRole(int(r)));\n        }\n\n        void setText( const QString& t )\n        {\n            label->setText( t );\n        }\n\n        void setInformativeText( const QString& t )\n        {\n            informativeText->setText( t );\n        }\n\n        void setCheckBox( bool b )\n        {\n            checkbox->setVisible( b );\n        }\n\n        bool isDontShowAgainChecked() const\n        {\n            return checkbox->isChecked();\n        }\n\n        int clickedButton() const { return m_clickedButton; }\n\n    private slots:\n        void onButtonClicked(class QAbstractButton*);\n\n    protected:\n        QLabel *icon, *label, *informativeText;\n        QDialogButtonBox* buttons;\n        QCheckBox* checkbox;\n        int m_clickedButton;\n    };\n}\n\nclass UNICORN_DLLEXPORT QMessageBoxBuilder\n{\n    unicorn::MessageDialog box;\n\npublic:\n    /** Try not to use 0! */\n    QMessageBoxBuilder( QWidget* parent ) : box( parent )\n    {}\n    \n    QMessageBoxBuilder& setTitle( const QString& x );\n    QMessageBoxBuilder& setText( const QString& x );\n    /** the default is Information */\n    QMessageBoxBuilder& setIcon( QMessageBox::Icon x ) { box.setIcon( x ); return *this; }\n    /** the default is a single OK button */\n    QMessageBoxBuilder& setButtons( QMessageBox::StandardButtons buttons ) { box.setStandardButtons( buttons ); return *this; }\n\n    QMessageBoxBuilder& setButtonText( QMessageBox::StandardButton aButton, const QString& text )\n    {\n        box.button( aButton )->setText( text );\n        return *this;\n    }\n\n    QMessageBoxBuilder& dontAskAgain(){ box.setCheckBox( true ); return *this; }\n\n    QMessageBoxBuilder& addButton( QAbstractButton* b, QMessageBox::ButtonRole r ){ box.addButton( b, r ); return *this; }\n\n    int exec( bool* dontAskAgain = 0 );\n\t\n    QMessageBoxBuilder& sheet()\n    {\n#ifdef Q_WS_MAC\n        if( box.parentWidget())\n            box.setWindowFlags( Qt::Sheet | ( box.windowFlags() & ~Qt::Drawer ) );\n#endif\n        return *this;\n    }\n};\n\n#endif // MESSAGE_BOX_BUILDER_H\n"
  },
  {
    "path": "lib/unicorn/ScrobblesModel.cpp",
    "content": "/*\n   Copyright 2011-2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QColor>\n#include <QDebug>\n\n#include <lastfm/ScrobbleCache.h>\n\n#include \"ScrobblesModel.h\"\n\nScrobblesModel::Scrobble::Scrobble( const lastfm::Track track )\n    :m_track( track ), m_scrobblingEnabled( true )\n{\n    bool ok;\n    int count = m_track.extra( \"playCount\" ).toInt( &ok );\n    m_originalPlayCount = ok ? count : 1;\n}\n\nlastfm::Track\nScrobblesModel::Scrobble::track() const\n{\n    return m_track;\n}\n\nQString\nScrobblesModel::Scrobble::title() const\n{\n    return m_track.title();\n}\n\nQString\nScrobblesModel::Scrobble::artist() const\n{\n    return m_track.artist();\n}\n\nQString\nScrobblesModel::Scrobble::album() const\n{\n    return m_track.album();\n}\n\nQDateTime\nScrobblesModel::Scrobble::timestamp() const\n{\n    return m_track.timestamp();\n}\n\nbool\nScrobblesModel::Scrobble::isLoved() const\n{\n    return m_track.isLoved();\n}\n\nbool\nScrobblesModel::Scrobble::isScrobblingEnabled() const\n{\n    return m_scrobblingEnabled;\n}\n\nvoid ScrobblesModel::Scrobble::setEnableScrobbling( bool allow )\n{\n    m_scrobblingEnabled = allow;\n}\n\nQVariant\nScrobblesModel::Scrobble::attribute( int index ) const\n{\n    switch( index )\n    {\n        case ScrobblesModel::Artist: return artist();\n        case ScrobblesModel::Title: return title();\n        case ScrobblesModel::Album: return album();\n        case ScrobblesModel::TimeStamp: return timestamp();\n        case ScrobblesModel::Plays: return track().extra( \"playCount\" ).toInt();\n        case ScrobblesModel::Loved: return isLoved();\n        default: break;\n    }\n\n    return QVariant();\n}\n\nint\nScrobblesModel::Scrobble::originalPlayCount() const\n{\n    return m_originalPlayCount;\n}\n\nbool\nScrobblesModel::Scrobble::operator<( const Scrobble& that ) const\n{\n    return this->m_track < that.m_track;\n}\n\n\nScrobblesModel::ScrobblesModel( QObject* parent )\n    : QAbstractTableModel( parent ), m_readOnly( false )\n{\n    m_headerTitles.append( tr( \"Artist\" ) );\n    m_headerTitles.append( tr( \"Title\" ) );\n    m_headerTitles.append( tr( \"Album\" ) );\n    m_headerTitles.append( tr( \"Plays\" ) );\n    m_headerTitles.append( tr( \"Last Played\" ) );\n    m_headerTitles.append( tr( \"Loved\" ) );\n}\n\nvoid\nScrobblesModel::addTracks( const QList<lastfm::Track>& tracks )\n{\n    beginInsertRows( QModelIndex(), m_scrobbleList.count(), m_scrobbleList.count() + tracks.count() - 1 );\n\n    foreach( lastfm::Track t, tracks )\n        m_scrobbleList.append( t );\n\n    endInsertRows();\n}\n\nvoid\nScrobblesModel::setReadOnly()\n{\n    m_readOnly = true;\n}\n\nint\nScrobblesModel::rowCount( const QModelIndex& /*parent*/ ) const\n{\n    return m_scrobbleList.count();\n}\n\nint\nScrobblesModel::columnCount( const QModelIndex& /*parent*/ ) const\n{\n    return m_headerTitles.count();\n}\n\nQVariant\nScrobblesModel::data( const QModelIndex& index, int role ) const\n{\n    if ( !index.isValid() )\n        return QVariant();\n\n    if ( index.row() >= m_scrobbleList.size() )\n        return QVariant();\n\n    if ( index.column() >= m_headerTitles.size() )\n        return QVariant();\n\n\n    if ( role == Qt::DisplayRole )\n        return m_scrobbleList.at( index.row() ).attribute( index.column() );\n    else if ( role == Qt::TextColorRole && !m_readOnly )\n    {\n        if ( !lastfm::ScrobbleCache::isValid( m_scrobbleList.at( index.row() ).track() ) )\n            return QColor( Qt::red );\n    }\n    else if ( role == Qt::ToolTipRole && !m_readOnly )\n    {\n        Scrobble s = m_scrobbleList.at( index.row() );\n        lastfm::ScrobbleCache::Invalidity invalidity;\n\n        if ( !lastfm::ScrobbleCache::isValid( s.track(), &invalidity ) )\n        {\n            switch ( invalidity )\n            {\n            case lastfm::ScrobbleCache::TooShort:\n                return tr( \"This track is under 30 seconds\" );\n            case lastfm::ScrobbleCache::ArtistNameMissing:\n                return tr( \"The artist name is missing\" );\n            case lastfm::ScrobbleCache::TrackNameMissing:\n                return tr( \"Invalid track title\" );\n            case lastfm::ScrobbleCache::ArtistInvalid:\n                return tr( \"Invalid artist\" );\n            case lastfm::ScrobbleCache::NoTimestamp:\n                return tr( \"There is no timestamp\" );\n            case lastfm::ScrobbleCache::FromTheFuture:\n                return tr( \"This track is too far in the future\" );\n            case lastfm::ScrobbleCache::FromTheDistantPast:\n                return tr( \"This track was played over two weeks ago\" );\n            }\n        }\n    }\n    else if ( role == Qt::CheckStateRole && index.column() == ScrobblesModel::Artist )\n    {\n        if ( m_readOnly )\n            return QVariant();\n        else if ( !lastfm::ScrobbleCache::isValid( m_scrobbleList.at( index.row() ).track() ) )\n            return Qt::Unchecked;\n        else\n            return m_scrobbleList.at( index.row() ).isScrobblingEnabled() ? Qt::Checked : Qt::Unchecked;\n    }\n\n    return QVariant();\n}\n\nQVariant\nScrobblesModel::headerData( int section, Qt::Orientation orientation, int role ) const\n{\n    if ( role != Qt::DisplayRole )\n        return QVariant();\n\n    if ( orientation == Qt::Horizontal )\n        return m_headerTitles.at( section );\n    else\n        return QVariant();\n}\n\nQt::ItemFlags\nScrobblesModel::flags( const QModelIndex& index ) const\n{\n    if ( !index.isValid() )\n        return Qt::ItemIsEnabled;\n\n    if ( !m_readOnly )\n    {\n        if ( index.column() == ScrobblesModel::Artist )\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsUserCheckable;\n        if ( index.column() == ScrobblesModel::Plays )\n            return QAbstractItemModel::flags( index ) | Qt::ItemIsEditable;\n    }\n\n    return QAbstractItemModel::flags( index );\n}\n\nbool\nScrobblesModel::setData( const QModelIndex& index, const QVariant& value, int role )\n{\n    if ( index.isValid() )\n    {\n        Scrobble s = m_scrobbleList.at( index.row() );\n\n        if ( index.column() == ScrobblesModel::Artist && role == Qt::CheckStateRole )\n        {\n            s.setEnableScrobbling( value.toBool() );\n            m_scrobbleList.replace( index.row(), s );\n            emit dataChanged( index, index );\n            return true;\n        }\n        else if ( index.column() == ScrobblesModel::Plays )\n        {\n            bool ok;\n            int count = value.toInt( &ok );\n\n            if ( ok && count != 0 && count <= s.originalPlayCount() )\n            {\n                lastfm::MutableTrack( s.track() ).setExtra( \"playCount\", QString::number( count ) );\n                emit dataChanged( index, index );\n            }\n\n            return true;\n        }\n    }\n\n    return false;\n}\n\nQList<lastfm::Track>\nScrobblesModel::tracksToScrobble() const\n{\n    QList<lastfm::Track> tracks;\n\n    for ( int i = 0 ; i < m_scrobbleList.count() ; i ++ )\n        if ( m_scrobbleList.at( i ).isScrobblingEnabled() )\n            tracks.append( m_scrobbleList.at( i ).track() );\n\n    return tracks;\n}\n"
  },
  {
    "path": "lib/unicorn/ScrobblesModel.h",
    "content": "/*\n   Copyright 2011-2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SCROBBLES_MODEL_H\n#define SCROBBLES_MODEL_H\n\n#include <QAbstractTableModel>\n#include <QStringList>\n\n#include <lastfm/Track.h>\n\n#include \"lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT ScrobblesModel : public QAbstractTableModel\n{\n    Q_OBJECT\npublic:\n\n    enum\n    {\n        Artist,\n        Title,\n        Album,\n        Plays,\n        TimeStamp,\n        Loved\n    };\n\n\n    ScrobblesModel( QObject* parent = 0 );\n    void addTracks( const QList<lastfm::Track>& tracks );\n\n    void setReadOnly();\n\n    int rowCount( const QModelIndex& parent = QModelIndex() ) const;\n    int columnCount( const QModelIndex& parent = QModelIndex() ) const;\n\n    QVariant data( const QModelIndex& index, int role ) const;\n    QVariant headerData( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const;\n    Qt::ItemFlags flags( const QModelIndex& index ) const;\n    bool setData( const QModelIndex& index, const QVariant& value, int role );\n\n    QList<lastfm::Track> tracksToScrobble() const;\n\nprivate:\n    class Scrobble\n    {\n    public:\n        Scrobble( const lastfm::Track track );\n\n        lastfm::Track track() const;\n        QString title() const;\n        QString artist() const;\n        QString album() const;\n        QDateTime timestamp() const;\n        bool isLoved() const;\n        bool isScrobblingEnabled() const;\n\n        void setEnableScrobbling( bool allow );\n\n        QVariant attribute( int index ) const;\n\n        int originalPlayCount() const;\n\n        bool operator<( const Scrobble& that ) const;\n\n    private:\n        lastfm::Track m_track;\n        bool m_scrobblingEnabled;\n        int m_originalPlayCount;\n    };\n\nprivate:\n    QList<Scrobble> m_scrobbleList;\n    QStringList m_headerTitles;\n    bool m_readOnly;\n};\n\n#endif // SCROBBLES_MODEL_H\n"
  },
  {
    "path": "lib/unicorn/SignalBlocker.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SIGNAL_BLOCKER_H_\n#define SIGNAL_BLOCKER_H_\n\n#include \"lib/DllExportMacro.h\"\n#include <QTimer>\n#include <QEventLoop>\n\n#include \"lib/DllExportMacro.h\"\n\n/**\n  * @brief Waits for a Qt signal to be emitted before\n  *        proceeding with code execution.\n  * \n  * @author Jono Cole<jono@last.fm>\n  */\nclass UNICORN_DLLEXPORT SignalBlocker : public QEventLoop\n{\nQ_OBJECT\npublic:\n    SignalBlocker( QObject* o, const char* signal, int timeout)\n    : m_ret( true )\n    {\n        m_timer.setSingleShot( true );\n        connect( o, signal, SLOT( onSignaled()));\n        \n        if( timeout > -1 ) {\n            m_timer.setInterval( timeout );\n            connect( &m_timer, SIGNAL(timeout()), this, SLOT( onTimeout()));\n        }\n    }\n    \n    /** returns true if the signal fired otherwise false if\n        the timeout fired */\n    bool start()\n    {\n        if( m_ret == false ) return false;\n        m_timer.start();\n        m_loop.exec();\n        return m_ret;\n    }\n\nprivate slots:\n    void onSignaled()\n    {\n        m_ret = true;\n        m_timer.stop();\n        m_loop.quit();\n    }\n\n    void onTimeout()\n    {\n        m_ret = false;\n        m_loop.quit();\n    }\n\nprivate:\n    QEventLoop m_loop;\n    bool m_ret;\n    QTimer m_timer;\n};\n\n#endif //SIGNAL_BLOCKER_H_\n"
  },
  {
    "path": "lib/unicorn/TrackImageFetcher.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"TrackImageFetcher.h\"\n#include <lastfm/Track.h>\n#include <lastfm/ws.h>\n#include <lastfm/XmlQuery.h>\n#include <QDebug>\n#include <QPixmap>\n#include <QStringList>\n\n\nTrackImageFetcher::TrackImageFetcher( const Track& track, Track::ImageSize size )\n    :m_track( track ),\n     m_size( size )\n{\n}\n\nvoid\nTrackImageFetcher::startAlbum()\n{\n    if (!album().isNull())\n    {\n        QUrl imageUrl = url( \"album\" );\n\n        if ( imageUrl.isValid() )\n            connect( lastfm::nam()->get( QNetworkRequest( imageUrl ) ), SIGNAL(finished()), SLOT(onAlbumImageDownloaded()) );\n        else\n            connect( album().getInfo(), SIGNAL(finished()), SLOT(onAlbumGotInfo()) );\n    }\n    else\n        startTrack();\n}\n\nvoid\nTrackImageFetcher::startTrack()\n{\n    QUrl imageUrl = url( \"track\" );\n\n    if ( imageUrl.isValid() )\n        connect( lastfm::nam()->get( QNetworkRequest( imageUrl ) ), SIGNAL(finished()), SLOT(onTrackImageDownloaded()) );\n    else\n        trackGetInfo();\n}\n\n\nvoid\nTrackImageFetcher::startArtist()\n{\n    QUrl imageUrl = url( \"artist\" );\n\n    if ( imageUrl.isValid() )\n        connect( lastfm::nam()->get( QNetworkRequest( imageUrl ) ), SIGNAL(finished()), SLOT(onArtistImageDownloaded()) );\n    else\n        artistGetInfo();\n}\n\n\nvoid\nTrackImageFetcher::trackGetInfo()\n{\n    if (!artist().isNull())\n        m_track.getInfo( this, \"onTrackGotInfo\" );\n    else\n        fail();\n}\n\n\nvoid\nTrackImageFetcher::artistGetInfo()\n{\n    if (!artist().isNull())\n        connect( artist().getInfo(), SIGNAL(finished()), SLOT(onArtistGotInfo()) );\n    else\n        fail();\n}\n\nvoid\nTrackImageFetcher::onAlbumGotInfo()\n{\n    if (!downloadImage( (QNetworkReply*)sender(), \"album\" ))\n        startTrack();\n}\n\nvoid\nTrackImageFetcher::onTrackGotInfo( const QByteArray& data )\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( data ) )\n    {\n        lastfm::MutableTrack track( m_track );\n        track.setImageUrl( Track::MegaImage, lfm[\"track\"][\"image size=mega\"].text() );\n        track.setImageUrl( Track::ExtraLargeImage, lfm[\"track\"][\"image size=extralarge\"].text() );\n        track.setImageUrl( Track::LargeImage, lfm[\"track\"][\"image size=large\"].text() );\n        track.setImageUrl( Track::MediumImage, lfm[\"track\"][\"image size=medium\"].text() );\n        track.setImageUrl( Track::SmallImage, lfm[\"track\"][\"image size=small\"].text() );\n\n        if (!downloadImage( 0, \"track\" ))\n            startArtist();\n    }\n    else\n    {\n        qWarning() << lfm.parseError().message();\n    }\n}\n\nvoid\nTrackImageFetcher::onArtistGotInfo()\n{\n    if (!downloadImage( (QNetworkReply*)sender(), \"artist\" ))\n        fail();\n}\n\nvoid\nTrackImageFetcher::onAlbumImageDownloaded()\n{\n    QPixmap i;\n\n    if ( i.loadFromData( qobject_cast<QNetworkReply*>(sender())->readAll() ) )\n        emit finished( i );\n    else\n        startTrack();\n\n    sender()->deleteLater(); //always deleteLater from slots connected to sender()\n}\n\nvoid\nTrackImageFetcher::onTrackImageDownloaded()\n{\n    QPixmap i;\n\n    if ( i.loadFromData( qobject_cast<QNetworkReply*>(sender())->readAll() ) )\n        emit finished( i );\n    else\n        startArtist();\n\n    sender()->deleteLater(); //always deleteLater from slots connected to sender()\n}\n\nvoid\nTrackImageFetcher::onArtistImageDownloaded()\n{\n    QPixmap i;\n\n    if ( i.loadFromData( qobject_cast<QNetworkReply*>(sender())->readAll() ) )\n        emit finished( i );\n    else\n        fail();\n    \n    sender()->deleteLater(); //always deleteLater from slots connected to sender()\n}\n\n\nbool\nTrackImageFetcher::downloadImage( QNetworkReply* reply, const QString& root_node )\n{\n    XmlQuery lfm;\n\n    if ( reply && lfm.parse( reply ) )\n    {\n        // cache all the sizes\n        if ( root_node == \"album\" )\n        {\n            m_track.album().setImageUrl( Track::MegaImage, lfm[root_node][\"image size=mega\"].text() );\n            m_track.album().setImageUrl( Track::ExtraLargeImage, lfm[root_node][\"image size=extralarge\"].text() );\n            m_track.album().setImageUrl( Track::LargeImage, lfm[root_node][\"image size=large\"].text() );\n            m_track.album().setImageUrl( Track::MediumImage, lfm[root_node][\"image size=medium\"].text() );\n            m_track.album().setImageUrl( Track::SmallImage, lfm[root_node][\"image size=small\"].text() );\n        }\n        else if ( root_node == \"artist\" )\n        {\n            m_track.artist().setImageUrl( Track::MegaImage, lfm[root_node][\"image size=mega\"].text() );\n            m_track.artist().setImageUrl( Track::ExtraLargeImage, lfm[root_node][\"image size=extralarge\"].text() );\n            m_track.artist().setImageUrl( Track::LargeImage, lfm[root_node][\"image size=large\"].text() );\n            m_track.artist().setImageUrl( Track::MediumImage, lfm[root_node][\"image size=medium\"].text() );\n            m_track.artist().setImageUrl( Track::SmallImage, lfm[root_node][\"image size=small\"].text() );\n        }\n    }\n    else\n    {\n        qWarning() << lfm.parseError().message();\n    }\n\n    QUrl imageUrl = url( root_node );\n\n    qWarning() << root_node << imageUrl;\n\n    if ( imageUrl.isValid() )\n    {\n        QNetworkReply* get = lastfm::nam()->get( QNetworkRequest( imageUrl ) );\n\n        if ( root_node == \"album\" )\n            connect( get, SIGNAL(finished()), SLOT(onAlbumImageDownloaded()) );\n        else if ( root_node == \"track\" )\n            connect( get, SIGNAL(finished()), SLOT(onTrackImageDownloaded()) );\n        else\n            connect( get, SIGNAL(finished()), SLOT(onArtistImageDownloaded()) );\n\n        return true;\n    }\n\n    return false;\n}\n\nQUrl\nTrackImageFetcher::url( const QString& root_node )\n{\n    QList<Track::ImageSize> sizes;\n\n    switch ( m_size )\n    {\n        default:\n        case Track::MegaImage: sizes << Track::MegaImage;\n        case Track::ExtraLargeImage: sizes << Track::ExtraLargeImage;\n        case Track::LargeImage: sizes << Track::LargeImage;\n        case Track::MediumImage: sizes << Track::MediumImage;\n        case Track::SmallImage: sizes << Track::SmallImage;\n    }\n\n    QUrl imageUrl;\n    Track::ImageSize foundSize;\n\n    foreach ( Track::ImageSize size, sizes )\n    {\n        QUrl url;\n\n        if ( root_node == \"album\" )\n            url = m_track.album().imageUrl( size, true );\n        else if ( root_node == \"track\" )\n            url = m_track.imageUrl( size, true );\n        else if ( root_node == \"artist\" )\n            url = m_track.artist().imageUrl( size, true );\n\n        // we seem to get a load of album.getInfos where the node exists\n        // but the value is \"\" and \"mega\" isn't currently used for album images\n        if ( url.isValid() )\n        {\n            imageUrl = url;\n            foundSize = size;\n            break;\n        }\n    }\n\n    return imageUrl;\n}\n\n\nvoid\nTrackImageFetcher::fail()\n{\n    //emit finished( QPixmap() );\n}\n"
  },
  {
    "path": "lib/unicorn/TrackImageFetcher.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TRACK_IMAGE_FETCHER_H\n#define TRACK_IMAGE_FETCHER_H\n\n#include <QObject>\n#include <lib/DllExportMacro.h>\n#include <lastfm/Track.h>\n\n\n/** @author <max@last.fm>\n  * Fetches the album art for an album, via album.getInfo\n  */\nclass UNICORN_DLLEXPORT TrackImageFetcher : public QObject\n{\n    Q_OBJECT\npublic:\n    TrackImageFetcher( const Track& track, Track::ImageSize size );\n\n    // The order of preference is this\n    // * if we know the album then use the album image\n    // * if no album image found, use track image which could be a guess at the album\n    // * if neither album nor track image found, fallback to an artist image.\n    void startAlbum();\n    void startTrack();\n    void startArtist();\n\n    Track track() const { return m_track; }\n\nprivate:\n    lastfm::Track m_track;\n\n    QUrl url( const QString& root_node );\n\n    void trackGetInfo();\n    void artistGetInfo();\n    void fail();\n    bool downloadImage( QNetworkReply*, const QString& root_node_name );\n    \n    Album album() const { return m_track.album(); }\n    Artist artist() const { return m_track.artist(); }\n\nsignals:\n    void finished( const class QPixmap& );\n\nprivate slots:\n    void onAlbumGotInfo();\n    void onTrackGotInfo(const QByteArray &data);\n    void onArtistGotInfo();\n    void onAlbumImageDownloaded();\n    void onTrackImageDownloaded();\n    void onArtistImageDownloaded();\n\nprivate:\n    lastfm::Track::ImageSize m_size;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/UnicornApplication.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifdef __APPLE__\n    // first to prevent compilation errors with Qt 4.5.0-beta1\n    #include <Carbon/Carbon.h>\n    #include <ApplicationServices/ApplicationServices.h>\n    #include <QMainWindow>\n    #include \"UnicornApplicationDelegate.h\"\n    extern void qt_mac_set_menubar_icons( bool );\n#elif defined WIN32\n    #include <windows.h>\n    #include <QAbstractEventDispatcher>\n#endif\n\n#include <QProcess>\n#include <QDebug>\n#include <QDir>\n#include <QFile>\n#include <QTemporaryFile>\n#include <QFileInfo>\n#include <QLocale>\n#include <QRegExp>\n#include <QStyle>\n#include <QTimer>\n#include <QTranslator>\n#include <QAction>\n\n#include <lastfm/misc.h>\n#include <lastfm/User.h>\n#include <lastfm/InternetConnectionMonitor.h>\n#include <lastfm/ws.h>\n#include <lastfm/XmlQuery.h>\n\n#include \"PlayBus/Bus.h\"\n#include \"dialogs/LoginContinueDialog.h\"\n#include \"dialogs/LoginDialog.h\"\n#include \"dialogs/UserManagerDialog.h\"\n#include \"LoginProcess.h\"\n#include \"QMessageBoxBuilder.h\"\n#include \"SignalBlocker.h\"\n#include \"UnicornCoreApplication.h\"\n#include \"UnicornSettings.h\"\n#include \"DesktopServices.h\"\n#include \"UnicornApplication.h\"\n\n\n\n\nunicorn::Application::Application(const QString &id, int &argc, char **argv) throw( StubbornUserException )\n                    : QtSingleApplication( id, argc, argv ),\n                      m_logoutAtQuit( false ),\n                      m_currentSession( new unicorn::Session ),\n                      m_wizardRunning( true ),\n                      m_icm( 0 )\n{\n    m_bus = new unicorn::Bus( this );\n\n    qsrand( QDateTime::currentDateTime().toTime_t() + QCoreApplication::applicationPid() );\n\n#ifdef Q_OS_MAC\n    m_delegate = new unicorn::UnicornApplicationDelegate( this );\n#endif\n}\n\nvoid\nunicorn::Application::init()\n{\n#ifdef Q_OS_MAC\n    addLibraryPath( applicationDirPath() + \"/../plugins\" );\n#elif defined Q_OS_WIN\n    addLibraryPath( applicationDirPath() + \"/plugins\" );\n#endif\n\n#ifdef Q_WS_MAC\n    qt_mac_set_menubar_icons( false );\n#endif\n\n    CoreApplication::init();\n\n    setupHotKeys();\n\n#ifdef __APPLE__\n    setGetURLEventHandler();\n    AEEventHandlerUPP urlHandler = NewAEEventHandlerUPP( appleEventHandler );\n    AEInstallEventHandler( kInternetEventClass, kAEGetURL, urlHandler, 0, false );\n\n    setOpenApplicationEventHandler();\n    AEEventHandlerUPP openHandler = NewAEEventHandlerUPP( appleEventHandler );\n    AEInstallEventHandler( kCoreEventClass, kAEReopenApplication, openHandler, 0, false );\n#endif\n\n#ifdef Q_WS_MAC\n#define CSS_PATH \"/../Resources/\"\n#else\n#define CSS_PATH \"/\"\n#endif\n\n    refreshStyleSheet();\n\n    translate();\n\n    m_icm = new lastfm::InternetConnectionMonitor( this );\n\n    connect( m_icm, SIGNAL(up(QString)), this, SIGNAL(internetConnectionUp()));\n    connect( m_icm, SIGNAL(down(QString)), this, SIGNAL(internetConnectionDown()));\n\n    connect( m_bus, SIGNAL(wizardRunningQuery(QString)), SLOT(onWizardRunningQuery(QString)));\n    connect( m_bus, SIGNAL(sessionQuery(QString)), SLOT(onBusSessionQuery(QString)));\n    connect( m_bus, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onBusSessionChanged(unicorn::Session)));\n    connect( m_bus, SIGNAL(lovedStateChanged(bool)), SIGNAL(busLovedStateChanged(bool)));\n\n    m_bus->board();\n\n#ifdef __APPLE__\n    setQuitOnLastWindowClosed( false );\n#endif\n}\n\nvoid \nunicorn::Application::loadStyleSheet( QFile& file )\n{\n    file.open( QIODevice::ReadOnly );\n    m_styleSheet += file.readAll();\n    setStyleSheet( m_styleSheet );\n}\n\nvoid\nunicorn::Application::initiateLogin( bool ) throw( StubbornUserException )\n{\n    Session* newSession = 0;\n\n    if( m_bus->isWizardRunning() )\n    {\n        SignalBlocker( m_bus, SIGNAL( sessionChanged( const QMap<QString, QString>& ) ), -1 ).start();\n    }\n    else\n    {\n        QMap<QString, QString> sessionData = m_bus->getSessionData();\n\n        //If the bus returns an empty session data, try to get the session from the last user logged in\n        if ( ! ( sessionData.contains( \"sessionKey\" ) || sessionData.contains( \"username\" ) ) )\n        {\n            sessionData = Session::lastSessionData();\n        }\n\n        if ( sessionData.contains( \"sessionKey\" ) && sessionData.contains( \"username\" ) )\n            newSession = new Session( sessionData[ \"username\" ], sessionData[ \"sessionKey\" ] );\n    }\n\n    if ( newSession )\n    {\n        changeSession( newSession );\n    }\n    else\n    {\n        SignalBlocker( m_bus, SIGNAL( sessionChanged( const QMap<QString, QString>& ) ), -1 ).start();\n\n        QMap<QString, QString> sessionData = m_bus->getSessionData();\n\n        if ( sessionData.contains( \"sessionKey\" ) && sessionData.contains( \"username\" ) )\n        {\n            newSession = new Session( sessionData[ \"username\" ], sessionData[ \"sessionKey\" ] );\n            changeSession( newSession );\n        }\n        else\n        {\n            throw StubbornUserException();\n        }\n    }\n}\n\n\nvoid \nunicorn::Application::manageUsers()\n{\n    UserManagerDialog um;\n    connect( &um, SIGNAL( rosterUpdated()), SIGNAL( rosterUpdated()));\n    \n    if( um.exec() )\n    {\n        QMap<QString, QString> lastSession = Session::lastSessionData();\n        if ( lastSession.contains( \"username\" ) && lastSession.contains( \"sessionKey\" ) )\n        {\n            changeSession( lastSession[ \"username\" ], lastSession[ \"sessionKey\" ] );\n        }\n    }\n}\n\n\nvoid\nunicorn::Application::translate()\n{\n    //Try to load the language set by the user and\n    //if there wasn't any, then use the system language\n    QString iso639 = AppSettings().value( \"language\", \"\" ).toString();\n    if ( iso639.isEmpty() )\n        iso639 = QLocale::system().name();\n\n    qDebug() << \"Locale: \" << iso639;\n\n    // set the default locale for the app which will be used by web services\n    QLocale::setDefault( QLocale( iso639 ) );\n\n    QString qmExt = iso639.left( 2 ) == \"zh\" ? iso639 : iso639.left( 2 );\n    qDebug() << \"Language ext: \" << qmExt;\n\n#ifdef Q_WS_MAC\n    QDir const d = lastfm::dir::bundle().filePath( \"Contents/Resources/qm\" );\n#elif defined(Q_OS_WIN)\n    QDir const d = qApp->applicationDirPath() + \"/i18n\";\n#elif defined(Q_OS_UNIX)\n    QDir const d = QString( PREFIX ) + \"/share/lastfm-scrobbler/i18n\";\n#endif\n\n    //TODO need a unicorn/core/etc. translation, plus policy of no translations elsewhere or something!\n    QTranslator* t1 = new QTranslator( this );\n    t1->load( d.filePath( \"lastfm_\" + qmExt ) );\n\n    QTranslator* t2 = new QTranslator( this );\n    t2->load( d.filePath( \"qt_\" + qmExt ) );\n\n    installTranslator( t1 );\n    installTranslator( t2 );\n\n#ifdef Q_OS_WIN\n    QTranslator* t3 = new QTranslator( this );\n    t3->load( d.filePath( \"qtsparkle/\" + qmExt ) );\n    installTranslator( t3 );\n#endif\n\n#ifdef Q_OS_MAC\n    macTranslate( qmExt );\n#endif\n}\n\n\nunicorn::Application::~Application()\n{\n}\n\n\nvoid\nunicorn::Application::setWizardRunning( bool running )\n{\n    m_wizardRunning = running;\n}\n\nvoid\nunicorn::Application::onWizardRunningQuery( const QString& uuid )\n{\n    qDebug() << \"Is the Wizard running?\";\n    if ( m_wizardRunning )\n    {\n        m_bus->sendQueryResponse( uuid, \"TRUE\" );\n    }\n    else\n    {\n        m_bus->sendQueryResponse( uuid, \"FALSE\" );\n    }\n\n}\n\nvoid \nunicorn::Application::onBusSessionQuery( const QString& uuid )\n{\n    QByteArray ba;\n    QDataStream s( &ba, QIODevice::WriteOnly );\n    QMap<QString, QString> sessionData;\n    sessionData[ \"username\" ] = currentSession().user().name();\n    sessionData[ \"sessionKey\" ] = currentSession().sessionKey();\n    s << sessionData;\n    m_bus->sendQueryResponse( uuid, ba );\n}\n\n\nvoid \nunicorn::Application::onBusSessionChanged( const unicorn::Session& session )\n{\n    unicorn::Session* newSession = new unicorn::Session( session.user().name(), session.sessionKey() );\n    changeSession( newSession, false );\n}\n\nvoid\nunicorn::Application::changeSession( const QString& username, const QString& sessionKey, bool announce )\n{\n    return changeSession( new unicorn::Session( username, sessionKey ), announce );\n}\n\nvoid\nunicorn::Application::changeSession( Session* newSession, bool announce )\n{\n    if( m_currentSession && !m_wizardRunning &&  Settings().value( \"changeSessionConfirmation\", true ).toBool() )\n    {\n        bool dontAskAgain = false;\n        int result = QMessageBoxBuilder( findMainWindow() ).setTitle( tr( \"Changing User\" ) )\n           .setText( tr( \"%1 will be logged into the Scrobbler and Last.fm Radio. \"\n                         \"All music will now be scrobbled to this account. Do you want to continue?\" )\n                         .arg( newSession->user().name() ))\n           .setIcon( QMessageBox::Information )\n           .setButtons( QMessageBox::Yes | QMessageBox::Cancel )\n           .dontAskAgain()\n           .exec( &dontAskAgain );\n\n        Settings().setValue( \"changeSessionConfirmation\", !dontAskAgain );\n        if( result != QMessageBox::Yes )\n            return;\n    }\n\n    disconnect( m_currentSession, SIGNAL(userInfoUpdated(lastfm::User)), this, SIGNAL(gotUserInfo(lastfm::User)) );\n    connect( newSession, SIGNAL(userInfoUpdated(lastfm::User)), SIGNAL(gotUserInfo(lastfm::User)) );\n\n    disconnect( m_currentSession, SIGNAL(sessionChanged(unicorn::Session)), this, SIGNAL(sessionChanged(unicorn::Session)) );\n    connect( newSession, SIGNAL(sessionChanged(unicorn::Session)), SIGNAL(sessionChanged(unicorn::Session)) );\n\n    delete m_currentSession;\n    m_currentSession = newSession;\n\n    lastfm::ws::Username = m_currentSession->user().name();\n    lastfm::ws::SessionKey = m_currentSession->sessionKey();\n    \n    if( announce )\n        m_bus->announceSessionChange( currentSession() );\n\n    emit sessionChanged( currentSession() );\n}\n\nunicorn::Session&\nunicorn::Application::currentSession() const\n{\n    return *m_currentSession;\n}\n\nvoid\nunicorn::Application::sendBusLovedStateChanged( bool loved )\n{\n    QByteArray message = loved ? \"LOVED=true\" : \"LOVED=false\";\n    m_bus->sendMessage(message);\n}\n\nvoid\nunicorn::Application::refreshStyleSheet()\n{\n    m_styleSheet.clear();\n\n    if ( m_cssFileName.isNull() )\n    {\n        // This is the first time we are loading the stylesheet\n\n        if( !styleSheet().isEmpty() ) {\n            m_cssFileName = QDir::currentPath() + QUrl( styleSheet() ).toLocalFile();\n            m_cssDir = QFileInfo( m_cssFileName ).path();\n        }\n\n        if( styleSheet().isEmpty()) {\n#if defined(Q_OS_WIN) || defined(Q_OS_MAC)\n            m_cssFileName = applicationDirPath() + CSS_PATH + applicationName() + \".css\";\n            m_cssDir = applicationDirPath() + CSS_PATH;\n#else\n            m_cssFileName = QString( PREFIX ) + \"/share/lastfm-scrobbler/\" + applicationName() + \".css\";\n            m_cssDir = QString( PREFIX ) + \"/share/lastfm-scrobbler/\";\n#endif\n        }\n    }\n\n    if ( !m_cssFileName.isNull() )\n    {\n        QFile cssFile( m_cssFileName );\n        cssFile.open( QIODevice::ReadOnly );\n        m_styleSheet = cssFile.readAll();\n        setStyleSheet( m_styleSheet );\n        cssFile.close();\n    }\n\n    QRegExp rx( \"@import\\\\s*\\\"([^\\\"]*)\\\";\" );\n    int pos = 0;\n    while( (pos = rx.indexIn( m_styleSheet, pos )) != -1 ) {\n        QFile f( m_cssDir + \"/\" +  rx.cap( 1 ));\n        loadStyleSheet( f );\n        pos += rx.matchedLength();\n    }\n\n//    QStyle* style = style();\n//    style->set\n//    setStyle( style );\n}\n\nvoid*\nunicorn::Application::installHotKey( Qt::KeyboardModifiers modifiers, quint32 virtualKey, QObject* receiver, const char* slot )\n{\n    qDebug() << \"Installing HotKey\";\n\tquint32 id = m_hotKeyMap.size() + 1;\n    m_hotKeyMap[id] = QPair<QObject*, const char*>( receiver, slot );\n\t\n#ifdef __APPLE__\n    EventHotKeyID hotKeyID;\n\n    hotKeyID.signature='htk1';\n    hotKeyID.id=id;\n\n    UInt32 appleMod=0;\n    if( modifiers.testFlag( Qt::ShiftModifier ))\n        appleMod |= shiftKey;\n    if( modifiers.testFlag( Qt::ControlModifier ))\n        appleMod |= controlKey;\n    if( modifiers.testFlag( Qt::AltModifier ))\n        appleMod |= optionKey;\n    if( modifiers.testFlag( Qt::MetaModifier ))\n        appleMod |= cmdKey;\n\n    EventHotKeyRef hkRef;\n\n    RegisterEventHotKey( virtualKey, appleMod, hotKeyID, GetApplicationEventTarget(), 0, &hkRef );\n    return hkRef;\n#elif defined WIN32\n\tquint32 winMod = 0;\n    if( modifiers.testFlag( Qt::ShiftModifier ))\n        winMod |= MOD_SHIFT;\n    if( modifiers.testFlag( Qt::ControlModifier ))\n        winMod |= MOD_CONTROL;\n    if( modifiers.testFlag( Qt::AltModifier ))\n        winMod |= MOD_ALT;\n    if( modifiers.testFlag( Qt::MetaModifier ))\n        winMod |= MOD_WIN;\n\t\t\n\tRegisterHotKey( NULL, id, winMod, virtualKey);\n    return reinterpret_cast<void*>(id);\n#endif\n}\n\nvoid\nunicorn::Application::unInstallHotKey( void* id )\n{\n#ifdef __APPLE__\n    UnregisterEventHotKey( (EventHotKeyRef)id );\n#elif defined WIN32\n    UnregisterHotKey( NULL, (int)id );\n#endif\n}\n\n\nvoid \nunicorn::Application::setupHotKeys()\n{\n#ifdef __APPLE__\n    EventTypeSpec eventType;\n    eventType.eventClass=kEventClassKeyboard;\n    eventType.eventKind=kEventHotKeyPressed;\n\n    using unicorn::Application;\n    InstallApplicationEventHandler(&Application::hotkeyEventHandler, 1, &eventType, this, NULL);\n#elif defined WIN32\n    QAbstractEventDispatcher::instance()->setEventFilter( winEventFilter );\n#endif\n}\n\nvoid \nunicorn::Application::onHotKeyEvent(quint32 id)\n{\n    QPair< QObject*, const char*> method = m_hotKeyMap[id];\n    QObject* receiver = method.first;\n    const char* slot = method.second;\n    QTimer::singleShot( 0, receiver, slot );\n}\n\nQMainWindow*  \nunicorn::Application::findMainWindow()\n{\n    QMainWindow* ret = 0;\n    foreach (QWidget* w, qApp->topLevelWidgets())\n        if ( (ret = qobject_cast<QMainWindow*>(w)) )\n            break;\n\n    return ret;\n}\n\n#ifdef __APPLE__\nOSStatus /* static */\nunicorn::Application::hotkeyEventHandler( EventHandlerCallRef, EventRef event, void* data )\n{\n    unicorn::Application* self = (unicorn::Application*)data;\n    EventHotKeyID hkId;\n    GetEventParameter( event, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkId), NULL, &hkId);\n    self->onHotKeyEvent( hkId.id );\n    return noErr;\n}\n\n\nvoid\nunicorn::Application::appleEventReceived( const QStringList& messages )\n{\n    emit messageReceived( messages );\n}\n\npascal OSErr /* static */\n#ifdef Q_OS_MAC64\nunicorn::Application::appleEventHandler( const AppleEvent* e, AppleEvent*, void* )\n#else\nunicorn::Application::appleEventHandler( const AppleEvent* e, AppleEvent*, long )\n#endif\n{\n    OSType id = typeWildCard;\n    AEGetAttributePtr( e, keyEventIDAttr, typeType, 0, &id, sizeof(id), 0 );\n \n    if ( id  == kAEQuitApplication )\n    {\n        qApp->quit();\n        return noErr;\n    }\n    else if ( id == kAEGetURL )\n    {\n        OSErr err = noErr;\n        Size actualSize = 0;\n        DescType descType = typeChar;\n\n        if ( (err = AESizeOfParam( e, keyDirectObject, &descType, &actualSize)) == noErr )\n        {\n            if ( 0 != actualSize )\n            {\n                // make a buffer (Qt style)\n                QByteArray bUrl;\n                bUrl.resize(actualSize);\n\n                err = AEGetParamPtr(e,\n                                    keyDirectObject,\n                                    typeChar,\n                                    0,\n                                    bUrl.data(),\n                                    actualSize,\n                                    &actualSize);\n\n                qobject_cast<unicorn::Application*>(qApp)->appleEventReceived( QStringList() << bUrl );\n            }\n        }\n\n        return noErr;\n    }\n    else\n    {\n        AEAddressDesc descList;\n\n        OSErr ret;\n        ret = AEGetParamDesc( e, keyAEPropData, typeAEList, &descList );\n        long count = 0;\n        ret = AECountItems( &descList, &count );\n        if( ret != noErr )\n            count = 0;\n\n        QStringList args;\n        for( int i = 1; i <= count; ++i ) {\n            AEAddressDesc desc;\n            AEGetNthDesc( &descList, i, typeChar, NULL, &desc );\n            if( ret == noErr ) {\n                unsigned int size = AEGetDescDataSize( &desc );\n                char data[size + 1];\n                data[ size ] = 0;\n                ret = AEGetDescData( &desc, data, size );\n                args << QString::fromUtf8( data );\n            }\n        }\n\n        qobject_cast<unicorn::Application*>(qApp)->appleEventReceived( args );\n        return noErr;\n    }\n\n    return unimpErr;\n}\n#endif\n\n#ifdef WIN32\nbool /* static */\nunicorn::Application::winEventFilter ( void* message )\n{\n\tMSG* msg = (MSG*)message;\n\tif( msg->message == WM_HOTKEY )\n\t{\n\t\tqDebug() << \"Filtered WM_HOTKEY\";\n        qobject_cast<unicorn::Application*>(qApp)->onHotKeyEvent( msg->wParam );\n\t\treturn true;\n\t}\n\treturn false;\n}\n#endif\n\nvoid\nunicorn::Application::restart()\n{\n\n#ifdef Q_OS_WIN\n    QStringList args;\n    args << \"--new\"; // force a new instance of the app, even if one is running\n    qDebug() << applicationFilePath();\n    QProcess::startDetached( applicationFilePath(), args );\n#endif\n\n#ifdef Q_OS_MAC\n    // In Mac OS the full path of aplication binary is:\n    //    <base-path>/myApp.app/Contents/MacOS/myApp\n    QStringList args;\n    args << \"-b\";\n    args << \"fm.last.Scrobbler\";\n    args << \"-n\"; // open a new instance even if one is running\n    args << \"--args\";\n    args << \"--new\"; // force a new instance of the app, even if one is running\n    qDebug() << QProcess::startDetached( \"open\", args );\n#endif\n\n    // Terminate current instance:\n    exit(0); // Exit gracefully by terminating the myApp instance\n}\n\nbool\nunicorn::Application::isInternetConnectionUp() const\n{\n    return m_icm->isUp();\n}\n\n#ifdef Q_OS_MAC\nvoid\nunicorn::Application::showDockIcon( bool show )\n{\n    m_delegate->showDockIcon( show );\n}\n#endif\n\n"
  },
  {
    "path": "lib/unicorn/UnicornApplication.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef UNICORN_APPLICATION_H\n#define UNICORN_APPLICATION_H\n\n#include \"qtsingleapplication/qtsingleapplication.h\"\n\n#include \"common/HideStupidWarnings.h\"\n#include \"lib/DllExportMacro.h\"\n#include \"UnicornSession.h\"\n#include <QApplication>\n#include <QDebug>\n#include <QMainWindow>\n#include <QPointer>\n\n#ifdef Q_OS_MAC\n#include \"UnicornApplicationDelegate.h\"\n#endif\n\n#ifdef Q_OS_MAC64\n#include <Carbon/Carbon.h>\n#endif\n\nnamespace lastfm{\n    class User;\n    class InternetConnectionMonitor;\n}\n\nclass LoginContinueDialog;\nclass QNetworkReply;\n\nnamespace unicorn\n{\n    class Bus;\n\n    /**\n     * Unicorn base Application.\n     *\n     * Child classes should make sure to call the protected function initiateLogin\n     * on their constructor otherwise the app would probably crash, as there will be\n     * no valid user session.\n     */\n    class UNICORN_DLLEXPORT Application : public QtSingleApplication\n    {\n        Q_OBJECT\n\n        bool m_logoutAtQuit;\n\n    public:\n        class StubbornUserException\n        {};\n\n        /** will put up the log in dialog if necessary, throwing if the user\n          * cancels, ie. they refuse to log in */\n        Application(const QString &id, int &argc, char **argv) throw( StubbornUserException );\n        ~Application();\n\n        virtual void init();\n\n        /** Will return the actual stylesheet that is loaded if one is specified\n           (on the command-line with -stylesheet or with setStyleSheet(). )\n           Note. the QApplication styleSheet property will return the path \n                 to the css file unlike this method. */\n        const QString& loadedStyleSheet() const {\n            return m_styleSheet;\n        }\n\n        Session& currentSession() const;\n\n        static unicorn::Application* instance(){ return (unicorn::Application*)qApp; }\n        void* installHotKey( Qt::KeyboardModifiers, quint32, QObject* receiver, const char* slot );\n        void unInstallHotKey( void* id );\n        bool isInternetConnectionUp() const;\n\n        void translate();\n#ifdef Q_OS_MAC\n        void macTranslate( const QString& lang );\n        void showDockIcon( bool show );\n        UnicornApplicationDelegate* delegate() const { return m_delegate; }\n#endif\n    public slots:\n        void manageUsers();\n        void changeSession( const QString& username, const QString& sessionKey, bool announce = true );\n        void sendBusLovedStateChanged(bool loved);\n        void refreshStyleSheet();\n        void restart();\n\n    private:\n        void changeSession( unicorn::Session* newSession, bool announce = true );\n        void setupHotKeys();\n        void onHotKeyEvent(quint32 id);\n        void loadStyleSheet( QFile& );\n        QMainWindow* findMainWindow();\n\n        QString m_styleSheet;\n        QPointer<Session> m_currentSession;\n        bool m_wizardRunning;\n        QMap< quint32, QPair<QObject*, const char*> > m_hotKeyMap;\n        QString m_cssDir;\n        QString m_cssFileName;\n#ifdef Q_OS_MAC\n        QPointer<UnicornApplicationDelegate> m_delegate;\n\n        void setOpenApplicationEventHandler();\n        void setGetURLEventHandler();\n    public:\n        void appleEventReceived( const QStringList& messages );\n\n    private:\n        static OSStatus hotkeyEventHandler( EventHandlerCallRef, EventRef, void* );\n\n#ifdef Q_OS_MAC64\n        static OSErr appleEventHandler( const AppleEvent*, AppleEvent*, void* );\n#else\n        static short appleEventHandler( const AppleEvent*, AppleEvent*, long );\n#endif\n#endif\n#ifdef WIN32\n        static bool winEventFilter ( void* );\n#endif\n    protected:\n        /**\n         * Reimplement this function if you want to control the initial login process.\n         */\n        virtual void initiateLogin( bool forceWizard = false ) throw( StubbornUserException );\n\n        void setWizardRunning( bool running );\n\n        QPointer<Bus> m_bus;\n        lastfm::InternetConnectionMonitor* m_icm;\n\t\n\n    private slots:\n        void onWizardRunningQuery( const QString& );\n        void onBusSessionQuery( const QString& );\n        void onBusSessionChanged( const unicorn::Session& session );\n\n    signals:\n        void gotUserInfo( const lastfm::User& user );\n        void sessionChanged( const unicorn::Session& session );\n        void rosterUpdated();\n        void busLovedStateChanged(bool loved);\n        void internetConnectionUp();\n        void internetConnectionDown();\n    };\n}\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/UnicornApplicationDelegate.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef UNICORNAPPLICATIONDELEGATE_H\n#define UNICORNAPPLICATIONDELEGATE_H\n\n#include <QPixmap>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn {\n\nclass UnicornApplicationDelegateCommandObserver\n{\npublic:\n    virtual QString trackTitle() const = 0;\n    virtual QString artist() const = 0;\n    virtual QString album() const = 0;\n    virtual int duration() = 0;\n    virtual QPixmap artwork() = 0;\n    virtual bool loved() = 0;\n};\n\nclass UNICORN_DLLEXPORT UnicornApplicationDelegate : public QObject\n{\n    Q_OBJECT\npublic:\n    explicit UnicornApplicationDelegate( QObject *parent = 0 );\n\n    void showDockIcon( bool show );\n\n    void setCommandObserver( UnicornApplicationDelegateCommandObserver* observer );\n\n    void forceInitialize();\n    void forceApplicationDidFinishLaunching( void* aNotification );\n    \nsignals:\n    void initialize();\n    void applicationDidFinishLaunching( void* aNotification ); /* NSNotification */\n    \npublic:\n    UnicornApplicationDelegateCommandObserver* m_observer;\n};\n\n}\n\n#endif // UNICORNAPPLICATIONDELEGATE_H\n"
  },
  {
    "path": "lib/unicorn/UnicornApplicationDelegate.mm",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UnicornSettings.h\"\n#include \"UnicornApplicationDelegate.h\"\n\n#include <QWidget>\n#include <QApplication>\n#include <QDebug>\n\n#import <Cocoa/Cocoa.h>\n#import <AppKit/NSView.h>\n#import <Carbon/Carbon.h>\n\n// Declare this here ourselves so we can compile on OSX 10.6\n// and ProcessTransformToUIElementApplication just won't work\nenum {\n  ProcessTransformToForegroundApplication = 1,\n  ProcessTransformToBackgroundApplication = 2, /* functional in Mac OS X Barolo and later */\n  ProcessTransformToUIElementApplication = 4 /* functional in Mac OS X Barolo and later */\n};\n\n@interface LFMAppDelegate : NSObject <NSApplicationDelegate> {\n    unicorn::UnicornApplicationDelegate* m_observer;\n    BOOL m_show;\n}\n- (LFMAppDelegate*) init:(unicorn::UnicornApplicationDelegate*)observer;\n@end\n\n@implementation LFMAppDelegate\n\n- (LFMAppDelegate*) init:(unicorn::UnicornApplicationDelegate*)observer\n{\n    if ( (self = [super init]) )\n    {\n        self->m_observer = observer;\n    }\n\n    return self;\n}\n\n-(void)initialize\n{\n    m_observer->forceInitialize();\n}\n\n- (void)applicationWillFinishLaunching:(NSNotification *)aNotification\n{\n    qDebug() << \"applicationWillFinishLaunching\";\n\n    if ( unicorn::Settings().showDock() )\n    {\n        ProcessSerialNumber psn = { 0, kCurrentProcess };\n        TransformProcessType(&psn, ProcessTransformToForegroundApplication);\n        SetSystemUIMode(kUIModeNormal, 0);\n        [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@\"com.apple.dock\" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:nil];\n        [[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE];\n    }\n}\n\n\n- (void)applicationDidFinishLaunching:(NSNotification *)aNotification\n{\n    m_observer->forceApplicationDidFinishLaunching( aNotification );\n}\n\n\n- (BOOL)application:(NSApplication*)sender delegateHandlesKey:(NSString*)key\n{\n    Q_UNUSED(sender);\n    return [[NSSet setWithObjects: @\"trackTitle\", @\"artist\", @\"album\", @\"duration\", @\"artwork\", @\"loved\", nil] containsObject:key];\n}\n\n- (NSString*)trackTitle\n{\n    if ( m_observer->m_observer )\n    {\n        QString string = m_observer->m_observer->trackTitle();\n\n        if ( !string.isEmpty() )\n            return [NSString stringWithCharacters:(const unichar *)string.unicode() length:(NSUInteger)string.length() ];\n    }\n\n    return nil;\n}\n\n- (NSString*)artist\n{\n    if ( m_observer->m_observer )\n    {\n        QString string = m_observer->m_observer->artist();\n\n        if ( !string.isEmpty() )\n            return [NSString stringWithCharacters:(const unichar *)string.unicode() length:(NSUInteger)string.length() ];\n    }\n\n    return nil;\n}\n\n- (NSString*)album\n{\n    if ( m_observer->m_observer )\n    {\n        QString string = m_observer->m_observer->album();\n\n        if ( !string.isEmpty() )\n            return [NSString stringWithCharacters:(const unichar *)string.unicode() length:(NSUInteger)string.length() ];\n    }\n\n    return nil;\n}\n\n- (NSNumber*)duration\n{\n    return [NSNumber numberWithInt:m_observer->m_observer ? m_observer->m_observer->duration() : 0];\n}\n\n- (NSData*)artwork\n{\n    if ( m_observer->m_observer )\n    {\n        QPixmap pixmap = m_observer->m_observer->artwork();\n\n        if ( !pixmap.isNull() )\n        {\n            CGImageRef cgImage = pixmap.toMacCGImageRef();\n            NSImage* nsImage = [[NSImage alloc] initWithCGImage:(CGImageRef)cgImage size:(NSSize)NSZeroSize];\n            NSData* data = [nsImage TIFFRepresentation];\n            return data;\n        }\n        else\n        {\n            NSImage* img = [NSImage imageNamed: NSImageNameApplicationIcon];\n            NSData* data = [img TIFFRepresentation];\n            return data;\n        }\n    }\n\n    return nil;\n}\n\n- (BOOL)loved\n{\n    return m_observer->m_observer && m_observer->m_observer->loved() ? YES : NO;\n}\n\n@end\n\nLFMAppDelegate* g_appDelegate;\n\nunicorn::UnicornApplicationDelegate::UnicornApplicationDelegate(QObject *parent) :\n    QObject(parent), m_observer( 0 )\n{\n    g_appDelegate = [[LFMAppDelegate alloc] init:this];\n\n    [[NSApplication sharedApplication] setDelegate: g_appDelegate];\n}\n\nvoid\nunicorn::UnicornApplicationDelegate::showDockIcon( bool show )\n{\n    ProcessSerialNumber psn = { 0, kCurrentProcess };\n    TransformProcessType(&psn, show?ProcessTransformToForegroundApplication:ProcessTransformToUIElementApplication);\n    SetSystemUIMode(kUIModeNormal, 0);\n    [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@\"com.apple.dock\" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:nil];\n    [[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE];\n}\n\nvoid\nunicorn::UnicornApplicationDelegate::setCommandObserver( UnicornApplicationDelegateCommandObserver* observer )\n{\n    m_observer = observer;\n}\n\nvoid\nunicorn::UnicornApplicationDelegate::forceInitialize()\n{\n    emit initialize();\n}\n\nvoid\nunicorn::UnicornApplicationDelegate::forceApplicationDidFinishLaunching( void* aNotification )\n{\n    emit applicationDidFinishLaunching( aNotification );\n}\n\n"
  },
  {
    "path": "lib/unicorn/UnicornApplication_mac.mm",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UnicornApplication.h\"\n#import <Foundation/NSAppleEventDescriptor.h>\n#import <Foundation/NSAppleEventManager.h>\n#import <Foundation/NSObject.h>\n\nvoid \nunicorn::Application::setOpenApplicationEventHandler()\n{\n    NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];\n    [appleEventManager setEventHandler:NULL andSelector:NULL forEventClass:kCoreEventClass andEventID:kAEReopenApplication];\n}\n\nvoid\nunicorn::Application::setGetURLEventHandler()\n{\n    NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];\n    [appleEventManager setEventHandler:NULL andSelector:NULL forEventClass:kInternetEventClass andEventID:kAEGetURL];\n}\n\nvoid\nunicorn::Application::macTranslate( const QString& lang )\n{\n    NSString* langString = [NSString stringWithCharacters:(const unichar *)lang.unicode() length:(NSUInteger)lang.length() ];\n\n    [[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObject:langString] forKey:@\"AppleLanguages\"];\n}\n\n"
  },
  {
    "path": "lib/unicorn/UnicornCoreApplication.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n#include <QLocale>\n\n#include <lastfm/ws.h>\n#include <lastfm/misc.h>\n#include <lastfm/Fingerprint.h>\n\n#include \"UnicornCoreApplication.h\"\n\n#include \"common/c++/Logger.h\"\n\nusing namespace lastfm;\n\n#ifdef WIN32\nextern void qWinMsgHandler( QtMsgType t, const char* msg );\n#endif\n\nunicorn::CoreApplication::CoreApplication( const QString& id, int& argc, char** argv )\n                      : QtSingleCoreApplication( id, argc, argv )\n{\n    init();\n}\n\nunicorn::CoreApplication::CoreApplication( int& argc, char** argv )\n                      : QtSingleCoreApplication( argc, argv )\n{\n    init();\n}\n\nvoid //static\nunicorn::CoreApplication::init()\n{\n    QCoreApplication::setOrganizationName( \"Last.fm\" /*unicorn::organizationName() */ );\n    QCoreApplication::setOrganizationDomain( \"last.fm\" /*unicorn::organizationDomain()*/ );\n\n    // you can override this api key and secret by setting the\n    // environment variables LASTFM_API_KEY and LASTFM_API_SECRET\n    lastfm::ws::ApiKey = QString( API_KEY ).isEmpty() ? \"9e89b44de1ff37c5246ad0af18406454\" : API_KEY;\n    lastfm::ws::SharedSecret = QString( API_SECRET ).isEmpty() ? \"147320ea9b8930fe196a4231da50ada4\" : API_SECRET;\n\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n#ifdef Q_OS_MAC\n    QString pluginsDir = applicationDirPath() + \"/../plugins\";\n#else\n    QString pluginsDir = applicationDirPath() + \"/plugins\";\n#endif\n    addLibraryPath( pluginsDir );\n#endif\n\n\n    dir::runtimeData().mkpath( \".\" );\n#ifndef WIN32\n    QFile runtimeDataPerms( dir::runtimeData().absolutePath() );\n    runtimeDataPerms.setPermissions( QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner );\n#endif\n    dir::cache().mkpath( \".\" );\n    dir::logs().mkpath( \".\" );\n\n#ifdef WIN32\n    QString bytes = CoreApplication::log( applicationName() ).absoluteFilePath();\n    const wchar_t* path = bytes.utf16();\n#else\n    QByteArray bytes = CoreApplication::log( applicationName() ).absoluteFilePath().toLocal8Bit();\n    const char* path = bytes.data();\n#endif\n    new Logger( path );\n\n    qInstallMsgHandler( qMsgHandler );\n    qDebug() << \"Introducing\" << applicationName()+' '+applicationVersion();\n    qDebug() << \"Directed by\" << lastfm::platform();\n#if defined(Q_OS_MAC) || defined(Q_OS_WIN)\n    qDebug() << \"Plugin DIR\" << pluginsDir;\n#endif\n}\n\n\nvoid\nunicorn::CoreApplication::qMsgHandler( QtMsgType type, const char* msg )\n{\n#ifndef NDEBUG\n#ifdef WIN32\n    qWinMsgHandler( type, msg );\n#else\n    Q_UNUSED( type );\n    fprintf( stderr, \"%s\\n\", msg );\n    fflush( stderr );\n#endif\n#endif\n      \n    Logger::the().log( msg );\n}\n\n\nQFileInfo\nunicorn::CoreApplication::log( const QString& productName )\n{\n#ifdef NDEBUG\n    return dir::logs().filePath( productName + \".log\" );\n#else\n    return dir::logs().filePath( productName + \".debug.log\" );\n#endif\n}\n\nbool\nunicorn::CoreApplication::notify(QObject* receiver, QEvent* event )\n{\n    try\n    {\n        return QCoreApplication::notify( receiver, event );\n    }\n#ifdef LASTFM_FINGERPRINTER\n    catch( const lastfm::Fingerprint::Error& e )\n    {\n        qDebug() << \"Fingerprint error\" << e;\n        qApp->quit();\n    }\n#endif\n    catch(...)\n    {\n       qDebug() << \"Exception caught.\";\n       qApp->quit();\n    }\n\n    return false;\n}\n"
  },
  {
    "path": "lib/unicorn/UnicornCoreApplication.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef UNICORN_CORE_APPLICATION_H\n#define UNICORN_CORE_APPLICATION_H\n\n#include \"lib/DllExportMacro.h\"\n#include \"qtsingleapplication/qtsinglecoreapplication.h\"\n#include <QFileInfo>\n\n\nnamespace unicorn\n{\n    class UNICORN_DLLEXPORT CoreApplication : public QtSingleCoreApplication\n    {\n        Q_DISABLE_COPY(CoreApplication);\n\n    \tfriend class Application;\n\t\n    \tstatic void init();\n    \tstatic void qMsgHandler( QtMsgType, const char* );\n\t\n    public:\n        CoreApplication( const QString& id, int& argc, char** argv );\n        CoreApplication( int& argc, char** argv );\n\t\n    \tstatic QFileInfo log()\n    \t{\n    \t\tQ_ASSERT( applicationName().size() );\n    \t\treturn log( applicationName() );\n    \t}\n\t\n    \tstatic QFileInfo log( const QString& productName );\n    \t\n        static const char* platformString();\n\n        // We need to catch exceptions from event handlers.\n        // liblastfm-fingerprint is a bit exception happy...\n        virtual bool notify ( QObject * receiver, QEvent * event );\n    };\n}\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/UnicornMainWindow.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"UnicornMainWindow.h\"\n#include \"UnicornApplication.h\"\n#include \"UnicornCoreApplication.h\"\n#include \"dialogs/AboutDialog.h\"\n#include \"UnicornSettings.h\"\n#include <lastfm/User.h>\n#include <QDesktopServices>\n#include <QDesktopWidget>\n#include <QMenuBar>\n#include <QShortcut>\n#include <QMouseEvent>\n\n#include \"lib/unicorn/DesktopServices.h\"\n\n#ifdef Q_OS_WIN32\n#include <Objbase.h>\n#endif\n\n#define SETTINGS_POSITION_KEY \"MainWindowPosition\"\n#define SETTINGS_GEOMETRY_KEY \"Geo\"\n\n\nunicorn::MainWindow::MainWindow( QMenuBar* menuBar, QWidget* parent )\n    :QMainWindow( parent ), m_menuBar( menuBar )\n{\n    new QShortcut( QKeySequence(Qt::CTRL+Qt::Key_W), this, SLOT(close()) );\n    new QShortcut( QKeySequence(Qt::ALT+Qt::SHIFT+Qt::Key_L), this, SLOT(openLog()) );\n    connect( qApp->desktop(), SIGNAL( resized(int)), SLOT( cleverlyPosition()));\n#ifdef Q_OS_WIN32\n    taskBarCreatedMessage = RegisterWindowMessage(L\"TaskbarButtonCreated\");\n#endif\n}\n\n\nunicorn::MainWindow::~MainWindow()\n{\n}\n\n\nvoid\nunicorn::MainWindow::finishUi()\n{\n#ifndef NDEBUG\n    QMenu* debug = appMenuBar()->addMenu( \"Debug\" );\n    debug->addAction( tr(\"Refresh Stylesheet\"), qApp, SLOT(refreshStyleSheet()), Qt::CTRL + Qt::Key_R );\n#endif\n\n    cleverlyPosition();\n}\n\n\nvoid\nunicorn::MainWindow::refreshStyleSheet()\n{\n    static_cast<unicorn::Application*>(qApp)->refreshStyleSheet();\n}\n\n#ifdef Q_OS_WIN32\nbool      \nunicorn::MainWindow::winEvent(MSG* message, long* result)\n{\n    if ( message->message == taskBarCreatedMessage)\n    {\n\n\n        HRESULT hr = CoCreateInstance(CLSID_TaskbarList,\n                                      0,\n                                      CLSCTX_INPROC_SERVER,\n                                      IID_PPV_ARGS( &taskbar));\n        if (hr == S_OK)\n        {\n            m_thumbButtonActions.clear();\n            addWinThumbBarButtons( m_thumbButtonActions );\n\n            Q_ASSERT_X( m_thumbButtonActions.count() <= 7, \"winEvent\", \"More than 7 thumb buttons\" );\n\n            // make sure we update the thumb buttons everytime they change state\n            foreach ( QAction* button, m_thumbButtonActions )\n            {\n                connect( button, SIGNAL(changed()), SLOT(updateThumbButtons()));\n                connect( button, SIGNAL(toggled(bool)), SLOT(updateThumbButtons()));\n            }\n\n            if ( m_thumbButtonActions.count() > 0 )\n                updateThumbButtons();\n\n            *result = hr;\n            return true;\n        }\n    }\n    else if ( message->message == WM_COMMAND )\n        if ( HIWORD(message->wParam) == THBN_CLICKED )\n            m_thumbButtonActions[LOWORD(message->wParam)]->trigger();\n\n    return false;\n}\n\n\nvoid\nunicorn::MainWindow::updateThumbButtons()\n{\n    THUMBBUTTON buttons[7];\n\n    for ( int i(0) ; i < m_thumbButtonActions.count() ; ++i )\n    {\n        buttons[i].dwMask = THB_ICON|THB_TOOLTIP|THB_FLAGS;\n        buttons[i].iId = i;\n        buttons[i].hIcon = m_thumbButtonActions[i]->isChecked() ?\n            m_thumbButtonActions[i]->icon().pixmap( QSize(16, 16), QIcon::Normal, QIcon::On ).toWinHICON():\n            m_thumbButtonActions[i]->icon().pixmap( QSize(16, 16), QIcon::Normal, QIcon::Off ).toWinHICON();\n        wcscpy(buttons[i].szTip, m_thumbButtonActions[i]->text().utf16());\n\n        buttons[i].dwFlags = m_thumbButtonActions[i]->isEnabled() ? THBF_ENABLED : THBF_DISABLED;\n    }\n\n    if (sender())\n        taskbar->ThumbBarUpdateButtons(winId(), m_thumbButtonActions.count(), buttons);\n    else\n        taskbar->ThumbBarAddButtons(winId(), m_thumbButtonActions.count(), buttons);\n}\n#endif // Q_OS_WIN32\n\n\nvoid\nunicorn::MainWindow::openLog()\n{\n    unicorn::DesktopServices::openUrl( QUrl::fromLocalFile( unicorn::CoreApplication::log().absoluteFilePath() ) );    \n}\n\n\n\nbool \nunicorn::MainWindow::eventFilter( QObject* o, QEvent* event )\n{\n#ifdef SUPER_MEGA_DEBUG\n\tqDebug() << o << event;\n#endif\n\t\n    QWidget* obj = qobject_cast<QWidget*>( o );\n    if (!obj)\n        return false;\n    \n    QMouseEvent* e = static_cast<QMouseEvent*>( event );\n    \n    switch ((int)e->type())\n    {\n        case QEvent::MouseButtonPress:\n            m_dragHandleMouseDownPos[ obj ] = e->globalPos() - pos();\n            return false;\n\n        case QEvent::MouseButtonRelease:\n            m_dragHandleMouseDownPos[ obj ] = QPoint();\n            return false;\n            \n        case QEvent::MouseMove:\n            if (m_dragHandleMouseDownPos.contains( obj ) && !m_dragHandleMouseDownPos[ obj ].isNull()) {\n                move( e->globalPos() - m_dragHandleMouseDownPos[ obj ] );\n                return true;\n            }\n    }\n\n    return QMainWindow::eventFilter(o, event);\n}\n\n\nvoid \nunicorn::MainWindow::addDragHandleWidget( QWidget* w )\n{\n    w->installEventFilter( this );\n}\n\n\nvoid \nunicorn::MainWindow::hideEvent( QHideEvent* )\n{\n    emit hidden( false );\n}\n\n\nvoid \nunicorn::MainWindow::showEvent( QShowEvent* )\n{\n    emit shown( true );\n}\n\n\nvoid \nunicorn::MainWindow::storeGeometry() const\n{\n    AppSettings s;\n    s.beginGroup( metaObject()->className() );\n    s.setValue( SETTINGS_GEOMETRY_KEY, saveGeometry() );\n    s.endGroup();\n}\n\n\nvoid \nunicorn::MainWindow::moveEvent( QMoveEvent* )\n{\n    storeGeometry();\n}\n\n\nvoid\nunicorn::MainWindow::resizeEvent( QResizeEvent* )\n{\n    storeGeometry();\n}\n\n\nvoid\nunicorn::MainWindow::cleverlyPosition()\n{\n    AppSettings s;\n    s.beginGroup( metaObject()->className() );\n\n    if ( s.contains( SETTINGS_GEOMETRY_KEY ) )\n        restoreGeometry( s.value( SETTINGS_GEOMETRY_KEY, \"\" ).toByteArray() );\n\n    s.endGroup();\n\n    int screenNum = qApp->desktop()->screenNumber( this );\n    QRect screenRect = qApp->desktop()->availableGeometry( screenNum );\n\n    if( !screenRect.contains( frameGeometry(), true) )\n    {\n        // the window is not entirly inside the screen\n\n        // make sure it is able to fit\n        resize( qMin( screenRect.width(), width() ), qMin( screenRect.height(), height() ) );\n\n        // make sure the window is on the screen\n        QRect diff = screenRect.intersected( frameGeometry() );\n\n        if (diff.left() == screenRect.left() )\n            move( diff.left(), pos().y() );\n        if( diff.right() == screenRect.right() )\n            move( diff.right() - width(), pos().y() );\n        if( diff.top() == screenRect.top() )\n            move( pos().x(), diff.top() );\n        if( diff.bottom() == screenRect.bottom() )\n            move( pos().x(), diff.bottom() - height() );\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/UnicornMainWindow.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef UNICORN_MAIN_WINDOW\n#define UNICORN_MAIN_WINDOW\n\n\n#include \"lib/DllExportMacro.h\"\n#include <QMainWindow>\n#include <QPointer>\n#include <QMenuBar>\n#include <QDialog>\n#include <QMap>\n\n#ifdef Q_OS_WIN32\n#include <windows.h>\n#include <shobjidl.h>\n#endif\n\nclass AboutDialog;\nclass UpdateDialog;\nclass QNetworkReply;\n\n\ntemplate <typename D> struct OneDialogPointer : public QPointer<D>\n{    \n    OneDialogPointer& operator=( QDialog* d )\n    {\n        QPointer<D>::operator=( (D*)d );\n    \td->setAttribute( Qt::WA_DeleteOnClose ); \n    \td->setWindowFlags( Qt::Dialog | Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint ); \n    \td->setModal( false );\n        return *this;\n    }\n    \n    void show()\n    {\n        QDialog* d = (QDialog*)QPointer<D>::data();\n        d->show();\n        d->raise();\n        d->activateWindow();\n    }\n};\n\nnamespace lastfm { class User; }\n\nnamespace unicorn\n{\n    class Session;\n\n    class UNICORN_DLLEXPORT MainWindow : public ::QMainWindow\n    {\n        Q_OBJECT\n\n    public:\n        MainWindow( QMenuBar*, QWidget* parent = 0 );\n        ~MainWindow();\n\n        /** call this to add the account menu and about menu action, etc. */\n        void finishUi();\n        void addDragHandleWidget( QWidget* );\n\n        QMenuBar* appMenuBar() const { return m_menuBar; }\n\n    public slots:\n        void openLog();\n        void refreshStyleSheet();\n\n    private:\n        void storeGeometry() const;\n\n        virtual bool eventFilter( QObject*, QEvent* );\n        virtual void hideEvent( QHideEvent* );\n        virtual void showEvent( QShowEvent* );\n        virtual void moveEvent( QMoveEvent* );\n        virtual void resizeEvent( QResizeEvent* );\n\n        virtual void addWinThumbBarButtons( QList<QAction*>& ) {;}\n\n        QMenuBar* menuBar() const { return 0; }\n\n    protected:\n        QPointer<QMenuBar> m_menuBar;\n\n    private:\n        QList<QAction*> m_thumbButtonActions;\n\n#ifdef Q_OS_WIN32\n        bool canUseTaskBar;\n        UINT taskBarCreatedMessage;\n        ITaskbarList3* taskbar;\n\n    private:\n        bool winEvent(MSG* message, long* result);\n#endif\n\n        QMap<QWidget*, QPoint> m_dragHandleMouseDownPos;\n\n    private slots:\n        void cleverlyPosition();\n#ifdef Q_OS_WIN32\n        void updateThumbButtons();\n#endif\n    \n    signals:\n        void hidden( bool );   \n        void shown( bool );\n    };\n}\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/UnicornSession.cpp",
    "content": "/*\n   Copyright 2009-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QApplication>\n#include <QDebug>\n#include <QTimer>\n\n#include <lastfm/User.h>\n#include <lastfm/Auth.h>\n#include <lastfm/XmlQuery.h>\n\n#include \"UnicornSession.h\"\n#include \"UnicornSettings.h\"\n\nnamespace unicorn {\n\n\nQMap<QString, QString>\nSession::lastSessionData()\n{\n    Settings s;\n    QMap<QString, QString> sessionData;\n\n    //use the Username setting or the first username if there have been any logged in previously\n    QString username = s.value( \"Username\", QString() ).toString();\n\n    if( !username.isEmpty() )\n    {\n        UserSettings us( username );\n\n        sessionData[ \"username\" ] = username;\n        const QString sk = us.value( \"SessionKey\", \"\" ).toString();\n\n        if( !sk.isEmpty() )\n            sessionData[ \"sessionKey\" ] = sk;\n    }\n\n    return sessionData;\n}\n\nSession::Session()\n{\n    m_info.valid = false;\n}\n\nSession::Session( const QString& username, QString sessionKey )\n{\n    init( username, sessionKey );\n    connect( qApp, SIGNAL( internetConnectionUp() ), SLOT( fetchInfo() ) );\n}\n\nSession::Session( QDataStream& dataStream )\n{\n    dataStream >> *this;\n    connect( qApp, SIGNAL( internetConnectionUp() ), SLOT( fetchInfo() ) );\n}\n\nQNetworkReply*\nSession::getToken()\n{\n    QMap<QString, QString> params;\n    params[\"method\"] = \"auth.getToken\";\n    return lastfm::ws::get( params );\n}\n\nQNetworkReply*\nSession::getSession( QString token )\n{\n    QMap<QString, QString> params;\n    params[\"method\"] = \"auth.getSession\";\n    params[\"token\"] = token;\n    return lastfm::ws::post( params, false );\n}\n\nQString\nSession::subscriptionPriceString() const\n{\n    return m_info.subscriptionPrice;\n}\n\nbool\nSession::isValid() const\n{\n    return m_info.valid;\n}\n\n\nbool\nSession::youRadio() const\n{\n    return m_info.youRadio;\n}\n\nbool\nSession::registeredRadio() const\n{\n    return m_info.registeredRadio;\n}\n\nbool\nSession::subscriberRadio() const\n{\n    return m_info.subscriberRadio;\n}\n\nbool\nSession::youWebRadio() const\n{\n    return m_info.youWebRadio;\n}\n\nbool\nSession::registeredWebRadio() const\n{\n    return m_info.registeredWebRadio;\n}\n\nbool\nSession::subscriberWebRadio() const\n{\n    return m_info.subscriberWebRadio;\n}\n\nQString \nSession::sessionKey() const\n{\n    return m_sessionKey;\n}\n\nlastfm::User\nSession::user() const\n{\n    return m_user;\n}\n\nvoid \nSession::init( const QString& username, const QString& sessionKey )\n{\n    Settings s;\n    s.setValue( \"Username\", username );\n\n    m_user.setName( username );\n    m_sessionKey = sessionKey;\n\n    UserSettings us( username );\n    m_user.setName( username );\n    m_user.setScrobbleCount( us.scrobbleCount() );\n    m_user.setDateRegistered( us.dateRegistered() );\n    m_user.setRealName( us.realName() );\n    m_user.setIsSubscriber( us.subscriber() );\n    m_user.setType( us.type() );\n\n    QList<QUrl> imageUrls;\n    int imageCount = us.beginReadArray( \"ImageUrls\" );\n\n    for ( int i = 0; i < imageCount; i++ )\n    {\n        us.setArrayIndex( i );\n        imageUrls.append( us.value( \"Url\", QUrl() ).toUrl() );\n    }\n\n    us.endArray();\n\n    m_user.setImages( imageUrls );\n\n    if ( sessionKey.isEmpty() )\n        Q_ASSERT( false );\n    else\n        us.setValue( \"SessionKey\", sessionKey );\n\n    m_info = us.sessionInfo();\n\n    fetchInfo();\n}\n\nvoid\nSession::fetchInfo()\n{\n    qDebug() << \"fetching user info\";\n    lastfm::ws::Username = m_user.name();\n    lastfm::ws::SessionKey = m_sessionKey;\n    connect( lastfm::User::getInfo(), SIGNAL( finished() ), SLOT( onUserGotInfo() ) );\n    connect( lastfm::Auth::getSessionInfo(), SIGNAL(finished()), SLOT(onAuthGotSessionInfo()) );\n}\n\nvoid\nSession::onUserGotInfo()\n{\n    QNetworkReply* reply = ( QNetworkReply* )sender();\n\n    XmlQuery lfm;\n\n    if ( lfm.parse( reply ) )\n    {\n        lastfm::User user( lfm[\"user\"] );\n\n        m_user = user;\n        cacheUserInfo( m_user );\n\n        emit userInfoUpdated( m_user );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\nvoid\nSession::onAuthGotSessionInfo()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( static_cast<QNetworkReply*>( sender() ) ) )\n    {\n        qDebug() << lfm;\n\n        m_info.valid = true;\n\n        m_info.subscriptionPrice = lfm[\"application\"][\"radioprice\"][\"formatted\"].text();\n\n        XmlQuery you = lfm[\"application\"][\"radioPermission\"][\"user type=you\"];\n        m_info.youRadio = you[\"radio\"].text() == \"1\";\n        m_info.youWebRadio = you[\"webradio\"].text() == \"1\";\n\n        XmlQuery registered = lfm[\"application\"][\"radioPermission\"][\"user type=registered\"];\n        m_info.registeredRadio = registered[\"radio\"].text() == \"1\";\n        m_info.registeredWebRadio = registered[\"webradio\"].text() == \"1\";\n\n        XmlQuery subscriber = lfm[\"application\"][\"radioPermission\"][\"user type=subscriber\"];\n        m_info.subscriberRadio = subscriber[\"radio\"].text() == \"1\";\n        m_info.subscriberWebRadio = subscriber[\"webradio\"].text() == \"1\";\n\n        bool isSubscriber = lfm[\"application\"][\"session\"][\"subscriber\"].text() == \"1\";\n        m_user.setIsSubscriber( isSubscriber );\n\n        cacheUserInfo( m_user ); // make sure the subscriber flag gets cached\n        cacheSessionInfo( *this );\n\n        emit sessionChanged( *this );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\nvoid\nSession::cacheUserInfo( const lastfm::User& user )\n{\n    UserSettings us( user.name() );\n    us.setSubscriber( user.isSubscriber() );\n    us.setValue( \"ScrobbleCount\", user.scrobbleCount() );\n    us.setValue( \"DateRegistered\", user.dateRegistered() );\n    us.setValue( \"RealName\", user.realName() );\n    us.setValue( \"Type\", user.type() );\n\n    QList<User::ImageSize> sizes;\n    sizes << User::SmallImage << User::MediumImage << User::LargeImage;\n\n    us.beginWriteArray( \"ImageUrls\", sizes.count() );\n    for ( int i = 0; i < sizes.count(); i++ )\n    {\n        us.setArrayIndex( i );\n        us.setValue( \"Url\", user.imageUrl( sizes[ i ] ) );\n    }\n    us.endArray();\n}\n\nvoid\nSession::cacheSessionInfo( const unicorn::Session& session )\n{\n    UserSettings userSettings( session.user().name() );\n    userSettings.setSessionInfo( m_info );\n}\n\nQDataStream&\nSession::write( QDataStream& out ) const\n{\n    QMap<QString, QString> data;\n    data[ \"username\" ] = user().name();\n    data[ \"sessionkey\" ] = m_sessionKey;\n    out << data;\n    return out;\n}\n\nQDataStream&\nSession::read( QDataStream& in )\n{\n    QMap<QString, QString> data;\n    in >> data;\n    init( data[ \"username\" ], data[ \"sessionkey\" ] );\n    return in;\n}\n\n}\n\nQDataStream& operator<<( QDataStream& out, const unicorn::Session& s ){ return s.write( out ); }\nQDataStream& operator>>( QDataStream& in, unicorn::Session& s ){ return s.read( in ); }\n\n"
  },
  {
    "path": "lib/unicorn/UnicornSession.h",
    "content": "/*\n   Copyright 2009-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef UNICORN_SESSION_H_\n#define UNICORN_SESSION_H_\n\n#include <lastfm/XmlQuery.h>\n#include <lastfm/misc.h>\n#include <lastfm/User.h>\n#include <lastfm/ws.h>\n\n#include <QObject>\n#include <QSharedData>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn {\n\nclass UNICORN_DLLEXPORT Session : public QObject\n{\n    Q_OBJECT\npublic:\n    struct Info\n    {\n        bool valid;\n\n        QString subscriptionPrice;\n\n        bool youRadio;\n        bool registeredRadio;\n        bool subscriberRadio;\n\n        bool youWebRadio;\n        bool registeredWebRadio;\n        bool subscriberWebRadio;\n    };\n\npublic:\n    /** Return session object from stored session */\n    Session();\n    Session( QDataStream& dataStream );\n    Session( const QString& username, QString sessionKey = \"\" );\n\n    bool isValid() const;\n\n    // client radio permissions\n    bool youRadio() const;\n    bool registeredRadio() const;\n    bool subscriberRadio() const;\n\n    // web radio permissions\n    bool youWebRadio() const;\n    bool registeredWebRadio() const;\n    bool subscriberWebRadio() const;\n\n    QString subscriptionPriceString() const;\n\n    QString sessionKey() const;\n    lastfm::User user() const;\n\n    static QNetworkReply* getToken();\n    static QNetworkReply* getSession( QString token );\n    static QMap<QString, QString> lastSessionData();\n\n    QDataStream& write( QDataStream& out ) const;\n    QDataStream& read( QDataStream& in );\n\nsignals:\n    void userInfoUpdated( const lastfm::User& user );\n    void sessionChanged( const unicorn::Session& session );\n\nprotected:\n    void init( const QString& username, const QString& sessionKey );\n\nprivate:\n    void cacheUserInfo( const lastfm::User& user );\n    void cacheSessionInfo( const unicorn::Session& session );\n\nprivate slots:\n    void fetchInfo();\n    void onUserGotInfo();\n    void onAuthGotSessionInfo();\n\nprivate:\n    QString m_prevUsername;\n    QString m_sessionKey;\n    lastfm::User m_user;\n\n    Info m_info;\n};\n\n}\n\nQDataStream& operator<<( QDataStream& out, const unicorn::Session& s );\nQDataStream& operator>>( QDataStream& in, unicorn::Session& s );\n\n#endif //UNICORN_SESSION_H_\n"
  },
  {
    "path": "lib/unicorn/UnicornSettings.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UnicornSettings.h\"\n#include \"UnicornApplication.h\"\n#include <lastfm/User.h>\n\nunicorn::Settings::Settings()\n    :QSettings( unicorn::organizationName(), \"\" )\n{}\n\nQList<lastfm::User>\nunicorn::Settings::userRoster() const\n{\n    const_cast<Settings*>(this)->beginGroup( \"Users\" );\n    QList<User> ret;\n    foreach( QString child, childGroups()) {\n        if( child == \"com\" || !contains( child + \"/SessionKey\" )) continue;\n        ret << User( child );\n    }\n    const_cast<Settings*>(this)->endGroup();\n    return ret;\n}\n\n\nbool\nunicorn::Settings::firstRunWizardCompleted() const\n{\n    return value( \"FirstRunWizardCompletedBeta\", false ).toBool();\n}\n\nvoid\nunicorn::Settings::setFirstRunWizardCompleted( bool firstRunWizardCompleted )\n{\n    setValue( \"FirstRunWizardCompletedBeta\", firstRunWizardCompleted );\n}\n\nbool\nunicorn::Settings::betaUpdates() const\n{\n    return value( \"betaUpdates\", false ).toBool();\n}\n\nvoid\nunicorn::Settings::setBetaUpdates( bool betaUpdates )\n{\n    setValue( \"betaUpdates\", betaUpdates );\n}\n\nvoid\nunicorn::Settings::showWhere()\n{\n    int showWhereIndex = value( \"showWhere\", -1 ).toInt();\n\n    if ( showWhereIndex != -1 )\n    {\n        // 0 == show both, 1 == show only dock, 2 == show only menu bar\n        setShowAS( showWhereIndex != 1 );\n        setShowDock( showWhereIndex != 2 );\n\n        remove( \"showWhere\" ); // don't read this setting again\n    }\n}\n\nbool\nunicorn::Settings::showAS()\n{\n    showWhere();\n    return value( \"showAS\", true ).toBool();\n}\n\nvoid\nunicorn::Settings::setShowAS( bool showAS )\n{\n    setValue( \"showAS\", showAS );\n}\n\nbool\nunicorn::Settings::showDock()\n{\n    showWhere();\n    return value( \"showDock\", true ).toBool();\n}\n\nvoid\nunicorn::Settings::setShowDock( bool showDock )\n{\n    setValue( \"showDock\", showDock );\n}\n\nbool\nunicorn::Settings::notifications() const\n{\n    return value( \"notifications\", true ).toBool();\n}\n\nvoid\nunicorn::Settings::setNotifications( bool notifications )\n{\n    setValue( \"notifications\", notifications );\n}\n\nbool\nunicorn::Settings::sendCrashReports() const\n{\n    return value( \"sendCrashReports\", true ).toBool();\n}\n\nvoid\nunicorn::Settings::setSendCrashReports( bool sendCrashReports )\n{\n    setValue( \"sendCrashReports\", sendCrashReports );\n}\n\nbool\nunicorn::Settings::checkForUpdates() const\n{\n    return value( \"checkForUpdates\", true ).toBool();\n}\n\nvoid\nunicorn::Settings::setCheckForUpdates( bool checkForUpdates )\n{\n    setValue( \"checkForUpdates\", checkForUpdates );\n}\n\nunicorn::AppSettings::AppSettings( QString appname )\n    : QSettings( unicorn::organizationName(), appname.isEmpty() ? qApp->applicationName() : appname )\n{}\n\nunicorn::UserSettings::UserSettings( QString username )\n{\n    beginGroup( \"Users\" );\n    beginGroup( username );\n}\n\n\nbool\nunicorn::AppSettings::alwaysAsk() const\n{\n    return value( \"alwaysAsk\", true ).toBool();\n}\n\nvoid\nunicorn::AppSettings::setAlwaysAsk( bool alwaysAsk )\n{\n    setValue( \"alwaysAsk\", alwaysAsk );\n}\n\nunicorn::OldeAppSettings::OldeAppSettings()\n    : AppSettings(\n#ifdef Q_OS_MAC\n\"scrobbler\"\n#else\n\"Client\"\n#endif\n          )\n{}\n\nbool\nunicorn::OldeAppSettings::deviceScrobblingEnabled() const\n{\n    return value( \"iPodScrobblingEnabled\", true ).toBool();\n}\n\nvoid\nunicorn::OldeAppSettings::setDeviceScrobblingEnabled( bool deviceScrobblingEnabled )\n{\n    setValue( \"iPodScrobblingEnabled\", deviceScrobblingEnabled );\n}\n\nbool\nunicorn::OldeAppSettings::launchWithMediaPlayers() const\n{\n    return value( \"LaunchWithMediaPlayer\", true ).toBool();\n}\n\nvoid\nunicorn::OldeAppSettings::setLaunchWithMediaPlayers( bool LaunchWithMediaPlayers )\n{\n    setValue( \"LaunchWithMediaPlayer\", LaunchWithMediaPlayers );\n}\n\nunicorn::Session::Info\nunicorn::UserSettings::sessionInfo()\n{\n    unicorn::Session::Info info;\n\n    beginGroup( \"Session\" );\n\n    info.valid = value( \"valid\", false ).toBool();\n    info.subscriptionPrice = value( \"subscriptionPrice\", \"\" ).toString();\n    info.youRadio = value( \"youRadio\", false ).toBool();\n    info.registeredRadio = value( \"registeredRadio\", false ).toBool();\n    info.subscriberRadio = value( \"subscriberRadio\", false ).toBool();\n    info.youWebRadio = value( \"youWebRadio\", false ).toBool();\n    info.registeredWebRadio = value( \"registeredWebRadio\", false ).toBool();\n    info.subscriberWebRadio = value( \"subscriberWebRadio\", false ).toBool();\n\n    endGroup();\n\n    return info;\n}\n\nvoid\nunicorn::UserSettings::setSessionInfo( const unicorn::Session::Info& sessionInfo )\n{\n    beginGroup( \"Session\" );\n    setValue( \"valid\", sessionInfo.valid );\n    setValue( \"subscriptionPrice\", sessionInfo.subscriptionPrice );\n    setValue( \"youRadio\", sessionInfo.youRadio );\n    setValue( \"registeredRadio\", sessionInfo.registeredRadio );\n    setValue( \"subscriberRadio\", sessionInfo.subscriberRadio );\n    setValue( \"youWebRadio\", sessionInfo.youWebRadio );\n    setValue( \"registeredWebRadio\", sessionInfo.registeredWebRadio );\n    setValue( \"subscriberWebRadio\", sessionInfo.subscriberWebRadio );\n    endGroup();\n}\n\nbool\nunicorn::UserSettings::subscriber() const\n{\n    return value( \"subscriber\", false ).toBool();\n}\n\nvoid\nunicorn::UserSettings::setSubscriber( bool subscriber )\n{\n    setValue( \"subscriber\", subscriber );\n}\n\nQString\nunicorn::UserSettings::sessionKey() const\n{\n    return value( \"SessionKey\", \"\" ).toString();\n}\n\nvoid\nunicorn::UserSettings::setSessionKey( const QString& sessionKey )\n{\n    setValue( \"SessionKey\", sessionKey );\n}\n\nquint32\nunicorn::UserSettings::scrobbleCount() const\n{\n    return value( \"ScrobbleCount\", 0 ).toUInt();\n}\n\nvoid\nunicorn::UserSettings::setScrobbleCount( quint32 scrobbleCount )\n{\n    setValue( \"ScrobbleCount\", scrobbleCount );\n}\n\nQDateTime\nunicorn::UserSettings::dateRegistered() const\n{\n    return value( \"DateRegistered\", false ).toDateTime();\n}\n\nvoid\nunicorn::UserSettings::setDateRegistered( const QDateTime& dateRegistered )\n{\n    setValue( \"DateRegistered\", dateRegistered );\n}\n\nQString\nunicorn::UserSettings::realName() const\n{\n    return value( \"RealName\", \"\" ).toString();\n}\n\nvoid\nunicorn::UserSettings::setRealName( const QString& realName )\n{\n    setValue( \"RealName\", realName );\n}\n\nUser::Type\nunicorn::UserSettings::type() const\n{\n    return static_cast<User::Type>( value( \"Type\", User::TypeUser ).toInt() );\n}\n\nvoid\nunicorn::UserSettings::setType( User::Type type )\n{\n    setValue( \"Type\", type );\n}\n\ndouble\nunicorn::UserSettings::scrobblePoint() const\n{\n    return value( \"scrobblePoint\", 50 ).toDouble();\n}\n\nvoid\nunicorn::UserSettings::setScrobblePoint( double scrobblePoint )\n{\n    setValue( \"scrobblePoint\", scrobblePoint );\n}\n\nbool\nunicorn::UserSettings::fingerprinting() const\n{\n    return value( \"fingerprint\", true ).toBool();\n}\n\nvoid\nunicorn::UserSettings::setFingerprinting( bool fingerprinting )\n{\n    setValue( \"fingerprint\", fingerprinting );\n}\n\nbool\nunicorn::UserSettings::podcasts() const\n{\n    return value( \"podcasts\", true ).toBool();\n}\n\nvoid\nunicorn::UserSettings::setPodcasts( bool podcasts )\n{\n    setValue( \"podcasts\", podcasts );\n}\n\nbool\nunicorn::UserSettings::scrobblingOn() const\n{\n    return value( \"scrobblingOn\", true ).toBool();\n}\n\nvoid\nunicorn::UserSettings::setScrobblingOn( bool scrobblingOn )\n{\n    setValue( \"scrobblingOn\", scrobblingOn );\n}\n\nQStringList\nunicorn::UserSettings::exclusionDirs() const\n{\n    return value( \"ExclusionDirs\", QStringList() ).toStringList();\n}\n\nvoid\nunicorn::UserSettings::setExclusionDirs( const QStringList& exclusionDirs )\n{\n    setValue( \"ExclusionDirs\", exclusionDirs );\n}\n\nbool\nunicorn::UserSettings::enforceScrobbleTimeMax() const\n{\n    return value( \"enforceScrobbleTimeMax\", true ).toBool();\n}\n\nvoid\nunicorn::UserSettings::setEnforceScrobbleTimeMax( bool enforceScrobbleTimeMax )\n{\n    setValue( \"enforceScrobbleTimeMax\", enforceScrobbleTimeMax );\n}\n"
  },
  {
    "path": "lib/unicorn/UnicornSettings.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef UNICORN_SETTINGS_H\n#define UNICORN_SETTINGS_H\n\n#include \"lib/unicorn/UnicornSession.h\"\n\n#include \"lib/DllExportMacro.h\"\n\n#include <lastfm/User.h>\n\n#include <QSettings>\n#include <QString>\n#include <QCoreApplication>\n\nnamespace unicorn\n{\n    inline const char* organizationName() { return \"Last.fm\"; }\n    inline const char* organizationDomain() { return \"last.fm\"; }\n\n    class UNICORN_DLLEXPORT Settings : public QSettings\n    {\n    public:\n        Settings();\n\n        QList<lastfm::User> userRoster() const;\n\n        bool firstRunWizardCompleted() const;\n        void setFirstRunWizardCompleted( bool firstRunWizardCompleted );\n\n        bool betaUpdates() const;\n        void setBetaUpdates( bool betaUpdates );\n\n        bool showAS();\n        void setShowAS( bool showAS );\n\n        bool showDock();\n        void setShowDock( bool showDock );\n\n        bool notifications() const;\n        void setNotifications( bool notifications );\n\n        bool sendCrashReports() const;\n        void setSendCrashReports( bool sendCrashReports );\n\n        bool checkForUpdates() const;\n        void setCheckForUpdates( bool checkForUpdates );\n\n\n    private:\n        void showWhere();\n    };\n\n    class UNICORN_DLLEXPORT AppSettings : public QSettings\n    {\n    public:\n        AppSettings( QString appname = QCoreApplication::applicationName() );\n\n        bool alwaysAsk() const;\n        void setAlwaysAsk( bool alwaysAsk );\n    };\n\n    class UNICORN_DLLEXPORT OldeAppSettings : public AppSettings\n    {\n    public:\n        OldeAppSettings();\n\n        bool deviceScrobblingEnabled() const;\n        void setDeviceScrobblingEnabled( bool deviceScrobblingEnabled );\n\n        bool launchWithMediaPlayers() const;\n        void setLaunchWithMediaPlayers( bool launchWithMediaPlayers );\n    };\n\n\n    /** Clearly no use until a username() has been assigned. But this is\n      * automatic if you use unicorn::Application anyway. */\n    class UNICORN_DLLEXPORT UserSettings : public Settings\n    {\n    public:\n        struct SessionInfo\n        {\n\n        };\n\n        UserSettings( QString userName = User() );\n\n        unicorn::Session::Info sessionInfo();\n        void setSessionInfo( const unicorn::Session::Info& sessionInfo );\n\n        bool subscriber() const;\n        void setSubscriber( bool subscriber );\n\n        QString sessionKey() const;\n        void setSessionKey( const QString& sessionKey );\n\n        quint32 scrobbleCount() const;\n        void setScrobbleCount( quint32 scrobbleCount );\n\n        QDateTime dateRegistered() const;\n        void setDateRegistered( const QDateTime& dateRegistered );\n\n        QString realName() const;\n        void setRealName( const QString& realName );\n\n        User::Type type() const;\n        void setType( User::Type type );\n\n        double scrobblePoint() const;\n        void setScrobblePoint( double scrobblePoint );\n\n        bool fingerprinting() const;\n        void setFingerprinting( bool fingerprinting );\n\n        bool podcasts() const;\n        void setPodcasts( bool podcasts );\n\n        bool scrobblingOn() const;\n        void setScrobblingOn( bool scrobblingOn );\n\n        QStringList exclusionDirs() const;\n        void setExclusionDirs( const QStringList& exclusionDirs );\n\n        bool enforceScrobbleTimeMax() const;\n        void setEnforceScrobbleTimeMax( bool enforceScrobbleTimeMax );\n    };\n}\n\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/UpdateInfoFetcher.cpp",
    "content": "/*\n   Copyright 2009-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UpdateInfoFetcher.h\"\n#include <lastfm/ws.h>\n#include <lastfm/XmlQuery.h>\n#include <QDebug>\n#include <QSettings>\n#include <QString>\n\n#ifdef WIN32\n    static const char *PLATFORM = \"win\";\n#elif defined Q_WS_X11\n    static const char *PLATFORM = \"linux\";\n#elif defined Q_WS_MAC\n    static const char *PLATFORM = \"mac\";\n#else\n    static const char *PLATFORM = \"unknown\";\n#endif\n\nPlugin::Plugin( const XmlQuery& query )\n       :m_bootstrapType( NoBootstrap ),\n        m_valid( true )\n\n{\n    m_name = query.attribute( \"name\" );\n    m_id = query.attribute( \"id\" );\n    m_url = QUrl( query[\"Url\"].text() );\n    m_installDir = QDir( query[ \"InstallDir\" ].text() );\n    m_args = query[\"Args\"].text();\n    m_minVersion = query[\"MinVersion\"].text();\n    m_maxVersion = query[\"MaxVersion\"].text();\n    m_regDisplayName = query[\"RegDisplayName\"].text();\n\n    QString bs = query[\"Bootstrap\"].text();\n    if( bs.compare( \"Client\", Qt::CaseInsensitive ) == 0) {\n        m_bootstrapType = ClientBootstrap;\n    } else if( bs.compare( \"Plugin\", Qt::CaseInsensitive ) == 0) {\n        m_bootstrapType = PluginBootstrap;\n    }\n}\n\n\nbool \nPlugin::isInstalled() const\n{\n#ifdef Q_OS_WIN\n    QSettings s(\"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall\\\\\", QSettings::NativeFormat );\n    foreach( QString group, s.childGroups()) {\n        s.beginGroup( group );\n            QString name = s.value( \"DisplayName\" ).toString();\n            if( name.contains( m_regDisplayName ) ||\n                group.contains( m_regDisplayName )) {\n                    return true;\n            }\n        s.endGroup();\n    }\n    return false;\n#elif defined Q_OS_MAC\n    return true;\n#endif\n}\n\n\nbool \nPlugin::isPluginInstalled() const\n{\n#ifdef Q_OS_WIN\n    QSettings s( \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Last.fm\\\\Client\\\\Plugins\", QSettings::NativeFormat );\n    return s.childGroups().contains( m_id );\n#elif defined Q_OS_MAC\n    return true;\n#endif\n}\n\n\nbool\nPlugin::canBootstrap() const\n{\n    return m_bootstrapType != NoBootstrap;\n}\n\n\nUpdateInfoFetcher::UpdateInfoFetcher( QNetworkReply* reply, QObject* parent )\n                  :QObject( parent )\n{\n    XmlQuery xq;\n    xq.parse( reply );\n\n    QList<XmlQuery> plugins = xq.children( \"Plugin\" );\n    foreach( const XmlQuery& plugin, plugins ) {\n        m_plugins << Plugin( plugin );\n    }\n}\n\n\nQNetworkReply* \nUpdateInfoFetcher::fetchInfo() //static\n{\n    QString url = QString( \"http://%1/ass/upgrade.xml.php?platform=%2&lang=en\" ).arg( lastfm::ws::host(), PLATFORM );\n    QNetworkRequest req( url );\n    return lastfm::nam()->get( req );\n}\n"
  },
  {
    "path": "lib/unicorn/UpdateInfoFetcher.h",
    "content": "/*\r\n   Copyright 2009-2012 Last.fm Ltd. \r\n      - Primarily authored by Jono Cole and Michael Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#ifndef UPDATE_INFO_FETCHER_H_\r\n#define UPDATE_INFO_FETCHER_H_\r\n#include <QObject>\r\n#include \"lib/DllExportMacro.h\"\r\n#include <QUrl>\r\n#include <QDir>\r\n\r\nnamespace lastfm{ class XmlQuery; }\r\n\r\nclass UNICORN_DLLEXPORT Plugin\r\n{\r\npublic:\r\n    enum BootstrapType{ NoBootstrap, ClientBootstrap, PluginBootstrap };\r\n\r\n    Plugin(): m_valid( false ){}\r\n    Plugin( const lastfm::XmlQuery& );\r\n\r\n    QString toString() const { \r\n         return QString( \"%1 (%2 - %3)\\n\\tinstallDir: %4\\n\\targs:%5\\n\\tregDisplayName: %6\" )\r\n                    .arg( m_name )\r\n                    .arg( m_minVersion )\r\n                    .arg( m_maxVersion )\r\n                    .arg( m_installDir.path() )\r\n                    .arg( m_args )\r\n                    .arg( m_regDisplayName );\r\n    }\r\n    \r\n    QString name() const { return m_name; }\r\n    QString regDisplayName() const { return m_regDisplayName; }\r\n\r\n    bool isValid() const { return m_valid; }\r\n    bool isInstalled() const;\r\n    bool isPluginInstalled() const;\r\n    bool canBootstrap() const;\r\n\r\nprivate:\r\n    QString m_name;\r\n    QString m_id;\r\n    QUrl m_url;\r\n    QDir m_installDir;\r\n    QString m_args;\r\n    QString m_minVersion;\r\n    QString m_maxVersion;\r\n    QString m_regDisplayName;\r\n\r\n    BootstrapType m_bootstrapType;\r\n\r\n    bool m_valid;\r\n};\r\n\r\n\r\nclass UNICORN_DLLEXPORT UpdateInfoFetcher : public QObject\r\n{\r\nQ_OBJECT\r\npublic:\r\n    UpdateInfoFetcher( class QNetworkReply* reply, QObject* parent = 0 );\r\n    static QNetworkReply* fetchInfo();\r\n    const QList<Plugin>& plugins() const{ return m_plugins; }\r\n\r\nprivate:\r\n    QList<Plugin> m_plugins;\r\n};\r\n\r\n#endif //UPDATE_INFO_FETCHER_H_\r\n"
  },
  {
    "path": "lib/unicorn/Updater/Updater.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Updater.h\"\n\n#ifndef Q_OS_MAC\n\n#ifdef Q_OS_WIN\n#include <QCoreApplication>\n#include <QStringList>\n#include <qtsparkle/Updater>\n#endif\n\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n\nunicorn::Updater::Updater( QWidget* parent ) :\n    QObject(parent), m_parentWidget( parent )\n{\n#ifdef Q_OS_WIN\n\n    if ( qApp->arguments().contains( \"--update\" ) )\n    {\n        int urlIndex = qApp->arguments().indexOf( \"--update\" ) + 1;\n\n        if ( qApp->arguments().count() > urlIndex && qApp->arguments()[urlIndex].startsWith( \"https://\" ) )\n        {\n            m_updater = new qtsparkle::Updater( QUrl( QString( qApp->arguments()[urlIndex].toUtf8() ) ), m_parentWidget );\n            m_updater->SetNetworkAccessManager( lastfm::nam() );\n            m_updater->SetIcon( QPixmap( \":/scrobbler_64.png\" ) );\n        }\n        else\n            setBetaUpdates( unicorn::Settings().betaUpdates() );\n    }\n    else\n        setBetaUpdates( unicorn::Settings().betaUpdates() );\n\n\n#endif\n}\n\nvoid\nunicorn::Updater::setBetaUpdates( bool betaUpdates )\n{\n#ifdef Q_OS_WIN\n    if ( !m_updater || m_betaUpdates != betaUpdates )\n    {\n        // there is no updater yet or we are changing the update file\n        m_betaUpdates = betaUpdates;\n\n        delete m_updater;\n        m_updater = new qtsparkle::Updater( QUrl( QString( betaUpdates ? UPDATE_URL_WIN_BETA : UPDATE_URL_WIN ) ), m_parentWidget );\n        m_updater->SetNetworkAccessManager( lastfm::nam() );\n        m_updater->SetIcon( QPixmap( \":/scrobbler_64.png\" ) );\n    }\n#endif\n}\n\nvoid\nunicorn::Updater::checkForUpdates()\n{\n#ifdef Q_OS_WIN\n    m_updater->CheckNow();\n#endif\n}\n\nunicorn::Updater::~Updater()\n{\n#ifdef Q_OS_WIN\n    delete m_updater;\n#endif\n}\n\n#endif // Q_OS_MAC\n"
  },
  {
    "path": "lib/unicorn/Updater/Updater.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef UPDATER_H\n#define UPDATER_H\n\n#include <QObject>\n#include <QPointer>\n\n#include \"lib/DllExportMacro.h\"\n\n#ifdef Q_OS_WIN\nnamespace qtsparkle { class Updater; }\n#define UPDATE_URL_WIN \"https://cdn.last.fm/client/updates/updates.win.xml\"\n#define UPDATE_URL_WIN_BETA \"https://cdn.last.fm/client/updates/updates.win.beta.xml\"\n#elif defined( Q_OS_MAC )\n#define UPDATE_URL_MAC @\"https://cdn.last.fm/client/updates/updates.mac.xml\"\n#define UPDATE_URL_MAC_BETA @\"https://cdn.last.fm/client/updates/updates.mac.beta.xml\"\n#endif\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT Updater : public QObject\n{\n    Q_OBJECT\npublic:\n    explicit Updater( QWidget* parent = 0 );\n    ~Updater();\n\n    void setBetaUpdates( bool betaUpdates );\n\npublic slots:\n    void checkForUpdates();\n\nprivate:\n#ifdef Q_OS_WIN\n    QPointer<qtsparkle::Updater> m_updater;\n    QWidget* m_parentWidget;\n    bool m_betaUpdates;\n#endif\n};\n\n}\n\n#endif // UPDATER_H\n"
  },
  {
    "path": "lib/unicorn/Updater/Updater_mac.mm",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringList>\n\n#include <../UnicornApplication.h>\n#include <../UnicornSettings.h>\n\n#include \"Updater.h\"\n\n#include <AppKit/NSNibDeclarations.h>\n#include <Foundation/Foundation.h>\n#include <Foundation/NSURL.h>\n\n#include <Sparkle/Sparkle.h>\n#include <Sparkle/SUUpdater.h>\n\n@interface UpdaterDelegate : NSObject {\n}\n@end\n\n@implementation UpdaterDelegate\n@end\n\nUpdaterDelegate* g_Delegate;\n\nunicorn::Updater::Updater(QWidget *parent) :\n    QObject(parent)\n{\n    SUUpdater* updater = [SUUpdater sharedUpdater];\n    g_Delegate = [UpdaterDelegate alloc];\n    [updater setDelegate:g_Delegate];\n\n    if ( qApp->arguments().contains( \"--update\" ) )\n    {\n        int urlIndex = qApp->arguments().indexOf( \"--update\" ) + 1;\n\n        if ( qApp->arguments().count() > urlIndex && qApp->arguments()[urlIndex].startsWith( \"https://\" ) )\n            [updater setFeedURL:[NSURL URLWithString: [NSString stringWithCharacters:(const unichar *)qApp->arguments()[urlIndex].unicode() length:(NSUInteger)qApp->arguments()[urlIndex].length() ]]];\n        else\n            setBetaUpdates( unicorn::Settings().betaUpdates() );\n    }\n    else\n        setBetaUpdates( unicorn::Settings().betaUpdates() );\n\n}\n\nvoid\nunicorn::Updater::setBetaUpdates( bool betaUpdates )\n{\n    if ( betaUpdates )\n        [[SUUpdater sharedUpdater] setFeedURL:[NSURL URLWithString:UPDATE_URL_MAC_BETA]];\n    else\n        [[SUUpdater sharedUpdater] setFeedURL:[NSURL URLWithString:UPDATE_URL_MAC]];\n\n}\n\nvoid\nunicorn::Updater::checkForUpdates()\n{\n    [[SUUpdater sharedUpdater] checkForUpdates:0];\n}\n\nunicorn::Updater::~Updater()\n{\n    // do nothing - included here for header compatibility with windows version\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/AboutDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"AboutDialog.h\"\n#include <QApplication>\n#include <QIcon>\n#include <QLabel>\n#include <QVBoxLayout>\n\n#include \"ui_AboutDialog.h\"\n\n\nAboutDialog::AboutDialog( QWidget* parent )\n           : QDialog( parent ),\n             ui( new Ui::AboutDialog )\n{\n    Q_ASSERT( qApp->applicationVersion().size() );\n\n    ui->setupUi( this );\n\n    ui->appName->setText( \"<b>\" + qApp->applicationName() );\n    ui->qtVersion->setText(  tr( \"%1 (built on Qt %2)\"  ).arg( qApp->applicationVersion(), qVersion() ) );\n\n    ui->lastfmLink->setText(  \"<a href='http://www.last.fm'>www.last.fm</a>\" );\n    ui->ircLink->setText(  \"<a href='https://getsatisfaction.com/lastfm/categories/lastfm_apps'>Last.fm Client Support</a>\" );\n\n    ui->copyright->setText( QString::fromUtf8(\"™ & © 2005 - 2019 Last.fm Limited\") );\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/AboutDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"lib/DllExportMacro.h\"\n#include <QDialog>\n\nnamespace Ui { class AboutDialog; }\n\nclass UNICORN_DLLEXPORT AboutDialog : public QDialog\n{\npublic:\n    AboutDialog( QWidget* parent );\n\nprivate:\n    Ui::AboutDialog* ui;\n};\n"
  },
  {
    "path": "lib/unicorn/dialogs/AboutDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>AboutDialog</class>\n <widget class=\"QDialog\" name=\"AboutDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>439</width>\n    <height>306</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>About</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"sizeConstraint\">\n    <enum>QLayout::SetFixedSize</enum>\n   </property>\n   <property name=\"margin\">\n    <number>0</number>\n   </property>\n   <item>\n    <widget class=\"QFrame\" name=\"frame\">\n     <property name=\"frameShape\">\n      <enum>QFrame::NoFrame</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_3\">\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n        <property name=\"spacing\">\n         <number>20</number>\n        </property>\n        <item>\n         <widget class=\"QLabel\" name=\"as\">\n          <property name=\"text\">\n           <string notr=\"true\">TextLabel</string>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n          <property name=\"spacing\">\n           <number>6</number>\n          </property>\n          <item>\n           <spacer name=\"verticalSpacer_2\">\n            <property name=\"orientation\">\n             <enum>Qt::Vertical</enum>\n            </property>\n            <property name=\"sizeHint\" stdset=\"0\">\n             <size>\n              <width>20</width>\n              <height>0</height>\n             </size>\n            </property>\n           </spacer>\n          </item>\n          <item>\n           <widget class=\"QLabel\" name=\"appName\">\n            <property name=\"text\">\n             <string notr=\"true\">TextLabel</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <widget class=\"QLabel\" name=\"qtVersion\">\n            <property name=\"text\">\n             <string notr=\"true\">TextLabel</string>\n            </property>\n           </widget>\n          </item>\n          <item>\n           <spacer name=\"verticalSpacer\">\n            <property name=\"orientation\">\n             <enum>Qt::Vertical</enum>\n            </property>\n            <property name=\"sizeHint\" stdset=\"0\">\n             <size>\n              <width>20</width>\n              <height>0</height>\n             </size>\n            </property>\n           </spacer>\n          </item>\n         </layout>\n        </item>\n       </layout>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"lastfmLink\">\n        <property name=\"text\">\n         <string notr=\"true\">TextLabel</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n        <property name=\"openExternalLinks\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"ircLink\">\n        <property name=\"text\">\n         <string notr=\"true\">TextLabel</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n        <property name=\"openExternalLinks\">\n         <bool>true</bool>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"copyright\">\n        <property name=\"text\">\n         <string notr=\"true\">TextLabel</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/CloseAppsDialog.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QTimer>\n#include <QPushButton>\n#include <QDebug>\n\n#ifdef Q_OS_WIN\n#include <windows.h>\n#include <psapi.h>\n#endif\n\n#ifndef Q_OS_MAC\n#include \"../plugins/ITunesPluginInfo.h\"\n#endif\n\n#include \"CloseAppsDialog.h\"\n#include \"ui_CloseAppsDialog.h\"\n\n\nunicorn::CloseAppsDialog::CloseAppsDialog( const QList<IPluginInfo*>& plugins, QWidget *parent )\n    :QDialog( parent ),\n      ui(new Ui::CloseAppsDialog),\n      m_plugins( plugins ),\n      m_ownsPlugins( false )\n{\n    commonSetup();\n}\n\nunicorn::CloseAppsDialog::CloseAppsDialog(QWidget *parent) :\n    QDialog( parent ),\n    ui(new Ui::CloseAppsDialog)\n{\n    commonSetup();\n}\n\nvoid\nunicorn::CloseAppsDialog::setTitle( const QString& title )\n{\n    setWindowTitle( title );\n}\n\nvoid\nunicorn::CloseAppsDialog::setDescription( const QString& description )\n{\n    ui->text->setText( description );\n}\n\nvoid\nunicorn::CloseAppsDialog::showPluginList( bool showPluginList )\n{\n    ui->listWidget->setVisible( showPluginList );\n}\n\nvoid\nunicorn::CloseAppsDialog::commonSetup()\n{\n    ui->setupUi(this);\n\n    ui->text->setText( tr( \"Please close the following apps to continue.\" ) );\n\n    if ( runningApps().count() == 0 )\n        hide();\n\n    checkApps();\n\n    QTimer* timer = new QTimer( this );\n    connect( timer, SIGNAL(timeout()), SLOT(checkApps()) );\n    timer->setInterval( 1000 );\n    timer->start();\n}\n\nvoid\nunicorn::CloseAppsDialog::setOwnsPlugins( bool ownsPlugins )\n{\n    m_ownsPlugins = ownsPlugins;\n}\n\nbool\nunicorn::CloseAppsDialog::isITunesRunning()\n{\n    QStringList apps;\n#ifndef Q_OS_MAC\n    QList<IPluginInfo*> plugins;\n    ITunesPluginInfo* iTunesPluginInfo = new ITunesPluginInfo;\n    plugins << iTunesPluginInfo;\n    apps = runningApps( plugins );\n    delete iTunesPluginInfo;\n#else\n    apps = runningApps();\n#endif\n    return apps.count() == 1;\n}\n\nvoid\nunicorn::CloseAppsDialog::checkApps()\n{\n    QStringList apps = runningApps();\n\n    ui->listWidget->setUpdatesEnabled( false );\n\n    ui->listWidget->clear();\n\n    foreach ( const QString& app, apps )\n        new QListWidgetItem( app, ui->listWidget );\n\n    ui->listWidget->setUpdatesEnabled( true );\n\n    if ( apps.count() == 0 )\n        accept();\n}\n\nvoid\nunicorn::CloseAppsDialog::showEvent( QShowEvent* event )\n{\n    adjustSize();\n}\n\n#ifndef Q_OS_MAC\nQStringList\nunicorn::CloseAppsDialog::runningApps()\n{\n    return runningApps( m_plugins );\n}\n\nQStringList\nunicorn::CloseAppsDialog::runningApps( const QList<IPluginInfo*>& plugins )\n{\n    QStringList apps;\n\n    DWORD aProcesses[1024];\n    DWORD cbNeeded;\n    DWORD cProcesses;\n    unsigned int i;\n\n    if ( EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )\n    {\n        // Calculate how many process identifiers were returned.\n\n        cProcesses = cbNeeded / sizeof(DWORD);\n\n        // Print the name and process identifier for each process.\n\n        for ( i = 0; i < cProcesses; ++i )\n        {\n            if( aProcesses[i] != 0 )\n            {\n                TCHAR szProcessName[MAX_PATH] = TEXT(\"<unknown>\");\n\n                // Get a handle to the process.\n                HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |\n                PROCESS_VM_READ,\n                FALSE, aProcesses[i] );\n\n                if (NULL != hProcess )\n                {\n                    HMODULE hMod;\n                    DWORD cbNeeded;\n\n                    if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )\n                    {\n                        GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );\n\n                        foreach( IPluginInfo* plugin, plugins )\n                            if ( plugin->processName().compare( QString::fromStdWString( szProcessName ), Qt::CaseInsensitive ) == 0 )\n                                apps << plugin->name();\n                    }\n                }\n\n                // Release the handle to the process.\n                CloseHandle( hProcess );\n            }\n        }\n    }\n\n    return apps;\n}\n#endif\n\nunicorn::CloseAppsDialog::~CloseAppsDialog()\n{\n    delete ui;\n#ifdef Q_OS_WIN\n    if ( m_ownsPlugins )\n        foreach ( IPluginInfo* plugin, m_plugins )\n            delete plugin;\n#endif\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/CloseAppsDialog.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef CLOSEAPPSDIALOG_H\n#define CLOSEAPPSDIALOG_H\n\n#include \"lib/DllExportMacro.h\"\n\n#include <QDialog>\n\nnamespace Ui { class CloseAppsDialog; }\n\nnamespace unicorn\n{\nclass IPluginInfo;\n\nclass UNICORN_DLLEXPORT CloseAppsDialog : public QDialog\n{\n    Q_OBJECT\n    \npublic:\n    explicit CloseAppsDialog( const QList<IPluginInfo*>& plugins, QWidget *parent );\n    explicit CloseAppsDialog(QWidget *parent = 0);\n    ~CloseAppsDialog();\n\n    void setTitle( const QString& title );\n    void setDescription( const QString& description );\n\n    void showPluginList( bool showPluginList );\n\n    void setOwnsPlugins( bool ownsPlugins );\n\n    static bool isITunesRunning();\n\nprivate:\n#ifndef Q_OS_MAC\n    static QStringList runningApps( const QList<IPluginInfo*>& plugins );\n#else\n    static // this method is only statis on mac\n#endif\n    QStringList runningApps();\n\n    void showEvent( QShowEvent* event );\n\nprivate slots:\n    void checkApps();\n\nprivate:\n    void commonSetup();\n    \nprivate:\n    Ui::CloseAppsDialog *ui;\n    QList<IPluginInfo*> m_plugins;\n\n    bool m_ownsPlugins;\n};\n\n}\n\n#endif // CLOSEAPPSDIALOG_H\n"
  },
  {
    "path": "lib/unicorn/dialogs/CloseAppsDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>CloseAppsDialog</class>\n <widget class=\"QDialog\" name=\"CloseAppsDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>313</width>\n    <height>341</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Close Apps</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\" stretch=\"1,0\">\n   <item>\n    <widget class=\"unicorn::Label\" name=\"text\">\n     <property name=\"toolTip\">\n      <string notr=\"true\"/>\n     </property>\n     <property name=\"text\">\n      <string notr=\"true\">TextLabel</string>\n     </property>\n     <property name=\"textFormat\">\n      <enum>Qt::RichText</enum>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QListWidget\" name=\"listWidget\">\n     <property name=\"selectionMode\">\n      <enum>QAbstractItemView::NoSelection</enum>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header location=\"global\">lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/CloseAppsDialog_mac.mm",
    "content": "#include \"CloseAppsDialog.h\"\n\nQString qt_mac_NSStringToQString(const NSString *nsstr)\n{\n    NSRange range;\n    range.location = 0;\n    range.length = [nsstr length];\n\n    unichar *chars = new unichar[range.length];\n    [nsstr getCharacters:chars range:range];\n    QString result = QString::fromUtf16(chars, range.length);\n    delete[] chars;\n    return result;\n}\n\nQStringList\nunicorn::CloseAppsDialog::runningApps()\n{\n    // we only ever test for iTunes on Mac\n\n    QStringList apps;\n\n    // make sure iTunes isn't running\n    NSArray* runningApps = [[NSWorkspace sharedWorkspace] runningApplications];\n\n    for ( unsigned int i = 0 ; i < [runningApps count] ; ++i )\n    {\n        if ( [[[runningApps objectAtIndex:i] bundleIdentifier] isEqualToString:@\"com.apple.iTunes\"] )\n        {\n            NSString* appName = [[runningApps objectAtIndex:i] localizedName];\n            apps << qt_mac_NSStringToQString( appName );\n            break;\n        }\n    }\n\n    return apps;\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/LoginContinueDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"LoginContinueDialog.h\"\n\n#include <QtGui>\n#include <QDialogButtonBox>\n\nLoginContinueDialog::LoginContinueDialog( QWidget* parent )\n    : QDialog( parent ), m_subscriber( true )\n{\n    setWindowModality( Qt::ApplicationModal );\n\n    QVBoxLayout* layout = new QVBoxLayout( this );\n\n    layout->addWidget( ui.title = new QLabel( tr(\"Are we done?\") ) );\n    ui.title->setObjectName( \"title\" );\n\n    layout->addWidget( ui.description = new QLabel( tr(\"Click OK once you have approved this app.\") ) );\n    ui.title->setObjectName( \"description\" );\n    ui.title->setWordWrap( true );\n\n    layout->addWidget( ui.buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok ) );\n\n    connect( ui.buttonBox, SIGNAL(accepted()), SLOT(accept()) );\n    connect( ui.buttonBox, SIGNAL(rejected()), SLOT(reject()) );\n}\n\n"
  },
  {
    "path": "lib/unicorn/dialogs/LoginContinueDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef LOGIN_CONTINUE_DIALOG_H\n#define LOGIN_CONTINUE_DIALOG_H\n\n#include \"lib/DllExportMacro.h\"\n#include <QDialog>\n#include <QDialogButtonBox>\n\nclass UNICORN_DLLEXPORT LoginContinueDialog : public QDialog\n{\n    Q_OBJECT\nprivate:\n\n    struct\n    {\n        class QLabel* title;\n        class QLabel* description;\n        class QDialogButtonBox* buttonBox;\n    } ui;\n\npublic:\n    LoginContinueDialog( QWidget* parent = 0 );\n\nprivate:\n    QPushButton* ok() const { return ui.buttonBox->button( QDialogButtonBox::Ok ); }\n\nprivate:\n    bool m_subscriber;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/dialogs/LoginDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"LoginDialog.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include <QtGui>\n\nLoginDialog::LoginDialog( QWidget* parent )\n            :QDialog( parent )\n{\n    setWindowModality( Qt::ApplicationModal );\n\n    QVBoxLayout* layout = new QVBoxLayout( this );\n\n    layout->addWidget( ui.title = new QLabel( tr(\"Last.fm needs your permission first!\") ) );\n    ui.title->setObjectName( \"title\" );\n\n    layout->addWidget( ui.description = new QLabel( tr(\"This application needs your permission to connect to your Last.fm profile.  Click OK to go to the Last.fm website and do this.\") ) );\n    ui.description->setWordWrap( true );\n    ui.title->setObjectName( \"description\" );\n    ui.title->setWordWrap( true );\n\n    layout->addWidget( ui.buttonBox = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ) );\n\n    connect( ui.buttonBox, SIGNAL(accepted()), SLOT(accept()) );\n    connect( ui.buttonBox, SIGNAL(rejected()), SLOT(reject()) );\n}\n\n\n\n"
  },
  {
    "path": "lib/unicorn/dialogs/LoginDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef LOGIN_DIALOG_H\n#define LOGIN_DIALOG_H\n\n#include \"lib/DllExportMacro.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n#include <QDialog>\n#include <QDialogButtonBox>\n\n\nclass UNICORN_DLLEXPORT LoginDialog : public QDialog\n{\n    Q_OBJECT\nprivate:\n\n    struct\n    {\n        class QLabel* title;\n        class QLabel* description;\n        class QDialogButtonBox* buttonBox;\n    } ui;\n\npublic:\n    LoginDialog( QWidget* parent = 0 );\n\nprivate:\n    QPushButton* ok() const { return ui.buttonBox->button( QDialogButtonBox::Ok ); }\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/dialogs/ProxyDialog.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"ProxyDialog.h\"\n#include \"ui_ProxyDialog.h\"\n\nunicorn::ProxyDialog::ProxyDialog(QWidget *parent) :\n    QDialog(parent),\n    ui(new Ui::ProxyDialog)\n{\n    ui->setupUi(this);\n\n    connect( this, SIGNAL(accepted()), SLOT(onAccepted()));\n\n    setFixedSize( width(), height() );\n}\n\nunicorn::ProxyDialog::~ProxyDialog()\n{\n    delete ui;\n}\n\nvoid\nunicorn::ProxyDialog::onAccepted()\n{\n    ui->proxySettings->save();\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/ProxyDialog.h",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PROXYDIALOG_H\n#define PROXYDIALOG_H\n\n#include \"lib/DllExportMacro.h\"\n\n#include <QDialog>\n\nnamespace Ui { class ProxyDialog; }\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT ProxyDialog : public QDialog\n{\n    Q_OBJECT\n    \npublic:\n    explicit ProxyDialog(QWidget *parent = 0);\n    ~ProxyDialog();\n\nprivate slots:\n    void onAccepted();\n    \nprivate:\n    Ui::ProxyDialog *ui;\n};\n\n}\n\n#endif // PROXYDIALOG_H\n"
  },
  {
    "path": "lib/unicorn/dialogs/ProxyDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ProxyDialog</class>\n <widget class=\"QDialog\" name=\"ProxyDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>310</width>\n    <height>200</height>\n   </rect>\n  </property>\n  <property name=\"sizePolicy\">\n   <sizepolicy hsizetype=\"Fixed\" vsizetype=\"Fixed\">\n    <horstretch>0</horstretch>\n    <verstretch>0</verstretch>\n   </sizepolicy>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Proxy Settings</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"unicorn::ProxyWidget\" name=\"proxySettings\" native=\"true\"/>\n   </item>\n   <item>\n    <widget class=\"QDialogButtonBox\" name=\"buttonBox\">\n     <property name=\"orientation\">\n      <enum>Qt::Horizontal</enum>\n     </property>\n     <property name=\"standardButtons\">\n      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::ProxyWidget</class>\n   <extends>QWidget</extends>\n   <header>lib/unicorn/widgets/ProxyWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections>\n  <connection>\n   <sender>buttonBox</sender>\n   <signal>accepted()</signal>\n   <receiver>ProxyDialog</receiver>\n   <slot>accept()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>248</x>\n     <y>254</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>157</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n  <connection>\n   <sender>buttonBox</sender>\n   <signal>rejected()</signal>\n   <receiver>ProxyDialog</receiver>\n   <slot>reject()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>316</x>\n     <y>260</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>286</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n </connections>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/ScrobbleConfirmationDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QCheckBox>\n#include <QDialogButtonBox>\n#include <QHeaderView>\n#include <QLabel>\n#include <QPushButton>\n#include <QSortFilterProxyModel>\n#include <QTableView>\n#include <QVBoxLayout>\n\n#include <lastfm/ScrobbleCache.h>\n\n#include \"../ScrobblesModel.h\"\n\n#include \"ScrobbleConfirmationDialog.h\"\n#include \"ui_ScrobbleConfirmationDialog.h\"\n\nScrobbleConfirmationDialog::ScrobbleConfirmationDialog( const QList<lastfm::Track>& tracks, QWidget* parent )\n    : QDialog( parent ), ui( new Ui::ScrobbleConfirmationDialog )\n{\n    ui->setupUi( this );\n\n    m_toggled = true;\n\n    m_scrobblesModel = new ScrobblesModel( this );\n    QSortFilterProxyModel* proxyModel = new QSortFilterProxyModel( this );\n    proxyModel->setSourceModel( m_scrobblesModel );\n    ui->scrobblesView->setModel( proxyModel );\n\n    ui->scrobblesView->sortByColumn( ScrobblesModel::TimeStamp, Qt::DescendingOrder );\n\n    ui->scrobblesView->hideColumn( ScrobblesModel::Loved );\n    ui->scrobblesView->hideColumn( ScrobblesModel::Album );\n\n    connect( ui->toggleButton, SIGNAL( clicked() ), SLOT( toggleSelection() ) );\n\n    addTracks( tracks );\n\n    ui->invalidScrobbleWarning->setVisible( tracksToScrobble().count() != m_scrobblesModel->tracksToScrobble().count() );\n}\n\nScrobbleConfirmationDialog::~ScrobbleConfirmationDialog()\n{\n    delete ui;\n}\n\nvoid\nScrobbleConfirmationDialog::setReadOnly()\n{\n    int count = 0;\n\n    foreach ( const lastfm::Track& track, m_scrobblesModel->tracksToScrobble() )\n        count += track.extra( \"playCount\" ).toInt();\n\n    ui->infoText->setText( tr( \"%n play(s) ha(s|ve) been scrobbled from a device\", \"\", count ) );\n\n    ui->buttons->removeButton( ui->buttons->button( QDialogButtonBox::No ) );\n    ui->buttons->removeButton( ui->buttons->button( QDialogButtonBox::Yes ) );\n    ui->buttons->addButton( QDialogButtonBox::Ok );\n\n    ui->toggleButton->hide();\n    ui->autoScrobble->hide();\n    ui->invalidScrobbleWarning->hide();\n\n\n    m_scrobblesModel->setReadOnly();\n}\n\nbool\nScrobbleConfirmationDialog::autoScrobble() const\n{\n    return ui->autoScrobble->isChecked();\n}\n\nvoid\nScrobbleConfirmationDialog::addTracks( const QList<lastfm::Track>& tracks )\n{\n    m_scrobblesModel->addTracks( tracks );\n\n    // a hack to get the view to sort for the added tracks\n    ui->scrobblesView->setSortingEnabled( false );\n    ui->scrobblesView->setSortingEnabled( true );\n\n    ui->scrobblesView->horizontalHeader()->setResizeMode( QHeaderView::Interactive );\n\n    ui->scrobblesView->resizeColumnsToContents();\n}\n\nvoid\nScrobbleConfirmationDialog::addFiles( const QStringList& files )\n{\n    m_files << files;\n}\n\nconst QStringList&\nScrobbleConfirmationDialog::files() const\n{\n    return m_files;\n}\n\nQList<lastfm::Track>\nScrobbleConfirmationDialog::tracksToScrobble() const\n{\n    QList<lastfm::Track> validTracks;\n\n    foreach ( lastfm::Track track, m_scrobblesModel->tracksToScrobble() )\n        if ( lastfm::ScrobbleCache::isValid( track ) )\n            validTracks << track;\n\n    return validTracks;\n}\n\nvoid\nScrobbleConfirmationDialog::toggleSelection()\n{\n    m_toggled = !m_toggled;\n\n    for( int i = 0; i < m_scrobblesModel->rowCount(); i++ )\n    {\n        QModelIndex idx = m_scrobblesModel->index( i, ScrobblesModel::Artist, QModelIndex() );\n        m_scrobblesModel->setData( idx, m_toggled, Qt::CheckStateRole );\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/ScrobbleConfirmationDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SCROBBLECONFIRMATIONDIALOG_H\n#define SCROBBLECONFIRMATIONDIALOG_H\n\n#include <QDialog>\n\n#include <lastfm/Track.h>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace Ui { class ScrobbleConfirmationDialog; }\n\nclass ScrobblesModel;\n\nclass UNICORN_DLLEXPORT ScrobbleConfirmationDialog : public QDialog\n{\n    Q_OBJECT\npublic:\n    ScrobbleConfirmationDialog( const QList<lastfm::Track>& tracks, QWidget* parent = 0 );\n    ~ScrobbleConfirmationDialog();\n\n    QList<lastfm::Track> tracksToScrobble() const;\n\n    void addTracks( const QList<lastfm::Track>& tracks );\n\n    const QStringList& files() const;\n    void addFiles( const QStringList& files );\n\n    void setReadOnly();\n\n    bool autoScrobble() const;\n\nprivate slots:\n    void toggleSelection();\n\nprivate:\n    Ui::ScrobbleConfirmationDialog* ui;\n\n    ScrobblesModel* m_scrobblesModel;\n    bool m_toggled;\n    QStringList m_files;\n};\n\n#endif // SCROBBLECONFIRMATIONDIALOG_H\n"
  },
  {
    "path": "lib/unicorn/dialogs/ScrobbleConfirmationDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ScrobbleConfirmationDialog</class>\n <widget class=\"QDialog\" name=\"ScrobbleConfirmationDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>500</width>\n    <height>450</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Device Scrobbles</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n   <item>\n    <widget class=\"QLabel\" name=\"infoText\">\n     <property name=\"text\">\n      <string>It looks like you've played these tracks. Would you like to scrobble them?</string>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"invalidScrobbleWarning\">\n     <property name=\"text\">\n      <string>Tracks appearing in red are invalid and will not be scrobbled. Hover your mouse over each track to find out why.</string>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QTableView\" name=\"scrobblesView\">\n     <property name=\"selectionMode\">\n      <enum>QAbstractItemView::NoSelection</enum>\n     </property>\n     <property name=\"showGrid\">\n      <bool>false</bool>\n     </property>\n     <property name=\"sortingEnabled\">\n      <bool>true</bool>\n     </property>\n     <property name=\"wordWrap\">\n      <bool>false</bool>\n     </property>\n     <property name=\"cornerButtonEnabled\">\n      <bool>false</bool>\n     </property>\n     <attribute name=\"horizontalHeaderCascadingSectionResizes\">\n      <bool>true</bool>\n     </attribute>\n     <attribute name=\"horizontalHeaderStretchLastSection\">\n      <bool>true</bool>\n     </attribute>\n     <attribute name=\"verticalHeaderVisible\">\n      <bool>false</bool>\n     </attribute>\n    </widget>\n   </item>\n   <item>\n    <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\">\n     <item>\n      <spacer name=\"horizontalSpacer\">\n       <property name=\"orientation\">\n        <enum>Qt::Horizontal</enum>\n       </property>\n       <property name=\"sizeHint\" stdset=\"0\">\n        <size>\n         <width>40</width>\n         <height>20</height>\n        </size>\n       </property>\n      </spacer>\n     </item>\n     <item>\n      <widget class=\"QCheckBox\" name=\"autoScrobble\">\n       <property name=\"layoutDirection\">\n        <enum>Qt::LeftToRight</enum>\n       </property>\n       <property name=\"text\">\n        <string>Scrobble devices automatically</string>\n       </property>\n       <property name=\"tristate\">\n        <bool>false</bool>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n   <item>\n    <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n     <item>\n      <widget class=\"QPushButton\" name=\"toggleButton\">\n       <property name=\"text\">\n        <string>Toggle selection</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QDialogButtonBox\" name=\"buttons\">\n       <property name=\"orientation\">\n        <enum>Qt::Horizontal</enum>\n       </property>\n       <property name=\"standardButtons\">\n        <set>QDialogButtonBox::No|QDialogButtonBox::Yes</set>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections>\n  <connection>\n   <sender>buttons</sender>\n   <signal>accepted()</signal>\n   <receiver>ScrobbleConfirmationDialog</receiver>\n   <slot>accept()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>248</x>\n     <y>254</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>157</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n  <connection>\n   <sender>buttons</sender>\n   <signal>rejected()</signal>\n   <receiver>ScrobbleConfirmationDialog</receiver>\n   <slot>reject()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>316</x>\n     <y>260</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>286</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n </connections>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/ShareDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QApplication>\n#include <QPainter>\n#include <QTimer>\n#include <QPushButton>\n#include <QVBoxLayout>\n#include <QLabel>\n#include <QPlainTextEdit>\n#include <QEvent>\n#include <QRadioButton>\n#include <QComboBox>\n#include <QListWidget>\n#include <QDebug>\n#include <QCheckBox>\n#include <QDesktopWidget>\n\n#include <lastfm/User.h>\n#include <lastfm/XmlQuery.h>\n\n#include \"lib/unicorn/widgets/TrackWidget.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n#include \"lib/unicorn/TrackImageFetcher.h\"\n\n#include \"ShareDialog.h\"\n\n#include \"ui_ShareDialog.h\"\n\n#include \"../widgets/ItemSelectorWidget.h\"\n\nconst int kMaxMessage(1000);\n\nShareDialog::ShareDialog( const Track& track, QWidget* parent )\n    : unicorn::Dialog( parent, Qt::Tool ),\n      ui( new Ui::ShareDialog ),\n      m_track( track )\n{\n    ui->setupUi( this );\n\n    ui->recipients->setType( ItemSelectorWidget::User );\n\n    ui->icon->setScaledContents( true );\n    ui->icon->setHref( m_track.www() );\n\n    enableDisableOk();\n\n    connect( ui->message, SIGNAL(textChanged()), SLOT(updateCharacterLimit()));\n    connect( ui->message, SIGNAL(textChanged()), SLOT(enableDisableOk()));\n    connect( ui->recipients, SIGNAL(changed()), SLOT(enableDisableOk()));\n\n    ui->title->setText( unicorn::Label::anchor( m_track.www().toString(), m_track.title() ) );\n\n    if ( m_track.album().isNull() )\n        ui->description->setText( tr( \"A track by %1\" ).arg( unicorn::Label::anchor( m_track.artist().www().toString(), m_track.artist().name() ) ) );\n    else\n        ui->description->setText( tr( \"A track by %1 from the release %2\" ).arg( unicorn::Label::anchor( m_track.artist().www().toString(), m_track.artist().name() ), unicorn::Label::anchor( m_track.album().www().toString(), m_track.album() ) ) );\n\n    m_imageFetcher = new TrackImageFetcher( m_track, Track::MediumImage );\n    connect( m_imageFetcher, SIGNAL(finished(QPixmap)), ui->icon, SLOT(setPixmap(QPixmap)) );\n    m_imageFetcher->startAlbum();\n\n    QPushButton* dummyDefault = ui->buttons->addButton( QDialogButtonBox::Help );\n    dummyDefault->setDefault( true );\n    dummyDefault->setAutoDefault( true );\n    dummyDefault->setVisible( false );\n}\n\nvoid\nShareDialog::enableDisableOk()\n{\n    ui->buttons->button( QDialogButtonBox::Ok )->setEnabled( ui->recipients->items().count() > 0\n                      && ui->message->toPlainText().length() <= kMaxMessage );\n}\n\nvoid\nShareDialog::updateCharacterLimit()\n{\n    ui->characterLimit->setText( QString::number( ui->message->toPlainText().length() ) + \"/\" + QString::number(kMaxMessage) );\n\n    if ( ui->message->toPlainText().length() > kMaxMessage ) {\n        ui->characterLimit->setProperty( \"xerror\", true );\n    }\n    else\n        ui->characterLimit->setProperty( \"xerror\", false );\n\n    style()->polish( ui->characterLimit );\n}\n\nvoid\nShareDialog::onMessageChanged()\n{\n    // update the character message\n    updateCharacterLimit();\n}\n\nvoid\nShareDialog::accept()\n{\n    QStringList recipients( ui->recipients->items() );\n    QString const message = ui->message->toPlainText();\n    bool isPublic = ui->isPublic->isChecked();\n\n    // disable the dialog until we get a response from Last.fm\n    setEnabled( false );\n    connect( m_track.share( recipients, message, isPublic ), SIGNAL(finished()), SLOT(onShared()) );\n}\n\nvoid\nShareDialog::shareTwitter( const Track& track )\n{\n    QUrl twitterShareIntent( \"http://twitter.com/intent/tweet\" );\n    twitterShareIntent.addEncodedQueryItem( \"text\", QUrl::toPercentEncoding( tr(\"Check out %1\").arg( track.toString() ) ) );\n    twitterShareIntent.addEncodedQueryItem( \"url\", QUrl::toPercentEncoding( track.www().toEncoded() ) );\n    twitterShareIntent.addQueryItem( \"via\", \"lastfm\" );\n    twitterShareIntent.addQueryItem( \"related\", \"lastfm,lastfmpresents\" );\n    unicorn::DesktopServices::openUrl( twitterShareIntent );\n\n}\n\nvoid\nShareDialog::shareFacebook( const Track& track )\n{\n    QUrl facebookShareIntent( \"http://www.facebook.com/sharer.php\" );\n    facebookShareIntent.addEncodedQueryItem( \"t\", QUrl::toPercentEncoding( track.toString() ) );\n    facebookShareIntent.addEncodedQueryItem( \"u\", QUrl::toPercentEncoding( track.www().toEncoded() ) );\n    unicorn::DesktopServices::openUrl( facebookShareIntent );\n}\n\nvoid\nShareDialog::onShared()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        if ( lfm.attribute( \"status\" ) == \"ok\" )\n            close();\n        else\n        {\n            // TODO: display some kind of error message\n            setEnabled( true );\n        }\n    }\n    else\n    {\n        // TODO: display some kind of error message\n        setEnabled( true );\n    }\n}\n\n"
  },
  {
    "path": "lib/unicorn/dialogs/ShareDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SHARE_DIALOG_H\n#define SHARE_DIALOG_H\n\n#include <lastfm/Track.h>\n#include <QDialogButtonBox>\n#include \"UnicornDialog.h\"\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace Ui { class ShareDialog; }\n\nclass UNICORN_DLLEXPORT ShareDialog : public unicorn::Dialog\n{\n    Q_OBJECT\npublic:\n    ShareDialog( const Track& track, QWidget* parent = 0 );\n\n    Track track() const { return m_track; }\n\n    static void shareTwitter( const Track& track );\n    static void shareFacebook( const Track& track );\n\nprivate slots:\n    void enableDisableOk();\n    void accept();\n    void onMessageChanged();\n    void onShared();\n    void updateCharacterLimit();\n\nprivate:\n    Ui::ShareDialog* ui;\n    Track m_track;\n    class TrackImageFetcher* m_imageFetcher;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/dialogs/ShareDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ShareDialog</class>\n <widget class=\"QDialog\" name=\"ShareDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>435</width>\n    <height>418</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Share with Friends</string>\n  </property>\n  <property name=\"modal\">\n   <bool>true</bool>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n   <property name=\"spacing\">\n    <number>0</number>\n   </property>\n   <property name=\"margin\">\n    <number>18</number>\n   </property>\n   <item>\n    <widget class=\"QFrame\" name=\"what\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\" stretch=\"0,1\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"HttpImageWidget\" name=\"icon\">\n        <property name=\"text\">\n         <string notr=\"true\">icon</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n        <property name=\"spacing\">\n         <number>0</number>\n        </property>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"title\">\n          <property name=\"text\">\n           <string notr=\"true\">TextLabel</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"description\">\n          <property name=\"text\">\n           <string notr=\"true\">TextLabel</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>0</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n       </layout>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"with\">\n     <property name=\"font\">\n      <font>\n       <weight>75</weight>\n       <bold>true</bold>\n      </font>\n     </property>\n     <property name=\"text\">\n      <string>With:</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"ItemSelectorWidget\" name=\"recipients\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"messageTitle\">\n     <property name=\"font\">\n      <font>\n       <weight>75</weight>\n       <bold>true</bold>\n      </font>\n     </property>\n     <property name=\"text\">\n      <string>Message (optional):</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QTextEdit\" name=\"message\">\n     <property name=\"tabChangesFocus\">\n      <bool>true</bool>\n     </property>\n     <property name=\"acceptRichText\">\n      <bool>true</bool>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <layout class=\"QHBoxLayout\" name=\"horizontalLayout\" stretch=\"1,0\">\n     <property name=\"spacing\">\n      <number>0</number>\n     </property>\n     <item>\n      <widget class=\"QCheckBox\" name=\"isPublic\">\n       <property name=\"text\">\n        <string>include in my recent activity</string>\n       </property>\n       <property name=\"checked\">\n        <bool>true</bool>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QLabel\" name=\"characterLimit\">\n       <property name=\"text\">\n        <string notr=\"true\">0/1000</string>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n   <item>\n    <widget class=\"QDialogButtonBox\" name=\"buttons\">\n     <property name=\"standardButtons\">\n      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>ItemSelectorWidget</class>\n   <extends>QFrame</extends>\n   <header>lib/unicorn/widgets/ItemSelectorWidget.h</header>\n   <container>1</container>\n  </customwidget>\n  <customwidget>\n   <class>HttpImageWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/HttpImageWidget.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections>\n  <connection>\n   <sender>buttons</sender>\n   <signal>accepted()</signal>\n   <receiver>ShareDialog</receiver>\n   <slot>accept()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>81</x>\n     <y>280</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>4</x>\n     <y>234</y>\n    </hint>\n   </hints>\n  </connection>\n  <connection>\n   <sender>buttons</sender>\n   <signal>rejected()</signal>\n   <receiver>ShareDialog</receiver>\n   <slot>reject()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>113</x>\n     <y>272</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>-7</x>\n     <y>271</y>\n    </hint>\n   </hints>\n  </connection>\n </connections>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/TagDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QtCore>\n#include <QtGui>\n#include <QPushButton>\n\n#include <lastfm/XmlQuery.h>\n#include <lastfm/User.h>\n\n#include \"../widgets/SpinnerLabel.h\"\n#include \"../widgets/TrackWidget.h\"\n#include \"../widgets/UnicornTabWidget.h\"\n#include \"../widgets/ItemSelectorWidget.h\"\n#include \"../widgets/DataListWidget.h\"\n#include \"../widgets/TagListWidget.h\"\n#include \"../TrackImageFetcher.h\"\n\n#include \"ui_TagDialog.h\"\n#include \"TagDialog.h\"\n\nTagDialog::TagDialog( const Track& track, QWidget *parent )\n        : unicorn::Dialog( parent, Qt::Tool ),\n          ui( new Ui::TagDialog )\n{\n    ui->setupUi( this );\n\n    m_track = track;\n\n    ui->icon->setScaledContents( true );\n    ui->icon->setHref( m_track.www() );\n\n    ui->tags->setType( ItemSelectorWidget::Tag );\n\n    layout()->setSizeConstraint( QLayout::SetFixedSize );\n    setSizeGripEnabled( false );\n\n    ui->title->setText( unicorn::Label::anchor( m_track.www().toString(), m_track.title() ) );\n\n    if ( m_track.album().isNull() )\n    {\n        ui->description->setText( tr( \"A track by %1\" ).arg( unicorn::Label::anchor( m_track.artist().www().toString(), m_track.artist().name() ) ) );\n        ui->album->setEnabled( false );\n    }\n    else\n        ui->description->setText( tr( \"A track by %1 from the release %2\" ).arg( unicorn::Label::anchor( m_track.artist().www().toString(), m_track.artist().name() ), unicorn::Label::anchor( m_track.album().www().toString(), m_track.album() ) ) );\n\n    m_imageFetcher = new TrackImageFetcher( m_track, Track::MediumImage );\n    connect( m_imageFetcher, SIGNAL(finished(QPixmap)), ui->icon, SLOT(setPixmap(QPixmap)) );\n    m_imageFetcher->startAlbum();\n\t\n    ui->buttonBox->button( QDialogButtonBox::Ok )->setText( tr(\"Tag\") );\n\n    connect( ui->buttonBox, SIGNAL(accepted()), SLOT(onAccepted()) );\n    connect( ui->buttonBox, SIGNAL(rejected()), SLOT(reject()) );\n\n    connect( ui->tags, SIGNAL(changed()), SLOT(enableDisableOk()));\n    enableDisableOk();\n\n    QPushButton* dummyDefault = ui->buttonBox->addButton( QDialogButtonBox::Help );\n    dummyDefault->setDefault( true );\n    dummyDefault->setAutoDefault( true );\n    dummyDefault->setVisible( false );\n\n    ui->track->click();\n}\n\nvoid\nTagDialog::enableDisableOk()\n{\n    ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( ui->tags->items().count() > 0 );\n}\n\nvoid\nTagDialog::onAccepted()\n{\n    // call the ws for tagging\n    QNetworkReply* reply;\n\n    if ( ui->track->isChecked() )\n        reply = m_track.addTags( ui->tags->items() );\n    else if ( ui->album->isChecked() )\n        reply = m_track.album().addTags( ui->tags->items() );\n    else\n        reply = m_track.artist().addTags( ui->tags->items() );\n\n    connect( reply, SIGNAL(finished()), SLOT(onAddTagFinished()));\n\n    setEnabled( false );\n}\n\nvoid\nTagDialog::onAddTagFinished()\n{\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n        if ( lfm.attribute( \"status\" ) == \"ok\" )\n            close();\n        else\n        {\n            // TODO: display some kind of error message\n            setEnabled( true );\n        }\n    }\n    else\n    {\n        // TODO: display some kind of error message\n        setEnabled( true );\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/TagDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TAG_DIALOG_H\n#define TAG_DIALOG_H\n\n#include <lastfm/Track.h>\n#include <QModelIndex>\n#include \"UnicornDialog.h\"\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace Ui { class TagDialog; }\n\nclass UNICORN_DLLEXPORT TagDialog : public unicorn::Dialog\n{\n    Q_OBJECT\n\npublic:\n    TagDialog( const Track&, QWidget* parent );\n\n\tTrack track() const { return m_track; }\n\nprivate slots:\n    void onAddTagFinished();\n\n    void onAccepted();\n\n    void enableDisableOk();\n\nprivate:\n    Ui::TagDialog* ui;\n    Track m_track;\n    class TrackImageFetcher* m_imageFetcher;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/dialogs/TagDialog.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>TagDialog</class>\n <widget class=\"QDialog\" name=\"TagDialog\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>403</width>\n    <height>300</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Tag</string>\n  </property>\n  <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\">\n   <item>\n    <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n     <item>\n      <widget class=\"QLabel\" name=\"choose\">\n       <property name=\"text\">\n        <string>Choose something to tag:</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QRadioButton\" name=\"track\">\n       <property name=\"text\">\n        <string>Track</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QRadioButton\" name=\"artist\">\n       <property name=\"text\">\n        <string>Artist</string>\n       </property>\n      </widget>\n     </item>\n     <item>\n      <widget class=\"QRadioButton\" name=\"album\">\n       <property name=\"text\">\n        <string>Album</string>\n       </property>\n      </widget>\n     </item>\n    </layout>\n   </item>\n   <item>\n    <widget class=\"QFrame\" name=\"what\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\" stretch=\"0,1\">\n      <property name=\"spacing\">\n       <number>0</number>\n      </property>\n      <property name=\"margin\">\n       <number>0</number>\n      </property>\n      <item>\n       <widget class=\"HttpImageWidget\" name=\"icon\">\n        <property name=\"text\">\n         <string>icon</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n        <property name=\"spacing\">\n         <number>0</number>\n        </property>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"title\">\n          <property name=\"text\">\n           <string notr=\"true\">TextLabel</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <widget class=\"unicorn::Label\" name=\"description\">\n          <property name=\"text\">\n           <string notr=\"true\">TextLabel</string>\n          </property>\n          <property name=\"textFormat\">\n           <enum>Qt::RichText</enum>\n          </property>\n          <property name=\"wordWrap\">\n           <bool>true</bool>\n          </property>\n         </widget>\n        </item>\n        <item>\n         <spacer name=\"verticalSpacer\">\n          <property name=\"orientation\">\n           <enum>Qt::Vertical</enum>\n          </property>\n          <property name=\"sizeHint\" stdset=\"0\">\n           <size>\n            <width>20</width>\n            <height>0</height>\n           </size>\n          </property>\n         </spacer>\n        </item>\n       </layout>\n      </item>\n     </layout>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QLabel\" name=\"addTags\">\n     <property name=\"text\">\n      <string>Add tags:</string>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"ItemSelectorWidget\" name=\"tags\">\n     <property name=\"frameShape\">\n      <enum>QFrame::StyledPanel</enum>\n     </property>\n     <property name=\"frameShadow\">\n      <enum>QFrame::Raised</enum>\n     </property>\n    </widget>\n   </item>\n   <item>\n    <widget class=\"QDialogButtonBox\" name=\"buttonBox\">\n     <property name=\"orientation\">\n      <enum>Qt::Horizontal</enum>\n     </property>\n     <property name=\"standardButtons\">\n      <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>\n     </property>\n    </widget>\n   </item>\n  </layout>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>HttpImageWidget</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/HttpImageWidget.h</header>\n  </customwidget>\n  <customwidget>\n   <class>unicorn::Label</class>\n   <extends>QLabel</extends>\n   <header>lib/unicorn/widgets/Label.h</header>\n  </customwidget>\n  <customwidget>\n   <class>ItemSelectorWidget</class>\n   <extends>QFrame</extends>\n   <header>lib/unicorn/widgets/ItemSelectorWidget.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections>\n  <connection>\n   <sender>buttonBox</sender>\n   <signal>accepted()</signal>\n   <receiver>TagDialog</receiver>\n   <slot>accept()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>248</x>\n     <y>254</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>157</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n  <connection>\n   <sender>buttonBox</sender>\n   <signal>rejected()</signal>\n   <receiver>TagDialog</receiver>\n   <slot>reject()</slot>\n   <hints>\n    <hint type=\"sourcelabel\">\n     <x>316</x>\n     <y>260</y>\n    </hint>\n    <hint type=\"destinationlabel\">\n     <x>286</x>\n     <y>274</y>\n    </hint>\n   </hints>\n  </connection>\n </connections>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/dialogs/UnicornDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef UNICORN_DIALOG_H_\n#define UNICORN_DIALOG_H_\n\n#include <QDialog>\n#include <QApplication>\n#include <QDesktopWidget>\n#include \"../UnicornMainWindow.h\"\n#include \"../UnicornSettings.h\"\n#include <math.h>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn {\nclass UNICORN_DLLEXPORT Dialog : public QDialog\n{\nQ_OBJECT\npublic:\n    Dialog( QWidget* parent = 0, Qt::WindowFlags f = 0 )\n    :QDialog( parent, f ), m_firstShow( true )\n    {\n        connect( qApp->desktop(), SIGNAL( resized(int)), SLOT( cleverlyPosition()));\n    }\n\n    virtual void setVisible( bool visible )\n    {\n        if( !visible || !m_firstShow ) return QDialog::setVisible( visible );\n        m_firstShow = false;\n\n        cleverlyPosition();\n        return QDialog::setVisible( visible );\n    }\n\nprotected:\n    void saveState( const QObject* object, const QString& key, const QVariant& value ) const\n    {\n        AppSettings s;\n        s.beginGroup( QString( metaObject()->className()));\n        s.beginGroup( QString( object->metaObject()->className()));\n        s.setValue( key, value );\n    }\n\n    QVariant restoreState( const QObject* object, const QString& key, const QVariant& defaultValue = QVariant() ) const\n    {\n        AppSettings s;\n        s.beginGroup( QString( metaObject()->className()));\n        s.beginGroup( QString( object->metaObject()->className()));\n        return s.value( key, defaultValue );\n    }\n\n    virtual void moveEvent( QMoveEvent* event )\n    {\n        using unicorn::MainWindow;\n        QWidget* mw = findMainWindow();\n        if( !mw ) return QDialog::moveEvent( event );\n\n        AppSettings s;\n        s.beginGroup( QString( metaObject()->className() ));\n            s.setValue( \"position\", (pos() - mw->pos()));\n        return QDialog::moveEvent( event );\n    }\n\nprivate slots:\n    void cleverlyPosition() \n    {\n        //Clever positioning\n        QWidget* mw = findMainWindow();\n\n        if( !mw ) return;\n\n        resize( sizeHint() );\n\n        AppSettings s;\n\n        s.beginGroup( QString( metaObject()->className() ));\n        QPoint offset = s.value( \"position\", QPoint( 40, 40 )).toPoint();\n        s.endGroup();\n\n        move( mw->pos() + offset);\n\n        int screenNum = qApp->desktop()->screenNumber( mw );\n        QRect screenRect = qApp->desktop()->availableGeometry( screenNum );\n        if( !screenRect.contains( frameGeometry(), true)) {\n            QRect diff;\n\n            diff = screenRect.intersected( frameGeometry() );\n\n            if (diff.left() == screenRect.left() )\n                move( diff.left(), pos().y());\n            if( diff.right() == screenRect.right())\n                move( diff.right() - width(), pos().y());\n            if( diff.top() == screenRect.top())\n                move( pos().x(), diff.top());\n            if( diff.bottom() == screenRect.bottom())\n                move( pos().x(), diff.bottom() - height());\n        }\n    }\n\nprivate:\n    bool m_firstShow;\n    QWidget* findMainWindow() const\n    {\n        unicorn::MainWindow* mw = 0;\n        foreach( QWidget* w, qApp->topLevelWidgets() ) {\n            mw = qobject_cast<unicorn::MainWindow*>( w );\n            if( mw ) break;\n        }\n        return mw;\n    };\n};\n\n} //unicorn\n\n#endif //UNICORN_DIALOG_H_\n"
  },
  {
    "path": "lib/unicorn/dialogs/UserManagerDialog.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UserManagerDialog.h\"\n\n#include <lastfm/User.h>\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/widgets/UserManagerWidget.h\"\n\n#include <QApplication>\n#include <QDebug>\n#include <QDialogButtonBox>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QMouseEvent>\n#include <QPushButton>\n#include <QTimer>\n#include <QVBoxLayout>\n\n\nUserManagerDialog::UserManagerDialog( QWidget* parent )\n            :QDialog( parent )\n{\n    m_users = new UserManagerWidget( this );\n    QVBoxLayout* layout = new QVBoxLayout();\n    QHBoxLayout* actionButtons = new QHBoxLayout();\n    QDialogButtonBox* bb;\n    actionButtons->addWidget( bb = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ));\n\n    layout->addWidget( m_users );\n    layout->addLayout( actionButtons );\n    setLayout( layout );\n\n    connect( m_users, SIGNAL( rosterUpdated() ), this, SIGNAL( rosterUpdated() ) );\n    connect( bb, SIGNAL( accepted()), SLOT( onAccept()));\n    connect( bb, SIGNAL( rejected()), SLOT( reject()));\n}\n\n\nUserManagerDialog::~UserManagerDialog()\n{\n}\n\nvoid \nUserManagerDialog::onAccept()\n{\n    unicorn::Settings s;\n    UserRadioButton* urb = m_users->checkedButton();\n\n    if( !urb || urb->user() == User().name())\n        return QDialog::reject();\n\n    s.setValue( \"Username\", urb->user());\n    QDialog::accept();\n}\n"
  },
  {
    "path": "lib/unicorn/dialogs/UserManagerDialog.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef USER_MANAGER_DIALOG_H_\n#define USER_MANAGER_DIALOG_H_\n\n\n\n#include <QDialog>\n#include <QRadioButton>\n#include \"lib/DllExportMacro.h\"\n\nnamespace lastfm{ class User; }\n\nclass UserManagerWidget;\n\nclass QLabel;\nclass QFrame;\nclass QPushButton;\n\nclass UNICORN_DLLEXPORT UserManagerDialog : public QDialog\n{\nQ_OBJECT\npublic:\n    UserManagerDialog( QWidget* parent = 0 );\n    ~UserManagerDialog();\n\nsignals:\n    void rosterUpdated();\n\nprotected slots:\n    void onAccept();\n\nprivate:\n    UserManagerWidget* m_users;\n};\n\n#endif //USER_MANAGER_DIALOG_H_\n"
  },
  {
    "path": "lib/unicorn/layouts/FlowLayout.cpp",
    "content": "/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial Usage\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http://www.gnu.org/copyleft/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http://www.qtsoftware.com/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************/\n\n#include <QtGui>\n\n#include \"FlowLayout.h\"\n//! [1]\nFlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing)\n    : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing), m_oneLine( false )\n{\n    setContentsMargins(margin, margin, margin, margin);\n}\n\nFlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing)\n    : m_hSpace(hSpacing), m_vSpace(vSpacing), m_oneLine( false )\n{\n    setContentsMargins(margin, margin, margin, margin);\n}\n//! [1]\n\n//! [2]\nFlowLayout::~FlowLayout()\n{\n    QLayoutItem *item;\n    while ((item = takeAt(0)))\n        delete item;\n}\n//! [2]\n\n//! [3]\nvoid FlowLayout::addItem(QLayoutItem *item)\n{\n    itemList.append(item);\n}\n//! [3]\n\nvoid FlowLayout::removeItem(QLayoutItem *item)\n{\n    itemList.removeAt(itemList.indexOf(item));\n    invalidate();\n}\n\nvoid FlowLayout::insertWidget(int index, QWidget* widget)\n{\n    // don't allow duplicates!\n    addChildWidget(widget);\n\n    QWidgetItem* item = new QWidgetItem(widget);\n    itemList.insert(index, item);\n    invalidate();\n}\n\n//! [4]\nint FlowLayout::horizontalSpacing() const\n{\n    if (m_hSpace >= 0) {\n        return m_hSpace;\n    } else {\n        return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);\n    }\n}\n\nint FlowLayout::verticalSpacing() const\n{\n    if (m_vSpace >= 0) {\n        return m_vSpace;\n    } else {\n        return smartSpacing(QStyle::PM_LayoutVerticalSpacing);\n    }\n}\n//! [4]\n\n//! [5]\nint FlowLayout::count() const\n{\n    return itemList.count();\n}\n\nQLayoutItem *FlowLayout::itemAt(int index) const\n{\n    return itemList.value(index);\n}\n\nQLayoutItem *FlowLayout::takeAt(int index)\n{\n    if (index >= 0 && index < itemList.size())\n        return itemList.takeAt(index);\n    else\n        return 0;\n}\n//! [5]\n\n//! [6]\nQt::Orientations FlowLayout::expandingDirections() const\n{\n    return 0;\n}\n//! [6]\n\n//! [7]\nbool FlowLayout::hasHeightForWidth() const\n{\n    return true;\n}\n\nint FlowLayout::heightForWidth(int width) const\n{\n    int height = doLayout(QRect(0, 0, width, 0), true);\n    return height;\n}\n//! [7]\n\n//! [8]\nvoid FlowLayout::setGeometry(const QRect &rect)\n{\n    QLayout::setGeometry(rect);\n    doLayout(rect, false);\n}\n\nQSize FlowLayout::sizeHint() const\n{\n    return minimumSize();\n}\n\nQSize FlowLayout::minimumSize() const\n{\n    QSize size;\n    QLayoutItem *item;\n    foreach (item, itemList)\n        size = size.expandedTo(item->minimumSize());\n\n    size += QSize(2*margin(), 2*margin());\n    return size;\n}\n//! [8]\n\n//! [9]\nint FlowLayout::doLayout(const QRect &rect, bool testOnly) const\n{\n    int left, top, right, bottom;\n    getContentsMargins(&left, &top, &right, &bottom);\n    QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);\n    int x = effectiveRect.x();\n    int y = effectiveRect.y();\n    int lineHeight = 0;\n//! [9]\n\n//! [10]\n    QLayoutItem *item;\n    foreach (item, itemList) {\n        QWidget *wid = item->widget();\n        int spaceX = horizontalSpacing();\n        if (spaceX == -1)\n            spaceX = wid->style()->layoutSpacing(\n                QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);\n        int spaceY = verticalSpacing();\n        if (spaceY == -1)\n            spaceY = wid->style()->layoutSpacing(\n                QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);\n//! [10]\n//! [11]\n        int nextX = x + item->sizeHint().width() + spaceX;\n        if (nextX - spaceX > effectiveRect.right() && lineHeight > 0)\n        {\n            if ( m_oneLine )\n            {\n                item->setGeometry( QRect( 0, 0, 0, 0 ) );\n                continue;\n            }\n            x = effectiveRect.x();\n            y = y + lineHeight + spaceY;\n            nextX = x + item->sizeHint().width() + spaceX;\n            lineHeight = 0;\n        }\n\n        if (!testOnly)\n            item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));\n\n        x = nextX;\n        lineHeight = qMax(lineHeight, item->sizeHint().height());\n    }\n    return y + lineHeight - rect.y() + bottom;\n}\n//! [11]\n//! [12]\nint FlowLayout::smartSpacing(QStyle::PixelMetric pm) const\n{\n    QObject *parent = this->parent();\n    if (!parent) {\n        return -1;\n    } else if (parent->isWidgetType()) {\n        QWidget *pw = static_cast<QWidget *>(parent);\n        return pw->style()->pixelMetric(pm, 0, pw);\n    } else {\n        return static_cast<QLayout *>(parent)->spacing();\n    }\n}\n//! [12]\n"
  },
  {
    "path": "lib/unicorn/layouts/FlowLayout.h",
    "content": "/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** Commercial Usage\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file.  Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http://www.gnu.org/copyleft/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http://www.qtsoftware.com/contact.\n** $QT_END_LICENSE$\n**\n****************************************************************************/\n\n#ifndef FLOWLAYOUT_H\n#define FLOWLAYOUT_H\n\n#include <QLayout>\n#include <QRect>\n#include <QWidgetItem>\n#include <QStyle>\n\n#include <lib/DllExportMacro.h>\n\n//! [0]\nclass UNICORN_DLLEXPORT FlowLayout : public QLayout\n{\npublic:\n    FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1);\n    FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1);\n    ~FlowLayout();\n\n    void setOneLine( bool oneLine ) { m_oneLine = oneLine; }\n\n    void addItem(QLayoutItem *item);\n    void removeItem(QLayoutItem *item);\n\n    void insertWidget(int index, QWidget* widget);\n\n    int horizontalSpacing() const;\n    int verticalSpacing() const;\n    Qt::Orientations expandingDirections() const;\n    bool hasHeightForWidth() const;\n    int heightForWidth(int) const;\n    int count() const;\n    QLayoutItem *itemAt(int index) const;\n    QSize minimumSize() const;\n    void setGeometry(const QRect &rect);\n    QSize sizeHint() const;\n    QLayoutItem *takeAt(int index);\n\nprivate:\n    int doLayout(const QRect &rect, bool testOnly) const;\n    int smartSpacing(QStyle::PixelMetric pm) const;\n\nprivate:\n    QList<QLayoutItem *> itemList;\n\n    int m_hSpace;\n    int m_vSpace;\n    bool m_oneLine;\n};\n//! [0]\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/mac/AppleScript.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"AppleScript.h\"\n#include <QDebug>\n\nComponentInstance AppleScript::s_component = NULL;\n\n\nAppleScript::AppleScript( const QString& code )\n           : m_compiled_script( kOSANullScript ),\n             m_code( code )\n{\n    if (!s_component)\n        s_component = OpenDefaultComponent( kOSAComponentType, typeAppleScript );\n}\n\n\nAppleScript::~AppleScript()\n{\n    OSADispose( s_component, m_compiled_script );\n}\n\n\nbool //static\nAppleScript::isAppleScriptAvailable()\n{\n#ifdef Q_OS_MAC64\n    SInt32 r;\n#else\n    long r;\n#endif\n    if (Gestalt( gestaltAppleScriptAttr, &r ) != noErr)\n        r = 0;\n    return (r & (1 << gestaltAppleScriptPresent)) != 0;\n}\n\n\nstatic inline QString\nqStringFromAEDesc( AEDesc d )\n{\n    const int N = AEGetDescDataSize( &d ) + 1;\n    QByteArray r( N, '\\0' );\n    AEGetDescData( &d, r.data(), r.size() );\n    // sometimes iTunes gives us \"bonus\" nulls for each returned applescript\n    // string component\n    return QString::fromUtf8( r.data(), r.size() ).remove( QChar::Null );\n}\n\n\nvoid\nAppleScript::logError()\n{\n    AEDesc d;\n    OSAScriptError( s_component, kOSAErrorMessage, typeUTF8Text, &d );\n    qWarning() << \"ERROR: AppleScript:\"\n               << m_compiled_script << '-'\n               << qStringFromAEDesc( d );\n}\n\n\nbool\nAppleScript::compile()\n{\n    QByteArray const utf8 = m_code.toUtf8();\n    void const* text = utf8.data();\n    long const textLength = utf8.length();\n   \n    OSStatus err;\n    AEDesc d;\n    err = AECreateDesc( typeUTF8Text, text, textLength, &d );\n    \n    if( err != noErr ) {\n        logError();\n        return false;\n    }\n\n    err = OSACompile( s_component, &d, kOSAModeNull, &m_compiled_script );\n\n    //qDebug() << \"Compiled:\" << m_compiled_script << '\\n' << m_code.trimmed();\n    \n    if (err != noErr) {\n        logError();\n        return false;\n    }\n    return true;\n}\n\n\n/** NOTE old, unedited text may not all apply:-\n  *\n  * LowRunAppleScript compiles and runs an AppleScript\n  * provided as text in the buffer pointed to by text.  textLength\n  * bytes will be compiled from this buffer and run as an AppleScript\n  * using all of the default environment and execution settings.  If\n  * resultData is not NULL, then the result returned by the execution\n  * command will be returned as typeChar in this descriptor record\n  * (or typeNull if there is no result information).  If the function\n  * returns errOSAScriptError, then resultData will be set to a\n  * descriptive error message describing the error (if one is\n  * available). */\nQString\nAppleScript::exec()\n{\n    if (m_compiled_script == kOSANullScript) {\n        if( !compile() ) return \"\";\n    }\n\n    OSAID id = kOSANullScript;\n    OSStatus err = OSAExecute( s_component,\n                               m_compiled_script,\n                               kOSANullScript,\n                               kOSAModeAlwaysInteract,\n                               &id );\n\n    if (err != noErr)\n    {\n        logError();\n        return \"\";\n    }\n\n    if (id == kOSANullScript) // means script succeeded with no output\n        return \"\";\n\n    AEDesc r;\n    OSADisplay( s_component, id, typeUTF8Text, kOSAModeNull, &r );\n    QString s = qStringFromAEDesc( r );\n    OSADispose( s_component, id );\n\n    // strip surrounding quotes if any\n    if (s.startsWith( '\"' ) && s.endsWith( '\"' ))\n    {\n        s = s.mid( 1, s.length() - 2 );\n    }\n\n    // iTunes also likes to escape quotes\n    s.replace( \"\\\\\\\"\", \"\\\"\" );\n\n    //qDebug() << \"Output from script:\" << m_compiled_script << s;\n\n    return s;\n}\n\n\n/** Due to the fact Apple Script can't work with Unicode characters directly \n  * written by Qt into the script, we convert the Unicode data from a QString \n  * into an AppleScript function + the hex values of the QString data (for \n  * example: \"<<data utxt00AB00BB>> as unicode text\") \n  * NOTE AppleScript 2 supports full unicode without this crap, but this works\n  * with all versions\n  */\nQString //static\nAppleScript::asUnicodeText( const QString& string )\n{\t\n    if (string.isEmpty())\n        return string;\n\n    QString const OPEN = QChar(0x00AB) + QString(\"data utxt\");\n    QString const CLOSE = QChar(0x00BB) + QString(\" as unicode text\");\n    QString r;\n\n    for (int i = 0, j = 0; i < string.length(); i++)\n    {\n        QString hexadecimal = QString::number( string[i].unicode(), 16 );\n        r += hexadecimal.rightJustified( 4, '0' );\n\n        // AppleScript is only able to work with 252 / 4 unicode chars at once\n        // (haha, yeah not 64 - the \"utxt\" prefix counts also and is 4 chars\n        // long, so 64 - 1 = 63), everything else would cause a compilation\n        // error. Therefore we split the string every 63 bytes and begin a new\n        // \"<<data utxt...\" function.\n        if (!(++j &= 63))\n        {\n            r += OPEN + \" & \" + CLOSE;\n        }\n    }\n\n    return OPEN + r + CLOSE;\n}\n"
  },
  {
    "path": "lib/unicorn/mac/AppleScript.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef CORE_APPLE_SCRIPT_H\n#define CORE_APPLE_SCRIPT_H\n#ifdef __APPLE__\n\n#include <QString>\n#include <Carbon/Carbon.h> // is there a less huge header option?\n\n\n/** @author Max Howell <max@last.fm> \n  */\nclass AppleScript\n{\npublic:\n    AppleScript( const QString& code = \"\" );\n    ~AppleScript();\n\n    /** add a whole line, newlines are added after every call to this function!\n      * escapes ' to \\\" for convenience \n      * NOTE calling exec() and then using this function is unsupported \n      */\n    AppleScript&\n    operator<<( QString line )\n    {\n        m_code += line.replace( '\\'', '\"' );\n        m_code += '\\n';\n        return *this;\n    }\n        \n    /** execs script set with setScript() \n      * @returns script output */\n    QString exec();\n    \n    /** AppleScript hates unicode, encode unicode strings with this */\n    static QString asUnicodeText( const QString& );\n    \n    /** if false, you're screwed, we've never yet seen that though */\n    static bool isAppleScriptAvailable();\n    \n    bool isEmpty() const { return m_code.isEmpty(); }\n    QString code() const { return m_code; }\n\t\nprivate:    \n    bool compile();\n    void logError();\n\nprivate:\n    OSAID m_compiled_script;\n    QString m_code;\n\n    static ComponentInstance s_component;\n};\n\n#endif\n#endif\n"
  },
  {
    "path": "lib/unicorn/notify/Notify.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef NOTIFY_H\n#define NOTIFY_H\n\n#include <QObject>\n#include <QPointer>\n\n#include \"lib/unicorn/TrackImageFetcher.h\"\n\nnamespace lastfm { class Track; }\n\nnamespace unicorn\n{\n\nclass Notify : public QObject\n{\n    Q_OBJECT\npublic:\n    explicit Notify(QObject *parent = 0);\n    ~Notify();\n\nsignals:\n    void clicked();\n\npublic slots:\n    void newTrack( const lastfm::Track& track );\n    void paused();\n    void resumed();\n    void stopped();\n\nprivate slots:\n    void onFinished( const QPixmap& pixmap );\n\npublic:\n    void growlNotificationWasClicked();\n\nprivate:\n    QPointer<TrackImageFetcher> m_trackImageFetcher;\n};\n\n}\n\n#endif // NOTIFY_H\n"
  },
  {
    "path": "lib/unicorn/notify/Notify.mm",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifdef LASTFM_USER_NOTIFICATIONS\n#include <Foundation/NSUserNotification.h>\n#endif\n\n#include <QPixmap>\n\n#include <Growl/Growl.h>\n\n#include <lastfm/Track.h>\n\n#include \"Notify.h\"\n\n\n#ifdef LASTFM_USER_NOTIFICATIONS\n@interface MacClickDelegate : NSObject <NSUserNotificationCenterDelegate> {\n    unicorn::Notify* m_observer;\n}\n    - (MacClickDelegate*) initialise:(unicorn::Notify*)observer;\n    - (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification;\n@end\n\n@implementation MacClickDelegate\n- (MacClickDelegate*) initialise:(unicorn::Notify*)observer\n{\n    if ( (self = [super init]) )\n    {\n        self->m_observer = observer;\n    }\n\n    return self;\n}\n\n- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification\n{\n    Q_UNUSED(center)\n    Q_UNUSED(notification)\n    self->m_observer->growlNotificationWasClicked();\n}\n@end\n#endif\n\n@interface GrowlClickDelegate : NSObject <GrowlApplicationBridgeDelegate> {\n    unicorn::Notify* m_observer;\n}\n    - (GrowlClickDelegate*) init:(unicorn::Notify*)observer;\n    - (void) growlNotificationWasClicked:(id)clickContext;\n@end\n\n@implementation GrowlClickDelegate\n- (GrowlClickDelegate*) init:(unicorn::Notify*)observer\n{\n    if ( (self = [super init]) )\n    {\n        self->m_observer = observer;\n    }\n\n    return self;\n}\n\n- (void) growlNotificationWasClicked:(id)clickContext\n{\n    Q_UNUSED(clickContext)\n    self->m_observer->growlNotificationWasClicked();\n}\n@end\n\nunicorn::Notify::Notify(QObject *parent) :\n    QObject(parent)\n{\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        MacClickDelegate* macDelegate = [[MacClickDelegate alloc] initialise: this];\n        [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:macDelegate];\n        [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n    }\n    else\n#endif\n    {\n        GrowlClickDelegate* growlDelegate = [[GrowlClickDelegate alloc] init: this];\n        [GrowlApplicationBridge setGrowlDelegate:growlDelegate];\n    }\n}\n\nunicorn::Notify::~Notify()\n{\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n    }\n#endif\n}\n\nvoid\nunicorn::Notify::newTrack( const lastfm::Track& track )\n{\n    delete m_trackImageFetcher;\n    m_trackImageFetcher = new TrackImageFetcher( track, Track::LargeImage );\n    connect( m_trackImageFetcher, SIGNAL(finished(QPixmap)), SLOT(onFinished(QPixmap)) );\n\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n        onFinished( QPixmap() );\n    }\n    else\n#endif\n    {\n        m_trackImageFetcher->startAlbum();\n    }\n}\n\nvoid\nunicorn::Notify::paused()\n{\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n        [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n#endif\n}\n\nvoid\nunicorn::Notify::resumed()\n{\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        if ( m_trackImageFetcher )\n        {\n            [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n            onFinished( QPixmap() );\n        }\n    }\n#endif\n}\n\nvoid\nunicorn::Notify::stopped()\n{\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        [[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];\n        delete m_trackImageFetcher;\n    }\n#endif\n}\n\nvoid\nunicorn::Notify::onFinished( const QPixmap& pixmap )\n{\n    Track track = m_trackImageFetcher->track();\n\n    QString title = track.title();\n    QString description = tr(\"%1\\n%2\").arg( track.artist(), track.album() );\n\n    if ( track.album().isNull() )\n        description = track.artist();\n\n    NSString* nsTitle = [NSString stringWithCharacters:(const unichar *)title.unicode() length:(NSUInteger)title.length() ];\n    NSString* nsDescription = [NSString stringWithCharacters:(const unichar *)description.unicode() length:(NSUInteger)description.length() ];\n\n#ifdef LASTFM_USER_NOTIFICATIONS\n    if ( [NSUserNotificationCenter class] )\n    {\n        NSUserNotification* userNotification = [NSUserNotification alloc];\n\n        [userNotification setTitle:nsTitle];\n        [userNotification setSubtitle:nsDescription];\n\n        [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];\n    }\n    else\n#endif\n    {\n        NSData* data = nil;\n\n        if ( !pixmap.isNull() )\n        {\n            CGImageRef cgImage = pixmap.toMacCGImageRef();\n            NSImage* nsImage = [[NSImage alloc] initWithCGImage:(CGImageRef)cgImage size:(NSSize)NSZeroSize];\n            data = [nsImage TIFFRepresentation];\n        }\n\n        // TODO: Do the growl notification here. It'll be great!\n        [GrowlApplicationBridge notifyWithTitle:(NSString *)nsTitle\n          description:(NSString *)nsDescription\n          notificationName:(NSString *)@\"New track\"\n                                    iconData:(NSData *)data\n                                    priority:(signed int)0\n                                    isSticky:(BOOL)NO\n                                    clickContext:(id)@\"context\"\n                                    identifier:(NSString*)@\"identifier\" ];\n    }\n\n}\n\n\nvoid\nunicorn::Notify::growlNotificationWasClicked()\n{\n    emit clicked();\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/FooBar08PluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringList>\n\n#include \"FooBar08PluginInfo.h\"\n\nunicorn::FooBar08PluginInfo::FooBar08PluginInfo( QObject* parent )\n    :IPluginInfo( parent )\n{}\n\nunicorn::Version\nunicorn::FooBar08PluginInfo::version() const\n{\n    return Version( 2, 1, 0 );\n}\n\nQString\nunicorn::FooBar08PluginInfo::name() const\n{\n    return \"foobar2000\";\n}\n\nQString\nunicorn::FooBar08PluginInfo::displayName() const\n{\n    return QString( \"foobar2000\" );\n}\n\nQString\nunicorn::FooBar08PluginInfo::processName() const\n{\n    return QString( \"foobar2000.exe\" );\n}\n\nQString\nunicorn::FooBar08PluginInfo::id() const\n{\n    return QString( \"foo2\" );\n}\n\nbool\nunicorn::FooBar08PluginInfo::isAppInstalled() const\n{\n    return QSettings(\"HKEY_CURRENT_USER\\\\Software\\\\foobar2000\", QSettings::NativeFormat).contains(\"DefaultShellAction\");\n}\n\nunicorn::IPluginInfo::BootstrapType\nunicorn::FooBar08PluginInfo::bootstrapType() const\n{\n    return NoBootstrap;\n}\n\nQString\nunicorn::FooBar08PluginInfo::pluginInstaller() const\n{\n    return \"FooPlugin0.9Setup_2.1.exe\";\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/FooBar08PluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef FOOBAR08_PLUGIN_INFO_H_\n#define FOOBAR08_PLUGIN_INFO_H_\n\n#include \"IPluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT FooBar08PluginInfo : public IPluginInfo\n{\n    Q_OBJECT\npublic:\n    FooBar08PluginInfo( QObject* parent = 0 );\n\n    Version version() const;\n    QString name() const;\n\n    QString displayName() const;\n    QString processName() const;\n\n    QString id() const;\n    BootstrapType bootstrapType() const;\n\n    bool isAppInstalled() const;\n    QString pluginInstallPath() const;\n    QString pluginInstaller() const;\n};\n\n}\n\n#endif //FOOBAR08_PLUGIN_INFO_H_\n"
  },
  {
    "path": "lib/unicorn/plugins/Foobar09PluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QSettings>\n#include <QStringList>\n\n#include \"FooBar09PluginInfo.h\"\n\nunicorn::FooBar09PluginInfo::FooBar09PluginInfo( QObject* parent )\n    :IPluginInfo( parent )\n{}\n\nunicorn::Version\nunicorn::FooBar09PluginInfo::version() const\n{\n    return Version( 2, 3, 1, 3 );\n}\n\nQString\nunicorn::FooBar09PluginInfo::name() const\n{\n    return \"foobar2000\";\n}\n\nQString\nunicorn::FooBar09PluginInfo::displayName() const\n{\n    return QString( \"foobar2000\" );\n}\n\nQString\nunicorn::FooBar09PluginInfo::processName() const\n{\n    return QString( \"foobar2000.exe\" );\n}\n\nQString\nunicorn::FooBar09PluginInfo::id() const\n{\n    return QString( \"foo3\" );\n}\n\nbool\nunicorn::FooBar09PluginInfo::isAppInstalled() const\n{\n    return QSettings(\"HKEY_CURRENT_USER\\\\Software\\\\foobar2000\", QSettings::NativeFormat).contains(\"DefaultShellAction\");\n}\n\nunicorn::IPluginInfo::BootstrapType\nunicorn::FooBar09PluginInfo::bootstrapType() const\n{\n    return NoBootstrap;\n}\n\nQString\nunicorn::FooBar09PluginInfo::pluginInstaller() const\n{\n    return \"FooPlugin0.9.4Setup_2.3.1.3.exe\";\n}\n\n"
  },
  {
    "path": "lib/unicorn/plugins/Foobar09PluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef FOOBAR09_PLUGIN_INFO_H_\n#define FOOBAR09_PLUGIN_INFO_H_\n\n#include \"IPluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT FooBar09PluginInfo : public IPluginInfo\n{\n    Q_OBJECT\npublic:\n    FooBar09PluginInfo( QObject* parent = 0 );\n\n    Version version() const;\n    QString name() const;\n\n    QString displayName() const;\n    QString processName() const;\n\n    QString id() const;\n    BootstrapType bootstrapType() const;\n\n    bool isAppInstalled() const;\n    QString pluginInstallPath() const;\n    QString pluginInstaller() const;\n};\n\n}\n\n#endif //FOOBAR09_PLUGIN_INFO_H_\n\n"
  },
  {
    "path": "lib/unicorn/plugins/IPluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QSettings>\n#include <QStringList>\n#include <QCoreApplication>\n#include <QProcess>\n#include <QDebug>\n\n#include <windows.h>\n#include <Shellapi.h>\n#include <Wtsapi32.h>\n\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"../Dialogs/CloseAppsDialog.h\"\n\n#include \"IPluginInfo.h\"\n#include \"KillProcess.h\"\n\nunicorn::IPluginInfo::IPluginInfo( QObject* parent )\n    :QObject( parent )\n    , m_install( false )\n    , m_verbose( false )\n{}\n\nbool\nunicorn::IPluginInfo::doInstall()\n{\n    bool success = false;\n\n    QList<IPluginInfo*> plugins;\n    plugins << this;\n\n    CloseAppsDialog* closeApps = new CloseAppsDialog( plugins, 0 );\n\n    if ( closeApps->result() != QDialog::Accepted )\n        closeApps->exec();\n    else\n        closeApps->deleteLater();\n\n    if ( closeApps->result() == QDialog::Accepted )\n    {\n        QString installer = QString( \"\\\"%1\\\"\" ).arg( QCoreApplication::applicationDirPath() + \"/plugins/\" + pluginInstaller() );\n        qDebug() << installer;\n        QProcess* installerProcess = new QProcess( this );\n        QStringList args;\n        if ( !m_verbose )\n            args << \"/SILENT\";\n        installerProcess->start( installer, args );\n        success = installerProcess->waitForFinished( -1 );\n\n        if ( m_verbose )\n        {\n            if ( !success )\n            {\n                // Tell the user that\n                QMessageBoxBuilder( 0 ).setTitle( tr( \"Plugin install error\" ) )\n                        .setIcon( QMessageBox::Information )\n                        .setText( tr( \"<p>There was an error updating your plugin.</p>\"\n                                      \"<p>Please try again later.</p>\" ) )\n                        .setButtons( QMessageBox::Ok )\n                        .exec();\n            }\n            else\n            {\n                // The user didn't closed their media players\n                QMessageBoxBuilder( 0 ).setTitle( tr( \"Plugin installed!\" ) )\n                        .setIcon( QMessageBox::Information )\n                        .setText( tr( \"<p>The %1 plugin has been installed.</p>\"\n                                      \"<p>You're now ready to scrobble with %1.</p>\" ).arg( name() ) )\n                        .setButtons( QMessageBox::Ok )\n                        .exec();\n            }\n        }\n    }\n    else\n    {\n        // The user didn't close their media players\n        QMessageBoxBuilder( 0 ).setTitle( tr( \"The %1 plugin hasn't been installed\" ).arg( name() ) )\n                .setIcon( QMessageBox::Warning )\n                .setText( tr( \"You didn't close %1 so its plugin hasn't been installed.\" ).arg( name() ) )\n                .setButtons( QMessageBox::Ok )\n                .exec();\n    }\n\n    return success;\n}\n\nbool\nunicorn::IPluginInfo::install() const\n{\n    return m_install;\n}\n\n\nvoid\nunicorn::IPluginInfo::install( bool install )\n{\n    m_install = install;\n}\n\n#ifdef Q_OS_WIN\nBOOL\nunicorn::IPluginInfo::isWow64()\n{\n    BOOL bIsWow64 = FALSE;\n\n    //IsWow64Process is not available on all supported versions of Windows.\n    //Use GetModuleHandle to get a handle to the DLL that contains the function\n    //and GetProcAddress to get a pointer to the function if available.\n\n    void* fnIsWow64Process = GetProcAddress(\n    GetModuleHandle(TEXT(\"kernel32\")),\"IsWow64Process\");\n\n    if(NULL != fnIsWow64Process)\n    {\n        if (!IsWow64Process(GetCurrentProcess(),&bIsWow64))\n        {\n            //handle error\n        }\n    }\n    return bIsWow64;\n}\n#endif\n\n\nbool\nunicorn::IPluginInfo::isInstalled() const\n{\n    QSettings settings( \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Last.fm\\\\Client\\\\Plugins\", QSettings::NativeFormat );\n    return settings.childGroups().contains( id() );\n}\n\nunicorn::Version\nunicorn::IPluginInfo::installedVersion() const\n{\n    QSettings settings( \"HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Last.fm\\\\Client\\\\Plugins\\\\\" + id(), QSettings::NativeFormat );\n    return Version::fromString( settings.value( \"Version\", \"0.0.0.0\" ).toString() );\n}\n\nbool\nunicorn::IPluginInfo::canBootstrap() const\n{\n    return bootstrapType() != NoBootstrap;\n}\n\nQString\nunicorn::IPluginInfo::programFilesX86() const\n{\n    return QString( getenv( \"ProgramFiles(x86)\" ) );\n}\n\nQString\nunicorn::IPluginInfo::programFiles64() const\n{\n    return QString( getenv( \"ProgramW6432\" ) );\n}\n\nvoid\nunicorn::IPluginInfo::setVerbose( bool verbose )\n{\n    m_verbose = verbose;\n}\n\n"
  },
  {
    "path": "lib/unicorn/plugins/IPluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLUGIN_INFO_H_\n#define PLUGIN_INFO_H_\n\n#include \"lib/unicorn/plugins/Version.h\"\n\n#include <lib/DllExportMacro.h>\n\n#include <QString>\n#include <QSettings>\n\n#ifdef WIN32\n#include <windows.h>\n#include <Shlobj.h>\n#endif\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT IPluginInfo : public QObject\n{\n    Q_OBJECT\npublic:\n    IPluginInfo( QObject* parent = 0);\n\n    enum BootstrapType{ NoBootstrap = 0, ClientBootstrap, PluginBootstrap };\n\n    bool install() const;\n\n\n    virtual QString name() const = 0;\n\n    virtual Version version() const = 0;\n    Version installedVersion() const;\n\n    virtual QString id() const = 0;\n    virtual BootstrapType bootstrapType() const = 0;\n\n    virtual bool isAppInstalled() const = 0;\n\n    virtual QString processName() const = 0;\n\n    // DisplayName string value as found in the HKEY_LM/Software/Microsoft/CurrentVersion/Uninstall/{GUID}/\n    virtual QString displayName() const = 0;\n\n    virtual QString pluginInstaller() const = 0;\n\n#ifdef Q_OS_WIN\n    static BOOL isWow64();\n#endif\n\n    virtual bool isInstalled() const;\n    bool canBootstrap() const;\n\n    void setVerbose( bool verbose );\n\npublic slots:\n    bool doInstall();\n    void install( bool install );\n\nprotected:\n    QString programFilesX86() const;\n    QString programFiles64() const;\n\nprivate:\n    bool m_install;\n    bool m_verbose;\n};\n\n}\n#endif //PLUGIN_INFO_H_\n"
  },
  {
    "path": "lib/unicorn/plugins/ITunesPluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringList>\n\n#include \"ITunesPluginInfo.h\"\n\nunicorn::ITunesPluginInfo::ITunesPluginInfo( QObject* parent )\n    :IPluginInfo( parent )\n{}\n\nunicorn::Version\nunicorn::ITunesPluginInfo::version() const\n{\n    return Version( 6, 0, 5, 4 );\n}\n\nQString\nunicorn::ITunesPluginInfo::name() const\n{\n    return \"iTunes\";\n}\n\nQString\nunicorn::ITunesPluginInfo::displayName() const\n{\n    return QString( \"iTunes\" );\n}\n\nQString\nunicorn::ITunesPluginInfo::processName() const\n{\n    return QString( \"iTunes.exe\" );\n}\n\nQString\nunicorn::ITunesPluginInfo::id() const\n{\n#ifdef Q_OS_WIN32\n    return \"itw\";\n#elif\n    return \"osx\";\n#endif\n}\n\nbool\nunicorn::ITunesPluginInfo::isAppInstalled() const\n{\n#ifdef Q_OS_WIN32\n    return QSettings(\"HKEY_CURRENT_USER\\\\Software\\\\Apple Computer, Inc.\\\\iTunes\", QSettings::NativeFormat).contains(\"SM Shortcut Installed\");\n#elif\n    return true;\n#endif\n}\n\nunicorn::IPluginInfo::BootstrapType\nunicorn::ITunesPluginInfo::bootstrapType() const\n{\n    return ClientBootstrap;\n}\n\nQString\nunicorn::ITunesPluginInfo::pluginInstaller() const\n{\n    return \"iTunesPluginWinSetup_6.0.5.4.exe\";\n}\n\n"
  },
  {
    "path": "lib/unicorn/plugins/ITunesPluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef ITUNES_PLUGIN_INFO_H_\n#define ITUNES_PLUGIN_INFO_H_\n\n#include \"IPluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT ITunesPluginInfo : public IPluginInfo\n{\n    Q_OBJECT\npublic:\n    ITunesPluginInfo( QObject* parent = 0 );\n\n    Version version() const;\n    QString name() const;\n\n    QString displayName() const;\n    QString processName() const;\n\n    QString id() const;\n    BootstrapType bootstrapType() const;\n\n    bool isAppInstalled() const;\n    QString pluginInstallPath() const;\n    QString pluginInstaller() const;\n\n#ifdef Q_OS_MAC\n    // the iTunes plugin is always installed on mac\n    bool isInstalled() const { return true; }\n#endif\n};\n\n}\n\n#endif //ITUNES_PLUGIN_INFO_H_\n\n"
  },
  {
    "path": "lib/unicorn/plugins/ITunesPluginInstaller.cpp",
    "content": "/***************************************************************************\n *   Copyright (C) 2005 - 2008 by                                          *\n *      Last.fm Ltd <client@last.fm>                                       *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n\n\n#include \"ITunesPluginInstaller.h\"\n\n#include \"lib/unicorn/dialogs/CloseAppsDialog.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n\n#include <CoreFoundation/CoreFoundation.h>\n\n#include <QApplication>\n#include <QDir>\n#include <QProcess>\n#include <QDebug>\n\nstatic const char* kBundleName = \"AudioScrobbler.bundle\";\nstatic const char* kPListFile = \"Contents/Info.plist\";\n\nQString\nshippedPluginDir()\n{\n    return qApp->applicationDirPath() + \"/\" + kBundleName + \"/\";\n}\n\nQString\niTunesPluginDir()\n{\n    return QDir::homePath() + \"/Library/iTunes/iTunes Plug-ins/\" + kBundleName + \"/\";\n}\n\nunicorn::ITunesPluginInstaller::ITunesPluginInstaller( QWidget* parent )\n    :QObject( parent ),\n      m_needsTwiddlyBootstrap( false )\n{\n    qDebug() << \" shippedPluginDir: \" << shippedPluginDir();\n}\n\nunicorn::Version\nunicorn::ITunesPluginInstaller::installedVersion()\n{\n    return pListVersion( iTunesPluginDir() + kPListFile );\n}\n\nunicorn::Version\nunicorn::ITunesPluginInstaller::bundledVersion()\n{\n    return pListVersion( shippedPluginDir() + kPListFile );\n}\n\nvoid\nunicorn::ITunesPluginInstaller::install()\n{\n    qDebug() << \"Found installed iTunes plugin?\" << isPluginInstalled();\n\n    Version installVersion;\n    Version shippedVersion;\n\n    disableLegacyHelperApp();\n\n    if ( isPluginInstalled() ) \n    {\n        installVersion = installedVersion();\n        qDebug() << \"Found installed iTunes plugin version:\" << installVersion.toString();\n    }\n    else\n        //TODO don't bootstrap if installation fails\n        m_needsTwiddlyBootstrap = true;\n\n    shippedVersion = bundledVersion();\n\n    if ( shippedVersion == Version() )\n    {\n        qDebug() << \"Could not locate shipped iTunes plugin!\" << shippedPluginDir();\n    }\n    else\n    {\n        qDebug() << \"Found shipped iTunes plugin version:\" << shippedVersion.toString();\n\n        if ( installVersion != shippedVersion )\n        {\n            bool closeAppsShown = false;\n\n            qDebug() << \"Installing shipped iTunes plugin...\";\n\n            QWidget* dialogParent = 0;\n            if ( parent()->isWidgetType() )\n                dialogParent = qobject_cast<QWidget*>( parent() );\n\n            unicorn::CloseAppsDialog* closeApps = new unicorn::CloseAppsDialog( dialogParent );\n\n            closeApps->setTitle( tr( \"Close iTunes for plugin update!\" ) );\n            closeApps->setDescription( tr( \"<p>Your iTunes plugin (%2) is different to the one shipped with this version of the app (%1).</p>\"\n                                           \"<p>Please close iTunes now to update.</p>\" ).arg( shippedVersion.toString(), installVersion == Version() ? tr( \"not installed\" ) : installVersion.toString() ) );\n            closeApps->showPluginList( false );\n\n            if ( closeApps->result() != QDialog::Accepted )\n            {\n                closeAppsShown = true;\n                closeApps->exec();\n            }\n            else\n                closeApps->deleteLater();\n\n            if ( closeApps->result() == QDialog::Accepted )\n            {\n                if ( !removeInstalledPlugin() )\n                {\n                    qDebug() << \"Removing installed plugin from\" << iTunesPluginDir() << \"failed!\";\n\n                    // The user didn't close their media players\n                    QMessageBoxBuilder( dialogParent ).setTitle( tr( \"Your plugin hasn't been installed\" ) )\n                            .setIcon( QMessageBox::Warning )\n                            .setText( tr( \"There was an error while removing the old plugin\" ) )\n                            .setButtons( QMessageBox::Ok )\n                            .exec();\n                }\n                else\n                {\n                    qDebug() << \"Successfully removed installed plugin.\";\n\n                    if ( installPlugin() )\n                    {\n                        qDebug() << \"Successfully installed the plugin.\";\n\n                        if ( closeAppsShown )\n                        {\n                            // Tell the user that\n                            QMessageBoxBuilder( dialogParent ).setTitle( tr( \"iTunes Plugin installed!\" ) )\n                                    .setIcon( QMessageBox::Information )\n                                    .setText( tr( \"<p>Your iTunes plugin has been installed.</p>\"\n                                                  \"<p>You're now ready to device scrobble.</p>\" ) )\n                                    .setButtons( QMessageBox::Ok )\n                                    .exec();\n                        }\n                    }\n                    else\n                    {\n                        qDebug() << \"Installing the plugin failed!\";\n\n                        // The user didn't close their media players\n                        QMessageBoxBuilder( dialogParent ).setTitle( tr( \"Your plugin hasn't been installed\" ) )\n                                .setIcon( QMessageBox::Warning )\n                                .setText( tr( \"There was an error while copying the new plugin into place\" ) )\n                                .setButtons( QMessageBox::Ok )\n                                .exec();\n                    }\n                }\n            }\n            else\n            {\n                qDebug() << \"Plugin not installed. User reject the dialog.\";\n\n                // The user didn't close their media players\n                QMessageBoxBuilder( dialogParent ).setTitle( tr( \"Your plugin hasn't been installed\" ) )\n                        .setIcon( QMessageBox::Warning )\n                        .setText( tr( \"You didn't close iTunes\" ) )\n                        .setButtons( QMessageBox::Ok )\n                        .exec();\n            }\n        }\n        else\n            qDebug() << \"Installed iTunes plugin is up-to-date.\";\n    }\n}\n\nbool\nunicorn::ITunesPluginInstaller::isPluginInstalled()\n{\n    return QDir( iTunesPluginDir() ).exists();\n}\n\n\nunicorn::Version\nunicorn::ITunesPluginInstaller::pListVersion( const QString& file )\n{\n    QFile f( file );\n    if ( !f.open( QIODevice::ReadOnly ) )\n        return Version();\n\n    const QString key( \"<key>CFBundleVersion</key>\" );\n    const QString begin( \"<string>\" );\n    const QString end( \"</string>\" );\n\n    while ( !f.atEnd() )\n    {\n        QString line = f.readLine();\n        if ( line.contains( key ) && !f.atEnd() )\n        {\n            QString versionLine = QString( ( f.readLine() ) ).trimmed();\n            QString versionString = versionLine.section( begin, 1 );\n            versionString = versionString.left( versionString.length() - end.length() );\n            Version version = Version::fromString( versionString );\n\n            f.close();\n            return version;\n        }\n    }\n\n    f.close();\n    return Version();\n}\n\n\nstatic bool\ndeleteDir( QString path )\n{\n    if ( !path.endsWith( \"/\" ) )\n        path += \"/\";\n\n    QDir d( path );\n\n    // Remove all files\n    const QStringList files = d.entryList( QDir::Files );\n    foreach( QString file, files )\n    {\n        if ( !d.remove( file ) )\n            return false;\n    }\n\n    // Remove all dirs (recursive)\n    const QStringList dirs = d.entryList( QDir::Dirs | QDir::NoDotAndDotDot );\n    foreach( QString dir, dirs )\n    {\n        if ( !deleteDir( path + dir ) )\n            return false;\n    }\n\n    return d.rmdir( path );\n}\n\n\nbool\nunicorn::ITunesPluginInstaller::removeInstalledPlugin()\n{\n    if ( !isPluginInstalled() )\n        return true;\n\n    return deleteDir( iTunesPluginDir() );\n}\n\n\nstatic bool\ncopyDir( QString path, QString dest )\n{\n    if ( !path.endsWith( '/' ) )\n        path += '/';\n    if ( !dest.endsWith( '/' ) )\n        dest += '/';\n\n    QDir( dest ).mkpath( \".\" );\n    QDir d( path );\n\n    const QStringList files = d.entryList( QDir::Files );\n    foreach( QString file, files )\n    {\n        QFile f( path + file );\n        if ( !f.copy( dest + file ) )\n            return false;\n    }\n\n    const QStringList dirs = d.entryList( QDir::Dirs | QDir::NoDotAndDotDot );\n    foreach( QString dir, dirs )\n    {\n        if ( !copyDir( path + dir, dest + dir ) )\n            return false;\n    }\n\n    return true;\n}\n\n\nbool\nunicorn::ITunesPluginInstaller::installPlugin()\n{\n    return copyDir( shippedPluginDir(), iTunesPluginDir() );\n}\n\n\nstatic inline QByteArray\nCFStringToUtf8( CFStringRef s )\n{\n    QByteArray result;\n\n    if (s != NULL) \n    {\n        CFIndex length;\n        length = CFStringGetLength( s );\n        length = CFStringGetMaximumSizeForEncoding( length, kCFStringEncodingUTF8 ) + 1;\n        char* buffer = new char[length];\n\n        if (CFStringGetCString( s, buffer, length, kCFStringEncodingUTF8 ))\n            result = QByteArray( buffer );\n        else\n            qWarning() << \"CFString conversion failed.\";\n\n        delete[] buffer;\n    }\n\n    return result;\n}\n\n\n\nvoid\nunicorn::ITunesPluginInstaller::disableLegacyHelperApp()\n{\n    qDebug() << \"Disabling old LastFmHelper\";\n\n    // EVEN MORE LEGACY: disable oldest helper auto-launch!\n    QString oldplist = QDir::homePath() + \"/Library/LaunchAgents/fm.last.lastfmhelper.plist\";\n    if ( QFile::exists( oldplist ) )\n    {\n        QProcess::execute( \"/bin/launchctl\", QStringList() << \"unload\" << oldplist );\n        QFile::remove( oldplist );\n    }\n\n    // REMOVE LastFmHelper from loginwindow.plist\n    CFArrayRef prefCFArrayRef = (CFArrayRef)CFPreferencesCopyValue( CFSTR( \"AutoLaunchedApplicationDictionary\" ), \n                                                                    CFSTR( \"loginwindow\" ), \n                                                                    kCFPreferencesCurrentUser, \n                                                                    kCFPreferencesAnyHost );\n    if ( prefCFArrayRef == NULL ) return;\n    CFMutableArrayRef tCFMutableArrayRef = CFArrayCreateMutableCopy( NULL, 0, prefCFArrayRef );\n    if ( tCFMutableArrayRef == NULL ) return;\n\n    for ( int i = CFArrayGetCount( prefCFArrayRef ) - 1; i >= 0 ; i-- )\n    {\n        CFDictionaryRef dict = (CFDictionaryRef)CFArrayGetValueAtIndex( prefCFArrayRef, i );\n        QString path = QString::fromUtf8( CFStringToUtf8( (CFStringRef)CFDictionaryGetValue( dict, CFSTR( \"Path\" ) ) ) );\n\n        if ( path.toLower().contains( \"lastfmhelper\" ) )\n        {\n            // Better make sure LastFmHelper is really dead\n            QProcess::execute( \"/usr/bin/killall\", QStringList() << \"LastFmHelper\" );\n\n            qDebug() << \"Removing helper from LoginItems at position\" << i;\n            CFArrayRemoveValueAtIndex( tCFMutableArrayRef, (CFIndex)i );\n        }\n    }\n\n    CFPreferencesSetValue( CFSTR( \"AutoLaunchedApplicationDictionary\" ), \n                           tCFMutableArrayRef, \n                           CFSTR( \"loginwindow\" ), \n                           kCFPreferencesCurrentUser, \n                           kCFPreferencesAnyHost );\n    CFPreferencesSynchronize( CFSTR( \"loginwindow\" ), \n                              kCFPreferencesCurrentUser, \n                              kCFPreferencesAnyHost );\n\n    CFRelease( prefCFArrayRef );\n    CFRelease( tCFMutableArrayRef );\n}\n\n\nvoid\nunicorn::ITunesPluginInstaller::uninstall()\n{\n    QDir d = iTunesPluginDir() + \"Contents/Resources\";\n    \n    // always use absolute paths to tools! - muesli\n    QProcess::startDetached( \"/bin/sh\", \n                             QStringList() << d.filePath( \"uninstall.sh\" ),\n                             d.path() );\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/ITunesPluginInstaller.h",
    "content": "/***************************************************************************\n *   Copyright 2005-2008 Last.fm Ltd <client@last.fm>                      *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\n ***************************************************************************/\n\n#pragma once\n\n#include \"Version.h\"\n\n#include <lib/DllExportMacro.h>\n\n#include <QObject>\n#include <QString>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT ITunesPluginInstaller : public QObject\n{\n    Q_OBJECT\npublic:\n    ITunesPluginInstaller( QWidget* parent );\n\n    static Version installedVersion();\n    static Version bundledVersion();\n    \n    void uninstall();\n\n    // NOTE this is only valid after calling install()\n    bool needsTwiddlyBootstrap() const { return m_needsTwiddlyBootstrap; }\n\npublic slots:\n    void install();\n\nprivate:\n    bool isPluginInstalled();\n    static Version pListVersion( const QString& file );\n\n    bool removeInstalledPlugin();\n    bool installPlugin();\n\n    // Legacy code: removes old LastFmHelper for updates\n    void disableLegacyHelperApp();\n\nprivate:\n    bool m_needsTwiddlyBootstrap;\n};\n\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/KillProcess.h",
    "content": "/***************************************************************************\r\n *   Copyright (C) 2005 - 2007 by                                          *\r\n *      Last.fm Ltd <client@last.fm>                                       *\r\n *                                                                         *\r\n *   This program is free software; you can redistribute it and/or modify  *\r\n *   it under the terms of the GNU General Public License as published by  *\r\n *   the Free Software Foundation; either version 2 of the License, or     *\r\n *   (at your option) any later version.                                   *\r\n *                                                                         *\r\n *   This program is distributed in the hope that it will be useful,       *\r\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\r\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\r\n *   GNU General Public License for more details.                          *\r\n *                                                                         *\r\n *   You should have received a copy of the GNU General Public License     *\r\n *   along with this program; if not, write to the                         *\r\n *   Free Software Foundation, Inc.,                                       *\r\n *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *\r\n ***************************************************************************/\r\n\r\n#ifdef WIN32\r\n\r\n#ifndef KILLPROCESS_H\r\n#define KILLPROCESS_H\r\n\r\n// This file contains legacy code that doesn't work with Unicode.\r\n#undef UNICODE\r\n#undef _UNICODE\r\n\r\n#include <windows.h>\r\n#include <tlhelp32.h>\r\n//\r\n// Some definitions from NTDDK and other sources\r\n//\r\n\r\ntypedef LONG    NTSTATUS;\r\ntypedef LONG    KPRIORITY;\r\n\r\n#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)\r\n\r\n#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)\r\n\r\n#define SystemProcessesAndThreadsInformation    5\r\n\r\ntypedef struct _CLIENT_ID {\r\n    DWORD        UniqueProcess;\r\n    DWORD        UniqueThread;\r\n} CLIENT_ID;\r\n\r\ntypedef struct _UNICODE_STRING {\r\n    USHORT        Length;\r\n    USHORT        MaximumLength;\r\n    PWSTR        Buffer;\r\n} UNICODE_STRING;\r\n\r\ntypedef struct _VM_COUNTERS {\r\n    SIZE_T        PeakVirtualSize;\r\n    SIZE_T        VirtualSize;\r\n    ULONG        PageFaultCount;\r\n    SIZE_T        PeakWorkingSetSize;\r\n    SIZE_T        WorkingSetSize;\r\n    SIZE_T        QuotaPeakPagedPoolUsage;\r\n    SIZE_T        QuotaPagedPoolUsage;\r\n    SIZE_T        QuotaPeakNonPagedPoolUsage;\r\n    SIZE_T        QuotaNonPagedPoolUsage;\r\n    SIZE_T        PagefileUsage;\r\n    SIZE_T        PeakPagefileUsage;\r\n} VM_COUNTERS;\r\n\r\ntypedef struct _SYSTEM_THREADS {\r\n    LARGE_INTEGER   KernelTime;\r\n    LARGE_INTEGER   UserTime;\r\n    LARGE_INTEGER   CreateTime;\r\n    ULONG            WaitTime;\r\n    PVOID            StartAddress;\r\n    CLIENT_ID        ClientId;\r\n    KPRIORITY        Priority;\r\n    KPRIORITY        BasePriority;\r\n    ULONG            ContextSwitchCount;\r\n    LONG            State;\r\n    LONG            WaitReason;\r\n} SYSTEM_THREADS, * PSYSTEM_THREADS;\r\n\r\n// Note that the size of the SYSTEM_PROCESSES structure is \r\n// different on NT 4 and Win2K, but we don't care about it, \r\n// since we don't access neither IoCounters member nor \r\n//Threads array\r\n\r\ntypedef struct _SYSTEM_PROCESSES {\r\n    ULONG            NextEntryDelta;\r\n    ULONG            ThreadCount;\r\n    ULONG            Reserved1[6];\r\n    LARGE_INTEGER   CreateTime;\r\n    LARGE_INTEGER   UserTime;\r\n    LARGE_INTEGER   KernelTime;\r\n    UNICODE_STRING  ProcessName;\r\n    KPRIORITY        BasePriority;\r\n    ULONG            ProcessId;\r\n    ULONG            InheritedFromProcessId;\r\n    ULONG            HandleCount;\r\n    ULONG            Reserved2[2];\r\n    VM_COUNTERS        VmCounters;\r\n#if _WIN32_WINNT >= 0x500\r\n    IO_COUNTERS        IoCounters;\r\n#endif\r\n    SYSTEM_THREADS  Threads[1];\r\n} SYSTEM_PROCESSES, * PSYSTEM_PROCESSES;\r\n\r\n\r\nclass CKillProcessHelper\r\n{\r\nprivate:\r\n    //Functions loaded from Kernel32\r\n    typedef HANDLE (WINAPI *PFCreateToolhelp32Snapshot)(\r\n        DWORD dwFlags,       \r\n        DWORD th32ProcessID  \r\n        );\r\n\r\n    typedef BOOL (WINAPI *PFProcess32First)(\r\n        HANDLE hSnapshot,      \r\n        LPPROCESSENTRY32 lppe  \r\n        );\r\n\r\n    typedef BOOL (WINAPI *PFProcess32Next)(\r\n        HANDLE hSnapshot,      \r\n        LPPROCESSENTRY32 lppe  \r\n        );\r\n\r\n    // Native NT API Definitions\r\n    typedef NTSTATUS (WINAPI * PFZwQuerySystemInformation)\r\n        (UINT, PVOID, ULONG, PULONG);\r\n    typedef HANDLE (WINAPI* PFGetProcessHeap)(VOID);\r\n    typedef LPVOID (WINAPI* PFHeapAlloc)\r\n        (HANDLE,DWORD,SIZE_T);\r\n    typedef BOOL (WINAPI* PFHeapFree)(HANDLE,DWORD,LPVOID);\r\n\r\npublic:\r\n    CKillProcessHelper() : FCreateToolhelp32Snapshot(NULL), \r\n        FProcess32First(NULL), FProcess32Next(NULL), \r\n        m_hKernelLib(NULL),\r\n        m_hNTLib(NULL)\r\n    {\r\n        m_hKernelLib = ::LoadLibraryA(\"Kernel32\");\r\n        if (m_hKernelLib)  \r\n        {\r\n            // Find ToolHelp functions\r\n            FCreateToolhelp32Snapshot = \r\n                (PFCreateToolhelp32Snapshot)\r\n                ::GetProcAddress(m_hKernelLib,\r\n                (\"CreateToolhelp32Snapshot\"));\r\n            FProcess32First = (PFProcess32First)\r\n                ::GetProcAddress(m_hKernelLib, \r\n                (\"Process32First\"));\r\n            FProcess32Next = (PFProcess32Next)\r\n                ::GetProcAddress(m_hKernelLib, \r\n                (\"Process32Next\"));\r\n        }\r\n        if(!FCreateToolhelp32Snapshot || \r\n            !FProcess32First || !FProcess32Next)\r\n        { // i.e. we couldn't find the ToolHelp functions, \r\n            //so we must be on NT4. Let's load the\r\n            // undocumented one instead.\r\n            if(!m_hKernelLib)\r\n                return; // can't do anything at all without \r\n            //the kernel.\r\n\r\n            m_hNTLib = ::LoadLibraryA(\"ntdll.dll\");\r\n            if(m_hNTLib)\r\n            {\r\n                FQuerySysInfo = \r\n                    (PFZwQuerySystemInformation)\r\n                    ::GetProcAddress(m_hNTLib, \r\n                    (\"ZwQuerySystemInformation\"));\r\n                // load some support funcs from the kernel\r\n                FGetProcessHeap = (PFGetProcessHeap)\r\n                    ::GetProcAddress(m_hKernelLib, \r\n                    (\"GetProcessHeap\"));\r\n                FHeapAlloc = (PFHeapAlloc)\r\n                    ::GetProcAddress(m_hKernelLib, \r\n                    (\"HeapAlloc\"));\r\n                FHeapFree = (PFHeapFree)\r\n                    ::GetProcAddress(m_hKernelLib, \r\n                    (\"HeapFree\"));\r\n            }\r\n        }\r\n    }\r\n    ~CKillProcessHelper()\r\n    {\r\n        if(m_hKernelLib)\r\n            FreeLibrary(m_hKernelLib);\r\n        if(m_hNTLib)\r\n            FreeLibrary(m_hNTLib);\r\n    }\r\n    bool KillProcess(IN const char* pstrProcessName)\r\n    {\r\n        DWORD dwId;\r\n        HANDLE hProcess = FindProcess(pstrProcessName, \r\n            dwId);\r\n        BOOL bResult;\r\n        if(!hProcess)\r\n            return false;\r\n\r\n        // TerminateAppEnum() posts WM_CLOSE to all windows whose PID\r\n        // matches your process's.\r\n        ::EnumWindows((WNDENUMPROC)\r\n            CKillProcessHelper::TerminateAppEnum, \r\n            (LPARAM) dwId);\r\n        // Wait on the handle. If it signals, great. \r\n        //If it times out, then you kill it.\r\n        if(WaitForSingleObject(hProcess, 5000)\r\n            !=WAIT_OBJECT_0)\r\n            bResult = TerminateProcess(hProcess,0);\r\n        else\r\n            bResult = TRUE; \r\n        CloseHandle(hProcess);\r\n        return static_cast<bool>(bResult != FALSE);\r\n    }\r\n    HANDLE FindProcess(IN const char* pstrProcessName,\r\n    OUT DWORD& dwId)\r\n    {\r\n        if(!m_hKernelLib)\r\n            return NULL;\r\n\r\n        if(FCreateToolhelp32Snapshot && FProcess32First && \r\n            FProcess32Next) // use toolhelpapi\r\n            return THFindProcess(pstrProcessName, dwId);\r\n        if(FQuerySysInfo && FHeapAlloc && \r\n            FGetProcessHeap && FHeapFree) // use NT api\r\n            return NTFindProcess(pstrProcessName, dwId);\r\n        // neither one got loaded. Strange.\r\n        return NULL;\r\n    }\r\n\r\nprivate:\r\n    HANDLE THFindProcess(IN const char* pstrProcessName, \r\n        OUT DWORD& dwId)\r\n    {\r\n        HANDLE            hSnapShot=NULL;\r\n        HANDLE            hResult = NULL;\r\n        PROCESSENTRY32    processInfo;\r\n        char*            pstrExeName;\r\n\r\n        bool bFirst = true;\r\n        ::ZeroMemory(&processInfo, sizeof(PROCESSENTRY32));\r\n        processInfo.dwSize = sizeof(PROCESSENTRY32);\r\n        hSnapShot = FCreateToolhelp32Snapshot(\r\n            TH32CS_SNAPPROCESS, 0);\r\n        if(hSnapShot == INVALID_HANDLE_VALUE)\r\n            return NULL; \r\n\r\n        // ok now let's iterate with Process32Next until we \r\n        // match up the name of our process\r\n        while((bFirst ? FProcess32First(hSnapShot, \r\n            &processInfo) : FProcess32Next(hSnapShot, \r\n            &processInfo)))\r\n        {\r\n            bFirst = false;\r\n            // we need to check for path... and extract \r\n            // just the exe name\r\n            pstrExeName = strrchr(processInfo.szExeFile, \r\n                '\\\\');\r\n            if(!pstrExeName)\r\n                pstrExeName = processInfo.szExeFile;\r\n            else\r\n                pstrExeName++; // skip the backslash\r\n            // ok now compare against our process name\r\n            if(_stricmp(pstrExeName, pstrProcessName) == 0)\r\n                // wee weee we found it\r\n            {\r\n                // let's get a HANDLE on it\r\n                hResult=OpenProcess(\r\n                    SYNCHRONIZE|PROCESS_TERMINATE, TRUE, \r\n                    processInfo.th32ProcessID);\r\n                dwId = processInfo.th32ProcessID;\r\n                break;\r\n            }\r\n        } // while(Process32Next(hSnapShot, &processInfo){\r\n        if(hSnapShot)\r\n            CloseHandle(hSnapShot);\r\n        return hResult;\r\n    }\r\n    HANDLE NTFindProcess(IN const char* pstrProcessName, \r\n        OUT DWORD& dwId)\r\n    {\r\n        HANDLE hHeap = FGetProcessHeap();\r\n        NTSTATUS Status;\r\n        ULONG cbBuffer = 0x8000;\r\n        PVOID pBuffer = NULL;\r\n        HANDLE hResult = NULL;\r\n        // it is difficult to say a priory which size of \r\n        // the buffer will be enough to retrieve all \r\n        // information, so we startwith 32K buffer and \r\n        // increase its size until we get the\r\n        // information successfully\r\n        do\r\n        {\r\n            pBuffer = HeapAlloc(hHeap, 0, cbBuffer);\r\n            if (pBuffer == NULL)\r\n                return SetLastError(\r\n                ERROR_NOT_ENOUGH_MEMORY), NULL;\r\n\r\n            Status = FQuerySysInfo(\r\n                SystemProcessesAndThreadsInformation,\r\n                pBuffer, cbBuffer, NULL);\r\n\r\n            if (Status == STATUS_INFO_LENGTH_MISMATCH)\r\n            {\r\n                HeapFree(hHeap, 0, pBuffer);\r\n                cbBuffer *= 2;\r\n            }\r\n            else if (!NT_SUCCESS(Status))\r\n            {\r\n                HeapFree(hHeap, 0, pBuffer);\r\n                return SetLastError(Status), NULL;\r\n            }\r\n        }\r\n        while (Status == STATUS_INFO_LENGTH_MISMATCH);\r\n\r\n        PSYSTEM_PROCESSES pProcesses = \r\n            (PSYSTEM_PROCESSES)pBuffer;\r\n\r\n        for (;;)\r\n        {\r\n            PCWSTR pszProcessName = \r\n                pProcesses->ProcessName.Buffer;\r\n            if (pszProcessName == NULL)\r\n                pszProcessName = L\"Idle\";\r\n\r\n            CHAR szProcessName[MAX_PATH];\r\n            WideCharToMultiByte(CP_ACP, 0, pszProcessName, \r\n                -1,szProcessName, MAX_PATH, NULL, NULL);\r\n\r\n            if(_stricmp(szProcessName, pstrProcessName)\r\n                == 0) // found it\r\n            {\r\n                hResult=OpenProcess(\r\n                    SYNCHRONIZE|PROCESS_TERMINATE, TRUE, \r\n                    pProcesses->ProcessId);\r\n                dwId = pProcesses->ProcessId;\r\n                break;\r\n            }\r\n\r\n            if (pProcesses->NextEntryDelta == 0)\r\n                break;\r\n\r\n            // find the address of the next process \r\n            // structure\r\n            pProcesses = (PSYSTEM_PROCESSES)(\r\n                ((LPBYTE)pProcesses)\r\n                + pProcesses->NextEntryDelta);\r\n        }\r\n\r\n        HeapFree(hHeap, 0, pBuffer);\r\n        return hResult;\r\n    }\r\n    // callback function for window enumeration\r\n    static BOOL CALLBACK TerminateAppEnum( HWND hwnd, \r\n        LPARAM lParam )\r\n    {\r\n        DWORD dwID ;\r\n\r\n        GetWindowThreadProcessId(hwnd, &dwID) ;\r\n\r\n        if(dwID == (DWORD)lParam)\r\n        {\r\n            PostMessage(hwnd, WM_CLOSE, 0, 0) ;\r\n        }\r\n\r\n        return TRUE ;\r\n    }\r\n    HMODULE            m_hNTLib;\r\n    HMODULE            m_hKernelLib;\r\n    // ToolHelp related functions\r\n    PFCreateToolhelp32Snapshot    FCreateToolhelp32Snapshot;\r\n    PFProcess32First            FProcess32First;\r\n    PFProcess32Next                FProcess32Next;\r\n    // native NT api functions\r\n    PFZwQuerySystemInformation    FQuerySysInfo;\r\n    PFGetProcessHeap            FGetProcessHeap;\r\n    PFHeapAlloc                    FHeapAlloc;\r\n    PFHeapFree                    FHeapFree;\r\n};\r\n\r\n#endif // KILLPROCESS_H\r\n\r\n#endif // WIN32\r\n"
  },
  {
    "path": "lib/unicorn/plugins/PluginList.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"PluginList.h\"\n#include <QStringList>\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::availablePlugins() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* plugin, m_plugins )\n    {\n        if( plugin->isInstalled() )\n            continue;\n        if( plugin->isAppInstalled() )\n            ret << plugin;\n    }\n    return ret;\n}\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::installedPlugins() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* plugin, m_plugins )\n    {\n        if( plugin->isInstalled())\n            ret << plugin;\n    }\n    return ret;\n}\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::bootstrappablePlugins() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* plugin, installedPlugins() )\n    {\n        if( plugin->isInstalled() && plugin->canBootstrap() )\n            ret << plugin;\n    }\n    return ret;\n}\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::supportedList() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* i, m_plugins )\n        ret << i;\n\n    return ret;\n}\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::installList() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* i, m_plugins )\n    {\n        if ( i->install() )\n            ret << i;\n    }\n\n    return ret;\n}\n\nQList<unicorn::IPluginInfo*>\nunicorn::PluginList::updatedList() const\n{\n    QList<IPluginInfo*> ret;\n    foreach( IPluginInfo* i, m_plugins )\n    {\n        if ( i->isInstalled() && i->version() > i->installedVersion() )\n            ret << i;\n    }\n\n    return ret;\n}\n\nQString\nunicorn::PluginList::availableDescription() const\n{\n    QStringList mediaPlayers;\n    \n    foreach( IPluginInfo* i, supportedList() )\n        mediaPlayers << i->name();\n\n    QString ret = mediaPlayers.takeLast();\n    \n    if( mediaPlayers.count() > 0 )\n        ret = mediaPlayers.join( \", \" ) + \" or \" + ret;\n\n    return ret;\n}\n\nunicorn::IPluginInfo*\nunicorn::PluginList::pluginById( const QString& id ) const\n{\n    foreach( IPluginInfo* plugin, m_plugins )\n    {\n        if( !plugin->id().compare( id ) )\n            return plugin;\n    }\n\n    return NULL;\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/PluginList.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PLUGIN_LIST_H_\n#define PLUGIN_LIST_H_\n\n#include <QObject>\n\n#include \"WinampPluginInfo.h\"\n#include \"WmpPluginInfo.h\"\n#include \"ITunesPluginInfo.h\"\n#include \"Foobar09PluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT PluginList : public QObject\n{\n    Q_OBJECT\npublic:\n    PluginList( QObject* parent = 0 ) : QObject( parent )\n    {\n        m_plugins << (new ITunesPluginInfo( this ));\n        m_plugins << (new WmpPluginInfo( this ));\n        m_plugins << (new WinampPluginInfo( this ));\n        m_plugins << (new FooBar09PluginInfo( this ));\n    }\n\n    QList<IPluginInfo*> availablePlugins() const;\n    QList<IPluginInfo*> installedPlugins() const;\n    QList<IPluginInfo*> bootstrappablePlugins() const;\n    QList<IPluginInfo*> installList() const;\n\n    QList<IPluginInfo*> updatedList() const;\n    QList<IPluginInfo*> supportedList() const;\n    QString availableDescription() const;\n\n    IPluginInfo* pluginById( const QString& id ) const;\n\nprivate:\n    QList<IPluginInfo*> m_plugins;\n};\n\n}\n\n#endif //PLUGIN_LIST_H_\n"
  },
  {
    "path": "lib/unicorn/plugins/Version.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"Version.h\"\n\n#include <QStringList>\n\nunicorn::Version::Version()\n    :m_major( 0 ),\n      m_minor( 0 ),\n      m_build( 0 ),\n      m_revision( 0 )\n{\n\n}\n\nunicorn::Version::Version( unsigned int major, unsigned int minor, unsigned int build, unsigned int revision )\n    :m_major( major ),\n      m_minor( minor ),\n      m_build( build ),\n      m_revision( revision )\n{\n}\n\nbool\nunicorn::Version::operator !=( const Version& that ) const\n{\n    return !(*this == that);\n}\n\nbool\nunicorn::Version::operator ==( const Version& that ) const\n{\n    if( m_major != that.m_major ) return false;\n    if( m_minor != that.m_minor ) return false;\n    if( m_build != that.m_build ) return false;\n    if( m_revision != that.m_revision ) return false;\n\n    return true;\n}\n\nbool\nunicorn::Version::operator <( const Version& that ) const\n{\n    return !(*this == that || *this > that );\n}\n\nbool\nunicorn::Version::operator >( const Version& that ) const\n{\n    if( m_major > that.m_major ) return true;\n    if( m_minor > that.m_minor ) return true;\n    if( m_build > that.m_build ) return true;\n    if( m_revision > that.m_revision ) return true;\n\n    return false;\n}\n\nQString\nunicorn::Version::toString() const\n{\n    return QString( \"%1.%2.%3.%4\" ).arg( QString::number( m_major ),\n                                         QString::number( m_minor ),\n                                         QString::number( m_build ),\n                                         QString::number( m_revision ) );\n}\n\nunicorn::Version\nunicorn::Version::fromString( const QString& string )\n{\n    QStringList versionList = string.split( \".\" );\n\n    int major = versionList.count() > 0 ? versionList.at( 0 ).toUInt() : 0;\n    int minor = versionList.count() > 1 ? versionList.at( 1 ).toUInt() : 0;\n    int build = versionList.count() > 2 ? versionList.at( 2 ).toUInt() : 0;\n    int revision = versionList.count() > 3 ? versionList.at( 3 ).toUInt() : 0;\n\n    return Version( major, minor, build, revision );\n}\n\n"
  },
  {
    "path": "lib/unicorn/plugins/Version.h",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#pragma once\n\n#include <lib/DllExportMacro.h>\n\n#include <QString>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT Version\n{\npublic:\n    Version();\n\n    Version( unsigned int major, unsigned int minor = 0, unsigned int build = 0, unsigned int revision = 0 );\n\n    QString toString() const;\n    static Version fromString( const QString& string );\n\n    bool operator !=( const Version& that ) const;\n    bool operator ==( const Version& that ) const;\n    bool operator <( const Version& that ) const;\n    bool operator >( const Version& that ) const;\n\nprivate:\n    unsigned int m_major;\n    unsigned int m_minor;\n    unsigned int m_build;\n    unsigned int m_revision;\n};\n\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/WinampPluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringList>\n\n#include \"WinampPluginInfo.h\"\n\nunicorn::WinampPluginInfo::WinampPluginInfo( QObject* parent )\n    :IPluginInfo( parent )\n{}\n\nunicorn::Version\nunicorn::WinampPluginInfo::version() const\n{\n    return Version( 2, 1, 0, 11 );\n}\n\nQString\nunicorn::WinampPluginInfo::name() const\n{\n    return \"Winamp\";\n}\n\nQString\nunicorn::WinampPluginInfo::displayName() const\n{\n    return QString( \"MPlayer2\" );\n}\n\nQString\nunicorn::WinampPluginInfo::processName() const\n{\n    return QString( \"winamp.exe\" );\n}\n\nQString\nunicorn::WinampPluginInfo::id() const\n{\n    return \"wa2\";\n}\n\nbool\nunicorn::WinampPluginInfo::isAppInstalled() const\n{\n    return QSettings(\"HKEY_CURRENT_USER\\\\Software\\\\Winamp\", QSettings::NativeFormat).contains(\".\");\n}\n\nunicorn::IPluginInfo::BootstrapType\nunicorn::WinampPluginInfo::bootstrapType() const\n{\n    return PluginBootstrap;\n}\n\nQString\nunicorn::WinampPluginInfo::pluginInstaller() const\n{\n    return \"WinampPluginSetup_2.1.0.11.exe\";\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/WinampPluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef WINAMP_PLUGIN_INFO_H_\n#define WINAMP_PLUGIN_INFO_H_\n\n#include \"../Plugins/IPluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT WinampPluginInfo : public IPluginInfo\n{\n    Q_OBJECT\npublic:\n    WinampPluginInfo( QObject* parent = 0 );\n\n    Version version() const;\n    QString name() const;\n    \n    QString displayName() const;\n    QString processName() const;\n\n    QString id() const;\n    BootstrapType bootstrapType() const;\n\n    bool isAppInstalled() const;\n    QString pluginInstallPath() const;\n    QString pluginInstaller() const;\n};\n\n}\n\n#endif //WINAMP_PLUGIN_INFO_H_\n\n"
  },
  {
    "path": "lib/unicorn/plugins/WmpPluginInfo.cpp",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStringList>\n\n#include \"WmpPluginInfo.h\"\n\nunicorn::WmpPluginInfo::WmpPluginInfo( QObject* parent )\n    :IPluginInfo( parent )\n{}\n\nunicorn::Version\nunicorn::WmpPluginInfo::version() const\n{\n    return Version( 2, 1, 0, 8 );\n}\n\nQString\nunicorn::WmpPluginInfo::name() const\n{\n    return \"Windows Media Player\";\n}\n\nQString\nunicorn::WmpPluginInfo::displayName() const\n{\n    return QString( \"MPlayer2\" );\n}\n\nQString\nunicorn::WmpPluginInfo::processName() const\n{\n    return QString( \"wmplayer.exe\" );\n}\n\nQString\nunicorn::WmpPluginInfo::id() const\n{\n    return \"wmp\";\n}\n\nbool\nunicorn::WmpPluginInfo::isAppInstalled() const\n{\n    return QSettings(\"HKEY_CURRENT_USER\\\\Software\\\\Microsoft\\\\MediaPlayer\\\\Preferences\", QSettings::NativeFormat).contains(\"FirstRun\");\n}\n\nunicorn::IPluginInfo::BootstrapType\nunicorn::WmpPluginInfo::bootstrapType() const\n{\n    return PluginBootstrap;\n}\n\nQString\nunicorn::WmpPluginInfo::pluginInstaller() const\n{\n    return \"WmpPluginSetup_2.1.0.8.exe\";\n}\n"
  },
  {
    "path": "lib/unicorn/plugins/WmpPluginInfo.h",
    "content": "/*\n   Copyright 2010-2013 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef WMP_PLUGIN_INFO_H_\n#define WMP_PLUGIN_INFO_H_\n\n#include \"../Plugins/IPluginInfo.h\"\n\n#include <lib/DllExportMacro.h>\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT WmpPluginInfo : public IPluginInfo\n{\n    Q_OBJECT\npublic:\n    WmpPluginInfo( QObject* parent = 0 );\n\n    Version version() const;\n    QString name() const;\n\n    QString displayName() const;\n    QString processName() const;\n\n    QString id() const;\n    BootstrapType bootstrapType() const;\n\n    bool isAppInstalled() const;\n    QString pluginInstallPath() const;\n    QString pluginInstaller() const;\n};\n\n}\n\n#endif //WMP_PLUGIN_INFO_H_\n\n"
  },
  {
    "path": "lib/unicorn/qrc/unicorn.qrc",
    "content": "<RCC/>\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlocalpeer.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include \"qtlocalpeer.h\"\r\n#include <QtCore/QCoreApplication>\r\n#include <QtCore/QTime>\r\n\r\n#if defined(Q_OS_WIN)\r\n#include <QtCore/QLibrary>\r\n#include <QtCore/qt_windows.h>\r\ntypedef BOOL(WINAPI*PProcessIdToSessionId)(DWORD,DWORD*);\r\nstatic PProcessIdToSessionId pProcessIdToSessionId = 0;\r\n#endif\r\n#if defined(Q_OS_UNIX)\r\n#include <time.h>\r\n#include <unistd.h>\r\n#endif\r\n\r\nnamespace QtLP_Private {\r\n#include \"qtlockedfile.cpp\"\r\n#if defined(Q_OS_WIN)\r\n#include \"qtlockedfile_win.cpp\"\r\n#else\r\n#include \"qtlockedfile_unix.cpp\"\r\n#endif\r\n}\r\n\r\nconst char* QtLocalPeer::ack = \"ack\";\r\n\r\nQtLocalPeer::QtLocalPeer(QObject* parent, const QString &appId)\r\n    : QObject(parent), id(appId)\r\n{\r\n    QString prefix = id;\r\n    if (id.isEmpty()) {\r\n        id = QCoreApplication::applicationFilePath();\r\n#if defined(Q_OS_WIN)\r\n        id = id.toLower();\r\n#endif\r\n        prefix = id.section(QLatin1Char('/'), -1);\r\n    }\r\n    prefix.remove(QRegExp(\"[^a-zA-Z]\"));\r\n    prefix.truncate(6);\r\n\r\n    QByteArray idc = id.toUtf8();\r\n    quint16 idNum = qChecksum(idc.constData(), idc.size());\r\n    socketName = QLatin1String(\"qtsingleapp-\") + prefix\r\n                 + QLatin1Char('-') + QString::number(idNum, 16);\r\n\r\n#if defined(Q_OS_WIN)\r\n    if (!pProcessIdToSessionId) {\r\n        QLibrary lib(\"kernel32\");\r\n        pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve(\"ProcessIdToSessionId\");\r\n    }\r\n    if (pProcessIdToSessionId) {\r\n        DWORD sessionId = 0;\r\n        pProcessIdToSessionId(GetCurrentProcessId(), &sessionId);\r\n        socketName += QLatin1Char('-') + QString::number(sessionId, 16);\r\n    }\r\n#else\r\n    socketName += QLatin1Char('-') + QString::number(::getuid(), 16);\r\n#endif\r\n\r\n    server = new QLocalServer(this);\r\n    QString lockName = QDir(QDir::tempPath()).absolutePath()\r\n                       + QLatin1Char('/') + socketName\r\n                       + QLatin1String(\"-lockfile\");\r\n    lockFile.setFileName(lockName);\r\n    lockFile.open(QIODevice::ReadWrite);\r\n}\r\n\r\n\r\n\r\nbool QtLocalPeer::isClient()\r\n{\r\n    if (lockFile.isLocked())\r\n        return false;\r\n\r\n    if (!lockFile.lock(QtLP_Private::QtLockedFile::WriteLock, false))\r\n        return true;\r\n\r\n    bool res = server->listen(socketName);\r\n#if defined(Q_OS_UNIX) && (QT_VERSION >= QT_VERSION_CHECK(4,5,0))\r\n    // ### Workaround\r\n    if (!res && server->serverError() == QAbstractSocket::AddressInUseError) {\r\n        QFile::remove(QDir::cleanPath(QDir::tempPath())+QLatin1Char('/')+socketName);\r\n        res = server->listen(socketName);\r\n    }\r\n#endif\r\n    if (!res)\r\n        qWarning(\"QtSingleCoreApplication: listen on local socket failed, %s\", qPrintable(server->errorString()));\r\n    QObject::connect(server, SIGNAL(newConnection()), SLOT(receiveConnection()));\r\n    return false;\r\n}\r\n\r\n\r\nbool QtLocalPeer::sendMessage(const QStringList &message, int timeout)\r\n{\r\n    if (!isClient())\r\n        return false;\r\n\r\n    QLocalSocket socket;\r\n    bool connOk = false;\r\n    for(int i = 0; i < 2; i++) {\r\n        // Try twice, in case the other instance is just starting up\r\n        socket.connectToServer(socketName);\r\n        connOk = socket.waitForConnected(timeout/2);\r\n        if (connOk || i)\r\n            break;\r\n        int ms = 250;\r\n#if defined(Q_OS_WIN)\r\n        Sleep(DWORD(ms));\r\n#else\r\n        struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };\r\n        nanosleep(&ts, NULL);\r\n#endif\r\n    }\r\n    if (!connOk)\r\n        return false;\r\n\r\n    QDataStream ds(&socket);\r\n    ds << message;\r\n    bool res = socket.waitForBytesWritten(timeout);\r\n    res &= socket.waitForReadyRead(timeout);   // wait for ack\r\n    res &= (socket.read(qstrlen(ack)) == ack);\r\n    return res;\r\n}\r\n\r\n\r\nvoid QtLocalPeer::receiveConnection()\r\n{\r\n    QLocalSocket* socket = server->nextPendingConnection();\r\n    if (!socket)\r\n        return;\r\n\r\n    while (socket->bytesAvailable() < (int)sizeof(quint32))\r\n        socket->waitForReadyRead();\r\n    QDataStream ds(socket);\r\n    QStringList message;\r\n    ds >> message;\r\n    socket->write(ack, qstrlen(ack));\r\n    socket->waitForBytesWritten(1000);\r\n    delete socket;\r\n    emit messageReceived(message); //### (might take a long time to return)\r\n}\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlocalpeer.h",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include <QtNetwork/QLocalServer>\r\n#include <QtNetwork/QLocalSocket>\r\n#include <QtCore/QDir>\r\n\r\nnamespace QtLP_Private {\r\n#include \"qtlockedfile.h\"\r\n}\r\n\r\nclass QtLocalPeer : public QObject\r\n{\r\n    Q_OBJECT\r\n\r\npublic:\r\n    QtLocalPeer(QObject *parent = 0, const QString &appId = QString());\r\n    bool isClient();\r\n    bool sendMessage(const QStringList &message, int timeout);\r\n    QString applicationId() const\r\n        { return id; }\r\n\r\nQ_SIGNALS:\r\n    void messageReceived(const QStringList &message);\r\n\r\nprotected Q_SLOTS:\r\n    void receiveConnection();\r\n\r\nprotected:\r\n    QString id;\r\n    QString socketName;\r\n    QLocalServer* server;\r\n    QtLP_Private::QtLockedFile lockFile;\r\n\r\nprivate:\r\n    static const char* ack;\r\n};\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlockedfile.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n#include \"qtlockedfile.h\"\r\n\r\n/*!\r\n    \\class QtLockedFile\r\n\r\n    \\brief The QtLockedFile class extends QFile with advisory locking\r\n    functions.\r\n\r\n    A file may be locked in read or write mode. Multiple instances of\r\n    \\e QtLockedFile, created in multiple processes running on the same\r\n    machine, may have a file locked in read mode. Exactly one instance\r\n    may have it locked in write mode. A read and a write lock cannot\r\n    exist simultaneously on the same file.\r\n\r\n    The file locks are advisory. This means that nothing prevents\r\n    another process from manipulating a locked file using QFile or\r\n    file system functions offered by the OS. Serialization is only\r\n    guaranteed if all processes that access the file use\r\n    QLockedFile. Also, while holding a lock on a file, a process\r\n    must not open the same file again (through any API), or locks\r\n    can be unexpectedly lost.\r\n\r\n    The lock provided by an instance of \\e QtLockedFile is released\r\n    whenever the program terminates. This is true even when the\r\n    program crashes and no destructors are called.\r\n*/\r\n\r\n/*! \\enum QtLockedFile::LockMode\r\n\r\n    This enum describes the available lock modes.\r\n\r\n    \\value ReadLock A read lock.\r\n    \\value WriteLock A write lock.\r\n    \\value NoLock Neither a read lock nor a write lock.\r\n*/\r\n\r\n/*!\r\n    Constructs an unlocked \\e QtLockedFile object. This constructor\r\n    behaves in the same way as \\e QFile::QFile().\r\n\r\n    \\sa QFile::QFile()\r\n*/\r\nQtLockedFile::QtLockedFile()\r\n    : QFile()\r\n{\r\n#ifdef Q_OS_WIN\r\n    wmutex = 0;\r\n    rmutex = 0;\r\n#endif\r\n    m_lock_mode = NoLock;\r\n}\r\n\r\n/*!\r\n    Constructs an unlocked QtLockedFile object with file \\a name. This\r\n    constructor behaves in the same way as \\e QFile::QFile(const\r\n    QString&).\r\n\r\n    \\sa QFile::QFile()\r\n*/\r\nQtLockedFile::QtLockedFile(const QString &name)\r\n    : QFile(name)\r\n{\r\n#ifdef Q_OS_WIN\r\n    wmutex = 0;\r\n    rmutex = 0;\r\n#endif\r\n    m_lock_mode = NoLock;\r\n}\r\n\r\n/*!\r\n  Opens the file in OpenMode \\a mode.\r\n\r\n  This is identical to QFile::open(), with the one exception that the\r\n  Truncate mode flag is disallowed. Truncation would conflict with the\r\n  advisory file locking, since the file would be modified before the\r\n  write lock is obtained. If truncation is required, use resize(0)\r\n  after obtaining the write lock.\r\n\r\n  Returns true if successful; otherwise false.\r\n\r\n  \\sa QFile::open(), QFile::resize()\r\n*/\r\nbool QtLockedFile::open(OpenMode mode)\r\n{\r\n    if (mode & QIODevice::Truncate) {\r\n        qWarning(\"QtLockedFile::open(): Truncate mode not allowed.\");\r\n        return false;\r\n    }\r\n    return QFile::open(mode);\r\n}\r\n\r\n/*!\r\n    Returns \\e true if this object has a in read or write lock;\r\n    otherwise returns \\e false.\r\n\r\n    \\sa lockMode()\r\n*/\r\nbool QtLockedFile::isLocked() const\r\n{\r\n    return m_lock_mode != NoLock;\r\n}\r\n\r\n/*!\r\n    Returns the type of lock currently held by this object, or \\e\r\n    QtLockedFile::NoLock.\r\n\r\n    \\sa isLocked()\r\n*/\r\nQtLockedFile::LockMode QtLockedFile::lockMode() const\r\n{\r\n    return m_lock_mode;\r\n}\r\n\r\n/*!\r\n    \\fn bool QtLockedFile::lock(LockMode mode, bool block = true)\r\n\r\n    Obtains a lock of type \\a mode. The file must be opened before it\r\n    can be locked.\r\n\r\n    If \\a block is true, this function will block until the lock is\r\n    aquired. If \\a block is false, this function returns \\e false\r\n    immediately if the lock cannot be aquired.\r\n\r\n    If this object already has a lock of type \\a mode, this function\r\n    returns \\e true immediately. If this object has a lock of a\r\n    different type than \\a mode, the lock is first released and then a\r\n    new lock is obtained.\r\n\r\n    This function returns \\e true if, after it executes, the file is\r\n    locked by this object, and \\e false otherwise.\r\n\r\n    \\sa unlock(), isLocked(), lockMode()\r\n*/\r\n\r\n/*!\r\n    \\fn bool QtLockedFile::unlock()\r\n\r\n    Releases a lock.\r\n\r\n    If the object has no lock, this function returns immediately.\r\n\r\n    This function returns \\e true if, after it executes, the file is\r\n    not locked by this object, and \\e false otherwise.\r\n\r\n    \\sa lock(), isLocked(), lockMode()\r\n*/\r\n\r\n/*!\r\n    \\fn QtLockedFile::~QtLockedFile()\r\n\r\n    Destroys the \\e QtLockedFile object. If any locks were held, they\r\n    are released.\r\n*/\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlockedfile.h",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n#ifndef QTLOCKEDFILE_H\r\n#define QTLOCKEDFILE_H\r\n\r\n#include <QtCore/QFile>\r\n#ifdef Q_OS_WIN\r\n#include <QtCore/QVector>\r\n#endif\r\n\r\n#if defined(Q_WS_WIN)\r\n#  if !defined(QT_QTLOCKEDFILE_EXPORT) && !defined(QT_QTLOCKEDFILE_IMPORT)\r\n#    define QT_QTLOCKEDFILE_EXPORT\r\n#  elif defined(QT_QTLOCKEDFILE_IMPORT)\r\n#    if defined(QT_QTLOCKEDFILE_EXPORT)\r\n#      undef QT_QTLOCKEDFILE_EXPORT\r\n#    endif\r\n#    define QT_QTLOCKEDFILE_EXPORT __declspec(dllimport)\r\n#  elif defined(QT_QTLOCKEDFILE_EXPORT)\r\n#    undef QT_QTLOCKEDFILE_EXPORT\r\n#    define QT_QTLOCKEDFILE_EXPORT __declspec(dllexport)\r\n#  endif\r\n#else\r\n#  define QT_QTLOCKEDFILE_EXPORT\r\n#endif\r\n\r\nclass QT_QTLOCKEDFILE_EXPORT QtLockedFile : public QFile\r\n{\r\npublic:\r\n    enum LockMode { NoLock = 0, ReadLock, WriteLock };\r\n\r\n    QtLockedFile();\r\n    QtLockedFile(const QString &name);\r\n    ~QtLockedFile();\r\n\r\n    bool open(OpenMode mode);\r\n\r\n    bool lock(LockMode mode, bool block = true);\r\n    bool unlock();\r\n    bool isLocked() const;\r\n    LockMode lockMode() const;\r\n\r\nprivate:\r\n#ifdef Q_OS_WIN\r\n    Qt::HANDLE wmutex;\r\n    Qt::HANDLE rmutex;\r\n    QVector<Qt::HANDLE> rmutexes;\r\n    QString mutexname;\r\n\r\n    Qt::HANDLE getMutexHandle(int idx, bool doCreate);\r\n    bool waitMutex(Qt::HANDLE mutex, bool doBlock);\r\n\r\n#endif\r\n    LockMode m_lock_mode;\r\n};\r\n\r\n#endif\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlockedfile_unix.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n#include <string.h>\r\n#include <errno.h>\r\n#include <unistd.h>\r\n#include <fcntl.h>\r\n\r\n#include \"qtlockedfile.h\"\r\n\r\nbool QtLockedFile::lock(LockMode mode, bool block)\r\n{\r\n    if (!isOpen()) {\r\n        qWarning(\"QtLockedFile::lock(): file is not opened\");\r\n        return false;\r\n    }\r\n \r\n    if (mode == NoLock)\r\n        return unlock();\r\n           \r\n    if (mode == m_lock_mode)\r\n        return true;\r\n\r\n    if (m_lock_mode != NoLock)\r\n        unlock();\r\n\r\n    struct flock fl;\r\n    fl.l_whence = SEEK_SET;\r\n    fl.l_start = 0;\r\n    fl.l_len = 0;\r\n    fl.l_type = (mode == ReadLock) ? F_RDLCK : F_WRLCK;\r\n    int cmd = block ? F_SETLKW : F_SETLK;\r\n    int ret = fcntl(handle(), cmd, &fl);\r\n    \r\n    if (ret == -1) {\r\n        if (errno != EINTR && errno != EAGAIN)\r\n            qWarning(\"QtLockedFile::lock(): fcntl: %s\", strerror(errno));\r\n        return false;\r\n    }\r\n\r\n    \r\n    m_lock_mode = mode;\r\n    return true;\r\n}\r\n\r\n\r\nbool QtLockedFile::unlock()\r\n{\r\n    if (!isOpen()) {\r\n        qWarning(\"QtLockedFile::unlock(): file is not opened\");\r\n        return false;\r\n    }\r\n\r\n    if (!isLocked())\r\n        return true;\r\n\r\n    struct flock fl;\r\n    fl.l_whence = SEEK_SET;\r\n    fl.l_start = 0;\r\n    fl.l_len = 0;\r\n    fl.l_type = F_UNLCK;\r\n    int ret = fcntl(handle(), F_SETLKW, &fl);\r\n    \r\n    if (ret == -1) {\r\n        qWarning(\"QtLockedFile::lock(): fcntl: %s\", strerror(errno));\r\n        return false;\r\n    }\r\n    \r\n    m_lock_mode = NoLock;\r\n    return true;\r\n}\r\n\r\nQtLockedFile::~QtLockedFile()\r\n{\r\n    if (isOpen())\r\n        unlock();\r\n}\r\n\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtlockedfile_win.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n#include \"qtlockedfile.h\"\r\n#include <qt_windows.h>\r\n#include <QtCore/QFileInfo>\r\n\r\n#define MUTEX_PREFIX \"QtLockedFile mutex \"\r\n// Maximum number of concurrent read locks. Must not be greater than MAXIMUM_WAIT_OBJECTS\r\n#define MAX_READERS MAXIMUM_WAIT_OBJECTS\r\n\r\nQt::HANDLE QtLockedFile::getMutexHandle(int idx, bool doCreate)\r\n{\r\n    if (mutexname.isEmpty()) {\r\n        QFileInfo fi(*this);\r\n        mutexname = QString::fromLatin1(MUTEX_PREFIX)\r\n                    + fi.absoluteFilePath().toLower();\r\n    }\r\n    QString mname(mutexname);\r\n    if (idx >= 0)\r\n        mname += QString::number(idx);\r\n\r\n    Qt::HANDLE mutex;\r\n    if (doCreate) {\r\n        QT_WA( { mutex = CreateMutexW(NULL, FALSE, (TCHAR*)mname.utf16()); },\r\n               { mutex = CreateMutexA(NULL, FALSE, mname.toLocal8Bit().constData()); } );\r\n        if (!mutex) {\r\n            qErrnoWarning(\"QtLockedFile::lock(): CreateMutex failed\");\r\n            return 0;\r\n        }\r\n    }\r\n    else {\r\n        QT_WA( { mutex = OpenMutexW(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, (TCHAR*)mname.utf16()); },\r\n               { mutex = OpenMutexA(SYNCHRONIZE | MUTEX_MODIFY_STATE, FALSE, mname.toLocal8Bit().constData()); } );\r\n        if (!mutex) {\r\n            if (GetLastError() != ERROR_FILE_NOT_FOUND)\r\n                qErrnoWarning(\"QtLockedFile::lock(): OpenMutex failed\");\r\n            return 0;\r\n        }\r\n    }\r\n    return mutex;\r\n}\r\n\r\nbool QtLockedFile::waitMutex(Qt::HANDLE mutex, bool doBlock)\r\n{\r\n    Q_ASSERT(mutex);\r\n    DWORD res = WaitForSingleObject(mutex, doBlock ? INFINITE : 0);\r\n    switch (res) {\r\n    case WAIT_OBJECT_0:\r\n    case WAIT_ABANDONED:\r\n        return true;\r\n        break;\r\n    case WAIT_TIMEOUT:\r\n        break;\r\n    default:\r\n        qErrnoWarning(\"QtLockedFile::lock(): WaitForSingleObject failed\");\r\n    }\r\n    return false;\r\n}\r\n\r\n\r\n\r\nbool QtLockedFile::lock(LockMode mode, bool block)\r\n{\r\n    if (!isOpen()) {\r\n        qWarning(\"QtLockedFile::lock(): file is not opened\");\r\n        return false;\r\n    }\r\n\r\n    if (mode == NoLock)\r\n        return unlock();\r\n\r\n    if (mode == m_lock_mode)\r\n        return true;\r\n\r\n    if (m_lock_mode != NoLock)\r\n        unlock();\r\n\r\n    if (!wmutex && !(wmutex = getMutexHandle(-1, true)))\r\n        return false;\r\n\r\n    if (!waitMutex(wmutex, block))\r\n        return false;\r\n\r\n    if (mode == ReadLock) {\r\n        int idx = 0;\r\n        for (; idx < MAX_READERS; idx++) {\r\n            rmutex = getMutexHandle(idx, false);\r\n            if (!rmutex || waitMutex(rmutex, false))\r\n                break;\r\n            CloseHandle(rmutex);\r\n        }\r\n        bool ok = true;\r\n        if (idx >= MAX_READERS) {\r\n            qWarning(\"QtLockedFile::lock(): too many readers\");\r\n            rmutex = 0;\r\n            ok = false;\r\n        }\r\n        else if (!rmutex) {\r\n            rmutex = getMutexHandle(idx, true);\r\n            if (!rmutex || !waitMutex(rmutex, false))\r\n                ok = false;\r\n        }\r\n        if (!ok && rmutex) {\r\n            CloseHandle(rmutex);\r\n            rmutex = 0;\r\n        }\r\n        ReleaseMutex(wmutex);\r\n        if (!ok)\r\n            return false;\r\n    }\r\n    else {\r\n        Q_ASSERT(rmutexes.isEmpty());\r\n        for (int i = 0; i < MAX_READERS; i++) {\r\n            Qt::HANDLE mutex = getMutexHandle(i, false);\r\n            if (mutex)\r\n                rmutexes.append(mutex);\r\n        }\r\n        if (rmutexes.size()) {\r\n            DWORD res = WaitForMultipleObjects(rmutexes.size(), rmutexes.constData(),\r\n                                               TRUE, block ? INFINITE : 0);\r\n            if (res != WAIT_OBJECT_0 && res != WAIT_ABANDONED) {\r\n                if (res != WAIT_TIMEOUT)\r\n                    qErrnoWarning(\"QtLockedFile::lock(): WaitForMultipleObjects failed\");\r\n                m_lock_mode = WriteLock;  // trick unlock() to clean up - semiyucky\r\n                unlock();\r\n                return false;\r\n            }\r\n        }\r\n    }\r\n\r\n    m_lock_mode = mode;\r\n    return true;\r\n}\r\n\r\nbool QtLockedFile::unlock()\r\n{\r\n    if (!isOpen()) {\r\n        qWarning(\"QtLockedFile::unlock(): file is not opened\");\r\n        return false;\r\n    }\r\n\r\n    if (!isLocked())\r\n        return true;\r\n\r\n    if (m_lock_mode == ReadLock) {\r\n        ReleaseMutex(rmutex);\r\n        CloseHandle(rmutex);\r\n        rmutex = 0;\r\n    }\r\n    else {\r\n        foreach(Qt::HANDLE mutex, rmutexes) {\r\n            ReleaseMutex(mutex);\r\n            CloseHandle(mutex);\r\n        }\r\n        rmutexes.clear();\r\n        ReleaseMutex(wmutex);\r\n    }\r\n\r\n    m_lock_mode = QtLockedFile::NoLock;\r\n    return true;\r\n}\r\n\r\nQtLockedFile::~QtLockedFile()\r\n{\r\n    if (isOpen())\r\n        unlock();\r\n    if (wmutex)\r\n        CloseHandle(wmutex);\r\n}\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtsingleapplication.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include \"qtsingleapplication.h\"\r\n#include \"qtlocalpeer.h\"\r\n#include <QtGui/QWidget>\r\n\r\n\r\n/*!\r\n    \\class QtSingleApplication qtsingleapplication.h\r\n    \\brief The QtSingleApplication class provides an API to detect and\r\n    communicate with running instances of an application.\r\n\r\n    This class allows you to create applications where only one\r\n    instance should be running at a time. I.e., if the user tries to\r\n    launch another instance, the already running instance will be\r\n    activated instead. Another usecase is a client-server system,\r\n    where the first started instance will assume the role of server,\r\n    and the later instances will act as clients of that server.\r\n\r\n    By default, the full path of the executable file is used to\r\n    determine whether two processes are instances of the same\r\n    application. You can also provide an explicit identifier string\r\n    that will be compared instead.\r\n\r\n    The application should create the QtSingleApplication object early\r\n    in the startup phase, and call isRunning() or sendMessage() to\r\n    find out if another instance of this application is already\r\n    running. Startup parameters (e.g. the name of the file the user\r\n    wanted this new instance to open) can be passed to the running\r\n    instance in the sendMessage() function.\r\n\r\n    If isRunning() or sendMessage() returns false, it means that no\r\n    other instance is running, and this instance has assumed the role\r\n    as the running instance. The application should continue with the\r\n    initialization of the application user interface before entering\r\n    the event loop with exec(), as normal. The messageReceived()\r\n    signal will be emitted when the application receives messages from\r\n    another instance of the same application.\r\n\r\n    If isRunning() or sendMessage() returns true, another instance is\r\n    already running, and the application should terminate or enter\r\n    client mode.\r\n\r\n    If a message is received it might be helpful to the user to raise\r\n    the application so that it becomes visible. To facilitate this,\r\n    QtSingleApplication provides the setActivationWindow() function\r\n    and the activateWindow() slot.\r\n\r\n    Here's an example that shows how to convert an existing\r\n    application to use QtSingleApplication. It is very simple and does\r\n    not make use of all QtSingleApplication's functionality (see the\r\n    examples for that).\r\n\r\n    \\code\r\n    // Original\r\n    int main(int argc, char **argv)\r\n    {\r\n        QApplication app(argc, argv);\r\n\r\n        MyMainWidget mmw;\r\n\r\n        mmw.show();\r\n        return app.exec();\r\n    }\r\n\r\n    // Single instance\r\n    int main(int argc, char **argv)\r\n    {\r\n        QtSingleApplication app(argc, argv);\r\n\r\n        if (app.isRunning())\r\n            return 0;\r\n\r\n        MyMainWidget mmw;\r\n\r\n        app.setActivationWindow(&mmw);\r\n\r\n        mmw.show();\r\n        return app.exec();\r\n    }\r\n    \\endcode\r\n\r\n    Once this QtSingleApplication instance is destroyed(for example,\r\n    when the user quits), when the user next attempts to run the\r\n    application this instance will not, of course, be encountered. The\r\n    next instance to call isRunning() or sendMessage() will assume the\r\n    role as the new running instance.\r\n\r\n    For console (non-GUI) applications, QtSingleCoreApplication may be\r\n    used instead of this class, to avoid the dependency on the QtGui\r\n    library.\r\n\r\n    \\sa QtSingleCoreApplication\r\n*/\r\n\r\n\r\nvoid QtSingleApplication::sysInit(const QString &appId)\r\n{\r\n    actWin = 0;\r\n    peer = new QtLocalPeer(this, appId);\r\n    connect(peer, SIGNAL(messageReceived(const QStringList&)), SIGNAL(messageReceived(const QStringList&)));\r\n}\r\n\r\n\r\n/*!\r\n    Creates a QtSingleApplication object. The application identifier\r\n    will be QCoreApplication::applicationFilePath(). \\a argc, \\a\r\n    argv, and \\a GUIenabled are passed on to the QAppliation constructor.\r\n\r\n    If you are creating a console application (i.e. setting \\a\r\n    GUIenabled to false), you may consider using\r\n    QtSingleCoreApplication instead.\r\n*/\r\n\r\nQtSingleApplication::QtSingleApplication(int &argc, char **argv, bool GUIenabled)\r\n    : QApplication(argc, argv, GUIenabled)\r\n{\r\n    sysInit();\r\n}\r\n\r\n\r\n/*!\r\n    Creates a QtSingleApplication object with the application\r\n    identifier \\a appId. \\a argc and \\a argv are passed on to the\r\n    QAppliation constructor.\r\n*/\r\n\r\nQtSingleApplication::QtSingleApplication(const QString &appId, int &argc, char **argv)\r\n    : QApplication(argc, argv)\r\n{\r\n    sysInit(appId);\r\n}\r\n\r\n\r\n/*!\r\n    Creates a QtSingleApplication object. The application identifier\r\n    will be QCoreApplication::applicationFilePath(). \\a argc, \\a\r\n    argv, and \\a type are passed on to the QAppliation constructor.\r\n*/\r\nQtSingleApplication::QtSingleApplication(int &argc, char **argv, Type type)\r\n    : QApplication(argc, argv, type)\r\n{\r\n    sysInit();\r\n}\r\n\r\n\r\n#if defined(Q_WS_X11)\r\n/*!\r\n  Special constructor for X11, ref. the documentation of\r\n  QApplication's corresponding constructor. The application identifier\r\n  will be QCoreApplication::applicationFilePath(). \\a dpy, \\a visual,\r\n  and \\a cmap are passed on to the QApplication constructor.\r\n*/\r\nQtSingleApplication::QtSingleApplication(Display* dpy, Qt::HANDLE visual, Qt::HANDLE cmap)\r\n    : QApplication(dpy, visual, cmap)\r\n{\r\n    sysInit();\r\n}\r\n\r\n/*!\r\n  Special constructor for X11, ref. the documentation of\r\n  QApplication's corresponding constructor. The application identifier\r\n  will be QCoreApplication::applicationFilePath(). \\a dpy, \\a argc, \\a\r\n  argv, \\a visual, and \\a cmap are passed on to the QApplication\r\n  constructor.\r\n*/\r\nQtSingleApplication::QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)\r\n    : QApplication(dpy, argc, argv, visual, cmap)\r\n{\r\n    sysInit();\r\n}\r\n\r\n/*!\r\n  Special constructor for X11, ref. the documentation of\r\n  QApplication's corresponding constructor. The application identifier\r\n  will be \\a appId. \\a dpy, \\a argc, \\a\r\n  argv, \\a visual, and \\a cmap are passed on to the QApplication\r\n  constructor.\r\n*/\r\nQtSingleApplication::QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual, Qt::HANDLE cmap)\r\n    : QApplication(dpy, argc, argv, visual, cmap)\r\n{\r\n    sysInit(appId);\r\n}\r\n#endif\r\n\r\n\r\n/*!\r\n    Returns true if another instance of this application is running;\r\n    otherwise false.\r\n\r\n    This function does not find instances of this application that are\r\n    being run by a different user (on Windows: that are running in\r\n    another session).\r\n\r\n    \\sa sendMessage()\r\n*/\r\n\r\nbool QtSingleApplication::isRunning()\r\n{\r\n    return peer->isClient();\r\n}\r\n\r\n\r\n/*!\r\n    Tries to send the text \\a message to the currently running\r\n    instance. The QtSingleApplication object in the running instance\r\n    will emit the messageReceived() signal when it receives the\r\n    message.\r\n\r\n    This function returns true if the message has been sent to, and\r\n    processed by, the current instance. If there is no instance\r\n    currently running, or if the running instance fails to process the\r\n    message within \\a timeout milliseconds, this function return false.\r\n\r\n    \\sa isRunning(), messageReceived()\r\n*/\r\nbool QtSingleApplication::sendMessage(const QStringList &message, int timeout)\r\n{\r\n    return peer->sendMessage(message, timeout);\r\n}\r\n\r\n\r\n/*!\r\n    Returns the application identifier. Two processes with the same\r\n    identifier will be regarded as instances of the same application.\r\n*/\r\nQString QtSingleApplication::id() const\r\n{\r\n    return peer->applicationId();\r\n}\r\n\r\n\r\n/*!\r\n  Sets the activation window of this application to \\a aw. The\r\n  activation window is the widget that will be activated by\r\n  activateWindow(). This is typically the application's main window.\r\n\r\n  If \\a activateOnMessage is true (the default), the window will be\r\n  activated automatically every time a message is received, just prior\r\n  to the messageReceived() signal being emitted.\r\n\r\n  \\sa activateWindow(), messageReceived()\r\n*/\r\n\r\nvoid QtSingleApplication::setActivationWindow(QWidget* aw, bool activateOnMessage)\r\n{\r\n    actWin = aw;\r\n    if (activateOnMessage)\r\n        connect(peer, SIGNAL(messageReceived(const QStringList&)), this, SLOT(activateWindow()));\r\n    else\r\n        disconnect(peer, SIGNAL(messageReceived(const QStringList&)), this, SLOT(activateWindow()));\r\n}\r\n\r\n\r\n/*!\r\n    Returns the applications activation window if one has been set by\r\n    calling setActivationWindow(), otherwise returns 0.\r\n\r\n    \\sa setActivationWindow()\r\n*/\r\nQWidget* QtSingleApplication::activationWindow() const\r\n{\r\n    return actWin;\r\n}\r\n\r\n\r\n/*!\r\n  De-minimizes, raises, and activates this application's activation window.\r\n  This function does nothing if no activation window has been set.\r\n\r\n  This is a convenience function to show the user that this\r\n  application instance has been activated when he has tried to start\r\n  another instance.\r\n\r\n  This function should typically be called in response to the\r\n  messageReceived() signal. By default, that will happen\r\n  automatically, if an activation window has been set.\r\n\r\n  \\sa setActivationWindow(), messageReceived(), initialize()\r\n*/\r\nvoid QtSingleApplication::activateWindow()\r\n{\r\n    if (actWin) {\r\n        actWin->setWindowState(actWin->windowState() & ~Qt::WindowMinimized);\r\n        actWin->raise();\r\n        actWin->activateWindow();\r\n    }\r\n}\r\n\r\n\r\n/*!\r\n    \\fn void QtSingleApplication::messageReceived(const QString& message)\r\n\r\n    This signal is emitted when the current instance receives a \\a\r\n    message from another instance of this application.\r\n\r\n    \\sa sendMessage(), setActivationWindow(), activateWindow()\r\n*/\r\n\r\n\r\n/*!\r\n    \\fn void QtSingleApplication::initialize(bool dummy = true)\r\n\r\n    \\obsolete\r\n*/\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtsingleapplication.h",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include <QtGui/QApplication>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nclass QtLocalPeer;\r\n\r\nclass UNICORN_DLLEXPORT QtSingleApplication : public QApplication\r\n{\r\n    Q_OBJECT\r\n\r\npublic:\r\n    QtSingleApplication(int &argc, char **argv, bool GUIenabled = true);\r\n    QtSingleApplication(const QString &id, int &argc, char **argv);\r\n    QtSingleApplication(int &argc, char **argv, Type type);\r\n#if defined(Q_WS_X11)\r\n    QtSingleApplication(Display* dpy, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);\r\n    QtSingleApplication(Display *dpy, int &argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE cmap= 0);\r\n    QtSingleApplication(Display* dpy, const QString &appId, int argc, char **argv, Qt::HANDLE visual = 0, Qt::HANDLE colormap = 0);\r\n#endif\r\n\r\n    bool isRunning();\r\n    QString id() const;\r\n\r\n    void setActivationWindow(QWidget* aw, bool activateOnMessage = true);\r\n    QWidget* activationWindow() const;\r\n\r\n    // Obsolete:\r\n    void initialize(bool dummy = true)\r\n        { isRunning(); Q_UNUSED(dummy) }\r\n\r\npublic Q_SLOTS:\r\n    bool sendMessage(const QStringList &message, int timeout = 5000);\r\n    void activateWindow();\r\n\r\n\r\nQ_SIGNALS:\r\n    void messageReceived(const QStringList &message);\r\n\r\n\r\nprivate:\r\n    void sysInit(const QString &appId = QString());\r\n    QtLocalPeer *peer;\r\n    QWidget *actWin;\r\n};\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtsinglecoreapplication.cpp",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include \"qtsinglecoreapplication.h\"\r\n#include \"qtlocalpeer.h\"\r\n\r\n/*!\r\n    \\class QtSingleCoreApplication qtsinglecoreapplication.h\r\n    \\brief A variant of the QtSingleApplication class for non-GUI applications.\r\n\r\n    This class is a variant of QtSingleApplication suited for use in\r\n    console (non-GUI) applications. It is an extension of\r\n    QCoreApplication (instead of QApplication). It does not require\r\n    the QtGui library.\r\n\r\n    The API and usage is identical to QtSingleApplication, except that\r\n    functions relating to the \"activation window\" are not present, for\r\n    obvious reasons. Please refer to the QtSingleApplication\r\n    documentation for explanation of the usage.\r\n\r\n    A QtSingleCoreApplication instance can communicate to a\r\n    QtSingleApplication instance if they share the same application\r\n    id. Hence, this class can be used to create a light-weight\r\n    command-line tool that sends commands to a GUI application.\r\n\r\n    \\sa QtSingleApplication\r\n*/\r\n\r\n/*!\r\n    Creates a QtSingleCoreApplication object. The application identifier\r\n    will be QCoreApplication::applicationFilePath(). \\a argc and \\a\r\n    argv are passed on to the QCoreAppliation constructor.\r\n*/\r\n\r\nQtSingleCoreApplication::QtSingleCoreApplication(int &argc, char **argv)\r\n    : QCoreApplication(argc, argv)\r\n{\r\n    peer = new QtLocalPeer(this);\r\n    connect(peer, SIGNAL(messageReceived(const QStringList&)), SIGNAL(messageReceived(const QStringList&)));\r\n}\r\n\r\n\r\n/*!\r\n    Creates a QtSingleCoreApplication object with the application\r\n    identifier \\a appId. \\a argc and \\a argv are passed on to the\r\n    QCoreAppliation constructor.\r\n*/\r\nQtSingleCoreApplication::QtSingleCoreApplication(const QString &appId, int &argc, char **argv)\r\n    : QCoreApplication(argc, argv)\r\n{\r\n    peer = new QtLocalPeer(this, appId);\r\n    connect(peer, SIGNAL(messageReceived(const QStringList&)), SIGNAL(messageReceived(const QStringList&)));\r\n}\r\n\r\n\r\n/*!\r\n    Returns true if another instance of this application is running;\r\n    otherwise false.\r\n\r\n    This function does not find instances of this application that are\r\n    being run by a different user (on Windows: that are running in\r\n    another session).\r\n\r\n    \\sa sendMessage()\r\n*/\r\n\r\nbool QtSingleCoreApplication::isRunning()\r\n{\r\n    return peer->isClient();\r\n}\r\n\r\n\r\n/*!\r\n    Tries to send the text \\a message to the currently running\r\n    instance. The QtSingleCoreApplication object in the running instance\r\n    will emit the messageReceived() signal when it receives the\r\n    message.\r\n\r\n    This function returns true if the message has been sent to, and\r\n    processed by, the current instance. If there is no instance\r\n    currently running, or if the running instance fails to process the\r\n    message within \\a timeout milliseconds, this function return false.\r\n\r\n    \\sa isRunning(), messageReceived()\r\n*/\r\n\r\nbool QtSingleCoreApplication::sendMessage(const QStringList &message, int timeout)\r\n{\r\n    return peer->sendMessage(message, timeout);\r\n}\r\n\r\n\r\n/*!\r\n    Returns the application identifier. Two processes with the same\r\n    identifier will be regarded as instances of the same application.\r\n*/\r\n\r\nQString QtSingleCoreApplication::id() const\r\n{\r\n    return peer->applicationId();\r\n}\r\n\r\n\r\n/*!\r\n    \\fn void QtSingleCoreApplication::messageReceived(const QString& message)\r\n\r\n    This signal is emitted when the current instance receives a \\a\r\n    message from another instance of this application.\r\n\r\n    \\sa sendMessage()\r\n*/\r\n"
  },
  {
    "path": "lib/unicorn/qtsingleapplication/qtsinglecoreapplication.h",
    "content": "/****************************************************************************\r\n** \r\n** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n** All rights reserved.\r\n** Contact: Nokia Corporation (qt-info@nokia.com)\r\n** \r\n** This file is part of a Qt Solutions component.\r\n**\r\n** Commercial Usage  \r\n** Licensees holding valid Qt Commercial licenses may use this file in\r\n** accordance with the Qt Solutions Commercial License Agreement provided\r\n** with the Software or, alternatively, in accordance with the terms\r\n** contained in a written agreement between you and Nokia.\r\n** \r\n** GNU Lesser General Public License Usage\r\n** Alternatively, this file may be used under the terms of the GNU Lesser\r\n** General Public License version 2.1 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.LGPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU Lesser General Public License version 2.1 requirements\r\n** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.\r\n** \r\n** In addition, as a special exception, Nokia gives you certain\r\n** additional rights. These rights are described in the Nokia Qt LGPL\r\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\r\n** package.\r\n** \r\n** GNU General Public License Usage \r\n** Alternatively, this file may be used under the terms of the GNU\r\n** General Public License version 3.0 as published by the Free Software\r\n** Foundation and appearing in the file LICENSE.GPL included in the\r\n** packaging of this file.  Please review the following information to\r\n** ensure the GNU General Public License version 3.0 requirements will be\r\n** met: http://www.gnu.org/copyleft/gpl.html.\r\n** \r\n** Please note Third Party Software included with Qt Solutions may impose\r\n** additional restrictions and it is the user's responsibility to ensure\r\n** that they have met the licensing requirements of the GPL, LGPL, or Qt\r\n** Solutions Commercial license and the relevant license of the Third\r\n** Party Software they are using.\r\n** \r\n** If you are unsure which license is appropriate for your use, please\r\n** contact Nokia at qt-info@nokia.com.\r\n** \r\n****************************************************************************/\r\n\r\n\r\n#include <QtCore/QCoreApplication>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nclass QtLocalPeer;\r\n\r\nclass UNICORN_DLLEXPORT QtSingleCoreApplication : public QCoreApplication\r\n{\r\n    Q_OBJECT\r\n\r\npublic:\r\n    QtSingleCoreApplication(int &argc, char **argv);\r\n    QtSingleCoreApplication(const QString &id, int &argc, char **argv);\r\n\r\n    bool isRunning();\r\n    QString id() const;\r\n\r\npublic Q_SLOTS:\r\n    bool sendMessage(const QStringList &message, int timeout = 5000);\r\n\r\n\r\nQ_SIGNALS:\r\n    void messageReceived(const QStringList &message);\r\n\r\n\r\nprivate:\r\n    QtLocalPeer* peer;\r\n};\r\n"
  },
  {
    "path": "lib/unicorn/qtwin.cpp",
    "content": "/****************************************************************************\r\n**\r\n** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n**\r\n** Use, modification and distribution is allowed without limitation,\r\n** warranty, liability or support of any kind.\r\n**\r\n****************************************************************************/\r\n\r\n#include \"qtwin.h\"\r\n#include <QLibrary>\r\n#include <QApplication>\r\n#include <QWidget>\r\n#include <QList>\r\n#include <QPointer>\r\n\r\n#ifdef Q_WS_WIN\r\n\r\n#include <qt_windows.h>\r\n\r\n// Blur behind data structures\r\n#define DWM_BB_ENABLE                 0x00000001  // fEnable has been specified\r\n#define DWM_BB_BLURREGION             0x00000002  // hRgnBlur has been specified\r\n#define DWM_BB_TRANSITIONONMAXIMIZED  0x00000004  // fTransitionOnMaximized has been specified\r\n#define WM_DWMCOMPOSITIONCHANGED        0x031E    // Composition changed window message\r\n\r\ntypedef struct _DWM_BLURBEHIND\r\n{\r\n    DWORD dwFlags;\r\n    BOOL fEnable;\r\n    HRGN hRgnBlur;\r\n    BOOL fTransitionOnMaximized;\r\n} DWM_BLURBEHIND, *PDWM_BLURBEHIND;\r\n\r\ntypedef struct _MARGINS\r\n{\r\n    int cxLeftWidth;\r\n    int cxRightWidth;\r\n    int cyTopHeight;\r\n    int cyBottomHeight;\r\n} MARGINS, *PMARGINS;\r\n\r\ntypedef HRESULT (WINAPI *PtrDwmIsCompositionEnabled)(BOOL* pfEnabled);\r\ntypedef HRESULT (WINAPI *PtrDwmExtendFrameIntoClientArea)(HWND hWnd, const MARGINS* pMarInset);\r\ntypedef HRESULT (WINAPI *PtrDwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);\r\ntypedef HRESULT (WINAPI *PtrDwmGetColorizationColor)(DWORD *pcrColorization, BOOL *pfOpaqueBlend);\r\n\r\nstatic PtrDwmIsCompositionEnabled pDwmIsCompositionEnabled= 0;\r\nstatic PtrDwmEnableBlurBehindWindow pDwmEnableBlurBehindWindow = 0;\r\nstatic PtrDwmExtendFrameIntoClientArea pDwmExtendFrameIntoClientArea = 0;\r\nstatic PtrDwmGetColorizationColor pDwmGetColorizationColor = 0;\r\n\r\n\r\n/*\r\n * Internal helper class that notifies windows if the\r\n * DWM compositing state changes and updates the widget\r\n * flags correspondingly.\r\n */\r\nclass WindowNotifier : public QWidget\r\n{\r\npublic:\r\n    WindowNotifier() { winId(); }\r\n    void addWidget(QWidget *widget) { widgets.append(widget); }\r\n    void removeWidget(QWidget *widget) { widgets.removeAll(widget); }\r\n    bool winEvent(MSG *message, long *result);\r\n\r\nprivate:\r\n    QWidgetList widgets;\r\n};\r\n\r\nstatic bool resolveLibs()\r\n{\r\n    if (!pDwmIsCompositionEnabled) {\r\n        QLibrary dwmLib(QString::fromAscii(\"dwmapi\"));\r\n        pDwmIsCompositionEnabled =(PtrDwmIsCompositionEnabled)dwmLib.resolve(\"DwmIsCompositionEnabled\");\r\n        pDwmExtendFrameIntoClientArea = (PtrDwmExtendFrameIntoClientArea)dwmLib.resolve(\"DwmExtendFrameIntoClientArea\");\r\n        pDwmEnableBlurBehindWindow = (PtrDwmEnableBlurBehindWindow)dwmLib.resolve(\"DwmEnableBlurBehindWindow\");\r\n        pDwmGetColorizationColor = (PtrDwmGetColorizationColor)dwmLib.resolve(\"DwmGetColorizationColor\");\r\n    }\r\n    return pDwmIsCompositionEnabled != 0;\r\n}\r\n\r\n#endif\r\n\r\n/*!\r\n  * Chekcs and returns true if Windows DWM composition\r\n  * is currently enabled on the system.\r\n  *\r\n  * To get live notification on the availability of\r\n  * this feature, you will currently have to\r\n  * reimplement winEvent() on your widget and listen\r\n  * for the WM_DWMCOMPOSITIONCHANGED event to occur.\r\n  *\r\n  */\r\nbool QtWin::isCompositionEnabled()\r\n{\r\n#ifdef Q_WS_WIN\r\n    if (resolveLibs()) {\r\n        HRESULT hr = S_OK;\r\n        BOOL isEnabled = false;\r\n        hr = pDwmIsCompositionEnabled(&isEnabled);\r\n        if (SUCCEEDED(hr))\r\n            return isEnabled;\r\n    }\r\n#endif\r\n    return false;\r\n}\r\n\r\n/*!\r\n  * Enables Blur behind on a Widget.\r\n  *\r\n  * \\a enable tells if the blur should be enabled or not\r\n  */\r\nbool QtWin::enableBlurBehindWindow(QWidget *widget, bool enable)\r\n{\r\n    Q_ASSERT(widget);\r\n    bool result = false;\r\n#ifdef Q_WS_WIN\r\n    if (resolveLibs()) {\r\n        DWM_BLURBEHIND bb = {0};\r\n        HRESULT hr = S_OK;\r\n        bb.fEnable = enable;\r\n        bb.dwFlags = DWM_BB_ENABLE;\r\n        bb.hRgnBlur = NULL;\r\n        widget->setAttribute(Qt::WA_TranslucentBackground, enable);\r\n        widget->setAttribute(Qt::WA_NoSystemBackground, enable);\r\n        hr = pDwmEnableBlurBehindWindow(widget->winId(), &bb);\r\n        if (SUCCEEDED(hr)) {\r\n            result = true;\r\n            windowNotifier()->addWidget(widget);\r\n        }\r\n    }\r\n#else\r\n    Q_UNUSED(enable)\r\n#endif\r\n    return result;\r\n}\r\n\r\n/*!\r\n  * ExtendFrameIntoClientArea.\r\n  *\r\n  * This controls the rendering of the frame inside the window.\r\n  * Note that passing margins of -1 (the default value) will completely\r\n  * remove the frame from the window.\r\n  *\r\n  * \\note you should not call enableBlurBehindWindow before calling\r\n  *       this functions\r\n  *\r\n  * \\a enable tells if the blur should be enabled or not\r\n  */\r\nbool QtWin::extendFrameIntoClientArea(QWidget *widget, int left, int top, int right, int bottom)\r\n{\r\n\r\n    Q_ASSERT(widget);\r\n    Q_UNUSED(left);\r\n    Q_UNUSED(top);\r\n    Q_UNUSED(right);\r\n    Q_UNUSED(bottom);\r\n\r\n    bool result = false;\r\n#ifdef Q_WS_WIN\r\n    if (resolveLibs()) {\r\n        QLibrary dwmLib(QString::fromAscii(\"dwmapi\"));\r\n        HRESULT hr = S_OK;\r\n        MARGINS m = {left, top, right, bottom};\r\n        hr = pDwmExtendFrameIntoClientArea(widget->winId(), &m);\r\n        if (SUCCEEDED(hr)) {\r\n            result = true;\r\n            windowNotifier()->addWidget(widget);\r\n        }\r\n        widget->setAttribute(Qt::WA_TranslucentBackground, result);\r\n    }\r\n#endif\r\n    return result;\r\n}\r\n\r\n/*!\r\n  * Returns the current colorizationColor for the window.\r\n  *\r\n  * \\a enable tells if the blur should be enabled or not\r\n  */\r\nQColor QtWin::colorizatinColor()\r\n{\r\n    QColor resultColor = QApplication::palette().window().color();\r\n\r\n#ifdef Q_WS_WIN\r\n    if (resolveLibs()) {\r\n        DWORD color = 0;\r\n        BOOL opaque = FALSE;\r\n        QLibrary dwmLib(QString::fromAscii(\"dwmapi\"));\r\n        HRESULT hr = S_OK;\r\n        hr = pDwmGetColorizationColor(&color, &opaque);\r\n        if (SUCCEEDED(hr))\r\n            resultColor = QColor(color);\r\n    }\r\n#endif\r\n    return resultColor;\r\n}\r\n\r\n#ifdef Q_WS_WIN\r\nWindowNotifier *QtWin::windowNotifier()\r\n{\r\n    static WindowNotifier *windowNotifierInstance = 0;\r\n    if (!windowNotifierInstance)\r\n        windowNotifierInstance = new WindowNotifier;\r\n    return windowNotifierInstance;\r\n}\r\n\r\n\r\n/* Notify all enabled windows that the DWM state changed */\r\nbool WindowNotifier::winEvent(MSG *message, long *result)\r\n{\r\n    if (message && message->message == WM_DWMCOMPOSITIONCHANGED) {\r\n        bool compositionEnabled = QtWin::isCompositionEnabled();\r\n        foreach(QWidget * widget, widgets) {\r\n            if (widget) {\r\n                widget->setAttribute(Qt::WA_NoSystemBackground, compositionEnabled);\r\n            }\r\n            widget->update();\r\n        }\r\n    }\r\n    return QWidget::winEvent(message, result);\r\n}\r\n#endif\r\n"
  },
  {
    "path": "lib/unicorn/qtwin.h",
    "content": "/****************************************************************************\r\n**\r\n** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).\r\n**\r\n** Use, modification and distribution is allowed without limitation,\r\n** warranty, liability or support of any kind.\r\n**\r\n****************************************************************************/\r\n\r\n#ifndef QTWIN_H\r\n#define QTWIN_H\r\n#include <lib/DllExportMacro.h>\r\n#include <QColor>\n#include <QWidget>\r\n/**\r\n  * This is a helper class for using the Desktop Window Manager\r\n  * functionality on Windows 7 and Windows Vista. On other platforms\r\n  * these functions will simply not do anything.\r\n  */\r\n\r\nclass WindowNotifier;\r\n\r\nclass UNICORN_DLLEXPORT QtWin\r\n{\r\npublic:\r\n    static bool enableBlurBehindWindow(QWidget *widget, bool enable = true);\r\n    static bool extendFrameIntoClientArea(QWidget *widget,\r\n                                          int left = -1, int top = -1,\r\n                                          int right = -1, int bottom = -1);\r\n    static bool isCompositionEnabled();\r\n    static QColor colorizatinColor();\r\n\r\nprivate:\r\n    static WindowNotifier *windowNotifier();\r\n};\r\n\r\n#endif // QTWIN_H\r\n"
  },
  {
    "path": "lib/unicorn/unicorn.pro",
    "content": "TARGET = unicorn\nTEMPLATE = lib\nCONFIG += dll lastfm sparkle growl logger\nunix:!mac {\n    CONFIG -= dll\n    CONFIG += staticlib\n    QMAKE_DISTCLEAN += -f ../../_bin/libunicorn.a\n}\n\nQT = core gui xml network\ninclude( ../../admin/include.qmake )\nDEFINES += _UNICORN_DLLEXPORT LASTFM_COLLAPSE_NAMESPACE\n\nDEFINES += API_KEY=\\\\\\\"$(LASTFM_API_KEY)\\\\\\\"\nDEFINES += API_SECRET=\\\\\\\"$(LASTFM_API_SECRET)\\\\\\\"\n\n# UniqueApplication\nwin32:LIBS += user32.lib shell32.lib ole32.lib kernel32.lib psapi.lib\n\nmacx:LIBS += -weak_framework Cocoa\n\nSOURCES += \\\n    dialogs/ShareDialog.cpp \\\n    widgets/AvatarWidget.cpp \\\n    layouts/FlowLayout.cpp \\\n    widgets/UserMenu.cpp \\\n    widgets/SlidingStackedWidget.cpp \\\n    widgets/UserToolButton.cpp \\\n    widgets/UserManagerWidget.cpp \\\n    widgets/UnicornTabWidget.cpp \\\n    widgets/TrackWidget.cpp \\\n    widgets/TagListWidget.cpp \\\n    widgets/StatusLight.cpp \\\n    widgets/SearchBox.cpp \\\n    widgets/MessageBar.cpp \\\n    widgets/LfmListViewWidget.cpp \\\n    widgets/Label.cpp \\\n    widgets/ItemSelectorWidget.cpp \\\n    widgets/ImageButton.cpp \\\n    widgets/HttpImageWidget.cpp \\\n    widgets/GhostWidget.cpp \\\n    widgets/FriendsPicker.cpp \\\n    widgets/DataListWidget.cpp \\\n    widgets/BannerWidget.cpp \\\n    widgets/ActionButton.cpp \\\n    UpdateInfoFetcher.cpp \\\n    UnicornSettings.cpp \\\n    UnicornSession.cpp \\\n    UnicornMainWindow.cpp \\\n    UnicornCoreApplication.cpp \\\n    UnicornApplication.cpp \\\n    TrackImageFetcher.cpp \\\n    ScrobblesModel.cpp \\\n    qtwin.cpp \\\n    qtsingleapplication/qtsinglecoreapplication.cpp \\\n    qtsingleapplication/qtsingleapplication.cpp \\\n    qtsingleapplication/qtlockedfile_unix.cpp \\\n    qtsingleapplication/qtlockedfile.cpp \\\n    qtsingleapplication/qtlocalpeer.cpp \\\n    QMessageBoxBuilder.cpp \\\n    LoginProcess.cpp \\\n    PlayBus/PlayBus.cpp \\\n    PlayBus/Bus.cpp \\\n    dialogs/UserManagerDialog.cpp \\\n    dialogs/TagDialog.cpp \\\n    dialogs/LoginDialog.cpp \\\n    dialogs/LoginContinueDialog.cpp \\\n    dialogs/AboutDialog.cpp \\\n    dialogs/ScrobbleConfirmationDialog.cpp \\\n    dialogs/CloseAppsDialog.cpp \\\n    AnimatedStatusBar.cpp \\\n    DesktopServices.cpp \\\n    Updater/Updater.cpp \\\n    widgets/StackedWidget.cpp \\\n    widgets/ProxyWidget.cpp \\\n    dialogs/ProxyDialog.cpp \\\n    plugins/Version.cpp\n\nHEADERS += \\\n    widgets/UserToolButton.h \\\n    widgets/UserMenu.h \\\n    widgets/UserManagerWidget.h \\\n    widgets/UserComboSelector.h \\\n    widgets/UnicornTabWidget.h \\\n    widgets/TrackWidget.h \\\n    widgets/TagListWidget.h \\\n    widgets/StatusLight.h \\\n    widgets/SpinnerLabel.h \\\n    widgets/Seed.h \\\n    widgets/SearchBox.h \\\n    widgets/PlayableMimeData.h \\\n    widgets/MessageBar.h \\\n    widgets/LfmListViewWidget.h \\\n    widgets/Label.h \\\n    widgets/ItemSelectorWidget.h \\\n    widgets/ImageButton.h \\\n    widgets/HttpImageWidget.h \\\n    widgets/GhostWidget.h \\\n    widgets/FriendsPicker.h \\\n    widgets/DataListWidget.h \\\n    widgets/DataBox.h \\\n    widgets/BannerWidget.h \\\n    widgets/ActionButton.h \\\n    UpdateInfoFetcher.h \\\n    UnicornSettings.h \\\n    UnicornSession.h \\\n    UnicornMainWindow.h \\\n    UnicornCoreApplication.h \\\n    UnicornApplication.h \\\n    TrackImageFetcher.h \\\n    SignalBlocker.h \\\n    ScrobblesModel.h \\\n    qtwin.h \\\n    qtsingleapplication/qtsinglecoreapplication.h \\\n    qtsingleapplication/qtsingleapplication.h \\\n    qtsingleapplication/qtlockedfile.h \\\n    qtsingleapplication/qtlocalpeer.h \\\n    QMessageBoxBuilder.h \\\n    PlayBus/Bus.h \\\n    PlayBus/PlayBus.h \\\n    LoginProcess.h \\\n    dialogs/UserManagerDialog.h \\\n    dialogs/UnicornDialog.h \\\n    dialogs/TagDialog.h \\\n    dialogs/LoginDialog.h \\\n    dialogs/LoginContinueDialog.h \\\n    dialogs/AboutDialog.h \\\n    dialogs/ScrobbleConfirmationDialog.h \\\n    dialogs/CloseAppsDialog.h \\\n    AnimatedStatusBar.h \\\n    AnimatedPushButton.h \\\n    dialogs/ShareDialog.h \\\n    widgets/AvatarWidget.h \\\n    layouts/FlowLayout.h \\\n    widgets/SlidingStackedWidget.h \\\n    Updater/Updater.h \\\n    DesktopServices.h \\\n    widgets/StackedWidget.h \\\n    widgets/ProxyWidget.h \\\n    dialogs/ProxyDialog.h \\\n    plugins/Version.h\n\t\nwin32:HEADERS += plugins/FooBar08PluginInfo.h \\\n                    plugins/FooBar09PluginInfo.h \\\n                    plugins/ITunesPluginInfo.h \\\n                    plugins/WinampPluginInfo.h \\\n                    plugins/WmpPluginInfo.h \\\n                    plugins/PluginList.h \\\n                    plugins/KillProcess.h \\\n                    plugins/IPluginInfo.h\n\nwin32:SOURCES += qtsingleapplication/qtlockedfile_win.cpp\\\n                    plugins/PluginList.cpp \\\n                    plugins/IPluginInfo.cpp \\\n                    plugins/FooBar08PluginInfo.cpp \\\n                    plugins/FooBar09PluginInfo.cpp \\\n                    plugins/ITunesPluginInfo.cpp \\\n                    plugins/WinampPluginInfo.cpp \\\n                    plugins/WmpPluginInfo.cpp\n\nmacx:SOURCES += mac/AppleScript.cpp \\\n                plugins/ITunesPluginInstaller.cpp\n\nmacx:OBJECTIVE_SOURCES += UnicornApplication_mac.mm \\\n                          notify/Notify.mm \\\n                          Updater/Updater_mac.mm \\\n                          UnicornApplicationDelegate.mm \\\n                          dialogs/CloseAppsDialog_mac.mm\n\nmacx:HEADERS += mac/AppleScript.h \\\n                notify/Notify.h \\\n                UnicornApplicationDelegate.h \\\n                plugins/ITunesPluginInstaller.h \\\n\nCONFIG( break ) {\n    HEADERS += CrashReporter/CrashReporter.h\n    SOURCES += CrashReporter/CrashReporter.cpp\n    macx:OBJECTIVE_SOURCES += CrashReporter/CrashReporter_mac.mm\n}\n                          \nFORMS += \\\n\tdialogs/ShareDialog.ui \\\n    dialogs/TagDialog.ui \\\n    dialogs/AboutDialog.ui \\\n    dialogs/ScrobbleConfirmationDialog.ui \\\n    widgets/ProxyWidget.ui \\\n    dialogs/ProxyDialog.ui \\\n    dialogs/CloseAppsDialog.ui\n\nunix:!mac {\n    FORMS   -= dialogs/CloseAppsDialog.ui\n\n    SOURCES -= dialogs/CloseAppsDialog.cpp \\\n               plugins/Version.cpp \\\n               Updater/Updater.cpp\n\n    HEADERS -= dialogs/CloseAppsDialog.cpp \\\n               plugins/Version.h \\\n               Updater/Updater.h\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/ActionButton.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ActionButton.h\"\n#include <QAction>\n\n\nvoid\nActionButton::setAction( QAction* action )\n{\n    const bool b = action->isCheckable();\n    setCheckable( b );\n    \n    // only do one or the other or you trigger it all twice\n    if (b)\n        connect( this, SIGNAL(toggled( bool )), action, SLOT(setChecked( bool )) );\n    else\n        connect( this, SIGNAL(clicked()), action, SLOT(trigger()) );\n    \n    connect( action, SIGNAL(changed()), SLOT(onActionChanged()) );\n    onActionChanged( action );\n}\n\n\nvoid\nActionButton::onActionChanged( QAction* action )\n{\n    if (!action) action = (QAction*) sender();\n    setEnabled( action->isEnabled());\n    setChecked( action->isChecked());\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/ActionButton.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ACTION_BUTTON_H\n#define ACTION_BUTTON_H\n\n\n#include <QAbstractButton>\n#include \"lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT ActionButton : public QAbstractButton\n{\n    Q_OBJECT\n    \npublic:\n    ActionButton( QWidget* parent = 0 ) : QAbstractButton( parent )\n    {}\n    \n    void setAction( class QAction* );\n    \nprivate slots:\n    void onActionChanged( QAction* = 0 );\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/AvatarWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"AvatarWidget.h\"\n\nAvatarWidget::AvatarWidget( QWidget *parent ) :\n    HttpImageWidget(parent)\n{\n    setPixmap( QPixmap( \":/user_default.png\" ) );\n}\n\nvoid\nAvatarWidget::setUser( const lastfm::User& user )\n{\n    m_user = user;\n    update();\n}\n\n\nvoid\nAvatarWidget::paintEvent( QPaintEvent* paintEvent )\n{\n    HttpImageWidget::paintEvent( paintEvent );\n\n    if ( m_user.isSubscriber() )\n    {\n        QPainter p( this );\n\n        QString text = tr( \"Subscriber\" );\n        QColor brush( Qt::black );\n\n        switch ( m_user.type() )\n        {\n        case User::TypeModerator:\n            text = tr( \"Moderator\" );\n            brush = QColor( 0xFFA500 );\n            break;\n        case User::TypeStaff:\n            text = tr( \"Staff\" );\n            brush = QColor( 0xD51007 );\n            break;\n        case User::TypeAlumni:\n            text = m_user.gender().female() ? tr( \"Alumna\" ) : tr( \"Alumnus\" );\n            brush = QColor( 0x5336BD );\n            break;\n        default:\n            break;\n        }\n\n        QFont font = p.font();\n        font.setPixelSize( 10 );\n        font.setWeight( QFont::Bold );\n        p.setFont( font );\n\n        // the 8 and the 20 are from the stylesheet\n        // (horrible, but there's no way to find those values out and this works)\n        int totalHeight = rect().height() - 8;\n        int totalWidth = rect().width() - 20;\n\n        QFontMetrics fm( font );\n        int width = fm.width( text ) + 4;\n        int height = fm.height() + 4;\n        QRect rect( (totalWidth / 2) - (width / 2), totalHeight - (height / 2), width, height ) ;\n\n        p.setBrush( brush );\n        p.drawRoundedRect( rect, 4, 4 );\n\n        p.setPen( QColor( Qt::white ) );\n        p.drawText( rect, Qt::AlignCenter, text );\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/AvatarWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef AVATARWIDGET_H\n#define AVATARWIDGET_H\n\n#include <lastfm/User.h>\n\n#include \"lib/unicorn/widgets/HttpImageWidget.h\"\n\n#include \"lib/DllExportMacro.h\"\n\n\nclass UNICORN_DLLEXPORT AvatarWidget : public HttpImageWidget\n{\n    Q_OBJECT\npublic:\n    explicit AvatarWidget( QWidget* parent = 0 );\n\n    void setUser( const lastfm::User& user );\n\nprivate:\n    void paintEvent( QPaintEvent *paintEvent );\n\nprivate:\n    lastfm::User m_user;\n};\n\n#endif // AVATARWIDGET_H\n"
  },
  {
    "path": "lib/unicorn/widgets/BannerWidget.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"BannerWidget.h\"\n\n#include <QStackedLayout>\n#include <QDesktopServices>\n#include <QMoveEvent>\n#include <QDebug>\n#include <QCoreApplication>\n\n#include \"lib/unicorn/DesktopServices.h\"\n\nBannerWidget::BannerWidget( const QString& pText, QWidget* parent )\n    :QFrame( parent ), m_childWidget( 0 )\n{\n    m_layout = new QStackedLayout( this );\n    setLayout( m_layout );\n    m_layout->setStackingMode( QStackedLayout::StackAll );\n    m_layout->addWidget( m_banner = new BannerWidgetPrivate(pText) );\n    connect( m_banner, SIGNAL( clicked() ), this, SLOT( onClick() ) );\n    setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n}\n\nvoid \nBannerWidget::setWidget( QWidget* w )\n{\n    //Remove any existing childWidget\n    if( m_layout->count() > 1 )\n    {\n        m_childWidget->removeEventFilter( this );\n        m_layout->removeWidget( m_childWidget );\n    }\n\n    m_childWidget = w;\n    m_childWidget->installEventFilter( this );\n    m_layout->insertWidget( 0, m_childWidget );\n    m_layout->setCurrentWidget( m_banner );\n}\n\nvoid \nBannerWidget::setHref( const QUrl& url )\n{\n#ifdef Q_OS_MAC\n    //On OSX Percent encoding seems to get applied to the url again.\n    m_href = QUrl::fromPercentEncoding( url.toString().toUtf8() );\n#else\n    m_href = url.toString();\n#endif\n\n    if( url.isValid())\n        setCursor( Qt::PointingHandCursor );\n    else\n        unsetCursor();\n}\n\nvoid\nBannerWidget::onClick()\n{\n    unicorn::DesktopServices::openUrl( m_href );\n}\n\nQSize \nBannerWidget::sizeHint() const\n{\n    if( m_childWidget )\n        return m_childWidget->sizeHint();\n\n    return QWidget::sizeHint();\n}\n\nvoid \nBannerWidget::mousePressEvent( QMouseEvent* e )\n{\n    QCoreApplication::sendEvent( m_layout, e );\n}\n\nbool\nBannerWidget::eventFilter( QObject* o, QEvent* e )\n{\n    QWidget* w = qobject_cast<QWidget*>(o);\n\n    if( !w )\n        return false;\n\n    if( e->type() == QEvent::Resize )\n        resize( static_cast<QResizeEvent*>(e)->size() );\n\n    return false;\n}\n\nvoid \nBannerWidget::setBannerVisible( bool visible )\n{\n    m_banner->setVisible( visible );\n}\n\nbool \nBannerWidget::bannerVisible() const\n{\n    return m_banner->isVisible();\n}\n\n\nBannerWidgetPrivate::BannerWidgetPrivate( const QString& pText, QWidget* parent )\n    :QAbstractButton(parent)\n{\n    setText( QString( \" \" ) + pText + \" \" );\n}\n\nvoid\nBannerWidgetPrivate::paintEvent( QPaintEvent* /*e*/ )\n{\n    QPainter painter( this );\n\n    painter.setRenderHint( QPainter::TextAntialiasing );\n    painter.setRenderHint( QPainter::Antialiasing );\n\n    QRect bgRect = m_textRect.adjusted( -20, 0, 20, 0 );\n\n    painter.setWorldMatrix( m_transformMatrix );\n\n    painter.fillRect( bgRect, palette().brush( QPalette::Window ));\n    style()->drawItemText( &painter, m_textRect.translated( 0, -1 ), Qt::AlignCenter, palette(), true, text() );\n}\n\nvoid\nBannerWidgetPrivate::resizeEvent( QResizeEvent* event )\n{\n    clearMask();\n    QFont f = font();\n    m_textRect = QFontMetrics( f ).boundingRect( text() );\n    m_textRect.adjust( 0, 0, 0, 5 );\n    m_transformMatrix.reset();\n\n    //Tiny optimization and means math.h doesn't need to be included\n    //and saves some runtime ops. I shouldn't imagine sin(45) is likely to change anytime soon!\n    const float sin45 = 0.707106781186548f;\n\n    m_transformMatrix.translate( event->size().width() - ((sin45 * m_textRect.width()) + 6 ), (sin45 * m_textRect.height()) - 6 );\n    m_transformMatrix.rotate( 45 );\n\n    QRegion mask = m_transformMatrix.map( QRegion( m_textRect.adjusted( -20, 0, 20, 0 ) ) );\n    setMask( mask );\n}\n\nvoid\nBannerWidgetPrivate::mousePressEvent( QMouseEvent* e )\n{\n    if( !mask().contains( e->pos() ) )\n    {\n        e->ignore();\n        return;\n    }\n\n    e->accept();\n    return QAbstractButton::mousePressEvent( e );\n}\n\nvoid\nBannerWidgetPrivate::mouseReleaseEvent( QMouseEvent* e )\n{\n    if( !mask().contains( e->pos() ) )\n    {\n        e->ignore();\n        return;\n    }\n\n    e->accept();\n    return QAbstractButton::mouseReleaseEvent( e );\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/BannerWidget.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef BANNER_WIDGET_H\n#define BANNER_WIDGET_H\n\n#include <QFrame>\n#include <QMatrix>\n#include <QRect>\n#include <QUrl>\n#include <QStyle>\n#include <QResizeEvent>\n#include <QPainter>\n#include <QAbstractButton>\n\n#include \"lib/DllExportMacro.h\"\n#include <QDebug>\n\nclass UNICORN_DLLEXPORT BannerWidget : public QFrame\n{\n    Q_OBJECT\npublic:\n    BannerWidget( const QString& text, QWidget* parent = 0 );\n    bool bannerVisible() const;\n    void setWidget( QWidget* w );\n    QSize sizeHint() const;\n\npublic slots:\n    void setHref( const QUrl& url );\n    void setBannerVisible( bool visible = true );\n\nprotected:\n    void mousePressEvent( QMouseEvent* e );\n    bool eventFilter( QObject*, QEvent* );\n\nprivate slots:\n    void onClick();\n\nprivate:\n    class QStackedLayout* m_layout;\n    class BannerWidgetPrivate* m_banner;\n    bool m_bannerVisible;\n\n    QString m_href;\n    QWidget* m_childWidget;\n};\n\n\n\nclass BannerWidgetPrivate : public QAbstractButton\n{\n    Q_OBJECT\npublic:\n    BannerWidgetPrivate( const QString& pText, QWidget* parent = 0 );\n\nprivate:\n    void paintEvent( QPaintEvent* /*e*/ );\n    void resizeEvent( QResizeEvent* event );\n    void mousePressEvent( QMouseEvent* e );\n    void mouseReleaseEvent( QMouseEvent* e );\n\nprivate:\n    QMatrix m_transformMatrix;\n    QRect m_textRect;\n};\n\n#endif //BANNER_WIDGET_H\n\n"
  },
  {
    "path": "lib/unicorn/widgets/DataBox.h",
    "content": "/*\r\n   Copyright 2010 Last.fm Ltd.\r\n      - Primarily authored by Jono Cole and Michael Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QHBoxLayout>\r\n#include <QLabel>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nclass UNICORN_DLLEXPORT DataBox : public QFrame\r\n{\r\n    Q_OBJECT\r\npublic:\r\n    DataBox( const QString& title, QWidget* child, QWidget* p = 0 )\r\n        :QFrame( p )\r\n    { \r\n        QFrame* w = new QFrame();\r\n        w->setObjectName( \"header\" );\r\n        new QHBoxLayout( w );\r\n        w->layout()->setContentsMargins( 0, 0, 0, 0 );\r\n        w->layout()->setSpacing( 0 );\r\n        QLabel* icon;\r\n        w->layout()->addWidget( icon = new QLabel());\r\n        icon->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\r\n        icon->setObjectName( \"icon\" );\r\n\t\t\r\n        w->layout()->addWidget( new QLabel( title ));\r\n\r\n        new QVBoxLayout( this );\r\n        layout()->addWidget( w );\r\n        QWidget* cw = new QFrame();\r\n        cw->setObjectName( \"contents\" );\r\n        QVBoxLayout* v = new QVBoxLayout( cw );\r\n        v->setContentsMargins( 0, 0, 0, 0 );\r\n        v->setSpacing( 0 );\r\n        v->addWidget( child );\r\n        v->addStretch( 1 );\r\n        layout()->addWidget( cw );\r\n        layout()->setContentsMargins( 0, 0, 0, 0 );\r\n        layout()->setSpacing( 0 );\r\n    }\r\n};\r\n"
  },
  {
    "path": "lib/unicorn/widgets/DataListWidget.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd.\r\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QDebug>\r\n#include <QLayout>\r\n#include <QScrollArea>\r\n#include <QUrl>\r\n#include <QDesktopServices>\r\n#include <QMimeData>\r\n#include <QUrl>\r\n#include <QLabel>\r\n#include <QDrag>\r\n#include <QMouseEvent>\r\n#include <QApplication>\r\n\r\n#include \"DataListWidget.h\"\r\n\r\n#include \"lib/unicorn/layouts/FlowLayout.h\"\r\n#include \"lib/unicorn/UnicornApplication.h\"\r\n\r\nclass DataItem : public QLabel\r\n{\r\npublic:\r\n    explicit DataItem( const QString& text, const QUrl& url ) \r\n    :m_url(url),\r\n     m_text(text)\r\n    {\r\n        setOpenExternalLinks( true );\r\n        setTextInteractionFlags( Qt::TextSelectableByMouse | Qt::LinksAccessibleByMouse );\r\n        QString ss = qobject_cast<unicorn::Application*>(qApp)->loadedStyleSheet();\r\n        setText( \"<style>\" + ss + \"</style><a href=\\\"\" + url.toString() + \"\\\">\" + text + \"</a>\" );\r\n    }\r\n\r\n    QUrl url() const{ return m_url; }\r\n\r\nprotected:\r\n    void mouseReleaseEvent( QMouseEvent* event )\r\n    {\r\n        QLabel::mouseReleaseEvent( event );\r\n        if ((event->pos() - m_dragStartPosition).manhattanLength()\r\n                >= QApplication::startDragDistance())\r\n            return;\r\n    }\r\n\r\n    void mousePressEvent(QMouseEvent *event)\r\n    {\r\n        QLabel::mousePressEvent( event );\r\n        if (event->button() == Qt::LeftButton)\r\n            m_dragStartPosition = event->pos();\r\n    }\r\n\r\n    void mouseMoveEvent(QMouseEvent *event)\r\n    {\r\n        QLabel::mouseMoveEvent( event );\r\n        if (!(event->buttons() & Qt::LeftButton))\r\n            return;\r\n        if ((event->pos() - m_dragStartPosition).manhattanLength()\r\n                < QApplication::startDragDistance())\r\n            return;\r\n\r\n        QDrag *drag = new QDrag(this);\r\n        QMimeData *mimeData = new QMimeData;\r\n\r\n        mimeData->setText( m_text );\r\n\r\n        QList<QUrl> urls;\r\n        urls.append( url() );\r\n        mimeData->setUrls( urls );\r\n        drag->setMimeData(mimeData);\r\n\r\n        drag->exec(Qt::CopyAction);\r\n    }\r\n\r\n    QUrl m_url;\r\n    QString m_text;\r\n    QPoint m_dragStartPosition;\r\n};\r\n\r\nDataListWidget::DataListWidget(QWidget* parent)\r\n    :QFrame(parent)\r\n{\r\n    new FlowLayout( this, 0, 0, 0 );\r\n}\r\n\r\nvoid \r\nDataListWidget::clear()\r\n{\r\n    foreach( QObject* c, findChildren<QWidget*>())\r\n        c->deleteLater();\r\n}\r\n\r\nvoid \r\nDataListWidget::addItem( const QString& text, const QUrl& url )\r\n{\r\n    layout()->addWidget( new DataItem( text, url ));\r\n}\r\n"
  },
  {
    "path": "lib/unicorn/widgets/DataListWidget.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd.\r\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#ifndef DATA_LIST_WIDGET_H_\r\n#define DATA_LIST_WIDGET_H_\r\n\r\n#include <QFrame>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nclass QUrl;\r\n\r\nclass UNICORN_DLLEXPORT DataListWidget : public QFrame \r\n{\r\n    Q_OBJECT\r\n\r\npublic:\r\n    explicit DataListWidget(QWidget* parent = 0);\r\n    void clear();\r\n    void addItem( const QString&, const QUrl& );\r\n\r\n};\r\n\r\n#endif //DATA_LIST_WIDGET_H_\r\n"
  },
  {
    "path": "lib/unicorn/widgets/FriendsPicker.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"FriendsPicker.h\"\n#include <QLineEdit>\n\n#include <lastfm/User.h>\n#include <QDebug>\n#include <QDialogButtonBox>\n#include <QListWidget>\n#include <QVBoxLayout>\n\n\nFriendsPicker::FriendsPicker( const User& user )\n{    \n    QVBoxLayout* v = new QVBoxLayout( this );\n    QLineEdit* lineEdit = new QLineEdit;\n#if QT_VERSION >= 0x040700\n    // The placeholder property was introduced in Qt 4.7\n    lineEdit->setPlaceholderText( tr(\"Search your friends\") );\n#endif\n    v->addWidget( lineEdit );\n    v->addWidget( ui.list = new QListWidget );\n    v->addWidget( ui.buttons = new QDialogButtonBox( QDialogButtonBox::Ok | QDialogButtonBox::Cancel ) );\n     \n    setWindowTitle( tr(\"Browse Friends\") );\n    \n    connect( user.getFriends(), SIGNAL(finished()), SLOT(onGetFriendsReturn()) );\n    \n    connect( ui.buttons, SIGNAL(accepted()), SLOT(accept()) );\n    connect( ui.buttons, SIGNAL(rejected()), SLOT(reject()) );\n}\n\n\nvoid\nFriendsPicker::onGetFriendsReturn()\n{\n    foreach (User u, User::list( (QNetworkReply*)sender() ).users())\n        ui.list->addItem( u );\n}\n\n\nQList<User>\nFriendsPicker::selection() const\n{\n    return QList<User>();\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/FriendsPicker.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef FRIENDS_PICKER_H\n#define FRIENDS_PICKER_H\n\n#include <QDialog>\n#include <lastfm/User.h>\n#include \"lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT FriendsPicker : public QDialog\n{\n    Q_OBJECT\n\n    struct\n    {\n        class QDialogButtonBox* buttons;\n        class QListWidget* list;\n    } ui;\n    \npublic:\n    FriendsPicker( const User& = User() );\n    \n    QList<User> selection() const;\n\nprivate slots:\n    void onGetFriendsReturn();\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/GhostWidget.cpp",
    "content": "/*\n   Copyright 2010-2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"GhostWidget.h\"\n#include <QResizeEvent>\n#include <QDebug>\n\nGhostWidget::GhostWidget( QWidget* parent )\n    :QWidget( parent )\n{\n}\n\nvoid\nGhostWidget::setOrigin( QWidget* origin )\n{\n    setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );\n    setFixedSize( origin->sizeHint() );\n    setVisible( origin->isVisible() );\n    origin->installEventFilter( this );\n}\n\nbool \nGhostWidget::eventFilter( QObject* /*obj*/, QEvent* event )\n{\n    switch ( event->type() )\n    {\n    case QEvent::Resize:\n        {\n        QResizeEvent* re = static_cast<QResizeEvent*>( event );\n        setFixedSize( re->size() );\n        }\n        break;\n    case QEvent::Show:\n        show();\n        break;\n    case QEvent::Hide:\n        hide();\n        break;\n    default:\n        break;\n    }\n\n    return false;\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/GhostWidget.h",
    "content": "/*\n   Copyright 2010-2011 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef GHOST_WIDGET_H\n#define GHOST_WIDGET_H\n\n#include <QWidget>\n#include \"lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT GhostWidget : public QWidget\n{\npublic:\n    GhostWidget(QWidget* parent = 0 );\n    void setOrigin( QWidget* origin );\n\nprotected:\n    bool eventFilter( QObject* obj, QEvent* event );\n};\n\n#endif //GHOST_WIDGET_H\n\n"
  },
  {
    "path": "lib/unicorn/widgets/HttpImageWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Micahel Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QStyle>\n#include \"HttpImageWidget.h\"\n\n#include \"lib/unicorn/DesktopServices.h\"\n\nHttpImageWidget::HttpImageWidget( QWidget* parent )\n    :QLabel( parent ), m_mouseDown( false )\n{\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\n    setAttribute( Qt::WA_MacNoClickThrough );\n}\n\nvoid\nHttpImageWidget::loadUrl( const QUrl& url, ScaleType scale )\n{\n    m_scale = scale;\n    connect( lastfm::nam()->get(QNetworkRequest(url)), SIGNAL(finished()), SLOT(onUrlLoaded()));\n}\n\nvoid HttpImageWidget::setHref( const QUrl& url )\n{\n#ifdef Q_OS_MAC\n    //On OSX Percent encoding seems to get applied to the url again.\n    m_href = QUrl::fromPercentEncoding( url.toString().toUtf8() );\n#else\n    m_href = url;\n#endif\n\n    setToolTip( m_href.toString() );\n\n    unsetCursor();\n    disconnect( this, SIGNAL( clicked()), this, SLOT(onClick()));\n\n    if( m_href.isValid())\n    {\n        setCursor( Qt::PointingHandCursor );\n        connect( this, SIGNAL(clicked()), SLOT(onClick()));\n    }\n}\n\n    \nvoid HttpImageWidget::mousePressEvent( QMouseEvent* /*event*/ )\n{\n    m_mouseDown = true;\n}\n\nvoid HttpImageWidget::mouseReleaseEvent( QMouseEvent* event )\n{\n    if( m_mouseDown &&\n        contentsRect().contains( event->pos() )) emit clicked();\n\n    m_mouseDown = false;\n}\n\nvoid HttpImageWidget::onClick()\n{\n    unicorn::DesktopServices::openUrl( m_href );\n}\n\nvoid HttpImageWidget::onUrlLoaded()\n{\n    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());\n    reply->deleteLater();\n\n    if ( reply->error() == QNetworkReply::NoError )\n    {\n        QPixmap px;\n        if ( px.loadFromData( reply->readAll() ) )\n        {\n            switch ( m_scale )\n            {\n            case ScaleAuto:\n                // Decide which way to scale based on the ratio of height to width\n                // of the image and the area that the image is going to be drawn to\n                if ( (px.height() * 1000) / px.width() > (height() * 1000) / width() )\n                    px = px.scaledToWidth( contentsRect().width(), Qt::SmoothTransformation );\n                else\n                    px = px.scaledToHeight( contentsRect().height(), Qt::SmoothTransformation );\n\n                break;\n            case ScaleNone:\n                break;\n            case ScaleWidth:\n                px = px.scaledToWidth( contentsRect().width(), Qt::SmoothTransformation );\n                break;\n            case ScaleHeight:\n                px = px.scaledToHeight( contentsRect().height(), Qt::SmoothTransformation );\n                break;\n            }\n\n            setPixmap( px );\n        }\n    }\n\n    emit loaded();\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/HttpImageWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Micahel Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef HTTP_IMAGE_WIDGET_H_\n#define HTTP_IMAGE_WIDGET_H_\n\n#include <QLabel>\n#include <QUrl>\n#include <QDesktopServices>\n#include <QPainter>\n#include <QMouseEvent>\n#include \"lib/DllExportMacro.h\"\n\n#include <lastfm/ws.h>\n\nclass UNICORN_DLLEXPORT HttpImageWidget : public QLabel\n{\n    Q_OBJECT\npublic:\n    enum ScaleType\n    {\n        ScaleNone,\n        ScaleAuto,\n        ScaleWidth,\n        ScaleHeight\n    };\n\n    HttpImageWidget( QWidget* parent = 0 );\n\npublic slots:\n    void loadUrl( const QUrl& url, ScaleType scale = ScaleAuto );\n    void setHref( const QUrl& url );\n    \nprotected:\n    void mousePressEvent( QMouseEvent* event );\n    void mouseReleaseEvent( QMouseEvent* event );\n\nprivate slots:\n    void onClick();\n    void onUrlLoaded();\n\nsignals:\n    void clicked();\n    void loaded();\n\nprivate:\n    bool m_mouseDown;\n    ScaleType m_scale;\n    QUrl m_href;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/ImageButton.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ImageButton.h\"\n#include <QPainter>\n#include <QPaintEvent>\n#include <QLayout>\n#include <QAction>\n#include <QPixmap>\n#include <QIcon>\n#include <QString>\n#include <QDebug>\n\n\nImageButton::ImageButton( const QPixmap& rest, QWidget* parent )\n           : ActionButton( parent )\n{\n    init( rest );\n}\n\n\nImageButton::ImageButton( const QString& path, QWidget* parent )\n           : ActionButton( parent )\n{\n    init( QPixmap( path ) );\n}\n\n\nvoid\nImageButton::init( const QPixmap& p )\n{\n    setPixmap( p );\n    m_sizeHint = p.size();\n}\n\n\nvoid\nImageButton::paintEvent( QPaintEvent* event )\n{\n    QPainter p( this );\n    p.setClipRect( event->rect() );\n    \n    QIcon::Mode mode = isDown()\n        ? QIcon::Active\n        : isEnabled() \n            ? QIcon::Normal \n            : QIcon::Disabled;\n    \n    QIcon::State state = isChecked()\n        ? QIcon::On \n        : QIcon::Off;\n    \n    QRect iconRect = rect();\n    if( m_iconOffsets.contains( mode ) )\n    {\n        iconRect.setLeft( iconRect.left() + m_iconOffsets[ mode ].x() );\n        iconRect.setBottom( iconRect.bottom() + m_iconOffsets[ mode ].y() - 3 );\n    }\n    \n    icon().paint( &p, iconRect, Qt::AlignCenter, mode, state );\n}\n\n\nvoid\nImageButton::setPixmap( const QPixmap& p, const QIcon::State state, const QIcon::Mode mode )\n{      \n    QIcon i = icon();\n    i.addPixmap( p, mode, state );\n    setIcon( i );\n}\n\n\nvoid\nImageButton::moveIcon( int x, int y, QIcon::Mode m )\n{\n    m_iconOffsets.insert( m, QPoint( x, y ) );\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/ImageButton.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IMAGE_BUTTON_H\n#define IMAGE_BUTTON_H\n\n#include \"ActionButton.h\"\n#include <QIcon>\n#include <QMap>\n#include \"lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT ImageButton : public ActionButton\n{\n    void init( const QPixmap& );\n\t\npublic:\n    /** this pixmap becomes the rest state pixmap and defines the size of the eventual widget */\n    explicit ImageButton( const QPixmap& pixmap, QWidget* parent = 0 );\n    explicit ImageButton( const QString& pixmap_path, QWidget* parent = 0 );\n    \n    void setPixmap( const QPixmap&, const QIcon::State = QIcon::Off, QIcon::Mode = QIcon::Normal );\n\tvoid moveIcon( int x, int y, QIcon::Mode = QIcon::Normal );\n    \n\tvirtual QSize sizeHint() const { return m_sizeHint; }    \n    \nprotected:\n\tvirtual void paintEvent( QPaintEvent* event );\n    \nprivate:\n    QSize m_sizeHint;\n\tQMap< QIcon::Mode, QPoint > m_iconOffsets;\n};\n\n#endif //IMAGE_BUTTON_H"
  },
  {
    "path": "lib/unicorn/widgets/ItemSelectorWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n#include <QLabel>\n#include <QComboBox>\n#include <QCompleter>\n#include <QAbstractItemView>\n#include <QTimer>\n\n#include \"lib/unicorn/widgets/SearchBox.h\"\n\n#include \"lib/unicorn/layouts/FlowLayout.h\"\n\n#include \"ItemSelectorWidget.h\"\n\n#include <lastfm/User.h>\n\nItemSelectorWidget::ItemSelectorWidget( QWidget* parent )\n    :QFrame(parent), m_clearText( false )\n{\n    QLayout* layout = new FlowLayout( this, 0, 0, 0 );\n    layout->setContentsMargins( 0, 0, 0, 0 );\n    layout->setSpacing( 0 );\n}\n\nvoid\nItemSelectorWidget::setType( Type type )\n{\n    if (type == User)\n        layout()->addItem( new QWidgetItem( ui.searchBox = new UserSearch( this ) ) );\n    else\n        layout()->addItem( new QWidgetItem( ui.searchBox = new TagSearch( this ) ) );\n\n    ui.searchBox->setFrame( false );\n    ui.searchBox->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );\n\n    setFocusPolicy( Qt::StrongFocus );\n    setFocusProxy( ui.searchBox );\n\n    connect( ui.searchBox, SIGNAL(editingFinished()), SLOT(onItemSelected()) );\n    connect( ui.searchBox->completer()->popup(), SIGNAL(clicked(QModelIndex)), SLOT(onItemSelected()));\n    connect( ui.searchBox, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));\n\n    connect( ui.searchBox, SIGNAL(commaPressed()), SLOT(onItemSelected()) );\n    connect( ui.searchBox, SIGNAL(deletePressed()), SLOT(onDeletePressed()) );\n}\n\n\nvoid\nItemSelectorWidget::onTextChanged( const QString& /*text*/ )\n{\n    //QFontMetrics fm(font());\n\n    //int completerWidth = ui.userSearch->completer()->popup()->sizeHint().width();\n    //int textWidth = fm.width( text + \"  \" );\n\n    //ui.userSearch->setFixedWidth( completerWidth > textWidth ? completerWidth : textWidth );\n}\n\nvoid\nItemSelectorWidget::onItemSelected()\n{\n    addItem( ui.searchBox->text() );\n}\n\nvoid\nItemSelectorWidget::onItemDeleted( QLabel* item )\n{\n    m_items.removeAt( m_items.indexOf( item ) );\n    layout()->removeWidget( item );\n    item->deleteLater();\n\n    ui.searchBox->setFocus( Qt::OtherFocusReason );\n\n    emit changed();\n}\n\nvoid\nItemSelectorWidget::onDeletePressed()\n{\n    if ( m_items.count() > 0 )\n    {\n        QLabel* lastLabel = m_items.takeLast();\n        int cursorPos = lastLabel->text().length();\n        ui.searchBox->setText( lastLabel->text() + ui.searchBox->text() );\n        ui.searchBox->setCursorPosition( cursorPos );\n        onItemDeleted( lastLabel );\n    }\n}\n\nvoid\nItemSelectorWidget::onCompleterActivated( const QString& text )\n{\n    addItem( text );\n}\n\nvoid\nItemSelectorWidget::addItem( const QString& text )\n{\n    if ( !ui.searchBox->text().isEmpty() // don't add empty recipients\n        && !itemsContain( text ) // don't add duplicates\n        && m_items.count() < 10 ) // limit to 10\n    {\n        QLabel* item = new QLabel( text, this );\n        m_items.append( item );\n        dynamic_cast<FlowLayout*>(layout())->insertWidget( layout()->count() - 1 , item );\n\n        // clear the line edit a little bit later because the QCompleter\n        // will set the text to be what was selected after this\n        QTimer::singleShot(1, ui.searchBox, SLOT(clear()));\n\n        emit changed();\n    }\n}\n\nbool\nItemSelectorWidget::itemsContain( const QString& text )\n{\n    foreach ( const QLabel* item, m_items )\n    {\n        if ( item->text() == text )\n            return true;\n    }\n\n    return false;\n}\n\nQStringList\nItemSelectorWidget::items() const\n{\n    QStringList items;\n\n    foreach (const QLabel* item, m_items)\n    {\n        items << item->text();\n    }\n\n    return items;\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/ItemSelectorWidget.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd.\r\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#ifndef ITEM_SELECTOR_WIDGET_H\r\n#define ITEM_SELECTOR_WIDGET_H\r\n\r\n#include <QFrame>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nclass UNICORN_DLLEXPORT ItemSelectorWidget : public QFrame\r\n{\r\n    Q_OBJECT\r\nprivate:\r\n    struct\r\n    {\r\n        class SearchBox* searchBox;\r\n    } ui;\r\n\r\npublic:\r\n    enum Type\r\n    {\r\n        Tag,\r\n        User\r\n    };\r\n\r\n    explicit ItemSelectorWidget( QWidget* parent = 0 );\r\n\r\n    void setType( Type type );\r\n\r\n    QStringList items() const;\r\n\r\nsignals:\r\n    void changed();\r\n\r\nprivate slots:\r\n    void onItemSelected();\r\n    void onDeletePressed();\r\n    void onItemDeleted( class QLabel* recipient );\r\n\r\n    void onCompleterActivated( const QString& text );\r\n    void onTextChanged( const QString& text );\r\n\r\nprivate:\r\n    void addItem( const QString& text );\r\n    bool itemsContain( const QString& text );\r\n\r\nprivate:\r\n    QList<class QLabel*> m_items;\r\n    bool m_clearText;\r\n};\r\n\r\n#endif // ITEM_SELECTOR_WIDGET_H\r\n"
  },
  {
    "path": "lib/unicorn/widgets/Label.cpp",
    "content": "/*\r\n   Copyright 2011-2013 Last.fm Ltd.\r\n      - Primarily authored by Michael Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#include <QEvent>\r\n#include <QResizeEvent>\r\n#include <QPainter>\r\n#include <QToolTip>\r\n#include <QUrl>\r\n#include <QGraphicsDropShadowEffect>\r\n#include <QDateTime>\r\n#include <QTimer>\r\n\r\n#include \"../DesktopServices.h\"\r\n\r\n#include \"Label.h\"\r\n\r\nunicorn::Label::Label( QWidget* parent )\r\n    :QLabel( parent ), m_linkColor( QRgb( 0x333333 ) )\r\n{\r\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\r\n    setAttribute( Qt::WA_MacNoClickThrough );\r\n\r\n    setOpenExternalLinks( false );\r\n\r\n    connect( this, SIGNAL(linkHovered(QString)), SLOT(onHovered(QString)));\r\n    connect( this, SIGNAL(linkActivated(QString)), SLOT(onActivated(QString)));\r\n}\r\n\r\n\r\nunicorn::Label::Label( const QString& text, QWidget* parent )\r\n    :QLabel( parent )\r\n{\r\n    setText( text );\r\n    setAttribute( Qt::WA_LayoutUsesWidgetRect );\r\n    setAttribute( Qt::WA_MacNoClickThrough );\r\n    setOpenExternalLinks( false );\r\n\r\n    connect( this, SIGNAL(linkHovered(QString)), SLOT(onHovered(QString)));\r\n    connect( this, SIGNAL(linkActivated(QString)), SLOT(onActivated(QString)));\r\n}\r\n\r\nvoid\r\nunicorn::Label::onActivated( const QString& url )\r\n{\r\n    unicorn::DesktopServices::openUrl( url );\r\n}\r\n\r\nvoid\r\nunicorn::Label::onHovered( const QString& url )\r\n{   \r\n    QUrl displayUrl( url );\r\n    QToolTip::showText( cursor().pos(), displayUrl.toString(), this, QRect() );\r\n}\r\n\r\nQString\r\nunicorn::Label::boldLinkStyle( const QString& text, QColor linkColor )\r\n{\r\n    return QString( \"<html><head><style type=text/css>\"\r\n                     \"a:link {color:%1; font-weight: bold; text-decoration:none;}\"\r\n                     \"a:hover {color:%1; font-weight: bold; text-decoration:none;}\"\r\n                     \"</style></head><body>%2</body></html>\" ).arg( linkColor.name(), text );\r\n}\r\n\r\nQString\r\nunicorn::Label::boldLinkStyle( const QString& text )\r\n{\r\n    return boldLinkStyle( text, m_linkColor );\r\n}\r\n\r\nQString\r\nunicorn::Label::text() const\r\n{\r\n    return m_text;\r\n}\r\n\r\nvoid\r\nunicorn::Label::setText( const QString& text )\r\n{\r\n    m_text = text;\r\n\r\n    if ( textFormat() == Qt::RichText )\r\n        QLabel::setText( boldLinkStyle( m_text ) );\r\n    else\r\n        QLabel::setText( \"\"  );\r\n\r\n    update();\r\n}\r\n\r\nvoid\r\nunicorn::Label::setLinkColor( QColor linkColor )\r\n{\r\n    m_linkColor = linkColor;\r\n}\r\n\r\nQString\r\nunicorn::Label::anchor( const QString& url, const QString& text )\r\n{\r\n    QString actualText = text;\r\n    actualText.replace( QRegExp( \"&\" ), \"&amp;\" ); // This _must_ come first\r\n    actualText.replace( QRegExp( \"<\" ), \"&lt;\" );\r\n    actualText.replace( QRegExp( \">\" ), \"&gt;\" );\r\n    actualText.replace( QRegExp( \"\\\"\" ), \"&quot;\" );\r\n\r\n    return QString( \"<a href=\\\"%1\\\">%2</a>\" ).arg( url, actualText );\r\n}\r\n\r\nvoid\r\nunicorn::Label::prettyTime( Label& timestampLabel, const QDateTime& timestamp, QTimer* callback )\r\n{\r\n    QDateTime now = QDateTime::currentDateTime();\r\n\r\n    // Full time in the tool tip\r\n    timestampLabel.setToolTip( timestamp.toString( Qt::DefaultLocaleLongDate ) );\r\n\r\n    int secondsAgo = timestamp.secsTo( now );\r\n\r\n    if ( secondsAgo < (60 * 60) )\r\n    {\r\n        // Less than an hour ago\r\n        int minutesAgo = ( timestamp.secsTo( now ) / 60 );\r\n        timestampLabel.setText( tr( \"%n minute(s) ago\", \"\", minutesAgo ) );\r\n        if ( callback ) callback->start( now.secsTo( timestamp.addSecs(((minutesAgo + 1 ) * 60 ) + 1 ) ) * 1000 );\r\n    }\r\n    else if ( secondsAgo < (60 * 60 * 6) || now.date() == timestamp.date() )\r\n    {\r\n        // Less than 6 hours ago or on the same date\r\n        int hoursAgo = ( timestamp.secsTo( now ) / (60 * 60) );\r\n        timestampLabel.setText( tr( \"%n hour(s) ago\", \"\", hoursAgo ) );\r\n        if ( callback ) callback->start( now.secsTo( timestamp.addSecs( ( (hoursAgo + 1) * 60 * 60 ) + 1 ) ) * 1000 );\r\n    }\r\n    else if ( secondsAgo < (60 * 60 * 24 * 365) )\r\n    {\r\n        // less than a year ago\r\n        timestampLabel.setText( timestamp.toString( Qt::DefaultLocaleShortDate ) );\r\n        // We don't need to set the timer because this date will never change (well, it might in a year's time)\r\n    }\r\n    else\r\n    {\r\n        timestampLabel.setText( timestamp.toString( Qt::DefaultLocaleLongDate ) );\r\n        // We don't need to set the timer because this date will never change\r\n    }\r\n\r\n    if ( secondsAgo < 0 )\r\n        timestampLabel.setText( tr( \"Time is broken\" ) ); // in the future!\r\n}\r\n\r\nQString\r\nunicorn::Label::price( const QString& price, const QString& currency )\r\n{\r\n    QString returnPrice;\r\n\r\n    if ( currency.compare( \"MXN\", Qt::CaseInsensitive ) == 0\r\n              || currency.compare( \"USD\", Qt::CaseInsensitive ) == 0\r\n              || currency.compare( \"AUD\", Qt::CaseInsensitive ) == 0\r\n              || currency.compare( \"NZD\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"$%1\" ).arg( price );\r\n    else if ( currency.compare( \"CAD\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"CAD$%1\" ).arg( price );\r\n    else if ( currency.compare( \"DKK\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"DKK%1\" ).arg( price );\r\n    else if ( currency.compare( \"CHF\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"CHF%1\" ).arg( price );\r\n    else if ( currency.compare( \"NOK\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"NOK%1\" ).arg( price );\r\n    else if ( currency.compare( \"SEK\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"SEK%1\" ).arg( price );\r\n    else if ( currency.compare( \"GBP\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"£%1\" ).arg( price );\r\n    else if ( currency.compare( \"EUR\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"€%1\" ).arg( price );\r\n    else if ( currency.compare( \"JPY\", Qt::CaseInsensitive ) == 0 )\r\n        returnPrice = QString::fromUtf8( \"¥%1\" ).arg( price );\r\n    else\r\n        returnPrice = QString( \"%1 %2\" ).arg( price, currency );\r\n\r\n    return returnPrice;\r\n}\r\n\r\nQSize\r\nunicorn::Label::sizeHint() const\r\n{\r\n    QSize sizeHint = QLabel::sizeHint();\r\n\r\n    if ( textFormat() != Qt::RichText )\r\n        sizeHint.setWidth( qMin ( sizeHint.width(), fontMetrics().width( m_text ) + 1 ) );\r\n\r\n    return sizeHint;\r\n}\r\n\r\nvoid\r\nunicorn::Label::paintEvent( QPaintEvent* event )\r\n{\r\n    if ( textFormat() == Qt::RichText )\r\n        QLabel::paintEvent( event );\r\n    else\r\n    {\r\n        QFrame::paintEvent(event);\r\n        QPainter p(this);\r\n        p.drawText( rect(), fontMetrics().elidedText( m_text, Qt::ElideRight, contentsRect().width() ) );\r\n    }\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "lib/unicorn/widgets/Label.h",
    "content": "/*\r\n   Copyright 2011-2013 Last.fm Ltd.\r\n      - Primarily authored by Michael Coffey\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n\r\n#ifndef LABEL_H\r\n#define LABEL_H\r\n\r\n#include <QLabel>\r\n\r\n#include \"lib/DllExportMacro.h\"\r\n\r\nnamespace unicorn\r\n{\r\n\r\nclass UNICORN_DLLEXPORT Label : public QLabel\r\n{\r\n    Q_OBJECT\r\npublic:\r\n    explicit Label( QWidget* parent = 0 );\r\n    explicit Label( const QString& text, QWidget* parent = 0 );\r\n\r\n    QString text() const;\r\n    void setText( const QString& text );\r\n    void setLinkColor( QColor linkColor );\r\n\r\n    static QString anchor( const QString& url, const QString& text );\r\n    static QString boldLinkStyle( const QString& text, QColor linkColor );\r\n\r\n    // Gives you a pretty time string and will call your slot when it's time to change it again\r\n    static void prettyTime( Label& timestampLabel, const class QDateTime& timestamp, QTimer* callback = 0 );\r\n    static QString price( const QString& price, const QString& currency );\r\n\r\nprivate:\r\n    void paintEvent( QPaintEvent* event );\r\n\r\n    QSize sizeHint() const;\r\n\r\n    QString boldLinkStyle( const QString& text );\r\n\r\nprivate slots:\r\n    void onHovered( const QString& url );\r\n    void onActivated( const QString& url );\r\n\r\nprivate:\r\n    QString m_text;\r\n    QColor m_linkColor;\r\n};\r\n\r\n}\r\n\r\n#endif // LABEL_H\r\n"
  },
  {
    "path": "lib/unicorn/widgets/LfmListViewWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QCoreApplication>\n#include <QDomDocument>\n#include <QFile>\n\n#include \"LfmListViewWidget.h\"\n#include <lastfm/User.h>\n#include <lastfm/Artist.h>\n#include <lastfm/Track.h>\n\n#include <iostream>\n\nLfmDelegate::LfmDelegate( QAbstractItemView* parent ):QStyledItemDelegate(parent)\n{\n    m_viewSize = parent->size();\n    parent->installEventFilter( this );\n}\n\nvoid LfmDelegate::paint( QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& index ) const\n{\n    QIcon icon;\n\n    if( index.data(Qt::DecorationRole).type() == QVariant::Icon )\n    {\n        icon = index.data(Qt::DecorationRole).value<QIcon>();\n\n        if ( icon.isNull() )\n            //icon = QIcon( m_defaultImage );\n            icon = QIcon( \":/default_user.png\" );\n\n        QRect iconRect = opt.rect.translated( 3, 3 );\n        iconRect.setSize( QSize( 34, 34 ));\n        icon.paint( p, iconRect );\n        QSize iconSize = icon.actualSize( iconRect.size());\n\n        if( iconSize.isEmpty()) iconSize = QSize( 34, 34 );\n\n        iconRect.translate( ( iconRect.width() - iconSize.width()) / 2.0f,\n                            ( iconRect.height() - iconSize.height()) /2.0f );\n        iconRect.setSize( iconSize );\n        p->drawRect( iconRect );\n    }\n\n    QFontMetrics fm( p->font() );\n    QString elidedText = fm.elidedText( index.data().toString(), Qt::ElideRight, opt.rect.width() - 50 );\n    p->drawText( opt.rect.adjusted( 46, 3, -5, -5 ), elidedText );\n}\n\nQSize LfmDelegate::sizeHint( const QStyleOptionViewItem& opt, const QModelIndex& /*index*/ ) const\n{\n    QFontMetrics fm( opt.font );\n    //int textWidth = fm.width( index.data().toString());\n    int spacing = qobject_cast<QListView*>(parent())->spacing();\n    return QSize( (m_viewSize.width() / 2)-(spacing*2), 40 );\n}\n\nbool LfmDelegate::eventFilter( QObject* obj, QEvent* event )\n{\n    if( event->type() == QEvent::Resize ) {\n        QWidget* view = qobject_cast< QWidget* >(obj );\n\n        if( !view ) return false;\n\n        m_viewSize = view->size();\n        emit sizeHintChanged( QModelIndex() );\n    }\n    return false;\n}\n\nQPixmap LfmDelegate::defaultImage() const\n{\n    return m_defaultImage;\n}\n\nvoid LfmDelegate::setDefaultImage( QPixmap defaultImage )\n{\n    m_defaultImage = defaultImage;\n}\n\n\nvoid\nLfmItem::onImageLoaded()\n{\n    QNetworkReply* reply = static_cast<QNetworkReply*>(sender());\n    reply->deleteLater();\n\n    QPixmap px;\n    px.loadFromData( reply->readAll() );\n    m_icon = QIcon( px );\n    emit updated();\n}\n\n\nvoid LfmItem::loadImage( const QUrl& url )\n{\n    QString imageUrl = url.toString();\n   \n    QNetworkReply* reply = lastfm::nam()->get(QNetworkRequest( url ));\n    connect( reply, SIGNAL( finished()), this, SLOT( onImageLoaded()));\n}\n\n\nvoid\nLfmListModel::addUser( const User& a_user )\n{\n    User* user = new User;\n    *user = a_user;\n    LfmItem* item = new LfmItem( user );\n    item->loadImage( user->imageUrl(User::SmallImage, true ));\n\n    beginInsertRows( QModelIndex(), rowCount(), rowCount());\n    m_items << item;\n    connect( item, SIGNAL(updated()), SLOT( itemUpdated()));\n    endInsertRows();\n}\n\n\nvoid \nLfmListModel::addArtist( const Artist& a_artist )\n{\n    Artist* artist = new Artist;\n    *artist = a_artist;\n    LfmItem* item = new LfmItem( artist );\n    item->loadImage( artist->imageUrl( Artist::SmallImage, true ));\n\n    beginInsertRows( QModelIndex(), rowCount(), rowCount());\n    m_items << item;\n    connect( item, SIGNAL(updated()), SLOT( itemUpdated()));\n    endInsertRows();   \n}\n\nvoid\nLfmListModel::itemUpdated()\n{\n    LfmItem* item = static_cast<LfmItem*>(sender());\n    int index = m_items.indexOf( item );\n    if ( index >= 0 )\n        emit dataChanged( createIndex( index, 0), createIndex( index, 0));\n}\n\n\nQVariant \nLfmListModel::data( const QModelIndex & index, int role ) const\n{\n    if( index.row() > m_items.count()) return QVariant();\n\n    const LfmItem& item = *(m_items[index.row()]);\n\n    switch( role ) {\n        case Qt::DisplayRole:\n            return item.m_type->toString();\n\n        case Qt::DecorationRole:\n            return item.m_icon;\n\n        case Qt::ToolTipRole:\n            return item.m_type->toString();\n\n        case CursorRole:\n            return Qt::PointingHandCursor;\n\n        case WwwRole:\n            return item.m_type->www();\n\n    }\n    return QVariant();\n}\n\n\n\nLfmListView::LfmListView(QWidget *parent):\n   QListView(parent),\n   m_lastRow(-1)\n{\n   setMouseTracking(true);\n   setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );\n   setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );\n}\n\n\n#include <QMouseEvent>\nvoid LfmListView::mouseMoveEvent(QMouseEvent *event)\n{\n   QAbstractItemModel *m(model());\n\n   if (m)\n   {\n      QModelIndex index = indexAt(event->pos());\n      if (index.isValid())\n      {\n         // When the index is valid, compare it to the last row.\n         // Only do something when the the mouse has moved to a new row.\n         if (index.row() != m_lastRow)\n         {\n            m_lastRow = index.row();\n            // Request the data for the CursorRole.\n            QVariant data = m->data(index, LfmListModel::CursorRole );\n\n            Qt::CursorShape shape = Qt::ArrowCursor;\n            if (!data.isNull())\n               shape = static_cast<Qt::CursorShape>(data.toInt());\n            setCursor(shape);\n         }\n      }\n      else\n      {\n         if (m_lastRow != -1)\n            setCursor(Qt::ArrowCursor);\n         m_lastRow = -1;\n      }\n   }\n   QListView::mouseMoveEvent(event);\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/LfmListViewWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd.\n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LFM_LIST_VIEW_WIDGET_H\n#define LFM_LIST_VIEW_WIDGET_H\n\n\n#include <lastfm/AbstractType.h>\n#include <QStyledItemDelegate>\n#include <QPainter>\n#include <QUrl>\n#include <QAbstractItemView>\n#include <QEvent>\n#include \"lib/DllExportMacro.h\"\n#include <QListView>\n#include <QFontMetrics>\n\n#include <QDebug>\n\nnamespace lastfm { class AbstractType; };\nusing lastfm::AbstractType;\n\nclass UNICORN_DLLEXPORT LfmDelegate :public QStyledItemDelegate {\n    Q_OBJECT\n    Q_PROPERTY(QPixmap defaultImage READ defaultImage WRITE setDefaultImage);\n\npublic:\n    LfmDelegate( QAbstractItemView* parent );\n\n    virtual void paint( QPainter* p, const QStyleOptionViewItem& opt, const QModelIndex& index ) const;\n    virtual QSize sizeHint( const QStyleOptionViewItem& opt, const QModelIndex& index ) const;\n    bool eventFilter( QObject* obj, QEvent* event );\n\n    QPixmap defaultImage() const;\n    void setDefaultImage( QPixmap defaultImage );\n\nprivate:\n    QSize m_viewSize;\n    QPixmap m_defaultImage;\n};\n\nclass LfmItem : public QObject {\n    Q_OBJECT\npublic:\n    LfmItem(AbstractType* type, QObject* parent = 0)\n        :QObject( parent ), m_type( type )\n    {;}\n\n    ~LfmItem() { delete m_type; }\n\n    bool operator==( const LfmItem& that ) const { return this->m_type->toString() == that.m_type->toString(); }\n\n    void loadImage( const QUrl& url );\n\n    QIcon m_icon;\n    AbstractType* m_type;\n\nsignals:\n    void updated();\n\nprotected slots:\n    void onImageLoaded();\n};\n\nnamespace lastfm {\nclass User;\nclass Artist;\nclass Track;\n}\nusing lastfm::User;\nusing lastfm::Artist;\nusing lastfm::Track;\n\nclass UNICORN_DLLEXPORT LfmListModel : public QAbstractListModel {\n    Q_OBJECT\npublic:\n    enum DataRole { WwwRole = Qt::UserRole,\n                    CursorRole};\n\n    LfmListModel( QObject* parent=0 ):QAbstractListModel( parent ){}\n\n    void addUser( const User& );\n    void addArtist( const Artist& );\n    void addCachedTrack( const Track& );\n    void addScrobbledTrack( const Track& );\n\n    void read(QString path);\n    void write(QString path) const;\n\n    int rowCount ( const QModelIndex& parent = QModelIndex() ) const\n    {\n        Q_UNUSED(parent);\n        return m_items.length();\n    }\n\n    QVariant data( const QModelIndex & index, int role = Qt::DisplayRole ) const;\n\n    void clear()\n    {\n    if( m_items.isEmpty()) return;\n    beginRemoveRows( QModelIndex(), 0, rowCount() -1 );\n        foreach( LfmItem* item, m_items ) {\n            item->deleteLater();\n            m_items.removeAll( item );\n        }\n    endRemoveRows();\n    }\n     \nprotected slots:\n    void itemUpdated();\n\nprotected:\n    QList<LfmItem*> m_items;\n\n};\n\n\n#include <QListView>\nclass UNICORN_DLLEXPORT LfmListView : public QListView {\n   Q_OBJECT\npublic:\n   LfmListView(QWidget *parent = 0);\n\nprotected:\n   virtual void mouseMoveEvent(QMouseEvent *event);\n\nprivate:\n   int m_lastRow;\n};\n\n\n#endif //LFM_LIST_VIEW_WIDGET_H\n\n"
  },
  {
    "path": "lib/unicorn/widgets/MessageBar.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QtGui>\n#include <QLabel>\n\n#include \"lib/unicorn/dialogs/ScrobbleConfirmationDialog.h\"\n#include \"lib/unicorn/widgets/Label.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"MessageBar.h\"\n\nMessageBar::MessageBar( QWidget* parent )\n    :QFrame( parent )\n{\n    QHBoxLayout* layout = new QHBoxLayout( this );\n\n    layout->addWidget( ui.icon = new QLabel() );\n    ui.icon->setObjectName( \"icon\" );\n\n    layout->addWidget( ui.message = new QLabel() );\n    ui.message->setObjectName( \"message\" );\n\n    layout->addStretch();\n\n    layout->addWidget( ui.close = new QPushButton() );\n    ui.close->setObjectName( \"close\" );\n\n    connect( ui.message, SIGNAL(linkActivated(QString)), SLOT(onLinkActivated(QString)));\n    connect( ui.close, SIGNAL(clicked()), SLOT(onCloseClicked()));\n\n    connect( qApp, SIGNAL(showMessage(QString,QString)), SLOT(show(QString,QString)));\n    connect( qApp, SIGNAL(error(QString)), SLOT(show(QString)));\n\n    hide();\n}\n\nvoid\nMessageBar::addTracks( const QList<lastfm::Track>& tracks )\n{\n    m_tracks << tracks;\n}\n\nconst QList<lastfm::Track>&\nMessageBar::tracks() const\n{\n    return m_tracks;\n}\n\nvoid\nMessageBar::show( const QString& message, const QString& id, int timeout )\n{\n    if ( !m_timeout )\n    {\n        m_timeout = new QTimer( this );\n        connect( m_timeout, SIGNAL(timeout()), SLOT(onCloseClicked()) );\n    }\n\n    if ( timeout != -1 )\n        m_timeout->start( timeout * 1000 );\n    else\n        m_timeout->stop();\n\n\n    setObjectName( id );\n    ui.message->setText( unicorn::Label::boldLinkStyle( message, Qt::black ) );\n\n    style()->polish( this );\n    style()->polish( ui.icon );\n\n    QWidget::show();\n}\n\nvoid\nMessageBar::onCloseClicked()\n{\n    m_tracks.clear();\n    hide();\n}\n\nvoid\nMessageBar::onLinkActivated( const QString& link )\n{\n    if ( link == \"tracks\" )\n    {\n        // always sort the tracks before displaying them\n        qSort ( m_tracks.begin(), m_tracks.end() );\n\n        // Show a dialog with the tracks\n        ScrobbleConfirmationDialog confirmDialog( m_tracks );\n        confirmDialog.setReadOnly();\n        confirmDialog.exec();\n    }\n\n    else if ( link == \"plugin\" )\n    {\n#ifdef Q_OS_MAC\n        if ( !m_installer )\n            m_installer = new unicorn::ITunesPluginInstaller( this );\n\n        m_installer->install();\n#elif defined( Q_OS_WIN )\n        if ( !m_itw )\n            m_itw = new unicorn::ITunesPluginInfo( this );\n\n        m_itw->setVerbose( true );\n        m_itw->doInstall();\n#endif\n    }\n\n    else\n    {\n        // this should be a url so open it in the browser\n        unicorn::DesktopServices::openUrl( link );\n    }\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/MessageBar.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef MESSAGE_BAR_H\n#define MESSAGE_BAR_H\n\n#include \"lib/DllExportMacro.h\"\n\n#include <lastfm/Track.h>\n\n#ifdef Q_OS_MAC\n#include \"lib/unicorn/plugins/ITunesPluginInstaller.h\"\n#elif defined( Q_OS_WIN )\n#include \"lib/unicorn/plugins/ITunesPluginInfo.h\"\n#endif\n\n#include <QFrame>\n\nclass UNICORN_DLLEXPORT MessageBar : public QFrame\n{\n    Q_OBJECT \nprivate:\n    struct\n    {\n        class QLabel* icon;\n        class QLabel* message;\n        class QPushButton* close;\n    } ui;\n\npublic:\n    explicit MessageBar( QWidget* parent );\n\n    void addTracks( const QList<lastfm::Track>& tracks );\n    const QList<lastfm::Track>& tracks() const;\n    \npublic slots:\n    void show( const QString& message, const QString& id = QString(), int timeout = -1 );\n\nprivate slots:\n    void onLinkActivated( const QString& link );\n    void onCloseClicked();\n\nprivate:\n    QList<lastfm::Track> m_tracks;\n    QPointer<QTimer> m_timeout;\n#ifdef Q_OS_MAC\n    QPointer<unicorn::ITunesPluginInstaller> m_installer;\n#elif defined( Q_OS_WIN )\n    QPointer<unicorn::ITunesPluginInfo> m_itw;\n#endif\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/PlayableMimeData.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef PLAYABLE_MIME_DATA\n#define PLAYABLE_MIME_DATA\n\n#include <QMimeData>\n#include <lastfm/Artist.h>\n#include <lastfm/Tag.h>\n#include <lastfm/User.h>\n#include \"Seed.h\"\n\n\nclass PlayableMimeData : public QMimeData\n{\n\tQ_OBJECT\npublic:\n\t\n\tstatic PlayableMimeData* createFromArtist( const Artist& a )\n\t{\n\t\tPlayableMimeData* data = new PlayableMimeData();\n\t\tdata->setText( a );\n\t\tdata->setUrls( QList<QUrl>() << a.www() );\n\t\tdata->setData( \"text/x-lfm-entity-type\", \"Artist\" );\n\t\tdata->m_type = Seed::ArtistType;\n\t\treturn data;\n\t}\n\t\n\tstatic PlayableMimeData* createFromTag( const Tag& t )\n\t{\n\t\tPlayableMimeData* data = new PlayableMimeData();\n\t\tdata->setText( t );\n\t\tdata->setUrls( QList<QUrl>() << t.www() );\n\t\tdata->setData( \"text/x-lfm-entity-type\", \"Tag\" );\n\t\tdata->m_type = Seed::TagType;\n\t\treturn data;\n\t}\n\t\n\tstatic PlayableMimeData* createFromUser( const User& u )\n\t{\n\t\tPlayableMimeData* data = new PlayableMimeData();\n\t\tdata->setText( u );\n\t\tdata->setUrls( QList<QUrl>() << u.www() );\n\t\tdata->setData( \"text/x-lfm-entity-type\", \"User\" );\n\t\tdata->m_type = Seed::UserType;\n\t\treturn data;\n\t}\n    \n    static PlayableMimeData* createFromPredefined( const QString& s )\n    {\n\t\tPlayableMimeData* data = new PlayableMimeData();\n\t\tdata->setText( s );\n\t\tdata->setData( \"text/x-lfm-entity-type\", \"Predefined\" );\n\t\tdata->m_type = Seed::PreDefinedType;\n\t\treturn data;\n    }\n\t\n    Seed::Type type() const\n\t{\n\t\treturn m_type;\n\t}\n\t\n\tvoid setType( Seed::Type t )\n\t{\n\t\tm_type = t;\n\t}\n    \n    void setRQL( const QString& rql ){ m_rql = rql; }\n\n    QString rql() const{ return m_rql; }\n\t\nprivate:\n    Seed::Type m_type;\n    QString m_rql;\n\t\n};\n\n#endif //PLAYABLE_MIME_DATA\n"
  },
  {
    "path": "lib/unicorn/widgets/ProxyWidget.cpp",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QNetworkProxy>\n\n#include <lastfm/NetworkAccessManager.h>\n\n#include \"lib/unicorn/UnicornSettings.h\"\n\n#include \"ProxyWidget.h\"\n#include \"ui_ProxyWidget.h\"\n\nunicorn::ProxyWidget::ProxyWidget(QWidget *parent) :\n    QWidget(parent), ui( new Ui::ProxyWidget)\n{\n    ui->setupUi( this );\n\n    unicorn::AppSettings appSettings;\n\n    QStringList proxyTypes;\n    proxyTypes << tr( \"Auto-detect\" ) << tr( \"No-proxy\" ) << tr(\"HTTP\") << tr(\"SOCKS5\");\n    ui->proxyType->addItems( proxyTypes );\n    ui->proxyType->setCurrentIndex( appSettings.value( \"proxyType\", 0 ).toInt() );\n    ui->proxyHost->setText( appSettings.value( \"proxyHost\", \"\" ).toString() );\n    ui->proxyPort->setText( appSettings.value( \"proxyPort\", \"\" ).toString() );\n    ui->proxyUsername->setText( appSettings.value( \"proxyUsername\", \"\" ).toString() );\n    ui->proxyPassword->setText( appSettings.value( \"proxyPassword\", \"\" ).toString() );\n\n    connect( ui->proxyType, SIGNAL(currentIndexChanged(int)), SIGNAL(changed()));\n    connect( ui->proxyHost, SIGNAL(textChanged(QString)), SIGNAL(changed()));\n    connect( ui->proxyPort, SIGNAL(textChanged(QString)), SIGNAL(changed()));\n    connect( ui->proxyUsername, SIGNAL(textChanged(QString)), SIGNAL(changed()));\n    connect( ui->proxyPassword, SIGNAL(textChanged(QString)), SIGNAL(changed()));\n\n    connect( this, SIGNAL(changed()), SLOT(onChanged()) );\n\n    onChanged();\n}\n\nunicorn::ProxyWidget::~ProxyWidget()\n{\n    delete ui;\n}\n\nvoid\nunicorn::ProxyWidget::onChanged()\n{\n    bool enabled = ui->proxyType->currentIndex() > 1;\n    ui->proxyHost->setEnabled( enabled );\n    ui->proxyPort->setEnabled( enabled );\n    ui->proxyUsername->setEnabled( enabled );\n    ui->proxyPassword->setEnabled( enabled );\n}\n\nvoid\nunicorn::ProxyWidget::save()\n{\n    unicorn::AppSettings appSettings;\n    int proxyType = appSettings.value( \"proxyType\", 0 ).toInt();\n    QString proxyHost = appSettings.value( \"proxyHost\", \"\" ).toString();\n    QString proxyPort = appSettings.value( \"proxyPort\", \"\" ).toString();\n    QString proxyUsername = appSettings.value( \"proxyUsername\", \"\" ).toString();\n    QString proxyPassword = appSettings.value( \"proxyPassword\", \"\" ).toString();\n\n    if ( proxyType != ui->proxyType->currentIndex()\n         || proxyHost != ui->proxyHost->text()\n         || proxyPort != ui->proxyPort->text()\n         || proxyUsername != ui->proxyUsername->text()\n         || proxyPassword != ui->proxyPassword->text() )\n    {\n        // one of the proxy settings has changed\n\n        // save them\n        appSettings.setValue( \"proxyType\", ui->proxyType->currentIndex() );\n        appSettings.setValue( \"proxyHost\", ui->proxyHost->text() );\n        appSettings.setValue( \"proxyPort\", ui->proxyPort->text() );\n        appSettings.setValue( \"proxyUsername\", ui->proxyUsername->text() );\n        appSettings.setValue( \"proxyPassword\", ui->proxyPassword->text() );\n\n        // set this new proxy\n        QNetworkProxy::ProxyType type = QNetworkProxy::DefaultProxy;\n\n        if ( ui->proxyType->currentIndex() == 1 )\n            type = QNetworkProxy::NoProxy;\n        else if ( ui->proxyType->currentIndex() == 2 )\n            type = QNetworkProxy::HttpProxy;\n        else if ( ui->proxyType->currentIndex() == 3 )\n            type = QNetworkProxy::Socks5Proxy;\n\n        QNetworkProxy proxy( type, ui->proxyHost->text(), ui->proxyPort->text().toInt(), ui->proxyUsername->text(), ui->proxyPassword->text() );\n        lastfm::NetworkAccessManager* nam = qobject_cast<lastfm::NetworkAccessManager*>( lastfm::nam() );\n\n        if ( nam )\n            nam->setUserProxy( proxy );\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/ProxyWidget.h",
    "content": "/*\n   Copyright 2013 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef PROXYWIDGET_H\n#define PROXYWIDGET_H\n\n#include \"lib/DllExportMacro.h\"\n\n#include <QWidget>\n\nnamespace Ui { class ProxyWidget; }\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT ProxyWidget : public QWidget\n{\n    Q_OBJECT\npublic:\n    explicit ProxyWidget(QWidget *parent = 0);\n    ~ProxyWidget();\n\n    void save();\n\nsignals:\n    void changed();\n\nprivate slots:\n    void onChanged();\n\nprivate:\n    Ui::ProxyWidget* ui;\n};\n\n}\n\n#endif // PROXYWIDGET_H\n"
  },
  {
    "path": "lib/unicorn/widgets/ProxyWidget.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ProxyWidget</class>\n <widget class=\"QWidget\" name=\"ProxyWidget\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>312</width>\n    <height>106</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string notr=\"true\">Form</string>\n  </property>\n  <layout class=\"QGridLayout\" name=\"gridLayout_2\">\n   <item row=\"1\" column=\"1\">\n    <widget class=\"QLineEdit\" name=\"proxyHost\"/>\n   </item>\n   <item row=\"1\" column=\"0\">\n    <widget class=\"QLabel\" name=\"label\">\n     <property name=\"text\">\n      <string>Host:</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"6\" column=\"1\">\n    <widget class=\"QLineEdit\" name=\"proxyUsername\"/>\n   </item>\n   <item row=\"6\" column=\"0\">\n    <widget class=\"QLabel\" name=\"label_2\">\n     <property name=\"text\">\n      <string>Username:</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"1\" column=\"2\">\n    <widget class=\"QLabel\" name=\"label_4\">\n     <property name=\"text\">\n      <string>Port:</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"1\" column=\"3\">\n    <widget class=\"QLineEdit\" name=\"proxyPort\"/>\n   </item>\n   <item row=\"6\" column=\"2\">\n    <widget class=\"QLabel\" name=\"label_3\">\n     <property name=\"text\">\n      <string>Password:</string>\n     </property>\n    </widget>\n   </item>\n   <item row=\"6\" column=\"3\">\n    <widget class=\"QLineEdit\" name=\"proxyPassword\">\n     <property name=\"echoMode\">\n      <enum>QLineEdit::Password</enum>\n     </property>\n    </widget>\n   </item>\n   <item row=\"0\" column=\"0\" colspan=\"2\">\n    <widget class=\"QComboBox\" name=\"proxyType\"/>\n   </item>\n  </layout>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "lib/unicorn/widgets/SearchBox.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QKeyEvent>\n\n#include \"SearchBox.h\"\n#include <QNetworkReply>\n#include <QPushButton>\n#include <QListView>\n#include <QCompleter>\n#include <QStringListModel>\n#include <lastfm/XmlQuery.h>\n#include <lastfm/Artist.h>\n#include <lastfm/Tag.h>\n#include <lastfm/User.h>\n\nSearchBox::SearchBox(QWidget* parent)\n: QLineEdit( parent )\n, m_searching(false)\n{\n    setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );\n    setAttribute( Qt::WA_MacShowFocusRect, false );\n    m_completer = new QCompleter(this);\n    m_completer->setCaseSensitivity(Qt::CaseInsensitive);\n    setCompleter(m_completer);\n\n    connect(this, SIGNAL(textEdited(QString)), SLOT(onTextEdited(QString)));\n}\n\nvoid\nSearchBox::onTextEdited(const QString& text)\n{\n    QString trimmedText = text.trimmed();\n\n    if (!m_searching && trimmedText.length()) {\n        QNetworkReply* reply = startSearch(trimmedText);\n        if (reply) {\n            m_searching = true;\n            connect(reply, SIGNAL(finished()), SLOT(onSearchFinished()));\n        }\n    }\n}\n\nvoid\nSearchBox::keyPressEvent( QKeyEvent* event )\n{\n    if ( event->key() == Qt::Key_Backspace )\n    {\n        if ( cursorPosition() == 0 )\n        {\n            emit deletePressed();\n            return;\n        }\n    }\n    else if ( event->text() == \",\" )\n    {\n        emit commaPressed();\n        return;\n    }\n\n    QLineEdit::keyPressEvent( event );\n}\n\nvoid\nSearchBox::onSearchFinished()\n{\n    sender()->deleteLater();\n    QString searchTerm;\n\n    XmlQuery lfm;\n\n    if ( lfm.parse( qobject_cast<QNetworkReply*>(sender()) ) )\n    {\n\n        searchTerm = ((QDomElement)lfm[\"results\"]).attribute(\"for\");\n        m_completer->setModel(\n            new QStringListModel(\n                handleSearchResponse(lfm)));\n        m_completer->complete();\n    } \n\n    m_searching = false;\n    // possibly a search pending:\n    if (text().trimmed() != searchTerm) {\n        onTextEdited(text());\n    }\n}\n\n\n\n///////////////////////////////////////////\n\nArtistSearch::ArtistSearch(QWidget* parent)\n: SearchBox(parent)\n{\n}\n\nQNetworkReply*\nArtistSearch::startSearch(const QString& term)\n{\n    return Artist(term).search();\n}\n\nQStringList\nArtistSearch::handleSearchResponse(XmlQuery& lfm)\n{\n    QStringList list;\n    foreach(XmlQuery i, lfm[\"results\"][\"artistmatches\"].children(\"artist\")) {\n        list << i[\"name\"].text();\n    }\n    return list;\n}\n\n///////////////////////////////////////////\n\nTagSearch::TagSearch(QWidget* parent)\n: SearchBox(parent)\n{\n}\n\nQNetworkReply*\nTagSearch::startSearch(const QString& term)\n{\n    return Tag(term).search();\n}\n\nQStringList\nTagSearch::handleSearchResponse(XmlQuery& lfm)\n{\n    QStringList list;\n    foreach(XmlQuery i, lfm[\"results\"][\"tagmatches\"].children(\"tag\")) {\n        list << i[\"name\"].text().toLower();\n    }\n    return list;\n}\n\n///////////////////////////////////////////\n\nUserSearch::UserSearch(QWidget* parent)\n: SearchBox(parent)\n{\n    connect(User().getFriends(), SIGNAL(finished()), SLOT(onGetFriendsFinished()));\n}\n\nint CaseInsensitiveLessThan(const QString& s1, const QString &s2)\n{\n    return s1.toLower() < s2.toLower();\n}\n\nvoid\nUserSearch::onGetFriendsFinished()\n{\n    lastfm::UserList friendPage = User::list( (QNetworkReply*)sender() );\n    m_friends += friendPage.users();\n\n    if ( friendPage.currentPage() == friendPage.totalPages() )\n    {\n        QStringList friends;\n\n        foreach (User u, m_friends)\n            friends << u.name();\n\n        qSort(friends.begin(), friends.end(), CaseInsensitiveLessThan);\n\n        m_completer->setCaseSensitivity( Qt::CaseInsensitive );\n        m_completer->setModel(new QStringListModel( friends ));\n    }\n    else\n    {\n        // get the next page of friends\n        connect(User().getFriends( false, friendPage.usersPerPage(), friendPage.currentPage() + 1 ), SIGNAL(finished()), SLOT(onGetFriendsFinished()));\n    }\n}\n\nQNetworkReply*\nUserSearch::startSearch(const QString& term)\n{\n    // alas, there is no user.search yet\n    Q_UNUSED(term);\n\n    m_completer->complete();\n    return 0;\n}\n\nQStringList\nUserSearch::handleSearchResponse(XmlQuery& lfm)\n{\n    Q_UNUSED(lfm);\n    return QStringList();\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/SearchBox.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SEARCH_BOX_H\n#define SEARCH_BOX_H\n\n#include <QLineEdit>\n#include <lastfm/global.h>\n#include \"lib/DllExportMacro.h\"\n#include <lastfm/User.h>\n\nclass QNetworkReply;\nclass QCompleter;\n\nnamespace lastfm {\n    class XmlQuery;\n}\n\n\nclass UNICORN_DLLEXPORT SearchBox : public QLineEdit\n{\n    Q_OBJECT;\n\npublic:\n    SearchBox(QWidget *parent = 0);\n\nsignals:\n    void commaPressed();\n    void deletePressed();\n\nprivate slots:\n    void onTextEdited(const QString& text);\n    void onSearchFinished();\n\nprotected:\n    virtual QNetworkReply* startSearch(const QString& term) = 0;\n    virtual QStringList handleSearchResponse(XmlQuery& lfm) = 0;\n\n    void keyPressEvent( QKeyEvent* event );\n\n    QCompleter* m_completer;\n    bool m_searching;\n};\n\n\nclass UNICORN_DLLEXPORT ArtistSearch : public SearchBox\n{\npublic:\n    ArtistSearch(QWidget *parent = 0);\n    virtual QNetworkReply* startSearch(const QString& term);\n    virtual QStringList handleSearchResponse(XmlQuery& lfm);\n};\n\n\nclass UNICORN_DLLEXPORT TagSearch : public SearchBox\n{\npublic:\n    TagSearch(QWidget *parent = 0);\n    virtual QNetworkReply* startSearch(const QString& term);\n    virtual QStringList handleSearchResponse(XmlQuery& lfm);\n\n};\n\n\nclass UNICORN_DLLEXPORT UserSearch : public SearchBox\n{\n    Q_OBJECT\npublic:\n    UserSearch(QWidget *parent = 0);\n    virtual QNetworkReply* startSearch(const QString& term);\n    virtual QStringList handleSearchResponse(XmlQuery& lfm);\n\npublic slots:\n     void finishEdit(){ emit editingFinished(); }\nprivate slots:\n    void onGetFriendsFinished();\nprivate:\n    QList<lastfm::User> m_friends;\n};\n\n#endif\n\n"
  },
  {
    "path": "lib/unicorn/widgets/Seed.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SEED_H\n#define SEED_H\n\n#include <lastfm/global.h>\n#include <QListWidgetItem>\n\nclass Seed : public QObject\n{\n    Q_OBJECT\n    \npublic:\n#if 0\n\tSeed( class SeedListView* parent = 0 );\n\tSeed( const QString& name, SeedListView* parent = 0 );\n#endif\n    enum Type { \n        Undefined = -1,\n        ArtistType = 0, \n        TagType, \n        UserType, \n        PreDefinedType, \n        CustomType\n    };\n#if 0\n    void setupItem()\n    {}\n    \n\tstatic Seed* createFromMimeData( const class PlayableMimeData* data, SeedListView* parent = 0 );\n\t\n\tvoid setPlayableType( const Seed::Type t ){ m_type = t; }\n    Seed::Type playableType() const{ return m_type; }\n    \n    Qt::ItemFlags flags() const{ return Qt::ItemIsDragEnabled | Qt::ItemIsEnabled; }\n\n    QString rql() const{ return m_rql; }\n    \n    void fetchImage();\n    \n    void setPixmap( const QPixmap );\n    \n    void setRQL( const QString& rql ){ m_rql = rql; }\n    \n    void setIcon( const QIcon& i ){ m_icon = i; emit updated(); }\n    const QIcon& icon() const{ return m_icon; }\n    \n    void setName( const QString& name ){ m_name = name; emit updated(); }\n    const QString& name() const{ return m_name; }\n    \nsignals:\n    void updated();\n    \npublic slots:\n    void iconDataDownloaded();\n    \nprivate slots:\n    void onArtistSearchFinished( QNetworkReply* r );\n    \nprivate:\n    QPixmap cropToSize( const QPixmap, const QSize& ) const;\n    QPixmap overlayPixmap( const QPixmap source, const QPixmap overlay, const QPoint offset = QPoint( 0, 0)) const;\n    QString m_rql;\n    Type m_type;\n    QString m_name;\n    QIcon m_icon;\n#endif\n};\n\nQ_DECLARE_METATYPE( Seed::Type )\n\n#endif //SEED_H\n"
  },
  {
    "path": "lib/unicorn/widgets/SlidingStackedWidget.cpp",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n#include <QPropertyAnimation>\n#include <QParallelAnimationGroup>\n\n#include \"SlidingStackedWidget.h\"\n\nunicorn::SlidingStackedWidget::SlidingStackedWidget( QWidget* parent )\n    : QStackedWidget(parent),\n    m_speed( 200 ),\n    m_animationtype( QEasingCurve::OutQuart ),\n    m_vertical( false ),\n    m_now( 0 ),\n    m_next( 0 ),\n    m_pnow( QPoint(0,0) ),\n    m_active( false ),\n    m_index( 0 )\n{\n}\n\nvoid\nunicorn::SlidingStackedWidget::setAnimation(enum QEasingCurve::Type animationtype)\n{\n        m_animationtype = animationtype;\n}\n\nvoid\nunicorn::SlidingStackedWidget::slide( int index )\n{\n    m_index = index;\n\n    if ( !m_active )\n    {\n        if ( index > count() - 1 )\n            index = (index) % count();\n        else\n            index = ( index + count() ) % count();\n\n        slideWidget( widget( index ) );\n    }\n}\n\nvoid\nunicorn::SlidingStackedWidget::slideWidget( QWidget* newwidget )\n{\n    m_active=true;\n\n    enum t_direction directionhint;\n    int now=currentIndex();\t\t//currentIndex() is a function inherited from QStackedWidget\n    int next=indexOf(newwidget);\n\n    if ( now == next )\n    {\n        m_active=false;\n        emit currentChanged( currentIndex() );\n        return;\n    }\n    else if ( now < next )\n    {\n        directionhint = m_vertical ? TOP2BOTTOM : RIGHT2LEFT;\n    }\n    else\n    {\n        directionhint = m_vertical ? BOTTOM2TOP : LEFT2RIGHT;\n    }\n\n    //NOW....\n    //calculate the shifts\n\n    int offsetx=frameRect().width(); //inherited from mother\n    int offsety=frameRect().height();//inherited from mother\n\n    //the following is important, to ensure that the new widget\n    //has correct geometry information when sliding in first time\n    widget(next)->setGeometry ( 0,  0, offsetx, offsety );\n\n    if (directionhint==BOTTOM2TOP)\n    {\n        offsetx=0;\n        offsety=-offsety;\n    }\n    else if (directionhint==TOP2BOTTOM)\n    {\n        offsetx=0;\n        //offsety=offsety;\n    }\n    else if (directionhint==RIGHT2LEFT)\n    {\n        offsetx=-offsetx;\n        offsety=0;\n    }\n    else if (directionhint==LEFT2RIGHT)\n    {\n        //offsetx=offsetx;\n        offsety=0;\n    }\n    //re-position the next widget outside/aside of the display area\n    QPoint pnext=widget(next)->pos();\n    QPoint pnow=widget(now)->pos();\n    m_pnow=pnow;\n\n    widget(next)->move(pnext.x()-offsetx,pnext.y()-offsety);\n    //make it visible/show\n    widget(next)->show();\n    widget(next)->raise();\n\n    //animate both, the now and next widget to the side, using animation framework\n    QPropertyAnimation *animnow = new QPropertyAnimation(widget(now), \"pos\");\n\n    animnow->setDuration(m_speed);\n    animnow->setEasingCurve(m_animationtype);\n    animnow->setStartValue(QPoint(pnow.x(), pnow.y()));\n    animnow->setEndValue(QPoint(offsetx+pnow.x(), offsety+pnow.y()));\n    QPropertyAnimation *animnext = new QPropertyAnimation(widget(next), \"pos\");\n    animnext->setDuration(m_speed);\n    animnext->setEasingCurve(m_animationtype);\n    animnext->setStartValue(QPoint(-offsetx+pnext.x(), offsety+pnext.y()));\n    animnext->setEndValue(QPoint(pnext.x(), pnext.y()));\n\n    QParallelAnimationGroup *animgroup = new QParallelAnimationGroup;\n\n    animgroup->addAnimation(animnow);\n    animgroup->addAnimation(animnext);\n\n    QObject::connect(animgroup, SIGNAL(finished()),this,SLOT(animationDoneSlot()));\n    m_next=next;\n    m_now=now;\n    m_active=true;\n    animgroup->start();\n}\n\n\nvoid\nunicorn::SlidingStackedWidget::animationDoneSlot(void)\n{\n    setCurrentIndex( m_next );\n    widget(m_now)->hide();\n    widget(m_now)->move(m_pnow);\n    m_active = false;\n\n    // animate again if they changed index while we were animating\n    if ( m_index != currentIndex() )\n        slide( m_index );\n    else\n        emit animationFinished();\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/SlidingStackedWidget.h",
    "content": "/*\n   Copyright 2011 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef SLIDINGSTACKEDWIDGET_H\n#define SLIDINGSTACKEDWIDGET_H\n\n#include <QStackedWidget>\n#include <QEasingCurve>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn {\n\nclass UNICORN_DLLEXPORT SlidingStackedWidget : public QStackedWidget\n{\n        Q_OBJECT\n\npublic:\n        //! This enumeration is used to define the animation direction\n        enum t_direction {\n                LEFT2RIGHT,\n                RIGHT2LEFT,\n                TOP2BOTTOM,\n                BOTTOM2TOP,\n                AUTOMATIC\n        };\n\n        //! The Constructor and Destructor\n        explicit SlidingStackedWidget(QWidget *parent);\n\n        Q_PROPERTY( QEasingCurve::Type easingCurve READ easingCurve WRITE setEasingCurve )\n        Q_PROPERTY( int speed READ speed WRITE setSpeed )\n\n        QEasingCurve::Type easingCurve() const { return m_animationtype; }\n        void setEasingCurve( QEasingCurve::Type animationtype ) { m_animationtype = animationtype; }\n\n        int speed() const { return m_speed; }\n        void setSpeed( int speed ) { m_speed = speed; }\n\npublic slots:\n        //! Some basic settings API\n        void setAnimation(enum QEasingCurve::Type animationtype); //check out the QEasingCurve documentation for different styles\n\n        //! The Animation / Page Change API\n        void slide( int index  );\n\nsignals:\n        //! this is used for internal purposes in the class engine\n        void animationFinished(void);\n\nprotected slots:\n        //! this is used for internal purposes in the class engine\n        void animationDoneSlot(void);\n\nprotected:\n        //! this is used for internal purposes in the class engine\n        void slideWidget( QWidget * widget );\n\n        QWidget* m_mainwindow;\n\n        int m_speed;\n        enum QEasingCurve::Type m_animationtype;\n        bool m_vertical;\n        int m_now;\n        int m_next;\n        QPoint m_pnow;\n        bool m_active;\n\n        int m_index;\n};\n\n}\n\n#endif // SLIDINGSTACKEDWIDGET_H\n"
  },
  {
    "path": "lib/unicorn/widgets/SpinnerLabel.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef SPINNER_LABEL_H\n#define SPINNER_LABEL_H\n\n#include <QEvent>\n#include <QLabel> //TODO implementation\n#include <QMovie> //TODO implementation\n#include <QDebug>\n \nclass SpinnerLabel : public QLabel\n{\n    virtual bool event( QEvent* e )\n    {\n        switch ((int)e->type())\n        {\n        case QEvent::Hide:\n            m_movie->stop();\n            break;\n        case QEvent::Show:\n            m_movie->start();\n            break;\n        }\n\n        return QLabel::event( e );\n    }\n\n    QMovie* m_movie;\n\npublic:\n    SpinnerLabel( QWidget* parent = 0 ) : QLabel( parent )\n    {\n        setMovie( m_movie = new QMovie( \":/lastfm/spinner.mng\" ) );\n        m_movie->setParent( this );\n        //qt fucking sucks\n        setFixedSize( 25, 18 );\n    }\n};\n\n#endif //SPINNER_LABEL_H\n"
  },
  {
    "path": "lib/unicorn/widgets/StackedWidget.cpp",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"StackedWidget.h\"\n\nunicorn::StackedWidget::StackedWidget(QWidget *parent) :\n    QStackedWidget(parent)\n{\n    connect( this, SIGNAL(currentChanged(int)), SLOT(onCurrentChanged(int)));\n}\n\nQSize\nunicorn::StackedWidget::sizeHint() const\n{\n    return currentWidget()->sizeHint();\n}\n\nvoid\nunicorn::StackedWidget::onCurrentChanged( int index )\n{\n    for ( int i = 0 ; i < count() ; ++i )\n    {\n        if ( i == index )\n        {\n            widget( i )->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Preferred );\n            widget( i )->adjustSize();\n        }\n        else\n            widget( i )->setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );\n    }\n\n    adjustSize();\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/StackedWidget.h",
    "content": "/*\n   Copyright 2012 Last.fm Ltd.\n      - Primarily authored by Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef STACKEDWIDGET_H\n#define STACKEDWIDGET_H\n\n#include <QStackedWidget>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace unicorn\n{\n\nclass UNICORN_DLLEXPORT StackedWidget : public QStackedWidget\n{\n    Q_OBJECT\npublic:\n    explicit StackedWidget(QWidget *parent = 0);\n    \nprivate slots:\n    void onCurrentChanged( int index );\n\nprivate:\n    QSize sizeHint() const;\n};\n\n}\n\n#endif // STACKEDWIDGET_H\n"
  },
  {
    "path": "lib/unicorn/widgets/StatusLight.cpp",
    "content": "/***************************************************************************\n *   Copyright 2008 by P. Sereno                                           *\n *       http://www.sereno-online.com                                      *\n *       http://www.qt4lab.org                                             *\n *       http://www.qphoton.org                                            *\n *   Copyright 2009 Last.fm Ltd. <max@last.fm>                             *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n#include \"StatusLight.h\"\n#include <QDebug>\n#include <QFontMetrics>\n#include <QPainter>\n#include <QRadialGradient>\n\n\nStatusLight::StatusLight( QWidget* parent )\n           : QWidget( parent )\n{\n    m_color = Qt::green;\n\n    int const M = fontMetrics().height();\n    setFixedSize( M, M );\n}\n\n\nvoid StatusLight::paintEvent( QPaintEvent* )\n{\n\tQPainter p( this );\n\tp.setRenderHint( QPainter::Antialiasing, true );\n\tp.setWindow( -50,-50, 100, 100 );\n\t\n\tp.setPen( Qt::white );\n\tp.drawArc( -25, -25, 50, 50, 0, 5670 );\n\tp.drawArc( -32, -33, 66, 66, 0, 5670 );\n\tp.setPen( QColor(Qt::darkGray).lighter( 125 ) );\n\tp.drawArc( -34, -33, 66, 66, 0, 180*16 );\n\t\n    QRadialGradient radialGrad(QPointF(0, -14), 20);\n    radialGrad.setColorAt( 0, QColor( 0xff, 0xff, 0xff, 0.8 ) );\n    radialGrad.setColorAt( 1, m_color );\n\n    QBrush brush(radialGrad);\n    p.setBrush(brush);\n    p.setPen( m_color.darker() );\n    p.drawEllipse(-25,-25,50,50);\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/StatusLight.h",
    "content": "/***************************************************************************\n *   Copyright 2008 by P. Sereno                                           *\n *       http://www.sereno-online.com                                      *\n *       http://www.qt4lab.org                                             *\n *       http://www.qphoton.org                                            *\n *   Copyright 2009 Last.fm Ltd. <max@last.fm>                             *\n *                                                                         *\n *   This program is free software; you can redistribute it and/or modify  *\n *   it under the terms of the GNU General Public License as published by  *\n *   the Free Software Foundation; either version 2 of the License, or     *\n *   (at your option) any later version.                                   *\n *                                                                         *\n *   This program is distributed in the hope that it will be useful,       *\n *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *\n *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *\n *   GNU General Public License for more details.                          *\n *                                                                         *\n *   You should have received a copy of the GNU General Public License     *\n *   along with this program; if not, write to the                         *\n *   Free Software Foundation, Inc.,                                       *\n *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *\n ***************************************************************************/\n#ifndef STATUS_LIGHT_H\n#define STATUS_LIGHT_H\n\n#include \"lib/DllExportMacro.h\"\n#include <QColor>\n#include <QWidget>\n\nclass UNICORN_DLLEXPORT StatusLight : public QWidget\n{\n    QColor m_color;\n\npublic: \n    StatusLight( QWidget* parent = 0 );\n\t\n    void setColor( const QColor& c ) { m_color = c; }\n\nprotected:\n    void paintEvent( QPaintEvent* );\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/TagListWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"TagListWidget.h\"\n#include \"PlayableMimeData.h\"\n#include <lastfm/Tag.h>\n#include <lastfm/ws.h>\n#include <QDesktopServices>\n#include <QHeaderView>\n#include <QItemDelegate>\n#include <QMenu>\n#include <QUrl>\n\n#include \"lib/unicorn/DesktopServices.h\"\n\n\nTagListWidget::TagListWidget( QWidget* parent ) \n             : QTreeWidget( parent )\n\t\t\t , m_currentReply( 0 )\n{\n    setColumnCount( 2 );\n    setRootIsDecorated( false );\n    setContextMenuPolicy( Qt::CustomContextMenu );\n    setFrameStyle( NoFrame );\n    setAlternatingRowColors( true );\n    setDragEnabled( true );\n\n    class TallerRowDelegate : public QItemDelegate\n    {\n        virtual QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const\n        {\n            return QItemDelegate::sizeHint( option, index ) + QSize( 0, 4 );\n        }\n    };\n\n    setItemDelegate( new TallerRowDelegate );\n    \n    QTreeWidget::hideColumn( 1 );\n    QTreeWidget::header()->hide();\n    \n    m_menu = new QMenu( this );\n    QActionGroup* group = new QActionGroup( this );\n    \n    QAction* a = m_menu->addAction( tr( \"Sort by Popularity\" ) );\n    connect( a, SIGNAL(triggered()), SLOT(sortByPopularity()) );\n    group->addAction( a );\n    a->setCheckable( true );\n    a->setChecked( true );\n\n    a = m_menu->addAction( tr( \"Sort Alphabetically\" ) );\n    connect( a, SIGNAL(triggered()), SLOT(sortAlphabetically()) );\n    group->addAction( a );\n    a->setCheckable( true );\n    \n    m_menu->addSeparator();\n    a = m_menu->addAction( tr(\"Open Last.fm Page for this Tag\") );\n    connect( a, SIGNAL(triggered()), SLOT(openTagPageForCurrentItem()) );\n    \n    connect( this, SIGNAL(customContextMenuRequested( QPoint )), SLOT(showMenu( QPoint )) );\n    connect( this, SIGNAL(doubleClicked( const QModelIndex& )), SLOT(onDoubleClicked ( const QModelIndex& )) );\n}\n\n\nQTreeWidgetItem*\nTagListWidget::createNewItem( QString tag )\n{\n    tag = tag.toLower();\n    \n    QTreeWidgetItem* item = new QTreeWidgetItem( QStringList() << tag );\n    QIcon icon;\n    icon.addPixmap( QPixmap( \":/buckets/tag.png\" ) );\n    item->setIcon( 0, icon );\n\n    addTopLevelItem( item );\n\n    return item;\n}\n\n\nbool\nTagListWidget::add( QString tag )\n{\n    //FIXME avoid duplicates\n    createNewItem( tag );\n    m_newTags += tag;\n    return true;\n}\n\n\nvoid\nTagListWidget::showMenu( const QPoint& point )\n{\n    m_menu->exec( mapToGlobal( point ) );\n}\n\n\nvoid\nTagListWidget::sortAlphabetically()\n{\n    sortItems( 0, Qt::AscendingOrder );\n}\n\n\nvoid\nTagListWidget::sortByPopularity()\n{\n    //I got here and wasn't sure if sortItems() should be used instead either --mxcl\n    sortByColumn( 1, Qt::DescendingOrder );\n}\n\n\nvoid\nTagListWidget::openTagPageForCurrentItem()\n{\n\tunicorn::DesktopServices::openUrl( Tag( currentItem()->text( 0 ) ).www() );\n}\n\n\nvoid\nTagListWidget::setTagsRequest( QNetworkReply* r )\n{\n    clear();\n\tdelete m_currentReply;\n\tm_currentReply = r;\n    connect( r, SIGNAL(finished()), SLOT(onTagsRequestFinished()) );\n}\n\n\nvoid\nTagListWidget::onTagsRequestFinished()\n{   \n    QNetworkReply* r = (QNetworkReply*)sender();\n    \n    QMap<int, QString> tags = Tag::list( r );\n    QMapIterator<int, QString> i( tags );\n    while (i.hasNext())\n\t{\n        QTreeWidgetItem *entry = createNewItem( i.next().value() );\n\t\t// I couldn't make it sort properly otherwise, even the QVariant methods wouldn't work!\n\t\tentry->setText( 1, QString::number( 10 * 1000 + i.key() ) );\n\t}\n\tm_currentReply = 0;\n}\n\n\nQMimeData* \nTagListWidget::mimeData( const QList<QTreeWidgetItem *> items ) const\n{\n    if( items.count() < 1 )\n        return 0;\n    \n    Tag tag( items.first()->text( 0 ) );\n    PlayableMimeData* pData = PlayableMimeData::createFromTag( tag );\n    \n    return pData;\n}\n\n\n#include <QPainter>\nTagIconView::TagIconView()\n{\n    setAlternatingRowColors( false );\n    disconnect( this, SIGNAL(customContextMenuRequested( QPoint )), 0, 0 );\n}\n\n\nvoid\nTagIconView::paintEvent( QPaintEvent* e )\n{    \n    TagListWidget::paintEvent( e );\n\n    if (topLevelItemCount()) \n        return;\n    \n    QPainter p( viewport() );\n    p.setPen( Qt::lightGray );\n#ifndef WIN32\n    QFont f = p.font();\n    f.setPixelSize( 15 );\n    p.setFont( f );\n#endif\n    p.drawText( viewport()->rect(), Qt::AlignCenter, tr(\"Type a tag above,\\nor choose from below\") );\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/TagListWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TAGLISTWIDGET_H\n#define TAGLISTWIDGET_H\n\n#include <QTreeWidget>\n#include \"PlayableMimeData.h\"\n\n\nclass TagListWidget : public QTreeWidget\n{\n    Q_OBJECT\n\npublic:\n    TagListWidget( QWidget* parent = 0 );\n    \n    using QTreeWidget::indexFromItem;\n    \n    /** we won't add the tag if we already have it, and in that case we \n      * return false */\n    bool add( QString );\n    QStringList newTags() const { return m_newTags; }\n\npublic slots:\n    void setTagsRequest( QNetworkReply* );\n    \nprotected:\n    virtual QMimeData* mimeData( const QList<QTreeWidgetItem *> items ) const;\n    \nprivate slots:\n    void onTagsRequestFinished();\n    \nprivate:\n    class QMenu* m_menu;\n    QStringList m_newTags;\n\tQNetworkReply *m_currentReply;\n\n    QTreeWidgetItem* createNewItem( QString tag );\n\nprivate slots:\n    void showMenu( const QPoint& );\n    \n    void sortByPopularity();\n    void sortAlphabetically();\n    void openTagPageForCurrentItem();\n};\n\n\nclass TagIconView : public TagListWidget\n{\n    virtual void paintEvent( QPaintEvent* );\n\npublic:\n    TagIconView();\n};\n\n#endif // TAGLISTWIDGET_H\n"
  },
  {
    "path": "lib/unicorn/widgets/TrackWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"TrackWidget.h\"\n#include \"lib/unicorn/TrackImageFetcher.h\"\n#include <QHBoxLayout>\n#include <QVBoxLayout>\n#include <QLabel>\n#include <QStackedWidget>\n#include <QRadioButton>\n#include <QPixmap>\n\n\nTrackWidget::TrackWidget( const lastfm::Track& track )\n    :m_track( track )\n{    \n    // the radio buttons layout\n    QVBoxLayout* radioButtons = new QVBoxLayout;\n\n    radioButtons->addWidget( ui.trackShare = new QRadioButton( tr(\"Track\"), this ) );\n    radioButtons->addWidget( ui.albumShare = new QRadioButton( tr(\"Album\"), this ) );\n    radioButtons->addWidget( ui.artistShare = new QRadioButton( tr(\"Artist\"), this ) );\n\n    connect( ui.artistShare, SIGNAL(clicked(bool)), SLOT(onRadioButtonsClicked(bool)) );\n    connect( ui.albumShare, SIGNAL(clicked(bool)), SLOT(onRadioButtonsClicked(bool)) );\n    connect( ui.trackShare, SIGNAL(clicked(bool)), SLOT(onRadioButtonsClicked(bool)) );\n\n    QHBoxLayout* h = new QHBoxLayout( this );\n    h->addLayout( radioButtons );\n    h->addWidget( ui.image = new QLabel, Qt::AlignLeft );\n    h->addWidget( ui.description = new QLabel, Qt::AlignLeft );\n\n    ui.image->setScaledContents( true );\n\n    // start fetching the image\n    m_fetcherAlbum = new TrackImageFetcher( track, Track::MediumImage );\n    connect( m_fetcherAlbum, SIGNAL(finished( QPixmap )), SLOT(onCoverDownloaded( QPixmap )) );\n    m_fetcherAlbum->startAlbum();\n\n    // start fetching the image\n    m_fetcherArtist = new TrackImageFetcher( track, Track::MediumImage );\n    connect( m_fetcherArtist, SIGNAL(finished( QPixmap )), SLOT(onArtistDownloaded( QPixmap )) );\n    m_fetcherArtist->startArtist();\n\n    // default the track being selected\n    ui.trackShare->setChecked( true );\n    onRadioButtonsClicked( true );\n\n    // we sometimes don't know the album name so disable the ablum option in that case\n    if ( m_track.album().isNull() ) ui.albumShare->setEnabled( false );\n\n    ui.image->setFixedSize( radioButtons->sizeHint().height(), radioButtons->sizeHint().height() );\n    \n    setFixedWidth( 400 );\n}\n\nvoid\nTrackWidget::onRadioButtonsClicked( bool )\n{\n    QFontMetrics fm( font() );\n    // change the share desription to what we are now sharing\n    if ( ui.artistShare->isChecked() )\n    {\n        QString artistName = fm.elidedText( m_track.artist().name(), Qt::ElideRight, ui.description->width() );\n        ui.description->setText( artistName + \"\\n\" );\n        ui.description->setToolTip( m_track.artist().name() );\n        ui.image->setPixmap( ui.artistImage );\n    }\n    else if ( ui.albumShare->isChecked() )\n    {\n        QString albumTitle = fm.elidedText( m_track.album().title(), Qt::ElideRight, ui.description->width() );\n        QString artistName = fm.elidedText( m_track.artist().name(), Qt::ElideRight, ui.description->width() );\n        ui.description->setText( albumTitle + \"\\n\" + artistName );\n        ui.description->setToolTip( m_track.album().title() + \"\\n\" + m_track.artist().name() );\n        ui.image->setPixmap( ui.albumImage );\n    }\n    else if ( ui.trackShare->isChecked() )\n    {\n        QString durationString = \" (\" + m_track.durationString() + \")\\n\";\n        int durationWidth = fm.width( durationString );\n        QString title = fm.elidedText( m_track.title(), Qt::ElideRight, ui.description->width() - durationWidth );\n        QString artistName = fm.elidedText( m_track.artist().name(), Qt::ElideRight, ui.description->width() );\n        ui.description->setText(  title + durationString + artistName );\n        ui.description->setToolTip( m_track.title() + durationString + m_track.artist().name() );\n        ui.image->setPixmap( ui.artistImage );\n    }\n}\n\nTrackWidget::Type\nTrackWidget::type() const\n{\n    if ( ui.artistShare->isChecked() )\n        return Artist;\n    else if ( ui.albumShare->isChecked() )\n        return Album;\n\n    return Track;\n}\n\nvoid\nTrackWidget::onCoverDownloaded( const QPixmap& pixmap )\n{\n    ui.albumImage = pixmap;\n\n    onRadioButtonsClicked( true );\n\n    sender()->deleteLater();\n}\n\nvoid\nTrackWidget::onArtistDownloaded( const QPixmap& pixmap )\n{\n    ui.artistImage = pixmap;\n\n    onRadioButtonsClicked( true );\n\n    sender()->deleteLater();\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/TrackWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef TRACK_WIDGET_H\n#define TRACK_WIDGET_H\n\n#include <lastfm/global.h>\n#include <lastfm/Track.h>\n#include <QWidget>\n#include \"lib/DllExportMacro.h\"\n#include <QStackedWidget>\n\nclass UNICORN_DLLEXPORT TrackWidget : public QWidget\n{\n    Q_OBJECT   \npublic:\n    enum Type\n    {\n        Artist,\n        Album,\n        Track\n    } m_type;\n\nprivate:\n    struct\n    {\n        class QRadioButton* trackShare;\n        class QRadioButton* albumShare;\n        class QRadioButton* artistShare;\n        class QLabel* image;\n        class QLabel* description;\n        class QPixmap artistImage;\n        class QPixmap albumImage;\n    } ui;\n\npublic:\n    TrackWidget( const lastfm::Track& track );\n\n    Type type() const;\n    \nprivate slots:\n    void onCoverDownloaded( const class QPixmap& );\n    void onArtistDownloaded( const class QPixmap& );\n\n    void onRadioButtonsClicked( bool );\n\nprivate:\n    const lastfm::Track& m_track;\n\n    class TrackImageFetcher* m_fetcherAlbum;\n    class TrackImageFetcher* m_fetcherArtist;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/UnicornTabWidget.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QMouseEvent>\n#include <QPainter>\n#include <QTabBar>\n#include <QHBoxLayout>\n#include <QApplication>\n\n#include \"UnicornTabWidget.h\"\n\nconst int unicorn::TabBar::k_startTearDistance = 30;\n\nunicorn::TabBar::TabBar()\n        :m_spacing( 0 ),\n         m_leftMargin( 5 ),\n         m_active( \":/DockWindow/tab/active.png\" )\n{\n#ifndef WIN32\n    QFont f = font();\n    f.setPixelSize( 10 );\n    f.setBold( true );\n    setFont( f );\n#endif\n\n    QPalette p = palette();\n    \n    QLinearGradient window( 0, 0, 0, sizeHint().height());\n    window.setColorAt( 0, 0x3c3939 );\n    window.setColorAt( 1, 0x282727 );\n    p.setBrush( QPalette::Window, window );\n    \n    QPixmap pm = m_active.copy( (m_active.width() / 2)-1, 0, 2, m_active.height());\n    p.setBrush( QPalette::Button, pm );\n    \n    QLinearGradient buttonHighlight( 0, 0, 0, sizeHint().height() - 14 );\n    buttonHighlight.setColorAt( 0, Qt::black );\n    buttonHighlight.setColorAt( 1, 0x474243 );\n    p.setBrush( QPalette::Midlight, buttonHighlight );\n    \n    p.setColor( QPalette::Active, QPalette::Text, 0x848383 );\n    p.setColor( QPalette::Inactive, QPalette::Text, 0x848383 );\n    setPalette( p );\n    \n    setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Fixed );\n    setFixedHeight( 33 );\n    setMinimumHeight( 33 );\n    \n    new QHBoxLayout( this );\n    layout()->setContentsMargins( 0, 0, 5, 0 );\n    ((QHBoxLayout*)layout())->addStretch( 1 );\n   \n    setAutoFillBackground( true );\n}\n\n\nQSize\nunicorn::TabBar::sizeHint() const\n{\n    return QSize( minimumWidth(), 33 );\n}\n\n\nvoid\nunicorn::TabBar::mousePressEvent( QMouseEvent* e )\n{\n    if (e->button() != Qt::LeftButton) {\n        e->ignore();\n        return;\n    }\n    \n    m_mouseDownPos = e->pos();\n    \n    int w = (minimumWidth() - layout()->minimumSize().width() - m_leftMargin) / count();\n    \n    int index = ( (e->pos().x() - m_leftMargin ) / (w + m_spacing ));\n\n    if( index < count() )\n        setCurrentIndex( index );\n}\n\n\nvoid \nunicorn::TabBar::mouseReleaseEvent( QMouseEvent* )\n{\n    m_mouseDownPos = QPoint();\n}\n\nvoid \nunicorn::TabBar::mouseMoveEvent( QMouseEvent* e )\n{\n    if( !m_tearable )\n        return;\n        \n    if( !(e->buttons() & Qt::LeftButton) || m_mouseDownPos.isNull() )\n        return;\n        \n    if( (e->pos() - m_mouseDownPos ).manhattanLength() < \n        k_startTearDistance)\n        return;\n        \n    TabWidget* tabWidget = qobject_cast<TabWidget*>( parentWidget() );\n    if( !tabWidget )\n        return;\n        \n    int index = currentIndex();\n    removeTab( index );\n\n    QWidget* curWidget = tabWidget->widget( index );\n    if( !curWidget )\n        return;\n        \n    QPoint offset = curWidget->mapToGlobal(curWidget->pos()) - QCursor::pos();\n    curWidget->setParent( window(), Qt::Tool );\n    curWidget->move( QCursor::pos() + QPoint(offset.x(), 0));\n    curWidget->resize( tabWidget->size());\n    curWidget->show();\n    m_tearable = false;\n    while( QApplication::mouseButtons() & Qt::LeftButton )\n    {\n        if( curWidget->pos() != QCursor::pos())\n            curWidget->move( QCursor::pos() + QPoint(offset.x(), 0));\n        QApplication::processEvents( QEventLoop::WaitForMoreEvents );\n    }\n    curWidget->installEventFilter( this );\n    m_tearable = true;\n    m_mouseDownPos = QPoint();\n}\n\n\nvoid\nunicorn::TabBar::tabInserted( int )\n{\n    int w = 0;\n    for (int i = 0; i < count(); ++i)\n        w = qMax( fontMetrics().width( tabText( i ) ), w );\n    setMinimumWidth( (m_leftMargin + (count() * ( w + 20 ))) + 10 + layout()->minimumSize().width());\n}\n\n\nvoid\nunicorn::TabBar::tabRemoved( int i )\n{\n    tabInserted( i );\n}\n\n\nvoid \nunicorn::TabBar::addWidget( QWidget* wi )\n{\n    layout()->addWidget( wi );\n    int w = 0;\n    for (int i = 0; i < count(); ++i)\n        w = qMax( fontMetrics().width( tabText( i ) ), w );\n    setMinimumWidth(  (m_leftMargin + (count() * ( w + 20 ))) + 10 + layout()->minimumSize().width());\n}\n\n\nvoid\nunicorn::TabBar::paintEvent( QPaintEvent* e )\n{\n    QPainter p( this );\n    \n    p.setClipRect( e->rect());\n    if( count() <= 0 )\n        return;\n        \n    int w = (minimumWidth() - layout()->minimumSize().width() - m_leftMargin) / count();\n    for (int i = 0; i < count(); ++i)\n    {\n        int const x = m_leftMargin + (i * ( w + m_spacing ));\n        \n        if (i == count() - 1)\n            w += (minimumWidth() - layout()->minimumSize().width() - m_leftMargin + 10) % w;\n        \n        if (currentIndex() == i)\n        {\n            p.setBrush( palette().brush( QPalette::Button ) );\n            p.drawPixmap( x, 7, 8, m_active.height(), m_active, 0, 0, 8, m_active.height() );\n            p.drawPixmap( x + 8, 7, w -16, m_active.height(), palette().brush( QPalette::Button ).texture());\n            p.drawPixmap( x + w - 8, 7, 9, m_active.height(), m_active, m_active.width() / 2, 0, 9, m_active.height() );\n            p.setPen( palette().color( QPalette::Active, QPalette::Text ) );\n        }\n        else\n        {\n            p.setPen( palette().color( QPalette::Inactive, QPalette::Text ) );\n        }\n                \n        p.drawText( x, -1, w, height(), Qt::AlignCenter, tabText( i ) );\n    }\n    \n    const int h = height() - 1;\n    p.setPen( QPen( Qt::black, 0 ) );\n    p.setRenderHint( QPainter::Antialiasing, false );\n    p.drawLine( 0, h, width(), h );   \n}\n\n\nvoid \nunicorn::TabBar::setSpacing( int spacing )\n{\n    m_spacing = spacing;\n}\n\n\nbool \nunicorn::TabBar::eventFilter( QObject* o, QEvent* e )\n{\n    if( e->type() != QEvent::Close )\n        return false;\n    \n    QWidget* w;\n    if( !( w = qobject_cast< QWidget* >( o )))\n        return false;\n        \n    if( w->windowTitle().isEmpty())\n        return false;\n        \n    ((TabWidget*)parentWidget())->addTab( w );\n    w->removeEventFilter( this );\n    return true;\n}\n\n\n\nunicorn::TabWidget::TabWidget()\n{\n    QVBoxLayout* v = new QVBoxLayout( this );\n    v->addWidget( m_bar = new TabBar );\n//    m_bar->setSpacing( 3 );\n    v->addWidget( m_stack = new QStackedWidget );\n    v->setSpacing( 0 );\n    v->setMargin( 0 );\n    \n    setAutoFillBackground( true );\n    \n    QPalette p = palette();\n    p.setBrush( QPalette::Window, QBrush( 0x0e0e0e ) );\n    setPalette( p );\n    \n    setSizePolicy( QSizePolicy::Minimum, QSizePolicy::Preferred );\n    \n    connect( m_bar, SIGNAL(currentChanged( int )), m_stack, SLOT(setCurrentIndex( int )) );\n    connect( m_bar, SIGNAL(currentChanged( int )), SIGNAL(currentChanged(int)));\n}\n\n\nvoid\nunicorn::TabWidget::addTab( const QString& title, QWidget* w )\n{\n    m_bar->addTab( title );\n    setMinimumWidth( m_bar->minimumWidth());\n    m_stack->addWidget( w );\n    w->setAttribute( Qt::WA_MacShowFocusRect, false );\n}\n\n\nvoid \nunicorn::TabWidget::addTab( QWidget* w )\n{\n    Q_ASSERT( !w->windowTitle().isEmpty());\n    addTab( w->windowTitle(), w );\n}\n\n\nvoid \nunicorn::TabWidget::setTabEnabled( int index, bool b )\n{\n    m_bar->setTabEnabled( index, b );\n}\n\n\nQWidget* \nunicorn::TabWidget::widget( int index ) const\n{\n    return m_stack->widget( index );\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/UnicornTabWidget.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef UNICORN_TAB_WIDGET_H\n#define UNICORN_TAB_WIDGET_H\n\n#include <QPixmap>\n#include <QStackedWidget>\n#include <QTabBar>\n\n#include <QDebug>\nnamespace unicorn\n{\n    class TabBar : public QTabBar\n    {\n        friend class UnicornMacStyle;\n        \n    public:\n        TabBar();\n        \n        virtual QSize sizeHint() const;\n        void setSpacing( int );\n        void setTearable( bool t ){ m_tearable = t; }\n        void addWidget( QWidget* w );\n        \n    protected:\n        virtual void mousePressEvent( QMouseEvent* );\n        virtual void mouseReleaseEvent( QMouseEvent* );\n        virtual void mouseMoveEvent( QMouseEvent* );\n        virtual void paintEvent( QPaintEvent* );\n        virtual void tabInserted( int );\n        virtual void tabRemoved( int );\n        virtual bool eventFilter(QObject* , QEvent* );\n        \n        int m_spacing;\n        const int m_leftMargin;\n        const QPixmap m_active;\n        \n    private:\n        QPoint m_mouseDownPos;\n        bool m_tearable;\n        static const int k_startTearDistance;\n    };\n    \n    \n    class TabWidget : public QWidget\n    {\n        Q_OBJECT\n        QStackedWidget* m_stack;\n        TabBar* m_bar;\n        \n    public:\n        TabWidget();\n        \n        TabBar* bar() const { return m_bar; }\n        \n        void addTab( const QString& title, QWidget* );\n        void addTab( QWidget* );\n        QWidget* currentWidget() const { return m_stack->currentWidget(); }\n        virtual QSize sizeHint() const { return QWidget::sizeHint().expandedTo( m_bar->sizeHint() ); }\n        \n        void setTabEnabled( int index, bool );\n        void setTearable( bool t ){ bar()->setTearable( t ); }\n        QWidget* widget( int index ) const;\n\n    signals:\n        void currentChanged( int );\n\n    };\n}\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/UserComboSelector.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole, William Viana Soares and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef USER_COMBO_SELECTOR_H_\n#define USER_COMBO_SELECTOR_H_\n\n#include <QComboBox>\n#include <QStandardItemModel>\n#include <lastfm/User.h>\n#include \"lib/DllExportMacro.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\nclass UNICORN_DLLEXPORT UserComboSelector : public QComboBox\n{\n    Q_OBJECT\npublic:\n    UserComboSelector( QWidget* p = 0 )\n    :QComboBox( p )\n    {\n        setStyle( qApp->style());\n        refresh();\n\n\n        connect( this, SIGNAL( activated( int)), SLOT( onActivated( int )));\n        connect( qApp, SIGNAL( rosterUpdated()), SLOT( refresh()));\n        connect( qApp, SIGNAL( sessionChanged( unicorn::Session, unicorn::Session ))\n                     , SLOT( onSessionChanged( unicorn::Session )));\n\n    }\n\nprotected:\n    void changeUser( const QString& username )\n    {\n        unicorn::UserSettings us( username );\n\n        QString sessionKey = us.value( \"sessionKey\", \"\" ).toString();\n        QMetaObject::invokeMethod( qApp, \"changeSession\",\n                                         Q_ARG( const QString, username ),\n                                         Q_ARG( const QString, sessionKey ) );\n\n    }\n\nprotected slots:\n    void onSessionChanged( unicorn::Session& s )\n    {\n        int index = findText( s.user().name() );\n        setCurrentIndex( index );\n    }\n\n    void onActivated( int index )\n    {\n        if( itemData( index ).toBool())\n            return changeUser( itemText( index ));\n        \n        //Reset current user as selected item\n        refresh();\n\n        //show manage users dialog\n        QMetaObject::invokeMethod( qApp, \"manageUsers\", Qt::DirectConnection );\n\n        //Reset user list / selected user\n        refresh();\n    }\n\n\n    void refresh()\n    {\n        clear();\n        foreach( User u, unicorn::Settings().userRoster() ) {\n            addItem( u.name(), true );\n        }\n\n        insertSeparator( count());  //why is there no addSeparator?!\n        addItem( \"Manage Users\", false );\n\n        onSessionChanged( qobject_cast<unicorn::Application*>(qApp)->currentSession() );\n    }\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/UserManagerWidget.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole, William Viana Soares and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UserManagerWidget.h\"\n\n#include \"lib/unicorn/widgets/AvatarWidget.h\"\n#include \"lib/unicorn/dialogs/LoginContinueDialog.h\"\n#include \"lib/unicorn/dialogs/LoginDialog.h\"\n#include \"lib/unicorn/LoginProcess.h\"\n#include \"lib/unicorn/QMessageBoxBuilder.h\"\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\n#include <lastfm/User.h>\n\n#include <QApplication>\n#include <QButtonGroup>\n#include <QDebug>\n#include <QDialogButtonBox>\n#include <QGroupBox>\n#include <QHBoxLayout>\n#include <QLabel>\n#include <QMouseEvent>\n#include <QPushButton>\n#include <QTimer>\n#include <QVBoxLayout>\n\nusing lastfm::User;\nUserRadioButton::UserRadioButton( const User& user )\n{\n    addWidget( ui.button = new QRadioButton() );\n    ui.button->setObjectName( \"button\" );\n\n    addWidget( ui.image = new AvatarWidget() );\n    ui.image->setObjectName( \"image\" );\n\n    QVBoxLayout* userTextLayout = new QVBoxLayout();\n    userTextLayout->setContentsMargins( 0, 0, 0, 0 );\n    userTextLayout->setSpacing( 0 );\n\n    userTextLayout->addWidget( ui.username = new QLabel( user.name() ) );\n    userTextLayout->addWidget( ui.realName = new QLabel() );\n    userTextLayout->addWidget( ui.loggedIn = new QLabel() );\n    ui.realName->setObjectName( \"realname\" );\n    addLayout(userTextLayout);\n\n    addStretch();\n\n    addWidget( ui.remove = new QPushButton( tr(\"Remove\") ));\n\n    setUser( user );\n\n    if( user.imageUrl( User::MediumImage ).isEmpty() )\n    {\n        QNetworkReply* reply = User::getInfo( user.name() );\n        connect( reply, SIGNAL(finished()), SLOT( onUserFetched()));\n    }\n\n\n    connect( ui.button, SIGNAL(clicked()), this, SIGNAL(clicked()) );\n    connect( ui.remove, SIGNAL(clicked()), this, SIGNAL(remove()) );\n\n    connect( qApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onSessionChanged(unicorn::Session)) );\n}\n\nvoid\nUserRadioButton::onSessionChanged( const unicorn::Session& session )\n{\n    if( ui.username->text() == session.user().name() )\n        ui.loggedIn->setText( tr( \"(currently logged in)\" ) );\n    else\n        ui.loggedIn->clear();\n}\n\nvoid\nUserRadioButton::click()\n{\n    ui.button->click();\n}\n\nbool\nUserRadioButton::isChecked() const\n{\n    return ui.button->isChecked();\n}\n\nvoid\nUserRadioButton::setUser( const lastfm::User& user )\n{\n    ui.username->setText( user.name() );\n\n    if( !user.realName().isEmpty() )\n        ui.realName->setText( QString( \"(%1)\" ).arg( user.realName() ) );\n\n    if( user == User() )\n        ui.loggedIn->setText( tr( \"(currently logged in)\" ) );\n\n    if ( !user.imageUrl( User::MediumImage ).isEmpty() )\n            ui.image->loadUrl( user.imageUrl( User::MediumImage ) );\n\n    ui.image->setHref( user.www() );\n}\n\nvoid \nUserRadioButton::onUserFetched()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>( sender());\n    Q_ASSERT( reply );\n\n    XmlQuery lfm;\n    if ( lfm.parse( reply ) )\n    {\n        User user( lfm[\"user\"] );\n        setUser( user );\n    }\n    else\n    {\n        qDebug() << lfm.parseError().message() << lfm.parseError().enumValue();\n    }\n}\n\n\nconst QString \nUserRadioButton::user() const\n{\n    return ui.username->text();\n}\n\n\nUserManagerWidget::UserManagerWidget( QWidget* parent )\n    :QWidget( parent )\n{\n    m_lcd = new LoginContinueDialog( this );\n    connect( m_lcd, SIGNAL( accepted()), SLOT( onLoginContinueDialogAccepted()));\n\n    QVBoxLayout* layout = new QVBoxLayout( this );\n    layout->setSpacing( 10 );\n\n    layout->addWidget( ui.groupBox = new QGroupBox() );\n\n    ui.usersLayout = new QVBoxLayout( ui.groupBox );\n\n    ui.groupBox->setTitle( tr( \"Connected User Accounts:\" ));\n\n    QHBoxLayout* buttonLayout = new QHBoxLayout();\n\n    ui.addUserButton = new QPushButton( tr( \"Add New User Account\" ), this );\n\n    buttonLayout->addWidget( ui.addUserButton );\n    buttonLayout->addStretch( 1 );\n\n    layout->addLayout( buttonLayout );\n\n    layout->addStretch();\n\n    QList<lastfm::User> roster = unicorn::Settings().userRoster();\n\n    foreach( lastfm::User u, roster )\n    {\n        UserRadioButton* b = new UserRadioButton( u );\n        add( b, false );\n    }\n\n    connect( ui.addUserButton, SIGNAL( clicked() ), SLOT( onAddUserClicked() ) );\n}\n\n\nUserManagerWidget::~UserManagerWidget()\n{\n}\n\nvoid\nUserManagerWidget::onAddUserClicked()\n{\n    LoginDialog* ld = new LoginDialog( this );\n    ld->setWindowFlags( Qt::Sheet );\n    ld->open();\n    connect( ld, SIGNAL( accepted()), SLOT( onLoginDialogAccepted()) );\n}\n\n\nvoid\nUserManagerWidget::onLoginDialogAccepted()\n{\n    LoginDialog* ld = qobject_cast<LoginDialog*>(sender());\n    Q_ASSERT( ld );\n\n    if ( m_loginProcess )\n    {\n        delete m_loginProcess;\n        m_loginProcess = 0;\n    }\n\n    m_loginProcess = new unicorn::LoginProcess( this );\n\n    ld->deleteLater();\n\n    connect( qApp, SIGNAL(sessionChanged(unicorn::Session)), SLOT(onLoginComplete(unicorn::Session)) );\n\n    m_loginProcess->authenticate();\n\n    m_lcd->setWindowFlags( Qt::Sheet );\n    m_lcd->open();\n}\n\n\nvoid\nUserManagerWidget::onLoginComplete( const unicorn::Session& session )\n{\n    Q_ASSERT( m_loginProcess );\n\n    disconnect( qApp, SIGNAL(sessionChanged(unicorn::Session)), this, SLOT(onLoginComplete(unicorn::Session)) );\n\n    if ( session.user().name().isEmpty() )\n    {\n        return;\n    }\n\n    bool alreadyAdded = false;\n    foreach ( UserRadioButton* b, findChildren<UserRadioButton*>() )\n    {\n        if ( session.user().name() == b->user() )\n        {\n            alreadyAdded = true;\n            break;\n        }\n    }\n\n    if ( !alreadyAdded )\n    {\n        User user( session.user().name() );\n        UserRadioButton* urb = new UserRadioButton( user );\n\n        add( urb );\n        if( ui.groupBox->layout()->count() <= 1 )\n            urb->click();\n    }\n    else\n    {\n        QMessageBoxBuilder( this )\n                    .setIcon( QMessageBox::Information )\n                    .setTitle( tr( \"Add User Error\" ) )\n                    .setText( tr( \"This user has already been added.\" ) )\n                    .exec();\n\n    }\n}\n\nvoid \nUserManagerWidget::onLoginContinueDialogAccepted()\n{\n    m_loginProcess->getSession();\n}\n\nvoid\nUserManagerWidget::onUserRemoved()\n{\n    UserRadioButton* urb = qobject_cast<UserRadioButton*>(sender());\n\n    int result =\n        QMessageBoxBuilder( parentWidget() ).setTitle( tr( \"Removing %1\" ).arg( urb->user() ) )\n                                  .setText( tr( \"Are you sure you want to remove this user? All user settings will be lost and you will need to re authenticate in order to scrobble in the future.\" ))\n                                  .setIcon( QMessageBox::Question )\n                                  .setButtons( QMessageBox::Yes | QMessageBox::No )\n                                  .exec();\n\n    if( result != QMessageBox::Yes )\n        return;\n\n    unicorn::Settings settings;\n    settings.beginGroup( \"Users\" );\n    settings.remove( urb->user() );\n    settings.endGroup();\n\n    if ( settings.userRoster().count() == 0 )\n    {\n        settings.setFirstRunWizardCompleted( false );\n        qobject_cast<unicorn::Application*>( qApp )->restart();\n    }\n\n    // if this is the currently logged in user we will have to choose someone else\n    if( urb->ui.button->isChecked() )\n    {\n        for ( int i = 0 ; i < ui.usersLayout->count() ; ++i )\n        {\n            UserRadioButton* button = qobject_cast<UserRadioButton*>(ui.usersLayout->itemAt( i )->layout());\n\n            if ( button->user() != urb->user() )\n            {\n                // This is the first user in the list that are not deleting!\n\n                button->click();\n\n                unicorn::Settings s;\n                s.setValue( \"Username\", button->user() );\n\n                unicorn::UserSettings us( button->user() );\n                QString sessionKey = us.value( \"SessionKey\", \"\" ).toString();\n                qobject_cast<unicorn::Application *>( qApp )->changeSession( button->user(), sessionKey, true );\n\n                break;\n            }\n        }\n    }\n\n    for ( int i = 0 ; i < layout()->count() ; ++i )\n    {\n        QLayoutItem* item = layout()->itemAt( i );\n\n        if ( qobject_cast<UserRadioButton*>( item->widget() ) == urb )\n        {\n            delete layout()->takeAt( i );\n            break;\n        }\n    }\n\n    urb->deleteLater();\n}\n\nvoid \nUserManagerWidget::add( UserRadioButton* urb, bool announce )\n{\n    ui.usersLayout->addLayout( urb );\n\n    if ( urb->user() == User().name() )\n        urb->click();\n\n    connect( urb, SIGNAL(remove()), SLOT(onUserRemoved()));\n    connect( urb, SIGNAL( clicked() ), this, SIGNAL( userChanged() ) );\n\n    if ( announce )\n        emit rosterUpdated();\n\n    connect( urb, SIGNAL( destroyed(QObject*)), SIGNAL( rosterUpdated()));\n}\n\n\nUserRadioButton*\nUserManagerWidget::checkedButton() const\n{\n    for ( int i = 0 ; i < ui.usersLayout->count() ; ++i )\n    {\n        UserRadioButton* button = qobject_cast<UserRadioButton*>(ui.usersLayout->itemAt( i )->layout());\n\n        if ( button && button->isChecked() )\n        {\n            return button;\n        }\n    }\n\n    return 0;\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/UserManagerWidget.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole, William Viana Soares and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef USER_MANAGER_WIDGET_H_\n#define USER_MANAGER_WIDGET_H_\n\n#include <QLayout>\n#include <QRadioButton>\n#include <QPointer>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace lastfm{ class User; }\nnamespace unicorn\n{\n    class LoginProcess;\n    class Session;\n}\n\nclass LoginContinueDialog;\n\nclass QAbstractButton;\nclass QButtonGroup;\nclass QFrame;\nclass QLabel;\nclass QPushButton;\nclass QVBoxLayout;\n\nclass UNICORN_DLLEXPORT UserRadioButton : public QHBoxLayout\n{\nQ_OBJECT\n\n    friend class UserManagerWidget;\n\npublic:\n    UserRadioButton( const lastfm::User& user );\n    const QString user() const;\n\n    void click();\n    bool isChecked() const;\n\nsignals:\n    void clicked();\n    void remove();\n\nprivate:\n    void setUser( const lastfm::User& user );\n\nprivate slots:\n    void onUserFetched();\n    void onSessionChanged( const unicorn::Session& session );\n\nprivate:\n    struct\n    {\n        QRadioButton* button;\n        QPushButton* remove;\n        QLabel* username;\n        QLabel* realName;\n        QLabel* loggedIn;\n        class AvatarWidget* image;\n        QFrame* frame;\n    } ui;\n};\n\n\nclass UNICORN_DLLEXPORT UserManagerWidget : public QWidget\n{\nQ_OBJECT\npublic:\n    UserManagerWidget( QWidget* parent = 0 );\n    ~UserManagerWidget();\n\n    UserRadioButton* checkedButton() const;\n\nsignals:\n    void rosterUpdated();\n    void userChanged();\n\nprotected slots:\n    void onAddUserClicked();\n    void onLoginDialogAccepted();\n    void onLoginContinueDialogAccepted();\n    void onUserRemoved();\n\nprotected:\n    void add( UserRadioButton*, bool = true );\n\n    struct {\n        class QGroupBox* groupBox;\n        class QVBoxLayout* usersLayout;\n        class QPushButton* addUserButton;\n    } ui;\n\n\nprivate slots:\n    void onLoginComplete( const unicorn::Session& session );\n\nprivate:\n    QPointer<unicorn::LoginProcess> m_loginProcess;\n    QPointer<LoginContinueDialog> m_lcd;\n};\n\n#endif //USER_MANAGER_WIDGET_H_\n"
  },
  {
    "path": "lib/unicorn/widgets/UserMenu.cpp",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include <QDebug>\n#include <QTimer>\n#include <QDesktopServices>\n\n#include <lastfm/User.h>\n#include <lastfm/UrlBuilder.h>\n\n#include \"lib/unicorn/UnicornApplication.h\"\n#include \"lib/unicorn/UnicornSettings.h\"\n#include \"lib/unicorn/DesktopServices.h\"\n\n#include \"UserMenu.h\"\n\nUserMenu::UserMenu( QWidget* p )\n    :QMenu( p )\n{\n    connect( qApp, SIGNAL(rosterUpdated()), SLOT(refresh()));\n    connect( qApp, SIGNAL(sessionChanged(unicorn::Session) ), SLOT( onSessionChanged( unicorn::Session) ) );\n\n    refresh();\n}\n\nvoid\nUserMenu::onSessionChanged( const unicorn::Session& session )\n{\n    foreach( QAction* a, actions() )\n        if( a->text() == session.user().name() )\n            a->setChecked( true );\n\n    // show the subscribe link if they don't have radio and could get it by subscribing\n    m_subscribe->setVisible( !session.youRadio() && session.subscriberRadio() );\n}\n\nvoid\nUserMenu::onTriggered( QAction* a )\n{\n    unicorn::UserSettings us( a->text() );\n\n    QString username = a->text();\n    QString sessionKey = us.sessionKey();\n    QMetaObject::invokeMethod( qApp, \"changeSession\",\n                                     Q_ARG( const QString, username ),\n                                     Q_ARG( const QString, sessionKey ) );\n\n    //Refresh the user list to be certain that\n    //the correct current user is checked.\n    //(ie. the user change could be cancelled after confirmation.)\n    refresh();\n\n}\n\nvoid\nUserMenu::manageUsers()\n{\n    //This is required so that the menu popup call can be completed\n    //in the event loop before the manage users dialog is displayed.\n    //(The manageUsers method may emit a signal which causes the menu\n    // to be destroyed)\n    QTimer::singleShot( 0, qApp, SLOT(manageUsers()) );\n}\n\nvoid\nUserMenu::subscribe()\n{\n    unicorn::DesktopServices::openUrl( lastfm::UrlBuilder( \"subscribe\" ).url() );\n}\n\nvoid\nUserMenu::refresh()\n{\n    clear();\n\n    m_subscribe = addAction( tr( \"Subscribe\" ), this, SLOT(subscribe()));\n\n    addSeparator();\n\n    QActionGroup* ag = new QActionGroup( this );\n\n    foreach( User u, unicorn::Settings().userRoster() )\n    {\n        QAction* a = ag->addAction( new QAction( u.name(), this ));\n        addAction( a );\n        if( u == User()) a->setChecked( true );\n        a->setCheckable( true );\n    }\n\n    ag->setExclusive( true );\n    connect( ag, SIGNAL(triggered(QAction*)), SLOT( onTriggered(QAction*)));\n\n    onSessionChanged( qobject_cast<unicorn::Application*>(qApp)->currentSession() );\n}\n\n"
  },
  {
    "path": "lib/unicorn/widgets/UserMenu.h",
    "content": "/*\n   Copyright 2010-2012 Last.fm Ltd.\n      - Primarily authored by Jono Cole and Michael Coffey\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef USER_MENU_H_\n#define USER_MENU_H_\n\n#include <QMenu>\n#include <QPointer>\n\n#include \"lib/DllExportMacro.h\"\n#include \"lib/unicorn/UnicornSession.h\"\n\nclass UNICORN_DLLEXPORT UserMenu : public QMenu\n{\n    Q_OBJECT\npublic:\n    UserMenu( QWidget* p = 0 );\n\nprotected slots:\n    void onSessionChanged( const unicorn::Session& session );\n\n    void onTriggered( QAction* a );\n    void manageUsers();\n    void refresh();\n    void subscribe();\n\nprivate:\n    QPointer<QAction> m_subscribe;\n};\n\n#endif\n"
  },
  {
    "path": "lib/unicorn/widgets/UserToolButton.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"UserToolButton.h\"\n#include <QApplication>\n\n#include <QDebug>\n#include <QToolButton>\n#include <QPainter>\n#include <lastfm/User.h>\n\n#include \"UserMenu.h\"\n\n#include \"../UnicornSettings.h\"\n\nusing namespace lastfm;\n\nUserToolButton::UserToolButton()\n{\n    setMouseTracking( true );\n    setIconSize( QSize( 40, 40 ));\n    setCheckable( true );\n\n    if( unicorn::Settings().userRoster().count() > 1 ) {\n        setMenu( new UserMenu());\n        setPopupMode( QToolButton::MenuButtonPopup );\n    }\n\n    connect( this, SIGNAL( toggled( bool )), window(), SLOT( toggleProfile( bool )));\n    connect( qApp, SIGNAL( sessionChanged(unicorn::Session)), SLOT( onSessionChanged(unicorn::Session)));\n    connect( qApp, SIGNAL( gotUserInfo( lastfm::User )), SLOT( onUserGotInfo( lastfm::User )));\n    connect( qApp, SIGNAL( rosterUpdated()), SLOT( onRosterUpdated()));\n}\n\nvoid \nUserToolButton::onSessionChanged( const unicorn::Session& /*session*/ )\n{\n    setIcon( QIcon() );\n}\n\nvoid \nUserToolButton::onUserGotInfo( const User& user )\n{\n    connect( lastfm::nam()->get(QNetworkRequest( user.imageUrl( lastfm::User::MediumImage))), SIGNAL( finished()),\n                                                                          SLOT( onImageDownloaded()));\n}\n\nvoid \nUserToolButton::onImageDownloaded()\n{\n    QNetworkReply* reply = qobject_cast<QNetworkReply*>( sender() );\n    Q_ASSERT( reply );\n\n    reply->deleteLater();\n\n    QPixmap pm;\n    if( !pm.loadFromData( reply->readAll()) )\n        pm = QPixmap(\":lastfm/default_user_small.png\");\n\n    QPixmap on( \":lastfm/profile_on.png\" );\n    QPixmap off( \":lastfm/profile_off.png\" );\n    QPixmap hover( \":lastfm/profile_hover.png\" );\n\n    QIcon icon;\n\n    {\n        QPainter p( &on );\n        p.setRenderHint( QPainter::SmoothPixmapTransform );\n        p.setCompositionMode( QPainter::CompositionMode_DestinationOver );\n        p.drawPixmap( on.rect().adjusted( 5, 5, -5, -5 ), pm, pm.rect());\n    }\n    icon.addPixmap( on, QIcon::Normal, QIcon::On );\n\n    {\n        QPainter p( &off );\n        p.setRenderHint( QPainter::SmoothPixmapTransform );\n        p.setCompositionMode( QPainter::CompositionMode_DestinationOver );\n        p.drawPixmap( off.rect().adjusted( 5, 5, -5, -5 ), pm, pm.rect());\n    }\n    icon.addPixmap( off, QIcon::Normal, QIcon::Off );\n\n     {\n        QPainter p( &hover );\n        p.setRenderHint( QPainter::SmoothPixmapTransform );\n        p.setCompositionMode( QPainter::CompositionMode_DestinationOver );\n        p.drawPixmap( hover.rect().adjusted( 5, 5, -5, -5 ), pm, pm.rect());\n    }\n    icon.addPixmap( hover, QIcon::Active );\n\n    setIcon( icon );\n}\n\nvoid \nUserToolButton::onRosterUpdated()\n{\n    if( unicorn::Settings().userRoster().count() > 1 ) {\n        setMenu( new UserMenu());\n        setPopupMode( QToolButton::MenuButtonPopup );\n        setStyle( QApplication::style());\n    } else {\n        setPopupMode( QToolButton::DelayedPopup );\n        menu()->deleteLater();\n        setStyle( QApplication::style());\n    }\n}\n"
  },
  {
    "path": "lib/unicorn/widgets/UserToolButton.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Jono Cole and Doug Mansell\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef USER_TOOL_BUTTON_H\n#define USER_TOOL_BUTTON_H\n\n#include <QToolButton>\n\n#include \"lib/DllExportMacro.h\"\n\nnamespace lastfm { class User; }\nnamespace unicorn { class Session; }\n\nclass UNICORN_DLLEXPORT UserToolButton : public QToolButton\n{\n    Q_OBJECT\npublic:\n    UserToolButton();\n\nprotected slots:\n    void onSessionChanged( const unicorn::Session& session );\n    void onUserGotInfo( const lastfm::User& user );\n    void onImageDownloaded();\n    void onRosterUpdated();\n};\n\n#endif //USER_TOOL_BUTTON_H\n"
  },
  {
    "path": "plugins/LFMRadio/PluginInfo.h",
    "content": "/*\n   Copyright 2010 Last.fm Ltd.\n      - Primarily authored by Jono Cole\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#ifndef LFM_PLUGIN_INFO_H_\n#define LFM_PLUGIN_INFO_H_\n\n#include \"../../lib/unicorn/Updater/IPluginInfo.h\"\n#include \"../../lib/DllExportMacro.h\"\n\nclass UNICORN_DLLEXPORT LFMRadioPluginInfo : public IPluginInfo\n{\npublic:\n    std::string name() const { return \"Last.fm Radio\"; }\n    Version minVersion() const { return Version(); }\n    Version maxVersion() const { return Version(); }\n    \n    std::string pluginPath() const { return std::string( \"\" ); }\n    std::string displayName() const { return std::string( \"\" ); }\n    std::string processName() const { return std::string( \"radio.exe\" ); }\n\n    std::string id() const { return \"ass\"; }\n    BootstrapType bootstrapType() const { return NoBootstrap; }\n\n    bool isPlatformSupported() const\n    {\n        return true;\n    }\n\n    bool isAppInstalled() const { return true; }\n    bool isInstalled() const { return true; }\n\n    #ifdef QT_VERSION\n    std::tstring pluginInstallPath() const\n    {\n        return std::tstring();\n    }\n    #endif\n \n};\n\n#endif //LFM_PLUGIN_INFO_H_\n\n"
  },
  {
    "path": "plugins/foobar08/audioscrobbler.cpp",
    "content": "/*\r\n    This file is part of the Audioscrobbler component for Foobar2000.\r\n\r\n    This component is free software; you can redistribute it and/or modify\r\n    it under the terms of the GNU General Public License as published by\r\n    the Free Software Foundation; either version 2 of the License, or\r\n    (at your option) any later version.\r\n\r\n    This component is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n    GNU General Public License for more details.\r\n\r\n    You should have received a copy of the GNU General Public License\r\n    along with this source; if not, write to the Free Software\r\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r\n\r\n\tCopyright 2006-2009 Last.fm Ltd.\r\n*/\r\n#include <ScrobSubmitter.h>\r\n#include \"../SDK/foobar2000.h\"\r\n#include \"../SDK/play_callback.h\"\r\n#include \"../SDK/console.h\"\r\n#include \"../SDK/metadb.h\"\r\n#include \"../SDK/initquit.h\"\r\n#include \"../SDK/componentversion.h\"\r\n#include \"../SDK/file_info_helper.h\"\r\n\r\n#define coalesce(a) (a!=NULL)?a:\"\"\r\n\r\nCScrobSubmitter *scrobbler;\r\n\r\nclass play_callback_jump : public play_callback {\r\n\tvirtual void on_playback_starting() {}\r\n\tvirtual void on_playback_new_track(metadb_handle * track) {\r\n\t\tfile_info_i_full info; \r\n\t\ttrack->handle_query(&info);\t\r\n\t\ttry {\r\n\t\t\tscrobbler->Start(std::string(coalesce(info.meta_get(\"artist\"))), \r\n\t\t\t\t\t\tstd::string(coalesce(info.meta_get(\"title\"))), \r\n\t\t\t\t\t\tstd::string(coalesce(info.meta_get(\"album\"))),\r\n\t\t\t\t\t\tstd::string(coalesce(info.meta_get(\"MUSICBRAINZ_TRACKID\"))), \r\n\t\t\t\t\t\tinfo.get_length(), \r\n\t\t\t\t\t\tstd::string(coalesce(info.get_file_path()))\r\n\t\t\t\t\t\t);\r\n\t\t} catch (CScrobSubmitter::CAudioScrobblerException& e) {\r\n\t\t\tconsole::warning(e.what());\r\n\t\t}\r\n\t}\r\n\tvirtual void on_playback_stop(play_control::stop_reason reason) {\r\n\t\ttry {\r\n\t\t\tscrobbler->Stop();\r\n\t\t} catch (CScrobSubmitter::CAudioScrobblerException& e) {\r\n\t\t\tconsole::warning(e.what());\r\n\t\t}\r\n\t}\r\n\tvirtual void on_playback_pause(int state) {\r\n\t\ttry {\r\n\t\t\tif (state) { // pausing\r\n\t\t\t\tscrobbler->Pause();\r\n\t\t\t} else {\t// unpausing\r\n\t\t\t\tscrobbler->Resume();\r\n\t\t\t}\r\n\t\t} catch (CScrobSubmitter::CAudioScrobblerException& e) {\r\n\t\t\tconsole::warning(e.what());\r\n\t\t}\r\n\t}\r\n\tvirtual void on_playback_seek(double time) {}\r\n\tvirtual void on_playback_edited(metadb_handle * track) {}\r\n\tvirtual void on_playback_dynamic_info(const file_info * info,bool b_track_change) {}\r\n};\r\n\r\nclass initquit_audioscrobbler : public initquit {\r\npublic:\r\n\tvoid on_init() \t{\r\n\t\tscrobbler = new CScrobSubmitter();\r\n\t\ttry {\r\n\t\t\tscrobbler->Init(\"foo\");\r\n\t\t} catch (CScrobSubmitter::CAudioScrobblerException& e) {\r\n\t\t\tconsole::warning(e.what());\r\n\t\t}\r\n\t\tconsole::info(\"Audioscrobbler loaded\");\r\n\t}\r\n\tvoid on_quit() \t{\r\n\t\tdelete scrobbler;\r\n\t}\r\n};\r\n\r\nstatic service_factory_single_t<play_callback, play_callback_jump> foo;\r\nstatic service_factory_single_t<initquit, initquit_audioscrobbler> bar;\r\nDECLARE_COMPONENT_VERSION(\"Audioscrobbler\", \"2.0\", \"http://www.last.fm\");"
  },
  {
    "path": "plugins/foobar08/foo_install.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=2.0.2\r\n\r\n[Setup]\r\nOutputBaseFilename=FooPlugin0.8Setup_2.0.2\r\n; setup.exe version\r\nVersionInfoVersion=0.9.1.0\r\nVersionInfoTextVersion=0.9.1.0\r\nAppName=Audioscrobbler foobar2000 0.8 Plugin\r\nAppVerName=Audioscrobbler foobar2000 0.8 Plugin {cm:Version}\r\nVersionInfoDescription=Audioscrobbler foobar2000 0.8 Plugin Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright Last.fm Ltd.\r\nDefaultDirName=\"{pf}\\foobar2000\\components\"\r\nUsePreviousAppDir=yes\r\nUninstallFilesDir={localappdata}\\Last.fm\\Audioscrobbler\\UninstFoo\r\nOutputDir=\".\"\r\nCompression=lzma\r\nSolidCompression=yes\r\nDirExistsWarning=no\r\nDisableReadyPage=yes\r\n; Keep this the same across versions, even if they're incompatible. That will ensure\r\n; uninstallation works fine after many upgrades.\r\nAppId=Audioscrobbler foobar2000 Plugin\r\nCreateUninstallRegKey=no\r\n\r\n[Registry]\r\n; The name of the final subkey here must match the one in plugins.data\r\nRoot: HKCU; Subkey: \"Software\\Last.fm\\Audioscrobbler\\Plugins\\foobar2000 0.8\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\n\r\n[Languages]\r\nName: \"english\"; MessagesFile: \"compiler:Default.isl\"\r\n\r\n[InstallDelete]\r\nType: files; Name: \"{app}\\foo_audioscrobbler.dll\"\r\n\r\n[UninstallDelete]\r\n;Type: files; Name: \"{app}\\AudioScrobbler.log.txt\"\r\n\r\n[Files]\r\nSource: \"foo_audioscrobbler.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\nSource: \"tools\\append_once.bat\"; DestDir: \"{tmp}\"\r\n; NOTE: Don't use \"Flags: ignoreversion\" on any shared system files\r\n\r\n[Run]\r\n; Add uninstaller exe path to AS uninst script\r\nFilename: \"{tmp}\\append_once.bat\"; Parameters: \"\"\"{uninstallexe}\"\" \"\"{localappdata}\\Last.fm\\Audioscrobbler\\uninst2.bat\"\"\"; Flags: runhidden\r\n\r\n"
  },
  {
    "path": "plugins/foobar08/tools/append_once.bat",
    "content": "REM %1 - string to append\r\nREM %2 - file to append it to\r\nfind /C /I %1 %2\r\nif not errorlevel 1 goto end\r\n    echo start /WAIT \"\" %1 /SILENT >> %2\r\n:end"
  },
  {
    "path": "plugins/foobar09/ChangeLog.txt",
    "content": "20/8/12 2.3.1.3\r\n-------------------------------------------------------------------------------\r\n* Now sends album artist as parameter d in scrob sub protocol.\r\n\r\n\r\n13/5/08 2.3.1.2\r\n-------------------------------------------------------------------------------\r\n* Updates broken Updater.exe in client if installed.\r\n\r\n\r\n16/1/08 2.3.1.1\r\n-------------------------------------------------------------------------------\r\n* Fix installer package to actually contain 2.3.1 and not 2.2!\r\n\r\n\r\n9/1/08 2.3.1.0\r\n-------------------------------------------------------------------------------\r\n* Make Scrobsubmitter global instead of heap-allocated to see if removing the\r\n  delete helps fixing crashes.\r\n* Only print to console on errors.\r\n* Only send Stop when playback stops.\r\n\r\n\r\n31/7/07 2.3.0.0\r\n-------------------------------------------------------------------------------\r\n* Recompiled with new ScrobSub for Vista compatibility.\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/audioscrobbler.cpp",
    "content": "/*\r\n    This file is part of the Audioscrobbler component for Foobar2000.\r\n\r\n    This component is free software; you can redistribute it and/or modify\r\n    it under the terms of the GNU General Public License as published by\r\n    the Free Software Foundation; either version 2 of the License, or\r\n    (at your option) any later version.\r\n\r\n    This component is distributed in the hope that it will be useful,\r\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n    GNU General Public License for more details.\r\n\r\n    You should have received a copy of the GNU General Public License\r\n    along with this source; if not, write to the Free Software\r\n    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r\n\r\n    Copyright 2007-2009 Last.fm Ltd.\r\n*/\r\n#include <ScrobSubmitter.h>\r\n\r\n#include \"SDK/foobar2000.h\"\r\n#include \"SDK/play_callback.h\"\r\n#include \"SDK/console.h\"\r\n#include \"SDK/metadb.h\"\r\n#include \"SDK/initquit.h\"\r\n#include \"SDK/componentversion.h\"\r\n\r\n#define coalesce(a) (a!=NULL)?a:\"\"\r\n\r\nScrobSubmitter scrobbler;\r\n\r\nclass play_callback_jump : public play_callback_static\r\n{\r\n\r\n    virtual unsigned int get_flags()\r\n    {\r\n        return flag_on_playback_new_track | flag_on_playback_stop | flag_on_playback_pause;\r\n    }\r\n\r\n    virtual void on_playback_starting(play_control::t_track_command p_command, bool p_paused) {}\r\n    \r\n    virtual void on_playback_new_track(metadb_handle_ptr track)\r\n    {\r\n        file_info_impl info; \r\n        track->get_info(info);\r\n        std::string path = coalesce(track->get_path());\r\n\r\n        if (path.length() > 7 &&\r\n            path[0] == 'f' &&\r\n            path[1] == 'i' &&\r\n            path[2] == 'l' &&\r\n            path[3] == 'e' &&\r\n            path[4] == ':' &&\r\n            path[5] == '/' &&\r\n            path[6] == '/')\r\n        {\r\n            path = path.substr(7, path.length() - 1);\r\n        }\r\n        \r\n        scrobbler.Start(std::string(coalesce(info.meta_get(\"artist\", 0))),\r\n\t\t\t\t\t\tstd::string(coalesce(info.meta_get(\"album artist\", 0))),\r\n                        std::string(coalesce(info.meta_get(\"title\", 0))), \r\n                        std::string(coalesce(info.meta_get(\"album\", 0))),\r\n                        std::string(coalesce(info.meta_get(\"MUSICBRAINZ_TRACKID\", 0))), \r\n                        (int)info.get_length(), \r\n                        path);\r\n\r\n    }\r\n\r\n    virtual void on_playback_stop(play_control::t_stop_reason reason)\r\n    {\r\n        if (reason != play_control::stop_reason_starting_another)\r\n        {\r\n            scrobbler.Stop();\r\n        }\r\n    }\r\n\r\n    virtual void on_playback_pause(bool state)\r\n    {\r\n        if (state) { // pausing\r\n            scrobbler.Pause();\r\n        } else {\t// unpausing\r\n            scrobbler.Resume();\r\n        }\r\n    }\r\n\r\n    virtual void on_playback_seek(double time) {}\r\n    virtual void on_playback_edited(metadb_handle_ptr p_track) {}\r\n    virtual void on_playback_dynamic_info(const file_info & info) {}\r\n    virtual void on_playback_dynamic_info_track(const file_info & info) {}\r\n    virtual void on_playback_time(double p_time) {}\r\n    virtual void on_volume_change(float p_new_val) {};\r\n};\r\n\r\nvoid statusCallback (int reqId, bool error, std::string msg, void* userData)\r\n{\r\n    if (error)\r\n    {\r\n\t    console::info(pfc::string8(\"Audioscrobbler: \") << msg.c_str());\r\n    }\r\n}\r\n\r\nclass initquit_audioscrobbler : public initquit {\r\npublic:\r\n\r\n    void on_init()\r\n    {\r\n        scrobbler.Init(\"foo\", &statusCallback, 0);\r\n        console::info(\"Audioscrobbler: Loaded\");\r\n    }\r\n\r\n    void on_quit()\r\n    {\r\n        scrobbler.Stop();\r\n        scrobbler.Term();\r\n    }\r\n};\r\n\r\nstatic play_callback_static_factory_t<play_callback_jump> foo;\r\nstatic initquit_factory_t<initquit_audioscrobbler> bar;\r\nDECLARE_COMPONENT_VERSION(\"Audioscrobbler\", \"2.3.1\", \"http://www.last.fm\");"
  },
  {
    "path": "plugins/foobar09/foo_audioscrobbler.rc",
    "content": "// Microsoft Visual C++ generated resource script.\r\n//\r\n#include \"resource.h\"\r\n\r\n#define APSTUDIO_READONLY_SYMBOLS\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 2 resource.\r\n//\r\n#include \"afxres.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#undef APSTUDIO_READONLY_SYMBOLS\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.K.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTINCLUDE\r\n//\r\n\r\n1 TEXTINCLUDE \r\nBEGIN\r\n    \"resource.h\\0\"\r\nEND\r\n\r\n2 TEXTINCLUDE \r\nBEGIN\r\n    \"#include \"\"afxres.h\"\"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n3 TEXTINCLUDE \r\nBEGIN\r\n    \"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Version\r\n//\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\n FILEVERSION 2,3,1,3\r\n PRODUCTVERSION 2,3,1,3\r\n FILEFLAGSMASK 0x17L\r\n#ifdef _DEBUG\r\n FILEFLAGS 0x1L\r\n#else\r\n FILEFLAGS 0x0L\r\n#endif\r\n FILEOS 0x4L\r\n FILETYPE 0x2L\r\n FILESUBTYPE 0x0L\r\nBEGIN\r\n    BLOCK \"StringFileInfo\"\r\n    BEGIN\r\n        BLOCK \"080904b0\"\r\n        BEGIN\r\n            VALUE \"Comments\", \"http://www.last.fm\"\r\n            VALUE \"CompanyName\", \"Last.fm\"\r\n            VALUE \"FileDescription\", \"Last.fm foobar2000 0.9.4 plugin\"\r\n            VALUE \"FileVersion\", \"2, 3, 1, 3\"\r\n            VALUE \"InternalName\", \"foo_audioscrobbler\"\r\n            VALUE \"LegalCopyright\", \"Copyright (C) 2007\"\r\n            VALUE \"OriginalFilename\", \"foo_audioscrobbler.dll\"\r\n            VALUE \"ProductName\", \"Last.fm foobar2000 0.9.4 plugin\"\r\n            VALUE \"ProductVersion\", \"2, 3, 1, 3\"\r\n        END\r\n    END\r\n    BLOCK \"VarFileInfo\"\r\n    BEGIN\r\n        VALUE \"Translation\", 0x809, 1200\r\n    END\r\nEND\r\n\r\n#endif    // English (U.K.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n#ifndef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 3 resource.\r\n//\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#endif    // not APSTUDIO_INVOKED\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foo_install.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=2.3.1.3\r\n\r\n[Setup]\r\nOutputBaseFilename=FooPlugin0.9.4Setup_2.3.1.3\r\n; setup.exe version\r\nVersionInfoVersion=2.3.1.3\r\nVersionInfoTextVersion=2.3.1.3\r\nAppName=Last.fm foobar2000 0.9.4 Plugin\r\nAppVerName=Last.fm foobar2000 0.9.4 Plugin {cm:Version}\r\nVersionInfoDescription=Last.fm foobar2000 0.9.4 Plugin Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright  Ltd (c)\r\nDefaultDirName=\"{pf}\\foobar2000\\components\"\r\nUsePreviousAppDir=yes\r\nUninstallFilesDir={commonappdata}\\Last.fm\\Client\\UninstFoo3\r\nOutputDir=\".\"\r\nCompression=lzma\r\nSolidCompression=yes\r\nDirExistsWarning=no\r\nDisableReadyPage=yes\r\n; Keep this the same across versions, even if they're incompatible. That will ensure\r\n; uninstallation works fine after many upgrades.\r\nAppId=Audioscrobbler foobar2000 Plugin\r\nCreateUninstallRegKey=no\r\n\r\n[Registry]\r\n; The name of the final subkey here must match the one in plugins.data\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\foo3\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\foo3\"; ValueType: string; ValueName: \"Name\"; ValueData: \"foobar2000 0.9.4\"; Flags: uninsdeletekey\r\n\r\n[Languages]\r\nName: \"english\"; MessagesFile: \"compiler:Default.isl\"\r\n\r\n[InstallDelete]\r\nType: files; Name: \"{app}\\foo_audioscrobbler.dll\"\r\n\r\n[UninstallDelete]\r\n;Type: files; Name: \"{app}\\AudioScrobbler.log.txt\"\r\n\r\n[Files]\r\nSource: \"release\\foo_audioscrobbler.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n[Run]\r\n\r\n[Code]\r\nprocedure CurStepChanged(CurStep: TSetupStep);\r\nvar\r\n  batfile: String;\r\n  batcontent: String;\r\n  uninstaller: String;\r\n  alreadyAdded: Boolean;\r\n  cmdToAdd: String;\r\nbegin\r\n  if (CurStep = ssPostInstall) then\r\n  begin\r\n    //MsgBox('postinstall', mbInformation, MB_OK);\r\n\r\n    batfile := ExpandConstant('{commonappdata}\\Last.fm\\Client\\uninst2.bat');\r\n    LoadStringFromFile(batfile, batcontent);\r\n    //MsgBox('loaded string: ' + batcontent, mbInformation, MB_OK);\r\n\r\n    uninstaller := ExpandConstant('{uninstallexe}');\r\n    //MsgBox('uninstaller pre-OEM: ' + uninstaller, mbInformation, MB_OK);\r\n\r\n    alreadyAdded := (Pos(uninstaller, batcontent) <> 0);\r\n    if (alreadyAdded = False) then\r\n    begin\r\n      cmdToAdd := uninstaller + #13#10;\r\n      //MsgBox('not present, will add: ' + cmdToAdd, mbInformation, MB_OK);\r\n\r\n      SaveStringToFile(batfile, cmdToAdd, True)\r\n    end;\r\n\r\n  end;\r\n\r\nend;\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/abort_callback.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid abort_callback::check() const {\r\n\tif (is_aborting()) throw exception_aborted();\r\n}\r\n\r\nvoid abort_callback::sleep(double p_timeout_seconds) const {\r\n\tif (!sleep_ex(p_timeout_seconds)) throw exception_aborted();\r\n}\r\n\r\nbool abort_callback::sleep_ex(double p_timeout_seconds) const {\r\n#ifdef _WIN32\r\n\treturn !win32_event::g_wait_for(get_abort_event(),p_timeout_seconds);\r\n#else\r\n#error PORTME\r\n#endif\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/abort_callback.h",
    "content": "#ifndef _foobar2000_sdk_abort_callback_h_\r\n#define _foobar2000_sdk_abort_callback_h_\r\n\r\nnamespace foobar2000_io {\r\n\r\nPFC_DECLARE_EXCEPTION(exception_aborted,pfc::exception,\"User abort\");\r\n\r\n#ifdef _WIN32\r\ntypedef HANDLE abort_callback_event;\r\n#else\r\n#error PORTME\r\n#endif\r\n\r\n//! This class is used to signal underlying worker code whether user has decided to abort a potentially time-consuming operation. It is commonly required by all file related operations. Code that receives an abort_callback object should periodically check it and abort any operations being performed if it is signaled, typically giving io_result_aborted return code (see: t_io_result). \\n\r\n//! See abort_callback_impl for implementation.\r\nclass NOVTABLE abort_callback\r\n{\r\npublic:\r\n\t//! Returns whether user has requested the operation to be aborted.\r\n\tvirtual bool is_aborting() const = 0;\r\n\r\n\t//! Retrieves event object that can be used with some OS calls. The even object becomes signaled when abort is triggered. On win32, this is equivalent to win32 event handle (see: CreateEvent).\r\n\tvirtual abort_callback_event get_abort_event() const = 0;\r\n\t\r\n\t//! Checks if user has requested the operation to be aborted, and throws exception_aborted if so.\r\n\tvoid check() const;\r\n\r\n\t//! For compatibility with old code.\r\n\tinline void check_e() const {check();}\r\n\r\n\t\r\n\t//! Sleeps p_timeout_seconds or less when aborted, throws exception_aborted on abort.\r\n\tvoid sleep(double p_timeout_seconds) const;\r\n\t//! Sleeps p_timeout_seconds or less when aborted, returns true when execution should continue, false when not.\r\n\tbool sleep_ex(double p_timeout_seconds) const;\r\nprotected:\r\n\tabort_callback() {}\r\n\t~abort_callback() {}\r\n};\r\n\r\n\r\n\r\n//! Implementation of abort_callback interface.\r\nclass abort_callback_impl : public abort_callback {\r\npublic:\r\n\tabort_callback_impl() : m_aborting(false) {\r\n\t\tm_event.create(true,false);\r\n\t}\r\n\tinline void abort() {set_state(true);}\r\n\tinline void reset() {set_state(false);}\r\n\r\n\tvoid set_state(bool p_state) {m_aborting = p_state; m_event.set_state(p_state);}\r\n\r\n\tbool is_aborting() const {return m_aborting;}\r\n\r\n\tabort_callback_event get_abort_event() const {return m_event.get();}\r\n\r\nprivate:\r\n\tabort_callback_impl(const abort_callback_impl &) {throw pfc::exception_not_implemented();}\r\n\tconst abort_callback_impl & operator=(const abort_callback_impl&) {throw pfc::exception_not_implemented();}\r\n\t\r\n\tvolatile bool m_aborting;\r\n#ifdef WIN32\r\n\twin32_event m_event;\r\n#endif\r\n};\r\n\r\n}\r\n\r\nusing namespace foobar2000_io;\r\n\r\n#endif //_foobar2000_sdk_abort_callback_h_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/advconfig.h",
    "content": "#ifndef _FOOBAR2000_SDK_ADVCONFIG_H_\r\n#define _FOOBAR2000_SDK_ADVCONFIG_H_\r\n\r\nclass advconfig_entry : public service_base {\r\npublic:\r\n\tvirtual void get_name(pfc::string_base & p_out) = 0;\r\n\tvirtual GUID get_guid() = 0;\r\n\tvirtual GUID get_parent() = 0;\r\n\tvirtual void reset() = 0;\r\n\tvirtual double get_sort_priority() = 0;\r\n\r\n\tstatic const GUID guid_root;\r\n\tstatic const GUID guid_branch_tagging,guid_branch_decoding,guid_branch_tools,guid_branch_playback,guid_branch_display;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(advconfig_entry);\r\n};\r\n\r\nclass advconfig_branch : public advconfig_entry {\r\npublic:\r\n\tFB2K_MAKE_SERVICE_INTERFACE(advconfig_branch,advconfig_entry);\r\n};\r\n\r\nclass advconfig_entry_checkbox : public advconfig_entry {\r\npublic:\r\n\tvirtual bool get_state() = 0;\r\n\tvirtual void set_state(bool p_state) = 0;\r\n\tvirtual bool is_radio() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_checkbox,advconfig_entry);\r\n};\r\n\r\nclass advconfig_entry_string : public advconfig_entry {\r\npublic:\r\n\tvirtual void get_state(pfc::string_base & p_out) = 0;\r\n\tvirtual void set_state(const char * p_string,t_size p_length = infinite) = 0;\r\n\tvirtual t_uint32 get_flags() = 0;\r\n\r\n\tenum {\r\n\t\tflag_is_integer\t\t= 1 << 0, \r\n\t\tflag_is_signed\t\t= 1 << 1,\r\n\t};\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_string,advconfig_entry);\r\n};\r\n\r\n\r\nclass advconfig_branch_impl : public advconfig_branch {\r\npublic:\r\n\tadvconfig_branch_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority) : m_name(p_name), m_guid(p_guid), m_parent(p_parent), m_priority(p_priority) {}\r\n\tvoid get_name(pfc::string_base & p_out) {p_out = m_name;}\r\n\tGUID get_guid() {return m_guid;}\r\n\tGUID get_parent() {return m_parent;}\r\n\tvoid reset() {}\r\n\tdouble get_sort_priority() {return m_priority;}\r\nprivate:\r\n\tpfc::string8 m_name;\r\n\tGUID m_guid,m_parent;\r\n\tconst double m_priority;\r\n};\r\n\r\ntemplate<bool p_is_radio = false>\r\nclass advconfig_entry_checkbox_impl : public advconfig_entry_checkbox {\r\npublic:\r\n\tadvconfig_entry_checkbox_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,bool p_initialstate)\r\n\t\t: m_name(p_name), m_initialstate(p_initialstate), m_state(p_guid,p_initialstate), m_parent(p_parent), m_priority(p_priority) {}\r\n\t\r\n\tvoid get_name(pfc::string_base & p_out) {p_out = m_name;}\r\n\tGUID get_guid() {return m_state.get_guid();}\r\n\tGUID get_parent() {return m_parent;}\r\n\tvoid reset() {m_state = m_initialstate;}\r\n\tbool get_state() {return m_state;}\r\n\tvoid set_state(bool p_state) {m_state = p_state;}\r\n\tbool is_radio() {return p_is_radio;}\r\n\tdouble get_sort_priority() {return m_priority;}\r\nprivate:\r\n\tpfc::string8 m_name;\r\n\tconst bool m_initialstate;\r\n\tcfg_bool m_state;\r\n\tGUID m_parent;\r\n\tconst double m_priority;\r\n};\r\n\r\nclass advconfig_branch_factory : public service_factory_single_t<advconfig_branch_impl> {\r\npublic:\r\n\tadvconfig_branch_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority)\r\n\t\t: service_factory_single_t<advconfig_branch_impl>(p_name,p_guid,p_parent,p_priority) {}\r\n};\r\n\r\ntemplate<bool p_is_radio>\r\nclass advconfig_checkbox_factory_t : public service_factory_single_t<advconfig_entry_checkbox_impl<p_is_radio> > {\r\npublic:\r\n\tadvconfig_checkbox_factory_t(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,bool p_initialstate) \r\n\t\t: service_factory_single_t<advconfig_entry_checkbox_impl<p_is_radio> >(p_name,p_guid,p_parent,p_priority,p_initialstate) {}\r\n};\r\n\r\ntypedef advconfig_checkbox_factory_t<false> advconfig_checkbox_factory;\r\ntypedef advconfig_checkbox_factory_t<true> advconfig_radio_factory;\r\n\r\nclass advconfig_entry_string_impl : public advconfig_entry_string {\r\npublic:\r\n\tadvconfig_entry_string_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate)\r\n\t\t: m_name(p_name), m_parent(p_parent), m_priority(p_priority), m_initialstate(p_initialstate), m_state(p_guid,p_initialstate) {}\r\n\tvoid get_name(pfc::string_base & p_out) {p_out = m_name;}//{p_out = pfc::string_formatter() << m_name << \" : \" << m_state;}\r\n\tGUID get_guid() {return m_state.get_guid();}\r\n\tGUID get_parent() {return m_parent;}\r\n\tvoid reset() {core_api::ensure_main_thread();m_state = m_initialstate;}\r\n\tdouble get_sort_priority() {return m_priority;}\r\n\tvoid get_state(pfc::string_base & p_out) {core_api::ensure_main_thread();p_out = m_state;}\r\n\tvoid set_state(const char * p_string,t_size p_length = infinite) {core_api::ensure_main_thread();m_state.set_string(p_string,p_length);}\r\n\tt_uint32 get_flags() {return 0;}\r\nprivate:\r\n\tconst pfc::string8 m_initialstate, m_name;\r\n\tcfg_string m_state;\r\n\tconst double m_priority;\r\n\tconst GUID m_parent;\r\n};\r\n\r\nclass advconfig_string_factory : public service_factory_single_t<advconfig_entry_string_impl> {\r\npublic:\r\n\tadvconfig_string_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,const char * p_initialstate) \r\n\t\t: service_factory_single_t<advconfig_entry_string_impl>(p_name,p_guid,p_parent,p_priority,p_initialstate) {}\r\n};\r\n\r\n\r\nclass advconfig_entry_integer_impl : public advconfig_entry_string {\r\npublic:\r\n\tadvconfig_entry_integer_impl(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,t_uint64 p_initialstate,t_uint64 p_min,t_uint64 p_max)\r\n\t\t: m_name(p_name), m_parent(p_parent), m_priority(p_priority), m_initval(p_initialstate), m_min(p_min), m_max(p_max), m_state(p_guid,p_initialstate) {}\r\n\tvoid get_name(pfc::string_base & p_out) {p_out = m_name;}\r\n\tGUID get_guid() {return m_state.get_guid();}\r\n\tGUID get_parent() {return m_parent;}\r\n\tvoid reset() {m_state = m_initval;}\r\n\tdouble get_sort_priority() {return m_priority;}\r\n\tvoid get_state(pfc::string_base & p_out) {p_out = pfc::format_uint(m_state.get_value());}\r\n\tvoid set_state(const char * p_string,t_size p_length) {m_state = pfc::clip_t<t_uint64>(pfc::atoui64_ex(p_string,p_length),m_min,m_max);}\r\n\tt_uint32 get_flags() {return advconfig_entry_string::flag_is_integer;}\r\n\r\n\tt_uint64 get_state_int() const {return m_state;}\r\nprivate:\r\n\tcfg_int_t<t_uint64> m_state;\r\n\tconst double m_priority;\r\n\tconst t_uint64 m_initval, m_min, m_max;\r\n\tconst GUID m_parent;\r\n\tconst pfc::string8 m_name;\r\n};\r\n\r\nclass advconfig_integer_factory : public service_factory_single_t<advconfig_entry_integer_impl> {\r\npublic:\r\n\tadvconfig_integer_factory(const char * p_name,const GUID & p_guid,const GUID & p_parent,double p_priority,t_uint64 p_initialstate,t_uint64 p_min,t_uint64 p_max) \r\n\t\t: service_factory_single_t<advconfig_entry_integer_impl>(p_name,p_guid,p_parent,p_priority,p_initialstate,p_min,p_max) {}\r\n};\r\n\r\n\r\nclass advconfig_entry_enum : public advconfig_entry {\r\npublic:\r\n\tvirtual t_size get_value_count() = 0;\r\n\tvirtual void enum_value(pfc::string_base & p_out,t_size p_index) = 0;\r\n\tvirtual t_size get_state() = 0;\r\n\tvirtual void set_state(t_size p_value) = 0;\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE(advconfig_entry_enum,advconfig_entry);\r\n};\r\n\r\n#endif //_FOOBAR2000_SDK_ADVCONFIG_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/app_close_blocker.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool app_close_blocker::g_query()\r\n{\r\n\tservice_ptr_t<app_close_blocker> ptr;\r\n\tservice_enum_t<app_close_blocker> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (!ptr->query()) return false;\r\n\t}\r\n\treturn true;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/app_close_blocker.h",
    "content": "#ifndef _APP_CLOSE_BLOCKER_H_\r\n#define _APP_CLOSE_BLOCKER_H_\r\n\r\n\r\n//! This service is used to signal whether something is currently preventing main window from being closed and app from being shut down.\r\nclass NOVTABLE app_close_blocker : public service_base\r\n{\r\npublic:\r\n\t//! Checks whether this service is currently preventing main window from being closed and app from being shut down.\r\n\tvirtual bool query() = 0;\r\n\r\n\t//! Static helper function, checks whether any of registered app_close_blocker services is currently preventing main window from being closed and app from being shut down.\r\n\tstatic bool g_query();\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(app_close_blocker);\r\n};\r\n\r\n#endif //_APP_CLOSE_BLOCKER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/audio_chunk.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid audio_chunk::set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config)\r\n{\r\n\tt_size size = samples * nch;\r\n\tset_data_size(size);\r\n\tif (src)\r\n\t\tpfc::memcpy_t(get_data(),src,size);\r\n\telse\r\n\t\tpfc::memset_t(get_data(),(audio_sample)0,size);\r\n\tset_sample_count(samples);\r\n\tset_channels(nch,channel_config);\r\n\tset_srate(srate);\r\n}\r\n\r\nstatic bool check_exclusive(unsigned val, unsigned mask)\r\n{\r\n\treturn (val&mask)!=0 && (val&mask)!=mask;\r\n}\r\n\r\nnamespace {\r\n\r\n\ttemplate<class T,bool b_swap,bool b_signed,bool b_pad> class msvc6_sucks_v2 { public:\r\n\t\tinline static void do_fixedpoint_convert(const void * source,unsigned bps,t_size count,audio_sample* buffer)\r\n\t\t{\r\n\t\t\tconst char * src = (const char *) source;\r\n\t\t\tunsigned bytes = bps>>3;\r\n\t\t\tt_size n;\r\n\t\t\tT max = ((T)1)<<(bps-1);\r\n\t\t\t\r\n\t\t\tT negmask = - max;\r\n\r\n\t\t\tASSUME(bytes<=sizeof(T));\r\n\r\n\t\t\tconst double div = 1.0 / (double)(1<<(bps-1));\r\n\t\t\tfor(n=0;n<count;n++) {\r\n\t\t\t\tT temp;\r\n\t\t\t\tif (b_pad)\r\n\t\t\t\t{\r\n\t\t\t\t\ttemp = 0;\r\n\t\t\t\t\tmemcpy(&temp,src,bytes);\r\n\t\t\t\t\tif (b_swap) pfc::byteswap_raw(&temp,bytes);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\ttemp = * reinterpret_cast<const T*>(src);\r\n\t\t\t\t\tif (b_swap) temp = pfc::byteswap_t(temp);\r\n\t\t\t\t}\r\n\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif (!b_signed) temp ^= max;\r\n\r\n\t\t\t\tif (b_pad)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (temp & max) temp |= negmask;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (b_pad)\r\n\t\t\t\t\tsrc += bytes;\r\n\t\t\t\telse\r\n\t\t\t\t\tsrc += sizeof(T);\r\n\r\n\r\n\t\t\t\tbuffer[n] = (audio_sample) ( (double)temp * div );\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate <class T,bool b_pad> class msvc6_sucks { public:\r\n\t\tinline static void do_fixedpoint_convert(bool b_swap,bool b_signed,const void * source,unsigned bps,t_size count,audio_sample* buffer)\r\n\t\t{\r\n\t\t\tif (sizeof(T)==1)\r\n\t\t\t{\r\n\t\t\t\tif (b_signed)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,false,true,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,false,false,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (b_swap)\r\n\t\t\t{\r\n\t\t\t\tif (b_signed)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,true,true,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,true,false,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (b_signed)\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,false,true,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tmsvc6_sucks_v2<T,false,false,b_pad>::do_fixedpoint_convert(source,bps,count,buffer);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\r\n};\r\n\r\n\r\nvoid audio_chunk::set_data_fixedpoint_ex(const void * source,t_size size,unsigned srate,unsigned nch,unsigned bps,unsigned flags,unsigned p_channel_config)\r\n{\r\n\tassert( check_exclusive(flags,FLAG_SIGNED|FLAG_UNSIGNED) );\r\n\tassert( check_exclusive(flags,FLAG_LITTLE_ENDIAN|FLAG_BIG_ENDIAN) );\r\n\r\n\tbool need_swap = !!(flags & FLAG_BIG_ENDIAN);\r\n\tif (pfc::byte_order_is_big_endian) need_swap = !need_swap;\r\n\r\n\tt_size count = size / (bps/8);\r\n\tset_data_size(count);\r\n\taudio_sample * buffer = get_data();\r\n\tbool b_signed = !!(flags & FLAG_SIGNED);\r\n\r\n\tswitch(bps)\r\n\t{\r\n\tcase 8:\r\n\t\tmsvc6_sucks<t_int8,false>::do_fixedpoint_convert(need_swap,b_signed,source,bps,count,buffer);\r\n\t\tbreak;\r\n\tcase 16:\r\n\t\tif (!need_swap && b_signed) audio_math::convert_from_int16((const t_int16*)source,count,buffer,1.0);\r\n\t\telse msvc6_sucks<t_int16,false>::do_fixedpoint_convert(need_swap,b_signed,source,bps,count,buffer);\r\n\t\tbreak;\r\n\tcase 24:\r\n\t\tmsvc6_sucks<t_int32,true>::do_fixedpoint_convert(need_swap,b_signed,source,bps,count,buffer);\r\n\t\tbreak;\r\n\tcase 32:\r\n\t\tif (!need_swap && b_signed) audio_math::convert_from_int32((const t_int32*)source,count,buffer,1.0);\r\n\t\telse msvc6_sucks<t_int32,false>::do_fixedpoint_convert(need_swap,b_signed,source,bps,count,buffer);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\t//unknown size, cant convert\r\n\t\tpfc::memset_t(buffer,(audio_sample)0,count);\r\n\t\tbreak;\r\n\t}\r\n\tset_sample_count(count/nch);\r\n\tset_srate(srate);\r\n\tset_channels(nch,p_channel_config);\r\n}\r\n\r\ntemplate<class t_float>\r\nstatic void process_float_multi(audio_sample * p_out,const t_float * p_in,const t_size p_count)\r\n{\r\n\tt_size n;\r\n\tfor(n=0;n<p_count;n++)\r\n\t\tp_out[n] = (audio_sample)p_in[n];\r\n}\r\n\r\ntemplate<class t_float>\r\nstatic void process_float_multi_swap(audio_sample * p_out,const t_float * p_in,const t_size p_count)\r\n{\r\n\tt_size n;\r\n\tfor(n=0;n<p_count;n++) {\r\n\t\tp_out[n] = (audio_sample) pfc::byteswap_t(p_in[n]);\r\n\t}\r\n}\r\n\r\nvoid audio_chunk::set_data_floatingpoint_ex(const void * ptr,t_size size,unsigned srate,unsigned nch,unsigned bps,unsigned flags,unsigned p_channel_config)\r\n{\r\n\tassert(bps==32 || bps==64);\r\n\tassert( check_exclusive(flags,FLAG_LITTLE_ENDIAN|FLAG_BIG_ENDIAN) );\r\n\tassert( ! (flags & (FLAG_SIGNED|FLAG_UNSIGNED) ) );\r\n\r\n\tbool use_swap = pfc::byte_order_is_big_endian ? !!(flags & FLAG_LITTLE_ENDIAN) : !!(flags & FLAG_BIG_ENDIAN);\r\n\r\n\tconst t_size count = size / (bps/8);\r\n\tset_data_size(count);\r\n\taudio_sample * out = get_data();\r\n\r\n\tif (bps == 32)\r\n\t{\r\n\t\tif (use_swap)\r\n\t\t\tprocess_float_multi_swap(out,reinterpret_cast<const float*>(ptr),count);\r\n\t\telse\r\n\t\t\tprocess_float_multi(out,reinterpret_cast<const float*>(ptr),count);\r\n\t}\r\n\telse if (bps == 64)\r\n\t{\r\n\t\tif (use_swap)\r\n\t\t\tprocess_float_multi_swap(out,reinterpret_cast<const double*>(ptr),count);\r\n\t\telse\r\n\t\t\tprocess_float_multi(out,reinterpret_cast<const double*>(ptr),count);\r\n\t}\r\n\telse throw exception_io_data(\"invalid bit depth\");\r\n\r\n\tset_sample_count(count/nch);\r\n\tset_srate(srate);\r\n\tset_channels(nch,p_channel_config);\r\n}\r\n\r\nbool audio_chunk::is_valid() const\r\n{\r\n\tunsigned nch = get_channels();\r\n\tif (nch==0 || nch>256) return false;\r\n\tunsigned srate = get_srate();\r\n\tif (srate<1000 || srate>1000000) return false;\r\n\tt_size samples = get_sample_count();\r\n\tif (samples==0 || samples >= 0x80000000 / (sizeof(audio_sample) * nch) ) return false;\r\n\tt_size size = get_data_size();\r\n\tif (samples * nch > size) return false;\r\n\tif (!get_data()) return false;\r\n\treturn true;\r\n}\r\n\r\n\r\nvoid audio_chunk::pad_with_silence_ex(t_size samples,unsigned hint_nch,unsigned hint_srate) {\r\n\tif (is_empty())\r\n\t{\r\n\t\tif (hint_srate && hint_nch) {\r\n\t\t\treturn set_data(0,samples,hint_nch,hint_srate);\r\n\t\t} else throw exception_io_data();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (hint_srate && hint_srate != get_srate()) samples = MulDiv_Size(samples,get_srate(),hint_srate);\r\n\t\tif (samples > get_sample_count())\r\n\t\t{\r\n\t\t\tt_size old_size = get_sample_count() * get_channels();\r\n\t\t\tt_size new_size = samples * get_channels();\r\n\t\t\tset_data_size(new_size);\r\n\t\t\tpfc::memset_t(get_data() + old_size,(audio_sample)0,new_size - old_size);\r\n\t\t\tset_sample_count(samples);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid audio_chunk::pad_with_silence(t_size samples) {\r\n\tif (samples > get_sample_count())\r\n\t{\r\n\t\tt_size old_size = get_sample_count() * get_channels();\r\n\t\tt_size new_size = samples * get_channels();\r\n\t\tset_data_size(new_size);\r\n\t\tpfc::memset_t(get_data() + old_size,(audio_sample)0,new_size - old_size);\r\n\t\tset_sample_count(samples);\r\n\t}\r\n}\r\n\r\nvoid audio_chunk::insert_silence_fromstart(t_size samples) {\r\n\tt_size old_size = get_sample_count() * get_channels();\r\n\tt_size delta = samples * get_channels();\r\n\tt_size new_size = old_size + delta;\r\n\tset_data_size(new_size);\r\n\taudio_sample * ptr = get_data();\r\n\tpfc::memmove_t(ptr+delta,ptr,old_size);\r\n\tpfc::memset_t(ptr,(audio_sample)0,delta);\r\n\tset_sample_count(get_sample_count() + samples);\r\n}\r\n\r\nt_size audio_chunk::skip_first_samples(t_size samples_delta)\r\n{\r\n\tt_size samples_old = get_sample_count();\r\n\tif (samples_delta >= samples_old)\r\n\t{\r\n\t\tset_sample_count(0);\r\n\t\tset_data_size(0);\r\n\t\treturn samples_old;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tt_size samples_new = samples_old - samples_delta;\r\n\t\tunsigned nch = get_channels();\r\n\t\taudio_sample * ptr = get_data();\r\n\t\tpfc::memmove_t(ptr,ptr+nch*samples_delta,nch*samples_new);\r\n\t\tset_sample_count(samples_new);\r\n\t\tset_data_size(nch*samples_new);\r\n\t\treturn samples_delta;\r\n\t}\r\n}\r\n\r\naudio_sample audio_chunk::get_peak(audio_sample peak) const\r\n{\r\n\treturn pfc::max_t<audio_sample>(peak,audio_math::calculate_peak(get_data(),get_sample_count() * get_channels() ));\r\n}\r\n\r\nvoid audio_chunk::scale(audio_sample p_value)\r\n{\r\n\taudio_sample * ptr = get_data();\r\n\taudio_math::scale(ptr,get_sample_count() * get_channels(),ptr,p_value);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/audio_chunk.h",
    "content": "#ifndef _AUDIO_CHUNK_H_\r\n#define _AUDIO_CHUNK_H_\r\n\r\n//! Interface to container of a chunk of audio data. See audio_chunk_impl for an implementation.\r\nclass NOVTABLE audio_chunk {\r\npublic:\r\n\t\r\n\t//! Channel map flag declarations. Note that order of interleaved channel data in the stream is same as order of these flags.\r\n\tenum\r\n\t{\r\n\t\tchannel_front_left\t\t\t= 1<<0,\r\n\t\tchannel_front_right\t\t\t= 1<<1,\r\n\t\tchannel_front_center\t\t= 1<<2,\r\n\t\tchannel_lfe\t\t\t\t\t= 1<<3,\r\n\t\tchannel_back_left\t\t\t= 1<<4,\r\n\t\tchannel_back_right\t\t\t= 1<<5,\r\n\t\tchannel_front_center_left\t= 1<<6,\r\n\t\tchannel_front_center_right\t= 1<<7,\r\n\t\tchannel_back_center\t\t\t= 1<<8,\r\n\t\tchannel_side_left\t\t\t= 1<<9,\r\n\t\tchannel_side_right\t\t\t= 1<<10,\r\n\t\tchannel_top_center\t\t\t= 1<<11,\r\n\t\tchannel_top_front_left\t\t= 1<<12,\r\n\t\tchannel_top_front_center\t= 1<<13,\r\n\t\tchannel_top_front_right\t\t= 1<<14,\r\n\t\tchannel_top_back_left\t\t= 1<<15,\r\n\t\tchannel_top_back_center\t\t= 1<<16,\r\n\t\tchannel_top_back_right\t\t= 1<<17,\r\n\r\n\t\tchannel_config_mono = channel_front_center,\r\n\t\tchannel_config_stereo = channel_front_left | channel_front_right,\r\n\t\tchannel_config_5point1 = channel_front_left | channel_front_right | channel_back_left | channel_back_right | channel_front_center | channel_lfe,\r\n\r\n\t\tdefined_channel_count = 18,\r\n\t};\r\n\r\n\t//! Helper function; guesses default channel map for specified channel count.\r\n\tstatic unsigned g_guess_channel_config(unsigned count);\r\n\r\n#ifdef _WIN32\r\n\t//! Helper function; translates audio_chunk channel map to WAVEFORMATEXTENSIBLE channel map.\r\n\tstatic DWORD g_channel_config_to_wfx(unsigned p_config);\r\n\t//! Helper function; translates WAVEFORMATEXTENSIBLE channel map to audio_chunk channel map.\r\n\tstatic unsigned g_channel_config_from_wfx(DWORD p_wfx);\r\n#endif\r\n\r\n\t//! Extracts flag describing Nth channel from specified map. Usable to figure what specific channel in a stream means.\r\n\tstatic unsigned g_extract_channel_flag(unsigned p_config,unsigned p_index);\r\n\t//! Counts channels specified by channel map.\r\n\tstatic unsigned g_count_channels(unsigned p_config);\r\n\t//! Calculates index of a channel specified by p_flag in a stream where channel map is described by p_config.\r\n\tstatic unsigned g_channel_index_from_flag(unsigned p_config,unsigned p_flag);\r\n\r\n\t\r\n\r\n\t//! Retrieves audio data buffer pointer (non-const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \\n\r\n\t//! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible.\r\n\tvirtual audio_sample * get_data() = 0;\r\n\t//! Retrieves audio data buffer pointer (const version). Returned pointer is for temporary use only; it is valid until next set_data_size call, or until the object is destroyed. \\n\r\n\t//! Size of returned buffer is equal to get_data_size() return value (in audio_samples). Amount of actual data may be smaller, depending on sample count and channel count. Conditions where sample count * channel count are greater than data size should not be possible.\r\n\tvirtual const audio_sample * get_data() const = 0;\r\n\t//! Retrieves size of allocated buffer space, in audio_samples.\r\n\tvirtual t_size get_data_size() const = 0;\r\n\t//! Resizes audio data buffer to specified size. Throws std::bad_alloc on failure.\r\n\tvirtual void set_data_size(t_size p_new_size) = 0;\r\n\t\r\n\t//! Retrieves sample rate of contained audio data.\r\n\tvirtual unsigned get_srate() const = 0;\r\n\t//! Sets sample rate of contained audio data.\r\n\tvirtual void set_srate(unsigned val) = 0;\r\n\t//! Retrieves channel count of contained audio data.\r\n\tvirtual unsigned get_channels() const = 0;\r\n\t//! Retrieves channel map of contained audio data. Conditions where number of channels specified by channel map don't match get_channels() return value should not be possible.\r\n\tvirtual unsigned get_channel_config() const = 0;\r\n\t//! Sets channel count / channel map.\r\n\tvirtual void set_channels(unsigned p_count,unsigned p_config) = 0;\r\n\r\n\t//! Retrieves number of valid samples in the buffer. \\n\r\n\t//! Note that a \"sample\" means a unit of interleaved PCM data representing states of each channel at given point of time, not a single PCM value. \\n\r\n\t//! For an example, duration of contained audio data is equal to sample count / sample rate, while actual size of contained data is equal to sample count * channel count.\r\n\tvirtual t_size get_sample_count() const = 0;\r\n\t\r\n\t//! Sets number of valid samples in the buffer. WARNING: sample count * channel count should never be above allocated buffer size.\r\n\tvirtual void set_sample_count(t_size val) = 0;\r\n\r\n\t//! Helper, same as get_srate().\r\n\tinline unsigned get_sample_rate() const {return get_srate();}\r\n\t//! Helper, same as set_srate().\r\n\tinline void set_sample_rate(unsigned val) {set_srate(val);}\r\n\r\n\t//! Helper; sets channel count to specified value and uses default channel map for this channel count.\r\n\tvoid set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));}\r\n\r\n\r\n\t//! Helper; resizes audio data buffer when it's current size is smaller than requested.\r\n\tinline void grow_data_size(t_size p_requested) {if (p_requested > get_data_size()) set_data_size(p_requested);}\r\n\r\n\r\n\t//! Retrieves duration of contained audio data, in seconds.\r\n\tinline double get_duration() const\r\n\t{\r\n\t\tdouble rv = 0;\r\n\t\tt_size srate = get_srate (), samples = get_sample_count();\r\n\t\tif (srate>0 && samples>0) rv = (double)samples/(double)srate;\r\n\t\treturn rv;\r\n\t}\r\n\t\r\n\t//! Returns whether the chunk is empty (contains no audio data).\r\n\tinline bool is_empty() const {return get_channels()==0 || get_srate()==0 || get_sample_count()==0;}\r\n\t\r\n\t//! Returns whether the chunk contents are valid (for bug check purposes).\r\n\tbool is_valid() const;\r\n\r\n\t//! Returns actual amount of audio data contained in the buffer (sample count * channel count). Must not be greater than data size (see get_data_size()).\r\n\tinline t_size get_data_length() const {return get_sample_count() * get_channels();}\r\n\r\n\t//! Resets all audio_chunk data.\r\n\tinline void reset() {\r\n\t\tset_sample_count(0);\r\n\t\tset_srate(0);\r\n\t\tset_channels(0);\r\n\t\tset_data_size(0);\r\n\t}\r\n\t\r\n\t//! Helper, sets chunk data to contents of specified buffer, with specified number of channels / sample rate / channel map.\r\n\tvoid set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate,unsigned channel_config);\r\n\t\r\n\t//! Helper, sets chunk data to contents of specified buffer, with specified number of channels / sample rate, using default channel map for specified channel count.\r\n\tinline void set_data(const audio_sample * src,t_size samples,unsigned nch,unsigned srate) {set_data(src,samples,nch,srate,g_guess_channel_config(nch));}\r\n\t\r\n\t//! Helper, sets chunk data to contents of specified buffer, using default win32/wav conventions for signed/unsigned switch.\r\n\tinline void set_data_fixedpoint(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config) {\r\n\t\tset_data_fixedpoint_ex(ptr,bytes,srate,nch,bps,(bps==8 ? FLAG_UNSIGNED : FLAG_SIGNED) | flags_autoendian(), channel_config);\r\n\t}\r\n\r\n\tinline void set_data_fixedpoint_unsigned(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config) {\r\n\t\treturn set_data_fixedpoint_ex(ptr,bytes,srate,nch,bps,FLAG_UNSIGNED | flags_autoendian(), channel_config);\r\n\t}\r\n\r\n\tinline void set_data_fixedpoint_signed(const void * ptr,t_size bytes,unsigned srate,unsigned nch,unsigned bps,unsigned channel_config) {\r\n\t\treturn set_data_fixedpoint_ex(ptr,bytes,srate,nch,bps,FLAG_SIGNED | flags_autoendian(), channel_config);\r\n\t}\r\n\r\n\tenum\r\n\t{\r\n\t\tFLAG_LITTLE_ENDIAN = 1,\r\n\t\tFLAG_BIG_ENDIAN = 2,\r\n\t\tFLAG_SIGNED = 4,\r\n\t\tFLAG_UNSIGNED = 8,\r\n\t};\r\n\r\n\tinline static unsigned flags_autoendian() {\r\n\t\treturn pfc::byte_order_is_big_endian ? FLAG_BIG_ENDIAN : FLAG_LITTLE_ENDIAN;\r\n\t}\r\n\r\n\tvoid set_data_fixedpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//p_flags - see FLAG_* above\r\n\r\n\tvoid set_data_floatingpoint_ex(const void * ptr,t_size bytes,unsigned p_sample_rate,unsigned p_channels,unsigned p_bits_per_sample,unsigned p_flags,unsigned p_channel_config);//signed/unsigned flags dont apply\r\n\r\n\tinline void set_data_32(const float * src,t_size samples,unsigned nch,unsigned srate) {return set_data(src,samples,nch,srate);}\r\n\r\n\tvoid pad_with_silence_ex(t_size samples,unsigned hint_nch,unsigned hint_srate);\r\n\tvoid pad_with_silence(t_size samples);\r\n\tvoid insert_silence_fromstart(t_size samples);\r\n\tt_size skip_first_samples(t_size samples);\r\n\r\n\r\n\t//! Helper, calculates peak value of data in the chunk. The optional parameter specifies initial peak value, to simplify calling code.\r\n\taudio_sample get_peak(audio_sample p_peak = 0) const;\r\n\r\n\t//! Helper function; scales entire chunk content by specified value.\r\n\tvoid scale(audio_sample p_value);\r\n\r\n\t//! Helper; copies content of another audio chunk to this chunk.\r\n\tvoid copy(const audio_chunk & p_source) {\r\n\t\tset_data(p_source.get_data(),p_source.get_sample_count(),p_source.get_channels(),p_source.get_srate(),p_source.get_channel_config());\r\n\t}\r\n\r\n\tconst audio_chunk & operator=(const audio_chunk & p_source) {\r\n\t\tcopy(p_source);\r\n\t\treturn *this;\r\n\t}\r\nprotected:\r\n\taudio_chunk() {}\r\n\t~audio_chunk() {}\t\r\n};\r\n\r\n//! Implementation of audio_chunk. Takes pfc allocator template as template parameter.\r\ntemplate<template<typename> class t_alloc = pfc::alloc_standard>\r\nclass audio_chunk_impl_t : public audio_chunk {\r\n\ttypedef audio_chunk_impl_t<t_alloc> t_self;\r\n\tpfc::array_t<audio_sample,t_alloc> m_data;\r\n\tunsigned m_srate,m_nch,m_setup;\r\n\tt_size m_samples;\r\npublic:\r\n\taudio_chunk_impl_t() : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {}\r\n\taudio_chunk_impl_t(const audio_sample * src,unsigned samples,unsigned nch,unsigned srate) : m_srate(0), m_nch(0), m_samples(0)\r\n\t{set_data(src,samples,nch,srate);}\r\n\taudio_chunk_impl_t(const audio_chunk & p_source) : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {copy(p_source);}\r\n\taudio_chunk_impl_t(const t_self & p_source) : m_srate(0), m_nch(0), m_samples(0), m_setup(0) {copy(p_source);}\r\n\t\r\n\tvirtual audio_sample * get_data() {return m_data.get_ptr();}\r\n\tvirtual const audio_sample * get_data() const {return m_data.get_ptr();}\r\n\tvirtual t_size get_data_size() const {return m_data.get_size();}\r\n\tvirtual void set_data_size(t_size new_size) {m_data.set_size(new_size);}\r\n\t\r\n\tvirtual unsigned get_srate() const {return m_srate;}\r\n\tvirtual void set_srate(unsigned val) {m_srate=val;}\r\n\tvirtual unsigned get_channels() const {return m_nch;}\r\n\tvirtual unsigned get_channel_config() const {return m_setup;}\r\n\tvirtual void set_channels(unsigned val,unsigned setup) {m_nch = val;m_setup = setup;}\r\n\tvoid set_channels(unsigned val) {set_channels(val,g_guess_channel_config(val));}\r\n\r\n\tvirtual t_size get_sample_count() const {return m_samples;}\r\n\tvirtual void set_sample_count(t_size val) {m_samples = val;}\r\n\r\n\tconst t_self & operator=(const audio_chunk & p_source) {copy(p_source);return *this;}\r\n\tconst t_self & operator=(const t_self & p_source) {copy(p_source);return *this;}\r\n};\r\n\r\ntypedef audio_chunk_impl_t<> audio_chunk_impl;\r\ntypedef audio_chunk_impl audio_chunk_i;//for compatibility\r\n\r\n//! Implements const methods of audio_chunk only, referring to an external buffer. For temporary use only (does not maintain own storage), e.g.: somefunc( audio_chunk_temp_impl(mybuffer,....) );\r\nclass audio_chunk_temp_impl : public audio_chunk {\r\npublic:\r\n\taudio_chunk_temp_impl(const audio_sample * p_data,t_size p_samples,t_uint32 p_sample_rate,t_uint32 p_channels,t_uint32 p_channel_config) :\r\n\tm_data(p_data), m_samples(p_samples), m_sample_rate(p_sample_rate), m_channels(p_channels), m_channel_config(p_channel_config)\r\n\t{\r\n\t\tPFC_ASSERT(is_valid());\r\n\t}\r\n\r\n\taudio_sample * get_data() {throw pfc::exception_not_implemented();}\r\n\tconst audio_sample * get_data() const {return m_data;}\r\n\tt_size get_data_size() const {return m_samples * m_channels;}\r\n\tvoid set_data_size(t_size p_new_size) {throw pfc::exception_not_implemented();}\r\n\t\r\n\tunsigned get_srate() const {return m_sample_rate;}\r\n\tvoid set_srate(unsigned val) {throw pfc::exception_not_implemented();}\r\n\tunsigned get_channels() const {return m_channels;}\r\n\tunsigned get_channel_config() const {return m_channel_config;}\r\n\tvoid set_channels(unsigned p_count,unsigned p_config) {throw pfc::exception_not_implemented();}\r\n\r\n\tt_size get_sample_count() const {return m_samples;}\r\n\t\r\n\tvoid set_sample_count(t_size val) {throw pfc::exception_not_implemented();}\r\n\r\nprivate:\r\n\tt_size m_samples;\r\n\tt_uint32 m_sample_rate,m_channels,m_channel_config;\r\n\tconst audio_sample * m_data;\r\n};\r\n\r\n#endif //_AUDIO_CHUNK_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/audio_chunk_channel_config.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n#ifdef _WIN32\r\n#include <ks.h>\r\n#include <ksmedia.h>\r\n\r\n#if 0\r\n#define SPEAKER_FRONT_LEFT             0x1\r\n#define SPEAKER_FRONT_RIGHT            0x2\r\n#define SPEAKER_FRONT_CENTER           0x4\r\n#define SPEAKER_LOW_FREQUENCY          0x8\r\n#define SPEAKER_BACK_LEFT              0x10\r\n#define SPEAKER_BACK_RIGHT             0x20\r\n#define SPEAKER_FRONT_LEFT_OF_CENTER   0x40\r\n#define SPEAKER_FRONT_RIGHT_OF_CENTER  0x80\r\n#define SPEAKER_BACK_CENTER            0x100\r\n#define SPEAKER_SIDE_LEFT              0x200\r\n#define SPEAKER_SIDE_RIGHT             0x400\r\n#define SPEAKER_TOP_CENTER             0x800\r\n#define SPEAKER_TOP_FRONT_LEFT         0x1000\r\n#define SPEAKER_TOP_FRONT_CENTER       0x2000\r\n#define SPEAKER_TOP_FRONT_RIGHT        0x4000\r\n#define SPEAKER_TOP_BACK_LEFT          0x8000\r\n#define SPEAKER_TOP_BACK_CENTER        0x10000\r\n#define SPEAKER_TOP_BACK_RIGHT         0x20000\r\n#endif\r\n\r\nstatic struct {DWORD m_wfx; unsigned m_native; } const g_translation_table[] =\r\n{\r\n\t{SPEAKER_FRONT_LEFT,\t\t\taudio_chunk::channel_front_left},\r\n\t{SPEAKER_FRONT_RIGHT,\t\t\taudio_chunk::channel_front_right},\r\n\t{SPEAKER_FRONT_CENTER,\t\t\taudio_chunk::channel_front_center},\r\n\t{SPEAKER_LOW_FREQUENCY,\t\t\taudio_chunk::channel_lfe},\r\n\t{SPEAKER_BACK_LEFT,\t\t\t\taudio_chunk::channel_back_left},\r\n\t{SPEAKER_BACK_RIGHT,\t\t\taudio_chunk::channel_back_right},\r\n\t{SPEAKER_FRONT_LEFT_OF_CENTER,\taudio_chunk::channel_front_center_left},\r\n\t{SPEAKER_FRONT_RIGHT_OF_CENTER,\taudio_chunk::channel_front_center_right},\r\n\t{SPEAKER_BACK_CENTER,\t\t\taudio_chunk::channel_back_center},\r\n\t{SPEAKER_SIDE_LEFT,\t\t\t\taudio_chunk::channel_side_left},\r\n\t{SPEAKER_SIDE_RIGHT,\t\t\taudio_chunk::channel_side_right},\r\n\t{SPEAKER_TOP_CENTER,\t\t\taudio_chunk::channel_top_center},\r\n\t{SPEAKER_TOP_FRONT_LEFT,\t\taudio_chunk::channel_top_front_left},\r\n\t{SPEAKER_TOP_FRONT_CENTER,\t\taudio_chunk::channel_top_front_center},\r\n\t{SPEAKER_TOP_FRONT_RIGHT,\t\taudio_chunk::channel_top_front_right},\r\n\t{SPEAKER_TOP_BACK_LEFT,\t\t\taudio_chunk::channel_top_back_left},\r\n\t{SPEAKER_TOP_BACK_CENTER,\t\taudio_chunk::channel_top_back_center},\r\n\t{SPEAKER_TOP_BACK_RIGHT,\t\taudio_chunk::channel_top_back_right},\r\n};\r\n\r\n\r\nDWORD audio_chunk::g_channel_config_to_wfx(unsigned p_config)\r\n{\r\n\tDWORD ret = 0;\r\n\tunsigned n;\r\n\tfor(n=0;n<tabsize(g_translation_table);n++)\r\n\t{\r\n\t\tif (p_config & g_translation_table[n].m_native) ret |= g_translation_table[n].m_wfx;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nunsigned audio_chunk::g_channel_config_from_wfx(DWORD p_wfx)\r\n{\r\n\tunsigned ret = 0;\r\n\tunsigned n;\r\n\tfor(n=0;n<tabsize(g_translation_table);n++)\r\n\t{\r\n\t\tif (p_wfx & g_translation_table[n].m_wfx) ret |= g_translation_table[n].m_native;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n#endif\r\n\r\n\r\nstatic unsigned g_audio_channel_config_table[] = \r\n{\r\n\t0,\r\n\taudio_chunk::channel_config_mono,\r\n\taudio_chunk::channel_config_stereo,\r\n\taudio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_lfe,\r\n\taudio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_back_left | audio_chunk::channel_back_right,\r\n\taudio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_back_left | audio_chunk::channel_back_right | audio_chunk::channel_lfe,\r\n\taudio_chunk::channel_config_5point1,\r\n\taudio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_back_left | audio_chunk::channel_back_right | audio_chunk::channel_lfe | audio_chunk::channel_front_center_right | audio_chunk::channel_front_center_left,\r\n\taudio_chunk::channel_front_left | audio_chunk::channel_front_right | audio_chunk::channel_back_left | audio_chunk::channel_back_right | audio_chunk::channel_front_center | audio_chunk::channel_lfe | audio_chunk::channel_front_center_right | audio_chunk::channel_front_center_left,\r\n};\r\n\r\n\r\nunsigned audio_chunk::g_guess_channel_config(unsigned count)\r\n{\r\n\tif (count >= tabsize(g_audio_channel_config_table)) return 0;\r\n\treturn g_audio_channel_config_table[count];\r\n}\r\n\r\n\r\nunsigned audio_chunk::g_channel_index_from_flag(unsigned p_config,unsigned p_flag) {\r\n\tunsigned index = 0;\r\n\tfor(unsigned walk = 0; walk < 32; walk++) {\r\n\t\tunsigned query = 1 << walk;\r\n\t\tif (p_flag & query) return index;\r\n\t\tif (p_config & query) index++;\r\n\t}\r\n\treturn infinite;\r\n}\r\n\r\nunsigned audio_chunk::g_extract_channel_flag(unsigned p_config,unsigned p_index)\r\n{\r\n\tunsigned toskip = p_index;\r\n\tunsigned flag = 1;\r\n\twhile(flag)\r\n\t{\r\n\t\tif (p_config & flag)\r\n\t\t{\r\n\t\t\tif (toskip == 0) break;\r\n\t\t\ttoskip--;\r\n\t\t}\r\n\t\tflag <<= 1;\r\n\t}\r\n\treturn flag;\r\n}\r\n\r\nunsigned audio_chunk::g_count_channels(unsigned p_config)\r\n{\r\n\tunsigned ret = 0;\r\n\twhile(p_config) {\r\n\t\tret += (p_config & 1);\r\n\t\tp_config >>= 1;\r\n\t}\r\n\treturn ret;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/audio_postprocessor.h",
    "content": "#ifndef _CVT_FLOAT_TO_LINEAR_H_\r\n#define _CVT_FLOAT_TO_LINEAR_H_\r\n\r\n//! This class handles conversion of audio data (audio_chunk) to various linear PCM types, with optional dithering.\r\n\r\nclass NOVTABLE audio_postprocessor : public service_base\r\n{\r\npublic:\r\n\t//! Processes one chunk of audio data.\r\n\t//! @param p_chunk Chunk of audio data to process.\r\n\t//! @param p_output Receives output linear signed PCM data.\r\n\t//! @param p_out_bps Desired bit depth of output.\r\n\t//! @param p_out_bps_physical Desired physical word width of output. Must be either 8, 16, 24 or 32, greater or equal to p_out_bps. This is typically set to same value as p_out_bps.\r\n\t//! @param p_dither Indicates whether dithering should be used. Note that dithering is CPU-heavy.\r\n\t//! @param p_prescale Value to scale all audio samples by when converting. Set to 1.0 to do nothing.\r\n\r\n\tvirtual void run(const audio_chunk & p_chunk,\r\n\t\tmem_block_container & p_output,\r\n\t\tt_uint32 p_out_bps,\r\n\t\tt_uint32 p_out_bps_physical,\r\n\t\tbool p_dither,\r\n\t\taudio_sample p_prescale\r\n\t\t) = 0;\r\n\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(audio_postprocessor);\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/cfg_var.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\n\r\ncfg_var * cfg_var::list=0;\r\n\r\n\r\nstatic int cfg_var_guid_compare(const cfg_var * p_var1,const cfg_var * p_var2)\r\n{\r\n\treturn pfc::guid_compare(p_var1->get_guid(),p_var2->get_guid());\r\n}\r\n\r\nstatic int cfg_var_guid_compare_search(const cfg_var * p_var1,const GUID & p_var2)\r\n{\r\n\treturn pfc::guid_compare(p_var1->get_guid(),p_var2);\r\n}\r\n\r\nvoid cfg_var::config_read_file(stream_reader * p_stream,abort_callback & p_abort)\r\n{\r\n\tfor(;;)\r\n\t{\r\n\t\tGUID guid;\r\n\t\tt_uint32 size;\r\n\r\n\t\tif (p_stream->read(&guid,sizeof(guid),p_abort) != sizeof(guid)) break;\r\n\t\tguid = pfc::byteswap_if_be_t(guid);\r\n\t\tp_stream->read_lendian_t(size,p_abort);\r\n\r\n\t\tbool found = false;\r\n\t\tcfg_var * ptr;\r\n\t\tfor(ptr = list; ptr; ptr=ptr->next) {\r\n\t\t\tif (ptr->get_guid() == guid) {\r\n\t\t\t\tstream_reader_limited_ref wrapper(p_stream,size);\r\n\t\t\t\ttry {\r\n\t\t\t\t\tptr->set_data_raw(&wrapper,size,p_abort);\r\n\t\t\t\t} catch(exception_io_data const & ) {}\r\n\t\t\t\twrapper.flush_remaining(p_abort);\r\n\t\t\t\tfound = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!found)\r\n\t\t\tp_stream->skip_object(size,p_abort);\r\n\t}\r\n}\r\n\r\nvoid cfg_var::config_write_file(stream_writer * p_stream,abort_callback & p_abort) {\r\n\tcfg_var * ptr;\r\n\tpfc::array_t<t_uint8,pfc::alloc_fast_aggressive> temp;\r\n\tfor(ptr = list; ptr; ptr=ptr->next) {\r\n\t\ttemp.set_size(0);\r\n\t\tptr->get_data_raw(&stream_writer_buffer_append_ref_t<pfc::array_t<t_uint8,pfc::alloc_fast_aggressive> >(temp),p_abort);\r\n\t\tp_stream->write_lendian_t(ptr->get_guid(),p_abort);\r\n\t\tp_stream->write_lendian_t(pfc::downcast_guarded<t_uint32>(temp.get_size()),p_abort);\r\n\t\tif (temp.get_size() > 0) {\r\n\t\t\tp_stream->write_object(temp.get_ptr(),temp.get_size(),p_abort);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nvoid cfg_string::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\tp_stream->write_object(get_ptr(),length(),p_abort);\r\n}\r\n\r\nvoid cfg_string::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\tpfc::string8_fastalloc temp;\r\n\tp_stream->read_string_raw(temp,p_abort);\r\n\tset_string(temp);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/cfg_var.h",
    "content": "#ifndef _FOOBAR2000_SDK_CFG_VAR_H_\r\n#define _FOOBAR2000_SDK_CFG_VAR_H_\r\n\r\n//! Base class for configuration variable classes; provides self-registration mechaisms and methods to set/retrieve configuration data; those methods are automatically called for all registered instances by backend when configuration file is being read or written.\\n\r\n//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such).\r\nclass NOVTABLE cfg_var {\r\nprotected:\r\n\t//! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var.\r\n\tcfg_var(const GUID & p_guid) : m_guid(p_guid) {PFC_ASSERT(!core_api::are_services_available());/*imperfect check for nonstatic instantiation*/next=list;list=this;};\r\n\t~cfg_var() {PFC_ASSERT(!core_api::are_services_available());/*imperfect check for nonstatic instantiation*/}\r\npublic:\r\n\t//! Retrieves state of the variable. Called only from main thread, when writing configuration file.\r\n\t//! @param p_stream Stream receiving state of the variable.\r\n\tvirtual void get_data_raw(stream_writer * p_stream,abort_callback & p_abort) = 0;\r\n\t//! Sets state of the variable. Called only from main thread, when reading configuration file.\r\n\t//! @param p_stream Stream containing new state of the variable.\r\n\t//! @param p_sizehint Number of bytes contained in the stream; reading past p_sizehint bytes will fail (EOF).\r\n\tvirtual void set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) = 0;\r\n\r\n\t//! For internal use only, do not call.\r\n\tinline const GUID & get_guid() const {return m_guid;}\r\n\r\n\t//! For internal use only, do not call.\r\n\tstatic void config_read_file(stream_reader * p_stream,abort_callback & p_abort);\r\n\t//! For internal use only, do not call.\r\n\tstatic void config_write_file(stream_writer * p_stream,abort_callback & p_abort);\r\nprivate:\r\n\tGUID m_guid;\r\n\tstatic cfg_var * list;\r\n\tcfg_var * next;\r\n\r\n\tcfg_var(const cfg_var& ) {throw pfc::exception_not_implemented();}\r\n\tconst cfg_var & operator=(const cfg_var& ) {throw pfc::exception_not_implemented();}\r\n};\r\n\r\n//! Generic integer config variable class. Template parameter can be used to specify integer type to use.\\n\r\n//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such).\r\ntemplate<typename t_inttype>\r\nclass cfg_int_t : public cfg_var {\r\nprivate:\r\n\tt_inttype m_val;\r\nprotected:\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {p_stream->write_lendian_t(m_val,p_abort);}\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\t\tt_inttype temp;\r\n\t\tp_stream->read_lendian_t(temp,p_abort);//alter member data only on success, this will throw an exception when something isn't right\r\n\t\tm_val = temp;\r\n\t}\r\n\r\npublic:\r\n\t//! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var.\r\n\t//! @param p_default Default value of the variable.\r\n\texplicit inline cfg_int_t(const GUID & p_guid,t_inttype p_default) : cfg_var(p_guid), m_val(p_default) {}\r\n\t\r\n\tinline const cfg_int_t<t_inttype> & operator=(const cfg_int_t<t_inttype> & p_val) {m_val=p_val.m_val;return *this;}\r\n\tinline t_inttype operator=(t_inttype p_val) {m_val=p_val;return m_val;}\r\n\r\n\tinline operator t_inttype() const {return m_val;}\r\n\r\n\tinline t_inttype get_value() const {return m_val;}\r\n};\r\n\r\ntypedef cfg_int_t<t_int32> cfg_int;\r\ntypedef cfg_int_t<t_uint32> cfg_uint;\r\n//! Since relevant byteswapping functions also understand GUIDs, this can be abused to declare a cfg_guid.\r\ntypedef cfg_int_t<GUID> cfg_guid;\r\ntypedef cfg_int_t<bool> cfg_bool;\r\n\r\n//! String config variable. Stored in the stream with int32 header containing size in bytes, followed by non-null-terminated UTF-8 data.\\n\r\n//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such).\r\nclass cfg_string : public cfg_var, public pfc::string8\r\n{\r\nprotected:\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort);\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort);\r\n\r\npublic:\r\n\t//! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var.\r\n\t//! @param p_defaultval Default/initial value of the variable.\r\n\texplicit inline cfg_string(const GUID & p_guid,const char * p_defaultval) : cfg_var(p_guid), pfc::string8(p_defaultval) {}\r\n\r\n\tinline const cfg_string& operator=(const cfg_string & p_val) {set_string(p_val);return *this;}\r\n\tinline const cfg_string& operator=(const char* p_val) {set_string(p_val);return *this;}\r\n\r\n\tinline operator const char * () const {return get_ptr();}\r\n\r\n};\r\n\r\n//! Struct config variable template. Warning: not endian safe, should be used only for nonportable code.\\n\r\n//! Note that cfg_var class and its derivatives may be only instantiated statically (as static objects or members of other static objects), NEVER dynamically (operator new, local variables, members of objects instantiated as such).\r\ntemplate<typename t_struct>\r\nclass cfg_struct_t : public cfg_var {\r\nprivate:\r\n\tt_struct m_val;\r\nprotected:\r\n\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {p_stream->write_object(&m_val,sizeof(m_val),p_abort);}\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\t\tt_struct temp;\r\n\t\tp_stream->read_object(&temp,sizeof(temp),p_abort);\r\n\t\tm_val = temp;\r\n\t}\r\npublic:\r\n\t//! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var.\r\n\tinline cfg_struct_t(const GUID & p_guid,const t_struct & p_val) : cfg_var(p_guid), m_val(p_val) {}\r\n\t//! @param p_guid GUID of the variable, used to identify variable implementations owning specific configuration file entries when reading the configuration file back. You must generate a new GUID every time you declare a new cfg_var.\r\n\tinline cfg_struct_t(const GUID & p_guid,int filler) : cfg_var(p_guid) {memset(&m_val,filler,sizeof(t_struct));}\r\n\t\r\n\tinline const cfg_struct_t<t_struct> & operator=(const cfg_struct_t<t_struct> & p_val) {m_val = p_val.get_value();return *this;}\r\n\tinline const cfg_struct_t<t_struct> & operator=(const t_struct & p_val) {m_val = p_val;return *this;}\r\n\r\n\tinline const t_struct& get_value() const {return m_val;}\r\n\tinline t_struct& get_value() {return m_val;}\r\n\tinline operator t_struct() const {return m_val;}\r\n};\r\n\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/chapterizer.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid chapter_list::copy(const chapter_list & p_source)\r\n{\r\n\tt_size n, count = p_source.get_chapter_count();\r\n\tset_chapter_count(count);\r\n\tfor(n=0;n<count;n++)\r\n\t\tset_info(n,p_source.get_info(n));\r\n}\r\n\r\nbool chapterizer::g_find(service_ptr_t<chapterizer> & p_out,const char * p_path,abort_callback & p_abort)\r\n{\r\n\tservice_ptr_t<chapterizer> ptr;\r\n\tservice_enum_t<chapterizer> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->is_our_file(p_path,p_abort))\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/chapterizer.h",
    "content": "//! Interface for object storing list of chapters.\r\nclass NOVTABLE chapter_list\r\n{\r\npublic:\r\n\t//! Returns number of chapters.\r\n\tvirtual t_size get_chapter_count() const = 0;\r\n\t//! Queries description of specified chapter.\r\n\t//! @param p_chapter Index of chapter to query, greater or equal zero and less than get_chapter_count() value. If p_chapter value is out of valid range, results are undefined (e.g. crash).\r\n\t//! @returns reference to file_info object describing specified chapter (length part of file_info indicates distance between beginning of this chapter and next chapter mark). Returned reference value for temporary use only, becomes invalid after any non-const operation on the chapter_list object.\r\n\tvirtual const file_info & get_info(t_size p_chapter) const = 0;\r\n\t\r\n\t//! Sets number of chapters.\r\n\tvirtual void set_chapter_count(t_size p_count) = 0;\r\n\t//! Modifies description of specified chapter.\r\n\t//! @param p_chapter_index Index of chapter to modify, greater or equal zero and less than get_chapter_count() value. If p_chapter value is out of valid range, results are undefined (e.g. crash).\r\n\t//! @param p_info New chapter description. Note that length part of file_info is used to calculate chapter marks.\r\n\tvirtual void set_info(t_size p_chapter,const file_info & p_info) = 0;\r\n\r\n\t//! Copies contents of specified chapter_list object to this object.\r\n\tvoid copy(const chapter_list & p_source);\r\n\t\r\n\tinline const chapter_list & operator=(const chapter_list & p_source) {copy(p_source); return *this;}\r\n\r\nprotected:\r\n\tchapter_list() {}\r\n\t~chapter_list() {}\r\n};\r\n\r\n//! Implements chapter_list.\r\nclass chapter_list_impl : public chapter_list\r\n{\r\npublic:\r\n\tchapter_list_impl(const chapter_list_impl & p_source) {copy(p_source);}\r\n\tchapter_list_impl(const chapter_list & p_source) {copy(p_source);}\r\n\tchapter_list_impl() {}\r\n\r\n\tconst chapter_list_impl & operator=(const chapter_list_impl & p_source) {copy(p_source); return *this;}\r\n\tconst chapter_list_impl & operator=(const chapter_list & p_source) {copy(p_source); return *this;}\r\n\r\n\tt_size get_chapter_count() const {return m_infos.get_size();}\r\n\tconst file_info & get_info(t_size p_chapter) const {return m_infos[p_chapter];}\r\n\r\n\tvoid set_chapter_count(t_size p_count) {m_infos.set_size(p_count);}\r\n\tvoid set_info(t_size p_chapter,const file_info & p_info) {m_infos[p_chapter] = p_info;}\r\nprivate:\r\n\tpfc::array_t<file_info_impl> m_infos;\r\n};\r\n\r\n\r\n//! This service implements chapter list editing operations for various file formats, e.g. for MP4 chapters or CD images with embedded cuesheets. Used by converter \"encode single file with chapters\" feature.\r\nclass NOVTABLE chapterizer : public service_base\r\n{\r\npublic:\r\n\t//! Tests whether specified path is supported by this implementation.\r\n\t//! @param p_path Path of file to examine.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual bool is_our_file(const char * p_path,abort_callback & p_abort) = 0;\r\n\t\r\n\t//! Writes new chapter list to specified file.\r\n\t//! @param p_path Path of file to modify.\r\n\t//! @param p_list New chapter list to write.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void set_chapters(const char * p_path,chapter_list const & p_list,abort_callback & p_abort) = 0;\r\n\t//! Retrieves chapter list from specified file.\r\n\t//! @param p_path Path of file to examine.\r\n\t//! @param p_list Object receiving chapter list.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void get_chapters(const char * p_path,chapter_list & p_list,abort_callback & p_abort) = 0;\r\n\r\n\t//! Static helper, tries to find chapterizer interface that supports specified file.\r\n\tstatic bool g_find(service_ptr_t<chapterizer> & p_out,const char * p_path,abort_callback & p_abort);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(chapterizer);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/commandline.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid commandline_handler_metadb_handle::on_file(const char * url)\r\n{\r\n\r\n\tabort_callback_impl blah;\r\n\r\n\t{\r\n\t\tplaylist_loader_callback_impl callback(blah);\r\n\r\n\t\tbool fail = false;\r\n\t\ttry {\r\n\t\t\tplaylist_loader::g_process_path_ex(url,callback);\r\n\t\t} catch(std::exception const & e) {\r\n\t\t\tconsole::formatter() << \"Unhandled exception in playlist loader: \" << e;\r\n\t\t\tfail = true;\r\n\t\t} catch(...) {\r\n\t\t\tconsole::formatter() << \"Unhandled exception in playlist loader\";\r\n\t\t\tfail = true;\r\n\t\t}\r\n\r\n\t\tif (!fail) {\r\n\t\t\tt_size n,m=callback.get_count();\r\n\t\t\tfor(n=0;n<m;n++) on_file(callback.get_item(n));\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/commandline.h",
    "content": "#ifndef _FOOBAR2000_SDK_COMMANDLINE_H_\r\n#define _FOOBAR2000_SDK_COMMANDLINE_H_\r\n\r\n#include \"service.h\"\r\n\r\nclass NOVTABLE commandline_handler : public service_base\r\n{\r\npublic:\r\n\tenum result\r\n\t{\r\n\t\tRESULT_NOT_OURS,//not our command\r\n\t\tRESULT_PROCESSED,//command processed\r\n\t\tRESULT_PROCESSED_EXPECT_FILES,//command processed, we want to takeover file urls after this command\r\n\t};\r\n\tvirtual result on_token(const char * token)=0;\r\n\tvirtual void on_file(const char * url) {};//optional\r\n\tvirtual void on_files_done() {};//optional\r\n\tvirtual bool want_directories() {return false;}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(commandline_handler);\r\n};\r\n\r\nclass commandline_handler_metadb_handle : public commandline_handler//helper\r\n{\r\nprotected:\r\n\tvirtual void on_file(const char * url);\r\n\tvirtual bool want_directories() {return true;}\r\npublic:\r\n\tvirtual result on_token(const char * token)=0;\t\r\n\tvirtual void on_files_done() {};\r\n\t\r\n\tvirtual void on_file(const metadb_handle_ptr & ptr)=0;\r\n};\r\n\r\n/*\r\n\r\nhow commandline_handler is used:\r\n\r\n\tscenario #1:\r\n\t\tcreation => on_token() => deletion\r\n\tscenario #2:\r\n\t\tcreation => on_token() returning RESULT_PROCESSED_EXPECT_FILES => on_file(), on_file().... => on_files_done() => deletion\r\n*/\r\n\r\ntemplate<typename T>\r\nclass commandline_handler_factory_t : public service_factory_t<T> {};\r\n\r\n\r\n\r\n#endif //_FOOBAR2000_SDK_COMMANDLINE_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/completion_notify.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nnamespace {\r\n\tclass main_thread_callback_myimpl : public main_thread_callback {\r\n\tpublic:\r\n\t\tvoid callback_run() {\r\n\t\t\tm_notify->on_completion(m_code);\r\n\t\t}\r\n\r\n\t\tmain_thread_callback_myimpl(completion_notify_ptr p_notify,unsigned p_code) : m_notify(p_notify), m_code(p_code) {}\r\n\tprivate:\r\n\t\tcompletion_notify_ptr m_notify;\r\n\t\tunsigned m_code;\r\n\t};\r\n}\r\n\r\nvoid completion_notify::g_signal_completion_async(completion_notify_ptr p_notify,unsigned p_code) {\r\n\tif (p_notify.is_valid()) {\r\n\t\tstatic_api_ptr_t<main_thread_callback_manager>()->add_callback(new service_impl_t<main_thread_callback_myimpl>(p_notify,p_code));\r\n\t}\r\n}\r\n\r\nvoid completion_notify::on_completion_async(unsigned p_code) {\r\n\tstatic_api_ptr_t<main_thread_callback_manager>()->add_callback(new service_impl_t<main_thread_callback_myimpl>(this,p_code));\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/completion_notify.h",
    "content": "//! Generic service for receiving notifications about async operation completion. Used by various other services.\r\nclass completion_notify : public service_base {\r\npublic:\r\n\t//! Called when an async operation has been completed. Note that on_completion is always called from main thread. You can use on_completion_async() helper if you need to signal completion while your context is in another thread.\\n\r\n\t//! IMPLEMENTATION WARNING: If process being completed creates a window taking caller's window as parent, you must not destroy the parent window inside on_completion(). If you need to do so, use PostMessage() or main_thread_callback to delay the deletion.\r\n\t//! @param p_code Context-specific status code. Possible values depend on the operation being performed.\r\n\tvirtual void on_completion(unsigned p_code) = 0;\r\n\r\n\t//! Helper. Queues a notification, using main_thread_callback.\r\n\tvoid on_completion_async(unsigned p_code);\r\n\r\n\t//! Helper. Checks for null ptr and calls on_completion_async when the ptr is not null.\r\n\tstatic void g_signal_completion_async(service_ptr_t<completion_notify> p_notify,unsigned p_code);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(completion_notify,service_base);\r\n};\r\n\r\n//! Helper implementation.\r\nclass completion_notify_orphanable : public completion_notify {\r\npublic:\r\n\tvirtual void orphan() = 0;\r\n};\r\n\r\n//! Helper implementation.\r\n//! IMPLEMENTATION WARNING: If process being completed creates a window taking caller's window as parent, you must not destroy the parent window inside on_task_completion(). If you need to do so, use PostMessage() or main_thread_callback to delay the deletion.\r\ntemplate<typename t_receiver>\r\nclass completion_notify_impl : public completion_notify_orphanable {\r\npublic:\r\n\tvoid on_completion(unsigned p_code) {\r\n\t\tif (m_receiver != NULL) {\r\n\t\t\tm_receiver->on_task_completion(m_taskid,p_code);\r\n\t\t}\r\n\t}\r\n\tvoid setup(t_receiver * p_receiver, unsigned p_task_id) {m_receiver = p_receiver; m_taskid = p_task_id;}\r\n\tvoid orphan() {m_receiver = NULL; m_taskid = 0;}\r\nprivate:\r\n\tt_receiver * m_receiver;\r\n\tunsigned m_taskid;\r\n};\r\n\r\ntemplate<typename t_receiver>\r\nservice_ptr_t<completion_notify_orphanable> completion_notify_create(t_receiver * p_receiver,unsigned p_taskid) {\r\n\tservice_ptr_t<completion_notify_impl<t_receiver> > instance = new service_impl_t<completion_notify_impl<t_receiver> >();\r\n\tinstance->setup(p_receiver,p_taskid);\r\n\treturn instance;\r\n}\r\n\r\ntypedef service_ptr_t<completion_notify> completion_notify_ptr;"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/component.h",
    "content": "#ifndef _COMPONENT_H_\r\n#define _COMPONENT_H_\r\n\r\n#include \"foobar2000.h\"\r\n\r\nclass NOVTABLE foobar2000_client\r\n{\r\npublic:\r\n\ttypedef service_factory_base* pservice_factory_base;\r\n\r\n\tenum {FOOBAR2000_CLIENT_VERSION_COMPATIBLE = 70, FOOBAR2000_CLIENT_VERSION = 72};\t//changes everytime global compatibility is broken\r\n\tvirtual t_uint32 FB2KAPI get_version() = 0;\r\n\tvirtual pservice_factory_base FB2KAPI get_service_list() = 0;\r\n\r\n\tvirtual void FB2KAPI get_config(stream_writer * p_stream,abort_callback & p_abort) = 0;\r\n\tvirtual void FB2KAPI set_config(stream_reader * p_stream,abort_callback & p_abort) = 0;\r\n\tvirtual void FB2KAPI set_library_path(const char * path,const char * name) = 0;\r\n\tvirtual void FB2KAPI services_init(bool val) = 0;\r\n\tvirtual bool is_debug() = 0;\r\nprotected:\r\n\tfoobar2000_client() {}\r\n\t~foobar2000_client() {}\r\n};\r\n\r\nclass NOVTABLE foobar2000_api\r\n{\r\npublic:\r\n\tvirtual service_class_ref FB2KAPI service_enum_find_class(const GUID & p_guid) = 0;\r\n\tvirtual bool FB2KAPI service_enum_create(service_ptr_t<service_base> & p_out,service_class_ref p_class,t_size p_index) = 0;\r\n\tvirtual t_size FB2KAPI service_enum_get_count(service_class_ref p_class) = 0;\r\n\tvirtual HWND FB2KAPI get_main_window()=0;\r\n\tvirtual bool FB2KAPI assert_main_thread()=0;\r\n\tvirtual bool FB2KAPI is_main_thread()=0;\r\n\tvirtual bool FB2KAPI is_shutting_down()=0;\r\n\tvirtual pcchar FB2KAPI get_profile_path()=0;\r\n\tvirtual bool FB2KAPI is_initializing() = 0;\r\nprotected:\r\n\tfoobar2000_api() {}\r\n\t~foobar2000_api() {}\r\n};\r\n\r\nextern foobar2000_api * g_api;\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/component_client.h",
    "content": "#ifndef _COMPONENT_CLIENT_H_\r\n#define _COMPONENT_CLIENT_H_\r\n\r\n\r\n\r\n#endif //_COMPONENT_CLIENT_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/components_menu.h",
    "content": "#ifndef _COMPONENTS_MENU_H_\r\n#define _COMPONENTS_MENU_H_\r\n\r\n#error deprecated, see menu_item.h\r\n\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/componentversion.h",
    "content": "#ifndef _COMPONENTVERSION_H_\r\n#define _COMPONENTVERSION_H_\r\n\r\nclass NOVTABLE componentversion : public service_base\r\n{\r\npublic:\r\n\tvirtual void get_file_name(pfc::string_base & out)=0;\r\n\tvirtual void get_component_name(pfc::string_base & out)=0;\r\n\tvirtual void get_component_version(pfc::string_base & out)=0;\r\n\tvirtual void get_about_message(pfc::string_base & out)=0;//about message uses \"\\n\" for line separators\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(componentversion);\r\n};\r\n\r\nclass componentversion_impl_simple : public componentversion\r\n{\r\n\tconst char * name,*version,*about;\r\npublic:\r\n\t//do not derive/override\r\n\tvirtual void get_file_name(pfc::string_base & out) {out.set_string(core_api::get_my_file_name());}\r\n\tvirtual void get_component_name(pfc::string_base & out) {out.set_string(name?name:\"\");}\r\n\tvirtual void get_component_version(pfc::string_base & out) {out.set_string(version?version:\"\");}\r\n\tvirtual void get_about_message(pfc::string_base & out) {out.set_string(about?about:\"\");}\r\n\texplicit componentversion_impl_simple(const char * p_name,const char * p_version,const char * p_about) : name(p_name), version(p_version), about(p_about ? p_about : \"\") {}\r\n};\r\n\r\nclass componentversion_impl_copy : public componentversion\r\n{\r\n\tpfc::string8 name,version,about;\r\npublic:\r\n\t//do not derive/override\r\n\tvirtual void get_file_name(pfc::string_base & out) {out.set_string(core_api::get_my_file_name());}\r\n\tvirtual void get_component_name(pfc::string_base & out) {out.set_string(name);}\r\n\tvirtual void get_component_version(pfc::string_base & out) {out.set_string(version);}\r\n\tvirtual void get_about_message(pfc::string_base & out) {out.set_string(about);}\r\n\texplicit componentversion_impl_copy(const char * p_name,const char * p_version,const char * p_about) : name(p_name), version(p_version), about(p_about ? p_about : \"\") {}\r\n};\r\n\r\ntypedef service_factory_single_transparent_t<componentversion_impl_simple> __componentversion_impl_simple_factory;\r\ntypedef service_factory_single_transparent_t<componentversion_impl_copy> __componentversion_impl_copy_factory;\r\n\r\nclass componentversion_impl_simple_factory : public __componentversion_impl_simple_factory {\r\npublic:\r\n\tcomponentversion_impl_simple_factory(const char * p_name,const char * p_version,const char * p_about) : __componentversion_impl_simple_factory(p_name,p_version,p_about) {}\r\n};\r\n\r\nclass componentversion_impl_copy_factory : public __componentversion_impl_copy_factory {\r\npublic:\r\n\tcomponentversion_impl_copy_factory(const char * p_name,const char * p_version,const char * p_about) : __componentversion_impl_copy_factory(p_name,p_version,p_about) {}\r\n};\r\n\r\n#define DECLARE_COMPONENT_VERSION(NAME,VERSION,ABOUT) \\\r\n\tstatic componentversion_impl_simple_factory g_componentversion_service(NAME,VERSION,ABOUT);\r\n\r\n#define DECLARE_COMPONENT_VERSION_COPY(NAME,VERSION,ABOUT) \\\r\n\tstatic componentversion_impl_copy_factory g_componentversion_service(NAME,VERSION,ABOUT);\r\n\r\n//usage: DECLARE_COMPONENT_VERSION(\"blah\",\"v1.337\",(const char*)NULL)\r\n//_copy version copies strings around instead of keeping pointers (bigger but sometimes needed, eg. if strings are created as string_printf() or something inside constructor\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/config_io_callback.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid config_io_callback::g_on_read()\r\n{\r\n\tservice_enum_t<config_io_callback> e;\r\n\tservice_ptr_t<config_io_callback> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tptr->on_read();\r\n\t} while(e.next(ptr));\r\n}\r\n\r\nvoid config_io_callback::g_on_write(bool reset)\r\n{\r\n\tservice_enum_t<config_io_callback> e;\r\n\tservice_ptr_t<config_io_callback> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tptr->on_write(reset);\r\n\t} while(e.next(ptr));\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/config_io_callback.h",
    "content": "#ifndef _config_io_callback_h_\r\n#define _config_io_callback_h_\r\n\r\nclass NOVTABLE config_io_callback : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_read() = 0;\r\n\tvirtual void on_write(bool reset) = 0;\r\n\r\n\t//for core use only\r\n\tstatic void g_on_read();\r\n\tstatic void g_on_write(bool reset);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_io_callback);\r\n};\r\n\r\n#endif //_config_io_callback_h_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/config_object.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid config_object_notify_manager::g_on_changed(const service_ptr_t<config_object> & p_object)\r\n{\r\n\tif (core_api::assert_main_thread())\r\n\t{\r\n\t\tservice_enum_t<config_object_notify_manager> e;\r\n\t\tservice_ptr_t<config_object_notify_manager> ptr;\r\n\t\twhile(e.next(ptr))\r\n\t\t\tptr->on_changed(p_object);\r\n\t}\r\n}\r\n\r\nbool config_object::g_find(service_ptr_t<config_object> & p_out,const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<config_object> ptr;\r\n\tservice_enum_t<config_object> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->get_guid() == p_guid)\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid config_object::g_get_data_string(const GUID & p_guid,pfc::string_base & p_out)\r\n{\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\tptr->get_data_string(p_out);\r\n}\r\n\r\nvoid config_object::g_set_data_string(const GUID & p_guid,const char * p_data,t_size p_length)\r\n{\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\tptr->set_data_string(p_data,p_length);\r\n}\r\n\r\nvoid config_object::get_data_int32(t_int32 & p_out)\r\n{\r\n\tt_int32 temp;\r\n\tget_data_struct_t<t_int32>(temp);\r\n\tbyte_order::order_le_to_native_t(temp);\r\n\tp_out = temp;\r\n}\r\n\r\nvoid config_object::set_data_int32(t_int32 p_val)\r\n{\r\n\tt_int32 temp = p_val;\r\n\tbyte_order::order_native_to_le_t(temp);\r\n\tset_data_struct_t<t_int32>(temp);\r\n}\r\n\r\nbool config_object::get_data_bool_simple(bool p_default) {\r\n\ttry {\r\n\t\tbool ret = p_default;\r\n\t\tget_data_bool(ret);\r\n\t\treturn ret;\r\n\t} catch(std::exception const &) {return p_default;}\r\n}\r\n\r\nt_int32 config_object::get_data_int32_simple(t_int32 p_default) {\r\n\ttry {\r\n\t\tt_int32 ret = p_default;\r\n\t\tget_data_int32(ret);\r\n\t\treturn ret;\r\n\t} catch(std::exception const &) {return p_default;}\r\n}\r\n\r\nvoid config_object::g_get_data_int32(const GUID & p_guid,t_int32 & p_out) {\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\tptr->get_data_int32(p_out);\r\n}\r\n\r\nvoid config_object::g_set_data_int32(const GUID & p_guid,t_int32 p_val) {\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\tptr->set_data_int32(p_val);\r\n}\r\n\r\nbool config_object::g_get_data_bool_simple(const GUID & p_guid,bool p_default)\r\n{\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\treturn ptr->get_data_bool_simple(p_default);\r\n}\r\n\r\nt_int32 config_object::g_get_data_int32_simple(const GUID & p_guid,t_int32 p_default)\r\n{\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\treturn ptr->get_data_int32_simple(p_default);\r\n}\r\n\r\nvoid config_object::get_data_bool(bool & p_out) {get_data_struct_t<bool>(p_out);}\r\nvoid config_object::set_data_bool(bool p_val) {set_data_struct_t<bool>(p_val);}\r\n\r\nvoid config_object::g_get_data_bool(const GUID & p_guid,bool & p_out) {g_get_data_struct_t<bool>(p_guid,p_out);}\r\nvoid config_object::g_set_data_bool(const GUID & p_guid,bool p_val) {g_set_data_struct_t<bool>(p_guid,p_val);}\r\n\r\nnamespace {\r\n\tclass stream_writer_string : public stream_writer {\r\n\tpublic:\r\n\t\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\t\tm_out.add_string((const char*)p_buffer,p_bytes);\r\n\t\t}\r\n\t\tstream_writer_string(pfc::string_base & p_out) : m_out(p_out) {m_out.reset();}\r\n\tprivate:\r\n\t\tpfc::string_base & m_out;\r\n\t};\r\n\r\n\tclass stream_writer_fixedbuffer : public stream_writer {\r\n\tpublic:\r\n\t\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\t\tif (p_bytes > 0) {\r\n\t\t\t\tif (p_bytes > m_bytes - m_bytes_read) throw pfc::exception_overflow();\r\n\t\t\t\tmemcpy((t_uint8*)m_out,p_buffer,p_bytes);\r\n\t\t\t\tm_bytes_read += p_bytes;\r\n\t\t\t}\r\n\t\t}\r\n\t\tstream_writer_fixedbuffer(void * p_out,t_size p_bytes,t_size & p_bytes_read) : m_out(p_out), m_bytes(p_bytes), m_bytes_read(p_bytes_read) {m_bytes_read = 0;}\r\n\tprivate:\r\n\t\tvoid * m_out;\r\n\t\tt_size m_bytes;\r\n\t\tt_size & m_bytes_read;\r\n\t};\r\n\r\n\r\n\r\n\tclass stream_writer_get_length : public stream_writer {\r\n\tpublic:\r\n\t\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\t\tm_length += p_bytes;\r\n\t\t}\r\n\t\tstream_writer_get_length(t_size & p_length) : m_length(p_length) {m_length = 0;}\r\n\tprivate:\r\n\t\tt_size & m_length;\r\n\t};\r\n};\r\n\r\nt_size config_object::get_data_raw(void * p_out,t_size p_bytes) {\r\n\tt_size ret = 0;\r\n\tget_data(&stream_writer_fixedbuffer(p_out,p_bytes,ret),abort_callback_impl());\r\n\treturn ret;\r\n}\r\n\r\nt_size config_object::get_data_raw_length() {\r\n\tt_size ret = 0;\r\n\tget_data(&stream_writer_get_length(ret),abort_callback_impl());\r\n\treturn ret;\r\n}\r\n\r\nvoid config_object::set_data_raw(const void * p_data,t_size p_bytes, bool p_notify) {\r\n\tset_data(&stream_reader_memblock_ref(p_data,p_bytes),abort_callback_impl(),p_notify);\r\n}\r\n\r\nvoid config_object::set_data_string(const char * p_data,t_size p_length) {\r\n\tset_data_raw(p_data,pfc::strlen_max(p_data,p_length));\r\n}\r\n\r\nvoid config_object::get_data_string(pfc::string_base & p_out) {\r\n\tget_data(&stream_writer_string(p_out),abort_callback_impl());\r\n}\r\n\r\n\r\n//config_object_impl stuff\r\n\r\n\r\nvoid config_object_impl::get_data(stream_writer * p_stream,abort_callback & p_abort) const {\r\n\tinsync(m_sync);\r\n\tp_stream->write_object(m_data.get_ptr(),m_data.get_size(),p_abort);\r\n}\r\n\r\nvoid config_object_impl::set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify) {\r\n\tcore_api::ensure_main_thread();\r\n\r\n\t{\r\n\t\tinsync(m_sync);\r\n\t\tm_data.set_size(0);\r\n\t\tenum {delta = 1024};\r\n\t\tt_uint8 buffer[delta];\r\n\t\tfor(;;)\r\n\t\t{\r\n\t\t\tt_size delta_done = p_stream->read(buffer,delta,p_abort);\r\n\t\t\t\r\n\t\t\tif (delta_done > 0)\r\n\t\t\t{\r\n\t\t\t\tm_data.append_fromptr(buffer,delta_done);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (delta_done != delta) break;\r\n\t\t}\r\n\t}\r\n\r\n\tif (p_notify) config_object_notify_manager::g_on_changed(this);\r\n}\r\n\r\nconfig_object_impl::config_object_impl(const GUID & p_guid,const void * p_data,t_size p_bytes) : cfg_var(p_guid)\r\n{\r\n\tm_data.set_data_fromptr((const t_uint8*)p_data,p_bytes);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/config_object.h",
    "content": "#ifndef _CONFIG_OBJECT_H_\r\n#define _CONFIG_OBJECT_H_\r\n\r\nclass config_object;\r\n\r\nclass NOVTABLE config_object_notify_manager : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_changed(const service_ptr_t<config_object> & p_object) = 0;\r\n\tstatic void g_on_changed(const service_ptr_t<config_object> & p_object);\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object_notify_manager);\r\n};\r\n\r\nclass NOVTABLE config_object : public service_base\r\n{\r\npublic:\r\n\t//interface\r\n\tvirtual GUID get_guid() const = 0;\r\n\tvirtual void get_data(stream_writer * p_stream,abort_callback & p_abort) const = 0;\r\n\tvirtual void set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_sendnotify = true) = 0;\r\n\r\n\t//helpers\r\n\tstatic bool g_find(service_ptr_t<config_object> & p_out,const GUID & p_guid);\r\n\r\n\tvoid set_data_raw(const void * p_data,t_size p_bytes,bool p_sendnotify = true);\r\n\tt_size get_data_raw(void * p_out,t_size p_bytes);\r\n\tt_size get_data_raw_length();\r\n\r\n\ttemplate<class T> void get_data_struct_t(T& p_out);\r\n\ttemplate<class T> void set_data_struct_t(const T& p_in);\r\n\ttemplate<class T> static void g_get_data_struct_t(const GUID & p_guid,T & p_out);\r\n\ttemplate<class T> static void g_set_data_struct_t(const GUID & p_guid,const T & p_in);\r\n\r\n\tvoid set_data_string(const char * p_data,t_size p_length);\r\n\tvoid get_data_string(pfc::string_base & p_out);\r\n\t\r\n\tvoid get_data_bool(bool & p_out);\r\n\tvoid set_data_bool(bool p_val);\r\n\tvoid get_data_int32(t_int32 & p_out);\r\n\tvoid set_data_int32(t_int32 p_val);\r\n\tbool get_data_bool_simple(bool p_default);\r\n\tt_int32 get_data_int32_simple(t_int32 p_default);\r\n\r\n\tstatic void g_get_data_string(const GUID & p_guid,pfc::string_base & p_out);\r\n\tstatic void g_set_data_string(const GUID & p_guid,const char * p_data,t_size p_length = ~0);\r\n\r\n\tstatic void g_get_data_bool(const GUID & p_guid,bool & p_out);\r\n\tstatic void g_set_data_bool(const GUID & p_guid,bool p_val);\r\n\tstatic void g_get_data_int32(const GUID & p_guid,t_int32 & p_out);\r\n\tstatic void g_set_data_int32(const GUID & p_guid,t_int32 p_val);\r\n\tstatic bool g_get_data_bool_simple(const GUID & p_guid,bool p_default);\r\n\tstatic t_int32 g_get_data_int32_simple(const GUID & p_guid,t_int32 p_default);\r\n\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object);\r\n};\r\n\r\nclass standard_config_objects\r\n{\r\npublic:\r\n\tstatic const GUID bool_remember_window_positions, bool_ui_always_on_top,bool_playlist_stop_after_current;\r\n\tstatic const GUID bool_playback_follows_cursor, bool_cursor_follows_playback;\r\n\tstatic const GUID bool_show_keyboard_shortcuts_in_menus;\r\n\tstatic const GUID string_gui_last_directory_media,string_gui_last_directory_playlists;\r\n\tstatic const GUID int32_dynamic_bitrate_display_rate;\r\n\r\n\r\n\tinline static bool query_show_keyboard_shortcuts_in_menus() {return config_object::g_get_data_bool_simple(standard_config_objects::bool_show_keyboard_shortcuts_in_menus,true);}\r\n\tinline static bool query_remember_window_positions() {return config_object::g_get_data_bool_simple(standard_config_objects::bool_remember_window_positions,true);}\r\n\t\r\n};\r\n\r\nclass config_object_notify : public service_base\r\n{\r\npublic:\r\n\tvirtual t_size get_watched_object_count() = 0;\r\n\tvirtual GUID get_watched_object(t_size p_index) = 0;\r\n\tvirtual void on_watched_object_changed(const service_ptr_t<config_object> & p_object) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(config_object_notify);\r\n};\r\n\r\n#endif _CONFIG_OBJECT_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/config_object_impl.h",
    "content": "#ifndef _CONFIG_OBJECT_IMPL_H_\r\n#define _CONFIG_OBJECT_IMPL_H_\r\n\r\n//template function bodies from config_object class\r\n\r\ntemplate<class T>\r\nvoid config_object::get_data_struct_t(T& p_out) {\r\n\tif (get_data_raw(&p_out,sizeof(T)) != sizeof(T)) throw exception_io_data_truncation();\r\n}\r\n\r\ntemplate<class T>\r\nvoid config_object::set_data_struct_t(const T& p_in) {\r\n\treturn set_data_raw(&p_in,sizeof(T));\r\n}\r\n\r\ntemplate<class T>\r\nvoid config_object::g_get_data_struct_t(const GUID & p_guid,T & p_out) {\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\treturn ptr->get_data_struct_t<T>(p_out);\r\n}\r\n\r\ntemplate<class T>\r\nvoid config_object::g_set_data_struct_t(const GUID & p_guid,const T & p_in) {\r\n\tservice_ptr_t<config_object> ptr;\r\n\tif (!g_find(ptr,p_guid)) throw exception_service_not_found();\r\n\treturn ptr->set_data_struct_t<T>(p_in);\r\n}\r\n\r\n\r\nclass config_object_impl : public config_object, private cfg_var\r\n{\r\npublic:\r\n\tGUID get_guid() const {return cfg_var::get_guid();}\r\n\tvoid get_data(stream_writer * p_stream,abort_callback & p_abort) const ;\r\n\tvoid set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify);\r\n\r\n\tconfig_object_impl(const GUID & p_guid,const void * p_data,t_size p_bytes);\r\nprivate:\r\n\r\n\t//cfg_var methods\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {get_data(p_stream,p_abort);}\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {set_data(p_stream,p_abort,false);}\r\n\r\n\tmutable critical_section m_sync;\r\n\tpfc::array_t<t_uint8> m_data;\t\r\n};\r\n\r\ntypedef service_factory_single_transparent_t<config_object_impl> config_object_factory;\r\n\r\ntemplate<t_size p_size>\r\nclass config_object_fixed_impl_t : public config_object, private cfg_var\r\n{\r\npublic:\r\n\tGUID get_guid() const {return cfg_var::get_guid();}\r\n\t\r\n\tvoid get_data(stream_writer * p_stream,abort_callback & p_abort) const {\r\n\t\tinsync(m_sync);\r\n\t\tp_stream->write_object(m_data,p_size,p_abort);\r\n\t}\r\n\r\n\tvoid set_data(stream_reader * p_stream,abort_callback & p_abort,bool p_notify) {\r\n\t\tcore_api::ensure_main_thread();\r\n\t\t\r\n\t\t{\r\n\t\t\tt_uint8 temp[p_size];\r\n\t\t\tp_stream->read_object(temp,p_size,p_abort);\r\n\t\t\tinsync(m_sync);\r\n\t\t\tmemcpy(m_data,temp,p_size);\r\n\t\t}\r\n\r\n\t\tif (p_notify) config_object_notify_manager::g_on_changed(this);\r\n\t}\r\n\r\n\tconfig_object_fixed_impl_t (const GUID & p_guid,const void * p_data)\r\n\t\t: cfg_var(p_guid)\r\n\t{\r\n\t\tmemcpy(m_data,p_data,p_size);\r\n\t}\r\n\r\nprivate:\r\n\t//cfg_var methods\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {get_data(p_stream,p_abort);}\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {set_data(p_stream,p_abort,false);}\r\n\r\n\tmutable critical_section m_sync;\r\n\tt_uint8 m_data[p_size];\r\n\t\r\n};\r\n\r\n\r\ntemplate<t_size p_size>\r\nclass config_object_fixed_factory_t : public service_factory_single_transparent_t<config_object_fixed_impl_t<p_size> >\r\n{\r\npublic:\r\n\tconfig_object_fixed_factory_t(const GUID & p_guid,const void * p_initval)\r\n\t\t:\r\n\t\tservice_factory_single_transparent_t<config_object_fixed_impl_t<p_size> >\r\n\t\t(p_guid,p_initval)\r\n\t{}\r\n};\r\n\r\n\r\nclass config_object_string_factory : public config_object_factory\r\n{\r\npublic:\r\n\tconfig_object_string_factory(const GUID & p_guid,const char * p_string,t_size p_string_length = infinite)\r\n\t\t: config_object_factory(p_guid,p_string,pfc::strlen_max(p_string,infinite)) {}\r\n\r\n};\r\n\r\nclass config_object_bool_factory : public config_object_fixed_factory_t<1>\r\n{\r\npublic:\r\n\tconfig_object_bool_factory(const GUID & p_guid,bool p_initval)\r\n\t\t: config_object_fixed_factory_t<1>(p_guid,&p_initval) {}\r\n};\r\n\r\ntemplate<class T>\r\nclass config_object_int_factory_t : public config_object_fixed_factory_t<sizeof(T)>\r\n{\r\nprivate:\r\n\ttemplate<class T>\r\n\tstruct t_initval\r\n\t{\r\n\t\tT m_initval;\r\n\t\tt_initval(T p_initval) : m_initval(p_initval) {byte_order::order_native_to_le_t(m_initval);}\r\n\t\tT * get_ptr() {return &m_initval;}\r\n\t};\r\npublic:\r\n\tconfig_object_int_factory_t(const GUID & p_guid,T p_initval)\r\n\t\t: config_object_fixed_factory_t<sizeof(T)>(p_guid,t_initval<T>(p_initval).get_ptr() )\r\n\t{}\r\n};\r\n\r\ntypedef config_object_int_factory_t<t_int32> config_object_int32_factory;\r\n\r\n\r\n\r\nclass config_object_notify_impl_simple : public config_object_notify\r\n{\r\npublic:\r\n\tt_size get_watched_object_count() {return 1;}\r\n\tGUID get_watched_object(t_size p_index) {return m_guid;}\r\n\tvoid on_watched_object_changed(const service_ptr_t<config_object> & p_object) {m_func(p_object);}\r\n\t\r\n\ttypedef void (*t_func)(const service_ptr_t<config_object> &);\r\n\r\n\tconfig_object_notify_impl_simple(const GUID & p_guid,t_func p_func) : m_guid(p_guid), m_func(p_func) {}\r\nprivate:\r\n\tGUID m_guid;\r\n\tt_func m_func;\t\r\n};\r\n\r\ntypedef service_factory_single_transparent_t<config_object_notify_impl_simple> config_object_notify_simple_factory;\r\n\r\n#endif _CONFIG_OBJECT_IMPL_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/console.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nvoid console::info(const char * p_message) {print(p_message);}\r\nvoid console::error(const char * p_message) {formatter() << \"ERROR : \" << p_message;}\r\nvoid console::warning(const char * p_message) {formatter() << \"WARNING : \" << p_message;}\r\n\r\nvoid console::info_location(const playable_location & src) {print_location(src);}\r\nvoid console::info_location(const metadb_handle_ptr & src) {print_location(src);}\r\n\r\nvoid console::print_location(const metadb_handle_ptr & src)\r\n{\r\n\tprint_location(src->get_location());\r\n}\r\n\r\nvoid console::print_location(const playable_location & src)\r\n{\r\n\tformatter() << src;\r\n}\r\n\r\nvoid console::print(const char* p_message)\r\n{\r\n\tif (core_api::are_services_available()) {\r\n\t\tservice_ptr_t<console_receiver> ptr;\r\n\t\tservice_enum_t<console_receiver> e;\r\n\t\twhile(e.next(ptr)) ptr->print(p_message,infinite);\r\n\t}\r\n}\r\n\r\nvoid console::printf(const char* p_format,...)\r\n{\r\n\tva_list list;\r\n\tva_start(list,p_format);\r\n\tprintfv(p_format,list);\r\n\tva_end(list);\r\n}\r\n\r\nvoid console::printfv(const char* p_format,va_list p_arglist)\r\n{\r\n\tpfc::string8_fastalloc temp;\r\n\tuPrintfV(temp,p_format,p_arglist);\r\n\tprint(temp);\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/console.h",
    "content": "#ifndef _CONSOLE_H_\r\n#define _CONSOLE_H_\r\n\r\n//! Namespace with functions for sending text to console. All functions are fully multi-thread safe, though they must not be called during dll initialization or deinitialization (e.g. static object constructors or destructors) when service system is not available.\r\nnamespace console\r\n{\r\n\tvoid info(const char * p_message);\r\n\tvoid error(const char * p_message);\r\n\tvoid warning(const char * p_message);\r\n\tvoid info_location(const playable_location & src);\r\n\tvoid info_location(const metadb_handle_ptr & src);\r\n\tvoid print_location(const playable_location & src);\r\n\tvoid print_location(const metadb_handle_ptr & src);\r\n\r\n\tvoid print(const char*);\r\n    void printf(const char*,...);\r\n\tvoid printfv(const char*,va_list p_arglist);\r\n\r\n\t//! Usage: console::formatter() << \"blah \" << somenumber << \" asdf\" << somestring;\r\n\tclass formatter : public pfc::string_formatter {\r\n\tpublic:\r\n\t\t~formatter() {if (!is_empty()) console::print(get_ptr());}\r\n\t};\r\n};\r\n\r\n//! Interface receiving console output. Do not reimplement or call directly; use console namespace functions instead.\r\nclass NOVTABLE console_receiver : public service_base\r\n{\r\npublic:\r\n\tvirtual void print(const char * p_message,t_size p_message_length) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(console_receiver);\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/contextmenu.h",
    "content": "#ifndef _FOOBAR2000_MENU_ITEM_H_\r\n#define _FOOBAR2000_MENU_ITEM_H_\r\n\r\ntypedef void * t_glyph;\r\n\r\n\r\nclass NOVTABLE contextmenu_item_node {\r\npublic:\r\n\tenum t_flags {\r\n\t\tFLAG_CHECKED = 1,\r\n\t\tFLAG_DISABLED = 2,\r\n\t\tFLAG_GRAYED = 4,\r\n\t\tFLAG_DISABLED_GRAYED = FLAG_DISABLED|FLAG_GRAYED,\r\n\t};\r\n\r\n\tenum t_type {\r\n\t\tTYPE_POPUP,TYPE_COMMAND,TYPE_SEPARATOR\r\n\t};\r\n\r\n\tvirtual bool get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) = 0;\r\n\tvirtual t_type get_type() = 0;\r\n\tvirtual void execute(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) = 0;\r\n\tvirtual t_glyph get_glyph(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) {return 0;}//RESERVED\r\n\tvirtual t_size get_children_count() = 0;\r\n\tvirtual contextmenu_item_node * get_child(t_size p_index) = 0;\r\n\tvirtual bool get_description(pfc::string_base & p_out) = 0;\r\n\tvirtual GUID get_guid() = 0;\r\n\tvirtual bool is_mappable_shortcut() = 0;\r\n\r\nprotected:\r\n\tcontextmenu_item_node() {}\r\n\t~contextmenu_item_node() {}\r\n};\r\n\r\nclass NOVTABLE contextmenu_item_node_root : public contextmenu_item_node\r\n{\r\npublic:\r\n\tvirtual ~contextmenu_item_node_root() {}\r\n};\r\n\r\nclass NOVTABLE contextmenu_item_node_leaf : public contextmenu_item_node\r\n{\r\npublic:\r\n\tt_type get_type() {return TYPE_COMMAND;}\r\n\tt_size get_children_count() {return 0;}\r\n\tcontextmenu_item_node * get_child(t_size) {return NULL;}\r\n};\r\n\r\nclass NOVTABLE contextmenu_item_node_root_leaf : public contextmenu_item_node_root\r\n{\r\npublic:\r\n\tt_type get_type() {return TYPE_COMMAND;}\r\n\tt_size get_children_count() {return 0;}\r\n\tcontextmenu_item_node * get_child(t_size) {return NULL;}\r\n};\r\n\r\nclass NOVTABLE contextmenu_item_node_popup : public contextmenu_item_node\r\n{\r\npublic:\r\n\tt_type get_type() {return TYPE_POPUP;}\r\n\tvoid execute(const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller) {}\r\n\tbool get_description(pfc::string_base & p_out) {return false;}\r\n};\r\n\r\nclass NOVTABLE contextmenu_item_node_root_popup : public contextmenu_item_node_root\r\n{\r\npublic:\r\n\tt_type get_type() {return TYPE_POPUP;}\r\n\tvoid execute(const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller) {}\r\n\tbool get_description(pfc::string_base & p_out) {return false;}\r\n};\r\n\r\nclass contextmenu_item_node_separator : public contextmenu_item_node\r\n{\r\npublic:\r\n\tt_type get_type() {return TYPE_SEPARATOR;}\r\n\tvoid execute(const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller) {}\r\n\tbool get_description(pfc::string_base & p_out) {return false;}\r\n\tt_size get_children_count() {return 0;}\r\n\tbool get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) \r\n\t{\r\n\t\tp_displayflags = 0;\r\n\t\tp_out = \"---\";\r\n\t\treturn true;\r\n\t}\r\n\tcontextmenu_item_node * get_child(t_size) {return NULL;}\r\n};\r\n\r\n/*!\r\nService class for declaring context menu commands.\\n\r\nSee contextmenu_item_simple for implementation helper without dynamic menu generation features.\\n\r\nAll methods are valid from main app thread only.\r\n*/\r\nclass NOVTABLE contextmenu_item : public service_base {\r\npublic:\r\n\tenum t_enabled_state {\r\n\t\tFORCE_OFF,\r\n\t\tDEFAULT_OFF,\r\n\t\tDEFAULT_ON,\r\n\t};\r\n\r\n\tvirtual unsigned get_num_items() = 0;\r\n\tvirtual contextmenu_item_node_root * instantiate_item(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) = 0;\r\n\tvirtual GUID get_item_guid(unsigned p_index) = 0;\r\n\tvirtual void get_item_name(unsigned p_index,pfc::string_base & p_out) = 0;\r\n\tvirtual void get_item_default_path(unsigned p_index,pfc::string_base & p_out) = 0;\r\n\tvirtual bool get_item_description(unsigned p_index,pfc::string_base & p_out) = 0;\r\n\tvirtual t_enabled_state get_enabled_state(unsigned p_index) = 0;\r\n\tvirtual void item_execute_simple(unsigned p_index,const GUID & p_node,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) = 0;\r\n\r\n\tbool item_get_display_data_root(pfc::string_base & p_out,unsigned & displayflags,unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller);\r\n\tbool item_get_display_data(pfc::string_base & p_out,unsigned & displayflags,unsigned p_index,const GUID & p_node,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller);\r\n\t\r\n\tstatic const GUID caller_now_playing;\r\n\tstatic const GUID caller_playlist;\r\n\tstatic const GUID caller_undefined;\r\n\tstatic const GUID caller_keyboard_shortcut_list;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(contextmenu_item);\r\n};\r\n\r\n//! contextmenu_item implementation helper for implementing non-dynamically-generated context menu items; derive from this instead of from contextmenu_item directly if your menu items are static.\r\nclass NOVTABLE contextmenu_item_simple : public contextmenu_item\r\n{\r\nprivate:\r\n\tclass contextmenu_item_node_impl : public contextmenu_item_node_root_leaf\r\n\t{\r\n\tpublic:\r\n\t\tcontextmenu_item_node_impl(contextmenu_item_simple * p_owner,unsigned p_index) : m_owner(p_owner), m_index(p_index) {}\r\n\t\tbool get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) {return m_owner->get_display_data(m_index,p_data,p_out,p_displayflags,p_caller);}\r\n\t\tvoid execute(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller) {m_owner->context_command(m_index,p_data,p_caller);}\r\n\t\tbool get_description(pfc::string_base & p_out) {return m_owner->get_item_description(m_index,p_out);}\r\n\t\tGUID get_guid() {return pfc::guid_null;}\r\n\t\tbool is_mappable_shortcut() {return m_owner->item_is_mappable_shortcut(m_index);}\r\n\tprivate:\r\n\t\tservice_ptr_t<contextmenu_item_simple> m_owner;\r\n\t\tunsigned m_index;\r\n\t};\r\n\r\n\tcontextmenu_item_node_root * instantiate_item(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller)\r\n\t{\r\n\t\treturn new contextmenu_item_node_impl(this,p_index);\r\n\t}\r\n\r\n\r\n\tvoid item_execute_simple(unsigned p_index,const GUID & p_node,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller)\r\n\t{\r\n\t\tif (p_node == pfc::guid_null)\r\n\t\t\tcontext_command(p_index,p_data,p_caller);\r\n\t}\r\n\r\n\tvirtual bool item_is_mappable_shortcut(unsigned p_index)\r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\tvirtual bool get_display_data(unsigned n,const pfc::list_base_const_t<metadb_handle_ptr> & data,pfc::string_base & p_out,unsigned & displayflags,const GUID & caller)\r\n\t{\r\n\t\tbool rv = false;\r\n\t\tassert(n>=0 && n<get_num_items());\r\n\t\tif (data.get_count()>0)\r\n\t\t{\r\n\t\t\trv = context_get_display(n,data,p_out,displayflags,caller);\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\npublic:\r\n\t//! Same as contextmenu_item_node::t_flags.\r\n\tenum t_flags\r\n\t{\r\n\t\tFLAG_CHECKED = 1,\r\n\t\tFLAG_DISABLED = 2,\r\n\t\tFLAG_GRAYED = 4,\r\n\t\tFLAG_DISABLED_GRAYED = FLAG_DISABLED|FLAG_GRAYED,\r\n\t};\r\n\r\n\t\r\n\tvirtual t_enabled_state get_enabled_state(unsigned p_index) {return contextmenu_item::DEFAULT_ON;}\r\n\tvirtual unsigned get_num_items()=0;\r\n\tvirtual void get_item_name(unsigned p_index,pfc::string_base & p_out)=0;\r\n\tvirtual void get_item_default_path(unsigned p_index,pfc::string_base & p_out) = 0;\r\n\tvirtual void context_command(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID& p_caller)=0;\r\n\tvirtual bool context_get_display(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,pfc::string_base & p_out,unsigned & p_displayflags,const GUID & p_caller) {\r\n\t\tPFC_ASSERT(p_index>=0 && p_index<get_num_items());\r\n\t\tget_item_name(p_index,p_out);\r\n\t\treturn true;\r\n\t}\r\n\tvirtual GUID get_item_guid(unsigned p_index) = 0;\r\n\tvirtual bool get_item_description(unsigned p_index,pfc::string_base & p_out) = 0;\r\n\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nclass contextmenu_item_factory_t : public service_factory_single_t<T> {};\r\n\r\n\r\n#define DECLARE_CONTEXT_MENU_ITEM(P_CLASSNAME,P_NAME,P_DEFAULTPATH,P_FUNC,P_GUID,P_DESCRIPTION)\t\\\r\n\tnamespace { \\\r\n\t\tclass P_CLASSNAME : public contextmenu_item_simple {\t\\\r\n\t\tpublic:\t\\\r\n\t\t\tunsigned get_num_items() {return 1;}\t\\\r\n\t\t\tvoid get_item_name(unsigned p_index,pfc::string_base & p_out) {p_out = P_NAME;}\t\\\r\n\t\t\tvoid get_item_default_path(unsigned p_index,pfc::string_base & p_out) {p_out = P_DEFAULTPATH;}\t\\\r\n\t\t\tvoid context_command(unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID& p_caller) {P_FUNC(p_data);}\t\\\r\n\t\t\tGUID get_item_guid(unsigned p_index) {return P_GUID;}\t\\\r\n\t\t\tbool get_item_description(unsigned p_index,pfc::string_base & p_out) {if (P_DESCRIPTION[0] == 0) return false;p_out = P_DESCRIPTION; return true;}\t\\\r\n\t\t};\t\\\r\n\t\tstatic contextmenu_item_factory_t<P_CLASSNAME> g_##P_CLASSNAME##_factory;\t\\\r\n\t}\r\n\r\n\r\n\r\n#endif //_FOOBAR2000_MENU_ITEM_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/contextmenu_manager.h",
    "content": "#ifndef _FOOBAR2000_MENU_MANAGER_H_\r\n#define _FOOBAR2000_MENU_MANAGER_H_\r\n\r\n\r\nclass NOVTABLE keyboard_shortcut_manager : public service_base\r\n{\r\npublic:\r\n\tstatic bool g_get(service_ptr_t<keyboard_shortcut_manager> & p_out) {return service_enum_create_t(p_out,0);}\r\n\r\n\tenum shortcut_type\r\n\t{\r\n\t\tTYPE_MAIN,\r\n\t\tTYPE_CONTEXT,\r\n\t\tTYPE_CONTEXT_PLAYLIST,\r\n\t\tTYPE_CONTEXT_NOW_PLAYING,\r\n\t};\r\n\r\n\r\n\tvirtual bool process_keydown(shortcut_type type,const pfc::list_base_const_t<metadb_handle_ptr> & data,unsigned keycode)=0;\r\n\tvirtual bool process_keydown_ex(shortcut_type type,const pfc::list_base_const_t<metadb_handle_ptr> & data,unsigned keycode,const GUID & caller)=0;\r\n\tbool on_keydown(shortcut_type type,WPARAM wp);\r\n\tbool on_keydown_context(const pfc::list_base_const_t<metadb_handle_ptr> & data,WPARAM wp,const GUID & caller);\r\n\tbool on_keydown_auto(WPARAM wp);\r\n\tbool on_keydown_auto_playlist(WPARAM wp);\r\n\tbool on_keydown_auto_context(const pfc::list_base_const_t<metadb_handle_ptr> & data,WPARAM wp,const GUID & caller);\r\n\r\n\tvirtual bool get_key_description_for_action(const GUID & p_command,const GUID & p_subcommand, pfc::string_base & out, shortcut_type type, bool is_global)=0;\r\n\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(keyboard_shortcut_manager);\r\n/*\r\nusage:\r\n\r\n  in a windowproc:\r\n\r\n\tcase WM_KEYDOWN:\r\n\t\tkeyboard_shortcut_manager::get()->on_keydown(wparam);\r\n\t\tbreak;\r\n\tcase WM_SYSKEYDOWN:\r\n\t\tkeyboard_shortcut_manager::get()->on_keydown(wparam);\r\n\t\tbreak;\r\n\r\n  return value is true if key got translated to one of user-configured actions, false if not\r\n  */\r\n};\r\n\r\n\r\n\r\n\r\nclass NOVTABLE contextmenu_node {\r\npublic:\r\n\tvirtual contextmenu_item_node::t_type get_type()=0;\r\n\tvirtual const char * get_name()=0;\r\n\tvirtual t_size get_num_children()=0;//TYPE_POPUP only\r\n\tvirtual contextmenu_node * get_child(t_size n)=0;//TYPE_POPUP only\r\n\tvirtual unsigned get_display_flags()=0;//TYPE_COMMAND/TYPE_POPUP only, see contextmenu_item::FLAG_*\r\n\tvirtual unsigned get_id()=0;//TYPE_COMMAND only, returns zero-based index (helpful for win32 menu command ids)\r\n\tvirtual void execute()=0;//TYPE_COMMAND only\r\n\tvirtual bool get_description(pfc::string_base & out)=0;//TYPE_COMMAND only\r\n\tvirtual bool get_full_name(pfc::string_base & out)=0;//TYPE_COMMAND only\r\n\tvirtual void * get_glyph()=0;//RESERVED, do not use\r\nprotected:\r\n\tcontextmenu_node() {}\r\n\t~contextmenu_node() {}\r\n};\r\n\r\n\r\n\r\nclass NOVTABLE contextmenu_manager : public service_base\r\n{\r\npublic:\r\n\tenum\r\n\t{\r\n\t\tFLAG_SHOW_SHORTCUTS = 1,\r\n\t\tFLAG_SHOW_SHORTCUTS_GLOBAL = 2,\r\n\t};\r\n\tvirtual void init_context(const pfc::list_base_const_t<metadb_handle_ptr> & data,unsigned flags)=0;//flags - see FLAG_* above\r\n\tvirtual void init_context_playlist(unsigned flags)=0;\r\n\tvirtual contextmenu_node * get_root()=0;//releasing contextmenu_manager service releaases nodes; root may be null in case of error or something\r\n\tvirtual contextmenu_node * find_by_id(unsigned id)=0;\r\n\tvirtual void set_shortcut_preference(const keyboard_shortcut_manager::shortcut_type * data,unsigned count)=0;\r\n\t\r\n\r\n\r\n\tstatic void g_create(service_ptr_t<contextmenu_manager> & p_out) {p_out = standard_api_create_t<contextmenu_manager>();}\r\n\r\n#ifdef WIN32\r\n\tstatic void win32_build_menu(HMENU menu,contextmenu_node * parent,int base_id,int max_id);//menu item identifiers are base_id<=N<base_id+max_id (if theres too many items, they will be clipped)\r\n\tstatic void win32_run_menu_context(HWND parent,const pfc::list_base_const_t<metadb_handle_ptr> & data, const POINT * pt = 0,unsigned flags = 0);\r\n\tstatic void win32_run_menu_context_playlist(HWND parent,const POINT * pt = 0,unsigned flags = 0);\r\n\tvoid win32_run_menu_popup(HWND parent,const POINT * pt = 0);\r\n\tvoid win32_build_menu(HMENU menu,int base_id,int max_id) {win32_build_menu(menu,get_root(),base_id,max_id);}\r\n\t\r\n\t\r\n#endif\r\n\r\n\tvirtual void init_context_ex(const pfc::list_base_const_t<metadb_handle_ptr> & data,unsigned flags,const GUID & caller)=0;\r\n\tvirtual bool init_context_now_playing(unsigned flags)=0;//returns false if not playing\r\n\r\n\tbool execute_by_id(unsigned id);\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(contextmenu_manager);\r\n};\r\n\r\n\r\n\r\n#endif //_FOOBAR2000_MENU_MANAGER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/core_api.h",
    "content": "#ifndef _CORE_API_H_\r\n#define _CORE_API_H_\r\n\r\nnamespace core_api {\r\n\r\n\t//! Exception thrown by APIs locked to main app thread when called from another thread.\r\n\tPFC_DECLARE_EXCEPTION(exception_wrong_thread,pfc::exception_bug_check,\"This method can be called only from the main thread\");\r\n\r\n\t//! Retrieves HINSTANCE of calling DLL.\r\n\tHINSTANCE get_my_instance();\r\n\t//! Retrieves filename of calling dll, excluding extension, e.g. \"foo_asdf\"\r\n\tconst char * get_my_file_name();\r\n\t//! Retrieves full path of calling dll, e.g. file://c:\\blah\\foobar2000\\foo_asdf.dll\r\n\tconst char * get_my_full_path();\r\n\t//! Retrieves main app window. WARNING: this is provided for parent of dialog windows and such only; using it for anything else (such as hooking windowproc to alter app behaviors) is absolutely illegal.\r\n\tHWND get_main_window();\r\n\t//! Tests whether services are available at this time. They are not available only during DLL startup or shutdown (e.g. inside static object constructors or destructors).\r\n\tbool are_services_available();\r\n\t//! Tests whether calling thread is main app thread, and shows diagnostic message in debugger output if it's not.\r\n\tbool assert_main_thread();\r\n\t//! Throws exception_wrong_thread if calling thread is not main app thread.\r\n\tvoid ensure_main_thread();\r\n\t//! Returns true if calling thread is main app thread, false otherwise.\r\n\tbool is_main_thread();\r\n\t//! Returns whether the app is currently shutting down.\r\n\tbool is_shutting_down();\r\n\t//! Returns whether the app is currently initializing.\r\n\tbool is_initializing();\r\n\t//! Returns filesystem path to directory with user settings, e.g. file://c:\\documents_and_settings\\username\\blah\\foobar2000\r\n\tconst char * get_profile_path();\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/coreversion.h",
    "content": "#ifndef _COREVERSION_H_\r\n#define _COREVERSION_H_\r\n\r\nclass NOVTABLE core_version_info : public service_base {\r\npublic:\r\n\tvirtual const char * get_version_string() = 0;\r\n\tstatic const char * g_get_version_string() {return static_api_ptr_t<core_version_info>()->get_version_string();}\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(core_version_info);\r\n};\r\n\r\nstruct t_core_version_data {\r\n\tt_uint32 m_major, m_minor1, m_minor2, m_minor3;\r\n};\r\n\r\n//! New (0.9.4.2)\r\nclass NOVTABLE core_version_info_v2 : public core_version_info {\r\npublic:\r\n\tvirtual const char * get_name() = 0;//\"foobar2000\"\r\n\tvirtual const char * get_version_as_text() = 0;//\"N.N.N.N\"\r\n\tvirtual t_core_version_data get_version() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(core_version_info_v2, core_version_info);\r\n};\r\n\r\n#endif //_COREVERSION_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/dsp.cpp",
    "content": "#include \"foobar2000.h\"\r\n#include <math.h>\r\n\r\nt_size dsp_chunk_list_impl::get_count() const {return m_data.get_count();}\r\n\r\naudio_chunk * dsp_chunk_list_impl::get_item(t_size n) const {return n>=0 && n<m_data.get_count() ? &*m_data[n] : 0;}\r\n\r\nvoid dsp_chunk_list_impl::remove_by_idx(t_size idx)\r\n{\r\n\tif (idx>=0 && idx<m_data.get_count())\r\n\t\tm_recycled.add_item(m_data.remove_by_idx(idx));\r\n}\r\n\r\nvoid dsp_chunk_list_impl::remove_mask(const bit_array & mask)\r\n{\r\n\tt_size n, m = m_data.get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t\tif (mask[m])\r\n\t\t\tm_recycled.add_item(m_data[n]);\r\n\tm_data.remove_mask(mask);\r\n}\r\n\r\naudio_chunk * dsp_chunk_list_impl::insert_item(t_size idx,t_size hint_size)\r\n{\r\n\tt_size max = get_count();\r\n\tif (idx<0) idx=0;\r\n\telse if (idx>max) idx = max;\r\n\tpfc::rcptr_t<audio_chunk> ret;\r\n\tif (m_recycled.get_count()>0)\r\n\t{\r\n\t\tt_size best;\r\n\t\tif (hint_size>0)\r\n\t\t{\r\n\t\t\tbest = 0;\r\n\t\t\tt_size best_found = m_recycled[0]->get_data_size(), n, total = m_recycled.get_count();\r\n\t\t\tfor(n=1;n<total;n++)\r\n\t\t\t{\r\n\t\t\t\tif (best_found==hint_size) break;\r\n\t\t\t\tt_size size = m_recycled[n]->get_data_size();\r\n\t\t\t\tint delta_old = abs((int)best_found - (int)hint_size), delta_new = abs((int)size - (int)hint_size);\r\n\t\t\t\tif (delta_new < delta_old)\r\n\t\t\t\t{\r\n\t\t\t\t\tbest_found = size;\r\n\t\t\t\t\tbest = n;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse best = m_recycled.get_count()-1;\r\n\r\n\t\tret = m_recycled.remove_by_idx(best);\r\n\t\tret->set_sample_count(0);\r\n\t\tret->set_channels(0);\r\n\t\tret->set_srate(0);\r\n\t}\r\n\telse ret = pfc::rcnew_t<audio_chunk_impl>();\r\n\tif (idx==max) m_data.add_item(ret);\r\n\telse m_data.insert_item(ret,idx);\r\n\treturn &*ret;\r\n}\r\n\r\nvoid dsp_chunk_list::remove_bad_chunks()\r\n{\r\n\tbool blah = false;\r\n\tt_size idx;\r\n\tfor(idx=0;idx<get_count();)\r\n\t{\r\n\t\taudio_chunk * chunk = get_item(idx);\r\n\t\tif (!chunk->is_valid())\r\n\t\t{\r\n\t\t\tchunk->reset();\r\n\t\t\tremove_by_idx(idx);\r\n\t\t\tblah = true;\r\n\t\t}\r\n\t\telse idx++;\r\n\t}\r\n\tif (blah) console::info(\"one or more bad chunks removed from dsp chunk list\");\r\n}\r\n\r\n\r\nbool dsp_entry::g_instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr;\r\n\tif (!g_get_interface(ptr,p_preset.get_owner())) return false;\r\n\treturn ptr->instantiate(p_out,p_preset);\r\n}\r\n\r\nbool dsp_entry::g_instantiate_default(service_ptr_t<dsp> & p_out,const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr;\r\n\tif (!g_get_interface(ptr,p_guid)) return false;\r\n\tdsp_preset_impl preset;\r\n\tif (!ptr->get_default_preset(preset)) return false;\r\n\treturn ptr->instantiate(p_out,preset);\r\n}\r\n\r\nbool dsp_entry::g_name_from_guid(pfc::string_base & p_out,const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr;\r\n\tif (!g_get_interface(ptr,p_guid)) return false;\r\n\tptr->get_name(p_out);\r\n\treturn true;\r\n}\r\n\r\nbool dsp_entry::g_dsp_exists(const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> blah;\r\n\treturn g_get_interface(blah,p_guid);\r\n}\r\n\r\nbool dsp_entry::g_get_default_preset(dsp_preset & p_out,const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr;\r\n\tif (!g_get_interface(ptr,p_guid)) return false;\r\n\treturn ptr->get_default_preset(p_out);\r\n}\r\n\r\nvoid dsp_chain_config::contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const {\r\n\tt_size n, count = get_count();\r\n\tp_stream->write_lendian_t(count,p_abort);\r\n\tfor(n=0;n<count;n++) {\r\n\t\tget_item(n).contents_to_stream(p_stream,p_abort);\r\n\t}\r\n}\r\n\r\nvoid dsp_chain_config::contents_from_stream(stream_reader * p_stream,abort_callback & p_abort) {\r\n\tt_uint32 n,count;\r\n\r\n\tremove_all();\r\n\r\n\tp_stream->read_lendian_t(count,p_abort);\r\n\r\n\tdsp_preset_impl temp;\r\n\r\n\tfor(n=0;n<count;n++) {\r\n\t\ttemp.contents_from_stream(p_stream,p_abort);\r\n\t\tadd_item(temp);\r\n\t}\r\n}\r\n\r\n\r\nbool cfg_dsp_chain_config::get_data(dsp_chain_config & p_data) const {\r\n\tp_data.copy(m_data);\r\n\treturn true;\r\n}\r\n\r\nvoid cfg_dsp_chain_config::set_data(const dsp_chain_config & p_data) {\r\n\tm_data.copy(p_data);\r\n}\r\n\r\nvoid cfg_dsp_chain_config::reset() {\r\n\tm_data.remove_all();\r\n}\r\n\r\nvoid cfg_dsp_chain_config::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\tm_data.contents_to_stream(p_stream,p_abort);\r\n}\r\n\r\nvoid cfg_dsp_chain_config::set_data_raw(stream_reader * p_stream,t_size,abort_callback & p_abort) {\r\n\tm_data.contents_from_stream(p_stream,p_abort);\r\n}\r\n\r\nvoid dsp_chain_config::remove_item(t_size p_index)\r\n{\r\n\tremove_mask(bit_array_one(p_index));\r\n}\r\n\r\nvoid dsp_chain_config::add_item(const dsp_preset & p_data)\r\n{\r\n\tinsert_item(p_data,get_count());\r\n}\r\n\r\nvoid dsp_chain_config::remove_all()\r\n{\r\n\tremove_mask(bit_array_true());\r\n}\r\n\r\nvoid dsp_chain_config::instantiate(service_list_t<dsp> & p_out)\r\n{\r\n\tp_out.remove_all();\r\n\tt_size n, m = get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tservice_ptr_t<dsp> temp;\r\n\t\tif (dsp_entry::g_instantiate(temp,get_item(n)))\r\n\t\t\tp_out.add_item(temp);\r\n\t}\r\n}\r\n\r\nt_size dsp_chain_config_impl::get_count() const\r\n{\r\n\treturn m_data.get_count();\r\n}\r\n\r\nconst dsp_preset & dsp_chain_config_impl::get_item(t_size p_index) const\r\n{\r\n\treturn *m_data[p_index];\r\n}\r\n\r\nvoid dsp_chain_config_impl::replace_item(const dsp_preset & p_data,t_size p_index)\r\n{\r\n\t*m_data[p_index] = p_data;\r\n}\r\n\r\nvoid dsp_chain_config_impl::insert_item(const dsp_preset & p_data,t_size p_index)\r\n{\r\n\tm_data.insert_item(new dsp_preset_impl(p_data),p_index);\r\n}\r\n\r\nvoid dsp_chain_config_impl::remove_mask(const bit_array & p_mask)\r\n{\r\n\tm_data.delete_mask(p_mask);\r\n}\r\n\r\ndsp_chain_config_impl::~dsp_chain_config_impl()\r\n{\r\n\tm_data.delete_all();\r\n}\r\n\r\nvoid dsp_preset::contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const {\r\n\tt_size size = get_data_size();\r\n\tp_stream->write_lendian_t(get_owner(),p_abort);\r\n\tp_stream->write_lendian_t(size,p_abort);\r\n\tif (size > 0) {\r\n\t\tp_stream->write_object(get_data(),size,p_abort);\r\n\t}\r\n}\r\n\r\nvoid dsp_preset::contents_from_stream(stream_reader * p_stream,abort_callback & p_abort) {\r\n\tt_uint32 size;\r\n\tGUID guid;\r\n\tp_stream->read_lendian_t(guid,p_abort);\r\n\tset_owner(guid);\r\n\tp_stream->read_lendian_t(size,p_abort);\r\n\tif (size > 1024*1024*32) throw exception_io_data();\r\n\tset_data_from_stream(p_stream,size,p_abort);\r\n}\r\n\r\nvoid dsp_preset::g_contents_from_stream_skip(stream_reader * p_stream,abort_callback & p_abort) {\r\n\tt_uint32 size;\r\n\tGUID guid;\r\n\tp_stream->read_lendian_t(guid,p_abort);\r\n\tp_stream->read_lendian_t(size,p_abort);\r\n\tif (size > 1024*1024*32) throw exception_io_data();\r\n\tp_stream->skip_object(size,p_abort);\r\n}\r\n\r\nvoid dsp_preset_impl::set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) {\r\n\tm_data.set_size(p_bytes);\r\n\tif (p_bytes > 0) p_stream->read_object(m_data.get_ptr(),p_bytes,p_abort);\r\n}\r\n\r\nvoid dsp_chain_config::copy(const dsp_chain_config & p_source) {\r\n\tremove_all();\r\n\tt_size n, m = p_source.get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t\tadd_item(p_source.get_item(n));\r\n}\r\n\r\nbool dsp_entry::g_have_config_popup(const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> entry;\r\n\tif (!g_get_interface(entry,p_guid)) return false;\r\n\treturn entry->have_config_popup();\r\n}\r\n\r\nbool dsp_entry::g_have_config_popup(const dsp_preset & p_preset)\r\n{\r\n\treturn g_have_config_popup(p_preset.get_owner());\r\n}\r\n\r\nbool dsp_entry::g_show_config_popup(dsp_preset & p_preset,HWND p_parent)\r\n{\r\n\tservice_ptr_t<dsp_entry> entry;\r\n\tif (!g_get_interface(entry,p_preset.get_owner())) return false;\r\n\treturn entry->show_config_popup(p_preset,p_parent);\r\n}\r\n\r\nvoid dsp_entry::g_show_config_popup_v2(const dsp_preset & p_preset,HWND p_parent,dsp_preset_edit_callback & p_callback) {\r\n\tservice_ptr_t<dsp_entry> entry;\r\n\tif (g_get_interface(entry,p_preset.get_owner())) {\r\n\t\tservice_ptr_t<dsp_entry_v2> entry_v2;\r\n\t\tif (entry->service_query_t(entry_v2)) {\r\n\t\t\tentry_v2->show_config_popup_v2(p_preset,p_parent,p_callback);\r\n\t\t} else {\r\n\t\t\tdsp_preset_impl temp(p_preset);\r\n\t\t\tif (entry->show_config_popup(temp,p_parent)) p_callback.on_preset_changed(temp);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool dsp_entry::g_get_interface(service_ptr_t<dsp_entry> & p_out,const GUID & p_guid)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr;\r\n\tservice_enum_t<dsp_entry> e;\r\n\te.reset();\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->get_guid() == p_guid)\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool resampler_entry::g_get_interface(service_ptr_t<resampler_entry> & p_out,unsigned p_srate_from,unsigned p_srate_to)\r\n{\r\n\tservice_ptr_t<dsp_entry> ptr_dsp;\r\n\tservice_ptr_t<resampler_entry> ptr_resampler;\r\n\tservice_enum_t<dsp_entry> e;\r\n\te.reset();\r\n\tfloat found_priority = 0;\r\n\tservice_ptr_t<resampler_entry> found;\r\n\twhile(e.next(ptr_dsp))\r\n\t{\r\n\t\tif (ptr_dsp->service_query_t(ptr_resampler))\r\n\t\t{\r\n\t\t\tif (p_srate_from == 0 || ptr_resampler->is_conversion_supported(p_srate_from,p_srate_to))\r\n\t\t\t{\r\n\t\t\t\tfloat priority = ptr_resampler->get_priority();\r\n\t\t\t\tif (found.is_empty() || priority > found_priority)\r\n\t\t\t\t{\r\n\t\t\t\t\tfound = ptr_resampler;\r\n\t\t\t\t\tfound_priority = priority;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (found.is_empty()) return false;\r\n\tp_out = found;\r\n\treturn true;\r\n}\r\n\r\nbool resampler_entry::g_create_preset(dsp_preset & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale)\r\n{\r\n\tservice_ptr_t<resampler_entry> entry;\r\n\tif (!g_get_interface(entry,p_srate_from,p_srate_to)) return false;\r\n\treturn entry->create_preset(p_out,p_srate_to,p_qualityscale);\r\n}\r\n\r\nbool resampler_entry::g_create(service_ptr_t<dsp> & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale)\r\n{\r\n\tservice_ptr_t<resampler_entry> entry;\r\n\tif (!g_get_interface(entry,p_srate_from,p_srate_to)) return false;\r\n\tdsp_preset_impl preset;\r\n\tif (!entry->create_preset(preset,p_srate_to,p_qualityscale)) return false;\r\n\treturn entry->instantiate(p_out,preset);\r\n}\r\n\r\n\r\nvoid dsp_chain_config::get_name_list(pfc::string_base & p_out) const\r\n{\r\n\tconst t_size count = get_count();\r\n\tbool added = false;\r\n\tfor(unsigned n=0;n<count;n++)\r\n\t{\r\n\t\tservice_ptr_t<dsp_entry> ptr;\r\n\t\tif (dsp_entry::g_get_interface(ptr,get_item(n).get_owner()))\r\n\t\t{\r\n\t\t\tif (added) p_out += \", \";\r\n\t\t\tadded = true;\r\n\r\n\t\t\tpfc::string8 temp;\r\n\t\t\tptr->get_name(temp);\r\n\t\t\tp_out += temp;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid dsp::run_abortable(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) {\r\n\tservice_ptr_t<dsp_v2> this_v2;\r\n\tif (this->service_query_t(this_v2)) this_v2->run_v2(p_chunk_list,p_cur_file,p_flags,p_abort);\r\n\telse run(p_chunk_list,p_cur_file,p_flags);\r\n}\r\n\r\nnamespace {\r\n\tclass dsp_preset_edit_callback_impl : public dsp_preset_edit_callback {\r\n\tpublic:\r\n\t\tdsp_preset_edit_callback_impl(dsp_preset & p_data) : m_data(p_data) {}\r\n\t\tvoid on_preset_changed(const dsp_preset & p_data) {m_data = p_data;}\r\n\tprivate:\r\n\t\tdsp_preset & m_data;\r\n\t};\r\n};\r\n\r\nbool dsp_entry_v2::show_config_popup(dsp_preset & p_data,HWND p_parent) {\r\n\tPFC_ASSERT(p_data.get_owner() == get_guid());\r\n\tdsp_preset_impl temp(p_data);\r\n\tshow_config_popup_v2(p_data,p_parent,dsp_preset_edit_callback_impl(temp));\r\n\tPFC_ASSERT(temp.get_owner() == get_guid());\r\n\tif (temp == p_data) return false;\r\n\tp_data = temp;\r\n\treturn true;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/dsp.h",
    "content": "class NOVTABLE dsp_chunk_list {\r\npublic:\r\n\tvirtual t_size get_count() const = 0;\r\n\tvirtual audio_chunk * get_item(t_size n) const = 0;\r\n\tvirtual void remove_by_idx(t_size idx) = 0;\r\n\tvirtual void remove_mask(const bit_array & mask) = 0;\r\n\tvirtual audio_chunk * insert_item(t_size idx,t_size hint_size=0) = 0;\r\n\r\n\taudio_chunk * add_item(t_size hint_size=0) {return insert_item(get_count(),hint_size);}\r\n\r\n\tvoid remove_all() {remove_mask(bit_array_true());}\r\n\r\n\tdouble get_duration() {\r\n\t\tdouble rv = 0;\r\n\t\tt_size n,m = get_count();\r\n\t\tfor(n=0;n<m;n++) rv += get_item(n)->get_duration();\r\n\t\treturn rv;\r\n\t}\r\n\r\n\tvoid add_chunk(const audio_chunk * chunk) {\r\n\t\taudio_chunk * dst = insert_item(get_count(),chunk->get_data_length());\r\n\t\tif (dst) dst->copy(*chunk);\r\n\t}\r\n\r\n\tvoid remove_bad_chunks();\r\nprotected:\r\n\tdsp_chunk_list() {}\r\n\t~dsp_chunk_list() {}\r\n};\r\n\r\nclass dsp_chunk_list_impl : public dsp_chunk_list//implementation\r\n{\r\n\tpfc::list_t<pfc::rcptr_t<audio_chunk> > m_data, m_recycled;\r\npublic:\r\n\tt_size get_count() const;\r\n\taudio_chunk * get_item(t_size n) const;\r\n\tvoid remove_by_idx(t_size idx);\r\n\tvoid remove_mask(const bit_array & mask);\r\n\taudio_chunk * insert_item(t_size idx,t_size hint_size=0);\r\n};\r\n\r\n//! Instance of a DSP.\\n\r\n//! Implementation: Derive from dsp_impl_base instead of deriving from dsp directly.\\n\r\n//! Instantiation: Use dsp_entry static helper methods to instantiate DSPs, or dsp_chain_config / dsp_manager to deal with entire DSP chains.\r\nclass NOVTABLE dsp : public service_base {\r\npublic:\r\n\tenum {\r\n\t\t//! Flush whatever you need to when tracks change.\r\n\t\tEND_OF_TRACK = 1,\r\n\t\t//! Flush everything.\r\n\t\tFLUSH = 2\t\r\n\t};\r\n\r\n\t//! @param p_chunk_list List of chunks to process. The implementation may alter the list in any way, inserting chunks of different sample rate / channel configuration etc.\r\n\t//! @param p_cur_file Optional, location of currently decoded file. May be null.\r\n\t//! @param p_flags Flags. Can be null, or a combination of END_OF_TRACK and FLUSH constants.\r\n\tvirtual void run(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags)=0;\r\n\r\n\t//! Flushes the DSP (reinitializes / drops any buffered data). Called after seeking, etc.\r\n\tvirtual void flush() = 0;\r\n\r\n\t//! Retrieves amount of data buffered by the DSP, for syncing visualisation.\r\n\t//! @returns Amount of buffered audio data, in seconds.\r\n\tvirtual double get_latency() = 0;\r\n\t//! Returns true if DSP needs to know exact track change point (eg. for crossfading, removing silence).\\n\r\n\t//! Signaling this will force-flush any DSPs placed before this DSP so when it gets END_OF_TRACK, relevant chunks contain last samples of the track.\\n\r\n\t//! Signaling this will often break regular gapless playback so don't use it unless you have reasons to.\r\n\tvirtual bool need_track_change_mark() = 0;\r\n\r\n\tvoid run_abortable(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(dsp,service_base);\r\n};\r\n\r\n//! Backwards-compatible extension to dsp interface, allows abortable operation. Introduced in 0.9.2.\r\nclass NOVTABLE dsp_v2 : public dsp {\r\npublic:\r\n\t//! Abortable version of dsp::run(). See dsp::run() for descriptions of parameters.\r\n\tvirtual void run_v2(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) = 0;\r\nprivate:\r\n\tvoid run(dsp_chunk_list * p_chunk_list,const metadb_handle_ptr & p_cur_file,int p_flags) {\r\n\t\trun_v2(p_chunk_list,p_cur_file,p_flags,abort_callback_impl());\r\n\t}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(dsp_v2,dsp);\r\n};\r\n\r\n//! Helper class for implementing dsps. You should derive from dsp_impl_base instead of from dsp directly.\\n\r\n//! The dsp_impl_base_t template allows you to use a custom interface class as a base class for your implementation, in case you provide extended functionality.\\n\r\n//! Use dsp_factory_t<> template to register your dsp implementation.\r\n//! The implementation - as required by dsp_factory_t<> template - must also provide following methods:\\n\r\n//! A constructor taking const dsp_preset&, initializing the DSP with specified preset data.\\n\r\n//! static void g_get_name(pfc::string_base &); - retrieving human-readable name of the DSP to display.\\n\r\n//! static bool g_get_default_preset(dsp_preset &); - retrieving default preset for this DSP. Return value is reserved for future use and should always be true.\\n\r\n//! static GUID g_get_guid(); - retrieving GUID of your DSP implementation, to be used to identify it when storing DSP chain configuration.\\n\r\n//! static bool g_have_config_popup(); - retrieving whether your DSP implementation supplies a popup dialog for configuring it.\\n\r\n//! static void g_show_config_popup(const dsp_preset & p_data,HWND p_parent, dsp_preset_edit_callback & p_callback); - displaying your DSP's settings dialog; called only when g_have_config_popup() returns true; call p_callback.on_preset_changed() whenever user has made adjustments to the preset data.\\n\r\ntemplate<class t_baseclass>\r\nclass dsp_impl_base_t : public t_baseclass {\r\nprivate:\r\n\ttypedef dsp_impl_base_t<t_baseclass> t_self;\r\n\tdsp_chunk_list * m_list;\r\n\tt_size m_chunk_ptr;\r\n\tmetadb_handle* m_cur_file;\r\n\tvoid run_v2(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort);\r\nprotected:\r\n\tbool get_cur_file(metadb_handle_ptr & p_out) {p_out = m_cur_file; return p_out.is_valid();}// call only from on_chunk / on_endoftrack (on_endoftrack will give info on track being finished); may return null !!\r\n\t\r\n\tdsp_impl_base_t() : m_list(NULL), m_cur_file(NULL), m_chunk_ptr(0) {}\r\n\t\r\n\taudio_chunk * insert_chunk(t_size p_hint_size = 0)\t//call only from on_endoftrack / on_endofplayback / on_chunk\r\n\t{//hint_size - optional, amout of buffer space you want to use\r\n\t\tPFC_ASSERT(m_list != NULL);\r\n\t\treturn m_list->insert_item(m_chunk_ptr++,p_hint_size);\r\n\t}\r\n\r\n\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Called on track change. You can use insert_chunk() to dump any data you have to flush. \\n\r\n\t//! Note that you must implement need_track_change_mark() to return true if you need this method called.\r\n\tvirtual void on_endoftrack(abort_callback & p_abort) = 0;\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Called at the end of played stream, typically at the end of last played track, to allow the DSP to return all data it has buffered-ahead.\\n\r\n\t//! Use insert_chunk() to return any data you have buffered.\\n\r\n\t//! Note that this call does not imply that the DSP will be destroyed next. \\n\r\n\t//! This is also called on track changes if some DSP placed after your DSP requests track change marks.\r\n\tvirtual void on_endofplayback(abort_callback & p_abort) = 0;\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Processes a chunk of audio data.\\n\r\n\t//! You can call insert_chunk() from inside on_chunk() to insert any audio data before currently processed chunk.\\n\r\n\t//! @param p_chunk Current chunk being processed. You can alter it in any way you like.\r\n\t//! @returns True to keep p_chunk (with alterations made inside on_chunk()) in the stream, false to remove it.\r\n\tvirtual bool on_chunk(audio_chunk * p_chunk,abort_callback & p_abort) = 0;\r\n\r\npublic:\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Flushes the DSP (reinitializes / drops any buffered data). Called after seeking, etc.\r\n\tvirtual void flush() = 0;\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Retrieves amount of data buffered by the DSP, for syncing visualisation.\r\n\t//! @returns Amount of buffered audio data, in seconds.\r\n\tvirtual double get_latency() = 0;\r\n\t//! To be overridden by a DSP implementation.\\n\r\n\t//! Returns true if DSP needs to know exact track change point (eg. for crossfading, removing silence).\\n\r\n\t//! Signaling this will force-flush any DSPs placed before this DSP so when it gets on_endoftrack(), relevant chunks contain last samples of the track.\\n\r\n\t//! Signaling this may interfere with gapless playback in certain scenarios (forces flush of DSPs placed before you) so don't use it unless you have reasons to.\r\n\tvirtual bool need_track_change_mark() = 0;\r\nprivate:\r\n\tdsp_impl_base_t(const t_self&) {throw pfc::exception_bug_check();}\r\n\tconst t_self & operator=(const t_self &) {throw pfc::exception_bug_check();}\r\n};\r\n\r\ntemplate<class t_baseclass>\r\nvoid dsp_impl_base_t<t_baseclass>::run_v2(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,int p_flags,abort_callback & p_abort) {\r\n\tpfc::vartoggle_t<dsp_chunk_list*> l_list_toggle(m_list,p_list);\r\n\tpfc::vartoggle_t<metadb_handle*> l_cur_file_toggle(m_cur_file,p_cur_file.get_ptr());\r\n\t\r\n\tfor(m_chunk_ptr = 0;m_chunk_ptr<m_list->get_count();m_chunk_ptr++) {\r\n\t\taudio_chunk * c = m_list->get_item(m_chunk_ptr);\r\n\t\tif (c->is_empty() || !on_chunk(c,p_abort))\r\n\t\t\tm_list->remove_by_idx(m_chunk_ptr--);\r\n\t}\r\n\r\n\tif (p_flags & FLUSH) {\r\n\t\ton_endofplayback(p_abort);\r\n\t} else if (p_flags & END_OF_TRACK) {\r\n\t\tif (need_track_change_mark()) on_endoftrack(p_abort);\r\n\t}\r\n}\r\n\r\n\r\ntypedef dsp_impl_base_t<dsp_v2> dsp_impl_base;\r\n\r\nclass NOVTABLE dsp_preset {\r\npublic:\r\n\tvirtual GUID get_owner() const = 0;\r\n\tvirtual void set_owner(const GUID & p_owner) = 0;\r\n\tvirtual const void * get_data() const = 0;\r\n\tvirtual t_size get_data_size() const = 0;\r\n\tvirtual void set_data(const void * p_data,t_size p_data_size) = 0;\r\n\tvirtual void set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) = 0;\r\n\r\n\tconst dsp_preset & operator=(const dsp_preset & p_source) {copy(p_source); return *this;}\r\n\r\n\tvoid copy(const dsp_preset & p_source) {set_owner(p_source.get_owner());set_data(p_source.get_data(),p_source.get_data_size());}\r\n\r\n\tvoid contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const;\r\n\tvoid contents_from_stream(stream_reader * p_stream,abort_callback & p_abort);\r\n\tstatic void g_contents_from_stream_skip(stream_reader * p_stream,abort_callback & p_abort);\r\n\r\n\tbool operator==(const dsp_preset & p_other) const {\r\n\t\tif (get_owner() != p_other.get_owner()) return false;\r\n\t\tif (get_data_size() != p_other.get_data_size()) return false;\r\n\t\tif (memcmp(get_data(),p_other.get_data(),get_data_size()) != 0) return false;\r\n\t\treturn true;\r\n\t}\r\n\tbool operator!=(const dsp_preset & p_other) const {\r\n\t\treturn !(*this == p_other);\r\n\t}\r\nprotected:\r\n\tdsp_preset() {}\r\n\t~dsp_preset() {}\r\n};\r\n\r\nclass dsp_preset_writer : public stream_writer {\r\npublic:\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\tm_data.append_fromptr((const t_uint8 *) p_buffer,p_bytes);\r\n\t}\r\n\tvoid flush(dsp_preset & p_preset) {\r\n\t\tp_preset.set_data(m_data.get_ptr(),m_data.get_size());\r\n\t\tm_data.set_size(0);\r\n\t}\r\nprivate:\r\n\tpfc::array_t<t_uint8,pfc::alloc_fast_aggressive> m_data;\r\n};\r\n\r\nclass dsp_preset_reader : public stream_reader {\r\npublic:\r\n\tdsp_preset_reader() : m_walk(0) {}\r\n\tdsp_preset_reader(const dsp_preset_reader & p_source) : m_walk(0) {*this = p_source;}\r\n\tvoid init(const dsp_preset & p_preset) {\r\n\t\tm_data.set_data_fromptr( (const t_uint8*) p_preset.get_data(), p_preset.get_data_size() );\r\n\t\tm_walk = 0;\r\n\t}\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\tt_size todo = pfc::min_t<t_size>(p_bytes,m_data.get_size()-m_walk);\r\n\t\tmemcpy(p_buffer,m_data.get_ptr()+m_walk,todo);\r\n\t\tm_walk += todo;\r\n\t\treturn todo;\r\n\t}\r\n\tbool is_finished() {return m_walk == m_data.get_size();}\r\nprivate:\r\n\tt_size m_walk;\r\n\tpfc::array_t<t_uint8> m_data;\r\n};\r\n\r\nclass dsp_preset_impl : public dsp_preset\r\n{\r\npublic:\r\n\tdsp_preset_impl() {}\r\n\tdsp_preset_impl(const dsp_preset_impl & p_source) {copy(p_source);}\r\n\tdsp_preset_impl(const dsp_preset & p_source) {copy(p_source);}\r\n\r\n\tconst dsp_preset_impl& operator=(const dsp_preset_impl & p_source) {copy(p_source); return *this;}\r\n\tconst dsp_preset_impl& operator=(const dsp_preset & p_source) {copy(p_source); return *this;}\r\n\r\n\tGUID get_owner() const {return m_owner;}\r\n\tvoid set_owner(const GUID & p_owner) {m_owner = p_owner;}\r\n\tconst void * get_data() const {return m_data.get_ptr();}\r\n\tt_size get_data_size() const {return m_data.get_size();}\r\n\tvoid set_data(const void * p_data,t_size p_data_size) {m_data.set_data_fromptr((const t_uint8*)p_data,p_data_size);}\r\n\tvoid set_data_from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort);\r\nprivate:\r\n\tGUID m_owner;\r\n\tpfc::array_t<t_uint8> m_data;\r\n};\r\n\r\nclass NOVTABLE dsp_preset_edit_callback {\r\npublic:\r\n\tvirtual void on_preset_changed(const dsp_preset &) = 0;\r\nprivate:\r\n\tdsp_preset_edit_callback(const dsp_preset_edit_callback&) {throw pfc::exception_not_implemented();}\r\n\tconst dsp_preset_edit_callback & operator=(const dsp_preset_edit_callback &) {throw pfc::exception_not_implemented();}\r\nprotected:\r\n\tdsp_preset_edit_callback() {}\r\n\t~dsp_preset_edit_callback() {}\r\n};\r\n\r\nclass NOVTABLE dsp_entry : public service_base {\r\npublic:\r\n\tvirtual void get_name(pfc::string_base & p_out) = 0;\r\n\tvirtual bool get_default_preset(dsp_preset & p_out) = 0;\r\n\tvirtual bool instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset) = 0;\t\r\n\tvirtual GUID get_guid() = 0;\r\n\tvirtual bool have_config_popup() = 0;\r\n\tvirtual bool show_config_popup(dsp_preset & p_data,HWND p_parent) = 0;\r\n\r\n\r\n\tstatic bool g_get_interface(service_ptr_t<dsp_entry> & p_out,const GUID & p_guid);\r\n\tstatic bool g_instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset);\r\n\tstatic bool g_instantiate_default(service_ptr_t<dsp> & p_out,const GUID & p_guid);\r\n\tstatic bool g_name_from_guid(pfc::string_base & p_out,const GUID & p_guid);\r\n\tstatic bool g_dsp_exists(const GUID & p_guid);\r\n\tstatic bool g_get_default_preset(dsp_preset & p_out,const GUID & p_guid);\r\n\tstatic bool g_have_config_popup(const GUID & p_guid);\r\n\tstatic bool g_have_config_popup(const dsp_preset & p_preset);\r\n\tstatic bool g_show_config_popup(dsp_preset & p_preset,HWND p_parent);\r\n\r\n\tstatic void g_show_config_popup_v2(const dsp_preset & p_preset,HWND p_parent,dsp_preset_edit_callback & p_callback);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_entry);\r\n};\r\n\r\nclass NOVTABLE dsp_entry_v2 : public dsp_entry {\r\npublic:\r\n\tvirtual void show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) = 0;\r\n\r\nprivate:\r\n\tbool show_config_popup(dsp_preset & p_data,HWND p_parent);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(dsp_entry_v2,dsp_entry);\r\n};\r\n\r\ntemplate<class T,class t_entry = dsp_entry>\r\nclass dsp_entry_impl_nopreset_t : public t_entry {\r\npublic:\r\n\tvoid get_name(pfc::string_base & p_out) {T::g_get_name(p_out);}\r\n\tbool get_default_preset(dsp_preset & p_out)\r\n\t{\r\n\t\tp_out.set_owner(T::g_get_guid());\r\n\t\tp_out.set_data(0,0);\r\n\t\treturn true;\r\n\t}\r\n\tbool instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset)\r\n\t{\r\n\t\tif (p_preset.get_owner() == T::g_get_guid() && p_preset.get_data_size() == 0)\r\n\t\t{\r\n\t\t\tp_out = new service_impl_t<T>();\r\n\t\t\treturn p_out.is_valid();\r\n\t\t}\r\n\t\telse return false;\r\n\t}\r\n\tGUID get_guid() {return T::g_get_guid();}\r\n\r\n\tbool have_config_popup() {return false;}\r\n\tbool show_config_popup(dsp_preset & p_data,HWND p_parent) {return false;}\r\n};\r\n\r\ntemplate<class T, class t_entry = dsp_entry_v2>\r\nclass dsp_entry_impl_t : public t_entry {\r\npublic:\r\n\tvoid get_name(pfc::string_base & p_out) {T::g_get_name(p_out);}\r\n\tbool get_default_preset(dsp_preset & p_out) {return T::g_get_default_preset(p_out);}\r\n\tbool instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset) {\r\n\t\tif (p_preset.get_owner() == T::g_get_guid()) {\r\n\t\t\tp_out = new service_impl_t<T>(p_preset);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse return false;\r\n\t}\r\n\tGUID get_guid() {return T::g_get_guid();}\r\n\r\n\tbool have_config_popup() {return T::g_have_config_popup();}\r\n\tbool show_config_popup(dsp_preset & p_data,HWND p_parent) {return T::g_show_config_popup(p_data,p_parent);}\r\n\t//void show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) {T::g_show_config_popup(p_data,p_parent,p_callback);}\r\n};\r\n\r\ntemplate<class T, class t_entry = dsp_entry_v2>\r\nclass dsp_entry_v2_impl_t : public t_entry {\r\npublic:\r\n\tvoid get_name(pfc::string_base & p_out) {T::g_get_name(p_out);}\r\n\tbool get_default_preset(dsp_preset & p_out) {return T::g_get_default_preset(p_out);}\r\n\tbool instantiate(service_ptr_t<dsp> & p_out,const dsp_preset & p_preset) {\r\n\t\tif (p_preset.get_owner() == T::g_get_guid()) {\r\n\t\t\tp_out = new service_impl_t<T>(p_preset);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse return false;\r\n\t}\r\n\tGUID get_guid() {return T::g_get_guid();}\r\n\r\n\tbool have_config_popup() {return T::g_have_config_popup();}\r\n\t//bool show_config_popup(dsp_preset & p_data,HWND p_parent) {return T::g_show_config_popup(p_data,p_parent);}\r\n\tvoid show_config_popup_v2(const dsp_preset & p_data,HWND p_parent,dsp_preset_edit_callback & p_callback) {T::g_show_config_popup(p_data,p_parent,p_callback);}\r\n};\r\n\r\n\r\ntemplate<class T>\r\nclass dsp_factory_nopreset_t : public service_factory_single_t<dsp_entry_impl_nopreset_t<T> > {};\r\n\r\ntemplate<class T>\r\nclass dsp_factory_t : public service_factory_single_t<dsp_entry_v2_impl_t<T> > {};\r\n\r\nclass NOVTABLE dsp_chain_config\r\n{\r\npublic:\r\n\tvirtual t_size get_count() const = 0;\r\n\tvirtual const dsp_preset & get_item(t_size p_index) const = 0;\r\n\tvirtual void replace_item(const dsp_preset & p_data,t_size p_index) = 0;\r\n\tvirtual void insert_item(const dsp_preset & p_data,t_size p_index) = 0;\r\n\tvirtual void remove_mask(const bit_array & p_mask) = 0;\r\n\t\r\n\tvoid remove_item(t_size p_index);\r\n\tvoid remove_all();\r\n\tvoid add_item(const dsp_preset & p_data);\r\n\tvoid copy(const dsp_chain_config & p_source);\r\n\r\n\tconst dsp_chain_config & operator=(const dsp_chain_config & p_source) {copy(p_source); return *this;}\r\n\r\n\tvoid contents_to_stream(stream_writer * p_stream,abort_callback & p_abort) const;\r\n\tvoid contents_from_stream(stream_reader * p_stream,abort_callback & p_abort);\r\n\r\n\tvoid instantiate(service_list_t<dsp> & p_out);\r\n\r\n\tvoid get_name_list(pfc::string_base & p_out) const;\r\n};\r\n\r\nclass dsp_chain_config_impl : public dsp_chain_config\r\n{\r\npublic:\r\n\tdsp_chain_config_impl() {}\r\n\tdsp_chain_config_impl(const dsp_chain_config & p_source) {copy(p_source);}\r\n\tdsp_chain_config_impl(const dsp_chain_config_impl & p_source) {copy(p_source);}\r\n\tt_size get_count() const;\r\n\tconst dsp_preset & get_item(t_size p_index) const;\r\n\tvoid replace_item(const dsp_preset & p_data,t_size p_index);\r\n\tvoid insert_item(const dsp_preset & p_data,t_size p_index);\r\n\tvoid remove_mask(const bit_array & p_mask);\r\n\r\n\tconst dsp_chain_config_impl & operator=(const dsp_chain_config & p_source) {copy(p_source); return *this;}\r\n\tconst dsp_chain_config_impl & operator=(const dsp_chain_config_impl & p_source) {copy(p_source); return *this;}\r\n\r\n\t~dsp_chain_config_impl();\r\nprivate:\r\n\tpfc::ptr_list_t<dsp_preset_impl> m_data;\r\n};\r\n\r\nclass cfg_dsp_chain_config : public cfg_var {\r\nprotected:\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort);\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort);\r\npublic:\r\n\tvoid reset();\r\n\tinline cfg_dsp_chain_config(const GUID & p_guid) : cfg_var(p_guid) {}\r\n\tt_size get_count() const {return m_data.get_count();}\r\n\tconst dsp_preset & get_item(t_size p_index) const {return m_data.get_item(p_index);}\r\n\tbool get_data(dsp_chain_config & p_data) const;\r\n\tvoid set_data(const dsp_chain_config & p_data);\r\nprivate:\r\n\tdsp_chain_config_impl m_data;\r\n\t\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/dsp_manager.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid dsp_manager::close() {\r\n\tm_chain.remove_all();\r\n\tm_config_changed = true;\r\n}\r\n\r\nvoid dsp_manager::set_config( const dsp_chain_config & p_data )\r\n{\r\n\t//dsp_chain_config::g_instantiate(m_dsp_list,p_data);\r\n\tm_config.copy(p_data);\r\n\tm_config_changed = true;\r\n}\r\n\r\nvoid dsp_manager::dsp_run(t_dsp_chain::const_iterator p_iter,dsp_chunk_list * p_list,const metadb_handle_ptr & cur_file,unsigned flags,double & latency,abort_callback & p_abort)\r\n{\r\n\tp_list->remove_bad_chunks();\r\n\r\n\tTRACK_CODE(\"dsp::run\",p_iter->m_dsp->run_abortable(p_list,cur_file,flags,p_abort));\r\n\tTRACK_CODE(\"dsp::get_latency\",latency += p_iter->m_dsp->get_latency());\r\n}\r\n\r\ndouble dsp_manager::run(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,unsigned p_flags,abort_callback & p_abort) {\r\n\tTRACK_CALL_TEXT(\"dsp_manager::run\");\r\n\r\n\ttry {\r\n\t\tfpu_control_default l_fpu_control;\r\n\r\n\t\tdouble latency=0;\r\n\t\tbool done = false;\r\n\r\n\t\tt_dsp_chain::const_iterator flush_mark;\r\n\t\tif ((p_flags & dsp::END_OF_TRACK) && ! (p_flags & dsp::FLUSH)) {\r\n\t\t\tfor(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\tif (iter->m_dsp->need_track_change_mark()) flush_mark = iter;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (m_config_changed)\r\n\t\t{\r\n\t\t\tt_dsp_chain newchain;\r\n\t\t\tbool recycle_available = true;\r\n\r\n\t\t\tfor(t_size n=0;n<m_config.get_count();n++) {\r\n\t\t\t\tservice_ptr_t<dsp> temp;\r\n\r\n\t\t\t\tconst dsp_preset & preset = m_config.get_item(n);\r\n\t\t\t\tif (dsp_entry::g_dsp_exists(preset.get_owner())) {\r\n\t\t\t\t\tt_dsp_chain::iterator iter = newchain.insert_last();\r\n\t\t\t\t\titer->m_preset = m_config.get_item(n);\r\n\t\t\t\t\titer->m_recycle_flag = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\r\n\t\t\t//HACK: recycle existing DSPs in a special case when user has apparently only altered settings of one of DSPs.\r\n\t\t\tif (newchain.get_count() == m_chain.get_count()) {\r\n\t\t\t\tt_size data_mismatch_count = 0;\r\n\t\t\t\tt_size owner_mismatch_count = 0;\r\n\t\t\t\tt_dsp_chain::iterator iter_src, iter_dst;\r\n\t\t\t\titer_src = m_chain.first(); iter_dst = newchain.first();\r\n\t\t\t\twhile(iter_src.is_valid() && iter_dst.is_valid()) {\r\n\t\t\t\t\tif (iter_src->m_preset.get_owner() != iter_dst->m_preset.get_owner()) {\r\n\t\t\t\t\t\towner_mismatch_count++;\r\n\t\t\t\t\t} else if (iter_src->m_preset != iter_dst->m_preset) {\r\n\t\t\t\t\t\tdata_mismatch_count++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t++iter_src; ++iter_dst;\r\n\t\t\t\t}\r\n\t\t\t\trecycle_available = (owner_mismatch_count == 0 && data_mismatch_count <= 1);\r\n\t\t\t} else {\r\n\t\t\t\trecycle_available = false;\r\n\t\t\t}\r\n\r\n\t\t\tif (recycle_available) {\r\n\t\t\t\tt_dsp_chain::iterator iter_src, iter_dst;\r\n\t\t\t\titer_src = m_chain.first(); iter_dst = newchain.first();\r\n\t\t\t\twhile(iter_src.is_valid() && iter_dst.is_valid()) {\r\n\t\t\t\t\tif (iter_src->m_preset == iter_dst->m_preset) {\r\n\t\t\t\t\t\titer_src->m_recycle_flag = true;\r\n\t\t\t\t\t\titer_dst->m_dsp = iter_src->m_dsp;\r\n\t\t\t\t\t}\r\n\t\t\t\t\t++iter_src; ++iter_dst;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor(t_dsp_chain::iterator iter = newchain.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\tif (iter->m_dsp.is_empty()) {\r\n\t\t\t\t\tif (!dsp_entry::g_instantiate(iter->m_dsp,iter->m_preset)) throw pfc::exception_bug_check();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (m_chain.get_count()>0) {\r\n\t\t\t\tbool flushflag = flush_mark.is_valid();\r\n\t\t\t\tfor(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\t\tunsigned flags2 = p_flags;\r\n\t\t\t\t\tif (iter == flush_mark) flushflag = false;\r\n\t\t\t\t\tif (flushflag || !iter->m_recycle_flag) flags2|=dsp::FLUSH;\r\n\t\t\t\t\tdsp_run(iter,p_list,p_cur_file,flags2,latency,p_abort);\r\n\t\t\t\t}\r\n\t\t\t\tdone = true;\r\n\t\t\t}\r\n\r\n\t\t\tm_chain = newchain;\r\n\t\t\tm_config_changed = false;\r\n\t\t}\r\n\t\t\r\n\t\tif (!done)\r\n\t\t{\r\n\t\t\tbool flushflag = flush_mark.is_valid();\r\n\t\t\tfor(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\tunsigned flags2 = p_flags;\r\n\t\t\t\tif (iter == flush_mark) flushflag = false;\r\n\t\t\t\tif (flushflag) flags2|=dsp::FLUSH;\r\n\t\t\t\tdsp_run(iter,p_list,p_cur_file,flags2,latency,p_abort);\r\n\t\t\t}\r\n\t\t\tdone = true;\r\n\t\t}\r\n\t\t\r\n\t\tp_list->remove_bad_chunks();\r\n\r\n\t\treturn latency;\r\n\t} catch(...) {\r\n\t\tp_list->remove_all();\r\n\t\tthrow;\r\n\t}\r\n}\r\n\r\nvoid dsp_manager::flush()\r\n{\r\n\tfor(t_dsp_chain::const_iterator iter = m_chain.first(); iter.is_valid(); ++iter) {\r\n\t\tTRACK_CODE(\"dsp::flush\",iter->m_dsp->flush());\r\n\t}\r\n}\r\n\r\n\r\nbool dsp_manager::is_active() {return m_config.get_count()>0;}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/dsp_manager.h",
    "content": "struct t_dsp_chain_entry {\r\n\tservice_ptr_t<dsp> m_dsp;\r\n\tdsp_preset_impl m_preset;\r\n\tbool m_recycle_flag;\r\n};\r\ntypedef pfc::chain_list_t<t_dsp_chain_entry> t_dsp_chain;\r\n\r\nclass dsp_manager {\r\npublic:\r\n\tdsp_manager() : m_config_changed(false) {}\r\n\r\n\tvoid set_config( const dsp_chain_config & p_data );\r\n\tdouble run(dsp_chunk_list * p_list,const metadb_handle_ptr & p_cur_file,unsigned p_flags,abort_callback & p_abort);\r\n\tvoid flush();\r\n\tvoid close();\r\n\r\n\tbool is_active();\r\n\r\nprivate:\r\n\tt_dsp_chain m_chain;\r\n\tdsp_chain_config_impl m_config;\r\n\tbool m_config_changed;\r\n\t\r\n\tvoid dsp_run(t_dsp_chain::const_iterator p_iter,dsp_chunk_list * list,const metadb_handle_ptr & cur_file,unsigned flags,double & latency,abort_callback&);\r\n\r\n\tdsp_manager(const dsp_manager &) {throw pfc::exception_not_implemented();}\r\n\tconst dsp_manager & operator=(const dsp_manager&) {throw pfc::exception_not_implemented();}\r\n};\r\n\r\n\r\nclass dsp_config_manager : public service_base\r\n{\r\npublic:\r\n\tvirtual void get_core_settings(dsp_chain_config & p_out) = 0;\r\n\tvirtual void set_core_settings(const dsp_chain_config & p_data) = 0;\r\n\t\r\n\tvirtual bool configure_popup(dsp_chain_config & p_data,HWND p_parent,const char * p_title) = 0;\r\n\t\r\n\tvirtual HWND configure_embedded(const dsp_chain_config & p_initdata,HWND p_parent,unsigned p_id,bool p_from_modal) = 0;\r\n\tvirtual void configure_embedded_retrieve(HWND wnd,dsp_chain_config & p_data) = 0;\r\n\tvirtual void configure_embedded_change(HWND wnd,const dsp_chain_config & p_data) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_config_manager);\r\n};\r\n\r\nclass NOVTABLE dsp_config_callback : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_core_settings_change(const dsp_chain_config & p_newdata) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(dsp_config_callback);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_info.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nt_size file_info::meta_find_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\tt_size n, m = meta_get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tif (pfc::stricmp_ascii_ex(meta_enum_name(n),infinite,p_name,p_name_length) == 0) return n;\r\n\t}\r\n\treturn infinite;\r\n}\r\n\r\nbool file_info::meta_exists_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\treturn meta_find_ex(p_name,p_name_length) != infinite;\r\n}\r\n\r\nvoid file_info::meta_remove_field_ex(const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = meta_find_ex(p_name,p_name_length);\r\n\tif (index!=infinite) meta_remove_index(index);\r\n}\r\n\r\n\r\nvoid file_info::meta_remove_index(t_size p_index)\r\n{\r\n\tmeta_remove_mask(bit_array_one(p_index));\r\n}\r\n\r\nvoid file_info::meta_remove_all()\r\n{\r\n\tmeta_remove_mask(bit_array_true());\r\n}\r\n\r\nvoid file_info::meta_remove_value(t_size p_index,t_size p_value)\r\n{\r\n\tmeta_remove_values(p_index,bit_array_one(p_value));\r\n}\r\n\r\nt_size file_info::meta_get_count_by_name_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\tt_size index = meta_find_ex(p_name,p_name_length);\r\n\tif (index == infinite) return 0;\r\n\treturn meta_enum_value_count(index);\r\n}\r\n\r\nt_size file_info::info_find_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\tt_size n, m = info_get_count();\r\n\tfor(n=0;n<m;n++) {\r\n\t\tif (pfc::stricmp_ascii_ex(info_enum_name(n),infinite,p_name,p_name_length) == 0) return n;\r\n\t}\r\n\treturn infinite;\r\n}\r\n\r\nbool file_info::info_exists_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\treturn info_find_ex(p_name,p_name_length) != infinite;\r\n}\r\n\r\nvoid file_info::info_remove_index(t_size p_index)\r\n{\r\n\tinfo_remove_mask(bit_array_one(p_index));\r\n}\r\n\r\nvoid file_info::info_remove_all()\r\n{\r\n\tinfo_remove_mask(bit_array_true());\r\n}\r\n\r\nbool file_info::info_remove_ex(const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = info_find_ex(p_name,p_name_length);\r\n\tif (index != infinite)\r\n\t{\r\n\t\tinfo_remove_index(index);\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nvoid file_info::copy_meta_single(const file_info & p_source,t_size p_index)\r\n{\r\n\tcopy_meta_single_rename(p_source,p_index,p_source.meta_enum_name(p_index));\r\n}\r\n\r\nvoid file_info::copy_meta_single_nocheck(const file_info & p_source,t_size p_index)\r\n{\r\n\tconst char * name = p_source.meta_enum_name(p_index);\r\n\tt_size n, m = p_source.meta_enum_value_count(p_index);\r\n\tt_size new_index = infinite;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tconst char * value = p_source.meta_enum_value(p_index,n);\r\n\t\tif (n == 0) new_index = meta_set_nocheck(name,value);\r\n\t\telse meta_add_value(new_index,value);\r\n\t}\r\n}\r\n\r\nvoid file_info::copy_meta_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = p_source.meta_find_ex(p_name,p_name_length);\r\n\tif (index != infinite) copy_meta_single(p_source,index);\r\n}\r\n\r\nvoid file_info::copy_info_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = p_source.info_find_ex(p_name,p_name_length);\r\n\tif (index != infinite) copy_info_single(p_source,index);\r\n}\r\n\r\nvoid file_info::copy_meta_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = p_source.meta_find_ex(p_name,p_name_length);\r\n\tif (index != infinite) copy_meta_single_nocheck(p_source,index);\r\n}\r\n\r\nvoid file_info::copy_info_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = p_source.info_find_ex(p_name,p_name_length);\r\n\tif (index != infinite) copy_info_single_nocheck(p_source,index);\r\n}\r\n\r\nvoid file_info::copy_info_single(const file_info & p_source,t_size p_index)\r\n{\r\n\tinfo_set(p_source.info_enum_name(p_index),p_source.info_enum_value(p_index));\r\n}\r\n\r\nvoid file_info::copy_info_single_nocheck(const file_info & p_source,t_size p_index)\r\n{\r\n\tinfo_set_nocheck(p_source.info_enum_name(p_index),p_source.info_enum_value(p_index));\r\n}\r\n\r\nvoid file_info::copy_meta(const file_info & p_source)\r\n{\r\n\tif (&p_source != this) {\r\n\t\tmeta_remove_all();\r\n\t\tt_size n, m = p_source.meta_get_count();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t\tcopy_meta_single_nocheck(p_source,n);\r\n\t}\r\n}\r\n\r\nvoid file_info::copy_info(const file_info & p_source)\r\n{\r\n\tif (&p_source != this) {\r\n\t\tinfo_remove_all();\r\n\t\tt_size n, m = p_source.info_get_count();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t\tcopy_info_single_nocheck(p_source,n);\r\n\t}\r\n}\r\n\r\nvoid file_info::copy(const file_info & p_source)\r\n{\r\n\tif (&p_source != this) {\r\n\t\tcopy_meta(p_source);\r\n\t\tcopy_info(p_source);\r\n\t\tset_length(p_source.get_length());\r\n\t\tset_replaygain(p_source.get_replaygain());\r\n\t}\r\n}\r\n\r\n\r\nconst char * file_info::meta_get_ex(const char * p_name,t_size p_name_length,t_size p_index) const\r\n{\r\n\tt_size index = meta_find_ex(p_name,p_name_length);\r\n\tif (index == infinite) return 0;\r\n\tt_size max = meta_enum_value_count(index);\r\n\tif (p_index >= max) return 0;\r\n\treturn meta_enum_value(index,p_index);\r\n}\r\n\r\nconst char * file_info::info_get_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n\tt_size index = info_find_ex(p_name,p_name_length);\r\n\tif (index == infinite) return 0;\r\n\treturn info_enum_value(index);\r\n}\r\n\r\nt_int64 file_info::info_get_int(const char * name) const\r\n{\r\n\tPFC_ASSERT(pfc::is_valid_utf8(name));\r\n\tconst char * val = info_get(name);\r\n\tif (val==0) return 0;\r\n\treturn _atoi64(val);\r\n}\r\n\r\nt_int64 file_info::info_get_length_samples() const\r\n{\r\n\tt_int64 ret = 0;\r\n\tdouble len = get_length();\r\n\tt_int64 srate = info_get_int(\"samplerate\");\r\n\r\n\tif (srate>0 && len>0)\r\n\t{\r\n\t\tret = audio_math::time_to_samples(len,(unsigned)srate);\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ndouble file_info::info_get_float(const char * name) const\r\n{\r\n\tconst char * ptr = info_get(name);\r\n\tif (ptr) return pfc::string_to_float(ptr);\r\n\telse return 0;\r\n}\r\n\r\nvoid file_info::info_set_int(const char * name,t_int64 value)\r\n{\r\n\tPFC_ASSERT(pfc::is_valid_utf8(name));\r\n\tinfo_set(name,pfc::format_int(value));\r\n}\r\n\r\nvoid file_info::info_set_float(const char * name,double value,unsigned precision,bool force_sign,const char * unit)\r\n{\r\n\tPFC_ASSERT(pfc::is_valid_utf8(name));\r\n\tPFC_ASSERT(unit==0 || strlen(unit) <= 64);\r\n\tchar temp[128];\r\n\tpfc::float_to_string(temp,64,value,precision,force_sign);\r\n\ttemp[63] = 0;\r\n\tif (unit)\r\n\t{\r\n\t\tstrcat(temp,\" \");\r\n\t\tstrcat(temp,unit);\r\n\t}\r\n\tinfo_set(name,temp);\r\n}\r\n\r\n\r\nvoid file_info::info_set_replaygain_album_gain(float value)\r\n{\r\n\treplaygain_info temp = get_replaygain();\r\n\ttemp.m_album_gain = value;\r\n\tset_replaygain(temp);\r\n}\r\n\r\nvoid file_info::info_set_replaygain_album_peak(float value)\r\n{\r\n\treplaygain_info temp = get_replaygain();\r\n\ttemp.m_album_peak = value;\r\n\tset_replaygain(temp);\r\n}\r\n\r\nvoid file_info::info_set_replaygain_track_gain(float value)\r\n{\r\n\treplaygain_info temp = get_replaygain();\r\n\ttemp.m_track_gain = value;\r\n\tset_replaygain(temp);\r\n}\r\n\r\nvoid file_info::info_set_replaygain_track_peak(float value)\r\n{\r\n\treplaygain_info temp = get_replaygain();\r\n\ttemp.m_track_peak = value;\r\n\tset_replaygain(temp);\r\n}\r\n\r\n\r\nstatic bool is_valid_bps(t_int64 val)\r\n{\r\n\treturn val>0 && val<=256;\r\n}\r\n\r\nunsigned file_info::info_get_decoded_bps() const\r\n{\r\n\tt_int64 val = info_get_int(\"decoded_bitspersample\");\r\n\tif (is_valid_bps(val)) return (unsigned)val;\r\n\tval = info_get_int(\"bitspersample\");\r\n\tif (is_valid_bps(val)) return (unsigned)val;\r\n\treturn 0;\r\n\r\n}\r\n\r\nvoid file_info::reset()\r\n{\r\n\tinfo_remove_all();\r\n\tmeta_remove_all();\r\n\tset_length(0);\r\n\treset_replaygain();\r\n}\r\n\r\nvoid file_info::reset_replaygain()\r\n{\r\n\treplaygain_info temp;\r\n\ttemp.reset();\r\n\tset_replaygain(temp);\r\n}\r\n\r\nvoid file_info::copy_meta_single_rename_ex(const file_info & p_source,t_size p_index,const char * p_new_name,t_size p_new_name_length)\r\n{\r\n\tt_size n, m = p_source.meta_enum_value_count(p_index);\r\n\tt_size new_index = infinite;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tconst char * value = p_source.meta_enum_value(p_index,n);\r\n\t\tif (n == 0) new_index = meta_set_ex(p_new_name,p_new_name_length,value,infinite);\r\n\t\telse meta_add_value(new_index,value);\r\n\t}\r\n}\r\n\r\nt_size file_info::meta_add_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\tt_size index = meta_find_ex(p_name,p_name_length);\r\n\tif (index == infinite) return meta_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);\r\n\telse\r\n\t{\r\n\t\tmeta_add_value_ex(index,p_value,p_value_length);\r\n\t\treturn index;\r\n\t}\r\n}\r\n\r\nvoid file_info::meta_add_value_ex(t_size p_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tmeta_insert_value_ex(p_index,meta_enum_value_count(p_index),p_value,p_value_length);\r\n}\r\n\r\n\r\nt_size file_info::meta_calc_total_value_count() const\r\n{\r\n\tt_size n, m = meta_get_count(), ret = 0;\r\n\tfor(n=0;n<m;n++) ret += meta_enum_value_count(n);\r\n\treturn ret;\r\n}\r\n\r\nbool file_info::info_set_replaygain_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len)\r\n{\r\n\treplaygain_info temp = get_replaygain();\r\n\tif (temp.set_from_meta_ex(p_name,p_name_len,p_value,p_value_len))\r\n\t{\r\n\t\tset_replaygain(temp);\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nvoid file_info::info_set_replaygain_auto_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len)\r\n{\r\n\tif (!info_set_replaygain_ex(p_name,p_name_len,p_value,p_value_len))\r\n\t\tinfo_set_ex(p_name,p_name_len,p_value,p_value_len);\r\n}\r\n\r\nbool replaygain_info::g_equal(const replaygain_info & item1,const replaygain_info & item2)\r\n{\r\n\treturn\titem1.m_album_gain == item2.m_album_gain &&\r\n\t\t\titem1.m_track_gain == item2.m_track_gain &&\r\n\t\t\titem1.m_album_peak == item2.m_album_peak &&\r\n\t\t\titem1.m_track_peak == item2.m_track_peak;\r\n}\r\n\r\nbool file_info::are_meta_fields_identical(t_size p_index1,t_size p_index2) const\r\n{\r\n\tconst t_size count = meta_enum_value_count(p_index1);\r\n\tif (count != meta_enum_value_count(p_index2)) return false;\r\n\tt_size n;\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\tif (strcmp(meta_enum_value(p_index1,n),meta_enum_value(p_index2,n))) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\n\r\nbool file_info::meta_format(const char * p_name,pfc::string_base & p_out) const\r\n{\r\n\tp_out.reset();\r\n\tt_size index = meta_find(p_name);\r\n\tif (index == infinite) return false;\r\n\tt_size val, count = meta_enum_value_count(index);\r\n\tif (count == 0) return false;\r\n\tfor(val=0;val<count;val++)\r\n\t{\r\n\t\tif (val > 0) p_out += \", \";\r\n\t\tp_out += meta_enum_value(index,val);\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid file_info::info_calculate_bitrate(t_filesize p_filesize,double p_length)\r\n{\r\n\tinfo_set_bitrate((unsigned)floor((double)p_filesize * 8 / (p_length * 1000) + 0.5));\r\n}\r\n\r\nbool file_info::is_encoding_lossy() const {\r\n\tconst char * encoding = info_get(\"encoding\");\r\n\tif (encoding != NULL) {\r\n\t\tif (pfc::stricmp_ascii(encoding,\"lossy\") == 0 /*|| pfc::stricmp_ascii(encoding,\"hybrid\") == 0*/) return true;\r\n\t} else {\r\n\t\t//the old way\r\n\t\tif (info_get(\"bitspersample\") == NULL) return true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool file_info::g_is_meta_equal(const file_info & p_item1,const file_info & p_item2) {\r\n\tconst t_size count = p_item1.meta_get_count();\r\n\tif (count != p_item2.meta_get_count()) {\r\n\t\t//uDebugLog() << \"meta count mismatch\";\r\n\t\treturn false;\r\n\t}\r\n\tpfc::map_t<const char*,t_size,field_name_comparator> item2_meta_map;\r\n\tfor(t_size n=0; n<count; n++) {\r\n\t\titem2_meta_map.set(p_item2.meta_enum_name(n),n);\r\n\t}\r\n\tfor(t_size n1=0; n1<count; n1++) {\r\n\t\tt_size n2;\r\n\t\tif (!item2_meta_map.query(p_item1.meta_enum_name(n1),n2)) {\r\n\t\t\t//uDebugLog() << \"item2 doesn't have \" << p_item1.meta_enum_name(n1);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tt_size value_count = p_item1.meta_enum_value_count(n1);\r\n\t\tif (value_count != p_item2.meta_enum_value_count(n2)) {\r\n\t\t\t//uDebugLog() << \"meta value count mismatch: \" << p_item1.meta_enum_name(n1) << \" : \" << value_count << \" vs \" << p_item2.meta_enum_value_count(n2);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tfor(t_size v = 0; v < value_count; v++) {\r\n\t\t\tif (strcmp(p_item1.meta_enum_value(n1,v),p_item2.meta_enum_value(n2,v)) != 0) {\r\n\t\t\t\t//uDebugLog() << \"meta mismatch: \" << p_item1.meta_enum_name(n1) << \" : \" << p_item1.meta_enum_value(n1,v) << \" vs \" << p_item2.meta_enum_value(n2,v);\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool file_info::g_is_info_equal(const file_info & p_item1,const file_info & p_item2) {\r\n\tt_size count = p_item1.info_get_count();\r\n\tif (count != p_item2.info_get_count()) return false;\r\n\tfor(t_size n1=0; n1<count; n1++) {\r\n\t\tt_size n2 = p_item2.info_find(p_item1.info_enum_name(n1));\r\n\t\tif (n2 == infinite) return false;\r\n\t\tif (strcmp(p_item1.info_enum_value(n1),p_item2.info_enum_value(n2)) != 0) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nstatic bool is_valid_field_name_char(char p_char) {\r\n\treturn p_char >= 32 && p_char < 127 && p_char != '=' && p_char != '%' && p_char != '<' && p_char != '>';\r\n}\r\n\r\nbool file_info::g_is_valid_field_name(const char * p_name,t_size p_length) {\r\n\tt_size walk;\r\n\tfor(walk = 0; walk < p_length && p_name[walk] != 0; walk++) {\r\n\t\tif (!is_valid_field_name_char(p_name[walk])) return false;\r\n\t}\r\n\treturn walk > 0;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_info.h",
    "content": "#ifndef _FILE_INFO_H_\r\n#define _FILE_INFO_H_\r\n\r\n//! Structure containing ReplayGain scan results from some playable object, also providing various helper methods to manipulate those results.\r\nstruct replaygain_info\r\n{\r\n\tfloat m_album_gain,m_track_gain;\r\n\tfloat m_album_peak,m_track_peak;\r\n\r\n\tenum {text_buffer_size = 16 };\r\n\ttypedef char t_text_buffer[text_buffer_size];\r\n\r\n\tenum { peak_invalid = -1, gain_invalid = -1000 };\r\n\r\n\tstatic bool g_format_gain(float p_value,char p_buffer[text_buffer_size]);\r\n\tstatic bool g_format_peak(float p_value,char p_buffer[text_buffer_size]);\r\n\r\n\tinline bool format_album_gain(char p_buffer[text_buffer_size]) const {return g_format_gain(m_album_gain,p_buffer);}\r\n\tinline bool format_track_gain(char p_buffer[text_buffer_size]) const {return g_format_gain(m_track_gain,p_buffer);}\r\n\tinline bool format_album_peak(char p_buffer[text_buffer_size]) const {return g_format_peak(m_album_peak,p_buffer);}\r\n\tinline bool format_track_peak(char p_buffer[text_buffer_size]) const {return g_format_peak(m_track_peak,p_buffer);}\r\n\r\n\tvoid set_album_gain_text(const char * p_text,t_size p_text_len = infinite);\r\n\tvoid set_track_gain_text(const char * p_text,t_size p_text_len = infinite);\r\n\tvoid set_album_peak_text(const char * p_text,t_size p_text_len = infinite);\r\n\tvoid set_track_peak_text(const char * p_text,t_size p_text_len = infinite);\r\n\r\n\tstatic bool g_is_meta_replaygain(const char * p_name,t_size p_name_len = infinite);\r\n\tbool set_from_meta_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len);\r\n\tinline bool set_from_meta(const char * p_name,const char * p_value) {return set_from_meta_ex(p_name,infinite,p_value,infinite);}\r\n\r\n\tinline bool is_album_gain_present() const {return m_album_gain != gain_invalid;}\r\n\tinline bool is_track_gain_present() const {return m_track_gain != gain_invalid;}\r\n\tinline bool is_album_peak_present() const {return m_album_peak != peak_invalid;}\r\n\tinline bool is_track_peak_present() const {return m_track_peak != peak_invalid;}\r\n\t\r\n\tinline void remove_album_gain() {m_album_gain = gain_invalid;}\r\n\tinline void remove_track_gain() {m_track_gain = gain_invalid;}\r\n\tinline void remove_album_peak() {m_album_peak = peak_invalid;}\r\n\tinline void remove_track_peak() {m_track_peak = peak_invalid;}\r\n\r\n\tt_size\tget_value_count();\r\n\r\n\tstatic replaygain_info g_merge(replaygain_info r1,replaygain_info r2);\r\n\r\n\tstatic bool g_equal(const replaygain_info & item1,const replaygain_info & item2);\r\n\r\n\tvoid reset();\t\r\n};\r\n\r\ninline bool operator==(const replaygain_info & item1,const replaygain_info & item2) {return replaygain_info::g_equal(item1,item2);}\r\ninline bool operator!=(const replaygain_info & item1,const replaygain_info & item2) {return !replaygain_info::g_equal(item1,item2);}\r\n\r\nstatic const replaygain_info replaygain_info_invalid = {replaygain_info::gain_invalid,replaygain_info::gain_invalid,replaygain_info::peak_invalid,replaygain_info::peak_invalid};\r\n\r\n\r\n//! Main interface class for information about some playable object.\r\nclass NOVTABLE file_info {\r\npublic:\r\n\t//! Retrieves length, in seconds.\r\n\tvirtual double\t\tget_length() const = 0;\r\n\t//! Sets length, in seconds.\r\n\tvirtual void\t\tset_length(double p_length) = 0;\r\n\r\n\t//! Sets ReplayGain information.\r\n\tvirtual void\t\t\tset_replaygain(const replaygain_info & p_info) = 0;\r\n\t//! Retrieves ReplayGain information.\r\n\tvirtual replaygain_info\tget_replaygain() const = 0;\r\n\r\n\t//! Retrieves count of metadata entries.\r\n\tvirtual t_size\t\tmeta_get_count() const = 0;\r\n\t//! Retrieves the name of metadata entry of specified index. Return value is a null-terminated UTF-8 encoded string.\r\n\tvirtual const char*\tmeta_enum_name(t_size p_index) const = 0;\r\n\t//! Retrieves count of values in metadata entry of specified index. The value is always equal to or greater than 1.\r\n\tvirtual t_size\t\tmeta_enum_value_count(t_size p_index) const = 0;\r\n\t//! Retrieves specified value from specified metadata entry. Return value is a null-terminated UTF-8 encoded string.\r\n\tvirtual const char*\tmeta_enum_value(t_size p_index,t_size p_value_number) const = 0;\r\n\t//! Finds index of metadata entry of specified name. Returns infinite when not found.\r\n\tvirtual t_size\t\tmeta_find_ex(const char * p_name,t_size p_name_length) const;\r\n\t//! Creates a new metadata entry of specified name with specified value. If an entry of same name already exists, it is erased. Return value is the index of newly created metadata entry.\r\n\tvirtual t_size\t\tmeta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0;\r\n\t//! Inserts a new value into specified metadata entry.\r\n\tvirtual void\t\tmeta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) = 0;\r\n\t//! Removes metadata entries according to specified bit mask.\r\n\tvirtual void\t\tmeta_remove_mask(const bit_array & p_mask) = 0;\r\n\t//! Reorders metadata entries according to specified permutation.\r\n\tvirtual void\t\tmeta_reorder(const t_size * p_order) = 0;\r\n\t//! Removes values according to specified bit mask from specified metadata entry. If all values are removed, entire metadata entry is removed as well.\r\n\tvirtual void\t\tmeta_remove_values(t_size p_index,const bit_array & p_mask) = 0;\r\n\t//! Alters specified value in specified metadata entry.\r\n\tvirtual void\t\tmeta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) = 0;\r\n\r\n\t//! Retrieves number of technical info entries.\r\n\tvirtual t_size\t\tinfo_get_count() const = 0;\r\n\t//! Retrieves the name of specified technical info entry. Return value is a null-terminated UTF-8 encoded string.\r\n\tvirtual const char*\tinfo_enum_name(t_size p_index) const = 0;\r\n\t//! Retrieves the value of specified technical info entry. Return value is a null-terminated UTF-8 encoded string.\r\n\tvirtual const char*\tinfo_enum_value(t_size p_index) const = 0;\r\n\t//! Creates a new technical info entry with specified name and specified value. If an entry of the same name already exists, it is erased. Return value is the index of newly created entry.\r\n\tvirtual t_size\t\tinfo_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0;\r\n\t//! Removes technical info entries indicated by specified bit mask.\r\n\tvirtual void\t\tinfo_remove_mask(const bit_array & p_mask) = 0;\r\n\t//! Finds technical info entry of specified name. Returns index of found entry on success, infinite on failure.\r\n\tvirtual t_size\t\tinfo_find_ex(const char * p_name,t_size p_name_length) const;\r\n\r\n\t//! Copies entire file_info contents from specified file_info object.\r\n\tvirtual void\t\tcopy(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass\r\n\t//! Copies metadata from specified file_info object.\r\n\tvirtual void\t\tcopy_meta(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass\r\n\t//! Copies technical info from specified file_info object.\r\n\tvirtual void\t\tcopy_info(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass\r\n\r\n\tbool\t\t\tmeta_exists_ex(const char * p_name,t_size p_name_length) const;\r\n\tvoid\t\t\tmeta_remove_field_ex(const char * p_name,t_size p_name_length);\r\n\tvoid\t\t\tmeta_remove_index(t_size p_index);\r\n\tvoid\t\t\tmeta_remove_all();\r\n\tvoid\t\t\tmeta_remove_value(t_size p_index,t_size p_value);\r\n\tconst char *\tmeta_get_ex(const char * p_name,t_size p_name_length,t_size p_index) const;\r\n\tt_size\t\t\tmeta_get_count_by_name_ex(const char * p_name,t_size p_name_length) const;\r\n\tvoid\t\t\tmeta_add_value_ex(t_size p_index,const char * p_value,t_size p_value_length);\r\n\tt_size\t\t\tmeta_add_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\tt_size\t\t\tmeta_calc_total_value_count() const;\r\n\tbool\t\t\tmeta_format(const char * p_name,pfc::string_base & p_out) const;\r\n\t\r\n\t\r\n\tbool\t\t\tinfo_exists_ex(const char * p_name,t_size p_name_length) const;\r\n\tvoid\t\t\tinfo_remove_index(t_size p_index);\r\n\tvoid\t\t\tinfo_remove_all();\r\n\tbool\t\t\tinfo_remove_ex(const char * p_name,t_size p_name_length);\r\n\tconst char *\tinfo_get_ex(const char * p_name,t_size p_name_length) const;\r\n\r\n\tinline t_size\t\tmeta_find(const char * p_name) const\t{return meta_find_ex(p_name,infinite);}\r\n\tinline bool\t\t\tmeta_exists(const char * p_name) const\t\t{return meta_exists_ex(p_name,infinite);}\r\n\tinline void\t\t\tmeta_remove_field(const char * p_name)\t\t{meta_remove_field_ex(p_name,infinite);}\r\n\tinline t_size\t\tmeta_set(const char * p_name,const char * p_value)\t\t{return meta_set_ex(p_name,infinite,p_value,infinite);}\r\n\tinline void\t\t\tmeta_insert_value(t_size p_index,t_size p_value_index,const char * p_value) {meta_insert_value_ex(p_index,p_value_index,p_value,infinite);}\r\n\tinline void\t\t\tmeta_add_value(t_size p_index,const char * p_value)\t{meta_add_value_ex(p_index,p_value,infinite);}\r\n\tinline const char*\tmeta_get(const char * p_name,t_size p_index) const\t{return meta_get_ex(p_name,infinite,p_index);}\r\n\tinline t_size\t\tmeta_get_count_by_name(const char * p_name) const\t\t{return meta_get_count_by_name_ex(p_name,infinite);}\r\n\tinline t_size\t\tmeta_add(const char * p_name,const char * p_value)\t\t{return meta_add_ex(p_name,infinite,p_value,infinite);}\r\n\tinline void\t\t\tmeta_modify_value(t_size p_index,t_size p_value_index,const char * p_value) {meta_modify_value_ex(p_index,p_value_index,p_value,infinite);}\r\n\r\n\t\r\n\r\n\tinline t_size\t\tinfo_set(const char * p_name,const char * p_value)\t{return info_set_ex(p_name,infinite,p_value,infinite);}\r\n\tinline t_size\t\tinfo_find(const char * p_name) const\t\t\t\t{return info_find_ex(p_name,infinite);}\r\n\tinline t_size\t\tinfo_exists(const char * p_name) const\t\t\t\t{return info_exists_ex(p_name,infinite);}\r\n\tinline bool\t\t\tinfo_remove(const char * p_name)\t\t\t\t\t{return info_remove_ex(p_name,infinite);}\r\n\tinline const char *\tinfo_get(const char * p_name) const\t\t\t\t\t{return info_get_ex(p_name,infinite);}\r\n\r\n\tbool\t\t\t\tinfo_set_replaygain_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len);\r\n\tinline bool\t\t\tinfo_set_replaygain(const char * p_name,const char * p_value) {return info_set_replaygain_ex(p_name,infinite,p_value,infinite);}\r\n\tvoid\t\t\t\tinfo_set_replaygain_auto_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len);\r\n\tinline void\t\t\tinfo_set_replaygain_auto(const char * p_name,const char * p_value) {info_set_replaygain_auto_ex(p_name,infinite,p_value,infinite);}\r\n\r\n\t\r\n\r\n\tvoid\t\tcopy_meta_single(const file_info & p_source,t_size p_index);\r\n\tvoid\t\tcopy_info_single(const file_info & p_source,t_size p_index);\r\n\tvoid\t\tcopy_meta_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length);\r\n\tvoid\t\tcopy_info_single_by_name_ex(const file_info & p_source,const char * p_name,t_size p_name_length);\r\n\tinline void\tcopy_meta_single_by_name(const file_info & p_source,const char * p_name) {copy_meta_single_by_name_ex(p_source,p_name,infinite);}\r\n\tinline void\tcopy_info_single_by_name(const file_info & p_source,const char * p_name) {copy_info_single_by_name_ex(p_source,p_name,infinite);}\r\n\tvoid\t\treset();\r\n\tvoid\t\treset_replaygain();\r\n\tvoid\t\tcopy_meta_single_rename_ex(const file_info & p_source,t_size p_index,const char * p_new_name,t_size p_new_name_length);\r\n\tinline void\tcopy_meta_single_rename(const file_info & p_source,t_size p_index,const char * p_new_name) {copy_meta_single_rename_ex(p_source,p_index,p_new_name,infinite);}\r\n\tvoid\t\toverwrite_info(const file_info & p_source);\r\n\r\n\tt_int64 info_get_int(const char * name) const;\r\n\tt_int64 info_get_length_samples() const;\r\n\tdouble info_get_float(const char * name) const;\r\n\tvoid info_set_int(const char * name,t_int64 value);\r\n\tvoid info_set_float(const char * name,double value,unsigned precision,bool force_sign = false,const char * unit = 0);\r\n\tvoid info_set_replaygain_track_gain(float value);\r\n\tvoid info_set_replaygain_album_gain(float value);\r\n\tvoid info_set_replaygain_track_peak(float value);\r\n\tvoid info_set_replaygain_album_peak(float value);\r\n\r\n\tinline t_int64 info_get_bitrate_vbr() const {return info_get_int(\"bitrate_dynamic\");}\r\n\tinline void info_set_bitrate_vbr(t_int64 val) {info_set_int(\"bitrate_dynamic\",val);}\r\n\tinline t_int64 info_get_bitrate() const {return info_get_int(\"bitrate\");}\r\n\tinline void info_set_bitrate(t_int64 val) {info_set_int(\"bitrate\",val);}\r\n\tbool is_encoding_lossy() const;\r\n\r\n\tvoid info_calculate_bitrate(t_filesize p_filesize,double p_length);\r\n\r\n\tunsigned info_get_decoded_bps() const;//what bps the stream originally was (before converting to audio_sample), 0 if unknown\r\n\r\n\tvoid merge(const pfc::list_base_const_t<const file_info*> & p_sources);\r\n\r\n\tbool are_meta_fields_identical(t_size p_index1,t_size p_index2) const;\r\n\r\n\tinline const file_info & operator=(const file_info & p_source) {copy(p_source);return *this;}\r\n\r\n\tstatic bool g_is_meta_equal(const file_info & p_item1,const file_info & p_item2);\r\n\tstatic bool g_is_info_equal(const file_info & p_item1,const file_info & p_item2);\r\n\r\n\t//! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally.\r\n\tt_size\t__meta_add_unsafe_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {return meta_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);}\r\n\t//! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally.\r\n\tt_size\t__meta_add_unsafe(const char * p_name,const char * p_value) {return meta_set_nocheck_ex(p_name,infinite,p_value,infinite);}\r\n\r\n\t//! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally.\r\n\tt_size __info_add_unsafe_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {return info_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);}\r\n\t//! Unsafe - does not check whether the field already exists and will result in duplicates if it does - call only when appropriate checks have been applied externally.\r\n\tt_size __info_add_unsafe(const char * p_name,const char * p_value) {return info_set_nocheck_ex(p_name,infinite,p_value,infinite);}\r\n\r\n\tstatic bool g_is_valid_field_name(const char * p_name,t_size p_length = infinite);\r\n\ttypedef pfc::comparator_stricmp_ascii field_name_comparator;\r\nprotected:\r\n\tfile_info() {}\r\n\t~file_info() {}\r\n\tvoid\tcopy_meta_single_nocheck(const file_info & p_source,t_size p_index);\r\n\tvoid\tcopy_info_single_nocheck(const file_info & p_source,t_size p_index);\r\n\tvoid\tcopy_meta_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length);\r\n\tvoid\tcopy_info_single_by_name_nocheck_ex(const file_info & p_source,const char * p_name,t_size p_name_length);\r\n\tinline void\tcopy_meta_single_by_name_nocheck(const file_info & p_source,const char * p_name) {copy_meta_single_by_name_nocheck_ex(p_source,p_name,infinite);}\r\n\tinline void\tcopy_info_single_by_name_nocheck(const file_info & p_source,const char * p_name) {copy_info_single_by_name_nocheck_ex(p_source,p_name,infinite);}\r\n\r\n\tvirtual t_size\tmeta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0;\r\n\tvirtual t_size\tinfo_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0;\r\n\tinline t_size\tmeta_set_nocheck(const char * p_name,const char * p_value) {return meta_set_nocheck_ex(p_name,infinite,p_value,infinite);}\r\n\tinline t_size\tinfo_set_nocheck(const char * p_name,const char * p_value) {return info_set_nocheck_ex(p_name,infinite,p_value,infinite);}\r\n};\r\n\r\n\r\n#endif //_FILE_INFO_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_info_impl.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nt_size file_info_impl::meta_get_count() const\r\n{\r\n\treturn m_meta.get_count();\r\n}\r\n\r\nconst char* file_info_impl::meta_enum_name(t_size p_index) const\r\n{\r\n\treturn m_meta.get_name(p_index);\r\n}\r\n\r\nt_size file_info_impl::meta_enum_value_count(t_size p_index) const\r\n{\r\n\treturn m_meta.get_value_count(p_index);\r\n}\r\n\r\nconst char* file_info_impl::meta_enum_value(t_size p_index,t_size p_value_number) const\r\n{\r\n\treturn m_meta.get_value(p_index,p_value_number);\r\n}\r\n\r\nt_size file_info_impl::meta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\tmeta_remove_field_ex(p_name,p_name_length);\r\n\treturn meta_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);\r\n}\r\n\r\nt_size file_info_impl::meta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\treturn m_meta.add_entry(p_name,p_name_length,p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl::meta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tm_meta.insert_value(p_index,p_value_index,p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl::meta_remove_mask(const bit_array & p_mask)\r\n{\r\n\tm_meta.remove_mask(p_mask);\r\n}\r\n\r\nvoid file_info_impl::meta_reorder(const t_size * p_order)\r\n{\r\n\tm_meta.reorder(p_order);\r\n}\r\n\r\nvoid file_info_impl::meta_remove_values(t_size p_index,const bit_array & p_mask)\r\n{\r\n\tm_meta.remove_values(p_index,p_mask);\r\n\tif (m_meta.get_value_count(p_index) == 0)\r\n\t\tm_meta.remove_mask(bit_array_one(p_index));\r\n}\r\n\r\nt_size file_info_impl::info_get_count() const\r\n{\r\n\treturn m_info.get_count();\r\n}\r\n\r\nconst char* file_info_impl::info_enum_name(t_size p_index) const\r\n{\r\n\treturn m_info.get_name(p_index);\r\n}\r\n\r\nconst char* file_info_impl::info_enum_value(t_size p_index) const\r\n{\r\n\treturn m_info.get_value(p_index);\r\n}\r\n\r\nt_size file_info_impl::info_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\tinfo_remove_ex(p_name,p_name_length);\r\n\treturn info_set_nocheck_ex(p_name,p_name_length,p_value,p_value_length);\r\n}\r\n\r\nt_size file_info_impl::info_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\treturn m_info.add_item(p_name,p_name_length,p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl::info_remove_mask(const bit_array & p_mask)\r\n{\r\n\tm_info.remove_mask(p_mask);\r\n}\r\n\r\n\r\nfile_info_impl::file_info_impl(const file_info & p_source) : m_length(0)\r\n{\r\n\tcopy(p_source);\r\n}\r\n\r\nfile_info_impl::file_info_impl(const file_info_impl & p_source) : m_length(0)\r\n{\r\n\tcopy(p_source);\r\n}\r\n\r\nconst file_info_impl & file_info_impl::operator=(const file_info_impl & p_source)\r\n{\r\n\tcopy(p_source);\r\n\treturn *this;\r\n}\r\n\r\nfile_info_impl::file_info_impl() : m_length(0)\r\n{\r\n\tm_replaygain.reset();\r\n}\r\n\r\ndouble file_info_impl::get_length() const\r\n{\r\n\treturn m_length;\r\n}\r\n\r\nvoid file_info_impl::set_length(double p_length)\r\n{\r\n\tm_length = p_length;\r\n}\r\n\r\nvoid file_info_impl::meta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tm_meta.modify_value(p_index,p_value_index,p_value,p_value_length);\r\n}\r\n\r\nreplaygain_info file_info_impl::get_replaygain() const\r\n{\r\n\treturn m_replaygain;\r\n}\r\n\r\nvoid file_info_impl::set_replaygain(const replaygain_info & p_info)\r\n{\r\n\tm_replaygain = p_info;\r\n}\r\n\r\n\r\n\r\n\r\nfile_info_impl::~file_info_impl()\r\n{\r\n}\r\n\r\nt_size file_info_impl_utils::info_storage::add_item(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {\r\n\tt_size index = m_info.get_size();\r\n\tm_info.set_size(index + 1);\r\n\tm_info[index].init(p_name,p_name_length,p_value,p_value_length);\r\n\treturn index;\r\n}\r\n\r\nvoid file_info_impl_utils::info_storage::remove_mask(const bit_array & p_mask) {\r\n\tpfc::remove_mask_t(m_info,p_mask);\r\n}\r\n\r\n\r\n\r\nt_size file_info_impl_utils::meta_storage::add_entry(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n{\r\n\tmeta_entry temp(p_name,p_name_length,p_value,p_value_length);\r\n\treturn pfc::append_swap_t(m_data,temp);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::insert_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tm_data[p_index].insert_value(p_value_index,p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::modify_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tm_data[p_index].modify_value(p_value_index,p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::remove_values(t_size p_index,const bit_array & p_mask)\r\n{\r\n\tm_data[p_index].remove_values(p_mask);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::remove_mask(const bit_array & p_mask)\r\n{\r\n\tpfc::remove_mask_t(m_data,p_mask);\r\n}\r\n\t\r\n\r\nfile_info_impl_utils::meta_entry::meta_entry(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len)\r\n{\r\n\tm_name.set_string(p_name,p_name_len);\r\n\tm_values.set_size(1);\r\n\tm_values[0].set_string(p_value,p_value_len);\r\n}\r\n\r\n\r\nvoid file_info_impl_utils::meta_entry::remove_values(const bit_array & p_mask)\r\n{\r\n\tpfc::remove_mask_t(m_values,p_mask);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_entry::insert_value(t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tpfc::string_simple temp;\r\n\ttemp.set_string(p_value,p_value_length);\r\n\tpfc::insert_swap_t(m_values,temp,p_value_index);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_entry::modify_value(t_size p_value_index,const char * p_value,t_size p_value_length)\r\n{\r\n\tm_values[p_value_index].set_string(p_value,p_value_length);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::reorder(const t_size * p_order)\r\n{\r\n\tpfc::reorder_t(m_data,p_order,m_data.get_size());\r\n}\r\n\r\nvoid file_info_impl::copy_meta(const file_info & p_source)\r\n{\r\n\tm_meta.copy_from(p_source);\r\n}\r\n\r\nvoid file_info_impl::copy_info(const file_info & p_source)\r\n{\r\n\tm_info.copy_from(p_source);\r\n}\r\n\r\nvoid file_info_impl_utils::meta_storage::copy_from(const file_info & p_info)\r\n{\r\n\tt_size meta_index,meta_count = p_info.meta_get_count();\r\n\tm_data.set_size(meta_count);\r\n\tfor(meta_index=0;meta_index<meta_count;meta_index++)\r\n\t{\r\n\t\tmeta_entry & entry = m_data[meta_index];\r\n\t\tt_size value_index,value_count = p_info.meta_enum_value_count(meta_index);\r\n\t\tentry.m_name = p_info.meta_enum_name(meta_index);\r\n\t\tentry.m_values.set_size(value_count);\r\n\t\tfor(value_index=0;value_index<value_count;value_index++)\r\n\t\t\tentry.m_values[value_index] = p_info.meta_enum_value(meta_index,value_index);\r\n\t}\r\n}\r\n\r\nvoid file_info_impl_utils::info_storage::copy_from(const file_info & p_info)\r\n{\r\n\tt_size n, count;\r\n\tcount = p_info.info_get_count();\r\n\tm_info.set_count(count);\r\n\tfor(n=0;n<count;n++) m_info[n].init(p_info.info_enum_name(n),infinite,p_info.info_enum_value(n),infinite);\t\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_info_impl.h",
    "content": "#ifndef _FOOBAR2000_SDK_FILE_INFO_IMPL_H_\r\n#define _FOOBAR2000_SDK_FILE_INFO_IMPL_H_\r\n\r\nnamespace file_info_impl_utils {\r\n\r\n\tstruct info_entry {\r\n\t\tvoid init(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len) {\r\n\t\t\tm_name.set_string(p_name,p_name_len);\r\n\t\t\tm_value.set_string(p_value,p_value_len);\r\n\t\t}\r\n\t\t\r\n\t\tinline const char * get_name() const {return m_name;}\r\n\t\tinline const char * get_value() const {return m_value;}\r\n\r\n\t\tpfc::string_simple m_name,m_value;\r\n\t};\r\n\r\n\ttypedef pfc::array_t<info_entry,pfc::alloc_fast> info_entry_array;\r\n\r\n}\r\n\r\nnamespace pfc {\r\n\ttemplate<> class traits_t<file_info_impl_utils::info_entry> : public traits_t<pfc::string_simple> {};\r\n};\r\n\r\n\r\nnamespace file_info_impl_utils {\r\n\tclass info_storage\r\n\t{\r\n\tpublic:\r\n\t\tt_size add_item(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\t\tvoid remove_mask(const bit_array & p_mask);\t\r\n\t\tinline t_size get_count() const {return m_info.get_count();}\r\n\t\tinline const char * get_name(t_size p_index) const {return m_info[p_index].get_name();}\r\n\t\tinline const char * get_value(t_size p_index) const {return m_info[p_index].get_value();}\r\n\t\tvoid copy_from(const file_info & p_info);\r\n\tprivate:\r\n\t\tinfo_entry_array m_info;\r\n\t};\r\n}\r\n\r\n\r\nnamespace file_info_impl_utils {\r\n\ttypedef pfc::array_hybrid_t<pfc::string_simple,1,pfc::alloc_fast > meta_value_array;\r\n\tstruct meta_entry {\r\n\t\tmeta_entry() {}\r\n\t\tmeta_entry(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len);\r\n\r\n\t\tvoid remove_values(const bit_array & p_mask);\r\n\t\tvoid insert_value(t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\t\tvoid modify_value(t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\r\n\t\tinline const char * get_name() const {return m_name;}\r\n\t\tinline const char * get_value(t_size p_index) const {return m_values[p_index];}\r\n\t\tinline t_size get_value_count() const {return m_values.get_size();}\r\n\t\t\r\n\r\n\t\tpfc::string_simple m_name;\r\n\t\tmeta_value_array m_values;\r\n\t};\r\n\ttypedef pfc::array_hybrid_t<meta_entry,10, pfc::alloc_fast> meta_entry_array;\r\n}\r\nnamespace pfc {\r\n\ttemplate<> class traits_t<file_info_impl_utils::meta_entry> : public pfc::traits_combined<pfc::string_simple,file_info_impl_utils::meta_value_array> {};\r\n}\r\n\r\n\r\nnamespace file_info_impl_utils {\r\n\tclass meta_storage\r\n\t{\r\n\tpublic:\r\n\t\tt_size add_entry(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\t\tvoid insert_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\t\tvoid modify_value(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\t\tvoid remove_values(t_size p_index,const bit_array & p_mask);\r\n\t\tvoid remove_mask(const bit_array & p_mask);\r\n\t\tvoid copy_from(const file_info & p_info);\r\n\r\n\t\tinline void reorder(const t_size * p_order);\r\n\r\n\t\tinline t_size get_count() const {return m_data.get_size();}\r\n\t\t\r\n\t\tinline const char * get_name(t_size p_index) const {assert(p_index < m_data.get_size()); return m_data[p_index].get_name();}\r\n\t\tinline const char * get_value(t_size p_index,t_size p_value_index) const {assert(p_index < m_data.get_size()); return m_data[p_index].get_value(p_value_index);}\r\n\t\tinline t_size get_value_count(t_size p_index) const {assert(p_index < m_data.get_size()); return m_data[p_index].get_value_count();}\r\n\r\n\tprivate:\r\n\t\tmeta_entry_array m_data;\r\n\t};\r\n}\r\n\r\n//! Implements file_info.\r\nclass file_info_impl : public file_info\r\n{\r\npublic:\r\n\tfile_info_impl(const file_info_impl & p_source);\r\n\tfile_info_impl(const file_info & p_source);\r\n\tfile_info_impl();\r\n\t~file_info_impl();\r\n\r\n\tdouble\t\tget_length() const;\r\n\tvoid\t\tset_length(double p_length);\r\n\r\n\tvoid\t\tcopy_meta(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass\r\n\tvoid\t\tcopy_info(const file_info & p_source);//virtualized for performance reasons, can be faster in two-pass\r\n\t\r\n\tt_size\tmeta_get_count() const;\r\n\tconst char*\tmeta_enum_name(t_size p_index) const;\r\n\tt_size\tmeta_enum_value_count(t_size p_index) const;\r\n\tconst char*\tmeta_enum_value(t_size p_index,t_size p_value_number) const;\r\n\tt_size\tmeta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\tvoid\t\tmeta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\tvoid\t\tmeta_remove_mask(const bit_array & p_mask);\r\n\tvoid\t\tmeta_reorder(const t_size * p_order);\r\n\tvoid\t\tmeta_remove_values(t_size p_index,const bit_array & p_mask);\r\n\tvoid\t\tmeta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length);\r\n\r\n\tt_size\tinfo_get_count() const;\r\n\tconst char*\tinfo_enum_name(t_size p_index) const;\r\n\tconst char*\tinfo_enum_value(t_size p_index) const;\r\n\tt_size\tinfo_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\tvoid\t\tinfo_remove_mask(const bit_array & p_mask);\r\n\r\n\tconst file_info_impl & operator=(const file_info_impl & p_source);\r\n\r\n\treplaygain_info\tget_replaygain() const;\r\n\tvoid\t\t\tset_replaygain(const replaygain_info & p_info);\r\n\r\nprotected:\r\n\tt_size\tmeta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\n\tt_size\tinfo_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length);\r\nprivate:\r\n\r\n\r\n\tfile_info_impl_utils::meta_storage m_meta;\r\n\tfile_info_impl_utils::info_storage m_info;\r\n\t\r\n\r\n\tdouble m_length;\r\n\r\n\treplaygain_info m_replaygain;\r\n};\r\n\r\ntypedef file_info_impl file_info_i;//for compatibility\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_info_merge.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nstatic t_size merge_tags_calc_rating_by_index(const file_info & p_info,t_size p_index) {\r\n\tt_size n,m = p_info.meta_enum_value_count(p_index);\r\n\tt_size ret = 0;\r\n\tfor(n=0;n<m;n++)\r\n\t\tret += strlen(p_info.meta_enum_value(p_index,n)) + 10;//yes, strlen on utf8 data, plus a slight bump to prefer multivalue over singlevalue w/ separator\r\n\treturn ret;\r\n}\r\n\r\nstatic t_size merge_tags_calc_rating(const file_info & p_info,const char * p_field) {\r\n\tt_size field_index = p_info.meta_find(p_field);\r\n\tt_size ret = 0;\r\n\tif (field_index != infinite) {\r\n\t\treturn merge_tags_calc_rating_by_index(p_info,field_index);\r\n\t} else {\r\n\t\treturn 0;\r\n\t}\r\n}\r\n\r\nstatic void merge_tags_copy_info(const char * field,const file_info * from,file_info * to)\r\n{\r\n\tconst char * val = from->info_get(field);\r\n\tif (val) to->info_set(field,val);\r\n}\r\n\r\nnamespace {\r\n\tstruct meta_merge_entry {\r\n\t\tmeta_merge_entry() : m_rating(0) {}\r\n\t\tt_size m_rating;\r\n\t\tpfc::array_t<const char *> m_data;\r\n\t};\r\n\r\n\tclass meta_merge_map_enumerator {\r\n\tpublic:\r\n\t\tmeta_merge_map_enumerator(file_info & p_out) : m_out(p_out) {\r\n\t\t\tm_out.meta_remove_all();\r\n\t\t}\r\n\t\tvoid operator() (const char * p_name, const meta_merge_entry & p_entry) {\r\n\t\t\tif (p_entry.m_data.get_size() > 0) {\r\n\t\t\t\tt_size index = m_out.__meta_add_unsafe(p_name,p_entry.m_data[0]);\r\n\t\t\t\tfor(t_size walk = 1; walk < p_entry.m_data.get_size(); ++walk) {\r\n\t\t\t\t\tm_out.meta_add_value(index,p_entry.m_data[walk]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tfile_info & m_out;\r\n\t};\r\n}\r\n\r\nstatic void merge_meta(file_info & p_out,const pfc::list_base_const_t<const file_info*> & p_in) {\r\n\tpfc::map_t<const char *,meta_merge_entry,pfc::comparator_stricmp_ascii> map;\r\n\tfor(t_size in_walk = 0; in_walk < p_in.get_count(); in_walk++) {\r\n\t\tconst file_info & in = * p_in[in_walk];\r\n\t\tfor(t_size meta_walk = 0, meta_count = in.meta_get_count(); meta_walk < meta_count; meta_walk++ ) {\r\n\t\t\tmeta_merge_entry & entry = map.find_or_add(in.meta_enum_name(meta_walk));\r\n\t\t\tt_size rating = merge_tags_calc_rating_by_index(in,meta_walk);\r\n\t\t\tif (rating > entry.m_rating) {\r\n\t\t\t\tentry.m_rating = rating;\r\n\t\t\t\tconst t_size value_count = in.meta_enum_value_count(meta_walk);\r\n\t\t\t\tentry.m_data.set_size(value_count);\r\n\t\t\t\tfor(t_size value_walk = 0; value_walk < value_count; value_walk++ ) {\r\n\t\t\t\t\tentry.m_data[value_walk] = in.meta_enum_value(meta_walk,value_walk);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tmap.enumerate(meta_merge_map_enumerator(p_out));\r\n}\r\n\r\nvoid file_info::merge(const pfc::list_base_const_t<const file_info*> & p_in)\r\n{\r\n\tt_size in_count = p_in.get_count();\r\n\tif (in_count == 0)\r\n\t{\r\n\t\tmeta_remove_all();\r\n\t\treturn;\r\n\t}\r\n\telse if (in_count == 1)\r\n\t{\r\n\t\tconst file_info * info = p_in[0];\r\n\r\n\t\tcopy_meta(*info);\r\n\r\n\t\tset_replaygain(replaygain_info::g_merge(get_replaygain(),info->get_replaygain()));\r\n\r\n\t\toverwrite_info(*info);\r\n\r\n\t\t//copy_info_single_by_name(*info,\"tagtype\");\r\n\t\t\r\n\t\treturn;\r\n\t}\r\n\t\r\n\tmerge_meta(*this,p_in);\r\n\r\n\t{\r\n\t\tpfc::string8_fastalloc tagtype;\r\n\t\treplaygain_info rg = get_replaygain();\r\n\t\tt_size in_ptr;\r\n\t\tfor(in_ptr = 0; in_ptr < in_count; in_ptr++ )\r\n\t\t{\r\n\t\t\tconst file_info * info = p_in[in_ptr];\r\n\t\t\trg = replaygain_info::g_merge(rg, info->get_replaygain());\r\n\t\t\tt_size field_ptr, field_max = info->info_get_count();\r\n\t\t\tfor(field_ptr = 0; field_ptr < field_max; field_ptr++ )\r\n\t\t\t{\r\n\t\t\t\tconst char * field_name = info->info_enum_name(field_ptr), * field_value = info->info_enum_value(field_ptr);\r\n\t\t\t\tif (*field_value)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!stricmp_utf8(field_name,\"tagtype\"))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (!tagtype.is_empty()) tagtype += \"|\";\r\n\t\t\t\t\t\ttagtype += field_value;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (!tagtype.is_empty()) info_set(\"tagtype\",tagtype);\r\n\t\tset_replaygain(rg);\r\n\t}\r\n}\r\n\r\nvoid file_info::overwrite_info(const file_info & p_source) {\r\n\tt_size count = p_source.info_get_count();\r\n\tfor(t_size n=0;n<count;n++) {\r\n\t\tinfo_set(p_source.info_enum_name(n),p_source.info_enum_value(n));\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_operation_callback.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nstatic void g_on_files_deleted_sorted(const pfc::list_base_const_t<const char *> & p_items)\r\n{\r\n\tstatic_api_ptr_t<library_manager>()->on_files_deleted_sorted(p_items);\r\n\tstatic_api_ptr_t<playlist_manager>()->on_files_deleted_sorted(p_items);\r\n\r\n\tservice_ptr_t<file_operation_callback> ptr;\r\n\tservice_enum_t<file_operation_callback> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tptr->on_files_deleted_sorted(p_items);\r\n\t}\r\n}\r\n\r\nstatic void g_on_files_moved_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to)\r\n{\r\n\tstatic_api_ptr_t<playlist_manager>()->on_files_moved_sorted(p_from,p_to);\r\n\tstatic_api_ptr_t<playlist_manager>()->on_files_deleted_sorted(p_from);\r\n\r\n\tservice_ptr_t<file_operation_callback> ptr;\r\n\tservice_enum_t<file_operation_callback> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tptr->on_files_moved_sorted(p_from,p_to);\r\n\t}\r\n}\r\n\r\nstatic void g_on_files_copied_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to)\r\n{\r\n\tservice_ptr_t<file_operation_callback> ptr;\r\n\tservice_enum_t<file_operation_callback> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tptr->on_files_copied_sorted(p_from,p_to);\r\n\t}\r\n}\r\n\r\nvoid file_operation_callback::g_on_files_deleted(const pfc::list_base_const_t<const char *> & p_items)\r\n{\r\n\tcore_api::ensure_main_thread();\r\n\tt_size count = p_items.get_count();\r\n\tif (count > 0)\r\n\t{\r\n\t\tif (count == 1) g_on_files_deleted_sorted(p_items);\r\n\t\telse\r\n\t\t{\r\n\t\t\tpfc::array_t<t_size> order; order.set_size(count);\r\n\t\t\torder_helper::g_fill(order);\r\n\t\t\tp_items.sort_get_permutation_t(metadb::path_compare,order.get_ptr());\r\n\t\t\tg_on_files_deleted_sorted(pfc::list_permutation_t<const char*>(p_items,order.get_ptr(),count));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid file_operation_callback::g_on_files_moved(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to)\r\n{\r\n\tcore_api::ensure_main_thread();\r\n\tpfc::dynamic_assert(p_from.get_count() == p_to.get_count());\r\n\tt_size count = p_from.get_count();\r\n\tif (count > 0)\r\n\t{\r\n\t\tif (count == 1) g_on_files_moved_sorted(p_from,p_to);\r\n\t\telse\r\n\t\t{\r\n\t\t\tpfc::array_t<t_size> order; order.set_size(count);\r\n\t\t\torder_helper::g_fill(order);\r\n\t\t\tp_from.sort_get_permutation_t(metadb::path_compare,order.get_ptr());\r\n\t\t\tg_on_files_moved_sorted(pfc::list_permutation_t<const char*>(p_from,order.get_ptr(),count),pfc::list_permutation_t<const char*>(p_to,order.get_ptr(),count));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid file_operation_callback::g_on_files_copied(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to)\r\n{\r\n\tif (core_api::assert_main_thread())\r\n\t{\r\n\t\tassert(p_from.get_count() == p_to.get_count());\r\n\t\tt_size count = p_from.get_count();\r\n\t\tif (count > 0)\r\n\t\t{\r\n\t\t\tif (count == 1) g_on_files_copied_sorted(p_from,p_to);\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tpfc::array_t<t_size> order; order.set_size(count);\r\n\t\t\t\torder_helper::g_fill(order);\r\n\t\t\t\tp_from.sort_get_permutation_t(metadb::path_compare,order.get_ptr());\r\n\t\t\t\tg_on_files_copied_sorted(pfc::list_permutation_t<const char*>(p_from,order.get_ptr(),count),pfc::list_permutation_t<const char*>(p_to,order.get_ptr(),count));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/file_operation_callback.h",
    "content": "#ifndef _FILE_OPERATION_CALLBACK_H_\r\n#define _FILE_OPERATION_CALLBACK_H_\r\n\r\n//! Interface to notify component system about files being deleted or moved. Operates in app's main thread only.\r\n\r\nclass file_operation_callback : public service_base\r\n{\r\npublic:\r\n\t//! p_items is a metadb::path_compare sorted list of files that have been deleted.\r\n\tvirtual void on_files_deleted_sorted(const pfc::list_base_const_t<const char *> & p_items) = 0;\r\n\t//! p_from is a metadb::path_compare sorted list of files that have been moved, p_to is a list of corresponding target locations.\r\n\tvirtual void on_files_moved_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to) = 0;\r\n\t//! p_from is a metadb::path_compare sorted list of files that have been copied, p_to is a list of corresponding target locations.\r\n\tvirtual void on_files_copied_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to) = 0;\r\n\r\n\tstatic void g_on_files_deleted(const pfc::list_base_const_t<const char *> & p_items);\r\n\tstatic void g_on_files_moved(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to);\r\n\tstatic void g_on_files_copied(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to);\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(file_operation_callback);\r\n};\r\n\r\n\r\n#endif //_FILE_OPERATION_CALLBACK_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/filesystem.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nvoid unpacker::g_open(service_ptr_t<file> & p_out,const service_ptr_t<file> & p,abort_callback & p_abort)\r\n{\r\n\tservice_enum_t<unpacker> e;\r\n\tservice_ptr_t<unpacker> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tp->reopen(p_abort);\r\n\t\ttry {\r\n\t\t\tptr->open(p_out,p,p_abort);\r\n\t\t\treturn;\r\n\t\t} catch(exception_io_data const &) {}\r\n\t} while(e.next(ptr));\r\n\tthrow exception_io_data();\r\n}\r\n\r\nvoid file::seek_ex(t_sfilesize p_position, file::t_seek_mode p_mode, abort_callback &p_abort) {\r\n\tswitch(p_mode) {\r\n\tcase seek_from_beginning:\r\n\t\tseek(p_position,p_abort);\r\n\t\tbreak;\r\n\tcase seek_from_current:\r\n\t\tseek(p_position + get_position(p_abort),p_abort);\r\n\t\tbreak;\r\n\tcase seek_from_eof:\r\n\t\tseek(p_position + get_size_ex(p_abort),p_abort);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tthrow exception_io_data();\r\n\t}\r\n}\r\n\r\nt_filesize file::g_transfer(stream_reader * p_src,stream_writer * p_dst,t_filesize p_bytes,abort_callback & p_abort) {\r\n\tenum {BUFSIZE = 1024*1024*8};\r\n\tpfc::array_t<t_uint8> temp;\r\n\ttemp.set_size((t_size)pfc::min_t<t_filesize>(BUFSIZE,p_bytes));\r\n\tvoid* ptr = temp.get_ptr();\r\n\tt_filesize done = 0;\r\n\twhile(done<p_bytes) {\r\n\t\tp_abort.check_e();\r\n\t\tt_size delta = (t_size)pfc::min_t<t_filesize>(BUFSIZE,p_bytes-done);\r\n\t\tdelta = p_src->read(ptr,delta,p_abort);\r\n\t\tif (delta<=0) break;\r\n\t\tp_dst->write(ptr,delta,p_abort);\r\n\t\tdone += delta;\r\n\t}\r\n\treturn done;\r\n}\r\n\r\nvoid file::g_transfer_object(stream_reader * p_src,stream_writer * p_dst,t_filesize p_bytes,abort_callback & p_abort) {\r\n\tif (g_transfer(p_src,p_dst,p_bytes,p_abort) != p_bytes)\r\n\t\tthrow exception_io_data_truncation();\r\n}\r\n\r\n\r\nvoid filesystem::g_get_canonical_path(const char * path,pfc::string_base & out)\r\n{\r\n\tTRACK_CALL_TEXT(\"filesystem::g_get_canonical_path\");\r\n\r\n\tservice_enum_t<filesystem> e;\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->get_canonical_path(path,out)) return;\r\n\t} while(e.next(ptr));\r\n\t//no one wants to process this, lets copy over\r\n\tout.set_string(path);\r\n}\r\n\r\nvoid filesystem::g_get_display_path(const char * path,pfc::string_base & out)\r\n{\r\n\tTRACK_CALL_TEXT(\"filesystem::g_get_display_path\");\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (!g_get_interface(ptr,path))\r\n\t{\r\n\t\t//noone wants to process this, lets copy over\r\n\t\tout.set_string(path);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (!ptr->get_display_path(path,out))\r\n\t\t\tout.set_string(path);\r\n\t}\r\n}\r\n\r\nbool filesystem::g_get_interface(service_ptr_t<filesystem> & p_out,const char * path)\r\n{\r\n\tservice_enum_t<filesystem> e;\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->is_our_path(path))\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n\r\n\r\nvoid filesystem::g_open(service_ptr_t<file> & p_out,const char * path,t_open_mode mode,abort_callback & p_abort)\r\n{\r\n\tTRACK_CALL_TEXT(\"filesystem::g_open\");\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (!g_get_interface(fs,path)) throw exception_io_no_handler_for_path();\r\n\tfs->open(p_out,path,mode,p_abort);\r\n}\r\n\r\nvoid filesystem::g_open_timeout(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort) {\r\n\tpfc::lores_timer timer;\r\n\ttimer.start();\r\n\tfor(;;) {\r\n\t\ttry {\r\n\t\t\tg_open(p_out,p_path,p_mode,p_abort);\r\n\t\t\tbreak;\r\n\t\t} catch(exception_io_sharing_violation) {\r\n\t\t\tif (timer.query() > p_timeout) throw;\r\n\t\t\tp_abort.sleep(0.01);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool filesystem::g_exists(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tt_filestats stats;\r\n\tbool dummy;\r\n\ttry {\r\n\t\tg_get_stats(p_path,stats,dummy,p_abort);\r\n\t} catch(exception_io_not_found) {return false;}\r\n\treturn true;\r\n}\r\n\r\nbool filesystem::g_exists_writeable(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tt_filestats stats;\r\n\tbool writeable;\r\n\ttry {\r\n\t\tg_get_stats(p_path,stats,writeable,p_abort);\r\n\t} catch(exception_io_not_found) {return false;}\r\n\treturn writeable;\r\n}\r\n\r\nvoid filesystem::g_remove(const char * p_path,abort_callback & p_abort) {\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (!g_get_interface(fs,p_path)) throw exception_io_no_handler_for_path();\r\n\tfs->remove(p_path,p_abort);\r\n}\r\n\r\nvoid filesystem::g_remove_timeout(const char * p_path,double p_timeout,abort_callback & p_abort) {\r\n\tpfc::lores_timer timer;\r\n\ttimer.start();\r\n\tfor(;;) {\r\n\t\ttry {\r\n\t\t\tg_remove(p_path,p_abort);\r\n\t\t\tbreak;\r\n\t\t} catch(exception_io_sharing_violation) {\r\n\t\t\tif (timer.query() > p_timeout) throw;\r\n\t\t\tp_abort.sleep(0.01);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid filesystem::g_move_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort) {\r\n\tpfc::lores_timer timer;\r\n\ttimer.start();\r\n\tfor(;;) {\r\n\t\ttry {\r\n\t\t\tg_move(p_src,p_dst,p_abort);\r\n\t\t\tbreak;\r\n\t\t} catch(exception_io_sharing_violation) {\r\n\t\t\tif (timer.query() > p_timeout) throw;\r\n\t\t\tp_abort.sleep(0.01);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid filesystem::g_copy_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort) {\r\n\tpfc::lores_timer timer;\r\n\ttimer.start();\r\n\tfor(;;) {\r\n\t\ttry {\r\n\t\t\tg_copy(p_src,p_dst,p_abort);\r\n\t\t\tbreak;\r\n\t\t} catch(exception_io_sharing_violation) {\r\n\t\t\tif (timer.query() > p_timeout) throw;\r\n\t\t\tp_abort.sleep(0.01);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid filesystem::g_create_directory(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (!g_get_interface(fs,p_path)) throw exception_io_no_handler_for_path();\r\n\tfs->create_directory(p_path,p_abort);\r\n}\r\n\r\nvoid filesystem::g_move(const char * src,const char * dst,abort_callback & p_abort) {\r\n\tservice_enum_t<filesystem> e;\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->is_our_path(src) && ptr->is_our_path(dst)) {\r\n\t\t\tptr->move(src,dst,p_abort);\r\n\t\t\treturn;\r\n\t\t}\r\n\t} while(e.next(ptr));\r\n\tthrow exception_io_no_handler_for_path();\r\n}\r\n\r\nvoid filesystem::g_list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort)\r\n{\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (!g_get_interface(ptr,p_path)) throw exception_io_no_handler_for_path();\r\n\tptr->list_directory(p_path,p_out,p_abort);\r\n}\r\n\r\n\r\nstatic void path_pack_string(pfc::string_base & out,const char * src)\r\n{\r\n\tout.add_char('|');\r\n\tout << strlen(src);\r\n\tout.add_char('|');\r\n\tout << src;\r\n\tout.add_char('|');\r\n}\r\n\r\nstatic int path_unpack_string(pfc::string8 & out,const char * src)\r\n{\r\n\tint ptr=0;\r\n\tif (src[ptr++]!='|') return -1;\r\n\tint len = atoi(src+ptr);\r\n\tif (len<=0) return -1;\r\n\twhile(src[ptr]!=0 && src[ptr]!='|') ptr++;\r\n\tif (src[ptr]!='|') return -1;\r\n\tptr++;\r\n\tint start = ptr;\r\n\twhile(ptr-start<len)\r\n\t{\r\n\t\tif (src[ptr]==0) return -1;\r\n\t\tptr++;\r\n\t}\r\n\tif (src[ptr]!='|') return -1;\r\n\tout.add_string(&src[start],len);\r\n\tptr++;\t\r\n\treturn ptr;\r\n}\r\n\r\n\r\nvoid filesystem::g_open_precache(service_ptr_t<file> & p_out,const char * p_path,abort_callback & p_abort) {\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (!g_get_interface(fs,p_path)) throw exception_io_no_handler_for_path();\r\n\tif (fs->is_remote(p_path)) throw exception_io_object_is_remote();\r\n\tfs->open(p_out,p_path,open_mode_read,p_abort);\r\n}\r\n\r\nbool filesystem::g_is_remote(const char * p_path) {\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (g_get_interface(fs,p_path)) return fs->is_remote(p_path);\r\n\telse throw exception_io_no_handler_for_path();\r\n}\r\n\r\nbool filesystem::g_is_remote_safe(const char * p_path) {\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (g_get_interface(fs,p_path)) return fs->is_remote(p_path);\r\n\telse return false;\r\n}\r\n\r\nbool filesystem::g_is_remote_or_unrecognized(const char * p_path) {\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (g_get_interface(fs,p_path)) return fs->is_remote(p_path);\r\n\telse return true;\r\n}\r\n\r\nbool filesystem::g_relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out)\r\n{\r\n\t\r\n\tbool rv = false;\r\n\tservice_ptr_t<filesystem> fs;\r\n\r\n\tif (g_get_interface(fs,file_path))\r\n\t\trv = fs->relative_path_create(file_path,playlist_path,out);\r\n\t\r\n\treturn rv;\r\n}\r\n\r\nbool filesystem::g_relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out)\r\n{\r\n\tservice_enum_t<filesystem> e;\r\n\tservice_ptr_t<filesystem> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->relative_path_parse(relative_path,playlist_path,out)) return true;\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\nbool archive_impl::get_canonical_path(const char * path,pfc::string_base & out)\r\n{\r\n\tif (is_our_path(path))\r\n\t{\r\n\t\tpfc::string8 archive,file,archive_canonical;\r\n\t\tif (g_parse_unpack_path(path,archive,file))\r\n\t\t{\r\n\t\t\tg_get_canonical_path(archive,archive_canonical);\r\n\t\t\tmake_unpack_path(out,archive_canonical,file);\r\n\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse return false;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nbool archive_impl::is_our_path(const char * path)\r\n{\r\n\tif (strncmp(path,\"unpack://\",9)) return false;\r\n\tconst char * type = get_archive_type();\r\n\tpath += 9;\r\n\twhile(*type)\r\n\t{\r\n\t\tif (*type!=*path) return false;\r\n\t\ttype++;\r\n\t\tpath++;\r\n\t}\r\n\tif (*path!='|') return false;\r\n\treturn true;\r\n}\r\n\r\nbool archive_impl::get_display_path(const char * path,pfc::string_base & out)\r\n{\r\n\tpfc::string8 archive,file;\r\n\tif (g_parse_unpack_path(path,archive,file))\r\n\t{\r\n\t\tg_get_display_path(archive,out);\r\n\t\tout.add_string(\"|\");\r\n\t\tout.add_string(file);\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nvoid archive_impl::open(service_ptr_t<file> & p_out,const char * path,t_open_mode mode, abort_callback & p_abort)\r\n{\r\n\tif (mode != open_mode_read) throw exception_io_denied();\r\n\tpfc::string8 archive,file;\r\n\tif (!g_parse_unpack_path(path,archive,file)) throw exception_io_not_found();\r\n\topen_archive(p_out,archive,file,p_abort);\r\n}\r\n\r\n\r\nvoid archive_impl::remove(const char * path,abort_callback & p_abort) {\r\n\tthrow exception_io_denied();\r\n}\r\n\r\nvoid archive_impl::move(const char * src,const char * dst,abort_callback & p_abort) {\r\n\tthrow exception_io_denied();\r\n}\r\n\r\nbool archive_impl::is_remote(const char * src) {\r\n\tpfc::string8 archive,file;\r\n\tif (g_parse_unpack_path(src,archive,file)) return g_is_remote(archive);\r\n\telse throw exception_io_not_found();\r\n}\r\n\r\nbool archive_impl::relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) {\r\n\tpfc::string8 archive,file;\r\n\tif (g_parse_unpack_path(file_path,archive,file))\r\n\t{\r\n\t\tpfc::string8 archive_rel;\r\n\t\tif (g_relative_path_create(archive,playlist_path,archive_rel))\r\n\t\t{\r\n\t\t\tpfc::string8 out_path;\r\n\t\t\tmake_unpack_path(out_path,archive_rel,file);\r\n\t\t\tout.set_string(out_path);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool archive_impl::relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out)\r\n{\r\n\tif (!is_our_path(relative_path)) return false;\r\n\tpfc::string8 archive_rel,file;\r\n\tif (g_parse_unpack_path(relative_path,archive_rel,file))\r\n\t{\r\n\t\tpfc::string8 archive;\r\n\t\tif (g_relative_path_parse(archive_rel,playlist_path,archive))\r\n\t\t{\r\n\t\t\tpfc::string8 out_path;\r\n\t\t\tmake_unpack_path(out_path,archive,file);\r\n\t\t\tout.set_string(out_path);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool archive_impl::g_parse_unpack_path(const char * path,pfc::string8 & archive,pfc::string8 & file)\r\n{\r\n\tpath  = strchr(path,'|');\r\n\tif (!path) return false;\r\n\tint delta = path_unpack_string(archive,path);\r\n\tif (delta<0) return false;\r\n\tpath += delta;\r\n\tfile = path;\r\n\treturn true;\r\n}\r\n\r\nvoid archive_impl::g_make_unpack_path(pfc::string_base & path,const char * archive,const char * file,const char * name)\r\n{\r\n\tpath = \"unpack://\";\r\n\tpath += name;\r\n\tpath_pack_string(path,archive);\r\n\tpath += file;\r\n}\r\n\r\nvoid archive_impl::make_unpack_path(pfc::string_base & path,const char * archive,const char * file) {g_make_unpack_path(path,archive,file,get_archive_type());}\r\n\r\n\r\nFILE * filesystem::streamio_open(const char * path,const char * flags)\r\n{\r\n\tFILE * ret = 0;\r\n\tpfc::string8 temp;\r\n\tg_get_canonical_path(path,temp);\r\n\tif (!strncmp(temp,\"file://\",7))\r\n\t{\r\n\t\tret = _wfopen(pfc::stringcvt::string_wide_from_utf8(path+7),pfc::stringcvt::string_wide_from_utf8(flags));\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n\r\nnamespace {\r\n\r\n\tclass directory_callback_isempty : public directory_callback\r\n\t{\r\n\t\tbool m_isempty;\r\n\tpublic:\r\n\t\tdirectory_callback_isempty() : m_isempty(true) {}\r\n\t\tbool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats)\r\n\t\t{\r\n\t\t\tm_isempty = false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool isempty() {return m_isempty;}\r\n\t};\r\n\r\n\tclass directory_callback_dummy : public directory_callback\r\n\t{\r\n\tpublic:\r\n\t\tbool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) {return false;}\r\n\t};\r\n\r\n}\r\n\r\nbool filesystem::g_is_empty_directory(const char * path,abort_callback & p_abort)\r\n{\r\n\tdirectory_callback_isempty callback;\r\n\ttry {\r\n\t\tg_list_directory(path,callback,p_abort);\r\n\t} catch(exception_io const &) {return false;}\r\n\treturn callback.isempty();\r\n}\r\n\r\nbool filesystem::g_is_valid_directory(const char * path,abort_callback & p_abort) {\r\n\ttry {\r\n\t\tg_list_directory(path,directory_callback_dummy(),p_abort);\r\n\t\treturn true;\r\n\t} catch(exception_io const &) {return false;}\r\n}\r\n\r\nbool directory_callback_impl::on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) {\r\n\tp_abort.check_e();\r\n\tif (is_subdirectory) {\r\n\t\tif (m_recur) {\r\n\t\t\ttry {\r\n\t\t\t\towner->list_directory(url,*this,p_abort);\r\n\t\t\t} catch(exception_io const &) {}\r\n\t\t}\r\n\t} else {\r\n\t\tm_data.add_item(pfc::rcnew_t<t_entry>(url,p_stats));\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nnamespace {\r\n\tclass directory_callback_impl_copy : public directory_callback\r\n\t{\r\n\tpublic:\r\n\t\tdirectory_callback_impl_copy(const char * p_target)\r\n\t\t{\r\n\t\t\tm_target = p_target;\r\n\t\t\tm_target.fix_dir_separator('\\\\');\r\n\t\t}\r\n\r\n\t\tbool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats) {\r\n\t\t\tconst char * fn = url + pfc::scan_filename(url);\r\n\t\t\tt_size truncat = m_target.length();\r\n\t\t\tm_target += fn;\r\n\t\t\tif (is_subdirectory) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tfilesystem::g_create_directory(m_target,p_abort);\r\n\t\t\t\t} catch(exception_io_already_exists) {}\r\n\t\t\t\tm_target += \"\\\\\";\r\n\t\t\t\towner->list_directory(url,*this,p_abort);\r\n\t\t\t} else {\r\n\t\t\t\tfilesystem::g_copy(url,m_target,p_abort);\r\n\t\t\t}\r\n\t\t\tm_target.truncate(truncat);\r\n\t\t\treturn true;\r\n\t\t}\r\n\tprivate:\r\n\t\tpfc::string8_fastalloc m_target;\r\n//\t\tt_io_result m_status;\r\n\t};\r\n}\r\n\r\nvoid filesystem::g_copy_directory(const char * src,const char * dst,abort_callback & p_abort) {\r\n\t//UNTESTED\r\n\tfilesystem::g_list_directory(src,directory_callback_impl_copy(dst),p_abort);\r\n}\r\n\r\nvoid filesystem::g_copy(const char * src,const char * dst,abort_callback & p_abort) {\r\n\tservice_ptr_t<file> r_src,r_dst;\r\n\tt_filesize size;\r\n\r\n\tg_open(r_src,src,open_mode_read,p_abort);\r\n\tsize = r_src->get_size_ex(p_abort);\r\n\tg_open(r_dst,dst,open_mode_write_new,p_abort);\r\n\t\r\n\tif (size > 0) {\r\n\t\ttry {\r\n\t\t\tfile::g_transfer_object(r_src,r_dst,size,p_abort);\r\n\t\t} catch(std::exception) {\r\n\t\t\tr_dst.release();\r\n\t\t\ttry {g_remove(dst,abort_callback_impl());} catch(std::exception) {}\r\n\t\t\tthrow;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid stream_reader::read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tif (read(p_buffer,p_bytes,p_abort) != p_bytes) throw exception_io_data_truncation();\r\n}\r\n\r\nt_filestats file::get_stats(abort_callback & p_abort)\r\n{\r\n\tt_filestats temp;\r\n\ttemp.m_size = get_size(p_abort);\r\n\ttemp.m_timestamp = get_timestamp(p_abort);\r\n\treturn temp;\r\n}\r\n\r\nt_filesize stream_reader::skip(t_filesize p_bytes,abort_callback & p_abort)\r\n{\r\n\tt_uint8 temp[256];\r\n\tt_filesize todo = p_bytes, done = 0;\r\n\twhile(todo > 0) {\r\n\t\tt_size delta,deltadone;\r\n\t\tdelta = sizeof(temp);\r\n\t\tif (delta > todo) delta = (t_size) todo;\r\n\t\tdeltadone = read(temp,delta,p_abort);\r\n\t\tdone += deltadone;\r\n\t\ttodo -= deltadone;\r\n\t\tif (deltadone < delta) break;\r\n\t}\r\n\treturn done;\r\n}\r\n\r\nvoid stream_reader::skip_object(t_filesize p_bytes,abort_callback & p_abort) {\r\n\tif (skip(p_bytes,p_abort) != p_bytes) throw exception_io_data_truncation();\r\n}\r\n\r\nvoid filesystem::g_open_write_new(service_ptr_t<file> & p_out,const char * p_path,abort_callback & p_abort) {\r\n\tg_open(p_out,p_path,open_mode_write_new,p_abort);\r\n}\r\nvoid file::g_transfer_file(const service_ptr_t<file> & p_from,const service_ptr_t<file> & p_to,abort_callback & p_abort) {\r\n\tt_filesize length = p_from->get_size_ex(p_abort);\r\n\tp_from->seek(0,p_abort);\r\n\tp_to->seek(0,p_abort);\r\n\tp_to->set_eof(p_abort);\r\n\tif (length > 0) {\r\n\t\tg_transfer_object(p_from,p_to,length,p_abort);\r\n\t}\r\n}\r\n\r\nvoid filesystem::g_open_temp(service_ptr_t<file> & p_out,abort_callback & p_abort) {\r\n\tg_open(p_out,\"tempfile://\",open_mode_write_new,p_abort);\r\n}\r\n\r\nvoid filesystem::g_open_tempmem(service_ptr_t<file> & p_out,abort_callback & p_abort) {\r\n\tg_open(p_out,\"tempmem://\",open_mode_write_new,p_abort);\r\n}\r\n\r\nvoid archive_impl::list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort) {\r\n\tthrow exception_io_not_found();\r\n}\r\n\r\nvoid archive_impl::create_directory(const char * path,abort_callback &) {\r\n\tthrow exception_io_denied();\r\n}\r\n\r\nvoid filesystem::g_get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) {\r\n\tTRACK_CALL_TEXT(\"filesystem::g_get_stats\");\r\n\tservice_ptr_t<filesystem> fs;\r\n\tif (!g_get_interface(fs,p_path)) throw exception_io_no_handler_for_path();\r\n\treturn fs->get_stats(p_path,p_stats,p_is_writeable,p_abort);\r\n}\r\n\r\nvoid archive_impl::get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) {\r\n\tpfc::string8 archive,file;\r\n\tif (g_parse_unpack_path(p_path,archive,file)) {\r\n\t\tif (g_is_remote(archive)) throw exception_io_object_is_remote();\r\n\t\tp_is_writeable = false;\r\n\t\tp_stats = get_stats_in_archive(archive,file,p_abort);\r\n\t}\r\n\telse throw exception_io_not_found();\r\n}\r\n\r\n\r\nbool file::is_eof(abort_callback & p_abort) {\r\n\tt_filesize position,size;\r\n\tposition = get_position(p_abort);\r\n\tsize = get_size(p_abort);\r\n\tif (size == filesize_invalid) return false;\r\n\treturn position >= size;\r\n}\r\n\r\n\r\nt_filetimestamp foobar2000_io::filetimestamp_from_system_timer()\r\n{\r\n\tt_filetimestamp ret;\r\n\tGetSystemTimeAsFileTime((FILETIME*)&ret);\r\n\treturn ret;\r\n}\r\n\r\nvoid stream_reader::read_string_ex(pfc::string_base & p_out,t_size p_bytes,abort_callback & p_abort) {\r\n\tchar * ptr = p_out.lock_buffer(p_bytes);\r\n\ttry {\r\n\t\tread_object(ptr,p_bytes,p_abort);\r\n\t} catch(...) {\r\n\t\tp_out.unlock_buffer();\r\n\t\tthrow;\r\n\t}\r\n\tp_out.unlock_buffer();\r\n}\r\nvoid stream_reader::read_string(pfc::string_base & p_out,abort_callback & p_abort)\r\n{\r\n\tt_uint32 length;\r\n\tread_lendian_t(length,p_abort);\r\n\tread_string_ex(p_out,length,p_abort);\r\n}\r\n\r\nvoid stream_reader::read_string_raw(pfc::string_base & p_out,abort_callback & p_abort) {\r\n\tenum {delta = 256};\r\n\tchar buffer[delta];\r\n\tp_out.reset();\r\n\tfor(;;) {\r\n\t\tt_size delta_done;\r\n\t\tdelta_done = read(buffer,delta,p_abort);\r\n\t\tp_out.add_string(buffer,delta_done);\r\n\t\tif (delta_done < delta) break;\r\n\t}\r\n}\r\n\r\nvoid stream_writer::write_string(const char * p_string,abort_callback & p_abort) {\r\n\tt_uint32 len = pfc::downcast_guarded<t_uint32>(strlen(p_string));\r\n\twrite_lendian_t(len,p_abort);\r\n\twrite_object(p_string,len,p_abort);\r\n}\r\n\r\nvoid stream_writer::write_string_raw(const char * p_string,abort_callback & p_abort) {\r\n\twrite_object(p_string,strlen(p_string),p_abort);\r\n}\r\n\r\nvoid file::truncate(t_uint64 p_position,abort_callback & p_abort) {\r\n\tif (p_position < get_size(p_abort)) resize(p_position,p_abort);\r\n}\r\n\r\n\r\nformat_filetimestamp::format_filetimestamp(t_filetimestamp p_timestamp) {\r\n#ifdef _WIN32\r\n\tSYSTEMTIME st; FILETIME ft;\r\n\tif (FileTimeToLocalFileTime((FILETIME*)&p_timestamp,&ft)) {\r\n\t\tif (FileTimeToSystemTime(&ft,&st)) {\r\n\t\t\tm_buffer \r\n\t\t\t\t<< pfc::format_uint(st.wYear,4) << \"-\" << pfc::format_uint(st.wMonth,2) << \"-\" << pfc::format_uint(st.wDay,2) << \" \" \r\n\t\t\t\t<< pfc::format_uint(st.wHour,2) << \":\" << pfc::format_uint(st.wMinute,2) << \":\" << pfc::format_uint(st.wSecond,2);\r\n\t\t} else m_buffer << \"<invalid timestamp>\";\r\n\t} else m_buffer << \"<invalid timestamp>\";\r\n#else\r\n#error portme\r\n#endif\r\n}\r\n\r\n#ifdef _WIN32\r\nnamespace {\r\n\t//rare/weird win32 errors that didn't make it to the main API\r\n\tPFC_DECLARE_EXCEPTION(exception_io_device_not_ready,\t\texception_io,\"Device not ready\");\r\n\tPFC_DECLARE_EXCEPTION(exception_io_invalid_drive,\t\t\texception_io_not_found,\"Drive not found\");\r\n\tPFC_DECLARE_EXCEPTION(exception_io_win32,\t\t\t\t\texception_io,\"Generic win32 I/O error\");\r\n\tPFC_DECLARE_EXCEPTION(exception_io_buffer_overflow,\t\t\texception_io,\"The file name is too long\");\r\n\r\n\tclass exception_io_win32_ex : public exception_io_win32 {\r\n\tpublic:\r\n\t\texception_io_win32_ex(DWORD p_code) : m_msg(pfc::string_formatter() << \"I/O error (win32 #\" << (t_uint32)p_code << \")\") {}\r\n\t\texception_io_win32_ex(const exception_io_win32_ex & p_other) {*this = p_other;}\r\n\t\tconst char * what() const throw() {return m_msg;}\r\n\tprivate:\r\n\t\tpfc::string8 m_msg;\r\n\t};\r\n}\r\nvoid foobar2000_io::exception_io_from_win32(DWORD p_code) {\r\n\tswitch(p_code) {\r\n\tcase ERROR_ALREADY_EXISTS:\r\n\tcase ERROR_FILE_EXISTS:\r\n\t\tthrow exception_io_already_exists();\r\n\tcase ERROR_NETWORK_ACCESS_DENIED:\r\n\tcase ERROR_ACCESS_DENIED:\r\n\t\tthrow exception_io_denied();\r\n\tcase ERROR_WRITE_PROTECT:\r\n\t\tthrow exception_io_write_protected();\r\n\tcase ERROR_BUSY:\r\n\tcase ERROR_PATH_BUSY:\r\n\tcase ERROR_SHARING_VIOLATION:\r\n\tcase ERROR_LOCK_VIOLATION:\r\n\t\tthrow exception_io_sharing_violation();\r\n\tcase ERROR_HANDLE_DISK_FULL:\r\n\tcase ERROR_DISK_FULL:\r\n\t\tthrow exception_io_device_full();\r\n\tcase ERROR_FILE_NOT_FOUND:\r\n\tcase ERROR_PATH_NOT_FOUND:\r\n\t\tthrow exception_io_not_found();\r\n\tcase ERROR_BROKEN_PIPE:\r\n\tcase ERROR_NO_DATA:\r\n\t\tthrow exception_io_no_data();\r\n\tcase ERROR_NETWORK_UNREACHABLE:\r\n\tcase ERROR_NETNAME_DELETED:\r\n\t\tthrow exception_io_network_not_reachable();\r\n\tcase ERROR_NOT_READY:\r\n\t\tthrow exception_io_device_not_ready();\r\n\tcase ERROR_INVALID_DRIVE:\r\n\t\tthrow exception_io_invalid_drive();\r\n\tcase ERROR_CRC:\r\n\tcase ERROR_FILE_CORRUPT:\r\n\tcase ERROR_DISK_CORRUPT:\r\n\t\tthrow exception_io_file_corrupted();\r\n\tcase ERROR_BUFFER_OVERFLOW:\r\n\t\tthrow exception_io_buffer_overflow();\r\n\tcase ERROR_DISK_CHANGE:\r\n\t\tthrow exception_io_disk_change();\r\n\tdefault:\r\n\t\tthrow exception_io_win32_ex(p_code);\r\n\t}\r\n}\r\n#endif\r\n\r\nt_filesize file::get_size_ex(abort_callback & p_abort) {\r\n\tt_filesize temp = get_size(p_abort);\r\n\tif (temp == filesize_invalid) throw exception_io_no_length();\r\n\treturn temp;\r\n}\r\n\r\nvoid file::ensure_local() {\r\n\tif (is_remote()) throw exception_io_object_is_remote();\r\n}\r\n\r\nvoid file::ensure_seekable() {\r\n\tif (!can_seek()) throw exception_io_object_not_seekable();\r\n}\r\n\r\nbool filesystem::g_is_recognized_path(const char * p_path) {\r\n\treturn g_get_interface(service_ptr_t<filesystem>(),p_path);\r\n}\r\n\r\nt_filesize file::get_remaining(abort_callback & p_abort) {\r\n\tt_filesize length = get_size_ex(p_abort);\r\n\tt_filesize position = get_position(p_abort);\r\n\tpfc::dynamic_assert(position <= length);\r\n\treturn length - position;\r\n}\r\n\r\n\r\nt_filesize file::g_transfer(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort) {\r\n\treturn g_transfer(pfc::safe_cast<stream_reader*>(p_src.get_ptr()),pfc::safe_cast<stream_writer*>(p_dst.get_ptr()),p_bytes,p_abort);\r\n}\r\n\r\nvoid file::g_transfer_object(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort) {\r\n\tif (p_bytes > 1024) /* don't bother on small objects */ \r\n\t{\r\n\t\tt_filesize oldsize = p_dst->get_size(p_abort);\r\n\t\tif (oldsize != filesize_invalid) {\r\n\t\t\tt_filesize newpos = p_dst->get_position(p_abort) + p_bytes;\r\n\t\t\tif (newpos > oldsize) p_dst->resize(newpos ,p_abort);\r\n\t\t}\r\n\t}\r\n\tg_transfer_object(pfc::safe_cast<stream_reader*>(p_src.get_ptr()),pfc::safe_cast<stream_writer*>(p_dst.get_ptr()),p_bytes,p_abort);\r\n}\r\n\r\n\r\nvoid foobar2000_io::generate_temp_location_for_file(pfc::string_base & p_out, const char * p_origpath,const char * p_extension,const char * p_magic) {\r\n\thasher_md5_result hash;\r\n\t{\r\n\t\tstatic_api_ptr_t<hasher_md5> hasher;\r\n\t\thasher_md5_state state;\r\n\t\thasher->initialize(state);\r\n\t\thasher->process(state,p_origpath,strlen(p_origpath));\r\n\t\thasher->process(state,p_extension,strlen(p_extension));\r\n\t\thasher->process(state,p_magic,strlen(p_magic));\r\n\t\thash = hasher->get_result(state);\r\n\t}\r\n\r\n\tp_out = p_origpath;\r\n\tp_out.truncate(p_out.scan_filename());\r\n\tp_out += \"temp-\";\r\n\tp_out += pfc::format_hexdump(hash.m_data,sizeof(hash.m_data),\"\");\r\n\tp_out += \".\";\r\n\tp_out += p_extension;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/filesystem.h",
    "content": "#ifndef _FOOBAR2000_SDK_FILESYSTEM_H_\r\n#define _FOOBAR2000_SDK_FILESYSTEM_H_\r\n\r\nclass playlist_loader_callback;\r\nclass file_info;\r\n\r\n//! Contains various I/O related structures and interfaces.\r\n\r\nnamespace foobar2000_io\r\n{\r\n\t//! Type used for file size related variables.\r\n\ttypedef t_uint64 t_filesize;\r\n\t//! Type used for file size related variables when signed value is needed.\r\n\ttypedef t_int64 t_sfilesize;\r\n\t//! Type used for file timestamp related variables. 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601; 0 for invalid/unknown time.\r\n\ttypedef t_uint64 t_filetimestamp;\r\n\t//! Invalid/unknown file timestamp constant. Also see: t_filetimestamp.\r\n\tconst t_filetimestamp filetimestamp_invalid = 0;\r\n\t//! Invalid/unknown file size constant. Also see: t_filesize.\r\n\tconst t_filesize filesize_invalid = (t_filesize)(~0);\r\n\r\n\t//! Generic I/O error. Root class for I/O failure exception. See relevant default message for description of each derived exception class.\r\n\tPFC_DECLARE_EXCEPTION(exception_io,\t\t\t\t\t\tpfc::exception,\"I/O error\");\r\n\t//! Object not found.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_not_found,\t\t\texception_io,\"Object not found\");\r\n\t//! Access denied.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_denied,\t\t\t\texception_io,\"Access denied\");\r\n\t//! Unsupported format or corrupted file (unexpected data encountered).\r\n\tPFC_DECLARE_EXCEPTION(exception_io_data,\t\t\t\texception_io,\"Unsupported format or corrupted file\");\r\n\t//! Unsupported format or corrupted file (truncation encountered).\r\n\tPFC_DECLARE_EXCEPTION(exception_io_data_truncation,\t\texception_io_data,\"Unsupported format or corrupted file\");\r\n\t//! Unsupported format (a subclass of \"unsupported format or corrupted file\" exception).\r\n\tPFC_DECLARE_EXCEPTION(exception_io_unsupported_format,\texception_io_data,\"Unsupported file format\");\r\n\t//! Object is remote, while specific operation is supported only for local objects.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_object_is_remote,\texception_io,\"This operation is not supported on remote objects\");\r\n\t//! Sharing violation.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_sharing_violation,\texception_io,\"Sharing violation\");\r\n\t//! Device full.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_device_full,\t\t\texception_io,\"Device full\");\r\n\t//! Attempt to seek outside valid range.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_seek_out_of_range,\texception_io,\"Seek offset out of range\");\r\n\t//! This operation requires a seekable object.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_object_not_seekable,\texception_io,\"Object is not seekable\");\r\n\t//! This operation requires an object with known length.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_no_length,\t\t\texception_io,\"Length of object is unknown\");\r\n\t//! Invalid path.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_no_handler_for_path,\texception_io,\"Invalid path\");\r\n\t//! Object already exists.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_already_exists,\t\texception_io,\"Object already exists\");\r\n\t//! Pipe error.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_no_data,\t\t\t\texception_io,\"The process receiving or sending data has terminated\");\r\n\t//! Network not reachable.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_network_not_reachable,exception_io,\"Network not reachable\");\r\n\t//! Media is write protected.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_write_protected,\t\texception_io_denied,\"The media is write protected\");\r\n\t//! File is corrupted. This indicates filesystem call failure, not actual invalid data being read by the app.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_file_corrupted,\t\texception_io,\"The file is corrupted\");\r\n\t//! The disc required for requested operation is not available.\r\n\tPFC_DECLARE_EXCEPTION(exception_io_disk_change,\t\t\texception_io,\"Disc not available\");\r\n\r\n\t//! Stores file stats (size and timestamp).\r\n\tstruct t_filestats {\r\n\t\t//! Size of the file.\r\n\t\tt_filesize m_size;\r\n\t\t//! Time of last file modification.\r\n\t\tt_filetimestamp m_timestamp;\r\n\r\n\t\tinline bool operator==(const t_filestats & param) const {return m_size == param.m_size && m_timestamp == param.m_timestamp;}\r\n\t\tinline bool operator!=(const t_filestats & param) const {return m_size != param.m_size || m_timestamp != param.m_timestamp;}\r\n\t};\r\n\r\n\t//! Invalid/unknown file stats constant. See: t_filestats.\r\n\tstatic const t_filestats filestats_invalid = {filesize_invalid,filetimestamp_invalid};\r\n\r\n#ifdef _WIN32\r\n\tvoid exception_io_from_win32(DWORD p_code);\r\n#endif\r\n\r\n\t//! Generic interface to read data from a nonseekable stream. Also see: stream_writer, file.\t\\n\r\n\t//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.\r\n\tclass NOVTABLE stream_reader {\r\n\tpublic:\r\n\t\t//! Attempts to reads specified number of bytes from the stream.\r\n\t\t//! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated.\r\n\t\t//! @param p_bytes Number of bytes to read.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\t//! @returns Number of bytes actually read. May be less than requested when EOF was reached.\r\n\t\tvirtual t_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0;\r\n\t\t//! Reads specified number of bytes from the stream. If requested amount of bytes can't be read (e.g. EOF), throws exception_io_data_truncation.\r\n\t\t//! @param p_buffer Receives data being read. Must have at least p_bytes bytes of space allocated.\r\n\t\t//! @param p_bytes Number of bytes to read.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void read_object(void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\t\t//! Attempts to skip specified number of bytes in the stream.\r\n\t\t//! @param p_bytes Number of bytes to skip.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\t//! @returns Number of bytes actually skipped, May be less than requested when EOF was reached.\r\n\t\tvirtual t_filesize skip(t_filesize p_bytes,abort_callback & p_abort);\r\n\t\t//! Skips specified number of bytes in the stream. If requested amount of bytes can't be skipped (e.g. EOF), throws exception_io_data_truncation.\r\n\t\t//! @param p_bytes Number of bytes to skip.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void skip_object(t_filesize p_bytes,abort_callback & p_abort);\r\n\r\n\t\t//! Helper template built around read_object. Reads single raw object from the stream.\r\n\t\t//! @param p_object Receives object read from the stream on success.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void read_object_t(T& p_object,abort_callback & p_abort) {pfc::assert_raw_type<T>(); read_object(&p_object,sizeof(p_object),p_abort);}\r\n\t\t//! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses little endian order.\r\n\t\t//! @param p_object Receives object read from the stream on success.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void read_lendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_le_to_native_t(p_object);}\r\n\t\t//! Helper template built around read_object. Reads single raw object from the stream; corrects byte order assuming stream uses big endian order.\r\n\t\t//! @param p_object Receives object read from the stream on success.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void read_bendian_t(T& p_object,abort_callback & p_abort) {read_object_t(p_object,p_abort); byte_order::order_be_to_native_t(p_object);}\r\n\r\n\t\t//! Helper function; reads string (with 32-bit header indicating length in bytes followed by UTF-8 encoded data without null terminator).\r\n\t\tvoid read_string(pfc::string_base & p_out,abort_callback & p_abort);\r\n\t\t//! Helper function; alternate way of storing strings; assumes string takes space up to end of stream.\r\n\t\tvoid read_string_raw(pfc::string_base & p_out,abort_callback & p_abort);\r\n\r\n\t\t//! Helper function; reads string of specified length from the stream.\r\n\t\tvoid read_string_ex(pfc::string_base & p_out,t_size p_bytes,abort_callback & p_abort);\r\n\tprotected:\r\n\t\tstream_reader() {}\r\n\t\t~stream_reader() {}\r\n\t};\r\n\r\n\r\n\t//! Generic interface to write data to a nonseekable stream. Also see: stream_reader, file.\t\\n\r\n\t//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.\r\n\tclass NOVTABLE stream_writer {\r\n\tpublic:\r\n\t\t//! Writes specified number of bytes from specified buffer to the stream.\r\n\t\t//! @param p_buffer Buffer with data to write. Must contain at least p_bytes bytes.\r\n\t\t//! @param p_bytes Number of bytes to write.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0;\r\n\t\t\r\n\t\t//! Helper. Same as write(), provided for consistency.\r\n\t\tinline void write_object(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {write(p_buffer,p_bytes,p_abort);}\r\n\r\n\t\t//! Helper template. Writes single raw object to the stream.\r\n\t\t//! @param p_object Object to write.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void write_object_t(const T & p_object, abort_callback & p_abort) {pfc::assert_raw_type<T>(); write_object(&p_object,sizeof(p_object),p_abort);}\r\n\t\t//! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses little endian order.\r\n\t\t//! @param p_object Object to write.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void write_lendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_le_t(temp); write_object_t(temp,p_abort);}\r\n\t\t//! Helper template. Writes single raw object to the stream; corrects byte order assuming stream uses big endian order.\r\n\t\t//! @param p_object Object to write.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\ttemplate<typename T> inline void write_bendian_t(const T & p_object, abort_callback & p_abort) {T temp = p_object; byte_order::order_native_to_be_t(temp); write_object_t(temp,p_abort);}\r\n\r\n\t\t//! Helper function; writes string (with 32-bit header indicating length in bytes followed by UTF-8 encoded data without null terminator).\r\n\t\tvoid write_string(const char * p_string,abort_callback & p_abort);\r\n\r\n\t\t//! Helper function; writes raw string to the stream, with no length info or null terminators.\r\n\t\tvoid write_string_raw(const char * p_string,abort_callback & p_abort);\r\n\tprotected:\r\n\t\tstream_writer() {}\r\n\t\t~stream_writer() {}\r\n\t};\r\n\r\n\t//! A class providing abstraction for an open file object, with reading/writing/seeking methods. See also: stream_reader, stream_writer (which it inherits read/write methods from). \\n\r\n\t//! Error handling: all methods may throw exception_io or one of derivatives on failure; exception_aborted when abort_callback is signaled.\r\n\tclass NOVTABLE file : public service_base, public stream_reader, public stream_writer {\r\n\tpublic:\r\n\r\n\t\t//! Seeking mode constants. Note: these are purposedly defined to same values as standard C SEEK_* constants\r\n\t\tenum t_seek_mode {\r\n\t\t\t//! Seek relative to beginning of file (same as seeking to absolute offset).\r\n\t\t\tseek_from_beginning = 0,\r\n\t\t\t//! Seek relative to current position.\r\n\t\t\tseek_from_current = 1,\r\n\t\t\t//! Seek relative to end of file.\r\n\t\t\tseek_from_eof = 2,\r\n\t\t};\r\n\r\n\t\t//! Retrieves size of the file.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\t//! @returns File size on success; filesize_invalid if unknown (nonseekable stream etc).\r\n\t\tvirtual t_filesize get_size(abort_callback & p_abort) = 0;\r\n\r\n\r\n\t\t//! Retrieves read/write cursor position in the file. In case of non-seekable stream, this should return number of bytes read so far since open/reopen call.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\t//! @returns Read/write cursor position\r\n\t\tvirtual t_filesize get_position(abort_callback & p_abort) = 0;\r\n\r\n\t\t//! Resizes file to specified size in bytes.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void resize(t_filesize p_size,abort_callback & p_abort) = 0;\r\n\r\n\t\t//! Sets read/write cursor position to specific offset.\r\n\t\t//! @param p_position position to seek to.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void seek(t_filesize p_position,abort_callback & p_abort) = 0;\r\n\r\n\t\t\r\n\t\t//! Sets read/write cursor position to specific offset; extended form allowing seeking relative to current position or to end of file.\r\n\t\t//! @param p_position Position to seek to; interpretation of this value depends on p_mode parameter.\r\n\t\t//! @param p_mode Seeking mode; see t_seek_mode enum values for further description.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void seek_ex(t_sfilesize p_position,t_seek_mode p_mode,abort_callback & p_abort);\r\n\r\n\t\t//! Returns whether the file is seekable or not. If can_seek() returns false, all seek() or seek_ex() calls will fail; reopen() is still usable on nonseekable streams.\r\n\t\tvirtual bool can_seek() = 0;\r\n\r\n\t\t//! Retrieves mime type of the file.\r\n\t\t//! @param p_out Receives content type string on success.\r\n\t\tvirtual bool get_content_type(pfc::string_base & p_out) = 0;\r\n\r\n\t\t//! Hint, returns whether the file is already fully buffered into memory.\r\n\t\tvirtual bool is_in_memory() {return false;}\r\n\r\n\t\t//! Optional, called by owner thread before sleeping.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void on_idle(abort_callback & p_abort) {}\r\n\r\n\t\t//! Retrieves last modification time of the file.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\t//! @returns Last modification time o fthe file; filetimestamp_invalid if N/A.\r\n\t\tvirtual t_filetimestamp get_timestamp(abort_callback & p_abort) {return filetimestamp_invalid;}\r\n\r\n\t\t//! Resets non-seekable stream, or seeks to zero on seekable file.\r\n\t\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t\tvirtual void reopen(abort_callback & p_abort) = 0;\r\n\t\t\r\n\t\t//! Indicates whether the file is a remote resource and non-sequential access may be slowed down by lag. This is typically returns to true on non-seekable sources but may also return true on seekable sources indicating that seeking is supported but will be relatively slow.\r\n\t\tvirtual bool is_remote() = 0;\r\n\t\t\r\n\t\t//! Retrieves file stats structure. Usese get_size() and get_timestamp().\r\n\t\tt_filestats get_stats(abort_callback & p_abort);\r\n\r\n\t\t//! Returns whether read/write cursor position is at the end of file.\r\n\t\tbool is_eof(abort_callback & p_abort);\r\n\r\n\t\t//! Truncates file to specified size (while preserving read/write cursor position if possible); uses set_eof().\r\n\t\tvoid truncate(t_filesize p_position,abort_callback & p_abort);\r\n\r\n\t\t//! Truncates the file at current read/write cursor position.\r\n\t\tvoid set_eof(abort_callback & p_abort) {resize(get_position(p_abort),p_abort);}\r\n\r\n\r\n\t\t//! Helper; retrieves size of the file. If size is not available (get_size() returns filesize_invalid), throws exception_io_no_length.\r\n\t\tt_filesize get_size_ex(abort_callback & p_abort);\r\n\r\n\t\t//! Helper; retrieves amount of bytes between read/write cursor position and end of file. Fails when length can't be determined.\r\n\t\tt_filesize get_remaining(abort_callback & p_abort);\r\n\r\n\t\t//! Helper; throws exception_io_object_not_seekable if file is not seekable.\r\n\t\tvoid ensure_seekable();\r\n\r\n\t\t//! Helper; throws exception_io_object_is_remote if the file is remote.\r\n\t\tvoid ensure_local();\r\n\r\n\t\t//! Helper; transfers specified number of bytes between streams.\r\n\t\t//! @returns number of bytes actually transferred. May be less than requested if e.g. EOF is reached.\r\n\t\tstatic t_filesize g_transfer(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort);\r\n\t\t//! Helper; transfers specified number of bytes between streams. Throws exception if requested number of bytes could not be read (EOF).\r\n\t\tstatic void g_transfer_object(stream_reader * src,stream_writer * dst,t_filesize bytes,abort_callback & p_abort);\r\n\t\t//! Helper; transfers entire file content from one file to another, erasing previous content.\r\n\t\tstatic void g_transfer_file(const service_ptr_t<file> & p_from,const service_ptr_t<file> & p_to,abort_callback & p_abort);\r\n\r\n\t\t//! Helper; improved performance over g_transfer on streams (avoids disk fragmentation when transferring large blocks).\r\n\t\tstatic t_filesize g_transfer(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort);\r\n\t\t//! Helper; improved performance over g_transfer_file on streams (avoids disk fragmentation when transferring large blocks).\r\n\t\tstatic void g_transfer_object(service_ptr_t<file> p_src,service_ptr_t<file> p_dst,t_filesize p_bytes,abort_callback & p_abort);\r\n\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE(file,service_base);\r\n\t};\r\n\r\n\t//! Special hack for shoutcast metadata nonsense handling. Documentme.\r\n\tclass file_dynamicinfo : public file {\r\n\tpublic:\r\n\t\t//! Retrieves \"static\" info that doesn't change in the middle of stream, such as station names etc. Returns true on success; false when static info is not available.\r\n\t\tvirtual bool get_static_info(class file_info & p_out) = 0;\r\n\t\t//! Returns whether dynamic info is available on this stream or not.\r\n\t\tvirtual bool is_dynamic_info_enabled()=0;\r\n\t\t//! Retrieves dynamic stream info (e.g. online stream track titles). Returns true on success, false when info has not changed since last call.\r\n\t\tvirtual bool get_dynamic_info(class file_info & p_out) = 0;\r\n\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE(file_dynamicinfo,file);\r\n\t};\r\n\r\n\t//! Implementation helper - contains dummy implementations of methods that modify the file\r\n\ttemplate<typename t_base> class file_readonly_t : public t_base {\r\n\tpublic:\r\n\t\tvoid resize(t_filesize p_size,abort_callback & p_abort) {throw exception_io_denied();}\r\n\t\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_denied();}\r\n\t};\r\n\ttypedef file_readonly_t<file> file_readonly;\r\n\r\n\tclass filesystem;\r\n\r\n\tclass NOVTABLE directory_callback {\r\n\tpublic:\r\n\t\t//! @returns true to continue enumeration, false to abort.\r\n\t\tvirtual bool on_entry(filesystem * p_owner,abort_callback & p_abort,const char * p_url,bool p_is_subdirectory,const t_filestats & p_stats)=0;\r\n\t};\r\n\r\n\r\n\t//! Entrypoint service for all filesystem operations.\\n\r\n\t//! Implementation: standard implementations for local filesystem etc are provided by core.\\n\r\n\t//! Instantiation: use static helper functions rather than calling filesystem interface methods directly, e.g. filesystem::g_open() to open a file.\r\n\tclass NOVTABLE filesystem : public service_base {\r\n\tpublic:\r\n\t\t//! Enumeration specifying how to open a file. See: filesystem::open(), filesystem::g_open().\r\n\t\tenum t_open_mode {\r\n\t\t\t//! Opens an existing file for reading; if the file does not exist, the operation will fail.\r\n\t\t\topen_mode_read,\r\n\t\t\t//! Opens an existing file for writing; if the file does not exist, the operation will fail.\r\n\t\t\topen_mode_write_existing,\r\n\t\t\t//! Opens a new file for writing; if the file exists, its contents will be wiped.\r\n\t\t\topen_mode_write_new,\r\n\t\t};\r\n\r\n\t\tvirtual bool get_canonical_path(const char * p_path,pfc::string_base & p_out)=0;\r\n\t\tvirtual bool is_our_path(const char * p_path)=0;\r\n\t\tvirtual bool get_display_path(const char * p_path,pfc::string_base & p_out)=0;\r\n\r\n\t\tvirtual void open(service_ptr_t<file> & p_out,const char * p_path, t_open_mode p_mode,abort_callback & p_abort)=0;\r\n\t\tvirtual void remove(const char * p_path,abort_callback & p_abort)=0;\r\n\t\tvirtual void move(const char * p_src,const char * p_dst,abort_callback & p_abort)=0;\r\n\t\t//! Queries whether a file at specified path belonging to this filesystem is a remove object or not.\r\n\t\tvirtual bool is_remote(const char * p_src) = 0;\r\n\r\n\t\t//! Retrieves stats of a file at specified path.\r\n\t\tvirtual void get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort) = 0;\r\n\t\t\r\n\t\tvirtual bool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out) {return false;}\r\n\t\tvirtual bool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out) {return false;}\r\n\r\n\t\t//! Creates a directory.\r\n\t\tvirtual void create_directory(const char * p_path,abort_callback & p_abort) = 0;\r\n\r\n\t\tvirtual void list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort)=0;\r\n\r\n\t\t//! Hint; returns whether this filesystem supports mime types.\r\n\t\tvirtual bool supports_content_types() = 0;\r\n\r\n\t\tstatic void g_get_canonical_path(const char * path,pfc::string_base & out);\r\n\t\tstatic void g_get_display_path(const char * path,pfc::string_base & out);\r\n\r\n\t\tstatic bool g_get_interface(service_ptr_t<filesystem> & p_out,const char * path);//path is AFTER get_canonical_path\r\n\t\tstatic bool g_is_remote(const char * p_path);//path is AFTER get_canonical_path\r\n\t\tstatic bool g_is_remote_safe(const char * p_path);//path is AFTER get_canonical_path\r\n\t\tstatic bool g_is_remote_or_unrecognized(const char * p_path);\r\n\t\tstatic bool g_is_recognized_path(const char * p_path);\r\n\t\t\r\n\t\t//! Opens file at specified path, with specified access privileges.\r\n\t\tstatic void g_open(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,abort_callback & p_abort);\r\n\t\t//! Attempts to open file at specified path; if the operation fails with sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.\r\n\t\tstatic void g_open_timeout(service_ptr_t<file> & p_out,const char * p_path,t_open_mode p_mode,double p_timeout,abort_callback & p_abort);\r\n\t\tstatic void g_open_write_new(service_ptr_t<file> & p_out,const char * p_path,abort_callback & p_abort);\r\n\t\tstatic void g_open_read(service_ptr_t<file> & p_out,const char * path,abort_callback & p_abort) {return g_open(p_out,path,open_mode_read,p_abort);}\r\n\t\tstatic void g_open_precache(service_ptr_t<file> & p_out,const char * path,abort_callback & p_abort);//open only for precaching data (eg. will fail on http etc)\r\n\t\tstatic bool g_exists(const char * p_path,abort_callback & p_abort);\r\n\t\tstatic bool g_exists_writeable(const char * p_path,abort_callback & p_abort);\r\n\t\t//! Removes file at specified path.\r\n\t\tstatic void g_remove(const char * p_path,abort_callback & p_abort);\r\n\t\t//! Attempts to remove file at specified path; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.\r\n\t\tstatic void g_remove_timeout(const char * p_path,double p_timeout,abort_callback & p_abort);\r\n\t\t//! Moves file from one path to another.\r\n\t\tstatic void g_move(const char * p_src,const char * p_dst,abort_callback & p_abort);\r\n\t\t//! Attempts to move file from one path to another; if the operation fails with a sharing violation error, keeps retrying (with short sleep period between retries) for specified amount of time.\r\n\t\tstatic void g_move_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort);\r\n\r\n\t\tstatic void g_copy(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path\r\n\t\tstatic void g_copy_timeout(const char * p_src,const char * p_dst,double p_timeout,abort_callback & p_abort);//needs canonical path\r\n\t\tstatic void g_copy_directory(const char * p_src,const char * p_dst,abort_callback & p_abort);//needs canonical path\r\n\t\tstatic void g_get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort);\r\n\t\tstatic bool g_relative_path_create(const char * p_file_path,const char * p_playlist_path,pfc::string_base & out);\r\n\t\tstatic bool g_relative_path_parse(const char * p_relative_path,const char * p_playlist_path,pfc::string_base & out);\r\n\t\t\r\n\t\tstatic void g_create_directory(const char * p_path,abort_callback & p_abort);\r\n\r\n\t\t//! If for some bloody reason you ever need stream io compatibility, use this, INSTEAD of calling fopen() on the path string you've got; will only work with file:// (and not with http://, unpack:// or whatever)\r\n\t\tstatic FILE * streamio_open(const char * p_path,const char * p_flags); \r\n\r\n\t\tstatic void g_open_temp(service_ptr_t<file> & p_out,abort_callback & p_abort);\r\n\t\tstatic void g_open_tempmem(service_ptr_t<file> & p_out,abort_callback & p_abort);\r\n\r\n\t\tstatic void g_list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort);// path must be canonical\r\n\r\n\t\tstatic bool g_is_valid_directory(const char * path,abort_callback & p_abort);\r\n\t\tstatic bool g_is_empty_directory(const char * path,abort_callback & p_abort);\r\n\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(filesystem);\r\n\t};\r\n\r\n\tclass directory_callback_impl : public directory_callback\r\n\t{\r\n\t\tstruct t_entry\r\n\t\t{\r\n\t\t\tpfc::string_simple m_path;\r\n\t\t\tt_filestats m_stats;\r\n\t\t\tt_entry(const char * p_path, const t_filestats & p_stats) : m_path(p_path), m_stats(p_stats) {}\r\n\t\t};\r\n\r\n\r\n\t\tpfc::list_t<pfc::rcptr_t<t_entry> > m_data;\r\n\t\tbool m_recur;\r\n\r\n\t\tstatic int sortfunc(const pfc::rcptr_const_t<t_entry> & p1, const pfc::rcptr_const_t<t_entry> & p2) {return stricmp_utf8(p1->m_path,p2->m_path);}\r\n\tpublic:\r\n\t\tbool on_entry(filesystem * owner,abort_callback & p_abort,const char * url,bool is_subdirectory,const t_filestats & p_stats);\r\n\r\n\t\tdirectory_callback_impl(bool p_recur) : m_recur(p_recur) {}\r\n\t\tt_size get_count() {return m_data.get_count();}\r\n\t\tconst char * operator[](t_size n) const {return m_data[n]->m_path;}\r\n\t\tconst char * get_item(t_size n) const {return m_data[n]->m_path;}\r\n\t\tconst t_filestats & get_item_stats(t_size n) const {return m_data[n]->m_stats;}\r\n\t\tvoid sort() {m_data.sort_t(sortfunc);}\r\n\t};\r\n\r\n\tclass archive;\r\n\r\n\tclass NOVTABLE archive_callback : public abort_callback {\r\n\tpublic:\r\n\t\tvirtual bool on_entry(archive * owner,const char * url,const t_filestats & p_stats,const service_ptr_t<file> & p_reader) = 0;\r\n\t};\r\n\r\n\t//! Interface for archive reader services. When implementing, derive from archive_impl rather than from deriving from archive directly.\r\n\tclass NOVTABLE archive : public filesystem {\r\n\tpublic:\r\n\t\tvirtual void archive_list(const char * p_path,const service_ptr_t<file> & p_reader,archive_callback & p_callback,bool p_want_readers) = 0;\r\n\t\t\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE(archive,filesystem);\r\n\t};\r\n\r\n\t//! Root class for archive implementations. Derive from this instead of from archive directly.\r\n\tclass NOVTABLE archive_impl : public archive {\r\n\tprivate:\r\n\t\t//do not override these\r\n\t\tbool get_canonical_path(const char * path,pfc::string_base & out);\r\n\t\tbool is_our_path(const char * path);\r\n\t\tbool get_display_path(const char * path,pfc::string_base & out);\r\n\t\tvoid remove(const char * path,abort_callback & p_abort);\r\n\t\tvoid move(const char * src,const char * dst,abort_callback & p_abort);\r\n\t\tbool is_remote(const char * src);\r\n\t\tbool relative_path_create(const char * file_path,const char * playlist_path,pfc::string_base & out);\r\n\t\tbool relative_path_parse(const char * relative_path,const char * playlist_path,pfc::string_base & out);\r\n\t\tvoid open(service_ptr_t<file> & p_out,const char * path, t_open_mode mode,abort_callback & p_abort);\r\n\t\tvoid create_directory(const char * path,abort_callback &);\r\n\t\tvoid list_directory(const char * p_path,directory_callback & p_out,abort_callback & p_abort);\r\n\t\tvoid get_stats(const char * p_path,t_filestats & p_stats,bool & p_is_writeable,abort_callback & p_abort);\r\n\tprotected:\r\n\t\t//override these\r\n\t\tvirtual const char * get_archive_type()=0;//eg. \"zip\", must be lowercase\r\n\t\tvirtual t_filestats get_stats_in_archive(const char * p_archive,const char * p_file,abort_callback & p_abort) = 0;\r\n\t\tvirtual void open_archive(service_ptr_t<file> & p_out,const char * archive,const char * file, abort_callback & p_abort)=0;//opens for reading\r\n\tpublic:\r\n\t\t//override these\r\n\t\t\r\n\t\tvirtual void archive_list(const char * path,const service_ptr_t<file> & p_reader,archive_callback & p_out,bool p_want_readers)=0;\r\n\t\t//playlist_loader_callback ONLY for on_progress calls\r\n\r\n\r\n\t\tstatic bool g_parse_unpack_path(const char * path,pfc::string8 & archive,pfc::string8 & file);\r\n\t\tstatic void g_make_unpack_path(pfc::string_base & path,const char * archive,const char * file,const char * name);\r\n\t\tvoid make_unpack_path(pfc::string_base & path,const char * archive,const char * file);\r\n\r\n\t\t\r\n\t};\r\n\r\n\ttemplate<typename T>\r\n\tclass archive_factory_t : public service_factory_single_t<T> {};\r\n\r\n\r\n\tt_filetimestamp filetimestamp_from_system_timer();\r\n\r\n\t//! Warning: this formats according to system timezone settings, created strings should be used for display only, never for storage.\r\n\tclass format_filetimestamp {\r\n\tpublic:\r\n\t\tformat_filetimestamp(t_filetimestamp p_timestamp);\r\n\t\toperator const char*() const {return m_buffer;}\r\n\t\tconst char * get_ptr() const {return m_buffer;}\r\n\tprivate:\r\n\t\tpfc::string_fixed_t<32> m_buffer;\r\n\t};\r\n\r\n\tvoid generate_temp_location_for_file(pfc::string_base & p_out, const char * p_origpath,const char * p_extension,const char * p_magic);\r\n}\r\n\r\nusing namespace foobar2000_io;\r\n\r\n#include \"filesystem_helper.h\"\r\n\r\n#endif//_FOOBAR2000_SDK_FILESYSTEM_H_\r\n\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/filesystem_helper.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid stream_writer_chunk::write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tt_size remaining = p_bytes, written = 0;\r\n\twhile(remaining > 0) {\r\n\t\tt_size delta = sizeof(m_buffer) - m_buffer_state;\r\n\t\tif (delta > remaining) delta = remaining;\r\n\t\tmemcpy(m_buffer,(const t_uint8*)p_buffer + written,delta);\r\n\t\twritten += delta;\r\n\t\tremaining -= delta;\r\n\r\n\t\tif (m_buffer_state == sizeof(m_buffer)) {\r\n\t\t\tm_writer->write_lendian_t((t_uint8)m_buffer_state,p_abort);\r\n\t\t\tm_writer->write_object(m_buffer,m_buffer_state,p_abort);\r\n\t\t\tm_buffer_state = 0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid stream_writer_chunk::flush(abort_callback & p_abort)\r\n{\r\n\tm_writer->write_lendian_t((t_uint8)m_buffer_state,p_abort);\r\n\tif (m_buffer_state > 0) {\r\n\t\tm_writer->write_object(m_buffer,m_buffer_state,p_abort);\r\n\t\tm_buffer_state = 0;\r\n\t}\r\n}\r\n\t\r\n/*\r\n\tstream_writer * m_writer;\r\n\tunsigned m_buffer_state;\r\n\tunsigned char m_buffer[255];\r\n*/\r\n\r\nt_size stream_reader_chunk::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort)\r\n{\r\n\tt_size todo = p_bytes, done = 0;\r\n\twhile(todo > 0) {\r\n\t\tif (m_buffer_size == m_buffer_state) {\r\n\t\t\tif (m_eof) break;\r\n\t\t\tt_uint8 temp;\r\n\t\t\tm_reader->read_lendian_t(temp,p_abort);\r\n\t\t\tm_buffer_size = temp;\r\n\t\t\tif (temp != sizeof(m_buffer)) m_eof = true;\r\n\t\t\tm_buffer_state = 0;\r\n\t\t\tif (m_buffer_size>0) {\r\n\t\t\t\tm_reader->read_object(m_buffer,m_buffer_size,p_abort);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tt_size delta = m_buffer_size - m_buffer_state;\r\n\t\tif (delta > todo) delta = todo;\r\n\t\tif (delta > 0) {\r\n\t\t\tmemcpy((unsigned char*)p_buffer + done,m_buffer + m_buffer_state,delta);\r\n\t\t\ttodo -= delta;\r\n\t\t\tdone += delta;\r\n\t\t\tm_buffer_state += delta;\r\n\t\t}\r\n\t}\r\n\treturn done;\r\n}\r\n\r\nvoid stream_reader_chunk::flush(abort_callback & p_abort) {\r\n\twhile(!m_eof) {\r\n\t\tp_abort.check_e();\r\n\t\tt_uint8 temp;\r\n\t\tm_reader->read_lendian_t(temp,p_abort);\r\n\t\tm_buffer_size = temp;\r\n\t\tif (temp != sizeof(m_buffer)) m_eof = true;\r\n\t\tm_buffer_state = 0;\r\n\t\tif (m_buffer_size>0) {\r\n\t\t\tm_reader->skip_object(m_buffer_size,p_abort);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n/*\r\n\tstream_reader * m_reader;\r\n\tunsigned m_buffer_state, m_buffer_size;\r\n\tbool m_eof;\r\n\tunsigned char m_buffer[255];\r\n*/\r\n\r\nvoid stream_reader_chunk::g_skip(stream_reader * p_stream,abort_callback & p_abort) {\r\n\tstream_reader_chunk(p_stream).flush(p_abort);\r\n}\r\n\r\nt_size reader_membuffer_base::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\tt_size max = get_buffer_size();\r\n\tif (max < m_offset) throw pfc::exception_bug_check();\r\n\tmax -= m_offset;\r\n\tt_size delta = p_bytes;\r\n\tif (delta > max) delta = max;\r\n\tmemcpy(p_buffer,(char*)get_buffer() + m_offset,delta);\r\n\tm_offset += delta;\r\n\treturn delta;\r\n}\r\n\r\nvoid reader_membuffer_base::seek(t_filesize position,abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\tt_filesize max = get_buffer_size();\r\n\tif (position == filesize_invalid || position > max) throw exception_io_seek_out_of_range();\r\n\tm_offset = (t_size)position;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/filesystem_helper.h",
    "content": "#ifndef _FILESYSTEM_HELPER_H_\r\n#define _FILESYSTEM_HELPER_H_\r\n\r\n//helper\r\nclass file_path_canonical {\r\npublic:\r\n\tfile_path_canonical(const char * src) {filesystem::g_get_canonical_path(src,m_data);}\r\n\toperator const char * () const {return m_data.get_ptr();}\r\n\tconst char * get_ptr() const {return m_data.get_ptr();}\r\n\tt_size get_length() const {return m_data.get_length();}\r\nprivate:\r\n\tpfc::string8 m_data;\r\n};\r\n\r\nclass file_path_display {\r\npublic:\r\n\tfile_path_display(const char * src) {filesystem::g_get_display_path(src,m_data);}\r\n\toperator const char * () const {return m_data.get_ptr();}\r\n\tconst char * get_ptr() const {return m_data.get_ptr();}\r\n\tt_size get_length() const {return m_data.get_length();}\r\nprivate:\r\n\tpfc::string8 m_data;\r\n};\r\n\r\n\r\nclass NOVTABLE reader_membuffer_base : public file_readonly {\r\npublic:\r\n\treader_membuffer_base() : m_offset(0) {}\r\n\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {throw exception_io_sharing_violation();}\r\n\r\n\tt_filesize get_size(abort_callback & p_abort) {return get_buffer_size();}\r\n\tt_filesize get_position(abort_callback & p_abort) {return m_offset;}\r\n\tvoid seek(t_filesize position,abort_callback & p_abort);\r\n\tvoid reopen(abort_callback & p_abort) {seek(0,p_abort);}\r\n\t\r\n\tbool can_seek() {return true;}\r\n\tbool is_in_memory() {return true;}\r\n\t\t\r\nprotected:\r\n\tvirtual const void * get_buffer() = 0;\r\n\tvirtual t_size get_buffer_size() = 0;\r\n\tvirtual t_filetimestamp get_timestamp(abort_callback & p_abort) = 0;\r\n\tvirtual bool get_content_type(pfc::string_base &) {return false;}\r\n\tinline void seek_internal(t_size p_offset) {if (p_offset > get_buffer_size()) throw exception_io_seek_out_of_range(); m_offset = p_offset;}\r\nprivate:\r\n\tt_size m_offset;\r\n};\r\n\r\nclass reader_membuffer_mirror : public reader_membuffer_base\r\n{\r\npublic:\r\n\tt_filetimestamp get_timestamp(abort_callback & p_abort) {return m_timestamp;}\r\n\tbool is_remote() {return m_remote;}\r\n\r\n\t//! Returns false when the object could not be mirrored (too big) or did not need mirroring.\r\n\tstatic bool g_create(service_ptr_t<file> & p_out,const service_ptr_t<file> & p_src,abort_callback & p_abort) {\r\n\t\tservice_ptr_t<reader_membuffer_mirror> ptr = new service_impl_t<reader_membuffer_mirror>();\r\n\t\tif (!ptr->init(p_src,p_abort)) return false;\r\n\t\tp_out = ptr.get_ptr();\r\n\t\treturn true;\r\n\t}\r\n\r\nprivate:\r\n\tconst void * get_buffer() {return m_buffer.get_ptr();}\r\n\tt_size get_buffer_size() {return m_buffer.get_size();}\r\n\r\n\tbool init(const service_ptr_t<file> & p_src,abort_callback & p_abort) {\r\n\t\tif (p_src->is_in_memory()) return false;//already buffered\r\n\t\tm_remote = p_src->is_remote();\r\n\t\t\r\n\t\tt_size size = pfc::downcast_guarded<t_size>(p_src->get_size(p_abort));\r\n\r\n\t\tm_buffer.set_size(size);\r\n\r\n\t\tp_src->reopen(p_abort);\r\n\t\t\r\n\t\tp_src->read_object(m_buffer.get_ptr(),size,p_abort);\r\n\r\n\t\tm_timestamp = p_src->get_timestamp(p_abort);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\tt_filetimestamp m_timestamp;\r\n\tpfc::array_t<char> m_buffer;\r\n\tbool m_remote;\r\n\r\n};\r\n\r\nclass reader_limited : public file_readonly {\r\n\tservice_ptr_t<file> r;\r\n\tt_filesize begin;\r\n\tt_filesize end;\r\n\t\r\npublic:\r\n\treader_limited() {begin=0;end=0;}\r\n\treader_limited(const service_ptr_t<file> & p_r,t_filesize p_begin,t_filesize p_end,abort_callback & p_abort) {\r\n\t\tr = p_r;\r\n\t\tbegin = p_begin;\r\n\t\tend = p_end;\r\n\t\tr->seek(begin,p_abort);\r\n\t}\r\n\r\n\tvoid init(const service_ptr_t<file> & p_r,t_filesize p_begin,t_filesize p_end,abort_callback & p_abort) {\r\n\t\tr = p_r;\r\n\t\tbegin = p_begin;\r\n\t\tend = p_end;\r\n\t\tr->seek(begin,p_abort);\r\n\t}\r\n\r\n\tt_filetimestamp get_timestamp(abort_callback & p_abort) {return r->get_timestamp(p_abort);}\r\n\r\n\tt_size read(void *p_buffer, t_size p_bytes,abort_callback & p_abort) {\r\n\t\tt_filesize pos;\r\n\t\tpos = r->get_position(p_abort);\r\n\t\tif (p_bytes > end - pos) p_bytes = (t_size)(end - pos);\r\n\t\treturn r->read(p_buffer,p_bytes,p_abort);\r\n\t}\r\n\r\n\tt_filesize get_size(abort_callback & p_abort) {return end-begin;}\r\n\r\n\tt_filesize get_position(abort_callback & p_abort) {\r\n\t\treturn r->get_position(p_abort) - begin;\r\n\t}\r\n\r\n\tvoid seek(t_filesize position,abort_callback & p_abort) {\r\n\t\tr->seek(position+begin,p_abort);\r\n\t}\r\n\tbool can_seek() {return r->can_seek();}\r\n\tbool is_remote() {return r->is_remote();}\r\n\t\r\n\tbool get_content_type(pfc::string_base &) {return false;}\r\n\r\n\tvoid reopen(abort_callback & p_abort) {seek(0,p_abort);}\r\n};\r\n\r\nclass stream_reader_memblock_ref : public stream_reader\r\n{\r\npublic:\r\n\tstream_reader_memblock_ref(const void * p_data,t_size p_data_size) : m_data((const unsigned char*)p_data), m_data_size(p_data_size), m_pointer(0) {}\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tt_size remaining = m_data_size - m_pointer;\r\n\t\tt_size toread = p_bytes;\r\n\t\tif (toread > remaining) toread = remaining;\r\n\t\tif (toread > 0) {\r\n\t\t\tmemcpy(p_buffer,m_data+m_pointer,toread);\r\n\t\t\tm_pointer += toread;\r\n\t\t}\r\n\r\n\t\treturn toread;\r\n\t}\r\nprivate:\r\n\tconst unsigned char * m_data;\r\n\tt_size m_data_size,m_pointer;\r\n};\r\n\r\ntemplate<class t_storage>\r\nclass stream_writer_buffer_append_ref_t : public stream_writer\r\n{\r\npublic:\r\n\tstream_writer_buffer_append_ref_t(t_storage & p_output) : m_output(p_output) {}\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tpfc::static_assert< sizeof(m_output[0]) == 1>();\r\n\t\tt_size base = m_output.get_size();\r\n\t\tif (base + p_bytes < base) throw std::bad_alloc();\r\n\t\tm_output.set_size(base + p_bytes);\r\n\t\tmemcpy( (t_uint8*) m_output.get_ptr() + base, p_buffer, p_bytes );\r\n\t}\r\nprivate:\r\n\tt_storage & m_output;\r\n};\r\n\r\nclass stream_reader_limited_ref : public stream_reader\r\n{\r\npublic:\r\n\tstream_reader_limited_ref(stream_reader * p_reader,t_size p_limit) : m_reader(p_reader), m_remaining(p_limit) {}\r\n\t\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tif (p_bytes > m_remaining) p_bytes = m_remaining;\r\n\r\n\t\tt_size done = m_reader->read(p_buffer,p_bytes,p_abort);\r\n\t\tm_remaining -= done;\r\n\t\treturn done;\r\n\t}\r\n\r\n\tinline t_size get_remaining() const {return m_remaining;}\r\n\r\n\tvoid flush_remaining(abort_callback & p_abort)\r\n\t{\r\n\t\tif (m_remaining > 0) return skip_object(m_remaining,p_abort);\r\n\t}\r\n\r\nprivate:\r\n\tstream_reader * m_reader;\r\n\tt_size m_remaining;\r\n};\r\n\r\nclass stream_writer_chunk_dwordheader : public stream_writer\r\n{\r\npublic:\r\n\tstream_writer_chunk_dwordheader(const service_ptr_t<file> & p_writer) : m_writer(p_writer) {}\r\n\r\n\tvoid initialize(abort_callback & p_abort) {\r\n\t\tm_headerposition = m_writer->get_position(p_abort);\r\n\t\tm_written = 0;\r\n\t\tm_writer->write_lendian_t((t_uint32)0,p_abort);\r\n\t}\r\n\r\n\tvoid finalize(abort_callback & p_abort) {\r\n\t\tt_filesize end_offset;\r\n\t\tend_offset = m_writer->get_position(p_abort);\r\n\t\tm_writer->seek(m_headerposition,p_abort);\r\n\t\tm_writer->write_lendian_t(pfc::downcast_guarded<t_uint32>(m_written),p_abort);\r\n\t\tm_writer->seek(end_offset,p_abort);\r\n\t}\r\n\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tm_writer->write(p_buffer,p_bytes,p_abort);\r\n\t\tm_written += p_bytes;\r\n\t}\r\n\r\nprivate:\r\n\tservice_ptr_t<file> m_writer;\r\n\tt_filesize m_headerposition;\r\n\tt_filesize m_written;\r\n};\r\n\r\nclass stream_writer_chunk : public stream_writer\r\n{\r\npublic:\r\n\tstream_writer_chunk(stream_writer * p_writer) : m_writer(p_writer), m_buffer_state(0) {}\r\n\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\r\n\tvoid flush(abort_callback & p_abort);//must be called after writing before object is destroyed\r\n\t\r\nprivate:\r\n\tstream_writer * m_writer;\r\n\tunsigned m_buffer_state;\r\n\tunsigned char m_buffer[255];\r\n};\r\n\r\nclass stream_reader_chunk : public stream_reader\r\n{\r\npublic:\r\n\tstream_reader_chunk(stream_reader * p_reader) : m_reader(p_reader), m_buffer_state(0), m_buffer_size(0), m_eof(false) {}\r\n\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\r\n\tvoid flush(abort_callback & p_abort);//must be called after reading before object is destroyed\r\n\r\n\tstatic void g_skip(stream_reader * p_stream,abort_callback & p_abort);\r\n\r\nprivate:\r\n\tstream_reader * m_reader;\r\n\tt_size m_buffer_state, m_buffer_size;\r\n\tbool m_eof;\r\n\tunsigned char m_buffer[255];\r\n};\r\n\r\n#endif//_FILESYSTEM_HELPER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/foobar2000.h",
    "content": "#ifndef _FOOBAR2000_H_\r\n#define _FOOBAR2000_H_\r\n\r\n#ifndef UNICODE\r\n#error Only UNICODE environment supported.\r\n#endif\r\n\r\n#include \"../../pfc/pfc.h\"\r\n\r\n#include \"shared.h\"\r\n\r\n#ifndef NOTHROW\r\n#ifdef _MSC_VER\r\n#define NOTHROW __declspec(nothrow)\r\n#else\r\n#define NOTHROW\r\n#endif\r\n#endif\r\n\r\n#define FB2KAPI /*NOTHROW*/\r\n\r\ntypedef const char * pcchar;\r\n\r\n#include \"core_api.h\"\r\n#include \"service.h\"\r\n\r\n#include \"completion_notify.h\"\r\n#include \"abort_callback.h\"\r\n#include \"audio_chunk.h\"\r\n#include \"componentversion.h\"\r\n#include \"preferences_page.h\"\r\n#include \"coreversion.h\"\r\n#include \"filesystem.h\"\r\n#include \"cfg_var.h\"\r\n#include \"mem_block_container.h\"\r\n#include \"audio_postprocessor.h\"\r\n#include \"playable_location.h\"\r\n#include \"file_info.h\"\r\n#include \"file_info_impl.h\"\r\n#include \"metadb_handle.h\"\r\n#include \"metadb.h\"\r\n#include \"console.h\"\r\n#include \"dsp.h\"\r\n#include \"dsp_manager.h\"\r\n#include \"initquit.h\"\r\n#include \"input.h\"\r\n#include \"input_impl.h\"\r\n#include \"menu.h\"\r\n#include \"contextmenu.h\"\r\n#include \"contextmenu_manager.h\"\r\n#include \"menu_helpers.h\"\r\n#include \"modeless_dialog.h\"\r\n#include \"playback_control.h\"\r\n#include \"play_callback.h\"\r\n#include \"playlist.h\"\r\n#include \"playlist_loader.h\"\r\n#include \"replaygain.h\"\r\n#include \"resampler.h\"\r\n#include \"tag_processor.h\"\r\n#include \"titleformat.h\"\r\n#include \"titleformat_config.h\"\r\n#include \"ui.h\"\r\n#include \"unpack.h\"\r\n#include \"vis.h\"\r\n#include \"packet_decoder.h\"\r\n#include \"commandline.h\"\r\n#include \"genrand.h\"\r\n#include \"file_operation_callback.h\"\r\n#include \"library_manager.h\"\r\n#include \"config_io_callback.h\"\r\n#include \"popup_message.h\"\r\n#include \"app_close_blocker.h\"\r\n#include \"config_object.h\"\r\n#include \"config_object_impl.h\"\r\n#include \"threaded_process.h\"\r\n#include \"hasher_md5.h\"\r\n#include \"message_loop.h\"\r\n#include \"input_file_type.h\"\r\n#include \"masstagger_action.h\"\r\n#include \"chapterizer.h\"\r\n#include \"link_resolver.h\"\r\n#include \"main_thread_callback.h\"\r\n#include \"advconfig.h\"\r\n#include \"info_lookup_handler.h\"\r\n#include \"track_property.h\"\r\n\r\n#endif //_FOOBAR2000_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/genrand.h",
    "content": "#ifndef _SDK_GENRAND_H_\r\n#define _SDK_GENRAND_H_\r\n\r\n//! PRNG service. Implemented by the core, do not reimplement.  Use g_create() helper function to instantiate.\r\nclass NOVTABLE genrand_service : public service_base\r\n{\r\npublic:\r\n\t//! Seeds the PRNG with specified value.\r\n\tvirtual void seed(unsigned val) = 0;\r\n\t//! Returns random value N, where 0 <= N < range.\r\n\tvirtual unsigned genrand(unsigned range)=0;\r\n\r\n\tstatic service_ptr_t<genrand_service> g_create() {return standard_api_create_t<genrand_service>();}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(genrand_service);\r\n};\r\n\r\n\r\n#endif //_SDK_GENRAND_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/guids.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n// {4B897EC8-A2F9-478d-A95E-1A2110A40078}\r\nFOOGUIDDECL const GUID hasher_md5::class_guid =\r\n{ 0x4b897ec8, 0xa2f9, 0x478d, { 0xa9, 0x5e, 0x1a, 0x21, 0x10, 0xa4, 0x0, 0x78 } };\r\n\r\n// {74497D81-6158-48ba-9657-386A5520D0FF}\r\nFOOGUIDDECL const GUID config_io_callback::class_guid =\r\n{ 0x74497d81, 0x6158, 0x48ba, { 0x96, 0x57, 0x38, 0x6a, 0x55, 0x20, 0xd0, 0xff } };\r\n\r\n// {10BB3EBD-DDF7-4975-A3CC-23084829453E}\r\nFOOGUIDDECL const GUID componentversion::class_guid =\r\n{ 0x10bb3ebd, 0xddf7, 0x4975, { 0xa3, 0xcc, 0x23, 0x8, 0x48, 0x29, 0x45, 0x3e } };\r\n\r\n// {7255E8D0-3FCF-4781-B93B-D06CB88DFAFA}\r\nFOOGUIDDECL const GUID preferences_page::class_guid =\r\n{ 0x7255e8d0, 0x3fcf, 0x4781, { 0xb9, 0x3b, 0xd0, 0x6c, 0xb8, 0x8d, 0xfa, 0xfa } };\r\n\r\n// {8146A883-F146-401b-BAF6-4FB2E306F2EB}\r\nFOOGUIDDECL const GUID preferences_branch::class_guid =\r\n{ 0x8146a883, 0xf146, 0x401b, { 0xba, 0xf6, 0x4f, 0xb2, 0xe3, 0x6, 0xf2, 0xeb } };\r\n\r\n// {90DF5270-65BB-4dba-BAF5-86BE9E59DC20}\r\nFOOGUIDDECL const GUID console_receiver::class_guid =\r\n{ 0x90df5270, 0x65bb, 0x4dba, { 0xba, 0xf5, 0x86, 0xbe, 0x9e, 0x59, 0xdc, 0x20 } };\r\n\r\n// {0C36A649-9EA0-4f48-B229-0CB2AA9AB6F4}\r\nFOOGUIDDECL const GUID core_version_info::class_guid =\r\n{ 0xc36a649, 0x9ea0, 0x4f48, { 0xb2, 0x29, 0xc, 0xb2, 0xaa, 0x9a, 0xb6, 0xf4 } };\r\n\r\n// {61C4E6E4-C31E-4c89-A759-BF0949DFC528}\r\nFOOGUIDDECL const GUID audio_postprocessor::class_guid =\r\n{ 0x61c4e6e4, 0xc31e, 0x4c89, { 0xa7, 0x59, 0xbf, 0x9, 0x49, 0xdf, 0xc5, 0x28 } };\r\n\r\n// {EE65D408-70D6-40f6-940D-D9F537F1BEF1}\r\nFOOGUIDDECL const GUID dsp_config_manager::class_guid =\r\n{ 0xee65d408, 0x70d6, 0x40f6, { 0x94, 0xd, 0xd9, 0xf5, 0x37, 0xf1, 0xbe, 0xf1 } };\r\n\r\n// {F8F03D26-C2DA-47ed-8748-1DBACBCEA508}\r\nFOOGUIDDECL const GUID dsp_config_callback::class_guid =\r\n{ 0xf8f03d26, 0xc2da, 0x47ed, { 0x87, 0x48, 0x1d, 0xba, 0xcb, 0xce, 0xa5, 0x8 } };\r\n\r\n// {0D048731-8AA8-4704-8AD6-189E24D48C88}\r\nFOOGUIDDECL const GUID dsp_entry::class_guid =\r\n{ 0xd048731, 0x8aa8, 0x4704, { 0x8a, 0xd6, 0x18, 0x9e, 0x24, 0xd4, 0x8c, 0x88 } };\r\n\r\n// {2A42AFEA-940B-455b-AEFF-CFDACAF52AFF}\r\nFOOGUIDDECL const GUID dsp::class_guid =\r\n{ 0x2a42afea, 0x940b, 0x455b, { 0xae, 0xff, 0xcf, 0xda, 0xca, 0xf5, 0x2a, 0xff } };\r\n\r\n// {113773C4-B387-4b48-8BDF-AB58BC6CE538}\r\nFOOGUIDDECL const GUID initquit::class_guid = \r\n{ 0x113773c4, 0xb387, 0x4b48, { 0x8b, 0xdf, 0xab, 0x58, 0xbc, 0x6c, 0xe5, 0x38 } };\r\n\r\n// {4560C877-C41A-4c71-BB75-A7A5BAFC18D8}\r\nFOOGUIDDECL const GUID metadb_display_hook::class_guid = \r\n{ 0x4560c877, 0xc41a, 0x4c71, { 0xbb, 0x75, 0xa7, 0xa5, 0xba, 0xfc, 0x18, 0xd8 } };\r\n\r\n// {609D48C8-C6A6-4784-8BBD-FDD32BF0740E}\r\nFOOGUIDDECL const GUID metadb::class_guid = \r\n{ 0x609d48c8, 0xc6a6, 0x4784, { 0x8b, 0xbd, 0xfd, 0xd3, 0x2b, 0xf0, 0x74, 0xe } };\r\n\r\n// {D5286BB4-FDED-47ef-A623-4C3FF056DEC1}\r\nFOOGUIDDECL const GUID metadb_io_callback::class_guid = \r\n{ 0xd5286bb4, 0xfded, 0x47ef, { 0xa6, 0x23, 0x4c, 0x3f, 0xf0, 0x56, 0xde, 0xc1 } };\r\n\r\n// {1C0802F7-CF24-49ef-B914-8B9866F19779}\r\nFOOGUIDDECL const GUID contextmenu_item::class_guid = \r\n{ 0x1c0802f7, 0xcf24, 0x49ef, { 0xb9, 0x14, 0x8b, 0x98, 0x66, 0xf1, 0x97, 0x79 } };\r\n\r\n// {98B00B13-8C0E-49ff-B17C-5E537D3AE4B7}\r\nFOOGUIDDECL const GUID visualisation_manager::class_guid = \r\n{ 0x98b00b13, 0x8c0e, 0x49ff, { 0xb1, 0x7c, 0x5e, 0x53, 0x7d, 0x3a, 0xe4, 0xb7 } };\r\n\r\n// {4A4B1DD8-82FF-4071-A6E2-BD043F4C251C}\r\nFOOGUIDDECL const GUID visualisation_stream::class_guid = \r\n{ 0x4a4b1dd8, 0x82ff, 0x4071, { 0xa6, 0xe2, 0xbd, 0x4, 0x3f, 0x4c, 0x25, 0x1c } };\r\n\r\n// {015A6C0E-1571-49bd-A367-30B4BD889C34}\r\nFOOGUIDDECL const GUID packet_decoder::class_guid = \r\n{ 0x15a6c0e, 0x1571, 0x49bd, { 0xa3, 0x67, 0x30, 0xb4, 0xbd, 0x88, 0x9c, 0x34 } };\r\n\r\n// {D815032D-AFEB-46c6-8AA3-6FD530A4CE67}\r\nFOOGUIDDECL const GUID packet_decoder_streamparse::class_guid = \r\n{ 0xd815032d, 0xafeb, 0x46c6, { 0x8a, 0xa3, 0x6f, 0xd5, 0x30, 0xa4, 0xce, 0x67 } };\r\n\r\n// {53006A71-C03C-4c38-822F-9A34A5655095}\r\nFOOGUIDDECL const GUID packet_decoder_entry::class_guid = \r\n{ 0x53006a71, 0xc03c, 0x4c38, { 0x82, 0x2f, 0x9a, 0x34, 0xa5, 0x65, 0x50, 0x95 } };\r\n\r\n// {D3BD5F53-A6D6-4346-991F-CF14DFAD2B3A}\r\nFOOGUIDDECL const GUID contextmenu_manager::class_guid = \r\n{ 0xd3bd5f53, 0xa6d6, 0x4346, { 0x99, 0x1f, 0xcf, 0x14, 0xdf, 0xad, 0x2b, 0x3a } };\r\n\r\n// {640E006E-2934-4d6c-8327-4FA9F341ECF2}\r\nFOOGUIDDECL const GUID input_file_type::class_guid = \r\n{ 0x640e006e, 0x2934, 0x4d6c, { 0x83, 0x27, 0x4f, 0xa9, 0xf3, 0x41, 0xec, 0xf2 } };\r\n\r\n// {2DC57FF7-476D-42f5-A05A-60499896134A}\r\nFOOGUIDDECL const GUID ui_control::class_guid = \r\n{ 0x2dc57ff7, 0x476d, 0x42f5, { 0xa0, 0x5a, 0x60, 0x49, 0x98, 0x96, 0x13, 0x4a } };\r\n\r\n// {392B88DE-50FC-43b0-9F03-2D79B071CAF6}\r\nFOOGUIDDECL const GUID ui_status_text_override::class_guid = \r\n{ 0x392b88de, 0x50fc, 0x43b0, { 0x9f, 0x3, 0x2d, 0x79, 0xb0, 0x71, 0xca, 0xf6 } };\r\n\r\n// {52BD7A17-540C-4a97-B812-72BC84EC4FF5}\r\nFOOGUIDDECL const GUID ui_drop_item_callback::class_guid = \r\n{ 0x52bd7a17, 0x540c, 0x4a97, { 0xb8, 0x12, 0x72, 0xbc, 0x84, 0xec, 0x4f, 0xf5 } };\r\n\r\n// {550B3A19-42A4-4c0f-91F2-90550189CBFF}\r\nFOOGUIDDECL const GUID commandline_handler::class_guid = \r\n{ 0x550b3a19, 0x42a4, 0x4c0f, { 0x91, 0xf2, 0x90, 0x55, 0x1, 0x89, 0xcb, 0xff } };\r\n\r\n// {C71B99BD-12C5-48fe-A9C0-469F6FEA88BF}\r\nFOOGUIDDECL const GUID modeless_dialog_manager::class_guid = \r\n{ 0xc71b99bd, 0x12c5, 0x48fe, { 0xa9, 0xc0, 0x46, 0x9f, 0x6f, 0xea, 0x88, 0xbf } };\r\n\r\n// {78BCBFA1-DFB9-487f-AB16-CD82BF90CCF7}\r\nFOOGUIDDECL const GUID play_callback_manager::class_guid = \r\n{ 0x78bcbfa1, 0xdfb9, 0x487f, { 0xab, 0x16, 0xcd, 0x82, 0xbf, 0x90, 0xcc, 0xf7 } };\r\n\r\n// {8E4EED7A-C6B8-49c7-99FE-97E04AAA63A8}\r\nFOOGUIDDECL const GUID play_callback_static::class_guid = \r\n{ 0x8e4eed7a, 0xc6b8, 0x49c7, { 0x99, 0xfe, 0x97, 0xe0, 0x4a, 0xaa, 0x63, 0xa8 } };\r\n\r\n// {BF803668-2977-4c71-B9AB-5C77C338C970}\r\nFOOGUIDDECL const GUID playback_control::class_guid = \r\n{ 0xbf803668, 0x2977, 0x4c71, { 0xb9, 0xab, 0x5c, 0x77, 0xc3, 0x38, 0xc9, 0x70 } };\r\n\r\n// {242D9341-211A-4637-A69F-F6684B52F9D6}\r\nFOOGUIDDECL const GUID playlist_callback_static::class_guid = \r\n{ 0x242d9341, 0x211a, 0x4637, { 0xa6, 0x9f, 0xf6, 0x68, 0x4b, 0x52, 0xf9, 0xd6 } };\r\n\r\n// {95E9F11B-4C99-4d0a-AB9F-367196B10925}\r\nFOOGUIDDECL const GUID playlist_callback_single_static::class_guid = \r\n{ 0x95e9f11b, 0x4c99, 0x4d0a, { 0xab, 0x9f, 0x36, 0x71, 0x96, 0xb1, 0x9, 0x25 } };\r\n\r\n// {88D7EDB1-A850-42a4-BBAB-49E955F4B81F}\r\nFOOGUIDDECL const GUID playlist_lock::class_guid = \r\n{ 0x88d7edb1, 0xa850, 0x42a4, { 0xbb, 0xab, 0x49, 0xe9, 0x55, 0xf4, 0xb8, 0x1f } };\r\n\r\n// {D2E5F92B-3424-4822-AE60-8663E6D26EAB}\r\nFOOGUIDDECL const GUID playlist_loader::class_guid = \r\n{ 0xd2e5f92b, 0x3424, 0x4822, { 0xae, 0x60, 0x86, 0x63, 0xe6, 0xd2, 0x6e, 0xab } };\r\n\r\n// {2FBCE1E5-902E-49e0-B9CF-CE0FBA765348}\r\nFOOGUIDDECL const GUID filesystem::class_guid = \r\n{ 0x2fbce1e5, 0x902e, 0x49e0, { 0xb9, 0xcf, 0xce, 0xf, 0xba, 0x76, 0x53, 0x48 } };\r\n\r\n// {9098AF12-61A3-4caa-8AA9-BB95C2EF8346}\r\nFOOGUIDDECL const GUID unpacker::class_guid = \r\n{ 0x9098af12, 0x61a3, 0x4caa, { 0x8a, 0xa9, 0xbb, 0x95, 0xc2, 0xef, 0x83, 0x46 } };\r\n\r\n// {EC707440-FA3E-4d12-9876-FC369F04D4A4}\r\nFOOGUIDDECL const GUID archive::class_guid = \r\n{ 0xec707440, 0xfa3e, 0x4d12, { 0x98, 0x76, 0xfc, 0x36, 0x9f, 0x4, 0xd4, 0xa4 } };\r\n\r\n// {B2F9FC40-3E55-4b23-A2C9-22BAAD8795B1}\r\nFOOGUIDDECL const GUID file::class_guid = \r\n{ 0xb2f9fc40, 0x3e55, 0x4b23, { 0xa2, 0xc9, 0x22, 0xba, 0xad, 0x87, 0x95, 0xb1 } };\r\n\r\n// {6374340F-82D4-4471-A24B-A754B1398285}\r\nFOOGUIDDECL const GUID file_dynamicinfo::class_guid = \r\n{ 0x6374340f, 0x82d4, 0x4471, { 0xa2, 0x4b, 0xa7, 0x54, 0xb1, 0x39, 0x82, 0x85 } };\r\n\r\n// {A00CB77D-ED72-4031-806B-4E45AF995241}\r\nFOOGUIDDECL const GUID replaygain_manager::class_guid = \r\n{ 0xa00cb77d, 0xed72, 0x4031, { 0x80, 0x6b, 0x4e, 0x45, 0xaf, 0x99, 0x52, 0x41 } };\r\n\r\n// {3FEED4FC-A400-4a30-8E73-F0ECD114D7E8}\r\nFOOGUIDDECL const GUID resampler_entry::class_guid = \r\n{ 0x3feed4fc, 0xa400, 0x4a30, { 0x8e, 0x73, 0xf0, 0xec, 0xd1, 0x14, 0xd7, 0xe8 } };\r\n\r\n// {3F7674AB-044C-4796-8801-6C443C244D88}\r\nFOOGUIDDECL const GUID titleformat_compiler::class_guid = \r\n{ 0x3f7674ab, 0x44c, 0x4796, { 0x88, 0x1, 0x6c, 0x44, 0x3c, 0x24, 0x4d, 0x88 } };\r\n\r\n// {1ADD4DC4-B278-4a0c-A105-2629F4B312F4}\r\nFOOGUIDDECL const GUID user_interface::class_guid = \r\n{ 0x1add4dc4, 0xb278, 0x4a0c, { 0xa1, 0x5, 0x26, 0x29, 0xf4, 0xb3, 0x12, 0xf4 } };\r\n\r\n// {994C0D0E-319E-45f3-92FC-518616E73ADC}\r\nFOOGUIDDECL const GUID contextmenu_item::caller_now_playing =\r\n{ 0x994c0d0e, 0x319e, 0x45f3, { 0x92, 0xfc, 0x51, 0x86, 0x16, 0xe7, 0x3a, 0xdc } };\r\n\r\n// {47502BA1-816D-4a3e-ADE5-A7A9860A67DB}\r\nFOOGUIDDECL const GUID contextmenu_item::caller_playlist =\r\n{ 0x47502ba1, 0x816d, 0x4a3e, { 0xad, 0xe5, 0xa7, 0xa9, 0x86, 0xa, 0x67, 0xdb } };\r\n\r\n// {00000000-0000-0000-0000-000000000000}\r\nFOOGUIDDECL const GUID contextmenu_item::caller_undefined =\r\n{ 0x00000000, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } };\r\n\r\n// {FABEE3E9-8901-4df4-A2D7-B9898D86C39B}\r\nFOOGUIDDECL const GUID contextmenu_item::caller_keyboard_shortcut_list =\r\n{ 0xfabee3e9, 0x8901, 0x4df4, { 0xa2, 0xd7, 0xb9, 0x89, 0x8d, 0x86, 0xc3, 0x9b } };\r\n\r\n// {95DE5842-30F5-4f72-B40C-191663782F80}\r\nFOOGUIDDECL const GUID keyboard_shortcut_manager::class_guid = \r\n{ 0x95de5842, 0x30f5, 0x4f72, { 0xb4, 0xc, 0x19, 0x16, 0x63, 0x78, 0x2f, 0x80 } };\r\n\r\n// {30F95BEB-FDF4-4a75-B597-60CAF93B39C4}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP4 = \r\n{ 0x30f95beb, 0xfdf4, 0x4a75, { 0xb5, 0x97, 0x60, 0xca, 0xf9, 0x3b, 0x39, 0xc4 } };\r\n\r\n// {8F450CB3-A083-4b83-8D85-ADCE5EA6D57F}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP4_ALAC =\r\n{ 0x8f450cb3, 0xa083, 0x4b83, { 0x8d, 0x85, 0xad, 0xce, 0x5e, 0xa6, 0xd5, 0x7f } };\r\n\r\n// {40017871-50A9-48b6-BF60-BD181A227F9B}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP4_AMR =\r\n{ 0x40017871, 0x50a9, 0x48b6, { 0xbf, 0x60, 0xbd, 0x18, 0x1a, 0x22, 0x7f, 0x9b } };\r\n\r\n// {2E729EA0-6BEB-4392-BF24-75C69B60166D}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP4_AMR_WB =\r\n{ 0x2e729ea0, 0x6beb, 0x4392, { 0xbf, 0x24, 0x75, 0xc6, 0x9b, 0x60, 0x16, 0x6d } };\r\n\r\n// {AF5B7CB0-A08E-404a-A3C0-5C5EA1A8A05C}\r\nFOOGUIDDECL const GUID packet_decoder::owner_ADTS =\r\n{ 0xaf5b7cb0, 0xa08e, 0x404a, { 0xa3, 0xc0, 0x5c, 0x5e, 0xa1, 0xa8, 0xa0, 0x5c } };\r\n\r\n// {F72D2EAE-835C-4dfb-97C6-624343EFAFB0}\r\nFOOGUIDDECL const GUID packet_decoder::owner_ADIF =\r\n{ 0xf72d2eae, 0x835c, 0x4dfb, { 0x97, 0xc6, 0x62, 0x43, 0x43, 0xef, 0xaf, 0xb0 } };\r\n\r\n// {5C2DE804-EAEE-4b8e-8C14-9207A2549BBE}\r\nFOOGUIDDECL const GUID packet_decoder::owner_matroska =\r\n{ 0x5c2de804, 0xeaee, 0x4b8e, { 0x8c, 0x14, 0x92, 0x7, 0xa2, 0x54, 0x9b, 0xbe } };\r\n\r\n// {7B741A69-1AC7-440d-A01D-88536DD4DE1C}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP3 = \r\n{ 0x7b741a69, 0x1ac7, 0x440d, { 0xa0, 0x1d, 0x88, 0x53, 0x6d, 0xd4, 0xde, 0x1c } };\r\n\r\n// {17B300A0-3110-4400-A434-C18FBEEABA81}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP2 = \r\n{ 0x17b300a0, 0x3110, 0x4400, { 0xa4, 0x34, 0xc1, 0x8f, 0xbe, 0xea, 0xba, 0x81 } };\r\n\r\n// {1C068E5E-DD65-4639-BF85-78B297C8FFAC}\r\nFOOGUIDDECL const GUID packet_decoder::owner_MP1 = \r\n{ 0x1c068e5e, 0xdd65, 0x4639, { 0xbf, 0x85, 0x78, 0xb2, 0x97, 0xc8, 0xff, 0xac } };\r\n\r\n// {BC73F9FC-0107-480e-BF0E-BE58AF7AF328}\r\nFOOGUIDDECL const GUID packet_decoder::property_samplerate = \r\n{ 0xbc73f9fc, 0x107, 0x480e, { 0xbf, 0xe, 0xbe, 0x58, 0xaf, 0x7a, 0xf3, 0x28 } };\r\n\r\n// {E5D19AAD-931B-48ac-AA6E-95E2C23BEC37}\r\nFOOGUIDDECL const GUID packet_decoder::property_bitspersample = \r\n{ 0xe5d19aad, 0x931b, 0x48ac, { 0xaa, 0x6e, 0x95, 0xe2, 0xc2, 0x3b, 0xec, 0x37 } };\r\n\r\n// {1AFA1145-E774-4c26-91D6-3F5DD61E260E}\r\nFOOGUIDDECL const GUID packet_decoder::property_channels = \r\n{ 0x1afa1145, 0xe774, 0x4c26, { 0x91, 0xd6, 0x3f, 0x5d, 0xd6, 0x1e, 0x26, 0xe } };\r\n\r\n// {29C556DA-065A-4d24-8A11-0F9DBC05A817}\r\nFOOGUIDDECL const GUID packet_decoder::property_byteorder = \r\n{ 0x29c556da, 0x65a, 0x4d24, { 0x8a, 0x11, 0xf, 0x9d, 0xbc, 0x5, 0xa8, 0x17 } };\r\n\r\n// {0759C32F-E78E-4479-B0C0-B653DFA014D8}\r\nFOOGUIDDECL const GUID packet_decoder::property_signed = \r\n{ 0x759c32f, 0xe78e, 0x4479, { 0xb0, 0xc0, 0xb6, 0x53, 0xdf, 0xa0, 0x14, 0xd8 } };\r\n\r\n// {BB31669E-0C30-4c5f-AAF0-20CD49D46058}\r\nFOOGUIDDECL const GUID packet_decoder::property_channelmask = \r\n{ 0xbb31669e, 0xc30, 0x4c5f, { 0xaa, 0xf0, 0x20, 0xcd, 0x49, 0xd4, 0x60, 0x58 } };\r\n\r\n// {6F441057-1D18-4a58-9AC4-8F409CDA7DFD}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_file_properties = \r\n{ 0x6f441057, 0x1d18, 0x4a58, { 0x9a, 0xc4, 0x8f, 0x40, 0x9c, 0xda, 0x7d, 0xfd } };\r\n\r\n// {EFC1E9C8-EEEF-427a-8F42-E5781605846D}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_file_open_directory = \r\n{ 0xefc1e9c8, 0xeeef, 0x427a, { 0x8f, 0x42, 0xe5, 0x78, 0x16, 0x5, 0x84, 0x6d } };\r\n\r\n// {FFE18008-BCA2-4b29-AB88-8816B492C434}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_copy_names = \r\n{ 0xffe18008, 0xbca2, 0x4b29, { 0xab, 0x88, 0x88, 0x16, 0xb4, 0x92, 0xc4, 0x34 } };\r\n\r\n// {44B8F02B-5408-4361-8240-18DEC881B95E}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_send_to_playlist = \r\n{ 0x44b8f02b, 0x5408, 0x4361, { 0x82, 0x40, 0x18, 0xde, 0xc8, 0x81, 0xb9, 0x5e } };\r\n\r\n// {8C3BA2CB-BC4D-4752-8282-C6F9AED75A78}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_reload_info = \r\n{ 0x8c3ba2cb, 0xbc4d, 0x4752, { 0x82, 0x82, 0xc6, 0xf9, 0xae, 0xd7, 0x5a, 0x78 } };\r\n\r\n// {BD045EA4-E5E9-4206-8FF9-12AD9F5DCDE1}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_reload_info_if_changed = \r\n{ 0xbd045ea4, 0xe5e9, 0x4206, { 0x8f, 0xf9, 0x12, 0xad, 0x9f, 0x5d, 0xcd, 0xe1 } };\r\n\r\n// {684D9FBB-4383-44a2-9789-7EE1376209C6}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_rewrite_info = \r\n{ 0x684d9fbb, 0x4383, 0x44a2, { 0x97, 0x89, 0x7e, 0xe1, 0x37, 0x62, 0x9, 0xc6 } };\r\n\r\n// {860179B7-962F-4340-ACAD-0DDAF060A6B8}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_remove_tags = \r\n{ 0x860179b7, 0x962f, 0x4340, { 0xac, 0xad, 0xd, 0xda, 0xf0, 0x60, 0xa6, 0xb8 } };\r\n\r\n// {4DD1E1AD-F481-480c-BC3E-DD9C878EAFC3}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_remove_from_database = \r\n{ 0x4dd1e1ad, 0xf481, 0x480c, { 0xbc, 0x3e, 0xdd, 0x9c, 0x87, 0x8e, 0xaf, 0xc3 } };\r\n\r\n// {A7E7ECB7-1943-4907-83B3-60E92353C7FA}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_convert_run = \r\n{ 0xa7e7ecb7, 0x1943, 0x4907, { 0x83, 0xb3, 0x60, 0xe9, 0x23, 0x53, 0xc7, 0xfa } };\r\n\r\n// {BED4FB6E-C4F2-40dd-B528-1DE1450DDFE9}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_convert_run_withcue = \r\n{ 0xbed4fb6e, 0xc4f2, 0x40dd, { 0xb5, 0x28, 0x1d, 0xe1, 0x45, 0xd, 0xdf, 0xe9 } };\r\n\r\n// {A58AE6EA-A34F-4879-B25C-F31F2CBC4DA9}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_convert_run_singlefile = \r\n{ 0xa58ae6ea, 0xa34f, 0x4879, { 0xb2, 0x5c, 0xf3, 0x1f, 0x2c, 0xbc, 0x4d, 0xa9 } };\r\n\r\n// {A8EFA42D-76CB-42bc-8803-70516567B13D}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_write_cd = \r\n{ 0xa8efa42d, 0x76cb, 0x42bc, { 0x88, 0x3, 0x70, 0x51, 0x65, 0x67, 0xb1, 0x3d } };\r\n\r\n// {487DAED1-02FB-4336-A813-5E90317AB041}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_rg_scan_track = \r\n{ 0x487daed1, 0x2fb, 0x4336, { 0xa8, 0x13, 0x5e, 0x90, 0x31, 0x7a, 0xb0, 0x41 } };\r\n\r\n// {3850F34C-F619-4296-B8A0-26C617B1D16C}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_rg_scan_album = \r\n{ 0x3850f34c, 0xf619, 0x4296, { 0xb8, 0xa0, 0x26, 0xc6, 0x17, 0xb1, 0xd1, 0x6c } };\r\n\r\n// {6A2DBA02-260C-436f-8F41-0190A4298266}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_rg_scan_album_multi = \r\n{ 0x6a2dba02, 0x260c, 0x436f, { 0x8f, 0x41, 0x1, 0x90, 0xa4, 0x29, 0x82, 0x66 } };\r\n\r\n// {54C82A92-5824-4381-8D1B-79FBB1E2ABB8}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_rg_remove = \r\n{ 0x54c82a92, 0x5824, 0x4381, { 0x8d, 0x1b, 0x79, 0xfb, 0xb1, 0xe2, 0xab, 0xb8 } };\r\n\r\n// {69EAA594-13D9-4237-9BD7-11A39FDD1454}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_save_playlist = \r\n{ 0x69eaa594, 0x13d9, 0x4237, { 0x9b, 0xd7, 0x11, 0xa3, 0x9f, 0xdd, 0x14, 0x54 } };\r\n\r\n// {2BEB6836-C657-40ef-BB6E-D5B222AB89CE}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_masstag_edit = \r\n{ 0x2beb6836, 0xc657, 0x40ef, { 0xbb, 0x6e, 0xd5, 0xb2, 0x22, 0xab, 0x89, 0xce } };\r\n\r\n// {A579FF07-5D0B-48ed-A071-B6FCE4385AA9}\r\nFOOGUIDDECL const GUID standard_commands::guid_context_masstag_rename = \r\n{ 0xa579ff07, 0x5d0b, 0x48ed, { 0xa0, 0x71, 0xb6, 0xfc, 0xe4, 0x38, 0x5a, 0xa9 } };\r\n\r\n// {77CFBCD0-98DC-4015-B327-D7142C664806}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_always_on_top = \r\n{ 0x77cfbcd0, 0x98dc, 0x4015, { 0xb3, 0x27, 0xd7, 0x14, 0x2c, 0x66, 0x48, 0x6 } };\r\n\r\n// {11213A01-9F36-4e69-A1BB-7A72F418DE3A}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_preferences = \r\n{ 0x11213a01, 0x9f36, 0x4e69, { 0xa1, 0xbb, 0x7a, 0x72, 0xf4, 0x18, 0xde, 0x3a } };\r\n\r\n// {EDA23441-5D38-4499-A22C-FE0CE0A987D9}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_about = \r\n{ 0xeda23441, 0x5d38, 0x4499, { 0xa2, 0x2c, 0xfe, 0xc, 0xe0, 0xa9, 0x87, 0xd9 } };\r\n\r\n// {6D38C73A-15D8-472c-8E68-6F946B82ECB4}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_exit = \r\n{ 0x6d38c73a, 0x15d8, 0x472c, { 0x8e, 0x68, 0x6f, 0x94, 0x6b, 0x82, 0xec, 0xb4 } };\r\n\r\n// {EF9B60FE-CB03-4c40-A8FD-3F1821020B37}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_restart = \r\n{ 0xef9b60fe, 0xcb03, 0x4c40, { 0xa8, 0xfd, 0x3f, 0x18, 0x21, 0x2, 0xb, 0x37 } };\r\n\r\n// {90500F09-F16F-415e-A047-AC5045C95FFE}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_activate = \r\n{ 0x90500f09, 0xf16f, 0x415e, { 0xa0, 0x47, 0xac, 0x50, 0x45, 0xc9, 0x5f, 0xfe } };\r\n\r\n// {13C17E8D-0D6F-41a4-B24A-59371043E925}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_hide = \r\n{ 0x13c17e8d, 0xd6f, 0x41a4, { 0xb2, 0x4a, 0x59, 0x37, 0x10, 0x43, 0xe9, 0x25 } };\r\n\r\n// {D9473FB2-BF11-4be0-972F-0E43F166A118}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_activate_or_hide = \r\n{ 0xd9473fb2, 0xbf11, 0x4be0, { 0x97, 0x2f, 0xe, 0x43, 0xf1, 0x66, 0xa1, 0x18 } };\r\n\r\n// {91E349DA-8800-42e5-BC8C-F3A92577AE84}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_titleformat_help = \r\n{ 0x91e349da, 0x8800, 0x42e5, { 0xbc, 0x8c, 0xf3, 0xa9, 0x25, 0x77, 0xae, 0x84 } };\r\n\r\n// {FBCFE01C-6C57-4e6a-A9F1-62334640DC91}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playback_follows_cursor= \r\n{ 0xfbcfe01c, 0x6c57, 0x4e6a, { 0xa9, 0xf1, 0x62, 0x33, 0x46, 0x40, 0xdc, 0x91 } };\r\n\r\n// {0E1C730A-1EA9-41cc-9C30-25700ABDD9FA}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_cursor_follows_playback= \r\n{ 0xe1c730a, 0x1ea9, 0x41cc, { 0x9c, 0x30, 0x25, 0x70, 0xa, 0xbd, 0xd9, 0xfa } };\r\n\r\n// {E58895A0-A2F0-45b6-8799-1440E4DB7284}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_next = \r\n{ 0xe58895a0, 0xa2f0, 0x45b6, { 0x87, 0x99, 0x14, 0x40, 0xe4, 0xdb, 0x72, 0x84 } };\r\n\r\n// {059C4566-4708-4ebf-8139-6A8EA5A9DFC8}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_previous = \r\n{ 0x59c4566, 0x4708, 0x4ebf, { 0x81, 0x39, 0x6a, 0x8e, 0xa5, 0xa9, 0xdf, 0xc8 } };\r\n\r\n// {18B1278A-F1BB-4b48-BC3D-6EC9EF80AD19}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_next_or_random = \r\n{ 0x18b1278a, 0xf1bb, 0x4b48, { 0xbc, 0x3d, 0x6e, 0xc9, 0xef, 0x80, 0xad, 0x19 } };\r\n\r\n// {42BDA765-30A8-40fa-BFA4-6A4E2F2B2CE9}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_random = \r\n{ 0x42bda765, 0x30a8, 0x40fa, { 0xbf, 0xa4, 0x6a, 0x4e, 0x2f, 0x2b, 0x2c, 0xe9 } };\r\n\r\n// {FCEF5262-7FA5-452e-A527-C14E0CB582DE}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_pause = \r\n{ 0xfcef5262, 0x7fa5, 0x452e, { 0xa5, 0x27, 0xc1, 0x4e, 0xc, 0xb5, 0x82, 0xde } };\r\n\r\n// {D3F83B15-D4AF-4586-8BD0-4EA415E31FE1}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_play = \r\n{ 0xd3f83b15, 0xd4af, 0x4586, { 0x8b, 0xd0, 0x4e, 0xa4, 0x15, 0xe3, 0x1f, 0xe1 } };\r\n\r\n// {8DEBC44E-EDA2-48d4-8696-31FC29D1F383}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_play_or_pause = \r\n{ 0x8debc44e, 0xeda2, 0x48d4, { 0x86, 0x96, 0x31, 0xfc, 0x29, 0xd1, 0xf3, 0x83 } };\r\n\r\n// {2DF17F25-80B9-4a43-B21D-620458FDDE1E}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_rg_set_album = \r\n{ 0x2df17f25, 0x80b9, 0x4a43, { 0xb2, 0x1d, 0x62, 0x4, 0x58, 0xfd, 0xde, 0x1e } };\r\n\r\n// {C26F1955-5753-4836-887F-84A563DD6DD9}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_rg_set_track = \r\n{ 0xc26f1955, 0x5753, 0x4836, { 0x88, 0x7f, 0x84, 0xa5, 0x63, 0xdd, 0x6d, 0xd9 } };\r\n\r\n// {8D2D808E-6AA2-455b-A2F1-CDB019328140}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_rg_disable = \r\n{ 0x8d2d808e, 0x6aa2, 0x455b, { 0xa2, 0xf1, 0xcd, 0xb0, 0x19, 0x32, 0x81, 0x40 } };\r\n\r\n// {C3378028-165F-4374-966C-2FA2E0FCD3A8}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_stop = \r\n{ 0xc3378028, 0x165f, 0x4374, { 0x96, 0x6c, 0x2f, 0xa2, 0xe0, 0xfc, 0xd3, 0xa8 } };\r\n\r\n// {EE057982-22F9-4862-A986-859E463316FB}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_stop_after_current = \r\n{ 0xee057982, 0x22f9, 0x4862, { 0xa9, 0x86, 0x85, 0x9e, 0x46, 0x33, 0x16, 0xfb } };\r\n\r\n// {11DC6526-73C4-44f0-91B1-DE5C2D26B0C7}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_volume_down = \r\n{ 0x11dc6526, 0x73c4, 0x44f0, { 0x91, 0xb1, 0xde, 0x5c, 0x2d, 0x26, 0xb0, 0xc7 } };\r\n\r\n// {A313E630-A04A-4ae8-B5B4-0A944AC964FF}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_volume_up = \r\n{ 0xa313e630, 0xa04a, 0x4ae8, { 0xb5, 0xb4, 0xa, 0x94, 0x4a, 0xc9, 0x64, 0xff } };\r\n\r\n// {4A36285B-B4AF-46ed-A1AA-6333057F485B}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_volume_mute = \r\n{ 0x4a36285b, 0xb4af, 0x46ed, { 0xa1, 0xaa, 0x63, 0x33, 0x5, 0x7f, 0x48, 0x5b } };\r\n\r\n// {2DC43C22-CA09-4ef9-A61E-7A0C1DAAE21E}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_add_directory = \r\n{ 0x2dc43c22, 0xca09, 0x4ef9, { 0xa6, 0x1e, 0x7a, 0xc, 0x1d, 0xaa, 0xe2, 0x1e } };\r\n\r\n// {FC89C278-4475-4853-96C9-F7F05E8CC837}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_add_files = \r\n{ 0xfc89c278, 0x4475, 0x4853, { 0x96, 0xc9, 0xf7, 0xf0, 0x5e, 0x8c, 0xc8, 0x37 } };\r\n\r\n// {9CA39D38-AC9B-4cca-B0CE-C0F62D188114}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_add_location = \r\n{ 0x9ca39d38, 0xac9b, 0x4cca, { 0xb0, 0xce, 0xc0, 0xf6, 0x2d, 0x18, 0x81, 0x14 } };\r\n\r\n// {73D6E69D-0DC9-4d5c-A7EE-FF4BE3896B08}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_add_playlist = \r\n{ 0x73d6e69d, 0xdc9, 0x4d5c, { 0xa7, 0xee, 0xff, 0x4b, 0xe3, 0x89, 0x6b, 0x8 } };\r\n\r\n// {55559142-7AEA-4c20-9B72-1D48E970A274}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_clear_playlist = \r\n{ 0x55559142, 0x7aea, 0x4c20, { 0x9b, 0x72, 0x1d, 0x48, 0xe9, 0x70, 0xa2, 0x74 } };\r\n\r\n// {BF72488F-36AC-46b3-A36D-193E60C79BC5}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_create_playlist = \r\n{ 0xbf72488f, 0x36ac, 0x46b3, { 0xa3, 0x6d, 0x19, 0x3e, 0x60, 0xc7, 0x9b, 0xc5 } };\r\n\r\n// {59E99BEE-42A3-4526-B06D-56C0C49F0BC1}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_highlight_playing = \r\n{ 0x59e99bee, 0x42a3, 0x4526, { 0xb0, 0x6d, 0x56, 0xc0, 0xc4, 0x9f, 0xb, 0xc1 } };\r\n\r\n// {D94393D4-9DBB-4e5c-BE8C-BE9CA80E214D}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_load_playlist = \r\n{ 0xd94393d4, 0x9dbb, 0x4e5c, { 0xbe, 0x8c, 0xbe, 0x9c, 0xa8, 0xe, 0x21, 0x4d } };\r\n\r\n// {EE1308C5-EBD2-48f1-959D-2627069C2E0F}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_next_playlist = \r\n{ 0xee1308c5, 0xebd2, 0x48f1, { 0x95, 0x9d, 0x26, 0x27, 0x6, 0x9c, 0x2e, 0xf } };\r\n\r\n// {486ECDA3-7BA2-49e9-BB44-4DB9DF9320C7}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_previous_playlist = \r\n{ 0x486ecda3, 0x7ba2, 0x49e9, { 0xbb, 0x44, 0x4d, 0xb9, 0xdf, 0x93, 0x20, 0xc7 } };\r\n\r\n// {69C778AA-B836-40a0-89CD-7A2E50C102CB}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_open = \r\n{ 0x69c778aa, 0xb836, 0x40a0, { 0x89, 0xcd, 0x7a, 0x2e, 0x50, 0xc1, 0x2, 0xcb } };\r\n\r\n// {EB7FB5A4-5904-4d2c-B66C-D882A3B15277}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_remove_playlist = \r\n{ 0xeb7fb5a4, 0x5904, 0x4d2c, { 0xb6, 0x6c, 0xd8, 0x82, 0xa3, 0xb1, 0x52, 0x77 } };\r\n\r\n// {C297BADB-8098-45a9-A5E8-B53A0D780CE3}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_remove_dead_entries = \r\n{ 0xc297badb, 0x8098, 0x45a9, { 0xa5, 0xe8, 0xb5, 0x3a, 0xd, 0x78, 0xc, 0xe3 } };\r\n\r\n// {D08C2921-7750-4979-98F9-3A513A31FF96}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_remove_duplicates = \r\n{ 0xd08c2921, 0x7750, 0x4979, { 0x98, 0xf9, 0x3a, 0x51, 0x3a, 0x31, 0xff, 0x96 } };\r\n\r\n// {D3A25E47-BA98-4e6b-95AD-A7502919EB75}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_rename_playlist = \r\n{ 0xd3a25e47, 0xba98, 0x4e6b, { 0x95, 0xad, 0xa7, 0x50, 0x29, 0x19, 0xeb, 0x75 } };\r\n\r\n// {0FDCFC65-9B39-445a-AA88-4D245F217480}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_save_all_playlists = \r\n{ 0xfdcfc65, 0x9b39, 0x445a, { 0xaa, 0x88, 0x4d, 0x24, 0x5f, 0x21, 0x74, 0x80 } };\r\n\r\n// {370B720B-4CF7-465b-908C-2D2ADD027900}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_save_playlist = \r\n{ 0x370b720b, 0x4cf7, 0x465b, { 0x90, 0x8c, 0x2d, 0x2a, 0xdd, 0x2, 0x79, 0x0 } };\r\n\r\n// {A6CFC2A8-56B3-4d12-88E7-0237961AC47E}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_search = \r\n{ 0xa6cfc2a8, 0x56b3, 0x4d12, { 0x88, 0xe7, 0x2, 0x37, 0x96, 0x1a, 0xc4, 0x7e } };\r\n\r\n// {383D4E8D-7E30-4fb8-B5DD-8C975D89E58E}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_sel_crop = \r\n{ 0x383d4e8d, 0x7e30, 0x4fb8, { 0xb5, 0xdd, 0x8c, 0x97, 0x5d, 0x89, 0xe5, 0x8e } };\r\n\r\n// {E0EEA319-E282-4e6c-8B82-4DFD42A1D4ED}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_sel_remove = \r\n{ 0xe0eea319, 0xe282, 0x4e6c, { 0x8b, 0x82, 0x4d, 0xfd, 0x42, 0xa1, 0xd4, 0xed } };\r\n\r\n// {F0845920-7F6D-40ac-B2EB-3D00C2C8260B}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_sel_invert = \r\n{ 0xf0845920, 0x7f6d, 0x40ac, { 0xb2, 0xeb, 0x3d, 0x0, 0xc2, 0xc8, 0x26, 0xb } };\r\n\r\n// {29910B33-79E9-40da-992B-5A4AA4281F78}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_undo = \r\n{ 0x29910b33, 0x79e9, 0x40da, { 0x99, 0x2b, 0x5a, 0x4a, 0xa4, 0x28, 0x1f, 0x78 } };\r\n\r\n// {7A9D9450-A8BF-4a88-B44F-DCD83A49DD7A}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_redo =\r\n{ 0x7a9d9450, 0xa8bf, 0x4a88, { 0xb4, 0x4f, 0xdc, 0xd8, 0x3a, 0x49, 0xdd, 0x7a } };\r\n\r\n// {02D89A8A-5F7D-41c3-A215-6731D8621036}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_show_console = \r\n{ 0x2d89a8a, 0x5f7d, 0x41c3, { 0xa2, 0x15, 0x67, 0x31, 0xd8, 0x62, 0x10, 0x36 } };\r\n\r\n// {E6970E91-33BE-4288-AC01-4B02F07B5D38}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_play_cd = \r\n{ 0xe6970e91, 0x33be, 0x4288, { 0xac, 0x1, 0x4b, 0x2, 0xf0, 0x7b, 0x5d, 0x38 } };\r\n\r\n// {1073AB1D-38ED-4957-8B06-38BC878C1F40}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_restart_resetconfig = \r\n{ 0x1073ab1d, 0x38ed, 0x4957, { 0x8b, 0x6, 0x38, 0xbc, 0x87, 0x8c, 0x1f, 0x40 } };\r\n\r\n// {FDC8A1C2-93EF-4415-8C20-60B6517F0B5F}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_record = \r\n{ 0xfdc8a1c2, 0x93ef, 0x4415, { 0x8c, 0x20, 0x60, 0xb6, 0x51, 0x7f, 0xb, 0x5f } };\r\n\r\n// {45EB37D2-3CD9-4f0a-9B20-8EAE649D7A9F}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_moveback = \r\n{ 0x45eb37d2, 0x3cd9, 0x4f0a, { 0x9b, 0x20, 0x8e, 0xae, 0x64, 0x9d, 0x7a, 0x9f } };\r\n\r\n// {02298938-596A-41f7-A398-19766A06E6EB}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_moveforward = \r\n{ 0x2298938, 0x596a, 0x41f7, { 0xa3, 0x98, 0x19, 0x76, 0x6a, 0x6, 0xe6, 0xeb } };\r\n\r\n// {E910ACC6-A81A-4a20-9F62-19015BCD1013}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_saveconfig = \r\n{ 0xe910acc6, 0xa81a, 0x4a20, { 0x9f, 0x62, 0x19, 0x1, 0x5b, 0xcd, 0x10, 0x13 } };\r\n\r\n// {03445FCC-71D9-4e01-AE02-A557D30B4CD7}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_playlist_select_all = \r\n{ 0x3445fcc, 0x71d9, 0x4e01, { 0xae, 0x2, 0xa5, 0x57, 0xd3, 0xb, 0x4c, 0xd7 } };\r\n\r\n// {919FA72B-1DF9-49ee-A8F1-D8BA1DEAA7E9}\r\nFOOGUIDDECL const GUID standard_commands::guid_main_show_now_playing = \r\n{ 0x919fa72b, 0x1df9, 0x49ee, { 0xa8, 0xf1, 0xd8, 0xba, 0x1d, 0xea, 0xa7, 0xe9 } };\r\n\r\n// {D8D51855-D79D-49b8-97A8-065785FA2426}\r\nFOOGUIDDECL const GUID playlist_manager::class_guid= \r\n{ 0xd8d51855, 0xd79d, 0x49b8, { 0x97, 0xa8, 0x6, 0x57, 0x85, 0xfa, 0x24, 0x26 } };\r\n\r\n// {C303A0F1-8E88-4539-87E5-9E455B7D548C}\r\nFOOGUIDDECL const GUID genrand_service::class_guid= \r\n{ 0xc303a0f1, 0x8e88, 0x4539, { 0x87, 0xe5, 0x9e, 0x45, 0x5b, 0x7d, 0x54, 0x8c } };\r\n\r\n// {EB8FA333-F365-46ad-8621-345671567BAA}\r\nFOOGUIDDECL const GUID playlist_incoming_item_filter::class_guid= \r\n{ 0xeb8fa333, 0xf365, 0x46ad, { 0x86, 0x21, 0x34, 0x56, 0x71, 0x56, 0x7b, 0xaa } };\r\n\r\n// {FEBD85B5-C12D-45b5-B55D-0D3F432B0C6B}\r\nFOOGUIDDECL const GUID library_manager::class_guid= \r\n{ 0xfebd85b5, 0xc12d, 0x45b5, { 0xb5, 0x5d, 0xd, 0x3f, 0x43, 0x2b, 0xc, 0x6b } };\r\n\r\n// {9A08B50F-E8C6-40c0-88C3-7530CF2C3115}\r\nFOOGUIDDECL const GUID library_callback::class_guid= \r\n{ 0x9a08b50f, 0xe8c6, 0x40c0, { 0x88, 0xc3, 0x75, 0x30, 0xcf, 0x2c, 0x31, 0x15 } };\r\n\r\n// {D5CAC75A-3023-4dce-8B0D-B502BD056A7C}\r\nFOOGUIDDECL const GUID popup_message::class_guid= \r\n{ 0xd5cac75a, 0x3023, 0x4dce, { 0x8b, 0xd, 0xb5, 0x2, 0xbd, 0x5, 0x6a, 0x7c } };\r\n\r\n// {13F9CB11-0EAE-4417-AF0C-8894DEB65E8B}\r\nFOOGUIDDECL const GUID app_close_blocker::class_guid= \r\n{ 0x13f9cb11, 0xeae, 0x4417, { 0xaf, 0xc, 0x88, 0x94, 0xde, 0xb6, 0x5e, 0x8b } };\r\n\r\n// {5570A2D2-8F9E-48a7-AFAC-DAC00A3C1636}\r\nFOOGUIDDECL const GUID file_operation_callback::class_guid= \r\n{ 0x5570a2d2, 0x8f9e, 0x48a7, { 0xaf, 0xac, 0xda, 0xc0, 0xa, 0x3c, 0x16, 0x36 } };\r\n\r\n// {942F5EFE-D68B-4bde-BA17-C442A8B2A445}\r\nFOOGUIDDECL const GUID titleformat_config::class_guid= \r\n{ 0x942f5efe, 0xd68b, 0x4bde, { 0xba, 0x17, 0xc4, 0x42, 0xa8, 0xb2, 0xa4, 0x45 } };\r\n\r\n// {9F33EDF0-B8F0-4d11-B27B-4FC1D3B3489F}\r\nFOOGUIDDECL const GUID titleformat_config_callback::class_guid= \r\n{ 0x9f33edf0, 0xb8f0, 0x4d11, { 0xb2, 0x7b, 0x4f, 0xc1, 0xd3, 0xb3, 0x48, 0x9f } };\r\n\r\n// {B905715B-4B26-4e0e-B3B8-FF4A232A4258}\r\nFOOGUIDDECL const GUID titleformat_config::config_playlist= \r\n{ 0xb905715b, 0x4b26, 0x4e0e, { 0xb3, 0xb8, 0xff, 0x4a, 0x23, 0x2a, 0x42, 0x58 } };\r\n\r\n// {A2051E09-A1EA-471b-B146-7375413105D2}\r\nFOOGUIDDECL const GUID titleformat_config::config_copy= \r\n{ 0xa2051e09, 0xa1ea, 0x471b, { 0xb1, 0x46, 0x73, 0x75, 0x41, 0x31, 0x5, 0xd2 } };\r\n\r\n// {70B56942-3C37-427b-8D58-3A2DF3D835BD}\r\nFOOGUIDDECL const GUID titleformat_config::config_statusbar= \r\n{ 0x70b56942, 0x3c37, 0x427b, { 0x8d, 0x58, 0x3a, 0x2d, 0xf3, 0xd8, 0x35, 0xbd } };\r\n\r\n// {8E728600-7BBD-4a5c-A001-40A450427EB6}\r\nFOOGUIDDECL const GUID titleformat_config::config_systray= \r\n{ 0x8e728600, 0x7bbd, 0x4a5c, { 0xa0, 0x1, 0x40, 0xa4, 0x50, 0x42, 0x7e, 0xb6 } };\r\n\r\n// {D02F2D01-BED3-46e8-B664-8B1F07E78F69}\r\nFOOGUIDDECL const GUID titleformat_config::config_windowtitle= \r\n{ 0xd02f2d01, 0xbed3, 0x46e8, { 0xb6, 0x64, 0x8b, 0x1f, 0x7, 0xe7, 0x8f, 0x69 } };\r\n\r\n// {340099D1-7BEC-4ac6-92A4-77FF01507891}\r\nFOOGUIDDECL const GUID config_object::class_guid= \r\n{ 0x340099d1, 0x7bec, 0x4ac6, { 0x92, 0xa4, 0x77, 0xff, 0x1, 0x50, 0x78, 0x91 } };\r\n\r\n// {1BA04122-DE9A-4a90-9FC3-A6A7EC8F9626}\r\nFOOGUIDDECL const GUID config_object_notify_manager::class_guid= \r\n{ 0x1ba04122, 0xde9a, 0x4a90, { 0x9f, 0xc3, 0xa6, 0xa7, 0xec, 0x8f, 0x96, 0x26 } };\r\n\r\n// {AD5138E6-CF8F-4482-89B2-B2EAAEDF3B4C}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_show_keyboard_shortcuts_in_menus=\r\n{ 0xad5138e6, 0xcf8f, 0x4482, { 0x89, 0xb2, 0xb2, 0xea, 0xae, 0xdf, 0x3b, 0x4c } };\r\n\r\n// {E91F618C-5741-470f-A178-21272C3ECA90}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_remember_window_positions=\r\n{ 0xe91f618c, 0x5741, 0x470f, { 0xa1, 0x78, 0x21, 0x27, 0x2c, 0x3e, 0xca, 0x90 } };\r\n\r\n// {5497FAA9-690C-4fb4-8BC0-678CEBCBBDC4}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_playback_follows_cursor=\r\n{ 0x5497faa9, 0x690c, 0x4fb4, { 0x8b, 0xc0, 0x67, 0x8c, 0xeb, 0xcb, 0xbd, 0xc4 } };\r\n\r\n// {58D3E2D6-DD6D-48dd-98EB-4EABF0ACFEB8}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_cursor_follows_playback=\r\n{ 0x58d3e2d6, 0xdd6d, 0x48dd, { 0x98, 0xeb, 0x4e, 0xab, 0xf0, 0xac, 0xfe, 0xb8 } };\r\n\r\n// {2DF7194D-86FC-4312-98DA-E820DA3E710D}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_ui_always_on_top=\r\n{ 0x2df7194d, 0x86fc, 0x4312, { 0x98, 0xda, 0xe8, 0x20, 0xda, 0x3e, 0x71, 0xd } };\r\n\r\n// {B572C86F-4206-40a0-8476-C7B27E74DB2D}\r\nFOOGUIDDECL const GUID standard_config_objects::bool_playlist_stop_after_current=\r\n{ 0xb572c86f, 0x4206, 0x40a0, { 0x84, 0x76, 0xc7, 0xb2, 0x7e, 0x74, 0xdb, 0x2d } };\r\n\r\n// {FFDFDA96-699C-4617-A977-22DC2F039B00}\r\nFOOGUIDDECL const GUID standard_config_objects::string_gui_last_directory_media=\r\n{ 0xffdfda96, 0x699c, 0x4617, { 0xa9, 0x77, 0x22, 0xdc, 0x2f, 0x3, 0x9b, 0x0 } };\r\n\r\n// {915D3B21-81CB-4b96-9762-1C90FBF371DF}\r\nFOOGUIDDECL const GUID standard_config_objects::string_gui_last_directory_playlists=\r\n{ 0x915d3b21, 0x81cb, 0x4b96, { 0x97, 0x62, 0x1c, 0x90, 0xfb, 0xf3, 0x71, 0xdf } };\r\n\r\n// {338B6871-EB1F-4384-BF83-6BFACE5B66BC}\r\nFOOGUIDDECL const GUID standard_config_objects::int32_dynamic_bitrate_display_rate=\r\n{ 0x338b6871, 0xeb1f, 0x4384, { 0xbf, 0x83, 0x6b, 0xfa, 0xce, 0x5b, 0x66, 0xbc } };\r\n\r\n// {3E35D949-DCDB-44e1-8013-9D1633C09756}\r\nFOOGUIDDECL const GUID config_object_notify::class_guid=\r\n{ 0x3e35d949, 0xdcdb, 0x44e1, { 0x80, 0x13, 0x9d, 0x16, 0x33, 0xc0, 0x97, 0x56 } };\r\n\r\n// {4AC9408E-4D9C-4135-ACB5-2CAB35376FC9}\r\nFOOGUIDDECL const GUID titleformat_object::class_guid=\r\n{ 0x4ac9408e, 0x4d9c, 0x4135, { 0xac, 0xb5, 0x2c, 0xab, 0x35, 0x37, 0x6f, 0xc9 } };\r\n\r\n// {25B0D20D-9BA3-4a7b-8D0E-89FAF75F916F}\r\nFOOGUIDDECL const GUID tag_processor_id3v2::class_guid=\r\n{ 0x25b0d20d, 0x9ba3, 0x4a7b, { 0x8d, 0xe, 0x89, 0xfa, 0xf7, 0x5f, 0x91, 0x6f } };\r\n\r\n// {AD537D40-499D-4c29-81D4-C0FA496DD58C}\r\nFOOGUIDDECL const GUID tag_processor_trailing::class_guid=\r\n{ 0xad537d40, 0x499d, 0x4c29, { 0x81, 0xd4, 0xc0, 0xfa, 0x49, 0x6d, 0xd5, 0x8c } };\r\n\r\n// {160885C6-3AA3-4f60-8718-1240615E6414}\r\nFOOGUIDDECL const GUID metadb_handle::class_guid=\r\n{ 0x160885c6, 0x3aa3, 0x4f60, { 0x87, 0x18, 0x12, 0x40, 0x61, 0x5e, 0x64, 0x14 } };\r\n\r\n// {9DBC262F-4795-4292-824B-23A655011A3E}\r\nFOOGUIDDECL const GUID threaded_process::class_guid=\r\n{ 0x9dbc262f, 0x4795, 0x4292, { 0x82, 0x4b, 0x23, 0xa6, 0x55, 0x1, 0x1a, 0x3e } };\r\n\r\n// {7B69141B-4271-4070-8998-10CD39249C12}\r\nFOOGUIDDECL const GUID threaded_process_callback::class_guid=\r\n{ 0x7b69141b, 0x4271, 0x4070, { 0x89, 0x98, 0x10, 0xcd, 0x39, 0x24, 0x9c, 0x12 } };\r\n\r\n\r\n// {64D18B80-5E97-40e4-A30C-A4640C60BCE5}\r\nFOOGUIDDECL const GUID metadb_io::class_guid=\r\n{ 0x64d18b80, 0x5e97, 0x40e4, { 0xa3, 0xc, 0xa4, 0x64, 0xc, 0x60, 0xbc, 0xe5 } };\r\n\r\n// {B9218D23-F73D-4b61-A1D9-BFD420CDAC77}\r\nFOOGUIDDECL const GUID preferences_page::guid_root=\r\n{ 0xb9218d23, 0xf73d, 0x4b61, { 0xa1, 0xd9, 0xbf, 0xd4, 0x20, 0xcd, 0xac, 0x77 } };\r\n\r\n// {2F0E2232-A5FD-43e4-B6AB-3839B8D1A707}\r\nFOOGUIDDECL const GUID preferences_page::guid_hidden=\r\n{ 0x2f0e2232, 0xa5fd, 0x43e4, { 0xb6, 0xab, 0x38, 0x39, 0xb8, 0xd1, 0xa7, 0x7 } };\r\n\r\n// {627C0767-0793-44f8-8087-BE4934311282}\r\nFOOGUIDDECL const GUID preferences_page::guid_tools=\r\n{ 0x627c0767, 0x793, 0x44f8, { 0x80, 0x87, 0xbe, 0x49, 0x34, 0x31, 0x12, 0x82 } };\r\n\r\n// {6AAA67B6-732F-4967-899A-18C5F8C70017}\r\nFOOGUIDDECL const GUID preferences_page::guid_display=\r\n{ 0x6aaa67b6, 0x732f, 0x4967, { 0x89, 0x9a, 0x18, 0xc5, 0xf8, 0xc7, 0x0, 0x17 } };\r\n\r\n// {67508677-CFCC-4a1c-921C-49B39CC5B986}\r\nFOOGUIDDECL const GUID preferences_page::guid_playback=\r\n{ 0x67508677, 0xcfcc, 0x4a1c, { 0x92, 0x1c, 0x49, 0xb3, 0x9c, 0xc5, 0xb9, 0x86 } };\r\n\r\n// {494326C8-88FF-4265-B2B2-E6470BEE13B3}\r\nFOOGUIDDECL const GUID preferences_page::guid_visualisations=\r\n{ 0x494326c8, 0x88ff, 0x4265, { 0xb2, 0xb2, 0xe6, 0x47, 0xb, 0xee, 0x13, 0xb3 } };\r\n\r\n// {FC01B529-4BD7-47cd-BAF7-2FB632F0DBB6}\r\nFOOGUIDDECL const GUID preferences_page::guid_input=\r\n{ 0xfc01b529, 0x4bd7, 0x47cd, { 0xba, 0xf7, 0x2f, 0xb6, 0x32, 0xf0, 0xdb, 0xb6 } };\r\n\r\n// {2E8E9647-4174-41b2-9EC4-910BE128082E}\r\nFOOGUIDDECL const GUID preferences_page::guid_core=\r\n{ 0x2e8e9647, 0x4174, 0x41b2, { 0x9e, 0xc4, 0x91, 0xb, 0xe1, 0x28, 0x8, 0x2e } };\r\n\r\n// {7D0334E5-ADD7-4ff5-9DB8-A618B4824028}\r\nFOOGUIDDECL const GUID preferences_page::guid_tag_writing=\r\n{ 0x7d0334e5, 0xadd7, 0x4ff5, { 0x9d, 0xb8, 0xa6, 0x18, 0xb4, 0x82, 0x40, 0x28 } };\r\n\r\n// {2D269FA9-6F78-4cec-9F1F-0A176EFCE77A}\r\nFOOGUIDDECL const GUID preferences_page::guid_media_library=\r\n{ 0x2d269fa9, 0x6f78, 0x4cec, { 0x9f, 0x1f, 0xa, 0x17, 0x6e, 0xfc, 0xe7, 0x7a } };\r\n\r\n// {B8C5CEEA-A5F4-4278-AA2D-798E4403001F}\r\nFOOGUIDDECL const GUID library_viewer::class_guid=\r\n{ 0xb8c5ceea, 0xa5f4, 0x4278, { 0xaa, 0x2d, 0x79, 0x8e, 0x44, 0x3, 0x0, 0x1f } };\r\n\r\n// {5CD49B5D-D604-4c07-A8FA-FFD8512AFD2B}\r\nFOOGUIDDECL const GUID message_loop::class_guid=\r\n{ 0x5cd49b5d, 0xd604, 0x4c07, { 0xa8, 0xfa, 0xff, 0xd8, 0x51, 0x2a, 0xfd, 0x2b } };\r\n\r\n// {932EC96D-4DFD-4ed7-A07C-2A22BE770185}\r\nFOOGUIDDECL const GUID chapterizer::class_guid=\r\n{ 0x932ec96d, 0x4dfd, 0x4ed7, { 0xa0, 0x7c, 0x2a, 0x22, 0xbe, 0x77, 0x1, 0x85 } };\r\n\r\n// {7EB442CD-FAD7-4a26-AD7E-16F6FC89207B}\r\nFOOGUIDDECL const GUID input_decoder::class_guid = \r\n{ 0x7eb442cd, 0xfad7, 0x4a26, { 0xad, 0x7e, 0x16, 0xf6, 0xfc, 0x89, 0x20, 0x7b } };\r\n\r\n// {8E9BB1D4-A52B-4df6-A929-1AAE4075388A}\r\nFOOGUIDDECL const GUID input_info_reader::class_guid = \r\n{ 0x8e9bb1d4, 0xa52b, 0x4df6, { 0xa9, 0x29, 0x1a, 0xae, 0x40, 0x75, 0x38, 0x8a } };\r\n\r\n// {FE40FF66-64C9-4234-B639-028DC8060CF7}\r\nFOOGUIDDECL const GUID input_info_writer::class_guid = \r\n{ 0xfe40ff66, 0x64c9, 0x4234, { 0xb6, 0x39, 0x2, 0x8d, 0xc8, 0x6, 0xc, 0xf7 } };\r\n\r\n// {436547FC-C4EF-4322-B59E-E696A25FAB2C}\r\nFOOGUIDDECL const GUID input_entry::class_guid = \r\n{ 0x436547fc, 0xc4ef, 0x4322, { 0xb5, 0x9e, 0xe6, 0x96, 0xa2, 0x5f, 0xab, 0x2c } };\r\n\r\n// {3296219B-EBA5-4c32-A193-C9BB174801DA}\r\nFOOGUIDDECL const GUID link_resolver::class_guid = \r\n{ 0x3296219b, 0xeba5, 0x4c32, { 0xa1, 0x93, 0xc9, 0xbb, 0x17, 0x48, 0x1, 0xda } };\r\n\r\n// {A49E087E-D064-4b2e-A08D-11264F691FFE}\r\nFOOGUIDDECL const GUID playback_queue_callback::class_guid = \r\n{ 0xa49e087e, 0xd064, 0x4b2e, { 0xa0, 0x8d, 0x11, 0x26, 0x4f, 0x69, 0x1f, 0xfe } };\r\n\r\n// {1131D64B-04CB-43ee-95EB-24D18B753248}\r\nFOOGUIDDECL const GUID main_thread_callback_manager::class_guid = \r\n{ 0x1131d64b, 0x4cb, 0x43ee, { 0x95, 0xeb, 0x24, 0xd1, 0x8b, 0x75, 0x32, 0x48 } };\r\n\r\n// {87D2C583-7AFB-4e58-B21E-FBD3E6E8F5E7}\r\nFOOGUIDDECL const GUID main_thread_callback::class_guid = \r\n{ 0x87d2c583, 0x7afb, 0x4e58, { 0xb2, 0x1e, 0xfb, 0xd3, 0xe6, 0xe8, 0xf5, 0xe7 } };\r\n\r\n\r\n\r\n// {21656AB9-0255-4f8c-8FB9-1A7748BCE93A}\r\nFOOGUIDDECL const GUID mainmenu_group::class_guid = \r\n{ 0x21656ab9, 0x255, 0x4f8c, { 0x8f, 0xb9, 0x1a, 0x77, 0x48, 0xbc, 0xe9, 0x3a } };\r\n\r\n// {2E673A2E-A4EE-419c-94C8-9C838660414C}\r\nFOOGUIDDECL const GUID mainmenu_group_popup::class_guid = \r\n{ 0x2e673a2e, 0xa4ee, 0x419c, { 0x94, 0xc8, 0x9c, 0x83, 0x86, 0x60, 0x41, 0x4c } };\r\n\r\n// {35077B8C-6E70-47ba-B9DD-D51500E12F2E}\r\nFOOGUIDDECL const GUID mainmenu_commands::class_guid = \r\n{ 0x35077b8c, 0x6e70, 0x47ba, { 0xb9, 0xdd, 0xd5, 0x15, 0x0, 0xe1, 0x2f, 0x2e } };\r\n\r\n// {350B3EA8-6B3E-4346-B6D2-799E98EFC920}\r\nFOOGUIDDECL const GUID mainmenu_manager::class_guid = \r\n{ 0x350b3ea8, 0x6b3e, 0x4346, { 0xb6, 0xd2, 0x79, 0x9e, 0x98, 0xef, 0xc9, 0x20 } };\r\n\r\n\r\n// {8F487F1F-419F-47a7-8ECF-EC44AF4449A3}\r\nFOOGUIDDECL const GUID mainmenu_groups::file = \r\n{ 0x8f487f1f, 0x419f, 0x47a7, { 0x8e, 0xcf, 0xec, 0x44, 0xaf, 0x44, 0x49, 0xa3 } };\r\n\r\n// {F8BE5604-165F-4bb9-B6A9-15E55E0E0D3A}\r\nFOOGUIDDECL const GUID mainmenu_groups::view = \r\n{ 0xf8be5604, 0x165f, 0x4bb9, { 0xb6, 0xa9, 0x15, 0xe5, 0x5e, 0xe, 0xd, 0x3a } };\r\n\r\n// {8CDA6B10-0613-4cfd-8730-3B9CBF4C6A39}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit = \r\n{ 0x8cda6b10, 0x613, 0x4cfd, { 0x87, 0x30, 0x3b, 0x9c, 0xbf, 0x4c, 0x6a, 0x39 } };\r\n\r\n// {D8A4FC46-5E3D-47aa-97B7-947988228246}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part1 = \r\n{ 0xd8a4fc46, 0x5e3d, 0x47aa, { 0x97, 0xb7, 0x94, 0x79, 0x88, 0x22, 0x82, 0x46 } };\r\n\r\n// {007682CE-2A99-4b70-8F63-DE765D1C5555}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part2 = \r\n{ 0x7682ce, 0x2a99, 0x4b70, { 0x8f, 0x63, 0xde, 0x76, 0x5d, 0x1c, 0x55, 0x55 } };\r\n\r\n// {1F572090-D620-4940-85EC-0EFE499FAC03}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part3 = \r\n{ 0x1f572090, 0xd620, 0x4940, { 0x85, 0xec, 0xe, 0xfe, 0x49, 0x9f, 0xac, 0x3 } };\r\n\r\n// {65FA047A-1599-4b9c-B53D-C3FEB716339D}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part2_selection = \r\n{ 0x65fa047a, 0x1599, 0x4b9c, { 0xb5, 0x3d, 0xc3, 0xfe, 0xb7, 0x16, 0x33, 0x9d } };\r\n\r\n// {5B8AEF2C-6E1A-420d-B488-3E3A00E39E28}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part2_sort = \r\n{ 0x5b8aef2c, 0x6e1a, 0x420d, { 0xb4, 0x88, 0x3e, 0x3a, 0x0, 0xe3, 0x9e, 0x28 } };\r\n\r\n// {EE9D6F72-7BC7-4a60-8C28-B96DED252BD3}\r\nFOOGUIDDECL const GUID mainmenu_groups::edit_part2_selection_sort = \r\n{ 0xee9d6f72, 0x7bc7, 0x4a60, { 0x8c, 0x28, 0xb9, 0x6d, 0xed, 0x25, 0x2b, 0xd3 } };\r\n\r\n// {53FA5B8A-FCBC-4296-B968-45BAE6888845}\r\nFOOGUIDDECL const GUID mainmenu_groups::playback = \r\n{ 0x53fa5b8a, 0xfcbc, 0x4296, { 0xb9, 0x68, 0x45, 0xba, 0xe6, 0x88, 0x88, 0x45 } };\r\n\r\n// {15D22753-9D30-4929-AA14-5124016F7E68}\r\nFOOGUIDDECL const GUID mainmenu_groups::library = \r\n{ 0x15d22753, 0x9d30, 0x4929, { 0xaa, 0x14, 0x51, 0x24, 0x1, 0x6f, 0x7e, 0x68 } };\r\n\r\n// {25DC3DB7-996A-4f48-AF53-712032EFA04F}\r\nFOOGUIDDECL const GUID mainmenu_groups::help = \r\n{ 0x25dc3db7, 0x996a, 0x4f48, { 0xaf, 0x53, 0x71, 0x20, 0x32, 0xef, 0xa0, 0x4f } };\r\n\r\n// {8EED252D-0A0F-4fc9-9D81-8CF7209A8BF2}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_open = \r\n{ 0x8eed252d, 0xa0f, 0x4fc9, { 0x9d, 0x81, 0x8c, 0xf7, 0x20, 0x9a, 0x8b, 0xf2 } };\r\n\r\n// {9E650B8E-C3F3-4495-AF15-6B656060C3B9}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_add = \r\n{ 0x9e650b8e, 0xc3f3, 0x4495, { 0xaf, 0x15, 0x6b, 0x65, 0x60, 0x60, 0xc3, 0xb9 } };\r\n\r\n// {9995FAE6-B1C4-457f-A747-5BD120930210}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_playlist = \r\n{ 0x9995fae6, 0xb1c4, 0x457f, { 0xa7, 0x47, 0x5b, 0xd1, 0x20, 0x93, 0x2, 0x10 } };\r\n\r\n// {8A324F18-6173-42ec-A640-5E296AD446B3}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_etc = \r\n{ 0x8a324f18, 0x6173, 0x42ec, { 0xa6, 0x40, 0x5e, 0x29, 0x6a, 0xd4, 0x46, 0xb3 } };\r\n\r\n// {12F5E247-5A81-4734-8119-8F9BC114FE74}\r\nFOOGUIDDECL const GUID mainmenu_groups::playback_controls = \r\n{ 0x12f5e247, 0x5a81, 0x4734, { 0x81, 0x19, 0x8f, 0x9b, 0xc1, 0x14, 0xfe, 0x74 } };\r\n\r\n// {1169B3EB-81B5-4199-8929-7D3EAFD4809F}\r\nFOOGUIDDECL const GUID mainmenu_groups::playback_etc = \r\n{ 0x1169b3eb, 0x81b5, 0x4199, { 0x89, 0x29, 0x7d, 0x3e, 0xaf, 0xd4, 0x80, 0x9f } };\r\n\r\n// {29272FEC-21C7-4b00-A9A7-01A8CE675EBF}\r\nFOOGUIDDECL const GUID mainmenu_groups::view_visualisations = \r\n{ 0x29272fec, 0x21c7, 0x4b00, { 0xa9, 0xa7, 0x1, 0xa8, 0xce, 0x67, 0x5e, 0xbf } };\r\n\r\n// {2DA055D4-0257-40b2-8281-7967866B485C}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_etc_preferences = \r\n{ 0x2da055d4, 0x257, 0x40b2, { 0x82, 0x81, 0x79, 0x67, 0x86, 0x6b, 0x48, 0x5c } };\r\n\r\n// {517BFAE8-A148-4cb2-8CCE-1AD2179FB910}\r\nFOOGUIDDECL const GUID mainmenu_groups::file_etc_exit = \r\n{ 0x517bfae8, 0xa148, 0x4cb2, { 0x8c, 0xce, 0x1a, 0xd2, 0x17, 0x9f, 0xb9, 0x10 } };\r\n\r\n// {61190F78-3B3A-4fda-A431-2CF7DA1C96CE}\r\nFOOGUIDDECL const GUID mainmenu_groups::view_alwaysontop = \r\n{ 0x61190f78, 0x3b3a, 0x4fda, { 0xa4, 0x31, 0x2c, 0xf7, 0xda, 0x1c, 0x96, 0xce } };\r\n\r\n// {E55F8D65-AE51-47bf-99F9-BB113421CB19}\r\nFOOGUIDDECL const GUID mainmenu_groups::help_about = \r\n{ 0xe55f8d65, 0xae51, 0x47bf, { 0x99, 0xf9, 0xbb, 0x11, 0x34, 0x21, 0xcb, 0x19 } };\r\n\r\n// {696DF823-B7AE-4b73-95C8-C1E9A9410726}\r\nFOOGUIDDECL const GUID mainmenu_groups::library_refresh= \r\n{ 0x696df823, 0xb7ae, 0x4b73, { 0x95, 0xc8, 0xc1, 0xe9, 0xa9, 0x41, 0x7, 0x26 } };\r\n\r\n// {004BF6ED-2F88-464f-BDC1-278F6E610C2F}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_1s = \r\n{ 0x4bf6ed, 0x2f88, 0x464f, { 0xbd, 0xc1, 0x27, 0x8f, 0x6e, 0x61, 0xc, 0x2f } };\r\n\r\n// {5B56D124-2ECA-4b0f-9895-2A533B31D29E}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_5s = \r\n{ 0x5b56d124, 0x2eca, 0x4b0f, { 0x98, 0x95, 0x2a, 0x53, 0x3b, 0x31, 0xd2, 0x9e } };\r\n\r\n// {B582E3CA-D86D-4568-8380-68BC9C93ED0E}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_10s = \r\n{ 0xb582e3ca, 0xd86d, 0x4568, { 0x83, 0x80, 0x68, 0xbc, 0x9c, 0x93, 0xed, 0xe } };\r\n\r\n// {DE6B96B7-3074-4da9-A260-988E31CEE0F9}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_30s = \r\n{ 0xde6b96b7, 0x3074, 0x4da9, { 0xa2, 0x60, 0x98, 0x8e, 0x31, 0xce, 0xe0, 0xf9 } };\r\n\r\n// {FEED4AD7-13D2-4846-8833-D91B5F8B4E94}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_1min = \r\n{ 0xfeed4ad7, 0x13d2, 0x4846, { 0x88, 0x33, 0xd9, 0x1b, 0x5f, 0x8b, 0x4e, 0x94 } };\r\n\r\n// {ECCF4904-03CF-429a-9D99-7A87FA62FD10}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_2min = \r\n{ 0xeccf4904, 0x3cf, 0x429a, { 0x9d, 0x99, 0x7a, 0x87, 0xfa, 0x62, 0xfd, 0x10 } };\r\n\r\n// {5F0F0AF7-F519-41e6-A8DB-04DF1390E69D}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_5min = \r\n{ 0x5f0f0af7, 0xf519, 0x41e6, { 0xa8, 0xdb, 0x4, 0xdf, 0x13, 0x90, 0xe6, 0x9d } };\r\n\r\n// {9ABA4292-1B8F-42ac-93AC-34B2A74C6320}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_ahead_10min = \r\n{ 0x9aba4292, 0x1b8f, 0x42ac, { 0x93, 0xac, 0x34, 0xb2, 0xa7, 0x4c, 0x63, 0x20 } };\r\n\r\n// {2F89AB1C-5646-4997-8E3F-92BEE0322A41}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_1s = \r\n{ 0x2f89ab1c, 0x5646, 0x4997, { 0x8e, 0x3f, 0x92, 0xbe, 0xe0, 0x32, 0x2a, 0x41 } };\r\n\r\n// {0CE84538-2E21-4482-BFE1-BCEC471467CC}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_5s = \r\n{ 0xce84538, 0x2e21, 0x4482, { 0xbf, 0xe1, 0xbc, 0xec, 0x47, 0x14, 0x67, 0xcc } };\r\n\r\n// {9F504218-AF5D-41a8-BCE3-26313FAE65EE}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_10s = \r\n{ 0x9f504218, 0xaf5d, 0x41a8, { 0xbc, 0xe3, 0x26, 0x31, 0x3f, 0xae, 0x65, 0xee } };\r\n\r\n// {98239B89-F66E-4160-B650-D9B068C59E63}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_30s = \r\n{ 0x98239b89, 0xf66e, 0x4160, { 0xb6, 0x50, 0xd9, 0xb0, 0x68, 0xc5, 0x9e, 0x63 } };\r\n\r\n// {6633226B-9AA9-4810-AFDA-185A281D9FE2}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_1min = \r\n{ 0x6633226b, 0x9aa9, 0x4810, { 0xaf, 0xda, 0x18, 0x5a, 0x28, 0x1d, 0x9f, 0xe2 } };\r\n\r\n// {E2F8B8BB-C539-44f3-A300-13185DE52227}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_2min = \r\n{ 0xe2f8b8bb, 0xc539, 0x44f3, { 0xa3, 0x0, 0x13, 0x18, 0x5d, 0xe5, 0x22, 0x27 } };\r\n\r\n// {7B41A130-01D2-4a1b-9CAD-6314633C61C4}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_5min = \r\n{ 0x7b41a130, 0x1d2, 0x4a1b, { 0x9c, 0xad, 0x63, 0x14, 0x63, 0x3c, 0x61, 0xc4 } };\r\n\r\n// {0B012852-BAF9-4f6b-B947-FAB89AE76B79}\r\nFOOGUIDDECL const GUID standard_commands::guid_seek_back_10min = \r\n{ 0xb012852, 0xbaf9, 0x4f6b, { 0xb9, 0x47, 0xfa, 0xb8, 0x9a, 0xe7, 0x6b, 0x79 } };\r\n\r\n// {97215C5E-7228-4237-B52C-A2B5504EF726}\r\nFOOGUIDDECL const GUID playback_statistics_collector::class_guid = \r\n{ 0x97215c5e, 0x7228, 0x4237, { 0xb5, 0x2c, 0xa2, 0xb5, 0x50, 0x4e, 0xf7, 0x26 } };\r\n\r\n// {9FB1DA49-AF6F-4fd2-9C73-48A8A109003B}\r\nFOOGUIDDECL const GUID dsp_v2::class_guid = \r\n{ 0x9fb1da49, 0xaf6f, 0x4fd2, { 0x9c, 0x73, 0x48, 0xa8, 0xa1, 0x9, 0x0, 0x3b } };\r\n\r\n// {9EC5D45E-10F5-46a7-9546-F3ACEC68B149}\r\nFOOGUIDDECL const GUID dsp_entry_v2::class_guid = \r\n{ 0x9ec5d45e, 0x10f5, 0x46a7, { 0x95, 0x46, 0xf3, 0xac, 0xec, 0x68, 0xb1, 0x49 } };\r\n\r\n\r\nFOOGUIDDECL const GUID advconfig_entry::guid_root = { 0x34949f34, 0xe655, 0x4f09, { 0xba, 0x50, 0xfa, 0xeb, 0x4d, 0x9b, 0x77, 0x69 } };\r\nFOOGUIDDECL const GUID advconfig_entry::class_guid = { 0x7e84602e, 0xdc49, 0x4047, { 0xaa, 0xee, 0x63, 0x71, 0x8b, 0xbc, 0x5a, 0x1f } };\r\nFOOGUIDDECL const GUID advconfig_branch::class_guid = { 0x6a60b472, 0x91ac, 0x4681, { 0x9d, 0xc2, 0x76, 0xc9, 0x94, 0x0, 0x5b, 0x63 } };\r\nFOOGUIDDECL const GUID advconfig_entry_checkbox::class_guid = { 0x5243aba4, 0x2a3d, 0x4627, { 0x88, 0xef, 0xce, 0xe3, 0x76, 0x1c, 0x7, 0x9c } };\r\nFOOGUIDDECL const GUID advconfig_entry::guid_branch_tagging = { 0xe8fe273f, 0xdd00, 0x476e, { 0xa7, 0x90, 0xe5, 0x9d, 0xf6, 0xb8, 0xf8, 0xd4 } };\r\nFOOGUIDDECL const GUID advconfig_entry::guid_branch_decoding = { 0x904c272b, 0x2317, 0x4c3c, { 0xb2, 0xff, 0xc5, 0xa0, 0x12, 0x5e, 0x2c, 0xc2 } };\r\nFOOGUIDDECL const GUID advconfig_entry_string::class_guid = { 0x185d582d, 0xfbd8, 0x4db3, { 0xbe, 0x23, 0x47, 0xaa, 0xc6, 0x75, 0xfc, 0x11 } };\r\nFOOGUIDDECL const GUID advconfig_entry::guid_branch_tools = { 0x35365484, 0xcc58, 0x4926, { 0x97, 0xe1, 0x5e, 0x63, 0xf3, 0xab, 0xb9, 0xe2 } };\r\nFOOGUIDDECL const GUID advconfig_entry::guid_branch_playback = { 0xc48d430d, 0x112, 0x4922, { 0x97, 0x23, 0x28, 0x38, 0xc7, 0xd9, 0x7d, 0xd7 } };\r\nFOOGUIDDECL const GUID advconfig_entry::guid_branch_display = { 0x6c4bc1c8, 0xbaf4, 0x40c3, { 0x9d, 0xb1, 0x9, 0x50, 0x7f, 0xc, 0xc, 0xb9 } };\r\n\r\n\r\n\r\nFOOGUIDDECL const GUID playback_control_v2::class_guid = { 0x1eb67bda, 0x1345, 0x49ae, { 0x8e, 0x89, 0x50, 0x5, 0xd9, 0x1, 0x62, 0x89 } };\r\n\r\nFOOGUIDDECL const GUID preferences_page_v2::class_guid = { 0xce4ebc9e, 0xab20, 0x46f9, { 0x92, 0x5f, 0x88, 0x3b, 0x8, 0x4f, 0x5, 0x69 } };\r\nFOOGUIDDECL const GUID preferences_branch_v2::class_guid = { 0x167ebeb9, 0x8334, 0x4b21, { 0xaf, 0x58, 0xa7, 0x40, 0xa5, 0xd5, 0xb6, 0x66 } };\r\n\r\n\r\n\r\nFOOGUIDDECL const GUID advconfig_entry_enum::class_guid = { 0xb1451540, 0x98ec, 0x4d36, { 0x9f, 0x19, 0xe3, 0x10, 0xfb, 0xa7, 0xab, 0x5a } };\r\n\r\nFOOGUIDDECL const GUID info_lookup_handler::class_guid = { 0x4fcfdab7, 0x55b5, 0x47d6, { 0xb1, 0x9d, 0xa4, 0xdc, 0x9f, 0xd7, 0x69, 0x4c } };\r\n\r\nFOOGUIDDECL const GUID completion_notify::class_guid = { 0xdf26d586, 0xf7ec, 0x40c3, { 0x9f, 0xe8, 0x2e, 0xa0, 0x72, 0x5d, 0x76, 0xc0 } };\r\n\r\nFOOGUIDDECL const GUID metadb_io_v2::class_guid = { 0x265c4ece, 0xffb2, 0x4299, { 0x91, 0xb5, 0x6c, 0xa6, 0x60, 0x3d, 0xa1, 0x53 } };\r\n\r\nFOOGUIDDECL const GUID file_info_filter::class_guid = { 0x45d0b800, 0xde83, 0x4a77, { 0xad, 0x34, 0x3f, 0x84, 0x2d, 0x40, 0xe7, 0x95 } };\r\n\r\nFOOGUIDDECL const GUID metadb_hint_list::class_guid = { 0x719dc072, 0x8d4d, 0x4aa6, { 0xa6, 0xf3, 0x90, 0x73, 0x7, 0xe5, 0xbc, 0xee } };\r\n\r\nFOOGUIDDECL const GUID playlist_incoming_item_filter_v2::class_guid = { 0xf335802b, 0xa522, 0x434d, { 0xbe, 0x89, 0xe8, 0x6d, 0x59, 0x56, 0x16, 0x48 } };\r\n\r\nFOOGUIDDECL const GUID process_locations_notify::class_guid = { 0x7d7eddac, 0xf93e, 0x4707, { 0x96, 0x9b, 0xcf, 0x44, 0xa9, 0xe1, 0xfb, 0x78 } };\r\n\r\nFOOGUIDDECL const GUID library_manager_v2::class_guid = { 0x900eae79, 0x68d0, 0x4900, { 0xa4, 0xd8, 0x18, 0x20, 0x5, 0xae, 0x33, 0x7e } };\r\n\r\nFOOGUIDDECL const GUID packet_decoder::owner_Ogg = { 0x8fa27457, 0xa021, 0x43b9, { 0xad, 0x20, 0xa7, 0x96, 0xdb, 0x94, 0x7c, 0xd1 } };\r\n\r\nFOOGUIDDECL const GUID packet_decoder::property_ogg_header = { 0xbeb22c78, 0xeb49, 0x4f9e, { 0x9e, 0x37, 0x57, 0xd8, 0x87, 0x40, 0xfb, 0x4c } };\r\n\r\nFOOGUIDDECL const GUID packet_decoder::property_ogg_query_sample_rate = { 0x6226bf73, 0x1c37, 0x4aa1, { 0xae, 0xb1, 0x18, 0x8b, 0x4a, 0xf3, 0xae, 0xf7 } };\r\n\r\nFOOGUIDDECL const GUID packet_decoder::property_ogg_packet = { 0xade740be, 0x8e2e, 0x4d0b, { 0xa4, 0x0, 0x3f, 0x6e, 0x8a, 0xf7, 0x71, 0xe4 } };\r\n\r\nFOOGUIDDECL const GUID track_property_provider::class_guid = { 0xefcdd365, 0x81fc, 0x4c82, { 0x96, 0x1c, 0xa2, 0xb5, 0x76, 0x1a, 0xf8, 0xb7 } };\r\n\r\nFOOGUIDDECL const GUID library_manager_v3::class_guid = { 0x65e34e4d, 0xa9ab, 0x4c02, { 0x9e, 0x8a, 0xe5, 0xf3, 0xb9, 0x55, 0x8c, 0xbe } };\r\n\r\nFOOGUIDDECL const GUID core_version_info_v2::class_guid = { 0x273704d7, 0x99ba, 0x4b58, { 0xa0, 0x60, 0x82, 0xab, 0x1, 0xb4, 0x92, 0x25 } };"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/hasher_md5.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nGUID hasher_md5::guid_from_result(const hasher_md5_result & param)\r\n{\r\n\tassert(sizeof(GUID) == sizeof(hasher_md5_result));\r\n\tGUID temp = * reinterpret_cast<const GUID*>(&param);\r\n\tbyte_order::order_le_to_native_t(temp);\r\n\treturn temp;\r\n}\r\n\r\nhasher_md5_result hasher_md5::process_single(const void * p_buffer,t_size p_bytes)\r\n{\r\n\thasher_md5_state state;\r\n\tinitialize(state);\r\n\tprocess(state,p_buffer,p_bytes);\r\n\treturn get_result(state);\r\n}\r\n\r\nGUID hasher_md5::process_single_guid(const void * p_buffer,t_size p_bytes)\r\n{\r\n\treturn guid_from_result(process_single(p_buffer,p_bytes));\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/hasher_md5.h",
    "content": "struct hasher_md5_state {\r\n\tchar m_data[128];\r\n};\r\n\r\nstruct hasher_md5_result {\r\n\tchar m_data[16];\r\n};\r\n\r\ninline bool operator==(const hasher_md5_result & p_item1,const hasher_md5_result & p_item2) {return memcmp(&p_item1,&p_item2,sizeof(hasher_md5_result)) == 0;}\r\ninline bool operator!=(const hasher_md5_result & p_item1,const hasher_md5_result & p_item2) {return memcmp(&p_item1,&p_item2,sizeof(hasher_md5_result)) != 0;}\r\n\r\nnamespace pfc {\r\n\ttemplate<> class traits_t<hasher_md5_state> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<hasher_md5_result> : public traits_rawobject {};\r\n}\r\n\r\nclass NOVTABLE hasher_md5 : public service_base\r\n{\r\npublic:\r\n\r\n\tvirtual void initialize(hasher_md5_state & p_state) = 0;\r\n\tvirtual void process(hasher_md5_state & p_state,const void * p_buffer,t_size p_bytes) = 0;\r\n\tvirtual hasher_md5_result get_result(const hasher_md5_state & p_state) = 0;\r\n\r\n\t\r\n\tstatic GUID guid_from_result(const hasher_md5_result & param);\r\n\r\n\thasher_md5_result process_single(const void * p_buffer,t_size p_bytes);\r\n\tGUID process_single_guid(const void * p_buffer,t_size p_bytes);\r\n\tGUID get_result_guid(const hasher_md5_state & p_state) {return guid_from_result(get_result(p_state));}\r\n\r\n\t\r\n\t//! Helper\r\n\tvoid process_string(hasher_md5_state & p_state,const char * p_string,t_size p_length = infinite) {return process(p_state,p_string,pfc::strlen_max(p_string,p_length));}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(hasher_md5);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/info_lookup_handler.h",
    "content": "//! Service used to access various external (online) track info lookup services, such as freedb, to update file tags with info retrieved from those services.\r\nclass NOVTABLE info_lookup_handler : public service_base {\r\npublic:\r\n\tenum {\r\n\t\tflag_album_lookup = 1 << 0,\r\n\t\tflag_track_lookup = 1 << 1,\r\n\t};\r\n\r\n\t//! Retrieves human-readable name of the lookup handler to display in user interface.\r\n\tvirtual void get_name(pfc::string_base & p_out) = 0;\r\n\r\n\t//! Returns one or more of flag_track_lookup, and flag_album_lookup.\r\n\tvirtual t_uint32 get_flags() = 0; \r\n\r\n\tvirtual HICON get_icon(int p_width, int p_height) = 0;\r\n\r\n\t//! Performs a lookup. Creates a modeless dialog and returns immediately.\r\n\t//! @param p_items Items to look up.\r\n\t//! @param p_notify Callback to notify caller when the operation has completed. Call on_completion with status code 0 to signal failure/abort, or with code 1 to signal success / new infos in metadb.\r\n\t//! @param p_parent Parent window for the lookup dialog. Caller will typically disable the window while lookup is in progress and enable it back when completion is signaled.\r\n\tvirtual void lookup(const pfc::list_base_const_t<metadb_handle_ptr> & p_items,completion_notify_ptr p_notify,HWND p_parent) = 0;\r\n \r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(info_lookup_handler);\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/initquit.h",
    "content": "#ifndef _INITQUIT_H_\r\n#define _INITQUIT_H_\r\n\r\n#include \"service.h\"\r\n\r\n//init/quit callback, on_init is called after main window has been created, on_quit is called before main window is destroyed\r\nclass NOVTABLE initquit : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_init() {}\r\n\tvirtual void on_quit() {}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(initquit);\r\n};\r\n\r\ntemplate<typename T>\r\nclass initquit_factory_t : public service_factory_single_t<T> {};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/input.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nbool input_entry::g_find_service_by_path(service_ptr_t<input_entry> & p_out,const char * p_path)\r\n{\r\n\tservice_ptr_t<input_entry> ptr;\r\n\tservice_enum_t<input_entry> e;\r\n\tpfc::string_extension ext(p_path);\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->is_our_path(p_path,ext))\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool input_entry::g_find_service_by_content_type(service_ptr_t<input_entry> & p_out,const char * p_content_type)\r\n{\r\n\tservice_ptr_t<input_entry> ptr;\r\n\tservice_enum_t<input_entry> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->is_our_content_type(p_content_type))\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\nstatic void prepare_for_open(service_ptr_t<input_entry> & p_service,service_ptr_t<file> & p_file,const char * p_path,filesystem::t_open_mode p_open_mode,abort_callback & p_abort,bool p_from_redirect)\r\n{\r\n\tif (p_file.is_empty())\r\n\t{\r\n\t\tservice_ptr_t<filesystem> fs;\r\n\t\tif (filesystem::g_get_interface(fs,p_path)) {\r\n\t\t\tif (fs->supports_content_types()) {\r\n\t\t\t\tfs->open(p_file,p_path,p_open_mode,p_abort);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tif (p_file.is_valid())\r\n\t{\r\n\t\tpfc::string8 content_type;\r\n\t\tif (p_file->get_content_type(content_type))\r\n\t\t{\r\n\t\t\tif (input_entry::g_find_service_by_content_type(p_service,content_type))\r\n\t\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tif (input_entry::g_find_service_by_path(p_service,p_path))\r\n\t{\r\n\t\tif (p_from_redirect && p_service->is_redirect()) throw exception_io_unsupported_format();\r\n\t\treturn;\r\n\t}\r\n\r\n\tthrow exception_io_unsupported_format();\r\n}\r\n\r\nnamespace {\r\n\r\n\tbool g_find_inputs_by_content_type(pfc::list_base_t<service_ptr_t<input_entry> > & p_out,const char * p_content_type,bool p_from_redirect) {\r\n\t\tservice_enum_t<input_entry> e;\r\n\t\tservice_ptr_t<input_entry> ptr;\r\n\t\tbool ret = false;\r\n\t\twhile(e.next(ptr)) {\r\n\t\t\tif (!(p_from_redirect && ptr->is_redirect())) {\r\n\t\t\t\tif (ptr->is_our_content_type(p_content_type)) {p_out.add_item(ptr); ret = true;}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tbool g_find_inputs_by_path(pfc::list_base_t<service_ptr_t<input_entry> > & p_out,const char * p_path,bool p_from_redirect) {\r\n\t\tservice_enum_t<input_entry> e;\r\n\t\tservice_ptr_t<input_entry> ptr;\r\n\t\tpfc::string_extension extension(p_path);\r\n\t\tbool ret = false;\r\n\t\twhile(e.next(ptr)) {\r\n\t\t\tif (!(p_from_redirect && ptr->is_redirect())) {\r\n\t\t\t\tif (ptr->is_our_path(p_path,extension)) {p_out.add_item(ptr); ret = true;}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\ttemplate<typename t_service> void g_open_from_list(service_ptr_t<t_service> & p_instance,pfc::list_base_const_t<service_ptr_t<input_entry> > const & p_list,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {\r\n\t\tconst t_size count = p_list.get_count();\r\n\t\tif (count == 1) {\r\n\t\t\tp_list[0]->open(p_instance,p_filehint,p_path,p_abort);\r\n\t\t} else {\r\n\t\t\tbool got_bad_data = false, got_bad_data_multi = false;\r\n\t\t\tbool done = false;\r\n\t\t\tpfc::string8 bad_data_message;\r\n\t\t\tfor(t_size n=0;n<count && !done;n++) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tp_list[n]->open(p_instance,p_filehint,p_path,p_abort);\r\n\t\t\t\t\tdone = true;\r\n\t\t\t\t} catch(exception_io_unsupported_format) {\r\n\t\t\t\t\t//do nothing, skip over\r\n\t\t\t\t} catch(exception_io_data const & e) {\r\n\t\t\t\t\tif (!got_bad_data) bad_data_message = e.what();\r\n\t\t\t\t\telse got_bad_data_multi = true;\r\n\t\t\t\t\tgot_bad_data = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!done) {\r\n\t\t\t\tif (got_bad_data_multi) throw exception_io_data();\r\n\t\t\t\telse if (got_bad_data) throw exception_io_data(bad_data_message);\r\n\t\t\t\telse throw exception_io_unsupported_format();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_service> bool needs_write_access() {return false;}\r\n\ttemplate<> bool needs_write_access<input_info_writer>() {return true;}\r\n\r\n\ttemplate<typename t_service> void g_open_t(service_ptr_t<t_service> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) {\r\n\t\tservice_ptr_t<file> l_file = p_filehint;\r\n\t\tif (l_file.is_empty()) {\r\n\t\t\tservice_ptr_t<filesystem> fs;\r\n\t\t\tif (filesystem::g_get_interface(fs,p_path)) {\r\n\t\t\t\tif (fs->supports_content_types()) {\r\n\t\t\t\t\tfs->open(l_file,p_path,needs_write_access<t_service>() ? filesystem::open_mode_write_existing : filesystem::open_mode_read,p_abort);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (l_file.is_valid()) {\r\n\t\t\tpfc::string8 content_type;\r\n\t\t\tif (l_file->get_content_type(content_type)) {\r\n\t\t\t\tpfc::list_hybrid_t<service_ptr_t<input_entry>,4> list;\r\n\t\t\t\tif (g_find_inputs_by_content_type(list,content_type,p_from_redirect)) {\r\n\t\t\t\t\tg_open_from_list(p_instance,list,l_file,p_path,p_abort);\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\tpfc::list_hybrid_t<service_ptr_t<input_entry>,4> list;\r\n\t\t\tif (g_find_inputs_by_path(list,p_path,p_from_redirect)) {\r\n\t\t\t\tg_open_from_list(p_instance,list,l_file,p_path,p_abort);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tthrow exception_io_unsupported_format();\r\n\t}\r\n};\r\n\r\nvoid input_entry::g_open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) {\r\n#if 1\r\n\tg_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect);\r\n#else\r\n\tservice_ptr_t<file> filehint = p_filehint;\r\n\tservice_ptr_t<input_entry> entry;\r\n\r\n\tprepare_for_open(entry,filehint,p_path,filesystem::open_mode_read,p_abort,p_from_redirect);\r\n\r\n\tentry->open_for_decoding(p_instance,filehint,p_path,p_abort);\r\n#endif\r\n\r\n}\r\n\r\nvoid input_entry::g_open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) {\r\n#if 1\r\n\tg_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect);\r\n#else\r\n\tservice_ptr_t<file> filehint = p_filehint;\r\n\tservice_ptr_t<input_entry> entry;\r\n\r\n\tprepare_for_open(entry,filehint,p_path,filesystem::open_mode_read,p_abort,p_from_redirect);\r\n\r\n\tentry->open_for_info_read(p_instance,filehint,p_path,p_abort);\r\n#endif\r\n}\r\n\r\nvoid input_entry::g_open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect) {\r\n#if 1\r\n\tg_open_t(p_instance,p_filehint,p_path,p_abort,p_from_redirect);\r\n#else\r\n\tservice_ptr_t<file> filehint = p_filehint;\r\n\tservice_ptr_t<input_entry> entry;\r\n\r\n\tprepare_for_open(entry,filehint,p_path,filesystem::open_mode_write_existing,p_abort,p_from_redirect);\r\n\r\n\tentry->open_for_info_write(p_instance,filehint,p_path,p_abort);\r\n#endif\r\n}\r\n\r\nvoid input_entry::g_open_for_info_write_timeout(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,double p_timeout,bool p_from_redirect) {\r\n\tpfc::lores_timer timer;\r\n\ttimer.start();\r\n\tfor(;;) {\r\n\t\ttry {\r\n\t\t\tg_open_for_info_write(p_instance,p_filehint,p_path,p_abort,p_from_redirect);\r\n\t\t\tbreak;\r\n\t\t} catch(exception_io_sharing_violation) {\r\n\t\t\tif (timer.query() > p_timeout) throw;\r\n\t\t\tp_abort.sleep(0.01);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool input_entry::g_is_supported_path(const char * p_path)\r\n{\r\n\tservice_ptr_t<input_entry> ptr;\r\n\tservice_enum_t<input_entry> e;\r\n\tpfc::string_extension ext(p_path);\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->is_our_path(p_path,ext)) return true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\n\r\nvoid input_open_file_helper(service_ptr_t<file> & p_file,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort)\r\n{\r\n\tif (p_file.is_empty()) {\r\n\t\tswitch(p_reason) {\r\n\t\tdefault:\r\n\t\t\tthrow pfc::exception_bug_check();\r\n\t\tcase input_open_info_read:\r\n\t\tcase input_open_decode:\r\n\t\t\tfilesystem::g_open(p_file,p_path,filesystem::open_mode_read,p_abort);\r\n\t\t\tbreak;\r\n\t\tcase input_open_info_write:\r\n\t\t\tfilesystem::g_open(p_file,p_path,filesystem::open_mode_write_existing,p_abort);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t} else {\r\n\t\tp_file->reopen(p_abort);\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/input.h",
    "content": "enum {\r\n\tinput_flag_no_seeking\t\t\t\t\t= 1 << 0,\r\n\tinput_flag_no_looping\t\t\t\t\t= 1 << 1,\r\n\tinput_flag_playback\t\t\t\t\t\t= 1 << 2,\r\n\tinput_flag_testing_integrity\t\t\t= 1 << 3,\r\n\tinput_flag_allow_inaccurate_seeking\t\t= 1 << 4,\r\n\r\n\tinput_flag_simpledecode = input_flag_no_seeking|input_flag_no_looping,\r\n};\r\n\r\n//! Class providing interface for retrieval of information (metadata, duration, replaygain, other tech infos) from files. Also see: file_info. \\n\r\n//! Instantiating: see input_entry.\\n\r\n//! Implementing: see input_impl.\r\n\r\nclass input_info_reader : public service_base\r\n{\r\npublic:\r\n\t//! Retrieves count of subsongs in the file. 1 for non-multisubsong-enabled inputs.\r\n\t//! Note: multi-subsong handling is disabled for remote files (see: filesystem::is_remote) for performance reasons. Remote files are always assumed to be single-subsong, with null index.\r\n\tvirtual t_uint32 get_subsong_count() = 0;\r\n\t\r\n\t//! Retrieves identifier of specified subsong; this identifier is meant to be used in playable_location as well as a parameter for input_info_reader::get_info().\r\n\t//! @param p_index Index of subsong to query. Must be >=0 and < get_subsong_count().\r\n\tvirtual t_uint32 get_subsong(t_uint32 p_index) = 0;\r\n\t\r\n\t//! Retrieves information about specified subsong.\r\n\t//! @param p_subsong Identifier of the subsong to query. See: input_info_reader::get_subsong(), playable_location.\r\n\t//! @param p_info file_info object to fill. Must be empty on entry.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) = 0;\r\n\r\n\t//! Retrieves file stats. Equivalent to calling get_stats() on file object.\r\n\tvirtual t_filestats get_file_stats(abort_callback & p_abort) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(input_info_reader,service_base);\r\n};\r\n\r\n//! Class providing interface for retrieval of PCM audio data from files.\\n\r\n//! Instantiating: see input_entry.\\n\r\n//! Implementing: see input_impl.\r\n\r\nclass input_decoder : public input_info_reader\r\n{\r\npublic:\r\n\t//! Prepares to decode specified subsong; resets playback position to the beginning of specified subsong. This must be called first, before any other input_decoder methods (other than those inherited from input_info_reader). \\n\r\n\t//! It is legal to set initialize() more than once, with same or different subsong, to play either the same subsong again or another subsong from same file without full reopen.\\n\r\n\t//! Warning: this interface inherits from input_info_reader, it is legal to call any input_info_reader methods even during decoding! Call order is not defined, other than initialize() requirement before calling other input_decoder methods.\\n\r\n\t//! @param p_subsong Subsong to decode. Should always be 0 for non-multi-subsong-enabled inputs.\r\n\t//!\t@param p_flags Specifies additional hints for decoding process. It can be null, or a combination of one or more following constants: \\n\r\n\t//!\t\tinput_flag_no_seeking - Indicates that seek() will never be called. Can be used to avoid building potentially expensive seektables when only sequential reading is needed.\\n\r\n\t//!\t\tinput_flag_no_looping - Certain input implementations can be configured to utilize looping info from file formats they process and keep playing single file forever, or keep repeating it specified number of times. This flag indicates that such features should be disabled, for e.g. ReplayGain scan or conversion.\\n\r\n\t//!\t\tinput_flag_playback\t- Indicates that decoding process will be used for realtime playback rather than conversion. This can be used to reconfigure features that are relevant only for conversion and take a lot of resources, such as very slow secure CDDA reading. \\n\r\n\t//!\t\tinput_flag_testing_integrity - Indicates that we're testing integrity of the file. Any recoverable problems where decoding would normally continue should cause decoder to fail with exception_io_data.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) = 0;\r\n\r\n\t//! Reads/decodes one chunk of audio data. Use false return value to signal end of file (no more data to return). Before calling run(), decoding must be initialized by initialize() call.\r\n\t//! @param p_chunk audio_chunk object receiving decoded data. Contents are valid only the method returns true.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\t//! @returns true on success (new data decoded), false on EOF.\r\n\tvirtual bool run(audio_chunk & p_chunk,abort_callback & p_abort) = 0;\r\n\r\n\t//! Seeks to specified time offset. Before seeking or other decoding calls, decoding must be initialized with initialize() call.\r\n\t//! @param p_seconds Time to seek to, in seconds. If p_seconds exceeds length of the object being decoded, succeed, and then return false from next run() call.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void seek(double p_seconds,abort_callback & p_abort) = 0;\r\n\t\r\n\t//! Queries whether resource being read/decoded is seekable. If p_value is set to false, all seek() calls will fail. Before calling can_seek() or other decoding calls, decoding must be initialized with initialize() call.\r\n\tvirtual bool can_seek() = 0;\r\n\r\n\t//! This function is used to signal dynamic VBR bitrate, etc. Called after each run() (or not called at all if caller doesn't care about dynamic info).\r\n\t//! @param p_out Initially contains currently displayed info (either last get_dynamic_info result or current cached info), use this object to return changed info.\r\n\t//! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0.\r\n\t//! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed.\r\n\tvirtual bool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) = 0;\r\n\r\n\t//! This function is used to signal dynamic live stream song titles etc. Called after each run() (or not called at all if caller doesn't care about dynamic info). The difference between this and get_dynamic_info() is frequency and relevance of dynamic info changes - get_dynamic_info_track() returns new info only on track change in the stream, returning new titles etc.\r\n\t//! @param p_out Initially contains currently displayed info (either last get_dynamic_info_track result or current cached info), use this object to return changed info.\r\n\t//! @param p_timestamp_delta Indicates when returned info should be displayed (in seconds, relative to first sample of last decoded chunk), initially set to 0.\r\n\t//! @returns false to keep old info, or true to indicate that changes have been made to p_info and those should be displayed.\r\n\tvirtual bool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) = 0;\r\n\r\n\t//! Called from playback thread before sleeping.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void on_idle(abort_callback & p_abort) = 0;\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(input_decoder,input_info_reader);\r\n};\r\n\r\n//! Class providing interface for writing metadata and replaygain info to files. Also see: file_info. \\n\r\n//! Instantiating: see input_entry.\\n\r\n//! Implementing: see input_impl.\r\n\r\nclass input_info_writer : public input_info_reader\r\n{\r\npublic:\r\n\t//! Tells the service to update file tags with new info for specified subsong.\r\n\t//! @param p_subsong Subsong to update. Should be always 0 for non-multisubsong-enabled inputs.\r\n\t//! @param p_info New info to write. Sometimes not all contents of p_info can be written. Caller will typically read info back after successful write, so e.g. tech infos that change with retag are properly maintained.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first.\r\n\tvirtual void set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) = 0;\r\n\t\r\n\t//! Commits pending updates. In case of multisubsong inputs, set_info should queue the update and perform actual file access in commit(). Otherwise, actual writing can be done in set_info() and then Commit() can just do nothing and always succeed.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation. WARNING: abort_callback object is provided for consistency; if writing tags actually gets aborted, user will be likely left with corrupted file. Anything calling this should make sure that aborting is either impossible, or gives appropriate warning to the user first.\r\n\tvirtual void commit(abort_callback & p_abort) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(input_info_writer,input_info_reader);\r\n};\r\n\r\nclass input_entry : public service_base\r\n{\r\npublic:\r\n\t//! Determines whether specified content type can be handled by this input.\r\n\t//! @param p_type Content type string to test.\r\n\tvirtual bool is_our_content_type(const char * p_type)=0;\r\n\r\n\t//! Determines whether specified file type can be handled by this input. This must not use any kind of file access; the result should be only based on file path / extension.\r\n\t//! @param p_full_path Full URL of file being tested.\r\n\t//! @param p_extension Extension of file being tested, provided by caller for performance reasons.\r\n\tvirtual bool is_our_path(const char * p_full_path,const char * p_extension)=0;\r\n\t\r\n\t//! Opens specified resource for decoding.\r\n\t//! @param p_instance Receives new input_decoder instance if successful.\r\n\t//! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example).\r\n\t//! @param p_path URL of resource being opened.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0;\r\n\r\n\t//! Opens specified file for reading info.\r\n\t//! @param p_instance Receives new input_info_reader instance if successful.\r\n\t//! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example).\r\n\t//! @param p_path URL of resource being opened.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0;\r\n\r\n\t//! Opens specified file for writing info.\r\n\t//! @param p_instance Receives new input_info_writer instance if successful.\r\n\t//! @param p_filehint Optional; passes file object to use for the operation; if set to null, the service will handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example).\r\n\t//! @param p_path URL of resource being opened.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) = 0;\r\n\r\n\t//! Reserved for future use. Do nothing and return until specifications are finalized.\r\n\tvirtual void get_extended_data(service_ptr_t<file> p_filehint,const playable_location & p_location,const GUID & p_guid,mem_block_container & p_out,abort_callback & p_abort) = 0;\r\n\r\n\tenum {\r\n\t\t//! Indicates that this service implements some kind of redirector that opens another input for decoding, used to avoid circular call possibility.\r\n\t\tflag_redirect = 1,\r\n\t\t//! Indicates that multi-CPU optimizations should not be used.\r\n\t\tflag_parallel_reads_slow = 2,\r\n\t};\r\n\t//! See flag_* enums.\r\n\tvirtual unsigned get_flags() = 0;\r\n\r\n\tinline bool is_redirect() {return (get_flags() & flag_redirect) != 0;}\r\n\tinline bool are_parallel_reads_slow() {return (get_flags() & flag_parallel_reads_slow) != 0;}\r\n\r\n\tstatic bool g_find_service_by_path(service_ptr_t<input_entry> & p_out,const char * p_path);\r\n\tstatic bool g_find_service_by_content_type(service_ptr_t<input_entry> & p_out,const char * p_content_type);\r\n\tstatic void g_open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false);\r\n\tstatic void g_open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false);\r\n\tstatic void g_open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,bool p_from_redirect = false);\r\n\tstatic void g_open_for_info_write_timeout(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort,double p_timeout,bool p_from_redirect = false);\r\n\tstatic bool g_is_supported_path(const char * p_path);\r\n\r\n\r\n\tvoid open(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_decoding(p_instance,p_filehint,p_path,p_abort);}\r\n\tvoid open(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_read(p_instance,p_filehint,p_path,p_abort);}\r\n\tvoid open(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> const & p_filehint,const char * p_path,abort_callback & p_abort) {open_for_info_write(p_instance,p_filehint,p_path,p_abort);}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_entry);\r\n};\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/input_file_type.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid input_file_type::build_openfile_mask(pfc::string_base & out, bool b_include_playlists)\r\n{\r\n\tpfc::string8_fastalloc name,mask,mask_alltypes,out_temp;\r\n\t\r\n\tif (b_include_playlists)\r\n\t{\r\n\t\tservice_enum_t<playlist_loader> e;\r\n\t\tservice_ptr_t<playlist_loader> ptr;\r\n\t\tif (e.first(ptr)) do {\r\n\t\t\tif (!mask.is_empty()) mask += \";\";\r\n\t\t\tmask += \"*.\";\r\n\t\t\tmask += ptr->get_extension();\r\n\t\t} while(e.next(ptr));\r\n\t\tout_temp += \"Playlists\";\r\n\t\tout_temp += \"|\";\r\n\t\tout_temp += mask;\r\n\t\tout_temp += \"|\";\r\n\r\n\t\tif (!mask_alltypes.is_empty())\r\n\t\t{\r\n\t\t\tif (mask_alltypes[mask_alltypes.length()-1]!=';')\r\n\t\t\t\tmask_alltypes += \";\";\r\n\t\t}\r\n\t\tmask_alltypes += mask;\r\n\t}\r\n\r\n\t{\r\n\t\tservice_enum_t<input_file_type> e;\r\n\t\tservice_ptr_t<input_file_type> ptr;\r\n\t\tif (e.first(ptr)) do {\r\n\t\t\tunsigned n,m = ptr->get_count();\r\n\t\t\tfor(n=0;n<m;n++)\r\n\t\t\t{\r\n\t\t\t\tname.reset();\r\n\t\t\t\tmask.reset();\r\n\t\t\t\tif (ptr->get_name(n,name) && ptr->get_mask(n,mask))\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!strchr(name,'|') && !strchr(mask,'|'))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tout_temp += name;\r\n\t\t\t\t\t\tout_temp += \"|\";\r\n\t\t\t\t\t\tout_temp += mask;\r\n\t\t\t\t\t\tout_temp += \"|\";\r\n\t\t\t\t\t\tif (!mask_alltypes.is_empty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (mask_alltypes[mask_alltypes.length()-1]!=';')\r\n\t\t\t\t\t\t\t\tmask_alltypes += \";\";\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tmask_alltypes += mask;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} while(e.next(ptr));\r\n\t}\r\n\tout.reset();\r\n\tout += \"All files|*.*|\";\r\n\tif (!mask_alltypes.is_empty())\r\n\t{\r\n\t\tout += \"All supported types|\";\r\n\t\tout += mask_alltypes;\r\n\t\tout += \"|\";\r\n\t}\r\n\tout += out_temp;\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/input_file_type.h",
    "content": "class input_file_type : public service_base\r\n{\r\npublic:\r\n\tvirtual unsigned get_count()=0;\r\n\tvirtual bool get_name(unsigned idx,pfc::string_base & out)=0;//e.g. \"MPEG file\"\r\n\tvirtual bool get_mask(unsigned idx,pfc::string_base & out)=0;//e.g. \"*.MP3;*.MP2\"; separate with semicolons\r\n\tvirtual bool is_associatable(unsigned idx) = 0;\r\n\r\n\tstatic void build_openfile_mask(pfc::string_base & out,bool b_include_playlists=true);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(input_file_type);\r\n};\r\n\r\nclass input_file_type_impl : public service_impl_single_t<input_file_type>\r\n{\r\n\tconst char * name, * mask;\r\n\tbool m_associatable;\r\npublic:\r\n\tinput_file_type_impl(const char * p_name, const char * p_mask,bool p_associatable) : name(p_name), mask(p_mask), m_associatable(p_associatable) {}\r\n\tunsigned get_count() {return 1;}\r\n\tbool get_name(unsigned idx,pfc::string_base & out) {if (idx==0) {out = name; return true;} else return false;}\r\n\tbool get_mask(unsigned idx,pfc::string_base & out) {if (idx==0) {out = mask; return true;} else return false;}\r\n\tbool is_associatable(unsigned idx) {return m_associatable;}\r\n};\r\n\r\n\r\n#define DECLARE_FILE_TYPE(NAME,MASK) \\\r\n\tnamespace { static input_file_type_impl g_filetype_instance(NAME,MASK,true); \\\r\n\tstatic service_factory_single_ref_t<input_file_type_impl> g_filetype_service(g_filetype_instance); }\r\n\r\n\r\n//USAGE: DECLARE_FILE_TYPE(\"Blah file\",\"*.blah;*.bleh\");\r\n\r\nclass input_file_type_factory : private service_factory_single_transparent_t<input_file_type_impl>\r\n{\r\npublic:\r\n\tinput_file_type_factory(const char * p_name,const char * p_mask,bool p_associatable)\r\n\t\t: service_factory_single_transparent_t<input_file_type_impl>(p_name,p_mask,p_associatable) {}\r\n};\r\n\r\n\r\n//usage: static input_file_type_factory mytype(\"blah type\",\"*.bla;*.meh\",true)"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/input_impl.h",
    "content": "enum t_input_open_reason {\r\n\tinput_open_info_read,\r\n\tinput_open_decode,\r\n\tinput_open_info_write\r\n};\r\n\r\n//! Helper function for input implementation use; ensures that file is open with relevant access mode. This is typically called from input_impl::open() and such.\r\n//! @param p_file File object pointer to process. If passed pointer is non-null, the function does nothing and always succeeds; otherwise it attempts to open the file using filesystem API methods.\r\n//! @param p_path Path to the file.\r\n//! @param p_reason Type of input operation requested. See: input_impl::open() parameters.\r\n//! @param p_abort abort_callback object signaling user aborting the operation.\r\nvoid input_open_file_helper(service_ptr_t<file> & p_file,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort);\r\n\r\n\r\n//! This is a class that just declares prototypes of functions that each input needs to implement. See input_decoder / input_info_reader / input_info_writer interfaces for full descriptions of member functions. Since input implementation class is instantiated using a template, you don't need to derive from input_impl as virtual functions are not used on implementation class level. Use input_factory_t template to register input class based on input_impl.\r\nclass input_impl\r\n{\r\npublic:\r\n\t//! Opens specified file for info read / decoding / info write. This is called only once, immediately after object creation, before any other methods, and no other methods are called if open() fails.\r\n\t//! @param p_filehint Optional; passes file object to use for the operation; if set to null, the implementation should handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). Typically, an input implementation that requires file access calls input_open_file_helper() function to ensure that file is open with relevant access mode (read or read/write).\r\n\t//! @param p_path URL of resource being opened.\r\n\t//! @param p_reason Type of operation requested. Possible values are: \\n\r\n\t//! - input_open_info_read - info retrieval methods are valid; \\n\r\n\t//! - input_open_decode - info retrieval and decoding methods are valid; \\n\r\n\t//! - input_open_info_write - info retrieval and retagging methods are valid; \\n\r\n\t//! Note that info retrieval methods are valid in all cases, and they may be called at any point of decoding/retagging process. Results of info retrieval methods (other than get_subsong_count() / get_subsong()) between retag_set_info() and retag_commit() are undefined however; those should not be called during that period.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort);\r\n\r\n\t//! See: input_info_reader::get_subsong_count(). Valid after open() with any reason.\r\n\tunsigned get_subsong_count();\r\n\t//! See: input_info_reader::get_subsong(). Valid after open() with any reason.\r\n\tt_uint32 get_subsong(unsigned p_index);\r\n\t//! See: input_info_reader::get_info(). Valid after open() with any reason.\r\n\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort);\r\n\t//! See: input_info_reader::get_file_stats(). Valid after open() with any reason.\r\n\tt_filestats get_file_stats(abort_callback & p_abort);\r\n\r\n\t//! See: input_decoder::initialize(). Valid after open() with input_open_decode reason.\r\n\tvoid decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort);\r\n\t//! See: input_decoder::run(). Valid after decode_initialize().\r\n\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort);\r\n\t//! See: input_decoder::seek(). Valid after decode_initialize().\r\n\tvoid decode_seek(double p_seconds,abort_callback & p_abort);\r\n\t//! See: input_decoder::can_seek(). Valid after decode_initialize().\r\n\tbool decode_can_seek();\r\n\t//! See: input_decoder::get_dynamic_info(). Valid after decode_initialize().\r\n\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta);\r\n\t//! See: input_decoder::get_dynamic_info_track(). Valid after decode_initialize().\r\n\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta);\r\n\t//! See: input_decoder::on_idle(). Valid after decode_initialize().\r\n\tvoid decode_on_idle(abort_callback & p_abort);\r\n\r\n\t//! See: input_info_writer::set_info(). Valid after open() with input_open_info_write reason.\r\n\tvoid retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort);\r\n\t//! See: input_info_writer::commit(). Valid after open() with input_open_info_write reason.\r\n\tvoid retag_commit(abort_callback & p_abort);\t\r\n\t\r\n\t//! See: input_entry::is_our_content_type().\r\n\tstatic bool g_is_our_content_type(const char * p_content_type);\r\n\t//! See: input_entry::is_our_path().\r\n\tstatic bool g_is_our_path(const char * p_path,const char * p_extension);\r\n\r\nprotected:\r\n\tinput_impl() {}\r\n\t~input_impl() {}\r\n};\r\n\r\n//! This is a class that just declares prototypes of functions that each non-multitrack-enabled input needs to implement. See input_decoder / input_info_reader / input_info_writer interfaces for full descriptions of member functions. Since input implementation class is instantiated using a template, you don't need to derive from input_singletrack_impl as virtual functions are not used on implementation class level. Use input_singletrack_factory_t template to register input class based on input_singletrack_impl.\r\nclass input_singletrack_impl\r\n{\r\npublic:\r\n\t//! Opens specified file for info read / decoding / info write. This is called only once, immediately after object creation, before any other methods, and no other methods are called if open() fails.\r\n\t//! @param p_filehint Optional; passes file object to use for the operation; if set to null, the implementation should handle opening file by itself. Note that not all inputs operate on physical files that can be reached through filesystem API, some of them require this parameter to be set to null (tone and silence generators for an example). Typically, an input implementation that requires file access calls input_open_file_helper() function to ensure that file is open with relevant access mode (read or read/write).\r\n\t//! @param p_path URL of resource being opened.\r\n\t//! @param p_reason Type of operation requested. Possible values are: \\n\r\n\t//! - input_open_info_read - info retrieval methods are valid; \\n\r\n\t//! - input_open_decode - info retrieval and decoding methods are valid; \\n\r\n\t//! - input_open_info_write - info retrieval and retagging methods are valid; \\n\r\n\t//! Note that info retrieval methods are valid in all cases, and they may be called at any point of decoding/retagging process. Results of info retrieval methods (other than get_subsong_count() / get_subsong()) between retag_set_info() and retag_commit() are undefined however; those should not be called during that period.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort);\r\n\r\n\t//! See: input_info_reader::get_info(). Valid after open() with any reason. \\n\r\n\t//! Implementation warning: this is typically also called immediately after tag update and should return newly written content then.\r\n\tvoid get_info(file_info & p_info,abort_callback & p_abort);\r\n\t//! See: input_info_reader::get_file_stats(). Valid after open() with any reason. \\n\r\n\t//! Implementation warning: this is typically also called immediately after tag update and should return new values then.\r\n\tt_filestats get_file_stats(abort_callback & p_abort);\r\n\r\n\t//! See: input_decoder::initialize(). Valid after open() with input_open_decode reason.\r\n\tvoid decode_initialize(unsigned p_flags,abort_callback & p_abort);\r\n\t//! See: input_decoder::run(). Valid after decode_initialize().\r\n\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort);\r\n\t//! See: input_decoder::seek(). Valid after decode_initialize().\r\n\tvoid decode_seek(double p_seconds,abort_callback & p_abort);\r\n\t//! See: input_decoder::can_seek(). Valid after decode_initialize().\r\n\tbool decode_can_seek();\r\n\t//! See: input_decoder::get_dynamic_info(). Valid after decode_initialize().\r\n\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta);\r\n\t//! See: input_decoder::get_dynamic_info_track(). Valid after decode_initialize().\r\n\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta);\r\n\t//! See: input_decoder::on_idle(). Valid after decode_initialize().\r\n\tvoid decode_on_idle(abort_callback & p_abort);\r\n\r\n\t//! See: input_info_writer::set_info(). Note that input_info_writer::commit() call isn't forwarded because it's useless in case of non-multitrack-enabled inputs. Valid after open() with input_open_info_write reason.\r\n\tvoid retag(const file_info & p_info,abort_callback & p_abort);\r\n\t\r\n\t//! See: input_entry::is_our_content_type().\r\n\tstatic bool g_is_our_content_type(const char * p_content_type);\r\n\t//! See: input_entry::is_our_path().\r\n\tstatic bool g_is_our_path(const char * p_path,const char * p_extension);\r\n\r\nprotected:\r\n\tinput_singletrack_impl() {}\r\n\t~input_singletrack_impl() {}\r\n};\r\n\r\n\r\n//! Misc helper, documentme.\r\nclass input_singletrack_file_impl\r\n{\r\npublic:\r\n\tvoid open(service_ptr_t<file> p_file,t_input_open_reason p_reason,abort_callback & p_abort);\r\n\r\n\tvoid get_info(file_info & p_info,abort_callback & p_abort);\r\n\tt_filestats get_file_stats(abort_callback & p_abort);\r\n\r\n\tvoid decode_initialize(unsigned p_flags,abort_callback & p_abort);\r\n\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort);\r\n\tvoid decode_seek(double p_seconds,abort_callback & p_abort);\r\n\tbool decode_can_seek();\r\n\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta);\r\n\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta);\r\n\tvoid decode_on_idle(abort_callback & p_abort);\r\n\r\n\tvoid retag(file_info & p_info,abort_callback & p_abort);\r\n\t\r\n\tstatic bool g_is_our_content_type(const char * p_content_type);\r\n\tstatic bool g_is_our_path(const char * p_path,const char * p_extension);\r\n\r\nprotected:\r\n\tinput_singletrack_file_impl() {}\r\n\t~input_singletrack_file_impl() {}\r\n};\r\n\r\n//! Used internally by standard input_entry implementation; do not use directly. Translates input_decoder / input_info_reader / input_info_writer calls to input_impl calls.\r\ntemplate<class I, class t_base>\r\nclass input_impl_interface_wrapper_t : public t_base\r\n{\r\npublic:\r\n\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) {\r\n\t\tm_instance.open(p_filehint,p_path,p_reason,p_abort);\r\n\t}\r\n\r\n\t// input_info_reader methods\r\n\r\n\tt_uint32 get_subsong_count() {\r\n\t\treturn m_instance.get_subsong_count();\r\n\t}\r\n\t\r\n\tt_uint32 get_subsong(t_uint32 p_index) {\r\n\t\treturn m_instance.get_subsong(p_index);\r\n\t}\r\n\r\n\t\r\n\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {\r\n\t\tm_instance.get_info(p_subsong,p_info,p_abort);\r\n\t}\r\n\r\n\tt_filestats get_file_stats(abort_callback & p_abort) {\r\n\t\treturn m_instance.get_file_stats(p_abort);\r\n\t}\r\n\r\n\t// input_decoder methods\r\n\r\n\tvoid initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) {\r\n\t\tm_instance.decode_initialize(p_subsong,p_flags,p_abort);\r\n\t}\r\n\r\n\tbool run(audio_chunk & p_chunk,abort_callback & p_abort) {\r\n\t\treturn m_instance.decode_run(p_chunk,p_abort);\r\n\t}\r\n\r\n\tvoid seek(double p_seconds,abort_callback & p_abort) {\r\n\t\tm_instance.decode_seek(p_seconds,p_abort);\r\n\t}\r\n\t\r\n\tbool can_seek() {\r\n\t\treturn m_instance.decode_can_seek();\r\n\t}\r\n\r\n\tbool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {\r\n\t\treturn m_instance.decode_get_dynamic_info(p_out,p_timestamp_delta);\r\n\t}\r\n\r\n\tbool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {\r\n\t\treturn m_instance.decode_get_dynamic_info_track(p_out,p_timestamp_delta);\r\n\t}\r\n\r\n\tvoid on_idle(abort_callback & p_abort) {\r\n\t\tm_instance.decode_on_idle(p_abort);\r\n\t}\r\n\r\n\t// input_info_writer methods\r\n\r\n\tvoid set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) {\r\n\t\tm_instance.retag_set_info(p_subsong,p_info,p_abort);\r\n\t}\r\n\t\r\n\tvoid commit(abort_callback & p_abort) {\r\n\t\tm_instance.retag_commit(p_abort);\r\n\t}\r\n\t\r\nprivate:\r\n\tI m_instance;\r\n};\r\n\r\n//! Helper used by input_singletrack_factory_t, do not use directly. Translates input_impl calls to input_singletrack_impl calls. \r\ntemplate<class I>\r\nclass input_wrapper_singletrack_t\r\n{\r\npublic:\r\n\tinput_wrapper_singletrack_t() {}\r\n\r\n\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) {\r\n\t\tm_instance.open(p_filehint,p_path,p_reason,p_abort);\r\n\t}\r\n\r\n\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {\r\n\t\tif (p_subsong != 0) throw exception_io_data();\r\n\t\tm_instance.get_info(p_info,p_abort);\r\n\t}\r\n\r\n\tt_uint32 get_subsong_count() {\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tt_uint32 get_subsong(t_uint32 p_index) {\r\n\t\tassert(p_index == 0);\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tt_filestats get_file_stats(abort_callback & p_abort) {\r\n\t\treturn m_instance.get_file_stats(p_abort);\r\n\t}\r\n\r\n\tvoid decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) {\r\n\t\tif (p_subsong != 0) throw exception_io_data();\r\n\t\tm_instance.decode_initialize(p_flags,p_abort);\r\n\t}\r\n\r\n\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) {return m_instance.decode_run(p_chunk,p_abort);}\r\n\tvoid decode_seek(double p_seconds,abort_callback & p_abort) {m_instance.decode_seek(p_seconds,p_abort);}\r\n\tbool decode_can_seek() {return m_instance.decode_can_seek();}\r\n\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {return m_instance.decode_get_dynamic_info(p_out,p_timestamp_delta);}\r\n\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return m_instance.decode_get_dynamic_info_track(p_out,p_timestamp_delta);}\r\n\tvoid decode_on_idle(abort_callback & p_abort) {m_instance.decode_on_idle(p_abort);}\r\n\r\n\tvoid retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) {\r\n\t\tif (p_subsong != 0) throw exception_io_data();\r\n\t\tm_instance.retag(p_info,p_abort);\r\n\t}\r\n\t\r\n\tvoid retag_commit(abort_callback & p_abort) {}\r\n\r\n\tstatic bool g_is_our_content_type(const char * p_content_type) {return I::g_is_our_content_type(p_content_type);}\r\n\tstatic bool g_is_our_path(const char * p_path,const char * p_extension) {return I::g_is_our_path(p_path,p_extension);}\r\n\r\n\t\r\nprivate:\r\n\tI m_instance;\r\n};\r\n\r\n//! Helper; standard input_entry implementation. Do not instantiate this directly, use input_factory_t or one of other input_*_factory_t helpers instead.\r\ntemplate<class I,unsigned t_flags>\r\nclass input_entry_impl_t : public input_entry\r\n{\r\nprivate:\r\n\t\r\n\ttemplate<class T>\r\n\tvoid instantiate_t(service_ptr_t<T> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort)\r\n\t{\r\n\t\tservice_ptr_t< service_impl_t<input_impl_interface_wrapper_t<I,T> > > temp;\r\n\t\ttemp = new service_impl_t<input_impl_interface_wrapper_t<I,T> >();\r\n\t\ttemp->open(p_filehint,p_path,p_reason,p_abort);\r\n\t\tp_instance = temp.get_ptr();\r\n\t}\r\npublic:\r\n\tbool is_our_content_type(const char * p_type) {return I::g_is_our_content_type(p_type);}\r\n\tbool is_our_path(const char * p_full_path,const char * p_extension) {return I::g_is_our_path(p_full_path,p_extension);}\r\n\t\r\n\tvoid open_for_decoding(service_ptr_t<input_decoder> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) {\r\n\t\tinstantiate_t(p_instance,p_filehint,p_path,input_open_decode,p_abort);\r\n\t}\r\n\r\n\tvoid open_for_info_read(service_ptr_t<input_info_reader> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) {\r\n\t\tinstantiate_t(p_instance,p_filehint,p_path,input_open_info_read,p_abort);\r\n\t}\r\n\r\n\tvoid open_for_info_write(service_ptr_t<input_info_writer> & p_instance,service_ptr_t<file> p_filehint,const char * p_path,abort_callback & p_abort) {\r\n\t\tinstantiate_t(p_instance,p_filehint,p_path,input_open_info_write,p_abort);\r\n\t}\r\n\r\n\tvoid get_extended_data(service_ptr_t<file> p_filehint,const playable_location & p_location,const GUID & p_guid,mem_block_container & p_out,abort_callback & p_abort) {\r\n\t\tp_out.reset();\r\n\t}\r\n\r\n\tunsigned get_flags() {return t_flags;}\r\n};\r\n\r\n\r\n//! Stardard input factory. For reference of functions that must be supported by registered class, see input_impl.\\n Usage: static input_factory_t<myinputclass> g_myinputclass_factory;\\n Note that input classes can't be registered through service_factory_t template directly.\r\ntemplate<class T>\r\nclass input_factory_t : public service_factory_single_t<input_entry_impl_t<T,0> > {};\r\n\r\n//! Non-multitrack-enabled input factory (helper) - hides multitrack management functions from input implementation; use this for inputs that handle file types where each physical file can contain only one user-visible playable track. For reference of functions that must be supported by registered class, see input_singletrack_impl.\\n Usage: static input_singletrack_factory_t<myinputclass> g_myinputclass_factory;\\n Note that input classes can't be registered through service_factory_t template directly.template<class T>\r\ntemplate<class T>\r\nclass input_singletrack_factory_t : public service_factory_single_t<input_entry_impl_t<input_wrapper_singletrack_t<T>,0> > {};\r\n\r\n//! Extended version of input_factory_t, with non-default flags. See: input_factory_t, input_entry::get_flags().\r\ntemplate<class T,unsigned t_flags>\r\nclass input_factory_ex_t : public service_factory_single_t<input_entry_impl_t<T,t_flags> > {};\r\n\r\n//! Extended version of input_singletrack_factory_t, with non-default flags. See: input_singletrack_factory_t, input_entry::get_flags().\r\ntemplate<class T,unsigned t_flags>\r\nclass input_singletrack_factory_ex_t : public service_factory_single_t<input_entry_impl_t<input_wrapper_singletrack_t<T>,t_flags> > {};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/library_manager.h",
    "content": "#ifndef _foobar2000_sdk_library_manager_h_\r\n#define _foobar2000_sdk_library_manager_h_\r\n\r\n/*!\r\nThis service implements methods allowing you to interact with the Media Library.\\n\r\nAll methods are valid from main thread only.\\n\r\nTo avoid race conditions, methods that alter library contents should not be called from inside global callbacks.\\n\r\nUsage: Use static_api_ptr_t<library_manager> to instantiate.\r\n*/\r\n\r\nclass NOVTABLE library_manager : public service_base {\r\npublic:\r\n\t//! Interface for use with library_manager::enum_items().\r\n\tclass NOVTABLE enum_callback {\r\n\tpublic:\r\n\t\t//! Return true to continue enumeration, false to abort.\r\n\t\tvirtual bool on_item(const metadb_handle_ptr & p_item) = 0;\r\n\t};\r\n\r\n\t//! Returns whether specified item is in the Media Library or not.\r\n\tvirtual bool is_item_in_library(const metadb_handle_ptr & p_item) = 0;\r\n\t//! Returns whether current user settings allow specified item to be added to the Media Library or not.\r\n\tvirtual bool is_item_addable(const metadb_handle_ptr & p_item) = 0;\r\n\t//! Returns whether current user settings allow specified item path to be added to the Media Library or not.\r\n\tvirtual bool is_path_addable(const char * p_path) = 0;\r\n\t//! Retrieves path of specified item relative to Media Library directory it is in. Returns true on success, false when the item is not in the Media Library.\r\n\tvirtual bool get_relative_path(const metadb_handle_ptr & p_item,pfc::string_base & p_out) = 0;\r\n\t//! Calls callback method for every item in the Media Library. Note that order of items in Media Library is undefined.\r\n\tvirtual void enum_items(enum_callback & p_callback) = 0;\r\n\t//! Adds specified items to the Media Library (items actually added will be filtered according to user settings).\r\n\tvirtual void add_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\t//! Removes specified items from the Media Library (does nothing if specific item is not in the Media Library).\r\n\tvirtual void remove_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\t//! Adds specified items to the Media Library (items actually added will be filtered according to user settings). The difference between this and add_items() is that items are not added immediately; the operation is queued and executed later, so it is safe to call from e.g. global callbacks.\r\n\tvirtual void add_items_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\t\r\n\t//! For internal use only; p_data must be sorted by metadb::path_compare; use file_operation_callback static methods instead of calling this directly.\r\n\tvirtual void on_files_deleted_sorted(const pfc::list_base_const_t<const char *> & p_data) = 0;\r\n\r\n\t//! Retrieves entire Media Library content.\r\n\tvirtual void get_all_items(pfc::list_base_t<metadb_handle_ptr> & p_out) = 0;\r\n\r\n\t//! Returns whether Media Library functionality is enabled or not, for e.g. notifying user to change settings when trying to use a Media Library viewer without having configured Media Library first.\r\n\tvirtual bool is_library_enabled() = 0;\r\n\t//! Pops up Media Library preferences page.\r\n\tvirtual void show_preferences() = 0;\r\n\r\n\t//! Deprecated; use library_manager_v2::rescan_async() when possible.\\n\r\n\t//! Rescans user-specified Media Library directories for new files and removes references to files that no longer exist from the Media Library.\\n\r\n\t//! Note that this function creates modal dialog and does not return until the operation has completed.\\n\r\n\tvirtual void rescan() = 0;\r\n\t\r\n\t//! Deprecated; use library_manager_v2::check_dead_entries_async() when possible.\\n\r\n\t//! Hints Media Library about possible dead items, typically used for \"remove dead entries\" context action in ML viewers. The implementation will verify whether the items are actually dead before ML contents are altered.\\n\r\n\t//! Note that this function creates modal dialog and does not return until the operation has completed.\\n\r\n\tvirtual void check_dead_entries(const pfc::list_base_t<metadb_handle_ptr> & p_list) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_manager);\r\n};\r\n\r\n//! New in 0.9.3\r\nclass NOVTABLE library_manager_v2 : public library_manager {\r\npublic:\r\n\t//! Returns whether a rescan process is currently running.\r\n\tvirtual bool is_rescan_running() = 0;\r\n\r\n\t//! Starts an async rescan process. Note that if another process is already running, the process is silently aborted.\r\n\t//! @param p_parent Parent window for displayed progress dialog.\r\n\t//! @param p_notify Allows caller to receive notifications about the process finishing. Status code: 1 on success, 0 on user abort. Pass NULL if caller doesn't care.\r\n\tvirtual void rescan_async(HWND p_parent,completion_notify_ptr p_notify) = 0;\r\n\r\n\t//! Hints Media Library about possible dead items, typically used for \"remove dead entries\" context action in ML viewers. The implementation will verify whether the items are actually dead before ML contents are altered.\\n\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_parent Parent window for displayed progress dialog.\r\n\t//! @param p_notify Allows caller to receive notifications about the process finishing. Status code: 1 on success, 0 on user abort. Pass NULL if caller doesn't care.\r\n\tvirtual void check_dead_entries_async(const pfc::list_base_t<metadb_handle_ptr> & p_list,HWND p_parent,completion_notify_ptr p_notify) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(library_manager_v2,library_manager);\r\n};\r\n\r\n//! New in 0.9.4\r\nclass NOVTABLE library_manager_v3 : public library_manager_v2 {\r\npublic:\r\n\t//! Retrieves directory path and subdirectory/filename formatting scheme for newly encoded/copied/moved tracks.\r\n\t//! @returns True on success, false when the feature has not been configured.\r\n\tvirtual bool get_new_file_pattern_tracks(pfc::string_base & p_directory,pfc::string_base & p_format) = 0;\r\n\t//! Retrieves directory path and subdirectory/filename formatting scheme for newly encoded/copied/moved full album images.\r\n\t//! @returns True on success, false when the feature has not been configured.\r\n\tvirtual bool get_new_file_pattern_images(pfc::string_base & p_directory,pfc::string_base & p_format) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(library_manager_v3,library_manager_v2);\r\n};\r\n\r\n//! Callback service receiving notifications about Media Library content changes. Methods called only from main thread.\\n\r\n//! Use library_callback_factory_t template to register.\r\nclass NOVTABLE library_callback : public service_base {\r\npublic:\r\n\t//! Called when new items are added to the Media Library.\r\n\tvirtual void on_items_added(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\t//! Called when some items have been removed from the Media Library.\r\n\tvirtual void on_items_removed(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\t//! Called when some items in the Media Library have been modified.\r\n\tvirtual void on_items_modified(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_callback);\r\n};\r\n\r\ntemplate<typename T>\r\nclass library_callback_factory_t : public service_factory_single_t<T> {};\r\n\r\n//! Implement this service to appear on \"library viewers\" list in Media Library preferences page.\\n\r\n//! Use library_viewer_factory_t to register.\r\nclass NOVTABLE library_viewer : public service_base {\r\npublic:\r\n\t//! Retrieves GUID of your preferences page (pfc::guid_null if you don't have one).\r\n\tvirtual GUID get_preferences_page() = 0;\r\n\t//! Queries whether \"activate\" action is supported (relevant button will be disabled if it's not).\r\n\tvirtual bool have_activate() = 0;\r\n\t//! Activates your Media Library viewer component (e.g. shows its window).\r\n\tvirtual void activate() = 0;\r\n\t//! Retrieves GUID of your library_viewer implementation, for internal identification. Note that this not the same as preferences page GUID.\r\n\tvirtual GUID get_guid() = 0;\r\n\t//! Retrieves name of your Media Library viewer, a null-terminated UTF-8 encoded string.\r\n\tvirtual const char * get_name() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(library_viewer);\r\n};\r\n\r\ntemplate<typename T>\r\nclass library_viewer_factory_t : public service_factory_single_t<T> {};\r\n\r\n\r\n#endif _foobar2000_sdk_library_manager_h_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/link_resolver.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool link_resolver::g_find(service_ptr_t<link_resolver> & p_out,const char * p_path)\r\n{\r\n\tservice_enum_t<link_resolver> e;\r\n\tservice_ptr_t<link_resolver> ptr;\r\n\tpfc::string_extension ext(p_path);\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->is_our_path(p_path,ext))\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/link_resolver.h",
    "content": "#ifndef _foobar2000_sdk_link_resolver_h_\r\n#define _foobar2000_sdk_link_resolver_h_\r\n\r\n//! Interface for resolving different sorts of link files.\r\n//! Utilized by mechanisms that convert filesystem path into list of playable locations.\r\n//! For security reasons, link may only point to playable object path, not to a playlist or another link.\r\n\r\nclass NOVTABLE link_resolver : public service_base\r\n{\r\npublic:\r\n\r\n\t//! Tests whether specified file is supported by this link_resolver service.\r\n\t//! @param p_path Path of file being queried.\r\n\t//! @param p_extension Extension of file being queried. This is provided for performance reasons, path already includes it.\r\n\tvirtual bool is_our_path(const char * p_path,const char * p_extension) = 0;\r\n\r\n\t//! Resolves a link file. Before this is called, path must be accepted by is_our_path().\r\n\t//! @param p_filehint Optional file interface to use. If null/empty, implementation should open file by itself.\r\n\t//! @param p_path Path of link file to resolve.\r\n\t//! @param p_out Receives path the link is pointing to.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void resolve(service_ptr_t<file> p_filehint,const char * p_path,pfc::string_base & p_out,abort_callback & p_abort) = 0;\r\n\r\n\t//! Helper function; finds link_resolver interface that supports specified link file.\r\n\t//! @param p_out Receives link_resolver interface on success.\r\n\t//! @param p_path Path of file to query.\r\n\t//! @returns True on success, false on failure (no interface that supports specified path could be found).\r\n\tstatic bool g_find(service_ptr_t<link_resolver> & p_out,const char * p_path);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(link_resolver);\r\n};\r\n\r\n#endif //_foobar2000_sdk_link_resolver_h_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/main_thread_callback.h",
    "content": "//! Callback object class for main_thread_callback_manager service.\r\nclass NOVTABLE main_thread_callback : public service_base {\r\npublic:\r\n\t//! Gets called from main app thread. See main_thread_callback_manager description for more info.\r\n\tvirtual void callback_run() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(main_thread_callback,service_base);\r\n};\r\n\r\n/*!\r\nAllows you to queue a callback object to be called from main app thread. This is commonly used to trigger main-thread-only API calls from worker threads.\\n\r\nThis can be also used from main app thread, to avoid race conditions when trying to use APIs that dispatch global callbacks from inside some other global callback, or using message loops / modal dialogs inside global callbacks.\r\n*/\r\nclass NOVTABLE main_thread_callback_manager : public service_base {\r\npublic:\r\n\t//! Queues a callback object. This can be called from any thread, implementation ensures multithread safety. Implementation will call p_callback->callback_run() once later. To get it called repeatedly, you would need to add your callback again.\r\n\tvirtual void add_callback(service_ptr_t<main_thread_callback> p_callback) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(main_thread_callback_manager);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/mainmenu.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool mainmenu_commands::g_execute(const GUID & p_guid,service_ptr_t<service_base> p_callback) {\r\n\tservice_enum_t<mainmenu_commands> e;\r\n\tservice_ptr_t<mainmenu_commands> ptr;\r\n\twhile(e.next(ptr)) {\r\n\t\tconst t_uint32 count = ptr->get_command_count();\r\n\t\tfor(t_uint32 n=0;n<count;n++) {\r\n\t\t\tif (ptr->get_command(n) == p_guid) {\r\n\t\t\t\tptr->execute(n,p_callback);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool mainmenu_commands::g_find_by_name(const char * p_name,GUID & p_guid) {\r\n\tservice_enum_t<mainmenu_commands> e;\r\n\tservice_ptr_t<mainmenu_commands> ptr;\r\n\tpfc::string8_fastalloc temp;\r\n\twhile(e.next(ptr)) {\r\n\t\tconst t_uint32 count = ptr->get_command_count();\r\n\t\tfor(t_uint32 n=0;n<count;n++) {\r\n\t\t\tptr->get_name(n,temp);\r\n\t\t\tif (stricmp_utf8(temp,p_name) == 0) {\r\n\t\t\t\tp_guid = ptr->get_command(n);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/masstagger_action.h",
    "content": "#ifndef _FOOBAR2000_MASSTAG_ACTION_H_\r\n#define _FOOBAR2000_MASSTAG_ACTION_H_\r\n\r\nclass NOVTABLE masstagger_action : public service_base\r\n{\r\npublic:\r\n\t/**\r\n\t * Get name to display on list of available actions.\r\n\t * \\param p_out store name in here\r\n\t */\r\n\tvirtual void get_name(pfc::string_base & p_out)=0;\r\n\r\n\t/**\r\n\t * Initialize and show configuration with default values, if appropriate.\r\n\t * \\param p_parent handle to parent window\r\n\t * \\returns true iff succesful\r\n\t */\r\n\tvirtual bool initialize(HWND p_parent) = 0;\r\n\r\n\t/**\r\n\t * Initialize and get configuration from parameter.\r\n\t * \\param p_data a zero-terminated string containing previously stored configuration data.\r\n\t * \\returns true iff succesful\r\n\t */\r\n\tvirtual bool initialize_fromconfig(const char * p_data)=0;\r\n\r\n\t/**\r\n\t * Show configuration with current values.\r\n\t * \\param parent handle to parent window\r\n\t * \\returns true if display string needs to be updated.\r\n\t */\r\n\tvirtual bool configure(HWND p_parent) = 0;\r\n\r\n\t/**\r\n\t * Get name to display on list of configured actions.\r\n\t * You should include value of settings, if possible.\r\n\t * \\param p_name store name in here\r\n\t */\r\n\tvirtual void get_display_string(pfc::string_base & p_name) = 0;\r\n\r\n\t/**\r\n\t * Get current settings as zero-terminated string.\r\n\t * \\param p_data store settings in here\r\n\t */\r\n\tvirtual void get_config(pfc::string_base & p_data) = 0;\r\n\r\n\t/**\r\n\t * Apply action on file info.\r\n\t * \\param p_location location of current item\r\n\t * \\param p_info file info of current item, contains modifications from previous actions\r\n\t * \\param p_index zero-based index of current item in list of processed items\r\n\t * \\param p_count number of processed items\r\n\t */\r\n\tvirtual void run(const playable_location & p_location, file_info * p_info, t_size p_index, t_size p_count) = 0;\r\n\r\n\t/**\r\n\t * Get GUID.\r\n\t * Used for identification when storing scripts.\r\n\t * \\returns your GUID\r\n\t */\r\n\tvirtual const GUID & get_guid()=0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(masstagger_action);\r\n};\r\n\r\nDECLARE_CLASS_GUID(masstagger_action,0x49da1f6c, 0x6744, 0x47f3, 0xbf, 0x93, 0x67, 0x1c, 0x37, 0x79, 0xff, 0xcd);\r\n\r\ntemplate<typename T>\r\nclass masstagger_action_factory_t : public service_factory_t<T> {};\r\n\r\n#endif //_FOOBAR2000_MASSTAG_ACTION_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/mem_block_container.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid mem_block_container::from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort) {\r\n\tif (p_bytes == 0) {set_size(0);}\r\n\tset_size(p_bytes);\r\n\tp_stream->read_object(get_ptr(),p_bytes,p_abort);\r\n}\r\n\r\nvoid mem_block_container::set(const void * p_buffer,t_size p_size) {\r\n\tset_size(p_size);\r\n\tmemcpy(get_ptr(),p_buffer,p_size);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/mem_block_container.h",
    "content": "//! Generic interface for a memory block; used by various other interfaces to return memory blocks while allowing caller to allocate.\r\nclass NOVTABLE mem_block_container {\r\npublic:\r\n\tvirtual const void * get_ptr() const = 0;\r\n\tvirtual void * get_ptr() = 0;\r\n\tvirtual t_size get_size() const = 0;\r\n\tvirtual void set_size(t_size p_size) = 0;\r\n\t\r\n\tvoid from_stream(stream_reader * p_stream,t_size p_bytes,abort_callback & p_abort);\r\n\r\n\tvoid set(const void * p_buffer,t_size p_size);\r\n\r\n\tinline void copy(const mem_block_container & p_source) {set(p_source.get_ptr(),p_source.get_size());}\r\n\tinline void reset() {set_size(0);}\r\n\r\n\tconst mem_block_container & operator=(const mem_block_container & p_source) {copy(p_source);return *this;}\r\n\r\nprotected:\r\n\tmem_block_container() {}\r\n\t~mem_block_container() {}\r\n};\r\n\r\n//! mem_block_container implementation.\r\ntemplate<template<typename> class t_alloc = pfc::alloc_standard>\r\nclass mem_block_container_impl_t : public mem_block_container {\r\npublic:\r\n\tconst void * get_ptr() const {return m_data.get_ptr();}\r\n\tvoid * get_ptr() {return m_data.get_ptr();}\r\n\tt_size get_size() const {return m_data.get_size();}\r\n\tvoid set_size(t_size p_size) {\r\n\t\tm_data.set_size(p_size);\r\n\t}\r\nprivate:\r\n\tpfc::array_t<t_uint8,t_alloc> m_data;\r\n};\r\n\r\ntypedef mem_block_container_impl_t<> mem_block_container_impl;\r\n\r\nclass mem_block_container_temp_impl : public mem_block_container {\r\npublic:\r\n\tmem_block_container_temp_impl(void * p_buffer,t_size p_size) : m_buffer(p_buffer), m_buffer_size(p_size), m_size(0) {}\r\n\tconst void * get_ptr() const {return m_buffer;}\r\n\tvoid * get_ptr() {return m_buffer;}\r\n\tt_size get_size() const {return m_size;}\r\n\tvoid set_size(t_size p_size) {if (p_size > m_buffer_size) throw pfc::exception_overflow(); m_size = p_size;}\r\nprivate:\r\n\tt_size m_size,m_buffer_size;\r\n\tvoid * m_buffer;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/menu.h",
    "content": "class NOVTABLE mainmenu_group : public service_base {\r\npublic:\r\n\tvirtual GUID get_guid() = 0;\r\n\tvirtual GUID get_parent() = 0;\r\n\tvirtual t_uint32 get_sort_priority() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_group);\r\n};\r\n\r\nclass NOVTABLE mainmenu_group_popup : public mainmenu_group {\r\npublic:\r\n\tvirtual void get_display_string(pfc::string_base & p_out) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(mainmenu_group_popup,mainmenu_group);\r\n};\r\n\r\nclass NOVTABLE mainmenu_commands : public service_base {\r\npublic:\r\n\tenum {\r\n\t\tflag_disabled = 1<<0,\r\n\t\tflag_checked =\t1<<1,\r\n\t\tsort_priority_base = 0x10000,\r\n\t\tsort_priority_dontcare = 0x80000000,\r\n\t\tsort_priority_last = infinite,\r\n\t};\r\n\r\n\t//! Retrieves number of implemented commands. Index parameter of other methods must be in 0....command_count-1 range.\r\n\tvirtual t_uint32 get_command_count() = 0;\r\n\t//! Retrieves GUID of specified command.\r\n\tvirtual GUID get_command(t_uint32 p_index) = 0;\r\n\t//! Retrieves name of item, for list of commands to assign keyboard shortcuts to etc.\r\n\tvirtual void get_name(t_uint32 p_index,pfc::string_base & p_out) = 0;\r\n\t//! Retrieves item's description for statusbar etc.\r\n\tvirtual bool get_description(t_uint32 p_index,pfc::string_base & p_out) = 0;\r\n\t//! Retrieves GUID of owning menu group.\r\n\tvirtual GUID get_parent() = 0;\r\n\t//! Retrieves sorting priority of the command; the lower the number, the upper in the menu your commands will appear. Third party components should use sorting_priority_base and up (values below are reserved for internal use). In case of equal priority, order is undefined.\r\n\tvirtual t_uint32 get_sort_priority() {return sort_priority_dontcare;}\r\n\t//! Retrieves display string and display flags to use when menu is about to be displayed. If returns false, menu item won't be displayed. You can create keyboard-shortcut-only commands by always returning false from get_display().\r\n\tvirtual bool get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) {p_flags = 0;get_name(p_index,p_text);return true;}\r\n\t//! Executes the command. p_callback parameter is reserved for future use and should be ignored / set to null pointer.\r\n\tvirtual void execute(t_uint32 p_index,service_ptr_t<service_base> p_callback) = 0;\r\n\r\n\tstatic bool g_execute(const GUID & p_guid,service_ptr_t<service_base> p_callback = service_ptr_t<service_base>());\r\n\tstatic bool g_find_by_name(const char * p_name,GUID & p_guid);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_commands);\r\n};\r\n\r\nclass NOVTABLE mainmenu_manager : public service_base {\r\npublic:\r\n\tenum {\r\n\t\tflag_show_shortcuts = 1 << 0,\r\n\t\tflag_show_shortcuts_global = 1 << 1,\r\n\t};\r\n\r\n\tvirtual void instantiate(const GUID & p_root) = 0;\r\n\t\r\n#ifdef _WIN32\r\n\tvirtual void generate_menu_win32(HMENU p_menu,t_uint32 p_id_base,t_uint32 p_id_count,t_uint32 p_flags) = 0;\r\n#else\r\n#error portme\r\n#endif\r\n\t//@param p_id Identifier of command to execute, relative to p_id_base of generate_menu_*()\r\n\t//@returns true if command was executed successfully, false if not (e.g. command with given identifier not found).\r\n\tvirtual bool execute_command(t_uint32 p_id,service_ptr_t<service_base> p_callback = service_ptr_t<service_base>()) = 0;\r\n\r\n\tvirtual bool get_description(t_uint32 p_id,pfc::string_base & p_out) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(mainmenu_manager);\r\n};\r\n\r\nclass mainmenu_groups {\r\npublic:\r\n\tstatic const GUID file,view,edit,playback,library,help;\r\n\tstatic const GUID file_open,file_add,file_playlist,file_etc;\r\n\tstatic const GUID playback_controls,playback_etc;\r\n\tstatic const GUID view_visualisations, view_alwaysontop;\r\n\tstatic const GUID edit_part1,edit_part2,edit_part3;\r\n\tstatic const GUID edit_part2_selection,edit_part2_sort,edit_part2_selection_sort;\r\n\tstatic const GUID file_etc_preferences, file_etc_exit;\r\n\tstatic const GUID help_about;\r\n\tstatic const GUID library_refresh;\r\n\r\n\tenum {priority_edit_part1,priority_edit_part2,priority_edit_part3};\r\n\tenum {priority_edit_part2_commands,priority_edit_part2_selection,priority_edit_part2_sort};\r\n\tenum {priority_edit_part2_selection_commands,priority_edit_part2_selection_sort};\r\n\tenum {priority_file_open,priority_file_add,priority_file_playlist,priority_file_etc = mainmenu_commands::sort_priority_last};\r\n};\r\n\r\n\r\nclass mainmenu_group_impl : public mainmenu_group {\r\npublic:\r\n\tmainmenu_group_impl(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority) : m_guid(p_guid), m_parent(p_parent), m_priority(p_priority) {}\r\n\tGUID get_guid() {return m_guid;}\r\n\tGUID get_parent() {return m_parent;}\r\n\tt_uint32 get_sort_priority() {return m_priority;}\r\nprivate:\r\n\tGUID m_guid,m_parent; t_uint32 m_priority;\r\n};\r\n\r\nclass mainmenu_group_popup_impl : public mainmenu_group_popup {\r\npublic:\r\n\tmainmenu_group_popup_impl(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority,const char * p_name) : m_guid(p_guid), m_parent(p_parent), m_priority(p_priority), m_name(p_name) {}\r\n\tGUID get_guid() {return m_guid;}\r\n\tGUID get_parent() {return m_parent;}\r\n\tt_uint32 get_sort_priority() {return m_priority;}\r\n\tvoid get_display_string(pfc::string_base & p_out) {p_out = m_name;}\r\nprivate:\r\n\tGUID m_guid,m_parent; t_uint32 m_priority; pfc::string8 m_name;\r\n};\r\n\r\ntypedef service_factory_single_t<mainmenu_group_impl> __mainmenu_group_factory;\r\ntypedef service_factory_single_t<mainmenu_group_popup_impl> __mainmenu_group_popup_factory;\r\n\r\nclass mainmenu_group_factory : public __mainmenu_group_factory {\r\npublic:\r\n\tinline mainmenu_group_factory(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority) : __mainmenu_group_factory(p_guid,p_parent,p_priority) {}\r\n};\r\n\r\nclass mainmenu_group_popup_factory : public __mainmenu_group_popup_factory {\r\npublic:\r\n\tinline mainmenu_group_popup_factory(const GUID & p_guid,const GUID & p_parent,t_uint32 p_priority,const char * p_name) : __mainmenu_group_popup_factory(p_guid,p_parent,p_priority,p_name) {}\r\n};\r\n\r\ntemplate<typename T>\r\nclass mainmenu_commands_factory_t : public service_factory_single_t<T> {};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/menu_helpers.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nbool menu_helpers::context_get_description(const GUID& p_guid,pfc::string_base & out)\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tunsigned action,num_actions = ptr->get_num_items();\r\n\t\tfor(action=0;action<num_actions;action++)\r\n\t\t{\r\n\t\t\tif (p_guid == ptr->get_item_guid(action))\r\n\t\t\t{\r\n\t\t\t\tbool rv = ptr->get_item_description(action,out);\r\n\t\t\t\tif (!rv) out.reset();\r\n\t\t\t\treturn rv;\r\n\t\t\t}\r\n\t\t}\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n\r\nstatic bool run_context_command_internal(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller)\r\n{\r\n\tbool done = false;\r\n\tif (data.get_count() > 0) {\r\n\t\tservice_enum_t<contextmenu_item> e;\r\n\t\tservice_ptr_t<contextmenu_item> ptr;\r\n\t\tif (e.first(ptr)) do {\r\n\t\t\tunsigned action,num_actions = ptr->get_num_items();\r\n\t\t\tfor(action=0;action<num_actions;action++)\r\n\t\t\t{\r\n\t\t\t\tif (p_command == ptr->get_item_guid(action))\r\n\t\t\t\t{\r\n\t\t\t\t\tTRACK_CALL_TEXT(\"menu_helpers::run_command(), by GUID\");\r\n\t\t\t\t\tptr->item_execute_simple(action,p_subcommand,data,caller);\r\n\t\t\t\t\tdone = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (done) break;\r\n\t\t} while(e.next(ptr));\r\n\t}\r\n\treturn done;\r\n}\r\n\r\nbool menu_helpers::run_command_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data)\r\n{\r\n\treturn run_context_command_internal(p_command,p_subcommand,data,contextmenu_item::caller_undefined);\r\n}\r\n\r\nbool menu_helpers::run_command_context_ex(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller)\r\n{\r\n\treturn run_context_command_internal(p_command,p_subcommand,data,caller);\r\n}\r\n\r\nbool menu_helpers::test_command_context(const GUID & p_guid)\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tbool done = false;\r\n\tif (e.first(ptr)) do {\r\n\t\tunsigned action,num_actions = ptr->get_num_items();\r\n\t\tfor(action=0;action<num_actions;action++)\r\n\t\t{\r\n\t\t\tif (ptr->get_item_guid(action) == p_guid)\r\n\t\t\t{\r\n\t\t\t\tdone = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (done) break;\r\n\t} while(e.next(ptr));\r\n\treturn done;\r\n}\r\n\r\nstatic bool g_is_checked(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller)\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tbool done = false, rv = false;\r\n\tpfc::string8_fastalloc dummystring;\r\n\tif (e.first(ptr)) do {\r\n\t\tunsigned action,num_actions = ptr->get_num_items();\r\n\t\tfor(action=0;action<num_actions;action++)\r\n\t\t{\r\n\t\t\tif (p_command == ptr->get_item_guid(action))\r\n\t\t\t{\r\n\t\t\t\tunsigned displayflags = 0;\r\n\t\t\t\tif (ptr->item_get_display_data(dummystring,displayflags,action,p_subcommand,data,caller))\r\n\t\t\t\t{\r\n\t\t\t\t\trv = !!(displayflags & contextmenu_item_node::FLAG_CHECKED);\r\n\t\t\t\t\tdone = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (done) break;\r\n\t} while(e.next(ptr));\r\n\treturn rv;\r\n}\r\n\r\nbool menu_helpers::is_command_checked_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data)\r\n{\r\n\treturn g_is_checked(p_command,p_subcommand,data,contextmenu_item::caller_undefined);\r\n}\r\n\r\nbool menu_helpers::is_command_checked_context_playlist(const GUID & p_command,const GUID & p_subcommand)\r\n{\r\n\tmetadb_handle_list temp;\r\n\tstatic_api_ptr_t<playlist_manager> api;\r\n\tapi->activeplaylist_get_selected_items(temp);\r\n\treturn g_is_checked(p_command,p_subcommand,temp,contextmenu_item::caller_playlist);\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nbool menu_helpers::run_command_context_playlist(const GUID & p_command,const GUID & p_subcommand)\r\n{\r\n\tmetadb_handle_list temp;\r\n\tstatic_api_ptr_t<playlist_manager> api;\r\n\tapi->activeplaylist_get_selected_items(temp);\r\n\treturn run_command_context_ex(p_command,p_subcommand,temp,contextmenu_item::caller_playlist);\r\n}\r\n\r\nbool menu_helpers::run_command_context_now_playing(const GUID & p_command,const GUID & p_subcommand)\r\n{\r\n\tmetadb_handle_ptr item;\r\n\tif (!static_api_ptr_t<playback_control>()->get_now_playing(item)) return false;//not playing\r\n\treturn run_command_context_ex(p_command,p_subcommand,pfc::list_single_ref_t<metadb_handle_ptr>(item),contextmenu_item::caller_now_playing);\r\n}\r\n\r\n\r\nbool menu_helpers::guid_from_name(const char * p_name,unsigned p_name_len,GUID & p_out)\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tpfc::string8_fastalloc nametemp;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tunsigned n, m = ptr->get_num_items();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t{\r\n\t\t\tptr->get_item_name(n,nametemp);\r\n\t\t\tif (!strcmp_ex(nametemp,infinite,p_name,p_name_len))\r\n\t\t\t{\r\n\t\t\t\tp_out = ptr->get_item_guid(n);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool menu_helpers::name_from_guid(const GUID & p_guid,pfc::string_base & p_out)\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tpfc::string8_fastalloc nametemp;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tunsigned n, m = ptr->get_num_items();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t{\r\n\t\t\tif (p_guid == ptr->get_item_guid(n))\r\n\t\t\t{\r\n\t\t\t\tptr->get_item_name(n,p_out);\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\n\r\nstatic unsigned calc_total_action_count()\r\n{\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tunsigned ret = 0;\r\n\twhile(e.next(ptr))\r\n\t\tret += ptr->get_num_items();\r\n\treturn ret;\r\n}\r\n\r\n\r\nconst char * menu_helpers::guid_to_name_table::search(const GUID & p_guid)\r\n{\r\n\tif (!m_inited)\r\n\t{\r\n\t\tm_data.set_size(calc_total_action_count());\r\n\t\tt_size dataptr = 0;\r\n\t\tpfc::string8_fastalloc nametemp;\r\n\r\n\t\tservice_enum_t<contextmenu_item> e;\r\n\t\tservice_ptr_t<contextmenu_item> ptr;\r\n\t\twhile(e.next(ptr))\r\n\t\t{\r\n\t\t\tunsigned n, m = ptr->get_num_items();\r\n\t\t\tfor(n=0;n<m;n++)\r\n\t\t\t{\r\n\t\t\t\tassert(dataptr < m_data.get_size());\r\n\r\n\t\t\t\tptr->get_item_name(n,nametemp);\r\n\t\t\t\tm_data[dataptr].m_name = strdup(nametemp);\r\n\t\t\t\tm_data[dataptr].m_guid = ptr->get_item_guid(n);\r\n\t\t\t\tdataptr++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tassert(dataptr == m_data.get_size());\r\n\r\n\t\tpfc::sort_t(m_data,entry_compare,m_data.get_size());\r\n\t\tm_inited = true;\r\n\t}\r\n\tt_size index;\r\n\tif (pfc::bsearch_t(m_data.get_size(),m_data,entry_compare_search,p_guid,index))\r\n\t\treturn m_data[index].m_name;\r\n\telse\r\n\t\treturn 0;\r\n}\r\n\r\nint menu_helpers::guid_to_name_table::entry_compare_search(const entry & entry1,const GUID & entry2)\r\n{\r\n\treturn pfc::guid_compare(entry1.m_guid,entry2);\r\n}\r\n\r\nint menu_helpers::guid_to_name_table::entry_compare(const entry & entry1,const entry & entry2)\r\n{\r\n\treturn pfc::guid_compare(entry1.m_guid,entry2.m_guid);\r\n}\r\n\r\nmenu_helpers::guid_to_name_table::guid_to_name_table()\r\n{\r\n\tm_inited = false;\r\n}\r\n\r\nmenu_helpers::guid_to_name_table::~guid_to_name_table()\r\n{\r\n\tt_size n, m = m_data.get_size();\r\n\tfor(n=0;n<m;n++) free(m_data[n].m_name);\r\n\r\n}\r\n\r\n\r\nint menu_helpers::name_to_guid_table::entry_compare_search(const entry & entry1,const search_entry & entry2)\r\n{\r\n\treturn stricmp_utf8_ex(entry1.m_name,infinite,entry2.m_name,entry2.m_name_len);\r\n}\r\n\r\nint menu_helpers::name_to_guid_table::entry_compare(const entry & entry1,const entry & entry2)\r\n{\r\n\treturn stricmp_utf8(entry1.m_name,entry2.m_name);\r\n}\r\n\r\nbool menu_helpers::name_to_guid_table::search(const char * p_name,unsigned p_name_len,GUID & p_out)\r\n{\r\n\tif (!m_inited)\r\n\t{\r\n\t\tm_data.set_size(calc_total_action_count());\r\n\t\tt_size dataptr = 0;\r\n\t\tpfc::string8_fastalloc nametemp;\r\n\r\n\t\tservice_enum_t<contextmenu_item> e;\r\n\t\tservice_ptr_t<contextmenu_item> ptr;\r\n\t\twhile(e.next(ptr))\r\n\t\t{\r\n\t\t\tunsigned n, m = ptr->get_num_items();\r\n\t\t\tfor(n=0;n<m;n++)\r\n\t\t\t{\r\n\t\t\t\tassert(dataptr < m_data.get_size());\r\n\r\n\t\t\t\tptr->get_item_name(n,nametemp);\r\n\t\t\t\tm_data[dataptr].m_name = strdup(nametemp);\r\n\t\t\t\tm_data[dataptr].m_guid = ptr->get_item_guid(n);\r\n\t\t\t\tdataptr++;\r\n\t\t\t}\r\n\t\t}\r\n\t\tassert(dataptr == m_data.get_size());\r\n\r\n\t\tpfc::sort_t(m_data,entry_compare,m_data.get_size());\r\n\t\tm_inited = true;\r\n\t}\r\n\tt_size index;\r\n\tsearch_entry temp = {p_name,p_name_len};\r\n\tif (pfc::bsearch_t(m_data.get_size(),m_data,entry_compare_search,temp,index))\r\n\t{\r\n\t\tp_out = m_data[index].m_guid;\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t\treturn false;\r\n}\r\n\r\nmenu_helpers::name_to_guid_table::name_to_guid_table()\r\n{\r\n\tm_inited = false;\r\n}\r\n\r\nmenu_helpers::name_to_guid_table::~name_to_guid_table()\r\n{\r\n\tt_size n, m = m_data.get_size();\r\n\tfor(n=0;n<m;n++) free(m_data[n].m_name);\r\n\r\n}\r\n\r\nbool menu_helpers::find_command_by_name(const char * p_name,service_ptr_t<contextmenu_item> & p_item,unsigned & p_index)\r\n{\r\n\tpfc::string8_fastalloc path,name;\r\n\tservice_enum_t<contextmenu_item> e;\r\n\tservice_ptr_t<contextmenu_item> ptr;\r\n\tif (e.first(ptr)) do {\r\n//\t\tif (ptr->get_type()==type)\r\n\t\t{\r\n\t\t\tunsigned action,num_actions = ptr->get_num_items();\r\n\t\t\tfor(action=0;action<num_actions;action++)\r\n\t\t\t{\r\n\t\t\t\tptr->get_item_default_path(action,path); ptr->get_item_name(action,name);\r\n\t\t\t\tif (!path.is_empty()) path += \"/\";\r\n\t\t\t\tpath += name;\r\n\t\t\t\tif (!stricmp_utf8(p_name,path))\r\n\t\t\t\t{\r\n\t\t\t\t\tp_item = ptr;\r\n\t\t\t\t\tp_index = action;\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n\r\n}\r\n\r\nbool menu_helpers::find_command_by_name(const char * p_name,GUID & p_command)\r\n{\r\n\tservice_ptr_t<contextmenu_item> item;\r\n\tunsigned index;\r\n\tbool ret = find_command_by_name(p_name,item,index);\r\n\tif (ret) p_command = item->get_item_guid(index);\r\n\treturn ret;\r\n}\r\n\r\n\r\nbool standard_commands::run_main(const GUID & p_guid) {\r\n\tservice_enum_t<mainmenu_commands> e;\r\n\tservice_ptr_t<mainmenu_commands> ptr;\r\n\twhile(e.next(ptr)) {\r\n\t\tconst t_size count = ptr->get_command_count();\r\n\t\tfor(t_size n=0;n<count;n++) {\r\n\t\t\tif (ptr->get_command(n) == p_guid) {\r\n\t\t\t\tptr->execute(n,service_ptr_t<service_base>());\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/menu_helpers.h",
    "content": "namespace menu_helpers {\r\n#ifdef _WIN32\r\n\tvoid win32_auto_mnemonics(HMENU menu);\r\n#endif\r\n\r\n\tbool run_command_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data);\r\n\tbool run_command_context_ex(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data,const GUID & caller);\r\n\tbool run_command_context_playlist(const GUID & p_command,const GUID & p_subcommand);\r\n\tbool run_command_context_now_playing(const GUID & p_command,const GUID & p_subcommand);\r\n\r\n\tbool test_command_context(const GUID & p_guid);\r\n\r\n\tbool is_command_checked_context(const GUID & p_command,const GUID & p_subcommand,const pfc::list_base_const_t<metadb_handle_ptr> & data);\r\n\tbool is_command_checked_context_playlist(const GUID & p_command,const GUID & p_subcommand);\r\n\r\n\tbool find_command_by_name(const char * p_name,service_ptr_t<contextmenu_item> & p_item,unsigned & p_index);\r\n\tbool find_command_by_name(const char * p_name,GUID & p_command);\r\n\t\r\n\tbool context_get_description(const GUID& p_guid,pfc::string_base & out);\r\n\r\n\tbool guid_from_name(const char * p_name,unsigned p_name_len,GUID & p_out);\r\n\tbool name_from_guid(const GUID & p_guid,pfc::string_base & p_out);\r\n\r\n\tclass guid_to_name_table\r\n\t{\r\n\tpublic:\r\n\t\tguid_to_name_table();\r\n\t\t~guid_to_name_table();\r\n\t\tconst char * search(const GUID & p_guid);\r\n\tprivate:\r\n\t\tstruct entry {\r\n\t\t\tchar* m_name;\r\n\t\t\tGUID m_guid;\r\n\t\t};\r\n\t\tpfc::array_t<entry> m_data;\r\n\t\tbool m_inited;\r\n\r\n\t\tstatic int entry_compare_search(const entry & entry1,const GUID & entry2);\r\n\t\tstatic int entry_compare(const entry & entry1,const entry & entry2);\r\n\t};\r\n\r\n\tclass name_to_guid_table\r\n\t{\r\n\tpublic:\r\n\t\tname_to_guid_table();\r\n\t\t~name_to_guid_table();\r\n\t\tbool search(const char * p_name,unsigned p_name_len,GUID & p_out);\r\n\tprivate:\r\n\t\tstruct entry {\r\n\t\t\tchar* m_name;\r\n\t\t\tGUID m_guid;\r\n\t\t};\r\n\t\tpfc::array_t<entry> m_data;\r\n\t\tbool m_inited;\r\n\t\tstruct search_entry {\r\n\t\t\tconst char * m_name; unsigned m_name_len;\r\n\t\t};\r\n\r\n\t\tstatic int entry_compare_search(const entry & entry1,const search_entry & entry2);\r\n\t\tstatic int entry_compare(const entry & entry1,const entry & entry2);\r\n\t};\r\n\r\n};\r\n\r\n\r\n\r\nclass standard_commands\r\n{\r\npublic:\r\n\tstatic const GUID\r\n\t\tguid_context_file_properties,\tguid_context_file_open_directory,\tguid_context_copy_names,\r\n\t\tguid_context_send_to_playlist,\tguid_context_reload_info,\t\t\tguid_context_reload_info_if_changed,\r\n\t\tguid_context_rewrite_info,\t\tguid_context_remove_tags,\t\t\tguid_context_remove_from_database,\r\n\t\tguid_context_convert_run,\t\tguid_context_convert_run_singlefile,guid_context_convert_run_withcue,\r\n\t\tguid_context_write_cd,\r\n\t\tguid_context_rg_scan_track,\t\tguid_context_rg_scan_album,\t\t\tguid_context_rg_scan_album_multi,\r\n\t\tguid_context_rg_remove,\t\t\tguid_context_save_playlist,\t\t\tguid_context_masstag_edit,\r\n\t\tguid_context_masstag_rename,\r\n\t\tguid_main_always_on_top,\t\tguid_main_preferences,\t\t\t\tguid_main_about,\r\n\t\tguid_main_exit,\t\t\t\t\tguid_main_restart,\t\t\t\t\tguid_main_activate,\r\n\t\tguid_main_hide,\t\t\t\t\tguid_main_activate_or_hide,\t\t\tguid_main_titleformat_help,\r\n\t\tguid_main_next,\t\t\t\t\tguid_main_previous,\r\n\t\tguid_main_next_or_random,\t\tguid_main_random,\t\t\t\t\tguid_main_pause,\r\n\t\tguid_main_play,\t\t\t\t\tguid_main_play_or_pause,\t\t\tguid_main_rg_set_album,\r\n\t\tguid_main_rg_set_track,\t\t\tguid_main_rg_disable,\t\t\t\tguid_main_stop,\r\n\t\tguid_main_stop_after_current,\tguid_main_volume_down,\t\t\t\tguid_main_volume_up,\r\n\t\tguid_main_volume_mute,\t\t\tguid_main_add_directory,\t\t\tguid_main_add_files,\r\n\t\tguid_main_add_location,\t\t\tguid_main_add_playlist,\t\t\t\tguid_main_clear_playlist,\r\n\t\tguid_main_create_playlist,\t\tguid_main_highlight_playing,\t\tguid_main_load_playlist,\r\n\t\tguid_main_next_playlist,\t\tguid_main_previous_playlist,\t\tguid_main_open,\r\n\t\tguid_main_remove_playlist,\t\tguid_main_remove_dead_entries,\t\tguid_main_remove_duplicates,\r\n\t\tguid_main_rename_playlist,\t\tguid_main_save_all_playlists,\t\tguid_main_save_playlist,\r\n\t\tguid_main_playlist_search,\t\tguid_main_playlist_sel_crop,\t\tguid_main_playlist_sel_remove,\r\n\t\tguid_main_playlist_sel_invert,\tguid_main_playlist_undo,\t\t\tguid_main_show_console,\r\n\t\tguid_main_play_cd,\t\t\t\tguid_main_restart_resetconfig,\t\tguid_main_record,\r\n\t\tguid_main_playlist_moveback,\tguid_main_playlist_moveforward,\t\tguid_main_playlist_redo,\r\n\t\tguid_main_playback_follows_cursor,\tguid_main_cursor_follows_playback, guid_main_saveconfig,\r\n\t\tguid_main_playlist_select_all,\tguid_main_show_now_playing,\r\n\r\n\t\tguid_seek_ahead_1s,\t\t\t\tguid_seek_ahead_5s,\t\t\t\t\tguid_seek_ahead_10s,\t\t\t\tguid_seek_ahead_30s,\r\n\t\tguid_seek_ahead_1min,\t\t\tguid_seek_ahead_2min,\t\t\t\tguid_seek_ahead_5min,\t\t\t\tguid_seek_ahead_10min,\r\n\r\n\t\tguid_seek_back_1s,\t\t\t\tguid_seek_back_5s,\t\t\t\t\tguid_seek_back_10s,\t\t\t\t\tguid_seek_back_30s,\r\n\t\tguid_seek_back_1min,\t\t\tguid_seek_back_2min,\t\t\t\tguid_seek_back_5min,\t\t\t\tguid_seek_back_10min\r\n\t\t;\r\n\r\n\tstatic bool run_main(const GUID & guid);\r\n\tstatic inline bool run_context(const GUID & guid,const pfc::list_base_const_t<metadb_handle_ptr> &data) {return menu_helpers::run_command_context(guid,pfc::guid_null,data);}\r\n\tstatic inline bool run_context(const GUID & guid,const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller) {return menu_helpers::run_command_context_ex(guid,pfc::guid_null,data,caller);}\r\n\r\n\tstatic inline bool context_file_properties(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_file_properties,data,caller);}\r\n\tstatic inline bool context_file_open_directory(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_file_open_directory,data,caller);}\r\n\tstatic inline bool context_copy_names(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_copy_names,data,caller);}\r\n\tstatic inline bool context_send_to_playlist(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_send_to_playlist,data,caller);}\r\n\tstatic inline bool context_reload_info(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_reload_info,data,caller);}\r\n\tstatic inline bool context_reload_info_if_changed(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_reload_info_if_changed,data,caller);}\r\n\tstatic inline bool context_rewrite_info(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rewrite_info,data,caller);}\r\n\tstatic inline bool context_remove_tags(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_remove_tags,data,caller);}\r\n\tstatic inline bool context_remove_from_database(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_remove_from_database,data,caller);}\r\n\tstatic inline bool context_convert_run(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_convert_run,data,caller);}\r\n\tstatic inline bool context_convert_run_singlefile(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_convert_run_singlefile,data,caller);}\r\n\tstatic inline bool context_write_cd(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_write_cd,data,caller);}\r\n\tstatic inline bool context_rg_scan_track(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_track,data,caller);}\r\n\tstatic inline bool context_rg_scan_album(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_album,data,caller);}\r\n\tstatic inline bool context_rg_scan_album_multi(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_scan_album_multi,data,caller);}\r\n\tstatic inline bool context_rg_remove(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_rg_remove,data,caller);}\r\n\tstatic inline bool context_save_playlist(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_save_playlist,data,caller);}\r\n\tstatic inline bool context_masstag_edit(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_masstag_edit,data,caller);}\r\n\tstatic inline bool context_masstag_rename(const pfc::list_base_const_t<metadb_handle_ptr> &data,const GUID& caller = contextmenu_item::caller_undefined) {return run_context(guid_context_masstag_rename,data,caller);}\r\n\tstatic inline bool main_always_on_top() {return run_main(guid_main_always_on_top);}\r\n\tstatic inline bool main_preferences() {return run_main(guid_main_preferences);}\r\n\tstatic inline bool main_about() {return run_main(guid_main_about);}\r\n\tstatic inline bool main_exit() {return run_main(guid_main_exit);}\r\n\tstatic inline bool main_restart() {return run_main(guid_main_restart);}\r\n\tstatic inline bool main_activate() {return run_main(guid_main_activate);}\r\n\tstatic inline bool main_hide() {return run_main(guid_main_hide);}\r\n\tstatic inline bool main_activate_or_hide() {return run_main(guid_main_activate_or_hide);}\r\n\tstatic inline bool main_titleformat_help() {return run_main(guid_main_titleformat_help);}\r\n\tstatic inline bool main_playback_follows_cursor() {return run_main(guid_main_playback_follows_cursor);}\r\n\tstatic inline bool main_next() {return run_main(guid_main_next);}\r\n\tstatic inline bool main_previous() {return run_main(guid_main_previous);}\r\n\tstatic inline bool main_next_or_random() {return run_main(guid_main_next_or_random);}\r\n\tstatic inline bool main_random() {return run_main(guid_main_random);}\r\n\tstatic inline bool main_pause() {return run_main(guid_main_pause);}\r\n\tstatic inline bool main_play() {return run_main(guid_main_play);}\r\n\tstatic inline bool main_play_or_pause() {return run_main(guid_main_play_or_pause);}\r\n\tstatic inline bool main_rg_set_album() {return run_main(guid_main_rg_set_album);}\r\n\tstatic inline bool main_rg_set_track() {return run_main(guid_main_rg_set_track);}\r\n\tstatic inline bool main_rg_disable() {return run_main(guid_main_rg_disable);}\r\n\tstatic inline bool main_stop() {return run_main(guid_main_stop);}\r\n\tstatic inline bool main_stop_after_current() {return run_main(guid_main_stop_after_current);}\r\n\tstatic inline bool main_volume_down() {return run_main(guid_main_volume_down);}\r\n\tstatic inline bool main_volume_up() {return run_main(guid_main_volume_up);}\r\n\tstatic inline bool main_volume_mute() {return run_main(guid_main_volume_mute);}\r\n\tstatic inline bool main_add_directory() {return run_main(guid_main_add_directory);}\r\n\tstatic inline bool main_add_files() {return run_main(guid_main_add_files);}\r\n\tstatic inline bool main_add_location() {return run_main(guid_main_add_location);}\r\n\tstatic inline bool main_add_playlist() {return run_main(guid_main_add_playlist);}\r\n\tstatic inline bool main_clear_playlist() {return run_main(guid_main_clear_playlist);}\r\n\tstatic inline bool main_create_playlist() {return run_main(guid_main_create_playlist);}\r\n\tstatic inline bool main_highlight_playing() {return run_main(guid_main_highlight_playing);}\r\n\tstatic inline bool main_load_playlist() {return run_main(guid_main_load_playlist);}\r\n\tstatic inline bool main_next_playlist() {return run_main(guid_main_next_playlist);}\r\n\tstatic inline bool main_previous_playlist() {return run_main(guid_main_previous_playlist);}\r\n\tstatic inline bool main_open() {return run_main(guid_main_open);}\r\n\tstatic inline bool main_remove_playlist() {return run_main(guid_main_remove_playlist);}\r\n\tstatic inline bool main_remove_dead_entries() {return run_main(guid_main_remove_dead_entries);}\r\n\tstatic inline bool main_remove_duplicates() {return run_main(guid_main_remove_duplicates);}\r\n\tstatic inline bool main_rename_playlist() {return run_main(guid_main_rename_playlist);}\r\n\tstatic inline bool main_save_all_playlists() {return run_main(guid_main_save_all_playlists);}\r\n\tstatic inline bool main_save_playlist() {return run_main(guid_main_save_playlist);}\r\n\tstatic inline bool main_playlist_search() {return run_main(guid_main_playlist_search);}\r\n\tstatic inline bool main_playlist_sel_crop() {return run_main(guid_main_playlist_sel_crop);}\r\n\tstatic inline bool main_playlist_sel_remove() {return run_main(guid_main_playlist_sel_remove);}\r\n\tstatic inline bool main_playlist_sel_invert() {return run_main(guid_main_playlist_sel_invert);}\r\n\tstatic inline bool main_playlist_undo() {return run_main(guid_main_playlist_undo);}\r\n\tstatic inline bool main_show_console() {return run_main(guid_main_show_console);}\r\n\tstatic inline bool main_play_cd() {return run_main(guid_main_play_cd);}\r\n\tstatic inline bool main_restart_resetconfig() {return run_main(guid_main_restart_resetconfig);}\r\n\tstatic inline bool main_playlist_moveback() {return run_main(guid_main_playlist_moveback);}\r\n\tstatic inline bool main_playlist_moveforward() {return run_main(guid_main_playlist_moveforward);}\r\n\tstatic inline bool main_saveconfig() {return run_main(guid_main_saveconfig);}\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/menu_item.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\n\r\nbool contextmenu_item::item_get_display_data_root(pfc::string_base & p_out,unsigned & p_displayflags,unsigned p_index,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller)\r\n{\r\n\tbool status = false;\r\n\tpfc::ptrholder_t<contextmenu_item_node_root> root ( instantiate_item(p_index,p_data,p_caller) );\r\n\tif (root.is_valid()) status = root->get_display_data(p_out,p_displayflags,p_data,p_caller);\r\n\treturn status;\r\n}\r\n\r\n\r\nstatic contextmenu_item_node * g_find_node(const GUID & p_guid,contextmenu_item_node * p_parent)\r\n{\r\n\tif (p_parent->get_guid() == p_guid) return p_parent;\r\n\telse if (p_parent->get_type() == contextmenu_item_node::TYPE_POPUP)\r\n\t{\r\n\t\tt_size n, m = p_parent->get_children_count();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t{\r\n\t\t\tcontextmenu_item_node * temp = g_find_node(p_guid,p_parent->get_child(n));\r\n\t\t\tif (temp) return temp;\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\telse return 0;\r\n}\r\n\r\nbool contextmenu_item::item_get_display_data(pfc::string_base & p_out,unsigned & p_displayflags,unsigned p_index,const GUID & p_node,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const GUID & p_caller)\r\n{\r\n\tbool status = false;\r\n\tpfc::ptrholder_t<contextmenu_item_node_root> root ( instantiate_item(p_index,p_data,p_caller) );\r\n\tif (root.is_valid())\r\n\t{\r\n\t\tcontextmenu_item_node * node = g_find_node(p_node,root.get_ptr());\r\n\t\tif (node) status = node->get_display_data(p_out,p_displayflags,p_data,p_caller);\r\n\t}\r\n\treturn status;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/menu_manager.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n#ifdef WIN32\r\n\r\nstatic void fix_ampersand(const char * src,pfc::string_base & out)\r\n{\r\n\tunsigned ptr = 0;\r\n\twhile(src[ptr])\r\n\t{\r\n\t\tif (src[ptr]=='&')\r\n\t\t{\r\n\t\t\tout.add_string(\"&&\");\r\n\t\t\tptr++;\r\n\t\t\twhile(src[ptr]=='&')\r\n\t\t\t{\r\n\t\t\t\tout.add_string(\"&&\");\r\n\t\t\t\tptr++;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse out.add_byte(src[ptr++]);\r\n\t}\r\n}\r\n\r\nstatic unsigned flags_to_win32(unsigned flags)\r\n{\r\n\tunsigned ret = 0;\r\n\tif (flags & contextmenu_item_node::FLAG_CHECKED) ret |= MF_CHECKED;\r\n\tif (flags & contextmenu_item_node::FLAG_DISABLED) ret |= MF_DISABLED;\r\n\tif (flags & contextmenu_item_node::FLAG_GRAYED) ret |= MF_GRAYED;\r\n\treturn ret;\r\n}\r\n\r\nvoid contextmenu_manager::win32_build_menu(HMENU menu,contextmenu_node * parent,int base_id,int max_id)//menu item identifiers are base_id<=N<base_id+max_id (if theres too many items, they will be clipped)\r\n{\r\n\tif (parent!=0 && parent->get_type()==contextmenu_item_node::TYPE_POPUP)\r\n\t{\r\n\t\tpfc::string8_fastalloc temp;\r\n\t\tt_size child_idx,child_num = parent->get_num_children();\r\n\t\tfor(child_idx=0;child_idx<child_num;child_idx++)\r\n\t\t{\r\n\t\t\tcontextmenu_node * child = parent->get_child(child_idx);\r\n\t\t\tif (child)\r\n\t\t\t{\r\n\t\t\t\tconst char * name = child->get_name();\r\n\t\t\t\tif (strchr(name,'&')) {fix_ampersand(name,temp);name=temp;}\r\n\t\t\t\tcontextmenu_item_node::t_type type = child->get_type();\r\n\t\t\t\tif (type==contextmenu_item_node::TYPE_POPUP)\r\n\t\t\t\t{\r\n\t\t\t\t\tHMENU new_menu = CreatePopupMenu();\r\n\t\t\t\t\tuAppendMenu(menu,MF_STRING|MF_POPUP | flags_to_win32(child->get_display_flags()),(UINT_PTR)new_menu,name);\r\n\t\t\t\t\twin32_build_menu(new_menu,child,base_id,max_id);\r\n\t\t\t\t}\r\n\t\t\t\telse if (type==contextmenu_item_node::TYPE_SEPARATOR)\r\n\t\t\t\t{\r\n\t\t\t\t\tuAppendMenu(menu,MF_SEPARATOR,0,0);\r\n\t\t\t\t}\r\n\t\t\t\telse if (type==contextmenu_item_node::TYPE_COMMAND)\r\n\t\t\t\t{\r\n\t\t\t\t\tint id = child->get_id();\r\n\t\t\t\t\tif (id>=0 && (max_id<0 || id<max_id))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tuAppendMenu(menu,MF_STRING | flags_to_win32(child->get_display_flags()),base_id+id,name);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\r\n\r\nbool contextmenu_manager::execute_by_id(unsigned id)\r\n{\r\n\tbool rv = false;\r\n\tcontextmenu_node * ptr = find_by_id(id);\r\n\tif (ptr) {rv=true;ptr->execute();}\r\n\treturn rv;\r\n}\r\n\r\n#ifdef WIN32\r\n\r\nvoid contextmenu_manager::win32_run_menu_popup(HWND parent,const POINT * pt)\r\n{\r\n\tenum {ID_CUSTOM_BASE = 1};\r\n\r\n\tint cmd;\r\n\r\n\t{\r\n\t\tPOINT p;\r\n\t\tif (pt) p = *pt;\r\n\t\telse GetCursorPos(&p);\r\n\t\t\r\n\t\tHMENU hmenu = CreatePopupMenu();\r\n\t\ttry {\r\n\t\t\r\n\t\t\twin32_build_menu(hmenu,ID_CUSTOM_BASE,-1);\r\n\t\t\tmenu_helpers::win32_auto_mnemonics(hmenu);\r\n\r\n\t\t\tcmd = TrackPopupMenu(hmenu,TPM_RIGHTBUTTON|TPM_NONOTIFY|TPM_RETURNCMD,p.x,p.y,0,parent,0);\r\n\t\t} catch(...) {DestroyMenu(hmenu); throw;}\r\n\t\t\r\n\t\tDestroyMenu(hmenu);\r\n\t}\t\t\t\r\n\r\n\tif (cmd>0)\r\n\t{\r\n\t\tif (cmd>=ID_CUSTOM_BASE)\r\n\t\t{\r\n\t\t\texecute_by_id(cmd - ID_CUSTOM_BASE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid contextmenu_manager::win32_run_menu_context(HWND parent,const pfc::list_base_const_t<metadb_handle_ptr> & data,const POINT * pt,unsigned flags)\r\n{\r\n\tservice_ptr_t<contextmenu_manager> manager;\r\n\tcontextmenu_manager::g_create(manager);\r\n\tmanager->init_context(data,flags);\r\n\tmanager->win32_run_menu_popup(parent,pt);\r\n}\r\n\r\nvoid contextmenu_manager::win32_run_menu_context_playlist(HWND parent,const POINT * pt,unsigned flags)\r\n{\r\n\tservice_ptr_t<contextmenu_manager> manager;\r\n\tcontextmenu_manager::g_create(manager);\r\n\tmanager->init_context_playlist(flags);\r\n\tmanager->win32_run_menu_popup(parent,pt);\r\n}\r\n\r\n\r\nnamespace {\r\n\tclass mnemonic_manager\r\n\t{\r\n\t\tpfc::string8_fastalloc used;\r\n\t\tbool is_used(unsigned c)\r\n\t\t{\r\n\t\t\tchar temp[8];\r\n\t\t\ttemp[pfc::utf8_encode_char(char_lower(c),temp)]=0;\r\n\t\t\treturn !!strstr(used,temp);\r\n\t\t}\r\n\r\n\t\tstatic bool is_alphanumeric(char c)\r\n\t\t{\r\n\t\t\treturn (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9');\r\n\t\t}\r\n\r\n\r\n\r\n\r\n\t\tvoid insert(const char * src,unsigned idx,pfc::string_base & out)\r\n\t\t{\r\n\t\t\tout.reset();\r\n\t\t\tout.add_string(src,idx);\r\n\t\t\tout.add_string(\"&\");\r\n\t\t\tout.add_string(src+idx);\r\n\t\t\tused.add_char(char_lower(src[idx]));\r\n\t\t}\r\n\tpublic:\r\n\t\tbool check_string(const char * src)\r\n\t\t{//check for existing mnemonics\r\n\t\t\tconst char * ptr = src;\r\n\t\t\twhile(ptr = strchr(ptr,'&'))\r\n\t\t\t{\r\n\t\t\t\tif (ptr[1]=='&') ptr+=2;\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned c = 0;\r\n\t\t\t\t\tif (pfc::utf8_decode_char(ptr+1,&c)>0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (!is_used(c)) used.add_char(char_lower(c));\r\n\t\t\t\t\t}\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool process_string(const char * src,pfc::string_base & out)//returns if changed\r\n\t\t{\r\n\t\t\tif (check_string(src)) {out=src;return false;}\r\n\t\t\tunsigned idx=0;\r\n\t\t\twhile(src[idx]==' ') idx++;\r\n\t\t\twhile(src[idx])\r\n\t\t\t{\r\n\t\t\t\tif (is_alphanumeric(src[idx]) && !is_used(src[idx]))\r\n\t\t\t\t{\r\n\t\t\t\t\tinsert(src,idx,out);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\r\n\t\t\t\twhile(src[idx] && src[idx]!=' ' && src[idx]!='\\t') idx++;\r\n\t\t\t\tif (src[idx]=='\\t') break;\r\n\t\t\t\twhile(src[idx]==' ') idx++;\r\n\t\t\t}\r\n\r\n\t\t\t//no success picking first letter of one of words\r\n\t\t\tidx=0;\r\n\t\t\twhile(src[idx])\r\n\t\t\t{\r\n\t\t\t\tif (src[idx]=='\\t') break;\r\n\t\t\t\tif (is_alphanumeric(src[idx]) && !is_used(src[idx]))\r\n\t\t\t\t{\r\n\t\t\t\t\tinsert(src,idx,out);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t\tidx++;\r\n\t\t\t}\r\n\r\n\t\t\t//giving up\r\n\t\t\tout = src;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t};\r\n}\r\n\r\nvoid menu_helpers::win32_auto_mnemonics(HMENU menu)\r\n{\r\n\tmnemonic_manager mgr;\r\n\tunsigned n, m = GetMenuItemCount(menu);\r\n\tpfc::string8_fastalloc temp,temp2;\r\n\tfor(n=0;n<m;n++)//first pass, check existing mnemonics\r\n\t{\r\n\t\tunsigned type = uGetMenuItemType(menu,n);\r\n\t\tif (type==MFT_STRING)\r\n\t\t{\r\n\t\t\tuGetMenuString(menu,n,temp,MF_BYPOSITION);\r\n\t\t\tmgr.check_string(temp);\r\n\t\t}\r\n\t}\r\n\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tHMENU submenu = GetSubMenu(menu,n);\r\n\t\tif (submenu) win32_auto_mnemonics(submenu);\r\n\r\n\t\t{\r\n\t\t\tunsigned type = uGetMenuItemType(menu,n);\r\n\t\t\tif (type==MFT_STRING)\r\n\t\t\t{\r\n\t\t\t\tunsigned state = submenu ? 0 : GetMenuState(menu,n,MF_BYPOSITION);\r\n\t\t\t\tunsigned id = GetMenuItemID(menu,n);\r\n\t\t\t\tuGetMenuString(menu,n,temp,MF_BYPOSITION);\r\n\t\t\t\tif (mgr.process_string(temp,temp2))\r\n\t\t\t\t{\r\n\t\t\t\t\tuModifyMenu(menu,n,MF_BYPOSITION|MF_STRING|state,id,temp2);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif\r\n\r\nstatic bool test_key(unsigned k)\r\n{\r\n\treturn (GetKeyState(k) & 0x8000) ? true : false;\r\n}\r\n\r\n#define F_SHIFT (HOTKEYF_SHIFT<<8)\r\n#define F_CTRL (HOTKEYF_CONTROL<<8)\r\n#define F_ALT (HOTKEYF_ALT<<8)\r\n#define F_WIN (HOTKEYF_EXT<<8)\r\n\r\nstatic unsigned get_key_code(WPARAM wp)\r\n{\r\n\tunsigned code = (unsigned)(wp & 0xFF);\r\n\tif (test_key(VK_CONTROL)) code|=F_CTRL;\r\n\tif (test_key(VK_SHIFT)) code|=F_SHIFT;\r\n\tif (test_key(VK_MENU)) code|=F_ALT;\r\n\tif (test_key(VK_LWIN) || test_key(VK_RWIN)) code|=F_WIN;\r\n\treturn code;\r\n}\r\n\r\nbool keyboard_shortcut_manager::on_keydown(shortcut_type type,WPARAM wp)\r\n{\r\n\tif (type==TYPE_CONTEXT) return false;\r\n\tmetadb_handle_list dummy;\r\n\treturn process_keydown(type,dummy,get_key_code(wp));\r\n}\r\n\r\nbool keyboard_shortcut_manager::on_keydown_context(const pfc::list_base_const_t<metadb_handle_ptr> & data,WPARAM wp,const GUID & caller)\r\n{\r\n\tif (data.get_count()==0) return false;\r\n\treturn process_keydown_ex(TYPE_CONTEXT,data,get_key_code(wp),caller);\r\n}\r\n\r\nbool keyboard_shortcut_manager::on_keydown_auto(WPARAM wp)\r\n{\r\n\tif (on_keydown(TYPE_MAIN,wp)) return true;\r\n\tif (on_keydown(TYPE_CONTEXT_PLAYLIST,wp)) return true;\r\n\tif (on_keydown(TYPE_CONTEXT_NOW_PLAYING,wp)) return true;\r\n\treturn false;\r\n}\r\n\r\nbool keyboard_shortcut_manager::on_keydown_auto_playlist(WPARAM wp)\r\n{\r\n\tmetadb_handle_list data;\r\n\tstatic_api_ptr_t<playlist_manager> api;\r\n\tapi->activeplaylist_get_selected_items(data);\r\n\treturn on_keydown_auto_context(data,wp,contextmenu_item::caller_playlist);\r\n}\r\n\r\nbool keyboard_shortcut_manager::on_keydown_auto_context(const pfc::list_base_const_t<metadb_handle_ptr> & data,WPARAM wp,const GUID & caller)\r\n{\r\n\tif (on_keydown_context(data,wp,caller)) return true;\r\n\telse return on_keydown_auto(wp);\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/message_loop.h",
    "content": "class NOVTABLE message_filter\r\n{\r\npublic:\r\n    virtual bool pretranslate_message(MSG * p_msg) = 0;\r\n};\r\n \r\nclass NOVTABLE idle_handler\r\n{\r\npublic:\r\n    virtual bool on_idle() = 0;\r\n};\r\n \r\nclass NOVTABLE message_loop : public service_base\r\n{\r\npublic:\r\n    virtual void add_message_filter(message_filter * ptr) = 0;\r\n    virtual void remove_message_filter(message_filter * ptr) = 0;\r\n \r\n    virtual void add_idle_handler(idle_handler * ptr) = 0;\r\n    virtual void remove_idle_handler(idle_handler * ptr) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(message_loop);\r\n};\r\n\r\nclass message_filter_impl_base : public message_filter {\r\npublic:\r\n\tmessage_filter_impl_base() {static_api_ptr_t<message_loop>()->add_message_filter(this);}\r\n\t~message_filter_impl_base() {static_api_ptr_t<message_loop>()->remove_message_filter(this);}\r\n\tbool pretranslate_message(MSG * p_msg) {return false;}\r\n\t\r\n\tPFC_CLASS_NOT_COPYABLE(message_filter_impl_base,message_filter_impl_base);\r\n};\r\n\r\nclass message_filter_impl_accel : public message_filter_impl_base {\r\nprotected:\r\n\tbool pretranslate_message(MSG * p_msg) {\r\n\t\tif (m_wnd != NULL) {\r\n\t\t\tif (GetActiveWindow() == m_wnd) {\r\n\t\t\t\tif (TranslateAccelerator(m_wnd,m_accel.get(),p_msg) != 0) {\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\npublic:\r\n\tmessage_filter_impl_accel(HINSTANCE p_instance,const TCHAR * p_accel) : m_wnd(NULL) {\r\n\t\tm_accel.load(p_instance,p_accel);\r\n\t}\r\n\tvoid set_wnd(HWND p_wnd) {m_wnd = p_wnd;}\r\nprivate:\r\n\tHWND m_wnd;\r\n\twin32_accelerator m_accel;\r\n\r\n\tPFC_CLASS_NOT_COPYABLE(message_filter_impl_accel,message_filter_impl_accel);\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/metadb.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nvoid metadb::handle_create_replace_path_canonical(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path) {\r\n\thandle_create(p_out,make_playable_location(p_new_path,p_source->get_subsong_index()));\r\n}\r\n\r\nvoid metadb::handle_create_replace_path(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path) {\r\n\tpfc::string8 path;\r\n\tfilesystem::g_get_canonical_path(p_new_path,path);\r\n\thandle_create_replace_path_canonical(p_out,p_source,path);\r\n}\r\n\r\nvoid metadb::handle_replace_path_canonical(metadb_handle_ptr & p_out,const char * p_new_path) {\r\n\tmetadb_handle_ptr temp;\r\n\thandle_create_replace_path_canonical(temp,p_out,p_new_path);\r\n\tp_out = temp;\r\n}\r\n\r\n\r\nmetadb_io::t_load_info_state metadb_io::load_info(metadb_handle_ptr p_item,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors) {\r\n\treturn load_info_multi(pfc::list_single_ref_t<metadb_handle_ptr>(p_item),p_type,p_parent_window,p_show_errors);\r\n}\r\n\r\nmetadb_io::t_update_info_state metadb_io::update_info(metadb_handle_ptr p_item,file_info & p_info,HWND p_parent_window,bool p_show_errors)\r\n{\r\n\tfile_info * blah = &p_info;\r\n\treturn update_info_multi(pfc::list_single_ref_t<metadb_handle_ptr>(p_item),pfc::list_single_ref_t<file_info*>(blah),p_parent_window,p_show_errors);\r\n}\r\n\r\nfile_info_update_helper::file_info_update_helper(metadb_handle_ptr p_item)\r\n{\r\n\tconst t_size count = 1;\r\n\tm_data.add_item(p_item);\r\n\r\n\tm_infos.set_size(count);\r\n\tm_mask.set_size(count);\r\n\tfor(t_size n=0;n<count;n++) m_mask[n] = false;\r\n}\r\n\r\nfile_info_update_helper::file_info_update_helper(const pfc::list_base_const_t<metadb_handle_ptr> & p_data)\r\n{\r\n\tconst t_size count = p_data.get_count();\r\n\tm_data.add_items(p_data);\r\n\r\n\tm_infos.set_size(count);\r\n\tm_mask.set_size(count);\r\n\tfor(t_size n=0;n<count;n++) m_mask[n] = false;\r\n}\r\n\r\nbool file_info_update_helper::read_infos(HWND p_parent,bool p_show_errors)\r\n{\r\n\tstatic_api_ptr_t<metadb_io> api;\r\n\tif (api->load_info_multi(m_data,metadb_io::load_info_default,p_parent,p_show_errors) != metadb_io::load_info_success) return false;\r\n\tt_size n; const t_size m = m_data.get_count();\r\n\tt_size loaded_count = 0;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tbool val = m_data[n]->get_info(m_infos[n]);\r\n\t\tif (val) loaded_count++;\r\n\t\tm_mask[n] = val;\r\n\t}\r\n\treturn loaded_count == m;\r\n}\r\n\r\nfile_info_update_helper::t_write_result file_info_update_helper::write_infos(HWND p_parent,bool p_show_errors)\r\n{\r\n\tt_size n, outptr = 0; const t_size count = m_data.get_count();\r\n\tpfc::array_t<metadb_handle_ptr> items_to_update;\r\n\tpfc::array_t<file_info *> infos_to_write;\r\n\titems_to_update.set_size(count);\r\n\tinfos_to_write.set_size(count);\r\n\t\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\tif (m_mask[n])\r\n\t\t{\r\n\t\t\titems_to_update[outptr] = m_data[n];\r\n\t\t\tinfos_to_write[outptr] = &m_infos[n];\r\n\t\t\toutptr++;\r\n\t\t}\r\n\t}\r\n\r\n\tif (outptr == 0) return write_ok;\r\n\telse\r\n\t{\r\n\t\tstatic_api_ptr_t<metadb_io> api;\r\n\t\tswitch(api->update_info_multi(\r\n\t\t\tpfc::list_const_array_t<metadb_handle_ptr,const pfc::array_t<metadb_handle_ptr>&>(items_to_update,outptr),\r\n\t\t\tpfc::list_const_array_t<file_info*,const pfc::array_t<file_info*>&>(infos_to_write,outptr),\r\n\t\t\tp_parent,\r\n\t\t\ttrue\r\n\t\t\t))\r\n\t\t{\r\n\t\tcase metadb_io::update_info_success:\r\n\t\t\treturn write_ok;\r\n\t\tcase metadb_io::update_info_aborted:\r\n\t\t\treturn write_aborted;\r\n\t\tdefault:\r\n\t\tcase metadb_io::update_info_errors:\r\n\t\t\treturn write_error;\r\n\t\t}\r\n\t}\r\n}\r\n\r\nt_size file_info_update_helper::get_item_count() const\r\n{\r\n\treturn m_data.get_count();\r\n}\r\n\r\nbool file_info_update_helper::is_item_valid(t_size p_index) const\r\n{\r\n\treturn m_mask[p_index];\r\n}\r\n\t\r\nfile_info & file_info_update_helper::get_item(t_size p_index)\r\n{\r\n\treturn m_infos[p_index];\r\n}\r\n\r\nmetadb_handle_ptr file_info_update_helper::get_item_handle(t_size p_index) const\r\n{\r\n\treturn m_data[p_index];\r\n}\r\n\r\nvoid file_info_update_helper::invalidate_item(t_size p_index)\r\n{\r\n\tm_mask[p_index] = false;\r\n}\r\n\r\n\r\nvoid metadb_io::hint_async(metadb_handle_ptr p_item,const file_info & p_info,const t_filestats & p_stats,bool p_fresh)\r\n{\r\n\tconst file_info * blargh = &p_info;\r\n\thint_multi_async(pfc::list_single_ref_t<metadb_handle_ptr>(p_item),pfc::list_single_ref_t<const file_info *>(blargh),pfc::list_single_ref_t<t_filestats>(p_stats),bit_array_val(p_fresh));\r\n}\r\n\r\n\r\nbool metadb::g_get_random_handle(metadb_handle_ptr & p_out) {\r\n\tif (static_api_ptr_t<playback_control>()->get_now_playing(p_out)) return true;\r\n\r\n\t{\r\n\t\tstatic_api_ptr_t<playlist_manager> api;\t\r\n\r\n\t\tt_size playlist_count = api->get_playlist_count();\r\n\t\tt_size active_playlist = api->get_active_playlist();\r\n\t\tif (active_playlist != infinite) {\r\n\t\t\tif (api->playlist_get_focus_item_handle(p_out,active_playlist)) return true;\r\n\t\t}\r\n\r\n\t\tfor(t_size n = 0; n < playlist_count; n++) {\r\n\t\t\tif (api->playlist_get_focus_item_handle(p_out,n)) return true;\r\n\t\t}\r\n\r\n\t\tif (active_playlist != infinite) {\r\n\t\t\tt_size item_count = api->playlist_get_item_count(active_playlist);\r\n\t\t\tif (item_count > 0) {\r\n\t\t\t\tif (api->playlist_get_item_handle(p_out,active_playlist,0)) return true;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor(t_size n = 0; n < playlist_count; n++) {\r\n\t\t\tt_size item_count = api->playlist_get_item_count(n);\r\n\t\t\tif (item_count > 0) {\r\n\t\t\t\tif (api->playlist_get_item_handle(p_out,n,0)) return true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn false;\r\n}\r\n\r\n\r\nvoid metadb_io_v2::update_info_async_simple(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_new_info, HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) {\r\n\tupdate_info_async(p_list,new service_impl_t<file_info_filter_impl>(p_list,p_new_info),p_parent_window,p_op_flags,p_notify);\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/metadb.h",
    "content": "#ifndef _METADB_H_\r\n#define _METADB_H_\r\n\r\n//! API for tag read/write operations. Legal to call from main thread only, except for hint_multi_async() / hint_async().\\n\r\n//! Implemented only by core, do not reimplement.\\n\r\n//! Use static_api_ptr_t template to access metadb_io methods.\\n\r\n//! WARNING: Methods that perform file access (tag reads/writes) run a modal message loop. They SHOULD NOT be called from global callbacks and such.\r\nclass NOVTABLE metadb_io : public service_base\r\n{\r\npublic:\r\n\tenum t_load_info_type {\r\n\t\tload_info_default,\r\n\t\tload_info_force,\r\n\t\tload_info_check_if_changed\r\n\t};\r\n\r\n\tenum t_update_info_state {\r\n\t\tupdate_info_success,\r\n\t\tupdate_info_aborted,\r\n\t\tupdate_info_errors,\t\t\r\n\t};\r\n\t\r\n\tenum t_load_info_state {\r\n\t\tload_info_success,\r\n\t\tload_info_aborted,\r\n\t\tload_info_errors,\t\t\r\n\t};\r\n\r\n\t//! Returns whether some tag I/O operation is currently running. Another one can't be started.\r\n\t__declspec(deprecated) virtual bool is_busy() = 0;\r\n\t//! Returns whether - in result of user settings - all update operations will fail.\r\n\t__declspec(deprecated) virtual bool is_updating_disabled() = 0;\r\n\t//! Returns whether - in result of user settings - all update operations will silently succeed but without actually modifying files.\r\n\t__declspec(deprecated) virtual bool is_file_updating_blocked() = 0;\r\n\t//! If another tag I/O operation is running, this call will give focus to its progress window.\r\n\t__declspec(deprecated) virtual void highlight_running_process() = 0;\r\n\t//! Loads tags from multiple items.\r\n\t__declspec(deprecated) virtual t_load_info_state load_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors) = 0;\r\n\t//! Updates tags on multiple items.\r\n\t__declspec(deprecated) virtual t_update_info_state update_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<file_info*> & p_new_info,HWND p_parent_window,bool p_show_errors) = 0;\r\n\t//! Rewrites tags on multiple items.\r\n\t__declspec(deprecated) virtual t_update_info_state rewrite_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,HWND p_parent_window,bool p_show_errors) = 0;\r\n\t//! Removes tags from multiple items.\r\n\t__declspec(deprecated) virtual t_update_info_state remove_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,HWND p_parent_window,bool p_show_errors) = 0;\r\n\r\n\tvirtual void hint_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_infos,const pfc::list_base_const_t<t_filestats> & p_stats,const bit_array & p_fresh_mask) = 0;\r\n\r\n\tvirtual void hint_multi_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_infos,const pfc::list_base_const_t<t_filestats> & p_stats,const bit_array & p_fresh_mask) = 0;\r\n\r\n\tvirtual void hint_reader(service_ptr_t<class input_info_reader> p_reader,const char * p_path,abort_callback & p_abort) = 0;\r\n\r\n\t//! For internal use only.\r\n\tvirtual void path_to_handles_simple(const char * p_path,pfc::list_base_t<metadb_handle_ptr> & p_out) = 0;\r\n\r\n\t//! Dispatches metadb_io_callback calls with specified items. To be used with metadb_display_hook when your component needs specified items refreshed.\r\n\tvirtual void dispatch_refresh(const pfc::list_base_const_t<metadb_handle_ptr> & p_list) = 0;\r\n\r\n\tvoid hint_async(metadb_handle_ptr p_item,const file_info & p_info,const t_filestats & p_stats,bool p_fresh);\r\n\r\n\t__declspec(deprecated) t_load_info_state load_info(metadb_handle_ptr p_item,t_load_info_type p_type,HWND p_parent_window,bool p_show_errors);\r\n\t__declspec(deprecated) t_update_info_state update_info(metadb_handle_ptr p_item,file_info & p_info,HWND p_parent_window,bool p_show_errors);\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_io);\r\n};\r\n\r\n//! Implementing this class gives you direct control over which part of file_info gets altered during a tag update uperation. To be used with metadb_io_v2::update_info_async().\r\nclass NOVTABLE file_info_filter : public service_base {\r\npublic:\r\n\t//! Alters specified file_info entry; called as a part of tag update process. Specified file_info has been read from a file, and will be written back.\\n\r\n\t//! WARNING: This will be typically called from another thread than main app thread (precisely, from thread created by tag updater). You should copy all relevant data to members of your file_info_filter instance in constructor and reference only member data in apply_filter() implementation.\r\n\t//! @returns True when you have altered file_info and changes need to be written back to the file; false if no changes have been made.\r\n\tvirtual bool apply_filter(metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info) = 0;\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE(file_info_filter,service_base);\r\n};\r\n\r\n//! Advanced interface for passing infos read from files to metadb backend. Use metadb_io_v2::create_hint_list() to instantiate.\r\nclass NOVTABLE metadb_hint_list : public service_base {\r\npublic:\r\n\t//! Adds a hint to the list.\r\n\t//! @param p_location Location of the item the hint applies to.\r\n\t//! @param p_info file_info object describing the item.\r\n\t//! @param p_stats Information about the file containing item the hint applies to.\r\n\t//! @param p_freshflag Set to true if the info has been directly read from the file, false if it comes from another source such as a playlist file.\r\n\tvirtual void add_hint(metadb_handle_ptr const & p_location,const file_info & p_info,const t_filestats & p_stats,bool p_freshflag) = 0;\r\n\t//! Reads info from specified info reader instance and adds hints. May throw an exception in case info read has failed.\r\n\tvirtual void add_hint_reader(const char * p_path,service_ptr_t<input_info_reader> const & p_reader,abort_callback & p_abort) = 0;\r\n\t//! Call this when you're done working with this metadb_hint_list instance, to apply hints and dispatch callbacks. If you don't call this, all added hints will be ignored.\r\n\tvirtual void on_done() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(metadb_hint_list,service_base);\r\n};\r\n\r\n//! New in 0.9.3. Extends metadb_io functionality with nonblocking versions of tag read/write functions, and some other utility features.\r\nclass NOVTABLE metadb_io_v2 : public metadb_io {\r\npublic:\r\n\tenum {\r\n\t\t//! By default, when some part of requested operation could not be performed for reasons other than user abort, a popup dialog with description of the problem is spawned.\\n\r\n\t\t//! Set this flag to disable error notification.\r\n\t\top_flag_no_errors\t\t= 1 << 0,\r\n\t\t//! Set this flag to make the progress dialog not steal focus on creation.\r\n\t\top_flag_background\t\t= 1 << 1,\r\n\t\t//! Set this flag to delay the progress dialog becoming visible, so it does not appear at all during short operations. Also implies op_flag_background effect.\r\n\t\top_flag_delay_ui\t\t= 1 << 2,\r\n\t};\r\n\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_notify Called when the task is completed. Status code is one of t_load_info_state values. Can be null if caller doesn't care.\r\n\tvirtual void load_info_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_load_info_type p_type,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0;\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care.\r\n\t//! @param p_filter Callback handling actual file_info alterations. Typically used to replace entire meta part of file_info, or to alter something else such as ReplayGain while leaving meta intact.\r\n\tvirtual void update_info_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,service_ptr_t<file_info_filter> p_filter,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0;\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care.\r\n\tvirtual void rewrite_info_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0;\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care.\r\n\tvirtual void remove_info_async(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify) = 0;\r\n\r\n\t//! Creates a metadb_hint_list object.\r\n\tvirtual service_ptr_t<metadb_hint_list> create_hint_list() = 0;\r\n\r\n\t//! @param p_list List of items to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_notify Called when the task is completed. Status code is one of t_update_info values. Can be null if caller doesn't care.\r\n\t//! @param p_new_info New infos to write to specified items.\r\n\tvoid update_info_async_simple(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_new_info, HWND p_parent_window,t_uint32 p_op_flags,completion_notify_ptr p_notify);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(metadb_io_v2,metadb_io);\r\n};\r\n\r\n//! Callback service receiving notifications about metadb contents changes.\r\nclass NOVTABLE metadb_io_callback : public service_base {\r\npublic:\r\n\t//! Called when metadb contents change. (Or, one of display hook component requests display update).\r\n\t//! @param p_items_sorted List of items that have been updated. The list is always sorted by pointer value, to allow fast bsearch to test whether specific item has changed.\r\n\t//! @param p_fromhook Set to true when actual contents haven't changed but one of display hooks requested an update.\r\n\tvirtual void on_changed_sorted(const pfc::list_base_const_t<metadb_handle_ptr> & p_items_sorted, bool p_fromhook) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_io_callback);\r\n};\r\n\r\n//! Entrypoint service for metadb_handle related operations.\\n\r\n//! Implemented only by core, do not reimplement.\\n\r\n//! Use static_api_ptr_t template to access it, e.g. static_api_ptr_t<metadb>()->handle_create(myhandle,mylocation);\r\nclass NOVTABLE metadb : public service_base\r\n{\r\npublic:\r\n\t//! Locks metadb to prevent other threads from modifying it while you're working with some of its contents. Some functions (metadb_handle::get_info_locked(), metadb_handle::get_info_async_locked()) can be called only from inside metadb lock section.\r\n\tvirtual void database_lock()=0;\r\n\t//! Unlocks metadb after database_lock(). Some functions (metadb_handle::get_info_locked(), metadb_handle::get_info_async_locked()) can be called only from inside metadb lock section.\r\n\tvirtual void database_unlock()=0;\r\n\t\r\n\t//! Returns metadb_handle object referencing specified location (attempts to find existing one, creates new one if doesn't exist).\r\n\t//! @param p_out Receives metadb_handle pointer.\r\n\t//! @param p_location Location to create metadb_handle for.\r\n\tvirtual void handle_create(metadb_handle_ptr & p_out,const playable_location & p_location)=0;\r\n\r\n\tvoid handle_create_replace_path_canonical(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path);\r\n\tvoid handle_replace_path_canonical(metadb_handle_ptr & p_out,const char * p_new_path);\r\n\tvoid handle_create_replace_path(metadb_handle_ptr & p_out,const metadb_handle_ptr & p_source,const char * p_new_path);\r\n\r\n\t//! Helper function; attempts to retrieve a handle to any known playable location to be used for e.g. titleformatting script preview.\\n\r\n\t//! @returns True on success; false on failure (no known playable locations).\r\n\tstatic bool g_get_random_handle(metadb_handle_ptr & p_out);\r\n\r\n\tenum {case_sensitive = true};\r\n\ttypedef pfc::comparator_strcmp path_comparator;\r\n\r\n\tinline static int path_compare_ex(const char * p1,unsigned len1,const char * p2,unsigned len2) {return case_sensitive ? pfc::strcmp_ex(p1,len1,p2,len2) : stricmp_utf8_ex(p1,len1,p2,len2);}\r\n\tinline static int path_compare(const char * p1,const char * p2) {return case_sensitive ? strcmp(p1,p2) : stricmp_utf8(p1,p2);}\r\n\tinline static int path_compare_metadb_handle(const metadb_handle_ptr & p1,const metadb_handle_ptr & p2) {return path_compare(p1->get_path(),p2->get_path());}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb);\r\n};\r\n\r\n\r\nclass in_metadb_sync {\r\npublic:\r\n\tin_metadb_sync() {\r\n\t\tm_api->database_lock();\r\n\t}\r\n\t~in_metadb_sync() {\r\n\t\tm_api->database_unlock();\r\n\t}\r\nprivate:\r\n\tstatic_api_ptr_t<metadb> m_api;\r\n};\r\n\r\nclass in_metadb_sync_fromptr {\r\npublic:\r\n\tin_metadb_sync_fromptr(const service_ptr_t<metadb> & p_api) : m_api(p_api) {m_api->database_lock();}\r\n\t~in_metadb_sync_fromptr() {m_api->database_unlock();}\r\nprivate:\r\n\tservice_ptr_t<metadb> m_api;\r\n};\r\n\r\nclass in_metadb_sync_fromhandle {\r\npublic:\r\n\tin_metadb_sync_fromhandle(const service_ptr_t<metadb_handle> & p_api) : m_api(p_api) {m_api->metadb_lock();}\r\n\t~in_metadb_sync_fromhandle() {m_api->metadb_unlock();}\r\nprivate:\r\n\tservice_ptr_t<metadb_handle> m_api;\r\n};\r\n\r\n\r\n//! Deprecated - use metadb_io_v2::update_info_async w/ file_info_filter whenever possible.\r\nclass __declspec(deprecated(\"Use metadb_io_v2::update_info_async instead whenever possible.\")) file_info_update_helper\r\n{\r\npublic:\r\n\tfile_info_update_helper(const pfc::list_base_const_t<metadb_handle_ptr> & p_data);\r\n\tfile_info_update_helper(metadb_handle_ptr p_item);\r\n\r\n\tbool read_infos(HWND p_parent,bool p_show_errors);\r\n\r\n\tenum t_write_result\r\n\t{\r\n\t\twrite_ok,\r\n\t\twrite_aborted,\r\n\t\twrite_error\r\n\t};\r\n\tt_write_result write_infos(HWND p_parent,bool p_show_errors);\r\n\r\n\tt_size get_item_count() const;\r\n\tbool is_item_valid(t_size p_index) const;//returns false where info reading failed\r\n\t\r\n\tfile_info & get_item(t_size p_index);\r\n\tmetadb_handle_ptr get_item_handle(t_size p_index) const;\r\n\r\n\tvoid invalidate_item(t_size p_index);\r\n\r\nprivate:\r\n\tmetadb_handle_list m_data;\r\n\tpfc::array_t<file_info_impl> m_infos;\r\n\tpfc::array_t<bool> m_mask;\r\n};\r\n\r\nclass titleformat_text_out;\r\nclass titleformat_hook_function_params;\r\n\r\n\r\n/*\r\n\tImplementing this service installs a global hook for metadb_handle::format_title field processing. \\n\r\n\tThis should be implemented only where absolutely necessary, for safety and performance reasons. \\n\r\n\tmetadb_display_hook methods should NEVER make any other API calls (other than possibly querying information from passed metadb_handle pointer), only read implementation-specific private data and return as soon as possible. Since those are called from metadb_handle::format_title, no assumptions should be made about calling context (threading etc). \\n\r\n\tBoth methods are called from inside metadb lock, so no additional locking is required to use *_locked metadb_handle methods.\r\n\tSee titleformat_hook for more info about methods/parameters. \\n\r\n\tIf there are multiple metadb_display_hook implementations registered, call order is undefined.\r\n*/\r\n\r\nclass metadb_display_hook : public service_base {\r\npublic:\r\n\tvirtual bool process_field(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) = 0;\r\n\tvirtual bool process_function(metadb_handle * p_handle,titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(metadb_display_hook);\r\n};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n//! Helper implementation of file_info_filter_impl.\r\nclass file_info_filter_impl : public file_info_filter {\r\npublic:\r\n\tfile_info_filter_impl(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_new_info) {\r\n\t\tpfc::dynamic_assert(p_list.get_count() == p_new_info.get_count());\r\n\t\tpfc::array_t<t_size> order;\r\n\t\torder.set_size(p_list.get_count());\r\n\t\torder_helper::g_fill(order.get_ptr(),order.get_size());\r\n\t\tp_list.sort_get_permutation_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>,order.get_ptr());\r\n\t\tm_handles.set_count(order.get_size());\r\n\t\tm_infos.set_size(order.get_size());\r\n\t\tfor(t_size n = 0; n < order.get_size(); n++) {\r\n\t\t\tm_handles[n] = p_list[order[n]];\r\n\t\t\tm_infos[n] = *p_new_info[order[n]];\r\n\t\t}\r\n\t}\r\n\r\n\tbool apply_filter(metadb_handle_ptr p_location,t_filestats p_stats,file_info & p_info) {\r\n\t\tt_size index;\r\n\t\tif (m_handles.bsearch_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>,p_location,index)) {\r\n\t\t\tp_info = m_infos[index];\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tmetadb_handle_list m_handles;\r\n\tpfc::array_t<file_info_impl> m_infos;\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/metadb_handle.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\ndouble metadb_handle::get_length()\r\n{\r\n\tdouble rv = 0;\r\n\tin_metadb_sync_fromhandle l_sync(this);\r\n\tconst file_info * info;\r\n\tif (get_info_locked(info))\r\n\t\trv = info->get_length();\r\n\treturn rv;\r\n}\r\n\r\nt_filetimestamp metadb_handle::get_filetimestamp()\r\n{\r\n\treturn get_filestats().m_timestamp;\r\n}\r\n\r\nt_filesize metadb_handle::get_filesize()\r\n{\r\n\treturn get_filestats().m_size;\r\n}\r\n\r\nbool metadb_handle::format_title_legacy(titleformat_hook * p_hook,pfc::string_base & p_out,const char * p_spec,titleformat_text_filter * p_filter)\r\n{\r\n\tservice_ptr_t<titleformat_object> script;\r\n\tif (static_api_ptr_t<titleformat_compiler>()->compile(script,p_spec)) {\r\n\t\treturn format_title(p_hook,p_out,script,p_filter);\r\n\t} else {\r\n\t\tp_out.reset();\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\n\r\n\r\nbool metadb_handle::g_should_reload(const t_filestats & p_old_stats,const t_filestats & p_new_stats,bool p_fresh)\r\n{\r\n\tif (p_new_stats.m_timestamp == filetimestamp_invalid) return p_fresh;\r\n\telse if (p_fresh) return p_old_stats!= p_new_stats;\r\n\telse return p_old_stats.m_timestamp < p_new_stats.m_timestamp;\r\n}\r\n\r\nbool metadb_handle::should_reload(const t_filestats & p_new_stats, bool p_fresh) const\r\n{\r\n\tif (!is_info_loaded_async()) return true;\r\n\telse return g_should_reload(get_filestats(),p_new_stats,p_fresh);\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/metadb_handle.h",
    "content": "#ifndef _FOOBAR2000_METADB_HANDLE_H_\r\n#define _FOOBAR2000_METADB_HANDLE_H_\r\n\r\nclass titleformat_hook;\r\nclass titleformat_text_filter;\r\n\r\n//! metadb_handle object represents interface to reference-counted file_info cache entry for specified location.\\n\r\n//! To obtain a metadb_handle to specific location, use metadb::handle_create(). To obtain a list of metadb_handle objects corresponding to specific path (directory, playlist, multitrack file, etc), use relevant playlist_loader static helper methods.\\n\r\n//! metadb_handle is also the most efficient way of passing playable object locations around because it provides fast access to both location and infos, and is reference counted so duplicating it is as fast as possible.\\n\r\n//! To retrieve a path of a file from a metadb_handle, use metadb_handle::get_path() function. Note that metadb_handle is NOT just file path, some formats support multiple subsongs per physical file, which are signaled using subsong indexes.\\n\r\n\r\nclass NOVTABLE metadb_handle : public service_base\r\n{\r\npublic:\r\n\t//! Retrieves location represented by this metadb_handle object. Returned reference is valid until calling context releases metadb_handle that returned it (metadb_handle_ptr is deallocated etc).\r\n\tvirtual const playable_location & get_location() const = 0;//never fails, returned pointer valid till the object is released\r\n\r\n\r\n\t//! Renders information about item referenced by this metadb_handle object.\r\n\t//! @param p_hook Optional callback object overriding fields and functions; set to NULL if not used.\r\n\t//! @param p_out String receiving the output on success.\r\n\t//! @param p_script Titleformat script to use. Use titleformat_compiler service to create one.\r\n\t//! @param p_filter Optional callback object allowing input to be filtered according to context (i.e. removal of linebreak characters present in tags when rendering playlist lines). Set to NULL when not used.\r\n\t//! @returns true on success, false when dummy file_info instance was used because actual info is was not (yet) known.\r\n\tvirtual bool format_title(titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t<class titleformat_object> & p_script,titleformat_text_filter * p_filter) = 0;\r\n\r\n\t//! Locks metadb to prevent other threads from modifying it while you're working with some of its contents. Some functions (metadb_handle::get_info_locked(), metadb_handle::get_info_async_locked()) can be called only from inside metadb lock section.\r\n\t//! Same as metadb::database_lock().\r\n\tvirtual void metadb_lock() = 0;\r\n\t//! Unlocks metadb after metadb_lock(). Some functions (metadb_handle::get_info_locked(), metadb_handle::get_info_async_locked()) can be called only from inside metadb lock section.\r\n\t//! Same as metadb::database_unlock().\r\n\tvirtual void metadb_unlock() = 0;\r\n\r\n\t//! Returns last seen file stats, filestats_invalid if unknown.\r\n\tvirtual t_filestats get_filestats() const = 0;\r\n\r\n\t//! Queries whether cached info about item referenced by this metadb_handle object is already available.\\n\r\n\t//! Note that state of cached info changes only inside main thread, so you can safely assume that it doesn't change while some block of your code inside main thread is being executed.\r\n\tvirtual bool is_info_loaded() const = 0;\r\n\t//! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known.\\n\r\n\t//! Note that state of cached info changes only inside main thread, so you can safely assume that it doesn't change while some block of your code inside main thread is being executed.\r\n\tvirtual bool get_info(file_info & p_info) const = 0;\r\n\t//! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known. This is more efficient than get_info() since no data is copied.\\n\r\n\t//! You must lock the metadb before calling this function, and unlock it after you are done working with the returned pointer, to ensure multithread safety.\\n\r\n\t//! Note that state of cached info changes only inside main thread, so you can safely assume that it doesn't change while some block of your code inside main thread is being executed.\r\n\t//! @param p_info On success, receives a pointer to metadb's file_info object. The pointer is for temporary use only, and becomes invalid when metadb is unlocked.\r\n\tvirtual bool get_info_locked(const file_info * & p_info) const = 0;\r\n\t\r\n\t//! Queries whether cached info about item referenced by this metadb_handle object is already available.\\n\r\n\t//! This is intended for use in special cases when you need to immediately retrieve info sent by metadb_io hint from another thread; state of returned data can be altered by any thread, as opposed to non-async methods.\r\n\tvirtual bool is_info_loaded_async() const = 0;\t\r\n\t//! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known.\\n\r\n\t//! This is intended for use in special cases when you need to immediately retrieve info sent by metadb_io hint from another thread; state of returned data can be altered by any thread, as opposed to non-async methods.\r\n\tvirtual bool get_info_async(file_info & p_info) const = 0;\t\r\n\t//! Queries cached info about item referenced by this metadb_handle object. Returns true on success, false when info is not yet known. This is more efficient than get_info() since no data is copied.\\n\r\n\t//! You must lock the metadb before calling this function, and unlock it after you are done working with the returned pointer, to ensure multithread safety.\\n\r\n\t//! This is intended for use in special cases when you need to immediately retrieve info sent by metadb_io hint from another thread; state of returned data can be altered by any thread, as opposed to non-async methods.\r\n\t//! @param p_info On success, receives a pointer to metadb's file_info object. The pointer is for temporary use only, and becomes invalid when metadb is unlocked.\r\n\tvirtual bool get_info_async_locked(const file_info * & p_info) const = 0;\r\n\r\n\r\n\t//! Renders information about item referenced by this metadb_handle object, using external file_info data.\r\n\tvirtual void format_title_from_external_info(const file_info & p_info,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t<class titleformat_object> & p_script,titleformat_text_filter * p_filter)=0;\r\n\t\r\n\tstatic bool g_should_reload(const t_filestats & p_old_stats,const t_filestats & p_new_stats,bool p_fresh);\r\n\tbool should_reload(const t_filestats & p_new_stats,bool p_fresh) const;\r\n\t\r\n\r\n\t//! Helper provided for backwards compatibility; takes formatting script as text string and calls relevant titleformat_compiler methods; returns false when the script could not be compiled.\\n\r\n\t//! See format_title() for descriptions of parameters.\\n\r\n\t//! Bottleneck warning: you should consider using precompiled titleformat script object and calling regular format_title() instead when processing large numbers of items.\r\n\tbool format_title_legacy(titleformat_hook * p_hook,pfc::string_base & out,const char * p_spec,titleformat_text_filter * p_filter);\r\n\r\n\t//! Retrieves path of item described by this metadb_handle instance. Returned string is valid until calling context releases metadb_handle that returned it (metadb_handle_ptr is deallocated etc).\r\n\tinline const char * get_path() const {return get_location().get_path();}\r\n\t//! Retrieves subsong index of item described by this metadb_handle instance (used for multiple playable tracks within single physical file).\r\n\tinline t_uint32 get_subsong_index() const {return get_location().get_subsong_index();}\r\n\t\r\n\tdouble get_length();//helper\r\n\t\r\n\tt_filetimestamp get_filetimestamp();\r\n\tt_filesize get_filesize();\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(metadb_handle,service_base);\r\n};\r\n\r\ntypedef service_ptr_t<metadb_handle> metadb_handle_ptr;\r\n\r\nnamespace metadb_handle_list_helper {\r\n\tvoid sort_by_format_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count,const char * spec,titleformat_hook * p_hook);\r\n\tvoid sort_by_format_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order,const char * spec,titleformat_hook * p_hook);\r\n\tvoid sort_by_format_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook);\r\n\tvoid sort_by_format_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook);\r\n\r\n\tvoid sort_by_relative_path_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count);\r\n\tvoid sort_by_relative_path_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order);\r\n\t\r\n\tvoid remove_duplicates(pfc::list_base_t<metadb_handle_ptr> & p_list);\r\n\tvoid sort_by_pointer_remove_duplicates(pfc::list_base_t<metadb_handle_ptr> & p_list);\r\n\tvoid sort_by_path_quick(pfc::list_base_t<metadb_handle_ptr> & p_list);\r\n\r\n\tvoid sort_by_pointer(pfc::list_base_t<metadb_handle_ptr> & p_list);\r\n\tt_size bsearch_by_pointer(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const metadb_handle_ptr & val);\r\n\r\n\tdouble calc_total_duration(const pfc::list_base_const_t<metadb_handle_ptr> & p_list);\r\n\r\n\tvoid sort_by_path(pfc::list_base_t<metadb_handle_ptr> & p_list);\r\n};\r\n\r\ntemplate<template<typename> class t_alloc = pfc::alloc_fast >\r\nclass metadb_handle_list_t : public service_list_t<metadb_handle,t_alloc> {\r\nprivate:\r\n\ttypedef metadb_handle_list_t<t_alloc> t_self;\r\n\ttypedef list_base_const_t<metadb_handle_ptr> t_interface;\r\npublic:\r\n\tinline void sort_by_format(const char * spec,titleformat_hook * p_hook) {return sort_by_format_partial(0,get_count(),spec,p_hook);}\r\n\tinline void sort_by_format_partial(t_size base,t_size count,const char * spec,titleformat_hook * p_hook) {metadb_handle_list_helper::sort_by_format_partial(*this,base,count,spec,p_hook);}\r\n\tinline void sort_by_format_get_order(t_size* order,const char * spec,titleformat_hook * p_hook) const {sort_by_format_get_order_partial(0,get_count(),order,spec,p_hook);}\r\n\tinline void sort_by_format_get_order_partial(t_size base,t_size count,t_size* order,const char * spec,titleformat_hook * p_hook) const {metadb_handle_list_helper::sort_by_format_get_order_partial(*this,base,count,order,spec,p_hook);}\r\n\r\n\tinline void sort_by_format(const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook) {return sort_by_format_partial(0,get_count(),p_script,p_hook);}\r\n\tinline void sort_by_format_partial(t_size base,t_size count,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook) {metadb_handle_list_helper::sort_by_format_partial(*this,base,count,p_script,p_hook);}\r\n\tinline void sort_by_format_get_order(t_size* order,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook) const {sort_by_format_get_order_partial(0,get_count(),order,p_script,p_hook);}\r\n\tinline void sort_by_format_get_order_partial(t_size base,t_size count,t_size* order,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook) const {metadb_handle_list_helper::sort_by_format_get_order_partial(*this,base,count,order,p_script,p_hook);}\r\n\t\r\n\tinline void sort_by_relative_path() {sort_by_relative_path_partial(0,get_count());}\r\n\tinline void sort_by_relative_path_partial(t_size base,t_size count) {metadb_handle_list_helper::sort_by_relative_path_partial(*this,base,count);}\r\n\tinline void sort_by_relative_path_get_order(t_size* order) const {sort_by_relative_path_get_order_partial(0,get_count(),order);}\r\n\tinline void sort_by_relative_path_get_order_partial(t_size base,t_size count,t_size* order) const {metadb_handle_list_helper::sort_by_relative_path_get_order_partial(*this,base,count,order);}\r\n\t\r\n\tinline void remove_duplicates() {metadb_handle_list_helper::remove_duplicates(*this);}\r\n\tinline void sort_by_pointer_remove_duplicates() {metadb_handle_list_helper::sort_by_pointer_remove_duplicates(*this);}\r\n\tinline void sort_by_path_quick() {metadb_handle_list_helper::sort_by_path_quick(*this);}\r\n\r\n\tinline void sort_by_pointer() {metadb_handle_list_helper::sort_by_pointer(*this);}\r\n\tinline t_size bsearch_by_pointer(const metadb_handle_ptr & val) const {return metadb_handle_list_helper::bsearch_by_pointer(*this,val);}\r\n\r\n\tinline double calc_total_duration() const {return metadb_handle_list_helper::calc_total_duration(*this);}\r\n\r\n\tinline void sort_by_path() {metadb_handle_list_helper::sort_by_path(*this);}\r\n\r\n\tconst t_self & operator=(const t_self & p_source) {remove_all(); add_items(p_source);return *this;}\r\n\tconst t_self & operator=(const t_interface & p_source) {remove_all(); add_items(p_source);return *this;}\r\n\tmetadb_handle_list_t(const t_self & p_source) {add_items(p_source);}\r\n\tmetadb_handle_list_t(const t_interface & p_source) {add_items(p_source);}\r\n\tmetadb_handle_list_t() {}\r\n\r\n};\r\n\r\ntypedef metadb_handle_list_t<> metadb_handle_list;\r\n\r\nnamespace metadb_handle_list_helper {\r\n\tvoid sorted_by_pointer_extract_difference(metadb_handle_list const & p_list_1,metadb_handle_list const & p_list_2,metadb_handle_list & p_list_1_specific,metadb_handle_list & p_list_2_specific);\r\n};\r\n\r\nclass metadb_handle_lock\r\n{\r\n\tmetadb_handle_ptr m_ptr;\r\npublic:\r\n\tinline metadb_handle_lock(const metadb_handle_ptr & param)\r\n\t{\r\n\t\tm_ptr = param;\r\n\t\tm_ptr->metadb_lock();\r\n\t}\t\r\n\tinline ~metadb_handle_lock() {m_ptr->metadb_unlock();}\r\n};\r\n\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,const metadb_handle_ptr & p_location) {\r\n\tif (p_location.is_valid()) \r\n\t\treturn p_fmt << p_location->get_location();\r\n\telse\r\n\t\treturn p_fmt << \"[invalid location]\";\r\n}\r\n\r\n\r\nclass string_format_title {\r\npublic:\r\n\tstring_format_title(metadb_handle_ptr p_item,const char * p_script) {\r\n\t\tp_item->format_title_legacy(NULL,m_data,p_script,NULL);\r\n\t}\r\n\tstring_format_title(metadb_handle_ptr p_item,service_ptr_t<class titleformat_object> p_script) {\r\n\t\tp_item->format_title(NULL,m_data,p_script,NULL);\r\n\t}\r\n\r\n\tconst char * get_ptr() const {return m_data.get_ptr();}\r\n\toperator const char * () const {return m_data.get_ptr();}\r\nprivate:\r\n\tpfc::string8_fastalloc m_data;\r\n};\r\n\r\n#endif //_FOOBAR2000_METADB_HANDLE_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/metadb_handle_list.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\n\r\n\r\nnamespace {\r\n\tstruct custom_sort_data\r\n\t{\r\n\t\tHANDLE text;\r\n\t\t//int subsong;\r\n\t\tt_size index;\r\n\t};\r\n}\r\nstatic int __cdecl custom_sort_compare(const custom_sort_data & elem1, const custom_sort_data & elem2 )\r\n{//depends on unicode/ansi, nonportable (win32 lstrcmpi)\r\n\tint ret = uSortStringCompare(elem1.text,elem2.text);//uStringCompare\r\n//\tif (ret == 0) ret = elem1.subsong - elem2.subsong;\r\n\tif (ret == 0) ret = pfc::sgn_t((t_ssize)elem1.index - (t_ssize)elem2.index);\r\n\treturn ret;\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_format_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count,const char * spec,titleformat_hook * p_hook)\r\n{\r\n\tservice_ptr_t<titleformat_object> script;\r\n\tif (static_api_ptr_t<titleformat_compiler>()->compile(script,spec))\r\n\t\tsort_by_format_partial(p_list,base,count,script,p_hook);\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_format_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order,const char * spec,titleformat_hook * p_hook)\r\n{\r\n\tservice_ptr_t<titleformat_object> script;\r\n\tif (static_api_ptr_t<titleformat_compiler>()->compile(script,spec))\r\n\t\tsort_by_format_get_order_partial(p_list,base,count,order,script,p_hook);\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_format_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook)\r\n{\r\n\tpfc::array_t<t_size> order; order.set_size(count);\r\n\tsort_by_format_get_order_partial(p_list,base,count,order.get_ptr(),p_script,p_hook);\r\n\tp_list.reorder_partial(base,order.get_ptr(),count);\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_format_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order,const service_ptr_t<titleformat_object> & p_script,titleformat_hook * p_hook)\r\n{\r\n\tassert(base+count<=p_list.get_count());\r\n\tt_size n;\r\n\tpfc::array_t<custom_sort_data> data;\r\n\tdata.set_size(count);\r\n\t\r\n\tpfc::string8_fastalloc temp;\r\n\tpfc::string8_fastalloc temp2;\r\n\ttemp.prealloc(512);\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\tmetadb_handle_ptr item;\r\n\t\tp_list.get_item_ex(item,base+n);\r\n\t\tassert(item.is_valid());\r\n\r\n\t\titem->format_title(p_hook,temp,p_script,0);\r\n\t\tdata[n].index = n;\r\n\t\tdata[n].text = uSortStringCreate(temp);\r\n\t\t//data[n].subsong = item->get_subsong_index();\r\n\t}\r\n\r\n\tpfc::sort_t(data,custom_sort_compare,count);\r\n\t//qsort(data.get_ptr(),count,sizeof(custom_sort_data),(int (__cdecl *)(const void *elem1, const void *elem2 ))custom_sort_compare);\r\n\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\torder[n]=data[n].index;\r\n\t\tuSortStringFree(data[n].text);\r\n\t}\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_relative_path_partial(pfc::list_base_t<metadb_handle_ptr> & p_list,t_size base,t_size count)\r\n{\r\n\tassert(base+count<=p_list.get_count());\r\n\tpfc::array_t<t_size> order; order.set_size(count);\r\n\tsort_by_relative_path_get_order_partial(p_list,base,count,order.get_ptr());\r\n\tp_list.reorder_partial(base,order.get_ptr(),count);\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_relative_path_get_order_partial(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,t_size base,t_size count,t_size* order)\r\n{\r\n\tassert(base+count<=p_list.get_count());\r\n\tt_size n;\r\n\tpfc::array_t<custom_sort_data> data;\r\n\tdata.set_size(count);\r\n\tstatic_api_ptr_t<library_manager> api;\r\n\t\r\n\tpfc::string8_fastalloc temp;\r\n\ttemp.prealloc(512);\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\tmetadb_handle_ptr item;\r\n\t\tp_list.get_item_ex(item,base+n);\r\n\t\tif (!api->get_relative_path(item,temp)) temp = \"\";\r\n\t\tdata[n].index = n;\r\n\t\tdata[n].text = uSortStringCreate(temp);\r\n\t\t//data[n].subsong = item->get_subsong_index();\r\n\t}\r\n\r\n\tpfc::sort_t(data,custom_sort_compare,count);\r\n\t//qsort(data.get_ptr(),count,sizeof(custom_sort_data),(int (__cdecl *)(const void *elem1, const void *elem2 ))custom_sort_compare);\r\n\r\n\tfor(n=0;n<count;n++)\r\n\t{\r\n\t\torder[n]=data[n].index;\r\n\t\tuSortStringFree(data[n].text);\r\n\t}\r\n}\r\n\r\nvoid metadb_handle_list_helper::remove_duplicates(pfc::list_base_t<metadb_handle_ptr> & p_list)\r\n{\r\n\tt_size count = p_list.get_count();\r\n\tif (count>0)\r\n\t{\r\n\t\tbit_array_bittable mask(count);\r\n\t\tpfc::array_t<t_size> order; order.set_size(count);\r\n\t\torder_helper::g_fill(order);\r\n\r\n\t\tp_list.sort_get_permutation_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>,order.get_ptr());\r\n\t\t\r\n\t\tt_size n;\r\n\t\tbool found = false;\r\n\t\tfor(n=0;n<count-1;n++)\r\n\t\t{\r\n\t\t\tif (p_list.get_item(order[n])==p_list.get_item(order[n+1]))\r\n\t\t\t{\r\n\t\t\t\tfound = true;\r\n\t\t\t\tmask.set(order[n+1],true);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif (found) p_list.remove_mask(mask);\r\n\t}\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_pointer_remove_duplicates(pfc::list_base_t<metadb_handle_ptr> & p_list)\r\n{\r\n\tt_size count = p_list.get_count();\r\n\tif (count>0)\r\n\t{\r\n\t\tsort_by_pointer(p_list);\r\n\t\tbool b_found = false;\r\n\t\tt_size n;\r\n\t\tfor(n=0;n<count-1;n++)\r\n\t\t{\r\n\t\t\tif (p_list.get_item(n)==p_list.get_item(n+1))\r\n\t\t\t{\r\n\t\t\t\tb_found = true;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (b_found)\r\n\t\t{\r\n\t\t\tbit_array_bittable mask(count);\r\n\t\t\tt_size n;\r\n\t\t\tfor(n=0;n<count-1;n++)\r\n\t\t\t{\r\n\t\t\t\tif (p_list.get_item(n)==p_list.get_item(n+1))\r\n\t\t\t\t\tmask.set(n+1,true);\r\n\t\t\t}\r\n\t\t\tp_list.remove_mask(mask);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_path_quick(pfc::list_base_t<metadb_handle_ptr> & p_list)\r\n{\r\n\tp_list.sort_t(metadb::path_compare_metadb_handle);\r\n}\r\n\r\n\r\nvoid metadb_handle_list_helper::sort_by_pointer(pfc::list_base_t<metadb_handle_ptr> & p_list)\r\n{\r\n\t//it seems MSVC71 /GL does something highly retarded here\r\n\t//p_list.sort_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>);\r\n\tp_list.sort();\r\n}\r\n\r\nt_size metadb_handle_list_helper::bsearch_by_pointer(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const metadb_handle_ptr & val)\r\n{\r\n\tt_size blah;\r\n\tif (p_list.bsearch_t(pfc::compare_t<metadb_handle_ptr,metadb_handle_ptr>,val,blah)) return blah;\r\n\telse return ~0;\r\n}\r\n\r\n\r\nvoid metadb_handle_list_helper::sorted_by_pointer_extract_difference(metadb_handle_list const & p_list_1,metadb_handle_list const & p_list_2,metadb_handle_list & p_list_1_specific,metadb_handle_list & p_list_2_specific)\r\n{\r\n\tt_size found_1, found_2;\r\n\tconst t_size count_1 = p_list_1.get_count(), count_2 = p_list_2.get_count();\r\n\tt_size ptr_1, ptr_2;\r\n\r\n\tfound_1 = found_2 = 0;\r\n\tptr_1 = ptr_2 = 0;\r\n\twhile(ptr_1 < count_1 || ptr_2 < count_2)\r\n\t{\r\n\t\twhile(ptr_1 < count_1 && (ptr_2 == count_2 || p_list_1[ptr_1] < p_list_2[ptr_2]))\r\n\t\t{\r\n\t\t\tfound_1++;\r\n\t\t\tt_size ptr_1_new = ptr_1 + 1;\r\n\t\t\twhile(ptr_1_new < count_1 && p_list_1[ptr_1_new] == p_list_1[ptr_1]) ptr_1_new++;\r\n\t\t\tptr_1 = ptr_1_new;\r\n\t\t}\r\n\t\twhile(ptr_2 < count_2 && (ptr_1 == count_1 || p_list_2[ptr_2] < p_list_1[ptr_1]))\r\n\t\t{\r\n\t\t\tfound_2++;\r\n\t\t\tt_size ptr_2_new = ptr_2 + 1;\r\n\t\t\twhile(ptr_2_new < count_2 && p_list_2[ptr_2_new] == p_list_2[ptr_2]) ptr_2_new++;\r\n\t\t\tptr_2 = ptr_2_new;\r\n\t\t}\r\n\t\twhile(ptr_1 < count_1 && ptr_2 < count_2 && p_list_1[ptr_1] == p_list_2[ptr_2]) {ptr_1++; ptr_2++;}\r\n\t}\r\n\r\n\t\r\n\r\n\tp_list_1_specific.set_count(found_1);\r\n\tp_list_2_specific.set_count(found_2);\r\n\tif (found_1 > 0 || found_2 > 0)\r\n\t{\r\n\t\tfound_1 = found_2 = 0;\r\n\t\tptr_1 = ptr_2 = 0;\r\n\r\n\t\twhile(ptr_1 < count_1 || ptr_2 < count_2)\r\n\t\t{\r\n\t\t\twhile(ptr_1 < count_1 && (ptr_2 == count_2 || p_list_1[ptr_1] < p_list_2[ptr_2]))\r\n\t\t\t{\r\n\t\t\t\tp_list_1_specific[found_1++] = p_list_1[ptr_1];\r\n\t\t\t\tt_size ptr_1_new = ptr_1 + 1;\r\n\t\t\t\twhile(ptr_1_new < count_1 && p_list_1[ptr_1_new] == p_list_1[ptr_1]) ptr_1_new++;\r\n\t\t\t\tptr_1 = ptr_1_new;\r\n\t\t\t}\r\n\t\t\twhile(ptr_2 < count_2 && (ptr_1 == count_1 || p_list_2[ptr_2] < p_list_1[ptr_1]))\r\n\t\t\t{\r\n\t\t\t\tp_list_2_specific[found_2++] = p_list_2[ptr_2];\r\n\t\t\t\tt_size ptr_2_new = ptr_2 + 1;\r\n\t\t\t\twhile(ptr_2_new < count_2 && p_list_2[ptr_2_new] == p_list_2[ptr_2]) ptr_2_new++;\r\n\t\t\t\tptr_2 = ptr_2_new;\r\n\t\t\t}\r\n\t\t\twhile(ptr_1 < count_1 && ptr_2 < count_2 && p_list_1[ptr_1] == p_list_2[ptr_2]) {ptr_1++; ptr_2++;}\r\n\t\t}\r\n\r\n\t}\r\n}\r\n\r\ndouble metadb_handle_list_helper::calc_total_duration(const pfc::list_base_const_t<metadb_handle_ptr> & p_list)\r\n{\r\n\tdouble ret = 0;\r\n\tt_size n, m = p_list.get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tdouble temp = p_list.get_item(n)->get_length();\r\n\t\tif (temp > 0) ret += temp;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nvoid metadb_handle_list_helper::sort_by_path(pfc::list_base_t<metadb_handle_ptr> & p_list)\r\n{\r\n\tsort_by_format_partial(p_list,0,p_list.get_count(),\"%path_sort%\",0);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/modeless_dialog.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid modeless_dialog_manager::g_add(HWND p_wnd)\r\n{\r\n\tservice_enum_t<modeless_dialog_manager> e;\r\n\tservice_ptr_t<modeless_dialog_manager> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tptr->add(p_wnd);\r\n\t} while(e.next(ptr));\r\n}\r\n\r\nvoid modeless_dialog_manager::g_remove(HWND p_wnd)\r\n{\r\n\tservice_enum_t<modeless_dialog_manager> e;\r\n\tservice_ptr_t<modeless_dialog_manager> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tptr->remove(p_wnd);\r\n\t} while(e.next(ptr));\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/modeless_dialog.h",
    "content": "#ifndef _MODELESS_DIALOG_H_\r\n#define _MODELESS_DIALOG_H_\r\n\r\n\r\n//! Service for plugging your nonmodal dialog windows into main app loop to receive IsDialogMessage()-translated messages.\\n\r\n//! Note that all methods are valid from main app thread only.\\n\r\n//! Usage: static_api_ptr_t<modeless_dialog_manager> or modeless_dialog_manager::g_add / modeless_dialog_manager::g_remove.\r\nclass NOVTABLE modeless_dialog_manager : public service_base\r\n{\r\npublic:\r\n\t//! Adds specified window to global list of windows to receive IsDialogMessage().\r\n\tvirtual void add(HWND p_wnd) = 0;\r\n\t//! Removes specified window from global list of windows to receive IsDialogMessage().\r\n\tvirtual void remove(HWND p_wnd) = 0;\r\n\r\n\t//! Static helper; see add().\r\n\tstatic void g_add(HWND p_wnd);\r\n\t//! Static helper; see remove().\r\n\tstatic void g_remove(HWND p_wnd);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(modeless_dialog_manager);\r\n};\r\n\r\n#endif //_MODELESS_DIALOG_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/packet_decoder.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid packet_decoder::g_open(service_ptr_t<packet_decoder> & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort)\r\n{\r\n\tservice_enum_t<packet_decoder_entry> e;\r\n\tservice_ptr_t<packet_decoder_entry> ptr;\r\n\twhile(e.next(ptr)) {\r\n\t\tif (ptr->is_our_setup(p_owner,p_param1,p_param2,p_param2size)) {\r\n\t\t\tptr->open(p_out,p_decode,p_owner,p_param1,p_param2,p_param2size,p_abort);\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\tthrow exception_io_data();\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/packet_decoder.h",
    "content": "//! Provides interface to decode various audio data types to PCM. Use packet_decoder_factory_t template to register.\r\n\r\nclass packet_decoder : public service_base {\r\nprotected:\r\n\t//! Prototype of function that must be implemented by packet_decoder implementation but is not accessible through packet_decoder interface itself.\r\n\t//! Determines whether specific packet_decoder implementation supports specified decoder setup data.\r\n\tstatic bool g_is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) {return false;}\r\n\r\n\t//! Prototype of function that must be implemented by packet_decoder implementation but is not accessible through packet_decoder interface itself.\r\n\t//! Initializes packet decoder instance with specified decoder setup data. This is called only once, before any other methods.\r\n\t//! @param p_decode If set to true, decode() and reset_after_seek() calls can be expected later. If set to false, those methods will not be called on this packet_decoder instance - for an example when caller is only retrieving information about the file rather than preparing to decode it.\r\n\tvoid open(const GUID & p_owner,bool p_decode,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) {throw exception_io_data();}\r\npublic:\r\n\r\n\r\n\t//! Forwards additional information about stream being decoded. \\n\r\n\t//! Calling: this must be called immediately after packet_decoder object is created, before any other methods are called.\\n\r\n\t//! Implementation: this is called after open() (which is called by implementation framework immediately after creation), and before any other methods are called.\r\n\tvirtual t_size set_stream_property(const GUID & p_type,t_size p_param1,const void * p_param2,t_size p_param2size) = 0;\r\n\r\n\t\r\n\t//! Retrieves additional user-readable tech infos that decoder can provide.\r\n\t//! @param p_info Interface receiving information about the stream being decoded. Note that it already contains partial info about the file; existing info should not be erased, decoder-provided info should be merged with it.\r\n\tvirtual void get_info(file_info & p_info) = 0;\r\n\r\n\t//! Returns many frames back to start decoding when seeking.\r\n\tvirtual unsigned get_max_frame_dependency()=0;\r\n\t//! Returns much time back to start decoding when seeking (for containers where going back by specified number of frames is not trivial).\r\n\tvirtual double get_max_frame_dependency_time()=0;\r\n\r\n\t//! Flushes decoder after seeking.\r\n\tvirtual void reset_after_seek()=0;\r\n\r\n\t//! Decodes a block of audio data.\\n\r\n\t//! It may return empty chunk even when successful (caused by encoder+decoder delay for an example), caller must check for it and handle it appropriately.\r\n\tvirtual void decode(const void * p_buffer,t_size p_bytes,audio_chunk & p_chunk,abort_callback & p_abort)=0;\r\n\r\n\t//! Returns whether this packet decoder supports analyze_first_frame() function.\r\n\tvirtual bool analyze_first_frame_supported() = 0;  \r\n\t//! Optional. Some codecs need to analyze first frame of the stream to return additional info about the stream, such as encoding setup. This can be only called immediately after instantiation (and set_stream_property() if present), before any actual decoding or get_info(). Caller can determine whether this method is supported or not by calling analyze_first_frame_supported(), to avoid reading first frame when decoder won't utiilize the extra info for an example. If particular decoder can't utilize first frame info in any way (and analyze_first_frame_supported() returns false), this function should do nothing and succeed.\r\n\tvirtual void analyze_first_frame(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) = 0;\r\n\t\r\n\t//! Static helper, creates a packet_decoder instance and initializes it with specific decoder setup data.\r\n\tstatic void g_open(service_ptr_t<packet_decoder> & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort);\r\n\r\n\tstatic const GUID owner_MP4,owner_matroska,owner_MP3,owner_MP2,owner_MP1,owner_MP4_ALAC,owner_ADTS,owner_ADIF, owner_Ogg, owner_MP4_AMR, owner_MP4_AMR_WB;\r\n\r\n\tstruct matroska_setup\r\n\t{\r\n\t\tconst char * codec_id;\r\n\t\tunsigned sample_rate,sample_rate_output;\r\n\t\tunsigned channels;\r\n\t\tunsigned codec_private_size;\r\n\t\tconst void * codec_private;\r\n\t};\r\n\t//owner_MP4: param1 - codec ID (MP4 audio type), param2 - MP4 codec initialization data\r\n\t//owner_MP3: raw MP3/MP2 file, parameters ignored\r\n\t//owner_matroska: param2 = matroska_setup struct, param2size size must be equal to sizeof(matroska_setup)\r\n\r\n\r\n\t//these are used to initialize PCM decoder\r\n\tstatic const GUID property_samplerate,property_bitspersample,property_channels,property_byteorder,property_signed,property_channelmask;\r\n\t//property_samplerate : param1 == sample rate in hz\r\n\t//property_bitspersample : param1 == bits per sample\r\n\t//property_channels : param1 == channel count\r\n\t//property_byteorder : if (param1) little_endian; else big_endian;\r\n\t//property_signed : if (param1) signed; else unsigned;\r\n\r\n\r\n\t//property_ogg_header : p_param1 = unused, p_param2 = ogg_packet structure, retval: 0 when more headers are wanted, 1 when done parsing headers\r\n\t//property_ogg_query_sample_rate : returns sample rate, no parameters\r\n\t//property_ogg_packet : p_param1 = unused, p_param2 = ogg_packet strucute\r\n\tstatic const GUID property_ogg_header, property_ogg_query_sample_rate, property_ogg_packet;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(packet_decoder,service_base);\r\n};\r\n\r\nclass packet_decoder_streamparse : public packet_decoder\r\n{\r\npublic:\r\n\tvirtual void decode_ex(const void * p_buffer,t_size p_bytes,t_size & p_bytes_processed,audio_chunk & p_chunk,abort_callback & p_abort) = 0;\r\n\tvirtual void analyze_first_frame_ex(const void * p_buffer,t_size p_bytes,t_size & p_bytes_processed,abort_callback & p_abort) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(packet_decoder_streamparse,packet_decoder);\r\n};\r\n\r\nclass packet_decoder_entry : public service_base\r\n{\r\npublic:\r\n\tvirtual bool is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) = 0;\r\n\tvirtual void open(service_ptr_t<packet_decoder> & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(packet_decoder_entry);\r\n};\r\n\r\n\r\ntemplate<class T>\r\nclass packet_decoder_entry_impl_t : public packet_decoder_entry\r\n{\r\npublic:\r\n\tbool is_our_setup(const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size) {\r\n\t\treturn T::g_is_our_setup(p_owner,p_param1,p_param2,p_param2size);\r\n\t}\r\n\tvoid open(service_ptr_t<packet_decoder> & p_out,bool p_decode,const GUID & p_owner,t_size p_param1,const void * p_param2,t_size p_param2size,abort_callback & p_abort) {\r\n\t\tassert(is_our_setup(p_owner,p_param1,p_param2,p_param2size));\r\n\t\tservice_ptr_t<T> instance = new service_impl_t<T>();\r\n\t\tinstance->open(p_owner,p_decode,p_param1,p_param2,p_param2size,p_abort);\r\n\t\tp_out = instance.get_ptr();\r\n\t}\r\n};\r\n\r\ntemplate<typename T>\r\nclass packet_decoder_factory_t : public service_factory_single_t<packet_decoder_entry_impl_t<T> > {};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/play_callback.h",
    "content": "#ifndef _PLAY_CALLBACK_H_\r\n#define _PLAY_CALLBACK_H_\r\n\r\n/*!\r\nClass receiving notifications about playback events. Note that all methods are called only from app's main thread.\r\nUse play_callback_manager to register your dynamically created instances. Statically registered version is available too - see play_callback_static.\r\n*/\r\nclass NOVTABLE play_callback {\r\npublic:\r\n\t//! Playback process is being initialized. on_playback_new_track() should be called soon after this when first file is successfully opened for decoding.\r\n\tvirtual void FB2KAPI on_playback_starting(play_control::t_track_command p_command,bool p_paused)=0;\r\n\t//! Playback advanced to new track.\r\n\tvirtual void FB2KAPI on_playback_new_track(metadb_handle_ptr p_track) = 0;\r\n\t//! Playback stopped.\r\n\tvirtual void FB2KAPI on_playback_stop(play_control::t_stop_reason p_reason)=0;\r\n\t//! User has seeked to specific time.\r\n\tvirtual void FB2KAPI on_playback_seek(double p_time)=0;\r\n\t//! Called on pause/unpause.\r\n\tvirtual void FB2KAPI on_playback_pause(bool p_state)=0;\r\n\t//! Called when currently played file gets edited.\r\n\tvirtual void FB2KAPI on_playback_edited(metadb_handle_ptr p_track) = 0;\r\n\t//! Dynamic info (VBR bitrate etc) change.\r\n\tvirtual void FB2KAPI on_playback_dynamic_info(const file_info & p_info) = 0;\r\n\t//! Per-track dynamic info (stream track titles etc) change. Happens less often than on_playback_dynamic_info().\r\n\tvirtual void FB2KAPI on_playback_dynamic_info_track(const file_info & p_info) = 0;\r\n\t//! Called every second, for time display\r\n\tvirtual void FB2KAPI on_playback_time(double p_time) = 0;\r\n\t//! User changed volume settings. Possibly called when not playing.\r\n\t//! @param p_new_val new volume level in dB; 0 for full volume.\r\n\tvirtual void FB2KAPI on_volume_change(float p_new_val) = 0;\r\n\r\n\tenum {\r\n\t\tflag_on_playback_starting\t\t\t= 1 << 0,\r\n\t\tflag_on_playback_new_track\t\t\t= 1 << 1, \r\n\t\tflag_on_playback_stop\t\t\t\t= 1 << 2,\r\n\t\tflag_on_playback_seek\t\t\t\t= 1 << 3,\r\n\t\tflag_on_playback_pause\t\t\t\t= 1 << 4,\r\n\t\tflag_on_playback_edited\t\t\t\t= 1 << 5,\r\n\t\tflag_on_playback_dynamic_info\t\t= 1 << 6,\r\n\t\tflag_on_playback_dynamic_info_track\t= 1 << 7,\r\n\t\tflag_on_playback_time\t\t\t\t= 1 << 8,\r\n\t\tflag_on_volume_change\t\t\t\t= 1 << 9,\r\n\r\n\t\tflag_on_playback_all = flag_on_playback_starting | flag_on_playback_new_track | \r\n\t\t\tflag_on_playback_stop | flag_on_playback_seek | \r\n\t\t\tflag_on_playback_pause | flag_on_playback_edited |\r\n\t\t\tflag_on_playback_dynamic_info | flag_on_playback_dynamic_info_track | flag_on_playback_time,\r\n\t};\r\nprotected:\r\n\tplay_callback() {}\r\n\t~play_callback() {}\r\n};\r\n\r\n//! Standard API (always present); manages registrations of dynamic play_callbacks.\r\n//! Usage: use static_api_ptr_t<play_callback_manager>.\r\n//! Do not reimplement.\r\nclass NOVTABLE play_callback_manager : public service_base\r\n{\r\npublic:\r\n\t//! Registers a play_callback object.\r\n\t//! @param p_callback Interface to register.\r\n\t//! @param p_flags Indicates which notifications are requested.\r\n\tvirtual void FB2KAPI register_callback(play_callback * p_callback,unsigned p_flags,bool p_forward_status_on_register) = 0;\r\n\t//! Unregisters a play_callback object.\r\n\t//! @p_callback Previously registered interface to unregister.\r\n\tvirtual void FB2KAPI unregister_callback(play_callback * p_callback) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(play_callback_manager);\r\n};\r\n\r\n\r\n//! Static (autoregistered) version of play_callback. Use play_callback_static_factory_t to register.\r\nclass play_callback_static : public service_base, public play_callback {\r\npublic:\r\n\t//! Controls which methods your callback wants called; returned value should not change in run time, you should expect it to be queried only once (on startup). See play_callback::flag_* constants.\r\n\tvirtual unsigned get_flags() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(play_callback_static);\r\n};\r\n\r\ntemplate<typename T>\r\nclass play_callback_static_factory_t : public service_factory_single_t<T> {};\r\n\r\n\r\n//! Gets notified about tracks being played. Notification occurs when at least 60s of the track has been played, or the track has reached its end after at least 1/3 of it has been played through.\r\n//! Use playback_statistics_collector_factory_t to register.\r\nclass NOVTABLE playback_statistics_collector : public service_base {\r\npublic:\r\n\tvirtual void on_item_played(metadb_handle_ptr p_item) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_statistics_collector);\r\n};\r\n\r\ntemplate<typename T>\r\nclass playback_statistics_collector_factory_t : public service_factory_single_t<T> {};\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playable_location.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nint playable_location::g_compare(const playable_location & p_item1,const playable_location & p_item2) {\r\n\tint ret = metadb::path_compare(p_item1.get_path(),p_item2.get_path());\r\n\tif (ret != 0) return 0;\r\n\treturn pfc::compare_t(p_item1.get_subsong(),p_item2.get_subsong());\r\n}\r\n\r\npfc::string_base & operator<<(pfc::string_base & p_fmt,const playable_location & p_location)\r\n{\r\n\tp_fmt << \"\\\"\" << file_path_display(p_location.get_path()) << \"\\\"\";\r\n\tt_uint32 index = p_location.get_subsong_index();\r\n\tif (index != 0) p_fmt << \" / index: \" << p_location.get_subsong_index();\r\n\treturn p_fmt;\r\n}\r\n\r\n\r\nbool playable_location::operator==(const playable_location & p_other) const {\r\n\treturn metadb::path_compare(get_path(),p_other.get_path()) == 0 && get_subsong() == p_other.get_subsong();\r\n}\r\nbool playable_location::operator!=(const playable_location & p_other) const {\r\n\treturn !(*this == p_other);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playable_location.h",
    "content": "#ifndef _FOOBAR2000_PLAYABLE_LOCATION_H_\r\n#define _FOOBAR2000_PLAYABLE_LOCATION_H_\r\n\r\n#include \"service.h\"\r\n\r\n//playable_location stores location of a playable resource, currently implemented as file path and integer for indicating multiple playable \"subsongs\" per file\r\n//also see: file_info.h\r\n//for getting more info about resource referenced by a playable_location, see metadb.h\r\n\r\n//char* strings are all UTF-8\r\n\r\nclass NOVTABLE playable_location//interface (for passing around between DLLs)\r\n{\r\npublic:\r\n\tvirtual const char * get_path() const =0;\r\n\tvirtual void set_path(const char*)=0;\r\n\tvirtual t_uint32 get_subsong() const =0;\r\n\tvirtual void set_subsong(t_uint32)=0;\r\n\t\r\n\tvoid copy(const playable_location & p_other) {\r\n\t\tset_path(p_other.get_path());\r\n\t\tset_subsong(p_other.get_subsong());\r\n\t}\r\n\r\n\tstatic int g_compare(const playable_location & p_item1,const playable_location & p_item2);\r\n\r\n\tconst playable_location & operator=(const playable_location & src) {copy(src);return *this;}\t\r\n\r\n\tbool operator==(const playable_location & p_other) const;\r\n\tbool operator!=(const playable_location & p_other) const;\r\n\r\n\tinline bool is_empty() {return get_path()[0]==0 && get_subsong()==0;}\r\n\tinline void reset() {set_path(\"\");set_subsong(0);}\r\n\tinline t_uint32 get_subsong_index() const {return get_subsong();}\r\n\tinline void set_subsong_index(t_uint32 v) {set_subsong(v);}\r\n\r\nprotected:\r\n\tplayable_location() {}\r\n\t~playable_location() {}\r\n};\r\n\r\ntypedef playable_location * pplayable_location;\r\ntypedef playable_location const * pcplayable_location;\r\ntypedef playable_location & rplayable_location;\r\ntypedef playable_location const & rcplayable_location;\r\n\r\nclass playable_location_impl : public playable_location//implementation\r\n{\r\npublic:\r\n\tconst char * get_path() const {return m_path;}\r\n\tvoid set_path(const char* p_path) {m_path=p_path;}\r\n\tt_uint32 get_subsong() const {return m_subsong;}\r\n\tvoid set_subsong(t_uint32 p_subsong) {m_subsong=p_subsong;}\r\n\r\n\tconst playable_location_impl & operator=(const playable_location & src) {copy(src);return *this;}\r\n\tconst playable_location_impl & operator=(const playable_location_impl & src) {copy(src);return *this;}\r\n\r\n\tplayable_location_impl() : m_subsong(0) {}\r\n\tplayable_location_impl(const char * p_path,t_uint32 p_subsong) : m_path(p_path), m_subsong(p_subsong) {}\r\n\tplayable_location_impl(const playable_location & src) {copy(src);}\r\n\tplayable_location_impl(const playable_location_impl & src) {copy(src);}\r\n\r\nprivate:\r\n\tpfc::string_simple m_path;\r\n\tt_uint32 m_subsong;\r\n};\r\n\r\n// usage: something( make_playable_location(\"file://c:\\blah.ogg\",0) );\r\n// only for use as a parameter to a function taking const playable_location &\r\nclass make_playable_location : public playable_location\r\n{\r\n\tconst char * path;\r\n\tt_uint32 num;\r\n\t\r\n\tvoid set_path(const char*) {throw pfc::exception_not_implemented();}\r\n\tvoid set_subsong(t_uint32) {throw pfc::exception_not_implemented();}\r\n\r\npublic:\r\n\tconst char * get_path() const {return path;}\r\n\tt_uint32 get_subsong() const {return num;}\r\n\r\n\tmake_playable_location(const char * p_path,t_uint32 p_num) : path(p_path), num(p_num) {}\r\n};\r\n\r\npfc::string_base & operator<<(pfc::string_base & p_fmt,const playable_location & p_location);\r\n\r\n#endif //_FOOBAR2000_PLAYABLE_LOCATION_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playback_control.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\ndouble playback_control::playback_get_length()\r\n{\r\n\tdouble rv = 0;\r\n\tmetadb_handle_ptr ptr;\r\n\tif (get_now_playing(ptr))\r\n\t{\r\n\t\trv = ptr->get_length();\r\n\t}\r\n\treturn rv;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playback_control.h",
    "content": "#ifndef _PLAY_CONTROL_H_\r\n#define _PLAY_CONTROL_H_\r\n\r\n//! Provides control for various playback-related operations.\r\n//! All methods provided by this interface work from main app thread only. Calling from another thread will do nothing or trigger an exception. If you need to trigger one of playback_control methods from another thread, see main_thread_callback.\r\n//! Do not call playback_control methods from inside any kind of global callback (e.g. playlist callback), otherwise race conditions may occur.\r\n//! Use static_api_ptr_t to instantiate. See static_api_ptr_t documentation for more info.\r\nclass NOVTABLE playback_control : public service_base\r\n{\r\npublic:\r\n\r\n\tenum t_stop_reason {\r\n\t\tstop_reason_user = 0,\r\n\t\tstop_reason_eof,\r\n\t\tstop_reason_starting_another,\r\n\t\tstop_reason_shutting_down,\r\n\t};\r\n\r\n\r\n\tenum t_track_command {\r\n\t\ttrack_command_default = 0,\r\n\t\ttrack_command_play,\r\n\t\ttrack_command_next,\r\n\t\ttrack_command_prev,\r\n\t\ttrack_command_settrack,\r\n\t\ttrack_command_rand,\r\n\t\ttrack_command_resume,\r\n\t};\r\n\r\n\t//! Retrieves now playing item handle.\r\n\t//! @returns true on success, false on failure (not playing).\r\n\tvirtual bool get_now_playing(metadb_handle_ptr & p_out) = 0;\r\n\t//! Starts playback. If playback is already active, existing process is stopped first.\r\n\t//! @param p_command Specifies what track to start playback from. See t_track_Command enum for more info.\r\n\t//! @param p_paused Specifies whether playback should be started as paused.\r\n\tvirtual void start(t_track_command p_command = track_command_play,bool p_paused = false) = 0;\r\n\t//! Stops playback.\r\n\tvirtual void stop() = 0;\r\n\t//! Returns whether playback is active.\r\n\tvirtual bool is_playing() = 0;\r\n\t//! Returns whether playback is active and in paused state.\r\n\tvirtual bool is_paused() = 0;\r\n\t//! Toggles pause state if playback is active.\r\n\t//! @param p_state set to true when pausing or to false when unpausing.\r\n\tvirtual void pause(bool p_state) = 0;\r\n\r\n\t//! Retrieves stop-after-current-track option state.\r\n\tvirtual bool get_stop_after_current() = 0;\r\n\t//! Alters stop-after-current-track option state.\r\n\tvirtual void set_stop_after_current(bool p_state) = 0;\r\n\t\r\n\t//! Alters playback volume level.\r\n\t//! @param p_value volume in dB; 0 for full volume.\r\n\tvirtual void set_volume(float p_value) = 0;\r\n\t//! Retrieves playback volume level.\r\n\t//! @returns current playback volume level, in dB; 0 for full volume.\r\n\tvirtual float get_volume() = 0;\r\n\t//! Alters playback volume level one step up.\r\n\tvirtual void volume_up() = 0;\r\n\t//! Alters playback volume level one step down.\r\n\tvirtual void volume_down() = 0;\r\n\t//! Toggles playback mute state.\r\n\tvirtual void volume_mute_toggle() = 0;\r\n\t//! Seeks in currenly played track to specified time.\r\n\t//! @param p_time target time in seconds.\r\n\tvirtual void playback_seek(double p_time) = 0;\r\n\t//! Seeks in currently played track by specified time forward or back.\r\n\t//! @param p_delta time in seconds to seek by; can be positive to seek forward or negative to seek back.\r\n\tvirtual void playback_seek_delta(double p_delta) = 0;\r\n\t//! Returns whether currently played track is seekable. If it's not, playback_seek/playback_seek_delta calls will be ignored.\r\n\tvirtual bool playback_can_seek() = 0;\r\n\t//! Returns current playback position within currently played track, in seconds.\r\n\tvirtual double playback_get_position() = 0;\r\n\r\n\t//! Type used to indicate level of dynamic playback-related info displayed. Safe to use with <> opereators, e.g. level above N always includes information rendered by level N.\r\n\tenum t_display_level {\r\n\t\t//! No playback-related info\r\n\t\tdisplay_level_none,\r\n\t\t//! Static info and is_playing/is_paused stats\r\n\t\tdisplay_level_basic,\r\n\t\t//! Display_level_static + dynamic track titles on e.g. live streams\r\n\t\tdisplay_level_titles,\r\n\t\t//! Display_level_titles + timing + VBR bitrate display etc\r\n\t\tdisplay_level_all,\r\n\t};\r\n\r\n\t//! Renders information about currently playing item.\r\n\t//! @param p_hook Optional callback object overriding fields and functions; set to NULL if not used.\r\n\t//! @param p_out String receiving the output on success.\r\n\t//! @param p_script Titleformat script to use. Use titleformat_compiler service to create one.\r\n\t//! @param p_filter Optional callback object allowing input to be filtered according to context (i.e. removal of linebreak characters present in tags when rendering playlist lines). Set to NULL when not used.\r\n\t//! @param p_level Indicates level of dynamic playback-related info displayed. See t_display_level enum for more details.\r\n\t//! @returns true on success, false when no item is currently being played.\r\n\tvirtual bool playback_format_title(titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t<class titleformat_object> & p_script,titleformat_text_filter * p_filter,t_display_level p_level) = 0;\r\n\t\r\n\r\n\r\n\t//! Helper; renders info about any item, including currently playing item info if the item is currently played.\r\n\tbool playback_format_title_ex(metadb_handle_ptr p_item,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t<class titleformat_object> & p_script,titleformat_text_filter * p_filter,t_display_level p_level) {\r\n\t\tif (p_item.is_empty()) return playback_format_title(p_hook,p_out,p_script,p_filter,p_level);\r\n\t\tmetadb_handle_ptr temp;\r\n\t\tif (get_now_playing(temp)) {\r\n\t\t\tif (temp == p_item) {\r\n\t\t\t\treturn playback_format_title(p_hook,p_out,p_script,p_filter,p_level);\r\n\t\t\t}\r\n\t\t}\r\n\t\tp_item->format_title(p_hook,p_out,p_script,p_filter);\r\n\t\treturn true;\r\n\t}\r\n\t\r\n\t//! Helper; retrieves length of currently playing item.\r\n\tdouble playback_get_length();\r\n\r\n\t//! Toggles stop-after-current state.\r\n\tvoid toggle_stop_after_current() {set_stop_after_current(!get_stop_after_current());}\r\n\t//! Toggles pause state.\r\n\tvoid toggle_pause() {pause(!is_paused());}\r\n\r\n\t//! Starts playback if playback is inactive, otherwise toggles pause.\r\n\tvoid play_or_pause() {if (is_playing()) toggle_pause(); else start();}\r\n\r\n\t//deprecated\r\n\tinline void play_start(t_track_command p_command = track_command_play,bool p_paused = false) {start(p_command,p_paused);}\r\n\t//deprecated\r\n\tinline void play_stop() {stop();}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_control);\r\n};\r\n\r\nclass playback_control_v2 : public playback_control {\r\npublic:\r\n\tvirtual float get_volume_step() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(playback_control_v2,playback_control);\r\n};\r\n\r\n//for compatibility with old code\r\ntypedef playback_control play_control;\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playlist.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\nnamespace {\r\n\tclass enum_items_callback_retrieve_item : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tmetadb_handle_ptr m_item;\r\n\tpublic:\r\n\t\tenum_items_callback_retrieve_item() : m_item(0) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tassert(m_item.is_empty());\r\n\t\t\tm_item = p_location;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tinline const metadb_handle_ptr & get_item() {return m_item;}\r\n\t};\r\n\r\n\tclass enum_items_callback_retrieve_selection : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tbool m_state;\r\n\tpublic:\r\n\t\tenum_items_callback_retrieve_selection() : m_state(false) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tm_state = b_selected;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tinline bool get_state() {return m_state;}\r\n\t};\r\n\r\n\tclass enum_items_callback_retrieve_selection_mask : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tbit_array_var & m_out;\r\n\tpublic:\r\n\t\tenum_items_callback_retrieve_selection_mask(bit_array_var & p_out) : m_out(p_out) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tm_out.set(p_index,b_selected);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\tclass enum_items_callback_retrieve_all_items : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tpfc::list_base_t<metadb_handle_ptr> & m_out;\r\n\tpublic:\r\n\t\tenum_items_callback_retrieve_all_items(pfc::list_base_t<metadb_handle_ptr> & p_out) : m_out(p_out) {m_out.remove_all();}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tm_out.add_item(p_location);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\tclass enum_items_callback_retrieve_selected_items : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tpfc::list_base_t<metadb_handle_ptr> & m_out;\r\n\tpublic:\r\n\t\tenum_items_callback_retrieve_selected_items(pfc::list_base_t<metadb_handle_ptr> & p_out) : m_out(p_out) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tif (b_selected) m_out.add_item(p_location);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t};\r\n\r\n\tclass enum_items_callback_count_selection : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tt_size m_counter,m_max;\r\n\tpublic:\r\n\t\tenum_items_callback_count_selection(t_size p_max) : m_max(p_max), m_counter(0) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tif (b_selected) \r\n\t\t\t{\r\n\t\t\t\tif (++m_counter >= m_max) return false;\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\r\n\t\tinline t_size get_count() {return m_counter;}\r\n\t};\r\n\r\n}\r\n\r\nvoid playlist_manager::playlist_get_all_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out)\r\n{\r\n\tplaylist_get_items(p_playlist,out,bit_array_true());\r\n}\r\n\r\nvoid playlist_manager::playlist_get_selected_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out)\r\n{\r\n\tplaylist_enum_items(p_playlist,enum_items_callback_retrieve_selected_items(out),bit_array_true());\r\n}\r\n\r\nvoid playlist_manager::playlist_get_selection_mask(t_size p_playlist,bit_array_var & out)\r\n{\r\n\tplaylist_enum_items(p_playlist,enum_items_callback_retrieve_selection_mask(out),bit_array_true());\r\n}\r\n\r\nbool playlist_manager::playlist_is_item_selected(t_size p_playlist,t_size p_item)\r\n{\r\n\tenum_items_callback_retrieve_selection callback;\r\n\tplaylist_enum_items(p_playlist,callback,bit_array_one(p_item));\r\n\treturn callback.get_state();\r\n}\r\n\r\nbool playlist_manager::playlist_get_item_handle(metadb_handle_ptr & p_out,t_size p_playlist,t_size p_item)\r\n{\r\n\tenum_items_callback_retrieve_item callback;\r\n\tplaylist_enum_items(p_playlist,callback,bit_array_one(p_item));\r\n\tp_out = callback.get_item();\r\n\treturn p_out.is_valid();\r\n}\r\n\r\nbool playlist_manager::playlist_move_selection(t_size p_playlist,int p_delta)\r\n{\r\n\tif (p_delta==0) return true;\r\n\t\r\n\tt_size count = playlist_get_item_count(p_playlist);\r\n\t\r\n\tpfc::array_t<t_size> order; order.set_size(count);\r\n\tpfc::array_t<bool> selection; selection.set_size(count);\r\n\t\r\n\t{\r\n\t\tt_size n;\r\n\t\tfor(n=0;n<count;n++) order[n]=n;\r\n\t}\r\n\r\n\tplaylist_get_selection_mask(p_playlist,bit_array_var_table(selection.get_ptr(),selection.get_size()));\r\n\r\n\tif (p_delta<0)\r\n\t{\r\n\t\tfor(;p_delta<0;p_delta++)\r\n\t\t{\r\n\t\t\tt_size idx;\r\n\t\t\tfor(idx=1;idx<count;idx++)\r\n\t\t\t{\r\n\t\t\t\tif (selection[idx] && !selection[idx-1])\r\n\t\t\t\t{\r\n\t\t\t\t\tpfc::swap_t(order[idx],order[idx-1]);\r\n\t\t\t\t\tpfc::swap_t(selection[idx],selection[idx-1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tfor(;p_delta>0;p_delta--)\r\n\t\t{\r\n\t\t\tt_size idx;\r\n\t\t\tfor(idx=count-2;(int)idx>=0;idx--)\r\n\t\t\t{\r\n\t\t\t\tif (selection[idx] && !selection[idx+1])\r\n\t\t\t\t{\r\n\t\t\t\t\tpfc::swap_t(order[idx],order[idx+1]);\r\n\t\t\t\t\tpfc::swap_t(selection[idx],selection[idx+1]);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn playlist_reorder_items(p_playlist,order.get_ptr(),count);\r\n}\r\n\r\n//retrieving status\r\nt_size playlist_manager::activeplaylist_get_item_count()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return 0;\r\n\telse return playlist_get_item_count(playlist);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_enum_items(enum_items_callback & p_callback,const bit_array & p_mask)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_enum_items(playlist,p_callback,p_mask);\r\n}\r\n\r\nt_size playlist_manager::activeplaylist_get_focus_item()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return infinite;\r\n\telse return playlist_get_focus_item(playlist);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_get_name(pfc::string_base & p_out)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return false;\r\n\telse return playlist_get_name(playlist,p_out);\r\n}\r\n\r\n//modifying playlist\r\nbool playlist_manager::activeplaylist_reorder_items(const t_size * order,t_size count)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_reorder_items(playlist,order,count);\r\n\telse return false;\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_set_selection(const bit_array & affected,const bit_array & status)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_set_selection(playlist,affected,status);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_remove_items(const bit_array & mask)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_remove_items(playlist,mask);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_replace_item(t_size p_item,const metadb_handle_ptr & p_new_item)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_replace_item(playlist,p_item,p_new_item);\r\n\telse return false;\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_set_focus_item(t_size p_item)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_set_focus_item(playlist,p_item);\r\n}\r\n\r\nt_size playlist_manager::activeplaylist_insert_items(t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_insert_items(playlist,p_base,data,p_selection);\r\n\telse return infinite;\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_ensure_visible(t_size p_item)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_ensure_visible(playlist,p_item);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_rename(const char * p_name,t_size p_name_len)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_rename(playlist,p_name,p_name_len);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_is_item_selected(t_size p_item)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_is_item_selected(playlist,p_item);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_get_item_handle(metadb_handle_ptr & p_out,t_size p_item)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_get_item_handle(p_out,playlist,p_item);\r\n\telse return false;\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_move_selection(int p_delta)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_move_selection(playlist,p_delta);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_get_selection_mask(bit_array_var & out)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_get_selection_mask(playlist,out);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_get_all_items(pfc::list_base_t<metadb_handle_ptr> & out)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_get_all_items(playlist,out);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_get_selected_items(pfc::list_base_t<metadb_handle_ptr> & out)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_get_selected_items(playlist,out);\r\n}\r\n\r\nbool playlist_manager::remove_playlist(t_size idx)\r\n{\r\n\treturn remove_playlists(bit_array_one(idx));\r\n}\r\n\r\nbool playlist_incoming_item_filter::process_location(const char * url,pfc::list_base_t<metadb_handle_ptr> & out,bool filter,const char * p_mask,const char * p_exclude,HWND p_parentwnd)\r\n{\r\n\treturn process_locations(pfc::list_single_ref_t<const char*>(url),out,filter,p_mask,p_exclude,p_parentwnd);\r\n}\r\n\r\nvoid playlist_manager::playlist_clear(t_size p_playlist)\r\n{\r\n\tplaylist_remove_items(p_playlist,bit_array_true());\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_clear()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_clear(playlist);\r\n}\r\n\r\nbool playlist_manager::playlist_add_items(t_size playlist,const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection)\r\n{\r\n\treturn playlist_insert_items(playlist,infinite,data,p_selection) != infinite;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_add_items(const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_add_items(playlist,data,p_selection);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::playlist_insert_items_filter(t_size p_playlist,t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select)\r\n{\r\n\tmetadb_handle_list temp;\r\n\tstatic_api_ptr_t<playlist_incoming_item_filter> api;\r\n\tif (!api->filter_items(p_data,temp))\r\n\t\treturn false;\r\n\treturn playlist_insert_items(p_playlist,p_base,temp,bit_array_val(p_select)) != infinite;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_insert_items_filter(t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_insert_items_filter(playlist,p_base,p_data,p_select);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::playlist_insert_locations(t_size p_playlist,t_size p_base,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd)\r\n{\r\n\tmetadb_handle_list temp;\r\n\tstatic_api_ptr_t<playlist_incoming_item_filter> api;\r\n\tif (!api->process_locations(p_urls,temp,true,0,0,p_parentwnd)) return false;\r\n\treturn playlist_insert_items(p_playlist,p_base,temp,bit_array_val(p_select)) != infinite;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_insert_locations(t_size p_base,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_insert_locations(playlist,p_base,p_urls,p_select,p_parentwnd);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::playlist_add_items_filter(t_size p_playlist,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select)\r\n{\r\n\treturn playlist_insert_items_filter(p_playlist,infinite,p_data,p_select);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_add_items_filter(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select)\r\n{\r\n\treturn activeplaylist_insert_items_filter(infinite,p_data,p_select);\r\n}\r\n\r\nbool playlist_manager::playlist_add_locations(t_size p_playlist,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd)\r\n{\r\n\treturn playlist_insert_locations(p_playlist,infinite,p_urls,p_select,p_parentwnd);\r\n}\r\nbool playlist_manager::activeplaylist_add_locations(const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd)\r\n{\r\n\treturn activeplaylist_insert_locations(infinite,p_urls,p_select,p_parentwnd);\r\n}\r\n\r\nvoid playlist_manager::reset_playing_playlist()\r\n{\r\n\tset_playing_playlist(get_active_playlist());\r\n}\r\n\r\nvoid playlist_manager::playlist_clear_selection(t_size p_playlist)\r\n{\r\n\tplaylist_set_selection(p_playlist,bit_array_true(),bit_array_false());\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_clear_selection()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_clear_selection(playlist);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_undo_backup()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_undo_backup(playlist);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_undo_restore()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_undo_restore(playlist);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::activeplaylist_redo_restore()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_redo_restore(playlist);\r\n\telse return false;\r\n}\r\n\r\nvoid playlist_manager::playlist_remove_selection(t_size p_playlist,bool p_crop)\r\n{\r\n\tbit_array_bittable table(playlist_get_item_count(p_playlist));\r\n\tplaylist_get_selection_mask(p_playlist,table);\r\n\tif (p_crop) playlist_remove_items(p_playlist,bit_array_not(table));\r\n\telse playlist_remove_items(p_playlist,table);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_remove_selection(bool p_crop)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_remove_selection(playlist,p_crop);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_item_format_title(t_size p_item,titleformat_hook * p_hook,pfc::string_base & out,const service_ptr_t<titleformat_object> & p_script,titleformat_text_filter * p_filter,play_control::t_display_level p_playback_info_level)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) out = \"NJET\";\r\n\telse playlist_item_format_title(playlist,p_item,p_hook,out,p_script,p_filter,p_playback_info_level);\r\n}\r\n\r\nvoid playlist_manager::playlist_set_selection_single(t_size p_playlist,t_size p_item,bool p_state)\r\n{\r\n\tplaylist_set_selection(p_playlist,bit_array_one(p_item),bit_array_val(p_state));\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_set_selection_single(t_size p_item,bool p_state)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_set_selection_single(playlist,p_item,p_state);\r\n}\r\n\r\nt_size playlist_manager::playlist_get_selection_count(t_size p_playlist,t_size p_max)\r\n{\r\n\tenum_items_callback_count_selection callback(p_max);\r\n\tplaylist_enum_items(p_playlist,callback,bit_array_true());\r\n\treturn callback.get_count();\r\n}\r\n\r\nt_size playlist_manager::activeplaylist_get_selection_count(t_size p_max)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_get_selection_count(playlist,p_max);\r\n\telse return 0;\r\n}\r\n\r\nbool playlist_manager::playlist_get_focus_item_handle(metadb_handle_ptr & p_out,t_size p_playlist)\r\n{\r\n\tt_size index = playlist_get_focus_item(p_playlist);\r\n\tif (index == infinite) return false;\r\n\treturn playlist_get_item_handle(p_out,p_playlist,index);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_get_focus_item_handle(metadb_handle_ptr & p_out)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_get_focus_item_handle(p_out,playlist);\r\n\telse return false;\r\n}\r\n\r\nt_size playlist_manager::find_playlist(const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size n, m = get_playlist_count();\r\n\tpfc::string8_fastalloc temp;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tif (!playlist_get_name(n,temp)) break;\r\n\t\tif (stricmp_utf8_ex(temp,temp.length(),p_name,p_name_length) == 0) return n;\r\n\t}\r\n\treturn infinite;\r\n}\r\n\r\nt_size playlist_manager::find_or_create_playlist(const char * p_name,t_size p_name_length)\r\n{\r\n\tt_size index = find_playlist(p_name,p_name_length);\r\n\tif (index != infinite) return index;\r\n\treturn create_playlist(p_name,p_name_length,infinite);\r\n}\r\n\r\nt_size playlist_manager::create_playlist_autoname(t_size p_index) {\t\r\n\tstatic const char new_playlist_text[] = \"New Playlist\";\r\n\tif (find_playlist(new_playlist_text,infinite) == infinite) return create_playlist(new_playlist_text,infinite,p_index);\r\n\tfor(t_size walk = 2; ; walk++) {\r\n\t\tpfc::string_fixed_t<64> namebuffer;\r\n\t\tnamebuffer << new_playlist_text << \" (\" << walk << \")\";\r\n\t\tif (find_playlist(namebuffer,infinite) == infinite) return create_playlist(namebuffer,infinite,p_index);\r\n\t}\r\n}\r\n\r\nbool playlist_manager::activeplaylist_sort_by_format(const char * spec,bool p_sel_only)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) return playlist_sort_by_format(playlist,spec,p_sel_only);\r\n\telse return false;\r\n}\r\n\r\nbool playlist_manager::highlight_playing_item()\r\n{\r\n\tt_size playlist,item;\r\n\tif (!get_playing_item_location(&playlist,&item)) return false;\r\n\tset_active_playlist(playlist);\r\n\tplaylist_set_focus_item(playlist,item);\r\n\tplaylist_set_selection(playlist,bit_array_true(),bit_array_one(item));\r\n\tplaylist_ensure_visible(playlist,item);\r\n\treturn true;\r\n}\r\n\r\nvoid playlist_manager::playlist_get_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out,const bit_array & p_mask)\r\n{\r\n\tplaylist_enum_items(p_playlist,enum_items_callback_retrieve_all_items(out),p_mask);\r\n}\r\n\r\nvoid playlist_manager::activeplaylist_get_items(pfc::list_base_t<metadb_handle_ptr> & out,const bit_array & p_mask)\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist != infinite) playlist_get_items(playlist,out,p_mask);\r\n}\r\n\r\nvoid playlist_manager::active_playlist_fix()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite)\r\n\t{\r\n\t\tt_size max = get_playlist_count();\r\n\t\tif (max == 0)\r\n\t\t{\r\n\t\t\tcreate_playlist_autoname();\r\n\t\t}\r\n\t\tset_active_playlist(0);\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\tclass enum_items_callback_remove_list : public playlist_manager::enum_items_callback\r\n\t{\r\n\t\tconst metadb_handle_list & m_data;\r\n\t\tbit_array_var & m_table;\r\n\t\tt_size m_found;\r\n\tpublic:\r\n\t\tenum_items_callback_remove_list(const metadb_handle_list & p_data,bit_array_var & p_table) : m_data(p_data), m_table(p_table), m_found(0) {}\r\n\t\tbool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected)\r\n\t\t{\r\n\t\t\tbool found = m_data.bsearch_by_pointer(p_location) != infinite;\r\n\t\t\tm_table.set(p_index,found);\r\n\t\t\tif (found) m_found++;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\t\r\n\t\tinline t_size get_found() const {return m_found;}\r\n\t};\r\n}\r\n\r\nvoid playlist_manager::remove_items_from_all_playlists(const pfc::list_base_const_t<metadb_handle_ptr> & p_data)\r\n{\r\n\tt_size playlist_num, playlist_max = get_playlist_count();\r\n\tif (playlist_max != infinite)\r\n\t{\r\n\t\tmetadb_handle_list temp;\r\n\t\ttemp.add_items(p_data);\r\n\t\ttemp.sort_by_pointer();\r\n\t\tfor(playlist_num = 0; playlist_num < playlist_max; playlist_num++ )\r\n\t\t{\r\n\t\t\tt_size playlist_item_count = playlist_get_item_count(playlist_num);\r\n\t\t\tif (playlist_item_count == infinite) break;\r\n\t\t\tbit_array_bittable table(playlist_item_count);\r\n\t\t\tenum_items_callback_remove_list callback(temp,table);\r\n\t\t\tplaylist_enum_items(playlist_num,callback,bit_array_true());\r\n\t\t\tif (callback.get_found()>0)\r\n\t\t\t\tplaylist_remove_items(playlist_num,table);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nbool playlist_manager::get_all_items(pfc::list_base_t<metadb_handle_ptr> & out)\r\n{\r\n\tt_size n, m = get_playlist_count();\r\n\tif (m == infinite) return false;\r\n\tenum_items_callback_retrieve_all_items callback(out);\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tplaylist_enum_items(n,callback,bit_array_true());\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nt_uint32 playlist_manager::activeplaylist_lock_get_filter_mask()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return ~0;\r\n\telse return playlist_lock_get_filter_mask(playlist);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_is_undo_available()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return false;\r\n\telse return playlist_is_undo_available(playlist);\r\n}\r\n\r\nbool playlist_manager::activeplaylist_is_redo_available()\r\n{\r\n\tt_size playlist = get_active_playlist();\r\n\tif (playlist == infinite) return false;\r\n\telse return playlist_is_redo_available(playlist);\r\n}\r\n\r\nbool playlist_manager::remove_playlist_switch(t_size idx)\r\n{\r\n\tbool need_switch = get_active_playlist() == idx;\r\n\tif (remove_playlist(idx))\r\n\t{\r\n\t\tif (need_switch)\r\n\t\t{\r\n\t\t\tt_size total = get_playlist_count();\r\n\t\t\tif (total > 0)\r\n\t\t\t{\r\n\t\t\t\tif (idx >= total) idx = total-1;\r\n\t\t\t\tset_active_playlist(idx);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\n\r\n\r\nbool t_playback_queue_item::operator==(const t_playback_queue_item & p_item) const\r\n{\r\n\treturn m_handle == p_item.m_handle && m_playlist == p_item.m_playlist && m_item == p_item.m_item;\r\n}\r\n\r\nbool t_playback_queue_item::operator!=(const t_playback_queue_item & p_item) const\r\n{\r\n\treturn m_handle != p_item.m_handle || m_playlist != p_item.m_playlist || m_item != p_item.m_item;\r\n}\r\n\r\n\r\n\r\nbool playlist_manager::activeplaylist_execute_default_action(t_size p_item) {\r\n\tt_size idx = get_active_playlist();\r\n\tif (idx == infinite) return false;\r\n\telse return playlist_execute_default_action(idx,p_item);\r\n}\r\n\r\nnamespace {\r\n\tclass completion_notify_dfd : public completion_notify {\r\n\tpublic:\r\n\t\tcompletion_notify_dfd(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,service_ptr_t<process_locations_notify> p_notify) : m_data(p_data), m_notify(p_notify) {}\r\n\t\tvoid on_completion(unsigned p_code) {\r\n\t\t\tswitch(p_code) {\r\n\t\t\tcase metadb_io::load_info_aborted:\r\n\t\t\t\tm_notify->on_aborted();\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tm_notify->on_completion(m_data);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tmetadb_handle_list m_data;\r\n\t\tservice_ptr_t<process_locations_notify> m_notify;\r\n\t};\r\n};\r\n\r\nvoid dropped_files_data_impl::to_handles_async_ex(t_uint32 p_op_flags,HWND p_parentwnd,service_ptr_t<process_locations_notify> p_notify) {\r\n\tif (m_is_paths) {\r\n\t\tstatic_api_ptr_t<playlist_incoming_item_filter_v2>()->process_locations_async(\r\n\t\t\tm_paths,\r\n\t\t\tp_op_flags,\r\n\t\t\tNULL,\r\n\t\t\tNULL,\r\n\t\t\tp_parentwnd,\r\n\t\t\tp_notify);\r\n\t} else {\r\n\t\tt_uint32 flags = 0;\r\n\t\tif (p_op_flags & playlist_incoming_item_filter_v2::op_flag_background) flags |= metadb_io_v2::op_flag_background;\r\n\t\tif (p_op_flags & playlist_incoming_item_filter_v2::op_flag_delay_ui) flags |= metadb_io_v2::op_flag_delay_ui;\r\n\t\tstatic_api_ptr_t<metadb_io_v2>()->load_info_async(m_handles,metadb_io::load_info_default,p_parentwnd,flags,new service_impl_t<completion_notify_dfd>(m_handles,p_notify));\r\n\t}\r\n}\r\nvoid dropped_files_data_impl::to_handles_async(bool p_filter,HWND p_parentwnd,service_ptr_t<process_locations_notify> p_notify) {\r\n\tto_handles_async_ex(p_filter ? 0 : playlist_incoming_item_filter_v2::op_flag_no_filter,p_parentwnd,p_notify);\r\n}\r\n\r\nbool dropped_files_data_impl::to_handles(pfc::list_base_t<metadb_handle_ptr> & p_out,bool p_filter,HWND p_parentwnd) {\r\n\tif (m_is_paths) {\r\n\t\treturn static_api_ptr_t<playlist_incoming_item_filter>()->process_locations(m_paths,p_out,p_filter,NULL,NULL,p_parentwnd);\r\n\t} else {\r\n\t\tif (static_api_ptr_t<metadb_io>()->load_info_multi(m_handles,metadb_io::load_info_default,p_parentwnd,true) == metadb_io::load_info_aborted) return false;\r\n\t\tp_out = m_handles;\r\n\t\treturn true;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playlist.h",
    "content": "#ifndef _PLAYLIST_H_\r\n#define _PLAYLIST_H_\r\n\r\n//! This interface allows filtering of playlist modification operations.\\n\r\n//! Implemented by components \"locking\" playlists; use playlist_manager::playlist_lock_install() etc to takeover specific playlist with your instance of playlist_lock.\r\nclass NOVTABLE playlist_lock : public service_base {\r\npublic:\r\n\tenum {\r\n\t\tfilter_add\t\t= 1 << 0,\r\n\t\tfilter_remove\t= 1 << 1,\r\n\t\tfilter_reorder  = 1 << 2,\r\n\t\tfilter_replace  = 1 << 3,\r\n\t\tfilter_rename\t= 1 << 4,\r\n\t\tfilter_remove_playlist = 1 << 5,\r\n\t\tfilter_default_action = 1 << 6,\r\n\t};\r\n\r\n\t//! Queries whether specified item insertiion operation is allowed in the locked playlist.\r\n\t//! @param p_base Index from which the items are being inserted.\r\n\t//! @param p_data Items being inserted.\r\n\t//! @param p_selection Caller-requested selection state of items being inserted.\r\n\t//! @returns True to allow the operation, false to block it.\r\n\tvirtual bool query_items_add(t_size p_base, const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const bit_array & p_selection) = 0;\r\n\t//! Queries whether specified item reorder operation is allowed in the locked playlist.\r\n\t//! @param p_order Pointer to array containing permutation defining requested reorder operation.\r\n\t//! @param p_count Number of items in array pointed to by p_order. This should always be equal to number of items on the locked playlist.\r\n\t//! @returns True to allow the operation, false to block it.\r\n\tvirtual bool query_items_reorder(const t_size * p_order,t_size p_count) = 0;\r\n\t//! Queries whether specified item removal operation is allowed in the locked playlist.\r\n\t//! @param p_mask Specifies which items from locked playlist are being removed.\r\n\t//! @param p_force If set to true, the call is made only for notification purpose and items are getting removed regardless (after e.g. they have been physically removed).\r\n\t//! @returns True to allow the operation, false to block it. Note that return value is ignored if p_force is set to true.\r\n\tvirtual bool query_items_remove(const bit_array & p_mask,bool p_force) = 0;\r\n\t//! Queries whether specified item replacement operation is allowed in the locked playlist.\r\n\t//! @param p_index Index of the item being replaced.\r\n\t//! @param p_old Old value of the item being replaced.\r\n\t//! @param p_new New value of the item being replaced.\r\n\t//! @returns True to allow the operation, false to block it.\r\n\tvirtual bool query_item_replace(t_size p_index,const metadb_handle_ptr & p_old,const metadb_handle_ptr & p_new)=0;\r\n\t//! Queries whether renaming the locked playlist is allowed.\r\n\t//! @param p_new_name Requested new name of the playlist; a UTF-8 encoded string.\r\n\t//! @param p_new_name_len Length limit of the name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings.\r\n\t//! @returns True to allow the operation, false to block it.\r\n\tvirtual bool query_playlist_rename(const char * p_new_name,t_size p_new_name_len) = 0;\r\n\t//! Queries whether removal of the locked playlist is allowed. Note that the lock will be released when the playlist is removed.\r\n\t//! @returns True to allow the operation, false to block it.\r\n\tvirtual bool query_playlist_remove() = 0;\r\n\t//! Executes \"default action\" (doubleclick etc) for specified playlist item. When the playlist is not locked, default action starts playback of the item.\r\n\t//! @returns True if custom default action was executed, false to fall-through to default one for non-locked playlists (start playback).\r\n\tvirtual bool execute_default_action(t_size p_item) = 0;\r\n\t//! Notifies lock about changed index of the playlist, in result of user reordering playlists or removing other playlists.\r\n\tvirtual void on_playlist_index_change(t_size p_new_index) = 0;\r\n\t//! Notifies lock about the locked playlist getting removed.\r\n\tvirtual void on_playlist_remove() = 0;\r\n\t//! Retrieves human-readable name of playlist lock to display.\r\n\tvirtual void get_lock_name(pfc::string_base & p_out) = 0;\r\n\t//! Requests user interface of component controlling the playlist lock to be shown.\r\n\tvirtual void show_ui() = 0;\r\n\t//! Queries which actions the lock filters. The return value must not change while the lock is registered with playlist_manager. The return value is a combination of one or more filter_* constants.\r\n\tvirtual t_uint32 get_filter_mask() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(playlist_lock,service_base);\r\n};\r\n\r\nstruct t_playback_queue_item {\r\n\tmetadb_handle_ptr m_handle;\r\n\tt_size m_playlist,m_item;\r\n\r\n\tbool operator==(const t_playback_queue_item & p_item) const;\r\n\tbool operator!=(const t_playback_queue_item & p_item) const;\r\n};\r\n\r\n\r\n//! This service provides methods for all sorts of playlist interaction.\\n\r\n//! All playlist_manager methods are valid only from main app thread.\\n\r\n//! Usage: static_api_ptr_t<playlist_manager>.\r\nclass NOVTABLE playlist_manager : public service_base\r\n{\r\npublic:\r\n\r\n\t//! Callback interface for playlist enumeration methods.\r\n\tclass NOVTABLE enum_items_callback {\r\n\tpublic:\r\n\t\t//! @returns True to continue enumeration, false to abort.\r\n\t\tvirtual bool on_item(t_size p_index,const metadb_handle_ptr & p_location,bool b_selected) = 0;//return false to stop\r\n\t};\r\n\r\n\t//! Retrieves number of playlists.\r\n\tvirtual t_size get_playlist_count() = 0;\r\n\t//! Retrieves index of active playlist; infinite if no playlist is active.\r\n\tvirtual t_size get_active_playlist() = 0;\r\n\t//! Sets active playlist (infinite to set no active playlist).\r\n\tvirtual void set_active_playlist(t_size p_index) = 0;\r\n\t//! Retrieves playlist from which items to be played are taken from.\r\n\tvirtual t_size get_playing_playlist() = 0;\r\n\t//! Sets playlist from which items to be played are taken from.\r\n\tvirtual void set_playing_playlist(t_size p_index) = 0;\r\n\t//! Removes playlists according to specified mask. See also: bit_array.\r\n\tvirtual bool remove_playlists(const bit_array & p_mask) = 0;\r\n\t//! Creates a new playlist.\r\n\t//! @param p_name Name of playlist to create; a UTF-8 encoded string.\r\n\t//! @param p_name_length Length limit of playlist name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings.\r\n\t//! @param p_index Index at which to insert new playlist; set to infinite to put it at the end of playlist list.\r\n\t//! @returns Actual index of newly inserted playlist, infinite on failure (call from invalid context).\r\n\tvirtual t_size create_playlist(const char * p_name,t_size p_name_length,t_size p_index) = 0;\r\n\t//! Reorders playlist list according to specified permutation.\r\n\t//! @returns True on success, false on failure (call from invalid context).\r\n\tvirtual bool reorder(const t_size * p_order,t_size p_count) = 0;\r\n\t\r\n\t\r\n\t//! Retrieves number of items on specified playlist.\r\n\tvirtual t_size playlist_get_item_count(t_size p_playlist) = 0;\r\n\t//! Enumerates contents of specified playlist.\r\n\tvirtual void playlist_enum_items(t_size p_playlist,enum_items_callback & p_callback,const bit_array & p_mask) = 0;\r\n\t//! Retrieves index of focus item on specified playlist; returns infinite when no item has focus.\r\n\tvirtual t_size playlist_get_focus_item(t_size p_playlist) = 0;\r\n\t//! Retrieves name of specified playlist.\r\n\tvirtual bool playlist_get_name(t_size p_playlist,pfc::string_base & p_out) = 0;\r\n\t\r\n\t//! Reorders items in specified playlist according to specified permutation.\r\n\tvirtual bool playlist_reorder_items(t_size p_playlist,const t_size * p_order,t_size p_count) = 0;\r\n\t//! Selects/deselects items on specified playlist.\r\n\t//! @param p_playlist Index of playlist to alter.\r\n\t//! @param p_affected Mask of items to alter.\r\n\t//! @param p_status Mask of selected/deselected state to apply to items specified by p_affected.\r\n\tvirtual void playlist_set_selection(t_size p_playlist,const bit_array & p_affected,const bit_array & p_status) = 0;\r\n\t//! Removes specified items from specified playlist. Returns true on success or false on failure (playlist locked).\r\n\tvirtual bool playlist_remove_items(t_size p_playlist,const bit_array & mask)=0;\r\n\t//! Replaces specified item on specified playlist. Returns true on success or false on failure (playlist locked).\r\n\tvirtual bool playlist_replace_item(t_size p_playlist,t_size p_item,const metadb_handle_ptr & p_new_item) = 0;\r\n\t//! Sets index of focus item on specified playlist; use infinite to set no focus item.\r\n\tvirtual void playlist_set_focus_item(t_size p_playlist,t_size p_item) = 0;\r\n\t//! Inserts new items into specified playlist, at specified position.\r\n\tvirtual t_size playlist_insert_items(t_size p_playlist,t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection) = 0;\r\n\t//! Tells playlist renderers to make sure that specified item is visible.\r\n\tvirtual void playlist_ensure_visible(t_size p_playlist,t_size p_item) = 0;\r\n\t//! Renames specified playlist.\r\n\t//! @param p_name New name of playlist; a UTF-8 encoded string.\r\n\t//! @param p_name_length Length limit of playlist name string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings.\r\n\t//! @returns True on success, false on failure (playlist locked).\r\n\tvirtual bool playlist_rename(t_size p_index,const char * p_name,t_size p_name_length) = 0;\r\n\r\n\r\n\t//! Creates an undo restore point for specified playlist.\r\n\tvirtual void playlist_undo_backup(t_size p_playlist) = 0;\r\n\t//! Reverts specified playlist to last undo restore point and generates a redo restore point.\r\n\t//! @returns True on success, false on failure (playlist locked or no restore point available).\r\n\tvirtual bool playlist_undo_restore(t_size p_playlist) = 0;\r\n\t//! Reverts specified playlist to next redo restore point and generates an undo restore point.\r\n\t//! @returns True on success, false on failure (playlist locked or no restore point available).\r\n\tvirtual bool playlist_redo_restore(t_size p_playlist) = 0;\r\n\t//! Returns whether an undo restore point is available for specified playlist.\r\n\tvirtual bool playlist_is_undo_available(t_size p_playlist) = 0;\r\n\t//! Returns whether a redo restore point is available for specified playlist.\r\n\tvirtual bool playlist_is_redo_available(t_size p_playlist) = 0;\r\n\r\n\t//! Renders information about specified playlist item, using specified titleformatting script parameters.\r\n\t//! @param p_playlist Index of playlist containing item being processed.\r\n\t//! @param p_item Index of item being processed in the playlist containing it.\r\n\t//! @param p_hook Titleformatting script hook to use; see titleformat_hook documentation for more info. Set to NULL when hook functionality is not needed.\r\n\t//! @param p_out String object receiving results.\r\n\t//! @param p_script Compiled titleformatting script to use; see titleformat_object cocumentation for more info.\r\n\t//! @param p_filter Text filter to use; see titleformat_text_filter documentation for more info. Set to NULL when text filter functionality is not needed.\r\n\t//! @param p_playback_info_level Level of playback related information requested. See playback_control::t_display_level documentation for more info.\r\n\tvirtual void playlist_item_format_title(t_size p_playlist,t_size p_item,titleformat_hook * p_hook,pfc::string_base & p_out,const service_ptr_t<titleformat_object> & p_script,titleformat_text_filter * p_filter,playback_control::t_display_level p_playback_info_level)=0;\r\n\r\n\r\n\t//! Retrieves playlist position of currently playing item.\r\n\t//! @param p_playlist Receives index of playlist containing currently playing item on success.\r\n\t//! @param p_index Receives index of currently playing item in the playlist that contains it on success.\r\n\t//! @returns True on success, false on failure (not playing or currently played item has been removed from the playlist it was on when starting).\r\n\tvirtual bool get_playing_item_location(t_size * p_playlist,t_size * p_index) = 0;\r\n\t\r\n\t//! Sorts specified playlist - entire playlist or selection only - by specified title formatting pattern, or randomizes the order.\r\n\t//! @param p_playlist Index of playlist to alter.\r\n\t//! @param p_pattern Title formatting pattern to sort by (an UTF-8 encoded null-termindated string). Set to NULL to randomize the order of items.\r\n\t//! @param p_sel_only Set to false to sort/randomize whole playlist, or to true to sort/randomize only selection on the playlist.\r\n\t//! @returns True on success, false on failure (playlist locked etc).\r\n\tvirtual bool playlist_sort_by_format(t_size p_playlist,const char * p_pattern,bool p_sel_only) = 0;\r\n\r\n\t//! For internal use only; p_items must be sorted by metadb::path_compare; use file_operation_callback static methods instead of calling this directly.\r\n\tvirtual void on_files_deleted_sorted(const pfc::list_base_const_t<const char *> & p_items) = 0;\r\n\t//! For internal use only; p_from must be sorted by metadb::path_compare; use file_operation_callback static methods instead of calling this directly.\r\n\tvirtual void on_files_moved_sorted(const pfc::list_base_const_t<const char *> & p_from,const pfc::list_base_const_t<const char *> & p_to) = 0;\r\n\r\n\tvirtual bool playlist_lock_install(t_size p_playlist,const service_ptr_t<playlist_lock> & p_lock) = 0;//returns false when invalid playlist or already locked\r\n\tvirtual bool playlist_lock_uninstall(t_size p_playlist,const service_ptr_t<playlist_lock> & p_lock) = 0;\r\n\tvirtual bool playlist_lock_is_present(t_size p_playlist) = 0;\r\n\tvirtual bool playlist_lock_query_name(t_size p_playlist,pfc::string_base & p_out) = 0;\r\n\tvirtual bool playlist_lock_show_ui(t_size p_playlist) = 0;\r\n\tvirtual t_uint32 playlist_lock_get_filter_mask(t_size p_playlist) = 0;\r\n\r\n\r\n\t//! Retrieves number of available playback order modes.\r\n\tvirtual t_size playback_order_get_count() = 0;\r\n\t//! Retrieves name of specified playback order move.\r\n\t//! @param p_index Index of playback order mode to query, from 0 to playback_order_get_count() return value - 1.\r\n\t//! @returns Null-terminated UTF-8 encoded string containing name of the playback order mode. Returned pointer points to statically allocated string and can be safely stored without having to free it later.\r\n\tvirtual const char * playback_order_get_name(t_size p_index) = 0;\r\n\t//! Retrieves GUID of specified playback order mode. Used for managing playback modes without relying on names.\r\n\t//! @param p_index Index of playback order mode to query, from 0 to playback_order_get_count() return value - 1.\r\n\tvirtual GUID playback_order_get_guid(t_size p_index) = 0;\r\n\t//! Retrieves index of active playback order mode.\r\n\tvirtual t_size playback_order_get_active() = 0;\r\n\t//! Sets index of active playback order mode.\r\n\tvirtual void playback_order_set_active(t_size p_index) = 0;\r\n\t\r\n\tvirtual void queue_remove_mask(bit_array const & p_mask) = 0;\r\n\tvirtual void queue_add_item_playlist(t_size p_playlist,t_size p_item) = 0;\r\n\tvirtual void queue_add_item(metadb_handle_ptr p_item) = 0;\r\n\tvirtual t_size queue_get_count() = 0;\r\n\tvirtual void queue_get_contents(pfc::list_base_t<t_playback_queue_item> & p_out) = 0;\r\n\t//! Returns index (0-based) on success, infinite on failure (item not in queue).\r\n\tvirtual t_size queue_find_index(t_playback_queue_item const & p_item) = 0;\r\n\r\n\t//! Registers a playlist callback; registered object receives notifications about any modifications of any of loaded playlists.\r\n\t//! @param p_callback Callback interface to register.\r\n\t//! @param p_flags Flags indicating which callback methods are requested. See playlist_callback::flag_* constants for more info. The main purpose of flags parameter is working set optimization by not calling methods that do nothing.\r\n\tvirtual void register_callback(class playlist_callback * p_callback,unsigned p_flags) = 0;\r\n\t//! Registers a playlist callback; registered object receives notifications about any modifications of active playlist.\r\n\t//! @param p_callback Callback interface to register.\r\n\t//! @param p_flags Flags indicating which callback methods are requested. See playlist_callback_single::flag_* constants for more info. The main purpose of flags parameter is working set optimization by not calling methods that do nothing.\r\n\tvirtual void register_callback(class playlist_callback_single * p_callback,unsigned p_flags) = 0;\r\n\t//! Unregisters a playlist callback (playlist_callback version).\r\n\tvirtual void unregister_callback(class playlist_callback * p_callback) = 0;\r\n\t//! Unregisters a playlist callback (playlist_callback_single version).\r\n\tvirtual void unregister_callback(class playlist_callback_single * p_callback) = 0;\r\n\t//! Modifies flags indicating which calback methods are requested (playlist_callback version).\r\n\tvirtual void modify_callback(class playlist_callback * p_callback,unsigned p_flags) = 0;\r\n\t//! Modifies flags indicating which calback methods are requested (playlist_callback_single version).\r\n\tvirtual void modify_callback(class playlist_callback_single * p_callback,unsigned p_flags) = 0;\r\n\t\r\n\t//! Executes default doubleclick/enter action for specified item on specified playlist (starts playing the item unless overridden by a lock to do something else).\r\n\tvirtual bool playlist_execute_default_action(t_size p_playlist,t_size p_item) = 0;\r\n\r\n\t\r\n\t//! Helper; removes all items from the playback queue.\r\n\tvoid queue_flush() {queue_remove_mask(bit_array_true());}\r\n\t//! Helper; returns whether there are items in the playback queue.\r\n\tbool queue_is_active() {return queue_get_count() > 0;}\r\n\r\n\t//! Helper; highlights currently playing item; returns true on success or false on failure (not playing or currently played item has been removed from playlist since playback started).\r\n\tbool highlight_playing_item();\r\n\t//! Helper; removes single playlist of specified index.\r\n\tbool remove_playlist(t_size p_playlist);\r\n\t//! Helper; removes single playlist of specified index, and switches to another playlist when possible.\r\n\tbool remove_playlist_switch(t_size p_playlist);\r\n\r\n\t//! Helper; returns whether specified item on specified playlist is selected or not.\r\n\tbool playlist_is_item_selected(t_size p_playlist,t_size p_item);\r\n\t//! Helper; retrieves metadb_handle of specified playlist item. Returns true on success, false on failure (invalid parameters).\r\n\tbool playlist_get_item_handle(metadb_handle_ptr & p_out,t_size p_playlist,t_size p_item);\r\n\r\n\t//! Moves selected items up/down in the playlist by specified offset.\r\n\t//! @param p_playlist Index of playlist to alter.\r\n\t//! @param p_delta Offset to move items by. Set it to a negative valuye to move up, or to a positive value to move down.\r\n\t//! @returns True on success, false on failure (e.g. playlist locked).\r\n\tbool playlist_move_selection(t_size p_playlist,int p_delta);\r\n\t//! Retrieves selection map of specific playlist, using bit_array_var interface.\r\n\tvoid playlist_get_selection_mask(t_size p_playlist,bit_array_var & out);\r\n\tvoid playlist_get_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out,const bit_array & p_mask);\r\n\tvoid playlist_get_all_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out);\r\n\tvoid playlist_get_selected_items(t_size p_playlist,pfc::list_base_t<metadb_handle_ptr> & out);\r\n\t\r\n\t//! Clears contents of specified playlist (removes all items from it).\r\n\tvoid playlist_clear(t_size p_playlist);\r\n\tbool playlist_add_items(t_size playlist,const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection);\r\n\tvoid playlist_clear_selection(t_size p_playlist);\r\n\tvoid playlist_remove_selection(t_size p_playlist,bool p_crop = false);\r\n\t\r\n\t\r\n\t//retrieving status\r\n\tt_size activeplaylist_get_item_count();\r\n\tvoid activeplaylist_enum_items(enum_items_callback & p_callback,const bit_array & p_mask);\r\n\tt_size activeplaylist_get_focus_item();//focus may be infinite if no item is focused\r\n\tbool activeplaylist_get_name(pfc::string_base & p_out);\r\n\r\n\t//modifying playlist\r\n\tbool activeplaylist_reorder_items(const t_size * order,t_size count);\r\n\tvoid activeplaylist_set_selection(const bit_array & affected,const bit_array & status);\r\n\tbool activeplaylist_remove_items(const bit_array & mask);\r\n\tbool activeplaylist_replace_item(t_size p_item,const metadb_handle_ptr & p_new_item);\r\n\tvoid activeplaylist_set_focus_item(t_size p_item);\r\n\tt_size activeplaylist_insert_items(t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection);\r\n\tvoid activeplaylist_ensure_visible(t_size p_item);\r\n\tbool activeplaylist_rename(const char * p_name,t_size p_name_len);\r\n\r\n\tvoid activeplaylist_undo_backup();\r\n\tbool activeplaylist_undo_restore();\r\n\tbool activeplaylist_redo_restore();\r\n\r\n\tbool activeplaylist_is_item_selected(t_size p_item);\r\n\tbool activeplaylist_get_item_handle(metadb_handle_ptr & item,t_size p_item);\r\n\tvoid activeplaylist_move_selection(int p_delta);\r\n\tvoid activeplaylist_get_selection_mask(bit_array_var & out);\r\n\tvoid activeplaylist_get_items(pfc::list_base_t<metadb_handle_ptr> & out,const bit_array & p_mask);\r\n\tvoid activeplaylist_get_all_items(pfc::list_base_t<metadb_handle_ptr> & out);\r\n\tvoid activeplaylist_get_selected_items(pfc::list_base_t<metadb_handle_ptr> & out);\r\n\tvoid activeplaylist_clear();\r\n\r\n\tbool activeplaylist_add_items(const pfc::list_base_const_t<metadb_handle_ptr> & data,const bit_array & p_selection);\r\n\r\n\tbool playlist_insert_items_filter(t_size p_playlist,t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select);\r\n\tbool activeplaylist_insert_items_filter(t_size p_base,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select);\r\n\r\n\t//! DEPRECATED (0.9.3) - use playlist_incoming_item_filter_v2::process_locations_async whenever possible\r\n\tbool playlist_insert_locations(t_size p_playlist,t_size p_base,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd);\r\n\t//! DEPRECATED (0.9.3) - use playlist_incoming_item_filter_v2::process_locations_async whenever possible\r\n\tbool activeplaylist_insert_locations(t_size p_base,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd);\r\n\r\n\tbool playlist_add_items_filter(t_size p_playlist,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select);\r\n\tbool activeplaylist_add_items_filter(const pfc::list_base_const_t<metadb_handle_ptr> & p_data,bool p_select);\r\n\r\n\tbool playlist_add_locations(t_size p_playlist,const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd);\r\n\tbool activeplaylist_add_locations(const pfc::list_base_const_t<const char*> & p_urls,bool p_select,HWND p_parentwnd);\r\n\r\n\tvoid reset_playing_playlist();\r\n\r\n\tvoid activeplaylist_clear_selection();\r\n\tvoid activeplaylist_remove_selection(bool p_crop = false);\r\n\r\n\tvoid activeplaylist_item_format_title(t_size p_item,titleformat_hook * p_hook,pfc::string_base & out,const service_ptr_t<titleformat_object> & p_script,titleformat_text_filter * p_filter,play_control::t_display_level p_playback_info_level);\r\n\r\n\tvoid playlist_set_selection_single(t_size p_playlist,t_size p_item,bool p_state);\r\n\tvoid activeplaylist_set_selection_single(t_size p_item,bool p_state);\r\n\r\n\tt_size playlist_get_selection_count(t_size p_playlist,t_size p_max);\r\n\tt_size activeplaylist_get_selection_count(t_size p_max);\r\n\r\n\tbool playlist_get_focus_item_handle(metadb_handle_ptr & p_item,t_size p_playlist);\r\n\tbool activeplaylist_get_focus_item_handle(metadb_handle_ptr & item);\r\n\r\n\tt_size find_playlist(const char * p_name,t_size p_name_length);\r\n\tt_size find_or_create_playlist(const char * p_name,t_size p_name_length);\r\n\r\n\tt_size create_playlist_autoname(t_size p_index = infinite);\r\n\r\n\tbool activeplaylist_sort_by_format(const char * spec,bool p_sel_only);\r\n\r\n\tt_uint32 activeplaylist_lock_get_filter_mask();\r\n\tbool activeplaylist_is_undo_available();\r\n\tbool activeplaylist_is_redo_available();\r\n\r\n\tbool activeplaylist_execute_default_action(t_size p_item);\r\n\r\n\tvoid remove_items_from_all_playlists(const pfc::list_base_const_t<metadb_handle_ptr> & p_data);\r\n\r\n\tvoid active_playlist_fix();\r\n\r\n\tbool get_all_items(pfc::list_base_t<metadb_handle_ptr> & out);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_manager);\r\n};\r\n\r\nclass NOVTABLE playlist_callback\r\n{\r\npublic:\r\n\tvirtual void FB2KAPI on_items_added(t_size p_playlist,t_size p_start, const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const bit_array & p_selection)=0;//inside any of these methods, you can call playlist APIs to get exact info about what happened (but only methods that read playlist state, not those that modify it)\r\n\tvirtual void FB2KAPI on_items_reordered(t_size p_playlist,const t_size * p_order,t_size p_count)=0;//changes selection too; doesnt actually change set of items that are selected or item having focus, just changes their order\r\n\tvirtual void FB2KAPI on_items_removing(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;//called before actually removing them\r\n\tvirtual void FB2KAPI on_items_removed(t_size p_playlist,const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;\r\n\tvirtual void FB2KAPI on_items_selection_change(t_size p_playlist,const bit_array & p_affected,const bit_array & p_state) = 0;\r\n\tvirtual void FB2KAPI on_item_focus_change(t_size p_playlist,t_size p_from,t_size p_to)=0;//focus may be -1 when no item has focus; reminder: focus may also change on other callbacks\r\n\t\r\n\tvirtual void FB2KAPI on_items_modified(t_size p_playlist,const bit_array & p_mask)=0;\r\n\tvirtual void FB2KAPI on_items_modified_fromplayback(t_size p_playlist,const bit_array & p_mask,play_control::t_display_level p_level)=0;\r\n\r\n\tstruct t_on_items_replaced_entry\r\n\t{\r\n\t\tt_size m_index;\r\n\t\tmetadb_handle_ptr m_old,m_new;\r\n\t};\r\n\r\n\tvirtual void FB2KAPI on_items_replaced(t_size p_playlist,const bit_array & p_mask,const pfc::list_base_const_t<t_on_items_replaced_entry> & p_data)=0;\r\n\r\n\tvirtual void FB2KAPI on_item_ensure_visible(t_size p_playlist,t_size p_idx)=0;\r\n\r\n\tvirtual void FB2KAPI on_playlist_activate(t_size p_old,t_size p_new) = 0;\r\n\tvirtual void FB2KAPI on_playlist_created(t_size p_index,const char * p_name,t_size p_name_len) = 0;\r\n\tvirtual void FB2KAPI on_playlists_reorder(const t_size * p_order,t_size p_count) = 0;\r\n\tvirtual void FB2KAPI on_playlists_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) = 0;\r\n\tvirtual void FB2KAPI on_playlists_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count) = 0;\r\n\tvirtual void FB2KAPI on_playlist_renamed(t_size p_index,const char * p_new_name,t_size p_new_name_len) = 0;\r\n\r\n\tvirtual void FB2KAPI on_default_format_changed() = 0;\r\n\tvirtual void FB2KAPI on_playback_order_changed(t_size p_new_index) = 0;\r\n\tvirtual void FB2KAPI on_playlist_locked(t_size p_playlist,bool p_locked) = 0;\r\n\r\n\tenum {\r\n\t\tflag_on_items_added\t\t\t\t\t= 1 << 0,\r\n\t\tflag_on_items_reordered\t\t\t\t= 1 << 1,\r\n\t\tflag_on_items_removing\t\t\t\t= 1 << 2,\r\n\t\tflag_on_items_removed\t\t\t\t= 1 << 3,\r\n\t\tflag_on_items_selection_change\t\t= 1 << 4,\r\n\t\tflag_on_item_focus_change\t\t\t= 1 << 5,\r\n\t\tflag_on_items_modified\t\t\t\t= 1 << 6,\r\n\t\tflag_on_items_modified_fromplayback\t= 1 << 7,\r\n\t\tflag_on_items_replaced\t\t\t\t= 1 << 8,\r\n\t\tflag_on_item_ensure_visible\t\t\t= 1 << 9,\r\n\t\tflag_on_playlist_activate\t\t\t= 1 << 10,\r\n\t\tflag_on_playlist_created\t\t\t= 1 << 11,\r\n\t\tflag_on_playlists_reorder\t\t\t= 1 << 12,\r\n\t\tflag_on_playlists_removing\t\t\t= 1 << 13,\r\n\t\tflag_on_playlists_removed\t\t\t= 1 << 14,\r\n\t\tflag_on_playlist_renamed\t\t\t= 1 << 15,\r\n\t\tflag_on_default_format_changed\t\t= 1 << 16,\r\n\t\tflag_on_playback_order_changed\t\t= 1 << 17,\r\n\t\tflag_on_playlist_locked\t\t\t\t= 1 << 18,\r\n\r\n\t\tflag_all\t\t\t\t\t\t\t= ~0,\r\n\t};\r\nprotected:\r\n\tplaylist_callback() {}\r\n\t~playlist_callback() {}\r\n};\r\n\r\nclass NOVTABLE playlist_callback_static : public service_base, public playlist_callback \r\n{\r\npublic:\r\n\tvirtual unsigned get_flags() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_callback_static);\r\n};\r\n\r\nclass NOVTABLE playlist_callback_single\r\n{\r\npublic:\r\n\tvirtual void FB2KAPI on_items_added(t_size start, const pfc::list_base_const_t<metadb_handle_ptr> & p_data,const bit_array & p_selection)=0;//inside any of these methods, you can call playlist APIs to get exact info about what happened (but only methods that read playlist state, not those that modify it)\r\n\tvirtual void FB2KAPI on_items_reordered(const t_size * order,t_size count)=0;//changes selection too; doesnt actually change set of items that are selected or item having focus, just changes their order\r\n\tvirtual void FB2KAPI on_items_removing(const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;//called before actually removing them\r\n\tvirtual void FB2KAPI on_items_removed(const bit_array & p_mask,t_size p_old_count,t_size p_new_count)=0;\r\n\tvirtual void FB2KAPI on_items_selection_change(const bit_array & p_affected,const bit_array & p_state) = 0;\r\n\tvirtual void FB2KAPI on_item_focus_change(t_size p_from,t_size p_to)=0;//focus may be -1 when no item has focus; reminder: focus may also change on other callbacks\r\n\tvirtual void FB2KAPI on_items_modified(const bit_array & p_mask)=0;\r\n\tvirtual void FB2KAPI on_items_modified_fromplayback(const bit_array & p_mask,play_control::t_display_level p_level)=0;\r\n\tvirtual void FB2KAPI on_items_replaced(const bit_array & p_mask,const pfc::list_base_const_t<playlist_callback::t_on_items_replaced_entry> & p_data)=0;\r\n\tvirtual void FB2KAPI on_item_ensure_visible(t_size p_idx)=0;\r\n\r\n\tvirtual void FB2KAPI on_playlist_switch() = 0;\r\n\tvirtual void FB2KAPI on_playlist_renamed(const char * p_new_name,t_size p_new_name_len) = 0;\r\n\tvirtual void FB2KAPI on_playlist_locked(bool p_locked) = 0;\r\n\r\n\tvirtual void FB2KAPI on_default_format_changed() = 0;\r\n\tvirtual void FB2KAPI on_playback_order_changed(t_size p_new_index) = 0;\r\n\r\n\tenum {\r\n\t\tflag_on_items_added\t\t\t\t\t= 1 << 0,\r\n\t\tflag_on_items_reordered\t\t\t\t= 1 << 1,\r\n\t\tflag_on_items_removing\t\t\t\t= 1 << 2,\r\n\t\tflag_on_items_removed\t\t\t\t= 1 << 3,\r\n\t\tflag_on_items_selection_change\t\t= 1 << 4,\r\n\t\tflag_on_item_focus_change\t\t\t= 1 << 5,\r\n\t\tflag_on_items_modified\t\t\t\t= 1 << 6,\r\n\t\tflag_on_items_modified_fromplayback = 1 << 7,\r\n\t\tflag_on_items_replaced\t\t\t\t= 1 << 8,\r\n\t\tflag_on_item_ensure_visible\t\t\t= 1 << 9,\r\n\t\tflag_on_playlist_switch\t\t\t\t= 1 << 10,\r\n\t\tflag_on_playlist_renamed\t\t\t= 1 << 11,\r\n\t\tflag_on_playlist_locked\t\t\t\t= 1 << 12,\r\n\t\tflag_on_default_format_changed\t\t= 1 << 13,\r\n\t\tflag_on_playback_order_changed\t\t= 1 << 14,\r\n\t\tflag_all\t\t\t\t\t\t\t= ~0,\r\n\t};\r\nprotected:\r\n\tplaylist_callback_single() {}\r\n\t~playlist_callback_single() {}\r\n};\r\n\r\nclass playlist_callback_single_static : public service_base, public playlist_callback_single\r\n{\r\npublic:\r\n\tvirtual unsigned get_flags() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_callback_single_static);\r\n};\r\n\r\n\r\n//! Class used for async processing of IDataObject. Content of IDataObject can be dumped into dropped_files_data without any time-consuming operations - won't block calling app when used inside drag&drop handler - and actual time-consuming processing (listing directories and reading infos) can be done later.\\n\r\n//! In 0.9.3 and up, instead of going thru dropped_files_data, you can use playlist_incoming_item_filter_v2::process_dropped_files_async().\r\nclass NOVTABLE dropped_files_data {\r\npublic:\r\n\tvirtual void set_paths(pfc::string_list_const const & p_paths) = 0;\r\n\tvirtual void set_handles(const pfc::list_base_const_t<metadb_handle_ptr> & p_handles) = 0;\r\nprotected:\r\n\tdropped_files_data() {}\r\n\t~dropped_files_data() {}\r\n};\r\n\r\n\r\nclass NOVTABLE playlist_incoming_item_filter : public service_base\r\n{\r\npublic:\r\n\tvirtual bool filter_items(const pfc::list_base_const_t<metadb_handle_ptr> & in,pfc::list_base_t<metadb_handle_ptr> & out) = 0;//sort / remove duplicates\r\n\t\r\n\t//! Deprecated; use playlist_incoming_item_filter_v2::process_locations_async() when possible.\\n\r\n\t//! Converts one or more paths to a list of metadb_handles; displays a progress dialog.\\n\r\n\t//! Note that this function creates modal dialog and does not return until the operation has completed.\r\n\t//! @returns True on success, false on user abort.\r\n\tvirtual bool process_locations(const pfc::list_base_const_t<const char*> & p_urls,pfc::list_base_t<metadb_handle_ptr> & p_out,bool p_filter,const char * p_restrict_mask_override, const char * p_exclude_mask_override,HWND p_parentwnd) = 0;\r\n\t\r\n\t//! Deprecated; use playlist_incoming_item_filter_v2::process_dropped_files_async() when possible.\\n\r\n\t//! Converts an IDataObject to a list of metadb_handles.\r\n\t//! Using this function is strongly disrecommended as it implies blocking the drag&drop source app (as well as our app).\\n\r\n\t//! @returns True on success, false on user abort or unknown data format.\r\n\tvirtual bool process_dropped_files(interface IDataObject * pDataObject,pfc::list_base_t<metadb_handle_ptr> & p_out,bool p_filter,HWND p_parentwnd) = 0;\r\n\r\n\t//! Checks whether IDataObject contains one of known data formats that can be translated to a list of metadb_handles.\r\n\tvirtual bool process_dropped_files_check(interface IDataObject * pDataObject) = 0;\r\n\t\r\n\t//! Checks whether IDataObject contains our own private data format (drag&drop within the app etc).\r\n\tvirtual bool process_dropped_files_check_if_native(interface IDataObject * pDataObject) = 0;\r\n\t\r\n\t//! Creates an IDataObject from specified metadb_handle list.\r\n\tvirtual interface IDataObject * create_dataobject(const pfc::list_base_const_t<metadb_handle_ptr> & p_data) = 0;\r\n\r\n\t//! Checks whether IDataObject contains one of known data formats that can be translated to a list of metadb_handles.\\n\r\n\t//! This function also returns drop effects to use (see: IDropTarget::DragEnter(), IDropTarget::DragOver() ). In certain cases, drag effects are necessary for drag&drop to work at all (such as dragging links from IE).\\n\r\n\tvirtual bool process_dropped_files_check_ex(interface IDataObject * pDataObject, DWORD * p_effect) = 0;\r\n\r\n\t//! Dumps IDataObject content to specified dropped_files_data object, without any time-consuming processing.\\n\r\n\t//! Using this function instead of process_dropped_files() and processing dropped_files_data outside drop handler allows you to avoid blocking drop source app when processing large directories etc.\\n\r\n\t//! Note: since 0.9.3, it is recommended to use playlist_incoming_item_filter_v2::process_dropped_files_async() instead.\r\n\t//! @returns True on success, false when IDataObject does not contain any of known data formats.\r\n\tvirtual bool process_dropped_files_delayed(dropped_files_data & p_out,interface IDataObject * pDataObject) = 0;\r\n\r\n\t//helper\r\n\tbool process_location(const char * url,pfc::list_base_t<metadb_handle_ptr> & out,bool filter,const char * p_mask,const char * p_exclude,HWND p_parentwnd);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_incoming_item_filter);\r\n};\r\n\r\n//! For use with playlist_incoming_item_filter_v2::process_locations_async().\r\nclass NOVTABLE process_locations_notify : public service_base {\r\npublic:\r\n\tvirtual void on_completion(const pfc::list_base_const_t<metadb_handle_ptr> & p_items) = 0;\r\n\tvirtual void on_aborted() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(process_locations_notify,service_base);\r\n};\r\n\r\ntypedef service_ptr_t<process_locations_notify> process_locations_notify_ptr;\r\n\r\n//! New (0.9.3)\r\nclass NOVTABLE playlist_incoming_item_filter_v2 : public playlist_incoming_item_filter {\r\npublic:\r\n\tenum {\r\n\t\t//! Set this to disable presorting (according to user settings) and duplicate removal in output list. Should be unset in most cases.\r\n\t\top_flag_no_filter\t\t= 1 << 0,\r\n\t\t//! Set this flag to make the progress dialog not steal focus on creation.\r\n\t\top_flag_background\t\t= 1 << 1,\r\n\t\t//! Set this flag to delay the progress dialog becoming visible, so it does not appear at all during short operations. Also implies op_flag_background effect.\r\n\t\top_flag_delay_ui\t\t= 1 << 2,\r\n\t};\r\n\r\n\t//! Converts one or more paths to a list of metadb_handles. The function returns immediately; specified callback object receives results when the operation has completed.\r\n\t//! @param p_urls List of paths to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_restrict_mask_override Override of \"restrict incoming items to\" setting. Pass NULL to use the value from preferences.\r\n\t//! @param p_exclude_mask_override Override of \"exclude file types\" setting. Pass NULL to use value from preferences.\r\n\t//! @param p_parentwnd Parent window for spawned progress dialogs.\r\n\t//! @param p_notify Callback receiving notifications about success/abort of the operation as well as output item list.\r\n\tvirtual void process_locations_async(const pfc::list_base_const_t<const char*> & p_urls,t_uint32 p_op_flags,const char * p_restrict_mask_override, const char * p_exclude_mask_override,HWND p_parentwnd,process_locations_notify_ptr p_notify) = 0;\r\n\r\n\t//! Converts an IDataObject to a list of metadb_handles. The function returns immediately; specified callback object receives results when the operation has completed.\r\n\t//! @param p_dataobject IDataObject to process.\r\n\t//! @param p_op_flags Can be null, or one or more of op_flag_* enum values combined, altering behaviors of the operation.\r\n\t//! @param p_parentwnd Parent window for spawned progress dialogs.\r\n\t//! @param p_notify Callback receiving notifications about success/abort of the operation as well as output item list.\r\n\tvirtual void process_dropped_files_async(interface IDataObject * p_dataobject,t_uint32 p_op_flags,HWND p_parentwnd,process_locations_notify_ptr p_notify) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(playlist_incoming_item_filter_v2,playlist_incoming_item_filter);\r\n};\r\n\r\n//! Implementation of dropped_files_data.\r\nclass dropped_files_data_impl : public dropped_files_data {\r\npublic:\r\n\tdropped_files_data_impl() : m_is_paths(false) {}\r\n\tvoid set_paths(pfc::string_list_const const & p_paths) {\r\n\t\tm_is_paths = true;\r\n\t\tm_paths = p_paths;\r\n\t}\r\n\tvoid set_handles(const pfc::list_base_const_t<metadb_handle_ptr> & p_handles) {\r\n\t\tm_is_paths = false;\r\n\t\tm_handles = p_handles;\r\n\t}\r\n\r\n\tvoid to_handles_async(bool p_filter,HWND p_parentwnd,service_ptr_t<process_locations_notify> p_notify);\r\n\t//! @param p_op_flags Can be null, or one or more of playlist_incoming_item_filter_v2::op_flag_* enum values combined, altering behaviors of the operation.\r\n\tvoid to_handles_async_ex(t_uint32 p_op_flags,HWND p_parentwnd,service_ptr_t<process_locations_notify> p_notify);\r\n\tbool to_handles(pfc::list_base_t<metadb_handle_ptr> & p_out,bool p_filter,HWND p_parentwnd);\r\nprivate:\r\n\tpfc::string_list_impl m_paths;\r\n\tmetadb_handle_list m_handles;\r\n\tbool m_is_paths;\r\n};\r\n\r\n\r\nclass NOVTABLE playback_queue_callback : public service_base\r\n{\r\npublic:\r\n\tenum t_change_origin {\r\n\t\tchanged_user_added,\r\n\t\tchanged_user_removed,\r\n\t\tchanged_playback_advance,\r\n\t};\r\n\tvirtual void on_changed(t_change_origin p_origin) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playback_queue_callback);\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playlist_loader.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nstatic void process_path_internal(const char * p_path,const service_ptr_t<file> & p_reader,playlist_loader_callback & callback,playlist_loader_callback::t_entry_type type,const t_filestats & p_stats);\r\n\r\nnamespace {\r\n\tclass archive_callback_impl : public archive_callback\r\n\t{\r\n\tpublic:\r\n\t\tarchive_callback_impl(playlist_loader_callback & p_callback) : m_callback(p_callback) {}\r\n\t\tbool on_entry(archive * owner,const char * p_path,const t_filestats & p_stats,const service_ptr_t<file> & p_reader)\r\n\t\t{\r\n\t\t\tprocess_path_internal(p_path,p_reader,m_callback,playlist_loader_callback::entry_directory_enumerated,p_stats);\r\n\t\t\treturn !m_callback.is_aborting();\r\n\t\t}\r\n\t\tbool is_aborting() const {return m_callback.is_aborting();}\r\n\t\tabort_callback_event get_abort_event() const {return m_callback.get_abort_event();}\r\n\tprivate:\r\n\t\tplaylist_loader_callback & m_callback;\r\n\t};\r\n}\r\n\r\nvoid playlist_loader::g_load_playlist(const char * p_path,playlist_loader_callback & callback)\r\n{\r\n\tTRACK_CALL_TEXT(\"playlist_loader::g_load_playlist\");\r\n\tpfc::string8 filename;\r\n\t\r\n\tfilename = file_path_canonical(p_path);\r\n\r\n\tservice_enum_t<playlist_loader> e;\r\n\tservice_ptr_t<playlist_loader> l;\r\n\r\n\tpfc::string_extension extension(filename);\r\n\r\n\tservice_ptr_t<file> l_file;\r\n\r\n\t{\r\n\t\tbool /*have_content_type, */have_extension;\r\n//\t\tstring8 content_type;\r\n//\t\thave_content_type = r->get_content_type(content_type);\r\n\t\thave_extension = extension.length()>0;\r\n\r\n\t\tif (e.first(l)) do {\r\n\t\t\tif (\r\n//\t\t\thave_content_type && l->is_our_content_type(content_type) || \r\n\t\t\t\t(have_extension && !stricmp_utf8(l->get_extension(),extension)))\r\n\t\t\t{\r\n\t\t\t\tif (l_file.is_empty()) {\r\n\t\t\t\t\tfilesystem::g_open_read(l_file,filename,callback);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tTRACK_CODE(\"playlist_loader::open\",l->open(filename,l_file,callback));\r\n\t\t\t\treturn;//success\r\n\t\t\t}\r\n\t\t} while(e.next(l));\r\n\t}\r\n\r\n\tthrow exception_io_unsupported_format();\r\n}\r\n\r\nstatic void track_indexer__g_get_tracks_e(const char * p_path,const service_ptr_t<file> & p_reader,const t_filestats & p_stats,playlist_loader_callback::t_entry_type p_type,playlist_loader_callback & p_callback,bool & p_got_input)\r\n{\r\n\tif (p_reader.is_empty() && filesystem::g_is_remote_safe(p_path))\r\n\t{\r\n\t\tmetadb_handle_ptr handle;\r\n\t\tp_callback.handle_create(handle,make_playable_location(p_path,0));\r\n\t\tp_got_input = true;\r\n\t\tp_callback.on_entry(handle,p_type,p_stats,true);\r\n\t} else {\r\n\t\tservice_ptr_t<input_info_reader> instance;\r\n\t\tinput_entry::g_open_for_info_read(instance,p_reader,p_path,p_callback);\r\n\r\n\t\tt_filestats stats = instance->get_file_stats(p_callback);\r\n\r\n\t\tt_uint32 subsong,subsong_count = instance->get_subsong_count();\r\n\t\tfor(subsong=0;subsong<subsong_count;subsong++)\r\n\t\t{\r\n\t\t\tp_callback.check_e();\r\n\t\t\tmetadb_handle_ptr handle;\r\n\t\t\tt_uint32 index = instance->get_subsong(subsong);\r\n\t\t\tp_callback.handle_create(handle,make_playable_location(p_path,index));\r\n\r\n\t\t\tp_got_input = true;\r\n\t\t\tif (p_callback.want_info(handle,p_type,stats,true))\r\n\t\t\t{\r\n\t\t\t\tfile_info_impl info;\r\n\t\t\t\tinstance->get_info(index,info,p_callback);\r\n\t\t\t\tp_callback.on_entry_info(handle,p_type,stats,info,true);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tp_callback.on_entry(handle,p_type,stats,true);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nstatic void track_indexer__g_get_tracks_wrap(const char * p_path,const service_ptr_t<file> & p_reader,const t_filestats & p_stats,playlist_loader_callback::t_entry_type p_type,playlist_loader_callback & p_callback) {\r\n\tbool got_input = false;\r\n\tbool fail = false;\r\n\ttry {\r\n\t\ttrack_indexer__g_get_tracks_e(p_path,p_reader,p_stats,p_type,p_callback,got_input);\r\n\t} catch(exception_aborted) {\r\n\t\tthrow;\r\n\t} catch(exception_io_unsupported_format) {\r\n\t\tfail = true;\r\n\t} catch(std::exception const & e) {\r\n\t\tfail = true;\r\n\t\tconsole::formatter() << \"could not enumerate tracks (\" << e << \") on:\\n\" << file_path_display(p_path);\r\n\t}\r\n\tif (fail) {\r\n\t\tif (!got_input && !p_callback.is_aborting()) {\r\n\t\t\tif (p_type == playlist_loader_callback::entry_user_requested)\r\n\t\t\t{\r\n\t\t\t\tmetadb_handle_ptr handle;\r\n\t\t\t\tp_callback.handle_create(handle,make_playable_location(p_path,0));\r\n\t\t\t\tp_callback.on_entry(handle,p_type,p_stats,true);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nstatic void process_path_internal(const char * p_path,const service_ptr_t<file> & p_reader,playlist_loader_callback & p_callback,playlist_loader_callback::t_entry_type p_type,const t_filestats & p_stats)\r\n{\r\n\t//p_path must be canonical\r\n\r\n\tp_callback.check_e();\r\n\r\n\tp_callback.on_progress(p_path);\r\n\r\n\t\r\n\t{\r\n\t\tif (p_reader.is_empty()) {\r\n\t\t\tdirectory_callback_impl directory_results(true);\r\n\t\t\ttry {\r\n\t\t\t\tfilesystem::g_list_directory(p_path,directory_results,p_callback);\r\n\t\t\t\tfor(t_size n=0;n<directory_results.get_count();n++) {\r\n\t\t\t\t\tprocess_path_internal(directory_results.get_item(n),0,p_callback,playlist_loader_callback::entry_directory_enumerated,directory_results.get_item_stats(n));\r\n\t\t\t\t}\r\n\t\t\t\treturn;\r\n\t\t\t} catch(exception_aborted) {throw;}\r\n\t\t\tcatch(...) {\r\n\t\t\t\t//do nothing, fall thru\r\n\t\t\t\t//fixme - catch only filesystem exceptions?\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbool found = false;\r\n\r\n\r\n\t\t{\r\n\t\t\tarchive_callback_impl archive_results(p_callback);\r\n\t\t\tservice_enum_t<filesystem> e;\r\n\t\t\tservice_ptr_t<filesystem> f;\r\n\t\t\twhile(e.next(f)) {\r\n\t\t\t\tp_callback.check_e();\r\n\t\t\t\tservice_ptr_t<archive> arch;\r\n\t\t\t\tif (f->service_query_t(arch)) {\r\n\t\t\t\t\tif (p_reader.is_valid()) p_reader->reopen(p_callback);\r\n\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tTRACK_CODE(\"archive::archive_list\",arch->archive_list(p_path,p_reader,archive_results,true));\r\n\t\t\t\t\t\treturn;\r\n\t\t\t\t\t} catch(exception_aborted) {throw;} \r\n\t\t\t\t\tcatch(...) {}\r\n\t\t\t\t}\r\n\t\t\t} \r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\r\n\t{\r\n\t\tservice_ptr_t<link_resolver> ptr;\r\n\t\tif (link_resolver::g_find(ptr,p_path))\r\n\t\t{\r\n\t\t\tif (p_reader.is_valid()) p_reader->reopen(p_callback);\r\n\r\n\t\t\tpfc::string8 temp;\r\n\t\t\ttry {\r\n\t\t\t\tTRACK_CODE(\"link_resolver::resolve\",ptr->resolve(p_reader,p_path,temp,p_callback));\r\n\r\n\t\t\t\ttrack_indexer__g_get_tracks_wrap(temp,0,filestats_invalid,playlist_loader_callback::entry_from_playlist,p_callback);\r\n\t\t\t\treturn;//success\r\n\t\t\t} catch(exception_aborted) {throw;}\r\n\t\t\tcatch(...) {}\r\n\t\t}\r\n\t}\r\n\r\n\ttrack_indexer__g_get_tracks_wrap(p_path,p_reader,p_stats,p_type,p_callback);\r\n}\r\n\r\nvoid playlist_loader::g_process_path(const char * p_filename,playlist_loader_callback & callback,playlist_loader_callback::t_entry_type type)\r\n{\r\n\tTRACK_CALL_TEXT(\"playlist_loader::g_process_path\");\r\n\r\n\tfile_path_canonical filename(p_filename);\r\n\r\n\tprocess_path_internal(filename,0,callback,type,filestats_invalid);\r\n}\r\n\r\nvoid playlist_loader::g_save_playlist(const char * p_filename,const pfc::list_base_const_t<metadb_handle_ptr> & data,abort_callback & p_abort)\r\n{\r\n\tTRACK_CALL_TEXT(\"playlist_loader::g_save_playlist\");\r\n\tpfc::string8 filename;\r\n\tfilesystem::g_get_canonical_path(p_filename,filename);\r\n\ttry {\r\n\t\tservice_ptr_t<file> r;\r\n\t\tfilesystem::g_open(r,filename,filesystem::open_mode_write_new,p_abort);\r\n\r\n\t\tpfc::string_extension ext(filename);\r\n\t\t\r\n\t\tservice_enum_t<playlist_loader> e;\r\n\t\tservice_ptr_t<playlist_loader> l;\r\n\t\tif (e.first(l)) do {\r\n\t\t\tif (l->can_write() && !stricmp_utf8(ext,l->get_extension())) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTRACK_CODE(\"playlist_loader::write\",l->write(filename,r,data,p_abort));\r\n\t\t\t\t\treturn;\r\n\t\t\t\t} catch(exception_io_data) {}\r\n\t\t\t}\r\n\t\t} while(e.next(l));\r\n\t\tthrow exception_io_data();\r\n\t} catch(...) {\r\n\t\ttry {filesystem::g_remove(filename,p_abort);} catch(...) {}\r\n\t\tthrow;\r\n\t}\r\n}\r\n\r\n\r\nbool playlist_loader::g_process_path_ex(const char * filename,playlist_loader_callback & callback,playlist_loader_callback::t_entry_type type)\r\n{\r\n\ttry {\r\n\t\tg_load_playlist(filename,callback);\r\n\t\treturn true;\r\n\t} catch(exception_io_unsupported_format) {//not a playlist format\r\n\t\tg_process_path(filename,callback,type);\r\n\t\treturn false;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playlist_loader.h",
    "content": "#ifndef _PLAYLIST_LOADER_H_\r\n#define _PLAYLIST_LOADER_H_\r\n\r\n//! Callback interface receiving item locations from playlist loader. Also inherits abort_callback methods and can be passed to functions that require an abort_callback. \\n\r\n//! See playlist_loader_callback_impl for a basic implementation of playlist_loader_callback. Typically, you call one of standard services such as playlist_incoming_item_filter instead of implementing this interface and calling playlist_loader methods directly.\r\nclass NOVTABLE playlist_loader_callback : public abort_callback {\r\npublic:\r\n\t//! Enumeration type representing origin of item passed to playlist_loader_callback.\r\n\tenum t_entry_type {\r\n\t\t//! User-requested (such as directly dropped to window or picked in openfiledialog).\r\n\t\tentry_user_requested,\r\n\t\t//! From directory content enumeration.\r\n\t\tentry_directory_enumerated,\r\n\t\t//! Referenced by playlist file.\r\n\t\tentry_from_playlist,\r\n\t};\r\n\t//! Indicates specified path being processed; provided for updating GUI. Note that optimally GUI should not be updated every time this is called because that could introduce a bottleneck.\r\n\tvirtual void on_progress(const char * p_path) = 0;\r\n\t\r\n\t//! Receives an item from one of playlist_loader functions.\r\n\t//! @param p_item Item location, in form of metadb_handle pointer.\r\n\t//! @param p_type Origin of this item - see t_entry_type for more info.\r\n\t//! @param p_stats File stats of this item; set to filestats_invalid if not available.\r\n\t//! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false).\r\n\tvirtual void on_entry(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,bool p_fresh) = 0;\r\n\t//! Queries whether file_info for specified item is requested. In typical scenario, if want_info() returns false, on_entry() will be called with same parameters; otherwise caller will attempt to read info from the item and call on_entry_info() with same parameters and file_info read from the item.\r\n\t//! @param p_item Item location, in form of metadb_handle pointer.\r\n\t//! @param p_type Origin of this item - see t_entry_type for more info.\r\n\t//! @param p_stats File stats of this item; set to filestats_invalid if not available.\r\n\t//! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false).\r\n\tvirtual bool want_info(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,bool p_fresh) = 0;\r\n\t//! Receives an item from one of playlist_loader functions; including file_info data. Except for file_info to be typically used as hint for metadb backend, behavior of this method is same as on_entry().\r\n\t//! @param p_item Item location, in form of metadb_handle pointer.\r\n\t//! @param p_type Origin of this item - see t_entry_type for more info.\r\n\t//! @param p_stats File stats of this item; set to filestats_invalid if not available.\r\n\t//! @param p_info Information about the item, read from the file directly (if p_fresh is set to true) or from e.g. playlist file (if p_fresh is set to false).\r\n\t//! @param p_fresh Fresh flag; indicates whether stats are directly from filesystem (true) or as stored earlier in a playlist file (false).\r\n\tvirtual void on_entry_info(const metadb_handle_ptr & p_item,t_entry_type p_type,const t_filestats & p_stats,const file_info & p_info,bool p_fresh) = 0;\r\n\r\n\t//! Same as metadb::handle_create(); provided here to avoid repeated metadb instantiation bottleneck since calling code will need this function often.\r\n\tvirtual void handle_create(metadb_handle_ptr & p_out,const playable_location & p_location) = 0;\r\n\r\nprotected:\r\n\tplaylist_loader_callback() {}\r\n\t~playlist_loader_callback() {}\r\n};\r\n\r\n//! Basic implementation of playlist_loader_callback.\r\nclass playlist_loader_callback_impl : public playlist_loader_callback {\r\npublic:\r\n\r\n\tplaylist_loader_callback_impl(abort_callback & p_abort) : m_abort(p_abort) {}\r\n\r\n\tbool is_aborting() const {return m_abort.is_aborting();}\r\n\tabort_callback_event get_abort_event() const {return m_abort.get_abort_event();}\r\n\r\n\tconst metadb_handle_ptr & get_item(t_size idx) const {return m_data[idx];}\r\n\tconst metadb_handle_ptr & operator[](t_size idx) const {return m_data[idx];}\r\n\tt_size get_count() const {return m_data.get_count();}\r\n\t\r\n\tconst metadb_handle_list & get_data() const {return m_data;}\r\n\r\n\tvoid on_progress(const char * path) {}\r\n\r\n\tvoid on_entry(const metadb_handle_ptr & ptr,t_entry_type type,const t_filestats & p_stats,bool p_fresh) {m_data.add_item(ptr);}\r\n\tbool want_info(const metadb_handle_ptr & ptr,t_entry_type type,const t_filestats & p_stats,bool p_fresh) {return false;}\r\n\tvoid on_entry_info(const metadb_handle_ptr & ptr,t_entry_type type,const t_filestats & p_stats,const file_info & p_info,bool p_fresh) {m_data.add_item(ptr);}\r\n\r\n\tvoid handle_create(metadb_handle_ptr & p_out,const playable_location & p_location) {m_api->handle_create(p_out,p_location);}\r\n\r\nprivate:\r\n\tmetadb_handle_list m_data;\r\n\tabort_callback & m_abort;\r\n\tstatic_api_ptr_t<metadb> m_api;\r\n};\r\n\r\n//! Service handling playlist file operations. There are multiple implementations handling different playlist formats; you can add new implementations to allow new custom playlist file formats to be read or written.\\n\r\n//! Also provides static helper functions for turning a filesystem path into a list of playable item locations. \\n\r\n//! Note that you should typically call playlist_incoming_item_filter methods instead of calling playlist_loader methods directly to get a list of playable items from a specified path; this way you get a core-implemented threading and abortable dialog displaying progress.\\n\r\n//! To register your own implementation, use playlist_loader_factory_t template.\\n\r\n//! To call existing implementations, use static helper methods of playlist_loader class.\r\nclass NOVTABLE playlist_loader : public service_base {\r\npublic:\r\n\t//! Parses specified playlist file into list of playable locations. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, exception_io_unsupported_format is thrown.\r\n\t//! @param p_path Path of playlist file to parse. Used for relative path handling purposes (p_file parameter is used for actual file access).\r\n\t//! @param p_file File interface to use for reading. Read/write pointer must be set to beginning by caller before calling.\r\n\t//! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation.\r\n\tvirtual void open(const char * p_path, const service_ptr_t<file> & p_file,playlist_loader_callback & p_callback) = 0;\r\n\t//! Writes a playlist file containing specific item list to specified file. Will fail (pfc::exception_not_implemented) if specified playlist_loader is read-only (can_write() returns false).\r\n\t//! @param p_path Path of playlist file to write. Used for relative path handling purposes (p_file parameter is used for actual file access).\r\n\t//! @param p_file File interface to use for writing. Caller should ensure that the file is empty (0 bytes long) before calling.\r\n\t//! @param p_data List of items to save to playlist file.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation. Note that aborting a save playlist operation will most likely leave user with corrupted/incomplete file.\r\n\tvirtual void write(const char * p_path, const service_ptr_t<file> & p_file,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,abort_callback & p_abort) = 0;\r\n\t//! Returns extension of file format handled by this playlist_loader implementation (a UTF-8 encoded null-terminated string).\r\n\tvirtual const char * get_extension() = 0;\r\n\t//! Returns whether this playlist_loader implementation supports writing. If can_write() returns false, all write() calls will fail.\r\n\tvirtual bool can_write() = 0;\r\n\t//! Returns whether specified content type is one of playlist types supported by this playlist_loaded implementation or not.\r\n\t//! @param p_content_type Content type to query, a UTF-8 encoded null-terminated string.\r\n\tvirtual bool is_our_content_type(const char* p_content_type) = 0;\r\n\t//! Returns whether playlist format extension supported by this implementation should be listed on file types associations page.\r\n\tvirtual bool is_associatable() = 0;\r\n\r\n\t//! Attempts to load a playlist file from specified filesystem path. Throws exception_io or derivatives on failure, exception_aborted on abort. If specified file is not a recognized playlist file, exception_io_unsupported_format is thrown.\r\n\t//! @param p_path Filesystem path to load playlist from, a UTF-8 encoded null-terminated string.\r\n\t//! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation.\r\n\tstatic void g_load_playlist(const char * p_path,playlist_loader_callback & p_callback);\r\n\r\n\t//! Saves specified list of locations into a playlist file. Throws exception_io or derivatives on failure, exception_aborted on abort.\r\n\t//! @param p_path Filesystem path to save playlist to, a UTF-8 encoded null-terminated string.\r\n\t//! @param p_data List of items to save to playlist file.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation. Note that aborting a save playlist operation will most likely leave user with corrupted/incomplete file.\r\n\tstatic void g_save_playlist(const char * p_path,const pfc::list_base_const_t<metadb_handle_ptr> & p_data,abort_callback & p_abort);\r\n\r\n\t//! Processes specified path to generate list of playable items. Includes recursive directory/archive enumeration. \\n\r\n\t//! Does not touch playlist files encountered - use g_process_path_ex() if specified path is possibly a playlist file; playlist files found inside directories or archives are ignored regardless.\\n\r\n\t//! Warning: caller must handle exceptions which will occur in case of I/O failure.\r\n\t//! @param p_path Filesystem path to process; a UTF-8 encoded null-terminated string.\r\n\t//! @param p_callback Callback object receiving enumerated playable item locations as well as signaling user aborting the operation.\r\n\t//! @param p_type Origin of p_path string. Reserved for internal use in recursive calls, should be left at default value; it controls various internal behaviors.\r\n\tstatic void g_process_path(const char * p_path,playlist_loader_callback & p_callback,playlist_loader_callback::t_entry_type p_type = playlist_loader_callback::entry_user_requested);\r\n\t\r\n\t//! Calls attempts to process specified path as a playlist; if that fails (i.e. not a playlist), calls g_process_path with same parameters. See g_process_path for parameter descriptions. \\n\r\n\t//! Warning: caller must handle exceptions which will occur in case of I/O failure or playlist parsing failure.\r\n\t//! @returns True if specified path was processed as a playlist file, false otherwise (relevant in some scenarios where output is sorted after loading, playlist file contents should not be sorted).\r\n\tstatic bool g_process_path_ex(const char * p_path,playlist_loader_callback & p_callback,playlist_loader_callback::t_entry_type p_type = playlist_loader_callback::entry_user_requested);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(playlist_loader);\r\n};\r\n\r\ntemplate<typename t_myclass>\r\nclass playlist_loader_factory_t : public service_factory_single_t<t_myclass> {};\r\n\r\n\r\n#endif //_PLAYLIST_LOADER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/playlist_lock.cpp",
    "content": "#include \"foobar2000.h\"\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/popup_message.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid popup_message::g_show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon)\r\n{\r\n\tstatic_api_ptr_t<popup_message>()->show_ex(p_msg,p_msg_length,p_title,p_title_length,p_icon);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/popup_message.h",
    "content": "#ifndef _POPUP_MESSAGE_H_\r\n#define _POPUP_MESSAGE_H_\r\n\r\n\r\n//! This interface allows you to show generic nonmodal noninteractive dialog with a text message. This should be used instead of MessageBox where possible.\\n\r\n//! Usage: use popup_message::g_show / popup_message::g_show_ex static helpers, or static_api_ptr_t<popup_message>.\\n\r\n//! Note that all strings are UTF-8.\r\n\r\nclass NOVTABLE popup_message : public service_base {\r\npublic:\r\n\tenum t_icon {icon_information, icon_error, icon_query};\r\n\t//! Activates the popup dialog; returns immediately (the dialog remains visible).\r\n\t//! @param p_msg Message to show (UTF-8 encoded string).\r\n\t//! @param p_msg_length Length limit of message string to show, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings.\r\n\t//! @param p_title Title of dialog to show (UTF-8 encoded string).\r\n\t//! @param p_title_length Length limit of the title string, in bytes (actual string may be shorter if null terminator is encountered before). Set this to infinite to use plain null-terminated strings.\r\n\t//! @param p_icon Icon of the dialog - can be set to icon_information, icon_error or icon_query.\r\n\tvirtual void show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon = icon_information) = 0;\r\n\r\n\t//! Activates the popup dialog; returns immediately (the dialog remains visible); helper function built around show_ex(), takes null terminated strings with no length limit parameters.\r\n\t//! @param p_msg Message to show (UTF-8 encoded string).\r\n\t//! @param p_title Title of dialog to show (UTF-8 encoded string).\r\n\t//! @param p_icon Icon of the dialog - can be set to icon_information, icon_error or icon_query.\r\n\tinline void show(const char * p_msg,const char * p_title,t_icon p_icon = icon_information) {show_ex(p_msg,infinite,p_title,infinite,p_icon);}\r\n\r\n\t//! Static helper function instantiating the service and activating the message dialog. See show_ex() for description of parameters.\r\n\tstatic void g_show_ex(const char * p_msg,unsigned p_msg_length,const char * p_title,unsigned p_title_length,t_icon p_icon = icon_information);\r\n\t//! Static helper function instantiating the service and activating the message dialog. See show() for description of parameters.\r\n\tstatic inline void g_show(const char * p_msg,const char * p_title,t_icon p_icon = icon_information) {g_show_ex(p_msg,infinite,p_title,infinite,p_icon);}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(popup_message);\r\n};\r\n\r\n#endif //_POPUP_MESSAGE_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/preferences_page.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool preferences_page::get_help_url(pfc::string_base & p_out)\r\n{\r\n\tp_out = \"http://help.foobar2000.org/\";\r\n\tp_out += core_version_info::g_get_version_string();\r\n\tp_out += \"/preferences/\";\r\n\tp_out += (const char*) pfc::print_guid(get_guid());\r\n\tp_out += \"/\";\r\n\tp_out += get_name();\r\n\treturn true;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/preferences_page.h",
    "content": "#ifndef _FOOBAR2000_SDK_PREFERENCES_PAGE_H_\r\n#define _FOOBAR2000_SDK_PREFERENCES_PAGE_H_\r\n\r\n//! Implementing this service will generate a page in preferences dialog. Use preferences_page_factory_t template to register.\r\nclass NOVTABLE preferences_page : public service_base {\r\npublic:\r\n\t//! Creates preferences page dialog window. It is safe to assume that two dialog instances will never coexist. Caller is responsible for embedding it into preferences dialog itself.\r\n\tvirtual HWND create(HWND p_parent) = 0;\r\n\t//! Retrieves name of the prefernces page to be displayed in preferences tree (static string).\r\n\tvirtual const char * get_name() = 0;\r\n\t//! Retrieves GUID of the page.\r\n\tvirtual GUID get_guid() = 0;\r\n\t//! Retrieves GUID of parent page/branch of this page. See preferences_page::guid_* constants for list of standard parent GUIDs. Can also be a GUID of another page or a branch (see: preferences_branch).\r\n\tvirtual GUID get_parent_guid() = 0;\r\n\t//! Queries whether this page supports \"reset page\" feature.\r\n\tvirtual bool reset_query() = 0;\r\n\t//! Activates \"reset page\" feature. It is safe to assume that the preferences page dialog does not exist at the point this is called (caller destroys it before calling reset and creates it again afterwards).\r\n\tvirtual void reset() = 0;\r\n\t//! Retrieves help URL. Without overriding it, it will redirect to foobar2000 wiki.\r\n\tvirtual bool get_help_url(pfc::string_base & p_out);\r\n\t\r\n\tstatic const GUID guid_root, guid_hidden, guid_tools,guid_core,guid_display,guid_playback,guid_visualisations,guid_input,guid_tag_writing,guid_media_library;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(preferences_page);\r\n};\r\n\r\nclass NOVTABLE preferences_page_v2 : public preferences_page {\r\npublic:\r\n\t//! Allows custom sorting order of preferences pages. Return lower value for higher priority (lower resulting index in the list). When sorting priority of two items matches, alphabetic sorting is used. Return 0 to use default alphabetic sorting without overriding priority.\r\n\tvirtual double get_sort_priority() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(preferences_page_v2,preferences_page);\r\n};\r\n\r\ntemplate<class T>\r\nclass preferences_page_factory_t : public service_factory_single_t<T> {};\r\n\r\n//! Creates a preferences branch - an empty page that only serves as a parent for other pages and is hidden when no child pages exist. Instead of implementing this, simply use preferences_branch_factory class to declare a preferences branch with specified parameters.\r\nclass NOVTABLE preferences_branch : public service_base {\r\npublic:\r\n\t//! Retrieves name of the preferences branch.\r\n\tvirtual const char * get_name() = 0;\r\n\t//! Retrieves GUID of the preferences branch. Use this GUID as parent GUID for pages/branches nested in this branch.\r\n\tvirtual GUID get_guid() = 0;\r\n\t//! Retrieves GUID of parent page/branch of this branch. See preferences_page::guid_* constants for list of standard parent GUIDs. Can also be a GUID of another branch or a page.\r\n\tvirtual GUID get_parent_guid() = 0;\r\n\t\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(preferences_branch);\r\n};\r\n\r\nclass preferences_branch_v2 : public preferences_branch {\r\npublic:\r\n\t//! Allows custom sorting order of preferences pages. Return lower value for higher priority (lower resulting index in the list). When sorting priority of two items matches, alphabetic sorting is used. Return 0 to use default alphabetic sorting without overriding priority.\r\n\tvirtual double get_sort_priority() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(preferences_branch_v2,preferences_branch);\r\n};\r\n\r\nclass preferences_branch_impl : public preferences_branch_v2 {\r\npublic:\r\n\tpreferences_branch_impl(const GUID & p_guid,const GUID & p_parent,const char * p_name,double p_sort_priority = 0) : m_guid(p_guid), m_parent(p_parent), m_name(p_name), m_sort_priority(p_sort_priority) {}\r\n\tconst char * get_name() {return m_name;}\r\n\tGUID get_guid() {return m_guid;}\r\n\tGUID get_parent_guid() {return m_parent;}\r\n\tdouble get_sort_priority() {return m_sort_priority;}\r\nprivate:\r\n\tconst GUID m_guid,m_parent;\r\n\tconst pfc::string8 m_name;\r\n\tconst double m_sort_priority;\r\n};\r\n\r\ntypedef service_factory_single_t<preferences_branch_impl> __preferences_branch_factory;\r\n\r\n//! Instantiating this class declares a preferences branch with specified parameters.\\n\r\n//! Usage: static preferences_branch_factory g_mybranch(mybranchguid,parentbranchguid,\"name of my preferences branch goes here\");\r\nclass preferences_branch_factory : public __preferences_branch_factory {\r\npublic:\r\n\tpreferences_branch_factory(const GUID & p_guid,const GUID & p_parent,const char * p_name,double p_sort_priority = 0) : __preferences_branch_factory(p_guid,p_parent,p_name,p_sort_priority) {}\r\n};\r\n\r\n#endif //_FOOBAR2000_SDK_PREFERENCES_PAGE_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/replaygain.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid t_replaygain_config::reset()\r\n{\r\n\tm_source_mode = source_mode_none;\r\n\tm_processing_mode = processing_mode_none;\r\n\tm_preamp_without_rg = 0;\r\n\tm_preamp_with_rg = 0;\r\n}\r\n\r\naudio_sample t_replaygain_config::query_scale(const file_info & p_info) const\r\n{\r\n\tconst audio_sample peak_margin = 1.0;//used to be 0.999 but it must not trigger on lossless\r\n\r\n\taudio_sample peak = peak_margin;\r\n\taudio_sample gain = 0;\r\n\r\n\tbool have_rg_gain = false, have_rg_peak = false;\r\n\r\n\tif (m_source_mode == source_mode_track || m_source_mode == source_mode_album)\r\n\t{\r\n\t\treplaygain_info info = p_info.get_replaygain();\r\n\t\tfloat gain_select = replaygain_info::gain_invalid, peak_select = replaygain_info::peak_invalid;\r\n\t\tif (m_source_mode == source_mode_track)\r\n\t\t{\r\n\t\t\tif (info.is_track_gain_present()) {gain = info.m_track_gain; have_rg_gain = true; }\r\n\t\t\telse if (info.is_album_gain_present()) {gain = info.m_album_gain; have_rg_gain = true; }\r\n\t\t\tif (info.is_track_peak_present()) {peak = info.m_track_peak; have_rg_peak = true; }\r\n\t\t\telse if (info.is_album_peak_present()) {peak = info.m_album_peak; have_rg_peak = true; }\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (info.is_album_gain_present()) {gain = info.m_album_gain; have_rg_gain = true; }\r\n\t\t\telse if (info.is_track_gain_present()) {gain = info.m_track_gain; have_rg_gain = true; }\r\n\t\t\tif (info.is_album_peak_present()) {peak = info.m_album_peak; have_rg_peak = true; }\r\n\t\t\telse if (info.is_track_peak_present()) {peak = info.m_track_peak; have_rg_peak = true; }\r\n\t\t}\r\n\t}\r\n\r\n\tgain += have_rg_gain ? m_preamp_with_rg : m_preamp_without_rg;\r\n\r\n\taudio_sample scale = 1.0;\r\n\r\n\tif (m_processing_mode == processing_mode_gain || m_processing_mode == processing_mode_gain_and_peak)\r\n\t{\r\n\t\tscale *= audio_math::gain_to_scale(gain);\r\n\t}\r\n\r\n\tif (m_processing_mode == processing_mode_peak || m_processing_mode == processing_mode_gain_and_peak)\r\n\t{\r\n\t\tif (scale * peak > peak_margin)\r\n\t\t\tscale = (audio_sample)(peak_margin / peak);\r\n\t}\r\n\r\n\treturn scale;\r\n}\r\n\r\naudio_sample t_replaygain_config::query_scale(const metadb_handle_ptr & p_object) const\r\n{\r\n\taudio_sample rv = 1.0;\r\n\tp_object->metadb_lock();\r\n\tconst file_info * info;\r\n\tif (p_object->get_info_async_locked(info))\r\n\t\trv = query_scale(*info);\r\n\tp_object->metadb_unlock();\r\n\treturn rv;\r\n}\r\n\r\naudio_sample replaygain_manager::core_settings_query_scale(const file_info & p_info)\r\n{\r\n\tt_replaygain_config temp;\r\n\tget_core_settings(temp);\r\n\treturn temp.query_scale(p_info);\r\n}\r\n\r\naudio_sample replaygain_manager::core_settings_query_scale(const metadb_handle_ptr & info)\r\n{\r\n\tt_replaygain_config temp;\r\n\tget_core_settings(temp);\r\n\treturn temp.query_scale(info);\r\n}\r\n\r\n//enum t_source_mode {source_mode_none,source_mode_track,source_mode_album};\r\n//enum t_processing_mode {processing_mode_none,processing_mode_gain,processing_mode_gain_and_peak,processing_mode_peak};\r\nnamespace {\r\nclass format_dbdelta\r\n{\r\npublic:\r\n\tformat_dbdelta(double p_val);\r\n\toperator const char*() const {return m_buffer;}\r\nprivate:\r\n\tpfc::string_fixed_t<128> m_buffer;\r\n};\r\nstatic const char * querysign(int val) {\r\n\treturn val<0 ? \"-\" : val>0 ? \"+\" : \"\\xc2\\xb1\";\r\n}\r\n\r\nformat_dbdelta::format_dbdelta(double p_val) {\r\n\tint val = (int)(p_val * 10);\r\n\tm_buffer << querysign(val) << (abs(val)/10) << \".\" << (abs(val)%10) << \"dB\";\r\n}\r\n}\r\nvoid t_replaygain_config::format_name(pfc::string_base & p_out) const\r\n{\r\n\tswitch(m_processing_mode)\r\n\t{\r\n\tcase processing_mode_none:\r\n\t\tp_out = \"None.\";\r\n\t\tbreak;\r\n\tcase processing_mode_gain:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\tif (m_preamp_without_rg == 0) p_out = \"None.\"; \r\n\t\t\telse p_out = pfc::string_formatter() << \"Preamp : \" << format_dbdelta(m_preamp_without_rg); \r\n\t\t\tbreak;\r\n\t\tcase source_mode_track:\r\n\t\t\t{\r\n\t\t\t\tpfc::string_formatter fmt;\r\n\t\t\t\tfmt << \"Apply track gain\";\r\n\t\t\t\tif (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << \", with preamp\";\r\n\t\t\t\tfmt << \".\";\r\n\t\t\t\tp_out = fmt;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase source_mode_album:\r\n\t\t\t{\r\n\t\t\t\tpfc::string_formatter fmt;\r\n\t\t\t\tfmt << \"Apply album gain\";\r\n\t\t\t\tif (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << \", with preamp\";\r\n\t\t\t\tfmt << \".\";\r\n\t\t\t\tp_out = fmt;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t};\r\n\t\tbreak;\r\n\tcase processing_mode_gain_and_peak:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\tif (m_preamp_without_rg >= 0) p_out = \"None.\";\r\n\t\t\telse p_out = pfc::string_formatter() << \"Preamp : \" << format_dbdelta(m_preamp_without_rg);\r\n\t\t\tbreak;\r\n\t\tcase source_mode_track:\r\n\t\t\t{\r\n\t\t\t\tpfc::string_formatter fmt;\r\n\t\t\t\tfmt << \"Apply track gain\";\r\n\t\t\t\tif (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << \", with preamp\";\r\n\t\t\t\tfmt << \", prevent clipping according to track peak.\";\r\n\t\t\t\tp_out = fmt;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase source_mode_album:\r\n\t\t\t{\r\n\t\t\t\tpfc::string_formatter fmt;\r\n\t\t\t\tfmt << \"Apply album gain\";\r\n\t\t\t\tif (m_preamp_without_rg != 0 || m_preamp_with_rg != 0) fmt << \", with preamp\";\r\n\t\t\t\tfmt << \", prevent clipping according to album peak.\";\r\n\t\t\t\tp_out = fmt;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t};\r\n\t\tbreak;\r\n\tcase processing_mode_peak:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\tp_out = \"None.\";\r\n\t\t\tbreak;\r\n\t\tcase source_mode_track:\r\n\t\t\tp_out = \"Prevent clipping according to track peak.\";\r\n\t\t\tbreak;\r\n\t\tcase source_mode_album:\r\n\t\t\tp_out = \"Prevent clipping according to album peak.\";\r\n\t\t\tbreak;\r\n\t\t};\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\nbool t_replaygain_config::is_active() const\r\n{\r\n\tswitch(m_processing_mode)\r\n\t{\r\n\tcase processing_mode_none:\r\n\t\treturn false;\r\n\tcase processing_mode_gain:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\treturn m_preamp_without_rg != 0;\r\n\t\tcase source_mode_track:\r\n\t\t\treturn true;\r\n\t\tcase source_mode_album:\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\treturn false;\r\n\tcase processing_mode_gain_and_peak:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\treturn m_preamp_without_rg < 0;\r\n\t\tcase source_mode_track:\r\n\t\t\treturn true;\r\n\t\tcase source_mode_album:\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\treturn false;\r\n\tcase processing_mode_peak:\r\n\t\tswitch(m_source_mode)\r\n\t\t{\r\n\t\tcase source_mode_none:\r\n\t\t\treturn false;\r\n\t\tcase source_mode_track:\r\n\t\t\treturn true;\r\n\t\tcase source_mode_album:\r\n\t\t\treturn true;\r\n\t\t};\r\n\t\treturn false;\r\n\tdefault:\r\n\t\treturn false;\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/replaygain.h",
    "content": "#ifndef _FOOBAR2000_SDK_REPLAYGAIN_H_\r\n#define _FOOBAR2000_SDK_REPLAYGAIN_H_\r\n\r\n//! Structure storing ReplayGain configuration: album/track source data modes, gain/peak processing modes and preamp values.\r\nstruct t_replaygain_config\r\n{\r\n\tenum t_source_mode {source_mode_none,source_mode_track,source_mode_album};\r\n\tenum t_processing_mode {processing_mode_none,processing_mode_gain,processing_mode_gain_and_peak,processing_mode_peak};\r\n\r\n\tt_replaygain_config() {reset();}\r\n\tt_replaygain_config(const t_replaygain_config & p_source) {*this = p_source;}\r\n\tt_replaygain_config(t_source_mode p_source_mode,t_processing_mode p_processing_mode,float p_preamp_without_rg, float p_preamp_with_rg)\r\n\t\t: m_source_mode(p_source_mode), m_processing_mode(p_processing_mode), m_preamp_without_rg(p_preamp_without_rg), m_preamp_with_rg(p_preamp_with_rg) {}\r\n\r\n\t\r\n\tt_source_mode m_source_mode;\r\n\tt_processing_mode m_processing_mode;\r\n\tfloat m_preamp_without_rg, m_preamp_with_rg;//preamp values in dB\r\n\r\n\tvoid reset();\r\n\taudio_sample query_scale(const file_info & info) const;\r\n\taudio_sample query_scale(const metadb_handle_ptr & info) const;\r\n\r\n\tvoid format_name(pfc::string_base & p_out) const;\r\n\tbool is_active() const;\r\n};\r\n\r\n//! Core service providing methods to retrieve/alter playback ReplayGain settings, as well as use ReplayGain configuration dialog.\r\nclass NOVTABLE replaygain_manager : public service_base {\r\npublic:\r\n\t//! Retrieves playback ReplayGain settings.\r\n\tvirtual void get_core_settings(t_replaygain_config & p_out) = 0;\r\n\r\n\t//! Creates embedded version of ReplayGain settings dialog. Note that embedded dialog sends WM_COMMAND with id/BN_CLICKED to parent window when user makes changes to settings.\r\n\tvirtual HWND configure_embedded(const t_replaygain_config & p_initdata,HWND p_parent,unsigned p_id,bool p_from_modal) = 0;\r\n\t//! Retrieves settings from embedded version of ReplayGain settings dialog.\r\n\tvirtual void configure_embedded_retrieve(HWND wnd,t_replaygain_config & p_data) = 0;\r\n\t\r\n\t//! Shows popup/modal version of ReplayGain settings dialog. Returns true when user changed the settings, false when user cancelled the operation. Title parameter can be null to use default one.\r\n\tvirtual bool configure_popup(t_replaygain_config & p_data,HWND p_parent,const char * p_title) = 0;\r\n\r\n\t//! Alters playback ReplayGain settings.\r\n\tvirtual void set_core_settings(const t_replaygain_config & p_config) = 0;\r\n\r\n\t//! Helper; queries scale value for specified item according to core playback settings.\r\n\taudio_sample core_settings_query_scale(const file_info & p_info);\r\n\t//! Helper; queries scale value for specified item according to core playback settings.\r\n\taudio_sample core_settings_query_scale(const metadb_handle_ptr & info);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(replaygain_manager);\r\n};\r\n\r\n#endif //_FOOBAR2000_SDK_REPLAYGAIN_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/replaygain_info.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool replaygain_info::g_format_gain(float p_value,char p_buffer[text_buffer_size])\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_value == gain_invalid)\r\n\t{\r\n\t\tp_buffer[0] = 0;\r\n\t\treturn false;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpfc::float_to_string(p_buffer,text_buffer_size - 4,p_value,2,true);\r\n\t\tstrcat(p_buffer,\" dB\");\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nbool replaygain_info::g_format_peak(float p_value,char p_buffer[text_buffer_size])\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_value == peak_invalid)\r\n\t{\r\n\t\tp_buffer[0] = 0;\r\n\t\treturn false;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tpfc::float_to_string(p_buffer,text_buffer_size,p_value,6,false);\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nvoid replaygain_info::reset()\r\n{\r\n\tm_album_gain = gain_invalid;\r\n\tm_track_gain = gain_invalid;\r\n\tm_album_peak = peak_invalid;\r\n\tm_track_peak = peak_invalid;\r\n}\r\n\r\nstatic const char meta_album_gain[] = \"replaygain_album_gain\", meta_album_peak[] = \"replaygain_album_peak\", meta_track_gain[] = \"replaygain_track_gain\", meta_track_peak[] = \"replaygain_track_peak\";\r\n\r\nbool replaygain_info::g_is_meta_replaygain(const char * p_name,t_size p_name_len)\r\n{\r\n\treturn \r\n\t\tstricmp_utf8_ex(p_name,p_name_len,meta_album_gain,infinite) == 0 ||\r\n\t\tstricmp_utf8_ex(p_name,p_name_len,meta_album_peak,infinite) == 0 ||\r\n\t\tstricmp_utf8_ex(p_name,p_name_len,meta_track_gain,infinite) == 0 ||\r\n\t\tstricmp_utf8_ex(p_name,p_name_len,meta_track_peak,infinite) == 0;\r\n}\r\n\r\nbool replaygain_info::set_from_meta_ex(const char * p_name,t_size p_name_len,const char * p_value,t_size p_value_len)\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (stricmp_utf8_ex(p_name,p_name_len,meta_album_gain,infinite) == 0)\r\n\t{\r\n\t\tm_album_gain = (float)pfc::string_to_float(p_value,p_value_len);\r\n\t\treturn true;\r\n\t}\r\n\telse if (stricmp_utf8_ex(p_name,p_name_len,meta_album_peak,infinite) == 0)\r\n\t{\r\n\t\tm_album_peak = (float)pfc::string_to_float(p_value,p_value_len);\r\n\t\tif (m_album_peak < 0) m_album_peak = 0;\r\n\t\treturn true;\r\n\t}\r\n\telse if (stricmp_utf8_ex(p_name,p_name_len,meta_track_gain,infinite) == 0)\r\n\t{\r\n\t\tm_track_gain = (float)pfc::string_to_float(p_value,p_value_len);\r\n\t\treturn true;\r\n\t}\r\n\telse if (stricmp_utf8_ex(p_name,p_name_len,meta_track_peak,infinite) == 0)\r\n\t{\r\n\t\tm_track_peak = (float)pfc::string_to_float(p_value,p_value_len);\r\n\t\tif (m_track_peak < 0) m_track_peak = 0;\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\n\r\nt_size replaygain_info::get_value_count()\r\n{\r\n\tt_size ret = 0;\r\n\tif (is_album_gain_present()) ret++;\r\n\tif (is_album_peak_present()) ret++;\r\n\tif (is_track_gain_present()) ret++;\r\n\tif (is_track_peak_present()) ret++;\r\n\treturn ret;\r\n}\r\n\r\nvoid replaygain_info::set_album_gain_text(const char * p_text,t_size p_text_len)\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_text != 0 && p_text_len > 0 && *p_text != 0)\r\n\t\tm_album_gain = (float)pfc::string_to_float(p_text,p_text_len);\r\n\telse\r\n\t\tremove_album_gain();\r\n}\r\n\r\nvoid replaygain_info::set_track_gain_text(const char * p_text,t_size p_text_len)\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_text != 0 && p_text_len > 0 && *p_text != 0)\r\n\t\tm_track_gain = (float)pfc::string_to_float(p_text,p_text_len);\r\n\telse\r\n\t\tremove_track_gain();\r\n}\r\n\r\nvoid replaygain_info::set_album_peak_text(const char * p_text,t_size p_text_len)\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_text != 0 && p_text_len > 0 && *p_text != 0)\r\n\t\tm_album_peak = (float)pfc::string_to_float(p_text,p_text_len);\r\n\telse\r\n\t\tremove_album_peak();\r\n}\r\n\r\nvoid replaygain_info::set_track_peak_text(const char * p_text,t_size p_text_len)\r\n{\r\n\tfpu_control_roundnearest bah;\r\n\tif (p_text != 0 && p_text_len > 0 && *p_text != 0)\r\n\t\tm_track_peak = (float)pfc::string_to_float(p_text,p_text_len);\r\n\telse\r\n\t\tremove_track_peak();\r\n}\r\n\r\nreplaygain_info replaygain_info::g_merge(replaygain_info r1,replaygain_info r2)\r\n{\r\n\treplaygain_info ret = r1;\r\n\tif (!ret.is_album_gain_present()) ret.m_album_gain = r2.m_album_gain;\r\n\tif (!ret.is_album_peak_present()) ret.m_album_peak = r2.m_album_peak;\r\n\tif (!ret.is_track_gain_present()) ret.m_track_gain = r2.m_track_gain;\r\n\tif (!ret.is_track_peak_present()) ret.m_track_peak = r2.m_track_peak;\r\n\treturn ret;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/resampler.h",
    "content": "class NOVTABLE resampler_entry : public dsp_entry\r\n{\r\npublic:\r\n\tvirtual bool is_conversion_supported(unsigned p_srate_from,unsigned p_srate_to) = 0;\r\n\tvirtual bool create_preset(dsp_preset & p_out,unsigned p_target_srate,float p_qualityscale) = 0;//p_qualityscale is 0...1\r\n\tvirtual float get_priority() = 0;//value is 0...1, where high-quality (SSRC etc) has 1\r\n\r\n\tstatic bool g_get_interface(service_ptr_t<resampler_entry> & p_out,unsigned p_srate_from,unsigned p_srate_to);\r\n\tstatic bool g_create(service_ptr_t<dsp> & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale);\r\n\tstatic bool g_create_preset(dsp_preset & p_out,unsigned p_srate_from,unsigned p_srate_to,float p_qualityscale);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(resampler_entry,dsp_entry);\r\n};\r\n\r\ntemplate<typename T>\r\nclass resampler_entry_impl_t : public dsp_entry_impl_t<T,resampler_entry>\r\n{\r\npublic:\r\n\tbool is_conversion_supported(unsigned p_srate_from,unsigned p_srate_to) {return T::g_is_conversion_supported(p_srate_from,p_srate_to);}\r\n\tbool create_preset(dsp_preset & p_out,unsigned p_target_srate,float p_qualityscale) {return T::g_create_preset(p_out,p_target_srate,p_qualityscale);}\r\n\tfloat get_priority() {return T::g_get_priority();}\r\n};\r\n\r\ntemplate<typename T>\r\nclass resampler_factory_t : public service_factory_single_t<resampler_entry_impl_t<T> > {};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/service.cpp",
    "content": "#include \"foobar2000.h\"\r\n#include \"component.h\"\r\n\r\nfoobar2000_api * g_api;\r\n\r\nservice_class_ref service_factory_base::enum_find_class(const GUID & p_guid)\r\n{\r\n\tPFC_ASSERT(core_api::are_services_available() && g_api);\r\n\treturn g_api->service_enum_find_class(p_guid);\r\n}\r\n\r\nbool service_factory_base::enum_create(service_ptr_t<service_base> & p_out,service_class_ref p_class,t_size p_index)\r\n{\r\n\tPFC_ASSERT(core_api::are_services_available() && g_api);\r\n\treturn g_api->service_enum_create(p_out,p_class,p_index);\r\n}\r\n\r\nt_size service_factory_base::enum_get_count(service_class_ref p_class)\r\n{\r\n\tPFC_ASSERT(core_api::are_services_available() && g_api);\r\n\treturn g_api->service_enum_get_count(p_class);\r\n}\r\n\r\nservice_factory_base * service_factory_base::__internal__list = NULL;\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/service.h",
    "content": "#ifndef _SERVICE_H_\r\n#define _SERVICE_H_\r\n\r\ntypedef const void* service_class_ref;\r\n\r\nPFC_DECLARE_EXCEPTION(exception_service_not_found,pfc::exception,\"Service not found\");\r\nPFC_DECLARE_EXCEPTION(exception_service_extension_not_found,pfc::exception,\"Service extension not found\");\r\nPFC_DECLARE_EXCEPTION(exception_service_duplicated,pfc::exception,\"Service duplicated\");\r\n\r\n#ifdef _MSC_VER\r\n#define FOOGUIDDECL __declspec(selectany)\r\n#else\r\n#define FOOGUIDDECL\r\n#endif\r\n\r\n\r\n#define DECLARE_GUID(NAME,A,S,D,F,G,H,J,K,L,Z,X) FOOGUIDDECL const GUID NAME = {A,S,D,{F,G,H,J,K,L,Z,X}};\r\n#define DECLARE_CLASS_GUID(NAME,A,S,D,F,G,H,J,K,L,Z,X) FOOGUIDDECL const GUID NAME::class_guid = {A,S,D,{F,G,H,J,K,L,Z,X}};\r\n\r\n//! Special hack to ensure errors when someone tries to ->service_add_ref()/->service_release() on a service_ptr_t\r\ntemplate<typename T> class service_obscure_refcounting : public T {\r\nprivate:\r\n\tint service_add_ref() throw();\r\n\tint service_release() throw();\r\n};\r\n\r\n//! Converts a service interface pointer to a pointer that obscures service counter functionality.\r\ntemplate<typename T> static inline service_obscure_refcounting<T>* service_obscure_refcounting_cast(T * p_source) throw() {return static_cast<service_obscure_refcounting<T>*>(p_source);}\r\n\r\n//! Multiple inheritance SNAFU fix. In some cases, old service_release_safe method of service_base would not get a NULL this pointer when called on a NULL pointer.\r\ntemplate<typename T> static void service_release_safe(T * p_ptr) throw() {\r\n\tif (p_ptr != NULL) p_ptr->service_release();\r\n}\r\n\r\n//! Multiple inheritance SNAFU fix. In some cases, old service_add_ref_safe method of service_base would not get a NULL this pointer when called on a NULL pointer.\r\ntemplate<typename T> static void service_add_ref_safe(T * p_ptr) throw() {\r\n\tif (p_ptr != NULL) p_ptr->service_add_ref();\r\n}\r\n\r\n//! Autopointer class to be used with all services. Manages reference counter calls behind-the-scenes.\r\ntemplate<typename T>\r\nclass service_ptr_t {\r\nprivate:\r\n\ttypedef service_ptr_t<T> t_self;\r\npublic:\r\n\tinline service_ptr_t() throw() : m_ptr(NULL) {}\r\n\tinline service_ptr_t(T* p_ptr) throw() : m_ptr(NULL) {copy(p_ptr);}\r\n\tinline service_ptr_t(const t_self & p_source) throw() : m_ptr(NULL) {copy(p_source);}\r\n\r\n\ttemplate<typename t_source>\r\n\tinline service_ptr_t(t_source * p_ptr) throw() : m_ptr(NULL) {copy(p_ptr);}\r\n\r\n\ttemplate<typename t_source>\r\n\tinline service_ptr_t(const service_ptr_t<t_source> & p_source) throw() : m_ptr(NULL) {copy(p_source);}\r\n\r\n\tinline ~service_ptr_t() throw() {service_release_safe(m_ptr);}\r\n\t\r\n\ttemplate<typename t_source>\r\n\tvoid copy(t_source * p_ptr) throw() {\r\n\t\tservice_release_safe(m_ptr);\r\n\t\tm_ptr = pfc::safe_ptr_cast<T>(p_ptr);\r\n\t\tservice_add_ref_safe(m_ptr);\r\n\t}\r\n\r\n\ttemplate<typename t_source>\r\n\tinline void copy(const service_ptr_t<t_source> & p_source) throw() {copy(p_source.get_ptr());}\r\n\r\n\r\n\tinline const t_self & operator=(const t_self & p_source) throw() {copy(p_source); return *this;}\r\n\tinline const t_self & operator=(T * p_ptr) throw() {copy(p_ptr); return *this;}\r\n\r\n\ttemplate<typename t_source> inline t_self & operator=(const service_ptr_t<t_source> & p_source) throw() {copy(p_source); return *this;}\r\n\ttemplate<typename t_source> inline t_self & operator=(t_source * p_ptr) throw() {copy(p_ptr); return *this;}\r\n\t\r\n\tinline void release() throw() {\r\n\t\tservice_release_safe(m_ptr);\r\n\t\tm_ptr = NULL;\r\n\t}\r\n\r\n\r\n\tinline service_obscure_refcounting<T>* operator->() const throw() {PFC_ASSERT(m_ptr != NULL);return service_obscure_refcounting_cast(m_ptr);}\r\n\r\n\tinline T* get_ptr() const throw() {return m_ptr;}\r\n\t\r\n\tinline bool is_valid() const throw() {return m_ptr != NULL;}\r\n\tinline bool is_empty() const throw() {return m_ptr == NULL;}\r\n\r\n\tinline bool operator==(const t_self & p_item) const throw() {return m_ptr == p_item.get_ptr();}\r\n\tinline bool operator!=(const t_self & p_item) const throw() {return m_ptr != p_item.get_ptr();}\r\n\tinline bool operator>(const t_self & p_item) const throw() {return m_ptr > p_item.get_ptr();}\r\n\tinline bool operator<(const t_self & p_item) const throw() {return m_ptr < p_item.get_ptr();}\r\n\r\n\ttemplate<typename t_other>\r\n\tinline t_self & operator<<(service_ptr_t<t_other> & p_source) throw() {__unsafe_set(p_source.__unsafe_detach());return *this;}\r\n\ttemplate<typename t_other>\r\n\tinline t_self & operator>>(service_ptr_t<t_other> & p_dest) throw() {p_dest.__unsafe_set(__unsafe_detach());return *this;}\r\n\r\n\r\n\tinline T* __unsafe_duplicate() const throw() {//should not be used ! temporary !\r\n\t\tservice_add_ref_safe(m_ptr);\r\n\t\treturn m_ptr;\r\n\t}\r\n\r\n\tinline T* __unsafe_detach() throw() {//should not be used ! temporary !\r\n\t\treturn pfc::replace_null_t(m_ptr);\r\n\t}\r\n\r\n\ttemplate<typename t_source>\r\n\tinline void __unsafe_set(t_source * p_ptr) throw() {//should not be used ! temporary !\r\n\t\tservice_release_safe(m_ptr);\r\n\t\tm_ptr = pfc::safe_ptr_cast<T>(p_ptr);\r\n\t}\r\nprivate:\r\n\tT* m_ptr;\r\n};\r\n\r\nnamespace pfc {\r\n\ttemplate<typename T>\r\n\tclass traits_t<service_ptr_t<T> > : public traits_default {\r\n\tpublic:\r\n\t\tenum { realloc_safe = true, constructor_may_fail = false};\r\n\t};\r\n}\r\n\r\n\r\ntemplate<typename T, template<typename> class t_alloc = pfc::alloc_fast>\r\nclass service_list_t : public pfc::list_t<service_ptr_t<T>, t_alloc >\r\n{\r\n};\r\n\r\n//! Helper macro for use when defining a service class. Generates standard features of a service, without ability to register using service_factory / enumerate using service_enum_t. \\n\r\n//! This is used for declaring services that are meant to be instantiated by means other than service_enum_t (or non-entrypoint services), or extensions of services (including extension of entrypoint services).\t\\n\r\n//! Sample non-entrypoint declaration: class myclass : public service_base {...; FB2K_MAKE_SERVICE_INTERFACE(myclass, service_base); };\t\\n\r\n//! Sample extension declaration: class myclass : public myotherclass {...; FB2K_MAKE_SERVICE_INTERFACE(myclass, myotherclass); };\t\\n\r\n//! This macro is intended for use ONLY WITH INTERFACE CLASSES, not with implementation classes.\r\n#define FB2K_MAKE_SERVICE_INTERFACE(THISCLASS,PARENTCLASS) \\\r\n\tpublic:\t\\\r\n\t\ttypedef THISCLASS t_interface;\t\\\r\n\t\ttypedef PARENTCLASS t_interface_parent;\t\\\r\n\t\t\t\\\r\n\t\tstatic const GUID class_guid;\t\\\r\n\t\t\t\\\r\n\t\tvirtual bool service_query(service_ptr_t<service_base> & p_out,const GUID & p_guid) {\t\\\r\n\t\t\tif (p_guid == class_guid) {p_out = this; return true;}\t\\\r\n\t\t\telse return PARENTCLASS::service_query(p_out,p_guid);\t\\\r\n\t\t}\t\\\r\n\tprotected:\t\\\r\n\t\tTHISCLASS() {}\t\\\r\n\t\t~THISCLASS() {}\t\\\r\n\tprivate:\t\\\r\n\t\tconst THISCLASS & operator=(const THISCLASS &) {throw pfc::exception_not_implemented();}\t\\\r\n\t\tTHISCLASS(const THISCLASS &) {throw pfc::exception_not_implemented();}\t\\\r\n\tprivate:\t\\\r\n\t\tvoid __private__service_declaration_selftest() {\t\\\r\n\t\t\tpfc::assert_same_type<PARENTCLASS,PARENTCLASS::t_interface>(); /*parentclass must be an interface*/\t\\\r\n\t\t\t__validate_service_class_helper<THISCLASS>(); /*service_base must be reachable by walking t_interface_parent*/\t\\\r\n\t\t\tpfc::safe_cast<service_base*>(this); /*this class must derive from service_base, directly or indirectly, and be implictly castable to it*/ \\\r\n\t\t}\r\n\r\n//! Helper macro for use when defining an entrypoint service class. Generates standard features of a service, including ability to register using service_factory and enumerate using service_enum.\t\\n\r\n//! Sample declaration: class myclass : public service_base {...; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(myclass); };\t\\n\r\n//! Note that entrypoint service classes must directly derive from service_base, and not from another service class.\r\n//! This macro is intended for use ONLY WITH INTERFACE CLASSES, not with implementation classes.\r\n#define FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(THISCLASS)\t\\\r\n\tpublic:\t\\\r\n\t\ttypedef THISCLASS t_interface_entrypoint;\t\\\r\n\tFB2K_MAKE_SERVICE_INTERFACE(THISCLASS,service_base)\r\n\t\t\r\n\t\r\n#define FB2K_DECLARE_SERVICE_BEGIN(THISCLASS,BASECLASS) \\\r\n\tclass NOVTABLE THISCLASS : public BASECLASS\t{\t\\\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE(THISCLASS,BASECLASS);\t\\\r\n\tpublic:\r\n\r\n#define FB2K_DECLARE_SERVICE_END() \\\r\n\t};\r\n\r\n#define FB2K_DECLARE_SERVICE_ENTRYPOINT_BEGIN(THISCLASS) \\\r\n\tclass NOVTABLE THISCLASS : public service_base {\t\\\r\n\t\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(THISCLASS)\t\\\r\n\tpublic:\r\n\t\t\r\n\r\n//! Base class for all service classes.\\n\r\n//! Provides interfaces for reference counter and querying for different interfaces supported by the object.\\n\r\nclass NOVTABLE service_base\r\n{\r\npublic:\t\r\n\t//! Decrements reference count; deletes the object if reference count reaches zero. This is normally not called directly but managed by service_ptr_t<> template.\r\n\t//! @returns New reference count. For debug purposes only, in certain conditions return values may be unreliable.\r\n\tvirtual int service_release() throw() = 0;\r\n\t//! Increments reference count. This is normally not called directly but managed by service_ptr_t<> template.\r\n\t//! @returns New reference count. For debug purposes only, in certain conditions return values may be unreliable.\r\n\tvirtual int service_add_ref() throw() = 0;\r\n\t//! Queries whether the object supports specific interface and retrieves a pointer to that interface. This is normally not called directly but managed by service_query_t<> function template.\r\n\t//! Typical implementation checks the parameter against GUIDs of interfaces supported by this object, if the GUID is one of supported interfaces, p_out is set to service_base pointer that can be static_cast<>'ed to queried interface and the method returns true; otherwise the method returns false.\r\n\tvirtual bool service_query(service_ptr_t<service_base> & p_out,const GUID & p_guid) {return false;}\r\n\r\n\t//! Queries whether the object supports specific interface and retrieves a pointer to that interface.\r\n\t//! @param p_out Receives pointer to queried interface on success.\r\n\t//! returns true on success, false on failure (interface not supported by the object).\r\n\ttemplate<class T>\r\n\tbool service_query_t(service_ptr_t<T> & p_out)\r\n\t{\r\n\t\tpfc::assert_same_type<T,T::t_interface>();\r\n\t\tservice_ptr_t<service_base> temp;\r\n\t\tif (!service_query(temp,T::class_guid)) return false;\r\n\t\tp_out.__unsafe_set(static_cast<T*>(temp.__unsafe_detach()));\r\n\t\treturn true;\r\n\t}\r\n\r\n\ttypedef service_base t_interface;\r\n\t\r\nprotected:\r\n\tservice_base() {}\r\n\t~service_base() {}\r\nprivate:\r\n\tservice_base(const service_base&) {throw pfc::exception_not_implemented();}\r\n\tconst service_base & operator=(const service_base&) {throw pfc::exception_not_implemented();}\r\n};\r\n\r\ntemplate<typename T>\r\nstatic void __validate_service_class_helper() {\r\n\t__validate_service_class_helper<T::t_interface_parent>();\r\n}\r\n\r\ntemplate<>\r\nstatic void __validate_service_class_helper<service_base>() {}\r\n\r\n\r\n#include \"service_impl.h\"\r\n\r\nclass NOVTABLE service_factory_base {\r\nprotected:\r\n\tinline service_factory_base(const GUID & p_guid) : m_guid(p_guid) {PFC_ASSERT(!core_api::are_services_available());__internal__next=__internal__list;__internal__list=this;}\r\n\tinline ~service_factory_base() {PFC_ASSERT(!core_api::are_services_available());}\r\npublic:\r\n\tinline const GUID & get_class_guid() const {return m_guid;}\r\n\r\n\tstatic service_class_ref enum_find_class(const GUID & p_guid);\r\n\tstatic bool enum_create(service_ptr_t<service_base> & p_out,service_class_ref p_class,t_size p_index);\r\n\tstatic t_size enum_get_count(service_class_ref p_class);\r\n\r\n\tinline static bool is_service_present(const GUID & g) {return enum_get_count(enum_find_class(g))>0;}\r\n\r\n\t//! Throws std::bad_alloc or another exception on failure.\r\n\tvirtual void instance_create(service_ptr_t<service_base> & p_out) = 0;\r\n\r\n\t//! FOR INTERNAL USE ONLY\r\n\tstatic service_factory_base *__internal__list;\r\n\t//! FOR INTERNAL USE ONLY\r\n\tservice_factory_base * __internal__next;\r\nprivate:\r\n\tconst GUID & m_guid;\r\n};\r\n\r\n\r\ntemplate<typename B>\r\nclass service_factory_base_t : public service_factory_base {\r\npublic:\r\n\tservice_factory_base_t() : service_factory_base(B::class_guid) {\r\n\t\tpfc::assert_same_type<B,B::t_interface_entrypoint>();\r\n\t}\r\n\r\n};\r\n\r\n\r\n\r\n\r\ntemplate<class T> static bool service_enum_create_t(service_ptr_t<T> & p_out,t_size p_index) {\r\n\tpfc::assert_same_type<T,T::t_interface_entrypoint>();\r\n\tservice_ptr_t<service_base> ptr;\r\n\tif (service_factory_base::enum_create(ptr,service_factory_base::enum_find_class(T::class_guid),p_index)) {\r\n\t\tp_out = static_cast<T*>(ptr.get_ptr());\r\n\t\treturn true;\r\n\t} else {\r\n\t\tp_out.release();\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\ntemplate<typename T> class service_class_helper_t {\r\npublic:\r\n\tservice_class_helper_t() : m_class(service_factory_base::enum_find_class(T::class_guid)) {\r\n\t\tpfc::assert_same_type<T,T::t_interface_entrypoint>();\r\n\t}\r\n\tt_size get_count() const {\r\n\t\treturn service_factory_base::enum_get_count(m_class);\r\n\t}\r\n\r\n\tbool create(service_ptr_t<T> & p_out,t_size p_index) const {\r\n\t\tservice_ptr_t<service_base> temp;\r\n\t\tif (!service_factory_base::enum_create(temp,m_class,p_index)) return false;\r\n\t\tp_out.__unsafe_set(static_cast<T*>(temp.__unsafe_detach()));\r\n\t\treturn true;\r\n\t}\r\n\r\n\tservice_ptr_t<T> create(t_size p_index) const {\r\n\t\tservice_ptr_t<T> temp;\r\n\t\tif (!create(temp,p_index)) throw pfc::exception_bug_check();\r\n\t\treturn temp;\r\n\t}\r\nprivate:\r\n\tservice_class_ref m_class;\r\n};\r\n\r\ntemplate<typename T> static void standard_api_create_t(service_ptr_t<T> & p_out) {\r\n\tif (pfc::is_same_type<T,T::t_interface_entrypoint>::value) {\r\n\t\tservice_class_helper_t<T::t_interface_entrypoint> helper;\r\n\t\tswitch(helper.get_count()) {\r\n\t\tcase 0:\r\n\t\t\tthrow exception_service_not_found();\r\n\t\tcase 1:\r\n\t\t\tif (!helper.create(reinterpret_cast<service_ptr_t<T::t_interface_entrypoint>&>(p_out),0)) throw pfc::exception_bug_check();\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tthrow exception_service_duplicated();\r\n\t\t}\r\n\t} else {\r\n\t\tservice_ptr_t<T::t_interface_entrypoint> temp;\r\n\t\tstandard_api_create_t(temp);\r\n\t\tif (!temp->service_query_t(p_out)) throw exception_service_extension_not_found();\r\n\t}\r\n}\r\n\r\ntemplate<typename T> static service_ptr_t<T> standard_api_create_t() {\r\n\tservice_ptr_t<T> temp;\r\n\tstandard_api_create_t(temp);\r\n\treturn temp;\r\n}\r\n\r\n//! Helper template used to easily access core services. \\n\r\n//! Usage: static_api_ptr_t<myclass> api; api->dosomething();\r\n//! Can be used at any point of code, WITH EXCEPTION of static objects that are initialized during DLL load before service system is initialized; such as static static_api_ptr_t objects or having static_api_ptr_t as members of statically created objects.\r\n//! Throws exception_service_not_found if service could not be reached (which can be ignored for core APIs that are always present unless there is some kind of bug in the code).\r\ntemplate<typename t_interface>\r\nclass static_api_ptr_t {\r\npublic:\r\n\tstatic_api_ptr_t() {\r\n\t\tstandard_api_create_t(m_ptr);\r\n\t}\r\n\tservice_obscure_refcounting<t_interface>* operator->() const {return service_obscure_refcounting_cast(m_ptr.get_ptr());}\r\n\tt_interface* get_ptr() const {return m_ptr.get_ptr();}\r\nprivate:\r\n\tservice_ptr_t<t_interface> m_ptr;\r\n};\r\n\r\n//! Helper; simulates array with instance of each available implementation of given service class.\r\ntemplate<typename T> class service_instance_array_t {\r\npublic:\r\n\ttypedef service_ptr_t<T> t_ptr;\r\n\tservice_instance_array_t() {\r\n\t\tservice_class_helper_t<T> helper;\r\n\t\tconst t_size count = helper.get_count();\r\n\t\tm_data.set_size(count);\r\n\t\tfor(t_size n=0;n<count;n++) m_data[n] = helper.create(n);\r\n\t}\r\n\r\n\tt_size get_size() const {return m_data.get_size();}\r\n\tconst t_ptr & operator[](t_size p_index) const {return m_data[p_index];}\r\n\r\n\t//nonconst version to allow sorting/bsearching; do not abuse\r\n\tt_ptr & operator[](t_size p_index) {return m_data[p_index];}\r\nprivate:\r\n\tpfc::array_t<t_ptr> m_data;\r\n};\r\n\r\ntemplate<typename t_interface>\r\nclass service_enum_t {\r\npublic:\r\n\tservice_enum_t() : m_index(0) {\r\n\t\tpfc::assert_same_type<t_interface,typename t_interface::t_interface_entrypoint>();\r\n\t}\r\n\tvoid reset() {m_index = 0;}\r\n\r\n\ttemplate<typename t_query>\r\n\tbool first(service_ptr_t<t_query> & p_out) {\r\n\t\treset();\r\n\t\treturn next(p_out);\r\n\t}\r\n\t\r\n\ttemplate<typename t_query>\r\n\tbool next(service_ptr_t<t_query> & p_out) {\r\n\t\tpfc::assert_same_type<typename t_query::t_interface_entrypoint,t_interface>();\r\n\t\tif (pfc::is_same_type<t_query,t_interface>::value) {\r\n\t\t\treturn __next(reinterpret_cast<service_ptr_t<t_interface>&>(p_out));\r\n\t\t} else {\r\n\t\t\tservice_ptr_t<t_interface> temp;\r\n\t\t\twhile(__next(temp)) {\r\n\t\t\t\tif (temp->service_query_t(p_out)) return true;\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\nprivate:\r\n\tbool __next(service_ptr_t<t_interface> & p_out) {\r\n\t\treturn m_helper.create(p_out,m_index++);\r\n\t}\r\n\tunsigned m_index;\r\n\tservice_class_helper_t<t_interface> m_helper;\r\n};\r\n\r\ntemplate<typename T>\r\nclass service_factory_t : public service_factory_base_t<typename T::t_interface_entrypoint> {\r\npublic:\r\n\tvoid instance_create(service_ptr_t<service_base> & p_out) {\r\n\t\tp_out = pfc::safe_cast<service_base*>(pfc::safe_cast<typename T::t_interface_entrypoint*>(pfc::safe_cast<T*>(  new service_impl_t<T>  )));\r\n\t}\r\n};\r\n\r\ntemplate<typename T>\r\nclass service_factory_single_t : public service_factory_base_t<typename T::t_interface_entrypoint> {\r\n\tservice_impl_single_t<T> g_instance;\r\npublic:\r\n\tTEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_factory_single_t,g_instance)\r\n\r\n\tvoid instance_create(service_ptr_t<service_base> & p_out) {\r\n\t\tp_out = pfc::safe_cast<service_base*>(pfc::safe_cast<typename T::t_interface_entrypoint*>(pfc::safe_cast<T*>(&g_instance)));\r\n\t}\r\n\r\n\tinline T& get_static_instance() {return g_instance;}\r\n};\r\n\r\ntemplate<typename T>\r\nclass service_factory_single_ref_t : public service_factory_base_t<typename T::t_interface_entrypoint>\r\n{\r\nprivate:\r\n\tT & instance;\r\npublic:\r\n\tservice_factory_single_ref_t(T& param) : instance(param) {}\r\n\r\n\tvoid instance_create(service_ptr_t<service_base> & p_out) {\r\n\t\tp_out = pfc::safe_cast<service_base*>(pfc::safe_cast<typename T::t_interface_entrypoint*>(pfc::safe_cast<T*>(&instance)));\r\n\t}\r\n\r\n\tinline T& get_static_instance() {return instance;}\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nclass service_factory_single_transparent_t : public service_factory_base_t<typename T::t_interface_entrypoint>, public service_impl_single_t<T>\r\n{\t\r\npublic:\r\n\tTEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_factory_single_transparent_t,service_impl_single_t<T>)\r\n\r\n\tvoid instance_create(service_ptr_t<service_base> & p_out) {\r\n\t\tp_out = pfc::safe_cast<service_base*>(pfc::safe_cast<typename T::t_interface_entrypoint*>(pfc::safe_cast<T*>(this)));\r\n\t}\r\n\r\n\tinline T& get_static_instance() {return *(T*)this;}\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/service_impl.h",
    "content": "//! Template implementing reference-counting features of service_base. Intended for dynamic instantiation: \"new service_impl_t<someclass>(param1,param2);\"; should not be instantiated otherwise (no local/static/member objects) because it does a \"delete this;\" when reference count reaches zero.\\n\r\n//! Note that some constructor parameters such as NULL will need explicit typecasts to ensure correctly guessed types for constructor function template (null string needs to be (const char*)NULL rather than just NULL, etc).\r\ntemplate<typename T>\r\nclass service_impl_t : public T\r\n{\r\npublic:\r\n\tint FB2KAPI service_release() throw() {\r\n\t\tint ret = --m_counter; \r\n\t\tif (ret == 0) try { delete this; } catch(...) {PFC_ASSERT(0);}\r\n\t\treturn ret;}\r\n\tint FB2KAPI service_add_ref() throw() {return ++m_counter;}\r\n\r\n\tTEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_impl_t,T)\r\nprivate:\r\n\tpfc::refcounter m_counter;\r\n};\r\n\r\n//! Template implementing dummy version of reference-counting features of service_base. Intended for static/local/member instantiation: \"static service_impl_single_t<someclass> myvar(params);\". Because reference counting features are disabled (dummy reference counter), code instantiating it is responsible for deleting it as well as ensuring that no references are active when the object gets deleted.\\n\r\n//! Note that some constructor parameters such as NULL will need explicit typecasts to ensure correctly guessed types for constructor function template (null string needs to be (const char*)NULL rather than just NULL, etc).\r\ntemplate<typename T>\r\nclass service_impl_single_t : public T\r\n{\r\npublic:\r\n\tint FB2KAPI service_release() throw() {return 1;}\r\n\tint FB2KAPI service_add_ref() throw() {return 1;}\r\n\r\n\tTEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(service_impl_single_t,T)\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/shared.h",
    "content": "//DEPRECATED\r\n\r\n#ifndef _FOOBAR2000_SHARED_H_\r\n#define _FOOBAR2000_SHARED_H_\r\n\r\n#include \"../shared/shared.h\"\r\n\r\nHWND uCreateDialog(UINT id,HWND parent,DLGPROC proc,LPARAM param=0);\r\nint uDialogBox(UINT id,HWND parent,DLGPROC proc,LPARAM param=0);\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/shortcut_actions.h",
    "content": "#error DEPRECATED\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/stdafx.cpp",
    "content": "//cpp used to generate precompiled header\r\n#include \"foobar2000.h\""
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/tag_processor.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid tag_processor_trailing::write_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort)\r\n{\r\n\twrite(p_file,p_info,flag_id3v1,p_abort);\r\n}\r\n\r\nvoid tag_processor_trailing::write_apev2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort)\r\n{\r\n\twrite(p_file,p_info,flag_apev2,p_abort);\r\n}\r\n\r\nvoid tag_processor_trailing::write_apev2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort)\r\n{\r\n\twrite(p_file,p_info,flag_id3v1|flag_apev2,p_abort);\r\n}\r\n\r\n\r\n\r\n\r\nenum {\r\n\tg_flag_id3v1 = 1<<0,\r\n\tg_flag_id3v2 = 1<<1,\r\n\tg_flag_apev2 = 1<<2\r\n};\r\n\r\nstatic void tagtype_list_append(pfc::string_base & p_out,const char * p_name)\r\n{\r\n\tif (!p_out.is_empty()) p_out += \"|\";\r\n\tp_out += p_name;\r\n}\r\n\r\nstatic void g_write_tags_ex(tag_write_callback & p_callback,unsigned p_flags,const service_ptr_t<file> & p_file,const file_info * p_info,abort_callback & p_abort) {\r\n\tPFC_ASSERT( p_flags == 0 || p_info != 0 );\r\n\r\n\r\n\tif (p_flags & (g_flag_id3v1 | g_flag_apev2)) {\r\n\t\tswitch(p_flags & (g_flag_id3v1 | g_flag_apev2)) {\r\n\t\tcase g_flag_id3v1 | g_flag_apev2:\r\n\t\t\tstatic_api_ptr_t<tag_processor_trailing>()->write_apev2_id3v1(p_file,*p_info,p_abort);\r\n\t\t\tbreak;\r\n\t\tcase g_flag_id3v1:\r\n\t\t\tstatic_api_ptr_t<tag_processor_trailing>()->write_id3v1(p_file,*p_info,p_abort);\r\n\t\t\tbreak;\r\n\t\tcase g_flag_apev2:\r\n\t\t\tstatic_api_ptr_t<tag_processor_trailing>()->write_apev2(p_file,*p_info,p_abort);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tthrow exception_io_data();\r\n\t\t}\r\n\t} else {\r\n\t\tstatic_api_ptr_t<tag_processor_trailing>()->remove(p_file,p_abort);\r\n\t}\r\n\r\n\tif (p_flags & g_flag_id3v2)\r\n\t{\r\n\t\tstatic_api_ptr_t<tag_processor_id3v2>()->write_ex(p_callback,p_file,*p_info,p_abort);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tt_uint64 dummy;\r\n\t\ttag_processor_id3v2::g_remove_ex(p_callback,p_file,dummy,p_abort);\r\n\t}\r\n}\r\n\r\nstatic void g_write_tags(unsigned p_flags,const service_ptr_t<file> & p_file,const file_info * p_info,abort_callback & p_abort) {\r\n\tg_write_tags_ex(tag_write_callback_dummy(),p_flags,p_file,p_info,p_abort);\r\n}\r\n\r\n\r\nvoid tag_processor::write_multi(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2) {\r\n\tunsigned flags = 0;\r\n\tif (p_write_id3v1) flags |= g_flag_id3v1;\r\n\tif (p_write_id3v2) flags |= g_flag_id3v2;\r\n\tif (p_write_apev2) flags |= g_flag_apev2;\r\n\tg_write_tags(flags,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_multi_ex(tag_write_callback & p_callback,const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2) {\r\n\tunsigned flags = 0;\r\n\tif (p_write_id3v1) flags |= g_flag_id3v1;\r\n\tif (p_write_id3v2) flags |= g_flag_id3v2;\r\n\tif (p_write_apev2) flags |= g_flag_apev2;\r\n\tg_write_tags_ex(p_callback,flags,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) {\r\n\tg_write_tags(g_flag_id3v1,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_apev2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) {\r\n\tg_write_tags(g_flag_apev2,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_apev2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) {\r\n\tg_write_tags(g_flag_apev2|g_flag_id3v1,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_id3v2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) {\r\n\tg_write_tags(g_flag_id3v2,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::write_id3v2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) {\r\n\tg_write_tags(g_flag_id3v2|g_flag_id3v1,p_file,&p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::remove_trailing(const service_ptr_t<file> & p_file,abort_callback & p_abort) {\r\n\treturn static_api_ptr_t<tag_processor_trailing>()->remove(p_file,p_abort);\r\n}\r\n\r\nvoid tag_processor::remove_id3v2(const service_ptr_t<file> & p_file,abort_callback & p_abort) {\r\n\tt_uint64 dummy;\r\n\ttag_processor_id3v2::g_remove(p_file,dummy,p_abort);\r\n}\r\n\r\nvoid tag_processor::remove_id3v2_trailing(const service_ptr_t<file> & p_file,abort_callback & p_abort) {\r\n\tremove_id3v2(p_file,p_abort);\r\n\tremove_trailing(p_file,p_abort);\r\n}\r\n\r\nvoid tag_processor::read_trailing(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort) {\r\n\tstatic_api_ptr_t<tag_processor_trailing>()->read(p_file,p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::read_trailing_ex(const service_ptr_t<file> & p_file,file_info & p_info,t_uint64 & p_tagoffset,abort_callback & p_abort) {\r\n\tstatic_api_ptr_t<tag_processor_trailing>()->read_ex(p_file,p_info,p_tagoffset,p_abort);\r\n}\r\n\r\nvoid tag_processor::read_id3v2(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort) {\r\n\tstatic_api_ptr_t<tag_processor_id3v2>()->read(p_file,p_info,p_abort);\r\n}\r\n\r\nvoid tag_processor::read_id3v2_trailing(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort)\r\n{\r\n\tfile_info_i temp_infos[2];\r\n\tbool have_id3v2 = true, have_trailing = true;\r\n\ttry {\r\n\t\tread_id3v2(p_file,temp_infos[0],p_abort);\r\n\t} catch(exception_io_data) {\r\n\t\thave_id3v2 = false;\r\n\t}\r\n\ttry {\r\n\t\tread_trailing(p_file,temp_infos[1],p_abort);\r\n\t} catch(exception_io_data) {\r\n\t\thave_trailing = false;\r\n\t}\r\n\r\n\tif (!have_id3v2 && !have_trailing) throw exception_tag_not_found();\r\n\telse  {\r\n\t\tpfc::ptr_list_t<const file_info> blargh;\r\n\t\tif (have_id3v2) blargh.add_item(&temp_infos[0]);\r\n\t\tif (have_trailing) blargh.add_item(&temp_infos[1]);\r\n\t\tp_info.merge(blargh);\r\n\t}\r\n}\r\n\r\nvoid tag_processor::skip_id3v2(const service_ptr_t<file> & p_file,t_uint64 & p_size_skipped,abort_callback & p_abort) {\r\n\ttag_processor_id3v2::g_skip(p_file,p_size_skipped,p_abort);\r\n}\r\n\r\nbool tag_processor::is_id3v1_sufficient(const file_info & p_info)\r\n{\r\n\treturn static_api_ptr_t<tag_processor_trailing>()->is_id3v1_sufficient(p_info);\r\n}\r\n\r\nvoid tag_processor::truncate_to_id3v1(file_info & p_info)\r\n{\r\n\tstatic_api_ptr_t<tag_processor_trailing>()->truncate_to_id3v1(p_info);\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/tag_processor.h",
    "content": "#ifndef _TAG_PROCESSOR_H_\r\n#define _TAG_PROCESSOR_H_\r\n\r\n\r\nPFC_DECLARE_EXCEPTION(exception_tag_not_found,exception_io_data,\"Tag not found\");\r\n\r\n//! Callback interface for write-tags-to-temp-file-and-swap scheme, used for ID3v2 tag updates and such where entire file needs to be rewritten. \r\n//! As a speed optimization, file content can be copied to a temporary file in the same directory as the file being updated, and then source file can be swapped for the newly created file with updated tags.\r\n//! This also gives better security against data loss on crash compared to rewriting the file in place and using memory or generic temporary file APIs to store content being rewritten.\r\nclass NOVTABLE tag_write_callback {\r\npublic:\r\n\t//! Called only once per operation (or not called at all when operation being performed can be done in-place).\r\n\t//! Requests a temporary file to be created in the same directory\r\n\tvirtual bool open_temp_file(service_ptr_t<file> & p_out,abort_callback & p_abort) = 0;\t\r\nprotected:\r\n\ttag_write_callback() {}\r\n\t~tag_write_callback() {}\r\nprivate:\r\n\ttag_write_callback(const tag_write_callback &) {throw pfc::exception_not_implemented();}\r\n\tconst tag_write_callback & operator=(const tag_write_callback &) {throw pfc::exception_not_implemented();}\r\n};\r\n\r\nclass tag_write_callback_dummy : public tag_write_callback {\r\npublic:\r\n\tbool open_temp_file(service_ptr_t<file> & p_out,abort_callback & p_abort) {return false;}\r\n};\r\n\r\nclass NOVTABLE tag_processor_id3v2 : public service_base\r\n{\r\npublic:\r\n\tvirtual void read(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort) = 0;\r\n\tvirtual void write(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) = 0;\r\n\tvirtual void write_ex(tag_write_callback & p_callback,const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort) = 0;\r\n\r\n\tstatic bool g_get(service_ptr_t<tag_processor_id3v2> & p_out);\r\n\tstatic void g_skip(const service_ptr_t<file> & p_file,t_filesize & p_size_skipped,abort_callback & p_abort);\r\n\tstatic void g_remove(const service_ptr_t<file> & p_file,t_filesize & p_size_removed,abort_callback & p_abort);\r\n\tstatic void g_remove_ex(tag_write_callback & p_callback,const service_ptr_t<file> & p_file,t_filesize & p_size_removed,abort_callback & p_abort);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(tag_processor_id3v2);\r\n};\r\n\r\nclass NOVTABLE tag_processor_trailing : public service_base\r\n{\r\npublic:\r\n\tenum {\r\n\t\tflag_apev2 = 1,\r\n\t\tflag_id3v1 = 2,\r\n\t};\r\n\r\n\tvirtual void read(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort) = 0;\r\n\tvirtual void write(const service_ptr_t<file> & p_file,const file_info & p_info,unsigned p_flags,abort_callback & p_abort) = 0;\r\n\tvirtual void remove(const service_ptr_t<file> & p_file,abort_callback & p_abort) = 0;\r\n\tvirtual bool is_id3v1_sufficient(const file_info & p_info) = 0;\r\n\tvirtual void truncate_to_id3v1(file_info & p_info) = 0;\r\n\tvirtual void read_ex(const service_ptr_t<file> & p_file,file_info & p_info,t_filesize & p_tagoffset,abort_callback & p_abort) = 0;\r\n\r\n\tvoid write_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\tvoid write_apev2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\tvoid write_apev2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(tag_processor_trailing);\r\n};\r\n\r\nnamespace tag_processor {\r\n\t//! Strips all recognized tags from the file and writes an ID3v1 tag with specified info.\r\n\tvoid write_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\t//! Strips all recognized tags from the file and writes an APEv2 tag with specified info.\r\n\tvoid write_apev2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\t//! Strips all recognized tags from the file and writes ID3v1+APEv2 tags with specified info.\r\n\tvoid write_apev2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\t//! Strips all recognized tags from the file and writes an ID3v2 tag with specified info.\r\n\tvoid write_id3v2(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\t//! Strips all recognized tags from the file and writes ID3v1+ID3v2 tags with specified info.\r\n\tvoid write_id3v2_id3v1(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort);\r\n\t//! Strips all recognized tags from the file and writes new tags with specified info according to parameters.\r\n\tvoid write_multi(const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2);\r\n\t//! Strips all recognized tags from the file and writes new tags with specified info according to parameters. Extended to allow write-tags-to-temp-file-and-swap scheme.\r\n\tvoid write_multi_ex(tag_write_callback & p_callback,const service_ptr_t<file> & p_file,const file_info & p_info,abort_callback & p_abort,bool p_write_id3v1,bool p_write_id3v2,bool p_write_apev2);\r\n\t//! Removes trailing tags from the file.\r\n\tvoid remove_trailing(const service_ptr_t<file> & p_file,abort_callback & p_abort);\r\n\t//! Removes ID3v2 tags from the file.\r\n\tvoid remove_id3v2(const service_ptr_t<file> & p_file,abort_callback & p_abort);\r\n\t//! Removes ID3v2 and trailing tags from specified file (not to be confused with trailing ID3v2 which are not yet supported).\r\n\tvoid remove_id3v2_trailing(const service_ptr_t<file> & p_file,abort_callback & p_abort);\r\n\t//! Reads trailing tags from the file.\r\n\tvoid read_trailing(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort);\r\n\t//! Reads trailing tags from the file. Extended version, returns offset at which parsed tags start.\r\n\tvoid read_trailing_ex(const service_ptr_t<file> & p_file,file_info & p_info,t_filesize & p_tagoffset,abort_callback & p_abort);\r\n\t//! Reads ID3v2 tags from specified file.\r\n\tvoid read_id3v2(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort);\r\n\t//! Reads ID3v2 and trailing tags from specified file (not to be confused with trailing ID3v2 which are not yet supported).\r\n\tvoid read_id3v2_trailing(const service_ptr_t<file> & p_file,file_info & p_info,abort_callback & p_abort);\r\n\r\n\tvoid skip_id3v2(const service_ptr_t<file> & p_file,t_filesize & p_size_skipped,abort_callback & p_abort);\r\n\r\n\tbool is_id3v1_sufficient(const file_info & p_info);\r\n\tvoid truncate_to_id3v1(file_info & p_info);\r\n\r\n};\r\n\r\n#endif //_TAG_PROCESSOR_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/tag_processor_id3v2.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool tag_processor_id3v2::g_get(service_ptr_t<tag_processor_id3v2> & p_out)\r\n{\r\n\treturn service_enum_t<tag_processor_id3v2>().first(p_out);\r\n}\r\n\r\nvoid tag_processor_id3v2::g_remove(const service_ptr_t<file> & p_file,t_uint64 & p_size_removed,abort_callback & p_abort) {\r\n\tg_remove_ex(tag_write_callback_dummy(),p_file,p_size_removed,p_abort);\r\n}\r\n\r\nvoid tag_processor_id3v2::g_remove_ex(tag_write_callback & p_callback,const service_ptr_t<file> & p_file,t_uint64 & p_size_removed,abort_callback & p_abort)\r\n{\r\n\tp_file->ensure_seekable();\r\n\r\n\tt_filesize len;\r\n\t\r\n\tlen = p_file->get_size(p_abort);\r\n\r\n\tif (len == filesize_invalid) throw exception_io_no_length();;\r\n\t\r\n\tp_file->seek(0,p_abort);\r\n\t\r\n\tt_uint64 offset;\r\n\tg_skip(p_file,offset,p_abort);\r\n\t\r\n\tif (offset>0 && offset<len)\r\n\t{\r\n\t\tlen-=offset;\r\n\t\tservice_ptr_t<file> temp;\r\n\t\tif (p_callback.open_temp_file(temp,p_abort)) {\r\n\t\t\tfile::g_transfer_object(p_file,temp,len,p_abort);\r\n\t\t} else {\r\n\t\t\tif (len > 16*1024*1024) filesystem::g_open_temp(temp,p_abort);\r\n\t\t\telse filesystem::g_open_tempmem(temp,p_abort);\r\n\t\t\tfile::g_transfer_object(p_file,temp,len,p_abort);\r\n\t\t\tp_file->seek(0,p_abort);\r\n\t\t\tp_file->set_eof(p_abort);\r\n\t\t\ttemp->seek(0,p_abort);\r\n\t\t\tfile::g_transfer_object(temp,p_file,len,p_abort);\r\n\t\t}\r\n\t}\r\n\tp_size_removed = offset;\r\n}\r\n\r\nvoid tag_processor_id3v2::g_skip(const service_ptr_t<file> & p_file,t_uint64 & p_size_skipped,abort_callback & p_abort)\r\n{\r\n\r\n\tunsigned char  tmp[10];\r\n\r\n\tt_size io_bytes_done;\r\n\r\n\tp_file->seek ( 0, p_abort );\r\n\r\n\tio_bytes_done = p_file->read( tmp, sizeof(tmp),  p_abort);\r\n\tif (io_bytes_done != sizeof(tmp))  {\r\n\t\tp_file->seek ( 0, p_abort );\r\n\t\tp_size_skipped = 0;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif ( 0 != memcmp ( tmp, \"ID3\", 3) ) {\r\n\t\tp_file->seek ( 0, p_abort );\r\n\t\tp_size_skipped = 0;\r\n\t\treturn;\r\n\t}\r\n\r\n\tint Unsynchronisation = tmp[5] & 0x80;\r\n\tint ExtHeaderPresent  = tmp[5] & 0x40;\r\n\tint ExperimentalFlag  = tmp[5] & 0x20;\r\n\tint FooterPresent     = tmp[5] & 0x10;\r\n\r\n\tif ( tmp[5] & 0x0F ) {\r\n\t\tp_file->seek ( 0, p_abort );\r\n\t\tp_size_skipped = 0;\r\n\t\treturn;\r\n\t}\r\n\r\n\tif ( (tmp[6] | tmp[7] | tmp[8] | tmp[9]) & 0x80 ) {\r\n\t\tp_file->seek ( 0, p_abort );\r\n\t\tp_size_skipped = 0;\r\n\t\treturn;\r\n\t}\r\n\r\n\tt_uint32 ret;\r\n\tret  = tmp[6] << 21;\r\n\tret += tmp[7] << 14;\r\n\tret += tmp[8] <<  7;\r\n\tret += tmp[9]      ;\r\n\tret += 10;\r\n\tif ( FooterPresent ) ret += 10;\r\n\r\n\tp_file->seek ( ret, p_abort );\r\n\r\n\tp_size_skipped = ret;\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/threaded_process.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid threaded_process_status::set_progress(t_size p_state,t_size p_max)\r\n{\r\n\tset_progress( progress_min + MulDiv_Size(p_state,progress_max-progress_min,p_max) );\r\n}\r\n\r\nvoid threaded_process_status::set_progress_secondary(t_size p_state,t_size p_max)\r\n{\r\n\tset_progress_secondary( progress_min + MulDiv_Size(p_state,progress_max-progress_min,p_max) );\r\n}\r\n\r\nvoid threaded_process_status::set_progress_float(double p_state)\r\n{\r\n\tif (p_state < 0.0) set_progress(progress_min);\r\n\telse if (p_state < 1.0) set_progress( progress_min + (t_size)(p_state * (progress_max - progress_min)));\r\n\telse set_progress(progress_max);\r\n}\r\n\r\nvoid threaded_process_status::set_progress_secondary_float(double p_state)\r\n{\r\n\tif (p_state < 0.0) set_progress_secondary(progress_min);\r\n\telse if (p_state < 1.0) set_progress_secondary( progress_min + (t_size)(p_state * (progress_max - progress_min)));\r\n\telse set_progress_secondary(progress_max);\r\n}\r\n\r\n\r\nbool threaded_process::g_run_modal(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len)\r\n{\r\n\treturn static_api_ptr_t<threaded_process>()->run_modal(p_callback,p_flags,p_parent,p_title,p_title_len);\r\n}\r\n\r\nbool threaded_process::g_run_modeless(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len)\r\n{\r\n\treturn static_api_ptr_t<threaded_process>()->run_modeless(p_callback,p_flags,p_parent,p_title,p_title_len);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/threaded_process.h",
    "content": "#ifndef _foobar2000_sdk_threaded_process_h_\r\n#define _foobar2000_sdk_threaded_process_h_\r\n\r\nclass NOVTABLE threaded_process_status\r\n{\r\npublic:\r\n\tenum {progress_min = 0, progress_max = 5000};\r\n\t\r\n\tvirtual void set_progress(t_size p_state) = 0;\r\n\tvirtual void set_progress_secondary(t_size p_state) = 0;\r\n\tvirtual void set_item(const char * p_item,t_size p_item_len = ~0) = 0;\r\n\tvirtual void set_item_path(const char * p_item,t_size p_item_len = ~0) = 0;\r\n\tvirtual void set_title(const char * p_title,t_size p_title_len = ~0) = 0;\r\n\tvirtual void force_update() = 0;\r\n\tvirtual bool is_paused() = 0;\r\n\tvirtual bool process_pause() = 0;//checks if process is paused and sleeps if needed; returns false when process should be aborted, true on success\r\n\r\n\tvoid set_progress(t_size p_state,t_size p_max);\r\n\tvoid set_progress_secondary(t_size p_state,t_size p_max);\r\n\tvoid set_progress_float(double p_state);\r\n\tvoid set_progress_secondary_float(double p_state);\r\nprotected:\r\n\tthreaded_process_status() {}\r\n\t~threaded_process_status() {}\r\n};\r\n\r\n\r\nclass NOVTABLE threaded_process_callback : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_init(HWND p_wnd) {}\r\n\tvirtual void run(threaded_process_status & p_status,abort_callback & p_abort) = 0;\r\n\tvirtual void on_done(HWND p_wnd,bool p_was_aborted) {}\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(threaded_process_callback,service_base);\r\n};\r\n\r\nclass NOVTABLE threaded_process : public service_base {\r\npublic:\r\n\tenum {\r\n\t\tflag_show_abort\t\t\t= 1,\r\n\t\tflag_show_minimize\t\t= 1 << 1,\r\n\t\tflag_show_progress\t\t= 1 << 2,\r\n\t\tflag_show_progress_dual\t= 1 << 3,//implies flag_show_progress\r\n\t\tflag_show_item\t\t\t= 1 << 4,\r\n\t\tflag_show_pause\t\t\t= 1 << 5,\r\n\t\tflag_high_priority\t\t= 1 << 6,\r\n\t\tflag_show_delayed\t\t= 1 << 7,//modeless-only\r\n\t\tflag_no_focus\t\t\t= 1 << 8,//new (0.9.3)\r\n\t};\r\n\r\n\tvirtual bool run_modal(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len) = 0;\r\n\tvirtual bool run_modeless(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len) = 0;\r\n\r\n\tstatic bool g_run_modal(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = infinite);\r\n\tstatic bool g_run_modeless(service_ptr_t<threaded_process_callback> p_callback,unsigned p_flags,HWND p_parent,const char * p_title,t_size p_title_len = infinite);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(threaded_process);\r\n};\r\n\r\n\r\n#endif //_foobar2000_sdk_threaded_process_h_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/titleformat.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nvoid titleformat_compiler::remove_color_marks(const char * src,pfc::string_base & out)//helper\r\n{\r\n\tout.reset();\r\n\twhile(*src)\r\n\t{\r\n\t\tif (*src==3)\r\n\t\t{\r\n\t\t\tsrc++;\r\n\t\t\twhile(*src && *src!=3) src++;\r\n\t\t\tif (*src==3) src++;\r\n\t\t}\r\n\t\telse out.add_byte(*src++);\r\n\t}\r\n}\r\n\r\nstatic bool test_for_bad_char(const char * source,t_size source_char_len,const char * reserved)\r\n{\r\n\treturn pfc::strstr_ex(reserved,(t_size)(-1),source,source_char_len) != (t_size)(-1);\r\n}\r\n\r\nvoid titleformat_compiler::remove_forbidden_chars(titleformat_text_out * p_out,const GUID & p_inputtype,const char * p_source,t_size p_source_len,const char * p_reserved_chars)\r\n{\r\n\tif (p_reserved_chars == 0 || *p_reserved_chars == 0)\r\n\t{\r\n\t\tp_out->write(p_inputtype,p_source,p_source_len);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tp_source_len = pfc::strlen_max(p_source,p_source_len);\r\n\t\tt_size index = 0;\r\n\t\tt_size good_byte_count = 0;\r\n\t\twhile(index < p_source_len)\r\n\t\t{\r\n\t\t\tt_size delta = pfc::utf8_char_len(p_source + index,p_source_len - index);\r\n\t\t\tif (delta == 0) break;\r\n\t\t\tif (test_for_bad_char(p_source+index,delta,p_reserved_chars))\r\n\t\t\t{\r\n\t\t\t\tif (good_byte_count > 0) {p_out->write(p_inputtype,p_source+index-good_byte_count,good_byte_count);good_byte_count=0;}\r\n\t\t\t\tp_out->write(p_inputtype,\"_\",1);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tgood_byte_count += delta;\r\n\t\t\t}\r\n\t\t\tindex += delta;\r\n\t\t}\r\n\t\tif (good_byte_count > 0) {p_out->write(p_inputtype,p_source+index-good_byte_count,good_byte_count);good_byte_count=0;}\r\n\t}\r\n}\r\n\r\nvoid titleformat_compiler::remove_forbidden_chars_string_append(pfc::string_receiver & p_out,const char * p_source,t_size p_source_len,const char * p_reserved_chars)\r\n{\r\n\tremove_forbidden_chars(&titleformat_text_out_impl_string(p_out),pfc::guid_null,p_source,p_source_len,p_reserved_chars);\r\n}\r\n\r\nvoid titleformat_compiler::remove_forbidden_chars_string(pfc::string_base & p_out,const char * p_source,t_size p_source_len,const char * p_reserved_chars)\r\n{\r\n\tp_out.reset();\r\n\tremove_forbidden_chars_string_append(p_out,p_source,p_source_len,p_reserved_chars);\r\n}\r\n\r\nvoid titleformat_hook_impl_file_info::process_codec(titleformat_text_out * p_out)\r\n{\r\n\tpfc::string8 temp;\r\n\tconst char * val = m_info->info_get(\"codec\");\r\n\tif (val)\r\n\t{\r\n\t\tp_out->write(titleformat_inputtypes::meta,val);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tval = m_info->info_get(\"referenced_file\");\r\n\t\tif (val) uAddStringUpper(temp,pfc::string_extension(val));\r\n\t\telse uAddStringUpper(temp,pfc::string_extension(m_location.get_path()));\r\n\t\tp_out->write(titleformat_inputtypes::meta,temp);\r\n\t}\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::remap_meta(t_size & p_meta_index, const char * p_name, t_size p_name_length)\r\n{\r\n\tp_meta_index = infinite;\r\n\tif (!stricmp_utf8_ex(p_name, p_name_length, \"album\", infinite))\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find(\"album\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"venue\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\treturn false;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name, p_name_length, \"artist\", infinite))\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find(\"artist\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"album artist\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"composer\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"performer\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\treturn false;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name, p_name_length, \"album artist\", infinite))\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find(\"album artist\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"artist\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"composer\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"performer\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\treturn false;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"track artist\",infinite))\r\n\t{\r\n\t\tt_size index_artist, index_album_artist;\r\n\t\t\r\n\t\tindex_artist = m_info->meta_find(\"artist\");\r\n\t\tif (index_artist == infinite) return false;\r\n\t\tindex_album_artist = m_info->meta_find(\"album artist\");\r\n\t\tif (index_album_artist == infinite) return false;\r\n\t\tif (m_info->are_meta_fields_identical(index_artist, index_album_artist)) return false;\r\n\r\n\t\tp_meta_index = index_artist;\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"track\",infinite) || !stricmp_utf8_ex(p_name,p_name_length,\"tracknumber\",infinite))\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find(\"tracknumber\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"track\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\treturn false;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"disc\",infinite) || !stricmp_utf8_ex(p_name,p_name_length,\"discnumber\",infinite))\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find(\"discnumber\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\tp_meta_index = m_info->meta_find(\"disc\");\r\n\t\tif (p_meta_index != infinite) return true;\r\n\t\treturn false;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tp_meta_index = m_info->meta_find_ex(p_name,p_name_length);\r\n\t\treturn p_meta_index != infinite;\r\n\t}\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag)\r\n{\r\n\tp_found_flag = false;\r\n\r\n\t//todo make this bsearch someday\r\n\tif (stricmp_utf8_ex(p_name,p_name_length,\"filename\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_filename\",infinite) == 0) {\r\n\t\tpfc::string8 temp;\r\n\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,pfc::string_filename(temp),infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"filename_ext\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_filename_ext\",infinite) == 0) {\r\n\t\tpfc::string8 temp;\r\n\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,pfc::string_filename_ext(temp),infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (!stricmp_utf8_ex(p_name,p_name_length,\"filename_sort\",infinite)) {\r\n\t\tpfc::string8 temp;\r\n\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,pfc::string_filename(temp),infinite);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,\"|\",infinite);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,pfc::format_uint(m_location.get_subsong(),10),infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"path\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_path\",infinite) == 0) {\r\n\t\tpfc::string8 temp;\r\n\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,temp.is_empty() ? \"n/a\" : temp.get_ptr(),infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (!stricmp_utf8_ex(p_name,p_name_length,\"path_sort\",infinite)) {\r\n\t\tpfc::string8_fastalloc temp;\r\n\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,temp,infinite);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,\"|\",infinite);\r\n\t\tp_out->write(titleformat_inputtypes::unknown,pfc::format_uint(m_location.get_subsong(),10),infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"directoryname\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_directoryname\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"directory\",infinite) == 0) {\r\n\t\tint count = 1;\r\n\t\tif (count > 0)\r\n\t\t{\r\n\t\t\tpfc::string8_fastalloc temp;\r\n\t\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\t\t\r\n\t\t\tfor(;count;count--)\r\n\t\t\t{\r\n\t\t\t\tt_size ptr = temp.scan_filename();\r\n\t\t\t\tif (ptr==0) {temp.reset();break;}\r\n\t\t\t\tptr--;\r\n\t\t\t\ttemp.truncate(ptr);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (temp.is_empty())\r\n\t\t\t{\r\n\t\t\t\tp_found_flag = false;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tp_out->write(titleformat_inputtypes::meta,temp + temp.scan_filename(),infinite);\r\n\t\t\t\tp_found_flag = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (stricmp_utf8_ex(p_name,p_name_length,\"subsong\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_subsong\",infinite) == 0)\r\n\t{\r\n\t\tp_out->write_int(titleformat_inputtypes::unknown,m_location.get_subsong());\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"channels\",infinite))\r\n\t{\r\n\t\tunsigned val = (unsigned)m_info->info_get_int(\"channels\");\r\n\t\tswitch(val)\r\n\t\t{\r\n\t\tcase 0: p_out->write(titleformat_inputtypes::meta,\"N/A\",infinite); break;\r\n\t\tcase 1: p_out->write(titleformat_inputtypes::meta,\"mono\",infinite); p_found_flag = true; break;\r\n\t\tcase 2: p_out->write(titleformat_inputtypes::meta,\"stereo\",infinite); p_found_flag = true; break;\r\n\t\tdefault: p_out->write_int(titleformat_inputtypes::meta,val); p_out->write(titleformat_inputtypes::meta,\"ch\",infinite); p_found_flag = true; break;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"bitrate\",infinite))\r\n\t{\r\n\t\tconst char * value = m_info->info_get(\"bitrate_dynamic\");\r\n\t\tif (value == 0 || *value == 0) value = m_info->info_get(\"bitrate\");\r\n\t\tif (value == 0 || *value == 0) return false;\r\n\t\tp_out->write(titleformat_inputtypes::meta,value);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"samplerate\",infinite))\r\n\t{\r\n\t\tconst char * value = m_info->info_get(\"samplerate\");\r\n\t\tif (value == 0 || *value == 0) return false;\r\n\t\tp_out->write(titleformat_inputtypes::meta,value);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"title\",infinite))\r\n\t{\r\n\t\tif (process_meta(p_out,p_name,p_name_length,\", \",2,\", \",2))\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tpfc::string8 temp;\r\n\t\t\tfilesystem::g_get_display_path(m_location.get_path(),temp);\r\n\t\t\tpfc::string_filename fn(temp);\r\n\t\t\tif (fn.is_empty()) p_out->write(titleformat_inputtypes::meta,temp);\r\n\t\t\telse p_out->write(titleformat_inputtypes::meta,fn);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"codec\",infinite))\r\n\t{\r\n\t\tprocess_codec(p_out);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (!stricmp_utf8_ex(p_name,p_name_length,\"codec_profile\",infinite)) {\r\n\t\tconst char * profile = m_info->info_get(\"codec_profile\");\r\n\t\tif (profile == NULL) return false;\r\n\t\tp_out->write(titleformat_inputtypes::meta,profile,infinite);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\t\t\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"track\",infinite) || !stricmp_utf8_ex(p_name,p_name_length,\"tracknumber\",infinite))\r\n\t{\r\n\t\tconst t_size pad = 2;\r\n\t\tconst char * val = m_info->meta_get_ex(\"tracknumber\",infinite,0);\r\n\t\tif (val == 0) m_info->meta_get_ex(\"track\",infinite,0);\r\n\t\tif (val != 0)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tt_size val_len = strlen(val);\r\n\t\t\tif (val_len < pad)\r\n\t\t\t{\r\n\t\t\t\tt_size n = pad - val_len;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tp_out->write(titleformat_inputtypes::meta,\"0\",1);\r\n\t\t\t\t\tn--;\r\n\t\t\t\t} while(n > 0);\r\n\t\t\t}\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,val);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"disc\",infinite) || !stricmp_utf8_ex(p_name,p_name_length,\"discnumber\",infinite))\r\n\t{\r\n\t\tconst t_size pad = 1;\r\n\t\tconst char * val = m_info->meta_get_ex(\"discnumber\",infinite,0);\r\n\t\tif (val == 0) val = m_info->meta_get_ex(\"disc\",infinite,0);\r\n\t\tif (val != 0)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tt_size val_len = strlen(val);\r\n\t\t\tif (val_len < pad)\r\n\t\t\t{\r\n\t\t\t\tt_size n = pad - val_len;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tp_out->write(titleformat_inputtypes::meta,\"0\");\r\n\t\t\t\t\tn--;\r\n\t\t\t\t} while(n > 0);\r\n\t\t\t}\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,val);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"totaltracks\",infinite))\t{\r\n\t\tconst t_size pad = 2;\r\n\t\tconst char * val = m_info->meta_get_ex(\"totaltracks\",infinite,0);\r\n\t\tif (val != NULL)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tt_size val_len = strlen(val);\r\n\t\t\tif (val_len < pad)\r\n\t\t\t{\r\n\t\t\t\tt_size n = pad - val_len;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tp_out->write(titleformat_inputtypes::meta,\"0\",1);\r\n\t\t\t\t\tn--;\r\n\t\t\t\t} while(n > 0);\r\n\t\t\t}\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,val);\r\n\t\t}\r\n\t\treturn true;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"length\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_length\",infinite) == 0) {\r\n\t\tdouble len = m_info->get_length();\r\n\t\tif (len>0)\r\n\t\t{\r\n\t\t\tp_out->write(titleformat_inputtypes::unknown,pfc::format_time(pfc::rint64(len)));\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse return false;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"length_ex\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_length_ex\",infinite) == 0) {\r\n\t\tdouble len = m_info->get_length();\r\n\t\tif (len>0)\r\n\t\t{\r\n\t\t\tp_out->write(titleformat_inputtypes::unknown,pfc::format_time_ex(len),infinite);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse return false;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"length_seconds\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_length_seconds\",infinite) == 0) {\r\n\t\tdouble len = m_info->get_length();\r\n\t\tif (len>0) {\r\n\t\t\tp_out->write_int(titleformat_inputtypes::unknown,(t_uint64)len);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t} else return false;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"length_seconds_fp\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_length_seconds_fp\",infinite) == 0) {\r\n\t\tdouble len = m_info->get_length();\r\n\t\tif (len>0) {\r\n\t\t\tp_out->write(titleformat_inputtypes::unknown,pfc::string_fixed_t<64>()<<len);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t} else return false;\r\n\t} else if (stricmp_utf8_ex(p_name,p_name_length,\"length_samples\",infinite) == 0 || stricmp_utf8_ex(p_name,p_name_length,\"_length_samples\",infinite) == 0) {\r\n\t\tt_int64 val = m_info->info_get_length_samples();\r\n\t\tif (val>0) {\r\n\t\t\tp_out->write_int(titleformat_inputtypes::unknown,val);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t} else return false;\r\n\t}\r\n\telse if (p_name_length > 2 && p_name[0] == '_' && p_name[1] == '_')\r\n\t{//info\r\n\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"__replaygain_album_gain\",infinite))\r\n\t\t{\r\n\t\t\tchar rgtemp[replaygain_info::text_buffer_size];\r\n\t\t\tm_info->get_replaygain().format_album_gain(rgtemp);\r\n\t\t\tif (rgtemp[0] == 0) return false;\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,rgtemp);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"__replaygain_album_peak\",infinite))\r\n\t\t{\r\n\t\t\tchar rgtemp[replaygain_info::text_buffer_size];\r\n\t\t\tm_info->get_replaygain().format_album_peak(rgtemp);\r\n\t\t\tif (rgtemp[0] == 0) return false;\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,rgtemp);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"__replaygain_track_gain\",infinite))\r\n\t\t{\r\n\t\t\tchar rgtemp[replaygain_info::text_buffer_size];\r\n\t\t\tm_info->get_replaygain().format_track_gain(rgtemp);\r\n\t\t\tif (rgtemp[0] == 0) return false;\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,rgtemp);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"__replaygain_track_peak\",infinite))\r\n\t\t{\r\n\t\t\tchar rgtemp[replaygain_info::text_buffer_size];\r\n\t\t\tm_info->get_replaygain().format_track_peak(rgtemp);\r\n\t\t\tif (rgtemp[0] == 0) return false;\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,rgtemp);\r\n\t\t\tp_found_flag = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tconst char * value = m_info->info_get_ex(p_name+2,p_name_length-2);\r\n\t\tif (value == 0 || *value == 0) return false;\r\n\t\tp_out->write(titleformat_inputtypes::meta,value);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\r\n\t}\r\n\telse if (p_name_length > 1 && p_name[0] == '_')\r\n\t{//special field\r\n\t\tbool found = process_extra(p_out,p_name+1,p_name_length-1);\r\n\t\tp_found_flag = found;\r\n\t\treturn found;\r\n\t}\r\n\telse\r\n\t{//meta\r\n\t\tt_size index;\r\n\t\tif (remap_meta(index, p_name, p_name_length))\r\n\t\t{\r\n\t\t\tbool status = process_meta(p_out,index,\", \",2,\", \",2);\r\n\t\t\tp_found_flag = status;\r\n\t\t\treturn status;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag)\r\n{\r\n\tp_found_flag = false;\r\n\tif (!stricmp_utf8_ex(p_name,p_name_length,\"meta\",infinite))\r\n\t{\r\n\t\tswitch(p_params->get_param_count())\r\n\t\t{\r\n\t\tcase 1:\r\n\t\t\t{\r\n\t\t\t\tconst char * name;\r\n\t\t\t\tt_size name_length;\r\n\t\t\t\tp_params->get_param(0,name,name_length);\r\n\t\t\t\tbool status = process_meta(p_out,name,name_length,\", \",2,\", \",2);\r\n\t\t\t\tp_found_flag = status;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\tcase 2:\r\n\t\t\t{\r\n\t\t\t\tconst char * name;\r\n\t\t\t\tt_size name_length;\r\n\t\t\t\tp_params->get_param(0,name,name_length);\r\n\t\t\t\tt_size index_val = p_params->get_param_uint(1);\r\n\t\t\t\tconst char * value = m_info->meta_get_ex(name,name_length,index_val);\r\n\t\t\t\tif (value != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tp_found_flag = true;\r\n\t\t\t\t\tp_out->write(titleformat_inputtypes::meta,value,infinite);\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\tdefault:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"meta_sep\",infinite))\r\n\t{\r\n\t\tswitch(p_params->get_param_count())\r\n\t\t{\r\n\t\tcase 2:\r\n\t\t\t{\r\n\t\t\t\tconst char * name, * sep1;\r\n\t\t\t\tt_size name_length, sep1_length;\r\n\t\t\t\tp_params->get_param(0,name,name_length);\r\n\t\t\t\tp_params->get_param(1,sep1,sep1_length);\r\n\t\t\t\tbool status = process_meta(p_out,name,name_length,sep1,sep1_length,sep1,sep1_length);\r\n\t\t\t\tp_found_flag = status;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\tcase 3:\r\n\t\t\t{\r\n\t\t\t\tconst char * name, * sep1, * sep2;\r\n\t\t\t\tt_size name_length, sep1_length, sep2_length;\r\n\t\t\t\tp_params->get_param(0,name,name_length);\r\n\t\t\t\tp_params->get_param(1,sep1,sep1_length);\r\n\t\t\t\tp_params->get_param(2,sep2,sep2_length);\r\n\t\t\t\tbool status = process_meta(p_out,name,name_length,sep1,sep1_length,sep2,sep2_length);\r\n\t\t\t\tp_found_flag = status;\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\tdefault:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"meta_test\",infinite))\r\n\t{\r\n\t\tt_size n, count = p_params->get_param_count();\r\n\t\tif (count == 0) return false;\r\n\t\tbool found_all = true;\r\n\t\tfor(n=0;n<count;n++)\r\n\t\t{\r\n\t\t\tconst char * name;\r\n\t\t\tt_size name_length;\r\n\t\t\tp_params->get_param(n,name,name_length);\r\n\t\t\tif (!m_info->meta_exists_ex(name,name_length))\r\n\t\t\t{\r\n\t\t\t\tfound_all = false;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (found_all)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tp_out->write_int(titleformat_inputtypes::meta,1);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"meta_num\",infinite))\r\n\t{\r\n\t\tif (p_params->get_param_count() != 1) return false;\r\n\t\tconst char * name;\r\n\t\tt_size name_length;\r\n\t\tp_params->get_param(0,name,name_length);\r\n\t\tt_size count = m_info->meta_get_count_by_name_ex(name,name_length);\r\n\t\tp_out->write_int(titleformat_inputtypes::meta,count);\r\n\t\tif (count > 0) p_found_flag = true;\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"info\",infinite))\r\n\t{\r\n\t\tif (p_params->get_param_count() != 1) return false;\r\n\t\tconst char * name;\r\n\t\tt_size name_length;\r\n\t\tp_params->get_param(0,name,name_length);\r\n\t\tconst char * value = m_info->info_get_ex(name,name_length);\r\n\t\tif (value != 0)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,value);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"extra\",infinite))\r\n\t{\r\n\t\tif (p_params->get_param_count() != 1) return false;\r\n\t\tconst char * name;\r\n\t\tt_size name_length;\r\n\t\tp_params->get_param(0,name,name_length);\r\n\t\tif (process_extra(p_out,name,name_length)) p_found_flag = true;\r\n\t\treturn true;\r\n\t} else if (!stricmp_utf8_ex(p_name,p_name_length,\"codec\",infinite))\r\n\t{\r\n\t\tif (p_params->get_param_count() != 0) return false;\r\n\t\tprocess_codec(p_out);\r\n\t\tp_found_flag = true;\r\n\t\treturn true;\t\t\r\n\t} else if (!stricmp_utf8_ex(p_name,p_name_length,\"channels\",infinite))\r\n\t{\r\n\t\tif (p_params->get_param_count() != 0) return false;\r\n\t\tunsigned val = (unsigned)m_info->info_get_int(\"channels\");\r\n\t\tswitch(val)\r\n\t\t{\r\n\t\tcase 0: p_out->write(titleformat_inputtypes::meta,\"N/A\",infinite); break;\r\n\t\tcase 1: p_out->write(titleformat_inputtypes::meta,\"mono\",infinite); p_found_flag = true; break;\r\n\t\tcase 2: p_out->write(titleformat_inputtypes::meta,\"stereo\",infinite); p_found_flag = true; break;\r\n\t\tdefault: p_out->write_int(titleformat_inputtypes::meta,val); p_out->write(titleformat_inputtypes::meta,\"ch\",infinite); p_found_flag = true; break;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"tracknumber\",infinite))\r\n\t{\r\n\t\tt_size pad = 2;\r\n\t\tt_size param_count = p_params->get_param_count();\r\n\t\tif (param_count > 1) return false;\r\n\t\tif (param_count == 1) pad = (t_size)p_params->get_param_uint(0);\r\n\t\tconst char * val = m_info->meta_get_ex(\"tracknumber\",infinite,0);\r\n\t\tif (val != 0)\r\n\t\t{\r\n\t\t\tp_found_flag = true;\r\n\t\t\tt_size val_len = strlen(val);\r\n\t\t\tif (val_len < pad)\r\n\t\t\t{\r\n\t\t\t\tt_size n = pad - val_len;\r\n\t\t\t\tdo {\r\n\t\t\t\t\tp_out->write(titleformat_inputtypes::meta,\"0\",1);\r\n\t\t\t\t\tn--;\r\n\t\t\t\t} while(n > 0);\r\n\t\t\t}\r\n\t\t\tp_out->write(titleformat_inputtypes::meta,val,infinite);\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::process_meta(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,const char * p_sep1,t_size p_sep1_length,const char * p_sep2,t_size p_sep2_length)\r\n{\r\n\tt_size index = m_info->meta_find_ex(p_name,p_name_length);\r\n\treturn process_meta(p_out, index, p_sep1, p_sep1_length, p_sep2, p_sep2_length);\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::process_meta(titleformat_text_out * p_out,t_size p_index,const char * p_sep1,t_size p_sep1_length,const char * p_sep2,t_size p_sep2_length)\r\n{\r\n\tif (p_index == infinite) return false;\r\n\r\n\tt_size n, m = m_info->meta_enum_value_count(p_index);\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tif (n>0)\r\n\t\t{\r\n\t\t\tif (n+1 == m) p_out->write(titleformat_inputtypes::meta,p_sep2,p_sep2_length);\r\n\t\t\telse p_out->write(titleformat_inputtypes::meta,p_sep1,p_sep1_length);\r\n\t\t}\t\t\t\r\n\t\tp_out->write(titleformat_inputtypes::meta,m_info->meta_enum_value(p_index,n),infinite);\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool titleformat_hook_impl_file_info::process_extra(titleformat_text_out * p_out,const char * p_name,t_size p_name_length)\r\n{\r\n\tif (!stricmp_utf8_ex(p_name,p_name_length,\"PATH_RAW\",infinite))\r\n\t{\r\n\t\tp_out->write(titleformat_inputtypes::unknown,m_location.get_path(),infinite);\r\n\t\treturn true;\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"FOOBAR2000_VERSION\",infinite))\r\n\t{\r\n\t\tp_out->write(titleformat_inputtypes::unknown,core_version_info::g_get_version_string(),infinite);\r\n\t\treturn true;\r\n\t}\r\n\telse return false;\r\n}\r\n\r\nvoid titleformat_object::run_hook(const playable_location & p_location,const file_info * p_source,titleformat_hook * p_hook,pfc::string_base & p_out,titleformat_text_filter * p_filter)\r\n{\r\n\tif (p_hook)\r\n\t{\r\n\t\trun(\r\n\t\t\t&titleformat_hook_impl_splitter(\r\n\t\t\t&titleformat_hook_impl_file_info(p_location,p_source),\r\n\t\t\tp_hook),\r\n\t\t\tp_out,p_filter);\r\n\t}\r\n\telse\r\n\t{\r\n\t\trun(\r\n\t\t\t&titleformat_hook_impl_file_info(p_location,p_source),\r\n\t\t\tp_out,p_filter);\r\n\t}\r\n}\r\n\r\nvoid titleformat_object::run_simple(const playable_location & p_location,const file_info * p_source,pfc::string_base & p_out)\r\n{\r\n\trun(&titleformat_hook_impl_file_info(p_location,p_source),p_out,NULL);\r\n}\r\n\r\nt_size titleformat_hook_function_params::get_param_uint(t_size index)\r\n{\r\n\tconst char * str;\r\n\tt_size str_len;\r\n\tget_param(index,str,str_len);\r\n\treturn pfc::atoui_ex(str,str_len);\r\n}\r\n\r\n\r\nvoid titleformat_text_out_impl_filter_chars::write(const GUID & p_inputtype,const char * p_data,t_size p_data_length)\r\n{\r\n\ttitleformat_compiler::remove_forbidden_chars(m_chain,p_inputtype,p_data,p_data_length,m_restricted_chars);\r\n}\r\n\r\nbool titleformat_hook_impl_splitter::process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag)\r\n{\r\n\tp_found_flag = false;\r\n\tif (m_hook1 && m_hook1->process_field(p_out,p_name,p_name_length,p_found_flag)) return true;\r\n\tp_found_flag = false;\r\n\tif (m_hook2 && m_hook2->process_field(p_out,p_name,p_name_length,p_found_flag)) return true;\r\n\tp_found_flag = false;\r\n\treturn false;\r\n}\r\n\r\nbool titleformat_hook_impl_splitter::process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag)\r\n{\r\n\tp_found_flag = false;\r\n\tif (m_hook1 && m_hook1->process_function(p_out,p_name,p_name_length,p_params,p_found_flag)) return true;\r\n\tp_found_flag = false;\r\n\tif (m_hook2 && m_hook2->process_function(p_out,p_name,p_name_length,p_params,p_found_flag)) return true;\r\n\tp_found_flag = false;\r\n\treturn false;\r\n}\r\n\r\nvoid titleformat_text_out::write_int_padded(const GUID & p_inputtype,t_int64 val,t_int64 maxval)\r\n{\r\n\tconst t_size bufsize = 64;\r\n\tchar temp[bufsize+1];\r\n\tt_size len = 0;\r\n\twhile(maxval) {maxval/=10;len++;}\r\n\tif (len == 0) len = 1;\r\n\tt_size n;\r\n\tfor(n=0;n<bufsize;n++) temp[n] = '0';\r\n\ttemp[n] = 0;\r\n\t_i64toa(val,temp+bufsize/2,10);\r\n\twrite(p_inputtype,temp + strlen(temp) - len,infinite);\r\n}\r\n\r\nvoid titleformat_text_out::write_int(const GUID & p_inputtype,t_int64 val)\r\n{\r\n\twrite(p_inputtype,pfc::format_int(val));\r\n}\r\nvoid titleformat_text_filter_impl_reserved_chars::write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length)\r\n{\r\n\tif (p_inputtype == titleformat_inputtypes::meta) titleformat_compiler::remove_forbidden_chars_string_append(p_out,p_data,p_data_length,m_reserved_chars);\r\n\telse p_out.add_string(p_data,p_data_length);\r\n}\r\n\r\nvoid titleformat_compiler::run(titleformat_hook * p_source,pfc::string_base & p_out,const char * p_spec)\r\n{\r\n\tservice_ptr_t<titleformat_object> ptr;\r\n\tif (!compile(ptr,p_spec)) p_out = \"[COMPILATION ERROR]\";\r\n\telse ptr->run(p_source,p_out,NULL);\r\n}\r\n\r\nvoid titleformat_compiler::compile_safe(service_ptr_t<titleformat_object> & p_out,const char * p_spec)\r\n{\r\n\tif (!compile(p_out,p_spec)) {\r\n\t\tif (!compile(p_out,\"%filename%\"))\r\n\t\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\n\r\nnamespace titleformat_inputtypes {\r\n\tconst GUID meta = { 0xcd839c8e, 0x5c66, 0x4ae1, { 0x8d, 0xad, 0x71, 0x1f, 0x86, 0x0, 0xa, 0xe3 } };\r\n\tconst GUID unknown = { 0x673aa1cd, 0xa7a8, 0x40c8, { 0xbf, 0x9b, 0x34, 0x37, 0x99, 0x29, 0x16, 0x3b } };\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/titleformat.h",
    "content": "#ifndef _FOOBAR2000_TITLEFORMAT_H_\r\n#define _FOOBAR2000_TITLEFORMAT_H_\r\n\r\nnamespace titleformat_inputtypes {\r\n\textern const GUID meta, unknown;\r\n};\r\n\r\nclass NOVTABLE titleformat_text_out {\r\npublic:\r\n\tvirtual void write(const GUID & p_inputtype,const char * p_data,t_size p_data_length = infinite) = 0;\r\n\tvoid write_int(const GUID & p_inputtype,t_int64 val);\r\n\tvoid write_int_padded(const GUID & p_inputtype,t_int64 val,t_int64 maxval);\r\nprotected:\r\n\ttitleformat_text_out() {}\r\n\t~titleformat_text_out() {}\r\n};\r\n\r\n\r\nclass NOVTABLE titleformat_text_filter {\r\npublic:\r\n\tvirtual void write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length) = 0;\r\nprotected:\r\n\ttitleformat_text_filter() {}\r\n\t~titleformat_text_filter() {}\r\n};\r\n\r\nclass NOVTABLE titleformat_hook_function_params\r\n{\r\npublic:\r\n\tvirtual t_size get_param_count() = 0;\r\n\tvirtual void get_param(t_size index,const char * & p_string,t_size & p_string_len) = 0;//warning: not a null-terminated string\r\n\t\r\n\t//helper\r\n\tt_size get_param_uint(t_size index);\r\n};\r\n\r\nclass NOVTABLE titleformat_hook\r\n{\r\npublic:\r\n\tvirtual bool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) = 0;\r\n\tvirtual bool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) = 0;\r\n};\r\n//! Represents precompiled executable title-formatting script. Use titleformat_compiler to instantiate; do not reimplement.\r\nclass NOVTABLE titleformat_object : public service_base\r\n{\r\npublic:\r\n\tvirtual void run(titleformat_hook * p_source,pfc::string_base & p_out,titleformat_text_filter * p_filter)=0;\r\n\r\n\tvoid run_hook(const playable_location & p_location,const file_info * p_source,titleformat_hook * p_hook,pfc::string_base & p_out,titleformat_text_filter * p_filter);\r\n\tvoid run_simple(const playable_location & p_location,const file_info * p_source,pfc::string_base & p_out);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(titleformat_object,service_base);\r\n};\r\n\r\n//! Standard service for instantiating titleformat_object. Implemented by the core; do not reimplement.\r\n//! To instantiate, use static_api_ptr_t<titleformat_compiler>.\r\nclass NOVTABLE titleformat_compiler : public service_base\r\n{\r\npublic:\r\n\t//! Returns false in case of a compilation error.\r\n\tvirtual bool compile(service_ptr_t<titleformat_object> & p_out,const char * p_spec) = 0;\r\n\t//! Helper;\r\n\tvoid run(titleformat_hook * p_source,pfc::string_base & p_out,const char * p_spec);\r\n\t//! Should never fail, falls back to %filename% in case of failure.\r\n\tvoid compile_safe(service_ptr_t<titleformat_object> & p_out,const char * p_spec);\r\n\r\n\t//! Throws bug check when script can't be compiled. For use with hardcoded scripts only.\r\n\tvoid compile_force(service_ptr_t<titleformat_object> & p_out,const char * p_spec) {if (!compile(p_out,p_spec)) throw pfc::exception_bug_check();}\r\n\r\n\r\n\tstatic void remove_color_marks(const char * src,pfc::string_base & out);//helper\r\n\tstatic void remove_forbidden_chars(titleformat_text_out * p_out,const GUID & p_inputtype,const char * p_source,t_size p_source_len,const char * p_forbidden_chars);\r\n\tstatic void remove_forbidden_chars_string_append(pfc::string_receiver & p_out,const char * p_source,t_size p_source_len,const char * p_forbidden_chars);\r\n\tstatic void remove_forbidden_chars_string(pfc::string_base & p_out,const char * p_source,t_size p_source_len,const char * p_forbidden_chars);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(titleformat_compiler);\r\n};\r\n\r\n\r\nclass titleformat_object_wrapper {\r\npublic:\r\n\ttitleformat_object_wrapper(const char * p_script) {\r\n\t\tstatic_api_ptr_t<titleformat_compiler>()->compile_force(m_script,p_script);\r\n\t}\r\n\r\n\toperator const service_ptr_t<titleformat_object> &() const {return m_script;}\r\n\t\r\nprivate:\r\n\tservice_ptr_t<titleformat_object> m_script;\r\n};\r\n\r\n\r\n//helpers\r\n\r\n\r\nclass titleformat_text_out_impl_filter_chars : public titleformat_text_out\r\n{\r\npublic:\r\n\tinline titleformat_text_out_impl_filter_chars(titleformat_text_out * p_chain,const char * p_restricted_chars)\r\n\t\t: m_chain(p_chain), m_restricted_chars(p_restricted_chars) {}\r\n\tvoid write(const GUID & p_inputtype,const char * p_data,t_size p_data_length);\r\nprivate:\r\n\ttitleformat_text_out * m_chain;\r\n\tconst char * m_restricted_chars;\r\n};\r\n\r\nclass titleformat_text_out_impl_string : public titleformat_text_out {\r\npublic:\r\n\ttitleformat_text_out_impl_string(pfc::string_receiver & p_string) : m_string(p_string) {}\r\n\tvoid write(const GUID & p_inputtype,const char * p_data,t_size p_data_length) {m_string.add_string(p_data,p_data_length);}\r\nprivate:\r\n\tpfc::string_receiver & m_string;\r\n};\r\n\r\nclass titleformat_hook_impl_file_info : public titleformat_hook\r\n{\r\npublic:\r\n\ttitleformat_hook_impl_file_info(const playable_location & p_location,const file_info * p_info) : m_location(p_location), m_info(p_info) {}//caller must ensure that referenced file_info object is alive as long as the titleformat_hook_impl_file_info instance\r\n\tbool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag);\r\n\tbool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag);\r\nprotected:\r\n\tbool process_meta(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,const char * p_sep1,t_size p_sep1_length,const char * p_sep2,t_size p_sep2_length);\r\n\tbool process_meta(titleformat_text_out * p_out,t_size p_index,const char * p_sep1,t_size p_sep1_length,const char * p_sep2,t_size p_sep2_length);\r\n\tbool process_extra(titleformat_text_out * p_out,const char * p_name,t_size p_name_length);\r\n\tbool remap_meta(t_size & p_index, const char * p_name, t_size p_name_length);\r\n\tconst file_info * m_info;\r\nprivate:\r\n\tvoid process_codec(titleformat_text_out * p_out);\r\n\tconst playable_location & m_location;\r\n};\r\n\r\nclass titleformat_hook_impl_splitter : public titleformat_hook {\r\npublic:\r\n\tinline titleformat_hook_impl_splitter(titleformat_hook * p_hook1,titleformat_hook * p_hook2) : m_hook1(p_hook1), m_hook2(p_hook2) {}\r\n\tbool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag);\r\n\tbool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag);\r\nprivate:\r\n\ttitleformat_hook * m_hook1, * m_hook2;\r\n};\r\n\r\nclass titleformat_text_filter_impl_reserved_chars : public titleformat_text_filter {\r\npublic:\r\n\ttitleformat_text_filter_impl_reserved_chars(const char * p_reserved_chars) : m_reserved_chars(p_reserved_chars) {}\r\n\tvirtual void write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length);\r\nprivate:\r\n\tconst char * m_reserved_chars;\r\n};\r\n\r\n#endif //_FOOBAR2000_TITLEFORMAT_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/titleformat_config.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\n\r\n//void on_change(const char * p_name,const char * p_value,unsigned p_value_length) ;\r\n\r\nvoid titleformat_config_callback::g_on_change(const GUID & p_guid,const char * p_name,const char * p_value,t_size p_value_length)\r\n{\r\n\tservice_ptr_t<titleformat_config_callback> ptr;\r\n\tservice_enum_t<titleformat_config_callback> e;\r\n\twhile(e.next(ptr))\r\n\t\tptr->on_change(p_guid,p_name,p_value,p_value_length);\r\n}\r\n\r\nconst char * titleformat_config_impl::get_name()\r\n{\r\n\treturn m_name;\r\n}\r\n\r\n\r\nvoid titleformat_config_impl::get_data(pfc::string_base & p_out)\r\n{\r\n\tinsync(m_sync);\r\n\tp_out = m_value;\r\n}\r\n\r\n\r\nvoid titleformat_config_impl::set_data(const char * p_string,unsigned p_string_length)\r\n{\r\n\tcore_api::ensure_main_thread();\r\n\t{\r\n\t\tinsync(m_sync);\r\n\t\tm_value.set_string(p_string,p_string_length);\r\n\t\tm_compilation_failed = false;\r\n\t\tm_instance.release();\r\n\t}\r\n\ttitleformat_config_callback::g_on_change(m_guid,m_name,p_string,p_string_length);\r\n}\r\n\r\nbool titleformat_config_impl::compile(service_ptr_t<titleformat_object> & p_out)\r\n{\r\n\tinsync(m_sync);\r\n\tif (m_instance.is_empty())\r\n\t{\r\n\t\tif (m_compilation_failed) return false;\r\n\t\tif (!static_api_ptr_t<titleformat_compiler>()->compile(m_instance,m_value))\r\n\t\t{\r\n\t\t\tm_compilation_failed = true;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tp_out = m_instance;\r\n\treturn true;\r\n}\r\n\r\nvoid titleformat_config_impl::reset()\r\n{\r\n\tset_data(m_value_default,infinite);\r\n}\r\n\r\n\r\nvoid titleformat_config_impl::get_data_raw(stream_writer * p_stream,abort_callback & p_abort)\r\n{\r\n\tp_stream->write_string_raw(m_value,p_abort);\r\n}\r\n\r\nvoid titleformat_config_impl::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort)\r\n{\r\n\tpfc::string8_fastalloc temp;\r\n\tp_stream->read_string_raw(temp,p_abort);\r\n\tm_instance.release();\r\n\tm_compilation_failed = false;\r\n\tm_value = temp;\r\n}\r\n\r\ntitleformat_config_impl::titleformat_config_impl(const GUID & p_guid,const char * p_name,const char * p_initvalue,double p_order) :\r\ncfg_var(p_guid),  m_guid(p_guid), m_name(p_name), m_value(p_initvalue), m_value_default(p_initvalue), m_compilation_failed(false), m_order(p_order) {}\r\n\r\n\r\nGUID titleformat_config_impl::get_guid() {return m_guid;}\r\n\r\n\r\nbool titleformat_config::g_find(const GUID & p_guid,service_ptr_t<titleformat_config> & p_out)\r\n{\r\n\tservice_ptr_t<titleformat_config> ptr;\r\n\tservice_enum_t<titleformat_config> e;\r\n\twhile(e.next(ptr))\r\n\t{\r\n\t\tif (ptr->get_guid() == p_guid)\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool titleformat_config::g_compile(const GUID & p_guid,service_ptr_t<titleformat_object> & p_out)\r\n{\r\n\tservice_ptr_t<titleformat_config> ptr;\r\n\tif (!g_find(p_guid,ptr)) return false;\r\n\treturn ptr->compile(p_out);\r\n}\r\n\r\nbool titleformat_config::g_get_data(const GUID & p_guid,pfc::string_base & p_out)\r\n{\r\n\tservice_ptr_t<titleformat_config> ptr;\r\n\tif (!g_find(p_guid,ptr)) return false;\r\n\tptr->get_data(p_out);\r\n\treturn true;\r\n}\r\n\r\ndouble titleformat_config_impl::get_order_priority() {return m_order;}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/titleformat_config.h",
    "content": "#ifndef _TITLEFORMAT_CONFIG_H_\r\n#define _TITLEFORMAT_CONFIG_H_\r\n\r\n\r\nclass NOVTABLE titleformat_config : public service_base\r\n{\r\npublic:\r\n\tvirtual GUID get_guid() = 0;\r\n\tvirtual const char * get_name() = 0;\r\n\tvirtual void get_data(pfc::string_base & p_out) = 0;\r\n\tvirtual void set_data(const char * p_string,unsigned p_string_length) = 0;\r\n\tvirtual void reset() = 0;\r\n\tvirtual bool compile(service_ptr_t<titleformat_object> & p_out) = 0;\r\n\tvirtual double get_order_priority() = 0;\r\n\r\n\r\n\r\n\tstatic bool g_find(const GUID & p_guid,service_ptr_t<titleformat_config> & p_out);\r\n\tstatic bool g_get_data(const GUID & p_guid,pfc::string_base & p_out);\r\n\tstatic bool g_compile(const GUID & p_guid,service_ptr_t<titleformat_object> & p_out);\r\n\r\n\r\n\tstatic const GUID config_playlist,config_copy,config_statusbar,config_systray,config_windowtitle;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(titleformat_config);\r\n};\r\n\r\nclass titleformat_config_callback : public service_base\r\n{\r\npublic:\r\n\tvirtual void on_change(const GUID & p_guid,const char * p_name,const char * p_value,t_size p_value_length) = 0;\r\n\r\n\tstatic void g_on_change(const GUID & p_guid,const char * p_name,const char * p_value,t_size p_value_length);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(titleformat_config_callback);\r\n};\r\n\r\nclass titleformat_config_impl : public titleformat_config, private cfg_var\r\n{\r\npublic:\r\n\tGUID get_guid();\r\n\tconst char * get_name();\r\n\tvoid get_data(pfc::string_base & p_out);\r\n\tvoid set_data(const char * p_string,unsigned p_string_length);\r\n\tvoid reset();\r\n\tbool compile(service_ptr_t<titleformat_object> & p_out);\r\n\tdouble get_order_priority();\r\n\ttitleformat_config_impl(const GUID &,const char * p_name,const char * p_initvalue,double p_order);\r\nprivate:\r\n\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort);\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort);\r\n\r\n\tpfc::string8 m_name,m_value,m_value_default;\r\n\tservice_ptr_t<titleformat_object> m_instance;\r\n\tbool m_compilation_failed;\r\n\tGUID m_guid;\r\n\tdouble m_order;\r\n\tcritical_section m_sync;\r\n};\r\n\r\ntypedef service_factory_single_transparent_t<titleformat_config_impl> titleformat_config_factory;\r\n\r\n//usage:\r\n//static titleformat_config_factory g_mytitleformatconfig(\"this will show up in titleformat config page\",\"%blah%\");\r\n\r\n#endif //_TITLEFORMAT_CONFIG_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/track_property.h",
    "content": "//! Callback interface for track_property_provider::enumerate_properties().\r\nclass NOVTABLE track_property_callback {\r\npublic:\r\n\t//! Sets a property list entry to display. Called by track_property_provider::enumerate_properties() implementation.\r\n\t//! @param p_group Name of group to put the entry in, case-sensitive. Note that non-standard groups are sorted alphabetically.\r\n\t//! @param p_sortpriority Sort priority of the property inside its group (smaller value means earlier in the list), pass 0 if you don't care (alphabetic order by name used when more than one item has same priority).\r\n\t//! @param p_name Name of the property.\r\n\t//! @param p_value Value of the property.\r\n\tvirtual void set_property(const char * p_group,double p_sortpriority,const char * p_name,const char * p_value) = 0;\r\nprotected:\r\n\t~track_property_callback() {}\r\n};\r\n\r\n//! Service for adding custom entries in \"General Properties\" section of the properties dialog.\r\nclass NOVTABLE track_property_provider : public service_base {\r\npublic:\r\n\t//! Enumerates properties of specified track list.\r\n\t//! @param p_tracks List of tracks to enumerate properties on.\r\n\t//! @param p_out Callback interface receiving enumerated properties.\r\n\tvirtual void enumerate_properties(pfc::list_base_const_t<metadb_handle_ptr> const & p_tracks, track_property_callback & p_out) = 0;\r\n\t//! Returns whether specified tech info filed is processed by our service and should not be displayed among unknown fields.\r\n\t//! @param p_name Name of tech info field being queried.\r\n\t//! @returns True if the field is among fields processed by this track_property_provider implementation and should not be displayed among unknown fields, false otherwise.\r\n\tvirtual bool is_our_tech_info(const char * p_name) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(track_property_provider);\r\n};\r\n\r\ntemplate<typename T>\r\nclass track_property_provider_factory_t : public service_factory_single_t<T> {};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/ui.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nbool ui_drop_item_callback::g_on_drop(interface IDataObject * pDataObject)\r\n{\r\n\tservice_enum_t<ui_drop_item_callback> e;\r\n\tservice_ptr_t<ui_drop_item_callback> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->on_drop(pDataObject)) return true;\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n\r\nbool ui_drop_item_callback::g_is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect)\r\n{\r\n\tservice_enum_t<ui_drop_item_callback> e;\r\n\tservice_ptr_t<ui_drop_item_callback> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->is_accepted_type(pDataObject,p_effect)) return true;\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n\r\nbool user_interface::g_find(service_ptr_t<user_interface> & p_out,const GUID & p_guid)\r\n{\r\n\tservice_enum_t<user_interface> e;\r\n\tservice_ptr_t<user_interface> ptr;\r\n\tif (e.first(ptr)) do {\r\n\t\tif (ptr->get_guid() == p_guid)\r\n\t\t{\r\n\t\t\tp_out = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t} while(e.next(ptr));\r\n\treturn false;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/ui.h",
    "content": "#ifndef _FOOBAR2000_UI_H_\r\n#define _FOOBAR2000_UI_H_\r\n\r\n#include \"service.h\"\r\n\r\n#ifndef _WINDOWS\r\n#error PORTME\r\n#endif\r\n\r\n//! Entrypoint service for user interface modules. Implement when registering an UI module. Do not call existing implementations; only core enumerates / dispatches calls. To control UI behaviors from other components, use ui_control API. \\n\r\n//! Use user_interface_factory_t<> to register, e.g static user_interface_factory_t<myclass> g_myclass_factory;\r\nclass NOVTABLE user_interface : public service_base {\r\npublic:\r\n\t//!HookProc usage: \\n\r\n\t//! in your windowproc, call HookProc first, and if it returns true, return LRESULT value it passed to you\r\n\ttypedef BOOL (WINAPI * HookProc_t)(HWND wnd,UINT msg,WPARAM wp,LPARAM lp,LRESULT * ret);\r\n\r\n\t//! Retrieves name (UTF-8 null-terminated string) of the UI module.\r\n\tvirtual const char * get_name()=0;\r\n\t//! Initializes the UI module - creates the main app window, etc. Failure should be signaled by appropriate exception (std::exception or a derivative).\r\n\tvirtual HWND init(HookProc_t hook)=0;\r\n\t//! Deinitializes the UI module - destroys the main app window, etc.\r\n\tvirtual void shutdown()=0;\r\n\t//! Activates main app window.\r\n\tvirtual void activate()=0;\r\n\t//! Minimizes/hides main app window.\r\n\tvirtual void hide()=0;\r\n\t//! Returns whether main window is visible / not minimized. Used for activate/hide command.\r\n\tvirtual bool is_visible() = 0;\r\n\t//! Retrieves GUID of your implementation, to be stored in configuration file etc.\r\n\tvirtual GUID get_guid() = 0;\r\n\r\n\t//! Overrides statusbar text with specified string. The parameter is a null terminated UTF-8 string. The override is valid until another override_statusbar_text() call or revert_statusbar_text() call.\r\n\tvirtual void override_statusbar_text(const char * p_text) = 0;\r\n\t//! Disables statusbar text override.\r\n\tvirtual void revert_statusbar_text() = 0;\r\n\r\n\t//! Shows now-playing item somehow (e.g. system notification area popup).\r\n\tvirtual void show_now_playing() = 0;\r\n\r\n\tstatic bool g_find(service_ptr_t<user_interface> & p_out,const GUID & p_guid);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(user_interface);\r\n};\r\n\r\ntemplate<typename T>\r\nclass user_interface_factory : public service_factory_single_t<T> {};\r\n\r\n//! Interface class allowing you to override UI statusbar text. There may be multiple callers trying to override statusbar text; backend decides which one succeeds so you will not always get what you want. Statusbar text override is automatically cancelled when the object is released.\\n\r\n//! Use ui_control::override_status_text_create() to instantiate.\r\n//! Implemented by core. Do not reimplement.\r\nclass NOVTABLE ui_status_text_override : public service_base\r\n{\r\npublic:\r\n\t//! Sets statusbar text to specified UTF-8 null-terminated string.\r\n\tvirtual void override_text(const char * p_message) = 0;\r\n\t//! Cancels statusbar text override.\r\n\tvirtual void revert_text() = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE(ui_status_text_override,service_base);\r\n};\r\n\r\n//! Serivce providing various UI-related commands. Implemented by core; do not reimplement.\r\n//! Instantiation: use static_api_ptr_t<ui_control>.\r\nclass NOVTABLE ui_control : public service_base {\r\npublic:\r\n\t//! Returns whether primary UI is visible/unminimized.\r\n\tvirtual bool is_visible()=0;\r\n\t//! Activates/unminimizes main UI.\r\n\tvirtual void activate()=0;\r\n\t//! Hides/minimizese main UI.\r\n\tvirtual void hide()=0;\r\n\t//! Retrieves main GUI icon, to use as window icon etc. Returned handle does not need to be freed.\r\n\tvirtual HICON get_main_icon()=0;\r\n\t//! Loads main GUI icon, version with specified width/height. Returned handle needs to be freed with DestroyIcon when you are done using it.\r\n\tvirtual HICON load_main_icon(unsigned width,unsigned height) = 0;\r\n\r\n\t//! Activates preferences dialog and navigates to specified page. See also: preference_page API.\r\n\tvirtual void show_preferences(const GUID & p_page) = 0;\r\n\r\n\t//! Instantiates ui_status_text_override service, that can be used to display status messages.\r\n\t//! @param p_out receives new ui_status_text_override instance.\r\n\t//! @returns true on success, false on failure (out of memory / no GUI loaded / etc)\r\n\tvirtual bool override_status_text_create(service_ptr_t<ui_status_text_override> & p_out) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_control);\r\n};\r\n\r\n//! Service called from the UI when some object is dropped into the UI. Usable for modifying drag&drop behaviors such as adding custom handlers for object types other than supported media files.\\n\r\n//! Implement where needed; use ui_drop_item_callback_factory_t<> template to register, e.g. static ui_drop_item_callback_factory_t<myclass> g_myclass_factory.\r\nclass NOVTABLE ui_drop_item_callback : public service_base {\r\npublic:\r\n\t//! Called when an object was dropped; returns true if the object was processed and false if not.\r\n\tvirtual bool on_drop(interface IDataObject * pDataObject) = 0;\r\n\t//! Tests whether specified object type is supported by this ui_drop_item_callback implementation. Returns true and sets p_effect when it's supported; returns false otherwise. \\n\r\n\t//! See IDropTarget::DragEnter() documentation for more information about p_effect values.\r\n\tvirtual bool is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect)=0;\r\n\r\n\t//! Static helper, calls all existing implementations appropriately. See on_drop().\r\n\tstatic bool g_on_drop(interface IDataObject * pDataObject);\r\n\t//! Static helper, calls all existing implementations appropriately. See is_accepted_type().\r\n\tstatic bool g_is_accepted_type(interface IDataObject * pDataObject, DWORD * p_effect);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(ui_drop_item_callback);\r\n};\r\n\r\ntemplate<class T>\r\nclass ui_drop_item_callback_factory_t : public service_factory_single_t<T> {};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/unpack.h",
    "content": "#ifndef _UNPACK_H_\r\n#define _UNPACK_H_\r\n\r\n//! Service providing \"unpacker\" functionality - processes \"packed\" file (such as a zip file containing a single media file inside) to allow its contents to be accessed transparently.\\n\r\n//! To access existing unpacker implementations, use unpacker::g_open helper function.\\n\r\n//! To register your own implementation, use unpacker_factory_t template.\r\nclass NOVTABLE unpacker : public service_base {\r\npublic:\r\n\t//! Attempts to open specified file for unpacking, creates interface to virtual file with uncompressed data on success. When examined file doesn't appear to be one of formats supported by this unpacker implementation, throws exception_io_data.\r\n\t//! @param p_out Receives interface to virtual file with uncompressed data on success.\r\n\t//! @param p_source Source file to process.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tvirtual void open(service_ptr_t<file> & p_out,const service_ptr_t<file> & p_source,abort_callback & p_abort) = 0;\r\n\r\n\t//! Static helper querying existing unpacker implementations until one that successfully opens specified file is found. Attempts to open specified file for unpacking, creates interface to virtual file with uncompressed data on success. When examined file doesn't appear to be one of formats supported by registered unpacker implementations, throws exception_io_data.\r\n\t//! @param p_out Receives interface to virtual file with uncompressed data on success.\r\n\t//! @param p_source Source file to process.\r\n\t//! @param p_abort abort_callback object signaling user aborting the operation.\r\n\tstatic void g_open(service_ptr_t<file> & p_out,const service_ptr_t<file> & p_source,abort_callback & p_abort);\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(unpacker);\r\n};\r\n\r\ntemplate<typename t_myclass>\r\nclass unpacker_factory_t : public service_factory_single_t<t_myclass> {};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/utf8api.cpp",
    "content": "#include \"foobar2000.h\"\r\n\r\nHWND uCreateDialog(UINT id,HWND parent,DLGPROC proc,LPARAM param)\r\n{\r\n\treturn CreateDialogParam(core_api::get_my_instance(),MAKEINTRESOURCE(id),parent,proc,param);\r\n}\r\n\r\nint uDialogBox(UINT id,HWND parent,DLGPROC proc,LPARAM param)\r\n{\r\n\treturn (int)DialogBoxParam(core_api::get_my_instance(),MAKEINTRESOURCE(id),parent,proc,param);\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/SDK/vis.h",
    "content": "#ifndef _FOOBAR2000_VIS_H_\r\n#define _FOOBAR2000_VIS_H_\r\n\r\n//! This class provides abstraction for receiving visualisation data. Instances of visualisation_stream being created/released serve as an indication for visualisation backend to process currently played audio data or shut down when there are no visualisation clients active.\\n\r\n//! Use visualisation_manager::create_stream to instantiate.\r\nclass NOVTABLE visualisation_stream : public service_base {\r\npublic:\r\n\t//! Retrieves absolute playback time since last playback start or seek. You typically pass value retrieved by this function - optionally with offset added - to other visualisation_stream methods.\r\n\tvirtual bool get_absolute_time(double & p_value) = 0;\r\n\t\r\n\t//! Retrieves an audio chunk starting at specified offset (see get_absolute_time()), of specified length.\r\n\t//! @returns False when requested timestamp is out of available range, true on success.\r\n\tvirtual bool get_chunk_absolute(audio_chunk & p_chunk,double p_offset,double p_requested_length) = 0;\r\n\t//! Retrieves spectrum for audio data at specified offset (see get_absolute_time()), with specified FFT size.\r\n\t//! @param p_chunk Receives spectrum data. audio_chunk type is used for consistency (since required functionality is identical to provided by audio_chunk), the data is *not* PCM. Returned sample count is equal to half of FFT size; channels and sample rate are as in audio stream the spectrum was generated from.\r\n\t//! @param p_offset Timestamp of spectrum to retrieve. See get_absolute_time().\r\n\t//! @param p_fft_size FFT size to use for spectrum generation. Must be a power of 2.\t\r\n\t//! @returns False when requested timestamp is out of available range, true on success.\r\n\tvirtual bool get_spectrum_absolute(audio_chunk & p_chunk,double p_offset,unsigned p_fft_size) = 0;\r\n\t\r\n\t//! Generates fake audio chunk to display when get_chunk_absolute() fails - e.g. shortly after visualisation_stream creation data for currently played audio might not be available yet.\r\n\t//! Throws std::exception derivatives on failure.\r\n\tvirtual void make_fake_chunk_absolute(audio_chunk & p_chunk,double p_offset,double p_requested_length) = 0;\r\n\t//! Generates fake spectrum to display when get_spectrum_absolute() fails - e.g. shortly after visualisation_stream creation data for currently played audio might not be available yet.\r\n\t//! Throws std::exception derivatives on failure.\r\n\tvirtual void make_fake_spectrum_absolute(audio_chunk & p_chunk,double p_offset,unsigned p_fft_size) = 0;\r\n\r\n\t\r\n\tFB2K_MAKE_SERVICE_INTERFACE(visualisation_stream,service_base);\r\n};\r\n\r\n//! Entrypoint service for visualisation processing; use this to create visualisation_stream objects that can be used to retrieve properties of currently played audio. \\n\r\n//! Implemented by core; do not reimplement.\\n\r\n//! Use static_api_ptr_t to access it, e.g. static_api_ptr_t<visualisation_manager>()->create_stream(mystream,0);\r\nclass NOVTABLE visualisation_manager : public service_base {\r\npublic:\r\n\t//! Creates a visualisation_stream object. See visualisation_stream for more info.\r\n\t//! @param p_out Receives newly created visualisation_stream instance.\r\n\t//! @param p_flags Reserved for future use. Must be set to zero.\r\n\tvirtual void create_stream(service_ptr_t<visualisation_stream> & p_out,unsigned p_flags) = 0;\r\n\r\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT(visualisation_manager);\r\n};\r\n\r\n\r\n#endif //_FOOBAR2000_VIS_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/foo_input_raw/foo_input_raw.cpp",
    "content": "#include \"../SDK/foobar2000.h\"\r\n\r\nenum {\r\n\traw_bits_per_sample = 16,\r\n\traw_channels = 2,\r\n\traw_sample_rate = 44100,\r\n\r\n\traw_bytes_per_sample = raw_bits_per_sample / 8,\r\n\traw_total_sample_width = raw_bytes_per_sample * raw_channels,\r\n};\r\n\r\n// No inheritance. Our methods get called over input framework templates. See input_singletrack_impl for descriptions of what each method does.\r\nclass input_raw {\r\npublic:\r\n\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) {\r\n\t\tif (p_reason == input_open_info_write) throw exception_io_unsupported_format();//our input does not support retagging.\r\n\t\tm_file = p_filehint;//p_filehint may be null, hence next line\r\n\t\tinput_open_file_helper(m_file,p_path,p_reason,p_abort);//if m_file is null, opens file with appropriate privileges for our operation (read/write for writing tags, read-only otherwise).\r\n\t}\r\n\r\n\tvoid get_info(file_info & p_info,abort_callback & p_abort) {\r\n\t\tt_filesize size = m_file->get_size(p_abort);\r\n\t\tif (size != filesize_invalid) {\r\n\t\t\t//file size is known, let's set length\r\n\t\t\tp_info.set_length(audio_math::samples_to_time( size / raw_total_sample_width, raw_sample_rate));\r\n\t\t}\r\n\t\t//note that the values below should be based on contents of the file itself, NOT on user-configurable variables for an example. To report info that changes independently from file contents, use get_dynamic_info/get_dynamic_info_track instead.\r\n\t\tp_info.info_set_int(\"samplerate\",raw_sample_rate);\r\n\t\tp_info.info_set_int(\"channels\",raw_channels);\r\n\t\tp_info.info_set_int(\"bitspersample\",raw_bits_per_sample);\r\n\t\tp_info.info_set(\"encoding\",\"lossless\");\r\n\t\tp_info.info_set_bitrate((raw_bits_per_sample * raw_channels * raw_sample_rate + 500 /* rounding for bps to kbps*/ ) / 1000 /* bps to kbps */);\r\n\t\t\r\n\t}\r\n\tt_filestats get_file_stats(abort_callback & p_abort) {return m_file->get_stats(p_abort);}\r\n\r\n\tvoid decode_initialize(unsigned p_flags,abort_callback & p_abort) {\r\n\t\tm_file->reopen(p_abort);//equivalent to seek to zero, except it also works on nonseekable streams\r\n\t}\r\n\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) {\r\n\t\tenum {\r\n\t\t\tdeltaread = 1024,\r\n\t\t};\r\n\t\tm_buffer.set_size(deltaread * raw_total_sample_width);\r\n\t\tt_size deltaread_done = m_file->read(m_buffer.get_ptr(),deltaread * raw_total_sample_width,p_abort) / raw_total_sample_width;\r\n\t\tif (deltaread_done == 0) return false;//EOF\r\n\r\n\t\tp_chunk.set_data_fixedpoint(m_buffer.get_ptr(),deltaread_done * raw_total_sample_width,raw_sample_rate,raw_channels,raw_bits_per_sample,audio_chunk::g_guess_channel_config(raw_channels));\r\n\t\t\r\n\t\t//processed successfully, no EOF\r\n\t\treturn true;\r\n\t}\r\n\tvoid decode_seek(double p_seconds,abort_callback & p_abort) {\r\n\t\tm_file->ensure_seekable();//throw exceptions if someone called decode_seek() despite of our input having reported itself as nonseekable.\r\n\t\t// IMPORTANT: convert time to sample offset with proper rounding! audio_math::time_to_samples does this properly for you.\r\n\t\tt_filesize target = audio_math::time_to_samples(p_seconds,raw_sample_rate) * raw_total_sample_width;\r\n\t\t\r\n\t\t// get_size_ex fails (throws exceptions) if size is not known (where get_size would return filesize_invalid). Should never fail on seekable streams (if it does it's not our problem anymore).\r\n\t\tt_filesize max = m_file->get_size_ex(p_abort);\r\n\t\tif (target > max) target = max;//clip seek-past-eof attempts to legal range (next decode_run() call will just signal EOF).\r\n\r\n\t\tm_file->seek(target,p_abort);\r\n\t}\r\n\tbool decode_can_seek() {return m_file->can_seek();}\r\n\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {return false;}\r\n\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return false;}\r\n\tvoid decode_on_idle(abort_callback & p_abort) {m_file->on_idle(p_abort);}\r\n\r\n\tvoid retag(const file_info & p_info,abort_callback & p_abort) {throw exception_io_unsupported_format();}\r\n\t\r\n\tstatic bool g_is_our_content_type(const char * p_content_type) {return false;}\r\n\tstatic bool g_is_our_path(const char * p_path,const char * p_extension) {return stricmp_utf8(p_extension,\"raw\") == 0;}\r\npublic:\r\n\tservice_ptr_t<file> m_file;\r\n\tpfc::array_t<t_uint8> m_buffer;\r\n};\r\n\r\nstatic input_singletrack_factory_t<input_raw> g_input_raw_factory;\r\n\r\n\r\nDECLARE_COMPONENT_VERSION(\"RAW input\",\"0.1\",\"about message goes here\");\r\nDECLARE_FILE_TYPE(\"Raw files\",\"*.RAW\");"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/foo_input_raw/readme.txt",
    "content": "Foo_input_raw is a sample component demonstrating implementation of a simple audio input service, use of filesystem APIs and service registration."
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/foo_input_validator/readme.txt",
    "content": "Decoder Validator v1.0 readme\r\n\r\n1) Usage.\r\nSelect a single file handled by the decoder you want to test, select \"Utils / Decoder Validator\" or \"Utils / Tag Writer Validator\" from the context menu.\r\nWARNING: Never run Tag Writer Validator on files you don't have backup copies of. Tag Writer Validator will repeatedly rewrite file's tags, with randomly generated info. In case of success (found problems with relevant tag writer implementations), the file will likely be permanently damaged or left with nonsense in its tags.\r\n\r\n2) What Decoder Validator does.\r\nDecoder Validator runs a series of automated decoding tests on the specified file, and reports any abnormal behaviors detected. It has been proven to be a highly useful tool for spotting certain kinds of bugs (especially inaccurate seeking).\r\nSome of the problems it detects are potentially harmful (such as inaccurate seeking on archiving-oriented audio formats) and are hard to detect or reliably reproduce using other means.\r\nDetected programming errors include:\r\n- Different decoding results when decoding the same file again from start.\r\n- Inaccurate seeking, noncompliant seeking-related behaviors.\r\n- File corruption during tag updates.\r\n- Incorrect/inconsistent behaviors of tag writer instance when asked to reread tags after a tag update.\r\n\r\n3) What Decoder Validator does not do.\r\nDecoder Validator does not:\r\n- Entirely ensure that your code is bug-free.\r\n- Check correctness of your decoder's output - only reference data it uses for comparisons is result of first decode pass, if your decoder consistently returns incorrect results, they won't be reported as incorrect.\r\n- Fully replace user testing cycle.\r\n- Test for exception transparency and abortability - abortability test has been excluded for performance reasons (since it was O(n^2)), you don't need automated tests to know whether your decoder implementation relays exceptions properly or not.\r\n- Test for unicode support in tag writers.\r\n- Test whether output of your tag writer is correct, only whether your own tag reader implementation reads it back and reports the same info as what it was asked to write.\r\n- Test freeform metadata handling - tag writing test is restricted to specific hardcoded fields filled with random data.\r\n\r\n4) But one of official components fails Decoder Validator tests!\r\nThis might occur because:\r\n- Limitations of file format being tested break certain features.\r\n- Bugs in third party libraries we have no power over (WMA)\r\n- You have found a bug.\r\n- The file you are trying to decode is corrupted and prevents decoder from returning results that the Validator would accept.\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/foobar2000_component_client/component_client.cpp",
    "content": "#include \"../SDK/foobar2000.h\"\r\n#include \"../SDK/component.h\"\r\n\r\nstatic HINSTANCE g_hIns;\r\n\r\nstatic pfc::string_simple g_name,g_full_path;\r\n\r\nstatic bool g_services_available = false, g_initialized = false;\r\n\r\n\r\n\r\nnamespace core_api\r\n{\r\n\r\n\tHINSTANCE get_my_instance()\r\n\t{\r\n\t\treturn g_hIns;\r\n\t}\r\n\r\n\tHWND get_main_window()\r\n\t{\r\n\t\treturn g_api->get_main_window();\r\n\t}\r\n\tpcchar get_my_file_name()\r\n\t{\r\n\t\treturn g_name;\r\n\t}\r\n\r\n\tpcchar get_my_full_path()\r\n\t{\r\n\t\treturn g_full_path;\r\n\t}\r\n\r\n\tbool are_services_available()\r\n\t{\r\n\t\treturn g_services_available;\r\n\t}\r\n\tbool assert_main_thread()\r\n\t{\r\n\t\treturn (g_services_available && g_api) ? g_api->assert_main_thread() : true;\r\n\t}\r\n\r\n\tvoid ensure_main_thread() {\r\n\t\tif (!assert_main_thread()) throw exception_wrong_thread();\r\n\t}\r\n\r\n\tbool is_main_thread()\r\n\t{\r\n\t\treturn (g_services_available && g_api) ? g_api->is_main_thread() : true;\r\n\t}\r\n\tpcchar get_profile_path()\r\n\t{\r\n\t\treturn (g_services_available && g_api) ? g_api->get_profile_path() : 0;\r\n\t}\r\n\r\n\tbool is_shutting_down()\r\n\t{\r\n\t\treturn (g_services_available && g_api) ? g_api->is_shutting_down() : g_initialized;\r\n\t}\r\n\tbool is_initializing()\r\n\t{\r\n\t\treturn (g_services_available && g_api) ? g_api->is_initializing() : !g_initialized;\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\tclass foobar2000_client_impl : public foobar2000_client\r\n\t{\r\n\tpublic:\r\n\t\tt_uint32 get_version() {return FOOBAR2000_CLIENT_VERSION;}\r\n\t\tpservice_factory_base get_service_list() {return service_factory_base::__internal__list;}\r\n\r\n\t\tvoid get_config(stream_writer * p_stream,abort_callback & p_abort) {\r\n\t\t\tcfg_var::config_write_file(p_stream,p_abort);\r\n\t\t}\r\n\r\n\t\tvoid set_config(stream_reader * p_stream,abort_callback & p_abort) {\r\n\t\t\tcfg_var::config_read_file(p_stream,p_abort);\r\n\t\t}\r\n\r\n\t\tvoid set_library_path(const char * path,const char * name) {\r\n\t\t\tg_full_path = path;\r\n\t\t\tg_name = name;\r\n\t\t}\r\n\r\n\t\tvoid services_init(bool val) {\r\n\t\t\tif (val) g_initialized = true;\r\n\t\t\tg_services_available = val;\r\n\t\t}\r\n\r\n\t\tbool is_debug() {\r\n#ifdef _DEBUG\r\n\t\t\treturn true;\r\n#else\r\n\t\t\treturn false;\r\n#endif\r\n\t\t}\r\n\t};\r\n}\r\n\r\nstatic foobar2000_client_impl g_client;\r\n\r\nextern \"C\"\r\n{\r\n\t__declspec(dllexport) foobar2000_client * _cdecl foobar2000_get_interface(foobar2000_api * p_api,HINSTANCE hIns)\r\n\t{\r\n\t\tg_hIns = hIns;\r\n\t\tg_api = p_api;\r\n\r\n\t\treturn &g_client;\r\n\t}\r\n}\r\n\r\n#if 0\r\nBOOLEAN WINAPI DllMain(IN HINSTANCE hDllHandle, IN DWORD     nReason,  IN LPVOID  Reserved )\r\n{\r\n    BOOLEAN bSuccess = TRUE;\r\n\r\n    switch ( nReason ) {\r\n        case DLL_PROCESS_ATTACH:\r\n\r\n            DisableThreadLibraryCalls( hDllHandle );\r\n\r\n            break;\r\n\r\n        case DLL_PROCESS_DETACH:\r\n\r\n            break;\r\n    }\r\n\treturn TRUE;\r\n}\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/StdAfx.cpp",
    "content": "// stdafx.cpp : source file that includes just the standard includes\r\n//\tfoobar2000_sdk_helpers.pch will be the pre-compiled header\r\n//\tstdafx.obj will contain the pre-compiled type information\r\n\r\n#include \"stdafx.h\"\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/StdAfx.h",
    "content": "// stdafx.h : include file for standard system include files,\r\n//  or project specific include files that are used frequently, but\r\n//      are changed infrequently\r\n//\r\n\r\n#if !defined(AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_)\r\n#define AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n\r\n#include \"../SDK/foobar2000.h\"\r\n#include \"helpers.h\"\r\n\r\n// TODO: reference additional headers your program requires here\r\n\r\n//{{AFX_INSERT_LOCATION}}\r\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\r\n\r\n#endif // !defined(AFX_STDAFX_H__6356EC2B_6DD1_4BE8_935C_87ECBA8697E4__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/bitreader_helper.h",
    "content": "namespace bitreader_helper {\r\n\r\n\tinline static size_t extract_bit(const t_uint8 * p_stream,size_t p_offset) {\r\n\t\treturn (p_stream[p_offset>>3] >> (7-(p_offset&7)))&1;\r\n\t}\r\n\r\n\tstatic size_t extract_int(const t_uint8 * p_stream,size_t p_base,size_t p_width) {\r\n\t\tsize_t ret = 0;\r\n\t\tsize_t offset = p_base;\r\n\t\tfor(size_t bit=0;bit<p_width;bit++) {\r\n\t\t\tret <<= 1;\r\n\t\t\tret |= extract_bit(p_stream,offset++);\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\nclass bitreader\r\n{\r\npublic:\r\n\tinline bitreader(const t_uint8 * p_ptr,t_size p_base)\r\n\t\t: m_ptr(p_ptr), m_bitptr(p_base)\r\n\t{\r\n\t}\r\n\r\n\tinline void skip(t_size p_bits)\r\n\t{\r\n\t\tm_bitptr += p_bits;\r\n\t}\r\n\r\n\ttemplate<typename t_ret>\r\n\tt_ret read_t(t_size p_bits) {\r\n\t\tt_ret ret = 0;\r\n\t\tfor(t_size bit=0;bit<p_bits;bit++)\r\n\t\t{\r\n\t\t\tret <<= 1;\r\n\t\t\tret |= (m_ptr[m_bitptr>>3] >> (7-(m_bitptr&7)))&1;\r\n\t\t\tm_bitptr++;\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tt_size read(t_size p_bits) {return read_t<t_size>(p_bits);}\r\n\r\n\tinline t_size get_bitptr() const {return m_bitptr;}\r\n\r\n\tinline bool read_bit() {\r\n\t\tbool state = ( (m_ptr[m_bitptr>>3] >> (7-(m_bitptr&7)))&1 ) != 0;\r\n\t\tm_bitptr++;\r\n\t\treturn state;\r\n\t}\r\n\r\nprivate:\r\n\r\n\tconst t_uint8 * m_ptr;\r\n\tt_size m_bitptr;\r\n};\r\n\r\nclass bitreader_fromfile\r\n{\r\npublic:\r\n\tinline bitreader_fromfile(service_ptr_t<file> const& p_file) : m_file(p_file), m_buffer_ptr(0) {}\r\n\t\r\n\tt_size read(t_size p_bits,abort_callback & p_abort) {\r\n\t\tt_size ret = 0;\r\n\t\tfor(t_size bit=0;bit<p_bits;bit++) {\r\n\t\t\tif (m_buffer_ptr == 0)\r\n\t\t\t\tm_file->read_object(&m_buffer,1,p_abort);\r\n\r\n\t\t\tret <<= 1;\r\n\t\t\tret |= (m_buffer >> (7-m_buffer_ptr))&1;\r\n\t\t\tm_buffer_ptr = (m_buffer_ptr+1) & 7;\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tvoid skip(t_size p_bits,abort_callback & p_abort) {\r\n\t\tfor(t_size bit=0;bit<p_bits;bit++) {\r\n\t\t\tif (m_buffer_ptr == 0) m_file->read_object(&m_buffer,1,p_abort);\r\n\t\t\tm_buffer_ptr = (m_buffer_ptr+1) & 7;\r\n\t\t}\r\n\t}\r\n\r\n\tinline void byte_align() {m_buffer_ptr = 0;}\r\n\r\nprivate:\r\n\tservice_ptr_t<file> m_file;\r\n\tt_size m_buffer_ptr;\r\n\tt_uint8 m_buffer;\r\n};\r\n\r\nclass bitreader_limited\r\n{\r\npublic:\r\n\tinline bitreader_limited(const t_uint8 * p_ptr,t_size p_base,t_size p_remaining) : m_reader(p_ptr,p_base), m_remaining(p_remaining) {}\r\n\r\n\tinline t_size get_bitptr() const {return m_reader.get_bitptr();}\r\n\r\n\tinline t_size get_remaining() const {return m_remaining;}\r\n\r\n\tinline void skip(t_size p_bits) {\r\n\t\tif (p_bits > m_remaining) throw exception_io_data_truncation();\r\n\t\tm_remaining -= p_bits;\r\n\t\tm_reader.skip(p_bits);\r\n\t}\r\n\r\n\tt_size read(t_size p_bits)\r\n\t{\r\n\t\tif (p_bits > m_remaining) throw exception_io_data_truncation();\r\n\t\tm_remaining -= p_bits;\r\n\t\treturn m_reader.read(p_bits);\r\n\t}\r\n\r\nprivate:\r\n\tbitreader m_reader;\r\n\tt_size m_remaining;\r\n};\r\n\r\ninline static t_size extract_bits(const t_uint8 * p_buffer,t_size p_base,t_size p_count) {\r\n\treturn bitreader(p_buffer,p_base).read(p_count);\r\n}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cfg_guidlist.h",
    "content": "class cfg_guidlist : public cfg_var, public pfc::list_t<GUID>\r\n{\r\npublic:\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\t\tt_uint32 n, m = pfc::downcast_guarded<t_uint32>(get_count());\r\n\t\tp_stream->write_lendian_t(m,p_abort);\r\n\t\tfor(n=0;n<m;n++) p_stream->write_lendian_t(get_item(n),p_abort);\r\n\t}\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\t\tt_uint32 n,count;\r\n\t\tp_stream->read_lendian_t(count,p_abort);\r\n\t\tm_buffer.set_size(count);\r\n\t\tfor(n=0;n<count;n++) {\r\n\t\t\ttry {\r\n\t\t\t\tp_stream->read_lendian_t(m_buffer[n],p_abort);\r\n\t\t\t} catch(...) {m_buffer.set_size(0); throw;}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid sort() {sort_t(pfc::guid_compare);}\r\n\r\n\tbool have_item_bsearch(const GUID & p_item) {\r\n\t\tt_size dummy;\r\n\t\treturn bsearch_t(pfc::guid_compare,p_item,dummy);\r\n\t}\r\n\r\npublic:\r\n\tcfg_guidlist(const GUID & p_guid) : cfg_var(p_guid) {}\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cfg_structlist.h",
    "content": "template<typename T>\r\nclass cfg_structlist_t : public cfg_var, public pfc::list_t<T>\r\n{\r\npublic:\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\t\tt_uint32 n, m = get_count();\r\n\t\tp_stream->write_lendian_t(m,p_abort);\r\n\t\tfor(n=0;n<m;n++) {\r\n\t\t\tp_stream->write_object(&m_buffer[n],sizeof(T),p_abort);\r\n\t\t}\r\n\t}\r\n\t\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size,abort_callback & p_abort) {\r\n\t\tt_uint32 n,count;\r\n\t\tp_stream->read_lendian_t(count,p_abort);\r\n\t\tm_buffer.set_size_e(count);\r\n\t\tfor(n=0;n<count;n++) {\r\n\t\t\ttry {\r\n\t\t\t\tp_stream->read_object(&m_buffer[n],sizeof(T),p_abort);\r\n\t\t\t} catch(...) {m_buffer.set_size(0); throw;}\r\n\t\t}\r\n\t}\r\npublic:\r\n\tcfg_structlist_t(const GUID & p_guid) : cfg_var(p_guid) {}\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/create_directory_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"create_directory_helper.h\"\r\n\r\nnamespace create_directory_helper\r\n{\r\n\tstatic void create_path_internal(const char * p_path,t_size p_base,abort_callback & p_abort) {\r\n\t\tpfc::string8_fastalloc temp;\r\n\t\tfor(t_size walk = p_base; p_path[walk]; walk++) {\r\n\t\t\tif (p_path[walk] == '\\\\') {\r\n\t\t\t\ttemp.set_string(p_path,walk);\r\n\t\t\t\ttry {filesystem::g_create_directory(temp.get_ptr(),p_abort);} catch(exception_io_already_exists) {}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tstatic bool is_valid_netpath_char(char p_char) {\r\n\t\treturn pfc::char_is_ascii_alphanumeric(p_char) || p_char == '_' || p_char == '-';\r\n\t}\r\n\r\n\tstatic bool test_localpath(const char * p_path) {\r\n\t\tif (pfc::strcmp_partial(p_path,\"file://\") == 0) p_path += strlen(\"file://\");\r\n\t\treturn pfc::char_is_ascii_alpha(p_path[0]) && \r\n\t\t\tp_path[1] == ':' &&\r\n\t\t\tp_path[2] == '\\\\';\r\n\t}\r\n\tstatic bool test_netpath(const char * p_path) {\r\n\t\tif (pfc::strcmp_partial(p_path,\"file://\") == 0) p_path += strlen(\"file://\");\r\n\t\tif (*p_path != '\\\\') return false;\r\n\t\tp_path++;\r\n\t\tif (*p_path != '\\\\') return false;\r\n\t\tp_path++;\r\n\t\tif (!is_valid_netpath_char(*p_path)) return false;\r\n\t\tp_path++;\r\n\t\twhile(is_valid_netpath_char(*p_path)) p_path++;\r\n\t\tif (*p_path != '\\\\') return false;\r\n\t\treturn true;\r\n\t}\r\n\r\n\tvoid create_path(const char * p_path,abort_callback & p_abort) {\r\n\t\tif (test_localpath(p_path)) {\r\n\t\t\tt_size walk = 0;\r\n\t\t\tif (pfc::strcmp_partial(p_path,\"file://\") == 0) walk += strlen(\"file://\");\r\n\t\t\tcreate_path_internal(p_path,walk + 3,p_abort);\r\n\t\t} else if (test_netpath(p_path)) {\r\n\t\t\tt_size walk = 0;\r\n\t\t\tif (pfc::strcmp_partial(p_path,\"file://\") == 0) walk += strlen(\"file://\");\r\n\t\t\twhile(p_path[walk] == '\\\\') walk++;\r\n\t\t\twhile(p_path[walk] != 0 && p_path[walk] != '\\\\') walk++;\r\n\t\t\twhile(p_path[walk] == '\\\\') walk++;\r\n\t\t\tcreate_path_internal(p_path,walk,p_abort);\r\n\t\t} else {\r\n\t\t\tthrow exception_io(\"Could not create directory structure; unknown path format\");\r\n\t\t}\r\n\t}\r\n\r\n\tstatic bool is_bad_dirchar(char c)\r\n\t{\r\n\t\treturn c==' ' || c=='.';\r\n\t}\r\n\r\n\tvoid make_path(const char * parent,const char * filename,const char * extension,bool allow_new_dirs,pfc::string8 & out,bool really_create_dirs,abort_callback & p_abort)\r\n\t{\r\n\t\tout.reset();\r\n\t\tif (parent && *parent)\r\n\t\t{\r\n\t\t\tout = parent;\r\n\t\t\tout.fix_dir_separator('\\\\');\r\n\t\t}\r\n\t\tbool last_char_is_dir_sep = true;\r\n\t\twhile(*filename)\r\n\t\t{\r\n#ifdef WIN32\r\n\t\t\tif (allow_new_dirs && is_bad_dirchar(*filename))\r\n\t\t\t{\r\n\t\t\t\tconst char * ptr = filename+1;\r\n\t\t\t\twhile(is_bad_dirchar(*ptr)) ptr++;\r\n\t\t\t\tif (*ptr!='\\\\' && *ptr!='/') out.add_string(filename,ptr-filename);\r\n\t\t\t\tfilename = ptr;\r\n\t\t\t\tif (*filename==0) break;\r\n\t\t\t}\r\n#endif\r\n\t\t\tif (pfc::is_path_bad_char(*filename))\r\n\t\t\t{\r\n\t\t\t\tif (allow_new_dirs && (*filename=='\\\\' || *filename=='/'))\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!last_char_is_dir_sep)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (really_create_dirs) try{filesystem::g_create_directory(out,p_abort);}catch(exception_io_already_exists){}\r\n\t\t\t\t\t\tout.add_char('\\\\');\r\n\t\t\t\t\t\tlast_char_is_dir_sep = true;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t\tout.add_char('_');\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tout.add_byte(*filename);\r\n\t\t\t\tlast_char_is_dir_sep = false;\r\n\t\t\t}\r\n\t\t\tfilename++;\r\n\t\t}\r\n\t\tif (out.length()>0 && out[out.length()-1]=='\\\\')\r\n\t\t{\r\n\t\t\tout.add_string(\"noname\");\r\n\t\t}\r\n\t\tif (extension && *extension)\r\n\t\t{\r\n\t\t\tout.add_char('.');\r\n\t\t\tout.add_string(extension);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\r\n\tclass titleformat_text_filter_impl_createdir : public titleformat_text_filter\r\n\t{\r\n\tpublic:\r\n\t\tvoid on_new_field() {}\r\n\t\tvoid write(const GUID & p_inputtype,pfc::string_receiver & p_out,const char * p_data,t_size p_data_length)\r\n\t\t{//not \"UTF-8 aware\" but coded not to clash with UTF-8, since only filtered chars are lower ASCII\r\n\t\t\tif (p_inputtype == titleformat_inputtypes::meta) {\r\n\t\t\t\tt_size index = 0;\r\n\t\t\t\tt_size good_bytes = 0;\r\n\t\t\t\twhile(index < p_data_length && p_data[index] != 0) {\r\n\t\t\t\t\tunsigned char c = (unsigned char)p_data[index];\r\n\t\t\t\t\tif (c < ' ' || c == '\\\\' || c=='/' || c=='|' || c==':')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (good_bytes > 0) {p_out.add_string(p_data+index-good_bytes,good_bytes);good_bytes=0;}\r\n\t\t\t\t\t\tp_out.add_string(\"_\",1);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse good_bytes++;\r\n\t\t\t\t\tindex++;\r\n\t\t\t\t}\r\n\t\t\t\tif (good_bytes > 0) {p_out.add_string(p_data+index-good_bytes,good_bytes);good_bytes=0;}\r\n\t\t\t} else {\r\n\t\t\t\tp_out.add_string(p_data,p_data_length);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n}\r\n\r\nvoid create_directory_helper::format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,const char * spec,pfc::string8 & out)\r\n{\r\n\tpfc::string8 temp;\r\n\thandle->format_title_legacy(p_hook,temp,spec,&titleformat_text_filter_impl_createdir());\r\n\ttemp.replace_char('/','\\\\');\r\n\ttemp.fix_filename_chars('_','\\\\');\r\n\tout = temp;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/create_directory_helper.h",
    "content": "#ifndef _CREATE_DIRECTORY_HELPER_H_\r\n#define _CREATE_DIRECTORY_HELPER_H_\r\n\r\nnamespace create_directory_helper {\r\n\tvoid create_path(const char * p_path,abort_callback & p_abort);\r\n\tvoid make_path(const char * parent,const char * filename,const char * extension,bool allow_new_dirs,pfc::string8 & out,bool b_really_create_dirs,abort_callback & p_dir_create_abort);\r\n\tvoid format_filename(const metadb_handle_ptr & handle,titleformat_hook * p_hook,const char * spec,pfc::string8 & out);\r\n};\r\n\r\n#endif//_CREATE_DIRECTORY_HELPER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cue_creator.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\n\r\nnamespace {\r\n\r\n\tclass format_meta\r\n\t{\r\n\tpublic:\r\n\t\tformat_meta(const file_info & p_source,const char * p_name,bool p_allow_space = true)\r\n\t\t{\r\n\t\t\tp_source.meta_format(p_name,m_buffer);\r\n\t\t\tm_buffer.replace_byte('\\\"','\\'');\r\n\t\t\tuReplaceString(m_buffer,pfc::string8(m_buffer),infinite,\"\\x0d\\x0a\",2,\"\\\\\",1,false);\r\n\t\t\tif (!p_allow_space) m_buffer.replace_byte(' ','_');\r\n\t\t\tm_buffer.replace_nontext_chars();\r\n\t\t}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tpfc::string8_fastalloc m_buffer;\r\n\t};\r\n}\r\n\r\nstatic bool is_meta_same_everywhere(const cue_creator::t_entry_list & p_list,const char * p_meta)\r\n{\r\n\tpfc::string8_fastalloc reference,temp;\r\n\r\n\tcue_creator::t_entry_list::const_iterator iter;\r\n\titer = p_list.first();\r\n\tif (!iter.is_valid()) return false;\r\n\tif (!iter->m_infos.meta_format(p_meta,reference)) return false;\r\n\tfor(;iter.is_valid();++iter)\r\n\t{\r\n\t\tif (!iter->m_infos.meta_format(p_meta,temp)) return false;\r\n\t\tif (strcmp(temp,reference)!=0) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nstatic const char g_eol[] = \"\\r\\n\";\r\n\r\n\r\nnamespace cue_creator\r\n{\r\n\tvoid create(pfc::string_formatter & p_out,const t_entry_list & p_data)\r\n\t{\r\n\t\tif (p_data.get_count() == 0) return;\r\n\t\tbool album_artist_global =\tis_meta_same_everywhere(p_data,\"album artist\"),\r\n\t\t\tartist_global =\t\t\tis_meta_same_everywhere(p_data,\"artist\"),\r\n\t\t\talbum_global =\t\t\tis_meta_same_everywhere(p_data,\"album\"),\r\n\t\t\tgenre_global =\t\t\tis_meta_same_everywhere(p_data,\"genre\"),\r\n\t\t\tdate_global =\t\t\tis_meta_same_everywhere(p_data,\"date\"),\r\n\t\t\tdiscid_global =\t\t\tis_meta_same_everywhere(p_data,\"discid\"),\r\n\t\t\tcomment_global =\t\tis_meta_same_everywhere(p_data,\"comment\"),\r\n\t\t\tcatalog_global =\t\tis_meta_same_everywhere(p_data,\"catalog\"),\r\n\t\t\tsongwriter_global =\t\tis_meta_same_everywhere(p_data,\"songwriter\");\r\n\r\n\t\tif (genre_global) {\r\n\t\t\tp_out << \"REM GENRE \" << format_meta(p_data.first()->m_infos,\"genre\") << g_eol;\r\n\t\t}\r\n\t\tif (date_global) {\r\n\t\t\tp_out << \"REM DATE \" << format_meta(p_data.first()->m_infos,\"date\") << g_eol;\r\n\t\t}\r\n\t\tif (discid_global) {\r\n\t\t\tp_out << \"REM DISCID \" << format_meta(p_data.first()->m_infos,\"discid\") << g_eol;\r\n\t\t}\r\n\t\tif (comment_global) {\r\n\t\t\tp_out << \"REM COMMENT \" << format_meta(p_data.first()->m_infos,\"comment\") << g_eol;\r\n\t\t}\r\n\t\tif (catalog_global) {\r\n\t\t\tp_out << \"CATALOG \" << format_meta(p_data.first()->m_infos,\"catalog\") << g_eol;\r\n\t\t}\r\n\t\tif (songwriter_global) {\r\n\t\t\tp_out << \"SONGWRITER \\\"\" << format_meta(p_data.first()->m_infos,\"songwriter\") << \"\\\"\" << g_eol;\r\n\t\t}\r\n\r\n\t\tif (album_artist_global)\r\n\t\t{\r\n\t\t\tp_out << \"PERFORMER \\\"\" << format_meta(p_data.first()->m_infos,\"album artist\") << \"\\\"\" << g_eol;\r\n\t\t\tartist_global = false;\r\n\t\t}\r\n\t\telse if (artist_global)\r\n\t\t{\r\n\t\t\tp_out << \"PERFORMER \\\"\" << format_meta(p_data.first()->m_infos,\"artist\") << \"\\\"\" << g_eol;\r\n\t\t}\r\n\t\tif (album_global)\r\n\t\t{\r\n\t\t\tp_out << \"TITLE \\\"\" << format_meta(p_data.first()->m_infos,\"album\") << \"\\\"\" << g_eol;\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\treplaygain_info::t_text_buffer rgbuffer;\r\n\t\t\treplaygain_info rg = p_data.first()->m_infos.get_replaygain();\r\n\t\t\tif (rg.format_album_gain(rgbuffer))\r\n\t\t\t\tp_out << \"REM REPLAYGAIN_ALBUM_GAIN \" << rgbuffer << g_eol;\r\n\t\t\tif (rg.format_album_peak(rgbuffer))\r\n\t\t\t\tp_out << \"REM REPLAYGAIN_ALBUM_PEAK \" << rgbuffer << g_eol;\t\t\t\r\n\t\t}\r\n\r\n\t\tpfc::string8 last_file;\r\n\r\n\t\tfor(t_entry_list::const_iterator iter = p_data.first();iter.is_valid();++iter)\r\n\t\t{\r\n\t\t\tif (strcmp(last_file,iter->m_file) != 0)\r\n\t\t\t{\r\n\t\t\t\tp_out << \"FILE \\\"\" << iter->m_file << \"\\\" WAVE\" << g_eol;\r\n\t\t\t\tlast_file = iter->m_file;\r\n\t\t\t}\r\n\r\n\t\t\tp_out << \"  TRACK \" << pfc::format_int(iter->m_track_number,2) << \" AUDIO\" << g_eol;\r\n\r\n\t\t\tif (iter->m_infos.meta_find(\"title\") != infinite)\r\n\t\t\t\tp_out << \"    TITLE \\\"\" << format_meta(iter->m_infos,\"title\") << \"\\\"\" << g_eol;\r\n\t\t\t\r\n\t\t\tif (!artist_global && iter->m_infos.meta_find(\"artist\") != infinite)\r\n\t\t\t\tp_out << \"    PERFORMER \\\"\" << format_meta(iter->m_infos,\"artist\") << \"\\\"\" << g_eol;\r\n\r\n\t\t\tif (!songwriter_global && iter->m_infos.meta_find(\"songwriter\") != infinite) {\r\n\t\t\t\tp_out << \"    SONGWRITER \\\"\" << format_meta(iter->m_infos,\"songwriter\") << \"\\\"\" << g_eol;\r\n\t\t\t}\r\n\r\n\t\t\tif (iter->m_infos.meta_find(\"isrc\") != infinite) {\r\n\t\t\t\tp_out << \"    ISRC \" << format_meta(iter->m_infos,\"isrc\") << g_eol;\r\n\t\t\t}\r\n\r\n\t\t\tif (!date_global && iter->m_infos.meta_find(\"date\") != infinite) {\r\n\t\t\t\tp_out << \"    REM DATE \" << format_meta(iter->m_infos,\"date\") << g_eol;\r\n\t\t\t}\r\n\r\n\r\n\r\n\t\t\t{\r\n\t\t\t\treplaygain_info::t_text_buffer rgbuffer;\r\n\t\t\t\treplaygain_info rg = iter->m_infos.get_replaygain();\r\n\t\t\t\tif (rg.format_track_gain(rgbuffer))\r\n\t\t\t\t\tp_out << \"    REM REPLAYGAIN_TRACK_GAIN \" << rgbuffer << g_eol;\r\n\t\t\t\tif (rg.format_track_peak(rgbuffer))\r\n\t\t\t\t\tp_out << \"    REM REPLAYGAIN_TRACK_PEAK \" << rgbuffer << g_eol;\t\t\t\r\n\t\t\t}\r\n\r\n\t\t\tif (!iter->m_flags.is_empty()) {\r\n\t\t\t\tp_out << \"    FLAGS \" << iter->m_flags << g_eol;\r\n\t\t\t}\r\n\r\n\t\t\tif (iter->m_index_list.m_positions[0] < iter->m_index_list.m_positions[1])\r\n\t\t\t{\r\n\t\t\t\tif (iter->m_index_list.m_positions[0] < 0)\r\n\t\t\t\t\tp_out << \"    PREGAP \" << cuesheet_format_index_time(iter->m_index_list.m_positions[1] - iter->m_index_list.m_positions[0]) << g_eol;\r\n\t\t\t\telse\r\n\t\t\t\t\tp_out << \"    INDEX 00 \" << cuesheet_format_index_time(iter->m_index_list.m_positions[0]) << g_eol;\r\n\t\t\t}\r\n\r\n\t\t\tp_out << \"    INDEX 01 \" << cuesheet_format_index_time(iter->m_index_list.m_positions[1]) << g_eol;\r\n\r\n\t\t\tfor(unsigned n=2;n<t_cuesheet_index_list::count && iter->m_index_list.m_positions[n] > 0;n++)\r\n\t\t\t{\r\n\t\t\t\tp_out << \"    INDEX \" << pfc::format_uint(n,2) << \" \" << cuesheet_format_index_time(iter->m_index_list.m_positions[n]) << g_eol;\r\n\t\t\t}\r\n\r\n\t\t\t// p_out << \"    INDEX 01 \" << cuesheet_format_index_time(iter->m_offset) << g_eol;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid t_entry::set_simple_index(double p_time)\r\n\t{\r\n\t\tm_index_list.reset();\r\n\t\tm_index_list.m_positions[0] = m_index_list.m_positions[1] = p_time;\r\n\t}\r\n\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cue_creator.h",
    "content": "namespace cue_creator\r\n{\r\n\tstruct t_entry\r\n\t{\r\n\t\tfile_info_impl m_infos;\r\n\t\tpfc::string8 m_file,m_flags;\r\n\t\tunsigned m_track_number;\r\n\r\n\t\tt_cuesheet_index_list m_index_list;\r\n\r\n\t\tvoid set_simple_index(double p_time);\r\n\t};\r\n\t\r\n\ttypedef pfc::chain_list_t<t_entry> t_entry_list;\r\n\r\n\tvoid create(pfc::string_formatter & p_out,const pfc::chain_list_t<t_entry> & p_list);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cue_parser.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nnamespace {\r\n\tPFC_DECLARE_EXCEPTION(exception_cue,pfc::exception,\"Invalid cuesheet\");\r\n}\r\n\r\nstatic bool is_numeric(char c) {return c>='0' && c<='9';}\r\n\r\n\r\nstatic bool is_spacing(char c)\r\n{\r\n\treturn c == ' ' || c == '\\t';\r\n}\r\n\r\nstatic bool is_linebreak(char c)\r\n{\r\n\treturn c == '\\n' || c == '\\r';\r\n}\r\n\r\nstatic void validate_file_type(const char * p_type,t_size p_type_length) {\r\n\tif (\r\n\t\t//standard types\r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"WAVE\",infinite) != 0 && \r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"MP3\",infinite) != 0 && \r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"AIFF\",infinite) != 0 && \r\n\t\t//common user-entered types\r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"APE\",infinite) != 0 && \r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"FLAC\",infinite) != 0 &&\r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"WV\",infinite) != 0 &&\r\n\t\tstricmp_utf8_ex(p_type,p_type_length,\"WAVPACK\",infinite) != 0\r\n\t\t)\r\n\t\tthrow exception_cue(pfc::string_formatter() << \"expected WAVE, MP3 or AIFF, got : \\\"\" << pfc::string8(p_type,p_type_length) << \"\\\"\");\r\n}\r\n\r\nnamespace {\r\n\t\r\n\tclass NOVTABLE cue_parser_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) = 0;\r\n\t\tvirtual void on_track(unsigned p_index,const char * p_type,t_size p_type_length) = 0;\r\n\t\tvirtual void on_pregap(unsigned p_value) = 0;\r\n\t\tvirtual void on_index(unsigned p_index,unsigned p_value) = 0;\r\n\t\tvirtual void on_title(const char * p_title,t_size p_title_length) = 0;\r\n\t\tvirtual void on_performer(const char * p_performer,t_size p_performer_length) = 0;\r\n\t\tvirtual void on_songwriter(const char * p_songwriter,t_size p_songwriter_length) = 0;\r\n\t\tvirtual void on_isrc(const char * p_isrc,t_size p_isrc_length) = 0;\r\n\t\tvirtual void on_catalog(const char * p_catalog,t_size p_catalog_length) = 0;\r\n\t\tvirtual void on_comment(const char * p_comment,t_size p_comment_length) = 0;\r\n\t\tvirtual void on_flags(const char * p_flags,t_size p_flags_length) = 0;\r\n\t};\r\n\r\n\tclass NOVTABLE cue_parser_callback_meta : public cue_parser_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) = 0;\r\n\t\tvirtual void on_track(unsigned p_index,const char * p_type,t_size p_type_length) = 0;\r\n\t\tvirtual void on_pregap(unsigned p_value) = 0;\r\n\t\tvirtual void on_index(unsigned p_index,unsigned p_value) = 0;\r\n\t\tvirtual void on_meta(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) = 0;\r\n\tprotected:\r\n\t\tstatic bool is_known_meta(const char * p_name,t_size p_length)\r\n\t\t{\r\n\t\t\tstatic const char * metas[] = {\"genre\",\"date\",\"discid\",\"comment\",\"replaygain_track_gain\",\"replaygain_track_peak\",\"replaygain_album_gain\",\"replaygain_album_peak\"};\r\n\t\t\tfor(t_size n=0;n<tabsize(metas);n++) {\r\n\t\t\t\tif (!stricmp_utf8_ex(p_name,p_length,metas[n],infinite)) return true;\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tvoid on_comment(const char * p_comment,t_size p_comment_length)\r\n\t\t{\r\n\t\t\tunsigned ptr = 0;\r\n\t\t\twhile(ptr < p_comment_length && !is_spacing(p_comment[ptr])) ptr++;\r\n\t\t\tif (is_known_meta(p_comment, ptr))\r\n\t\t\t{\r\n\t\t\t\tunsigned name_length = ptr;\r\n\t\t\t\twhile(ptr < p_comment_length && is_spacing(p_comment[ptr])) ptr++;\r\n\t\t\t\tif (ptr < p_comment_length)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (p_comment[ptr] == '\\\"')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tptr++;\r\n\t\t\t\t\t\tunsigned value_base = ptr;\r\n\t\t\t\t\t\twhile(ptr < p_comment_length && p_comment[ptr] != '\\\"') ptr++;\r\n\t\t\t\t\t\tif (ptr == p_comment_length) throw exception_cue(\"invalid REM syntax\",0);\r\n\t\t\t\t\t\tif (ptr > value_base) on_meta(p_comment,name_length,p_comment + value_base,ptr - value_base);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tunsigned value_base = ptr;\r\n\t\t\t\t\t\twhile(ptr < p_comment_length /*&& !is_spacing(p_comment[ptr])*/) ptr++;\r\n\t\t\t\t\t\tif (ptr > value_base) on_meta(p_comment,name_length,p_comment + value_base,ptr - value_base);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid on_title(const char * p_title,t_size p_title_length)\r\n\t\t{\r\n\t\t\ton_meta(\"title\",infinite,p_title,p_title_length);\r\n\t\t}\r\n\t\tvoid on_songwriter(const char * p_songwriter,t_size p_songwriter_length) {\r\n\t\t\ton_meta(\"songwriter\",infinite,p_songwriter,p_songwriter_length);\r\n\t\t}\r\n\t\tvoid on_performer(const char * p_performer,t_size p_performer_length)\r\n\t\t{\r\n\t\t\ton_meta(\"artist\",infinite,p_performer,p_performer_length);\r\n\t\t}\r\n\r\n\t\tvoid on_isrc(const char * p_isrc,t_size p_isrc_length)\r\n\t\t{\r\n\t\t\ton_meta(\"isrc\",infinite,p_isrc,p_isrc_length);\r\n\t\t}\r\n\t\tvoid on_catalog(const char * p_catalog,t_size p_catalog_length)\r\n\t\t{\r\n\t\t\ton_meta(\"catalog\",infinite,p_catalog,p_catalog_length);\r\n\t\t}\r\n\t\tvoid on_flags(const char * p_flags,t_size p_flags_length) {}\r\n\t};\r\n\r\n\r\n\tclass cue_parser_callback_retrievelist : public cue_parser_callback\r\n\t{\r\n\tpublic:\r\n\t\tcue_parser_callback_retrievelist(pfc::chain_list_t<cue_parser::cue_entry> & p_out) : m_out(p_out), m_track(0), m_pregap(0), m_index0_set(false), m_index1_set(false)\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\tvoid on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length)\r\n\t\t{\r\n\t\t\tvalidate_file_type(p_type,p_type_length);\r\n\t\t\tm_file.set_string(p_file,p_file_length);\r\n\t\t}\r\n\t\t\r\n\t\tvoid on_track(unsigned p_index,const char * p_type,t_size p_type_length)\r\n\t\t{\r\n\t\t\tif (stricmp_utf8_ex(p_type,p_type_length,\"audio\",infinite)) throw exception_cue(\"only tracks of type AUDIO supported\",0);\r\n\t\t\t//if (p_index != m_track + 1) throw exception_cue(\"cuesheet tracks out of order\");\r\n\t\t\tif (m_track != 0) finalize_track();\r\n\t\t\tif (m_file.is_empty()) throw exception_cue(\"declaring a track with no file set\",0);\r\n\t\t\tm_trackfile = m_file;\r\n\t\t\tm_track = p_index;\r\n\t\t}\r\n\r\n\t\tvoid on_pregap(unsigned p_value) {m_pregap = (double) p_value / 75.0;}\r\n\r\n\t\tvoid on_index(unsigned p_index,unsigned p_value)\r\n\t\t{\r\n\t\t\tif (p_index < t_cuesheet_index_list::count)\r\n\t\t\t{\r\n\t\t\t\tswitch(p_index)\r\n\t\t\t\t{\r\n\t\t\t\tcase 0: m_index0_set = true; break;\r\n\t\t\t\tcase 1: m_index1_set = true; break;\r\n\t\t\t\t}\r\n\t\t\t\tm_index_list.m_positions[p_index] = (double) p_value / 75.0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid on_title(const char * p_title,t_size p_title_length) {}\r\n\t\tvoid on_performer(const char * p_performer,t_size p_performer_length) {}\r\n\t\tvoid on_songwriter(const char * p_songwriter,t_size p_songwriter_length) {}\r\n\t\tvoid on_isrc(const char * p_isrc,t_size p_isrc_length) {}\r\n\t\tvoid on_catalog(const char * p_catalog,t_size p_catalog_length) {}\r\n\t\tvoid on_comment(const char * p_comment,t_size p_comment_length) {}\r\n\t\tvoid on_flags(const char * p_flags,t_size p_flags_length) {}\r\n\r\n\t\tvoid finalize()\r\n\t\t{\r\n\t\t\tif (m_track != 0)\r\n\t\t\t{\r\n\t\t\t\tfinalize_track();\r\n\t\t\t\tm_track = 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tvoid finalize_track()\r\n\t\t{\r\n\t\t\tif (!m_index1_set) throw exception_cue(\"INDEX 01 not set\",0);\r\n\t\t\tif (!m_index0_set) m_index_list.m_positions[0] = m_index_list.m_positions[1] - m_pregap;\r\n\t\t\tif (!m_index_list.is_valid()) throw exception_cue(\"invalid index list\");\r\n\r\n\t\t\tpfc::chain_list_t<cue_parser::cue_entry>::iterator iter;\r\n\t\t\titer = m_out.insert_last();\r\n\t\t\tif (m_trackfile.is_empty()) throw exception_cue(\"track has no file assigned\",0);\r\n\t\t\titer->m_file = m_trackfile;\r\n\t\t\titer->m_track_number = m_track;\r\n\t\t\titer->m_indexes = m_index_list;\r\n\t\t\t\r\n\t\t\tm_index_list.reset();\r\n\t\t\tm_index0_set = false;\r\n\t\t\tm_index1_set = false;\r\n\t\t\tm_pregap = 0;\r\n\t\t}\r\n\r\n\t\tbool m_index0_set,m_index1_set;\r\n\t\tt_cuesheet_index_list m_index_list;\r\n\t\tdouble m_pregap;\r\n\t\tunsigned m_track;\r\n\t\tpfc::string8 m_file,m_trackfile;\r\n\t\tpfc::chain_list_t<cue_parser::cue_entry> & m_out;\r\n\t};\r\n\r\n\tclass cue_parser_callback_retrieveinfo : public cue_parser_callback_meta\r\n\t{\r\n\tpublic:\r\n\t\tcue_parser_callback_retrieveinfo(file_info & p_out,unsigned p_wanted_track) : m_out(p_out), m_wanted_track(p_wanted_track), m_track(0), m_is_va(false), m_index0_set(false), m_index1_set(false), m_pregap(0), m_totaltracks(0) {}\r\n\r\n\t\tvoid on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) {}\r\n\r\n\t\tvoid on_track(unsigned p_index,const char * p_type,t_size p_type_length)\r\n\t\t{\r\n\t\t\tif (p_index == 0) throw exception_cue(\"invalid TRACK index\",0);\r\n\t\t\tif (p_index == m_wanted_track)\r\n\t\t\t{\r\n\t\t\t\tif (stricmp_utf8_ex(p_type,p_type_length,\"audio\",infinite)) throw exception_cue(\"only tracks of type AUDIO supported\",0);\r\n\t\t\t}\r\n\t\t\tm_track = p_index;\r\n\t\t\tm_totaltracks++;\r\n\t\t}\r\n\r\n\t\tvoid on_pregap(unsigned p_value) {if (m_track == m_wanted_track) m_pregap = (double) p_value / 75.0;}\r\n\r\n\t\tvoid on_index(unsigned p_index,unsigned p_value)\r\n\t\t{\r\n\t\t\tif (m_track == m_wanted_track && p_index < t_cuesheet_index_list::count)\r\n\t\t\t{\r\n\t\t\t\tswitch(p_index)\r\n\t\t\t\t{\r\n\t\t\t\tcase 0:\tm_index0_set = true; break;\r\n\t\t\t\tcase 1: m_index1_set = true; break;\r\n\t\t\t\t}\r\n\t\t\t\tm_indexes.m_positions[p_index] = (double) p_value / 75.0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\r\n\t\tvoid on_meta(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length)\r\n\t\t{\r\n\t\t\tt_meta_list::iterator iter;\r\n\t\t\tif (m_track == 0) //globals\r\n\t\t\t{\r\n\t\t\t\t//convert global title to album\r\n\t\t\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"title\",infinite))\r\n\t\t\t\t{\r\n\t\t\t\t\tp_name = \"album\";\r\n\t\t\t\t\tp_name_length = 5;\r\n\t\t\t\t}\r\n\t\t\t\telse if (!stricmp_utf8_ex(p_name,p_name_length,\"artist\",infinite))\r\n\t\t\t\t{\r\n\t\t\t\t\tm_album_artist.set_string(p_value,p_value_length);\r\n\t\t\t\t}\r\n\r\n\t\t\t\titer = m_globals.insert_last();\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif (!m_is_va)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (!stricmp_utf8_ex(p_name,p_name_length,\"artist\",infinite))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (!m_album_artist.is_empty())\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (stricmp_utf8_ex(p_value,p_value_length,m_album_artist,m_album_artist.length())) m_is_va = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (m_track == m_wanted_track) //locals\r\n\t\t\t\t{\r\n\t\t\t\t\titer = m_locals.insert_last();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (iter.is_valid())\r\n\t\t\t{\r\n\t\t\t\titer->m_name.set_string(p_name,p_name_length);\r\n\t\t\t\titer->m_value.set_string(p_value,p_value_length);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid finalize()\r\n\t\t{\r\n\t\t\tif (!m_index1_set) throw exception_cue(\"INDEX 01 not set\",0);\r\n\t\t\tif (!m_index0_set) m_indexes.m_positions[0] = m_indexes.m_positions[1] - m_pregap;\r\n\t\t\tm_indexes.to_infos(m_out);\r\n\r\n\t\t\treplaygain_info rg;\r\n\t\t\trg.reset();\r\n\t\t\tt_meta_list::const_iterator iter;\r\n\r\n\t\t\tif (m_is_va)\r\n\t\t\t{\r\n\t\t\t\t//clean up VA mess\r\n\r\n\t\t\t\tt_meta_list::const_iterator iter_global,iter_local;\r\n\r\n\t\t\t\titer_global = find_first_field(m_globals,\"artist\");\r\n\t\t\t\titer_local = find_first_field(m_locals,\"artist\");\r\n\t\t\t\tif (iter_global.is_valid())\r\n\t\t\t\t{\r\n\t\t\t\t\tm_out.meta_set(\"album artist\",iter_global->m_value);\r\n\t\t\t\t\tif (iter_local.is_valid()) m_out.meta_set(\"artist\",iter_local->m_value);\r\n\t\t\t\t\telse m_out.meta_set(\"artist\",iter_global->m_value);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tif (iter_local.is_valid()) m_out.meta_set(\"artist\",iter_local->m_value);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\r\n\t\t\t\twipe_field(m_globals,\"artist\");\r\n\t\t\t\twipe_field(m_locals,\"artist\");\r\n\t\t\t\t\r\n\t\t\t}\r\n\r\n\t\t\tfor(iter=m_globals.first();iter.is_valid();iter++)\r\n\t\t\t{\r\n\t\t\t\tif (!rg.set_from_meta(iter->m_name,iter->m_value))\r\n\t\t\t\t\tm_out.meta_set(iter->m_name,iter->m_value);\r\n\t\t\t}\r\n\t\t\tfor(iter=m_locals.first();iter.is_valid();iter++)\r\n\t\t\t{\r\n\t\t\t\tif (!rg.set_from_meta(iter->m_name,iter->m_value))\r\n\t\t\t\t\tm_out.meta_set(iter->m_name,iter->m_value);\r\n\t\t\t}\r\n\t\t\tm_out.meta_set(\"tracknumber\",pfc::string_formatter() << m_wanted_track);\r\n\t\t\tm_out.meta_set(\"totaltracks\", pfc::string_formatter() << m_totaltracks);\r\n\t\t\tm_out.set_replaygain(rg);\r\n\r\n\t\t}\r\n\tprivate:\r\n\t\tstruct t_meta_entry {\r\n\t\t\tpfc::string8 m_name,m_value;\r\n\t\t};\r\n\t\ttypedef pfc::chain_list_t<t_meta_entry> t_meta_list;\r\n\r\n\t\tstatic t_meta_list::const_iterator find_first_field(t_meta_list const & p_list,const char * p_field)\r\n\t\t{\r\n\t\t\tt_meta_list::const_iterator iter;\r\n\t\t\tfor(iter=p_list.first();iter.is_valid();++iter)\r\n\t\t\t{\r\n\t\t\t\tif (!stricmp_utf8(p_field,iter->m_name)) return iter;\r\n\t\t\t}\r\n\t\t\treturn t_meta_list::const_iterator();//null iterator\r\n\t\t}\r\n\r\n\t\tstatic void wipe_field(t_meta_list & p_list,const char * p_field)\r\n\t\t{\r\n\t\t\tt_meta_list::iterator iter;\r\n\t\t\tfor(iter=p_list.first();iter.is_valid();)\r\n\t\t\t{\r\n\t\t\t\tif (!stricmp_utf8(p_field,iter->m_name))\r\n\t\t\t\t{\r\n\t\t\t\t\tt_meta_list::iterator temp = iter;\r\n\t\t\t\t\t++temp;\r\n\t\t\t\t\tp_list.remove_single(iter);\r\n\t\t\t\t\titer = temp;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\t++iter;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tt_meta_list m_globals,m_locals;\r\n\t\tfile_info & m_out;\r\n\t\tunsigned m_wanted_track, m_track,m_totaltracks;\r\n\t\tpfc::string8 m_album_artist;\r\n\t\tbool m_is_va;\r\n\t\tt_cuesheet_index_list m_indexes;\r\n\t\tbool m_index0_set,m_index1_set;\r\n\t\tdouble m_pregap;\r\n\t};\r\n\r\n};\r\n\r\n\r\nstatic void g_parse_cue_line(const char * p_line,t_size p_line_length,cue_parser_callback & p_callback)\r\n{\r\n\tt_size ptr = 0;\r\n\twhile(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++;\r\n\tif (!stricmp_utf8_ex(p_line,ptr,\"file\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tt_size file_base,file_length, type_base,type_length;\r\n\t\t\r\n\t\tif (p_line[ptr] == '\\\"')\r\n\t\t{\r\n\t\t\tptr++;\r\n\t\t\tfile_base = ptr;\r\n\t\t\twhile(ptr < p_line_length && p_line[ptr] != '\\\"') ptr++;\r\n\t\t\tif (ptr == p_line_length) throw exception_cue(\"invalid FILE syntax\",0);\r\n\t\t\tfile_length = ptr - file_base;\r\n\t\t\tptr++;\r\n\t\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tfile_base = ptr;\r\n\t\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++;\r\n\t\t\tfile_length = ptr - file_base;\r\n\t\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t}\r\n\r\n\t\ttype_base = ptr;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++;\r\n\t\ttype_length = ptr - type_base;\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\r\n\t\tif (ptr != p_line_length || file_length == 0 || type_length == 0) throw exception_cue(\"invalid FILE syntax\",0);\r\n\r\n\t\tp_callback.on_file(p_line + file_base, file_length, p_line + type_base, type_length);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"track\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\r\n\t\tt_size track_base = ptr, track_length;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr]))\r\n\t\t{\r\n\t\t\tif (!is_numeric(p_line[ptr])) throw exception_cue(\"invalid TRACK syntax\",0);\r\n\t\t\tptr++;\r\n\t\t}\r\n\t\ttrack_length = ptr - track_base;\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\r\n\t\tt_size type_base = ptr, type_length;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr])) ptr++;\r\n\t\ttype_length = ptr - type_base;\r\n\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr != p_line_length || type_length == 0) throw exception_cue(\"invalid TRACK syntax\",0);\r\n\t\tunsigned track = pfc::atoui_ex(p_line+track_base,track_length);\r\n\t\tif (track < 1 || track > 99) throw exception_cue(\"invalid track number\",0);\r\n\r\n\t\tp_callback.on_track(track,p_line + type_base, type_length);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"index\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\r\n\t\tt_size index_base,index_length, time_base,time_length;\r\n\t\tindex_base = ptr;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr]))\r\n\t\t{\r\n\t\t\tif (!is_numeric(p_line[ptr])) throw exception_cue(\"invalid INDEX syntax\",0);\r\n\t\t\tptr++;\r\n\t\t}\r\n\t\tindex_length = ptr - index_base;\r\n\t\t\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\ttime_base = ptr;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr]))\r\n\t\t{\r\n\t\t\tif (!is_numeric(p_line[ptr]) && p_line[ptr] != ':')\r\n\t\t\t\tthrow exception_cue(\"invalid INDEX syntax\",0);\r\n\t\t\tptr++;\r\n\t\t}\r\n\t\ttime_length = ptr - time_base;\r\n\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\r\n\t\tif (ptr != p_line_length || index_length == 0 || time_length == 0)\r\n\t\t\tthrow exception_cue(\"invalid INDEX syntax\",0);\r\n\r\n\t\tunsigned index = pfc::atoui_ex(p_line+index_base,index_length);\r\n\t\tif (index > 99) throw exception_cue(\"invalid INDEX syntax\",0);\r\n\t\tunsigned time = cuesheet_parse_index_time_ticks_e(p_line + time_base,time_length);\r\n\t\t\r\n\t\tp_callback.on_index(index,time);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"pregap\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\r\n\t\tt_size time_base, time_length;\r\n\t\ttime_base = ptr;\r\n\t\twhile(ptr < p_line_length && !is_spacing(p_line[ptr]))\r\n\t\t{\r\n\t\t\tif (!is_numeric(p_line[ptr]) && p_line[ptr] != ':')\r\n\t\t\t\tthrow exception_cue(\"invalid PREGAP syntax\",0);\r\n\t\t\tptr++;\r\n\t\t}\r\n\t\ttime_length = ptr - time_base;\r\n\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\r\n\t\tif (ptr != p_line_length || time_length == 0)\r\n\t\t\tthrow exception_cue(\"invalid PREGAP syntax\",0);\r\n\r\n\t\tunsigned time = cuesheet_parse_index_time_ticks_e(p_line + time_base,time_length);\r\n\t\t\r\n\t\tp_callback.on_pregap(time);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"title\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr == p_line_length) throw exception_cue(\"invalid TITLE syntax\",0);\r\n\t\tif (p_line[ptr] == '\\\"')\r\n\t\t{\r\n\t\t\tptr++;\r\n\t\t\tt_size base = ptr;\r\n\t\t\twhile(ptr < p_line_length && p_line[ptr] != '\\\"') ptr++;\r\n\t\t\tif (ptr == p_line_length) throw exception_cue(\"invalid TITLE syntax\",0);\r\n\t\t\tt_size length = ptr-base;\r\n\t\t\tptr++;\r\n\t\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\tif (ptr != p_line_length) throw exception_cue(\"invalid TITLE syntax\",0);\r\n\t\t\tp_callback.on_title(p_line+base,length);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tp_callback.on_title(p_line+ptr,p_line_length-ptr);\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"performer\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr == p_line_length) throw exception_cue(\"invalid PERFORMER syntax\",0);\r\n\t\tif (p_line[ptr] == '\\\"')\r\n\t\t{\r\n\t\t\tptr++;\r\n\t\t\tt_size base = ptr;\r\n\t\t\twhile(ptr < p_line_length && p_line[ptr] != '\\\"') ptr++;\r\n\t\t\tif (ptr == p_line_length) throw exception_cue(\"invalid PERFORMER syntax\",0);\r\n\t\t\tt_size length = ptr-base;\r\n\t\t\tptr++;\r\n\t\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\tif (ptr != p_line_length) throw exception_cue(\"invalid PERFORMER syntax\",0);\r\n\t\t\tp_callback.on_performer(p_line+base,length);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tp_callback.on_performer(p_line+ptr,p_line_length-ptr);\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"songwriter\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr == p_line_length) throw exception_cue(\"invalid SONGWRITER syntax\",0);\r\n\t\tif (p_line[ptr] == '\\\"')\r\n\t\t{\r\n\t\t\tptr++;\r\n\t\t\tt_size base = ptr;\r\n\t\t\twhile(ptr < p_line_length && p_line[ptr] != '\\\"') ptr++;\r\n\t\t\tif (ptr == p_line_length) throw exception_cue(\"invalid SONGWRITER syntax\",0);\r\n\t\t\tt_size length = ptr-base;\r\n\t\t\tptr++;\r\n\t\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\t\tif (ptr != p_line_length) throw exception_cue(\"invalid SONGWRITER syntax\",0);\r\n\t\t\tp_callback.on_songwriter(p_line+base,length);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tp_callback.on_songwriter(p_line+ptr,p_line_length-ptr);\r\n\t\t}\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"isrc\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tt_size length = p_line_length - ptr;\r\n\t\tif (length == 0) throw exception_cue(\"invalid ISRC syntax\",0);\r\n\t\tp_callback.on_isrc(p_line+ptr,length);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"catalog\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tt_size length = p_line_length - ptr;\r\n\t\tif (length == 0) throw exception_cue(\"invalid CATALOG syntax\",0);\r\n\t\tp_callback.on_catalog(p_line+ptr,length);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"flags\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr < p_line_length)\r\n\t\t\tp_callback.on_flags(p_line + ptr, p_line_length - ptr);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"rem\",infinite))\r\n\t{\r\n\t\twhile(ptr < p_line_length && is_spacing(p_line[ptr])) ptr++;\r\n\t\tif (ptr < p_line_length)\r\n\t\t\tp_callback.on_comment(p_line + ptr, p_line_length - ptr);\r\n\t}\r\n\telse if (!stricmp_utf8_ex(p_line,ptr,\"postgap\",infinite)) {\r\n\t\tthrow exception_cue(\"POSTGAP is not supported\",0);\r\n\t} else if (!stricmp_utf8_ex(p_line,ptr,\"cdtextfile\",infinite)) {\r\n\t\t//do nothing\r\n\t}\r\n\telse throw exception_cue(\"unknown cuesheet item\",0);\r\n}\r\n\r\nstatic void g_parse_cue(const char * p_cuesheet,cue_parser_callback & p_callback)\r\n{\r\n\tconst char * parseptr = p_cuesheet;\r\n\tt_size lineidx = 1;\r\n\twhile(*parseptr)\r\n\t{\r\n\t\twhile(is_spacing(*parseptr)) *parseptr++;\r\n\t\tif (*parseptr)\r\n\t\t{\r\n\t\t\tt_size length = 0;\r\n\t\t\twhile(parseptr[length] && !is_linebreak(parseptr[length])) length++;\r\n\t\t\tif (length > 0) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tg_parse_cue_line(parseptr,length,p_callback);\r\n\t\t\t\t} catch(exception_cue const & e) {//rethrow with line info\r\n\t\t\t\t\tthrow exception_cue(pfc::string_formatter() << e.what() << \" (line \" << lineidx << \")\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tparseptr += length;\r\n\t\t\twhile(is_linebreak(*parseptr)) {\r\n\t\t\t\tif (*parseptr == '\\n') lineidx++;\r\n\t\t\t\tparseptr++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid cue_parser::parse(const char *p_cuesheet,pfc::chain_list_t<cue_entry> & p_out) {\r\n\ttry {\r\n\t\tcue_parser_callback_retrievelist callback(p_out);\r\n\t\tg_parse_cue(p_cuesheet,callback);\r\n\t\tcallback.finalize();\r\n\t} catch(exception_cue const & e) {\r\n\t\tthrow exception_bad_cuesheet(pfc::string_formatter() << \"Error parsing cuesheet: \" << e.what());\r\n\t}\r\n}\r\nvoid cue_parser::parse_info(const char * p_cuesheet,file_info & p_info,unsigned p_index) {\r\n\ttry {\r\n\t\tcue_parser_callback_retrieveinfo callback(p_info,p_index);\r\n\t\tg_parse_cue(p_cuesheet,callback);\r\n\t\tcallback.finalize();\r\n\t} catch(exception_cue const & e) {\r\n\t\tthrow exception_bad_cuesheet(pfc::string_formatter() << \"Error parsing cuesheet: \" << e.what());\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\r\n\tclass cue_parser_callback_retrievecount : public cue_parser_callback\r\n\t{\r\n\tpublic:\r\n\t\tcue_parser_callback_retrievecount() : m_count(0) {}\r\n\t\tunsigned get_count() const {return m_count;}\r\n\t\tvoid on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) {}\r\n\t\tvoid on_track(unsigned p_index,const char * p_type,t_size p_type_length) {m_count++;}\r\n\t\tvoid on_pregap(unsigned p_value) {}\r\n\t\tvoid on_index(unsigned p_index,unsigned p_value) {}\r\n\t\tvoid on_title(const char * p_title,t_size p_title_length) {}\r\n\t\tvoid on_performer(const char * p_performer,t_size p_performer_length) {}\r\n\t\tvoid on_isrc(const char * p_isrc,t_size p_isrc_length) {}\r\n\t\tvoid on_catalog(const char * p_catalog,t_size p_catalog_length) {}\r\n\t\tvoid on_comment(const char * p_comment,t_size p_comment_length) {}\r\n\t\tvoid on_flags(const char * p_flags,t_size p_flags_length) {}\r\n\tprivate:\r\n\t\tunsigned m_count;\r\n\t};\r\n\r\n\tclass cue_parser_callback_retrievecreatorentries : public cue_parser_callback\r\n\t{\r\n\tpublic:\r\n\t\tcue_parser_callback_retrievecreatorentries(cue_creator::t_entry_list & p_out) : m_out(p_out), m_track(0), m_pregap(0), m_index0_set(false), m_index1_set(false) {}\r\n\r\n\t\tvoid on_file(const char * p_file,t_size p_file_length,const char * p_type,t_size p_type_length) {\r\n\t\t\tvalidate_file_type(p_type,p_type_length);\r\n\t\t\tm_file.set_string(p_file,p_file_length);\r\n\t\t}\r\n\t\t\r\n\t\tvoid on_track(unsigned p_index,const char * p_type,t_size p_type_length)\r\n\t\t{\r\n\t\t\tif (stricmp_utf8_ex(p_type,p_type_length,\"audio\",infinite)) throw exception_cue(\"only tracks of type AUDIO supported\",0);\r\n\t\t\t//if (p_index != m_track + 1) throw exception_cue(\"cuesheet tracks out of order\",0);\r\n\t\t\tif (m_track != 0) finalize_track();\r\n\t\t\tif (m_file.is_empty()) throw exception_cue(\"declaring a track with no file set\",0);\r\n\t\t\tm_trackfile = m_file;\r\n\t\t\tm_track = p_index;\r\n\t\t}\r\n\t\t\r\n\t\tvoid on_pregap(unsigned p_value)\r\n\t\t{\r\n\t\t\tm_pregap = (double) p_value / 75.0;\r\n\t\t}\r\n\r\n\t\tvoid on_index(unsigned p_index,unsigned p_value)\r\n\t\t{\r\n\t\t\tif (p_index < t_cuesheet_index_list::count)\r\n\t\t\t{\r\n\t\t\t\tswitch(p_index)\r\n\t\t\t\t{\r\n\t\t\t\tcase 0:\tm_index0_set = true; break;\r\n\t\t\t\tcase 1: m_index1_set = true; break;\r\n\t\t\t\t}\r\n\t\t\t\tm_indexes.m_positions[p_index] = (double) p_value / 75.0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid on_title(const char * p_title,t_size p_title_length) {}\r\n\t\tvoid on_performer(const char * p_performer,t_size p_performer_length) {}\r\n\t\tvoid on_songwriter(const char * p_performer,t_size p_performer_length) {}\r\n\t\tvoid on_isrc(const char * p_isrc,t_size p_isrc_length) {}\r\n\t\tvoid on_catalog(const char * p_catalog,t_size p_catalog_length) {}\r\n\t\tvoid on_comment(const char * p_comment,t_size p_comment_length) {}\t\t\r\n\t\tvoid finalize()\r\n\t\t{\r\n\t\t\tif (m_track != 0)\r\n\t\t\t{\r\n\t\t\t\tfinalize_track(); \r\n\t\t\t\tm_track = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid on_flags(const char * p_flags,t_size p_flags_length) {\r\n\t\t\tm_flags.set_string(p_flags,p_flags_length);\r\n\t\t}\r\n\tprivate:\r\n\t\tvoid finalize_track()\r\n\t\t{\r\n\t\t\tif (m_track < 1 || m_track > 99) throw exception_cue(\"track number out of range\",0);\r\n\t\t\tif (!m_index1_set) throw exception_cue(\"INDEX 01 not set\",0);\r\n\t\t\tif (!m_index0_set) m_indexes.m_positions[0] = m_indexes.m_positions[1] - m_pregap;\r\n\t\t\tif (!m_indexes.is_valid()) throw exception_cue(\"invalid index list\");\r\n\r\n\t\t\tcue_creator::t_entry_list::iterator iter;\r\n\t\t\titer = m_out.insert_last();\r\n\t\t\titer->m_track_number = m_track;\r\n\t\t\titer->m_file = m_trackfile;\r\n\t\t\titer->m_index_list = m_indexes;\t\t\t\r\n\t\t\titer->m_flags = m_flags;\r\n\t\t\tm_pregap = 0;\r\n\t\t\tm_indexes.reset();\r\n\t\t\tm_index0_set = m_index1_set = false;\r\n\t\t\tm_flags.reset();\r\n\t\t}\r\n\r\n\t\tbool m_index0_set,m_index1_set;\r\n\t\tdouble m_pregap;\r\n\t\tunsigned m_track;\r\n\t\tcue_creator::t_entry_list & m_out;\r\n\t\tpfc::string8 m_file,m_trackfile,m_flags;\r\n\t\tt_cuesheet_index_list m_indexes;\r\n\t};\r\n}\r\n\r\nvoid cue_parser::parse_full(const char * p_cuesheet,cue_creator::t_entry_list & p_out) {\r\n\ttry {\r\n\t\t{\r\n\t\t\tcue_parser_callback_retrievecreatorentries callback(p_out);\r\n\t\t\tg_parse_cue(p_cuesheet,callback);\r\n\t\t\tcallback.finalize();\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\tcue_creator::t_entry_list::iterator iter;\r\n\t\t\tfor(iter=p_out.first();iter.is_valid();++iter)\r\n\t\t\t{\r\n\t\t\t\tcue_parser_callback_retrieveinfo callback(iter->m_infos,iter->m_track_number);\r\n\t\t\t\tg_parse_cue(p_cuesheet,callback);\r\n\t\t\t\tcallback.finalize();\r\n\t\t\t}\r\n\t\t}\r\n\t} catch(exception_cue const & e) {\r\n\t\tthrow exception_bad_cuesheet(pfc::string_formatter() << \"Error parsing cuesheet: \" << e.what());\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cue_parser.h",
    "content": "//HINT: for info on how to generate an embedded cuesheet enabled input, see the end of this header.\r\n\r\n//to be moved somewhere else later\r\nnamespace file_info_record_helper {\r\n\r\n\tclass __file_info_record__info__enumerator {\r\n\tpublic:\r\n\t\t__file_info_record__info__enumerator(file_info & p_out) : m_out(p_out) {}\r\n\t\tvoid operator() (const char * p_name,const char * p_value) {m_out.__info_add_unsafe(p_name,p_value);}\r\n\tprivate:\r\n\t\tfile_info & m_out;\r\n\t};\r\n\r\n\tclass __file_info_record__meta__enumerator {\r\n\tpublic:\r\n\t\t__file_info_record__meta__enumerator(file_info & p_out) : m_out(p_out) {}\r\n\t\ttemplate<typename t_value> void operator() (const char * p_name,const t_value & p_value) {\r\n\t\t\tt_size index = infinite;\r\n\t\t\tfor(typename t_value::const_iterator iter = p_value.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\tif (index == infinite) index = m_out.__meta_add_unsafe(p_name,*iter);\r\n\t\t\t\telse m_out.meta_add_value(index,*iter);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tfile_info & m_out;\r\n\t};\r\n\r\n\tclass file_info_record {\r\n\tpublic:\r\n\t\ttypedef pfc::chain_list_t<pfc::string8> t_meta_value;\r\n\t\ttypedef pfc::map_t<pfc::string8,t_meta_value,file_info::field_name_comparator> t_meta_map;\r\n\t\ttypedef pfc::map_t<pfc::string8,pfc::string8,file_info::field_name_comparator> t_info_map;\r\n\r\n\t\tfile_info_record() : m_replaygain(replaygain_info_invalid), m_length(0) {}\r\n\r\n\t\treplaygain_info get_replaygain() const {return m_replaygain;}\r\n\t\tvoid set_replaygain(const replaygain_info & p_replaygain) {m_replaygain = p_replaygain;}\r\n\t\tdouble get_length() const {return m_length;}\r\n\t\tvoid set_length(double p_length) {m_length = p_length;}\r\n\r\n\t\tvoid reset() {\r\n\t\t\tm_meta.remove_all(); m_info.remove_all();\r\n\t\t\tm_length = 0;\r\n\t\t\tm_replaygain = replaygain_info_invalid;\r\n\t\t}\r\n\r\n\t\tvoid from_info_overwrite_info(const file_info & p_info) {\r\n\t\t\tfor(t_size infowalk = 0, infocount = p_info.info_get_count(); infowalk < infocount; ++infowalk) {\r\n\t\t\t\tm_info.set(p_info.info_enum_name(infowalk),p_info.info_enum_value(infowalk));\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid from_info_overwrite_meta(const file_info & p_info) {\r\n\t\t\tfor(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) {\r\n\t\t\t\tconst t_size valuecount = p_info.meta_enum_value_count(metawalk);\r\n\t\t\t\tif (valuecount > 0) {\r\n\t\t\t\t\tt_meta_value & entry = m_meta.find_or_add(p_info.meta_enum_name(metawalk));\r\n\t\t\t\t\tentry.remove_all();\r\n\t\t\t\t\tfor(t_size valuewalk = 0; valuewalk < valuecount; ++valuewalk) {\r\n\t\t\t\t\t\tentry.insert_last(p_info.meta_enum_value(metawalk,valuewalk));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid from_info_overwrite_rg(const file_info & p_info) {\r\n\t\t\tm_replaygain = replaygain_info::g_merge(m_replaygain,p_info.get_replaygain());\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tvoid overwrite_meta(const t_source & p_meta) {\r\n\t\t\tm_meta.overwrite(p_meta);\r\n\t\t}\r\n\t\ttemplate<typename t_source>\r\n\t\tvoid overwrite_info(const t_source & p_info) {\r\n\t\t\tm_info.overwrite(p_info);\r\n\t\t}\r\n\r\n\t\tvoid merge_overwrite(const file_info & p_info) {\r\n\t\t\tfrom_info_overwrite_info(p_info);\r\n\t\t\tfrom_info_overwrite_meta(p_info);\r\n\t\t\tfrom_info_overwrite_rg(p_info);\r\n\t\t}\r\n\r\n\t\tvoid transfer_meta_entry(const char * p_name,const file_info & p_info,t_size p_index) {\r\n\t\t\tconst t_size count = p_info.meta_enum_value_count(p_index);\r\n\t\t\tif (count == 0) {\r\n\t\t\t\tm_meta.remove(p_name);\r\n\t\t\t} else {\r\n\t\t\t\tt_meta_value & val = m_meta.find_or_add(p_name);\r\n\t\t\t\tval.remove_all();\r\n\t\t\t\tfor(t_size walk = 0; walk < count; ++walk) {\r\n\t\t\t\t\tval.insert_last(p_info.meta_enum_value(p_index,walk));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid meta_set(const char * p_name,const char * p_value) {\r\n\t\t\tm_meta.find_or_add(p_name).set_single(p_value);\r\n\t\t}\r\n\r\n\t\tconst t_meta_value * meta_query_ptr(const char * p_name) const {\r\n\t\t\treturn m_meta.query_ptr(p_name);\r\n\t\t}\r\n\r\n\r\n\t\tvoid from_info_set_meta(const file_info & p_info) {\r\n\t\t\tm_meta.remove_all();\r\n\t\t\tfrom_info_overwrite_meta(p_info);\r\n\t\t}\r\n\r\n\t\tvoid from_info(const file_info & p_info) {\r\n\t\t\treset();\r\n\t\t\tm_length = p_info.get_length();\r\n\t\t\tm_replaygain = p_info.get_replaygain();\r\n\t\t\tfrom_info_overwrite_meta(p_info);\r\n\t\t\tfrom_info_overwrite_info(p_info);\r\n\t\t}\r\n\t\tvoid to_info(file_info & p_info) const {\r\n\t\t\tp_info.reset();\r\n\t\t\tp_info.set_length(m_length);\r\n\t\t\tp_info.set_replaygain(m_replaygain);\r\n\t\t\tm_info.enumerate(__file_info_record__info__enumerator(p_info));\r\n\t\t\tm_meta.enumerate(__file_info_record__meta__enumerator(p_info));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback> void enumerate_meta(t_callback & p_callback) const {m_meta.enumerate(p_callback);}\r\n\t\ttemplate<typename t_callback> void enumerate_meta(t_callback & p_callback) {m_meta.enumerate(p_callback);}\r\n\r\n\t//private:\r\n\t\tt_meta_map m_meta;\r\n\t\tt_info_map m_info;\r\n\t\treplaygain_info m_replaygain;\r\n\t\tdouble m_length;\r\n\t};\r\n\r\n}//namespace file_info_record_helper\r\n\r\n\r\nnamespace cue_parser\r\n{\r\n\tstruct cue_entry {\r\n\t\tpfc::string8 m_file;\r\n\t\tunsigned m_track_number;\r\n\t\tt_cuesheet_index_list m_indexes;\r\n\t};\r\n\r\n\r\n\tPFC_DECLARE_EXCEPTION(exception_bad_cuesheet,exception_io_data,\"Invalid cuesheet\");\r\n\r\n\t//! Throws exception_bad_cuesheet on failure.\r\n\tvoid parse(const char *p_cuesheet,pfc::chain_list_t<cue_entry> & p_out);\r\n\t//! Throws exception_bad_cuesheet on failure.\r\n\tvoid parse_info(const char *p_cuesheet,file_info & p_info,unsigned p_index);\r\n\t//! Throws exception_bad_cuesheet on failure.\r\n\tvoid parse_full(const char * p_cuesheet,cue_creator::t_entry_list & p_out);\r\n\r\n\t\r\n\r\n\tstruct track_record {\r\n\t\tfile_info_record_helper::file_info_record m_info;\r\n\t\tpfc::string8 m_file,m_flags;\r\n\t\tt_cuesheet_index_list m_index_list;\r\n\t};\r\n\r\n\ttypedef pfc::map_t<unsigned,track_record> track_record_list;\r\n\r\n\tclass embeddedcue_metadata_manager {\r\n\tpublic:\r\n\t\tvoid get_tag(file_info & p_info) const;\r\n\t\tvoid set_tag(file_info const & p_info);\r\n\r\n\t\tvoid get_track_info(unsigned p_track,file_info & p_info) const;\r\n\t\tvoid set_track_info(unsigned p_track,file_info const & p_info);\r\n\t\tvoid query_track_offsets(unsigned p_track,double & p_begin,double & p_length) const;\r\n\t\tbool have_cuesheet() const;\r\n\t\tunsigned remap_trackno(unsigned p_index) const;\r\n\t\tt_size get_cue_track_count() const;\r\n\tprivate:\r\n\t\ttrack_record_list m_content;\r\n\t};\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tclass __decoder_wrapper {\r\n\tpublic:\r\n\t\tvirtual bool run(audio_chunk & p_chunk,abort_callback & p_abort) = 0;\r\n\t\tvirtual void seek(double p_seconds,abort_callback & p_abort) = 0;\r\n\t\tvirtual bool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) = 0;\r\n\t\tvirtual bool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) = 0;\r\n\t\tvirtual void on_idle(abort_callback & p_abort) = 0;\r\n\t\tvirtual ~__decoder_wrapper() {}\r\n\t};\r\n\r\n\ttemplate<typename t_input>\r\n\tclass __decoder_wrapper_simple : public __decoder_wrapper {\r\n\tpublic:\r\n\t\tvoid initialize(service_ptr_t<file> p_filehint,const char * p_path,unsigned p_flags,abort_callback & p_abort) {\r\n\t\t\tm_input.open(p_filehint,p_path,input_open_decode,p_abort);\r\n\t\t\tm_input.decode_initialize(p_flags,p_abort);\r\n\t\t}\r\n\t\tbool run(audio_chunk & p_chunk,abort_callback & p_abort) {return m_input.decode_run(p_chunk,p_abort);}\r\n\t\tvoid seek(double p_seconds,abort_callback & p_abort) {m_input.decode_seek(p_seconds,p_abort);}\r\n\t\tbool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {return m_input.decode_get_dynamic_info(p_out,p_timestamp_delta);}\r\n\t\tbool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return m_input.decode_get_dynamic_info_track(p_out,p_timestamp_delta);}\r\n\t\tvoid on_idle(abort_callback & p_abort) {m_input.decode_on_idle(p_abort);}\r\n\tprivate:\r\n\t\tt_input m_input;\r\n\t};\r\n\r\n\tclass __decoder_wrapper_cue : public __decoder_wrapper {\r\n\tpublic:\r\n\t\tvoid open(service_ptr_t<file> p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,double p_start,double p_length) {\r\n\t\t\tm_input.open(p_filehint,p_location,p_flags,p_abort,p_start,p_length);\r\n\t\t}\r\n\t\tbool run(audio_chunk & p_chunk,abort_callback & p_abort) {return m_input.run(p_chunk,p_abort);}\r\n\t\tvoid seek(double p_seconds,abort_callback & p_abort) {m_input.seek(p_seconds,p_abort);}\r\n\t\tbool get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {return m_input.get_dynamic_info(p_out,p_timestamp_delta);}\r\n\t\tbool get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {return m_input.get_dynamic_info_track(p_out,p_timestamp_delta);}\r\n\t\tvoid on_idle(abort_callback & p_abort) {m_input.on_idle(p_abort);}\r\n\r\n\tprivate:\r\n\t\tinput_helper_cue m_input;\r\n\t};\r\n\r\n\ttemplate<typename t_base>\r\n\tclass input_wrapper_cue_t {\r\n\tpublic:\r\n\t\tinput_wrapper_cue_t() {}\r\n\t\t~input_wrapper_cue_t() {}\r\n\r\n\t\tvoid open(service_ptr_t<file> p_filehint,const char * p_path,t_input_open_reason p_reason,abort_callback & p_abort) {\r\n\t\t\tm_path = p_path;\r\n\r\n\t\t\tm_file = p_filehint;\r\n\t\t\tinput_open_file_helper(m_file,p_path,p_reason,p_abort);\r\n\r\n\t\t\t{\r\n\t\t\t\tfile_info_impl info;\r\n\t\t\t\tt_base instance;\r\n\t\t\t\tinstance.open(m_file,p_path,p_reason,p_abort);\r\n\t\t\t\tinstance.get_info(info,p_abort);\r\n\t\t\t\tm_meta.set_tag(info);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tt_uint32 get_subsong_count() {\r\n\t\t\treturn m_meta.have_cuesheet() ? m_meta.get_cue_track_count() : 1;\r\n\t\t}\r\n\r\n\t\tt_uint32 get_subsong(t_uint32 p_index) {\r\n\t\t\treturn m_meta.have_cuesheet() ? m_meta.remap_trackno(p_index) : 0;\r\n\t\t}\r\n\r\n\t\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {\r\n\t\t\tif (p_subsong == 0) {\r\n\t\t\t\tm_meta.get_tag(p_info);\r\n\t\t\t} else {\r\n\t\t\t\tm_meta.get_track_info(p_subsong,p_info);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tt_filestats get_file_stats(abort_callback & p_abort) {return m_file->get_stats(p_abort);}\r\n\r\n\t\tvoid decode_initialize(t_uint32 p_subsong,unsigned p_flags,abort_callback & p_abort) {\r\n\t\t\tm_decoder.release();\r\n\t\t\tif (p_subsong == 0) {\r\n\t\t\t\tpfc::rcptr_t<__decoder_wrapper_simple<t_base> > temp;\r\n\t\t\t\ttemp.new_t();\r\n\t\t\t\tm_file->reopen(p_abort);\r\n\t\t\t\ttemp->initialize(m_file,m_path,p_flags,p_abort);\r\n\t\t\t\tm_decoder = temp;\r\n\t\t\t} else {\r\n\t\t\t\tdouble start,length;\r\n\t\t\t\tm_meta.query_track_offsets(p_subsong,start,length);\r\n\r\n\t\t\t\tpfc::rcptr_t<__decoder_wrapper_cue> temp;\r\n\t\t\t\ttemp.new_t();\r\n\t\t\t\tm_file->reopen(p_abort);\r\n\t\t\t\ttemp->open(m_file,make_playable_location(m_path,0),p_flags & ~input_flag_no_seeking,p_abort,start,length);\r\n\t\t\t\tm_decoder = temp;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbool decode_run(audio_chunk & p_chunk,abort_callback & p_abort) {\r\n\t\t\treturn m_decoder->run(p_chunk,p_abort);\r\n\t\t}\r\n\t\t\r\n\t\tvoid decode_seek(double p_seconds,abort_callback & p_abort) {\r\n\t\t\tm_decoder->seek(p_seconds,p_abort);\r\n\t\t}\r\n\t\t\r\n\t\tbool decode_can_seek() {return true;}\r\n\r\n\t\tbool decode_get_dynamic_info(file_info & p_out, double & p_timestamp_delta) {\r\n\t\t\treturn m_decoder->get_dynamic_info(p_out,p_timestamp_delta);\r\n\t\t}\r\n\r\n\t\tbool decode_get_dynamic_info_track(file_info & p_out, double & p_timestamp_delta) {\r\n\t\t\treturn m_decoder->get_dynamic_info_track(p_out,p_timestamp_delta);\r\n\t\t}\r\n\r\n\t\tvoid decode_on_idle(abort_callback & p_abort) {\r\n\t\t\tm_decoder->on_idle(p_abort);\r\n\t\t}\r\n\r\n\t\tvoid retag_set_info(t_uint32 p_subsong,const file_info & p_info,abort_callback & p_abort) {\r\n\t\t\tpfc::dynamic_assert(m_decoder.is_empty());\r\n\t\t\tif (p_subsong == 0) {\r\n\t\t\t\tm_meta.set_tag(p_info);\r\n\t\t\t} else {\r\n\t\t\t\tm_meta.set_track_info(p_subsong,p_info);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid retag_commit(abort_callback & p_abort) {\r\n\t\t\tpfc::dynamic_assert(m_decoder.is_empty());\r\n\r\n\t\t\tfile_info_impl info;\r\n\t\t\tm_meta.get_tag(info);\r\n\t\t\t\r\n\t\t\t{\r\n\t\t\t\tt_base instance;\r\n\t\t\t\tm_file->reopen(p_abort);\r\n\t\t\t\tinstance.open(m_file,m_path,input_open_info_write,p_abort);\r\n\t\t\t\tinstance.retag(pfc::safe_cast<const file_info&>(info),p_abort);\r\n\t\t\t\tinfo.reset();\r\n\t\t\t\tinstance.get_info(info,p_abort);\r\n\t\t\t\tm_meta.set_tag(info);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tinline static bool g_is_our_content_type(const char * p_content_type) {return t_base::g_is_our_content_type(p_content_type);}\r\n\t\tinline static bool g_is_our_path(const char * p_path,const char * p_extension) {return t_base::g_is_our_path(p_path,p_extension);}\r\n\r\n\tprivate:\r\n\t\tpfc::rcptr_t<__decoder_wrapper> m_decoder;\r\n\r\n\t\tfile_info_impl m_info;\r\n\t\tpfc::string8 m_path;\r\n\t\tservice_ptr_t<file> m_file;\r\n\r\n\t\tembeddedcue_metadata_manager m_meta;\r\n\t};\r\n\r\n\ttemplate<typename I>\r\n\tclass chapterizer_impl_t : public chapterizer\r\n\t{\r\n\tpublic:\r\n\t\tbool is_our_file(const char * p_path,abort_callback & p_abort) \r\n\t\t{\r\n\t\t\treturn I::g_is_our_path(p_path,pfc::string_extension(p_path));\r\n\t\t}\r\n\r\n\t\tvoid set_chapters(const char * p_path,chapter_list const & p_list,abort_callback & p_abort) {\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tinput_wrapper_cue_t<I> instance;\r\n\t\t\tinstance.open(0,p_path,input_open_info_write,p_abort);\r\n\r\n\t\t\t//stamp the cuesheet first\r\n\t\t\t{\r\n\t\t\t\tfile_info_impl info;\r\n\t\t\t\tinstance.get_info(0,info,p_abort);\r\n\r\n\t\t\t\tpfc::string_formatter cuesheet;\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t{\r\n\t\t\t\t\tcue_creator::t_entry_list entries;\r\n\t\t\t\t\tt_size n, m = p_list.get_chapter_count();\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\tdouble offset_acc = 0;\r\n\t\t\t\t\tfor(n=0;n<m;n++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcue_creator::t_entry_list::iterator entry;\r\n\t\t\t\t\t\tentry = entries.insert_last();\r\n\t\t\t\t\t\tentry->m_infos = p_list.get_info(n);\r\n\t\t\t\t\t\tentry->m_file = \"CDImage.wav\";\r\n\t\t\t\t\t\tentry->m_track_number = (unsigned)(n+1);\r\n\t\t\t\t\t\tentry->m_index_list.from_infos(entry->m_infos,offset_acc);\r\n\t\t\t\t\t\toffset_acc += entry->m_infos.get_length();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcue_creator::create(cuesheet,entries);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinfo.meta_set(\"cuesheet\",cuesheet);\r\n\r\n\t\t\t\tinstance.retag_set_info(0,info,p_abort);\r\n\t\t\t}\r\n\t\t\t//stamp per-chapter infos\r\n\t\t\tfor(t_size walk = 0, total = p_list.get_chapter_count(); walk < total; ++walk) {\r\n\t\t\t\tinstance.retag_set_info(walk + 1, p_list.get_info(walk),p_abort);\r\n\t\t\t}\r\n\r\n\t\t\tinstance.retag_commit(p_abort);\r\n\t\t}\r\n\r\n\t\tvoid get_chapters(const char * p_path,chapter_list & p_list,abort_callback & p_abort) {\r\n\r\n\t\t\tinput_wrapper_cue_t<I> instance;\r\n\r\n\r\n\t\t\tinstance.open(0,p_path,input_open_info_read,p_abort);\r\n\r\n\t\t\tconst t_uint32 total = instance.get_subsong_count();\r\n\r\n\t\t\tp_list.set_chapter_count(total);\r\n\t\t\tfor(t_uint32 walk = 0; walk < total; ++walk) {\r\n\t\t\t\tfile_info_impl info;\r\n\t\t\t\tinstance.get_info(instance.get_subsong(walk),info,p_abort);\r\n\t\t\t\tp_list.set_info(walk,info);\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n};\r\n\r\n//! Wrapper template for generating embedded cuesheet enabled inputs.\r\n//! t_input_impl is a singletrack input implementation (see input_singletrack_impl for method declarations).\r\n//! To declare an embedded cuesheet enabled input, change your input declaration from input_singletrack_factory_t<myinput> to input_cuesheet_factory_t<myinput>.\r\ntemplate<typename t_input_impl>\r\nclass input_cuesheet_factory_t {\r\npublic:\r\n\tinput_factory_t<cue_parser::input_wrapper_cue_t<t_input_impl> > m_input_factory;\r\n\tservice_factory_single_t<cue_parser::chapterizer_impl_t<t_input_impl> > m_chapterizer_factory;\t\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cue_parser_embedding.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nusing namespace cue_parser;\r\nusing namespace file_info_record_helper;\r\nstatic void build_cue_meta_name(const char * p_name,unsigned p_tracknumber,pfc::string_base & p_out) {\r\n\tp_out.reset();\r\n\tp_out << \"cue_track\" << pfc::format_uint(p_tracknumber % 100,2) << \"_\" << p_name;\r\n}\r\n\r\nstatic bool is_reserved_meta_entry(const char * p_name) {\r\n\treturn file_info::field_name_comparator::compare(p_name,\"cuesheet\") == 0;\r\n}\r\n\r\nstatic bool is_global_meta_entry(const char * p_name) {\r\n\tstatic const char header[] = \"cue_track\";\r\n\treturn pfc::stricmp_ascii_ex(p_name,strlen(header),header,infinite) != 0;\r\n}\r\nstatic bool is_allowed_field(const char * p_name) {\r\n\treturn !is_reserved_meta_entry(p_name) && is_global_meta_entry(p_name);\r\n}\r\nnamespace {\r\n\tclass __get_tag_cue_track_list_builder {\r\n\tpublic:\r\n\t\t__get_tag_cue_track_list_builder(cue_creator::t_entry_list & p_entries) : m_entries(p_entries) {}\r\n\t\tvoid operator() (unsigned p_trackno,const track_record & p_record) {\r\n\t\t\tif (p_trackno > 0) {\r\n\t\t\t\tcue_creator::t_entry_list::iterator iter = m_entries.insert_last();\r\n\t\t\t\titer->m_file = p_record.m_file;\r\n\t\t\t\titer->m_flags = p_record.m_flags;\r\n\t\t\t\titer->m_index_list = p_record.m_index_list;\r\n\t\t\t\titer->m_track_number = p_trackno;\r\n\t\t\t\tp_record.m_info.to_info(iter->m_infos);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tcue_creator::t_entry_list & m_entries;\r\n\t};\r\n\r\n\ttypedef pfc::avltree_t<pfc::string8,file_info::field_name_comparator> field_name_list;\r\n\r\n\tclass __get_tag__enum_fields_enumerator {\r\n\tpublic:\r\n\t\t__get_tag__enum_fields_enumerator(field_name_list & p_out) : m_out(p_out) {}\r\n\t\tvoid operator() (unsigned p_trackno,const track_record & p_record) {\r\n\t\t\tif (p_trackno > 0) p_record.m_info.enumerate_meta(*this);\r\n\t\t}\r\n\t\ttemplate<typename t_value> void operator() (const char * p_name,const t_value & p_value) {\r\n\t\t\tm_out.add(p_name);\r\n\t\t}\r\n\tprivate:\r\n\t\tfield_name_list & m_out;\r\n\t};\r\n\r\n\r\n\tclass __get_tag__is_field_global_check {\r\n\tprivate:\r\n\t\ttypedef file_info_record::t_meta_value t_value;\r\n\tpublic:\r\n\t\t__get_tag__is_field_global_check(const char * p_field) : m_field(p_field), m_value(NULL), m_state(true) {}\r\n\t\t\r\n\t\tvoid operator() (unsigned p_trackno,const track_record & p_record) {\r\n\t\t\tif (p_trackno > 0 && m_state) {\r\n\t\t\t\tconst t_value * val = p_record.m_info.meta_query_ptr(m_field);\r\n\t\t\t\tif (val == NULL) {m_state = false; return;}\r\n\t\t\t\tif (m_value == NULL) {\r\n\t\t\t\t\tm_value = val;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (pfc::comparator_chainlist<pfc::comparator_strcmp>::compare(*m_value,*val) != 0) {\r\n\t\t\t\t\t\tm_state = false; return;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid finalize(file_info_record::t_meta_map & p_globals) {\r\n\t\t\tif (m_state && m_value != NULL) {\r\n\t\t\t\tp_globals.set(m_field,*m_value);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tconst char * const m_field;\r\n\t\tconst t_value * m_value;\r\n\t\tbool m_state;\r\n\t};\r\n\r\n\tclass __get_tag__filter_globals {\r\n\tpublic:\r\n\t\t__get_tag__filter_globals(track_record_list const & p_tracks,file_info_record::t_meta_map & p_globals) : m_tracks(p_tracks), m_globals(p_globals) {}\r\n\r\n\t\tvoid operator() (const char * p_field) {\r\n\t\t\tif (is_allowed_field(p_field)) {\r\n\t\t\t\t__get_tag__is_field_global_check wrapper(p_field);\r\n\t\t\t\tm_tracks.enumerate(wrapper);\r\n\t\t\t\twrapper.finalize(m_globals);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tconst track_record_list & m_tracks;\r\n\t\tfile_info_record::t_meta_map & m_globals;\r\n\t};\r\n\r\n\tclass __get_tag__local_field_filter {\r\n\tpublic:\r\n\t\t__get_tag__local_field_filter(const file_info_record::t_meta_map & p_globals,file_info_record::t_meta_map & p_output) : m_globals(p_globals), m_output(p_output), m_currenttrack(0) {}\r\n\t\tvoid operator() (unsigned p_trackno,const track_record & p_track) {\r\n\t\t\tif (p_trackno > 0) {\r\n\t\t\t\tm_currenttrack = p_trackno;\r\n\t\t\t\tp_track.m_info.enumerate_meta(*this);\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid operator() (const char * p_name,const file_info_record::t_meta_value & p_value) {\r\n\t\t\tPFC_ASSERT(m_currenttrack > 0);\r\n\t\t\tif (!m_globals.have_item(p_name)) {\r\n\t\t\t\tbuild_cue_meta_name(p_name,m_currenttrack,m_buffer);\r\n\t\t\t\tm_output.set(m_buffer,p_value);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tunsigned m_currenttrack;\r\n\t\tpfc::string8_fastalloc m_buffer;\r\n\t\tconst file_info_record::t_meta_map & m_globals;\r\n\t\tfile_info_record::t_meta_map & m_output;\r\n\t};\r\n};\r\n\r\nstatic void strip_redundant_track_meta(unsigned p_tracknumber,const file_info & p_cueinfo,file_info_record::t_meta_map & p_meta,const char * p_metaname) {\r\n\tt_size metaindex = p_cueinfo.meta_find(p_metaname);\r\n\tif (metaindex == infinite) return;\r\n\tpfc::string_formatter namelocal;\r\n\tbuild_cue_meta_name(p_metaname,p_tracknumber,namelocal);\r\n\t{\r\n\t\tconst file_info_record::t_meta_value * val = p_meta.query_ptr(namelocal);\r\n\t\tif (val == NULL) return;\r\n\t\tfile_info_record::t_meta_value::const_iterator iter = val->first();\r\n\t\tfor(t_size valwalk = 0, valcount = p_cueinfo.meta_enum_value_count(metaindex); valwalk < valcount; ++valwalk) {\r\n\t\t\tif (iter.is_empty()) return;\r\n\t\t\tif (strcmp(*iter,p_cueinfo.meta_enum_value(metaindex,valwalk)) != 0) return;\r\n\t\t\t++iter;\r\n\t\t}\r\n\t\tif (!iter.is_empty()) return;\r\n\t}\r\n\t//success\r\n\tp_meta.remove(namelocal);\r\n}\r\n\r\nvoid embeddedcue_metadata_manager::get_tag(file_info & p_info) const {\r\n\tif (!have_cuesheet()) {\r\n\t\tm_content.query_ptr((unsigned)0)->m_info.to_info(p_info);\r\n\t\tp_info.meta_remove_field(\"cuesheet\");\r\n\t} else {\r\n\t\tcue_creator::t_entry_list entries;\r\n\t\tm_content.enumerate(__get_tag_cue_track_list_builder(entries));\r\n\t\tpfc::string_formatter cuesheet;\r\n\t\tcue_creator::create(cuesheet,entries);\r\n\t\tentries.remove_all();\r\n\t\t//parse it back to see what info got stored in the cuesheet and what needs to be stored outside cuesheet in the tags\r\n\t\tcue_parser::parse_full(cuesheet,entries);\r\n\t\tfile_info_record output;\r\n\r\n\t\t\r\n\t\t\r\n\r\n\t\t{\r\n\t\t\tfile_info_record::t_meta_map globals;\r\n\t\t\t//1. find global infos and forward them\r\n\t\t\t{\r\n\t\t\t\tfield_name_list fields;\r\n\t\t\t\tm_content.enumerate(__get_tag__enum_fields_enumerator(fields));\r\n\t\t\t\tfields.enumerate(__get_tag__filter_globals(m_content,globals));\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\toutput.overwrite_meta(globals);\r\n\r\n\t\t\t//2. find local infos\r\n\t\t\tm_content.enumerate(__get_tag__local_field_filter(globals,output.m_meta));\r\n\t\t}\r\n\t\t\r\n\r\n\t\t//strip redundant titles and tracknumbers that the cuesheet already contains\r\n\t\tfor(cue_creator::t_entry_list::const_iterator iter = entries.first(); iter.is_valid(); ++iter) {\r\n\t\t\tstrip_redundant_track_meta(iter->m_track_number,iter->m_infos,output.m_meta,\"tracknumber\");\r\n\t\t\tstrip_redundant_track_meta(iter->m_track_number,iter->m_infos,output.m_meta,\"title\");\r\n\t\t}\r\n\r\n\r\n\t\t//add tech infos etc\r\n\r\n\t\t{\r\n\t\t\tconst track_record * rec = m_content.query_ptr((unsigned)0);\r\n\t\t\tif (rec != NULL) {\r\n\t\t\t\toutput.set_length(rec->m_info.get_length());\r\n\t\t\t\toutput.set_replaygain(rec->m_info.get_replaygain());\r\n\t\t\t\toutput.overwrite_info(rec->m_info.m_info);\r\n\t\t\t}\r\n\t\t}\r\n\t\toutput.meta_set(\"cuesheet\",cuesheet);\r\n\t\toutput.to_info(p_info);\r\n\t}\r\n}\r\n\r\nstatic bool resolve_cue_meta_name(const char * p_name,pfc::string_base & p_outname,unsigned & p_tracknumber) {\r\n\t//\"cue_trackNN_fieldname\"\r\n\tstatic const char header[] = \"cue_track\";\r\n\tif (pfc::stricmp_ascii_ex(p_name,strlen(header),header,infinite) != 0) return false;\r\n\tp_name += strlen(header);\r\n\tif (!pfc::char_is_numeric(p_name[0]) || !pfc::char_is_numeric(p_name[1]) || p_name[2] != '_') return false;\r\n\tunsigned tracknumber = pfc::atoui_ex(p_name,2);\r\n\tif (tracknumber == 0) return false;\r\n\tp_name += 3;\r\n\tp_tracknumber = tracknumber;\r\n\tp_outname = p_name;\r\n\treturn true;\r\n}\r\n\r\n\r\nnamespace {\r\n\tclass __set_tag_global_field_relay {\r\n\tpublic:\r\n\t\t__set_tag_global_field_relay(const file_info & p_info,t_size p_index) : m_info(p_info), m_index(p_index) {}\r\n\t\tvoid operator() (unsigned p_trackno,track_record & p_record) {\r\n\t\t\tif (p_trackno > 0) {\r\n\t\t\t\tp_record.m_info.transfer_meta_entry(m_info.meta_enum_name(m_index),m_info,m_index);\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tconst file_info & m_info;\r\n\t\tconst t_size m_index;\r\n\t};\r\n}\r\n\r\nvoid embeddedcue_metadata_manager::set_tag(file_info const & p_info) {\r\n\tm_content.remove_all();\r\n\t\r\n\t{\r\n\t\ttrack_record & track0 = m_content.find_or_add((unsigned)0);\r\n\t\ttrack0.m_info.from_info(p_info);\r\n\t\ttrack0.m_info.m_info.set(\"cue_embedded\",\"no\");\r\n\t}\r\n\t\r\n\t\r\n\r\n\tconst char * cuesheet = p_info.meta_get(\"cuesheet\",0);\r\n\tif (cuesheet == NULL) {\r\n\t\treturn;\r\n\t}\r\n\r\n\t//processing order\r\n\t//1. cuesheet content\r\n\t//2. overwrite with global metadata from the tag\r\n\t//2. overwrite with local metadata from the tag\r\n\r\n\t{\r\n\t\tcue_creator::t_entry_list entries;\r\n\t\ttry {\r\n\t\t\tcue_parser::parse_full(cuesheet,entries);\r\n\t\t} catch(exception_io_data const & e) {\r\n\t\t\tconsole::formatter() << e;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tfor(cue_creator::t_entry_list::const_iterator iter = entries.first(); iter.is_valid(); ) {\r\n\t\t\tcue_creator::t_entry_list::const_iterator next = iter;\r\n\t\t\t++next;\r\n\t\t\ttrack_record & entry = m_content.find_or_add(iter->m_track_number);\r\n\t\t\tentry.m_file = iter->m_file;\r\n\t\t\tentry.m_flags = iter->m_flags;\r\n\t\t\tentry.m_index_list = iter->m_index_list;\r\n\t\t\tentry.m_info.from_info(iter->m_infos);\r\n\t\t\tentry.m_info.from_info_overwrite_info(p_info);\r\n\t\t\tentry.m_info.m_info.set(\"cue_embedded\",\"yes\");\r\n\t\t\tdouble begin = entry.m_index_list.start(), end = next.is_valid() ? next->m_index_list.start() : p_info.get_length();\r\n\t\t\tif (end <= begin) throw exception_io_data();\r\n\t\t\tentry.m_info.set_length(end - begin);\r\n\t\t\titer = next;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) {\r\n\t\tconst char * name = p_info.meta_enum_name(metawalk);\r\n\t\tconst t_size valuecount = p_info.meta_enum_value_count(metawalk);\r\n\t\tif (valuecount > 0 && !is_reserved_meta_entry(name) && is_global_meta_entry(name)) {\r\n\t\t\t__set_tag_global_field_relay relay(p_info,metawalk);\r\n\t\t\tm_content.enumerate(relay);\r\n\t\t}\r\n\t}\r\n\r\n\t{\r\n\t\tpfc::string8_fastalloc namebuffer;\r\n\t\tfor(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk) {\r\n\t\t\tconst char * name = p_info.meta_enum_name(metawalk);\r\n\t\t\tconst t_size valuecount = p_info.meta_enum_value_count(metawalk);\r\n\t\t\tunsigned trackno;\r\n\t\t\tif (valuecount > 0 && !is_reserved_meta_entry(name) && resolve_cue_meta_name(name,namebuffer,trackno)) {\r\n\t\t\t\ttrack_record * rec = m_content.query_ptr(trackno);\r\n\t\t\t\tif (rec != NULL) {\r\n\t\t\t\t\trec->m_info.transfer_meta_entry(namebuffer,p_info,metawalk);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid embeddedcue_metadata_manager::get_track_info(unsigned p_track,file_info & p_info) const {\r\n\tconst track_record * rec = m_content.query_ptr(p_track);\r\n\tif (rec == NULL) throw exception_io_data();\r\n\trec->m_info.to_info(p_info);\r\n}\r\n\r\nvoid embeddedcue_metadata_manager::set_track_info(unsigned p_track,file_info const & p_info) {\r\n\ttrack_record * rec = m_content.query_ptr(p_track);\r\n\tif (rec == NULL) throw exception_io_data();\r\n\trec->m_info.from_info_set_meta(p_info);\r\n\trec->m_info.set_replaygain(p_info.get_replaygain());\r\n}\r\n\r\nvoid embeddedcue_metadata_manager::query_track_offsets(unsigned p_track,double & p_begin,double & p_length) const {\r\n\tconst track_record * rec = m_content.query_ptr(p_track);\r\n\tif (rec == NULL) throw exception_io_data();\r\n\tp_begin = rec->m_index_list.start();\r\n\tp_length = rec->m_info.get_length();\r\n}\r\n\r\nbool embeddedcue_metadata_manager::have_cuesheet() const {\r\n\treturn m_content.get_count() > 1;\r\n}\r\n\r\nnamespace {\r\n\tclass __remap_trackno_enumerator {\r\n\tpublic:\r\n\t\t__remap_trackno_enumerator(unsigned p_index) : m_countdown(p_index), m_result(0) {}\r\n\t\ttemplate<typename t_blah> void operator() (unsigned p_trackno,const t_blah&) {\r\n\t\t\tif (p_trackno > 0 && m_result == 0) {\r\n\t\t\t\tif (m_countdown == 0) {\r\n\t\t\t\t\tm_result = p_trackno;\r\n\t\t\t\t} else {\r\n\t\t\t\t\t--m_countdown;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tunsigned result() const {return m_result;}\r\n\tprivate:\r\n\t\tunsigned m_countdown;\r\n\t\tunsigned m_result;\r\n\t};\r\n};\r\n\r\nunsigned embeddedcue_metadata_manager::remap_trackno(unsigned p_index) const {\r\n\tif (have_cuesheet()) {\r\n\t\t__remap_trackno_enumerator wrapper(p_index);\r\n\t\tm_content.enumerate(wrapper);\r\n\t\treturn wrapper.result();\r\n\t} else {\r\n\t\treturn 0;\r\n\t}\t\r\n}\r\n\r\nt_size embeddedcue_metadata_manager::get_cue_track_count() const {\r\n\treturn m_content.get_count() - 1;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cuesheet_index_list.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic bool is_numeric(char c) {return c>='0' && c<='9';}\r\n\r\n\r\nbool t_cuesheet_index_list::is_valid() const {\r\n\tif (m_positions[1] < m_positions[0]) return false;\r\n\tfor(t_size n = 2; n < count && m_positions[n] > 0; n++) {\r\n\t\tif (m_positions[n] < m_positions[n-1]) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid t_cuesheet_index_list::to_infos(file_info & p_out) const\r\n{\r\n\tdouble base = m_positions[1];\r\n\r\n\tif (base > 0) {\r\n\t\tp_out.info_set(\"referenced_offset\",cuesheet_format_index_time(base));\r\n\t}\r\n\t\r\n\tif (m_positions[0] < base)\r\n\t\tp_out.info_set(\"pregap\",cuesheet_format_index_time(base - m_positions[0]));\r\n\telse\r\n\t\tp_out.info_remove(\"pregap\");\r\n\r\n\tp_out.info_remove(\"index 00\");\t\r\n\tp_out.info_remove(\"index 01\");\r\n\t\r\n\tfor(unsigned n=2;n<count;n++)\r\n\t{\r\n\t\tchar namebuffer[16];\r\n\t\tsprintf(namebuffer,\"index %02u\",n);\r\n\t\tdouble position = m_positions[n] - base;\r\n\t\tif (position > 0)\r\n\t\t\tp_out.info_set(namebuffer,cuesheet_format_index_time(position));\r\n\t\telse\r\n\t\t\tp_out.info_remove(namebuffer);\r\n\t}\r\n}\r\n\r\nstatic bool parse_value(const char * p_name,double & p_out)\r\n{\r\n\tif (p_name == NULL) return false;\r\n\ttry {\r\n\t\tp_out = cuesheet_parse_index_time_e(p_name,strlen(p_name));\r\n\t} catch(std::exception const &) {return false;}\r\n\treturn true;\r\n}\r\n\r\nbool t_cuesheet_index_list::from_infos(file_info const & p_in,double p_base)\r\n{\r\n\tdouble pregap;\r\n\tbool found = false;\r\n\tif (!parse_value(p_in.info_get(\"pregap\"),pregap)) pregap = 0;\r\n\telse found = true;\r\n\tm_positions[0] = p_base - pregap;\r\n\tm_positions[1] = p_base;\r\n\tfor(unsigned n=2;n<count;n++)\r\n\t{\r\n\t\tchar namebuffer[16];\r\n\t\tsprintf(namebuffer,\"index %02u\",n);\r\n\t\tdouble temp;\r\n\t\tif (parse_value(p_in.info_get(namebuffer),temp)) {\r\n\t\t\tm_positions[n] = temp + p_base; found = true;\r\n\t\t} else {\r\n\t\t\tm_positions[n] = 0;\r\n\t\t}\r\n\t}\r\n\treturn found;\t\r\n}\r\n\r\ncuesheet_format_index_time::cuesheet_format_index_time(double p_time)\r\n{\r\n\tt_uint64 ticks = audio_math::time_to_samples(p_time,75);\r\n\tt_uint64 seconds = ticks / 75; ticks %= 75;\r\n\tt_uint64 minutes = seconds / 60; seconds %= 60;\r\n\tm_buffer << pfc::format_uint(minutes,2) << \":\" << pfc::format_uint(seconds,2) << \":\" << pfc::format_uint(ticks,2);\r\n}\r\n\r\ndouble cuesheet_parse_index_time_e(const char * p_string,t_size p_length)\r\n{\r\n\treturn (double) cuesheet_parse_index_time_ticks_e(p_string,p_length) / 75.0;\r\n}\r\n\r\nunsigned cuesheet_parse_index_time_ticks_e(const char * p_string,t_size p_length)\r\n{\r\n\tp_length = pfc::strlen_max(p_string,p_length);\r\n\tt_size ptr = 0;\r\n\tt_size splitmarks[2];\r\n\tt_size splitptr = 0;\r\n\tfor(ptr=0;ptr<p_length;ptr++)\r\n\t{\r\n\t\tif (p_string[ptr] == ':')\r\n\t\t{\r\n\t\t\tif (splitptr >= 2) throw std::exception(\"invalid INDEX time syntax\",0);\r\n\t\t\tsplitmarks[splitptr++] = ptr;\r\n\t\t}\r\n\t\telse if (!is_numeric(p_string[ptr])) throw std::exception(\"invalid INDEX time syntax\",0);\r\n\t}\r\n\t\r\n\tt_size minutes_base = 0, minutes_length = 0, seconds_base = 0, seconds_length = 0, frames_base = 0, frames_length = 0;\r\n\r\n\tswitch(splitptr)\r\n\t{\r\n\tcase 0:\r\n\t\tframes_base = 0;\r\n\t\tframes_length = p_length;\r\n\t\tbreak;\r\n\tcase 1:\r\n\t\tseconds_base = 0;\r\n\t\tseconds_length = splitmarks[0];\r\n\t\tframes_base = splitmarks[0] + 1;\r\n\t\tframes_length = p_length - frames_base;\r\n\t\tbreak;\r\n\tcase 2:\r\n\t\tminutes_base = 0;\r\n\t\tminutes_length = splitmarks[0];\r\n\t\tseconds_base = splitmarks[0] + 1;\r\n\t\tseconds_length = splitmarks[1] - seconds_base;\r\n\t\tframes_base = splitmarks[1] + 1;\r\n\t\tframes_length = p_length - frames_base;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tunsigned ret = 0;\r\n\r\n\tif (frames_length > 0) ret += pfc::atoui_ex(p_string + frames_base,frames_length);\r\n\tif (seconds_length > 0) ret += 75 * pfc::atoui_ex(p_string + seconds_base,seconds_length);\r\n\tif (minutes_length > 0) ret += 60 * 75 * pfc::atoui_ex(p_string + minutes_base,minutes_length);\r\n\r\n\treturn ret;\t\r\n}\r\n\r\n\r\nbool t_cuesheet_index_list::is_empty() const {\r\n\tfor(unsigned n=0;n<count;n++) if (m_positions[n] != m_positions[1]) return false;\r\n\treturn true;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/cuesheet_index_list.h",
    "content": "struct t_cuesheet_index_list\r\n{\r\n\tenum {count = 100};\r\n\tinline t_cuesheet_index_list() {reset();}\r\n\tinline t_cuesheet_index_list(const t_cuesheet_index_list & p_source) {*this=p_source;}\r\n\tvoid reset() {for(unsigned n=0;n<count;n++) m_positions[n]=0;}\r\n\r\n\tvoid to_infos(file_info & p_out) const;\r\n\t\r\n\t//returns false when there was nothing relevant in infos\r\n\tbool from_infos(file_info const & p_in,double p_base);\r\n\r\n\tdouble m_positions[count];\r\n\r\n\tinline double start() const {return m_positions[1];}\r\n\tbool is_empty() const;\r\n\r\n\tbool is_valid() const;\r\n};\r\n\r\nunsigned cuesheet_parse_index_time_ticks_e(const char * p_string,t_size p_length);\r\ndouble cuesheet_parse_index_time_e(const char * p_string,t_size p_length);\r\n\r\nclass cuesheet_format_index_time\r\n{\r\npublic:\r\n\tcuesheet_format_index_time(double p_time);\r\n\tinline operator const char*() const {return m_buffer;}\r\nprivate:\r\n\tpfc::string_formatter m_buffer;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dialog_resize_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"dialog_resize_helper.h\"\r\n\r\nvoid resize::calc_xy(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,0,0,\r\n\t\tr.right-r.left+c.right-o.right,\r\n\t\tr.bottom-r.top+c.bottom-o.bottom,\r\n\t\tSWP_NOMOVE|SWP_NOZORDER);\r\n}\r\n\r\nvoid resize::calc_move_xy(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,\r\n\t\tc.right-o.right+r.left,\r\n\t\tc.bottom-o.bottom+r.top,\r\n\t\t0,0,SWP_NOSIZE|SWP_NOZORDER);\r\n}\r\n\r\nvoid resize::calc_move_x(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,\r\n\t\tc.right-o.right+r.left,\r\n\t\tr.top,\r\n\t\t0,0,SWP_NOSIZE|SWP_NOZORDER);\r\n}\r\n\r\nvoid resize::calc_move_x_size_y(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,\r\n\t\tc.right-o.right+r.left,\r\n\t\tr.top,\r\n\t\tr.right-r.left,\r\n\t\tr.bottom-r.top+c.bottom-o.bottom,\r\n\t\tSWP_NOZORDER);\r\n}\r\n\r\nvoid resize::calc_move_y(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,\r\n\t\tr.left,\r\n\t\tc.bottom-o.bottom+r.top,\r\n\t\t0,0,SWP_NOSIZE|SWP_NOZORDER);\r\n}\r\n\r\nvoid resize::calc_x(HWND wnd,UINT id,RECT &r,RECT & o)\r\n{\r\n\tRECT c;\r\n\tGetClientRect(wnd,&c);\r\n\tSetWindowPos(GetDlgItem(wnd,id),0,0,0,\r\n\t\tr.right-r.left+c.right-o.right,\r\n\t\tr.bottom-r.top,\r\n\t\tSWP_NOMOVE|SWP_NOZORDER);\r\n}\r\n\r\nvoid GetChildRect(HWND wnd,UINT id,RECT* child)\r\n{\r\n\tRECT temp;\r\n\tGetWindowRect(GetDlgItem(wnd,id),&temp);\r\n\tMapWindowPoints(0,wnd,(POINT*)&temp,2);\r\n\t*child = temp;\r\n}\r\n\r\n/*\r\nclass dialog_resize_helper\r\n{\r\n\tstruct entry { RECT orig; UINT id; UINT flags };\r\n\tmem_block_list<entry> data;\r\n\tRECT orig_client;\r\n\tHWND parent;\r\npublic:\r\n\tenum {\r\n\t\tX_MOVE = 1, X_SIZE = 2, Y_MOVE = 4, Y_SIZE = 8\r\n\t};\r\n\tvoid set_parent(HWND wnd);\r\n\tvoid add_item(UINT id,UINT flags);\r\n\tvoid reset();\r\n};\r\n*/\r\n\r\nvoid dialog_resize_helper::set_parent(HWND wnd)\r\n{\r\n\treset();\r\n\tparent = wnd;\r\n\tGetClientRect(parent,&orig_client);\r\n}\r\n\r\nvoid dialog_resize_helper::reset()\r\n{\r\n\tparent = 0;\r\n\tsizegrip = 0;\r\n}\r\n\r\nvoid dialog_resize_helper::on_wm_size()\r\n{\r\n\tif (parent)\r\n\t{\r\n\t\tunsigned count = m_table.get_size();\r\n\t\tif (sizegrip != 0) count++;\r\n\t\tHDWP hWinPosInfo = BeginDeferWindowPos(count);\r\n\t\tfor(unsigned n=0;n<m_table.get_size();n++)\r\n\t\t{\r\n\t\t\tparam & e = m_table[n];\r\n\t\t\tconst RECT & orig_rect = rects[n];\r\n\t\t\tRECT cur_client;\r\n\t\t\tGetClientRect(parent,&cur_client);\r\n\t\t\tHWND wnd = GetDlgItem(parent,e.id);\r\n\r\n\t\t\tunsigned dest_x = orig_rect.left, dest_y = orig_rect.top, \r\n\t\t\t\tdest_cx = orig_rect.right - orig_rect.left, dest_cy = orig_rect.bottom - orig_rect.top;\r\n\r\n\t\t\tint delta_x = cur_client.right - orig_client.right,\r\n\t\t\t\tdelta_y = cur_client.bottom - orig_client.bottom;\r\n\r\n\t\t\tif (e.flags & X_MOVE)\r\n\t\t\t\tdest_x += delta_x;\r\n\t\t\telse if (e.flags & X_SIZE)\r\n\t\t\t\tdest_cx += delta_x;\r\n\r\n\t\t\tif (e.flags & Y_MOVE)\r\n\t\t\t\tdest_y += delta_y;\r\n\t\t\telse if (e.flags & Y_SIZE)\r\n\t\t\t\tdest_cy += delta_y;\r\n\t\t\t\r\n\t\t\tDeferWindowPos(hWinPosInfo, wnd,0,dest_x,dest_y,dest_cx,dest_cy,SWP_NOZORDER);\r\n\t\t}\r\n\t\tif (sizegrip != 0)\r\n\t\t{\r\n\t\t\tRECT rc, rc_grip;\r\n\t\t\tGetClientRect(parent, &rc);\r\n\t\t\tGetWindowRect(sizegrip, &rc_grip);\r\n\t\t\tDeferWindowPos(hWinPosInfo, sizegrip, NULL, rc.right - (rc_grip.right - rc_grip.left), rc.bottom - (rc_grip.bottom - rc_grip.top), 0, 0, SWP_NOZORDER | SWP_NOSIZE);\r\n\t\t}\r\n\t\tEndDeferWindowPos(hWinPosInfo);\r\n\t\tRedrawWindow(parent,0,0,RDW_INVALIDATE);\r\n\t}\r\n}\r\n\r\n\r\nbool dialog_resize_helper::process_message(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)\r\n{\r\n\tswitch(msg)\r\n\t{\r\n\tcase WM_SIZE:\r\n\t\ton_wm_size();\r\n\t\treturn true;\r\n\tcase WM_GETMINMAXINFO:\r\n\t\t{\r\n\t\t\tRECT r;\r\n\t\t\tLPMINMAXINFO info = (LPMINMAXINFO) lp;\r\n\t\t\tDWORD dwStyle = GetWindowLong(wnd, GWL_STYLE);\r\n\t\t\tDWORD dwExStyle = GetWindowLong(wnd, GWL_EXSTYLE);\r\n\t\t\tif (max_x && max_y)\r\n\t\t\t{\r\n\t\t\t\tr.left = 0; r.right = max_x;\r\n\t\t\t\tr.top = 0; r.bottom = max_y;\r\n\t\t\t\tMapDialogRect(wnd,&r);\r\n\t\t\t\tAdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);\r\n\t\t\t\tinfo->ptMaxTrackSize.x = r.right - r.left;\r\n\t\t\t\tinfo->ptMaxTrackSize.y = r.bottom - r.top;\r\n\t\t\t}\r\n\t\t\tif (min_x && min_y)\r\n\t\t\t{\r\n\t\t\t\tr.left = 0; r.right = min_x;\r\n\t\t\t\tr.top = 0; r.bottom = min_y;\r\n\t\t\t\tMapDialogRect(wnd,&r);\r\n\t\t\t\tAdjustWindowRectEx(&r, dwStyle, FALSE, dwExStyle);\r\n\t\t\t\tinfo->ptMinTrackSize.x = r.right - r.left;\r\n\t\t\t\tinfo->ptMinTrackSize.y = r.bottom - r.top;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn true;\r\n\tcase WM_INITDIALOG:\r\n\t\tset_parent(wnd);\r\n\t\t{\r\n\t\t\tunsigned n;\r\n\t\t\tfor(n=0;n<m_table.get_size();n++)\r\n\t\t\t{\r\n\t\t\t\tGetChildRect(parent,m_table[n].id,&rects[n]);\r\n\t\t\t}\r\n\t\t}\r\n\t\tbreak;\r\n\tcase WM_DESTROY:\r\n\t\treset();\r\n\t\tbreak;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid dialog_resize_helper::add_sizegrip()\r\n{\r\n\tif (parent != 0 && sizegrip == 0)\r\n\t{\r\n\t\tsizegrip = CreateWindowEx(0, WC_SCROLLBAR, _T(\"\"), WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SBS_SIZEGRIP | SBS_SIZEBOXBOTTOMRIGHTALIGN,\r\n\t\t\t0, 0, CW_USEDEFAULT, CW_USEDEFAULT,\r\n\t\t\tparent, (HMENU)0, NULL, NULL);\r\n\t\tif (sizegrip != 0)\r\n\t\t{\r\n\t\t\tRECT rc, rc_grip;\r\n\t\t\tGetClientRect(parent, &rc);\r\n\t\t\tGetWindowRect(sizegrip, &rc_grip);\r\n\t\t\tSetWindowPos(sizegrip, NULL, rc.right - (rc_grip.right - rc_grip.left), rc.bottom - (rc_grip.bottom - rc_grip.top), 0, 0, SWP_NOZORDER | SWP_NOSIZE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\ndialog_resize_helper::dialog_resize_helper(const param * src,unsigned count,unsigned p_min_x,unsigned p_min_y,unsigned p_max_x,unsigned p_max_y) \r\n\t: min_x(p_min_x), min_y(p_min_y), max_x(p_max_x), max_y(p_max_y), parent(0), sizegrip(0)\r\n{\r\n\tm_table.set_size(count);\r\n\tunsigned n;\r\n\tfor(n=0;n<count;n++)\r\n\t\tm_table[n] = src[n];\r\n\trects.set_size(count);\r\n}\r\n\r\ndialog_resize_helper::~dialog_resize_helper()\r\n{\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dialog_resize_helper.h",
    "content": "#ifndef _DIALOG_RESIZE_HELPER_H_\r\n#define _DIALOG_RESIZE_HELPER_H_\r\n\r\n\r\n//deprecated, use dialog_resize_helper class\r\nnamespace resize\r\n{\r\n\tvoid calc_xy(HWND wnd,UINT id,RECT &r,RECT & o);\r\n\tvoid calc_move_xy(HWND wnd,UINT id,RECT &r,RECT & o);\r\n\tvoid calc_move_x(HWND wnd,UINT id,RECT &r,RECT & o);\r\n\tvoid calc_move_x_size_y(HWND wnd,UINT id,RECT &r,RECT & o);\r\n\tvoid calc_move_y(HWND wnd,UINT id,RECT &r,RECT & o);\r\n\tvoid calc_x(HWND wnd,UINT id,RECT &r,RECT & o);\r\n};\r\n\r\nvoid GetChildRect(HWND wnd,UINT id,RECT* child);\r\n\r\n\r\nclass dialog_resize_helper\r\n{\r\n\tpfc::array_t<RECT> rects;\r\n\tRECT orig_client;\r\n\tHWND parent;\r\n\tHWND sizegrip;\r\n\tunsigned min_x,min_y,max_x,max_y;\r\n\r\npublic:\r\n\tstruct param {\r\n\t\tunsigned short id;\r\n\t\tunsigned short flags;\r\n\t};\r\nprivate:\r\n\tpfc::array_t<param> m_table;\r\n\r\n\tvoid set_parent(HWND wnd);\r\n\tvoid add_item(UINT id,UINT flags);\r\n\tvoid reset();\r\n\tvoid on_wm_size();\r\n\tvoid add_items(const param* table,unsigned count);\r\npublic:\r\n\tinline void set_min_size(unsigned x,unsigned y) {min_x = x; min_y = y;}\r\n\tinline void set_max_size(unsigned x,unsigned y) {max_x = x; max_y = y;}\r\n\tvoid add_sizegrip();\r\n\t\r\n\tenum {\r\n\t\tX_MOVE = 1, X_SIZE = 2, Y_MOVE = 4, Y_SIZE = 8,\r\n\t\tXY_MOVE = X_MOVE|Y_MOVE, XY_SIZE = X_SIZE|Y_SIZE,\r\n\t\tX_MOVE_Y_SIZE = X_MOVE|Y_SIZE, X_SIZE_Y_MOVE = X_SIZE|Y_MOVE,\r\n\t};\r\n\tbool process_message(HWND wnd,UINT msg,WPARAM wp,LPARAM lp);\r\n\r\n\r\n\r\n\texplicit dialog_resize_helper(const param * src,unsigned count,unsigned p_min_x,unsigned p_min_y,unsigned p_max_x,unsigned p_max_y);\r\n\t~dialog_resize_helper();\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dropdown_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"dropdown_helper.h\"\r\n\r\n\r\nvoid cfg_dropdown_history::build_list(pfc::ptr_list_t<char> & out)\r\n{\r\n\tconst char * src = data;\r\n\twhile(*src)\r\n\t{\r\n\t\tint ptr = 0;\r\n\t\twhile(src[ptr] && src[ptr]!=separator) ptr++;\r\n\t\tif (ptr>0)\r\n\t\t{\r\n\t\t\tout.add_item(pfc::strdup_n(src,ptr));\r\n\t\t\tsrc += ptr;\r\n\t\t}\r\n\t\twhile(*src==separator) src++;\r\n\t}\r\n}\r\n\r\nvoid cfg_dropdown_history::parse_list(const pfc::ptr_list_t<char> & src)\r\n{\r\n\tt_size n;\r\n\tpfc::string8_fastalloc temp;\r\n\tfor(n=0;n<src.get_count();n++)\r\n\t{\r\n\t\ttemp.add_string(src[n]);\r\n\t\ttemp.add_char(separator);\t\t\r\n\t}\r\n\tdata = temp;\r\n}\r\n\r\nstatic void g_setup_dropdown_fromlist(HWND wnd,const pfc::ptr_list_t<char> & list)\r\n{\r\n\tt_size n, m = list.get_count();\r\n\tuSendMessage(wnd,CB_RESETCONTENT,0,0);\r\n\tfor(n=0;n<m;n++) {\r\n\t\tuSendMessageText(wnd,CB_ADDSTRING,0,list[n]);\r\n\t}\r\n}\r\n\r\nvoid cfg_dropdown_history::setup_dropdown(HWND wnd)\r\n{\r\n\tpfc::ptr_list_t<char> list;\r\n\tbuild_list(list);\r\n\tg_setup_dropdown_fromlist(wnd,list);\r\n\tlist.free_all();\r\n}\r\n\r\nvoid cfg_dropdown_history::add_item(const char * item)\r\n{\r\n\tif (!item || !*item) return;\r\n\tpfc::string8 meh;\r\n\tif (strchr(item,separator))\r\n\t{\r\n\t\tuReplaceChar(meh,item,-1,separator,'|',false);\r\n\t\titem = meh;\r\n\t}\r\n\tpfc::ptr_list_t<char> list;\r\n\tbuild_list(list);\r\n\tunsigned n;\r\n\tbool found = false;\r\n\tfor(n=0;n<list.get_count();n++)\r\n\t{\r\n\t\tif (!strcmp(list[n],item))\r\n\t\t{\r\n\t\t\tchar* temp = list.remove_by_idx(n);\r\n\t\t\tlist.insert_item(temp,0);\r\n\t\t\tfound = true;\r\n\t\t}\r\n\t}\r\n\r\n\tif (!found)\r\n\t{\r\n\t\twhile(list.get_count() > max) list.delete_by_idx(list.get_count()-1);\r\n\t\tlist.insert_item(strdup(item),0);\r\n\t}\r\n\tparse_list(list);\r\n\tlist.free_all();\r\n}\r\n\r\nbool cfg_dropdown_history::is_empty()\r\n{\r\n\tconst char * src = data;\r\n\twhile(*src)\r\n\t{\r\n\t\tif (*src!=separator) return false;\r\n\t\tsrc++;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid cfg_dropdown_history::on_context(HWND wnd,LPARAM coords)\r\n{\r\n\tint coords_x = (short)LOWORD(coords), coords_y = (short)HIWORD(coords);\r\n\tif (coords_x == -1 && coords_y == -1)\r\n\t{\r\n\t\tRECT asdf;\r\n\t\tGetWindowRect(wnd,&asdf);\r\n\t\tcoords_x = (asdf.left + asdf.right) / 2;\r\n\t\tcoords_y = (asdf.top + asdf.bottom) / 2;\r\n\t}\r\n\tenum {ID_ERASE_ALL = 1, ID_ERASE_ONE };\r\n\tHMENU menu = CreatePopupMenu();\r\n\tuAppendMenu(menu,MF_STRING,ID_ERASE_ALL,\"Wipe history\");\r\n\t{\r\n\t\tpfc::string8 tempvalue;\r\n\t\tuGetWindowText(wnd,tempvalue);\r\n\t\tif (!tempvalue.is_empty())\r\n\t\t\tuAppendMenu(menu,MF_STRING,ID_ERASE_ONE,\"Remove this history item\");\r\n\t}\r\n\tint cmd = TrackPopupMenu(menu,TPM_RIGHTBUTTON|TPM_NONOTIFY|TPM_RETURNCMD,coords_x,coords_y,0,wnd,0);\r\n\tDestroyMenu(menu);\r\n\tswitch(cmd)\r\n\t{\r\n\tcase ID_ERASE_ALL:\r\n\t\t{\r\n\t\t\tdata = \"\";\r\n\t\t\tpfc::string8 value;//preserve old value while wiping dropdown list\r\n\t\t\tuGetWindowText(wnd,value);\r\n\t\t\tuSendMessage(wnd,CB_RESETCONTENT,0,0);\r\n\t\t\tuSetWindowText(wnd,value);\r\n\t\t}\r\n\t\tbreak;\r\n\tcase ID_ERASE_ONE:\r\n\t\t{\r\n\t\t\tpfc::string8 value;\r\n\t\t\tuGetWindowText(wnd,value);\r\n\r\n\t\t\tpfc::ptr_list_t<char> list;\r\n\t\t\tt_size n,m;\r\n\t\t\tbool found;\r\n\t\t\tbuild_list(list);\r\n\t\t\tm = list.get_count();\r\n\t\t\tfound = false;\r\n\t\t\tfor(n=0;n<m;n++)\r\n\t\t\t{\r\n\t\t\t\tif (!strcmp(value,list[n]))\r\n\t\t\t\t{\r\n\t\t\t\t\tfree(list[n]);\r\n\t\t\t\t\tlist.remove_by_idx(n);\r\n\t\t\t\t\tfound = true;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (found) parse_list(list);\r\n\t\t\tg_setup_dropdown_fromlist(wnd,list);\r\n\t\t\tlist.free_all();\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dropdown_helper.h",
    "content": "#ifndef _DROPDOWN_HELPER_H_\r\n#define _DROPDOWN_HELPER_H_\r\n\r\n\r\nclass cfg_dropdown_history\r\n{\r\n\tenum {separator = '\\n'};\r\n\tcfg_string data;\r\n\tunsigned max;\r\n\tvoid build_list(pfc::ptr_list_t<char> & out);\r\n\tvoid parse_list(const pfc::ptr_list_t<char> & src);\r\npublic:\r\n\tcfg_dropdown_history(const GUID & p_guid,unsigned p_max = 10,const char * init_vals = \"\") : data(p_guid,init_vals) {max = p_max;}\r\n\tvoid setup_dropdown(HWND wnd);\r\n\tvoid setup_dropdown(HWND wnd,UINT id) {setup_dropdown(GetDlgItem(wnd,id));}\r\n\tvoid add_item(const char * item);\r\n\tbool is_empty();\r\n\tvoid on_context(HWND wnd,LPARAM coords);\r\n};\r\n\r\n\r\n#endif //_DROPDOWN_HELPER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dynamic_bitrate_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic unsigned g_query_settings()\r\n{\r\n\tt_int32 temp;\r\n\ttry {\r\n\t\tconfig_object::g_get_data_int32(standard_config_objects::int32_dynamic_bitrate_display_rate,temp);\r\n\t} catch(std::exception const &) {return 9;}\r\n\tif (temp < 0) return 0;\r\n\treturn (unsigned) temp;\r\n}\r\n\r\ndynamic_bitrate_helper::dynamic_bitrate_helper()\r\n{\r\n\treset();\r\n}\r\n\r\nvoid dynamic_bitrate_helper::init()\r\n{\r\n\tif (!m_inited)\r\n\t{\r\n\t\tm_inited = true;\r\n\t\tunsigned temp = g_query_settings();\r\n\t\tif (temp > 0) {m_enabled = true; m_update_interval = 1.0 / (double) temp; }\r\n\t\telse {m_enabled = false; m_update_interval = 0; }\r\n\t\tm_last_duration = 0;\r\n\t\tm_update_bits = 0;\r\n\t\tm_update_time = 0;\r\n\r\n\t}\r\n}\r\n\r\nvoid dynamic_bitrate_helper::on_frame(double p_duration,t_size p_bits)\r\n{\r\n\tinit();\r\n\tm_last_duration = p_duration;\r\n\tm_update_time += p_duration;\r\n\tm_update_bits += p_bits;\r\n}\r\n\r\nbool dynamic_bitrate_helper::on_update(file_info & p_out, double & p_timestamp_delta)\r\n{\r\n\tinit();\r\n\r\n\tbool ret = false;\r\n\tif (m_enabled)\r\n\t{\r\n\t\tif (m_update_time > m_update_interval)\r\n\t\t{\r\n\t\t\tint val = (int) ( ((double)m_update_bits / m_update_time + 500.0) / 1000.0 );\r\n\t\t\tif (val != p_out.info_get_bitrate_vbr())\r\n\t\t\t{\r\n\t\t\t\tp_timestamp_delta = - (m_update_time - m_last_duration);\t//relative to last frame beginning;\r\n\t\t\t\tp_out.info_set_bitrate_vbr(val);\r\n\t\t\t\tret = true;\r\n\t\t\t}\r\n\t\t\tm_update_bits = 0;\r\n\t\t\tm_update_time = 0;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_update_bits = 0;\r\n\t\tm_update_time = 0;\r\n\t}\r\n\r\n\treturn ret;\r\n\r\n}\r\n\r\nvoid dynamic_bitrate_helper::reset()\r\n{\r\n\tm_inited = false;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/dynamic_bitrate_helper.h",
    "content": "class dynamic_bitrate_helper\r\n{\r\npublic:\r\n\tdynamic_bitrate_helper();\r\n\tvoid on_frame(double p_duration,t_size p_bits);\r\n\tbool on_update(file_info & p_out, double & p_timestamp_delta);\r\n\tvoid reset();\r\nprivate:\r\n\tvoid init();\r\n\tdouble m_last_duration;\r\n\tt_size m_update_bits;\r\n\tdouble m_update_time;\r\n\tdouble m_update_interval;\r\n\tbool m_inited, m_enabled;\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_cached.h",
    "content": "template<unsigned blocksize>\r\nclass file_cached : public file {\r\npublic:\r\n\tstatic void g_create(service_ptr_t<file> & p_out,service_ptr_t<file> p_base,abort_callback & p_abort) {\r\n\t\tservice_ptr_t<file_cached<blocksize> > temp;\r\n\t\ttemp = new service_impl_t<file_cached<blocksize> >();\r\n\t\ttemp->initialize(p_base,p_abort);\r\n\t\tp_out = temp.get_ptr();\r\n\t}\r\nprivate:\r\n\tvoid initialize(service_ptr_t<file> p_base,abort_callback & p_abort) {\r\n\t\tm_base = p_base;\r\n\t\tm_position = 0;\r\n\t\tm_can_seek = m_base->can_seek();\r\n\t\tif (m_can_seek) {\r\n\t\t\tm_position_base = m_base->get_position(p_abort);\r\n\t\t} else {\r\n\t\t\tm_position_base = 0;\r\n\t\t}\r\n\r\n\t\tm_size = m_base->get_size(p_abort);\r\n\r\n\t\tflush_buffer();\r\n\t}\r\npublic:\r\n\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tt_uint8 * outptr = (t_uint8*)p_buffer;\r\n\t\tt_size done = 0;\r\n\t\twhile(done < p_bytes && m_position < m_size) {\r\n\t\t\tp_abort.check();\r\n\r\n\t\t\tif (m_position >= m_buffer_position && m_position < m_buffer_position + m_buffer_status) {\t\t\t\t\r\n\t\t\t\tt_size delta = pfc::min_t<t_size>((t_size)(m_buffer_position + m_buffer_status - m_position),p_bytes - done);\r\n\t\t\t\tt_size bufptr = (t_size)(m_position - m_buffer_position);\r\n\t\t\t\tmemcpy(outptr+done,m_buffer+bufptr,delta);\r\n\t\t\t\tdone += delta;\r\n\t\t\t\tm_position += delta;\r\n\t\t\t\tif (m_buffer_status != sizeof(m_buffer) && done < p_bytes) break;//EOF before m_size is hit\r\n\t\t\t} else {\r\n\t\t\t\tm_buffer_position = m_position - m_position % blocksize;\r\n\t\t\t\tadjust_position(m_buffer_position,p_abort);\r\n\r\n\t\t\t\tm_buffer_status = m_base->read(m_buffer,sizeof(m_buffer),p_abort);\r\n\t\t\t\tm_position_base += m_buffer_status;\r\n\r\n\t\t\t\tif (m_buffer_status <= (t_size)(m_position - m_buffer_position)) break;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn done;\r\n\t}\r\n\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\tadjust_position(m_position,p_abort);\r\n\t\tm_base->write(p_buffer,p_bytes,p_abort);\r\n\t\tm_position_base = m_position = m_position + p_bytes;\r\n\t\tif (m_size < m_position) m_size = m_position;\r\n\t\tflush_buffer();\r\n\t}\r\n\r\n\tt_filesize get_size(abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\treturn m_size;\r\n\t}\r\n\tt_filesize get_position(abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\treturn m_position;\r\n\t}\r\n\tvoid set_eof(abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\tadjust_position(m_position,p_abort);\r\n\t\tm_base->set_eof(p_abort);\r\n\t\tflush_buffer();\r\n\t}\r\n\tvoid seek(t_filesize p_position,abort_callback & p_abort) {\r\n\t\tp_abort.check();\r\n\t\tif (!m_can_seek) throw exception_io_object_not_seekable();\r\n\t\tif (p_position > m_size) throw exception_io_seek_out_of_range();\r\n\t\tm_position = p_position;\r\n\t}\r\n\tvoid reopen(abort_callback & p_abort) {seek(0,p_abort);}\r\n\tbool can_seek() {return m_can_seek;}\r\n\tbool get_content_type(pfc::string_base & out) {return m_base->get_content_type(out);}\r\n\tvoid on_idle(abort_callback & p_abort) {p_abort.check();m_base->on_idle(p_abort);}\r\n\tt_filetimestamp get_timestamp(abort_callback & p_abort) {p_abort.check(); return m_base->get_timestamp(p_abort);}\r\n\tbool is_remote() {return m_base->is_remote();}\r\n\tvoid resize(t_filesize p_size,abort_callback & p_abort) {\r\n\t\tflush_buffer();\r\n\t\tm_base->resize(p_size,p_abort);\r\n\t\tm_size = p_size;\r\n\t\tif (m_position > m_size) m_position = m_size;\r\n\t\tif (m_position_base > m_size) m_position_base = m_size;\r\n\t}\r\nprivate:\r\n\tvoid adjust_position(t_filesize p_target,abort_callback & p_abort) {\r\n\t\tif (p_target != m_position_base) {\r\n\t\t\tm_base->seek(p_target,p_abort);\r\n\t\t\tm_position_base = p_target;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid flush_buffer() {\r\n\t\tm_buffer_status = 0;\r\n\t\tm_buffer_position = 0;\r\n\t}\r\n\r\n\tservice_ptr_t<file> m_base;\r\n\tt_filesize m_position,m_position_base,m_size;\r\n\tbool m_can_seek;\r\n\tt_filesize m_buffer_position;\r\n\tt_size m_buffer_status;\r\n\tt_uint8 m_buffer[blocksize];\t\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_info_const_impl.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic const char * const standard_fieldnames[] = \r\n{\r\n\t\"artist\",\"ARTIST\",\"Artist\",\r\n\t\"album\",\"ALBUM\",\"Album\",\r\n\t\"tracknumber\",\"TRACKNUMBER\",\"Tracknumber\",\r\n\t\"totaltracks\",\"TOTALTRACKS\",\"Totaltracks\",\r\n\t\"genre\",\"GENRE\",\"Genre\",\r\n\t\"title\",\"TITLE\",\"Title\",\r\n\t\"comment\",\"COMMENT\",\"Comment\",\r\n\t\"date\",\"DATE\",\"Date\",\r\n\t\"discnumber\",\"DISCNUMBER\",\"Discnumber\"\r\n};\r\n\r\nstatic const char * const standard_infonames[] = \r\n{\r\n\t\"bitspersample\", \"channels\", \"bitrate\", \"codec\", \"codec_profile\",\"tool\",\"tagtype\", \"samplerate\"\r\n};\r\n\r\nstatic const char * optimize_fieldname(const char * p_string)\r\n{\r\n\tfor(t_size n=0;n<tabsize(standard_fieldnames);n++)\r\n\t{\r\n\t\tconst char * stdstring = standard_fieldnames[n];\r\n\t\tif (/*p_string[0] == stdstring[0] && */strcmp(p_string,stdstring) == 0) {\r\n\t\t\treturn stdstring;\r\n\t\t}\r\n\t}\r\n\treturn NULL;\r\n}\r\n\r\nstatic const char * optimize_infoname(const char * p_string)\r\n{\r\n\tfor(t_size n=0;n<tabsize(standard_infonames);n++)\r\n\t{\r\n\t\tconst char * stdstring = standard_infonames[n];\r\n\t\tif (/*p_string[0] == stdstring[0] && */strcmp(p_string,stdstring) == 0) {\r\n\t\t\treturn stdstring;\r\n\t\t}\r\n\t}\r\n\treturn NULL;\r\n}\r\n\r\n/*\r\norder of things\r\n\r\n  meta entries\r\n  meta value map\r\n  info entries \r\n  string buffer\r\n\r\n*/\r\n\r\ninline static char* stringbuffer_append(char * & buffer,const char * value)\r\n{\r\n\tchar * ret = buffer;\r\n\twhile(*value) *(buffer++) = *(value++);\r\n\t*(buffer++) = 0;\r\n\treturn ret;\r\n}\r\n\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\r\nnamespace {\r\n\tclass sort_callback_hintmap_impl : public pfc::sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_hintmap_impl(const file_info_const_impl::meta_entry * p_meta,file_info_const_impl::t_index * p_hintmap)\r\n\t\t\t: m_meta(p_meta), m_hintmap(p_hintmap)\r\n\t\t{\r\n\t\t}\r\n\t\t\r\n\t\tint compare(t_size p_index1, t_size p_index2) const\r\n\t\t{\r\n//\t\t\tprofiler(sort_callback_hintmap_impl_compare);\r\n\t\t\treturn pfc::stricmp_ascii(m_meta[m_hintmap[p_index1]].m_name,m_meta[m_hintmap[p_index2]].m_name);\r\n\t\t}\r\n\t\t\r\n\t\tvoid swap(t_size p_index1, t_size p_index2)\r\n\t\t{\r\n\t\t\tpfc::swap_t<file_info_const_impl::t_index>(m_hintmap[p_index1],m_hintmap[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tconst file_info_const_impl::meta_entry * m_meta;\r\n\t\tfile_info_const_impl::t_index * m_hintmap;\r\n\t};\r\n\r\n\tclass bsearch_callback_hintmap_impl : public pfc::bsearch_callback\r\n\t{\r\n\tpublic:\r\n\t\tbsearch_callback_hintmap_impl(\r\n\t\t\tconst file_info_const_impl::meta_entry * p_meta,\r\n\t\t\tconst file_info_const_impl::t_index * p_hintmap,\r\n\t\t\tconst char * p_name,\r\n\t\t\tt_size p_name_length)\r\n\t\t\t: m_meta(p_meta), m_hintmap(p_hintmap), m_name(p_name), m_name_length(p_name_length)\r\n\t\t{\r\n\t\t}\r\n\r\n\t\tint test(t_size p_index) const\r\n\t\t{\r\n\t\t\treturn pfc::stricmp_ascii_ex(m_meta[m_hintmap[p_index]].m_name,infinite,m_name,m_name_length);\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tconst file_info_const_impl::meta_entry * m_meta;\r\n\t\tconst file_info_const_impl::t_index * m_hintmap;\r\n\t\tconst char * m_name;\r\n\t\tt_size m_name_length;\r\n\t};\r\n}\r\n\r\n#endif//__file_info_const_impl_have_hintmap__\r\n\r\nvoid file_info_const_impl::copy(const file_info & p_source)\r\n{\r\n//\tprofiler(file_info_const_impl__copy);\r\n\tt_size meta_size = 0;\r\n\tt_size info_size = 0;\r\n\tt_size valuemap_size = 0;\r\n\tt_size stringbuffer_size = 0;\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tt_size hintmap_size = 0;\r\n#endif\r\n\r\n\t{\r\n//\t\tprofiler(file_info_const_impl__copy__pass1);\r\n\t\tt_size index;\r\n\t\tm_meta_count = pfc::downcast_guarded<t_index>(p_source.meta_get_count());\r\n\t\tmeta_size = m_meta_count * sizeof(meta_entry);\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\t\thintmap_size = (m_meta_count > hintmap_cutoff) ? m_meta_count * sizeof(t_index) : 0;\r\n#endif//__file_info_const_impl_have_hintmap__\r\n\t\tfor(index = 0; index < m_meta_count; index++ )\r\n\t\t{\r\n\t\t\t{\r\n\t\t\t\tconst char * name = p_source.meta_enum_name(index);\r\n\t\t\t\tif (optimize_fieldname(name) == 0)\r\n\t\t\t\t\tstringbuffer_size += strlen(name) + 1;\r\n\t\t\t}\r\n\r\n\t\t\tt_size val; const t_size val_max = p_source.meta_enum_value_count(index);\r\n\t\t\t\r\n\t\t\tif (val_max == 1)\r\n\t\t\t{\r\n\t\t\t\tstringbuffer_size += strlen(p_source.meta_enum_value(index,0)) + 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvaluemap_size += val_max * sizeof(char*);\r\n\r\n\t\t\t\tfor(val = 0; val < val_max; val++ )\r\n\t\t\t\t{\r\n\t\t\t\t\tstringbuffer_size += strlen(p_source.meta_enum_value(index,val)) + 1;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tm_info_count = pfc::downcast_guarded<t_index>(p_source.info_get_count());\r\n\t\tinfo_size = m_info_count * sizeof(info_entry);\r\n\t\tfor(index = 0; index < m_info_count; index++ )\r\n\t\t{\r\n\t\t\tconst char * name = p_source.info_enum_name(index);\r\n\t\t\tif (optimize_infoname(name) == NULL) stringbuffer_size += strlen(name) + 1;\r\n\t\t\tstringbuffer_size += strlen(p_source.info_enum_value(index)) + 1;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t{\r\n//\t\tprofiler(file_info_const_impl__copy__alloc);\r\n\t\tm_buffer.set_size(\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\t\t\thintmap_size + \r\n#endif\r\n\t\t\tmeta_size + info_size + valuemap_size + stringbuffer_size);\r\n\t}\r\n\r\n\tchar * walk = m_buffer.get_ptr();\r\n\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tt_index* hintmap = (hintmap_size > 0) ? (t_index*) walk : NULL;\r\n\twalk += hintmap_size;\r\n#endif\r\n\tmeta_entry * meta = (meta_entry*) walk;\r\n\twalk += meta_size;\r\n\tchar ** valuemap = (char**) walk;\r\n\twalk += valuemap_size;\r\n\tinfo_entry * info = (info_entry*) walk;\r\n\twalk += info_size;\r\n\tchar * stringbuffer = walk;\r\n\r\n\tm_meta = meta;\r\n\tm_info = info;\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tm_hintmap = hintmap;\r\n#endif\r\n\r\n\t{\r\n//\t\tprofiler(file_info_const_impl__copy__pass2);\r\n\t\tt_size index;\r\n\t\tfor( index = 0; index < m_meta_count; index ++ )\r\n\t\t{\r\n\t\t\tt_size val; const t_size val_max = p_source.meta_enum_value_count(index);\r\n\r\n\t\t\t{\r\n\t\t\t\tconst char * name = p_source.meta_enum_name(index);\r\n\t\t\t\tconst char * name_opt = optimize_fieldname(name);\r\n\t\t\t\tif (name_opt == NULL)\r\n\t\t\t\t\tmeta[index].m_name = stringbuffer_append(stringbuffer, name );\r\n\t\t\t\telse\r\n\t\t\t\t\tmeta[index].m_name = name_opt;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tmeta[index].m_valuecount = val_max;\r\n\r\n\t\t\tif (val_max == 1)\r\n\t\t\t{\r\n\t\t\t\tmeta[index].m_valuemap = reinterpret_cast<const char * const *>(stringbuffer_append(stringbuffer, p_source.meta_enum_value(index,0) ));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tmeta[index].m_valuemap = valuemap;\r\n\t\t\t\tfor( val = 0; val < val_max ; val ++ )\r\n\t\t\t\t\t*(valuemap ++ ) = stringbuffer_append(stringbuffer, p_source.meta_enum_value(index,val) );\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tfor( index = 0; index < m_info_count; index ++ )\r\n\t\t{\r\n\t\t\tconst char * name = p_source.info_enum_name(index);\r\n\t\t\tconst char * name_opt = optimize_infoname(name);\r\n\t\t\tif (name_opt == NULL)\r\n\t\t\t\tinfo[index].m_name = stringbuffer_append(stringbuffer, name );\r\n\t\t\telse\r\n\t\t\t\tinfo[index].m_name = name_opt;\r\n\t\t\tinfo[index].m_value = stringbuffer_append(stringbuffer, p_source.info_enum_value(index) );\r\n\t\t}\r\n\t}\r\n\r\n\tm_length = p_source.get_length();\r\n\tm_replaygain = p_source.get_replaygain();\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tif (hintmap != NULL) {\r\n//\t\tprofiler(file_info_const_impl__copy__hintmap);\r\n\t\tfor(t_size n=0;n<m_meta_count;n++) hintmap[n]=n;\r\n\t\tpfc::sort(sort_callback_hintmap_impl(meta,hintmap),m_meta_count);\r\n\t}\r\n#endif//__file_info_const_impl_have_hintmap__\r\n}\r\n\r\n\r\nvoid file_info_const_impl::reset()\r\n{\r\n\tm_meta_count = m_info_count = 0; m_length = 0; m_replaygain.reset();\r\n}\r\n\r\nt_size file_info_const_impl::meta_find_ex(const char * p_name,t_size p_name_length) const\r\n{\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tif (m_hintmap != NULL) {\r\n\t\tt_size result = infinite;\r\n\t\tif (!pfc::bsearch(m_meta_count,bsearch_callback_hintmap_impl(m_meta,m_hintmap,p_name,p_name_length),result)) return infinite;\r\n\t\telse return m_hintmap[result];\r\n\t} else {\r\n\t\treturn file_info::meta_find_ex(p_name,p_name_length);\r\n\t}\r\n#else\r\n\treturn file_info::meta_find_ex(p_name,p_name_length);\r\n#endif\r\n}\r\n\r\n\r\nt_size\tfile_info_const_impl::meta_enum_value_count(t_size p_index) const\r\n{\r\n\treturn m_meta[p_index].m_valuecount;\r\n}\r\n\r\nconst char*\tfile_info_const_impl::meta_enum_value(t_size p_index,t_size p_value_number) const\r\n{\r\n\tconst meta_entry & entry = m_meta[p_index];\r\n\tif (entry.m_valuecount == 1)\r\n\t\treturn reinterpret_cast<const char*>(entry.m_valuemap);\r\n\telse\r\n\t\treturn entry.m_valuemap[p_value_number];\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_info_const_impl.h",
    "content": "#define __file_info_const_impl_have_hintmap__\r\n\r\n//! Special implementation of file_info that implements only const and copy methods. The difference between this and regular file_info_impl is amount of resources used and speed of the copy operation.\r\nclass file_info_const_impl : public file_info\r\n{\r\npublic:\r\n\tfile_info_const_impl(const file_info & p_source) {copy(p_source);}\r\n\tfile_info_const_impl(const file_info_const_impl & p_source) {copy(p_source);}\r\n\tfile_info_const_impl() {m_meta_count = m_info_count = 0; m_length = 0; m_replaygain.reset();}\r\n\r\n\tdouble\t\tget_length() const {return m_length;}\r\n\t\r\n\tt_size\t\tmeta_get_count() const {return m_meta_count;}\r\n\tconst char*\tmeta_enum_name(t_size p_index) const {return m_meta[p_index].m_name;}\r\n\tt_size\t\tmeta_enum_value_count(t_size p_index) const;\r\n\tconst char*\tmeta_enum_value(t_size p_index,t_size p_value_number) const;\r\n\tt_size\t\tmeta_find_ex(const char * p_name,t_size p_name_length) const;\r\n\r\n\tt_size\t\tinfo_get_count() const {return m_info_count;}\r\n\tconst char*\tinfo_enum_name(t_size p_index) const {return m_info[p_index].m_name;}\r\n\tconst char*\tinfo_enum_value(t_size p_index) const {return m_info[p_index].m_value;}\r\n\r\n\r\n\tconst file_info_const_impl & operator=(const file_info & p_source) {copy(p_source); return *this;}\r\n\tconst file_info_const_impl & operator=(const file_info_const_impl & p_source) {copy(p_source); return *this;}\r\n\tvoid copy(const file_info & p_source);\r\n\tvoid reset();\r\n\r\n\treplaygain_info\tget_replaygain() const {return m_replaygain;}\r\n\r\nprivate:\r\n\tvoid\t\tset_length(double p_length) {throw pfc::exception_bug_check();}\r\n\r\n\tt_size\t\tmeta_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tmeta_insert_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tmeta_remove_mask(const bit_array & p_mask) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tmeta_reorder(const t_size * p_order) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tmeta_remove_values(t_size p_index,const bit_array & p_mask) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tmeta_modify_value_ex(t_size p_index,t_size p_value_index,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\n\r\n\tt_size\t\tinfo_set_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\n\tvoid\t\tinfo_remove_mask(const bit_array & p_mask) {throw pfc::exception_bug_check();}\r\n\r\n\tvoid\t\t\tset_replaygain(const replaygain_info & p_info) {throw pfc::exception_bug_check();}\r\n\t\r\n\tt_size\t\tmeta_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\n\tt_size\t\tinfo_set_nocheck_ex(const char * p_name,t_size p_name_length,const char * p_value,t_size p_value_length) {throw pfc::exception_bug_check();}\r\npublic:\r\n\tstruct meta_entry {\r\n\t\tconst char * m_name;\r\n\t\tt_size m_valuecount;\r\n\t\tconst char * const * m_valuemap;\r\n\t};\r\n\r\n\tstruct info_entry {\r\n\t\tconst char * m_name;\r\n\t\tconst char * m_value;\r\n\t};\r\n\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\ttypedef t_uint32 t_index;\r\n\tenum {hintmap_cutoff = 20};\r\n#endif//__file_info_const_impl_have_hintmap__\r\nprivate:\r\n\tpfc::array_t<char> m_buffer;\r\n\tt_index m_meta_count;\r\n\tt_index m_info_count;\r\n\t\r\n\tconst meta_entry * m_meta;\r\n\tconst info_entry * m_info;\r\n\r\n#ifdef __file_info_const_impl_have_hintmap__\r\n\tconst t_index * m_hintmap;\r\n#endif\r\n\r\n\tdouble m_length;\r\n\treplaygain_info m_replaygain;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_list_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic void file_list_remove_duplicates(pfc::ptr_list_t<char> & out)\r\n{\r\n\tt_size n, m = out.get_count();\r\n\tout.sort_t(metadb::path_compare);\r\n\tbit_array_bittable mask(m);\r\n\tt_size duplicates = 0;\r\n\tfor(n=1;n<m;n++) {\r\n\t\tif (!metadb::path_compare(out[n-1],out[n])) {duplicates++;mask.set(n,true);}\r\n\t}\r\n\tif (duplicates>0) {\r\n\t\tout.free_mask(mask);\r\n\t}\r\n}\r\n\r\n\r\nnamespace file_list_helper\r\n{\r\n\tvoid file_list_from_metadb_handle_list::__add(const char * p_what) {\r\n\t\tchar * temp = strdup(p_what);\r\n\t\tif (temp == NULL) throw std::bad_alloc();\r\n\t\ttry {m_data.add_item(temp); } catch(...) {free(temp); throw;}\r\n\t}\r\n\r\n\tvoid file_list_from_metadb_handle_list::init_from_list(const list_base_const_t<metadb_handle_ptr> & p_list)\r\n\t{\r\n\t\tm_data.free_all();\r\n\r\n\t\tt_size n, m = p_list.get_count();\r\n\t\tfor(n=0;n<m;n++) {\r\n\t\t\t__add( p_list.get_item(n)->get_path() );\r\n\t\t}\r\n\t\tfile_list_remove_duplicates(m_data);\r\n\r\n\t}\r\n\r\n\tvoid file_list_from_metadb_handle_list::init_from_list_display(const list_base_const_t<metadb_handle_ptr> & p_list)\r\n\t{\r\n\t\tm_data.free_all();\r\n\t\t\r\n\t\tpfc::string8_fastalloc temp;\r\n\r\n\t\tt_size n, m = p_list.get_count();\r\n\t\tfor(n=0;n<m;n++)\r\n\t\t{\r\n\t\t\tfilesystem::g_get_display_path(p_list.get_item(n)->get_path(),temp);\r\n\t\t\t__add(temp);\r\n\t\t}\r\n\t\tfile_list_remove_duplicates(m_data);\r\n\r\n\r\n\t}\r\n\r\n\tt_size file_list_from_metadb_handle_list::get_count() const {return m_data.get_count();}\r\n\tvoid file_list_from_metadb_handle_list::get_item_ex(const char * & p_out,t_size n) const {p_out = m_data.get_item(n);}\r\n\r\n\tfile_list_from_metadb_handle_list::~file_list_from_metadb_handle_list()\r\n\t{\r\n\t\tm_data.free_all();\r\n\t}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_list_helper.h",
    "content": "#ifndef _foobar2000_helpers_file_list_helper_\r\n#define _foobar2000_helpers_file_list_helper_\r\n\r\n\r\nnamespace file_list_helper\r\n{\r\n\t//list guaranteed to be sorted by metadb::path_compare\r\n\tclass file_list_from_metadb_handle_list : public pfc::list_base_const_t<const char*> {\r\n\tpublic:\r\n\r\n\t\tvoid init_from_list(const list_base_const_t<metadb_handle_ptr> & p_list);\r\n\t\tvoid init_from_list_display(const list_base_const_t<metadb_handle_ptr> & p_list);\r\n\r\n\t\tt_size get_count() const;\r\n\t\tvoid get_item_ex(const char * & p_out,t_size n) const;\r\n\r\n\t\t~file_list_from_metadb_handle_list();\r\n\r\n\tprivate:\r\n\t\tvoid __add(const char * p_what);\r\n\t\tpfc::ptr_list_t<char> m_data;\r\n\t};\r\n\r\n\r\n};\r\n\r\n\r\n#endif //_foobar2000_helpers_file_list_helper_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_move_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic bool grab_items_by_path(pfc::list_base_t<metadb_handle_ptr> & p_out,const char * p_path,abort_callback & p_abort)\r\n{\r\n\ttry {\r\n\t\tpfc::string8 path;\r\n\t\tfilesystem::g_get_canonical_path(p_path,path);\r\n\t\tp_out.remove_all();\r\n\t\tservice_ptr_t<input_info_reader> reader;\r\n\t\tinput_entry::g_open_for_info_read(reader,0,path,p_abort);\r\n\r\n\t\tstatic_api_ptr_t<metadb> l_metadb;\r\n\t\t\r\n\t\tconst t_uint32 count = reader->get_subsong_count();\r\n\t\tfor(t_uint32 n=0;n<count;n++) {\r\n\t\t\tp_abort.check_e();\r\n\t\t\tmetadb_handle_ptr ptr;\r\n\t\t\tl_metadb->handle_create(ptr,make_playable_location(path,reader->get_subsong(n)));\r\n\t\t\tp_out.add_item(ptr);\r\n\t\t}\r\n\r\n\t\treturn p_out.get_count() > 0;\r\n\t} catch(std::exception const &) {return false;}\r\n}\r\n\r\nfile_move_helper::file_move_helper() {}\r\nfile_move_helper::~file_move_helper() {}\r\nfile_move_helper::file_move_helper(const file_move_helper & p_src) {*this = p_src;}\r\n\r\nbool file_move_helper::take_snapshot(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tin_metadb_sync blah;\r\n\r\n\tm_source_handles.remove_all();\r\n\tm_data.set_size(0);\r\n\tif (!grab_items_by_path(m_source_handles,p_path,p_abort)) return false;\r\n\tt_size n, m = m_source_handles.get_count();\r\n\tm_data.set_size(m);\t\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tm_data[n].m_location = m_source_handles[n]->get_location();\r\n\t\tm_data[n].m_have_info = m_source_handles[n]->get_info(m_data[n].m_info);\r\n\t\tm_data[n].m_stats = m_source_handles[n]->get_filestats();\r\n\t\t\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool file_move_helper::on_moved(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tbool ret;\r\n\tfile_move_callback_manager cb;\r\n\tret = on_moved(p_path,p_abort,cb);\r\n\tcb.run_callback();\r\n\treturn ret;\r\n}\r\n\r\nbool file_move_helper::on_copied(const char * p_path,abort_callback & p_abort)\r\n{\r\n\tbool ret;\r\n\tfile_move_callback_manager cb;\r\n\tret = on_copied(p_path,p_abort,cb);\r\n\tcb.run_callback();\r\n\treturn ret;\r\n}\r\n\r\nbool file_move_helper::on_moved(const char * p_path,abort_callback & p_abort,file_move_callback_manager & p_cb)\r\n{\r\n\tfile_path_canonical path(p_path);\r\n\tif (m_data.get_size() == 0) return false;\r\n\tif (!metadb::path_compare(path,get_source_path())) return true;\r\n\r\n\tmetadb_handle_list items;\r\n\tmake_new_item_list(items,path,p_cb);\r\n\t\r\n\r\n\t/*if (p_update_db)*/\r\n\tp_cb.on_library_add_items(items);\r\n\tp_cb.on_library_remove_items(m_source_handles);\r\n\r\n\tp_cb.on_moved(pfc::list_single_ref_t<const char*>(get_source_path()),pfc::list_single_ref_t<const char*>(path));\r\n\r\n\treturn true;\r\n}\r\n\r\nbool file_move_helper::on_copied(const char * p_path,abort_callback & p_abort,file_move_callback_manager & p_cb)\r\n{\r\n\tfile_path_canonical path(p_path);\r\n\tif (m_data.get_size() == 0) return false;\r\n\tif (!metadb::path_compare(path,get_source_path())) return true;\r\n\tmetadb_handle_list items;\r\n\tmake_new_item_list(items,path,p_cb);\r\n\t/*if (p_update_db)*/ p_cb.on_library_add_items(items);\r\n\tp_cb.on_copied(pfc::list_single_ref_t<const char*>(get_source_path()),pfc::list_single_ref_t<const char*>(path));\r\n\treturn true;\r\n}\r\n\r\nbool file_move_helper::g_on_deleted(const pfc::list_base_const_t<const char *> & p_files)\r\n{\r\n\tfile_operation_callback::g_on_files_deleted(p_files);\r\n\treturn true;\r\n}\r\n\r\nvoid file_move_helper::make_new_item_list(pfc::list_base_t<metadb_handle_ptr> & p_out,const char * p_new_path,file_move_callback_manager & p_cb)\r\n{\r\n\tpfc::string8 new_path;\r\n\tfilesystem::g_get_canonical_path(p_new_path,new_path);\r\n\r\n\tt_size n; const t_size m = m_data.get_size();\r\n\tstatic_api_ptr_t<metadb> api;\r\n\tpfc::array_t<metadb_handle_ptr> hint_handles;\r\n\tpfc::array_t<const file_info*> hint_infos;\r\n\tpfc::array_t<t_filestats> hint_stats;\r\n\thint_handles.set_size(m); hint_infos.set_size(m); hint_stats.set_size(m);\r\n\tt_size hintptr = 0;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tmetadb_handle_ptr temp;\r\n\t\tapi->handle_create(temp,make_playable_location(new_path,m_data[n].m_location.get_subsong()));\r\n\t\tif (m_data[n].m_have_info)\r\n\t\t{\r\n\t\t\thint_handles[hintptr] = temp;\r\n\t\t\thint_infos[hintptr] = &m_data[n].m_info;\r\n\t\t\thint_stats[hintptr] = m_data[n].m_stats;\r\n\r\n\t\t\thintptr++;\r\n\t\t}\r\n\t\tp_out.add_item(temp);\r\n\t}\r\n\r\n\tif (hintptr > 0)\r\n\t{\r\n\t\tp_cb.on_hint(\r\n\t\t\tpfc::list_const_array_t<metadb_handle_ptr,const pfc::array_t<metadb_handle_ptr> &>(hint_handles,hintptr),\r\n\t\t\tpfc::list_const_array_t<const file_info *,const pfc::array_t<const file_info *> &>(hint_infos,hintptr),\r\n\t\t\tpfc::list_const_array_t<t_filestats,const pfc::array_t<t_filestats> &>(hint_stats,hintptr)\r\n\t\t\t);\r\n/*\r\n\t\tstatic_api_ptr_t<metadb_io>()->hint_multi(\r\n\t\t\tlist_const_array_t<metadb_handle_ptr,const array_t<metadb_handle_ptr> &>(hint_handles,hintptr),\r\n\t\t\tlist_const_array_t<const file_info *,const array_t<const file_info *> &>(hint_infos,hintptr),\r\n\t\t\tlist_const_array_t<t_filestats,const array_t<t_filestats> &>(hint_stats,hintptr),\r\n\t\t\tbit_array_false());*/\r\n\t}\r\n\r\n}\r\n\r\nconst char * file_move_helper::get_source_path() const\r\n{\r\n\treturn m_data.get_size() > 0 ? m_data[0].m_location.get_path() : 0;\r\n}\r\n\r\nt_size file_move_helper::g_filter_dead_files_sorted_make_mask(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead,bit_array_var & p_mask)\r\n{\r\n\tt_size n, m = p_data.get_count();\r\n\tt_size found = 0;\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tt_size dummy;\r\n\t\tbool dead = p_dead.bsearch_t(metadb::path_compare,p_data.get_item(n)->get_path(),dummy);\r\n\t\tif (dead) found++;\r\n\t\tp_mask.set(n,dead);\r\n\t}\r\n\treturn found;\r\n}\r\n\r\nt_size file_move_helper::g_filter_dead_files_sorted(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead)\r\n{\r\n\tbit_array_bittable mask(p_data.get_count());\r\n\tt_size found = g_filter_dead_files_sorted_make_mask(p_data,p_dead,mask);\r\n\tif (found > 0) p_data.remove_mask(mask);\r\n\treturn found;\r\n}\r\n\r\nt_size file_move_helper::g_filter_dead_files(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead)\r\n{\r\n\tpfc::ptr_list_t<const char> temp;\r\n\ttemp.add_items(p_dead);\r\n\ttemp.sort_t(metadb::path_compare);\r\n\treturn g_filter_dead_files_sorted(p_data,temp);\r\n}\r\n\r\n\r\nvoid file_move_callback_manager::on_library_add_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data)\r\n{\r\n\tm_added.add_items(p_data);\r\n}\r\n\r\nvoid file_move_callback_manager::on_library_remove_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data)\r\n{\r\n\tm_removed.add_items(p_data);\r\n}\r\n\r\nvoid file_move_callback_manager::on_moved(const pfc::string_list_const & p_from,const pfc::string_list_const & p_to)\r\n{\r\n\tassert(p_from.get_count() == p_to.get_count());\r\n\tm_move_from += p_from;\r\n\tm_move_to += p_to;\r\n}\r\n\r\nvoid file_move_callback_manager::on_copied(const pfc::string_list_const & p_from,const pfc::string_list_const & p_to)\r\n{\r\n\tassert(p_from.get_count() == p_to.get_count());\r\n\tm_copy_from += p_from;\r\n\tm_copy_to += p_to;\r\n}\r\n\r\nvoid file_move_callback_manager::on_hint(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_infos,const pfc::list_base_const_t<t_filestats> & p_stats)\r\n{\r\n\tm_hint_handles.add_items(p_list);\r\n\tm_hint_stats.add_items(p_stats);\r\n\r\n\t{\r\n\t\tt_size old_count = m_hint_infos.get_count(), delta = p_infos.get_count();\r\n\t\tm_hint_infos.set_count(old_count + delta);\r\n\t\tfor(t_size n=0;n<delta;n++)\r\n\t\t\tm_hint_infos[old_count+n] = *p_infos[n];\r\n\t}\r\n\t\r\n/*\tmetadb_handle_list m_hint_handles;\r\n\tlist_t<file_info_impl_const> m_hint_infos;\r\n\tlist_t<t_filestats> m_hint_stats;*/\r\n\t\r\n}\r\n\r\n\r\nvoid file_move_callback_manager::run_callback()\r\n{\r\n\tif (m_hint_handles.get_count() > 0)\r\n\t{\r\n\t\tstatic_api_ptr_t<metadb_io>()->hint_multi(\r\n\t\t\tm_hint_handles,\r\n\t\t\tpfc::ptr_list_const_array_t<const file_info,const pfc::list_t<file_info_const_impl> &>(m_hint_infos,m_hint_infos.get_count()),\r\n\t\t\tm_hint_stats,\r\n\t\t\tbit_array_false());\r\n\r\n\t\tm_hint_infos.remove_all();\r\n\t\tm_hint_stats.remove_all();\r\n\r\n\t\t//trick to make sure values don't get wiped\r\n\t\t//m_hint_handles.remove_all();\r\n\r\n\t}\r\n\r\n\tassert(m_copy_from.get_count() == m_copy_to.get_count());\r\n\tassert(m_move_from.get_count() == m_move_to.get_count());\r\n\r\n\tstatic_api_ptr_t<library_manager> api_library_manager;\r\n\r\n\tif (m_added.get_count() > 0)\r\n\t{\r\n\t\tapi_library_manager->add_items(m_added);\r\n\t\tm_added.remove_all();\r\n\t}\r\n\r\n\tif (m_removed.get_count())\r\n\t{\r\n\t\tapi_library_manager->remove_items(m_removed);\r\n\t\tm_removed.remove_all();\r\n\t}\r\n\r\n\tif (m_copy_from.get_count() > 0)\r\n\t{\r\n\t\tfile_operation_callback::g_on_files_copied(m_copy_from,m_copy_to);\r\n\t\tm_copy_from.remove_all();\r\n\t\tm_copy_to.remove_all();\r\n\t}\r\n\r\n\tif (m_move_from.get_count() > 0)\r\n\t{\r\n\t\tfile_operation_callback::g_on_files_moved(m_move_from,m_move_to);\r\n\t\tm_move_from.remove_all();\r\n\t\tm_move_to.remove_all();\r\n\t}\r\n\r\n\t//trick to make sure values don't get wiped\r\n\tm_hint_handles.remove_all();\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_move_helper.h",
    "content": "class file_move_callback_manager\r\n{\r\npublic:\r\n\tvoid on_library_add_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data);\r\n\tvoid on_library_remove_items(const pfc::list_base_const_t<metadb_handle_ptr> & p_data);\r\n\r\n\tvoid on_moved(const pfc::string_list_const & p_from,const pfc::string_list_const & p_to);\r\n\tvoid on_copied(const pfc::string_list_const & p_from,const pfc::string_list_const & p_to);\r\n\r\n\tvoid on_hint(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,const pfc::list_base_const_t<const file_info*> & p_infos,const pfc::list_base_const_t<t_filestats> & p_stats);\r\n\r\n\tvoid run_callback();\r\nprivate:\r\n\tmetadb_handle_list m_removed;\r\n\tmetadb_handle_list m_added;\r\n\r\n\tpfc::string_list_impl m_copy_from,m_copy_to;\r\n\tpfc::string_list_impl m_move_from,m_move_to;\r\n\r\n\tmetadb_handle_list m_hint_handles;\r\n\tpfc::list_t<file_info_const_impl> m_hint_infos;\r\n\tpfc::list_t<t_filestats> m_hint_stats;\r\n};\r\n\r\nclass file_move_helper\r\n{\r\npublic:\r\n\tfile_move_helper();\r\n\t~file_move_helper();\r\n\tfile_move_helper(const file_move_helper & p_src);\r\n\tbool take_snapshot(const char * p_path,abort_callback & p_abort);\r\n\tbool on_moved(const char * p_path,abort_callback & p_abort);\r\n\tbool on_copied(const char * p_path,abort_callback & p_abort);\r\n\tbool on_moved(const char * p_path,abort_callback & p_abort,file_move_callback_manager & p_cb);\r\n\tbool on_copied(const char * p_path,abort_callback & p_abort,file_move_callback_manager & p_cb);\r\n\t\r\n\tstatic bool g_on_deleted(const pfc::list_base_const_t<const char *> & p_files);\r\n\r\n\tstatic t_size g_filter_dead_files_sorted_make_mask(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead,bit_array_var & p_mask);\r\n\tstatic t_size g_filter_dead_files_sorted(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead);\r\n\tstatic t_size g_filter_dead_files(pfc::list_base_t<metadb_handle_ptr> & p_data,const pfc::list_base_const_t<const char*> & p_dead);\r\n\r\nprivate:\r\n\r\n\tstruct t_entry\r\n\t{\r\n\t\tplayable_location_impl m_location;\r\n\t\tfile_info_i m_info;\r\n\t\tt_filestats m_stats;\r\n\t\tbool m_have_info;\r\n\t};\r\n\t\r\n\tmetadb_handle_list m_source_handles;\r\n\r\n\tpfc::array_t<t_entry> m_data;\r\n\r\n\tconst char * get_source_path() const;\r\n\r\n\tvoid make_new_item_list(pfc::list_base_t<metadb_handle_ptr> & p_out,const char * p_path,file_move_callback_manager & p_cb);\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_win32_wrapper.h",
    "content": "namespace file_win32_helpers {\r\n\tstatic t_filesize get_size(HANDLE p_handle) {\r\n\t\tunion {\r\n\t\t\tt_uint64 val64;\r\n\t\t\tt_uint32 val32[2];\r\n\t\t} u;\r\n\r\n\t\tu.val64 = 0;\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tu.val32[0] = GetFileSize(p_handle,reinterpret_cast<DWORD*>(&u.val32[1]));\r\n\t\tif (GetLastError()!=NO_ERROR) exception_io_from_win32(GetLastError());\r\n\t\treturn u.val64;\r\n\t}\r\n\tstatic void seek(HANDLE p_handle,t_sfilesize p_position,file::t_seek_mode p_mode) {\r\n\t\tunion  {\r\n\t\t\tt_int64 temp64;\r\n\t\t\tstruct {\r\n\t\t\t\tDWORD temp_lo;\r\n\t\t\t\tLONG temp_hi;\r\n\t\t\t};\r\n\t\t};\r\n\r\n\t\ttemp64 = p_position;\r\n\t\tSetLastError(ERROR_SUCCESS);\t\t\r\n\t\ttemp_lo = SetFilePointer(p_handle,temp_lo,&temp_hi,(DWORD)p_mode);\r\n\t\tif (GetLastError() != ERROR_SUCCESS) exception_io_from_win32(GetLastError());\r\n\t}\r\n}\r\n\r\ntemplate<bool p_seekable,bool p_writeable>\r\nclass file_win32_wrapper_t : public file {\r\npublic:\r\n\tfile_win32_wrapper_t(HANDLE p_handle) : m_handle(p_handle), m_position(0)\r\n\t{\r\n\t}\r\n\r\n\tstatic service_ptr_t<file> g_CreateFile(const char * p_path,DWORD p_access,DWORD p_sharemode,LPSECURITY_ATTRIBUTES p_security_attributes,DWORD p_createmode,DWORD p_flags,HANDLE p_template) {\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tHANDLE handle = uCreateFile(p_path,p_access,p_sharemode,p_security_attributes,p_createmode,p_flags,p_template);\r\n\t\tif (handle == INVALID_HANDLE_VALUE) exception_io_from_win32(GetLastError());\r\n\t\ttry {\r\n\t\t\treturn g_create_from_handle(handle);\r\n\t\t} catch(...) {CloseHandle(handle); throw;}\r\n\t}\r\n\r\n\tstatic service_ptr_t<file> g_create_from_handle(HANDLE p_handle) {\r\n\t\treturn new service_impl_t<file_win32_wrapper_t<p_seekable,p_writeable> >(p_handle);\r\n\t}\r\n\r\n\r\n\tvoid reopen(abort_callback & p_abort) {seek(0,p_abort);}\r\n\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tif (!p_writeable) throw exception_io_denied();\r\n\r\n\t\tpfc::static_assert_t< (sizeof(t_size) >= sizeof(DWORD)) >();\r\n\r\n\t\tt_size bytes_written_total = 0;\r\n\r\n\t\tif (sizeof(t_size) == sizeof(DWORD)) {\r\n\t\t\tp_abort.check_e();\r\n\t\t\tDWORD bytes_written = 0;\r\n\t\t\tSetLastError(ERROR_SUCCESS);\r\n\t\t\tif (!WriteFile(m_handle,p_buffer,(DWORD)p_bytes,&bytes_written,0)) exception_io_from_win32(GetLastError());\r\n\t\t\tif (bytes_written != p_bytes) throw exception_io(\"Write failure\");\r\n\t\t\tbytes_written_total = bytes_written;\r\n\t\t\tm_position += bytes_written;\r\n\t\t} else {\r\n\t\t\twhile(bytes_written_total < p_bytes) {\r\n\t\t\t\tp_abort.check_e();\r\n\t\t\t\tDWORD bytes_written = 0;\r\n\t\t\t\tDWORD delta = (DWORD) pfc::min_t<t_size>(p_bytes - bytes_written_total, 0x80000000);\r\n\t\t\t\tSetLastError(ERROR_SUCCESS);\r\n\t\t\t\tif (!WriteFile(m_handle,(const t_uint8*)p_buffer + bytes_written_total,delta,&bytes_written,0)) exception_io_from_win32(GetLastError());\r\n\t\t\t\tif (bytes_written != delta) throw exception_io(\"Write failure\");\r\n\t\t\t\tbytes_written_total += bytes_written;\r\n\t\t\t\tm_position += bytes_written;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\t\tpfc::static_assert_t< (sizeof(t_size) >= sizeof(DWORD)) >();\r\n\t\t\r\n\t\tt_size bytes_read_total = 0;\r\n\t\tif (sizeof(t_size) == sizeof(DWORD)) {\r\n\t\t\tp_abort.check_e();\r\n\t\t\tDWORD bytes_read = 0;\r\n\t\t\tSetLastError(ERROR_SUCCESS);\r\n\t\t\tif (!ReadFile(m_handle,p_buffer,pfc::downcast_guarded<DWORD>(p_bytes),&bytes_read,0)) exception_io_from_win32(GetLastError());\r\n\t\t\tbytes_read_total = bytes_read;\r\n\t\t\tm_position += bytes_read;\r\n\t\t} else {\r\n\t\t\twhile(bytes_read_total < p_bytes) {\r\n\t\t\t\tp_abort.check_e();\r\n\t\t\t\tDWORD bytes_read = 0;\r\n\t\t\t\tDWORD delta = (DWORD) pfc::min_t<t_size>(p_bytes - bytes_read_total, 0x80000000);\r\n\t\t\t\tSetLastError(ERROR_SUCCESS);\r\n\t\t\t\tif (!ReadFile(m_handle,(t_uint8*)p_buffer + bytes_read_total,delta,&bytes_read,0)) exception_io_from_win32(GetLastError());\r\n\t\t\t\tbytes_read_total += bytes_read;\r\n\t\t\t\tm_position += bytes_read;\r\n\t\t\t\tif (bytes_read != delta) break;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn bytes_read_total;\r\n\t}\r\n\r\n\r\n\tt_filesize get_size(abort_callback & p_abort) {\r\n\t\tp_abort.check_e();\r\n\t\treturn file_win32_helpers::get_size(m_handle);\r\n\t}\r\n\r\n\tt_filesize get_position(abort_callback & p_abort) {\r\n\t\tp_abort.check_e();\r\n\t\treturn m_position;\r\n\t}\r\n\t\r\n\tvoid resize(t_filesize p_size,abort_callback & p_abort) {\r\n\t\tif (!p_writeable) throw exception_io_denied();\r\n\t\tp_abort.check_e();\r\n\t\tif (m_position != p_size) {\r\n\t\t\tfile_win32_helpers::seek(m_handle,p_size,file::seek_from_beginning);\r\n\t\t}\r\n\t\tSetLastError(ERROR_SUCCESS);\r\n\t\tif (!SetEndOfFile(m_handle)) {\r\n\t\t\tDWORD code = GetLastError();\r\n\t\t\tif (m_position != p_size) try {file_win32_helpers::seek(m_handle,m_position,file::seek_from_beginning);} catch(...) {}\r\n\t\t\texception_io_from_win32(code);\r\n\t\t}\r\n\t\tif (m_position > p_size) m_position = p_size;\r\n\t\tif (m_position != p_size) file_win32_helpers::seek(m_handle,m_position,file::seek_from_beginning);\r\n\t}\r\n\r\n#if 0\r\n\tvoid set_eof(abort_callback & p_abort) {\r\n\t\tif (!p_writeable) throw exception_io_denied();\r\n\t\tp_abort.check_e();\r\n\r\n\t\tSetLastError(ERROR_SUCCESS);\r\n\t\tif (!SetEndOfFile(m_handle)) exception_io_from_win32(GetLastError());\r\n\t}\r\n#endif\r\n\r\n\tvoid seek(t_filesize p_position,abort_callback & p_abort) {\r\n\t\tif (!p_seekable) throw exception_io_object_not_seekable();\r\n\t\tp_abort.check_e();\r\n\t\tif (p_position > file_win32_helpers::get_size(m_handle)) throw exception_io_seek_out_of_range();\r\n\t\tfile_win32_helpers::seek(m_handle,p_position,file::seek_from_beginning);\r\n\t\tm_position = p_position;\r\n\t\t//return seek_ex((t_sfilesize)p_position,file::seek_from_beginning,p_abort);\r\n\t}\r\n#if 0\r\n\tvoid seek_ex(t_sfilesize p_position,file::t_seek_mode p_mode,abort_callback & p_abort) {\r\n\t\tif (!p_seekable) throw exception_io_object_not_seekable();\r\n\t\tp_abort.check_e();\r\n\r\n\t\tfile_win32_helpers::seek(m_handle,p_position,p_mode);\r\n\r\n        m_position = (t_filesize) temp64;\r\n\t}\r\n#endif\r\n\r\n\tbool can_seek() {return p_seekable;}\r\n\tbool get_content_type(pfc::string_base & out) {return false;}\r\n\tbool is_in_memory() {return false;}\r\n\tvoid on_idle(abort_callback & p_abort) {p_abort.check_e();}\r\n\t\r\n\tt_filetimestamp get_timestamp(abort_callback & p_abort) {\r\n\t\tp_abort.check_e();\r\n\t\tFlushFileBuffers(m_handle);\r\n\t\tSetLastError(ERROR_SUCCESS);\r\n\t\tt_filetimestamp temp;\r\n\t\tif (!GetFileTime(m_handle,0,0,(FILETIME*)&temp)) exception_io_from_win32(GetLastError());\r\n\t\treturn temp;\r\n\t}\r\n\r\n\tbool is_remote() {return false;}\r\n\t~file_win32_wrapper_t() {CloseHandle(m_handle);}\r\nprivate:\r\n\tHANDLE m_handle;\r\n\tt_filesize m_position;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_wrapper_simple.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nt_size file_wrapper_simple::read(void * p_buffer,t_size p_bytes) {\r\n\tif (m_has_failed) return 0;\r\n\ttry {\r\n\t\treturn m_file->read(p_buffer,p_bytes,m_abort);\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn 0;\r\n\t}\r\n}\r\n\r\nt_size file_wrapper_simple::write(const void * p_buffer,t_size p_bytes) {\r\n\tif (m_has_failed) return 0;\r\n\ttry {\r\n\t\tm_file->write(p_buffer,p_bytes,m_abort);\r\n\t\treturn p_bytes;\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn 0;\r\n\t}\r\n}\r\n\r\nbool file_wrapper_simple::seek(t_filesize p_offset) {\r\n\tif (m_has_failed) return false;\r\n\ttry {\r\n\t\tm_file->seek(p_offset,m_abort);\r\n\t\treturn true;\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nt_filesize file_wrapper_simple::get_position() {\r\n\tif (m_has_failed) return filesize_invalid;\r\n\ttry {\r\n\t\treturn m_file->get_position(m_abort);\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn filesize_invalid;\r\n\t}\r\n}\r\n\r\nbool file_wrapper_simple::truncate() {\r\n\tif (m_has_failed) return false;\r\n\ttry {\r\n\t\tm_file->set_eof(m_abort);\r\n\t\treturn true;\r\n\t} catch(std::exception) {\r\n\t\tm_has_failed = true;\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\n\r\nt_filesize file_wrapper_simple::get_size() {\r\n\tif (m_has_failed) return filesize_invalid;\r\n\ttry {\r\n\t\treturn m_file->get_size(m_abort);\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn filesize_invalid;\r\n\t}\r\n}\r\n\r\nbool file_wrapper_simple::can_seek() {\r\n\tif (m_has_failed) return false;\r\n\ttry {\r\n\t\treturn m_file->can_seek();\r\n\t} catch(std::exception const &) {\r\n\t\tm_has_failed = true;\r\n\t\treturn false;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/file_wrapper_simple.h",
    "content": "class file_wrapper_simple\r\n{\r\npublic:\r\n\texplicit file_wrapper_simple(const service_ptr_t<file> & p_file,abort_callback & p_abort) : m_file(p_file), m_abort(p_abort), m_has_failed(false) {}\r\n\r\n\tinline bool has_failed() const {return m_has_failed;}\r\n\tinline void reset_status() {m_has_failed = false;}\r\n\r\n\r\n\tt_size read(void * p_buffer,t_size p_bytes);\r\n\tt_size write(const void * p_buffer,t_size p_bytes);\r\n\tbool seek(t_filesize p_offset);\r\n\tt_filesize get_position();\r\n\tt_filesize get_size();\r\n\tbool can_seek();\r\n\tbool truncate();\r\nprivate:\r\n\tservice_ptr_t<file> m_file;\r\n\tabort_callback & m_abort;\r\n\tbool m_has_failed;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/format_title_group.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nnamespace {\r\n\tclass titleformat_hook_impl : public titleformat_hook {\r\n\tpublic:\r\n\t\ttitleformat_hook_impl(pfc::list_base_const_t<metadb_handle_ptr> const & p_items,titleformat_hook * p_hook) : m_hook(p_hook) {\r\n\t\t\tm_infos.set_size(p_items.get_count());\r\n\t\t\tfor(t_size n = 0; n < p_items.get_count(); n++) {\r\n\t\t\t\tif (p_items[n]->get_info_locked(m_infos[n])) m_infos[n] = NULL;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tbool process_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) {\r\n\t\t\tif (m_hook != NULL) {\r\n\t\t\t\tif (m_hook->process_field(p_out,p_name,p_name_length,p_found_flag)) return true;\r\n\t\t\t}\r\n\t\t\tif (process_own_field(p_out,p_name,p_name_length,p_found_flag)) return true;\r\n\t\t\tfor(t_size n = 0; n < m_infos.get_size(); n++) {\r\n\t\t\t\tif (m_infos[n] != NULL) {\r\n\t\t\t\t\tif (titleformat_hook_impl_file_info(make_playable_location(\"\",0),m_infos[n]).process_field(p_out,p_name,p_name_length,p_found_flag))\r\n\t\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbool process_function(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,titleformat_hook_function_params * p_params,bool & p_found_flag) {\r\n\t\t\tif (m_hook != NULL) {\r\n\t\t\t\tif (m_hook->process_function(p_out,p_name,p_name_length,p_params,p_found_flag)) return true;\r\n\t\t\t}\r\n\t\t\tfor(t_size n = 0; n < m_infos.get_size(); n++) {\r\n\t\t\t\tif (m_infos[n] != NULL) {\r\n\t\t\t\t\tif (titleformat_hook_impl_file_info(make_playable_location(\"\",0),m_infos[n]).process_function(p_out,p_name,p_name_length,p_params,p_found_flag))\r\n\t\t\t\t\t\treturn true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn false;\r\n\t\t}\r\n\tprivate:\r\n\t\tbool process_own_field(titleformat_text_out * p_out,const char * p_name,t_size p_name_length,bool & p_found_flag) {\r\n\t\t\tif (stricmp_utf8_ex(p_name,p_name_length,\"multiitem\",infinite) == 0) {\r\n\t\t\t\tif (m_infos.get_size() > 1) {\r\n\t\t\t\t\tp_out->write_int(titleformat_inputtypes::unknown,1);\r\n\t\t\t\t\tp_found_flag = true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tp_out->write_int(titleformat_inputtypes::unknown,0);\r\n\t\t\t\t\tp_found_flag = false;\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tin_metadb_sync m_lock;\r\n\t\ttitleformat_hook * m_hook;\r\n\t\tpfc::array_t<const file_info*> m_infos;\r\n\t};\r\n\t\r\n}\r\n\r\nvoid format_title_group(pfc::list_base_const_t<metadb_handle_ptr> const & p_items,titleformat_hook * p_hook,pfc::string_base & p_out,service_ptr_t<titleformat_object> p_script,titleformat_text_filter * p_filter) {\r\n\tp_script->run(&titleformat_hook_impl(p_items,p_hook),p_out,p_filter);\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/format_title_group.h",
    "content": "void format_title_group(pfc::list_base_const_t<metadb_handle_ptr> const & p_list,titleformat_hook * p_hook,pfc::string_base & p_out,service_ptr_t<titleformat_object> p_script,titleformat_text_filter * p_filter);"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/helpers.h",
    "content": "#ifndef _FOOBAR2000_SDK_HELPERS_H_\r\n#define _FOOBAR2000_SDK_HELPERS_H_\r\n\r\n#include \"input_helpers.h\"\r\n#include \"create_directory_helper.h\"\r\n#include \"dialog_resize_helper.h\"\r\n#include \"dropdown_helper.h\"\r\n#include \"window_placement_helper.h\"\r\n#include \"win32_dialog.h\"\r\n#include \"wildcard.h\"\r\n#include \"cuesheet_index_list.h\"\r\n#include \"cue_creator.h\"\r\n#include \"cue_parser.h\"\r\n#include \"search_filter.h\"\r\n#include \"text_file_loader.h\"\r\n#include \"file_list_helper.h\"\r\n#include \"preload_info_helper.h\"\r\n#include \"listview_helper.h\"\r\n#include \"stream_buffer_helper.h\"\r\n#include \"file_info_const_impl.h\"\r\n#include \"file_wrapper_simple.h\"\r\n#include \"dynamic_bitrate_helper.h\"\r\n#include \"cfg_guidlist.h\"\r\n#include \"cfg_structlist.h\"\r\n#include \"file_win32_wrapper.h\"\r\n#include \"file_move_helper.h\"\r\n#include \"file_cached.h\"\r\n#include \"seekabilizer.h\"\r\n#include \"string_filter.h\"\r\n#include \"bitreader_helper.h\"\r\n#include \"mp3_utils.h\"\r\n#include \"win32_misc.h\"\r\n#include \"metadb_io_hintlist.h\"\r\n#include \"format_title_group.h\"\r\n#include \"inplace_edit.h\"\r\n#include \"meta_table_builder.h\"\r\n\r\n#endif //_FOOBAR2000_SDK_HELPERS_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/inplace_edit.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\n\r\nusing namespace InPlaceEdit;\r\n\r\n\r\nstatic const TCHAR g_prop_instance[] = _T(\"{91154665-2B6A-42da-BB2A-A132EC20927F}\");\r\n\r\n\r\nnamespace {\r\n\r\n\tstatic pfc::avltree_t<HWND> g_editboxes;\r\n\tstatic HHOOK g_hook = NULL;\r\n\r\n\tstatic LRESULT CALLBACK GMouseProc(int nCode,WPARAM wParam,LPARAM lParam) {\r\n\t\tif (nCode >= 0) {\r\n\t\t\tconst MOUSEHOOKSTRUCT * mhs = (const MOUSEHOOKSTRUCT *) lParam;\r\n\t\t\tswitch(wParam) {\r\n\t\t\tcase WM_NCLBUTTONDOWN:\r\n\t\t\tcase WM_NCRBUTTONDOWN:\r\n\t\t\tcase WM_NCMBUTTONDOWN:\r\n\t\t\tcase WM_NCXBUTTONDOWN:\r\n\t\t\tcase WM_LBUTTONDOWN:\r\n\t\t\tcase WM_RBUTTONDOWN:\r\n\t\t\tcase WM_MBUTTONDOWN:\r\n\t\t\tcase WM_XBUTTONDOWN:\r\n\t\t\t\tif (!g_editboxes.have_item(mhs->hwnd)) {\r\n\t\t\t\t\tSetFocus(mhs->hwnd);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn CallNextHookEx(g_hook,nCode,wParam,lParam);\r\n\t}\r\n\r\n\tvoid on_editbox_creation(HWND p_editbox) {\r\n\t\tg_editboxes.add(p_editbox);\r\n\t\tif (g_hook == NULL) {\r\n\t\t\tg_hook = SetWindowsHookEx(WH_MOUSE,GMouseProc,NULL,GetCurrentThreadId());\r\n\t\t}\r\n\t}\r\n\tvoid on_editbox_destruction(HWND p_editbox) {\r\n\t\tg_editboxes.remove(p_editbox);\r\n\t\tif (g_editboxes.get_count() == 0 && g_hook != NULL) {\r\n\t\t\tUnhookWindowsHookEx(pfc::replace_null_t(g_hook));\r\n\t\t}\r\n\t}\r\n\r\n\tenum {\r\n\t\tMSG_COMPLETION = WM_USER,\r\n\t\tMSG_DISABLE_EDITING,\r\n\t};\r\n\r\nclass InPlaceEditHook {\r\npublic:\r\n\tInPlaceEditHook(HWND p_wnd) : m_oldproc(NULL) \r\n\t{\r\n\t\tSetProp(p_wnd,g_prop_instance,reinterpret_cast<HANDLE>(this));\r\n\t\tm_oldproc = uHookWindowProc(p_wnd,GEditHook);\r\n\t\ton_editbox_creation(p_wnd);\r\n\t}\r\nprivate:\r\n\tstatic void ForwardCompletion(HWND p_mywnd,unsigned p_code) {\r\n\t\tHWND owner = GetParent(p_mywnd);\r\n\t\tSendMessage(owner,MSG_DISABLE_EDITING,0,0);\r\n\t\tPostMessage(owner,MSG_COMPLETION,p_code,0);\r\n\t\tEnableWindow(p_mywnd,FALSE);\r\n\t}\r\n\t~InPlaceEditHook() {}\r\n\tLRESULT EditHook(HWND p_wnd,UINT p_msg,WPARAM p_wp,LPARAM p_lp) {\r\n\t\tswitch(p_msg) {\r\n\t\tcase WM_GETDLGCODE:\r\n\t\t\treturn DLGC_WANTALLKEYS;\r\n\t\tcase WM_KILLFOCUS:\r\n\t\t\tForwardCompletion(p_wnd,KEditLostFocus);\r\n\t\t\treturn m_oldproc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\tcase WM_CHAR:\r\n\t\t\tswitch(p_wp) {\r\n\t\t\tcase VK_RETURN:\r\n\t\t\t\tif (!IsKeyPressed(VK_LCONTROL) && !IsKeyPressed(VK_RCONTROL)) {\r\n\t\t\t\t\tForwardCompletion(p_wnd,KEditEnter);\r\n\t\t\t\t\treturn 0;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase VK_TAB:\r\n\t\t\t\tForwardCompletion(p_wnd,IsKeyPressed(VK_SHIFT) ? KEditShiftTab : KEditTab);\r\n\t\t\t\treturn 0;\r\n\t\t\tcase VK_ESCAPE:\r\n\t\t\t\tForwardCompletion(p_wnd,KEditAborted);\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\treturn m_oldproc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\tcase WM_DESTROY:\r\n\t\t\t{\r\n\t\t\t\tWNDPROC l_wndproc = m_oldproc;\r\n\t\t\t\tuHookWindowProc(p_wnd,l_wndproc);\r\n\t\t\t\tRemoveProp(p_wnd,g_prop_instance);\r\n\t\t\t\ton_editbox_destruction(p_wnd);\r\n\t\t\t\ttry {delete this;} catch(...) {}\r\n\t\t\t\treturn l_wndproc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\t\t}\r\n\t\tdefault:\r\n\t\t\treturn m_oldproc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\t}\r\n\t}\r\n\r\n\tstatic LRESULT CALLBACK GEditHook(HWND p_wnd,UINT p_msg,WPARAM p_wp,LPARAM p_lp) {\r\n\t\tInPlaceEditHook * instance = reinterpret_cast<InPlaceEditHook*>( GetProp(p_wnd,g_prop_instance) );\r\n\t\tif (instance == NULL) return DefWindowProc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\treturn instance->EditHook(p_wnd,p_msg,p_wp,p_lp);\r\n\t}\r\n\r\n\tWNDPROC m_oldproc;\r\n};\r\n\r\nclass InPlaceEditContainer {\r\npublic:\r\n\tInPlaceEditContainer(HWND p_parentwnd,const RECT & p_rect,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify) \r\n\t\t: m_content(p_content), m_notify(p_notify), m_completed(false), m_initialized(false), m_changed(false), m_disable_editing(false) {\r\n\t\t{\r\n\t\t\tstatic volatile unsigned increment;\r\n\t\t\tTCHAR classname[64];\r\n\t\t\twsprintf(classname,_T(\"{54340C80-248C-4b8e-8CD4-D624A8E9377B}/%u\"),++increment);\r\n\t\t\tm_class_scope.toggle_on(0,GWndProc,0,sizeof(void*),NULL,NULL,NULL,classname,NULL);\r\n\t\t}\r\n\r\n\t\tHWND container, edit;\r\n\r\n\r\n\t\tRECT rect_cropped;\r\n\t\t{\r\n\t\t\tRECT client;\r\n\t\t\tSetLastError(0);\r\n\t\t\tif (!GetClientRect(p_parentwnd,&client)) throw exception_win32(GetLastError());\r\n\t\t\tIntersectRect(&rect_cropped,&client,&p_rect);\r\n\t\t}\r\n\t\tAdjustWindowRect(&rect_cropped,WS_BORDER|WS_CHILD,FALSE);\r\n\r\n\t\tSetLastError(0);\r\n\t\tcontainer = CreateWindowEx(\r\n\t\t\t0,\r\n\t\t\t(const TCHAR*) m_class_scope.get_class(),\r\n\t\t\t_T(\"\"),\r\n\t\t\tWS_BORDER|WS_CHILD,\r\n\t\t\trect_cropped.left,rect_cropped.top,\r\n\t\t\trect_cropped.right-rect_cropped.left,rect_cropped.bottom-rect_cropped.top,\r\n\t\t\tp_parentwnd,NULL,\r\n\t\t\tcore_api::get_my_instance(),reinterpret_cast<void*>(this));\r\n\t\tif (container == NULL) throw exception_win32(GetLastError());\r\n\r\n\t\ttry {\r\n\t\t\t\r\n\t\t\tRECT parent_client;\r\n\t\t\tSetLastError(0);\r\n\t\t\tif (!GetClientRect(container,&parent_client)) throw exception_win32(GetLastError());\r\n\t\t\tSetLastError(0);\r\n\t\t\tedit = CreateWindowEx(\r\n\t\t\t\t/*WS_EX_STATICEDGE*/ 0,\r\n\t\t\t\tWC_EDIT,TEXT(\"\"),\r\n\t\t\t\t((p_flags & KFlagMultiLine) ? (WS_VSCROLL|ES_MULTILINE) : ES_AUTOHSCROLL) | \r\n\t\t\t\t((p_flags & KFlagReadOnly) ? ES_READONLY : 0) |\r\n\t\t\t\tWS_CHILD|ES_LEFT|WS_VISIBLE,//parent is invisible now\r\n\t\t\t\t0,0,\r\n\t\t\t\tparent_client.right,parent_client.bottom,\r\n\t\t\t\tcontainer,\r\n\t\t\t\t(HMENU)ID_MYEDIT,\r\n\t\t\t\tcore_api::get_my_instance(),\r\n\t\t\t\t0);\r\n\r\n\t\t\tif (edit == NULL) throw exception_win32(GetLastError());\r\n\r\n\t\t\tSendMessage(edit,WM_SETFONT,SendMessage(p_parentwnd,WM_GETFONT,0,0),0);\r\n\r\n\t\t\tuSetWindowText(edit,*m_content);\r\n\t\t\tSendMessage(edit,EM_SETSEL,0,-1);\r\n\t\t} catch(...) {\r\n\t\t\tPostMessage(container,MSG_COMPLETION,InPlaceEdit::KEditAborted,0);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\ttry {\r\n\t\t\tnew InPlaceEditHook(edit);\r\n\t\t} catch(...) {\r\n\t\t\tPostMessage(container,MSG_COMPLETION,InPlaceEdit::KEditAborted,0);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tShowWindow(container,SW_SHOW);\r\n\t\tSetFocus(edit);\r\n\r\n\t\tm_initialized = true;\r\n\t}\r\nprivate:\r\n\tenum {ID_MYEDIT = 666};\r\n\r\n\tLRESULT WndProc(HWND p_wnd,UINT p_msg,WPARAM p_wp,LPARAM p_lp) {\r\n\t\tswitch(p_msg) {\r\n\t\tcase WM_MOUSEWHEEL:\r\n\t\t\treturn 0;\r\n\t\tcase MSG_DISABLE_EDITING:\r\n\t\t\tShowWindow(p_wnd,SW_HIDE);\r\n\t\t\tUpdateWindow(GetParent(p_wnd));\r\n\t\t\tm_disable_editing = true;\r\n\t\t\treturn 0;\r\n\t\tcase MSG_COMPLETION:\r\n\t\t\tPFC_ASSERT(m_initialized);\r\n\t\t\tif ((p_wp & KEditMaskReason) != KEditLostFocus) {\r\n\t\t\t\tSetFocus(GetParent(p_wnd));\r\n\t\t\t}\r\n\t\t\tOnCompletion(p_wp);\r\n\t\t\tDestroyWindow(p_wnd);\r\n\t\t\treturn 0;\r\n\t\tcase WM_COMMAND:\r\n\t\t\tswitch(p_wp) {\r\n\t\t\tcase (EN_CHANGE << 16) | ID_MYEDIT:\r\n\t\t\t\tif (m_initialized && !m_disable_editing) {\r\n\t\t\t\t\tuGetDlgItemText(p_wnd,ID_MYEDIT,*m_content);\r\n\t\t\t\t\tm_changed = true;\r\n\t\t\t\t}\r\n\t\t\t\treturn 0;\r\n\t\t\tdefault:\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t\t\r\n\t\tcase WM_DESTROY:\r\n\t\t\ttry {delete this;}catch(...){}\r\n\t\t\tSetWindowLongPtr(p_wnd,0,NULL);\r\n\t\t\treturn DefWindowProc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\tdefault:\r\n\t\t\treturn DefWindowProc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\t}\r\n\t}\r\n\tstatic LRESULT CALLBACK GWndProc(HWND p_wnd,UINT p_msg,WPARAM p_wp,LPARAM p_lp) {\r\n\t\tif (p_msg == WM_CREATE) {\r\n\t\t\tconst CREATESTRUCT * ptr = reinterpret_cast<const CREATESTRUCT*>(p_lp);\r\n\t\t\tSetWindowLongPtr(p_wnd,0,reinterpret_cast<LONG_PTR>(ptr->lpCreateParams));\r\n\t\t}\r\n\r\n\t\tInPlaceEditContainer * instance = reinterpret_cast<InPlaceEditContainer*>(GetWindowLongPtr(p_wnd,0));\r\n\t\tif (instance != NULL) {\r\n\t\t\treturn instance->WndProc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\t} else {\r\n\t\t\treturn DefWindowProc(p_wnd,p_msg,p_wp,p_lp);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid OnCompletion(unsigned p_status) {\r\n\t\tif (!m_completed) {\r\n\t\t\tm_completed = true;\r\n\t\t\tp_status &= KEditMaskReason;\r\n\t\t\tunsigned code = p_status;\r\n\t\t\tif (m_changed && p_status != KEditAborted) code |= KEditFlagContentChanged;\r\n\t\t\tif (m_notify.is_valid()) m_notify->on_completion(code);\r\n\t\t}\r\n\t}\r\n\r\n\tregisterclass_scope_delayed m_class_scope;\r\n\tpfc::rcptr_t<pfc::string_base> m_content;\r\n\tcompletion_notify_ptr m_notify;\r\n\tbool m_completed;\r\n\tbool m_initialized, m_changed;\r\n\tbool m_disable_editing;\r\n};\r\n\r\n}\r\n\r\nstatic void fail(completion_notify_ptr p_notify) {\r\n\tcompletion_notify::g_signal_completion_async(p_notify,KEditAborted);\r\n}\r\n\r\nvoid InPlaceEdit::Start(HWND p_parentwnd,const RECT & p_rect,bool p_multiline,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify) {\r\n\tStartEx(p_parentwnd,p_rect,p_multiline ? KFlagMultiLine : 0, p_content,p_notify);\r\n}\r\n\r\nvoid InPlaceEdit::Start_FromListView(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify) {\r\n\tStart_FromListViewEx(p_listview,p_item,p_subitem,p_linecount,0,p_content,p_notify);\r\n}\r\n\r\nbool InPlaceEdit::TableEditAdvance(unsigned & p_item,unsigned & p_column, unsigned p_item_count,unsigned p_column_count, unsigned p_whathappened) {\r\n\tif (p_item >= p_item_count || p_column >= p_column_count) return false;\r\n\tint delta = 0;\r\n\r\n\tswitch(p_whathappened & KEditMaskReason) {\r\n\tcase KEditEnter:\r\n\t\tdelta = (int) p_column_count;\r\n\t\tbreak;\r\n\tcase KEditTab:\r\n\t\tdelta = 1;\r\n\t\tbreak;\r\n\tcase KEditShiftTab:\r\n\t\tdelta = -1;\r\n\t\tbreak;\r\n\tdefault:\r\n\t\treturn false;\r\n\t}\r\n\twhile(delta > 0) {\r\n\t\tp_column++;\r\n\t\tif (p_column >= p_column_count) {\r\n\t\t\tp_column = 0;\r\n\t\t\tp_item++;\r\n\t\t\tif (p_item >= p_item_count) return false;\r\n\t\t}\r\n\t\tdelta--;\r\n\t}\r\n\twhile(delta < 0) {\r\n\t\tif (p_column == 0) {\r\n\t\t\tif (p_item == 0) return false;\r\n\t\t\tp_item--;\r\n\t\t\tp_column = p_column_count;\r\n\t\t} \r\n\t\tp_column--;\r\n\t\tdelta++;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid InPlaceEdit::StartEx(HWND p_parentwnd,const RECT & p_rect,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify) {\r\n\ttry {\r\n\t\tnew InPlaceEditContainer(p_parentwnd,p_rect,p_flags,p_content,p_notify);\r\n\t} catch(...) {\r\n\t\tfail(p_notify);\r\n\t}\r\n}\r\n\r\nvoid InPlaceEdit::Start_FromListViewEx(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify) {\r\n\ttry {\r\n\t\tListView_EnsureVisible(p_listview,p_item,FALSE);\r\n\t\tRECT itemrect;\r\n\t\tif (!ListView_GetSubItemRect(p_listview,p_item,p_subitem,LVIR_BOUNDS,&itemrect)) throw pfc::exception(\"ListView_GetSubItemRect failure\");\r\n\r\n\t\tconst bool multiline = p_linecount > 1;\r\n\t\tif (multiline) {\r\n\t\t\titemrect.bottom = itemrect.top + (itemrect.bottom - itemrect.top) * p_linecount;\r\n\t\t}\r\n\r\n\t\tStartEx(p_listview,itemrect,p_flags | (multiline ? KFlagMultiLine : 0),p_content,p_notify);\r\n\t} catch(...) {\r\n\t\tfail(p_notify);\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/inplace_edit.h",
    "content": "namespace InPlaceEdit {\r\n\r\n\tenum {\r\n\t\tKEditAborted = 0,\r\n\t\tKEditTab,\r\n\t\tKEditShiftTab,\r\n\t\tKEditEnter,\r\n\t\tKEditLostFocus,\r\n\r\n\t\tKEditMaskReason = 0xFF,\r\n\t\tKEditFlagContentChanged = 0x100,\r\n\r\n\t\tKFlagReadOnly\t= 1 << 0,\r\n\t\tKFlagMultiLine\t= 1 << 1,\r\n\t};\r\n\r\n\tvoid Start(HWND p_parentwnd,const RECT & p_rect,bool p_multiline,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);\r\n\r\n\tvoid StartEx(HWND p_parentwnd,const RECT & p_rect,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);\r\n\r\n\tvoid Start_FromListView(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);\r\n\tvoid Start_FromListViewEx(HWND p_listview,unsigned p_item,unsigned p_subitem,unsigned p_linecount,unsigned p_flags,pfc::rcptr_t<pfc::string_base> p_content,completion_notify_ptr p_notify);\r\n\t\r\n\tbool TableEditAdvance(unsigned & p_item,unsigned & p_column, unsigned p_item_count,unsigned p_column_count, unsigned p_whathappened);\r\n\r\n\r\n\tclass CTableEditHelper {\r\n\tpublic:\r\n\t\tvoid TableEdit_Start(HWND p_listview,unsigned p_item,unsigned p_column,unsigned p_itemcount,unsigned p_columncount,unsigned p_basecolumn,unsigned p_flags = 0) {\r\n\t\t\tif (m_notify.is_valid()) return;\r\n\t\t\tm_listview = p_listview;\r\n\t\t\tm_item = p_item;\r\n\t\t\tm_column = p_column;\r\n\t\t\tm_itemcount = p_itemcount;\r\n\t\t\tm_columncount = p_columncount;\r\n\t\t\tm_basecolumn = p_basecolumn;\r\n\t\t\tm_flags = p_flags;\r\n\t\t\t__Start();\r\n\t\t}\r\n\r\n\t\tvoid TableEdit_Abort(bool p_forwardcontent) {\r\n\t\t\tif (m_notify.is_valid()) {\r\n\t\t\t\tm_notify->orphan();\r\n\t\t\t\tm_notify.release();\r\n\r\n\t\t\t\tif (p_forwardcontent) {\r\n\t\t\t\t\tif (m_content.is_valid()) {\r\n\t\t\t\t\t\tpfc::string8 temp(*m_content);\r\n\t\t\t\t\t\tm_content.release();\r\n\t\t\t\t\t\tTableEdit_SetItemText(m_item,m_column,temp);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else {\r\n\t\t\t\t\tm_content.release();\r\n\t\t\t\t}\r\n\t\t\t\tSetFocus(NULL);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tbool TableEdit_IsActive() const {\r\n\t\t\treturn m_notify.is_valid();\r\n\t\t}\r\n\r\n\t\tvirtual bool TableEdit_GetItemText(unsigned p_item,unsigned p_column,pfc::string_base & p_out,unsigned & p_linecount) {\r\n\t\t\tlistview_helper::get_item_text(m_listview,p_item,p_column + m_basecolumn,p_out);\r\n\t\t\tp_linecount = pfc::is_multiline(p_out) ? 5 : 1;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tvirtual void TableEdit_SetItemText(unsigned p_item,unsigned p_column,const char * p_text) {\r\n\t\t\tlistview_helper::set_item_text(m_listview,p_item,p_column + m_basecolumn,p_text);\r\n\t\t}\r\n\t\t\r\n\t\tvoid on_task_completion(unsigned p_taskid,unsigned p_state) {\r\n\t\t\tif (p_taskid == KTaskID) {\r\n\t\t\t\tm_notify.release();\t\t\t\r\n\t\t\t\tif (m_content.is_valid()) {\r\n\t\t\t\t\tif (p_state & InPlaceEdit::KEditFlagContentChanged) {\r\n\t\t\t\t\t\tTableEdit_SetItemText(m_item,m_column,*m_content);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tm_content.release();\r\n\t\t\t\t}\r\n\t\t\t\tif (InPlaceEdit::TableEditAdvance(m_item,m_column,m_itemcount,m_columncount,p_state)) {\r\n\t\t\t\t\t__Start();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t~CTableEditHelper() {\r\n\t\t\tif (m_notify.is_valid()) {\r\n\t\t\t\tm_notify->orphan();\r\n\t\t\t\tm_notify.release();\r\n\t\t\t}\r\n\t\t}\r\n\tprotected:\r\n\t\tHWND TableEdit_GetListView() const {return m_listview;}\r\n\tprivate:\r\n\t\tvoid __Start() {\r\n\t\t\tlistview_helper::select_single_item(m_listview,m_item);\r\n\t\t\tm_content.new_t();\r\n\t\t\tunsigned linecount = 1;\r\n\t\t\tif (!TableEdit_GetItemText(m_item,m_column,*m_content,linecount)) return;\r\n\t\t\tm_notify = completion_notify_create(this,KTaskID);\r\n\t\t\tInPlaceEdit::Start_FromListViewEx(m_listview,m_item,m_column+m_basecolumn,linecount,m_flags,m_content,m_notify);\r\n\t\t}\r\n\t\tenum {\r\n\t\t\tKTaskID = 0xc0ffee\r\n\t\t};\r\n\t\tHWND m_listview;\r\n\t\tunsigned m_item,m_column;\r\n\t\tunsigned m_itemcount,m_columncount,m_basecolumn;\r\n\t\tunsigned m_flags;\r\n\t\tpfc::rcptr_t<pfc::string8> m_content;\r\n\t\tservice_ptr_t<completion_notify_orphanable> m_notify;\r\n\t};\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/input_helpers.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nvoid input_helper::open(service_ptr_t<file> p_filehint,metadb_handle_ptr p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints)\r\n{\r\n\topen(p_filehint,p_location->get_location(),p_flags,p_abort,p_from_redirect,p_skip_hints);\r\n}\r\n\r\nstatic void process_fullbuffer(service_ptr_t<file> & p_file,const char * p_path,t_filesize p_fullbuffer,abort_callback & p_abort) {\r\n\tif (p_fullbuffer > 0) {\r\n\t\tif (p_file.is_empty()) {\r\n\t\t\tservice_ptr_t<filesystem> fs;\r\n\t\t\tif (filesystem::g_get_interface(fs,p_path)) {\r\n\t\t\t\tfs->open(p_file,p_path,filesystem::open_mode_read,p_abort);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (p_file.is_valid()) {\r\n\t\t\tt_filesize size = p_file->get_size(p_abort);\r\n\t\t\tif (size != filesize_invalid && size <= p_fullbuffer) {\r\n\t\t\t\tservice_ptr_t<file> l_file_buffered;\r\n\t\t\t\tif (reader_membuffer_mirror::g_create(l_file_buffered,p_file,p_abort)) {\r\n\t\t\t\t\tp_file = l_file_buffered;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid input_helper::open(service_ptr_t<file> p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect,bool p_skip_hints) {\r\n\tp_abort.check();\r\n\r\n\tif (m_input.is_empty() || metadb::path_compare(p_location.get_path(),m_path) != 0)\r\n\t{\r\n\t\tm_input.release();\r\n\r\n\t\tservice_ptr_t<file> l_file = p_filehint;\r\n\t\tprocess_fullbuffer(l_file,p_location.get_path(),m_fullbuffer,p_abort);\r\n\r\n\t\tTRACK_CODE(\"input_entry::g_open_for_decoding\",\r\n\t\t\tinput_entry::g_open_for_decoding(m_input,l_file,p_location.get_path(),p_abort,p_from_redirect)\r\n\t\t\t);\r\n\r\n\t\t\r\n\t\tif (!p_skip_hints) {\r\n\t\t\ttry {\r\n\t\t\t\tstatic_api_ptr_t<metadb_io>()->hint_reader(m_input.get_ptr(),p_location.get_path(),p_abort);\r\n\t\t\t} catch(exception_io_data) {\r\n\t\t\t\t//don't fail to decode when this barfs\r\n\t\t\t\tm_input.release();\r\n\t\t\t\tif (l_file.is_valid()) l_file->reopen(p_abort);\r\n\t\t\t\tTRACK_CODE(\"input_entry::g_open_for_decoding\",\r\n\t\t\t\t\tinput_entry::g_open_for_decoding(m_input,l_file,p_location.get_path(),p_abort,p_from_redirect)\r\n\t\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tm_path = p_location.get_path();\r\n\t}\r\n\r\n\tTRACK_CODE(\"input_decoder::initialize\",m_input->initialize(p_location.get_subsong_index(),p_flags,p_abort));\r\n}\r\n\r\n\r\nvoid input_helper::close() {\r\n\tm_input.release();\r\n}\r\n\r\nbool input_helper::is_open() {\r\n\treturn m_input.is_valid();\r\n}\r\n\r\nbool input_helper::run(audio_chunk & p_chunk,abort_callback & p_abort)\r\n{\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::run\",return m_input->run(p_chunk,p_abort));\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nvoid input_helper::seek(double seconds,abort_callback & p_abort)\r\n{\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::seek\",m_input->seek(seconds,p_abort));\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nbool input_helper::can_seek() {\r\n\tif (m_input.is_valid()) {\r\n\t\treturn m_input->can_seek();\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nvoid input_helper::set_full_buffer(t_filesize val) {\r\n\tm_fullbuffer = val;\r\n}\r\nvoid input_helper::on_idle(abort_callback & p_abort) {\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::on_idle\",m_input->on_idle(p_abort));\r\n\t}\r\n}\r\n\r\nbool input_helper::get_dynamic_info(file_info & p_out,double & p_timestamp_delta) {\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::get_dynamic_info\",return m_input->get_dynamic_info(p_out,p_timestamp_delta));\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nbool input_helper::get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta) {\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::get_dynamic_info_track\",return m_input->get_dynamic_info_track(p_out,p_timestamp_delta));\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nvoid input_helper::get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {\r\n\tif (m_input.is_valid()) {\r\n\t\tTRACK_CODE(\"input_decoder::get_info\",m_input->get_info(p_subsong,p_info,p_abort));\r\n\t} else {\r\n\t\tthrow pfc::exception_bug_check();\r\n\t}\r\n}\r\n\r\nconst char * input_helper::get_path() const {\r\n\treturn m_path;\r\n}\r\n\r\n\r\ninput_helper::input_helper() : m_fullbuffer(0)\r\n{\r\n}\r\n\r\n\r\nvoid input_helper::g_get_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect) {\r\n\tservice_ptr_t<input_info_reader> instance;\r\n\tinput_entry::g_open_for_info_read(instance,0,p_location.get_path(),p_abort,p_from_redirect);\r\n\tinstance->get_info(p_location.get_subsong_index(),p_info,p_abort);\r\n}\r\n\r\nvoid input_helper::g_set_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect) {\r\n\tservice_ptr_t<input_info_writer> instance;\r\n\tinput_entry::g_open_for_info_write(instance,0,p_location.get_path(),p_abort,p_from_redirect);\r\n\tinstance->set_info(p_location.get_subsong_index(),p_info,p_abort);\r\n\tinstance->commit(p_abort);\r\n}\r\n\r\n\r\nbool dead_item_filter::run(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,bit_array_var & p_mask) {\r\n\tfile_list_helper::file_list_from_metadb_handle_list path_list;\r\n\tpath_list.init_from_list(p_list);\r\n\tmetadb_handle_list valid_handles;\r\n\tstatic_api_ptr_t<metadb> l_metadb;\r\n\tfor(t_size pathidx=0;pathidx<path_list.get_count();pathidx++)\r\n\t{\r\n\t\tif (is_aborting()) return false;\r\n\t\ton_progress(pathidx,path_list.get_count());\r\n\r\n\t\tconst char * path = path_list[pathidx];\r\n\r\n\t\tif (filesystem::g_is_remote_safe(path)) {\r\n\t\t\tmetadb_handle_ptr temp;\r\n\t\t\tl_metadb->handle_create(temp,make_playable_location(path,0));\r\n\t\t\tvalid_handles.add_item(temp);\r\n\t\t} else {\r\n\t\t\ttry {\r\n\t\t\t\tservice_ptr_t<input_info_reader> reader;\r\n\t\t\t\t\r\n\t\t\t\tinput_entry::g_open_for_info_read(reader,0,path,*this);\r\n\t\t\t\tt_uint32 count = reader->get_subsong_count();\r\n\t\t\t\tfor(t_uint32 n=0;n<count && !is_aborting();n++) {\r\n\t\t\t\t\tmetadb_handle_ptr ptr;\r\n\t\t\t\t\tt_uint32 index = reader->get_subsong(n);\r\n\t\t\t\t\tl_metadb->handle_create(ptr,make_playable_location(path,index));\r\n\t\t\t\t\tvalid_handles.add_item(ptr);\r\n\t\t\t\t}\r\n\t\t\t} catch(...) {}\r\n\t\t}\r\n\t}\r\n\r\n\tif (is_aborting()) return false;\r\n\r\n\tvalid_handles.sort_by_pointer();\r\n\tfor(t_size listidx=0;listidx<p_list.get_count();listidx++) {\r\n\t\tbool dead = valid_handles.bsearch_by_pointer(p_list[listidx]) == infinite;\r\n\t\tif (dead) console::formatter() << \"Dead item: \" << p_list[listidx];\r\n\t\tp_mask.set(listidx,dead);\r\n\t}\r\n\treturn !is_aborting();\r\n}\r\n\r\nnamespace {\r\n\r\nclass dead_item_filter_impl_simple : public dead_item_filter\r\n{\r\npublic:\r\n\tinline dead_item_filter_impl_simple(abort_callback & p_abort) : m_abort(p_abort) {}\r\n\tbool is_aborting() const {return m_abort.is_aborting();}\r\n\tabort_callback_event get_abort_event() const {return m_abort.get_abort_event();}\r\n\tvoid on_progress(t_size p_position,t_size p_total) {}\r\nprivate:\r\n\tabort_callback & m_abort;\r\n};\r\n\r\n}\r\n\r\nbool input_helper::g_mark_dead(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,bit_array_var & p_mask,abort_callback & p_abort)\r\n{\r\n\tdead_item_filter_impl_simple filter(p_abort);\r\n\treturn filter.run(p_list,p_mask);\r\n}\r\n\r\nvoid input_info_read_helper::open(const char * p_path,abort_callback & p_abort) {\r\n\tif (m_input.is_empty() || metadb::path_compare(m_path,p_path) != 0)\r\n\t{\r\n\t\tTRACK_CODE(\"input_entry::g_open_for_info_read\",input_entry::g_open_for_info_read(m_input,0,p_path,p_abort));\r\n\r\n\t\tm_path = p_path;\r\n\t}\r\n}\r\n\r\nvoid input_info_read_helper::get_info(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,abort_callback & p_abort) {\r\n\topen(p_location.get_path(),p_abort);\r\n\r\n\tTRACK_CODE(\"input_info_reader::get_file_stats\",p_stats = m_input->get_file_stats(p_abort));\r\n\r\n\tTRACK_CODE(\"input_info_reader::get_info\",m_input->get_info(p_location.get_subsong_index(),p_info,p_abort));\r\n}\r\n\r\nvoid input_info_read_helper::get_info_check(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,bool & p_reloaded,abort_callback & p_abort) {\r\n\topen(p_location.get_path(),p_abort);\r\n\tt_filestats newstats;\r\n\tTRACK_CODE(\"input_info_reader::get_file_stats\",newstats = m_input->get_file_stats(p_abort));\r\n\tif (metadb_handle::g_should_reload(p_stats,newstats,true)) {\r\n\t\tp_stats = newstats;\r\n\t\tTRACK_CODE(\"input_info_reader::get_info\",m_input->get_info(p_location.get_subsong_index(),p_info,p_abort));\r\n\t\tp_reloaded = true;\r\n\t} else {\r\n\t\tp_reloaded = false;\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\nvoid input_helper_cue::open(service_ptr_t<file> p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,double p_start,double p_length) {\r\n\tp_abort.check();\r\n\r\n\tm_start = p_start;\r\n\tm_position = 0;\r\n\tm_dynamic_info_trigger = false;\r\n\tm_dynamic_info_track_trigger = false;\r\n\t\r\n\tm_input.open(p_filehint,p_location,p_flags,p_abort,true,true);\r\n\t\r\n\tif (!m_input.can_seek()) throw exception_io_object_not_seekable();\r\n\r\n\tif (m_start > 0) {\r\n\t\tm_input.seek(m_start,p_abort);\r\n\t}\r\n\r\n\tif (p_length > 0) {\r\n\t\tm_length = p_length;\r\n\t} else {\r\n\t\tfile_info_impl temp;\r\n\t\tm_input.get_info(0,temp,p_abort);\r\n\t\tdouble ref_length = temp.get_length();\r\n\t\tif (ref_length <= 0) throw exception_io_data();\r\n\t\tm_length = ref_length - m_start + p_length /* negative or zero */;\r\n\t\tif (m_length <= 0) throw exception_io_data();\r\n\t}\r\n}\r\n\r\nvoid input_helper_cue::close() {m_input.close();}\r\nbool input_helper_cue::is_open() {return m_input.is_open();}\r\n\r\nbool input_helper_cue::run(audio_chunk & p_chunk,abort_callback & p_abort) {\r\n\tp_abort.check();\r\n\r\n\r\n\tif (m_length > 0) {\r\n\t\tif (m_position >= m_length) return false;\r\n\r\n\t\tm_dynamic_info_trigger = true;\r\n\t\tm_dynamic_info_track_trigger = true;\r\n\r\n\t\tif (!m_input.run(p_chunk,p_abort)) return false;\r\n\r\n\t\tt_uint64 max = (t_uint64) audio_math::time_to_samples(m_length - m_position, p_chunk.get_sample_rate());\r\n\t\tif (max == 0)\r\n\t\t{//handle rounding accidents, this normally shouldn't trigger\r\n\t\t\tm_position = m_length;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tt_size samples = p_chunk.get_sample_count();\r\n\t\tif ((t_uint64)samples > max)\r\n\t\t{\r\n\t\t\tp_chunk.set_sample_count((unsigned)max);\r\n\t\t\tm_position = m_length;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_position += p_chunk.get_duration();\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif (!m_input.run(p_chunk,p_abort)) return false;\r\n\t\tm_position += p_chunk.get_duration();\r\n\t\treturn true;\r\n\t}\r\n}\r\n\r\nvoid input_helper_cue::seek(double p_seconds,abort_callback & p_abort)\r\n{\r\n\tm_dynamic_info_trigger = false;\r\n\tm_dynamic_info_track_trigger = false;\r\n\tif (m_length <= 0 || p_seconds < m_length) {\r\n\t\tm_input.seek(p_seconds + m_start,p_abort);\r\n\t\tm_position = p_seconds;\r\n\t} else {\r\n\t\tm_position = m_length;\r\n\t}\r\n}\r\n\r\nbool input_helper_cue::can_seek() {return true;}\r\nvoid input_helper_cue::set_full_buffer(t_filesize val) {m_input.set_full_buffer(val);}\r\n\r\nvoid input_helper_cue::on_idle(abort_callback & p_abort) {m_input.on_idle(p_abort);}\r\n\r\nbool input_helper_cue::get_dynamic_info(file_info & p_out,double & p_timestamp_delta) {\r\n\tif (m_dynamic_info_trigger) {\r\n\t\tm_dynamic_info_trigger = false;\r\n\t\treturn m_input.get_dynamic_info(p_out,p_timestamp_delta);\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nbool input_helper_cue::get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta) {\r\n\tif (m_dynamic_info_track_trigger) {\r\n\t\tm_dynamic_info_track_trigger = false;\r\n\t\treturn m_input.get_dynamic_info_track(p_out,p_timestamp_delta);\r\n\t} else {\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nconst char * input_helper_cue::get_path() const {return m_input.get_path();}\r\n\t\r\nvoid input_helper_cue::get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort) {m_input.get_info(p_subsong,p_info,p_abort);}\r\n\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/input_helpers.h",
    "content": "#ifndef _INPUT_HELPERS_H_\r\n#define _INPUT_HELPERS_H_\r\n\r\nclass input_helper {\r\npublic:\r\n\tinput_helper();\r\n\tvoid open(service_ptr_t<file> p_filehint,metadb_handle_ptr p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect = false,bool p_skip_hints = false);\r\n\tvoid open(service_ptr_t<file> p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,bool p_from_redirect = false,bool p_skip_hints = false);\r\n\r\n\tvoid close();\r\n\tbool is_open();\r\n\tbool run(audio_chunk & p_chunk,abort_callback & p_abort);\r\n\tvoid seek(double seconds,abort_callback & p_abort);\r\n\tbool can_seek();\r\n\tvoid set_full_buffer(t_filesize val);\r\n\tvoid on_idle(abort_callback & p_abort);\r\n\tbool get_dynamic_info(file_info & p_out,double & p_timestamp_delta);\r\n\tbool get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta);\r\n\r\n\t//! Retrieves path of currently open file.\r\n\tconst char * get_path() const;\r\n\r\n\t//! Retrieves info about specific subsong of currently open file.\r\n\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort);\r\n\r\n\tstatic void g_get_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect = false);\r\n\tstatic void g_set_info(const playable_location & p_location,file_info & p_info,abort_callback & p_abort,bool p_from_redirect = false);\r\n\r\n\r\n\tstatic bool g_mark_dead(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,bit_array_var & p_mask,abort_callback & p_abort);\r\n\r\nprivate:\r\n\tservice_ptr_t<input_decoder> m_input;\r\n\tpfc::string8 m_path;\r\n\tt_filesize m_fullbuffer;\r\n};\r\n\r\nclass NOVTABLE dead_item_filter : public abort_callback {\r\npublic:\r\n\tvirtual void on_progress(t_size p_position,t_size p_total) = 0;\r\n\r\n\tbool run(const pfc::list_base_const_t<metadb_handle_ptr> & p_list,bit_array_var & p_mask);\r\n};\r\n\r\nclass input_info_read_helper {\r\npublic:\r\n\tinput_info_read_helper() {}\r\n\tvoid get_info(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,abort_callback & p_abort);\r\n\tvoid get_info_check(const playable_location & p_location,file_info & p_info,t_filestats & p_stats,bool & p_reloaded,abort_callback & p_abort);\r\nprivate:\r\n\tvoid open(const char * p_path,abort_callback & p_abort);\r\n\r\n\tpfc::string8 m_path;\r\n\tservice_ptr_t<input_info_reader> m_input;\r\n};\r\n\r\n\r\n\r\nclass input_helper_cue {\r\npublic:\r\n\tvoid open(service_ptr_t<file> p_filehint,const playable_location & p_location,unsigned p_flags,abort_callback & p_abort,double p_start,double p_length);\r\n\r\n\tvoid close();\r\n\tbool is_open();\r\n\tbool run(audio_chunk & p_chunk,abort_callback & p_abort);\r\n\tvoid seek(double seconds,abort_callback & p_abort);\r\n\tbool can_seek();\r\n\tvoid set_full_buffer(t_filesize val);\r\n\tvoid on_idle(abort_callback & p_abort);\r\n\tbool get_dynamic_info(file_info & p_out,double & p_timestamp_delta);\r\n\tbool get_dynamic_info_track(file_info & p_out,double & p_timestamp_delta);\r\n\r\n\tconst char * get_path() const;\r\n\t\r\n\tvoid get_info(t_uint32 p_subsong,file_info & p_info,abort_callback & p_abort);\r\n\r\nprivate:\r\n\tinput_helper m_input;\r\n\tdouble m_start,m_length,m_position;\r\n\tbool m_dynamic_info_trigger,m_dynamic_info_track_trigger;\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/listview_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\n\r\n#define uTEXT(blah) TEXT(blah)\r\n#define uLVM_SETITEM LVM_SETITEM\r\n#define uLVM_INSERTITEM LVM_INSERTITEM\r\n#define uLVM_INSERTCOLUMN LVM_INSERTCOLUMN\r\n#define uLVM_GETITEM LVM_GETITEM\r\n\r\nnamespace listview_helper {\r\n\r\n\tunsigned insert_item(HWND p_listview,unsigned p_index,const char * p_name,LPARAM p_param)\r\n\t{\r\n\t\tif (p_index == infinite) p_index = ListView_GetItemCount(p_listview);\r\n\t\tLVITEM item;\r\n\t\tmemset(&item,0,sizeof(item));\r\n\r\n\t\tpfc::stringcvt::string_os_from_utf8 os_string_temp(p_name);\r\n\t\tos_string_temp.convert(p_name);\r\n\r\n\t\titem.mask = LVIF_TEXT | LVIF_PARAM;\r\n\t\titem.iItem = p_index;\r\n\t\titem.lParam = p_param;\r\n\t\titem.pszText = const_cast<TCHAR*>(os_string_temp.get_ptr());\r\n\t\t\r\n\t\tLRESULT ret = uSendMessage(p_listview,uLVM_INSERTITEM,0,(LPARAM)&item);\r\n\t\tif (ret < 0) return infinite;\r\n\t\telse return (unsigned) ret;\r\n\t}\r\n\r\n\r\n\r\n\tunsigned insert_column(HWND p_listview,unsigned p_index,const char * p_name,unsigned p_width_dlu)\r\n\t{\r\n\t\tpfc::stringcvt::string_os_from_utf8 os_string_temp;\r\n\t\tos_string_temp.convert(p_name);\r\n\r\n\t\tRECT rect = {0,0,p_width_dlu,0};\r\n\t\tMapDialogRect(GetParent(p_listview),&rect);\r\n\r\n\t\tLVCOLUMN data;\r\n\t\tmemset(&data,0,sizeof(data));\r\n\t\tdata.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_FMT;\r\n\t\tdata.fmt = LVCFMT_LEFT;\r\n\t\tdata.cx = rect.right;\r\n\t\tdata.pszText = const_cast<TCHAR*>(os_string_temp.get_ptr());\r\n\t\t\r\n\t\tLRESULT ret = uSendMessage(p_listview,uLVM_INSERTCOLUMN,p_index,(LPARAM)&data);\r\n\t\tif (ret < 0) return infinite;\r\n\t\telse return (unsigned) ret;\r\n\t}\r\n\r\n\tvoid get_item_text(HWND p_listview,unsigned p_index,unsigned p_column,pfc::string_base & p_out) {\r\n\t\tenum {buffer_length = 4096};\r\n\t\tTCHAR buffer[buffer_length];\r\n\t\tListView_GetItemText(p_listview,p_index,p_column,buffer,buffer_length);\r\n\t\tp_out = pfc::stringcvt::string_utf8_from_os(buffer,buffer_length);\r\n\t}\r\n\r\n\tbool set_item_text(HWND p_listview,unsigned p_index,unsigned p_column,const char * p_name)\r\n\t{\r\n\t\tLVITEM item;\r\n\t\tmemset(&item,0,sizeof(item));\r\n\r\n\t\tpfc::stringcvt::string_os_from_utf8 os_string_temp;\r\n\t\tos_string_temp.convert(p_name);\r\n\r\n\t\titem.mask = LVIF_TEXT;\r\n\t\titem.iItem = p_index;\r\n\t\titem.iSubItem = p_column;\r\n\t\titem.pszText = const_cast<TCHAR*>(os_string_temp.get_ptr());\r\n\t\treturn uSendMessage(p_listview,uLVM_SETITEM,0,(LPARAM)&item) ? true : false;\r\n\t}\r\n\r\n\tbool is_item_selected(HWND p_listview,unsigned p_index)\r\n\t{\r\n\t\tLVITEM item;\r\n\t\tmemset(&item,0,sizeof(item));\r\n\t\titem.mask = LVIF_STATE;\r\n\t\titem.iItem = p_index;\r\n\t\titem.stateMask = LVIS_SELECTED;\r\n\t\tif (!uSendMessage(p_listview,uLVM_GETITEM,0,(LPARAM)&item)) return false;\r\n\t\treturn (item.state & LVIS_SELECTED) ? true : false;\r\n\t}\r\n\r\n\tbool set_item_selection(HWND p_listview,unsigned p_index,bool p_state)\r\n\t{\r\n\t\tLVITEM item;\r\n\t\tmemset(&item,0,sizeof(item));\r\n\t\titem.mask = LVIF_STATE;\r\n\t\titem.iItem = p_index;\r\n\t\titem.stateMask = LVIS_SELECTED;\r\n\t\titem.state = p_state ? LVIS_SELECTED : 0;\r\n\t\treturn uSendMessage(p_listview,uLVM_SETITEM,0,(LPARAM)&item) ? true : false;\r\n\t}\r\n\r\n\tbool select_single_item(HWND p_listview,unsigned p_index)\r\n\t{\r\n\t\tLRESULT temp = SendMessage(p_listview,LVM_GETITEMCOUNT,0,0);\r\n\t\tif (temp < 0) return false;\r\n\t\tListView_SetSelectionMark(p_listview,p_index);\r\n\t\tunsigned n; const unsigned m = pfc::downcast_guarded<unsigned>(temp);\r\n\t\tfor(n=0;n<m;n++) {\r\n\t\t\tenum {mask = LVIS_FOCUSED | LVIS_SELECTED};\r\n\t\t\tListView_SetItemState(p_listview,n,n == p_index ? mask : 0, mask);\r\n\t\t}\r\n\t\treturn ensure_visible(p_listview,p_index);\r\n\t}\r\n\r\n\tbool ensure_visible(HWND p_listview,unsigned p_index)\r\n\t{\r\n\t\treturn uSendMessage(p_listview,LVM_ENSUREVISIBLE,p_index,FALSE) ? true : false;\r\n\t}\r\n}\r\n\r\n\r\n\r\nbool ListView_GetContextMenuPoint(HWND p_list,LPARAM p_coords,POINT & p_point,int & p_selection) {\r\n\tif ((DWORD)p_coords == (DWORD)infinite) {\r\n\t\tint firstsel = ListView_GetFirstSelection(p_list);\r\n\t\tif (firstsel >= 0) {\r\n\t\t\tRECT rect;\r\n\t\t\tif (!ListView_GetItemRect(p_list,firstsel,&rect,LVIR_BOUNDS)) return false;\r\n\t\t\tp_point.x = (rect.left + rect.right) / 2;\r\n\t\t\tp_point.y = (rect.top + rect.bottom) / 2;\r\n\t\t\tif (!ClientToScreen(p_list,&p_point)) return false;\r\n\t\t} else {\r\n\t\t\tRECT rect;\r\n\t\t\tif (!GetClientRect(p_list,&rect)) return false;\r\n\t\t\tp_point.x = (rect.left + rect.right) / 2;\r\n\t\t\tp_point.y = (rect.top + rect.bottom) / 2;\r\n\t\t\tif (!ClientToScreen(p_list,&p_point)) return false;\r\n\t\t}\r\n\t\tp_selection = firstsel;\r\n\t\treturn true;\r\n\t} else {\r\n\t\tPOINT pt = {(short)LOWORD(p_coords),(short)HIWORD(p_coords)};\r\n\t\tp_point = pt;\r\n\t\tPOINT client = pt;\r\n\t\tif (!ScreenToClient(p_list,&client)) return false;\r\n\t\tLVHITTESTINFO info;\r\n\t\tmemset(&info,0,sizeof(info));\r\n\t\tinfo.pt = client;\r\n\t\tp_selection = ListView_HitTest(p_list,&info);\r\n\t\treturn true;\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/listview_helper.h",
    "content": "namespace listview_helper\r\n{\r\n\tunsigned insert_item(HWND p_listview,unsigned p_index,const char * p_name,LPARAM p_param);//returns index of new item on success, infinite on failure\r\n\r\n\tunsigned insert_column(HWND p_listview,unsigned p_index,const char * p_name,unsigned p_width_dlu);//returns index of new item on success, infinite on failure\r\n\r\n\tbool set_item_text(HWND p_listview,unsigned p_index,unsigned p_column,const char * p_name);\r\n\r\n\tbool is_item_selected(HWND p_listview,unsigned p_index);\r\n\r\n\tbool set_item_selection(HWND p_listview,unsigned p_index,bool p_state);\r\n\r\n\tbool select_single_item(HWND p_listview,unsigned p_index);\r\n\r\n\tbool ensure_visible(HWND p_listview,unsigned p_index);\r\n\r\n\tvoid get_item_text(HWND p_listview,unsigned p_index,unsigned p_column,pfc::string_base & p_out);\r\n\r\n};\r\n\r\nstatic int ListView_GetFirstSelection(HWND p_listview) {\r\n\treturn ListView_GetNextItem(p_listview,-1,LVNI_SELECTED);\r\n}\r\n\r\nstatic int ListView_GetSingleSelection(HWND p_listview) {\r\n\tif (ListView_GetSelectedCount(p_listview) != 1) return -1;\r\n\treturn ListView_GetFirstSelection(p_listview);\r\n}\r\n\r\nstatic int ListView_GetFocusItem(HWND p_listview) {\r\n\treturn ListView_GetNextItem(p_listview,-1,LVNI_FOCUSED);\r\n}\r\n\r\nstatic bool ListView_IsItemSelected(HWND p_listview,int p_index) {\r\n\treturn ListView_GetItemState(p_listview,p_index,LVIS_SELECTED) != 0;\r\n}\r\n\r\nbool ListView_GetContextMenuPoint(HWND p_list,LPARAM p_coords,POINT & p_point,int & p_selection);"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/meta_table_builder.h",
    "content": "class __meta_table_enum_wrapper {\r\npublic:\r\n\t__meta_table_enum_wrapper(file_info & p_info) : m_info(p_info) {}\r\n\tvoid operator() (const char * p_name,const pfc::chain_list_t<pfc::string8> & p_values) {\r\n\t\tt_size index = infinite;\r\n\t\tfor(pfc::chain_list_t<pfc::string8>::const_iterator iter = p_values.first(); iter.is_valid(); ++iter) {\r\n\t\t\tif (index == infinite) index = m_info.__meta_add_unsafe(p_name,*iter);\r\n\t\t\telse m_info.meta_add_value(index,*iter);\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tfile_info & m_info;\r\n};\r\n\r\n//! Purpose: building a file_info metadata table from loose input without search-for-existing-entry bottleneck\r\nclass meta_table_builder {\r\npublic:\r\n\tvoid add(const char * p_name,const char * p_value,t_size p_value_len = infinite) {\r\n\t\tif (file_info::g_is_valid_field_name(p_name)) {\r\n\t\t\t__add(p_name).insert_last()->set_string(p_value,p_value_len);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid remove(const char * p_name) {\r\n\t\tm_data.remove(p_name);\r\n\t}\r\n\tvoid set(const char * p_name,const char * p_value,t_size p_value_len = infinite) {\r\n\t\tif (file_info::g_is_valid_field_name(p_name)) {\r\n\t\t\tt_entry & entry = __add(p_name);\r\n\t\t\tentry.remove_all();\r\n\t\t\tentry.insert_last()->set_string(p_value,p_value_len);\r\n\t\t}\r\n\t}\r\n\tpfc::chain_list_t<pfc::string8> & add(const char * p_name) {\r\n\t\tif (!file_info::g_is_valid_field_name(p_name)) throw pfc::exception_bug_check();//we return a reference, nothing smarter to do\r\n\t\treturn __add(p_name);\r\n\t}\r\n\tvoid finalize(file_info & p_info) {\r\n\t\tp_info.meta_remove_all();\r\n\t\tm_data.enumerate(__meta_table_enum_wrapper(p_info));\r\n\t}\r\n\r\n\tvoid from_info(const file_info & p_info) {\r\n\t\tm_data.remove_all();\r\n\t\tfrom_info_overwrite(p_info);\r\n\t}\r\n\tvoid from_info_overwrite(const file_info & p_info) {\r\n\t\tfor(t_size metawalk = 0, metacount = p_info.meta_get_count(); metawalk < metacount; ++metawalk ) {\r\n\t\t\tconst t_size valuecount = p_info.meta_enum_value_count(metawalk);\r\n\t\t\tif (valuecount > 0) {\r\n\t\t\t\tt_entry & entry = add(p_info.meta_enum_name(metawalk));\r\n\t\t\t\tentry.remove_all();\r\n\t\t\t\tfor(t_size valuewalk = 0; valuewalk < valuecount; ++valuewalk) {\r\n\t\t\t\t\tentry.insert_last(p_info.meta_enum_value(metawalk,valuewalk));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\nprivate:\r\n\ttypedef pfc::chain_list_t<pfc::string8> t_entry;\r\n\r\n\tt_entry & __add(const char * p_name) {\r\n\t\treturn m_data.find_or_add(p_name);\r\n\t}\r\n\r\n\tpfc::map_t<pfc::string8,t_entry,file_info::field_name_comparator> m_data;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/metadb_io_hintlist.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nvoid metadb_io_hintlist::run() {\r\n\tif (m_entries.get_count() > 0) {\r\n\t\tstatic_api_ptr_t<metadb_io>()->hint_multi_async(\r\n\t\t\tmetadb_io_hintlist_wrapper_part1(m_entries),\r\n\t\t\tmetadb_io_hintlist_wrapper_part2(m_entries),\r\n\t\t\tmetadb_io_hintlist_wrapper_part3(m_entries),\r\n\t\t\tmetadb_io_hintlist_wrapper_part4(m_entries)\r\n\t\t\t);\r\n\t}\r\n\tm_entries.remove_all();\r\n}\r\n\r\nvoid metadb_io_hintlist::add(metadb_handle_ptr const & p_handle,const file_info & p_info,t_filestats const & p_stats,bool p_fresh) {\r\n\tt_entry entry;\r\n\tentry.m_handle = p_handle;\r\n\tentry.m_info.new_t(p_info);\r\n\tentry.m_stats = p_stats;\r\n\tentry.m_fresh = p_fresh;\r\n\tm_entries.add_item(entry);\r\n}\r\n\r\nvoid metadb_io_hintlist::hint_reader(service_ptr_t<input_info_reader> p_reader, const char * p_path,abort_callback & p_abort) {\r\n\tstatic_api_ptr_t<metadb> api;\r\n\tconst t_uint32 subsongcount = p_reader->get_subsong_count();\r\n\tt_filestats stats = p_reader->get_file_stats(p_abort);\r\n\tfor(t_uint32 subsong = 0; subsong < subsongcount; subsong++) {\r\n\t\tt_uint32 subsong_id = p_reader->get_subsong(subsong);\r\n\t\tmetadb_handle_ptr handle;\r\n\t\tapi->handle_create(handle,make_playable_location(p_path,subsong_id));\r\n\t\tif (handle->should_reload(stats,true)) {\r\n\t\t\tfile_info_impl temp;\r\n\t\t\tp_reader->get_info(subsong_id,temp,p_abort);\r\n\r\n\t\t\tadd(handle,temp,stats,true);\r\n\t\t}\r\n\t}\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/metadb_io_hintlist.h",
    "content": "\r\nclass metadb_io_hintlist {\r\npublic:\r\n\tvoid hint_reader(service_ptr_t<input_info_reader> p_reader, const char * p_path,abort_callback & p_abort);\r\n\tvoid add(metadb_handle_ptr const & p_handle,const file_info & p_info,t_filestats const & p_stats,bool p_fresh);\r\n\tvoid run();\r\nprivate:\r\n\tstruct t_entry {\r\n\t\tmetadb_handle_ptr m_handle;\r\n\t\tpfc::rcptr_t<file_info_const_impl> m_info;\r\n\t\tt_filestats m_stats;\r\n\t\tbool m_fresh;\r\n\t};\r\n\tclass metadb_io_hintlist_wrapper_part1 : public pfc::list_base_const_t<metadb_handle_ptr> {\r\n\tpublic:\r\n\t\tmetadb_io_hintlist_wrapper_part1(const pfc::list_base_const_t<metadb_io_hintlist::t_entry> & p_list) : m_list(p_list) {}\r\n\t\tt_size get_count() const {return m_list.get_count();}\r\n\t\tvoid get_item_ex(metadb_handle_ptr & p_out, t_size n) const {p_out = m_list[n].m_handle;}\r\n\r\n\tprivate:\r\n\t\tconst pfc::list_base_const_t<metadb_io_hintlist::t_entry> & m_list;\r\n\t};\r\n\tclass metadb_io_hintlist_wrapper_part2 : public pfc::list_base_const_t<const file_info*> {\r\n\tpublic:\r\n\t\tmetadb_io_hintlist_wrapper_part2(const pfc::list_base_const_t<metadb_io_hintlist::t_entry> & p_list) : m_list(p_list) {}\r\n\t\tt_size get_count() const {return m_list.get_count();}\r\n\t\tvoid get_item_ex(const file_info* & p_out, t_size n) const {p_out = &*m_list[n].m_info;}\r\n\tprivate:\r\n\t\tconst pfc::list_base_const_t<metadb_io_hintlist::t_entry> & m_list;\r\n\t};\r\n\tclass metadb_io_hintlist_wrapper_part3 : public pfc::list_base_const_t<t_filestats> {\r\n\tpublic:\r\n\t\tmetadb_io_hintlist_wrapper_part3(const pfc::list_base_const_t<metadb_io_hintlist::t_entry> & p_list) : m_list(p_list) {}\r\n\t\tt_size get_count() const {return m_list.get_count();}\r\n\t\tvoid get_item_ex(t_filestats & p_out, t_size n) const {p_out = m_list[n].m_stats;}\r\n\tprivate:\r\n\t\tconst pfc::list_base_const_t<metadb_io_hintlist::t_entry> & m_list;\r\n\t};\r\n\tclass metadb_io_hintlist_wrapper_part4 : public bit_array {\r\n\tpublic:\r\n\t\tmetadb_io_hintlist_wrapper_part4(const pfc::list_base_const_t<metadb_io_hintlist::t_entry> & p_list) : m_list(p_list) {}\r\n\t\tbool get(t_size n) const {return m_list[n].m_fresh;}\r\n\tprivate:\r\n\t\tconst pfc::list_base_const_t<metadb_io_hintlist::t_entry> & m_list;\r\n\t};\r\n\r\n\tpfc::list_t<t_entry,pfc::alloc_fast> m_entries;\r\n};\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/mp3_utils.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nusing namespace bitreader_helper;\r\n\r\nstatic unsigned extract_header_bits(const t_uint8 p_header[4],unsigned p_base,unsigned p_bits)\r\n{\r\n\tassert(p_base+p_bits<=32);\r\n\treturn extract_bits(p_header,p_base,p_bits);\r\n}\r\n\r\nnamespace {\r\n\r\n\tclass header_parser\r\n\t{\r\n\tpublic:\r\n\t\theader_parser(const t_uint8 p_header[4]) : m_bitptr(0) \r\n\t\t{\r\n\t\t\tmemcpy(m_header,p_header,4);\r\n\t\t}\r\n\t\tunsigned read(unsigned p_bits)\r\n\t\t{\r\n\t\t\tunsigned ret = extract_header_bits(m_header,m_bitptr,p_bits);\r\n\t\t\tm_bitptr += p_bits;\r\n\t\t\treturn ret;\r\n\t\t}\r\n\tprivate:\r\n\t\tt_uint8 m_header[4];\r\n\t\tunsigned m_bitptr;\r\n\t};\r\n}\r\n\r\ntypedef t_uint16 uint16;\r\n\r\nstatic const uint16 bitrate_table_l1v1[16]  = {  0, 32, 64, 96,128,160,192,224,256,288,320,352,384,416,448,  0};\r\nstatic const uint16 bitrate_table_l2v1[16]  = {  0, 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384,  0};\r\nstatic const uint16 bitrate_table_l3v1[16]  = {  0, 32, 40, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,  0};\r\nstatic const uint16 bitrate_table_l1v2[16]  = {  0, 32, 48, 56, 64, 80, 96,112,128,144,160,176,192,224,256,  0};\r\nstatic const uint16 bitrate_table_l23v2[16] = {  0,  8, 16, 24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160,  0};\r\nstatic const uint16 sample_rate_table[] = {11025,12000,8000};\r\n\r\nunsigned mp3_utils::QueryMPEGFrameSize(const t_uint8 p_header[4])\r\n{\r\n\tTMPEGFrameInfo info;\r\n\tif (!ParseMPEGFrameHeader(info,p_header)) return 0;\r\n\treturn info.m_bytes;\r\n}\r\n\r\nbool mp3_utils::ParseMPEGFrameHeader(TMPEGFrameInfo & p_info,const t_uint8 p_header[4])\r\n{\r\n\tenum {MPEG_LAYER_1 = 3, MPEG_LAYER_2 = 2, MPEG_LAYER_3 = 1};\r\n\tenum {_MPEG_1 = 3, _MPEG_2 = 2, _MPEG_25 = 0};\r\n\r\n\theader_parser parser(p_header);\r\n\tif (parser.read(11) != 0x7FF) return false;\r\n\tunsigned mpeg_version = parser.read(2);\r\n\tunsigned layer = parser.read(2);\r\n\tunsigned protection = parser.read(1);\r\n\tunsigned bitrate_index = parser.read(4);\r\n\tunsigned sample_rate_index = parser.read(2);\r\n\tif (sample_rate_index == 11) return false;//reserved\r\n\tunsigned paddingbit = parser.read(1);\r\n\tint paddingdelta = 0;\r\n\tparser.read(1);//private\r\n\tunsigned channel_mode = parser.read(2);\r\n\tparser.read(2);//channel_mode_extension\r\n\tparser.read(1);//copyright\r\n\tparser.read(1);//original\r\n\tparser.read(2);//emphasis\r\n\r\n\tunsigned bitrate = 0,sample_rate = 0;\r\n\r\n\tswitch(layer)\r\n\t{\r\n\tdefault:\r\n\t\treturn false;\r\n\tcase MPEG_LAYER_3:\r\n\t\tpaddingdelta = paddingbit ? 1 : 0;\r\n\t\t\r\n\t\tp_info.m_layer = 3;\r\n\t\tswitch(mpeg_version)\r\n\t\t{\r\n\t\tcase _MPEG_1:\r\n\t\t\tp_info.m_duration = 1152;\r\n\t\t\tbitrate = bitrate_table_l3v1[bitrate_index];\r\n\t\t\tbreak;\r\n\t\tcase _MPEG_2:\r\n\t\tcase _MPEG_25:\r\n\t\t\tp_info.m_duration = 576;\r\n\t\t\tbitrate = bitrate_table_l23v2[bitrate_index];\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\r\n\t\tbreak;\r\n\tcase MPEG_LAYER_2:\r\n\t\tpaddingdelta = paddingbit ? 1 : 0;\r\n\t\tp_info.m_duration = 1152;\r\n\t\tp_info.m_layer = 2;\r\n\t\tswitch(mpeg_version)\r\n\t\t{\r\n\t\tcase _MPEG_1:\r\n\t\t\tbitrate = bitrate_table_l2v1[bitrate_index];\r\n\t\t\tbreak;\r\n\t\tcase _MPEG_2:\r\n\t\tcase _MPEG_25:\r\n\t\t\tbitrate = bitrate_table_l23v2[bitrate_index];\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\tcase MPEG_LAYER_1:\r\n\t\tpaddingdelta = paddingbit ? 4 : 0;\r\n\t\tp_info.m_duration = 384;\r\n\t\tp_info.m_layer = 1;\r\n\t\tswitch(mpeg_version)\r\n\t\t{\r\n\t\tcase _MPEG_1:\r\n\t\t\tbitrate = bitrate_table_l1v1[bitrate_index];\r\n\t\t\tbreak;\r\n\t\tcase _MPEG_2:\r\n\t\tcase _MPEG_25:\r\n\t\t\tbitrate = bitrate_table_l1v2[bitrate_index];\r\n\t\t\tbreak;\t\t\r\n\t\tdefault:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tbreak;\r\n\t}\r\n\tif (bitrate == 0) return false;\r\n\r\n\tsample_rate = sample_rate_table[sample_rate_index];\r\n\tif (sample_rate == 0) return false;\r\n\tswitch(mpeg_version)\r\n\t{\r\n\tcase _MPEG_1:\r\n\t\tsample_rate *= 4;\r\n\t\tp_info.m_mpegversion = MPEG_1;\r\n\t\tbreak;\r\n\tcase _MPEG_2:\r\n\t\tsample_rate *= 2;\r\n\t\tp_info.m_mpegversion = MPEG_2;\r\n\t\tbreak;\r\n\tcase _MPEG_25:\r\n\t\tp_info.m_mpegversion = MPEG_25;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tswitch(channel_mode)\r\n\t{\r\n\tcase 0:\r\n\tcase 1:\r\n\tcase 2:\r\n\t\tp_info.m_channels = 2;\r\n\t\tbreak;\r\n\tcase 3:\r\n\t\tp_info.m_channels = 1;\r\n\t\tbreak;\r\n\t}\r\n\r\n\tp_info.m_channel_mode = channel_mode;\r\n\r\n\tp_info.m_sample_rate = sample_rate;\r\n\r\n\r\n\tp_info.m_bytes = ( bitrate /*kbps*/ * (1000/8) /* kbps-to-bytes*/ * p_info.m_duration /*samples-per-frame*/ ) / sample_rate + paddingdelta;\r\n\r\n\tif (p_info.m_layer == 1) p_info.m_bytes &= ~3;\r\n\r\n\tp_info.m_crc = protection == 0;\r\n\r\n\treturn true;\r\n}\r\n\r\nunsigned mp3header::get_samples_per_frame()\r\n{\r\n\tmp3_utils::TMPEGFrameInfo fr;\r\n\tif (!decode(fr)) return 0;\r\n\treturn fr.m_duration;\r\n}\r\n\r\n\r\nbool mp3_utils::IsSameStream(TMPEGFrameInfo const & p_frame1,TMPEGFrameInfo const & p_frame2) {\r\n\treturn \r\n\t\tp_frame1.m_channel_mode == p_frame2.m_channel_mode && \r\n\t\tp_frame1.m_sample_rate == p_frame2.m_sample_rate &&\r\n\t\tp_frame1.m_layer == p_frame2.m_layer &&\r\n\t\tp_frame1.m_mpegversion == p_frame2.m_mpegversion;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/mp3_utils.h",
    "content": "namespace mp3_utils\r\n{\r\n\r\n\tenum {\r\n\t\tMPG_MD_STEREO=0,\r\n\t\tMPG_MD_JOINT_STEREO=1,\r\n\t\tMPG_MD_DUAL_CHANNEL=2,\r\n\t\tMPG_MD_MONO=3,\r\n\t};\r\n\r\n\ttypedef t_uint8 byte;\r\n\r\n\tenum {MPEG_1, MPEG_2, MPEG_25};\r\n\r\n\tstruct TMPEGFrameInfo\r\n\t{\r\n\t\tunsigned m_bytes;\r\n\t\tunsigned m_sample_rate;\r\n\t\tunsigned m_layer;\r\n\t\tunsigned m_mpegversion;\r\n\t\tunsigned m_channels;\r\n\t\tunsigned m_duration;\r\n\t\tunsigned m_channel_mode;\r\n\t\tbool m_crc;\r\n\t};\r\n\r\n\r\n\tbool ParseMPEGFrameHeader(TMPEGFrameInfo & p_info,const t_uint8 p_header[4]);\r\n\tunsigned QueryMPEGFrameSize(const t_uint8 p_header[4]);\r\n\tbool IsSameStream(TMPEGFrameInfo const & p_frame1,TMPEGFrameInfo const & p_frame2);\r\n};\r\n\r\nclass mp3header\r\n{\r\n\tt_uint8 bytes[4];\r\npublic:\r\n\r\n\tinline void copy(const mp3header & src) {memcpy(bytes,src.bytes,4);}\r\n\tinline void copy_raw(const void * src) {memcpy(bytes,src,4);}\r\n\r\n\tinline mp3header(const mp3header & src) {copy(src);}\r\n\tinline mp3header() {}\r\n\r\n\tinline const mp3header & operator=(const mp3header & src) {copy(src); return *this;}\r\n\r\n\tinline void get_bytes(void * out) {memcpy(out,bytes,4);}\r\n\tinline unsigned get_frame_size() const {return mp3_utils::QueryMPEGFrameSize(bytes);}\r\n\tinline bool decode(mp3_utils::TMPEGFrameInfo & p_out) {return mp3_utils::ParseMPEGFrameHeader(p_out,bytes);}\r\n\r\n\tunsigned get_samples_per_frame();\r\n};\r\n\r\nstatic inline mp3header mp3header_from_buffer(const void * p_buffer)\r\n{\r\n\tmp3header temp;\r\n\ttemp.copy_raw(p_buffer);\r\n\treturn temp;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/preload_info_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nbool preload_info_helper::preload_info(metadb_handle_ptr p_item,HWND p_parent_window,bool p_showerror) {\r\n\tif (p_item->is_info_loaded()) return true;\r\n\treturn static_api_ptr_t<metadb_io>()->load_info(p_item,metadb_io::load_info_default,p_parent_window,p_showerror) == metadb_io::load_info_success;\r\n}\r\n\r\nbool preload_info_helper::are_all_loaded(const pfc::list_base_const_t<metadb_handle_ptr> & p_items)\r\n{\r\n\tt_size n, m = p_items.get_count();\r\n\tfor(n=0;n<m;n++)\r\n\t{\r\n\t\tif (!p_items[n]->is_info_loaded()) return false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool preload_info_helper::preload_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_items,HWND p_parent_window,bool p_showerror)\r\n{\r\n\tif (are_all_loaded(p_items)) return true;\r\n\treturn static_api_ptr_t<metadb_io>()->load_info_multi(p_items,metadb_io::load_info_default,p_parent_window,p_showerror) == metadb_io::load_info_success;\r\n}\r\n\r\nbool preload_info_helper::preload_info_multi_modalcheck(const pfc::list_base_const_t<metadb_handle_ptr> & p_items,HWND p_parent_window,bool p_showerror)\r\n{\r\n\tif (are_all_loaded(p_items)) return true;\r\n\tif (!modal_dialog_scope::can_create()) return false;\r\n\treturn static_api_ptr_t<metadb_io>()->load_info_multi(p_items,metadb_io::load_info_default,p_parent_window,p_showerror) == metadb_io::load_info_success;\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/preload_info_helper.h",
    "content": "namespace preload_info_helper {\r\n\tbool __declspec(deprecated(\"Use metadb_io_v2 methods instead.\")) preload_info(metadb_handle_ptr p_item,HWND p_parent_window,bool p_showerror);\r\n\tbool __declspec(deprecated(\"Use metadb_io_v2 methods instead.\")) preload_info_multi(const pfc::list_base_const_t<metadb_handle_ptr> & p_items,HWND p_parent_window,bool p_showerror);\r\n\tbool __declspec(deprecated(\"Use metadb_io_v2 methods instead.\")) preload_info_multi_modalcheck(const pfc::list_base_const_t<metadb_handle_ptr> & p_items,HWND p_parent_window,bool p_showerror);\r\n\tbool are_all_loaded(const pfc::list_base_const_t<metadb_handle_ptr> & p_items);\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/search_filter.cpp",
    "content": "#include \"stdafx.h\"\n\nstatic bool is_spacing(char c) {return c == ' ' || c==10 || c==13;}\nstatic bool is_alpha(char c) {return (c>='a' && c<='z') || (c>='A' && c<='Z');}\nstatic bool is_alphanumeric(char c) {return is_alpha(c) || (c>='0' && c<='9');}\nstatic bool is_spacing_or_null(char c) {return c == 0 || is_spacing(c);}\n\nstatic bool is_format_spec(const char * ptr) {return strchr(ptr,'%') || strchr(ptr,'#') || strchr(ptr,'$');}\n\nnamespace search_tools {\n\n\tclass substring_filter {\n\t\tpfc::ptr_list_t<char> data;\n\t\tmutable pfc::string8_fastalloc temp;\n\tpublic:\n\t\tsubstring_filter(const char * src) {\n\t\t\twhile(*src) {\n\t\t\t\twhile(*src && is_spacing(*src)) src++;\n\t\t\t\tt_size ptr = 0;\n\t\t\t\twhile(src[ptr] && !is_spacing(src[ptr])) ptr++;\n\t\t\t\tif (ptr) {\n\t\t\t\t\tuStringLower(temp,src,ptr);\n\t\t\t\t\tdata.add_item(strdup(temp));\n\t\t\t\t}\n\t\t\t\tsrc+=ptr;\n\t\t\t}\n\t\t}\n\t\tbool test(const char * src) const \t\t{\n\t\t\tt_size n,m = data.get_count();\n\t\t\tif (m==0) return false;\n\t\t\tuStringLower(temp,src);\n\t\t\tfor(n=0;n<m;n++) {\n\t\t\t\tif (!strstr(temp,data[n])) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\t~substring_filter() {data.free_all();}\n\t};\n\n\n\tclass filter_node_and : public filter_node \t{\n\t\tfilter_node_cptr n1, n2;\n\tpublic:\n\t\tfilter_node_and(filter_node_cptr p1,filter_node_cptr p2) : n1(p1), n2(p2) {}\n\t\tvirtual bool test(const file_info * item,const metadb_handle_ptr & handle) const {return n1->test(item,handle) && n2->test(item,handle);}\n\t};\n\n\tclass filter_node_or : public filter_node {\n\t\tfilter_node_cptr n1, n2;\n\tpublic:\n\t\tfilter_node_or(filter_node_cptr p1,filter_node_cptr p2) : n1(p1), n2(p2) {}\n\t\tvirtual bool test(const file_info * item,const metadb_handle_ptr & handle) const {return n1->test(item,handle) || n2->test(item,handle);}\n\t};\n\n\tclass filter_node_not : public filter_node {\n\t\tfilter_node_cptr n;\n\tpublic:\n\t\tfilter_node_not(filter_node_cptr p) : n(p) {}\n\t\tvirtual bool test(const file_info * item,const metadb_handle_ptr & handle) const {return !n->test(item,handle);}\n\t};\n\n\tclass filter_node_missing : public filter_node {\n\t\tpfc::string8 m_field;\n\tpublic:\n\t\tfilter_node_missing(const char * p_string,t_size p_len) {\n\t\t\twhile(p_len > 0 && p_string[0] == ' ') {p_string++;p_len--;}\n\t\t\twhile(p_len > 0 && p_string[p_len - 1] == ' ') p_len--;\n\t\t\tm_field.set_string(p_string,p_len);\n\t\t}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\n\t\t\treturn item->meta_find(m_field) == infinite;\n\t\t}\n\t};\n\n\tclass filter_node_is_format : public filter_node {\n\t\tpfc::string_simple param;\n\t\tservice_ptr_t<titleformat_object> m_script;\n\t\tmutable pfc::string8_fastalloc temp;\n\t\tbool is_wildcard;\n\t\tbool test_internal(const char * src) const {\n\t\t\tif (is_wildcard) return wildcard_helper::test(src,param,false);\n\t\t\telse return !stricmp_utf8(src,param);\n\t\t}\n\tpublic:\n\t\tfilter_node_is_format(const char * p_field,const char * p_param)\n\t\t\t: param(p_param), is_wildcard(wildcard_helper::has_wildcards(p_param))\n\t\t{\n\t\t\tif (!static_api_ptr_t<titleformat_compiler>()->compile(m_script,p_field))\n\t\t\t\tthrow exception_parse_error();\n\t\t}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\n\t\t\thandle->format_title(0,temp,m_script,0);\n\t\t\treturn test_internal(temp);\n\t\t}\n\t};\n\n\tclass filter_node_is : public filter_node {\n\t\tpfc::string_simple field,param;\n\t\tmutable pfc::string8_fastalloc temp;\n\t\tbool is_wildcard;\n\t\tbool test_internal(const char * src) const {\n\t\t\tif (is_wildcard) return wildcard_helper::test(src,param,false);\n\t\t\telse return !stricmp_utf8(src,param);\n\t\t}\n\tpublic:\n\t\tfilter_node_is(const char * p_field,const char * p_param)\n\t\t\t: field(p_field), param(p_param), is_wildcard(wildcard_helper::has_wildcards(p_param))\n\t\t{\n\t\t}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\n\t\t\tt_size index = item->meta_find(field);\n\t\t\tif (index == infinite) return false;\n\t\t\tt_size n,m = item->meta_enum_value_count(index);\n\t\t\tfor(n=0;n<m;n++)\n\t\t\t{\n\t\t\t\tif (test_internal(item->meta_enum_value(index,n))) return true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tclass filter_node_has : public filter_node {\n\t\tpfc::string_simple field;\n\t\tmutable pfc::string8_fastalloc temp;\n\t\tsubstring_filter m_filter;\n\tpublic:\n\t\tfilter_node_has(const char * p_field,const char * p_param)\n\t\t\t: field(p_field), m_filter(p_param)\n\t\t{\n\t\t}\n\n\t\t~filter_node_has() {}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\n\t\t\tt_size index = item->meta_find(field);\n\t\t\tif (index == infinite) return false;\n\t\t\tt_size n, m = item->meta_enum_value_count(index);\n\t\t\ttemp.reset();\n\t\t\tfor(n=0;n<m;n++)\n\t\t\t{\n\t\t\t\ttemp += \" \";\n\t\t\t\ttemp += item->meta_enum_value(index,n);\n\t\t\t}\n\t\t\treturn m_filter.test(temp);\n\t\t}\n\t};\n\n\tclass filter_node_has_ex : public filter_node {\n\t\tpfc::string_simple field;\n\t\tsubstring_filter m_filter;\t\t\t\n\t\tmutable pfc::string8_fastalloc temp;\n\tpublic:\n\t\tfilter_node_has_ex(const char * p_field,const char * p_param)\n\t\t\t: field(p_field), m_filter(p_param)\n\t\t{\n\t\t}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\n\t\t\thandle->format_title_legacy(0,temp,field,0);\n\t\t\treturn m_filter.test(temp);\n\t\t}\n\t};\n\n\tclass filter_node_simple : public filter_node {\n\t\tsubstring_filter m_filter;\n\t\tmutable pfc::string8_fastalloc temp;\n\tpublic:\n\t\tfilter_node_simple(const char * src) : m_filter(src) {}\n\t\tbool test(const file_info * info,const metadb_handle_ptr & handle) const {\n\t\t\tt_size n, m = info->meta_get_count();\n\t\t\ttemp = handle->get_path();\n\t\t\tfor(n=0;n<m;n++) {\n\t\t\t\tt_size n1, m1 = info->meta_enum_value_count(n);\n\t\t\t\tfor(n1=0;n1<m1;n1++)\n\t\t\t\t{\n\t\t\t\t\ttemp += \" \";\n\t\t\t\t\ttemp += info->meta_enum_value(n,n1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tm = info->info_get_count();\n\t\t\tfor(n=0;n<m;n++) {\n\t\t\t\ttemp += \" \";\n\t\t\t\ttemp += info->info_enum_value(n);\n\t\t\t}\n\n\t\t\treturn m_filter.test(temp);\n\t\t}\n\t};\n\n\tclass parser {\n\t\tconst char * base;\n\t\tt_size len,ptr;\n\tpublic:\n\t\tinline parser() : base(0), len(0), ptr(0) {}\n\t\tinline parser(const char * p_ptr,t_size p_len) : base(p_ptr), len(p_len), ptr(0) {}\n\t\tinline parser(const parser & param) : base(param.get_ptr()), len(param.get_remaining()), ptr(0) {}\n\t\tinline parser(const parser & param,t_size len) : base(param.get_ptr()), len(len), ptr(0) {assert(len<=param.get_remaining());}\n\t\tinline const char * get_ptr() const {return base+ptr;}\n\t\tinline t_size get_remaining() const {return len-ptr;}\n\t\tinline t_size advance(t_size n) {ptr+=n; assert(ptr<=len);return n;}\n\t\tinline char get_char() const {return get_ptr()[0];}\n\t\tinline t_size get_offset() const {return ptr;}\n\t\tinline void reset(t_size offset=0) {ptr=offset;}\n\t\t\n\t\tt_size test_spacing() const {\n\t\t\tt_size n = 0, m = get_remaining();\n\t\t\tconst char * src = get_ptr();\n\t\t\twhile(n<m && is_spacing(src[n])) n++;\n\t\t\treturn n;\n\t\t}\n\n\t\tt_size skip_spacing() {\n\t\t\treturn advance(test_spacing());\n\t\t}\n\n\t\tbool is_empty() const {return test_spacing() == get_remaining();}\n\n\t\tt_size test_token() const {\n\t\t\tparser p(*this);\n\t\t\tif (p.get_remaining()==0) return 0;\n\t\t\tif (p.get_char() == '\\\"')\n\t\t\t{\n\t\t\t\tp.advance(1);\n\t\t\t\tfor(;;)\n\t\t\t\t{\n\t\t\t\t\tif (p.get_remaining()==0) return 0;\n\t\t\t\t\tif (p.get_char()=='\\\"')\n\t\t\t\t\t{\n\t\t\t\t\t\tp.advance(1);\n\t\t\t\t\t\treturn p.get_offset();\n\t\t\t\t\t}\n\t\t\t\t\telse p.advance(1);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (p.get_char()=='(')\n\t\t\t{\n\t\t\t\tp.advance(1);\n\t\t\t\tp.skip_spacing();\n\t\t\t\tdo {\n\t\t\t\t\tif (p.skip_token()==0) return 0;\n\t\t\t\t\tp.skip_spacing();\n\t\t\t\t\tif (p.get_remaining()==0) return 0;\n\t\t\t\t} while(p.get_char()!=')');\n\t\t\t\tp.advance(1);\n\t\t\t\treturn p.get_offset();\n\t\t\t}\n\t\t\telse if (p.get_char()==')') return 0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tdo { p.advance(1); } while(p.get_remaining()>0 && p.get_char()!=')' && !is_spacing(p.get_char()));\n\t\t\t\treturn p.get_offset();\n\t\t\t}\n\t\t\treturn 0;\n\t\t}\n\n\t\tt_size skip_token() {\n\t\t\treturn advance(test_token());\n\t\t}\n\t};\n\n\ttypedef filter_node_cptr (*operator_handler)(const parser & token_left,const parser & token_right);\n\n\tstatic filter_node_cptr operator_handler_and(const parser & token_left,const parser & token_right) {\n\t\treturn pfc::rcnew_t<filter_node_and>(filter_node::g_create(token_left),filter_node::g_create(token_right));\n\t}\n\n\tstatic filter_node_cptr operator_handler_or(const parser & token_left,const parser & token_right) {\n\t\treturn pfc::rcnew_t<filter_node_or>(filter_node::g_create(token_left),filter_node::g_create(token_right));\n\t}\n\n\tstatic filter_node_cptr operator_handler_not(const parser & token_left,const parser & token_right) {\n\t\tif (!token_left.is_empty()) throw exception_parse_error();\n\t\treturn pfc::rcnew_t<filter_node_not>(filter_node::g_create(token_right));\n\t}\n\t\n\tstatic filter_node_cptr operator_handler_missing(const parser & token_left,const parser & token_right)\n\t{\n\t\tif (!token_right.is_empty()) throw exception_parse_error();\n\t\treturn pfc::rcnew_t<filter_node_missing>(token_left.get_ptr(),token_left.get_remaining());\n\t}\n\n\tstatic void parse_string(const parser & src,pfc::string_base & out)\n\t{\n\t\tparser p(src);\n\t\tp.skip_spacing();\n\t\tout.reset();\n\t\tif (p.get_remaining()>0)\n\t\t{\n\t\t\tif (p.get_char()=='\\\"')\n\t\t\t{\n\t\t\t\tp.advance(1);\n\t\t\t\twhile(p.get_remaining()>0 && p.get_char()!='\\\"') {out.add_byte(p.get_char());p.advance(1);}\n\t\t\t\tif (p.get_remaining() == 0) throw exception_parse_error();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tout.add_string(p.get_ptr(),p.get_remaining());\n\t\t\t\tt_size trunc = out.length();\n\t\t\t\twhile(trunc>0 && is_spacing(out[trunc-1])) trunc--;\n\t\t\t\tout.truncate(trunc);\n\t\t\t\tif (trunc == 0) throw exception_parse_error();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse throw exception_parse_error();\n\t}\n\n\tstatic filter_node_cptr operator_handler_has(const parser & token_left,const parser & token_right) {\n\t\tpfc::string8 name,value;\n\t\tparse_string(token_left,name); parse_string(token_right,value);\n\t\tif (!strcmp(name,\"*\")) return pfc::rcnew_t<filter_node_simple>(value);\n\t\telse if (is_format_spec(name)) return pfc::rcnew_t<filter_node_has_ex>(name,value);\n\t\telse return pfc::rcnew_t<filter_node_has>(name,value);\n\t}\n\n\tstatic filter_node_cptr operator_handler_is(const parser & token_left,const parser & token_right)\n\t{\n\t\tpfc::string8 name,value;\n\t\tparse_string(token_left,name); parse_string(token_right,value);\n\t\tif (is_format_spec(name)) return pfc::rcnew_t<filter_node_is_format>(name,value);\n\t\telse return pfc::rcnew_t<filter_node_is>(name,value);\n\t}\n\n\tclass filter_node_mathop : public filter_node\n\t{\n\t\tpfc::string_simple left;\n\t\tservice_ptr_t<titleformat_object> left_script;\n\t\tt_int64 rval;\n\t\tbool left_ex;\n\t\tint type;\n\t\tmutable pfc::string8_fastalloc ltemp;\n\n\t\tstatic t_int64 parse_int_or_time(const char * ptr)\n\t\t{\n\t\t\tbool neg = false;\n\t\t\tt_int64 a = 0;\n\t\t\t// whitespace\n\t\t\twhile (ptr[0] == ' ' || ptr[0] == '\\t')\n\t\t\t\tptr++;\n\t\t\t// sign\n\t\t\tneg = ptr[0] == '-';\n\t\t\tif (ptr[0] == '+' || ptr[0] == '-')\n\t\t\t\tptr++;\n\t\t\t// digits\n\t\t\tif (ptr[0] >= '0' && ptr[0] <= '9')\n\t\t\t{\n\t\t\t\tdo\n\t\t\t\t{\n\t\t\t\t\ta = a * 10 + (ptr[0] - '0');\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t\twhile (*ptr >= '0' && *ptr <= '9');\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn 0;\n\t\t\tif (ptr[0] != ':')\n\t\t\t\treturn neg ? -a : a;\n\t\t\tptr++;\n\t\t\t// minutes or seconds\n\t\t\tif ((ptr[0] >= '0' && ptr[0] <= '5') && (ptr[1] >= '0' && ptr[1] <= '9'))\n\t\t\t{\n\t\t\t\ta = a * 60 + (ptr[0] - '0') * 10 + (ptr[1] - '0');\n\t\t\t\tif (ptr[2] == ':')\n\t\t\t\t{\n\t\t\t\t\t// seconds\n\t\t\t\t\tif ((ptr[3] >= '0' && ptr[3] <= '5') && (ptr[4] >= '0' && ptr[4] <= '9') && !(ptr[5] >= '0' && ptr[5] <= '9'))\n\t\t\t\t\t{\n\t\t\t\t\t\ta = a * 60 + (ptr[3] - '0') * 10 + (ptr[4] - '0');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn neg ? -a : a;\n\t\t}\n\n\tpublic:\n\t\texplicit filter_node_mathop(const char * p_left,const char * p_right,int p_type) : left(p_left), rval(parse_int_or_time(p_right)), type(p_type),\n\t\t\tleft_ex(is_format_spec(p_left))\n\t\t{\n\t\t\tif (left_ex)\n\t\t\t\tstatic_api_ptr_t<titleformat_compiler>()->compile_safe(left_script,left);\n\t\t}\n\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const \n\t\t{\n\t\t\tt_int64 lval;\n\t\t\tif (left_ex)\n\t\t\t{\n\t\t\t\thandle->format_title(0,ltemp,left_script,0);\n\t\t\t\tlval = parse_int_or_time(ltemp);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tconst char * ptr = item->meta_get(left,0);\n\t\t\t\tif (!ptr) return false;\n\t\t\t\tlval = parse_int_or_time(ptr);\n\t\t\t}\n\n\t\t\tswitch(type)\n\t\t\t{\n\t\t\tcase -1: return lval <  rval;\n\t\t\tcase 0:  return lval == rval;\n\t\t\tcase 1:  return lval >  rval;\n\t\t\tdefault: assert(0); return false;\n\t\t\t}\n\t\t}\n\t};\n\n\tstatic filter_node_cptr operator_handler_mathop(const parser & token_left,const parser & token_right,int type) {\n\t\tpfc::string8 left,right;\n\t\tparse_string(token_left,left); parse_string(token_right,right);\n\t\treturn pfc::rcnew_t<filter_node_mathop>(left,right,type);\n\t}\n\n\tstatic filter_node_cptr operator_handler_greater(const parser & token_left,const parser & token_right)\n\t{\n\t\treturn operator_handler_mathop(token_left,token_right,1);\n\t}\n\n\tstatic filter_node_cptr operator_handler_less(const parser & token_left,const parser & token_right)\n\t{\n\t\treturn operator_handler_mathop(token_left,token_right,-1);\n\t}\n\n\tstatic filter_node_cptr operator_handler_equal(const parser & token_left,const parser & token_right)\n\t{\n\t\treturn operator_handler_mathop(token_left,token_right,0);\n\t}\n\n\tstruct operator_desc\n\t{\n\t\tconst char * name;\n\t\tbool right_to_left;\n\t\toperator_handler handler;\n\t\t\n\t\tbool test_name(const char * ptr,t_size len) const\n\t\t{\n\t\t\tconst char * ptr2 = name;\n\t\t\twhile(len)\n\t\t\t{\n\t\t\t\tif (*ptr != *ptr2) return false;\n\t\t\t\tptr++;\n\t\t\t\tptr2++;\n\t\t\t\tlen--;\n\t\t\t}\n\t\t\treturn *ptr2==0;\n\t\t}\n\t};\n\n\tstatic operator_desc g_operators[] =\n\t{\n\t\t{\"OR\",false,operator_handler_or},\n\t\t{\"AND\",false,operator_handler_and},\n\t\t{\"NOT\",false,operator_handler_not},\n\t\t{\"HAS\",false,operator_handler_has},\n\t\t{\"IS\",false,operator_handler_is},\n\t\t{\"IST\",false,operator_handler_is},\n\t\t{\"EQUAL\",false,operator_handler_equal},\n\t\t{\"GREATER\",false,operator_handler_greater},\n\t\t{\"LESS\",false,operator_handler_less},\n\t\t{\"MISSING\",false,operator_handler_missing},\n\t};\n\n\n\tstatic bool has_operators(const char * src) {\n\t\tt_size n;\n\t\tfor(n=0;n<tabsize(g_operators);n++) {\n\t\t\tconst char * name = g_operators[n].name;\n\t\t\tt_size namelen = strlen(name);\n\t\t\tconst char * ptr = src;\n\t\t\tfor(;;) {\n\t\t\t\tptr = strstr(ptr,name);\n\t\t\t\tif (ptr) {\n\t\t\t\t\tif (ptr && (ptr==src || is_spacing(ptr[-1])) && is_spacing_or_null(ptr[namelen])) return true;\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t\telse break;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tstruct token_info {\n\t\tt_size ptr,len;\n\t\ttoken_info() {}\n\t\ttoken_info(t_size p_ptr,t_size p_len) : ptr(p_ptr), len(p_len) {}\n\t};\n\n\tstatic t_size test_operator(const char * ptr,t_size len) {\n\t\tt_size n;\n\t\tfor(n=0;n<tabsize(g_operators);n++) {\n\t\t\tif (g_operators[n].test_name(ptr,len)) return n;\n\t\t}\n\t\treturn ~0;\n\t}\n\n\tstatic bool is_operator(const char * ptr,t_size len) {return test_operator(ptr,len)!=~0;}\n\n\tfilter_node_cptr filter_node::g_create(const parser & p_parser,bool b_allow_simple)\n\t{\n\t\tparser p(p_parser);\n\n\t\tif (b_allow_simple)\n\t\t{\n\t\t\tif (!has_operators(pfc::string8(p.get_ptr(),p.get_remaining())))\n\t\t\t{\n\t\t\t\tpfc::string8 temp;\n\t\t\t\tparse_string(p,temp);\n\t\t\t\treturn pfc::rcnew_t<filter_node_simple>(temp);\n\t\t\t}\n\t\t}\n\n\t\tpfc::list_hybrid_t<token_info,8> operators;\n\t\t\n\t\tp.skip_spacing();\n\t\twhile(p.get_remaining()>0)\n\t\t{\n\t\t\tt_size delta = p.test_token();\n\t\t\tif (delta==0) throw exception_parse_error();\n\t\t\tif (is_operator(p.get_ptr(),delta)) operators.add_item(token_info(p.get_offset(),delta));\n\t\t\tp.advance(delta);\n\t\t\tp.skip_spacing();\n\t\t}\n\n\t\tp.reset();\n\n\t\tif (operators.get_count()>0)\n\t\t{\n\t\t\tt_size n;\n\t\t\tfor(n=0;n<tabsize(g_operators);n++)\n\t\t\t{\n\t\t\t\tif (g_operators[n].right_to_left)\n\t\t\t\t{\n\t\t\t\t\tt_size m;\n\t\t\t\t\tfor(m=operators.get_count()-1;m!=infinite;m--)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (g_operators[n].test_name(p.get_ptr()+operators[m].ptr,operators[m].len))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tt_size right_base = operators[m].ptr + operators[m].len;\n\t\t\t\t\t\t\treturn g_operators[n].handler(parser(p.get_ptr(),operators[m].ptr),parser(p.get_ptr()+right_base,p.get_remaining()-right_base));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tt_size m;\n\t\t\t\t\tfor(m=0;m<operators.get_count();m++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (g_operators[n].test_name(p.get_ptr()+operators[m].ptr,operators[m].len))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tt_size right_base = operators[m].ptr + operators[m].len;\n\t\t\t\t\t\t\treturn g_operators[n].handler(parser(p.get_ptr(),operators[m].ptr),parser(p.get_ptr()+right_base,p.get_remaining()-right_base));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow exception_parse_error();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tp.skip_spacing();\n\t\t\tif (p.get_remaining()>0 && p.get_char()=='(')\n\t\t\t{\n\t\t\t\tt_size base = p.get_offset();\n\t\t\t\tt_size len = p.skip_token();\n\t\t\t\tif (len==0 || len<2) throw exception_parse_error();\n\t\t\t\tif (!p.is_empty()) throw exception_parse_error();\n\t\t\t\tp.reset(base+1);\n\t\t\t\treturn g_create(parser(p,len-2));\n\t\t\t}\n\t\t\telse if (b_allow_simple)\n\t\t\t{\n\t\t\t\tpfc::string8 temp;\n\t\t\t\tparse_string(p,temp);\n\t\t\t\treturn pfc::rcnew_t<filter_node_simple>(temp);\n\t\t\t}\n\t\t\tthrow exception_parse_error();\n\t\t}\n\t}\n\n\tfilter_node_cptr filter_node::g_create(const char * ptr,t_size len,bool b_allow_simple) {\n\t\treturn g_create(parser(ptr,len),b_allow_simple);\n\t}\n}\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/search_filter.h",
    "content": "namespace search_tools {\r\n\r\n\tPFC_DECLARE_EXCEPTION(exception_parse_error,pfc::exception,\"Error parsing filter expression\");\r\n\r\n\tclass filter_node;\r\n\t\t\r\n\ttypedef pfc::rcptr_const_t<filter_node> filter_node_cptr;\r\n\ttypedef pfc::rcptr_t<filter_node> filter_node_ptr;\r\n\r\n\tclass NOVTABLE filter_node {\r\n\tpublic:\r\n\t\tvirtual bool test(const file_info * item,const metadb_handle_ptr & handle) const = 0;\r\n\t\tvirtual ~filter_node() {}\r\n\t\tstatic filter_node_cptr g_create(const char * ptr,t_size len,bool b_allow_simple = false);\r\n\t\tstatic filter_node_cptr g_create(const class parser & p,bool b_allow_simple = false);\r\n\t};\r\n\r\n\tclass search_filter {\r\n\t\tfilter_node_cptr m_root;\r\n\tpublic:\r\n\t\tsearch_filter() {}\r\n\t\t~search_filter() {}\r\n\t\tbool init(const char * pattern) {\r\n\t\t\ttry {\r\n\t\t\t\tm_root =  filter_node::g_create(pattern,strlen(pattern),true) ;\r\n\t\t\t\treturn true;\r\n\t\t\t} catch(exception_parse_error) {return false;}\r\n\t\t}\r\n\r\n\t\tvoid deinit() {\r\n\t\t\tm_root.release();\r\n\t\t}\r\n\r\n\t\tbool test(const file_info * item,const metadb_handle_ptr & handle) const {\r\n\t\t\treturn m_root.is_valid() ? m_root->test(item,handle) : false;\r\n\t\t}\r\n\r\n\t\tbool test(const metadb_handle_ptr & item) const {\r\n\t\t\tbool rv = false;\r\n\t\t\tconst file_info * ptr;\r\n\t\t\tif (item->get_info_locked(ptr)) rv = test(ptr,item);\r\n\t\t\treturn rv;\r\n\t\t}\r\n\t};\r\n\r\n\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/seekabilizer.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nenum {backread_on_seek = 1024};\r\n\r\nvoid seekabilizer_backbuffer::initialize(t_size p_size)\r\n{\r\n\tm_depth = m_cursor = 0;\r\n\r\n\tm_buffer.set_size(p_size);\r\n}\r\n\r\nvoid seekabilizer_backbuffer::write(const void * p_buffer,t_size p_bytes)\r\n{\r\n\tif (p_bytes >= m_buffer.get_size())\r\n\t{\r\n\t\tmemcpy(m_buffer.get_ptr(),(const t_uint8*)p_buffer + p_bytes - m_buffer.get_size(),m_buffer.get_size());\r\n\t\tm_cursor = 0;\r\n\t\tm_depth = m_buffer.get_size();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tconst t_uint8* sourceptr = (const t_uint8*) p_buffer;\r\n\t\tt_size remaining = p_bytes;\r\n\t\twhile(remaining > 0)\r\n\t\t{\r\n\t\t\tt_size delta = m_buffer.get_size() - m_cursor;\r\n\t\t\tif (delta > remaining) delta = remaining;\r\n\r\n\t\t\tmemcpy(m_buffer.get_ptr() + m_cursor,sourceptr,delta);\r\n\r\n\t\t\tsourceptr += delta;\r\n\t\t\tremaining -= delta;\r\n\t\t\tm_cursor = (m_cursor + delta) % m_buffer.get_size();\r\n\r\n\t\t\tm_depth = pfc::min_t<t_size>(m_buffer.get_size(),m_depth + delta);\r\n\t\t\t\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid seekabilizer_backbuffer::read(t_size p_backlogdepth,void * p_buffer,t_size p_bytes) const\r\n{\r\n\tassert(p_backlogdepth <= m_depth);\r\n\tassert(p_backlogdepth >= p_bytes);\r\n\r\n\t\t\r\n\tt_uint8* targetptr = (t_uint8*) p_buffer;\r\n\tt_size remaining = p_bytes;\r\n\tt_size cursor = (m_cursor + m_buffer.get_size() - p_backlogdepth) % m_buffer.get_size();\r\n\t\r\n\twhile(remaining > 0)\r\n\t{\r\n\t\tt_size delta = m_buffer.get_size() - cursor;\r\n\t\tif (delta > remaining) delta = remaining;\r\n\t\t\r\n\t\tmemcpy(targetptr,m_buffer.get_ptr() + cursor,delta);\r\n\r\n\t\ttargetptr += delta;\r\n\t\tremaining -= delta;\r\n\t\tcursor = (cursor + delta) % m_buffer.get_size();\r\n\t}\r\n}\r\n\r\nt_size seekabilizer_backbuffer::get_depth() const\r\n{\r\n\treturn m_depth;\r\n}\r\n\r\nt_size seekabilizer_backbuffer::get_max_depth() const\r\n{\r\n\treturn m_buffer.get_size();\r\n}\r\n\r\nvoid seekabilizer_backbuffer::reset()\r\n{\r\n\tm_depth = m_cursor = 0;\r\n}\r\n\r\n\r\nvoid seekabilizer::initialize(service_ptr_t<file> p_base,t_size p_buffer_size,abort_callback & p_abort) {\r\n\tm_buffer.initialize(p_buffer_size);\r\n\tm_file = p_base;\r\n\tm_position = m_position_base = 0;\r\n\tm_size = m_file->get_size(p_abort);\r\n}\r\n\r\nvoid seekabilizer::g_seekabilize(service_ptr_t<file> & p_reader,t_size p_buffer_size,abort_callback & p_abort) {\r\n\tif (p_reader.is_valid() && p_reader->is_remote() && p_buffer_size > 0) {\r\n\t\tservice_ptr_t<seekabilizer> instance = new service_impl_t<seekabilizer>();\r\n\t\tinstance->initialize(p_reader,p_buffer_size,p_abort);\r\n\t\tp_reader = instance.get_ptr();\r\n\t}\r\n}\r\n\r\nt_size seekabilizer::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\r\n\tif (m_position > m_position_base + pfc::max_t<t_size>(m_buffer.get_max_depth(),backread_on_seek) && m_file->can_seek()) {\r\n\t\tt_filesize target = m_position;\r\n\t\tif (target < backread_on_seek) target = 0;\r\n\t\telse target -= backread_on_seek;\r\n\t\tm_file->seek(target,p_abort);\r\n\t\tm_position_base = target;\r\n\t}\r\n\r\n\t//seek ahead\r\n\twhile(m_position > m_position_base) {\r\n\t\tenum {tempsize = 1024};\r\n\t\tt_uint8 temp[tempsize];\r\n\t\tt_size delta = (t_size) pfc::min_t<t_filesize>(tempsize,m_position - m_position_base);\r\n\t\tt_size bytes_read = 0;\r\n\t\tbytes_read = m_file->read(temp,delta,p_abort);\r\n\t\tm_buffer.write(temp,bytes_read);\r\n\t\tm_position_base += bytes_read;\r\n\r\n\t\tif (bytes_read < delta) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\tt_size done = 0;\r\n\tt_uint8 * targetptr = (t_uint8*) p_buffer;\r\n\r\n\t//try to read backbuffer\r\n\tif (m_position < m_position_base) {\r\n\t\tif (m_position_base - m_position > (t_filesize)m_buffer.get_depth()) throw exception_io_seek_out_of_range();\r\n\t\tt_size backread_depth = (t_size) (m_position_base - m_position);\r\n\t\tt_size delta = pfc::min_t<t_size>(backread_depth,p_bytes-done);\r\n\t\tm_buffer.read(backread_depth,targetptr,delta);\r\n\t\tdone += delta;\r\n\t\tm_position += delta;\r\n\t}\r\n\r\n\t//regular read\r\n\tif (done < p_bytes)\r\n\t{\r\n\t\tt_size bytes_read;\r\n\t\tbytes_read = m_file->read(targetptr+done,p_bytes-done,p_abort);\r\n\r\n\t\tm_buffer.write(targetptr+done,bytes_read);\r\n\r\n\t\tdone += bytes_read;\r\n\t\tm_position += bytes_read;\r\n\t\tm_position_base += bytes_read;\r\n\t}\r\n\r\n\treturn done;\r\n}\r\n\r\nt_filesize seekabilizer::get_size(abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\treturn m_size;\r\n}\r\n\r\nt_filesize seekabilizer::get_position(abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\treturn m_position;\r\n}\r\n\r\nvoid seekabilizer::seek(t_filesize p_position,abort_callback & p_abort) {\r\n\tassert(m_position_base >= m_buffer.get_depth());\r\n\tp_abort.check_e();\r\n\r\n\tif (m_size != filesize_invalid && p_position > m_size) throw exception_io_seek_out_of_range();\r\n\r\n\tt_filesize lowest = m_position_base - m_buffer.get_depth();\r\n\r\n\tif (p_position < lowest) {\r\n\t\tif (m_file->can_seek()) {\r\n\t\t\tm_buffer.reset();\r\n\t\t\tt_filesize target = p_position;\r\n\t\t\tt_size delta = m_buffer.get_max_depth();\r\n\t\t\tif (delta > backread_on_seek) delta = backread_on_seek;\r\n\t\t\tif (target > delta) target -= delta;\r\n\t\t\telse target = 0;\r\n\t\t\tm_file->seek(target,p_abort);\r\n\t\t\tm_position_base = target;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tm_buffer.reset();\r\n\t\t\tm_file->reopen(p_abort);\r\n\t\t\tm_position_base = 0;\r\n\t\t}\r\n\t}\r\n\r\n\tm_position = p_position;\r\n}\r\n\r\nbool seekabilizer::can_seek()\r\n{\r\n\treturn true;\r\n}\r\n\r\nbool seekabilizer::get_content_type(pfc::string_base & p_out) {return m_file->get_content_type(p_out);}\r\n\r\nbool seekabilizer::is_in_memory() {return false;}\r\n\r\nvoid seekabilizer::on_idle(abort_callback & p_abort) {return m_file->on_idle(p_abort);}\r\n\r\nt_filetimestamp seekabilizer::get_timestamp(abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\treturn m_file->get_timestamp(p_abort);\r\n}\r\n\r\nvoid seekabilizer::reopen(abort_callback & p_abort) {\r\n\tif (m_position_base - m_buffer.get_depth() == 0) {\r\n\t\tseek(0,p_abort);\r\n\t} else {\r\n\t\tm_position = m_position_base = 0;\r\n\t\tm_buffer.reset();\r\n\t\tm_file->reopen(p_abort);\r\n\t}\r\n}\r\n\r\nbool seekabilizer::is_remote()\r\n{\r\n\treturn m_file->is_remote();\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/seekabilizer.h",
    "content": "class seekabilizer_backbuffer\r\n{\r\npublic:\r\n\tvoid initialize(t_size p_size);\r\n\tvoid write(const void * p_buffer,t_size p_bytes);\r\n\tvoid read(t_size p_backlogdepth,void * p_buffer,t_size p_bytes) const;\r\n\tt_size get_depth() const;\r\n\tvoid reset();\r\n\tt_size get_max_depth() const;\r\nprivate:\r\n\tpfc::array_t<t_uint8> m_buffer;\r\n\tt_size m_depth,m_cursor;\r\n};\r\n\r\nclass seekabilizer : public file_readonly {\r\npublic:\r\n\tvoid initialize(service_ptr_t<file> p_base,t_size p_buffer_size,abort_callback & p_abort);\r\n\t\r\n\tstatic void g_seekabilize(service_ptr_t<file> & p_reader,t_size p_buffer_size,abort_callback & p_abort);\r\n\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\tt_filesize get_size(abort_callback & p_abort);\r\n\tt_filesize get_position(abort_callback & p_abort);\r\n\tvoid seek(t_filesize p_position,abort_callback & p_abort);\r\n\tbool can_seek();\r\n\tbool get_content_type(pfc::string_base & p_out);\r\n\tbool is_in_memory();\r\n\tvoid on_idle(abort_callback & p_abort);\r\n\tt_filetimestamp get_timestamp(abort_callback & p_abort);\r\n\tvoid reopen(abort_callback & p_abort);\r\n\tbool is_remote();\r\nprivate:\r\n\tservice_ptr_t<file> m_file;\r\n\tseekabilizer_backbuffer m_buffer;\r\n\tt_filesize m_size,m_position,m_position_base;\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/stream_buffer_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstream_reader_buffered::stream_reader_buffered(stream_reader * p_base,t_size p_buffer) : m_base(p_base)\r\n{\r\n\tm_buffer.set_size(p_buffer);\r\n\tm_buffer_ptr = 0;\r\n\tm_buffer_max = 0;\r\n}\r\n\r\nt_size stream_reader_buffered::read(void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\tchar * output = (char*) p_buffer;\r\n\tt_size output_ptr = 0;\r\n\t\r\n\twhile(output_ptr < p_bytes) {\r\n\t\t{\r\n\t\t\tt_size delta = pfc::min_t(p_bytes - output_ptr, m_buffer_max - m_buffer_ptr);\r\n\t\t\tif (delta > 0)\r\n\t\t\t{\r\n\t\t\t\tmemcpy(output + output_ptr, m_buffer.get_ptr() + m_buffer_ptr, delta);\r\n\t\t\t\toutput_ptr += delta;\r\n\t\t\t\tm_buffer_ptr += delta;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (m_buffer_ptr == m_buffer_max)\r\n\t\t{\r\n\t\t\tt_size bytes_read;\r\n\t\t\tbytes_read = m_base->read(m_buffer.get_ptr(), m_buffer.get_size(), p_abort);\r\n\t\t\tm_buffer_ptr = 0;\r\n\t\t\tm_buffer_max = bytes_read;\r\n\r\n\t\t\tif (m_buffer_max == 0) break;\r\n\t\t}\r\n\t}\t\t\r\n\r\n\treturn output_ptr;\r\n}\r\n\r\nstream_writer_buffered::stream_writer_buffered(stream_writer * p_base,t_size p_buffer)\r\n\t: m_base(p_base)\r\n{\r\n\tm_buffer.set_size(p_buffer);\r\n\tm_buffer_ptr = 0;\r\n}\r\n\t\r\nvoid stream_writer_buffered::write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort) {\r\n\tp_abort.check_e();\r\n\tconst char * source = (const char*)p_buffer;\r\n\tt_size source_remaining = p_bytes;\r\n\tconst t_size buffer_size = m_buffer.get_size();\r\n\tif (source_remaining >= buffer_size)\r\n\t{\r\n\t\tflush(p_abort);\r\n\t\tm_base->write_object(source,source_remaining,p_abort);\r\n\t\treturn;\r\n\t}\r\n\r\n\tif (m_buffer_ptr + source_remaining >= buffer_size)\r\n\t{\r\n\t\tt_size delta = buffer_size - m_buffer_ptr;\r\n\t\tmemcpy(m_buffer.get_ptr() + m_buffer_ptr, source,delta);\r\n\t\tsource += delta;\r\n\t\tsource_remaining -= delta;\r\n\t\tm_buffer_ptr += delta;\r\n\t\tflush(p_abort);\r\n\t}\r\n\r\n\tmemcpy(m_buffer.get_ptr() + m_buffer_ptr, source,source_remaining);\r\n\tm_buffer_ptr += source_remaining;\r\n}\r\n\r\n\r\nvoid stream_writer_buffered::flush(abort_callback & p_abort) {\r\n\tif (m_buffer_ptr > 0) {\r\n\t\tm_base->write_object(m_buffer.get_ptr(),m_buffer_ptr,p_abort);\r\n\t\tm_buffer_ptr = 0;\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/stream_buffer_helper.h",
    "content": "class stream_reader_buffered : public stream_reader\r\n{\r\npublic:\r\n\tstream_reader_buffered(stream_reader * p_base,t_size p_buffer);\r\n\tt_size read(void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\nprivate:\r\n\tstream_reader * m_base;\r\n\tpfc::array_t<char> m_buffer;\r\n\tt_size m_buffer_ptr, m_buffer_max;\r\n};\r\n\r\nclass stream_writer_buffered : public stream_writer\r\n{\r\npublic:\r\n\tstream_writer_buffered(stream_writer * p_base,t_size p_buffer);\r\n\t\r\n\tvoid write(const void * p_buffer,t_size p_bytes,abort_callback & p_abort);\r\n\r\n\tvoid flush(abort_callback & p_abort);\r\n\r\nprivate:\r\n\tstream_writer * m_base;\r\n\tpfc::array_t<char> m_buffer;\r\n\tt_size m_buffer_ptr;\r\n};\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/string_filter.h",
    "content": "class string_filter_noncasesensitive {\r\npublic:\r\n\tstring_filter_noncasesensitive(const char * p_string,t_size p_string_len = infinite) {\r\n\t\tuStringLower(m_pattern,p_string,p_string_len);\r\n\t}\r\n\r\n\tbool test(const char * p_string,t_size p_string_len = infinite) const {\r\n\t\t::uStringLower(m_lowercasebuffer,p_string,p_string_len);\r\n\t\tt_size walk = 0;\r\n\t\twhile(m_pattern[walk] != 0) {\r\n\t\t\twhile(m_pattern[walk] == ' ') walk++;\r\n\t\t\tt_size delta = 0;\r\n\t\t\twhile(m_pattern[walk+delta] != 0 && m_pattern[walk+delta] != ' ') delta++;\r\n\t\t\tif (delta > 0) {\r\n\t\t\t\tif (pfc::string_find_first_ex(m_lowercasebuffer,infinite,m_pattern+walk,delta) == infinite) return false;\r\n\t\t\t}\r\n\t\t\twalk += delta;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\nprivate:\r\n\tmutable pfc::string8_fastalloc m_lowercasebuffer;\r\n\tpfc::string8 m_pattern;\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/text_file_loader.cpp",
    "content": "#include \"StdAfx.h\"\r\n\r\nstatic const unsigned char utf8_header[3] = {0xEF,0xBB,0xBF};\r\n\r\nnamespace text_file_loader\r\n{\r\n\tvoid write(const service_ptr_t<file> & p_file,abort_callback & p_abort,const char * p_string,bool is_utf8)\r\n\t{\r\n\t\tp_file->seek(0,p_abort);\r\n\t\tp_file->set_eof(p_abort);\r\n\t\tif (is_utf8)\r\n\t\t{\r\n\t\t\tp_file->write_object(utf8_header,sizeof(utf8_header),p_abort);\r\n\t\t\tp_file->write_object(p_string,strlen(p_string),p_abort);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tpfc::stringcvt::string_ansi_from_utf8 bah(p_string);\r\n\t\t\tp_file->write_object(bah,bah.length(),p_abort);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid read(const service_ptr_t<file> & p_file,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8) {\r\n\t\tp_out.reset();\r\n\t\tif (p_file->can_seek())\r\n\t\t{\r\n\t\t\tp_file->seek(0,p_abort);\r\n\t\t}\r\n\t\t\r\n\t\tpfc::array_t<char> mem;\r\n\t\tt_filesize size64;\r\n\t\tsize64 = p_file->get_size(p_abort);\r\n\t\tif (size64 == filesize_invalid)//typically HTTP\r\n\t\t{\r\n\t\t\tpfc::string8 ansitemp;\r\n\t\t\tis_utf8 = false;\r\n\t\t\tenum {delta = 1024*64, max = 1024*512};\r\n\t\t\tchar temp[3];\r\n\t\t\tt_size done;\r\n\t\t\tdone = p_file->read(temp,3,p_abort);\r\n\t\t\tif (done != 3)\r\n\t\t\t{\r\n\t\t\t\tif (done > 0) p_out = pfc::stringcvt::string_utf8_from_ansi(temp,done);\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t\tif (!memcmp(utf8_header,temp,3)) is_utf8 = true;\r\n\t\t\telse ansitemp.add_string(temp,3);\r\n\r\n\t\t\tmem.set_size(delta);\r\n\t\t\t\r\n\t\t\tfor(;;)\r\n\t\t\t{\r\n\t\t\t\tdone = p_file->read(mem.get_ptr(),delta,p_abort);\r\n\t\t\t\tif (done > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (is_utf8) p_out.add_string(mem.get_ptr(),done);\r\n\t\t\t\t\telse ansitemp.add_string(mem.get_ptr(),done);\r\n\t\t\t\t}\r\n\t\t\t\tif (done < delta) break;\r\n\t\t\t}\r\n\r\n\t\t\tif (!is_utf8)\r\n\t\t\t{\r\n\t\t\t\tp_out = pfc::stringcvt::string_utf8_from_ansi(ansitemp);\r\n\t\t\t}\r\n\r\n\t\t\treturn;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (size64>1024*1024*128) throw exception_io_data();//hard limit\r\n\t\t\tt_size size = pfc::downcast_guarded<t_size>(size64);\r\n\t\t\tmem.set_size(size+1);\r\n\t\t\tchar * asdf = mem.get_ptr();\r\n\t\t\tp_file->read_object(asdf,size,p_abort);\r\n\t\t\tasdf[size]=0;\r\n\t\t\tif (size>3 && !memcmp(utf8_header,asdf,3)) {is_utf8 = true; p_out.add_string(asdf+3); }\r\n\t\t\telse {\r\n\t\t\t\tis_utf8 = false;\r\n\t\t\t\tp_out = pfc::stringcvt::string_utf8_from_ansi(asdf);\r\n\t\t\t}\r\n\t\t\treturn;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid write(const char * p_path,abort_callback & p_abort,const char * p_string,bool is_utf8)\r\n\t{\r\n\t\tservice_ptr_t<file> f;\r\n\t\tfilesystem::g_open_write_new(f,p_path,p_abort);\r\n\t\twrite(f,p_abort,p_string,is_utf8);\r\n\t}\r\n\r\n\tvoid read(const char * p_path,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8)\r\n\t{\r\n\t\tservice_ptr_t<file> f;\r\n\t\tfilesystem::g_open_read(f,p_path,p_abort);\r\n\t\tread(f,p_abort,p_out,is_utf8);\r\n\t}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/text_file_loader.h",
    "content": "namespace text_file_loader\r\n{\r\n\tvoid write(const service_ptr_t<file> & p_file,abort_callback & p_abort,const char * p_string,bool is_utf8);\r\n\tvoid read(const service_ptr_t<file> & p_file,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8);\r\n\r\n\tvoid write(const char * p_path,abort_callback & p_abort,const char * p_string,bool is_utf8);\r\n\tvoid read(const char * p_path,abort_callback & p_abort,pfc::string_base & p_out,bool & is_utf8);\r\n\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/wildcard.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic bool test_recur(const char * fn,const char * rm,bool b_sep)\r\n{\r\n\tfor(;;)\r\n\t{\r\n\t\tif ((b_sep && *rm==';') || *rm==0) return *fn==0;\r\n\t\telse if (*rm=='*')\r\n\t\t{\r\n\t\t\trm++;\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tif (test_recur(fn,rm,b_sep)) return true;\r\n\t\t\t} while(pfc::utf8_advance(fn));\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\telse if (*fn==0) return false;\r\n\t\telse if (*rm!='?' && char_lower(pfc::utf8_get_char(fn))!=char_lower(pfc::utf8_get_char(rm))) return false;\r\n\t\t\r\n\t\tfn = pfc::utf8_char_next(fn); rm = pfc::utf8_char_next(rm);\r\n\t}\r\n}\r\n\r\nbool wildcard_helper::test_path(const char * path,const char * pattern,bool b_sep) {return test(path + pfc::scan_filename(path),pattern,b_sep);}\r\n\r\nbool wildcard_helper::test(const char * fn,const char * pattern,bool b_sep)\r\n{\r\n\tif (!b_sep) return test_recur(fn,pattern,false);\r\n\tconst char * rm=pattern;\r\n\twhile(*rm)\r\n\t{\r\n\t\tif (test_recur(fn,rm,true)) return true;\r\n\t\twhile(*rm && *rm!=';') rm++;\r\n\t\tif (*rm==';')\r\n\t\t{\r\n\t\t\twhile(*rm==';') rm++;\r\n\t\t\twhile(*rm==' ') rm++;\r\n\t\t}\r\n\t};\r\n\r\n\treturn false;\r\n}\r\n\r\nbool wildcard_helper::has_wildcards(const char * str) {return strchr(str,'*') || strchr(str,'?');}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/wildcard.h",
    "content": "#ifndef __FOOBAR2000_HELPER_WILDCARD_H__\r\n#define __FOOBAR2000_HELPER_WILDCARD_H__\r\n\r\nnamespace wildcard_helper\r\n{\r\n\tbool test_path(const char * path,const char * pattern,bool b_separate_by_semicolon = false);//will extract filename from path first\r\n\tbool test(const char * str,const char * pattern,bool b_separate_by_semicolon = false);//tests if str matches pattern\r\n\tbool has_wildcards(const char * str);\r\n};\r\n\r\n#endif //__FOOBAR2000_HELPER_WILDCARD_H__"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/win32_dialog.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\n\r\nnamespace dialog_helper {\r\n\r\n\r\n\tINT_PTR CALLBACK dialog::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tdialog * p_this;\r\n\t\tBOOL rv;\r\n\t\tif (msg==WM_INITDIALOG)\r\n\t\t{\r\n\t\t\tp_this = reinterpret_cast<dialog*>(lp);\r\n\t\t\tp_this->wnd = wnd;\r\n\t\t\tSetWindowLongPtr(wnd,DWLP_USER,lp);\r\n\r\n\t\t\tif (p_this->m_is_modal) p_this->m_modal_scope.initialize(wnd);\r\n\t\t}\r\n\t\telse p_this = reinterpret_cast<dialog*>(GetWindowLongPtr(wnd,DWLP_USER));\r\n\r\n\t\trv = p_this ? p_this->on_message(msg,wp,lp) : FALSE;\r\n\r\n\t\tif (msg==WM_DESTROY && p_this)\r\n\t\t{\r\n\t\t\tSetWindowLongPtr(wnd,DWLP_USER,0);\r\n//\t\t\tp_this->wnd = 0;\r\n\t\t}\r\n\r\n\t\treturn rv;\r\n\t}\r\n\r\n\r\n\tint dialog::run_modal(unsigned id,HWND parent)\r\n\t{\r\n\t\tassert(wnd == 0);\r\n\t\tif (wnd != 0) return -1;\r\n\t\tm_is_modal = true; \r\n\t\treturn uDialogBox(id,parent,DlgProc,reinterpret_cast<LPARAM>(this));\r\n\t}\r\n\tHWND dialog::run_modeless(unsigned id,HWND parent)\r\n\t{\r\n\t\tassert(wnd == 0);\r\n\t\tif (wnd != 0) return 0;\r\n\t\tm_is_modal = false; \r\n\t\treturn uCreateDialog(id,parent,DlgProc,reinterpret_cast<LPARAM>(this));\r\n\t}\r\n\r\n\tvoid dialog::end_dialog(int code)\r\n\t{\r\n\t\tassert(m_is_modal); \r\n\t\tif (m_is_modal) uEndDialog(wnd,code);\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tint dialog_modal::run(unsigned p_id,HWND p_parent,HINSTANCE p_instance)\r\n\t{\r\n\t\tint status;\r\n\r\n\t\t// note: uDialogBox() has its own modal scope, we don't want that to trigger\r\n\t\t// if this is ever changed, move deinit to WM_DESTROY handler in DlgProc\r\n\r\n\t\tstatus = (int)DialogBoxParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast<LPARAM>(this));\r\n\r\n\t\tm_modal_scope.deinitialize();\r\n\r\n\t\treturn status;\r\n\t}\r\n\t\t\r\n\tvoid dialog_modal::end_dialog(int p_code)\r\n\t{\r\n\t\tEndDialog(m_wnd,p_code);\r\n\t}\r\n\r\n\t\t\r\n\tINT_PTR CALLBACK dialog_modal::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tdialog_modal * _this;\r\n\t\tif (msg==WM_INITDIALOG)\r\n\t\t{\r\n\t\t\t_this = reinterpret_cast<dialog_modal*>(lp);\r\n\t\t\t_this->m_wnd = wnd;\r\n\t\t\tSetWindowLongPtr(wnd,DWLP_USER,lp);\r\n\r\n\t\t\t_this->m_modal_scope.initialize(wnd);\r\n\t\t}\r\n\t\telse _this = reinterpret_cast<dialog_modal*>(GetWindowLongPtr(wnd,DWLP_USER));\r\n\r\n\t\tassert(_this == 0 || _this->m_wnd == wnd);\r\n\r\n\t\treturn _this ? _this->on_message(msg,wp,lp) : FALSE;\r\n\t}\r\n\r\n\r\n\tbool dialog_modeless::create(unsigned p_id,HWND p_parent,HINSTANCE p_instance) {\r\n\t\tassert(!m_is_in_create);\r\n\t\tif (m_is_in_create) return false;\r\n\t\tpfc::vartoggle_t<bool> scope(m_is_in_create,true);\r\n\t\tif (CreateDialogParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast<LPARAM>(this)) == 0) return false;\r\n\t\treturn m_wnd != 0;\r\n\t}\r\n\r\n\tdialog_modeless::~dialog_modeless() {\r\n\t\tassert(!m_is_in_create);\r\n\t\tswitch(m_destructor_status)\r\n\t\t{\r\n\t\tcase destructor_none:\r\n\t\t\tm_destructor_status = destructor_normal;\r\n\t\t\tif (m_wnd != 0)\r\n\t\t\t{\r\n\t\t\t\tDestroyWindow(m_wnd);\r\n\t\t\t\tm_wnd = 0;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase destructor_fromwindow:\r\n\t\t\tif (m_wnd != 0) SetWindowLongPtr(m_wnd,DWLP_USER,0);\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\t//should never trigger\r\n\t\t\tpfc::crash();\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid dialog_modeless::on_window_destruction()\r\n\t{\r\n\t\tif (m_is_in_create)\r\n\t\t{\r\n\t\t\tm_wnd = 0;\r\n\t\t}\r\n\t\telse\r\n\t\tswitch(m_destructor_status)\r\n\t\t{\r\n\t\tcase destructor_none:\r\n\t\t\tm_destructor_status = destructor_fromwindow;\r\n\t\t\tdelete this;\r\n\t\t\tbreak;\r\n\t\tcase destructor_fromwindow:\r\n\t\t\tpfc::crash();\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tBOOL dialog_modeless::on_message_wrap(UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tif (m_destructor_status == destructor_none)\r\n\t\t\treturn on_message(msg,wp,lp);\r\n\t\telse\r\n\t\t\treturn FALSE;\r\n\t}\r\n\r\n\tINT_PTR CALLBACK dialog_modeless::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tdialog_modeless * thisptr;\r\n\t\tBOOL rv;\r\n\t\tif (msg == WM_INITDIALOG)\r\n\t\t{\r\n\t\t\tthisptr = reinterpret_cast<dialog_modeless*>(lp);\r\n\t\t\tthisptr->m_wnd = wnd;\r\n\t\t\tSetWindowLongPtr(wnd,DWLP_USER,lp);\r\n\t\t\tmodeless_dialog_manager::g_add(wnd);\r\n\t\t}\r\n\t\telse thisptr = reinterpret_cast<dialog_modeless*>(GetWindowLongPtr(wnd,DWLP_USER));\r\n\r\n\t\trv = thisptr ? thisptr->on_message_wrap(msg,wp,lp) : FALSE;\r\n\r\n\t\tif (msg == WM_DESTROY)\r\n\t\t\tmodeless_dialog_manager::g_remove(wnd);\r\n\r\n\t\tif (msg == WM_DESTROY && thisptr != 0)\r\n\t\t\tthisptr->on_window_destruction();\r\n\r\n\t\treturn rv;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\tdialog_modeless_v2::dialog_modeless_v2(unsigned p_id,HWND p_parent,HINSTANCE p_instance,bool p_stealfocus) : m_wnd(0), m_status(status_construction), m_stealfocus(p_stealfocus)\r\n\t{\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tHWND result = CreateDialogParam(p_instance,MAKEINTRESOURCE(p_id),p_parent,DlgProc,reinterpret_cast<LPARAM>(this));\r\n\t\tif (result == 0 || m_wnd == 0) throw exception_win32(GetLastError());\r\n\t\tm_status = status_lifetime;\r\n\t}\r\n\r\n\tdialog_modeless_v2::~dialog_modeless_v2()\r\n\t{\r\n\t\tbool is_window_being_destroyed = (m_status == status_destruction_requested);\r\n\t\tm_status = status_destruction;\r\n\r\n\t\tif (m_wnd != 0)\r\n\t\t{\r\n\t\t\tif (is_window_being_destroyed)\r\n\t\t\t\tdetach_window();\r\n\t\t\telse\r\n\t\t\t\tDestroyWindow(m_wnd);\r\n\t\t}\r\n\t}\r\n\t\r\n\tINT_PTR CALLBACK dialog_modeless_v2::DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tdialog_modeless_v2 * thisptr;\r\n\t\tBOOL rv = FALSE;\r\n\t\tif (msg == WM_INITDIALOG)\r\n\t\t{\r\n\t\t\tthisptr = reinterpret_cast<dialog_modeless_v2*>(lp);\r\n\t\t\tassert(thisptr->m_status == status_construction);\r\n\t\t\tthisptr->m_wnd = wnd;\r\n\t\t\tSetWindowLongPtr(wnd,DWLP_USER,lp);\r\n\t\t\tmodeless_dialog_manager::g_add(wnd);\r\n\t\t}\r\n\t\telse thisptr = reinterpret_cast<dialog_modeless_v2*>(GetWindowLongPtr(wnd,DWLP_USER));\r\n\r\n\t\tif (thisptr != NULL) rv = thisptr->on_message_internal(msg,wp,lp);\r\n\r\n\t\tif (msg == WM_DESTROY)\r\n\t\t{\r\n\t\t\tmodeless_dialog_manager::g_remove(wnd);\r\n\t\t}\r\n\r\n\t\treturn rv;\r\n\t}\r\n\r\n\r\n\tvoid dialog_modeless_v2::detach_window()\r\n\t{\r\n\t\tif (m_wnd != 0)\r\n\t\t{\r\n\t\t\tSetWindowLongPtr(m_wnd,DWLP_USER,0);\r\n\t\t\tm_wnd = 0;\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\tBOOL dialog_modeless_v2::on_message_internal(UINT msg,WPARAM wp,LPARAM lp)\r\n\t{\r\n\t\tif (m_status == status_lifetime || m_status == status_destruction_requested)\r\n\t\t{\r\n\t\t\tif (msg == WM_DESTROY)\r\n\t\t\t{\r\n\t\t\t\tassert(m_status == status_lifetime);\r\n\t\t\t\tm_status = status_destruction_requested;\r\n\t\t\t\tdelete this;\r\n\t\t\t\treturn TRUE;\r\n\t\t\t}\r\n\t\t\telse \r\n\t\t\t\treturn on_message(msg,wp,lp);\r\n\t\t}\r\n\t\telse if (m_status == status_construction)\r\n\t\t{\r\n\t\t\tif (msg == WM_INITDIALOG) return m_stealfocus ? TRUE : FALSE;\r\n\t\t\telse return FALSE;\r\n\t\t}\r\n\t\telse return FALSE;\r\n\t}\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/win32_dialog.h",
    "content": "#ifndef _FOOBAR2000_HELPERS_WIN32_DIALOG_H_\r\n#define _FOOBAR2000_HELPERS_WIN32_DIALOG_H_\r\n\r\n\r\nnamespace dialog_helper\r\n{\r\n\tclass dialog\r\n\t{\r\n\tprotected:\r\n\t\t\r\n\t\tdialog() : wnd(0), m_is_modal(false) {}\r\n\t\t~dialog() { }\r\n\r\n\t\tvirtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0;\r\n\r\n\t\tvoid end_dialog(int code);\r\n\r\n\tpublic:\r\n\t\tinline HWND get_wnd() {return wnd;}\r\n\r\n\t\tint run_modal(unsigned id,HWND parent);\r\n\r\n\t\tHWND run_modeless(unsigned id,HWND parent);\r\n\tprivate:\r\n\t\tHWND wnd;\r\n\t\tstatic INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp);\r\n\r\n\t\tbool m_is_modal;\r\n\r\n\t\tmodal_dialog_scope m_modal_scope;\r\n\t};\r\n\r\n\r\n\t//! This class is meant to be instantiated on-stack, as a local variable. Using new/delete operators instead or even making this a member of another object works, but does not make much sense because of the way this works (single run() call).\r\n\tclass dialog_modal\r\n\t{\r\n\tpublic:\r\n\t\tint run(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance());\r\n\tprotected:\r\n\t\tvirtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0;\r\n\r\n\t\tinline dialog_modal() : m_wnd(0) {}\r\n\t\tvoid end_dialog(int p_code);\r\n\t\tinline HWND get_wnd() const {return m_wnd;}\r\n\tprivate:\r\n\t\tstatic INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp);\r\n\r\n\t\tHWND m_wnd;\r\n\t\tmodal_dialog_scope m_modal_scope;\r\n\t};\r\n\r\n\r\n\t//! This class is meant to be used with new/delete operators only. Destroying the window - outside create() / WM_INITDIALOG - will result in object calling delete this. If object is deleted directly using delete operator, WM_DESTROY handler may not be called so it should not be used (use destructor of derived class instead).\r\n\t//! Classes derived from dialog_modeless must not be instantiated in any other way than operator new().\r\n\t/*! Typical usage : \\n\r\n\tclass mydialog : public dialog_helper::dialog_modeless {...};\r\n\t(...)\r\n\tbool createmydialog()\r\n\t{\r\n\t\tmydialog * instance = new mydialog;\r\n\t\tif (instance == 0) return flase;\r\n\t\tif (!instance->create(...)) {delete instance; return false;}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t*/\r\n\tclass dialog_modeless\r\n\t{\r\n\tpublic:\r\n\t\t//! Creates the dialog window. This will call on_message with WM_INITDIALOG. To abort creation, you can call DestroyWindow() on our window; it will not delete the object but make create() return false instead. You should not delete the object from inside WM_INITDIALOG handler or anything else possibly called from create().\r\n\t\t//! @returns true on success, false on failure.\r\n\t\tbool create(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance());\r\n\tprotected:\r\n\t\t//! Standard windows message handler (DialogProc-style). Use get_wnd() to retrieve our dialog window handle.\r\n\t\tvirtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp)=0;\r\n\r\n\t\tinline dialog_modeless() : m_wnd(0), m_destructor_status(destructor_none), m_is_in_create(false) {}\r\n\t\tinline HWND get_wnd() const {return m_wnd;}\r\n\t\tvirtual ~dialog_modeless();\r\n\tprivate:\r\n\t\tstatic INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp);\r\n\t\tvoid on_window_destruction();\r\n\t\t\r\n\t\tBOOL on_message_wrap(UINT msg,WPARAM wp,LPARAM lp);\r\n\r\n\t\tHWND m_wnd;\r\n\t\tenum {destructor_none,destructor_normal,destructor_fromwindow} m_destructor_status;\r\n\t\tbool m_is_in_create;\r\n\t};\r\n\r\n#pragma deprecated(dialog_modeless)\r\n\r\n\r\n\r\n\tclass dialog_modeless_v2\r\n\t{\r\n\tprotected:\r\n\t\texplicit dialog_modeless_v2(unsigned p_id,HWND p_parent,HINSTANCE p_instance = core_api::get_my_instance(),bool p_stealfocus = true);\r\n\t\tvirtual ~dialog_modeless_v2();\r\n\t\tHWND get_wnd() const {return m_wnd;}\r\n\t\tvirtual BOOL on_message(UINT msg,WPARAM wp,LPARAM lp) {return FALSE;}\r\n\r\n\t\tstatic dialog_modeless_v2 * __unsafe__instance_from_window(HWND p_wnd) {return reinterpret_cast<dialog_modeless_v2*>(GetWindowLongPtr(p_wnd,DWLP_USER));}\r\n\tprivate:\r\n\t\tstatic INT_PTR CALLBACK DlgProc(HWND wnd,UINT msg,WPARAM wp,LPARAM lp);\r\n\t\tvoid detach_window();\r\n\t\tBOOL on_message_internal(UINT msg,WPARAM wp,LPARAM lp);\r\n\t\tenum {status_construction, status_lifetime, status_destruction_requested, status_destruction} m_status;\r\n\t\tHWND m_wnd;\r\n\t\tconst bool m_stealfocus;\r\n\r\n\t\tconst dialog_modeless_v2 & operator=(const dialog_modeless_v2 &);\r\n\t\tdialog_modeless_v2(const dialog_modeless_v2 &);\r\n\t};\r\n\r\n\r\n};\r\n\r\n\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/win32_misc.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nvoid registerclass_scope_delayed::toggle_on(UINT p_style,WNDPROC p_wndproc,int p_clsextra,int p_wndextra,HICON p_icon,HCURSOR p_cursor,HBRUSH p_background,const TCHAR * p_class_name,const TCHAR * p_menu_name) {\r\n\ttoggle_off();\r\n\tWNDCLASS wc;\r\n\tmemset(&wc,0,sizeof(wc));\r\n\twc.style = p_style;\r\n\twc.lpfnWndProc = p_wndproc;\r\n\twc.cbClsExtra = p_clsextra;\r\n\twc.cbWndExtra = p_wndextra;\r\n\twc.hInstance = core_api::get_my_instance();\r\n\twc.hIcon = p_icon;\r\n\twc.hCursor = p_cursor;\r\n\twc.hbrBackground = p_background;\r\n\twc.lpszMenuName = p_menu_name;\r\n\twc.lpszClassName = p_class_name;\r\n\tSetLastError(NO_ERROR);\r\n\tm_class = RegisterClass(&wc);\r\n\tif (m_class == 0) throw ::exception_win32(GetLastError());\r\n}\r\n\r\nvoid registerclass_scope_delayed::toggle_off() {\r\n\tif (m_class != 0) {\r\n\t\tUnregisterClass((LPCTSTR)m_class,core_api::get_my_instance());\r\n\t\tm_class = 0;\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\tclass clipboard_scope {\r\n\tpublic:\r\n\t\tclipboard_scope() : m_open(false) {}\r\n\t\t~clipboard_scope() {close();}\r\n\t\tbool open(HWND p_owner) {\r\n\t\t\tclose();\r\n\t\t\tif (OpenClipboard(p_owner) == TRUE) {\r\n\t\t\t\tm_open = true;\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid close() {\r\n\t\t\tif (m_open) {\r\n\t\t\t\tm_open = false;\r\n\t\t\t\tCloseClipboard();\r\n\t\t\t}\r\n\t\t}\r\n\tprivate:\r\n\t\tbool m_open;\r\n\t};\r\n};\r\nbool uGetClipboardString(pfc::string_base & p_out) {\r\n\tclipboard_scope scope;\r\n\tif (!scope.open(NULL)) return false;\r\n\tHANDLE data = GetClipboardData(\r\n#ifdef UNICODE\r\n\t\tCF_UNICODETEXT\r\n#else\r\n\t\tCF_TEXT\r\n#endif\r\n\t\t);\r\n\tif (data == NULL) return false;\r\n\r\n\tCGlobalLock lock(data);\r\n\tp_out = pfc::stringcvt::string_utf8_from_os( (const TCHAR*) lock.GetPtr(), lock.GetSize() / sizeof(TCHAR) );\r\n\treturn true;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/win32_misc.h",
    "content": "class registerclass_scope_delayed {\r\npublic:\r\n\tregisterclass_scope_delayed() : m_class(0) {}\r\n\r\n\tbool is_registered() const {return m_class != 0;}\r\n\tvoid toggle_on(UINT p_style,WNDPROC p_wndproc,int p_clsextra,int p_wndextra,HICON p_icon,HCURSOR p_cursor,HBRUSH p_background,const TCHAR * p_classname,const TCHAR * p_menuname);\r\n\tvoid toggle_off();\r\n\tATOM get_class() const {return m_class;}\r\n\r\n\t~registerclass_scope_delayed() {toggle_off();}\r\nprivate:\r\n\tregisterclass_scope_delayed(const registerclass_scope_delayed &) {throw pfc::exception_not_implemented();}\r\n\tconst registerclass_scope_delayed & operator=(const registerclass_scope_delayed &) {throw pfc::exception_not_implemented();}\r\n\r\n\tATOM m_class;\r\n};\r\n\r\n\r\n\r\ntemplate<typename t_object>\r\nclass syncd_storage {\r\nprivate:\r\n\ttypedef syncd_storage<t_object> t_self;\r\npublic:\r\n\tsyncd_storage() {}\r\n\ttemplate<typename t_source>\r\n\tsyncd_storage(const t_source & p_source) : m_object(p_source) {}\r\n\ttemplate<typename t_source>\r\n\tvoid set(t_source const & p_in) {\r\n\t\tinsync(m_sync);\r\n\t\tm_object = p_in;\r\n\t}\r\n\ttemplate<typename t_destination>\r\n\tvoid get(t_destination & p_out) const {\r\n\t\tinsync(m_sync);\r\n\t\tp_out = m_object;\r\n\t}\r\n\tt_object get() const {\r\n\t\tinsync(m_sync);\r\n\t\treturn m_object;\r\n\t}\r\n\ttemplate<typename t_source>\r\n\tconst t_self & operator=(t_source const & p_source) {set(p_source); return *this;}\r\nprivate:\r\n\tmutable critical_section m_sync;\r\n\tt_object m_object;\r\n};\r\n\r\ntemplate<typename t_object>\r\nclass syncd_storage_flagged {\r\nprivate:\r\n\ttypedef syncd_storage_flagged<t_object> t_self;\r\npublic:\r\n\tsyncd_storage_flagged() : m_changed_flag(false) {}\r\n\ttemplate<typename t_source>\r\n\tsyncd_storage_flagged(const t_source & p_source) : m_changed_flag(false), m_object(p_source) {}\r\n\tvoid set_changed(bool p_flag = true) {\r\n\t\tinsync(m_sync); \r\n\t\tm_changed_flag = p_flag;\r\n\t}\r\n\ttemplate<typename t_source>\r\n\tvoid set(t_source const & p_in) {\r\n\t\tinsync(m_sync);\r\n\t\tm_object = p_in;\r\n\t\tm_changed_flag = true;\r\n\t}\r\n\tbool has_changed() const {\r\n\t\tinsync(m_sync); \r\n\t\treturn m_changed_flag;\r\n\t}\r\n\tt_object peek() const {insync(m_sync); return m_object;}\r\n\ttemplate<typename t_destination>\r\n\tbool get_if_changed(t_destination & p_out) {\r\n\t\tinsync(m_sync);\r\n\t\tif (m_changed_flag) {\r\n\t\t\tp_out = m_object;\r\n\t\t\tm_changed_flag = false;\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\tt_object get() {\r\n\t\tinsync(m_sync);\r\n\t\tm_changed_flag = false;\r\n\t\treturn m_object;\r\n\t}\r\n\ttemplate<typename t_destination>\r\n\tvoid get(t_destination & p_out) {\r\n\t\tinsync(m_sync);\r\n\t\tp_out = m_object;\r\n\t\tm_changed_flag = false;\r\n\t}\r\n\ttemplate<typename t_source>\r\n\tconst t_self & operator=(t_source const & p_source) {set(p_source); return *this;}\r\nprivate:\r\n\tbool m_changed_flag;\r\n\tmutable critical_section m_sync;\r\n\tt_object m_object;\r\n};\r\n\r\nclass CGlobalLock {\r\npublic:\r\n\tCGlobalLock(HGLOBAL p_handle) : m_handle(p_handle), m_ptr(GlobalLock(p_handle)) {}\r\n\t~CGlobalLock() {\r\n\t\tif (m_ptr != NULL) GlobalUnlock(m_handle);\r\n\t}\r\n\tvoid * GetPtr() const {return m_ptr;}\r\n\tt_size GetSize() const {return GlobalSize(m_handle);}\r\nprivate:\r\n\tvoid * m_ptr;\r\n\tHGLOBAL m_handle;\r\n};\r\n\r\nbool uGetClipboardString(pfc::string_base & p_out);\r\n\r\n\r\n\r\n#ifdef __ATLWIN_H__\r\n\r\nclass CMenuSelectionReceiver : public CWindowImpl<CMenuSelectionReceiver> {\r\npublic:\r\n\tCMenuSelectionReceiver(HWND p_parent) {\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tif (Create(p_parent) == NULL) throw exception_win32(GetLastError());\r\n\t}\r\n\t~CMenuSelectionReceiver() {\r\n\t\tDestroyWindow();\r\n\t}\r\n\ttypedef CWindowImpl<CMenuSelectionReceiver> _baseClass;\r\n\tDECLARE_WND_CLASS_EX(TEXT(\"{DF0087DB-E765-4283-BBAB-6AB2E8AB64A1}\"),0,0);\r\n\r\n\tBEGIN_MSG_MAP(CMenuSelectionReceiver)\r\n\t\tMESSAGE_HANDLER(WM_MENUSELECT,OnMenuSelect)\r\n\tEND_MSG_MAP()\r\nprotected:\r\n\tvirtual bool QueryHint(unsigned p_id,pfc::string_base & p_out) {\r\n\t\treturn false;\r\n\t}\r\nprivate:\r\n\tLRESULT OnMenuSelect(UINT,WPARAM p_wp,LPARAM p_lp,BOOL&) {\r\n\t\tif (p_lp != 0) {\r\n\t\t\tif (HIWORD(p_wp) & MF_POPUP) {\r\n\t\t\t\tm_status.release();\r\n\t\t\t} else {\r\n\t\t\t\tpfc::string8 msg;\r\n\t\t\t\tif (!QueryHint(LOWORD(p_wp),msg)) {\r\n\t\t\t\t\tm_status.release();\r\n\t\t\t\t} else {\r\n\t\t\t\t\tif (m_status.is_empty()) {\r\n\t\t\t\t\t\tif (!static_api_ptr_t<ui_control>()->override_status_text_create(m_status)) m_status.release();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (m_status.is_valid()) {\r\n\t\t\t\t\t\tm_status->override_text(msg);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tm_status.release();\r\n\t\t}\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tservice_ptr_t<ui_status_text_override> m_status;\r\n\r\n\tPFC_CLASS_NOT_COPYABLE(CMenuSelectionReceiver,CMenuSelectionReceiver);\r\n};\r\n#endif //#ifdef __ATLWIN_H__\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/window_placement_helper.cpp",
    "content": "#include \"stdafx.h\"\r\n\r\nstatic bool g_is_enabled()\r\n{\r\n\treturn standard_config_objects::query_remember_window_positions();\r\n}\r\n\r\nstatic BOOL CALLBACK __MonitorEnumProc(\r\n  HMONITOR hMonitor,  // handle to display monitor\r\n  HDC hdcMonitor,     // handle to monitor DC\r\n  LPRECT lprcMonitor, // monitor intersection rectangle\r\n  LPARAM dwData       // data\r\n  ) {\r\n\tRECT * clip = (RECT*)dwData;\r\n\tRECT newclip;\r\n\tUnionRect(&newclip,clip,lprcMonitor);\r\n\t*clip = newclip;\r\n\treturn TRUE;\r\n}\r\n\r\nstatic bool test_rect(const RECT * rc) {\r\n\tRECT clip = {};\r\n\tif (EnumDisplayMonitors(NULL,NULL,__MonitorEnumProc,(LPARAM)&clip)) {\r\n\t\tconst LONG sanitycheck = 4;\r\n\t\tconst LONG cwidth = clip.right - clip.left;\r\n\t\tconst LONG cheight = clip.bottom - clip.top;\r\n\t\t\r\n\t\tconst LONG width = rc->right - rc->left;\r\n\t\tconst LONG height = rc->bottom - rc->top;\r\n\r\n\t\tif (width > cwidth * sanitycheck || height > cheight * sanitycheck) return false;\r\n\t}\r\n\t\r\n\treturn MonitorFromRect(rc,MONITOR_DEFAULTTONULL) != NULL;\r\n}\r\n\r\n\r\n\r\nbool cfg_window_placement::read_from_window(HWND window)\r\n{\r\n\tWINDOWPLACEMENT wp;\r\n\tmemset(&wp,0,sizeof(wp));\r\n\tif (g_is_enabled())\r\n\t{\r\n\t\twp.length = sizeof(wp);\r\n\t\tif (!GetWindowPlacement(window,&wp))\r\n\t\t\tmemset(&wp,0,sizeof(wp));\r\n\t\t/*else\r\n\t\t{\r\n\t\t\tif (!IsWindowVisible(window)) wp.showCmd = SW_HIDE;\r\n\t\t}*/\r\n\t}\r\n\tm_data = wp;\r\n\treturn m_data.length == sizeof(m_data);\r\n}\r\n\r\nbool cfg_window_placement::on_window_creation(HWND window)\r\n{\r\n\tbool ret = false;\r\n\tPFC_ASSERT(!m_windows.have_item(window));\r\n\tm_windows.add_item(window);\r\n\r\n\tif (g_is_enabled())\r\n\t{\r\n\t\tif (m_data.length==sizeof(m_data) && test_rect(&m_data.rcNormalPosition))\r\n\t\t{\r\n\t\t\tif (SetWindowPlacement(window,&m_data))\r\n\t\t\t{\r\n\t\t\t\tret = true;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\treturn ret;\r\n}\r\n\r\n\r\nvoid cfg_window_placement::on_window_destruction(HWND window)\r\n{\r\n\tif (m_windows.have_item(window))\r\n\t{\r\n\t\tread_from_window(window);\r\n\t\tm_windows.remove_item(window);\r\n\t}\r\n}\r\n\r\nvoid cfg_window_placement::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\tif (g_is_enabled()) {\r\n\t\t{\r\n\t\t\tt_size n, m = m_windows.get_count();\r\n\t\t\tfor(n=0;n<m;n++) {\r\n\t\t\t\tHWND window = m_windows[n];\r\n\t\t\t\tPFC_ASSERT(IsWindow(window));\r\n\t\t\t\tif (IsWindow(window) && read_from_window(window)) break;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (m_data.length == sizeof(m_data)) {\r\n\t\t\tp_stream->write_object(&m_data,sizeof(m_data),p_abort);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid cfg_window_placement::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\tWINDOWPLACEMENT temp;\r\n\ttry {\r\n\t\tp_stream->read_object(&temp,sizeof(temp),p_abort);\r\n\t} catch(exception_io_data const &) {return;}\r\n\tif (temp.length == sizeof(temp)) m_data = temp;\r\n}\r\n\r\n\r\ncfg_window_placement::cfg_window_placement(const GUID & p_guid) : cfg_var(p_guid)\r\n{\r\n\tmemset(&m_data,0,sizeof(m_data));\r\n}\r\n\r\n\r\ncfg_window_size::cfg_window_size(const GUID & p_guid) : cfg_var(p_guid), m_width(infinite32), m_height(infinite32) {}\r\n\r\nstatic BOOL SetWindowSize(HWND p_wnd,unsigned p_x,unsigned p_y)\r\n{\r\n\tif (p_x != infinite32 && p_y != infinite32)\r\n\t\treturn SetWindowPos(p_wnd,0,0,0,p_x,p_y,SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOZORDER);\r\n\telse\r\n\t\treturn FALSE;\r\n}\r\n\r\nbool cfg_window_size::on_window_creation(HWND p_wnd)\r\n{\r\n\tbool ret = false;\r\n\tPFC_ASSERT(!m_windows.have_item(p_wnd));\r\n\tm_windows.add_item(p_wnd);\r\n\r\n\tif (g_is_enabled())\r\n\t{\r\n\t\tif (SetWindowSize(p_wnd,m_width,m_height)) ret = true;\r\n\t}\r\n\r\n\treturn ret;\r\n}\r\n\r\nvoid cfg_window_size::on_window_destruction(HWND p_wnd)\r\n{\r\n\tif (m_windows.have_item(p_wnd))\r\n\t{\r\n\t\tread_from_window(p_wnd);\r\n\t\tm_windows.remove_item(p_wnd);\r\n\t}\r\n}\r\n\r\nbool cfg_window_size::read_from_window(HWND p_wnd)\r\n{\r\n\tif (g_is_enabled())\r\n\t{\r\n\t\tRECT r;\r\n\t\tif (GetWindowRect(p_wnd,&r))\r\n\t\t{\r\n\t\t\tm_width = r.right - r.left;\r\n\t\t\tm_height = r.bottom - r.top;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_width = m_height = infinite32;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_width = m_height = infinite32;\r\n\t\treturn false;\r\n\t}\r\n}\r\n\r\nvoid cfg_window_size::get_data_raw(stream_writer * p_stream,abort_callback & p_abort) {\r\n\tif (g_is_enabled())  {\r\n\t\t{\r\n\t\t\tt_size n, m = m_windows.get_count();\r\n\t\t\tfor(n=0;n<m;n++) {\r\n\t\t\t\tHWND window = m_windows[n];\r\n\t\t\t\tPFC_ASSERT(IsWindow(window));\r\n\t\t\t\tif (IsWindow(window) && read_from_window(window)) break;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (m_width != infinite32 && m_height != infinite32) {\r\n\t\t\tp_stream->write_lendian_t(m_width,p_abort);\r\n\t\t\tp_stream->write_lendian_t(m_height,p_abort);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid cfg_window_size::set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort) {\r\n\tt_uint32 width,height;\r\n\ttry {\r\n\t\tp_stream->read_lendian_t(width,p_abort);\r\n\t\tp_stream->read_lendian_t(height,p_abort);\r\n\t} catch(exception_io_data const &) {return;}\r\n\r\n\tm_width = width; m_height = height;\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/helpers/window_placement_helper.h",
    "content": "#ifndef _WINDOW_PLACEMENT_HELPER_H_\r\n#define _WINDOW_PLACEMENT_HELPER_H_\r\n\r\nclass cfg_window_placement : public cfg_var\r\n{\r\npublic:\r\n\tbool on_window_creation(HWND window);//returns true if window position has been changed, false if not\r\n\tvoid on_window_destruction(HWND window);\r\n\tbool read_from_window(HWND window);\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort);\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort);\r\n\tcfg_window_placement(const GUID & p_guid);\r\nprivate:\r\n\tpfc::list_hybrid_t<HWND,2> m_windows;\r\n\tWINDOWPLACEMENT m_data;\r\n};\r\n\r\nclass cfg_window_size : public cfg_var\r\n{\r\npublic:\r\n\tbool on_window_creation(HWND window);//returns true if window position has been changed, false if not\r\n\tvoid on_window_destruction(HWND window);\r\n\tbool read_from_window(HWND window);\r\n\tvoid get_data_raw(stream_writer * p_stream,abort_callback & p_abort);\r\n\tvoid set_data_raw(stream_reader * p_stream,t_size p_sizehint,abort_callback & p_abort);\r\n\tcfg_window_size(const GUID & p_guid);\r\nprivate:\r\n\tpfc::list_hybrid_t<HWND,2> m_windows;\r\n\tt_uint32 m_width,m_height;\r\n};\r\n\r\n\r\n#endif //_WINDOW_PLACEMENT_HELPER_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/shared/audio_math.h",
    "content": "#include <math.h>\r\n\r\n#ifdef _M_X64\r\n#include <xmmintrin.h>\r\n#include <emmintrin.h>\r\n#endif\r\n\r\n\r\n#define audio_sample_size 32\r\n\r\n#if audio_sample_size == 32\r\ntypedef float audio_sample;\r\n#define audio_sample_asm dword\r\n#elif audio_sample_size == 64\r\ntypedef double audio_sample;\r\n#define audio_sample_asm qword\r\n#else\r\n#error wrong audio_sample_size\r\n#endif\r\n\r\n#define audio_sample_bytes (audio_sample_size/8)\r\n\r\nnamespace audio_math\r\n{\r\n\t//! p_source/p_output can point to same buffer\r\n\tvoid SHARED_EXPORT scale(const audio_sample * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale);\r\n\tvoid SHARED_EXPORT convert_to_int16(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale);\r\n\tvoid SHARED_EXPORT convert_to_int32(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale);\r\n\taudio_sample SHARED_EXPORT convert_to_int16_calculate_peak(const audio_sample * p_source,t_size p_count,t_int16 * p_output,audio_sample p_scale);\r\n\tvoid SHARED_EXPORT convert_from_int16(const t_int16 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale);\r\n\tvoid SHARED_EXPORT convert_from_int32(const t_int32 * p_source,t_size p_count,audio_sample * p_output,audio_sample p_scale);\r\n\taudio_sample SHARED_EXPORT convert_to_int32_calculate_peak(const audio_sample * p_source,t_size p_count,t_int32 * p_output,audio_sample p_scale);\r\n\taudio_sample SHARED_EXPORT calculate_peak(const audio_sample * p_source,t_size p_count);\r\n\tvoid SHARED_EXPORT remove_denormals(audio_sample * p_buffer,t_size p_count);\r\n\tvoid SHARED_EXPORT add_offset(audio_sample * p_buffer,audio_sample p_delta,t_size p_count);\r\n\r\n\t\r\n\tinline t_uint64 time_to_samples(double p_time,t_uint32 p_sample_rate) {\r\n\t\treturn (t_uint64)floor((double)p_sample_rate * p_time + 0.5);\r\n\t}\r\n\r\n\tinline double samples_to_time(t_uint64 p_samples,t_uint32 p_sample_rate) {\r\n\t\tPFC_ASSERT(p_sample_rate > 0);\r\n\t\treturn (double) p_samples / (double) p_sample_rate;\r\n\t}\r\n\r\n\r\n#ifdef _M_IX86\r\n\tinline static t_int64 rint64(audio_sample val) {\r\n\t\tt_int64 rv;\r\n\t\t_asm {\r\n\t\t\tfld val;\r\n\t\t\tfistp rv;\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\n\tinline static t_int32 rint32(audio_sample val) {\r\n\t\tt_int32 rv; \r\n\t\t_asm {\r\n\t\t\tfld val;\r\n\t\t\tfistp rv;\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\n#elif defined(_M_X64)\r\n\tinline static t_int64 rint64(audio_sample val) {return (t_int64)floor(val+0.5);}\r\n\tstatic inline t_int32 rint32(float p_val) {\r\n\t\treturn (t_int32)_mm_cvtss_si32(_mm_load_ss(&p_val));\r\n\t}\r\n#else\r\n\tinline static t_int64 rint64(audio_sample val) {return (t_int64)floor(val+0.5);}\r\n\tinline static t_int32 rint32(audio_sample val) {return (t_int32)floor(val+0.5);}\r\n#endif\r\n\r\n\r\n\tinline audio_sample gain_to_scale(double p_gain) {return (audio_sample) pow(10.0,p_gain / 20.0);}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/shared/shared.h",
    "content": "#ifndef _SHARED_DLL__SHARED_H_\r\n#define _SHARED_DLL__SHARED_H_\r\n\r\n#include \"../../pfc/pfc.h\"\r\n\r\n#ifndef WIN32\r\n#error N/A\r\n#endif\r\n\r\n#ifndef STRICT\r\n#define STRICT\r\n#endif\r\n\r\n#include <windows.h>\r\n#include <ddeml.h>\r\n#include <commctrl.h>\r\n\r\n#ifndef NOTHROW\r\n#ifdef _MSC_VER\r\n#define NOTHROW __declspec(nothrow)\r\n#else\r\n#define NOTHROW\r\n#endif\r\n#endif\r\n\r\n#define SHARED_API /*NOTHROW*/ __stdcall\r\n\r\n#ifndef SHARED_EXPORTS\r\n#define SHARED_EXPORT __declspec(dllimport) SHARED_API\r\n#else\r\n#define SHARED_EXPORT __declspec(dllexport) SHARED_API\r\n#endif\r\n\r\nextern \"C\" {\r\n\r\n//SHARED_EXPORT BOOL IsUnicode();\r\n#ifdef UNICODE\r\n#define IsUnicode() 1\r\n#else\r\n#define IsUnicode() 0\r\n#endif\r\n\r\nLRESULT SHARED_EXPORT uSendMessageText(HWND wnd,UINT msg,WPARAM wp,const char * text);\r\nLRESULT SHARED_EXPORT uSendDlgItemMessageText(HWND wnd,UINT id,UINT msg,WPARAM wp,const char * text);\r\nBOOL SHARED_EXPORT uGetWindowText(HWND wnd,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uSetWindowText(HWND wnd,const char * p_text);\r\nBOOL SHARED_EXPORT uSetWindowTextEx(HWND wnd,const char * p_text,unsigned p_text_length);\r\nBOOL SHARED_EXPORT uGetDlgItemText(HWND wnd,UINT id,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uSetDlgItemText(HWND wnd,UINT id,const char * p_text);\r\nBOOL SHARED_EXPORT uSetDlgItemTextEx(HWND wnd,UINT id,const char * p_text,unsigned p_text_length);\r\nBOOL SHARED_EXPORT uBrowseForFolder(HWND parent,const char * title,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uBrowseForFolderWithFile(HWND parent,const char * title,pfc::string_base & out,const char * p_file_to_find);\r\nint SHARED_EXPORT uMessageBox(HWND wnd,const char * text,const char * caption,UINT type);\r\nvoid SHARED_EXPORT uOutputDebugString(const char * msg);\r\nBOOL SHARED_EXPORT uAppendMenu(HMENU menu,UINT flags,UINT_PTR id,const char * content);\r\nBOOL SHARED_EXPORT uInsertMenu(HMENU menu,UINT position,UINT flags,UINT_PTR id,const char * content);\r\nint SHARED_EXPORT uStringCompare(const char * elem1, const char * elem2);\r\nint SHARED_EXPORT uCharCompare(t_uint32 p_char1,t_uint32 p_char2);\r\nint SHARED_EXPORT uStringCompare_ConvertNumbers(const char * elem1,const char * elem2);\r\nHINSTANCE SHARED_EXPORT uLoadLibrary(const char * name);\r\nHANDLE SHARED_EXPORT uCreateEvent(LPSECURITY_ATTRIBUTES lpEventAttributes,BOOL bManualReset,BOOL bInitialState, const char * lpName);\r\nDWORD SHARED_EXPORT uGetModuleFileName(HMODULE hMod,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uSetClipboardString(const char * ptr);\r\nBOOL SHARED_EXPORT uIsDialogMessage(HWND dlg,LPMSG msg);\r\nBOOL SHARED_EXPORT uGetMessage(LPMSG msg,HWND wnd,UINT min,UINT max);\r\nBOOL SHARED_EXPORT uGetClassName(HWND wnd,pfc::string_base & out);\r\nt_size SHARED_EXPORT uCharLength(const char * src);\r\nBOOL SHARED_EXPORT uDragQueryFile(HDROP hDrop,UINT idx,pfc::string_base & out);\r\nUINT SHARED_EXPORT uDragQueryFileCount(HDROP hDrop);\r\nBOOL SHARED_EXPORT uGetTextExtentPoint32(HDC dc,const char * text,UINT cb,LPSIZE size);//note, cb is number of bytes, not actual unicode characters in the string (read: plain strlen() will do)\r\nBOOL SHARED_EXPORT uExtTextOut(HDC dc,int x,int y,UINT flags,const RECT * rect,const char * text,UINT cb,const int * lpdx);\r\nBOOL SHARED_EXPORT uTextOutColors(HDC dc,const char * src,UINT len,int x,int y,const RECT * clip,BOOL is_selected,DWORD default_color);\r\nBOOL SHARED_EXPORT uTextOutColorsTabbed(HDC dc,const char * src,UINT src_len,const RECT * item,int border,const RECT * clip,BOOL selected,DWORD default_color,BOOL use_columns);\r\nUINT SHARED_EXPORT uGetTextHeight(HDC dc);\r\nUINT SHARED_EXPORT uGetFontHeight(HFONT font);\r\nBOOL SHARED_EXPORT uChooseColor(DWORD * p_color,HWND parent,DWORD * p_custom_colors);\r\nHCURSOR SHARED_EXPORT uLoadCursor(HINSTANCE hIns,const char * name);\r\nHICON SHARED_EXPORT uLoadIcon(HINSTANCE hIns,const char * name);\r\nHMENU SHARED_EXPORT uLoadMenu(HINSTANCE hIns,const char * name);\r\nBOOL SHARED_EXPORT uGetEnvironmentVariable(const char * name,pfc::string_base & out);\r\nHMODULE SHARED_EXPORT uGetModuleHandle(const char * name);\r\nUINT SHARED_EXPORT uRegisterWindowMessage(const char * name);\r\nBOOL SHARED_EXPORT uMoveFile(const char * src,const char * dst);\r\nBOOL SHARED_EXPORT uDeleteFile(const char * fn);\r\nDWORD SHARED_EXPORT uGetFileAttributes(const char * fn);\r\nBOOL SHARED_EXPORT uFileExists(const char * fn);\r\nBOOL SHARED_EXPORT uRemoveDirectory(const char * fn);\r\nHANDLE SHARED_EXPORT uCreateFile(const char * p_path,DWORD p_access,DWORD p_sharemode,LPSECURITY_ATTRIBUTES p_security_attributes,DWORD p_createmode,DWORD p_flags,HANDLE p_template);\r\nHANDLE SHARED_EXPORT uCreateFileMapping(HANDLE hFile,LPSECURITY_ATTRIBUTES lpFileMappingAttributes,DWORD flProtect,DWORD dwMaximumSizeHigh,DWORD dwMaximumSizeLow,const char * lpName);\r\nBOOL SHARED_EXPORT uCreateDirectory(const char * fn,LPSECURITY_ATTRIBUTES blah);\r\nHANDLE SHARED_EXPORT uCreateMutex(LPSECURITY_ATTRIBUTES blah,BOOL bInitialOwner,const char * name);\r\nBOOL SHARED_EXPORT uGetLongPathName(const char * name,pfc::string_base & out);//may just fail to work on old windows versions, present on win98/win2k+\r\nBOOL SHARED_EXPORT uGetFullPathName(const char * name,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uSearchPath(const char * path, const char * filename, const char * extension, pfc::string_base & p_out);\r\nBOOL SHARED_EXPORT uFixPathCaps(const char * path,pfc::string_base & p_out);\r\nvoid SHARED_EXPORT uGetCommandLine(pfc::string_base & out);\r\nBOOL SHARED_EXPORT uGetTempPath(pfc::string_base & out);\r\nBOOL SHARED_EXPORT uGetTempFileName(const char * path_name,const char * prefix,UINT unique,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uGetOpenFileName(HWND parent,const char * p_ext_mask,unsigned def_ext_mask,const char * p_def_ext,const char * p_title,const char * p_directory,pfc::string_base & p_filename,BOOL b_save);\r\n//note: uGetOpenFileName extension mask uses | as separator, not null\r\nHANDLE SHARED_EXPORT uLoadImage(HINSTANCE hIns,const char * name,UINT type,int x,int y,UINT flags);\r\nUINT SHARED_EXPORT uRegisterClipboardFormat(const char * name);\r\nBOOL SHARED_EXPORT uGetClipboardFormatName(UINT format,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uFormatSystemErrorMessage(pfc::string_base & p_out,DWORD p_code);\r\n\r\nHANDLE SHARED_EXPORT uSortStringCreate(const char * src);\r\nint SHARED_EXPORT uSortStringCompare(HANDLE string1,HANDLE string2);\r\nint SHARED_EXPORT uSortStringCompareEx(HANDLE string1,HANDLE string2,DWORD flags);//flags - see win32 CompareString\r\nint SHARED_EXPORT uSortPathCompare(HANDLE string1,HANDLE string2);\r\nvoid SHARED_EXPORT uSortStringFree(HANDLE string);\r\n\r\n\r\nint SHARED_EXPORT uCompareString(DWORD flags,const char * str1,unsigned len1,const char * str2,unsigned len2);\r\n\r\nclass NOVTABLE uGetOpenFileNameMultiResult : public pfc::list_base_const_t<const char*>\r\n{\r\npublic:\r\n\tinline t_size GetCount() {return get_count();}\r\n\tinline const char * GetFileName(t_size index) {return get_item(index);}\r\n\tvirtual ~uGetOpenFileNameMultiResult() {}\r\n};\r\n\r\ntypedef uGetOpenFileNameMultiResult * puGetOpenFileNameMultiResult;\r\n\r\npuGetOpenFileNameMultiResult SHARED_EXPORT uGetOpenFileNameMulti(HWND parent,const char * p_ext_mask,unsigned def_ext_mask,const char * p_def_ext,const char * p_title,const char * p_directory);\r\n\r\nclass NOVTABLE uFindFile\r\n{\r\nprotected:\r\n\tuFindFile() {}\r\npublic:\r\n\tvirtual BOOL FindNext()=0;\r\n\tvirtual const char * GetFileName()=0;\r\n\tvirtual t_uint64 GetFileSize()=0;\r\n\tvirtual DWORD GetAttributes()=0;\r\n\tvirtual FILETIME GetCreationTime()=0;\r\n\tvirtual FILETIME GetLastAccessTime()=0;\r\n\tvirtual FILETIME GetLastWriteTime()=0;\r\n\tvirtual ~uFindFile() {};\r\n\tinline bool IsDirectory() {return (GetAttributes() & FILE_ATTRIBUTE_DIRECTORY) ? true : false;}\r\n};\r\n\r\ntypedef uFindFile * puFindFile;\r\n\r\npuFindFile SHARED_EXPORT uFindFirstFile(const char * path);\r\n\r\nHINSTANCE SHARED_EXPORT uShellExecute(HWND wnd,const char * oper,const char * file,const char * params,const char * dir,int cmd);\r\nHWND SHARED_EXPORT uCreateStatusWindow(LONG style,const char * text,HWND parent,UINT id);\r\n\r\nBOOL SHARED_EXPORT uShellNotifyIcon(DWORD dwMessage,HWND wnd,UINT id,UINT callbackmsg,HICON icon,const char * tip);\r\nBOOL SHARED_EXPORT uShellNotifyIconEx(DWORD dwMessage,HWND wnd,UINT id,UINT callbackmsg,HICON icon,const char * tip,const char * balloon_title,const char * balloon_msg);\r\n\r\nHWND SHARED_EXPORT uCreateWindowEx(DWORD dwExStyle,const char * lpClassName,const char * lpWindowName,DWORD dwStyle,int x,int y,int nWidth,int nHeight,HWND hWndParent,HMENU hMenu,HINSTANCE hInstance,LPVOID lpParam);\r\n\r\nBOOL SHARED_EXPORT uGetSystemDirectory(pfc::string_base & out); \r\nBOOL SHARED_EXPORT uGetWindowsDirectory(pfc::string_base & out); \r\nBOOL SHARED_EXPORT uSetCurrentDirectory(const char * path);\r\nBOOL SHARED_EXPORT uGetCurrentDirectory(pfc::string_base & out);\r\nBOOL SHARED_EXPORT uExpandEnvironmentStrings(const char * src,pfc::string_base & out);\r\nBOOL SHARED_EXPORT uGetUserName(pfc::string_base & out);\r\nBOOL SHARED_EXPORT uGetShortPathName(const char * src,pfc::string_base & out);\r\n\r\nHSZ SHARED_EXPORT uDdeCreateStringHandle(DWORD ins,const char * src);\r\nBOOL SHARED_EXPORT uDdeQueryString(DWORD ins,HSZ hsz,pfc::string_base & out);\r\nUINT SHARED_EXPORT uDdeInitialize(LPDWORD pidInst,PFNCALLBACK pfnCallback,DWORD afCmd,DWORD ulRes);\r\nBOOL SHARED_EXPORT uDdeAccessData_Text(HDDEDATA data,pfc::string_base & out);\r\n\r\nHIMAGELIST SHARED_EXPORT uImageList_LoadImage(HINSTANCE hi, const char * lpbmp, int cx, int cGrow, COLORREF crMask, UINT uType, UINT uFlags);\r\n\r\n#define uDdeFreeStringHandle DdeFreeStringHandle\r\n#define uDdeCmpStringHandles DdeCmpStringHandles\r\n#define uDdeKeepStringHandle DdeKeepStringHandle\r\n#define uDdeUninitialize DdeUninitialize\r\n#define uDdeNameService DdeNameService\r\n#define uDdeFreeDataHandle DdeFreeDataHandle\r\n\r\n\r\ntypedef TVINSERTSTRUCTA uTVINSERTSTRUCT;\r\n\r\nHTREEITEM SHARED_EXPORT uTreeView_InsertItem(HWND wnd,const uTVINSERTSTRUCT * param);\r\nLPARAM SHARED_EXPORT uTreeView_GetUserData(HWND wnd,HTREEITEM item);\r\nbool SHARED_EXPORT uTreeView_GetText(HWND wnd,HTREEITEM item,pfc::string_base & out);\r\n\r\n#define uSetWindowsHookEx SetWindowsHookEx\r\n#define uUnhookWindowsHookEx UnhookWindowsHookEx\r\n#define uCallNextHookEx CallNextHookEx\r\n\r\n\r\n/* usage:\r\n\r\n  const char * src = \"something\";\r\n\r\n  void * temp = malloc(uOSStringEstimateSize(src));\r\n  uOSStringConvert(src,temp);\r\n  //now temp contains OS-friendly (TCHAR) version of src\r\n*/\r\n\r\ntypedef TCITEMA uTCITEM;\r\nint SHARED_EXPORT uTabCtrl_InsertItem(HWND wnd,t_size idx,const uTCITEM * item);\r\nint SHARED_EXPORT uTabCtrl_SetItem(HWND wnd,t_size idx,const uTCITEM * item);\r\n\r\nint SHARED_EXPORT uGetKeyNameText(LONG lparam,pfc::string_base & out);\r\n\r\nvoid SHARED_EXPORT uFixAmpersandChars(const char * src,pfc::string_base & out);//for systray\r\nvoid SHARED_EXPORT uFixAmpersandChars_v2(const char * src,pfc::string_base & out);//for other controls\r\n\r\n//deprecated\r\nt_size SHARED_EXPORT uPrintCrashInfo(LPEXCEPTION_POINTERS param,const char * extrainfo,char * out);\r\nenum {uPrintCrashInfo_max_length = 1024};\r\n\r\nvoid SHARED_EXPORT uPrintCrashInfo_Init(const char * name);//called only by exe on startup\r\nvoid SHARED_EXPORT uPrintCrashInfo_AddInfo(const char * p_info);//called only by exe on startup\r\nvoid SHARED_EXPORT uPrintCrashInfo_SetDumpPath(const char * name);//called only by exe on startup\r\n\r\n\r\nvoid SHARED_EXPORT uDumpCrashInfo(LPEXCEPTION_POINTERS param);\r\n\r\nBOOL SHARED_EXPORT uListBox_GetText(HWND listbox,UINT index,pfc::string_base & out);\r\n\r\nvoid SHARED_EXPORT uPrintfV(pfc::string_base & out,const char * fmt,va_list arglist);\r\nstatic inline void uPrintf(pfc::string_base & out,const char * fmt,...) {va_list list;va_start(list,fmt);uPrintfV(out,fmt,list);va_end(list);}\r\n\r\n\r\nclass NOVTABLE uResource\r\n{\r\npublic:\r\n\tvirtual const void * GetPointer() = 0;\r\n\tvirtual unsigned GetSize() = 0;\r\n\tvirtual ~uResource() {}\r\n};\r\n\r\ntypedef uResource* puResource;\r\n\r\npuResource SHARED_EXPORT uLoadResource(HMODULE hMod,const char * name,const char * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) );\r\npuResource SHARED_EXPORT LoadResourceEx(HMODULE hMod,const TCHAR * name,const TCHAR * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) );\r\nHRSRC SHARED_EXPORT uFindResource(HMODULE hMod,const char * name,const char * type,WORD wLang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL) );\r\n\r\nBOOL SHARED_EXPORT uLoadString(HINSTANCE ins,UINT id,pfc::string_base & out);\r\n\r\nUINT SHARED_EXPORT uCharLower(UINT c);\r\nUINT SHARED_EXPORT uCharUpper(UINT c);\r\n\r\nBOOL SHARED_EXPORT uGetMenuString(HMENU menu,UINT id,pfc::string_base & out,UINT flag);\r\nBOOL SHARED_EXPORT uModifyMenu(HMENU menu,UINT id,UINT flags,UINT newitem,const char * data);\r\nUINT SHARED_EXPORT uGetMenuItemType(HMENU menu,UINT position);\r\n\r\n\r\n}//extern \"C\"\r\n\r\ninline char * uCharNext(char * src) {return src+uCharLength(src);}\r\ninline const char * uCharNext(const char * src) {return src+uCharLength(src);}\r\n\r\n\r\nclass string_utf8_from_window\r\n{\r\npublic:\r\n\tstring_utf8_from_window(HWND wnd)\r\n\t{\r\n\t\tuGetWindowText(wnd,m_data);\r\n\t}\r\n\tstring_utf8_from_window(HWND wnd,UINT id)\r\n\t{\r\n\t\tuGetDlgItemText(wnd,id,m_data);\r\n\t}\r\n\tinline operator const char * () const {return m_data.get_ptr();}\r\n\tinline t_size length() const {return m_data.length();}\r\n\tinline bool is_empty() const {return length() == 0;}\r\n\tinline const char * get_ptr() const {return m_data.get_ptr();}\r\nprivate:\r\n\tpfc::string8 m_data;\r\n};\r\n\r\n#define uMAKEINTRESOURCE(x) ((const char*)LOWORD(x))\r\n\r\n#ifdef _DEBUG\r\nclass critical_section {\r\nprivate:\r\n\tCRITICAL_SECTION sec;\r\n\tint count;\r\npublic:\r\n\tint enter() {EnterCriticalSection(&sec);return ++count;}\r\n\tint leave() {int rv = --count;LeaveCriticalSection(&sec);return rv;}\r\n\tint get_lock_count() {return count;}\r\n\tint get_lock_count_check() {enter();return leave();}\r\n\tinline void assert_locked() {assert(get_lock_count_check()>0);}\r\n\tinline void assert_not_locked() {assert(get_lock_count_check()==0);}\r\n\tcritical_section() {InitializeCriticalSection(&sec);count=0;}\r\n\t~critical_section() {DeleteCriticalSection(&sec);}\r\nprivate:\r\n\tcritical_section(const critical_section&) {throw pfc::exception_not_implemented();}\r\n\tconst critical_section & operator=(const critical_section &) {throw pfc::exception_not_implemented();}\r\n};\r\n#else\r\nclass critical_section {\r\nprivate:\r\n\tCRITICAL_SECTION sec;\r\npublic:\r\n\tvoid enter() throw() {EnterCriticalSection(&sec);}\r\n\tvoid leave() throw() {LeaveCriticalSection(&sec);}\r\n\tcritical_section() {InitializeCriticalSection(&sec);}\r\n\t~critical_section() {DeleteCriticalSection(&sec);}\r\nprivate:\r\n\tcritical_section(const critical_section&) {throw pfc::exception_not_implemented();}\r\n\tconst critical_section & operator=(const critical_section &) {throw pfc::exception_not_implemented();}\r\n};\r\n#endif\r\nclass c_insync\r\n{\r\nprivate:\r\n\tcritical_section & m_section;\r\npublic:\r\n\tc_insync(critical_section * p_section) throw() : m_section(*p_section) {m_section.enter();}\r\n\tc_insync(critical_section & p_section) throw() : m_section(p_section) {m_section.enter();}\r\n\t~c_insync() throw() {m_section.leave();}\r\n};\r\n\r\n#define insync(X) c_insync blah____sync(X)\r\n\r\n\r\nclass critical_section2\t//smarter version, has try_enter()\r\n{\r\nprivate:\r\n\tHANDLE hMutex;\r\n\tint count;\r\npublic:\r\n\tint enter() {return enter_timeout(INFINITE);}\r\n\tint leave() {int rv = --count;ReleaseMutex(hMutex);return rv;}\r\n\tint get_lock_count() {return count;}\r\n\tint get_lock_count_check()\r\n\t{\r\n\t\tint val = try_enter();\r\n\t\tif (val>0) val = leave();\r\n\t\treturn val;\r\n\t}\r\n\tint enter_timeout(DWORD t) {return WaitForSingleObject(hMutex,t)==WAIT_OBJECT_0 ? ++count : 0;}\r\n\tint try_enter() {return enter_timeout(0);}\r\n\tint check_count() {enter();return leave();}\r\n\tcritical_section2()\r\n\t{\r\n\t\thMutex = uCreateMutex(0,0,0);\r\n\t\tcount=0;\r\n\t}\r\n\t~critical_section2() {CloseHandle(hMutex);}\r\n\r\n\tinline void assert_locked() {assert(get_lock_count_check()>0);}\r\n\tinline void assert_not_locked() {assert(get_lock_count_check()==0);}\r\n\r\n};\r\n\r\nclass c_insync2\r\n{\r\nprivate:\r\n\tcritical_section2 * ptr;\r\npublic:\r\n\tc_insync2(critical_section2 * p) {ptr=p;ptr->enter();}\r\n\tc_insync2(critical_section2 & p) {ptr=&p;ptr->enter();}\r\n\t~c_insync2() {ptr->leave();}\r\n};\r\n\r\n#define insync2(X) c_insync2 blah____sync2(X)\r\n\r\n\r\n//other\r\n\r\n#define uIsDialogMessage IsDialogMessage\r\n#define uGetMessage GetMessage\r\n#define uPeekMessage PeekMessage\r\n#define uDispatchMessage DispatchMessage\r\n\r\n#define uCallWindowProc CallWindowProc\r\n#define uDefWindowProc DefWindowProc\r\n#define uGetWindowLong GetWindowLong\r\n#define uSetWindowLong SetWindowLong\r\n\r\n#define uEndDialog EndDialog\r\n#define uDestroyWindow DestroyWindow\r\n#define uGetDlgItem GetDlgItem\r\n#define uEnableWindow EnableWindow\r\n#define uGetDlgItemInt GetDlgItemInt\r\n#define uSetDlgItemInt SetDlgItemInt\r\n\r\n#define __uHookWindowProc(WND,PROC) ((WNDPROC)SetWindowLongPtr(WND,GWLP_WNDPROC,(LONG_PTR)(PROC)))\r\nstatic WNDPROC uHookWindowProc(HWND p_wnd,WNDPROC p_proc) {return __uHookWindowProc(p_wnd,p_proc);}\r\n\r\n#define uCreateToolbarEx CreateToolbarEx\r\n#define uIsBadStringPtr IsBadStringPtrA\r\n#define uSendMessage SendMessage\r\n#define uSendDlgItemMessage SendDlgItemMessage\r\n#define uSendMessageTimeout SendMessageTimeout\r\n#define uSendNotifyMessage SendNotifyMessage\r\n#define uSendMessageCallback SendMessageCallback\r\n#define uPostMessage PostMessage\r\n#define uPostThreadMessage PostThreadMessage\r\n\r\n\r\nclass string_print_crash\r\n{\r\n\tchar block[uPrintCrashInfo_max_length];\r\npublic:\r\n\tinline operator const char * () const {return block;}\r\n\tinline const char * get_ptr() const {return block;}\r\n\tinline t_size length() {return strlen(block);}\r\n\tinline string_print_crash(LPEXCEPTION_POINTERS param,const char * extrainfo = 0) {uPrintCrashInfo(param,extrainfo,block);}\r\n};\r\n\r\nclass uStringPrintf\r\n{\r\npublic:\r\n\tinline explicit uStringPrintf(const char * fmt,...)\r\n\t{\r\n\t\tva_list list;\r\n\t\tva_start(list,fmt);\r\n\t\tuPrintfV(m_data,fmt,list);\r\n\t\tva_end(list);\r\n\t}\r\n\tinline operator const char * () const {return m_data.get_ptr();}\r\n\tinline t_size length() const {return m_data.length();}\r\n\tinline bool is_empty() const {return length() == 0;}\r\n\tinline const char * get_ptr() const {return m_data.get_ptr();}\r\nprivate:\r\n\tpfc::string8_fastalloc m_data;\r\n};\r\n#pragma deprecated(uStringPrintf, uPrintf, uPrintfV)\r\n\r\ninline LRESULT uButton_SetCheck(HWND wnd,UINT id,bool state) {return uSendDlgItemMessage(wnd,id,BM_SETCHECK,state ? BST_CHECKED : BST_UNCHECKED,0); }\r\ninline bool uButton_GetCheck(HWND wnd,UINT id) {return uSendDlgItemMessage(wnd,id,BM_GETCHECK,0,0) == BST_CHECKED;}\r\n\r\nclass uCallStackTracker\r\n{\r\n\tt_size param;\r\npublic:\r\n\texplicit SHARED_EXPORT uCallStackTracker(const char * name);\r\n\tSHARED_EXPORT ~uCallStackTracker();\r\n};\r\n\r\nextern \"C\"\r\n{\r\n\tLPCSTR SHARED_EXPORT uGetCallStackPath();\r\n}\r\n\r\n#if 1\r\n#define TRACK_CALL(X) uCallStackTracker TRACKER__##X(#X)\r\n#define TRACK_CALL_TEXT(X) uCallStackTracker TRACKER__BLAH(X)\r\n#define TRACK_CODE(description,code) {uCallStackTracker __call_tracker(description); code;}\r\n#else\r\n#define TRACK_CALL(X)\r\n#define TRACK_CALL_TEXT(X)\r\n#define TRACK_CODE(description,code) {code;}\r\n#endif\r\n\r\nextern \"C\" {\r\nint SHARED_EXPORT stricmp_utf8(const char * p1,const char * p2);\r\nint SHARED_EXPORT stricmp_utf8_ex(const char * p1,t_size len1,const char * p2,t_size len2);\r\nint SHARED_EXPORT stricmp_utf8_stringtoblock(const char * p1,const char * p2,t_size p2_bytes);\r\nint SHARED_EXPORT stricmp_utf8_partial(const char * p1,const char * p2,t_size num = ~0);\r\nint SHARED_EXPORT stricmp_utf8_max(const char * p1,const char * p2,t_size p1_bytes);\r\nt_size SHARED_EXPORT uReplaceStringAdd(pfc::string_base & out,const char * src,t_size src_len,const char * s1,t_size len1,const char * s2,t_size len2,bool casesens);\r\nt_size SHARED_EXPORT uReplaceCharAdd(pfc::string_base & out,const char * src,t_size src_len,unsigned c1,unsigned c2,bool casesens);\r\n//all lengths in uReplaceString functions are optional, set to -1 if parameters is a simple null-terminated string\r\nvoid SHARED_EXPORT uAddStringLower(pfc::string_base & out,const char * src,t_size len = ~0);\r\nvoid SHARED_EXPORT uAddStringUpper(pfc::string_base & out,const char * src,t_size len = ~0);\r\n}\r\n\r\nclass comparator_stricmp_utf8 {\r\npublic:\r\n\tstatic int compare(const char * p_string1,const char * p_string2) {return stricmp_utf8(p_string1,p_string2);}\r\n};\r\n\r\ninline void uStringLower(pfc::string_base & out,const char * src,t_size len = ~0) {out.reset();uAddStringLower(out,src,len);}\r\ninline void uStringUpper(pfc::string_base & out,const char * src,t_size len = ~0) {out.reset();uAddStringUpper(out,src,len);}\r\n\r\ninline t_size uReplaceString(pfc::string_base & out,const char * src,t_size src_len,const char * s1,t_size len1,const char * s2,t_size len2,bool casesens)\r\n{\r\n\tout.reset();\r\n\treturn uReplaceStringAdd(out,src,src_len,s1,len1,s2,len2,casesens);\r\n}\r\n\r\ninline t_size uReplaceChar(pfc::string_base & out,const char * src,t_size src_len,unsigned c1,unsigned c2,bool casesens)\r\n{\r\n\tout.reset();\r\n\treturn uReplaceCharAdd(out,src,src_len,c1,c2,casesens);\r\n}\r\n\r\nclass string_lower\r\n{\r\npublic:\r\n\texplicit string_lower(const char * ptr,t_size p_count = ~0) {uAddStringLower(m_data,ptr,p_count);}\r\n\tinline operator const char * () const {return m_data.get_ptr();}\r\n\tinline t_size length() const {return m_data.length();}\r\n\tinline bool is_empty() const {return length() == 0;}\r\n\tinline const char * get_ptr() const {return m_data.get_ptr();}\r\nprivate:\r\n\tpfc::string8 m_data;\r\n};\r\n\r\nclass string_upper\r\n{\r\npublic:\r\n\texplicit string_upper(const char * ptr,t_size p_count = ~0) {uAddStringUpper(m_data,ptr,p_count);}\r\n\tinline operator const char * () const {return m_data.get_ptr();}\r\n\tinline t_size length() const {return m_data.length();}\r\n\tinline bool is_empty() const {return length() == 0;}\r\n\tinline const char * get_ptr() const {return m_data.get_ptr();}\r\nprivate:\r\n\tpfc::string8 m_data;\r\n};\r\n\r\ninline UINT char_lower(UINT c) {return uCharLower(c);}\r\ninline UINT char_upper(UINT c) {return uCharUpper(c);}\r\n\r\ninline BOOL uGetLongPathNameEx(const char * name,pfc::string_base & out)\r\n{\r\n\tif (uGetLongPathName(name,out)) return TRUE;\r\n\treturn uGetFullPathName(name,out);\r\n}\r\n\r\nstruct t_font_description\r\n{\r\n\tenum\r\n\t{\r\n\t\tm_facename_length = LF_FACESIZE*2,\r\n\t\tm_height_dpi = 480,\r\n\t};\r\n\r\n\tt_uint32 m_height;\r\n\tt_uint32 m_weight;\r\n\tt_uint8 m_italic;\r\n\tt_uint8 m_charset;\r\n\tchar m_facename[m_facename_length];\r\n\r\n\tHFONT SHARED_EXPORT create() const;\r\n\tbool SHARED_EXPORT popup_dialog(HWND p_parent);\r\n\tvoid SHARED_EXPORT from_font(HFONT p_font);\r\n\tstatic t_font_description SHARED_EXPORT g_from_font(HFONT p_font);\r\n};\r\n\r\n\r\nstruct t_modal_dialog_entry\r\n{\r\n\tHWND m_wnd_to_poke;\r\n\tbool m_in_use;\r\n};\r\n\r\nextern \"C\" {\r\n\tvoid SHARED_EXPORT ModalDialog_Switch(t_modal_dialog_entry & p_entry);\r\n\tvoid SHARED_EXPORT ModalDialog_PokeExisting();\r\n\tbool SHARED_EXPORT ModalDialog_CanCreateNew();\r\n\r\n\tHWND SHARED_EXPORT FindOwningPopup(HWND p_wnd);\r\n\tvoid SHARED_EXPORT PokeWindow(HWND p_wnd);\r\n};\r\n\r\n//! The purpose of modal_dialog_scope is to help to avoid the modal dialog recursion problem. Current toplevel modal dialog handle is stored globally, so when creation of a new modal dialog is blocked, it can be activated to indicate the reason for the task being blocked.\r\nclass modal_dialog_scope {\r\npublic:\r\n\t//! This constructor initializes the modal dialog scope with specified dialog handle.\r\n\tinline modal_dialog_scope(HWND p_wnd) : m_initialized(false) {initialize(p_wnd);}\r\n\t//! This constructor leaves the scope uninitialized (you can call initialize() later with your window handle).\r\n\tinline modal_dialog_scope() : m_initialized(false) {}\r\n\tinline ~modal_dialog_scope() {deinitialize();}\r\n\r\n\t//! Returns whether creation of a new modal dialog is allowed (false when there's another one active).\\n\r\n\t//! NOTE: when calling context is already inside a modal dialog that you own, you should not be checking this before creating a new modal dialog.\r\n\tinline static bool can_create() {return ModalDialog_CanCreateNew();}\r\n\t//! Activates the top-level modal dialog existing, if one exists.\r\n\tinline static void poke_existing() {ModalDialog_PokeExisting();}\r\n\r\n\t//! Initializes the scope with specified window handle.\r\n\tvoid initialize(HWND p_wnd)\r\n\t{\r\n\t\tif (!m_initialized)\r\n\t\t{\r\n\t\t\tm_initialized = true;\r\n\t\t\tm_entry.m_in_use = true;\r\n\t\t\tm_entry.m_wnd_to_poke = p_wnd;\r\n\t\t\tModalDialog_Switch(m_entry);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid deinitialize()\r\n\t{\r\n\t\tif (m_initialized)\r\n\t\t{\r\n\t\t\tModalDialog_Switch(m_entry);\r\n\t\t\tm_initialized = false;\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\r\nprivate:\r\n\tmodal_dialog_scope(const modal_dialog_scope & p_scope) {assert(0);}\r\n\tconst modal_dialog_scope & operator=(const modal_dialog_scope &) {assert(0); return *this;}\r\n\r\n\tt_modal_dialog_entry m_entry;\r\n\r\n\tbool m_initialized;\r\n};\r\n\r\nclass format_win32_error {\r\npublic:\r\n\tformat_win32_error(DWORD p_code) {\r\n\t\tif (!uFormatSystemErrorMessage(m_buffer,p_code)) m_buffer << \"Unknown error code (\" << (unsigned)p_code << \")\";\r\n\t}\r\n\r\n\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\toperator const char*() const {return m_buffer.get_ptr();}\r\nprivate:\r\n\tpfc::string8 m_buffer;\r\n};\r\n\r\nstruct exception_win32 : public std::exception {\r\n\texception_win32(DWORD p_code) : std::exception(format_win32_error(p_code)), m_code(p_code) {}\r\n\tDWORD get_code() const {return m_code;}\r\nprivate:\r\n\tDWORD m_code;\r\n};\r\n\r\n\r\nclass uDebugLog : public pfc::string_formatter {\r\npublic:\r\n\t~uDebugLog() {*this << \"\\n\"; uOutputDebugString(get_ptr());}\r\n};\r\n\r\nstatic void uAddWindowStyle(HWND p_wnd,LONG p_style) {\r\n\tSetWindowLong(p_wnd,GWL_STYLE, GetWindowLong(p_wnd,GWL_STYLE) | p_style);\r\n}\r\n\r\nstatic void uRemoveWindowStyle(HWND p_wnd,LONG p_style) {\r\n\tSetWindowLong(p_wnd,GWL_STYLE, GetWindowLong(p_wnd,GWL_STYLE) & ~p_style);\r\n}\r\n\r\nstatic void uAddWindowExStyle(HWND p_wnd,LONG p_style) {\r\n\tSetWindowLong(p_wnd,GWL_EXSTYLE, GetWindowLong(p_wnd,GWL_EXSTYLE) | p_style);\r\n}\r\n\r\nstatic void uRemoveWindowExStyle(HWND p_wnd,LONG p_style) {\r\n\tSetWindowLong(p_wnd,GWL_EXSTYLE, GetWindowLong(p_wnd,GWL_EXSTYLE) & ~p_style);\r\n}\r\n\r\nstatic unsigned MapDialogWidth(HWND p_dialog,unsigned p_value) {\r\n\tRECT temp;\r\n\ttemp.left = 0; temp.right = p_value; temp.top = temp.bottom = 0;\r\n\tif (!MapDialogRect(p_dialog,&temp)) return 0;\r\n\treturn temp.right;\r\n}\r\n\r\nstatic bool IsKeyPressed(unsigned vk) {\r\n\treturn (GetKeyState(vk) & 0x8000) ? true : false;\r\n}\r\n\r\n#include \"audio_math.h\"\r\n#include \"win32_misc.h\"\r\n\r\n#endif //_SHARED_DLL__SHARED_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/foobar2000/shared/win32_misc.h",
    "content": "class win32_menu {\r\npublic:\r\n\twin32_menu(HMENU p_initval) : m_menu(p_initval) {}\r\n\twin32_menu() : m_menu(NULL) {}\r\n\t~win32_menu() {release();}\r\n\tvoid release() {\r\n\t\tif (m_menu != NULL) {\r\n\t\t\tDestroyMenu(m_menu);\r\n\t\t\tm_menu = NULL;\r\n\t\t}\r\n\t}\r\n\tvoid set(HMENU p_menu) {release(); m_menu = p_menu;}\r\n\tvoid create_popup() {\r\n\t\trelease();\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tm_menu = CreatePopupMenu();\r\n\t\tif (m_menu == NULL) throw exception_win32(GetLastError());\r\n\t}\r\n\tHMENU get() const {return m_menu;}\r\n\tHMENU detach() {return pfc::replace_t(m_menu,(HMENU)NULL);}\r\n\t\r\n\tbool is_valid() const {return m_menu != NULL;}\r\nprivate:\r\n\twin32_menu(const win32_menu &) {throw pfc::exception_not_implemented();}\r\n\tconst win32_menu & operator=(const win32_menu &) {throw pfc::exception_not_implemented();}\r\n\r\n\tHMENU m_menu;\r\n};\r\n\r\nclass win32_font {\r\npublic:\r\n\twin32_font(HFONT p_initval) : m_font(p_initval) {}\r\n\twin32_font() : m_font(NULL) {}\r\n\t~win32_font() {release();}\r\n\r\n\tvoid release() {\r\n\t\tHFONT temp = detach();\r\n\t\tif (temp != NULL) DeleteObject(temp);\r\n\t}\r\n\r\n\tvoid set(HFONT p_font) {release(); m_font = p_font;}\r\n\tHFONT get() const {return m_font;}\r\n\tHFONT detach() {return pfc::replace_t(m_font,(HFONT)NULL);}\r\n\r\n\tvoid create(const t_font_description & p_desc) {\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tHFONT temp = p_desc.create();\r\n\t\tif (temp == NULL) throw exception_win32(GetLastError());\r\n\t\tset(temp);\r\n\t}\r\n\r\n\tbool is_valid() const {return m_font != NULL;}\r\n\r\nprivate:\r\n\twin32_font(const win32_font&) {throw pfc::exception_not_implemented();}\r\n\tconst win32_font & operator=(const win32_font &) {throw pfc::exception_not_implemented();}\r\n\r\n\tHFONT m_font;\r\n};\r\n\r\nclass win32_event {\r\npublic:\r\n\twin32_event() : m_handle(NULL) {}\r\n\t~win32_event() {release();}\r\n\r\n\tvoid create(bool p_manualreset,bool p_initialstate) {\r\n\t\trelease();\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tm_handle = CreateEvent(NULL,p_manualreset ? TRUE : FALSE, p_initialstate ? TRUE : FALSE,NULL);\r\n\t\tif (m_handle == NULL) throw exception_win32(GetLastError());\r\n\t}\r\n\t\r\n\tvoid set(HANDLE p_handle) {release(); m_handle = p_handle;}\r\n\tHANDLE get() const {return m_handle;}\r\n\tHANDLE detach() {return pfc::replace_t(m_handle,(HANDLE)NULL);}\r\n\tbool is_valid() const {return m_handle != NULL;}\r\n\t\r\n\tvoid release() {\r\n\t\tHANDLE temp = detach();\r\n\t\tif (temp != NULL) CloseHandle(temp);\r\n\t}\r\n\r\n\r\n\t//! Returns true when signaled, false on timeout\r\n\tbool wait_for(double p_timeout_seconds) {return g_wait_for(get(),p_timeout_seconds);}\r\n\t\r\n\tstatic DWORD g_calculate_wait_time(double p_seconds) {\r\n\t\tDWORD time = 0;\r\n\t\tif (p_seconds> 0) {\r\n\t\t\ttime = audio_math::rint32((audio_sample)(p_seconds * 1000.0));\r\n\t\t\tif (time == 0) time = 1;\r\n\t\t} else if (p_seconds < 0) {\r\n\t\t\ttime = INFINITE;\r\n\t\t}\r\n\t\treturn time;\r\n\t}\r\n\r\n\t//! Returns true when signaled, false on timeout\r\n\tstatic bool g_wait_for(HANDLE p_event,double p_timeout_seconds) {\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tDWORD status = WaitForSingleObject(p_event,g_calculate_wait_time(p_timeout_seconds));\r\n\t\tswitch(status) {\r\n\t\tcase WAIT_FAILED:\r\n\t\t\tthrow exception_win32(GetLastError());\r\n\t\tdefault:\r\n\t\t\tthrow pfc::exception_bug_check();\r\n\t\tcase WAIT_OBJECT_0:\r\n\t\t\treturn true;\r\n\t\tcase WAIT_TIMEOUT:\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid set_state(bool p_state) {\r\n\t\tPFC_ASSERT(m_handle != NULL);\r\n\t\tif (p_state) SetEvent(m_handle);\r\n\t\telse ResetEvent(m_handle);\r\n\t}\r\n\r\nprivate:\r\n\twin32_event(const win32_event&) {throw pfc::exception_not_implemented();}\r\n\tconst win32_event & operator=(const win32_event &) {throw pfc::exception_not_implemented();}\r\n\r\n\tHANDLE m_handle;\r\n};\r\n\r\nstatic void uSleepSeconds(double p_time,bool p_alertable) {\r\n\tSleepEx(win32_event::g_calculate_wait_time(p_time),p_alertable ? TRUE : FALSE);\r\n}\r\n\r\n\r\n\r\n\r\nclass win32_icon {\r\npublic:\r\n\twin32_icon(HICON p_initval) : m_icon(p_initval) {}\r\n\twin32_icon() : m_icon(NULL) {}\r\n\t~win32_icon() {release();}\r\n\r\n\tvoid release() {\r\n\t\tHICON temp = detach();\r\n\t\tif (temp != NULL) DestroyIcon(temp);\r\n\t}\r\n\r\n\tvoid set(HICON p_icon) {release(); m_icon = p_icon;}\r\n\tHICON get() const {return m_icon;}\r\n\tHICON detach() {return pfc::replace_t(m_icon,(HICON)NULL);}\r\n\r\n\tbool is_valid() const {return m_icon != NULL;}\r\n\r\nprivate:\r\n\twin32_icon(const win32_icon&) {throw pfc::exception_not_implemented();}\r\n\tconst win32_icon & operator=(const win32_icon &) {throw pfc::exception_not_implemented();}\r\n\r\n\tHICON m_icon;\r\n};\r\n\r\nclass win32_accelerator {\r\npublic:\r\n\twin32_accelerator() : m_accel(NULL) {}\r\n\t~win32_accelerator() {release();}\r\n\tHACCEL get() const {return m_accel;}\r\n\r\n\tvoid load(HINSTANCE p_inst,const TCHAR * p_id) {\r\n\t\trelease();\r\n\t\tSetLastError(NO_ERROR);\r\n\t\tm_accel = LoadAccelerators(p_inst,p_id);\r\n\t\tif (m_accel == NULL) {\r\n\t\t\tthrow exception_win32(GetLastError());\r\n\t\t}\r\n\t}\r\n\t\r\n\tvoid release() {\r\n\t\tif (m_accel != NULL) {\r\n\t\t\tDestroyAcceleratorTable(m_accel);\r\n\t\t\tm_accel = NULL;\r\n\t\t}\r\n\t}\r\nprivate:\r\n\tHACCEL m_accel;\r\n\tPFC_CLASS_NOT_COPYABLE(win32_accelerator,win32_accelerator);\r\n};\r\n\r\n\r\nclass SelectObjectScope {\r\npublic:\r\n\tSelectObjectScope(HDC p_dc,HGDIOBJ p_obj) : m_dc(p_dc), m_obj(SelectObject(p_dc,p_obj)) {}\r\n\t~SelectObjectScope() {SelectObject(m_dc,m_obj);}\r\nprivate:\r\n\tSelectObjectScope(const SelectObjectScope&) {throw pfc::exception_not_implemented();}\r\n\tconst SelectObjectScope & operator=(const SelectObjectScope&) {throw pfc::exception_not_implemented();}\r\n\tHDC m_dc;\r\n\tHGDIOBJ m_obj;\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/alloc.h",
    "content": "namespace pfc {\r\n\r\n\tstatic void * raw_malloc(t_size p_size) {\r\n\t\treturn p_size > 0 ? new_ptr_check_t(malloc(p_size)) : NULL;\r\n\t}\r\n\r\n\tstatic void raw_free(void * p_block) throw() {free(p_block);}\r\n\r\n\tstatic void* raw_realloc(void * p_ptr,t_size p_size) {\r\n\t\tif (p_size == 0) {raw_free(p_ptr); return NULL;}\r\n\t\telse if (p_ptr == NULL) return raw_malloc(p_size);\r\n\t\telse return pfc::new_ptr_check_t(::realloc(p_ptr,p_size));\r\n\t}\r\n\r\n\tstatic bool raw_realloc_inplace(void * p_block,t_size p_size) throw() {\r\n\t\tif (p_block == NULL) return p_size == 0;\r\n#ifdef _MSC_VER\r\n\t\tif (p_size == 0) return false;\r\n\t\treturn _expand(p_block,p_size) != NULL;\r\n#else\r\n\t\treturn false;\r\n#endif\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tt_size calc_array_width(t_size p_width) {\r\n\t\treturn pfc::mul_safe_t<std::bad_alloc,t_size>(p_width,sizeof(T));\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tT * __raw_malloc_t(t_size p_size) {\r\n\t\treturn reinterpret_cast<T*>(raw_malloc(calc_array_width<T>(p_size)));\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tvoid __raw_free_t(T * p_block) throw() {\r\n\t\traw_free(reinterpret_cast<void*>(p_block));\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tT * __raw_realloc_t(T * p_block,t_size p_size) {\r\n\t\treturn reinterpret_cast<T*>(raw_realloc(p_block,calc_array_width<T>(p_size)));\r\n\t}\r\n\t\r\n\ttemplate<typename T>\r\n\tbool __raw_realloc_inplace_t(T * p_block,t_size p_size) {\r\n\t\treturn raw_realloc_inplace(p_block,calc_array_width<T>(p_size));\r\n\t}\r\n\r\n\r\n\ttemplate<typename t_exception,typename t_int>\r\n\tinline t_int safe_shift_left_t(t_int p_val,t_size p_shift = 1) {\r\n\t\tt_int newval = p_val << p_shift;\r\n\t\tif (newval >> p_shift != p_val) throw t_exception();\r\n\t\treturn newval;\r\n\t}\r\n\r\n\ttemplate<typename t_item> class alloc_dummy {\r\n\tprivate: typedef alloc_dummy<t_item> t_self;\r\n\tpublic:\r\n\t\talloc_dummy() {}\r\n\t\tvoid set_size(t_size p_size) {throw pfc::exception_not_implemented();}\r\n\t\tt_size get_size() const {throw pfc::exception_not_implemented();}\r\n\t\tconst t_item & operator[](t_size p_index) const {throw pfc::exception_not_implemented();}\r\n\t\tt_item & operator[](t_size p_index) {throw pfc::exception_not_implemented();}\r\n\r\n\t\tbool is_ptr_owned(const void * p_item) const {return false;}\r\n\r\n\t\t//not mandatory\r\n\t\tconst t_item * get_ptr() const {throw pfc::exception_not_implemented();}\r\n\t\tt_item * get_ptr() {throw pfc::exception_not_implemented();}\r\n\t\tvoid prealloc(t_size) {throw pfc::exception_not_implemented();}\r\n\t\tvoid force_reset() {throw pfc::exception_not_implemented();}\r\n\tprivate:\r\n\t\tconst t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\talloc_dummy(const t_self&) {throw pfc::exception_not_implemented();}\r\n\t};\r\n\r\n\ttemplate<typename t_item>\r\n\tbool is_pointer_in_range(const t_item * p_buffer,t_size p_buffer_size,const void * p_pointer) {\r\n\t\treturn p_pointer >= reinterpret_cast<const void*>(p_buffer) && p_pointer < reinterpret_cast<const void*>(p_buffer + p_buffer_size);\r\n\t}\r\n\r\n\r\n\t//! Simple inefficient fully portable allocator.\r\n\ttemplate<typename t_item> class alloc_simple {\r\n\tprivate: typedef alloc_simple<t_item> t_self;\r\n\tpublic:\r\n\t\talloc_simple() : m_data(NULL), m_size(0) {}\r\n\t\tvoid set_size(t_size p_size) {\r\n\t\t\tif (p_size != m_size) {\r\n\t\t\t\tt_item * l_data = NULL;\r\n\t\t\t\tif (p_size > 0) l_data = new t_item[p_size];\r\n\t\t\t\ttry {\r\n\t\t\t\t\tpfc::memcpy_t(l_data,m_data,pfc::min_t(m_size,p_size));\r\n\t\t\t\t} catch(...) {\r\n\t\t\t\t\tdelete[] l_data;\r\n\t\t\t\t\tthrow;\r\n\t\t\t\t}\r\n\t\t\t\tdelete[] m_data;\r\n\t\t\t\tm_data = l_data;\r\n\t\t\t\tm_size = p_size;\r\n\t\t\t}\r\n\t\t}\r\n\t\tt_size get_size() const {return m_size;}\r\n\t\tconst t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < m_size); return m_data[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {PFC_ASSERT(p_index < m_size); return m_data[p_index];}\r\n\t\tbool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(get_ptr(),get_size(),p_item);}\r\n\r\n\t\tt_item * get_ptr() {return m_data;}\r\n\t\tconst t_item * get_ptr() const {return m_data;}\r\n\r\n\t\tvoid prealloc(t_size) {}\r\n\t\tvoid force_reset() {set_size(0);}\r\n\r\n\t\t~alloc_simple() {delete[] m_data;}\r\n\tprivate:\r\n\t\tconst t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\talloc_simple(const t_self&) {throw pfc::exception_not_implemented();}\r\n\r\n\t\tt_item * m_data;\r\n\t\tt_size m_size;\r\n\t};\r\n\r\n\ttemplate<typename t_item> class __array_fast_helper_t {\r\n\tprivate:\r\n\t\ttypedef __array_fast_helper_t<t_item> t_self;\r\n\tpublic:\r\n\t\t__array_fast_helper_t() : m_buffer(NULL), m_size_total(0), m_size(0) {}\r\n\t\t\r\n\r\n\t\tvoid set_size(t_size p_size,t_size p_size_total) {\r\n\t\t\tPFC_ASSERT(p_size <= p_size_total);\r\n\t\t\tPFC_ASSERT(m_size <= m_size_total);\r\n\t\t\tif (p_size_total > m_size_total) {\r\n\t\t\t\tresize_storage(p_size_total);\r\n\t\t\t\tresize_content(p_size);\r\n\t\t\t} else {\r\n\t\t\t\tresize_content(p_size);\r\n\t\t\t\tresize_storage(p_size_total);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\r\n\t\tt_size get_size() const {return m_size;}\r\n\t\tt_size get_size_total() const {return m_size_total;}\r\n\t\tconst t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {PFC_ASSERT(p_index < m_size); return m_buffer[p_index];}\r\n\t\t~__array_fast_helper_t() {\r\n\t\t\tset_size(0,0);\r\n\t\t}\r\n\t\tt_item * get_ptr() {return m_buffer;}\r\n\t\tconst t_item * get_ptr() const {return m_buffer;}\r\n\t\tbool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(m_buffer,m_size_total,p_item);}\r\n\tprivate:\r\n\t\tconst t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\t__array_fast_helper_t(const t_self &) {throw pfc::exception_not_implemented();}\r\n\r\n\r\n\t\tvoid resize_content(t_size p_size) {\r\n\t\t\tif (traits_t<t_item>::needs_constructor || traits_t<t_item>::needs_destructor) {\r\n\t\t\t\tif (p_size > m_size) {//expand\r\n\t\t\t\t\tdo {\r\n\t\t\t\t\t\t__unsafe__in_place_constructor_t(m_buffer[m_size]);\r\n\t\t\t\t\t\tm_size++;\r\n\t\t\t\t\t} while(m_size < p_size);\r\n\t\t\t\t} else if (p_size < m_size) {\r\n\t\t\t\t\t__unsafe__in_place_destructor_array_t(m_buffer + p_size, m_size - p_size);\r\n\t\t\t\t\tm_size = p_size;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tm_size = p_size;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid resize_storage(t_size p_size) {\r\n\t\t\tPFC_ASSERT( m_size <= m_size_total );\r\n\t\t\tPFC_ASSERT( m_size <= p_size );\r\n\t\t\tif (m_size_total != p_size) {\r\n\t\t\t\tif (pfc::traits_t<t_item>::realloc_safe) {\r\n\t\t\t\t\tm_buffer = pfc::__raw_realloc_t(m_buffer,p_size);\r\n\t\t\t\t\tm_size_total = p_size;\r\n\t\t\t\t} else if (__raw_realloc_inplace_t(m_buffer,p_size)) {\r\n\t\t\t\t\t//success\r\n\t\t\t\t\tm_size_total = p_size;\r\n\t\t\t\t} else {\r\n\t\t\t\t\tt_item * newbuffer = pfc::__raw_malloc_t<t_item>(p_size);\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tpfc::__unsafe__in_place_constructor_array_copy_t(newbuffer,m_size,m_buffer);\r\n\t\t\t\t\t} catch(...) {\r\n\t\t\t\t\t\tpfc::__raw_free_t(newbuffer);\r\n\t\t\t\t\t\tthrow;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tpfc::__unsafe__in_place_destructor_array_t(m_buffer,m_size);\r\n\t\t\t\t\tpfc::__raw_free_t(m_buffer);\r\n\t\t\t\t\tm_buffer = newbuffer;\r\n\t\t\t\t\tm_size_total = p_size;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tt_item * m_buffer;\r\n\t\tt_size m_size,m_size_total;\r\n\t};\r\n\r\n\ttemplate<typename t_item> class alloc_standard {\r\n\tprivate: typedef alloc_standard<t_item> t_self;\r\n\tpublic:\r\n\t\talloc_standard() {}\r\n\t\tvoid set_size(t_size p_size) {m_content.set_size(p_size,p_size);}\r\n\t\t\r\n\t\tt_size get_size() const {return m_content.get_size();}\r\n\t\t\r\n\t\tconst t_item & operator[](t_size p_index) const {return m_content[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {return m_content[p_index];}\r\n\r\n\t\tconst t_item * get_ptr() const {return m_content.get_ptr();}\r\n\t\tt_item * get_ptr() {return m_content.get_ptr();}\r\n\r\n\t\tbool is_ptr_owned(const void * p_item) const {return m_content.is_ptr_owned(p_item);}\r\n\t\tvoid prealloc(t_size p_size) {}\r\n\t\tvoid force_reset() {set_size(0);}\r\n\tprivate:\r\n\t\talloc_standard(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\tconst t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();}\r\n\r\n\t\t__array_fast_helper_t<t_item> m_content;\r\n\t};\r\n\r\n\ttemplate<typename t_item> class alloc_fast {\r\n\tprivate: typedef alloc_fast<t_item> t_self;\r\n\tpublic:\r\n\t\talloc_fast() {}\r\n\r\n\t\tvoid set_size(t_size p_size) {\r\n\t\t\tt_size size_base = m_data.get_size_total();\r\n\t\t\tif (size_base == 0) size_base = 1;\r\n\t\t\twhile(size_base < p_size) {\r\n\t\t\t\tsize_base = safe_shift_left_t<std::bad_alloc,t_size>(size_base,1);\r\n\t\t\t}\r\n\t\t\twhile(size_base >> 2 > p_size) {\r\n\t\t\t\tsize_base >>= 1;\r\n\t\t\t}\r\n\t\t\tm_data.set_size(p_size,size_base);\r\n\t\t}\r\n\t\t\r\n\t\tt_size get_size() const {return m_data.get_size();}\r\n\t\tconst t_item & operator[](t_size p_index) const {return m_data[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {return m_data[p_index];}\r\n\r\n\t\tconst t_item * get_ptr() const {return m_data.get_ptr();}\r\n\t\tt_item * get_ptr() {return m_data.get_ptr();}\r\n\t\tbool is_ptr_owned(const void * p_item) const {return m_data.is_ptr_owned(p_item);}\r\n\t\tvoid prealloc(t_size) {}\r\n\t\tvoid force_reset() {m_data.set_size(0,0);}\r\n\tprivate:\r\n\t\talloc_fast(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\tconst t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();}\r\n\t\t__array_fast_helper_t<t_item> m_data;\r\n\t};\r\n\r\n\ttemplate<typename t_item> class alloc_fast_aggressive {\r\n\tprivate: typedef alloc_fast_aggressive<t_item> t_self;\r\n\tpublic:\r\n\t\talloc_fast_aggressive() {}\r\n\r\n\t\tvoid set_size(t_size p_size) {\r\n\t\t\tt_size size_base = m_data.get_size_total();\r\n\t\t\tif (size_base == 0) size_base = 1;\r\n\t\t\twhile(size_base < p_size) {\r\n\t\t\t\tsize_base = safe_shift_left_t<std::bad_alloc,t_size>(size_base,1);\r\n\t\t\t}\r\n\t\t\tm_data.set_size(p_size,size_base);\r\n\t\t}\r\n\r\n\t\tvoid prealloc(t_size p_size) {\r\n\t\t\tif (p_size > 0) {\r\n\t\t\t\tt_size size_base = m_data.get_size_total();\r\n\t\t\t\tif (size_base == 0) size_base = 1;\r\n\t\t\t\twhile(size_base < p_size) {\r\n\t\t\t\t\tsize_base = safe_shift_left_t<std::bad_alloc,t_size>(size_base,1);\r\n\t\t\t\t}\r\n\t\t\t\tm_data.set_size(m_data.get_size(),size_base);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tt_size get_size() const {return m_data.get_size();}\r\n\t\tconst t_item & operator[](t_size p_index) const {;return m_data[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {return m_data[p_index];}\r\n\r\n\t\tconst t_item * get_ptr() const {return m_data.get_ptr();}\r\n\t\tt_item * get_ptr() {return m_data.get_ptr();}\r\n\t\tbool is_ptr_owned(const void * p_item) const {return m_data.is_ptr_owned(p_item);}\r\n\t\tvoid force_reset() {m_data.set_size(0,0);}\r\n\tprivate:\r\n\t\talloc_fast_aggressive(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\tconst t_self & operator=(const t_self&) {throw pfc::exception_not_implemented();}\r\n\t\t__array_fast_helper_t<t_item> m_data;\r\n\t};\r\n\r\n\ttemplate<t_size p_width> class alloc_fixed {\r\n\tpublic:\r\n\t\ttemplate<typename t_item> class alloc {\r\n\t\tprivate: typedef alloc<t_item> t_self;\r\n\t\tpublic:\r\n\t\t\talloc() : m_size(0) {}\r\n\r\n\t\t\tvoid set_size(t_size p_size) {\r\n\t\t\t\tstatic_assert_t<sizeof(m_array) == sizeof(t_item[p_width])>();\r\n\r\n\t\t\t\tif (p_size > p_width) throw pfc::exception_overflow();\r\n\t\t\t\telse if (p_size > m_size) {\r\n\t\t\t\t\t__unsafe__in_place_constructor_array_t(get_ptr()+m_size,p_size-m_size);\r\n\t\t\t\t\tm_size = p_size;\r\n\t\t\t\t} else if (p_size < m_size) {\r\n\t\t\t\t\t__unsafe__in_place_destructor_array_t(get_ptr()+p_size,m_size-p_size);\r\n\t\t\t\t\tm_size = p_size;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t~alloc() {\r\n\t\t\t\tif (pfc::traits_t<t_item>::needs_destructor) set_size(0);\r\n\t\t\t}\r\n\r\n\t\t\tt_size get_size() const {return m_size;}\r\n\r\n\t\t\tt_item * get_ptr() {return reinterpret_cast<t_item*>(&m_array);}\r\n\t\t\tconst t_item * get_ptr() const {return reinterpret_cast<const t_item*>(&m_array);}\r\n\r\n\t\t\tconst t_item & operator[](t_size n) const {return get_ptr()[n];}\r\n\t\t\tt_item & operator[](t_size n) {return get_ptr()[n];}\r\n\t\t\tbool is_ptr_owned(const void * p_item) const {return is_pointer_in_range(get_ptr(),p_width,p_item);}\r\n\t\t\tvoid prealloc(t_size) {}\r\n\t\t\tvoid force_reset() {set_size(0);}\r\n\t\tprivate:\r\n\t\t\talloc(const t_self&) {throw pfc::exception_not_implemented();}\r\n\t\t\tconst t_self& operator=(const t_self&) {throw pfc::exception_not_implemented();}\r\n\r\n\t\t\tt_uint8 m_array[sizeof(t_item[p_width])];\r\n\t\t\tt_size m_size;\r\n\t\t};\r\n\t};\r\n\r\n\ttemplate<t_size p_width, template<typename> class t_alloc = alloc_standard > class alloc_hybrid {\r\n\tpublic:\r\n\t\ttemplate<typename t_item> class alloc {\r\n\t\tprivate: typedef alloc<t_item> t_self;\r\n\t\tpublic:\r\n\t\t\talloc() {}\r\n\r\n\t\t\tvoid set_size(t_size p_size) {\r\n\t\t\t\tif (p_size > p_width) {\r\n\t\t\t\t\tm_fixed.set_size(p_width);\r\n\t\t\t\t\tm_variable.set_size(p_size - p_width);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tm_fixed.set_size(p_size);\r\n\t\t\t\t\tm_variable.set_size(0);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tt_item & operator[](t_size p_index) {\r\n\t\t\t\tPFC_ASSERT(p_index < get_size());\r\n\t\t\t\tif (p_index < p_width) return m_fixed[p_index];\r\n\t\t\t\telse return m_variable[p_index - p_width];\r\n\t\t\t}\r\n\r\n\t\t\tconst t_item & operator[](t_size p_index) const {\r\n\t\t\t\tPFC_ASSERT(p_index < get_size());\r\n\t\t\t\tif (p_index < p_width) return m_fixed[p_index];\r\n\t\t\t\telse return m_variable[p_index - p_width];\r\n\t\t\t}\r\n\r\n\t\t\tt_size get_size() const {return m_fixed.get_size() + m_variable.get_size();}\r\n\t\t\tbool is_ptr_owned(const void * p_item) const {return m_fixed.is_ptr_owned(p_item) || m_variable.is_ptr_owned(p_item);}\r\n\t\t\tvoid prealloc(t_size p_size) {\r\n\t\t\t\tif (p_size > p_width) m_variable.prealloc(p_size - p_width);\r\n\t\t\t}\r\n\t\t\tvoid force_reset() {\r\n\t\t\t\tm_fixed.force_reset(); m_variable.force_reset();\r\n\t\t\t}\r\n\t\tprivate:\r\n\t\t\talloc(const t_self&) {throw pfc::exception_not_implemented();}\r\n\t\t\tconst t_self& operator=(const t_self&) {throw pfc::exception_not_implemented();}\r\n\r\n\t\t\ttypename alloc_fixed<p_width>::template alloc<t_item> m_fixed;\r\n\t\t\tt_alloc<t_item> m_variable;\r\n\t\t};\r\n\t};\r\n\r\n\ttemplate<typename t_item> class traits_t<alloc_simple<t_item> > : public traits_default_movable {};\r\n\ttemplate<typename t_item> class traits_t<__array_fast_helper_t<t_item> > : public traits_default_movable {};\r\n\ttemplate<typename t_item> class traits_t<alloc_standard<t_item> > : public pfc::traits_t<__array_fast_helper_t<t_item> > {};\r\n\ttemplate<typename t_item> class traits_t<alloc_fast<t_item> > : public pfc::traits_t<__array_fast_helper_t<t_item> > {};\r\n\ttemplate<typename t_item> class traits_t<alloc_fast_aggressive<t_item> > : public pfc::traits_t<__array_fast_helper_t<t_item> > {};\r\n\r\n#if 0//not working (compiler bug?)\r\n\ttemplate<t_size p_width,typename t_item> class traits_t<typename alloc_fixed<p_width>::template alloc<t_item> > : public pfc::traits_t<t_item> {\r\n\tpublic:\r\n\t\tenum {\r\n\t\t\tneeds_constructor = true, \r\n\t\t};\r\n\t};\r\n\r\n\ttemplate<t_size p_width,template<typename> class t_alloc,typename t_item>\r\n\tclass traits_t<typename alloc_hybrid<p_width,t_alloc>::template alloc<t_item> > : public traits_combined<t_alloc,typename alloc_fixed<p_width>::template alloc<t_item> > {};\r\n#endif\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/array.h",
    "content": "#ifndef _PFC_ARRAY_H_\r\n#define _PFC_ARRAY_H_\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<typename t_item, template<typename> class t_alloc = alloc_standard> class array_t;\r\n\r\n\r\n\t//! Special simplififed version of array class that avoids stepping on landmines with classes without public copy operators/constructors.\r\n\ttemplate<typename _t_item>\r\n\tclass array_staticsize_t {\r\n\tpublic: typedef _t_item t_item;\r\n\tprivate: typedef array_staticsize_t<t_item> t_self;\r\n\tpublic:\r\n\t\tarray_staticsize_t() : m_size(0), m_array(NULL) {}\r\n\t\tarray_staticsize_t(t_size p_size) : m_size(0), m_array(NULL) {set_size_discard(p_size);}\r\n\t\t~array_staticsize_t() {__release();}\r\n\r\n\t\t//! Copy constructor nonfunctional when data type is not copyable.\r\n\t\tarray_staticsize_t(const t_self & p_source) : m_size(0), m_array(NULL) {\r\n\t\t\t*this = p_source;\r\n\t\t}\r\n\r\n\t\t//! Copy operator nonfunctional when data type is not copyable.\r\n\t\tconst t_self & operator=(const t_self & p_source) {\r\n\t\t\t__release();\r\n\t\t\t\r\n\t\t\t//m_array = pfc::malloc_copy_t(p_source.get_size(),p_source.get_ptr());\r\n\t\t\tconst t_size newsize = p_source.get_size()\r\n\t\t\tm_array = new t_item[newsize]\r\n\t\t\tm_size = newsize;\r\n\t\t\tfor(t_size n = 0; n < newsize; n++) m_array[n] = p_source[n];\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tvoid set_size_discard(t_size p_size) {\r\n\t\t\t__release();\r\n\t\t\tif (p_size > 0) {\r\n\t\t\t\tm_array = new t_item[p_size];\r\n\t\t\t\tm_size = p_size;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tt_size get_size() const {return m_size;}\r\n\t\tconst t_item * get_ptr() const {return m_array;}\r\n\t\tt_item * get_ptr() {return m_array;}\r\n\r\n\t\tconst t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < get_size());return m_array[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {PFC_ASSERT(p_index < get_size());return m_array[p_index];}\r\n\t\t\r\n\t\ttemplate<typename t_source> bool is_owned(const t_source & p_item) {return pfc::is_pointer_in_range(get_ptr(),get_size(),&p_item);}\r\n\tprivate:\r\n\t\tvoid __release() {\r\n\t\t\tm_size = 0;\r\n\t\t\tdelete[] pfc::replace_null_t(m_array);\r\n\t\t}\r\n\t\tt_item * m_array;\r\n\t\tt_size m_size;\r\n\t};\r\n\r\n\ttemplate<typename t_to,typename t_from>\r\n\tinline void copy_array_t(t_to & p_to,const t_from & p_from) {\r\n\t\tconst t_size size = array_size_t(p_from);\r\n\t\tif (p_to.has_owned_items(p_from)) {//avoid landmines with actual array data overlapping, or p_from being same as p_to\r\n\t\t\tarray_staticsize_t<typename t_to::t_item> temp;\r\n\t\t\ttemp.set_size_discard(size);\r\n\t\t\tpfc::copy_array_loop_t(temp,p_from,size);\r\n\t\t\tp_to.set_size(size);\r\n\t\t\tpfc::copy_array_loop_t(p_to,temp,size);\r\n\t\t} else {\r\n\t\t\tp_to.set_size(size);\r\n\t\t\tpfc::copy_array_loop_t(p_to,p_from,size);\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename t_value>\r\n\tinline void fill_array_t(t_array & p_array,const t_value & p_value) {\r\n\t\tconst t_size size = array_size_t(p_array);\r\n\t\tfor(t_size n=0;n<size;n++) p_array[n] = p_value;\r\n\t}\r\n\r\n\ttemplate<typename _t_item, template<typename> class t_alloc> class array_t {\r\n\tpublic:\ttypedef _t_item t_item;\r\n\tprivate: typedef array_t<t_item,t_alloc> t_self;\r\n\tpublic:\r\n\t\tarray_t() {}\r\n\t\tarray_t(const t_self & p_source) {copy_array_t(*this,p_source);}\r\n\t\ttemplate<typename t_source> array_t(const t_source & p_source) {copy_array_t(*this,p_source);}\r\n\t\tconst t_self & operator=(const t_self & p_source) {copy_array_t(*this,p_source); return *this;}\r\n\t\ttemplate<typename t_source> const t_self & operator=(const t_source & p_source) {copy_array_t(*this,p_source); return *this;}\r\n\t\t\r\n\t\tvoid set_size(t_size p_size) {m_alloc.set_size(p_size);}\r\n\t\tvoid set_count(t_size p_count) {m_alloc.set_size(p_count);}\r\n\t\tt_size get_size() const {return m_alloc.get_size();}\r\n\t\tt_size get_count() const {return m_alloc.get_size();}\r\n\t\tvoid force_reset() {m_alloc.force_reset();}\r\n\t\t\r\n\t\tconst t_item & operator[](t_size p_index) const {PFC_ASSERT(p_index < get_size());return m_alloc[p_index];}\r\n\t\tt_item & operator[](t_size p_index) {PFC_ASSERT(p_index < get_size());return m_alloc[p_index];}\r\n\r\n\t\t//! Warning: buffer pointer must not point to buffer allocated by this array (fixme).\r\n\t\ttemplate<typename t_source>\r\n\t\tvoid set_data_fromptr(const t_source * p_buffer,t_size p_count) {\r\n\t\t\t\r\n\t\t\tset_size(p_count);\r\n\t\t\tpfc::copy_array_loop_t(*this,p_buffer,p_count);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_array>\r\n\t\tvoid append(const t_array & p_source) {\r\n\t\t\tif (has_owned_items(p_source)) append(array_t<t_item>(p_source));\r\n\t\t\telse {\r\n\t\t\t\tconst t_size source_size = array_size_t(p_source);\r\n\t\t\t\tconst t_size base = get_size();\r\n\t\t\t\tincrease_size(source_size);\r\n\t\t\t\tfor(t_size n=0;n<source_size;n++) m_alloc[base+n] = p_source[n];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t//! Warning: buffer pointer must not point to buffer allocated by this array (fixme).\r\n\t\ttemplate<typename t_append>\r\n\t\tvoid append_fromptr(const t_append * p_buffer,t_size p_count) {\r\n\t\t\tPFC_ASSERT( !is_owned(&p_buffer[0]) );\r\n\t\t\tt_size base = get_size();\r\n\t\t\tincrease_size(p_count);\r\n\t\t\tfor(t_size n=0;n<p_count;n++) m_alloc[base+n] = p_buffer[n];\r\n\t\t}\r\n\r\n\t\tvoid increase_size(t_size p_delta) {\r\n\t\t\tt_size new_size = get_size() + p_delta;\r\n\t\t\tif (new_size < p_delta) throw std::bad_alloc();\r\n\t\t\tset_size(new_size);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_append>\r\n\t\tvoid append_single(const t_append & p_item) {\r\n\t\t\tif (is_owned(p_item)) append_single(t_append(p_item));\r\n\t\t\telse {\r\n\t\t\t\tconst t_size base = get_size();\r\n\t\t\t\tincrease_size(1);\r\n\t\t\t\tm_alloc[base] = p_item;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_filler>\r\n\t\tvoid fill(const t_filler & p_filler) {\r\n\t\t\tconst t_size max = get_size();\r\n\t\t\tfor(t_size n=0;n<max;n++) m_alloc[n] = p_filler;\r\n\t\t}\r\n\r\n\t\tvoid fill_null() {\r\n\t\t\tconst t_size max = get_size();\r\n\t\t\tfor(t_size n=0;n<max;n++) m_alloc[n] = 0;\r\n}\r\n\r\n\t\tvoid grow_size(t_size p_size) {\r\n\t\t\tif (p_size > get_size()) set_size(p_size);\r\n\t\t}\r\n\r\n\t\t//not supported by some allocs\r\n\t\tconst t_item * get_ptr() const {return m_alloc.get_ptr();}\r\n\t\tt_item * get_ptr() {return m_alloc.get_ptr();}\r\n\r\n\t\tvoid prealloc(t_size p_size) {m_alloc.prealloc(p_size);}\r\n\r\n\t\ttemplate<typename t_array>\r\n\t\tbool has_owned_items(const t_array & p_source) {\r\n\t\t\tif (array_size_t(p_source) == 0) return false;\r\n\r\n\t\t\t//how the hell would we properly check if any of source items is owned by us, in case source array implements some weird mixing of references of items from different sources?\r\n\t\t\t//the most obvious way means evil bottleneck here (whether it matters or not from caller's point of view which does something O(n) already is another question)\r\n\t\t\t//at least this will work fine with all standard classes which don't crossreference anyhow and always use own storage\r\n\t\t\t//perhaps we'll traitify this someday later\r\n\t\t\treturn is_owned(p_source[0]);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tbool is_owned(const t_source & p_item) {\r\n\t\t\treturn m_alloc.is_ptr_owned(&p_item);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tvoid set_single(const t_item & p_item) {\r\n\t\t\tset_size(1);\r\n\t\t\t(*this)[0] = p_item;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) const {\r\n\t\t\tfor(t_size n = 0; n < get_size(); n++ ) {\r\n\t\t\t\tp_callback((*this)[n]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tt_alloc<t_item> m_alloc;\r\n\t};\r\n\r\n\ttemplate<typename t_item,t_size p_width,template<typename> class t_alloc = alloc_standard >\r\n\tclass array_hybrid_t : public array_t<t_item, pfc::alloc_hybrid<p_width,t_alloc>::template alloc >\r\n\t{};\r\n\r\n\r\n\ttemplate<typename t_item> class traits_t<array_staticsize_t<t_item> > : public traits_default_movable {};\r\n\ttemplate<typename t_item,template<typename> class t_alloc> class traits_t<array_t<t_item,t_alloc> > : public pfc::traits_t<t_alloc<t_item> > {};\r\n\r\n\r\n\ttemplate<typename t_comparator = comparator_default>\r\n\tclass comparator_array {\r\n\tpublic:\r\n\t\ttemplate<typename t_array1, typename t_array2>\r\n\t\tstatic int compare(const t_array1 & p_array1, const t_array2 & p_array2) {\r\n\t\t\tt_size walk = 0;\r\n\t\t\tfor(;;) {\r\n\t\t\t\tif (walk >= p_array1.get_size() && walk >= p_array2.get_size()) return 0;\r\n\t\t\t\telse if (walk >= p_array1.get_size()) return -1;\r\n\t\t\t\telse if (walk >= p_array2.get_size()) return 1;\r\n\t\t\t\telse {\r\n\t\t\t\t\tint state = t_comparator::compare(p_array1[walk],p_array2[walk]);\r\n\t\t\t\t\tif (state != 0) return state;\r\n\t\t\t\t}\r\n\t\t\t\t++walk;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n}\r\n\r\n\r\n#endif //_PFC_ARRAY_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/avltree.h",
    "content": "#ifndef _AVLTREE_T_H_INCLUDED_\r\n#define _AVLTREE_T_H_INCLUDED_\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<typename t_storage,typename t_comparator = comparator_default>\r\n\tclass avltree_t {\r\n\t\ttypedef avltree_t<t_storage,t_comparator> t_self;\r\n\r\n\t\ttemplate<typename t_item1,typename t_item2>\r\n\t\tinline static int compare(const t_item1 & p_item1, const t_item2 & p_item2) {\r\n\t\t\treturn t_comparator::compare(p_item1,p_item2);\r\n\t\t}\r\n\r\n\t\tstruct t_node {\r\n\t\t\tt_node *m_left,*m_right;\r\n\t\t\tt_size m_depth;\r\n\t\t\tt_storage m_data;\r\n\r\n\t\t\ttemplate<bool p_which> t_node * & child() {return p_which ? m_right : m_left;}\r\n\t\t\ttemplate<bool p_which> t_node * child() const {return p_which ? m_right : m_left;}\r\n\r\n\t\t\t~t_node() {\r\n\t\t\t\tif (m_left != NULL) delete m_left;\r\n\t\t\t\tif (m_right != NULL) delete m_right;\r\n\t\t\t}\r\n\r\n\t\t\ttemplate<typename T>\r\n\t\t\tt_node(T const & p_param) : m_data(p_param), m_left(NULL), m_right(NULL), m_depth(0) {}\r\n\t\t};\r\n\r\n\t\tt_node * m_root;\r\n\r\n\t\tstatic t_size calc_depth(const t_node * ptr)\r\n\t\t{\r\n\t\t\treturn ptr ? 1+ptr->m_depth : 0;\r\n\t\t}\r\n\r\n\t\tstatic void recalc_depth(t_node * ptr) {\r\n\t\t\tptr->m_depth = pfc::max_t(calc_depth(ptr->m_left), calc_depth(ptr->m_right));\r\n\t\t}\r\n\r\n\t\tstatic void assert_children(t_node * ptr)\r\n\t\t{\r\n\t#ifdef _DEBUG\r\n\t\t\tPFC_ASSERT(ptr->m_depth == pfc::max_t(calc_depth(ptr->m_left),calc_depth(ptr->m_right)) );\r\n\t#endif\r\n\t\t}\r\n\r\n\t\tstatic int test_depth(t_node * ptr)\r\n\t\t{\r\n\t\t\tif (ptr==0) return 0;\r\n\t\t\telse return calc_depth(ptr->m_right) - calc_depth(ptr->m_left);\r\n\t\t}\r\n\r\n\t\tstatic t_node * extract_left_leaf(t_node * & p_base) {\r\n\t\t\tif (p_base->m_left != NULL) {\r\n\t\t\t\tt_node * ret = extract_left_leaf(p_base->m_left);\r\n\t\t\t\trecalc_depth(p_base);\r\n\t\t\t\tg_rebalance(p_base);\r\n\t\t\t\treturn ret;\r\n\t\t\t} else {\r\n\t\t\t\tt_node * node = p_base;\r\n\t\t\t\tp_base = node->m_right;\r\n\t\t\t\tnode->m_right = 0;\r\n\t\t\t\tnode->m_depth = 0;\r\n\t\t\t\treturn node;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic t_node * extract_right_leaf(t_node ** p_base) {\r\n\t\t\tt_node * node = *p_base;\r\n\t\t\tif (node->m_right != NULL) {\r\n\t\t\t\tt_node * ret = extract_right_leaf(&node->m_right);\r\n\t\t\t\trecalc_depth(node);\r\n\t\t\t\tg_rebalance(p_base);\r\n\t\t\t\treturn ret;\r\n\t\t\t} else {\r\n\t\t\t\t*p_base = node->m_left;\r\n\t\t\t\tnode->m_left = 0;\r\n\t\t\t\tnode->m_depth = 0;\r\n\t\t\t\treturn node;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic void remove_internal(t_node* & p_node) {\r\n\t\t\tt_node * deleteme = p_node;\r\n\t\t\tif (p_node->m_left==0)\r\n\t\t\t\tp_node = p_node->m_right;\r\n\t\t\telse if (p_node->m_right==0)\r\n\t\t\t\tp_node = p_node->m_left;\r\n\t\t\telse {\r\n\t\t\t\tt_node * swap = extract_left_leaf(p_node->m_right);\r\n\t\t\t\tswap->m_left = deleteme->m_left;\r\n\t\t\t\tswap->m_right = deleteme->m_right;\r\n\t\t\t\trecalc_depth(swap);\r\n\t\t\t\tp_node = swap;\r\n\t\t\t}\r\n\t\t\tdeleteme->m_left = deleteme->m_right = NULL;\r\n\t\t\tdeleteme->m_depth = 0;\r\n\t\t\tdelete deleteme;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_nodewalk,typename t_callback>\r\n\t\tstatic void __enum_items_recur(t_nodewalk * p_node,t_callback & p_callback) {\r\n\t\t\tif (p_node != NULL) {\r\n\t\t\t\t__enum_items_recur<t_nodewalk>(p_node->m_left,p_callback);\r\n\t\t\t\tp_callback (p_node->m_data);\r\n\t\t\t\t__enum_items_recur<t_nodewalk>(p_node->m_right,p_callback);\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_search>\r\n\t\tstatic t_storage * g_find_or_add(t_node * & p_base,t_search const & p_search,bool & p_new)\r\n\t\t{\r\n\t\t\tif (p_base == NULL) {\r\n\t\t\t\tp_base = new t_node(p_search);\r\n\t\t\t\tp_new = true;\r\n\t\t\t\treturn &p_base->m_data;\r\n\t\t\t}\r\n\r\n\t\t\tint result = compare(p_base->m_data,p_search);\r\n\t\t\tif (result > 0) {\r\n\t\t\t\tt_storage * ret = g_find_or_add<t_search>(p_base->m_left,p_search,p_new);\r\n\t\t\t\tif (p_new) {\r\n\t\t\t\t\trecalc_depth(p_base);\r\n\t\t\t\t\tg_rebalance(p_base);\r\n\t\t\t\t}\r\n\t\t\t\treturn ret;\r\n\t\t\t} else if (result < 0) {\r\n\t\t\t\tt_storage * ret = g_find_or_add<t_search>(p_base->m_right,p_search,p_new);\r\n\t\t\t\tif (p_new) {\r\n\t\t\t\t\trecalc_depth(p_base);\r\n\t\t\t\t\tg_rebalance(p_base);\r\n\t\t\t\t}\r\n\t\t\t\treturn ret;\r\n\t\t\t} else {\r\n\t\t\t\tp_new = false;\r\n\t\t\t\treturn &p_base->m_data;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tstatic void g_rotate_right(t_node * & p_node) {\r\n\t\t\tt_node * oldroot = p_node;\r\n\t\t\tt_node * newroot = oldroot->m_right;\r\n\t\t\tPFC_ASSERT(newroot != NULL);\r\n\t\t\toldroot->m_right = newroot->m_left;\r\n\t\t\tnewroot->m_left = oldroot;\r\n\t\t\trecalc_depth(oldroot);\r\n\t\t\trecalc_depth(newroot);\r\n\t\t\tp_node = newroot;\r\n\t\t}\r\n\r\n\t\tstatic void g_rotate_left(t_node * & p_node) {\r\n\t\t\tt_node * oldroot = p_node;\r\n\t\t\tt_node * newroot = oldroot->m_left;\r\n\t\t\tPFC_ASSERT(newroot != NULL);\r\n\t\t\toldroot->m_left = newroot->m_right;\r\n\t\t\tnewroot->m_right = oldroot;\r\n\t\t\trecalc_depth(oldroot);\r\n\t\t\trecalc_depth(newroot);\r\n\t\t\tp_node = newroot;\r\n\t\t}\r\n\r\n\t\tstatic void g_rebalance(t_node * & p_node) {\r\n\t\t\tint balance = test_depth(p_node);\r\n\t\t\tif (balance > 1) {\r\n\t\t\t\t//right becomes root\r\n\t\t\t\tif (test_depth((p_node)->m_right) < 0) {\r\n\t\t\t\t\tg_rotate_left((p_node)->m_right);\r\n\t\t\t\t}\r\n\t\t\t\tg_rotate_right(p_node);\r\n\t\t\t} else if (balance < -1) {\r\n\t\t\t\t//left becomes root\r\n\t\t\t\tif (test_depth((p_node)->m_left) > 0) {\r\n\t\t\t\t\tg_rotate_right((p_node)->m_left);\r\n\t\t\t\t}\r\n\t\t\t\tg_rotate_left(p_node);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_search>\r\n\t\tstatic bool g_remove(t_node * & p_node,t_search const & p_search) {\r\n\t\t\tif (p_node == NULL) return false;\r\n\r\n\t\t\tint result = compare(p_node->m_data,p_search);\r\n\t\t\tif (result == 0) {\r\n\t\t\t\tremove_internal(p_node);\r\n\t\t\t\tif (p_node != NULL) {\r\n\t\t\t\t\trecalc_depth(p_node);\r\n\t\t\t\t\tg_rebalance(p_node);\r\n\t\t\t\t\tselftest(p_node);\r\n\t\t\t\t}\r\n\t\t\t\treturn true;\r\n\t\t\t} else {\r\n\t\t\t\tif (g_remove<t_search>(result > 0 ? p_node->m_left : p_node->m_right,p_search)) {\r\n\t\t\t\t\trecalc_depth(p_node);\r\n\t\t\t\t\tg_rebalance(p_node);\r\n\t\t\t\t\tselftest(p_node);\r\n\t\t\t\t\treturn true;\r\n\t\t\t\t} else {\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstatic void selftest(t_node * p_node) {\r\n\t#if 0 //def _DEBUG\r\n\t\t\tif (p_node != NULL) {\r\n\t\t\t\tselftest(p_node->m_left);\r\n\t\t\t\tselftest(p_node->m_right);\r\n\t\t\t\tassert_children(p_node);\r\n\t\t\t\tint delta = test_depth(p_node);\r\n\t\t\t\tassert(delta >= -1 && delta <= 1);\r\n\t\t\t}\r\n\t#endif\r\n\t\t}\r\n\r\n\r\n\t\tstatic t_size calc_count(const t_node * p_node) {\r\n\t\t\tif (p_node != NULL) {\r\n\t\t\t\treturn 1 + calc_count(p_node->m_left) + calc_count(p_node->m_right);\r\n\t\t\t} else {\r\n\t\t\t\treturn 0;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tt_storage * __find_item_ptr(t_item const & p_item) const {\r\n\t\t\tt_node* ptr = m_root;\r\n\t\t\twhile(ptr != NULL) {\r\n\t\t\t\tint result = compare(ptr->m_data,p_item);\r\n\t\t\t\tif (result > 0) ptr=ptr->m_left;\r\n\t\t\t\telse if (result < 0) ptr=ptr->m_right;\r\n\t\t\t\telse return &ptr->m_data;\r\n\t\t\t}\r\n\t\t\treturn NULL;\r\n\t\t}\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_search> t_storage * __find_nearest(const t_search & p_search) const {\r\n\t\t\tt_node * ptr = m_root;\r\n\t\t\tt_storage * found = NULL;\r\n\t\t\twhile(ptr != NULL) {\r\n\t\t\t\tint result = compare(ptr->m_data,p_search);\r\n\t\t\t\tif (above) result = -result;\r\n\t\t\t\tif (inclusive && result == 0) {\r\n\t\t\t\t\t//direct hit\r\n\t\t\t\t\tfound = &ptr->m_data;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t} else if (result < 0) {\r\n\t\t\t\t\t//match\r\n\t\t\t\t\tfound = &ptr->m_data;\r\n\t\t\t\t\tptr = ptr->child<!above>();\r\n\t\t\t\t} else {\r\n\t\t\t\t\t//mismatch\r\n\t\t\t\t\tptr = ptr->child<above>();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn found;\r\n\t\t}\r\n\tpublic:\r\n\t\tavltree_t() : m_root(NULL) {}\r\n\t\t~avltree_t() {reset();}\r\n\t\tconst t_self & operator=(const t_self & p_other) {__copy(p_other);return *this;}\r\n\t\tavltree_t(const t_self & p_other) : m_root(NULL) {__copy(p_other);}\r\n\r\n\t\ttemplate<typename t_other> const t_self & operator=(const t_other & p_other) {copy_list_enumerated(*this,p_other);return *this;}\r\n\t\ttemplate<typename t_other> avltree_t(const t_other & p_other) : m_root(NULL) {copy_list_enumerated(*this,p_other);}\r\n\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_search> const t_storage * find_nearest_item(const t_search & p_search) const {\r\n\t\t\treturn __find_nearest<inclusive,above>(p_search);\r\n\t\t}\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_search> t_storage * find_nearest_item(const t_search & p_search) {\r\n\t\t\treturn __find_nearest<inclusive,above>(p_search);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tt_storage & add_item(t_item const & p_item) {\r\n\t\t\tbool dummy;\r\n\t\t\treturn add_item_ex(p_item,dummy);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tt_storage & add_item_ex(t_item const & p_item,bool & p_isnew) {\r\n\t\t\tt_storage * ret = g_find_or_add(m_root,p_item,p_isnew);\r\n\t\t\tselftest(m_root);\r\n\t\t\treturn *ret;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tvoid set_item(const t_item & p_item) {\r\n\t\t\tbool isnew;\r\n\t\t\tt_storage & found = add_item_ex(p_item,isnew);\r\n\t\t\tif (isnew) found = p_item;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tconst t_storage * find_item_ptr(t_item const & p_item) const {\r\n\t\t\treturn __find_item_ptr(p_item);\r\n\t\t}\r\n\r\n\t\t//! WARNING: caller must not alter the item in a way that changes the sort order.\r\n\t\ttemplate<typename t_item>\r\n\t\tt_storage * find_item_ptr(t_item const & p_item) {\r\n\t\t\treturn __find_item_ptr(p_item);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tbool have_item(const t_item & p_item) const {\r\n\t\t\treturn find_item_ptr(p_item) != NULL;\r\n\t\t}\r\n\r\n\t\tvoid remove_all() {\r\n\t\t\tdelete pfc::replace_null_t(m_root);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_item>\r\n\t\tvoid remove_item(t_item const & p_item) {\r\n\t\t\tg_remove<t_item>(m_root,p_item);\r\n\t\t\tselftest(m_root);\r\n\t\t}\r\n\r\n\t\tt_size get_count() const {\r\n\t\t\treturn calc_count(m_root);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) const {\r\n\t\t\t__enum_items_recur<const t_node>(m_root,p_callback);\r\n\t\t}\r\n\r\n\t\t//! Allows callback to modify the tree content.\r\n\t\t//! WARNING: items must not be altered in a way that changes their sort order.\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid __enumerate(t_callback & p_callback) {\r\n\t\t\t__enum_items_recur<t_node>(m_root,p_callback);\r\n\t\t}\r\n\r\n\t\t//deprecated backwards compatibility method wrappers\r\n\t\ttemplate<typename t_item> t_storage & add(const t_item & p_item) {return add_item(p_item);}\r\n\t\ttemplate<typename t_item> t_storage & add_ex(const t_item & p_item,bool & p_isnew) {return add_item_ex(p_item,p_isnew);}\r\n\t\ttemplate<typename t_item> const t_storage * find_ptr(t_item const & p_item) const {return find_item_ptr(p_item);}\r\n\t\ttemplate<typename t_item> t_storage * find_ptr(t_item const & p_item) {return find_item_ptr(p_item);}\r\n\t\ttemplate<typename t_item> bool exists(t_item const & p_item) const {return have_item(p_item);}\r\n\t\tvoid reset() {remove_all();}\r\n\t\ttemplate<typename t_item> void remove(t_item const & p_item) {remove_item(p_item);}\r\n\r\n\tprivate:\r\n\t\tstatic t_node * __copy_recur(const t_node * p_source) {\r\n\t\t\tif (p_source == NULL) {\r\n\t\t\t\treturn NULL;\r\n\t\t\t} else {\r\n\t\t\t\tpfc::ptrholder_t<t_node> newnode = new t_node(p_source->m_data);\r\n\t\t\t\tnewnode->m_depth = p_source->m_depth;\r\n\t\t\t\tnewnode->m_left = __copy_recur(p_source->m_left);\r\n\t\t\t\tnewnode->m_right = __copy_recur(p_source->m_right);\r\n\t\t\t\treturn newnode.detach();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid __copy(const t_self & p_other) {\r\n\t\t\treset();\r\n\t\t\tm_root = __copy_recur(p_other.m_root);\r\n\t\t}\r\n\t};\r\n\r\n\r\n\ttemplate<typename t_storage,typename t_comparator>\r\n\tclass traits_t<avltree_t<t_storage,t_comparator> > : public traits_default_movable {};\r\n}\r\n#endif //_AVLTREE_T_H_INCLUDED_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/bit_array.h",
    "content": "#ifndef _PFC_BIT_ARRAY_H_\r\n#define _PFC_BIT_ARRAY_H_\r\n\r\nclass NOVTABLE bit_array {\r\npublic:\r\n\tvirtual bool get(t_size n) const = 0;\r\n\tvirtual t_size find(bool val,t_size start,t_ssize count) const//can be overridden for improved speed; returns first occurance of val between start and start+count (excluding start+count), or start+count if not found; count may be negative if we're searching back\r\n\t{\r\n\t\tt_ssize d, todo, ptr = start;\r\n\t\tif (count==0) return start;\r\n\t\telse if (count<0) {d = -1; todo = -count;}\r\n\t\telse {d = 1; todo = count;}\r\n\t\twhile(todo>0 && get(ptr)!=val) {ptr+=d;todo--;}\r\n\t\treturn ptr;\r\n\t}\r\n\tinline bool operator[](t_size n) const {return get(n);}\r\n\r\n\tt_size calc_count(bool val,t_size start,t_size count,t_size count_max = ~0) const//counts number of vals for start<=n<start+count\r\n\t{\r\n\t\tt_size found = 0;\r\n\t\tt_size max = start+count;\r\n\t\tt_size ptr;\r\n\t\tfor(ptr=find(val,start,count);found<count_max && ptr<max;ptr=find(val,ptr+1,max-ptr-1)) found++;\r\n\t\treturn found;\r\n\t}\r\n\r\n\tinline t_size find_first(bool val,t_size start,t_size max) const {return find(val,start,max-start);}\r\n\tinline t_size find_next(bool val,t_size previous,t_size max) const {return find(val,previous+1,max-(previous+1));}\r\n\t//for(n = mask.find_first(true,0,m); n < m; n = mask.find_next(true,n,m) )\r\nprotected:\r\n\tbit_array() {}\r\n\t~bit_array() {}\r\n};\r\n\r\nclass NOVTABLE bit_array_var : public bit_array {\r\npublic:\r\n\tvirtual void set(t_size n,bool val)=0;\r\nprotected:\r\n\tbit_array_var() {}\r\n\t~bit_array_var() {}\r\n};\r\n\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/bit_array_impl.h",
    "content": "#ifndef _PFC_BIT_ARRAY_IMPL_H_\r\n#define _PFC_BIT_ARRAY_IMPL_H_\r\n\r\ntemplate<class T>\r\nclass bit_array_table_t : public bit_array\r\n{\r\n\tconst T * data;\r\n\tt_size count;\r\n\tbool after;\r\npublic:\r\n\tinline bit_array_table_t(const T * p_data,t_size p_count,bool p_after = false)\r\n\t\t: data(p_data), count(p_count), after(p_after)\r\n\t{\r\n\t}\r\n\r\n\tbool get(t_size n) const\r\n\t{\r\n\t\tif (n<count) return !!data[n];\r\n\t\telse return after;\r\n\t}\r\n};\r\n\r\ntemplate<class T>\r\nclass bit_array_var_table_t : public bit_array_var\r\n{\r\n\tT * data;\r\n\tt_size count;\r\n\tbool after;\r\npublic:\r\n\tinline bit_array_var_table_t(T * p_data,t_size p_count,bool p_after = false)\r\n\t\t: data(p_data), count(p_count), after(p_after)\r\n\t{\r\n\t}\r\n\r\n\tbool get(t_size n) const {\r\n\t\tif (n<count) return !!data[n];\r\n\t\telse return after;\r\n\t}\r\n\r\n\tvoid set(t_size n,bool val) {\r\n\t\tif (n<count) data[n] = !!val;\r\n\t}\r\n};\r\n\r\n\r\ntypedef bit_array_table_t<bool> bit_array_table;\r\ntypedef bit_array_var_table_t<bool> bit_array_var_table;\r\n\r\nclass bit_array_range : public bit_array\r\n{\r\n\tt_size begin,end;\r\n\tbool state;\r\npublic:\r\n\tbit_array_range(t_size first,t_size count,bool p_state = true) : begin(first), end(first+count), state(p_state) {}\r\n\t\r\n\tbool get(t_size n) const\r\n\t{\r\n\t\tbool rv = n>=begin && n<end;\r\n\t\tif (!state) rv = !rv;\r\n\t\treturn rv;\r\n\t}\r\n};\r\n\r\nclass bit_array_and : public bit_array\r\n{\r\n\tconst bit_array & a1, & a2;\r\npublic:\r\n\tbit_array_and(const bit_array & p_a1, const bit_array & p_a2) : a1(p_a1), a2(p_a2) {}\r\n\tbool get(t_size n) const {return a1.get(n) && a2.get(n);}\r\n};\r\n\r\nclass bit_array_or : public bit_array\r\n{\r\n\tconst bit_array & a1, & a2;\r\npublic:\r\n\tbit_array_or(const bit_array & p_a1, const bit_array & p_a2) : a1(p_a1), a2(p_a2) {}\r\n\tbool get(t_size n) const {return a1.get(n) || a2.get(n);}\r\n};\r\n\r\nclass bit_array_xor : public bit_array\r\n{\r\n\tconst bit_array & a1, & a2;\r\npublic:\r\n\tbit_array_xor(const bit_array & p_a1, const bit_array & p_a2) : a1(p_a1), a2(p_a2) {}\r\n\tbool get(t_size n) const\r\n\t{\r\n\t\tbool v1 = a1.get(n), v2 = a2.get(n);\r\n\t\treturn (v1 && !v2) || (!v1 && v2);\r\n\t}\r\n};\r\n\r\nclass bit_array_not : public bit_array\r\n{\r\n\tconst bit_array & a1;\r\npublic:\r\n\tbit_array_not(const bit_array & p_a1) : a1(p_a1) {}\r\n\tbool get(t_size n) const {return !a1.get(n);}\r\n\tt_size find(bool val,t_size start,t_ssize count) const\r\n\t{return a1.find(!val,start,count);}\r\n\r\n};\r\n\r\nclass bit_array_true : public bit_array\r\n{\r\npublic:\r\n\tbool get(t_size n) const {return true;}\r\n\tt_size find(bool val,t_size start,t_ssize count) const\r\n\t{return val ? start : start+count;}\r\n};\r\n\r\nclass bit_array_false : public bit_array\r\n{\r\npublic:\r\n\tbool get(t_size n) const {return false;}\r\n\tt_size find(bool val,t_size start,t_ssize count) const\r\n\t{return val ? start+count : start;}\r\n};\r\n\r\nclass bit_array_val : public bit_array\r\n{\r\n\tbool val;\r\npublic:\r\n\tbit_array_val(bool v) : val(v) {}\r\n\tbool get(t_size n) const {return val;}\r\n\tt_size find(bool p_val,t_size start,t_ssize count) const\r\n\t{return val==p_val ? start : start+count;}\r\n};\r\n\r\nclass bit_array_one : public bit_array\r\n{\r\n\tt_size val;\r\npublic:\r\n\tbit_array_one(t_size p_val) : val(p_val) {}\r\n\tvirtual bool get(t_size n) const {return n==val;}\r\n\r\n\tvirtual t_size find(bool p_val,t_size start,t_ssize count) const\r\n\t{\r\n\t\tif (count==0) return start;\r\n\t\telse if (p_val)\r\n\t\t{\r\n\t\t\tif (count>0)\r\n\t\t\t\treturn (val>=start && val<start+count) ? val : start+count;\r\n\t\t\telse\r\n\t\t\t\treturn (val<=start && val>start+count) ? val : start+count;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tif (start == val) return count>0 ? start+1 : start-1;\r\n\t\t\telse return start;\r\n\t\t}\r\n\t}\r\n};\r\n\r\nclass bit_array_bittable : public bit_array_var\r\n{\r\n\tpfc::array_t<t_uint8> m_data;\r\n\tt_size m_count;\r\npublic:\r\n\t//helpers\r\n\ttemplate<typename t_array>\r\n\tinline static bool g_get(const t_array & p_array,t_size idx)\r\n\t{\r\n\t\treturn !! (p_array[idx>>3] & (1<<(idx&7)));\r\n\t}\r\n\r\n\ttemplate<typename t_array>\r\n\tinline static void g_set(t_array & p_array,t_size idx,bool val)\r\n\t{\r\n\t\tunsigned char & dst = p_array[idx>>3];\r\n\t\tunsigned char mask = 1<<(idx&7);\r\n\t\tdst = val ? dst|mask : dst&~mask;\r\n\t}\r\n\r\n\tinline static t_size g_estimate_size(t_size p_count) {return (p_count+7)>>3;}\r\n\r\n\tvoid resize(t_size p_count)\r\n\t{\r\n\t\tt_size old_bytes = g_estimate_size(m_count);\r\n\t\tm_count = p_count;\r\n\t\tt_size bytes = g_estimate_size(m_count);\r\n\t\tm_data.set_size(bytes);\r\n\t\tif (bytes > old_bytes) pfc::memset_null_t(m_data.get_ptr()+old_bytes,bytes-old_bytes);\r\n\t}\r\n\r\n\tbit_array_bittable(t_size p_count) : m_count(0) {resize(p_count);}\r\n\t\t\r\n\tvoid set(t_size n,bool val)\r\n\t{\r\n\t\tif (n<m_count)\r\n\t\t{\r\n\t\t\tg_set(m_data,n,val);\r\n\t\t}\r\n\t}\r\n\r\n\tbool get(t_size n) const\r\n\t{\r\n\t\tbool rv = false;\r\n\t\tif (n<m_count) {\r\n\t\t\trv = g_get(m_data,n);\r\n\t\t}\r\n\t\treturn rv;\r\n\t}\r\n};\r\n\r\n\r\nclass bit_array_order_changed : public bit_array\r\n{\r\npublic:\r\n\tbit_array_order_changed(const t_size * p_order) : m_order(p_order) {}\r\n\tbool get(t_size n) const\r\n\t{\r\n\t\treturn m_order[n] != n;\r\n\t}\r\n\r\nprivate:\r\n\tconst t_size * m_order;\r\n};\r\n\r\n#define for_each_bit_array(var,mask,val,start,count) for(var = mask.find(val,start,count);var<start+count;var=mask.find(val,var+1,count-(var+1-start)))\r\n\r\n\r\n#endif //_PFC_BIT_ARRAY_IMPL_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/bsearch.cpp",
    "content": "#include \"pfc.h\"\r\n\r\n\r\n\r\n/*\r\nclass NOVTABLE bsearch_callback\r\n{\r\npublic:\r\n\tvirtual int test(t_size p_index) const = 0;\r\n};\r\n*/\r\n\r\nnamespace pfc {\r\n\r\n\tbool pfc::bsearch(t_size p_count, bsearch_callback const & p_callback,t_size & p_result) {\r\n\t\treturn bsearch_inline_t(p_count,p_callback,p_result);\r\n\t}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/bsearch.h",
    "content": "namespace pfc {\r\n\r\n\tclass NOVTABLE bsearch_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual int test(t_size n) const = 0;\r\n\t};\r\n\r\n\tPFC_DLL_EXPORT bool bsearch(t_size p_count, bsearch_callback const & p_callback,t_size & p_result);\r\n\r\n\ttemplate<typename t_container,typename t_compare, typename t_param>\r\n\tclass bsearch_callback_impl_simple_t : public bsearch_callback {\r\n\tpublic:\r\n\t\tint test(t_size p_index) const {\r\n\t\t\treturn m_compare(m_container[p_index],m_param);\r\n\t\t}\r\n\t\tbsearch_callback_impl_simple_t(const t_container & p_container,t_compare p_compare,const t_param & p_param)\r\n\t\t\t: m_container(p_container), m_compare(p_compare), m_param(p_param) \r\n\t\t{\r\n\t\t}\r\n\tprivate:\r\n\t\tconst t_container & m_container;\r\n\t\tt_compare m_compare;\r\n\t\tconst t_param & m_param;\r\n\t};\r\n\r\n\ttemplate<typename t_container,typename t_compare, typename t_param,typename t_permutation>\r\n\tclass bsearch_callback_impl_permutation_t : public bsearch_callback {\r\n\tpublic:\r\n\t\tint test(t_size p_index) const {\r\n\t\t\treturn m_compare(m_container[m_permutation[p_index]],m_param);\r\n\t\t}\r\n\t\tbsearch_callback_impl_permutation_t(const t_container & p_container,t_compare p_compare,const t_param & p_param,const t_permutation & p_permutation)\r\n\t\t\t: m_container(p_container), m_compare(p_compare), m_param(p_param), m_permutation(p_permutation)\r\n\t\t{\r\n\t\t}\r\n\tprivate:\r\n\t\tconst t_container & m_container;\r\n\t\tt_compare m_compare;\r\n\t\tconst t_param & m_param;\r\n\t\tconst t_permutation & m_permutation;\r\n\t};\r\n\r\n\r\n\ttemplate<typename t_container,typename t_compare, typename t_param>\r\n\tbool bsearch_t(t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,t_size & p_index) {\r\n\t\treturn bsearch(\r\n\t\t\tp_count,\r\n\t\t\tbsearch_callback_impl_simple_t<t_container,t_compare,t_param>(p_container,p_compare,p_param),\r\n\t\t\tp_index);\r\n\t}\r\n\r\n\ttemplate<typename t_container,typename t_compare,typename t_param,typename t_permutation>\r\n\tbool bsearch_permutation_t(t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,const t_permutation & p_permutation,t_size & p_index) {\r\n\t\tt_size index;\r\n\t\tif (bsearch(\r\n\t\t\tp_count,\r\n\t\t\tbsearch_callback_impl_permutation_t<t_container,t_compare,t_param,t_permutation>(p_container,p_compare,p_param,p_permutation),\r\n\t\t\tindex))\r\n\t\t{\r\n\t\t\tp_index = p_permutation[index];\r\n\t\t\treturn true;\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_container,typename t_compare, typename t_param>\r\n\tbool bsearch_range_t(const t_size p_count,const t_container & p_container,t_compare p_compare,const t_param & p_param,t_size & p_range_base,t_size & p_range_count)\r\n\t{\r\n\t\tt_size probe;\r\n\t\tif (!bsearch(\r\n\t\t\tp_count,\r\n\t\t\tbsearch_callback_impl_simple_t<t_container,t_compare,t_param>(p_container,p_compare,p_param),\r\n\t\t\tprobe)) return false;\r\n\r\n\t\tt_size base = probe, count = 1;\r\n\t\twhile(base > 0 && p_compare(p_container[base-1],p_param) == 0) {base--; count++;}\r\n\t\twhile(base + count < p_count && p_compare(p_container[base+count],p_param) == 0) {count++;}\r\n\t\tp_range_base = base;\r\n\t\tp_range_count = count;\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/bsearch_inline.h",
    "content": "namespace pfc {\r\n\r\ntemplate<typename t_callback>\r\ninline bool bsearch_inline_t(t_size p_count, const t_callback & p_callback,t_size & p_result)\r\n{\r\n\tt_size max = p_count;\r\n\tt_size min = 0;\r\n\tt_size ptr;\r\n\twhile(min<max)\r\n\t{\r\n\t\tptr = min + ( (max-min) >> 1);\r\n\t\tint result = p_callback.test(ptr);\r\n\t\tif (result<0) min = ptr + 1;\r\n\t\telse if (result>0) max = ptr;\r\n\t\telse \r\n\t\t{\r\n\t\t\tp_result = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tp_result = min;\r\n\treturn false;\r\n}\r\n\r\ntemplate<typename t_buffer,typename t_value>\r\ninline bool bsearch_simple_inline_t(const t_buffer & p_buffer,t_size p_count,t_value const & p_value,t_size & p_result)\r\n{\r\n\tt_size max = p_count;\r\n\tt_size min = 0;\r\n\tt_size ptr;\r\n\twhile(min<max)\r\n\t{\r\n\t\tptr = min + ( (max-min) >> 1);\r\n\t\tif (p_value > p_buffer[ptr]) min = ptr + 1;\r\n\t\telse if (p_value < p_buffer[ptr]) max = ptr;\r\n\t\telse \r\n\t\t{\r\n\t\t\tp_result = ptr;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\tp_result = min;\r\n\treturn false;\r\n}\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/byte_order_helper.h",
    "content": "#ifndef _PFC_BYTE_ORDER_HELPER_\r\n#define _PFC_BYTE_ORDER_HELPER_\r\n\r\nnamespace pfc {\r\n\tvoid byteswap_raw(void * p_buffer,t_size p_bytes);\r\n\r\n\ttemplate<typename T> T byteswap_t(T p_source);\r\n\r\n\ttemplate<> inline char byteswap_t<char>(char p_source) {return p_source;}\r\n\ttemplate<> inline unsigned char byteswap_t<unsigned char>(unsigned char p_source) {return p_source;}\r\n\r\n#ifdef _MSC_VER//does this even help with performance/size?\r\n\ttemplate<> inline wchar_t byteswap_t<wchar_t>(wchar_t p_source) {return _byteswap_ushort(p_source);}\r\n\r\n\ttemplate<> inline short byteswap_t<short>(short p_source) {return _byteswap_ushort(p_source);}\r\n\ttemplate<> inline unsigned short byteswap_t<unsigned short>(unsigned short p_source) {return _byteswap_ushort(p_source);}\r\n\r\n\ttemplate<> inline int byteswap_t<int>(int p_source) {return _byteswap_ulong(p_source);}\r\n\ttemplate<> inline unsigned int byteswap_t<unsigned int>(unsigned int p_source) {return _byteswap_ulong(p_source);}\r\n\r\n\ttemplate<> inline long byteswap_t<long>(long p_source) {return _byteswap_ulong(p_source);}\r\n\ttemplate<> inline unsigned long byteswap_t<unsigned long>(unsigned long p_source) {return _byteswap_ulong(p_source);}\r\n\r\n\ttemplate<> inline long long byteswap_t<long long>(long long p_source) {return _byteswap_uint64(p_source);}\r\n\ttemplate<> inline unsigned long long byteswap_t<unsigned long long>(unsigned long long p_source) {return _byteswap_uint64(p_source);}\r\n#else\r\n\ttemplate<> inline t_uint16 byteswap_t<t_uint16>(t_uint16 p_source) {return ((p_source & 0xFF00) >> 8) | ((p_source & 0x00FF) << 8);}\r\n\ttemplate<> inline t_int16 byteswap_t<t_int16>(t_int16 p_source) {return byteswap_t<t_uint16>(p_source);}\r\n\r\n\ttemplate<> inline t_uint32 byteswap_t<t_uint32>(t_uint32 p_source) {return ((p_source & 0xFF000000) >> 24) | ((p_source & 0x00FF0000) >> 8) | ((p_source & 0x0000FF00) << 8) | ((p_source & 0x000000FF) << 24);}\r\n\ttemplate<> inline t_int32 byteswap_t<t_int32>(t_int32 p_source) {return byteswap_t<t_uint32>(p_source);}\r\n\r\n\ttemplate<> inline t_uint64 byteswap_t<t_uint64>(t_uint64 p_source) {\r\n\t\t//optimizeme\r\n\t\tbyteswap_raw(&p_source,sizeof(p_source));\r\n\t\treturn p_source;\t\t\r\n\t}\r\n\ttemplate<> inline t_int64 byteswap_t<t_int64>(t_int64 p_source) {return byteswap_t<t_uint64>(p_source);}\r\n\r\n\ttemplate<> inline wchar_t byteswap_t<wchar_t>(wchar_t p_source) {\r\n\t\treturn byteswap_t<pfc::sized_int_t<sizeof(wchar_t)>::t_unsigned>(p_source);\r\n\t}\r\n#endif\r\n\r\n\ttemplate<> inline float byteswap_t<float>(float p_source) {\r\n\t\tfloat ret;\r\n\t\t*(t_uint32*) &ret = byteswap_t(*(const t_uint32*)&p_source );\r\n\t\treturn ret;\r\n\t}\r\n\r\n\ttemplate<> inline double byteswap_t<double>(double p_source) {\r\n\t\tdouble ret;\r\n\t\t*(t_uint64*) &ret = byteswap_t(*(const t_uint64*)&p_source );\r\n\t\treturn ret;\r\n\t}\r\n\r\n\t//blargh at GUID byteswap issue\r\n\ttemplate<> inline GUID byteswap_t<GUID>(GUID p_guid) {\r\n\t\tGUID ret;\r\n\t\tret.Data1 = pfc::byteswap_t(p_guid.Data1);\r\n\t\tret.Data2 = pfc::byteswap_t(p_guid.Data2);\r\n\t\tret.Data3 = pfc::byteswap_t(p_guid.Data3);\r\n\t\tret.Data4[0] = p_guid.Data4[0];\r\n\t\tret.Data4[1] = p_guid.Data4[1];\r\n\t\tret.Data4[2] = p_guid.Data4[2];\r\n\t\tret.Data4[3] = p_guid.Data4[3];\r\n\t\tret.Data4[4] = p_guid.Data4[4];\r\n\t\tret.Data4[5] = p_guid.Data4[5];\r\n\t\tret.Data4[6] = p_guid.Data4[6];\r\n\t\tret.Data4[7] = p_guid.Data4[7];\r\n\t\treturn ret;\r\n\t}\r\n\r\n\r\n\t\r\n};\r\n\r\n#ifdef _MSC_VER\r\n\r\n#if defined(_M_IX86) || defined(_M_X64)\r\n#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 0\r\n#endif\r\n\r\n#else//_MSC_VER\r\n\r\n#include <endian.h>\r\n#if __BYTE_ORDER == __LITTLE_ENDIAN\r\n#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 1\r\n#else\r\n#define PFC_BYTE_ORDER_IS_BIG_ENDIAN 0\r\n#endif\r\n\r\n#endif//_MSC_VER\r\n\r\n#ifdef PFC_BYTE_ORDER_IS_BIG_ENDIAN\r\n#define PFC_BYTE_ORDER_IS_LITTLE_ENDIAN (!(PFC_BYTE_ORDER_IS_BIG_ENDIAN))\r\n#else\r\n#error please update byte order #defines\r\n#endif\r\n\r\n\r\nnamespace pfc {\r\n\tenum {\r\n\t\tbyte_order_is_big_endian = PFC_BYTE_ORDER_IS_BIG_ENDIAN,\r\n\t\tbyte_order_is_little_endian = PFC_BYTE_ORDER_IS_LITTLE_ENDIAN,\r\n\t};\r\n\r\n\ttemplate<typename T> T byteswap_if_be_t(T p_param) {return byte_order_is_big_endian ? byteswap_t(p_param) : p_param;}\r\n\ttemplate<typename T> T byteswap_if_le_t(T p_param) {return byte_order_is_little_endian ? byteswap_t(p_param) : p_param;}\r\n}\r\n\r\nnamespace byte_order {\r\n\r\n#if PFC_BYTE_ORDER_IS_BIG_ENDIAN//big endian\r\n\ttemplate<typename T> inline void order_native_to_le_t(T& param) {param = pfc::byteswap_t(param);}\r\n\ttemplate<typename T> inline void order_native_to_be_t(T& param) {}\r\n\ttemplate<typename T> inline void order_le_to_native_t(T& param) {param = pfc::byteswap_t(param);}\r\n\ttemplate<typename T> inline void order_be_to_native_t(T& param) {}\r\n#else//little endian\r\n\ttemplate<typename T> inline void order_native_to_le_t(T& param) {}\r\n\ttemplate<typename T> inline void order_native_to_be_t(T& param) {param = pfc::byteswap_t(param);}\r\n\ttemplate<typename T> inline void order_le_to_native_t(T& param) {}\r\n\ttemplate<typename T> inline void order_be_to_native_t(T& param) {param = pfc::byteswap_t(param);}\r\n#endif\r\n};\r\n\r\n\r\n\r\nnamespace pfc {\r\n\ttemplate<typename TInt,unsigned width,bool IsBigEndian>\r\n\tclass __EncodeIntHelper {\r\n\tpublic:\r\n\t\tinline static void Run(TInt p_value,t_uint8 * p_out) {\r\n\t\t\t*p_out = (t_uint8)(p_value);\r\n\t\t\t__EncodeIntHelper<TInt,width-1,IsBigEndian>::Run(p_value >> 8,p_out + (IsBigEndian ? -1 : 1));\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<typename TInt,bool IsBigEndian>\r\n\tclass __EncodeIntHelper<TInt,1,IsBigEndian> {\r\n\tpublic:\r\n\t\tinline static void Run(TInt p_value,t_uint8* p_out) {\r\n\t\t\t*p_out = (t_uint8)(p_value);\r\n\t\t}\r\n\t};\r\n\ttemplate<typename TInt,bool IsBigEndian>\r\n\tclass __EncodeIntHelper<TInt,0,IsBigEndian> {\r\n\tpublic:\r\n\t\tinline static void Run(TInt,t_uint8*) {}\r\n\t};\r\n\r\n\ttemplate<typename TInt>\r\n\tinline void encode_little_endian(t_uint8 * p_buffer,TInt p_value) {\r\n\t\t__EncodeIntHelper<TInt,sizeof(TInt),false>::Run(p_value,p_buffer);\r\n\t}\r\n\ttemplate<typename TInt>\r\n\tinline void encode_big_endian(t_uint8 * p_buffer,TInt p_value) {\r\n\t\t__EncodeIntHelper<TInt,sizeof(TInt),true>::Run(p_value,p_buffer + (sizeof(TInt) - 1));\r\n\t}\r\n\r\n\r\n\ttemplate<typename TInt,unsigned width,bool IsBigEndian>\r\n\tclass __DecodeIntHelper {\r\n\tpublic:\r\n\t\tinline static TInt Run(const t_uint8 * p_in) {\r\n\t\t\treturn (__DecodeIntHelper<TInt,width-1,IsBigEndian>::Run(p_in + (IsBigEndian ? -1 : 1)) << 8) + *p_in;\r\n\t\t}\r\n\t};\r\n\t\r\n\ttemplate<typename TInt,bool IsBigEndian>\r\n\tclass __DecodeIntHelper<TInt,1,IsBigEndian> {\r\n\tpublic:\r\n\t\tinline static TInt Run(const t_uint8* p_in) {return *p_in;}\r\n\t};\r\n\r\n\ttemplate<typename TInt,bool IsBigEndian>\r\n\tclass __DecodeIntHelper<TInt,0,IsBigEndian> {\r\n\tpublic:\r\n\t\tinline static TInt Run(const t_uint8*) {return 0;}\r\n\t};\r\n\r\n\ttemplate<typename TInt>\r\n\tinline void decode_little_endian(TInt & p_out,const t_uint8 * p_buffer) {\r\n\t\tp_out = __DecodeIntHelper<TInt,sizeof(TInt),false>::Run(p_buffer);\r\n\t}\r\n\r\n\ttemplate<typename TInt>\r\n\tinline void decode_big_endian(TInt & p_out,const t_uint8 * p_buffer) {\r\n\t\tp_out = __DecodeIntHelper<TInt,sizeof(TInt),true>::Run(p_buffer + (sizeof(TInt) - 1));\r\n\t}\r\n\r\n\ttemplate<typename TInt>\r\n\tinline TInt decode_little_endian(const t_uint8 * p_buffer) {\r\n\t\tTInt temp;\r\n\t\tdecode_little_endian(temp,p_buffer);\r\n\t\treturn temp;\r\n\t}\r\n\r\n\ttemplate<typename TInt>\r\n\tinline TInt decode_big_endian(const t_uint8 * p_buffer) {\r\n\t\tTInt temp;\r\n\t\tdecode_big_endian(temp,p_buffer);\r\n\t\treturn temp;\r\n\t}\r\n}\r\n\r\n\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/chainlist.h",
    "content": "#ifndef _PFC_CHAINLIST_H_\r\n#define _PFC_CHAINLIST_H_\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<typename T>\r\n\tclass chain_list_simple_t {\r\n\tprivate:\r\n\t\ttypedef chain_list_simple_t<T> t_self;\r\n\tpublic:\r\n\t\tchain_list_simple_t() : m_first(0), m_last(0), m_count(0) {}\r\n\t\tchain_list_simple_t(const t_self & p_source) : m_first(0), m_last(0), m_count(0) {\r\n\t\t\tt_iter iter;\r\n\t\t\tfor(iter = p_source.first();iter;iter = p_source.next(iter))\r\n\t\t\t\tinsert_last(p_source.get_item(iter));\r\n\t\t}\r\n\r\n\t\tt_self const & operator=(t_self const & p_source) {\r\n\t\t\tremove_all();\r\n\t\t\tfor(t_iter iter = p_source.first();iter;iter = p_source.next(iter))\r\n\t\t\t\tinsert_last(p_source.get_item(iter));\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\ttypedef void* t_iter;\r\n\r\n\t\tinline t_size get_count() const {return m_count;}\r\n\t\tinline t_iter first() const {return reinterpret_cast<t_iter>(m_first);}\r\n\t\tinline t_iter last () const {return reinterpret_cast<t_iter>(m_last );}\r\n\t\tinline t_iter next(t_iter param) {return reinterpret_cast<elem*>(param)->m_next;}\r\n\t\tinline t_iter prev(t_iter param) {return reinterpret_cast<elem*>(param)->m_prev;}\r\n\t\tinline T & get_item(t_iter param) {return reinterpret_cast<elem*>(param)->m_data;}\r\n\t\tinline const T & get_item(t_iter param) const {return reinterpret_cast<elem*>(param)->m_data;}\r\n\t\tinline t_iter insert_first() {return _insert_first(new elem());}\r\n\t\tinline t_iter insert_first(const T& param) {return _insert_first(new elem(param));}\r\n\t\tinline t_iter insert_last() {return _insert_last(new elem());}\r\n\t\tinline t_iter insert_last(const T& param) {return _insert_last(new elem(param));}\r\n\t\tinline t_iter insert_before(t_iter p_iter) {return _insert_before(p_iter,new elem());}\r\n\t\tinline t_iter insert_before(t_iter p_iter,const T& param) {return _insert_before(p_iter,new elem(param));}\r\n\t\tinline t_iter insert_after(t_iter p_iter) {return _insert_after(p_iter,new elem());}\r\n\t\tinline t_iter insert_after(t_iter p_iter,const T& param) {return _insert_after(p_iter,new elem(param));}\r\n\t\tinline void remove(t_iter p_iter) {elem * item = reinterpret_cast<elem*>(p_iter); _unlink(item); delete item;}\r\n\t\t\r\n\t\tinline void unlink(t_iter p_iter) {_unlink(reinterpret_cast<elem*>(p_iter));}\r\n\t\tinline void link_first(t_iter p_iter) {_insert_first(reinterpret_cast<elem*>(p_iter));}\r\n\t\tinline void link_last(t_iter p_iter) {_insert_last(reinterpret_cast<elem*>(p_iter));}\r\n\t\tinline void link_before(t_iter p_next,t_iter p_iter) {_insert_before(p_next,reinterpret_cast<elem*>(p_iter));}\r\n\t\tinline void link_after(t_iter p_prev,t_iter p_iter) {_insert_after(p_prev,reinterpret_cast<elem*>(p_iter));}\r\n\t\t\r\n\t\tvoid remove_all() {while(m_count > 0) remove(first());}\r\n\r\n\t\t~chain_list_simple_t() {remove_all();}\r\n\tprivate:\r\n\t\tstruct elem;\r\n\r\n\t\tt_iter _insert_first(elem * p_elem)\r\n\t\t{\r\n\t\t\tp_elem->m_prev = 0;\r\n\t\t\tp_elem->m_next = m_first;\r\n\t\t\t(m_first ? m_first->m_prev : m_last) = p_elem;\r\n\t\t\tm_first = p_elem;\r\n\t\t\tm_count++;\r\n\t\t\treturn reinterpret_cast<t_iter>(p_elem);\r\n\t\t}\r\n\r\n\t\tt_iter _insert_last(elem * p_elem)\r\n\t\t{\r\n\t\t\tp_elem->m_prev = m_last;\r\n\t\t\tp_elem->m_next = 0;\r\n\t\t\t(m_last ? m_last->m_next : m_first) = p_elem;\r\n\t\t\tm_last = p_elem;\r\n\t\t\tm_count++;\r\n\t\t\treturn reinterpret_cast<t_iter>(p_elem);\r\n\t\t}\r\n\t\t\r\n\t\tt_iter _insert_before(t_iter p_iter,elem * p_elem)\r\n\t\t{\r\n\t\t\telem * p_next = reinterpret_cast<elem*>(p_iter);\r\n\t\t\tp_elem->m_next = p_next;\r\n\t\t\tp_elem->m_prev = p_next->m_prev;\r\n\t\t\t(p_next->m_prev ? p_next->m_prev->m_next : m_first) = p_elem;\r\n\t\t\tp_next->m_prev = p_elem;\t\t\t\r\n\t\t\tm_count++;\r\n\t\t\treturn reinterpret_cast<t_iter>(p_elem);\r\n\t\t}\r\n\r\n\t\tt_iter _insert_after(t_iter p_iter,elem * p_elem)\r\n\t\t{\r\n\t\t\telem * p_prev = reinterpret_cast<elem*>(p_iter);\r\n\t\t\tp_elem->m_next = p_prev->m_next;\r\n\t\t\tp_elem->m_prev = p_prev;\r\n\t\t\t(p_prev->m_next ? p_prev->m_next->m_prev : m_last) = p_elem;\r\n\t\t\tp_prev->m_next = p_elem;\r\n\t\t\tm_count++;\r\n\t\t\treturn reinterpret_cast<t_iter>(p_elem);\r\n\t\t}\r\n\r\n\t\tvoid _unlink(elem * p_elem)\r\n\t\t{\r\n\t\t\t(p_elem->m_prev ? p_elem->m_prev->m_next : m_first) = p_elem->m_next;\r\n\t\t\t(p_elem->m_next ? p_elem->m_next->m_prev : m_last) = p_elem->m_prev;\r\n\t\t\tp_elem->m_next = p_elem->m_prev = 0;\r\n\t\t\tm_count--;\r\n\t\t}\r\n\r\n\t\tstruct elem {\r\n\t\t\telem() : m_prev(0), m_next(0) {}\r\n\t\t\telem(const elem & p_src) {*this = p_src;}\r\n\t\t\telem(const T& p_src) : m_data(p_src), m_prev(NULL), m_next(NULL) {}\r\n\r\n\t\t\tT m_data;\r\n\t\t\telem * m_prev, * m_next;\r\n\t\t};\r\n\t\telem * m_first, * m_last;\r\n\t\tt_size m_count;\r\n\t};\r\n\r\n\r\n\ttemplate<typename t_comparator = comparator_default>\r\n\tclass comparator_chainlist {\r\n\tpublic:\r\n\t\ttemplate<typename t_list1, typename t_list2>\r\n\t\tstatic int compare(const t_list1 & p_list1, const t_list2 p_list2) {\r\n\t\t\ttypename t_list1::const_iterator iter1 = p_list1.first();\r\n\t\t\ttypename t_list2::const_iterator iter2 = p_list2.first();\r\n\t\t\tfor(;;) {\r\n\t\t\t\tif (iter1.is_empty() && iter2.is_empty()) return 0;\r\n\t\t\t\telse if (iter1.is_empty()) return -1;\r\n\t\t\t\telse if (iter2.is_empty()) return 1;\r\n\t\t\t\telse {\r\n\t\t\t\t\tint state = t_comparator::compare(*iter1,*iter2);\r\n\t\t\t\t\tif (state != 0) return state;\r\n\t\t\t\t}\r\n\t\t\t\t++iter1; ++iter2;\r\n\t\t\t}\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<typename T>\r\n\tclass chain_list_t\r\n\t{\r\n\tpublic:\r\n\t\tclass const_iterator;\r\n\t\tclass iterator;\r\n\t\tfriend class const_iterator;\r\n\t\tfriend class iterator;\r\n\r\n\tprivate:\r\n\t\tclass elem;\r\n\r\n\t\ttypedef chain_list_t<T> t_self;\r\n\tpublic:\r\n\r\n\t\tclass const_iterator\r\n\t\t{\r\n\t\tpublic:\r\n\t\t\tfriend class chain_list_t<T>;\r\n\r\n\t\t\tinline const T & operator*() const {return m_ptr->m_data;}\r\n\t\t\tinline const T * operator->() const {return &m_ptr->m_data;}\r\n\t\t\tinline const_iterator() : m_owner(0), m_ptr(0) {}\r\n\t\t\tinline const_iterator(const const_iterator & p_source) : m_owner(0), m_ptr(0) {*this = p_source;}\r\n\t\t\tinline ~const_iterator() {if (m_owner) m_owner->_remove_iterator(this);}\r\n\t\t\t\r\n\t\t\tinline const_iterator(const chain_list_t<T> * p_owner,elem * p_ptr) : m_owner(p_owner), m_ptr(p_ptr)\r\n\t\t\t{\r\n\t\t\t\tif (m_owner != NULL) m_owner->_add_iterator(this);\r\n\t\t\t}\r\n\r\n\r\n\t\t\tinline const const_iterator & operator=(const const_iterator & p_source)\r\n\t\t\t{\r\n\t\t\t\tif (m_owner != NULL) m_owner->_remove_iterator(this);\r\n\t\t\t\tm_owner = p_source.m_owner;\r\n\t\t\t\tm_ptr = p_source.m_ptr;\r\n\t\t\t\tif (m_owner != NULL) m_owner->_add_iterator(this);\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\r\n\t\t\tinline void next() {if (m_ptr != NULL) m_ptr = m_ptr->m_next;}\r\n\t\t\tinline void prev() {if (m_ptr != NULL) m_ptr = m_ptr->m_prev;}\r\n\t\t\t\r\n\t\t\tinline const const_iterator & operator++() {next();return *this;}\r\n\t\t\tinline const_iterator operator++(int) {const_iterator old = *this; next(); return old;}\r\n\t\t\tinline const const_iterator & operator--() {prev();return *this;}\r\n\t\t\tinline const_iterator operator--(int) {const_iterator old = *this; prev(); return old;}\r\n\r\n\t\t\tinline bool is_valid() const {return m_ptr != NULL;}\r\n\t\t\tinline bool is_empty() const {return m_ptr == NULL;}\r\n\r\n\t\t\tinline bool operator==(const const_iterator &  p_iter) const {return m_ptr == p_iter.m_ptr;}\r\n\t\t\tinline bool operator!=(const const_iterator &  p_iter) const {return m_ptr != p_iter.m_ptr;}\r\n\r\n\t\tprotected:\r\n\t\t\tconst chain_list_t<T> * m_owner;\r\n\t\t\telem * m_ptr;\r\n\r\n\t\t\tvoid orphan() {m_ptr = 0;m_owner=0;}\r\n\t\t};\r\n\r\n\t\tclass iterator : public const_iterator\r\n\t\t{\r\n\t\tpublic:\r\n\t\t\tinline iterator() {}\r\n\t\t\tinline iterator(const iterator & p_source) : const_iterator(p_source) {}\r\n\t\t\tinline iterator(const chain_list_t<T> * p_owner,elem * p_ptr) : const_iterator(p_owner,p_ptr) {}\r\n\t\t\tinline const iterator & operator=(const iterator & p_source) { *(const_iterator*)this = *(const const_iterator*) & p_source; return *this;}\r\n\t\t\tinline T & operator*() const {return this->m_ptr->m_data;}\r\n\t\t\tinline T * operator->() const {return &this->m_ptr->m_data;}\r\n\t\t\tinline bool operator==(const iterator &  p_iter) const {return this->m_ptr == p_iter.m_ptr;}\r\n\t\t\tinline bool operator!=(const iterator &  p_iter) const {return this->m_ptr != p_iter.m_ptr;}\r\n\t\t\tinline const iterator & operator++() {this->next();return *this;}\r\n\t\t\tinline iterator operator++(int) {iterator old = *this; this->next(); return old;}\r\n\t\t\tinline const iterator & operator--() {this->prev();return *this;}\r\n\t\t\tinline iterator operator--(int) {iterator old = *this; this->prev(); return old;}\r\n\t\t};\r\n\r\n\r\n\t\tinline iterator first() {return iterator(this,m_first);}\r\n\t\tinline iterator last() {return iterator(this,m_last);}\r\n\r\n\t\tinline const_iterator first() const {return const_iterator(this,m_first);}\r\n\t\tinline const_iterator last() const {return const_iterator(this,m_last);}\r\n\r\n\t\tinline t_size get_count() const {return m_count;}\r\n\r\n\t\tinline chain_list_t() {_init();}\r\n\t\tinline chain_list_t(const t_self & p_other) { _init(); *this = p_other; }\r\n\t\ttemplate<typename t_other> inline chain_list_t(const t_other & p_other) { _init(); *this = p_other; }\r\n\t\tinline ~chain_list_t()\r\n\t\t{\r\n\t\t\tremove_all();\r\n\t\t}\r\n\t\t\r\n\t\tinline const t_self & operator=(const t_self & p_other) {\r\n\t\t\tcopy_list_enumerated(*this,p_other);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t\ttemplate<typename t_other> inline const t_self & operator=(const t_other & p_other) {\r\n\t\t\tcopy_list_enumerated(*this,p_other);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\r\n\t\ttemplate<typename t_insert> iterator insert_after(iterator const & p_iter,const t_insert & p_item) {\r\n\t\t\tdynamic_assert(p_iter.is_valid() && p_iter.m_owner == this);\r\n\t\t\telem * new_elem = new elem(p_item,0);\r\n\t\t\t__link_after(p_iter,new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_insert> iterator insert_before(iterator const & p_iter,const t_insert & p_item) {\r\n\t\t\tdynamic_assert(p_iter.is_valid() && p_iter.m_owner == this);\r\n\t\t\telem * new_elem = new elem(p_item,0);\r\n\t\t\t__link_before(p_iter,new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_insert> iterator insert_last(const t_insert & p_item) {\r\n\t\t\telem * new_elem = new elem(p_item,0);\r\n\t\t\t__link_last(new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_insert> iterator insert_first(const t_insert & p_item) {\r\n\t\t\telem * new_elem = new elem(p_item,0);\r\n\t\t\t__link_first(new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\titerator insert_after(iterator const & p_iter) {\r\n\t\t\tdynamic_assert(p_iter.is_valid() && p_iter.m_owner == this);\r\n\t\t\telem * new_elem = new elem();\r\n\t\t\t__link_after(p_iter,new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\titerator insert_before(iterator const & p_iter) {\r\n\t\t\tdynamic_assert(p_iter.is_valid() && p_iter.m_owner == this);\r\n\t\t\telem * new_elem = new elem();\r\n\t\t\t__link_before(p_iter,new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\titerator insert_last() {\r\n\t\t\telem * new_elem = new elem();\r\n\t\t\t__link_last(new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\t\titerator insert_first() {\r\n\t\t\telem * new_elem = new elem();\r\n\t\t\t__link_first(new_elem);\r\n\t\t\treturn iterator(this,new_elem);\r\n\t\t}\r\n\r\n\r\n\t\ttemplate<typename t_insert> void insert_last_multi(const chain_list_t<t_insert> & p_list) {\r\n\t\t\ttypename chain_list_t<t_insert>::const_iterator iter;\r\n\t\t\tfor(iter = p_list.first(); iter.is_valid(); ++iter) {\r\n\t\t\t\t__link_last(new elem(*iter,0));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_insert> void insert_first_multi(const chain_list_t<t_insert> & p_list) {\r\n\t\t\ttypename chain_list_t<t_insert>::const_iterator iter;\r\n\t\t\tfor(iter = p_list.last(); iter.is_valid(); --iter) {\r\n\t\t\t\t__link_first(new elem(*iter,0));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid remove_single(iterator const & p_iter);\r\n\t\tvoid remove_range(iterator const & p_from,iterator const & p_to);\r\n\t\tvoid remove_all();\r\n\r\n\t\tinline iterator find_forward(iterator const & p_iter,const T & p_item) const {return iterator(this,_find_forward(p_iter.m_ptr,p_item));}\r\n\t\tinline const_iterator find_forward(const_iterator const & p_iter,const T & p_item) const {return const_iterator(this,_find_forward(p_iter.m_ptr,p_item));}\r\n\t\tinline iterator find_back(iterator const & p_iter,const T & p_item) const {return iterator(this,_find_back(p_iter.m_ptr,p_item));}\r\n\t\tinline const_iterator find_back(const_iterator const & p_iter,const T & p_item) const {return const_iterator(this,_find_back(p_iter.m_ptr,p_item));}\r\n\r\n\t\tinline iterator find_first(const T & p_item) {return find_forward(first(),p_item);}\r\n\t\tinline const_iterator find_first(const T & p_item) const {return find_forward(first(),p_item);}\r\n\t\tinline iterator find_next(iterator p_iter,const T & p_item) const {p_iter++; return find_forward(p_iter,p_item);}\r\n\t\tinline const_iterator find_next(const_iterator p_iter,const T & p_item) const {p_iter++; return find_forward(p_iter,p_item);}\r\n\r\n\t\tinline iterator find_last(const T & p_item) {return find_back(last(),p_item);}\r\n\t\tinline const_iterator find_last(const T & p_item) const {return find_back(last(),p_item);}\r\n\t\tinline iterator find_prev(iterator p_iter,const T & p_item) const {p_iter++; return find_back(p_iter,p_item);}\r\n\t\tinline const_iterator find_prev(const_iterator p_iter,const T & p_item) const {p_iter++; return find_back(p_iter,p_item);}\r\n\r\n\t\tinline bool find_first_and_remove(const T & p_item) {\r\n\t\t\titerator iter = find_first(p_item);\r\n\t\t\tif (iter.is_valid()) {remove_single(iter); return true;}\r\n\t\t\telse return false;\r\n\t\t}\r\n\r\n\t\tconst_iterator by_index(unsigned p_idx) const\r\n\t\t{\r\n\t\t\tconst_iterator iter = first();\r\n\t\t\twhile(iter.is_valid() && p_idx)\r\n\t\t\t{\r\n\t\t\t\t++iter;\r\n\t\t\t\tp_idx--;\r\n\t\t\t}\r\n\t\t\treturn iter;\r\n\t\t}\r\n\r\n\t\titerator by_index(unsigned p_idx)\r\n\t\t{\r\n\t\t\titerator iter = first();\r\n\t\t\twhile(iter.is_valid() && p_idx)\r\n\t\t\t{\r\n\t\t\t\t++iter;\r\n\t\t\t\tp_idx--;\r\n\t\t\t}\r\n\t\t\treturn iter;\r\n\t\t}\r\n\r\n\t\tbool operator==(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_other) == 0;}\r\n\t\tbool operator!=(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_other) != 0;}\r\n\r\n\t\tbool operator<(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_ohter) < 0;}\r\n\t\tbool operator>(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_ohter) > 0;}\r\n\t\tbool operator<=(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_ohter) <= 0;}\r\n\t\tbool operator>=(const t_self & p_other) const {return comparator_chainlist::compare(*this,p_ohter) >= 0;}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) const {\r\n\t\t\t__enumerate_chain<const elem>(m_first,p_callback);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) {\r\n\t\t\t__enumerate_chain<elem>(m_first,p_callback);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_value>\r\n\t\titerator set_single(const t_value & p_value) {\r\n\t\t\tremove_all();\r\n\t\t\treturn insert_last(p_value);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_value>\r\n\t\titerator set_single() {\r\n\t\t\tremove_all();\r\n\t\t\treturn insert_last();\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_value>\r\n\t\tvoid add_item(const t_value & p_value) {\r\n\t\t\t__link_last(new elem(p_value,0));\r\n\t\t}\r\n\r\n\tprivate:\r\n\t\tstruct elem {\r\n\t\t\telem() : m_prev(NULL), m_next(NULL) {}\r\n\t\t\ttemplate<typename t_param>\r\n\t\t\telem(const t_param & p_source,int) : m_data(p_source), m_prev(0), m_next(0) {}\r\n\r\n\t\t\tT m_data;\r\n\t\t\telem * m_prev, * m_next;\r\n\t\t};\r\n\r\n\t\tvoid __link_after(iterator const & p_iter,elem * new_elem) {\r\n\t\t\telem * ptr = p_iter.m_ptr;\r\n\t\t\tnew_elem->m_prev = ptr;\r\n\t\t\tnew_elem->m_next = ptr->m_next;\r\n\t\t\t(ptr->m_next ? ptr->m_next->m_prev : m_last) = new_elem;\r\n\t\t\tptr->m_next = new_elem;\r\n\t\t\tm_count++;\r\n\t\t}\r\n\r\n\t\tvoid __link_before(iterator const & p_iter,elem * new_elem) {\r\n\t\t\telem * ptr = p_iter.m_ptr;\r\n\t\t\tnew_elem->m_next = ptr;\r\n\t\t\tnew_elem->m_prev = ptr->m_prev;\r\n\t\t\t(ptr->m_prev ? ptr->m_prev->m_next : m_first) = new_elem;\r\n\t\t\tptr->m_prev = new_elem;\r\n\t\t\tm_count++;\r\n\t\t}\r\n\r\n\t\tvoid __link_last(elem * new_elem) {\r\n\t\t\tnew_elem->m_prev = m_last;\r\n\t\t\t(m_last ? m_last->m_next : m_first) = new_elem;\r\n\t\t\tm_last = new_elem;\r\n\t\t\tm_count++;\r\n\t\t}\r\n\r\n\t\tvoid __link_first(elem * new_elem) {\r\n\t\t\tnew_elem->m_next = m_first;\r\n\t\t\t(m_first ? m_first->m_prev : m_last) = new_elem;\r\n\t\t\tm_first = new_elem;\r\n\t\t\tm_count++;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_elemwalk,typename t_callback>\r\n\t\tstatic void __enumerate_chain(t_elemwalk * p_elem,t_callback & p_callback) {\r\n\t\t\tt_elemwalk * walk = p_elem;\r\n\t\t\twhile(walk != NULL) {\r\n\t\t\t\tp_callback(walk->m_data);\r\n\t\t\t\twalk = walk->m_next;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\telem * m_first, * m_last;\r\n\r\n\t\tt_size m_count;\r\n\r\n\t\ttypedef typename chain_list_simple_t<const_iterator*>::t_iter t_iter_entry;\r\n\r\n\t\tmutable chain_list_simple_t<const_iterator*> m_iterators,m_iterators_recycle;\r\n\t\tenum {iterators_recycle_max = 32};\r\n\r\n\t\telem * _find_forward(elem * p_base,const T & p_item) const\r\n\t\t{\r\n\t\t\telem * walk = p_base;\r\n\t\t\twhile(walk)\r\n\t\t\t{\r\n\t\t\t\tif (walk->m_data == p_item) return walk;\r\n\t\t\t\twalk = walk->m_next;\r\n\t\t\t}\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\telem * _find_back(elem * p_base,const T & p_item) const\r\n\t\t{\r\n\t\t\telem * walk = p_base;\r\n\t\t\twhile(walk)\r\n\t\t\t{\r\n\t\t\t\tif (walk->m_data == p_item) return walk;\r\n\t\t\t\twalk = walk->m_prev;\r\n\t\t\t}\r\n\t\t\treturn 0;\r\n\t\t}\r\n\r\n\t\tvoid _init()\r\n\t\t{\r\n\t\t\tm_first = m_last = 0;\r\n\t\t\tm_count = 0;\r\n\t\t}\r\n\r\n\t\tvoid _delete_iter_entry(t_iter_entry p_iter) const\r\n\t\t{\r\n\t\t\tif (m_iterators_recycle.get_count() < iterators_recycle_max)\r\n\t\t\t{\r\n\t\t\t\tm_iterators.unlink(p_iter);\r\n\t\t\t\tm_iterators_recycle.link_last(p_iter);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tm_iterators.remove(p_iter);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid _add_iterator(const_iterator * p_iter) const\r\n\t\t{\r\n\t\t\tif (m_iterators_recycle.get_count() > 0)\r\n\t\t\t{\r\n\t\t\t\tt_iter_entry temp = m_iterators_recycle.first();\r\n\t\t\t\tm_iterators_recycle.unlink(temp);\r\n\t\t\t\tm_iterators.link_last(temp);\r\n\t\t\t\tm_iterators.get_item(temp) = p_iter;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tm_iterators.insert_last(p_iter);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid _remove_iterator(const_iterator * p_iter) const\r\n\t\t{\r\n\t\t\tt_iter_entry entry = m_iterators.first();\r\n\t\t\twhile(entry)\r\n\t\t\t{\r\n\t\t\t\tif (m_iterators.get_item(entry) == p_iter)\r\n\t\t\t\t{\r\n\t\t\t\t\t_delete_iter_entry(entry);\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tentry = m_iterators.next(entry);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid _update_iterators_on_removed(const elem * ptr)\r\n\t\t{\r\n\t\t\tt_iter_entry entry = m_iterators.first();\r\n\t\t\twhile(entry)\r\n\t\t\t{\r\n\t\t\t\tt_iter_entry entry_next = m_iterators.next(entry);\r\n\t\t\t\tconst_iterator * iter = m_iterators.get_item(entry);\r\n\t\t\t\tif (iter->m_ptr == ptr)\r\n\t\t\t\t{\r\n\t\t\t\t\titer->orphan();\r\n\t\t\t\t\t_delete_iter_entry(entry);\r\n\t\t\t\t}\r\n\t\t\t\tentry = entry_next;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t};//chain_list_t\r\n\r\n\ttemplate<typename T>\r\n\tvoid chain_list_t<T>::remove_single(iterator const & p_iter)\r\n\t{\r\n\t\telem * ptr = p_iter.m_ptr;\r\n\t\t(ptr->m_prev ? ptr->m_prev->m_next : m_first) = ptr->m_next;\r\n\t\t(ptr->m_next ? ptr->m_next->m_prev : m_last) = ptr->m_prev;\r\n\r\n\t\tm_count--;\r\n\r\n\t\t_update_iterators_on_removed(ptr);\r\n\r\n\t\tdelete ptr;\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tvoid chain_list_t<T>::remove_range(iterator const & p_from,iterator const & p_to)\r\n\t{\r\n\t\tif (p_from.is_valid() && p_to.is_valid())\r\n\t\t{\r\n\t\t\tbug_check_assert(p_from.m_owner == this && p_to.m_owner == this);\r\n\r\n\t\t\titerator walk = p_from;\r\n\t\t\twhile(walk != p_to)\r\n\t\t\t{\r\n\t\t\t\titerator axeme = walk;\r\n\t\t\t\twalk.next();\r\n\t\t\t\tbug_check_assert(walk.is_valid());\r\n\t\t\t\tremove_single(axeme);\r\n\t\t\t}\r\n\r\n\t\t\tremove_single(walk);\r\n\t\t}\r\n\t}\r\n\ttemplate<typename T>\r\n\tvoid chain_list_t<T>::remove_all() {remove_range(first(),last());}\r\n}\r\n\r\n#endif //_PFC_CHAINLIST_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/com_ptr_t.h",
    "content": "namespace pfc {\r\n\r\n\r\n//this is windows-only\r\n//update me to new conventions\r\ntemplate<class T>\r\nclass com_ptr_t\r\n{\r\npublic:\r\n\tinline com_ptr_t() : m_ptr(0) {}\r\n\tinline com_ptr_t(T* p_ptr) : m_ptr(p_ptr) {if (m_ptr) m_ptr->AddRef();}\r\n\tinline com_ptr_t(const com_ptr_t<T> & p_source) : m_ptr(p_source.m_ptr) {if (m_ptr) m_ptr->AddRef();}\r\n\r\n\tinline ~com_ptr_t() {if (m_ptr) m_ptr->Release();}\r\n\t\r\n\tinline void copy(T * p_ptr)\r\n\t{\r\n\t\tif (m_ptr) m_ptr->Release();\r\n\t\tm_ptr = p_ptr;\r\n\t\tif (m_ptr) m_ptr->AddRef();\r\n\t}\r\n\r\n\tinline void copy(const com_ptr_t<T> & p_source) {copy(p_source.m_ptr);}\r\n\r\n\tinline void set(T * p_ptr)//should not be used ! temporary !\r\n\t{\r\n\t\tif (m_ptr) m_ptr->Release();\r\n\t\tm_ptr = p_ptr;\r\n\t}\r\n\r\n\tinline const com_ptr_t<T> & operator=(const com_ptr_t<T> & p_source) {copy(p_source); return *this;}\r\n\tinline const com_ptr_t<T> & operator=(T * p_ptr) {copy(p_ptr); return *this;}\r\n\r\n\tinline void release()\r\n\t{\r\n\t\tif (m_ptr) m_ptr->Release();\r\n\t\tm_ptr = 0;\r\n\t}\r\n\r\n\r\n\tinline T* operator->() const {assert(m_ptr);return m_ptr;}\r\n\r\n\tinline T* get_ptr() const {return m_ptr;}\r\n\t\r\n\tinline T* duplicate_ptr() const//should not be used ! temporary !\r\n\t{\r\n\t\tif (m_ptr) m_ptr->AddRef();\r\n\t\treturn m_ptr;\r\n\t}\r\n\r\n\tinline T* duplicate_ptr_release() {\r\n\t\tT* ret = m_ptr;\r\n\t\tm_ptr = 0;\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tinline bool is_valid() const {return m_ptr != 0;}\r\n\tinline bool is_empty() const {return m_ptr == 0;}\r\n\r\n\tinline bool operator==(const com_ptr_t<T> & p_item) const {return m_ptr == p_item.m_ptr;}\r\n\tinline bool operator!=(const com_ptr_t<T> & p_item) const {return m_ptr != p_item.m_ptr;}\r\n\tinline bool operator>(const com_ptr_t<T> & p_item) const {return m_ptr > p_item.m_ptr;}\r\n\tinline bool operator<(const com_ptr_t<T> & p_item) const {return m_ptr < p_item.m_ptr;}\r\n\r\n\tinline static void g_swap(com_ptr_t<T> & item1, com_ptr_t<T> & item2) {\r\n\t\tpfc::swap_t(item1.m_ptr,item2.m_ptr);\r\n\t}\r\n\r\n\tinline T** receive_ptr() {release();return &m_ptr;}\r\n\r\nprivate:\r\n\tT* m_ptr;\r\n};\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/guid.cpp",
    "content": "#include \"pfc.h\"\r\n\r\nnamespace pfc {\r\n/*\r\n6B29FC40-CA47-1067-B31D-00DD010662DA\r\n.\r\ntypedef struct _GUID {          // size is 16\r\n    DWORD Data1;\r\n    WORD   Data2;\r\n    WORD   Data3;\r\n    BYTE  Data4[8];\r\n} GUID;\r\n\r\n// {B296CF59-4D51-466f-8E0B-E57D3F91D908}\r\nstatic const GUID <<name>> = \r\n{ 0xb296cf59, 0x4d51, 0x466f, { 0x8e, 0xb, 0xe5, 0x7d, 0x3f, 0x91, 0xd9, 0x8 } };\r\n\r\n*/\r\n\r\nunsigned GUID_from_text::read_hex(char c)\r\n{\r\n\tif (c>='0' && c<='9') return (unsigned)c - '0';\r\n\telse if (c>='a' && c<='f') return 0xa + (unsigned)c - 'a';\r\n\telse if (c>='A' && c<='F') return 0xa + (unsigned)c - 'A';\r\n\telse return 0;\r\n}\r\n\r\nunsigned GUID_from_text::read_byte(const char * ptr)\r\n{\r\n\treturn (read_hex(ptr[0])<<4) | read_hex(ptr[1]);\r\n}\r\nunsigned GUID_from_text::read_word(const char * ptr)\r\n{\r\n\treturn (read_byte(ptr)<<8) | read_byte(ptr+2);\r\n}\r\n\r\nunsigned GUID_from_text::read_dword(const char * ptr)\r\n{\r\n\treturn (read_word(ptr)<<16) | read_word(ptr+4);\r\n}\r\n\r\nvoid GUID_from_text::read_bytes(BYTE * out,unsigned num,const char * ptr)\r\n{\r\n\tfor(;num;num--)\r\n\t{\r\n\t\t*out = read_byte(ptr);\r\n\t\tout++;ptr+=2;\r\n\t}\r\n}\r\n\r\n\r\nGUID_from_text::GUID_from_text(const char * text)\r\n{\r\n\tif (*text=='{') text++;\r\n\tconst char * max;\r\n\r\n\t{\r\n\t\tconst char * t = strchr(text,'}');\r\n\t\tif (t) max = t;\r\n\t\telse max = text + strlen(text);\r\n\t}\r\n\r\n\t(GUID)*this = pfc::guid_null;\r\n\r\n\t\r\n\tdo {\r\n\t\tif (text+8>max) break;\r\n\t\tData1 = read_dword(text);\r\n\t\ttext += 8;\r\n\t\twhile(*text=='-') text++;\r\n\t\tif (text+4>max) break;\r\n\t\tData2 = read_word(text);\r\n\t\ttext += 4;\r\n\t\twhile(*text=='-') text++;\r\n\t\tif (text+4>max) break;\r\n\t\tData3 = read_word(text);\r\n\t\ttext += 4;\r\n\t\twhile(*text=='-') text++;\r\n\t\tif (text+4>max) break;\r\n\t\tread_bytes(Data4,2,text);\r\n\t\ttext += 4;\r\n\t\twhile(*text=='-') text++;\r\n\t\tif (text+12>max) break;\r\n\t\tread_bytes(Data4+2,6,text);\r\n\t} while(false);\r\n}\r\n\r\n\r\nstatic inline char print_hex_digit(unsigned val)\r\n{\r\n\tstatic const char table[16] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};\r\n\tassert((val & ~0xF) == 0);\r\n\treturn table[val];\r\n}\r\n\r\nstatic void print_hex(unsigned val,char * &out,unsigned bytes)\r\n{\r\n\tunsigned n;\r\n\tfor(n=0;n<bytes;n++)\r\n\t{\r\n\t\tunsigned char c = (unsigned char)((val >> ((bytes - 1 - n) << 3)) & 0xFF);\r\n\t\t*(out++) = print_hex_digit( c >> 4 );\r\n\t\t*(out++) = print_hex_digit( c & 0xF );\r\n\t}\r\n\t*out = 0;\r\n}\r\n\r\n\r\nprint_guid::print_guid(const GUID & p_guid)\r\n{\r\n\tchar * out = m_data;\r\n\tprint_hex(p_guid.Data1,out,4);\r\n\t*(out++) = '-';\r\n\tprint_hex(p_guid.Data2,out,2);\r\n\t*(out++) = '-';\r\n\tprint_hex(p_guid.Data3,out,2);\r\n\t*(out++) = '-';\r\n\tprint_hex(p_guid.Data4[0],out,1);\r\n\tprint_hex(p_guid.Data4[1],out,1);\r\n\t*(out++) = '-';\r\n\tprint_hex(p_guid.Data4[2],out,1);\r\n\tprint_hex(p_guid.Data4[3],out,1);\r\n\tprint_hex(p_guid.Data4[4],out,1);\r\n\tprint_hex(p_guid.Data4[5],out,1);\r\n\tprint_hex(p_guid.Data4[6],out,1);\r\n\tprint_hex(p_guid.Data4[7],out,1);\r\n\t*out = 0;\r\n}\r\n\r\n\r\nPFC_DLL_EXPORT void print_hex_raw(const void * buffer,unsigned bytes,char * p_out)\r\n{\r\n\tchar * out = p_out;\r\n\tconst unsigned char * in = (const unsigned char *) buffer;\r\n\tunsigned n;\r\n\tfor(n=0;n<bytes;n++)\r\n\t\tprint_hex(in[n],out,1);\r\n}\r\n\r\n}\r\n\r\n\r\n\r\nconst GUID pfc::guid_null = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } };"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/guid.h",
    "content": "#ifndef _PFC_GUID_H_\r\n#define _PFC_GUID_H_\r\n\r\nnamespace pfc {\r\n\r\n\tclass GUID_from_text : public GUID\r\n\t{\r\n\t\tunsigned read_hex(char c);\r\n\t\tunsigned read_byte(const char * ptr);\r\n\t\tunsigned read_word(const char * ptr);\r\n\t\tunsigned read_dword(const char * ptr);\r\n\t\tvoid read_bytes(unsigned char * out,unsigned num,const char * ptr);\r\n\r\n\tpublic:\r\n\t\tGUID_from_text(const char * text);\r\n\t};\r\n\r\n\tclass print_guid\r\n\t{\r\n\tpublic:\r\n\t\tprint_guid(const GUID & p_guid);\r\n\t\tinline operator const char * () const {return m_data;}\r\n\t\tinline const char * get_ptr() {return m_data;}\r\n\tprivate:\r\n\t\tchar m_data[64];\r\n\t};\r\n\r\n\tinline int guid_compare(const GUID & g1,const GUID & g2) {return memcmp(&g1,&g2,sizeof(GUID));}\r\n\r\n\tinline bool guid_equal(const GUID & g1,const GUID & g2) {return (g1 == g2) ? true : false;}\r\n\ttemplate<> inline int compare_t<GUID,GUID>(const GUID & p_item1,const GUID & p_item2) {return guid_compare(p_item1,p_item2);}\r\n\r\n\textern const GUID guid_null;\r\n\r\n\tPFC_DLL_EXPORT void print_hex_raw(const void * buffer,unsigned bytes,char * p_out);\r\n}\r\n\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/instance_tracker.h",
    "content": "namespace pfc {\r\n\ttemplate<typename t_object>\r\n\tclass instance_tracker_server_t {\r\n\tpublic:\r\n\t\tvoid add(t_object * p_object) {\r\n\t\t\tm_list.add_item(p_object);\r\n\t\t}\r\n\t\tvoid remove(t_object * p_object) {\r\n\t\t\tm_list.remove_item(p_object);\r\n\t\t}\r\n\r\n\t\tt_size get_count() const {return m_list.get_count();}\r\n\t\tt_object * get_item(t_size p_index) {return m_list[p_index];}\r\n\t\tt_object * operator[](t_size p_index) {return m_list[p_index];}\r\n\r\n\tprivate:\r\n\t\tptr_list_hybrid_t<t_object,4> m_list;\r\n\t};\r\n\r\n\r\n\ttemplate<typename t_object,instance_tracker_server_t<t_object> & p_server>\r\n\tclass instance_tracker_client_t {\r\n\tpublic:\r\n\t\tinstance_tracker_client_t(t_object* p_ptr) : m_ptr(NULL), m_added(false) {initialize(p_ptr);}\r\n\t\tinstance_tracker_client_t() : m_ptr(NULL), m_added(false) {}\r\n\r\n\t\tvoid initialize(t_object * p_ptr) {\r\n\t\t\tuninitialize();\r\n\t\t\tp_server.add(p_ptr);\r\n\t\t\tm_ptr = p_ptr;\r\n\t\t\tm_added = true;\r\n\t\t}\r\n\r\n\t\tvoid uninitialize() {\r\n\t\t\tif (m_added) {\r\n\t\t\t\tp_server.remove(m_ptr);\r\n\t\t\t\tm_ptr = NULL;\r\n\t\t\t\tm_added = false;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t~instance_tracker_client_t() {\r\n\t\t\tuninitialize();\r\n\t\t}\r\n\tprivate:\r\n\t\tbool m_added;\r\n\t\tt_object * m_ptr;\r\n\t};\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/int_types.h",
    "content": "#if !defined(_MSC_VER) && !defined(_EVC_VER)\r\n#include <stdint.h>\r\ntypedef int64_t t_int64;\r\ntypedef uint64_t t_uint64;\r\ntypedef int32_t t_int32;\r\ntypedef uint32_t t_uint32;\r\ntypedef int16_t t_int16;\r\ntypedef uint16_t t_uint16;\r\ntypedef int8_t t_int8;\r\ntypedef uint8_t t_uint8;\r\n#else\r\ntypedef __int64 t_int64;\r\ntypedef unsigned __int64 t_uint64;\r\ntypedef __int32 t_int32;\r\ntypedef unsigned __int32 t_uint32;\r\ntypedef __int16 t_int16;\r\ntypedef unsigned __int16 t_uint16;\r\ntypedef __int8 t_int8;\r\ntypedef unsigned __int8 t_uint8;\r\n#endif\r\n\r\ntypedef int t_int;\r\ntypedef unsigned int t_uint;\r\n\r\ntypedef float t_float32;\r\ntypedef double t_float64;\r\n\r\n\r\n\r\n#if defined(_WIN32) && !defined(_WIN64)\r\n#define __PFC_WP64 __w64\r\n#else\r\n#define __PFC_WP64\r\n#endif\r\n\r\n\r\nnamespace pfc {\r\n\ttemplate<unsigned t_bytes>\r\n\tclass sized_int_t;\r\n\r\n\ttemplate<> class sized_int_t<1> {\r\n\tpublic:\r\n\t\ttypedef t_uint8 t_unsigned;\r\n\t\ttypedef t_int8 t_signed;\r\n\t};\r\n\r\n\ttemplate<> class sized_int_t<2> {\r\n\tpublic:\r\n\t\ttypedef t_uint16 t_unsigned;\r\n\t\ttypedef t_int16 t_signed;\r\n\t};\r\n\r\n\ttemplate<> class sized_int_t<4> {\r\n\tpublic:\r\n\t\ttypedef t_uint32 t_unsigned;\r\n\t\ttypedef t_int32 t_signed;\r\n\t};\r\n\r\n\ttemplate<> class sized_int_t<8> {\r\n\tpublic:\r\n\t\ttypedef t_uint64 t_unsigned;\r\n\t\ttypedef t_int64 t_signed;\r\n\t};\r\n}\r\n\r\n\r\ntypedef pfc::sized_int_t<sizeof(void*)>::t_unsigned __PFC_WP64 t_size;\r\ntypedef pfc::sized_int_t<sizeof(void*)>::t_signed __PFC_WP64 t_ssize;\r\n\r\n\r\n#define infinite (~0)\r\n\r\nconst t_uint16 infinite16 = (t_uint16)(~0);\r\nconst t_uint32 infinite32 = (t_uint32)(~0);\r\nconst t_uint64 infinite64 = (t_uint64)(~0);\r\nconst t_size infinite_size = (t_size)(~0);\r\n\r\n\r\n#if defined(_WIN32) && !defined(_WIN64)\r\ninline t_size MulDiv_Size(t_size x,t_size y,t_size z) {return (t_size) ( ((t_uint64)x * (t_uint64)y) / (t_uint64)z );}\r\n#elif defined(_WIN64)\r\ninline t_size MulDiv_Size(t_size x,t_size y,t_size z) {return (x*y)/z;}\r\n#else\r\n#error portme\r\n#endif\r\n\r\n\r\nnamespace pfc {\r\n\ttemplate<typename T> class int_specs_t;\r\n\r\n\ttemplate<typename T>\r\n\tclass int_specs_signed_t {\r\n\tpublic:\r\n\t\tinline static T get_min() {return ((T)1<<(sizeof(T)*8-1));}\r\n\t\tinline static T get_max() {return ~((T)1<<(sizeof(T)*8-1));}\r\n\t\tenum {is_signed = true};\r\n\t};\r\n\r\n\ttemplate<typename T>\r\n\tclass int_specs_unsigned_t {\r\n\tpublic:\r\n\t\tinline static T get_min() {return (T)0;}\r\n\t\tinline static T get_max() {return (T)~0;}\r\n\t\tenum {is_signed = false};\r\n\t};\r\n\r\n\ttemplate<> class int_specs_t<char> : public int_specs_signed_t<char> {};\r\n\ttemplate<> class int_specs_t<unsigned char> : public int_specs_unsigned_t<unsigned char> {};\r\n\ttemplate<> class int_specs_t<short> : public int_specs_signed_t<short> {};\r\n\ttemplate<> class int_specs_t<unsigned short> : public int_specs_unsigned_t<unsigned short> {};\r\n\ttemplate<> class int_specs_t<int> : public int_specs_signed_t<int> {};\r\n\ttemplate<> class int_specs_t<unsigned int> : public int_specs_unsigned_t<unsigned int> {};\r\n\ttemplate<> class int_specs_t<long> : public int_specs_signed_t<long> {};\r\n\ttemplate<> class int_specs_t<unsigned long> : public int_specs_unsigned_t<unsigned long> {};\r\n\ttemplate<> class int_specs_t<long long> : public int_specs_signed_t<long long> {};\r\n\ttemplate<> class int_specs_t<unsigned long long> : public int_specs_unsigned_t<unsigned long long> {};\r\n\t\r\n\ttemplate<> class int_specs_t<wchar_t> : public int_specs_unsigned_t<wchar_t> {};\r\n\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/license.txt",
    "content": "Copyright (c) 2001-2006, Peter Pawlowski\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n\r\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \r\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. \r\nNeither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/list.h",
    "content": "#ifndef _PFC_LIST_H_\r\n#define _PFC_LIST_H_\r\n\r\nnamespace pfc {\r\n\r\ntemplate<typename T>\r\nclass NOVTABLE list_base_const_t {\r\nprivate: typedef list_base_const_t<T> t_self;\r\npublic:\r\n\tvirtual t_size get_count() const = 0;\r\n\tvirtual void get_item_ex(T& p_out, t_size n) const = 0;\r\n\r\n\tinline t_size get_size() const {return get_count();}\r\n\r\n\tinline T get_item(t_size n) const {T temp; get_item_ex(temp,n); return temp;}\r\n\tinline T operator[](t_size n) const {T temp; get_item_ex(temp,n); return temp;}\r\n\r\n\ttemplate<typename t_compare>\r\n\tt_size find_duplicates_sorted_t(t_compare p_compare,bit_array_var & p_out) const\r\n\t{\r\n\t\treturn pfc::find_duplicates_sorted_t<list_base_const_t<T> const &,t_compare>(*this,get_count(),p_compare,p_out);\r\n\t}\r\n\r\n\ttemplate<typename t_compare,typename t_permutation>\r\n\tt_size find_duplicates_sorted_permutation_t(t_compare p_compare,t_permutation const & p_permutation,bit_array_var & p_out)\r\n\t{\r\n\t\treturn pfc::find_duplicates_sorted_permutation_t<list_base_const_t<T> const &,t_compare,t_permutation>(*this,get_count(),p_compare,p_permutation,p_out);\r\n\t}\r\n\r\n\ttemplate<typename t_search>\r\n\tt_size find_item(const t_search & p_item) const//returns index of first occurance, infinite if not found\r\n\t{\r\n\t\tt_size n,max = get_count();\r\n\t\tfor(n=0;n<max;n++)\r\n\t\t\tif (get_item(n)==p_item) return n;\r\n\t\treturn ~0;\r\n\t}\r\n\r\n\ttemplate<typename t_search>\r\n\tinline bool have_item(const t_search & p_item) const {return find_item<t_search>(p_item)!=~0;}\r\n\r\n\r\n\ttemplate<typename t_compare, typename t_param>\r\n\tbool bsearch_t(t_compare p_compare,t_param const & p_param,t_size &p_index) const {\r\n\t\treturn pfc::bsearch_t(get_count(),*this,p_compare,p_param,p_index);\r\n\t}\r\n\r\n\ttemplate<typename t_compare,typename t_param,typename t_permutation>\r\n\tbool bsearch_permutation_t(t_compare p_compare,t_param const & p_param,const t_permutation & p_permutation,t_size & p_index) {\r\n\t\treturn pfc::bsearch_permutation_t(get_count(),*this,p_compare,p_param,p_permutation,p_index);\r\n\t}\r\n\r\n\ttemplate<typename t_compare,typename t_permutation>\r\n\tvoid sort_get_permutation_t(t_compare p_compare,t_permutation const & p_permutation) const {\r\n\t\tpfc::sort_get_permutation_t<list_base_const_t<T>,t_compare,t_permutation>(*this,p_compare,get_count(),p_permutation);\r\n\t}\r\n\r\n\ttemplate<typename t_compare,typename t_permutation>\r\n\tvoid sort_stable_get_permutation_t(t_compare p_compare,t_permutation const & p_permutation) const {\r\n\t\tpfc::sort_stable_get_permutation_t<list_base_const_t<T>,t_compare,t_permutation>(*this,p_compare,get_count(),p_permutation);\r\n\t}\r\n\r\n\ttemplate<typename t_callback>\r\n\tvoid enumerate(t_callback & p_callback) const {\r\n\t\tfor(t_size n = 0, m = get_count(); n < m; ++n ) {\r\n\t\t\tp_callback( (*this)[n] );\r\n\t\t}\r\n\t}\r\n\t\r\nprotected:\r\n\tlist_base_const_t() {}\r\n\t~list_base_const_t() {}\r\nprivate:\r\n\tconst t_self & operator=(const t_self &) {throw pfc::exception_not_implemented();}\r\n};\r\n\r\n\r\ntemplate<typename T>\r\nclass list_single_ref_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tlist_single_ref_t(const T & p_item,t_size p_count = 1) : m_item(p_item), m_count(p_count) {}\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T& p_out,t_size n) const {PFC_ASSERT(n<m_count); p_out = m_item;}\r\nprivate:\r\n\tconst T & m_item;\r\n\tt_size m_count;\r\n};\r\n\r\ntemplate<typename T>\r\nclass list_partial_ref_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tlist_partial_ref_t(const list_base_const_t<T> & p_list,t_size p_base,t_size p_count)\r\n\t\t: m_list(p_list), m_base(p_base), m_count(p_count)\r\n\t{\r\n\t\tPFC_ASSERT(m_base + m_count <= m_list.get_count());\r\n\t}\r\n\r\nprivate:\r\n\tconst list_base_const_t<T> & m_list;\r\n\tt_size m_base,m_count;\r\n\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T & p_out,t_size n) const {m_list.get_item_ex(p_out,n+m_base);}\r\n};\r\n\r\ntemplate<typename T,typename A>\r\nclass list_const_array_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tinline list_const_array_t(A p_data,t_size p_count) : m_data(p_data), m_count(p_count) {}\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T & p_out,t_size n) const {p_out = m_data[n];}\r\nprivate:\r\n\tA m_data;\r\n\tt_size m_count;\r\n};\r\n\r\ntemplate<typename to,typename from>\r\nclass list_const_cast_t : public list_base_const_t<to>\r\n{\r\npublic:\r\n\tlist_const_cast_t(const list_base_const_t<from> & p_from) : m_from(p_from) {}\r\n\tt_size get_count() const {return m_from.get_count();}\r\n\tvoid get_item_ex(to & p_out,t_size n) const\r\n\t{\r\n\t\tfrom temp;\r\n\t\tm_from.get_item_ex(temp,n);\r\n\t\tp_out = temp;\r\n\t}\r\nprivate:\r\n\tconst list_base_const_t<from> & m_from;\r\n};\r\n\r\ntemplate<typename T,typename A>\r\nclass ptr_list_const_array_t : public list_base_const_t<T*>\r\n{\r\npublic:\r\n\tinline ptr_list_const_array_t(A p_data,t_size p_count) : m_data(p_data), m_count(p_count) {}\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T* & p_out,t_size n) const {p_out = &m_data[n];}\r\nprivate:\r\n\tA m_data;\r\n\tt_size m_count;\r\n};\r\ntemplate<typename T>\r\nclass list_const_ptr_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tinline list_const_ptr_t(const T * p_data,t_size p_count) : m_data(p_data), m_count(p_count) {}\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T & p_out,t_size n) const {p_out = m_data[n];}\r\nprivate:\r\n\tconst T * m_data;\r\n\tt_size m_count;\r\n};\r\n\r\ntemplate<typename T>\r\nclass NOVTABLE list_base_t : public list_base_const_t<T> {\r\nprivate:\r\n\ttypedef list_base_t<T> t_self;\r\npublic:\r\n\tclass NOVTABLE sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual int compare(const T& p_item1,const T& p_item2) = 0;\r\n\t};\r\n\r\n\tvirtual void filter_mask(const bit_array & mask) = 0;\r\n\tvirtual t_size insert_items(const list_base_const_t<T> & items,t_size base) = 0;\r\n\tvirtual void reorder_partial(t_size p_base,const t_size * p_data,t_size p_count) = 0;\r\n\tvirtual void sort(sort_callback & p_callback) = 0;\r\n\tvirtual void sort_stable(sort_callback & p_callback) = 0;\r\n\tvirtual void replace_item(t_size p_index,const T& p_item) = 0;\r\n\tvirtual void swap_item_with(t_size p_index,T & p_item) = 0;\r\n\tvirtual void swap_items(t_size p_index1,t_size p_index2) = 0;\r\n\r\n\tinline void reorder(const t_size * p_data) {reorder_partial(0,p_data,this->get_count());}\r\n\r\n\tinline t_size insert_item(const T & item,t_size base) {return insert_items(list_single_ref_t<T>(item),base);}\r\n\tt_size insert_items_repeat(const T & item,t_size num,t_size base) {return insert_items(list_single_ref_t<T>(item,num),base);}\r\n\tinline t_size add_items_repeat(T item,t_size num) {return insert_items_repeat(item,num,this->get_count());}\r\n\tt_size insert_items_fromptr(const T* source,t_size num,t_size base) {return insert_items(list_const_ptr_t<T>(source,num),base);}\r\n\tinline t_size add_items_fromptr(const T* source,t_size num) {return insert_items_fromptr(source,num,this->get_count());}\r\n\r\n\tinline t_size add_items(const list_base_const_t<T> & items) {return insert_items(items,this->get_count());}\r\n\tinline t_size add_item(const T& item) {return insert_item(item,this->get_count());}\r\n\r\n\tinline void remove_mask(const bit_array & mask) {filter_mask(bit_array_not(mask));}\r\n\tinline void remove_all() {filter_mask(bit_array_false());}\r\n\tinline void truncate(t_size val) {if (val < this->get_count()) remove_mask(bit_array_range(val,this->get_count()-val,true));}\r\n\t\r\n\tinline T replace_item_ex(t_size p_index,const T & p_item) {T ret = p_item;swap_item_with(p_index,ret);return ret;}\r\n\r\n\tinline T operator[](t_size n) const {return this->get_item(n);}\r\n\r\n\ttemplate<typename t_compare>\r\n\tclass sort_callback_impl_t : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_impl_t(t_compare p_compare) : m_compare(p_compare) {}\r\n\t\tint compare(const T& p_item1,const T& p_item2) {return m_compare(p_item1,p_item2);}\r\n\tprivate:\r\n\t\tt_compare m_compare;\r\n\t};\r\n\r\n\tclass sort_callback_auto : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tint compare(const T& p_item1,const T& p_item2) {return pfc::compare_t(p_item1,p_item2);}\r\n\t};\r\n\r\n\tvoid sort() {sort(sort_callback_auto());}\r\n\ttemplate<typename t_compare> void sort_t(t_compare p_compare) {sort(sort_callback_impl_t<t_compare>(p_compare));}\r\n\ttemplate<typename t_compare> void sort_stable_t(t_compare p_compare) {sort_stable(sort_callback_impl_t<t_compare>(p_compare));}\r\n\r\n\ttemplate<typename t_compare> void sort_remove_duplicates_t(t_compare p_compare)\r\n\t{\r\n\t\tsort_t<t_compare>(p_compare);\r\n\t\tbit_array_bittable array(this->get_count());\t\t\r\n\t\tif (this->template find_duplicates_sorted_t<t_compare>(p_compare,array) > 0)\r\n\t\t\tremove_mask(array);\r\n\t}\r\n\r\n\ttemplate<typename t_compare> void sort_stable_remove_duplicates_t(t_compare p_compare)\r\n\t{\r\n\t\tsort_stable_t<t_compare>(p_compare);\r\n\t\tbit_array_bittable array(this->get_count());\t\t\r\n\t\tif (this->template find_duplicates_sorted_t<t_compare>(p_compare,array) > 0)\r\n\t\t\tremove_mask(array);\r\n\t}\r\n\r\n\r\n\ttemplate<typename t_compare> void remove_duplicates_t(t_compare p_compare)\r\n\t{\r\n\t\torder_helper order(this->get_count());\r\n\t\tsort_get_permutation_t<t_compare,order_helper&>(p_compare,order);\r\n\t\tbit_array_bittable array(this->get_count());\r\n\t\tif (this->template find_duplicates_sorted_permutation_t<t_compare,order_helper const&>(p_compare,order,array) > 0)\r\n\t\t\tremove_mask(array);\r\n\t}\r\n\r\n\ttemplate<typename t_func>\r\n\tvoid for_each(t_func p_func) {\r\n\t\tt_size n,max=this->get_count();\r\n\t\tfor(n=0;n<max;n++) p_func(this->get_item(n));\r\n\t}\r\n\r\n\ttemplate<typename t_func>\r\n\tvoid for_each(t_func p_func,const bit_array & p_mask) {\r\n\t\tt_size n,max=this->get_count();\r\n\t\tfor(n=p_mask.find(true,0,max);n<max;n=p_mask.find(true,n+1,max-n-1)) {\r\n\t\t\tp_func(this->get_item(n));\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_releasefunc>\r\n\tvoid remove_mask_ex(const bit_array & p_mask,t_releasefunc p_func) {\r\n\t\tthis->template for_each<t_releasefunc>(p_func,p_mask);\r\n\t\tremove_mask(p_mask);\r\n\t}\r\n\r\n\ttemplate<typename t_releasefunc>\r\n\tvoid remove_all_ex(t_releasefunc p_func) {\r\n\t\tthis->template for_each<t_releasefunc>(p_func);\r\n\t\tremove_all();\r\n\t}\r\n\r\n\tconst t_self & operator=(const t_self & p_source) {remove_all(); add_items(p_source);return *this;}\r\nprotected:\r\n\tlist_base_t() {}\r\n\t~list_base_t() {}\r\n};\r\n\r\n\r\ntemplate<typename T,typename t_storage>\r\nclass list_impl_t : public list_base_t<T>\r\n{\r\npublic:\r\n\tlist_impl_t() {}\r\n\tlist_impl_t(const list_impl_t<T,t_storage> & p_source) { *this = p_source; }\r\n\r\n\tvoid prealloc(t_size count) {m_buffer.prealloc(count);}\r\n\r\n\tvoid set_count(t_size p_count) {m_buffer.set_size(p_count);}\r\n\tvoid set_size(t_size p_count) {m_buffer.set_size(p_count);}\r\n\r\n\tt_size insert_item(const T& item,t_size idx)\r\n\t{\r\n\t\tt_size max = m_buffer.get_size();\r\n\t\tif (idx > max) idx = max;\r\n\t\tmax++;\r\n\t\tm_buffer.set_size(max);\r\n\t\tt_size n;\r\n\t\tfor(n=max-1;n>idx;n--)\r\n\t\t\tm_buffer[n]=m_buffer[n-1];\r\n\t\tm_buffer[idx]=item;\r\n\t\treturn idx;\r\n\t}\r\n\r\n\tT remove_by_idx(t_size idx)\r\n\t{\r\n\t\tT ret = m_buffer[idx];\r\n\t\tt_size n;\r\n\t\tt_size max = m_buffer.get_size();\r\n\t\tfor(n=idx+1;n<max;n++)\r\n\t\t{\r\n\t\t\tpfc::swap_t(m_buffer[n-1],m_buffer[n]);\r\n\t\t}\r\n\t\tm_buffer.set_size(max-1);\r\n\t\treturn ret;\r\n\t}\r\n\r\n\r\n\tinline void get_item_ex(T& p_out,t_size n) const\r\n\t{\r\n\t\tPFC_ASSERT(n>=0);\r\n\t\tPFC_ASSERT(n<get_count());\r\n\t\tp_out = m_buffer[n];\r\n\t}\r\n\r\n\tinline const T& get_item_ref(t_size n) const\r\n\t{\r\n\t\tPFC_ASSERT(n>=0);\r\n\t\tPFC_ASSERT(n<get_count());\r\n\t\treturn m_buffer[n];\r\n\t}\r\n\r\n\tinline T get_item(t_size n) const\r\n\t{\r\n\t\tPFC_ASSERT(n >= 0);\r\n\t\tPFC_ASSERT(n < get_count() );\r\n\t\treturn m_buffer[n];\r\n\t};\r\n\r\n\tinline t_size get_count() const {return m_buffer.get_size();}\r\n\tinline t_size get_size() const {return get_count();}\r\n\r\n\tinline const T & operator[](t_size n) const\r\n\t{\r\n\t\tPFC_ASSERT(n>=0);\r\n\t\tPFC_ASSERT(n<get_count());\r\n\t\treturn m_buffer[n];\r\n\t}\r\n\r\n\tinline const T* get_ptr() const {return m_buffer.get_ptr();}\r\n\tinline T* get_ptr() {return m_buffer.get_ptr();}\r\n\r\n\tinline T& operator[](t_size n) {return m_buffer[n];}\r\n\r\n\tinline void remove_from_idx(t_size idx,t_size num)\r\n\t{\r\n\t\tremove_mask(bit_array_range(idx,num));\r\n\t}\r\n\r\n\tt_size insert_items(const list_base_const_t<T> & source,t_size base)\r\n\t{\r\n\t\tt_size count = get_count();\r\n\t\tif (base>count) base = count;\r\n\t\tt_size num = source.get_count();\r\n\t\tm_buffer.set_size(count+num);\r\n\t\tif (count > base)\r\n\t\t{\r\n\t\t\tt_size n;\r\n\t\t\tfor(n=count-1;(int)n>=(int)base;n--)\r\n\t\t\t{\r\n\t\t\t\tpfc::swap_t(m_buffer[n+num],m_buffer[n]);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\tt_size n;\r\n\t\t\tfor(n=0;n<num;n++)\r\n\t\t\t{\r\n\t\t\t\tsource.get_item_ex(m_buffer[n+base],n);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn base;\r\n\r\n\t}\r\n\r\n\tvoid get_items_mask(list_impl_t<T,t_storage> & out,const bit_array & mask)\r\n\t{\r\n\t\tt_size n,count = get_count();\r\n\t\tfor_each_bit_array(n,mask,true,0,count)\r\n\t\t\tout.add_item(m_buffer[n]);\r\n\t}\r\n\r\n\tvoid filter_mask(const bit_array & mask)\r\n\t{\r\n\t\tt_size n,count = get_count(), total = 0;\r\n\r\n\t\tn = total = mask.find(false,0,count);\r\n\r\n\t\tif (n<count)\r\n\t\t{\r\n\t\t\tfor(n=mask.find(true,n+1,count-n-1);n<count;n=mask.find(true,n+1,count-n-1))\r\n\t\t\t\tpfc::swap_t(m_buffer[total++],m_buffer[n]);\r\n\r\n\t\t\tm_buffer.set_size(total);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid replace_item(t_size idx,const T& item)\r\n\t{\r\n\t\tPFC_ASSERT(idx>=0);\r\n\t\tPFC_ASSERT(idx<get_count());\r\n\t\tm_buffer[idx] = item;\r\n\t}\r\n\r\n\tvoid sort()\r\n\t{\r\n\t\tpfc::sort_callback_impl_auto_wrap_t<t_storage> wrapper(m_buffer);\r\n\t\tpfc::sort(wrapper,get_count());\r\n\t}\r\n\r\n\ttemplate<typename t_compare>\r\n\tvoid sort_t(t_compare p_compare)\r\n\t{\r\n\t\tpfc::sort_callback_impl_simple_wrap_t<t_storage,t_compare> wrapper(m_buffer,p_compare);\r\n\t\tpfc::sort(wrapper,get_count());\r\n\t}\r\n\r\n\ttemplate<typename t_compare>\r\n\tvoid sort_stable_t(t_compare p_compare)\r\n\t{\r\n\t\tpfc::sort_callback_impl_simple_wrap_t<t_storage,t_compare> wrapper(m_buffer,p_compare);\r\n\t\tpfc::sort_stable(wrapper,get_count());\r\n\t}\r\n\tinline void reorder_partial(t_size p_base,const t_size * p_order,t_size p_count)\r\n\t{\r\n\t\tPFC_ASSERT(p_base+p_count<=get_count());\r\n\t\tpfc::reorder_partial_t(m_buffer,p_base,p_order,p_count);\r\n\t}\r\n\r\n\ttemplate<typename t_compare>\r\n\tt_size find_duplicates_sorted_t(t_compare p_compare,bit_array_var & p_out) const\r\n\t{\r\n\t\treturn pfc::find_duplicates_sorted_t<list_impl_t<T,t_storage> const &,t_compare>(*this,get_count(),p_compare,p_out);\r\n\t}\r\n\r\n\ttemplate<typename t_compare,typename t_permutation>\r\n\tt_size find_duplicates_sorted_permutation_t(t_compare p_compare,t_permutation p_permutation,bit_array_var & p_out)\r\n\t{\r\n\t\treturn pfc::find_duplicates_sorted_permutation_t<list_impl_t<T,t_storage> const &,t_compare,t_permutation>(*this,get_count(),p_compare,p_permutation,p_out);\r\n\t}\r\n\r\n\r\nprivate:\r\n\tclass sort_callback_wrapper\r\n\t{\r\n\tpublic:\r\n\t\texplicit inline sort_callback_wrapper(sort_callback & p_callback) : m_callback(p_callback) {}\r\n\t\tinline int operator()(const T& item1,const T& item2) const {return m_callback.compare(item1,item2);}\r\n\tprivate:\r\n\t\tsort_callback & m_callback;\r\n\t};\r\npublic:\r\n\tvoid sort(sort_callback & p_callback)\r\n\t{\r\n\t\tsort_t(sort_callback_wrapper(p_callback));\r\n\t}\r\n\t\r\n\tvoid sort_stable(sort_callback & p_callback)\r\n\t{\r\n\t\tsort_stable_t(sort_callback_wrapper(p_callback));\r\n\t}\r\n\r\n\tvoid remove_mask(const bit_array & mask) {filter_mask(bit_array_not(mask));}\r\n\r\n\tvoid remove_mask(const bool * mask) {remove_mask(bit_array_table(mask,get_count()));}\r\n\tvoid filter_mask(const bool * mask) {filter_mask(bit_array_table(mask,get_count()));}\r\n\r\n\tt_size add_item(const T& item)\r\n\t{\r\n\t\tt_size idx = get_count();\r\n\t\tinsert_item(item,idx);\r\n\t\treturn idx;\r\n\t}\r\n\r\n\tvoid remove_all() {remove_mask(bit_array_true());}\r\n\r\n\tvoid remove_item(const T& item)\r\n\t{\r\n\t\tt_size n,max = get_count();\r\n\t\tbit_array_bittable mask(max);\r\n\t\tfor(n=0;n<max;n++)\r\n\t\t\tmask.set(n,get_item(n)==item);\r\n\t\tremove_mask(mask);\t\t\r\n\t}\r\n\r\n\tvoid swap_item_with(t_size p_index,T & p_item)\r\n\t{\r\n\t\tPFC_ASSERT(p_index < get_count());\r\n\t\tpfc::swap_t(m_buffer[p_index],p_item);\r\n\t}\r\n\r\n\tvoid swap_items(t_size p_index1,t_size p_index2) \r\n\t{\r\n\t\tPFC_ASSERT(p_index1 < get_count());\r\n\t\tPFC_ASSERT(p_index1 < get_count());\r\n\t\tpfc::swap_t(m_buffer[p_index1],m_buffer[p_index2]);\r\n\t}\r\n\r\n\tinline static void g_swap(list_impl_t<T,t_storage> & p_item1,list_impl_t<T,t_storage> & p_item2)\r\n\t{\r\n\t\tpfc::swap_t(p_item1.m_buffer,p_item2.m_buffer);\r\n\t}\r\n\r\n\ttemplate<typename t_search>\r\n\tt_size find_item(const t_search & p_item) const//returns index of first occurance, infinite if not found\r\n\t{\r\n\t\tt_size n,max = get_count();\r\n\t\tfor(n=0;n<max;n++)\r\n\t\t\tif (m_buffer[n]==p_item) return n;\r\n\t\treturn ~0;\r\n\t}\r\n\r\n\ttemplate<typename t_search>\r\n\tinline bool have_item(const t_search & p_item) const {return this->template find_item<t_search>(p_item)!=~0;}\r\n\r\nprotected:\r\n\tt_storage m_buffer;\r\n};\r\n\r\ntemplate<typename t_item, template<typename> class t_alloc = pfc::alloc_fast >\r\nclass list_t : public list_impl_t<t_item,pfc::array_t<t_item,t_alloc> > { };\r\n\r\ntemplate<typename t_item, t_size p_fixed_count, template<typename> class t_alloc = pfc::alloc_fast >\r\nclass list_hybrid_t : public list_impl_t<t_item,pfc::array_hybrid_t<t_item,p_fixed_count,t_alloc> > {};\r\n\r\ntemplate<typename T>\r\nclass ptr_list_const_cast_t : public list_base_const_t<const T *>\r\n{\r\npublic:\r\n\tinline ptr_list_const_cast_t(const list_base_const_t<T*> & p_param) : m_param(p_param) {}\r\n\tt_size get_count() const {return m_param.get_count();}\r\n\tvoid get_item_ex(const T * & p_out,t_size n) const {T* temp; m_param.get_item_ex(temp,n); p_out = temp;}\r\nprivate:\r\n\tconst list_base_const_t<T*> & m_param;\r\n\r\n};\r\n\r\n\r\ntemplate<typename T,typename P>\r\nclass list_const_permutation_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tinline list_const_permutation_t(const list_base_const_t<T> & p_list,P p_permutation) : m_list(p_list), m_permutation(p_permutation) {}\r\n\tt_size get_count() const {return m_list.get_count();}\r\n\tvoid get_item_ex(T & p_out,t_size n) const {m_list.get_item_ex(p_out,m_permutation[n]);}\r\nprivate:\r\n\tP m_permutation;\r\n\tconst list_base_const_t<T> & m_list;\r\n};\r\n\r\n\r\ntemplate<class T>\r\nclass list_permutation_t : public list_base_const_t<T>\r\n{\r\npublic:\r\n\tt_size get_count() const {return m_count;}\r\n\tvoid get_item_ex(T & p_out,t_size n) const {m_base.get_item_ex(p_out,m_order[n]);}\r\n\tlist_permutation_t(const list_base_const_t<T> & p_base,const t_size * p_order,t_size p_count)\r\n\t\t: m_base(p_base), m_order(p_order), m_count(p_count)\r\n\t{\r\n\t\tPFC_ASSERT(m_base.get_count() >= m_count);\r\n\t}\r\nprivate:\r\n\tconst list_base_const_t<T> & m_base;\r\n\tconst t_size * m_order;\r\n\tt_size m_count;\r\n};\r\n\r\n}\r\n#endif //_PFC_LIST_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/map.h",
    "content": "#ifndef _MAP_T_H_INCLUDED_\r\n#define _MAP_T_H_INCLUDED_\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<typename t_destination> class __map_overwrite_wrapper {\r\n\tpublic:\r\n\t\t__map_overwrite_wrapper(t_destination & p_destination) : m_destination(p_destination) {}\r\n\t\ttemplate<typename t_from,typename t_to> void operator() (const t_from & p_from,const t_to & p_to) {m_destination.set(p_from,p_to);}\r\n\tprivate:\r\n\t\tt_destination & m_destination;\r\n\t};\r\n\r\n\ttemplate<typename t_storage_from, typename t_storage_to, typename t_comparator = comparator_default>\r\n\tclass map_t {\r\n\tprivate:\r\n\t\ttypedef map_t<t_storage_from,t_storage_to,t_comparator> t_self;\r\n\tpublic:\r\n\t\ttemplate<typename t_from,typename t_to>\r\n\t\tvoid set(const t_from & p_from, const t_to & p_to) {\r\n\t\t\tbool isnew;\r\n\t\t\tt_storage & storage = m_data.add_ex(t_search_set<t_from,t_to>(p_from,p_to), isnew);\r\n\t\t\tif (!isnew) storage.m_to = p_to;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tt_storage_to & find_or_add(t_from const & p_from) {\r\n\t\t\treturn m_data.add(t_search_query<t_from>(p_from)).m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tt_storage_to & find_or_add_ex(t_from const & p_from,bool & p_isnew) {\r\n\t\t\treturn m_data.add_ex(t_search_query<t_from>(p_from),p_isnew).m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tbool have_item(const t_from & p_from) const {\r\n\t\t\treturn m_data.have_item(t_search_query<t_from>(p_from));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from,typename t_to>\r\n\t\tbool query(const t_from & p_from,t_to & p_to) const {\r\n\t\t\tconst t_storage * storage = m_data.find_ptr(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return false;\r\n\t\t\tp_to = storage->m_to;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tconst t_storage_to * query_ptr(const t_from & p_from) const {\r\n\t\t\tconst t_storage * storage = m_data.find_ptr(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return NULL;\r\n\t\t\treturn &storage->m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tt_storage_to * query_ptr(const t_from & p_from) {\r\n\t\t\tt_storage * storage = m_data.find_ptr(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return NULL;\r\n\t\t\treturn &storage->m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_from>\r\n\t\tconst t_storage_to * query_nearest_ptr(t_from & p_from) const {\r\n\t\t\tconst t_storage * storage = m_data.find_nearest_item<inclusive,above>(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return NULL;\r\n\t\t\tp_from = storage->m_from;\r\n\t\t\treturn &storage->m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_from>\r\n\t\tt_storage_to * query_nearest_ptr(t_from & p_from) {\r\n\t\t\tt_storage * storage = m_data.find_nearest_item<inclusive,above>(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return NULL;\r\n\t\t\tp_from = storage->m_from;\r\n\t\t\treturn &storage->m_to;\r\n\t\t}\r\n\r\n\t\ttemplate<bool inclusive,bool above,typename t_from,typename t_to>\r\n\t\tbool query_nearest(t_from & p_from,t_to & p_to) const {\r\n\t\t\tconst t_storage * storage = m_data.find_nearest_item<inclusive,above>(t_search_query<t_from>(p_from));\r\n\t\t\tif (storage == NULL) return false;\r\n\t\t\tp_from = storage->m_from;\r\n\t\t\tp_to = storage->m_to;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_from>\r\n\t\tvoid remove(const t_from & p_from) {\r\n\t\t\tm_data.remove_item(t_search_query<t_from>(p_from));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) const {\r\n\t\t\tm_data.enumerate(enumeration_wrapper<t_callback>(p_callback));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tvoid enumerate(t_callback & p_callback) {\r\n\t\t\tm_data.__enumerate(enumeration_wrapper_var<t_callback>(p_callback));\r\n\t\t}\r\n\r\n\r\n\t\tt_size get_count() const {return m_data.get_count();}\r\n\r\n\t\tvoid remove_all() {m_data.remove_all();}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tvoid overwrite(const t_source & p_source) {\r\n\t\t\t__map_overwrite_wrapper<t_self> wrapper(*this);\r\n\t\t\tp_source.enumerate(wrapper);\r\n\t\t}\r\n\r\n\t\t//backwards compatibility method wrappers\r\n\t\ttemplate<typename t_from> bool exists(const t_from & p_from) const {return have_item(p_from);}\r\n\r\n\tprivate:\r\n\t\ttemplate<typename t_from>\r\n\t\tstruct t_search_query {\r\n\t\t\tt_search_query(const t_from & p_from) : m_from(p_from) {}\r\n\t\t\tt_from const & m_from;\r\n\t\t};\r\n\t\ttemplate<typename t_from,typename t_to>\r\n\t\tstruct t_search_set {\r\n\t\t\tt_search_set(const t_from & p_from, const t_to & p_to) : m_from(p_from), m_to(p_to) {}\r\n\r\n\t\t\tt_from const & m_from;\r\n\t\t\tt_to const & m_to;\r\n\t\t};\r\n\r\n\t\tstruct t_storage {\r\n\t\t\tt_storage_from m_from;\r\n\t\t\tt_storage_to m_to;\r\n\r\n\r\n\t\t\t\r\n\t\t\ttemplate<typename t_from>\r\n\t\t\tt_storage(t_search_query<t_from> const & p_source) : m_from(p_source.m_from), m_to() {}\r\n\r\n\t\t\ttemplate<typename t_from,typename t_to>\r\n\t\t\tt_storage(t_search_set<t_from,t_to> const & p_source) : m_from(p_source.m_from), m_to(p_source.m_to) {}\r\n\t\t};\r\n\r\n\t\tclass comparator_wrapper {\r\n\t\tpublic:\r\n\t\t\ttemplate<typename t_other>\r\n\t\t\tinline static int compare(const t_storage & p_item1,const t_other & p_item2) {\r\n\t\t\t\treturn t_comparator::compare(p_item1.m_from,p_item2.m_from);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tclass enumeration_wrapper {\r\n\t\tpublic:\r\n\t\t\tenumeration_wrapper(t_callback & p_callback) : m_callback(p_callback) {}\r\n\t\t\tvoid operator()(const t_storage & p_item) {m_callback(p_item.m_from,p_item.m_to);}\r\n\t\tprivate:\r\n\t\t\tt_callback & m_callback;\r\n\t\t};\r\n\r\n\t\ttemplate<typename t_callback>\r\n\t\tclass enumeration_wrapper_var {\r\n\t\tpublic:\r\n\t\t\tenumeration_wrapper_var(t_callback & p_callback) : m_callback(p_callback) {}\r\n\t\t\tvoid operator()(t_storage & p_item) {m_callback(safe_cast<t_storage_from const&>(p_item.m_from),p_item.m_to);}\r\n\t\tprivate:\r\n\t\t\tt_callback & m_callback;\r\n\t\t};\r\n\r\n\t\ttypedef avltree_t<t_storage,comparator_wrapper> t_content;\r\n\r\n\t\tt_content m_data;\r\n\tpublic:\r\n\t\ttypedef traits_t<t_content> traits;\r\n\t};\r\n\r\n\ttemplate<typename t_storage_from, typename t_storage_to, typename t_comparator>\r\n\tclass traits_t<map_t<t_storage_from,t_storage_to,t_comparator> > : public map_t<t_storage_from,t_storage_to,t_comparator>::traits {};\r\n\r\n\r\n}\r\n\r\n#endif //_MAP_T_H_INCLUDED_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/mem_block_mgr.h",
    "content": "#ifndef _MEM_BLOCK_MGR_H_\r\n#define _MEM_BLOCK_MGR_H_\r\n\r\n#error DEPRECATED\r\n\r\n\r\ntemplate<class T>\r\nclass mem_block_manager\r\n{\r\n\tstruct entry\r\n\t{\r\n\t\tmem_block_t<T> block;\r\n\t\tbool used;\r\n\t};\r\n\tptr_list_t<entry> list;\r\npublic:\r\n\tT * copy(const T* ptr,int size)\r\n\t{\r\n\t\tint n;\r\n\t\tint found_size = -1,found_index = -1;\r\n\t\tfor(n=0;n<list.get_count();n++)\r\n\t\t{\r\n\t\t\tif (!list[n]->used)\r\n\t\t\t{\r\n\t\t\t\tint block_size = list[n]->block.get_size();\r\n\t\t\t\tif (found_size<0)\r\n\t\t\t\t{\r\n\t\t\t\t\tfound_index=n; found_size = block_size;\r\n\t\t\t\t}\r\n\t\t\t\telse if (found_size<size)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (block_size>found_size)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfound_index=n; found_size = block_size;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse if (found_size>size)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (block_size>=size && block_size<found_size)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tfound_index=n; found_size = block_size;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (found_size==size) break;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (found_index>=0)\r\n\t\t{\r\n\t\t\tlist[found_index]->used = true;\r\n\t\t\treturn list[found_index]->block.copy(ptr,size);\t\t\t\t\r\n\t\t}\r\n\t\tentry * new_entry = new entry;\r\n\t\tnew_entry->used = true;\r\n\t\tlist.add_item(new_entry);\r\n\t\treturn new_entry->block.copy(ptr,size);\r\n\t}\r\n\t\r\n\tvoid mark_as_free()\r\n\t{\r\n\t\tint n;\r\n\t\tfor(n=0;n<list.get_count();n++)\r\n\t\t{\r\n\t\t\tlist[n]->used = false;\r\n\t\t}\r\n\t}\r\n\r\n\t~mem_block_manager() {list.delete_all();}\r\n};\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/order_helper.h",
    "content": "class order_helper\r\n{\r\n\tpfc::array_t<t_size> m_data;\r\npublic:\r\n\torder_helper(t_size p_size) {\r\n\t\tm_data.set_size(p_size);\r\n\t\tfor(t_size n=0;n<p_size;n++) m_data[n]=n;\r\n\t}\r\n\r\n\torder_helper(const order_helper & p_order) {*this = p_order;}\r\n\r\n\r\n\ttemplate<typename t_int>\r\n\tstatic void g_fill(t_int * p_order,const t_size p_count) {\r\n\t\tt_size n; for(n=0;n<p_count;n++) p_order[n] = (t_int)n;\r\n\t}\r\n\r\n\ttemplate<typename t_array>\r\n\tstatic void g_fill(t_array & p_array) {\r\n\t\tt_size n; const t_size max = pfc::array_size_t(p_array);\r\n\t\tfor(n=0;n<max;n++) p_array[n] = n;\r\n\t}\r\n\r\n\r\n\tt_size get_item(t_size ptr) const {return m_data[ptr];}\r\n\r\n\tt_size & operator[](t_size ptr) {return m_data[ptr];}\r\n\tt_size operator[](t_size ptr) const {return m_data[ptr];}\r\n\r\n\tstatic void g_swap(t_size * p_data,t_size ptr1,t_size ptr2);\r\n\tinline void swap(t_size ptr1,t_size ptr2) {pfc::swap_t(m_data[ptr1],m_data[ptr2]);}\r\n\r\n\tconst t_size * get_ptr() const {return m_data.get_ptr();}\r\n\r\n\tstatic t_size g_find_reverse(const t_size * order,t_size val);\r\n\tinline t_size find_reverse(t_size val) {return g_find_reverse(m_data.get_ptr(),val);}\r\n\r\n\tstatic void g_reverse(t_size * order,t_size base,t_size count);\r\n\tinline void reverse(t_size base,t_size count) {g_reverse(m_data.get_ptr(),base,count);}\r\n\r\n\tt_size get_count() const {return m_data.get_size();}\r\n};\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/other.cpp",
    "content": "#include \"pfc.h\"\r\n\r\n#include <intrin.h>\r\n\r\n\r\nvoid order_helper::g_swap(t_size * data,t_size ptr1,t_size ptr2)\r\n{\r\n\tt_size temp = data[ptr1];\r\n\tdata[ptr1] = data[ptr2];\r\n\tdata[ptr2] = temp;\r\n}\r\n\r\n\r\nt_size order_helper::g_find_reverse(const t_size * order,t_size val)\r\n{\r\n\tt_size prev = val, next = order[val];\r\n\twhile(next != val)\r\n\t{\r\n\t\tprev = next;\r\n\t\tnext = order[next];\r\n\t}\r\n\treturn prev;\r\n}\r\n\r\n\r\nvoid order_helper::g_reverse(t_size * order,t_size base,t_size count)\r\n{\r\n\tt_size max = count>>1;\r\n\tt_size n;\r\n\tt_size base2 = base+count-1;\r\n\tfor(n=0;n<max;n++)\r\n\t\tg_swap(order,base+n,base2-n);\r\n}\r\n\r\n\r\nvoid pfc::crash() {\r\n#if 0 //def _MSC_VER\r\n\t__debugbreak();\r\n#else\r\n\t*(char*)NULL = 0;\r\n#endif\r\n}\r\n\r\n\r\nvoid pfc::byteswap_raw(void * p_buffer,const t_size p_bytes) {\r\n\tt_uint8 * ptr = (t_uint8*)p_buffer;\r\n\tt_size n;\r\n\tfor(n=0;n<p_bytes>>1;n++) swap_t(ptr[n],ptr[p_bytes-n-1]);\r\n}\r\n\r\n#if defined(_DEBUG) && defined(_WIN32)\r\nvoid pfc::myassert(const wchar_t * _Message, const wchar_t *_File, unsigned _Line) { \r\n\tif (IsDebuggerPresent()) pfc::crash();\r\n\t_wassert(_Message,_File,_Line);\r\n}\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/other.h",
    "content": "#ifndef _PFC_OTHER_H_\r\n#define _PFC_OTHER_H_\r\n\r\nnamespace pfc {\r\n\ttemplate<class T>\r\n\tclass vartoggle_t {\r\n\t\tT oldval; T & var;\r\n\tpublic:\r\n\t\tvartoggle_t(T & p_var,const T & val) : var(p_var) {\r\n\t\t\toldval = var;\r\n\t\t\tvar = val;\r\n\t\t}\r\n\t\t~vartoggle_t() {var = oldval;}\r\n\t};\r\n\r\n\ttypedef vartoggle_t<bool> booltoggle;\r\n};\r\n\r\n#ifdef _MSC_VER\r\n\r\nclass fpu_control\r\n{\r\n\tunsigned old_val;\r\n\tunsigned mask;\r\npublic:\r\n\tinline fpu_control(unsigned p_mask,unsigned p_val)\r\n\t{\r\n\t\tmask = p_mask;\r\n\t\t_controlfp_s(&old_val,p_val,mask);\r\n\t}\r\n\tinline ~fpu_control()\r\n\t{\r\n\t\tunsigned dummy;\r\n\t\t_controlfp_s(&dummy,old_val,mask);\r\n\t}\r\n};\r\n\r\nclass fpu_control_roundnearest : private fpu_control\r\n{\r\npublic:\r\n\tfpu_control_roundnearest() : fpu_control(_MCW_RC,_RC_NEAR) {}\r\n};\r\n\r\nclass fpu_control_flushdenormal : private fpu_control\r\n{\r\npublic:\r\n\tfpu_control_flushdenormal() : fpu_control(_MCW_DN,_DN_FLUSH) {}\r\n};\r\n\r\nclass fpu_control_default : private fpu_control\r\n{\r\npublic:\r\n\tfpu_control_default() : fpu_control(_MCW_DN|_MCW_RC,_DN_FLUSH|_RC_NEAR) {}\r\n};\r\n\r\n#ifdef _M_IX86\r\nclass sse_control {\r\npublic:\r\n\tsse_control(unsigned p_mask,unsigned p_val) : m_mask(p_mask) {\r\n\t\t__control87_2(p_val,p_mask,NULL,&m_oldval);\r\n\t}\r\n\t~sse_control() {\r\n\t\t__control87_2(m_oldval,m_mask,NULL,&m_oldval);\r\n\t}\r\nprivate:\r\n\tunsigned m_mask,m_oldval;\r\n};\r\nclass sse_control_flushdenormal : private sse_control {\r\npublic:\r\n\tsse_control_flushdenormal() : sse_control(_MCW_DN,_DN_FLUSH) {}\r\n};\r\n#endif\r\n\r\n#endif\r\n\r\nnamespace pfc {\r\n\tclass refcounter {\r\n\tpublic:\r\n\t\trefcounter(long p_val = 0) : m_val(p_val) {}\r\n#ifdef _WINDOWS\r\n\t\tlong operator++() {return InterlockedIncrement(&m_val);}\r\n\t\tlong operator--() {return InterlockedDecrement(&m_val);}\r\n#else\r\n\t\tlong operator++() {return ++m_val;}\r\n\t\tlong operator--() {return --m_val;}\r\n#pragma message(\"PORTME\")\r\n#endif\r\n\tprivate:\r\n\t\tlong m_val;\r\n\t};\r\n\r\n\tclass releaser_delete {\r\n\tpublic:\r\n\t\ttemplate<typename T> static void release(T* p_ptr) {delete p_ptr;}\r\n\t};\r\n\tclass releaser_delete_array {\r\n\tpublic:\r\n\t\ttemplate<typename T> static void release(T* p_ptr) {delete[] p_ptr;}\r\n\t};\r\n\tclass releaser_free {\r\n\tpublic:\r\n\t\tstatic void release(void * p_ptr) {free(p_ptr);}\r\n\t};\r\n\r\n\t//! Assumes t_freefunc to never throw exceptions.\r\n\ttemplate<typename T,typename t_releaser = releaser_delete >\r\n\tclass ptrholder_t {\r\n\tprivate:\r\n\t\ttypedef ptrholder_t<T,t_releaser> t_self;\r\n\tpublic:\r\n\t\tinline ptrholder_t(T* p_ptr) : m_ptr(p_ptr) {}\r\n\t\tinline ptrholder_t() : m_ptr(NULL) {}\r\n\t\tinline ~ptrholder_t() {t_releaser::release(m_ptr);}\r\n\t\tinline bool is_valid() const {return m_ptr != NULL;}\r\n\t\tinline bool is_empty() const {return m_ptr == NULL;}\r\n\t\tinline T* operator->() const {return m_ptr;}\r\n\t\tinline T* get_ptr() const {return m_ptr;}\r\n\t\tinline void release() {t_releaser::release(replace_null_t(m_ptr));;}\r\n\t\tinline void attach(T * p_ptr) {release(); m_ptr = p_ptr;}\r\n\t\tinline const t_self & operator=(T * p_ptr) {set(p_ptr);return *this;}\r\n\t\tinline T* detach() {return pfc::replace_null_t(m_ptr);}\r\n\t\tinline T& operator*() const {return *m_ptr;}\r\n\r\n\t\tinline t_self & operator<<(t_self & p_source) {attach(p_source.detach());return *this;}\r\n\t\tinline t_self & operator>>(t_self & p_dest) {p_dest.attach(detach());return *this;}\r\n\r\n\t\t//deprecated\r\n\t\tinline void set(T * p_ptr) {attach(p_ptr);}\r\n\tprivate:\r\n\t\tptrholder_t(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\tconst t_self & operator=(const t_self & ) {throw pfc::exception_not_implemented();}\r\n\r\n\t\tT* m_ptr;\r\n\t};\r\n\r\n\t//avoid \"void&\" breakage\r\n\ttemplate<typename t_releaser>\r\n\tclass ptrholder_t<void,t_releaser> {\r\n\tprivate:\r\n\t\ttypedef void T;\r\n\t\ttypedef ptrholder_t<T,t_releaser> t_self;\r\n\tpublic:\r\n\t\tinline ptrholder_t(T* p_ptr) : m_ptr(p_ptr) {}\r\n\t\tinline ptrholder_t() : m_ptr(NULL) {}\r\n\t\tinline ~ptrholder_t() {t_releaser::release(m_ptr);}\r\n\t\tinline bool is_valid() const {return m_ptr != NULL;}\r\n\t\tinline bool is_empty() const {return m_ptr == NULL;}\r\n\t\tinline T* operator->() const {return m_ptr;}\r\n\t\tinline T* get_ptr() const {return m_ptr;}\r\n\t\tinline void release() {t_releaser::release(replace_null_t(m_ptr));;}\r\n\t\tinline void attach(T * p_ptr) {release(); m_ptr = p_ptr;}\r\n\t\tinline const t_self & operator=(T * p_ptr) {set(p_ptr);return *this;}\r\n\t\tinline T* detach() {return pfc::replace_null_t(m_ptr);}\r\n\r\n\t\tinline t_self & operator<<(t_self & p_source) {attach(p_source.detach());return *this;}\r\n\t\tinline t_self & operator>>(t_self & p_dest) {p_dest.attach(detach());return *this;}\r\n\r\n\t\t//deprecated\r\n\t\tinline void set(T * p_ptr) {attach(p_ptr);}\r\n\tprivate:\r\n\t\tptrholder_t(const t_self &) {throw pfc::exception_not_implemented();}\r\n\t\tconst t_self & operator=(const t_self & ) {throw pfc::exception_not_implemented();}\r\n\r\n\t\tT* m_ptr;\r\n\t};\r\n\r\n\tvoid crash();\r\n}\r\n\r\n#endif"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/pfc.h",
    "content": "#ifndef ___PFC_H___\r\n#define ___PFC_H___\r\n\r\n#if !defined(_WINDOWS) && (defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_WIN32_WCE))\r\n#define _WINDOWS\r\n#endif\r\n\r\n\r\n#define PFC_DLL_EXPORT\r\n\r\n#if defined(_WIN32) || defined(_WIN32_WCE)\r\n\r\n#ifndef STRICT\r\n#define STRICT\r\n#endif\r\n\r\n#ifndef _SYS_GUID_OPERATOR_EQ_\r\n#define _NO_SYS_GUID_OPERATOR_EQ_\t//fix retarded warning with operator== on GUID returning int\r\n#endif\r\n\r\n#ifndef _WIN32_WINNT\r\n#define _WIN32_WINNT 0x500\r\n#endif\r\n\r\n#include <windows.h>\r\n\r\n#ifndef _SYS_GUID_OPERATOR_EQ_\r\n__inline bool __InlineIsEqualGUID(REFGUID rguid1, REFGUID rguid2)\r\n{\r\n   return (\r\n      ((unsigned long *) &rguid1)[0] == ((unsigned long *) &rguid2)[0] &&\r\n      ((unsigned long *) &rguid1)[1] == ((unsigned long *) &rguid2)[1] &&\r\n      ((unsigned long *) &rguid1)[2] == ((unsigned long *) &rguid2)[2] &&\r\n      ((unsigned long *) &rguid1)[3] == ((unsigned long *) &rguid2)[3]);\r\n}\r\n\r\ninline bool operator==(REFGUID guidOne, REFGUID guidOther) {return __InlineIsEqualGUID(guidOne,guidOther);}\r\ninline bool operator!=(REFGUID guidOne, REFGUID guidOther) {return !__InlineIsEqualGUID(guidOne,guidOther);}\r\n#endif\r\n\r\n#include <tchar.h>\r\n\r\n#elif defined(__GNUC__) && (defined __unix__ || defined __POSIX__)\r\n#include <stdint.h>\r\n#include <memory.h>\r\ntypedef struct {\r\n        uint32_t Data1;\r\n        uint16_t Data2;\r\n        uint16_t Data3;\r\n        uint8_t  Data4[ 8 ];\r\n    } GUID; //same as win32 GUID\r\n\r\ninline bool operator==(const GUID & p_item1,const GUID & p_item2) {\r\n\treturn memcmp(&p_item1,&p_item2,sizeof(GUID)) == 0;\r\n}\r\n\r\ninline bool operator!=(const GUID & p_item1,const GUID & p_item2) {\r\n\treturn memcmp(&p_item1,&p_item2,sizeof(GUID)) != 0;\r\n}\r\n\r\n#else\r\n\r\n#error Only win32 or unix target supported.\r\n\r\n#endif\r\n\r\n\r\n\r\n#define PFC_MEMORY_SPACE_LIMIT ((t_uint64)1<<(sizeof(void*)*8-1))\r\n\r\n#define PFC_ALLOCA_LIMIT (4096)\r\n\r\n#define INDEX_INVALID ((unsigned)(-1))\r\n\r\n\r\n#include <exception>\r\n#include <stdexcept>\r\n#include <new>\r\n\r\n#include <malloc.h>\r\n\r\n#include <stdio.h>\r\n\r\n#include <assert.h>\r\n\r\n#include <math.h>\r\n#include <float.h>\r\n\r\n\r\n#ifndef _DEBUG\r\n#define PFC_ASSERT(_Expression)     ((void)0)\r\n#else\r\n#ifdef _WIN32\r\nnamespace pfc { void myassert(const wchar_t * _Message, const wchar_t *_File, unsigned _Line); }\r\n#define PFC_ASSERT(_Expression) (void)( (!!(_Expression)) || (pfc::myassert(_CRT_WIDE(#_Expression), _CRT_WIDE(__FILE__), __LINE__), 0) )\r\n#else\r\n#define PFC_ASSERT(_Expression) assert(_Expression)\r\n#endif\r\n#endif\r\n\r\n#ifdef _MSC_VER\r\n\r\n#ifdef _DEBUG\r\n#define NOVTABLE\r\n#else\r\n#define NOVTABLE _declspec(novtable)\r\n#endif\r\n\r\n#ifdef _DEBUG\r\n#define ASSUME(X) PFC_ASSERT(X)\r\n#else\r\n#define ASSUME(X) __assume(X)\r\n#endif\r\n\r\n#define PFC_DEPRECATE(X) __declspec(deprecated(X))\r\n#else\r\n\r\n#define NOVTABLE\r\n#define ASSUME(X) assert(X)\r\n#define PFC_DEPRECATE(X)\r\n\r\n#endif\r\n\r\n#include \"int_types.h\"\r\n#include \"traits.h\"\r\n#include \"bit_array.h\"\r\n#include \"primitives.h\"\r\n#include \"alloc.h\"\r\n#include \"array.h\"\r\n#include \"bit_array_impl.h\"\r\n#include \"bsearch_inline.h\"\r\n#include \"bsearch.h\"\r\n#include \"sort.h\"\r\n#include \"order_helper.h\"\r\n#include \"list.h\"\r\n#include \"ptr_list.h\"\r\n#include \"string.h\"\r\n#include \"string_list.h\"\r\n#include \"avltree.h\"\r\n#include \"map.h\"\r\n#include \"profiler.h\"\r\n#include \"guid.h\"\r\n#include \"byte_order_helper.h\"\r\n#include \"other.h\"\r\n#include \"chainlist.h\"\r\n#include \"ref_counter.h\"\r\n#include \"rcptr.h\"\r\n#include \"com_ptr_t.h\"\r\n#include \"string_conv.h\"\r\n#include \"instance_tracker.h\"\r\n#endif //___PFC_H___"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/primitives.h",
    "content": "#define tabsize(x) ((size_t)(sizeof(x)/sizeof(*x)))\r\n\r\n#define TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(THISCLASS,MEMBER,INITIALIZER)\t\\\r\n\tTHISCLASS() INITIALIZER\t\\\r\n\ttemplate<typename t_param1>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1) :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMEMBER(p_param1) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2) :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMEMBER(p_param1,p_param2) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2,typename t_param3>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3) :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMEMBER(p_param1,p_param2,p_param3) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4) :\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMEMBER(p_param1,p_param2,p_param3,p_param4) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5>\t\t\t\t\t\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5) :\t\t\t\t\t\t\t\t\t\t\t\t\t\tMEMBER(p_param1,p_param2,p_param3,p_param4,p_param5) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5,typename t_param6>\t\t\t\t\t\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5,const t_param6 & p_param6) :\t\t\t\t\t\t\tMEMBER(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6) INITIALIZER\t\\\r\n\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5,typename t_param6, typename t_param7>\tTHISCLASS(const t_param1 & p_param1,const t_param2 & p_param2,const t_param3 & p_param3,const t_param4 & p_param4,const t_param5 & p_param5,const t_param6 & p_param6,const t_param7 & p_param7) :\tMEMBER(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6,p_param7) INITIALIZER\r\n\r\n#define TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(THISCLASS,MEMBER) TEMPLATE_CONSTRUCTOR_FORWARD_FLOOD_WITH_INITIALIZER(THISCLASS,MEMBER,{})\r\n\r\n\r\n#ifdef _MSC_VER\r\n\r\n//Bah. I noticed the fact that std::exception carrying a custom message is MS-specific *after* making exception classes a part of ABI. To be nuked next time fb2k component backwards compatibility is axed.\r\n\r\n#define PFC_DECLARE_EXCEPTION(NAME,BASECLASS,DEFAULTMSG)\t\\\r\nclass NAME : public BASECLASS {\t\\\r\npublic:\t\\\r\n\tstatic const char * g_what() {return DEFAULTMSG;}\t\\\r\n\tNAME() : BASECLASS(DEFAULTMSG,0) {}\t\\\r\n\tNAME(const char * p_msg) : BASECLASS(p_msg) {}\t\\\r\n\tNAME(const char * p_msg,int) : BASECLASS(p_msg,0) {}\t\\\r\n\tNAME(const NAME & p_source) : BASECLASS(p_source) {}\t\\\r\n};\r\n\r\nnamespace pfc {\r\n\ttemplate<typename t_exception> inline void throw_exception_with_message(const char * p_message) {\r\n\t\tthrow t_exception(p_message);\r\n\t}\r\n}\r\n\r\n#else\r\n\r\n#define PFC_DECLARE_EXCEPTION(NAME,BASECLASS,DEFAULTMSG)\t\\\r\nclass NAME : public BASECLASS { \\\r\npublic:\t\\\r\n\tstatic const char * g_what() {return DEFAULTMSG;}\t\\\r\n\tconst char* what() const throw() {return DEFAULTMSG;}\t\\\r\n};\r\n\r\nnamespace pfc {\r\n\ttemplate<typename t_base> class __exception_with_message_t : public t_base {\r\n\tprivate:\ttypedef __exception_with_message_t<t_base> t_self;\r\n\tpublic:\r\n\t\t__exception_with_message_t(const char * p_message) : m_message(NULL) {\r\n\t\t\tset_message(p_message);\t\t\t\r\n\t\t}\r\n\t\t__exception_with_message_t() : m_message(NULL) {}\r\n\t\t__exception_with_message_t(const t_self & p_source) : m_message(NULL) {set_message(p_source.m_message);}\r\n\r\n\t\tconst char* what() const throw() {return m_message != NULL ? m_message : \"unnamed exception\";}\r\n\r\n\t\tconst t_self & operator=(const t_self & p_source) {set_message(p_source.m_message);}\r\n\r\n\t\t~__exception_with_message_t() throw() {cleanup();}\r\n\r\n\tprivate:\r\n\t\tvoid set_message(const char * p_message) throw() {\r\n\t\t\tcleanup();\r\n\t\t\tif (p_message != NULL) m_message = strdup(p_message);\r\n\t\t}\r\n\t\tvoid cleanup() throw() {\r\n\t\t\tif (m_message != NULL) {free(m_message); m_message = NULL;}\r\n\t\t}\r\n\t\tchar * m_message;\r\n\t};\r\n\ttemplate<typename t_exception> void throw_exception_with_message(const char * p_message) {\r\n\t\tthrow __exception_with_message_t<t_exception>(p_message);\r\n\t}\r\n}\r\n#endif\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<typename p_type1,typename p_type2> class assert_same_type;\r\n\ttemplate<typename p_type> class assert_same_type<p_type,p_type> {};\r\n\r\n\ttemplate<typename p_type1,typename p_type2>\r\n\tclass is_same_type { public: enum {value = false}; };\r\n\r\n\ttemplate<typename p_type>\r\n\tclass is_same_type<p_type,p_type> { public: enum {value = true}; };\r\n\r\n\ttemplate<bool p_val> class __static_assert_switcher_t;\r\n\ttemplate<> class __static_assert_switcher_t<true> {\r\n\tpublic:\r\n\t\ttypedef void t_assert_failed;\r\n\t};\r\n\r\n\t//depreacted\r\n\ttemplate<bool p_val> typename __static_assert_switcher_t<p_val>::t_assert_failed static_assert_t() {}\r\n\r\n\ttemplate<bool p_val> typename __static_assert_switcher_t<p_val>::t_assert_failed static_assert() {}\r\n\r\n\ttemplate<typename t_type>\r\n\tvoid assert_raw_type() {static_assert_t< !traits_t<t_type>::needs_constructor && !traits_t<t_type>::needs_destructor >();}\r\n\r\n\r\n\ttemplate<typename t_type> void __unsafe__memcpy_t(t_type * p_dst,const t_type * p_src,t_size p_count) {\r\n\t\t::memcpy(reinterpret_cast<void*>(p_dst), reinterpret_cast<const void*>(p_src), p_count * sizeof(t_type));\r\n\t}\r\n\r\n\ttemplate<typename t_type> void __unsafe__in_place_destructor_t(t_type & p_item) throw() {\r\n\t\tif (traits_t<t_type>::needs_destructor) try{ p_item.~t_type(); } catch(...) {}\r\n\t}\r\n\t\r\n\ttemplate<typename t_type> void __unsafe__in_place_constructor_t(t_type & p_item) {\r\n\t\tif (traits_t<t_type>::needs_constructor) {\r\n\t\t\tt_type * ret = new(&p_item) t_type;\r\n\t\t\tPFC_ASSERT(ret == &p_item);\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_type> void __unsafe__in_place_destructor_array_t(t_type * p_items, t_size p_count) throw() {\r\n\t\tif (traits_t<t_type>::needs_destructor) {\r\n\t\t\tt_type * walk = p_items;\r\n\t\t\tfor(t_size n=p_count;n;--n) __unsafe__in_place_destructor_t(*(walk++));\r\n\t\t}\r\n\t}\r\n\t\r\n\ttemplate<typename t_type> t_type * __unsafe__in_place_constructor_array_t(t_type * p_items,t_size p_count) {\r\n\t\tif (traits_t<t_type>::needs_constructor) {\r\n\t\t\tt_size walkptr = 0;\r\n\t\t\ttry {\r\n\t\t\t\tfor(walkptr=0;walkptr<p_count;++walkptr) __unsafe__in_place_constructor_t(p_items[walkptr]);\r\n\t\t\t} catch(...) {\r\n\t\t\t\t__unsafe__in_place_destructor_array_t(p_items,walkptr);\r\n\t\t\t\tthrow;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn p_items;\r\n\t}\r\n\r\n\ttemplate<typename t_type> t_type * __unsafe__in_place_resize_array_t(t_type * p_items,t_size p_from,t_size p_to) {\r\n\t\tif (p_from < p_to) __unsafe__in_place_constructor_array_t(p_items + p_from, p_to - p_from);\r\n\t\telse if (p_from > p_to) __unsafe__in_place_destructor_array_t(p_items + p_to, p_from - p_to);\r\n\t\treturn p_items;\r\n\t}\r\n\r\n\ttemplate<typename t_type,typename t_copy> void __unsafe__in_place_constructor_copy_t(t_type & p_item,const t_copy & p_copyfrom) {\r\n\t\tif (traits_t<t_type>::needs_constructor) {\r\n\t\t\tt_type * ret = new(&p_item) t_type(p_copyfrom);\r\n\t\t\tPFC_ASSERT(ret == &p_item);\r\n\t\t} else {\r\n\t\t\tp_item = p_copyfrom;\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_type,typename t_copy> t_type * __unsafe__in_place_constructor_array_copy_t(t_type * p_items,t_size p_count, const t_copy * p_copyfrom) {\r\n\t\tt_size walkptr = 0;\r\n\t\ttry {\r\n\t\t\tfor(walkptr=0;walkptr<p_count;++walkptr) __unsafe__in_place_constructor_copy_t(p_items[walkptr],p_copyfrom[walkptr]);\r\n\t\t} catch(...) {\r\n\t\t\t__unsafe__in_place_destructor_array_t(p_items,walkptr);\r\n\t\t\tthrow;\r\n\t\t}\r\n\t\treturn p_items;\r\n\t}\r\n\r\n\ttemplate<typename t_type,typename t_copy> t_type * __unsafe__in_place_constructor_array_copy_partial_t(t_type * p_items,t_size p_count, const t_copy * p_copyfrom,t_size p_copyfrom_count) {\r\n\t\tif (p_copyfrom_count > p_count) p_copyfrom_count = p_count;\r\n\t\t__unsafe__in_place_constructor_array_copy_t(p_items,p_copyfrom_count,p_copyfrom);\r\n\t\ttry {\r\n\t\t\t__unsafe__in_place_constructor_array_t(p_items + p_copyfrom_count,p_count - p_copyfrom_count);\r\n\t\t} catch(...) {\r\n\t\t\t__unsafe__in_place_destructor_array_t(p_items,p_copyfrom_count);\r\n\t\t\tthrow;\r\n\t\t}\r\n\t\treturn p_items;\r\n\t}\r\n\r\n\ttemplate<typename t_ret,typename t_param> \r\n\tt_ret safe_cast(t_param const & p_param) {\r\n\t\treturn p_param;\r\n\t}\r\n\r\n\ttemplate<typename t_ret,typename t_param>\r\n\tt_ret * safe_ptr_cast(t_param * p_param) {\r\n\t\tif (pfc::is_same_type<t_ret,t_param>::value) return p_param;\r\n\t\telse {\r\n\t\t\tif (p_param == NULL) return NULL;\r\n\t\t\telse return p_param;\r\n\t\t}\r\n\t}\r\n\r\n\ttypedef std::exception exception;\r\n\r\n\tPFC_DECLARE_EXCEPTION(exception_overflow,exception,\"Overflow\");\r\n\tPFC_DECLARE_EXCEPTION(exception_bug_check,exception,\"Bug check\");\r\n\tPFC_DECLARE_EXCEPTION(exception_unexpected_recursion,exception_bug_check,\"Unexpected recursion\");\r\n\tPFC_DECLARE_EXCEPTION(exception_not_implemented,exception_bug_check,\"Feature not implemented\");\r\n\tPFC_DECLARE_EXCEPTION(exception_dynamic_assert,exception_bug_check,\"dynamic_assert failure\");\r\n\r\n\ttemplate<typename t_ret,typename t_param>\r\n\tt_ret downcast_guarded(const t_param & p_param) {\r\n\t\tt_ret temp = (t_ret) p_param;\r\n\t\tif ((t_param) temp != p_param) throw exception_overflow();\r\n\t\treturn temp;\r\n\t}\r\n\t\r\n\ttemplate<typename t_exception,typename t_ret,typename t_param>\r\n\tt_ret downcast_guarded_ex(const t_param & p_param) {\r\n\t\tt_ret temp = (t_ret) p_param;\r\n\t\tif ((t_param) temp != p_param) throw t_exception();\r\n\t\treturn temp;\r\n\t}\r\n\r\n\ttemplate<typename t_acc,typename t_add>\r\n\tvoid accumulate_guarded(t_acc & p_acc, const t_add & p_add) {\r\n\t\tt_acc delta = downcast_guarded<t_acc>(p_add);\r\n\t\tdelta += p_acc;\r\n\t\tif (delta < p_acc) throw exception_overflow();\r\n\t\tp_acc = delta;\r\n\t}\r\n\r\n\t//deprecated\r\n\tinline void bug_check_assert(bool p_condition, const char * p_msg) {\r\n\t\tif (!p_condition) {\r\n\t\t\tPFC_ASSERT(0);\r\n\t\t\tthrow_exception_with_message<exception_bug_check>(p_msg);\r\n\t\t}\r\n\t}\r\n\t//deprecated\r\n\tinline void bug_check_assert(bool p_condition) {\r\n\t\tif (!p_condition) {\r\n\t\t\tPFC_ASSERT(0);\r\n\t\t\tthrow exception_bug_check();\r\n\t\t}\r\n\t}\r\n\r\n\tinline void dynamic_assert(bool p_condition, const char * p_msg) {\r\n\t\tif (!p_condition) {\r\n\t\t\tPFC_ASSERT(0);\r\n\t\t\tthrow_exception_with_message<exception_dynamic_assert>(p_msg);\r\n\t\t}\r\n\t}\r\n\tinline void dynamic_assert(bool p_condition) {\r\n\t\tif (!p_condition) {\r\n\t\t\tPFC_ASSERT(0);\r\n\t\t\tthrow exception_dynamic_assert();\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tinline void swap_multi_t(T * p_buffer1,T * p_buffer2,t_size p_size) {\r\n\t\tT * walk1 = p_buffer1, * walk2 = p_buffer2;\r\n\t\tfor(t_size n=p_size;n;--n) {\r\n\t\t\tT temp (* walk1);\r\n\t\t\t*walk1 = *walk2;\r\n\t\t\t*walk2 = temp;\r\n\t\t\twalk1++; walk2++;\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename T,t_size p_size>\r\n\tinline void swap_multi_t(T * p_buffer1,T * p_buffer2) {\r\n\t\tT * walk1 = p_buffer1, * walk2 = p_buffer2;\r\n\t\tfor(t_size n=p_size;n;--n) {\r\n\t\t\tT temp (* walk1);\r\n\t\t\t*walk1 = *walk2;\r\n\t\t\t*walk2 = temp;\r\n\t\t\twalk1++; walk2++;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\ttemplate<t_size p_size>\r\n\tinline void __unsafe__swap_raw_t(void * p_object1, void * p_object2) {\r\n\t\tif (p_size % sizeof(t_size) == 0) {\r\n\t\t\tswap_multi_t<t_size,p_size/sizeof(t_size)>(reinterpret_cast<t_size*>(p_object1),reinterpret_cast<t_size*>(p_object2));\r\n\t\t} else {\r\n\t\t\tswap_multi_t<t_uint8,p_size>(reinterpret_cast<t_uint8*>(p_object1),reinterpret_cast<t_uint8*>(p_object2));\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tinline void swap_t(T & p_item1, T & p_item2) {\r\n\t\tif (traits_t<T>::realloc_safe) {\r\n\t\t\t__unsafe__swap_raw_t<sizeof(T)>( reinterpret_cast<void*>( &p_item1 ), reinterpret_cast<void*>( &p_item2 ) );\r\n\t\t} else {\r\n\t\t\tT temp(p_item2);\r\n\t\t\tp_item2 = p_item1;\r\n\t\t\tp_item1 = temp;\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_array>\r\n\tt_size array_size_t(const t_array & p_array) {return p_array.get_size();}\r\n\r\n\ttemplate<typename t_item, t_size p_width>\r\n\tt_size array_size_t(const t_item (&p_array)[p_width]) {return p_width;}\r\n\r\n\r\n\ttemplate<typename t_array,typename t_filler>\r\n\tinline void fill_t(t_array & p_buffer,const t_size p_count, const t_filler & p_filler) {\r\n\t\tfor(t_size n=0;n<p_count;n++)\r\n\t\t\tp_buffer[n] = p_filler;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename t_filler>\r\n\tinline void fill_ptr_t(t_array * p_buffer,const t_size p_count, const t_filler & p_filler) {\r\n\t\tfor(t_size n=0;n<p_count;n++)\r\n\t\t\tp_buffer[n] = p_filler;\r\n\t}\r\n\r\n\ttemplate<typename t_item1, typename t_item2>\r\n\tinline int compare_t(const t_item1 & p_item1, const t_item2 & p_item2) {\r\n\t\tif (p_item1 < p_item2) return -1;\r\n\t\telse if (p_item1 > p_item2) return 1;\r\n\t\telse return 0;\r\n\t}\r\n\r\n\t//! For use with avltree/map etc.\r\n\tclass comparator_default {\r\n\tpublic:\r\n\t\ttemplate<typename t_item1,typename t_item2>\r\n\t\tinline static int compare(const t_item1 & p_item1,const t_item2 & p_item2) {return pfc::compare_t(p_item1,p_item2);}\r\n\t};\r\n\r\n\tclass comparator_memcmp {\r\n\tpublic:\r\n\t\ttemplate<typename t_item1,typename t_item2>\r\n\t\tinline static int compare(const t_item1 & p_item1,const t_item2 & p_item2) {\r\n\t\t\tstatic_assert<sizeof(t_item1) == sizeof(t_item2)>();\r\n\t\t\treturn memcmp(&p_item1,&p_item2,sizeof(t_item1));\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<typename t_source1, typename t_source2>\r\n\tt_size subtract_sorted_lists_calculate_count(const t_source1 & p_source1, const t_source2 & p_source2) {\r\n\t\tt_size walk1 = 0, walk2 = 0, walk_out = 0;\r\n\t\tconst t_size max1 = p_source1.get_size(), max2 = p_source2.get_size();\r\n\t\tfor(;;) {\r\n\t\t\tint state;\r\n\t\t\tif (walk1 < max1 && walk2 < max2) {\r\n\t\t\t\tstate = pfc::compare_t(p_source1[walk1],p_source2[walk2]);\r\n\t\t\t} else if (walk1 < max1) {\r\n\t\t\t\tstate = -1;\r\n\t\t\t} else if (walk2 < max2) {\r\n\t\t\t\tstate = 1;\r\n\t\t\t} else {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (state < 0) walk_out++;\r\n\t\t\tif (state <= 0) walk1++;\r\n\t\t\tif (state >= 0) walk2++;\r\n\t\t}\r\n\t\treturn walk_out;\r\n\t}\r\n\r\n\t//! Subtracts p_source2 contents from p_source1 and stores result in p_destination. Both source lists must be sorted.\r\n\t//! Note: duplicates will be carried over (and ignored for p_source2).\r\n\ttemplate<typename t_destination, typename t_source1, typename t_source2>\r\n\tvoid subtract_sorted_lists(t_destination & p_destination,const t_source1 & p_source1, const t_source2 & p_source2) {\r\n\t\tp_destination.set_size(subtract_sorted_lists_calculate_count(p_source1,p_source2));\r\n\t\tt_size walk1 = 0, walk2 = 0, walk_out = 0;\r\n\t\tconst t_size max1 = p_source1.get_size(), max2 = p_source2.get_size();\r\n\t\tfor(;;) {\r\n\t\t\tint state;\r\n\t\t\tif (walk1 < max1 && walk2 < max2) {\r\n\t\t\t\tstate = pfc::compare_t(p_source1[walk1],p_source2[walk2]);\r\n\t\t\t} else if (walk1 < max1) {\r\n\t\t\t\tstate = -1;\r\n\t\t\t} else if (walk2 < max2) {\r\n\t\t\t\tstate = 1;\r\n\t\t\t} else {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t\r\n\t\t\tif (state < 0) p_destination[walk_out++] = p_source1[walk1];\r\n\t\t\tif (state <= 0) walk1++;\r\n\t\t\tif (state >= 0) walk2++;\r\n\t\t}\r\n\t}\r\n\r\n\ttemplate<typename t_source1, typename t_source2>\r\n\tt_size merge_sorted_lists_calculate_count(const t_source1 & p_source1, const t_source2 & p_source2) {\r\n\t\tt_size walk1 = 0, walk2 = 0, walk_out = 0;\r\n\t\tconst t_size max1 = p_source1.get_size(), max2 = p_source2.get_size();\r\n\t\tfor(;;) {\r\n\t\t\tint state;\r\n\t\t\tif (walk1 < max1 && walk2 < max2) {\r\n\t\t\t\tstate = pfc::compare_t(p_source1[walk1],p_source2[walk2]);\r\n\t\t\t} else if (walk1 < max1) {\r\n\t\t\t\tstate = -1;\r\n\t\t\t} else if (walk2 < max2) {\r\n\t\t\t\tstate = 1;\r\n\t\t\t} else {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (state <= 0) walk1++;\r\n\t\t\tif (state >= 0) walk2++;\r\n\t\t\twalk_out++;\r\n\t\t}\r\n\t\treturn walk_out;\r\n\t}\r\n\r\n\t//! Merges p_source1 and p_source2, storing content in p_destination. Both source lists must be sorted.\r\n\t//! Note: duplicates will be carried over.\r\n\ttemplate<typename t_destination, typename t_source1, typename t_source2>\r\n\tvoid merge_sorted_lists(t_destination & p_destination,const t_source1 & p_source1, const t_source2 & p_source2) {\r\n\t\tp_destination.set_size(merge_sorted_lists_calculate_count(p_source1,p_source2));\r\n\t\tt_size walk1 = 0, walk2 = 0, walk_out = 0;\r\n\t\tconst t_size max1 = p_source1.get_size(), max2 = p_source2.get_size();\r\n\t\tfor(;;) {\r\n\t\t\tint state;\r\n\t\t\tif (walk1 < max1 && walk2 < max2) {\r\n\t\t\t\tstate = pfc::compare_t(p_source1[walk1],p_source2[walk2]);\r\n\t\t\t} else if (walk1 < max1) {\r\n\t\t\t\tstate = -1;\r\n\t\t\t} else if (walk2 < max2) {\r\n\t\t\t\tstate = 1;\r\n\t\t\t} else {\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tif (state < 0) {\r\n\t\t\t\tp_destination[walk_out] = p_source1[walk1++];\r\n\t\t\t} else if (state > 0) {\r\n\t\t\t\tp_destination[walk_out] = p_source2[walk2++];\r\n\t\t\t} else {\r\n\t\t\t\tp_destination[walk_out] = p_source1[walk1];\r\n\t\t\t\twalk1++; walk2++;\r\n\t\t\t}\r\n\t\t\twalk_out++;\r\n\t\t}\r\n\t}\r\n\r\n\t\r\n\r\n\ttemplate<typename t_array,typename T>\r\n\tinline t_size append_t(t_array & p_array,const T & p_item)\r\n\t{\r\n\t\tt_size old_count = p_array.get_size();\r\n\t\tp_array.set_size(old_count + 1);\r\n\t\tp_array[old_count] = p_item;\r\n\t\treturn old_count;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename T>\r\n\tinline t_size append_swap_t(t_array & p_array,T & p_item)\r\n\t{\r\n\t\tt_size old_count = p_array.get_size();\r\n\t\tp_array.set_size(old_count + 1);\r\n\t\tswap_t(p_array[old_count],p_item);\r\n\t\treturn old_count;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename T>\r\n\tinline t_size insert_t(t_array & p_array,const T & p_item,t_size p_index)\r\n\t{\r\n\t\tt_size old_count = p_array.get_size();\r\n\t\tif (p_index > old_count) p_index = old_count;\r\n\t\tp_array.set_size(old_count + 1);\r\n\t\tfor(t_size n=old_count;n>p_index;n--)\r\n\t\t\tp_array[n] = p_array[n-1];\r\n\t\tp_array[p_index] = p_item;\r\n\t\treturn p_index;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename T>\r\n\tinline t_size insert_swap_t(t_array & p_array,T & p_item,t_size p_index)\r\n\t{\r\n\t\tt_size old_count = p_array.get_size();\r\n\t\tif (p_index > old_count) p_index = old_count;\r\n\t\tp_array.set_size(old_count + 1);\r\n\t\tfor(t_size n=old_count;n>p_index;n--)\r\n\t\t\tswap_t(p_array[n],p_array[n-1]);\r\n\t\tswap_t(p_array[p_index],p_item);\r\n\t\treturn p_index;\r\n\t}\r\n\r\n\t\r\n\ttemplate<typename T>\r\n\tinline T max_t(const T & item1, const T & item2) {return item1 > item2 ? item1 : item2;};\r\n\r\n\ttemplate<typename T>\r\n\tinline T min_t(const T & item1, const T & item2) {return item1 < item2 ? item1 : item2;};\r\n\r\n\ttemplate<typename T>\r\n\tinline T abs_t(T item) {return item<0 ? -item : item;}\r\n\r\n\ttemplate<typename T>\r\n\tinline T sqr_t(T item) {return item * item;}\r\n\r\n\ttemplate<typename T>\r\n\tinline T clip_t(const T & p_item, const T & p_min, const T & p_max) {\r\n\t\tif (p_item < p_min) return p_min;\r\n\t\telse if (p_item <= p_max) return p_item;\r\n\t\telse return p_max;\r\n\t}\r\n\r\n\r\n\r\n\r\n\r\n\ttemplate<typename T>\r\n\tinline void delete_t(T* ptr) {delete ptr;}\r\n\r\n\ttemplate<typename T>\r\n\tinline void delete_array_t(T* ptr) {delete[] ptr;}\r\n\r\n\ttemplate<typename T>\r\n\tinline T* clone_t(T* ptr) {return new T(*ptr);}\r\n\r\n\r\n\ttemplate<typename t_exception,typename t_int>\r\n\tinline t_int mul_safe_t(t_int p_val1,t_int p_val2) {\r\n\t\tif (p_val1 == 0 || p_val2 == 0) return 0;\r\n\t\tt_int temp = (t_int) (p_val1 * p_val2);\r\n\t\tif (temp < p_val1 || temp < p_val2) throw t_exception();\r\n\t\treturn temp;\r\n\t}\r\n\r\n\ttemplate<typename t_src,typename t_dst>\r\n\tvoid memcpy_t(t_dst* p_dst,const t_src* p_src,t_size p_count) {\r\n\t\tfor(t_size n=0;n<p_count;n++) p_dst[n] = p_src[n];\r\n\t}\r\n\r\n\ttemplate<typename t_dst,typename t_src>\r\n\tvoid copy_array_loop_t(t_dst & p_dst,const t_src & p_src,t_size p_count) {\r\n\t\tfor(t_size n=0;n<p_count;n++) p_dst[n] = p_src[n];\r\n\t}\r\n\r\n\ttemplate<typename t_src,typename t_dst>\r\n\tvoid memcpy_backwards_t(t_dst * p_dst,const t_src * p_src,t_size p_count) {\r\n\t\tp_dst += p_count; p_src += p_count;\r\n\t\tfor(t_size n=0;n<p_count;n++) *(--p_dst) = *(--p_src);\r\n\t}\r\n\r\n\ttemplate<typename T,typename t_val>\r\n\tvoid memset_t(T * p_buffer,const t_val & p_val,t_size p_count) {\r\n\t\tfor(t_size n=0;n<p_count;n++) p_buffer[n] = p_val;\r\n\t}\r\n\r\n\ttemplate<typename T,typename t_val>\r\n\tvoid memset_t(T &p_buffer,const t_val & p_val) {\r\n\t\tconst t_size width = pfc::array_size_t(p_buffer);\r\n\t\tfor(t_size n=0;n<width;n++) p_buffer[n] = p_val;\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tvoid memset_null_t(T * p_buffer,t_size p_count) {\r\n\t\tfor(t_size n=0;n<p_count;n++) p_buffer[n] = 0;\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tvoid memset_null_t(T &p_buffer) {\r\n\t\tconst t_size width = pfc::array_size_t(p_buffer);\r\n\t\tfor(t_size n=0;n<width;n++) p_buffer[n] = 0;\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tvoid memmove_t(T* p_dst,const T* p_src,t_size p_count) {\r\n\t\tif (p_dst == p_src) {/*do nothing*/}\r\n\t\telse if (p_dst > p_src && p_dst < p_src + p_count) memcpy_backwards_t<T>(p_dst,p_src,p_count);\r\n\t\telse memcpy_t<T>(p_dst,p_src,p_count);\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tT* new_ptr_check_t(T* p_ptr) {\r\n\t\tif (p_ptr == NULL) throw std::bad_alloc();\r\n\t\treturn p_ptr;\r\n\t}\r\n\r\n\ttemplate<typename T>\r\n\tint sgn_t(const T & p_val) {\r\n\t\tif (p_val < 0) return -1;\r\n\t\telse if (p_val > 0) return 1;\r\n\t\telse return 0;\r\n\t}\r\n\r\n\ttemplate<typename T> const T* empty_string_t();\r\n\r\n\ttemplate<> inline const char * empty_string_t<char>() {return \"\";}\r\n\ttemplate<> inline const wchar_t * empty_string_t<wchar_t>() {return L\"\";}\r\n\r\n\r\n\ttemplate<typename t_type,typename t_newval>\r\n\tt_type replace_t(t_type & p_var,const t_newval & p_newval) {\r\n\t\tt_type oldval = p_var;\r\n\t\tp_var = p_newval;\r\n\t\treturn oldval;\r\n\t}\r\n\ttemplate<typename t_type>\r\n\tt_type replace_null_t(t_type & p_var) {\r\n\t\tt_type ret = p_var;\r\n\t\tp_var = NULL;\r\n\t\treturn ret;\r\n\t}\r\n\r\n\ttemplate<t_size p_size_pow2>\r\n\tinline bool is_ptr_aligned_t(const void * p_ptr) {\r\n\t\tstatic_assert_t< (p_size_pow2 & (p_size_pow2 - 1)) == 0 >();\r\n\t\treturn ( ((t_size)p_ptr) & (p_size_pow2-1) ) == 0;\r\n\t}\r\n\r\n\r\n\ttemplate<typename t_array>\r\n\tvoid array_rangecheck_t(const t_array & p_array,t_size p_index) {\r\n\t\tif (p_index >= pfc::array_size_t(p_array)) throw pfc::exception_overflow();\r\n\t}\r\n\r\n\ttemplate<typename t_array>\r\n\tvoid array_rangecheck_t(const t_array & p_array,t_size p_from,t_size p_to) {\r\n\t\tif (p_from > p_to) throw pfc::exception_overflow();\r\n\t\tarray_rangecheck_t(p_array,p_from); array_rangecheck_t(p_array,p_to);\r\n\t}\r\n\r\n\tinline t_int32 rint32(double p_val) {return (t_int32) floor(p_val + 0.5);}\r\n\tinline t_int64 rint64(double p_val) {return (t_int64) floor(p_val + 0.5);}\r\n\r\n\r\n\r\n\r\n\ttemplate<typename t_array>\r\n\tinline t_size remove_mask_t(t_array & p_array,const bit_array & p_mask)//returns amount of items left\r\n\t{\r\n\t\tt_size n,count = p_array.get_size(), total = 0;\r\n\r\n\t\tn = total = p_mask.find(true,0,count);\r\n\r\n\t\tif (n<count)\r\n\t\t{\r\n\t\t\tfor(n=p_mask.find(false,n+1,count-n-1);n<count;n=p_mask.find(false,n+1,count-n-1))\r\n\t\t\t\tswap_t(p_array[total++],p_array[n]);\r\n\r\n\t\t\tp_array.set_size(total);\r\n\t\t\t\r\n\t\t\treturn total;\r\n\t\t}\r\n\t\telse return count;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename t_compare>\r\n\tt_size find_duplicates_sorted_t(t_array p_array,t_size p_count,t_compare p_compare,bit_array_var & p_out) {\r\n\t\tt_size ret = 0;\r\n\t\tt_size n;\r\n\t\tif (p_count > 0)\r\n\t\t{\r\n\t\t\tp_out.set(0,false);\r\n\t\t\tfor(n=1;n<p_count;n++)\r\n\t\t\t{\r\n\t\t\t\tbool found = p_compare(p_array[n-1],p_array[n]) == 0;\r\n\t\t\t\tif (found) ret++;\r\n\t\t\t\tp_out.set(n,found);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\ttemplate<typename t_array,typename t_compare,typename t_permutation>\r\n\tt_size find_duplicates_sorted_permutation_t(t_array p_array,t_size p_count,t_compare p_compare,t_permutation const & p_permutation,bit_array_var & p_out) {\r\n\t\tt_size ret = 0;\r\n\t\tt_size n;\r\n\t\tif (p_count > 0) {\r\n\t\t\tp_out.set(p_permutation[0],false);\r\n\t\t\tfor(n=1;n<p_count;n++)\r\n\t\t\t{\r\n\t\t\t\tbool found = p_compare(p_array[p_permutation[n-1]],p_array[p_permutation[n]]) == 0;\r\n\t\t\t\tif (found) ret++;\r\n\t\t\t\tp_out.set(p_permutation[n],found);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\ttemplate<typename t_char>\r\n\tt_size strlen_t(const t_char * p_string,t_size p_length = infinite) {\r\n\t\tfor(t_size walk = 0;;walk++) {\r\n\t\t\tif (walk >= p_length || p_string[walk] == 0) return walk;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\ttemplate<typename t_array>\r\n\tclass __list_to_array_enumerator {\r\n\tpublic:\r\n\t\t__list_to_array_enumerator(t_array & p_array) : m_array(p_array), m_walk(0) {}\r\n\t\ttemplate<typename t_item>\r\n\t\tvoid operator() (const t_item & p_item) {\r\n\t\t\tPFC_ASSERT(m_walk < m_array.get_size());\r\n\t\t\tm_array[m_walk++] = p_item;\r\n\t\t}\r\n\t\tvoid finalize() {\r\n\t\t\tPFC_ASSERT(m_walk == m_array.get_size());\r\n\t\t}\r\n\tprivate:\r\n\t\tt_size m_walk;\r\n\t\tt_array & m_array;\r\n\t};\r\n\r\n\ttemplate<typename t_list,typename t_array>\r\n\tvoid list_to_array(t_array & p_array,const t_list & p_list) {\r\n\t\tp_array.set_size(p_list.get_count());\r\n\t\t__list_to_array_enumerator<t_array> enumerator(p_array);\r\n\t\tp_list.enumerate(enumerator);\r\n\t\tenumerator.finalize();\r\n\t}\r\n\r\n\ttemplate<typename t_receiver>\r\n\tclass enumerator_add_item {\r\n\tpublic:\r\n\t\tenumerator_add_item(t_receiver & p_receiver) : m_receiver(p_receiver) {}\r\n\t\ttemplate<typename t_item> void operator() (const t_item & p_item) {m_receiver.add_item(p_item);}\r\n\tprivate:\r\n\t\tt_receiver & m_receiver;\r\n\t};\r\n\r\n\ttemplate<typename t_receiver,typename t_giver>\r\n\tvoid overwrite_list_enumerated(t_receiver & p_receiver,const t_giver & p_giver) {\r\n\t\tenumerator_add_item<t_receiver> wrapper(p_receiver);\r\n\t\tp_giver.enumerate(wrapper);\r\n\t}\r\n\r\n\ttemplate<typename t_receiver,typename t_giver>\r\n\tvoid copy_list_enumerated(t_receiver & p_receiver,const t_giver & p_giver) {\r\n\t\tp_receiver.remove_all();\r\n\t\toverwrite_list_enumerated(p_receiver,p_giver);\r\n\t}\r\n};\r\n\r\n\r\n#define PFC_CLASS_NOT_COPYABLE(THISCLASSNAME,THISTYPE) \\\r\n\tprivate:\t\\\r\n\tTHISCLASSNAME(const THISTYPE&) {throw pfc::exception_bug_check();}\t\\\r\n\tconst THISTYPE & operator=(const THISTYPE &) {throw pfc::exception_bug_check();}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/printf.cpp",
    "content": "#include \"pfc.h\"\r\n\r\n//implementations of deprecated string_printf methods, with a pragma to disable warnings when they reference other deprecated methods.\r\n\r\n#pragma warning(disable:4996)\r\n\r\nnamespace pfc {\r\n\r\nvoid string_printf::run(const char * fmt,va_list list) {g_run(*this,fmt,list);}\r\n\r\nstring_printf_va::string_printf_va(const char * fmt,va_list list) {string_printf::g_run(*this,fmt,list);}\r\n\r\nvoid string_printf::g_run(string_base & out,const char * fmt,va_list list)\r\n{\r\n\tout.reset();\r\n\twhile(*fmt)\r\n\t{\r\n\t\tif (*fmt=='%')\r\n\t\t{\r\n\t\t\tfmt++;\r\n\t\t\tif (*fmt=='%')\r\n\t\t\t{\r\n\t\t\t\tout.add_char('%');\r\n\t\t\t\tfmt++;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tbool force_sign = false;\r\n\t\t\t\tif (*fmt=='+')\r\n\t\t\t\t{\r\n\t\t\t\t\tforce_sign = true;\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\t\t\t\tchar padchar = (*fmt == '0') ? '0' : ' ';\r\n\t\t\t\tt_size pad = 0;\r\n\t\t\t\twhile(*fmt>='0' && *fmt<='9')\r\n\t\t\t\t{\r\n\t\t\t\t\tpad = pad * 10 + (*fmt - '0');\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (*fmt=='s' || *fmt=='S')\r\n\t\t\t\t{\r\n\t\t\t\t\tconst char * ptr = va_arg(list,const char*);\r\n\t\t\t\t\tt_size len = strlen(ptr);\r\n\t\t\t\t\tif (pad>len) out.add_chars(padchar,pad-len);\r\n\t\t\t\t\tout.add_string(ptr);\r\n\t\t\t\t\tfmt++;\r\n\r\n\t\t\t\t}\r\n\t\t\t\telse if (*fmt=='i' || *fmt=='I' || *fmt=='d' || *fmt=='D')\r\n\t\t\t\t{\r\n\t\t\t\t\tchar temp[8*sizeof(int)];\r\n\t\t\t\t\tint val = va_arg(list,int);\r\n\t\t\t\t\tif (force_sign && val>0) out.add_char('+');\r\n\t\t\t\t\t_itoa_s(val,temp,10);\r\n\t\t\t\t\tt_size len = strlen(temp);\r\n\t\t\t\t\tif (pad>len) out.add_chars(padchar,pad-len);\r\n\t\t\t\t\tout.add_string(temp);\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\t\t\t\telse if (*fmt=='u' || *fmt=='U')\r\n\t\t\t\t{\r\n\t\t\t\t\tchar temp[8*sizeof(int)];\r\n\t\t\t\t\tint val = va_arg(list,int);\r\n\t\t\t\t\tif (force_sign && val>0) out.add_char('+');\r\n\t\t\t\t\t_ultoa_s(val,temp,10);\r\n\t\t\t\t\tt_size len = strlen(temp);\r\n\t\t\t\t\tif (pad>len) out.add_chars(padchar,pad-len);\r\n\t\t\t\t\tout.add_string(temp);\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\t\t\t\telse if (*fmt=='x' || *fmt=='X')\r\n\t\t\t\t{\r\n\t\t\t\t\tchar temp[8*sizeof(int)];\r\n\t\t\t\t\tint val = va_arg(list,int);\r\n\t\t\t\t\tif (force_sign && val>0) out.add_char('+');\r\n\t\t\t\t\t_ultoa_s(val,temp,16);\r\n\t\t\t\t\tif (*fmt=='X')\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tchar * t = temp;\r\n\t\t\t\t\t\twhile(*t)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (*t>='a' && *t<='z')\r\n\t\t\t\t\t\t\t\t*t += 'A' - 'a';\r\n\t\t\t\t\t\t\tt++;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tt_size len = strlen(temp);\r\n\t\t\t\t\tif (pad>len) out.add_chars(padchar,pad-len);\r\n\t\t\t\t\tout.add_string(temp);\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\t\t\t\telse if (*fmt=='c' || *fmt=='C')\r\n\t\t\t\t{\r\n\t\t\t\t\tout.add_char(va_arg(list,char));\r\n\t\t\t\t\tfmt++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tout.add_char(*(fmt++));\r\n\t\t}\r\n\t}\r\n}\r\n\r\nstring_printf::string_printf(const char * fmt,...)\r\n{\r\n\tva_list list;\r\n\tva_start(list,fmt);\r\n\trun(fmt,list);\r\n\tva_end(list);\r\n}\r\n\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/profiler.cpp",
    "content": "#include \"pfc.h\"\r\n\r\n#ifdef _WINDOWS\r\nnamespace pfc {\r\n\r\nprofiler_static::profiler_static(const char * p_name)\r\n{\r\n\tname = p_name;\r\n\ttotal_time = 0;\r\n\tnum_called = 0;\r\n}\r\n\r\nprofiler_static::~profiler_static()\r\n{\r\n\ttry {\r\n\t\tpfc::string_fixed_t<511> message;\r\n\t\tmessage << \"profiler: \" << pfc::format_pad_left<pfc::string_fixed_t<127> >(48,' ',name) << \" - \" << \r\n\t\t\tpfc::format_pad_right<pfc::string_fixed_t<128> >(16,' ',pfc::format_uint(total_time) ) << \" cycles\";\r\n\r\n\t\tif (num_called > 0) {\r\n\t\t\tmessage << \" (executed \" << num_called << \" times, \" << (total_time / num_called) << \" average)\";\r\n\t\t}\r\n\t\tmessage << \"\\n\";\r\n\t\tOutputDebugStringA(message);\r\n\t} catch(...) {\r\n\t\t//should never happen\r\n\t\tOutputDebugString(_T(\"unexpected profiler failure\\n\"));\r\n\t}\r\n}\r\n\r\n}\r\n#else\r\n//PORTME\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/profiler.h",
    "content": "#ifndef _PFC_PROFILER_H_\r\n#define _PFC_PROFILER_H_\r\n\r\n#ifdef _WINDOWS\r\n\r\n#include <intrin.h>\r\nnamespace pfc {\r\nclass profiler_static {\r\npublic:\r\n\tprofiler_static(const char * p_name);\r\n\t~profiler_static();\r\n\tvoid add_time(t_int64 delta) {total_time+=delta;num_called++;}\r\nprivate:\r\n\tconst char * name;\r\n\tt_uint64 total_time,num_called;\r\n};\r\n\r\nclass profiler_local {\r\npublic:\r\n\tprofiler_local(profiler_static * p_owner) {\r\n\t\towner = p_owner;\r\n\t\tstart = __rdtsc();\r\n\t}\r\n\t~profiler_local() {\r\n\t\tt_int64 end = __rdtsc();\r\n\t\towner->add_time(end-start);\r\n\t}\r\nprivate:\r\n\tt_int64 start;\r\n\tprofiler_static * owner;\r\n};\r\n\r\n#define profiler(name) \\\r\n\tstatic pfc::profiler_static profiler_static_##name(#name); \\\r\n\tpfc::profiler_local profiler_local_##name(&profiler_static_##name);\r\n\t\r\n\r\nclass hires_timer {\r\npublic:\r\n\tvoid start() {\r\n\t\tm_start = g_query();\r\n\t}\r\n\tdouble query() const {\r\n\t\treturn _query( g_query() );\r\n\t}\r\n\tdouble query_reset() {\r\n\t\tt_uint64 current = g_query();\r\n\t\tdouble ret = _query(current);\r\n\t\tm_start = current;\r\n\t\treturn ret;\r\n\t}\r\nprivate:\r\n\tdouble _query(t_uint64 p_val) const {\r\n\t\treturn (double)( p_val - m_start ) / (double) g_query_freq();\r\n\t}\r\n\tstatic t_uint64 g_query() {\r\n\t\tLARGE_INTEGER val;\r\n\t\tif (!QueryPerformanceCounter(&val)) throw pfc::exception_not_implemented();\r\n\t\treturn val.QuadPart;\r\n\t}\r\n\tstatic t_uint64 g_query_freq() {\r\n\t\tLARGE_INTEGER val;\r\n\t\tif (!QueryPerformanceFrequency(&val)) throw pfc::exception_not_implemented();\r\n\t\treturn val.QuadPart;\r\n\t}\r\n\tt_uint64 m_start;\r\n};\r\n\r\nclass lores_timer {\r\npublic:\r\n\tvoid start() {\r\n\t\t_start(GetTickCount());\r\n\t}\r\n\r\n\tdouble query() const {\r\n\t\treturn _query(GetTickCount());\r\n\t}\r\n\tdouble query_reset() {\r\n\t\tt_uint32 time = GetTickCount();\r\n\t\tdouble ret = _query(time);\r\n\t\t_start(time);\r\n\t\treturn ret;\r\n\t}\r\nprivate:\r\n\tvoid _start(t_uint32 p_time) {m_last_seen = m_start = p_time;}\r\n\tdouble _query(t_uint32 p_time) const {\r\n\t\tt_uint64 time = p_time;\r\n\t\tif (time < (m_last_seen & 0xFFFFFFFF)) time += 0x100000000;\r\n\t\tm_last_seen = (m_last_seen & 0xFFFFFFFF00000000) + time;\r\n\t\treturn (double)(m_last_seen - m_start) / 1000.0;\r\n\t}\r\n\tt_uint64 m_start;\r\n\tmutable t_uint64 m_last_seen;\r\n};\r\n}\r\n#else \r\n//PORTME\r\n#endif\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/ptr_list.h",
    "content": "#ifndef __PFC_PTR_LIST_H_\r\n#define __PFC_PTR_LIST_H_\r\n\r\nnamespace pfc {\r\n\r\n\ttemplate<class T, class B = list_t<T*> >\r\n\tclass ptr_list_t : public B\r\n\t{\r\n\tpublic:\r\n\t\tptr_list_t() {}\r\n\t\tptr_list_t(const ptr_list_t<T> & p_source) {*this = p_source;}\r\n\r\n\t\tvoid free_by_idx(t_size n) {free_mask(bit_array_one(n));}\r\n\t\tvoid free_all() {this->remove_all_ex(free);}\r\n\t\tvoid free_mask(const bit_array & p_mask) {this->remove_mask_ex(p_mask,free);}\r\n\r\n\t\tvoid delete_item(T* ptr) {delete_by_idx(find_item(ptr));}\r\n\r\n\t\tvoid delete_by_idx(t_size p_index) {\r\n\t\t\tdelete_mask(bit_array_one(p_index));\r\n\t\t}\r\n\r\n\t\tvoid delete_all() {\r\n\t\t\tthis->remove_all_ex(pfc::delete_t<T>);\r\n\t\t}\r\n\r\n\t\tvoid delete_mask(const bit_array & p_mask) {\r\n\t\t\tthis->remove_mask_ex(p_mask,pfc::delete_t<T>);\r\n\t\t}\r\n\r\n\t\tT * operator[](t_size n) const {return this->get_item(n);}\r\n\t};\r\n\r\n\ttemplate<typename T,t_size N>\r\n\tclass ptr_list_hybrid_t : public ptr_list_t<T,list_hybrid_t<T*,N> > {\r\n\tpublic:\r\n\t\tptr_list_hybrid_t() {}\r\n\t\tptr_list_hybrid_t(const ptr_list_hybrid_t<T,N> & p_source) {*this = p_source;}\r\n\t};\r\n\r\n\ttypedef ptr_list_t<void> ptr_list;\r\n}\r\n\r\n\r\n#endif //__PFC_PTR_LIST_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/rcptr.h",
    "content": "namespace pfc {\r\n\r\n\tclass rc_container_base {\r\n\tpublic:\r\n\t\tlong add_ref() {\r\n\t\t\treturn ++m_counter;\r\n\t\t}\r\n\t\tlong release() {\r\n\t\t\tlong ret = --m_counter;\r\n\t\t\tif (ret == 0) delete this;\r\n\t\t\treturn ret;\r\n\t\t}\r\n\tprotected:\r\n\t\tvirtual ~rc_container_base() {}\r\n\tprivate:\r\n\t\trefcounter m_counter;\r\n\t};\r\n\r\n\ttemplate<typename t_object>\r\n\tclass rc_container_t : public rc_container_base {\r\n\tpublic:\r\n\t\tTEMPLATE_CONSTRUCTOR_FORWARD_FLOOD(rc_container_t,m_object)\r\n\r\n\t\tt_object m_object;\r\n\t};\r\n\r\n\ttemplate<typename t_object>\r\n\tclass rcptr_const_t {\r\n\tprotected:\r\n\t\ttypedef rc_container_base t_container;\r\n\t\ttypedef rc_container_t<t_object> t_container_impl;\r\n\tprivate:\r\n\t\ttypedef rcptr_const_t<t_object> t_self;\r\n\tpublic:\r\n\r\n\t\trcptr_const_t() : m_container(NULL), m_ptr(NULL) {}\r\n\t\trcptr_const_t(const t_self & p_source) : m_container(NULL), m_ptr(NULL) {*this = p_source;}\r\n\r\n\t\tvoid __set_from_cast(t_container * p_container,t_object * p_ptr) {\r\n\t\t\trelease();\r\n\t\t\tp_container->add_ref();\r\n\t\t\tm_container = p_container;\r\n\t\t\tm_ptr = p_ptr;\r\n\t\t}\r\n\r\n\t\tbool is_valid() const {return m_container != NULL;}\r\n\t\tbool is_empty() const {return m_container == NULL;}\r\n\r\n\t\tt_self const & operator=(const t_self & p_source) {\r\n\t\t\trelease(); \r\n\t\t\tif (p_source.is_valid()) {\r\n\t\t\t\tp_source.m_container->add_ref();\r\n\t\t\t\tm_container = p_source.m_container;\r\n\t\t\t\tm_ptr = p_source.m_ptr;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\t~rcptr_const_t() {release();}\r\n\r\n\t\tvoid release() {\r\n\t\t\tt_container * temp = m_container;\r\n\t\t\tm_ptr = NULL;\r\n\t\t\tm_container = NULL;\r\n\t\t\tif (temp != NULL) temp->release();\r\n\t\t}\r\n\r\n\t\tconst t_object & operator*() const {return *m_ptr;}\r\n\t\tconst t_object * operator->() const {return m_ptr;}\r\n\r\n\t\ttemplate<typename t_object_cast>\r\n\t\toperator rcptr_const_t<t_object_cast>() const {\r\n\t\t\trcptr_const_t<t_object_cast> temp;\r\n\t\t\tif (is_valid()) temp.__set_from_cast(m_container,m_ptr);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_object_cast>\r\n\t\trcptr_const_t<t_object_cast> static_cast_t() const {\r\n\t\t\trcptr_const_t<t_object_cast> temp;\r\n\t\t\tif (is_valid()) temp.__set_from_cast(m_container,static_cast<t_object_cast*>(m_ptr));\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\tbool operator==(const t_self & p_other) const {\r\n\t\t\treturn m_container == p_other.m_container;\r\n\t\t}\r\n\r\n\t\tbool operator!=(const t_self & p_other) const {\r\n\t\t\treturn m_container != p_other.m_container;\r\n\t\t}\r\n\r\n\tprotected:\r\n\t\tt_container * m_container;\r\n\t\tt_object * m_ptr;\r\n\t};\r\n\r\n\ttemplate<typename t_object>\r\n\tclass rcptr_t : public rcptr_const_t<t_object> {\r\n\tprivate:\r\n\t\ttypedef rcptr_t<t_object> t_self;\r\n\tprotected:\r\n\t\ttypedef rc_container_base t_container;\r\n\t\ttypedef rc_container_t<t_object> t_container_impl;\r\n\tpublic:\r\n\t\tt_self const & operator=(const t_self & p_source) {\r\n\t\t\tthis->release(); \r\n\t\t\tif (p_source.is_valid()) {\r\n\t\t\t\tp_source.m_container->add_ref();\r\n\t\t\t\tthis->m_container = p_source.m_container;\r\n\t\t\t\tthis->m_ptr = p_source.m_ptr;\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_object_cast>\r\n\t\toperator rcptr_t<t_object_cast>() const {\r\n\t\t\trcptr_t<t_object_cast> temp;\r\n\t\t\tif (is_valid()) temp.__set_from_cast(this->m_container,this->m_ptr);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_object_cast>\r\n\t\trcptr_t<t_object_cast> static_cast_t() const {\r\n\t\t\trcptr_t<t_object_cast> temp;\r\n\t\t\tif (is_valid()) temp.__set_from_cast(this->m_container,static_cast<t_object_cast*>(this->m_ptr));\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\tvoid new_t() {\r\n\t\t\ton_new(new t_container_impl());\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1>\r\n\t\tvoid new_t(t_param1 const & p_param1) {\r\n\t\t\ton_new(new t_container_impl(p_param1));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2>\r\n\t\tvoid new_t(t_param1 const & p_param1, t_param2 const & p_param2) {\r\n\t\t\ton_new(new t_container_impl(p_param1,p_param2));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3>\r\n\t\tvoid new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3) {\r\n\t\t\ton_new(new t_container_impl(p_param1,p_param2,p_param3));\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4>\r\n\t\tvoid new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) {\r\n\t\t\ton_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4));\r\n\t\t}\r\n\t\t\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5>\r\n\t\tvoid new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) {\r\n\t\t\ton_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4,p_param5));\r\n\t\t}\r\n\t\t\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5,typename t_param6>\r\n\t\tvoid new_t(t_param1 const & p_param1, t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5,t_param6 const & p_param6) {\r\n\t\t\ton_new(new t_container_impl(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6));\r\n\t\t}\r\n\r\n\t\tstatic t_self g_new_t() {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t();\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1>\r\n\t\tstatic t_self g_new_t(t_param1 const & p_param1) {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t(p_param1);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2>\r\n\t\tstatic t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2) {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t(p_param1,p_param2);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3>\r\n\t\tstatic t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3) {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t(p_param1,p_param2,p_param3);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4>\r\n\t\tstatic t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t(p_param1,p_param2,p_param3,p_param4);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5>\r\n\t\tstatic t_self g_new_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) {\r\n\t\t\tt_self temp;\r\n\t\t\ttemp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5);\r\n\t\t\treturn temp;\r\n\t\t}\r\n\r\n\t\tt_object & operator*() const {return *this->m_ptr;}\r\n\r\n\t\tt_object * operator->() const {return this->m_ptr;}\r\n\r\n\tprivate:\r\n\t\tvoid on_new(t_container_impl * p_container) {\r\n\t\t\tthis->release();\r\n\t\t\tp_container->add_ref();\r\n\t\t\tthis->m_ptr = &p_container->m_object;\r\n\t\t\tthis->m_container = p_container;\r\n\t\t}\r\n\t};\r\n\r\n\ttemplate<typename t_object>\r\n\trcptr_t<t_object> rcnew_t() {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t();\r\n\t\treturn temp;\t\t\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1);\r\n\t\treturn temp;\t\t\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1,typename t_param2>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1,p_param2);\r\n\t\treturn temp;\t\t\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1,typename t_param2,typename t_param3>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1,p_param2,p_param3);\r\n\t\treturn temp;\t\t\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1,typename t_param2,typename t_param3,typename t_param4>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1,p_param2,p_param3,p_param4);\r\n\t\treturn temp;\t\t\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5);\r\n\t\treturn temp;\r\n\t}\r\n\r\n\ttemplate<typename t_object,typename t_param1,typename t_param2,typename t_param3,typename t_param4,typename t_param5,typename t_param6>\r\n\trcptr_t<t_object> rcnew_t(t_param1 const & p_param1,t_param2 const & p_param2,t_param3 const & p_param3,t_param4 const & p_param4,t_param5 const & p_param5,t_param6 const & p_param6) {\r\n\t\trcptr_t<t_object> temp;\r\n\t\ttemp.new_t(p_param1,p_param2,p_param3,p_param4,p_param5,p_param6);\r\n\t\treturn temp;\r\n\t}\r\n\r\n\tclass traits_rcptr : public traits_default {\r\n\tpublic:\r\n\t\tenum { realloc_safe = true, constructor_may_fail = false };\r\n\t};\r\n\r\n\ttemplate<typename T> class traits_t<rcptr_const_t<T> > : public traits_rcptr {};\r\n\ttemplate<typename T> class traits_t<rcptr_t<T> > : public traits_rcptr {};\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/ref_counter.h",
    "content": "namespace pfc {\r\n\r\n\tclass NOVTABLE refcounted_object_root\r\n\t{\r\n\tpublic:\r\n\t\tvoid refcount_add_ref() {++m_counter;}\r\n\t\tvoid refcount_release() {if (--m_counter == 0) delete this;}\r\n\tprotected:\r\n\t\trefcounted_object_root() {}\r\n\t\tvirtual ~refcounted_object_root() {}\r\n\tprivate:\r\n\t\trefcounter m_counter;\r\n\t};\r\n\r\n\ttemplate<typename T>\r\n\tclass refcounted_object_ptr_t {\r\n\tprivate:\r\n\t\ttypedef refcounted_object_ptr_t<T> t_self;\r\n\tpublic:\r\n\t\tinline refcounted_object_ptr_t() : m_ptr(NULL) {}\r\n\t\tinline refcounted_object_ptr_t(T* p_ptr) : m_ptr(NULL) {copy(p_ptr);}\r\n\t\tinline refcounted_object_ptr_t(const t_self & p_source) : m_ptr(NULL) {copy(p_source);}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tinline refcounted_object_ptr_t(t_source * p_ptr) : m_ptr(NULL) {copy(p_ptr);}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tinline refcounted_object_ptr_t(const refcounted_object_ptr_t<t_source> & p_source) : m_ptr(NULL) {copy(p_source);}\r\n\r\n\t\tinline ~refcounted_object_ptr_t() {if (m_ptr != NULL) m_ptr->refcount_release();}\r\n\t\t\r\n\t\ttemplate<typename t_source>\r\n\t\tinline void copy(t_source * p_ptr) {\r\n\t\t\tT* torel = pfc::replace_t(m_ptr,pfc::safe_ptr_cast<T>(p_ptr));\r\n\t\t\tif (m_ptr != NULL) m_ptr->refcount_add_ref();\r\n\t\t\tif (torel != NULL) torel->refcount_release();\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_source>\r\n\t\tinline void copy(const refcounted_object_ptr_t<t_source> & p_source) {copy(p_source.get_ptr());}\r\n\r\n\r\n\t\tinline const t_self & operator=(const t_self & p_source) {copy(p_source); return *this;}\r\n\t\tinline const t_self & operator=(T * p_ptr) {copy(p_ptr); return *this;}\r\n\r\n\t\ttemplate<typename t_source> inline t_self & operator=(const refcounted_object_ptr_t<t_source> & p_source) {copy(p_source); return *this;}\r\n\t\ttemplate<typename t_source> inline t_self & operator=(t_source * p_ptr) {copy(p_ptr); return *this;}\r\n\t\t\r\n\t\tinline void release() {\r\n\t\t\tT * temp = pfc::replace_t(m_ptr,(T*)NULL);\r\n\t\t\tif (temp != NULL) temp->refcount_release();\r\n\t\t}\r\n\r\n\r\n\t\tinline T* operator->() const {PFC_ASSERT(m_ptr != NULL);return m_ptr;}\r\n\r\n\t\tinline T* get_ptr() const {return m_ptr;}\r\n\t\t\r\n\t\tinline bool is_valid() const {return m_ptr != NULL;}\r\n\t\tinline bool is_empty() const {return m_ptr == NULL;}\r\n\r\n\t\tinline bool operator==(const t_self & p_item) const {return m_ptr == p_item.get_ptr();}\r\n\t\tinline bool operator!=(const t_self & p_item) const {return m_ptr != p_item.get_ptr();}\r\n\t\tinline bool operator>(const t_self & p_item) const {return m_ptr > p_item.get_ptr();}\r\n\t\tinline bool operator<(const t_self & p_item) const {return m_ptr < p_item.get_ptr();}\r\n\r\n\r\n\t\tinline T* __unsafe_duplicate() const//should not be used ! temporary !\r\n\t\t{\r\n\t\t\tif (m_ptr) m_ptr->refcount_add_ref();\r\n\t\t\treturn m_ptr;\r\n\t\t}\r\n\r\n\t\tinline T* __unsafe_detach() {\r\n\t\t\tT* ret = m_ptr;\r\n\t\t\tm_ptr = 0;\r\n\t\t\treturn ret;\r\n\t\t}\r\n\r\n\t\tinline void __unsafe_set(T * p_ptr) {//should not be used ! temporary !\r\n\t\t\trelease();\r\n\t\t\tm_ptr = p_ptr;\r\n\t\t}\r\n\tprivate:\r\n\t\tT* m_ptr;\r\n\t};\r\n\r\n\ttemplate<typename T>\r\n\tclass traits_t<refcounted_object_ptr_t<T> > : public traits_default {\r\n\tpublic:\r\n\t\tenum { realloc_safe = true, constructor_may_fail = false};\r\n\t};\r\n\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/selftest.cpp",
    "content": "#include \"pfc.h\"\r\n\r\nstatic void selftest() //never called, testing done at compile time\r\n{\r\n\tpfc::static_assert_t<sizeof(t_uint8) == 1>();\r\n\tpfc::static_assert_t<sizeof(t_uint16) == 2>();\r\n\tpfc::static_assert_t<sizeof(t_uint32) == 4>();\r\n\tpfc::static_assert_t<sizeof(t_uint64) == 8>();\r\n\r\n\tpfc::static_assert_t<sizeof(t_int8) == 1>();\r\n\tpfc::static_assert_t<sizeof(t_int16) == 2>();\r\n\tpfc::static_assert_t<sizeof(t_int32) == 4>();\r\n\tpfc::static_assert_t<sizeof(t_int64) == 8>();\r\n\r\n\tpfc::static_assert_t<sizeof(t_float32) == 4>();\r\n\tpfc::static_assert_t<sizeof(t_float64) == 8>();\r\n\r\n\tpfc::static_assert_t<sizeof(t_size) == sizeof(void*)>();\r\n\tpfc::static_assert_t<sizeof(t_ssize) == sizeof(void*)>();\r\n\r\n\tpfc::static_assert_t<sizeof(wchar_t) == 2 || sizeof(wchar_t) == 4>();\r\n\r\n\tpfc::static_assert_t<sizeof(GUID) == 16>();\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/sort.cpp",
    "content": "#include \"pfc.h\"\r\n\r\nnamespace pfc {\r\n\r\nPFC_DLL_EXPORT void swap_void(void * item1,void * item2,t_size width)\r\n{\r\n\tunsigned char * ptr1 = (unsigned char*)item1, * ptr2 = (unsigned char*)item2;\r\n\tt_size n;\r\n\tunsigned char temp;\r\n\tfor(n=0;n<width;n++)\r\n\t{\r\n\t\ttemp = *ptr2;\r\n\t\t*ptr2 = *ptr1;\r\n\t\t*ptr1 = temp;\r\n\t\tptr1++;\r\n\t\tptr2++;\r\n\t}\r\n}\r\n\r\nPFC_DLL_EXPORT void reorder(reorder_callback & p_callback,const t_size * p_order,t_size p_count)\r\n{\r\n\tt_size done_size = bit_array_bittable::g_estimate_size(p_count);\r\n\tpfc::array_hybrid_t<unsigned char,1024> done;\r\n\tdone.set_size(done_size);\r\n\tpfc::memset_t(done,(unsigned char)0);\r\n\tt_size n;\r\n\tfor(n=0;n<p_count;n++)\r\n\t{\r\n\t\tt_size next = p_order[n];\r\n\t\tif (next!=n && !bit_array_bittable::g_get(done,n))\r\n\t\t{\r\n\t\t\tt_size prev = n;\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tassert(!bit_array_bittable::g_get(done,next));\r\n\t\t\t\tassert(next>n);\r\n\t\t\t\tassert(n<p_count);\r\n\t\t\t\tp_callback.swap(prev,next);\r\n\t\t\t\tbit_array_bittable::g_set(done,next,true);\r\n\t\t\t\tprev = next;\r\n\t\t\t\tnext = p_order[next];\r\n\t\t\t} while(next!=n);\r\n\t\t\t//bit_array_bittable::g_set(done,n,true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nPFC_DLL_EXPORT void reorder_void(void * data,t_size width,const t_size * order,t_size num,void (*swapfunc)(void * item1,void * item2,t_size width))\r\n{\r\n\tunsigned char * base = (unsigned char *) data;\r\n\tt_size done_size = bit_array_bittable::g_estimate_size(num);\r\n\tpfc::array_hybrid_t<unsigned char,1024> done;\r\n\tdone.set_size(done_size);\r\n\tpfc::memset_t(done,(unsigned char)0);\r\n\tt_size n;\r\n\tfor(n=0;n<num;n++)\r\n\t{\r\n\t\tt_size next = order[n];\r\n\t\tif (next!=n && !bit_array_bittable::g_get(done,n))\r\n\t\t{\r\n\t\t\tt_size prev = n;\r\n\t\t\tdo\r\n\t\t\t{\r\n\t\t\t\tassert(!bit_array_bittable::g_get(done,next));\r\n\t\t\t\tassert(next>n);\r\n\t\t\t\tassert(n<num);\r\n\t\t\t\tswapfunc(base+width*prev,base+width*next,width);\r\n\t\t\t\tbit_array_bittable::g_set(done,next,true);\r\n\t\t\t\tprev = next;\r\n\t\t\t\tnext = order[next];\r\n\t\t\t} while(next!=n);\r\n\t\t\t//bit_array_bittable::g_set(done,n,true);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nnamespace {\r\n\r\nclass sort_callback_impl_legacy : public sort_callback\r\n{\r\npublic:\r\n\tsort_callback_impl_legacy(\r\n\t\tvoid * p_base,t_size p_width, \r\n\t\tint (*p_comp)(const void *, const void *),\r\n\t\tvoid (*p_swap)(void *, void *, t_size)\r\n\t\t) :\r\n\tm_base((char*)p_base), m_width(p_width),\r\n\tm_comp(p_comp), m_swap(p_swap)\r\n\t{\r\n\t}\r\n\r\n\r\n\tint compare(t_size p_index1, t_size p_index2) const\r\n\t{\r\n\t\treturn m_comp(m_base + p_index1 * m_width, m_base + p_index2 * m_width);\r\n\t}\r\n\t\r\n\tvoid swap(t_size p_index1, t_size p_index2)\r\n\t{\r\n\t\tm_swap(m_base + p_index1 * m_width, m_base + p_index2 * m_width, m_width);\r\n\t}\r\n\r\nprivate:\r\n\tchar * m_base;\r\n\tt_size m_width;\r\n    int (*m_comp)(const void *, const void *);\r\n\tvoid (*m_swap)(void *, void *, t_size);\r\n};\r\n}\r\n\r\nPFC_DLL_EXPORT void sort_void_ex (\r\n    void *base,\r\n    t_size num,\r\n    t_size width,\r\n    int (*comp)(const void *, const void *),\r\n\tvoid (*swap)(void *, void *, t_size) )\r\n{\r\n\tsort(sort_callback_impl_legacy(base,width,comp,swap),num);\r\n}\r\n\r\nstatic void squaresort(pfc::sort_callback & p_callback,t_size const p_base,t_size const p_count) {\r\n\tconst t_size max = p_base + p_count;\r\n\tfor(t_size walk = p_base + 1; walk < max; ++walk) {\r\n\t\tfor(t_size prev = p_base; prev < walk; ++prev) {\r\n\t\t\tp_callback.swap_check(prev,walk);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\ninline static void __sort_2elem_helper(pfc::sort_callback & p_callback,t_size & p_elem1,t_size & p_elem2) {\r\n\tif (p_callback.compare(p_elem1,p_elem2) > 0) pfc::swap_t(p_elem1,p_elem2);\r\n}\r\n\r\ninline static t_size __pivot_helper(pfc::sort_callback & p_callback,t_size const p_base,t_size const p_count) {\r\n\tPFC_ASSERT(p_count > 1);\r\n\t//take middle element from lowest/middle/highest ones in original order. todo: try to come up with smarter approach?\r\n\tt_size val1 = p_base, val2 = p_base + (p_count / 2), val3 = p_base + (p_count - 1);\r\n\t\r\n\t__sort_2elem_helper(p_callback,val1,val2);\r\n\t__sort_2elem_helper(p_callback,val1,val3);\r\n\t__sort_2elem_helper(p_callback,val2,val3);\r\n\r\n\treturn val2;\r\n}\r\n\r\nstatic void newsort(pfc::sort_callback & p_callback,t_size const p_base,t_size const p_count) {\r\n\tif (p_count <= 4) {\r\n\t\tsquaresort(p_callback,p_base,p_count);\r\n\t\treturn;\r\n\t}\r\n\r\n\tt_size pivot = __pivot_helper(p_callback,p_base,p_count);\r\n\r\n\t{\r\n\t\tconst t_size target = p_base + p_count - 1;\r\n\t\tif (pivot != target) {\r\n\t\t\tp_callback.swap(pivot,target); pivot = target;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tt_size partition = p_base;\r\n\t{\r\n\t\tbool asdf = false;\r\n\t\tfor(t_size walk = p_base; walk < pivot; ++walk) {\r\n\t\t\tconst int comp = p_callback.compare(walk,pivot);\r\n\t\t\tbool trigger = false;\r\n\t\t\tif (comp == 0) {\r\n\t\t\t\ttrigger = asdf;\r\n\t\t\t\tasdf = !asdf;\r\n\t\t\t} else if (comp < 0) {\r\n\t\t\t\ttrigger = true;\r\n\t\t\t}\r\n\t\t\tif (trigger) {\r\n\t\t\t\tif (partition != walk) p_callback.swap(partition,walk);\r\n\t\t\t\tpartition++;\r\n\t\t\t}\r\n\t\t}\r\n\t}\t\r\n\tif (pivot != partition) {\r\n\t\tp_callback.swap(pivot,partition); pivot = partition;\r\n\t}\r\n\r\n\tnewsort(p_callback,p_base,pivot-p_base);\r\n\tnewsort(p_callback,pivot+1,p_count-(pivot+1-p_base));\r\n}\r\n\r\nvoid sort(pfc::sort_callback & p_callback,t_size p_num) {\r\n\tnewsort(p_callback,0,p_num);\r\n}\r\n\r\n\r\nPFC_DLL_EXPORT void sort_void(void * base,t_size num,t_size width,int (*comp)(const void *, const void *) )\r\n{\r\n\tsort_void_ex(base,num,width,comp,swap_void);\r\n}\r\n\r\n\r\n\r\n\r\nsort_callback_stabilizer::sort_callback_stabilizer(sort_callback & p_chain,t_size p_count)\r\n: m_chain(p_chain)\r\n{\r\n\tm_order.set_size(p_count);\r\n\tt_size n;\r\n\tfor(n=0;n<p_count;n++) m_order[n] = n;\r\n}\r\n\r\nint sort_callback_stabilizer::compare(t_size p_index1, t_size p_index2) const\r\n{\r\n\tint ret = m_chain.compare(p_index1,p_index2);\r\n\tif (ret == 0) ret = pfc::sgn_t((t_ssize)m_order[p_index1] - (t_ssize)m_order[p_index2]);\r\n\treturn ret;\r\n}\r\n\r\nvoid sort_callback_stabilizer::swap(t_size p_index1, t_size p_index2)\r\n{\r\n\tm_chain.swap(p_index1,p_index2);\r\n\tpfc::swap_t(m_order[p_index1],m_order[p_index2]);\r\n}\r\n\r\n\r\nPFC_DLL_EXPORT void sort_stable(sort_callback & p_callback,t_size p_count)\r\n{\r\n\tsort(sort_callback_stabilizer(p_callback,p_count),p_count);\r\n}\r\n\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/sort.h",
    "content": "namespace pfc {\r\n\r\n\tPFC_DLL_EXPORT void swap_void(void * item1,void * item2,t_size width);\r\n\r\n\tPFC_DLL_EXPORT void reorder_void(void * data,t_size width,const t_size * order,t_size num,void (*swapfunc)(void * item1,void * item2,t_size width) = swap_void);\r\n\r\n\tclass NOVTABLE reorder_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual void swap(t_size p_index1,t_size p_index2) = 0;\r\n\t};\r\n\r\n\tPFC_DLL_EXPORT void reorder(reorder_callback & p_callback,const t_size * p_order,t_size p_count);\r\n\r\n\ttemplate<typename t_container>\r\n\tclass reorder_callback_impl_t : public reorder_callback\r\n\t{\r\n\tpublic:\r\n\t\treorder_callback_impl_t(t_container & p_data) : m_data(p_data) {}\r\n\t\tvoid swap(t_size p_index1,t_size p_index2)\r\n\t\t{\r\n\t\t\tpfc::swap_t(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tt_container & m_data;\r\n\t};\r\n\r\n\tclass reorder_callback_impl_delta : public reorder_callback\r\n\t{\r\n\tpublic:\r\n\t\treorder_callback_impl_delta(reorder_callback & p_data,t_size p_delta) : m_data(p_data), m_delta(p_delta) {}\r\n\t\tvoid swap(t_size p_index1,t_size p_index2)\r\n\t\t{\r\n\t\t\tm_data.swap(p_index1+m_delta,p_index2+m_delta);\r\n\t\t}\r\n\tprivate:\r\n\t\treorder_callback & m_data;\r\n\t\tt_size m_delta;\r\n\t};\r\n\r\n\ttemplate<typename t_container>\r\n\tvoid reorder_t(t_container & p_data,const t_size * p_order,t_size p_count)\r\n\t{\r\n\t\treorder(reorder_callback_impl_t<t_container>(p_data),p_order,p_count);\r\n\t}\r\n\r\n\ttemplate<typename t_container>\r\n\tvoid reorder_partial_t(t_container & p_data,t_size p_base,const t_size * p_order,t_size p_count)\r\n\t{\r\n\t\treorder(reorder_callback_impl_delta(reorder_callback_impl_t<t_container>(p_data),p_base),p_order,p_count);\r\n\t}\r\n\t\r\n\ttemplate<typename T>\r\n\tclass reorder_callback_impl_ptr_t : public reorder_callback\r\n\t{\r\n\tpublic:\r\n\t\treorder_callback_impl_ptr_t(T * p_data) : m_data(p_data) {}\r\n\t\tvoid swap(t_size p_index1,t_size p_index2)\r\n\t\t{\r\n\t\t\tpfc::swap_t(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tT* m_data;\r\n\t};\r\n\r\n\r\n\ttemplate<typename T>\r\n\tvoid reorder_ptr_t(T* p_data,const t_size * p_order,t_size p_count)\r\n\t{\r\n\t\treorder(reorder_callback_impl_ptr_t<T>(p_data),p_order,p_count);\r\n\t}\r\n\r\n\r\n\r\n\tclass NOVTABLE sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tvirtual int compare(t_size p_index1, t_size p_index2) const = 0;\r\n\t\tvirtual void swap(t_size p_index1, t_size p_index2) = 0;\r\n\t\tvoid swap_check(t_size p_index1, t_size p_index2) {if (compare(p_index1,p_index2) > 0) swap(p_index1,p_index2);}\r\n\t};\r\n\r\n\tclass sort_callback_stabilizer : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_stabilizer(sort_callback & p_chain,t_size p_count);\r\n\t\tvirtual int compare(t_size p_index1, t_size p_index2) const;\r\n\t\tvirtual void swap(t_size p_index1, t_size p_index2);\r\n\tprivate:\r\n\t\tsort_callback & m_chain;\r\n\t\tarray_t<t_size> m_order;\r\n\t};\r\n\r\n\tPFC_DLL_EXPORT void sort(sort_callback & p_callback,t_size p_count);\r\n\tPFC_DLL_EXPORT void sort_stable(sort_callback & p_callback,t_size p_count);\r\n\r\n\tPFC_DLL_EXPORT void sort_void_ex(void *base,t_size num,t_size width, int (*comp)(const void *, const void *),void (*swap)(void *, void *, t_size) );\r\n\tPFC_DLL_EXPORT void sort_void(void * base,t_size num,t_size width,int (*comp)(const void *, const void *) );\r\n\r\n\ttemplate<typename t_container,typename t_compare>\r\n\tclass sort_callback_impl_simple_wrap_t : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_impl_simple_wrap_t(t_container & p_data, t_compare p_compare) : m_data(p_data), m_compare(p_compare) {}\r\n\t\tint compare(t_size p_index1, t_size p_index2) const\r\n\t\t{\r\n\t\t\treturn m_compare(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\r\n\t\tvoid swap(t_size p_index1, t_size p_index2)\r\n\t\t{\r\n\t\t\tswap_t(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tt_container & m_data;\r\n\t\tt_compare m_compare;\r\n\t};\r\n\r\n\ttemplate<typename t_container>\r\n\tclass sort_callback_impl_auto_wrap_t : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_impl_auto_wrap_t(t_container & p_data) : m_data(p_data) {}\r\n\t\tint compare(t_size p_index1, t_size p_index2) const\r\n\t\t{\r\n\t\t\treturn compare_t(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\r\n\t\tvoid swap(t_size p_index1, t_size p_index2)\r\n\t\t{\r\n\t\t\tswap_t(m_data[p_index1],m_data[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tt_container & m_data;\r\n\t};\r\n\r\n\ttemplate<typename t_container,typename t_compare,typename t_permutation>\r\n\tclass sort_callback_impl_permutation_wrap_t : public sort_callback\r\n\t{\r\n\tpublic:\r\n\t\tsort_callback_impl_permutation_wrap_t(const t_container & p_data, t_compare p_compare,t_permutation const & p_permutation) : m_data(p_data), m_compare(p_compare), m_permutation(p_permutation) {}\r\n\t\tint compare(t_size p_index1, t_size p_index2) const\r\n\t\t{\r\n\t\t\treturn m_compare(m_data[m_permutation[p_index1]],m_data[m_permutation[p_index2]]);\r\n\t\t}\r\n\r\n\t\tvoid swap(t_size p_index1, t_size p_index2)\r\n\t\t{\r\n\t\t\tswap_t(m_permutation[p_index1],m_permutation[p_index2]);\r\n\t\t}\r\n\tprivate:\r\n\t\tconst t_container & m_data;\r\n\t\tt_compare m_compare;\r\n\t\tt_permutation const & m_permutation;\r\n\t};\r\n\r\n\ttemplate<typename t_container,typename t_compare>\r\n\tstatic void sort_t(t_container & p_data,t_compare p_compare,t_size p_count)\r\n\t{\r\n\t\tsort(sort_callback_impl_simple_wrap_t<t_container,t_compare>(p_data,p_compare),p_count);\r\n\t}\r\n\r\n\ttemplate<typename t_container,typename t_compare>\r\n\tstatic void sort_stable_t(t_container & p_data,t_compare p_compare,t_size p_count)\r\n\t{\r\n\t\tsort_stable(sort_callback_impl_simple_wrap_t<t_container,t_compare>(p_data,p_compare),p_count);\r\n\t}\r\n\r\n\ttemplate<typename t_container,typename t_compare,typename t_permutation>\r\n\tstatic void sort_get_permutation_t(const t_container & p_data,t_compare p_compare,t_size p_count,t_permutation const & p_permutation)\r\n\t{\r\n\t\tsort(sort_callback_impl_permutation_wrap_t<t_container,t_compare,t_permutation>(p_data,p_compare,p_permutation),p_count);\r\n\t}\r\n\r\n\ttemplate<typename t_container,typename t_compare,typename t_permutation>\r\n\tstatic void sort_stable_get_permutation_t(const t_container & p_data,t_compare p_compare,t_size p_count,t_permutation const & p_permutation)\r\n\t{\r\n\t\tsort_stable(sort_callback_impl_permutation_wrap_t<t_container,t_compare,t_permutation>(p_data,p_compare,p_permutation),p_count);\r\n\t}\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/stdafx.cpp",
    "content": "//cpp used to generate precompiled header\r\n#include \"pfc.h\""
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string.cpp",
    "content": "#include \"pfc.h\"\r\n\r\nnamespace pfc {\r\n\r\nvoid string_receiver::add_char(t_uint32 p_char)\r\n{\r\n\tchar temp[8];\r\n\tt_size len = utf8_encode_char(p_char,temp);\r\n\tif (len>0) add_string(temp,len);\r\n}\r\n\r\nvoid string_base::skip_trailing_char(unsigned skip)\r\n{\r\n\tconst char * str = get_ptr();\r\n\tt_size ptr,trunc;\r\n\tbool need_trunc = false;\r\n\tfor(ptr=0;str[ptr];)\r\n\t{\r\n\t\tunsigned c;\r\n\t\tt_size delta = utf8_decode_char(str+ptr,&c);\r\n\t\tif (delta==0) break;\r\n\t\tif (c==skip)\r\n\t\t{\r\n\t\t\tneed_trunc = true;\r\n\t\t\ttrunc = ptr;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tneed_trunc = false;\r\n\t\t}\r\n\t\tptr += delta;\r\n\t}\r\n\tif (need_trunc) truncate(trunc);\r\n}\r\n\r\nformat_time::format_time(t_uint64 p_seconds) {\r\n\tt_uint64 length = p_seconds;\r\n\tunsigned weeks,days,hours,minutes,seconds;\r\n\t\r\n\tweeks = (unsigned)( ( length / (60*60*24*7) ) );\r\n\tdays = (unsigned)( ( length / (60*60*24) ) % 7 );\r\n\thours = (unsigned) ( ( length / (60 * 60) ) % 24);\r\n\tminutes = (unsigned) ( ( length / (60 ) ) % 60 );\r\n\tseconds = (unsigned) ( ( length ) % 60 );\r\n\r\n\tif (weeks) {\r\n\t\tm_buffer << weeks << \"wk \";\r\n\t}\r\n\tif (days || weeks) {\r\n\t\tm_buffer << days << \"d \";\r\n\t}\r\n\tif (hours || days || weeks) {\r\n\t\tm_buffer << hours << \":\" << format_uint(minutes,2) << \":\" << format_uint(seconds,2);\r\n\t} else {\r\n\t\tm_buffer << minutes << \":\" << format_uint(seconds,2);\r\n\t}\r\n}\r\n\r\nint strcmp_partial(const char * p_string,const char * p_substring) {return strcmp_partial_ex(p_string,infinite,p_substring,infinite);}\r\n\r\nstatic int __strcmp_partial_ex(const char * p_string,t_size p_string_length,const char * p_substring,t_size p_substring_length) throw() {\r\n\tfor(t_size walk=0;walk<p_substring_length;walk++) {\r\n\t\tchar stringchar = (walk>=p_string_length ? 0 : p_string[walk]);\r\n\t\tchar substringchar = p_substring[walk];\r\n\t\tint result = compare_t(stringchar,substringchar);\r\n\t\tif (result != 0) return result;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nint strcmp_partial_ex(const char * p_string,t_size p_string_length,const char * p_substring,t_size p_substring_length) /*throw()*/ {\r\n\tp_string_length = strlen_max(p_string,p_string_length); p_substring_length = strlen_max(p_substring,p_substring_length);\r\n\treturn __strcmp_partial_ex(p_string,p_string_length,p_substring,p_substring_length);\r\n}\r\n\r\nbool is_path_separator(unsigned c)\r\n{\r\n\treturn c=='\\\\' || c=='/' || c=='|' || c==':';\r\n}\r\n\r\nbool is_path_bad_char(unsigned c)\r\n{\r\n#ifdef _WINDOWS\r\n\treturn c=='\\\\' || c=='/' || c=='|' || c==':' || c=='*' || c=='?' || c=='\\\"' || c=='>' || c=='<';\r\n#else\r\n#error portme\r\n#endif\r\n}\r\n\r\n\r\n\r\nchar * strdup_n(const char * src,t_size len)\r\n{\r\n\tlen = strlen_max(src,len);\r\n\tchar * ret = (char*)malloc(len+1);\r\n\tif (ret)\r\n\t{\r\n\t\tmemcpy(ret,src,len);\r\n\t\tret[len]=0;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nstring_filename::string_filename(const char * fn)\r\n{\r\n\tfn += pfc::scan_filename(fn);\r\n\tconst char * ptr=fn,*dot=0;\r\n\twhile(*ptr && *ptr!='?')\r\n\t{\r\n\t\tif (*ptr=='.') dot=ptr;\r\n\t\tptr++;\r\n\t}\r\n\r\n\tif (dot && dot>fn) set_string(fn,dot-fn);\r\n\telse set_string(fn);\r\n}\r\n\r\nstring_filename_ext::string_filename_ext(const char * fn)\r\n{\r\n\tfn += pfc::scan_filename(fn);\r\n\tconst char * ptr = fn;\r\n\twhile(*ptr && *ptr!='?') ptr++;\r\n\tset_string(fn,ptr-fn);\r\n}\r\n\r\nstring_extension::string_extension(const char * src)\r\n{\r\n\tbuffer[0]=0;\r\n\tconst char * start = src + pfc::scan_filename(src);\r\n\tconst char * end = start + strlen(start);\r\n\tconst char * ptr = end-1;\r\n\twhile(ptr>start && *ptr!='.')\r\n\t{\r\n\t\tif (*ptr=='?') end=ptr;\r\n\t\tptr--;\r\n\t}\r\n\r\n\tif (ptr>=start && *ptr=='.')\r\n\t{\r\n\t\tptr++;\r\n\t\tt_size len = end-ptr;\r\n\t\tif (len<tabsize(buffer))\r\n\t\t{\r\n\t\t\tmemcpy(buffer,ptr,len*sizeof(char));\r\n\t\t\tbuffer[len]=0;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\nbool has_path_bad_chars(const char * param)\r\n{\r\n\twhile(*param)\r\n\t{\r\n\t\tif (is_path_bad_char(*param)) return true;\r\n\t\tparam++;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nvoid float_to_string(char * out,t_size out_max,double val,unsigned precision,bool b_sign) {\r\n\tpfc::string_fixed_t<63> temp;\r\n\tt_size outptr;\r\n\r\n\tif (out_max == 0) return;\r\n\tout_max--;//for null terminator\r\n\t\r\n\toutptr = 0;\t\r\n\r\n\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\r\n\tif (val<0) {out[outptr++] = '-'; val = -val;}\r\n\telse if (b_sign) {out[outptr++] = '+';}\r\n\r\n\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\r\n\t\r\n\t{\r\n\t\tdouble powval = pow((double)10.0,(double)precision);\r\n\t\ttemp << (t_int64)floor(val * powval + 0.5);\r\n\t\t//_i64toa(blargh,temp,10);\r\n\t}\r\n\t\r\n\tconst t_size temp_len = temp.length();\r\n\tif (temp_len <= precision)\r\n\t{\r\n\t\tout[outptr++] = '0';\r\n\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\tout[outptr++] = '.';\r\n\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\tt_size d;\r\n\t\tfor(d=precision-temp_len;d;d--)\r\n\t\t{\r\n\t\t\tout[outptr++] = '0';\r\n\t\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\t}\r\n\t\tfor(d=0;d<temp_len;d++)\r\n\t\t{\r\n\t\t\tout[outptr++] = temp[d];\r\n\t\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tt_size d = temp_len;\r\n\t\tconst char * src = temp;\r\n\t\twhile(*src)\r\n\t\t{\r\n\t\t\tif (d-- == precision)\r\n\t\t\t{\r\n\t\t\t\tout[outptr++] = '.';\r\n\t\t\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\t\t}\r\n\t\t\tout[outptr++] = *(src++);\r\n\t\t\tif (outptr == out_max) {out[outptr]=0;return;}\r\n\t\t}\r\n\t}\r\n\tout[outptr] = 0;\r\n}\r\n\r\nstatic double pfc_string_to_float_internal(const char * src)\r\n{\r\n\tbool neg = false;\r\n\tt_int64 val = 0;\r\n\tint div = 0;\r\n\tbool got_dot = false;\r\n\r\n\twhile(*src==' ') src++;\r\n\r\n\tif (*src=='-') {neg = true;src++;}\r\n\telse if (*src=='+') src++;\r\n\t\r\n\twhile(*src)\r\n\t{\r\n\t\tif (*src>='0' && *src<='9')\r\n\t\t{\r\n\t\t\tint d = *src - '0';\r\n\t\t\tval = val * 10 + d;\r\n\t\t\tif (got_dot) div--;\r\n\t\t\tsrc++;\r\n\t\t}\r\n\t\telse if (*src=='.' || *src==',')\r\n\t\t{\r\n\t\t\tif (got_dot) break;\r\n\t\t\tgot_dot = true;\r\n\t\t\tsrc++;\r\n\t\t}\r\n\t\telse if (*src=='E' || *src=='e')\r\n\t\t{\r\n\t\t\tsrc++;\r\n\t\t\tdiv += atoi(src);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse break;\r\n\t}\r\n\tif (neg) val = -val;\r\n\treturn (double) val * pow(10.0,(double)div);\r\n}\r\n\r\ndouble string_to_float(const char * src,t_size max) {\r\n\t//old function wants an oldstyle nullterminated string, and i don't currently care enough to rewrite it as it works appropriately otherwise\r\n\tchar blargh[128];\r\n\tif (max > 127) max = 127;\r\n\tt_size walk;\r\n\tfor(walk = 0; walk < max && src[walk]; walk++) blargh[walk] = src[walk];\r\n\tblargh[walk] = 0;\r\n\treturn pfc_string_to_float_internal(blargh);\r\n}\r\n\r\n\r\n\r\nvoid string_base::convert_to_lower_ascii(const char * src,char replace)\r\n{\r\n\treset();\r\n\tPFC_ASSERT(replace>0);\r\n\twhile(*src)\r\n\t{\r\n\t\tunsigned c;\r\n\t\tt_size delta = utf8_decode_char(src,&c);\r\n\t\tif (delta==0) {c = replace; delta = 1;}\r\n\t\telse if (c>=0x80) c = replace;\r\n\t\tadd_byte((char)c);\r\n\t\tsrc += delta;\r\n\t}\r\n}\r\n\r\nvoid convert_to_lower_ascii(const char * src,t_size max,char * out,char replace)\r\n{\r\n\tt_size ptr = 0;\r\n\tPFC_ASSERT(replace>0);\r\n\twhile(ptr<max && src[ptr])\r\n\t{\r\n\t\tunsigned c;\r\n\t\tt_size delta = utf8_decode_char(src+ptr,&c,max-ptr);\r\n\t\tif (delta==0) {c = replace; delta = 1;}\r\n\t\telse if (c>=0x80) c = replace;\r\n\t\t*(out++) = (char)c;\r\n\t\tptr += delta;\r\n\t}\r\n\t*out = 0;\r\n}\r\n\r\nt_size strstr_ex(const char * p_string,t_size p_string_len,const char * p_substring,t_size p_substring_len)\r\n{\r\n\tp_string_len = strlen_max(p_string,p_string_len);\r\n\tp_substring_len = strlen_max(p_substring,p_substring_len);\r\n\tt_size index = 0;\r\n\twhile(index + p_substring_len <= p_string_len)\r\n\t{\r\n\t\tif (memcmp(p_string+index,p_substring,p_substring_len) == 0) return index;\r\n\t\tt_size delta = utf8_char_len(p_string+index,p_string_len - index);\r\n\t\tif (delta == 0) break;\r\n\t\tindex += delta;\r\n\t}\r\n\treturn ~0;\r\n}\r\n\r\nunsigned atoui_ex(const char * p_string,t_size p_string_len)\r\n{\r\n\tunsigned ret = 0; t_size ptr = 0;\r\n\twhile(ptr<p_string_len)\r\n\t{\r\n\t\tchar c = p_string[ptr];\r\n\t\tif (! ( c >= '0' && c <= '9' ) ) break;\r\n\t\tret = ret * 10 + (unsigned)( c - '0' );\r\n\t\tptr++;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nint strcmp_ex(const char* p1,t_size n1,const char* p2,t_size n2)\r\n{\r\n\tt_size idx = 0;\r\n\tn1 = strlen_max(p1,n1); n2 = strlen_max(p2,n2);\r\n\tfor(;;)\r\n\t{\r\n\t\tif (idx == n1 && idx == n2) return 0;\r\n\t\telse if (idx == n1) return -1;//end of param1\r\n\t\telse if (idx == n2) return 1;//end of param2\r\n\r\n\t\tchar c1 = p1[idx], c2 = p2[idx];\r\n\t\tif (c1<c2) return -1;\r\n\t\telse if (c1>c2) return 1;\r\n\t\t\r\n\t\tidx++;\r\n\t}\r\n}\r\n\r\nt_uint64 atoui64_ex(const char * src,t_size len) {\r\n\tlen = strlen_max(src,len);\r\n\tt_uint64 ret = 0, mul = 1;\r\n\tt_size ptr = len;\r\n\tt_size start = 0;\r\n//\tstart += skip_spacing(src+start,len-start);\r\n\t\r\n\twhile(ptr>start)\r\n\t{\r\n\t\tchar c = src[--ptr];\r\n\t\tif (c>='0' && c<='9')\r\n\t\t{\r\n\t\t\tret += (c-'0') * mul;\r\n\t\t\tmul *= 10;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tret = 0;\r\n\t\t\tmul = 1;\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n\r\nt_int64 atoi64_ex(const char * src,t_size len)\r\n{\r\n\tlen = strlen_max(src,len);\r\n\tt_int64 ret = 0, mul = 1;\r\n\tt_size ptr = len;\r\n\tt_size start = 0;\r\n\tbool neg = false;\r\n//\tstart += skip_spacing(src+start,len-start);\r\n\tif (start < len && src[start] == '-') {neg = true; start++;}\r\n//\tstart += skip_spacing(src+start,len-start);\r\n\t\r\n\twhile(ptr>start)\r\n\t{\r\n\t\tchar c = src[--ptr];\r\n\t\tif (c>='0' && c<='9')\r\n\t\t{\r\n\t\t\tret += (c-'0') * mul;\r\n\t\t\tmul *= 10;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tret = 0;\r\n\t\t\tmul = 1;\r\n\t\t}\r\n\t}\r\n\treturn neg ? -ret : ret;\r\n}\r\n\r\nint stricmp_ascii_ex(const char * const s1,t_size const len1,const char * const s2,t_size const len2) {\r\n\tt_size walk1 = 0, walk2 = 0;\r\n\tfor(;;) {\r\n\t\tchar c1 = (walk1 < len1) ? s1[walk1] : 0;\r\n\t\tchar c2 = (walk2 < len2) ? s2[walk2] : 0;\r\n\t\tc1 = ascii_tolower(c1); c2 = ascii_tolower(c2);\r\n\t\tif (c1<c2) return -1;\r\n\t\telse if (c1>c2) return 1;\r\n\t\telse if (c1 == 0) return 0;\r\n\t\twalk1++;\r\n\t\twalk2++;\r\n\t}\r\n\r\n}\r\nint stricmp_ascii(const char * s1,const char * s2) {\r\n\tfor(;;) {\r\n\t\tchar c1 = ascii_tolower(*s1), c2 = ascii_tolower(*s2);\r\n\t\tif (c1<c2) return -1;\r\n\t\telse if (c1>c2) return 1;\r\n\t\telse if (c1 == 0) return 0;\r\n\t\ts1++;\r\n\t\ts2++;\r\n\t}\r\n}\r\n\r\nformat_float::format_float(double p_val,unsigned p_width,unsigned p_prec)\r\n{\r\n\tchar temp[64];\r\n\tfloat_to_string(temp,64,p_val,p_prec,false);\r\n\ttemp[63] = 0;\r\n\tt_size len = strlen(temp);\r\n\tif (len < p_width)\r\n\t\tm_buffer.add_chars(' ',p_width-len);\r\n\tm_buffer += temp;\r\n}\r\n\r\nstatic char format_hex_char(unsigned p_val)\r\n{\r\n\tPFC_ASSERT(p_val < 16);\r\n\treturn (p_val < 10) ? p_val + '0' : p_val - 10 + 'A';\r\n}\r\n\r\nformat_hex::format_hex(t_uint64 p_val,unsigned p_width)\r\n{\r\n\tif (p_width > 16) p_width = 16;\r\n\telse if (p_width == 0) p_width = 1;\r\n\tchar temp[16];\r\n\tunsigned n;\r\n\tfor(n=0;n<16;n++)\r\n\t{\r\n\t\ttemp[15-n] = format_hex_char((unsigned)(p_val & 0xF));\r\n\t\tp_val >>= 4;\r\n\t}\r\n\r\n\tfor(n=0;n<16 && temp[n] == '0';n++) {}\r\n\t\r\n\tif (n > 16 - p_width) n = 16 - p_width;\r\n\t\r\n\tchar * out = m_buffer;\r\n\tfor(;n<16;n++)\r\n\t\t*(out++) = temp[n];\r\n\t*out = 0;\r\n}\r\n\r\nstatic char format_hex_char_lowercase(unsigned p_val)\r\n{\r\n\tPFC_ASSERT(p_val < 16);\r\n\treturn (p_val < 10) ? p_val + '0' : p_val - 10 + 'a';\r\n}\r\n\r\nformat_hex_lowercase::format_hex_lowercase(t_uint64 p_val,unsigned p_width)\r\n{\r\n\tif (p_width > 16) p_width = 16;\r\n\telse if (p_width == 0) p_width = 1;\r\n\tchar temp[16];\r\n\tunsigned n;\r\n\tfor(n=0;n<16;n++)\r\n\t{\r\n\t\ttemp[15-n] = format_hex_char_lowercase((unsigned)(p_val & 0xF));\r\n\t\tp_val >>= 4;\r\n\t}\r\n\r\n\tfor(n=0;n<16 && temp[n] == '0';n++) {}\r\n\t\r\n\tif (n > 16 - p_width) n = 16 - p_width;\r\n\t\r\n\tchar * out = m_buffer;\r\n\tfor(;n<16;n++)\r\n\t\t*(out++) = temp[n];\r\n\t*out = 0;\r\n}\r\n\r\nformat_uint::format_uint(t_uint64 val,unsigned p_width,unsigned p_base)\r\n{\r\n\t\r\n\tenum {max_width = tabsize(m_buffer) - 1};\r\n\r\n\tif (p_width > max_width) p_width = max_width;\r\n\telse if (p_width == 0) p_width = 1;\r\n\r\n\tchar temp[max_width];\r\n\t\r\n\tunsigned n;\r\n\tfor(n=0;n<max_width;n++)\r\n\t{\r\n\t\ttemp[max_width-1-n] = format_hex_char((unsigned)(val % p_base));\r\n\t\tval /= p_base;\r\n\t}\r\n\r\n\tfor(n=0;n<max_width && temp[n] == '0';n++) {}\r\n\t\r\n\tif (n > max_width - p_width) n = max_width - p_width;\r\n\t\r\n\tchar * out = m_buffer;\r\n\r\n\tfor(;n<max_width;n++)\r\n\t\t*(out++) = temp[n];\r\n\t*out = 0;\r\n}\r\n\r\nformat_fixedpoint::format_fixedpoint(t_int64 p_val,unsigned p_point)\r\n{\r\n\tunsigned div = 1;\r\n\tfor(unsigned n=0;n<p_point;n++) div *= 10;\r\n\r\n\tif (p_val < 0) {m_buffer << \"-\";p_val = -p_val;}\r\n\r\n\t\r\n\tm_buffer << format_int(p_val / div) << \".\" << format_int(p_val % div, p_point);\r\n}\r\n\r\nformat_int::format_int(t_int64 p_val,unsigned p_width,unsigned p_base)\r\n{\r\n\tbool neg = false;\r\n\tt_uint64 val;\r\n\tif (p_val < 0) {neg = true; val = (t_uint64)(-p_val);}\r\n\telse val = (t_uint64)p_val;\r\n\t\r\n\tenum {max_width = tabsize(m_buffer) - 1};\r\n\r\n\tif (p_width > max_width) p_width = max_width;\r\n\telse if (p_width == 0) p_width = 1;\r\n\r\n\tif (neg && p_width > 1) p_width --;\r\n\t\r\n\tchar temp[max_width];\r\n\t\r\n\tunsigned n;\r\n\tfor(n=0;n<max_width;n++)\r\n\t{\r\n\t\ttemp[max_width-1-n] = format_hex_char((unsigned)(val % p_base));\r\n\t\tval /= p_base;\r\n\t}\r\n\r\n\tfor(n=0;n<max_width && temp[n] == '0';n++) {}\r\n\t\r\n\tif (n > max_width - p_width) n = max_width - p_width;\r\n\t\r\n\tchar * out = m_buffer;\r\n\r\n\tif (neg) *(out++) = '-';\r\n\r\n\tfor(;n<max_width;n++)\r\n\t\t*(out++) = temp[n];\r\n\t*out = 0;\r\n}\r\n\r\nformat_hexdump_lowercase::format_hexdump_lowercase(const void * p_buffer,t_size p_bytes,const char * p_spacing)\r\n{\r\n\tt_size n;\r\n\tconst t_uint8 * buffer = (const t_uint8*)p_buffer;\r\n\tfor(n=0;n<p_bytes;n++)\r\n\t{\r\n\t\tif (n > 0 && p_spacing != 0) m_formatter << p_spacing;\r\n\t\tm_formatter << format_hex_lowercase(buffer[n],2);\r\n\t}\r\n}\r\n\r\nformat_hexdump::format_hexdump(const void * p_buffer,t_size p_bytes,const char * p_spacing)\r\n{\r\n\tt_size n;\r\n\tconst t_uint8 * buffer = (const t_uint8*)p_buffer;\r\n\tfor(n=0;n<p_bytes;n++)\r\n\t{\r\n\t\tif (n > 0 && p_spacing != 0) m_formatter << p_spacing;\r\n\t\tm_formatter << format_hex(buffer[n],2);\r\n\t}\r\n}\r\n\r\n\r\n\r\nstring_replace_extension::string_replace_extension(const char * p_path,const char * p_ext)\r\n{\r\n\tm_data = p_path;\r\n\tt_size dot = m_data.find_last('.');\r\n\tif (dot < m_data.scan_filename())\r\n\t{//argh\r\n\t\tm_data += \".\";\r\n\t\tm_data += p_ext;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tm_data.truncate(dot+1);\r\n\t\tm_data += p_ext;\r\n\t}\r\n}\r\n\r\nstring_directory::string_directory(const char * p_path)\r\n{\r\n\tt_size ptr = scan_filename(p_path);\r\n\tif (ptr > 0) m_data.set_string(p_path,ptr-1);\r\n}\r\n\r\nt_size scan_filename(const char * ptr)\r\n{\r\n\tt_size n;\r\n\tt_size _used = strlen(ptr);\r\n\tfor(n=_used-1;n!=~0;n--)\r\n\t{\r\n\t\tif (is_path_separator(ptr[n])) return n+1;\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\n\r\n\r\nt_size string_find_first(const char * p_string,char p_tofind,t_size p_start) {\r\n\treturn string_find_first_ex(p_string,infinite,&p_tofind,1,p_start);\r\n}\r\nt_size string_find_last(const char * p_string,char p_tofind,t_size p_start) {\r\n\treturn string_find_last_ex(p_string,infinite,&p_tofind,1,p_start);\r\n}\r\nt_size string_find_first(const char * p_string,const char * p_tofind,t_size p_start) {\r\n\treturn string_find_first_ex(p_string,infinite,p_tofind,infinite,p_start);\r\n}\r\nt_size string_find_last(const char * p_string,const char * p_tofind,t_size p_start) {\r\n\treturn string_find_last_ex(p_string,infinite,p_tofind,infinite,p_start);\r\n}\r\n\r\nt_size string_find_first_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start) {\r\n\treturn string_find_first_ex(p_string,p_string_length,&p_tofind,1,p_start);\r\n}\r\nt_size string_find_last_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start) {\r\n\treturn string_find_last_ex(p_string,p_string_length,&p_tofind,1,p_start);\r\n}\r\nt_size string_find_first_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start) {\r\n\tp_string_length = strlen_max(p_string,p_string_length); p_tofind_length = strlen_max(p_tofind,p_tofind_length);\r\n\tif (p_string_length >= p_tofind_length) {\r\n\t\tt_size max = p_string_length - p_tofind_length;\r\n\t\tfor(t_size walk = p_start; walk <= max; walk++) {\r\n\t\t\tif (__strcmp_partial_ex(p_string+walk,p_string_length-walk,p_tofind,p_tofind_length) == 0) return walk;\r\n\t\t}\r\n\t}\r\n\treturn infinite;\r\n}\r\nt_size string_find_last_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start) {\r\n\tp_string_length = strlen_max(p_string,p_string_length); p_tofind_length = strlen_max(p_tofind,p_tofind_length);\r\n\tif (p_string_length >= p_tofind_length) {\r\n\t\tt_size max = min_t<t_size>(p_string_length - p_tofind_length,p_start);\r\n\t\tfor(t_size walk = max; walk != (t_size)(-1); walk--) {\r\n\t\t\tif (__strcmp_partial_ex(p_string+walk,p_string_length-walk,p_tofind,p_tofind_length) == 0) return walk;\r\n\t\t}\r\n\t}\r\n\treturn infinite;\r\n}\r\n\r\n\r\nbool string_is_numeric(const char * p_string,t_size p_length) {\r\n\tbool retval = false;\r\n\tfor(t_size walk = 0; walk < p_length && p_string[walk] != 0; walk++) {\r\n\t\tif (!char_is_numeric(p_string[walk])) {retval = false; break;}\r\n\t\tretval = true;\r\n\t}\r\n\treturn retval;\r\n}\r\n\r\n\r\nvoid string_base::fix_dir_separator(char p_char) {\r\n\tt_size length = get_length();\r\n\tif (length == 0 || get_ptr()[length-1] != p_char) add_byte(p_char);\r\n}\r\n\r\nbool is_multiline(const char * p_string,t_size p_len) {\r\n\tfor(t_size n = 0; n < p_len && p_string[n]; n++) {\r\n\t\tswitch(p_string[n]) {\r\n\t\tcase '\\r':\r\n\t\tcase '\\n':\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nstatic t_uint64 pow10_helper(unsigned p_extra) {\r\n\tt_uint64 ret = 1;\r\n\tfor(unsigned n = 0; n < p_extra; n++ ) ret *= 10;\r\n\treturn ret;\r\n}\r\n\r\nformat_time_ex::format_time_ex(double p_seconds,unsigned p_extra) {\r\n\tt_uint64 pow10 = pow10_helper(p_extra);\r\n\tt_uint64 ticks = pfc::rint64(pow10 * p_seconds);\r\n\r\n\tm_buffer << pfc::format_time(ticks / pow10);\r\n\tif (p_extra>0) {\r\n\t\tm_buffer << \".\" << pfc::format_uint(ticks % pow10, p_extra);\r\n\t}\r\n}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string.h",
    "content": "#ifndef _PFC_STRING_H_\r\n#define _PFC_STRING_H_\r\n\r\nnamespace pfc {\r\n\r\n\tclass NOVTABLE string_receiver {\r\n\tpublic:\r\n\t\tvirtual void add_string(const char * p_string,t_size p_string_size = infinite) = 0;\r\n\r\n\t\tvoid add_char(t_uint32 c);//adds unicode char to the string\r\n\t\tvoid add_byte(char c) {add_string(&c,1);}\r\n\t\tvoid add_chars(t_uint32 p_char,t_size p_count) {for(;p_count;p_count--) add_char(p_char);}\r\n\tprotected:\r\n\t\tstring_receiver() {}\r\n\t\t~string_receiver() {}\r\n\t};\r\n\r\n\tt_size scan_filename(const char * ptr);\r\n\r\n\tbool is_path_separator(unsigned c);\r\n\tbool is_path_bad_char(unsigned c);\r\n\tbool is_valid_utf8(const char * param,t_size max = infinite);\r\n\tbool is_lower_ascii(const char * param);\r\n\tbool is_multiline(const char * p_string,t_size p_len = infinite);\r\n\tbool has_path_bad_chars(const char * param);\r\n\tvoid recover_invalid_utf8(const char * src,char * out,unsigned replace);//out must be enough to hold strlen(char) + 1, or appropiately bigger if replace needs multiple chars\r\n\tvoid convert_to_lower_ascii(const char * src,t_size max,char * out,char replace = '?');//out should be at least strlen(src)+1 long\r\n\r\n\tinline char ascii_tolower(char c) {if (c >= 'A' && c <= 'Z') c += 'a' - 'A'; return c;}\r\n\tinline char ascii_toupper(char c) {if (c >= 'a' && c <= 'z') c += 'A' - 'a'; return c;}\r\n\r\n\tt_size string_find_first(const char * p_string,char p_tofind,t_size p_start = 0);\t//returns infinite if not found\r\n\tt_size string_find_last(const char * p_string,char p_tofind,t_size p_start = ~0);\t//returns infinite if not found\r\n\tt_size string_find_first(const char * p_string,const char * p_tofind,t_size p_start = 0);\t//returns infinite if not found\r\n\tt_size string_find_last(const char * p_string,const char * p_tofind,t_size p_start = ~0);\t//returns infinite if not found\r\n\r\n\tt_size string_find_first_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start = 0);\t//returns infinite if not found\r\n\tt_size string_find_last_ex(const char * p_string,t_size p_string_length,char p_tofind,t_size p_start = ~0);\t//returns infinite if not found\r\n\tt_size string_find_first_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start = 0);\t//returns infinite if not found\r\n\tt_size string_find_last_ex(const char * p_string,t_size p_string_length,const char * p_tofind,t_size p_tofind_length,t_size p_start = ~0);\t//returns infinite if not found\r\n\r\n\t\r\n\ttemplate<typename t_char>\r\n\tt_size strlen_max_t(const t_char * ptr,t_size max) {\r\n\t\tif (ptr == NULL) return 0;\r\n\t\tt_size n = 0;\r\n\t\twhile(n<max && ptr[n] != 0) n++;\r\n\t\treturn n;\r\n\t}\r\n\r\n\tinline t_size strlen_max(const char * ptr,t_size max) {return strlen_max_t(ptr,max);}\r\n\tinline t_size wcslen_max(const wchar_t * ptr,t_size max) {return strlen_max_t(ptr,max);}\r\n\r\n#ifdef _WINDOWS\r\n\tinline t_size tcslen_max(const TCHAR * ptr,t_size max) {return strlen_max_t(ptr,max);}\r\n#endif\r\n\t\r\n\tbool string_is_numeric(const char * p_string,t_size p_length = infinite);\r\n\tinline bool char_is_numeric(char p_char) {return p_char >= '0' && p_char <= '9';}\r\n\tinline bool char_is_ascii_alpha_upper(char p_char) {return p_char >= 'A' && p_char <= 'Z';}\r\n\tinline bool char_is_ascii_alpha_lower(char p_char) {return p_char >= 'a' && p_char <= 'z';}\r\n\tinline bool char_is_ascii_alpha(char p_char) {return char_is_ascii_alpha_lower(p_char) || char_is_ascii_alpha_upper(p_char);}\r\n\tinline bool char_is_ascii_alphanumeric(char p_char) {return char_is_ascii_alpha(p_char) || char_is_numeric(p_char);}\r\n\t\r\n\tunsigned atoui_ex(const char * ptr,t_size max);\r\n\tt_int64 atoi64_ex(const char * ptr,t_size max);\r\n\tt_uint64 atoui64_ex(const char * ptr,t_size max);\r\n\r\n\tt_size strlen_utf8(const char * s,t_size num = ~0);//returns number of characters in utf8 string; num - no. of bytes (optional)\r\n\tt_size utf8_char_len(const char * s,t_size max = ~0);//returns size of utf8 character pointed by s, in bytes, 0 on error\r\n\tt_size utf8_char_len_from_header(char c);\r\n\tt_size utf8_chars_to_bytes(const char * string,t_size count);\r\n\r\n\tt_size strcpy_utf8_truncate(const char * src,char * out,t_size maxbytes);\r\n\r\n\tt_size utf8_decode_char(const char * src,unsigned * out,t_size src_bytes = ~0);//returns length in bytes\r\n\tt_size utf8_encode_char(unsigned c,char * out);//returns used length in bytes, max 6\r\n\tt_size utf16_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length = ~0);\r\n\tt_size utf16_encode_char(unsigned c,wchar_t * out);\r\n\r\n\r\n\tt_size strstr_ex(const char * p_string,t_size p_string_len,const char * p_substring,t_size p_substring_len);\r\n\r\n\tint strcmp_partial(const char * p_string,const char * p_substring);\r\n\tint strcmp_partial_ex(const char * p_string,t_size p_string_length,const char * p_substring,t_size p_substring_length);\r\n\r\n\tt_size skip_utf8_chars(const char * ptr,t_size count);\r\n\tchar * strdup_n(const char * src,t_size len);\r\n\tint stricmp_ascii(const char * s1,const char * s2);\r\n\tint stricmp_ascii_ex(const char * s1,t_size len1,const char * s2,t_size len2);\r\n\r\n\tint strcmp_ex(const char* p1,t_size n1,const char* p2,t_size n2);\r\n\r\n\tunsigned utf8_get_char(const char * src);\r\n\r\n\tinline bool utf8_advance(const char * & var) {\r\n\t\tt_size delta = utf8_char_len(var);\r\n\t\tvar += delta;\r\n\t\treturn delta>0;\r\n\t}\r\n\r\n\tinline bool utf8_advance(char * & var) {\r\n\t\tt_size delta = utf8_char_len(var);\r\n\t\tvar += delta;\r\n\t\treturn delta>0;\r\n\t}\r\n\r\n\tinline const char * utf8_char_next(const char * src) {return src + utf8_char_len(src);}\r\n\tinline char * utf8_char_next(char * src) {return src + utf8_char_len(src);}\r\n\r\n\tclass NOVTABLE string_base : public pfc::string_receiver {\r\n\tpublic:\r\n\t\tvirtual const char * get_ptr() const = 0;\r\n\t\tvirtual void add_string(const char * p_string,t_size p_length = ~0) = 0;//same as string_receiver method\r\n\t\tvirtual void set_string(const char * p_string,t_size p_length = ~0) {reset();add_string(p_string,p_length);}\r\n\t\tvirtual void truncate(t_size len)=0;\r\n\t\tvirtual t_size get_length() const {return strlen(get_ptr());}\r\n\t\tvirtual char * lock_buffer(t_size p_requested_length) = 0;\r\n\t\tvirtual void unlock_buffer() = 0;\r\n\r\n\t\t//! For compatibility with old conventions.\r\n\t\tinline t_size length() const {return get_length();}\r\n\t\t\r\n\t\tinline void reset() {truncate(0);}\r\n\t\t\r\n\t\tinline bool is_empty() const {return *get_ptr()==0;}\r\n\t\t\r\n\t\tvoid skip_trailing_char(unsigned c = ' ');\r\n\r\n\t\tbool is_valid_utf8() {return pfc::is_valid_utf8(get_ptr());}\r\n\r\n\t\tvoid convert_to_lower_ascii(const char * src,char replace = '?');\r\n\r\n\t\tinline const string_base & operator= (const char * src) {set_string(src);return *this;}\r\n\t\tinline const string_base & operator+= (const char * src) {add_string(src);return *this;}\r\n\t\tinline const string_base & operator= (const string_base & src) {set_string(src);return *this;}\r\n\t\tinline const string_base & operator+= (const string_base & src) {add_string(src);return *this;}\r\n\r\n\t\tinline operator const char * () const {return get_ptr();}\r\n\r\n\t\tt_size scan_filename() const {return pfc::scan_filename(get_ptr());}\r\n\r\n\t\tt_size find_first(char p_char,t_size p_start = 0) {return pfc::string_find_first(get_ptr(),p_char,p_start);}\r\n\t\tt_size find_last(char p_char,t_size p_start = ~0) {return pfc::string_find_last(get_ptr(),p_char,p_start);}\r\n\t\tt_size find_first(const char * p_string,t_size p_start = 0) {return pfc::string_find_first(get_ptr(),p_string,p_start);}\r\n\t\tt_size find_last(const char * p_string,t_size p_start = ~0) {return pfc::string_find_last(get_ptr(),p_string,p_start);}\r\n\r\n\t\tvoid fix_dir_separator(char p_char);\r\n\tprotected:\r\n\t\tstring_base() {}\r\n\t\t~string_base() {}\r\n\t};\r\n\r\n\ttemplate<t_size max_length>\r\n\tclass string_fixed_t : public pfc::string_base {\r\n\tpublic:\r\n\t\tinline string_fixed_t() {init();}\r\n\t\tinline string_fixed_t(const string_fixed_t<max_length> & p_source) {init(); *this = p_source;}\r\n\t\tinline string_fixed_t(const char * p_source) {init(); set_string(p_source);}\r\n\t\t\r\n\t\tinline const string_fixed_t<max_length> & operator=(const string_fixed_t<max_length> & p_source) {set_string(p_source);return *this;}\r\n\t\tinline const string_fixed_t<max_length> & operator=(const char * p_source) {set_string(p_source);return *this;}\r\n\r\n\t\tchar * lock_buffer(t_size p_requested_length) {\r\n\t\t\tif (p_requested_length >= max_length) return NULL;\r\n\t\t\tmemset(m_data,0,sizeof(m_data));\r\n\t\t\treturn m_data;\r\n\t\t}\r\n\t\tvoid unlock_buffer() {\r\n\t\t\tm_length = strlen(m_data);\r\n\t\t}\r\n\r\n\t\tinline operator const char * () const {return m_data;}\r\n\t\t\r\n\t\tconst char * get_ptr() const {return m_data;}\r\n\r\n\t\tvoid add_string(const char * ptr,t_size len) {\r\n\t\t\tlen = strlen_max(ptr,len);\r\n\t\t\tif (m_length + len < m_length || m_length + len > max_length) throw pfc::exception_overflow();\r\n\t\t\tfor(t_size n=0;n<len;n++) {\r\n\t\t\t\tm_data[m_length++] = ptr[n];\r\n\t\t\t}\r\n\t\t\tm_data[m_length] = 0;\r\n\t\t}\r\n\t\tvoid truncate(t_size len) {\r\n\t\t\tif (len > max_length) len = max_length;\r\n\t\t\tif (m_length > len) {\r\n\t\t\t\tm_length = len;\r\n\t\t\t\tm_data[len] = 0;\r\n\t\t\t}\r\n\t\t}\r\n\t\tt_size get_length() const {return m_length;}\r\n\tprivate:\r\n\t\tinline void init() {\r\n\t\t\tpfc::static_assert<(max_length>1)>();\r\n\t\t\tm_length = 0; m_data[0] = 0;\r\n\t\t}\r\n\t\tt_size m_length;\r\n\t\tchar m_data[max_length+1];\r\n\t};\r\n\r\n\ttemplate<template<typename> class t_alloc>\r\n\tclass string8_t : public pfc::string_base {\r\n\tprivate:\r\n\t\ttypedef string8_t<t_alloc> t_self;\r\n\tprotected:\r\n\t\tpfc::array_t<char,t_alloc> m_data;\r\n\t\tt_size used;\r\n\r\n\t\tinline void makespace(t_size s)\r\n\t\t{\r\n\t\t\tt_size old_size = m_data.get_size();\r\n\t\t\tif (old_size < s)\r\n\t\t\t\tm_data.set_size(s+16);\r\n\t\t\telse if (old_size > s + 32)\r\n\t\t\t\tm_data.set_size(s);\r\n\t\t}\r\n\r\n\t\tinline const char * __get_ptr() const throw() {return used > 0 ? m_data.get_ptr() : \"\";}\r\n\r\n\tpublic:\r\n\t\tinline const t_self & operator= (const char * src) {set_string(src);return *this;}\r\n\t\tinline const t_self & operator+= (const char * src) {add_string(src);return *this;}\r\n\t\tinline const t_self & operator= (const string_base & src) {set_string(src);return *this;}\r\n\t\tinline const t_self & operator+= (const string_base & src) {add_string(src);return *this;}\r\n\t\tinline const t_self & operator= (const t_self & src) {set_string(src);return *this;}\r\n\t\tinline const t_self & operator+= (const t_self & src) {add_string(src);return *this;}\r\n\r\n\t\tinline operator const char * () const throw() {return __get_ptr();}\r\n\r\n\t\tstring8_t() : used(0) {}\r\n\t\tstring8_t(const char * p_string) : used(0) {set_string(p_string);}\r\n\t\tstring8_t(const char * p_string,t_size p_length) : used(0) {set_string(p_string,p_length);}\r\n\t\tstring8_t(const t_self & p_string) : used(0) {set_string(p_string);}\r\n\t\tstring8_t(const string_base & p_string) : used(0) {set_string(p_string);}\r\n\r\n\t\tvoid prealloc(t_size p_size) {m_data.prealloc(p_size+1);}\r\n\r\n\t\tconst char * get_ptr() const throw() {return __get_ptr();}\r\n\r\n\t\tvoid add_string(const char * p_string,t_size p_length = ~0);\r\n\t\tvoid set_string(const char * p_string,t_size p_length = ~0);\r\n\r\n\t\tvoid truncate(t_size len)\r\n\t\t{\r\n\t\t\tif (used>len) {used=len;m_data[len]=0;makespace(used+1);}\r\n\t\t}\r\n\r\n\t\tt_size get_length() const throw() {return used;}\r\n\r\n\r\n\t\tvoid set_char(unsigned offset,char c);\r\n\r\n\t\tt_size replace_nontext_chars(char p_replace = '_');\r\n\t\tt_size replace_char(unsigned c1,unsigned c2,t_size start = 0);\r\n\t\tt_size replace_byte(char c1,char c2,t_size start = 0);\r\n\t\tvoid fix_filename_chars(char def = '_',char leave=0);//replace \"bad\" characters, leave can be used to keep eg. path separators\r\n\t\tvoid remove_chars(t_size first,t_size count); //slow\r\n\t\tvoid insert_chars(t_size first,const char * src, t_size count);//slow\r\n\t\tvoid insert_chars(t_size first,const char * src);\r\n\t\tbool truncate_eol(t_size start = 0);\r\n\t\tbool fix_eol(const char * append = \" (...)\",t_size start = 0);\r\n\t\tbool limit_length(t_size length_in_chars,const char * append = \" (...)\");\r\n\r\n\t\t//for string_buffer class\r\n\t\tchar * lock_buffer(t_size n)\r\n\t\t{\r\n\t\t\tmakespace(n+1);\r\n\t\t\tpfc::memset_t(m_data,(char)0);\r\n\t\t\treturn m_data.get_ptr();;\r\n\t\t}\r\n\r\n\t\tvoid unlock_buffer() {\r\n\t\t\tused=strlen(m_data.get_ptr());\r\n\t\t\tmakespace(used+1);\r\n\t\t}\r\n\r\n\t\tvoid force_reset() {used=0;m_data.force_reset();}\r\n\r\n\t\tinline static void g_swap(t_self & p_item1,t_self & p_item2) {\r\n\t\t\tpfc::swap_t(p_item1.m_data,p_item2.m_data);\r\n\t\t\tpfc::swap_t(p_item1.used,p_item2.used);\r\n\t\t}\r\n\t};\r\n\r\n\ttypedef string8_t<pfc::alloc_standard> string8;\r\n\ttypedef string8_t<pfc::alloc_fast> string8_fast;\r\n\ttypedef string8_t<pfc::alloc_fast_aggressive> string8_fast_aggressive;\r\n\t//for backwards compatibility\r\n\ttypedef string8_t<pfc::alloc_fast_aggressive> string8_fastalloc;\r\n\r\n\r\n\ttemplate<template<typename> class t_alloc> class traits_t<string8_t<t_alloc> > : public pfc::combine_traits<pfc::traits_vtable,pfc::traits_t<pfc::array_t<char,t_alloc> > > {\r\n\tpublic:\r\n\t\tenum {\r\n\t\t\tneeds_constructor = true,\r\n\t\t};\r\n\t};\r\n}\r\n\r\n\r\n\r\n#include \"string8_impl.h\"\r\n\r\n#define PFC_DEPRECATE_PRINTF PFC_DEPRECATE(\"Use string8/string_fixed_t with operator<< overloads instead.\")\r\n\r\nnamespace pfc {\r\n\r\n\tclass string_buffer {\r\n\tprivate:\r\n\t\tstring_base & m_owner;\r\n\t\tchar * m_buffer;\r\n\tpublic:\r\n\t\texplicit string_buffer(string_base & p_string,t_size p_requeted_length) : m_owner(p_string) {m_buffer = m_owner.lock_buffer(p_requeted_length);}\r\n\t\t~string_buffer() {m_owner.unlock_buffer();}\r\n\t\toperator char* () {return m_buffer;}\r\n\t};\r\n\r\n\tclass PFC_DEPRECATE_PRINTF string_printf : public string8_fastalloc {\r\n\tpublic:\r\n\t\tstatic void g_run(string_base & out,const char * fmt,va_list list);\r\n\t\tvoid run(const char * fmt,va_list list);\r\n\r\n\t\texplicit string_printf(const char * fmt,...);\r\n\t};\r\n\r\n\tclass PFC_DEPRECATE_PRINTF string_printf_va : public string8_fastalloc {\r\n\tpublic:\r\n\t\tstring_printf_va(const char * fmt,va_list list);\r\n\t};\r\n\r\n\tclass format_time {\r\n\tpublic:\r\n\t\tformat_time(t_uint64 p_seconds);\r\n\t\tconst char * get_ptr() const {return m_buffer;}\r\n\t\toperator const char * () const {return m_buffer;}\r\n\tprotected:\r\n\t\tstring_fixed_t<127> m_buffer;\r\n\t};\r\n\r\n\r\n\tclass format_time_ex {\r\n\tpublic:\r\n\t\tformat_time_ex(double p_seconds,unsigned p_extra = 3);\r\n\t\tconst char * get_ptr() const {return m_buffer;}\r\n\t\toperator const char * () const {return m_buffer;}\r\n\tprivate:\r\n\t\tstring_fixed_t<127> m_buffer;\r\n\t};\r\n\r\n\r\n\r\n\r\n\tclass string_filename : public string8 {\r\n\tpublic:\r\n\t\texplicit string_filename(const char * fn);\r\n\t};\r\n\r\n\tclass string_filename_ext : public string8 {\r\n\tpublic:\r\n\t\texplicit string_filename_ext(const char * fn);\r\n\t};\r\n\r\n\tclass string_extension\r\n\t{\r\n\t\tchar buffer[32];\r\n\tpublic:\r\n\t\tinline const char * get_ptr() const {return buffer;}\r\n\t\tinline t_size length() const {return strlen(buffer);}\r\n\t\tinline operator const char * () const {return buffer;}\r\n\t\texplicit string_extension(const char * src);\r\n\t};\r\n\r\n\r\n\tclass string_replace_extension\r\n\t{\r\n\tpublic:\r\n\t\tstring_replace_extension(const char * p_path,const char * p_ext);\r\n\t\tinline operator const char*() const {return m_data;}\r\n\tprivate:\r\n\t\tstring8 m_data;\r\n\t};\r\n\r\n\tclass string_directory\r\n\t{\r\n\tpublic:\r\n\t\tstring_directory(const char * p_path);\r\n\t\tinline operator const char*() const {return m_data;}\r\n\tprivate:\r\n\t\tstring8 m_data;\r\n\t};\r\n\r\n\tvoid float_to_string(char * out,t_size out_max,double val,unsigned precision,bool force_sign = false);//doesnt add E+X etc, has internal range limits, useful for storing float numbers as strings without having to bother with international coma/dot settings BS\r\n\tdouble string_to_float(const char * src,t_size len = infinite);\r\n\r\n\ttemplate<>\r\n\tinline void swap_t(string8 & p_item1,string8 & p_item2)\r\n\t{\r\n\t\tstring8::g_swap(p_item1,p_item2);\r\n\t}\r\n\r\n\tclass format_float\r\n\t{\r\n\tpublic:\r\n\t\tformat_float(double p_val,unsigned p_width,unsigned p_prec);\r\n\t\tformat_float(const format_float & p_source) {*this = p_source;}\r\n\r\n\t\tinline const char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\tinline operator const char*() const {return m_buffer.get_ptr();}\r\n\tprivate:\r\n\t\tstring8 m_buffer;\r\n\t};\r\n\r\n\tclass format_int\r\n\t{\r\n\tpublic:\r\n\t\tformat_int(t_int64 p_val,unsigned p_width = 0,unsigned p_base = 10);\r\n\t\tformat_int(const format_int & p_source) {*this = p_source;}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tchar m_buffer[64];\r\n\t};\r\n\r\n\r\n\tclass format_uint\r\n\t{\r\n\tpublic:\r\n\t\tformat_uint(t_uint64 p_val,unsigned p_width = 0,unsigned p_base = 10);\r\n\t\tformat_uint(const format_uint & p_source) {*this = p_source;}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tchar m_buffer[64];\r\n\t};\r\n\r\n\tclass format_hex\r\n\t{\r\n\tpublic:\r\n\t\tformat_hex(t_uint64 p_val,unsigned p_width = 0);\r\n\t\tformat_hex(const format_hex & p_source) {*this = p_source;}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tchar m_buffer[17];\r\n\t};\r\n\r\n\tclass format_hex_lowercase\r\n\t{\r\n\tpublic:\r\n\t\tformat_hex_lowercase(t_uint64 p_val,unsigned p_width = 0);\r\n\t\tformat_hex_lowercase(const format_hex_lowercase & p_source) {*this = p_source;}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tchar m_buffer[17];\r\n\t};\r\n\r\n\r\n\ttypedef string8_fastalloc string_formatter;\r\n\r\n\tclass format_hexdump\r\n\t{\r\n\tpublic:\r\n\t\tformat_hexdump(const void * p_buffer,t_size p_bytes,const char * p_spacing = \" \");\r\n\r\n\t\tinline const char * get_ptr() const {return m_formatter;}\r\n\t\tinline operator const char * () const {return m_formatter;}\r\n\r\n\tprivate:\r\n\t\tstring_formatter m_formatter;\r\n\t};\r\n\r\n\tclass format_hexdump_lowercase\r\n\t{\r\n\tpublic:\r\n\t\tformat_hexdump_lowercase(const void * p_buffer,t_size p_bytes,const char * p_spacing = \" \");\r\n\r\n\t\tinline const char * get_ptr() const {return m_formatter;}\r\n\t\tinline operator const char * () const {return m_formatter;}\r\n\r\n\tprivate:\r\n\t\tstring_formatter m_formatter;\r\n\t};\r\n\r\n\tclass format_fixedpoint\r\n\t{\r\n\tpublic:\r\n\t\tformat_fixedpoint(t_int64 p_val,unsigned p_point);\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tstring_formatter m_buffer;\r\n\t};\r\n\r\n\tclass format_char {\r\n\tpublic:\r\n\t\tformat_char(char p_char) {m_buffer[0] = p_char; m_buffer[1] = 0;}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tchar m_buffer[2];\r\n\t};\r\n\r\n\ttemplate<typename t_stringbuffer = pfc::string8_fastalloc>\r\n\tclass format_pad_left {\r\n\tpublic:\r\n\t\tformat_pad_left(t_size p_chars,t_uint32 p_padding /* = ' ' */,const char * p_string,t_size p_string_length = infinite) {\r\n\t\t\tt_size source_len = 0, source_walk = 0;\r\n\t\t\t\r\n\t\t\twhile(source_walk < p_string_length && source_len < p_chars) {\r\n\t\t\t\tunsigned dummy;\r\n\t\t\t\tt_size delta = pfc::utf8_decode_char(p_string + source_walk, &dummy, p_string_length - source_walk);\r\n\t\t\t\tif (delta == 0) break;\r\n\t\t\t\tsource_len++;\r\n\t\t\t\tsource_walk += delta;\r\n\t\t\t}\r\n\r\n\t\t\tm_buffer.add_string(p_string,source_walk);\r\n\t\t\tm_buffer.add_chars(p_padding,p_chars - source_len);\r\n\t\t}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tt_stringbuffer m_buffer;\r\n\t};\r\n\r\n\ttemplate<typename t_stringbuffer = pfc::string8_fastalloc>\r\n\tclass format_pad_right {\r\n\tpublic:\r\n\t\tformat_pad_right(t_size p_chars,t_uint32 p_padding /* = ' ' */,const char * p_string,t_size p_string_length = infinite) {\r\n\t\t\tt_size source_len = 0, source_walk = 0;\r\n\t\t\t\r\n\t\t\twhile(source_walk < p_string_length && source_len < p_chars) {\r\n\t\t\t\tunsigned dummy;\r\n\t\t\t\tt_size delta = pfc::utf8_decode_char(p_string + source_walk, &dummy, p_string_length - source_walk);\r\n\t\t\t\tif (delta == 0) break;\r\n\t\t\t\tsource_len++;\r\n\t\t\t\tsource_walk += delta;\r\n\t\t\t}\r\n\r\n\t\t\tm_buffer.add_chars(p_padding,p_chars - source_len);\r\n\t\t\tm_buffer.add_string(p_string,source_walk);\r\n\t\t}\r\n\t\tinline const char * get_ptr() const {return m_buffer;}\r\n\t\tinline operator const char*() const {return m_buffer;}\r\n\tprivate:\r\n\t\tt_stringbuffer m_buffer;\r\n\t};\r\n}\r\n\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,const char * p_source) {p_fmt.add_string(p_source); return p_fmt;}\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,t_int32 p_val) {return p_fmt << pfc::format_int(p_val);}\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,t_uint32 p_val) {return p_fmt << pfc::format_uint(p_val);}\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,t_int64 p_val) {return p_fmt << pfc::format_int(p_val);}\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,t_uint64 p_val) {return p_fmt << pfc::format_uint(p_val);}\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,double p_val) {return p_fmt << pfc::format_float(p_val,0,7);}\r\n\r\ninline pfc::string_base & operator<<(pfc::string_base & p_fmt,std::exception const & p_exception) {return p_fmt << p_exception.what();}\r\n\r\n\r\n\r\n\r\n\r\n\r\nnamespace pfc {\r\n\ttemplate<typename t_char>\r\n\tclass string_simple_t {\r\n\tprivate:\r\n\t\ttypedef string_simple_t<t_char> t_self;\r\n\tpublic:\r\n\t\tt_size length(t_size p_limit = infinite) const {return pfc::strlen_t(get_ptr(),infinite);}\r\n\t\tbool is_empty() const {return length(1) == 0;}\r\n\t\tvoid set_string(const t_char * p_source,t_size p_length = infinite) {\r\n\t\t\tt_size length = pfc::strlen_t(p_source,p_length);\r\n\t\t\tm_buffer.set_size(length + 1);\r\n\t\t\tpfc::memcpy_t(m_buffer.get_ptr(),p_source,length);\r\n\t\t\tm_buffer[length] = 0;\r\n\t\t}\r\n\t\tstring_simple_t() {}\r\n\t\tstring_simple_t(const t_char * p_source,t_size p_length = infinite) {set_string(p_source,p_length);}\r\n\t\tconst t_self & operator=(const t_char * p_source) {set_string(p_source);return *this;}\r\n\t\toperator const t_char* () const {return get_ptr();}\r\n\t\tconst t_char * get_ptr() const {return m_buffer.get_size() > 0 ? m_buffer.get_ptr() : pfc::empty_string_t<t_char>();}\r\n\tprivate:\r\n\t\tpfc::array_t<t_char> m_buffer;\r\n\t};\r\n\r\n\ttypedef string_simple_t<char> string_simple;\r\n\r\n\ttemplate<typename t_char> class traits_t<string_simple_t<t_char> > : public traits_t<array_t<t_char> > {};\r\n}\r\n\r\n\r\nnamespace pfc {\r\n\t//for tree/map classes\r\n\r\n\tclass comparator_strcmp {\r\n\tpublic:\r\n\t\tinline static int compare(const char * p_item1,const char * p_item2) {return strcmp(p_item1,p_item2);}\r\n\t};\r\n\r\n\tclass comparator_stricmp_ascii {\r\n\tpublic:\r\n\t\tinline static int compare(const char * p_item1,const char * p_item2) {return pfc::stricmp_ascii(p_item1,p_item2);}\r\n\t};\r\n\r\n}\r\n\r\n#endif //_PFC_STRING_H_"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string8_impl.h",
    "content": "namespace pfc {\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::add_string(const char * ptr,t_size len)\r\n{\r\n\tif (len > 0 && ptr >= m_data.get_ptr() && ptr <= m_data.get_ptr() + m_data.get_size()) {\r\n\t\tadd_string(string8(ptr,len));\r\n\t} else {\r\n\t\tlen = strlen_max(ptr,len);\r\n\t\tmakespace(used+len+1);\r\n\t\tpfc::memcpy_t(m_data.get_ptr() + used,ptr,len);\r\n\t\tused+=len;\r\n\t\tm_data[used]=0;\r\n\t\ttrue;\r\n\t}\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::set_string(const char * ptr,t_size len) {\r\n\tif (len > 0 && ptr >= m_data.get_ptr() && ptr < m_data.get_ptr() + m_data.get_size()) {\r\n\t\tset_string(string8(ptr,len));\r\n\t} else {\r\n\t\tlen = strlen_max(ptr,len);\r\n\t\tmakespace(len+1);\r\n\t\tpfc::memcpy_t(m_data.get_ptr(),ptr,len);\r\n\t\tused=len;\r\n\t\tm_data[used]=0;\r\n\t}\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::set_char(unsigned offset,char c)\r\n{\r\n\tif (!c) truncate(offset);\r\n\telse if (offset<used) m_data[offset]=c;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::fix_filename_chars(char def,char leave)//replace \"bad\" characters, leave can be used to keep eg. path separators\r\n{\r\n\tt_size n;\r\n\tfor(n=0;n<used;n++)\r\n\t\tif (m_data[n]!=leave && pfc::is_path_bad_char(m_data[n])) m_data[n]=def;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::remove_chars(t_size first,t_size count)\r\n{\r\n\tif (first>used) first = used;\r\n\tif (first+count>used) count = used-first;\r\n\tif (count>0)\r\n\t{\r\n\t\tt_size n;\r\n\t\tfor(n=first+count;n<=used;n++)\r\n\t\t\tm_data[n-count]=m_data[n];\r\n\t\tused -= count;\r\n\t\tmakespace(used+1);\r\n\t}\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::insert_chars(t_size first,const char * src, t_size count)\r\n{\r\n\tif (first > used) first = used;\r\n\r\n\tmakespace(used+count+1);\r\n\tt_size n;\r\n\tfor(n=used;(int)n>=(int)first;n--)\r\n\t\tm_data[n+count] = m_data[n];\r\n\tfor(n=0;n<count;n++)\r\n\t\tm_data[first+n] = src[n];\r\n\r\n\tused+=count;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nvoid string8_t<t_alloc>::insert_chars(t_size first,const char * src) {insert_chars(first,src,strlen(src));}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nbool string8_t<t_alloc>::truncate_eol(t_size start)\r\n{\r\n\tt_size n;\r\n\tconst char * ptr = m_data.get_ptr() + start;\r\n\tfor(n=start;n<used;n++)\r\n\t{\r\n\t\tif (*ptr==10 || *ptr==13)\r\n\t\t{\r\n\t\t\ttruncate(n);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tptr++;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nbool string8_t<t_alloc>::fix_eol(const char * append,t_size start)\r\n{\r\n\tbool rv = truncate_eol(start);\r\n\tif (rv) add_string(append);\r\n\treturn rv;\r\n}\r\n\r\n\r\ntemplate<template<typename> class t_alloc>\r\nbool string8_t<t_alloc>::limit_length(t_size length_in_chars,const char * append)\r\n{\r\n\tbool rv = false;\r\n\tconst char * base = get_ptr(), * ptr = base;\r\n\twhile(length_in_chars && utf8_advance(ptr)) length_in_chars--;\r\n\tif (length_in_chars==0)\r\n\t{\r\n\t\ttruncate(ptr-base);\r\n\t\tadd_string(append);\r\n\t\trv = true;\r\n\t}\r\n\treturn rv;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nt_size string8_t<t_alloc>::replace_nontext_chars(char p_replace)\r\n{\r\n\tt_size ret = 0;\r\n\tfor(t_size n=0;n<used;n++)\r\n\t{\r\n\t\tif ((unsigned char)m_data[n] < 32) {m_data[n] = p_replace; ret++; }\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nt_size string8_t<t_alloc>::replace_byte(char c1,char c2,t_size start)\r\n{\r\n\tPFC_ASSERT(c1 != 0); PFC_ASSERT(c2 != 0);\r\n\tt_size n, ret = 0;\r\n\tfor(n=start;n<used;n++)\r\n\t{\r\n\t\tif (m_data[n] == c1) {m_data[n] = c2; ret++;}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\ntemplate<template<typename> class t_alloc>\r\nt_size string8_t<t_alloc>::replace_char(unsigned c1,unsigned c2,t_size start)\r\n{\r\n\tif (c1 < 128 && c2 < 128) return replace_byte((char)c1,(char)c2,start);\r\n\r\n\tstring8 temp(get_ptr()+start);\r\n\ttruncate(start);\r\n\tconst char * ptr = temp;\r\n\tt_size rv = 0;\r\n\twhile(*ptr)\r\n\t{\r\n\t\tunsigned test;\r\n\t\tt_size delta = utf8_decode_char(ptr,&test);\r\n\t\tif (delta==0 || test==0) break;\r\n\t\tif (test == c1) {test = c2;rv++;}\r\n\t\tadd_char(test);\r\n\t\tptr += delta;\r\n\t}\r\n\treturn rv;\r\n}\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string_conv.cpp",
    "content": "#include \"pfc.h\"\r\n\r\n\r\n#ifdef _WINDOWS\r\n\r\nnamespace {\r\n\ttemplate<typename t_char> \r\n\tclass string_writer_t {\r\n\tpublic:\r\n\t\tstring_writer_t(t_char * p_buffer,t_size p_size) : m_buffer(p_buffer), m_size(p_size), m_writeptr(0) {}\r\n\t\t\r\n\t\tvoid write(t_char p_char) {\r\n\t\t\tif (m_writeptr < m_size) {\r\n\t\t\t\tm_buffer[m_writeptr++] = p_char;\r\n\t\t\t}\r\n\t\t}\r\n\t\tvoid write_multi(const t_char * p_buffer,t_size p_count) {\r\n\t\t\tconst t_size delta = pfc::min_t<t_size>(p_count,m_size-m_writeptr);\r\n\t\t\tfor(t_size n=0;n<delta;n++) {\r\n\t\t\t\tm_buffer[m_writeptr++] = p_buffer[n];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tvoid write_as_utf8(unsigned p_char) {\r\n\t\t\tchar temp[6];\r\n\t\t\tt_size n = pfc::utf8_encode_char(p_char,temp);\r\n\t\t\twrite_multi(temp,n);\r\n\t\t}\r\n\r\n\t\tvoid write_as_wide(unsigned p_char) {\r\n\t\t\twchar_t temp[2];\r\n\t\t\tt_size n = pfc::utf16_encode_char(p_char,temp);\r\n\t\t\twrite_multi(temp,n);\r\n\t\t}\r\n\r\n\t\tt_size finalize() {\r\n\t\t\tif (m_size == 0) return 0;\r\n\t\t\tt_size terminator = pfc::min_t<t_size>(m_writeptr,m_size-1);\r\n\t\t\tm_buffer[terminator] = 0;\r\n\t\t\treturn terminator;\r\n\t\t}\r\n\t\tbool is_overrun() const {\r\n\t\t\treturn m_writeptr >= m_size;\r\n\t\t}\r\n\tprivate:\r\n\t\tt_char * m_buffer;\r\n\t\tt_size m_size;\r\n\t\tt_size m_writeptr;\r\n\t};\r\n\r\n\r\n\r\n};\r\n\r\nnamespace pfc {\r\n\tnamespace stringcvt {\r\n\r\n\r\n\t\tt_size convert_utf8_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_in,t_size p_in_size) {\r\n\t\t\tconst t_size insize = p_in_size;\r\n\t\t\tt_size inptr = 0;\r\n\t\t\tstring_writer_t<wchar_t> writer(p_out,p_out_size);\r\n\r\n\t\t\twhile(inptr < insize && !writer.is_overrun()) {\r\n\t\t\t\tunsigned newchar = 0;\r\n\t\t\t\tt_size delta = utf8_decode_char(p_in + inptr,&newchar,insize - inptr);\r\n\t\t\t\tif (delta == 0 || newchar == 0) break;\r\n\t\t\t\tPFC_ASSERT(inptr + delta <= insize);\r\n\t\t\t\tinptr += delta;\r\n\t\t\t\twriter.write_as_wide(newchar);\r\n\t\t\t}\r\n\r\n\t\t\treturn writer.finalize();\r\n\t\t}\r\n\r\n\t\tt_size convert_wide_to_utf8(char * p_out,t_size p_out_size,const wchar_t * p_in,t_size p_in_size) {\r\n\t\t\tconst t_size insize = p_in_size;\r\n\t\t\tt_size inptr = 0;\r\n\t\t\tstring_writer_t<char> writer(p_out,p_out_size);\r\n\r\n\t\t\twhile(inptr < insize && !writer.is_overrun()) {\r\n\t\t\t\tunsigned newchar = 0;\r\n\t\t\t\tt_size delta = utf16_decode_char(p_in + inptr,&newchar,insize - inptr);\r\n\t\t\t\tif (delta == 0 || newchar == 0) break;\r\n\t\t\t\tPFC_ASSERT(inptr + delta <= insize);\r\n\t\t\t\tinptr += delta;\r\n\t\t\t\twriter.write_as_utf8(newchar);\r\n\t\t\t}\r\n\r\n\t\t\treturn writer.finalize();\r\n\t\t}\r\n\r\n\t\tt_size estimate_utf8_to_wide(const char * p_in,t_size p_in_size) {\r\n\t\t\tconst t_size insize = p_in_size;\r\n\t\t\tt_size inptr = 0;\r\n\t\t\tt_size retval = 1;//1 for null terminator\r\n\t\t\twhile(inptr < insize) {\r\n\t\t\t\tunsigned newchar = 0;\r\n\t\t\t\tt_size delta = utf8_decode_char(p_in + inptr,&newchar,insize - inptr);\r\n\t\t\t\tif (delta == 0 || newchar == 0) break;\r\n\t\t\t\tPFC_ASSERT(inptr + delta <= insize);\r\n\t\t\t\tinptr += delta;\r\n\t\t\t\t\r\n\t\t\t\t{\r\n\t\t\t\t\twchar_t temp[2];\r\n\t\t\t\t\tdelta = utf16_encode_char(newchar,temp);\r\n\t\t\t\t\tif (delta == 0) break;\r\n\t\t\t\t\tretval += delta;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn retval;\r\n\t\t}\r\n\r\n\t\tt_size estimate_wide_to_utf8(const wchar_t * p_in,t_size p_in_size) {\r\n\t\t\tconst t_size insize = p_in_size;\r\n\t\t\tt_size inptr = 0;\r\n\t\t\tt_size retval = 1;//1 for null terminator\r\n\t\t\twhile(inptr < insize) {\r\n\t\t\t\tunsigned newchar = 0;\r\n\t\t\t\tt_size delta = utf16_decode_char(p_in + inptr,&newchar,insize - inptr);\r\n\t\t\t\tif (delta == 0 || newchar == 0) break;\r\n\t\t\t\tPFC_ASSERT(inptr + delta <= insize);\r\n\t\t\t\tinptr += delta;\r\n\t\t\t\t\r\n\t\t\t\t{\r\n\t\t\t\t\tchar temp[6];\r\n\t\t\t\t\tdelta = utf8_encode_char(newchar,temp);\r\n\t\t\t\t\tif (delta == 0) break;\r\n\t\t\t\t\tretval += delta;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn retval;\r\n\t\t}\r\n\r\n\r\n\t\tt_size convert_codepage_to_wide(unsigned p_codepage,wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size) {\r\n\t\t\tif (p_out_size == 0) return 0;\r\n\t\t\tmemset(p_out,0,p_out_size * sizeof(*p_out));\r\n\t\t\tMultiByteToWideChar(p_codepage,0,p_source,p_source_size,p_out,p_out_size);\r\n\t\t\tp_out[p_out_size-1] = 0;\r\n\t\t\treturn wcslen(p_out);\r\n\t\t}\r\n\r\n\t\tt_size convert_wide_to_codepage(unsigned p_codepage,char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size) {\r\n\t\t\tif (p_out_size == 0) return 0;\r\n\t\t\tmemset(p_out,0,p_out_size * sizeof(*p_out));\r\n\t\t\tWideCharToMultiByte(p_codepage,0,p_source,p_source_size,p_out,p_out_size,0,FALSE);\r\n\t\t\tp_out[p_out_size-1] = 0;\r\n\t\t\treturn strlen(p_out);\r\n\t\t}\r\n\r\n\t\tt_size estimate_codepage_to_wide(unsigned p_codepage,const char * p_source,t_size p_source_size) {\r\n\t\t\treturn MultiByteToWideChar(p_codepage,0,p_source,strlen_max(p_source,p_source_size),0,0) + 1;\r\n\t\t}\r\n\t\tt_size estimate_wide_to_codepage(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size) {\r\n\t\t\treturn WideCharToMultiByte(p_codepage,0,p_source,wcslen_max(p_source,p_source_size),0,0,0,FALSE) + 1;\r\n\t\t}\r\n\t}\r\n\r\n}\r\n\r\n#endif //_WINDOWS\r\n\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string_conv.h",
    "content": "namespace pfc {\r\n\r\n\tnamespace stringcvt {\r\n\r\n#ifdef _WINDOWS\r\n\t\tenum {\r\n\t\t\tcodepage_system = CP_ACP,\r\n\t\t\tcodepage_ascii = 20127,\r\n\t\t\tcodepage_iso_8859_1 = 28591,\r\n\t\t};\r\n\r\n\t\t//! Converts UTF-8 characters to wide character.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tt_size convert_utf8_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size);\r\n\r\n\t\t//! Estimates buffer size required to convert specified UTF-8 string to widechar.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tt_size estimate_utf8_to_wide(const char * p_source,t_size p_source_size);\r\n\r\n\t\t//! Converts wide character string to UTF-8.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tt_size convert_wide_to_utf8(char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size);\r\n\r\n\t\t//! Estimates buffer size required to convert specified wide character string to UTF-8.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tt_size estimate_wide_to_utf8(const wchar_t * p_source,t_size p_source_size);\r\n\r\n\r\n\r\n\t\t//! Converts string from specified codepage to wide character.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_codepage Codepage ID of source string.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tt_size convert_codepage_to_wide(unsigned p_codepage,wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size);\r\n\r\n\t\t//! Estimates buffer size required to convert specified string from specified codepage to wide character.\r\n\t\t//! @param p_codepage Codepage ID of source string.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tt_size estimate_codepage_to_wide(unsigned p_codepage,const char * p_source,t_size p_source_size);\r\n\r\n\t\t//! Converts string from wide character to specified codepage.\r\n\t\t//! @param p_codepage Codepage ID of source string.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tt_size convert_wide_to_codepage(unsigned p_codepage,char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size);\r\n\r\n\t\t//! Estimates buffer size required to convert specified wide character string to specified codepage.\r\n\t\t//! @param p_codepage Codepage ID of source string.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tt_size estimate_wide_to_codepage(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size);\r\n\t\t\r\n\r\n\t\t//! Converts string from system codepage to wide character.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tinline t_size convert_ansi_to_wide(wchar_t * p_out,t_size p_out_size,const char * p_source,t_size p_source_size) {\r\n\t\t\treturn convert_codepage_to_wide(codepage_system,p_out,p_out_size,p_source,p_source_size);\r\n\t\t}\r\n\r\n\t\t//! Estimates buffer size required to convert specified system codepage string to wide character.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tinline t_size estimate_ansi_to_wide(const char * p_source,t_size p_source_size) {\r\n\t\t\treturn estimate_codepage_to_wide(codepage_system,p_source,p_source_size);\r\n\t\t}\r\n\r\n\t\t//! Converts string from wide character to system codepage.\r\n\t\t//! @param p_out Output buffer, receives converted string, with null terminator.\r\n\t\t//! @param p_out_size Size of output buffer, in characters. If converted string is too long, it will be truncated. Null terminator is always written, unless p_out_size is zero.\r\n\t\t//! @param p_source String to convert.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters written, not counting null terminator.\r\n\t\tinline t_size convert_wide_to_ansi(char * p_out,t_size p_out_size,const wchar_t * p_source,t_size p_source_size) {\r\n\t\t\treturn convert_wide_to_codepage(codepage_system,p_out,p_out_size,p_source,p_source_size);\r\n\t\t}\r\n\r\n\t\t//! Estimates buffer size required to convert specified wide character string to system codepage.\r\n\t\t//! @param p_source String to be converted.\r\n\t\t//! @param p_source_size Number of characters to read from p_source. If reading stops if null terminator is encountered earlier.\r\n\t\t//! @returns Number of characters to allocate, including space for null terminator.\r\n\t\tinline t_size estimate_wide_to_ansi(const wchar_t * p_source,t_size p_source_size) {\r\n\t\t\treturn estimate_wide_to_codepage(codepage_system,p_source,p_source_size);\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_char> const t_char * null_string_t();\r\n\t\ttemplate<> inline const char * null_string_t<char>() {return \"\";}\r\n\t\ttemplate<> inline const wchar_t * null_string_t<wchar_t>() {return L\"\";}\r\n\r\n\t\ttemplate<typename t_char> t_size strlen_t(const t_char * p_string,t_size p_string_size = ~0) {\r\n\t\t\tfor(t_size n=0;n<p_string_size;n++) {\r\n\t\t\t\tif (p_string[n] == 0) return n;\r\n\t\t\t}\r\n\t\t\treturn p_string_size;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_char> bool string_is_empty_t(const t_char * p_string,t_size p_string_size = ~0) {\r\n\t\t\tif (p_string_size == 0) return true;\r\n\t\t\treturn p_string[0] == 0;\r\n\t\t}\r\n\r\n\t\ttemplate<typename t_char,template<typename t_allocitem> class t_alloc = pfc::alloc_standard> class char_buffer_t {\r\n\t\tpublic:\r\n\t\t\tchar_buffer_t() {}\r\n\t\t\tchar_buffer_t(const char_buffer_t & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tvoid set_size(t_size p_count) {m_buffer.set_size(p_count);}\r\n\t\t\tt_char * get_ptr_var() {return m_buffer.get_ptr();}\r\n\t\t\tconst t_char * get_ptr() const {\r\n\t\t\t\treturn m_buffer.get_size() > 0 ? m_buffer.get_ptr() : null_string_t<t_char>();\r\n\t\t\t}\r\n\t\tprivate:\r\n\t\t\tpfc::array_t<t_char,t_alloc> m_buffer;\r\n\t\t};\r\n\r\n\t\ttemplate<template<typename t_allocitem> class t_alloc = pfc::alloc_standard>\r\n\t\tclass string_utf8_from_wide_t {\r\n\t\tpublic:\r\n\t\t\tstring_utf8_from_wide_t() {}\r\n\t\t\tstring_utf8_from_wide_t(const wchar_t * p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);}\r\n\t\t\r\n\t\t\tvoid convert(const wchar_t * p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tt_size size = estimate_wide_to_utf8(p_source,p_source_size);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_wide_to_utf8( m_buffer.get_ptr_var(),size,p_source,p_source_size);\r\n\t\t\t}\r\n\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<char,t_alloc> m_buffer;\r\n\t\t};\r\n\t\ttypedef string_utf8_from_wide_t<> string_utf8_from_wide;\r\n\t\t\r\n\t\ttemplate<template<typename t_allocitem> class t_alloc = pfc::alloc_standard>\r\n\t\tclass string_wide_from_utf8_t {\r\n\t\tpublic:\r\n\t\t\tstring_wide_from_utf8_t() {}\r\n\t\t\tstring_wide_from_utf8_t(const string_wide_from_utf8_t<t_alloc> & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_wide_from_utf8_t(const char* p_source,t_size p_source_size = ~0) {convert(p_source,p_source_size);}\r\n\r\n\t\t\tvoid convert(const char* p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tt_size size = estimate_utf8_to_wide(p_source,p_source_size);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_utf8_to_wide( m_buffer.get_ptr_var(),size,p_source,p_source_size);\r\n\t\t\t}\r\n\r\n\t\t\toperator const wchar_t * () const {return get_ptr();}\r\n\t\t\tconst wchar_t * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<wchar_t,t_alloc> m_buffer;\r\n\t\t};\r\n\t\ttypedef string_wide_from_utf8_t<> string_wide_from_utf8;\r\n\r\n\t\ttemplate<template<typename t_allocitem> class t_alloc = pfc::alloc_standard>\r\n\t\tclass string_wide_from_codepage_t {\r\n\t\tpublic:\r\n\t\t\tstring_wide_from_codepage_t() {}\r\n\t\t\tstring_wide_from_codepage_t(const string_wide_from_codepage_t<t_alloc> & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_wide_from_codepage_t(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);}\r\n\r\n\t\t\tvoid convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tt_size size = estimate_codepage_to_wide(p_codepage,p_source,p_source_size);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_codepage_to_wide(p_codepage, m_buffer.get_ptr_var(),size,p_source,p_source_size);\r\n\t\t\t}\r\n\r\n\t\t\toperator const wchar_t * () const {return get_ptr();}\r\n\t\t\tconst wchar_t * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<wchar_t,t_alloc> m_buffer;\r\n\t\t};\r\n\t\ttypedef string_wide_from_codepage_t<> string_wide_from_codepage;\r\n\r\n\t\t\r\n\t\ttemplate<template<typename t_allocitem> class t_alloc = pfc::alloc_standard>\r\n\t\tclass string_codepage_from_wide_t {\r\n\t\tpublic:\r\n\t\t\tstring_codepage_from_wide_t() {}\r\n\t\t\tstring_codepage_from_wide_t(const string_codepage_from_wide_t<t_alloc> & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_codepage_from_wide_t(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);}\r\n\r\n\t\t\tvoid convert(unsigned p_codepage,const wchar_t * p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tt_size size = estimate_wide_to_codepage(p_codepage,p_source,p_source_size);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_wide_to_codepage(p_codepage, m_buffer.get_ptr_var(),size,p_source,p_source_size);\r\n\t\t\t}\r\n\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<char,t_alloc> m_buffer;\r\n\t\t};\r\n\t\ttypedef string_codepage_from_wide_t<> string_codepage_from_wide;\r\n\r\n\t\tclass string_codepage_from_utf8 {\r\n\t\tpublic:\r\n\t\t\tstring_codepage_from_utf8() {}\r\n\t\t\tstring_codepage_from_utf8(const string_codepage_from_utf8 & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_codepage_from_utf8(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);}\r\n\t\t\t\r\n\t\t\tvoid convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tstring_wide_from_utf8 temp;\r\n\t\t\t\ttemp.convert(p_source,p_source_size);\r\n\t\t\t\tt_size size = estimate_wide_to_codepage(p_codepage,temp,~0);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_wide_to_codepage(p_codepage,m_buffer.get_ptr_var(),size,temp,~0);\r\n\t\t\t}\r\n\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<char> m_buffer;\r\n\t\t};\r\n\r\n\t\tclass string_utf8_from_codepage {\r\n\t\tpublic:\r\n\t\t\tstring_utf8_from_codepage() {}\r\n\t\t\tstring_utf8_from_codepage(const string_utf8_from_codepage & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_utf8_from_codepage(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {convert(p_codepage,p_source,p_source_size);}\r\n\t\t\t\r\n\t\t\tvoid convert(unsigned p_codepage,const char * p_source,t_size p_source_size = ~0) {\r\n\t\t\t\tstring_wide_from_codepage temp;\r\n\t\t\t\ttemp.convert(p_codepage,p_source,p_source_size);\r\n\t\t\t\tt_size size = estimate_wide_to_utf8(temp,~0);\r\n\t\t\t\tm_buffer.set_size(size);\r\n\t\t\t\tconvert_wide_to_utf8( m_buffer.get_ptr_var(),size,temp,~0);\r\n\t\t\t}\r\n\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\tprivate:\r\n\t\t\tchar_buffer_t<char> m_buffer;\r\n\t\t};\r\n\r\n\r\n\t\tclass string_utf8_from_ansi {\r\n\t\tpublic:\r\n\t\t\tstring_utf8_from_ansi() {}\r\n\t\t\tstring_utf8_from_ansi(const string_utf8_from_ansi & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_utf8_from_ansi(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {}\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\t\tvoid convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);}\r\n\r\n\t\tprivate:\r\n\t\t\tstring_utf8_from_codepage m_buffer;\r\n\t\t};\r\n\r\n\t\tclass string_ansi_from_utf8 {\r\n\t\tpublic:\r\n\t\t\tstring_ansi_from_utf8() {}\r\n\t\t\tstring_ansi_from_utf8(const string_ansi_from_utf8 & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_ansi_from_utf8(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {}\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\t\tvoid convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);}\r\n\r\n\t\tprivate:\r\n\t\t\tstring_codepage_from_utf8 m_buffer;\r\n\t\t};\r\n\r\n\t\tclass string_wide_from_ansi {\r\n\t\tpublic:\r\n\t\t\tstring_wide_from_ansi() {}\r\n\t\t\tstring_wide_from_ansi(const string_wide_from_ansi & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_wide_from_ansi(const char * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {}\r\n\t\t\toperator const wchar_t * () const {return get_ptr();}\r\n\t\t\tconst wchar_t * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\t\tvoid convert(const char * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);}\r\n\r\n\t\tprivate:\r\n\t\t\tstring_wide_from_codepage m_buffer;\r\n\t\t};\r\n\r\n\t\tclass string_ansi_from_wide {\r\n\t\tpublic:\r\n\t\t\tstring_ansi_from_wide() {}\r\n\t\t\tstring_ansi_from_wide(const string_ansi_from_wide & p_source) : m_buffer(p_source.m_buffer) {}\r\n\t\t\tstring_ansi_from_wide(const wchar_t * p_source,t_size p_source_size = ~0) : m_buffer(codepage_system,p_source,p_source_size) {}\r\n\t\t\toperator const char * () const {return get_ptr();}\r\n\t\t\tconst char * get_ptr() const {return m_buffer.get_ptr();}\r\n\t\t\tbool is_empty() const {return string_is_empty_t(get_ptr());}\r\n\t\t\tt_size length() const {return strlen_t(get_ptr());}\r\n\r\n\t\t\tvoid convert(const wchar_t * p_source,t_size p_source_size = ~0) {m_buffer.convert(codepage_system,p_source,p_source_size);}\r\n\r\n\t\tprivate:\r\n\t\t\tstring_codepage_from_wide m_buffer;\r\n\t\t};\r\n\r\n#ifdef UNICODE\r\n\t\ttypedef string_wide_from_utf8 string_os_from_utf8;\r\n\t\ttypedef string_utf8_from_wide string_utf8_from_os;\r\n#else\r\n\t\ttypedef string_ansi_from_utf8 string_os_from_utf8;\r\n\t\ttypedef string_utf8_from_ansi string_utf8_from_os;\r\n#endif\r\n\t}\r\n\r\n#else\r\n//PORTME\r\n#endif\r\n};"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/string_list.h",
    "content": "#ifndef _PFC_STRING_LIST_H_\r\n#define _PFC_STRING_LIST_H_\r\n\r\nnamespace pfc {\r\n\r\n\ttypedef list_base_const_t<const char*> string_list_const;\r\n\r\n\tclass string_list_impl : public string_list_const\r\n\t{\r\n\tpublic:\r\n\t\tt_size get_count() const {return m_data.get_size();}\r\n\t\tvoid get_item_ex(const char* & p_out, t_size n) const {p_out = m_data[n];}\r\n\r\n\t\tinline const char * operator[] (t_size n) const {return m_data[n];}\r\n\r\n\t\tvoid add_item(const char * p_string) {\r\n\t\t\tt_size idx = m_data.get_size();\r\n\t\t\tm_data.set_size(idx + 1);\r\n\t\t\tm_data[idx] = p_string;\r\n\t\t}\r\n\r\n\t\tvoid add_items(const string_list_const & p_source) {_append(p_source);}\r\n\r\n\t\tvoid remove_all() \r\n\t\t{\r\n\t\t\tm_data.set_size(0);\r\n\t\t}\r\n\r\n\t\t//unnecessary since pfc::array_t<pfc::string8> is in use for implementation\r\n\t\t//~string_list_impl() {remove_all();}\r\n\r\n\t\tinline string_list_impl() {}\r\n\t\tinline string_list_impl(const string_list_impl & p_source) {_copy(p_source);}\r\n\t\tinline string_list_impl(const string_list_const & p_source) {_copy(p_source);}\r\n\t\tinline const string_list_impl & operator=(const string_list_impl & p_source) {_copy(p_source);return *this;}\r\n\t\tinline const string_list_impl & operator=(const string_list_const & p_source) {_copy(p_source);return *this;}\r\n\t\tinline const string_list_impl & operator+=(const string_list_impl & p_source) {_append(p_source);return *this;}\r\n\t\tinline const string_list_impl & operator+=(const string_list_const & p_source) {_append(p_source);return *this;}\r\n\r\n\tprivate:\r\n\r\n\t\tvoid _append(const string_list_const & p_source) {\r\n\t\t\tconst t_size toadd = p_source.get_count(), base = m_data.get_size();\r\n\t\t\tm_data.set_size(base+toadd);\r\n\t\t\tfor(t_size n=0;n<toadd;n++) m_data[base+n] = p_source[n];\r\n\t\t}\r\n\r\n\t\tvoid _copy(const string_list_const & p_source) {\r\n\t\t\tconst t_size newcount = p_source.get_count();\r\n\t\t\tm_data.set_size(newcount);\r\n\t\t\tfor(t_size n=0;n<newcount;n++) m_data[n] = p_source[n];\r\n\t\t}\r\n\r\n\t\tpfc::array_t<pfc::string8,pfc::alloc_fast> m_data;\r\n\t};\r\n}\r\n\r\n#endif //_PFC_STRING_LIST_H_\r\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/traits.h",
    "content": "namespace pfc {\r\n\r\n\tclass traits_default {\r\n\tpublic:\r\n\t\tenum { \r\n\t\t\trealloc_safe = false, \r\n\t\t\tneeds_destructor = true, \r\n\t\t\tneeds_constructor = true, \r\n\t\t\tconstructor_may_fail = true\r\n\t\t};\r\n\t};\r\n\t\r\n\tclass traits_default_movable {\r\n\tpublic:\r\n\t\tenum { \r\n\t\t\trealloc_safe = true, \r\n\t\t\tneeds_destructor = true, \r\n\t\t\tneeds_constructor = true, \r\n\t\t\tconstructor_may_fail = true\r\n\t\t};\r\n\t};\r\n\r\n\tclass traits_rawobject : public traits_default {\r\n\tpublic:\r\n\t\tenum { \r\n\t\t\trealloc_safe = true, \r\n\t\t\tneeds_destructor = false, \r\n\t\t\tneeds_constructor = false, \r\n\t\t\tconstructor_may_fail = false\r\n\t\t};\r\n\t};\r\n\r\n\tclass traits_vtable {\r\n\tpublic:\r\n\t\tenum {\r\n\t\t\trealloc_safe = true,\r\n\t\t\tneeds_destructor = true,\r\n\t\t\tneeds_constructor = true,\r\n\t\t\tconstructor_may_fail = false\r\n\t\t};\r\n\t};\r\n\r\n\ttemplate<typename T> class traits_t : public traits_default {};\r\n\r\n\ttemplate<typename traits1,typename traits2>\r\n\tclass combine_traits {\r\n\tpublic:\r\n\t\tenum {\r\n\t\t\trealloc_safe = (traits1::realloc_safe && traits2::realloc_safe),\r\n\t\t\tneeds_destructor = (traits1::needs_destructor || traits2::needs_destructor),\r\n\t\t\tneeds_constructor = (traits1::needs_constructor || traits2::needs_constructor),\r\n\t\t\tconstructor_may_fail = (traits1::constructor_may_fail || traits2::constructor_may_fail),\r\n\t\t};\r\n\t};\r\n\r\n\ttemplate<typename type1, typename type2>\r\n\tclass traits_combined : public combine_traits<pfc::traits_t<type1>,pfc::traits_t<type2> > {};\r\n\r\n\ttemplate<typename T> class traits_t<T*> : public traits_rawobject {};\r\n\r\n\ttemplate<> class traits_t<char> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<unsigned char> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<wchar_t> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<short> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<unsigned short> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<int> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<unsigned int> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<long> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<unsigned long> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<long long> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<unsigned long long> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<bool> : public traits_rawobject {};\r\n\r\n\ttemplate<> class traits_t<float> : public traits_rawobject {};\r\n\ttemplate<> class traits_t<double> : public traits_rawobject {};\r\n\t\r\n\ttemplate<> class traits_t<GUID> : public traits_rawobject {};\r\n\r\n\ttemplate<typename T,t_size p_count>\r\n\tclass traits_t<T[p_count]> : public traits_t<T> {};\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/pfc/utf8.cpp",
    "content": "#include \"pfc.h\"\r\n\r\nnamespace pfc {\r\n//utf8 stuff\r\n\r\nstatic const t_uint8 mask_tab[6]={0x80,0xE0,0xF0,0xF8,0xFC,0xFE};\r\n\r\nstatic const t_uint8 val_tab[6]={0,0xC0,0xE0,0xF0,0xF8,0xFC};\r\n\r\nt_size utf8_char_len_from_header(char p_c)\r\n{\r\n\tt_uint8 c = (t_uint8)p_c;\r\n\r\n\tt_size cnt = 0;\r\n\tfor(;;)\r\n\t{\r\n\t\tif ((p_c & mask_tab[cnt])==val_tab[cnt]) break;\r\n\t\tif (++cnt>=6) return 0;\r\n\t}\r\n\r\n\treturn cnt + 1;\r\n\r\n}\r\n\r\nt_size utf8_decode_char(const char *p_utf8,unsigned * wide,t_size max)\r\n{\r\n\tconst t_uint8 * utf8 = (const t_uint8*)p_utf8;\r\n\t\r\n\tif (wide) *wide = 0;\r\n\r\n\tif (max==0)\r\n\t\treturn 0;\r\n\telse if (max>6) max = 6;\r\n\r\n\tif (utf8[0]<0x80)\r\n\t{\r\n\t\tif (wide) *wide = utf8[0];\r\n\t\treturn utf8[0]>0 ? 1 : 0;\r\n\t}\r\n\r\n\tunsigned res=0;\r\n\tunsigned n;\r\n\tunsigned cnt=0;\r\n\tfor(;;)\r\n\t{\r\n\t\tif ((*utf8&mask_tab[cnt])==val_tab[cnt]) break;\r\n\t\tif (++cnt>=max) return 0;\r\n\t}\r\n\tcnt++;\r\n\r\n\tif (cnt==2 && !(*utf8&0x1E)) return 0;\r\n\r\n\tif (cnt==1)\r\n\t\tres=*utf8;\r\n\telse\r\n\t\tres=(0xFF>>(cnt+1))&*utf8;\r\n\r\n\tfor (n=1;n<cnt;n++)\r\n\t{\r\n\t\tif ((utf8[n]&0xC0) != 0x80)\r\n\t\t\treturn 0;\r\n\t\tif (!res && n==2 && !((utf8[n]&0x7F) >> (7 - cnt)))\r\n\t\t\treturn 0;\r\n\r\n\t\tres=(res<<6)|(utf8[n]&0x3F);\r\n\t}\r\n\r\n\tif (wide)\r\n\t\t*wide=res;\r\n\r\n\treturn cnt;\r\n}\r\n\r\n\r\nt_size utf8_encode_char(unsigned wide,char * target)\r\n{\r\n\tt_size count;\r\n\r\n\tif (wide < 0x80)\r\n\t\tcount = 1;\r\n\telse if (wide < 0x800)\r\n\t\tcount = 2;\r\n\telse if (wide < 0x10000)\r\n\t\tcount = 3;\r\n\telse if (wide < 0x200000)\r\n\t\tcount = 4;\r\n\telse if (wide < 0x4000000)\r\n\t\tcount = 5;\r\n\telse if (wide <= 0x7FFFFFFF)\r\n\t\tcount = 6;\r\n\telse\r\n\t\treturn 0;\r\n\t//if (count>max) return 0;\r\n\r\n\tif (target == 0)\r\n\t\treturn count;\r\n\r\n\tswitch (count)\r\n\t{\r\n    case 6:\r\n\t\ttarget[5] = 0x80 | (wide & 0x3F);\r\n\t\twide = wide >> 6;\r\n\t\twide |= 0x4000000;\r\n    case 5:\r\n\t\ttarget[4] = 0x80 | (wide & 0x3F);\r\n\t\twide = wide >> 6;\r\n\t\twide |= 0x200000;\r\n    case 4:\r\n\t\ttarget[3] = 0x80 | (wide & 0x3F);\r\n\t\twide = wide >> 6;\r\n\t\twide |= 0x10000;\r\n    case 3:\r\n\t\ttarget[2] = 0x80 | (wide & 0x3F);\r\n\t\twide = wide >> 6;\r\n\t\twide |= 0x800;\r\n    case 2:\r\n\t\ttarget[1] = 0x80 | (wide & 0x3F);\r\n\t\twide = wide >> 6;\r\n\t\twide |= 0xC0;\r\n\tcase 1:\r\n\t\ttarget[0] = wide;\r\n\t}\r\n\r\n\treturn count;\r\n}\r\n\r\nt_size utf16_encode_char(unsigned cur_wchar,wchar_t * out)\r\n{\r\n\tif (cur_wchar>0 && cur_wchar<(1<<20))\r\n\t{\r\n\t\tif (sizeof(wchar_t) == 2 && cur_wchar>=0x10000)\r\n\t\t{\r\n\t\t\tunsigned c = cur_wchar - 0x10000;\r\n\t\t\t//MSDN:\r\n\t\t\t//The first (high) surrogate is a 16-bit code value in the range U+D800 to U+DBFF. The second (low) surrogate is a 16-bit code value in the range U+DC00 to U+DFFF. Using surrogates, Unicode can support over one million characters. For more details about surrogates, refer to The Unicode Standard, version 2.0.\r\n\t\t\tout[0] = (wchar_t)(0xD800 | (0x3FF & (c>>10)) );\r\n\t\t\tout[1] = (wchar_t)(0xDC00 | (0x3FF & c) ) ;\r\n\t\t\treturn 2;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t*out = (wchar_t)cur_wchar;\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t}\r\n\treturn 0;\r\n}\r\n\r\nt_size utf16_decode_char(const wchar_t * p_source,unsigned * p_out,t_size p_source_length) {\r\n\tif (p_source_length == 0) return 0;\r\n\telse if (p_source_length == 1) {\r\n\t\t*p_out = p_source[0];\r\n\t\treturn 1;\r\n\t} else {\r\n\t\tt_size retval = 0;\r\n\t\tunsigned decoded = p_source[0];\r\n\t\tif (decoded != 0)\r\n\t\t{\r\n\t\t\tretval = 1;\r\n\t\t\tif ((decoded & 0xFC00) == 0xD800)\r\n\t\t\t{\r\n\t\t\t\tunsigned low = p_source[1];\r\n\t\t\t\tif ((low & 0xFC00) == 0xDC00)\r\n\t\t\t\t{\r\n\t\t\t\t\tdecoded = 0x10000 + ( ((decoded & 0x3FF) << 10) | (low & 0x3FF) );\r\n\t\t\t\t\tretval = 2;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t*p_out = decoded;\r\n\t\treturn retval;\r\n\t}\r\n}\r\n\r\n\r\nUINT utf8_get_char(const char * src)\r\n{\r\n\tUINT rv = 0;\r\n\tutf8_decode_char(src,&rv);\r\n\treturn rv;\r\n}\r\n\r\n\r\nt_size utf8_char_len(const char * s,t_size max)\r\n{\r\n\treturn utf8_decode_char(s,0,max);\r\n}\r\n\r\nt_size skip_utf8_chars(const char * ptr,t_size count)\r\n{\r\n\tt_size num = 0;\r\n\tfor(;count && ptr[num];count--)\r\n\t{\r\n\t\tt_size d = utf8_char_len(ptr+num);\r\n\t\tif (d<=0) break;\r\n\t\tnum+=d;\t\t\r\n\t}\r\n\treturn num;\r\n}\r\n\r\nbool is_valid_utf8(const char * param,t_size max) {\r\n\tt_size walk = 0;\r\n\twhile(walk < max && param[walk] != 0) {\r\n\t\tt_size d;\r\n\t\td = utf8_decode_char(param + walk,NULL,max - walk);\r\n\t\tif (d==0) return false;\r\n\t\twalk += d;\r\n\t\tif (walk > max) {\r\n\t\t\tPFC_ASSERT(0);//should not be triggerable\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool is_lower_ascii(const char * param)\r\n{\r\n\twhile(*param)\r\n\t{\r\n\t\tif (*param<0) return false;\r\n\t\tparam++;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nstatic bool check_end_of_string(const char * ptr)\r\n{\r\n\t__try {\r\n\t\treturn !*ptr;\r\n\t}\r\n\t__except(1) {return true;}\r\n}\r\n\r\nunsigned strcpy_utf8_truncate(const char * src,char * out,unsigned maxbytes)\r\n{\r\n\tunsigned rv = 0 , ptr = 0;\r\n\tif (maxbytes>0)\r\n\t{\t\r\n\t\tmaxbytes--;//for null\r\n\t\twhile(!check_end_of_string(src) && maxbytes>0)\r\n\t\t{\r\n\t\t\t__try {\r\n\t\t\t\tt_size delta = utf8_char_len(src);\r\n\t\t\t\tif (delta>maxbytes || delta==0) break;\r\n\t\t\t\tdo \r\n\t\t\t\t{\r\n\t\t\t\t\tout[ptr++] = *(src++);\r\n\t\t\t\t} while(--delta);\r\n\t\t\t} __except(1) { break; }\r\n\t\t\trv = ptr;\r\n\t\t}\r\n\t\tout[rv]=0;\r\n\t}\r\n\treturn rv;\r\n}\r\n\r\nt_size strlen_utf8(const char * p,t_size num)\r\n{\r\n\tunsigned w;\r\n\tt_size d;\r\n\tt_size ret = 0;\r\n\tfor(;num;)\r\n\t{\r\n\t\td = utf8_decode_char(p,&w);\r\n\t\tif (w==0 || d<=0) break;\r\n\t\tret++;\r\n\t\tp+=d;\r\n\t\tnum-=d;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nt_size utf8_chars_to_bytes(const char * string,t_size count)\r\n{\r\n\tt_size bytes = 0;\r\n\twhile(count)\r\n\t{\r\n\t\tt_size delta = utf8_decode_char(string+bytes,0);\r\n\t\tif (delta==0) break;\r\n\t\tbytes += delta;\r\n\t\tcount--;\r\n\t}\r\n\treturn bytes;\r\n}\r\n\r\n}"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/sdk-license.txt",
    "content": "foobar2000 0.9.4 SDK\r\nCopyright (c) 2001-2007, Peter Pawlowski\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\r\n\r\nRedistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. \r\nNeither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\r\nRedistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\r\n\r\nUsage restrictions:\r\nIt is illegal to use this SDK as a part of foobar2000 components that operate outside of legally documented programming interfaces (APIs), such as using window procedure hooks to modify user interface behaviors. We believe components doing so to be harmful to our userbase by introducing compatibility issues and dependencies on undocumented behaviors of our code that may change at any time without any notice or an update to the SDK which would reflect the change.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
  },
  {
    "path": "plugins/foobar09/foobar_sdk/sdk-readme.css",
    "content": "/**\n * Design elements for default Template\n *\n * @author Andreas Gohr <andi@splitbrain.org>\n * @author Anika Henke <henke@cosmocode.de>\n */\n\n/* -------------- general elements --------------- */\n\nbody {\n  font: 80% \"Lucida Grande\", Verdana, Lucida, Helvetica, Arial, sans-serif;\n  background-color: White;\n  color: Black;\n  margin: 0;\n  padding: 0;\n}\n\n/* the document */\ndiv.page {\n  margin-top: 4px;\n  margin-left:  1em;\n  margin-right: 2em;\n  text-align: justify;\n}\n\ntable {\n  font-size: 100%;\n  padding:0;\n  margin:0;\n}\n\ntr,td,th {padding:0; margin:0;}\n\nimg {border:0}\n\np {padding:0; margin: 0 0 1.0em 0;}\n\nhr {\n  border: 0px;\n  border-top: 1px solid #8cacbb;\n  text-align:center;\n  height: 0px;\n}\n\ndiv.nothing {\n  text-align:center;\n\tmargin: 2em;\n}\n\n/* ---------------- forms ------------------------ */\n\nform {\n  border: none;\n  margin: 0;\n  display: inline;\n}\n\nlabel {\n  display: block;\n  text-align: right;\n  font-weight: bold;\n}\n\nlabel.simple {\n  text-align: left;\n  font-weight: normal;\n}\n\nlabel input.edit {\n  width: 50%;\n}\n\nfieldset {\n  width: 300px;\n  text-align: center;\n  border: 1px solid #8cacbb;\n  padding: 0.5em;\n}\n\ntextarea.edit {\n  font-family:monospace;\n  border: 1px solid #8cacbb;  \n  color: Black;\n  background-color: white;\n  font-size:14px;\n  padding: 3px;\n  width:100%;\n}\n\ninput.edit,select.edit {\n  font-size: 100%;\n  border: 1px solid #8cacbb;\n  height: 22px !important;\n  max-height: 22px !important;\n  min-height: 22px !important;\n  color: Black;\n  background-color: white;\n  vertical-align: middle;\n  padding: 1px;\n  display: inline;\n}\n\ninput.missing {\n  font-size: 100%;\n  border: 1px solid #8cacbb;\n  height: 22px !important;\n  max-height: 22px !important;\n  min-height: 22px !important;\n  color: Black;\n  background-color: #ffcccc;\n  vertical-align: middle;\n  padding: 1px;\n  display: inline;\n}\n\n/* --------- buttons ------------------- */\n\n\ninput.button {\n  border: 1px solid #8cacbb;  \n  color: Black;\n  background-color: white;\n  vertical-align: middle;\n  text-decoration:none;\n  font-size: 100%;\n  cursor: pointer;\n  height: 22px !important;\n  max-height: 22px !important;\n  min-height: 22px !important;\n  margin: 1px;\n  display: inline;\n}\n\ndiv.secedit input.button {\n  border: 1px solid #8cacbb;\n  color: Black;\n  background-color: white;\n  vertical-align: middle;\n  text-decoration:none;\n  margin: 0px;\n  padding: 0px;\n  font-size: 10px;\n  cursor: pointer;\n  height: 15px;\n  max-height: 15px !important;\n  min-height: 15px !important;\n  float:right;\n  display: inline;\n}\n\n/* --------------- Links ------------------ */\n\na {\n  color:#436976;\n  text-decoration:none;\n}\na:hover {\n  color:#000000;\n  text-decoration:underline;\n}\n\n/* external link */\na.urlextern{\n    background: transparent url(images/link_icon.gif) 0px 1px no-repeat;\n    padding: 1px 0px 1px 16px;\n    color:#436976;\n    text-decoration:none;\n}\na.urlextern:visited {\n  color:Purple;\n}\na.urlextern:hover {\n  text-decoration:underline;\n}\n\n/* windows share */\na.windows{\n    background: transparent url(images/windows.gif) 0px 1px no-repeat;\n    padding: 1px 0px 1px 16px;\n    color:#436976;\n    text-decoration:none;\n} \na.windows:visited {\n  color:Purple;\n}\na.windows:hover { \n  text-decoration:underline;\n}\n\n/* interwiki link */\na.interwiki{\n    background: transparent url(images/interwiki.png) 0px 1px no-repeat;\n\t\tpadding-left: 16px;\n    color:#436976;\n    text-decoration:none;\n}\na.interwiki:visited {\n  color:Purple;\n}\na.interwiki:hover {\n  text-decoration:underline;\n}\n\n/* link to some embedded media */\na.media {\n  color:#436976;\n  text-decoration:none;\n}\na.media:hover {\n  color:#436976;\n  text-decoration:underline\n}\n\n/* email link */\na.mail {\n  background: transparent url(images/mail_icon.gif) 0px 1px no-repeat;\n  padding: 1px 0px 1px 16px;\n  color:#436976;\n  text-decoration:none;\n}\na.mail:hover {\n  text-decoration:underline;\n}\n\n/* existing wikipage */\na.wikilink1:link    { color:#009900; text-decoration:none }\na.wikilink1:visited { color:#009900; text-decoration:none }\na.wikilink1:hover   { color:#009900; text-decoration:underline }\n\n/* not existing wikipage */\na.wikilink2:link    { color:#FF3300; text-decoration:none }\na.wikilink2:visited { color:#FF3300; text-decoration:none }\na.wikilink2:hover   { color:#FF3300; text-decoration:underline }\n\n\n/* ------------- Page elements ----------------- */\n\ndiv.preview{\n  background:#f7f9fa;\n  margin-left:2em;\n  padding: 4px;\n  border: 1px dashed #000000;\n}\n\ndiv.breadcrumbs{\n  background-color: #f5f5f5;\n  font-size:80%;\n  color: #666666;\n  padding-left: 4px;\n}\n\nspan.user{\n  color: #cccccc;\n  font-size: 90%;\n}\n\n/* embedded images */\nimg.media {\n  margin: 3px;\n}\n\nimg.medialeft {\n  border: 0;\n  float: left;\n  margin: 0 1.5em 0 0;\n}\n\nimg.mediaright {\n  border: 0;\n  float: right;\n  margin: 0 0 0 1.5em;\n}\n\nimg.mediacenter {\n  border: 0;\n\tdisplay: block;\n  margin-left: auto;\n  margin-right: auto;\n}\n\nacronym {\n  cursor: help;\n  border-bottom: 1px dotted #000;\n}\n\n/* general headline setup */\nh1, h2, h3, h4, h5 {\n    color: Black;\n    background-color: transparent;\n    font-family: \"Lucida Grande\", Verdana, Lucida, Helvetica, Arial, sans-serif;\n    font-size: 100%;\n    font-weight: normal;\n    margin-left:    0;\n    margin-right:   0;\n    margin-top:     0;\n    margin-bottom:  1em;\n    padding-left:   0;\n    padding-right:  0;\n    padding-top:    0.5em;\n    padding-bottom: 0;\n    border-bottom: 1px solid #8cacbb;\n    clear: left;\n}\n\n/* special headlines */\nh1 {font-size: 160%; margin-left: 0px; font-weight: bold;}\nh2 {font-size: 150%; margin-left: 20px;}\nh3 {font-size: 140%; margin-left: 40px; border-bottom: none; font-weight: bold;}\nh4 {font-size: 120%; margin-left: 60px; border-bottom: none; font-weight: bold;}\nh5 {font-size: 100%; margin-left: 80px; border-bottom: none; font-weight: bold;}\n\n/* indent different sections */\ndiv.level1 {margin-left: 3px;}\ndiv.level2 {margin-left: 23px;}\ndiv.level3 {margin-left: 43px;}\ndiv.level4 {margin-left: 63px;}\ndiv.level5 {margin-left: 83px;}\n\n/* unordered lists */\nul { \n  line-height: 1.5em;\n  list-style-type: square;\n  margin: 0.5em 0 0.5em 1.5em;\n  padding: 0;\n  list-style-image: url(images/bullet.gif);\n}\n\n/* ordered lists */\nol {\n  line-height: 1.5em;\n  margin: 0.5em 0 0.5em 1.5em;\n  padding: 0;\n  color: #638c9c;\n  font-weight: bold;\n  list-style-image: none;\n}\n\n/* the list items overriding the ol definition */\nspan.li {\n  color: #000000;\n  font-weight: normal;\n}\n\nol {list-style-type: decimal}\nol ol {list-style-type: upper-roman}\nol ol ol {list-style-type: lower-alpha}\nol ol ol ol {list-style-type: lower-greek}\n\nli.open {\n  list-style-image: url(images/open.gif);\n}\n\nli.closed {\n  list-style-image: url(images/closed.gif);\n}\n\nblockquote {\n  border-left: 2px solid #8cacbb;\n  padding-left: 3px;\n  margin-left: 0;\n}\n\n/* code blocks by indention */\npre.pre {\n  font-size: 120%;\n  padding: 0.5em;\n  border: 1px dashed #8cacbb;\n  color: Black;\n  background-color: #f7f9fa;\n  overflow: auto;\n}\n\n/* code blocks by code tag */\npre.code {\n  font-size: 120%;\n  padding: 0.5em;\n  border: 1px dashed #8cacbb;\n  color: Black;\n  background-color: #f7f9fa;\n  overflow: auto;\n}\n\n/* inline code words */\ncode {\n  font-size: 120%;\n}\n\n/* code blocks by file tag */\npre.file {\n  font-size: 120%;\n  padding: 0.5em;\n  border: 1px dashed #8cacbb;\n  color: Black;\n  background-color: #dee7ec;\n  overflow: auto;\n}\n\n/* inline tables */\ntable.inline {\n  background-color: #ffffff;\n  border-spacing: 0px;\n  border-collapse: collapse;\n}\n\ntable.inline th {\n  padding: 3px;\n  border: 1px solid #8cacbb;\n  background-color: #dee7ec;\n}\n\ntable.inline td {\n  padding: 3px;\n  border: 1px solid #8cacbb;\n}\n\n.leftalign{\n  text-align: left;\n}\n\n.centeralign{\n  text-align: center;\n}\n\n.rightalign{\n  text-align: right;\n}\n\n/* ---------- table of contents ------------------- */\n\ndiv.toc {\n  margin-left: 2em;\n  margin-top: 1.2em;\n  margin-bottom: 0;\n  float:right;\n  width: 200px;\n  font-size: 80%;\n  clear:both;\n}\n\ndiv.tocheader {\n  padding: 3px;\n  border: 1px solid #8cacbb;\n  background-color: #dee7ec;\n  text-align: left;\n  font-weight:bold;\n  margin-bottom: 2px;\n}\n\n#tocinside {\n  border: 1px solid #8cacbb;\n  background-color: #ffffff;\n  text-align: left;\n  padding-top: 0.5em;\n  padding-bottom: 0.7em;\n}\n\nul.toc {\n  list-style-type: none;\n  list-style-image: none;\n  line-height: 1.2em;\n  margin: 0;\n  padding: 0;\n  padding-left: 1em;\n}\n\nul.toc li {\n  background: transparent url(images/tocdot2.gif) 0 0.6em no-repeat;\n  padding-left:0.4em;\n}\n\nul.toc li.clear {\n  background-image: none;\n  padding-left:0.4em;\n}\n\na.toc {\n  color: #436976;\n  text-decoration:none;\n}\n\na.toc:hover {\n  color: #000000;\n  text-decoration:underline; \n}\n\n/* ---------------------------- Diff rendering --------------------------*/\ntable.diff { background:white; }\ntd.diff-blockheader {font-weight:bold}\ntd.diff-header {\n  border-bottom: 1px solid #8cacbb;\n  font-size:120%;\n}\ntd.diff-addedline {\n    background:#ddffdd;\n    font-family: monospace;\n    font-size: 100%;\n}\ntd.diff-deletedline { \n    background:#ffffbb;\n    font-family: monospace;    \n    font-size: 100%;\n}\ntd.diff-context {\n    background:#f7f9fa;\n    font-family: monospace;\n    font-size: 100%;\n}\nspan.diffchange { color: red; }\n\n/* --------------------- footnotes -------------------------------- */\n\ndiv.footnotes{\n  clear:both;\n  border-top: 1px solid #8cacbb;\n  padding-left: 1em;\n  margin-top: 1em;\n}\n\ndiv.fn{\n  font-size:90%;\n}\n\na.fn_top{\n  vertical-align:super;\n  font-size:80%;\n}\n\na.fn_bot{\n  vertical-align:super;\n  font-size:80%;\n  font-weight:bold;\n}\n\n\n/* --------------- search result formating --------------- */\n.search_result{\n  margin-bottom: 6px;\n  padding-left: 30px;\n  padding-right: 10px;\n}\n\n.search_snippet{\n  color: #999999;\n  font-size: 12px;\n  margin-left: 20px;\n}\n\n.search_sep{\n  color: #000000;\n}\n\n.search_hit{\n  color: #000000;\n  background: #FFFF99;\n}\n\ndiv.search_quickresult{\n  margin-bottom: 15px;\n  padding-bottom: 5px;\n  border-bottom: 1px dashed #8cacbb;\n  margin-left: 30px;\n  padding-right: 10px;\n}\n\ndiv.search_quickhits {\n  margin-left: 1em;\n  float:left;\n  background: transparent url(images/bullet.gif) 0px 1px no-repeat;\n  padding: 1px 0px 1px 8px;\n  width: 30%;\n}\n\n/* ------------------ Additional ---------------------- */\n.footerinc a img {\n    opacity: 0.5;\n}\n\n.footerinc a:hover img {\n    opacity: 1;\n}\n\n/* ---- Admin --- */\n\ndiv.acladmin label {\n  text-align: left;\n  font-weight: normal;\n  display: inline;\n}\n\ndiv.acladmin table{\n  margin-left: 10%;\n  width: 80%;\n}\n"
  },
  {
    "path": "plugins/foobar09/foobar_sdk/sdk-readme.html",
    "content": "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\"\r\n lang=\"en\" dir=\"ltr\">\r\n<head>\n  <title>foobar2000 0.9.4 SDK readme</title>\r\n  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n  <meta name=\"generator\" content=\"DokuWiki Release 2005-05-07\" />\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"sdk-readme.css\" />\n</head>\n<body>\n<div class=\"toc\">\n<div class=\"tocheader\">Table of Contents <script type=\"text/javascript\">showTocToggle(\"+\",\"-\")</script></div>\n<div id=\"tocinside\">\n<ul class=\"toc\">\n<li class=\"level1\"><span class=\"li\"><a href=\"#foobar2000_0.9.4_sdk_readme\" class=\"toc\"> foobar2000 0.9.4 SDK readme </a></span><ul class=\"toc\">\n<li class=\"level2\"><span class=\"li\"><a href=\"#compatibility\" class=\"toc\"> Compatibility </a></span></li>\n<li class=\"level2\"><span class=\"li\"><a href=\"#basic_usage\" class=\"toc\"> Basic usage </a></span></li>\n<li class=\"level2\"><span class=\"li\"><a href=\"#structure_of_a_component\" class=\"toc\"> Structure of a component </a></span><ul class=\"toc\">\n<li class=\"level3\"><span class=\"li\"><a href=\"#services\" class=\"toc\"> Services </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#entrypoint_services\" class=\"toc\"> Entrypoint services </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#service_extensions\" class=\"toc\"> Service extensions </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#autopointer_template_use\" class=\"toc\"> Autopointer template use </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#exception_use\" class=\"toc\"> Exception use </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#storing_configuration\" class=\"toc\"> Storing configuration </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#use_of_global_callback_services\" class=\"toc\"> Use of global callback services </a></span></li>\n</ul>\n</li>\n<li class=\"level2\"><span class=\"li\"><a href=\"#service_class_design_guidelines_advanced\" class=\"toc\"> Service class design guidelines (advanced) </a></span><ul class=\"toc\">\n<li class=\"level3\"><span class=\"li\"><a href=\"#cross-dll_safety\" class=\"toc\"> Cross-DLL safety </a></span></li>\n<li class=\"level3\"><span class=\"li\"><a href=\"#entrypoint_service_efficiency\" class=\"toc\"> Entrypoint service efficiency </a></span></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</div>\n</div>\n\n<a name=\"foobar2000_0.9.4_sdk_readme\"></a><h1> foobar2000 0.9.4 SDK readme </h1>\n<div class=\"level1\">\n\n</div>\n<!-- SECTION [1-46] -->\n<a name=\"compatibility\"></a><h2> Compatibility </h2>\n<div class=\"level2\">\n\n<p>\n This <acronym title=\"Software Development Kit\">SDK</acronym> is compatible with foobar2000 0.9.4. It is not compatible with any earlier versions, and not guaranteed to be compatible with any future versions (though upcoming 0.9.X releases will aim to maintain compatibility as far as possible without crippling newly added functionality).\n</p>\n\n</div>\n<!-- SECTION [47-361] -->\n<a name=\"basic_usage\"></a><h2> Basic usage </h2>\n<div class=\"level2\">\n\n<p>\n Each component must link against:\n</p>\n<ul>\n<li class=\"level1\"><span class=\"li\"> foobar2000_SDK project (contains declarations of services and various service-specific helper code)</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> foobar2000_component_client project (contains DLL entrypoint)</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> shared.dll (various helper code, mainly win32 function wrappers taking UTF-8 strings)</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> PFC (non-<acronym title=\"Operating System\">OS</acronym>-specific helper class library)</span>\n</li>\n</ul>\n\n<p>\n Foobar2000_SDK, foobar2000_component_client and PFC are included in sourcecode form; you can link against them by adding them to your workspace and using dependencies. To link against shared.dll, you must add &ldquo;shared.lib&rdquo; to linker input manually.\n</p>\n\n</div>\n<!-- SECTION [362-977] -->\n<a name=\"structure_of_a_component\"></a><h2> Structure of a component </h2>\n<div class=\"level2\">\n\n<p>\n A component is a DLL that implements one or more entrypoint services and interacts with services provided by other components. \n</p>\n\n</div>\n<!-- SECTION [978-1144] -->\n<a name=\"services\"></a><h3> Services </h3>\n<div class=\"level3\">\n\n<p>\n A service type is an interface class, deriving directly or indirectly from <code>service_base</code> class. A service type class must not have any data members; it can only provide virtual methods (to be overridden by service implementation), helper non-virtual methods built around virtual methods, static helper methods, and constants / enums. Each service interface class must have a static <code>class_guid</code> member, used for identification when enumerating services or querying for supported functionality. A service type declaration should declare a class with public virtual/helper/static methods, and use <code>FB2K_MAKE_SERVICE_INTERFACE()</code> / <code>FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT()</code> macro to implement standard service behaviors for the class; additionally, <code>class_guid</code> needs to be defined outside class declaration (e.g. <code>const GUID someclass::class_guid = {....};</code> ). Note that most of components will not declare their own service types, they will only implement existing ones declared in the <acronym title=\"Software Development Kit\">SDK</acronym>.\n</p>\n\n<p>\nA service implementation is a class derived from relevant service type class, implementing virtual methods declared by service type class. Note that service implementation class does not implement virtual methods declared by service_base; those are implemented by service type declaration framework (<code>service_query</code>) or by instantiation framework (<code>service_add_ref</code> / <code>service_release</code>). Service implementation classes are instantiated using <code>service_factory</code> templates in case of entrypoint services (see below), or using <code>service_impl_t</code> template and operator <code>new</code>: &ldquo;<code>myserviceptr = new service_impl_t&lt;myservice_impl&gt;(params);</code>&ldquo;.\n</p>\n\n<p>\nEach service object provides reference counter features and (<code>service_add_ref()</code> and <code>service_release()</code> methods) as well as a method to query for extended functionality (<code>service_query()</code> method). Those methods are implemented by service framework and should be never overridden by service implementations. These methods should also never be called directly - reference counter methods are managed by relevant autopointer templates, <code>service_query_t</code> function template should be used instead of calling <code>service_query</code> directly, to ensure type safety and correct type conversions.\n</p>\n\n</div>\n<!-- SECTION [1145-3410] -->\n<a name=\"entrypoint_services\"></a><h3> Entrypoint services </h3>\n<div class=\"level3\">\n\n<p>\n An entrypoint service type is a special case of a service type that can be registered using <code>service_factory</code> templates, and then accessed from any point of service system (excluding DLL startup/shutdown code, such as code inside static object constructors/destructors). An entrypoint service type class must directly derive from <code>service_base</code>.\n</p>\n\n<p>\nRegistered entrypoint services can be accessed using:\n</p>\n<ul>\n<li class=\"level1\"><span class=\"li\"> For services types with variable number of implementations registered: <code>service_enum_t&lt;T&gt;</code> template, <code>service_class_helper_t&lt;T&gt;</code> template, etc, e.g. <pre class=\"code\">service_enum_t&lt;someclass&gt; e; service_ptr_t&lt;someclass&gt; ptr; <span class=\"kw1\">while</span><span class=\"br0\">&#40;</span>e.<span class=\"me1\">next</span><span class=\"br0\">&#40;</span>ptr<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> ptr-&gt;dosomething<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;</pre>\n<p>\n</span>\n\n</p>\n</li>\n<li class=\"level1\"><span class=\"li\"> For services types with single always-present implementation registered - such as core services like <code>playlist_manager</code> - using <code>static_api_ptr_t&lt;T&gt;</code> template, e.g.: <pre class=\"code\">static_api_ptr_t&lt;someclass&gt; api; api-&gt;dosomething<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>; api-&gt;dosomethingelse<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;</pre>\n<p>\n</span>\n\n</p>\n</li>\n<li class=\"level1\"><span class=\"li\"> Using per-service-type defined static helper functions, e.g. <code>someclass::g_dosomething()</code> - those use relevant service enumeration methods internally.</span>\n</li>\n</ul>\n\n<p>\n An entrypoint service type must use <code>FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT()</code> macro to implement standard entrypoint service behaviors, as opposed to all other service types that use <code>FB2K_MAKE_SERVICE_INTERFACE()</code> macro instead.\n</p>\n\n<p>\nYou can register your own entrypoint service implementations using either <code>service_factory_t</code> or <code>service_factory_single_t</code> template - the difference between the two is that the former instantiates the class on demand, while the latter keeps a single static instance and returns references to it when requested; the latter is faster but usable only for things that have no per-instance member data to maintain. Each <code>service_factory_t</code> / <code>service_factory_single_t</code> instance should be a static variable, such as: &ldquo;<code>static service_factory_t&lt;myclass&gt; g_myclass_factory;</code>&ldquo;.\n</p>\n\n<p>\nCertain service types require custom <code>service_factory</code> helper templates to be used instead of standard <code>service_factory_t</code> / <code>service_factory_single_t</code> templates; see documentation of specific service type for exact info about registering.\n</p>\n\n<p>\nA typical entrypoint service implementation looks like this: \n</p>\n<pre class=\"code\">class myservice_impl : <span class=\"kw2\">public</span> myservice <span class=\"br0\">&#123;</span>\n<span class=\"kw2\">public</span>:\n\t<span class=\"kw4\">void</span> dosomething<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>....<span class=\"br0\">&#125;</span>;\n\t<span class=\"kw4\">void</span> dosomethingelse<span class=\"br0\">&#40;</span><span class=\"kw4\">int</span> meh<span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>...<span class=\"br0\">&#125;</span>;\n<span class=\"br0\">&#125;</span>;\n<span class=\"kw4\">static</span> service_factory_single_t&lt;myservice_impl&gt; g_myservice_impl_factory;</pre>\n</div>\n<!-- SECTION [3411-5882] -->\n<a name=\"service_extensions\"></a><h3> Service extensions </h3>\n<div class=\"level3\">\n\n<p>\n Additional methods can be added to any service type, by declaring a new service type class deriving from service type class you want to extend. For example: \n</p>\n<pre class=\"code\">class myservice : <span class=\"kw2\">public</span> service_base <span class=\"br0\">&#123;</span> <span class=\"kw2\">public</span>: <span class=\"kw2\">virtual</span> <span class=\"kw4\">void</span> dosomething<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>; FB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT<span class=\"br0\">&#40;</span>myservice<span class=\"br0\">&#41;</span>; <span class=\"br0\">&#125;</span>;\nclass myservice_v2 : <span class=\"kw2\">public</span> myservice <span class=\"br0\">&#123;</span> <span class=\"kw2\">public</span>: <span class=\"kw2\">virtual</span> <span class=\"kw4\">void</span> dosomethingelse<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>; FB2K_MAKE_SERVICE_INTERFACE<span class=\"br0\">&#40;</span>myservice_v2, myservice<span class=\"br0\">&#41;</span>; <span class=\"br0\">&#125;</span>;</pre>\n<p>\n In such scenario, to query whether a myservice instance is a <code>myservice_v2</code> and to retrieve <code>myservice_v2</code> pointer, use <code>service_query</code> functionality: \n</p>\n<pre class=\"code\">service_ptr_t&lt;myservice&gt; ptr;\n<span class=\"br0\">&#40;</span>...<span class=\"br0\">&#41;</span>\nservice_ptr_t&lt;myservice_v2&gt; ptr_ex;\n<span class=\"kw1\">if</span> <span class=\"br0\">&#40;</span>ptr-&gt;service_query_t<span class=\"br0\">&#40;</span>ptr_ex<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span> <span class=\"coMULTI\">/* ptr_ex is a valid pointer to myservice_v2 interface of our myservice instance */</span> <span class=\"br0\">&#40;</span>...<span class=\"br0\">&#41;</span> <span class=\"br0\">&#125;</span>\n<span class=\"kw1\">else</span> <span class=\"br0\">&#123;</span><span class=\"coMULTI\">/* this myservice implementation does not implement myservice_v2 */</span> <span class=\"br0\">&#40;</span>...<span class=\"br0\">&#41;</span> <span class=\"br0\">&#125;</span></pre>\n</div>\n<!-- SECTION [5883-6822] -->\n<a name=\"autopointer_template_use\"></a><h3> Autopointer template use </h3>\n<div class=\"level3\">\n\n<p>\n When performing most kinds of service operations, <code>service_ptr_t&lt;T&gt;</code> template should be used rather than working with service pointers directly; it automatically manages reference counter calls, ensuring that the service object is deleted when it is no longer referenced. Additionally, <code>static_api_ptr_t&lt;T&gt;</code> can be used to automatically acquire/release a pointer to single-implementation entrypoint service, such as one of standard APIs like <code>playlist_manager</code>.\n</p>\n\n</div>\n<!-- SECTION [6823-7327] -->\n<a name=\"exception_use\"></a><h3> Exception use </h3>\n<div class=\"level3\">\n\n<p>\n Most of <acronym title=\"Application Programming Interface\">API</acronym> functions use C++ exceptions to signal failure conditions. All used exception classes must derive from <code>std::exception</code> (which <code>pfc::exception</code> is typedef&rsquo;d to); this design allows various instances of code to use single <code>catch()</code> line to get human-readable description of the problem to display.\n</p>\n\n<p>\nAdditionally, special subclasses of exceptions are defined for use in specific conditions, such as <code>exception_io</code> for I/O failures. As a result, you must provide an exception handler whenever you invoke any kind of I/O code that may fail, unless in specific case calling context already handles exceptions (e.g. input implementation code - any exceptions should be forwarded to calling context, since exceptions are a part of input <acronym title=\"Application Programming Interface\">API</acronym>).\n</p>\n\n<p>\nImplementations of global callback services such as <code>playlist_callback</code>, <code>playback_callback</code> or <code>library_callback</code> must not throw unhandled exceptions; behaviors in case they do are undefined (app termination is to be expected).\n</p>\n\n</div>\n<!-- SECTION [7328-8345] -->\n<a name=\"storing_configuration\"></a><h3> Storing configuration </h3>\n<div class=\"level3\">\n\n<p>\n In order to create your entries in the configuration file, you must instantiate some objects that derive from <code>cfg_var</code> class. Those can be either predefined classes (<code>cfg_int</code>, <code>cfg_string</code>, etc) or your own classes implementing relevant methods.\n</p>\n\n<p>\nEach <code>cfg_var</code> instance has a GUID assigned, to identify its configuration file entry. The GUID is passed to its constructor (which implementations must take care of, typically by providing a constructor that takes a GUID and forwards it to <code>cfg_var</code> constructor).\n</p>\n\n<p>\nNote that <code>cfg_var</code> objects can only be instantiated statically (either directly as static objects, or as members of other static objects). Additionally, you can create configuration data objects that can be accessed by other components, by implementing <code>config_object</code> service. Some standard configuration variables can be also accessed using <code>config_object</code> interface.\n</p>\n\n</div>\n<!-- SECTION [8346-9281] -->\n<a name=\"use_of_global_callback_services\"></a><h3> Use of global callback services </h3>\n<div class=\"level3\">\n\n<p>\n Multiple service classes presented by the <acronym title=\"Software Development Kit\">SDK</acronym> allow your component to receive notifications about various events:\n</p>\n<ul>\n<li class=\"level1\"><span class=\"li\"> file_operation_callback - tracking file move/copy/delete operations.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> library_callback - tracking Media Library content changes.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> metadb_io_callback - tracking tag read / write operations altering cached/displayed media information.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> play_callback - tracking playback related events.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> playback_statistics_collector - collecting information about played tracks.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> playlist_callback, playlist_callback_single - tracking playlist changes (the latter tracks only active playlist changes).</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> playback_queue_callback - tracking playback queue changes.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> titleformat_config_callback - tracking changes of title formatting configuration.</span>\n</li>\n<li class=\"level1\"><span class=\"li\"> ui_drop_item_callback - filtering items dropped into the <acronym title=\"User Interface\">UI</acronym>.</span>\n</li>\n</ul>\n\n<p>\nAll of global callbacks operate only within main app thread, allowing easy cooperation with windows <acronym title=\"Graphical User Interface\">GUI</acronym> - for an example, you perform playlist view window repainting directly from your playlist_callback implementation.\n</p>\n\n<p>\nThere are restrictions on things that are legal to call from within global callbacks. For an example, you can&rsquo;t modify playlist from inside a playlist callback, because there are other registered callbacks tracking playlist changes that haven&rsquo;t been notified about the change being currently processed yet.\n</p>\n\n<p>\n<strong>IMPORTANT</strong>: You must not enter modal message loops from inside global callbacks, as those allow <strong>any</strong> unrelated code (queued messages, user input, etc.) to be executed, without being aware that a global callback is being processed. Certain global <acronym title=\"Application Programming Interface\">API</acronym> methods such as metadb_io::load_info_multi or threaded_process::run_modal enter modal loops when called. In other words, calling tag read/write operations from within one of global callbacks is illegal and will lead to issues. Use main_thread_callback service to avoid this problem and delay execution of problematic code.\n</p>\n\n</div>\n<!-- SECTION [9282-11264] -->\n<a name=\"service_class_design_guidelines_advanced\"></a><h2> Service class design guidelines (advanced) </h2>\n<div class=\"level2\">\n\n<p>\n This chapter describes things you should keep on your mind when designing your own service type classes. Since 99% of components will only implement existing service types rather than adding their own cross-DLL-communication protocols, you can probably skip reading this chapter.\n</p>\n\n</div>\n<!-- SECTION [11265-11601] -->\n<a name=\"cross-dll_safety\"></a><h3> Cross-DLL safety </h3>\n<div class=\"level3\">\n\n<p>\n It is important that all function parameters used by virtual methods of services are cross-DLL safe (do not depend on compiler-specific or runtime-specific behaviors, so no unexpected behaviors occur when calling code is built with different compiler/runtime than callee). To achieve this, any classes passed around must be either simple objects with no structure that could possibly vary with different compilers/runtimes (i.e. make sure that any memory blocks are freed on the side that allocated them); easiest way to achieve this is to reduce all complex data objects or classes passed around to interfaces with virtual methods, with implementation details hidden from callee. For an example, use <code>pfc::string_base&amp;</code> as parameter to a function that is meant to return variable-length strings.\n</p>\n\n</div>\n<!-- SECTION [11602-12429] -->\n<a name=\"entrypoint_service_efficiency\"></a><h3> Entrypoint service efficiency </h3>\n<div class=\"level3\">\n\n<p>\n When designing an entrypoint service interface meant to have multiple different implementations, you should consider making it possible for all its implementations to use <code>service_factory_single_t</code> (i.e. no per-instance member data); by e.g. moving functionality that needs multi-instance operation to a separate service type class that is created on-demand by one of entrypoint service methods. For example: \n</p>\n<pre class=\"code\">class myservice : <span class=\"kw2\">public</span> service_base <span class=\"br0\">&#123;</span>\n<span class=\"kw2\">public</span>:\n\t<span class=\"co1\">//this method accesses per-instance member data of the implementation class</span>\n\t<span class=\"kw2\">virtual</span> <span class=\"kw4\">void</span> workerfunction<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">void</span> * p_databuffer,t_size p_buffersize<span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>;\n\t<span class=\"co1\">//this method is used to determine which implementation can be used to process specific data stream.</span>\n\t<span class=\"kw2\">virtual</span> <span class=\"kw4\">bool</span> queryfunction<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">char</span> * p_dataformat<span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>;\n&nbsp;\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT<span class=\"br0\">&#40;</span>myservice<span class=\"br0\">&#41;</span>;\n<span class=\"br0\">&#125;</span>;\n<span class=\"br0\">&#40;</span>...<span class=\"br0\">&#41;</span>\nservice_ptr_t&lt;myservice&gt; findservice<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">char</span> * p_dataformat<span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>\n\tservice_enum_t&lt;myservice&gt; e; service_ptr_t&lt;myservice&gt; ptr;\n\t<span class=\"co1\">//BOTTLENECK, this dynamically instantiates the service for each query.</span>\n\t<span class=\"kw1\">while</span><span class=\"br0\">&#40;</span>e.<span class=\"me1\">next</span><span class=\"br0\">&#40;</span>ptr<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>\n\t\t<span class=\"kw1\">if</span> <span class=\"br0\">&#40;</span>ptr-&gt;queryfunction<span class=\"br0\">&#40;</span>p_dataformat<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> <span class=\"kw1\">return</span> ptr;\n\t<span class=\"br0\">&#125;</span>\n\tthrow exception_io_data<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;\n<span class=\"br0\">&#125;</span></pre>\n<p>\n.. should be changed to:\n</p>\n<pre class=\"code\"><span class=\"co1\">//no longer an entrypoint service - use myservice::instantiate to get an instance instead.</span>\nclass myservice_instance : <span class=\"kw2\">public</span> service_base <span class=\"br0\">&#123;</span>\n<span class=\"kw2\">public</span>:\n\t<span class=\"kw2\">virtual</span> <span class=\"kw4\">void</span> workerfunction<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">void</span> * p_databuffer,t_size p_buffersize<span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>;\n\tFB2K_MAKE_SERVICE_INTERFACE<span class=\"br0\">&#40;</span>myservice_instance,service_base<span class=\"br0\">&#41;</span>;\n<span class=\"br0\">&#125;</span>;\n&nbsp;\nclass myservice : <span class=\"kw2\">public</span> service_base <span class=\"br0\">&#123;</span>\n<span class=\"kw2\">public</span>:\n\t<span class=\"co1\">//this method is used to determine which implementation can be used to process specific data stream.</span>\n\t<span class=\"kw2\">virtual</span> <span class=\"kw4\">bool</span> queryfunction<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">char</span> * p_dataformat<span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>;\n\t<span class=\"kw2\">virtual</span> service_ptr_t&lt;myservice_instance&gt; instantiate<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span> = <span class=\"nu0\">0</span>;\n\tFB2K_MAKE_SERVICE_INTERFACE_ENTRYPOINT<span class=\"br0\">&#40;</span>myservice<span class=\"br0\">&#41;</span>;\n<span class=\"br0\">&#125;</span>;\n&nbsp;\ntemplate&lt;typename t_myservice_instance_impl&gt;\nclass myservice_impl_t : <span class=\"kw2\">public</span> myservice <span class=\"br0\">&#123;</span>\n<span class=\"kw2\">public</span>:\n\t<span class=\"co1\">//implementation of myservice_instance must provide static bool g_queryformatfunction(const char*);</span>\n\t<span class=\"kw4\">bool</span> queryfunction<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">char</span> * p_dataformat<span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span><span class=\"kw1\">return</span> t_myservice_instance_impl::<span class=\"me2\">g_queryfunction</span><span class=\"br0\">&#40;</span>p_dataformat<span class=\"br0\">&#41;</span>;<span class=\"br0\">&#125;</span>\n\tservice_ptr_t&lt;myservice_instance&gt; instantiate<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span><span class=\"kw1\">return</span> <span class=\"kw3\">new</span> service_impl_t&lt;t_myservice_instance_impl&gt;<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;<span class=\"br0\">&#125;</span>\n<span class=\"br0\">&#125;</span>;\n&nbsp;\ntemplate&lt;typename t_myservice_instance_impl&gt; class myservice_factory_t :\n\t<span class=\"kw2\">public</span> service_factory_single_t&lt;myservice_impl_t&lt;t_myservice_instance_impl&gt; &gt; <span class=\"br0\">&#123;</span><span class=\"br0\">&#125;</span>;\n<span class=\"co1\">//usage: static myservice_factory_t&lt;myclass&gt; g_myclass_factory;</span>\n&nbsp;\n<span class=\"br0\">&#40;</span>...<span class=\"br0\">&#41;</span>\n&nbsp;\nservice_ptr_t&lt;myservice_instance&gt; findservice<span class=\"br0\">&#40;</span><span class=\"kw4\">const</span> <span class=\"kw4\">char</span> * p_dataformat<span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>\n\tservice_enum_t&lt;myservice&gt; e; service_ptr_t&lt;myservice&gt; ptr;\n\t<span class=\"co1\">//no more bottleneck, enumerated service does not perform inefficient operations when requesting an instance.</span>\n\t<span class=\"kw1\">while</span><span class=\"br0\">&#40;</span>e.<span class=\"me1\">next</span><span class=\"br0\">&#40;</span>ptr<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> <span class=\"br0\">&#123;</span>\n\t\t<span class=\"co1\">//&quot;inefficient&quot; part is used only once, with implementation that actually supports what we request.</span>\n\t\t<span class=\"kw1\">if</span> <span class=\"br0\">&#40;</span>ptr-&gt;queryfunction<span class=\"br0\">&#40;</span>p_dataformat<span class=\"br0\">&#41;</span><span class=\"br0\">&#41;</span> <span class=\"kw1\">return</span> ptr-&gt;instantiate<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;\n\t<span class=\"br0\">&#125;</span>\n\tthrow exception_io_data<span class=\"br0\">&#40;</span><span class=\"br0\">&#41;</span>;\n<span class=\"br0\">&#125;</span></pre>\n</div>\n<!-- SECTION [12430-] -->\n<!-- cachefile D:\\www\\htdocs\\wiki\\data/_cache/xhtml/5b1d34cdff62204c62a18fe09b122a2e used -->\n</body>\n</html>\n"
  },
  {
    "path": "plugins/foobar09/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by foo_audioscrobbler.rc\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        101\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1001\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/foobar09/tools/append_once.bat",
    "content": "REM %1 - string to append\r\nREM %2 - file to append it to\r\nfind /C /I %1 %2\r\nif not errorlevel 1 goto end\r\n    echo start /WAIT \"\" %1 /SILENT >> %2\r\n:end"
  },
  {
    "path": "plugins/iTunes/ChangeLog.txt",
    "content": "5.0.5.1 (19/11/12)\r\n-------------------------------------------------------------------------------\r\n* Now syncs tracks more often for less spurious double scrobbles (only happened\r\n  if you skipped to the end of a track with 20s)\r\n\r\n5.0.4.1 (20/8/12)\r\n-------------------------------------------------------------------------------\r\n* Now sends album artist as parameter d in scrob sub protocol.\r\n\r\n3.0.1.0 (16/5/08)\r\n-------------------------------------------------------------------------------\r\n* Better error handling.\r\n* Mac: fixed iTunes slowdown (beach balling)\r\n\r\n\r\n3.0.0.13 (13/5/08)\r\n-------------------------------------------------------------------------------\r\n* Fixed double scrobbling of tracks when using iPod classic.\r\n* Updates broken Updater.exe in client if installed.\r\n\r\n\r\n3.0.0.12 (8/5/08)\r\n-------------------------------------------------------------------------------\r\n* Win: fixed random crashes on track changes.\r\n* Win: fixed crash on track start in iTunes 6.\r\n\r\n\r\n3.0.0.10 (6/5/08)\r\n-------------------------------------------------------------------------------\r\n* Mac: fixed crash when upgrading iPod firmware.\r\n\r\n\r\n3.0.0.9 (1/5/08)\r\n-------------------------------------------------------------------------------\r\n* Retrying when we get a playcount diff of 0 from iTunes.\r\n\r\n\r\n3.0.0.8 (29/4/08)\r\n-------------------------------------------------------------------------------\r\n* Fixed crash on track start with iPod scrobbling disabled.\r\n\r\n\r\n3.0.0.5 (19/3/08)\r\n-------------------------------------------------------------------------------\r\n* Fixed crash on CD track change.\r\n* Fixed crash on unmounting Firewire device.\r\n* Don't start iPod scrobbling when a non-iPod USB device is unmounted.\r\n\r\n\r\n3.0.0.4 (17/3/08)\r\n-------------------------------------------------------------------------------\r\n* Repeated tracks now scrobble correctly (Win)\r\n* Fixed bug where a restarted iTunes track would not lead to the scrobble\r\n  timer in the client getting reset (Win)\r\n\r\n\r\n3.0.0.0 (19/2/08)\r\n-------------------------------------------------------------------------------\r\n* Now with iPod scrobbling\r\n\r\n\r\n2.0.13.0 (6/8/07)\r\n-------------------------------------------------------------------------------\r\n* Recompiled with new ScrobSub for Vista compatibility.\r\n* Fixed path retrieval for iTunes 7+\r\n\r\n\r\n2.0.11.0 (3/4/07)\r\n-------------------------------------------------------------------------------\r\n* Fixed crash on shutdown on Vista.\r\n* Fixed GDI memory leak making iTunes GUI sluggish after prolonged use.\r\n* Fixed version reporting.\r\n* Ripped out unnecessary WTL dependency.\r\n\r\n\r\n2.0.9.0 (13/9/06)\r\n-------------------------------------------------------------------------------\r\n* Changed structure around to work with new ScrobSub.\r\n\r\n\r\n2.0.8.0 (22/6/06)\r\n-------------------------------------------------------------------------------\r\n* Changed output name to itw_scrobbler.dll and recompiled with new ScrobSub\r\n  for the beta release of the new Last.fm client.\r\n\r\n\r\n2.0.6.0 (16/5/06)\r\n-------------------------------------------------------------------------------\r\n* Submitting songs from shared playlists now works\r\n\r\n\r\n2.0.4.0 (11/4/06)\r\n-------------------------------------------------------------------------------\r\n* Searching for \"movie\" as well as \"video\" to filter out video files\r\n"
  },
  {
    "path": "plugins/iTunes/IPod.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"IPod.h\"\n#include <sys/stat.h>\n#include <iostream>\n#include <sstream>\n\n#ifndef WIN32\n    #include <dirent.h>\n#endif\n\n#ifndef WIN32\nstd::string escape(std::string const &s)\n#else\nstd::wstring escape(std::wstring const &s)\n#endif\n{\n    std::size_t n = s.length();\n#ifndef WIN32\n    std::string escaped;\n#else\n\tstd::wstring escaped;\n#endif\n    escaped.reserve(n * 2);        // pessimistic preallocation\n    \n    for (std::size_t i = 0; i < n; ++i) {\n        if (s[i] == '\\\\' || s[i] == '\\'')\n            escaped += '\\\\';\n        escaped += s[i];\n    }\n    return escaped;\n}\n\nconst COMMON_STD_STRING \nIPod::twiddlyFlags() const\n{\n    LFM_STRINGSTREAM ss;\n    \n    ss << \"--device \";\n    ss << device();\n    \n    ss << \" --connection \";\n    switch( m_connectionType )\n    {\n        case usb:\n            ss << \"usb\";\n            break;\n            \n        case fireWire:\n            ss << \"fireWire\";\n            break;\n    }\n    \n    ss << \" --pid \" << m_pid;\n    ss << \" --vid \" << m_vid;\n    ss << \" --serial \" << m_serial;\n    ss << \" --name \" << escape( m_displayName );\n    \n    if( m_manualMode )\n        ss << \" --manual\";\n\n    return ss.str();\n}\n\n\nCOMMON_STD_STRING\nIPod::device() const\n{\n    #ifdef WIN32\n        #define _(x) L##x\n    #else\n        #define _(x) x\n    #endif\n\n    switch( m_type )\n    {\n        case iPod:   return _( \"ipod\" );\n        case iTouch: return _( \"itouch\" );\n        case iPhone: return _( \"iphone\" );\n        case iPad:   return _( \"ipad\" );            \n        default:     return _( \"unknown\" );\n    }\n\n    #undef _\n}\n"
  },
  {
    "path": "plugins/iTunes/IPod.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IPOD_H\n#define IPOD_H\n\n#include <string>\n#include <vector>\n#include \"common/c++/logger.h\"\n\n#ifdef WIN32\n    #define LFM_STRINGSTREAM std::wstringstream\n#else\n    #include <IOKit/IOKitLib.h>\n    #include <CoreFoundation/CoreFoundation.h>\n    #define LFM_STRINGSTREAM std::stringstream\n#endif\n\n\n/** @author Jono Cole <jono@last.fm> \n  * @brief stores iPod / iPhone device information\n  */  \n    class IPod\n    {\n        public:\n            const COMMON_STD_STRING twiddlyFlags() const;\n            const COMMON_STD_STRING& serial() const { return m_serial; }\n            COMMON_STD_STRING device() const;\n            const COMMON_STD_STRING& displayName() const { return m_displayName; }\n\n            enum deviceType { unknown = 0,\n                   iPod,\n                   iTouch,\n                   iPhone,\n                   iPad };\n\n            bool isManualMode() const{ return m_manualMode; }\n            bool isMobileScrobblerInstalled() const { return m_mobileScrobblerInstalled; }\n\n            /** populates the m_manualMode bool \n              * NOTE possibly shouldn't be here */\n            void populateIPodManual();\n        \n            #ifdef WIN32\n\n                //Note: It's not ideal that the IPodDetector has to pass the IWbemServices pointer\n                //      to the IPod class but it is necessary in order to make further WMI queries\n                //      in this class. It should be safe however as no IPod instances should exist\n                //      beyond the scope of the IPodDetector instance.\n                static IPod* newFromUsbDevice( struct IWbemClassObject* device, \n                                               struct IWbemServices* wmiServices );\n\n                /** get the serial, pid and vid of a CIM_PnPEntity device\n                  * ( pass NULL to any of the output parameters if not needed ) */\n                static void getSerialVidPid( struct IWbemClassObject* device, \n                                             std::wstring *const serialOut = NULL, \n                                             int *const vidOut = NULL, \n                                             int *const pidOut = NULL );\n\n                /** get the name of the CIM_PnPEntity device */\n                std::wstring getDeviceName( struct IWbemClassObject* const object ) const;\n\n                /** Check if the IPod is older than the timeout value (milliseconds) ) */\n                bool hasTimeoutExpired( DWORD timeoutValue );\n\n            #else //MAC:\n                /** Utility method to get the usb serial number of a io_object_t device\n                  * without having to create an object. */\n                static bool getUsbSerial( io_object_t device, std::string* serialOut );\n                static bool getFireWireSerial( io_object_t device, std::string* serialOut );\n\n                static IPod* newFromUsbDevice( io_object_t device, deviceType type = unknown );\n                static IPod* newFromFireWireDevice( io_object_t device );\n                static io_object_t getBaseDevice( io_object_t device );\n                \n                void setMountPoint( const std::string& mountPoint ){ m_mountPoint = mountPoint; }\n                void setDiskID( const std::string& diskID ){ m_diskID = diskID; }\n                const std::string& diskID() const{ return m_diskID; }\n                void getDisplayName();\n            #endif\n\n        private:\n            IPod(): m_manualMode( false ), m_mobileScrobblerInstalled( false )\n            {}\n        \n            COMMON_STD_STRING m_serial;\n            int m_pid;\n            int m_vid;\n            \n            bool m_manualMode;\n            bool m_mobileScrobblerInstalled;\n\n            enum { fireWire = 0,\n                   usb } m_connectionType;\n\n            deviceType m_type;\n\n            std::string m_mountPoint;\n            COMMON_STD_STRING m_displayName;\n\n            #ifdef WIN32\n                static void tokenize( const std::wstring& str, \n                                      std::vector< std::wstring >& tokens, \n                                      const std::wstring& delimiters = L\" \" );\n\n                DWORD m_connectionTickCount;\n\n                struct IWbemServices* m_wmiServices;\n                \n                /** populates the m_mountPoint string querying using WMI */\n                void populateMountPoint( IWbemClassObject *device );\n                char getDriveLetterFromPnPEntity( IWbemClassObject* device ) const;\n                char getDriveLetterFromDiskDrive( IWbemClassObject* diskDrive ) const;\n                char getDriveLetterFromPartition( IWbemClassObject* partition ) const;\n\n                /** populates the m_manualMode and m_mobileScrobblerInstalled bools */\n                void populateIPhoneMobileScrobblerAndManualMode();\n\n                /** Waits for iPod backup to complete (checking mod time of Info.plist\n                  * or times out after 5 mins.\n                  */\n                void waitForIpodBackup( const std::wstring& backupPath ) const;\n\n                /** Query if mobile scrobbler is installed by iterating through each\n                  * file in the backupPath directory checking for the if it's a \n                  * mobilescrobbler plist file.\n                  */\n                bool queryMobileScrobblerInstalled( const std::wstring& backupPath ) const;\n\n                /** Determines if a file is a backup of a mobilescrobbler plist file by \n                  * searching for the string \"org.c99.MobileScrobbler.plist\". \n                  */\n                bool isMobileScrobblerPlist( const std::wstring& path ) const;\n\n                /** Determines if the iPhone is in manual or automatic mode by\n                  * reading the info.plist file and checking the iTunesPrefs section.\n                  */\n                bool queryIPhoneManual( const std::wstring& infoPlistPath ) const;\n\n            #else //MAC:\n                bool isOldIpod( io_object_t device );\n                bool getDeviceId( io_object_t device, int* vid, int* pid );\n                bool getDeviceFireWireId( io_object_t device, int* vid, int* pid );\n                std::string m_diskID;\n\n                \n                bool isMobileScrobblerPlist( const char* path ) const;\n                bool queryMobileScrobblerInstalled() const;\n                bool queryIPhoneManual() const;\n                bool waitForIpodBackup() const;\n                CFDictionaryRef createDictionaryFromXML( CFStringRef filePath ) const;\n            #endif\n    };\n\n#endif //IPOD_H\n"
  },
  {
    "path": "plugins/iTunes/IPodDetector.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef IPOD_DETECTOR_H\n#define IPOD_DETECTOR_H\n\n#include \"common/c++/logger.h\"\n#include \"Moose.h\"\n#include \"IPod.h\"\n\n#include <string>\n#include <map>\n#include <vector>\n\n#ifdef WIN32\n    #include <windows.h>\n#else\n    #include <IOKit/IOKitLib.h>\n    #include \"pthread.h\"\n\n    #include <CoreServices/CoreServices.h>\n    #include <Carbon/Carbon.h>    \n#endif\n\n\n/** @author Jono Cole <jono@last.fm> \n  * @brief launches twiddly for diffing when an iPod / iPhone is unplugged\n  */\nclass IPodDetector\n{\npublic:\n    IPodDetector();\n    ~IPodDetector();\n\nprivate:\n    // NOTE inline because there is no IPodDetector.cpp\n    void\n    startTwiddlyWithFlag( const COMMON_STD_STRING& args )\n    {\n        if ( !Moose::isTwiddlyRunning() )\n        {\n            Moose::exec( Moose::twiddlyPath(), args );\n        }\n    }\n\n    // NOTE inline because there is no IPodDetector.cpp\n    void \n    startTwiddlyWithIpodSerial( const COMMON_STD_STRING& serial, char* trigger = \"unknown\" )\n    {\n        std::map< COMMON_STD_STRING, IPod*>::iterator it = m_ipodMap.find( serial );\n        if( it != m_ipodMap.end() )\n        {\n            LOG( 3, \"Ipod scrobbling triggered by \" << trigger << \" method.\" );\n            IPod* iPod = it->second;\n            startTwiddlyWithFlag( iPod->twiddlyFlags() );\n            m_ipodMap.erase( serial );\n            delete iPod;\n        }\n    }\n\n    std::map< COMMON_STD_STRING, IPod*> m_ipodMap;\n    \n    void notifyIfUnknownIPod( IPod* ipod );\n\n  #ifdef WIN32\n    void threadMain();\n\n    static unsigned CALLBACK threadEntry( LPVOID lpParam );\n    static LRESULT CALLBACK WindowProc(  HWND hwnd,\n                                         UINT uMsg,\n                                         WPARAM wParam,\n                                         LPARAM lParam\n                                     );\n    \n    static std::map< HWND, IPodDetector* > s_hwndMap;\n    HWND m_deviceDetectionWnd;\n\n    bool initializeWMI();\n    void shutdownWMI();\n\n    /** Check if the device still exists (determined using the serial number and WMI) */\n    bool doesIpodExist( IPod* ipod );\n\n    void checkConnectedDevices();\n\n    bool queryCurrentlyConnectedDevices( struct IEnumWbemClassObject** enumerator );\n    bool queryByDeviceID( const std::string& deviceId, IEnumWbemClassObject** enumerator );\n\n    void runDetectionEventLoop();\n\n    void onDeviceConnected( struct IWbemClassObject* const device );\n    void onDeviceRemoved();\n\n    std::string getDBTDeviceInfo( const LPARAM lparam ) const;\n\n    bool m_shutdown;\n\n    HANDLE m_thread;\n\n    struct IWbemLocator *m_wmiLocator;\n    struct IWbemServices *m_wmiServices;\n\n  #else\n    bool setupDetection();\n\n    /// callbacks\n    static void* threadEntry( void* param );\n    static void onIPadDetected( void*, io_iterator_t newIterator );\n    static void onIPhoneDetected( void*, io_iterator_t newIterator );\n    static void onUsbIPodDetected( void*, io_iterator_t newIterator );\n    static void onDeviceRemoved( void*, io_iterator_t newIterator );\n    static void onFireWireDetected( void*, io_iterator_t newIterator );\n    static void onFireWireRemoved( void*, io_iterator_t newIterator );\n    static void onDeviceNodeAdded( void*, io_iterator_t newIterator );\n    static void onDeviceNodeRemoved( void*, io_iterator_t newIterator );\n    \n    static OSStatus onMountStateChanged(  EventHandlerCallRef handlerCallRef,\n                                          EventRef event,\n                                          void* userData );\n\n    \n    static void onSyncTimerFire( CFRunLoopTimerRef timer, void *info );\n    static void onSyncTimerRelease( const void *info );\n\n    static void onQuit( void* param );\n    \n    void startSyncTimer( class IPod* const ipod );\n    \n    std::string getMountPoint( const std::string& deviceName ) const;\n\n    CFRunLoopSourceRef m_quitSource;\n    \n    pthread_t m_threadId;\n    \n    bool m_detectorStarted;\n    \n    bool m_threadError;\n    \n  #endif\n};\n\n#endif //IPOD_DETECTOR_H\n"
  },
  {
    "path": "plugins/iTunes/IPodDetector_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"iPodDetector.h\"\n#include \"Ipod.h\"\n\n#include \"common/c++/logger.h\"\n#include \"Moose.h\"\n\n#include <IOKit/IOKitLib.h>\n#include <IOKit/storage/IOMedia.h>\n#include <IOKit/storage/IOPartitionScheme.h>\n#include <IOKit/IOBSD.h>\n\n#include <CoreFoundation/CoreFoundation.h>\n#include <CoreServices/CoreServices.h>\n#include <Carbon/Carbon.h>\n\n#include <mach/mach.h>\n#include <mach/error.h>\n\n#include <sys/mount.h>\n\n#include <fstream>\n\nusing namespace std;\n\nstatic const double kTimeOutInterval = 5.0 * 60.0;  // 5 minute timeout before sync is forced\n\n\n/** @author Jono Cole <jono@last.fm> \n  * @brief Used in the callback when the sync timer timesout\n  */  \nstruct SyncTimeoutInfo\n{\n    IPodDetector* iPodDetector;\n    std::string ipodSerial;\n};\n\n\nIPodDetector::IPodDetector()\n             :m_detectorStarted( false ),\n              m_threadError( false )\n              \n{\n    pthread_attr_t attr;\n    pthread_attr_init( &attr );\n    pthread_create( &m_threadId, &attr, threadEntry, this );\n}\n\n\nIPodDetector::~IPodDetector()\n{\n    if( !m_threadError )\n    {\n        CFRunLoopSourceSignal( m_quitSource );\n        CFRunLoopWakeUp( CFRunLoopGetCurrent() );\n    }\n}\n\n\nvoid* //static\nIPodDetector::threadEntry( void* param )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>(param);\n    \n    /* setup native events to give mount / unmount detection\n     * IOKit does not give this information as it is not at\n     * the Hardware level.\n     */\n     \n    EventHandlerUPP handlerUPP;\n    handlerUPP = NewEventHandlerUPP( onMountStateChanged );\n    EventTypeSpec eventTypes[] =\n    {\n        { kEventClassVolume, kEventVolumeMounted },\n        { kEventClassVolume, kEventVolumeUnmounted }\n    };\n\n    OSStatus err = InstallApplicationEventHandler( handlerUPP, 2, eventTypes, param, NULL );\n    //TODO error handling\n\n     \n     \n    /* Set up IOKit to give notifications for hardware events\n     * (USB and Firewire Device plugin / remove )\n     * This is mainly needed to support non-mountable devices\n     * such as the iPhone and iPod Touch. But is also used to\n     * retrieve the USB serial number for all devices. \n     */\n    \n    if( !ipd->setupDetection() )\n    {\n        LOG( 2, \"Error - could not initialize iPod / iPhone detection.\\n\"\n                 \"Devices will not be detected and wont scrobble.\" );\n        ipd->m_threadError = true;\n        return 0;\n    }\n    \n    CFRunLoopSourceContext context = {\n       0,           //version;\n       ipd,         //void *info;\n       NULL,        //CFAllocatorRetainCallBack retain;\n       NULL,        //CFAllocatorReleaseCallBack release;\n       NULL,        //CFAllocatorCopyDescriptionCallBack copyDescription;\n       NULL,        //CFRunLoopEqualCallBack equal;\n       NULL,        //CFRunLoopHashCallBack hash;\n       NULL,        //CFRunLoopScheduleCallBack schedule;\n       NULL,        //CFRunLoopCancelCallBack cancel;\n       onQuit       //CFRunLoopPerformCallBack perform;\n    };\n    ipd->m_quitSource = CFRunLoopSourceCreate( kCFAllocatorDefault, 0, &context );\n    CFRunLoopAddSource( CFRunLoopGetCurrent(), ipd->m_quitSource, kCFRunLoopDefaultMode );\n    \n    ipd->m_detectorStarted = true;\n    CFRunLoopRun();\n    \n    LOG( 3, \"Clearing up iPodMap\" );\n    //clear up memory\n    map< std::string, IPod* >::iterator i;\n    for( i = ipd->m_ipodMap.begin(); i != ipd->m_ipodMap.end(); ipd++ )\n    {\n        delete i->second;\n    }\n    ipd->m_ipodMap.clear();\n    \n    return 0;\n}\n\n\nbool\nIPodDetector::setupDetection()\n{\n    kern_return_t ioResult;\n    \n    IONotificationPortRef notificationObject = IONotificationPortCreate( kIOMasterPortDefault );\n    \n    CFRunLoopSourceRef notificationRunLoopSource;\n\n    //Use the notification object received from IONotificationPortCreate\n    notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationObject);\n                \n    //Add the notification object to the event loop\n    CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);\n    \n    //Dictionary for matching iPhone / iPod connections\n    CFMutableDictionaryRef iPadConnectMatch = IOServiceNameMatching( \"iPad\" ); \n    CFMutableDictionaryRef iPhoneConnectMatch = IOServiceNameMatching( \"iPhone\" ); \n    CFMutableDictionaryRef iPodConnectMatch = IOServiceNameMatching( \"iPod\" ); \n    CFMutableDictionaryRef iPodMiniConnectMatch = IOServiceNameMatching( \"iPod mini\" ); \n        \n    //Dictionaries for matching iPhone / iPod disconnections\n    CFMutableDictionaryRef iPadDisconnectMatch = IOServiceNameMatching( \"iPad\" ); \n    CFMutableDictionaryRef iPhoneDisconnectMatch = IOServiceNameMatching( \"iPhone\" ); \n    CFMutableDictionaryRef iPodDisconnectMatch = IOServiceNameMatching( \"iPod\" ); \n    CFMutableDictionaryRef iPodMiniDisconnectMatch = IOServiceNameMatching( \"iPod mini\" );\n    \n    //Dictionaries for matching Firewire devices\n    CFMutableDictionaryRef fireWireConnectMatch = IOServiceMatching( \"IOFireWireSBP2LUN\" );\n    CFMutableDictionaryRef fireWireDisconnectMatch = IOServiceMatching( \"IOFireWireSBP2LUN\" );\n    \n    //Dictionaries for mount and unmount\n    CFMutableDictionaryRef deviceNodeAddedMatch = IOServiceMatching( \"IOMedia\" );\n    CFMutableDictionaryRef deviceNodeRemovedMatch = IOServiceMatching( \"IOMedia\" );\n    \n    //These iterators will be used to check the current state of already\n    //plugged in devices before the notifications start coming in.\n    io_iterator_t iPadAddedIter;\n    io_iterator_t iPadRemovedIter;\n    io_iterator_t iPhoneAddedIter;\n    io_iterator_t iPhoneRemovedIter;\n    io_iterator_t iPodAddedIter;\n    io_iterator_t iPodRemovedIter;\n    io_iterator_t iPodMiniAddedIter;\n    io_iterator_t iPodMiniRemovedIter;\n    io_iterator_t fireWireAddedIter;\n    io_iterator_t fireWireRemovedIter;\n    io_iterator_t deviceNodeAddedIter;\n    io_iterator_t deviceNodeRemovedIter;\n            \n    //Add the notifications for connected / disconnected\n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 iPadConnectMatch, \n                                                 onIPadDetected, \n                                                 this, \n                                                 &iPadAddedIter );\n\n    \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPad connected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 iPhoneConnectMatch, \n                                                 onIPhoneDetected, \n                                                 this, \n                                                 &iPhoneAddedIter );\n\n    \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPhone connected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 iPodConnectMatch, \n                                                 onUsbIPodDetected, \n                                                 this, \n                                                 &iPodAddedIter );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPod connected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 iPodMiniConnectMatch, \n                                                 onUsbIPodDetected, \n                                                 this, \n                                                 &iPodMiniAddedIter );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPod Mini connected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n                                          \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 fireWireConnectMatch, \n                                                 onFireWireDetected, \n                                                 this, \n                                                 &fireWireAddedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add firewire connected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 iPadDisconnectMatch, \n                                                 onDeviceRemoved, \n                                                 this, \n                                                 &iPadRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPhone disconnected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n     \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 iPhoneDisconnectMatch, \n                                                 onDeviceRemoved, \n                                                 this, \n                                                 &iPhoneRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPhone disconnected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n                                      \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 iPodDisconnectMatch, \n                                                 onDeviceRemoved, \n                                                 this, \n                                                 &iPodRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPod disconnected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n                                      \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 iPodMiniDisconnectMatch, \n                                                 onDeviceRemoved, \n                                                 this, \n                                                 &iPodMiniRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPod Mini disconnected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n                                       \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 fireWireDisconnectMatch, \n                                                 onFireWireRemoved, \n                                                 this, \n                                                 &fireWireRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add iPod Mini disconnected notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n                                           \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOMatchedNotification,\n                                                 deviceNodeAddedMatch, \n                                                 onDeviceNodeAdded, \n                                                 this, \n                                                 &deviceNodeAddedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add device mount notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }        \n                                       \n    ioResult = IOServiceAddMatchingNotification( notificationObject, \n                                                 kIOTerminatedNotification,\n                                                 deviceNodeRemovedMatch, \n                                                 onDeviceNodeRemoved, \n                                                 this, \n                                                 &deviceNodeRemovedIter );\n                                                 \n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not add device unmount notification: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    // Check if there are any devices already plugged in / disconnected\n    // and 'arm' the notification mechanism\n    onIPhoneDetected( this, iPhoneAddedIter );\n    onIPadDetected( this, iPadAddedIter );\n    onUsbIPodDetected( this, iPodAddedIter );\n    onUsbIPodDetected( this, iPodMiniAddedIter );\n    onFireWireDetected( this, fireWireAddedIter );\n    onDeviceRemoved( this, iPhoneRemovedIter );\n    onDeviceRemoved( this, iPadRemovedIter );\n    onDeviceRemoved( this, iPodRemovedIter );\n    onDeviceRemoved( this, iPodMiniRemovedIter );\n    onFireWireRemoved( this, fireWireRemovedIter );\n    onDeviceNodeAdded( this, deviceNodeAddedIter );\n    onDeviceNodeRemoved( this, deviceNodeRemovedIter );\n    \n    return true;\n}\n\n\nvoid //static\nIPodDetector::onUsbIPodDetected( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( param );\n    io_object_t ioUsbDeviceNub;\n    \n    while( ioUsbDeviceNub = IOIteratorNext( newIterator ) )\n    {\n        IPod* iPod = IPod::newFromUsbDevice( ioUsbDeviceNub );\n        if( iPod )\n        {\n            ipd->notifyIfUnknownIPod( iPod );\n\n            if( iPod->isMobileScrobblerInstalled() )\n            {\n                LOG( 3, \"Mobile Scrobbler detected on iPod Touch - client scrobbling not needed.\" );\n                delete iPod;\n                IOObjectRelease( ioUsbDeviceNub );\n                continue;\n            }\n            \n            ipd->m_ipodMap[ iPod->serial() ] = iPod;\n            \n            if( iPod->isManualMode() )\n            {\n                LOG( 3, \"iPod detected in manual mode.\" );\n                ipd->startTwiddlyWithIpodSerial( iPod->serial() );\n            }\n            else\n            {\n                //Either the iPod is in automatic mode OR it's an old iPod\n                LOG( 3, \"iPod detected\" );\n                ipd->startSyncTimer( iPod );    \n            }\n        }\n        \n        IOObjectRelease( ioUsbDeviceNub );\n    }\n}\n\n\nvoid //static\nIPodDetector::onIPadDetected( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( param );\n    io_object_t ioUsbDeviceNub;\n    \n    while( ioUsbDeviceNub = IOIteratorNext( newIterator ) )\n    {\n        \n        IPod* iPod = IPod::newFromUsbDevice( ioUsbDeviceNub, IPod::iPad );\n        \n        if( iPod )\n        {\n            ipd->notifyIfUnknownIPod( iPod );\n            \n            if( iPod->isMobileScrobblerInstalled() )\n            {  \n                LOG( 3, \"Mobile Scrobbler detected on iPad - client scrobbling not needed.\" );\n                delete iPod;\n                IOObjectRelease( ioUsbDeviceNub );\n                continue;\n            }\n            \n            ipd->m_ipodMap[ iPod->serial() ] = iPod;\n            \n            if( iPod->isManualMode() )\n            {\n                LOG( 3, \"iPad detected in manual mode\" );\n                ipd->startTwiddlyWithIpodSerial( iPod->serial(), \"manualMode\" );\n            }\n            else\n            {\n                LOG( 3, \"iPad detected in automatic mode\" );\n                ipd->startSyncTimer( iPod );  \n            }\n        }\n        IOObjectRelease( ioUsbDeviceNub );\n    }\n}\n\n\nvoid //static\nIPodDetector::onIPhoneDetected( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( param );\n    io_object_t ioUsbDeviceNub;\n    \n    while( ioUsbDeviceNub = IOIteratorNext( newIterator ) )\n    {\n\n        IPod* iPod = IPod::newFromUsbDevice( ioUsbDeviceNub, IPod::iPhone );\n        \n        if( iPod )\n        {\n            ipd->notifyIfUnknownIPod( iPod );\n\n            if( iPod->isMobileScrobblerInstalled() )\n            {  \n                LOG( 3, \"Mobile Scrobbler detected on iPhone - client scrobbling not needed.\" );\n                delete iPod;\n                IOObjectRelease( ioUsbDeviceNub );\n                continue;\n            }\n\n            ipd->m_ipodMap[ iPod->serial() ] = iPod;\n            \n            if( iPod->isManualMode() )\n            {\n                LOG( 3, \"iPhone detected in manual mode\" );\n                ipd->startTwiddlyWithIpodSerial( iPod->serial(), \"manualMode\" );\n            }\n            else\n            {\n                LOG( 3, \"iPhone detected in automatic mode\" );\n                ipd->startSyncTimer( iPod );  \n            }\n        }\n        IOObjectRelease( ioUsbDeviceNub );\n    }\n}\n\n\nvoid //static\nIPodDetector::onDeviceRemoved( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( param );\n    io_object_t deviceInfo;\n    while( deviceInfo = IOIteratorNext( newIterator ) )\n    {\n        std::string serial;\n        IPod::getUsbSerial( deviceInfo, &serial );\n\n        ipd->startTwiddlyWithIpodSerial( serial, \"unplug\" );\n\n        IOObjectRelease( deviceInfo );\n    }\n}\n\n\nvoid //static\nIPodDetector::onFireWireDetected( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( param );\n    io_object_t ioFireWireDeviceNub;\n    kern_return_t ioResult;\n    while( ioFireWireDeviceNub = IOIteratorNext( newIterator ) )\n    {\n        CFMutableDictionaryRef propertyDictionary;\n        ioResult = IORegistryEntryCreateCFProperties( (io_registry_entry_t)ioFireWireDeviceNub, \n                                               &propertyDictionary, \n                                               kCFAllocatorDefault, \n                                               0 );\n\n        if( ioResult != kIOReturnSuccess )\n        {\n            LOG( 3, \"Could not get firewire device properties: \" << mach_error_string( ioResult ) );\n            IOObjectRelease( ioFireWireDeviceNub );\n            continue;\n        }\n        \n        CFStringRef cfProductName;\n        cfProductName = (CFStringRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"FireWire Product Name\" ) );\n        \n        if( CFStringCompare( cfProductName, CFSTR( \"iPod\" ), 0 ) == kCFCompareEqualTo )\n        {\n            //This firewire device is an iPod!\n            \n            IPod* iPod = IPod::newFromFireWireDevice( ioFireWireDeviceNub );\n            \n            if( iPod )\n            {\n                ipd->notifyIfUnknownIPod( iPod );\n\n                LOG( 3, \"FireWire iPod plugged in\" );\n                ipd->m_ipodMap[ iPod->serial() ] = iPod;\n                ipd->startSyncTimer( iPod );\n            }\n        }\n        \n        IOObjectRelease( ioFireWireDeviceNub );\n    }\n}\n\n\nvoid //static\nIPodDetector::onFireWireRemoved( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast< IPodDetector* >( param );\n    io_object_t ioFireWireDeviceNub;\n    while( ioFireWireDeviceNub = IOIteratorNext( newIterator ) )\n    {\n        std::string serial;\n        IPod::getFireWireSerial( ioFireWireDeviceNub, &serial );\n\n        ipd->startTwiddlyWithIpodSerial( serial, \"unplug\" );\n\n        IOObjectRelease( ioFireWireDeviceNub );\n    }\n}\n\n\nvoid //static \nIPodDetector::onDeviceNodeAdded( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast< IPodDetector* >( param );\n    io_object_t device;\n    \n    while( device = IOIteratorNext( newIterator ) )\n    {\n        CFBooleanRef isWhole = (CFBooleanRef)IORegistryEntryCreateCFProperty( device,\n                                                                              CFSTR( kIOMediaWholeKey ),\n                                                                              kCFAllocatorDefault,\n                                                                              0 );\n        \n        if( isWhole )\n        {\n            if( CFBooleanGetValue( isWhole ) )\n            {\n                IOObjectRelease( device );\n                continue;\n            } \n        }\n\n        /* //TODO: try and use the following to determine the device name\n        CFStringRef cfBsdName = (CFStringRef)IORegistryEntryCreateCFProperty( device,\n                                                                              CFSTR( kIOBSDNameKey ),\n                                                                              kCFAllocatorDefault,\n                                                                              0 ); */\n                                                                              \n        CFNumberRef cfBsdUnit = (CFNumberRef)IORegistryEntryCreateCFProperty( device,\n                                                                              CFSTR( kIOBSDUnitKey ),\n                                                                              kCFAllocatorDefault,\n                                                                              0 );\n                                                                              \n        CFNumberRef cfPartId  = (CFNumberRef)IORegistryEntryCreateCFProperty( device,\n                                                                              CFSTR( kIOMediaPartitionIDKey ),\n                                                                              kCFAllocatorDefault,\n                                                                              0 );\n        \n        int bsdUnit, partitionId;\n        CFNumberGetValue( cfBsdUnit, kCFNumberIntType, &bsdUnit );\n        CFNumberGetValue( cfPartId, kCFNumberIntType, &partitionId );\n        \n        CFRelease( cfBsdUnit );\n        CFRelease( cfPartId );\n        \n        std::stringstream deviceDev;\n        deviceDev << \"disk\" << bsdUnit << \"s\" << partitionId;\n\n        std::string serialNo;\n        if( !IPod::getUsbSerial( device, &serialNo ) )\n        {\n            io_name_t className;\n            IOObjectGetClass( device, className );\n            LOG( 3, \"Could not get serial - className: \" << className );\n        }\n\n        if( ipd->m_ipodMap.find( serialNo ) == ipd->m_ipodMap.end() )\n        {\n            LOG( 3, \"Error: something's gone wrong - cannot find iPod in the map\" );\n            IOObjectRelease( device );\n            continue;\n        }\n        \n        IPod* ipod = ipd->m_ipodMap[ serialNo ];\n                    \n        if( ipd->m_detectorStarted )\n        {\n            /* Store the deviceID in the iPod object so that we can \n             * match it up with a mount point when it is mounted.\n             */\n             ipod->setDiskID( deviceDev.str() );\n        }\n        else\n        {\n            /* The media can only be guarunteed to be mounted by the operating system\n             * if the device was connected before iTunes started.\n             * (ie the detector has NOT started yet.)\n             */\n            std::string mountPoint = ipd->getMountPoint( deviceDev.str() );\n            ipod->setMountPoint( mountPoint );\n            ipod->populateIPodManual();\n            if( ipod->isManualMode() )\n            {\n                ipd->startTwiddlyWithIpodSerial( ipod->serial(), \"manual\" );\n            }\n        }\n        IOObjectRelease( device );\n    }\n}\n\n\nstd::string \nIPodDetector::getMountPoint( const std::string& deviceName ) const\n{\n    LOG( 3, deviceName << \" scanned.\" );\n    std::string devPath = \"/dev/\";\n    devPath += deviceName;\n \n    int mountCount = getfsstat( NULL, 0, MNT_WAIT );\n    \n    struct statfs * mountInfo = new struct statfs[ mountCount ];\n    \n    sleep( 1 );\n    \n    int result = getfsstat( mountInfo, sizeof( struct statfs ) * mountCount, MNT_WAIT );\n    if ( result < 0 )\n    {\n        LOG( 3, \"getfsstat error: \" << result );\n        return \"\";\n    }\n    \n    std::string mountPoint = \"\";\n    \n    for( int i = 0; i < mountCount; i++ )\n    {\n        if( strncmp( devPath.c_str(), mountInfo[i].f_mntfromname, devPath.length() ) == 0 )\n        {\n            mountPoint = mountInfo[i].f_mntonname;\n            break;\n        }\n    }\n    \n    delete[] mountInfo;\n    return mountPoint;\n}\n\n\nvoid //static \nIPodDetector::onDeviceNodeRemoved( void* param, io_iterator_t newIterator )\n{\n    IPodDetector* ipd = static_cast< IPodDetector* >( param );\n    io_object_t device;\n    while( device = IOIteratorNext( newIterator ) )\n    {\n        kern_return_t ioResult;\n\n        CFBooleanRef isLeaf = (CFBooleanRef)IORegistryEntryCreateCFProperty( device, \n                                                                             CFSTR( kIOMediaLeafKey ), \n                                                                             kCFAllocatorDefault, \n                                                                             0 );\n\n        if( isLeaf )\n        {\n            if( CFBooleanGetValue( isLeaf ) )\n            {\n                LOG( 3, \"Leaf node removal ignored\" );\n                IOObjectRelease( device );\n                continue;\n            }\n        }\n        \n        io_iterator_t iter;\n        ioResult = IORegistryEntryCreateIterator( device, \n                                                  kIOServicePlane, \n                                                  kIORegistryIterateParents | kIORegistryIterateRecursively, \n                                                  &iter);\n        if( ioResult != kIOReturnSuccess )\n        {\n            LOG( 3, \"Could not create iterator to iterate over unmounted device\" << mach_error_string( ioResult ) );\n        }\n        \n        LOG( 3, \"determining ipod unmount details\" );\n        io_object_t curParent;\n        while( curParent = IOIteratorNext( iter ) )\n        {\n            io_name_t deviceName;\n            ioResult = IORegistryEntryGetName( curParent, deviceName );\n            if( ioResult != kIOReturnSuccess )\n            {\n                LOG( 3, \"Could not get unmount parent's name/class: \" << mach_error_string( ioResult ) );\n                IOObjectRelease( curParent );\n                continue;\n            }\n            \n            if( strncmp( deviceName, \"iPod\", 4 ) == 0 ||\n                strncmp( deviceName, \"iPod mini\", 9 ) == 0 )\n            {\n                LOG( 3, \"iPod has been unmounted\" );\n                std::string serial;\n                if( !IPod::getUsbSerial( curParent, &serial ) )\n                {\n                    LOG( 3, \"Error: could not determine serial number of iPod from unmount event\" );\n                    IOObjectRelease( curParent );\n                    continue;\n                }\n                ipd->startTwiddlyWithIpodSerial( serial, \"unmount\" );\n            }\n            if( strncmp( deviceName, \"IOFireWireSBP2LUN\", 17 ) == 0 )\n            {\n                LOG( 3, \"iPod has been unmounted\" );\n                std::string serial;\n                if( !IPod::getFireWireSerial( curParent, &serial ) )\n                {\n                    LOG( 3, \"Error: could not determine serial number of iPod from unmount event\" );\n                    IOObjectRelease( curParent );\n                    continue;\n                }\n                ipd->startTwiddlyWithIpodSerial( serial, \"unmount\" );\n            }\n            IOObjectRelease( curParent );\n        }\n            \n        IOObjectRelease( device );\n    }\n}\n\n\nOSStatus //Static\nIPodDetector::onMountStateChanged(  EventHandlerCallRef handlerCallRef,\n                                    EventRef event,\n                                    void* userData )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>( userData );\n    unsigned int eventKind = GetEventKind( event );\n    unsigned int eventClass = GetEventClass( event );\n    \n    switch( eventClass )\n    {\n        case kEventClassVolume:\n        {\n            switch( eventKind )\n            {\n                case kEventVolumeMounted:\n                {\n                    FSVolumeRefNum volNum = 0;\n                    OSStatus result = GetEventParameter( event, kEventParamDirectObject, typeFSVolumeRefNum,\n                                       NULL, sizeof( volNum ), NULL, &volNum );\n                    if( result != noErr )\n                    {\n                        //This has been known to be caused by iPod firmware update / restore\n                        LOG( 3, \"Could not get event parameters. This mount will be ignored\" );\n                        break;\n                    }\n                    \n                    CFStringRef cfDiskID = NULL;\n                    result = FSCopyDiskIDForVolume( volNum, &cfDiskID );\n                    \n                    if( result != noErr )\n                    {\n                        LOG( 3, \"Could not get diskID from mounted volume. This mount will be ignored\" );\n                        break;\n                    }\n                    \n                    char diskID[255];\n                    CFStringGetCString( cfDiskID, diskID, sizeof( diskID ), kCFStringEncodingASCII );\n                    CFRelease( cfDiskID );\n                    \n                    LOG( 3, \"mounted Volume location = /dev/\" << diskID );\n\n                \n                    std::string volumePath = ipd->getMountPoint( diskID );\n                    \n                    LOG( 3, \"Volume mounted at location: \" << volumePath );\n                    \n                    std::map< std::string, IPod* >::iterator mapIter;\n                    for( mapIter = ipd->m_ipodMap.begin(); \n                         mapIter != ipd->m_ipodMap.end(); )\n                    {\n                        IPod* curIpod = mapIter->second;\n                        const std::string& curDiskID = curIpod->diskID();\n                        \n                        mapIter++;\n                        \n                        if( strncmp( curDiskID.c_str(), diskID, curDiskID.length() ) != 0 )\n                            continue;\n\n                        curIpod->setMountPoint( volumePath );\n                        curIpod->populateIPodManual();\n\n                        if( curIpod->isManualMode() )\n                        {\n                            LOG( 3, \"iPod detected in manual sync mode.\" );\n                            ipd->startTwiddlyWithIpodSerial( curIpod->serial(), \"manual\" );\n                        }\n                        else\n                        {\n                            LOG( 3, \"iPod detected in automatic sync mode.\" );\n                        }\n                        \n                    }\n                }\n                break;\n                case kEventVolumeUnmounted:\n                {\n                    LOG( 3, \"kEventVolumeUnmounted event received.\" );\n                }\n                break;\n            }\n        }\n        break;\n        default:\n        assert( !\"Unexpected event received from the carbon event system.\" );\n    }\n    return noErr;\n}\n\n\nvoid \nIPodDetector::startSyncTimer( IPod* const ipod )\n{\n    CFRunLoopTimerRef timer;\n    \n    SyncTimeoutInfo* info = new SyncTimeoutInfo();\n    info->iPodDetector = this;\n    info->ipodSerial = ipod->serial();\n    \n    CFRunLoopTimerContext context = {\n                0,                              //version (must be 0)\n                info,                           //parameter to pass to callback\n                NULL,                           //retain callback\n                onSyncTimerRelease,             //release callback\n                NULL                            //copy description callback\n    };\n    \n    timer = CFRunLoopTimerCreate (\n                kCFAllocatorDefault,                              //Allocator\n                CFAbsoluteTimeGetCurrent () + kTimeOutInterval,   //fireDate\n                0,                                                //interval 0 == one-shot timer\n                0,                                                //flags (for future compatibility)\n                0,                                                //order (currently ignored by runloops?!)\n                onSyncTimerFire,                                  //callback method\n                &context                                          //context information\n    );\n    CFRunLoopAddTimer( CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode );\n    CFRunLoopWakeUp( CFRunLoopGetCurrent() );   \n}\n\nvoid //static\nIPodDetector::onSyncTimerFire(  CFRunLoopTimerRef timer, void *info )\n{\n    SyncTimeoutInfo* timeoutInfo = static_cast<SyncTimeoutInfo*>( info );\n    timeoutInfo->iPodDetector->startTwiddlyWithIpodSerial( timeoutInfo->ipodSerial, \"timeout\" );\n}\n\n\nvoid //static\nIPodDetector::onSyncTimerRelease( const void *info )\n{\n    const SyncTimeoutInfo* timeoutInfo = static_cast<const SyncTimeoutInfo*>( info );\n    delete timeoutInfo;\n}\n\n\nvoid //static\nIPodDetector::onQuit( void* param )\n{\n    IPodDetector* ipd = static_cast< IPodDetector* >( param );\n    CFRunLoopStop( CFRunLoopGetCurrent() );\n    pthread_join(  ipd->m_threadId, NULL );\n}\n\n\nvoid\nIPodDetector::notifyIfUnknownIPod( IPod* ipod )\n{\n    // Qt unexpectedly separates with '.'\n    std::string tmp = \"device.\" + ipod->device() + '.' + ipod->serial() + \".user\";\n    CFStringRef key = CFStringCreateWithBytes( NULL,\n                                              (const unsigned char*) tmp.c_str(),\n                                               tmp.length(),\n                                               kCFStringEncodingUTF8,\n                                               false );\n    if (!key)\n        return;\n\n    CFStringRef appId = CFSTR( \"fm.last\" );\n    CFStringRef user = (CFStringRef) CFPreferencesCopyAppValue( key, appId );\n\n    std::vector<std::string> args;\n    args.push_back( \"--tray\" );\n    if (user == NULL)\n    {\n        CFPreferencesSetAppValue( key, CFSTR( \"\" ), appId );\n        CFPreferencesAppSynchronize( appId );\n        args.push_back( \"--new-ipod-detected\" );\n    } else {\n        CFRelease( user );\n        args.push_back( \"--ipod-detected\" );\n    }\n    \n    args.push_back( ipod->displayName() );\n    \n    Moose::launchAudioscrobbler( args );\n    \n    CFRelease( key );\n}\n"
  },
  {
    "path": "plugins/iTunes/IPodDetector_win.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"iPodDetector.h\"\n#include \"common/c++/Logger.h\"\n#include \"Moose.h\"\n#include \"IPod.h\"\n#include <cassert>\n\n#include <process.h> // for beginthreadex\n#include <iostream>\n#include <sstream>\n\n#include <Windows.h>\n#include <Dbt.h>\n#include <SetupAPI.h>\n\n#include <comdef.h>\n#include <Wbemidl.h>\n\nusing namespace std;\n\nstd::map< HWND, IPodDetector* > IPodDetector::s_hwndMap;\n\nstatic const DWORD kTimeOutInterval = 5 * 60 * 1000;  // 5 minute timeout before sync is forced\n\n//The following strings are used in the notification query\n#define IPHONE_ITOUCH_NAME \"Apple Mobile Device USB Driver\"\n#define IPOD_NAME \"USB Mass Storage Device\"\n#define IPOD_NANO_NAME \"Apple iPod USB Driver\"\n#define IPOD_FIREWIRE_NAME \"Apple Computer_ Inc. iPod IEEE 1394 SBP2 Device\"\n\n#define VID_STRING \"%VID_05AC%\"\n#define LONG_VID_STRING \"%APPLE_COMPUTER__INC%\"\n\n\nIPodDetector::IPodDetector()\n             :m_shutdown( false ),\n              m_wmiLocator( NULL ),\n              m_wmiServices( NULL )\n{\n    unsigned int threadId;\n    m_thread = (HANDLE)_beginthreadex( NULL,\n                                       0,\n                                       IPodDetector::threadEntry,\n                                       this,\n                                       0,\n                                       &threadId );\n\n    LOG( 3, \"Starting iPod detection\" );\n}\n\n\nIPodDetector::~IPodDetector()\n{\n    m_shutdown = true;\n\n    //Wake up the event loop\n    ::SendMessage( m_deviceDetectionWnd, WM_NULL, 0, 0 );\n    \n    DWORD threadResult = WaitForSingleObject( m_thread, 5000 );\n    if( threadResult == WAIT_TIMEOUT )\n        LOGL( 3, \"Error: the IPodDetector shutdown code failed to complete after 5 seconds.\" );\n}\n\n\nunsigned CALLBACK //static\nIPodDetector::threadEntry( LPVOID lpParam )\n{\n    IPodDetector* ipd = static_cast<IPodDetector*>(lpParam);\n    ipd->threadMain();\n    return 0;\n}\n\n\nvoid\nIPodDetector::threadMain()\n{\n    if( !initializeWMI() )\n    {\n        return;\n    }\n\n    checkConnectedDevices();\n\n    runDetectionEventLoop();\n       \n    LOGL( 3, \"Cleaning up iPod Detector\" );\n   \n    shutdownWMI();\n\n    return;\n\t\n}\n\n\nvoid \nIPodDetector::runDetectionEventLoop()\n{\n    WNDCLASSEX wndClass;\n    wndClass.cbSize = sizeof( wndClass );\n    wndClass.style = NULL;\n    wndClass.lpfnWndProc = IPodDetector::WindowProc;\n    wndClass.cbClsExtra = 0;\n    wndClass.cbWndExtra = 0;\n    wndClass.hInstance = GetModuleHandle(NULL);\n    wndClass.hIcon = NULL;\n    wndClass.hCursor = NULL;\n    wndClass.hbrBackground = NULL;\n    wndClass.lpszMenuName = \"\";\n    wndClass.lpszClassName = \"DeviceDetectionClass\";\n    wndClass.hIconSm = NULL;\n\n    ATOM regClassResult = RegisterClassEx( &wndClass );\n    \n    m_deviceDetectionWnd = CreateWindow(  \"DeviceDetectionClass\",\n                                          \"DeviceDetectionWindow\",\n                                          NULL,\n                                          0,\n                                          0,\n                                          0,\n                                          0,\n                                          NULL,\n                                          NULL,\n                                          NULL,\n                                          NULL);\n\n\n    s_hwndMap[ m_deviceDetectionWnd ] = this;\n\n\n    DEV_BROADCAST_DEVICEINTERFACE filter;\n    ZeroMemory( &filter, sizeof( filter ) );\n    filter.dbcc_size = sizeof( filter );\n    filter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;\n\n    HDEVNOTIFY deviceNotifierHandle = RegisterDeviceNotification(\n        m_deviceDetectionWnd,\n        reinterpret_cast<void*>( &filter ),\n        DEVICE_NOTIFY_WINDOW_HANDLE |\n        // This next parameter causes notifications to be sent for all devices,\n        // regardless of the dbcc_classguid member of filter. However, it's not\n        // supported by Win 98/2000 so better use a sensible class anyway.\n        0x00000004 /* == DEVICE_NOTIFY_ALL_INTERFACE_CLASSES argh! */ );\n\n    if( !deviceNotifierHandle )\n         LOG( 3, \"RegisterDeviceNotification Error: \" << GetLastError() );\n\n\n    BOOL messageVal = 1;    //initialize to non-zero value\n    MSG message;\n    while( messageVal != 0 && !m_shutdown )\n    {\n        if( PeekMessage( &message, m_deviceDetectionWnd, 0, 0, PM_REMOVE ) > 0 )\n        {\n            if( messageVal == -1 )\n            {\n                LOGL( 3, \"GetMessage error: \" << GetLastError() );\n            }\n            else\n            {\n                TranslateMessage( &message );\n                DispatchMessage( &message );\n            }\n        }\n\n        Sleep( 100 ); //Think of the poor CPU cycles\n        \n        if( m_ipodMap.empty() )\n            continue;\n\n        //Check to see if any of the connected iPods have timedout\n        std::map< std::wstring, IPod* >::iterator iter;\n        for( iter = m_ipodMap.begin(); iter != m_ipodMap.end(); )\n        {\n            IPod* ipod = iter->second;\n\n            /* This looks wierd but we must increment the pointer before the\n             * startTwiddlyWithIpodSerial method erases the ipod and invalidates\n             * the previous pointer (Norman will tell you all about this) */\n            ++iter;\n            if( ipod->hasTimeoutExpired( kTimeOutInterval ) )\n            {\n                startTwiddlyWithIpodSerial( ipod->serial(), \"timeout\" );\n            }\n        }\n    }\n\n}\n\n\nLRESULT CALLBACK  //static\nIPodDetector::WindowProc(  HWND hwnd,\n                           UINT uMsg,\n                           WPARAM wParam,\n                           LPARAM lParam\n                         )\n{\n    IPodDetector* ipd = s_hwndMap[ hwnd ];\n\n    switch( uMsg )\n    {\n        case WM_DEVICECHANGE:\n        {\n            HRESULT result = PostMessage( hwnd, WM_USER, wParam, lParam );\n            if( FAILED( result ) )\n                LOGL( 3, \"error: PostMessage WM_USER failed: \" << ::GetLastError() )\n\n        }\n        break;\n\n        case WM_USER:\n            switch( wParam )\n            {\n                case DBT_DEVICEARRIVAL:\n                {\n                    std::string deviceId = ipd->getDBTDeviceInfo( lParam );\n                    LOGL( 3, \"Device arrived - id: \" << deviceId )\n                    IEnumWbemClassObject* enumerator;\n                    ipd->queryByDeviceID( deviceId, &enumerator );\n                    \n                    IWbemClassObject* object;\n                    ULONG retCount;\n\n                    int count = 0;\n                    while( enumerator )\n                    {\n                        enumerator->Next( WBEM_INFINITE,\n                                          1,\n                                          &object,\n                                          &retCount );\n\n                        if( 0 == retCount )\n                            break;\n\n                        ipd->onDeviceConnected( object );\n                        object->Release();\n                        count++;\n                    }\n                    if( count > 0 )\n                    {\n                        LOGL( 3, count << \" ipods found with this deviceId\" );\n                    }\n                    else\n                    {\n                        LOGL( 3, \"no ipods found with this deviceid - presumeably a non-ipod has been plugged in!\" )\n                    }\n                    enumerator->Release();\n                }\n                break;\n\n                case DBT_DEVICEREMOVECOMPLETE:\n                {\n                    //std::string deviceId = ipd->getDBTDeviceInfo( lParam );\n                    LOGL( 3, \"DBT device removal detected - checking for disconnected iPod..\" );\n                    ipd->onDeviceRemoved();\n                }\n                break;\n\n                default:\n                {\n        //            LOGL( 3, \"Unknown WM_DEVICECHANGE wParam: \" << wParam );\n                }\n                break;\n            }\n        break;\n\n        default:\n            return DefWindowProc( hwnd, uMsg, wParam, lParam );\n        break;\n    }\n    return 0;\n}\n\n\nstd::string \nIPodDetector::getDBTDeviceInfo( const LPARAM lParam ) const\n{\n    std::string retVal = \"unknown\";\n    PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam;\n\n    if (lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE)\n    {\n        PDEV_BROADCAST_DEVICEINTERFACE lpDevIf = (PDEV_BROADCAST_DEVICEINTERFACE)lpdb;\n\n        /* The dbcc_name needs to be copied into another memory location as\n         * the SetupDiCreateDeviceInfoList function seems to clear the lpdb memory\n         * (this seems to only happen with firewire devices *sigh* ) */\n\n        char* dbcc_name = new char[ strlen( lpDevIf->dbcc_name ) + 1 ];\n        strncpy( dbcc_name, lpDevIf->dbcc_name, strlen( lpDevIf->dbcc_name ) + 1 );\n\n        HDEVINFO devInfoList = SetupDiCreateDeviceInfoList( NULL, NULL );\n        \n        SP_DEVICE_INTERFACE_DATA devInterfaceData;\n        ZeroMemory( &devInterfaceData, sizeof( devInterfaceData ) );\n        devInterfaceData.cbSize = sizeof( devInterfaceData );\n        BOOL b = SetupDiOpenDeviceInterface( devInfoList,\n                                             dbcc_name,\n                                             0,\n                                             &devInterfaceData );\n                                    \n        delete[] dbcc_name;\n        \n        DWORD required;\n        SP_DEVICE_INTERFACE_DETAIL_DATA devDetailData;\n        ZeroMemory( &devDetailData, sizeof( devDetailData ) );\n        devDetailData.cbSize = sizeof( devDetailData );\n\n        \n        SP_DEVINFO_DATA devInfoData;\n        ZeroMemory( &devInfoData, sizeof( devInfoData ) );\n        devInfoData.cbSize = sizeof( devInfoData );\n        b = SetupDiGetDeviceInterfaceDetail( devInfoList,\n                                         &devInterfaceData,\n                                         &devDetailData,\n                                         sizeof( devDetailData ),\n                                         &required,\n                                         &devInfoData );\n       \n        TCHAR deviceId[1000];\n        b = SetupDiGetDeviceInstanceId( devInfoList,\n                                        &devInfoData,\n                                        deviceId,\n                                        1000,\n                                        NULL );\n\n        retVal = deviceId; \n    }\n    return retVal;\n}\n\n\nvoid \nIPodDetector::onDeviceConnected( IWbemClassObject* const device )\n{\n    IPod* iPod = IPod::newFromUsbDevice( device, m_wmiServices );\n\n    if( !iPod )\n        return;\n\n    notifyIfUnknownIPod( iPod );\n\n    if( iPod->isMobileScrobblerInstalled() )\n    {\n        LOGL( 3, \"Ignoring this iPhone / iPod touch as mobile scrobbler has been detected!\" );\n        return;\n    }\n\n    m_ipodMap[ iPod->serial() ] = iPod;\n\n    if( iPod->isManualMode() )\n    {\n        LOGWL( 3, L\"Manual iPod detected launching twiddly..:\" << iPod->serial() );\n        startTwiddlyWithIpodSerial( iPod->serial(), \"manual\" );\n    }\n    else\n    {\n        LOGWL( 3, L\"Device connected in automatic sync mode: \" << iPod->serial() );\n    }\n}\n\n\nvoid\nIPodDetector::notifyIfUnknownIPod( IPod* ipod )\n{\n    std::wstring const key = UNICORN_HKEY L\"\\\\device\\\\\" +\n                             ipod->device() + L\"\\\\\" +\n                             ipod->serial();\n\n    HKEY h = NULL;\n    LONG r = RegOpenKeyExW( HKEY_CURRENT_USER,\n                            key.c_str(),\n                            0,              // reserved\n                            KEY_ALL_ACCESS, // access mask\n                            &h );\n    \n    if ( r != ERROR_SUCCESS )\n    {\n        Moose::exec( Moose::applicationPath(), \n                     L\"--ipod-detected \" + ipod->serial() );\n        \n        r = RegCreateKeyExW( HKEY_CURRENT_USER,\n                             key.c_str(),\n                             0,                       // reserved, must be 0\n                             NULL,                    // class, ignore\n                             REG_OPTION_NON_VOLATILE, // saves key on exit\n                             KEY_ALL_ACCESS,          // access mask. TODO: test this as non-admin\n                             NULL,                    // security attrs, NULL = default, inherit from parent\n                             &h,\n                             NULL );\n    }\n\n    // Internet says this is safe, even if NULL, or after failed function calls\n    RegCloseKey( h );\n}\n\n\nvoid \nIPodDetector::onDeviceRemoved()\n{\n    bool iPodFound = false;\n    std::map< std::wstring, IPod* >::iterator iter;\n\n    for( iter = m_ipodMap.begin(); iter != m_ipodMap.end();)\n    {\n        IPod* curIpod = iter->second;\n        iter++; //Stop the iterator from being invalidated\n        if( !doesIpodExist( curIpod ) )\n        {\n            iPodFound = true;\n            LOGWL( 3, L\"Ipod: \" << curIpod->serial() << L\" removed.\" );\n            startTwiddlyWithIpodSerial( curIpod->serial(), \"unplug\" );\n        }\n    }\n    if( !iPodFound )\n        LOGL( 3, \"Could not find any disconnected iPods - a non-ipod device must have been removed\" );\n}\n\n\nbool \nIPodDetector::initializeWMI()\n{\n    HRESULT result;\n\n    // Initialize COM.\n\n    result =  CoInitializeEx(0, COINIT_APARTMENTTHREADED); \n    if (FAILED(result))\n    {\n        LOGL( 3, \"Failed to initialize COM library. Error code = 0x\" \n            << hex << result );\n        return false;\n    }\n\n    \n    // Obtain the initial locator to WMI\n\n    result = CoCreateInstance(\n        CLSID_WbemLocator,             \n        0, \n        CLSCTX_INPROC_SERVER, \n        IID_IWbemLocator, \n        (LPVOID *) &m_wmiLocator);\n \n    if (FAILED(result))\n    {\n        LOGL( 3, \"Failed to create IWbemLocator object.\"\n            << \" Err code = 0x\"\n            << hex << result );\n        CoUninitialize();\n        return false;\n    }\n\n    // Connect to WMI through the IWbemLocator::ConnectServer method\n\n\t\n    // Connect to the root\\cimv2 namespace with\n    // the current user and obtain pointer m_services\n    // to make IWbemServices calls.\n    result = m_wmiLocator->ConnectServer(\n         _bstr_t(L\"ROOT\\\\CIMV2\"), // Object path of WMI namespace\n         NULL,                    // User name. NULL = current user\n         NULL,                    // User password. NULL = current\n         0,                       // Locale. NULL indicates current\n         NULL,                    // Security flags.\n         0,                       // Authority (e.g. Kerberos)\n         0,                       // Context object \n         &m_wmiServices           // pointer to IWbemServices proxy\n         );\n    \n    if (FAILED(result))\n    {\n        LOGL( 3, \"Could not connect to WMI. Error code = 0x\" \n             << hex << result );\n        m_wmiLocator->Release();     \n        CoUninitialize();\n        return false;\n    }\n\n    LOGL( 3, \"Connected to ROOT\\\\CIMV2 WMI namespace\" );\n\n\n    // Set security levels on the proxy\n\n    result = CoSetProxyBlanket(\n       m_wmiServices,               // Indicates the proxy to set\n       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx\n       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx\n       NULL,                        // Server principal name \n       RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx \n       RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx\n       NULL,                        // client identity\n       EOAC_NONE                    // proxy capabilities \n    );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"Could not set proxy blanket. Error code = 0x\" \n            << hex << result );\n        m_wmiServices->Release();\n        m_wmiLocator->Release();     \n        CoUninitialize();\n        return false;\n    }\n    return true;\n}\n\n\nbool \nIPodDetector::queryByDeviceID( const std::string& deviceId, IEnumWbemClassObject** enumerator )\n{\n   HRESULT result;\n\n   std::string query = \"SELECT * FROM Win32_PnPEntity \"\n                       \"WHERE DeviceID LIKE '\";\n   query += deviceId;\n   query += \"' AND \"\n            \" (Name = '\" IPHONE_ITOUCH_NAME \"' OR \"\n            \"  Name = '\" IPOD_NAME \"' OR \"\n            \"  Name = '\" IPOD_FIREWIRE_NAME \"' OR \"\n            \"  Name = '\" IPOD_NANO_NAME \"') AND \"\n            \" (DeviceID LIKE '\" VID_STRING \"' OR \"\n            \"  DeviceID LIKE '\" LONG_VID_STRING \"')\";\n\n   size_t pos = 0;\n   for( pos = query.find(\"\\\\\", pos); pos != query.npos ; pos = query.find(\"\\\\\", pos) )\n   {\n       query.replace(pos, 1, \"\\\\\\\\\");\n       pos += 2;\n   }\n\n   result = m_wmiServices->ExecQuery(\n        bstr_t(\"WQL\"),\n        bstr_t(query.c_str()),\n        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n        NULL,\n        enumerator\n    );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"ExecQuery Error code = 0x\" \n            << hex << result );\n        return false;\n    }\n    return true;\n}\n\n\nbool \nIPodDetector::queryCurrentlyConnectedDevices( IEnumWbemClassObject** enumerator )\n{\n    HRESULT result;\n\n    result = m_wmiServices->ExecQuery(\n        bstr_t(\"WQL\"),\n        bstr_t(\"SELECT * FROM Win32_PnPEntity \"\n               \"WHERE  (Name = '\" IPHONE_ITOUCH_NAME \"' OR \"\n               \"        Name = '\" IPOD_NAME \"' OR \"\n               \"        Name = '\" IPOD_FIREWIRE_NAME \"' OR \"\n               \"        Name = '\" IPOD_NANO_NAME \"') AND \"\n               \"       (DeviceID LIKE '\" VID_STRING \"' OR \"\n               \"        DeviceID LIKE '\" LONG_VID_STRING \"')\"),\n        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n        NULL,\n        enumerator\n    );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"ExecQuery Error code = 0x\" \n            << hex << result );\n        return false;\n    }\n    return true;\n}\n\n\nvoid\nIPodDetector::checkConnectedDevices()\n{\n    IEnumWbemClassObject* currentDevicesEnumerator = NULL;\n    queryCurrentlyConnectedDevices( &currentDevicesEnumerator );\n\n    IWbemClassObject* device;\n    ULONG returnCount = 0;\n\n    while( currentDevicesEnumerator )\n    {\n        currentDevicesEnumerator->Next( WBEM_INFINITE,\n                                        1,\n                                        &device,\n                                        &returnCount );\n        if( 0 == returnCount )\n        {\n            break;\n        }\n        if( returnCount > 0 )\n        {\n            LOGL( 3, \"Detected pre-connected iPod\" );\n            onDeviceConnected( device );\n        }\n        device->Release();\n    }\n    currentDevicesEnumerator->Release();\n}\n\n\nvoid \nIPodDetector::shutdownWMI()\n{\n    m_wmiServices->Release();\n    m_wmiLocator->Release();\n    CoUninitialize();\n}\n\n\nbool \nIPodDetector::doesIpodExist(IPod *ipod)\n{\n    IEnumWbemClassObject* enumerator = NULL;\n    std::stringstream output;\n\n    for( size_t i = 0; i < ipod->serial().length(); ++i )\n    {\n        output << (char)ipod->serial().c_str()[i];\n    }\n    queryByDeviceID( output.str(), &enumerator );\n    \n    IWbemClassObject* object;\n    ULONG count;\n\n    enumerator->Next( WBEM_INFINITE, 1, &object, &count );\n    \n    enumerator->Release();\n\n    if( count > 0 )\n    {\n        object->Release();\n        return true;\n    }\n    return false;\n}\n"
  },
  {
    "path": "plugins/iTunes/IPod_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"IPod.h\"\n#include <dirent.h>\n#include <sys/stat.h>\n#include <mach/mach.h>\n#include <mach/error.h>\n#include <IOKit/usb/IOUSBLib.h>\n\n\nIPod* //static\nIPod::newFromUsbDevice( io_object_t device, deviceType type /* = unknown */ )\n{\n    IPod* ipod = new IPod();\n\n    io_object_t usbDevice = device;\n    io_name_t className;\n    IOObjectGetClass( usbDevice, className );\n    if( strncmp( className, kIOUSBDeviceClassName, sizeof( kIOUSBDeviceClassName ) ) != 0 )\n    {\n        usbDevice = getBaseDevice( device );\n        if( NULL == usbDevice )\n        {\n            LOG( 3, \"Error could not find base USBDevice for device class: \" << className );\n            return NULL;\n        }\n    }\n    \n    ipod->m_connectionType = usb;\n    if ( !getUsbSerial( device, &ipod->m_serial ) )\n    {\n        delete ipod;\n        return NULL;\n    }\n    \n    try\n    {\n        if( type != unknown )\n        {\n            //IPhone\n            ipod->m_type = type;\n        }\n        else if( ipod->isOldIpod( device ) )\n        {\n            //IPod classic\n            ipod->m_type = iPod;\n        }\n        else \n        {\n            //IPod Touch\n            ipod->m_type = iTouch;\n        }\n    }\n    catch ( const kern_return_t e )\n    {\n        // the kern_return_t error number is thrown if isOldIpod fails\n        // (the success can't be determined by the return value)\n        delete ipod;\n        return NULL;\n    }\n    \n    ipod->getDisplayName();\n    \n    if( ipod->m_type == iTouch ||\n        ipod->m_type == iPhone ||\n        ipod->m_type == iPad)\n    {\n        if( ipod->waitForIpodBackup() )\n        {\n            ipod->m_mobileScrobblerInstalled = false;\n             //ipod->queryMobileScrobblerInstalled();\n            ipod->m_manualMode = ipod->queryIPhoneManual();\n        }\n        else\n        {\n            LOG( 3, \"Warning: could not determine information from iPhone / iPod touch backup information\\n\"\n                     \"The presumption is that this device is in automatic sync mode without mobile scrobbler installed\" );\n        }\n    }\n    \n    if( !ipod->getDeviceId( device, &ipod->m_vid, &ipod->m_pid ) )\n    {\n        delete ipod;\n        return NULL;\n    }\n    \n    if( usbDevice != device )\n    {\n        IOObjectRelease( usbDevice );\n    }\n    return ipod;\n}\n\n\nIPod* //static\nIPod::newFromFireWireDevice( io_object_t device )\n{\n    IPod* ipod = new IPod();\n    ipod->m_connectionType = fireWire;\n    if ( !getFireWireSerial( device, &ipod->m_serial ) )\n    {\n        delete ipod;\n        return NULL;\n    }\n\n    //We can presume that all firewire IPods are classic iPods\n    //( Apple deprecated firewire connections with iPods after 4G )\n    ipod->m_type = iPod;\n    \n    if( !ipod->getDeviceFireWireId( device, &ipod->m_vid, &ipod->m_pid ) )\n    {\n        delete ipod;\n        return NULL;\n    }\n    return ipod;\n}\n\n\nbool \nIPod::getDeviceId( io_object_t device, int* vid, int* pid )\n{\n    CFMutableDictionaryRef propertyDictionary;\n    kern_return_t ioResult;\n    ioResult = IORegistryEntryCreateCFProperties( (io_registry_entry_t)device, \n                                                   &propertyDictionary, \n                                                   kCFAllocatorDefault, \n                                                   0 );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not get usb device properties: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    CFNumberRef cfVendor;\n    cfVendor = (CFNumberRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"idVendor\" ) );\n\n    CFNumberRef cfProduct;    \n    cfProduct = (CFNumberRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"idProduct\" ) );\n    \n    CFNumberGetValue ( cfVendor, kCFNumberIntType, vid );\n    CFNumberGetValue ( cfProduct, kCFNumberIntType, pid );\n\n    CFRelease( cfVendor );\n    CFRelease( cfProduct );\n    return true;\n}\n\n\nbool \nIPod::getDeviceFireWireId( io_object_t device, int* vid, int* pid )\n{\n    CFMutableDictionaryRef propertyDictionary;\n    kern_return_t ioResult;\n    ioResult = IORegistryEntryCreateCFProperties( (io_registry_entry_t)device, \n                                                   &propertyDictionary, \n                                                   kCFAllocatorDefault, \n                                                   0 );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not get firewire device properties: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n\n    CFNumberRef cfVendor;\n    cfVendor = (CFNumberRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"Vendor_ID\" ) );\n\n    CFNumberRef cfProduct;    \n    cfProduct = (CFNumberRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"Model_ID\" ) );\n    \n    CFNumberGetValue ( cfVendor, kCFNumberIntType, vid );\n    CFNumberGetValue ( cfProduct, kCFNumberIntType, pid );\n\n    CFRelease( cfVendor );\n    CFRelease( cfProduct );\n    return true;\n}\n\n\nbool //static\nIPod::getUsbSerial( io_object_t device, std::string* serialOut )\n{\n\n    io_object_t usbDevice = device;\n    io_name_t className;\n    IOObjectGetClass( usbDevice, className );\n    if( strncmp( className, kIOUSBDeviceClassName, sizeof( kIOUSBDeviceClassName ) ) != 0 )\n    {\n        usbDevice = getBaseDevice( device );\n        if( usbDevice == NULL )\n        {\n            LOG( 3, \"Error could not find base USBDevice for device class: \" << className );\n            return NULL;\n        }\n    }\n\n    CFMutableDictionaryRef propertyDictionary;\n    kern_return_t ioResult;\n    ioResult = IORegistryEntryCreateCFProperties( (io_registry_entry_t)usbDevice, \n                                                   &propertyDictionary, \n                                                   kCFAllocatorDefault, \n                                                   0 );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not get serial properties: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n    \n    CFStringRef cfSerial;\n    cfSerial = (CFStringRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"USB Serial Number\" ) );\n    if( cfSerial == NULL )\n    {\n        LOG( 3, \"Error - Could not get USB Serial Number\" );\n        return false;\n    }\n    \n    char serial[50];\n    CFStringGetCString( cfSerial, serial, 50, kCFStringEncodingASCII );\n\n    CFRelease( cfSerial );\n    *serialOut = serial;\n    \n    if( usbDevice != device )\n    {\n        IOObjectRelease( usbDevice );\n    }\n    return true;\n}\n\n\nbool //static\nIPod::getFireWireSerial( io_object_t device, std::string* serialOut )\n{\n    CFMutableDictionaryRef propertyDictionary;\n    kern_return_t ioResult;\n    ioResult = IORegistryEntryCreateCFProperties( (io_registry_entry_t)device, \n                                                   &propertyDictionary, \n                                                   kCFAllocatorDefault, \n                                                   0 );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not get USB device properties: \" << mach_error_string( ioResult ) );\n        return false;\n    }\n    \n    CFNumberRef cfSerial;\n    cfSerial = (CFNumberRef)CFDictionaryGetValue( propertyDictionary, CFSTR( \"GUID\" ) );\n    if( cfSerial == NULL )\n    {\n        LOG( 3, \"GUID property does not exist for this device\" );\n        return false;\n    } \n\n    int serial;\n\n    CFNumberGetValue( cfSerial, kCFNumberIntType, &serial );\n    \n    \n    std::stringstream serialStream;\n    serialStream << \"0x\" << std::hex << serial;\n    *serialOut = serialStream.str();\n\n    CFRelease( cfSerial );\n    \n    return true;\n}\n\n\nbool \nIPod::isOldIpod( io_object_t device )\n{\n    io_iterator_t iter;\n    kern_return_t ioResult;\n    ioResult = IORegistryEntryCreateIterator( (io_registry_entry_t)device, \n                                               kIOServicePlane, \n                                               kIORegistryIterateRecursively, \n                                               &iter );\n\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not create isOldIpod recursive iterator: \" << mach_error_string( ioResult ) );\n        throw ioResult;\n    }\n    \n    io_object_t curObject;\n    while( curObject = IOIteratorNext( iter ) )\n    {\n        io_name_t className;\n        ioResult = IOObjectGetClass( curObject, className );\n        \n        if( ioResult != kIOReturnSuccess )\n        {\n            LOG( 3, \"Could not get class name from current object: \" << mach_error_string( ioResult ) );\n            throw ioResult;\n        }\n\n        IOObjectRelease( curObject );\n        if( strncmp( (char*)className, \"IOUSBMassStorageClass\", sizeof( className ) ) == 0 )\n        {\n            return true;\n        }\n    }\n    return false;\n}\n\n\nCFDictionaryRef \nIPod::createDictionaryFromXML( CFStringRef filePath ) const\n{\n    CFDictionaryRef dictionary = NULL;\n    CFDataRef resourceData = NULL;\n    CFStringRef errorString = NULL;\n    SInt32 errorCode;\n\n    CFURLRef fileURL;\n    fileURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault,\n                                             filePath,                // file path name\n                                             kCFURLPOSIXPathStyle,    // interpret as POSIX path\n                                             false );                 // is it a directory?\n\n    Boolean result = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault,      // allocator\n                                                               fileURL,                  // file location\n                                                               &resourceData,            // place to put file data\n                                                               NULL,                     // properties\n                                                               NULL,                     // properties which are desired\n                                                               &errorCode);              // error code\n\n    if( !result )\n    {\n        LOG( 3, \"Error: could not get data from backup file:\" << CFStringGetCStringPtr ( filePath, kCFStringEncodingASCII ) );\n        CFRelease( fileURL );\n        return dictionary;\n    }\n\n    dictionary = (CFDictionaryRef)CFPropertyListCreateFromXMLData( kCFAllocatorDefault,\n                                                                       resourceData,\n                                                                       kCFPropertyListImmutable,\n                                                                       &errorString);\n    CFRelease( resourceData );\n    CFRelease( fileURL );\n    return dictionary;\n}\n\n\nbool \nIPod::queryIPhoneManual() const\n{\n\n    CFDictionaryRef iTunesFiles;\n    UInt8 manualMode;\n    CFDataRef iTunesPrefsData;\n    \n    CFMutableStringRef infoPlistPath = CFStringCreateMutable( kCFAllocatorDefault, 0 );\n    CFStringAppendCString( infoPlistPath, ::getenv( \"HOME\" ), kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, \"/Library/Application Support/MobileSync/Backup/\", kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, m_serial.c_str(), kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, \"/Info.plist\", kCFStringEncodingASCII );\n    \n    CFDictionaryRef propertyList = createDictionaryFromXML( infoPlistPath );\n    CFRelease( infoPlistPath );\n    \n    if( propertyList == NULL )\n    {\n        LOG( 3, \"Error: Could not read Info.plist file - presuming automatic sync enabled\" );\n        return false;\n    }\n\n    iTunesFiles = (CFDictionaryRef)CFDictionaryGetValue( propertyList, CFSTR( \"iTunes Files\" ) );\n    \n    if( iTunesFiles == NULL )\n    {\n        LOG( 3, \"Error: Could not extract the iTunes Files property from Info.plist file. \"\n                 \"Presuming automatic sync enabled.\" );\n        return false;\n    }\n    \n    iTunesPrefsData = (CFDataRef)CFDictionaryGetValue( iTunesFiles, CFSTR( \"iTunesPrefs\" ) );    \n    \n    if( iTunesPrefsData == NULL )\n    {\n        LOG( 3, \"Error: Could not read the iTunesPrefs data from Info.plist - iTunesFiles section. \"\n                 \"Presuming automatic sync enabled.\" );\n        return false;\n    }\n    \n    if( CFDataGetLength( iTunesPrefsData ) < 11 )\n    {\n        LOG( 3, \"Error: Data length of iTunesPrefs data is too small. \"\n                 \"Presuming automatic sync enabled.\" );\n        return false;\n    }\n    \n    /* The 10th byte of the iTunesPrefs file determines whether the iPod is\n     * in manual or automatic mode.\n     * Automatic == 1, Manual == 0\n     */ \n    CFDataGetBytes( iTunesPrefsData, CFRangeMake( 10, 1 ), &manualMode );\n\n    CFRelease( iTunesPrefsData );\n    return (manualMode == 0);\n}\n\nvoid \nIPod::getDisplayName()\n{\n    // fall back on the serial number if we can't find the display name\n    m_displayName = m_serial;\n    \n    CFStringRef displayName;\n    \n    CFMutableStringRef infoPlistPath = CFStringCreateMutable( kCFAllocatorDefault, 0 );\n    CFStringAppendCString( infoPlistPath, ::getenv( \"HOME\" ), kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, \"/Library/Application Support/MobileSync/Backup/\", kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, m_serial.c_str(), kCFStringEncodingASCII );\n    CFStringAppendCString( infoPlistPath, \"/Info.plist\", kCFStringEncodingASCII );\n    \n    CFDictionaryRef propertyList = createDictionaryFromXML( infoPlistPath );\n    CFRelease( infoPlistPath );\n    \n    if( propertyList == NULL )\n    {\n        LOG( 3, \"Error: Could not read Info.plist file - presuming automatic sync enabled\" );\n        return;\n    }\n    \n    displayName = (CFStringRef)CFDictionaryGetValue( propertyList, CFSTR( \"Display Name\" ) );\n        \n    if( displayName == NULL )\n    {\n        LOG( 3, \"Error: Could not read Display Name data from Info.plist.\" );\n        return;\n    }\n    \n    CFIndex length = CFStringGetLength( displayName );\n    length = CFStringGetMaximumSizeForEncoding( length, kCFStringEncodingUTF8 );\n    char* buffer = new char[length];\n    CFStringGetCString( displayName, buffer, length, kCFStringEncodingUTF8 );\n    \n    m_displayName = buffer;\n    delete[] buffer;\n     \n    CFRelease( displayName );\n}\n\n\nvoid \nIPod::populateIPodManual()\n{\n    CFMutableStringRef iTunesPrefsPath = CFStringCreateMutable( kCFAllocatorDefault, 0 );\n    CFStringAppendCString( iTunesPrefsPath, m_mountPoint.c_str(), kCFStringEncodingASCII );\n    CFStringAppendCString( iTunesPrefsPath, \"/iPod_Control/iTunes/iTunesPrefs\", kCFStringEncodingASCII );\n    \n    \n    CFURLRef fileURL;\n    fileURL = CFURLCreateWithFileSystemPath( kCFAllocatorDefault,\n                                             iTunesPrefsPath,         // file path name\n                                             kCFURLPOSIXPathStyle,    // interpret as POSIX path\n                                             false );                 // is it a directory?\n                                             \n    CFRelease( iTunesPrefsPath );\n                                             \n    CFDataRef iTunesPrefsData;\n    \n    SInt32 errorCode;\n    Boolean result = CFURLCreateDataAndPropertiesFromResource( kCFAllocatorDefault,      // allocator\n                                                               fileURL,                  // file location\n                                                               &iTunesPrefsData,         // place to put file data\n                                                               NULL,                     // properties\n                                                               NULL,                     // properties which are desired\n                                                               &errorCode);              // error code\n                                                               \n    if( !result ||\n        CFDataGetLength( iTunesPrefsData ) < 11 )\n    {\n        LOG( 3, \"Error: Data length of iTunesPrefs data is too small. \"\n                 \"Presuming automatic sync enabled. \" << std::endl <<\n                 \"MountPoint: \" << m_mountPoint );\n        m_manualMode = false;\n        return;\n    }\n    \n    \n    UInt8 manualMode;\n    /* The 10th byte of the iTunesPrefs file determines whether the iPod is\n     * in manual or automatic mode.\n     * Automatic == 1, Manual == 0\n     */ \n    CFDataGetBytes( iTunesPrefsData, CFRangeMake( 10, 1 ), &manualMode );\n\n    CFRelease( iTunesPrefsData );\n    m_manualMode = (manualMode == 0);\n}\n\n\nio_object_t //static\nIPod::getBaseDevice( io_object_t device )\n{\n    io_iterator_t parentIter;\n    IOReturn ioResult = IORegistryEntryCreateIterator( device, \n                                              kIOServicePlane, \n                                              kIORegistryIterateParents | kIORegistryIterateRecursively, \n                                              &parentIter);\n    if( ioResult != kIOReturnSuccess )\n    {\n        LOG( 3, \"Could not create iterator to iterate over unmounted device\" << mach_error_string( ioResult ) );\n    }\n    \n    io_object_t curParent;\n    while( curParent = IOIteratorNext( parentIter ) )\n    {\n        io_name_t deviceName;\n        ioResult = IORegistryEntryGetName( curParent, deviceName );\n        if( ioResult != kIOReturnSuccess )\n        {\n            LOG( 3, \"Could not get parent's name/class: \" << mach_error_string( ioResult ) );\n            IOObjectRelease( curParent );\n            continue;\n        }\n        \n        if( strncmp( deviceName, \"iPod\", 4 ) == 0 ||\n            strncmp( deviceName, \"iPad\", 4 ) == 0 ||\n            strncmp( deviceName, \"iPod mini\", 9 ) == 0 ||\n            strncmp( deviceName, \"IOFireWireSBP2LUN\", 17 ) == 0 )\n        {\n            return curParent;\n        }\n        IOObjectRelease( curParent );\n    }\n    return NULL;\n}\n\n\nbool \nIPod::queryMobileScrobblerInstalled() const\n{\n    DIR* plistFolder;\n    struct dirent *dirEntry;\n    \n    std::string backupPath = ::getenv( \"HOME\" );\n    backupPath += \"/Library/Application Support/MobileSync/Backup/\";\n    backupPath += m_serial;\n    backupPath += \"/\";\n    \n    plistFolder = opendir( backupPath.c_str() );\n    if( plistFolder == NULL )\n    {\n        LOG( 3, \"Could not query itouch / iphone backup folder - presuming MobileScrobbler is NOT installed..\" );\n        return false;\n    }\n    while( dirEntry = readdir( plistFolder ) )\n    {\n        if( dirEntry->d_type != DT_REG )\n            continue;\n        \n        std::string curPath = backupPath + dirEntry->d_name;\n        \n        if( isMobileScrobblerPlist( curPath.c_str() ) )\n            return true;\n    }\n    return false;\n}\n\nbool \nIPod::isMobileScrobblerPlist( const char* path ) const\n{\n    std::ifstream fin( path );\n    fin.seekg( 0, std::ios_base::end );\n    int length = fin.tellg();\n \n    if( length < 29 )\n        return false;   \n    \n    fin.seekg( 0, std::ios_base::beg );\n    char* buffer = new char[ length ];\n    fin.read( buffer, length );\n\n    bool retval = false;\n    if(strstr( buffer, \"org.c99.MobileScrobbler.plist\" ))\n        retval = true;\n\n    delete[] buffer;\n    return retval;\n}\n\nbool \nIPod::waitForIpodBackup() const\n{\n    std::string backupPath = ::getenv( \"HOME\" );\n    backupPath += \"/Library/Application Support/MobileSync/Backup/\";\n    backupPath += m_serial;\n    backupPath += \"/Info.plist\";\n\n    struct stat infoPlistStat;\n    long int curTime = time( NULL );\n    long int infoPlistModTime = 0;\n    int count;\n    const int timeout = 60 * 5; //5 minute timeout\n    for( count = 0; count < timeout && infoPlistModTime < curTime; count++ )\n    {\n        sleep( 1 ); //sleep 1 second\n        if( stat( backupPath.c_str(), &infoPlistStat ) )\n        {\n            //TODO: error handling pls\n        }\n        infoPlistModTime = infoPlistStat.st_mtimespec.tv_sec;\n    }\n    return count != timeout;\n}\n"
  },
  {
    "path": "plugins/iTunes/IPod_win.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"IPod.h\"\n\n#include <cstdio>\n#include <string>\n#include <ctime>\n\n#include <comdef.h>\n#include <Wbemidl.h>\n\n#include <shlobj.h>\n#include <sys/stat.h>\n#include \"Plist.h\"\n\nIPod* //static\nIPod::newFromUsbDevice( IWbemClassObject *device, IWbemServices* wmiServices )\n{\n    IPod* ipod = new IPod;\n\n    ipod->m_wmiServices = wmiServices;\n\n    std::wstring name = ipod->getDeviceName( device );\n\n    getSerialVidPid( device, &ipod->m_serial, &ipod->m_vid, &ipod->m_pid );\n\n    if( L\"Apple Mobile Device USB Driver\" == name )\n    {\n        //iPhone / iPod Touch Detected\n        ipod->m_type = iPhone;\n        ipod->populateIPhoneMobileScrobblerAndManualMode();\n    }\n    else if( L\"unknown\" == name )\n    {\n        ipod->m_type = unknown;\n    }\n    else\n    {\n        ipod->m_type = iPod;\n        ipod->populateMountPoint( device );\n        if( ipod->m_mountPoint.length() < 1 )\n        {\n            LOGL( 3, \"No mount point found - presuming automatic sync mode\" );\n        }\n        else\n        {\n            ipod->populateIPodManual();\n        }\n    }\n\n    if( L\"Apple Computer_ Inc. iPod IEEE 1394 SBP2 Device\" == name )\n        ipod->m_connectionType = fireWire;\n    else\n        ipod->m_connectionType = usb;\n\n\n    ipod->m_connectionTickCount = ::GetTickCount();\n\n    return ipod;\n}\n\nvoid //static\nIPod::getSerialVidPid( IWbemClassObject* const object, \n                       std::wstring *const serialOut /* = NULL */, \n                       int *const vidOut /* = NULL */, \n                       int *const pidOut /* = NULL */ )\n{\n    HRESULT result;\n    VARIANT vtDeviceId;\n\n    std::wstring deviceId;\n\n    //get full pnpDevice Id String\n    result = object->Get( L\"DeviceID\", 0, &vtDeviceId, 0, 0 );\n    if( SUCCEEDED(result) )\n    {\n        deviceId = std::wstring( _bstr_t( vtDeviceId.bstrVal ) );\n    }\n    else\n    {\n        LOGL( 3, \"Error getting DeviceID from WMI: 0x\" << std::hex << result );\n        VariantClear( &vtDeviceId );\n        if( vidOut )\n            *vidOut = 0;\n        if( pidOut )\n            *pidOut = 0;\n        if( serialOut )\n            *serialOut = L\"unknown\";\n        return;\n    }\n\n    //seperate deviceId into tokens delimited by a '\\'\n    std::vector<std::wstring> tokens;\n    tokenize( deviceId, tokens, L\"\\\\\" );\n\n    if( tokens.size() < 3 )\n    {\n        LOGWL( 3, L\"Could not determine serial / pid / vid from deviceID string: \" << deviceId );\n         VariantClear( &vtDeviceId );\n         if( vidOut )\n            *vidOut = 0;\n         if( pidOut )\n            *pidOut = 0;\n         if( serialOut )\n            *serialOut = L\"unknown\";\n        return;\n    }\n    \n    //serial number ( + optional &APPL0 if iPod classic ) is always 3rd element of vector\n    std::vector<std::wstring> serialTokens;\n    tokenize( tokens.at(2), serialTokens, L\"&\" );\n\n    if( serialOut )\n        *serialOut = serialTokens.at( 0 );\n\n    // vid / pid information is in 2nd element of vector\n    // split on &\n    std::vector<std::wstring> vidPidTokens;\n    tokenize( tokens.at(1), vidPidTokens, L\"&\" );\n    \n    if( vidPidTokens.size() < 2 )\n    {\n        LOGWL( 3, L\"Could not determine  pid / vid from vidpid string: \" << tokens.at(1) );\n        VariantClear( &vtDeviceId );\n        if( vidOut )\n            *vidOut = 0;\n        if( pidOut )\n            *pidOut = 0;\n        return;\n    }\n\n    std::wstring vid = vidPidTokens.at( 0 );\n    std::wstring pid = vidPidTokens.at( 1 );\n\n    std::wstringstream vidStream( vid.substr( 4, vid.length() - 4 ) );\n    std::wstringstream pidStream( pid.substr( 4, pid.length() - 4 ) );\n\n    //convert hex string to int\n    if( pidOut )\n        pidStream >> std::hex >> *pidOut;\n    \n    if( vidOut )\n        vidStream >> std::hex >> *vidOut;\n    return;\n}\n\n\nstd::wstring \nIPod::getDeviceName( IWbemClassObject* const object ) const\n{\n    HRESULT result;\n    VARIANT vtName;\n    std::wstring retVal;\n\n    result = object->Get( L\"Name\", 0, &vtName, 0, 0 );\n    if( FAILED( result ) )\n    {\n        LOGL( 3, \"Error getting Name from WMI: 0x\" << std::hex << result );\n        retVal = L\"unknown\";\n    }\n    else\n    {\n       retVal = std::wstring( _bstr_t( vtName.bstrVal ) );\n       VariantClear( &vtName );\n    }\n    return retVal;\n}\n\n\nbool \nIPod::hasTimeoutExpired( DWORD timeoutValue )\n{\n    if( ( ::GetTickCount() - m_connectionTickCount ) > timeoutValue )\n    {\n        return true;\n    }\n    return false;\n}\n\n\nvoid //static\nIPod::tokenize( const std::wstring & str, \n                      std::vector<std::wstring> & tokens, \n                      const std::wstring & delimiters /* = L\" \" */ )\n{\n    // Skip delimiters at beginning.\n  std::wstring::size_type last_pos = str.find_first_not_of(delimiters, 0);\n    // Find first \"non-delimiter\".\n  std::wstring::size_type pos = str.find_first_of(delimiters, last_pos);\n  while (std::wstring::npos != pos || std::wstring::npos != last_pos)\n  {\n        // Found a token, add it to the vector.\n      tokens.push_back(str.substr(last_pos, pos - last_pos));\n        // Skip delimiters.  Note the \"not_of\"\n      last_pos = str.find_first_not_of(delimiters, pos);\n        // Find next \"non-delimiter\"\n      pos = str.find_first_of(delimiters, last_pos);\n  }\n}\n\n\nvoid\nIPod::populateMountPoint( IWbemClassObject *device )\n{\n    char driveLetter = NULL;\n    int i;\n    LOGL( 3, \"Searching for iPod mountpoint..\" );\n    for( i = 0; i < 100 && driveLetter == NULL; i++ )\n    {\n        driveLetter = getDriveLetterFromPnPEntity( device );\n        Sleep( 100 );\n    }\n    if( driveLetter == NULL )\n    {\n        LOGL( 3, \"Error: could not determine mount point of connected iPod after 10 seconds of waiting.\" );\n    } else\n    {\n        m_mountPoint = driveLetter;\n        m_mountPoint += \":\";\n        LOGL( 3, \"Mount point \" << m_mountPoint << \" found after\" << ( (float)i / 10.0f) << \"seconds\" );\n    }\n}\n\n\nchar \nIPod::getDriveLetterFromPnPEntity( IWbemClassObject* device ) const\n{\n    char driveLetter = NULL;\n\n    std::wstring query = L\"select * from Win32_DiskDrive where PNPDeviceID LIKE '%\";\n    query += m_serial;\n    query += L\"%'\";\n\n    IEnumWbemClassObject* enumerator;\n\n    HRESULT result = m_wmiServices->ExecQuery(\n                         bstr_t(\"WQL\"),\n                         bstr_t(query.c_str()),\n                         WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n                         NULL,\n                         &enumerator );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"ExecQuery Error code = 0x\" \n            << std::hex << result );\n        return NULL;\n    }\n\n    ULONG returnCount;\n\n    IWbemClassObject* diskDrive;\n    enumerator->Next( WBEM_INFINITE,\n                      1,\n                      &diskDrive,\n                      &returnCount );\n\n    if( returnCount > 0 )\n    {\n        driveLetter = getDriveLetterFromDiskDrive( diskDrive );\n        diskDrive->Release();\n    }\n    enumerator->Release();\n    return driveLetter;\n}\n\n\nchar \nIPod::getDriveLetterFromDiskDrive( IWbemClassObject* diskDrive ) const\n{\n    char driveLetter = NULL;\n    VARIANT vtName;\n    diskDrive->Get( L\"Name\", 0, &vtName, 0, 0 );\n\n    std::wstring query = L\"Associators Of {Win32_DiskDrive.DeviceID=\\\"\";\n    query += vtName.bstrVal;\n    query += L\"\\\"} where AssocClass = Win32_DiskDriveToDiskPartition\";\n\n    size_t pos = 0;\n    for( pos = query.find(L\"\\\\\", pos); pos != query.npos ; pos = query.find(L\"\\\\\", pos) )\n    {\n        query.replace(pos, 1, L\"\\\\\\\\\");\n        pos += 2;\n    }\n\n    IEnumWbemClassObject* diskPartitionEnum;\n\n    HRESULT result = m_wmiServices->ExecQuery(\n                         bstr_t(\"WQL\"),\n                         bstr_t(query.c_str()),\n                         WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n                         NULL,\n                         &diskPartitionEnum );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"ExecQuery Error code = 0x\" \n            << std::hex << result );\n        return NULL;\n    }\n\n    ULONG diskEnumReturnCount;\n    IWbemClassObject* Partition;\n    diskPartitionEnum->Next( WBEM_INFINITE,\n                             1,\n                             &Partition,\n                             &diskEnumReturnCount );\n\n    if( diskEnumReturnCount > 0 )\n    {\n        driveLetter = getDriveLetterFromPartition( Partition );\n        Partition->Release();\n    }\n\n    diskPartitionEnum->Release();\n    return driveLetter;\n}\n\nchar \nIPod::getDriveLetterFromPartition( IWbemClassObject* partition ) const\n{\n    char driveLetter = NULL;\n    VARIANT vtPartitionID;\n    partition->Get( L\"DeviceID\",\n                           0,\n                           &vtPartitionID,\n                           0,\n                           0 );\n\n\n    std::wstring query = L\"associators of {Win32_DiskPartition.DeviceID=\\\"\";\n    query += vtPartitionID.bstrVal;\n    query += L\"\\\"} where AssocClass = Win32_LogicalDiskToPartition\";\n\n    IEnumWbemClassObject* logicalDiskEnum;\n\n    HRESULT result = m_wmiServices->ExecQuery(\n                     bstr_t(\"WQL\"),\n                     bstr_t(query.c_str()),\n                     WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,\n                     NULL,\n                     &logicalDiskEnum );\n\n    if (FAILED(result))\n    {\n        LOGL( 3, \"ExecQuery Error code = 0x\" \n            << std::hex << result );\n        return NULL;\n    }\n\n    ULONG logicalDiskEnumReturnCount;\n\n    IWbemClassObject* logicalDisk;\n    logicalDiskEnum->Next( WBEM_INFINITE,\n                             1,\n                             &logicalDisk,\n                             &logicalDiskEnumReturnCount );\n\n    if( logicalDiskEnumReturnCount > 0 )\n    {\n        VARIANT vtDriveLetter;\n        logicalDisk->Get( L\"DeviceID\",\n                          0,\n                          &vtDriveLetter,\n                          0,\n                          0);\n\n        //This returns the first byte of the first wchar_t in the string\n        //which will be the drive letter of the drive unless microsoft go\n        //and do something stupid like enable unicode drive letters!\n        driveLetter = (reinterpret_cast<char*>( vtDriveLetter.pbstrVal ))[0];\n        logicalDisk->Release();\n    }\n    logicalDiskEnum->Release();\n    return driveLetter;\n}\n\nvoid\nIPod::populateIPodManual()\n{\n    std::string iTunesPrefsPath = m_mountPoint + \"\\\\iPod_Control\\\\iTunes\\\\iTunesPrefs\";\n    FILE* fp = fopen( iTunesPrefsPath.c_str(), \"r\" );\n\n    try \n    {\n        if (!fp) throw \"Couldn't open\";\n        int r = fseek( fp, 10, SEEK_SET );\n        if (r != 0) throw \"Couldn't seek to byte 10\";\n        int c = fgetc( fp );\n        m_manualMode = (c == 0);\n    }\n    catch (const char* message)\n    {\n        LOGL( 2, message << \" `\" << iTunesPrefsPath << \"'\" );\n    }\n\n    if( fp )\n        fclose( fp );\n\n    LOGL( 3, \"Sync mode detected: \" << ( m_manualMode ? \"Manual\" : \"Automatic\" ) );\n}\n\n\nvoid \nIPod::populateIPhoneMobileScrobblerAndManualMode()\n{\n    WCHAR appData[ MAX_PATH ];\n    \n    HRESULT result = ::SHGetFolderPathW( NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, appData );\n    if( result != S_OK )\n    {\n        LOGL( 3, \"Could not get CSIDL_APPDATA location - presuming iPhone is in automatic sync mode and mobile scrobbler is NOT installed.\" );\n        return;\n    }\n    \n    std::wstring backupPath = appData;\n    backupPath += L\"\\\\Apple Computer\\\\MobileSync\\\\Backup\\\\\";\n    backupPath += m_serial;\n    backupPath += L\"\\\\\";\n\n    std::wstring infoPlistPath = backupPath + L\"Info.plist\";\n\n    waitForIpodBackup( infoPlistPath );\n\n    m_mobileScrobblerInstalled = queryMobileScrobblerInstalled( backupPath );\n    m_manualMode = queryIPhoneManual( infoPlistPath );\n\n}\n\n\nvoid \nIPod::waitForIpodBackup( const std::wstring& backupPath ) const\n{\n    struct _stat infoPlistStat;\n    time_t curTime = time( NULL );\n    time_t infoPlistModTime = 0;\n\n    int i = 0;\n    for( i = 0; infoPlistModTime < curTime && i < (5 * 60); i++ )\n    {\n        Sleep( 1000 );       \n        if( _wstat( backupPath.c_str(), &infoPlistStat ) )\n        {\n            //TODO: error handling pls\n        }\n\n        infoPlistModTime = infoPlistStat.st_mtime;\n    }\n\n    if( infoPlistModTime < curTime )\n        LOGL( 3, \"Waiting for ipod backup has timed out - \"\n                 \"Presuming that settings haven't changed since last backup.\" );\n}\n\n\nbool \nIPod::queryIPhoneManual( const std::wstring& infoPlistPath ) const\n{\n\n    char manualMode;\n    try\n    {\n        std::ifstream plistStream( infoPlistPath.c_str() );\n        if( plistStream.fail() )\n            throw std::string( \"Could not open info.plist backup file.\" );\n\n        Plist plist( plistStream );\n        Element iTunesPrefs = plist[0][ \"iTunes Files\" ][ \"iTunesPrefs\" ];\n        if( iTunesPrefs.getDataLength() < 10 )\n            throw std::string( \"iTunesPrefs data looks too short\" );\n\n        manualMode = iTunesPrefs.getData()[10];\n    }\n    catch( const std::string& e )\n    {\n        LOGL( 3, \"Could not determine whether iPod is in manual / automatic mode error: \" << e\n                  << \". Presuming automatic mode.\");\n        manualMode = 1;\n    }\n    return (manualMode == 0);\n}\n\n\nbool \nIPod::queryMobileScrobblerInstalled( const std::wstring& backupPath ) const\n{\n\n    std::wstring searchPath = backupPath + L\"*.mdbackup\";\n\n    WIN32_FIND_DATAW fileInfo;\n    HANDLE dirHandle = ::FindFirstFileW( searchPath.c_str(), &fileInfo );\n\n    if( dirHandle == INVALID_HANDLE_VALUE )\n    {\n        LOGL( 3, \"Could not search the backup folder for mdbackup files - presuming Mobile scrobbler is NOT installed.\" );\n        return false;\n    }\n\n    do{\n        std::wstring curPath = backupPath + fileInfo.cFileName;\n        if( isMobileScrobblerPlist( curPath ) )\n            return true;\n    }while( ::FindNextFileW( dirHandle, &fileInfo ) != 0 );\n    \n    \n    FindClose( dirHandle );\n    return false;\n}\n\n\nbool \nIPod::isMobileScrobblerPlist( const std::wstring& path ) const\n{\n    std::ifstream fin( path.c_str() );\n    fin.seekg( 0, std::ios_base::end );\n    int length = fin.tellg();\n    fin.seekg( 0, std::ios_base::beg );\n    char* buffer = new char[ length ];\n    fin.read( buffer, length );\n\n    bool retval = false;\n    if(strstr (buffer, \"org.c99.MobileScrobbler.plist\" ))\n        retval = true;\n\n    delete[] buffer;\n    return retval;\n}"
  },
  {
    "path": "plugins/iTunes/ITunesComThread.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifdef WIN32\r\n\r\n#include \"ITunesComThread.h\"\r\n#include \"ITunesPlaysDatabase.h\"\r\n\r\n#include \"ITunesComWrapper.h\"\r\n#include \"common/c++/Logger.h\"\r\n#include \"Moose.h\"\r\n#include \"EncodingUtils.h\"\r\n\r\n#include <process.h>\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\n// We use a custom message to tell our thread message loop to sync\r\nenum {\r\n\tWM_SYNC_PLAYS_DB = WM_USER,\r\n\tWM_STOP,\r\n\tWM_IS_PLAYING\r\n};\r\n    \r\n/******************************************************************************\r\n    ITunesComThread\r\n******************************************************************************/\r\nITunesComThread::ITunesComThread() :\r\n    m_com( 0 ),\r\n    m_db( 0 ),\r\n    m_comEnabled( true ),\r\n    m_threadHandle( 0 ),\r\n    m_hWnd( 0 ),\r\n    m_timeOfLastTrackChange( 0 ),\r\n    m_retrying( false ),\r\n    m_retryAttempts( 0 )\r\n{\r\n    InitializeCriticalSection(&m_critSect);\r\n\r\n\tstartComThread();\r\n}\r\n\r\n\r\nITunesComThread::~ITunesComThread()\r\n{\r\n    LOGL( 3, \"~ITunesComThread()\" );\r\n\r\n    // Thread shutdown has been initialised already via the OnAboutToQuit event\r\n    DWORD waitResult = WaitForSingleObject( m_threadHandle, 5000 );\r\n    if ( waitResult == WAIT_TIMEOUT || waitResult == WAIT_FAILED )\r\n    {\r\n        LOGL( 2, \"Wait for ITunesComThread thread termination \" <<\r\n            ( ( waitResult == WAIT_TIMEOUT ) ? \"timed out. \" : \"failed. \" ) <<\r\n            \"GetLastError(): \" << GetLastError() );\r\n    }\r\n    else\r\n    {\r\n        LOGL( 3, \"iTunes COM thread terminated\" );\r\n    }\r\n\t\r\n\r\n    CloseHandle( m_threadHandle );\r\n    DeleteCriticalSection( &m_critSect );\r\n}\r\n\r\nvoid\r\nITunesComThread::startComThread()\r\n{\r\n   unsigned threadId;\r\n    m_threadHandle = reinterpret_cast<HANDLE>(\r\n        _beginthreadex(\r\n            NULL,          // security crap\r\n            0,             // stack size\r\n            threadMain,    // start function\r\n            reinterpret_cast<void*>(this),  // argument to thread\r\n            0,             // run straight away\r\n            &threadId ) ); // thread id out\r\n\r\n    if ( m_threadHandle == 0 ) // Error\r\n    {\r\n        // FIXME\r\n        LOGL( 1, \"Failed to start iTunes COM thread: \" << string( strerror(errno) ) );\r\n    }\r\n}\r\n\r\nvoid\r\nITunesComThread::syncTrack( const VisualPluginTrack& vpt )\r\n{\r\n\t// If the com thread was closed due to a close signal\r\n\t// but iTunes didn't actaully close we should start up our thread again\r\n\tif ( !m_com )\r\n\t\tstartComThread();\r\n\r\n    // Needs guarding because it will be read by the worker thread after the\r\n    // PostMessage. If we come into this function twice before the worker thread\r\n    // has had a chance to wake up, it shouldn't matter that we miss we the first\r\n    // track. The reason being that if two or more tracks come in in such quick\r\n    // succession, they have most likely been skipped and their playcounts\r\n    // won't have increased.\r\n    EnterCriticalSection( &m_critSect );\r\n    m_visTrackToSync = vpt;\r\n    LeaveCriticalSection( &m_critSect );\r\n    \r\n    PostMessage( m_hWnd, WM_SYNC_PLAYS_DB, reinterpret_cast<WPARAM>( this ), 0 );\r\n}\r\n\r\nvoid\r\nITunesComThread::stop()\r\n{\r\n\t// If the com thread was closed due to a close signal\r\n\t// but iTunes didn't actaully close we should start up our thread again\r\n\tif ( !m_com )\r\n\t\tstartComThread();\r\n    \r\n    PostMessage( m_hWnd, WM_STOP, reinterpret_cast<WPARAM>( this ), 0 );\r\n}\r\n\r\nvoid\r\nITunesComThread::callbackIfStopped( void (*callback)() )\r\n{\r\n\tif ( !m_com )\r\n\t\tstartComThread();\r\n\r\n\tSendMessageCallback( m_hWnd, WM_IS_PLAYING, reinterpret_cast<WPARAM>( this ), 0, ITunesComThread::isPlayingCallback, reinterpret_cast<WPARAM>( callback ) );\r\n}\r\n\r\nbool\r\nITunesComThread::isPlaying()\r\n{\r\n\tbool isPlaying = true;\r\n\r\n\ttry\r\n\t{\r\n\t\tm_com->currentTrack();\r\n\t}\r\n\tcatch (...)\r\n\t{\r\n\t\tisPlaying = false;\r\n\t}\r\n\r\n\treturn isPlaying;\r\n}\r\n\r\nVOID\r\nITunesComThread::isPlayingCallback( HWND hwnd, UINT uMsg, ULONG_PTR dwData, LRESULT isPlaying )\r\n{\r\n\tvoid (*callback)() = reinterpret_cast<void (*)()>( dwData );\r\n\r\n\tif ( !isPlaying )\r\n\t\tcallback();\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::onDatabaseChanged( std::vector<ITunesEventInterface::ITunesIdSet> deletedObjects,\r\n                                    std::vector<ITunesEventInterface::ITunesIdSet> changedObjects )\r\n{\r\n/*\r\n    for ( int i = 0; i < changedObjects.size(); ++i )\r\n    {\r\n        ITunesEventInterface::ITunesIdSet ids = changedObjects.at( i );\r\n        ITunesTrack t = m_com->track( ids );\r\n    \r\n        if ( !t.isNull() )\r\n        {\r\n            LOGL( 3, \"Changed track: \" << t.toString() );\r\n        }\r\n    }\r\n*/\r\n}\r\n    \r\n\r\nvoid\r\nITunesComThread::onPlay( ITunesTrack track )\r\n{\r\n/*\r\n    LOGWL( 3, \"onPlay track: \" << track.toString() << \" \" << track.playCount() );\r\n    LOGWL( 3, \"onPlay m_lastTrack: \" << m_lastTrack.toString() << \" \" << m_lastTrack.initialPlayCount() );\r\n\r\n    if ( !track.isSameAs( m_lastTrack ) )\r\n    {\r\n        if ( m_loopMode )\r\n        {\r\n            // We sync here because otherwise we will miss looped tracks\r\n            // (the cunts don't emit a stopped when they exit the loop).\r\n            //\r\n            // They do however emit a stop if they are skipped. In that case\r\n            // it will have been synced in onStop and the m_lastTrack has been\r\n            // set to null. So only sync here if it's non-null.\r\n            //\r\n            // The remaining flaw in this system is that if the user presses\r\n            // stop on a looped track, we will not get a stop event. Therefore\r\n            // the playcounts for that track will not be synced until the user\r\n            // starts another track.\r\n            if ( !m_lastTrack.isNull() )\r\n            {\r\n                LOGL( 3, \"Leaving loop mode, syncing\" );\r\n\r\n                syncComTrackInThread( m_lastTrack );\r\n            }\r\n        }\r\n\r\n        // This stores the current playcount internally at this point\r\n        m_lastTrack = ExtendedITunesTrack::from( track );\r\n\r\n        m_loopMode = false;\r\n    }\r\n    else\r\n    {\r\n        // Don't sync when we're looping one track as iTunes event emissions are fucked.\r\n        LOGL( 3, \"Same track detected, loopmode = true\" );\r\n        m_loopMode = true;\r\n    }\r\n*/\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::onStop( ITunesTrack )\r\n{\r\n    //LOGWL( 3, \"onStop m_lastTrack: \" << m_lastTrack.toString() << \" \" << m_lastTrack.initialPlayCount() );\r\n    //LOGWL( 3, \"onStop current track: \" << m_com->currentTrack().toString() << \" \" << m_com->currentTrack().playCount() );\r\n    \r\n    // We compare the current track to last track here so as to prevent syncing when\r\n    // we're in 1x loop mode. Once iTunes changes to a different track we will sync.\r\n    // This conditional will also not hit when the user pressed stop on a track as iTunes\r\n    // considers the stopped track still current (it's still displayed in the iTunes\r\n    // current track window thingie). However, this is not a problem as the playcount\r\n    // hasn't increased in this case, so a sync isn't necessary.\r\n\r\n/*\r\n    if ( !m_lastTrack.isSameAs( m_com->currentTrack() ) )\r\n    {\r\n        // We sync here because otherwise we will miss the sync at end of playlist.\r\n        // We blank the m_lastTrack to prevent a double sync from happening when\r\n        // we come into onPlay after leaving loop mode by skipping.\r\n        syncComTrackInThread( m_lastTrack );\r\n        m_lastTrack = ExtendedITunesTrack();    \r\n    }\r\n    else\r\n        LOGL( 3, \"Same track, not syncing\" );\r\n*/    \r\n\r\n    // Why do we clear this here?\r\n    // If we don't, we know that we always have an m_lastTrack in onPlay and can compare\r\n    // to see if we're looping the same track.\r\n    //m_lastTrack = ExtendedITunesTrack();\r\n}\r\n\r\nvoid\r\nITunesComThread::doStop()\r\n{\r\n    //LOGWL( 3, \"onStop m_lastTrack: \" << m_lastTrack.toString() << \" \" << m_lastTrack.initialPlayCount() );\r\n    //LOGWL( 3, \"onStop current track: \" << m_com->currentTrack().toString() << \" \" << m_com->currentTrack().playCount() );\r\n    \r\n    // We compare the current track to last track here so as to prevent syncing when\r\n    // we're in 1x loop mode. Once iTunes changes to a different track we will sync.\r\n    // This conditional will also not hit when the user pressed stop on a track as iTunes\r\n    // considers the stopped track still current (it's still displayed in the iTunes\r\n    // current track window thingie). However, this is not a problem as the playcount\r\n    // hasn't increased in this case, so a sync isn't necessary.\r\n\r\n\tITunesTrack currentTrack;\r\n\t\r\n\ttry\r\n\t{\r\n\t\tcurrentTrack = m_com->currentTrack();\r\n\t}\r\n\tcatch (...)\r\n\t{\r\n\t}\r\n\r\n    if ( !m_lastTrack.isSameAs( currentTrack ) )\r\n    {\r\n        // We sync here because otherwise we will miss the sync at end of playlist.\r\n        // We blank the m_lastTrack to prevent a double sync from happening when\r\n        // we come into onPlay after leaving loop mode by skipping.\r\n        syncComTrackInThread( m_lastTrack );\r\n        m_lastTrack = ExtendedITunesTrack();    \r\n    }\r\n    else\r\n        LOGL( 3, \"Same track, not syncing\" );\r\n    \r\n\r\n    // Why do we clear this here?\r\n    // If we don't, we know that we always have an m_lastTrack in onPlay and can compare\r\n    // to see if we're looping the same track.\r\n    //m_lastTrack = ExtendedITunesTrack();\r\n}\r\n\r\n\r\n\r\nvoid\r\nITunesComThread::onTrackChanged( ITunesTrack track )\r\n{\r\n    // This is fired for \"joined CD tracks\" (see Advanced menu).\r\n    // However, iTunes doesn't maintain playcounts for CD tracks so we\r\n    // don't need to do any syncing in here.\r\n    \r\n    // The other thing that will cause this event to fire is if the user\r\n    // changed the metadata of a track. This should never cause a playcount\r\n    // change either so no need to sync. We should probably update our\r\n    // database with the new path here though. TODO!\r\n\r\n    //LOGWL( 3, \"onTrackChanged track: \" << track.toString() << \" \" << track.playCount() );\r\n    //LOGWL( 3, \"onTrackChanged m_lastTrack: \" << m_lastTrack.toString() << \" \" << m_lastTrack.initialPlayCount() );\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::onAboutToPromptUserToQuit()\r\n{\r\n    // Terminate the thread's message loop\r\n    PostQuitMessage( 0 );\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::onComCallsDisabled()\r\n{\r\n    LOGL( 3, \"\" );\r\n\r\n    m_comEnabled = false;\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::onComCallsEnabled()\r\n{\r\n    LOGL( 3, \"\" );\r\n\r\n    m_comEnabled = true;\r\n\r\n    syncQueue();\r\n}\r\n\r\nunsigned\r\nITunesComThread::eventLoop()\r\n{\r\n    setupWndProc();\r\n\r\n    UINT returnCode = 0;\r\n    try\r\n    {\r\n        // This call will cause the bootstrap to happen first time it's called\r\n        m_db = new ITunesPlaysDatabase();\r\n        \r\n        // This might take a long time if iTunes isn't responding to the CoCreateInstance\r\n        m_com = new ITunesComWrapper( this );\r\n        \r\n        try { LOGWL( 3, \"iTunes version: \" << m_com->iTunesVersion() ); }\r\n        catch ( ITunesException& ) { }\r\n\r\n        BOOL messageVal;\r\n        MSG message;\r\n        while ( ( messageVal = GetMessage( &message, NULL, 0, 0 ) ) != 0 )\r\n        {\r\n            if ( messageVal == -1 )\r\n            {\r\n                LOGL( 3, \"GetMessage error: \" << GetLastError() );\r\n                continue;\r\n            }\r\n            else\r\n            {\r\n                TranslateMessage( &message );\r\n                DispatchMessage( &message );\r\n            }\r\n        }\r\n\r\n        // This is the wParam of the WM_QUIT message\r\n        returnCode = static_cast<UINT>( message.wParam );\r\n    }\r\n    catch ( ITunesException& e )\r\n    {\r\n        LOGL( 1, \"FATAL ERROR: \" << e.what() );\r\n    }\r\n\r\n    delete m_com;\r\n\tm_com = 0;\r\n    delete m_db;\r\n\tm_db = 0;\r\n\r\n    LOGL( 3, \"Thread shutting down\" );\r\n\r\n    return returnCode;\r\n}\r\n\r\n\r\nbool\r\nITunesComThread::setupWndProc()\r\n{\r\n    WNDCLASSEX wndClass;\r\n    wndClass.cbSize = sizeof( wndClass );\r\n    wndClass.style = NULL;\r\n    wndClass.lpfnWndProc = ITunesComThread::wndProc;\r\n    wndClass.cbClsExtra = 0;\r\n    wndClass.cbWndExtra = 0;\r\n    wndClass.hInstance = GetModuleHandle( NULL );\r\n    wndClass.hIcon = NULL;\r\n    wndClass.hCursor = NULL;\r\n    wndClass.hbrBackground = NULL;\r\n    wndClass.lpszMenuName = \"\";\r\n    wndClass.lpszClassName = \"ITunesComThreadClass\";\r\n    wndClass.hIconSm = NULL;\r\n\r\n    ATOM regClassResult = RegisterClassEx( &wndClass );\r\n    \r\n    if ( regClassResult == 0 )\r\n    {\r\n        LOGL( 1, \"RegisterClassEx failed: \" << regClassResult );\r\n        LOGL( 1, \"Last Error Code: \" << GetLastError() );\r\n        return false;\r\n    }\r\n    \r\n    m_hWnd = CreateWindow( \"ITunesComThreadClass\",\r\n                           \"ITunesComThreadWindow\",\r\n                           NULL, 0, 0, 0, 0, NULL, NULL, NULL, NULL );\r\n \r\n    if ( m_hWnd == NULL )\r\n    {\r\n        LOGL( 1, \"CreateWindow failed: \" << m_hWnd );\r\n        LOGL( 1, \"Last Error Code: \" << GetLastError() );\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n\r\n// static\r\nLRESULT CALLBACK \r\nITunesComThread::wndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )\r\n{\r\n    if ( uMsg == WM_SYNC_PLAYS_DB )\r\n    {\r\n        ITunesComThread* instance = reinterpret_cast<ITunesComThread*>( wParam );\r\n        instance->syncVisTrackInThread();\r\n        return 0;\r\n    }\r\n\telse if ( uMsg == WM_STOP )\r\n    {\r\n        ITunesComThread* instance = reinterpret_cast<ITunesComThread*>( wParam );\r\n        instance->doStop();\r\n        return 0;\r\n    }\r\n\telse if ( uMsg == WM_IS_PLAYING )\r\n    {\r\n        ITunesComThread* instance = reinterpret_cast<ITunesComThread*>( wParam );\r\n        return instance->isPlaying();\r\n    }\r\n    else if ( uMsg == WM_TIMER )\r\n    {\r\n        ITunesComThread* instance = reinterpret_cast<ITunesComThread*>( wParam );\r\n        instance->syncVisTrackInThread();\r\n        return 0;\r\n    }\r\n    else\r\n    {\r\n        return DefWindowProc( hwnd, uMsg, wParam, lParam );\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::syncComTrackInThread( const ExtendedITunesTrack& changedTrack )\r\n{\r\n    try\r\n    {\r\n        if ( !changedTrack.isNull() )\r\n        {\r\n            // This is used if we sync from the COM events (which we currently don't)\r\n            if ( !m_db->sync( changedTrack ) )\r\n            {\r\n                LOGWL( 2, \"ITunesComThread failed to update the local database for: \"\r\n                         << changedTrack.toString() );\r\n            }\r\n\r\n\t\t\tif ( !m_db->syncOld( changedTrack ) )\r\n            {\r\n                LOGWL( 2, \"ITunesComThread failed to update the old local database for: \"\r\n                         << changedTrack.toString() );\r\n            }\r\n        }\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        // Ignore this track\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::syncVisTrackInThread()\r\n{\r\n    if ( m_comEnabled )\r\n    {\r\n        ExtendedITunesTrack currentComTrack;\r\n        try\r\n        {\r\n            // TODO: potential sanity checking of this track against the m_visTrackToSync\r\n            currentComTrack = ExtendedITunesTrack::from( m_com->currentTrack() );\r\n\r\n            if ( !m_lastTrack.isNull() )\r\n            {\r\n                // HACK WARNING: all this crap was introduced last minute when we found that iTunes\r\n                // had stopped always returning the new playcount on track change. This logic has\r\n                // got a bit too complicated, refactor.\r\n\r\n                DWORD elapsed = GetTickCount() - m_timeOfLastTrackChange;\r\n                \r\n                if ( !m_retrying )\r\n                {\r\n                    // To avoid lots of superfluous sync attempts on repeated skipping, we\r\n                    // don't bother trying to sync if less than 1s has passed.\r\n                    m_timeOfLastTrackChange = GetTickCount();\r\n                    if ( elapsed < ( 1 * 1000 ) )\r\n                    {\r\n                        LOGL( 3, \"Less than 1 second since last change, won't sync\" );\r\n\r\n                        goto refreshCurrentTrack;\r\n                    }\r\n                }\r\n                else\r\n                {\r\n                    // Check if we've been retrying for too long and should give up.\r\n                    if ( elapsed > ( 15 * 1000 ) )\r\n                    {\r\n                        LOGL( 3, \"Retried for 15 seconds and still no diff. Give up.\" );\r\n\r\n                        KillTimer( m_hWnd, (UINT_PTR)this );\r\n                        m_retrying = false;\r\n\r\n                        goto refreshCurrentTrack;\r\n                    }\r\n                }\r\n\r\n                // Check if the diff is 0 and if so, go into retry mode. We have to do this\r\n                // because iTunes doesn't seem to update its internal playcount immediately\r\n                // after the track finished\r\n                int diff = 0;\r\n                try\r\n                {\r\n                    diff = m_lastTrack.playCountDifference();\r\n                }\r\n                catch( PlayCountException& )\r\n                {\r\n                    LOGL( 2, \"Playcount Exception when reading initial diff, can't sync\" );\r\n                    diff = 0;\r\n                }\r\n\r\n                if ( diff == 0 )\r\n                {\r\n                    if ( !m_retrying )\r\n                    {\r\n                        LOGL( 3, \"Got a diff of 0, starting retry timer\" );\r\n                        SetTimer( m_hWnd, (UINT_PTR)this, 1000, 0 ); // 1-sec timer                \r\n                        m_retrying = true;\r\n                        m_retryAttempts = 0;\r\n                    }\r\n                    else\r\n                    {\r\n                        m_retryAttempts++;\r\n                    }\r\n                    return;            \r\n                }\r\n                else\r\n                {\r\n                    if ( m_retrying )\r\n                        LOGL( 3, \"Got a diff of \" << diff << \" after \" << m_retryAttempts << \" secs\" );\r\n\r\n                    KillTimer( m_hWnd, (UINT_PTR)this );\r\n                    m_retrying = false;\r\n                    m_retryAttempts = 0;\r\n                }\r\n\r\n                // Sync previous track\r\n                if ( !m_db->sync( m_lastTrack ) )\r\n                {\r\n                    LOGWL( 3, \"ITunesComThread failed to update the local database for: \"\r\n                             << m_lastTrack.toString() );\r\n                }\r\n\r\n\t\t\t\tif ( !m_db->syncOld( m_lastTrack ) )\r\n                {\r\n                    LOGWL( 3, \"ITunesComThread failed to update the old local database for: \"\r\n                             << m_lastTrack.toString() );\r\n                }\r\n            }\r\n        }\r\n        catch ( ITunesException& e )\r\n        {\r\n            LOGL( 2, e.what() );\r\n        }\r\n\r\n      refreshCurrentTrack:\r\n        LOGWL( 3, \"Current track: \" << currentComTrack.toString() );\r\n        m_lastTrack = currentComTrack;\r\n\r\n    }\r\n    else // COM is disabled\r\n    {\r\n        if ( m_retrying )\r\n        {\r\n            KillTimer( m_hWnd, (UINT_PTR)this );\r\n            m_retrying = false;\r\n            return;\r\n        }\r\n\r\n        // This happens when COM is unavailable due to a modal dialog displaying\r\n        // in iTunes. We store the track on a queue for later processing.\r\n        VisualPluginTrack lastVisTrack;\r\n        EnterCriticalSection( &m_critSect );\r\n        lastVisTrack = m_visTrackToSync;\r\n        LeaveCriticalSection( &m_critSect );\r\n\r\n        LOGWL( 3, \"COM is disabled, putting \" << lastVisTrack.track << \" in queue\" );\r\n        m_visTrackQueue.push_back( lastVisTrack );\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nITunesComThread::syncQueue()\r\n{\r\n    LOGL( 3, \"Size of vis track queue before weeding: \" << m_visTrackQueue.size() );\r\n\r\n    // Weed out dupes in m_visTrackQueue and only keep the one with the lowest playcount.\r\n    // m_lastTrack also needs to be taken into account.\r\n    VisualPluginTrack current;\r\n    current.path = m_lastTrack.path();\r\n    size_t i = -1; // m_lastTrack is index -1\r\n    while ( true ) \r\n    {\r\n        // Search for dupes of current track in the remainder (hence i+1) of list\r\n        for ( size_t j = i + 1; j < m_visTrackQueue.size(); /* nowt */ )\r\n        {\r\n            if ( current.path == m_visTrackQueue.at( j ).path )\r\n                m_visTrackQueue.erase( m_visTrackQueue.begin() + j );\r\n            else\r\n                j++;\r\n        }\r\n    \r\n        i++;\r\n        if ( i < m_visTrackQueue.size() )\r\n            current = m_visTrackQueue.at( i );\r\n        else\r\n            break;    \r\n    }\r\n\r\n    LOGL( 3, \"Size of vis track queue after weeding: \" << m_visTrackQueue.size() );\r\n\r\n\r\n    // Sync tracks that were put on queue while COM was off\r\n    for ( size_t n = 0; n < m_visTrackQueue.size(); ++n )\r\n    {\r\n        try\r\n        {\r\n            VisualPluginTrack vpt = m_visTrackQueue.at( n );\r\n     \r\n            // Now, we need to try and locate this track in the iTunes library\r\n            // to find its current playcount.\r\n            vector<ITunesTrack> results =\r\n                m_com->searchForTrack( ITPlaylistSearchFieldSongNames, vpt.track );\r\n\r\n            ITunesTrack ourGuy;\r\n            if ( results.size() == 0 )\r\n            {\r\n                // Eh?\r\n                LOGWL( 2, \"Couldn't find matching track in db for \" << vpt.track << \". Result size 0.\" );\r\n                continue;\r\n            }\r\n            else if ( results.size() == 1 )\r\n            {\r\n                // We've found our guy\r\n                ourGuy = results.at( 0 );\r\n            }\r\n            else\r\n            {\r\n                // Need to narrow it down, let's look at the path too\r\n                for ( size_t i = 0; i < results.size(); ++i )\r\n                {\r\n                    ITunesTrack currentResult = results.at( i );\r\n                    if ( currentResult.path() == vpt.path )\r\n                    {\r\n                        // Found him\r\n                        ourGuy = currentResult;\r\n                        break;\r\n                    }\r\n                }\r\n                \r\n                if ( ourGuy.isNull() )\r\n                {\r\n                    // Not much we can do, we'll have to drop the diff for this track\r\n                    LOGWL( 2, \"Couldn't find matching track in db for \" << vpt.track << \". Path not found.\" );\r\n                    continue;\r\n                }\r\n            }\r\n\r\n            ExtendedITunesTrack diffTrack = ExtendedITunesTrack::from( ourGuy ); // throws\r\n\r\n            diffTrack.setInitialPlaycount( vpt.playCount );\r\n            if ( !m_db->sync( diffTrack ) )\r\n            {\r\n                LOGWL( 2, \"ITunesComThread failed to update the local database for: \"\r\n                         << diffTrack.toString() );\r\n            }\r\n\r\n\t\t\tif ( !m_db->syncOld( diffTrack ) )\r\n            {\r\n                LOGWL( 2, \"ITunesComThread failed to update the old local database for: \"\r\n                         << diffTrack.toString() );\r\n            }\r\n        }\r\n        catch ( ITunesException& )\r\n        {\r\n            LOGL( 2, \"ITunesException when trying to sync one of the tracks in the queue, ignoring track.\" );\r\n        }\r\n\r\n    }\r\n    \r\n    m_visTrackQueue.clear();\r\n\r\n    // This will cause the old m_lastTrack which we still have kicking about\r\n    // to get synced and the current track stored in m_lastTrack.\r\n    syncVisTrackInThread();\r\n}\r\n\r\n#endif // WIN32\r\n\r\n"
  },
  {
    "path": "plugins/iTunes/ITunesComThread.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef ITUNESCOMTHREAD_H\r\n#define ITUNESCOMTHREAD_H\r\n\r\n#ifdef WIN32\r\n\r\n#include \"ITunesTrack.h\"\r\n#include \"ITunesEventInterface.h\"\r\n\r\n#include <windows.h>\r\n\r\n#include <vector>\r\n#include <string>\r\n\r\n/// Used to pass the track info we get from the visual plugin in one chunk\r\nstruct VisualPluginTrack\r\n{\r\n    std::wstring artist;\r\n\tstd::wstring albumArtist;\r\n    std::wstring track;\r\n    std::wstring album;\r\n    std::wstring path;\r\n    unsigned long playCount;\r\n};\r\n\r\n\r\n/** @author Erik Jalevik <erik@last.fm>\r\n  * @brief Sets up a thread which internally uses the ITunesComWrapper.\r\n  *        This is because we can't make COM calls on the iTunes main thread\r\n  *        whilst inside an iTunes plugin. It also acts as the event sink\r\n  *        for any events iTunes emits.\r\n  */\r\nclass ITunesComThread : public ITunesEventInterface\r\n{\r\npublic:\r\n    ITunesComThread();\r\n    ~ITunesComThread();\r\n\r\n\tvoid callbackIfStopped( void (*callback)() );\r\n\r\n    // But because the COM interface has a bug which delivers wonky events\r\n    // when looping a track, we use this function to sync instead, which is\r\n    // driven by the visualizer plugin stop/start events.\r\n    void syncTrack( const VisualPluginTrack& vpt );\r\n\tvoid stop();\r\n\r\nprivate:\r\n\t// These are the COM event handlers\r\n    virtual void\r\n    onDatabaseChanged( std::vector<ITunesEventInterface::ITunesIdSet> deletedObjects,\r\n                       std::vector<ITunesEventInterface::ITunesIdSet> changedObjects );\r\n    virtual void onPlay( ITunesTrack );\r\n    virtual void onStop( ITunesTrack );\r\n    virtual void onTrackChanged( ITunesTrack );\r\n    virtual void onAboutToPromptUserToQuit();\r\n    virtual void onComCallsDisabled();\r\n    virtual void onComCallsEnabled();\r\n\r\n\tvoid startComThread();\r\n    \r\n    static unsigned __stdcall\r\n    threadMain( LPVOID p )\r\n    {\r\n        return reinterpret_cast<ITunesComThread*>(p)->eventLoop();\r\n    }\r\n\r\n    /// Eternal event loop for handling action messages from other threads\r\n    unsigned eventLoop();\r\n\r\n    /// We need a window with a WndProc for the iTunes event sink to work\r\n    bool setupWndProc();\r\n    static LRESULT CALLBACK wndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam );\r\n\r\n    void syncComTrackInThread( const ExtendedITunesTrack& track );\r\n    void syncVisTrackInThread();\r\n\tbool isPlaying();\r\n\tstatic VOID CALLBACK isPlayingCallback( HWND hwnd, UINT uMsg, ULONG_PTR dwData, LRESULT lResult );\r\n\r\n    /// Syncs tracks that were put on the queue while COM was disabled\r\n    void syncQueue();\r\n\tvoid doStop();\r\n\r\n    class ITunesComWrapper* m_com;\r\n    class ITunesPlaysDatabase* m_db;\r\n    \r\n    ExtendedITunesTrack m_lastTrack;\r\n    bool m_comEnabled;\r\n\r\n    DWORD m_timeOfLastTrackChange;\r\n    bool m_retrying;\r\n    int m_retryAttempts;\r\n\r\n    CRITICAL_SECTION m_critSect;\r\n    VisualPluginTrack m_visTrackToSync;\r\n    std::vector<VisualPluginTrack> m_visTrackQueue;\r\n\r\n    HANDLE m_threadHandle;\r\n    HWND m_hWnd;\r\n};\r\n\r\n#endif // WIN32\r\n\r\n#endif // ITUNESCOMTHREAD_H"
  },
  {
    "path": "plugins/iTunes/ITunesComWrapper.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifdef WIN32\r\n\r\n#include \"ITunesComWrapper.h\"\r\n#include \"plugins/scrobsub/EncodingUtils.h\"\r\n#include \"common/c++/Logger.h\"\r\n#include <comutil.h>\r\n#include <process.h>\r\n#include <iostream>\r\n#include <sstream>\r\n#include <cassert>\r\n\r\nusing namespace std;\r\n\r\nTheAtlModule* g_atlModule = NULL;\r\n\r\n   \r\n/******************************************************************************\r\n    ITunesComWrapper\r\n******************************************************************************/\r\nITunesComWrapper::ITunesComWrapper(\r\n    ITunesEventInterface* handler ) :\r\n        m_iTunesApp( 0 ),\r\n        m_allTracks( 0 ),\r\n        m_trackCount( -1 ),\r\n        m_sink( 0 ),\r\n        m_sinkAsUnknown( 0 ),\r\n        m_sinkId( 0 )\r\n{\r\n    initialiseCom(); // throws\r\n\r\n    if ( handler )\r\n    {\r\n        try\r\n        { \r\n            connectSink( handler );\r\n        }\r\n        catch ( ITunesException& )\r\n        {\r\n            // Just carry on if this fails, we'll get no events but the other stuff will work\r\n        }\r\n    }\r\n\r\n    libraryTrackCount(); // throws\r\n}\r\n\r\n\r\nITunesComWrapper::~ITunesComWrapper()\r\n{\r\n    uninitialiseCom();\r\n}\r\n    \r\n\r\nlong\r\nITunesComWrapper::libraryTrackCount()\r\n{\r\n    // Can't use isValid here as it also checks the m_trackCount and m_allTracks\r\n    // which this method initialises when called from the ctor. Bad class design.\r\n    if ( m_iTunesApp == 0 )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    IITLibraryPlaylist* playlist;\r\n    HRESULT res = m_iTunesApp->get_LibraryPlaylist( &playlist );\r\n    handleComResult( res, L\"Failed to get iTunes library playlist\" );\r\n\r\n    if ( !m_allTracks )\r\n    {\r\n        res = playlist->get_Tracks( &m_allTracks );\r\n        try\r\n        {\r\n            handleComResult( res, L\"Failed to get iTunes library track collection\" );\r\n        }\r\n        catch ( ITunesException& )\r\n        {\r\n            m_allTracks = 0;\r\n            playlist->Release();\r\n            throw;\r\n        }\r\n    }\r\n\r\n    res = m_allTracks->get_Count( &m_trackCount );\r\n    try\r\n    {\r\n        handleComResult( res, L\"Failed to get iTunes library track count\" );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        m_trackCount = -1;\r\n        playlist->Release();\r\n        throw;\r\n    }\r\n\r\n    playlist->Release();\r\n\r\n    return m_trackCount;\r\n}\r\n\r\nvoid\r\nITunesComWrapper::setPersistentIDForTrack( ITunesTrack& t, IITTrack* track )\r\n{\r\n    VARIANT variant;\r\n    VariantInit( &variant );\r\n    variant.pdispVal = reinterpret_cast<IDispatch*>( track );\r\n    variant.vt = VT_DISPATCH;\r\n\r\n    long high = 0;\r\n    long low = 0;\r\n    HRESULT res = m_iTunesApp->get_ITObjectPersistentIDHigh( &variant, &high );\r\n    if ( res == S_OK )\r\n        res = m_iTunesApp->get_ITObjectPersistentIDLow( &variant, &low );\r\n\r\n    if ( res == S_OK )\r\n    {\r\n        wstringstream ss;\r\n        ss.fill( '0' );\r\n        ss.width( 8 );\r\n        ss << hex << high << low;\r\n        t.setPersistentId( ss.str() );\r\n    }\r\n    else\r\n    {\r\n        LOGW( 2, \"Failed to get persistent ID\" );\r\n    }\r\n}\r\n\r\nITunesTrack\r\nITunesComWrapper::track( long idx )\r\n{\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    IITTrack* track;\r\n    HRESULT res = m_allTracks->get_Item( idx + 1, &track ); // COM arrays are 1-based\r\n    handleComResult( res, L\"Failed to get track\" );\r\n        \r\n    // IITTrack pointer is Released by the ITunesTrack.\r\n    // Won't throw if the track has no path.\r\n    ITunesTrack t( track );\r\n    setPersistentIDForTrack( t, track );\r\n    return t;\r\n}\r\n\r\n\r\nIITPlaylist*\r\nITunesComWrapper::iPodLibraryPlaylist()\r\n{\r\n    HRESULT h;\r\n    #define HANDLE_COM_FAIL( x ) h = ( x ); handleComResult( h, L#x )\r\n\r\n    IITSourceCollection* sources;\r\n    HANDLE_COM_FAIL( m_iTunesApp->get_Sources( &sources ) );\r\n\r\n    long n;\r\n    try\r\n    {\r\n        HANDLE_COM_FAIL( sources->get_Count( &n ) );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        sources->Release();\r\n        throw;\r\n    }\r\n\r\n    IITPlaylist* playlist = NULL;\r\n    for( int i = 1; i < n + 1 && !playlist; ++i )\r\n    {\r\n        IITSource* source = NULL;\r\n        IITPlaylistCollection* playlists = NULL;\r\n        try\r\n        {\r\n            HANDLE_COM_FAIL( sources->get_Item( i, &source ) );\r\n\r\n            ITSourceKind kind;\r\n            HANDLE_COM_FAIL( source->get_Kind( &kind ) );\r\n            \r\n            if ( kind == ITSourceKindIPod )\r\n            {\r\n                HANDLE_COM_FAIL( source->get_Playlists( &playlists ) );\r\n                            \r\n                HANDLE_COM_FAIL( playlists->get_Item( 1, &playlist ) );\r\n\r\n                BSTR name;\r\n                HANDLE_COM_FAIL( playlist->get_Name( &name ) );\r\n\r\n                LOGW( 3, \"Playlist name: \" << bstrToWString( name ) );\r\n            }\r\n        }\r\n        catch ( ITunesException& )\r\n        {\r\n            // We'll just continue to the next source\r\n        }\r\n        \r\n        if ( source != NULL ) source->Release();\r\n        if ( playlists != NULL ) playlists->Release();\r\n    }\r\n\r\n    sources->Release();\r\n\r\n    if ( playlist == NULL )\r\n        throw ITunesException( \"No iPod library found\" );\r\n\r\n    return playlist;\r\n}\r\n\r\n\r\nlong\r\nITunesComWrapper::iPodLibraryTrackCount()\r\n{\r\n    IITPlaylist* playlist = iPodLibraryPlaylist();\r\n\r\n    HRESULT res = playlist->get_Tracks( &m_allTracks );\r\n    try\r\n    {\r\n        handleComResult( res, L\"Failed to get iPod library track collection\" );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        m_allTracks = 0;\r\n        playlist->Release();\r\n        throw;\r\n    }\r\n\r\n    m_trackCount = -1;\r\n    res = m_allTracks->get_Count( &m_trackCount );\r\n    try\r\n    {\r\n        handleComResult( res, L\"Failed to get iPod library track collection\" );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        playlist->Release();\r\n        throw;\r\n    }\r\n\r\n    playlist->Release();\r\n\r\n    return m_trackCount;\r\n}\r\n\r\n\r\nITunesTrack\r\nITunesComWrapper::track( const ITunesEventInterface::ITunesIdSet& ids )\r\n{\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    IITObject* obj;\r\n    HRESULT res = m_iTunesApp->GetITObjectByID( ids.sourceId, ids.playlistId, ids.trackId, ids.dbId, &obj );\r\n    handleComResult( res, L\"Failed to get object from ID set\" );\r\n        \r\n    IITTrack* track = 0;\r\n    res = obj->QueryInterface( IID_IITTrack, (void**)&track );\r\n    if ( res != S_OK || track == 0 )\r\n    {\r\n        // Not a track object, ignore\r\n        obj->Release();\r\n        handleComResult( res, L\"ID set didn't represent a track\" );\r\n    }\r\n\r\n    // IITTrack pointer is Released by the ITunesTrack.\r\n    // This ctor can't throw.\r\n    ITunesTrack t( track );\r\n    setPersistentIDForTrack( t, track );\r\n    return t;\r\n}\r\n\r\n    \r\nITunesTrack\r\nITunesComWrapper::currentTrack()\r\n{\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    IITTrack* track = NULL;\r\n    HRESULT res = m_iTunesApp->get_CurrentTrack( &track );\r\n    handleComResult( res, L\"Failed to get current track\" );\r\n        \r\n    // IITTrack pointer is Released by the ITunesTrack\r\n    // This ctor can't throw.\r\n    ITunesTrack t( track );\r\n    setPersistentIDForTrack( t, track );\r\n    return t;\r\n}\r\n\r\n\r\nITPlayerState\r\nITunesComWrapper::playerState()\r\n{\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    ITPlayerState state;\r\n    HRESULT res = m_iTunesApp->get_PlayerState( &state );\r\n    handleComResult( res, L\"Failed to get player state\" );\r\n\r\n    return state;\r\n}\r\n\r\n\r\nlong\r\nITunesComWrapper::playerPosition()\r\n{\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    long pos;\r\n    HRESULT res = m_iTunesApp->get_PlayerPosition( &pos );\r\n    handleComResult( res, L\"Failed to get player pos\" );\r\n        \r\n    return pos;\r\n}\r\n\r\n\r\nwstring\r\nITunesComWrapper::iTunesVersion()\r\n{\r\n    if ( !isValid() )\r\n        return L\"\";\r\n\r\n    BSTR v;\r\n    HRESULT res = m_iTunesApp->get_Version( &v );\r\n    if ( !handleComResult( res, L\"Failed to get iTunes version\" ) )\r\n        return L\"\";\r\n        \r\n    return bstrToWString( v );\r\n}\r\n\r\n\r\nvector<ITunesTrack>\r\nITunesComWrapper::searchForTrack( ITPlaylistSearchField searchField, wstring searchTerm )\r\n{\r\n    vector<ITunesTrack> results;\r\n\r\n    if ( !isValid() )\r\n        throw ITunesException( \"COM not initialised\" );\r\n\r\n    IITLibraryPlaylist* playlist;\r\n    HRESULT res = m_iTunesApp->get_LibraryPlaylist( &playlist );\r\n    handleComResult( res, L\"Failed to get iTunes library playlist\" );\r\n\r\n    _bstr_t bTerm( searchTerm.c_str() );\r\n    IITTrackCollection* tc;\r\n    res = playlist->Search( bTerm, searchField, &tc );\r\n    try\r\n    {\r\n        handleComResult( res, L\"Failed to search iTunes library\" );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        playlist->Release();\r\n        throw;\r\n    }\r\n        \r\n    if ( tc == 0 )\r\n    {\r\n        playlist->Release();\r\n        return results;\r\n    }\r\n        \r\n    long count;\r\n    tc->get_Count( &count );\r\n    try\r\n    {\r\n        handleComResult( res, L\"Failed to get count of search results\" );\r\n    }\r\n    catch ( ITunesException& )\r\n    {\r\n        playlist->Release();\r\n        throw;\r\n    }\r\n    \r\n    for ( long i = 1; i < ( count + 1 ); ++i )\r\n    {\r\n        try\r\n        {\r\n            IITTrack* track; \r\n            tc->get_Item( i, &track );\r\n            handleComResult( res, L\"Failed to get track out of search results\" );\r\n\r\n            ITunesTrack t( track );\r\n\t\t\tsetPersistentIDForTrack( t, track );\r\n            results.push_back( t );\r\n        }\r\n        catch ( ITunesException& )\r\n        {\r\n            // Just move on to the next\r\n        }\r\n    }\r\n    \r\n    playlist->Release();\r\n    return results;\r\n}\r\n\r\n\r\nvoid\r\nITunesComWrapper::initialiseCom()\r\n{\r\n    LOG( 3, \"Calling CoInitializeEx...\" );\r\n\r\n    // Init COM\r\n    HRESULT res = CoInitializeEx( NULL, COINIT_APARTMENTTHREADED );\r\n\r\n    // S_FALSE means COM has already been initialised on this thread.\r\n    if ( res != S_OK && res != S_FALSE )\r\n    {\r\n        LOG( 2, \"Failed to initialise COM. Return: \" << res );\r\n    }\r\n    else\r\n    {\r\n        bool retry = false;\r\n        do\r\n        {\r\n            LOG( 3, \"Calling CoCreateInstance...\" );\r\n\r\n            HRESULT res = 0;\r\n            res = CoCreateInstance( CLSID_iTunesApp, // CLSID\r\n                                    NULL, // not part of aggregate\r\n                                    CLSCTX_LOCAL_SERVER, // server is on same machine\r\n                                    IID_IiTunes, // specifies what interface we want the pointer to adhere to (a COM object can implement more than one)\r\n                                    (PVOID*)&m_iTunesApp ); // the pointer to fill\r\n\r\n            if ( res == S_OK )\r\n            {\r\n                // We're all set\r\n                retry = false;\r\n            }\r\n            else if ( res == CO_E_SERVER_EXEC_FAILURE )\r\n            {\r\n                // This seems to happen if there is a modal dialog being shown in iTunes\r\n                // or some other delay has occurred. Retrying should do the trick.\r\n                LOG( 2, \"Got CO_E_SERVER_EXEC_FAILURE, retrying...\" );\r\n                retry = true;\r\n            }\r\n            else\r\n            {\r\n                logComError( res, L\"Failed to get hold of iTunes instance via COM\" );\r\n                m_iTunesApp = 0;\r\n                retry = false;\r\n            }\r\n        \r\n        } while ( retry );\r\n        \r\n        if ( m_iTunesApp == 0 )\r\n            throw ITunesException( \"Failed to get hold of iTunes instance via COM\" );\r\n\r\n        LOG( 3, \"Value of iTunes ptr: \" << m_iTunesApp );\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nITunesComWrapper::connectSink( ITunesEventInterface* handler )\r\n{\r\n    LOG( 3, \"Connecting sink\" );\r\n    \r\n    // Init COM the ATL way, needed for the CComObject to work\r\n    g_atlModule = new TheAtlModule();\r\n\r\n    // Instantiate our sink object. By wrapping it in a CComObject, we get all\r\n    // the IUnknown plumbing for free.\r\n    HRESULT res = CComObject<ITunesComEventSink>::CreateInstance( &m_sink );\r\n    handleComResult( res, L\"Failed to create event sink object\" );\r\n\r\n    m_sink->setHandler( handler );\r\n\r\n    // Query our own sink object to see if it supports the IUnknown interface (which it\r\n    // obviously does) and return a reference to it as an IUnknown*.\r\n    res = m_sink->QueryInterface( IID_IUnknown, reinterpret_cast<void**>( &m_sinkAsUnknown ) );\r\n    handleComResult( res, L\"Getting IUnknown from ITunesComEventSink failed\" );\r\n\r\n    // Hook up the outgoing events interface from iTunes with our own sink, and get hold\r\n    // of the ID so we can unadvise at shutdown.\r\n    res = AtlAdvise( m_iTunesApp, m_sinkAsUnknown, DIID__IiTunesEvents, &m_sinkId );\r\n    handleComResult( res, L\"AtlAdvise failed\" );\r\n}\r\n\r\n\r\nvoid\r\nITunesComWrapper::uninitialiseCom()\r\n{\r\n    LOG( 3, \"Uninitialising COM...\" );\r\n\r\n    // Don't do anything unless we managed to initialise the iTunes pointer correctly\r\n    if ( m_iTunesApp != 0 )\r\n    {\r\n        // Release everything in reverse order to what we initialised it in\r\n        if ( m_sinkId != 0 )\r\n        {\r\n            HRESULT res = AtlUnadvise( m_iTunesApp, DIID__IiTunesEvents, m_sinkId );\r\n            try\r\n            {\r\n                handleComResult( res, L\"AtlUnadvise failed but what can we do except sigh, shrug our shoulders and move on.\" );\r\n            }\r\n            catch ( ITunesException& )\r\n            {}\r\n        }\r\n\r\n        if ( m_sinkAsUnknown != 0 )\r\n            m_sinkAsUnknown->Release();\r\n\r\n        if ( g_atlModule != 0 )\r\n        {\r\n            delete g_atlModule;\r\n            g_atlModule = 0;\r\n        }\r\n\r\n        if ( m_allTracks != 0 )\r\n            m_allTracks->Release();\r\n\r\n        m_iTunesApp->Release();\r\n    }\r\n\r\n    // Close COM, returns no error\r\n    CoUninitialize();\r\n\r\n    LOG( 3, \"CoUninitialize done\" );\r\n}\r\n\r\n\r\nwstring\r\nITunesComWrapper::bstrToWString( BSTR bstr )\r\n{\r\n    if ( bstr == 0 )\r\n        return wstring();\r\n    else\r\n    {\r\n        // This wraps the BSTR and the _b_str_t class will take care of\r\n        // deallocating its memory so we don't have to do it.\r\n        _bstr_t bstrCls( bstr, false );\r\n        return wstring( bstrCls );\r\n    }\r\n\r\n/* We used to convert it to Utf8\r\n    unsigned int len = bstrCls.length();\r\n\r\n    char* utf8buf = new char[len * 4];\r\n    memset( utf8buf, 0, len * 4 );\r\n\r\n    // _bstr_t has an operator wchar_t*() which will be used here\r\n    EncodingUtils::UnicodeToUtf8( bstrCls, len, utf8buf, len * 4 );\r\n    string s( utf8buf );\r\n\r\n    delete[] utf8buf;\r\n    \r\n    return s;\r\n*/\r\n}\r\n\r\n// HACK: This shouldn't be here but there isn't really anywhere else to put\r\n// it right now unless we want to create a utility class inside common.\r\nstring\r\nwstring2string( wstring ws )\r\n{\r\n    string s;\r\n    for ( size_t i = 0; i < ws.size(); ++i )\r\n    {\r\n        unsigned short us = ws.at( i );\r\n        char c = (char)us;\r\n        s += c;\r\n    }\r\n    return s;\r\n}\r\n\r\n\r\nbool\r\nITunesComWrapper::handleComResult( HRESULT res, wstring err )\r\n{\r\n    if ( res == S_OK )\r\n    {\r\n        return false;\r\n    }\r\n    else\r\n    {\r\n        if ( err.empty() )\r\n            err = L\"Generic COM error\";\r\n        logComError( res, err );\r\n        throw ITunesException( wstring2string( err ).c_str() );\r\n        return true;\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nITunesComWrapper::logComError( HRESULT res, wstring err )\r\n{\r\n    wstring sRes;\r\n    switch ( res )\r\n    {\r\n        case S_OK:                     sRes = L\"S_OK\"; break;\r\n        case S_FALSE:                  sRes = L\"S_FALSE\"; break;\r\n        case E_POINTER:                sRes = L\"E_POINTER\"; break;\r\n        case ITUNES_E_OBJECTDELETED:   sRes = L\"ITUNES_E_OBJECTDELETED\"; break;\r\n        case ITUNES_E_OBJECTLOCKED:    sRes = L\"ITUNES_E_OBJECTLOCKED\"; break;\r\n        case E_FAIL:                   sRes = L\"E_FAIL\"; break;\r\n        case REGDB_E_CLASSNOTREG:      sRes = L\"REGDB_E_CLASSNOTREG\"; break;\r\n        case CLASS_E_NOAGGREGATION:    sRes = L\"CLASS_E_NOAGGREGATION\"; break;\r\n        case E_NOINTERFACE:            sRes = L\"E_NOINTERFACE\"; break;\r\n\r\n        // Happens when CoCreateInstance times out for whatever reason\r\n        case CO_E_SERVER_EXEC_FAILURE: sRes = L\"CO_E_SERVER_EXEC_FAILURE\"; break;\r\n\r\n        // We've lost the connection to iTunes\r\n        case CO_E_OBJNOTCONNECTED:     sRes = L\"CO_E_OBJNOTCONNECTED\"; break;\r\n\r\n        // Happens when iTunes displays dialog\r\n        case RPC_E_CALL_REJECTED:      sRes = L\"RPC_E_CALL_REJECTED\"; break;\r\n\r\n        // Happens when iTunes is shut down while we're accessing it\r\n        // (couldn't find the enum value in winerror.h)\r\n        case (HRESULT)0x800706BA:      sRes = L\"RPC_S_SERVER_UNAVAILABLE\"; break;\r\n\r\n        default:\r\n            wchar_t buf[50];\r\n            swprintf_s( buf, 50, L\"%x\", static_cast<unsigned long>( res ) );\r\n            sRes = wstring( buf );\r\n    }\r\n    \r\n    wostringstream os;\r\n    os << L\"COM error: \" << err << L\"\\n  Result code: \" << sRes;\r\n    LOGW( 2, os.str() );\r\n}\r\n\r\n\r\n/******************************************************************************\r\n    ITunesComEventSink\r\n******************************************************************************/\r\nHRESULT\r\nITunesComEventSink::Invoke( DISPID dispidMember,       // the event in question\r\n                            REFIID /*riid*/,           // reserved - NULL\r\n                            LCID /*lcid*/,             // locale\r\n                            WORD /*wFlags*/,           // context of call\r\n                            DISPPARAMS* pdispparams,   // arguments\r\n                            VARIANT* /*pvarResult*/,   // return value - NULL\r\n                            EXCEPINFO* /*pexcepinfo*/, // out param for exception info\r\n                            UINT* /*puArgErr*/ )       // out param for which param was wrong\r\n{\r\n    // TODO: figure out if I need to free the DISPPARAMS objects\r\n\r\n    #define EVENT_ERROR( name )                                                              \\\r\n    {                                                                                        \\\r\n        if ( pdispparams == 0 )                                                              \\\r\n        {                                                                                    \\\r\n            LOG( 2, #name \" event pdispparams NULL\" );                                      \\\r\n            hr = DISP_E_PARAMNOTFOUND;                                                       \\\r\n        }                                                                                    \\\r\n        else                                                                                 \\\r\n        {                                                                                    \\\r\n            LOG( 2, #name \" event returned wrong number of args: \" << pdispparams->cArgs ); \\\r\n            hr = DISP_E_BADPARAMCOUNT;                                                       \\\r\n        }                                                                                    \\\r\n    }\r\n\r\n    HRESULT\thr = S_OK;\r\n\r\n    ITEvent evt = (ITEvent)( dispidMember );\r\n    switch ( evt )\r\n    {\r\n        case ITEventDatabaseChanged:\r\n        {\r\n            //LOG( 3, \"ondbchanged\" );\r\n\r\n            // OnDatabaseChanged should have two parameters\r\n            if ( pdispparams != 0 && pdispparams->cArgs == 2 )\r\n            {\r\n                // IDispatch arguments are passed in reverse order\r\n                onDatabaseChangedEvent( pdispparams->rgvarg[1], pdispparams->rgvarg[0] );\r\n            }\r\n            else\r\n                EVENT_ERROR( OnDatabaseChanged );\r\n        }\r\n        break;\r\n\r\n        case ITEventPlayerPlay:\r\n        {\r\n            //LOG( 3, \"onplay\" );\r\n\r\n            // Should have one parameter\r\n            if ( pdispparams != 0 && pdispparams->cArgs == 1 )\r\n            {\r\n                IDispatch* d = pdispparams->rgvarg[0].pdispVal;\r\n                if ( d == 0 )\r\n                {\r\n                    LOG( 2, \"d null in onPlay, sending empty track\" );\r\n\r\n                    // iTunes can return 0 here, so we use a null track\r\n                    m_handler->onPlay( ITunesTrack() );\r\n                }\r\n                else\r\n                {\r\n                    IITTrack* track = 0;\r\n                    HRESULT res = d->QueryInterface( IID_IITTrack, (void**)&track );\r\n                    if ( res == S_OK )\r\n                    {\r\n                        m_handler->onPlay( ITunesTrack( track ) );\r\n                    }\r\n                }\r\n            }\r\n            else\r\n                EVENT_ERROR( OnPlayerPlay );\r\n        }\r\n        break;\r\n\r\n        case ITEventPlayerStop:\r\n        {\r\n            //LOG( 3, \"onstop\" );\r\n\r\n            // Should have one parameter\r\n            if ( pdispparams != 0 && pdispparams->cArgs == 1 )\r\n            {\r\n                IDispatch* d = pdispparams->rgvarg[0].pdispVal;\r\n                if ( d == 0 )\r\n                {\r\n                    LOG( 2, \"d null in onStop, sending empty track\" );\r\n                    \r\n                    // iTunes can return 0 here, so we use a null track\r\n                    m_handler->onStop( ITunesTrack() );\r\n                }\r\n                else\r\n                {\r\n                    IITTrack* track = 0;\r\n                    HRESULT res = d->QueryInterface( IID_IITTrack, (void**)&track );\r\n                    if ( res == S_OK )\r\n                    {\r\n                        m_handler->onStop( ITunesTrack( track ) );\r\n                    }\r\n                }\r\n            }\r\n            else\r\n                EVENT_ERROR( OnPlayerStop );\r\n        }\r\n        break;\r\n\r\n        case ITEventPlayerPlayingTrackChanged:\r\n        {\r\n            //LOG( 3, \"ontrackchanged\" );\r\n\r\n            // Should have one parameter\r\n            if ( pdispparams != 0 && pdispparams->cArgs == 1 )\r\n            {\r\n                IDispatch* d = pdispparams->rgvarg[0].pdispVal;\r\n                if ( d == 0 )\r\n                {\r\n                    LOG( 2, \"d null in onTrackChanged, sending empty track\" );\r\n\r\n                    // iTunes can return 0 here, so we use a null track\r\n                    m_handler->onTrackChanged( ITunesTrack() );\r\n                }\r\n                else\r\n                {\r\n                    IITTrack* track = 0;\r\n                    HRESULT res = d->QueryInterface( IID_IITTrack, (void**)&track );\r\n                    if ( res == S_OK )\r\n                    {\r\n                        m_handler->onTrackChanged( ITunesTrack( track ) );\r\n                    }\r\n                }\r\n            }\r\n            else\r\n                EVENT_ERROR( OnPlayingTrackChanged );\r\n        }\r\n        break;\r\n\r\n        case ITEventCOMCallsDisabled:\r\n            m_handler->onComCallsDisabled();\r\n        break;\r\n\r\n        case ITEventCOMCallsEnabled:\r\n            m_handler->onComCallsEnabled();\r\n        break;\r\n\r\n        case ITEventQuitting:\r\n        break;\r\n\r\n        case ITEventAboutToPromptUserToQuit:\r\n            m_handler->onAboutToPromptUserToQuit();\r\n        break;\r\n\r\n        case ITEventSoundVolumeChanged:\r\n        break;\r\n\r\n        default:\r\n            hr = DISP_E_MEMBERNOTFOUND;\r\n        break;\r\n    }\r\n        \r\n    return hr;\r\n}\r\n\r\n\r\nvoid\r\nITunesComEventSink::onDatabaseChangedEvent( VARIANT deletedObjectIDs,\r\n                                            VARIANT changedObjectIDs )\r\n{\r\n    // TODO: can this really not go wrong? No docs about what happens when it fails.\r\n    // Tried forcing an exception in a release build but nothing happened.\r\n    CComSafeArray<VARIANT> deleted( deletedObjectIDs.parray );\r\n    CComSafeArray<VARIANT> changed( changedObjectIDs.parray );\r\n    std::vector<ITunesEventInterface::ITunesIdSet> vecDeleted;\r\n    std::vector<ITunesEventInterface::ITunesIdSet> vecChanged;\r\n    \r\n    LOG( 3, \"Deleted: \" << deleted.GetCount() << \", Changed: \" << changed.GetCount() );\r\n\r\n    for ( ULONG i = 0; i < deleted.GetCount(); ++i )\r\n    {\r\n        ITunesEventInterface::ITunesIdSet ids = getIdsFromSafeArray( i, deleted );\r\n        vecDeleted.push_back( ids );\r\n    }\r\n    \r\n    for ( ULONG i = 0; i < changed.GetCount(); ++i )\r\n    {\r\n        ITunesEventInterface::ITunesIdSet ids = getIdsFromSafeArray( i, changed );\r\n        vecChanged.push_back( ids );\r\n    }\r\n    \r\n    m_handler->onDatabaseChanged( vecDeleted, vecChanged );\r\n}    \r\n\r\n\r\nITunesEventInterface::ITunesIdSet\r\nITunesComEventSink::getIdsFromSafeArray( long index, \r\n                                         CComSafeArray<VARIANT>& array )\r\n{\r\n    VARIANT elem;\r\n    LONG idx2d[2];\r\n\r\n    idx2d[0] = index;\r\n    idx2d[1] = 0;\r\n    array.MultiDimGetAt( idx2d, elem );\r\n    long sourceId = elem.lVal;\r\n\r\n    idx2d[1] = 1;\r\n    array.MultiDimGetAt( idx2d, elem );\r\n    long playlistId = elem.lVal;\r\n\r\n    idx2d[1] = 2;\r\n    array.MultiDimGetAt( idx2d, elem );\r\n    long trackId = elem.lVal;\r\n\r\n    idx2d[1] = 3;\r\n    array.MultiDimGetAt( idx2d, elem );\r\n    long dbId = elem.lVal;\r\n\r\n    ITunesEventInterface::ITunesIdSet ids = { sourceId, playlistId, trackId, dbId };\r\n    return ids;\r\n}\r\n\r\n\r\n// Old crap, but leaving the code here for now for reference purposes\r\n// ------------------------------------------------------------------\r\n//void\r\n//ITunesComWrapper::buildMapping()\r\n//{\r\n//    //stdext::hash_map<long, string> mapping; \r\n//\r\n//    cout << \"Starting building map\" << endl;\r\n//\r\n//    DWORD startTime = GetTickCount();\r\n//\r\n//    // iterate over itunes collection\r\n//    IITLibraryPlaylist* playlist;\r\n//    m_iTunesApp->get_LibraryPlaylist( &playlist );\r\n//\r\n//    IITTrackCollection* coll;\r\n//    playlist->get_Tracks( &coll );\r\n//        \r\n//    long cnt;\r\n//    coll->get_Count( &cnt );\r\n//\r\n//    for ( long i = 1; i <= cnt; ++i ) // arrays are 1-based in COM\r\n//    {\r\n//        IITTrack* track;\r\n//        coll->get_Item( i, &track );\r\n//        \r\n//        long dbId;\r\n//        track->get_TrackDatabaseID( &dbId );\r\n//        \r\n//        string path = pathForTrack( track );\r\n//        \r\n//        //ostringstream os;\r\n//        //os << \"ID: \" << dbId << \"\\nPath: \" << path;\r\n//        //Log( os.str() );\r\n//        \r\n//        //mapping.insert( make_pair( dbId, path ) ); \r\n//    }\r\n//\r\n//    DWORD finishTime = GetTickCount();\r\n//    DWORD elapsed = finishTime - startTime;\r\n//\r\n//    ostringstream os;\r\n//    os << \"Finished building mapping, time: \" << elapsed;\r\n//    Log( os.str() );\r\n//\r\n//    std::cout << os.str().c_str();\r\n//    \r\n//\r\n//    // get runtime id and path for each track\r\n//    // put these in hash table\r\n//}\r\n//\r\n//\r\n//string\r\n//ITunesComWrapper::findPersistentIdForTrack( IITTrack* track )\r\n//{\r\n//    // Get the metadata from the track\r\n//    BSTR bstrTitle = 0;\r\n//    BSTR bstrArtist = 0;\r\n//    BSTR bstrAlbum = 0;\r\n//    bool gotMetadata =\r\n//        handleComResult( track->get_Name( &bstrTitle ) ) &&\r\n//        handleComResult( track->get_Artist( &bstrArtist ) ) &&\r\n//        handleComResult( track->get_Album( &bstrAlbum ) );\r\n//    if ( !gotMetadata )\r\n//    {\r\n//        Log( \"Failed to get metadata\" );\r\n//        return \"\";\r\n//    }\r\n//    \r\n//    string titleUtf8 = bstrToUtf8( bstrTitle );\r\n//    string artistUtf8 = bstrToUtf8( bstrArtist );\r\n//    string albumUtf8 = bstrToUtf8( bstrAlbum );\r\n//\r\n//    // Get the path to the XML\r\n//    BSTR bstrPath;\r\n//    HRESULT res = m_iTunesApp->get_LibraryXMLPath( &bstrPath );\r\n//    if ( res != S_OK )\r\n//    {\r\n//        logComError( \"COM failed to get library XML path\", res );\r\n//        return \"\";\r\n//    }\r\n//\r\n//    // Try opening it...\r\n//    _bstr_t path( bstrPath );\r\n//\r\n///*\r\n//    FILE* fp;\r\n//    errno_t err = _wfopen_s( &fp, path, \"r\" );\r\n//    if ( err != 0 )\r\n//    {\r\n//        char buf[100];\r\n//        strerror_s( buf, 100, err );\r\n//        ostringstream os;\r\n//        os << \"Failed to open iTunes XML file. Error: \" << buf;\r\n//        Log( os.str() );\r\n//        return \"\";\r\n//    }\r\n//*/\r\n//\r\n//    ifstream fs( static_cast<wchar_t*>( path ) );\r\n//    if ( !fs )\r\n//    {\r\n//        Log( \"Failed to open iTunes XML file\" );\r\n//        return \"\";\r\n//    }\r\n//    \r\n//    // OK, we have the XML file ready and willing\r\n//    \r\n//\r\n//}\r\n\r\n#endif // WIN32\r\n\r\n"
  },
  {
    "path": "plugins/iTunes/ITunesComWrapper.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef ITUNESCOMWRAPPER_H\r\n#define ITUNESCOMWRAPPER_H\r\n\r\n#ifdef WIN32\r\n\r\n#include \"ITunesTrack.h\"\r\n#include \"ITunesEventInterface.h\"\r\n\r\n// Needed for CoInitializeEx\r\n#ifndef _WIN32_DCOM \r\n    #define _WIN32_DCOM \r\n#endif    \r\n\r\n#include <windows.h>\r\n\r\n// Must include objbase before iTunes interface or it won't compile\r\n#include <objbase.h>\r\n#include <atlbase.h>\r\n#include <atlsafe.h>\r\n#include <atlcom.h>\r\n#include \"lib/3rdparty/iTunesCOMAPI/iTunesCOMInterface.h\"\r\n\r\n#include <string>\r\n#include <vector>\r\n\r\nclass ITunesComEventSink;\r\n\r\n/** @author Erik Jalevik <erik@last.fm>\r\n  * @brief Uses COM to query iTunes for track information.\r\n  *        All functions that access COM directly will throw an ITunesException\r\n  *        if something went wrong.\r\n  */\r\nclass ITunesComWrapper\r\n{\r\npublic:\r\n\r\n    /// If you want events, pass in an implementation of the event handler interface,\r\n    /// leave it as 0 and the event sink won't get initialised.\r\n    ITunesComWrapper( ITunesEventInterface* handler = 0 );\r\n    ~ITunesComWrapper();\r\n\r\n    /// If this returns false, we didn't manage to initialise COM and all the\r\n    /// other malarkey required for this to work.\r\n    bool isValid() { return m_iTunesApp != 0 && m_trackCount != -1 && m_allTracks != 0; }\r\n\r\n    /// Call libraryTrackCount first...\r\n    long libraryTrackCount();\r\n\r\n    /// if you call this instead of the libraryTrackCount() equivalent\r\n    /// all other functions that involve m_allTracks will reference the iPod\r\n    /// instead FIXME sucks!\r\n    /// NOTE as above, call this before calling track()\r\n    long iPodLibraryTrackCount();\r\n\r\n    /// Then pass an index in the range 0..libraryTrackCount to this function\r\n    ITunesTrack track( long idx );\r\n\r\n    /// Or an ITunesIdSet to this. An ITunesIdSet does not necessarily represent\r\n    /// a track, it could be any iTunes object. If the set of IDs passed in does\r\n    /// not represent a track, an ITunesException will be thrown.\r\n    ITunesTrack track( const ITunesEventInterface::ITunesIdSet& ids );\r\n\r\n    /// Get currently playing track in iTunes\r\n    ITunesTrack currentTrack();\r\n\r\n    /// Get state of player (stopped/running etc)\r\n    ITPlayerState playerState();\r\n    \r\n    /// Get player position in seconds\r\n    long playerPosition();\r\n\r\n    /// Get iTunes version\r\n    std::wstring iTunesVersion();\r\n\r\n    /// Search library. ITPlaylistSearchField is an iTunes type.\r\n    std::vector<ITunesTrack>\r\n    searchForTrack( ITPlaylistSearchField searchField, std::wstring searchTerm );\r\n\r\nprivate:\r\n    void initialiseCom();\r\n    void uninitialiseCom();\r\n\r\n    void setPersistentIDForTrack( ITunesTrack& t, IITTrack* track );\r\n\r\n    /// Connects iTunes events to our event sink\r\n    void connectSink( ITunesEventInterface* handler );\r\n\r\n    /// Throws if no iPod found in iTunes\r\n    IITPlaylist* iPodLibraryPlaylist();\r\n\r\n    static std::wstring bstrToWString( BSTR bstr );\r\n    static bool handleComResult( HRESULT res, std::wstring err = L\"\" );\r\n    static void logComError( HRESULT res, std::wstring err );\r\n\r\n    IiTunes* m_iTunesApp;\r\n    IITTrackCollection* m_allTracks;\r\n    long m_trackCount;\r\n\r\n    CComObject<ITunesComEventSink>* m_sink;\r\n    DWORD m_sinkId; // needed to close the connection\r\n    IUnknown* m_sinkAsUnknown;\r\n    \r\n    friend ITunesTrack;\r\n};\r\n\r\n\r\n/** @author Erik Jalevik <erik@last.fm>\r\n  * @brief Internal handler for COM events fired by iTunes.\r\n  */\r\nclass ATL_NO_VTABLE ITunesComEventSink : \r\n    public CComObjectRootEx<CComObjectThreadModel>,\r\n    public IDispatch\r\n{\r\npublic:\r\n\r\n    BEGIN_COM_MAP(ITunesComEventSink)\r\n        COM_INTERFACE_ENTRY( IDispatch )\r\n        COM_INTERFACE_ENTRY_IID( DIID__IiTunesEvents, IDispatch )\r\n    END_COM_MAP()\r\n\r\n    ITunesComEventSink() : m_handler( 0 ) { }\r\n\r\n    /// You must call this function with a valid handler after initialising this class.\r\n    void setHandler( ITunesEventInterface* handler ) { m_handler = handler; }\r\n\r\n    // IDispatch stuff\r\n    HRESULT __stdcall Invoke( DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,\r\n                              DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr );\r\n    HRESULT __stdcall GetTypeInfoCount( UINT* ) { return E_NOTIMPL; }\r\n    HRESULT __stdcall GetTypeInfo( UINT, LCID, ITypeInfo** ) { return E_NOTIMPL; }\r\n    HRESULT __stdcall GetIDsOfNames( REFIID, LPOLESTR*, UINT, LCID, DISPID* ) { return E_NOTIMPL; }\r\n\r\nprivate:\r\n\r\n    ITunesEventInterface* m_handler;\r\n\r\n    void onDatabaseChangedEvent( VARIANT deletedObjectIDs, VARIANT changedObjectIDs );\r\n\r\n    ITunesEventInterface::ITunesIdSet\r\n    getIdsFromSafeArray( long index, CComSafeArray<VARIANT>& array );\r\n\r\n};\r\n\r\n\r\n// We need one of these things hanging around for the ATL calls to work.\r\n// It's initialised in connectSink.\r\nclass TheAtlModule : public CAtlDllModuleT<TheAtlModule> { };\r\n//class TheAtlModule : public CAtlExeModuleT<TheAtlModule> { };\r\n\r\n\r\n#endif // WIN32\r\n\r\n#endif // ITUNESCOMTHREAD_H"
  },
  {
    "path": "plugins/iTunes/ITunesEventInterface.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef ITUNESEVENTINTERFACE_H\r\n#define ITUNESEVENTINTERFACE_H\r\n\r\n#ifdef WIN32\r\n\r\n#include <vector>\r\n\r\n/** @author Erik Jalevik <erik@last.fm>\r\n  * @brief This interface should be implemented by anyone interested in receiving\r\n  * events from iTunes without having to touch COM.\r\n  */\r\nclass ITunesEventInterface\r\n{\r\npublic:\r\n\r\n    struct ITunesIdSet\r\n    {\r\n        long sourceId;\r\n        long playlistId;\r\n        long trackId;\r\n        long dbId;\r\n    };\r\n\r\n    virtual void\r\n    onDatabaseChanged( std::vector<ITunesIdSet> deletedObjects,\r\n                       std::vector<ITunesIdSet> changedObjects ) = 0;\r\n    \r\n    virtual void\r\n    onPlay( ITunesTrack ) = 0;\r\n\r\n    virtual void\r\n    onStop( ITunesTrack ) = 0;\r\n\r\n    virtual void\r\n    onTrackChanged( ITunesTrack ) = 0;\r\n\r\n    virtual void\r\n    onAboutToPromptUserToQuit() = 0;\r\n\r\n    virtual void\r\n    onComCallsDisabled() = 0;\r\n\r\n    virtual void\r\n    onComCallsEnabled() = 0;\r\n\r\n};\r\n\r\n#endif // WIN32\r\n\r\n#endif // ITUNESEVENTINTERFACE_H"
  },
  {
    "path": "plugins/iTunes/ITunesExceptions.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ITUNES_EXCEPTIONS_H\n#define ITUNES_EXCEPTIONS_H\n\n#include <stdexcept>\n\nclass ITunesException : public std::runtime_error\n{\npublic:\n    ITunesException( const char* s = \"ITunesException\" ) : std::runtime_error( s ) { }\n};\n\n\nclass PlayCountException : public ITunesException\n{\npublic:\n    PlayCountException() : ITunesException( \"PlayCountException\" ) { }\n};\n\n#endif // ITUNESEXCEPTIONS_H\n"
  },
  {
    "path": "plugins/iTunes/ITunesPlaysDatabase.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesPlaysDatabase.h\"\n\n#include \"Moose.h\"\n#include \"common/c++/logger.h\"\n#include \"ITunesTrack.h\"\n\n#include <errno.h>\n#include <sys/stat.h>\n\n#ifndef WIN32\n#include <pthread.h>\n#include <unistd.h>   \n#endif\n\n#include \"sqlite3.h\"\n\n\n// this is a macro to ensure useful location information in the log\n#define logError( db ) \\\n        LOG( 2, \"sqlite error: \" \\\n            << sqlite3_errcode( db ) \\\n            << \" (\" << sqlite3_errmsg( db ) << \")\" );\n\n\nITunesPlaysDatabase::ITunesPlaysDatabase()\n{\n#ifdef WIN32\n    std::string path = Moose::wStringToUtf8( Moose::applicationSupport() + L\"\\\\iTunesPlays.db\" );\n#else\n    std::string path = Moose::applicationSupport() + \"iTunesPlays.db\";\n#endif\n\n    if ( sqlite3_open( path.c_str(), &m_db ) != SQLITE_OK )\n    {\n        LOG( 2, \"ERROR: Could not open iTunesPlays Database: \" << path );\n        logError( m_db );\n    }\n\n#ifdef WIN32\n    prepare();\n#endif\n}\n\n\nvoid\nITunesPlaysDatabase::prepare()\n{\n\t#ifdef WIN32\n\t\t#define BOOTSTRAP_FLAG L\"--bootstrap\"\n\t#else\n\t\t#define BOOTSTRAP_FLAG \"--bootstrap\"\n\t#endif\n\n    // if twiddly is already running, quite probably we're already bootstrapping\n    if ( (!isValid() || needsBootstrap()) && !Moose::isTwiddlyRunning() )\n\t\tMoose::exec( Moose::twiddlyPath(), BOOTSTRAP_FLAG );\n}\n\n\nITunesPlaysDatabase::~ITunesPlaysDatabase()\n{\n    sqlite3_close( m_db ); //docs says passing NULL is harmless noop\n}\n\n#ifdef WIN32\n/*\n** A pointer to an instance of this structure is passed as the user-context\n** pointer when registering for an unlock-notify callback.\n*/\ntypedef struct UnlockNotification UnlockNotification;\n\nstruct UnlockNotification\n{\n\tint fired;                         /* True after unlock event has occurred */\n\tCRITICAL_SECTION mutex;\n\tCONDITION_VARIABLE cond;\n};\n\n/*\n** This function is an unlock-notify callback registered with SQLite.\n*/\nstatic void unlock_notify_cb(void **apArg, int nArg)\n{\n\tfor( int i = 0; i < nArg ; i++)\n\t{\n\t\tUnlockNotification *p = (UnlockNotification *)apArg[i];\n\t\tEnterCriticalSection( &p->mutex );\n\t\tp->fired = 1;\n\t\t//WakeConditionVariable( &p->cond );\n\t\tLeaveCriticalSection( &p->mutex );\n\t}\n}\n\n/*\n** This function assumes that an SQLite API call (either sqlite3_prepare_v2() \n** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the\n** associated database connection.\n**\n** This function calls sqlite3_unlock_notify() to register for an \n** unlock-notify callback, then blocks until that callback is delivered \n** and returns SQLITE_OK. The caller should then retry the failed operation.\n**\n** Or, if sqlite3_unlock_notify() indicates that to block would deadlock \n** the system, then this function returns SQLITE_LOCKED immediately. In \n** this case the caller should not retry the operation and should roll \n** back the current transaction (if any).\n*/\nstatic int wait_for_unlock_notify(sqlite3 *db){\n\tint rc;\n\tUnlockNotification un;\n\n\t/* Initialize the UnlockNotification structure. */\n\tun.fired = 0;\n\tInitializeCriticalSection( &un.mutex );\n\t//InitializeConditionVariable( &un.cond );\n\n\t/* Register for an unlock-notify callback. */\n\trc = sqlite3_unlock_notify( db, unlock_notify_cb, (void *)&un );\n\n\t//assert( rc==SQLITE_LOCKED || rc==SQLITE_OK );\n\n\t/* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED \n\t** or SQLITE_OK. \n\t**\n\t** If SQLITE_LOCKED was returned, then the system is deadlocked. In this\n\t** case this function needs to return SQLITE_LOCKED to the caller so \n\t** that the current transaction can be rolled back. Otherwise, block\n\t** until the unlock-notify callback is invoked, then return SQLITE_OK.\n\t*/\n\tif( rc==SQLITE_OK )\n\t{\n\t\tEnterCriticalSection( &un.mutex );\n\n\t\tif( !un.fired )\n\t\t{\n\t\t\t//SleepConditionVariableCS( &un.cond, &un.mutex, INFINITE );\n\t\t}\n\n\t\tLeaveCriticalSection( &un.mutex );\n\t}\n\n\t/* Destroy the mutex and condition variables. */\n\t//pthread_cond_destroy(&un.cond);\n\tDeleteCriticalSection( &un.mutex );\n\n\treturn rc;\n}\n\n#else\n\n/*\n ** A pointer to an instance of this structure is passed as the user-context\n ** pointer when registering for an unlock-notify callback.\n */\ntypedef struct UnlockNotification UnlockNotification;\nstruct UnlockNotification {\n    int fired;                         /* True after unlock event has occurred */\n    pthread_cond_t cond;               /* Condition variable to wait on */\n    pthread_mutex_t mutex;             /* Mutex to protect structure */\n};\n\n/*\n ** This function is an unlock-notify callback registered with SQLite.\n */\nstatic void unlock_notify_cb(void **apArg, int nArg){\n    int i;\n    for(i=0; i<nArg; i++){\n        UnlockNotification *p = (UnlockNotification *)apArg[i];\n        pthread_mutex_lock(&p->mutex);\n        p->fired = 1;\n        pthread_cond_signal(&p->cond);\n        pthread_mutex_unlock(&p->mutex);\n    }\n}\n\n/*\n ** This function assumes that an SQLite API call (either sqlite3_prepare_v2()\n ** or sqlite3_step()) has just returned SQLITE_LOCKED. The argument is the\n ** associated database connection.\n **\n ** This function calls sqlite3_unlock_notify() to register for an\n ** unlock-notify callback, then blocks until that callback is delivered\n ** and returns SQLITE_OK. The caller should then retry the failed operation.\n **\n ** Or, if sqlite3_unlock_notify() indicates that to block would deadlock\n ** the system, then this function returns SQLITE_LOCKED immediately. In\n ** this case the caller should not retry the operation and should roll\n ** back the current transaction (if any).\n */\nstatic int wait_for_unlock_notify(sqlite3 *db){\n    int rc;\n    UnlockNotification un;\n    \n    /* Initialize the UnlockNotification structure. */\n    un.fired = 0;\n    pthread_mutex_init(&un.mutex, 0);\n    pthread_cond_init(&un.cond, 0);\n    \n    /* Register for an unlock-notify callback. */\n    rc = sqlite3_unlock_notify(db, unlock_notify_cb, (void *)&un);\n    assert( rc==SQLITE_LOCKED || rc==SQLITE_OK );\n    \n    /* The call to sqlite3_unlock_notify() always returns either SQLITE_LOCKED\n     ** or SQLITE_OK.\n     **\n     ** If SQLITE_LOCKED was returned, then the system is deadlocked. In this\n     ** case this function needs to return SQLITE_LOCKED to the caller so\n     ** that the current transaction can be rolled back. Otherwise, block\n     ** until the unlock-notify callback is invoked, then return SQLITE_OK.\n     */\n    if( rc==SQLITE_OK ){\n        pthread_mutex_lock(&un.mutex);\n        if( !un.fired ){\n            pthread_cond_wait(&un.cond, &un.mutex);\n        }\n        pthread_mutex_unlock(&un.mutex);\n    }\n    \n    /* Destroy the mutex and condition variables. */\n    pthread_cond_destroy(&un.cond);\n    pthread_mutex_destroy(&un.mutex);\n    \n    return rc;\n}\n\n#endif\n\nbool\nITunesPlaysDatabase::query( /* utf-8 */ const char* statement, std::string* result )\n{\n    LOG( 3, statement );\n    \n    int error = 0;\n    sqlite3_stmt* stmt = 0;\n\n    try\n    {\n        const char* tail;\n        error = sqlite3_prepare( m_db, statement, static_cast<int>( strlen( statement ) ), &stmt, &tail );\n        \n        if ( error != SQLITE_OK )\n            throw \"Could not compile SQL to byte-code\";        \n        \n        int busyCount = 0;\n        while( error != SQLITE_DONE && busyCount < 20 )\n        {\n            error = sqlite3_step( stmt );\n\n            switch( error )\n            {\n                case SQLITE_BUSY:\n                    busyCount++;\n                    sqlite3_sleep( 25 );\n                    break;\n\n                case SQLITE_MISUSE:\n                    throw \"Could not execute SQL - SQLITE_MISUSE\";\n\n                case SQLITE_ERROR:\n                    throw \"Could not execute SQL - SQLITE_ERROR\";\n\n                case SQLITE_ROW:\n                    if ( sqlite3_column_count( stmt ) > 0 && result )\n                    {\n                        *result = (const char*) sqlite3_column_text( stmt, 0 );\n                        LOG( 3, \"SQLite result: `\" << *result << '\\'' );\n                    }\n                    break;\n\n                case SQLITE_DONE:\n                    break;\n\n\t\t\t\tcase SQLITE_LOCKED:\n\t\t\t\t\tLOG( 3, \"Database locked. Waiting for unlock.\" );\n\t\t\t\t\tbusyCount++;\n                    sqlite3_sleep( 25 );\n\t\t\t\t\t//wait_for_unlock_notify( m_db );\n\t\t\t\t\tbreak;\n\n                default:\n                    throw \"Unhandled sqlite3_step() return value\";\n            }\n        }\n        \n        if ( busyCount )\n        {\n            if ( busyCount >= 20 )\n                throw \"Could not execute SQL - SQLite was too busy\";\n            \n            LOG( 3, \"SQLite was busy \" << busyCount << \" times\" );\n        }\n    }\n    catch( const char* message )\n    {\n        LOG( 2, \"ERROR: \" << message );\n        logError( m_db );\n    }\n\n    sqlite3_finalize( stmt );\n\n    return error == SQLITE_DONE;\n}\n\n\n#include \"common/c++/fileCreationTime.cpp\"\n\n\nbool\nITunesPlaysDatabase::isValid()\n{\n    if (!query( \"SELECT COUNT( * ) FROM \" TABLE_NAME \" LIMIT 0, 1;\" ))\n        return false;\n\n    // uninstallation protection\n    // we store the ctime in the database, so if the database is removed we\n    // don't have this value still stored, which may cause additional issues\n    // the principle is, if the plugin is uninstalled, then reinstalled sometime\n    // the ctime will be different to what we stored at the time of bootstrap\n    // the reason for all this is, if there was a period of uninstallation\n    // in which the db wasn't removed (happens everytime on Windows), we don't\n    // want to scrobble everything played since the uninstallation!\n    std::string r;\n    query( \"SELECT value FROM metadata WHERE key='plugin_ctime';\", &r );\n\n    long const stored_time = std::strtol( r.c_str(), 0, 10 /*base*/ );\n    time_t actual_time = common::fileCreationTime( Moose::pluginPath() );\n\n    LOG( 3, \"Plugin binary ctime: \" << actual_time );\n\n    if (errno == EINVAL || stored_time != actual_time)\n    {\n        LOG( 3, \"Uninstallation protection triggered; forcing bootstrap\" );\n        return false;\n    }\n\n    return true;\n}\n\n\nbool\nITunesPlaysDatabase::needsBootstrap()\n{\n    std::string out;\n    bool b = query( \"SELECT value FROM metadata WHERE key='bootstrap_complete'\", &out );\n    if (!b || out != \"true\")\n        return true;\n\n   \n#ifndef WIN32\n    b = query( \"SELECT value FROM metadata WHERE key='schema'\", &out );\n    if (!b || out != \"2\")\n        return true;\n#endif\n\n    return false;\n}\n\n\nint\nITunesPlaysDatabase::playCount( const ITunesTrack& track )\n{\n#ifdef WIN32\n\tstd::string id = Moose::wStringToUtf8( track.persistentId() );\n#else\n\tstd::string id = track.persistentId();\n#endif\n    char* format = \"SELECT play_count FROM \" TABLE_NAME \" WHERE persistent_id='%q'\";\n\n    char* token = sqlite3_mprintf( format, id.c_str() );\n    std::string result;\n    \n    if ( !query( token, &result ) )\n        return -1;\n    \n    long c = std::strtol( result.c_str(), 0, 10 /*base*/ );\n    if ( errno == EINVAL )\n        return -1;\n    return c;\n}\n\nint\nITunesPlaysDatabase::playCountOld( const ITunesTrack& track )\n{\n#ifdef WIN32\n    std::string id = Moose::wStringToUtf8( track.path() );\n\tchar* format = \"SELECT play_count FROM itunes_db WHERE path='%q'\";\n#else\n\tstd::string id = track.persistentId();\n\tchar* format = \"SELECT play_count FROM itunes_db WHERE persistent_id='%q'\";\n#endif\n\n    char* token = sqlite3_mprintf( format, id.c_str() );\n    std::string result;\n    \n    if ( !query( token, &result ) )\n        return -1;\n    \n    long c = std::strtol( result.c_str(), 0, 10 /*base*/ );\n    if ( errno == EINVAL )\n        return -1;\n    return c;\n}\n"
  },
  {
    "path": "plugins/iTunes/ITunesPlaysDatabase.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef ITUNES_PLAYS_DATABASE_H\n#define ITUNES_PLAYS_DATABASE_H\n\n#ifdef WIN32\n\t#include \"ITunesTrack.h\"\n#endif\n\n#include <string>\n\nextern \"C\"\n{\n    typedef struct sqlite3 sqlite3;\n}\n\n#define TABLE_NAME \"playcounts\"\n\n/** @author Christian Muehlhaeuser <chris@last.fm>\n  * @contributor Jono Cole <jono@last.fm>\n  * @contributor Max Howell <max@last.fm>\n  * @contributor <erik@last.fm>\n  */\nclass ITunesPlaysDatabase\n{\npublic:\n    ITunesPlaysDatabase();\n    ~ITunesPlaysDatabase();\n    \n    /** @returns false if the tables aren't valid or created */\n    bool isValid();\n    /** @returns true if the db has no valid bootstrap */\n    bool needsBootstrap();\n    \n    /** tracks unknown to us return -1, which means you should verify the \n      * playCount with iTunes before doing anything with that track generally */\n    int playCount( const class ITunesTrack& track );\n\n\t/** tracks unknown to us return -1, which means you should verify the \n      * playCount with iTunes before doing anything with that track generally */\n    int playCountOld( const class ITunesTrack& track );\n\n    /** call to sync the just finished playing track, NOTE the implementation\n      * stores what is playing now for the next call to sync() so always call\n      * this every new track\n      */\n    static void sync();\n\n#ifndef WIN32    \n    /** general init, and if necessary, creates tables, bootstraps db, etc. */\n    static void init();\n    \n    /** cleans up, call when plugin is unloaded */\n    static void finit();\n#else\n\tbool sync( const ExtendedITunesTrack& );\n\tbool syncOld( const ExtendedITunesTrack& );\n#endif\n\nprotected:\n    /** prepares us for iPod scrobbling, ie creates the tables and bootstraps\n      * the database */\n    void prepare();\n    \n    bool query( /* utf-8 */ const char* statement, std::string* result = 0 );\n    \n    sqlite3* m_db;\n    \n#ifndef WIN32\n    static void* onPlayStateChanged( void* );\n    static void* sync( void* );\n    static void* syncOld( void* );\n    \n    static pthread_mutex_t s_mutex;\n#endif\n};\n\n\n#endif //ITUNES_PLAYS_DATABASE_H\n"
  },
  {
    "path": "plugins/iTunes/ITunesPlaysDatabase_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesPlaysDatabase.h\"\n#include \"ITunesTrack.h\"\n#include \"ITunesExceptions.h\"\n#include \"common/c++/logger.h\"\n\n#include <pthread.h>\n#include <sqlite3.h>\n\npthread_mutex_t ITunesPlaysDatabase::s_mutex;\n\n\nvoid //static\nITunesPlaysDatabase::init()\n{\n    ITunesPlaysDatabase().prepare();\n    pthread_mutex_init( &s_mutex, NULL );\n}\n\n\nvoid //static\nITunesPlaysDatabase::finit()\n{\n    pthread_mutex_destroy( &s_mutex );\n}\n\n\nstruct PThreadMutexLocker\n{\n    PThreadMutexLocker( pthread_mutex_t& mutex ) : m_mutex( &mutex )\n    {\n        pthread_mutex_lock( m_mutex );\n    }\n    \n    ~PThreadMutexLocker()\n    {\n        pthread_mutex_unlock( m_mutex );\n    }\n    \nprivate:\n    pthread_mutex_t* const m_mutex;\n};\n\n\nvoid* //static\nITunesPlaysDatabase::sync( void* that )\n{\n    ExtendedITunesTrack& track = * (ExtendedITunesTrack*) that;\n\n    LOG( 3, \"Syncing \" << track.path() );\n\n    // On trackChange iTunes takes about 4 seconds to update the playCount for \n    // the previous track :(\n    // Thus we try to obtain a new playCount for up to 124 seconds (0+4+8+16+32+64)\n    // We stop then because if the user skips a track, playCount will never\n    // change. However we try for up to 60 as we have no idea how long it may\n    // take for iTunes to update its db.\n    for( int s = 4; s < 128; s += s )\n    {\n        try \n        {\n            // do as infrequently as possible because it spawns applescript\n            int const diff = track.playCountDifference();\n            \n            if (diff)\n            {\n                ITunesPlaysDatabase db;\n                \n                // rationale for UPDATE: if the track is not in the db then it\n                // is new since the last ipod sync. Thus it cannot be on the ipod\n                // It will be automatically inserted with the current playcount\n                // when the ipod is next synced and Twiddly is run.\n                // NOTE db.playCount() will return -1 in this case so the logs\n                // will be misleading, usually stating: play_count='0', but this\n                // is fine since the UPDATE will fail in this case.\n                char* format = \"UPDATE \" TABLE_NAME \" SET play_count='%d' WHERE persistent_id='%q'\";\n                char* token = sqlite3_mprintf( format,\n                                              db.playCount( track ) + diff,\n                                              track.persistentId().c_str() );\n                db.query( token );\n                sqlite3_free( token );\n                break;\n            }\n        }\n        catch( PlayCountException& )\n        {\n            LOG( 2, \"Applescript failed to obtain playCount\" );\n            \n            // NOTE our options here are an additional scrobble or potentially\n            // lose scrobbles, the latter is perhaps better, as statistically\n            // the user is unlikely to have played the track in question on his\n            // iPod, however the code to achieve that would make this function\n            // far less maintainable\n        }\n        \n        LOG( 3, \"Playcount unchanged - sleeping \" << s << \" seconds...\" );\n        sqlite3_sleep( s * 1000 );\n    }\n\n    delete &track;\n    \n    pthread_exit( 0 );\n}\n\nvoid* //static\nITunesPlaysDatabase::syncOld( void* that )\n{\n    ExtendedITunesTrack& track = * (ExtendedITunesTrack*) that;\n\n    LOG( 3, \"Syncing \" << track.path() );\n\n    // On trackChange iTunes takes about 4 seconds to update the playCount for \n    // the previous track :(\n    // Thus we try to obtain a new playCount for up to 124 seconds (0+4+8+16+32+64)\n    // We stop then because if the user skips a track, playCount will never\n    // change. However we try for up to 60 as we have no idea how long it may\n    // take for iTunes to update its db.\n    for( int s = 4; s < 128; s += s )\n    {\n        try \n        {\n            // do as infrequently as possible because it spawns applescript\n            int const diff = track.playCountDifference();\n            \n            if (diff)\n            {\n                ITunesPlaysDatabase db;\n                \n                // rationale for UPDATE: if the track is not in the db then it\n                // is new since the last ipod sync. Thus it cannot be on the ipod\n                // It will be automatically inserted with the current playcount\n                // when the ipod is next synced and Twiddly is run.\n                // NOTE db.playCount() will return -1 in this case so the logs\n                // will be misleading, usually stating: play_count='0', but this\n                // is fine since the UPDATE will fail in this case.\n                char* format = \"UPDATE itunes_db SET play_count='%d' WHERE persistent_id='%q'\";\n                char* token = sqlite3_mprintf( format,\n                                              db.playCountOld( track ) + diff,\n                                              track.persistentId().c_str() );\n                db.query( token );\n                sqlite3_free( token );\n                break;\n            }\n        }\n        catch( PlayCountException& )\n        {\n            LOG( 2, \"Applescript failed to obtain playCount\" );\n            \n            // NOTE our options here are an additional scrobble or potentially\n            // lose scrobbles, the latter is perhaps better, as statistically\n            // the user is unlikely to have played the track in question on his\n            // iPod, however the code to achieve that would make this function\n            // far less maintainable\n        }\n        \n        LOG( 3, \"Playcount unchanged - sleeping \" << s << \" seconds...\" );\n        sqlite3_sleep( s * 1000 );\n    }\n\n    delete &track;\n    \n    pthread_exit( 0 );\n}\n\nvoid* //static\nITunesPlaysDatabase::onPlayStateChanged( void* )\n{\n    /** Behaviour:\n      * Playback started: get current track, exit\n      * Track changed: sync previous track, get current track, exit\n      * Playback stopped (playlist ended): sync last track, clear s_track\n      */\n\n    static ExtendedITunesTrack s_track;\n    ExtendedITunesTrack currentTrack = ExtendedITunesTrack::currentTrack();\n    \n    LOG( 3, \"kind: \" << s_track.kind() );\n\n    {\n        PThreadMutexLocker locker( s_mutex );\n\n        if (!s_track.isNull())\n        {\n            // s_track is the track that has just finished playing\n            pthread_t thread;\n            pthread_create( &thread, NULL, sync, new ExtendedITunesTrack( s_track ) );\n\n            pthread_t threadOld;\n            pthread_create( &threadOld, NULL, syncOld, new ExtendedITunesTrack( s_track ) );\n        }\n        else\n            LOG( 3, \"Track is null, won't sync\" );\n\n        s_track = currentTrack;\n    }\n    \n    pthread_exit( 0 );\n}\n\n\nvoid //static\nITunesPlaysDatabase::sync()\n{\n    pthread_t thread;\n    pthread_create( &thread, NULL, onPlayStateChanged, 0 );\n}\n"
  },
  {
    "path": "plugins/iTunes/ITunesPlaysDatabase_win.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesPlaysDatabase.h\"\n#include \"Moose.h\"\n\n#include \"ITunesTrack.h\"\n#include \"common/c++/logger.h\"\n\n#include \"sqlite3.h\"\n\n\nbool\nITunesPlaysDatabase::sync( const ExtendedITunesTrack& track )\n{\n    if ( track.isNull() )\n    {\n        // This means the track has no COM pointer or no path\n        return false;\n    }\n\n    try\n    {\n        int const diff = track.playCountDifference();\n        LOGWL( 3, \"Diff = \" << diff << \" for \" << track.toString() );\n\n        int const twiddlyPlayCount = playCount( track );\n\n        // if the track is new and not yet in the database then twiddlyPlayCount\n        // will be -1, therefore sync with the iTunes playCount for this track\n        int const playCountToSync = (twiddlyPlayCount == -1)\n                ? track.playCount()\n                : twiddlyPlayCount + diff;\n\n        if ( playCountToSync == twiddlyPlayCount )\n        {\n            // Nothing to do. This isn't really an error, we just happened to sync\n            // even though the playcount hadn't inced.\n            return true;\n        }\n\n        const char* format = \"REPLACE INTO \" TABLE_NAME \" ( persistent_id, play_count ) VALUES ( '%q', '%d' );\";\n        char* token = sqlite3_mprintf( format,\n                                       Moose::wStringToUtf8( track.persistentId() ).c_str(),\n                                       playCountToSync );\n\n        LOGWL( 3, \"Syncing local db for: \" << track.artist() << \" - \" << track.track() );\n\n        bool success = query( token );\n        sqlite3_free( token );\n\n        return success;\n    }\n    catch ( ITunesException& )\n    {\n        // This means COM failed to retrieve the playcount, abort\n        // NOTE no logging because a higher up function logs already\n        return false;   \n    }\n}\n\nbool\nITunesPlaysDatabase::syncOld( const ExtendedITunesTrack& track )\n{\n    if ( track.isNull() )\n    {\n        // This means the track has no COM pointer or no path\n        return false;\n    }\n\n    try\n    {\n        int const diff = track.playCountDifference();\n        LOGWL( 3, \"Diff = \" << diff << \" for \" << track.toString() );\n\n        int const twiddlyPlayCount = playCountOld( track );\n\n        // if the track is new and not yet in the database then twiddlyPlayCount\n        // will be -1, therefore sync with the iTunes playCount for this track\n        int const playCountToSync = (twiddlyPlayCount == -1)\n                ? track.playCount()\n                : twiddlyPlayCount + diff;\n\n        if ( playCountToSync == twiddlyPlayCount )\n        {\n            // Nothing to do. This isn't really an error, we just happened to sync\n            // even though the playcount hadn't inced.\n            return true;\n        }\n\n        const char* format = \"REPLACE INTO itunes_db ( persistent_id, path, play_count ) VALUES ( '%q', '%q', '%d' );\";\n        char* token = sqlite3_mprintf( format,\n                                       Moose::wStringToUtf8( track.persistentId() ).c_str(),\n                                       Moose::wStringToUtf8( track.path() ).c_str(),\n                                       playCountToSync );\n\n        LOGWL( 3, \"Syncing old local db for: \" << track.artist() << \" - \" << track.track() );\n\n        bool success = query( token );\n        sqlite3_free( token );\n\n        return success;\n    }\n    catch ( ITunesException& )\n    {\n        // This means COM failed to retrieve the playcount, abort\n        // NOTE no logging because a higher up function logs already\n        return false;   \n    }\n}\n"
  },
  {
    "path": "plugins/iTunes/ITunesTrack.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"ITunesTrack.h\"\n#include \"common/c++/Logger.h\"\n\n#include <cassert>\n#include <errno.h>\n\n#ifdef WIN32\n    #include \"ITunesComWrapper.h\"\n    #include <atlcomtime.h> // for COleDateTime\n    #include <iostream>\n    #include <iomanip>\n    #include <sstream>\n#endif\n\nusing namespace std;\n\n\nlong stdStringToLong( const std::string& s ) throw( PlayCountException )\n{\n    long c = std::strtol( s.c_str(), 0, 10 /*base*/ );\n    if ( errno == EINVAL )\n        throw PlayCountException();\n    return c;\n}\n\n\n#ifdef WIN32\nITunesTrack::ITunesTrack() :\n    m_comTrack( 0 )\n{}\n\n\nITunesTrack::ITunesTrack( IITTrack* track ) :\n    m_comTrack( track )\n{\n    assert( track != 0 );\n\n    m_path = pathForTrack( track );\n    m_id = L\"-1\";\n}\n\n\nITunesTrack::ITunesTrack( const ITunesTrack& that )\n{\n    clone( that );\n}\n\n\nITunesTrack&\nITunesTrack::operator=( const ITunesTrack& that )\n{\n    // Check for self-assignment\n    if ( &that != this )\n    {\n        clone( that );\n    }\n\n    return *this;\n}\n\n\nvoid\nITunesTrack::clone( const ITunesTrack& that )\n{\n    m_comTrack = that.m_comTrack;\n    m_id = that.m_id;\n    m_path = that.m_path;\n\n    if ( m_comTrack != 0 )\n        m_comTrack->AddRef();\n}\n\n\nITunesTrack::~ITunesTrack()\n{\n    if ( m_comTrack != 0 )\n        m_comTrack->Release();\n}\n#endif // WIN32\n\n\n#ifndef WIN32\nstatic void splitTheseFiveCommaSeparatedParts( const std::string& in, std::string out[] )\n{\n    unsigned int first = 0;\n    for (int x = 0; x < 4; ++x)\n    {   \n        unsigned int const second = in.find( ',', first );\n\n        if (second == std::string::npos)\n            throw PlayCountException();\n\n        out[x] = in.substr( first, second - first );\n\n        first = second + 2;\n    }\n    \n    out[4] = in.substr( first );\n}\n\n\nExtendedITunesTrack\nExtendedITunesTrack::currentTrack()\n{\n    ExtendedITunesTrack t;\n    \n    try\n    {\n        //TODO may as well precompile 3 scripts and then run them with carbon\n        // that should be most efficient computationally and easiest to read method\n        \n        // returns eg. \"412EAE1061ABF7D2, 6152, 3, /music/file.mp3\", \"Audio CD Track\"\n        std::string const s = scriptResult( \"currentTrack.scpt\" );\n\n        if( s.length() == 0 ) throw PlayCountException();\n        std::string parts[5];\n        splitTheseFiveCommaSeparatedParts( s, parts );\n        \n        t.m_id = parts[0];\n        t.m_dbid = parts[1];\n        t.m_path = parts[3];\n        t.m_kind = parts[4];\n        // may throw PlayCountException, if so initialPlayCount stays at -1\n        // this always happens when iTunes is stopped\n        t.m_initialPlayCount = stdStringToLong( parts[2] );\n    }\n    catch (PlayCountException&)\n    {\n        LOGL( 3, \"Couldn't get current track data\" );\n    }\n    catch (ITunesException& e)\n    {\n        LOGL( 3, (std::string(\"Couldn't determine current track: \") + e.what()).c_str());\n    }\n    \n    return t;\n}\n#endif\n    \n\nlong\nITunesTrack::playCount() const throw( PlayCountException )\n{\n#ifdef WIN32\n    if ( m_comTrack == 0 )\n        return -1; // empty track case\n\n    long cnt;\n    HRESULT res = m_comTrack->get_PlayedCount( &cnt );\n    try { ITunesComWrapper::handleComResult( res, L\"Failed to get play count for track\" ); }\n    catch( ITunesException& ) { throw PlayCountException(); }\n\n    return cnt;\n\n#else\n    std::string s = scriptResult( \"playCountForDatabaseId.scpt\", m_dbid );\n\n    //std::string s = scriptResult( \"playCountForPersistentId.scpt\", m_id );    \n    return stdStringToLong( s ); //may throw\n#endif\n}\n\n\n#ifdef WIN32\nwstring\nITunesTrack::track() const\n{\n    if ( m_comTrack == 0 )\n        return L\"\";  // empty track case\n\n    BSTR bstrName = 0;\n    HRESULT res = m_comTrack->get_Name( &bstrName );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read title of track\" );\n\n    return ITunesComWrapper::bstrToWString( bstrName );\n}\n#endif\n\n\n#ifdef WIN32\nwstring\nITunesTrack::artist() const\n{\n    if ( m_comTrack == 0 )\n        return L\"\";  // empty track case\n\n    BSTR bstrArtist = 0;\n    HRESULT res = m_comTrack->get_Artist( &bstrArtist );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read artist of track\" );\n\n    return ITunesComWrapper::bstrToWString( bstrArtist );\n}\n#endif\n\n\n#ifdef WIN32\nwstring\nITunesTrack::albumArtist() const\n{\n    if ( m_comTrack == 0 )\n        return L\"\";  // empty track case\n\n    BSTR bstrAlbumArtist = 0;\n\n    IITFileOrCDTrack* fileTrack = static_cast<IITFileOrCDTrack*>(m_comTrack);\n    HRESULT res = m_comTrack->QueryInterface(IID_IITFileOrCDTrack, (void**)&fileTrack);\n\n    if ( res != S_OK || fileTrack == 0 )\n    {\n        ITunesComWrapper::logComError( res, L\"albumArtist Casting IITrack to IITFileOrCDTrack failed\" );\n    }\n    else\n    {\n        res = fileTrack->get_AlbumArtist( &bstrAlbumArtist );\n        ITunesComWrapper::logComError( res, L\"Failed to read album artist of track\" );\n        fileTrack->Release();\n    }\n\n    return ITunesComWrapper::bstrToWString( bstrAlbumArtist );\n}\n#endif\n\n#ifdef WIN32\nwstring\nITunesTrack::album() const\n{\n    if ( m_comTrack == 0 )\n        return L\"\";  // empty track case\n\n    BSTR bstrAlbum = 0;\n    HRESULT res = m_comTrack->get_Album( &bstrAlbum );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read album of track\" );\n\n    return ITunesComWrapper::bstrToWString( bstrAlbum );\n}\n#endif\n\n\n#ifdef WIN32\nwstring\nITunesTrack::lastPlayed() const\n{\n    if ( m_comTrack == 0 )\n        return L\"\";  // empty track case\n\n    DATE date; // this is a double\n    HRESULT res = m_comTrack->get_PlayedDate( &date );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read last played date of track\" );\n\n    // We get a date of 0.00000 if the track has never been played\n    if ( date < 0.00001 && date > -0.00001 )\n        return L\"\";\n\n    COleDateTime oleDate( date );\n    if ( oleDate.GetStatus() == COleDateTime::valid )\n    {\n        wostringstream os;\n        os << setfill(L'0')\n           << setw(4) << oleDate.GetYear() << \"-\" << setw(2) << oleDate.GetMonth() << \"-\" << setw(2) << oleDate.GetDay() \n           << L\" \"\n           << setw(2) << oleDate.GetHour() << \":\" << setw(2) << oleDate.GetMinute() << \":\" << setw(2) << oleDate.GetSecond();\n        \n        return os.str();\n    }\n    else\n    {\n        throw ITunesException( \"Failed to read last played date of track\" );\n    }\n}\n#endif\n\n\n#ifdef WIN32\nlong\nITunesTrack::duration() const\n{\n    if ( m_comTrack == 0 )\n        return -1;  // empty track case\n\n    long duration = 0;\n    HRESULT res = m_comTrack->get_Duration( &duration );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read duration of track\" );\n\n    return duration;\n}\n#endif\n\n#ifdef WIN32\nbool\nITunesTrack::isSameAs( const ITunesTrack& that )\n{\n    if ( m_comTrack == 0 || that.m_comTrack == 0 )\n        return false;\n\n    long myDbId = 0;\n    long theirDbId = 0;\n    \n    HRESULT res = m_comTrack->get_TrackDatabaseID( &myDbId );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read db ID of track\" );\n    \n    res = that.m_comTrack->get_TrackDatabaseID( &theirDbId );\n    ITunesComWrapper::handleComResult( res, L\"Failed to read db ID of track\" );\n\n    return myDbId == theirDbId;\n}  \n#endif\n\nbool\nITunesTrack::isNull() const\n{ \n  #ifdef WIN32\n    return m_comTrack == 0;\n  #else\n    return m_id == \"\" || m_kind == \"Audio CD Track\";\n  #endif\n}\n\n\n#ifndef WIN32\n#include \"Moose.h\"\n\nstd::string //static\nITunesTrack::scriptResult( const char* filename, const std::string& argv1 ) throw()\n{\n    LOG( 4, \"Executing script: `\" << filename << \"' `\" << argv1 << '\\'' );\n    \n    std::string command;\n    command += \"osascript '\";\n    command += Moose::bundleFolder() + \"Contents/Resources/\";\n    command += filename;\n    command += \"'\";\n    \n    if ( argv1.size() )\n    {\n        command += ' ' + argv1;\n    }\n    \n    // avoid iTunes error -54\n    Moose::setFileDescriptorsCloseOnExec();\n    \n    FILE* pipe = ::popen( command.c_str(), \"r\" );\n    if ( !pipe )\n        return \"ERROR\";\n    \n    char buf[ 128 ];\n    std::string out;\n    while( fgets( buf, 128, pipe ) )\n    {\n        out += buf;\n    }\n    ::pclose( pipe );\n    \n    if ( out.length() ) {\n        out.resize( out.length() - 1 ); // last character is always a \\n\n        LOG( 4, \"Script result: `\" << out << '\\'' );\n    }\n    \n    return out;\n}\n#endif\n\n\n#ifdef WIN32\nwstring\nITunesTrack::pathForTrack( IITTrack* track )\n{\n    wstring path;\n    IITFileOrCDTrack* fileTrack = 0;\n    HRESULT res = track->QueryInterface( IID_IITFileOrCDTrack, (void**)&fileTrack );\n    if ( res != S_OK || fileTrack == 0 )\n    {\n        // Not ideal, but logging this makes the iPodScrobbler log\n        // really messy for mostly iTunes Match track libraries\n        //ITunesComWrapper::logComError( res, L\"Casting IITrack to IITFileOrCDTrack failed\" );\n    }\n    else\n    {\n        BSTR bstrLocation = 0; // BSTR = WCHAR*\n        res = fileTrack->get_Location( &bstrLocation );\n        if ( res == S_OK )\n        {\n            path = ITunesComWrapper::bstrToWString( bstrLocation );\n        }\n        else\n        {\n            BSTR a;\n            BSTR n;\n            fileTrack->get_Artist( &a );\n            fileTrack->get_Name( &n );\n            wstring artist = ITunesComWrapper::bstrToWString( a );\n            wstring track = ITunesComWrapper::bstrToWString( n );\n            wostringstream os;\n            os << L\"COM couldn't get file path for \" << artist << L\" - \" << track;\n            ITunesComWrapper::logComError( res, os.str() );\n        }\n\n        fileTrack->Release();\n    }\n\n    return path;\n}\n#endif\n\n#ifdef WIN32\nbool\nITunesTrack::podcast()\n{\n    VARIANT_BOOL podcast = FALSE;\n    IITFileOrCDTrack* fileTrack = 0;\n    HRESULT res = m_comTrack->QueryInterface( IID_IITFileOrCDTrack, (void**)&fileTrack );\n    if ( res != S_OK || fileTrack == 0 )\n    {\n        ITunesComWrapper::logComError( res, L\"podcast Casting IITrack to IITFileOrCDTrack failed\" );\n    }\n    else\n    {\n        res = fileTrack->get_Podcast( &podcast );\n        if ( res != S_OK )\n        {\n            BSTR a;\n            BSTR n;\n            fileTrack->get_Artist( &a );\n            fileTrack->get_Name( &n );\n            wstring artist = ITunesComWrapper::bstrToWString( a );\n            wstring track = ITunesComWrapper::bstrToWString( n );\n            wostringstream os;\n            os << L\"COM couldn't get podcast for \" << artist << L\" - \" << track;\n            ITunesComWrapper::logComError( res, os.str() );\n        }\n\n        fileTrack->Release();\n    }\n\n    return podcast != FALSE;\n}\n#endif\n\n#ifdef WIN32\nbool\nITunesTrack::video()\n{\n    bool video = false;\n    IITFileOrCDTrack* fileTrack = 0;\n    HRESULT res = m_comTrack->QueryInterface( IID_IITFileOrCDTrack, (void**)&fileTrack );\n    if ( res != S_OK || fileTrack == 0 )\n    {\n        ITunesComWrapper::logComError( res, L\"video Casting IITrack to IITFileOrCDTrack failed\" );\n    }\n    else\n    {\n        ITVideoKind videoKind = ITVideoKindNone;\n        res = fileTrack->get_VideoKind( &videoKind );\n        if ( res == S_OK )\n        {\n            video = videoKind != ITVideoKindNone && videoKind != ITVideoKindMusicVideo;\n        }\n        else\n        {\n            BSTR a;\n            BSTR n;\n            fileTrack->get_Artist( &a );\n            fileTrack->get_Name( &n );\n            wstring artist = ITunesComWrapper::bstrToWString( a );\n            wstring track = ITunesComWrapper::bstrToWString( n );\n            wostringstream os;\n            os << L\"COM couldn't get video kind for \" << artist << L\" - \" << track;\n            ITunesComWrapper::logComError( res, os.str() );\n        }\n\n        fileTrack->Release();\n    }\n\n    return video;\n}\n#endif\n\nint\nExtendedITunesTrack::playCountDifference() const throw( PlayCountException )\n{\n    assert( m_initialPlayCount != -2 ); // the default value for a null track\n    \n    int const playCount = this->playCount();\n\n    // COM or Applescript failed :(\n    if ( m_initialPlayCount == -1 || playCount == -1 )\n        throw PlayCountException();\n\n    return playCount - m_initialPlayCount;\n}\n"
  },
  {
    "path": "plugins/iTunes/ITunesTrack.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef ITUNES_TRACK_H\r\n#define ITUNES_TRACK_H\r\n\r\n#include \"ITunesExceptions.h\"\r\n\r\n#ifdef WIN32\r\n    // Disable warning about exception specifications\r\n    #pragma warning( disable : 4290 )\r\n\r\n\tstruct IITTrack;\r\n#endif\r\n\r\n#include <string>\r\n\r\n\r\n/** @author Max Howell <max@last.fm> -- mac\r\n  * @author Erik Jalevik <erik@last.fm> -- windows\r\n  * @brief Uses AppleScript or COM to retrieve properties of an iTunes track.\r\n  *        All functions that access COM directly will throw an ITunesException\r\n  *        if something went wrong.\r\n  */\r\nclass ITunesTrack\r\n{\r\npublic:\r\n  #ifdef WIN32\r\n\r\n    ITunesTrack(); // creates a null track\r\n      \r\n    /** Creates a track from a COM track object. Ownership is passed to this\r\n      * class and it will call Release on the object when done. Never throws. */\r\n    ITunesTrack( IITTrack* track );\r\n\r\n    // Copy ctor (needed because of owned COM pointer)\r\n    ITunesTrack( const ITunesTrack& that );\r\n    ITunesTrack& operator=( const ITunesTrack& that );\r\n    \r\n    ITunesTrack::~ITunesTrack();\r\n\r\n    /** Unicode */\r\n    std::wstring track() const;\r\n    std::wstring artist() const;\r\n\tstd::wstring albumArtist() const;\r\n    std::wstring album() const;\r\n\r\n    /** Date format: \"YYYY-MM-DD HH:MM:SS\", returns an empty string if track was never played */\r\n    std::wstring lastPlayed() const;\r\n\r\n    /** In seconds */\r\n    long duration() const;\r\n    \r\n    /** Convenience function for logging etc */\r\n    std::wstring toString() const { return artist() + L\" - \" + track(); }\r\n\r\n    /** Uses runtime ID to compare the two. */\r\n    bool isSameAs( const ITunesTrack& that );\r\n\r\n    /** These two fields are always populated when an iTunes track is created */\r\n    std::wstring persistentId() const { return m_id; }\r\n    std::wstring path() const { return m_path; }\r\n\r\n    void setPersistentId( std::wstring id ) { m_id = id; }\r\n\r\n    /** podcasts have the option of not scrobbling and videos are never scrobbled */\r\n    bool podcast();\r\n    bool video();\r\n\r\n  #else\r\n      \r\n    /** These two fields are always populated when an iTunes track is created */\r\n    std::string persistentId() const { return m_id; }\r\n    std::string path() const { return m_path; }\r\n    std::string kind() const { return m_kind; }\r\n  \r\n  #endif\r\n\r\n    /** The below fields are real-time */\r\n    long playCount() const throw( PlayCountException );\r\n    bool isNull() const;\r\n\r\nprotected:\r\n\r\n  #ifdef WIN32\r\n\r\n    std::wstring m_id;\r\n    std::wstring m_path;\r\n\r\n    std::wstring pathForTrack( IITTrack* track );\r\n    void clone( const ITunesTrack& that );\r\n\r\n    IITTrack* m_comTrack;\r\n\r\n  #else\r\n\r\n    std::string m_id; // utf8\r\n    std::string m_path; // utf8\r\n    std::string m_dbid; //database ID\r\n    std::string m_kind; // \"Audio CD Track\" etc\r\n    \r\n    /** executes an applescript in the bundle and returns the output */\r\n    static std::string scriptResult( const char* filename, const std::string& argv1 = \"\" ) throw();\r\n\r\n  #endif  \r\n};\r\n\r\n\r\n/** @author Max Howell <max@last.fm>\r\n  * @brief Specialised variety of ITunesTrack, used for playCount sync \r\n  *   operations, where we need the difference in playCount since the object was\r\n  *   initialised */\r\nclass ExtendedITunesTrack : public ITunesTrack\r\n{\r\npublic:\r\n    ExtendedITunesTrack() : m_initialPlayCount( -2 )\r\n    {}\r\n    \r\n#ifdef WIN32\r\n    static ExtendedITunesTrack from( const ITunesTrack& that )\r\n    {\r\n\t\tExtendedITunesTrack t;\r\n\t\tt.ITunesTrack::operator=( that );\r\n        t.m_initialPlayCount = that.playCount();\r\n        return t;\r\n    }\r\n#else\r\n    /** returns the track currently playing in iTunes */\r\n    static ExtendedITunesTrack currentTrack();\r\n#endif\r\n\r\n    int playCountDifference() const throw( PlayCountException );\r\n    int initialPlayCount() const { return m_initialPlayCount; }\r\n    void setInitialPlaycount( int pc ) { m_initialPlayCount = pc; }\r\n    \r\nprivate:\r\n    int m_initialPlayCount;\r\n};\r\n\r\n#endif // ITUNESTRACK_H\r\n"
  },
  {
    "path": "plugins/iTunes/Moose.h",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#ifndef MOOSE_H\n#define MOOSE_H\n\n#include <cstdio>\n#include \"common/c++/string.h\"\n#include \"common/c++/logger.h\"\n\n#ifdef WIN32\n    #define UNICORN_HKEY L\"Software\\\\Last.fm\\\\\" \n    #define MOOSE_HKEY_A \"Software\\\\Last.fm\\\\Last.fm\"\n    #define MOOSE_HKEY  L\"Software\\\\Last.fm\\\\Last.fm\"\n    #define MOOSE_PLUGIN_HKEY_A \"Software\\\\Last.fm\\\\Client\\\\Plugins\\\\itw\"\n#else\n    #define MOOSE_PREFS_PLIST \"fm.last.scrobbler\"\n    #include <vector>\n    #include <string>\n    #include <CoreServices/CoreServices.h>\n    #include <ApplicationServices/ApplicationServices.h>\n    #include <sys/syslimits.h>\n#endif\n\n\nnamespace Moose\n{\n    /** @returns  /-terminated utf8 encoded path */\n    COMMON_STD_STRING\n    applicationFolder();\n\n    /** @returns /-terminated utf8 encoded path */\n    COMMON_STD_STRING\n    applicationSupport();\n\n    /** @returns utf8 encoded Last.fm client application binary path */\n    COMMON_STD_STRING\n    applicationPath();    \n    \n    /** @returns utf8 encoded path */\n    COMMON_STD_STRING\n    twiddlyPath();\n\n    /** @returns the complete path to the plugin library binary\n      * 16-bit unicode on Windows and local 8-bit on Mac */\n    COMMON_STD_STRING\n    pluginPath();\n\n    bool\n    isTwiddlyRunning();\n\n    /** on mac, calls setFileDescriptorsCloseOnExec() for you\n      * on mac all parameters should be utf8 */\n    bool\n    exec( const COMMON_STD_STRING& command, const COMMON_STD_STRING& space_separated_args );\n    \n    bool\n    iPodScrobblingEnabled();\n\n    #if !defined WIN32\n        /** returns true if the Moose setting for launch with media player is set */\n        bool\n        launchWithMediaPlayer();\n        \n        /** call when you exec something, otherwise you'll get error -54 */\n        void\n        setFileDescriptorsCloseOnExec();\n\n        /** /-terminated */\n        std::string\n        bundleFolder();\n\n    \n        /** use launch services to start / send a message to the scrobbler */\n        void \n        launchAudioscrobbler( const std::vector<std::string>& arg );\n    #endif\n\n    #ifdef WIN32\n        /** I'm not sure what this does really --mxcl */\n        std::wstring\n        fixStr( const std::wstring& );\n\n        /** Converts our nice unicode to utf-8 using MS' horrific api call :) */\n        std::string\n        wStringToUtf8( const std::wstring& );\n    #endif\n}\n\n\n#ifndef WIN32\n    inline std::string \n    Moose::twiddlyPath()\n    {\n        FSRef appRef;\n        LSFindApplicationForInfo( kLSUnknownCreator, CFSTR( \"fm.last.Scrobbler\" ), NULL, &appRef, NULL );\n        \n        char path[PATH_MAX];\n        FSRefMakePath( &appRef, (unsigned char*)path, PATH_MAX );\n        \n        std::string ret( path );\n        ret.append( \"/Contents/Helpers/iPodScrobbler\" );\n        \n\t\treturn ret;\n    }\n#else\n    inline std::wstring\n    Moose::twiddlyPath()\n    {\n        return applicationFolder() + L\"iPodScrobbler.exe\";\n    }\n#endif\n\n#endif //MOOSE_H\n"
  },
  {
    "path": "plugins/iTunes/Moose_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#define AUDIOSCROBBLER_BUNDLEID \"fm.last.Scrobbler\"\n#include \"Moose.h\"\n#include \"common/c++/Logger.h\"\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <CoreServices/CoreServices.h>\n#include <CoreFoundation/CoreFoundation.h>\n\n\nstd::string\nMoose::applicationSupport()\n{\n    std::string path = std::getenv( \"HOME\" );\n    path += \"/Library/Application Support/Last.fm/\";\n    return path;\n}\n\n\nstatic std::string\nCFStringToStdString( CFStringRef s )\n{\n    std::string r;\n\n    if (s == NULL)\n        return r;\n\n    CFIndex n;\n    n = CFStringGetLength( s );\n    n = CFStringGetMaximumSizeForEncoding( n, kCFStringEncodingUTF8 );\n    char* buffer = new char[n];\n    CFStringGetCString( s, buffer, n, kCFStringEncodingUTF8 );\n\n    r = buffer;\n    delete[] buffer;\n    return r;\n}\n\n\nstd::string\nMoose::applicationPath()\n{\n    FSRef appRef;\n    LSFindApplicationForInfo( kLSUnknownCreator, CFSTR( AUDIOSCROBBLER_BUNDLEID ), NULL, &appRef, NULL );\n    \n    char path[PATH_MAX];\n    FSRefMakePath( &appRef, (unsigned char*)path, PATH_MAX );\n    \n    if ( path == NULL )\n        return \"/Applications/Last.fm Scrobbler.app/Contents/MacOS/Last.fm Scrobbler\";\n\n    std::string s = path;\n    s.append( \"/Contents/MacOS/Last.fm Scrobbler\" );\n    return s;\n}\n\n\nbool\nMoose::iPodScrobblingEnabled()\n{\n    Boolean key_exists;\n    bool b = CFPreferencesGetAppBooleanValue( \n                    CFSTR( \"iPodScrobblingEnabled\"),\n                    CFSTR( MOOSE_PREFS_PLIST ),\n                    &key_exists );\n                    \n    if (!key_exists) return true;\n\n    return b;\n}\n\n\nstd::string\nMoose::applicationFolder()\n{\n    std::string s = applicationPath();\n    return s.substr( 0, s.rfind( '/' ) + 1 );\n}\n\n\nbool\nMoose::launchWithMediaPlayer()\n{\n    return true;\n    CFBooleanRef v = (CFBooleanRef) CFPreferencesCopyAppValue( \n            CFSTR( \"LaunchWithMediaPlayer\" ), \n            CFSTR( MOOSE_PREFS_PLIST ) );\n\n    if (v)\n    {\n        bool b = CFBooleanGetValue( v );\n        CFRelease( v );\n        return b;\n    }\n    else\n        return true;\n}\n\n\nvoid\nMoose::setFileDescriptorsCloseOnExec()\n{\n    int n = 0;\n    int fd = sysconf( _SC_OPEN_MAX );\n    while (--fd > 2)\n    {\n        int flags = fcntl( fd, F_GETFD, 0 );\n        if ((flags != -1) && !(flags & FD_CLOEXEC))\n        {\n            n++;\n            flags |= FD_CLOEXEC;\n            fcntl( fd, F_SETFD, flags );\n        }\n    }\n    if (n) LOG( 3, \"Set \" << n << \" file descriptors FD_CLOEXEC\" );\n}\n\nvoid \nMoose::launchAudioscrobbler( const std::vector<std::string>& vargs )\n{\n    FSRef appRef;\n    LSFindApplicationForInfo( kLSUnknownCreator, CFSTR( AUDIOSCROBBLER_BUNDLEID ), NULL, &appRef, NULL );\n    \n    const void* arg[vargs.size()];\n    \n    int index(0);\n\n    AEDescList argAEList;\n    AECreateList( NULL, 0, FALSE, &argAEList );\n    \n    for( std::vector<std::string>::const_iterator i = vargs.begin(); i != vargs.end(); i++ ) {\n        arg[index++] = CFStringCreateWithCString( NULL, i->c_str(), kCFStringEncodingUTF8 );\n        AEPutPtr( &argAEList, 0, typeChar, i->c_str(), i->length());\n    }\n    \n    LSApplicationParameters params;\n    params.version = 0;\n    params.flags = kLSLaunchAndHide | kLSLaunchDontSwitch | kLSLaunchAsync;;\n    params.application = &appRef;\n    params.asyncLaunchRefCon = NULL;\n    params.environment = NULL;\n    \n    CFArrayRef args = CFArrayCreate( NULL, ((const void**)arg), vargs.size(), NULL);\n    params.argv = args;\n    \n  \n    AEAddressDesc target;\n    AECreateDesc( typeApplicationBundleID, CFSTR( AUDIOSCROBBLER_BUNDLEID ), 16, &target);\n    \n    AppleEvent event;\n    AECreateAppleEvent ( kCoreEventClass,\n                        kAEReopenApplication ,\n                        &target,\n                        kAutoGenerateReturnID,\n                        kAnyTransactionID,\n                        &event );\n    \n    AEPutParamDesc( &event, keyAEPropData, &argAEList );\n    \n    params.initialEvent = &event;\n    \n    LSOpenApplication( &params, NULL );\n    AEDisposeDesc( &argAEList );\n    AEDisposeDesc( &target );\n}\n\n\nbool\nMoose::exec( const std::string& command, const std::string& args )\n{\n    // fixes error -54 bug, where endless dialogs are spawned\n    // presumably because the child Twiddly process inherits some key\n    // file descriptors from iTunes\n    setFileDescriptorsCloseOnExec();\n    \n    std::string s = \"\\\"\" + command + \"\\\" \" + args + \" &\";\n\n    LOG( 3, \"Launching `\" << s << \"'\" )\n    return ( std::system( s.c_str() ) >= 0 );\n}\n\n\n#include \"common/c++/mac/getBsdProcessList.c\"\n\n\nbool\nMoose::isTwiddlyRunning()\n{\n    bool found = false;\n    \n    kinfo_proc* processList = NULL;\n    size_t processCount = 0;\n\n    if ( getBsdProcessList( &processList, &processCount ) )\n    {\n        LOG( 3, \"Failed to get the process list\" );\n        return false;\n    }\n\n    uint const uid = ::getuid();\n    for ( size_t processIndex = 0; processIndex < processCount; processIndex++ )\n    {\n        if ( processList[processIndex].kp_eproc.e_pcred.p_ruid == uid )\n        {\n            if ( strcmp( processList[processIndex].kp_proc.p_comm, \"twiddly\" ) == 0 )\n            {\n                found = true;\n                break;\n            }\n        }\n    }\n\n    free( processList );\n\n    if ( found ) LOG( 3, \"Twiddly already running!\" );\n\n    return found;\n}\n\n\nstd::string\nMoose::bundleFolder()\n{\n    std::string path;\n    path += ::getenv( \"HOME\" );\n    path += \"/Library/iTunes/iTunes Plug-ins/AudioScrobbler.bundle/\";\n    return path;\n}\n\n\nstd::string\nMoose::pluginPath()\n{\n    return bundleFolder() + \"Contents/MacOS/AudioScrobbler\";\n}\n"
  },
  {
    "path": "plugins/iTunes/Moose_win.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#include \"Moose.h\"\n#include <Windows.h>\n#include <shlobj.h>\n#include <wchar.h>\n#include \"common/c++/Logger.h\"\n#include \"RegistryUtils.h\" // part of ScrobSub\n\nusing namespace::std;\n\n\nstd::wstring\nMoose::applicationSupport()\n{\n    // This might not work on Win98 and earlier but we're not officially\n    // supporting them anyway. Upgrading to IE5 will solve the problem.\n    wchar_t acPath[MAX_PATH];\n    HRESULT h = SHGetFolderPathW( NULL, \n                                 CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE,\n                                 NULL, \n                                 0, \n                                 acPath );\n    if ( h != S_OK )\n        wcscpy( acPath, L\"C:\" );\n\n    return std::wstring( acPath ) + L\"\\\\Last.fm\\\\Client\";\n}\n\n\n/** I'm not sure what this does really --mxcl */\nstd::wstring\nMoose::fixStr(const std::wstring& str)\n{\n    std::wstring ret;\n    \n    if (str.length() == 0) return str;\n    \n    // Mac strings store the length in the first char of the string:\n    size_t len = (size_t)str[0];\n    ret = str.substr(1);\n    if(len > 0 && len < ret.length())\n    {\n        ret = ret.substr(0,len);\n    }\n    return ret;\n}\n\n\n/** Converts our nice unicode to utf-8 using MS' horrific api call :) */\nstd::string\nMoose::wStringToUtf8( const std::wstring& wideStr )\n{\n    // first call works out required buffer length\n    int recLen = WideCharToMultiByte(CP_UTF8,0,wideStr.c_str(),(int)wideStr.length(),NULL,NULL,NULL,NULL);\n    \n    char* buffer = new char[recLen + 1];\n    memset(buffer,0,recLen+1);\n    \n    //  second call actually converts\n    WideCharToMultiByte(CP_UTF8,0,wideStr.c_str(),(int)wideStr.length(),buffer,recLen,NULL,NULL);\n    \n    std::string ret = buffer;\n    \n    // fuck <-- this comment for the sake of GoogleCode profanity searches\n    delete[] buffer;\n    \n    return ret;\n}\n\n\n    std::wstring\n    Moose::applicationPath()\n    {\n        HKEY h;\n        LONG lResult = RegOpenKeyExA(\n            HKEY_CURRENT_USER, \n            MOOSE_HKEY_A,\n            0,              // reserved\n            KEY_READ, // access mask\n            &h );\n\n        wchar_t buffer[MAX_PATH];\n        buffer[0] = L'\\0';\n\n        if ( lResult == ERROR_SUCCESS )\n        {\n            try\n            {\n                RegistryUtils::QueryString( h, L\"Path\", buffer, MAX_PATH, false );\n            }\n            catch ( const RegistryUtils::CRegistryException& )\n            {\n                LOGL( 2, \"Client path not found in HKCU\" );\n            }\n\n            RegCloseKey( h );\n        }\n\n        if ( buffer[0] == L'\\0' )\n        {\n            // Couldn't read path from HKCU, try HKLM\n            lResult = RegOpenKeyExA(\n                HKEY_LOCAL_MACHINE,\n                MOOSE_HKEY_A,\n                0,              // reserved\n                KEY_READ,       // access mask\n                &h);\n        \n            if ( lResult == ERROR_SUCCESS )\n            {\n                try\n                {\n                    RegistryUtils::QueryString( h, L\"Path\", buffer, MAX_PATH, false );\n                }\n                catch ( const RegistryUtils::CRegistryException& )\n                {\n                    LOGL( 2, \"Client path not found in HKLM\" );\n                }\n\n                RegCloseKey( h );\n            }\n        }\n\n        if ( buffer[0] == L'\\0' )\n        {\n            LOGL( 1, \"Couldn't read the client path from the registry.\");\n            return std::wstring();\n        }    \n\n        return buffer;\n    }\n\n\n    std::wstring\n    Moose::applicationFolder()\n    {\n        std::wstring result = Moose::applicationPath();\n\n        size_t pos = result.rfind( '\\\\' );\n        if ( pos == wstring::npos )\n            pos = result.rfind( '/' );\n            \n        if ( pos == wstring::npos )\n        {\n            LOGL( 2, \"Path to exe invalid\" );\n            return std::wstring();\n        }\n        \n        return result.substr( 0, pos + 1 );\n    }\n\n\nbool\nMoose::exec( const std::wstring& command, const std::wstring& args )\n{\n    LOGWL( 3, \"Launching `\" << command << ' ' << args << '\\'' );\n    HINSTANCE h = ShellExecuteW( NULL,\n                                L\"open\",\n                                command.c_str(),\n                                args.c_str(),\n                                NULL,\n                                SW_SHOWNORMAL );\n\n    if ( h <= reinterpret_cast<void*>( 32 ) )\n    {\n        LOGWL( 3, \"Failed launching `\" << command <<  \"'\\n. ShellExecute error: \" << h );\n        return false;\n    }\n\n    return true;\n}\n\n\nbool\nMoose::isTwiddlyRunning()\n{\n    bool found = false;\n\n    HANDLE mutex = ::CreateMutexA(  NULL,\n                                    false,\n                                    \"Twiddly-05F67299-64CC-4775-A10B-0FBF41B6C4D0\" );\n    \n    DWORD const e = ::GetLastError();\n    if( e == ERROR_ALREADY_EXISTS || e == ERROR_ACCESS_DENIED )\n    {\n        //Can't create the mutex so twiddly must be running\n        found = true;\n    }\n\n    //close the handle so that twiddly can create the mutex\n    BOOL success = ::CloseHandle( mutex );\n    LOGL( 3, \"Twiddly mutex closed: \" << (success ? \"true\" : \"false\") );\n\n    if ( found ) LOGL( 3, \"Twiddly already running!\" );\n\n    return found;\n}\n\n\nstd::wstring\nMoose::pluginPath()\n{\n    std::wstring path = L\"C:\\\\Program Files\\\\iTunes\\\\Plug-Ins\\\\itw_scrobbler.dll\";\n    HKEY h = NULL;\n    \n    try\n    {\n        LONG l = RegOpenKeyExA( HKEY_LOCAL_MACHINE,\n                                MOOSE_PLUGIN_HKEY_A,\n                                0,              // reserved\n                                KEY_READ,       // access mask\n                                &h );\n\n        if (l == ERROR_SUCCESS)\n        {\n            wchar_t buffer[MAX_PATH];\n            RegistryUtils::QueryString( h, \n                                        L\"Path\", \n                                        buffer, \n                                        MAX_PATH, \n                                        false, \n                                        path.c_str() /*default*/ );\n            path = buffer;\n        }\n    }\n    catch (RegistryUtils::CRegistryException&)\n    {}\n    \n    RegCloseKey( h );\n    \n    return path;\n}\n\n\nbool\nMoose::iPodScrobblingEnabled()\n{\n    bool b = true;\n    HKEY h = NULL;\n\n    try\n    {\n        LONG l = RegOpenKeyExA( HKEY_CURRENT_USER,\n                                MOOSE_HKEY_A,\n                                0,            // reserved\n                                KEY_READ,     // access mask\n                                &h );\n\n        if (l == ERROR_SUCCESS)\n        {\n            // Qt stores booleans as strings! :(\n            wchar_t buffer[12];\n            RegistryUtils::QueryString( h, L\"iPodScrobblingEnabled\", buffer, 12, false, L\"true\" /*default*/ );\n            b = wcscmp( buffer, L\"true\" ) == 0;\n        }\n    }\n    catch (RegistryUtils::CRegistryException&)\n    {}\n\n    RegCloseKey( h );\n\n    return b;\n}\n"
  },
  {
    "path": "plugins/iTunes/Plist.cpp",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#include \"Plist.h\"\r\n#include <string>\r\n#include <sstream>\r\n\r\nstatic const std::string base64chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\r\n\r\nvoid Plist::read( std::istream &in)\r\n{\r\n    //std::string buffer;\r\n    std::stringbuf buffer;\r\n    char tmp;\r\n    while( in.good() )\r\n    {\r\n        in >> tmp;\r\n        if(  tmp == '<' && ( in.peek() == '?' || in.peek() == '!' ) )\r\n        {\r\n            in.get( buffer, '>' );\r\n            in.get();\r\n            continue;\r\n        }\r\n        else\r\n            in.putback( tmp );\r\n\r\n        m_root = Element( in );\r\n    }\r\n}\r\n\r\nvoid Plist::write( std::ostream& out ) const\r\n{\r\n    out << m_root;\r\n}\r\n\r\nElement::~Element()\r\n{\r\n    if( m_type == DATA )\r\n        delete[] m_dataPtr;\r\n}\r\n\r\n\r\nElement& \r\nElement::operator=( const Element& element )\r\n{\r\n    m_type = element.m_type;\r\n    m_string = element.m_string;\r\n    m_dataLength = element.m_dataLength;\r\n    m_dict = element.m_dict;\r\n    m_string = element.m_string;\r\n    m_array = element.m_array;\r\n    m_indent = element.m_indent;\r\n\r\n    if( element.m_type == DATA )\r\n    {\r\n        m_dataPtr = new char[ m_dataLength ];\r\n        memcpy( m_dataPtr, element.m_dataPtr, m_dataLength );\r\n    }\r\n    return *this;\r\n}\r\n\r\n\r\nstd::string //static\r\nElement::trim( const std::string& str )\r\n{\r\n    std::string retVal;\r\n    std::string::const_iterator iter;\r\n    for( iter = str.begin(); iter != str.end(); iter++ )\r\n    {\r\n        if( *iter != ' ' && \r\n            *iter != '\\n' &&\r\n            *iter != '\\t' )\r\n            retVal+= *iter;\r\n    }\r\n    return retVal;\r\n}\r\n\r\n\r\nvoid \r\nElement::read(std::istream &in)\r\n{\r\n    std::string elementName = readElementName( in );\r\n\r\n    if( elementName.find( \"<plist\" ) == 0 )\r\n    {\r\n        m_type = PLIST;\r\n        while( in.good() )\r\n        {\r\n            m_array.push_back( Element( in ) );\r\n        }\r\n    }\r\n    else if( elementName.find( \"<string\" ) == 0 )\r\n    {\r\n        m_type = Element::STRING;\r\n        m_string = readElementContents( in );\r\n    }\r\n    else if( elementName.find( \"<data\" ) == 0 )\r\n    {\r\n        m_type = Element::DATA;\r\n        m_string = trim( readElementContents( in ) );\r\n        m_dataLength = (unsigned int(m_string.length()) / 4) * 3;\r\n        m_dataPtr = new char[ m_dataLength ];\r\n        base64decode( m_string, m_dataPtr );\r\n    }\r\n    else if( elementName.find( \"<date\" ) == 0 )\r\n    {\r\n        m_type = Element::DATE;\r\n        m_string = readElementContents( in );\r\n    }\r\n    else if( elementName.find( \"<dict\" ) == 0 )\r\n    {\r\n        m_type = Element::DICT;\r\n        std::string curElement = readElementName( in );\r\n        while( curElement.find( \"</dict>\" ) == std::string::npos )\r\n        {\r\n            if( curElement.find( \"<key\" ) == std::string::npos )\r\n                throw std::string( \"Unexpected element - expecting key\" );\r\n\r\n            std::string key = readElementContents( in );\r\n            \r\n            curElement = readElementName( in );\r\n\r\n            if( curElement.find( \"</key>\" ) == std::string::npos )\r\n                throw std::string( \"Parsing error: Missed match key tags.\" );\r\n\r\n            m_dict[ key ] = Element( in );\r\n            m_dict[ key ].setIndent( m_indent + 1 );\r\n            curElement = readElementName( in );\r\n        }\r\n        return;\r\n    }\r\n    //remove closing tag from the stream\r\n    //TODO: check for mismatched elements?\r\n    readElementName( in );\r\n}\r\n\r\n\r\nstd::string \r\nElement::readElementName( std::istream& in ) const\r\n{\r\n    std::stringbuf buffer;\r\n    in.get( buffer, '>' );\r\n    std::string elementName = trim( buffer.str() );\r\n    elementName += in.get();\r\n    return elementName;\r\n}\r\n\r\n\r\nstd::string \r\nElement::readElementContents( std::istream& in ) const\r\n{\r\n    std::stringbuf buffer;\r\n    in.get( buffer, '<' );\r\n    return buffer.str();\r\n}\r\n\r\n\r\nvoid\r\nElement::write(std::ostream &out) const\r\n{\r\n    switch( m_type )\r\n    {\r\n    case PLIST:\r\n    case ARRAY:\r\n        {\r\n            std::vector<Element>::const_iterator iter;\r\n            for( iter = m_array.begin(); iter != m_array.end(); iter++ )\r\n            {\r\n                out << *iter << std::endl;\r\n            }\r\n        }\r\n        break;\r\n    case DICT:\r\n        {\r\n            std::map< std::string, Element >::const_iterator iter;\r\n            for( iter = m_dict.begin(); iter != m_dict.end(); iter++ )\r\n            {\r\n                out << std::endl;\r\n                for( int i = 0; i < m_indent; i++ )\r\n                    out << '\\t';\r\n\r\n                out << iter->first << \" = \" << iter->second << std::endl;\r\n            }\r\n        }\r\n        break;\r\n\r\n    case STRING:\r\n    case DATE:\r\n    case DATA:\r\n        out << m_string;\r\n        break;\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nElement::base64decode( std::string &in, char *out )\r\n{\r\n    if( in.length() > 0 && in.length() % 4 )\r\n    {\r\n        throw std::string( \"Error cannot convert from base64 - wrong character length\" );\r\n    }\r\n    std::string::iterator iter;\r\n    char n[4];\r\n    unsigned int outIndex = 0;\r\n\r\n    for( iter = in.begin(); iter != in.end(); )\r\n    {\r\n        for( int i = 0; i < 4; i++ )\r\n        {\r\n            n[i] = *(iter++);\r\n\r\n            // the '=' character is used as padding in base64\r\n            if( n[i] == '=' )\r\n            {\r\n                n[i] = 0;\r\n                continue;\r\n            }\r\n\r\n            //get the index of the character\r\n            n[i] = base64chars.find( n[i] );\r\n        }\r\n        \r\n        //redistribute the 4 x 6byte values into 3 x 8byte values\r\n        //and insert into output buffer.\r\n        out[outIndex++] = ( n[0] << 2) + ((n[1] & 0x30) >> 4);\r\n        out[outIndex++] = ((n[1] & 0xf) << 4) + ((n[2] & 0x3c) >> 2);\r\n        out[outIndex++] = ((n[2] & 0x3) << 6) + n[3];\r\n    }\r\n}\r\n\r\n\r\nElement& \r\nElement::operator[]( const std::string& key )\r\n{ \r\n    if( m_type != DICT ) \r\n        throw std::string( \"Could not access key from non dictionary node.\" ); \r\n    \r\n    return m_dict[ key ];\r\n}\r\n\r\n\r\nElement& \r\nElement::operator[]( int index )\r\n{ \r\n    if( m_type != ARRAY && \r\n        m_type != PLIST )\r\n    {\r\n        throw std::string( \"Can only access elements by index with Array or Plist elements.\" );\r\n    }\r\n    return m_array[ index ];\r\n}\r\n\r\n\r\nconst char * const\r\nElement::getData() const\r\n{\r\n    if( m_type != DATA )\r\n    {\r\n        throw std::string( \"Can only access data from DATA elements\" );\r\n    }\r\n    return m_dataPtr;\r\n}\r\n"
  },
  {
    "path": "plugins/iTunes/Plist.h",
    "content": "/*\r\n   Copyright 2005-2009 Last.fm Ltd. \r\n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \r\n        Christian Muehlhaeuser\r\n\r\n   This file is part of the Last.fm Desktop Application Suite.\r\n\r\n   lastfm-desktop is free software: you can redistribute it and/or modify\r\n   it under the terms of the GNU General Public License as published by\r\n   the Free Software Foundation, either version 3 of the License, or\r\n   (at your option) any later version.\r\n\r\n   lastfm-desktop is distributed in the hope that it will be useful,\r\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r\n   GNU General Public License for more details.\r\n\r\n   You should have received a copy of the GNU General Public License\r\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\r\n*/\r\n#ifndef PLIST_H\r\n#define PLIST_H\r\n\r\n#include <iostream>\r\n#include <map>\r\n#include <vector>\r\n\r\n\r\n/** @author Jono Cole <jono@last.fm>\r\n  * @brief Represents a single plist/array/dict/data/string/date element\r\n  *        and can read / write from a stream\r\n  */\r\nclass Element\r\n{\r\npublic:\r\n    Element():m_indent(0){}\r\n\r\n    /** Construct an element by reading from an istream */\r\n    explicit Element( std::istream& in ):m_indent(0){ read( in ); }\r\n\r\n    ~Element();\r\n\r\n    /** Retrieve an indexed element from an array or plist type element */\r\n    Element& operator[]( int index );\r\n\r\n    /** Retrieve an element from a dictionary based on a key */\r\n    Element& operator[]( const std::string& key );\r\n\r\n    /** set the indent size (used for pretty formatting when debugging!) */\r\n    void setIndent( int indent ){ m_indent = indent; }\r\n\r\n    /** get data length **/\r\n    const int getDataLength() const{ return m_dataLength; }\r\n\r\n    /** get a pointer the data stored in a data element */\r\n    const char * const getData() const;\r\n\r\n    /** Populate an Element from data in an istream */\r\n    void read( std::istream& in );\r\n\r\n    /** Write a prettified representation of the element to an ostream */\r\n    void write( std::ostream& out ) const;\r\n\r\n    /** Copy constructor calls operator= */\r\n    Element( const Element& element ){ *this = element; }\r\n\r\n    /** Overloaded operator= to make sure that data is copied if \r\n      * the element is a data element */\r\n    Element& operator=( const Element& element );\r\n\r\nprivate:\r\n    enum{ STRING = 0,\r\n      DATA,\r\n      DATE,\r\n      ARRAY,\r\n      DICT,\r\n      PLIST} m_type;\r\n\r\n    std::string m_string;\r\n    std::vector<Element> m_array;\r\n    std::map< std::string, Element > m_dict;\r\n    \r\n    unsigned int m_dataLength;\r\n    char* m_dataPtr;\r\n\r\n    int m_indent;\r\n\r\n    /** read the next element name from the stream\r\n      * (ie <dict>, <plist>, <string> etc.)\r\n\t  * NOTE calls trim on the elementName\r\n\t  * TODO name with trim in it\r\n      */\r\n    std::string readElementName( std::istream& in ) const;\r\n\r\n    /** read the conents of the element ie the data between \r\n      * <data> and </data> elements\r\n      */\r\n    std::string readElementContents( std::istream& in ) const;\r\n    \r\n\t/** removes all whitespace, including internal whitespace */\r\n    static std::string trim( const std::string& str );\r\n\r\n    /** decode the base64 encoded in string into the out buffer */\r\n    void base64decode( std::string& in, char* out );\r\n};\r\n\r\ninline std::istream& operator>>( std::istream& in, Element& element ){ element.read( in ); return in; }\r\ninline std::ostream& operator<<( std::ostream& out, const Element& element ){ element.write( out ); return out; }\r\n\r\n\r\n/** @author Jono Cole <jono@last.fm>\r\n  * @brief Represents a single plist file and can read / write from a stream\r\n  *        using m_root as the root node.\r\n  */\r\nclass Plist\r\n{\r\npublic:\r\n    Plist(){}\r\n    Plist( std::istream& in ){ read( in ); }\r\n    ~Plist(void){};\r\n    void read( std::istream& in );\r\n    void write( std::ostream& out ) const;\r\n\r\n    template <class T>\r\n        Element& operator[]( T index ){ return m_root[ index ]; }\r\n\r\nprivate:\r\n    Element m_root;\r\n};\r\n\r\ninline std::istream& operator>>( std::istream& in, Plist& plist ){ plist.read( in ); return in; }\r\ninline std::ostream& operator<<( std::ostream& out, const Plist& plist ){ plist.write( out ); return out; }\r\n\r\n#endif // PLIST_H"
  },
  {
    "path": "plugins/iTunes/README.dist",
    "content": "Edit the version in:\n\nmain.h\niScrobbleWin.rc\nitunes_install.iss\niTunes Scrobbler.plist\n\nNote there are two version numbers in the iss file.\n\nBuild the release build in Visual Studio.\n\nThen open the iss and compile to get the installer exe.\n\n"
  },
  {
    "path": "plugins/iTunes/_iTunes.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=6.0.5.4\r\n\r\n[Setup]\r\nOutputBaseFilename=iTunesPluginWinSetup_6.0.5.4\r\n; setup.exe version\r\nVersionInfoVersion=6.0.5.4\r\nVersionInfoTextVersion=6.0.5.4\r\nAppName=Last.fm iTunes Plugin\r\nAppVerName=Last.fm iTunes Plugin {cm:Version}\r\nVersionInfoDescription=Last.fm iTunes Plugin Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright  Ltd (c)\r\nDefaultDirName=\"{pf}\\iTunes\\Plug-Ins\"\r\nUsePreviousAppDir=yes\r\nUninstallFilesDir={commonappdata}\\Last.fm\\Client\\UninstITW\r\nOutputDir=.\r\nCompression=lzma\r\nSolidCompression=yes\r\nDirExistsWarning=no\r\nDisableReadyPage=yes\r\n; Keep this the same across versions, even if they're incompatible. That will ensure\r\n; uninstallation works fine after many upgrades. Can't use GUID as it'll break backward\r\n; compatibility.\r\nAppId=Audioscrobbler iTunes Plugin\r\nCreateUninstallRegKey=no\r\n\r\n[Dirs]\r\nName: \"{localappdata}\\Last.fm\\Client\"\r\n\r\n[Registry]\r\n; The name of the final subkey here must match the one in plugins.data\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\itw\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\itw\"; ValueType: string; ValueName: \"Name\"; ValueData: \"iTunes\"; Flags: uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\itw\"; ValueType: string; ValueName: \"Path\"; ValueData: \"{app}\\itw_scrobbler.dll\"; Flags: uninsdeletekey\r\n\r\n[Languages]\r\nName: \"english\"; MessagesFile: \"compiler:Default.isl\"\r\n\r\n[InstallDelete]\r\n; This is the name of the old old plugin\r\nType: files; Name: \"{app}\\iScrobbleWin.dll\"\r\n; This is the name of the old ASS plugin\r\nType: files; Name: \"{app}\\audioscrobbler.dll\"\r\n\r\n[UninstallDelete]\r\n; For legacy reasons\r\nType: files; Name: \"{app}\\audioscrobbler.log\"\r\n\r\n; Try and delete the localappdata log for the case where the user running the uninstaller is the same as the plugin user\r\nType: files; Name: \"{localappdata}\\Last.fm\\Client\\iTunesPlugin.log\"\r\n\r\n[Files]\r\nSource: \"Release\\itw_scrobbler.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n\r\n[Run]\r\n\r\n[Code]\r\nprocedure CurStepChanged(CurStep: TSetupStep);\r\nvar\r\n  batfile: String;\r\n  batcontent: String;\r\n  uninstaller: String;\r\n  alreadyAdded: Boolean;\r\n  cmdToAdd: String;\r\nbegin\r\n  if (CurStep = ssPostInstall) then\r\n  begin\r\n    //MsgBox('postinstall', mbInformation, MB_OK);\r\n\r\n    batfile := ExpandConstant('{commonappdata}\\Last.fm\\Client\\uninst2.bat');\r\n    LoadStringFromFile(batfile, batcontent);\r\n    //MsgBox('loaded string: ' + batcontent, mbInformation, MB_OK);\r\n\r\n    uninstaller := ExpandConstant('{uninstallexe}');\r\n    //MsgBox('uninstaller pre-OEM: ' + uninstaller, mbInformation, MB_OK);\r\n\r\n    alreadyAdded := (Pos(uninstaller, batcontent) <> 0);\r\n    if (alreadyAdded = False) then\r\n    begin\r\n      cmdToAdd := uninstaller + #13#10;\r\n      //MsgBox('not present, will add: ' + cmdToAdd, mbInformation, MB_OK);\r\n\r\n      SaveStringToFile(batfile, cmdToAdd, True)\r\n    end;\r\n\r\n  end;\r\n\r\nend;\r\n\r\n"
  },
  {
    "path": "plugins/iTunes/_iTunes.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>English</string>\n\t<key>CFBundleExecutable</key>\n\t<string>AudioScrobbler</string>\n\t<key>CFBundleGetInfoString</key>\n\t<string>The official Last.fm iTunes AudioScrobbler plugin</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>fm.last.iTunes Scrobbler</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>AudioScrobbler</string>\n\t<key>CFBundleDisplayName</key>\n\t<string>Last.fm iTunes AudioScrobbler</string>\n\t<key>CFBundlePackageType</key>\n\t<string>hvpl</string>\n\t<key>CFBundleSignature</key>\n\t<string>hook</string>\n\t<key>CFBundleVersion</key>\n\t<string>6.0.5.4</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>6.0.5</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "plugins/iTunes/_iTunes.rc",
    "content": "// Microsoft Visual C++ generated resource script.\r\n//\r\n#include \"resource.h\"\r\n\r\n#define APSTUDIO_READONLY_SYMBOLS\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 2 resource.\r\n//\r\n#include \"afxres.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#undef APSTUDIO_READONLY_SYMBOLS\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.S.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTINCLUDE\r\n//\r\n\r\n1 TEXTINCLUDE \r\nBEGIN\r\n    \"resource.h\\0\"\r\nEND\r\n\r\n2 TEXTINCLUDE \r\nBEGIN\r\n    \"#include \"\"afxres.h\"\"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n3 TEXTINCLUDE \r\nBEGIN\r\n    \"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n#endif    // English (U.S.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.K.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Version\r\n//\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\n FILEVERSION 6,0,5,4\r\n PRODUCTVERSION 6,0,5,4\r\n FILEFLAGSMASK 0x17L\r\n#ifdef _DEBUG\r\n FILEFLAGS 0x1L\r\n#else\r\n FILEFLAGS 0x0L\r\n#endif\r\n FILEOS 0x4L\r\n FILETYPE 0x2L\r\n FILESUBTYPE 0x0L\r\nBEGIN\r\n    BLOCK \"StringFileInfo\"\r\n    BEGIN\r\n        BLOCK \"080904b0\"\r\n        BEGIN\r\n            VALUE \"Comments\", \"http://www.last.fm\"\r\n            VALUE \"CompanyName\", \"Last.fm\"\r\n            VALUE \"FileDescription\", \"Last.fm iTunes plugin\"\r\n            VALUE \"FileVersion\", \"6, 0, 5, 4\"\r\n            VALUE \"InternalName\", \"itw_scrobbler\"\r\n            VALUE \"LegalCopyright\", \"Copyright (C) 2008\"\r\n            VALUE \"OriginalFilename\", \"itw_scrobbler.dll\"\r\n            VALUE \"ProductName\", \"Last.fm iTunes plugin\"\r\n            VALUE \"ProductVersion\", \"6, 0, 5, 4\"\r\n        END\r\n    END\r\n    BLOCK \"VarFileInfo\"\r\n    BEGIN\r\n        VALUE \"Translation\", 0x809, 1200\r\n    END\r\nEND\r\n\r\n#endif    // English (U.K.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n#ifndef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 3 resource.\r\n//\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#endif    // not APSTUDIO_INVOKED\r\n\r\n"
  },
  {
    "path": "plugins/iTunes/_iTunes.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 46;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t4C3C565816849BEC002A3DBC /* sqlite3.c in Sources */ = {isa = PBXBuildFile; fileRef = 4C3C565616849BEB002A3DBC /* sqlite3.c */; };\n\t\t4C7B8BBE141657F600C2A26C /* iTunesAPI.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4C7B8BBD141657F600C2A26C /* iTunesAPI.cpp */; };\n\t\t4CCE0E96162725220090F29C /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4CCE0E95162725220090F29C /* Cocoa.framework */; };\n\t\t63233BAF0D7491470009EC65 /* Logger.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 63233BAD0D7491470009EC65 /* Logger.cpp */; };\n\t\t632E70550DD9FF0200A16D88 /* playCountForDatabaseId.scpt in Resources */ = {isa = PBXBuildFile; fileRef = 632E70520DD9FEF900A16D88 /* playCountForDatabaseId.scpt */; };\n\t\t633C62970D6CA1DD00B609B9 /* main_mac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 633C62960D6CA1DD00B609B9 /* main_mac.cpp */; };\n\t\t634E6EF50D3FBA7D00E16E0D /* currentTrackLocation.scpt in Resources */ = {isa = PBXBuildFile; fileRef = 638053560D3E95A10003DB13 /* currentTrackLocation.scpt */; };\n\t\t634E6EF60D3FBA7D00E16E0D /* currentTrackPersistentId.scpt in Resources */ = {isa = PBXBuildFile; fileRef = 638053570D3E95A10003DB13 /* currentTrackPersistentId.scpt */; };\n\t\t634E6EF70D3FBA7D00E16E0D /* playCountForPersistentId.scpt in Resources */ = {isa = PBXBuildFile; fileRef = 638053580D3E95A10003DB13 /* playCountForPersistentId.scpt */; };\n\t\t637452E10D58B02B00429514 /* Moose_mac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 637452E00D58B02B00429514 /* Moose_mac.cpp */; };\n\t\t637A231E0DAA9B1C004590E1 /* uninstall.sh in Resources */ = {isa = PBXBuildFile; fileRef = 637A231D0DAA9B1C004590E1 /* uninstall.sh */; };\n\t\t638052470D3E53940003DB13 /* ChangeLog.txt in Resources */ = {isa = PBXBuildFile; fileRef = 638052460D3E53940003DB13 /* ChangeLog.txt */; };\n\t\t6392AF640D788A2D00E1B4F6 /* ITunesPlaysDatabase.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6392AF620D788A2D00E1B4F6 /* ITunesPlaysDatabase.cpp */; };\n\t\t63B2F45E0E9FBECD0088AF7A /* ITunesTrack.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 63B2F45D0E9FBECD0088AF7A /* ITunesTrack.cpp */; };\n\t\t63E5E4770D6B51C500774857 /* IPodDetector_mac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 63E5E4760D6B51C500774857 /* IPodDetector_mac.cpp */; };\n\t\t63ED46C20DD8D52900F6FBE0 /* currentTrack.scpt in Resources */ = {isa = PBXBuildFile; fileRef = 63ED46BF0DD8D51D00F6FBE0 /* currentTrack.scpt */; };\n\t\tDC26679C0BD9410900B4ED68 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 01285C0700CC38597F000001 /* main.cpp */; };\n\t\tDC26679F0BD9410900B4ED68 /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0AA1909FFE8422F4C02AAC07 /* CoreFoundation.framework */; };\n\t\tFB0C1E670D9919CD004820B9 /* CoreServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB0C1E660D9919CD004820B9 /* CoreServices.framework */; };\n\t\tFB0C20D00D9922CD004820B9 /* Carbon.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB0C20CF0D9922CD004820B9 /* Carbon.framework */; };\n\t\tFB3EA6B90D5795BE003DC14E /* ITunesPlaysDatabase_mac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FB3EA6B70D5795BE003DC14E /* ITunesPlaysDatabase_mac.cpp */; };\n\t\tFB4ED6F30D6B00CE00F243B8 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FB4ED6F20D6B00CE00F243B8 /* IOKit.framework */; };\n\t\tFB6471A70D80643A007006E4 /* IPod.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FB6471A40D806439007006E4 /* IPod.cpp */; };\n\t\tFB6471A90D80643A007006E4 /* IPod_mac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = FB6471A60D80643A007006E4 /* IPod_mac.cpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXFileReference section */\n\t\t01285C0200CC31B17F000001 /* iTunesAPI.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = iTunesAPI.h; sourceTree = \"<group>\"; };\n\t\t01285C0300CC31B17F000001 /* iTunesVisualAPI.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = iTunesVisualAPI.h; sourceTree = \"<group>\"; };\n\t\t01285C0700CC38597F000001 /* main.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 30; path = main.cpp; sourceTree = \"<group>\"; };\n\t\t0AA1909FFE8422F4C02AAC07 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = /System/Library/Frameworks/CoreFoundation.framework; sourceTree = \"<absolute>\"; };\n\t\t4C3C565616849BEB002A3DBC /* sqlite3.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = sqlite3.c; path = libs/sqlite3.c; sourceTree = \"<group>\"; };\n\t\t4C3C565716849BEB002A3DBC /* sqlite3.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = sqlite3.h; path = libs/sqlite3.h; sourceTree = \"<group>\"; };\n\t\t4C7B8BBD141657F600C2A26C /* iTunesAPI.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = iTunesAPI.cpp; sourceTree = \"<group>\"; };\n\t\t4CCE0E95162725220090F29C /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/System/Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; };\n\t\t63233BAD0D7491470009EC65 /* Logger.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = Logger.cpp; path = \"../../common/c++/Logger.cpp\"; sourceTree = \"<group>\"; };\n\t\t63233BAE0D7491470009EC65 /* Logger.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Logger.h; path = \"../../common/c++/Logger.h\"; sourceTree = \"<group>\"; };\n\t\t632E70520DD9FEF900A16D88 /* playCountForDatabaseId.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.scpt; name = playCountForDatabaseId.scpt; path = scripts/playCountForDatabaseId.scpt; sourceTree = \"<group>\"; };\n\t\t633C62960D6CA1DD00B609B9 /* main_mac.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = main_mac.cpp; sourceTree = \"<group>\"; };\n\t\t637452E00D58B02B00429514 /* Moose_mac.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = Moose_mac.cpp; sourceTree = \"<group>\"; };\n\t\t637A1ED30D4FCA15004FA19F /* Moose.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = Moose.h; sourceTree = \"<group>\"; };\n\t\t637A231D0DAA9B1C004590E1 /* uninstall.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; name = uninstall.sh; path = scripts/uninstall.sh; sourceTree = \"<group>\"; };\n\t\t638052460D3E53940003DB13 /* ChangeLog.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ChangeLog.txt; sourceTree = \"<group>\"; };\n\t\t638053560D3E95A10003DB13 /* currentTrackLocation.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.scpt; name = currentTrackLocation.scpt; path = scripts/currentTrackLocation.scpt; sourceTree = \"<group>\"; };\n\t\t638053570D3E95A10003DB13 /* currentTrackPersistentId.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.scpt; name = currentTrackPersistentId.scpt; path = scripts/currentTrackPersistentId.scpt; sourceTree = \"<group>\"; };\n\t\t638053580D3E95A10003DB13 /* playCountForPersistentId.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.scpt; name = playCountForPersistentId.scpt; path = scripts/playCountForPersistentId.scpt; sourceTree = \"<group>\"; };\n\t\t6392AF620D788A2D00E1B4F6 /* ITunesPlaysDatabase.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = ITunesPlaysDatabase.cpp; sourceTree = \"<group>\"; };\n\t\t6392AF630D788A2D00E1B4F6 /* ITunesPlaysDatabase.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = ITunesPlaysDatabase.h; sourceTree = \"<group>\"; };\n\t\t63B2F45D0E9FBECD0088AF7A /* ITunesTrack.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = ITunesTrack.cpp; sourceTree = \"<group>\"; };\n\t\t63E5E4760D6B51C500774857 /* IPodDetector_mac.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = IPodDetector_mac.cpp; sourceTree = \"<group>\"; };\n\t\t63ED46BF0DD8D51D00F6FBE0 /* currentTrack.scpt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.scpt; name = currentTrack.scpt; path = scripts/currentTrack.scpt; sourceTree = \"<group>\"; };\n\t\tAF289ABC0CDFDCF200C8C0B4 /* _iTunes.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = _iTunes.plist; sourceTree = \"<group>\"; };\n\t\tDC2667A60BD9410900B4ED68 /* AudioScrobbler.bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AudioScrobbler.bundle; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\tFB0C1E660D9919CD004820B9 /* CoreServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreServices.framework; path = /System/Library/Frameworks/CoreServices.framework; sourceTree = \"<absolute>\"; };\n\t\tFB0C20CF0D9922CD004820B9 /* Carbon.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Carbon.framework; path = /System/Library/Frameworks/Carbon.framework; sourceTree = \"<absolute>\"; };\n\t\tFB3EA6B70D5795BE003DC14E /* ITunesPlaysDatabase_mac.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = ITunesPlaysDatabase_mac.cpp; sourceTree = \"<group>\"; };\n\t\tFB3EA6C80D587677003DC14E /* ITunesTrack.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = ITunesTrack.h; sourceTree = \"<group>\"; };\n\t\tFB4ED6F20D6B00CE00F243B8 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = /System/Library/Frameworks/IOKit.framework; sourceTree = \"<absolute>\"; };\n\t\tFB5345DE0D4A060200BD9819 /* main.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = main.h; sourceTree = \"<group>\"; };\n\t\tFB6471A40D806439007006E4 /* IPod.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = IPod.cpp; sourceTree = \"<group>\"; };\n\t\tFB6471A50D80643A007006E4 /* IPod.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = IPod.h; sourceTree = \"<group>\"; };\n\t\tFB6471A60D80643A007006E4 /* IPod_mac.cpp */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = IPod_mac.cpp; sourceTree = \"<group>\"; };\n\t\tFBAF702D0D7496B000A4919B /* IPodDetector.h */ = {isa = PBXFileReference; explicitFileType = sourcecode.cpp.objcpp; fileEncoding = 4; path = IPodDetector.h; sourceTree = \"<group>\"; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\tDC26679E0BD9410900B4ED68 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t4CCE0E96162725220090F29C /* Cocoa.framework in Frameworks */,\n\t\t\t\tDC26679F0BD9410900B4ED68 /* CoreFoundation.framework in Frameworks */,\n\t\t\t\tFB4ED6F30D6B00CE00F243B8 /* IOKit.framework in Frameworks */,\n\t\t\t\tFB0C1E670D9919CD004820B9 /* CoreServices.framework in Frameworks */,\n\t\t\t\tFB0C20D00D9922CD004820B9 /* Carbon.framework in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t01285C0000CC31B17F000001 /* iTunesVisualAPI */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4C7B8BBD141657F600C2A26C /* iTunesAPI.cpp */,\n\t\t\t\t01285C0200CC31B17F000001 /* iTunesAPI.h */,\n\t\t\t\t01285C0300CC31B17F000001 /* iTunesVisualAPI.h */,\n\t\t\t);\n\t\t\tpath = iTunesVisualAPI;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t089C166AFE841209C02AAC07 /* iTunesPlugIn */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t638053590D3E95AF0003DB13 /* Scripts */,\n\t\t\t\t08FB77AFFE84173DC02AAC07 /* Source */,\n\t\t\t\t089C1671FE841209C02AAC07 /* External Frameworks and Libraries */,\n\t\t\t\t19C28FB6FE9D52B211CA2CBB /* Products */,\n\t\t\t\t638052460D3E53940003DB13 /* ChangeLog.txt */,\n\t\t\t\tAF289ABC0CDFDCF200C8C0B4 /* _iTunes.plist */,\n\t\t\t);\n\t\t\tname = iTunesPlugIn;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t089C1671FE841209C02AAC07 /* External Frameworks and Libraries */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4CCE0E95162725220090F29C /* Cocoa.framework */,\n\t\t\t\tFB0C20CF0D9922CD004820B9 /* Carbon.framework */,\n\t\t\t\tFB0C1E660D9919CD004820B9 /* CoreServices.framework */,\n\t\t\t\tFB4ED6F20D6B00CE00F243B8 /* IOKit.framework */,\n\t\t\t\t0AA1909FFE8422F4C02AAC07 /* CoreFoundation.framework */,\n\t\t\t);\n\t\t\tname = \"External Frameworks and Libraries\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t08FB77AFFE84173DC02AAC07 /* Source */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4C3C565916849BF0002A3DBC /* sqlite3 */,\n\t\t\t\tFB6471A40D806439007006E4 /* IPod.cpp */,\n\t\t\t\tFB6471A60D80643A007006E4 /* IPod_mac.cpp */,\n\t\t\t\tFB6471A50D80643A007006E4 /* IPod.h */,\n\t\t\t\t6392AF620D788A2D00E1B4F6 /* ITunesPlaysDatabase.cpp */,\n\t\t\t\t6392AF630D788A2D00E1B4F6 /* ITunesPlaysDatabase.h */,\n\t\t\t\t63E5E4760D6B51C500774857 /* IPodDetector_mac.cpp */,\n\t\t\t\tFBAF702D0D7496B000A4919B /* IPodDetector.h */,\n\t\t\t\t63233BAD0D7491470009EC65 /* Logger.cpp */,\n\t\t\t\t63233BAE0D7491470009EC65 /* Logger.h */,\n\t\t\t\tFB5345DE0D4A060200BD9819 /* main.h */,\n\t\t\t\t01285C0700CC38597F000001 /* main.cpp */,\n\t\t\t\t633C62960D6CA1DD00B609B9 /* main_mac.cpp */,\n\t\t\t\tFB3EA6B70D5795BE003DC14E /* ITunesPlaysDatabase_mac.cpp */,\n\t\t\t\tFB3EA6C80D587677003DC14E /* ITunesTrack.h */,\n\t\t\t\t63B2F45D0E9FBECD0088AF7A /* ITunesTrack.cpp */,\n\t\t\t\t637A1ED30D4FCA15004FA19F /* Moose.h */,\n\t\t\t\t637452E00D58B02B00429514 /* Moose_mac.cpp */,\n\t\t\t\t01285C0000CC31B17F000001 /* iTunesVisualAPI */,\n\t\t\t);\n\t\t\tname = Source;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t19C28FB6FE9D52B211CA2CBB /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tDC2667A60BD9410900B4ED68 /* AudioScrobbler.bundle */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t4C3C565916849BF0002A3DBC /* sqlite3 */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t4C3C565716849BEB002A3DBC /* sqlite3.h */,\n\t\t\t\t4C3C565616849BEB002A3DBC /* sqlite3.c */,\n\t\t\t);\n\t\t\tname = sqlite3;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t638053590D3E95AF0003DB13 /* Scripts */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t632E70520DD9FEF900A16D88 /* playCountForDatabaseId.scpt */,\n\t\t\t\t63ED46BF0DD8D51D00F6FBE0 /* currentTrack.scpt */,\n\t\t\t\t637A231D0DAA9B1C004590E1 /* uninstall.sh */,\n\t\t\t\t638053560D3E95A10003DB13 /* currentTrackLocation.scpt */,\n\t\t\t\t638053570D3E95A10003DB13 /* currentTrackPersistentId.scpt */,\n\t\t\t\t638053580D3E95A10003DB13 /* playCountForPersistentId.scpt */,\n\t\t\t);\n\t\t\tname = Scripts;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXNativeTarget section */\n\t\tDC2667930BD9410900B4ED68 /* iTunes Scrobbler */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = DC2667A10BD9410900B4ED68 /* Build configuration list for PBXNativeTarget \"iTunes Scrobbler\" */;\n\t\t\tbuildPhases = (\n\t\t\t\tDC2667970BD9410900B4ED68 /* Resources */,\n\t\t\t\tDC26679B0BD9410900B4ED68 /* Sources */,\n\t\t\t\tDC26679E0BD9410900B4ED68 /* Frameworks */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = \"iTunes Scrobbler\";\n\t\t\tproductInstallPath = \"/Users/guillerm/Library/iTunes/iTunes Plug-ins\";\n\t\t\tproductName = iTunesPlugIn;\n\t\t\tproductReference = DC2667A60BD9410900B4ED68 /* AudioScrobbler.bundle */;\n\t\t\tproductType = \"com.apple.product-type.bundle\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t089C1669FE841209C02AAC07 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 0420;\n\t\t\t};\n\t\t\tbuildConfigurationList = AF2F40450BD811FE009D75EB /* Build configuration list for PBXProject \"_iTunes\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.2\";\n\t\t\tdevelopmentRegion = English;\n\t\t\thasScannedForEncodings = 1;\n\t\t\tknownRegions = (\n\t\t\t\tEnglish,\n\t\t\t\tJapanese,\n\t\t\t\tFrench,\n\t\t\t\tGerman,\n\t\t\t);\n\t\t\tmainGroup = 089C166AFE841209C02AAC07 /* iTunesPlugIn */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\tDC2667930BD9410900B4ED68 /* iTunes Scrobbler */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\tDC2667970BD9410900B4ED68 /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t632E70550DD9FF0200A16D88 /* playCountForDatabaseId.scpt in Resources */,\n\t\t\t\t63ED46C20DD8D52900F6FBE0 /* currentTrack.scpt in Resources */,\n\t\t\t\t634E6EF50D3FBA7D00E16E0D /* currentTrackLocation.scpt in Resources */,\n\t\t\t\t634E6EF60D3FBA7D00E16E0D /* currentTrackPersistentId.scpt in Resources */,\n\t\t\t\t634E6EF70D3FBA7D00E16E0D /* playCountForPersistentId.scpt in Resources */,\n\t\t\t\t638052470D3E53940003DB13 /* ChangeLog.txt in Resources */,\n\t\t\t\t637A231E0DAA9B1C004590E1 /* uninstall.sh in Resources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\tDC26679B0BD9410900B4ED68 /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\tDC26679C0BD9410900B4ED68 /* main.cpp in Sources */,\n\t\t\t\tFB3EA6B90D5795BE003DC14E /* ITunesPlaysDatabase_mac.cpp in Sources */,\n\t\t\t\t637452E10D58B02B00429514 /* Moose_mac.cpp in Sources */,\n\t\t\t\t63E5E4770D6B51C500774857 /* IPodDetector_mac.cpp in Sources */,\n\t\t\t\t633C62970D6CA1DD00B609B9 /* main_mac.cpp in Sources */,\n\t\t\t\t63233BAF0D7491470009EC65 /* Logger.cpp in Sources */,\n\t\t\t\t6392AF640D788A2D00E1B4F6 /* ITunesPlaysDatabase.cpp in Sources */,\n\t\t\t\tFB6471A70D80643A007006E4 /* IPod.cpp in Sources */,\n\t\t\t\tFB6471A90D80643A007006E4 /* IPod_mac.cpp in Sources */,\n\t\t\t\t63B2F45E0E9FBECD0088AF7A /* ITunesTrack.cpp in Sources */,\n\t\t\t\t4C7B8BBE141657F600C2A26C /* iTunesAPI.cpp in Sources */,\n\t\t\t\t4C3C565816849BEC002A3DBC /* sqlite3.c in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\tAF2F40460BD811FE009D75EB /* Development */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tCODE_SIGN_IDENTITY = \"Developer ID Application: Last.fm\";\n\t\t\t\tGCC_VERSION = \"\";\n\t\t\t\tHEADER_SEARCH_PATHS = \"\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tPROVISIONING_PROFILE = \"\";\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tUSER_HEADER_SEARCH_PATHS = ../../;\n\t\t\t};\n\t\t\tname = Development;\n\t\t};\n\t\tAF2F40470BD811FE009D75EB /* Deployment */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tCODE_SIGN_IDENTITY = \"Developer ID Application: Last.fm\";\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tGCC_GENERATE_DEBUGGING_SYMBOLS = NO;\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = YES;\n\t\t\t\tGCC_VERSION = \"\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tPROVISIONING_PROFILE = \"\";\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tUSER_HEADER_SEARCH_PATHS = ../../;\n\t\t\t};\n\t\t\tname = Deployment;\n\t\t};\n\t\tAF2F40480BD811FE009D75EB /* Default */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tCODE_SIGN_IDENTITY = \"Developer ID Application: Last.fm\";\n\t\t\t\tGCC_VERSION = \"\";\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tPROVISIONING_PROFILE = \"\";\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tUSER_HEADER_SEARCH_PATHS = ../../;\n\t\t\t};\n\t\t\tname = Default;\n\t\t};\n\t\tDC2667A20BD9410900B4ED68 /* Development */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"\\\"$(SYSTEM_LIBRARY_DIR)/Frameworks/CoreServices.framework/Frameworks\\\"\",\n\t\t\t\t);\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_GENERATE_DEBUGGING_SYMBOLS = NO;\n\t\t\t\tGCC_INPUT_FILETYPE = automatic;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = SQLITE_ENABLE_UNLOCK_NOTIFY;\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = NO;\n\t\t\t\tGENERATE_PKGINFO_FILE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = \"\";\n\t\t\t\tINFOPLIST_FILE = _iTunes.plist;\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t/usr/local/Cellar/sqlite/3.7.14/lib,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tOTHER_CFLAGS = \"\";\n\t\t\t\tOTHER_LDFLAGS = \"-lsqlite3\";\n\t\t\t\tOTHER_REZFLAGS = \"\";\n\t\t\t\tPRODUCT_NAME = AudioScrobbler;\n\t\t\t\tREZ_EXECUTABLE = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tSECTORDER_FLAGS = \"\";\n\t\t\t\tSTRIP_INSTALLED_PRODUCT = NO;\n\t\t\t\tWARNING_CFLAGS = (\n\t\t\t\t\t\"-Wmost\",\n\t\t\t\t\t\"-Wno-four-char-constants\",\n\t\t\t\t\t\"-Wno-unknown-pragmas\",\n\t\t\t\t);\n\t\t\t\tWRAPPER_EXTENSION = bundle;\n\t\t\t\tZERO_LINK = YES;\n\t\t\t};\n\t\t\tname = Development;\n\t\t};\n\t\tDC2667A30BD9410900B4ED68 /* Deployment */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tCOPY_PHASE_STRIP = YES;\n\t\t\t\tDEAD_CODE_STRIPPING = YES;\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"\\\"$(SYSTEM_LIBRARY_DIR)/Frameworks/CoreServices.framework/Frameworks\\\"\",\n\t\t\t\t);\n\t\t\t\tGCC_GENERATE_DEBUGGING_SYMBOLS = NO;\n\t\t\t\tGCC_INPUT_FILETYPE = automatic;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = s;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\tNDEBUG,\n\t\t\t\t\tSQLITE_ENABLE_UNLOCK_NOTIFY,\n\t\t\t\t);\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = NO;\n\t\t\t\tGENERATE_PKGINFO_FILE = YES;\n\t\t\t\tHEADER_SEARCH_PATHS = \"\";\n\t\t\t\tINFOPLIST_FILE = _iTunes.plist;\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t/usr/local/Cellar/sqlite/3.7.14/lib,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tOTHER_CFLAGS = \"\";\n\t\t\t\tOTHER_LDFLAGS = \"-lsqlite3\";\n\t\t\t\tOTHER_REZFLAGS = \"\";\n\t\t\t\tPRODUCT_NAME = AudioScrobbler;\n\t\t\t\tREZ_EXECUTABLE = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tSECTORDER_FLAGS = \"\";\n\t\t\t\tSTRIP_STYLE = all;\n\t\t\t\tWARNING_CFLAGS = (\n\t\t\t\t\t\"-Wmost\",\n\t\t\t\t\t\"-Wno-four-char-constants\",\n\t\t\t\t\t\"-Wno-unknown-pragmas\",\n\t\t\t\t);\n\t\t\t\tWRAPPER_EXTENSION = bundle;\n\t\t\t\tZERO_LINK = NO;\n\t\t\t};\n\t\t\tname = Deployment;\n\t\t};\n\t\tDC2667A40BD9410900B4ED68 /* Default */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\";\n\t\t\t\tFRAMEWORK_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"\\\"$(SYSTEM_LIBRARY_DIR)/Frameworks/CoreServices.framework/Frameworks\\\"\",\n\t\t\t\t);\n\t\t\t\tGCC_GENERATE_DEBUGGING_SYMBOLS = NO;\n\t\t\t\tGCC_INPUT_FILETYPE = automatic;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 3;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = SQLITE_ENABLE_UNLOCK_NOTIFY;\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = NO;\n\t\t\t\tHEADER_SEARCH_PATHS = \"\";\n\t\t\t\tINFOPLIST_FILE = _iTunes.plist;\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t/usr/local/Cellar/sqlite/3.7.14/lib,\n\t\t\t\t);\n\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 10.6;\n\t\t\t\tOTHER_CFLAGS = \"\";\n\t\t\t\tOTHER_LDFLAGS = \"-lsqlite3\";\n\t\t\t\tOTHER_REZFLAGS = \"\";\n\t\t\t\tPRODUCT_NAME = AudioScrobbler;\n\t\t\t\tREZ_EXECUTABLE = YES;\n\t\t\t\tSDKROOT = macosx;\n\t\t\t\tSECTORDER_FLAGS = \"\";\n\t\t\t\tWARNING_CFLAGS = (\n\t\t\t\t\t\"-Wmost\",\n\t\t\t\t\t\"-Wno-four-char-constants\",\n\t\t\t\t\t\"-Wno-unknown-pragmas\",\n\t\t\t\t);\n\t\t\t\tWRAPPER_EXTENSION = bundle;\n\t\t\t};\n\t\t\tname = Default;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\tAF2F40450BD811FE009D75EB /* Build configuration list for PBXProject \"_iTunes\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\tAF2F40460BD811FE009D75EB /* Development */,\n\t\t\t\tAF2F40470BD811FE009D75EB /* Deployment */,\n\t\t\t\tAF2F40480BD811FE009D75EB /* Default */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Default;\n\t\t};\n\t\tDC2667A10BD9410900B4ED68 /* Build configuration list for PBXNativeTarget \"iTunes Scrobbler\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\tDC2667A20BD9410900B4ED68 /* Development */,\n\t\t\t\tDC2667A30BD9410900B4ED68 /* Deployment */,\n\t\t\t\tDC2667A40BD9410900B4ED68 /* Default */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Default;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 089C1669FE841209C02AAC07 /* Project object */;\n}\n"
  },
  {
    "path": "plugins/iTunes/iTunesVisualAPI/iTunesAPI.cpp",
    "content": "//\r\n// File:       iTunesAPI.c\r\n//\r\n// Abstract:   part of iTunes Visual SDK\r\n//\r\n// Version:    2.0\r\n//\r\n// Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ( \"Apple\" )\r\n//             in consideration of your agreement to the following terms, and your use,\r\n//             installation, modification or redistribution of this Apple software\r\n//             constitutes acceptance of these terms.  If you do not agree with these\r\n//             terms, please do not use, install, modify or redistribute this Apple\r\n//             software.\r\n//\r\n//             In consideration of your agreement to abide by the following terms, and\r\n//             subject to these terms, Apple grants you a personal, non - exclusive\r\n//             license, under Apple's copyrights in this original Apple software ( the\r\n//             \"Apple Software\" ), to use, reproduce, modify and redistribute the Apple\r\n//             Software, with or without modifications, in source and / or binary forms;\r\n//             provided that if you redistribute the Apple Software in its entirety and\r\n//             without modifications, you must retain this notice and the following text\r\n//             and disclaimers in all such redistributions of the Apple Software. Neither\r\n//             the name, trademarks, service marks or logos of Apple Inc. may be used to\r\n//             endorse or promote products derived from the Apple Software without specific\r\n//             prior written permission from Apple.  Except as expressly stated in this\r\n//             notice, no other rights or licenses, express or implied, are granted by\r\n//             Apple herein, including but not limited to any patent rights that may be\r\n//             infringed by your derivative works or by other works in which the Apple\r\n//             Software may be incorporated.\r\n//\r\n//             The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO\r\n//             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED\r\n//             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A\r\n//             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION\r\n//             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.\r\n//\r\n//             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR\r\n//             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n//             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n//             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION\r\n//             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER\r\n//             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR\r\n//             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n//\r\n// Copyright © 2000-2011 Apple Inc. All Rights Reserved.\r\n//\r\n#include \"iTunesAPI.h\"\r\n#include \"iTunesVisualAPI.h\"\r\n\r\n#include <string.h>\r\n\r\n// SetNumVersion\r\n//\r\nvoid SetNumVersion(NumVersion *numVersion, UInt8 majorRev, UInt8 minorAndBugRev, UInt8 stage, UInt8 nonRelRev)\r\n{\r\n\tnumVersion->majorRev\t\t= majorRev;\r\n\tnumVersion->minorAndBugRev\t= minorAndBugRev;\r\n\tnumVersion->stage\t\t\t= stage;\r\n\tnumVersion->nonRelRev\t\t= nonRelRev;\r\n}\r\n\r\n\r\n// ITCallApplicationInternal\r\n//\r\nstatic OSStatus ITCallApplicationInternal(void *appCookie, ITAppProcPtr handler, OSType message, UInt32 messageMajorVersion, UInt32 messageMinorVersion, PlayerMessageInfo *messageInfo)\r\n{\r\n\tPlayerMessageInfo\tlocalMessageInfo;\r\n\t\r\n\tif (messageInfo == nil)\r\n\t{\r\n\t\tmemset(&localMessageInfo, 0, sizeof(localMessageInfo));\r\n\t\t\r\n\t\tmessageInfo = &localMessageInfo;\r\n\t}\r\n\t\r\n\tmessageInfo->messageMajorVersion = messageMajorVersion;\r\n\tmessageInfo->messageMinorVersion = messageMinorVersion;\r\n\tmessageInfo->messageInfoSize\t = sizeof(PlayerMessageInfo);\r\n\t\r\n\treturn handler(appCookie, message, messageInfo);\r\n}\r\n\r\n// ITCallApplication\r\n//\r\nOSStatus ITCallApplication(void *appCookie, ITAppProcPtr handler, OSType message, PlayerMessageInfo *messageInfo)\r\n{\r\n\treturn ITCallApplicationInternal(appCookie, handler, message, kITPluginMajorMessageVersion, kITPluginMinorMessageVersion, messageInfo);\r\n}\r\n\r\n\r\n// PlayerSetFullScreen\r\n//\r\nOSStatus PlayerSetFullScreen(void *appCookie, ITAppProcPtr appProc, Boolean fullScreen)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.setFullScreenMessage.fullScreen = fullScreen;\r\n\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerSetFullScreenMessage, &messageInfo);\r\n}\r\n\r\n\r\n\r\n\r\n// PlayerRequestCurrentTrackCoverArt\r\n//\r\nOSStatus PlayerRequestCurrentTrackCoverArt(void *appCookie, ITAppProcPtr appProc)\r\n{\r\n\tOSStatus\t\t\tstatus;\r\n\t\r\n\tstatus = ITCallApplication(appCookie, appProc, kPlayerRequestCurrentTrackCoverArtMessage, nil);\r\n\r\n\treturn status;\r\n}\r\n\r\n\r\n// PlayerGetPluginData\r\n//\r\nOSStatus PlayerGetPluginData(void *appCookie, ITAppProcPtr appProc, void *dataPtr, UInt32 dataBufferSize, UInt32 *dataSize)\r\n{\r\n\tOSStatus\t\t\tstatus;\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.getPluginDataMessage.dataPtr\t\t\t= dataPtr;\r\n\tmessageInfo.u.getPluginDataMessage.dataBufferSize\t= dataBufferSize;\r\n\t\r\n\tstatus = ITCallApplication(appCookie, appProc, kPlayerGetPluginDataMessage, &messageInfo);\r\n\t\r\n\tif (dataSize != nil)\r\n\t\t*dataSize = messageInfo.u.getPluginDataMessage.dataSize;\r\n\t\r\n\treturn status;\r\n}\r\n\r\n\r\n// PlayerSetPluginData\r\n//\r\nOSStatus PlayerSetPluginData(void *appCookie, ITAppProcPtr appProc, void *dataPtr, UInt32 dataSize)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.setPluginDataMessage.dataPtr\t= dataPtr;\r\n\tmessageInfo.u.setPluginDataMessage.dataSize\t= dataSize;\r\n\t\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerSetPluginDataMessage, &messageInfo);\r\n}\r\n\r\n\r\n// PlayerGetPluginNamedData\r\n//\r\nOSStatus PlayerGetPluginNamedData(void *appCookie, ITAppProcPtr appProc, ConstStringPtr dataName, void *dataPtr, UInt32 dataBufferSize, UInt32 *dataSize)\r\n{\r\n\tOSStatus\t\t\tstatus;\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.getPluginNamedDataMessage.dataName\t\t= dataName;\r\n\tmessageInfo.u.getPluginNamedDataMessage.dataPtr\t\t\t= dataPtr;\r\n\tmessageInfo.u.getPluginNamedDataMessage.dataBufferSize\t= dataBufferSize;\r\n\t\r\n\tstatus = ITCallApplication(appCookie, appProc, kPlayerGetPluginNamedDataMessage, &messageInfo);\r\n\t\r\n\tif (dataSize != nil)\r\n\t\t*dataSize = messageInfo.u.getPluginNamedDataMessage.dataSize;\r\n\t\r\n\treturn status;\r\n}\r\n\r\n\r\n// PlayerSetPluginNamedData\r\n//\r\nOSStatus PlayerSetPluginNamedData(void *appCookie, ITAppProcPtr appProc, ConstStringPtr dataName, void *dataPtr, UInt32 dataSize)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.setPluginNamedDataMessage.dataName\t= dataName;\r\n\tmessageInfo.u.setPluginNamedDataMessage.dataPtr\t\t= dataPtr;\r\n\tmessageInfo.u.setPluginNamedDataMessage.dataSize\t= dataSize;\r\n\t\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerSetPluginNamedDataMessage, &messageInfo);\r\n}\r\n\r\n\r\n// PlayerIdle\r\n//\r\nOSStatus PlayerIdle(void *appCookie, ITAppProcPtr appProc)\r\n{\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerIdleMessage, nil);\r\n}\r\n\r\n\r\n// PlayerShowAbout\r\n//\r\nvoid PlayerShowAbout(void *appCookie, ITAppProcPtr appProc)\r\n{\r\n\tITCallApplication(appCookie, appProc, kPlayerShowAboutMessage, nil);\r\n}\r\n\r\n\r\n// PlayerOpenURL\r\n//\r\nvoid PlayerOpenURL(void *appCookie, ITAppProcPtr appProc, SInt8 *string, UInt32 length)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.openURLMessage.url\t= string;\r\n\tmessageInfo.u.openURLMessage.length\t= length;\r\n\r\n\tITCallApplication(appCookie, appProc, kPlayerOpenURLMessage, &messageInfo);\r\n}\r\n\r\n// PlayerUnregisterPlugin\r\n//\r\nOSStatus PlayerUnregisterPlugin(void *appCookie, ITAppProcPtr appProc, PlayerMessageInfo *messageInfo)\r\n{\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerUnregisterPluginMessage, messageInfo);\r\n}\r\n\r\n\r\n// PlayerRegisterVisualPlugin\r\n//\r\nOSStatus PlayerRegisterVisualPlugin(void *appCookie, ITAppProcPtr appProc, PlayerMessageInfo *messageInfo)\r\n{\r\n\treturn ITCallApplicationInternal(appCookie, appProc, kPlayerRegisterVisualPluginMessage, kITVisualPluginMajorMessageVersion, kITVisualPluginMinorMessageVersion, messageInfo);\r\n}\r\n\r\n// PlayerGetPluginITFileSpec\r\n//\r\nOSStatus PlayerGetPluginITFileSpec(void *appCookie, ITAppProcPtr appProc, ITFileSpec *pluginFileSpec)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.getPluginITFileSpecMessage.fileSpec = pluginFileSpec;\r\n\t\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerGetPluginITFileSpecMessage, &messageInfo);\r\n}\r\n\r\n// PlayerGetFileTrackInfo\r\n//\r\nOSStatus PlayerGetFileTrackInfo(void *appCookie, ITAppProcPtr appProc, const ITFileSpec *fileSpec, ITTrackInfo *trackInfo)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.getFileTrackInfoMessage.fileSpec \t= fileSpec;\r\n\tmessageInfo.u.getFileTrackInfoMessage.trackInfo = trackInfo;\r\n\t\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerGetFileTrackInfoMessage, &messageInfo);\r\n}\r\n\r\n// PlayerSetFileTrackInfo\r\n//\r\nOSStatus PlayerSetFileTrackInfo(void *appCookie, ITAppProcPtr appProc, const ITFileSpec *fileSpec, const ITTrackInfo *trackInfo)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tmessageInfo.u.setFileTrackInfoMessage.fileSpec \t= fileSpec;\r\n\tmessageInfo.u.setFileTrackInfoMessage.trackInfo = trackInfo;\r\n\t\r\n\treturn ITCallApplication(appCookie, appProc, kPlayerSetFileTrackInfoMessage, &messageInfo);\r\n}\r\n\r\n// PlayerGetITTrackInfoSize\r\n//\r\nOSStatus PlayerGetITTrackInfoSize(void *appCookie, ITAppProcPtr appProc, UInt32 appPluginMajorVersion, UInt32 appPluginMinorVersion, UInt32 *itTrackInfoSize)\r\n{\r\n\tPlayerMessageInfo\tmessageInfo;\r\n\tOSStatus\t\t\tstatus;\r\n\t\r\n\t/*\r\n\t\tNote: appPluginMajorVersion and appPluginMinorVersion are the versions given to the plugin by iTunes in the plugin's init message.\r\n\t\t\t  These versions are *not* the version of the API used when the plugin was compiled.\r\n\t*/\r\n\t\r\n\t*itTrackInfoSize = 0;\r\n\t\r\n\tmemset(&messageInfo, 0, sizeof(messageInfo));\r\n\t\r\n\tstatus = ITCallApplication(appCookie, appProc, kPlayerGetITTrackInfoSizeMessage, &messageInfo);\r\n\tif( status == noErr )\r\n\t{\r\n\t\t*itTrackInfoSize = messageInfo.u.getITTrackInfoSizeMessage.itTrackInfoSize;\r\n\t}\r\n\telse if( appPluginMajorVersion == 10 && appPluginMinorVersion == 2 )\r\n\t{\r\n\t\t// iTunes 2.0.x\r\n \t\t\r\n\t\t*itTrackInfoSize = ((UInt32)(uintptr_t) &((ITTrackInfo *) 0)->composer);\r\n\t\t\r\n\t\tstatus = noErr;\r\n\t}\r\n\telse if( appPluginMajorVersion == 10 && appPluginMinorVersion == 3 )\r\n\t{\r\n\t\t// iTunes 3.0.x\r\n\t\t\r\n\t\t*itTrackInfoSize = ((UInt32)(uintptr_t) &((ITTrackInfo *) 0)->beatsPerMinute);\r\n\t\t\r\n\t\tstatus = noErr;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// iTunes 4.0 and later implement the kPlayerGetITTrackInfoSizeMessage message. If you got here\r\n\t\t// then the appPluginMajorVersion or appPluginMinorVersion are incorrect.\r\n\t\t\r\n\t\tstatus = paramErr;\r\n\t}\r\n\t\r\n\tif( status == noErr && (*itTrackInfoSize) > sizeof(ITTrackInfo) )\r\n\t{\r\n\t\t// iTunes is using a larger ITTrackInfo than the one when this plugin was compiled. Pin *itTrackInfoSize to the plugin's known size\r\n\t\t\r\n\t\t*itTrackInfoSize = sizeof(ITTrackInfo);\r\n\t}\r\n\t\r\n\treturn status;\r\n}\r\n"
  },
  {
    "path": "plugins/iTunes/iTunesVisualAPI/iTunesAPI.h",
    "content": "//\r\n// File:       iTunesAPI.h\r\n//\r\n// Abstract:   part of iTunes Visual SDK\r\n//\r\n// Version:    2.0\r\n//\r\n// Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ( \"Apple\" )\r\n//             in consideration of your agreement to the following terms, and your use,\r\n//             installation, modification or redistribution of this Apple software\r\n//             constitutes acceptance of these terms.  If you do not agree with these\r\n//             terms, please do not use, install, modify or redistribute this Apple\r\n//             software.\r\n//\r\n//             In consideration of your agreement to abide by the following terms, and\r\n//             subject to these terms, Apple grants you a personal, non - exclusive\r\n//             license, under Apple's copyrights in this original Apple software ( the\r\n//             \"Apple Software\" ), to use, reproduce, modify and redistribute the Apple\r\n//             Software, with or without modifications, in source and / or binary forms;\r\n//             provided that if you redistribute the Apple Software in its entirety and\r\n//             without modifications, you must retain this notice and the following text\r\n//             and disclaimers in all such redistributions of the Apple Software. Neither\r\n//             the name, trademarks, service marks or logos of Apple Inc. may be used to\r\n//             endorse or promote products derived from the Apple Software without specific\r\n//             prior written permission from Apple.  Except as expressly stated in this\r\n//             notice, no other rights or licenses, express or implied, are granted by\r\n//             Apple herein, including but not limited to any patent rights that may be\r\n//             infringed by your derivative works or by other works in which the Apple\r\n//             Software may be incorporated.\r\n//\r\n//             The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO\r\n//             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED\r\n//             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A\r\n//             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION\r\n//             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.\r\n//\r\n//             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR\r\n//             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n//             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n//             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION\r\n//             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER\r\n//             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR\r\n//             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n//\r\n// Copyright © 2000-2011 Apple Inc. All Rights Reserved.\r\n//\r\n#ifndef ITUNESAPI_H_\r\n#define ITUNESAPI_H_\r\n\r\n#if PRAGMA_ONCE\r\n#pragma once\r\n#endif\r\n\r\n\r\n#if defined(_MSC_VER)\r\n\t#define TARGET_OS_MAC\t\t0\r\n\t#define TARGET_OS_WIN32\t\t1\r\n#else\r\n\t#define TARGET_OS_MAC\t\t1\r\n\t#define TARGET_OS_WIN32\t\t0\r\n#endif\r\n\r\n#if TARGET_OS_MAC\r\n\t#include <Carbon/Carbon.h>\r\n\t#include <CoreAudio/CoreAudioTypes.h>\r\n\t#include <CoreFoundation/CoreFoundation.h>\r\n\t#include <CoreServices/CoreServices.h>\r\n#endif\r\n#if TARGET_OS_WIN32\r\n\t#include <windows.h>\r\n#endif\r\n\t\r\n#if !defined(__CONDITIONALMACROS__)\r\ntypedef unsigned long\tUInt32;\r\ntypedef signed long\t\tSInt32;\r\ntypedef unsigned short\tUInt16;\r\ntypedef signed short\tSInt16;\r\ntypedef\tunsigned char\tUInt8;\r\ntypedef signed char\t\tSInt8;\r\ntypedef UInt32\t\t\tOptionBits;\r\n\r\ntypedef UInt8\t\t\tStr255[256];\r\ntypedef UInt8\t\t\tStr63[64];\r\ntypedef UInt8 *\t\t\tStringPtr;\r\ntypedef const UInt8 *\tConstStringPtr;\r\ntypedef UInt32\t\t\tOSType;\r\n\r\ntypedef SInt32\t\t\tOSStatus;\r\n\r\ntypedef UInt16\t\t\tUniChar;\r\n\r\ntypedef double\t\t\tFloat64;\r\n\r\n\r\n#if TARGET_OS_WIN32\r\ntypedef unsigned __int64\tUInt64;\r\n#else\r\ntypedef unsigned long long\tUInt64;\r\n#endif\r\n\r\ntypedef void **\t\t\tHandle;\r\n\r\nstruct NumVersion {\r\n\tUInt8\t\t\tmajorRev;\r\n\tUInt8\t\t\tminorAndBugRev;\r\n\tUInt8\t\t\tstage;\r\n\tUInt8\t\t\tnonRelRev;\r\n};\r\ntypedef struct NumVersion NumVersion;\r\n\r\nstruct Point {\r\n    short\t\t\tv;\r\n    short\t\t\th;\r\n};\r\ntypedef struct Point Point;\r\n\r\nstruct Rect {\r\n\tshort\t\t\ttop;\r\n\tshort\t\t\tleft;\r\n\tshort\t\t\tbottom;\r\n\tshort\t\t\tright;\r\n};\r\ntypedef struct Rect Rect;\r\n\r\ntypedef UInt8\t\t\tBoolean;\r\n\r\ntypedef UInt32\t\t\tUnsignedFixed;\r\n\r\ntypedef void *\t\t\tLogicalAddress;\r\n\r\n#define\tfalse\t0\r\n#define\ttrue\t1\r\n#define\tnil\t\tNULL\r\n\r\nenum {\r\n\tnoErr\t\t\t= 0,\r\n\tunimpErr\t\t= -4,\r\n\treadErr\t\t\t= -19,\r\n\twritErr\t\t\t= -20,\r\n\topenErr\t\t\t= -23,\r\n\tclosErr\t\t\t= -24,\r\n\tdirFulErr\t\t= -33,\r\n\tdskFulErr\t\t= -34,\r\n\tnsvErr\t\t\t= -35,\r\n\tioErr\t\t\t= -36,\r\n\tbdNamErr\t\t= -37,\r\n\tfnOpnErr\t\t= -38,\r\n\teofErr\t\t\t= -39,\r\n\tposErr\t\t\t= -40,\r\n\ttmfoErr\t\t\t= -42,\r\n\tfnfErr\t\t\t= -43,\r\n\twPrErr\t\t\t= -44,\r\n\tfLckdErr\t\t= -45,\r\n\tvLckdErr\t\t= -46,\r\n\tfBsyErr\t\t\t= -47,\r\n\tdupFNErr\t\t= -48,\r\n\topWrErr\t\t\t= -49,\r\n\tparamErr\t\t= -50,\r\n\tpermErr\t\t\t= -54,\r\n\tnsDrvErr\t\t= -56,\r\n\twrPermErr\t\t= -61,\r\n\tmemFullErr\t\t= -108,\r\n\tdirNFErr\t\t= -120,\r\n\tbadMovErr\t\t= -122\r\n};\r\n\r\nenum {\r\n\tdevelopStage\t= 0x20,\r\n\talphaStage\t\t= 0x40,\r\n\tbetaStage\t\t= 0x60,\r\n\tfinalStage\t\t= 0x80\r\n};\r\n\r\nstruct SoundComponentData {\r\n\tlong\t\t\tflags;\r\n\tOSType\t\t\tformat;\r\n\tshort\t\t\tnumChannels;\r\n\tshort\t\t\tsampleSize;\r\n\tUnsignedFixed\tsampleRate;\r\n\tlong\t\t\tsampleCount;\r\n\tUInt8 *\t\t\tbuffer;\r\n\tlong\t\t\treserved;\r\n};\r\ntypedef struct SoundComponentData SoundComponentData;\r\n\r\nstruct AudioStreamBasicDescription\r\n{\r\n    Float64 mSampleRate;\r\n    UInt32  mFormatID;\r\n    UInt32  mFormatFlags;\r\n    UInt32  mBytesPerPacket;\r\n    UInt32  mFramesPerPacket;\r\n    UInt32  mBytesPerFrame;\r\n    UInt32  mChannelsPerFrame;\r\n    UInt32  mBitsPerChannel;\r\n    UInt32  mReserved;\r\n};\r\ntypedef struct AudioStreamBasicDescription AudioStreamBasicDescription;\r\n\r\n#endif\r\n\r\n#if TARGET_OS_WIN32\r\n#define VISUAL_PLATFORM_VIEW\t\tHWND\r\n#define\tVISUAL_PLATFORM_DATA\t\tLPCVOID\r\n#else\r\n#ifdef __OBJC__\r\n\t@class NSView;\r\n#else\r\n\tstruct NSView;\r\n#endif\r\n#define VISUAL_PLATFORM_VIEW\t\tNSView*\r\n#define\tVISUAL_PLATFORM_DATA\t\tCFDataRef\r\n#endif\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n#if PRAGMA_STRUCT_ALIGN\r\n    #pragma options align=power\r\n#elif PRAGMA_STRUCT_PACKPUSH\r\n    #pragma pack(push, 4)\r\n#elif PRAGMA_STRUCT_PACK\r\n    #pragma pack(4)\r\n#endif\r\n\r\n\r\nenum {\r\n\tkITPluginMajorMessageVersion = 10,\r\n\tkITPluginMinorMessageVersion = 9\r\n};\r\n\r\nenum {\r\n\tkTrackSupportsID3Tags\t\t\t= (1u << 0),\r\n\tkTrackHasVariableBitRate\t\t= (1u << 1),\r\n\tkTrackHasVideo\t\t\t\t\t= (1u << 6)\t\t\t/* Track has video track which can be played in iTunes */\r\n};\r\ntypedef OptionBits\tITTrackAttributes;\r\n\r\nenum {\r\n\t/*\r\n\t\tThese mask values are specified in ITTrackInfo.validFields\r\n\t\tto indicate which fields contain valid data\r\n\t*/\r\n\t\r\n\tkITTIFieldInvalid\t\t\t\t= 0,\r\n\tkITTINameFieldMask\t\t\t\t= (1u << 0),\r\n\tkITTIFileNameFieldMask\t\t\t= (1u << 1),\r\n\tkITTIArtistFieldMask\t\t\t= (1u << 2),\r\n\tkITTIAlbumFieldMask\t\t\t\t= (1u << 3),\r\n\tkITTIGenreFieldMask\t\t\t\t= (1u << 4),\r\n\tkITTIKindFieldMask\t\t\t\t= (1u << 5),\r\n\tkITTITrackNumberFieldsMask\t\t= (1u << 6),\r\n\tkITTIYearFieldMask\t\t\t\t= (1u << 7),\r\n\tkITTISoundVolumeFieldMask\t\t= (1u << 8),\r\n\tkITTIEQPresetFieldMask\t\t\t= (1u << 9),\r\n\tkITTICommentsFieldMask\t\t\t= (1u << 10),\r\n\tkITTITotalTimeFieldMask\t\t\t= (1u << 11),\t\t\t\r\n\tkITTIStartTimeFieldMask\t\t\t= (1u << 12),\r\n\tkITTIStopTimeFieldMask\t\t\t= (1u << 13),\r\n\tkITTISizeFieldMask\t\t\t\t= (1u << 14),\r\n\tkITTIBitRateFieldMask\t\t\t= (1u << 15),\r\n\tkITTISampleRateFieldMask\t\t= (1u << 16),\r\n\tkITTIAttributesFieldMask\t\t= (1u << 17),\r\n\tkITTIFileTypeFieldMask\t\t\t= (1u << 18),\r\n\tkITTIDateFieldMask\t\t\t\t= (1u << 19),\r\n//\tkITTIFileCreatorFieldMask\t\t= (1u << 20),\t/* Removed in iTunes 9.0.2 */\r\n\tkITTIComposerFieldMask\t\t\t= (1u << 21),\t/* Added in iTunes 3.0 */\r\n\tkITTICompilationFieldMask\t\t= (1u << 22),\t/* Added in iTunes 3.0 */\r\n\tkITTIDiscNumberFieldsMask\t\t= (1u << 23),\t/* Added in iTunes 3.0 */\r\n\tkITTITrackRatingFieldMask\t\t= (1u << 24),\t/* Added in iTunes 3.0 - used to be called kITTIUserRatingFieldMask */\r\n\tkITTIPlayCountFieldMask \t\t= (1u << 25),\t/* Added in iTunes 3.0 */\r\n\tkITTILastPlayDateFieldMask\t\t= (1u << 26),\t/* Added in iTunes 3.0 */\r\n\tkITTIBeatsPerMinuteFieldMask\t= (1u << 27),\t/* Added in iTunes 4.0 */\r\n\tkITTIGroupingFieldMask\t\t\t= (1u << 28),\t/* Added in iTunes 4.2 */\r\n\tkITTIGaplessAlbumFieldMask\t\t= (1u << 29),\t/* Added in iTunes 7.0 */\r\n\tkITTIAlbumArtistFieldMask\t\t= (1u << 30)\t/* Added in iTunes 7.0 */\r\n};\r\ntypedef OptionBits\tITTIFieldMask;\r\n\r\n#define kLastKnownITTIField\t\t\t\tkITTIAlbumArtistFieldMask\r\n#define\tkAllKnownITTIFieldsMask\t\t\t((((UInt32) kLastKnownITTIField) << 1) - 1)\r\n\r\nenum\r\n{\r\n\tkITTIUserModifiableFieldsMask \t= kITTINameFieldMask | kITTIArtistFieldMask | kITTIAlbumFieldMask | kITTIGroupingFieldMask | kITTIGenreFieldMask |\r\n\t\t\t\t\t\t\t\t\t\tkITTITrackNumberFieldsMask | kITTIYearFieldMask | kITTISoundVolumeFieldMask | kITTIEQPresetFieldMask |\r\n\t\t\t\t\t\t\t\t\t\tkITTICommentsFieldMask | kITTIStartTimeFieldMask | kITTIStopTimeFieldMask | kITTIComposerFieldMask |\r\n\t\t\t\t\t\t\t\t\t\tkITTICompilationFieldMask | kITTIDiscNumberFieldsMask | kITTITrackRatingFieldMask | kITTIBeatsPerMinuteFieldMask |\r\n\t\t\t\t\t\t\t\t\t\tkITTIGaplessAlbumFieldMask | kITTIAlbumArtistFieldMask\r\n};\r\n\r\ntypedef UniChar \t\tITUniStr255[256];\t\t\t\t/* Similar to Str255. First element is length of string in characters. */\r\ntypedef UniChar *\t\tITUniStringPtr;\r\ntypedef const UniChar *\tConstITUniStringPtr;\r\n\r\n#if TARGET_OS_MAC\r\n\ttypedef FSRef\tITFileSpec;\r\n#endif\r\n\r\n#if TARGET_OS_WIN32\r\n\t#define\tkITFileSpecMaxPathLength\t(MAX_PATH - 1)\r\n\r\n\ttypedef struct ITFileSpec\r\n\t{\r\n\t\tUInt16\tlength;\t\t// Length in characters\r\n\t\tUniChar\tfullPath[kITFileSpecMaxPathLength];\r\n\t} ITFileSpec;\r\n#endif\r\n\r\nstruct ITTrackInfo {\r\n\tITTIFieldMask\t\tvalidFields;\r\n\tUInt32\t\t\t\trecordLength;\t\t\t\t\t/* Size of this structure in bytes */\r\n\t\r\n\tITUniStr255\t\t\tname;\t\r\n\tITUniStr255\t\t\tfileName;\r\n\tITUniStr255\t\t\tartist;\r\n\tITUniStr255\t\t\talbum;\r\n\tITUniStr255\t\t\tgenre;\r\n\tITUniStr255\t\t\tkind;\r\n\tITUniStr255\t\t\teqPresetName;\r\n\tITUniStr255\t\t\tcomments;\r\n\t\r\n\tUInt32\t\t\t\ttrackNumber;\r\n\tUInt32\t\t\t\tnumTracks;\r\n\t\t\r\n\tUInt16\t\t\t\tyear;\r\n\tSInt16\t\t\t\tsoundVolumeAdjustment;\t\t\t/* Valid range is -255 to +255 */\r\n\t\t\r\n\tUInt32\t\t\t\ttotalTimeInMS;\r\n\tUInt32\t\t\t\tstartTimeInMS;\r\n\tUInt32\t\t\t\tstopTimeInMS;\r\n\r\n\tUInt32\t\t\t\tdate;\r\n\tUInt32\t\t\t\toldSizeInBytes;\t\t\t\t\t/* Deprecated in iTunes 7.1 */\r\n\r\n\tUInt32\t\t\t\tbitRate;\r\n\tUInt32\t\t\t\toldSampleRateFixed;\t\t\t\t/* Deprecated in iTunes 5.0 */\r\n\r\n\tOSType\t\t\t\tfileType;\r\n\tOSType\t\t\t\tobsoleteFileCreator;\t\t\t/* Removed in iTunes 9.0.2 */\r\n\t\r\n\tITTrackAttributes\tattributes;\r\n\tITTrackAttributes\tvalidAttributes;\t\t\t\t/* Mask indicating which attributes are applicable */\r\n\r\n\tITUniStr255\t\t\tcomposer;\t\t\t\t\t\t/* Added in iTunes 3.0 */\r\n\t\r\n\tBoolean\t\t\t\tisCompilationTrack;\t\t\t\t/* Added in iTunes 3.0 */\r\n\tBoolean\t\t\t\tpartOfGaplessAlbum;\t\t\t\t/* Added in iTunes 7.0 (was reserved) */\r\n\t\r\n\tUInt16\t\t\t\ttrackRating;\t\t\t\t\t\t/* Added in iTunes 3.0. 0 = unrated, valid values are 20, 40, 60, 80 and 100. Used to be called userRating */\r\n\r\n\tUInt16\t\t\t\tdiscNumber;\t\t\t\t\t\t/* Added in iTunes 3.0 */\r\n\tUInt16\t\t\t\tnumDiscs;\t\t\t\t\t\t/* Added in iTunes 3.0 */\r\n\t\r\n\tUInt32\t\t\t\tplayCount;\t\t\t\t\t\t/* Added in iTunes 3.0 */\r\n\tUInt32\t\t\t\tlastPlayDate;\t\t\t\t\t/* Added in iTunes 3.0 */\r\n\t\r\n\tUInt16\t\t\t\tbeatsPerMinute;\t\t\t\t\t/* Added in iTunes 4.0 */\r\n\tUInt16\t\t\t\treserved;\t\t\t\t\t\t/* Reserved. Must be zero. */\t\t\r\n\r\n\tITUniStr255\t\t\tgrouping;\t\t\t\t\t\t/* Added in iTunes 4.0 */\r\n\t\r\n\tfloat\t\t\t\tsampleRateFloat;\t\t\t\t/* Added in iTunes 5.0 */\r\n\r\n\tITUniStr255\t\t\talbumArtist;\t\t\t\t\t/* Added in iTunes 7.0 */\r\n\t\r\n\tUInt64\t\t\t\tsizeInBytes;\t\t\t\t\t/* Added in iTunes 7.1 */\r\n};\r\ntypedef struct ITTrackInfo ITTrackInfo;\r\n\r\nenum\r\n{\r\n\tkStreamInfoOption_OverrideAll\t\t= 0x00000001\r\n};\r\n\r\nstruct ITStreamInfo {\r\n\tSInt32\t\t\t\tversion;\r\n\tITUniStr255\t\t\tstreamTitle;\r\n\tITUniStr255\t\t\tstreamURL;\r\n\tITUniStr255\t\t\tstreamMessage;\r\n\t\r\n\tOptionBits\t\t\toptions;\t\t\t// added in iTunes 10.3 - add at the end of struct to maintain compatibility\r\n\tITUniStr255\t\t\tstreamName;\t\t\t// added in iTunes 10.3 - add at the end of struct to maintain compatibility\r\n};\r\ntypedef struct ITStreamInfo ITStreamInfo;\r\n\r\nenum {\r\n\t/* messages sent to plugin main */\r\n\t\r\n\tkPluginInitMessage\t\t\t\t\t= 'init',\r\n\tkPluginCleanupMessage\t\t\t\t= 'clr ',\r\n\tkPluginPrepareToQuitMessage\t\t\t= 'prqt',\r\n\t\r\n\tkPluginIdleMessage\t\t\t\t\t= 'idle'\r\n};\r\n\r\n\r\nenum {\r\n\t/* PluginInitMessage.options */\r\n\t\r\n\tkPluginWantsIdleMessages\t\t\t= (1u << 1),\t/* Send idle messages to plugin main */\r\n\tkPluginWantsToBeLeftOpen\t\t\t= (1u << 2),\t/* Don't close this plugin just because it didn't register anyone */\r\n\tkPluginWantsDisplayNotification\t\t= (1u << 5)\t\t/* The plugin wants to know when the display depth/size changes */\r\n};\r\n\r\n\r\nenum {\r\n\t/* iTunes API messages */\r\n\r\n\tkPlayerRegisterVisualPluginMessage\t= 'regv',\t/* Register a visual plugin */\r\n\t\r\n\t/* Available for all plugins */\r\n\r\n\tkPlayerUnregisterPluginMessage\t\t= 'unrg',\t/* Unregister the plugin this comes from */\r\n\tkPlayerIdleMessage\t\t\t\t\t= 'idle',\t/* Give iTunes some time */\r\n\t\r\n\tkPlayerShowAboutMessage\t\t\t\t= 'abou',\t/* Show the about box. */\r\n\tkPlayerOpenURLMessage\t\t\t\t= 'url ',\t/* Open a URL */\r\n\r\n\tkPlayerSetPluginDataMessage\t\t\t= 'sprf',\t/* Set plugin preferences */\r\n\tkPlayerGetPluginDataMessage\t\t\t= 'gprf',\t/* Get plugin preferences */\r\n\t\r\n\tkPlayerSetPluginNamedDataMessage\t= 'snpr',\t/* Set plugin named preferenes */\r\n\tkPlayerGetPluginNamedDataMessage\t= 'gnpr',\t/* Get plugin named preferenes */\r\n\t\r\n\tkPlayerGetFileTrackInfoMessage\t\t= 'gfti',\t/* Query iTunes for information about a file */ \r\n\tkPlayerSetFileTrackInfoMessage\t\t= 'sfti',\t/* Ask iTunes to set information about a file */ \r\n\t\r\n\tkPlayerGetITTrackInfoSizeMessage\t= 'itsz',\t/* Query iTunes for the sizeof(ITTrackInfo). This allows newer plugins to correctly workd with older versions of iTunes. */\r\n\r\n\tkPlayerHandleMacOSEventMessage\t\t= 'evnt',\t/* Tell player to handle unhandled event */\r\n\r\n\tkPlayerGetPluginITFileSpecMessage\t= 'itfs',\t/* Get the location of the plugin executable (iTunes 4.1 or later) */\r\n\r\n\tkPluginDisplayChangedMessage\t\t= 'disp'\t/* Something about some display has changed */\r\n};\r\n\r\nstruct PlayerMessageInfo;\r\n\r\ntypedef OSStatus (*ITAppProcPtr)(void *appCookie, OSType message, struct PlayerMessageInfo *messageInfo);\r\n\r\n\r\n/*\r\n\tPlugin main Messages\r\n*/\r\n\r\nstruct PluginInitMessage {\r\n\tUInt32\t\t\t\t\t\t\tmajorVersion;\t\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tminorVersion;\t\t\t/* Input */\r\n\r\n\tvoid *\t\t\t\t\t\t\tappCookie;\t\t\t\t/* Input */\r\n\tITAppProcPtr\t\t\t\t\tappProc;\t\t\t\t/* Input */\r\n\t\r\n\tOptionBits\t\t\t\t\t\toptions;\t\t\t\t/* Output, see above for values */\r\n\tvoid *\t\t\t\t\t\t\trefCon;\t\t\t\t\t/* Output */\r\n};\r\ntypedef struct PluginInitMessage PluginInitMessage;\r\n\r\n\r\nstruct PluginMessageInfo {\r\n\tunion {\r\n\t\tPluginInitMessage\t\t\t\t\tinitMessage;\r\n\t} u;\r\n};\r\ntypedef struct PluginMessageInfo PluginMessageInfo;\r\n\r\n/* Plugin main entry point message handler */\r\ntypedef OSStatus (*PluginProcPtr)(OSType message, PluginMessageInfo *messageInfo, void *refCon);\r\n\r\n/* Visual plugin message handler */\r\nstruct VisualPluginMessageInfo;\r\ntypedef OSStatus (*VisualPluginProcPtr)(OSType message, struct VisualPluginMessageInfo *messageInfo, void *refCon);\r\n\r\n/*\r\n\tCallbacks to iTunes\r\n*/\r\nstruct PlayerOpenURLMessage {\r\n\tSInt8 *\t\t\t\t\t\t\turl;\r\n\tUInt32\t\t\t\t\t\t\tlength;\r\n};\r\ntypedef struct PlayerOpenURLMessage PlayerOpenURLMessage;\r\n\r\nstruct PlayerSetPluginDataMessage {\r\n\tvoid *\t\t\t\t\t\t\tdataPtr;\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tdataSize;\t\t/* Input */\r\n};\r\ntypedef struct PlayerSetPluginDataMessage PlayerSetPluginDataMessage;\r\n\r\nstruct PlayerGetPluginDataMessage {\r\n\tvoid *\t\t\t\t\t\t\tdataPtr;\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tdataBufferSize;\t/* Input */\r\n\t\r\n\tUInt32\t\t\t\t\t\t\tdataSize;\t\t/* Output */\r\n};\r\ntypedef struct PlayerGetPluginDataMessage PlayerGetPluginDataMessage;\r\n\r\nstruct PlayerSetPluginNamedDataMessage {\r\n\tConstStringPtr\t\t\t\t\tdataName;\t\t/* Input */\r\n\r\n\tvoid *\t\t\t\t\t\t\tdataPtr;\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tdataSize;\t\t/* Input */\r\n};\r\ntypedef struct PlayerSetPluginNamedDataMessage PlayerSetPluginNamedDataMessage;\r\n\r\nstruct PlayerGetPluginNamedDataMessage {\r\n\tConstStringPtr\t\t\t\t\tdataName;\t\t/* Input */\r\n\r\n\tvoid *\t\t\t\t\t\t\tdataPtr;\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tdataBufferSize;\t/* Input */\r\n\t\r\n\tUInt32\t\t\t\t\t\t\tdataSize;\t\t/* Output */\r\n};\r\ntypedef struct PlayerGetPluginNamedDataMessage PlayerGetPluginNamedDataMessage;\r\n\r\nstruct PlayerGetPluginITFileSpecMessage {\r\n\tITFileSpec *\t\t\t\t\tfileSpec;\t\t/* Output */\r\n};\r\ntypedef struct PlayerGetPluginITFileSpecMessage PlayerGetPluginITFileSpecMessage;\r\n\r\nstruct PlayerGetFileTrackInfoMessage {\r\n\tconst ITFileSpec *\t\t\t\tfileSpec;\t\t/* Input */\r\n\tITTrackInfo *\t\t\t\t\ttrackInfo;\t\t/* Output */\r\n};\r\ntypedef struct PlayerGetFileTrackInfoMessage PlayerGetFileTrackInfoMessage;\r\n\r\nstruct PlayerSetFileTrackInfoMessage {\r\n\tconst ITFileSpec *\t\t\t\tfileSpec;\t\t/* Input */\r\n\tconst ITTrackInfo *\t\t\t\ttrackInfo;\t\t/* Input */\r\n};\r\ntypedef struct PlayerSetFileTrackInfoMessage PlayerSetFileTrackInfoMessage;\r\n\r\nstruct PlayerGetITTrackInfoSizeMessage {\r\n\tUInt32\t\t\t\t\t\t\titTrackInfoSize;\t/* Output */\r\n};\r\ntypedef struct PlayerGetITTrackInfoSizeMessage PlayerGetITTrackInfoSizeMessage;\r\n\r\n/*\r\n\tiTunes API callback visual structures\r\n*/\r\nenum {\r\n\t/* PlayerRegisterVisualPluginMessage.options */\r\n\t\r\n\t/* Plugin uses 3D exclusively (OpenGL or Direct3D), iTunes does not need to invalidate the backing native view. */\r\n\tkVisualUsesOnly3D\t\t\t\t\t= (1u << 0),\r\n\t/* Plugin supports discrete or integrated graphics without requiring a mode switch. */\r\n\tkVisualSupportsMuxedGraphics\t\t= (1u << 1),\r\n\t/* Mac-only: Plugin adds an NSView-based subview to the one provided, iTunes does not need to invalidate the backing native view.*/\r\n\tkVisualUsesSubview\t\t\t\t\t= (1u << 2),\r\n\t/* Plugin wants periodic idle messages.  Note that these idle messages are not for drawing, only for internal processing. */\r\n\tkVisualWantsIdleMessages\t\t\t= (1u << 3),\r\n\t/* Plugin supports a configure dialog, iTunes will display an item in the menus to show it. */\r\n\tkVisualWantsConfigure\t\t\t\t= (1u << 5)\r\n};\r\n\r\nstruct PlayerRegisterVisualPluginMessage {\r\n\t/* Input from plugin */\r\n\tITUniStr255\t\t\t\t\t\tname;\t\t\t\t\t\t/* Displayed in the Visualizer menu */\r\n\tOptionBits\t\t\t\t\t\toptions;\t\t\t\t\t/* See above */\r\n\t\r\n\tOSType\t\t\t\t\t\t\tcreator;\t\t\t\t\t/* Identifies the plugin */\r\n\t\r\n\tNumVersion\t\t\t\t\t\tpluginVersion;\t\t\t\t/* Version number of the plugin */\r\n\r\n\tVisualPluginProcPtr\t\t\t\thandler;\t\t\t\t\t/* Handler for the plugin's messages */\r\n\tvoid *\t\t\t\t\t\t\tregisterRefCon;\t\t\t\t/* RefCon for the plugin's handler */\r\n\r\n\tUInt32\t\t\t\t\t\t\tpulseRateInHz;\t\t\t\t/* Send the plugin a \"pulse\" message N times a second (max ~= 120 but may vary) */\r\n\tUInt32\t\t\t\t\t\t\tnumWaveformChannels;\t\t/* 0-2 waveforms requested */\r\n\tUInt32\t\t\t\t\t\t\tnumSpectrumChannels;\t\t/* 0-2 spectrums requested */\r\n\t\r\n\tSInt32\t\t\t\t\t\t\tminWidth;\t\t\t\t\t/* Minimum resizeable width (0 for no restriction) */\r\n\tSInt32\t\t\t\t\t\t\tminHeight;\t\t\t\t\t/* Minimum resizeable height (0 for no restriction) */\r\n\t\r\n\tSInt32\t\t\t\t\t\t\tmaxWidth;\t\t\t\t\t/* Maximum resizeable width (0 for no limit) */\r\n\tSInt32\t\t\t\t\t\t\tmaxHeight;\t\t\t\t\t/* Maximum resizeable height (0 for no limit) */\r\n};\r\ntypedef struct PlayerRegisterVisualPluginMessage PlayerRegisterVisualPluginMessage;\r\n\r\nstruct PlayerSetFullScreenMessage {\r\n\tBoolean\t\t\t\t\t\t\tfullScreen;\r\n};\r\ntypedef struct PlayerSetFullScreenMessage PlayerSetFullScreenMessage;\r\n\r\n\r\n// iTunes API callback union structure\r\nstruct PlayerMessageInfo {\r\n\tUInt32\t\t\t\t\t\t\t\t\tmessageMajorVersion;\t\t/* Should be kITPluginMajorMessageVersion */\r\n\tUInt32\t\t\t\t\t\t\t\t\tmessageMinorVersion;\t\t/* Should be kITPluginMinorMessageVersion */\r\n\tUInt32\t\t\t\t\t\t\t\t\tmessageInfoSize;\t\t\t/* Should be sizeof(PlayerMessageInfo) */\r\n\t\r\n\tunion {\r\n\t\tPlayerOpenURLMessage\t\t\t\topenURLMessage;\r\n\t\t\r\n\t\tPlayerSetPluginDataMessage\t\t\tsetPluginDataMessage;\r\n\t\tPlayerGetPluginDataMessage\t\t\tgetPluginDataMessage;\r\n\t\t\r\n\t\tPlayerSetPluginNamedDataMessage\t\tsetPluginNamedDataMessage;\r\n\t\tPlayerGetPluginNamedDataMessage\t\tgetPluginNamedDataMessage;\r\n\t\t\r\n\t\t\t\t\r\n\t\tPlayerGetFileTrackInfoMessage\t\tgetFileTrackInfoMessage;\r\n\t\tPlayerSetFileTrackInfoMessage\t\tsetFileTrackInfoMessage;\r\n\t\tPlayerGetITTrackInfoSizeMessage\t\tgetITTrackInfoSizeMessage;\r\n\r\n\t\tPlayerGetPluginITFileSpecMessage\tgetPluginITFileSpecMessage;\r\n\r\n\t\t// visual APIs\r\n\t\tPlayerRegisterVisualPluginMessage\t\tregisterVisualPluginMessage;\r\n\t\tPlayerSetFullScreenMessage\t\t\t\tsetFullScreenMessage;\r\n\r\n\t} u;\r\n};\r\ntypedef struct PlayerMessageInfo PlayerMessageInfo;\r\n\r\nextern OSStatus ITCallApplication(void *appCookie, ITAppProcPtr appProc, OSType message, PlayerMessageInfo *messageInfo);\r\nextern void\t\tSetNumVersion(NumVersion *numVersion, UInt8 majorRev, UInt8 minorAndBugRev, UInt8 stage, UInt8 nonRelRev);\r\n\r\n\r\n/* For all plugins */\r\n\r\nextern OSStatus\tPlayerUnregisterPlugin(void *appCookie, ITAppProcPtr appProc, PlayerMessageInfo *messageInfo);\r\nextern OSStatus PlayerIdle(void *appCookie, ITAppProcPtr appProc);\r\n\r\nextern void\t\tPlayerShowAbout(void *appCookie, ITAppProcPtr appProc);\r\nextern void\t\tPlayerOpenURL(void *appCookie, ITAppProcPtr appProc, SInt8 *string, UInt32 length);\r\n\r\nextern OSStatus\tPlayerGetPluginData(void *appCookie, ITAppProcPtr appProc, void *dataPtr, UInt32 dataBufferSize, UInt32 *dataSize);\r\nextern OSStatus\tPlayerSetPluginData(void *appCookie, ITAppProcPtr appProc, void *dataPtr, UInt32 dataSize);\r\n\r\nextern OSStatus\tPlayerGetPluginNamedData(void *appCookie, ITAppProcPtr appProc, ConstStringPtr dataName, void *dataPtr, UInt32 dataBufferSize, UInt32 *dataSize);\r\nextern OSStatus\tPlayerSetPluginNamedData(void *appCookie, ITAppProcPtr appProc, ConstStringPtr dataName, void *dataPtr, UInt32 dataSize);\r\n\r\nextern OSStatus\tPlayerGetFileTrackInfo(void *appCookie, ITAppProcPtr appProc, const ITFileSpec *fileSpec, ITTrackInfo *trackInfo);\r\nextern OSStatus\tPlayerSetFileTrackInfo(void *appCookie, ITAppProcPtr appProc, const ITFileSpec *fileSpec, const ITTrackInfo *trackInfo);\r\n\r\nextern OSStatus PlayerGetITTrackInfoSize(void *appCookie, ITAppProcPtr appProc, UInt32 appPluginMajorVersion, UInt32 appPluginMinorVersion, UInt32 *itTrackInfoSize);\r\n\r\nextern OSStatus\tPlayerGetPluginITFileSpec(void *appCookie, ITAppProcPtr appProc, ITFileSpec *pluginFileSpec);\r\n\r\n/* iTunes APIs For visual plugins */\r\nenum {\r\n\tkPlayerSetFullScreenMessage\t\t\t= 'sful',\t\t/* Set full screen mode */\r\n\tkPlayerSetFullScreenOptionsMessage\t= 'sfop',\t\t/* Set full screen options */\r\n\r\n\t/*\r\n\t\tRequest the current player track cover artwork.\r\n\t\tIt will be returned asynchronously via kVisualPluginCoverArtworkMessage.\r\n\t*/\r\n\tkPlayerRequestCurrentTrackCoverArtMessage = 'rart'\r\n\r\n};\r\n\r\nextern OSStatus PlayerRegisterVisualPlugin(void *appCookie, ITAppProcPtr appProc, PlayerMessageInfo *messageInfo);\r\n\r\nextern OSStatus PlayerSetFullScreen(void *appCookie, ITAppProcPtr appProc, Boolean fullScreen);\r\nextern OSStatus PlayerSetFullScreenOptions(void *appCookie, ITAppProcPtr appProc, SInt16 minBitDepth, SInt16 maxBitDepth, SInt16 preferredBitDepth, SInt16 desiredWidth, SInt16 desiredHeight);\r\nextern OSStatus PlayerRequestCurrentTrackCoverArt(void *appCookie, ITAppProcPtr appProc);\r\n\r\n#if PRAGMA_STRUCT_ALIGN\r\n    #pragma options align=reset\r\n#elif PRAGMA_STRUCT_PACKPUSH\r\n    #pragma pack(pop)\r\n#elif PRAGMA_STRUCT_PACK\r\n    #pragma pack()\r\n#endif\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif /* ITUNESAPI_H_ */\r\n"
  },
  {
    "path": "plugins/iTunes/iTunesVisualAPI/iTunesVisualAPI.h",
    "content": "//\r\n// File:       iTunesVisualAPI.h\r\n//\r\n// Abstract:   part of iTunes Visual SDK\r\n//\r\n// Version:    2.0\r\n//\r\n// Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Inc. ( \"Apple\" )\r\n//             in consideration of your agreement to the following terms, and your use,\r\n//             installation, modification or redistribution of this Apple software\r\n//             constitutes acceptance of these terms.  If you do not agree with these\r\n//             terms, please do not use, install, modify or redistribute this Apple\r\n//             software.\r\n//\r\n//             In consideration of your agreement to abide by the following terms, and\r\n//             subject to these terms, Apple grants you a personal, non - exclusive\r\n//             license, under Apple's copyrights in this original Apple software ( the\r\n//             \"Apple Software\" ), to use, reproduce, modify and redistribute the Apple\r\n//             Software, with or without modifications, in source and / or binary forms;\r\n//             provided that if you redistribute the Apple Software in its entirety and\r\n//             without modifications, you must retain this notice and the following text\r\n//             and disclaimers in all such redistributions of the Apple Software. Neither\r\n//             the name, trademarks, service marks or logos of Apple Inc. may be used to\r\n//             endorse or promote products derived from the Apple Software without specific\r\n//             prior written permission from Apple.  Except as expressly stated in this\r\n//             notice, no other rights or licenses, express or implied, are granted by\r\n//             Apple herein, including but not limited to any patent rights that may be\r\n//             infringed by your derivative works or by other works in which the Apple\r\n//             Software may be incorporated.\r\n//\r\n//             The Apple Software is provided by Apple on an \"AS IS\" basis.  APPLE MAKES NO\r\n//             WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED\r\n//             WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A\r\n//             PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION\r\n//             ALONE OR IN COMBINATION WITH YOUR PRODUCTS.\r\n//\r\n//             IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR\r\n//             CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\r\n//             SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\r\n//             INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION\r\n//             AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER\r\n//             UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR\r\n//             OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n//\r\n// Copyright © 2000-2011 Apple Inc. All Rights Reserved.\r\n//\r\n#ifndef ITUNESVISUALAPI_H_\r\n#define ITUNESVISUALAPI_H_\r\n\r\n#include \"iTunesAPI.h\"\r\n\r\n#if PRAGMA_ONCE\r\n#pragma once\r\n#endif\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n\r\n#if PRAGMA_STRUCT_ALIGN\r\n    #pragma options align=power\r\n#elif PRAGMA_STRUCT_PACKPUSH\r\n    #pragma pack(push, 4)\r\n#elif PRAGMA_STRUCT_PACK\r\n    #pragma pack(4)\r\n#endif\r\n\r\n\r\nenum {\r\n\tkCurrentITStreamInfoVersion = 1\r\n};\r\n\r\nenum {\r\n\tkITVisualPluginMajorMessageVersion = 10,\r\n\tkITVisualPluginMinorMessageVersion = 7\r\n};\r\n\r\nenum {\r\n\t/* VisualPlugin messages */\r\n\t\r\n\tkVisualPluginInitMessage\t\t\t= 'init',\r\n\tkVisualPluginCleanupMessage\t\t\t= 'clr ',\r\n\t\r\n\tkVisualPluginIdleMessage\t\t\t= 'null',\r\n\r\n\tkVisualPluginConfigureMessage\t\t= 'cnfg',\t/* Configure the plugin. */\r\n\t\r\n\tkVisualPluginEnableMessage\t\t\t= 'von ',\t/* Enable the plugin and make it available to the user (automatic). */\r\n\tkVisualPluginDisableMessage\t\t\t= 'voff',\t/* Disable the plugin. */\r\n\t\r\n\tkVisualPluginActivateMessage\t\t= 'Vact',\t/* Visualizer is being shown on screen (allocate large memory here) */\r\n\tkVisualPluginWindowChangedMessage\t= 'Vmov',\t/* The visualizer context was moved to a new window.  A draw message will be sent immediately. */\r\n\tkVisualPluginDeactivateMessage\t\t= 'Vdct',\t/* Visualizer is being removed from the screen (deallocate large memory here) */\r\n\r\n\tkVisualPluginPulseMessage\t\t\t= 'Vpls',\t/* Sent at the rate requested during plugin registration. Contains new data if currently playing audio. */\r\n\tkVisualPluginDrawMessage\t\t\t= 'Vdrw',\t/* Draw a new frame.  Sent when the OS decides to repaint the backing view. */\r\n\tkVisualPluginFrameChangedMessage\t= 'Vfrm',\t/* The visualizer area resized.  A draw message will be sent immediately. */\r\n\r\n\tkVisualPluginPlayMessage\t\t\t= 'Vply',\t/* Starting playback. */\r\n\tkVisualPluginChangeTrackMessage\t\t= 'Ctrk',\t/* Current track changed or info about the current track has changed. */\r\n\tkVisualPluginSetPositionMessage\t\t= 'setp',\t/* Setting the position of the currently playing track. */\r\n\tkVisualPluginStopMessage\t\t\t= 'vstp',\t/* Stopping playback. */\r\n\tkVisualPluginCoverArtMessage\t\t= 'Vart',\t/* Delivers the current track artwork as requested by the plugin. Plugin must retain/copy it if it wants to keep it. */\r\n\r\n\tkVisualPluginDisplayChangedMessage\t= 'dchn'\t/* Something about display state changed. */\r\n\r\n};\r\n\r\n/*\r\n\tVisualPlugin messages\r\n*/\r\n\r\nenum {\r\n\tkVisualMaxDataChannels\t\t= 2,\r\n\r\n\tkVisualNumWaveformEntries\t= 512,\r\n\tkVisualNumSpectrumEntries\t= 512\r\n};\r\n\r\nenum {\r\n\t/* CoverArt format types */\r\n\tkVisualCoverArtFormatJPEG\t= 13,\r\n\tkVisualCoverArtFormatPNG\t= 14,\r\n\tkVisualCoverArtFormatBMP\t= 27\r\n};\r\n\r\nenum {\r\n\t/* Activate options */\r\n\t\r\n\tkWindowIsFullScreen = (1u << 0)\r\n};\r\n\r\nstruct RenderVisualData {\r\n\tUInt8\t\t\t\t\t\t\tnumWaveformChannels;\r\n\tUInt8\t\t\t\t\t\t\twaveformData[kVisualMaxDataChannels][kVisualNumWaveformEntries];\r\n\t\r\n\tUInt8\t\t\t\t\t\t\tnumSpectrumChannels;\r\n\tUInt8\t\t\t\t\t\t\tspectrumData[kVisualMaxDataChannels][kVisualNumSpectrumEntries];\r\n};\r\ntypedef struct RenderVisualData RenderVisualData;\r\n\r\nstruct VisualPluginInitMessage {\r\n\tUInt32\t\t\t\t\t\t\tmessageMajorVersion;\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tmessageMinorVersion;\t/* Input */\r\n\tNumVersion\t\t\t\t\t\tappVersion;\t\t\t\t/* Input */\r\n\r\n\tvoid *\t\t\t\t\t\t\tappCookie;\t\t\t\t/* Input */\r\n\tITAppProcPtr\t\t\t\t\tappProc;\t\t\t\t/* Input */\r\n\r\n\tOptionBits\t\t\t\t\t\tunused;\t\t\t\t\t/* N/A */\r\n\tvoid *\t\t\t\t\t\t\trefCon;\t\t\t\t\t/* Output */\r\n};\r\ntypedef struct VisualPluginInitMessage VisualPluginInitMessage;\r\n\r\nstruct VisualPluginActivateMessage {\r\n\tVISUAL_PLATFORM_VIEW\t\t\tview;\t\t\t\t\t/* Input - plugin should draw in entire bounds */\r\n\tOptionBits\t\t\t\t\t\toptions;\t\t\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginActivateMessage VisualPluginActivateMessage;\r\n\r\nstruct VisualPluginWindowChangedMessage {\r\n\tOptionBits\t\t\t\t\t\toptions;\t\t\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginWindowChangedMessage VisualPluginWindowChangedMessage;\r\n\r\nstruct VisualPluginPulseMessage {\r\n\tRenderVisualData *\t\t\t\trenderData;\t\t\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\ttimeStampID;\t\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tcurrentPositionInMS;\t/* Input */\r\n\t\r\n\tUInt32\t\t\t\t\t\t\tnewPulseRateInHz;\t\t/* Input/Output - contains current rate on input, modify it to get a new rate. */\r\n};\r\ntypedef struct VisualPluginPulseMessage VisualPluginPulseMessage;\r\n\r\nstruct VisualPluginPlayMessage {\r\n\tITTrackInfo *\t\t\t\t\ttrackInfo;\t\t\t\t/* Input */\r\n\tITStreamInfo *\t\t\t\t\tstreamInfo;\t\t\t\t/* Input */\r\n\r\n\tAudioStreamBasicDescription\t\taudioFormat;\t\t\t/* Input */\r\n\tUInt32\t\t\t\t\t\t\tbitRate;\t\t\t\t/* Input */\r\n\tSInt32\t\t\t\t\t\t\tvolume;\t\t\t\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginPlayMessage VisualPluginPlayMessage;\r\n\r\nstruct VisualPluginChangeTrackMessage {\r\n\tITTrackInfo *\t\t\t\t\ttrackInfo;\t\t\t\t/* Input */\r\n\tITStreamInfo *\t\t\t\t\tstreamInfo;\t\t\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginChangeTrackMessage VisualPluginChangeTrackMessage;\r\n\r\nstruct VisualPluginCoverArtMessage {\r\n\tVISUAL_PLATFORM_DATA\t\tcoverArt;\t\t\t\t\t/* input - client must retain (mac) or copy (windows) the data if they want to keep it after this message completes.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t - note that coverArt will be NULL if the current track has no artwork */\r\n\tUInt32\t\t\t\t\t\tcoverArtSize;\t\t\t\t/* input - size of the coverArt in bytes */\r\n\tUInt32\t\t\t\t\t\tcoverArtFormat;\t\t\t\t/* input - format of cover art */\r\n};\r\ntypedef struct VisualPluginCoverArtMessage VisualPluginCoverArtMessage;\r\n\r\nstruct VisualPluginSetPositionMessage {\r\n\tUInt32\t\t\t\t\t\t\tpositionTimeInMS;\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginSetPositionMessage VisualPluginSetPositionMessage;\r\n\r\nenum {\r\n\tkVisualDisplayDepthChanged \t= 1 << 0,\t\t\t\t\t/* the display's depth has changed */\r\n\tkVisualDisplayRectChanged\t= 1 << 1,\t\t\t\t\t/* the display's location changed */\r\n\tkVisualWindowMoved\t\t\t= 1 << 2,\t\t\t\t\t/* the window has moved location */\t\r\n\tkVisualDisplayConfigChanged\t= 1 << 3,\t\t\t\t\t/* something else about the display changed */\r\n};\r\n\r\nstruct VisualPluginDisplayChangedMessage {\r\n\tUInt32\t\t\t\t\t\t\tflags;\t\t/* Input */\r\n};\r\ntypedef struct VisualPluginDisplayChangedMessage VisualPluginDisplayChangedMessage;\r\n\r\n\r\nstruct VisualPluginMessageInfo {\r\n\tunion {\r\n\t\tVisualPluginInitMessage\t\t\t\t\tinitMessage;\r\n\t\tVisualPluginActivateMessage\t\t\t\tactivateMessage;\r\n\t\tVisualPluginWindowChangedMessage\t\twindowChangedMessage;\r\n\t\tVisualPluginPulseMessage\t\t\t\tpulseMessage;\r\n\t\tVisualPluginPlayMessage\t\t\t\t\tplayMessage;\r\n\t\tVisualPluginChangeTrackMessage\t\t\tchangeTrackMessage;\r\n\t\tVisualPluginSetPositionMessage\t\t\tsetPositionMessage;\r\n\t\tVisualPluginCoverArtMessage\t\t\t\tcoverArtMessage;\r\n\t\tVisualPluginDisplayChangedMessage\t\tdisplayChangedMessage;\r\n\t} u;\r\n};\r\ntypedef struct VisualPluginMessageInfo VisualPluginMessageInfo;\r\n\r\n#if PRAGMA_STRUCT_ALIGN\r\n    #pragma options align=reset\r\n#elif PRAGMA_STRUCT_PACKPUSH\r\n    #pragma pack(pop)\r\n#elif PRAGMA_STRUCT_PACK\r\n    #pragma pack()\r\n#endif\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif /* ITUNESVISUALAPI_H_ */\r\n"
  },
  {
    "path": "plugins/iTunes/libs/sqlite3.c",
    "content": "/******************************************************************************\n** This file is an amalgamation of many separate C source files from SQLite\n** version 3.7.14.1.  By combining all the individual C code files into this \n** single large file, the entire code can be compiled as a single translation\n** unit.  This allows many compilers to do optimizations that would not be\n** possible if the files were compiled separately.  Performance improvements\n** of 5% or more are commonly seen when SQLite is compiled as a single\n** translation unit.\n**\n** This file is all you need to compile SQLite.  To use SQLite in other\n** programs, you need this file and the \"sqlite3.h\" header file that defines\n** the programming interface to the SQLite library.  (If you do not have \n** the \"sqlite3.h\" header file at hand, you will find a copy embedded within\n** the text of this file.  Search for \"Begin file sqlite3.h\" to find the start\n** of the embedded sqlite3.h header file.) Additional code files may be needed\n** if you want a wrapper to interface SQLite with your choice of programming\n** language. The code for the \"sqlite3\" command-line shell is also in a\n** separate file. This file contains only code for the core SQLite library.\n*/\n#define SQLITE_CORE 1\n#define SQLITE_AMALGAMATION 1\n#ifndef SQLITE_PRIVATE\n# define SQLITE_PRIVATE static\n#endif\n#ifndef SQLITE_API\n# define SQLITE_API\n#endif\n/************** Begin file sqliteInt.h ***************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Internal interface definitions for SQLite.\n**\n*/\n#ifndef _SQLITEINT_H_\n#define _SQLITEINT_H_\n\n/*\n** These #defines should enable >2GB file support on POSIX if the\n** underlying operating system supports it.  If the OS lacks\n** large file support, or if the OS is windows, these should be no-ops.\n**\n** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any\n** system #includes.  Hence, this block of code must be the very first\n** code in all source files.\n**\n** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch\n** on the compiler command line.  This is necessary if you are compiling\n** on a recent machine (ex: Red Hat 7.2) but you want your code to work\n** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2\n** without this option, LFS is enable.  But LFS does not exist in the kernel\n** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary\n** portability you should omit LFS.\n**\n** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.\n*/\n#ifndef SQLITE_DISABLE_LFS\n# define _LARGE_FILE       1\n# ifndef _FILE_OFFSET_BITS\n#   define _FILE_OFFSET_BITS 64\n# endif\n# define _LARGEFILE_SOURCE 1\n#endif\n\n/*\n** Include the configuration header output by 'configure' if we're using the\n** autoconf-based build\n*/\n#ifdef _HAVE_SQLITE_CONFIG_H\n#include \"config.h\"\n#endif\n\n/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/\n/************** Begin file sqliteLimit.h *************************************/\n/*\n** 2007 May 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** \n** This file defines various limits of what SQLite can process.\n*/\n\n/*\n** The maximum length of a TEXT or BLOB in bytes.   This also\n** limits the size of a row in a table or index.\n**\n** The hard limit is the ability of a 32-bit signed integer\n** to count the size: 2^31-1 or 2147483647.\n*/\n#ifndef SQLITE_MAX_LENGTH\n# define SQLITE_MAX_LENGTH 1000000000\n#endif\n\n/*\n** This is the maximum number of\n**\n**    * Columns in a table\n**    * Columns in an index\n**    * Columns in a view\n**    * Terms in the SET clause of an UPDATE statement\n**    * Terms in the result set of a SELECT statement\n**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.\n**    * Terms in the VALUES clause of an INSERT statement\n**\n** The hard upper limit here is 32676.  Most database people will\n** tell you that in a well-normalized database, you usually should\n** not have more than a dozen or so columns in any table.  And if\n** that is the case, there is no point in having more than a few\n** dozen values in any of the other situations described above.\n*/\n#ifndef SQLITE_MAX_COLUMN\n# define SQLITE_MAX_COLUMN 2000\n#endif\n\n/*\n** The maximum length of a single SQL statement in bytes.\n**\n** It used to be the case that setting this value to zero would\n** turn the limit off.  That is no longer true.  It is not possible\n** to turn this limit off.\n*/\n#ifndef SQLITE_MAX_SQL_LENGTH\n# define SQLITE_MAX_SQL_LENGTH 1000000000\n#endif\n\n/*\n** The maximum depth of an expression tree. This is limited to \n** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might \n** want to place more severe limits on the complexity of an \n** expression.\n**\n** A value of 0 used to mean that the limit was not enforced.\n** But that is no longer true.  The limit is now strictly enforced\n** at all times.\n*/\n#ifndef SQLITE_MAX_EXPR_DEPTH\n# define SQLITE_MAX_EXPR_DEPTH 1000\n#endif\n\n/*\n** The maximum number of terms in a compound SELECT statement.\n** The code generator for compound SELECT statements does one\n** level of recursion for each term.  A stack overflow can result\n** if the number of terms is too large.  In practice, most SQL\n** never has more than 3 or 4 terms.  Use a value of 0 to disable\n** any limit on the number of terms in a compount SELECT.\n*/\n#ifndef SQLITE_MAX_COMPOUND_SELECT\n# define SQLITE_MAX_COMPOUND_SELECT 500\n#endif\n\n/*\n** The maximum number of opcodes in a VDBE program.\n** Not currently enforced.\n*/\n#ifndef SQLITE_MAX_VDBE_OP\n# define SQLITE_MAX_VDBE_OP 25000\n#endif\n\n/*\n** The maximum number of arguments to an SQL function.\n*/\n#ifndef SQLITE_MAX_FUNCTION_ARG\n# define SQLITE_MAX_FUNCTION_ARG 127\n#endif\n\n/*\n** The maximum number of in-memory pages to use for the main database\n** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE\n*/\n#ifndef SQLITE_DEFAULT_CACHE_SIZE\n# define SQLITE_DEFAULT_CACHE_SIZE  2000\n#endif\n#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE\n# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500\n#endif\n\n/*\n** The default number of frames to accumulate in the log file before\n** checkpointing the database in WAL mode.\n*/\n#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT\n# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000\n#endif\n\n/*\n** The maximum number of attached databases.  This must be between 0\n** and 62.  The upper bound on 62 is because a 64-bit integer bitmap\n** is used internally to track attached databases.\n*/\n#ifndef SQLITE_MAX_ATTACHED\n# define SQLITE_MAX_ATTACHED 10\n#endif\n\n\n/*\n** The maximum value of a ?nnn wildcard that the parser will accept.\n*/\n#ifndef SQLITE_MAX_VARIABLE_NUMBER\n# define SQLITE_MAX_VARIABLE_NUMBER 999\n#endif\n\n/* Maximum page size.  The upper bound on this value is 65536.  This a limit\n** imposed by the use of 16-bit offsets within each page.\n**\n** Earlier versions of SQLite allowed the user to change this value at\n** compile time. This is no longer permitted, on the grounds that it creates\n** a library that is technically incompatible with an SQLite library \n** compiled with a different limit. If a process operating on a database \n** with a page-size of 65536 bytes crashes, then an instance of SQLite \n** compiled with the default page-size limit will not be able to rollback \n** the aborted transaction. This could lead to database corruption.\n*/\n#ifdef SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_MAX_PAGE_SIZE\n#endif\n#define SQLITE_MAX_PAGE_SIZE 65536\n\n\n/*\n** The default size of a database page.\n*/\n#ifndef SQLITE_DEFAULT_PAGE_SIZE\n# define SQLITE_DEFAULT_PAGE_SIZE 1024\n#endif\n#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_DEFAULT_PAGE_SIZE\n# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE\n#endif\n\n/*\n** Ordinarily, if no value is explicitly provided, SQLite creates databases\n** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain\n** device characteristics (sector-size and atomic write() support),\n** SQLite may choose a larger value. This constant is the maximum value\n** SQLite will choose on its own.\n*/\n#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE\n# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192\n#endif\n#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE\n# undef SQLITE_MAX_DEFAULT_PAGE_SIZE\n# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE\n#endif\n\n\n/*\n** Maximum number of pages in one database file.\n**\n** This is really just the default value for the max_page_count pragma.\n** This value can be lowered (or raised) at run-time using that the\n** max_page_count macro.\n*/\n#ifndef SQLITE_MAX_PAGE_COUNT\n# define SQLITE_MAX_PAGE_COUNT 1073741823\n#endif\n\n/*\n** Maximum length (in bytes) of the pattern in a LIKE or GLOB\n** operator.\n*/\n#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH\n# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000\n#endif\n\n/*\n** Maximum depth of recursion for triggers.\n**\n** A value of 1 means that a trigger program will not be able to itself\n** fire any triggers. A value of 0 means that no trigger programs at all \n** may be executed.\n*/\n#ifndef SQLITE_MAX_TRIGGER_DEPTH\n# define SQLITE_MAX_TRIGGER_DEPTH 1000\n#endif\n\n/************** End of sqliteLimit.h *****************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/* Disable nuisance warnings on Borland compilers */\n#if defined(__BORLANDC__)\n#pragma warn -rch /* unreachable code */\n#pragma warn -ccc /* Condition is always true or false */\n#pragma warn -aus /* Assigned value is never used */\n#pragma warn -csu /* Comparing signed and unsigned */\n#pragma warn -spa /* Suspicious pointer arithmetic */\n#endif\n\n/* Needed for various definitions... */\n#ifndef _GNU_SOURCE\n# define _GNU_SOURCE\n#endif\n\n/*\n** Include standard header files as necessary\n*/\n#ifdef HAVE_STDINT_H\n#include <stdint.h>\n#endif\n#ifdef HAVE_INTTYPES_H\n#include <inttypes.h>\n#endif\n\n/*\n** The following macros are used to cast pointers to integers and\n** integers to pointers.  The way you do this varies from one compiler\n** to the next, so we have developed the following set of #if statements\n** to generate appropriate macros for a wide range of compilers.\n**\n** The correct \"ANSI\" way to do this is to use the intptr_t type. \n** Unfortunately, that typedef is not available on all compilers, or\n** if it is available, it requires an #include of specific headers\n** that vary from one machine to the next.\n**\n** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on\n** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).\n** So we have to define the macros in different ways depending on the\n** compiler.\n*/\n#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))\n#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */\n# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])\n# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))\n#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))\n#else                          /* Generates a warning - but it always works */\n# define SQLITE_INT_TO_PTR(X)  ((void*)(X))\n# define SQLITE_PTR_TO_INT(X)  ((int)(X))\n#endif\n\n/*\n** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.\n** 0 means mutexes are permanently disable and the library is never\n** threadsafe.  1 means the library is serialized which is the highest\n** level of threadsafety.  2 means the libary is multithreaded - multiple\n** threads can use SQLite as long as no two threads try to use the same\n** database connection at the same time.\n**\n** Older versions of SQLite used an optional THREADSAFE macro.\n** We support that for legacy.\n*/\n#if !defined(SQLITE_THREADSAFE)\n#if defined(THREADSAFE)\n# define SQLITE_THREADSAFE THREADSAFE\n#else\n# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */\n#endif\n#endif\n\n/*\n** Powersafe overwrite is on by default.  But can be turned off using\n** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.\n*/\n#ifndef SQLITE_POWERSAFE_OVERWRITE\n# define SQLITE_POWERSAFE_OVERWRITE 1\n#endif\n\n/*\n** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.\n** It determines whether or not the features related to \n** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can\n** be overridden at runtime using the sqlite3_config() API.\n*/\n#if !defined(SQLITE_DEFAULT_MEMSTATUS)\n# define SQLITE_DEFAULT_MEMSTATUS 1\n#endif\n\n/*\n** Exactly one of the following macros must be defined in order to\n** specify which memory allocation subsystem to use.\n**\n**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()\n**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API\n**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails\n**     SQLITE_MEMDEBUG               // Debugging version of system malloc()\n**\n** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the\n** assert() macro is enabled, each call into the Win32 native heap subsystem\n** will cause HeapValidate to be called.  If heap validation should fail, an\n** assertion will be triggered.\n**\n** (Historical note:  There used to be several other options, but we've\n** pared it down to just these three.)\n**\n** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as\n** the default.\n*/\n#if defined(SQLITE_SYSTEM_MALLOC) \\\n  + defined(SQLITE_WIN32_MALLOC) \\\n  + defined(SQLITE_ZERO_MALLOC) \\\n  + defined(SQLITE_MEMDEBUG)>1\n# error \"Two or more of the following compile-time configuration options\\\n are defined but at most one is allowed:\\\n SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\\\n SQLITE_ZERO_MALLOC\"\n#endif\n#if defined(SQLITE_SYSTEM_MALLOC) \\\n  + defined(SQLITE_WIN32_MALLOC) \\\n  + defined(SQLITE_ZERO_MALLOC) \\\n  + defined(SQLITE_MEMDEBUG)==0\n# define SQLITE_SYSTEM_MALLOC 1\n#endif\n\n/*\n** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the\n** sizes of memory allocations below this value where possible.\n*/\n#if !defined(SQLITE_MALLOC_SOFT_LIMIT)\n# define SQLITE_MALLOC_SOFT_LIMIT 1024\n#endif\n\n/*\n** We need to define _XOPEN_SOURCE as follows in order to enable\n** recursive mutexes on most Unix systems.  But Mac OS X is different.\n** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,\n** so it is omitted there.  See ticket #2673.\n**\n** Later we learn that _XOPEN_SOURCE is poorly or incorrectly\n** implemented on some systems.  So we avoid defining it at all\n** if it is already defined or if it is unneeded because we are\n** not doing a threadsafe build.  Ticket #2681.\n**\n** See also ticket #2741.\n*/\n#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE\n#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */\n#endif\n\n/*\n** The TCL headers are only needed when compiling the TCL bindings.\n*/\n#if defined(SQLITE_TCL) || defined(TCLSH)\n# include <tcl.h>\n#endif\n\n/*\n** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that\n** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,\n** make it true by defining or undefining NDEBUG.\n**\n** Setting NDEBUG makes the code smaller and run faster by disabling the\n** number assert() statements in the code.  So we want the default action\n** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG\n** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out\n** feature.\n*/\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n#if defined(NDEBUG) && defined(SQLITE_DEBUG)\n# undef NDEBUG\n#endif\n\n/*\n** The testcase() macro is used to aid in coverage testing.  When \n** doing coverage testing, the condition inside the argument to\n** testcase() must be evaluated both true and false in order to\n** get full branch coverage.  The testcase() macro is inserted\n** to help ensure adequate test coverage in places where simple\n** condition/decision coverage is inadequate.  For example, testcase()\n** can be used to make sure boundary values are tested.  For\n** bitmask tests, testcase() can be used to make sure each bit\n** is significant and used at least once.  On switch statements\n** where multiple cases go to the same block of code, testcase()\n** can insure that all cases are evaluated.\n**\n*/\n#ifdef SQLITE_COVERAGE_TEST\nSQLITE_PRIVATE   void sqlite3Coverage(int);\n# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }\n#else\n# define testcase(X)\n#endif\n\n/*\n** The TESTONLY macro is used to enclose variable declarations or\n** other bits of code that are needed to support the arguments\n** within testcase() and assert() macros.\n*/\n#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)\n# define TESTONLY(X)  X\n#else\n# define TESTONLY(X)\n#endif\n\n/*\n** Sometimes we need a small amount of code such as a variable initialization\n** to setup for a later assert() statement.  We do not want this code to\n** appear when assert() is disabled.  The following macro is therefore\n** used to contain that setup code.  The \"VVA\" acronym stands for\n** \"Verification, Validation, and Accreditation\".  In other words, the\n** code within VVA_ONLY() will only run during verification processes.\n*/\n#ifndef NDEBUG\n# define VVA_ONLY(X)  X\n#else\n# define VVA_ONLY(X)\n#endif\n\n/*\n** The ALWAYS and NEVER macros surround boolean expressions which \n** are intended to always be true or false, respectively.  Such\n** expressions could be omitted from the code completely.  But they\n** are included in a few cases in order to enhance the resilience\n** of SQLite to unexpected behavior - to make the code \"self-healing\"\n** or \"ductile\" rather than being \"brittle\" and crashing at the first\n** hint of unplanned behavior.\n**\n** In other words, ALWAYS and NEVER are added for defensive code.\n**\n** When doing coverage testing ALWAYS and NEVER are hard-coded to\n** be true and false so that the unreachable code then specify will\n** not be counted as untested code.\n*/\n#if defined(SQLITE_COVERAGE_TEST)\n# define ALWAYS(X)      (1)\n# define NEVER(X)       (0)\n#elif !defined(NDEBUG)\n# define ALWAYS(X)      ((X)?1:(assert(0),0))\n# define NEVER(X)       ((X)?(assert(0),1):0)\n#else\n# define ALWAYS(X)      (X)\n# define NEVER(X)       (X)\n#endif\n\n/*\n** Return true (non-zero) if the input is a integer that is too large\n** to fit in 32-bits.  This macro is used inside of various testcase()\n** macros to verify that we have tested SQLite for large-file support.\n*/\n#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)\n\n/*\n** The macro unlikely() is a hint that surrounds a boolean\n** expression that is usually false.  Macro likely() surrounds\n** a boolean expression that is usually true.  GCC is able to\n** use these hints to generate better code, sometimes.\n*/\n#if defined(__GNUC__) && 0\n# define likely(X)    __builtin_expect((X),1)\n# define unlikely(X)  __builtin_expect((X),0)\n#else\n# define likely(X)    !!(X)\n# define unlikely(X)  !!(X)\n#endif\n\n/************** Include sqlite3.h in the middle of sqliteInt.h ***************/\n/************** Begin file sqlite3.h *****************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the SQLite library\n** presents to client programs.  If a C-function, structure, datatype,\n** or constant definition does not appear in this file, then it is\n** not a published API of SQLite, is subject to change without\n** notice, and should not be referenced by programs that use SQLite.\n**\n** Some of the definitions that are in this file are marked as\n** \"experimental\".  Experimental interfaces are normally new\n** features recently added to SQLite.  We do not anticipate changes\n** to experimental interfaces but reserve the right to make minor changes\n** if experience from use \"in the wild\" suggest such changes are prudent.\n**\n** The official C-language API documentation for SQLite is derived\n** from comments in this file.  This file is the authoritative source\n** on how SQLite interfaces are suppose to operate.\n**\n** The name of this file under configuration management is \"sqlite.h.in\".\n** The makefile makes some minor changes to this file (such as inserting\n** the version number) and changes its name to \"sqlite3.h\" as\n** part of the build process.\n*/\n#ifndef _SQLITE3_H_\n#define _SQLITE3_H_\n#include <stdarg.h>     /* Needed for the definition of va_list */\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#if 0\nextern \"C\" {\n#endif\n\n\n/*\n** Add the ability to override 'extern'\n*/\n#ifndef SQLITE_EXTERN\n# define SQLITE_EXTERN extern\n#endif\n\n#ifndef SQLITE_API\n# define SQLITE_API\n#endif\n\n\n/*\n** These no-op macros are used in front of interfaces to mark those\n** interfaces as either deprecated or experimental.  New applications\n** should not use deprecated interfaces - they are support for backwards\n** compatibility only.  Application writers should be aware that\n** experimental interfaces are subject to change in point releases.\n**\n** These macros used to resolve to various kinds of compiler magic that\n** would generate warning messages when they were used.  But that\n** compiler magic ended up generating such a flurry of bug reports\n** that we have taken it all out and gone back to using simple\n** noop macros.\n*/\n#define SQLITE_DEPRECATED\n#define SQLITE_EXPERIMENTAL\n\n/*\n** Ensure these symbols were not defined by some previous header file.\n*/\n#ifdef SQLITE_VERSION\n# undef SQLITE_VERSION\n#endif\n#ifdef SQLITE_VERSION_NUMBER\n# undef SQLITE_VERSION_NUMBER\n#endif\n\n/*\n** CAPI3REF: Compile-Time Library Version Numbers\n**\n** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header\n** evaluates to a string literal that is the SQLite version in the\n** format \"X.Y.Z\" where X is the major version number (always 3 for\n** SQLite3) and Y is the minor version number and Z is the release number.)^\n** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer\n** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same\n** numbers used in [SQLITE_VERSION].)^\n** The SQLITE_VERSION_NUMBER for any given release of SQLite will also\n** be larger than the release from which it is derived.  Either Y will\n** be held constant and Z will be incremented or else Y will be incremented\n** and Z will be reset to zero.\n**\n** Since version 3.6.18, SQLite source code has been stored in the\n** <a href=\"http://www.fossil-scm.org/\">Fossil configuration management\n** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to\n** a string which identifies a particular check-in of SQLite\n** within its configuration management system.  ^The SQLITE_SOURCE_ID\n** string contains the date and time of the check-in (UTC) and an SHA1\n** hash of the entire source tree.\n**\n** See also: [sqlite3_libversion()],\n** [sqlite3_libversion_number()], [sqlite3_sourceid()],\n** [sqlite_version()] and [sqlite_source_id()].\n*/\n#define SQLITE_VERSION        \"3.7.14.1\"\n#define SQLITE_VERSION_NUMBER 3007014\n#define SQLITE_SOURCE_ID      \"2012-10-04 19:37:12 091570e46d04e84b67228e0bdbcd6e1fb60c6bdb\"\n\n/*\n** CAPI3REF: Run-Time Library Version Numbers\n** KEYWORDS: sqlite3_version, sqlite3_sourceid\n**\n** These interfaces provide the same information as the [SQLITE_VERSION],\n** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros\n** but are associated with the library instead of the header file.  ^(Cautious\n** programmers might include assert() statements in their application to\n** verify that values returned by these interfaces match the macros in\n** the header, and thus insure that the application is\n** compiled with matching library and header files.\n**\n** <blockquote><pre>\n** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );\n** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );\n** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );\n** </pre></blockquote>)^\n**\n** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]\n** macro.  ^The sqlite3_libversion() function returns a pointer to the\n** to the sqlite3_version[] string constant.  The sqlite3_libversion()\n** function is provided for use in DLLs since DLL users usually do not have\n** direct access to string constants within the DLL.  ^The\n** sqlite3_libversion_number() function returns an integer equal to\n** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns \n** a pointer to a string constant whose value is the same as the \n** [SQLITE_SOURCE_ID] C preprocessor macro.\n**\n** See also: [sqlite_version()] and [sqlite_source_id()].\n*/\nSQLITE_API const char sqlite3_version[] = SQLITE_VERSION;\nSQLITE_API const char *sqlite3_libversion(void);\nSQLITE_API const char *sqlite3_sourceid(void);\nSQLITE_API int sqlite3_libversion_number(void);\n\n/*\n** CAPI3REF: Run-Time Library Compilation Options Diagnostics\n**\n** ^The sqlite3_compileoption_used() function returns 0 or 1 \n** indicating whether the specified option was defined at \n** compile time.  ^The SQLITE_ prefix may be omitted from the \n** option name passed to sqlite3_compileoption_used().  \n**\n** ^The sqlite3_compileoption_get() function allows iterating\n** over the list of options that were defined at compile time by\n** returning the N-th compile time option string.  ^If N is out of range,\n** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ \n** prefix is omitted from any strings returned by \n** sqlite3_compileoption_get().\n**\n** ^Support for the diagnostic functions sqlite3_compileoption_used()\n** and sqlite3_compileoption_get() may be omitted by specifying the \n** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.\n**\n** See also: SQL functions [sqlite_compileoption_used()] and\n** [sqlite_compileoption_get()] and the [compile_options pragma].\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName);\nSQLITE_API const char *sqlite3_compileoption_get(int N);\n#endif\n\n/*\n** CAPI3REF: Test To See If The Library Is Threadsafe\n**\n** ^The sqlite3_threadsafe() function returns zero if and only if\n** SQLite was compiled with mutexing code omitted due to the\n** [SQLITE_THREADSAFE] compile-time option being set to 0.\n**\n** SQLite can be compiled with or without mutexes.  When\n** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes\n** are enabled and SQLite is threadsafe.  When the\n** [SQLITE_THREADSAFE] macro is 0, \n** the mutexes are omitted.  Without the mutexes, it is not safe\n** to use SQLite concurrently from more than one thread.\n**\n** Enabling mutexes incurs a measurable performance penalty.\n** So if speed is of utmost importance, it makes sense to disable\n** the mutexes.  But for maximum safety, mutexes should be enabled.\n** ^The default behavior is for mutexes to be enabled.\n**\n** This interface can be used by an application to make sure that the\n** version of SQLite that it is linking against was compiled with\n** the desired setting of the [SQLITE_THREADSAFE] macro.\n**\n** This interface only reports on the compile-time mutex setting\n** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with\n** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but\n** can be fully or partially disabled using a call to [sqlite3_config()]\n** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],\n** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the\n** sqlite3_threadsafe() function shows only the compile-time setting of\n** thread safety, not any run-time changes to that setting made by\n** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()\n** is unchanged by calls to sqlite3_config().)^\n**\n** See the [threading mode] documentation for additional information.\n*/\nSQLITE_API int sqlite3_threadsafe(void);\n\n/*\n** CAPI3REF: Database Connection Handle\n** KEYWORDS: {database connection} {database connections}\n**\n** Each open SQLite database is represented by a pointer to an instance of\n** the opaque structure named \"sqlite3\".  It is useful to think of an sqlite3\n** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and\n** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]\n** and [sqlite3_close_v2()] are its destructors.  There are many other\n** interfaces (such as\n** [sqlite3_prepare_v2()], [sqlite3_create_function()], and\n** [sqlite3_busy_timeout()] to name but three) that are methods on an\n** sqlite3 object.\n*/\ntypedef struct sqlite3 sqlite3;\n\n/*\n** CAPI3REF: 64-Bit Integer Types\n** KEYWORDS: sqlite_int64 sqlite_uint64\n**\n** Because there is no cross-platform way to specify 64-bit integer types\n** SQLite includes typedefs for 64-bit signed and unsigned integers.\n**\n** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.\n** The sqlite_int64 and sqlite_uint64 types are supported for backwards\n** compatibility only.\n**\n** ^The sqlite3_int64 and sqlite_int64 types can store integer values\n** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The\n** sqlite3_uint64 and sqlite_uint64 types can store integer values \n** between 0 and +18446744073709551615 inclusive.\n*/\n#ifdef SQLITE_INT64_TYPE\n  typedef SQLITE_INT64_TYPE sqlite_int64;\n  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;\n#elif defined(_MSC_VER) || defined(__BORLANDC__)\n  typedef __int64 sqlite_int64;\n  typedef unsigned __int64 sqlite_uint64;\n#else\n  typedef long long int sqlite_int64;\n  typedef unsigned long long int sqlite_uint64;\n#endif\ntypedef sqlite_int64 sqlite3_int64;\ntypedef sqlite_uint64 sqlite3_uint64;\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite3_int64\n#endif\n\n/*\n** CAPI3REF: Closing A Database Connection\n**\n** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors\n** for the [sqlite3] object.\n** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if\n** the [sqlite3] object is successfully destroyed and all associated\n** resources are deallocated.\n**\n** ^If the database connection is associated with unfinalized prepared\n** statements or unfinished sqlite3_backup objects then sqlite3_close()\n** will leave the database connection open and return [SQLITE_BUSY].\n** ^If sqlite3_close_v2() is called with unfinalized prepared statements\n** and unfinished sqlite3_backups, then the database connection becomes\n** an unusable \"zombie\" which will automatically be deallocated when the\n** last prepared statement is finalized or the last sqlite3_backup is\n** finished.  The sqlite3_close_v2() interface is intended for use with\n** host languages that are garbage collected, and where the order in which\n** destructors are called is arbitrary.\n**\n** Applications should [sqlite3_finalize | finalize] all [prepared statements],\n** [sqlite3_blob_close | close] all [BLOB handles], and \n** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated\n** with the [sqlite3] object prior to attempting to close the object.  ^If\n** sqlite3_close() is called on a [database connection] that still has\n** outstanding [prepared statements], [BLOB handles], and/or\n** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation\n** of resources is deferred until all [prepared statements], [BLOB handles],\n** and [sqlite3_backup] objects are also destroyed.\n**\n** ^If an [sqlite3] object is destroyed while a transaction is open,\n** the transaction is automatically rolled back.\n**\n** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]\n** must be either a NULL\n** pointer or an [sqlite3] object pointer obtained\n** from [sqlite3_open()], [sqlite3_open16()], or\n** [sqlite3_open_v2()], and not previously closed.\n** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer\n** argument is a harmless no-op.\n*/\nSQLITE_API int sqlite3_close(sqlite3*);\nSQLITE_API int sqlite3_close_v2(sqlite3*);\n\n/*\n** The type for a callback function.\n** This is legacy and deprecated.  It is included for historical\n** compatibility and is not documented.\n*/\ntypedef int (*sqlite3_callback)(void*,int,char**, char**);\n\n/*\n** CAPI3REF: One-Step Query Execution Interface\n**\n** The sqlite3_exec() interface is a convenience wrapper around\n** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],\n** that allows an application to run multiple statements of SQL\n** without having to use a lot of C code. \n**\n** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,\n** semicolon-separate SQL statements passed into its 2nd argument,\n** in the context of the [database connection] passed in as its 1st\n** argument.  ^If the callback function of the 3rd argument to\n** sqlite3_exec() is not NULL, then it is invoked for each result row\n** coming out of the evaluated SQL statements.  ^The 4th argument to\n** sqlite3_exec() is relayed through to the 1st argument of each\n** callback invocation.  ^If the callback pointer to sqlite3_exec()\n** is NULL, then no callback is ever invoked and result rows are\n** ignored.\n**\n** ^If an error occurs while evaluating the SQL statements passed into\n** sqlite3_exec(), then execution of the current statement stops and\n** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()\n** is not NULL then any error message is written into memory obtained\n** from [sqlite3_malloc()] and passed back through the 5th parameter.\n** To avoid memory leaks, the application should invoke [sqlite3_free()]\n** on error message strings returned through the 5th parameter of\n** of sqlite3_exec() after the error message string is no longer needed.\n** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors\n** occur, then sqlite3_exec() sets the pointer in its 5th parameter to\n** NULL before returning.\n**\n** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()\n** routine returns SQLITE_ABORT without invoking the callback again and\n** without running any subsequent SQL statements.\n**\n** ^The 2nd argument to the sqlite3_exec() callback function is the\n** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()\n** callback is an array of pointers to strings obtained as if from\n** [sqlite3_column_text()], one for each column.  ^If an element of a\n** result row is NULL then the corresponding string pointer for the\n** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the\n** sqlite3_exec() callback is an array of pointers to strings where each\n** entry represents the name of corresponding result column as obtained\n** from [sqlite3_column_name()].\n**\n** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer\n** to an empty string, or a pointer that contains only whitespace and/or \n** SQL comments, then no SQL statements are evaluated and the database\n** is not changed.\n**\n** Restrictions:\n**\n** <ul>\n** <li> The application must insure that the 1st parameter to sqlite3_exec()\n**      is a valid and open [database connection].\n** <li> The application must not close [database connection] specified by\n**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.\n** <li> The application must not modify the SQL statement text passed into\n**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.\n** </ul>\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3*,                                  /* An open database */\n  const char *sql,                           /* SQL to be evaluated */\n  int (*callback)(void*,int,char**,char**),  /* Callback function */\n  void *,                                    /* 1st argument to callback */\n  char **errmsg                              /* Error msg written here */\n);\n\n/*\n** CAPI3REF: Result Codes\n** KEYWORDS: SQLITE_OK {error code} {error codes}\n** KEYWORDS: {result code} {result codes}\n**\n** Many SQLite functions return an integer result code from the set shown\n** here in order to indicate success or failure.\n**\n** New error codes may be added in future versions of SQLite.\n**\n** See also: [SQLITE_IOERR_READ | extended result codes],\n** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].\n*/\n#define SQLITE_OK           0   /* Successful result */\n/* beginning-of-error-codes */\n#define SQLITE_ERROR        1   /* SQL error or missing database */\n#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */\n#define SQLITE_PERM         3   /* Access permission denied */\n#define SQLITE_ABORT        4   /* Callback routine requested an abort */\n#define SQLITE_BUSY         5   /* The database file is locked */\n#define SQLITE_LOCKED       6   /* A table in the database is locked */\n#define SQLITE_NOMEM        7   /* A malloc() failed */\n#define SQLITE_READONLY     8   /* Attempt to write a readonly database */\n#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/\n#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */\n#define SQLITE_CORRUPT     11   /* The database disk image is malformed */\n#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */\n#define SQLITE_FULL        13   /* Insertion failed because database is full */\n#define SQLITE_CANTOPEN    14   /* Unable to open the database file */\n#define SQLITE_PROTOCOL    15   /* Database lock protocol error */\n#define SQLITE_EMPTY       16   /* Database is empty */\n#define SQLITE_SCHEMA      17   /* The database schema changed */\n#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */\n#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */\n#define SQLITE_MISMATCH    20   /* Data type mismatch */\n#define SQLITE_MISUSE      21   /* Library used incorrectly */\n#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */\n#define SQLITE_AUTH        23   /* Authorization denied */\n#define SQLITE_FORMAT      24   /* Auxiliary database format error */\n#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */\n#define SQLITE_NOTADB      26   /* File opened that is not a database file */\n#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */\n#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */\n/* end-of-error-codes */\n\n/*\n** CAPI3REF: Extended Result Codes\n** KEYWORDS: {extended error code} {extended error codes}\n** KEYWORDS: {extended result code} {extended result codes}\n**\n** In its default configuration, SQLite API routines return one of 26 integer\n** [SQLITE_OK | result codes].  However, experience has shown that many of\n** these result codes are too coarse-grained.  They do not provide as\n** much information about problems as programmers might like.  In an effort to\n** address this, newer versions of SQLite (version 3.3.8 and later) include\n** support for additional result codes that provide more detailed information\n** about errors. The extended result codes are enabled or disabled\n** on a per database connection basis using the\n** [sqlite3_extended_result_codes()] API.\n**\n** Some of the available extended result codes are listed here.\n** One may expect the number of extended result codes will be expand\n** over time.  Software that uses extended result codes should expect\n** to see new result codes in future releases of SQLite.\n**\n** The SQLITE_OK result code will never be extended.  It will always\n** be exactly zero.\n*/\n#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))\n#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))\n#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))\n#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))\n#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))\n#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))\n#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))\n#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))\n#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))\n#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))\n#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))\n#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))\n#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))\n#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))\n#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))\n#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))\n#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))\n#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))\n#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))\n#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))\n#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))\n#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))\n#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))\n#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))\n#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))\n#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))\n#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))\n#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))\n#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))\n#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))\n\n/*\n** CAPI3REF: Flags For File Open Operations\n**\n** These bit values are intended for use in the\n** 3rd parameter to the [sqlite3_open_v2()] interface and\n** in the 4th parameter to the [sqlite3_vfs.xOpen] method.\n*/\n#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */\n#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */\n#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */\n#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */\n#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */\n#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */\n#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */\n#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */\n#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */\n#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */\n#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */\n\n/* Reserved:                         0x00F00000 */\n\n/*\n** CAPI3REF: Device Characteristics\n**\n** The xDeviceCharacteristics method of the [sqlite3_io_methods]\n** object returns an integer which is a vector of these\n** bit values expressing I/O characteristics of the mass storage\n** device that holds the file that the [sqlite3_io_methods]\n** refers to.\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that\n** after reboot following a crash or power loss, the only bytes in a\n** file that were written at the application level might have changed\n** and that adjacent bytes, even bytes within the same sector are\n** guaranteed to be unchanged.\n*/\n#define SQLITE_IOCAP_ATOMIC                 0x00000001\n#define SQLITE_IOCAP_ATOMIC512              0x00000002\n#define SQLITE_IOCAP_ATOMIC1K               0x00000004\n#define SQLITE_IOCAP_ATOMIC2K               0x00000008\n#define SQLITE_IOCAP_ATOMIC4K               0x00000010\n#define SQLITE_IOCAP_ATOMIC8K               0x00000020\n#define SQLITE_IOCAP_ATOMIC16K              0x00000040\n#define SQLITE_IOCAP_ATOMIC32K              0x00000080\n#define SQLITE_IOCAP_ATOMIC64K              0x00000100\n#define SQLITE_IOCAP_SAFE_APPEND            0x00000200\n#define SQLITE_IOCAP_SEQUENTIAL             0x00000400\n#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800\n#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000\n\n/*\n** CAPI3REF: File Locking Levels\n**\n** SQLite uses one of these integer values as the second\n** argument to calls it makes to the xLock() and xUnlock() methods\n** of an [sqlite3_io_methods] object.\n*/\n#define SQLITE_LOCK_NONE          0\n#define SQLITE_LOCK_SHARED        1\n#define SQLITE_LOCK_RESERVED      2\n#define SQLITE_LOCK_PENDING       3\n#define SQLITE_LOCK_EXCLUSIVE     4\n\n/*\n** CAPI3REF: Synchronization Type Flags\n**\n** When SQLite invokes the xSync() method of an\n** [sqlite3_io_methods] object it uses a combination of\n** these integer values as the second argument.\n**\n** When the SQLITE_SYNC_DATAONLY flag is used, it means that the\n** sync operation only needs to flush data to mass storage.  Inode\n** information need not be flushed. If the lower four bits of the flag\n** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.\n** If the lower four bits equal SQLITE_SYNC_FULL, that means\n** to use Mac OS X style fullsync instead of fsync().\n**\n** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags\n** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL\n** settings.  The [synchronous pragma] determines when calls to the\n** xSync VFS method occur and applies uniformly across all platforms.\n** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how\n** energetic or rigorous or forceful the sync operations are and\n** only make a difference on Mac OSX for the default SQLite code.\n** (Third-party VFS implementations might also make the distinction\n** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the\n** operating systems natively supported by SQLite, only Mac OSX\n** cares about the difference.)\n*/\n#define SQLITE_SYNC_NORMAL        0x00002\n#define SQLITE_SYNC_FULL          0x00003\n#define SQLITE_SYNC_DATAONLY      0x00010\n\n/*\n** CAPI3REF: OS Interface Open File Handle\n**\n** An [sqlite3_file] object represents an open file in the \n** [sqlite3_vfs | OS interface layer].  Individual OS interface\n** implementations will\n** want to subclass this object by appending additional fields\n** for their own use.  The pMethods entry is a pointer to an\n** [sqlite3_io_methods] object that defines methods for performing\n** I/O operations on the open file.\n*/\ntypedef struct sqlite3_file sqlite3_file;\nstruct sqlite3_file {\n  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */\n};\n\n/*\n** CAPI3REF: OS Interface File Virtual Methods Object\n**\n** Every file opened by the [sqlite3_vfs.xOpen] method populates an\n** [sqlite3_file] object (or, more commonly, a subclass of the\n** [sqlite3_file] object) with a pointer to an instance of this object.\n** This object defines the methods used to perform various operations\n** against the open file represented by the [sqlite3_file] object.\n**\n** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element \n** to a non-NULL pointer, then the sqlite3_io_methods.xClose method\n** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The\n** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]\n** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element\n** to NULL.\n**\n** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or\n** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().\n** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]\n** flag may be ORed in to indicate that only the data of the file\n** and not its inode needs to be synced.\n**\n** The integer values to xLock() and xUnlock() are one of\n** <ul>\n** <li> [SQLITE_LOCK_NONE],\n** <li> [SQLITE_LOCK_SHARED],\n** <li> [SQLITE_LOCK_RESERVED],\n** <li> [SQLITE_LOCK_PENDING], or\n** <li> [SQLITE_LOCK_EXCLUSIVE].\n** </ul>\n** xLock() increases the lock. xUnlock() decreases the lock.\n** The xCheckReservedLock() method checks whether any database connection,\n** either in this process or in some other process, is holding a RESERVED,\n** PENDING, or EXCLUSIVE lock on the file.  It returns true\n** if such a lock exists and false otherwise.\n**\n** The xFileControl() method is a generic interface that allows custom\n** VFS implementations to directly control an open file using the\n** [sqlite3_file_control()] interface.  The second \"op\" argument is an\n** integer opcode.  The third argument is a generic pointer intended to\n** point to a structure that may contain arguments or space in which to\n** write return values.  Potential uses for xFileControl() might be\n** functions to enable blocking locks with timeouts, to change the\n** locking strategy (for example to use dot-file locks), to inquire\n** about the status of a lock, or to break stale locks.  The SQLite\n** core reserves all opcodes less than 100 for its own use.\n** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.\n** Applications that define a custom xFileControl method should use opcodes\n** greater than 100 to avoid conflicts.  VFS implementations should\n** return [SQLITE_NOTFOUND] for file control opcodes that they do not\n** recognize.\n**\n** The xSectorSize() method returns the sector size of the\n** device that underlies the file.  The sector size is the\n** minimum write that can be performed without disturbing\n** other bytes in the file.  The xDeviceCharacteristics()\n** method returns a bit vector describing behaviors of the\n** underlying device:\n**\n** <ul>\n** <li> [SQLITE_IOCAP_ATOMIC]\n** <li> [SQLITE_IOCAP_ATOMIC512]\n** <li> [SQLITE_IOCAP_ATOMIC1K]\n** <li> [SQLITE_IOCAP_ATOMIC2K]\n** <li> [SQLITE_IOCAP_ATOMIC4K]\n** <li> [SQLITE_IOCAP_ATOMIC8K]\n** <li> [SQLITE_IOCAP_ATOMIC16K]\n** <li> [SQLITE_IOCAP_ATOMIC32K]\n** <li> [SQLITE_IOCAP_ATOMIC64K]\n** <li> [SQLITE_IOCAP_SAFE_APPEND]\n** <li> [SQLITE_IOCAP_SEQUENTIAL]\n** </ul>\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().\n**\n** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill\n** in the unread portions of the buffer with zeros.  A VFS that\n** fails to zero-fill short reads might seem to work.  However,\n** failure to zero-fill short reads will eventually lead to\n** database corruption.\n*/\ntypedef struct sqlite3_io_methods sqlite3_io_methods;\nstruct sqlite3_io_methods {\n  int iVersion;\n  int (*xClose)(sqlite3_file*);\n  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);\n  int (*xSync)(sqlite3_file*, int flags);\n  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);\n  int (*xLock)(sqlite3_file*, int);\n  int (*xUnlock)(sqlite3_file*, int);\n  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);\n  int (*xFileControl)(sqlite3_file*, int op, void *pArg);\n  int (*xSectorSize)(sqlite3_file*);\n  int (*xDeviceCharacteristics)(sqlite3_file*);\n  /* Methods above are valid for version 1 */\n  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\n  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);\n  void (*xShmBarrier)(sqlite3_file*);\n  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);\n  /* Methods above are valid for version 2 */\n  /* Additional methods may be added in future releases */\n};\n\n/*\n** CAPI3REF: Standard File Control Opcodes\n**\n** These integer constants are opcodes for the xFileControl method\n** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]\n** interface.\n**\n** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to write the current state of\n** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],\n** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])\n** into an integer that the pArg argument points to. This capability\n** is used during testing and only needs to be supported when SQLITE_TEST\n** is defined.\n** <ul>\n** <li>[[SQLITE_FCNTL_SIZE_HINT]]\n** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS\n** layer a hint of how large the database file will grow to be during the\n** current transaction.  This hint is not guaranteed to be accurate but it\n** is often close.  The underlying VFS might choose to preallocate database\n** file space based on this hint in order to help writes to the database\n** file run faster.\n**\n** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]\n** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS\n** extends and truncates the database file in chunks of a size specified\n** by the user. The fourth argument to [sqlite3_file_control()] should \n** point to an integer (type int) containing the new chunk-size to use\n** for the nominated database. Allocating database file space in large\n** chunks (say 1MB at a time), may reduce file-system fragmentation and\n** improve performance on some systems.\n**\n** <li>[[SQLITE_FCNTL_FILE_POINTER]]\n** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with a particular database\n** connection.  See the [sqlite3_file_control()] documentation for\n** additional information.\n**\n** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]\n** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by\n** SQLite and sent to all VFSes in place of a call to the xSync method\n** when the database connection has [PRAGMA synchronous] set to OFF.)^\n** Some specialized VFSes need this signal in order to operate correctly\n** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most \n** VFSes do not need this signal and should silently ignore this opcode.\n** Applications should not call [sqlite3_file_control()] with this\n** opcode as doing so may disrupt the operation of the specialized VFSes\n** that do require it.  \n**\n** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]\n** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic\n** retry counts and intervals for certain disk I/O operations for the\n** windows [VFS] in order to provide robustness in the presence of\n** anti-virus programs.  By default, the windows VFS will retry file read,\n** file write, and file delete operations up to 10 times, with a delay\n** of 25 milliseconds before the first retry and with the delay increasing\n** by an additional 25 milliseconds with each subsequent retry.  This\n** opcode allows these two values (10 retries and 25 milliseconds of delay)\n** to be adjusted.  The values are changed for all database connections\n** within the same process.  The argument is a pointer to an array of two\n** integers where the first integer i the new retry count and the second\n** integer is the delay.  If either integer is negative, then the setting\n** is not changed but instead the prior value of that setting is written\n** into the array entry, allowing the current retry settings to be\n** interrogated.  The zDbName parameter is ignored.\n**\n** <li>[[SQLITE_FCNTL_PERSIST_WAL]]\n** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the\n** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary\n** write ahead log and shared memory files used for transaction control\n** are automatically deleted when the latest connection to the database\n** closes.  Setting persistent WAL mode causes those files to persist after\n** close.  Persisting the files is useful when other processes that do not\n** have write permission on the directory containing the database file want\n** to read the database file, as the WAL and shared memory files must exist\n** in order for the database to be readable.  The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable persistent WAL mode or 1 to enable persistent\n** WAL mode.  If the integer is -1, then it is overwritten with the current\n** WAL persistence setting.\n**\n** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]\n** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the\n** persistent \"powersafe-overwrite\" or \"PSOW\" setting.  The PSOW setting\n** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the\n** xDeviceCharacteristics methods. The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage\n** mode.  If the integer is -1, then it is overwritten with the current\n** zero-damage mode setting.\n**\n** <li>[[SQLITE_FCNTL_OVERWRITE]]\n** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening\n** a write transaction to indicate that, unless it is rolled back for some\n** reason, the entire database file will be overwritten by the current \n** transaction. This is used by VACUUM operations.\n**\n** <li>[[SQLITE_FCNTL_VFSNAME]]\n** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of\n** all [VFSes] in the VFS stack.  The names are of all VFS shims and the\n** final bottom-level VFS are written into memory obtained from \n** [sqlite3_malloc()] and the result is stored in the char* variable\n** that the fourth parameter of [sqlite3_file_control()] points to.\n** The caller is responsible for freeing the memory when done.  As with\n** all file-control actions, there is no guarantee that this will actually\n** do anything.  Callers should initialize the char* variable to a NULL\n** pointer in case this file-control is not implemented.  This file-control\n** is intended for diagnostic use only.\n**\n** <li>[[SQLITE_FCNTL_PRAGMA]]\n** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] \n** file control is sent to the open [sqlite3_file] object corresponding\n** to the database file to which the pragma statement refers. ^The argument\n** to the [SQLITE_FCNTL_PRAGMA] file control is an array of\n** pointers to strings (char**) in which the second element of the array\n** is the name of the pragma and the third element is the argument to the\n** pragma or NULL if the pragma has no argument.  ^The handler for an\n** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element\n** of the char** argument point to a string obtained from [sqlite3_mprintf()]\n** or the equivalent and that string will become the result of the pragma or\n** the error message if the pragma fails. ^If the\n** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal \n** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]\n** file control returns [SQLITE_OK], then the parser assumes that the\n** VFS has handled the PRAGMA itself and the parser generates a no-op\n** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns\n** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means\n** that the VFS encountered an error while handling the [PRAGMA] and the\n** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]\n** file control occurs at the beginning of pragma statement analysis and so\n** it is able to override built-in [PRAGMA] statements.\n** </ul>\n*/\n#define SQLITE_FCNTL_LOCKSTATE               1\n#define SQLITE_GET_LOCKPROXYFILE             2\n#define SQLITE_SET_LOCKPROXYFILE             3\n#define SQLITE_LAST_ERRNO                    4\n#define SQLITE_FCNTL_SIZE_HINT               5\n#define SQLITE_FCNTL_CHUNK_SIZE              6\n#define SQLITE_FCNTL_FILE_POINTER            7\n#define SQLITE_FCNTL_SYNC_OMITTED            8\n#define SQLITE_FCNTL_WIN32_AV_RETRY          9\n#define SQLITE_FCNTL_PERSIST_WAL            10\n#define SQLITE_FCNTL_OVERWRITE              11\n#define SQLITE_FCNTL_VFSNAME                12\n#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13\n#define SQLITE_FCNTL_PRAGMA                 14\n\n/*\n** CAPI3REF: Mutex Handle\n**\n** The mutex module within SQLite defines [sqlite3_mutex] to be an\n** abstract type for a mutex object.  The SQLite core never looks\n** at the internal representation of an [sqlite3_mutex].  It only\n** deals with pointers to the [sqlite3_mutex] object.\n**\n** Mutexes are created using [sqlite3_mutex_alloc()].\n*/\ntypedef struct sqlite3_mutex sqlite3_mutex;\n\n/*\n** CAPI3REF: OS Interface Object\n**\n** An instance of the sqlite3_vfs object defines the interface between\n** the SQLite core and the underlying operating system.  The \"vfs\"\n** in the name of the object stands for \"virtual file system\".  See\n** the [VFS | VFS documentation] for further information.\n**\n** The value of the iVersion field is initially 1 but may be larger in\n** future versions of SQLite.  Additional fields may be appended to this\n** object when the iVersion value is increased.  Note that the structure\n** of the sqlite3_vfs object changes in the transaction between\n** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not\n** modified.\n**\n** The szOsFile field is the size of the subclassed [sqlite3_file]\n** structure used by this VFS.  mxPathname is the maximum length of\n** a pathname in this VFS.\n**\n** Registered sqlite3_vfs objects are kept on a linked list formed by\n** the pNext pointer.  The [sqlite3_vfs_register()]\n** and [sqlite3_vfs_unregister()] interfaces manage this list\n** in a thread-safe way.  The [sqlite3_vfs_find()] interface\n** searches the list.  Neither the application code nor the VFS\n** implementation should use the pNext pointer.\n**\n** The pNext field is the only field in the sqlite3_vfs\n** structure that SQLite will ever modify.  SQLite will only access\n** or modify this field while holding a particular static mutex.\n** The application should never modify anything within the sqlite3_vfs\n** object once the object has been registered.\n**\n** The zName field holds the name of the VFS module.  The name must\n** be unique across all VFS modules.\n**\n** [[sqlite3_vfs.xOpen]]\n** ^SQLite guarantees that the zFilename parameter to xOpen\n** is either a NULL pointer or string obtained\n** from xFullPathname() with an optional suffix added.\n** ^If a suffix is added to the zFilename parameter, it will\n** consist of a single \"-\" character followed by no more than\n** 11 alphanumeric and/or \"-\" characters.\n** ^SQLite further guarantees that\n** the string will be valid and unchanged until xClose() is\n** called. Because of the previous sentence,\n** the [sqlite3_file] can safely store a pointer to the\n** filename if it needs to remember the filename for some reason.\n** If the zFilename parameter to xOpen is a NULL pointer then xOpen\n** must invent its own temporary name for the file.  ^Whenever the \n** xFilename parameter is NULL it will also be the case that the\n** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].\n**\n** The flags argument to xOpen() includes all bits set in\n** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]\n** or [sqlite3_open16()] is used, then flags includes at least\n** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. \n** If xOpen() opens a file read-only then it sets *pOutFlags to\n** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.\n**\n** ^(SQLite will also add one of the following flags to the xOpen()\n** call, depending on the object being opened:\n**\n** <ul>\n** <li>  [SQLITE_OPEN_MAIN_DB]\n** <li>  [SQLITE_OPEN_MAIN_JOURNAL]\n** <li>  [SQLITE_OPEN_TEMP_DB]\n** <li>  [SQLITE_OPEN_TEMP_JOURNAL]\n** <li>  [SQLITE_OPEN_TRANSIENT_DB]\n** <li>  [SQLITE_OPEN_SUBJOURNAL]\n** <li>  [SQLITE_OPEN_MASTER_JOURNAL]\n** <li>  [SQLITE_OPEN_WAL]\n** </ul>)^\n**\n** The file I/O implementation can use the object type flags to\n** change the way it deals with files.  For example, an application\n** that does not care about crash recovery or rollback might make\n** the open of a journal file a no-op.  Writes to this journal would\n** also be no-ops, and any attempt to read the journal would return\n** SQLITE_IOERR.  Or the implementation might recognize that a database\n** file will be doing page-aligned sector reads and writes in a random\n** order and set up its I/O subsystem accordingly.\n**\n** SQLite might also add one of the following flags to the xOpen method:\n**\n** <ul>\n** <li> [SQLITE_OPEN_DELETEONCLOSE]\n** <li> [SQLITE_OPEN_EXCLUSIVE]\n** </ul>\n**\n** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be\n** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]\n** will be set for TEMP databases and their journals, transient\n** databases, and subjournals.\n**\n** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction\n** with the [SQLITE_OPEN_CREATE] flag, which are both directly\n** analogous to the O_EXCL and O_CREAT flags of the POSIX open()\n** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the \n** SQLITE_OPEN_CREATE, is used to indicate that file should always\n** be created, and that it is an error if it already exists.\n** It is <i>not</i> used to indicate the file should be opened \n** for exclusive access.\n**\n** ^At least szOsFile bytes of memory are allocated by SQLite\n** to hold the  [sqlite3_file] structure passed as the third\n** argument to xOpen.  The xOpen method does not have to\n** allocate the structure; it should just fill it in.  Note that\n** the xOpen method must set the sqlite3_file.pMethods to either\n** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do\n** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods\n** element will be valid after xOpen returns regardless of the success\n** or failure of the xOpen call.\n**\n** [[sqlite3_vfs.xAccess]]\n** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]\n** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to\n** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]\n** to test whether a file is at least readable.   The file can be a\n** directory.\n**\n** ^SQLite will always allocate at least mxPathname+1 bytes for the\n** output buffer xFullPathname.  The exact size of the output buffer\n** is also passed as a parameter to both  methods. If the output buffer\n** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is\n** handled as a fatal error by SQLite, vfs implementations should endeavor\n** to prevent this by setting mxPathname to a sufficiently large value.\n**\n** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()\n** interfaces are not strictly a part of the filesystem, but they are\n** included in the VFS structure for completeness.\n** The xRandomness() function attempts to return nBytes bytes\n** of good-quality randomness into zOut.  The return value is\n** the actual number of bytes of randomness obtained.\n** The xSleep() method causes the calling thread to sleep for at\n** least the number of microseconds given.  ^The xCurrentTime()\n** method returns a Julian Day Number for the current date and time as\n** a floating point value.\n** ^The xCurrentTimeInt64() method returns, as an integer, the Julian\n** Day Number multiplied by 86400000 (the number of milliseconds in \n** a 24-hour day).  \n** ^SQLite will use the xCurrentTimeInt64() method to get the current\n** date and time if that method is available (if iVersion is 2 or \n** greater and the function pointer is not NULL) and will fall back\n** to xCurrentTime() if xCurrentTimeInt64() is unavailable.\n**\n** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces\n** are not used by the SQLite core.  These optional interfaces are provided\n** by some VFSes to facilitate testing of the VFS code. By overriding \n** system calls with functions under its control, a test program can\n** simulate faults and error conditions that would otherwise be difficult\n** or impossible to induce.  The set of system calls that can be overridden\n** varies from one VFS to another, and from one version of the same VFS to the\n** next.  Applications that use these interfaces must be prepared for any\n** or all of these interfaces to be NULL or for their behavior to change\n** from one release to the next.  Applications must not attempt to access\n** any of these methods if the iVersion of the VFS is less than 3.\n*/\ntypedef struct sqlite3_vfs sqlite3_vfs;\ntypedef void (*sqlite3_syscall_ptr)(void);\nstruct sqlite3_vfs {\n  int iVersion;            /* Structure version number (currently 3) */\n  int szOsFile;            /* Size of subclassed sqlite3_file */\n  int mxPathname;          /* Maximum file pathname length */\n  sqlite3_vfs *pNext;      /* Next registered VFS */\n  const char *zName;       /* Name of this virtual file system */\n  void *pAppData;          /* Pointer to application-specific data */\n  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,\n               int flags, int *pOutFlags);\n  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);\n  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);\n  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);\n  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);\n  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);\n  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);\n  void (*xDlClose)(sqlite3_vfs*, void*);\n  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);\n  int (*xSleep)(sqlite3_vfs*, int microseconds);\n  int (*xCurrentTime)(sqlite3_vfs*, double*);\n  int (*xGetLastError)(sqlite3_vfs*, int, char *);\n  /*\n  ** The methods above are in version 1 of the sqlite_vfs object\n  ** definition.  Those that follow are added in version 2 or later\n  */\n  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);\n  /*\n  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.\n  ** Those below are for version 3 and greater.\n  */\n  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);\n  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);\n  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);\n  /*\n  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.\n  ** New fields may be appended in figure versions.  The iVersion\n  ** value will increment whenever this happens. \n  */\n};\n\n/*\n** CAPI3REF: Flags for the xAccess VFS method\n**\n** These integer constants can be used as the third parameter to\n** the xAccess method of an [sqlite3_vfs] object.  They determine\n** what kind of permissions the xAccess method is looking for.\n** With SQLITE_ACCESS_EXISTS, the xAccess method\n** simply checks whether the file exists.\n** With SQLITE_ACCESS_READWRITE, the xAccess method\n** checks whether the named directory is both readable and writable\n** (in other words, if files can be added, removed, and renamed within\n** the directory).\n** The SQLITE_ACCESS_READWRITE constant is currently used only by the\n** [temp_store_directory pragma], though this could change in a future\n** release of SQLite.\n** With SQLITE_ACCESS_READ, the xAccess method\n** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is\n** currently unused, though it might be used in a future release of\n** SQLite.\n*/\n#define SQLITE_ACCESS_EXISTS    0\n#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */\n#define SQLITE_ACCESS_READ      2   /* Unused */\n\n/*\n** CAPI3REF: Flags for the xShmLock VFS method\n**\n** These integer constants define the various locking operations\n** allowed by the xShmLock method of [sqlite3_io_methods].  The\n** following are the only legal combinations of flags to the\n** xShmLock method:\n**\n** <ul>\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE\n** </ul>\n**\n** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as\n** was given no the corresponding lock.  \n**\n** The xShmLock method can transition between unlocked and SHARED or\n** between unlocked and EXCLUSIVE.  It cannot transition between SHARED\n** and EXCLUSIVE.\n*/\n#define SQLITE_SHM_UNLOCK       1\n#define SQLITE_SHM_LOCK         2\n#define SQLITE_SHM_SHARED       4\n#define SQLITE_SHM_EXCLUSIVE    8\n\n/*\n** CAPI3REF: Maximum xShmLock index\n**\n** The xShmLock method on [sqlite3_io_methods] may use values\n** between 0 and this upper bound as its \"offset\" argument.\n** The SQLite core will never attempt to acquire or release a\n** lock outside of this range\n*/\n#define SQLITE_SHM_NLOCK        8\n\n\n/*\n** CAPI3REF: Initialize The SQLite Library\n**\n** ^The sqlite3_initialize() routine initializes the\n** SQLite library.  ^The sqlite3_shutdown() routine\n** deallocates any resources that were allocated by sqlite3_initialize().\n** These routines are designed to aid in process initialization and\n** shutdown on embedded systems.  Workstation applications using\n** SQLite normally do not need to invoke either of these routines.\n**\n** A call to sqlite3_initialize() is an \"effective\" call if it is\n** the first time sqlite3_initialize() is invoked during the lifetime of\n** the process, or if it is the first time sqlite3_initialize() is invoked\n** following a call to sqlite3_shutdown().  ^(Only an effective call\n** of sqlite3_initialize() does any initialization.  All other calls\n** are harmless no-ops.)^\n**\n** A call to sqlite3_shutdown() is an \"effective\" call if it is the first\n** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only\n** an effective call to sqlite3_shutdown() does any deinitialization.\n** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^\n**\n** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()\n** is not.  The sqlite3_shutdown() interface must only be called from a\n** single thread.  All open [database connections] must be closed and all\n** other SQLite resources must be deallocated prior to invoking\n** sqlite3_shutdown().\n**\n** Among other things, ^sqlite3_initialize() will invoke\n** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()\n** will invoke sqlite3_os_end().\n**\n** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.\n** ^If for some reason, sqlite3_initialize() is unable to initialize\n** the library (perhaps it is unable to allocate a needed resource such\n** as a mutex) it returns an [error code] other than [SQLITE_OK].\n**\n** ^The sqlite3_initialize() routine is called internally by many other\n** SQLite interfaces so that an application usually does not need to\n** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]\n** calls sqlite3_initialize() so the SQLite library will be automatically\n** initialized when [sqlite3_open()] is called if it has not be initialized\n** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]\n** compile-time option, then the automatic calls to sqlite3_initialize()\n** are omitted and the application must call sqlite3_initialize() directly\n** prior to using any other SQLite interface.  For maximum portability,\n** it is recommended that applications always invoke sqlite3_initialize()\n** directly prior to using any other SQLite interface.  Future releases\n** of SQLite may require this.  In other words, the behavior exhibited\n** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the\n** default behavior in some future release of SQLite.\n**\n** The sqlite3_os_init() routine does operating-system specific\n** initialization of the SQLite library.  The sqlite3_os_end()\n** routine undoes the effect of sqlite3_os_init().  Typical tasks\n** performed by these routines include allocation or deallocation\n** of static resources, initialization of global variables,\n** setting up a default [sqlite3_vfs] module, or setting up\n** a default configuration using [sqlite3_config()].\n**\n** The application should never invoke either sqlite3_os_init()\n** or sqlite3_os_end() directly.  The application should only invoke\n** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()\n** interface is called automatically by sqlite3_initialize() and\n** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate\n** implementations for sqlite3_os_init() and sqlite3_os_end()\n** are built into SQLite when it is compiled for Unix, Windows, or OS/2.\n** When [custom builds | built for other platforms]\n** (using the [SQLITE_OS_OTHER=1] compile-time\n** option) the application must supply a suitable implementation for\n** sqlite3_os_init() and sqlite3_os_end().  An application-supplied\n** implementation of sqlite3_os_init() or sqlite3_os_end()\n** must return [SQLITE_OK] on success and some other [error code] upon\n** failure.\n*/\nSQLITE_API int sqlite3_initialize(void);\nSQLITE_API int sqlite3_shutdown(void);\nSQLITE_API int sqlite3_os_init(void);\nSQLITE_API int sqlite3_os_end(void);\n\n/*\n** CAPI3REF: Configuring The SQLite Library\n**\n** The sqlite3_config() interface is used to make global configuration\n** changes to SQLite in order to tune SQLite to the specific needs of\n** the application.  The default configuration is recommended for most\n** applications and so this routine is usually not necessary.  It is\n** provided to support rare applications with unusual needs.\n**\n** The sqlite3_config() interface is not threadsafe.  The application\n** must insure that no other SQLite interfaces are invoked by other\n** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()\n** may only be invoked prior to library initialization using\n** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].\n** ^If sqlite3_config() is called after [sqlite3_initialize()] and before\n** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.\n** Note, however, that ^sqlite3_config() can be called as part of the\n** implementation of an application-defined [sqlite3_os_init()].\n**\n** The first argument to sqlite3_config() is an integer\n** [configuration option] that determines\n** what property of SQLite is to be configured.  Subsequent arguments\n** vary depending on the [configuration option]\n** in the first argument.\n**\n** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].\n** ^If the option is unknown or SQLite is unable to set the option\n** then this routine returns a non-zero [error code].\n*/\nSQLITE_API int sqlite3_config(int, ...);\n\n/*\n** CAPI3REF: Configure database connections\n**\n** The sqlite3_db_config() interface is used to make configuration\n** changes to a [database connection].  The interface is similar to\n** [sqlite3_config()] except that the changes apply to a single\n** [database connection] (specified in the first argument).\n**\n** The second argument to sqlite3_db_config(D,V,...)  is the\n** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code \n** that indicates what aspect of the [database connection] is being configured.\n** Subsequent arguments vary depending on the configuration verb.\n**\n** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if\n** the call is considered successful.\n*/\nSQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Memory Allocation Routines\n**\n** An instance of this object defines the interface between SQLite\n** and low-level memory allocation routines.\n**\n** This object is used in only one place in the SQLite interface.\n** A pointer to an instance of this object is the argument to\n** [sqlite3_config()] when the configuration option is\n** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  \n** By creating an instance of this object\n** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])\n** during configuration, an application can specify an alternative\n** memory allocation subsystem for SQLite to use for all of its\n** dynamic memory needs.\n**\n** Note that SQLite comes with several [built-in memory allocators]\n** that are perfectly adequate for the overwhelming majority of applications\n** and that this object is only useful to a tiny minority of applications\n** with specialized memory allocation requirements.  This object is\n** also used during testing of SQLite in order to specify an alternative\n** memory allocator that simulates memory out-of-memory conditions in\n** order to verify that SQLite recovers gracefully from such\n** conditions.\n**\n** The xMalloc, xRealloc, and xFree methods must work like the\n** malloc(), realloc() and free() functions from the standard C library.\n** ^SQLite guarantees that the second argument to\n** xRealloc is always a value returned by a prior call to xRoundup.\n**\n** xSize should return the allocated size of a memory allocation\n** previously obtained from xMalloc or xRealloc.  The allocated size\n** is always at least as big as the requested size but may be larger.\n**\n** The xRoundup method returns what would be the allocated size of\n** a memory allocation given a particular requested size.  Most memory\n** allocators round up memory allocations at least to the next multiple\n** of 8.  Some allocators round up to a larger multiple or to a power of 2.\n** Every memory allocation request coming in through [sqlite3_malloc()]\n** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, \n** that causes the corresponding memory allocation to fail.\n**\n** The xInit method initializes the memory allocator.  (For example,\n** it might allocate any require mutexes or initialize internal data\n** structures.  The xShutdown method is invoked (indirectly) by\n** [sqlite3_shutdown()] and should deallocate any resources acquired\n** by xInit.  The pAppData pointer is used as the only parameter to\n** xInit and xShutdown.\n**\n** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes\n** the xInit method, so the xInit method need not be threadsafe.  The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  For all other methods, SQLite\n** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the\n** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which\n** it is by default) and so the methods are automatically serialized.\n** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other\n** methods must be threadsafe or else make their own arrangements for\n** serialization.\n**\n** SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n*/\ntypedef struct sqlite3_mem_methods sqlite3_mem_methods;\nstruct sqlite3_mem_methods {\n  void *(*xMalloc)(int);         /* Memory allocation function */\n  void (*xFree)(void*);          /* Free a prior allocation */\n  void *(*xRealloc)(void*,int);  /* Resize an allocation */\n  int (*xSize)(void*);           /* Return the size of an allocation */\n  int (*xRoundup)(int);          /* Round up request size to allocation size */\n  int (*xInit)(void*);           /* Initialize the memory allocator */\n  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */\n  void *pAppData;                /* Argument to xInit() and xShutdown() */\n};\n\n/*\n** CAPI3REF: Configuration Options\n** KEYWORDS: {configuration option}\n**\n** These constants are the available integer configuration options that\n** can be passed as the first argument to the [sqlite3_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_config()] to make sure that\n** the call worked.  The [sqlite3_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Single-thread.  In other words, it disables\n** all mutexing and puts SQLite into a mode where it can only be used\n** by a single thread.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to change the [threading mode] from its default\n** value of Single-thread and so [sqlite3_config()] will return \n** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD\n** configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Multi-thread.  In other words, it disables\n** mutexing on [database connection] and [prepared statement] objects.\n** The application is responsible for serializing access to\n** [database connections] and [prepared statements].  But other mutexes\n** are enabled so that SQLite will be safe to use in a multi-threaded\n** environment as long as no two threads attempt to use the same\n** [database connection] at the same time.  ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Multi-thread [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>\n**\n** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Serialized. In other words, this option enables\n** all mutexes including the recursive\n** mutexes on [database connection] and [prepared statement] objects.\n** In this mode (which is the default when SQLite is compiled with\n** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access\n** to [database connections] and [prepared statements] so that the\n** application is free to use the same [database connection] or the\n** same [prepared statement] in different threads at the same time.\n** ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Serialized [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_SERIALIZED configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mem_methods] structure.  The argument specifies\n** alternative low-level memory allocation routines to be used in place of\n** the memory allocation routines built into SQLite.)^ ^SQLite makes\n** its own private copy of the content of the [sqlite3_mem_methods] structure\n** before the [sqlite3_config()] call returns.</dd>\n**\n** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]\n** structure is filled with the currently defined memory allocation routines.)^\n** This option can be used to overload the default memory allocation\n** routines with a wrapper that simulations memory allocation failure or\n** tracks memory usage, for example. </dd>\n**\n** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>\n** <dd> ^This option takes single argument of type int, interpreted as a \n** boolean, which enables or disables the collection of memory allocation \n** statistics. ^(When memory allocation statistics are disabled, the \n** following SQLite interfaces become non-operational:\n**   <ul>\n**   <li> [sqlite3_memory_used()]\n**   <li> [sqlite3_memory_highwater()]\n**   <li> [sqlite3_soft_heap_limit64()]\n**   <li> [sqlite3_status()]\n**   </ul>)^\n** ^Memory allocation statistics are enabled by default unless SQLite is\n** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory\n** allocation statistics are disabled by default.\n** </dd>\n**\n** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite can use for\n** scratch memory.  There are three arguments:  A pointer an 8-byte\n** aligned memory buffer from which the scratch allocations will be\n** drawn, the size of each scratch allocation (sz),\n** and the maximum number of scratch allocations (N).  The sz\n** argument must be a multiple of 16.\n** The first argument must be a pointer to an 8-byte aligned buffer\n** of at least sz*N bytes of memory.\n** ^SQLite will use no more than two scratch buffers per thread.  So\n** N should be set to twice the expected maximum number of threads.\n** ^SQLite will never require a scratch buffer that is more than 6\n** times the database page size. ^If SQLite needs needs additional\n** scratch memory beyond what is provided by this configuration option, then \n** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>\n**\n** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite can use for\n** the database page cache with the default page cache implementation.  \n** This configuration should not be used if an application-define page\n** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.\n** There are three arguments to this option: A pointer to 8-byte aligned\n** memory, the size of each page buffer (sz), and the number of pages (N).\n** The sz argument should be the size of the largest database page\n** (a power of two between 512 and 32768) plus a little extra for each\n** page header.  ^The page header size is 20 to 40 bytes depending on\n** the host architecture.  ^It is harmless, apart from the wasted memory,\n** to make sz a little too large.  The first\n** argument should point to an allocation of at least sz*N bytes of memory.\n** ^SQLite will use the memory provided by the first argument to satisfy its\n** memory needs for the first N pages that it adds to cache.  ^If additional\n** page cache memory is needed beyond what is provided by this option, then\n** SQLite goes to [sqlite3_malloc()] for the additional storage space.\n** The pointer in the first argument must\n** be aligned to an 8-byte boundary or subsequent behavior of SQLite\n** will be undefined.</dd>\n**\n** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite will use\n** for all of its dynamic memory allocation needs beyond those provided\n** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].\n** There are three arguments: An 8-byte aligned pointer to the memory,\n** the number of bytes in the memory buffer, and the minimum allocation size.\n** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts\n** to using its default memory allocator (the system malloc() implementation),\n** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the\n** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or\n** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory\n** allocator is engaged to handle all of SQLites memory allocation needs.\n** The first pointer (the memory pointer) must be aligned to an 8-byte\n** boundary or subsequent behavior of SQLite will be undefined.\n** The minimum allocation size is capped at 2**12. Reasonable values\n** for the minimum allocation size are 2**5 through 2**8.</dd>\n**\n** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mutex_methods] structure.  The argument specifies\n** alternative low-level mutex routines to be used in place\n** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the\n** content of the [sqlite3_mutex_methods] structure before the call to\n** [sqlite3_config()] returns. ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mutex_methods] structure.  The\n** [sqlite3_mutex_methods]\n** structure is filled with the currently defined mutex routines.)^\n** This option can be used to overload the default mutex allocation\n** routines with a wrapper used to track mutex usage for performance\n** profiling or testing, for example.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>\n** <dd> ^(This option takes two arguments that determine the default\n** memory allocation for the lookaside memory allocator on each\n** [database connection].  The first argument is the\n** size of each lookaside buffer slot and the second is the number of\n** slots allocated to each database connection.)^  ^(This option sets the\n** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]\n** verb to [sqlite3_db_config()] can be used to change the lookaside\n** configuration on individual connections.)^ </dd>\n**\n** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>\n** <dd> ^(This option takes a single argument which is a pointer to\n** an [sqlite3_pcache_methods2] object.  This object specifies the interface\n** to a custom page cache implementation.)^  ^SQLite makes a copy of the\n** object and uses it for page cache memory allocations.</dd>\n**\n** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** [sqlite3_pcache_methods2] object.  SQLite copies of the current\n** page cache implementation into that object.)^ </dd>\n**\n** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>\n** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a\n** function with a call signature of void(*)(void*,int,const char*), \n** and a pointer to void. ^If the function pointer is not NULL, it is\n** invoked by [sqlite3_log()] to process each logging event.  ^If the\n** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.\n** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is\n** passed through as the first parameter to the application-defined logger\n** function whenever that function is invoked.  ^The second parameter to\n** the logger function is a copy of the first parameter to the corresponding\n** [sqlite3_log()] call and is intended to be a [result code] or an\n** [extended result code].  ^The third parameter passed to the logger is\n** log message after formatting via [sqlite3_snprintf()].\n** The SQLite logging interface is not reentrant; the logger function\n** supplied by the application must not invoke any SQLite interface.\n** In a multi-threaded application, the application-defined logger\n** function must be threadsafe. </dd>\n**\n** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI\n** <dd> This option takes a single argument of type int. If non-zero, then\n** URI handling is globally enabled. If the parameter is zero, then URI handling\n** is globally disabled. If URI handling is globally enabled, all filenames\n** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or\n** specified as part of [ATTACH] commands are interpreted as URIs, regardless\n** of whether or not the [SQLITE_OPEN_URI] flag is set when the database\n** connection is opened. If it is globally disabled, filenames are\n** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the\n** database connection is opened. By default, URI handling is globally\n** disabled. The default value may be changed by compiling with the\n** [SQLITE_USE_URI] symbol defined.\n**\n** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]\n** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE\n** <dd> These options are obsolete and should not be used by new code.\n** They are retained for backwards compatibility but are now no-ops.\n** </dl>\n*/\n#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */\n#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */\n#define SQLITE_CONFIG_SERIALIZED    3  /* nil */\n#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */\n#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */\n#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */\n#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */\n#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */\n#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */\n/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ \n#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */\n#define SQLITE_CONFIG_PCACHE       14  /* no-op */\n#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */\n#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */\n#define SQLITE_CONFIG_URI          17  /* int */\n#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */\n\n/*\n** CAPI3REF: Database Connection Configuration Options\n**\n** These constants are the available integer configuration options that\n** can be passed as the second argument to the [sqlite3_db_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_db_config()] to make sure that\n** the call worked.  ^The [sqlite3_db_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>\n** <dd> ^This option takes three additional arguments that determine the \n** [lookaside memory allocator] configuration for the [database connection].\n** ^The first argument (the third parameter to [sqlite3_db_config()] is a\n** pointer to a memory buffer to use for lookaside memory.\n** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb\n** may be NULL in which case SQLite will allocate the\n** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the\n** size of each lookaside buffer slot.  ^The third argument is the number of\n** slots.  The size of the buffer in the first argument must be greater than\n** or equal to the product of the second and third arguments.  The buffer\n** must be aligned to an 8-byte boundary.  ^If the second argument to\n** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally\n** rounded down to the next smaller multiple of 8.  ^(The lookaside memory\n** configuration for a database connection can only be changed when that\n** connection is not currently using lookaside memory, or in other words\n** when the \"current value\" returned by\n** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.\n** Any attempt to change the lookaside memory configuration when lookaside\n** memory is in use leaves the configuration unchanged and returns \n** [SQLITE_BUSY].)^</dd>\n**\n** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>\n** <dd> ^This option is used to enable or disable the enforcement of\n** [foreign key constraints].  There should be two additional arguments.\n** The first argument is an integer which is 0 to disable FK enforcement,\n** positive to enable FK enforcement or negative to leave FK enforcement\n** unchanged.  The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether FK enforcement is off or on\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the FK enforcement setting is not reported back. </dd>\n**\n** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>\n** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable triggers,\n** positive to enable triggers or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether triggers are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the trigger setting is not reported back. </dd>\n**\n** </dl>\n*/\n#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */\n#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */\n\n\n/*\n** CAPI3REF: Enable Or Disable Extended Result Codes\n**\n** ^The sqlite3_extended_result_codes() routine enables or disables the\n** [extended result codes] feature of SQLite. ^The extended result\n** codes are disabled by default for historical compatibility.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);\n\n/*\n** CAPI3REF: Last Insert Rowid\n**\n** ^Each entry in an SQLite table has a unique 64-bit signed\n** integer key called the [ROWID | \"rowid\"]. ^The rowid is always available\n** as an undeclared column named ROWID, OID, or _ROWID_ as long as those\n** names are not also used by explicitly declared columns. ^If\n** the table has a column of type [INTEGER PRIMARY KEY] then that column\n** is another alias for the rowid.\n**\n** ^This routine returns the [rowid] of the most recent\n** successful [INSERT] into the database from the [database connection]\n** in the first argument.  ^As of SQLite version 3.7.7, this routines\n** records the last insert rowid of both ordinary tables and [virtual tables].\n** ^If no successful [INSERT]s\n** have ever occurred on that database connection, zero is returned.\n**\n** ^(If an [INSERT] occurs within a trigger or within a [virtual table]\n** method, then this routine will return the [rowid] of the inserted\n** row as long as the trigger or virtual table method is running.\n** But once the trigger or virtual table method ends, the value returned \n** by this routine reverts to what it was before the trigger or virtual\n** table method began.)^\n**\n** ^An [INSERT] that fails due to a constraint violation is not a\n** successful [INSERT] and does not change the value returned by this\n** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,\n** and INSERT OR ABORT make no changes to the return value of this\n** routine when their insertion fails.  ^(When INSERT OR REPLACE\n** encounters a constraint violation, it does not fail.  The\n** INSERT continues to completion after deleting rows that caused\n** the constraint problem so INSERT OR REPLACE will always change\n** the return value of this interface.)^\n**\n** ^For the purposes of this routine, an [INSERT] is considered to\n** be successful even if it is subsequently rolled back.\n**\n** This function is accessible to SQL statements via the\n** [last_insert_rowid() SQL function].\n**\n** If a separate thread performs a new [INSERT] on the same\n** database connection while the [sqlite3_last_insert_rowid()]\n** function is running and thus changes the last insert [rowid],\n** then the value returned by [sqlite3_last_insert_rowid()] is\n** unpredictable and might not equal either the old or the new\n** last insert [rowid].\n*/\nSQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);\n\n/*\n** CAPI3REF: Count The Number Of Rows Modified\n**\n** ^This function returns the number of database rows that were changed\n** or inserted or deleted by the most recently completed SQL statement\n** on the [database connection] specified by the first parameter.\n** ^(Only changes that are directly specified by the [INSERT], [UPDATE],\n** or [DELETE] statement are counted.  Auxiliary changes caused by\n** triggers or [foreign key actions] are not counted.)^ Use the\n** [sqlite3_total_changes()] function to find the total number of changes\n** including changes caused by triggers and foreign key actions.\n**\n** ^Changes to a view that are simulated by an [INSTEAD OF trigger]\n** are not counted.  Only real table changes are counted.\n**\n** ^(A \"row change\" is a change to a single row of a single table\n** caused by an INSERT, DELETE, or UPDATE statement.  Rows that\n** are changed as side effects of [REPLACE] constraint resolution,\n** rollback, ABORT processing, [DROP TABLE], or by any other\n** mechanisms do not count as direct row changes.)^\n**\n** A \"trigger context\" is a scope of execution that begins and\n** ends with the script of a [CREATE TRIGGER | trigger]. \n** Most SQL statements are\n** evaluated outside of any trigger.  This is the \"top level\"\n** trigger context.  If a trigger fires from the top level, a\n** new trigger context is entered for the duration of that one\n** trigger.  Subtriggers create subcontexts for their duration.\n**\n** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does\n** not create a new trigger context.\n**\n** ^This function returns the number of direct row changes in the\n** most recent INSERT, UPDATE, or DELETE statement within the same\n** trigger context.\n**\n** ^Thus, when called from the top level, this function returns the\n** number of changes in the most recent INSERT, UPDATE, or DELETE\n** that also occurred at the top level.  ^(Within the body of a trigger,\n** the sqlite3_changes() interface can be called to find the number of\n** changes in the most recently completed INSERT, UPDATE, or DELETE\n** statement within the body of the same trigger.\n** However, the number returned does not include changes\n** caused by subtriggers since those have their own context.)^\n**\n** See also the [sqlite3_total_changes()] interface, the\n** [count_changes pragma], and the [changes() SQL function].\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_changes()] is running then the value returned\n** is unpredictable and not meaningful.\n*/\nSQLITE_API int sqlite3_changes(sqlite3*);\n\n/*\n** CAPI3REF: Total Number Of Rows Modified\n**\n** ^This function returns the number of row changes caused by [INSERT],\n** [UPDATE] or [DELETE] statements since the [database connection] was opened.\n** ^(The count returned by sqlite3_total_changes() includes all changes\n** from all [CREATE TRIGGER | trigger] contexts and changes made by\n** [foreign key actions]. However,\n** the count does not include changes used to implement [REPLACE] constraints,\n** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The\n** count does not include rows of views that fire an [INSTEAD OF trigger],\n** though if the INSTEAD OF trigger makes changes of its own, those changes \n** are counted.)^\n** ^The sqlite3_total_changes() function counts the changes as soon as\n** the statement that makes them is completed (when the statement handle\n** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).\n**\n** See also the [sqlite3_changes()] interface, the\n** [count_changes pragma], and the [total_changes() SQL function].\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_total_changes()] is running then the value\n** returned is unpredictable and not meaningful.\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3*);\n\n/*\n** CAPI3REF: Interrupt A Long-Running Query\n**\n** ^This function causes any pending database operation to abort and\n** return at its earliest opportunity. This routine is typically\n** called in response to a user action such as pressing \"Cancel\"\n** or Ctrl-C where the user wants a long query operation to halt\n** immediately.\n**\n** ^It is safe to call this routine from a thread different from the\n** thread that is currently running the database operation.  But it\n** is not safe to call this routine with a [database connection] that\n** is closed or might close before sqlite3_interrupt() returns.\n**\n** ^If an SQL operation is very nearly finished at the time when\n** sqlite3_interrupt() is called, then it might not have an opportunity\n** to be interrupted and might continue to completion.\n**\n** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].\n** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE\n** that is inside an explicit transaction, then the entire transaction\n** will be rolled back automatically.\n**\n** ^The sqlite3_interrupt(D) call is in effect until all currently running\n** SQL statements on [database connection] D complete.  ^Any new SQL statements\n** that are started after the sqlite3_interrupt() call and before the \n** running statements reaches zero are interrupted as if they had been\n** running prior to the sqlite3_interrupt() call.  ^New SQL statements\n** that are started after the running statement count reaches zero are\n** not effected by the sqlite3_interrupt().\n** ^A call to sqlite3_interrupt(D) that occurs when there are no running\n** SQL statements is a no-op and has no effect on SQL statements\n** that are started after the sqlite3_interrupt() call returns.\n**\n** If the database connection closes while [sqlite3_interrupt()]\n** is running then bad things will likely happen.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3*);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Is Complete\n**\n** These routines are useful during command-line input to determine if the\n** currently entered text seems to form a complete SQL statement or\n** if additional input is needed before sending the text into\n** SQLite for parsing.  ^These routines return 1 if the input string\n** appears to be a complete SQL statement.  ^A statement is judged to be\n** complete if it ends with a semicolon token and is not a prefix of a\n** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within\n** string literals or quoted identifier names or comments are not\n** independent tokens (they are part of the token in which they are\n** embedded) and thus do not count as a statement terminator.  ^Whitespace\n** and comments that follow the final semicolon are ignored.\n**\n** ^These routines return 0 if the statement is incomplete.  ^If a\n** memory allocation fails, then SQLITE_NOMEM is returned.\n**\n** ^These routines do not parse the SQL statements thus\n** will not detect syntactically incorrect SQL.\n**\n** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior \n** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked\n** automatically by sqlite3_complete16().  If that initialization fails,\n** then the return value from sqlite3_complete16() will be non-zero\n** regardless of whether or not the input SQL is complete.)^\n**\n** The input to [sqlite3_complete()] must be a zero-terminated\n** UTF-8 string.\n**\n** The input to [sqlite3_complete16()] must be a zero-terminated\n** UTF-16 string in native byte order.\n*/\nSQLITE_API int sqlite3_complete(const char *sql);\nSQLITE_API int sqlite3_complete16(const void *sql);\n\n/*\n** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors\n**\n** ^This routine sets a callback function that might be invoked whenever\n** an attempt is made to open a database table that another thread\n** or process has locked.\n**\n** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]\n** is returned immediately upon encountering the lock.  ^If the busy callback\n** is not NULL, then the callback might be invoked with two arguments.\n**\n** ^The first argument to the busy handler is a copy of the void* pointer which\n** is the third argument to sqlite3_busy_handler().  ^The second argument to\n** the busy handler callback is the number of times that the busy handler has\n** been invoked for this locking event.  ^If the\n** busy callback returns 0, then no additional attempts are made to\n** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.\n** ^If the callback returns non-zero, then another attempt\n** is made to open the database for reading and the cycle repeats.\n**\n** The presence of a busy handler does not guarantee that it will be invoked\n** when there is lock contention. ^If SQLite determines that invoking the busy\n** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]\n** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.\n** Consider a scenario where one process is holding a read lock that\n** it is trying to promote to a reserved lock and\n** a second process is holding a reserved lock that it is trying\n** to promote to an exclusive lock.  The first process cannot proceed\n** because it is blocked by the second and the second process cannot\n** proceed because it is blocked by the first.  If both processes\n** invoke the busy handlers, neither will make any progress.  Therefore,\n** SQLite returns [SQLITE_BUSY] for the first process, hoping that this\n** will induce the first process to release its read lock and allow\n** the second process to proceed.\n**\n** ^The default busy callback is NULL.\n**\n** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]\n** when SQLite is in the middle of a large transaction where all the\n** changes will not fit into the in-memory cache.  SQLite will\n** already hold a RESERVED lock on the database file, but it needs\n** to promote this lock to EXCLUSIVE so that it can spill cache\n** pages into the database file without harm to concurrent\n** readers.  ^If it is unable to promote the lock, then the in-memory\n** cache will be left in an inconsistent state and so the error\n** code is promoted from the relatively benign [SQLITE_BUSY] to\n** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion\n** forces an automatic rollback of the changes.  See the\n** <a href=\"/cvstrac/wiki?p=CorruptionFollowingBusyError\">\n** CorruptionFollowingBusyError</a> wiki page for a discussion of why\n** this is important.\n**\n** ^(There can only be a single busy handler defined for each\n** [database connection].  Setting a new busy handler clears any\n** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]\n** will also set or clear the busy handler.\n**\n** The busy callback should not take any actions which modify the\n** database connection that invoked the busy handler.  Any such actions\n** result in undefined behavior.\n** \n** A busy handler must not close the database connection\n** or [prepared statement] that invoked the busy handler.\n*/\nSQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);\n\n/*\n** CAPI3REF: Set A Busy Timeout\n**\n** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps\n** for a specified amount of time when a table is locked.  ^The handler\n** will sleep multiple times until at least \"ms\" milliseconds of sleeping\n** have accumulated.  ^After at least \"ms\" milliseconds of sleeping,\n** the handler returns 0 which causes [sqlite3_step()] to return\n** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].\n**\n** ^Calling this routine with an argument less than or equal to zero\n** turns off all busy handlers.\n**\n** ^(There can only be a single busy handler for a particular\n** [database connection] any any given moment.  If another busy handler\n** was defined  (using [sqlite3_busy_handler()]) prior to calling\n** this routine, that other busy handler is cleared.)^\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);\n\n/*\n** CAPI3REF: Convenience Routines For Running Queries\n**\n** This is a legacy interface that is preserved for backwards compatibility.\n** Use of this interface is not recommended.\n**\n** Definition: A <b>result table</b> is memory data structure created by the\n** [sqlite3_get_table()] interface.  A result table records the\n** complete query results from one or more queries.\n**\n** The table conceptually has a number of rows and columns.  But\n** these numbers are not part of the result table itself.  These\n** numbers are obtained separately.  Let N be the number of rows\n** and M be the number of columns.\n**\n** A result table is an array of pointers to zero-terminated UTF-8 strings.\n** There are (N+1)*M elements in the array.  The first M pointers point\n** to zero-terminated strings that  contain the names of the columns.\n** The remaining entries all point to query results.  NULL values result\n** in NULL pointers.  All other values are in their UTF-8 zero-terminated\n** string representation as returned by [sqlite3_column_text()].\n**\n** A result table might consist of one or more memory allocations.\n** It is not safe to pass a result table directly to [sqlite3_free()].\n** A result table should be deallocated using [sqlite3_free_table()].\n**\n** ^(As an example of the result table format, suppose a query result\n** is as follows:\n**\n** <blockquote><pre>\n**        Name        | Age\n**        -----------------------\n**        Alice       | 43\n**        Bob         | 28\n**        Cindy       | 21\n** </pre></blockquote>\n**\n** There are two column (M==2) and three rows (N==3).  Thus the\n** result table has 8 entries.  Suppose the result table is stored\n** in an array names azResult.  Then azResult holds this content:\n**\n** <blockquote><pre>\n**        azResult&#91;0] = \"Name\";\n**        azResult&#91;1] = \"Age\";\n**        azResult&#91;2] = \"Alice\";\n**        azResult&#91;3] = \"43\";\n**        azResult&#91;4] = \"Bob\";\n**        azResult&#91;5] = \"28\";\n**        azResult&#91;6] = \"Cindy\";\n**        azResult&#91;7] = \"21\";\n** </pre></blockquote>)^\n**\n** ^The sqlite3_get_table() function evaluates one or more\n** semicolon-separated SQL statements in the zero-terminated UTF-8\n** string of its 2nd parameter and returns a result table to the\n** pointer given in its 3rd parameter.\n**\n** After the application has finished with the result from sqlite3_get_table(),\n** it must pass the result table pointer to sqlite3_free_table() in order to\n** release the memory that was malloced.  Because of the way the\n** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling\n** function must not try to call [sqlite3_free()] directly.  Only\n** [sqlite3_free_table()] is able to release the memory properly and safely.\n**\n** The sqlite3_get_table() interface is implemented as a wrapper around\n** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access\n** to any internal data structures of SQLite.  It uses only the public\n** interface defined here.  As a consequence, errors that occur in the\n** wrapper layer outside of the internal [sqlite3_exec()] call are not\n** reflected in subsequent calls to [sqlite3_errcode()] or\n** [sqlite3_errmsg()].\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,          /* An open database */\n  const char *zSql,     /* SQL to be evaluated */\n  char ***pazResult,    /* Results of the query */\n  int *pnRow,           /* Number of result rows written here */\n  int *pnColumn,        /* Number of result columns written here */\n  char **pzErrmsg       /* Error msg written here */\n);\nSQLITE_API void sqlite3_free_table(char **result);\n\n/*\n** CAPI3REF: Formatted String Printing Functions\n**\n** These routines are work-alikes of the \"printf()\" family of functions\n** from the standard C library.\n**\n** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their\n** results into memory obtained from [sqlite3_malloc()].\n** The strings returned by these two routines should be\n** released by [sqlite3_free()].  ^Both routines return a\n** NULL pointer if [sqlite3_malloc()] is unable to allocate enough\n** memory to hold the resulting string.\n**\n** ^(The sqlite3_snprintf() routine is similar to \"snprintf()\" from\n** the standard C library.  The result is written into the\n** buffer supplied as the second parameter whose size is given by\n** the first parameter. Note that the order of the\n** first two parameters is reversed from snprintf().)^  This is an\n** historical accident that cannot be fixed without breaking\n** backwards compatibility.  ^(Note also that sqlite3_snprintf()\n** returns a pointer to its buffer instead of the number of\n** characters actually written into the buffer.)^  We admit that\n** the number of characters written would be a more useful return\n** value but we cannot change the implementation of sqlite3_snprintf()\n** now without breaking compatibility.\n**\n** ^As long as the buffer size is greater than zero, sqlite3_snprintf()\n** guarantees that the buffer is always zero-terminated.  ^The first\n** parameter \"n\" is the total size of the buffer, including space for\n** the zero terminator.  So the longest string that can be completely\n** written will be n-1 characters.\n**\n** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().\n**\n** These routines all implement some additional formatting\n** options that are useful for constructing SQL statements.\n** All of the usual printf() formatting options apply.  In addition, there\n** is are \"%q\", \"%Q\", and \"%z\" options.\n**\n** ^(The %q option works like %s in that it substitutes a nul-terminated\n** string from the argument list.  But %q also doubles every '\\'' character.\n** %q is designed for use inside a string literal.)^  By doubling each '\\''\n** character it escapes that character and allows it to be inserted into\n** the string.\n**\n** For example, assume the string variable zText contains text as follows:\n**\n** <blockquote><pre>\n**  char *zText = \"It's a happy day!\";\n** </pre></blockquote>\n**\n** One can use this text in an SQL statement as follows:\n**\n** <blockquote><pre>\n**  char *zSQL = sqlite3_mprintf(\"INSERT INTO table VALUES('%q')\", zText);\n**  sqlite3_exec(db, zSQL, 0, 0, 0);\n**  sqlite3_free(zSQL);\n** </pre></blockquote>\n**\n** Because the %q format string is used, the '\\'' character in zText\n** is escaped and the SQL generated is as follows:\n**\n** <blockquote><pre>\n**  INSERT INTO table1 VALUES('It''s a happy day!')\n** </pre></blockquote>\n**\n** This is correct.  Had we used %s instead of %q, the generated SQL\n** would have looked like this:\n**\n** <blockquote><pre>\n**  INSERT INTO table1 VALUES('It's a happy day!');\n** </pre></blockquote>\n**\n** This second example is an SQL syntax error.  As a general rule you should\n** always use %q instead of %s when inserting text into a string literal.\n**\n** ^(The %Q option works like %q except it also adds single quotes around\n** the outside of the total string.  Additionally, if the parameter in the\n** argument list is a NULL pointer, %Q substitutes the text \"NULL\" (without\n** single quotes).)^  So, for example, one could say:\n**\n** <blockquote><pre>\n**  char *zSQL = sqlite3_mprintf(\"INSERT INTO table VALUES(%Q)\", zText);\n**  sqlite3_exec(db, zSQL, 0, 0, 0);\n**  sqlite3_free(zSQL);\n** </pre></blockquote>\n**\n** The code above will render a correct SQL statement in the zSQL\n** variable even if the zText variable is a NULL pointer.\n**\n** ^(The \"%z\" formatting option works like \"%s\" but with the\n** addition that after the string has been read and copied into\n** the result, [sqlite3_free()] is called on the input string.)^\n*/\nSQLITE_API char *sqlite3_mprintf(const char*,...);\nSQLITE_API char *sqlite3_vmprintf(const char*, va_list);\nSQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);\nSQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);\n\n/*\n** CAPI3REF: Memory Allocation Subsystem\n**\n** The SQLite core uses these three routines for all of its own\n** internal memory allocation needs. \"Core\" in the previous sentence\n** does not include operating-system specific VFS implementation.  The\n** Windows VFS uses native malloc() and free() for some operations.\n**\n** ^The sqlite3_malloc() routine returns a pointer to a block\n** of memory at least N bytes in length, where N is the parameter.\n** ^If sqlite3_malloc() is unable to obtain sufficient free\n** memory, it returns a NULL pointer.  ^If the parameter N to\n** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns\n** a NULL pointer.\n**\n** ^Calling sqlite3_free() with a pointer previously returned\n** by sqlite3_malloc() or sqlite3_realloc() releases that memory so\n** that it might be reused.  ^The sqlite3_free() routine is\n** a no-op if is called with a NULL pointer.  Passing a NULL pointer\n** to sqlite3_free() is harmless.  After being freed, memory\n** should neither be read nor written.  Even reading previously freed\n** memory might result in a segmentation fault or other severe error.\n** Memory corruption, a segmentation fault, or other severe error\n** might result if sqlite3_free() is called with a non-NULL pointer that\n** was not obtained from sqlite3_malloc() or sqlite3_realloc().\n**\n** ^(The sqlite3_realloc() interface attempts to resize a\n** prior memory allocation to be at least N bytes, where N is the\n** second parameter.  The memory allocation to be resized is the first\n** parameter.)^ ^ If the first parameter to sqlite3_realloc()\n** is a NULL pointer then its behavior is identical to calling\n** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().\n** ^If the second parameter to sqlite3_realloc() is zero or\n** negative then the behavior is exactly the same as calling\n** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().\n** ^sqlite3_realloc() returns a pointer to a memory allocation\n** of at least N bytes in size or NULL if sufficient memory is unavailable.\n** ^If M is the size of the prior allocation, then min(N,M) bytes\n** of the prior allocation are copied into the beginning of buffer returned\n** by sqlite3_realloc() and the prior allocation is freed.\n** ^If sqlite3_realloc() returns NULL, then the prior allocation\n** is not freed.\n**\n** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()\n** is always aligned to at least an 8 byte boundary, or to a\n** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time\n** option is used.\n**\n** In SQLite version 3.5.0 and 3.5.1, it was possible to define\n** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in\n** implementation of these routines to be omitted.  That capability\n** is no longer provided.  Only built-in memory allocators can be used.\n**\n** Prior to SQLite version 3.7.10, the Windows OS interface layer called\n** the system malloc() and free() directly when converting\n** filenames between the UTF-8 encoding used by SQLite\n** and whatever filename encoding is used by the particular Windows\n** installation.  Memory allocation errors were detected, but\n** they were reported back as [SQLITE_CANTOPEN] or\n** [SQLITE_IOERR] rather than [SQLITE_NOMEM].\n**\n** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]\n** must be either NULL or else pointers obtained from a prior\n** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have\n** not yet been released.\n**\n** The application must not read or write any part of\n** a block of memory after it has been released using\n** [sqlite3_free()] or [sqlite3_realloc()].\n*/\nSQLITE_API void *sqlite3_malloc(int);\nSQLITE_API void *sqlite3_realloc(void*, int);\nSQLITE_API void sqlite3_free(void*);\n\n/*\n** CAPI3REF: Memory Allocator Statistics\n**\n** SQLite provides these two interfaces for reporting on the status\n** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]\n** routines, which form the built-in memory allocation subsystem.\n**\n** ^The [sqlite3_memory_used()] routine returns the number of bytes\n** of memory currently outstanding (malloced but not freed).\n** ^The [sqlite3_memory_highwater()] routine returns the maximum\n** value of [sqlite3_memory_used()] since the high-water mark\n** was last reset.  ^The values returned by [sqlite3_memory_used()] and\n** [sqlite3_memory_highwater()] include any overhead\n** added by SQLite in its implementation of [sqlite3_malloc()],\n** but not overhead added by the any underlying system library\n** routines that [sqlite3_malloc()] may call.\n**\n** ^The memory high-water mark is reset to the current value of\n** [sqlite3_memory_used()] if and only if the parameter to\n** [sqlite3_memory_highwater()] is true.  ^The value returned\n** by [sqlite3_memory_highwater(1)] is the high-water mark\n** prior to the reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void);\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);\n\n/*\n** CAPI3REF: Pseudo-Random Number Generator\n**\n** SQLite contains a high-quality pseudo-random number generator (PRNG) used to\n** select random [ROWID | ROWIDs] when inserting new records into a table that\n** already uses the largest possible [ROWID].  The PRNG is also used for\n** the build-in random() and randomblob() SQL functions.  This interface allows\n** applications to access the same PRNG for other purposes.\n**\n** ^A call to this routine stores N bytes of randomness into buffer P.\n**\n** ^The first time this routine is invoked (either internally or by\n** the application) the PRNG is seeded using randomness obtained\n** from the xRandomness method of the default [sqlite3_vfs] object.\n** ^On all subsequent invocations, the pseudo-randomness is generated\n** internally and without recourse to the [sqlite3_vfs] xRandomness\n** method.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *P);\n\n/*\n** CAPI3REF: Compile-Time Authorization Callbacks\n**\n** ^This routine registers an authorizer callback with a particular\n** [database connection], supplied in the first argument.\n** ^The authorizer callback is invoked as SQL statements are being compiled\n** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],\n** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various\n** points during the compilation process, as logic is being created\n** to perform various actions, the authorizer callback is invoked to\n** see if those actions are allowed.  ^The authorizer callback should\n** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the\n** specific action but allow the SQL statement to continue to be\n** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be\n** rejected with an error.  ^If the authorizer callback returns\n** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]\n** then the [sqlite3_prepare_v2()] or equivalent call that triggered\n** the authorizer will fail with an error message.\n**\n** When the callback returns [SQLITE_OK], that means the operation\n** requested is ok.  ^When the callback returns [SQLITE_DENY], the\n** [sqlite3_prepare_v2()] or equivalent call that triggered the\n** authorizer will fail with an error message explaining that\n** access is denied. \n**\n** ^The first parameter to the authorizer callback is a copy of the third\n** parameter to the sqlite3_set_authorizer() interface. ^The second parameter\n** to the callback is an integer [SQLITE_COPY | action code] that specifies\n** the particular action to be authorized. ^The third through sixth parameters\n** to the callback are zero-terminated strings that contain additional\n** details about the action to be authorized.\n**\n** ^If the action code is [SQLITE_READ]\n** and the callback returns [SQLITE_IGNORE] then the\n** [prepared statement] statement is constructed to substitute\n** a NULL value in place of the table column that would have\n** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]\n** return can be used to deny an untrusted user access to individual\n** columns of a table.\n** ^If the action code is [SQLITE_DELETE] and the callback returns\n** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the\n** [truncate optimization] is disabled and all rows are deleted individually.\n**\n** An authorizer is used when [sqlite3_prepare | preparing]\n** SQL statements from an untrusted source, to ensure that the SQL statements\n** do not try to access data they are not allowed to see, or that they do not\n** try to execute malicious statements that damage the database.  For\n** example, an application may allow a user to enter arbitrary\n** SQL queries for evaluation by a database.  But the application does\n** not want the user to be able to make arbitrary changes to the\n** database.  An authorizer could then be put in place while the\n** user-entered SQL is being [sqlite3_prepare | prepared] that\n** disallows everything except [SELECT] statements.\n**\n** Applications that need to process SQL from untrusted sources\n** might also consider lowering resource limits using [sqlite3_limit()]\n** and limiting database size using the [max_page_count] [PRAGMA]\n** in addition to using an authorizer.\n**\n** ^(Only a single authorizer can be in place on a database connection\n** at a time.  Each call to sqlite3_set_authorizer overrides the\n** previous call.)^  ^Disable the authorizer by installing a NULL callback.\n** The authorizer is disabled by default.\n**\n** The authorizer callback must not do anything that will modify\n** the database connection that invoked the authorizer callback.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the\n** statement might be re-prepared during [sqlite3_step()] due to a \n** schema change.  Hence, the application should ensure that the\n** correct authorizer callback remains in place during the [sqlite3_step()].\n**\n** ^Note that the authorizer callback is invoked only during\n** [sqlite3_prepare()] or its variants.  Authorization is not\n** performed during statement evaluation in [sqlite3_step()], unless\n** as stated in the previous paragraph, sqlite3_step() invokes\n** sqlite3_prepare_v2() to reprepare a statement after a schema change.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3*,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pUserData\n);\n\n/*\n** CAPI3REF: Authorizer Return Codes\n**\n** The [sqlite3_set_authorizer | authorizer callback function] must\n** return either [SQLITE_OK] or one of these two constants in order\n** to signal SQLite whether or not the action is permitted.  See the\n** [sqlite3_set_authorizer | authorizer documentation] for additional\n** information.\n**\n** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]\n** from the [sqlite3_vtab_on_conflict()] interface.\n*/\n#define SQLITE_DENY   1   /* Abort the SQL statement with an error */\n#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */\n\n/*\n** CAPI3REF: Authorizer Action Codes\n**\n** The [sqlite3_set_authorizer()] interface registers a callback function\n** that is invoked to authorize certain SQL statement actions.  The\n** second parameter to the callback is an integer code that specifies\n** what action is being authorized.  These are the integer action codes that\n** the authorizer callback may be passed.\n**\n** These action code values signify what kind of operation is to be\n** authorized.  The 3rd and 4th parameters to the authorization\n** callback function will be parameters or NULL depending on which of these\n** codes is used as the second parameter.  ^(The 5th parameter to the\n** authorizer callback is the name of the database (\"main\", \"temp\",\n** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback\n** is the name of the inner-most trigger or view that is responsible for\n** the access attempt or NULL if this access attempt is directly from\n** top-level SQL code.\n*/\n/******************************************* 3rd ************ 4th ***********/\n#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */\n#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */\n#define SQLITE_DELETE                9   /* Table Name      NULL            */\n#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */\n#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */\n#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */\n#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */\n#define SQLITE_INSERT               18   /* Table Name      NULL            */\n#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */\n#define SQLITE_READ                 20   /* Table Name      Column Name     */\n#define SQLITE_SELECT               21   /* NULL            NULL            */\n#define SQLITE_TRANSACTION          22   /* Operation       NULL            */\n#define SQLITE_UPDATE               23   /* Table Name      Column Name     */\n#define SQLITE_ATTACH               24   /* Filename        NULL            */\n#define SQLITE_DETACH               25   /* Database Name   NULL            */\n#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */\n#define SQLITE_REINDEX              27   /* Index Name      NULL            */\n#define SQLITE_ANALYZE              28   /* Table Name      NULL            */\n#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */\n#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */\n#define SQLITE_FUNCTION             31   /* NULL            Function Name   */\n#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */\n#define SQLITE_COPY                  0   /* No longer used */\n\n/*\n** CAPI3REF: Tracing And Profiling Functions\n**\n** These routines register callback functions that can be used for\n** tracing and profiling the execution of SQL statements.\n**\n** ^The callback function registered by sqlite3_trace() is invoked at\n** various times when an SQL statement is being run by [sqlite3_step()].\n** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the\n** SQL statement text as the statement first begins executing.\n** ^(Additional sqlite3_trace() callbacks might occur\n** as each triggered subprogram is entered.  The callbacks for triggers\n** contain a UTF-8 SQL comment that identifies the trigger.)^\n**\n** ^The callback function registered by sqlite3_profile() is invoked\n** as each SQL statement finishes.  ^The profile callback contains\n** the original statement text and an estimate of wall-clock time\n** of how long that statement took to run.  ^The profile callback\n** time is in units of nanoseconds, however the current implementation\n** is only capable of millisecond resolution so the six least significant\n** digits in the time are meaningless.  Future versions of SQLite\n** might provide greater resolution on the profiler callback.  The\n** sqlite3_profile() function is considered experimental and is\n** subject to change in future versions of SQLite.\n*/\nSQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);\nSQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,\n   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);\n\n/*\n** CAPI3REF: Query Progress Callbacks\n**\n** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback\n** function X to be invoked periodically during long running calls to\n** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for\n** database connection D.  An example use for this\n** interface is to keep a GUI updated during a large query.\n**\n** ^The parameter P is passed through as the only parameter to the \n** callback function X.  ^The parameter N is the number of \n** [virtual machine instructions] that are evaluated between successive\n** invocations of the callback X.\n**\n** ^Only a single progress handler may be defined at one time per\n** [database connection]; setting a new progress handler cancels the\n** old one.  ^Setting parameter X to NULL disables the progress handler.\n** ^The progress handler is also disabled by setting N to a value less\n** than 1.\n**\n** ^If the progress callback returns non-zero, the operation is\n** interrupted.  This feature can be used to implement a\n** \"Cancel\" button on a GUI progress dialog box.\n**\n** The progress handler callback must not do anything that will modify\n** the database connection that invoked the progress handler.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n*/\nSQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);\n\n/*\n** CAPI3REF: Opening A New Database Connection\n**\n** ^These routines open an SQLite database file as specified by the \n** filename argument. ^The filename argument is interpreted as UTF-8 for\n** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte\n** order for sqlite3_open16(). ^(A [database connection] handle is usually\n** returned in *ppDb, even if an error occurs.  The only exception is that\n** if SQLite is unable to allocate memory to hold the [sqlite3] object,\n** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]\n** object.)^ ^(If the database is opened (and/or created) successfully, then\n** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The\n** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain\n** an English language description of the error following a failure of any\n** of the sqlite3_open() routines.\n**\n** ^The default encoding for the database will be UTF-8 if\n** sqlite3_open() or sqlite3_open_v2() is called and\n** UTF-16 in the native byte order if sqlite3_open16() is used.\n**\n** Whether or not an error occurs when it is opened, resources\n** associated with the [database connection] handle should be released by\n** passing it to [sqlite3_close()] when it is no longer required.\n**\n** The sqlite3_open_v2() interface works like sqlite3_open()\n** except that it accepts two additional parameters for additional control\n** over the new database connection.  ^(The flags parameter to\n** sqlite3_open_v2() can take one of\n** the following three values, optionally combined with the \n** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],\n** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_READONLY]</dt>\n** <dd>The database is opened in read-only mode.  If the database does not\n** already exist, an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>\n** <dd>The database is opened for reading and writing if possible, or reading\n** only if the file is write protected by the operating system.  In either\n** case the database must already exist, otherwise an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>\n** <dd>The database is opened for reading and writing, and is created if\n** it does not already exist. This is the behavior that is always used for\n** sqlite3_open() and sqlite3_open16().</dd>)^\n** </dl>\n**\n** If the 3rd parameter to sqlite3_open_v2() is not one of the\n** combinations shown above optionally combined with other\n** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]\n** then the behavior is undefined.\n**\n** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection\n** opens in the multi-thread [threading mode] as long as the single-thread\n** mode has not been set at compile-time or start-time.  ^If the\n** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens\n** in the serialized [threading mode] unless single-thread was\n** previously selected at compile-time or start-time.\n** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be\n** eligible to use [shared cache mode], regardless of whether or not shared\n** cache is enabled using [sqlite3_enable_shared_cache()].  ^The\n** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not\n** participate in [shared cache mode] even if it is enabled.\n**\n** ^The fourth parameter to sqlite3_open_v2() is the name of the\n** [sqlite3_vfs] object that defines the operating system interface that\n** the new database connection should use.  ^If the fourth parameter is\n** a NULL pointer then the default [sqlite3_vfs] object is used.\n**\n** ^If the filename is \":memory:\", then a private, temporary in-memory database\n** is created for the connection.  ^This in-memory database will vanish when\n** the database connection is closed.  Future versions of SQLite might\n** make use of additional special filenames that begin with the \":\" character.\n** It is recommended that when a database filename actually does begin with\n** a \":\" character you should prefix the filename with a pathname such as\n** \"./\" to avoid ambiguity.\n**\n** ^If the filename is an empty string, then a private, temporary\n** on-disk database will be created.  ^This private database will be\n** automatically deleted as soon as the database connection is closed.\n**\n** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>\n**\n** ^If [URI filename] interpretation is enabled, and the filename argument\n** begins with \"file:\", then the filename is interpreted as a URI. ^URI\n** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is\n** set in the fourth argument to sqlite3_open_v2(), or if it has\n** been enabled globally using the [SQLITE_CONFIG_URI] option with the\n** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.\n** As of SQLite version 3.7.7, URI filename interpretation is turned off\n** by default, but future releases of SQLite might enable URI filename\n** interpretation by default.  See \"[URI filenames]\" for additional\n** information.\n**\n** URI filenames are parsed according to RFC 3986. ^If the URI contains an\n** authority, then it must be either an empty string or the string \n** \"localhost\". ^If the authority is not an empty string or \"localhost\", an \n** error is returned to the caller. ^The fragment component of a URI, if \n** present, is ignored.\n**\n** ^SQLite uses the path component of the URI as the name of the disk file\n** which contains the database. ^If the path begins with a '/' character, \n** then it is interpreted as an absolute path. ^If the path does not begin \n** with a '/' (meaning that the authority section is omitted from the URI)\n** then the path is interpreted as a relative path. \n** ^On windows, the first component of an absolute path \n** is a drive specification (e.g. \"C:\").\n**\n** [[core URI query parameters]]\n** The query component of a URI may contain parameters that are interpreted\n** either by SQLite itself, or by a [VFS | custom VFS implementation].\n** SQLite interprets the following three query parameters:\n**\n** <ul>\n**   <li> <b>vfs</b>: ^The \"vfs\" parameter may be used to specify the name of\n**     a VFS object that provides the operating system interface that should\n**     be used to access the database file on disk. ^If this option is set to\n**     an empty string the default VFS object is used. ^Specifying an unknown\n**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is\n**     present, then the VFS specified by the option takes precedence over\n**     the value passed as the fourth parameter to sqlite3_open_v2().\n**\n**   <li> <b>mode</b>: ^(The mode parameter may be set to either \"ro\", \"rw\",\n**     \"rwc\", or \"memory\". Attempting to set it to any other value is\n**     an error)^. \n**     ^If \"ro\" is specified, then the database is opened for read-only \n**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the \n**     third argument to sqlite3_prepare_v2(). ^If the mode option is set to \n**     \"rw\", then the database is opened for read-write (but not create) \n**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had \n**     been set. ^Value \"rwc\" is equivalent to setting both \n**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is\n**     set to \"memory\" then a pure [in-memory database] that never reads\n**     or writes from disk is used. ^It is an error to specify a value for\n**     the mode parameter that is less restrictive than that specified by\n**     the flags passed in the third parameter to sqlite3_open_v2().\n**\n**   <li> <b>cache</b>: ^The cache parameter may be set to either \"shared\" or\n**     \"private\". ^Setting it to \"shared\" is equivalent to setting the\n**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to\n**     sqlite3_open_v2(). ^Setting the cache parameter to \"private\" is \n**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.\n**     ^If sqlite3_open_v2() is used and the \"cache\" parameter is present in\n**     a URI filename, its value overrides any behaviour requested by setting\n**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.\n** </ul>\n**\n** ^Specifying an unknown parameter in the query component of a URI is not an\n** error.  Future versions of SQLite might understand additional query\n** parameters.  See \"[query parameters with special meaning to SQLite]\" for\n** additional information.\n**\n** [[URI filename examples]] <h3>URI filename examples</h3>\n**\n** <table border=\"1\" align=center cellpadding=5>\n** <tr><th> URI filenames <th> Results\n** <tr><td> file:data.db <td> \n**          Open the file \"data.db\" in the current directory.\n** <tr><td> file:/home/fred/data.db<br>\n**          file:///home/fred/data.db <br> \n**          file://localhost/home/fred/data.db <br> <td> \n**          Open the database file \"/home/fred/data.db\".\n** <tr><td> file://darkstar/home/fred/data.db <td> \n**          An error. \"darkstar\" is not a recognized authority.\n** <tr><td style=\"white-space:nowrap\"> \n**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db\n**     <td> Windows only: Open the file \"data.db\" on fred's desktop on drive\n**          C:. Note that the %20 escaping in this example is not strictly \n**          necessary - space characters can be used literally\n**          in URI filenames.\n** <tr><td> file:data.db?mode=ro&cache=private <td> \n**          Open file \"data.db\" in the current directory for read-only access.\n**          Regardless of whether or not shared-cache mode is enabled by\n**          default, use a private cache.\n** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>\n**          Open file \"/home/fred/data.db\". Use the special VFS \"unix-nolock\".\n** <tr><td> file:data.db?mode=readonly <td> \n**          An error. \"readonly\" is not a valid option for the \"mode\" parameter.\n** </table>\n**\n** ^URI hexadecimal escape sequences (%HH) are supported within the path and\n** query components of a URI. A hexadecimal escape sequence consists of a\n** percent sign - \"%\" - followed by exactly two hexadecimal digits \n** specifying an octet value. ^Before the path or query components of a\n** URI filename are interpreted, they are encoded using UTF-8 and all \n** hexadecimal escape sequences replaced by a single byte containing the\n** corresponding octet. If this process generates an invalid UTF-8 encoding,\n** the results are undefined.\n**\n** <b>Note to Windows users:</b>  The encoding used for the filename argument\n** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever\n** codepage is currently defined.  Filenames containing international\n** characters must be converted to UTF-8 prior to passing them into\n** sqlite3_open() or sqlite3_open_v2().\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various\n** features that require the use of temporary files may fail.\n**\n** See also: [sqlite3_temp_directory]\n*/\nSQLITE_API int sqlite3_open(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open16(\n  const void *filename,   /* Database filename (UTF-16) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n);\n\n/*\n** CAPI3REF: Obtain Values For URI Parameters\n**\n** These are utility routines, useful to VFS implementations, that check\n** to see if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of that query parameter.\n**\n** If F is the database filename pointer passed into the xOpen() method of \n** a VFS implementation when the flags parameter to xOpen() has one or \n** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and\n** P is the name of the query parameter, then\n** sqlite3_uri_parameter(F,P) returns the value of the P\n** parameter if it exists or a NULL pointer if P does not appear as a \n** query parameter on F.  If P is a query parameter of F\n** has no explicit value, then sqlite3_uri_parameter(F,P) returns\n** a pointer to an empty string.\n**\n** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean\n** parameter and returns true (1) or false (0) according to the value\n** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the\n** value of query parameter P is one of \"yes\", \"true\", or \"on\" in any\n** case or if the value begins with a non-zero number.  The \n** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of\n** query parameter P is one of \"no\", \"false\", or \"off\" in any case or\n** if the value begins with a numeric zero.  If P is not a query\n** parameter on F or if the value of P is does not match any of the\n** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).\n**\n** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a\n** 64-bit signed integer and returns that integer, or D if P does not\n** exist.  If the value of P is something other than an integer, then\n** zero is returned.\n** \n** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and\n** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and\n** is not a database file pathname pointer that SQLite passed into the xOpen\n** VFS method, then the behavior of this routine is undefined and probably\n** undesirable.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);\nSQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);\n\n\n/*\n** CAPI3REF: Error Codes And Messages\n**\n** ^The sqlite3_errcode() interface returns the numeric [result code] or\n** [extended result code] for the most recent failed sqlite3_* API call\n** associated with a [database connection]. If a prior API call failed\n** but the most recent API call succeeded, the return value from\n** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()\n** interface is the same except that it always returns the \n** [extended result code] even when extended result codes are\n** disabled.\n**\n** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language\n** text that describes the error, as either UTF-8 or UTF-16 respectively.\n** ^(Memory to hold the error message string is managed internally.\n** The application does not need to worry about freeing the result.\n** However, the error string might be overwritten or deallocated by\n** subsequent calls to other SQLite interface functions.)^\n**\n** When the serialized [threading mode] is in use, it might be the\n** case that a second error occurs on a separate thread in between\n** the time of the first error and the call to these interfaces.\n** When that happens, the second error will be reported since these\n** interfaces always report the most recent result.  To avoid\n** this, each thread can obtain exclusive use of the [database connection] D\n** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning\n** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after\n** all calls to the interfaces listed here are completed.\n**\n** If an interface fails with SQLITE_MISUSE, that means the interface\n** was invoked incorrectly by the application.  In that case, the\n** error code and message may or may not be set.\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db);\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db);\nSQLITE_API const char *sqlite3_errmsg(sqlite3*);\nSQLITE_API const void *sqlite3_errmsg16(sqlite3*);\n\n/*\n** CAPI3REF: SQL Statement Object\n** KEYWORDS: {prepared statement} {prepared statements}\n**\n** An instance of this object represents a single SQL statement.\n** This object is variously known as a \"prepared statement\" or a\n** \"compiled SQL statement\" or simply as a \"statement\".\n**\n** The life of a statement object goes something like this:\n**\n** <ol>\n** <li> Create the object using [sqlite3_prepare_v2()] or a related\n**      function.\n** <li> Bind values to [host parameters] using the sqlite3_bind_*()\n**      interfaces.\n** <li> Run the SQL by calling [sqlite3_step()] one or more times.\n** <li> Reset the statement using [sqlite3_reset()] then go back\n**      to step 2.  Do this zero or more times.\n** <li> Destroy the object using [sqlite3_finalize()].\n** </ol>\n**\n** Refer to documentation on individual methods above for additional\n** information.\n*/\ntypedef struct sqlite3_stmt sqlite3_stmt;\n\n/*\n** CAPI3REF: Run-time Limits\n**\n** ^(This interface allows the size of various constructs to be limited\n** on a connection by connection basis.  The first parameter is the\n** [database connection] whose limit is to be set or queried.  The\n** second parameter is one of the [limit categories] that define a\n** class of constructs to be size limited.  The third parameter is the\n** new limit for that construct.)^\n**\n** ^If the new limit is a negative number, the limit is unchanged.\n** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a \n** [limits | hard upper bound]\n** set at compile-time by a C preprocessor macro called\n** [limits | SQLITE_MAX_<i>NAME</i>].\n** (The \"_LIMIT_\" in the name is changed to \"_MAX_\".))^\n** ^Attempts to increase a limit above its hard upper bound are\n** silently truncated to the hard upper bound.\n**\n** ^Regardless of whether or not the limit was changed, the \n** [sqlite3_limit()] interface returns the prior value of the limit.\n** ^Hence, to find the current value of a limit without changing it,\n** simply invoke this interface with the third parameter set to -1.\n**\n** Run-time limits are intended for use in applications that manage\n** both their own internal database and also databases that are controlled\n** by untrusted external sources.  An example application might be a\n** web browser that has its own databases for storing history and\n** separate databases controlled by JavaScript applications downloaded\n** off the Internet.  The internal databases can be given the\n** large, default limits.  Databases managed by external sources can\n** be given much smaller limits designed to prevent a denial of service\n** attack.  Developers might also want to use the [sqlite3_set_authorizer()]\n** interface to further control untrusted SQL.  The size of the database\n** created by an untrusted script can be contained using the\n** [max_page_count] [PRAGMA].\n**\n** New run-time limit categories may be added in future releases.\n*/\nSQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);\n\n/*\n** CAPI3REF: Run-Time Limit Categories\n** KEYWORDS: {limit category} {*limit categories}\n**\n** These constants define various performance limits\n** that can be lowered at run-time using [sqlite3_limit()].\n** The synopsis of the meanings of the various limits is shown below.\n** Additional information is available at [limits | Limits in SQLite].\n**\n** <dl>\n** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>\n** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^\n**\n** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>\n** <dd>The maximum length of an SQL statement, in bytes.</dd>)^\n**\n** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>\n** <dd>The maximum number of columns in a table definition or in the\n** result set of a [SELECT] or the maximum number of columns in an index\n** or in an ORDER BY or GROUP BY clause.</dd>)^\n**\n** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>\n** <dd>The maximum depth of the parse tree on any expression.</dd>)^\n**\n** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>\n** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^\n**\n** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>\n** <dd>The maximum number of instructions in a virtual machine program\n** used to implement an SQL statement.  This limit is not currently\n** enforced, though that might be added in some future release of\n** SQLite.</dd>)^\n**\n** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>\n** <dd>The maximum number of arguments on a function.</dd>)^\n**\n** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>\n** <dd>The maximum number of [ATTACH | attached databases].)^</dd>\n**\n** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]\n** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>\n** <dd>The maximum length of the pattern argument to the [LIKE] or\n** [GLOB] operators.</dd>)^\n**\n** [[SQLITE_LIMIT_VARIABLE_NUMBER]]\n** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>\n** <dd>The maximum index number of any [parameter] in an SQL statement.)^\n**\n** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>\n** <dd>The maximum depth of recursion for triggers.</dd>)^\n** </dl>\n*/\n#define SQLITE_LIMIT_LENGTH                    0\n#define SQLITE_LIMIT_SQL_LENGTH                1\n#define SQLITE_LIMIT_COLUMN                    2\n#define SQLITE_LIMIT_EXPR_DEPTH                3\n#define SQLITE_LIMIT_COMPOUND_SELECT           4\n#define SQLITE_LIMIT_VDBE_OP                   5\n#define SQLITE_LIMIT_FUNCTION_ARG              6\n#define SQLITE_LIMIT_ATTACHED                  7\n#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8\n#define SQLITE_LIMIT_VARIABLE_NUMBER           9\n#define SQLITE_LIMIT_TRIGGER_DEPTH            10\n\n/*\n** CAPI3REF: Compiling An SQL Statement\n** KEYWORDS: {SQL statement compiler}\n**\n** To execute an SQL query, it must first be compiled into a byte-code\n** program using one of these routines.\n**\n** The first argument, \"db\", is a [database connection] obtained from a\n** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or\n** [sqlite3_open16()].  The database connection must not have been closed.\n**\n** The second argument, \"zSql\", is the statement to be compiled, encoded\n** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()\n** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()\n** use UTF-16.\n**\n** ^If the nByte argument is less than zero, then zSql is read up to the\n** first zero terminator. ^If nByte is non-negative, then it is the maximum\n** number of  bytes read from zSql.  ^When nByte is non-negative, the\n** zSql string ends at either the first '\\000' or '\\u0000' character or\n** the nByte-th byte, whichever comes first. If the caller knows\n** that the supplied string is nul-terminated, then there is a small\n** performance advantage to be gained by passing an nByte parameter that\n** is equal to the number of bytes in the input string <i>including</i>\n** the nul-terminator bytes as this saves SQLite from having to\n** make a copy of the input string.\n**\n** ^If pzTail is not NULL then *pzTail is made to point to the first byte\n** past the end of the first SQL statement in zSql.  These routines only\n** compile the first statement in zSql, so *pzTail is left pointing to\n** what remains uncompiled.\n**\n** ^*ppStmt is left pointing to a compiled [prepared statement] that can be\n** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set\n** to NULL.  ^If the input text contains no SQL (if the input is an empty\n** string or a comment) then *ppStmt is set to NULL.\n** The calling procedure is responsible for deleting the compiled\n** SQL statement using [sqlite3_finalize()] after it has finished with it.\n** ppStmt may not be NULL.\n**\n** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];\n** otherwise an [error code] is returned.\n**\n** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are\n** recommended for all new programs. The two older interfaces are retained\n** for backwards compatibility, but their use is discouraged.\n** ^In the \"v2\" interfaces, the prepared statement\n** that is returned (the [sqlite3_stmt] object) contains a copy of the\n** original SQL text. This causes the [sqlite3_step()] interface to\n** behave differently in three ways:\n**\n** <ol>\n** <li>\n** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it\n** always used to do, [sqlite3_step()] will automatically recompile the SQL\n** statement and try to run it again.\n** </li>\n**\n** <li>\n** ^When an error occurs, [sqlite3_step()] will return one of the detailed\n** [error codes] or [extended error codes].  ^The legacy behavior was that\n** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code\n** and the application would have to make a second call to [sqlite3_reset()]\n** in order to find the underlying cause of the problem. With the \"v2\" prepare\n** interfaces, the underlying reason for the error is returned immediately.\n** </li>\n**\n** <li>\n** ^If the specific value bound to [parameter | host parameter] in the \n** WHERE clause might influence the choice of query plan for a statement,\n** then the statement will be automatically recompiled, as if there had been \n** a schema change, on the first  [sqlite3_step()] call following any change\n** to the [sqlite3_bind_text | bindings] of that [parameter]. \n** ^The specific value of WHERE-clause [parameter] might influence the \n** choice of query plan if the parameter is the left-hand side of a [LIKE]\n** or [GLOB] operator or if the parameter is compared to an indexed column\n** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.\n** the \n** </li>\n** </ol>\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\n\n/*\n** CAPI3REF: Retrieving Statement SQL\n**\n** ^This interface can be used to retrieve a saved copy of the original\n** SQL text used to create a [prepared statement] if that statement was\n** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Writes The Database\n**\n** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if\n** and only if the [prepared statement] X makes no direct changes to\n** the content of the database file.\n**\n** Note that [application-defined SQL functions] or\n** [virtual tables] might change the database indirectly as a side effect.  \n** ^(For example, if an application defines a function \"eval()\" that \n** calls [sqlite3_exec()], then the following SQL statement would\n** change the database file through side-effects:\n**\n** <blockquote><pre>\n**    SELECT eval('DELETE FROM t1') FROM t2;\n** </pre></blockquote>\n**\n** But because the [SELECT] statement does not change the database file\n** directly, sqlite3_stmt_readonly() would still return true.)^\n**\n** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],\n** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,\n** since the statements themselves do not actually modify the database but\n** rather they control the timing of when other statements modify the \n** database.  ^The [ATTACH] and [DETACH] statements also cause\n** sqlite3_stmt_readonly() to return true since, while those statements\n** change the configuration of a database connection, they do not make \n** changes to the content of the database files on disk.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If A Prepared Statement Has Been Reset\n**\n** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the\n** [prepared statement] S has been stepped at least once using \n** [sqlite3_step(S)] but has not run to completion and/or has not \n** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)\n** interface returns false if S is a NULL pointer.  If S is not a \n** NULL pointer and is not a pointer to a valid [prepared statement]\n** object, then the behavior is undefined and probably undesirable.\n**\n** This interface can be used in combination [sqlite3_next_stmt()]\n** to locate all prepared statements associated with a database \n** connection that are in need of being reset.  This can be used,\n** for example, in diagnostic routines to search for prepared \n** statements that are holding a transaction open.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Dynamically Typed Value Object\n** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}\n**\n** SQLite uses the sqlite3_value object to represent all values\n** that can be stored in a database table. SQLite uses dynamic typing\n** for the values it stores.  ^Values stored in sqlite3_value objects\n** can be integers, floating point values, strings, BLOBs, or NULL.\n**\n** An sqlite3_value object may be either \"protected\" or \"unprotected\".\n** Some interfaces require a protected sqlite3_value.  Other interfaces\n** will accept either a protected or an unprotected sqlite3_value.\n** Every interface that accepts sqlite3_value arguments specifies\n** whether or not it requires a protected sqlite3_value.\n**\n** The terms \"protected\" and \"unprotected\" refer to whether or not\n** a mutex is held.  An internal mutex is held for a protected\n** sqlite3_value object but no mutex is held for an unprotected\n** sqlite3_value object.  If SQLite is compiled to be single-threaded\n** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)\n** or if SQLite is run in one of reduced mutex modes \n** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]\n** then there is no distinction between protected and unprotected\n** sqlite3_value objects and they can be used interchangeably.  However,\n** for maximum code portability it is recommended that applications\n** still make the distinction between protected and unprotected\n** sqlite3_value objects even when not strictly required.\n**\n** ^The sqlite3_value objects that are passed as parameters into the\n** implementation of [application-defined SQL functions] are protected.\n** ^The sqlite3_value object returned by\n** [sqlite3_column_value()] is unprotected.\n** Unprotected sqlite3_value objects may only be used with\n** [sqlite3_result_value()] and [sqlite3_bind_value()].\n** The [sqlite3_value_blob | sqlite3_value_type()] family of\n** interfaces require protected sqlite3_value objects.\n*/\ntypedef struct Mem sqlite3_value;\n\n/*\n** CAPI3REF: SQL Function Context Object\n**\n** The context in which an SQL function executes is stored in an\n** sqlite3_context object.  ^A pointer to an sqlite3_context object\n** is always first parameter to [application-defined SQL functions].\n** The application-defined SQL function implementation will pass this\n** pointer through into calls to [sqlite3_result_int | sqlite3_result()],\n** [sqlite3_aggregate_context()], [sqlite3_user_data()],\n** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],\n** and/or [sqlite3_set_auxdata()].\n*/\ntypedef struct sqlite3_context sqlite3_context;\n\n/*\n** CAPI3REF: Binding Values To Prepared Statements\n** KEYWORDS: {host parameter} {host parameters} {host parameter name}\n** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}\n**\n** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,\n** literals may be replaced by a [parameter] that matches one of following\n** templates:\n**\n** <ul>\n** <li>  ?\n** <li>  ?NNN\n** <li>  :VVV\n** <li>  @VVV\n** <li>  $VVV\n** </ul>\n**\n** In the templates above, NNN represents an integer literal,\n** and VVV represents an alphanumeric identifier.)^  ^The values of these\n** parameters (also called \"host parameter names\" or \"SQL parameters\")\n** can be set using the sqlite3_bind_*() routines defined here.\n**\n** ^The first argument to the sqlite3_bind_*() routines is always\n** a pointer to the [sqlite3_stmt] object returned from\n** [sqlite3_prepare_v2()] or its variants.\n**\n** ^The second argument is the index of the SQL parameter to be set.\n** ^The leftmost SQL parameter has an index of 1.  ^When the same named\n** SQL parameter is used more than once, second and subsequent\n** occurrences have the same index as the first occurrence.\n** ^The index for named parameters can be looked up using the\n** [sqlite3_bind_parameter_index()] API if desired.  ^The index\n** for \"?NNN\" parameters is the value of NNN.\n** ^The NNN value must be between 1 and the [sqlite3_limit()]\n** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).\n**\n** ^The third argument is the value to bind to the parameter.\n**\n** ^(In those routines that have a fourth argument, its value is the\n** number of bytes in the parameter.  To be clear: the value is the\n** number of <u>bytes</u> in the value, not the number of characters.)^\n** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** is negative, then the length of the string is\n** the number of bytes up to the first zero terminator.\n** If the fourth parameter to sqlite3_bind_blob() is negative, then\n** the behavior is undefined.\n** If a non-negative fourth parameter is provided to sqlite3_bind_text()\n** or sqlite3_bind_text16() then that parameter must be the byte offset\n** where the NUL terminator would occur assuming the string were NUL\n** terminated.  If any NUL characters occur at byte offsets less than \n** the value of the fourth parameter then the resulting string value will\n** contain embedded NULs.  The result of expressions involving strings\n** with embedded NULs is undefined.\n**\n** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and\n** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or\n** string after SQLite has finished with it.  ^The destructor is called\n** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),\n** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  \n** ^If the fifth argument is\n** the special value [SQLITE_STATIC], then SQLite assumes that the\n** information is in static, unmanaged space and does not need to be freed.\n** ^If the fifth argument has the value [SQLITE_TRANSIENT], then\n** SQLite makes its own private copy of the data immediately, before\n** the sqlite3_bind_*() routine returns.\n**\n** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that\n** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory\n** (just an integer to hold its size) while it is being processed.\n** Zeroblobs are intended to serve as placeholders for BLOBs whose\n** content is later written using\n** [sqlite3_blob_open | incremental BLOB I/O] routines.\n** ^A negative value for the zeroblob results in a zero-length BLOB.\n**\n** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer\n** for the [prepared statement] or with a prepared statement for which\n** [sqlite3_step()] has been called more recently than [sqlite3_reset()],\n** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()\n** routine is passed a [prepared statement] that has been finalized, the\n** result is undefined and probably harmful.\n**\n** ^Bindings are not cleared by the [sqlite3_reset()] routine.\n** ^Unbound parameters are interpreted as NULL.\n**\n** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an\n** [error code] if anything goes wrong.\n** ^[SQLITE_RANGE] is returned if the parameter\n** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.\n**\n** See also: [sqlite3_bind_parameter_count()],\n** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);\nSQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);\n\n/*\n** CAPI3REF: Number Of SQL Parameters\n**\n** ^This routine can be used to find the number of [SQL parameters]\n** in a [prepared statement].  SQL parameters are tokens of the\n** form \"?\", \"?NNN\", \":AAA\", \"$AAA\", or \"@AAA\" that serve as\n** placeholders for values that are [sqlite3_bind_blob | bound]\n** to the parameters at a later time.\n**\n** ^(This routine actually returns the index of the largest (rightmost)\n** parameter. For all forms except ?NNN, this will correspond to the\n** number of unique parameters.  If parameters of the ?NNN form are used,\n** there may be gaps in the list.)^\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_name()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Name Of A Host Parameter\n**\n** ^The sqlite3_bind_parameter_name(P,N) interface returns\n** the name of the N-th [SQL parameter] in the [prepared statement] P.\n** ^(SQL parameters of the form \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** have a name which is the string \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** respectively.\n** In other words, the initial \":\" or \"$\" or \"@\" or \"?\"\n** is included as part of the name.)^\n** ^Parameters of the form \"?\" without a following integer have no name\n** and are referred to as \"nameless\" or \"anonymous parameters\".\n**\n** ^The first host parameter has an index of 1, not 0.\n**\n** ^If the value N is out of range or if the N-th parameter is\n** nameless, then NULL is returned.  ^The returned string is\n** always in UTF-8 encoding even if the named parameter was\n** originally specified as UTF-16 in [sqlite3_prepare16()] or\n** [sqlite3_prepare16_v2()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);\n\n/*\n** CAPI3REF: Index Of A Parameter With A Given Name\n**\n** ^Return the index of an SQL parameter given its name.  ^The\n** index value returned is suitable for use as the second\n** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero\n** is returned if no matching parameter is found.  ^The parameter\n** name must be given in UTF-8 even if the original statement\n** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);\n\n/*\n** CAPI3REF: Reset All Bindings On A Prepared Statement\n**\n** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset\n** the [sqlite3_bind_blob | bindings] on a [prepared statement].\n** ^Use this routine to reset all host parameters to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number Of Columns In A Result Set\n**\n** ^Return the number of columns in the result set returned by the\n** [prepared statement]. ^This routine returns 0 if pStmt is an SQL\n** statement that does not return data (for example an [UPDATE]).\n**\n** See also: [sqlite3_data_count()]\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Column Names In A Result Set\n**\n** ^These routines return the name assigned to a particular column\n** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()\n** interface returns a pointer to a zero-terminated UTF-8 string\n** and sqlite3_column_name16() returns a pointer to a zero-terminated\n** UTF-16 string.  ^The first parameter is the [prepared statement]\n** that implements the [SELECT] statement. ^The second parameter is the\n** column number.  ^The leftmost column is number 0.\n**\n** ^The returned string pointer is valid until either the [prepared statement]\n** is destroyed by [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the next call to\n** sqlite3_column_name() or sqlite3_column_name16() on the same column.\n**\n** ^If sqlite3_malloc() fails during the processing of either routine\n** (for example during a conversion from UTF-8 to UTF-16) then a\n** NULL pointer is returned.\n**\n** ^The name of a result column is the value of the \"AS\" clause for\n** that column, if there is an AS clause.  If there is no AS clause\n** then the name of the column is unspecified and may change from\n** one release of SQLite to the next.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);\n\n/*\n** CAPI3REF: Source Of Data In A Query Result\n**\n** ^These routines provide a means to determine the database, table, and\n** table column that is the origin of a particular result column in\n** [SELECT] statement.\n** ^The name of the database or table or column can be returned as\n** either a UTF-8 or UTF-16 string.  ^The _database_ routines return\n** the database name, the _table_ routines return the table name, and\n** the origin_ routines return the column name.\n** ^The returned string is valid until the [prepared statement] is destroyed\n** using [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the same information is requested\n** again in a different encoding.\n**\n** ^The names returned are the original un-aliased names of the\n** database, table, and column.\n**\n** ^The first argument to these interfaces is a [prepared statement].\n** ^These functions return information about the Nth result column returned by\n** the statement, where N is the second function argument.\n** ^The left-most column is column 0 for these routines.\n**\n** ^If the Nth column returned by the statement is an expression or\n** subquery and is not a column value, then all of these functions return\n** NULL.  ^These routine might also return NULL if a memory allocation error\n** occurs.  ^Otherwise, they return the name of the attached database, table,\n** or column that query result column was extracted from.\n**\n** ^As with all other SQLite APIs, those whose names end with \"16\" return\n** UTF-16 encoded strings and the other functions return UTF-8.\n**\n** ^These APIs are only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.\n**\n** If two or more threads call one or more of these routines against the same\n** prepared statement and column at the same time then the results are\n** undefined.\n**\n** If two or more threads call one or more\n** [sqlite3_column_database_name | column metadata interfaces]\n** for the same [prepared statement] and result column\n** at the same time then the results are undefined.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Declared Datatype Of A Query Result\n**\n** ^(The first parameter is a [prepared statement].\n** If this statement is a [SELECT] statement and the Nth column of the\n** returned result set of that [SELECT] is a table column (not an\n** expression or subquery) then the declared type of the table\n** column is returned.)^  ^If the Nth column of the result set is an\n** expression or subquery, then a NULL pointer is returned.\n** ^The returned string is always UTF-8 encoded.\n**\n** ^(For example, given the database schema:\n**\n** CREATE TABLE t1(c1 VARIANT);\n**\n** and the following statement to be compiled:\n**\n** SELECT c1 + 1, c1 FROM t1;\n**\n** this routine would return the string \"VARIANT\" for the second result\n** column (i==1), and a NULL pointer for the first result column (i==0).)^\n**\n** ^SQLite uses dynamic run-time typing.  ^So just because a column\n** is declared to contain a particular type does not mean that the\n** data stored in that column is of the declared type.  SQLite is\n** strongly typed, but the typing is dynamic not static.  ^Type\n** is associated with individual values, not with the containers\n** used to hold those values.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Evaluate An SQL Statement\n**\n** After a [prepared statement] has been prepared using either\n** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy\n** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function\n** must be called one or more times to evaluate the statement.\n**\n** The details of the behavior of the sqlite3_step() interface depend\n** on whether the statement was prepared using the newer \"v2\" interface\n** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy\n** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the\n** new \"v2\" interface is recommended for new applications but the legacy\n** interface will continue to be supported.\n**\n** ^In the legacy interface, the return value will be either [SQLITE_BUSY],\n** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].\n** ^With the \"v2\" interface, any of the other [result codes] or\n** [extended result codes] might be returned as well.\n**\n** ^[SQLITE_BUSY] means that the database engine was unable to acquire the\n** database locks it needs to do its job.  ^If the statement is a [COMMIT]\n** or occurs outside of an explicit transaction, then you can retry the\n** statement.  If the statement is not a [COMMIT] and occurs within an\n** explicit transaction then you should rollback the transaction before\n** continuing.\n**\n** ^[SQLITE_DONE] means that the statement has finished executing\n** successfully.  sqlite3_step() should not be called again on this virtual\n** machine without first calling [sqlite3_reset()] to reset the virtual\n** machine back to its initial state.\n**\n** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]\n** is returned each time a new row of data is ready for processing by the\n** caller. The values may be accessed using the [column access functions].\n** sqlite3_step() is called again to retrieve the next row of data.\n**\n** ^[SQLITE_ERROR] means that a run-time error (such as a constraint\n** violation) has occurred.  sqlite3_step() should not be called again on\n** the VM. More information may be found by calling [sqlite3_errmsg()].\n** ^With the legacy interface, a more specific error code (for example,\n** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)\n** can be obtained by calling [sqlite3_reset()] on the\n** [prepared statement].  ^In the \"v2\" interface,\n** the more specific error code is returned directly by sqlite3_step().\n**\n** [SQLITE_MISUSE] means that the this routine was called inappropriately.\n** Perhaps it was called on a [prepared statement] that has\n** already been [sqlite3_finalize | finalized] or on one that had\n** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could\n** be the case that the same database connection is being used by two or\n** more threads at the same moment in time.\n**\n** For all versions of SQLite up to and including 3.6.23.1, a call to\n** [sqlite3_reset()] was required after sqlite3_step() returned anything\n** other than [SQLITE_ROW] before any subsequent invocation of\n** sqlite3_step().  Failure to reset the prepared statement using \n** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from\n** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began\n** calling [sqlite3_reset()] automatically in this circumstance rather\n** than returning [SQLITE_MISUSE].  This is not considered a compatibility\n** break because any application that ever receives an SQLITE_MISUSE error\n** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option\n** can be used to restore the legacy behavior.\n**\n** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()\n** API always returns a generic error code, [SQLITE_ERROR], following any\n** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call\n** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the\n** specific [error codes] that better describes the error.\n** We admit that this is a goofy design.  The problem has been fixed\n** with the \"v2\" interface.  If you prepare all of your SQL statements\n** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead\n** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,\n** then the more specific [error codes] are returned directly\n** by sqlite3_step().  The use of the \"v2\" interface is recommended.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number of columns in a result set\n**\n** ^The sqlite3_data_count(P) interface returns the number of columns in the\n** current row of the result set of [prepared statement] P.\n** ^If prepared statement P does not have results ready to return\n** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of\n** interfaces) then sqlite3_data_count(P) returns 0.\n** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.\n** ^The sqlite3_data_count(P) routine returns 0 if the previous call to\n** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)\n** will return non-zero if previous call to [sqlite3_step](P) returned\n** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]\n** where it always returns zero since each step of that multi-step\n** pragma returns 0 columns of data.\n**\n** See also: [sqlite3_column_count()]\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Fundamental Datatypes\n** KEYWORDS: SQLITE_TEXT\n**\n** ^(Every value in SQLite has one of five fundamental datatypes:\n**\n** <ul>\n** <li> 64-bit signed integer\n** <li> 64-bit IEEE floating point number\n** <li> string\n** <li> BLOB\n** <li> NULL\n** </ul>)^\n**\n** These constants are codes for each of those types.\n**\n** Note that the SQLITE_TEXT constant was also used in SQLite version 2\n** for a completely different meaning.  Software that links against both\n** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not\n** SQLITE_TEXT.\n*/\n#define SQLITE_INTEGER  1\n#define SQLITE_FLOAT    2\n#define SQLITE_BLOB     4\n#define SQLITE_NULL     5\n#ifdef SQLITE_TEXT\n# undef SQLITE_TEXT\n#else\n# define SQLITE_TEXT     3\n#endif\n#define SQLITE3_TEXT     3\n\n/*\n** CAPI3REF: Result Values From A Query\n** KEYWORDS: {column access functions}\n**\n** These routines form the \"result set\" interface.\n**\n** ^These routines return information about a single column of the current\n** result row of a query.  ^In every case the first argument is a pointer\n** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]\n** that was returned from [sqlite3_prepare_v2()] or one of its variants)\n** and the second argument is the index of the column for which information\n** should be returned. ^The leftmost column of the result set has the index 0.\n** ^The number of columns in the result can be determined using\n** [sqlite3_column_count()].\n**\n** If the SQL statement does not currently point to a valid row, or if the\n** column index is out of range, the result is undefined.\n** These routines may only be called when the most recent call to\n** [sqlite3_step()] has returned [SQLITE_ROW] and neither\n** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.\n** If any of these routines are called after [sqlite3_reset()] or\n** [sqlite3_finalize()] or after [sqlite3_step()] has returned\n** something other than [SQLITE_ROW], the results are undefined.\n** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]\n** are called from a different thread while any of these routines\n** are pending, then the results are undefined.\n**\n** ^The sqlite3_column_type() routine returns the\n** [SQLITE_INTEGER | datatype code] for the initial data type\n** of the result column.  ^The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value\n** returned by sqlite3_column_type() is only meaningful if no type\n** conversions have occurred as described below.  After a type conversion,\n** the value returned by sqlite3_column_type() is undefined.  Future\n** versions of SQLite may change the behavior of sqlite3_column_type()\n** following a type conversion.\n**\n** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts\n** the string to UTF-8 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes() returns zero.\n**\n** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts\n** the string to UTF-16 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes16() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.\n**\n** ^The values returned by [sqlite3_column_bytes()] and \n** [sqlite3_column_bytes16()] do not include the zero terminators at the end\n** of the string.  ^For clarity: the values returned by\n** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of\n** bytes in the string, not the number of characters.\n**\n** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),\n** even empty strings, are always zero-terminated.  ^The return\n** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.\n**\n** ^The object returned by [sqlite3_column_value()] is an\n** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object\n** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].\n** If the [unprotected sqlite3_value] object returned by\n** [sqlite3_column_value()] is used in any other way, including calls\n** to routines like [sqlite3_value_int()], [sqlite3_value_text()],\n** or [sqlite3_value_bytes()], then the behavior is undefined.\n**\n** These routines attempt to convert the value where appropriate.  ^For\n** example, if the internal representation is FLOAT and a text result\n** is requested, [sqlite3_snprintf()] is used internally to perform the\n** conversion automatically.  ^(The following table details the conversions\n** that are applied:\n**\n** <blockquote>\n** <table border=\"1\">\n** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion\n**\n** <tr><td>  NULL    <td> INTEGER   <td> Result is 0\n** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0\n** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer\n** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer\n** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float\n** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer\n** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT\n** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer\n** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float\n** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT\n** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()\n** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()\n** <tr><td>  TEXT    <td>   BLOB    <td> No change\n** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()\n** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()\n** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed\n** </table>\n** </blockquote>)^\n**\n** The table above makes reference to standard C library functions atoi()\n** and atof().  SQLite does not really use these functions.  It has its\n** own equivalent internal routines.  The atoi() and atof() names are\n** used in the table for brevity and because they are familiar to most\n** C programmers.\n**\n** Note that when type conversions occur, pointers returned by prior\n** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or\n** sqlite3_column_text16() may be invalidated.\n** Type conversions and pointer invalidations might occur\n** in the following cases:\n**\n** <ul>\n** <li> The initial content is a BLOB and sqlite3_column_text() or\n**      sqlite3_column_text16() is called.  A zero-terminator might\n**      need to be added to the string.</li>\n** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or\n**      sqlite3_column_text16() is called.  The content must be converted\n**      to UTF-16.</li>\n** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or\n**      sqlite3_column_text() is called.  The content must be converted\n**      to UTF-8.</li>\n** </ul>\n**\n** ^Conversions between UTF-16be and UTF-16le are always done in place and do\n** not invalidate a prior pointer, though of course the content of the buffer\n** that the prior pointer references will have been modified.  Other kinds\n** of conversion are done in place when it is possible, but sometimes they\n** are not possible and in those cases prior pointers are invalidated.\n**\n** The safest and easiest to remember policy is to invoke these routines\n** in one of the following ways:\n**\n** <ul>\n**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>\n** </ul>\n**\n** In other words, you should call sqlite3_column_text(),\n** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result\n** into the desired format, then invoke sqlite3_column_bytes() or\n** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls\n** to sqlite3_column_text() or sqlite3_column_blob() with calls to\n** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()\n** with calls to sqlite3_column_bytes().\n**\n** ^The pointers returned are valid until a type conversion occurs as\n** described above, or until [sqlite3_step()] or [sqlite3_reset()] or\n** [sqlite3_finalize()] is called.  ^The memory space used to hold strings\n** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned\n** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into\n** [sqlite3_free()].\n**\n** ^(If a memory allocation error occurs during the evaluation of any\n** of these routines, a default value is returned.  The default value\n** is either the integer 0, the floating point number 0.0, or a NULL\n** pointer.  Subsequent calls to [sqlite3_errcode()] will return\n** [SQLITE_NOMEM].)^\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);\nSQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);\n\n/*\n** CAPI3REF: Destroy A Prepared Statement Object\n**\n** ^The sqlite3_finalize() function is called to delete a [prepared statement].\n** ^If the most recent evaluation of the statement encountered no errors\n** or if the statement is never been evaluated, then sqlite3_finalize() returns\n** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then\n** sqlite3_finalize(S) returns the appropriate [error code] or\n** [extended error code].\n**\n** ^The sqlite3_finalize(S) routine can be called at any point during\n** the life cycle of [prepared statement] S:\n** before statement S is ever evaluated, after\n** one or more calls to [sqlite3_reset()], or after any call\n** to [sqlite3_step()] regardless of whether or not the statement has\n** completed execution.\n**\n** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.\n**\n** The application must finalize every [prepared statement] in order to avoid\n** resource leaks.  It is a grievous error for the application to try to use\n** a prepared statement after it has been finalized.  Any use of a prepared\n** statement after it has been finalized can result in undefined and\n** undesirable behavior such as segfaults and heap corruption.\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Reset A Prepared Statement Object\n**\n** The sqlite3_reset() function is called to reset a [prepared statement]\n** object back to its initial state, ready to be re-executed.\n** ^Any SQL statement variables that had values bound to them using\n** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.\n** Use [sqlite3_clear_bindings()] to reset the bindings.\n**\n** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S\n** back to the beginning of its program.\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],\n** or if [sqlite3_step(S)] has never before been called on S,\n** then [sqlite3_reset(S)] returns [SQLITE_OK].\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S indicated an error, then\n** [sqlite3_reset(S)] returns an appropriate [error code].\n**\n** ^The [sqlite3_reset(S)] interface does not change the values\n** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Create Or Redefine SQL Functions\n** KEYWORDS: {function creation routines}\n** KEYWORDS: {application-defined SQL function}\n** KEYWORDS: {application-defined SQL functions}\n**\n** ^These functions (collectively known as \"function creation routines\")\n** are used to add SQL functions or aggregates or to redefine the behavior\n** of existing SQL functions or aggregates.  The only differences between\n** these routines are the text encoding expected for\n** the second parameter (the name of the function being created)\n** and the presence or absence of a destructor callback for\n** the application data pointer.\n**\n** ^The first parameter is the [database connection] to which the SQL\n** function is to be added.  ^If an application uses more than one database\n** connection then application-defined SQL functions must be added\n** to each database connection separately.\n**\n** ^The second parameter is the name of the SQL function to be created or\n** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8\n** representation, exclusive of the zero-terminator.  ^Note that the name\n** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  \n** ^Any attempt to create a function with a longer name\n** will result in [SQLITE_MISUSE] being returned.\n**\n** ^The third parameter (nArg)\n** is the number of arguments that the SQL function or\n** aggregate takes. ^If this parameter is -1, then the SQL function or\n** aggregate may take any number of arguments between 0 and the limit\n** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third\n** parameter is less than -1 or greater than 127 then the behavior is\n** undefined.\n**\n** ^The fourth parameter, eTextRep, specifies what\n** [SQLITE_UTF8 | text encoding] this SQL function prefers for\n** its parameters.  Every SQL function implementation must be able to work\n** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be\n** more efficient with one encoding than another.  ^An application may\n** invoke sqlite3_create_function() or sqlite3_create_function16() multiple\n** times with the same function but with different values of eTextRep.\n** ^When multiple implementations of the same function are available, SQLite\n** will pick the one that involves the least amount of data conversion.\n** If there is only a single implementation which does not care what text\n** encoding is used, then the fourth argument should be [SQLITE_ANY].\n**\n** ^(The fifth parameter is an arbitrary pointer.  The implementation of the\n** function can gain access to this pointer using [sqlite3_user_data()].)^\n**\n** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are\n** pointers to C-language functions that implement the SQL function or\n** aggregate. ^A scalar SQL function requires an implementation of the xFunc\n** callback only; NULL pointers must be passed as the xStep and xFinal\n** parameters. ^An aggregate SQL function requires an implementation of xStep\n** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing\n** SQL function or aggregate, pass NULL pointers for all three function\n** callbacks.\n**\n** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,\n** then it is destructor for the application data pointer. \n** The destructor is invoked when the function is deleted, either by being\n** overloaded or when the database connection closes.)^\n** ^The destructor is also invoked if the call to\n** sqlite3_create_function_v2() fails.\n** ^When the destructor callback of the tenth parameter is invoked, it\n** is passed a single argument which is a copy of the application data \n** pointer which was the fifth parameter to sqlite3_create_function_v2().\n**\n** ^It is permitted to register multiple implementations of the same\n** functions with the same name but with either differing numbers of\n** arguments or differing preferred text encodings.  ^SQLite will use\n** the implementation that most closely matches the way in which the\n** SQL function is used.  ^A function implementation with a non-negative\n** nArg parameter is a better match than a function implementation with\n** a negative nArg.  ^A function where the preferred text encoding\n** matches the database encoding is a better\n** match than a function where the encoding is different.  \n** ^A function where the encoding difference is between UTF16le and UTF16be\n** is a closer match than a function where the encoding difference is\n** between UTF8 and UTF16.\n**\n** ^Built-in functions may be overloaded by new application-defined functions.\n**\n** ^An application-defined function is permitted to call other\n** SQLite interfaces.  However, such calls must not\n** close the database connection nor finalize or reset the prepared\n** statement in which the function is running.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void(*xDestroy)(void*)\n);\n\n/*\n** CAPI3REF: Text Encodings\n**\n** These constant define integer codes that represent the various\n** text encodings supported by SQLite.\n*/\n#define SQLITE_UTF8           1\n#define SQLITE_UTF16LE        2\n#define SQLITE_UTF16BE        3\n#define SQLITE_UTF16          4    /* Use native byte order */\n#define SQLITE_ANY            5    /* sqlite3_create_function only */\n#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */\n\n/*\n** CAPI3REF: Deprecated Functions\n** DEPRECATED\n**\n** These functions are [deprecated].  In order to maintain\n** backwards compatibility with older code, these functions continue \n** to be supported.  However, new applications should avoid\n** the use of these functions.  To help encourage people to avoid\n** using these functions, we are not going to tell you what they do.\n*/\n#ifndef SQLITE_OMIT_DEPRECATED\nSQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);\nSQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);\n#endif\n\n/*\n** CAPI3REF: Obtaining SQL Function Parameter Values\n**\n** The C-language implementation of SQL functions and aggregates uses\n** this set of interface routines to access the parameter values on\n** the function or aggregate.\n**\n** The xFunc (for scalar functions) or xStep (for aggregates) parameters\n** to [sqlite3_create_function()] and [sqlite3_create_function16()]\n** define callbacks that implement the SQL functions and aggregates.\n** The 3rd parameter to these callbacks is an array of pointers to\n** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for\n** each parameter to the SQL function.  These routines are used to\n** extract values from the [sqlite3_value] objects.\n**\n** These routines work only with [protected sqlite3_value] objects.\n** Any attempt to use these routines on an [unprotected sqlite3_value]\n** object results in undefined behavior.\n**\n** ^These routines work just like the corresponding [column access functions]\n** except that  these routines take a single [protected sqlite3_value] object\n** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.\n**\n** ^The sqlite3_value_text16() interface extracts a UTF-16 string\n** in the native byte-order of the host machine.  ^The\n** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces\n** extract UTF-16 strings as big-endian and little-endian respectively.\n**\n** ^(The sqlite3_value_numeric_type() interface attempts to apply\n** numeric affinity to the value.  This means that an attempt is\n** made to convert the value to an integer or floating point.  If\n** such a conversion is possible without loss of information (in other\n** words, if the value is a string that looks like a number)\n** then the conversion is performed.  Otherwise no conversion occurs.\n** The [SQLITE_INTEGER | datatype] after conversion is returned.)^\n**\n** Please pay particular attention to the fact that the pointer returned\n** from [sqlite3_value_blob()], [sqlite3_value_text()], or\n** [sqlite3_value_text16()] can be invalidated by a subsequent call to\n** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],\n** or [sqlite3_value_text16()].\n**\n** These routines must be called from the same thread as\n** the SQL function that supplied the [sqlite3_value*] parameters.\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value*);\nSQLITE_API double sqlite3_value_double(sqlite3_value*);\nSQLITE_API int sqlite3_value_int(sqlite3_value*);\nSQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);\nSQLITE_API int sqlite3_value_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);\n\n/*\n** CAPI3REF: Obtain Aggregate Function Context\n**\n** Implementations of aggregate SQL functions use this\n** routine to allocate memory for storing their state.\n**\n** ^The first time the sqlite3_aggregate_context(C,N) routine is called \n** for a particular aggregate function, SQLite\n** allocates N of memory, zeroes out that memory, and returns a pointer\n** to the new memory. ^On second and subsequent calls to\n** sqlite3_aggregate_context() for the same aggregate function instance,\n** the same buffer is returned.  Sqlite3_aggregate_context() is normally\n** called once for each invocation of the xStep callback and then one\n** last time when the xFinal callback is invoked.  ^(When no rows match\n** an aggregate query, the xStep() callback of the aggregate function\n** implementation is never called and xFinal() is called exactly once.\n** In those cases, sqlite3_aggregate_context() might be called for the\n** first time from within xFinal().)^\n**\n** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is\n** less than or equal to zero or if a memory allocate error occurs.\n**\n** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is\n** determined by the N parameter on first successful call.  Changing the\n** value of N in subsequent call to sqlite3_aggregate_context() within\n** the same aggregate function instance will not resize the memory\n** allocation.)^\n**\n** ^SQLite automatically frees the memory allocated by \n** sqlite3_aggregate_context() when the aggregate query concludes.\n**\n** The first parameter must be a copy of the\n** [sqlite3_context | SQL function context] that is the first parameter\n** to the xStep or xFinal callback routine that implements the aggregate\n** function.\n**\n** This routine must be called from the same thread in which\n** the aggregate SQL function is running.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);\n\n/*\n** CAPI3REF: User Data For Functions\n**\n** ^The sqlite3_user_data() interface returns a copy of\n** the pointer that was the pUserData parameter (the 5th parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n**\n** This routine must be called from the same thread in which\n** the application-defined function is running.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context*);\n\n/*\n** CAPI3REF: Database Connection For Functions\n**\n** ^The sqlite3_context_db_handle() interface returns a copy of\n** the pointer to the [database connection] (the 1st parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);\n\n/*\n** CAPI3REF: Function Auxiliary Data\n**\n** The following two functions may be used by scalar SQL functions to\n** associate metadata with argument values. If the same value is passed to\n** multiple invocations of the same SQL function during query execution, under\n** some circumstances the associated metadata may be preserved. This may\n** be used, for example, to add a regular-expression matching scalar\n** function. The compiled version of the regular expression is stored as\n** metadata associated with the SQL value passed as the regular expression\n** pattern.  The compiled regular expression can be reused on multiple\n** invocations of the same function so that the original pattern string\n** does not need to be recompiled on each invocation.\n**\n** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata\n** associated by the sqlite3_set_auxdata() function with the Nth argument\n** value to the application-defined function. ^If no metadata has been ever\n** been set for the Nth argument of the function, or if the corresponding\n** function parameter has changed since the meta-data was set,\n** then sqlite3_get_auxdata() returns a NULL pointer.\n**\n** ^The sqlite3_set_auxdata() interface saves the metadata\n** pointed to by its 3rd parameter as the metadata for the N-th\n** argument of the application-defined function.  Subsequent\n** calls to sqlite3_get_auxdata() might return this data, if it has\n** not been destroyed.\n** ^If it is not NULL, SQLite will invoke the destructor\n** function given by the 4th parameter to sqlite3_set_auxdata() on\n** the metadata when the corresponding function parameter changes\n** or when the SQL statement completes, whichever comes first.\n**\n** SQLite is free to call the destructor and drop metadata on any\n** parameter of any function at any time.  ^The only guarantee is that\n** the destructor will be called before the metadata is dropped.\n**\n** ^(In practice, metadata is preserved between function calls for\n** expressions that are constant at compile time. This includes literal\n** values and [parameters].)^\n**\n** These routines must be called from the same thread in which\n** the SQL function is running.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);\nSQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));\n\n\n/*\n** CAPI3REF: Constants Defining Special Destructor Behavior\n**\n** These are special values for the destructor that is passed in as the\n** final argument to routines like [sqlite3_result_blob()].  ^If the destructor\n** argument is SQLITE_STATIC, it means that the content pointer is constant\n** and will never change.  It does not need to be destroyed.  ^The\n** SQLITE_TRANSIENT value means that the content will likely change in\n** the near future and that SQLite should make its own private copy of\n** the content before returning.\n**\n** The typedef is necessary to work around problems in certain\n** C++ compilers.  See ticket #2191.\n*/\ntypedef void (*sqlite3_destructor_type)(void*);\n#define SQLITE_STATIC      ((sqlite3_destructor_type)0)\n#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)\n\n/*\n** CAPI3REF: Setting The Result Of An SQL Function\n**\n** These routines are used by the xFunc or xFinal callbacks that\n** implement SQL functions and aggregates.  See\n** [sqlite3_create_function()] and [sqlite3_create_function16()]\n** for additional information.\n**\n** These functions work very much like the [parameter binding] family of\n** functions used to bind values to host parameters in prepared statements.\n** Refer to the [SQL parameter] documentation for additional information.\n**\n** ^The sqlite3_result_blob() interface sets the result from\n** an application-defined function to be the BLOB whose content is pointed\n** to by the second parameter and which is N bytes long where N is the\n** third parameter.\n**\n** ^The sqlite3_result_zeroblob() interfaces set the result of\n** the application-defined function to be a BLOB containing all zero\n** bytes and N bytes in size, where N is the value of the 2nd parameter.\n**\n** ^The sqlite3_result_double() interface sets the result from\n** an application-defined function to be a floating point value specified\n** by its 2nd argument.\n**\n** ^The sqlite3_result_error() and sqlite3_result_error16() functions\n** cause the implemented SQL function to throw an exception.\n** ^SQLite uses the string pointed to by the\n** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()\n** as the text of an error message.  ^SQLite interprets the error\n** message string from sqlite3_result_error() as UTF-8. ^SQLite\n** interprets the string from sqlite3_result_error16() as UTF-16 in native\n** byte order.  ^If the third parameter to sqlite3_result_error()\n** or sqlite3_result_error16() is negative then SQLite takes as the error\n** message all text up through the first zero character.\n** ^If the third parameter to sqlite3_result_error() or\n** sqlite3_result_error16() is non-negative then SQLite takes that many\n** bytes (not characters) from the 2nd parameter as the error message.\n** ^The sqlite3_result_error() and sqlite3_result_error16()\n** routines make a private copy of the error message text before\n** they return.  Hence, the calling function can deallocate or\n** modify the text after they return without harm.\n** ^The sqlite3_result_error_code() function changes the error code\n** returned by SQLite as a result of an error in a function.  ^By default,\n** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()\n** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.\n**\n** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an\n** error indicating that a string or BLOB is too long to represent.\n**\n** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an\n** error indicating that a memory allocation failed.\n**\n** ^The sqlite3_result_int() interface sets the return value\n** of the application-defined function to be the 32-bit signed integer\n** value given in the 2nd argument.\n** ^The sqlite3_result_int64() interface sets the return value\n** of the application-defined function to be the 64-bit signed integer\n** value given in the 2nd argument.\n**\n** ^The sqlite3_result_null() interface sets the return value\n** of the application-defined function to be NULL.\n**\n** ^The sqlite3_result_text(), sqlite3_result_text16(),\n** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces\n** set the return value of the application-defined function to be\n** a text string which is represented as UTF-8, UTF-16 native byte order,\n** UTF-16 little endian, or UTF-16 big endian, respectively.\n** ^SQLite takes the text result from the application from\n** the 2nd parameter of the sqlite3_result_text* interfaces.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is negative, then SQLite takes result text from the 2nd parameter\n** through the first zero character.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is non-negative, then as many bytes (not characters) of the text\n** pointed to by the 2nd parameter are taken as the application-defined\n** function result.  If the 3rd parameter is non-negative, then it\n** must be the byte offset into the string where the NUL terminator would\n** appear if the string where NUL terminated.  If any NUL characters occur\n** in the string at a byte offset that is less than the value of the 3rd\n** parameter, then the resulting string will contain embedded NULs and the\n** result of expressions operating on strings with embedded NULs is undefined.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that\n** function as the destructor on the text or BLOB result when it has\n** finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces or to\n** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite\n** assumes that the text or BLOB result is in constant space and does not\n** copy the content of the parameter nor call a destructor on the content\n** when it has finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT\n** then SQLite makes a copy of the result into space obtained from\n** from [sqlite3_malloc()] before it returns.\n**\n** ^The sqlite3_result_value() interface sets the result of\n** the application-defined function to be a copy the\n** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The\n** sqlite3_result_value() interface makes a copy of the [sqlite3_value]\n** so that the [sqlite3_value] specified in the parameter may change or\n** be deallocated after sqlite3_result_value() returns without harm.\n** ^A [protected sqlite3_value] object may always be used where an\n** [unprotected sqlite3_value] object is required, so either\n** kind of [sqlite3_value] object can be used with this interface.\n**\n** If these routines are called from within the different thread\n** than the one containing the application-defined function that received\n** the [sqlite3_context] pointer, the results are undefined.\n*/\nSQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_double(sqlite3_context*, double);\nSQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);\nSQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);\nSQLITE_API void sqlite3_result_null(sqlite3_context*);\nSQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);\n\n/*\n** CAPI3REF: Define New Collating Sequences\n**\n** ^These functions add, remove, or modify a [collation] associated\n** with the [database connection] specified as the first argument.\n**\n** ^The name of the collation is a UTF-8 string\n** for sqlite3_create_collation() and sqlite3_create_collation_v2()\n** and a UTF-16 string in native byte order for sqlite3_create_collation16().\n** ^Collation names that compare equal according to [sqlite3_strnicmp()] are\n** considered to be the same name.\n**\n** ^(The third argument (eTextRep) must be one of the constants:\n** <ul>\n** <li> [SQLITE_UTF8],\n** <li> [SQLITE_UTF16LE],\n** <li> [SQLITE_UTF16BE],\n** <li> [SQLITE_UTF16], or\n** <li> [SQLITE_UTF16_ALIGNED].\n** </ul>)^\n** ^The eTextRep argument determines the encoding of strings passed\n** to the collating function callback, xCallback.\n** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep\n** force strings to be UTF16 with native byte order.\n** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin\n** on an even byte address.\n**\n** ^The fourth argument, pArg, is an application data pointer that is passed\n** through as the first argument to the collating function callback.\n**\n** ^The fifth argument, xCallback, is a pointer to the collating function.\n** ^Multiple collating functions can be registered using the same name but\n** with different eTextRep parameters and SQLite will use whichever\n** function requires the least amount of data transformation.\n** ^If the xCallback argument is NULL then the collating function is\n** deleted.  ^When all collating functions having the same name are deleted,\n** that collation is no longer usable.\n**\n** ^The collating function callback is invoked with a copy of the pArg \n** application data pointer and with two strings in the encoding specified\n** by the eTextRep argument.  The collating function must return an\n** integer that is negative, zero, or positive\n** if the first string is less than, equal to, or greater than the second,\n** respectively.  A collating function must always return the same answer\n** given the same inputs.  If two or more collating functions are registered\n** to the same collation name (using different eTextRep values) then all\n** must give an equivalent answer when invoked with equivalent strings.\n** The collating function must obey the following properties for all\n** strings A, B, and C:\n**\n** <ol>\n** <li> If A==B then B==A.\n** <li> If A==B and B==C then A==C.\n** <li> If A&lt;B THEN B&gt;A.\n** <li> If A&lt;B and B&lt;C then A&lt;C.\n** </ol>\n**\n** If a collating function fails any of the above constraints and that\n** collating function is  registered and used, then the behavior of SQLite\n** is undefined.\n**\n** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()\n** with the addition that the xDestroy callback is invoked on pArg when\n** the collating function is deleted.\n** ^Collating functions are deleted when they are overridden by later\n** calls to the collation creation functions or when the\n** [database connection] is closed using [sqlite3_close()].\n**\n** ^The xDestroy callback is <u>not</u> called if the \n** sqlite3_create_collation_v2() function fails.  Applications that invoke\n** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should \n** check the return code and dispose of the application data pointer\n** themselves rather than expecting SQLite to deal with it for them.\n** This is different from every other SQLite interface.  The inconsistency \n** is unfortunate but cannot be changed without breaking backwards \n** compatibility.\n**\n** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3*, \n  const void *zName,\n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\n\n/*\n** CAPI3REF: Collation Needed Callbacks\n**\n** ^To avoid having to register all collation sequences before a database\n** can be used, a single callback function may be registered with the\n** [database connection] to be invoked whenever an undefined collation\n** sequence is required.\n**\n** ^If the function is registered using the sqlite3_collation_needed() API,\n** then it is passed the names of undefined collation sequences as strings\n** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,\n** the names are passed as UTF-16 in machine native byte order.\n** ^A call to either function replaces the existing collation-needed callback.\n**\n** ^(When the callback is invoked, the first argument passed is a copy\n** of the second argument to sqlite3_collation_needed() or\n** sqlite3_collation_needed16().  The second argument is the database\n** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],\n** or [SQLITE_UTF16LE], indicating the most desirable form of the collation\n** sequence function required.  The fourth parameter is the name of the\n** required collation sequence.)^\n**\n** The callback function should register the desired collation using\n** [sqlite3_create_collation()], [sqlite3_create_collation16()], or\n** [sqlite3_create_collation_v2()].\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3*, \n  void*, \n  void(*)(void*,sqlite3*,int eTextRep,const char*)\n);\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3*, \n  void*,\n  void(*)(void*,sqlite3*,int eTextRep,const void*)\n);\n\n#ifdef SQLITE_HAS_CODEC\n/*\n** Specify the key for an encrypted database.  This routine should be\n** called right after sqlite3_open().\n**\n** The code to implement this API is not available in the public release\n** of SQLite.\n*/\nSQLITE_API int sqlite3_key(\n  sqlite3 *db,                   /* Database to be rekeyed */\n  const void *pKey, int nKey     /* The key */\n);\n\n/*\n** Change the key on an open database.  If the current database is not\n** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the\n** database is decrypted.\n**\n** The code to implement this API is not available in the public release\n** of SQLite.\n*/\nSQLITE_API int sqlite3_rekey(\n  sqlite3 *db,                   /* Database to be rekeyed */\n  const void *pKey, int nKey     /* The new key */\n);\n\n/*\n** Specify the activation key for a SEE database.  Unless \n** activated, none of the SEE routines will work.\n*/\nSQLITE_API void sqlite3_activate_see(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n#ifdef SQLITE_ENABLE_CEROD\n/*\n** Specify the activation key for a CEROD database.  Unless \n** activated, none of the CEROD routines will work.\n*/\nSQLITE_API void sqlite3_activate_cerod(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n/*\n** CAPI3REF: Suspend Execution For A Short Time\n**\n** The sqlite3_sleep() function causes the current thread to suspend execution\n** for at least a number of milliseconds specified in its parameter.\n**\n** If the operating system does not support sleep requests with\n** millisecond time resolution, then the time will be rounded up to\n** the nearest second. The number of milliseconds of sleep actually\n** requested from the operating system is returned.\n**\n** ^SQLite implements this interface by calling the xSleep()\n** method of the default [sqlite3_vfs] object.  If the xSleep() method\n** of the default VFS is not implemented correctly, or not implemented at\n** all, then the behavior of sqlite3_sleep() may deviate from the description\n** in the previous paragraphs.\n*/\nSQLITE_API int sqlite3_sleep(int);\n\n/*\n** CAPI3REF: Name Of The Folder Holding Temporary Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all temporary files\n** created by SQLite when using a built-in [sqlite3_vfs | VFS]\n** will be placed in that directory.)^  ^If this variable\n** is a NULL pointer, then SQLite performs a search for an appropriate\n** temporary file directory.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [temp_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [temp_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [temp_store_directory pragma] should be avoided.\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various\n** features that require the use of temporary files may fail.  Here is an\n** example of how to do this using C++ with the Windows Runtime:\n**\n** <blockquote><pre>\n** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->\n** &nbsp;     TemporaryFolder->Path->Data();\n** char zPathBuf&#91;MAX_PATH + 1&#93;;\n** memset(zPathBuf, 0, sizeof(zPathBuf));\n** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),\n** &nbsp;     NULL, NULL);\n** sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zPathBuf);\n** </pre></blockquote>\n*/\nSQLITE_API char *sqlite3_temp_directory;\n\n/*\n** CAPI3REF: Name Of The Folder Holding Database Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all database files\n** specified with a relative pathname and created or accessed by\n** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed\n** to be relative to that directory.)^ ^If this variable is a NULL\n** pointer, then SQLite assumes that all database files specified\n** with a relative pathname are relative to the current directory\n** for the process.  Only the windows VFS makes use of this global\n** variable; it is ignored by the unix VFS.\n**\n** Changing the value of this variable while a database connection is\n** open can result in a corrupt database.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [data_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [data_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [data_store_directory pragma] should be avoided.\n*/\nSQLITE_API char *sqlite3_data_directory;\n\n/*\n** CAPI3REF: Test For Auto-Commit Mode\n** KEYWORDS: {autocommit mode}\n**\n** ^The sqlite3_get_autocommit() interface returns non-zero or\n** zero if the given database connection is or is not in autocommit mode,\n** respectively.  ^Autocommit mode is on by default.\n** ^Autocommit mode is disabled by a [BEGIN] statement.\n** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].\n**\n** If certain kinds of errors occur on a statement within a multi-statement\n** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],\n** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the\n** transaction might be rolled back automatically.  The only way to\n** find out whether SQLite automatically rolled back the transaction after\n** an error is to use this function.\n**\n** If another thread changes the autocommit status of the database\n** connection while this routine is running, then the return value\n** is undefined.\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3*);\n\n/*\n** CAPI3REF: Find The Database Handle Of A Prepared Statement\n**\n** ^The sqlite3_db_handle interface returns the [database connection] handle\n** to which a [prepared statement] belongs.  ^The [database connection]\n** returned by sqlite3_db_handle is the same [database connection]\n** that was the first argument\n** to the [sqlite3_prepare_v2()] call (or its variants) that was used to\n** create the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Return The Filename For A Database Connection\n**\n** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename\n** associated with database N of connection D.  ^The main database file\n** has the name \"main\".  If there is no attached database N on the database\n** connection D, or if database N is a temporary or in-memory database, then\n** a NULL pointer is returned.\n**\n** ^The filename returned by this function is the output of the\n** xFullPathname method of the [VFS].  ^In other words, the filename\n** will be an absolute pathname, even if the filename used\n** to open the database originally was a URI or relative pathname.\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Determine if a database is read-only\n**\n** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N\n** of connection D is read-only, 0 if it is read/write, or -1 if N is not\n** the name of a database on connection D.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Find the next prepared statement\n**\n** ^This interface returns a pointer to the next [prepared statement] after\n** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL\n** then this interface returns a pointer to the first prepared statement\n** associated with the database connection pDb.  ^If no prepared statement\n** satisfies the conditions of this routine, it returns NULL.\n**\n** The [database connection] pointer D in a call to\n** [sqlite3_next_stmt(D,S)] must refer to an open database\n** connection and in particular must not be a NULL pointer.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Commit And Rollback Notification Callbacks\n**\n** ^The sqlite3_commit_hook() interface registers a callback\n** function to be invoked whenever a transaction is [COMMIT | committed].\n** ^Any callback set by a previous call to sqlite3_commit_hook()\n** for the same database connection is overridden.\n** ^The sqlite3_rollback_hook() interface registers a callback\n** function to be invoked whenever a transaction is [ROLLBACK | rolled back].\n** ^Any callback set by a previous call to sqlite3_rollback_hook()\n** for the same database connection is overridden.\n** ^The pArg argument is passed through to the callback.\n** ^If the callback on a commit hook function returns non-zero,\n** then the commit is converted into a rollback.\n**\n** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions\n** return the P argument from the previous call of the same function\n** on the same [database connection] D, or NULL for\n** the first call for each function on D.\n**\n** The commit and rollback hook callbacks are not reentrant.\n** The callback implementation must not do anything that will modify\n** the database connection that invoked the callback.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the commit\n** or rollback hook in the first place.\n** Note that running any other SQL statements, including SELECT statements,\n** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify\n** the database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^Registering a NULL function disables the callback.\n**\n** ^When the commit hook callback routine returns zero, the [COMMIT]\n** operation is allowed to continue normally.  ^If the commit hook\n** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].\n** ^The rollback hook is invoked on a rollback that results from a commit\n** hook returning non-zero, just as it would be with any other rollback.\n**\n** ^For the purposes of this API, a transaction is said to have been\n** rolled back if an explicit \"ROLLBACK\" statement is executed, or\n** an error or constraint causes an implicit rollback to occur.\n** ^The rollback callback is not invoked if a transaction is\n** automatically rolled back because the database connection is closed.\n**\n** See also the [sqlite3_update_hook()] interface.\n*/\nSQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);\nSQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);\n\n/*\n** CAPI3REF: Data Change Notification Callbacks\n**\n** ^The sqlite3_update_hook() interface registers a callback function\n** with the [database connection] identified by the first argument\n** to be invoked whenever a row is updated, inserted or deleted.\n** ^Any callback set by a previous call to this function\n** for the same database connection is overridden.\n**\n** ^The second argument is a pointer to the function to invoke when a\n** row is updated, inserted or deleted.\n** ^The first argument to the callback is a copy of the third argument\n** to sqlite3_update_hook().\n** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],\n** or [SQLITE_UPDATE], depending on the operation that caused the callback\n** to be invoked.\n** ^The third and fourth arguments to the callback contain pointers to the\n** database and table name containing the affected row.\n** ^The final callback parameter is the [rowid] of the row.\n** ^In the case of an update, this is the [rowid] after the update takes place.\n**\n** ^(The update hook is not invoked when internal system tables are\n** modified (i.e. sqlite_master and sqlite_sequence).)^\n**\n** ^In the current implementation, the update hook\n** is not invoked when duplication rows are deleted because of an\n** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook\n** invoked when rows are deleted using the [truncate optimization].\n** The exceptions defined in this paragraph might change in a future\n** release of SQLite.\n**\n** The update hook implementation must not do anything that will modify\n** the database connection that invoked the update hook.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the update hook.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^The sqlite3_update_hook(D,C,P) function\n** returns the P argument from the previous call\n** on the same [database connection] D, or NULL for\n** the first call on D.\n**\n** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]\n** interfaces.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3*, \n  void(*)(void *,int ,char const *,char const *,sqlite3_int64),\n  void*\n);\n\n/*\n** CAPI3REF: Enable Or Disable Shared Pager Cache\n**\n** ^(This routine enables or disables the sharing of the database cache\n** and schema data structures between [database connection | connections]\n** to the same database. Sharing is enabled if the argument is true\n** and disabled if the argument is false.)^\n**\n** ^Cache sharing is enabled and disabled for an entire process.\n** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,\n** sharing was enabled or disabled for each thread separately.\n**\n** ^(The cache sharing mode set by this interface effects all subsequent\n** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].\n** Existing database connections continue use the sharing mode\n** that was in effect at the time they were opened.)^\n**\n** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled\n** successfully.  An [error code] is returned otherwise.)^\n**\n** ^Shared cache is disabled by default. But this might change in\n** future releases of SQLite.  Applications that care about shared\n** cache setting should set it explicitly.\n**\n** See Also:  [SQLite Shared-Cache Mode]\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int);\n\n/*\n** CAPI3REF: Attempt To Free Heap Memory\n**\n** ^The sqlite3_release_memory() interface attempts to free N bytes\n** of heap memory by deallocating non-essential memory allocations\n** held by the database library.   Memory used to cache database\n** pages to improve performance is an example of non-essential memory.\n** ^sqlite3_release_memory() returns the number of bytes actually freed,\n** which might be more or less than the amount requested.\n** ^The sqlite3_release_memory() routine is a no-op returning zero\n** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** See also: [sqlite3_db_release_memory()]\n*/\nSQLITE_API int sqlite3_release_memory(int);\n\n/*\n** CAPI3REF: Free Memory Used By A Database Connection\n**\n** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap\n** memory as possible from database connection D. Unlike the\n** [sqlite3_release_memory()] interface, this interface is effect even\n** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is\n** omitted.\n**\n** See also: [sqlite3_release_memory()]\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3*);\n\n/*\n** CAPI3REF: Impose A Limit On Heap Size\n**\n** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the\n** soft limit on the amount of heap memory that may be allocated by SQLite.\n** ^SQLite strives to keep heap memory utilization below the soft heap\n** limit by reducing the number of pages held in the page cache\n** as heap memory usages approaches the limit.\n** ^The soft heap limit is \"soft\" because even though SQLite strives to stay\n** below the limit, it will exceed the limit rather than generate\n** an [SQLITE_NOMEM] error.  In other words, the soft heap limit \n** is advisory only.\n**\n** ^The return value from sqlite3_soft_heap_limit64() is the size of\n** the soft heap limit prior to the call, or negative in the case of an\n** error.  ^If the argument N is negative\n** then no change is made to the soft heap limit.  Hence, the current\n** size of the soft heap limit can be determined by invoking\n** sqlite3_soft_heap_limit64() with a negative argument.\n**\n** ^If the argument N is zero then the soft heap limit is disabled.\n**\n** ^(The soft heap limit is not enforced in the current implementation\n** if one or more of following conditions are true:\n**\n** <ul>\n** <li> The soft heap limit is set to zero.\n** <li> Memory accounting is disabled using a combination of the\n**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and\n**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.\n** <li> An alternative page cache implementation is specified using\n**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).\n** <li> The page cache allocates from its own memory pool supplied\n**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than\n**      from the heap.\n** </ul>)^\n**\n** Beginning with SQLite version 3.7.3, the soft heap limit is enforced\n** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]\n** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],\n** the soft heap limit is enforced on every memory allocation.  Without\n** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced\n** when memory is allocated by the page cache.  Testing suggests that because\n** the page cache is the predominate memory user in SQLite, most\n** applications will achieve adequate soft heap limit enforcement without\n** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** The circumstances under which SQLite will enforce the soft heap limit may\n** changes in future releases of SQLite.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);\n\n/*\n** CAPI3REF: Deprecated Soft Heap Limit Interface\n** DEPRECATED\n**\n** This is a deprecated version of the [sqlite3_soft_heap_limit64()]\n** interface.  This routine is provided for historical compatibility\n** only.  All new applications should use the\n** [sqlite3_soft_heap_limit64()] interface rather than this one.\n*/\nSQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);\n\n\n/*\n** CAPI3REF: Extract Metadata About A Column Of A Table\n**\n** ^This routine returns metadata about a specific column of a specific\n** database table accessible using the [database connection] handle\n** passed as the first function argument.\n**\n** ^The column is identified by the second, third and fourth parameters to\n** this function. ^The second parameter is either the name of the database\n** (i.e. \"main\", \"temp\", or an attached database) containing the specified\n** table or NULL. ^If it is NULL, then all attached databases are searched\n** for the table using the same algorithm used by the database engine to\n** resolve unqualified table references.\n**\n** ^The third and fourth parameters to this function are the table and column\n** name of the desired column, respectively. Neither of these parameters\n** may be NULL.\n**\n** ^Metadata is returned by writing to the memory locations passed as the 5th\n** and subsequent parameters to this function. ^Any of these arguments may be\n** NULL, in which case the corresponding element of metadata is omitted.\n**\n** ^(<blockquote>\n** <table border=\"1\">\n** <tr><th> Parameter <th> Output<br>Type <th>  Description\n**\n** <tr><td> 5th <td> const char* <td> Data type\n** <tr><td> 6th <td> const char* <td> Name of default collation sequence\n** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint\n** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY\n** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]\n** </table>\n** </blockquote>)^\n**\n** ^The memory pointed to by the character pointers returned for the\n** declaration type and collation sequence is valid only until the next\n** call to any SQLite API function.\n**\n** ^If the specified table is actually a view, an [error code] is returned.\n**\n** ^If the specified column is \"rowid\", \"oid\" or \"_rowid_\" and an\n** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output\n** parameters are set for the explicitly declared column. ^(If there is no\n** explicitly declared [INTEGER PRIMARY KEY] column, then the output\n** parameters are set as follows:\n**\n** <pre>\n**     data type: \"INTEGER\"\n**     collation sequence: \"BINARY\"\n**     not null: 0\n**     primary key: 1\n**     auto increment: 0\n** </pre>)^\n**\n** ^(This function may load one or more schemas from database files. If an\n** error occurs during this process, or if the requested table or column\n** cannot be found, an [error code] is returned and an error message left\n** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^\n**\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.\n*/\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n);\n\n/*\n** CAPI3REF: Load An Extension\n**\n** ^This interface loads an SQLite extension library from the named file.\n**\n** ^The sqlite3_load_extension() interface attempts to load an\n** SQLite extension library contained in the file zFile.\n**\n** ^The entry point is zProc.\n** ^zProc may be 0, in which case the name of the entry point\n** defaults to \"sqlite3_extension_init\".\n** ^The sqlite3_load_extension() interface returns\n** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.\n** ^If an error occurs and pzErrMsg is not 0, then the\n** [sqlite3_load_extension()] interface shall attempt to\n** fill *pzErrMsg with error message text stored in memory\n** obtained from [sqlite3_malloc()]. The calling function\n** should free this memory by calling [sqlite3_free()].\n**\n** ^Extension loading must be enabled using\n** [sqlite3_enable_load_extension()] prior to calling this API,\n** otherwise an error will be returned.\n**\n** See also the [load_extension() SQL function].\n*/\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Derived from zFile if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n);\n\n/*\n** CAPI3REF: Enable Or Disable Extension Loading\n**\n** ^So as not to open security holes in older applications that are\n** unprepared to deal with extension loading, and as a means of disabling\n** extension loading while evaluating user-entered SQL, the following API\n** is provided to turn the [sqlite3_load_extension()] mechanism on and off.\n**\n** ^Extension loading is off by default. See ticket #1863.\n** ^Call the sqlite3_enable_load_extension() routine with onoff==1\n** to turn extension loading on and call it with onoff==0 to turn\n** it back off again.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);\n\n/*\n** CAPI3REF: Automatically Load Statically Linked Extensions\n**\n** ^This interface causes the xEntryPoint() function to be invoked for\n** each new [database connection] that is created.  The idea here is that\n** xEntryPoint() is the entry point for a statically linked SQLite extension\n** that is to be automatically loaded into all new database connections.\n**\n** ^(Even though the function prototype shows that xEntryPoint() takes\n** no arguments and returns void, SQLite invokes xEntryPoint() with three\n** arguments and expects and integer result as if the signature of the\n** entry point where as follows:\n**\n** <blockquote><pre>\n** &nbsp;  int xEntryPoint(\n** &nbsp;    sqlite3 *db,\n** &nbsp;    const char **pzErrMsg,\n** &nbsp;    const struct sqlite3_api_routines *pThunk\n** &nbsp;  );\n** </pre></blockquote>)^\n**\n** If the xEntryPoint routine encounters an error, it should make *pzErrMsg\n** point to an appropriate error message (obtained from [sqlite3_mprintf()])\n** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg\n** is NULL before calling the xEntryPoint().  ^SQLite will invoke\n** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any\n** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],\n** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.\n**\n** ^Calling sqlite3_auto_extension(X) with an entry point X that is already\n** on the list of automatic extensions is a harmless no-op. ^No entry point\n** will be called more than once for each database connection that is opened.\n**\n** See also: [sqlite3_reset_auto_extension()].\n*/\nSQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Reset Automatic Extension Loading\n**\n** ^This interface disables all automatic extensions previously\n** registered using [sqlite3_auto_extension()].\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void);\n\n/*\n** The interface to the virtual-table mechanism is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** Structures used by the virtual table interface\n*/\ntypedef struct sqlite3_vtab sqlite3_vtab;\ntypedef struct sqlite3_index_info sqlite3_index_info;\ntypedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;\ntypedef struct sqlite3_module sqlite3_module;\n\n/*\n** CAPI3REF: Virtual Table Object\n** KEYWORDS: sqlite3_module {virtual table module}\n**\n** This structure, sometimes called a \"virtual table module\", \n** defines the implementation of a [virtual tables].  \n** This structure consists mostly of methods for the module.\n**\n** ^A virtual table module is created by filling in a persistent\n** instance of this structure and passing a pointer to that instance\n** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].\n** ^The registration remains valid until it is replaced by a different\n** module or until the [database connection] closes.  The content\n** of this structure must not change while it is registered with\n** any database connection.\n*/\nstruct sqlite3_module {\n  int iVersion;\n  int (*xCreate)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xConnect)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);\n  int (*xDisconnect)(sqlite3_vtab *pVTab);\n  int (*xDestroy)(sqlite3_vtab *pVTab);\n  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);\n  int (*xClose)(sqlite3_vtab_cursor*);\n  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,\n                int argc, sqlite3_value **argv);\n  int (*xNext)(sqlite3_vtab_cursor*);\n  int (*xEof)(sqlite3_vtab_cursor*);\n  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);\n  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);\n  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);\n  int (*xBegin)(sqlite3_vtab *pVTab);\n  int (*xSync)(sqlite3_vtab *pVTab);\n  int (*xCommit)(sqlite3_vtab *pVTab);\n  int (*xRollback)(sqlite3_vtab *pVTab);\n  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,\n                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),\n                       void **ppArg);\n  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);\n  /* The methods above are in version 1 of the sqlite_module object. Those \n  ** below are for version 2 and greater. */\n  int (*xSavepoint)(sqlite3_vtab *pVTab, int);\n  int (*xRelease)(sqlite3_vtab *pVTab, int);\n  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);\n};\n\n/*\n** CAPI3REF: Virtual Table Indexing Information\n** KEYWORDS: sqlite3_index_info\n**\n** The sqlite3_index_info structure and its substructures is used as part\n** of the [virtual table] interface to\n** pass information into and receive the reply from the [xBestIndex]\n** method of a [virtual table module].  The fields under **Inputs** are the\n** inputs to xBestIndex and are read-only.  xBestIndex inserts its\n** results into the **Outputs** fields.\n**\n** ^(The aConstraint[] array records WHERE clause constraints of the form:\n**\n** <blockquote>column OP expr</blockquote>\n**\n** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is\n** stored in aConstraint[].op using one of the\n** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^\n** ^(The index of the column is stored in\n** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the\n** expr on the right-hand side can be evaluated (and thus the constraint\n** is usable) and false if it cannot.)^\n**\n** ^The optimizer automatically inverts terms of the form \"expr OP column\"\n** and makes other simplifications to the WHERE clause in an attempt to\n** get as many WHERE clause terms into the form shown above as possible.\n** ^The aConstraint[] array only reports WHERE clause terms that are\n** relevant to the particular virtual table being queried.\n**\n** ^Information about the ORDER BY clause is stored in aOrderBy[].\n** ^Each term of aOrderBy records a column of the ORDER BY clause.\n**\n** The [xBestIndex] method must fill aConstraintUsage[] with information\n** about what parameters to pass to xFilter.  ^If argvIndex>0 then\n** the right-hand side of the corresponding aConstraint[] is evaluated\n** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit\n** is true, then the constraint is assumed to be fully handled by the\n** virtual table and is not checked again by SQLite.)^\n**\n** ^The idxNum and idxPtr values are recorded and passed into the\n** [xFilter] method.\n** ^[sqlite3_free()] is used to free idxPtr if and only if\n** needToFreeIdxPtr is true.\n**\n** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in\n** the correct order to satisfy the ORDER BY clause so that no separate\n** sorting step is required.\n**\n** ^The estimatedCost value is an estimate of the cost of doing the\n** particular lookup.  A full scan of a table with N entries should have\n** a cost of N.  A binary search of a table of N entries should have a\n** cost of approximately log(N).\n*/\nstruct sqlite3_index_info {\n  /* Inputs */\n  int nConstraint;           /* Number of entries in aConstraint */\n  struct sqlite3_index_constraint {\n     int iColumn;              /* Column on left-hand side of constraint */\n     unsigned char op;         /* Constraint operator */\n     unsigned char usable;     /* True if this constraint is usable */\n     int iTermOffset;          /* Used internally - xBestIndex should ignore */\n  } *aConstraint;            /* Table of WHERE clause constraints */\n  int nOrderBy;              /* Number of terms in the ORDER BY clause */\n  struct sqlite3_index_orderby {\n     int iColumn;              /* Column number */\n     unsigned char desc;       /* True for DESC.  False for ASC. */\n  } *aOrderBy;               /* The ORDER BY clause */\n  /* Outputs */\n  struct sqlite3_index_constraint_usage {\n    int argvIndex;           /* if >0, constraint is part of argv to xFilter */\n    unsigned char omit;      /* Do not code a test for this constraint */\n  } *aConstraintUsage;\n  int idxNum;                /* Number used to identify the index */\n  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */\n  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */\n  int orderByConsumed;       /* True if output is already ordered */\n  double estimatedCost;      /* Estimated cost of using this index */\n};\n\n/*\n** CAPI3REF: Virtual Table Constraint Operator Codes\n**\n** These macros defined the allowed values for the\n** [sqlite3_index_info].aConstraint[].op field.  Each value represents\n** an operator that is part of a constraint term in the wHERE clause of\n** a query that uses a [virtual table].\n*/\n#define SQLITE_INDEX_CONSTRAINT_EQ    2\n#define SQLITE_INDEX_CONSTRAINT_GT    4\n#define SQLITE_INDEX_CONSTRAINT_LE    8\n#define SQLITE_INDEX_CONSTRAINT_LT    16\n#define SQLITE_INDEX_CONSTRAINT_GE    32\n#define SQLITE_INDEX_CONSTRAINT_MATCH 64\n\n/*\n** CAPI3REF: Register A Virtual Table Implementation\n**\n** ^These routines are used to register a new [virtual table module] name.\n** ^Module names must be registered before\n** creating a new [virtual table] using the module and before using a\n** preexisting [virtual table] for the module.\n**\n** ^The module name is registered on the [database connection] specified\n** by the first parameter.  ^The name of the module is given by the \n** second parameter.  ^The third parameter is a pointer to\n** the implementation of the [virtual table module].   ^The fourth\n** parameter is an arbitrary client data pointer that is passed through\n** into the [xCreate] and [xConnect] methods of the virtual table module\n** when a new virtual table is be being created or reinitialized.\n**\n** ^The sqlite3_create_module_v2() interface has a fifth parameter which\n** is a pointer to a destructor for the pClientData.  ^SQLite will\n** invoke the destructor function (if it is not NULL) when SQLite\n** no longer needs the pClientData pointer.  ^The destructor will also\n** be invoked if the call to sqlite3_create_module_v2() fails.\n** ^The sqlite3_create_module()\n** interface is equivalent to sqlite3_create_module_v2() with a NULL\n** destructor.\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData          /* Client data for xCreate/xConnect */\n);\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData,         /* Client data for xCreate/xConnect */\n  void(*xDestroy)(void*)     /* Module destructor function */\n);\n\n/*\n** CAPI3REF: Virtual Table Instance Object\n** KEYWORDS: sqlite3_vtab\n**\n** Every [virtual table module] implementation uses a subclass\n** of this object to describe a particular instance\n** of the [virtual table].  Each subclass will\n** be tailored to the specific needs of the module implementation.\n** The purpose of this superclass is to define certain fields that are\n** common to all module implementations.\n**\n** ^Virtual tables methods can set an error message by assigning a\n** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should\n** take care that any prior string is freed by a call to [sqlite3_free()]\n** prior to assigning a new string to zErrMsg.  ^After the error message\n** is delivered up to the client application, the string will be automatically\n** freed by sqlite3_free() and the zErrMsg field will be zeroed.\n*/\nstruct sqlite3_vtab {\n  const sqlite3_module *pModule;  /* The module for this virtual table */\n  int nRef;                       /* NO LONGER USED */\n  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Virtual Table Cursor Object\n** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}\n**\n** Every [virtual table module] implementation uses a subclass of the\n** following structure to describe cursors that point into the\n** [virtual table] and are used\n** to loop through the virtual table.  Cursors are created using the\n** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed\n** by the [sqlite3_module.xClose | xClose] method.  Cursors are used\n** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods\n** of the module.  Each module implementation will define\n** the content of a cursor structure to suit its own needs.\n**\n** This superclass exists in order to define fields of the cursor that\n** are common to all implementations.\n*/\nstruct sqlite3_vtab_cursor {\n  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Declare The Schema Of A Virtual Table\n**\n** ^The [xCreate] and [xConnect] methods of a\n** [virtual table module] call this interface\n** to declare the format (the names and datatypes of the columns) of\n** the virtual tables they implement.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);\n\n/*\n** CAPI3REF: Overload A Function For A Virtual Table\n**\n** ^(Virtual tables can provide alternative implementations of functions\n** using the [xFindFunction] method of the [virtual table module].  \n** But global versions of those functions\n** must exist in order to be overloaded.)^\n**\n** ^(This API makes sure a global version of a function with a particular\n** name and number of parameters exists.  If no such function exists\n** before this API is called, a new function is created.)^  ^The implementation\n** of the new function always causes an exception to be thrown.  So\n** the new function is not good for anything by itself.  Its only\n** purpose is to be a placeholder function that can be overloaded\n** by a [virtual table].\n*/\nSQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);\n\n/*\n** The interface to the virtual-table mechanism defined above (back up\n** to a comment remarkably similar to this one) is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** CAPI3REF: A Handle To An Open BLOB\n** KEYWORDS: {BLOB handle} {BLOB handles}\n**\n** An instance of this object represents an open BLOB on which\n** [sqlite3_blob_open | incremental BLOB I/O] can be performed.\n** ^Objects of this type are created by [sqlite3_blob_open()]\n** and destroyed by [sqlite3_blob_close()].\n** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces\n** can be used to read or write small subsections of the BLOB.\n** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.\n*/\ntypedef struct sqlite3_blob sqlite3_blob;\n\n/*\n** CAPI3REF: Open A BLOB For Incremental I/O\n**\n** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located\n** in row iRow, column zColumn, table zTable in database zDb;\n** in other words, the same BLOB that would be selected by:\n**\n** <pre>\n**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;\n** </pre>)^\n**\n** ^If the flags parameter is non-zero, then the BLOB is opened for read\n** and write access. ^If it is zero, the BLOB is opened for read access.\n** ^It is not possible to open a column that is part of an index or primary \n** key for writing. ^If [foreign key constraints] are enabled, it is \n** not possible to open a column that is part of a [child key] for writing.\n**\n** ^Note that the database name is not the filename that contains\n** the database but rather the symbolic name of the database that\n** appears after the AS keyword when the database is connected using [ATTACH].\n** ^For the main database file, the database name is \"main\".\n** ^For TEMP tables, the database name is \"temp\".\n**\n** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written\n** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set\n** to be a null pointer.)^\n** ^This function sets the [database connection] error code and message\n** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related\n** functions. ^Note that the *ppBlob variable is always initialized in a\n** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob\n** regardless of the success or failure of this routine.\n**\n** ^(If the row that a BLOB handle points to is modified by an\n** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects\n** then the BLOB handle is marked as \"expired\".\n** This is true if any column of the row is changed, even a column\n** other than the one the BLOB handle is open on.)^\n** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for\n** an expired BLOB handle fail with a return code of [SQLITE_ABORT].\n** ^(Changes written into a BLOB prior to the BLOB expiring are not\n** rolled back by the expiration of the BLOB.  Such changes will eventually\n** commit if the transaction continues to completion.)^\n**\n** ^Use the [sqlite3_blob_bytes()] interface to determine the size of\n** the opened blob.  ^The size of a blob may not be changed by this\n** interface.  Use the [UPDATE] SQL command to change the size of a\n** blob.\n**\n** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces\n** and the built-in [zeroblob] SQL function can be used, if desired,\n** to create an empty, zero-filled blob in which to read or write using\n** this interface.\n**\n** To avoid a resource leak, every open [BLOB handle] should eventually\n** be released by a call to [sqlite3_blob_close()].\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3*,\n  const char *zDb,\n  const char *zTable,\n  const char *zColumn,\n  sqlite3_int64 iRow,\n  int flags,\n  sqlite3_blob **ppBlob\n);\n\n/*\n** CAPI3REF: Move a BLOB Handle to a New Row\n**\n** ^This function is used to move an existing blob handle so that it points\n** to a different row of the same database table. ^The new row is identified\n** by the rowid value passed as the second argument. Only the row can be\n** changed. ^The database, table and column on which the blob handle is open\n** remain the same. Moving an existing blob handle to a new row can be\n** faster than closing the existing handle and opening a new one.\n**\n** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -\n** it must exist and there must be either a blob or text value stored in\n** the nominated column.)^ ^If the new row is not present in the table, or if\n** it does not contain a blob or text value, or if another error occurs, an\n** SQLite error code is returned and the blob handle is considered aborted.\n** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or\n** [sqlite3_blob_reopen()] on an aborted blob handle immediately return\n** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle\n** always returns zero.\n**\n** ^This function sets the database handle error code and message.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);\n\n/*\n** CAPI3REF: Close A BLOB Handle\n**\n** ^Closes an open [BLOB handle].\n**\n** ^Closing a BLOB shall cause the current transaction to commit\n** if there are no other BLOBs, no pending prepared statements, and the\n** database connection is in [autocommit mode].\n** ^If any writes were made to the BLOB, they might be held in cache\n** until the close operation if they will fit.\n**\n** ^(Closing the BLOB often forces the changes\n** out to disk and so if any I/O errors occur, they will likely occur\n** at the time when the BLOB is closed.  Any errors that occur during\n** closing are reported as a non-zero return value.)^\n**\n** ^(The BLOB is closed unconditionally.  Even if this routine returns\n** an error code, the BLOB is still closed.)^\n**\n** ^Calling this routine with a null pointer (such as would be returned\n** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *);\n\n/*\n** CAPI3REF: Return The Size Of An Open BLOB\n**\n** ^Returns the size in bytes of the BLOB accessible via the \n** successfully opened [BLOB handle] in its only argument.  ^The\n** incremental blob I/O routines can only read or overwriting existing\n** blob content; they cannot change the size of a blob.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);\n\n/*\n** CAPI3REF: Read Data From A BLOB Incrementally\n**\n** ^(This function is used to read data from an open [BLOB handle] into a\n** caller-supplied buffer. N bytes of data are copied into buffer Z\n** from the open BLOB, starting at offset iOffset.)^\n**\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is\n** less than zero, [SQLITE_ERROR] is returned and no data is read.\n** ^The size of the blob (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to read from an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].\n**\n** ^(On success, sqlite3_blob_read() returns SQLITE_OK.\n** Otherwise, an [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);\n\n/*\n** CAPI3REF: Write Data Into A BLOB Incrementally\n**\n** ^This function is used to write data into an open [BLOB handle] from a\n** caller-supplied buffer. ^N bytes of data are copied from the buffer Z\n** into the open BLOB, starting at offset iOffset.\n**\n** ^If the [BLOB handle] passed as the first argument was not opened for\n** writing (the flags parameter to [sqlite3_blob_open()] was zero),\n** this function returns [SQLITE_READONLY].\n**\n** ^This function may only modify the contents of the BLOB; it is\n** not possible to increase the size of a BLOB using this API.\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is written.  ^If N is\n** less than zero [SQLITE_ERROR] is returned and no data is written.\n** The size of the BLOB (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to write to an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred\n** before the [BLOB handle] expired are not rolled back by the\n** expiration of the handle, though of course those changes might\n** have been overwritten by the statement that expired the BLOB handle\n** or by other independent statements.\n**\n** ^(On success, sqlite3_blob_write() returns SQLITE_OK.\n** Otherwise, an  [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_read()].\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);\n\n/*\n** CAPI3REF: Virtual File System Objects\n**\n** A virtual filesystem (VFS) is an [sqlite3_vfs] object\n** that SQLite uses to interact\n** with the underlying operating system.  Most SQLite builds come with a\n** single default VFS that is appropriate for the host computer.\n** New VFSes can be registered and existing VFSes can be unregistered.\n** The following interfaces are provided.\n**\n** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.\n** ^Names are case sensitive.\n** ^Names are zero-terminated UTF-8 strings.\n** ^If there is no match, a NULL pointer is returned.\n** ^If zVfsName is NULL then the default VFS is returned.\n**\n** ^New VFSes are registered with sqlite3_vfs_register().\n** ^Each new VFS becomes the default VFS if the makeDflt flag is set.\n** ^The same VFS can be registered multiple times without injury.\n** ^To make an existing VFS into the default VFS, register it again\n** with the makeDflt flag set.  If two different VFSes with the\n** same name are registered, the behavior is undefined.  If a\n** VFS is registered with a name that is NULL or an empty string,\n** then the behavior is undefined.\n**\n** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.\n** ^(If the default VFS is unregistered, another VFS is chosen as\n** the default.  The choice for the new VFS is arbitrary.)^\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);\n\n/*\n** CAPI3REF: Mutexes\n**\n** The SQLite core uses these routines for thread\n** synchronization. Though they are intended for internal\n** use by SQLite, code that links against SQLite is\n** permitted to use any of these routines.\n**\n** The SQLite source code contains multiple implementations\n** of these mutex routines.  An appropriate implementation\n** is selected automatically at compile-time.  ^(The following\n** implementations are available in the SQLite core:\n**\n** <ul>\n** <li>   SQLITE_MUTEX_PTHREADS\n** <li>   SQLITE_MUTEX_W32\n** <li>   SQLITE_MUTEX_NOOP\n** </ul>)^\n**\n** ^The SQLITE_MUTEX_NOOP implementation is a set of routines\n** that does no real locking and is appropriate for use in\n** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and\n** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix\n** and Windows.\n**\n** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor\n** macro defined (with \"-DSQLITE_MUTEX_APPDEF=1\"), then no mutex\n** implementation is included with the library. In this case the\n** application must supply a custom mutex implementation using the\n** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function\n** before calling sqlite3_initialize() or any other public sqlite3_\n** function that calls sqlite3_initialize().)^\n**\n** ^The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it. ^If it returns NULL\n** that means that a mutex could not be allocated.  ^SQLite\n** will unwind its stack and return an error.  ^(The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_MEM2\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_LRU2\n** </ul>)^\n**\n** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)\n** cause sqlite3_mutex_alloc() to create\n** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  ^SQLite will only request a recursive mutex in\n** cases where it really needs one.  ^If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other\n** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return\n** a pointer to a static preexisting mutex.  ^Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  ^But for the static\n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n**\n** ^The sqlite3_mutex_free() routine deallocates a previously\n** allocated dynamic mutex.  ^SQLite is careful to deallocate every\n** dynamic mutex that it allocates.  The dynamic mutexes must not be in\n** use when they are deallocated.  Attempting to deallocate a static\n** mutex results in undefined behavior.  ^SQLite never deallocates\n** a static mutex.\n**\n** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  ^If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]\n** upon successful entry.  ^(Mutexes created using\n** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.\n** In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.)^  ^(If the same thread tries to enter any other\n** kind of mutex more than once, the behavior is undefined.\n** SQLite will never exhibit\n** such behavior in its own use of mutexes.)^\n**\n** ^(Some systems (for example, Windows 95) do not support the operation\n** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()\n** will always return SQLITE_BUSY.  The SQLite core only ever uses\n** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^\n**\n** ^The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.   ^(The behavior\n** is undefined if the mutex is not currently entered by the\n** calling thread or is not currently allocated.  SQLite will\n** never do either.)^\n**\n** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or\n** sqlite3_mutex_leave() is a NULL pointer, then all three routines\n** behave as no-ops.\n**\n** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);\n\n/*\n** CAPI3REF: Mutex Methods Object\n**\n** An instance of this structure defines the low-level routines\n** used to allocate and use mutexes.\n**\n** Usually, the default mutex implementations provided by SQLite are\n** sufficient, however the user has the option of substituting a custom\n** implementation for specialized deployments or systems for which SQLite\n** does not provide a suitable implementation. In this case, the user\n** creates and populates an instance of this structure to pass\n** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.\n** Additionally, an instance of this structure can be used as an\n** output variable when querying the system for the current mutex\n** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.\n**\n** ^The xMutexInit method defined by this structure is invoked as\n** part of system initialization by the sqlite3_initialize() function.\n** ^The xMutexInit routine is called by SQLite exactly once for each\n** effective call to [sqlite3_initialize()].\n**\n** ^The xMutexEnd method defined by this structure is invoked as\n** part of system shutdown by the sqlite3_shutdown() function. The\n** implementation of this method is expected to release all outstanding\n** resources obtained by the mutex methods implementation, especially\n** those obtained by the xMutexInit method.  ^The xMutexEnd()\n** interface is invoked exactly once for each call to [sqlite3_shutdown()].\n**\n** ^(The remaining seven methods defined by this structure (xMutexAlloc,\n** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and\n** xMutexNotheld) implement the following interfaces (respectively):\n**\n** <ul>\n**   <li>  [sqlite3_mutex_alloc()] </li>\n**   <li>  [sqlite3_mutex_free()] </li>\n**   <li>  [sqlite3_mutex_enter()] </li>\n**   <li>  [sqlite3_mutex_try()] </li>\n**   <li>  [sqlite3_mutex_leave()] </li>\n**   <li>  [sqlite3_mutex_held()] </li>\n**   <li>  [sqlite3_mutex_notheld()] </li>\n** </ul>)^\n**\n** The only difference is that the public sqlite3_XXX functions enumerated\n** above silently ignore any invocations that pass a NULL pointer instead\n** of a valid mutex handle. The implementations of the methods defined\n** by this structure are not required to handle this case, the results\n** of passing a NULL pointer instead of a valid mutex handle are undefined\n** (i.e. it is acceptable to provide an implementation that segfaults if\n** it is passed a NULL pointer).\n**\n** The xMutexInit() method must be threadsafe.  ^It must be harmless to\n** invoke xMutexInit() multiple times within the same process and without\n** intervening calls to xMutexEnd().  Second and subsequent calls to\n** xMutexInit() must be no-ops.\n**\n** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]\n** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory\n** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite\n** memory allocation for a fast or recursive mutex.\n**\n** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is\n** called, but only if the prior call to xMutexInit returned SQLITE_OK.\n** If xMutexInit fails in any way, it is expected to clean up after itself\n** prior to returning.\n*/\ntypedef struct sqlite3_mutex_methods sqlite3_mutex_methods;\nstruct sqlite3_mutex_methods {\n  int (*xMutexInit)(void);\n  int (*xMutexEnd)(void);\n  sqlite3_mutex *(*xMutexAlloc)(int);\n  void (*xMutexFree)(sqlite3_mutex *);\n  void (*xMutexEnter)(sqlite3_mutex *);\n  int (*xMutexTry)(sqlite3_mutex *);\n  void (*xMutexLeave)(sqlite3_mutex *);\n  int (*xMutexHeld)(sqlite3_mutex *);\n  int (*xMutexNotheld)(sqlite3_mutex *);\n};\n\n/*\n** CAPI3REF: Mutex Verification Routines\n**\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines\n** are intended for use inside assert() statements.  ^The SQLite core\n** never uses these routines except inside an assert() and applications\n** are advised to follow the lead of the core.  ^The SQLite core only\n** provides implementations for these routines when it is compiled\n** with the SQLITE_DEBUG flag.  ^External mutex implementations\n** are only required to provide these routines if SQLITE_DEBUG is\n** defined and if NDEBUG is not defined.\n**\n** ^These routines should return true if the mutex in their argument\n** is held or not held, respectively, by the calling thread.\n**\n** ^The implementation is not required to provide versions of these\n** routines that actually work. If the implementation does not provide working\n** versions of these routines, it should at least provide stubs that always\n** return true so that one does not get spurious assertion failures.\n**\n** ^If the argument to sqlite3_mutex_held() is a NULL pointer then\n** the routine should return 1.   This seems counter-intuitive since\n** clearly the mutex cannot be held if it does not exist.  But\n** the reason the mutex does not exist is because the build is not\n** using mutexes.  And we do not want the assert() containing the\n** call to sqlite3_mutex_held() to fail, so a non-zero return is\n** the appropriate thing to do.  ^The sqlite3_mutex_notheld()\n** interface should also return 1 when given a NULL pointer.\n*/\n#ifndef NDEBUG\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);\n#endif\n\n/*\n** CAPI3REF: Mutex Types\n**\n** The [sqlite3_mutex_alloc()] interface takes a single argument\n** which is one of these integer constants.\n**\n** The set of static mutexes may change from one SQLite release to the\n** next.  Applications that override the built-in mutex logic must be\n** prepared to accommodate additional static mutexes.\n*/\n#define SQLITE_MUTEX_FAST             0\n#define SQLITE_MUTEX_RECURSIVE        1\n#define SQLITE_MUTEX_STATIC_MASTER    2\n#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */\n#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */\n#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */\n#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */\n#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */\n\n/*\n** CAPI3REF: Retrieve the mutex for a database connection\n**\n** ^This interface returns a pointer the [sqlite3_mutex] object that \n** serializes access to the [database connection] given in the argument\n** when the [threading mode] is Serialized.\n** ^If the [threading mode] is Single-thread or Multi-thread then this\n** routine returns a NULL pointer.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);\n\n/*\n** CAPI3REF: Low-Level Control Of Database Files\n**\n** ^The [sqlite3_file_control()] interface makes a direct call to the\n** xFileControl method for the [sqlite3_io_methods] object associated\n** with a particular database identified by the second argument. ^The\n** name of the database is \"main\" for the main database or \"temp\" for the\n** TEMP database, or the name that appears after the AS keyword for\n** databases that are added using the [ATTACH] SQL command.\n** ^A NULL pointer can be used in place of \"main\" to refer to the\n** main database file.\n** ^The third and fourth parameters to this routine\n** are passed directly through to the second and third parameters of\n** the xFileControl method.  ^The return value of the xFileControl\n** method becomes the return value of this routine.\n**\n** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes\n** a pointer to the underlying [sqlite3_file] object to be written into\n** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER\n** case is a short-circuit path which does not actually invoke the\n** underlying sqlite3_io_methods.xFileControl method.\n**\n** ^If the second parameter (zDbName) does not match the name of any\n** open database file, then SQLITE_ERROR is returned.  ^This error\n** code is not remembered and will not be recalled by [sqlite3_errcode()]\n** or [sqlite3_errmsg()].  The underlying xFileControl method might\n** also return SQLITE_ERROR.  There is no way to distinguish between\n** an incorrect zDbName and an SQLITE_ERROR return from the underlying\n** xFileControl method.\n**\n** See also: [SQLITE_FCNTL_LOCKSTATE]\n*/\nSQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);\n\n/*\n** CAPI3REF: Testing Interface\n**\n** ^The sqlite3_test_control() interface is used to read out internal\n** state of SQLite and to inject faults into SQLite for testing\n** purposes.  ^The first parameter is an operation code that determines\n** the number, meaning, and operation of all subsequent parameters.\n**\n** This interface is not for use by applications.  It exists solely\n** for verifying the correct operation of the SQLite library.  Depending\n** on how the SQLite library is compiled, this interface might not exist.\n**\n** The details of the operation codes, their meanings, the parameters\n** they take, and what they do are all subject to change without notice.\n** Unlike most of the SQLite API, this function is not guaranteed to\n** operate consistently from one release to the next.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...);\n\n/*\n** CAPI3REF: Testing Interface Operation Codes\n**\n** These constants are the valid operation code parameters used\n** as the first argument to [sqlite3_test_control()].\n**\n** These parameters and their meanings are subject to change\n** without notice.  These values are for testing purposes only.\n** Applications should not use any of these parameters or the\n** [sqlite3_test_control()] interface.\n*/\n#define SQLITE_TESTCTRL_FIRST                    5\n#define SQLITE_TESTCTRL_PRNG_SAVE                5\n#define SQLITE_TESTCTRL_PRNG_RESTORE             6\n#define SQLITE_TESTCTRL_PRNG_RESET               7\n#define SQLITE_TESTCTRL_BITVEC_TEST              8\n#define SQLITE_TESTCTRL_FAULT_INSTALL            9\n#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10\n#define SQLITE_TESTCTRL_PENDING_BYTE            11\n#define SQLITE_TESTCTRL_ASSERT                  12\n#define SQLITE_TESTCTRL_ALWAYS                  13\n#define SQLITE_TESTCTRL_RESERVE                 14\n#define SQLITE_TESTCTRL_OPTIMIZATIONS           15\n#define SQLITE_TESTCTRL_ISKEYWORD               16\n#define SQLITE_TESTCTRL_SCRATCHMALLOC           17\n#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18\n#define SQLITE_TESTCTRL_EXPLAIN_STMT            19\n#define SQLITE_TESTCTRL_LAST                    19\n\n/*\n** CAPI3REF: SQLite Runtime Status\n**\n** ^This interface is used to retrieve runtime status information\n** about the performance of SQLite, and optionally to reset various\n** highwater marks.  ^The first argument is an integer code for\n** the specific parameter to measure.  ^(Recognized integer codes\n** are of the form [status parameters | SQLITE_STATUS_...].)^\n** ^The current value of the parameter is returned into *pCurrent.\n** ^The highest recorded value is returned in *pHighwater.  ^If the\n** resetFlag is true, then the highest record value is reset after\n** *pHighwater is written.  ^(Some parameters do not record the highest\n** value.  For those parameters\n** nothing is written into *pHighwater and the resetFlag is ignored.)^\n** ^(Other parameters record only the highwater mark and not the current\n** value.  For these latter parameters nothing is written into *pCurrent.)^\n**\n** ^The sqlite3_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** This routine is threadsafe but is not atomic.  This routine can be\n** called while other threads are running the same or different SQLite\n** interfaces.  However the values returned in *pCurrent and\n** *pHighwater reflect the status of SQLite at different points in time\n** and it is possible that another thread might change the parameter\n** in between the times when *pCurrent and *pHighwater are written.\n**\n** See also: [sqlite3_db_status()]\n*/\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);\n\n\n/*\n** CAPI3REF: Status Parameters\n** KEYWORDS: {status parameters}\n**\n** These integer constants designate various run-time status parameters\n** that can be returned by [sqlite3_status()].\n**\n** <dl>\n** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>\n** <dd>This parameter is the current amount of memory checked out\n** using [sqlite3_malloc()], either directly or indirectly.  The\n** figure includes calls made to [sqlite3_malloc()] by the application\n** and internal memory usage by the SQLite library.  Scratch memory\n** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache\n** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in\n** this parameter.  The amount returned is the sum of the allocation\n** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their\n** internal equivalents).  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>\n** <dd>This parameter records the number of separate memory allocations\n** currently checked out.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>\n** <dd>This parameter returns the number of pages used out of the\n** [pagecache memory allocator] that was configured using \n** [SQLITE_CONFIG_PAGECACHE].  The\n** value returned is in pages, not in bytes.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] \n** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of page cache\n** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The\n** returned value includes allocations that overflowed because they\n** where too large (they were larger than the \"sz\" parameter to\n** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because\n** no space was left in the page cache.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [pagecache memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>\n** <dd>This parameter returns the number of allocations used out of the\n** [scratch memory allocator] configured using\n** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not\n** in bytes.  Since a single thread may only have one scratch allocation\n** outstanding at time, this parameter also reports the number of threads\n** using scratch memory at the same time.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of scratch memory\n** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The values\n** returned include overflows because the requested allocation was too\n** larger (that is, because the requested allocation was larger than the\n** \"sz\" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer\n** slots were available.\n** </dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [scratch memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>\n** <dd>This parameter records the deepest parser stack.  It is only\n** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^\n** </dl>\n**\n** New status parameters may be added from time to time.\n*/\n#define SQLITE_STATUS_MEMORY_USED          0\n#define SQLITE_STATUS_PAGECACHE_USED       1\n#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2\n#define SQLITE_STATUS_SCRATCH_USED         3\n#define SQLITE_STATUS_SCRATCH_OVERFLOW     4\n#define SQLITE_STATUS_MALLOC_SIZE          5\n#define SQLITE_STATUS_PARSER_STACK         6\n#define SQLITE_STATUS_PAGECACHE_SIZE       7\n#define SQLITE_STATUS_SCRATCH_SIZE         8\n#define SQLITE_STATUS_MALLOC_COUNT         9\n\n/*\n** CAPI3REF: Database Connection Status\n**\n** ^This interface is used to retrieve runtime status information \n** about a single [database connection].  ^The first argument is the\n** database connection object to be interrogated.  ^The second argument\n** is an integer constant, taken from the set of\n** [SQLITE_DBSTATUS options], that\n** determines the parameter to interrogate.  The set of \n** [SQLITE_DBSTATUS options] is likely\n** to grow in future releases of SQLite.\n**\n** ^The current value of the requested parameter is written into *pCur\n** and the highest instantaneous value is written into *pHiwtr.  ^If\n** the resetFlg is true, then the highest instantaneous value is\n** reset back down to the current value.\n**\n** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** See also: [sqlite3_status()] and [sqlite3_stmt_status()].\n*/\nSQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for database connections\n** KEYWORDS: {SQLITE_DBSTATUS options}\n**\n** These constants are the available integer \"verbs\" that can be passed as\n** the second argument to the [sqlite3_db_status()] interface.\n**\n** New verbs may be added in future releases of SQLite. Existing verbs\n** might be discontinued. Applications should check the return code from\n** [sqlite3_db_status()] to make sure that the call worked.\n** The [sqlite3_db_status()] interface will return a non-zero error code\n** if a discontinued or unsupported verb is invoked.\n**\n** <dl>\n** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>\n** <dd>This parameter returns the number of lookaside memory slots currently\n** checked out.</dd>)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>\n** <dd>This parameter returns the number malloc attempts that were \n** satisfied using lookaside memory. Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to the amount of\n** memory requested being larger than the lookaside slot size.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to all lookaside\n** memory already being in use.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** memory used by all pager caches associated with the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** memory used to store the schema for all databases associated\n** with the connection - main, temp, and any [ATTACH]-ed databases.)^ \n** ^The full amount of memory used by the schemas is reported, even if the\n** schema memory is shared with other database connections due to\n** [shared cache mode] being enabled.\n** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** and lookaside memory used by all prepared statements associated with\n** the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>\n** <dd>This parameter returns the number of pager cache hits that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>\n** <dd>This parameter returns the number of pager cache misses that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk. Specifically, the number of pages written to the\n** wal file in wal mode databases, or the number of pages written to the\n** database file in rollback mode databases. Any pages written as part of\n** transaction rollback or database recovery operations are not included.\n** If an IO or other error occurs while writing a page to disk, the effect\n** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The\n** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBSTATUS_LOOKASIDE_USED       0\n#define SQLITE_DBSTATUS_CACHE_USED           1\n#define SQLITE_DBSTATUS_SCHEMA_USED          2\n#define SQLITE_DBSTATUS_STMT_USED            3\n#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6\n#define SQLITE_DBSTATUS_CACHE_HIT            7\n#define SQLITE_DBSTATUS_CACHE_MISS           8\n#define SQLITE_DBSTATUS_CACHE_WRITE          9\n#define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */\n\n\n/*\n** CAPI3REF: Prepared Statement Status\n**\n** ^(Each prepared statement maintains various\n** [SQLITE_STMTSTATUS counters] that measure the number\n** of times it has performed specific operations.)^  These counters can\n** be used to monitor the performance characteristics of the prepared\n** statements.  For example, if the number of table steps greatly exceeds\n** the number of table searches or result rows, that would tend to indicate\n** that the prepared statement is using a full table scan rather than\n** an index.  \n**\n** ^(This interface is used to retrieve and reset counter values from\n** a [prepared statement].  The first argument is the prepared statement\n** object to be interrogated.  The second argument\n** is an integer code for a specific [SQLITE_STMTSTATUS counter]\n** to be interrogated.)^\n** ^The current value of the requested counter is returned.\n** ^If the resetFlg is true, then the counter is reset to zero after this\n** interface call returns.\n**\n** See also: [sqlite3_status()] and [sqlite3_db_status()].\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for prepared statements\n** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}\n**\n** These preprocessor macros define integer codes that name counter\n** values associated with the [sqlite3_stmt_status()] interface.\n** The meanings of the various counters are as follows:\n**\n** <dl>\n** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>\n** <dd>^This is the number of times that SQLite has stepped forward in\n** a table as part of a full table scan.  Large numbers for this counter\n** may indicate opportunities for performance improvement through \n** careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>\n** <dd>^This is the number of sort operations that have occurred.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance through careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>\n** <dd>^This is the number of rows inserted into transient indices that\n** were created automatically in order to help joins run faster.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance by adding permanent indices that do not\n** need to be reinitialized each time the statement is run.</dd>\n** </dl>\n*/\n#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1\n#define SQLITE_STMTSTATUS_SORT              2\n#define SQLITE_STMTSTATUS_AUTOINDEX         3\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache type is opaque.  It is implemented by\n** the pluggable module.  The SQLite core has no knowledge of\n** its size or internal structure and never deals with the\n** sqlite3_pcache object except by holding and passing pointers\n** to the object.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache sqlite3_pcache;\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache_page object represents a single page in the\n** page cache.  The page cache will allocate instances of this\n** object.  Various methods of the page cache use pointers to instances\n** of this object as parameters or as their return value.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache_page sqlite3_pcache_page;\nstruct sqlite3_pcache_page {\n  void *pBuf;        /* The content of the page */\n  void *pExtra;      /* Extra information associated with the page */\n};\n\n/*\n** CAPI3REF: Application Defined Page Cache.\n** KEYWORDS: {page cache}\n**\n** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can\n** register an alternative page cache implementation by passing in an \n** instance of the sqlite3_pcache_methods2 structure.)^\n** In many applications, most of the heap memory allocated by \n** SQLite is used for the page cache.\n** By implementing a \n** custom page cache using this API, an application can better control\n** the amount of memory consumed by SQLite, the way in which \n** that memory is allocated and released, and the policies used to \n** determine exactly which parts of a database file are cached and for \n** how long.\n**\n** The alternative page cache mechanism is an\n** extreme measure that is only needed by the most demanding applications.\n** The built-in page cache is recommended for most uses.\n**\n** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an\n** internal buffer by SQLite within the call to [sqlite3_config].  Hence\n** the application may discard the parameter after the call to\n** [sqlite3_config()] returns.)^\n**\n** [[the xInit() page cache method]]\n** ^(The xInit() method is called once for each effective \n** call to [sqlite3_initialize()])^\n** (usually only once during the lifetime of the process). ^(The xInit()\n** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^\n** The intent of the xInit() method is to set up global data structures \n** required by the custom page cache implementation. \n** ^(If the xInit() method is NULL, then the \n** built-in default page cache is used instead of the application defined\n** page cache.)^\n**\n** [[the xShutdown() page cache method]]\n** ^The xShutdown() method is called by [sqlite3_shutdown()].\n** It can be used to clean up \n** any outstanding resources before process shutdown, if required.\n** ^The xShutdown() method may be NULL.\n**\n** ^SQLite automatically serializes calls to the xInit method,\n** so the xInit method need not be threadsafe.  ^The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  All other methods must be threadsafe\n** in multithreaded applications.\n**\n** ^SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n**\n** [[the xCreate() page cache methods]]\n** ^SQLite invokes the xCreate() method to construct a new cache instance.\n** SQLite will typically create one cache instance for each open database file,\n** though this is not guaranteed. ^The\n** first parameter, szPage, is the size in bytes of the pages that must\n** be allocated by the cache.  ^szPage will always a power of two.  ^The\n** second parameter szExtra is a number of bytes of extra storage \n** associated with each page cache entry.  ^The szExtra parameter will\n** a number less than 250.  SQLite will use the\n** extra szExtra bytes on each page to store metadata about the underlying\n** database page on disk.  The value passed into szExtra depends\n** on the SQLite version, the target platform, and how SQLite was compiled.\n** ^The third argument to xCreate(), bPurgeable, is true if the cache being\n** created will be used to cache database pages of a file stored on disk, or\n** false if it is used for an in-memory database. The cache implementation\n** does not have to do anything special based with the value of bPurgeable;\n** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will\n** never invoke xUnpin() except to deliberately delete a page.\n** ^In other words, calls to xUnpin() on a cache with bPurgeable set to\n** false will always have the \"discard\" flag set to true.  \n** ^Hence, a cache created with bPurgeable false will\n** never contain any unpinned pages.\n**\n** [[the xCachesize() page cache method]]\n** ^(The xCachesize() method may be called at any time by SQLite to set the\n** suggested maximum cache-size (number of pages stored by) the cache\n** instance passed as the first argument. This is the value configured using\n** the SQLite \"[PRAGMA cache_size]\" command.)^  As with the bPurgeable\n** parameter, the implementation is not required to do anything with this\n** value; it is advisory only.\n**\n** [[the xPagecount() page cache methods]]\n** The xPagecount() method must return the number of pages currently\n** stored in the cache, both pinned and unpinned.\n** \n** [[the xFetch() page cache methods]]\n** The xFetch() method locates a page in the cache and returns a pointer to \n** an sqlite3_pcache_page object associated with that page, or a NULL pointer.\n** The pBuf element of the returned sqlite3_pcache_page object will be a\n** pointer to a buffer of szPage bytes used to store the content of a \n** single database page.  The pExtra element of sqlite3_pcache_page will be\n** a pointer to the szExtra bytes of extra storage that SQLite has requested\n** for each entry in the page cache.\n**\n** The page to be fetched is determined by the key. ^The minimum key value\n** is 1.  After it has been retrieved using xFetch, the page is considered\n** to be \"pinned\".\n**\n** If the requested page is already in the page cache, then the page cache\n** implementation must return a pointer to the page buffer with its content\n** intact.  If the requested page is not already in the cache, then the\n** cache implementation should use the value of the createFlag\n** parameter to help it determined what action to take:\n**\n** <table border=1 width=85% align=center>\n** <tr><th> createFlag <th> Behaviour when page is not already in cache\n** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.\n** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.\n**                 Otherwise return NULL.\n** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return\n**                 NULL if allocating a new page is effectively impossible.\n** </table>\n**\n** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite\n** will only use a createFlag of 2 after a prior call with a createFlag of 1\n** failed.)^  In between the to xFetch() calls, SQLite may\n** attempt to unpin one or more cache pages by spilling the content of\n** pinned pages to disk and synching the operating system disk cache.\n**\n** [[the xUnpin() page cache method]]\n** ^xUnpin() is called by SQLite with a pointer to a currently pinned page\n** as its second argument.  If the third parameter, discard, is non-zero,\n** then the page must be evicted from the cache.\n** ^If the discard parameter is\n** zero, then the page may be discarded or retained at the discretion of\n** page cache implementation. ^The page cache implementation\n** may choose to evict unpinned pages at any time.\n**\n** The cache must not perform any reference counting. A single \n** call to xUnpin() unpins the page regardless of the number of prior calls \n** to xFetch().\n**\n** [[the xRekey() page cache methods]]\n** The xRekey() method is used to change the key value associated with the\n** page passed as the second argument. If the cache\n** previously contains an entry associated with newKey, it must be\n** discarded. ^Any prior cache entry associated with newKey is guaranteed not\n** to be pinned.\n**\n** When SQLite calls the xTruncate() method, the cache must discard all\n** existing cache entries with page numbers (keys) greater than or equal\n** to the value of the iLimit parameter passed to xTruncate(). If any\n** of these pages are pinned, they are implicitly unpinned, meaning that\n** they can be safely discarded.\n**\n** [[the xDestroy() page cache method]]\n** ^The xDestroy() method is used to delete a cache allocated by xCreate().\n** All resources associated with the specified cache should be freed. ^After\n** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]\n** handle invalid, and will not use it with any other sqlite3_pcache_methods2\n** functions.\n**\n** [[the xShrink() page cache method]]\n** ^SQLite invokes the xShrink() method when it wants the page cache to\n** free up as much of heap memory as possible.  The page cache implementation\n** is not obligated to free any memory, but well-behaved implementations should\n** do their best.\n*/\ntypedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;\nstruct sqlite3_pcache_methods2 {\n  int iVersion;\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);\n  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, \n      unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n  void (*xShrink)(sqlite3_pcache*);\n};\n\n/*\n** This is the obsolete pcache_methods object that has now been replaced\n** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is\n** retained in the header file for backwards compatibility only.\n*/\ntypedef struct sqlite3_pcache_methods sqlite3_pcache_methods;\nstruct sqlite3_pcache_methods {\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, void*, int discard);\n  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n};\n\n\n/*\n** CAPI3REF: Online Backup Object\n**\n** The sqlite3_backup object records state information about an ongoing\n** online backup operation.  ^The sqlite3_backup object is created by\n** a call to [sqlite3_backup_init()] and is destroyed by a call to\n** [sqlite3_backup_finish()].\n**\n** See Also: [Using the SQLite Online Backup API]\n*/\ntypedef struct sqlite3_backup sqlite3_backup;\n\n/*\n** CAPI3REF: Online Backup API.\n**\n** The backup API copies the content of one database into another.\n** It is useful either for creating backups of databases or\n** for copying in-memory databases to or from persistent files. \n**\n** See Also: [Using the SQLite Online Backup API]\n**\n** ^SQLite holds a write transaction open on the destination database file\n** for the duration of the backup operation.\n** ^The source database is read-locked only while it is being read;\n** it is not locked continuously for the entire backup operation.\n** ^Thus, the backup may be performed on a live source database without\n** preventing other database connections from\n** reading or writing to the source database while the backup is underway.\n** \n** ^(To perform a backup operation: \n**   <ol>\n**     <li><b>sqlite3_backup_init()</b> is called once to initialize the\n**         backup, \n**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer \n**         the data between the two databases, and finally\n**     <li><b>sqlite3_backup_finish()</b> is called to release all resources \n**         associated with the backup operation. \n**   </ol>)^\n** There should be exactly one call to sqlite3_backup_finish() for each\n** successful call to sqlite3_backup_init().\n**\n** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>\n**\n** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the \n** [database connection] associated with the destination database \n** and the database name, respectively.\n** ^The database name is \"main\" for the main database, \"temp\" for the\n** temporary database, or the name specified after the AS keyword in\n** an [ATTACH] statement for an attached database.\n** ^The S and M arguments passed to \n** sqlite3_backup_init(D,N,S,M) identify the [database connection]\n** and database name of the source database, respectively.\n** ^The source and destination [database connections] (parameters S and D)\n** must be different or else sqlite3_backup_init(D,N,S,M) will fail with\n** an error.\n**\n** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is\n** returned and an error code and error message are stored in the\n** destination [database connection] D.\n** ^The error code and message for the failed call to sqlite3_backup_init()\n** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or\n** [sqlite3_errmsg16()] functions.\n** ^A successful call to sqlite3_backup_init() returns a pointer to an\n** [sqlite3_backup] object.\n** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and\n** sqlite3_backup_finish() functions to perform the specified backup \n** operation.\n**\n** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>\n**\n** ^Function sqlite3_backup_step(B,N) will copy up to N pages between \n** the source and destination databases specified by [sqlite3_backup] object B.\n** ^If N is negative, all remaining source pages are copied. \n** ^If sqlite3_backup_step(B,N) successfully copies N pages and there\n** are still more pages to be copied, then the function returns [SQLITE_OK].\n** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages\n** from source to destination, then it returns [SQLITE_DONE].\n** ^If an error occurs while running sqlite3_backup_step(B,N),\n** then an [error code] is returned. ^As well as [SQLITE_OK] and\n** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],\n** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.\n**\n** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if\n** <ol>\n** <li> the destination database was opened read-only, or\n** <li> the destination database is using write-ahead-log journaling\n** and the destination and source page sizes differ, or\n** <li> the destination database is an in-memory database and the\n** destination and source page sizes differ.\n** </ol>)^\n**\n** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then\n** the [sqlite3_busy_handler | busy-handler function]\n** is invoked (if one is specified). ^If the \n** busy-handler returns non-zero before the lock is available, then \n** [SQLITE_BUSY] is returned to the caller. ^In this case the call to\n** sqlite3_backup_step() can be retried later. ^If the source\n** [database connection]\n** is being used to write to the source database when sqlite3_backup_step()\n** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this\n** case the call to sqlite3_backup_step() can be retried later on. ^(If\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or\n** [SQLITE_READONLY] is returned, then \n** there is no point in retrying the call to sqlite3_backup_step(). These \n** errors are considered fatal.)^  The application must accept \n** that the backup operation has failed and pass the backup operation handle \n** to the sqlite3_backup_finish() to release associated resources.\n**\n** ^The first call to sqlite3_backup_step() obtains an exclusive lock\n** on the destination file. ^The exclusive lock is not released until either \n** sqlite3_backup_finish() is called or the backup operation is complete \n** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to\n** sqlite3_backup_step() obtains a [shared lock] on the source database that\n** lasts for the duration of the sqlite3_backup_step() call.\n** ^Because the source database is not locked between calls to\n** sqlite3_backup_step(), the source database may be modified mid-way\n** through the backup process.  ^If the source database is modified by an\n** external process or via a database connection other than the one being\n** used by the backup operation, then the backup will be automatically\n** restarted by the next call to sqlite3_backup_step(). ^If the source \n** database is modified by the using the same database connection as is used\n** by the backup operation, then the backup database is automatically\n** updated at the same time.\n**\n** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>\n**\n** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the \n** application wishes to abandon the backup operation, the application\n** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().\n** ^The sqlite3_backup_finish() interfaces releases all\n** resources associated with the [sqlite3_backup] object. \n** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any\n** active write-transaction on the destination database is rolled back.\n** The [sqlite3_backup] object is invalid\n** and may not be used following a call to sqlite3_backup_finish().\n**\n** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no\n** sqlite3_backup_step() errors occurred, regardless or whether or not\n** sqlite3_backup_step() completed.\n** ^If an out-of-memory condition or IO error occurred during any prior\n** sqlite3_backup_step() call on the same [sqlite3_backup] object, then\n** sqlite3_backup_finish() returns the corresponding [error code].\n**\n** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()\n** is not a permanent error and does not affect the return value of\n** sqlite3_backup_finish().\n**\n** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]\n** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>\n**\n** ^Each call to sqlite3_backup_step() sets two values inside\n** the [sqlite3_backup] object: the number of pages still to be backed\n** up and the total number of pages in the source database file.\n** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces\n** retrieve these two values, respectively.\n**\n** ^The values returned by these functions are only updated by\n** sqlite3_backup_step(). ^If the source database is modified during a backup\n** operation, then the values are not updated to account for any extra\n** pages that need to be updated or the size of the source database file\n** changing.\n**\n** <b>Concurrent Usage of Database Handles</b>\n**\n** ^The source [database connection] may be used by the application for other\n** purposes while a backup operation is underway or being initialized.\n** ^If SQLite is compiled and configured to support threadsafe database\n** connections, then the source database connection may be used concurrently\n** from within other threads.\n**\n** However, the application must guarantee that the destination \n** [database connection] is not passed to any other API (by any thread) after \n** sqlite3_backup_init() is called and before the corresponding call to\n** sqlite3_backup_finish().  SQLite does not currently check to see\n** if the application incorrectly accesses the destination [database connection]\n** and so no error code is reported, but the operations may malfunction\n** nevertheless.  Use of the destination database connection while a\n** backup is in progress might also also cause a mutex deadlock.\n**\n** If running in [shared cache mode], the application must\n** guarantee that the shared cache used by the destination database\n** is not accessed while the backup is running. In practice this means\n** that the application must guarantee that the disk file being \n** backed up to is not accessed by any connection within the process,\n** not just the specific connection that was passed to sqlite3_backup_init().\n**\n** The [sqlite3_backup] object itself is partially threadsafe. Multiple \n** threads may safely make multiple concurrent calls to sqlite3_backup_step().\n** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()\n** APIs are not strictly speaking threadsafe. If they are invoked at the\n** same time as another thread is invoking sqlite3_backup_step() it is\n** possible that they return invalid values.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3 *pDest,                        /* Destination database handle */\n  const char *zDestName,                 /* Destination database name */\n  sqlite3 *pSource,                      /* Source database handle */\n  const char *zSourceName                /* Source database name */\n);\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);\n\n/*\n** CAPI3REF: Unlock Notification\n**\n** ^When running in shared-cache mode, a database operation may fail with\n** an [SQLITE_LOCKED] error if the required locks on the shared-cache or\n** individual tables within the shared-cache cannot be obtained. See\n** [SQLite Shared-Cache Mode] for a description of shared-cache locking. \n** ^This API may be used to register a callback that SQLite will invoke \n** when the connection currently holding the required lock relinquishes it.\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.\n**\n** See Also: [Using the SQLite Unlock Notification Feature].\n**\n** ^Shared-cache locks are released when a database connection concludes\n** its current transaction, either by committing it or rolling it back. \n**\n** ^When a connection (known as the blocked connection) fails to obtain a\n** shared-cache lock and SQLITE_LOCKED is returned to the caller, the\n** identity of the database connection (the blocking connection) that\n** has locked the required resource is stored internally. ^After an \n** application receives an SQLITE_LOCKED error, it may call the\n** sqlite3_unlock_notify() method with the blocked connection handle as \n** the first argument to register for a callback that will be invoked\n** when the blocking connections current transaction is concluded. ^The\n** callback is invoked from within the [sqlite3_step] or [sqlite3_close]\n** call that concludes the blocking connections transaction.\n**\n** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,\n** there is a chance that the blocking connection will have already\n** concluded its transaction by the time sqlite3_unlock_notify() is invoked.\n** If this happens, then the specified callback is invoked immediately,\n** from within the call to sqlite3_unlock_notify().)^\n**\n** ^If the blocked connection is attempting to obtain a write-lock on a\n** shared-cache table, and more than one other connection currently holds\n** a read-lock on the same table, then SQLite arbitrarily selects one of \n** the other connections to use as the blocking connection.\n**\n** ^(There may be at most one unlock-notify callback registered by a \n** blocked connection. If sqlite3_unlock_notify() is called when the\n** blocked connection already has a registered unlock-notify callback,\n** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is\n** called with a NULL pointer as its second argument, then any existing\n** unlock-notify callback is canceled. ^The blocked connections \n** unlock-notify callback may also be canceled by closing the blocked\n** connection using [sqlite3_close()].\n**\n** The unlock-notify callback is not reentrant. If an application invokes\n** any sqlite3_xxx API functions from within an unlock-notify callback, a\n** crash or deadlock may be the result.\n**\n** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always\n** returns SQLITE_OK.\n**\n** <b>Callback Invocation Details</b>\n**\n** When an unlock-notify callback is registered, the application provides a \n** single void* pointer that is passed to the callback when it is invoked.\n** However, the signature of the callback function allows SQLite to pass\n** it an array of void* context pointers. The first argument passed to\n** an unlock-notify callback is a pointer to an array of void* pointers,\n** and the second is the number of entries in the array.\n**\n** When a blocking connections transaction is concluded, there may be\n** more than one blocked connection that has registered for an unlock-notify\n** callback. ^If two or more such blocked connections have specified the\n** same callback function, then instead of invoking the callback function\n** multiple times, it is invoked once with the set of void* context pointers\n** specified by the blocked connections bundled together into an array.\n** This gives the application an opportunity to prioritize any actions \n** related to the set of unblocked database connections.\n**\n** <b>Deadlock Detection</b>\n**\n** Assuming that after registering for an unlock-notify callback a \n** database waits for the callback to be issued before taking any further\n** action (a reasonable assumption), then using this API may cause the\n** application to deadlock. For example, if connection X is waiting for\n** connection Y's transaction to be concluded, and similarly connection\n** Y is waiting on connection X's transaction, then neither connection\n** will proceed and the system may remain deadlocked indefinitely.\n**\n** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock\n** detection. ^If a given call to sqlite3_unlock_notify() would put the\n** system in a deadlocked state, then SQLITE_LOCKED is returned and no\n** unlock-notify callback is registered. The system is said to be in\n** a deadlocked state if connection A has registered for an unlock-notify\n** callback on the conclusion of connection B's transaction, and connection\n** B has itself registered for an unlock-notify callback when connection\n** A's transaction is concluded. ^Indirect deadlock is also detected, so\n** the system is also considered to be deadlocked if connection B has\n** registered for an unlock-notify callback on the conclusion of connection\n** C's transaction, where connection C is waiting on connection A. ^Any\n** number of levels of indirection are allowed.\n**\n** <b>The \"DROP TABLE\" Exception</b>\n**\n** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost \n** always appropriate to call sqlite3_unlock_notify(). There is however,\n** one exception. When executing a \"DROP TABLE\" or \"DROP INDEX\" statement,\n** SQLite checks if there are any currently executing SELECT statements\n** that belong to the same connection. If there are, SQLITE_LOCKED is\n** returned. In this case there is no \"blocking connection\", so invoking\n** sqlite3_unlock_notify() results in the unlock-notify callback being\n** invoked immediately. If the application then re-attempts the \"DROP TABLE\"\n** or \"DROP INDEX\" query, an infinite loop might be the result.\n**\n** One way around this problem is to check the extended error code returned\n** by an sqlite3_step() call. ^(If there is a blocking connection, then the\n** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in\n** the special \"DROP TABLE/INDEX\" case, the extended error code is just \n** SQLITE_LOCKED.)^\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *pBlocked,                          /* Waiting connection */\n  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */\n  void *pNotifyArg                            /* Argument to pass to xNotify */\n);\n\n\n/*\n** CAPI3REF: String Comparison\n**\n** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications\n** and extensions to compare the contents of two buffers containing UTF-8\n** strings in a case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *, const char *);\nSQLITE_API int sqlite3_strnicmp(const char *, const char *, int);\n\n/*\n** CAPI3REF: Error Logging Interface\n**\n** ^The [sqlite3_log()] interface writes a message into the error log\n** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].\n** ^If logging is enabled, the zFormat string and subsequent arguments are\n** used with [sqlite3_snprintf()] to generate the final output string.\n**\n** The sqlite3_log() interface is intended for use by extensions such as\n** virtual tables, collating functions, and SQL functions.  While there is\n** nothing to prevent an application from calling sqlite3_log(), doing so\n** is considered bad form.\n**\n** The zFormat string must not be NULL.\n**\n** To avoid deadlocks and other threading problems, the sqlite3_log() routine\n** will not use dynamically allocated memory.  The log message is stored in\n** a fixed-length buffer on the stack.  If the log message is longer than\n** a few hundred characters, it will be truncated to the length of the\n** buffer.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);\n\n/*\n** CAPI3REF: Write-Ahead Log Commit Hook\n**\n** ^The [sqlite3_wal_hook()] function is used to register a callback that\n** will be invoked each time a database connection commits data to a\n** [write-ahead log] (i.e. whenever a transaction is committed in\n** [journal_mode | journal_mode=WAL mode]). \n**\n** ^The callback is invoked by SQLite after the commit has taken place and \n** the associated write-lock on the database released, so the implementation \n** may read, write or [checkpoint] the database as required.\n**\n** ^The first parameter passed to the callback function when it is invoked\n** is a copy of the third parameter passed to sqlite3_wal_hook() when\n** registering the callback. ^The second is a copy of the database handle.\n** ^The third parameter is the name of the database that was written to -\n** either \"main\" or the name of an [ATTACH]-ed database. ^The fourth parameter\n** is the number of pages currently in the write-ahead log file,\n** including those that were just committed.\n**\n** The callback function should normally return [SQLITE_OK].  ^If an error\n** code is returned, that error will propagate back up through the\n** SQLite code base to cause the statement that provoked the callback\n** to report an error, though the commit will have still occurred. If the\n** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value\n** that does not correspond to any valid SQLite error code, the results\n** are undefined.\n**\n** A single database handle may have at most a single write-ahead log callback \n** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any\n** previously registered write-ahead log callback. ^Note that the\n** [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will\n** those overwrite any prior [sqlite3_wal_hook()] settings.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3*, \n  int(*)(void *,sqlite3*,const char*,int),\n  void*\n);\n\n/*\n** CAPI3REF: Configure an auto-checkpoint\n**\n** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around\n** [sqlite3_wal_hook()] that causes any database on [database connection] D\n** to automatically [checkpoint]\n** after committing a transaction if there are N or\n** more frames in the [write-ahead log] file.  ^Passing zero or \n** a negative value as the nFrame parameter disables automatic\n** checkpoints entirely.\n**\n** ^The callback registered by this function replaces any existing callback\n** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback\n** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism\n** configured by this function.\n**\n** ^The [wal_autocheckpoint pragma] can be used to invoke this interface\n** from SQL.\n**\n** ^Every new [database connection] defaults to having the auto-checkpoint\n** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]\n** pages.  The use of this interface\n** is only necessary if the default setting is found to be suboptimal\n** for a particular application.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);\n\n/*\n** CAPI3REF: Checkpoint a database\n**\n** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X\n** on [database connection] D to be [checkpointed].  ^If X is NULL or an\n** empty string, then a checkpoint is run on all databases of\n** connection D.  ^If the database connection D is not in\n** [WAL | write-ahead log mode] then this interface is a harmless no-op.\n**\n** ^The [wal_checkpoint pragma] can be used to invoke this interface\n** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] can be used to cause this interface to be\n** run whenever the WAL reaches a certain size threshold.\n**\n** See also: [sqlite3_wal_checkpoint_v2()]\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Checkpoint a database\n**\n** Run a checkpoint operation on WAL database zDb attached to database \n** handle db. The specific operation is determined by the value of the \n** eMode parameter:\n**\n** <dl>\n** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>\n**   Checkpoint as many frames as possible without waiting for any database \n**   readers or writers to finish. Sync the db file if all frames in the log\n**   are checkpointed. This mode is the same as calling \n**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.\n**\n** <dt>SQLITE_CHECKPOINT_FULL<dd>\n**   This mode blocks (calls the busy-handler callback) until there is no\n**   database writer and all readers are reading from the most recent database\n**   snapshot. It then checkpoints all frames in the log file and syncs the\n**   database file. This call blocks database writers while it is running,\n**   but not database readers.\n**\n** <dt>SQLITE_CHECKPOINT_RESTART<dd>\n**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after \n**   checkpointing the log file it blocks (calls the busy-handler callback)\n**   until all readers are reading from the database file only. This ensures \n**   that the next client to write to the database file restarts the log file \n**   from the beginning. This call blocks database writers while it is running,\n**   but not database readers.\n** </dl>\n**\n** If pnLog is not NULL, then *pnLog is set to the total number of frames in\n** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to\n** the total number of checkpointed frames (including any that were already\n** checkpointed when this function is called). *pnLog and *pnCkpt may be\n** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.\n** If no values are available because of an error, they are both set to -1\n** before returning to communicate this to the caller.\n**\n** All calls obtain an exclusive \"checkpoint\" lock on the database file. If\n** any other process is running a checkpoint operation at the same time, the \n** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a \n** busy-handler configured, it will not be invoked in this case.\n**\n** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive \n** \"writer\" lock on the database file. If the writer lock cannot be obtained\n** immediately, and a busy-handler is configured, it is invoked and the writer\n** lock retried until either the busy-handler returns 0 or the lock is\n** successfully obtained. The busy-handler is also invoked while waiting for\n** database readers as described above. If the busy-handler returns 0 before\n** the writer lock is obtained or while waiting for database readers, the\n** checkpoint operation proceeds from that point in the same way as \n** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible \n** without blocking any further. SQLITE_BUSY is returned in this case.\n**\n** If parameter zDb is NULL or points to a zero length string, then the\n** specified operation is attempted on all WAL databases. In this case the\n** values written to output parameters *pnLog and *pnCkpt are undefined. If \n** an SQLITE_BUSY error is encountered when processing one or more of the \n** attached WAL databases, the operation is still attempted on any remaining \n** attached databases and SQLITE_BUSY is returned to the caller. If any other \n** error occurs while processing an attached database, processing is abandoned \n** and the error code returned to the caller immediately. If no error \n** (SQLITE_BUSY or otherwise) is encountered while processing the attached \n** databases, SQLITE_OK is returned.\n**\n** If database zDb is the name of an attached database that is not in WAL\n** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If\n** zDb is not NULL (or a zero length string) and is not the name of any\n** attached database, SQLITE_ERROR is returned to the caller.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n);\n\n/*\n** CAPI3REF: Checkpoint operation parameters\n**\n** These constants can be used as the 3rd parameter to\n** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]\n** documentation for additional information about the meaning and use of\n** each of these values.\n*/\n#define SQLITE_CHECKPOINT_PASSIVE 0\n#define SQLITE_CHECKPOINT_FULL    1\n#define SQLITE_CHECKPOINT_RESTART 2\n\n/*\n** CAPI3REF: Virtual Table Interface Configuration\n**\n** This function may be called by either the [xConnect] or [xCreate] method\n** of a [virtual table] implementation to configure\n** various facets of the virtual table interface.\n**\n** If this interface is invoked outside the context of an xConnect or\n** xCreate virtual table method then the behavior is undefined.\n**\n** At present, there is only one option that may be configured using\n** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options\n** may be added in the future.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Virtual Table Configuration Options\n**\n** These macros define the various options to the\n** [sqlite3_vtab_config()] interface that [virtual table] implementations\n** can use to customize and optimize their behavior.\n**\n** <dl>\n** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,\n** where X is an integer.  If X is zero, then the [virtual table] whose\n** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not\n** support constraints.  In this configuration (which is the default) if\n** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire\n** statement is rolled back as if [ON CONFLICT | OR ABORT] had been\n** specified as part of the users SQL statement, regardless of the actual\n** ON CONFLICT mode specified.\n**\n** If X is non-zero, then the virtual table implementation guarantees\n** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before\n** any modifications to internal or persistent data structures have been made.\n** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite \n** is able to roll back a statement or database transaction, and abandon\n** or continue processing the current SQL statement as appropriate. \n** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns\n** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode\n** had been ABORT.\n**\n** Virtual table implementations that are required to handle OR REPLACE\n** must do so within the [xUpdate] method. If a call to the \n** [sqlite3_vtab_on_conflict()] function indicates that the current ON \n** CONFLICT policy is REPLACE, the virtual table implementation should \n** silently replace the appropriate rows within the xUpdate callback and\n** return SQLITE_OK. Or, if this is not possible, it may return\n** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT \n** constraint handling.\n** </dl>\n*/\n#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1\n\n/*\n** CAPI3REF: Determine The Virtual Table Conflict Policy\n**\n** This function may only be called from within a call to the [xUpdate] method\n** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The\n** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],\n** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode\n** of the SQL statement that triggered the call to the [xUpdate] method of the\n** [virtual table].\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);\n\n/*\n** CAPI3REF: Conflict resolution modes\n**\n** These constants are returned by [sqlite3_vtab_on_conflict()] to\n** inform a [virtual table] implementation what the [ON CONFLICT] mode\n** is for the SQL statement being evaluated.\n**\n** Note that the [SQLITE_IGNORE] constant is also used as a potential\n** return value from the [sqlite3_set_authorizer()] callback and that\n** [SQLITE_ABORT] is also a [result code].\n*/\n#define SQLITE_ROLLBACK 1\n/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */\n#define SQLITE_FAIL     3\n/* #define SQLITE_ABORT 4  // Also an error code */\n#define SQLITE_REPLACE  5\n\n\n\n/*\n** Undo the hack that converts floating point types to integer for\n** builds on processors without floating point support.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# undef double\n#endif\n\n#if 0\n}  /* End of the 'extern \"C\"' block */\n#endif\n#endif\n\n/*\n** 2010 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n\n#ifndef _SQLITE3RTREE_H_\n#define _SQLITE3RTREE_H_\n\n\n#if 0\nextern \"C\" {\n#endif\n\ntypedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;\n\n/*\n** Register a geometry callback named zGeom that can be used as part of an\n** R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,\n  const char *zGeom,\n#ifdef SQLITE_RTREE_INT_ONLY\n  int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),\n#else\n  int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),\n#endif\n  void *pContext\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the first\n** argument to callbacks registered using rtree_geometry_callback().\n*/\nstruct sqlite3_rtree_geometry {\n  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */\n  int nParam;                     /* Size of array aParam[] */\n  double *aParam;                 /* Parameters passed to SQL geom function */\n  void *pUser;                    /* Callback implementation user data */\n  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */\n};\n\n\n#if 0\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif  /* ifndef _SQLITE3RTREE_H_ */\n\n\n/************** End of sqlite3.h *********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include hash.h in the middle of sqliteInt.h ******************/\n/************** Begin file hash.h ********************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for the generic hash-table implemenation\n** used in SQLite.\n*/\n#ifndef _SQLITE_HASH_H_\n#define _SQLITE_HASH_H_\n\n/* Forward declarations of structures. */\ntypedef struct Hash Hash;\ntypedef struct HashElem HashElem;\n\n/* A complete hash table is an instance of the following structure.\n** The internals of this structure are intended to be opaque -- client\n** code should not attempt to access or modify the fields of this structure\n** directly.  Change this structure only by using the routines below.\n** However, some of the \"procedures\" and \"functions\" for modifying and\n** accessing this structure are really macros, so we can't really make\n** this structure opaque.\n**\n** All elements of the hash table are on a single doubly-linked list.\n** Hash.first points to the head of this list.\n**\n** There are Hash.htsize buckets.  Each bucket points to a spot in\n** the global doubly-linked list.  The contents of the bucket are the\n** element pointed to plus the next _ht.count-1 elements in the list.\n**\n** Hash.htsize and Hash.ht may be zero.  In that case lookup is done\n** by a linear search of the global list.  For small tables, the \n** Hash.ht table is never allocated because if there are few elements\n** in the table, it is faster to do a linear search than to manage\n** the hash table.\n*/\nstruct Hash {\n  unsigned int htsize;      /* Number of buckets in the hash table */\n  unsigned int count;       /* Number of entries in this table */\n  HashElem *first;          /* The first element of the array */\n  struct _ht {              /* the hash table */\n    int count;                 /* Number of entries with this hash */\n    HashElem *chain;           /* Pointer to first entry with this hash */\n  } *ht;\n};\n\n/* Each element in the hash table is an instance of the following \n** structure.  All elements are stored on a single doubly-linked list.\n**\n** Again, this structure is intended to be opaque, but it can't really\n** be opaque because it is used by macros.\n*/\nstruct HashElem {\n  HashElem *next, *prev;       /* Next and previous elements in the table */\n  void *data;                  /* Data associated with this element */\n  const char *pKey; int nKey;  /* Key associated with this element */\n};\n\n/*\n** Access routines.  To delete, insert a NULL pointer.\n*/\nSQLITE_PRIVATE void sqlite3HashInit(Hash*);\nSQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);\nSQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);\nSQLITE_PRIVATE void sqlite3HashClear(Hash*);\n\n/*\n** Macros for looping over all elements of a hash table.  The idiom is\n** like this:\n**\n**   Hash h;\n**   HashElem *p;\n**   ...\n**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){\n**     SomeStructure *pData = sqliteHashData(p);\n**     // do something with pData\n**   }\n*/\n#define sqliteHashFirst(H)  ((H)->first)\n#define sqliteHashNext(E)   ((E)->next)\n#define sqliteHashData(E)   ((E)->data)\n/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */\n/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */\n\n/*\n** Number of entries in a hash table\n*/\n/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */\n\n#endif /* _SQLITE_HASH_H_ */\n\n/************** End of hash.h ************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include parse.h in the middle of sqliteInt.h *****************/\n/************** Begin file parse.h *******************************************/\n#define TK_SEMI                            1\n#define TK_EXPLAIN                         2\n#define TK_QUERY                           3\n#define TK_PLAN                            4\n#define TK_BEGIN                           5\n#define TK_TRANSACTION                     6\n#define TK_DEFERRED                        7\n#define TK_IMMEDIATE                       8\n#define TK_EXCLUSIVE                       9\n#define TK_COMMIT                         10\n#define TK_END                            11\n#define TK_ROLLBACK                       12\n#define TK_SAVEPOINT                      13\n#define TK_RELEASE                        14\n#define TK_TO                             15\n#define TK_TABLE                          16\n#define TK_CREATE                         17\n#define TK_IF                             18\n#define TK_NOT                            19\n#define TK_EXISTS                         20\n#define TK_TEMP                           21\n#define TK_LP                             22\n#define TK_RP                             23\n#define TK_AS                             24\n#define TK_COMMA                          25\n#define TK_ID                             26\n#define TK_INDEXED                        27\n#define TK_ABORT                          28\n#define TK_ACTION                         29\n#define TK_AFTER                          30\n#define TK_ANALYZE                        31\n#define TK_ASC                            32\n#define TK_ATTACH                         33\n#define TK_BEFORE                         34\n#define TK_BY                             35\n#define TK_CASCADE                        36\n#define TK_CAST                           37\n#define TK_COLUMNKW                       38\n#define TK_CONFLICT                       39\n#define TK_DATABASE                       40\n#define TK_DESC                           41\n#define TK_DETACH                         42\n#define TK_EACH                           43\n#define TK_FAIL                           44\n#define TK_FOR                            45\n#define TK_IGNORE                         46\n#define TK_INITIALLY                      47\n#define TK_INSTEAD                        48\n#define TK_LIKE_KW                        49\n#define TK_MATCH                          50\n#define TK_NO                             51\n#define TK_KEY                            52\n#define TK_OF                             53\n#define TK_OFFSET                         54\n#define TK_PRAGMA                         55\n#define TK_RAISE                          56\n#define TK_REPLACE                        57\n#define TK_RESTRICT                       58\n#define TK_ROW                            59\n#define TK_TRIGGER                        60\n#define TK_VACUUM                         61\n#define TK_VIEW                           62\n#define TK_VIRTUAL                        63\n#define TK_REINDEX                        64\n#define TK_RENAME                         65\n#define TK_CTIME_KW                       66\n#define TK_ANY                            67\n#define TK_OR                             68\n#define TK_AND                            69\n#define TK_IS                             70\n#define TK_BETWEEN                        71\n#define TK_IN                             72\n#define TK_ISNULL                         73\n#define TK_NOTNULL                        74\n#define TK_NE                             75\n#define TK_EQ                             76\n#define TK_GT                             77\n#define TK_LE                             78\n#define TK_LT                             79\n#define TK_GE                             80\n#define TK_ESCAPE                         81\n#define TK_BITAND                         82\n#define TK_BITOR                          83\n#define TK_LSHIFT                         84\n#define TK_RSHIFT                         85\n#define TK_PLUS                           86\n#define TK_MINUS                          87\n#define TK_STAR                           88\n#define TK_SLASH                          89\n#define TK_REM                            90\n#define TK_CONCAT                         91\n#define TK_COLLATE                        92\n#define TK_BITNOT                         93\n#define TK_STRING                         94\n#define TK_JOIN_KW                        95\n#define TK_CONSTRAINT                     96\n#define TK_DEFAULT                        97\n#define TK_NULL                           98\n#define TK_PRIMARY                        99\n#define TK_UNIQUE                         100\n#define TK_CHECK                          101\n#define TK_REFERENCES                     102\n#define TK_AUTOINCR                       103\n#define TK_ON                             104\n#define TK_INSERT                         105\n#define TK_DELETE                         106\n#define TK_UPDATE                         107\n#define TK_SET                            108\n#define TK_DEFERRABLE                     109\n#define TK_FOREIGN                        110\n#define TK_DROP                           111\n#define TK_UNION                          112\n#define TK_ALL                            113\n#define TK_EXCEPT                         114\n#define TK_INTERSECT                      115\n#define TK_SELECT                         116\n#define TK_DISTINCT                       117\n#define TK_DOT                            118\n#define TK_FROM                           119\n#define TK_JOIN                           120\n#define TK_USING                          121\n#define TK_ORDER                          122\n#define TK_GROUP                          123\n#define TK_HAVING                         124\n#define TK_LIMIT                          125\n#define TK_WHERE                          126\n#define TK_INTO                           127\n#define TK_VALUES                         128\n#define TK_INTEGER                        129\n#define TK_FLOAT                          130\n#define TK_BLOB                           131\n#define TK_REGISTER                       132\n#define TK_VARIABLE                       133\n#define TK_CASE                           134\n#define TK_WHEN                           135\n#define TK_THEN                           136\n#define TK_ELSE                           137\n#define TK_INDEX                          138\n#define TK_ALTER                          139\n#define TK_ADD                            140\n#define TK_TO_TEXT                        141\n#define TK_TO_BLOB                        142\n#define TK_TO_NUMERIC                     143\n#define TK_TO_INT                         144\n#define TK_TO_REAL                        145\n#define TK_ISNOT                          146\n#define TK_END_OF_FILE                    147\n#define TK_ILLEGAL                        148\n#define TK_SPACE                          149\n#define TK_UNCLOSED_STRING                150\n#define TK_FUNCTION                       151\n#define TK_COLUMN                         152\n#define TK_AGG_FUNCTION                   153\n#define TK_AGG_COLUMN                     154\n#define TK_CONST_FUNC                     155\n#define TK_UMINUS                         156\n#define TK_UPLUS                          157\n\n/************** End of parse.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <assert.h>\n#include <stddef.h>\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite_int64\n# define float sqlite_int64\n# define LONGDOUBLE_TYPE sqlite_int64\n# ifndef SQLITE_BIG_DBL\n#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)\n# endif\n# define SQLITE_OMIT_DATETIME_FUNCS 1\n# define SQLITE_OMIT_TRACE 1\n# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT\n# undef SQLITE_HAVE_ISNAN\n#endif\n#ifndef SQLITE_BIG_DBL\n# define SQLITE_BIG_DBL (1e99)\n#endif\n\n/*\n** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0\n** afterward. Having this macro allows us to cause the C compiler \n** to omit code used by TEMP tables without messy #ifndef statements.\n*/\n#ifdef SQLITE_OMIT_TEMPDB\n#define OMIT_TEMPDB 1\n#else\n#define OMIT_TEMPDB 0\n#endif\n\n/*\n** The \"file format\" number is an integer that is incremented whenever\n** the VDBE-level file format changes.  The following macros define the\n** the default file format for new databases and the maximum file format\n** that the library can read.\n*/\n#define SQLITE_MAX_FILE_FORMAT 4\n#ifndef SQLITE_DEFAULT_FILE_FORMAT\n# define SQLITE_DEFAULT_FILE_FORMAT 4\n#endif\n\n/*\n** Determine whether triggers are recursive by default.  This can be\n** changed at run-time using a pragma.\n*/\n#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS\n# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0\n#endif\n\n/*\n** Provide a default value for SQLITE_TEMP_STORE in case it is not specified\n** on the command-line\n*/\n#ifndef SQLITE_TEMP_STORE\n# define SQLITE_TEMP_STORE 1\n#endif\n\n/*\n** GCC does not define the offsetof() macro so we'll have to do it\n** ourselves.\n*/\n#ifndef offsetof\n#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))\n#endif\n\n/*\n** Check to see if this machine uses EBCDIC.  (Yes, believe it or\n** not, there are still machines out there that use EBCDIC.)\n*/\n#if 'A' == '\\301'\n# define SQLITE_EBCDIC 1\n#else\n# define SQLITE_ASCII 1\n#endif\n\n/*\n** Integers of known sizes.  These typedefs might change for architectures\n** where the sizes very.  Preprocessor macros are available so that the\n** types can be conveniently redefined at compile-type.  Like this:\n**\n**         cc '-DUINTPTR_TYPE=long long int' ...\n*/\n#ifndef UINT32_TYPE\n# ifdef HAVE_UINT32_T\n#  define UINT32_TYPE uint32_t\n# else\n#  define UINT32_TYPE unsigned int\n# endif\n#endif\n#ifndef UINT16_TYPE\n# ifdef HAVE_UINT16_T\n#  define UINT16_TYPE uint16_t\n# else\n#  define UINT16_TYPE unsigned short int\n# endif\n#endif\n#ifndef INT16_TYPE\n# ifdef HAVE_INT16_T\n#  define INT16_TYPE int16_t\n# else\n#  define INT16_TYPE short int\n# endif\n#endif\n#ifndef UINT8_TYPE\n# ifdef HAVE_UINT8_T\n#  define UINT8_TYPE uint8_t\n# else\n#  define UINT8_TYPE unsigned char\n# endif\n#endif\n#ifndef INT8_TYPE\n# ifdef HAVE_INT8_T\n#  define INT8_TYPE int8_t\n# else\n#  define INT8_TYPE signed char\n# endif\n#endif\n#ifndef LONGDOUBLE_TYPE\n# define LONGDOUBLE_TYPE long double\n#endif\ntypedef sqlite_int64 i64;          /* 8-byte signed integer */\ntypedef sqlite_uint64 u64;         /* 8-byte unsigned integer */\ntypedef UINT32_TYPE u32;           /* 4-byte unsigned integer */\ntypedef UINT16_TYPE u16;           /* 2-byte unsigned integer */\ntypedef INT16_TYPE i16;            /* 2-byte signed integer */\ntypedef UINT8_TYPE u8;             /* 1-byte unsigned integer */\ntypedef INT8_TYPE i8;              /* 1-byte signed integer */\n\n/*\n** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value\n** that can be stored in a u32 without loss of data.  The value\n** is 0x00000000ffffffff.  But because of quirks of some compilers, we\n** have to specify the value in the less intuitive manner shown:\n*/\n#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)\n\n/*\n** The datatype used to store estimates of the number of rows in a\n** table or index.  This is an unsigned integer type.  For 99.9% of\n** the world, a 32-bit integer is sufficient.  But a 64-bit integer\n** can be used at compile-time if desired.\n*/\n#ifdef SQLITE_64BIT_STATS\n typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */\n#else\n typedef u32 tRowcnt;    /* 32-bit is the default */\n#endif\n\n/*\n** Macros to determine whether the machine is big or little endian,\n** evaluated at runtime.\n*/\n#ifdef SQLITE_AMALGAMATION\nSQLITE_PRIVATE const int sqlite3one = 1;\n#else\nSQLITE_PRIVATE const int sqlite3one;\n#endif\n#if defined(i386) || defined(__i386__) || defined(_M_IX86)\\\n                             || defined(__x86_64) || defined(__x86_64__)\n# define SQLITE_BIGENDIAN    0\n# define SQLITE_LITTLEENDIAN 1\n# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE\n#else\n# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)\n# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)\n# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)\n#endif\n\n/*\n** Constants for the largest and smallest possible 64-bit signed integers.\n** These macros are designed to work correctly on both 32-bit and 64-bit\n** compilers.\n*/\n#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))\n#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)\n\n/* \n** Round up a number to the next larger multiple of 8.  This is used\n** to force 8-byte alignment on 64-bit architectures.\n*/\n#define ROUND8(x)     (((x)+7)&~7)\n\n/*\n** Round down to the nearest multiple of 8\n*/\n#define ROUNDDOWN8(x) ((x)&~7)\n\n/*\n** Assert that the pointer X is aligned to an 8-byte boundary.  This\n** macro is used only within assert() to verify that the code gets\n** all alignment restrictions correct.\n**\n** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the\n** underlying malloc() implemention might return us 4-byte aligned\n** pointers.  In that case, only verify 4-byte alignment.\n*/\n#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC\n# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)\n#else\n# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)\n#endif\n\n\n/*\n** An instance of the following structure is used to store the busy-handler\n** callback for a given sqlite handle. \n**\n** The sqlite.busyHandler member of the sqlite struct contains the busy\n** callback for the database handle. Each pager opened via the sqlite\n** handle is passed a pointer to sqlite.busyHandler. The busy-handler\n** callback is currently invoked only from within pager.c.\n*/\ntypedef struct BusyHandler BusyHandler;\nstruct BusyHandler {\n  int (*xFunc)(void *,int);  /* The busy callback */\n  void *pArg;                /* First arg to busy callback */\n  int nBusy;                 /* Incremented with each busy call */\n};\n\n/*\n** Name of the master database table.  The master database table\n** is a special table that holds the names and attributes of all\n** user tables and indices.\n*/\n#define MASTER_NAME       \"sqlite_master\"\n#define TEMP_MASTER_NAME  \"sqlite_temp_master\"\n\n/*\n** The root-page of the master database table.\n*/\n#define MASTER_ROOT       1\n\n/*\n** The name of the schema table.\n*/\n#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)\n\n/*\n** A convenience macro that returns the number of elements in\n** an array.\n*/\n#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))\n\n/*\n** The following value as a destructor means to use sqlite3DbFree().\n** The sqlite3DbFree() routine requires two parameters instead of the \n** one parameter that destructors normally want.  So we have to introduce \n** this magic value that the code knows to handle differently.  Any \n** pointer will work here as long as it is distinct from SQLITE_STATIC\n** and SQLITE_TRANSIENT.\n*/\n#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)\n\n/*\n** When SQLITE_OMIT_WSD is defined, it means that the target platform does\n** not support Writable Static Data (WSD) such as global and static variables.\n** All variables must either be on the stack or dynamically allocated from\n** the heap.  When WSD is unsupported, the variable declarations scattered\n** throughout the SQLite code must become constants instead.  The SQLITE_WSD\n** macro is used for this purpose.  And instead of referencing the variable\n** directly, we use its constant as a key to lookup the run-time allocated\n** buffer that holds real variable.  The constant is also the initializer\n** for the run-time allocated buffer.\n**\n** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL\n** macros become no-ops and have zero performance impact.\n*/\n#ifdef SQLITE_OMIT_WSD\n  #define SQLITE_WSD const\n  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))\n  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)\nSQLITE_API   int sqlite3_wsd_init(int N, int J);\nSQLITE_API   void *sqlite3_wsd_find(void *K, int L);\n#else\n  #define SQLITE_WSD \n  #define GLOBAL(t,v) v\n  #define sqlite3GlobalConfig sqlite3Config\n#endif\n\n/*\n** The following macros are used to suppress compiler warnings and to\n** make it clear to human readers when a function parameter is deliberately \n** left unused within the body of a function. This usually happens when\n** a function is called via a function pointer. For example the \n** implementation of an SQL aggregate step callback may not use the\n** parameter indicating the number of arguments passed to the aggregate,\n** if it knows that this is enforced elsewhere.\n**\n** When a function parameter is not used at all within the body of a function,\n** it is generally named \"NotUsed\" or \"NotUsed2\" to make things even clearer.\n** However, these macros may also be used to suppress warnings related to\n** parameters that may or may not be used depending on compilation options.\n** For example those parameters only used in assert() statements. In these\n** cases the parameters are named as per the usual conventions.\n*/\n#define UNUSED_PARAMETER(x) (void)(x)\n#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)\n\n/*\n** Forward references to structures\n*/\ntypedef struct AggInfo AggInfo;\ntypedef struct AuthContext AuthContext;\ntypedef struct AutoincInfo AutoincInfo;\ntypedef struct Bitvec Bitvec;\ntypedef struct CollSeq CollSeq;\ntypedef struct Column Column;\ntypedef struct Db Db;\ntypedef struct Schema Schema;\ntypedef struct Expr Expr;\ntypedef struct ExprList ExprList;\ntypedef struct ExprSpan ExprSpan;\ntypedef struct FKey FKey;\ntypedef struct FuncDestructor FuncDestructor;\ntypedef struct FuncDef FuncDef;\ntypedef struct FuncDefHash FuncDefHash;\ntypedef struct IdList IdList;\ntypedef struct Index Index;\ntypedef struct IndexSample IndexSample;\ntypedef struct KeyClass KeyClass;\ntypedef struct KeyInfo KeyInfo;\ntypedef struct Lookaside Lookaside;\ntypedef struct LookasideSlot LookasideSlot;\ntypedef struct Module Module;\ntypedef struct NameContext NameContext;\ntypedef struct Parse Parse;\ntypedef struct RowSet RowSet;\ntypedef struct Savepoint Savepoint;\ntypedef struct Select Select;\ntypedef struct SrcList SrcList;\ntypedef struct StrAccum StrAccum;\ntypedef struct Table Table;\ntypedef struct TableLock TableLock;\ntypedef struct Token Token;\ntypedef struct Trigger Trigger;\ntypedef struct TriggerPrg TriggerPrg;\ntypedef struct TriggerStep TriggerStep;\ntypedef struct UnpackedRecord UnpackedRecord;\ntypedef struct VTable VTable;\ntypedef struct VtabCtx VtabCtx;\ntypedef struct Walker Walker;\ntypedef struct WherePlan WherePlan;\ntypedef struct WhereInfo WhereInfo;\ntypedef struct WhereLevel WhereLevel;\n\n/*\n** Defer sourcing vdbe.h and btree.h until after the \"u8\" and \n** \"BusyHandler\" typedefs. vdbe.h also requires a few of the opaque\n** pointer types (i.e. FuncDef) defined above.\n*/\n/************** Include btree.h in the middle of sqliteInt.h *****************/\n/************** Begin file btree.h *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite B-Tree file\n** subsystem.  See comments in the source code for a detailed description\n** of what each interface routine does.\n*/\n#ifndef _BTREE_H_\n#define _BTREE_H_\n\n/* TODO: This definition is just included so other modules compile. It\n** needs to be revisited.\n*/\n#define SQLITE_N_BTREE_META 10\n\n/*\n** If defined as non-zero, auto-vacuum is enabled by default. Otherwise\n** it must be turned on for each database using \"PRAGMA auto_vacuum = 1\".\n*/\n#ifndef SQLITE_DEFAULT_AUTOVACUUM\n  #define SQLITE_DEFAULT_AUTOVACUUM 0\n#endif\n\n#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */\n#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */\n#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */\n\n/*\n** Forward declarations of structure\n*/\ntypedef struct Btree Btree;\ntypedef struct BtCursor BtCursor;\ntypedef struct BtShared BtShared;\n\n\nSQLITE_PRIVATE int sqlite3BtreeOpen(\n  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */\n  const char *zFilename,   /* Name of database file to open */\n  sqlite3 *db,             /* Associated database connection */\n  Btree **ppBtree,         /* Return open Btree* here */\n  int flags,               /* Flags */\n  int vfsFlags             /* Flags passed through to VFS open */\n);\n\n/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the\n** following values.\n**\n** NOTE:  These values must match the corresponding PAGER_ values in\n** pager.h.\n*/\n#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */\n#define BTREE_MEMORY        2  /* This is an in-memory DB */\n#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */\n#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */\n\nSQLITE_PRIVATE int sqlite3BtreeClose(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);\nSQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);\nSQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);\nSQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);\nSQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);\nSQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);\nSQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);\nSQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);\nSQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);\nSQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);\nSQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));\nSQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);\nSQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);\nSQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);\n\nSQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);\nSQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);\nSQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);\n\nSQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);\n\n/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR\n** of the flags shown below.\n**\n** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.\n** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data\n** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With\n** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored\n** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL\n** indices.)\n*/\n#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */\n#define BTREE_BLOBKEY    2    /* Table has keys only - no data */\n\nSQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);\nSQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);\nSQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);\n\nSQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);\nSQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);\n\n/*\n** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta\n** should be one of the following values. The integer values are assigned \n** to constants so that the offset of the corresponding field in an\n** SQLite database header may be found using the following formula:\n**\n**   offset = 36 + (idx * 4)\n**\n** For example, the free-page-count field is located at byte offset 36 of\n** the database file header. The incr-vacuum-flag field is located at\n** byte offset 64 (== 36+4*7).\n*/\n#define BTREE_FREE_PAGE_COUNT     0\n#define BTREE_SCHEMA_VERSION      1\n#define BTREE_FILE_FORMAT         2\n#define BTREE_DEFAULT_CACHE_SIZE  3\n#define BTREE_LARGEST_ROOT_PAGE   4\n#define BTREE_TEXT_ENCODING       5\n#define BTREE_USER_VERSION        6\n#define BTREE_INCR_VACUUM         7\n\n/*\n** Values that may be OR'd together to form the second argument of an\n** sqlite3BtreeCursorHints() call.\n*/\n#define BTREE_BULKLOAD 0x00000001\n\nSQLITE_PRIVATE int sqlite3BtreeCursor(\n  Btree*,                              /* BTree containing table to open */\n  int iTable,                          /* Index of root page */\n  int wrFlag,                          /* 1 for writing.  0 for read-only */\n  struct KeyInfo*,                     /* First argument to compare function */\n  BtCursor *pCursor                    /* Space to write cursor structure */\n);\nSQLITE_PRIVATE int sqlite3BtreeCursorSize(void);\nSQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);\n\nSQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(\n  BtCursor*,\n  UnpackedRecord *pUnKey,\n  i64 intKey,\n  int bias,\n  int *pRes\n);\nSQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);\nSQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,\n                                  const void *pData, int nData,\n                                  int nZero, int bias, int seekResult);\nSQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);\nSQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);\nSQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);\nSQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);\nSQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);\nSQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);\nSQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);\nSQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);\n\nSQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);\nSQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);\n\nSQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);\nSQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);\nSQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);\nSQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);\nSQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);\n\n#ifndef NDEBUG\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);\n#endif\n\n#ifndef SQLITE_OMIT_BTREECOUNT\nSQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);\n#endif\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);\nSQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);\n#endif\n\n#ifndef SQLITE_OMIT_WAL\nSQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);\n#endif\n\n/*\n** If we are not using shared cache, then there is no need to\n** use mutexes to access the BtShared structures.  So make the\n** Enter and Leave procedures no-ops.\n*/\n#ifndef SQLITE_OMIT_SHARED_CACHE\nSQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);\n#else\n# define sqlite3BtreeEnter(X) \n# define sqlite3BtreeEnterAll(X)\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE\nSQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);\nSQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);\nSQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);\nSQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);\n#ifndef NDEBUG\n  /* These routines are used inside assert() statements only. */\nSQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);\nSQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);\nSQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);\n#endif\n#else\n\n# define sqlite3BtreeSharable(X) 0\n# define sqlite3BtreeLeave(X)\n# define sqlite3BtreeEnterCursor(X)\n# define sqlite3BtreeLeaveCursor(X)\n# define sqlite3BtreeLeaveAll(X)\n\n# define sqlite3BtreeHoldsMutex(X) 1\n# define sqlite3BtreeHoldsAllMutexes(X) 1\n# define sqlite3SchemaMutexHeld(X,Y,Z) 1\n#endif\n\n\n#endif /* _BTREE_H_ */\n\n/************** End of btree.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include vdbe.h in the middle of sqliteInt.h ******************/\n/************** Begin file vdbe.h ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Header file for the Virtual DataBase Engine (VDBE)\n**\n** This header defines the interface to the virtual database engine\n** or VDBE.  The VDBE implements an abstract machine that runs a\n** simple program to access and modify the underlying database.\n*/\n#ifndef _SQLITE_VDBE_H_\n#define _SQLITE_VDBE_H_\n/* #include <stdio.h> */\n\n/*\n** A single VDBE is an opaque structure named \"Vdbe\".  Only routines\n** in the source file sqliteVdbe.c are allowed to see the insides\n** of this structure.\n*/\ntypedef struct Vdbe Vdbe;\n\n/*\n** The names of the following types declared in vdbeInt.h are required\n** for the VdbeOp definition.\n*/\ntypedef struct VdbeFunc VdbeFunc;\ntypedef struct Mem Mem;\ntypedef struct SubProgram SubProgram;\n\n/*\n** A single instruction of the virtual machine has an opcode\n** and as many as three operands.  The instruction is recorded\n** as an instance of the following structure:\n*/\nstruct VdbeOp {\n  u8 opcode;          /* What operation to perform */\n  signed char p4type; /* One of the P4_xxx constants for p4 */\n  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */\n  u8 p5;              /* Fifth parameter is an unsigned character */\n  int p1;             /* First operand */\n  int p2;             /* Second parameter (often the jump destination) */\n  int p3;             /* The third parameter */\n  union {             /* fourth parameter */\n    int i;                 /* Integer value if p4type==P4_INT32 */\n    void *p;               /* Generic pointer */\n    char *z;               /* Pointer to data for string (char array) types */\n    i64 *pI64;             /* Used when p4type is P4_INT64 */\n    double *pReal;         /* Used when p4type is P4_REAL */\n    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */\n    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */\n    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */\n    Mem *pMem;             /* Used when p4type is P4_MEM */\n    VTable *pVtab;         /* Used when p4type is P4_VTAB */\n    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */\n    int *ai;               /* Used when p4type is P4_INTARRAY */\n    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */\n    int (*xAdvance)(BtCursor *, int *);\n  } p4;\n#ifdef SQLITE_DEBUG\n  char *zComment;          /* Comment to improve readability */\n#endif\n#ifdef VDBE_PROFILE\n  int cnt;                 /* Number of times this instruction was executed */\n  u64 cycles;              /* Total time spent executing this instruction */\n#endif\n};\ntypedef struct VdbeOp VdbeOp;\n\n\n/*\n** A sub-routine used to implement a trigger program.\n*/\nstruct SubProgram {\n  VdbeOp *aOp;                  /* Array of opcodes for sub-program */\n  int nOp;                      /* Elements in aOp[] */\n  int nMem;                     /* Number of memory cells required */\n  int nCsr;                     /* Number of cursors required */\n  int nOnce;                    /* Number of OP_Once instructions */\n  void *token;                  /* id that may be used to recursive triggers */\n  SubProgram *pNext;            /* Next sub-program already visited */\n};\n\n/*\n** A smaller version of VdbeOp used for the VdbeAddOpList() function because\n** it takes up less space.\n*/\nstruct VdbeOpList {\n  u8 opcode;          /* What operation to perform */\n  signed char p1;     /* First operand */\n  signed char p2;     /* Second parameter (often the jump destination) */\n  signed char p3;     /* Third parameter */\n};\ntypedef struct VdbeOpList VdbeOpList;\n\n/*\n** Allowed values of VdbeOp.p4type\n*/\n#define P4_NOTUSED    0   /* The P4 parameter is not used */\n#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */\n#define P4_STATIC   (-2)  /* Pointer to a static string */\n#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */\n#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */\n#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */\n#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */\n#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */\n#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */\n#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */\n#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */\n#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */\n#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */\n#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */\n#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */\n#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */\n#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */\n\n/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure\n** is made.  That copy is freed when the Vdbe is finalized.  But if the\n** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still\n** gets freed when the Vdbe is finalized so it still should be obtained\n** from a single sqliteMalloc().  But no copy is made and the calling\n** function should *not* try to free the KeyInfo.\n*/\n#define P4_KEYINFO_HANDOFF (-16)\n#define P4_KEYINFO_STATIC  (-17)\n\n/*\n** The Vdbe.aColName array contains 5n Mem structures, where n is the \n** number of columns of data returned by the statement.\n*/\n#define COLNAME_NAME     0\n#define COLNAME_DECLTYPE 1\n#define COLNAME_DATABASE 2\n#define COLNAME_TABLE    3\n#define COLNAME_COLUMN   4\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */\n#else\n# ifdef SQLITE_OMIT_DECLTYPE\n#   define COLNAME_N      1      /* Store only the name */\n# else\n#   define COLNAME_N      2      /* Store the name and decltype */\n# endif\n#endif\n\n/*\n** The following macro converts a relative address in the p2 field\n** of a VdbeOp structure into a negative number so that \n** sqlite3VdbeAddOpList() knows that the address is relative.  Calling\n** the macro again restores the address.\n*/\n#define ADDR(X)  (-1-(X))\n\n/*\n** The makefile scans the vdbe.c source file and creates the \"opcodes.h\"\n** header file that defines a number for each opcode used by the VDBE.\n*/\n/************** Include opcodes.h in the middle of vdbe.h ********************/\n/************** Begin file opcodes.h *****************************************/\n/* Automatically generated.  Do not edit */\n/* See the mkopcodeh.awk script for details */\n#define OP_Goto                                 1\n#define OP_Gosub                                2\n#define OP_Return                               3\n#define OP_Yield                                4\n#define OP_HaltIfNull                           5\n#define OP_Halt                                 6\n#define OP_Integer                              7\n#define OP_Int64                                8\n#define OP_Real                               130   /* same as TK_FLOAT    */\n#define OP_String8                             94   /* same as TK_STRING   */\n#define OP_String                               9\n#define OP_Null                                10\n#define OP_Blob                                11\n#define OP_Variable                            12\n#define OP_Move                                13\n#define OP_Copy                                14\n#define OP_SCopy                               15\n#define OP_ResultRow                           16\n#define OP_Concat                              91   /* same as TK_CONCAT   */\n#define OP_Add                                 86   /* same as TK_PLUS     */\n#define OP_Subtract                            87   /* same as TK_MINUS    */\n#define OP_Multiply                            88   /* same as TK_STAR     */\n#define OP_Divide                              89   /* same as TK_SLASH    */\n#define OP_Remainder                           90   /* same as TK_REM      */\n#define OP_CollSeq                             17\n#define OP_Function                            18\n#define OP_BitAnd                              82   /* same as TK_BITAND   */\n#define OP_BitOr                               83   /* same as TK_BITOR    */\n#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */\n#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */\n#define OP_AddImm                              20\n#define OP_MustBeInt                           21\n#define OP_RealAffinity                        22\n#define OP_ToText                             141   /* same as TK_TO_TEXT  */\n#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */\n#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/\n#define OP_ToInt                              144   /* same as TK_TO_INT   */\n#define OP_ToReal                             145   /* same as TK_TO_REAL  */\n#define OP_Eq                                  76   /* same as TK_EQ       */\n#define OP_Ne                                  75   /* same as TK_NE       */\n#define OP_Lt                                  79   /* same as TK_LT       */\n#define OP_Le                                  78   /* same as TK_LE       */\n#define OP_Gt                                  77   /* same as TK_GT       */\n#define OP_Ge                                  80   /* same as TK_GE       */\n#define OP_Permutation                         23\n#define OP_Compare                             24\n#define OP_Jump                                25\n#define OP_And                                 69   /* same as TK_AND      */\n#define OP_Or                                  68   /* same as TK_OR       */\n#define OP_Not                                 19   /* same as TK_NOT      */\n#define OP_BitNot                              93   /* same as TK_BITNOT   */\n#define OP_Once                                26\n#define OP_If                                  27\n#define OP_IfNot                               28\n#define OP_IsNull                              73   /* same as TK_ISNULL   */\n#define OP_NotNull                             74   /* same as TK_NOTNULL  */\n#define OP_Column                              29\n#define OP_Affinity                            30\n#define OP_MakeRecord                          31\n#define OP_Count                               32\n#define OP_Savepoint                           33\n#define OP_AutoCommit                          34\n#define OP_Transaction                         35\n#define OP_ReadCookie                          36\n#define OP_SetCookie                           37\n#define OP_VerifyCookie                        38\n#define OP_OpenRead                            39\n#define OP_OpenWrite                           40\n#define OP_OpenAutoindex                       41\n#define OP_OpenEphemeral                       42\n#define OP_SorterOpen                          43\n#define OP_OpenPseudo                          44\n#define OP_Close                               45\n#define OP_SeekLt                              46\n#define OP_SeekLe                              47\n#define OP_SeekGe                              48\n#define OP_SeekGt                              49\n#define OP_Seek                                50\n#define OP_NotFound                            51\n#define OP_Found                               52\n#define OP_IsUnique                            53\n#define OP_NotExists                           54\n#define OP_Sequence                            55\n#define OP_NewRowid                            56\n#define OP_Insert                              57\n#define OP_InsertInt                           58\n#define OP_Delete                              59\n#define OP_ResetCount                          60\n#define OP_SorterCompare                       61\n#define OP_SorterData                          62\n#define OP_RowKey                              63\n#define OP_RowData                             64\n#define OP_Rowid                               65\n#define OP_NullRow                             66\n#define OP_Last                                67\n#define OP_SorterSort                          70\n#define OP_Sort                                71\n#define OP_Rewind                              72\n#define OP_SorterNext                          81\n#define OP_Prev                                92\n#define OP_Next                                95\n#define OP_SorterInsert                        96\n#define OP_IdxInsert                           97\n#define OP_IdxDelete                           98\n#define OP_IdxRowid                            99\n#define OP_IdxLT                              100\n#define OP_IdxGE                              101\n#define OP_Destroy                            102\n#define OP_Clear                              103\n#define OP_CreateIndex                        104\n#define OP_CreateTable                        105\n#define OP_ParseSchema                        106\n#define OP_LoadAnalysis                       107\n#define OP_DropTable                          108\n#define OP_DropIndex                          109\n#define OP_DropTrigger                        110\n#define OP_IntegrityCk                        111\n#define OP_RowSetAdd                          112\n#define OP_RowSetRead                         113\n#define OP_RowSetTest                         114\n#define OP_Program                            115\n#define OP_Param                              116\n#define OP_FkCounter                          117\n#define OP_FkIfZero                           118\n#define OP_MemMax                             119\n#define OP_IfPos                              120\n#define OP_IfNeg                              121\n#define OP_IfZero                             122\n#define OP_AggStep                            123\n#define OP_AggFinal                           124\n#define OP_Checkpoint                         125\n#define OP_JournalMode                        126\n#define OP_Vacuum                             127\n#define OP_IncrVacuum                         128\n#define OP_Expire                             129\n#define OP_TableLock                          131\n#define OP_VBegin                             132\n#define OP_VCreate                            133\n#define OP_VDestroy                           134\n#define OP_VOpen                              135\n#define OP_VFilter                            136\n#define OP_VColumn                            137\n#define OP_VNext                              138\n#define OP_VRename                            139\n#define OP_VUpdate                            140\n#define OP_Pagecount                          146\n#define OP_MaxPgcnt                           147\n#define OP_Trace                              148\n#define OP_Noop                               149\n#define OP_Explain                            150\n\n\n/* Properties such as \"out2\" or \"jump\" that are specified in\n** comments following the \"case\" for each opcode in the vdbe.c\n** are encoded into bitvectors as follows:\n*/\n#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */\n#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */\n#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */\n#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */\n#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */\n#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */\n#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */\n#define OPFLG_INITIALIZER {\\\n/*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\\\n/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\\\n/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\\\n/*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\\\n/*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\\\n/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\\\n/*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\\\n/*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n/*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\\\n/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\\\n/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\\\n/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\\\n/*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\\\n/* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n/* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\\\n/* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\\\n/* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\\\n/* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\\\n/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}\n\n/************** End of opcodes.h *********************************************/\n/************** Continuing where we left off in vdbe.h ***********************/\n\n/*\n** Prototypes for the VDBE interface.  See comments on the implementation\n** for a description of what each of these routines does.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);\nSQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);\nSQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);\nSQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);\nSQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);\nSQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);\nSQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);\nSQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);\nSQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);\nSQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);\nSQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);\nSQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);\nSQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);\nSQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);\nSQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);\nSQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));\nSQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);\nSQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);\nSQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);\nSQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);\nSQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);\nSQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);\n#ifndef SQLITE_OMIT_TRACE\nSQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);\n#endif\n\nSQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);\nSQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);\nSQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);\n\n#ifndef SQLITE_OMIT_TRIGGER\nSQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);\n#endif\n\n\n#ifndef NDEBUG\nSQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);\n# define VdbeComment(X)  sqlite3VdbeComment X\nSQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);\n# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X\n#else\n# define VdbeComment(X)\n# define VdbeNoopComment(X)\n#endif\n\n#endif\n\n/************** End of vdbe.h ************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include pager.h in the middle of sqliteInt.h *****************/\n/************** Begin file pager.h *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite page cache\n** subsystem.  The page cache subsystem reads and writes a file a page\n** at a time and provides a journal for rollback.\n*/\n\n#ifndef _PAGER_H_\n#define _PAGER_H_\n\n/*\n** Default maximum size for persistent journal files. A negative \n** value means no limit. This value may be overridden using the \n** sqlite3PagerJournalSizeLimit() API. See also \"PRAGMA journal_size_limit\".\n*/\n#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT\n  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1\n#endif\n\n/*\n** The type used to represent a page number.  The first page in a file\n** is called page 1.  0 is used to represent \"not a page\".\n*/\ntypedef u32 Pgno;\n\n/*\n** Each open file is managed by a separate instance of the \"Pager\" structure.\n*/\ntypedef struct Pager Pager;\n\n/*\n** Handle type for pages.\n*/\ntypedef struct PgHdr DbPage;\n\n/*\n** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is\n** reserved for working around a windows/posix incompatibility). It is\n** used in the journal to signify that the remainder of the journal file \n** is devoted to storing a master journal name - there are no more pages to\n** roll back. See comments for function writeMasterJournal() in pager.c \n** for details.\n*/\n#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))\n\n/*\n** Allowed values for the flags parameter to sqlite3PagerOpen().\n**\n** NOTE: These values must match the corresponding BTREE_ values in btree.h.\n*/\n#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */\n#define PAGER_MEMORY        0x0002    /* In-memory database */\n\n/*\n** Valid values for the second argument to sqlite3PagerLockingMode().\n*/\n#define PAGER_LOCKINGMODE_QUERY      -1\n#define PAGER_LOCKINGMODE_NORMAL      0\n#define PAGER_LOCKINGMODE_EXCLUSIVE   1\n\n/*\n** Numeric constants that encode the journalmode.  \n*/\n#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */\n#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */\n#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */\n#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */\n#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */\n#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */\n#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */\n\n/*\n** The remainder of this file contains the declarations of the functions\n** that make up the Pager sub-system API. See source code comments for \n** a detailed description of each routine.\n*/\n\n/* Open and close a Pager connection. */ \nSQLITE_PRIVATE int sqlite3PagerOpen(\n  sqlite3_vfs*,\n  Pager **ppPager,\n  const char*,\n  int,\n  int,\n  int,\n  void(*)(DbPage*)\n);\nSQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);\nSQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);\n\n/* Functions used to configure a Pager object. */\nSQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);\nSQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);\nSQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);\nSQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);\nSQLITE_PRIVATE void sqlite3PagerShrink(Pager*);\nSQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);\nSQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);\nSQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);\nSQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);\nSQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);\nSQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);\nSQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);\n\n/* Functions used to obtain and release page references. */ \nSQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);\n#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)\nSQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);\nSQLITE_PRIVATE void sqlite3PagerRef(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);\n\n/* Operations on page references. */\nSQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);\nSQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);\nSQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);\nSQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);\nSQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); \nSQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); \n\n/* Functions used to manage pager transactions and savepoints. */\nSQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);\nSQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);\nSQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);\nSQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);\nSQLITE_PRIVATE int sqlite3PagerRollback(Pager*);\nSQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);\nSQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);\nSQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);\n\nSQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);\nSQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);\nSQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);\nSQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);\nSQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);\n#ifdef SQLITE_ENABLE_ZIPVFS\nSQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);\n#endif\n\n/* Functions used to query pager state and configuration. */\nSQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);\nSQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);\nSQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);\nSQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);\nSQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);\nSQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);\nSQLITE_PRIVATE int sqlite3PagerNosync(Pager*);\nSQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);\nSQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);\nSQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);\nSQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);\n\n/* Functions used to truncate the database file. */\nSQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);\n\n#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)\nSQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);\n#endif\n\n/* Functions to support testing and debugging. */\n#if !defined(NDEBUG) || defined(SQLITE_TEST)\nSQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);\nSQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);\n#endif\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);\nSQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);\n  void disable_simulated_io_errors(void);\n  void enable_simulated_io_errors(void);\n#else\n# define disable_simulated_io_errors()\n# define enable_simulated_io_errors()\n#endif\n\n#endif /* _PAGER_H_ */\n\n/************** End of pager.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include pcache.h in the middle of sqliteInt.h ****************/\n/************** Begin file pcache.h ******************************************/\n/*\n** 2008 August 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the sqlite page cache\n** subsystem. \n*/\n\n#ifndef _PCACHE_H_\n\ntypedef struct PgHdr PgHdr;\ntypedef struct PCache PCache;\n\n/*\n** Every page in the cache is controlled by an instance of the following\n** structure.\n*/\nstruct PgHdr {\n  sqlite3_pcache_page *pPage;    /* Pcache object page handle */\n  void *pData;                   /* Page data */\n  void *pExtra;                  /* Extra content */\n  PgHdr *pDirty;                 /* Transient list of dirty pages */\n  Pager *pPager;                 /* The pager this page is part of */\n  Pgno pgno;                     /* Page number for this page */\n#ifdef SQLITE_CHECK_PAGES\n  u32 pageHash;                  /* Hash of page content */\n#endif\n  u16 flags;                     /* PGHDR flags defined below */\n\n  /**********************************************************************\n  ** Elements above are public.  All that follows is private to pcache.c\n  ** and should not be accessed by other modules.\n  */\n  i16 nRef;                      /* Number of users of this page */\n  PCache *pCache;                /* Cache that owns this page */\n\n  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */\n  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */\n};\n\n/* Bit values for PgHdr.flags */\n#define PGHDR_DIRTY             0x002  /* Page has changed */\n#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before\n                                       ** writing this page to the database */\n#define PGHDR_NEED_READ         0x008  /* Content is unread */\n#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */\n#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */\n\n/* Initialize and shutdown the page cache subsystem */\nSQLITE_PRIVATE int sqlite3PcacheInitialize(void);\nSQLITE_PRIVATE void sqlite3PcacheShutdown(void);\n\n/* Page cache buffer management:\n** These routines implement SQLITE_CONFIG_PAGECACHE.\n*/\nSQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);\n\n/* Create a new pager cache.\n** Under memory stress, invoke xStress to try to make pages clean.\n** Only clean and unpinned pages can be reclaimed.\n*/\nSQLITE_PRIVATE void sqlite3PcacheOpen(\n  int szPage,                    /* Size of every page */\n  int szExtra,                   /* Extra space associated with each page */\n  int bPurgeable,                /* True if pages are on backing store */\n  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */\n  void *pStress,                 /* Argument to xStress */\n  PCache *pToInit                /* Preallocated space for the PCache */\n);\n\n/* Modify the page-size after the cache has been created. */\nSQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);\n\n/* Return the size in bytes of a PCache object.  Used to preallocate\n** storage space.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSize(void);\n\n/* One release per successful fetch.  Page is pinned until released.\n** Reference counted. \n*/\nSQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);\nSQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);\n\nSQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */\nSQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */\nSQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */\nSQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */\n\n/* Change a page number.  Used by incr-vacuum. */\nSQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);\n\n/* Remove all pages with pgno>x.  Reset the cache if x==0 */\nSQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);\n\n/* Get a list of all dirty pages in the cache, sorted by page number */\nSQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);\n\n/* Reset and close the cache object */\nSQLITE_PRIVATE void sqlite3PcacheClose(PCache*);\n\n/* Clear flags from pages of the page cache */\nSQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);\n\n/* Discard the contents of the cache */\nSQLITE_PRIVATE void sqlite3PcacheClear(PCache*);\n\n/* Return the total number of outstanding page references */\nSQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);\n\n/* Increment the reference count of an existing page */\nSQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);\n\nSQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);\n\n/* Return the total number of pages stored in the cache */\nSQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);\n\n#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)\n/* Iterate through all dirty pages currently stored in the cache. This\n** interface is only available if SQLITE_CHECK_PAGES is defined when the \n** library is built.\n*/\nSQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));\n#endif\n\n/* Set and get the suggested cache-size for the specified pager-cache.\n**\n** If no global maximum is configured, then the system attempts to limit\n** the total number of pages cached by purgeable pager-caches to the sum\n** of the suggested cache-sizes.\n*/\nSQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);\n#endif\n\n/* Free up as much memory as possible from the page cache */\nSQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/* Try to return memory used by the pcache module to the main memory heap */\nSQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);\n#endif\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);\n#endif\n\nSQLITE_PRIVATE void sqlite3PCacheSetDefault(void);\n\n#endif /* _PCACHE_H_ */\n\n/************** End of pcache.h **********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n/************** Include os.h in the middle of sqliteInt.h ********************/\n/************** Begin file os.h **********************************************/\n/*\n** 2001 September 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file (together with is companion C source-code file\n** \"os.c\") attempt to abstract the underlying operating system so that\n** the SQLite library will work on both POSIX and windows systems.\n**\n** This header file is #include-ed by sqliteInt.h and thus ends up\n** being included by every source file.\n*/\n#ifndef _SQLITE_OS_H_\n#define _SQLITE_OS_H_\n\n/*\n** Figure out if we are dealing with Unix, Windows, or some other\n** operating system.  After the following block of preprocess macros,\n** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER \n** will defined to either 1 or 0.  One of the four will be 1.  The other \n** three will be 0.\n*/\n#if defined(SQLITE_OS_OTHER)\n# if SQLITE_OS_OTHER==1\n#   undef SQLITE_OS_UNIX\n#   define SQLITE_OS_UNIX 0\n#   undef SQLITE_OS_WIN\n#   define SQLITE_OS_WIN 0\n# else\n#   undef SQLITE_OS_OTHER\n# endif\n#endif\n#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)\n# define SQLITE_OS_OTHER 0\n# ifndef SQLITE_OS_WIN\n#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)\n#     define SQLITE_OS_WIN 1\n#     define SQLITE_OS_UNIX 0\n#   else\n#     define SQLITE_OS_WIN 0\n#     define SQLITE_OS_UNIX 1\n#  endif\n# else\n#  define SQLITE_OS_UNIX 0\n# endif\n#else\n# ifndef SQLITE_OS_WIN\n#  define SQLITE_OS_WIN 0\n# endif\n#endif\n\n#if SQLITE_OS_WIN\n# include <windows.h>\n#endif\n\n/*\n** Determine if we are dealing with Windows NT.\n**\n** We ought to be able to determine if we are compiling for win98 or winNT\n** using the _WIN32_WINNT macro as follows:\n**\n** #if defined(_WIN32_WINNT)\n** # define SQLITE_OS_WINNT 1\n** #else\n** # define SQLITE_OS_WINNT 0\n** #endif\n**\n** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,\n** so the above test does not work.  We'll just assume that everything is\n** winNT unless the programmer explicitly says otherwise by setting\n** SQLITE_OS_WINNT to 0.\n*/\n#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)\n# define SQLITE_OS_WINNT 1\n#endif\n\n/*\n** Determine if we are dealing with WindowsCE - which has a much\n** reduced API.\n*/\n#if defined(_WIN32_WCE)\n# define SQLITE_OS_WINCE 1\n#else\n# define SQLITE_OS_WINCE 0\n#endif\n\n/*\n** Determine if we are dealing with WinRT, which provides only a subset of\n** the full Win32 API.\n*/\n#if !defined(SQLITE_OS_WINRT)\n# define SQLITE_OS_WINRT 0\n#endif\n\n/*\n** When compiled for WinCE or WinRT, there is no concept of the current\n** directory.\n */\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n# define SQLITE_CURDIR 1\n#endif\n\n/* If the SET_FULLSYNC macro is not defined above, then make it\n** a no-op\n*/\n#ifndef SET_FULLSYNC\n# define SET_FULLSYNC(x,y)\n#endif\n\n/*\n** The default size of a disk sector\n*/\n#ifndef SQLITE_DEFAULT_SECTOR_SIZE\n# define SQLITE_DEFAULT_SECTOR_SIZE 4096\n#endif\n\n/*\n** Temporary files are named starting with this prefix followed by 16 random\n** alphanumeric characters, and no file extension. They are stored in the\n** OS's standard temporary file directory, and are deleted prior to exit.\n** If sqlite is being embedded in another program, you may wish to change the\n** prefix to reflect your program's name, so that if your program exits\n** prematurely, old temporary files can be easily identified. This can be done\n** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.\n**\n** 2006-10-31:  The default prefix used to be \"sqlite_\".  But then\n** Mcafee started using SQLite in their anti-virus product and it\n** started putting files with the \"sqlite\" name in the c:/temp folder.\n** This annoyed many windows users.  Those users would then do a \n** Google search for \"sqlite\", find the telephone numbers of the\n** developers and call to wake them up at night and complain.\n** For this reason, the default name prefix is changed to be \"sqlite\" \n** spelled backwards.  So the temp files are still identified, but\n** anybody smart enough to figure out the code is also likely smart\n** enough to know that calling the developer will not help get rid\n** of the file.\n*/\n#ifndef SQLITE_TEMP_FILE_PREFIX\n# define SQLITE_TEMP_FILE_PREFIX \"etilqs_\"\n#endif\n\n/*\n** The following values may be passed as the second argument to\n** sqlite3OsLock(). The various locks exhibit the following semantics:\n**\n** SHARED:    Any number of processes may hold a SHARED lock simultaneously.\n** RESERVED:  A single process may hold a RESERVED lock on a file at\n**            any time. Other processes may hold and obtain new SHARED locks.\n** PENDING:   A single process may hold a PENDING lock on a file at\n**            any one time. Existing SHARED locks may persist, but no new\n**            SHARED locks may be obtained by other processes.\n** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.\n**\n** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a\n** process that requests an EXCLUSIVE lock may actually obtain a PENDING\n** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to\n** sqlite3OsLock().\n*/\n#define NO_LOCK         0\n#define SHARED_LOCK     1\n#define RESERVED_LOCK   2\n#define PENDING_LOCK    3\n#define EXCLUSIVE_LOCK  4\n\n/*\n** File Locking Notes:  (Mostly about windows but also some info for Unix)\n**\n** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because\n** those functions are not available.  So we use only LockFile() and\n** UnlockFile().\n**\n** LockFile() prevents not just writing but also reading by other processes.\n** A SHARED_LOCK is obtained by locking a single randomly-chosen \n** byte out of a specific range of bytes. The lock byte is obtained at \n** random so two separate readers can probably access the file at the \n** same time, unless they are unlucky and choose the same lock byte.\n** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.\n** There can only be one writer.  A RESERVED_LOCK is obtained by locking\n** a single byte of the file that is designated as the reserved lock byte.\n** A PENDING_LOCK is obtained by locking a designated byte different from\n** the RESERVED_LOCK byte.\n**\n** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,\n** which means we can use reader/writer locks.  When reader/writer locks\n** are used, the lock is placed on the same range of bytes that is used\n** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme\n** will support two or more Win95 readers or two or more WinNT readers.\n** But a single Win95 reader will lock out all WinNT readers and a single\n** WinNT reader will lock out all other Win95 readers.\n**\n** The following #defines specify the range of bytes used for locking.\n** SHARED_SIZE is the number of bytes available in the pool from which\n** a random byte is selected for a shared lock.  The pool of bytes for\n** shared locks begins at SHARED_FIRST. \n**\n** The same locking strategy and\n** byte ranges are used for Unix.  This leaves open the possiblity of having\n** clients on win95, winNT, and unix all talking to the same shared file\n** and all locking correctly.  To do so would require that samba (or whatever\n** tool is being used for file sharing) implements locks correctly between\n** windows and unix.  I'm guessing that isn't likely to happen, but by\n** using the same locking range we are at least open to the possibility.\n**\n** Locking in windows is manditory.  For this reason, we cannot store\n** actual data in the bytes used for locking.  The pager never allocates\n** the pages involved in locking therefore.  SHARED_SIZE is selected so\n** that all locks will fit on a single page even at the minimum page size.\n** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE\n** is set high so that we don't have to allocate an unused page except\n** for very large databases.  But one should test the page skipping logic \n** by setting PENDING_BYTE low and running the entire regression suite.\n**\n** Changing the value of PENDING_BYTE results in a subtly incompatible\n** file format.  Depending on how it is changed, you might not notice\n** the incompatibility right away, even running a full regression test.\n** The default location of PENDING_BYTE is the first byte past the\n** 1GB boundary.\n**\n*/\n#ifdef SQLITE_OMIT_WSD\n# define PENDING_BYTE     (0x40000000)\n#else\n# define PENDING_BYTE      sqlite3PendingByte\n#endif\n#define RESERVED_BYTE     (PENDING_BYTE+1)\n#define SHARED_FIRST      (PENDING_BYTE+2)\n#define SHARED_SIZE       510\n\n/*\n** Wrapper around OS specific sqlite3_os_init() function.\n*/\nSQLITE_PRIVATE int sqlite3OsInit(void);\n\n/* \n** Functions for accessing sqlite3_file methods \n*/\nSQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);\nSQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);\nSQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);\nSQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);\nSQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);\nSQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);\nSQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);\nSQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);\nSQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);\n#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0\nSQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);\nSQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);\nSQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);\nSQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);\nSQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);\nSQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);\n\n\n/* \n** Functions for accessing sqlite3_vfs methods \n*/\nSQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);\nSQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);\nSQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);\nSQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);\nSQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);\nSQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);\nSQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\nSQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);\nSQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);\nSQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);\n\n/*\n** Convenience functions for opening and closing files using \n** sqlite3_malloc() to obtain space for the file-handle structure.\n*/\nSQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);\nSQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);\n\n#endif /* _SQLITE_OS_H_ */\n\n/************** End of os.h **************************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n/************** Include mutex.h in the middle of sqliteInt.h *****************/\n/************** Begin file mutex.h *******************************************/\n/*\n** 2007 August 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the common header for all mutex implementations.\n** The sqliteInt.h header #includes this file so that it is available\n** to all source files.  We break it out in an effort to keep the code\n** better organized.\n**\n** NOTE:  source files should *not* #include this header file directly.\n** Source files should #include the sqliteInt.h file and let that file\n** include this one indirectly.\n*/\n\n\n/*\n** Figure out what version of the code to use.  The choices are\n**\n**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The\n**                             mutexes implemention cannot be overridden\n**                             at start-time.\n**\n**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No\n**                             mutual exclusion is provided.  But this\n**                             implementation can be overridden at\n**                             start-time.\n**\n**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.\n**\n**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.\n*/\n#if !SQLITE_THREADSAFE\n# define SQLITE_MUTEX_OMIT\n#endif\n#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)\n#  if SQLITE_OS_UNIX\n#    define SQLITE_MUTEX_PTHREADS\n#  elif SQLITE_OS_WIN\n#    define SQLITE_MUTEX_W32\n#  else\n#    define SQLITE_MUTEX_NOOP\n#  endif\n#endif\n\n#ifdef SQLITE_MUTEX_OMIT\n/*\n** If this is a no-op implementation, implement everything as macros.\n*/\n#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)\n#define sqlite3_mutex_free(X)\n#define sqlite3_mutex_enter(X)    \n#define sqlite3_mutex_try(X)      SQLITE_OK\n#define sqlite3_mutex_leave(X)    \n#define sqlite3_mutex_held(X)     ((void)(X),1)\n#define sqlite3_mutex_notheld(X)  ((void)(X),1)\n#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)\n#define sqlite3MutexInit()        SQLITE_OK\n#define sqlite3MutexEnd()\n#define MUTEX_LOGIC(X)\n#else\n#define MUTEX_LOGIC(X)            X\n#endif /* defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex.h ***********************************************/\n/************** Continuing where we left off in sqliteInt.h ******************/\n\n\n/*\n** Each database file to be accessed by the system is an instance\n** of the following structure.  There are normally two of these structures\n** in the sqlite.aDb[] array.  aDb[0] is the main database file and\n** aDb[1] is the database file used to hold temporary tables.  Additional\n** databases may be attached.\n*/\nstruct Db {\n  char *zName;         /* Name of this database */\n  Btree *pBt;          /* The B*Tree structure for this database file */\n  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */\n  u8 safety_level;     /* How aggressive at syncing data to disk */\n  Schema *pSchema;     /* Pointer to database schema (possibly shared) */\n};\n\n/*\n** An instance of the following structure stores a database schema.\n**\n** Most Schema objects are associated with a Btree.  The exception is\n** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.\n** In shared cache mode, a single Schema object can be shared by multiple\n** Btrees that refer to the same underlying BtShared object.\n** \n** Schema objects are automatically deallocated when the last Btree that\n** references them is destroyed.   The TEMP Schema is manually freed by\n** sqlite3_close().\n*\n** A thread must be holding a mutex on the corresponding Btree in order\n** to access Schema content.  This implies that the thread must also be\n** holding a mutex on the sqlite3 connection pointer that owns the Btree.\n** For a TEMP Schema, only the connection mutex is required.\n*/\nstruct Schema {\n  int schema_cookie;   /* Database schema version number for this file */\n  int iGeneration;     /* Generation counter.  Incremented with each change */\n  Hash tblHash;        /* All tables indexed by name */\n  Hash idxHash;        /* All (named) indices indexed by name */\n  Hash trigHash;       /* All triggers indexed by name */\n  Hash fkeyHash;       /* All foreign keys by referenced table name */\n  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */\n  u8 file_format;      /* Schema format version for this file */\n  u8 enc;              /* Text encoding used by this database */\n  u16 flags;           /* Flags associated with this schema */\n  int cache_size;      /* Number of pages to use in the cache */\n};\n\n/*\n** These macros can be used to test, set, or clear bits in the \n** Db.pSchema->flags field.\n*/\n#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))\n#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)\n#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)\n#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)\n\n/*\n** Allowed values for the DB.pSchema->flags field.\n**\n** The DB_SchemaLoaded flag is set after the database schema has been\n** read into internal hash tables.\n**\n** DB_UnresetViews means that one or more views have column names that\n** have been filled out.  If the schema changes, these column names might\n** changes and so the view will need to be reset.\n*/\n#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */\n#define DB_UnresetViews    0x0002  /* Some views have defined column names */\n#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */\n\n/*\n** The number of different kinds of things that can be limited\n** using the sqlite3_limit() interface.\n*/\n#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)\n\n/*\n** Lookaside malloc is a set of fixed-size buffers that can be used\n** to satisfy small transient memory allocation requests for objects\n** associated with a particular database connection.  The use of\n** lookaside malloc provides a significant performance enhancement\n** (approx 10%) by avoiding numerous malloc/free requests while parsing\n** SQL statements.\n**\n** The Lookaside structure holds configuration information about the\n** lookaside malloc subsystem.  Each available memory allocation in\n** the lookaside subsystem is stored on a linked list of LookasideSlot\n** objects.\n**\n** Lookaside allocations are only allowed for objects that are associated\n** with a particular database connection.  Hence, schema information cannot\n** be stored in lookaside because in shared cache mode the schema information\n** is shared by multiple database connections.  Therefore, while parsing\n** schema information, the Lookaside.bEnabled flag is cleared so that\n** lookaside allocations are not used to construct the schema objects.\n*/\nstruct Lookaside {\n  u16 sz;                 /* Size of each buffer in bytes */\n  u8 bEnabled;            /* False to disable new lookaside allocations */\n  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */\n  int nOut;               /* Number of buffers currently checked out */\n  int mxOut;              /* Highwater mark for nOut */\n  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */\n  LookasideSlot *pFree;   /* List of available buffers */\n  void *pStart;           /* First byte of available memory space */\n  void *pEnd;             /* First byte past end of available space */\n};\nstruct LookasideSlot {\n  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */\n};\n\n/*\n** A hash table for function definitions.\n**\n** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.\n** Collisions are on the FuncDef.pHash chain.\n*/\nstruct FuncDefHash {\n  FuncDef *a[23];       /* Hash table for functions */\n};\n\n/*\n** Each database connection is an instance of the following structure.\n*/\nstruct sqlite3 {\n  sqlite3_vfs *pVfs;            /* OS Interface */\n  struct Vdbe *pVdbe;           /* List of active virtual machines */\n  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */\n  sqlite3_mutex *mutex;         /* Connection mutex */\n  Db *aDb;                      /* All backends */\n  int nDb;                      /* Number of backends currently in use */\n  int flags;                    /* Miscellaneous flags. See below */\n  i64 lastRowid;                /* ROWID of most recent insert (see above) */\n  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */\n  int errCode;                  /* Most recent error code (SQLITE_*) */\n  int errMask;                  /* & result codes with this before returning */\n  u8 autoCommit;                /* The auto-commit flag. */\n  u8 temp_store;                /* 1: file 2: memory 0: default */\n  u8 mallocFailed;              /* True if we have seen a malloc failure */\n  u8 dfltLockMode;              /* Default locking-mode for attached dbs */\n  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */\n  u8 suppressErr;               /* Do not issue error messages if true */\n  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */\n  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */\n  int nextPagesize;             /* Pagesize after VACUUM if >0 */\n  u32 magic;                    /* Magic number for detect library misuse */\n  int nChange;                  /* Value returned by sqlite3_changes() */\n  int nTotalChange;             /* Value returned by sqlite3_total_changes() */\n  int aLimit[SQLITE_N_LIMIT];   /* Limits */\n  struct sqlite3InitInfo {      /* Information used during initialization */\n    int newTnum;                /* Rootpage of table being initialized */\n    u8 iDb;                     /* Which db file is being initialized */\n    u8 busy;                    /* TRUE if currently initializing */\n    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */\n  } init;\n  int activeVdbeCnt;            /* Number of VDBEs currently executing */\n  int writeVdbeCnt;             /* Number of active VDBEs that are writing */\n  int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */\n  int nExtension;               /* Number of loaded extensions */\n  void **aExtension;            /* Array of shared library handles */\n  void (*xTrace)(void*,const char*);        /* Trace function */\n  void *pTraceArg;                          /* Argument to the trace function */\n  void (*xProfile)(void*,const char*,u64);  /* Profiling function */\n  void *pProfileArg;                        /* Argument to profile function */\n  void *pCommitArg;                 /* Argument to xCommitCallback() */   \n  int (*xCommitCallback)(void*);    /* Invoked at every commit. */\n  void *pRollbackArg;               /* Argument to xRollbackCallback() */   \n  void (*xRollbackCallback)(void*); /* Invoked at every commit. */\n  void *pUpdateArg;\n  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);\n#ifndef SQLITE_OMIT_WAL\n  int (*xWalCallback)(void *, sqlite3 *, const char *, int);\n  void *pWalArg;\n#endif\n  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);\n  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);\n  void *pCollNeededArg;\n  sqlite3_value *pErr;          /* Most recent error message */\n  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */\n  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */\n  union {\n    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */\n    double notUsed1;            /* Spacer */\n  } u1;\n  Lookaside lookaside;          /* Lookaside malloc configuration */\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);\n                                /* Access authorization function */\n  void *pAuthArg;               /* 1st argument to the access auth function */\n#endif\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  int (*xProgress)(void *);     /* The progress callback */\n  void *pProgressArg;           /* Argument to the progress callback */\n  int nProgressOps;             /* Number of opcodes for progress callback */\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int nVTrans;                  /* Allocated size of aVTrans */\n  Hash aModule;                 /* populated by sqlite3_create_module() */\n  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */\n  VTable **aVTrans;             /* Virtual tables with open transactions */\n  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */\n#endif\n  FuncDefHash aFunc;            /* Hash table of connection functions */\n  Hash aCollSeq;                /* All collating sequences */\n  BusyHandler busyHandler;      /* Busy callback */\n  Db aDbStatic[2];              /* Static space for the 2 default backends */\n  Savepoint *pSavepoint;        /* List of active savepoints */\n  int busyTimeout;              /* Busy handler timeout, in msec */\n  int nSavepoint;               /* Number of non-transaction savepoints */\n  int nStatement;               /* Number of nested statement-transactions  */\n  i64 nDeferredCons;            /* Net deferred constraints this transaction. */\n  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */\n\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n  /* The following variables are all protected by the STATIC_MASTER \n  ** mutex, not by sqlite3.mutex. They are used by code in notify.c. \n  **\n  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to\n  ** unlock so that it can proceed.\n  **\n  ** When X.pBlockingConnection==Y, that means that something that X tried\n  ** tried to do recently failed with an SQLITE_LOCKED error due to locks\n  ** held by Y.\n  */\n  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */\n  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */\n  void *pUnlockArg;                     /* Argument to xUnlockNotify */\n  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */\n  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */\n#endif\n};\n\n/*\n** A macro to discover the encoding of a database.\n*/\n#define ENC(db) ((db)->aDb[0].pSchema->enc)\n\n/*\n** Possible values for the sqlite3.flags.\n*/\n#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */\n#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */\n#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */\n#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */\n#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */\n                                          /*   DELETE, or UPDATE and return */\n                                          /*   the count using a callback. */\n#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */\n                                          /*   result set is empty */\n#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */\n#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */\n#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */\n                         /*   0x00020000  Unused */\n#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */\n#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */\n#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */\n#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */\n#define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */\n#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */\n#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */\n#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */\n#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */\n#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */\n#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */\n#define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */\n#define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */\n\n/*\n** Bits of the sqlite3.flags field that are used by the\n** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.\n** These must be the low-order bits of the flags field.\n*/\n#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */\n#define SQLITE_ColumnCache    0x02        /* Disable the column cache */\n#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */\n#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */\n#define SQLITE_IndexCover     0x10        /* Disable index covering table */\n#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */\n#define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */\n#define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */\n#define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */\n#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */\n\n/*\n** Possible values for the sqlite.magic field.\n** The numbers are obtained at random and have no special meaning, other\n** than being distinct from one another.\n*/\n#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */\n#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */\n#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */\n#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */\n#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */\n#define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */\n\n/*\n** Each SQL function is defined by an instance of the following\n** structure.  A pointer to this structure is stored in the sqlite.aFunc\n** hash table.  When multiple functions have the same name, the hash table\n** points to a linked list of these structures.\n*/\nstruct FuncDef {\n  i16 nArg;            /* Number of arguments.  -1 means unlimited */\n  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */\n  u8 flags;            /* Some combination of SQLITE_FUNC_* */\n  void *pUserData;     /* User data parameter */\n  FuncDef *pNext;      /* Next function with same name */\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */\n  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */\n  char *zName;         /* SQL name of the function. */\n  FuncDef *pHash;      /* Next with a different name but the same hash */\n  FuncDestructor *pDestructor;   /* Reference counted destructor function */\n};\n\n/*\n** This structure encapsulates a user-function destructor callback (as\n** configured using create_function_v2()) and a reference counter. When\n** create_function_v2() is called to create a function with a destructor,\n** a single object of this type is allocated. FuncDestructor.nRef is set to \n** the number of FuncDef objects created (either 1 or 3, depending on whether\n** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor\n** member of each of the new FuncDef objects is set to point to the allocated\n** FuncDestructor.\n**\n** Thereafter, when one of the FuncDef objects is deleted, the reference\n** count on this object is decremented. When it reaches 0, the destructor\n** is invoked and the FuncDestructor structure freed.\n*/\nstruct FuncDestructor {\n  int nRef;\n  void (*xDestroy)(void *);\n  void *pUserData;\n};\n\n/*\n** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF\n** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There\n** are assert() statements in the code to verify this.\n*/\n#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */\n#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */\n#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */\n#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */\n#define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */\n#define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */\n#define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */\n#define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */\n\n/*\n** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are\n** used to create the initializers for the FuncDef structures.\n**\n**   FUNCTION(zName, nArg, iArg, bNC, xFunc)\n**     Used to create a scalar function definition of a function zName \n**     implemented by C function xFunc that accepts nArg arguments. The\n**     value passed as iArg is cast to a (void*) and made available\n**     as the user-data (sqlite3_user_data()) for the function. If \n**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.\n**\n**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)\n**     Used to create an aggregate function definition implemented by\n**     the C functions xStep and xFinal. The first four parameters\n**     are interpreted in the same way as the first 4 parameters to\n**     FUNCTION().\n**\n**   LIKEFUNC(zName, nArg, pArg, flags)\n**     Used to create a scalar function definition of a function zName \n**     that accepts nArg arguments and is implemented by a call to C \n**     function likeFunc. Argument pArg is cast to a (void *) and made\n**     available as the function user-data (sqlite3_user_data()). The\n**     FuncDef.flags variable is set to the value passed as the flags\n**     parameter.\n*/\n#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \\\n  {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}\n#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \\\n  {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \\\n   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}\n#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \\\n  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \\\n   pArg, 0, xFunc, 0, 0, #zName, 0, 0}\n#define LIKEFUNC(zName, nArg, arg, flags) \\\n  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}\n#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \\\n  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \\\n   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}\n\n/*\n** All current savepoints are stored in a linked list starting at\n** sqlite3.pSavepoint. The first element in the list is the most recently\n** opened savepoint. Savepoints are added to the list by the vdbe\n** OP_Savepoint instruction.\n*/\nstruct Savepoint {\n  char *zName;                        /* Savepoint name (nul-terminated) */\n  i64 nDeferredCons;                  /* Number of deferred fk violations */\n  Savepoint *pNext;                   /* Parent savepoint (if any) */\n};\n\n/*\n** The following are used as the second parameter to sqlite3Savepoint(),\n** and as the P1 argument to the OP_Savepoint instruction.\n*/\n#define SAVEPOINT_BEGIN      0\n#define SAVEPOINT_RELEASE    1\n#define SAVEPOINT_ROLLBACK   2\n\n\n/*\n** Each SQLite module (virtual table definition) is defined by an\n** instance of the following structure, stored in the sqlite3.aModule\n** hash table.\n*/\nstruct Module {\n  const sqlite3_module *pModule;       /* Callback pointers */\n  const char *zName;                   /* Name passed to create_module() */\n  void *pAux;                          /* pAux passed to create_module() */\n  void (*xDestroy)(void *);            /* Module destructor function */\n};\n\n/*\n** information about each column of an SQL table is held in an instance\n** of this structure.\n*/\nstruct Column {\n  char *zName;     /* Name of this column */\n  Expr *pDflt;     /* Default value of this column */\n  char *zDflt;     /* Original text of the default value */\n  char *zType;     /* Data type for this column */\n  char *zColl;     /* Collating sequence.  If NULL, use the default */\n  u8 notNull;      /* True if there is a NOT NULL constraint */\n  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */\n  char affinity;   /* One of the SQLITE_AFF_... values */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  u8 isHidden;     /* True if this column is 'hidden' */\n#endif\n};\n\n/*\n** A \"Collating Sequence\" is defined by an instance of the following\n** structure. Conceptually, a collating sequence consists of a name and\n** a comparison routine that defines the order of that sequence.\n**\n** There may two separate implementations of the collation function, one\n** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that\n** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine\n** native byte order. When a collation sequence is invoked, SQLite selects\n** the version that will require the least expensive encoding\n** translations, if any.\n**\n** The CollSeq.pUser member variable is an extra parameter that passed in\n** as the first argument to the UTF-8 comparison function, xCmp.\n** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,\n** xCmp16.\n**\n** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the\n** collating sequence is undefined.  Indices built on an undefined\n** collating sequence may not be read or written.\n*/\nstruct CollSeq {\n  char *zName;          /* Name of the collating sequence, UTF-8 encoded */\n  u8 enc;               /* Text encoding handled by xCmp() */\n  void *pUser;          /* First argument to xCmp() */\n  int (*xCmp)(void*,int, const void*, int, const void*);\n  void (*xDel)(void*);  /* Destructor for pUser */\n};\n\n/*\n** A sort order can be either ASC or DESC.\n*/\n#define SQLITE_SO_ASC       0  /* Sort in ascending order */\n#define SQLITE_SO_DESC      1  /* Sort in ascending order */\n\n/*\n** Column affinity types.\n**\n** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and\n** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve\n** the speed a little by numbering the values consecutively.  \n**\n** But rather than start with 0 or 1, we begin with 'a'.  That way,\n** when multiple affinity types are concatenated into a string and\n** used as the P4 operand, they will be more readable.\n**\n** Note also that the numeric types are grouped together so that testing\n** for a numeric type is a single comparison.\n*/\n#define SQLITE_AFF_TEXT     'a'\n#define SQLITE_AFF_NONE     'b'\n#define SQLITE_AFF_NUMERIC  'c'\n#define SQLITE_AFF_INTEGER  'd'\n#define SQLITE_AFF_REAL     'e'\n\n#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)\n\n/*\n** The SQLITE_AFF_MASK values masks off the significant bits of an\n** affinity value. \n*/\n#define SQLITE_AFF_MASK     0x67\n\n/*\n** Additional bit values that can be ORed with an affinity without\n** changing the affinity.\n*/\n#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */\n#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */\n#define SQLITE_NULLEQ       0x80  /* NULL=NULL */\n\n/*\n** An object of this type is created for each virtual table present in\n** the database schema. \n**\n** If the database schema is shared, then there is one instance of this\n** structure for each database connection (sqlite3*) that uses the shared\n** schema. This is because each database connection requires its own unique\n** instance of the sqlite3_vtab* handle used to access the virtual table \n** implementation. sqlite3_vtab* handles can not be shared between \n** database connections, even when the rest of the in-memory database \n** schema is shared, as the implementation often stores the database\n** connection handle passed to it via the xConnect() or xCreate() method\n** during initialization internally. This database connection handle may\n** then be used by the virtual table implementation to access real tables \n** within the database. So that they appear as part of the callers \n** transaction, these accesses need to be made via the same database \n** connection as that used to execute SQL operations on the virtual table.\n**\n** All VTable objects that correspond to a single table in a shared\n** database schema are initially stored in a linked-list pointed to by\n** the Table.pVTable member variable of the corresponding Table object.\n** When an sqlite3_prepare() operation is required to access the virtual\n** table, it searches the list for the VTable that corresponds to the\n** database connection doing the preparing so as to use the correct\n** sqlite3_vtab* handle in the compiled query.\n**\n** When an in-memory Table object is deleted (for example when the\n** schema is being reloaded for some reason), the VTable objects are not \n** deleted and the sqlite3_vtab* handles are not xDisconnect()ed \n** immediately. Instead, they are moved from the Table.pVTable list to\n** another linked list headed by the sqlite3.pDisconnect member of the\n** corresponding sqlite3 structure. They are then deleted/xDisconnected \n** next time a statement is prepared using said sqlite3*. This is done\n** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.\n** Refer to comments above function sqlite3VtabUnlockList() for an\n** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect\n** list without holding the corresponding sqlite3.mutex mutex.\n**\n** The memory for objects of this type is always allocated by \n** sqlite3DbMalloc(), using the connection handle stored in VTable.db as \n** the first argument.\n*/\nstruct VTable {\n  sqlite3 *db;              /* Database connection associated with this table */\n  Module *pMod;             /* Pointer to module implementation */\n  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */\n  int nRef;                 /* Number of pointers to this structure */\n  u8 bConstraint;           /* True if constraints are supported */\n  int iSavepoint;           /* Depth of the SAVEPOINT stack */\n  VTable *pNext;            /* Next in linked list (see above) */\n};\n\n/*\n** Each SQL table is represented in memory by an instance of the\n** following structure.\n**\n** Table.zName is the name of the table.  The case of the original\n** CREATE TABLE statement is stored, but case is not significant for\n** comparisons.\n**\n** Table.nCol is the number of columns in this table.  Table.aCol is a\n** pointer to an array of Column structures, one for each column.\n**\n** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of\n** the column that is that key.   Otherwise Table.iPKey is negative.  Note\n** that the datatype of the PRIMARY KEY must be INTEGER for this field to\n** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of\n** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid\n** is generated for each row of the table.  TF_HasPrimaryKey is set if\n** the table has any PRIMARY KEY, INTEGER or otherwise.\n**\n** Table.tnum is the page number for the root BTree page of the table in the\n** database file.  If Table.iDb is the index of the database table backend\n** in sqlite.aDb[].  0 is for the main database and 1 is for the file that\n** holds temporary tables and indices.  If TF_Ephemeral is set\n** then the table is stored in a file that is automatically deleted\n** when the VDBE cursor to the table is closed.  In this case Table.tnum \n** refers VDBE cursor number that holds the table open, not to the root\n** page number.  Transient tables are used to hold the results of a\n** sub-query that appears instead of a real table name in the FROM clause \n** of a SELECT statement.\n*/\nstruct Table {\n  char *zName;         /* Name of the table or view */\n  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */\n  int nCol;            /* Number of columns in this table */\n  Column *aCol;        /* Information about each column */\n  Index *pIndex;       /* List of SQL indexes on this table. */\n  int tnum;            /* Root BTree node for this table (see note above) */\n  tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */\n  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */\n  u16 nRef;            /* Number of pointers to this Table */\n  u8 tabFlags;         /* Mask of TF_* values */\n  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */\n  FKey *pFKey;         /* Linked list of all foreign keys in this table */\n  char *zColAff;       /* String defining the affinity of each column */\n#ifndef SQLITE_OMIT_CHECK\n  ExprList *pCheck;    /* All CHECK constraints */\n#endif\n#ifndef SQLITE_OMIT_ALTERTABLE\n  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  VTable *pVTable;     /* List of VTable objects. */\n  int nModuleArg;      /* Number of arguments to the module */\n  char **azModuleArg;  /* Text of all module args. [0] is module name */\n#endif\n  Trigger *pTrigger;   /* List of triggers stored in pSchema */\n  Schema *pSchema;     /* Schema that contains this table */\n  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */\n};\n\n/*\n** Allowed values for Tabe.tabFlags.\n*/\n#define TF_Readonly        0x01    /* Read-only system table */\n#define TF_Ephemeral       0x02    /* An ephemeral table */\n#define TF_HasPrimaryKey   0x04    /* Table has a primary key */\n#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */\n#define TF_Virtual         0x10    /* Is a virtual table */\n\n\n/*\n** Test to see whether or not a table is a virtual table.  This is\n** done as a macro so that it will be optimized out when virtual\n** table support is omitted from the build.\n*/\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)\n#  define IsHiddenColumn(X) ((X)->isHidden)\n#else\n#  define IsVirtual(X)      0\n#  define IsHiddenColumn(X) 0\n#endif\n\n/*\n** Each foreign key constraint is an instance of the following structure.\n**\n** A foreign key is associated with two tables.  The \"from\" table is\n** the table that contains the REFERENCES clause that creates the foreign\n** key.  The \"to\" table is the table that is named in the REFERENCES clause.\n** Consider this example:\n**\n**     CREATE TABLE ex1(\n**       a INTEGER PRIMARY KEY,\n**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)\n**     );\n**\n** For foreign key \"fk1\", the from-table is \"ex1\" and the to-table is \"ex2\".\n**\n** Each REFERENCES clause generates an instance of the following structure\n** which is attached to the from-table.  The to-table need not exist when\n** the from-table is created.  The existence of the to-table is not checked.\n*/\nstruct FKey {\n  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */\n  FKey *pNextFrom;  /* Next foreign key in pFrom */\n  char *zTo;        /* Name of table that the key points to (aka: Parent) */\n  FKey *pNextTo;    /* Next foreign key on table named zTo */\n  FKey *pPrevTo;    /* Previous foreign key on table named zTo */\n  int nCol;         /* Number of columns in this key */\n  /* EV: R-30323-21917 */\n  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */\n  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */\n  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */\n  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */\n    int iFrom;         /* Index of column in pFrom */\n    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */\n  } aCol[1];        /* One entry for each of nCol column s */\n};\n\n/*\n** SQLite supports many different ways to resolve a constraint\n** error.  ROLLBACK processing means that a constraint violation\n** causes the operation in process to fail and for the current transaction\n** to be rolled back.  ABORT processing means the operation in process\n** fails and any prior changes from that one operation are backed out,\n** but the transaction is not rolled back.  FAIL processing means that\n** the operation in progress stops and returns an error code.  But prior\n** changes due to the same operation are not backed out and no rollback\n** occurs.  IGNORE means that the particular row that caused the constraint\n** error is not inserted or updated.  Processing continues and no error\n** is returned.  REPLACE means that preexisting database rows that caused\n** a UNIQUE constraint violation are removed so that the new insert or\n** update can proceed.  Processing continues and no error is reported.\n**\n** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.\n** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the\n** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign\n** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the\n** referenced table row is propagated into the row that holds the\n** foreign key.\n** \n** The following symbolic values are used to record which type\n** of action to take.\n*/\n#define OE_None     0   /* There is no constraint to check */\n#define OE_Rollback 1   /* Fail the operation and rollback the transaction */\n#define OE_Abort    2   /* Back out changes but do no rollback transaction */\n#define OE_Fail     3   /* Stop the operation but leave all prior changes */\n#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */\n#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */\n\n#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */\n#define OE_SetNull  7   /* Set the foreign key value to NULL */\n#define OE_SetDflt  8   /* Set the foreign key value to its default */\n#define OE_Cascade  9   /* Cascade the changes */\n\n#define OE_Default  99  /* Do whatever the default action is */\n\n\n/*\n** An instance of the following structure is passed as the first\n** argument to sqlite3VdbeKeyCompare and is used to control the \n** comparison of the two index keys.\n*/\nstruct KeyInfo {\n  sqlite3 *db;        /* The database connection */\n  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */\n  u16 nField;         /* Number of entries in aColl[] */\n  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */\n  CollSeq *aColl[1];  /* Collating sequence for each term of the key */\n};\n\n/*\n** An instance of the following structure holds information about a\n** single index record that has already been parsed out into individual\n** values.\n**\n** A record is an object that contains one or more fields of data.\n** Records are used to store the content of a table row and to store\n** the key of an index.  A blob encoding of a record is created by\n** the OP_MakeRecord opcode of the VDBE and is disassembled by the\n** OP_Column opcode.\n**\n** This structure holds a record that has already been disassembled\n** into its constituent fields.\n*/\nstruct UnpackedRecord {\n  KeyInfo *pKeyInfo;  /* Collation and sort-order information */\n  u16 nField;         /* Number of entries in apMem[] */\n  u8 flags;           /* Boolean settings.  UNPACKED_... below */\n  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */\n  Mem *aMem;          /* Values */\n};\n\n/*\n** Allowed values of UnpackedRecord.flags\n*/\n#define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */\n#define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */\n#define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */\n\n/*\n** Each SQL index is represented in memory by an\n** instance of the following structure.\n**\n** The columns of the table that are to be indexed are described\n** by the aiColumn[] field of this structure.  For example, suppose\n** we have the following table and index:\n**\n**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);\n**     CREATE INDEX Ex2 ON Ex1(c3,c1);\n**\n** In the Table structure describing Ex1, nCol==3 because there are\n** three columns in the table.  In the Index structure describing\n** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.\n** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the \n** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].\n** The second column to be indexed (c1) has an index of 0 in\n** Ex1.aCol[], hence Ex2.aiColumn[1]==0.\n**\n** The Index.onError field determines whether or not the indexed columns\n** must be unique and what to do if they are not.  When Index.onError=OE_None,\n** it means this is not a unique index.  Otherwise it is a unique index\n** and the value of Index.onError indicate the which conflict resolution \n** algorithm to employ whenever an attempt is made to insert a non-unique\n** element.\n*/\nstruct Index {\n  char *zName;     /* Name of this index */\n  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */\n  tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */\n  Table *pTable;   /* The SQL table being indexed */\n  char *zColAff;   /* String defining the affinity of each column */\n  Index *pNext;    /* The next index associated with the same table */\n  Schema *pSchema; /* Schema containing this index */\n  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */\n  char **azColl;   /* Array of collation sequence names for index */\n  int nColumn;     /* Number of columns in the table used by this index */\n  int tnum;        /* Page containing root of this index in database file */\n  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */\n  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */\n  u8 bUnordered;   /* Use this index for == or IN queries only */\n#ifdef SQLITE_ENABLE_STAT3\n  int nSample;             /* Number of elements in aSample[] */\n  tRowcnt avgEq;           /* Average nEq value for key values not in aSample */\n  IndexSample *aSample;    /* Samples of the left-most key */\n#endif\n};\n\n/*\n** Each sample stored in the sqlite_stat3 table is represented in memory \n** using a structure of this type.  See documentation at the top of the\n** analyze.c source file for additional information.\n*/\nstruct IndexSample {\n  union {\n    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */\n    double r;       /* Value if eType is SQLITE_FLOAT */\n    i64 i;          /* Value if eType is SQLITE_INTEGER */\n  } u;\n  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */\n  int nByte;        /* Size in byte of text or blob. */\n  tRowcnt nEq;      /* Est. number of rows where the key equals this sample */\n  tRowcnt nLt;      /* Est. number of rows where key is less than this sample */\n  tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */\n};\n\n/*\n** Each token coming out of the lexer is an instance of\n** this structure.  Tokens are also used as part of an expression.\n**\n** Note if Token.z==0 then Token.dyn and Token.n are undefined and\n** may contain random values.  Do not make any assumptions about Token.dyn\n** and Token.n when Token.z==0.\n*/\nstruct Token {\n  const char *z;     /* Text of the token.  Not NULL-terminated! */\n  unsigned int n;    /* Number of characters in this token */\n};\n\n/*\n** An instance of this structure contains information needed to generate\n** code for a SELECT that contains aggregate functions.\n**\n** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a\n** pointer to this structure.  The Expr.iColumn field is the index in\n** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate\n** code for that node.\n**\n** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the\n** original Select structure that describes the SELECT statement.  These\n** fields do not need to be freed when deallocating the AggInfo structure.\n*/\nstruct AggInfo {\n  u8 directMode;          /* Direct rendering mode means take data directly\n                          ** from source tables rather than from accumulators */\n  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather\n                          ** than the source table */\n  int sortingIdx;         /* Cursor number of the sorting index */\n  int sortingIdxPTab;     /* Cursor number of pseudo-table */\n  int nSortingColumn;     /* Number of columns in the sorting index */\n  ExprList *pGroupBy;     /* The group by clause */\n  struct AggInfo_col {    /* For each column used in source tables */\n    Table *pTab;             /* Source table */\n    int iTable;              /* Cursor number of the source table */\n    int iColumn;             /* Column number within the source table */\n    int iSorterColumn;       /* Column number in the sorting index */\n    int iMem;                /* Memory location that acts as accumulator */\n    Expr *pExpr;             /* The original expression */\n  } *aCol;\n  int nColumn;            /* Number of used entries in aCol[] */\n  int nAccumulator;       /* Number of columns that show through to the output.\n                          ** Additional columns are used only as parameters to\n                          ** aggregate functions */\n  struct AggInfo_func {   /* For each aggregate function */\n    Expr *pExpr;             /* Expression encoding the function */\n    FuncDef *pFunc;          /* The aggregate function implementation */\n    int iMem;                /* Memory location that acts as accumulator */\n    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */\n  } *aFunc;\n  int nFunc;              /* Number of entries in aFunc[] */\n};\n\n/*\n** The datatype ynVar is a signed integer, either 16-bit or 32-bit.\n** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater\n** than 32767 we have to make it 32-bit.  16-bit is preferred because\n** it uses less memory in the Expr object, which is a big memory user\n** in systems with lots of prepared statements.  And few applications\n** need more than about 10 or 20 variables.  But some extreme users want\n** to have prepared statements with over 32767 variables, and for them\n** the option is available (at compile-time).\n*/\n#if SQLITE_MAX_VARIABLE_NUMBER<=32767\ntypedef i16 ynVar;\n#else\ntypedef int ynVar;\n#endif\n\n/*\n** Each node of an expression in the parse tree is an instance\n** of this structure.\n**\n** Expr.op is the opcode. The integer parser token codes are reused\n** as opcodes here. For example, the parser defines TK_GE to be an integer\n** code representing the \">=\" operator. This same integer code is reused\n** to represent the greater-than-or-equal-to operator in the expression\n** tree.\n**\n** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, \n** or TK_STRING), then Expr.token contains the text of the SQL literal. If\n** the expression is a variable (TK_VARIABLE), then Expr.token contains the \n** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),\n** then Expr.token contains the name of the function.\n**\n** Expr.pRight and Expr.pLeft are the left and right subexpressions of a\n** binary operator. Either or both may be NULL.\n**\n** Expr.x.pList is a list of arguments if the expression is an SQL function,\n** a CASE expression or an IN expression of the form \"<lhs> IN (<y>, <z>...)\".\n** Expr.x.pSelect is used if the expression is a sub-select or an expression of\n** the form \"<lhs> IN (SELECT ...)\". If the EP_xIsSelect bit is set in the\n** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is \n** valid.\n**\n** An expression of the form ID or ID.ID refers to a column in a table.\n** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is\n** the integer cursor number of a VDBE cursor pointing to that table and\n** Expr.iColumn is the column number for the specific column.  If the\n** expression is used as a result in an aggregate SELECT, then the\n** value is also stored in the Expr.iAgg column in the aggregate so that\n** it can be accessed after all aggregates are computed.\n**\n** If the expression is an unbound variable marker (a question mark \n** character '?' in the original SQL) then the Expr.iTable holds the index \n** number for that variable.\n**\n** If the expression is a subquery then Expr.iColumn holds an integer\n** register number containing the result of the subquery.  If the\n** subquery gives a constant result, then iTable is -1.  If the subquery\n** gives a different answer at different times during statement processing\n** then iTable is the address of a subroutine that computes the subquery.\n**\n** If the Expr is of type OP_Column, and the table it is selecting from\n** is a disk table or the \"old.*\" pseudo-table, then pTab points to the\n** corresponding table definition.\n**\n** ALLOCATION NOTES:\n**\n** Expr objects can use a lot of memory space in database schema.  To\n** help reduce memory requirements, sometimes an Expr object will be\n** truncated.  And to reduce the number of memory allocations, sometimes\n** two or more Expr objects will be stored in a single memory allocation,\n** together with Expr.zToken strings.\n**\n** If the EP_Reduced and EP_TokenOnly flags are set when\n** an Expr object is truncated.  When EP_Reduced is set, then all\n** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees\n** are contained within the same memory allocation.  Note, however, that\n** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately\n** allocated, regardless of whether or not EP_Reduced is set.\n*/\nstruct Expr {\n  u8 op;                 /* Operation performed by this node */\n  char affinity;         /* The affinity of the column or 0 if not a column */\n  u16 flags;             /* Various flags.  EP_* See below */\n  union {\n    char *zToken;          /* Token value. Zero terminated and dequoted */\n    int iValue;            /* Non-negative integer value if EP_IntValue */\n  } u;\n\n  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no\n  ** space is allocated for the fields below this point. An attempt to\n  ** access them will result in a segfault or malfunction. \n  *********************************************************************/\n\n  Expr *pLeft;           /* Left subnode */\n  Expr *pRight;          /* Right subnode */\n  union {\n    ExprList *pList;     /* Function arguments or in \"<expr> IN (<expr-list)\" */\n    Select *pSelect;     /* Used for sub-selects and \"<expr> IN (<select>)\" */\n  } x;\n  CollSeq *pColl;        /* The collation type of the column or 0 */\n\n  /* If the EP_Reduced flag is set in the Expr.flags mask, then no\n  ** space is allocated for the fields below this point. An attempt to\n  ** access them will result in a segfault or malfunction.\n  *********************************************************************/\n\n  int iTable;            /* TK_COLUMN: cursor number of table holding column\n                         ** TK_REGISTER: register number\n                         ** TK_TRIGGER: 1 -> new, 0 -> old */\n  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.\n                         ** TK_VARIABLE: variable number (always >= 1). */\n  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */\n  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */\n  u8 flags2;             /* Second set of flags.  EP2_... */\n  u8 op2;                /* TK_REGISTER: original value of Expr.op\n                         ** TK_COLUMN: the value of p5 for OP_Column\n                         ** TK_AGG_FUNCTION: nesting depth */\n  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */\n  Table *pTab;           /* Table for TK_COLUMN expressions. */\n#if SQLITE_MAX_EXPR_DEPTH>0\n  int nHeight;           /* Height of the tree headed by this node */\n#endif\n};\n\n/*\n** The following are the meanings of bits in the Expr.flags field.\n*/\n#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */\n#define EP_Agg        0x0002  /* Contains one or more aggregate functions */\n#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */\n#define EP_Error      0x0008  /* Expression contains one or more errors */\n#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */\n#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */\n#define EP_DblQuoted  0x0040  /* token.z was originally in \"...\" */\n#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */\n#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */\n#define EP_FixedDest  0x0200  /* Result needed in a specific register */\n#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */\n#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */\n#define EP_Hint       0x1000  /* Not used */\n#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */\n#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */\n#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */\n\n/*\n** The following are the meanings of bits in the Expr.flags2 field.\n*/\n#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */\n#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */\n\n/*\n** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible\n** flag on an expression structure.  This flag is used for VV&A only.  The\n** routine is implemented as a macro that only works when in debugging mode,\n** so as not to burden production code.\n*/\n#ifdef SQLITE_DEBUG\n# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible\n#else\n# define ExprSetIrreducible(X)\n#endif\n\n/*\n** These macros can be used to test, set, or clear bits in the \n** Expr.flags field.\n*/\n#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))\n#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)\n#define ExprSetProperty(E,P)     (E)->flags|=(P)\n#define ExprClearProperty(E,P)   (E)->flags&=~(P)\n\n/*\n** Macros to determine the number of bytes required by a normal Expr \n** struct, an Expr struct with the EP_Reduced flag set in Expr.flags \n** and an Expr struct with the EP_TokenOnly flag set.\n*/\n#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */\n#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */\n#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */\n\n/*\n** Flags passed to the sqlite3ExprDup() function. See the header comment \n** above sqlite3ExprDup() for details.\n*/\n#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */\n\n/*\n** A list of expressions.  Each expression may optionally have a\n** name.  An expr/name combination can be used in several ways, such\n** as the list of \"expr AS ID\" fields following a \"SELECT\" or in the\n** list of \"ID = expr\" items in an UPDATE.  A list of expressions can\n** also be used as the argument to a function, in which case the a.zName\n** field is not used.\n*/\nstruct ExprList {\n  int nExpr;             /* Number of expressions on the list */\n  int iECursor;          /* VDBE Cursor associated with this ExprList */\n  struct ExprList_item { /* For each expression in the list */\n    Expr *pExpr;           /* The list of expressions */\n    char *zName;           /* Token associated with this expression */\n    char *zSpan;           /* Original text of the expression */\n    u8 sortOrder;          /* 1 for DESC or 0 for ASC */\n    u8 done;               /* A flag to indicate when processing is finished */\n    u16 iOrderByCol;       /* For ORDER BY, column number in result set */\n    u16 iAlias;            /* Index into Parse.aAlias[] for zName */\n  } *a;                  /* Alloc a power of two greater or equal to nExpr */\n};\n\n/*\n** An instance of this structure is used by the parser to record both\n** the parse tree for an expression and the span of input text for an\n** expression.\n*/\nstruct ExprSpan {\n  Expr *pExpr;          /* The expression parse tree */\n  const char *zStart;   /* First character of input text */\n  const char *zEnd;     /* One character past the end of input text */\n};\n\n/*\n** An instance of this structure can hold a simple list of identifiers,\n** such as the list \"a,b,c\" in the following statements:\n**\n**      INSERT INTO t(a,b,c) VALUES ...;\n**      CREATE INDEX idx ON t(a,b,c);\n**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;\n**\n** The IdList.a.idx field is used when the IdList represents the list of\n** column names after a table name in an INSERT statement.  In the statement\n**\n**     INSERT INTO t(a,b,c) ...\n**\n** If \"a\" is the k-th column of table \"t\", then IdList.a[0].idx==k.\n*/\nstruct IdList {\n  struct IdList_item {\n    char *zName;      /* Name of the identifier */\n    int idx;          /* Index in some Table.aCol[] of a column named zName */\n  } *a;\n  int nId;         /* Number of identifiers on the list */\n};\n\n/*\n** The bitmask datatype defined below is used for various optimizations.\n**\n** Changing this from a 64-bit to a 32-bit type limits the number of\n** tables in a join to 32 instead of 64.  But it also reduces the size\n** of the library by 738 bytes on ix86.\n*/\ntypedef u64 Bitmask;\n\n/*\n** The number of bits in a Bitmask.  \"BMS\" means \"BitMask Size\".\n*/\n#define BMS  ((int)(sizeof(Bitmask)*8))\n\n/*\n** The following structure describes the FROM clause of a SELECT statement.\n** Each table or subquery in the FROM clause is a separate element of\n** the SrcList.a[] array.\n**\n** With the addition of multiple database support, the following structure\n** can also be used to describe a particular table such as the table that\n** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,\n** such a table must be a simple name: ID.  But in SQLite, the table can\n** now be identified by a database name, a dot, then the table name: ID.ID.\n**\n** The jointype starts out showing the join type between the current table\n** and the next table on the list.  The parser builds the list this way.\n** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each\n** jointype expresses the join between the table and the previous table.\n**\n** In the colUsed field, the high-order bit (bit 63) is set if the table\n** contains more than 63 columns and the 64-th or later column is used.\n*/\nstruct SrcList {\n  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */\n  i16 nAlloc;      /* Number of entries allocated in a[] below */\n  struct SrcList_item {\n    char *zDatabase;  /* Name of database holding this table */\n    char *zName;      /* Name of the table */\n    char *zAlias;     /* The \"B\" part of a \"A AS B\" phrase.  zName is the \"A\" */\n    Table *pTab;      /* An SQL table corresponding to zName */\n    Select *pSelect;  /* A SELECT statement used in place of a table name */\n    int addrFillSub;  /* Address of subroutine to manifest a subquery */\n    int regReturn;    /* Register holding return address of addrFillSub */\n    u8 jointype;      /* Type of join between this able and the previous */\n    u8 notIndexed;    /* True if there is a NOT INDEXED clause */\n    u8 isCorrelated;  /* True if sub-query is correlated */\n#ifndef SQLITE_OMIT_EXPLAIN\n    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */\n#endif\n    int iCursor;      /* The VDBE cursor number used to access this table */\n    Expr *pOn;        /* The ON clause of a join */\n    IdList *pUsing;   /* The USING clause of a join */\n    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */\n    char *zIndex;     /* Identifier from \"INDEXED BY <zIndex>\" clause */\n    Index *pIndex;    /* Index structure corresponding to zIndex, if any */\n  } a[1];             /* One entry for each identifier on the list */\n};\n\n/*\n** Permitted values of the SrcList.a.jointype field\n*/\n#define JT_INNER     0x0001    /* Any kind of inner or cross join */\n#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */\n#define JT_NATURAL   0x0004    /* True for a \"natural\" join */\n#define JT_LEFT      0x0008    /* Left outer join */\n#define JT_RIGHT     0x0010    /* Right outer join */\n#define JT_OUTER     0x0020    /* The \"OUTER\" keyword is present */\n#define JT_ERROR     0x0040    /* unknown or unsupported join type */\n\n\n/*\n** A WherePlan object holds information that describes a lookup\n** strategy.\n**\n** This object is intended to be opaque outside of the where.c module.\n** It is included here only so that that compiler will know how big it\n** is.  None of the fields in this object should be used outside of\n** the where.c module.\n**\n** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.\n** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx\n** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the\n** case that more than one of these conditions is true.\n*/\nstruct WherePlan {\n  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */\n  u32 nEq;                       /* Number of == constraints */\n  double nRow;                   /* Estimated number of rows (for EQP) */\n  union {\n    Index *pIdx;                   /* Index when WHERE_INDEXED is true */\n    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */\n    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */\n  } u;\n};\n\n/*\n** For each nested loop in a WHERE clause implementation, the WhereInfo\n** structure contains a single instance of this structure.  This structure\n** is intended to be private to the where.c module and should not be\n** access or modified by other modules.\n**\n** The pIdxInfo field is used to help pick the best index on a\n** virtual table.  The pIdxInfo pointer contains indexing\n** information for the i-th table in the FROM clause before reordering.\n** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.\n** All other information in the i-th WhereLevel object for the i-th table\n** after FROM clause ordering.\n*/\nstruct WhereLevel {\n  WherePlan plan;       /* query plan for this element of the FROM clause */\n  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */\n  int iTabCur;          /* The VDBE cursor used to access the table */\n  int iIdxCur;          /* The VDBE cursor used to access pIdx */\n  int addrBrk;          /* Jump here to break out of the loop */\n  int addrNxt;          /* Jump here to start the next IN combination */\n  int addrCont;         /* Jump here to continue with the next loop cycle */\n  int addrFirst;        /* First instruction of interior of the loop */\n  u8 iFrom;             /* Which entry in the FROM clause */\n  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */\n  int p1, p2;           /* Operands of the opcode used to ends the loop */\n  union {               /* Information that depends on plan.wsFlags */\n    struct {\n      int nIn;              /* Number of entries in aInLoop[] */\n      struct InLoop {\n        int iCur;              /* The VDBE cursor used by this IN operator */\n        int addrInTop;         /* Top of the IN loop */\n      } *aInLoop;           /* Information about each nested IN operator */\n    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */\n    Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */\n  } u;\n\n  /* The following field is really not part of the current level.  But\n  ** we need a place to cache virtual table index information for each\n  ** virtual table in the FROM clause and the WhereLevel structure is\n  ** a convenient place since there is one WhereLevel for each FROM clause\n  ** element.\n  */\n  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */\n};\n\n/*\n** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()\n** and the WhereInfo.wctrlFlags member.\n*/\n#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */\n#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */\n#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */\n#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */\n#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */\n#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */\n#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */\n#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */\n#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */\n\n/*\n** The WHERE clause processing routine has two halves.  The\n** first part does the start of the WHERE loop and the second\n** half does the tail of the WHERE loop.  An instance of\n** this structure is returned by the first half and passed\n** into the second half to give some continuity.\n*/\nstruct WhereInfo {\n  Parse *pParse;       /* Parsing and code generating context */\n  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */\n  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */\n  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */\n  u8 eDistinct;\n  SrcList *pTabList;             /* List of tables in the join */\n  int iTop;                      /* The very beginning of the WHERE loop */\n  int iContinue;                 /* Jump here to continue with next record */\n  int iBreak;                    /* Jump here to break out of the loop */\n  int nLevel;                    /* Number of nested loop */\n  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */\n  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */\n  double nRowOut;                /* Estimated number of output rows */\n  WhereLevel a[1];               /* Information about each nest loop in WHERE */\n};\n\n#define WHERE_DISTINCT_UNIQUE 1\n#define WHERE_DISTINCT_ORDERED 2\n\n/*\n** A NameContext defines a context in which to resolve table and column\n** names.  The context consists of a list of tables (the pSrcList) field and\n** a list of named expression (pEList).  The named expression list may\n** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or\n** to the table being operated on by INSERT, UPDATE, or DELETE.  The\n** pEList corresponds to the result set of a SELECT and is NULL for\n** other statements.\n**\n** NameContexts can be nested.  When resolving names, the inner-most \n** context is searched first.  If no match is found, the next outer\n** context is checked.  If there is still no match, the next context\n** is checked.  This process continues until either a match is found\n** or all contexts are check.  When a match is found, the nRef member of\n** the context containing the match is incremented. \n**\n** Each subquery gets a new NameContext.  The pNext field points to the\n** NameContext in the parent query.  Thus the process of scanning the\n** NameContext list corresponds to searching through successively outer\n** subqueries looking for a match.\n*/\nstruct NameContext {\n  Parse *pParse;       /* The parser */\n  SrcList *pSrcList;   /* One or more tables used to resolve names */\n  ExprList *pEList;    /* Optional list of named expressions */\n  AggInfo *pAggInfo;   /* Information about aggregates at this level */\n  NameContext *pNext;  /* Next outer name context.  NULL for outermost */\n  int nRef;            /* Number of names resolved by this context */\n  int nErr;            /* Number of errors encountered while resolving names */\n  u8 ncFlags;          /* Zero or more NC_* flags defined below */\n};\n\n/*\n** Allowed values for the NameContext, ncFlags field.\n*/\n#define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */\n#define NC_HasAgg    0x02    /* One or more aggregate functions seen */\n#define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */\n#define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */\n\n/*\n** An instance of the following structure contains all information\n** needed to generate code for a single SELECT statement.\n**\n** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.\n** If there is a LIMIT clause, the parser sets nLimit to the value of the\n** limit and nOffset to the value of the offset (or 0 if there is not\n** offset).  But later on, nLimit and nOffset become the memory locations\n** in the VDBE that record the limit and offset counters.\n**\n** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.\n** These addresses must be stored so that we can go back and fill in\n** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor\n** the number of columns in P2 can be computed at the same time\n** as the OP_OpenEphm instruction is coded because not\n** enough information about the compound query is known at that point.\n** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences\n** for the result set.  The KeyInfo for addrOpenTran[2] contains collating\n** sequences for the ORDER BY clause.\n*/\nstruct Select {\n  ExprList *pEList;      /* The fields of the result */\n  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */\n  char affinity;         /* MakeRecord with this affinity for SRT_Set */\n  u16 selFlags;          /* Various SF_* values */\n  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */\n  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */\n  double nSelectRow;     /* Estimated number of result rows */\n  SrcList *pSrc;         /* The FROM clause */\n  Expr *pWhere;          /* The WHERE clause */\n  ExprList *pGroupBy;    /* The GROUP BY clause */\n  Expr *pHaving;         /* The HAVING clause */\n  ExprList *pOrderBy;    /* The ORDER BY clause */\n  Select *pPrior;        /* Prior select in a compound select statement */\n  Select *pNext;         /* Next select to the left in a compound */\n  Select *pRightmost;    /* Right-most select in a compound select statement */\n  Expr *pLimit;          /* LIMIT expression. NULL means not used. */\n  Expr *pOffset;         /* OFFSET expression. NULL means not used. */\n};\n\n/*\n** Allowed values for Select.selFlags.  The \"SF\" prefix stands for\n** \"Select Flag\".\n*/\n#define SF_Distinct        0x01  /* Output should be DISTINCT */\n#define SF_Resolved        0x02  /* Identifiers have been resolved */\n#define SF_Aggregate       0x04  /* Contains aggregate functions */\n#define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */\n#define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */\n#define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */\n#define SF_UseSorter       0x40  /* Sort using a sorter */\n#define SF_Values          0x80  /* Synthesized from VALUES clause */\n\n\n/*\n** The results of a select can be distributed in several ways.  The\n** \"SRT\" prefix means \"SELECT Result Type\".\n*/\n#define SRT_Union        1  /* Store result as keys in an index */\n#define SRT_Except       2  /* Remove result from a UNION index */\n#define SRT_Exists       3  /* Store 1 if the result is not empty */\n#define SRT_Discard      4  /* Do not save the results anywhere */\n\n/* The ORDER BY clause is ignored for all of the above */\n#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)\n\n#define SRT_Output       5  /* Output each row of result */\n#define SRT_Mem          6  /* Store result in a memory cell */\n#define SRT_Set          7  /* Store results as keys in an index */\n#define SRT_Table        8  /* Store result as data with an automatic rowid */\n#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */\n#define SRT_Coroutine   10  /* Generate a single row of result */\n\n/*\n** A structure used to customize the behavior of sqlite3Select(). See\n** comments above sqlite3Select() for details.\n*/\ntypedef struct SelectDest SelectDest;\nstruct SelectDest {\n  u8 eDest;         /* How to dispose of the results */\n  u8 affSdst;       /* Affinity used when eDest==SRT_Set */\n  int iSDParm;      /* A parameter used by the eDest disposal method */\n  int iSdst;        /* Base register where results are written */\n  int nSdst;        /* Number of registers allocated */\n};\n\n/*\n** During code generation of statements that do inserts into AUTOINCREMENT \n** tables, the following information is attached to the Table.u.autoInc.p\n** pointer of each autoincrement table to record some side information that\n** the code generator needs.  We have to keep per-table autoincrement\n** information in case inserts are down within triggers.  Triggers do not\n** normally coordinate their activities, but we do need to coordinate the\n** loading and saving of autoincrement information.\n*/\nstruct AutoincInfo {\n  AutoincInfo *pNext;   /* Next info block in a list of them all */\n  Table *pTab;          /* Table this info block refers to */\n  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */\n  int regCtr;           /* Memory register holding the rowid counter */\n};\n\n/*\n** Size of the column cache\n*/\n#ifndef SQLITE_N_COLCACHE\n# define SQLITE_N_COLCACHE 10\n#endif\n\n/*\n** At least one instance of the following structure is created for each \n** trigger that may be fired while parsing an INSERT, UPDATE or DELETE\n** statement. All such objects are stored in the linked list headed at\n** Parse.pTriggerPrg and deleted once statement compilation has been\n** completed.\n**\n** A Vdbe sub-program that implements the body and WHEN clause of trigger\n** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of\n** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.\n** The Parse.pTriggerPrg list never contains two entries with the same\n** values for both pTrigger and orconf.\n**\n** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns\n** accessed (or set to 0 for triggers fired as a result of INSERT \n** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to\n** a mask of new.* columns used by the program.\n*/\nstruct TriggerPrg {\n  Trigger *pTrigger;      /* Trigger this program was coded from */\n  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */\n  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */\n  int orconf;             /* Default ON CONFLICT policy */\n  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */\n};\n\n/*\n** The yDbMask datatype for the bitmask of all attached databases.\n*/\n#if SQLITE_MAX_ATTACHED>30\n  typedef sqlite3_uint64 yDbMask;\n#else\n  typedef unsigned int yDbMask;\n#endif\n\n/*\n** An SQL parser context.  A copy of this structure is passed through\n** the parser and down into all the parser action routine in order to\n** carry around information that is global to the entire parse.\n**\n** The structure is divided into two parts.  When the parser and code\n** generate call themselves recursively, the first part of the structure\n** is constant but the second part is reset at the beginning and end of\n** each recursion.\n**\n** The nTableLock and aTableLock variables are only used if the shared-cache \n** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are\n** used to store the set of table-locks required by the statement being\n** compiled. Function sqlite3TableLock() is used to add entries to the\n** list.\n*/\nstruct Parse {\n  sqlite3 *db;         /* The main database structure */\n  char *zErrMsg;       /* An error message */\n  Vdbe *pVdbe;         /* An engine for executing database bytecode */\n  int rc;              /* Return code from execution */\n  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */\n  u8 checkSchema;      /* Causes schema cookie check after an error */\n  u8 nested;           /* Number of nested calls to the parser/code generator */\n  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */\n  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */\n  u8 nColCache;        /* Number of entries in aColCache[] */\n  u8 iColCache;        /* Next entry in aColCache[] to replace */\n  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */\n  u8 mayAbort;         /* True if statement may throw an ABORT exception */\n  int aTempReg[8];     /* Holding area for temporary registers */\n  int nRangeReg;       /* Size of the temporary register block */\n  int iRangeReg;       /* First register in temporary register block */\n  int nErr;            /* Number of errors seen */\n  int nTab;            /* Number of previously allocated VDBE cursors */\n  int nMem;            /* Number of memory cells used so far */\n  int nSet;            /* Number of sets used so far */\n  int nOnce;           /* Number of OP_Once instructions so far */\n  int ckBase;          /* Base register of data during check constraints */\n  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */\n  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */\n  struct yColCache {\n    int iTable;           /* Table cursor number */\n    int iColumn;          /* Table column number */\n    u8 tempReg;           /* iReg is a temp register that needs to be freed */\n    int iLevel;           /* Nesting level */\n    int iReg;             /* Reg with value of this column. 0 means none. */\n    int lru;              /* Least recently used entry has the smallest value */\n  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */\n  yDbMask writeMask;   /* Start a write transaction on these databases */\n  yDbMask cookieMask;  /* Bitmask of schema verified databases */\n  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */\n  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */\n  int regRowid;        /* Register holding rowid of CREATE TABLE entry */\n  int regRoot;         /* Register holding root page number for new objects */\n  int nMaxArg;         /* Max args passed to user function by sub-program */\n  Token constraintName;/* Name of the constraint currently being parsed */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  int nTableLock;        /* Number of locks in aTableLock */\n  TableLock *aTableLock; /* Required table locks for shared-cache mode */\n#endif\n  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */\n\n  /* Information used while coding trigger programs. */\n  Parse *pToplevel;    /* Parse structure for main program (or NULL) */\n  Table *pTriggerTab;  /* Table triggers are being coded for */\n  double nQueryLoop;   /* Estimated number of iterations of a query */\n  u32 oldmask;         /* Mask of old.* columns referenced */\n  u32 newmask;         /* Mask of new.* columns referenced */\n  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */\n  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */\n  u8 disableTriggers;  /* True to disable triggers */\n\n  /* Above is constant between recursions.  Below is reset before and after\n  ** each recursion */\n\n  int nVar;                 /* Number of '?' variables seen in the SQL so far */\n  int nzVar;                /* Number of available slots in azVar[] */\n  u8 explain;               /* True if the EXPLAIN flag is found on the query */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */\n  int nVtabLock;            /* Number of virtual tables to lock */\n#endif\n  int nAlias;               /* Number of aliased result set columns */\n  int nHeight;              /* Expression tree height of current sub-select */\n#ifndef SQLITE_OMIT_EXPLAIN\n  int iSelectId;            /* ID of current select for EXPLAIN output */\n  int iNextSelectId;        /* Next available select ID for EXPLAIN output */\n#endif\n  char **azVar;             /* Pointers to names of parameters */\n  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */\n  int *aAlias;              /* Register used to hold aliased result */\n  const char *zTail;        /* All SQL text past the last semicolon parsed */\n  Table *pNewTable;         /* A table being constructed by CREATE TABLE */\n  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */\n  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */\n  Token sNameToken;         /* Token with unqualified schema object name */\n  Token sLastToken;         /* The last token parsed */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  Token sArg;               /* Complete text of a module argument */\n  Table **apVtabLock;       /* Pointer to virtual tables needing locking */\n#endif\n  Table *pZombieTab;        /* List of Table objects to delete after code gen */\n  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */\n};\n\n/*\n** Return true if currently inside an sqlite3_declare_vtab() call.\n*/\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n  #define IN_DECLARE_VTAB 0\n#else\n  #define IN_DECLARE_VTAB (pParse->declareVtab)\n#endif\n\n/*\n** An instance of the following structure can be declared on a stack and used\n** to save the Parse.zAuthContext value so that it can be restored later.\n*/\nstruct AuthContext {\n  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */\n  Parse *pParse;              /* The Parse structure */\n};\n\n/*\n** Bitfield flags for P5 value in various opcodes.\n*/\n#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */\n#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */\n#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */\n#define OPFLAG_APPEND        0x08    /* This is likely to be an append */\n#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */\n#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */\n#define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */\n#define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */\n#define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */\n#define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */\n\n/*\n * Each trigger present in the database schema is stored as an instance of\n * struct Trigger. \n *\n * Pointers to instances of struct Trigger are stored in two ways.\n * 1. In the \"trigHash\" hash table (part of the sqlite3* that represents the \n *    database). This allows Trigger structures to be retrieved by name.\n * 2. All triggers associated with a single table form a linked list, using the\n *    pNext member of struct Trigger. A pointer to the first element of the\n *    linked list is stored as the \"pTrigger\" member of the associated\n *    struct Table.\n *\n * The \"step_list\" member points to the first element of a linked list\n * containing the SQL statements specified as the trigger program.\n */\nstruct Trigger {\n  char *zName;            /* The name of the trigger                        */\n  char *table;            /* The table or view to which the trigger applies */\n  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */\n  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */\n  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */\n  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,\n                             the <column-list> is stored here */\n  Schema *pSchema;        /* Schema containing the trigger */\n  Schema *pTabSchema;     /* Schema containing the table */\n  TriggerStep *step_list; /* Link list of trigger program steps             */\n  Trigger *pNext;         /* Next trigger associated with the table */\n};\n\n/*\n** A trigger is either a BEFORE or an AFTER trigger.  The following constants\n** determine which. \n**\n** If there are multiple triggers, you might of some BEFORE and some AFTER.\n** In that cases, the constants below can be ORed together.\n*/\n#define TRIGGER_BEFORE  1\n#define TRIGGER_AFTER   2\n\n/*\n * An instance of struct TriggerStep is used to store a single SQL statement\n * that is a part of a trigger-program. \n *\n * Instances of struct TriggerStep are stored in a singly linked list (linked\n * using the \"pNext\" member) referenced by the \"step_list\" member of the \n * associated struct Trigger instance. The first element of the linked list is\n * the first step of the trigger-program.\n * \n * The \"op\" member indicates whether this is a \"DELETE\", \"INSERT\", \"UPDATE\" or\n * \"SELECT\" statement. The meanings of the other members is determined by the \n * value of \"op\" as follows:\n *\n * (op == TK_INSERT)\n * orconf    -> stores the ON CONFLICT algorithm\n * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then\n *              this stores a pointer to the SELECT statement. Otherwise NULL.\n * target    -> A token holding the quoted name of the table to insert into.\n * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then\n *              this stores values to be inserted. Otherwise NULL.\n * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... \n *              statement, then this stores the column-names to be\n *              inserted into.\n *\n * (op == TK_DELETE)\n * target    -> A token holding the quoted name of the table to delete from.\n * pWhere    -> The WHERE clause of the DELETE statement if one is specified.\n *              Otherwise NULL.\n * \n * (op == TK_UPDATE)\n * target    -> A token holding the quoted name of the table to update rows of.\n * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.\n *              Otherwise NULL.\n * pExprList -> A list of the columns to update and the expressions to update\n *              them to. See sqlite3Update() documentation of \"pChanges\"\n *              argument.\n * \n */\nstruct TriggerStep {\n  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */\n  u8 orconf;           /* OE_Rollback etc. */\n  Trigger *pTrig;      /* The trigger that this step is a part of */\n  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */\n  Token target;        /* Target table for DELETE, UPDATE, INSERT */\n  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */\n  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */\n  IdList *pIdList;     /* Column names for INSERT */\n  TriggerStep *pNext;  /* Next in the link-list */\n  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */\n};\n\n/*\n** The following structure contains information used by the sqliteFix...\n** routines as they walk the parse tree to make database references\n** explicit.  \n*/\ntypedef struct DbFixer DbFixer;\nstruct DbFixer {\n  Parse *pParse;      /* The parsing context.  Error messages written here */\n  const char *zDb;    /* Make sure all objects are contained in this database */\n  const char *zType;  /* Type of the container - used for error messages */\n  const Token *pName; /* Name of the container - used for error messages */\n};\n\n/*\n** An objected used to accumulate the text of a string where we\n** do not necessarily know how big the string will be in the end.\n*/\nstruct StrAccum {\n  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */\n  char *zBase;         /* A base allocation.  Not from malloc. */\n  char *zText;         /* The string collected so far */\n  int  nChar;          /* Length of the string so far */\n  int  nAlloc;         /* Amount of space allocated in zText */\n  int  mxAlloc;        /* Maximum allowed string length */\n  u8   mallocFailed;   /* Becomes true if any memory allocation fails */\n  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */\n  u8   tooBig;         /* Becomes true if string size exceeds limits */\n};\n\n/*\n** A pointer to this structure is used to communicate information\n** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.\n*/\ntypedef struct {\n  sqlite3 *db;        /* The database being initialized */\n  char **pzErrMsg;    /* Error message stored here */\n  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */\n  int rc;             /* Result code stored here */\n} InitData;\n\n/*\n** Structure containing global configuration data for the SQLite library.\n**\n** This structure also contains some state information.\n*/\nstruct Sqlite3Config {\n  int bMemstat;                     /* True to enable memory status */\n  int bCoreMutex;                   /* True to enable core mutexing */\n  int bFullMutex;                   /* True to enable full mutexing */\n  int bOpenUri;                     /* True to interpret filenames as URIs */\n  int mxStrlen;                     /* Maximum string length */\n  int szLookaside;                  /* Default lookaside buffer size */\n  int nLookaside;                   /* Default lookaside buffer count */\n  sqlite3_mem_methods m;            /* Low-level memory allocation interface */\n  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */\n  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */\n  void *pHeap;                      /* Heap storage space */\n  int nHeap;                        /* Size of pHeap[] */\n  int mnReq, mxReq;                 /* Min and max heap requests sizes */\n  void *pScratch;                   /* Scratch memory */\n  int szScratch;                    /* Size of each scratch buffer */\n  int nScratch;                     /* Number of scratch buffers */\n  void *pPage;                      /* Page cache memory */\n  int szPage;                       /* Size of each page in pPage[] */\n  int nPage;                        /* Number of pages in pPage[] */\n  int mxParserStack;                /* maximum depth of the parser stack */\n  int sharedCacheEnabled;           /* true if shared-cache mode enabled */\n  /* The above might be initialized to non-zero.  The following need to always\n  ** initially be zero, however. */\n  int isInit;                       /* True after initialization has finished */\n  int inProgress;                   /* True while initialization in progress */\n  int isMutexInit;                  /* True after mutexes are initialized */\n  int isMallocInit;                 /* True after malloc is initialized */\n  int isPCacheInit;                 /* True after malloc is initialized */\n  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */\n  int nRefInitMutex;                /* Number of users of pInitMutex */\n  void (*xLog)(void*,int,const char*); /* Function for logging */\n  void *pLogArg;                       /* First argument to xLog() */\n  int bLocaltimeFault;              /* True to fail localtime() calls */\n};\n\n/*\n** Context pointer passed down through the tree-walk.\n*/\nstruct Walker {\n  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */\n  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */\n  Parse *pParse;                            /* Parser context.  */\n  int walkerDepth;                          /* Number of subqueries */\n  union {                                   /* Extra data for callback */\n    NameContext *pNC;                          /* Naming context */\n    int i;                                     /* Integer value */\n    SrcList *pSrcList;                         /* FROM clause */\n    struct SrcCount *pSrcCount;                /* Counting column references */\n  } u;\n};\n\n/* Forward declarations */\nSQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);\nSQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);\nSQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);\nSQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);\n\n/*\n** Return code from the parse-tree walking primitives and their\n** callbacks.\n*/\n#define WRC_Continue    0   /* Continue down into children */\n#define WRC_Prune       1   /* Omit children but continue walking siblings */\n#define WRC_Abort       2   /* Abandon the tree walk */\n\n/*\n** Assuming zIn points to the first byte of a UTF-8 character,\n** advance zIn to point to the first byte of the next UTF-8 character.\n*/\n#define SQLITE_SKIP_UTF8(zIn) {                        \\\n  if( (*(zIn++))>=0xc0 ){                              \\\n    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \\\n  }                                                    \\\n}\n\n/*\n** The SQLITE_*_BKPT macros are substitutes for the error codes with\n** the same name but without the _BKPT suffix.  These macros invoke\n** routines that report the line-number on which the error originated\n** using sqlite3_log().  The routines also provide a convenient place\n** to set a debugger breakpoint.\n*/\nSQLITE_PRIVATE int sqlite3CorruptError(int);\nSQLITE_PRIVATE int sqlite3MisuseError(int);\nSQLITE_PRIVATE int sqlite3CantopenError(int);\n#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)\n#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)\n#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)\n\n\n/*\n** FTS4 is really an extension for FTS3.  It is enabled using the\n** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all\n** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.\n*/\n#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)\n# define SQLITE_ENABLE_FTS3\n#endif\n\n/*\n** The ctype.h header is needed for non-ASCII systems.  It is also\n** needed by FTS3 when FTS3 is included in the amalgamation.\n*/\n#if !defined(SQLITE_ASCII) || \\\n    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))\n# include <ctype.h>\n#endif\n\n/*\n** The following macros mimic the standard library functions toupper(),\n** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The\n** sqlite versions only work for ASCII characters, regardless of locale.\n*/\n#ifdef SQLITE_ASCII\n# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))\n# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)\n# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)\n# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)\n# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)\n# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)\n# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])\n#else\n# define sqlite3Toupper(x)   toupper((unsigned char)(x))\n# define sqlite3Isspace(x)   isspace((unsigned char)(x))\n# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))\n# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))\n# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))\n# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))\n# define sqlite3Tolower(x)   tolower((unsigned char)(x))\n#endif\n\n/*\n** Internal function prototypes\n*/\n#define sqlite3StrICmp sqlite3_stricmp\nSQLITE_PRIVATE int sqlite3Strlen30(const char*);\n#define sqlite3StrNICmp sqlite3_strnicmp\n\nSQLITE_PRIVATE int sqlite3MallocInit(void);\nSQLITE_PRIVATE void sqlite3MallocEnd(void);\nSQLITE_PRIVATE void *sqlite3Malloc(int);\nSQLITE_PRIVATE void *sqlite3MallocZero(int);\nSQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);\nSQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);\nSQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);\nSQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);\nSQLITE_PRIVATE void *sqlite3Realloc(void*, int);\nSQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);\nSQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);\nSQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);\nSQLITE_PRIVATE int sqlite3MallocSize(void*);\nSQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);\nSQLITE_PRIVATE void *sqlite3ScratchMalloc(int);\nSQLITE_PRIVATE void sqlite3ScratchFree(void*);\nSQLITE_PRIVATE void *sqlite3PageMalloc(int);\nSQLITE_PRIVATE void sqlite3PageFree(void*);\nSQLITE_PRIVATE void sqlite3MemSetDefault(void);\nSQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));\nSQLITE_PRIVATE int sqlite3HeapNearlyFull(void);\n\n/*\n** On systems with ample stack space and that support alloca(), make\n** use of alloca() to obtain space for large automatic objects.  By default,\n** obtain space from malloc().\n**\n** The alloca() routine never returns NULL.  This will cause code paths\n** that deal with sqlite3StackAlloc() failures to be unreachable.\n*/\n#ifdef SQLITE_USE_ALLOCA\n# define sqlite3StackAllocRaw(D,N)   alloca(N)\n# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)\n# define sqlite3StackFree(D,P)       \n#else\n# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)\n# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)\n# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)\n#endif\n\n#ifdef SQLITE_ENABLE_MEMSYS3\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS5\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);\n#endif\n\n\n#ifndef SQLITE_MUTEX_OMIT\nSQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);\nSQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);\nSQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);\nSQLITE_PRIVATE   int sqlite3MutexInit(void);\nSQLITE_PRIVATE   int sqlite3MutexEnd(void);\n#endif\n\nSQLITE_PRIVATE int sqlite3StatusValue(int);\nSQLITE_PRIVATE void sqlite3StatusAdd(int, int);\nSQLITE_PRIVATE void sqlite3StatusSet(int, int);\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\nSQLITE_PRIVATE   int sqlite3IsNaN(double);\n#else\n# define sqlite3IsNaN(X)  0\n#endif\n\nSQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);\n#ifndef SQLITE_OMIT_TRACE\nSQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);\n#endif\nSQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);\nSQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);\nSQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);\n#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)\nSQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);\n#endif\n#if defined(SQLITE_TEST)\nSQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);\n#endif\n\n/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\nSQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);\nSQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);\nSQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);\nSQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);\nSQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);\nSQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);\nSQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);\nSQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);\nSQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);\nSQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);\n#else\n# define sqlite3ExplainBegin(X)\n# define sqlite3ExplainSelect(A,B)\n# define sqlite3ExplainExpr(A,B)\n# define sqlite3ExplainExprList(A,B)\n# define sqlite3ExplainFinish(X)\n# define sqlite3VdbeExplanation(X) 0\n#endif\n\n\nSQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);\nSQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);\nSQLITE_PRIVATE int sqlite3Dequote(char*);\nSQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);\nSQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);\nSQLITE_PRIVATE void sqlite3FinishCoding(Parse*);\nSQLITE_PRIVATE int sqlite3GetTempReg(Parse*);\nSQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);\nSQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);\nSQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);\nSQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);\nSQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);\nSQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);\nSQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);\nSQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);\nSQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);\nSQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);\nSQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);\nSQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);\nSQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);\nSQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);\nSQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);\nSQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);\nSQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);\nSQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);\nSQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);\nSQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);\nSQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);\nSQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);\nSQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);\nSQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);\nSQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);\nSQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);\nSQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);\nSQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);\nSQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);\nSQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);\nSQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);\nSQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,\n                    sqlite3_vfs**,char**,char **);\nSQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);\nSQLITE_PRIVATE int sqlite3CodeOnce(Parse *);\n\nSQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);\nSQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);\nSQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);\nSQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);\nSQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);\nSQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);\nSQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);\n\nSQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);\nSQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);\nSQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);\nSQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);\nSQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);\n\nSQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);\n\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\nSQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);\n#else\n# define sqlite3ViewGetColumnNames(A,B) 0\n#endif\n\nSQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);\nSQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);\nSQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);\n#ifndef SQLITE_OMIT_AUTOINCREMENT\nSQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);\nSQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);\n#else\n# define sqlite3AutoincrementBegin(X)\n# define sqlite3AutoincrementEnd(X)\n#endif\nSQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);\nSQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);\nSQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);\nSQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);\nSQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,\n                                      Token*, Select*, Expr*, IdList*);\nSQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);\nSQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);\nSQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);\nSQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);\nSQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);\nSQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);\nSQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,\n                        Token*, int, int);\nSQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);\nSQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);\nSQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,\n                         Expr*,ExprList*,int,Expr*,Expr*);\nSQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);\nSQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);\nSQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);\nSQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\nSQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);\n#endif\nSQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);\nSQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);\nSQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(\n    Parse*,SrcList*,Expr*,ExprList**,ExprList*,u16,int);\nSQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);\nSQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);\nSQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);\nSQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);\nSQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);\nSQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);\nSQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);\nSQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);\nSQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);\nSQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);\nSQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);\nSQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);\nSQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);\nSQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);\nSQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);\nSQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);\nSQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);\nSQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);\nSQLITE_PRIVATE void sqlite3Vacuum(Parse*);\nSQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);\nSQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);\nSQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);\nSQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);\nSQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);\nSQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);\nSQLITE_PRIVATE void sqlite3PrngSaveState(void);\nSQLITE_PRIVATE void sqlite3PrngRestoreState(void);\nSQLITE_PRIVATE void sqlite3PrngResetState(void);\nSQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);\nSQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);\nSQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);\nSQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);\nSQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);\nSQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);\nSQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);\nSQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);\nSQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);\nSQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);\nSQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);\nSQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);\nSQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);\nSQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);\nSQLITE_PRIVATE int sqlite3IsRowid(const char*);\nSQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);\nSQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);\nSQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);\nSQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,\n                                     int*,int,int,int,int,int*);\nSQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);\nSQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);\nSQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);\nSQLITE_PRIVATE void sqlite3MultiWrite(Parse*);\nSQLITE_PRIVATE void sqlite3MayAbort(Parse*);\nSQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);\nSQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);\nSQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);\nSQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);\nSQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);\nSQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);\nSQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);\nSQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);\nSQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);\nSQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);\nSQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);\nSQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);\nSQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);\n\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\nSQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,\n                           Expr*,int, int);\nSQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);\nSQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);\nSQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);\nSQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);\nSQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);\nSQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,\n                            int, int, int);\nSQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);\n  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);\nSQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,\n                                        ExprList*,Select*,u8);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);\nSQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);\nSQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);\nSQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);\nSQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);\n# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))\n#else\n# define sqlite3TriggersExist(B,C,D,E,F) 0\n# define sqlite3DeleteTrigger(A,B)\n# define sqlite3DropTriggerPtr(A,B)\n# define sqlite3UnlinkAndDeleteTrigger(A,B,C)\n# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)\n# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)\n# define sqlite3TriggerList(X, Y) 0\n# define sqlite3ParseToplevel(p) p\n# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0\n#endif\n\nSQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);\nSQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);\nSQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);\n#ifndef SQLITE_OMIT_AUTHORIZATION\nSQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);\nSQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);\nSQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);\nSQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);\nSQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);\n#else\n# define sqlite3AuthRead(a,b,c,d)\n# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK\n# define sqlite3AuthContextPush(a,b,c)\n# define sqlite3AuthContextPop(a)  ((void)(a))\n#endif\nSQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);\nSQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);\nSQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);\nSQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);\nSQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);\nSQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);\nSQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);\nSQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);\nSQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);\nSQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);\nSQLITE_PRIVATE int sqlite3Atoi(const char*);\nSQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);\nSQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);\nSQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);\n\n/*\n** Routines to read and write variable-length integers.  These used to\n** be defined locally, but now we use the varint routines in the util.c\n** file.  Code should use the MACRO forms below, as the Varint32 versions\n** are coded to assume the single byte case is already handled (which \n** the MACRO form does).\n*/\nSQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);\nSQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);\nSQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);\nSQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);\nSQLITE_PRIVATE int sqlite3VarintLen(u64 v);\n\n/*\n** The header of a record consists of a sequence variable-length integers.\n** These integers are almost always small and are encoded as a single byte.\n** The following macros take advantage this fact to provide a fast encode\n** and decode of the integers in a record header.  It is faster for the common\n** case where the integer is a single byte.  It is a little slower when the\n** integer is two or more bytes.  But overall it is faster.\n**\n** The following expressions are equivalent:\n**\n**     x = sqlite3GetVarint32( A, &B );\n**     x = sqlite3PutVarint32( A, B );\n**\n**     x = getVarint32( A, B );\n**     x = putVarint32( A, B );\n**\n*/\n#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))\n#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))\n#define getVarint    sqlite3GetVarint\n#define putVarint    sqlite3PutVarint\n\n\nSQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);\nSQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);\nSQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);\nSQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);\nSQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);\nSQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);\nSQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);\nSQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);\nSQLITE_PRIVATE u8 sqlite3HexToInt(int h);\nSQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);\nSQLITE_PRIVATE const char *sqlite3ErrStr(int);\nSQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);\nSQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);\nSQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);\nSQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);\nSQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);\nSQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);\nSQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);\nSQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);\nSQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);\nSQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);\nSQLITE_PRIVATE int sqlite3AbsInt32(int);\n#ifdef SQLITE_ENABLE_8_3_NAMES\nSQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);\n#else\n# define sqlite3FileSuffix3(X,Y)\n#endif\nSQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);\n\nSQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);\nSQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);\nSQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, \n                        void(*)(void*));\nSQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);\nSQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);\nSQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);\n#ifdef SQLITE_ENABLE_STAT3\nSQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);\n#endif\nSQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);\nSQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);\n#ifndef SQLITE_AMALGAMATION\nSQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];\nSQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];\nSQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];\nSQLITE_PRIVATE const Token sqlite3IntTokens[];\nSQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;\nSQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;\n#ifndef SQLITE_OMIT_WSD\nSQLITE_PRIVATE int sqlite3PendingByte;\n#endif\n#endif\nSQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);\nSQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);\nSQLITE_PRIVATE void sqlite3AlterFunctions(void);\nSQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);\nSQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);\nSQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);\nSQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);\nSQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);\nSQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);\nSQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);\nSQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);\nSQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);\nSQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);\nSQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);\nSQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);\nSQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);\nSQLITE_PRIVATE char sqlite3AffinityType(const char*);\nSQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);\nSQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);\nSQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);\nSQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);\nSQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);\nSQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);\nSQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);\nSQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);\nSQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);\nSQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);\nSQLITE_PRIVATE void sqlite3SchemaClear(void *);\nSQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);\nSQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);\nSQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);\nSQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, \n  void (*)(sqlite3_context*,int,sqlite3_value **),\n  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),\n  FuncDestructor *pDestructor\n);\nSQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);\nSQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);\n\nSQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);\nSQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);\nSQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);\nSQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);\nSQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);\nSQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);\nSQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);\n\nSQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);\nSQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);\n\n/*\n** The interface to the LEMON-generated parser\n*/\nSQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));\nSQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));\nSQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);\n#ifdef YYTRACKMAXSTACKDEPTH\nSQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);\n#endif\n\nSQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);\n#else\n# define sqlite3CloseExtensions(X)\n#endif\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\nSQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);\n#else\n  #define sqlite3TableLock(v,w,x,y,z)\n#endif\n\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);\n#endif\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n#  define sqlite3VtabClear(Y)\n#  define sqlite3VtabSync(X,Y) SQLITE_OK\n#  define sqlite3VtabRollback(X)\n#  define sqlite3VtabCommit(X)\n#  define sqlite3VtabInSync(db) 0\n#  define sqlite3VtabLock(X) \n#  define sqlite3VtabUnlock(X)\n#  define sqlite3VtabUnlockList(X)\n#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK\n#  define sqlite3GetVTable(X,Y)  ((VTable*)0)\n#else\nSQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);\nSQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);\nSQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);\nSQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);\nSQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);\nSQLITE_PRIVATE    void sqlite3VtabLock(VTable *);\nSQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);\nSQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);\nSQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);\nSQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);\n#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)\n#endif\nSQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);\nSQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);\nSQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);\nSQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);\nSQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);\nSQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);\nSQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);\nSQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);\nSQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);\nSQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);\nSQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);\nSQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);\nSQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);\nSQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);\nSQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);\nSQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);\nSQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);\nSQLITE_PRIVATE const char *sqlite3JournalModename(int);\nSQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);\nSQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);\n\n/* Declarations for functions in fkey.c. All of these are replaced by\n** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign\n** key functionality is available. If OMIT_TRIGGER is defined but\n** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In\n** this case foreign keys are parsed, but no other functionality is \n** provided (enforcement of FK constraints requires the triggers sub-system).\n*/\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);\nSQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);\nSQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);\nSQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);\nSQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);\nSQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);\n#else\n  #define sqlite3FkActions(a,b,c,d)\n  #define sqlite3FkCheck(a,b,c,d)\n  #define sqlite3FkDropTable(a,b,c)\n  #define sqlite3FkOldmask(a,b)      0\n  #define sqlite3FkRequired(a,b,c,d) 0\n#endif\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);\n#else\n  #define sqlite3FkDelete(a,b)\n#endif\n\n\n/*\n** Available fault injectors.  Should be numbered beginning with 0.\n*/\n#define SQLITE_FAULTINJECTOR_MALLOC     0\n#define SQLITE_FAULTINJECTOR_COUNT      1\n\n/*\n** The interface to the code in fault.c used for identifying \"benign\"\n** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST\n** is not defined.\n*/\n#ifndef SQLITE_OMIT_BUILTIN_TEST\nSQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);\nSQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);\n#else\n  #define sqlite3BeginBenignMalloc()\n  #define sqlite3EndBenignMalloc()\n#endif\n\n#define IN_INDEX_ROWID           1\n#define IN_INDEX_EPH             2\n#define IN_INDEX_INDEX           3\nSQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);\n\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\nSQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);\nSQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);\nSQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);\n#else\n  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)\n#endif\n\nSQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);\nSQLITE_PRIVATE int sqlite3MemJournalSize(void);\nSQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);\n\n#if SQLITE_MAX_EXPR_DEPTH>0\nSQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);\nSQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);\nSQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);\n#else\n  #define sqlite3ExprSetHeight(x,y)\n  #define sqlite3SelectExprHeight(x) 0\n  #define sqlite3ExprCheckHeight(x,y)\n#endif\n\nSQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);\nSQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);\n\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\nSQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);\nSQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);\nSQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);\n#else\n  #define sqlite3ConnectionBlocked(x,y)\n  #define sqlite3ConnectionUnlocked(x)\n  #define sqlite3ConnectionClosed(x)\n#endif\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);\n#endif\n\n/*\n** If the SQLITE_ENABLE IOTRACE exists then the global variable\n** sqlite3IoTrace is a pointer to a printf-like routine used to\n** print I/O tracing messages. \n*/\n#ifdef SQLITE_ENABLE_IOTRACE\n# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }\nSQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);\nSQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);\n#else\n# define IOTRACE(A)\n# define sqlite3VdbeIOTraceSql(X)\n#endif\n\n/*\n** These routines are available for the mem2.c debugging memory allocator\n** only.  They are used to verify that different \"types\" of memory\n** allocations are properly tracked by the system.\n**\n** sqlite3MemdebugSetType() sets the \"type\" of an allocation to one of\n** the MEMTYPE_* macros defined below.  The type must be a bitmask with\n** a single bit set.\n**\n** sqlite3MemdebugHasType() returns true if any of the bits in its second\n** argument match the type set by the previous sqlite3MemdebugSetType().\n** sqlite3MemdebugHasType() is intended for use inside assert() statements.\n**\n** sqlite3MemdebugNoType() returns true if none of the bits in its second\n** argument match the type set by the previous sqlite3MemdebugSetType().\n**\n** Perhaps the most important point is the difference between MEMTYPE_HEAP\n** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means\n** it might have been allocated by lookaside, except the allocation was\n** too large or lookaside was already full.  It is important to verify\n** that allocations that might have been satisfied by lookaside are not\n** passed back to non-lookaside free() routines.  Asserts such as the\n** example above are placed on the non-lookaside free() routines to verify\n** this constraint. \n**\n** All of this is no-op for a production build.  It only comes into\n** play when the SQLITE_MEMDEBUG compile-time option is used.\n*/\n#ifdef SQLITE_MEMDEBUG\nSQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);\nSQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);\nSQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);\n#else\n# define sqlite3MemdebugSetType(X,Y)  /* no-op */\n# define sqlite3MemdebugHasType(X,Y)  1\n# define sqlite3MemdebugNoType(X,Y)   1\n#endif\n#define MEMTYPE_HEAP       0x01  /* General heap allocations */\n#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */\n#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */\n#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */\n#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */\n\n#endif /* _SQLITEINT_H_ */\n\n/************** End of sqliteInt.h *******************************************/\n/************** Begin file global.c ******************************************/\n/*\n** 2008 June 13\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains definitions of global variables and contants.\n*/\n\n/* An array to map all upper-case characters into their corresponding\n** lower-case character. \n**\n** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not\n** handle case conversions for the UTF character set since the tables\n** involved are nearly as big or bigger than SQLite itself.\n*/\nSQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {\n#ifdef SQLITE_ASCII\n      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,\n     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,\n     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,\n     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,\n    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,\n    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,\n    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,\n    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,\n    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,\n    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,\n    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,\n    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,\n    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,\n    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,\n    252,253,254,255\n#endif\n#ifdef SQLITE_EBCDIC\n      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */\n     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */\n     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */\n     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */\n     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */\n     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */\n     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */\n    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */\n    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */\n    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */\n    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */\n    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */\n    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */\n    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */\n    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */\n    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */\n#endif\n};\n\n/*\n** The following 256 byte lookup table is used to support SQLites built-in\n** equivalents to the following standard library functions:\n**\n**   isspace()                        0x01\n**   isalpha()                        0x02\n**   isdigit()                        0x04\n**   isalnum()                        0x06\n**   isxdigit()                       0x08\n**   toupper()                        0x20\n**   SQLite identifier character      0x40\n**\n** Bit 0x20 is set if the mapped character requires translation to upper\n** case. i.e. if the character is a lower-case ASCII character.\n** If x is a lower-case ASCII character, then its upper-case equivalent\n** is (x - 0x20). Therefore toupper() can be implemented as:\n**\n**   (x & ~(map[x]&0x20))\n**\n** Standard function tolower() is implemented using the sqlite3UpperToLower[]\n** array. tolower() is used more often than toupper() by SQLite.\n**\n** Bit 0x40 is set if the character non-alphanumeric and can be used in an \n** SQLite identifier.  Identifiers are alphanumerics, \"_\", \"$\", and any\n** non-ASCII UTF character. Hence the test for whether or not a character is\n** part of an identifier is 0x46.\n**\n** SQLite's versions are identical to the standard versions assuming a\n** locale of \"C\". They are implemented as macros in sqliteInt.h.\n*/\n#ifdef SQLITE_ASCII\nSQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */\n  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */\n  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !\"#$%&' */\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */\n  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */\n  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */\n\n  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */\n  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */\n  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */\n  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\\]^_ */\n  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */\n  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */\n  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */\n  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */\n\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */\n\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */\n  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */\n};\n#endif\n\n#ifndef SQLITE_USE_URI\n# define  SQLITE_USE_URI 0\n#endif\n\n/*\n** The following singleton contains the global configuration for\n** the SQLite library.\n*/\nSQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {\n   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */\n   1,                         /* bCoreMutex */\n   SQLITE_THREADSAFE==1,      /* bFullMutex */\n   SQLITE_USE_URI,            /* bOpenUri */\n   0x7ffffffe,                /* mxStrlen */\n   128,                       /* szLookaside */\n   500,                       /* nLookaside */\n   {0,0,0,0,0,0,0,0},         /* m */\n   {0,0,0,0,0,0,0,0,0},       /* mutex */\n   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */\n   (void*)0,                  /* pHeap */\n   0,                         /* nHeap */\n   0, 0,                      /* mnHeap, mxHeap */\n   (void*)0,                  /* pScratch */\n   0,                         /* szScratch */\n   0,                         /* nScratch */\n   (void*)0,                  /* pPage */\n   0,                         /* szPage */\n   0,                         /* nPage */\n   0,                         /* mxParserStack */\n   0,                         /* sharedCacheEnabled */\n   /* All the rest should always be initialized to zero */\n   0,                         /* isInit */\n   0,                         /* inProgress */\n   0,                         /* isMutexInit */\n   0,                         /* isMallocInit */\n   0,                         /* isPCacheInit */\n   0,                         /* pInitMutex */\n   0,                         /* nRefInitMutex */\n   0,                         /* xLog */\n   0,                         /* pLogArg */\n   0,                         /* bLocaltimeFault */\n};\n\n\n/*\n** Hash table for global functions - functions common to all\n** database connections.  After initialization, this table is\n** read-only.\n*/\nSQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;\n\n/*\n** Constant tokens for values 0 and 1.\n*/\nSQLITE_PRIVATE const Token sqlite3IntTokens[] = {\n   { \"0\", 1 },\n   { \"1\", 1 }\n};\n\n\n/*\n** The value of the \"pending\" byte must be 0x40000000 (1 byte past the\n** 1-gibabyte boundary) in a compatible database.  SQLite never uses\n** the database page that contains the pending byte.  It never attempts\n** to read or write that page.  The pending byte page is set assign\n** for use by the VFS layers as space for managing file locks.\n**\n** During testing, it is often desirable to move the pending byte to\n** a different position in the file.  This allows code that has to\n** deal with the pending byte to run on files that are much smaller\n** than 1 GiB.  The sqlite3_test_control() interface can be used to\n** move the pending byte.\n**\n** IMPORTANT:  Changing the pending byte to any value other than\n** 0x40000000 results in an incompatible database file format!\n** Changing the pending byte during operating results in undefined\n** and dileterious behavior.\n*/\n#ifndef SQLITE_OMIT_WSD\nSQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;\n#endif\n\n/*\n** Properties of opcodes.  The OPFLG_INITIALIZER macro is\n** created by mkopcodeh.awk during compilation.  Data is obtained\n** from the comments following the \"case OP_xxxx:\" statements in\n** the vdbe.c file.  \n*/\nSQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;\n\n/************** End of global.c **********************************************/\n/************** Begin file ctime.c *******************************************/\n/*\n** 2010 February 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements routines used to report what compile-time options\n** SQLite was built with.\n*/\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n\n\n/*\n** An array of names of all compile-time options.  This array should \n** be sorted A-Z.\n**\n** This array looks large, but in a typical installation actually uses\n** only a handful of compile-time options, so most times this array is usually\n** rather short and uses little memory space.\n*/\nstatic const char * const azCompileOpt[] = {\n\n/* These macros are provided to \"stringify\" the value of the define\n** for those options in which the value is meaningful. */\n#define CTIMEOPT_VAL_(opt) #opt\n#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)\n\n#ifdef SQLITE_32BIT_ROWID\n  \"32BIT_ROWID\",\n#endif\n#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC\n  \"4_BYTE_ALIGNED_MALLOC\",\n#endif\n#ifdef SQLITE_CASE_SENSITIVE_LIKE\n  \"CASE_SENSITIVE_LIKE\",\n#endif\n#ifdef SQLITE_CHECK_PAGES\n  \"CHECK_PAGES\",\n#endif\n#ifdef SQLITE_COVERAGE_TEST\n  \"COVERAGE_TEST\",\n#endif\n#ifdef SQLITE_CURDIR\n  \"CURDIR\",\n#endif\n#ifdef SQLITE_DEBUG\n  \"DEBUG\",\n#endif\n#ifdef SQLITE_DEFAULT_LOCKING_MODE\n  \"DEFAULT_LOCKING_MODE=\" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),\n#endif\n#ifdef SQLITE_DISABLE_DIRSYNC\n  \"DISABLE_DIRSYNC\",\n#endif\n#ifdef SQLITE_DISABLE_LFS\n  \"DISABLE_LFS\",\n#endif\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n  \"ENABLE_ATOMIC_WRITE\",\n#endif\n#ifdef SQLITE_ENABLE_CEROD\n  \"ENABLE_CEROD\",\n#endif\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n  \"ENABLE_COLUMN_METADATA\",\n#endif\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n  \"ENABLE_EXPENSIVE_ASSERT\",\n#endif\n#ifdef SQLITE_ENABLE_FTS1\n  \"ENABLE_FTS1\",\n#endif\n#ifdef SQLITE_ENABLE_FTS2\n  \"ENABLE_FTS2\",\n#endif\n#ifdef SQLITE_ENABLE_FTS3\n  \"ENABLE_FTS3\",\n#endif\n#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS\n  \"ENABLE_FTS3_PARENTHESIS\",\n#endif\n#ifdef SQLITE_ENABLE_FTS4\n  \"ENABLE_FTS4\",\n#endif\n#ifdef SQLITE_ENABLE_ICU\n  \"ENABLE_ICU\",\n#endif\n#ifdef SQLITE_ENABLE_IOTRACE\n  \"ENABLE_IOTRACE\",\n#endif\n#ifdef SQLITE_ENABLE_LOAD_EXTENSION\n  \"ENABLE_LOAD_EXTENSION\",\n#endif\n#ifdef SQLITE_ENABLE_LOCKING_STYLE\n  \"ENABLE_LOCKING_STYLE=\" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),\n#endif\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n  \"ENABLE_MEMORY_MANAGEMENT\",\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS3\n  \"ENABLE_MEMSYS3\",\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS5\n  \"ENABLE_MEMSYS5\",\n#endif\n#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK\n  \"ENABLE_OVERSIZE_CELL_CHECK\",\n#endif\n#ifdef SQLITE_ENABLE_RTREE\n  \"ENABLE_RTREE\",\n#endif\n#ifdef SQLITE_ENABLE_STAT3\n  \"ENABLE_STAT3\",\n#endif\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n  \"ENABLE_UNLOCK_NOTIFY\",\n#endif\n#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT\n  \"ENABLE_UPDATE_DELETE_LIMIT\",\n#endif\n#ifdef SQLITE_HAS_CODEC\n  \"HAS_CODEC\",\n#endif\n#ifdef SQLITE_HAVE_ISNAN\n  \"HAVE_ISNAN\",\n#endif\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  \"HOMEGROWN_RECURSIVE_MUTEX\",\n#endif\n#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS\n  \"IGNORE_AFP_LOCK_ERRORS\",\n#endif\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  \"IGNORE_FLOCK_LOCK_ERRORS\",\n#endif\n#ifdef SQLITE_INT64_TYPE\n  \"INT64_TYPE\",\n#endif\n#ifdef SQLITE_LOCK_TRACE\n  \"LOCK_TRACE\",\n#endif\n#ifdef SQLITE_MAX_SCHEMA_RETRY\n  \"MAX_SCHEMA_RETRY=\" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),\n#endif\n#ifdef SQLITE_MEMDEBUG\n  \"MEMDEBUG\",\n#endif\n#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT\n  \"MIXED_ENDIAN_64BIT_FLOAT\",\n#endif\n#ifdef SQLITE_NO_SYNC\n  \"NO_SYNC\",\n#endif\n#ifdef SQLITE_OMIT_ALTERTABLE\n  \"OMIT_ALTERTABLE\",\n#endif\n#ifdef SQLITE_OMIT_ANALYZE\n  \"OMIT_ANALYZE\",\n#endif\n#ifdef SQLITE_OMIT_ATTACH\n  \"OMIT_ATTACH\",\n#endif\n#ifdef SQLITE_OMIT_AUTHORIZATION\n  \"OMIT_AUTHORIZATION\",\n#endif\n#ifdef SQLITE_OMIT_AUTOINCREMENT\n  \"OMIT_AUTOINCREMENT\",\n#endif\n#ifdef SQLITE_OMIT_AUTOINIT\n  \"OMIT_AUTOINIT\",\n#endif\n#ifdef SQLITE_OMIT_AUTOMATIC_INDEX\n  \"OMIT_AUTOMATIC_INDEX\",\n#endif\n#ifdef SQLITE_OMIT_AUTORESET\n  \"OMIT_AUTORESET\",\n#endif\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  \"OMIT_AUTOVACUUM\",\n#endif\n#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION\n  \"OMIT_BETWEEN_OPTIMIZATION\",\n#endif\n#ifdef SQLITE_OMIT_BLOB_LITERAL\n  \"OMIT_BLOB_LITERAL\",\n#endif\n#ifdef SQLITE_OMIT_BTREECOUNT\n  \"OMIT_BTREECOUNT\",\n#endif\n#ifdef SQLITE_OMIT_BUILTIN_TEST\n  \"OMIT_BUILTIN_TEST\",\n#endif\n#ifdef SQLITE_OMIT_CAST\n  \"OMIT_CAST\",\n#endif\n#ifdef SQLITE_OMIT_CHECK\n  \"OMIT_CHECK\",\n#endif\n/* // redundant\n** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS\n**   \"OMIT_COMPILEOPTION_DIAGS\",\n** #endif\n*/\n#ifdef SQLITE_OMIT_COMPLETE\n  \"OMIT_COMPLETE\",\n#endif\n#ifdef SQLITE_OMIT_COMPOUND_SELECT\n  \"OMIT_COMPOUND_SELECT\",\n#endif\n#ifdef SQLITE_OMIT_DATETIME_FUNCS\n  \"OMIT_DATETIME_FUNCS\",\n#endif\n#ifdef SQLITE_OMIT_DECLTYPE\n  \"OMIT_DECLTYPE\",\n#endif\n#ifdef SQLITE_OMIT_DEPRECATED\n  \"OMIT_DEPRECATED\",\n#endif\n#ifdef SQLITE_OMIT_DISKIO\n  \"OMIT_DISKIO\",\n#endif\n#ifdef SQLITE_OMIT_EXPLAIN\n  \"OMIT_EXPLAIN\",\n#endif\n#ifdef SQLITE_OMIT_FLAG_PRAGMAS\n  \"OMIT_FLAG_PRAGMAS\",\n#endif\n#ifdef SQLITE_OMIT_FLOATING_POINT\n  \"OMIT_FLOATING_POINT\",\n#endif\n#ifdef SQLITE_OMIT_FOREIGN_KEY\n  \"OMIT_FOREIGN_KEY\",\n#endif\n#ifdef SQLITE_OMIT_GET_TABLE\n  \"OMIT_GET_TABLE\",\n#endif\n#ifdef SQLITE_OMIT_INCRBLOB\n  \"OMIT_INCRBLOB\",\n#endif\n#ifdef SQLITE_OMIT_INTEGRITY_CHECK\n  \"OMIT_INTEGRITY_CHECK\",\n#endif\n#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION\n  \"OMIT_LIKE_OPTIMIZATION\",\n#endif\n#ifdef SQLITE_OMIT_LOAD_EXTENSION\n  \"OMIT_LOAD_EXTENSION\",\n#endif\n#ifdef SQLITE_OMIT_LOCALTIME\n  \"OMIT_LOCALTIME\",\n#endif\n#ifdef SQLITE_OMIT_LOOKASIDE\n  \"OMIT_LOOKASIDE\",\n#endif\n#ifdef SQLITE_OMIT_MEMORYDB\n  \"OMIT_MEMORYDB\",\n#endif\n#ifdef SQLITE_OMIT_MERGE_SORT\n  \"OMIT_MERGE_SORT\",\n#endif\n#ifdef SQLITE_OMIT_OR_OPTIMIZATION\n  \"OMIT_OR_OPTIMIZATION\",\n#endif\n#ifdef SQLITE_OMIT_PAGER_PRAGMAS\n  \"OMIT_PAGER_PRAGMAS\",\n#endif\n#ifdef SQLITE_OMIT_PRAGMA\n  \"OMIT_PRAGMA\",\n#endif\n#ifdef SQLITE_OMIT_PROGRESS_CALLBACK\n  \"OMIT_PROGRESS_CALLBACK\",\n#endif\n#ifdef SQLITE_OMIT_QUICKBALANCE\n  \"OMIT_QUICKBALANCE\",\n#endif\n#ifdef SQLITE_OMIT_REINDEX\n  \"OMIT_REINDEX\",\n#endif\n#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS\n  \"OMIT_SCHEMA_PRAGMAS\",\n#endif\n#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS\n  \"OMIT_SCHEMA_VERSION_PRAGMAS\",\n#endif\n#ifdef SQLITE_OMIT_SHARED_CACHE\n  \"OMIT_SHARED_CACHE\",\n#endif\n#ifdef SQLITE_OMIT_SUBQUERY\n  \"OMIT_SUBQUERY\",\n#endif\n#ifdef SQLITE_OMIT_TCL_VARIABLE\n  \"OMIT_TCL_VARIABLE\",\n#endif\n#ifdef SQLITE_OMIT_TEMPDB\n  \"OMIT_TEMPDB\",\n#endif\n#ifdef SQLITE_OMIT_TRACE\n  \"OMIT_TRACE\",\n#endif\n#ifdef SQLITE_OMIT_TRIGGER\n  \"OMIT_TRIGGER\",\n#endif\n#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION\n  \"OMIT_TRUNCATE_OPTIMIZATION\",\n#endif\n#ifdef SQLITE_OMIT_UTF16\n  \"OMIT_UTF16\",\n#endif\n#ifdef SQLITE_OMIT_VACUUM\n  \"OMIT_VACUUM\",\n#endif\n#ifdef SQLITE_OMIT_VIEW\n  \"OMIT_VIEW\",\n#endif\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n  \"OMIT_VIRTUALTABLE\",\n#endif\n#ifdef SQLITE_OMIT_WAL\n  \"OMIT_WAL\",\n#endif\n#ifdef SQLITE_OMIT_WSD\n  \"OMIT_WSD\",\n#endif\n#ifdef SQLITE_OMIT_XFER_OPT\n  \"OMIT_XFER_OPT\",\n#endif\n#ifdef SQLITE_PERFORMANCE_TRACE\n  \"PERFORMANCE_TRACE\",\n#endif\n#ifdef SQLITE_PROXY_DEBUG\n  \"PROXY_DEBUG\",\n#endif\n#ifdef SQLITE_SECURE_DELETE\n  \"SECURE_DELETE\",\n#endif\n#ifdef SQLITE_SMALL_STACK\n  \"SMALL_STACK\",\n#endif\n#ifdef SQLITE_SOUNDEX\n  \"SOUNDEX\",\n#endif\n#ifdef SQLITE_TCL\n  \"TCL\",\n#endif\n#ifdef SQLITE_TEMP_STORE\n  \"TEMP_STORE=\" CTIMEOPT_VAL(SQLITE_TEMP_STORE),\n#endif\n#ifdef SQLITE_TEST\n  \"TEST\",\n#endif\n#ifdef SQLITE_THREADSAFE\n  \"THREADSAFE=\" CTIMEOPT_VAL(SQLITE_THREADSAFE),\n#endif\n#ifdef SQLITE_USE_ALLOCA\n  \"USE_ALLOCA\",\n#endif\n#ifdef SQLITE_ZERO_MALLOC\n  \"ZERO_MALLOC\"\n#endif\n};\n\n/*\n** Given the name of a compile-time option, return true if that option\n** was used and false if not.\n**\n** The name can optionally begin with \"SQLITE_\" but the \"SQLITE_\" prefix\n** is not required for a match.\n*/\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName){\n  int i, n;\n  if( sqlite3StrNICmp(zOptName, \"SQLITE_\", 7)==0 ) zOptName += 7;\n  n = sqlite3Strlen30(zOptName);\n\n  /* Since ArraySize(azCompileOpt) is normally in single digits, a\n  ** linear search is adequate.  No need for a binary search. */\n  for(i=0; i<ArraySize(azCompileOpt); i++){\n    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)\n       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;\n  }\n  return 0;\n}\n\n/*\n** Return the N-th compile-time option string.  If N is out of range,\n** return a NULL pointer.\n*/\nSQLITE_API const char *sqlite3_compileoption_get(int N){\n  if( N>=0 && N<ArraySize(azCompileOpt) ){\n    return azCompileOpt[N];\n  }\n  return 0;\n}\n\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/************** End of ctime.c ***********************************************/\n/************** Begin file status.c ******************************************/\n/*\n** 2008 June 18\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This module implements the sqlite3_status() interface and related\n** functionality.\n*/\n/************** Include vdbeInt.h in the middle of status.c ******************/\n/************** Begin file vdbeInt.h *****************************************/\n/*\n** 2003 September 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for information that is private to the\n** VDBE.  This information used to all be at the top of the single\n** source code file \"vdbe.c\".  When that file became too big (over\n** 6000 lines long) it was split up into several smaller files and\n** this header information was factored out.\n*/\n#ifndef _VDBEINT_H_\n#define _VDBEINT_H_\n\n/*\n** SQL is translated into a sequence of instructions to be\n** executed by a virtual machine.  Each instruction is an instance\n** of the following structure.\n*/\ntypedef struct VdbeOp Op;\n\n/*\n** Boolean values\n*/\ntypedef unsigned char Bool;\n\n/* Opaque type used by code in vdbesort.c */\ntypedef struct VdbeSorter VdbeSorter;\n\n/* Opaque type used by the explainer */\ntypedef struct Explain Explain;\n\n/*\n** A cursor is a pointer into a single BTree within a database file.\n** The cursor can seek to a BTree entry with a particular key, or\n** loop over all entries of the Btree.  You can also insert new BTree\n** entries or retrieve the key or data from the entry that the cursor\n** is currently pointing to.\n** \n** Every cursor that the virtual machine has open is represented by an\n** instance of the following structure.\n*/\nstruct VdbeCursor {\n  BtCursor *pCursor;    /* The cursor structure of the backend */\n  Btree *pBt;           /* Separate file holding temporary table */\n  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */\n  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */\n  int pseudoTableReg;   /* Register holding pseudotable content. */\n  int nField;           /* Number of fields in the header */\n  Bool zeroed;          /* True if zeroed out and ready for reuse */\n  Bool rowidIsValid;    /* True if lastRowid is valid */\n  Bool atFirst;         /* True if pointing to first entry */\n  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */\n  Bool nullRow;         /* True if pointing to a row with no data */\n  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */\n  Bool isTable;         /* True if a table requiring integer keys */\n  Bool isIndex;         /* True if an index containing keys only - no data */\n  Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */\n  Bool isSorter;        /* True if a new-style sorter */\n  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */\n  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */\n  i64 seqCount;         /* Sequence counter */\n  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */\n  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */\n  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */\n\n  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or \n  ** OP_IsUnique opcode on this cursor. */\n  int seekResult;\n\n  /* Cached information about the header for the data record that the\n  ** cursor is currently pointing to.  Only valid if cacheStatus matches\n  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of\n  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that\n  ** the cache is out of date.\n  **\n  ** aRow might point to (ephemeral) data for the current row, or it might\n  ** be NULL.\n  */\n  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */\n  int payloadSize;      /* Total number of bytes in the record */\n  u32 *aType;           /* Type values for all entries in the record */\n  u32 *aOffset;         /* Cached offsets to the start of each columns data */\n  u8 *aRow;             /* Data for the current row, if all on one page */\n};\ntypedef struct VdbeCursor VdbeCursor;\n\n/*\n** When a sub-program is executed (OP_Program), a structure of this type\n** is allocated to store the current value of the program counter, as\n** well as the current memory cell array and various other frame specific\n** values stored in the Vdbe struct. When the sub-program is finished, \n** these values are copied back to the Vdbe from the VdbeFrame structure,\n** restoring the state of the VM to as it was before the sub-program\n** began executing.\n**\n** The memory for a VdbeFrame object is allocated and managed by a memory\n** cell in the parent (calling) frame. When the memory cell is deleted or\n** overwritten, the VdbeFrame object is not freed immediately. Instead, it\n** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame\n** list is deleted when the VM is reset in VdbeHalt(). The reason for doing\n** this instead of deleting the VdbeFrame immediately is to avoid recursive\n** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the\n** child frame are released.\n**\n** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is\n** set to NULL if the currently executing frame is the main program.\n*/\ntypedef struct VdbeFrame VdbeFrame;\nstruct VdbeFrame {\n  Vdbe *v;                /* VM this frame belongs to */\n  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */\n  Op *aOp;                /* Program instructions for parent frame */\n  Mem *aMem;              /* Array of memory cells for parent frame */\n  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */\n  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */\n  void *token;            /* Copy of SubProgram.token */\n  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */\n  u16 nCursor;            /* Number of entries in apCsr */\n  int pc;                 /* Program Counter in parent (calling) frame */\n  int nOp;                /* Size of aOp array */\n  int nMem;               /* Number of entries in aMem */\n  int nOnceFlag;          /* Number of entries in aOnceFlag */\n  int nChildMem;          /* Number of memory cells for child frame */\n  int nChildCsr;          /* Number of cursors for child frame */\n  int nChange;            /* Statement changes (Vdbe.nChanges)     */\n};\n\n#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])\n\n/*\n** A value for VdbeCursor.cacheValid that means the cache is always invalid.\n*/\n#define CACHE_STALE 0\n\n/*\n** Internally, the vdbe manipulates nearly all SQL values as Mem\n** structures. Each Mem struct may cache multiple representations (string,\n** integer etc.) of the same value.\n*/\nstruct Mem {\n  sqlite3 *db;        /* The associated database connection */\n  char *z;            /* String or BLOB value */\n  double r;           /* Real value */\n  union {\n    i64 i;              /* Integer value used when MEM_Int is set in flags */\n    int nZero;          /* Used when bit MEM_Zero is set in flags */\n    FuncDef *pDef;      /* Used only when flags==MEM_Agg */\n    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */\n    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */\n  } u;\n  int n;              /* Number of characters in string value, excluding '\\0' */\n  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */\n  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */\n  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */\n#ifdef SQLITE_DEBUG\n  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */\n  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */\n#endif\n  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */\n  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */\n};\n\n/* One or more of the following flags are set to indicate the validOK\n** representations of the value stored in the Mem struct.\n**\n** If the MEM_Null flag is set, then the value is an SQL NULL value.\n** No other flags may be set in this case.\n**\n** If the MEM_Str flag is set then Mem.z points at a string representation.\n** Usually this is encoded in the same unicode encoding as the main\n** database (see below for exceptions). If the MEM_Term flag is also\n** set, then the string is nul terminated. The MEM_Int and MEM_Real \n** flags may coexist with the MEM_Str flag.\n*/\n#define MEM_Null      0x0001   /* Value is NULL */\n#define MEM_Str       0x0002   /* Value is a string */\n#define MEM_Int       0x0004   /* Value is an integer */\n#define MEM_Real      0x0008   /* Value is a real number */\n#define MEM_Blob      0x0010   /* Value is a BLOB */\n#define MEM_RowSet    0x0020   /* Value is a RowSet object */\n#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */\n#define MEM_Invalid   0x0080   /* Value is undefined */\n#define MEM_TypeMask  0x00ff   /* Mask of type bits */\n\n/* Whenever Mem contains a valid string or blob representation, one of\n** the following flags must be set to determine the memory management\n** policy for Mem.z.  The MEM_Term flag tells us whether or not the\n** string is \\000 or \\u0000 terminated\n*/\n#define MEM_Term      0x0200   /* String rep is nul terminated */\n#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */\n#define MEM_Static    0x0800   /* Mem.z points to a static string */\n#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */\n#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */\n#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */\n#ifdef SQLITE_OMIT_INCRBLOB\n  #undef MEM_Zero\n  #define MEM_Zero 0x0000\n#endif\n\n/*\n** Clear any existing type flags from a Mem and replace them with f\n*/\n#define MemSetTypeFlag(p, f) \\\n   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)\n\n/*\n** Return true if a memory cell is not marked as invalid.  This macro\n** is for use inside assert() statements only.\n*/\n#ifdef SQLITE_DEBUG\n#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0\n#endif\n\n\n/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains\n** additional information about auxiliary information bound to arguments\n** of the function.  This is used to implement the sqlite3_get_auxdata()\n** and sqlite3_set_auxdata() APIs.  The \"auxdata\" is some auxiliary data\n** that can be associated with a constant argument to a function.  This\n** allows functions such as \"regexp\" to compile their constant regular\n** expression argument once and reused the compiled code for multiple\n** invocations.\n*/\nstruct VdbeFunc {\n  FuncDef *pFunc;               /* The definition of the function */\n  int nAux;                     /* Number of entries allocated for apAux[] */\n  struct AuxData {\n    void *pAux;                   /* Aux data for the i-th argument */\n    void (*xDelete)(void *);      /* Destructor for the aux data */\n  } apAux[1];                   /* One slot for each function argument */\n};\n\n/*\n** The \"context\" argument for a installable function.  A pointer to an\n** instance of this structure is the first argument to the routines used\n** implement the SQL functions.\n**\n** There is a typedef for this structure in sqlite.h.  So all routines,\n** even the public interface to SQLite, can use a pointer to this structure.\n** But this file is the only place where the internal details of this\n** structure are known.\n**\n** This structure is defined inside of vdbeInt.h because it uses substructures\n** (Mem) which are only defined there.\n*/\nstruct sqlite3_context {\n  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */\n  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */\n  Mem s;                /* The return value is stored here */\n  Mem *pMem;            /* Memory cell used to store aggregate context */\n  CollSeq *pColl;       /* Collating sequence */\n  int isError;          /* Error code returned by the function. */\n  int skipFlag;         /* Skip skip accumulator loading if true */\n};\n\n/*\n** An Explain object accumulates indented output which is helpful\n** in describing recursive data structures.\n*/\nstruct Explain {\n  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */\n  StrAccum str;      /* The string being accumulated */\n  int nIndent;       /* Number of elements in aIndent */\n  u16 aIndent[100];  /* Levels of indentation */\n  char zBase[100];   /* Initial space */\n};\n\n/*\n** An instance of the virtual machine.  This structure contains the complete\n** state of the virtual machine.\n**\n** The \"sqlite3_stmt\" structure pointer that is returned by sqlite3_prepare()\n** is really a pointer to an instance of this structure.\n**\n** The Vdbe.inVtabMethod variable is set to non-zero for the duration of\n** any virtual table method invocations made by the vdbe program. It is\n** set to 2 for xDestroy method calls and 1 for all other methods. This\n** variable is used for two purposes: to allow xDestroy methods to execute\n** \"DROP TABLE\" statements and to prevent some nasty side effects of\n** malloc failure when SQLite is invoked recursively by a virtual table \n** method function.\n*/\nstruct Vdbe {\n  sqlite3 *db;            /* The database connection that owns this statement */\n  Op *aOp;                /* Space to hold the virtual machine's program */\n  Mem *aMem;              /* The memory locations */\n  Mem **apArg;            /* Arguments to currently executing user function */\n  Mem *aColName;          /* Column names to return */\n  Mem *pResultSet;        /* Pointer to an array of results */\n  int nMem;               /* Number of memory locations currently allocated */\n  int nOp;                /* Number of instructions in the program */\n  int nOpAlloc;           /* Number of slots allocated for aOp[] */\n  int nLabel;             /* Number of labels used */\n  int *aLabel;            /* Space to hold the labels */\n  u16 nResColumn;         /* Number of columns in one row of the result set */\n  u16 nCursor;            /* Number of slots in apCsr[] */\n  u32 magic;              /* Magic number for sanity checking */\n  char *zErrMsg;          /* Error message written here */\n  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */\n  VdbeCursor **apCsr;     /* One element of this array for each open cursor */\n  Mem *aVar;              /* Values for the OP_Variable opcode. */\n  char **azVar;           /* Name of variables */\n  ynVar nVar;             /* Number of entries in aVar[] */\n  ynVar nzVar;            /* Number of entries in azVar[] */\n  u32 cacheCtr;           /* VdbeCursor row cache generation counter */\n  int pc;                 /* The program counter */\n  int rc;                 /* Value to return */\n  u8 errorAction;         /* Recovery action to do in case of an error */\n  u8 explain;             /* True if EXPLAIN present on SQL command */\n  u8 changeCntOn;         /* True to update the change-counter */\n  u8 expired;             /* True if the VM needs to be recompiled */\n  u8 runOnlyOnce;         /* Automatically expire on reset */\n  u8 minWriteFileFormat;  /* Minimum file format for writable database files */\n  u8 inVtabMethod;        /* See comments above */\n  u8 usesStmtJournal;     /* True if uses a statement journal */\n  u8 readOnly;            /* True for read-only statements */\n  u8 isPrepareV2;         /* True if prepared with prepare_v2() */\n  int nChange;            /* Number of db changes made since last reset */\n  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */\n  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */\n  int iStatement;         /* Statement number (or 0 if has not opened stmt) */\n  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */\n#ifndef SQLITE_OMIT_TRACE\n  i64 startTime;          /* Time when query started - used for profiling */\n#endif\n  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */\n  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */\n  char *zSql;             /* Text of the SQL statement that generated this */\n  void *pFree;            /* Free this when deleting the vdbe */\n#ifdef SQLITE_DEBUG\n  FILE *trace;            /* Write an execution trace here, if not NULL */\n#endif\n#ifdef SQLITE_ENABLE_TREE_EXPLAIN\n  Explain *pExplain;      /* The explainer */\n  char *zExplain;         /* Explanation of data structures */\n#endif\n  VdbeFrame *pFrame;      /* Parent frame */\n  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */\n  int nFrame;             /* Number of frames in pFrame list */\n  u32 expmask;            /* Binding to these vars invalidates VM */\n  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */\n  int nOnceFlag;          /* Size of array aOnceFlag[] */\n  u8 *aOnceFlag;          /* Flags for OP_Once */\n};\n\n/*\n** The following are allowed values for Vdbe.magic\n*/\n#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */\n#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */\n#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */\n#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */\n\n/*\n** Function prototypes\n*/\nSQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);\nvoid sqliteVdbePopStack(Vdbe*,int);\nSQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\nSQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);\n#endif\nSQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);\nSQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);\nSQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);\n\nint sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);\nSQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);\nSQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);\nSQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);\nSQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);\nSQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);\nSQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);\nSQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));\nSQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64\n#else\nSQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);\n#endif\nSQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);\nSQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);\nSQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);\nSQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);\nSQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);\nSQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);\nSQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);\n#define VdbeMemRelease(X)  \\\n  if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \\\n    sqlite3VdbeMemReleaseExternal(X);\nSQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);\nSQLITE_PRIVATE const char *sqlite3OpcodeName(int);\nSQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);\nSQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);\nSQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);\nSQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);\nSQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);\nSQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);\n\n#ifdef SQLITE_OMIT_MERGE_SORT\n# define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK\n# define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK\n# define sqlite3VdbeSorterClose(Y,Z)\n# define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK\n# define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK\n# define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK\n# define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK\n#else\nSQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);\nSQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);\nSQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);\nSQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);\nSQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);\nSQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);\nSQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0\nSQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);\nSQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);\n#else\n# define sqlite3VdbeEnter(X)\n# define sqlite3VdbeLeave(X)\n#endif\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);\n#endif\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);\n#else\n# define sqlite3VdbeCheckFk(p,i) 0\n#endif\n\nSQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);\nSQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);\n#endif\nSQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);\n\n#ifndef SQLITE_OMIT_INCRBLOB\nSQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);\n  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)\n#else\n  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK\n  #define ExpandBlob(P) SQLITE_OK\n#endif\n\n#endif /* !defined(_VDBEINT_H_) */\n\n/************** End of vdbeInt.h *********************************************/\n/************** Continuing where we left off in status.c *********************/\n\n/*\n** Variables in which to record status information.\n*/\ntypedef struct sqlite3StatType sqlite3StatType;\nstatic SQLITE_WSD struct sqlite3StatType {\n  int nowValue[10];         /* Current value */\n  int mxValue[10];          /* Maximum value */\n} sqlite3Stat = { {0,}, {0,} };\n\n\n/* The \"wsdStat\" macro will resolve to the status information\n** state vector.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdStat can refer directly\n** to the \"sqlite3Stat\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)\n# define wsdStat x[0]\n#else\n# define wsdStatInit\n# define wsdStat sqlite3Stat\n#endif\n\n/*\n** Return the current value of a status parameter.\n*/\nSQLITE_PRIVATE int sqlite3StatusValue(int op){\n  wsdStatInit;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  return wsdStat.nowValue[op];\n}\n\n/*\n** Add N to the value of a status record.  It is assumed that the\n** caller holds appropriate locks.\n*/\nSQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){\n  wsdStatInit;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  wsdStat.nowValue[op] += N;\n  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){\n    wsdStat.mxValue[op] = wsdStat.nowValue[op];\n  }\n}\n\n/*\n** Set the value of a status to X.\n*/\nSQLITE_PRIVATE void sqlite3StatusSet(int op, int X){\n  wsdStatInit;\n  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );\n  wsdStat.nowValue[op] = X;\n  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){\n    wsdStat.mxValue[op] = wsdStat.nowValue[op];\n  }\n}\n\n/*\n** Query status information.\n**\n** This implementation assumes that reading or writing an aligned\n** 32-bit integer is an atomic operation.  If that assumption is not true,\n** then this routine is not threadsafe.\n*/\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){\n  wsdStatInit;\n  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  *pCurrent = wsdStat.nowValue[op];\n  *pHighwater = wsdStat.mxValue[op];\n  if( resetFlag ){\n    wsdStat.mxValue[op] = wsdStat.nowValue[op];\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Query status information for a single database connection\n*/\nSQLITE_API int sqlite3_db_status(\n  sqlite3 *db,          /* The database connection whose status is desired */\n  int op,               /* Status verb */\n  int *pCurrent,        /* Write current value here */\n  int *pHighwater,      /* Write high-water mark here */\n  int resetFlag         /* Reset high-water mark if true */\n){\n  int rc = SQLITE_OK;   /* Return code */\n  sqlite3_mutex_enter(db->mutex);\n  switch( op ){\n    case SQLITE_DBSTATUS_LOOKASIDE_USED: {\n      *pCurrent = db->lookaside.nOut;\n      *pHighwater = db->lookaside.mxOut;\n      if( resetFlag ){\n        db->lookaside.mxOut = db->lookaside.nOut;\n      }\n      break;\n    }\n\n    case SQLITE_DBSTATUS_LOOKASIDE_HIT:\n    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:\n    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );\n      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );\n      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );\n      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );\n      *pCurrent = 0;\n      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];\n      if( resetFlag ){\n        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;\n      }\n      break;\n    }\n\n    /* \n    ** Return an approximation for the amount of memory currently used\n    ** by all pagers associated with the given database connection.  The\n    ** highwater mark is meaningless and is returned as zero.\n    */\n    case SQLITE_DBSTATUS_CACHE_USED: {\n      int totalUsed = 0;\n      int i;\n      sqlite3BtreeEnterAll(db);\n      for(i=0; i<db->nDb; i++){\n        Btree *pBt = db->aDb[i].pBt;\n        if( pBt ){\n          Pager *pPager = sqlite3BtreePager(pBt);\n          totalUsed += sqlite3PagerMemUsed(pPager);\n        }\n      }\n      sqlite3BtreeLeaveAll(db);\n      *pCurrent = totalUsed;\n      *pHighwater = 0;\n      break;\n    }\n\n    /*\n    ** *pCurrent gets an accurate estimate of the amount of memory used\n    ** to store the schema for all databases (main, temp, and any ATTACHed\n    ** databases.  *pHighwater is set to zero.\n    */\n    case SQLITE_DBSTATUS_SCHEMA_USED: {\n      int i;                      /* Used to iterate through schemas */\n      int nByte = 0;              /* Used to accumulate return value */\n\n      sqlite3BtreeEnterAll(db);\n      db->pnBytesFreed = &nByte;\n      for(i=0; i<db->nDb; i++){\n        Schema *pSchema = db->aDb[i].pSchema;\n        if( ALWAYS(pSchema!=0) ){\n          HashElem *p;\n\n          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (\n              pSchema->tblHash.count \n            + pSchema->trigHash.count\n            + pSchema->idxHash.count\n            + pSchema->fkeyHash.count\n          );\n          nByte += sqlite3MallocSize(pSchema->tblHash.ht);\n          nByte += sqlite3MallocSize(pSchema->trigHash.ht);\n          nByte += sqlite3MallocSize(pSchema->idxHash.ht);\n          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);\n\n          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){\n            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));\n          }\n          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){\n            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));\n          }\n        }\n      }\n      db->pnBytesFreed = 0;\n      sqlite3BtreeLeaveAll(db);\n\n      *pHighwater = 0;\n      *pCurrent = nByte;\n      break;\n    }\n\n    /*\n    ** *pCurrent gets an accurate estimate of the amount of memory used\n    ** to store all prepared statements.\n    ** *pHighwater is set to zero.\n    */\n    case SQLITE_DBSTATUS_STMT_USED: {\n      struct Vdbe *pVdbe;         /* Used to iterate through VMs */\n      int nByte = 0;              /* Used to accumulate return value */\n\n      db->pnBytesFreed = &nByte;\n      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){\n        sqlite3VdbeDeleteObject(db, pVdbe);\n      }\n      db->pnBytesFreed = 0;\n\n      *pHighwater = 0;\n      *pCurrent = nByte;\n\n      break;\n    }\n\n    /*\n    ** Set *pCurrent to the total cache hits or misses encountered by all\n    ** pagers the database handle is connected to. *pHighwater is always set \n    ** to zero.\n    */\n    case SQLITE_DBSTATUS_CACHE_HIT:\n    case SQLITE_DBSTATUS_CACHE_MISS:\n    case SQLITE_DBSTATUS_CACHE_WRITE:{\n      int i;\n      int nRet = 0;\n      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );\n      assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );\n\n      for(i=0; i<db->nDb; i++){\n        if( db->aDb[i].pBt ){\n          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);\n          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);\n        }\n      }\n      *pHighwater = 0;\n      *pCurrent = nRet;\n      break;\n    }\n\n    default: {\n      rc = SQLITE_ERROR;\n    }\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/************** End of status.c **********************************************/\n/************** Begin file date.c ********************************************/\n/*\n** 2003 October 31\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement date and time\n** functions for SQLite.  \n**\n** There is only one exported symbol in this file - the function\n** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.\n** All other code has file scope.\n**\n** SQLite processes all times and dates as Julian Day numbers.  The\n** dates and times are stored as the number of days since noon\n** in Greenwich on November 24, 4714 B.C. according to the Gregorian\n** calendar system. \n**\n** 1970-01-01 00:00:00 is JD 2440587.5\n** 2000-01-01 00:00:00 is JD 2451544.5\n**\n** This implemention requires years to be expressed as a 4-digit number\n** which means that only dates between 0000-01-01 and 9999-12-31 can\n** be represented, even though julian day numbers allow a much wider\n** range of dates.\n**\n** The Gregorian calendar system is used for all dates and times,\n** even those that predate the Gregorian calendar.  Historians usually\n** use the Julian calendar for dates prior to 1582-10-15 and for some\n** dates afterwards, depending on locale.  Beware of this difference.\n**\n** The conversion algorithms are implemented based on descriptions\n** in the following text:\n**\n**      Jean Meeus\n**      Astronomical Algorithms, 2nd Edition, 1998\n**      ISBM 0-943396-61-1\n**      Willmann-Bell, Inc\n**      Richmond, Virginia (USA)\n*/\n/* #include <stdlib.h> */\n/* #include <assert.h> */\n#include <time.h>\n\n#ifndef SQLITE_OMIT_DATETIME_FUNCS\n\n\n/*\n** A structure for holding a single date and time.\n*/\ntypedef struct DateTime DateTime;\nstruct DateTime {\n  sqlite3_int64 iJD; /* The julian day number times 86400000 */\n  int Y, M, D;       /* Year, month, and day */\n  int h, m;          /* Hour and minutes */\n  int tz;            /* Timezone offset in minutes */\n  double s;          /* Seconds */\n  char validYMD;     /* True (1) if Y,M,D are valid */\n  char validHMS;     /* True (1) if h,m,s are valid */\n  char validJD;      /* True (1) if iJD is valid */\n  char validTZ;      /* True (1) if tz is valid */\n};\n\n\n/*\n** Convert zDate into one or more integers.  Additional arguments\n** come in groups of 5 as follows:\n**\n**       N       number of digits in the integer\n**       min     minimum allowed value of the integer\n**       max     maximum allowed value of the integer\n**       nextC   first character after the integer\n**       pVal    where to write the integers value.\n**\n** Conversions continue until one with nextC==0 is encountered.\n** The function returns the number of successful conversions.\n*/\nstatic int getDigits(const char *zDate, ...){\n  va_list ap;\n  int val;\n  int N;\n  int min;\n  int max;\n  int nextC;\n  int *pVal;\n  int cnt = 0;\n  va_start(ap, zDate);\n  do{\n    N = va_arg(ap, int);\n    min = va_arg(ap, int);\n    max = va_arg(ap, int);\n    nextC = va_arg(ap, int);\n    pVal = va_arg(ap, int*);\n    val = 0;\n    while( N-- ){\n      if( !sqlite3Isdigit(*zDate) ){\n        goto end_getDigits;\n      }\n      val = val*10 + *zDate - '0';\n      zDate++;\n    }\n    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){\n      goto end_getDigits;\n    }\n    *pVal = val;\n    zDate++;\n    cnt++;\n  }while( nextC );\nend_getDigits:\n  va_end(ap);\n  return cnt;\n}\n\n/*\n** Parse a timezone extension on the end of a date-time.\n** The extension is of the form:\n**\n**        (+/-)HH:MM\n**\n** Or the \"zulu\" notation:\n**\n**        Z\n**\n** If the parse is successful, write the number of minutes\n** of change in p->tz and return 0.  If a parser error occurs,\n** return non-zero.\n**\n** A missing specifier is not considered an error.\n*/\nstatic int parseTimezone(const char *zDate, DateTime *p){\n  int sgn = 0;\n  int nHr, nMn;\n  int c;\n  while( sqlite3Isspace(*zDate) ){ zDate++; }\n  p->tz = 0;\n  c = *zDate;\n  if( c=='-' ){\n    sgn = -1;\n  }else if( c=='+' ){\n    sgn = +1;\n  }else if( c=='Z' || c=='z' ){\n    zDate++;\n    goto zulu_time;\n  }else{\n    return c!=0;\n  }\n  zDate++;\n  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){\n    return 1;\n  }\n  zDate += 5;\n  p->tz = sgn*(nMn + nHr*60);\nzulu_time:\n  while( sqlite3Isspace(*zDate) ){ zDate++; }\n  return *zDate!=0;\n}\n\n/*\n** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.\n** The HH, MM, and SS must each be exactly 2 digits.  The\n** fractional seconds FFFF can be one or more digits.\n**\n** Return 1 if there is a parsing error and 0 on success.\n*/\nstatic int parseHhMmSs(const char *zDate, DateTime *p){\n  int h, m, s;\n  double ms = 0.0;\n  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){\n    return 1;\n  }\n  zDate += 5;\n  if( *zDate==':' ){\n    zDate++;\n    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){\n      return 1;\n    }\n    zDate += 2;\n    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){\n      double rScale = 1.0;\n      zDate++;\n      while( sqlite3Isdigit(*zDate) ){\n        ms = ms*10.0 + *zDate - '0';\n        rScale *= 10.0;\n        zDate++;\n      }\n      ms /= rScale;\n    }\n  }else{\n    s = 0;\n  }\n  p->validJD = 0;\n  p->validHMS = 1;\n  p->h = h;\n  p->m = m;\n  p->s = s + ms;\n  if( parseTimezone(zDate, p) ) return 1;\n  p->validTZ = (p->tz!=0)?1:0;\n  return 0;\n}\n\n/*\n** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume\n** that the YYYY-MM-DD is according to the Gregorian calendar.\n**\n** Reference:  Meeus page 61\n*/\nstatic void computeJD(DateTime *p){\n  int Y, M, D, A, B, X1, X2;\n\n  if( p->validJD ) return;\n  if( p->validYMD ){\n    Y = p->Y;\n    M = p->M;\n    D = p->D;\n  }else{\n    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */\n    M = 1;\n    D = 1;\n  }\n  if( M<=2 ){\n    Y--;\n    M += 12;\n  }\n  A = Y/100;\n  B = 2 - A + (A/4);\n  X1 = 36525*(Y+4716)/100;\n  X2 = 306001*(M+1)/10000;\n  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);\n  p->validJD = 1;\n  if( p->validHMS ){\n    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);\n    if( p->validTZ ){\n      p->iJD -= p->tz*60000;\n      p->validYMD = 0;\n      p->validHMS = 0;\n      p->validTZ = 0;\n    }\n  }\n}\n\n/*\n** Parse dates of the form\n**\n**     YYYY-MM-DD HH:MM:SS.FFF\n**     YYYY-MM-DD HH:MM:SS\n**     YYYY-MM-DD HH:MM\n**     YYYY-MM-DD\n**\n** Write the result into the DateTime structure and return 0\n** on success and 1 if the input string is not a well-formed\n** date.\n*/\nstatic int parseYyyyMmDd(const char *zDate, DateTime *p){\n  int Y, M, D, neg;\n\n  if( zDate[0]=='-' ){\n    zDate++;\n    neg = 1;\n  }else{\n    neg = 0;\n  }\n  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){\n    return 1;\n  }\n  zDate += 10;\n  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }\n  if( parseHhMmSs(zDate, p)==0 ){\n    /* We got the time */\n  }else if( *zDate==0 ){\n    p->validHMS = 0;\n  }else{\n    return 1;\n  }\n  p->validJD = 0;\n  p->validYMD = 1;\n  p->Y = neg ? -Y : Y;\n  p->M = M;\n  p->D = D;\n  if( p->validTZ ){\n    computeJD(p);\n  }\n  return 0;\n}\n\n/*\n** Set the time to the current time reported by the VFS.\n**\n** Return the number of errors.\n*/\nstatic int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){\n    p->validJD = 1;\n    return 0;\n  }else{\n    return 1;\n  }\n}\n\n/*\n** Attempt to parse the given string into a Julian Day Number.  Return\n** the number of errors.\n**\n** The following are acceptable forms for the input string:\n**\n**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM\n**      DDDD.DD \n**      now\n**\n** In the first form, the +/-HH:MM is always optional.  The fractional\n** seconds extension (the \".FFF\") is optional.  The seconds portion\n** (\":SS.FFF\") is option.  The year and date can be omitted as long\n** as there is a time string.  The time string can be omitted as long\n** as there is a year and date.\n*/\nstatic int parseDateOrTime(\n  sqlite3_context *context, \n  const char *zDate, \n  DateTime *p\n){\n  double r;\n  if( parseYyyyMmDd(zDate,p)==0 ){\n    return 0;\n  }else if( parseHhMmSs(zDate, p)==0 ){\n    return 0;\n  }else if( sqlite3StrICmp(zDate,\"now\")==0){\n    return setDateTimeToCurrent(context, p);\n  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){\n    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);\n    p->validJD = 1;\n    return 0;\n  }\n  return 1;\n}\n\n/*\n** Compute the Year, Month, and Day from the julian day number.\n*/\nstatic void computeYMD(DateTime *p){\n  int Z, A, B, C, D, E, X1;\n  if( p->validYMD ) return;\n  if( !p->validJD ){\n    p->Y = 2000;\n    p->M = 1;\n    p->D = 1;\n  }else{\n    Z = (int)((p->iJD + 43200000)/86400000);\n    A = (int)((Z - 1867216.25)/36524.25);\n    A = Z + 1 + A - (A/4);\n    B = A + 1524;\n    C = (int)((B - 122.1)/365.25);\n    D = (36525*C)/100;\n    E = (int)((B-D)/30.6001);\n    X1 = (int)(30.6001*E);\n    p->D = B - D - X1;\n    p->M = E<14 ? E-1 : E-13;\n    p->Y = p->M>2 ? C - 4716 : C - 4715;\n  }\n  p->validYMD = 1;\n}\n\n/*\n** Compute the Hour, Minute, and Seconds from the julian day number.\n*/\nstatic void computeHMS(DateTime *p){\n  int s;\n  if( p->validHMS ) return;\n  computeJD(p);\n  s = (int)((p->iJD + 43200000) % 86400000);\n  p->s = s/1000.0;\n  s = (int)p->s;\n  p->s -= s;\n  p->h = s/3600;\n  s -= p->h*3600;\n  p->m = s/60;\n  p->s += s - p->m*60;\n  p->validHMS = 1;\n}\n\n/*\n** Compute both YMD and HMS\n*/\nstatic void computeYMD_HMS(DateTime *p){\n  computeYMD(p);\n  computeHMS(p);\n}\n\n/*\n** Clear the YMD and HMS and the TZ\n*/\nstatic void clearYMD_HMS_TZ(DateTime *p){\n  p->validYMD = 0;\n  p->validHMS = 0;\n  p->validTZ = 0;\n}\n\n/*\n** On recent Windows platforms, the localtime_s() function is available\n** as part of the \"Secure CRT\". It is essentially equivalent to \n** localtime_r() available under most POSIX platforms, except that the \n** order of the parameters is reversed.\n**\n** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.\n**\n** If the user has not indicated to use localtime_r() or localtime_s()\n** already, check for an MSVC build environment that provides \n** localtime_s().\n*/\n#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \\\n     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)\n#define HAVE_LOCALTIME_S 1\n#endif\n\n#ifndef SQLITE_OMIT_LOCALTIME\n/*\n** The following routine implements the rough equivalent of localtime_r()\n** using whatever operating-system specific localtime facility that\n** is available.  This routine returns 0 on success and\n** non-zero on any kind of error.\n**\n** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this\n** routine will always fail.\n*/\nstatic int osLocaltime(time_t *t, struct tm *pTm){\n  int rc;\n#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \\\n      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)\n  struct tm *pX;\n#if SQLITE_THREADSAFE>0\n  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  sqlite3_mutex_enter(mutex);\n  pX = localtime(t);\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;\n#endif\n  if( pX ) *pTm = *pX;\n  sqlite3_mutex_leave(mutex);\n  rc = pX==0;\n#else\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;\n#endif\n#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R\n  rc = localtime_r(t, pTm)==0;\n#else\n  rc = localtime_s(pTm, t);\n#endif /* HAVE_LOCALTIME_R */\n#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */\n  return rc;\n}\n#endif /* SQLITE_OMIT_LOCALTIME */\n\n\n#ifndef SQLITE_OMIT_LOCALTIME\n/*\n** Compute the difference (in milliseconds) between localtime and UTC\n** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,\n** return this value and set *pRc to SQLITE_OK. \n**\n** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value\n** is undefined in this case.\n*/\nstatic sqlite3_int64 localtimeOffset(\n  DateTime *p,                    /* Date at which to calculate offset */\n  sqlite3_context *pCtx,          /* Write error here if one occurs */\n  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */\n){\n  DateTime x, y;\n  time_t t;\n  struct tm sLocal;\n\n  /* Initialize the contents of sLocal to avoid a compiler warning. */\n  memset(&sLocal, 0, sizeof(sLocal));\n\n  x = *p;\n  computeYMD_HMS(&x);\n  if( x.Y<1971 || x.Y>=2038 ){\n    x.Y = 2000;\n    x.M = 1;\n    x.D = 1;\n    x.h = 0;\n    x.m = 0;\n    x.s = 0.0;\n  } else {\n    int s = (int)(x.s + 0.5);\n    x.s = s;\n  }\n  x.tz = 0;\n  x.validJD = 0;\n  computeJD(&x);\n  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);\n  if( osLocaltime(&t, &sLocal) ){\n    sqlite3_result_error(pCtx, \"local time unavailable\", -1);\n    *pRc = SQLITE_ERROR;\n    return 0;\n  }\n  y.Y = sLocal.tm_year + 1900;\n  y.M = sLocal.tm_mon + 1;\n  y.D = sLocal.tm_mday;\n  y.h = sLocal.tm_hour;\n  y.m = sLocal.tm_min;\n  y.s = sLocal.tm_sec;\n  y.validYMD = 1;\n  y.validHMS = 1;\n  y.validJD = 0;\n  y.validTZ = 0;\n  computeJD(&y);\n  *pRc = SQLITE_OK;\n  return y.iJD - x.iJD;\n}\n#endif /* SQLITE_OMIT_LOCALTIME */\n\n/*\n** Process a modifier to a date-time stamp.  The modifiers are\n** as follows:\n**\n**     NNN days\n**     NNN hours\n**     NNN minutes\n**     NNN.NNNN seconds\n**     NNN months\n**     NNN years\n**     start of month\n**     start of year\n**     start of week\n**     start of day\n**     weekday N\n**     unixepoch\n**     localtime\n**     utc\n**\n** Return 0 on success and 1 if there is any kind of error. If the error\n** is in a system call (i.e. localtime()), then an error message is written\n** to context pCtx. If the error is an unrecognized modifier, no error is\n** written to pCtx.\n*/\nstatic int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){\n  int rc = 1;\n  int n;\n  double r;\n  char *z, zBuf[30];\n  z = zBuf;\n  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){\n    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];\n  }\n  z[n] = 0;\n  switch( z[0] ){\n#ifndef SQLITE_OMIT_LOCALTIME\n    case 'l': {\n      /*    localtime\n      **\n      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to\n      ** show local time.\n      */\n      if( strcmp(z, \"localtime\")==0 ){\n        computeJD(p);\n        p->iJD += localtimeOffset(p, pCtx, &rc);\n        clearYMD_HMS_TZ(p);\n      }\n      break;\n    }\n#endif\n    case 'u': {\n      /*\n      **    unixepoch\n      **\n      ** Treat the current value of p->iJD as the number of\n      ** seconds since 1970.  Convert to a real julian day number.\n      */\n      if( strcmp(z, \"unixepoch\")==0 && p->validJD ){\n        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;\n        clearYMD_HMS_TZ(p);\n        rc = 0;\n      }\n#ifndef SQLITE_OMIT_LOCALTIME\n      else if( strcmp(z, \"utc\")==0 ){\n        sqlite3_int64 c1;\n        computeJD(p);\n        c1 = localtimeOffset(p, pCtx, &rc);\n        if( rc==SQLITE_OK ){\n          p->iJD -= c1;\n          clearYMD_HMS_TZ(p);\n          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);\n        }\n      }\n#endif\n      break;\n    }\n    case 'w': {\n      /*\n      **    weekday N\n      **\n      ** Move the date to the same time on the next occurrence of\n      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the\n      ** date is already on the appropriate weekday, this is a no-op.\n      */\n      if( strncmp(z, \"weekday \", 8)==0\n               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)\n               && (n=(int)r)==r && n>=0 && r<7 ){\n        sqlite3_int64 Z;\n        computeYMD_HMS(p);\n        p->validTZ = 0;\n        p->validJD = 0;\n        computeJD(p);\n        Z = ((p->iJD + 129600000)/86400000) % 7;\n        if( Z>n ) Z -= 7;\n        p->iJD += (n - Z)*86400000;\n        clearYMD_HMS_TZ(p);\n        rc = 0;\n      }\n      break;\n    }\n    case 's': {\n      /*\n      **    start of TTTTT\n      **\n      ** Move the date backwards to the beginning of the current day,\n      ** or month or year.\n      */\n      if( strncmp(z, \"start of \", 9)!=0 ) break;\n      z += 9;\n      computeYMD(p);\n      p->validHMS = 1;\n      p->h = p->m = 0;\n      p->s = 0.0;\n      p->validTZ = 0;\n      p->validJD = 0;\n      if( strcmp(z,\"month\")==0 ){\n        p->D = 1;\n        rc = 0;\n      }else if( strcmp(z,\"year\")==0 ){\n        computeYMD(p);\n        p->M = 1;\n        p->D = 1;\n        rc = 0;\n      }else if( strcmp(z,\"day\")==0 ){\n        rc = 0;\n      }\n      break;\n    }\n    case '+':\n    case '-':\n    case '0':\n    case '1':\n    case '2':\n    case '3':\n    case '4':\n    case '5':\n    case '6':\n    case '7':\n    case '8':\n    case '9': {\n      double rRounder;\n      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}\n      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){\n        rc = 1;\n        break;\n      }\n      if( z[n]==':' ){\n        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the\n        ** specified number of hours, minutes, seconds, and fractional seconds\n        ** to the time.  The \".FFF\" may be omitted.  The \":SS.FFF\" may be\n        ** omitted.\n        */\n        const char *z2 = z;\n        DateTime tx;\n        sqlite3_int64 day;\n        if( !sqlite3Isdigit(*z2) ) z2++;\n        memset(&tx, 0, sizeof(tx));\n        if( parseHhMmSs(z2, &tx) ) break;\n        computeJD(&tx);\n        tx.iJD -= 43200000;\n        day = tx.iJD/86400000;\n        tx.iJD -= day*86400000;\n        if( z[0]=='-' ) tx.iJD = -tx.iJD;\n        computeJD(p);\n        clearYMD_HMS_TZ(p);\n        p->iJD += tx.iJD;\n        rc = 0;\n        break;\n      }\n      z += n;\n      while( sqlite3Isspace(*z) ) z++;\n      n = sqlite3Strlen30(z);\n      if( n>10 || n<3 ) break;\n      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }\n      computeJD(p);\n      rc = 0;\n      rRounder = r<0 ? -0.5 : +0.5;\n      if( n==3 && strcmp(z,\"day\")==0 ){\n        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);\n      }else if( n==4 && strcmp(z,\"hour\")==0 ){\n        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);\n      }else if( n==6 && strcmp(z,\"minute\")==0 ){\n        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);\n      }else if( n==6 && strcmp(z,\"second\")==0 ){\n        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);\n      }else if( n==5 && strcmp(z,\"month\")==0 ){\n        int x, y;\n        computeYMD_HMS(p);\n        p->M += (int)r;\n        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;\n        p->Y += x;\n        p->M -= x*12;\n        p->validJD = 0;\n        computeJD(p);\n        y = (int)r;\n        if( y!=r ){\n          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);\n        }\n      }else if( n==4 && strcmp(z,\"year\")==0 ){\n        int y = (int)r;\n        computeYMD_HMS(p);\n        p->Y += y;\n        p->validJD = 0;\n        computeJD(p);\n        if( y!=r ){\n          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);\n        }\n      }else{\n        rc = 1;\n      }\n      clearYMD_HMS_TZ(p);\n      break;\n    }\n    default: {\n      break;\n    }\n  }\n  return rc;\n}\n\n/*\n** Process time function arguments.  argv[0] is a date-time stamp.\n** argv[1] and following are modifiers.  Parse them all and write\n** the resulting time into the DateTime structure p.  Return 0\n** on success and 1 if there are any errors.\n**\n** If there are zero parameters (if even argv[0] is undefined)\n** then assume a default value of \"now\" for argv[0].\n*/\nstatic int isDate(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv, \n  DateTime *p\n){\n  int i;\n  const unsigned char *z;\n  int eType;\n  memset(p, 0, sizeof(*p));\n  if( argc==0 ){\n    return setDateTimeToCurrent(context, p);\n  }\n  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT\n                   || eType==SQLITE_INTEGER ){\n    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);\n    p->validJD = 1;\n  }else{\n    z = sqlite3_value_text(argv[0]);\n    if( !z || parseDateOrTime(context, (char*)z, p) ){\n      return 1;\n    }\n  }\n  for(i=1; i<argc; i++){\n    z = sqlite3_value_text(argv[i]);\n    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;\n  }\n  return 0;\n}\n\n\n/*\n** The following routines implement the various date and time functions\n** of SQLite.\n*/\n\n/*\n**    julianday( TIMESTRING, MOD, MOD, ...)\n**\n** Return the julian day number of the date specified in the arguments\n*/\nstatic void juliandayFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    computeJD(&x);\n    sqlite3_result_double(context, x.iJD/86400000.0);\n  }\n}\n\n/*\n**    datetime( TIMESTRING, MOD, MOD, ...)\n**\n** Return YYYY-MM-DD HH:MM:SS\n*/\nstatic void datetimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeYMD_HMS(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%04d-%02d-%02d %02d:%02d:%02d\",\n                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    time( TIMESTRING, MOD, MOD, ...)\n**\n** Return HH:MM:SS\n*/\nstatic void timeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeHMS(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%02d:%02d:%02d\", x.h, x.m, (int)x.s);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    date( TIMESTRING, MOD, MOD, ...)\n**\n** Return YYYY-MM-DD\n*/\nstatic void dateFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  if( isDate(context, argc, argv, &x)==0 ){\n    char zBuf[100];\n    computeYMD(&x);\n    sqlite3_snprintf(sizeof(zBuf), zBuf, \"%04d-%02d-%02d\", x.Y, x.M, x.D);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)\n**\n** Return a string described by FORMAT.  Conversions as follows:\n**\n**   %d  day of month\n**   %f  ** fractional seconds  SS.SSS\n**   %H  hour 00-24\n**   %j  day of year 000-366\n**   %J  ** Julian day number\n**   %m  month 01-12\n**   %M  minute 00-59\n**   %s  seconds since 1970-01-01\n**   %S  seconds 00-59\n**   %w  day of week 0-6  sunday==0\n**   %W  week of year 00-53\n**   %Y  year 0000-9999\n**   %%  %\n*/\nstatic void strftimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  DateTime x;\n  u64 n;\n  size_t i,j;\n  char *z;\n  sqlite3 *db;\n  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);\n  char zBuf[100];\n  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;\n  db = sqlite3_context_db_handle(context);\n  for(i=0, n=1; zFmt[i]; i++, n++){\n    if( zFmt[i]=='%' ){\n      switch( zFmt[i+1] ){\n        case 'd':\n        case 'H':\n        case 'm':\n        case 'M':\n        case 'S':\n        case 'W':\n          n++;\n          /* fall thru */\n        case 'w':\n        case '%':\n          break;\n        case 'f':\n          n += 8;\n          break;\n        case 'j':\n          n += 3;\n          break;\n        case 'Y':\n          n += 8;\n          break;\n        case 's':\n        case 'J':\n          n += 50;\n          break;\n        default:\n          return;  /* ERROR.  return a NULL */\n      }\n      i++;\n    }\n  }\n  testcase( n==sizeof(zBuf)-1 );\n  testcase( n==sizeof(zBuf) );\n  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );\n  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );\n  if( n<sizeof(zBuf) ){\n    z = zBuf;\n  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    sqlite3_result_error_toobig(context);\n    return;\n  }else{\n    z = sqlite3DbMallocRaw(db, (int)n);\n    if( z==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n  }\n  computeJD(&x);\n  computeYMD_HMS(&x);\n  for(i=j=0; zFmt[i]; i++){\n    if( zFmt[i]!='%' ){\n      z[j++] = zFmt[i];\n    }else{\n      i++;\n      switch( zFmt[i] ){\n        case 'd':  sqlite3_snprintf(3, &z[j],\"%02d\",x.D); j+=2; break;\n        case 'f': {\n          double s = x.s;\n          if( s>59.999 ) s = 59.999;\n          sqlite3_snprintf(7, &z[j],\"%06.3f\", s);\n          j += sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'H':  sqlite3_snprintf(3, &z[j],\"%02d\",x.h); j+=2; break;\n        case 'W': /* Fall thru */\n        case 'j': {\n          int nDay;             /* Number of days since 1st day of year */\n          DateTime y = x;\n          y.validJD = 0;\n          y.M = 1;\n          y.D = 1;\n          computeJD(&y);\n          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);\n          if( zFmt[i]=='W' ){\n            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */\n            wd = (int)(((x.iJD+43200000)/86400000)%7);\n            sqlite3_snprintf(3, &z[j],\"%02d\",(nDay+7-wd)/7);\n            j += 2;\n          }else{\n            sqlite3_snprintf(4, &z[j],\"%03d\",nDay+1);\n            j += 3;\n          }\n          break;\n        }\n        case 'J': {\n          sqlite3_snprintf(20, &z[j],\"%.16g\",x.iJD/86400000.0);\n          j+=sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'm':  sqlite3_snprintf(3, &z[j],\"%02d\",x.M); j+=2; break;\n        case 'M':  sqlite3_snprintf(3, &z[j],\"%02d\",x.m); j+=2; break;\n        case 's': {\n          sqlite3_snprintf(30,&z[j],\"%lld\",\n                           (i64)(x.iJD/1000 - 21086676*(i64)10000));\n          j += sqlite3Strlen30(&z[j]);\n          break;\n        }\n        case 'S':  sqlite3_snprintf(3,&z[j],\"%02d\",(int)x.s); j+=2; break;\n        case 'w': {\n          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';\n          break;\n        }\n        case 'Y': {\n          sqlite3_snprintf(5,&z[j],\"%04d\",x.Y); j+=sqlite3Strlen30(&z[j]);\n          break;\n        }\n        default:   z[j++] = '%'; break;\n      }\n    }\n  }\n  z[j] = 0;\n  sqlite3_result_text(context, z, -1,\n                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);\n}\n\n/*\n** current_time()\n**\n** This function returns the same value as time('now').\n*/\nstatic void ctimeFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  timeFunc(context, 0, 0);\n}\n\n/*\n** current_date()\n**\n** This function returns the same value as date('now').\n*/\nstatic void cdateFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  dateFunc(context, 0, 0);\n}\n\n/*\n** current_timestamp()\n**\n** This function returns the same value as datetime('now').\n*/\nstatic void ctimestampFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  datetimeFunc(context, 0, 0);\n}\n#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */\n\n#ifdef SQLITE_OMIT_DATETIME_FUNCS\n/*\n** If the library is compiled to omit the full-scale date and time\n** handling (to get a smaller binary), the following minimal version\n** of the functions current_time(), current_date() and current_timestamp()\n** are included instead. This is to support column declarations that\n** include \"DEFAULT CURRENT_TIME\" etc.\n**\n** This function uses the C-library functions time(), gmtime()\n** and strftime(). The format string to pass to strftime() is supplied\n** as the user-data for the function.\n*/\nstatic void currentTimeFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  time_t t;\n  char *zFormat = (char *)sqlite3_user_data(context);\n  sqlite3 *db;\n  sqlite3_int64 iT;\n  struct tm *pTm;\n  struct tm sNow;\n  char zBuf[20];\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  db = sqlite3_context_db_handle(context);\n  if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;\n  t = iT/1000 - 10000*(sqlite3_int64)21086676;\n#ifdef HAVE_GMTIME_R\n  pTm = gmtime_r(&t, &sNow);\n#else\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n  pTm = gmtime(&t);\n  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n#endif\n  if( pTm ){\n    strftime(zBuf, 20, zFormat, &sNow);\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n  }\n}\n#endif\n\n/*\n** This function registered all of the above C functions as SQL\n** functions.  This should be the only routine in this file with\n** external linkage.\n*/\nSQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){\n  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {\n#ifndef SQLITE_OMIT_DATETIME_FUNCS\n    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),\n    FUNCTION(date,             -1, 0, 0, dateFunc      ),\n    FUNCTION(time,             -1, 0, 0, timeFunc      ),\n    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),\n    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),\n    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),\n    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),\n    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),\n#else\n    STR_FUNCTION(current_time,      0, \"%H:%M:%S\",          0, currentTimeFunc),\n    STR_FUNCTION(current_date,      0, \"%Y-%m-%d\",          0, currentTimeFunc),\n    STR_FUNCTION(current_timestamp, 0, \"%Y-%m-%d %H:%M:%S\", 0, currentTimeFunc),\n#endif\n  };\n  int i;\n  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);\n  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);\n\n  for(i=0; i<ArraySize(aDateTimeFuncs); i++){\n    sqlite3FuncDefInsert(pHash, &aFunc[i]);\n  }\n}\n\n/************** End of date.c ************************************************/\n/************** Begin file os.c **********************************************/\n/*\n** 2005 November 29\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains OS interface code that is common to all\n** architectures.\n*/\n#define _SQLITE_OS_C_ 1\n#undef _SQLITE_OS_C_\n\n/*\n** The default SQLite sqlite3_vfs implementations do not allocate\n** memory (actually, os_unix.c allocates a small amount of memory\n** from within OsOpen()), but some third-party implementations may.\n** So we test the effects of a malloc() failing and the sqlite3OsXXX()\n** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.\n**\n** The following functions are instrumented for malloc() failure \n** testing:\n**\n**     sqlite3OsRead()\n**     sqlite3OsWrite()\n**     sqlite3OsSync()\n**     sqlite3OsFileSize()\n**     sqlite3OsLock()\n**     sqlite3OsCheckReservedLock()\n**     sqlite3OsFileControl()\n**     sqlite3OsShmMap()\n**     sqlite3OsOpen()\n**     sqlite3OsDelete()\n**     sqlite3OsAccess()\n**     sqlite3OsFullPathname()\n**\n*/\n#if defined(SQLITE_TEST)\nSQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;\n  #define DO_OS_MALLOC_TEST(x)                                       \\\n  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \\\n    void *pTstAlloc = sqlite3Malloc(10);                             \\\n    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \\\n    sqlite3_free(pTstAlloc);                                         \\\n  }\n#else\n  #define DO_OS_MALLOC_TEST(x)\n#endif\n\n/*\n** The following routines are convenience wrappers around methods\n** of the sqlite3_file object.  This is mostly just syntactic sugar. All\n** of this would be completely automatic if SQLite were coded using\n** C++ instead of plain old C.\n*/\nSQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){\n  int rc = SQLITE_OK;\n  if( pId->pMethods ){\n    rc = pId->pMethods->xClose(pId);\n    pId->pMethods = 0;\n  }\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xRead(id, pBuf, amt, offset);\n}\nSQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xWrite(id, pBuf, amt, offset);\n}\nSQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){\n  return id->pMethods->xTruncate(id, size);\n}\nSQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xSync(id, flags);\n}\nSQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xFileSize(id, pSize);\n}\nSQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xLock(id, lockType);\n}\nSQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){\n  return id->pMethods->xUnlock(id, lockType);\n}\nSQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xCheckReservedLock(id, pResOut);\n}\n\n/*\n** Use sqlite3OsFileControl() when we are doing something that might fail\n** and we need to know about the failures.  Use sqlite3OsFileControlHint()\n** when simply tossing information over the wall to the VFS and we do not\n** really care if the VFS receives and understands the information since it\n** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()\n** routine has no return value since the return value would be meaningless.\n*/\nSQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xFileControl(id, op, pArg);\n}\nSQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){\n  (void)id->pMethods->xFileControl(id, op, pArg);\n}\n\nSQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){\n  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;\n  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);\n}\nSQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){\n  return id->pMethods->xDeviceCharacteristics(id);\n}\nSQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){\n  return id->pMethods->xShmLock(id, offset, n, flags);\n}\nSQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){\n  id->pMethods->xShmBarrier(id);\n}\nSQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){\n  return id->pMethods->xShmUnmap(id, deleteFlag);\n}\nSQLITE_PRIVATE int sqlite3OsShmMap(\n  sqlite3_file *id,               /* Database file handle */\n  int iPage,\n  int pgsz,\n  int bExtend,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Pointer to mapping */\n){\n  DO_OS_MALLOC_TEST(id);\n  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);\n}\n\n/*\n** The next group of routines are convenience wrappers around the\n** VFS methods.\n*/\nSQLITE_PRIVATE int sqlite3OsOpen(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  sqlite3_file *pFile, \n  int flags, \n  int *pFlagsOut\n){\n  int rc;\n  DO_OS_MALLOC_TEST(0);\n  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed\n  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,\n  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before\n  ** reaching the VFS. */\n  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);\n  assert( rc==SQLITE_OK || pFile->pMethods==0 );\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){\n  DO_OS_MALLOC_TEST(0);\n  assert( dirSync==0 || dirSync==1 );\n  return pVfs->xDelete(pVfs, zPath, dirSync);\n}\nSQLITE_PRIVATE int sqlite3OsAccess(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int flags, \n  int *pResOut\n){\n  DO_OS_MALLOC_TEST(0);\n  return pVfs->xAccess(pVfs, zPath, flags, pResOut);\n}\nSQLITE_PRIVATE int sqlite3OsFullPathname(\n  sqlite3_vfs *pVfs, \n  const char *zPath, \n  int nPathOut, \n  char *zPathOut\n){\n  DO_OS_MALLOC_TEST(0);\n  zPathOut[0] = 0;\n  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);\n}\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\nSQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){\n  return pVfs->xDlOpen(pVfs, zPath);\n}\nSQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  pVfs->xDlError(pVfs, nByte, zBufOut);\n}\nSQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){\n  return pVfs->xDlSym(pVfs, pHdle, zSym);\n}\nSQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  pVfs->xDlClose(pVfs, pHandle);\n}\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\nSQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){\n  return pVfs->xRandomness(pVfs, nByte, zBufOut);\n}\nSQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){\n  return pVfs->xSleep(pVfs, nMicro);\n}\nSQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){\n  int rc;\n  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()\n  ** method to get the current date and time if that method is available\n  ** (if iVersion is 2 or greater and the function pointer is not NULL) and\n  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is\n  ** unavailable.\n  */\n  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){\n    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);\n  }else{\n    double r;\n    rc = pVfs->xCurrentTime(pVfs, &r);\n    *pTimeOut = (sqlite3_int64)(r*86400000.0);\n  }\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3OsOpenMalloc(\n  sqlite3_vfs *pVfs, \n  const char *zFile, \n  sqlite3_file **ppFile, \n  int flags,\n  int *pOutFlags\n){\n  int rc = SQLITE_NOMEM;\n  sqlite3_file *pFile;\n  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);\n  if( pFile ){\n    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);\n    if( rc!=SQLITE_OK ){\n      sqlite3_free(pFile);\n    }else{\n      *ppFile = pFile;\n    }\n  }\n  return rc;\n}\nSQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){\n  int rc = SQLITE_OK;\n  assert( pFile );\n  rc = sqlite3OsClose(pFile);\n  sqlite3_free(pFile);\n  return rc;\n}\n\n/*\n** This function is a wrapper around the OS specific implementation of\n** sqlite3_os_init(). The purpose of the wrapper is to provide the\n** ability to simulate a malloc failure, so that the handling of an\n** error in sqlite3_os_init() by the upper layers can be tested.\n*/\nSQLITE_PRIVATE int sqlite3OsInit(void){\n  void *p = sqlite3_malloc(10);\n  if( p==0 ) return SQLITE_NOMEM;\n  sqlite3_free(p);\n  return sqlite3_os_init();\n}\n\n/*\n** The list of all registered VFS implementations.\n*/\nstatic sqlite3_vfs * SQLITE_WSD vfsList = 0;\n#define vfsList GLOBAL(sqlite3_vfs *, vfsList)\n\n/*\n** Locate a VFS by name.  If no name is given, simply return the\n** first VFS on the list.\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){\n  sqlite3_vfs *pVfs = 0;\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex;\n#endif\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return 0;\n#endif\n#if SQLITE_THREADSAFE\n  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  sqlite3_mutex_enter(mutex);\n  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){\n    if( zVfs==0 ) break;\n    if( strcmp(zVfs, pVfs->zName)==0 ) break;\n  }\n  sqlite3_mutex_leave(mutex);\n  return pVfs;\n}\n\n/*\n** Unlink a VFS from the linked list\n*/\nstatic void vfsUnlink(sqlite3_vfs *pVfs){\n  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );\n  if( pVfs==0 ){\n    /* No-op */\n  }else if( vfsList==pVfs ){\n    vfsList = pVfs->pNext;\n  }else if( vfsList ){\n    sqlite3_vfs *p = vfsList;\n    while( p->pNext && p->pNext!=pVfs ){\n      p = p->pNext;\n    }\n    if( p->pNext==pVfs ){\n      p->pNext = pVfs->pNext;\n    }\n  }\n}\n\n/*\n** Register a VFS with the system.  It is harmless to register the same\n** VFS multiple times.  The new VFS becomes the default if makeDflt is\n** true.\n*/\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){\n  MUTEX_LOGIC(sqlite3_mutex *mutex;)\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(mutex);\n  vfsUnlink(pVfs);\n  if( makeDflt || vfsList==0 ){\n    pVfs->pNext = vfsList;\n    vfsList = pVfs;\n  }else{\n    pVfs->pNext = vfsList->pNext;\n    vfsList->pNext = pVfs;\n  }\n  assert(vfsList);\n  sqlite3_mutex_leave(mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Unregister a VFS so that it is no longer accessible.\n*/\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n  sqlite3_mutex_enter(mutex);\n  vfsUnlink(pVfs);\n  sqlite3_mutex_leave(mutex);\n  return SQLITE_OK;\n}\n\n/************** End of os.c **************************************************/\n/************** Begin file fault.c *******************************************/\n/*\n** 2008 Jan 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code to support the concept of \"benign\" \n** malloc failures (when the xMalloc() or xRealloc() method of the\n** sqlite3_mem_methods structure fails to allocate a block of memory\n** and returns 0). \n**\n** Most malloc failures are non-benign. After they occur, SQLite\n** abandons the current operation and returns an error code (usually\n** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily\n** fatal. For example, if a malloc fails while resizing a hash table, this \n** is completely recoverable simply by not carrying out the resize. The \n** hash table will continue to function normally.  So a malloc failure \n** during a hash table resize is a benign fault.\n*/\n\n\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n\n/*\n** Global variables.\n*/\ntypedef struct BenignMallocHooks BenignMallocHooks;\nstatic SQLITE_WSD struct BenignMallocHooks {\n  void (*xBenignBegin)(void);\n  void (*xBenignEnd)(void);\n} sqlite3Hooks = { 0, 0 };\n\n/* The \"wsdHooks\" macro will resolve to the appropriate BenignMallocHooks\n** structure.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdHooks can refer directly\n** to the \"sqlite3Hooks\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdHooksInit \\\n  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)\n# define wsdHooks x[0]\n#else\n# define wsdHooksInit\n# define wsdHooks sqlite3Hooks\n#endif\n\n\n/*\n** Register hooks to call when sqlite3BeginBenignMalloc() and\n** sqlite3EndBenignMalloc() are called, respectively.\n*/\nSQLITE_PRIVATE void sqlite3BenignMallocHooks(\n  void (*xBenignBegin)(void),\n  void (*xBenignEnd)(void)\n){\n  wsdHooksInit;\n  wsdHooks.xBenignBegin = xBenignBegin;\n  wsdHooks.xBenignEnd = xBenignEnd;\n}\n\n/*\n** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that\n** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()\n** indicates that subsequent malloc failures are non-benign.\n*/\nSQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){\n  wsdHooksInit;\n  if( wsdHooks.xBenignBegin ){\n    wsdHooks.xBenignBegin();\n  }\n}\nSQLITE_PRIVATE void sqlite3EndBenignMalloc(void){\n  wsdHooksInit;\n  if( wsdHooks.xBenignEnd ){\n    wsdHooks.xBenignEnd();\n  }\n}\n\n#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */\n\n/************** End of fault.c ***********************************************/\n/************** Begin file mem0.c ********************************************/\n/*\n** 2008 October 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains a no-op memory allocation drivers for use when\n** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented\n** here always fail.  SQLite will not operate with these drivers.  These\n** are merely placeholders.  Real drivers must be substituted using\n** sqlite3_config() before SQLite will operate.\n*/\n\n/*\n** This version of the memory allocator is the default.  It is\n** used when no other memory allocator is specified using compile-time\n** macros.\n*/\n#ifdef SQLITE_ZERO_MALLOC\n\n/*\n** No-op versions of all memory allocation routines\n*/\nstatic void *sqlite3MemMalloc(int nByte){ return 0; }\nstatic void sqlite3MemFree(void *pPrior){ return; }\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }\nstatic int sqlite3MemSize(void *pPrior){ return 0; }\nstatic int sqlite3MemRoundup(int n){ return n; }\nstatic int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }\nstatic void sqlite3MemShutdown(void *NotUsed){ return; }\n\n/*\n** This routine is the only routine in this file with external linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n#endif /* SQLITE_ZERO_MALLOC */\n\n/************** End of mem0.c ************************************************/\n/************** Begin file mem1.c ********************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains low-level memory allocation drivers for when\n** SQLite will use the standard C-library malloc/realloc/free interface\n** to obtain the memory it needs.\n**\n** This file contains implementations of the low-level memory allocation\n** routines specified in the sqlite3_mem_methods object.  The content of\n** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The\n** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the\n** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The\n** default configuration is to use memory allocation routines in this\n** file.\n**\n** C-preprocessor macro summary:\n**\n**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if\n**                                the malloc_usable_size() interface exists\n**                                on the target platform.  Or, this symbol\n**                                can be set manually, if desired.\n**                                If an equivalent interface exists by\n**                                a different name, using a separate -D\n**                                option to rename it.\n**\n**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone\n**                                memory allocator.  Set this symbol to enable\n**                                building on older macs.\n**\n**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of\n**                                _msize() on windows systems.  This might\n**                                be necessary when compiling for Delphi,\n**                                for example.\n*/\n\n/*\n** This version of the memory allocator is the default.  It is\n** used when no other memory allocator is specified using compile-time\n** macros.\n*/\n#ifdef SQLITE_SYSTEM_MALLOC\n\n/*\n** The MSVCRT has malloc_usable_size() but it is called _msize().\n** The use of _msize() is automatic, but can be disabled by compiling\n** with -DSQLITE_WITHOUT_MSIZE\n*/\n#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)\n# define SQLITE_MALLOCSIZE _msize\n#endif\n\n#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)\n\n/*\n** Use the zone allocator available on apple products unless the\n** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.\n*/\n#include <sys/sysctl.h>\n#include <malloc/malloc.h>\n#include <libkern/OSAtomic.h>\nstatic malloc_zone_t* _sqliteZone_;\n#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))\n#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));\n#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))\n#define SQLITE_MALLOCSIZE(x) \\\n        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))\n\n#else /* if not __APPLE__ */\n\n/*\n** Use standard C library malloc and free on non-Apple systems.  \n** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.\n*/\n#define SQLITE_MALLOC(x)    malloc(x)\n#define SQLITE_FREE(x)      free(x)\n#define SQLITE_REALLOC(x,y) realloc((x),(y))\n\n#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \\\n      || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))\n# include <malloc.h>    /* Needed for malloc_usable_size on linux */\n#endif\n#ifdef HAVE_MALLOC_USABLE_SIZE\n# ifndef SQLITE_MALLOCSIZE\n#  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)\n# endif\n#else\n# undef SQLITE_MALLOCSIZE\n#endif\n\n#endif /* __APPLE__ or not __APPLE__ */\n\n/*\n** Like malloc(), but remember the size of the allocation\n** so that we can find it later using sqlite3MemSize().\n**\n** For this low-level routine, we are guaranteed that nByte>0 because\n** cases of nByte<=0 will be intercepted and dealt with by higher level\n** routines.\n*/\nstatic void *sqlite3MemMalloc(int nByte){\n#ifdef SQLITE_MALLOCSIZE\n  void *p = SQLITE_MALLOC( nByte );\n  if( p==0 ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes of memory\", nByte);\n  }\n  return p;\n#else\n  sqlite3_int64 *p;\n  assert( nByte>0 );\n  nByte = ROUND8(nByte);\n  p = SQLITE_MALLOC( nByte+8 );\n  if( p ){\n    p[0] = nByte;\n    p++;\n  }else{\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes of memory\", nByte);\n  }\n  return (void *)p;\n#endif\n}\n\n/*\n** Like free() but works for allocations obtained from sqlite3MemMalloc()\n** or sqlite3MemRealloc().\n**\n** For this low-level routine, we already know that pPrior!=0 since\n** cases where pPrior==0 will have been intecepted and dealt with\n** by higher-level routines.\n*/\nstatic void sqlite3MemFree(void *pPrior){\n#ifdef SQLITE_MALLOCSIZE\n  SQLITE_FREE(pPrior);\n#else\n  sqlite3_int64 *p = (sqlite3_int64*)pPrior;\n  assert( pPrior!=0 );\n  p--;\n  SQLITE_FREE(p);\n#endif\n}\n\n/*\n** Report the allocated size of a prior return from xMalloc()\n** or xRealloc().\n*/\nstatic int sqlite3MemSize(void *pPrior){\n#ifdef SQLITE_MALLOCSIZE\n  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;\n#else\n  sqlite3_int64 *p;\n  if( pPrior==0 ) return 0;\n  p = (sqlite3_int64*)pPrior;\n  p--;\n  return (int)p[0];\n#endif\n}\n\n/*\n** Like realloc().  Resize an allocation previously obtained from\n** sqlite3MemMalloc().\n**\n** For this low-level interface, we know that pPrior!=0.  Cases where\n** pPrior==0 while have been intercepted by higher-level routine and\n** redirected to xMalloc.  Similarly, we know that nByte>0 becauses\n** cases where nByte<=0 will have been intercepted by higher-level\n** routines and redirected to xFree.\n*/\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){\n#ifdef SQLITE_MALLOCSIZE\n  void *p = SQLITE_REALLOC(pPrior, nByte);\n  if( p==0 ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM,\n      \"failed memory resize %u to %u bytes\",\n      SQLITE_MALLOCSIZE(pPrior), nByte);\n  }\n  return p;\n#else\n  sqlite3_int64 *p = (sqlite3_int64*)pPrior;\n  assert( pPrior!=0 && nByte>0 );\n  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */\n  p--;\n  p = SQLITE_REALLOC(p, nByte+8 );\n  if( p ){\n    p[0] = nByte;\n    p++;\n  }else{\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM,\n      \"failed memory resize %u to %u bytes\",\n      sqlite3MemSize(pPrior), nByte);\n  }\n  return (void*)p;\n#endif\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int sqlite3MemRoundup(int n){\n  return ROUND8(n);\n}\n\n/*\n** Initialize this module.\n*/\nstatic int sqlite3MemInit(void *NotUsed){\n#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)\n  int cpuCount;\n  size_t len;\n  if( _sqliteZone_ ){\n    return SQLITE_OK;\n  }\n  len = sizeof(cpuCount);\n  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */\n  sysctlbyname(\"hw.ncpu\", &cpuCount, &len, NULL, 0);\n  if( cpuCount>1 ){\n    /* defer MT decisions to system malloc */\n    _sqliteZone_ = malloc_default_zone();\n  }else{\n    /* only 1 core, use our own zone to contention over global locks, \n    ** e.g. we have our own dedicated locks */\n    bool success;\n    malloc_zone_t* newzone = malloc_create_zone(4096, 0);\n    malloc_set_zone_name(newzone, \"Sqlite_Heap\");\n    do{\n      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, \n                                 (void * volatile *)&_sqliteZone_);\n    }while(!_sqliteZone_);\n    if( !success ){\n      /* somebody registered a zone first */\n      malloc_destroy_zone(newzone);\n    }\n  }\n#endif\n  UNUSED_PARAMETER(NotUsed);\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void sqlite3MemShutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  return;\n}\n\n/*\n** This routine is the only routine in this file with external linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n#endif /* SQLITE_SYSTEM_MALLOC */\n\n/************** End of mem1.c ************************************************/\n/************** Begin file mem2.c ********************************************/\n/*\n** 2007 August 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains low-level memory allocation drivers for when\n** SQLite will use the standard C-library malloc/realloc/free interface\n** to obtain the memory it needs while adding lots of additional debugging\n** information to each allocation in order to help detect and fix memory\n** leaks and memory usage errors.\n**\n** This file contains implementations of the low-level memory allocation\n** routines specified in the sqlite3_mem_methods object.\n*/\n\n/*\n** This version of the memory allocator is used only if the\n** SQLITE_MEMDEBUG macro is defined\n*/\n#ifdef SQLITE_MEMDEBUG\n\n/*\n** The backtrace functionality is only available with GLIBC\n*/\n#ifdef __GLIBC__\n  extern int backtrace(void**,int);\n  extern void backtrace_symbols_fd(void*const*,int,int);\n#else\n# define backtrace(A,B) 1\n# define backtrace_symbols_fd(A,B,C)\n#endif\n/* #include <stdio.h> */\n\n/*\n** Each memory allocation looks like this:\n**\n**  ------------------------------------------------------------------------\n**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |\n**  ------------------------------------------------------------------------\n**\n** The application code sees only a pointer to the allocation.  We have\n** to back up from the allocation pointer to find the MemBlockHdr.  The\n** MemBlockHdr tells us the size of the allocation and the number of\n** backtrace pointers.  There is also a guard word at the end of the\n** MemBlockHdr.\n*/\nstruct MemBlockHdr {\n  i64 iSize;                          /* Size of this allocation */\n  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */\n  char nBacktrace;                    /* Number of backtraces on this alloc */\n  char nBacktraceSlots;               /* Available backtrace slots */\n  u8 nTitle;                          /* Bytes of title; includes '\\0' */\n  u8 eType;                           /* Allocation type code */\n  int iForeGuard;                     /* Guard word for sanity */\n};\n\n/*\n** Guard words\n*/\n#define FOREGUARD 0x80F5E153\n#define REARGUARD 0xE4676B53\n\n/*\n** Number of malloc size increments to track.\n*/\n#define NCSIZE  1000\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic struct {\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n\n  /*\n  ** Head and tail of a linked list of all outstanding allocations\n  */\n  struct MemBlockHdr *pFirst;\n  struct MemBlockHdr *pLast;\n  \n  /*\n  ** The number of levels of backtrace to save in new allocations.\n  */\n  int nBacktrace;\n  void (*xBacktrace)(int, int, void **);\n\n  /*\n  ** Title text to insert in front of each block\n  */\n  int nTitle;        /* Bytes of zTitle to save.  Includes '\\0' and padding */\n  char zTitle[100];  /* The title text */\n\n  /* \n  ** sqlite3MallocDisallow() increments the following counter.\n  ** sqlite3MallocAllow() decrements it.\n  */\n  int disallow; /* Do not allow memory allocation */\n\n  /*\n  ** Gather statistics on the sizes of memory allocations.\n  ** nAlloc[i] is the number of allocation attempts of i*8\n  ** bytes.  i==NCSIZE is the number of allocation attempts for\n  ** sizes more than NCSIZE*8 bytes.\n  */\n  int nAlloc[NCSIZE];      /* Total number of allocations */\n  int nCurrent[NCSIZE];    /* Current number of allocations */\n  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */\n\n} mem;\n\n\n/*\n** Adjust memory usage statistics\n*/\nstatic void adjustStats(int iSize, int increment){\n  int i = ROUND8(iSize)/8;\n  if( i>NCSIZE-1 ){\n    i = NCSIZE - 1;\n  }\n  if( increment>0 ){\n    mem.nAlloc[i]++;\n    mem.nCurrent[i]++;\n    if( mem.nCurrent[i]>mem.mxCurrent[i] ){\n      mem.mxCurrent[i] = mem.nCurrent[i];\n    }\n  }else{\n    mem.nCurrent[i]--;\n    assert( mem.nCurrent[i]>=0 );\n  }\n}\n\n/*\n** Given an allocation, find the MemBlockHdr for that allocation.\n**\n** This routine checks the guards at either end of the allocation and\n** if they are incorrect it asserts.\n*/\nstatic struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){\n  struct MemBlockHdr *p;\n  int *pInt;\n  u8 *pU8;\n  int nReserve;\n\n  p = (struct MemBlockHdr*)pAllocation;\n  p--;\n  assert( p->iForeGuard==(int)FOREGUARD );\n  nReserve = ROUND8(p->iSize);\n  pInt = (int*)pAllocation;\n  pU8 = (u8*)pAllocation;\n  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );\n  /* This checks any of the \"extra\" bytes allocated due\n  ** to rounding up to an 8 byte boundary to ensure \n  ** they haven't been overwritten.\n  */\n  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );\n  return p;\n}\n\n/*\n** Return the number of bytes currently allocated at address p.\n*/\nstatic int sqlite3MemSize(void *p){\n  struct MemBlockHdr *pHdr;\n  if( !p ){\n    return 0;\n  }\n  pHdr = sqlite3MemsysGetHeader(p);\n  return pHdr->iSize;\n}\n\n/*\n** Initialize the memory allocation subsystem.\n*/\nstatic int sqlite3MemInit(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( (sizeof(struct MemBlockHdr)&7) == 0 );\n  if( !sqlite3GlobalConfig.bMemstat ){\n    /* If memory status is enabled, then the malloc.c wrapper will already\n    ** hold the STATIC_MEM mutex when the routines here are invoked. */\n    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize the memory allocation subsystem.\n*/\nstatic void sqlite3MemShutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem.mutex = 0;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int sqlite3MemRoundup(int n){\n  return ROUND8(n);\n}\n\n/*\n** Fill a buffer with pseudo-random bytes.  This is used to preset\n** the content of a new memory allocation to unpredictable values and\n** to clear the content of a freed allocation to unpredictable values.\n*/\nstatic void randomFill(char *pBuf, int nByte){\n  unsigned int x, y, r;\n  x = SQLITE_PTR_TO_INT(pBuf);\n  y = nByte | 1;\n  while( nByte >= 4 ){\n    x = (x>>1) ^ (-(x&1) & 0xd0000001);\n    y = y*1103515245 + 12345;\n    r = x ^ y;\n    *(int*)pBuf = r;\n    pBuf += 4;\n    nByte -= 4;\n  }\n  while( nByte-- > 0 ){\n    x = (x>>1) ^ (-(x&1) & 0xd0000001);\n    y = y*1103515245 + 12345;\n    r = x ^ y;\n    *(pBuf++) = r & 0xff;\n  }\n}\n\n/*\n** Allocate nByte bytes of memory.\n*/\nstatic void *sqlite3MemMalloc(int nByte){\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  char *z;\n  int *pInt;\n  void *p = 0;\n  int totalSize;\n  int nReserve;\n  sqlite3_mutex_enter(mem.mutex);\n  assert( mem.disallow==0 );\n  nReserve = ROUND8(nByte);\n  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +\n               mem.nBacktrace*sizeof(void*) + mem.nTitle;\n  p = malloc(totalSize);\n  if( p ){\n    z = p;\n    pBt = (void**)&z[mem.nTitle];\n    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];\n    pHdr->pNext = 0;\n    pHdr->pPrev = mem.pLast;\n    if( mem.pLast ){\n      mem.pLast->pNext = pHdr;\n    }else{\n      mem.pFirst = pHdr;\n    }\n    mem.pLast = pHdr;\n    pHdr->iForeGuard = FOREGUARD;\n    pHdr->eType = MEMTYPE_HEAP;\n    pHdr->nBacktraceSlots = mem.nBacktrace;\n    pHdr->nTitle = mem.nTitle;\n    if( mem.nBacktrace ){\n      void *aAddr[40];\n      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;\n      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));\n      assert(pBt[0]);\n      if( mem.xBacktrace ){\n        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);\n      }\n    }else{\n      pHdr->nBacktrace = 0;\n    }\n    if( mem.nTitle ){\n      memcpy(z, mem.zTitle, mem.nTitle);\n    }\n    pHdr->iSize = nByte;\n    adjustStats(nByte, +1);\n    pInt = (int*)&pHdr[1];\n    pInt[nReserve/sizeof(int)] = REARGUARD;\n    randomFill((char*)pInt, nByte);\n    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);\n    p = (void*)pInt;\n  }\n  sqlite3_mutex_leave(mem.mutex);\n  return p; \n}\n\n/*\n** Free memory.\n*/\nstatic void sqlite3MemFree(void *pPrior){\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  char *z;\n  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 \n       || mem.mutex!=0 );\n  pHdr = sqlite3MemsysGetHeader(pPrior);\n  pBt = (void**)pHdr;\n  pBt -= pHdr->nBacktraceSlots;\n  sqlite3_mutex_enter(mem.mutex);\n  if( pHdr->pPrev ){\n    assert( pHdr->pPrev->pNext==pHdr );\n    pHdr->pPrev->pNext = pHdr->pNext;\n  }else{\n    assert( mem.pFirst==pHdr );\n    mem.pFirst = pHdr->pNext;\n  }\n  if( pHdr->pNext ){\n    assert( pHdr->pNext->pPrev==pHdr );\n    pHdr->pNext->pPrev = pHdr->pPrev;\n  }else{\n    assert( mem.pLast==pHdr );\n    mem.pLast = pHdr->pPrev;\n  }\n  z = (char*)pBt;\n  z -= pHdr->nTitle;\n  adjustStats(pHdr->iSize, -1);\n  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +\n                pHdr->iSize + sizeof(int) + pHdr->nTitle);\n  free(z);\n  sqlite3_mutex_leave(mem.mutex);  \n}\n\n/*\n** Change the size of an existing memory allocation.\n**\n** For this debugging implementation, we *always* make a copy of the\n** allocation into a new place in memory.  In this way, if the \n** higher level code is using pointer to the old allocation, it is \n** much more likely to break and we are much more liking to find\n** the error.\n*/\nstatic void *sqlite3MemRealloc(void *pPrior, int nByte){\n  struct MemBlockHdr *pOldHdr;\n  void *pNew;\n  assert( mem.disallow==0 );\n  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */\n  pOldHdr = sqlite3MemsysGetHeader(pPrior);\n  pNew = sqlite3MemMalloc(nByte);\n  if( pNew ){\n    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);\n    if( nByte>pOldHdr->iSize ){\n      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);\n    }\n    sqlite3MemFree(pPrior);\n  }\n  return pNew;\n}\n\n/*\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file.\n*/\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  static const sqlite3_mem_methods defaultMethods = {\n     sqlite3MemMalloc,\n     sqlite3MemFree,\n     sqlite3MemRealloc,\n     sqlite3MemSize,\n     sqlite3MemRoundup,\n     sqlite3MemInit,\n     sqlite3MemShutdown,\n     0\n  };\n  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);\n}\n\n/*\n** Set the \"type\" of an allocation.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );\n    pHdr->eType = eType;\n  }\n}\n\n/*\n** Return TRUE if the mask of type in eType matches the type of the\n** allocation p.  Also return true if p==NULL.\n**\n** This routine is designed for use within an assert() statement, to\n** verify the type of an allocation.  For example:\n**\n**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );\n*/\nSQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){\n  int rc = 1;\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */\n    if( (pHdr->eType&eType)==0 ){\n      rc = 0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Return TRUE if the mask of type in eType matches no bits of the type of the\n** allocation p.  Also return true if p==NULL.\n**\n** This routine is designed for use within an assert() statement, to\n** verify the type of an allocation.  For example:\n**\n**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );\n*/\nSQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){\n  int rc = 1;\n  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){\n    struct MemBlockHdr *pHdr;\n    pHdr = sqlite3MemsysGetHeader(p);\n    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */\n    if( (pHdr->eType&eType)!=0 ){\n      rc = 0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Set the number of backtrace levels kept for each allocation.\n** A value of zero turns off backtracing.  The number is always rounded\n** up to a multiple of 2.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){\n  if( depth<0 ){ depth = 0; }\n  if( depth>20 ){ depth = 20; }\n  depth = (depth+1)&0xfe;\n  mem.nBacktrace = depth;\n}\n\nSQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){\n  mem.xBacktrace = xBacktrace;\n}\n\n/*\n** Set the title string for subsequent allocations.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){\n  unsigned int n = sqlite3Strlen30(zTitle) + 1;\n  sqlite3_mutex_enter(mem.mutex);\n  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;\n  memcpy(mem.zTitle, zTitle, n);\n  mem.zTitle[n] = 0;\n  mem.nTitle = ROUND8(n);\n  sqlite3_mutex_leave(mem.mutex);\n}\n\nSQLITE_PRIVATE void sqlite3MemdebugSync(){\n  struct MemBlockHdr *pHdr;\n  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){\n    void **pBt = (void**)pHdr;\n    pBt -= pHdr->nBacktraceSlots;\n    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);\n  }\n}\n\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){\n  FILE *out;\n  struct MemBlockHdr *pHdr;\n  void **pBt;\n  int i;\n  out = fopen(zFilename, \"w\");\n  if( out==0 ){\n    fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                    zFilename);\n    return;\n  }\n  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){\n    char *z = (char*)pHdr;\n    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;\n    fprintf(out, \"**** %lld bytes at %p from %s ****\\n\", \n            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : \"???\");\n    if( pHdr->nBacktrace ){\n      fflush(out);\n      pBt = (void**)pHdr;\n      pBt -= pHdr->nBacktraceSlots;\n      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));\n      fprintf(out, \"\\n\");\n    }\n  }\n  fprintf(out, \"COUNTS:\\n\");\n  for(i=0; i<NCSIZE-1; i++){\n    if( mem.nAlloc[i] ){\n      fprintf(out, \"   %5d: %10d %10d %10d\\n\", \n            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);\n    }\n  }\n  if( mem.nAlloc[NCSIZE-1] ){\n    fprintf(out, \"   %5d: %10d %10d %10d\\n\",\n             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],\n             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);\n  }\n  fclose(out);\n}\n\n/*\n** Return the number of times sqlite3MemMalloc() has been called.\n*/\nSQLITE_PRIVATE int sqlite3MemdebugMallocCount(){\n  int i;\n  int nTotal = 0;\n  for(i=0; i<NCSIZE; i++){\n    nTotal += mem.nAlloc[i];\n  }\n  return nTotal;\n}\n\n\n#endif /* SQLITE_MEMDEBUG */\n\n/************** End of mem2.c ************************************************/\n/************** Begin file mem3.c ********************************************/\n/*\n** 2007 October 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement a memory\n** allocation subsystem for use by SQLite. \n**\n** This version of the memory allocation subsystem omits all\n** use of malloc(). The SQLite user supplies a block of memory\n** before calling sqlite3_initialize() from which allocations\n** are made and returned by the xMalloc() and xRealloc() \n** implementations. Once sqlite3_initialize() has been called,\n** the amount of memory available to SQLite is fixed and cannot\n** be changed.\n**\n** This version of the memory allocation subsystem is included\n** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.\n*/\n\n/*\n** This version of the memory allocator is only built into the library\n** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not\n** mean that the library will use a memory-pool by default, just that\n** it is available. The mempool allocator is activated by calling\n** sqlite3_config().\n*/\n#ifdef SQLITE_ENABLE_MEMSYS3\n\n/*\n** Maximum size (in Mem3Blocks) of a \"small\" chunk.\n*/\n#define MX_SMALL 10\n\n\n/*\n** Number of freelist hash slots\n*/\n#define N_HASH  61\n\n/*\n** A memory allocation (also called a \"chunk\") consists of two or \n** more blocks where each block is 8 bytes.  The first 8 bytes are \n** a header that is not returned to the user.\n**\n** A chunk is two or more blocks that is either checked out or\n** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the\n** size of the allocation in blocks if the allocation is free.\n** The u.hdr.size4x&1 bit is true if the chunk is checked out and\n** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit\n** is true if the previous chunk is checked out and false if the\n** previous chunk is free.  The u.hdr.prevSize field is the size of\n** the previous chunk in blocks if the previous chunk is on the\n** freelist. If the previous chunk is checked out, then\n** u.hdr.prevSize can be part of the data for that chunk and should\n** not be read or written.\n**\n** We often identify a chunk by its index in mem3.aPool[].  When\n** this is done, the chunk index refers to the second block of\n** the chunk.  In this way, the first chunk has an index of 1.\n** A chunk index of 0 means \"no such chunk\" and is the equivalent\n** of a NULL pointer.\n**\n** The second block of free chunks is of the form u.list.  The\n** two fields form a double-linked list of chunks of related sizes.\n** Pointers to the head of the list are stored in mem3.aiSmall[] \n** for smaller chunks and mem3.aiHash[] for larger chunks.\n**\n** The second block of a chunk is user data if the chunk is checked \n** out.  If a chunk is checked out, the user data may extend into\n** the u.hdr.prevSize value of the following chunk.\n*/\ntypedef struct Mem3Block Mem3Block;\nstruct Mem3Block {\n  union {\n    struct {\n      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */\n      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */\n    } hdr;\n    struct {\n      u32 next;       /* Index in mem3.aPool[] of next free chunk */\n      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */\n    } list;\n  } u;\n};\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem3\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic SQLITE_WSD struct Mem3Global {\n  /*\n  ** Memory available for allocation. nPool is the size of the array\n  ** (in Mem3Blocks) pointed to by aPool less 2.\n  */\n  u32 nPool;\n  Mem3Block *aPool;\n\n  /*\n  ** True if we are evaluating an out-of-memory callback.\n  */\n  int alarmBusy;\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n  \n  /*\n  ** The minimum amount of free space that we have seen.\n  */\n  u32 mnMaster;\n\n  /*\n  ** iMaster is the index of the master chunk.  Most new allocations\n  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)\n  ** of the current master.  iMaster is 0 if there is not master chunk.\n  ** The master chunk is not in either the aiHash[] or aiSmall[].\n  */\n  u32 iMaster;\n  u32 szMaster;\n\n  /*\n  ** Array of lists of free blocks according to the block size \n  ** for smaller chunks, or a hash on the block size for larger\n  ** chunks.\n  */\n  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */\n  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */\n} mem3 = { 97535575 };\n\n#define mem3 GLOBAL(struct Mem3Global, mem3)\n\n/*\n** Unlink the chunk at mem3.aPool[i] from list it is currently\n** on.  *pRoot is the list that i is a member of.\n*/\nstatic void memsys3UnlinkFromList(u32 i, u32 *pRoot){\n  u32 next = mem3.aPool[i].u.list.next;\n  u32 prev = mem3.aPool[i].u.list.prev;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  if( prev==0 ){\n    *pRoot = next;\n  }else{\n    mem3.aPool[prev].u.list.next = next;\n  }\n  if( next ){\n    mem3.aPool[next].u.list.prev = prev;\n  }\n  mem3.aPool[i].u.list.next = 0;\n  mem3.aPool[i].u.list.prev = 0;\n}\n\n/*\n** Unlink the chunk at index i from \n** whatever list is currently a member of.\n*/\nstatic void memsys3Unlink(u32 i){\n  u32 size, hash;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );\n  assert( i>=1 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );\n  assert( size>=2 );\n  if( size <= MX_SMALL ){\n    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);\n  }else{\n    hash = size % N_HASH;\n    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);\n  }\n}\n\n/*\n** Link the chunk at mem3.aPool[i] so that is on the list rooted\n** at *pRoot.\n*/\nstatic void memsys3LinkIntoList(u32 i, u32 *pRoot){\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  mem3.aPool[i].u.list.next = *pRoot;\n  mem3.aPool[i].u.list.prev = 0;\n  if( *pRoot ){\n    mem3.aPool[*pRoot].u.list.prev = i;\n  }\n  *pRoot = i;\n}\n\n/*\n** Link the chunk at index i into either the appropriate\n** small chunk list, or into the large chunk hash table.\n*/\nstatic void memsys3Link(u32 i){\n  u32 size, hash;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( i>=1 );\n  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );\n  assert( size>=2 );\n  if( size <= MX_SMALL ){\n    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);\n  }else{\n    hash = size % N_HASH;\n    memsys3LinkIntoList(i, &mem3.aiHash[hash]);\n  }\n}\n\n/*\n** If the STATIC_MEM mutex is not already held, obtain it now. The mutex\n** will already be held (obtained by code in malloc.c) if\n** sqlite3GlobalConfig.bMemStat is true.\n*/\nstatic void memsys3Enter(void){\n  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){\n    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n  sqlite3_mutex_enter(mem3.mutex);\n}\nstatic void memsys3Leave(void){\n  sqlite3_mutex_leave(mem3.mutex);\n}\n\n/*\n** Called when we are unable to satisfy an allocation of nBytes.\n*/\nstatic void memsys3OutOfMemory(int nByte){\n  if( !mem3.alarmBusy ){\n    mem3.alarmBusy = 1;\n    assert( sqlite3_mutex_held(mem3.mutex) );\n    sqlite3_mutex_leave(mem3.mutex);\n    sqlite3_release_memory(nByte);\n    sqlite3_mutex_enter(mem3.mutex);\n    mem3.alarmBusy = 0;\n  }\n}\n\n\n/*\n** Chunk i is a free chunk that has been unlinked.  Adjust its \n** size parameters for check-out and return a pointer to the \n** user portion of the chunk.\n*/\nstatic void *memsys3Checkout(u32 i, u32 nBlock){\n  u32 x;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( i>=1 );\n  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );\n  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );\n  x = mem3.aPool[i-1].u.hdr.size4x;\n  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);\n  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;\n  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;\n  return &mem3.aPool[i];\n}\n\n/*\n** Carve a piece off of the end of the mem3.iMaster free chunk.\n** Return a pointer to the new allocation.  Or, if the master chunk\n** is not large enough, return 0.\n*/\nstatic void *memsys3FromMaster(u32 nBlock){\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( mem3.szMaster>=nBlock );\n  if( nBlock>=mem3.szMaster-1 ){\n    /* Use the entire master */\n    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);\n    mem3.iMaster = 0;\n    mem3.szMaster = 0;\n    mem3.mnMaster = 0;\n    return p;\n  }else{\n    /* Split the master block.  Return the tail. */\n    u32 newi, x;\n    newi = mem3.iMaster + mem3.szMaster - nBlock;\n    assert( newi > mem3.iMaster+1 );\n    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;\n    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;\n    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;\n    mem3.szMaster -= nBlock;\n    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;\n    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n    if( mem3.szMaster < mem3.mnMaster ){\n      mem3.mnMaster = mem3.szMaster;\n    }\n    return (void*)&mem3.aPool[newi];\n  }\n}\n\n/*\n** *pRoot is the head of a list of free chunks of the same size\n** or same size hash.  In other words, *pRoot is an entry in either\n** mem3.aiSmall[] or mem3.aiHash[].  \n**\n** This routine examines all entries on the given list and tries\n** to coalesce each entries with adjacent free chunks.  \n**\n** If it sees a chunk that is larger than mem3.iMaster, it replaces \n** the current mem3.iMaster with the new larger chunk.  In order for\n** this mem3.iMaster replacement to work, the master chunk must be\n** linked into the hash tables.  That is not the normal state of\n** affairs, of course.  The calling routine must link the master\n** chunk before invoking this routine, then must unlink the (possibly\n** changed) master chunk once this routine has finished.\n*/\nstatic void memsys3Merge(u32 *pRoot){\n  u32 iNext, prev, size, i, x;\n\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  for(i=*pRoot; i>0; i=iNext){\n    iNext = mem3.aPool[i].u.list.next;\n    size = mem3.aPool[i-1].u.hdr.size4x;\n    assert( (size&1)==0 );\n    if( (size&2)==0 ){\n      memsys3UnlinkFromList(i, pRoot);\n      assert( i > mem3.aPool[i-1].u.hdr.prevSize );\n      prev = i - mem3.aPool[i-1].u.hdr.prevSize;\n      if( prev==iNext ){\n        iNext = mem3.aPool[prev].u.list.next;\n      }\n      memsys3Unlink(prev);\n      size = i + size/4 - prev;\n      x = mem3.aPool[prev-1].u.hdr.size4x & 2;\n      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;\n      mem3.aPool[prev+size-1].u.hdr.prevSize = size;\n      memsys3Link(prev);\n      i = prev;\n    }else{\n      size /= 4;\n    }\n    if( size>mem3.szMaster ){\n      mem3.iMaster = i;\n      mem3.szMaster = size;\n    }\n  }\n}\n\n/*\n** Return a block of memory of at least nBytes in size.\n** Return NULL if unable.\n**\n** This function assumes that the necessary mutexes, if any, are\n** already held by the caller. Hence \"Unsafe\".\n*/\nstatic void *memsys3MallocUnsafe(int nByte){\n  u32 i;\n  u32 nBlock;\n  u32 toFree;\n\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( sizeof(Mem3Block)==8 );\n  if( nByte<=12 ){\n    nBlock = 2;\n  }else{\n    nBlock = (nByte + 11)/8;\n  }\n  assert( nBlock>=2 );\n\n  /* STEP 1:\n  ** Look for an entry of the correct size in either the small\n  ** chunk table or in the large chunk hash table.  This is\n  ** successful most of the time (about 9 times out of 10).\n  */\n  if( nBlock <= MX_SMALL ){\n    i = mem3.aiSmall[nBlock-2];\n    if( i>0 ){\n      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);\n      return memsys3Checkout(i, nBlock);\n    }\n  }else{\n    int hash = nBlock % N_HASH;\n    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){\n      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){\n        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);\n        return memsys3Checkout(i, nBlock);\n      }\n    }\n  }\n\n  /* STEP 2:\n  ** Try to satisfy the allocation by carving a piece off of the end\n  ** of the master chunk.  This step usually works if step 1 fails.\n  */\n  if( mem3.szMaster>=nBlock ){\n    return memsys3FromMaster(nBlock);\n  }\n\n\n  /* STEP 3:  \n  ** Loop through the entire memory pool.  Coalesce adjacent free\n  ** chunks.  Recompute the master chunk as the largest free chunk.\n  ** Then try again to satisfy the allocation by carving a piece off\n  ** of the end of the master chunk.  This step happens very\n  ** rarely (we hope!)\n  */\n  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){\n    memsys3OutOfMemory(toFree);\n    if( mem3.iMaster ){\n      memsys3Link(mem3.iMaster);\n      mem3.iMaster = 0;\n      mem3.szMaster = 0;\n    }\n    for(i=0; i<N_HASH; i++){\n      memsys3Merge(&mem3.aiHash[i]);\n    }\n    for(i=0; i<MX_SMALL-1; i++){\n      memsys3Merge(&mem3.aiSmall[i]);\n    }\n    if( mem3.szMaster ){\n      memsys3Unlink(mem3.iMaster);\n      if( mem3.szMaster>=nBlock ){\n        return memsys3FromMaster(nBlock);\n      }\n    }\n  }\n\n  /* If none of the above worked, then we fail. */\n  return 0;\n}\n\n/*\n** Free an outstanding memory allocation.\n**\n** This function assumes that the necessary mutexes, if any, are\n** already held by the caller. Hence \"Unsafe\".\n*/\nstatic void memsys3FreeUnsafe(void *pOld){\n  Mem3Block *p = (Mem3Block*)pOld;\n  int i;\n  u32 size, x;\n  assert( sqlite3_mutex_held(mem3.mutex) );\n  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );\n  i = p - mem3.aPool;\n  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );\n  size = mem3.aPool[i-1].u.hdr.size4x/4;\n  assert( i+size<=mem3.nPool+1 );\n  mem3.aPool[i-1].u.hdr.size4x &= ~1;\n  mem3.aPool[i+size-1].u.hdr.prevSize = size;\n  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;\n  memsys3Link(i);\n\n  /* Try to expand the master using the newly freed chunk */\n  if( mem3.iMaster ){\n    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){\n      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;\n      mem3.iMaster -= size;\n      mem3.szMaster += size;\n      memsys3Unlink(mem3.iMaster);\n      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;\n    }\n    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;\n    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){\n      memsys3Unlink(mem3.iMaster+mem3.szMaster);\n      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;\n      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;\n      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;\n    }\n  }\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.  The\n** size returned omits the 8-byte header overhead.  This only\n** works for chunks that are currently checked out.\n*/\nstatic int memsys3Size(void *p){\n  Mem3Block *pBlock;\n  if( p==0 ) return 0;\n  pBlock = (Mem3Block*)p;\n  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );\n  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int memsys3Roundup(int n){\n  if( n<=12 ){\n    return 12;\n  }else{\n    return ((n+11)&~7) - 4;\n  }\n}\n\n/*\n** Allocate nBytes of memory.\n*/\nstatic void *memsys3Malloc(int nBytes){\n  sqlite3_int64 *p;\n  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */\n  memsys3Enter();\n  p = memsys3MallocUnsafe(nBytes);\n  memsys3Leave();\n  return (void*)p; \n}\n\n/*\n** Free memory.\n*/\nstatic void memsys3Free(void *pPrior){\n  assert( pPrior );\n  memsys3Enter();\n  memsys3FreeUnsafe(pPrior);\n  memsys3Leave();\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nstatic void *memsys3Realloc(void *pPrior, int nBytes){\n  int nOld;\n  void *p;\n  if( pPrior==0 ){\n    return sqlite3_malloc(nBytes);\n  }\n  if( nBytes<=0 ){\n    sqlite3_free(pPrior);\n    return 0;\n  }\n  nOld = memsys3Size(pPrior);\n  if( nBytes<=nOld && nBytes>=nOld-128 ){\n    return pPrior;\n  }\n  memsys3Enter();\n  p = memsys3MallocUnsafe(nBytes);\n  if( p ){\n    if( nOld<nBytes ){\n      memcpy(p, pPrior, nOld);\n    }else{\n      memcpy(p, pPrior, nBytes);\n    }\n    memsys3FreeUnsafe(pPrior);\n  }\n  memsys3Leave();\n  return p;\n}\n\n/*\n** Initialize this module.\n*/\nstatic int memsys3Init(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  if( !sqlite3GlobalConfig.pHeap ){\n    return SQLITE_ERROR;\n  }\n\n  /* Store a pointer to the memory block in global structure mem3. */\n  assert( sizeof(Mem3Block)==8 );\n  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;\n  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;\n\n  /* Initialize the master block. */\n  mem3.szMaster = mem3.nPool;\n  mem3.mnMaster = mem3.szMaster;\n  mem3.iMaster = 1;\n  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;\n  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;\n  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;\n\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void memsys3Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem3.mutex = 0;\n  return;\n}\n\n\n\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){\n#ifdef SQLITE_DEBUG\n  FILE *out;\n  u32 i, j;\n  u32 size;\n  if( zFilename==0 || zFilename[0]==0 ){\n    out = stdout;\n  }else{\n    out = fopen(zFilename, \"w\");\n    if( out==0 ){\n      fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                      zFilename);\n      return;\n    }\n  }\n  memsys3Enter();\n  fprintf(out, \"CHUNKS:\\n\");\n  for(i=1; i<=mem3.nPool; i+=size/4){\n    size = mem3.aPool[i-1].u.hdr.size4x;\n    if( size/4<=1 ){\n      fprintf(out, \"%p size error\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){\n      fprintf(out, \"%p tail size does not match\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){\n      fprintf(out, \"%p tail checkout bit is incorrect\\n\", &mem3.aPool[i]);\n      assert( 0 );\n      break;\n    }\n    if( size&1 ){\n      fprintf(out, \"%p %6d bytes checked out\\n\", &mem3.aPool[i], (size/4)*8-8);\n    }else{\n      fprintf(out, \"%p %6d bytes free%s\\n\", &mem3.aPool[i], (size/4)*8-8,\n                  i==mem3.iMaster ? \" **master**\" : \"\");\n    }\n  }\n  for(i=0; i<MX_SMALL-1; i++){\n    if( mem3.aiSmall[i]==0 ) continue;\n    fprintf(out, \"small(%2d):\", i);\n    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){\n      fprintf(out, \" %p(%d)\", &mem3.aPool[j],\n              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);\n    }\n    fprintf(out, \"\\n\"); \n  }\n  for(i=0; i<N_HASH; i++){\n    if( mem3.aiHash[i]==0 ) continue;\n    fprintf(out, \"hash(%2d):\", i);\n    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){\n      fprintf(out, \" %p(%d)\", &mem3.aPool[j],\n              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);\n    }\n    fprintf(out, \"\\n\"); \n  }\n  fprintf(out, \"master=%d\\n\", mem3.iMaster);\n  fprintf(out, \"nowUsed=%d\\n\", mem3.nPool*8 - mem3.szMaster*8);\n  fprintf(out, \"mxUsed=%d\\n\", mem3.nPool*8 - mem3.mnMaster*8);\n  sqlite3_mutex_leave(mem3.mutex);\n  if( out==stdout ){\n    fflush(stdout);\n  }else{\n    fclose(out);\n  }\n#else\n  UNUSED_PARAMETER(zFilename);\n#endif\n}\n\n/*\n** This routine is the only routine in this file with external \n** linkage.\n**\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file. The\n** arguments specify the block of memory to manage.\n**\n** This routine is only called by sqlite3_config(), and therefore\n** is not required to be threadsafe (it is not).\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){\n  static const sqlite3_mem_methods mempoolMethods = {\n     memsys3Malloc,\n     memsys3Free,\n     memsys3Realloc,\n     memsys3Size,\n     memsys3Roundup,\n     memsys3Init,\n     memsys3Shutdown,\n     0\n  };\n  return &mempoolMethods;\n}\n\n#endif /* SQLITE_ENABLE_MEMSYS3 */\n\n/************** End of mem3.c ************************************************/\n/************** Begin file mem5.c ********************************************/\n/*\n** 2007 October 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement a memory\n** allocation subsystem for use by SQLite. \n**\n** This version of the memory allocation subsystem omits all\n** use of malloc(). The application gives SQLite a block of memory\n** before calling sqlite3_initialize() from which allocations\n** are made and returned by the xMalloc() and xRealloc() \n** implementations. Once sqlite3_initialize() has been called,\n** the amount of memory available to SQLite is fixed and cannot\n** be changed.\n**\n** This version of the memory allocation subsystem is included\n** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.\n**\n** This memory allocator uses the following algorithm:\n**\n**   1.  All memory allocations sizes are rounded up to a power of 2.\n**\n**   2.  If two adjacent free blocks are the halves of a larger block,\n**       then the two blocks are coalesed into the single larger block.\n**\n**   3.  New memory is allocated from the first available free block.\n**\n** This algorithm is described in: J. M. Robson. \"Bounds for Some Functions\n** Concerning Dynamic Storage Allocation\". Journal of the Association for\n** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.\n** \n** Let n be the size of the largest allocation divided by the minimum\n** allocation size (after rounding all sizes up to a power of 2.)  Let M\n** be the maximum amount of memory ever outstanding at one time.  Let\n** N be the total amount of memory available for allocation.  Robson\n** proved that this memory allocator will never breakdown due to \n** fragmentation as long as the following constraint holds:\n**\n**      N >=  M*(1 + log2(n)/2) - n + 1\n**\n** The sqlite3_status() logic tracks the maximum values of n and M so\n** that an application can, at any time, verify this constraint.\n*/\n\n/*\n** This version of the memory allocator is used only when \n** SQLITE_ENABLE_MEMSYS5 is defined.\n*/\n#ifdef SQLITE_ENABLE_MEMSYS5\n\n/*\n** A minimum allocation is an instance of the following structure.\n** Larger allocations are an array of these structures where the\n** size of the array is a power of 2.\n**\n** The size of this object must be a power of two.  That fact is\n** verified in memsys5Init().\n*/\ntypedef struct Mem5Link Mem5Link;\nstruct Mem5Link {\n  int next;       /* Index of next free chunk */\n  int prev;       /* Index of previous free chunk */\n};\n\n/*\n** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since\n** mem5.szAtom is always at least 8 and 32-bit integers are used,\n** it is not actually possible to reach this limit.\n*/\n#define LOGMAX 30\n\n/*\n** Masks used for mem5.aCtrl[] elements.\n*/\n#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */\n#define CTRL_FREE     0x20    /* True if not checked out */\n\n/*\n** All of the static variables used by this module are collected\n** into a single structure named \"mem5\".  This is to keep the\n** static variables organized and to reduce namespace pollution\n** when this module is combined with other in the amalgamation.\n*/\nstatic SQLITE_WSD struct Mem5Global {\n  /*\n  ** Memory available for allocation\n  */\n  int szAtom;      /* Smallest possible allocation in bytes */\n  int nBlock;      /* Number of szAtom sized blocks in zPool */\n  u8 *zPool;       /* Memory available to be allocated */\n  \n  /*\n  ** Mutex to control access to the memory allocation subsystem.\n  */\n  sqlite3_mutex *mutex;\n\n  /*\n  ** Performance statistics\n  */\n  u64 nAlloc;         /* Total number of calls to malloc */\n  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */\n  u64 totalExcess;    /* Total internal fragmentation */\n  u32 currentOut;     /* Current checkout, including internal fragmentation */\n  u32 currentCount;   /* Current number of distinct checkouts */\n  u32 maxOut;         /* Maximum instantaneous currentOut */\n  u32 maxCount;       /* Maximum instantaneous currentCount */\n  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */\n  \n  /*\n  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of\n  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.\n  ** and so forth.\n  */\n  int aiFreelist[LOGMAX+1];\n\n  /*\n  ** Space for tracking which blocks are checked out and the size\n  ** of each block.  One byte per block.\n  */\n  u8 *aCtrl;\n\n} mem5;\n\n/*\n** Access the static variable through a macro for SQLITE_OMIT_WSD\n*/\n#define mem5 GLOBAL(struct Mem5Global, mem5)\n\n/*\n** Assuming mem5.zPool is divided up into an array of Mem5Link\n** structures, return a pointer to the idx-th such lik.\n*/\n#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))\n\n/*\n** Unlink the chunk at mem5.aPool[i] from list it is currently\n** on.  It should be found on mem5.aiFreelist[iLogsize].\n*/\nstatic void memsys5Unlink(int i, int iLogsize){\n  int next, prev;\n  assert( i>=0 && i<mem5.nBlock );\n  assert( iLogsize>=0 && iLogsize<=LOGMAX );\n  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );\n\n  next = MEM5LINK(i)->next;\n  prev = MEM5LINK(i)->prev;\n  if( prev<0 ){\n    mem5.aiFreelist[iLogsize] = next;\n  }else{\n    MEM5LINK(prev)->next = next;\n  }\n  if( next>=0 ){\n    MEM5LINK(next)->prev = prev;\n  }\n}\n\n/*\n** Link the chunk at mem5.aPool[i] so that is on the iLogsize\n** free list.\n*/\nstatic void memsys5Link(int i, int iLogsize){\n  int x;\n  assert( sqlite3_mutex_held(mem5.mutex) );\n  assert( i>=0 && i<mem5.nBlock );\n  assert( iLogsize>=0 && iLogsize<=LOGMAX );\n  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );\n\n  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];\n  MEM5LINK(i)->prev = -1;\n  if( x>=0 ){\n    assert( x<mem5.nBlock );\n    MEM5LINK(x)->prev = i;\n  }\n  mem5.aiFreelist[iLogsize] = i;\n}\n\n/*\n** If the STATIC_MEM mutex is not already held, obtain it now. The mutex\n** will already be held (obtained by code in malloc.c) if\n** sqlite3GlobalConfig.bMemStat is true.\n*/\nstatic void memsys5Enter(void){\n  sqlite3_mutex_enter(mem5.mutex);\n}\nstatic void memsys5Leave(void){\n  sqlite3_mutex_leave(mem5.mutex);\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.  The\n** size returned omits the 8-byte header overhead.  This only\n** works for chunks that are currently checked out.\n*/\nstatic int memsys5Size(void *p){\n  int iSize = 0;\n  if( p ){\n    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;\n    assert( i>=0 && i<mem5.nBlock );\n    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));\n  }\n  return iSize;\n}\n\n/*\n** Find the first entry on the freelist iLogsize.  Unlink that\n** entry and return its index. \n*/\nstatic int memsys5UnlinkFirst(int iLogsize){\n  int i;\n  int iFirst;\n\n  assert( iLogsize>=0 && iLogsize<=LOGMAX );\n  i = iFirst = mem5.aiFreelist[iLogsize];\n  assert( iFirst>=0 );\n  while( i>0 ){\n    if( i<iFirst ) iFirst = i;\n    i = MEM5LINK(i)->next;\n  }\n  memsys5Unlink(iFirst, iLogsize);\n  return iFirst;\n}\n\n/*\n** Return a block of memory of at least nBytes in size.\n** Return NULL if unable.  Return NULL if nBytes==0.\n**\n** The caller guarantees that nByte positive.\n**\n** The caller has obtained a mutex prior to invoking this\n** routine so there is never any chance that two or more\n** threads can be in this routine at the same time.\n*/\nstatic void *memsys5MallocUnsafe(int nByte){\n  int i;           /* Index of a mem5.aPool[] slot */\n  int iBin;        /* Index into mem5.aiFreelist[] */\n  int iFullSz;     /* Size of allocation rounded up to power of 2 */\n  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */\n\n  /* nByte must be a positive */\n  assert( nByte>0 );\n\n  /* Keep track of the maximum allocation request.  Even unfulfilled\n  ** requests are counted */\n  if( (u32)nByte>mem5.maxRequest ){\n    mem5.maxRequest = nByte;\n  }\n\n  /* Abort if the requested allocation size is larger than the largest\n  ** power of two that we can represent using 32-bit signed integers.\n  */\n  if( nByte > 0x40000000 ){\n    return 0;\n  }\n\n  /* Round nByte up to the next valid power of two */\n  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}\n\n  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free\n  ** block.  If not, then split a block of the next larger power of\n  ** two in order to create a new free block of size iLogsize.\n  */\n  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}\n  if( iBin>LOGMAX ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(SQLITE_NOMEM, \"failed to allocate %u bytes\", nByte);\n    return 0;\n  }\n  i = memsys5UnlinkFirst(iBin);\n  while( iBin>iLogsize ){\n    int newSize;\n\n    iBin--;\n    newSize = 1 << iBin;\n    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;\n    memsys5Link(i+newSize, iBin);\n  }\n  mem5.aCtrl[i] = iLogsize;\n\n  /* Update allocator performance statistics. */\n  mem5.nAlloc++;\n  mem5.totalAlloc += iFullSz;\n  mem5.totalExcess += iFullSz - nByte;\n  mem5.currentCount++;\n  mem5.currentOut += iFullSz;\n  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;\n  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;\n\n  /* Return a pointer to the allocated memory. */\n  return (void*)&mem5.zPool[i*mem5.szAtom];\n}\n\n/*\n** Free an outstanding memory allocation.\n*/\nstatic void memsys5FreeUnsafe(void *pOld){\n  u32 size, iLogsize;\n  int iBlock;\n\n  /* Set iBlock to the index of the block pointed to by pOld in \n  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.\n  */\n  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;\n\n  /* Check that the pointer pOld points to a valid, non-free block. */\n  assert( iBlock>=0 && iBlock<mem5.nBlock );\n  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );\n  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );\n\n  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;\n  size = 1<<iLogsize;\n  assert( iBlock+size-1<(u32)mem5.nBlock );\n\n  mem5.aCtrl[iBlock] |= CTRL_FREE;\n  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;\n  assert( mem5.currentCount>0 );\n  assert( mem5.currentOut>=(size*mem5.szAtom) );\n  mem5.currentCount--;\n  mem5.currentOut -= size*mem5.szAtom;\n  assert( mem5.currentOut>0 || mem5.currentCount==0 );\n  assert( mem5.currentCount>0 || mem5.currentOut==0 );\n\n  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;\n  while( ALWAYS(iLogsize<LOGMAX) ){\n    int iBuddy;\n    if( (iBlock>>iLogsize) & 1 ){\n      iBuddy = iBlock - size;\n    }else{\n      iBuddy = iBlock + size;\n    }\n    assert( iBuddy>=0 );\n    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;\n    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;\n    memsys5Unlink(iBuddy, iLogsize);\n    iLogsize++;\n    if( iBuddy<iBlock ){\n      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;\n      mem5.aCtrl[iBlock] = 0;\n      iBlock = iBuddy;\n    }else{\n      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;\n      mem5.aCtrl[iBuddy] = 0;\n    }\n    size *= 2;\n  }\n  memsys5Link(iBlock, iLogsize);\n}\n\n/*\n** Allocate nBytes of memory\n*/\nstatic void *memsys5Malloc(int nBytes){\n  sqlite3_int64 *p = 0;\n  if( nBytes>0 ){\n    memsys5Enter();\n    p = memsys5MallocUnsafe(nBytes);\n    memsys5Leave();\n  }\n  return (void*)p; \n}\n\n/*\n** Free memory.\n**\n** The outer layer memory allocator prevents this routine from\n** being called with pPrior==0.\n*/\nstatic void memsys5Free(void *pPrior){\n  assert( pPrior!=0 );\n  memsys5Enter();\n  memsys5FreeUnsafe(pPrior);\n  memsys5Leave();  \n}\n\n/*\n** Change the size of an existing memory allocation.\n**\n** The outer layer memory allocator prevents this routine from\n** being called with pPrior==0.  \n**\n** nBytes is always a value obtained from a prior call to\n** memsys5Round().  Hence nBytes is always a non-negative power\n** of two.  If nBytes==0 that means that an oversize allocation\n** (an allocation larger than 0x40000000) was requested and this\n** routine should return 0 without freeing pPrior.\n*/\nstatic void *memsys5Realloc(void *pPrior, int nBytes){\n  int nOld;\n  void *p;\n  assert( pPrior!=0 );\n  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */\n  assert( nBytes>=0 );\n  if( nBytes==0 ){\n    return 0;\n  }\n  nOld = memsys5Size(pPrior);\n  if( nBytes<=nOld ){\n    return pPrior;\n  }\n  memsys5Enter();\n  p = memsys5MallocUnsafe(nBytes);\n  if( p ){\n    memcpy(p, pPrior, nOld);\n    memsys5FreeUnsafe(pPrior);\n  }\n  memsys5Leave();\n  return p;\n}\n\n/*\n** Round up a request size to the next valid allocation size.  If\n** the allocation is too large to be handled by this allocation system,\n** return 0.\n**\n** All allocations must be a power of two and must be expressed by a\n** 32-bit signed integer.  Hence the largest allocation is 0x40000000\n** or 1073741824 bytes.\n*/\nstatic int memsys5Roundup(int n){\n  int iFullSz;\n  if( n > 0x40000000 ) return 0;\n  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);\n  return iFullSz;\n}\n\n/*\n** Return the ceiling of the logarithm base 2 of iValue.\n**\n** Examples:   memsys5Log(1) -> 0\n**             memsys5Log(2) -> 1\n**             memsys5Log(4) -> 2\n**             memsys5Log(5) -> 3\n**             memsys5Log(8) -> 3\n**             memsys5Log(9) -> 4\n*/\nstatic int memsys5Log(int iValue){\n  int iLog;\n  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);\n  return iLog;\n}\n\n/*\n** Initialize the memory allocator.\n**\n** This routine is not threadsafe.  The caller must be holding a mutex\n** to prevent multiple threads from entering at the same time.\n*/\nstatic int memsys5Init(void *NotUsed){\n  int ii;            /* Loop counter */\n  int nByte;         /* Number of bytes of memory available to this allocator */\n  u8 *zByte;         /* Memory usable by this allocator */\n  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */\n  int iOffset;       /* An offset into mem5.aCtrl[] */\n\n  UNUSED_PARAMETER(NotUsed);\n\n  /* For the purposes of this routine, disable the mutex */\n  mem5.mutex = 0;\n\n  /* The size of a Mem5Link object must be a power of two.  Verify that\n  ** this is case.\n  */\n  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );\n\n  nByte = sqlite3GlobalConfig.nHeap;\n  zByte = (u8*)sqlite3GlobalConfig.pHeap;\n  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */\n\n  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */\n  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);\n  mem5.szAtom = (1<<nMinLog);\n  while( (int)sizeof(Mem5Link)>mem5.szAtom ){\n    mem5.szAtom = mem5.szAtom << 1;\n  }\n\n  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));\n  mem5.zPool = zByte;\n  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];\n\n  for(ii=0; ii<=LOGMAX; ii++){\n    mem5.aiFreelist[ii] = -1;\n  }\n\n  iOffset = 0;\n  for(ii=LOGMAX; ii>=0; ii--){\n    int nAlloc = (1<<ii);\n    if( (iOffset+nAlloc)<=mem5.nBlock ){\n      mem5.aCtrl[iOffset] = ii | CTRL_FREE;\n      memsys5Link(iOffset, ii);\n      iOffset += nAlloc;\n    }\n    assert((iOffset+nAlloc)>mem5.nBlock);\n  }\n\n  /* If a mutex is required for normal operation, allocate one */\n  if( sqlite3GlobalConfig.bMemstat==0 ){\n    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void memsys5Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  mem5.mutex = 0;\n  return;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Open the file indicated and write a log of all unfreed memory \n** allocations into that log.\n*/\nSQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){\n  FILE *out;\n  int i, j, n;\n  int nMinLog;\n\n  if( zFilename==0 || zFilename[0]==0 ){\n    out = stdout;\n  }else{\n    out = fopen(zFilename, \"w\");\n    if( out==0 ){\n      fprintf(stderr, \"** Unable to output memory debug output log: %s **\\n\",\n                      zFilename);\n      return;\n    }\n  }\n  memsys5Enter();\n  nMinLog = memsys5Log(mem5.szAtom);\n  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){\n    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}\n    fprintf(out, \"freelist items of size %d: %d\\n\", mem5.szAtom << i, n);\n  }\n  fprintf(out, \"mem5.nAlloc       = %llu\\n\", mem5.nAlloc);\n  fprintf(out, \"mem5.totalAlloc   = %llu\\n\", mem5.totalAlloc);\n  fprintf(out, \"mem5.totalExcess  = %llu\\n\", mem5.totalExcess);\n  fprintf(out, \"mem5.currentOut   = %u\\n\", mem5.currentOut);\n  fprintf(out, \"mem5.currentCount = %u\\n\", mem5.currentCount);\n  fprintf(out, \"mem5.maxOut       = %u\\n\", mem5.maxOut);\n  fprintf(out, \"mem5.maxCount     = %u\\n\", mem5.maxCount);\n  fprintf(out, \"mem5.maxRequest   = %u\\n\", mem5.maxRequest);\n  memsys5Leave();\n  if( out==stdout ){\n    fflush(stdout);\n  }else{\n    fclose(out);\n  }\n}\n#endif\n\n/*\n** This routine is the only routine in this file with external \n** linkage. It returns a pointer to a static sqlite3_mem_methods\n** struct populated with the memsys5 methods.\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){\n  static const sqlite3_mem_methods memsys5Methods = {\n     memsys5Malloc,\n     memsys5Free,\n     memsys5Realloc,\n     memsys5Size,\n     memsys5Roundup,\n     memsys5Init,\n     memsys5Shutdown,\n     0\n  };\n  return &memsys5Methods;\n}\n\n#endif /* SQLITE_ENABLE_MEMSYS5 */\n\n/************** End of mem5.c ************************************************/\n/************** Begin file mutex.c *******************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes.\n**\n** This file contains code that is common across all mutex implementations.\n*/\n\n#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)\n/*\n** For debugging purposes, record when the mutex subsystem is initialized\n** and uninitialized so that we can assert() if there is an attempt to\n** allocate a mutex while the system is uninitialized.\n*/\nstatic SQLITE_WSD int mutexIsInit = 0;\n#endif /* SQLITE_DEBUG */\n\n\n#ifndef SQLITE_MUTEX_OMIT\n/*\n** Initialize the mutex system.\n*/\nSQLITE_PRIVATE int sqlite3MutexInit(void){ \n  int rc = SQLITE_OK;\n  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){\n    /* If the xMutexAlloc method has not been set, then the user did not\n    ** install a mutex implementation via sqlite3_config() prior to \n    ** sqlite3_initialize() being called. This block copies pointers to\n    ** the default implementation into the sqlite3GlobalConfig structure.\n    */\n    sqlite3_mutex_methods const *pFrom;\n    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;\n\n    if( sqlite3GlobalConfig.bCoreMutex ){\n      pFrom = sqlite3DefaultMutex();\n    }else{\n      pFrom = sqlite3NoopMutex();\n    }\n    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));\n    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,\n           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));\n    pTo->xMutexAlloc = pFrom->xMutexAlloc;\n  }\n  rc = sqlite3GlobalConfig.mutex.xMutexInit();\n\n#ifdef SQLITE_DEBUG\n  GLOBAL(int, mutexIsInit) = 1;\n#endif\n\n  return rc;\n}\n\n/*\n** Shutdown the mutex system. This call frees resources allocated by\n** sqlite3MutexInit().\n*/\nSQLITE_PRIVATE int sqlite3MutexEnd(void){\n  int rc = SQLITE_OK;\n  if( sqlite3GlobalConfig.mutex.xMutexEnd ){\n    rc = sqlite3GlobalConfig.mutex.xMutexEnd();\n  }\n\n#ifdef SQLITE_DEBUG\n  GLOBAL(int, mutexIsInit) = 0;\n#endif\n\n  return rc;\n}\n\n/*\n** Retrieve a pointer to a static mutex or allocate a new dynamic one.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);\n}\n\nSQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){\n  if( !sqlite3GlobalConfig.bCoreMutex ){\n    return 0;\n  }\n  assert( GLOBAL(int, mutexIsInit) );\n  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);\n}\n\n/*\n** Free a dynamic mutex.\n*/\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){\n  if( p ){\n    sqlite3GlobalConfig.mutex.xMutexFree(p);\n  }\n}\n\n/*\n** Obtain the mutex p. If some other thread already has the mutex, block\n** until it can be obtained.\n*/\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){\n  if( p ){\n    sqlite3GlobalConfig.mutex.xMutexEnter(p);\n  }\n}\n\n/*\n** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another\n** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.\n*/\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){\n  int rc = SQLITE_OK;\n  if( p ){\n    return sqlite3GlobalConfig.mutex.xMutexTry(p);\n  }\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was previously\n** entered by the same thread.  The behavior is undefined if the mutex \n** is not currently entered. If a NULL pointer is passed as an argument\n** this function is a no-op.\n*/\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){\n  if( p ){\n    sqlite3GlobalConfig.mutex.xMutexLeave(p);\n  }\n}\n\n#ifndef NDEBUG\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use inside assert() statements.\n*/\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){\n  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);\n}\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){\n  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);\n}\n#endif\n\n#endif /* !defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex.c ***********************************************/\n/************** Begin file mutex_noop.c **************************************/\n/*\n** 2008 October 07\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes.\n**\n** This implementation in this file does not provide any mutual\n** exclusion and is thus suitable for use only in applications\n** that use SQLite in a single thread.  The routines defined\n** here are place-holders.  Applications can substitute working\n** mutex routines at start-time using the\n**\n**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)\n**\n** interface.\n**\n** If compiled with SQLITE_DEBUG, then additional logic is inserted\n** that does error checking on mutexes to make sure they are being\n** called correctly.\n*/\n\n#ifndef SQLITE_MUTEX_OMIT\n\n#ifndef SQLITE_DEBUG\n/*\n** Stub routines for all mutex methods.\n**\n** This routines provide no mutual exclusion or error checking.\n*/\nstatic int noopMutexInit(void){ return SQLITE_OK; }\nstatic int noopMutexEnd(void){ return SQLITE_OK; }\nstatic sqlite3_mutex *noopMutexAlloc(int id){ \n  UNUSED_PARAMETER(id);\n  return (sqlite3_mutex*)8; \n}\nstatic void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\nstatic void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\nstatic int noopMutexTry(sqlite3_mutex *p){\n  UNUSED_PARAMETER(p);\n  return SQLITE_OK;\n}\nstatic void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    noopMutexInit,\n    noopMutexEnd,\n    noopMutexAlloc,\n    noopMutexFree,\n    noopMutexEnter,\n    noopMutexTry,\n    noopMutexLeave,\n\n    0,\n    0,\n  };\n\n  return &sMutex;\n}\n#endif /* !SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/*\n** In this implementation, error checking is provided for testing\n** and debugging purposes.  The mutexes still do not provide any\n** mutual exclusion.\n*/\n\n/*\n** The mutex object\n*/\ntypedef struct sqlite3_debug_mutex {\n  int id;     /* The mutex type */\n  int cnt;    /* Number of entries without a matching leave */\n} sqlite3_debug_mutex;\n\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use inside assert() statements.\n*/\nstatic int debugMutexHeld(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  return p==0 || p->cnt>0;\n}\nstatic int debugMutexNotheld(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  return p==0 || p->cnt==0;\n}\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic int debugMutexInit(void){ return SQLITE_OK; }\nstatic int debugMutexEnd(void){ return SQLITE_OK; }\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated. \n*/\nstatic sqlite3_mutex *debugMutexAlloc(int id){\n  static sqlite3_debug_mutex aStatic[6];\n  sqlite3_debug_mutex *pNew = 0;\n  switch( id ){\n    case SQLITE_MUTEX_FAST:\n    case SQLITE_MUTEX_RECURSIVE: {\n      pNew = sqlite3Malloc(sizeof(*pNew));\n      if( pNew ){\n        pNew->id = id;\n        pNew->cnt = 0;\n      }\n      break;\n    }\n    default: {\n      assert( id-2 >= 0 );\n      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );\n      pNew = &aStatic[id-2];\n      pNew->id = id;\n      break;\n    }\n  }\n  return (sqlite3_mutex*)pNew;\n}\n\n/*\n** This routine deallocates a previously allocated mutex.\n*/\nstatic void debugMutexFree(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->cnt==0 );\n  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );\n  sqlite3_free(p);\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void debugMutexEnter(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n  p->cnt++;\n}\nstatic int debugMutexTry(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n  p->cnt++;\n  return SQLITE_OK;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void debugMutexLeave(sqlite3_mutex *pX){\n  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;\n  assert( debugMutexHeld(pX) );\n  p->cnt--;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    debugMutexInit,\n    debugMutexEnd,\n    debugMutexAlloc,\n    debugMutexFree,\n    debugMutexEnter,\n    debugMutexTry,\n    debugMutexLeave,\n\n    debugMutexHeld,\n    debugMutexNotheld\n  };\n\n  return &sMutex;\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation\n** is used regardless of the run-time threadsafety setting.\n*/\n#ifdef SQLITE_MUTEX_NOOP\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  return sqlite3NoopMutex();\n}\n#endif /* defined(SQLITE_MUTEX_NOOP) */\n#endif /* !defined(SQLITE_MUTEX_OMIT) */\n\n/************** End of mutex_noop.c ******************************************/\n/************** Begin file mutex_unix.c **************************************/\n/*\n** 2007 August 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes for pthreads\n*/\n\n/*\n** The code in this file is only used if we are compiling threadsafe\n** under unix with pthreads.\n**\n** Note that this implementation requires a version of pthreads that\n** supports recursive mutexes.\n*/\n#ifdef SQLITE_MUTEX_PTHREADS\n\n#include <pthread.h>\n\n/*\n** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields\n** are necessary under two condidtions:  (1) Debug builds and (2) using\n** home-grown mutexes.  Encapsulate these conditions into a single #define.\n*/\n#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)\n# define SQLITE_MUTEX_NREF 1\n#else\n# define SQLITE_MUTEX_NREF 0\n#endif\n\n/*\n** Each recursive mutex is an instance of the following structure.\n*/\nstruct sqlite3_mutex {\n  pthread_mutex_t mutex;     /* Mutex controlling the lock */\n#if SQLITE_MUTEX_NREF\n  int id;                    /* Mutex type */\n  volatile int nRef;         /* Number of entrances */\n  volatile pthread_t owner;  /* Thread that is within this mutex */\n  int trace;                 /* True to trace changes */\n#endif\n};\n#if SQLITE_MUTEX_NREF\n#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }\n#else\n#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }\n#endif\n\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use only inside assert() statements.  On some platforms,\n** there might be race conditions that can cause these routines to\n** deliver incorrect results.  In particular, if pthread_equal() is\n** not an atomic operation, then these routines might delivery\n** incorrect results.  On most platforms, pthread_equal() is a \n** comparison of two integers and is therefore atomic.  But we are\n** told that HPUX is not such a platform.  If so, then these routines\n** will not always work correctly on HPUX.\n**\n** On those platforms where pthread_equal() is not atomic, SQLite\n** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to\n** make sure no assert() statements are evaluated and hence these\n** routines are never called.\n*/\n#if !defined(NDEBUG) || defined(SQLITE_DEBUG)\nstatic int pthreadMutexHeld(sqlite3_mutex *p){\n  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));\n}\nstatic int pthreadMutexNotheld(sqlite3_mutex *p){\n  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;\n}\n#endif\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic int pthreadMutexInit(void){ return SQLITE_OK; }\nstatic int pthreadMutexEnd(void){ return SQLITE_OK; }\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated.  SQLite\n** will unwind its stack and return an error.  The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_MEM2\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** </ul>\n**\n** The first two constants cause sqlite3_mutex_alloc() to create\n** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  But SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** The other allowed parameters to sqlite3_mutex_alloc() each return\n** a pointer to a static preexisting mutex.  Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  But for the static \n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n*/\nstatic sqlite3_mutex *pthreadMutexAlloc(int iType){\n  static sqlite3_mutex staticMutexes[] = {\n    SQLITE3_MUTEX_INITIALIZER,\n    SQLITE3_MUTEX_INITIALIZER,\n    SQLITE3_MUTEX_INITIALIZER,\n    SQLITE3_MUTEX_INITIALIZER,\n    SQLITE3_MUTEX_INITIALIZER,\n    SQLITE3_MUTEX_INITIALIZER\n  };\n  sqlite3_mutex *p;\n  switch( iType ){\n    case SQLITE_MUTEX_RECURSIVE: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n        /* If recursive mutexes are not available, we will have to\n        ** build our own.  See below. */\n        pthread_mutex_init(&p->mutex, 0);\n#else\n        /* Use a recursive mutex if it is available */\n        pthread_mutexattr_t recursiveAttr;\n        pthread_mutexattr_init(&recursiveAttr);\n        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);\n        pthread_mutex_init(&p->mutex, &recursiveAttr);\n        pthread_mutexattr_destroy(&recursiveAttr);\n#endif\n#if SQLITE_MUTEX_NREF\n        p->id = iType;\n#endif\n      }\n      break;\n    }\n    case SQLITE_MUTEX_FAST: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){\n#if SQLITE_MUTEX_NREF\n        p->id = iType;\n#endif\n        pthread_mutex_init(&p->mutex, 0);\n      }\n      break;\n    }\n    default: {\n      assert( iType-2 >= 0 );\n      assert( iType-2 < ArraySize(staticMutexes) );\n      p = &staticMutexes[iType-2];\n#if SQLITE_MUTEX_NREF\n      p->id = iType;\n#endif\n      break;\n    }\n  }\n  return p;\n}\n\n\n/*\n** This routine deallocates a previously\n** allocated mutex.  SQLite is careful to deallocate every\n** mutex that it allocates.\n*/\nstatic void pthreadMutexFree(sqlite3_mutex *p){\n  assert( p->nRef==0 );\n  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );\n  pthread_mutex_destroy(&p->mutex);\n  sqlite3_free(p);\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void pthreadMutexEnter(sqlite3_mutex *p){\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  /* If recursive mutexes are not available, then we have to grow\n  ** our own.  This implementation assumes that pthread_equal()\n  ** is atomic - that it cannot be deceived into thinking self\n  ** and p->owner are equal if p->owner changes between two values\n  ** that are not equal to self while the comparison is taking place.\n  ** This implementation also assumes a coherent cache - that \n  ** separate processes cannot read different values from the same\n  ** address at the same time.  If either of these two conditions\n  ** are not met, then the mutexes will fail and problems will result.\n  */\n  {\n    pthread_t self = pthread_self();\n    if( p->nRef>0 && pthread_equal(p->owner, self) ){\n      p->nRef++;\n    }else{\n      pthread_mutex_lock(&p->mutex);\n      assert( p->nRef==0 );\n      p->owner = self;\n      p->nRef = 1;\n    }\n  }\n#else\n  /* Use the built-in recursive mutexes if they are available.\n  */\n  pthread_mutex_lock(&p->mutex);\n#if SQLITE_MUTEX_NREF\n  assert( p->nRef>0 || p->owner==0 );\n  p->owner = pthread_self();\n  p->nRef++;\n#endif\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    printf(\"enter mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\nstatic int pthreadMutexTry(sqlite3_mutex *p){\n  int rc;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  /* If recursive mutexes are not available, then we have to grow\n  ** our own.  This implementation assumes that pthread_equal()\n  ** is atomic - that it cannot be deceived into thinking self\n  ** and p->owner are equal if p->owner changes between two values\n  ** that are not equal to self while the comparison is taking place.\n  ** This implementation also assumes a coherent cache - that \n  ** separate processes cannot read different values from the same\n  ** address at the same time.  If either of these two conditions\n  ** are not met, then the mutexes will fail and problems will result.\n  */\n  {\n    pthread_t self = pthread_self();\n    if( p->nRef>0 && pthread_equal(p->owner, self) ){\n      p->nRef++;\n      rc = SQLITE_OK;\n    }else if( pthread_mutex_trylock(&p->mutex)==0 ){\n      assert( p->nRef==0 );\n      p->owner = self;\n      p->nRef = 1;\n      rc = SQLITE_OK;\n    }else{\n      rc = SQLITE_BUSY;\n    }\n  }\n#else\n  /* Use the built-in recursive mutexes if they are available.\n  */\n  if( pthread_mutex_trylock(&p->mutex)==0 ){\n#if SQLITE_MUTEX_NREF\n    p->owner = pthread_self();\n    p->nRef++;\n#endif\n    rc = SQLITE_OK;\n  }else{\n    rc = SQLITE_BUSY;\n  }\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( rc==SQLITE_OK && p->trace ){\n    printf(\"enter mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void pthreadMutexLeave(sqlite3_mutex *p){\n  assert( pthreadMutexHeld(p) );\n#if SQLITE_MUTEX_NREF\n  p->nRef--;\n  if( p->nRef==0 ) p->owner = 0;\n#endif\n  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );\n\n#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX\n  if( p->nRef==0 ){\n    pthread_mutex_unlock(&p->mutex);\n  }\n#else\n  pthread_mutex_unlock(&p->mutex);\n#endif\n\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    printf(\"leave mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    pthreadMutexInit,\n    pthreadMutexEnd,\n    pthreadMutexAlloc,\n    pthreadMutexFree,\n    pthreadMutexEnter,\n    pthreadMutexTry,\n    pthreadMutexLeave,\n#ifdef SQLITE_DEBUG\n    pthreadMutexHeld,\n    pthreadMutexNotheld\n#else\n    0,\n    0\n#endif\n  };\n\n  return &sMutex;\n}\n\n#endif /* SQLITE_MUTEX_PTHREADS */\n\n/************** End of mutex_unix.c ******************************************/\n/************** Begin file mutex_w32.c ***************************************/\n/*\n** 2007 August 14\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement mutexes for win32\n*/\n\n/*\n** The code in this file is only used if we are compiling multithreaded\n** on a win32 system.\n*/\n#ifdef SQLITE_MUTEX_W32\n\n/*\n** Each recursive mutex is an instance of the following structure.\n*/\nstruct sqlite3_mutex {\n  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */\n  int id;                    /* Mutex type */\n#ifdef SQLITE_DEBUG\n  volatile int nRef;         /* Number of enterances */\n  volatile DWORD owner;      /* Thread holding this mutex */\n  int trace;                 /* True to trace changes */\n#endif\n};\n#define SQLITE_W32_MUTEX_INITIALIZER { 0 }\n#ifdef SQLITE_DEBUG\n#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }\n#else\n#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }\n#endif\n\n/*\n** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,\n** or WinCE.  Return false (zero) for Win95, Win98, or WinME.\n**\n** Here is an interesting observation:  Win95, Win98, and WinME lack\n** the LockFileEx() API.  But we can still statically link against that\n** API as long as we don't call it win running Win95/98/ME.  A call to\n** this routine is used to determine if the host is Win95/98/ME or\n** WinNT/2K/XP so that we will know whether or not we can safely call\n** the LockFileEx() API.\n**\n** mutexIsNT() is only used for the TryEnterCriticalSection() API call,\n** which is only available if your application was compiled with \n** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only\n** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef \n** this out as well.\n*/\n#if 0\n#if SQLITE_OS_WINCE || SQLITE_OS_WINRT\n# define mutexIsNT()  (1)\n#else\n  static int mutexIsNT(void){\n    static int osType = 0;\n    if( osType==0 ){\n      OSVERSIONINFO sInfo;\n      sInfo.dwOSVersionInfoSize = sizeof(sInfo);\n      GetVersionEx(&sInfo);\n      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;\n    }\n    return osType==2;\n  }\n#endif /* SQLITE_OS_WINCE */\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are\n** intended for use only inside assert() statements.\n*/\nstatic int winMutexHeld(sqlite3_mutex *p){\n  return p->nRef!=0 && p->owner==GetCurrentThreadId();\n}\nstatic int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){\n  return p->nRef==0 || p->owner!=tid;\n}\nstatic int winMutexNotheld(sqlite3_mutex *p){\n  DWORD tid = GetCurrentThreadId(); \n  return winMutexNotheld2(p, tid);\n}\n#endif\n\n\n/*\n** Initialize and deinitialize the mutex subsystem.\n*/\nstatic sqlite3_mutex winMutex_staticMutexes[6] = {\n  SQLITE3_MUTEX_INITIALIZER,\n  SQLITE3_MUTEX_INITIALIZER,\n  SQLITE3_MUTEX_INITIALIZER,\n  SQLITE3_MUTEX_INITIALIZER,\n  SQLITE3_MUTEX_INITIALIZER,\n  SQLITE3_MUTEX_INITIALIZER\n};\nstatic int winMutex_isInit = 0;\n/* As winMutexInit() and winMutexEnd() are called as part\n** of the sqlite3_initialize and sqlite3_shutdown()\n** processing, the \"interlocked\" magic is probably not\n** strictly necessary.\n*/\nstatic long winMutex_lock = 0;\n\nSQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */\n\nstatic int winMutexInit(void){ \n  /* The first to increment to 1 does actual initialization */\n  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){\n    int i;\n    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){\n#if SQLITE_OS_WINRT\n      InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);\n#else\n      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);\n#endif\n    }\n    winMutex_isInit = 1;\n  }else{\n    /* Someone else is in the process of initing the static mutexes */\n    while( !winMutex_isInit ){\n      sqlite3_win32_sleep(1);\n    }\n  }\n  return SQLITE_OK; \n}\n\nstatic int winMutexEnd(void){ \n  /* The first to decrement to 0 does actual shutdown \n  ** (which should be the last to shutdown.) */\n  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){\n    if( winMutex_isInit==1 ){\n      int i;\n      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){\n        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);\n      }\n      winMutex_isInit = 0;\n    }\n  }\n  return SQLITE_OK; \n}\n\n/*\n** The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it.  If it returns NULL\n** that means that a mutex could not be allocated.  SQLite\n** will unwind its stack and return an error.  The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_MEM2\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_PMEM\n** </ul>\n**\n** The first two constants cause sqlite3_mutex_alloc() to create\n** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  But SQLite will only request a recursive mutex in\n** cases where it really needs one.  If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** The other allowed parameters to sqlite3_mutex_alloc() each return\n** a pointer to a static preexisting mutex.  Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  But for the static \n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n*/\nstatic sqlite3_mutex *winMutexAlloc(int iType){\n  sqlite3_mutex *p;\n\n  switch( iType ){\n    case SQLITE_MUTEX_FAST:\n    case SQLITE_MUTEX_RECURSIVE: {\n      p = sqlite3MallocZero( sizeof(*p) );\n      if( p ){  \n#ifdef SQLITE_DEBUG\n        p->id = iType;\n#endif\n#if SQLITE_OS_WINRT\n        InitializeCriticalSectionEx(&p->mutex, 0, 0);\n#else\n        InitializeCriticalSection(&p->mutex);\n#endif\n      }\n      break;\n    }\n    default: {\n      assert( winMutex_isInit==1 );\n      assert( iType-2 >= 0 );\n      assert( iType-2 < ArraySize(winMutex_staticMutexes) );\n      p = &winMutex_staticMutexes[iType-2];\n#ifdef SQLITE_DEBUG\n      p->id = iType;\n#endif\n      break;\n    }\n  }\n  return p;\n}\n\n\n/*\n** This routine deallocates a previously\n** allocated mutex.  SQLite is careful to deallocate every\n** mutex that it allocates.\n*/\nstatic void winMutexFree(sqlite3_mutex *p){\n  assert( p );\n  assert( p->nRef==0 && p->owner==0 );\n  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );\n  DeleteCriticalSection(&p->mutex);\n  sqlite3_free(p);\n}\n\n/*\n** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK\n** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can\n** be entered multiple times by the same thread.  In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.  If the same thread tries to enter any other kind of mutex\n** more than once, the behavior is undefined.\n*/\nstatic void winMutexEnter(sqlite3_mutex *p){\n#ifdef SQLITE_DEBUG\n  DWORD tid = GetCurrentThreadId(); \n  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );\n#endif\n  EnterCriticalSection(&p->mutex);\n#ifdef SQLITE_DEBUG\n  assert( p->nRef>0 || p->owner==0 );\n  p->owner = tid; \n  p->nRef++;\n  if( p->trace ){\n    printf(\"enter mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\nstatic int winMutexTry(sqlite3_mutex *p){\n#ifndef NDEBUG\n  DWORD tid = GetCurrentThreadId(); \n#endif\n  int rc = SQLITE_BUSY;\n  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );\n  /*\n  ** The sqlite3_mutex_try() routine is very rarely used, and when it\n  ** is used it is merely an optimization.  So it is OK for it to always\n  ** fail.  \n  **\n  ** The TryEnterCriticalSection() interface is only available on WinNT.\n  ** And some windows compilers complain if you try to use it without\n  ** first doing some #defines that prevent SQLite from building on Win98.\n  ** For that reason, we will omit this optimization for now.  See\n  ** ticket #2685.\n  */\n#if 0\n  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){\n    p->owner = tid;\n    p->nRef++;\n    rc = SQLITE_OK;\n  }\n#else\n  UNUSED_PARAMETER(p);\n#endif\n#ifdef SQLITE_DEBUG\n  if( rc==SQLITE_OK && p->trace ){\n    printf(\"try mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n  return rc;\n}\n\n/*\n** The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.  The behavior\n** is undefined if the mutex is not currently entered or\n** is not currently allocated.  SQLite will never do either.\n*/\nstatic void winMutexLeave(sqlite3_mutex *p){\n#ifndef NDEBUG\n  DWORD tid = GetCurrentThreadId();\n  assert( p->nRef>0 );\n  assert( p->owner==tid );\n  p->nRef--;\n  if( p->nRef==0 ) p->owner = 0;\n  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );\n#endif\n  LeaveCriticalSection(&p->mutex);\n#ifdef SQLITE_DEBUG\n  if( p->trace ){\n    printf(\"leave mutex %p (%d) with nRef=%d\\n\", p, p->trace, p->nRef);\n  }\n#endif\n}\n\nSQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){\n  static const sqlite3_mutex_methods sMutex = {\n    winMutexInit,\n    winMutexEnd,\n    winMutexAlloc,\n    winMutexFree,\n    winMutexEnter,\n    winMutexTry,\n    winMutexLeave,\n#ifdef SQLITE_DEBUG\n    winMutexHeld,\n    winMutexNotheld\n#else\n    0,\n    0\n#endif\n  };\n\n  return &sMutex;\n}\n#endif /* SQLITE_MUTEX_W32 */\n\n/************** End of mutex_w32.c *******************************************/\n/************** Begin file malloc.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** Memory allocation functions used throughout sqlite.\n*/\n/* #include <stdarg.h> */\n\n/*\n** Attempt to release up to n bytes of non-essential memory currently\n** held by SQLite. An example of non-essential memory is memory used to\n** cache database pages that are not currently in use.\n*/\nSQLITE_API int sqlite3_release_memory(int n){\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n  return sqlite3PcacheReleaseMemory(n);\n#else\n  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine\n  ** is a no-op returning zero if SQLite is not compiled with\n  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */\n  UNUSED_PARAMETER(n);\n  return 0;\n#endif\n}\n\n/*\n** An instance of the following object records the location of\n** each unused scratch buffer.\n*/\ntypedef struct ScratchFreeslot {\n  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */\n} ScratchFreeslot;\n\n/*\n** State information local to the memory allocation subsystem.\n*/\nstatic SQLITE_WSD struct Mem0Global {\n  sqlite3_mutex *mutex;         /* Mutex to serialize access */\n\n  /*\n  ** The alarm callback and its arguments.  The mem0.mutex lock will\n  ** be held while the callback is running.  Recursive calls into\n  ** the memory subsystem are allowed, but no new callbacks will be\n  ** issued.\n  */\n  sqlite3_int64 alarmThreshold;\n  void (*alarmCallback)(void*, sqlite3_int64,int);\n  void *alarmArg;\n\n  /*\n  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory\n  ** (so that a range test can be used to determine if an allocation\n  ** being freed came from pScratch) and a pointer to the list of\n  ** unused scratch allocations.\n  */\n  void *pScratchEnd;\n  ScratchFreeslot *pScratchFree;\n  u32 nScratchFree;\n\n  /*\n  ** True if heap is nearly \"full\" where \"full\" is defined by the\n  ** sqlite3_soft_heap_limit() setting.\n  */\n  int nearlyFull;\n} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };\n\n#define mem0 GLOBAL(struct Mem0Global, mem0)\n\n/*\n** This routine runs when the memory allocator sees that the\n** total memory allocation is about to exceed the soft heap\n** limit.\n*/\nstatic void softHeapLimitEnforcer(\n  void *NotUsed, \n  sqlite3_int64 NotUsed2,\n  int allocSize\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  sqlite3_release_memory(allocSize);\n}\n\n/*\n** Change the alarm callback\n*/\nstatic int sqlite3MemoryAlarm(\n  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),\n  void *pArg,\n  sqlite3_int64 iThreshold\n){\n  int nUsed;\n  sqlite3_mutex_enter(mem0.mutex);\n  mem0.alarmCallback = xCallback;\n  mem0.alarmArg = pArg;\n  mem0.alarmThreshold = iThreshold;\n  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);\n  sqlite3_mutex_leave(mem0.mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Deprecated external interface.  Internal/core SQLite code\n** should call sqlite3MemoryAlarm.\n*/\nSQLITE_API int sqlite3_memory_alarm(\n  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),\n  void *pArg,\n  sqlite3_int64 iThreshold\n){\n  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);\n}\n#endif\n\n/*\n** Set the soft heap-size limit for the library. Passing a zero or \n** negative value indicates no limit.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){\n  sqlite3_int64 priorLimit;\n  sqlite3_int64 excess;\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return -1;\n#endif\n  sqlite3_mutex_enter(mem0.mutex);\n  priorLimit = mem0.alarmThreshold;\n  sqlite3_mutex_leave(mem0.mutex);\n  if( n<0 ) return priorLimit;\n  if( n>0 ){\n    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);\n  }else{\n    sqlite3MemoryAlarm(0, 0, 0);\n  }\n  excess = sqlite3_memory_used() - n;\n  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));\n  return priorLimit;\n}\nSQLITE_API void sqlite3_soft_heap_limit(int n){\n  if( n<0 ) n = 0;\n  sqlite3_soft_heap_limit64(n);\n}\n\n/*\n** Initialize the memory allocation subsystem.\n*/\nSQLITE_PRIVATE int sqlite3MallocInit(void){\n  if( sqlite3GlobalConfig.m.xMalloc==0 ){\n    sqlite3MemSetDefault();\n  }\n  memset(&mem0, 0, sizeof(mem0));\n  if( sqlite3GlobalConfig.bCoreMutex ){\n    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);\n  }\n  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100\n      && sqlite3GlobalConfig.nScratch>0 ){\n    int i, n, sz;\n    ScratchFreeslot *pSlot;\n    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);\n    sqlite3GlobalConfig.szScratch = sz;\n    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;\n    n = sqlite3GlobalConfig.nScratch;\n    mem0.pScratchFree = pSlot;\n    mem0.nScratchFree = n;\n    for(i=0; i<n-1; i++){\n      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);\n      pSlot = pSlot->pNext;\n    }\n    pSlot->pNext = 0;\n    mem0.pScratchEnd = (void*)&pSlot[1];\n  }else{\n    mem0.pScratchEnd = 0;\n    sqlite3GlobalConfig.pScratch = 0;\n    sqlite3GlobalConfig.szScratch = 0;\n    sqlite3GlobalConfig.nScratch = 0;\n  }\n  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512\n      || sqlite3GlobalConfig.nPage<1 ){\n    sqlite3GlobalConfig.pPage = 0;\n    sqlite3GlobalConfig.szPage = 0;\n    sqlite3GlobalConfig.nPage = 0;\n  }\n  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);\n}\n\n/*\n** Return true if the heap is currently under memory pressure - in other\n** words if the amount of heap used is close to the limit set by\n** sqlite3_soft_heap_limit().\n*/\nSQLITE_PRIVATE int sqlite3HeapNearlyFull(void){\n  return mem0.nearlyFull;\n}\n\n/*\n** Deinitialize the memory allocation subsystem.\n*/\nSQLITE_PRIVATE void sqlite3MallocEnd(void){\n  if( sqlite3GlobalConfig.m.xShutdown ){\n    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);\n  }\n  memset(&mem0, 0, sizeof(mem0));\n}\n\n/*\n** Return the amount of memory currently checked out.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void){\n  int n, mx;\n  sqlite3_int64 res;\n  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);\n  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */\n  return res;\n}\n\n/*\n** Return the maximum amount of memory that has ever been\n** checked out since either the beginning of this process\n** or since the most recent reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){\n  int n, mx;\n  sqlite3_int64 res;\n  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);\n  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */\n  return res;\n}\n\n/*\n** Trigger the alarm \n*/\nstatic void sqlite3MallocAlarm(int nByte){\n  void (*xCallback)(void*,sqlite3_int64,int);\n  sqlite3_int64 nowUsed;\n  void *pArg;\n  if( mem0.alarmCallback==0 ) return;\n  xCallback = mem0.alarmCallback;\n  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n  pArg = mem0.alarmArg;\n  mem0.alarmCallback = 0;\n  sqlite3_mutex_leave(mem0.mutex);\n  xCallback(pArg, nowUsed, nByte);\n  sqlite3_mutex_enter(mem0.mutex);\n  mem0.alarmCallback = xCallback;\n  mem0.alarmArg = pArg;\n}\n\n/*\n** Do a memory allocation with statistics and alarms.  Assume the\n** lock is already held.\n*/\nstatic int mallocWithAlarm(int n, void **pp){\n  int nFull;\n  void *p;\n  assert( sqlite3_mutex_held(mem0.mutex) );\n  nFull = sqlite3GlobalConfig.m.xRoundup(n);\n  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);\n  if( mem0.alarmCallback!=0 ){\n    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);\n    if( nUsed >= mem0.alarmThreshold - nFull ){\n      mem0.nearlyFull = 1;\n      sqlite3MallocAlarm(nFull);\n    }else{\n      mem0.nearlyFull = 0;\n    }\n  }\n  p = sqlite3GlobalConfig.m.xMalloc(nFull);\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n  if( p==0 && mem0.alarmCallback ){\n    sqlite3MallocAlarm(nFull);\n    p = sqlite3GlobalConfig.m.xMalloc(nFull);\n  }\n#endif\n  if( p ){\n    nFull = sqlite3MallocSize(p);\n    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);\n    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);\n  }\n  *pp = p;\n  return nFull;\n}\n\n/*\n** Allocate memory.  This routine is like sqlite3_malloc() except that it\n** assumes the memory subsystem has already been initialized.\n*/\nSQLITE_PRIVATE void *sqlite3Malloc(int n){\n  void *p;\n  if( n<=0               /* IMP: R-65312-04917 */ \n   || n>=0x7fffff00\n  ){\n    /* A memory allocation of a number of bytes which is near the maximum\n    ** signed integer value might cause an integer overflow inside of the\n    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving\n    ** 255 bytes of overhead.  SQLite itself will never use anything near\n    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */\n    p = 0;\n  }else if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    mallocWithAlarm(n, &p);\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    p = sqlite3GlobalConfig.m.xMalloc(n);\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */\n  return p;\n}\n\n/*\n** This version of the memory allocation is for use by the application.\n** First make sure the memory subsystem is initialized, then do the\n** allocation.\n*/\nSQLITE_API void *sqlite3_malloc(int n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return sqlite3Malloc(n);\n}\n\n/*\n** Each thread may only have a single outstanding allocation from\n** xScratchMalloc().  We verify this constraint in the single-threaded\n** case by setting scratchAllocOut to 1 when an allocation\n** is outstanding clearing it when the allocation is freed.\n*/\n#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)\nstatic int scratchAllocOut = 0;\n#endif\n\n\n/*\n** Allocate memory that is to be used and released right away.\n** This routine is similar to alloca() in that it is not intended\n** for situations where the memory might be held long-term.  This\n** routine is intended to get memory to old large transient data\n** structures that would not normally fit on the stack of an\n** embedded processor.\n*/\nSQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){\n  void *p;\n  assert( n>0 );\n\n  sqlite3_mutex_enter(mem0.mutex);\n  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){\n    p = mem0.pScratchFree;\n    mem0.pScratchFree = mem0.pScratchFree->pNext;\n    mem0.nScratchFree--;\n    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);\n    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    if( sqlite3GlobalConfig.bMemstat ){\n      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);\n      n = mallocWithAlarm(n, &p);\n      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);\n      sqlite3_mutex_leave(mem0.mutex);\n    }else{\n      sqlite3_mutex_leave(mem0.mutex);\n      p = sqlite3GlobalConfig.m.xMalloc(n);\n    }\n    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);\n  }\n  assert( sqlite3_mutex_notheld(mem0.mutex) );\n\n\n#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)\n  /* Verify that no more than two scratch allocations per thread\n  ** are outstanding at one time.  (This is only checked in the\n  ** single-threaded case since checking in the multi-threaded case\n  ** would be much more complicated.) */\n  assert( scratchAllocOut<=1 );\n  if( p ) scratchAllocOut++;\n#endif\n\n  return p;\n}\nSQLITE_PRIVATE void sqlite3ScratchFree(void *p){\n  if( p ){\n\n#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)\n    /* Verify that no more than two scratch allocation per thread\n    ** is outstanding at one time.  (This is only checked in the\n    ** single-threaded case since checking in the multi-threaded case\n    ** would be much more complicated.) */\n    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );\n    scratchAllocOut--;\n#endif\n\n    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){\n      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */\n      ScratchFreeslot *pSlot;\n      pSlot = (ScratchFreeslot*)p;\n      sqlite3_mutex_enter(mem0.mutex);\n      pSlot->pNext = mem0.pScratchFree;\n      mem0.pScratchFree = pSlot;\n      mem0.nScratchFree++;\n      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );\n      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);\n      sqlite3_mutex_leave(mem0.mutex);\n    }else{\n      /* Release memory back to the heap */\n      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );\n      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );\n      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n      if( sqlite3GlobalConfig.bMemstat ){\n        int iSize = sqlite3MallocSize(p);\n        sqlite3_mutex_enter(mem0.mutex);\n        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);\n        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);\n        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);\n        sqlite3GlobalConfig.m.xFree(p);\n        sqlite3_mutex_leave(mem0.mutex);\n      }else{\n        sqlite3GlobalConfig.m.xFree(p);\n      }\n    }\n  }\n}\n\n/*\n** TRUE if p is a lookaside memory allocation from db\n*/\n#ifndef SQLITE_OMIT_LOOKASIDE\nstatic int isLookaside(sqlite3 *db, void *p){\n  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;\n}\n#else\n#define isLookaside(A,B) 0\n#endif\n\n/*\n** Return the size of a memory allocation previously obtained from\n** sqlite3Malloc() or sqlite3_malloc().\n*/\nSQLITE_PRIVATE int sqlite3MallocSize(void *p){\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );\n  return sqlite3GlobalConfig.m.xSize(p);\n}\nSQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){\n  assert( db==0 || sqlite3_mutex_held(db->mutex) );\n  if( db && isLookaside(db, p) ){\n    return db->lookaside.sz;\n  }else{\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );\n    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );\n    return sqlite3GlobalConfig.m.xSize(p);\n  }\n}\n\n/*\n** Free memory previously obtained from sqlite3Malloc().\n*/\nSQLITE_API void sqlite3_free(void *p){\n  if( p==0 ) return;  /* IMP: R-49053-54554 */\n  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );\n  if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));\n    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);\n    sqlite3GlobalConfig.m.xFree(p);\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    sqlite3GlobalConfig.m.xFree(p);\n  }\n}\n\n/*\n** Free memory that might be associated with a particular database\n** connection.\n*/\nSQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){\n  assert( db==0 || sqlite3_mutex_held(db->mutex) );\n  if( db ){\n    if( db->pnBytesFreed ){\n      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);\n      return;\n    }\n    if( isLookaside(db, p) ){\n      LookasideSlot *pBuf = (LookasideSlot*)p;\n#if SQLITE_DEBUG\n      /* Trash all content in the buffer being freed */\n      memset(p, 0xaa, db->lookaside.sz);\n#endif\n      pBuf->pNext = db->lookaside.pFree;\n      db->lookaside.pFree = pBuf;\n      db->lookaside.nOut--;\n      return;\n    }\n  }\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );\n  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );\n  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );\n  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n  sqlite3_free(p);\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nSQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){\n  int nOld, nNew, nDiff;\n  void *pNew;\n  if( pOld==0 ){\n    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */\n  }\n  if( nBytes<=0 ){\n    sqlite3_free(pOld); /* IMP: R-31593-10574 */\n    return 0;\n  }\n  if( nBytes>=0x7fffff00 ){\n    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */\n    return 0;\n  }\n  nOld = sqlite3MallocSize(pOld);\n  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second\n  ** argument to xRealloc is always a value returned by a prior call to\n  ** xRoundup. */\n  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);\n  if( nOld==nNew ){\n    pNew = pOld;\n  }else if( sqlite3GlobalConfig.bMemstat ){\n    sqlite3_mutex_enter(mem0.mutex);\n    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);\n    nDiff = nNew - nOld;\n    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= \n          mem0.alarmThreshold-nDiff ){\n      sqlite3MallocAlarm(nDiff);\n    }\n    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );\n    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );\n    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n    if( pNew==0 && mem0.alarmCallback ){\n      sqlite3MallocAlarm(nBytes);\n      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n    }\n    if( pNew ){\n      nNew = sqlite3MallocSize(pNew);\n      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);\n    }\n    sqlite3_mutex_leave(mem0.mutex);\n  }else{\n    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);\n  }\n  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */\n  return pNew;\n}\n\n/*\n** The public interface to sqlite3Realloc.  Make sure that the memory\n** subsystem is initialized prior to invoking sqliteRealloc.\n*/\nSQLITE_API void *sqlite3_realloc(void *pOld, int n){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  return sqlite3Realloc(pOld, n);\n}\n\n\n/*\n** Allocate and zero memory.\n*/ \nSQLITE_PRIVATE void *sqlite3MallocZero(int n){\n  void *p = sqlite3Malloc(n);\n  if( p ){\n    memset(p, 0, n);\n  }\n  return p;\n}\n\n/*\n** Allocate and zero memory.  If the allocation fails, make\n** the mallocFailed flag in the connection pointer.\n*/\nSQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){\n  void *p = sqlite3DbMallocRaw(db, n);\n  if( p ){\n    memset(p, 0, n);\n  }\n  return p;\n}\n\n/*\n** Allocate and zero memory.  If the allocation fails, make\n** the mallocFailed flag in the connection pointer.\n**\n** If db!=0 and db->mallocFailed is true (indicating a prior malloc\n** failure on the same database connection) then always return 0.\n** Hence for a particular database connection, once malloc starts\n** failing, it fails consistently until mallocFailed is reset.\n** This is an important assumption.  There are many places in the\n** code that do things like this:\n**\n**         int *a = (int*)sqlite3DbMallocRaw(db, 100);\n**         int *b = (int*)sqlite3DbMallocRaw(db, 200);\n**         if( b ) a[10] = 9;\n**\n** In other words, if a subsequent malloc (ex: \"b\") worked, it is assumed\n** that all prior mallocs (ex: \"a\") worked too.\n*/\nSQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){\n  void *p;\n  assert( db==0 || sqlite3_mutex_held(db->mutex) );\n  assert( db==0 || db->pnBytesFreed==0 );\n#ifndef SQLITE_OMIT_LOOKASIDE\n  if( db ){\n    LookasideSlot *pBuf;\n    if( db->mallocFailed ){\n      return 0;\n    }\n    if( db->lookaside.bEnabled ){\n      if( n>db->lookaside.sz ){\n        db->lookaside.anStat[1]++;\n      }else if( (pBuf = db->lookaside.pFree)==0 ){\n        db->lookaside.anStat[2]++;\n      }else{\n        db->lookaside.pFree = pBuf->pNext;\n        db->lookaside.nOut++;\n        db->lookaside.anStat[0]++;\n        if( db->lookaside.nOut>db->lookaside.mxOut ){\n          db->lookaside.mxOut = db->lookaside.nOut;\n        }\n        return (void*)pBuf;\n      }\n    }\n  }\n#else\n  if( db && db->mallocFailed ){\n    return 0;\n  }\n#endif\n  p = sqlite3Malloc(n);\n  if( !p && db ){\n    db->mallocFailed = 1;\n  }\n  sqlite3MemdebugSetType(p, MEMTYPE_DB |\n         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));\n  return p;\n}\n\n/*\n** Resize the block of memory pointed to by p to n bytes. If the\n** resize fails, set the mallocFailed flag in the connection object.\n*/\nSQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){\n  void *pNew = 0;\n  assert( db!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( db->mallocFailed==0 ){\n    if( p==0 ){\n      return sqlite3DbMallocRaw(db, n);\n    }\n    if( isLookaside(db, p) ){\n      if( n<=db->lookaside.sz ){\n        return p;\n      }\n      pNew = sqlite3DbMallocRaw(db, n);\n      if( pNew ){\n        memcpy(pNew, p, db->lookaside.sz);\n        sqlite3DbFree(db, p);\n      }\n    }else{\n      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );\n      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );\n      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n      pNew = sqlite3_realloc(p, n);\n      if( !pNew ){\n        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);\n        db->mallocFailed = 1;\n      }\n      sqlite3MemdebugSetType(pNew, MEMTYPE_DB | \n            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));\n    }\n  }\n  return pNew;\n}\n\n/*\n** Attempt to reallocate p.  If the reallocation fails, then free p\n** and set the mallocFailed flag in the database connection.\n*/\nSQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){\n  void *pNew;\n  pNew = sqlite3DbRealloc(db, p, n);\n  if( !pNew ){\n    sqlite3DbFree(db, p);\n  }\n  return pNew;\n}\n\n/*\n** Make a copy of a string in memory obtained from sqliteMalloc(). These \n** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This\n** is because when memory debugging is turned on, these two functions are \n** called via macros that record the current file and line number in the\n** ThreadData structure.\n*/\nSQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){\n  char *zNew;\n  size_t n;\n  if( z==0 ){\n    return 0;\n  }\n  n = sqlite3Strlen30(z) + 1;\n  assert( (n&0x7fffffff)==n );\n  zNew = sqlite3DbMallocRaw(db, (int)n);\n  if( zNew ){\n    memcpy(zNew, z, n);\n  }\n  return zNew;\n}\nSQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){\n  char *zNew;\n  if( z==0 ){\n    return 0;\n  }\n  assert( (n&0x7fffffff)==n );\n  zNew = sqlite3DbMallocRaw(db, n+1);\n  if( zNew ){\n    memcpy(zNew, z, n);\n    zNew[n] = 0;\n  }\n  return zNew;\n}\n\n/*\n** Create a string from the zFromat argument and the va_list that follows.\n** Store the string in memory obtained from sqliteMalloc() and make *pz\n** point to that string.\n*/\nSQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){\n  va_list ap;\n  char *z;\n\n  va_start(ap, zFormat);\n  z = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  sqlite3DbFree(db, *pz);\n  *pz = z;\n}\n\n\n/*\n** This function must be called before exiting any API function (i.e. \n** returning control to the user) that has called sqlite3_malloc or\n** sqlite3_realloc.\n**\n** The returned value is normally a copy of the second argument to this\n** function. However, if a malloc() failure has occurred since the previous\n** invocation SQLITE_NOMEM is returned instead. \n**\n** If the first argument, db, is not NULL and a malloc() error has occurred,\n** then the connection error-code (the value returned by sqlite3_errcode())\n** is set to SQLITE_NOMEM.\n*/\nSQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){\n  /* If the db handle is not NULL, then we must hold the connection handle\n  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed \n  ** is unsafe, as is the call to sqlite3Error().\n  */\n  assert( !db || sqlite3_mutex_held(db->mutex) );\n  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){\n    sqlite3Error(db, SQLITE_NOMEM, 0);\n    db->mallocFailed = 0;\n    rc = SQLITE_NOMEM;\n  }\n  return rc & (db ? db->errMask : 0xff);\n}\n\n/************** End of malloc.c **********************************************/\n/************** Begin file printf.c ******************************************/\n/*\n** The \"printf\" code that follows dates from the 1980's.  It is in\n** the public domain.  The original comments are included here for\n** completeness.  They are very out-of-date but might be useful as\n** an historical reference.  Most of the \"enhancements\" have been backed\n** out so that the functionality is now the same as standard printf().\n**\n**************************************************************************\n**\n** This file contains code for a set of \"printf\"-like routines.  These\n** routines format strings much like the printf() from the standard C\n** library, though the implementation here has enhancements to support\n** SQLlite.\n*/\n\n/*\n** Conversion types fall into various categories as defined by the\n** following enumeration.\n*/\n#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */\n#define etFLOAT       2 /* Floating point.  %f */\n#define etEXP         3 /* Exponentional notation. %e and %E */\n#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */\n#define etSIZE        5 /* Return number of characters processed so far. %n */\n#define etSTRING      6 /* Strings. %s */\n#define etDYNSTRING   7 /* Dynamically allocated strings. %z */\n#define etPERCENT     8 /* Percent symbol. %% */\n#define etCHARX       9 /* Characters. %c */\n/* The rest are extensions, not normally found in printf() */\n#define etSQLESCAPE  10 /* Strings with '\\'' doubled.  %q */\n#define etSQLESCAPE2 11 /* Strings with '\\'' doubled and enclosed in '',\n                          NULL pointers replaced by SQL NULL.  %Q */\n#define etTOKEN      12 /* a pointer to a Token structure */\n#define etSRCLIST    13 /* a pointer to a SrcList */\n#define etPOINTER    14 /* The %p conversion */\n#define etSQLESCAPE3 15 /* %w -> Strings with '\\\"' doubled */\n#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */\n\n#define etINVALID     0 /* Any unrecognized conversion type */\n\n\n/*\n** An \"etByte\" is an 8-bit unsigned value.\n*/\ntypedef unsigned char etByte;\n\n/*\n** Each builtin conversion character (ex: the 'd' in \"%d\") is described\n** by an instance of the following structure\n*/\ntypedef struct et_info {   /* Information about each format field */\n  char fmttype;            /* The format field code letter */\n  etByte base;             /* The base for radix conversion */\n  etByte flags;            /* One or more of FLAG_ constants below */\n  etByte type;             /* Conversion paradigm */\n  etByte charset;          /* Offset into aDigits[] of the digits string */\n  etByte prefix;           /* Offset into aPrefix[] of the prefix string */\n} et_info;\n\n/*\n** Allowed values for et_info.flags\n*/\n#define FLAG_SIGNED  1     /* True if the value to convert is signed */\n#define FLAG_INTERN  2     /* True if for internal use only */\n#define FLAG_STRING  4     /* Allow infinity precision */\n\n\n/*\n** The following table is searched linearly, so it is good to put the\n** most frequently used conversion types first.\n*/\nstatic const char aDigits[] = \"0123456789ABCDEF0123456789abcdef\";\nstatic const char aPrefix[] = \"-x0\\000X0\";\nstatic const et_info fmtinfo[] = {\n  {  'd', 10, 1, etRADIX,      0,  0 },\n  {  's',  0, 4, etSTRING,     0,  0 },\n  {  'g',  0, 1, etGENERIC,    30, 0 },\n  {  'z',  0, 4, etDYNSTRING,  0,  0 },\n  {  'q',  0, 4, etSQLESCAPE,  0,  0 },\n  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },\n  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },\n  {  'c',  0, 0, etCHARX,      0,  0 },\n  {  'o',  8, 0, etRADIX,      0,  2 },\n  {  'u', 10, 0, etRADIX,      0,  0 },\n  {  'x', 16, 0, etRADIX,      16, 1 },\n  {  'X', 16, 0, etRADIX,      0,  4 },\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  {  'f',  0, 1, etFLOAT,      0,  0 },\n  {  'e',  0, 1, etEXP,        30, 0 },\n  {  'E',  0, 1, etEXP,        14, 0 },\n  {  'G',  0, 1, etGENERIC,    14, 0 },\n#endif\n  {  'i', 10, 1, etRADIX,      0,  0 },\n  {  'n',  0, 0, etSIZE,       0,  0 },\n  {  '%',  0, 0, etPERCENT,    0,  0 },\n  {  'p', 16, 0, etPOINTER,    0,  1 },\n\n/* All the rest have the FLAG_INTERN bit set and are thus for internal\n** use only */\n  {  'T',  0, 2, etTOKEN,      0,  0 },\n  {  'S',  0, 2, etSRCLIST,    0,  0 },\n  {  'r', 10, 3, etORDINAL,    0,  0 },\n};\n\n/*\n** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point\n** conversions will work.\n*/\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** \"*val\" is a double such that 0.1 <= *val < 10.0\n** Return the ascii code for the leading digit of *val, then\n** multiply \"*val\" by 10.0 to renormalize.\n**\n** Example:\n**     input:     *val = 3.14159\n**     output:    *val = 1.4159    function return = '3'\n**\n** The counter *cnt is incremented each time.  After counter exceeds\n** 16 (the number of significant digits in a 64-bit float) '0' is\n** always returned.\n*/\nstatic char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){\n  int digit;\n  LONGDOUBLE_TYPE d;\n  if( (*cnt)<=0 ) return '0';\n  (*cnt)--;\n  digit = (int)*val;\n  d = digit;\n  digit += '0';\n  *val = (*val - d)*10.0;\n  return (char)digit;\n}\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n\n/*\n** Append N space characters to the given string buffer.\n*/\nSQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){\n  static const char zSpaces[] = \"                             \";\n  while( N>=(int)sizeof(zSpaces)-1 ){\n    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);\n    N -= sizeof(zSpaces)-1;\n  }\n  if( N>0 ){\n    sqlite3StrAccumAppend(pAccum, zSpaces, N);\n  }\n}\n\n/*\n** On machines with a small stack size, you can redefine the\n** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.\n*/\n#ifndef SQLITE_PRINT_BUF_SIZE\n# define SQLITE_PRINT_BUF_SIZE 70\n#endif\n#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */\n\n/*\n** Render a string given by \"fmt\" into the StrAccum object.\n*/\nSQLITE_PRIVATE void sqlite3VXPrintf(\n  StrAccum *pAccum,                  /* Accumulate results here */\n  int useExtended,                   /* Allow extended %-conversions */\n  const char *fmt,                   /* Format string */\n  va_list ap                         /* arguments */\n){\n  int c;                     /* Next character in the format string */\n  char *bufpt;               /* Pointer to the conversion buffer */\n  int precision;             /* Precision of the current field */\n  int length;                /* Length of the field */\n  int idx;                   /* A general purpose loop counter */\n  int width;                 /* Width of the current field */\n  etByte flag_leftjustify;   /* True if \"-\" flag is present */\n  etByte flag_plussign;      /* True if \"+\" flag is present */\n  etByte flag_blanksign;     /* True if \" \" flag is present */\n  etByte flag_alternateform; /* True if \"#\" flag is present */\n  etByte flag_altform2;      /* True if \"!\" flag is present */\n  etByte flag_zeropad;       /* True if field width constant starts with zero */\n  etByte flag_long;          /* True if \"l\" flag is present */\n  etByte flag_longlong;      /* True if the \"ll\" flag is present */\n  etByte done;               /* Loop termination flag */\n  etByte xtype = 0;          /* Conversion paradigm */\n  char prefix;               /* Prefix character.  \"+\" or \"-\" or \" \" or '\\0'. */\n  sqlite_uint64 longvalue;   /* Value for integer types */\n  LONGDOUBLE_TYPE realvalue; /* Value for real types */\n  const et_info *infop;      /* Pointer to the appropriate info structure */\n  char *zOut;                /* Rendering buffer */\n  int nOut;                  /* Size of the rendering buffer */\n  char *zExtra;              /* Malloced memory used by some conversion */\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  int  exp, e2;              /* exponent of real numbers */\n  int nsd;                   /* Number of significant digits returned */\n  double rounder;            /* Used for rounding floating point values */\n  etByte flag_dp;            /* True if decimal point should be shown */\n  etByte flag_rtz;           /* True if trailing zeros should be removed */\n#endif\n  char buf[etBUFSIZE];       /* Conversion buffer */\n\n  bufpt = 0;\n  for(; (c=(*fmt))!=0; ++fmt){\n    if( c!='%' ){\n      int amt;\n      bufpt = (char *)fmt;\n      amt = 1;\n      while( (c=(*++fmt))!='%' && c!=0 ) amt++;\n      sqlite3StrAccumAppend(pAccum, bufpt, amt);\n      if( c==0 ) break;\n    }\n    if( (c=(*++fmt))==0 ){\n      sqlite3StrAccumAppend(pAccum, \"%\", 1);\n      break;\n    }\n    /* Find out what flags are present */\n    flag_leftjustify = flag_plussign = flag_blanksign = \n     flag_alternateform = flag_altform2 = flag_zeropad = 0;\n    done = 0;\n    do{\n      switch( c ){\n        case '-':   flag_leftjustify = 1;     break;\n        case '+':   flag_plussign = 1;        break;\n        case ' ':   flag_blanksign = 1;       break;\n        case '#':   flag_alternateform = 1;   break;\n        case '!':   flag_altform2 = 1;        break;\n        case '0':   flag_zeropad = 1;         break;\n        default:    done = 1;                 break;\n      }\n    }while( !done && (c=(*++fmt))!=0 );\n    /* Get the field width */\n    width = 0;\n    if( c=='*' ){\n      width = va_arg(ap,int);\n      if( width<0 ){\n        flag_leftjustify = 1;\n        width = -width;\n      }\n      c = *++fmt;\n    }else{\n      while( c>='0' && c<='9' ){\n        width = width*10 + c - '0';\n        c = *++fmt;\n      }\n    }\n    /* Get the precision */\n    if( c=='.' ){\n      precision = 0;\n      c = *++fmt;\n      if( c=='*' ){\n        precision = va_arg(ap,int);\n        if( precision<0 ) precision = -precision;\n        c = *++fmt;\n      }else{\n        while( c>='0' && c<='9' ){\n          precision = precision*10 + c - '0';\n          c = *++fmt;\n        }\n      }\n    }else{\n      precision = -1;\n    }\n    /* Get the conversion type modifier */\n    if( c=='l' ){\n      flag_long = 1;\n      c = *++fmt;\n      if( c=='l' ){\n        flag_longlong = 1;\n        c = *++fmt;\n      }else{\n        flag_longlong = 0;\n      }\n    }else{\n      flag_long = flag_longlong = 0;\n    }\n    /* Fetch the info entry for the field */\n    infop = &fmtinfo[0];\n    xtype = etINVALID;\n    for(idx=0; idx<ArraySize(fmtinfo); idx++){\n      if( c==fmtinfo[idx].fmttype ){\n        infop = &fmtinfo[idx];\n        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){\n          xtype = infop->type;\n        }else{\n          return;\n        }\n        break;\n      }\n    }\n    zExtra = 0;\n\n    /*\n    ** At this point, variables are initialized as follows:\n    **\n    **   flag_alternateform          TRUE if a '#' is present.\n    **   flag_altform2               TRUE if a '!' is present.\n    **   flag_plussign               TRUE if a '+' is present.\n    **   flag_leftjustify            TRUE if a '-' is present or if the\n    **                               field width was negative.\n    **   flag_zeropad                TRUE if the width began with 0.\n    **   flag_long                   TRUE if the letter 'l' (ell) prefixed\n    **                               the conversion character.\n    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed\n    **                               the conversion character.\n    **   flag_blanksign              TRUE if a ' ' is present.\n    **   width                       The specified field width.  This is\n    **                               always non-negative.  Zero is the default.\n    **   precision                   The specified precision.  The default\n    **                               is -1.\n    **   xtype                       The class of the conversion.\n    **   infop                       Pointer to the appropriate info struct.\n    */\n    switch( xtype ){\n      case etPOINTER:\n        flag_longlong = sizeof(char*)==sizeof(i64);\n        flag_long = sizeof(char*)==sizeof(long int);\n        /* Fall through into the next case */\n      case etORDINAL:\n      case etRADIX:\n        if( infop->flags & FLAG_SIGNED ){\n          i64 v;\n          if( flag_longlong ){\n            v = va_arg(ap,i64);\n          }else if( flag_long ){\n            v = va_arg(ap,long int);\n          }else{\n            v = va_arg(ap,int);\n          }\n          if( v<0 ){\n            if( v==SMALLEST_INT64 ){\n              longvalue = ((u64)1)<<63;\n            }else{\n              longvalue = -v;\n            }\n            prefix = '-';\n          }else{\n            longvalue = v;\n            if( flag_plussign )        prefix = '+';\n            else if( flag_blanksign )  prefix = ' ';\n            else                       prefix = 0;\n          }\n        }else{\n          if( flag_longlong ){\n            longvalue = va_arg(ap,u64);\n          }else if( flag_long ){\n            longvalue = va_arg(ap,unsigned long int);\n          }else{\n            longvalue = va_arg(ap,unsigned int);\n          }\n          prefix = 0;\n        }\n        if( longvalue==0 ) flag_alternateform = 0;\n        if( flag_zeropad && precision<width-(prefix!=0) ){\n          precision = width-(prefix!=0);\n        }\n        if( precision<etBUFSIZE-10 ){\n          nOut = etBUFSIZE;\n          zOut = buf;\n        }else{\n          nOut = precision + 10;\n          zOut = zExtra = sqlite3Malloc( nOut );\n          if( zOut==0 ){\n            pAccum->mallocFailed = 1;\n            return;\n          }\n        }\n        bufpt = &zOut[nOut-1];\n        if( xtype==etORDINAL ){\n          static const char zOrd[] = \"thstndrd\";\n          int x = (int)(longvalue % 10);\n          if( x>=4 || (longvalue/10)%10==1 ){\n            x = 0;\n          }\n          *(--bufpt) = zOrd[x*2+1];\n          *(--bufpt) = zOrd[x*2];\n        }\n        {\n          register const char *cset;      /* Use registers for speed */\n          register int base;\n          cset = &aDigits[infop->charset];\n          base = infop->base;\n          do{                                           /* Convert to ascii */\n            *(--bufpt) = cset[longvalue%base];\n            longvalue = longvalue/base;\n          }while( longvalue>0 );\n        }\n        length = (int)(&zOut[nOut-1]-bufpt);\n        for(idx=precision-length; idx>0; idx--){\n          *(--bufpt) = '0';                             /* Zero pad */\n        }\n        if( prefix ) *(--bufpt) = prefix;               /* Add sign */\n        if( flag_alternateform && infop->prefix ){      /* Add \"0\" or \"0x\" */\n          const char *pre;\n          char x;\n          pre = &aPrefix[infop->prefix];\n          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;\n        }\n        length = (int)(&zOut[nOut-1]-bufpt);\n        break;\n      case etFLOAT:\n      case etEXP:\n      case etGENERIC:\n        realvalue = va_arg(ap,double);\n#ifdef SQLITE_OMIT_FLOATING_POINT\n        length = 0;\n#else\n        if( precision<0 ) precision = 6;         /* Set default precision */\n        if( realvalue<0.0 ){\n          realvalue = -realvalue;\n          prefix = '-';\n        }else{\n          if( flag_plussign )          prefix = '+';\n          else if( flag_blanksign )    prefix = ' ';\n          else                         prefix = 0;\n        }\n        if( xtype==etGENERIC && precision>0 ) precision--;\n#if 0\n        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */\n        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);\n#else\n        /* It makes more sense to use 0.5 */\n        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}\n#endif\n        if( xtype==etFLOAT ) realvalue += rounder;\n        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */\n        exp = 0;\n        if( sqlite3IsNaN((double)realvalue) ){\n          bufpt = \"NaN\";\n          length = 3;\n          break;\n        }\n        if( realvalue>0.0 ){\n          LONGDOUBLE_TYPE scale = 1.0;\n          while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}\n          while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }\n          while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }\n          while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }\n          realvalue /= scale;\n          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }\n          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }\n          if( exp>350 ){\n            if( prefix=='-' ){\n              bufpt = \"-Inf\";\n            }else if( prefix=='+' ){\n              bufpt = \"+Inf\";\n            }else{\n              bufpt = \"Inf\";\n            }\n            length = sqlite3Strlen30(bufpt);\n            break;\n          }\n        }\n        bufpt = buf;\n        /*\n        ** If the field type is etGENERIC, then convert to either etEXP\n        ** or etFLOAT, as appropriate.\n        */\n        if( xtype!=etFLOAT ){\n          realvalue += rounder;\n          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }\n        }\n        if( xtype==etGENERIC ){\n          flag_rtz = !flag_alternateform;\n          if( exp<-4 || exp>precision ){\n            xtype = etEXP;\n          }else{\n            precision = precision - exp;\n            xtype = etFLOAT;\n          }\n        }else{\n          flag_rtz = flag_altform2;\n        }\n        if( xtype==etEXP ){\n          e2 = 0;\n        }else{\n          e2 = exp;\n        }\n        if( e2+precision+width > etBUFSIZE - 15 ){\n          bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );\n          if( bufpt==0 ){\n            pAccum->mallocFailed = 1;\n            return;\n          }\n        }\n        zOut = bufpt;\n        nsd = 16 + flag_altform2*10;\n        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;\n        /* The sign in front of the number */\n        if( prefix ){\n          *(bufpt++) = prefix;\n        }\n        /* Digits prior to the decimal point */\n        if( e2<0 ){\n          *(bufpt++) = '0';\n        }else{\n          for(; e2>=0; e2--){\n            *(bufpt++) = et_getdigit(&realvalue,&nsd);\n          }\n        }\n        /* The decimal point */\n        if( flag_dp ){\n          *(bufpt++) = '.';\n        }\n        /* \"0\" digits after the decimal point but before the first\n        ** significant digit of the number */\n        for(e2++; e2<0; precision--, e2++){\n          assert( precision>0 );\n          *(bufpt++) = '0';\n        }\n        /* Significant digits after the decimal point */\n        while( (precision--)>0 ){\n          *(bufpt++) = et_getdigit(&realvalue,&nsd);\n        }\n        /* Remove trailing zeros and the \".\" if no digits follow the \".\" */\n        if( flag_rtz && flag_dp ){\n          while( bufpt[-1]=='0' ) *(--bufpt) = 0;\n          assert( bufpt>zOut );\n          if( bufpt[-1]=='.' ){\n            if( flag_altform2 ){\n              *(bufpt++) = '0';\n            }else{\n              *(--bufpt) = 0;\n            }\n          }\n        }\n        /* Add the \"eNNN\" suffix */\n        if( xtype==etEXP ){\n          *(bufpt++) = aDigits[infop->charset];\n          if( exp<0 ){\n            *(bufpt++) = '-'; exp = -exp;\n          }else{\n            *(bufpt++) = '+';\n          }\n          if( exp>=100 ){\n            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */\n            exp %= 100;\n          }\n          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */\n          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */\n        }\n        *bufpt = 0;\n\n        /* The converted number is in buf[] and zero terminated. Output it.\n        ** Note that the number is in the usual order, not reversed as with\n        ** integer conversions. */\n        length = (int)(bufpt-zOut);\n        bufpt = zOut;\n\n        /* Special case:  Add leading zeros if the flag_zeropad flag is\n        ** set and we are not left justified */\n        if( flag_zeropad && !flag_leftjustify && length < width){\n          int i;\n          int nPad = width - length;\n          for(i=width; i>=nPad; i--){\n            bufpt[i] = bufpt[i-nPad];\n          }\n          i = prefix!=0;\n          while( nPad-- ) bufpt[i++] = '0';\n          length = width;\n        }\n#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */\n        break;\n      case etSIZE:\n        *(va_arg(ap,int*)) = pAccum->nChar;\n        length = width = 0;\n        break;\n      case etPERCENT:\n        buf[0] = '%';\n        bufpt = buf;\n        length = 1;\n        break;\n      case etCHARX:\n        c = va_arg(ap,int);\n        buf[0] = (char)c;\n        if( precision>=0 ){\n          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;\n          length = precision;\n        }else{\n          length =1;\n        }\n        bufpt = buf;\n        break;\n      case etSTRING:\n      case etDYNSTRING:\n        bufpt = va_arg(ap,char*);\n        if( bufpt==0 ){\n          bufpt = \"\";\n        }else if( xtype==etDYNSTRING ){\n          zExtra = bufpt;\n        }\n        if( precision>=0 ){\n          for(length=0; length<precision && bufpt[length]; length++){}\n        }else{\n          length = sqlite3Strlen30(bufpt);\n        }\n        break;\n      case etSQLESCAPE:\n      case etSQLESCAPE2:\n      case etSQLESCAPE3: {\n        int i, j, k, n, isnull;\n        int needQuote;\n        char ch;\n        char q = ((xtype==etSQLESCAPE3)?'\"':'\\'');   /* Quote character */\n        char *escarg = va_arg(ap,char*);\n        isnull = escarg==0;\n        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? \"NULL\" : \"(NULL)\");\n        k = precision;\n        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){\n          if( ch==q )  n++;\n        }\n        needQuote = !isnull && xtype==etSQLESCAPE2;\n        n += i + 1 + needQuote*2;\n        if( n>etBUFSIZE ){\n          bufpt = zExtra = sqlite3Malloc( n );\n          if( bufpt==0 ){\n            pAccum->mallocFailed = 1;\n            return;\n          }\n        }else{\n          bufpt = buf;\n        }\n        j = 0;\n        if( needQuote ) bufpt[j++] = q;\n        k = i;\n        for(i=0; i<k; i++){\n          bufpt[j++] = ch = escarg[i];\n          if( ch==q ) bufpt[j++] = ch;\n        }\n        if( needQuote ) bufpt[j++] = q;\n        bufpt[j] = 0;\n        length = j;\n        /* The precision in %q and %Q means how many input characters to\n        ** consume, not the length of the output...\n        ** if( precision>=0 && precision<length ) length = precision; */\n        break;\n      }\n      case etTOKEN: {\n        Token *pToken = va_arg(ap, Token*);\n        if( pToken ){\n          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);\n        }\n        length = width = 0;\n        break;\n      }\n      case etSRCLIST: {\n        SrcList *pSrc = va_arg(ap, SrcList*);\n        int k = va_arg(ap, int);\n        struct SrcList_item *pItem = &pSrc->a[k];\n        assert( k>=0 && k<pSrc->nSrc );\n        if( pItem->zDatabase ){\n          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);\n          sqlite3StrAccumAppend(pAccum, \".\", 1);\n        }\n        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);\n        length = width = 0;\n        break;\n      }\n      default: {\n        assert( xtype==etINVALID );\n        return;\n      }\n    }/* End switch over the format type */\n    /*\n    ** The text of the conversion is pointed to by \"bufpt\" and is\n    ** \"length\" characters long.  The field width is \"width\".  Do\n    ** the output.\n    */\n    if( !flag_leftjustify ){\n      register int nspace;\n      nspace = width-length;\n      if( nspace>0 ){\n        sqlite3AppendSpace(pAccum, nspace);\n      }\n    }\n    if( length>0 ){\n      sqlite3StrAccumAppend(pAccum, bufpt, length);\n    }\n    if( flag_leftjustify ){\n      register int nspace;\n      nspace = width-length;\n      if( nspace>0 ){\n        sqlite3AppendSpace(pAccum, nspace);\n      }\n    }\n    sqlite3_free(zExtra);\n  }/* End for loop over the format string */\n} /* End of function */\n\n/*\n** Append N bytes of text from z to the StrAccum object.\n*/\nSQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){\n  assert( z!=0 || N==0 );\n  if( p->tooBig | p->mallocFailed ){\n    testcase(p->tooBig);\n    testcase(p->mallocFailed);\n    return;\n  }\n  assert( p->zText!=0 || p->nChar==0 );\n  if( N<0 ){\n    N = sqlite3Strlen30(z);\n  }\n  if( N==0 || NEVER(z==0) ){\n    return;\n  }\n  if( p->nChar+N >= p->nAlloc ){\n    char *zNew;\n    if( !p->useMalloc ){\n      p->tooBig = 1;\n      N = p->nAlloc - p->nChar - 1;\n      if( N<=0 ){\n        return;\n      }\n    }else{\n      char *zOld = (p->zText==p->zBase ? 0 : p->zText);\n      i64 szNew = p->nChar;\n      szNew += N + 1;\n      if( szNew > p->mxAlloc ){\n        sqlite3StrAccumReset(p);\n        p->tooBig = 1;\n        return;\n      }else{\n        p->nAlloc = (int)szNew;\n      }\n      if( p->useMalloc==1 ){\n        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);\n      }else{\n        zNew = sqlite3_realloc(zOld, p->nAlloc);\n      }\n      if( zNew ){\n        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);\n        p->zText = zNew;\n      }else{\n        p->mallocFailed = 1;\n        sqlite3StrAccumReset(p);\n        return;\n      }\n    }\n  }\n  assert( p->zText );\n  memcpy(&p->zText[p->nChar], z, N);\n  p->nChar += N;\n}\n\n/*\n** Finish off a string by making sure it is zero-terminated.\n** Return a pointer to the resulting string.  Return a NULL\n** pointer if any kind of error was encountered.\n*/\nSQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){\n  if( p->zText ){\n    p->zText[p->nChar] = 0;\n    if( p->useMalloc && p->zText==p->zBase ){\n      if( p->useMalloc==1 ){\n        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );\n      }else{\n        p->zText = sqlite3_malloc(p->nChar+1);\n      }\n      if( p->zText ){\n        memcpy(p->zText, p->zBase, p->nChar+1);\n      }else{\n        p->mallocFailed = 1;\n      }\n    }\n  }\n  return p->zText;\n}\n\n/*\n** Reset an StrAccum string.  Reclaim all malloced memory.\n*/\nSQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){\n  if( p->zText!=p->zBase ){\n    if( p->useMalloc==1 ){\n      sqlite3DbFree(p->db, p->zText);\n    }else{\n      sqlite3_free(p->zText);\n    }\n  }\n  p->zText = 0;\n}\n\n/*\n** Initialize a string accumulator\n*/\nSQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){\n  p->zText = p->zBase = zBase;\n  p->db = 0;\n  p->nChar = 0;\n  p->nAlloc = n;\n  p->mxAlloc = mx;\n  p->useMalloc = 1;\n  p->tooBig = 0;\n  p->mallocFailed = 0;\n}\n\n/*\n** Print into memory obtained from sqliteMalloc().  Use the internal\n** %-conversion extensions.\n*/\nSQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){\n  char *z;\n  char zBase[SQLITE_PRINT_BUF_SIZE];\n  StrAccum acc;\n  assert( db!=0 );\n  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),\n                      db->aLimit[SQLITE_LIMIT_LENGTH]);\n  acc.db = db;\n  sqlite3VXPrintf(&acc, 1, zFormat, ap);\n  z = sqlite3StrAccumFinish(&acc);\n  if( acc.mallocFailed ){\n    db->mallocFailed = 1;\n  }\n  return z;\n}\n\n/*\n** Print into memory obtained from sqliteMalloc().  Use the internal\n** %-conversion extensions.\n*/\nSQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){\n  va_list ap;\n  char *z;\n  va_start(ap, zFormat);\n  z = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting\n** the string and before returnning.  This routine is intended to be used\n** to modify an existing string.  For example:\n**\n**       x = sqlite3MPrintf(db, x, \"prefix %s suffix\", x);\n**\n*/\nSQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){\n  va_list ap;\n  char *z;\n  va_start(ap, zFormat);\n  z = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  sqlite3DbFree(db, zStr);\n  return z;\n}\n\n/*\n** Print into memory obtained from sqlite3_malloc().  Omit the internal\n** %-conversion extensions.\n*/\nSQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){\n  char *z;\n  char zBase[SQLITE_PRINT_BUF_SIZE];\n  StrAccum acc;\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);\n  acc.useMalloc = 2;\n  sqlite3VXPrintf(&acc, 0, zFormat, ap);\n  z = sqlite3StrAccumFinish(&acc);\n  return z;\n}\n\n/*\n** Print into memory obtained from sqlite3_malloc()().  Omit the internal\n** %-conversion extensions.\n*/\nSQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){\n  va_list ap;\n  char *z;\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize() ) return 0;\n#endif\n  va_start(ap, zFormat);\n  z = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** sqlite3_snprintf() works like snprintf() except that it ignores the\n** current locale settings.  This is important for SQLite because we\n** are not able to use a \",\" as the decimal point in place of \".\" as\n** specified by some locales.\n**\n** Oops:  The first two arguments of sqlite3_snprintf() are backwards\n** from the snprintf() standard.  Unfortunately, it is too late to change\n** this without breaking compatibility, so we just have to live with the\n** mistake.\n**\n** sqlite3_vsnprintf() is the varargs version.\n*/\nSQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){\n  StrAccum acc;\n  if( n<=0 ) return zBuf;\n  sqlite3StrAccumInit(&acc, zBuf, n, 0);\n  acc.useMalloc = 0;\n  sqlite3VXPrintf(&acc, 0, zFormat, ap);\n  return sqlite3StrAccumFinish(&acc);\n}\nSQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){\n  char *z;\n  va_list ap;\n  va_start(ap,zFormat);\n  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);\n  va_end(ap);\n  return z;\n}\n\n/*\n** This is the routine that actually formats the sqlite3_log() message.\n** We house it in a separate routine from sqlite3_log() to avoid using\n** stack space on small-stack systems when logging is disabled.\n**\n** sqlite3_log() must render into a static buffer.  It cannot dynamically\n** allocate memory because it might be called while the memory allocator\n** mutex is held.\n*/\nstatic void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){\n  StrAccum acc;                          /* String accumulator */\n  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */\n\n  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);\n  acc.useMalloc = 0;\n  sqlite3VXPrintf(&acc, 0, zFormat, ap);\n  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,\n                           sqlite3StrAccumFinish(&acc));\n}\n\n/*\n** Format and write a message to the log if logging is enabled.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){\n  va_list ap;                             /* Vararg list */\n  if( sqlite3GlobalConfig.xLog ){\n    va_start(ap, zFormat);\n    renderLogMsg(iErrCode, zFormat, ap);\n    va_end(ap);\n  }\n}\n\n#if defined(SQLITE_DEBUG)\n/*\n** A version of printf() that understands %lld.  Used for debugging.\n** The printf() built into some versions of windows does not understand %lld\n** and segfaults if you give it a long long int.\n*/\nSQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){\n  va_list ap;\n  StrAccum acc;\n  char zBuf[500];\n  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);\n  acc.useMalloc = 0;\n  va_start(ap,zFormat);\n  sqlite3VXPrintf(&acc, 0, zFormat, ap);\n  va_end(ap);\n  sqlite3StrAccumFinish(&acc);\n  fprintf(stdout,\"%s\", zBuf);\n  fflush(stdout);\n}\n#endif\n\n#ifndef SQLITE_OMIT_TRACE\n/*\n** variable-argument wrapper around sqlite3VXPrintf().\n*/\nSQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){\n  va_list ap;\n  va_start(ap,zFormat);\n  sqlite3VXPrintf(p, 1, zFormat, ap);\n  va_end(ap);\n}\n#endif\n\n/************** End of printf.c **********************************************/\n/************** Begin file random.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code to implement a pseudo-random number\n** generator (PRNG) for SQLite.\n**\n** Random numbers are used by some of the database backends in order\n** to generate random integer keys for tables or random filenames.\n*/\n\n\n/* All threads share a single random number generator.\n** This structure is the current state of the generator.\n*/\nstatic SQLITE_WSD struct sqlite3PrngType {\n  unsigned char isInit;          /* True if initialized */\n  unsigned char i, j;            /* State variables */\n  unsigned char s[256];          /* State variables */\n} sqlite3Prng;\n\n/*\n** Get a single 8-bit random value from the RC4 PRNG.  The Mutex\n** must be held while executing this routine.\n**\n** Why not just use a library random generator like lrand48() for this?\n** Because the OP_NewRowid opcode in the VDBE depends on having a very\n** good source of random numbers.  The lrand48() library function may\n** well be good enough.  But maybe not.  Or maybe lrand48() has some\n** subtle problems on some systems that could cause problems.  It is hard\n** to know.  To minimize the risk of problems due to bad lrand48()\n** implementations, SQLite uses this random number generator based\n** on RC4, which we know works very well.\n**\n** (Later):  Actually, OP_NewRowid does not depend on a good source of\n** randomness any more.  But we will leave this code in all the same.\n*/\nstatic u8 randomByte(void){\n  unsigned char t;\n\n\n  /* The \"wsdPrng\" macro will resolve to the pseudo-random number generator\n  ** state vector.  If writable static data is unsupported on the target,\n  ** we have to locate the state vector at run-time.  In the more common\n  ** case where writable static data is supported, wsdPrng can refer directly\n  ** to the \"sqlite3Prng\" state vector declared above.\n  */\n#ifdef SQLITE_OMIT_WSD\n  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);\n# define wsdPrng p[0]\n#else\n# define wsdPrng sqlite3Prng\n#endif\n\n\n  /* Initialize the state of the random number generator once,\n  ** the first time this routine is called.  The seed value does\n  ** not need to contain a lot of randomness since we are not\n  ** trying to do secure encryption or anything like that...\n  **\n  ** Nothing in this file or anywhere else in SQLite does any kind of\n  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random\n  ** number generator) not as an encryption device.\n  */\n  if( !wsdPrng.isInit ){\n    int i;\n    char k[256];\n    wsdPrng.j = 0;\n    wsdPrng.i = 0;\n    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);\n    for(i=0; i<256; i++){\n      wsdPrng.s[i] = (u8)i;\n    }\n    for(i=0; i<256; i++){\n      wsdPrng.j += wsdPrng.s[i] + k[i];\n      t = wsdPrng.s[wsdPrng.j];\n      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];\n      wsdPrng.s[i] = t;\n    }\n    wsdPrng.isInit = 1;\n  }\n\n  /* Generate and return single random byte\n  */\n  wsdPrng.i++;\n  t = wsdPrng.s[wsdPrng.i];\n  wsdPrng.j += t;\n  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];\n  wsdPrng.s[wsdPrng.j] = t;\n  t += wsdPrng.s[wsdPrng.i];\n  return wsdPrng.s[t];\n}\n\n/*\n** Return N random bytes.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *pBuf){\n  unsigned char *zBuf = pBuf;\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);\n#endif\n  sqlite3_mutex_enter(mutex);\n  while( N-- ){\n    *(zBuf++) = randomByte();\n  }\n  sqlite3_mutex_leave(mutex);\n}\n\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n/*\n** For testing purposes, we sometimes want to preserve the state of\n** PRNG and restore the PRNG to its saved state at a later time, or\n** to reset the PRNG to its initial state.  These routines accomplish\n** those tasks.\n**\n** The sqlite3_test_control() interface calls these routines to\n** control the PRNG.\n*/\nstatic SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;\nSQLITE_PRIVATE void sqlite3PrngSaveState(void){\n  memcpy(\n    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),\n    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),\n    sizeof(sqlite3Prng)\n  );\n}\nSQLITE_PRIVATE void sqlite3PrngRestoreState(void){\n  memcpy(\n    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),\n    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),\n    sizeof(sqlite3Prng)\n  );\n}\nSQLITE_PRIVATE void sqlite3PrngResetState(void){\n  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;\n}\n#endif /* SQLITE_OMIT_BUILTIN_TEST */\n\n/************** End of random.c **********************************************/\n/************** Begin file utf.c *********************************************/\n/*\n** 2004 April 13\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used to translate between UTF-8, \n** UTF-16, UTF-16BE, and UTF-16LE.\n**\n** Notes on UTF-8:\n**\n**   Byte-0    Byte-1    Byte-2    Byte-3    Value\n**  0xxxxxxx                                 00000000 00000000 0xxxxxxx\n**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx\n**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx\n**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx\n**\n**\n** Notes on UTF-16:  (with wwww+1==uuuuu)\n**\n**      Word-0               Word-1          Value\n**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx\n**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx\n**\n**\n** BOM or Byte Order Mark:\n**     0xff 0xfe   little-endian utf-16 follows\n**     0xfe 0xff   big-endian utf-16 follows\n**\n*/\n/* #include <assert.h> */\n\n#ifndef SQLITE_AMALGAMATION\n/*\n** The following constant value is used by the SQLITE_BIGENDIAN and\n** SQLITE_LITTLEENDIAN macros.\n*/\nSQLITE_PRIVATE const int sqlite3one = 1;\n#endif /* SQLITE_AMALGAMATION */\n\n/*\n** This lookup table is used to help decode the first byte of\n** a multi-byte UTF8 character.\n*/\nstatic const unsigned char sqlite3Utf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n\n#define WRITE_UTF8(zOut, c) {                          \\\n  if( c<0x00080 ){                                     \\\n    *zOut++ = (u8)(c&0xFF);                            \\\n  }                                                    \\\n  else if( c<0x00800 ){                                \\\n    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n  else if( c<0x10000 ){                                \\\n    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }else{                                               \\\n    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \\\n    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n}\n\n#define WRITE_UTF16LE(zOut, c) {                                    \\\n  if( c<=0xFFFF ){                                                  \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n    *zOut++ = (u8)((c>>8)&0x00FF);                                  \\\n  }else{                                                            \\\n    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \\\n    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \\\n  }                                                                 \\\n}\n\n#define WRITE_UTF16BE(zOut, c) {                                    \\\n  if( c<=0xFFFF ){                                                  \\\n    *zOut++ = (u8)((c>>8)&0x00FF);                                  \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n  }else{                                                            \\\n    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \\\n    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \\\n    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \\\n    *zOut++ = (u8)(c&0x00FF);                                       \\\n  }                                                                 \\\n}\n\n#define READ_UTF16LE(zIn, TERM, c){                                   \\\n  c = (*zIn++);                                                       \\\n  c += ((*zIn++)<<8);                                                 \\\n  if( c>=0xD800 && c<0xE000 && TERM ){                                \\\n    int c2 = (*zIn++);                                                \\\n    c2 += ((*zIn++)<<8);                                              \\\n    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \\\n  }                                                                   \\\n}\n\n#define READ_UTF16BE(zIn, TERM, c){                                   \\\n  c = ((*zIn++)<<8);                                                  \\\n  c += (*zIn++);                                                      \\\n  if( c>=0xD800 && c<0xE000 && TERM ){                                \\\n    int c2 = ((*zIn++)<<8);                                           \\\n    c2 += (*zIn++);                                                   \\\n    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \\\n  }                                                                   \\\n}\n\n/*\n** Translate a single UTF-8 character.  Return the unicode value.\n**\n** During translation, assume that the byte that zTerm points\n** is a 0x00.\n**\n** Write a pointer to the next unread byte back into *pzNext.\n**\n** Notes On Invalid UTF-8:\n**\n**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to\n**     be encoded as a multi-byte character.  Any multi-byte character that\n**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.\n**\n**  *  This routine never allows a UTF16 surrogate value to be encoded.\n**     If a multi-byte character attempts to encode a value between\n**     0xd800 and 0xe000 then it is rendered as 0xfffd.\n**\n**  *  Bytes in the range of 0x80 through 0xbf which occur as the first\n**     byte of a character are interpreted as single-byte characters\n**     and rendered as themselves even though they are technically\n**     invalid characters.\n**\n**  *  This routine accepts an infinite number of different UTF8 encodings\n**     for unicode values 0x80 and greater.  It do not change over-length\n**     encodings to 0xfffd as some systems recommend.\n*/\n#define READ_UTF8(zIn, zTerm, c)                           \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = sqlite3Utf8Trans1[c-0xc0];                         \\\n    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n    if( c<0x80                                             \\\n        || (c&0xFFFFF800)==0xD800                          \\\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \\\n  }\nSQLITE_PRIVATE u32 sqlite3Utf8Read(\n  const unsigned char *zIn,       /* First byte of UTF-8 character */\n  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */\n){\n  unsigned int c;\n\n  /* Same as READ_UTF8() above but without the zTerm parameter.\n  ** For this routine, we assume the UTF8 string is always zero-terminated.\n  */\n  c = *(zIn++);\n  if( c>=0xc0 ){\n    c = sqlite3Utf8Trans1[c-0xc0];\n    while( (*zIn & 0xc0)==0x80 ){\n      c = (c<<6) + (0x3f & *(zIn++));\n    }\n    if( c<0x80\n        || (c&0xFFFFF800)==0xD800\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }\n  }\n  *pzNext = zIn;\n  return c;\n}\n\n\n\n\n/*\n** If the TRANSLATE_TRACE macro is defined, the value of each Mem is\n** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().\n*/ \n/* #define TRANSLATE_TRACE 1 */\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** This routine transforms the internal text encoding used by pMem to\n** desiredEnc. It is an error if the string is already of the desired\n** encoding, or if *pMem does not contain a string value.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){\n  int len;                    /* Maximum length of output string in bytes */\n  unsigned char *zOut;                  /* Output buffer */\n  unsigned char *zIn;                   /* Input iterator */\n  unsigned char *zTerm;                 /* End of input */\n  unsigned char *z;                     /* Output iterator */\n  unsigned int c;\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( pMem->flags&MEM_Str );\n  assert( pMem->enc!=desiredEnc );\n  assert( pMem->enc!=0 );\n  assert( pMem->n>=0 );\n\n#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)\n  {\n    char zBuf[100];\n    sqlite3VdbeMemPrettyPrint(pMem, zBuf);\n    fprintf(stderr, \"INPUT:  %s\\n\", zBuf);\n  }\n#endif\n\n  /* If the translation is between UTF-16 little and big endian, then \n  ** all that is required is to swap the byte order. This case is handled\n  ** differently from the others.\n  */\n  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){\n    u8 temp;\n    int rc;\n    rc = sqlite3VdbeMemMakeWriteable(pMem);\n    if( rc!=SQLITE_OK ){\n      assert( rc==SQLITE_NOMEM );\n      return SQLITE_NOMEM;\n    }\n    zIn = (u8*)pMem->z;\n    zTerm = &zIn[pMem->n&~1];\n    while( zIn<zTerm ){\n      temp = *zIn;\n      *zIn = *(zIn+1);\n      zIn++;\n      *zIn++ = temp;\n    }\n    pMem->enc = desiredEnc;\n    goto translate_out;\n  }\n\n  /* Set len to the maximum number of bytes required in the output buffer. */\n  if( desiredEnc==SQLITE_UTF8 ){\n    /* When converting from UTF-16, the maximum growth results from\n    ** translating a 2-byte character to a 4-byte UTF-8 character.\n    ** A single byte is required for the output string\n    ** nul-terminator.\n    */\n    pMem->n &= ~1;\n    len = pMem->n * 2 + 1;\n  }else{\n    /* When converting from UTF-8 to UTF-16 the maximum growth is caused\n    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16\n    ** character. Two bytes are required in the output buffer for the\n    ** nul-terminator.\n    */\n    len = pMem->n * 2 + 2;\n  }\n\n  /* Set zIn to point at the start of the input buffer and zTerm to point 1\n  ** byte past the end.\n  **\n  ** Variable zOut is set to point at the output buffer, space obtained\n  ** from sqlite3_malloc().\n  */\n  zIn = (u8*)pMem->z;\n  zTerm = &zIn[pMem->n];\n  zOut = sqlite3DbMallocRaw(pMem->db, len);\n  if( !zOut ){\n    return SQLITE_NOMEM;\n  }\n  z = zOut;\n\n  if( pMem->enc==SQLITE_UTF8 ){\n    if( desiredEnc==SQLITE_UTF16LE ){\n      /* UTF-8 -> UTF-16 Little-endian */\n      while( zIn<zTerm ){\n        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */\n        READ_UTF8(zIn, zTerm, c);\n        WRITE_UTF16LE(z, c);\n      }\n    }else{\n      assert( desiredEnc==SQLITE_UTF16BE );\n      /* UTF-8 -> UTF-16 Big-endian */\n      while( zIn<zTerm ){\n        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */\n        READ_UTF8(zIn, zTerm, c);\n        WRITE_UTF16BE(z, c);\n      }\n    }\n    pMem->n = (int)(z - zOut);\n    *z++ = 0;\n  }else{\n    assert( desiredEnc==SQLITE_UTF8 );\n    if( pMem->enc==SQLITE_UTF16LE ){\n      /* UTF-16 Little-endian -> UTF-8 */\n      while( zIn<zTerm ){\n        READ_UTF16LE(zIn, zIn<zTerm, c); \n        WRITE_UTF8(z, c);\n      }\n    }else{\n      /* UTF-16 Big-endian -> UTF-8 */\n      while( zIn<zTerm ){\n        READ_UTF16BE(zIn, zIn<zTerm, c); \n        WRITE_UTF8(z, c);\n      }\n    }\n    pMem->n = (int)(z - zOut);\n  }\n  *z = 0;\n  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );\n\n  sqlite3VdbeMemRelease(pMem);\n  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);\n  pMem->enc = desiredEnc;\n  pMem->flags |= (MEM_Term|MEM_Dyn);\n  pMem->z = (char*)zOut;\n  pMem->zMalloc = pMem->z;\n\ntranslate_out:\n#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)\n  {\n    char zBuf[100];\n    sqlite3VdbeMemPrettyPrint(pMem, zBuf);\n    fprintf(stderr, \"OUTPUT: %s\\n\", zBuf);\n  }\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** This routine checks for a byte-order mark at the beginning of the \n** UTF-16 string stored in *pMem. If one is present, it is removed and\n** the encoding of the Mem adjusted. This routine does not do any\n** byte-swapping, it just sets Mem.enc appropriately.\n**\n** The allocation (static, dynamic etc.) and encoding of the Mem may be\n** changed by this function.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){\n  int rc = SQLITE_OK;\n  u8 bom = 0;\n\n  assert( pMem->n>=0 );\n  if( pMem->n>1 ){\n    u8 b1 = *(u8 *)pMem->z;\n    u8 b2 = *(((u8 *)pMem->z) + 1);\n    if( b1==0xFE && b2==0xFF ){\n      bom = SQLITE_UTF16BE;\n    }\n    if( b1==0xFF && b2==0xFE ){\n      bom = SQLITE_UTF16LE;\n    }\n  }\n  \n  if( bom ){\n    rc = sqlite3VdbeMemMakeWriteable(pMem);\n    if( rc==SQLITE_OK ){\n      pMem->n -= 2;\n      memmove(pMem->z, &pMem->z[2], pMem->n);\n      pMem->z[pMem->n] = '\\0';\n      pMem->z[pMem->n+1] = '\\0';\n      pMem->flags |= MEM_Term;\n      pMem->enc = bom;\n    }\n  }\n  return rc;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,\n** return the number of unicode characters in pZ up to (but not including)\n** the first 0x00 byte. If nByte is not less than zero, return the\n** number of unicode characters in the first nByte of pZ (or up to \n** the first 0x00, whichever comes first).\n*/\nSQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){\n  int r = 0;\n  const u8 *z = (const u8*)zIn;\n  const u8 *zTerm;\n  if( nByte>=0 ){\n    zTerm = &z[nByte];\n  }else{\n    zTerm = (const u8*)(-1);\n  }\n  assert( z<=zTerm );\n  while( *z!=0 && z<zTerm ){\n    SQLITE_SKIP_UTF8(z);\n    r++;\n  }\n  return r;\n}\n\n/* This test function is not currently used by the automated test-suite. \n** Hence it is only available in debug builds.\n*/\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n/*\n** Translate UTF-8 to UTF-8.\n**\n** This has the effect of making sure that the string is well-formed\n** UTF-8.  Miscoded characters are removed.\n**\n** The translation is done in-place and aborted if the output\n** overruns the input.\n*/\nSQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){\n  unsigned char *zOut = zIn;\n  unsigned char *zStart = zIn;\n  u32 c;\n\n  while( zIn[0] && zOut<=zIn ){\n    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);\n    if( c!=0xfffd ){\n      WRITE_UTF8(zOut, c);\n    }\n  }\n  *zOut = 0;\n  return (int)(zOut - zStart);\n}\n#endif\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Convert a UTF-16 string in the native encoding into a UTF-8 string.\n** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must\n** be freed by the calling function.\n**\n** NULL is returned if there is an allocation error.\n*/\nSQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){\n  Mem m;\n  memset(&m, 0, sizeof(m));\n  m.db = db;\n  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);\n  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);\n  if( db->mallocFailed ){\n    sqlite3VdbeMemRelease(&m);\n    m.z = 0;\n  }\n  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );\n  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );\n  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );\n  assert( m.z || db->mallocFailed );\n  return m.z;\n}\n\n/*\n** Convert a UTF-8 string to the UTF-16 encoding specified by parameter\n** enc. A pointer to the new string is returned, and the value of *pnOut\n** is set to the length of the returned string in bytes. The call should\n** arrange to call sqlite3DbFree() on the returned pointer when it is\n** no longer required.\n** \n** If a malloc failure occurs, NULL is returned and the db.mallocFailed\n** flag set.\n*/\n#ifdef SQLITE_ENABLE_STAT3\nSQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){\n  Mem m;\n  memset(&m, 0, sizeof(m));\n  m.db = db;\n  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);\n  if( sqlite3VdbeMemTranslate(&m, enc) ){\n    assert( db->mallocFailed );\n    return 0;\n  }\n  assert( m.z==m.zMalloc );\n  *pnOut = m.n;\n  return m.z;\n}\n#endif\n\n/*\n** zIn is a UTF-16 encoded unicode string at least nChar characters long.\n** Return the number of bytes in the first nChar unicode characters\n** in pZ.  nChar must be non-negative.\n*/\nSQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){\n  int c;\n  unsigned char const *z = zIn;\n  int n = 0;\n  \n  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){\n    while( n<nChar ){\n      READ_UTF16BE(z, 1, c);\n      n++;\n    }\n  }else{\n    while( n<nChar ){\n      READ_UTF16LE(z, 1, c);\n      n++;\n    }\n  }\n  return (int)(z-(unsigned char const *)zIn);\n}\n\n#if defined(SQLITE_TEST)\n/*\n** This routine is called from the TCL test function \"translate_selftest\".\n** It checks that the primitives for serializing and deserializing\n** characters in each encoding are inverses of each other.\n*/\nSQLITE_PRIVATE void sqlite3UtfSelfTest(void){\n  unsigned int i, t;\n  unsigned char zBuf[20];\n  unsigned char *z;\n  int n;\n  unsigned int c;\n\n  for(i=0; i<0x00110000; i++){\n    z = zBuf;\n    WRITE_UTF8(z, i);\n    n = (int)(z-zBuf);\n    assert( n>0 && n<=4 );\n    z[0] = 0;\n    z = zBuf;\n    c = sqlite3Utf8Read(z, (const u8**)&z);\n    t = i;\n    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;\n    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;\n    assert( c==t );\n    assert( (z-zBuf)==n );\n  }\n  for(i=0; i<0x00110000; i++){\n    if( i>=0xD800 && i<0xE000 ) continue;\n    z = zBuf;\n    WRITE_UTF16LE(z, i);\n    n = (int)(z-zBuf);\n    assert( n>0 && n<=4 );\n    z[0] = 0;\n    z = zBuf;\n    READ_UTF16LE(z, 1, c);\n    assert( c==i );\n    assert( (z-zBuf)==n );\n  }\n  for(i=0; i<0x00110000; i++){\n    if( i>=0xD800 && i<0xE000 ) continue;\n    z = zBuf;\n    WRITE_UTF16BE(z, i);\n    n = (int)(z-zBuf);\n    assert( n>0 && n<=4 );\n    z[0] = 0;\n    z = zBuf;\n    READ_UTF16BE(z, 1, c);\n    assert( c==i );\n    assert( (z-zBuf)==n );\n  }\n}\n#endif /* SQLITE_TEST */\n#endif /* SQLITE_OMIT_UTF16 */\n\n/************** End of utf.c *************************************************/\n/************** Begin file util.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Utility functions used throughout sqlite.\n**\n** This file contains functions for allocating memory, comparing\n** strings, and stuff like that.\n**\n*/\n/* #include <stdarg.h> */\n#ifdef SQLITE_HAVE_ISNAN\n# include <math.h>\n#endif\n\n/*\n** Routine needed to support the testcase() macro.\n*/\n#ifdef SQLITE_COVERAGE_TEST\nSQLITE_PRIVATE void sqlite3Coverage(int x){\n  static unsigned dummy = 0;\n  dummy += (unsigned)x;\n}\n#endif\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Return true if the floating point value is Not a Number (NaN).\n**\n** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.\n** Otherwise, we have our own implementation that works on most systems.\n*/\nSQLITE_PRIVATE int sqlite3IsNaN(double x){\n  int rc;   /* The value return */\n#if !defined(SQLITE_HAVE_ISNAN)\n  /*\n  ** Systems that support the isnan() library function should probably\n  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have\n  ** found that many systems do not have a working isnan() function so\n  ** this implementation is provided as an alternative.\n  **\n  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.\n  ** On the other hand, the use of -ffast-math comes with the following\n  ** warning:\n  **\n  **      This option [-ffast-math] should never be turned on by any\n  **      -O option since it can result in incorrect output for programs\n  **      which depend on an exact implementation of IEEE or ISO \n  **      rules/specifications for math functions.\n  **\n  ** Under MSVC, this NaN test may fail if compiled with a floating-\n  ** point precision mode other than /fp:precise.  From the MSDN \n  ** documentation:\n  **\n  **      The compiler [with /fp:precise] will properly handle comparisons \n  **      involving NaN. For example, x != x evaluates to true if x is NaN \n  **      ...\n  */\n#ifdef __FAST_MATH__\n# error SQLite will not work correctly with the -ffast-math option of GCC.\n#endif\n  volatile double y = x;\n  volatile double z = y;\n  rc = (y!=z);\n#else  /* if defined(SQLITE_HAVE_ISNAN) */\n  rc = isnan(x);\n#endif /* SQLITE_HAVE_ISNAN */\n  testcase( rc );\n  return rc;\n}\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n\n/*\n** Compute a string length that is limited to what can be stored in\n** lower 30 bits of a 32-bit signed integer.\n**\n** The value returned will never be negative.  Nor will it ever be greater\n** than the actual length of the string.  For very long strings (greater\n** than 1GiB) the value returned might be less than the true string length.\n*/\nSQLITE_PRIVATE int sqlite3Strlen30(const char *z){\n  const char *z2 = z;\n  if( z==0 ) return 0;\n  while( *z2 ){ z2++; }\n  return 0x3fffffff & (int)(z2 - z);\n}\n\n/*\n** Set the most recent error code and error string for the sqlite\n** handle \"db\". The error code is set to \"err_code\".\n**\n** If it is not NULL, string zFormat specifies the format of the\n** error string in the style of the printf functions: The following\n** format characters are allowed:\n**\n**      %s      Insert a string\n**      %z      A string that should be freed after use\n**      %d      Insert an integer\n**      %T      Insert a token\n**      %S      Insert the first element of a SrcList\n**\n** zFormat and any string tokens that follow it are assumed to be\n** encoded in UTF-8.\n**\n** To clear the most recent error for sqlite handle \"db\", sqlite3Error\n** should be called with err_code set to SQLITE_OK and zFormat set\n** to NULL.\n*/\nSQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){\n  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){\n    db->errCode = err_code;\n    if( zFormat ){\n      char *z;\n      va_list ap;\n      va_start(ap, zFormat);\n      z = sqlite3VMPrintf(db, zFormat, ap);\n      va_end(ap);\n      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);\n    }else{\n      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);\n    }\n  }\n}\n\n/*\n** Add an error message to pParse->zErrMsg and increment pParse->nErr.\n** The following formatting characters are allowed:\n**\n**      %s      Insert a string\n**      %z      A string that should be freed after use\n**      %d      Insert an integer\n**      %T      Insert a token\n**      %S      Insert the first element of a SrcList\n**\n** This function should be used to report any error that occurs whilst\n** compiling an SQL statement (i.e. within sqlite3_prepare()). The\n** last thing the sqlite3_prepare() function does is copy the error\n** stored by this function into the database handle using sqlite3Error().\n** Function sqlite3Error() should be used during statement execution\n** (sqlite3_step() etc.).\n*/\nSQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){\n  char *zMsg;\n  va_list ap;\n  sqlite3 *db = pParse->db;\n  va_start(ap, zFormat);\n  zMsg = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  if( db->suppressErr ){\n    sqlite3DbFree(db, zMsg);\n  }else{\n    pParse->nErr++;\n    sqlite3DbFree(db, pParse->zErrMsg);\n    pParse->zErrMsg = zMsg;\n    pParse->rc = SQLITE_ERROR;\n  }\n}\n\n/*\n** Convert an SQL-style quoted string into a normal string by removing\n** the quote characters.  The conversion is done in-place.  If the\n** input does not begin with a quote character, then this routine\n** is a no-op.\n**\n** The input string must be zero-terminated.  A new zero-terminator\n** is added to the dequoted string.\n**\n** The return value is -1 if no dequoting occurs or the length of the\n** dequoted string, exclusive of the zero terminator, if dequoting does\n** occur.\n**\n** 2002-Feb-14: This routine is extended to remove MS-Access style\n** brackets from around identifers.  For example:  \"[a-b-c]\" becomes\n** \"a-b-c\".\n*/\nSQLITE_PRIVATE int sqlite3Dequote(char *z){\n  char quote;\n  int i, j;\n  if( z==0 ) return -1;\n  quote = z[0];\n  switch( quote ){\n    case '\\'':  break;\n    case '\"':   break;\n    case '`':   break;                /* For MySQL compatibility */\n    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */\n    default:    return -1;\n  }\n  for(i=1, j=0; ALWAYS(z[i]); i++){\n    if( z[i]==quote ){\n      if( z[i+1]==quote ){\n        z[j++] = quote;\n        i++;\n      }else{\n        break;\n      }\n    }else{\n      z[j++] = z[i];\n    }\n  }\n  z[j] = 0;\n  return j;\n}\n\n/* Convenient short-hand */\n#define UpperToLower sqlite3UpperToLower\n\n/*\n** Some systems have stricmp().  Others have strcasecmp().  Because\n** there is no consistency, we will define our own.\n**\n** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and\n** sqlite3_strnicmp() APIs allow applications and extensions to compare\n** the contents of two buffers containing UTF-8 strings in a\n** case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){\n  register unsigned char *a, *b;\n  a = (unsigned char *)zLeft;\n  b = (unsigned char *)zRight;\n  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }\n  return UpperToLower[*a] - UpperToLower[*b];\n}\nSQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){\n  register unsigned char *a, *b;\n  a = (unsigned char *)zLeft;\n  b = (unsigned char *)zRight;\n  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }\n  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];\n}\n\n/*\n** The string z[] is an text representation of a real number.\n** Convert this string to a double and write it into *pResult.\n**\n** The string z[] is length bytes in length (bytes, not characters) and\n** uses the encoding enc.  The string is not necessarily zero-terminated.\n**\n** Return TRUE if the result is a valid real number (or integer) and FALSE\n** if the string is empty or contains extraneous text.  Valid numbers\n** are in one of these formats:\n**\n**    [+-]digits[E[+-]digits]\n**    [+-]digits.[digits][E[+-]digits]\n**    [+-].digits[E[+-]digits]\n**\n** Leading and trailing whitespace is ignored for the purpose of determining\n** validity.\n**\n** If some prefix of the input string is a valid number, this routine\n** returns FALSE but it still converts the prefix and writes the result\n** into *pResult.\n*/\nSQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  int incr = (enc==SQLITE_UTF8?1:2);\n  const char *zEnd = z + length;\n  /* sign * significand * (10 ^ (esign * exponent)) */\n  int sign = 1;    /* sign of significand */\n  i64 s = 0;       /* significand */\n  int d = 0;       /* adjust exponent for shifting decimal point */\n  int esign = 1;   /* sign of exponent */\n  int e = 0;       /* exponent */\n  int eValid = 1;  /* True exponent is either not used or is well-formed */\n  double result;\n  int nDigits = 0;\n\n  *pResult = 0.0;   /* Default return value, in case of an error */\n\n  if( enc==SQLITE_UTF16BE ) z++;\n\n  /* skip leading spaces */\n  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;\n  if( z>=zEnd ) return 0;\n\n  /* get sign of significand */\n  if( *z=='-' ){\n    sign = -1;\n    z+=incr;\n  }else if( *z=='+' ){\n    z+=incr;\n  }\n\n  /* skip leading zeroes */\n  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;\n\n  /* copy max significant digits to significand */\n  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){\n    s = s*10 + (*z - '0');\n    z+=incr, nDigits++;\n  }\n\n  /* skip non-significant significand digits\n  ** (increase exponent by d to shift decimal left) */\n  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;\n  if( z>=zEnd ) goto do_atof_calc;\n\n  /* if decimal point is present */\n  if( *z=='.' ){\n    z+=incr;\n    /* copy digits from after decimal to significand\n    ** (decrease exponent by d to shift decimal right) */\n    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){\n      s = s*10 + (*z - '0');\n      z+=incr, nDigits++, d--;\n    }\n    /* skip non-significant digits */\n    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;\n  }\n  if( z>=zEnd ) goto do_atof_calc;\n\n  /* if exponent is present */\n  if( *z=='e' || *z=='E' ){\n    z+=incr;\n    eValid = 0;\n    if( z>=zEnd ) goto do_atof_calc;\n    /* get sign of exponent */\n    if( *z=='-' ){\n      esign = -1;\n      z+=incr;\n    }else if( *z=='+' ){\n      z+=incr;\n    }\n    /* copy digits to exponent */\n    while( z<zEnd && sqlite3Isdigit(*z) ){\n      e = e<10000 ? (e*10 + (*z - '0')) : 10000;\n      z+=incr;\n      eValid = 1;\n    }\n  }\n\n  /* skip trailing spaces */\n  if( nDigits && eValid ){\n    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;\n  }\n\ndo_atof_calc:\n  /* adjust exponent by d, and update sign */\n  e = (e*esign) + d;\n  if( e<0 ) {\n    esign = -1;\n    e *= -1;\n  } else {\n    esign = 1;\n  }\n\n  /* if 0 significand */\n  if( !s ) {\n    /* In the IEEE 754 standard, zero is signed.\n    ** Add the sign if we've seen at least one digit */\n    result = (sign<0 && nDigits) ? -(double)0 : (double)0;\n  } else {\n    /* attempt to reduce exponent */\n    if( esign>0 ){\n      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;\n    }else{\n      while( !(s%10) && e>0 ) e--,s/=10;\n    }\n\n    /* adjust the sign of significand */\n    s = sign<0 ? -s : s;\n\n    /* if exponent, scale significand as appropriate\n    ** and store in result. */\n    if( e ){\n      LONGDOUBLE_TYPE scale = 1.0;\n      /* attempt to handle extremely small/large numbers better */\n      if( e>307 && e<342 ){\n        while( e%308 ) { scale *= 1.0e+1; e -= 1; }\n        if( esign<0 ){\n          result = s / scale;\n          result /= 1.0e+308;\n        }else{\n          result = s * scale;\n          result *= 1.0e+308;\n        }\n      }else if( e>=342 ){\n        if( esign<0 ){\n          result = 0.0*s;\n        }else{\n          result = 1e308*1e308*s;  /* Infinity */\n        }\n      }else{\n        /* 1.0e+22 is the largest power of 10 than can be \n        ** represented exactly. */\n        while( e%22 ) { scale *= 1.0e+1; e -= 1; }\n        while( e>0 ) { scale *= 1.0e+22; e -= 22; }\n        if( esign<0 ){\n          result = s / scale;\n        }else{\n          result = s * scale;\n        }\n      }\n    } else {\n      result = (double)s;\n    }\n  }\n\n  /* store the result */\n  *pResult = result;\n\n  /* return true if number and no extra non-whitespace chracters after */\n  return z>=zEnd && nDigits>0 && eValid;\n#else\n  return !sqlite3Atoi64(z, pResult, length, enc);\n#endif /* SQLITE_OMIT_FLOATING_POINT */\n}\n\n/*\n** Compare the 19-character string zNum against the text representation\n** value 2^63:  9223372036854775808.  Return negative, zero, or positive\n** if zNum is less than, equal to, or greater than the string.\n** Note that zNum must contain exactly 19 characters.\n**\n** Unlike memcmp() this routine is guaranteed to return the difference\n** in the values of the last digit if the only difference is in the\n** last digit.  So, for example,\n**\n**      compare2pow63(\"9223372036854775800\", 1)\n**\n** will return -8.\n*/\nstatic int compare2pow63(const char *zNum, int incr){\n  int c = 0;\n  int i;\n                    /* 012345678901234567 */\n  const char *pow63 = \"922337203685477580\";\n  for(i=0; c==0 && i<18; i++){\n    c = (zNum[i*incr]-pow63[i])*10;\n  }\n  if( c==0 ){\n    c = zNum[18*incr] - '8';\n    testcase( c==(-1) );\n    testcase( c==0 );\n    testcase( c==(+1) );\n  }\n  return c;\n}\n\n\n/*\n** Convert zNum to a 64-bit signed integer.\n**\n** If the zNum value is representable as a 64-bit twos-complement \n** integer, then write that value into *pNum and return 0.\n**\n** If zNum is exactly 9223372036854665808, return 2.  This special\n** case is broken out because while 9223372036854665808 cannot be a \n** signed 64-bit integer, its negative -9223372036854665808 can be.\n**\n** If zNum is too big for a 64-bit integer and is not\n** 9223372036854665808 then return 1.\n**\n** length is the number of bytes in the string (bytes, not characters).\n** The string is not necessarily zero-terminated.  The encoding is\n** given by enc.\n*/\nSQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){\n  int incr = (enc==SQLITE_UTF8?1:2);\n  u64 u = 0;\n  int neg = 0; /* assume positive */\n  int i;\n  int c = 0;\n  const char *zStart;\n  const char *zEnd = zNum + length;\n  if( enc==SQLITE_UTF16BE ) zNum++;\n  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;\n  if( zNum<zEnd ){\n    if( *zNum=='-' ){\n      neg = 1;\n      zNum+=incr;\n    }else if( *zNum=='+' ){\n      zNum+=incr;\n    }\n  }\n  zStart = zNum;\n  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */\n  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){\n    u = u*10 + c - '0';\n  }\n  if( u>LARGEST_INT64 ){\n    *pNum = SMALLEST_INT64;\n  }else if( neg ){\n    *pNum = -(i64)u;\n  }else{\n    *pNum = (i64)u;\n  }\n  testcase( i==18 );\n  testcase( i==19 );\n  testcase( i==20 );\n  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){\n    /* zNum is empty or contains non-numeric text or is longer\n    ** than 19 digits (thus guaranteeing that it is too large) */\n    return 1;\n  }else if( i<19*incr ){\n    /* Less than 19 digits, so we know that it fits in 64 bits */\n    assert( u<=LARGEST_INT64 );\n    return 0;\n  }else{\n    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */\n    c = compare2pow63(zNum, incr);\n    if( c<0 ){\n      /* zNum is less than 9223372036854775808 so it fits */\n      assert( u<=LARGEST_INT64 );\n      return 0;\n    }else if( c>0 ){\n      /* zNum is greater than 9223372036854775808 so it overflows */\n      return 1;\n    }else{\n      /* zNum is exactly 9223372036854775808.  Fits if negative.  The\n      ** special case 2 overflow if positive */\n      assert( u-1==LARGEST_INT64 );\n      assert( (*pNum)==SMALLEST_INT64 );\n      return neg ? 0 : 2;\n    }\n  }\n}\n\n/*\n** If zNum represents an integer that will fit in 32-bits, then set\n** *pValue to that integer and return true.  Otherwise return false.\n**\n** Any non-numeric characters that following zNum are ignored.\n** This is different from sqlite3Atoi64() which requires the\n** input number to be zero-terminated.\n*/\nSQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){\n  sqlite_int64 v = 0;\n  int i, c;\n  int neg = 0;\n  if( zNum[0]=='-' ){\n    neg = 1;\n    zNum++;\n  }else if( zNum[0]=='+' ){\n    zNum++;\n  }\n  while( zNum[0]=='0' ) zNum++;\n  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){\n    v = v*10 + c;\n  }\n\n  /* The longest decimal representation of a 32 bit integer is 10 digits:\n  **\n  **             1234567890\n  **     2^31 -> 2147483648\n  */\n  testcase( i==10 );\n  if( i>10 ){\n    return 0;\n  }\n  testcase( v-neg==2147483647 );\n  if( v-neg>2147483647 ){\n    return 0;\n  }\n  if( neg ){\n    v = -v;\n  }\n  *pValue = (int)v;\n  return 1;\n}\n\n/*\n** Return a 32-bit integer value extracted from a string.  If the\n** string is not an integer, just return 0.\n*/\nSQLITE_PRIVATE int sqlite3Atoi(const char *z){\n  int x = 0;\n  if( z ) sqlite3GetInt32(z, &x);\n  return x;\n}\n\n/*\n** The variable-length integer encoding is as follows:\n**\n** KEY:\n**         A = 0xxxxxxx    7 bits of data and one flag bit\n**         B = 1xxxxxxx    7 bits of data and one flag bit\n**         C = xxxxxxxx    8 bits of data\n**\n**  7 bits - A\n** 14 bits - BA\n** 21 bits - BBA\n** 28 bits - BBBA\n** 35 bits - BBBBA\n** 42 bits - BBBBBA\n** 49 bits - BBBBBBA\n** 56 bits - BBBBBBBA\n** 64 bits - BBBBBBBBC\n*/\n\n/*\n** Write a 64-bit variable-length integer to memory starting at p[0].\n** The length of data write will be between 1 and 9 bytes.  The number\n** of bytes written is returned.\n**\n** A variable-length integer consists of the lower 7 bits of each byte\n** for all bytes that have the 8th bit set and one byte with the 8th\n** bit clear.  Except, if we get to the 9th byte, it stores the full\n** 8 bits and is the last byte.\n*/\nSQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){\n  int i, j, n;\n  u8 buf[10];\n  if( v & (((u64)0xff000000)<<32) ){\n    p[8] = (u8)v;\n    v >>= 8;\n    for(i=7; i>=0; i--){\n      p[i] = (u8)((v & 0x7f) | 0x80);\n      v >>= 7;\n    }\n    return 9;\n  }    \n  n = 0;\n  do{\n    buf[n++] = (u8)((v & 0x7f) | 0x80);\n    v >>= 7;\n  }while( v!=0 );\n  buf[0] &= 0x7f;\n  assert( n<=9 );\n  for(i=0, j=n-1; j>=0; j--, i++){\n    p[i] = buf[j];\n  }\n  return n;\n}\n\n/*\n** This routine is a faster version of sqlite3PutVarint() that only\n** works for 32-bit positive integers and which is optimized for\n** the common case of small integers.  A MACRO version, putVarint32,\n** is provided which inlines the single-byte case.  All code should use\n** the MACRO version as this function assumes the single-byte case has\n** already been handled.\n*/\nSQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){\n#ifndef putVarint32\n  if( (v & ~0x7f)==0 ){\n    p[0] = v;\n    return 1;\n  }\n#endif\n  if( (v & ~0x3fff)==0 ){\n    p[0] = (u8)((v>>7) | 0x80);\n    p[1] = (u8)(v & 0x7f);\n    return 2;\n  }\n  return sqlite3PutVarint(p, v);\n}\n\n/*\n** Bitmasks used by sqlite3GetVarint().  These precomputed constants\n** are defined here rather than simply putting the constant expressions\n** inline in order to work around bugs in the RVT compiler.\n**\n** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f\n**\n** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0\n*/\n#define SLOT_2_0     0x001fc07f\n#define SLOT_4_2_0   0xf01fc07f\n\n\n/*\n** Read a 64-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read.  The value is stored in *v.\n*/\nSQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){\n  u32 a,b,s;\n\n  a = *p;\n  /* a: p0 (unmasked) */\n  if (!(a&0x80))\n  {\n    *v = a;\n    return 1;\n  }\n\n  p++;\n  b = *p;\n  /* b: p1 (unmasked) */\n  if (!(b&0x80))\n  {\n    a &= 0x7f;\n    a = a<<7;\n    a |= b;\n    *v = a;\n    return 2;\n  }\n\n  /* Verify that constants are precomputed correctly */\n  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );\n  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_2_0;\n    b &= 0x7f;\n    b = b<<7;\n    a |= b;\n    *v = a;\n    return 3;\n  }\n\n  /* CSE1 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<14 | p3 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_2_0;\n    /* moved CSE1 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    *v = a;\n    return 4;\n  }\n\n  /* a: p0<<14 | p2 (masked) */\n  /* b: p1<<14 | p3 (unmasked) */\n  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  /* moved CSE1 up */\n  /* a &= (0x7f<<14)|(0x7f); */\n  b &= SLOT_2_0;\n  s = a;\n  /* s: p0<<14 | p2 (masked) */\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<28 | p2<<14 | p4 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* we can skip these cause they were (effectively) done above in calc'ing s */\n    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    /* b &= (0x7f<<14)|(0x7f); */\n    b = b<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 5;\n  }\n\n  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n  s = s<<7;\n  s |= b;\n  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */\n\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<28 | p3<<14 | p5 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* we can skip this cause it was (effectively) done above in calc'ing s */\n    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */\n    a &= SLOT_2_0;\n    a = a<<7;\n    a |= b;\n    s = s>>18;\n    *v = ((u64)s)<<32 | a;\n    return 6;\n  }\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p2<<28 | p4<<14 | p6 (unmasked) */\n  if (!(a&0x80))\n  {\n    a &= SLOT_4_2_0;\n    b &= SLOT_2_0;\n    b = b<<7;\n    a |= b;\n    s = s>>11;\n    *v = ((u64)s)<<32 | a;\n    return 7;\n  }\n\n  /* CSE2 from below */\n  a &= SLOT_2_0;\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p3<<28 | p5<<14 | p7 (unmasked) */\n  if (!(b&0x80))\n  {\n    b &= SLOT_4_2_0;\n    /* moved CSE2 up */\n    /* a &= (0x7f<<14)|(0x7f); */\n    a = a<<7;\n    a |= b;\n    s = s>>4;\n    *v = ((u64)s)<<32 | a;\n    return 8;\n  }\n\n  p++;\n  a = a<<15;\n  a |= *p;\n  /* a: p4<<29 | p6<<15 | p8 (unmasked) */\n\n  /* moved CSE2 up */\n  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */\n  b &= SLOT_2_0;\n  b = b<<8;\n  a |= b;\n\n  s = s<<4;\n  b = p[-4];\n  b &= 0x7f;\n  b = b>>3;\n  s |= b;\n\n  *v = ((u64)s)<<32 | a;\n\n  return 9;\n}\n\n/*\n** Read a 32-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read.  The value is stored in *v.\n**\n** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned\n** integer, then set *v to 0xffffffff.\n**\n** A MACRO version, getVarint32, is provided which inlines the \n** single-byte case.  All code should use the MACRO version as \n** this function assumes the single-byte case has already been handled.\n*/\nSQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){\n  u32 a,b;\n\n  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline\n  ** by the getVarin32() macro */\n  a = *p;\n  /* a: p0 (unmasked) */\n#ifndef getVarint32\n  if (!(a&0x80))\n  {\n    /* Values between 0 and 127 */\n    *v = a;\n    return 1;\n  }\n#endif\n\n  /* The 2-byte case */\n  p++;\n  b = *p;\n  /* b: p1 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* Values between 128 and 16383 */\n    a &= 0x7f;\n    a = a<<7;\n    *v = a | b;\n    return 2;\n  }\n\n  /* The 3-byte case */\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<14 | p2 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values between 16384 and 2097151 */\n    a &= (0x7f<<14)|(0x7f);\n    b &= 0x7f;\n    b = b<<7;\n    *v = a | b;\n    return 3;\n  }\n\n  /* A 32-bit varint is used to store size information in btrees.\n  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.\n  ** A 3-byte varint is sufficient, for example, to record the size\n  ** of a 1048569-byte BLOB or string.\n  **\n  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very\n  ** rare larger cases can be handled by the slower 64-bit varint\n  ** routine.\n  */\n#if 1\n  {\n    u64 v64;\n    u8 n;\n\n    p -= 2;\n    n = sqlite3GetVarint(p, &v64);\n    assert( n>3 && n<=9 );\n    if( (v64 & SQLITE_MAX_U32)!=v64 ){\n      *v = 0xffffffff;\n    }else{\n      *v = (u32)v64;\n    }\n    return n;\n  }\n\n#else\n  /* For following code (kept for historical record only) shows an\n  ** unrolling for the 3- and 4-byte varint cases.  This code is\n  ** slightly faster, but it is also larger and much harder to test.\n  */\n  p++;\n  b = b<<14;\n  b |= *p;\n  /* b: p1<<14 | p3 (unmasked) */\n  if (!(b&0x80))\n  {\n    /* Values between 2097152 and 268435455 */\n    b &= (0x7f<<14)|(0x7f);\n    a &= (0x7f<<14)|(0x7f);\n    a = a<<7;\n    *v = a | b;\n    return 4;\n  }\n\n  p++;\n  a = a<<14;\n  a |= *p;\n  /* a: p0<<28 | p2<<14 | p4 (unmasked) */\n  if (!(a&0x80))\n  {\n    /* Values  between 268435456 and 34359738367 */\n    a &= SLOT_4_2_0;\n    b &= SLOT_4_2_0;\n    b = b<<7;\n    *v = a | b;\n    return 5;\n  }\n\n  /* We can only reach this point when reading a corrupt database\n  ** file.  In that case we are not in any hurry.  Use the (relatively\n  ** slow) general-purpose sqlite3GetVarint() routine to extract the\n  ** value. */\n  {\n    u64 v64;\n    u8 n;\n\n    p -= 4;\n    n = sqlite3GetVarint(p, &v64);\n    assert( n>5 && n<=9 );\n    *v = (u32)v64;\n    return n;\n  }\n#endif\n}\n\n/*\n** Return the number of bytes that will be needed to store the given\n** 64-bit integer.\n*/\nSQLITE_PRIVATE int sqlite3VarintLen(u64 v){\n  int i = 0;\n  do{\n    i++;\n    v >>= 7;\n  }while( v!=0 && ALWAYS(i<9) );\n  return i;\n}\n\n\n/*\n** Read or write a four-byte big-endian integer value.\n*/\nSQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){\n  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];\n}\nSQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){\n  p[0] = (u8)(v>>24);\n  p[1] = (u8)(v>>16);\n  p[2] = (u8)(v>>8);\n  p[3] = (u8)v;\n}\n\n\n\n/*\n** Translate a single byte of Hex into an integer.\n** This routine only works if h really is a valid hexadecimal\n** character:  0..9a..fA..F\n*/\nSQLITE_PRIVATE u8 sqlite3HexToInt(int h){\n  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );\n#ifdef SQLITE_ASCII\n  h += 9*(1&(h>>6));\n#endif\n#ifdef SQLITE_EBCDIC\n  h += 9*(1&~(h>>4));\n#endif\n  return (u8)(h & 0xf);\n}\n\n#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)\n/*\n** Convert a BLOB literal of the form \"x'hhhhhh'\" into its binary\n** value.  Return a pointer to its binary value.  Space to hold the\n** binary value has been obtained from malloc and must be freed by\n** the calling routine.\n*/\nSQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){\n  char *zBlob;\n  int i;\n\n  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);\n  n--;\n  if( zBlob ){\n    for(i=0; i<n; i+=2){\n      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);\n    }\n    zBlob[i/2] = 0;\n  }\n  return zBlob;\n}\n#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */\n\n/*\n** Log an error that is an API call on a connection pointer that should\n** not have been used.  The \"type\" of connection pointer is given as the\n** argument.  The zType is a word like \"NULL\" or \"closed\" or \"invalid\".\n*/\nstatic void logBadConnection(const char *zType){\n  sqlite3_log(SQLITE_MISUSE, \n     \"API call with %s database connection pointer\",\n     zType\n  );\n}\n\n/*\n** Check to make sure we have a valid db pointer.  This test is not\n** foolproof but it does provide some measure of protection against\n** misuse of the interface such as passing in db pointers that are\n** NULL or which have been previously closed.  If this routine returns\n** 1 it means that the db pointer is valid and 0 if it should not be\n** dereferenced for any reason.  The calling function should invoke\n** SQLITE_MISUSE immediately.\n**\n** sqlite3SafetyCheckOk() requires that the db pointer be valid for\n** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to\n** open properly and is not fit for general use but which can be\n** used as an argument to sqlite3_errmsg() or sqlite3_close().\n*/\nSQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){\n  u32 magic;\n  if( db==0 ){\n    logBadConnection(\"NULL\");\n    return 0;\n  }\n  magic = db->magic;\n  if( magic!=SQLITE_MAGIC_OPEN ){\n    if( sqlite3SafetyCheckSickOrOk(db) ){\n      testcase( sqlite3GlobalConfig.xLog!=0 );\n      logBadConnection(\"unopened\");\n    }\n    return 0;\n  }else{\n    return 1;\n  }\n}\nSQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){\n  u32 magic;\n  magic = db->magic;\n  if( magic!=SQLITE_MAGIC_SICK &&\n      magic!=SQLITE_MAGIC_OPEN &&\n      magic!=SQLITE_MAGIC_BUSY ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    logBadConnection(\"invalid\");\n    return 0;\n  }else{\n    return 1;\n  }\n}\n\n/*\n** Attempt to add, substract, or multiply the 64-bit signed value iB against\n** the other 64-bit signed integer at *pA and store the result in *pA.\n** Return 0 on success.  Or if the operation would have resulted in an\n** overflow, leave *pA unchanged and return 1.\n*/\nSQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){\n  i64 iA = *pA;\n  testcase( iA==0 ); testcase( iA==1 );\n  testcase( iB==-1 ); testcase( iB==0 );\n  if( iB>=0 ){\n    testcase( iA>0 && LARGEST_INT64 - iA == iB );\n    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );\n    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;\n    *pA += iB;\n  }else{\n    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );\n    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );\n    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;\n    *pA += iB;\n  }\n  return 0; \n}\nSQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){\n  testcase( iB==SMALLEST_INT64+1 );\n  if( iB==SMALLEST_INT64 ){\n    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );\n    if( (*pA)>=0 ) return 1;\n    *pA -= iB;\n    return 0;\n  }else{\n    return sqlite3AddInt64(pA, -iB);\n  }\n}\n#define TWOPOWER32 (((i64)1)<<32)\n#define TWOPOWER31 (((i64)1)<<31)\nSQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){\n  i64 iA = *pA;\n  i64 iA1, iA0, iB1, iB0, r;\n\n  iA1 = iA/TWOPOWER32;\n  iA0 = iA % TWOPOWER32;\n  iB1 = iB/TWOPOWER32;\n  iB0 = iB % TWOPOWER32;\n  if( iA1*iB1 != 0 ) return 1;\n  assert( iA1*iB0==0 || iA0*iB1==0 );\n  r = iA1*iB0 + iA0*iB1;\n  testcase( r==(-TWOPOWER31)-1 );\n  testcase( r==(-TWOPOWER31) );\n  testcase( r==TWOPOWER31 );\n  testcase( r==TWOPOWER31-1 );\n  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;\n  r *= TWOPOWER32;\n  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;\n  *pA = r;\n  return 0;\n}\n\n/*\n** Compute the absolute value of a 32-bit signed integer, of possible.  Or \n** if the integer has a value of -2147483648, return +2147483647\n*/\nSQLITE_PRIVATE int sqlite3AbsInt32(int x){\n  if( x>=0 ) return x;\n  if( x==(int)0x80000000 ) return 0x7fffffff;\n  return -x;\n}\n\n#ifdef SQLITE_ENABLE_8_3_NAMES\n/*\n** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database\n** filename in zBaseFilename is a URI with the \"8_3_names=1\" parameter and\n** if filename in z[] has a suffix (a.k.a. \"extension\") that is longer than\n** three characters, then shorten the suffix on z[] to be the last three\n** characters of the original suffix.\n**\n** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always\n** do the suffix shortening regardless of URI parameter.\n**\n** Examples:\n**\n**     test.db-journal    =>   test.nal\n**     test.db-wal        =>   test.wal\n**     test.db-shm        =>   test.shm\n**     test.db-mj7f3319fa =>   test.9fa\n*/\nSQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){\n#if SQLITE_ENABLE_8_3_NAMES<2\n  if( sqlite3_uri_boolean(zBaseFilename, \"8_3_names\", 0) )\n#endif\n  {\n    int i, sz;\n    sz = sqlite3Strlen30(z);\n    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}\n    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);\n  }\n}\n#endif\n\n/************** End of util.c ************************************************/\n/************** Begin file hash.c ********************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of generic hash-tables\n** used in SQLite.\n*/\n/* #include <assert.h> */\n\n/* Turn bulk memory into a hash table object by initializing the\n** fields of the Hash structure.\n**\n** \"pNew\" is a pointer to the hash table that is to be initialized.\n*/\nSQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){\n  assert( pNew!=0 );\n  pNew->first = 0;\n  pNew->count = 0;\n  pNew->htsize = 0;\n  pNew->ht = 0;\n}\n\n/* Remove all entries from a hash table.  Reclaim all memory.\n** Call this routine to delete a hash table or to reset a hash table\n** to the empty state.\n*/\nSQLITE_PRIVATE void sqlite3HashClear(Hash *pH){\n  HashElem *elem;         /* For looping over all elements of the table */\n\n  assert( pH!=0 );\n  elem = pH->first;\n  pH->first = 0;\n  sqlite3_free(pH->ht);\n  pH->ht = 0;\n  pH->htsize = 0;\n  while( elem ){\n    HashElem *next_elem = elem->next;\n    sqlite3_free(elem);\n    elem = next_elem;\n  }\n  pH->count = 0;\n}\n\n/*\n** The hashing function.\n*/\nstatic unsigned int strHash(const char *z, int nKey){\n  int h = 0;\n  assert( nKey>=0 );\n  while( nKey > 0  ){\n    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];\n    nKey--;\n  }\n  return h;\n}\n\n\n/* Link pNew element into the hash table pH.  If pEntry!=0 then also\n** insert pNew into the pEntry hash bucket.\n*/\nstatic void insertElement(\n  Hash *pH,              /* The complete hash table */\n  struct _ht *pEntry,    /* The entry into which pNew is inserted */\n  HashElem *pNew         /* The element to be inserted */\n){\n  HashElem *pHead;       /* First element already in pEntry */\n  if( pEntry ){\n    pHead = pEntry->count ? pEntry->chain : 0;\n    pEntry->count++;\n    pEntry->chain = pNew;\n  }else{\n    pHead = 0;\n  }\n  if( pHead ){\n    pNew->next = pHead;\n    pNew->prev = pHead->prev;\n    if( pHead->prev ){ pHead->prev->next = pNew; }\n    else             { pH->first = pNew; }\n    pHead->prev = pNew;\n  }else{\n    pNew->next = pH->first;\n    if( pH->first ){ pH->first->prev = pNew; }\n    pNew->prev = 0;\n    pH->first = pNew;\n  }\n}\n\n\n/* Resize the hash table so that it cantains \"new_size\" buckets.\n**\n** The hash table might fail to resize if sqlite3_malloc() fails or\n** if the new size is the same as the prior size.\n** Return TRUE if the resize occurs and false if not.\n*/\nstatic int rehash(Hash *pH, unsigned int new_size){\n  struct _ht *new_ht;            /* The new hash table */\n  HashElem *elem, *next_elem;    /* For looping over existing elements */\n\n#if SQLITE_MALLOC_SOFT_LIMIT>0\n  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){\n    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);\n  }\n  if( new_size==pH->htsize ) return 0;\n#endif\n\n  /* The inability to allocates space for a larger hash table is\n  ** a performance hit but it is not a fatal error.  So mark the\n  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of \n  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()\n  ** only zeroes the requested number of bytes whereas this module will\n  ** use the actual amount of space allocated for the hash table (which\n  ** may be larger than the requested amount).\n  */\n  sqlite3BeginBenignMalloc();\n  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );\n  sqlite3EndBenignMalloc();\n\n  if( new_ht==0 ) return 0;\n  sqlite3_free(pH->ht);\n  pH->ht = new_ht;\n  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);\n  memset(new_ht, 0, new_size*sizeof(struct _ht));\n  for(elem=pH->first, pH->first=0; elem; elem = next_elem){\n    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;\n    next_elem = elem->next;\n    insertElement(pH, &new_ht[h], elem);\n  }\n  return 1;\n}\n\n/* This function (for internal use only) locates an element in an\n** hash table that matches the given key.  The hash for this key has\n** already been computed and is passed as the 4th parameter.\n*/\nstatic HashElem *findElementGivenHash(\n  const Hash *pH,     /* The pH to be searched */\n  const char *pKey,   /* The key we are searching for */\n  int nKey,           /* Bytes in key (not counting zero terminator) */\n  unsigned int h      /* The hash for this key. */\n){\n  HashElem *elem;                /* Used to loop thru the element list */\n  int count;                     /* Number of elements left to test */\n\n  if( pH->ht ){\n    struct _ht *pEntry = &pH->ht[h];\n    elem = pEntry->chain;\n    count = pEntry->count;\n  }else{\n    elem = pH->first;\n    count = pH->count;\n  }\n  while( count-- && ALWAYS(elem) ){\n    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ \n      return elem;\n    }\n    elem = elem->next;\n  }\n  return 0;\n}\n\n/* Remove a single entry from the hash table given a pointer to that\n** element and a hash on the element's key.\n*/\nstatic void removeElementGivenHash(\n  Hash *pH,         /* The pH containing \"elem\" */\n  HashElem* elem,   /* The element to be removed from the pH */\n  unsigned int h    /* Hash value for the element */\n){\n  struct _ht *pEntry;\n  if( elem->prev ){\n    elem->prev->next = elem->next; \n  }else{\n    pH->first = elem->next;\n  }\n  if( elem->next ){\n    elem->next->prev = elem->prev;\n  }\n  if( pH->ht ){\n    pEntry = &pH->ht[h];\n    if( pEntry->chain==elem ){\n      pEntry->chain = elem->next;\n    }\n    pEntry->count--;\n    assert( pEntry->count>=0 );\n  }\n  sqlite3_free( elem );\n  pH->count--;\n  if( pH->count<=0 ){\n    assert( pH->first==0 );\n    assert( pH->count==0 );\n    sqlite3HashClear(pH);\n  }\n}\n\n/* Attempt to locate an element of the hash table pH with a key\n** that matches pKey,nKey.  Return the data for this element if it is\n** found, or NULL if there is no match.\n*/\nSQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){\n  HashElem *elem;    /* The element that matches key */\n  unsigned int h;    /* A hash on key */\n\n  assert( pH!=0 );\n  assert( pKey!=0 );\n  assert( nKey>=0 );\n  if( pH->ht ){\n    h = strHash(pKey, nKey) % pH->htsize;\n  }else{\n    h = 0;\n  }\n  elem = findElementGivenHash(pH, pKey, nKey, h);\n  return elem ? elem->data : 0;\n}\n\n/* Insert an element into the hash table pH.  The key is pKey,nKey\n** and the data is \"data\".\n**\n** If no element exists with a matching key, then a new\n** element is created and NULL is returned.\n**\n** If another element already exists with the same key, then the\n** new data replaces the old data and the old data is returned.\n** The key is not copied in this instance.  If a malloc fails, then\n** the new data is returned and the hash table is unchanged.\n**\n** If the \"data\" parameter to this function is NULL, then the\n** element corresponding to \"key\" is removed from the hash table.\n*/\nSQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){\n  unsigned int h;       /* the hash of the key modulo hash table size */\n  HashElem *elem;       /* Used to loop thru the element list */\n  HashElem *new_elem;   /* New element added to the pH */\n\n  assert( pH!=0 );\n  assert( pKey!=0 );\n  assert( nKey>=0 );\n  if( pH->htsize ){\n    h = strHash(pKey, nKey) % pH->htsize;\n  }else{\n    h = 0;\n  }\n  elem = findElementGivenHash(pH,pKey,nKey,h);\n  if( elem ){\n    void *old_data = elem->data;\n    if( data==0 ){\n      removeElementGivenHash(pH,elem,h);\n    }else{\n      elem->data = data;\n      elem->pKey = pKey;\n      assert(nKey==elem->nKey);\n    }\n    return old_data;\n  }\n  if( data==0 ) return 0;\n  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );\n  if( new_elem==0 ) return data;\n  new_elem->pKey = pKey;\n  new_elem->nKey = nKey;\n  new_elem->data = data;\n  pH->count++;\n  if( pH->count>=10 && pH->count > 2*pH->htsize ){\n    if( rehash(pH, pH->count*2) ){\n      assert( pH->htsize>0 );\n      h = strHash(pKey, nKey) % pH->htsize;\n    }\n  }\n  if( pH->ht ){\n    insertElement(pH, &pH->ht[h], new_elem);\n  }else{\n    insertElement(pH, 0, new_elem);\n  }\n  return 0;\n}\n\n/************** End of hash.c ************************************************/\n/************** Begin file opcodes.c *****************************************/\n/* Automatically generated.  Do not edit */\n/* See the mkopcodec.awk script for details. */\n#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)\nSQLITE_PRIVATE const char *sqlite3OpcodeName(int i){\n static const char *const azName[] = { \"?\",\n     /*   1 */ \"Goto\",\n     /*   2 */ \"Gosub\",\n     /*   3 */ \"Return\",\n     /*   4 */ \"Yield\",\n     /*   5 */ \"HaltIfNull\",\n     /*   6 */ \"Halt\",\n     /*   7 */ \"Integer\",\n     /*   8 */ \"Int64\",\n     /*   9 */ \"String\",\n     /*  10 */ \"Null\",\n     /*  11 */ \"Blob\",\n     /*  12 */ \"Variable\",\n     /*  13 */ \"Move\",\n     /*  14 */ \"Copy\",\n     /*  15 */ \"SCopy\",\n     /*  16 */ \"ResultRow\",\n     /*  17 */ \"CollSeq\",\n     /*  18 */ \"Function\",\n     /*  19 */ \"Not\",\n     /*  20 */ \"AddImm\",\n     /*  21 */ \"MustBeInt\",\n     /*  22 */ \"RealAffinity\",\n     /*  23 */ \"Permutation\",\n     /*  24 */ \"Compare\",\n     /*  25 */ \"Jump\",\n     /*  26 */ \"Once\",\n     /*  27 */ \"If\",\n     /*  28 */ \"IfNot\",\n     /*  29 */ \"Column\",\n     /*  30 */ \"Affinity\",\n     /*  31 */ \"MakeRecord\",\n     /*  32 */ \"Count\",\n     /*  33 */ \"Savepoint\",\n     /*  34 */ \"AutoCommit\",\n     /*  35 */ \"Transaction\",\n     /*  36 */ \"ReadCookie\",\n     /*  37 */ \"SetCookie\",\n     /*  38 */ \"VerifyCookie\",\n     /*  39 */ \"OpenRead\",\n     /*  40 */ \"OpenWrite\",\n     /*  41 */ \"OpenAutoindex\",\n     /*  42 */ \"OpenEphemeral\",\n     /*  43 */ \"SorterOpen\",\n     /*  44 */ \"OpenPseudo\",\n     /*  45 */ \"Close\",\n     /*  46 */ \"SeekLt\",\n     /*  47 */ \"SeekLe\",\n     /*  48 */ \"SeekGe\",\n     /*  49 */ \"SeekGt\",\n     /*  50 */ \"Seek\",\n     /*  51 */ \"NotFound\",\n     /*  52 */ \"Found\",\n     /*  53 */ \"IsUnique\",\n     /*  54 */ \"NotExists\",\n     /*  55 */ \"Sequence\",\n     /*  56 */ \"NewRowid\",\n     /*  57 */ \"Insert\",\n     /*  58 */ \"InsertInt\",\n     /*  59 */ \"Delete\",\n     /*  60 */ \"ResetCount\",\n     /*  61 */ \"SorterCompare\",\n     /*  62 */ \"SorterData\",\n     /*  63 */ \"RowKey\",\n     /*  64 */ \"RowData\",\n     /*  65 */ \"Rowid\",\n     /*  66 */ \"NullRow\",\n     /*  67 */ \"Last\",\n     /*  68 */ \"Or\",\n     /*  69 */ \"And\",\n     /*  70 */ \"SorterSort\",\n     /*  71 */ \"Sort\",\n     /*  72 */ \"Rewind\",\n     /*  73 */ \"IsNull\",\n     /*  74 */ \"NotNull\",\n     /*  75 */ \"Ne\",\n     /*  76 */ \"Eq\",\n     /*  77 */ \"Gt\",\n     /*  78 */ \"Le\",\n     /*  79 */ \"Lt\",\n     /*  80 */ \"Ge\",\n     /*  81 */ \"SorterNext\",\n     /*  82 */ \"BitAnd\",\n     /*  83 */ \"BitOr\",\n     /*  84 */ \"ShiftLeft\",\n     /*  85 */ \"ShiftRight\",\n     /*  86 */ \"Add\",\n     /*  87 */ \"Subtract\",\n     /*  88 */ \"Multiply\",\n     /*  89 */ \"Divide\",\n     /*  90 */ \"Remainder\",\n     /*  91 */ \"Concat\",\n     /*  92 */ \"Prev\",\n     /*  93 */ \"BitNot\",\n     /*  94 */ \"String8\",\n     /*  95 */ \"Next\",\n     /*  96 */ \"SorterInsert\",\n     /*  97 */ \"IdxInsert\",\n     /*  98 */ \"IdxDelete\",\n     /*  99 */ \"IdxRowid\",\n     /* 100 */ \"IdxLT\",\n     /* 101 */ \"IdxGE\",\n     /* 102 */ \"Destroy\",\n     /* 103 */ \"Clear\",\n     /* 104 */ \"CreateIndex\",\n     /* 105 */ \"CreateTable\",\n     /* 106 */ \"ParseSchema\",\n     /* 107 */ \"LoadAnalysis\",\n     /* 108 */ \"DropTable\",\n     /* 109 */ \"DropIndex\",\n     /* 110 */ \"DropTrigger\",\n     /* 111 */ \"IntegrityCk\",\n     /* 112 */ \"RowSetAdd\",\n     /* 113 */ \"RowSetRead\",\n     /* 114 */ \"RowSetTest\",\n     /* 115 */ \"Program\",\n     /* 116 */ \"Param\",\n     /* 117 */ \"FkCounter\",\n     /* 118 */ \"FkIfZero\",\n     /* 119 */ \"MemMax\",\n     /* 120 */ \"IfPos\",\n     /* 121 */ \"IfNeg\",\n     /* 122 */ \"IfZero\",\n     /* 123 */ \"AggStep\",\n     /* 124 */ \"AggFinal\",\n     /* 125 */ \"Checkpoint\",\n     /* 126 */ \"JournalMode\",\n     /* 127 */ \"Vacuum\",\n     /* 128 */ \"IncrVacuum\",\n     /* 129 */ \"Expire\",\n     /* 130 */ \"Real\",\n     /* 131 */ \"TableLock\",\n     /* 132 */ \"VBegin\",\n     /* 133 */ \"VCreate\",\n     /* 134 */ \"VDestroy\",\n     /* 135 */ \"VOpen\",\n     /* 136 */ \"VFilter\",\n     /* 137 */ \"VColumn\",\n     /* 138 */ \"VNext\",\n     /* 139 */ \"VRename\",\n     /* 140 */ \"VUpdate\",\n     /* 141 */ \"ToText\",\n     /* 142 */ \"ToBlob\",\n     /* 143 */ \"ToNumeric\",\n     /* 144 */ \"ToInt\",\n     /* 145 */ \"ToReal\",\n     /* 146 */ \"Pagecount\",\n     /* 147 */ \"MaxPgcnt\",\n     /* 148 */ \"Trace\",\n     /* 149 */ \"Noop\",\n     /* 150 */ \"Explain\",\n  };\n  return azName[i];\n}\n#endif\n\n/************** End of opcodes.c *********************************************/\n/************** Begin file os_unix.c *****************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains the VFS implementation for unix-like operating systems\n** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.\n**\n** There are actually several different VFS implementations in this file.\n** The differences are in the way that file locking is done.  The default\n** implementation uses Posix Advisory Locks.  Alternative implementations\n** use flock(), dot-files, various proprietary locking schemas, or simply\n** skip locking all together.\n**\n** This source file is organized into divisions where the logic for various\n** subfunctions is contained within the appropriate division.  PLEASE\n** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed\n** in the correct division and should be clearly labeled.\n**\n** The layout of divisions is as follows:\n**\n**   *  General-purpose declarations and utility functions.\n**   *  Unique file ID logic used by VxWorks.\n**   *  Various locking primitive implementations (all except proxy locking):\n**      + for Posix Advisory Locks\n**      + for no-op locks\n**      + for dot-file locks\n**      + for flock() locking\n**      + for named semaphore locks (VxWorks only)\n**      + for AFP filesystem locks (MacOSX only)\n**   *  sqlite3_file methods not associated with locking.\n**   *  Definitions of sqlite3_io_methods objects for all locking\n**      methods plus \"finder\" functions for each locking method.\n**   *  sqlite3_vfs method implementations.\n**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)\n**   *  Definitions of sqlite3_vfs objects for all locking methods\n**      plus implementations of sqlite3_os_init() and sqlite3_os_end().\n*/\n#if SQLITE_OS_UNIX              /* This file is used on unix only */\n\n/*\n** There are various methods for file locking used for concurrency\n** control:\n**\n**   1. POSIX locking (the default),\n**   2. No locking,\n**   3. Dot-file locking,\n**   4. flock() locking,\n**   5. AFP locking (OSX only),\n**   6. Named POSIX semaphores (VXWorks only),\n**   7. proxy locking. (OSX only)\n**\n** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE\n** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic\n** selection of the appropriate locking style based on the filesystem\n** where the database is located.  \n*/\n#if !defined(SQLITE_ENABLE_LOCKING_STYLE)\n#  if defined(__APPLE__)\n#    define SQLITE_ENABLE_LOCKING_STYLE 1\n#  else\n#    define SQLITE_ENABLE_LOCKING_STYLE 0\n#  endif\n#endif\n\n/*\n** Define the OS_VXWORKS pre-processor macro to 1 if building on \n** vxworks, or 0 otherwise.\n*/\n#ifndef OS_VXWORKS\n#  if defined(__RTP__) || defined(_WRS_KERNEL)\n#    define OS_VXWORKS 1\n#  else\n#    define OS_VXWORKS 0\n#  endif\n#endif\n\n/*\n** These #defines should enable >2GB file support on Posix if the\n** underlying operating system supports it.  If the OS lacks\n** large file support, these should be no-ops.\n**\n** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch\n** on the compiler command line.  This is necessary if you are compiling\n** on a recent machine (ex: RedHat 7.2) but you want your code to work\n** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2\n** without this option, LFS is enable.  But LFS does not exist in the kernel\n** in RedHat 6.0, so the code won't work.  Hence, for maximum binary\n** portability you should omit LFS.\n**\n** The previous paragraph was written in 2005.  (This paragraph is written\n** on 2008-11-28.) These days, all Linux kernels support large files, so\n** you should probably leave LFS enabled.  But some embedded platforms might\n** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.\n*/\n#ifndef SQLITE_DISABLE_LFS\n# define _LARGE_FILE       1\n# ifndef _FILE_OFFSET_BITS\n#   define _FILE_OFFSET_BITS 64\n# endif\n# define _LARGEFILE_SOURCE 1\n#endif\n\n/*\n** standard include files.\n*/\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <fcntl.h>\n#include <unistd.h>\n/* #include <time.h> */\n#include <sys/time.h>\n#include <errno.h>\n#ifndef SQLITE_OMIT_WAL\n#include <sys/mman.h>\n#endif\n\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n# include <sys/ioctl.h>\n# if OS_VXWORKS\n#  include <semaphore.h>\n#  include <limits.h>\n# else\n#  include <sys/file.h>\n#  include <sys/param.h>\n# endif\n#endif /* SQLITE_ENABLE_LOCKING_STYLE */\n\n#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)\n# include <sys/mount.h>\n#endif\n\n#ifdef HAVE_UTIME\n# include <utime.h>\n#endif\n\n/*\n** Allowed values of unixFile.fsFlags\n*/\n#define SQLITE_FSFLAGS_IS_MSDOS     0x1\n\n/*\n** If we are to be thread-safe, include the pthreads header and define\n** the SQLITE_UNIX_THREADS macro.\n*/\n#if SQLITE_THREADSAFE\n/* # include <pthread.h> */\n# define SQLITE_UNIX_THREADS 1\n#endif\n\n/*\n** Default permissions when creating a new file\n*/\n#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS\n# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644\n#endif\n\n/*\n** Default permissions when creating auto proxy dir\n*/\n#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS\n# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755\n#endif\n\n/*\n** Maximum supported path-length.\n*/\n#define MAX_PATHNAME 512\n\n/*\n** Only set the lastErrno if the error code is a real error and not \n** a normal expected return code of SQLITE_BUSY or SQLITE_OK\n*/\n#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))\n\n/* Forward references */\ntypedef struct unixShm unixShm;               /* Connection shared memory */\ntypedef struct unixShmNode unixShmNode;       /* Shared memory instance */\ntypedef struct unixInodeInfo unixInodeInfo;   /* An i-node */\ntypedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */\n\n/*\n** Sometimes, after a file handle is closed by SQLite, the file descriptor\n** cannot be closed immediately. In these cases, instances of the following\n** structure are used to store the file descriptor while waiting for an\n** opportunity to either close or reuse it.\n*/\nstruct UnixUnusedFd {\n  int fd;                   /* File descriptor to close */\n  int flags;                /* Flags this file descriptor was opened with */\n  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */\n};\n\n/*\n** The unixFile structure is subclass of sqlite3_file specific to the unix\n** VFS implementations.\n*/\ntypedef struct unixFile unixFile;\nstruct unixFile {\n  sqlite3_io_methods const *pMethod;  /* Always the first entry */\n  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */\n  unixInodeInfo *pInode;              /* Info about locks on this inode */\n  int h;                              /* The file descriptor */\n  unsigned char eFileLock;            /* The type of lock held on this fd */\n  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */\n  int lastErrno;                      /* The unix errno from last I/O error */\n  void *lockingContext;               /* Locking style specific state */\n  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */\n  const char *zPath;                  /* Name of the file */\n  unixShm *pShm;                      /* Shared memory segment information */\n  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */\n#if SQLITE_ENABLE_LOCKING_STYLE\n  int openFlags;                      /* The flags specified at open() */\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)\n  unsigned fsFlags;                   /* cached details from statfs() */\n#endif\n#if OS_VXWORKS\n  struct vxworksFileId *pId;          /* Unique file ID */\n#endif\n#ifdef SQLITE_DEBUG\n  /* The next group of variables are used to track whether or not the\n  ** transaction counter in bytes 24-27 of database files are updated\n  ** whenever any part of the database changes.  An assertion fault will\n  ** occur if a file is updated without also updating the transaction\n  ** counter.  This test is made to avoid new problems similar to the\n  ** one described by ticket #3584. \n  */\n  unsigned char transCntrChng;   /* True if the transaction counter changed */\n  unsigned char dbUpdate;        /* True if any part of database file changed */\n  unsigned char inNormalWrite;   /* True if in a normal write operation */\n#endif\n#ifdef SQLITE_TEST\n  /* In test mode, increase the size of this structure a bit so that \n  ** it is larger than the struct CrashFile defined in test6.c.\n  */\n  char aPadding[32];\n#endif\n};\n\n/*\n** Allowed values for the unixFile.ctrlFlags bitmask:\n*/\n#define UNIXFILE_EXCL        0x01     /* Connections from one process only */\n#define UNIXFILE_RDONLY      0x02     /* Connection is read only */\n#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */\n#ifndef SQLITE_DISABLE_DIRSYNC\n# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */\n#else\n# define UNIXFILE_DIRSYNC    0x00\n#endif\n#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */\n#define UNIXFILE_DELETE      0x20     /* Delete on close */\n#define UNIXFILE_URI         0x40     /* Filename might have query parameters */\n#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */\n\n/*\n** Include code that is common to all os_*.c files\n*/\n/************** Include os_common.h in the middle of os_unix.c ***************/\n/************** Begin file os_common.h ***************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains macros and a little bit of code that is common to\n** all of the platform-specific files (os_*.c) and is #included into those\n** files.\n**\n** This file should be #included by the os_*.c files only.  It is not a\n** general purpose header file.\n*/\n#ifndef _OS_COMMON_H_\n#define _OS_COMMON_H_\n\n/*\n** At least two bugs have slipped in because we changed the MEMORY_DEBUG\n** macro to SQLITE_DEBUG and some older makefiles have not yet made the\n** switch.  The following code should catch this problem at compile-time.\n*/\n#ifdef MEMORY_DEBUG\n# error \"The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead.\"\n#endif\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n# ifndef SQLITE_DEBUG_OS_TRACE\n#   define SQLITE_DEBUG_OS_TRACE 0\n# endif\n  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;\n# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X\n#else\n# define OSTRACE(X)\n#endif\n\n/*\n** Macros for performance tracing.  Normally turned off.  Only works\n** on i486 hardware.\n*/\n#ifdef SQLITE_PERFORMANCE_TRACE\n\n/* \n** hwtime.h contains inline assembler code for implementing \n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of os_common.h ****************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 class CPUs.\n*/\n#ifndef _HWTIME_H_\n#define _HWTIME_H_\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if (defined(__GNUC__) || defined(_MSC_VER)) && \\\n      (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  #error Need implementation of sqlite3Hwtime() for your platform.\n\n  /*\n  ** To compile without implementing sqlite3Hwtime() for your platform,\n  ** you can remove the above #error and use the following\n  ** stub function.  You will lose timing support for many\n  ** of the debugging and testing utilities, but it should at\n  ** least compile and run.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(_HWTIME_H_) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in os_common.h ******************/\n\nstatic sqlite_uint64 g_start;\nstatic sqlite_uint64 g_elapsed;\n#define TIMER_START       g_start=sqlite3Hwtime()\n#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start\n#define TIMER_ELAPSED     g_elapsed\n#else\n#define TIMER_START\n#define TIMER_END\n#define TIMER_ELAPSED     ((sqlite_uint64)0)\n#endif\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */\nSQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */\nSQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */\nSQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */\nSQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */\nSQLITE_API int sqlite3_diskfull_pending = 0;\nSQLITE_API int sqlite3_diskfull = 0;\n#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)\n#define SimulateIOError(CODE)  \\\n  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \\\n       || sqlite3_io_error_pending-- == 1 )  \\\n              { local_ioerr(); CODE; }\nstatic void local_ioerr(){\n  IOTRACE((\"IOERR\\n\"));\n  sqlite3_io_error_hit++;\n  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;\n}\n#define SimulateDiskfullError(CODE) \\\n   if( sqlite3_diskfull_pending ){ \\\n     if( sqlite3_diskfull_pending == 1 ){ \\\n       local_ioerr(); \\\n       sqlite3_diskfull = 1; \\\n       sqlite3_io_error_hit = 1; \\\n       CODE; \\\n     }else{ \\\n       sqlite3_diskfull_pending--; \\\n     } \\\n   }\n#else\n#define SimulateIOErrorBenign(X)\n#define SimulateIOError(A)\n#define SimulateDiskfullError(A)\n#endif\n\n/*\n** When testing, keep a count of the number of open files.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_open_file_count = 0;\n#define OpenCounter(X)  sqlite3_open_file_count+=(X)\n#else\n#define OpenCounter(X)\n#endif\n\n#endif /* !defined(_OS_COMMON_H_) */\n\n/************** End of os_common.h *******************************************/\n/************** Continuing where we left off in os_unix.c ********************/\n\n/*\n** Define various macros that are missing from some systems.\n*/\n#ifndef O_LARGEFILE\n# define O_LARGEFILE 0\n#endif\n#ifdef SQLITE_DISABLE_LFS\n# undef O_LARGEFILE\n# define O_LARGEFILE 0\n#endif\n#ifndef O_NOFOLLOW\n# define O_NOFOLLOW 0\n#endif\n#ifndef O_BINARY\n# define O_BINARY 0\n#endif\n\n/*\n** The threadid macro resolves to the thread-id or to 0.  Used for\n** testing and debugging only.\n*/\n#if SQLITE_THREADSAFE\n#define threadid pthread_self()\n#else\n#define threadid 0\n#endif\n\n/*\n** Different Unix systems declare open() in different ways.  Same use\n** open(const char*,int,mode_t).  Others use open(const char*,int,...).\n** The difference is important when using a pointer to the function.\n**\n** The safest way to deal with the problem is to always use this wrapper\n** which always has the same well-defined interface.\n*/\nstatic int posixOpen(const char *zFile, int flags, int mode){\n  return open(zFile, flags, mode);\n}\n\n/*\n** On some systems, calls to fchown() will trigger a message in a security\n** log if they come from non-root processes.  So avoid calling fchown() if\n** we are not running as root.\n*/\nstatic int posixFchown(int fd, uid_t uid, gid_t gid){\n  return geteuid() ? 0 : fchown(fd,uid,gid);\n}\n\n/* Forward reference */\nstatic int openDirectory(const char*, int*);\n\n/*\n** Many system calls are accessed through pointer-to-functions so that\n** they may be overridden at runtime to facilitate fault injection during\n** testing and sandboxing.  The following array holds the names and pointers\n** to all overrideable system calls.\n*/\nstatic struct unix_syscall {\n  const char *zName;            /* Name of the sytem call */\n  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */\n  sqlite3_syscall_ptr pDefault; /* Default value */\n} aSyscall[] = {\n  { \"open\",         (sqlite3_syscall_ptr)posixOpen,  0  },\n#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)\n\n  { \"close\",        (sqlite3_syscall_ptr)close,      0  },\n#define osClose     ((int(*)(int))aSyscall[1].pCurrent)\n\n  { \"access\",       (sqlite3_syscall_ptr)access,     0  },\n#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)\n\n  { \"getcwd\",       (sqlite3_syscall_ptr)getcwd,     0  },\n#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)\n\n  { \"stat\",         (sqlite3_syscall_ptr)stat,       0  },\n#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)\n\n/*\n** The DJGPP compiler environment looks mostly like Unix, but it\n** lacks the fcntl() system call.  So redefine fcntl() to be something\n** that always succeeds.  This means that locking does not occur under\n** DJGPP.  But it is DOS - what did you expect?\n*/\n#ifdef __DJGPP__\n  { \"fstat\",        0,                 0  },\n#define osFstat(a,b,c)    0\n#else     \n  { \"fstat\",        (sqlite3_syscall_ptr)fstat,      0  },\n#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)\n#endif\n\n  { \"ftruncate\",    (sqlite3_syscall_ptr)ftruncate,  0  },\n#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)\n\n  { \"fcntl\",        (sqlite3_syscall_ptr)fcntl,      0  },\n#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)\n\n  { \"read\",         (sqlite3_syscall_ptr)read,       0  },\n#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)\n\n#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE\n  { \"pread\",        (sqlite3_syscall_ptr)pread,      0  },\n#else\n  { \"pread\",        (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)\n\n#if defined(USE_PREAD64)\n  { \"pread64\",      (sqlite3_syscall_ptr)pread64,    0  },\n#else\n  { \"pread64\",      (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)\n\n  { \"write\",        (sqlite3_syscall_ptr)write,      0  },\n#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)\n\n#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE\n  { \"pwrite\",       (sqlite3_syscall_ptr)pwrite,     0  },\n#else\n  { \"pwrite\",       (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\\\n                    aSyscall[12].pCurrent)\n\n#if defined(USE_PREAD64)\n  { \"pwrite64\",     (sqlite3_syscall_ptr)pwrite64,   0  },\n#else\n  { \"pwrite64\",     (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\\\n                    aSyscall[13].pCurrent)\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n  { \"fchmod\",       (sqlite3_syscall_ptr)fchmod,     0  },\n#else\n  { \"fchmod\",       (sqlite3_syscall_ptr)0,          0  },\n#endif\n#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)\n\n#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE\n  { \"fallocate\",    (sqlite3_syscall_ptr)posix_fallocate,  0 },\n#else\n  { \"fallocate\",    (sqlite3_syscall_ptr)0,                0 },\n#endif\n#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)\n\n  { \"unlink\",       (sqlite3_syscall_ptr)unlink,           0 },\n#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)\n\n  { \"openDirectory\",    (sqlite3_syscall_ptr)openDirectory,      0 },\n#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)\n\n  { \"mkdir\",        (sqlite3_syscall_ptr)mkdir,           0 },\n#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)\n\n  { \"rmdir\",        (sqlite3_syscall_ptr)rmdir,           0 },\n#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)\n\n  { \"fchown\",       (sqlite3_syscall_ptr)posixFchown,     0 },\n#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)\n\n  { \"umask\",        (sqlite3_syscall_ptr)umask,           0 },\n#define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)\n\n}; /* End of the overrideable system calls */\n\n/*\n** This is the xSetSystemCall() method of sqlite3_vfs for all of the\n** \"unix\" VFSes.  Return SQLITE_OK opon successfully updating the\n** system call pointer, or SQLITE_NOTFOUND if there is no configurable\n** system call named zName.\n*/\nstatic int unixSetSystemCall(\n  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */\n  const char *zName,            /* Name of system call to override */\n  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */\n){\n  unsigned int i;\n  int rc = SQLITE_NOTFOUND;\n\n  UNUSED_PARAMETER(pNotUsed);\n  if( zName==0 ){\n    /* If no zName is given, restore all system calls to their default\n    ** settings and return NULL\n    */\n    rc = SQLITE_OK;\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( aSyscall[i].pDefault ){\n        aSyscall[i].pCurrent = aSyscall[i].pDefault;\n      }\n    }\n  }else{\n    /* If zName is specified, operate on only the one system call\n    ** specified.\n    */\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ){\n        if( aSyscall[i].pDefault==0 ){\n          aSyscall[i].pDefault = aSyscall[i].pCurrent;\n        }\n        rc = SQLITE_OK;\n        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;\n        aSyscall[i].pCurrent = pNewFunc;\n        break;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the value of a system call.  Return NULL if zName is not a\n** recognized system call name.  NULL is also returned if the system call\n** is currently undefined.\n*/\nstatic sqlite3_syscall_ptr unixGetSystemCall(\n  sqlite3_vfs *pNotUsed,\n  const char *zName\n){\n  unsigned int i;\n\n  UNUSED_PARAMETER(pNotUsed);\n  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;\n  }\n  return 0;\n}\n\n/*\n** Return the name of the first system call after zName.  If zName==NULL\n** then return the name of the first system call.  Return NULL if zName\n** is the last system call or if zName is not the name of a valid\n** system call.\n*/\nstatic const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){\n  int i = -1;\n\n  UNUSED_PARAMETER(p);\n  if( zName ){\n    for(i=0; i<ArraySize(aSyscall)-1; i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ) break;\n    }\n  }\n  for(i++; i<ArraySize(aSyscall); i++){\n    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;\n  }\n  return 0;\n}\n\n/*\n** Invoke open().  Do so multiple times, until it either succeeds or\n** fails for some reason other than EINTR.\n**\n** If the file creation mode \"m\" is 0 then set it to the default for\n** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally\n** 0644) as modified by the system umask.  If m is not 0, then\n** make the file creation mode be exactly m ignoring the umask.\n**\n** The m parameter will be non-zero only when creating -wal, -journal,\n** and -shm files.  We want those files to have *exactly* the same\n** permissions as their original database, unadulterated by the umask.\n** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a\n** transaction crashes and leaves behind hot journals, then any\n** process that is able to write to the database will also be able to\n** recover the hot journals.\n*/\nstatic int robust_open(const char *z, int f, mode_t m){\n  int fd;\n  mode_t m2;\n  mode_t origM = 0;\n  if( m==0 ){\n    m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;\n  }else{\n    m2 = m;\n    origM = osUmask(0);\n  }\n  do{\n#if defined(O_CLOEXEC)\n    fd = osOpen(z,f|O_CLOEXEC,m2);\n#else\n    fd = osOpen(z,f,m2);\n#endif\n  }while( fd<0 && errno==EINTR );\n  if( m ){\n    osUmask(origM);\n  }\n#if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)\n  if( fd>=0 ) osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);\n#endif\n  return fd;\n}\n\n/*\n** Helper functions to obtain and relinquish the global mutex. The\n** global mutex is used to protect the unixInodeInfo and\n** vxworksFileId objects used by this file, all of which may be \n** shared by multiple threads.\n**\n** Function unixMutexHeld() is used to assert() that the global mutex \n** is held when required. This function is only used as part of assert() \n** statements. e.g.\n**\n**   unixEnterMutex()\n**     assert( unixMutexHeld() );\n**   unixEnterLeave()\n*/\nstatic void unixEnterMutex(void){\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\nstatic void unixLeaveMutex(void){\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n#ifdef SQLITE_DEBUG\nstatic int unixMutexHeld(void) {\n  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n#endif\n\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n/*\n** Helper function for printing out trace information from debugging\n** binaries. This returns the string represetation of the supplied\n** integer lock-type.\n*/\nstatic const char *azFileLock(int eFileLock){\n  switch( eFileLock ){\n    case NO_LOCK: return \"NONE\";\n    case SHARED_LOCK: return \"SHARED\";\n    case RESERVED_LOCK: return \"RESERVED\";\n    case PENDING_LOCK: return \"PENDING\";\n    case EXCLUSIVE_LOCK: return \"EXCLUSIVE\";\n  }\n  return \"ERROR\";\n}\n#endif\n\n#ifdef SQLITE_LOCK_TRACE\n/*\n** Print out information about all locking operations.\n**\n** This routine is used for troubleshooting locks on multithreaded\n** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE\n** command-line option on the compiler.  This code is normally\n** turned off.\n*/\nstatic int lockTrace(int fd, int op, struct flock *p){\n  char *zOpName, *zType;\n  int s;\n  int savedErrno;\n  if( op==F_GETLK ){\n    zOpName = \"GETLK\";\n  }else if( op==F_SETLK ){\n    zOpName = \"SETLK\";\n  }else{\n    s = osFcntl(fd, op, p);\n    sqlite3DebugPrintf(\"fcntl unknown %d %d %d\\n\", fd, op, s);\n    return s;\n  }\n  if( p->l_type==F_RDLCK ){\n    zType = \"RDLCK\";\n  }else if( p->l_type==F_WRLCK ){\n    zType = \"WRLCK\";\n  }else if( p->l_type==F_UNLCK ){\n    zType = \"UNLCK\";\n  }else{\n    assert( 0 );\n  }\n  assert( p->l_whence==SEEK_SET );\n  s = osFcntl(fd, op, p);\n  savedErrno = errno;\n  sqlite3DebugPrintf(\"fcntl %d %d %s %s %d %d %d %d\\n\",\n     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,\n     (int)p->l_pid, s);\n  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){\n    struct flock l2;\n    l2 = *p;\n    osFcntl(fd, F_GETLK, &l2);\n    if( l2.l_type==F_RDLCK ){\n      zType = \"RDLCK\";\n    }else if( l2.l_type==F_WRLCK ){\n      zType = \"WRLCK\";\n    }else if( l2.l_type==F_UNLCK ){\n      zType = \"UNLCK\";\n    }else{\n      assert( 0 );\n    }\n    sqlite3DebugPrintf(\"fcntl-failure-reason: %s %d %d %d\\n\",\n       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);\n  }\n  errno = savedErrno;\n  return s;\n}\n#undef osFcntl\n#define osFcntl lockTrace\n#endif /* SQLITE_LOCK_TRACE */\n\n/*\n** Retry ftruncate() calls that fail due to EINTR\n*/\nstatic int robust_ftruncate(int h, sqlite3_int64 sz){\n  int rc;\n  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );\n  return rc;\n}\n\n/*\n** This routine translates a standard POSIX errno code into something\n** useful to the clients of the sqlite3 functions.  Specifically, it is\n** intended to translate a variety of \"try again\" errors into SQLITE_BUSY\n** and a variety of \"please close the file descriptor NOW\" errors into \n** SQLITE_IOERR\n** \n** Errors during initialization of locks, or file system support for locks,\n** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.\n*/\nstatic int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {\n  switch (posixError) {\n#if 0\n  /* At one point this code was not commented out. In theory, this branch\n  ** should never be hit, as this function should only be called after\n  ** a locking-related function (i.e. fcntl()) has returned non-zero with\n  ** the value of errno as the first argument. Since a system call has failed,\n  ** errno should be non-zero.\n  **\n  ** Despite this, if errno really is zero, we still don't want to return\n  ** SQLITE_OK. The system call failed, and *some* SQLite error should be\n  ** propagated back to the caller. Commenting this branch out means errno==0\n  ** will be handled by the \"default:\" case below.\n  */\n  case 0: \n    return SQLITE_OK;\n#endif\n\n  case EAGAIN:\n  case ETIMEDOUT:\n  case EBUSY:\n  case EINTR:\n  case ENOLCK:  \n    /* random NFS retry error, unless during file system support \n     * introspection, in which it actually means what it says */\n    return SQLITE_BUSY;\n    \n  case EACCES: \n    /* EACCES is like EAGAIN during locking operations, but not any other time*/\n    if( (sqliteIOErr == SQLITE_IOERR_LOCK) || \n        (sqliteIOErr == SQLITE_IOERR_UNLOCK) || \n        (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||\n        (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){\n      return SQLITE_BUSY;\n    }\n    /* else fall through */\n  case EPERM: \n    return SQLITE_PERM;\n    \n  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And\n  ** this module never makes such a call. And the code in SQLite itself \n  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons\n  ** this case is also commented out. If the system does set errno to EDEADLK,\n  ** the default SQLITE_IOERR_XXX code will be returned. */\n#if 0\n  case EDEADLK:\n    return SQLITE_IOERR_BLOCKED;\n#endif\n    \n#if EOPNOTSUPP!=ENOTSUP\n  case EOPNOTSUPP: \n    /* something went terribly awry, unless during file system support \n     * introspection, in which it actually means what it says */\n#endif\n#ifdef ENOTSUP\n  case ENOTSUP: \n    /* invalid fd, unless during file system support introspection, in which \n     * it actually means what it says */\n#endif\n  case EIO:\n  case EBADF:\n  case EINVAL:\n  case ENOTCONN:\n  case ENODEV:\n  case ENXIO:\n  case ENOENT:\n#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */\n  case ESTALE:\n#endif\n  case ENOSYS:\n    /* these should force the client to close the file and reconnect */\n    \n  default: \n    return sqliteIOErr;\n  }\n}\n\n\n\n/******************************************************************************\n****************** Begin Unique File ID Utility Used By VxWorks ***************\n**\n** On most versions of unix, we can get a unique ID for a file by concatenating\n** the device number and the inode number.  But this does not work on VxWorks.\n** On VxWorks, a unique file id must be based on the canonical filename.\n**\n** A pointer to an instance of the following structure can be used as a\n** unique file ID in VxWorks.  Each instance of this structure contains\n** a copy of the canonical filename.  There is also a reference count.  \n** The structure is reclaimed when the number of pointers to it drops to\n** zero.\n**\n** There are never very many files open at one time and lookups are not\n** a performance-critical path, so it is sufficient to put these\n** structures on a linked list.\n*/\nstruct vxworksFileId {\n  struct vxworksFileId *pNext;  /* Next in a list of them all */\n  int nRef;                     /* Number of references to this one */\n  int nName;                    /* Length of the zCanonicalName[] string */\n  char *zCanonicalName;         /* Canonical filename */\n};\n\n#if OS_VXWORKS\n/* \n** All unique filenames are held on a linked list headed by this\n** variable:\n*/\nstatic struct vxworksFileId *vxworksFileList = 0;\n\n/*\n** Simplify a filename into its canonical form\n** by making the following changes:\n**\n**  * removing any trailing and duplicate /\n**  * convert /./ into just /\n**  * convert /A/../ where A is any simple name into just /\n**\n** Changes are made in-place.  Return the new name length.\n**\n** The original filename is in z[0..n-1].  Return the number of\n** characters in the simplified name.\n*/\nstatic int vxworksSimplifyName(char *z, int n){\n  int i, j;\n  while( n>1 && z[n-1]=='/' ){ n--; }\n  for(i=j=0; i<n; i++){\n    if( z[i]=='/' ){\n      if( z[i+1]=='/' ) continue;\n      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){\n        i += 1;\n        continue;\n      }\n      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){\n        while( j>0 && z[j-1]!='/' ){ j--; }\n        if( j>0 ){ j--; }\n        i += 2;\n        continue;\n      }\n    }\n    z[j++] = z[i];\n  }\n  z[j] = 0;\n  return j;\n}\n\n/*\n** Find a unique file ID for the given absolute pathname.  Return\n** a pointer to the vxworksFileId object.  This pointer is the unique\n** file ID.\n**\n** The nRef field of the vxworksFileId object is incremented before\n** the object is returned.  A new vxworksFileId object is created\n** and added to the global list if necessary.\n**\n** If a memory allocation error occurs, return NULL.\n*/\nstatic struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){\n  struct vxworksFileId *pNew;         /* search key and new file ID */\n  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */\n  int n;                              /* Length of zAbsoluteName string */\n\n  assert( zAbsoluteName[0]=='/' );\n  n = (int)strlen(zAbsoluteName);\n  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );\n  if( pNew==0 ) return 0;\n  pNew->zCanonicalName = (char*)&pNew[1];\n  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);\n  n = vxworksSimplifyName(pNew->zCanonicalName, n);\n\n  /* Search for an existing entry that matching the canonical name.\n  ** If found, increment the reference count and return a pointer to\n  ** the existing file ID.\n  */\n  unixEnterMutex();\n  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){\n    if( pCandidate->nName==n \n     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0\n    ){\n       sqlite3_free(pNew);\n       pCandidate->nRef++;\n       unixLeaveMutex();\n       return pCandidate;\n    }\n  }\n\n  /* No match was found.  We will make a new file ID */\n  pNew->nRef = 1;\n  pNew->nName = n;\n  pNew->pNext = vxworksFileList;\n  vxworksFileList = pNew;\n  unixLeaveMutex();\n  return pNew;\n}\n\n/*\n** Decrement the reference count on a vxworksFileId object.  Free\n** the object when the reference count reaches zero.\n*/\nstatic void vxworksReleaseFileId(struct vxworksFileId *pId){\n  unixEnterMutex();\n  assert( pId->nRef>0 );\n  pId->nRef--;\n  if( pId->nRef==0 ){\n    struct vxworksFileId **pp;\n    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}\n    assert( *pp==pId );\n    *pp = pId->pNext;\n    sqlite3_free(pId);\n  }\n  unixLeaveMutex();\n}\n#endif /* OS_VXWORKS */\n/*************** End of Unique File ID Utility Used By VxWorks ****************\n******************************************************************************/\n\n\n/******************************************************************************\n*************************** Posix Advisory Locking ****************************\n**\n** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)\n** section 6.5.2.2 lines 483 through 490 specify that when a process\n** sets or clears a lock, that operation overrides any prior locks set\n** by the same process.  It does not explicitly say so, but this implies\n** that it overrides locks set by the same process using a different\n** file descriptor.  Consider this test case:\n**\n**       int fd1 = open(\"./file1\", O_RDWR|O_CREAT, 0644);\n**       int fd2 = open(\"./file2\", O_RDWR|O_CREAT, 0644);\n**\n** Suppose ./file1 and ./file2 are really the same file (because\n** one is a hard or symbolic link to the other) then if you set\n** an exclusive lock on fd1, then try to get an exclusive lock\n** on fd2, it works.  I would have expected the second lock to\n** fail since there was already a lock on the file due to fd1.\n** But not so.  Since both locks came from the same process, the\n** second overrides the first, even though they were on different\n** file descriptors opened on different file names.\n**\n** This means that we cannot use POSIX locks to synchronize file access\n** among competing threads of the same process.  POSIX locks will work fine\n** to synchronize access for threads in separate processes, but not\n** threads within the same process.\n**\n** To work around the problem, SQLite has to manage file locks internally\n** on its own.  Whenever a new database is opened, we have to find the\n** specific inode of the database file (the inode is determined by the\n** st_dev and st_ino fields of the stat structure that fstat() fills in)\n** and check for locks already existing on that inode.  When locks are\n** created or removed, we have to look at our own internal record of the\n** locks to see if another thread has previously set a lock on that same\n** inode.\n**\n** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.\n** For VxWorks, we have to use the alternative unique ID system based on\n** canonical filename and implemented in the previous division.)\n**\n** The sqlite3_file structure for POSIX is no longer just an integer file\n** descriptor.  It is now a structure that holds the integer file\n** descriptor and a pointer to a structure that describes the internal\n** locks on the corresponding inode.  There is one locking structure\n** per inode, so if the same inode is opened twice, both unixFile structures\n** point to the same locking structure.  The locking structure keeps\n** a reference count (so we will know when to delete it) and a \"cnt\"\n** field that tells us its internal lock status.  cnt==0 means the\n** file is unlocked.  cnt==-1 means the file has an exclusive lock.\n** cnt>0 means there are cnt shared locks on the file.\n**\n** Any attempt to lock or unlock a file first checks the locking\n** structure.  The fcntl() system call is only invoked to set a \n** POSIX lock if the internal lock structure transitions between\n** a locked and an unlocked state.\n**\n** But wait:  there are yet more problems with POSIX advisory locks.\n**\n** If you close a file descriptor that points to a file that has locks,\n** all locks on that file that are owned by the current process are\n** released.  To work around this problem, each unixInodeInfo object\n** maintains a count of the number of pending locks on tha inode.\n** When an attempt is made to close an unixFile, if there are\n** other unixFile open on the same inode that are holding locks, the call\n** to close() the file descriptor is deferred until all of the locks clear.\n** The unixInodeInfo structure keeps a list of file descriptors that need to\n** be closed and that list is walked (and cleared) when the last lock\n** clears.\n**\n** Yet another problem:  LinuxThreads do not play well with posix locks.\n**\n** Many older versions of linux use the LinuxThreads library which is\n** not posix compliant.  Under LinuxThreads, a lock created by thread\n** A cannot be modified or overridden by a different thread B.\n** Only thread A can modify the lock.  Locking behavior is correct\n** if the appliation uses the newer Native Posix Thread Library (NPTL)\n** on linux - with NPTL a lock created by thread A can override locks\n** in thread B.  But there is no way to know at compile-time which\n** threading library is being used.  So there is no way to know at\n** compile-time whether or not thread A can override locks on thread B.\n** One has to do a run-time check to discover the behavior of the\n** current process.\n**\n** SQLite used to support LinuxThreads.  But support for LinuxThreads\n** was dropped beginning with version 3.7.0.  SQLite will still work with\n** LinuxThreads provided that (1) there is no more than one connection \n** per database file in the same process and (2) database connections\n** do not move across threads.\n*/\n\n/*\n** An instance of the following structure serves as the key used\n** to locate a particular unixInodeInfo object.\n*/\nstruct unixFileId {\n  dev_t dev;                  /* Device number */\n#if OS_VXWORKS\n  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */\n#else\n  ino_t ino;                  /* Inode number */\n#endif\n};\n\n/*\n** An instance of the following structure is allocated for each open\n** inode.  Or, on LinuxThreads, there is one of these structures for\n** each inode opened by each thread.\n**\n** A single inode can have multiple file descriptors, so each unixFile\n** structure contains a pointer to an instance of this object and this\n** object keeps a count of the number of unixFile pointing to it.\n*/\nstruct unixInodeInfo {\n  struct unixFileId fileId;       /* The lookup key */\n  int nShared;                    /* Number of SHARED locks held */\n  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */\n  unsigned char bProcessLock;     /* An exclusive process lock is held */\n  int nRef;                       /* Number of pointers to this structure */\n  unixShmNode *pShmNode;          /* Shared memory associated with this inode */\n  int nLock;                      /* Number of outstanding file locks */\n  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */\n  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */\n  unixInodeInfo *pPrev;           /*    .... doubly linked */\n#if SQLITE_ENABLE_LOCKING_STYLE\n  unsigned long long sharedByte;  /* for AFP simulated shared lock */\n#endif\n#if OS_VXWORKS\n  sem_t *pSem;                    /* Named POSIX semaphore */\n  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */\n#endif\n};\n\n/*\n** A lists of all unixInodeInfo objects.\n*/\nstatic unixInodeInfo *inodeList = 0;\n\n/*\n**\n** This function - unixLogError_x(), is only ever called via the macro\n** unixLogError().\n**\n** It is invoked after an error occurs in an OS function and errno has been\n** set. It logs a message using sqlite3_log() containing the current value of\n** errno and, if possible, the human-readable equivalent from strerror() or\n** strerror_r().\n**\n** The first argument passed to the macro should be the error code that\n** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). \n** The two subsequent arguments should be the name of the OS function that\n** failed (e.g. \"unlink\", \"open\") and the associated file-system path,\n** if any.\n*/\n#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)\nstatic int unixLogErrorAtLine(\n  int errcode,                    /* SQLite error code */\n  const char *zFunc,              /* Name of OS function that failed */\n  const char *zPath,              /* File path associated with error */\n  int iLine                       /* Source line number where error occurred */\n){\n  char *zErr;                     /* Message from strerror() or equivalent */\n  int iErrno = errno;             /* Saved syscall error number */\n\n  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use\n  ** the strerror() function to obtain the human-readable error message\n  ** equivalent to errno. Otherwise, use strerror_r().\n  */ \n#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)\n  char aErr[80];\n  memset(aErr, 0, sizeof(aErr));\n  zErr = aErr;\n\n  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,\n  ** assume that the system provides the GNU version of strerror_r() that\n  ** returns a pointer to a buffer containing the error message. That pointer \n  ** may point to aErr[], or it may point to some static storage somewhere. \n  ** Otherwise, assume that the system provides the POSIX version of \n  ** strerror_r(), which always writes an error message into aErr[].\n  **\n  ** If the code incorrectly assumes that it is the POSIX version that is\n  ** available, the error message will often be an empty string. Not a\n  ** huge problem. Incorrectly concluding that the GNU version is available \n  ** could lead to a segfault though.\n  */\n#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)\n  zErr = \n# endif\n  strerror_r(iErrno, aErr, sizeof(aErr)-1);\n\n#elif SQLITE_THREADSAFE\n  /* This is a threadsafe build, but strerror_r() is not available. */\n  zErr = \"\";\n#else\n  /* Non-threadsafe build, use strerror(). */\n  zErr = strerror(iErrno);\n#endif\n\n  assert( errcode!=SQLITE_OK );\n  if( zPath==0 ) zPath = \"\";\n  sqlite3_log(errcode,\n      \"os_unix.c:%d: (%d) %s(%s) - %s\",\n      iLine, iErrno, zFunc, zPath, zErr\n  );\n\n  return errcode;\n}\n\n/*\n** Close a file descriptor.\n**\n** We assume that close() almost always works, since it is only in a\n** very sick application or on a very sick platform that it might fail.\n** If it does fail, simply leak the file descriptor, but do log the\n** error.\n**\n** Note that it is not safe to retry close() after EINTR since the\n** file descriptor might have already been reused by another thread.\n** So we don't even try to recover from an EINTR.  Just log the error\n** and move on.\n*/\nstatic void robust_close(unixFile *pFile, int h, int lineno){\n  if( osClose(h) ){\n    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, \"close\",\n                       pFile ? pFile->zPath : 0, lineno);\n  }\n}\n\n/*\n** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.\n*/ \nstatic void closePendingFds(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  UnixUnusedFd *p;\n  UnixUnusedFd *pNext;\n  for(p=pInode->pUnused; p; p=pNext){\n    pNext = p->pNext;\n    robust_close(pFile, p->fd, __LINE__);\n    sqlite3_free(p);\n  }\n  pInode->pUnused = 0;\n}\n\n/*\n** Release a unixInodeInfo structure previously allocated by findInodeInfo().\n**\n** The mutex entered using the unixEnterMutex() function must be held\n** when this function is called.\n*/\nstatic void releaseInodeInfo(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  assert( unixMutexHeld() );\n  if( ALWAYS(pInode) ){\n    pInode->nRef--;\n    if( pInode->nRef==0 ){\n      assert( pInode->pShmNode==0 );\n      closePendingFds(pFile);\n      if( pInode->pPrev ){\n        assert( pInode->pPrev->pNext==pInode );\n        pInode->pPrev->pNext = pInode->pNext;\n      }else{\n        assert( inodeList==pInode );\n        inodeList = pInode->pNext;\n      }\n      if( pInode->pNext ){\n        assert( pInode->pNext->pPrev==pInode );\n        pInode->pNext->pPrev = pInode->pPrev;\n      }\n      sqlite3_free(pInode);\n    }\n  }\n}\n\n/*\n** Given a file descriptor, locate the unixInodeInfo object that\n** describes that file descriptor.  Create a new one if necessary.  The\n** return value might be uninitialized if an error occurs.\n**\n** The mutex entered using the unixEnterMutex() function must be held\n** when this function is called.\n**\n** Return an appropriate error code.\n*/\nstatic int findInodeInfo(\n  unixFile *pFile,               /* Unix file with file desc used in the key */\n  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */\n){\n  int rc;                        /* System call return code */\n  int fd;                        /* The file descriptor for pFile */\n  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */\n  struct stat statbuf;           /* Low-level file information */\n  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */\n\n  assert( unixMutexHeld() );\n\n  /* Get low-level information about the file that we can used to\n  ** create a unique name for the file.\n  */\n  fd = pFile->h;\n  rc = osFstat(fd, &statbuf);\n  if( rc!=0 ){\n    pFile->lastErrno = errno;\n#ifdef EOVERFLOW\n    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;\n#endif\n    return SQLITE_IOERR;\n  }\n\n#ifdef __APPLE__\n  /* On OS X on an msdos filesystem, the inode number is reported\n  ** incorrectly for zero-size files.  See ticket #3260.  To work\n  ** around this problem (we consider it a bug in OS X, not SQLite)\n  ** we always increase the file size to 1 by writing a single byte\n  ** prior to accessing the inode number.  The one byte written is\n  ** an ASCII 'S' character which also happens to be the first byte\n  ** in the header of every SQLite database.  In this way, if there\n  ** is a race condition such that another thread has already populated\n  ** the first page of the database, no damage is done.\n  */\n  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){\n    do{ rc = osWrite(fd, \"S\", 1); }while( rc<0 && errno==EINTR );\n    if( rc!=1 ){\n      pFile->lastErrno = errno;\n      return SQLITE_IOERR;\n    }\n    rc = osFstat(fd, &statbuf);\n    if( rc!=0 ){\n      pFile->lastErrno = errno;\n      return SQLITE_IOERR;\n    }\n  }\n#endif\n\n  memset(&fileId, 0, sizeof(fileId));\n  fileId.dev = statbuf.st_dev;\n#if OS_VXWORKS\n  fileId.pId = pFile->pId;\n#else\n  fileId.ino = statbuf.st_ino;\n#endif\n  pInode = inodeList;\n  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){\n    pInode = pInode->pNext;\n  }\n  if( pInode==0 ){\n    pInode = sqlite3_malloc( sizeof(*pInode) );\n    if( pInode==0 ){\n      return SQLITE_NOMEM;\n    }\n    memset(pInode, 0, sizeof(*pInode));\n    memcpy(&pInode->fileId, &fileId, sizeof(fileId));\n    pInode->nRef = 1;\n    pInode->pNext = inodeList;\n    pInode->pPrev = 0;\n    if( inodeList ) inodeList->pPrev = pInode;\n    inodeList = pInode;\n  }else{\n    pInode->nRef++;\n  }\n  *ppInode = pInode;\n  return SQLITE_OK;\n}\n\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int unixCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n\n  assert( pFile );\n  unixEnterMutex(); /* Because pFile->pInode is shared across threads */\n\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->pInode->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n\n  /* Otherwise see if some other process holds it.\n  */\n#ifndef __DJGPP__\n  if( !reserved && !pFile->pInode->bProcessLock ){\n    struct flock lock;\n    lock.l_whence = SEEK_SET;\n    lock.l_start = RESERVED_BYTE;\n    lock.l_len = 1;\n    lock.l_type = F_WRLCK;\n    if( osFcntl(pFile->h, F_GETLK, &lock) ){\n      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;\n      pFile->lastErrno = errno;\n    } else if( lock.l_type!=F_UNLCK ){\n      reserved = 1;\n    }\n  }\n#endif\n  \n  unixLeaveMutex();\n  OSTRACE((\"TEST WR-LOCK %d %d %d (unix)\\n\", pFile->h, rc, reserved));\n\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Attempt to set a system-lock on the file pFile.  The lock is \n** described by pLock.\n**\n** If the pFile was opened read/write from unix-excl, then the only lock\n** ever obtained is an exclusive lock, and it is obtained exactly once\n** the first time any lock is attempted.  All subsequent system locking\n** operations become no-ops.  Locking operations still happen internally,\n** in order to coordinate access between separate database connections\n** within this process, but all of that is handled in memory and the\n** operating system does not participate.\n**\n** This function is a pass-through to fcntl(F_SETLK) if pFile is using\n** any VFS other than \"unix-excl\" or if pFile is opened on \"unix-excl\"\n** and is read-only.\n**\n** Zero is returned if the call completes successfully, or -1 if a call\n** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).\n*/\nstatic int unixFileLock(unixFile *pFile, struct flock *pLock){\n  int rc;\n  unixInodeInfo *pInode = pFile->pInode;\n  assert( unixMutexHeld() );\n  assert( pInode!=0 );\n  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)\n   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)\n  ){\n    if( pInode->bProcessLock==0 ){\n      struct flock lock;\n      assert( pInode->nLock==0 );\n      lock.l_whence = SEEK_SET;\n      lock.l_start = SHARED_FIRST;\n      lock.l_len = SHARED_SIZE;\n      lock.l_type = F_WRLCK;\n      rc = osFcntl(pFile->h, F_SETLK, &lock);\n      if( rc<0 ) return rc;\n      pInode->bProcessLock = 1;\n      pInode->nLock++;\n    }else{\n      rc = 0;\n    }\n  }else{\n    rc = osFcntl(pFile->h, F_SETLK, pLock);\n  }\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int unixLock(sqlite3_file *id, int eFileLock){\n  /* The following describes the implementation of the various locks and\n  ** lock transitions in terms of the POSIX advisory shared and exclusive\n  ** lock primitives (called read-locks and write-locks below, to avoid\n  ** confusion with SQLite lock names). The algorithms are complicated\n  ** slightly in order to be compatible with windows systems simultaneously\n  ** accessing the same database file, in case that is ever required.\n  **\n  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved\n  ** byte', each single bytes at well known offsets, and the 'shared byte\n  ** range', a range of 510 bytes at a well known offset.\n  **\n  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending\n  ** byte'.  If this is successful, a random byte from the 'shared byte\n  ** range' is read-locked and the lock on the 'pending byte' released.\n  **\n  ** A process may only obtain a RESERVED lock after it has a SHARED lock.\n  ** A RESERVED lock is implemented by grabbing a write-lock on the\n  ** 'reserved byte'. \n  **\n  ** A process may only obtain a PENDING lock after it has obtained a\n  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock\n  ** on the 'pending byte'. This ensures that no new SHARED locks can be\n  ** obtained, but existing SHARED locks are allowed to persist. A process\n  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.\n  ** This property is used by the algorithm for rolling back a journal file\n  ** after a crash.\n  **\n  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is\n  ** implemented by obtaining a write-lock on the entire 'shared byte\n  ** range'. Since all other locks require a read-lock on one of the bytes\n  ** within this range, this ensures that no other locks are held on the\n  ** database. \n  **\n  ** The reason a single byte cannot be used instead of the 'shared byte\n  ** range' is that some versions of windows do not support read-locks. By\n  ** locking a random byte from a range, concurrent SHARED locks may exist\n  ** even if the locking primitive used is always a write-lock.\n  */\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  struct flock lock;\n  int tErrno = 0;\n\n  assert( pFile );\n  OSTRACE((\"LOCK    %d %s was %s(%s,%d) pid=%d (unix)\\n\", pFile->h,\n      azFileLock(eFileLock), azFileLock(pFile->eFileLock),\n      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** unixFile, do nothing. Don't use the end_lock: exit path, as\n  ** unixEnterMutex() hasn't been called yet.\n  */\n  if( pFile->eFileLock>=eFileLock ){\n    OSTRACE((\"LOCK    %d %s ok (already held) (unix)\\n\", pFile->h,\n            azFileLock(eFileLock)));\n    return SQLITE_OK;\n  }\n\n  /* Make sure the locking sequence is correct.\n  **  (1) We never move from unlocked to anything higher than shared lock.\n  **  (2) SQLite never explicitly requests a pendig lock.\n  **  (3) A shared lock is always held when a reserve lock is requested.\n  */\n  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );\n  assert( eFileLock!=PENDING_LOCK );\n  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );\n\n  /* This mutex is needed because pFile->pInode is shared across threads\n  */\n  unixEnterMutex();\n  pInode = pFile->pInode;\n\n  /* If some thread using this PID has a lock via a different unixFile*\n  ** handle that precludes the requested lock, return BUSY.\n  */\n  if( (pFile->eFileLock!=pInode->eFileLock && \n          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))\n  ){\n    rc = SQLITE_BUSY;\n    goto end_lock;\n  }\n\n  /* If a SHARED lock is requested, and some thread using this PID already\n  ** has a SHARED or RESERVED lock, then increment reference counts and\n  ** return SQLITE_OK.\n  */\n  if( eFileLock==SHARED_LOCK && \n      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){\n    assert( eFileLock==SHARED_LOCK );\n    assert( pFile->eFileLock==0 );\n    assert( pInode->nShared>0 );\n    pFile->eFileLock = SHARED_LOCK;\n    pInode->nShared++;\n    pInode->nLock++;\n    goto end_lock;\n  }\n\n\n  /* A PENDING lock is needed before acquiring a SHARED lock and before\n  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will\n  ** be released.\n  */\n  lock.l_len = 1L;\n  lock.l_whence = SEEK_SET;\n  if( eFileLock==SHARED_LOCK \n      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)\n  ){\n    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);\n    lock.l_start = PENDING_BYTE;\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( rc!=SQLITE_BUSY ){\n        pFile->lastErrno = tErrno;\n      }\n      goto end_lock;\n    }\n  }\n\n\n  /* If control gets to this point, then actually go ahead and make\n  ** operating system calls for the specified lock.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    assert( pInode->nShared==0 );\n    assert( pInode->eFileLock==0 );\n    assert( rc==SQLITE_OK );\n\n    /* Now get the read-lock */\n    lock.l_start = SHARED_FIRST;\n    lock.l_len = SHARED_SIZE;\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n    }\n\n    /* Drop the temporary PENDING lock */\n    lock.l_start = PENDING_BYTE;\n    lock.l_len = 1L;\n    lock.l_type = F_UNLCK;\n    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){\n      /* This could happen with a network mount */\n      tErrno = errno;\n      rc = SQLITE_IOERR_UNLOCK; \n    }\n\n    if( rc ){\n      if( rc!=SQLITE_BUSY ){\n        pFile->lastErrno = tErrno;\n      }\n      goto end_lock;\n    }else{\n      pFile->eFileLock = SHARED_LOCK;\n      pInode->nLock++;\n      pInode->nShared = 1;\n    }\n  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){\n    /* We are trying for an exclusive lock but another thread in this\n    ** same process is still holding a shared lock. */\n    rc = SQLITE_BUSY;\n  }else{\n    /* The request was for a RESERVED or EXCLUSIVE lock.  It is\n    ** assumed that there is a SHARED or greater lock on the file\n    ** already.\n    */\n    assert( 0!=pFile->eFileLock );\n    lock.l_type = F_WRLCK;\n\n    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );\n    if( eFileLock==RESERVED_LOCK ){\n      lock.l_start = RESERVED_BYTE;\n      lock.l_len = 1L;\n    }else{\n      lock.l_start = SHARED_FIRST;\n      lock.l_len = SHARED_SIZE;\n    }\n\n    if( unixFileLock(pFile, &lock) ){\n      tErrno = errno;\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( rc!=SQLITE_BUSY ){\n        pFile->lastErrno = tErrno;\n      }\n    }\n  }\n  \n\n#ifdef SQLITE_DEBUG\n  /* Set up the transaction-counter change checking flags when\n  ** transitioning from a SHARED to a RESERVED lock.  The change\n  ** from SHARED to RESERVED marks the beginning of a normal\n  ** write operation (not a hot journal rollback).\n  */\n  if( rc==SQLITE_OK\n   && pFile->eFileLock<=SHARED_LOCK\n   && eFileLock==RESERVED_LOCK\n  ){\n    pFile->transCntrChng = 0;\n    pFile->dbUpdate = 0;\n    pFile->inNormalWrite = 1;\n  }\n#endif\n\n\n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n    pInode->eFileLock = eFileLock;\n  }else if( eFileLock==EXCLUSIVE_LOCK ){\n    pFile->eFileLock = PENDING_LOCK;\n    pInode->eFileLock = PENDING_LOCK;\n  }\n\nend_lock:\n  unixLeaveMutex();\n  OSTRACE((\"LOCK    %d %s %s (unix)\\n\", pFile->h, azFileLock(eFileLock), \n      rc==SQLITE_OK ? \"ok\" : \"failed\"));\n  return rc;\n}\n\n/*\n** Add the file descriptor used by file handle pFile to the corresponding\n** pUnused list.\n*/\nstatic void setPendingFd(unixFile *pFile){\n  unixInodeInfo *pInode = pFile->pInode;\n  UnixUnusedFd *p = pFile->pUnused;\n  p->pNext = pInode->pUnused;\n  pInode->pUnused = p;\n  pFile->h = -1;\n  pFile->pUnused = 0;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n** \n** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED\n** the byte range is divided into 2 parts and the first part is unlocked then\n** set to a read lock, then the other part is simply unlocked.  This works \n** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to \n** remove the write lock on a region when a read lock is set.\n*/\nstatic int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  struct flock lock;\n  int rc = SQLITE_OK;\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\\n\", pFile->h, eFileLock,\n      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,\n      getpid()));\n\n  assert( eFileLock<=SHARED_LOCK );\n  if( pFile->eFileLock<=eFileLock ){\n    return SQLITE_OK;\n  }\n  unixEnterMutex();\n  pInode = pFile->pInode;\n  assert( pInode->nShared!=0 );\n  if( pFile->eFileLock>SHARED_LOCK ){\n    assert( pInode->eFileLock==pFile->eFileLock );\n\n#ifdef SQLITE_DEBUG\n    /* When reducing a lock such that other processes can start\n    ** reading the database file again, make sure that the\n    ** transaction counter was updated if any part of the database\n    ** file changed.  If the transaction counter is not updated,\n    ** other connections to the same file might not realize that\n    ** the file has changed and hence might not know to flush their\n    ** cache.  The use of a stale cache can lead to database corruption.\n    */\n    pFile->inNormalWrite = 0;\n#endif\n\n    /* downgrading to a shared lock on NFS involves clearing the write lock\n    ** before establishing the readlock - to avoid a race condition we downgrade\n    ** the lock in 2 blocks, so that part of the range will be covered by a \n    ** write lock until the rest is covered by a read lock:\n    **  1:   [WWWWW]\n    **  2:   [....W]\n    **  3:   [RRRRW]\n    **  4:   [RRRR.]\n    */\n    if( eFileLock==SHARED_LOCK ){\n\n#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE\n      (void)handleNFSUnlock;\n      assert( handleNFSUnlock==0 );\n#endif\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n      if( handleNFSUnlock ){\n        int tErrno;               /* Error code from system call errors */\n        off_t divSize = SHARED_SIZE - 1;\n        \n        lock.l_type = F_UNLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = SQLITE_IOERR_UNLOCK;\n          if( IS_LOCK_ERROR(rc) ){\n            pFile->lastErrno = tErrno;\n          }\n          goto end_unlock;\n        }\n        lock.l_type = F_RDLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);\n          if( IS_LOCK_ERROR(rc) ){\n            pFile->lastErrno = tErrno;\n          }\n          goto end_unlock;\n        }\n        lock.l_type = F_UNLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST+divSize;\n        lock.l_len = SHARED_SIZE-divSize;\n        if( unixFileLock(pFile, &lock)==(-1) ){\n          tErrno = errno;\n          rc = SQLITE_IOERR_UNLOCK;\n          if( IS_LOCK_ERROR(rc) ){\n            pFile->lastErrno = tErrno;\n          }\n          goto end_unlock;\n        }\n      }else\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n      {\n        lock.l_type = F_RDLCK;\n        lock.l_whence = SEEK_SET;\n        lock.l_start = SHARED_FIRST;\n        lock.l_len = SHARED_SIZE;\n        if( unixFileLock(pFile, &lock) ){\n          /* In theory, the call to unixFileLock() cannot fail because another\n          ** process is holding an incompatible lock. If it does, this \n          ** indicates that the other process is not following the locking\n          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning\n          ** SQLITE_BUSY would confuse the upper layer (in practice it causes \n          ** an assert to fail). */ \n          rc = SQLITE_IOERR_RDLOCK;\n          pFile->lastErrno = errno;\n          goto end_unlock;\n        }\n      }\n    }\n    lock.l_type = F_UNLCK;\n    lock.l_whence = SEEK_SET;\n    lock.l_start = PENDING_BYTE;\n    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );\n    if( unixFileLock(pFile, &lock)==0 ){\n      pInode->eFileLock = SHARED_LOCK;\n    }else{\n      rc = SQLITE_IOERR_UNLOCK;\n      pFile->lastErrno = errno;\n      goto end_unlock;\n    }\n  }\n  if( eFileLock==NO_LOCK ){\n    /* Decrement the shared lock counter.  Release the lock using an\n    ** OS call only when all threads in this same process have released\n    ** the lock.\n    */\n    pInode->nShared--;\n    if( pInode->nShared==0 ){\n      lock.l_type = F_UNLCK;\n      lock.l_whence = SEEK_SET;\n      lock.l_start = lock.l_len = 0L;\n      if( unixFileLock(pFile, &lock)==0 ){\n        pInode->eFileLock = NO_LOCK;\n      }else{\n        rc = SQLITE_IOERR_UNLOCK;\n        pFile->lastErrno = errno;\n        pInode->eFileLock = NO_LOCK;\n        pFile->eFileLock = NO_LOCK;\n      }\n    }\n\n    /* Decrement the count of locks against this same file.  When the\n    ** count reaches zero, close any other file descriptors whose close\n    ** was deferred because of outstanding locks.\n    */\n    pInode->nLock--;\n    assert( pInode->nLock>=0 );\n    if( pInode->nLock==0 ){\n      closePendingFds(pFile);\n    }\n  }\n\nend_unlock:\n  unixLeaveMutex();\n  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int unixUnlock(sqlite3_file *id, int eFileLock){\n  return posixUnlock(id, eFileLock, 0);\n}\n\n/*\n** This function performs the parts of the \"close file\" operation \n** common to all locking schemes. It closes the directory and file\n** handles, if they are valid, and sets all fields of the unixFile\n** structure to 0.\n**\n** It is *not* necessary to hold the mutex when this routine is called,\n** even on VxWorks.  A mutex will be acquired on VxWorks by the\n** vxworksReleaseFileId() routine.\n*/\nstatic int closeUnixFile(sqlite3_file *id){\n  unixFile *pFile = (unixFile*)id;\n  if( pFile->h>=0 ){\n    robust_close(pFile, pFile->h, __LINE__);\n    pFile->h = -1;\n  }\n#if OS_VXWORKS\n  if( pFile->pId ){\n    if( pFile->ctrlFlags & UNIXFILE_DELETE ){\n      osUnlink(pFile->pId->zCanonicalName);\n    }\n    vxworksReleaseFileId(pFile->pId);\n    pFile->pId = 0;\n  }\n#endif\n  OSTRACE((\"CLOSE   %-3d\\n\", pFile->h));\n  OpenCounter(-1);\n  sqlite3_free(pFile->pUnused);\n  memset(pFile, 0, sizeof(unixFile));\n  return SQLITE_OK;\n}\n\n/*\n** Close a file.\n*/\nstatic int unixClose(sqlite3_file *id){\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile *)id;\n  unixUnlock(id, NO_LOCK);\n  unixEnterMutex();\n\n  /* unixFile.pInode is always valid here. Otherwise, a different close\n  ** routine (e.g. nolockClose()) would be called instead.\n  */\n  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );\n  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){\n    /* If there are outstanding locks, do not actually close the file just\n    ** yet because that would clear those locks.  Instead, add the file\n    ** descriptor to pInode->pUnused list.  It will be automatically closed \n    ** when the last lock is cleared.\n    */\n    setPendingFd(pFile);\n  }\n  releaseInodeInfo(pFile);\n  rc = closeUnixFile(id);\n  unixLeaveMutex();\n  return rc;\n}\n\n/************** End of the posix advisory lock implementation *****************\n******************************************************************************/\n\n/******************************************************************************\n****************************** No-op Locking **********************************\n**\n** Of the various locking implementations available, this is by far the\n** simplest:  locking is ignored.  No attempt is made to lock the database\n** file for reading or writing.\n**\n** This locking mode is appropriate for use on read-only databases\n** (ex: databases that are burned into CD-ROM, for example.)  It can\n** also be used if the application employs some external mechanism to\n** prevent simultaneous access of the same database by two or more\n** database connections.  But there is a serious risk of database\n** corruption if this locking mode is used in situations where multiple\n** database connections are accessing the same database file at the same\n** time and one or more of those connections are writing.\n*/\n\nstatic int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){\n  UNUSED_PARAMETER(NotUsed);\n  *pResOut = 0;\n  return SQLITE_OK;\n}\nstatic int nolockLock(sqlite3_file *NotUsed, int NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return SQLITE_OK;\n}\nstatic int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return SQLITE_OK;\n}\n\n/*\n** Close the file.\n*/\nstatic int nolockClose(sqlite3_file *id) {\n  return closeUnixFile(id);\n}\n\n/******************* End of the no-op lock implementation *********************\n******************************************************************************/\n\n/******************************************************************************\n************************* Begin dot-file Locking ******************************\n**\n** The dotfile locking implementation uses the existance of separate lock\n** files (really a directory) to control access to the database.  This works\n** on just about every filesystem imaginable.  But there are serious downsides:\n**\n**    (1)  There is zero concurrency.  A single reader blocks all other\n**         connections from reading or writing the database.\n**\n**    (2)  An application crash or power loss can leave stale lock files\n**         sitting around that need to be cleared manually.\n**\n** Nevertheless, a dotlock is an appropriate locking mode for use if no\n** other locking strategy is available.\n**\n** Dotfile locking works by creating a subdirectory in the same directory as\n** the database and with the same name but with a \".lock\" extension added.\n** The existance of a lock directory implies an EXCLUSIVE lock.  All other\n** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.\n*/\n\n/*\n** The file suffix added to the data base filename in order to create the\n** lock directory.\n*/\n#define DOTLOCK_SUFFIX \".lock\"\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n**\n** In dotfile locking, either a lock exists or it does not.  So in this\n** variation of CheckReservedLock(), *pResOut is set to true if any lock\n** is held on the file and false if the file is unlocked.\n*/\nstatic int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->eFileLock>SHARED_LOCK ){\n    /* Either this connection or some other connection in the same process\n    ** holds a lock on the file.  No need to check further. */\n    reserved = 1;\n  }else{\n    /* The lock is held if and only if the lockfile exists */\n    const char *zLockFile = (const char*)pFile->lockingContext;\n    reserved = osAccess(zLockFile, 0)==0;\n  }\n  OSTRACE((\"TEST WR-LOCK %d %d %d (dotlock)\\n\", pFile->h, rc, reserved));\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n**\n** With dotfile locking, we really only support state (4): EXCLUSIVE.\n** But we track the other locking levels internally.\n*/\nstatic int dotlockLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  char *zLockFile = (char *)pFile->lockingContext;\n  int rc = SQLITE_OK;\n\n\n  /* If we have any lock, then the lock file already exists.  All we have\n  ** to do is adjust our internal record of the lock level.\n  */\n  if( pFile->eFileLock > NO_LOCK ){\n    pFile->eFileLock = eFileLock;\n    /* Always update the timestamp on the old file */\n#ifdef HAVE_UTIME\n    utime(zLockFile, NULL);\n#else\n    utimes(zLockFile, NULL);\n#endif\n    return SQLITE_OK;\n  }\n  \n  /* grab an exclusive lock */\n  rc = osMkdir(zLockFile, 0777);\n  if( rc<0 ){\n    /* failed to open/create the lock directory */\n    int tErrno = errno;\n    if( EEXIST == tErrno ){\n      rc = SQLITE_BUSY;\n    } else {\n      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n      if( IS_LOCK_ERROR(rc) ){\n        pFile->lastErrno = tErrno;\n      }\n    }\n    return rc;\n  } \n  \n  /* got it, set the type and return ok */\n  pFile->eFileLock = eFileLock;\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n**\n** When the locking level reaches NO_LOCK, delete the lock file.\n*/\nstatic int dotlockUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  char *zLockFile = (char *)pFile->lockingContext;\n  int rc;\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (dotlock)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, getpid()));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n\n  /* To downgrade to shared, simply update our internal notion of the\n  ** lock state.  No need to mess with the file on disk.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    pFile->eFileLock = SHARED_LOCK;\n    return SQLITE_OK;\n  }\n  \n  /* To fully unlock the database, delete the lock file */\n  assert( eFileLock==NO_LOCK );\n  rc = osRmdir(zLockFile);\n  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);\n  if( rc<0 ){\n    int tErrno = errno;\n    rc = 0;\n    if( ENOENT != tErrno ){\n      rc = SQLITE_IOERR_UNLOCK;\n    }\n    if( IS_LOCK_ERROR(rc) ){\n      pFile->lastErrno = tErrno;\n    }\n    return rc; \n  }\n  pFile->eFileLock = NO_LOCK;\n  return SQLITE_OK;\n}\n\n/*\n** Close a file.  Make sure the lock has been released before closing.\n*/\nstatic int dotlockClose(sqlite3_file *id) {\n  int rc;\n  if( id ){\n    unixFile *pFile = (unixFile*)id;\n    dotlockUnlock(id, NO_LOCK);\n    sqlite3_free(pFile->lockingContext);\n  }\n  rc = closeUnixFile(id);\n  return rc;\n}\n/****************** End of the dot-file lock implementation *******************\n******************************************************************************/\n\n/******************************************************************************\n************************** Begin flock Locking ********************************\n**\n** Use the flock() system call to do file locking.\n**\n** flock() locking is like dot-file locking in that the various\n** fine-grain locking levels supported by SQLite are collapsed into\n** a single exclusive lock.  In other words, SHARED, RESERVED, and\n** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite\n** still works when you do this, but concurrency is reduced since\n** only a single process can be reading the database at a time.\n**\n** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if\n** compiling for VXWORKS.\n*/\n#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS\n\n/*\n** Retry flock() calls that fail with EINTR\n*/\n#ifdef EINTR\nstatic int robust_flock(int fd, int op){\n  int rc;\n  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );\n  return rc;\n}\n#else\n# define robust_flock(a,b) flock(a,b)\n#endif\n     \n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int flockCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n  \n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n  \n  /* Check if a thread in this process holds such a lock */\n  if( pFile->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it. */\n  if( !reserved ){\n    /* attempt to get the lock */\n    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);\n    if( !lrc ){\n      /* got the lock, unlock it */\n      lrc = robust_flock(pFile->h, LOCK_UN);\n      if ( lrc ) {\n        int tErrno = errno;\n        /* unlock failed with an error */\n        lrc = SQLITE_IOERR_UNLOCK; \n        if( IS_LOCK_ERROR(lrc) ){\n          pFile->lastErrno = tErrno;\n          rc = lrc;\n        }\n      }\n    } else {\n      int tErrno = errno;\n      reserved = 1;\n      /* someone else might have it reserved */\n      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); \n      if( IS_LOCK_ERROR(lrc) ){\n        pFile->lastErrno = tErrno;\n        rc = lrc;\n      }\n    }\n  }\n  OSTRACE((\"TEST WR-LOCK %d %d %d (flock)\\n\", pFile->h, rc, reserved));\n\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){\n    rc = SQLITE_OK;\n    reserved=1;\n  }\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** flock() only really support EXCLUSIVE locks.  We track intermediate\n** lock states in the sqlite3_file structure, but all locks SHARED or\n** above are really EXCLUSIVE locks and exclude all other processes from\n** access the file.\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int flockLock(sqlite3_file *id, int eFileLock) {\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n\n  assert( pFile );\n\n  /* if we already have a lock, it is exclusive.  \n  ** Just adjust level and punt on outta here. */\n  if (pFile->eFileLock > NO_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* grab an exclusive lock */\n  \n  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {\n    int tErrno = errno;\n    /* didn't get, must be busy */\n    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);\n    if( IS_LOCK_ERROR(rc) ){\n      pFile->lastErrno = tErrno;\n    }\n  } else {\n    /* got it, set the type and return ok */\n    pFile->eFileLock = eFileLock;\n  }\n  OSTRACE((\"LOCK    %d %s %s (flock)\\n\", pFile->h, azFileLock(eFileLock), \n           rc==SQLITE_OK ? \"ok\" : \"failed\"));\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){\n    rc = SQLITE_BUSY;\n  }\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n  return rc;\n}\n\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int flockUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  \n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (flock)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, getpid()));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n  \n  /* shared can just be set because we always have an exclusive */\n  if (eFileLock==SHARED_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* no, really, unlock. */\n  if( robust_flock(pFile->h, LOCK_UN) ){\n#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS\n    return SQLITE_OK;\n#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */\n    return SQLITE_IOERR_UNLOCK;\n  }else{\n    pFile->eFileLock = NO_LOCK;\n    return SQLITE_OK;\n  }\n}\n\n/*\n** Close a file.\n*/\nstatic int flockClose(sqlite3_file *id) {\n  if( id ){\n    flockUnlock(id, NO_LOCK);\n  }\n  return closeUnixFile(id);\n}\n\n#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */\n\n/******************* End of the flock lock implementation *********************\n******************************************************************************/\n\n/******************************************************************************\n************************ Begin Named Semaphore Locking ************************\n**\n** Named semaphore locking is only supported on VxWorks.\n**\n** Semaphore locking is like dot-lock and flock in that it really only\n** supports EXCLUSIVE locking.  Only a single process can read or write\n** the database file at a time.  This reduces potential concurrency, but\n** makes the lock implementation much easier.\n*/\n#if OS_VXWORKS\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int semCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n\n  /* Check if a thread in this process holds such a lock */\n  if( pFile->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it. */\n  if( !reserved ){\n    sem_t *pSem = pFile->pInode->pSem;\n    struct stat statBuf;\n\n    if( sem_trywait(pSem)==-1 ){\n      int tErrno = errno;\n      if( EAGAIN != tErrno ){\n        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);\n        pFile->lastErrno = tErrno;\n      } else {\n        /* someone else has the lock when we are in NO_LOCK */\n        reserved = (pFile->eFileLock < SHARED_LOCK);\n      }\n    }else{\n      /* we could have it if we want it */\n      sem_post(pSem);\n    }\n  }\n  OSTRACE((\"TEST WR-LOCK %d %d %d (sem)\\n\", pFile->h, rc, reserved));\n\n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate\n** lock states in the sqlite3_file structure, but all locks SHARED or\n** above are really EXCLUSIVE locks and exclude all other processes from\n** access the file.\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int semLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  int fd;\n  sem_t *pSem = pFile->pInode->pSem;\n  int rc = SQLITE_OK;\n\n  /* if we already have a lock, it is exclusive.  \n  ** Just adjust level and punt on outta here. */\n  if (pFile->eFileLock > NO_LOCK) {\n    pFile->eFileLock = eFileLock;\n    rc = SQLITE_OK;\n    goto sem_end_lock;\n  }\n  \n  /* lock semaphore now but bail out when already locked. */\n  if( sem_trywait(pSem)==-1 ){\n    rc = SQLITE_BUSY;\n    goto sem_end_lock;\n  }\n\n  /* got it, set the type and return ok */\n  pFile->eFileLock = eFileLock;\n\n sem_end_lock:\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int semUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  sem_t *pSem = pFile->pInode->pSem;\n\n  assert( pFile );\n  assert( pSem );\n  OSTRACE((\"UNLOCK  %d %d was %d pid=%d (sem)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, getpid()));\n  assert( eFileLock<=SHARED_LOCK );\n  \n  /* no-op if possible */\n  if( pFile->eFileLock==eFileLock ){\n    return SQLITE_OK;\n  }\n  \n  /* shared can just be set because we always have an exclusive */\n  if (eFileLock==SHARED_LOCK) {\n    pFile->eFileLock = eFileLock;\n    return SQLITE_OK;\n  }\n  \n  /* no, really unlock. */\n  if ( sem_post(pSem)==-1 ) {\n    int rc, tErrno = errno;\n    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);\n    if( IS_LOCK_ERROR(rc) ){\n      pFile->lastErrno = tErrno;\n    }\n    return rc; \n  }\n  pFile->eFileLock = NO_LOCK;\n  return SQLITE_OK;\n}\n\n/*\n ** Close a file.\n */\nstatic int semClose(sqlite3_file *id) {\n  if( id ){\n    unixFile *pFile = (unixFile*)id;\n    semUnlock(id, NO_LOCK);\n    assert( pFile );\n    unixEnterMutex();\n    releaseInodeInfo(pFile);\n    unixLeaveMutex();\n    closeUnixFile(id);\n  }\n  return SQLITE_OK;\n}\n\n#endif /* OS_VXWORKS */\n/*\n** Named semaphore locking is only available on VxWorks.\n**\n*************** End of the named semaphore lock implementation ****************\n******************************************************************************/\n\n\n/******************************************************************************\n*************************** Begin AFP Locking *********************************\n**\n** AFP is the Apple Filing Protocol.  AFP is a network filesystem found\n** on Apple Macintosh computers - both OS9 and OSX.\n**\n** Third-party implementations of AFP are available.  But this code here\n** only works on OSX.\n*/\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/*\n** The afpLockingContext structure contains all afp lock specific state\n*/\ntypedef struct afpLockingContext afpLockingContext;\nstruct afpLockingContext {\n  int reserved;\n  const char *dbPath;             /* Name of the open file */\n};\n\nstruct ByteRangeLockPB2\n{\n  unsigned long long offset;        /* offset to first byte to lock */\n  unsigned long long length;        /* nbr of bytes to lock */\n  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */\n  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */\n  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */\n  int fd;                           /* file desc to assoc this lock with */\n};\n\n#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)\n\n/*\n** This is a utility for setting or clearing a bit-range lock on an\n** AFP filesystem.\n** \n** Return SQLITE_OK on success, SQLITE_BUSY on failure.\n*/\nstatic int afpSetLock(\n  const char *path,              /* Name of the file to be locked or unlocked */\n  unixFile *pFile,               /* Open file descriptor on path */\n  unsigned long long offset,     /* First byte to be locked */\n  unsigned long long length,     /* Number of bytes to lock */\n  int setLockFlag                /* True to set lock.  False to clear lock */\n){\n  struct ByteRangeLockPB2 pb;\n  int err;\n  \n  pb.unLockFlag = setLockFlag ? 0 : 1;\n  pb.startEndFlag = 0;\n  pb.offset = offset;\n  pb.length = length; \n  pb.fd = pFile->h;\n  \n  OSTRACE((\"AFPSETLOCK [%s] for %d%s in range %llx:%llx\\n\", \n    (setLockFlag?\"ON\":\"OFF\"), pFile->h, (pb.fd==-1?\"[testval-1]\":\"\"),\n    offset, length));\n  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);\n  if ( err==-1 ) {\n    int rc;\n    int tErrno = errno;\n    OSTRACE((\"AFPSETLOCK failed to fsctl() '%s' %d %s\\n\",\n             path, tErrno, strerror(tErrno)));\n#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS\n    rc = SQLITE_BUSY;\n#else\n    rc = sqliteErrorFromPosixError(tErrno,\n                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);\n#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */\n    if( IS_LOCK_ERROR(rc) ){\n      pFile->lastErrno = tErrno;\n    }\n    return rc;\n  } else {\n    return SQLITE_OK;\n  }\n}\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int afpCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc = SQLITE_OK;\n  int reserved = 0;\n  unixFile *pFile = (unixFile*)id;\n  afpLockingContext *context;\n  \n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n  \n  assert( pFile );\n  context = (afpLockingContext *) pFile->lockingContext;\n  if( context->reserved ){\n    *pResOut = 1;\n    return SQLITE_OK;\n  }\n  unixEnterMutex(); /* Because pFile->pInode is shared across threads */\n  \n  /* Check if a thread in this process holds such a lock */\n  if( pFile->pInode->eFileLock>SHARED_LOCK ){\n    reserved = 1;\n  }\n  \n  /* Otherwise see if some other process holds it.\n   */\n  if( !reserved ){\n    /* lock the RESERVED byte */\n    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  \n    if( SQLITE_OK==lrc ){\n      /* if we succeeded in taking the reserved lock, unlock it to restore\n      ** the original state */\n      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);\n    } else {\n      /* if we failed to get the lock then someone else must have it */\n      reserved = 1;\n    }\n    if( IS_LOCK_ERROR(lrc) ){\n      rc=lrc;\n    }\n  }\n  \n  unixLeaveMutex();\n  OSTRACE((\"TEST WR-LOCK %d %d %d (afp)\\n\", pFile->h, rc, reserved));\n  \n  *pResOut = reserved;\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int afpLock(sqlite3_file *id, int eFileLock){\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode = pFile->pInode;\n  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;\n  \n  assert( pFile );\n  OSTRACE((\"LOCK    %d %s was %s(%s,%d) pid=%d (afp)\\n\", pFile->h,\n           azFileLock(eFileLock), azFileLock(pFile->eFileLock),\n           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as\n  ** unixEnterMutex() hasn't been called yet.\n  */\n  if( pFile->eFileLock>=eFileLock ){\n    OSTRACE((\"LOCK    %d %s ok (already held) (afp)\\n\", pFile->h,\n           azFileLock(eFileLock)));\n    return SQLITE_OK;\n  }\n\n  /* Make sure the locking sequence is correct\n  **  (1) We never move from unlocked to anything higher than shared lock.\n  **  (2) SQLite never explicitly requests a pendig lock.\n  **  (3) A shared lock is always held when a reserve lock is requested.\n  */\n  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );\n  assert( eFileLock!=PENDING_LOCK );\n  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );\n  \n  /* This mutex is needed because pFile->pInode is shared across threads\n  */\n  unixEnterMutex();\n  pInode = pFile->pInode;\n\n  /* If some thread using this PID has a lock via a different unixFile*\n  ** handle that precludes the requested lock, return BUSY.\n  */\n  if( (pFile->eFileLock!=pInode->eFileLock && \n       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))\n     ){\n    rc = SQLITE_BUSY;\n    goto afp_end_lock;\n  }\n  \n  /* If a SHARED lock is requested, and some thread using this PID already\n  ** has a SHARED or RESERVED lock, then increment reference counts and\n  ** return SQLITE_OK.\n  */\n  if( eFileLock==SHARED_LOCK && \n     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){\n    assert( eFileLock==SHARED_LOCK );\n    assert( pFile->eFileLock==0 );\n    assert( pInode->nShared>0 );\n    pFile->eFileLock = SHARED_LOCK;\n    pInode->nShared++;\n    pInode->nLock++;\n    goto afp_end_lock;\n  }\n    \n  /* A PENDING lock is needed before acquiring a SHARED lock and before\n  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will\n  ** be released.\n  */\n  if( eFileLock==SHARED_LOCK \n      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)\n  ){\n    int failed;\n    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);\n    if (failed) {\n      rc = failed;\n      goto afp_end_lock;\n    }\n  }\n  \n  /* If control gets to this point, then actually go ahead and make\n  ** operating system calls for the specified lock.\n  */\n  if( eFileLock==SHARED_LOCK ){\n    int lrc1, lrc2, lrc1Errno = 0;\n    long lk, mask;\n    \n    assert( pInode->nShared==0 );\n    assert( pInode->eFileLock==0 );\n        \n    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;\n    /* Now get the read-lock SHARED_LOCK */\n    /* note that the quality of the randomness doesn't matter that much */\n    lk = random(); \n    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);\n    lrc1 = afpSetLock(context->dbPath, pFile, \n          SHARED_FIRST+pInode->sharedByte, 1, 1);\n    if( IS_LOCK_ERROR(lrc1) ){\n      lrc1Errno = pFile->lastErrno;\n    }\n    /* Drop the temporary PENDING lock */\n    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);\n    \n    if( IS_LOCK_ERROR(lrc1) ) {\n      pFile->lastErrno = lrc1Errno;\n      rc = lrc1;\n      goto afp_end_lock;\n    } else if( IS_LOCK_ERROR(lrc2) ){\n      rc = lrc2;\n      goto afp_end_lock;\n    } else if( lrc1 != SQLITE_OK ) {\n      rc = lrc1;\n    } else {\n      pFile->eFileLock = SHARED_LOCK;\n      pInode->nLock++;\n      pInode->nShared = 1;\n    }\n  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){\n    /* We are trying for an exclusive lock but another thread in this\n     ** same process is still holding a shared lock. */\n    rc = SQLITE_BUSY;\n  }else{\n    /* The request was for a RESERVED or EXCLUSIVE lock.  It is\n    ** assumed that there is a SHARED or greater lock on the file\n    ** already.\n    */\n    int failed = 0;\n    assert( 0!=pFile->eFileLock );\n    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {\n        /* Acquire a RESERVED lock */\n        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);\n      if( !failed ){\n        context->reserved = 1;\n      }\n    }\n    if (!failed && eFileLock == EXCLUSIVE_LOCK) {\n      /* Acquire an EXCLUSIVE lock */\n        \n      /* Remove the shared lock before trying the range.  we'll need to \n      ** reestablish the shared lock if we can't get the  afpUnlock\n      */\n      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +\n                         pInode->sharedByte, 1, 0)) ){\n        int failed2 = SQLITE_OK;\n        /* now attemmpt to get the exclusive lock range */\n        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, \n                               SHARED_SIZE, 1);\n        if( failed && (failed2 = afpSetLock(context->dbPath, pFile, \n                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){\n          /* Can't reestablish the shared lock.  Sqlite can't deal, this is\n          ** a critical I/O error\n          */\n          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : \n               SQLITE_IOERR_LOCK;\n          goto afp_end_lock;\n        } \n      }else{\n        rc = failed; \n      }\n    }\n    if( failed ){\n      rc = failed;\n    }\n  }\n  \n  if( rc==SQLITE_OK ){\n    pFile->eFileLock = eFileLock;\n    pInode->eFileLock = eFileLock;\n  }else if( eFileLock==EXCLUSIVE_LOCK ){\n    pFile->eFileLock = PENDING_LOCK;\n    pInode->eFileLock = PENDING_LOCK;\n  }\n  \nafp_end_lock:\n  unixLeaveMutex();\n  OSTRACE((\"LOCK    %d %s %s (afp)\\n\", pFile->h, azFileLock(eFileLock), \n         rc==SQLITE_OK ? \"ok\" : \"failed\"));\n  return rc;\n}\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int afpUnlock(sqlite3_file *id, int eFileLock) {\n  int rc = SQLITE_OK;\n  unixFile *pFile = (unixFile*)id;\n  unixInodeInfo *pInode;\n  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;\n  int skipShared = 0;\n#ifdef SQLITE_TEST\n  int h = pFile->h;\n#endif\n\n  assert( pFile );\n  OSTRACE((\"UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\\n\", pFile->h, eFileLock,\n           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,\n           getpid()));\n\n  assert( eFileLock<=SHARED_LOCK );\n  if( pFile->eFileLock<=eFileLock ){\n    return SQLITE_OK;\n  }\n  unixEnterMutex();\n  pInode = pFile->pInode;\n  assert( pInode->nShared!=0 );\n  if( pFile->eFileLock>SHARED_LOCK ){\n    assert( pInode->eFileLock==pFile->eFileLock );\n    SimulateIOErrorBenign(1);\n    SimulateIOError( h=(-1) )\n    SimulateIOErrorBenign(0);\n    \n#ifdef SQLITE_DEBUG\n    /* When reducing a lock such that other processes can start\n    ** reading the database file again, make sure that the\n    ** transaction counter was updated if any part of the database\n    ** file changed.  If the transaction counter is not updated,\n    ** other connections to the same file might not realize that\n    ** the file has changed and hence might not know to flush their\n    ** cache.  The use of a stale cache can lead to database corruption.\n    */\n    assert( pFile->inNormalWrite==0\n           || pFile->dbUpdate==0\n           || pFile->transCntrChng==1 );\n    pFile->inNormalWrite = 0;\n#endif\n    \n    if( pFile->eFileLock==EXCLUSIVE_LOCK ){\n      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);\n      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){\n        /* only re-establish the shared lock if necessary */\n        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;\n        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);\n      } else {\n        skipShared = 1;\n      }\n    }\n    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){\n      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);\n    } \n    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){\n      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);\n      if( !rc ){ \n        context->reserved = 0; \n      }\n    }\n    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){\n      pInode->eFileLock = SHARED_LOCK;\n    }\n  }\n  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){\n\n    /* Decrement the shared lock counter.  Release the lock using an\n    ** OS call only when all threads in this same process have released\n    ** the lock.\n    */\n    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;\n    pInode->nShared--;\n    if( pInode->nShared==0 ){\n      SimulateIOErrorBenign(1);\n      SimulateIOError( h=(-1) )\n      SimulateIOErrorBenign(0);\n      if( !skipShared ){\n        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);\n      }\n      if( !rc ){\n        pInode->eFileLock = NO_LOCK;\n        pFile->eFileLock = NO_LOCK;\n      }\n    }\n    if( rc==SQLITE_OK ){\n      pInode->nLock--;\n      assert( pInode->nLock>=0 );\n      if( pInode->nLock==0 ){\n        closePendingFds(pFile);\n      }\n    }\n  }\n  \n  unixLeaveMutex();\n  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;\n  return rc;\n}\n\n/*\n** Close a file & cleanup AFP specific locking context \n*/\nstatic int afpClose(sqlite3_file *id) {\n  int rc = SQLITE_OK;\n  if( id ){\n    unixFile *pFile = (unixFile*)id;\n    afpUnlock(id, NO_LOCK);\n    unixEnterMutex();\n    if( pFile->pInode && pFile->pInode->nLock ){\n      /* If there are outstanding locks, do not actually close the file just\n      ** yet because that would clear those locks.  Instead, add the file\n      ** descriptor to pInode->aPending.  It will be automatically closed when\n      ** the last lock is cleared.\n      */\n      setPendingFd(pFile);\n    }\n    releaseInodeInfo(pFile);\n    sqlite3_free(pFile->lockingContext);\n    rc = closeUnixFile(id);\n    unixLeaveMutex();\n  }\n  return rc;\n}\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The code above is the AFP lock implementation.  The code is specific\n** to MacOSX and does not work on other unix platforms.  No alternative\n** is available.  If you don't compile for a mac, then the \"unix-afp\"\n** VFS is not available.\n**\n********************* End of the AFP lock implementation **********************\n******************************************************************************/\n\n/******************************************************************************\n*************************** Begin NFS Locking ********************************/\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/*\n ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n ** must be either NO_LOCK or SHARED_LOCK.\n **\n ** If the locking level of the file descriptor is already at or below\n ** the requested locking level, this routine is a no-op.\n */\nstatic int nfsUnlock(sqlite3_file *id, int eFileLock){\n  return posixUnlock(id, eFileLock, 1);\n}\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The code above is the NFS lock implementation.  The code is specific\n** to MacOSX and does not work on other unix platforms.  No alternative\n** is available.  \n**\n********************* End of the NFS lock implementation **********************\n******************************************************************************/\n\n/******************************************************************************\n**************** Non-locking sqlite3_file methods *****************************\n**\n** The next division contains implementations for all methods of the \n** sqlite3_file object other than the locking methods.  The locking\n** methods were defined in divisions above (one locking method per\n** division).  Those methods that are common to all locking modes\n** are gather together into this division.\n*/\n\n/*\n** Seek to the offset passed as the second argument, then read cnt \n** bytes into pBuf. Return the number of bytes actually read.\n**\n** NB:  If you define USE_PREAD or USE_PREAD64, then it might also\n** be necessary to define _XOPEN_SOURCE to be 500.  This varies from\n** one system to another.  Since SQLite does not define USE_PREAD\n** any any form by default, we will not attempt to define _XOPEN_SOURCE.\n** See tickets #2741 and #2681.\n**\n** To avoid stomping the errno value on a failed read the lastErrno value\n** is set before returning.\n*/\nstatic int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){\n  int got;\n  int prior = 0;\n#if (!defined(USE_PREAD) && !defined(USE_PREAD64))\n  i64 newOffset;\n#endif\n  TIMER_START;\n  do{\n#if defined(USE_PREAD)\n    got = osPread(id->h, pBuf, cnt, offset);\n    SimulateIOError( got = -1 );\n#elif defined(USE_PREAD64)\n    got = osPread64(id->h, pBuf, cnt, offset);\n    SimulateIOError( got = -1 );\n#else\n    newOffset = lseek(id->h, offset, SEEK_SET);\n    SimulateIOError( newOffset-- );\n    if( newOffset!=offset ){\n      if( newOffset == -1 ){\n        ((unixFile*)id)->lastErrno = errno;\n      }else{\n        ((unixFile*)id)->lastErrno = 0;\n      }\n      return -1;\n    }\n    got = osRead(id->h, pBuf, cnt);\n#endif\n    if( got==cnt ) break;\n    if( got<0 ){\n      if( errno==EINTR ){ got = 1; continue; }\n      prior = 0;\n      ((unixFile*)id)->lastErrno = errno;\n      break;\n    }else if( got>0 ){\n      cnt -= got;\n      offset += got;\n      prior += got;\n      pBuf = (void*)(got + (char*)pBuf);\n    }\n  }while( got>0 );\n  TIMER_END;\n  OSTRACE((\"READ    %-3d %5d %7lld %llu\\n\",\n            id->h, got+prior, offset-prior, TIMER_ELAPSED));\n  return got+prior;\n}\n\n/*\n** Read data from a file into a buffer.  Return SQLITE_OK if all\n** bytes were read successfully and SQLITE_IOERR if anything goes\n** wrong.\n*/\nstatic int unixRead(\n  sqlite3_file *id, \n  void *pBuf, \n  int amt,\n  sqlite3_int64 offset\n){\n  unixFile *pFile = (unixFile *)id;\n  int got;\n  assert( id );\n\n  /* If this is a database file (not a journal, master-journal or temp\n  ** file), the bytes in the locking range should never be read or written. */\n#if 0\n  assert( pFile->pUnused==0\n       || offset>=PENDING_BYTE+512\n       || offset+amt<=PENDING_BYTE \n  );\n#endif\n\n  got = seekAndRead(pFile, offset, pBuf, amt);\n  if( got==amt ){\n    return SQLITE_OK;\n  }else if( got<0 ){\n    /* lastErrno set by seekAndRead */\n    return SQLITE_IOERR_READ;\n  }else{\n    pFile->lastErrno = 0; /* not a system error */\n    /* Unread parts of the buffer must be zero-filled */\n    memset(&((char*)pBuf)[got], 0, amt-got);\n    return SQLITE_IOERR_SHORT_READ;\n  }\n}\n\n/*\n** Seek to the offset in id->offset then read cnt bytes into pBuf.\n** Return the number of bytes actually read.  Update the offset.\n**\n** To avoid stomping the errno value on a failed write the lastErrno value\n** is set before returning.\n*/\nstatic int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){\n  int got;\n#if (!defined(USE_PREAD) && !defined(USE_PREAD64))\n  i64 newOffset;\n#endif\n  TIMER_START;\n#if defined(USE_PREAD)\n  do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );\n#elif defined(USE_PREAD64)\n  do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);\n#else\n  do{\n    newOffset = lseek(id->h, offset, SEEK_SET);\n    SimulateIOError( newOffset-- );\n    if( newOffset!=offset ){\n      if( newOffset == -1 ){\n        ((unixFile*)id)->lastErrno = errno;\n      }else{\n        ((unixFile*)id)->lastErrno = 0;\n      }\n      return -1;\n    }\n    got = osWrite(id->h, pBuf, cnt);\n  }while( got<0 && errno==EINTR );\n#endif\n  TIMER_END;\n  if( got<0 ){\n    ((unixFile*)id)->lastErrno = errno;\n  }\n\n  OSTRACE((\"WRITE   %-3d %5d %7lld %llu\\n\", id->h, got, offset, TIMER_ELAPSED));\n  return got;\n}\n\n\n/*\n** Write data from a buffer into a file.  Return SQLITE_OK on success\n** or some other error code on failure.\n*/\nstatic int unixWrite(\n  sqlite3_file *id, \n  const void *pBuf, \n  int amt,\n  sqlite3_int64 offset \n){\n  unixFile *pFile = (unixFile*)id;\n  int wrote = 0;\n  assert( id );\n  assert( amt>0 );\n\n  /* If this is a database file (not a journal, master-journal or temp\n  ** file), the bytes in the locking range should never be read or written. */\n#if 0\n  assert( pFile->pUnused==0\n       || offset>=PENDING_BYTE+512\n       || offset+amt<=PENDING_BYTE \n  );\n#endif\n\n#ifdef SQLITE_DEBUG\n  /* If we are doing a normal write to a database file (as opposed to\n  ** doing a hot-journal rollback or a write to some file other than a\n  ** normal database file) then record the fact that the database\n  ** has changed.  If the transaction counter is modified, record that\n  ** fact too.\n  */\n  if( pFile->inNormalWrite ){\n    pFile->dbUpdate = 1;  /* The database has been modified */\n    if( offset<=24 && offset+amt>=27 ){\n      int rc;\n      char oldCntr[4];\n      SimulateIOErrorBenign(1);\n      rc = seekAndRead(pFile, 24, oldCntr, 4);\n      SimulateIOErrorBenign(0);\n      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){\n        pFile->transCntrChng = 1;  /* The transaction counter has changed */\n      }\n    }\n  }\n#endif\n\n  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){\n    amt -= wrote;\n    offset += wrote;\n    pBuf = &((char*)pBuf)[wrote];\n  }\n  SimulateIOError(( wrote=(-1), amt=1 ));\n  SimulateDiskfullError(( wrote=0, amt=1 ));\n\n  if( amt>0 ){\n    if( wrote<0 && pFile->lastErrno!=ENOSPC ){\n      /* lastErrno set by seekAndWrite */\n      return SQLITE_IOERR_WRITE;\n    }else{\n      pFile->lastErrno = 0; /* not a system error */\n      return SQLITE_FULL;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Count the number of fullsyncs and normal syncs.  This is used to test\n** that syncs and fullsyncs are occurring at the right times.\n*/\nSQLITE_API int sqlite3_sync_count = 0;\nSQLITE_API int sqlite3_fullsync_count = 0;\n#endif\n\n/*\n** We do not trust systems to provide a working fdatasync().  Some do.\n** Others do no.  To be safe, we will stick with the (slightly slower)\n** fsync(). If you know that your system does support fdatasync() correctly,\n** then simply compile with -Dfdatasync=fdatasync\n*/\n#if !defined(fdatasync)\n# define fdatasync fsync\n#endif\n\n/*\n** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not\n** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently\n** only available on Mac OS X.  But that could change.\n*/\n#ifdef F_FULLFSYNC\n# define HAVE_FULLFSYNC 1\n#else\n# define HAVE_FULLFSYNC 0\n#endif\n\n\n/*\n** The fsync() system call does not work as advertised on many\n** unix systems.  The following procedure is an attempt to make\n** it work better.\n**\n** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful\n** for testing when we want to run through the test suite quickly.\n** You are strongly advised *not* to deploy with SQLITE_NO_SYNC\n** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash\n** or power failure will likely corrupt the database file.\n**\n** SQLite sets the dataOnly flag if the size of the file is unchanged.\n** The idea behind dataOnly is that it should only write the file content\n** to disk, not the inode.  We only set dataOnly if the file size is \n** unchanged since the file size is part of the inode.  However, \n** Ted Ts'o tells us that fdatasync() will also write the inode if the\n** file size has changed.  The only real difference between fdatasync()\n** and fsync(), Ted tells us, is that fdatasync() will not flush the\n** inode if the mtime or owner or other inode attributes have changed.\n** We only care about the file size, not the other file attributes, so\n** as far as SQLite is concerned, an fdatasync() is always adequate.\n** So, we always use fdatasync() if it is available, regardless of\n** the value of the dataOnly flag.\n*/\nstatic int full_fsync(int fd, int fullSync, int dataOnly){\n  int rc;\n\n  /* The following \"ifdef/elif/else/\" block has the same structure as\n  ** the one below. It is replicated here solely to avoid cluttering \n  ** up the real code with the UNUSED_PARAMETER() macros.\n  */\n#ifdef SQLITE_NO_SYNC\n  UNUSED_PARAMETER(fd);\n  UNUSED_PARAMETER(fullSync);\n  UNUSED_PARAMETER(dataOnly);\n#elif HAVE_FULLFSYNC\n  UNUSED_PARAMETER(dataOnly);\n#else\n  UNUSED_PARAMETER(fullSync);\n  UNUSED_PARAMETER(dataOnly);\n#endif\n\n  /* Record the number of times that we do a normal fsync() and \n  ** FULLSYNC.  This is used during testing to verify that this procedure\n  ** gets called with the correct arguments.\n  */\n#ifdef SQLITE_TEST\n  if( fullSync ) sqlite3_fullsync_count++;\n  sqlite3_sync_count++;\n#endif\n\n  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a\n  ** no-op\n  */\n#ifdef SQLITE_NO_SYNC\n  rc = SQLITE_OK;\n#elif HAVE_FULLFSYNC\n  if( fullSync ){\n    rc = osFcntl(fd, F_FULLFSYNC, 0);\n  }else{\n    rc = 1;\n  }\n  /* If the FULLFSYNC failed, fall back to attempting an fsync().\n  ** It shouldn't be possible for fullfsync to fail on the local \n  ** file system (on OSX), so failure indicates that FULLFSYNC\n  ** isn't supported for this file system. So, attempt an fsync \n  ** and (for now) ignore the overhead of a superfluous fcntl call.  \n  ** It'd be better to detect fullfsync support once and avoid \n  ** the fcntl call every time sync is called.\n  */\n  if( rc ) rc = fsync(fd);\n\n#elif defined(__APPLE__)\n  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly\n  ** so currently we default to the macro that redefines fdatasync to fsync\n  */\n  rc = fsync(fd);\n#else \n  rc = fdatasync(fd);\n#if OS_VXWORKS\n  if( rc==-1 && errno==ENOTSUP ){\n    rc = fsync(fd);\n  }\n#endif /* OS_VXWORKS */\n#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */\n\n  if( OS_VXWORKS && rc!= -1 ){\n    rc = 0;\n  }\n  return rc;\n}\n\n/*\n** Open a file descriptor to the directory containing file zFilename.\n** If successful, *pFd is set to the opened file descriptor and\n** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM\n** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined\n** value.\n**\n** The directory file descriptor is used for only one thing - to\n** fsync() a directory to make sure file creation and deletion events\n** are flushed to disk.  Such fsyncs are not needed on newer\n** journaling filesystems, but are required on older filesystems.\n**\n** This routine can be overridden using the xSetSysCall interface.\n** The ability to override this routine was added in support of the\n** chromium sandbox.  Opening a directory is a security risk (we are\n** told) so making it overrideable allows the chromium sandbox to\n** replace this routine with a harmless no-op.  To make this routine\n** a no-op, replace it with a stub that returns SQLITE_OK but leaves\n** *pFd set to a negative number.\n**\n** If SQLITE_OK is returned, the caller is responsible for closing\n** the file descriptor *pFd using close().\n*/\nstatic int openDirectory(const char *zFilename, int *pFd){\n  int ii;\n  int fd = -1;\n  char zDirname[MAX_PATHNAME+1];\n\n  sqlite3_snprintf(MAX_PATHNAME, zDirname, \"%s\", zFilename);\n  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);\n  if( ii>0 ){\n    zDirname[ii] = '\\0';\n    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);\n    if( fd>=0 ){\n      OSTRACE((\"OPENDIR %-3d %s\\n\", fd, zDirname));\n    }\n  }\n  *pFd = fd;\n  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, \"open\", zDirname));\n}\n\n/*\n** Make sure all writes to a particular file are committed to disk.\n**\n** If dataOnly==0 then both the file itself and its metadata (file\n** size, access time, etc) are synced.  If dataOnly!=0 then only the\n** file data is synced.\n**\n** Under Unix, also make sure that the directory entry for the file\n** has been created by fsync-ing the directory that contains the file.\n** If we do not do this and we encounter a power failure, the directory\n** entry for the journal might not exist after we reboot.  The next\n** SQLite to access the file will not know that the journal exists (because\n** the directory entry for the journal was never created) and the transaction\n** will not roll back - possibly leading to database corruption.\n*/\nstatic int unixSync(sqlite3_file *id, int flags){\n  int rc;\n  unixFile *pFile = (unixFile*)id;\n\n  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);\n  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;\n\n  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */\n  assert((flags&0x0F)==SQLITE_SYNC_NORMAL\n      || (flags&0x0F)==SQLITE_SYNC_FULL\n  );\n\n  /* Unix cannot, but some systems may return SQLITE_FULL from here. This\n  ** line is to test that doing so does not cause any problems.\n  */\n  SimulateDiskfullError( return SQLITE_FULL );\n\n  assert( pFile );\n  OSTRACE((\"SYNC    %-3d\\n\", pFile->h));\n  rc = full_fsync(pFile->h, isFullsync, isDataOnly);\n  SimulateIOError( rc=1 );\n  if( rc ){\n    pFile->lastErrno = errno;\n    return unixLogError(SQLITE_IOERR_FSYNC, \"full_fsync\", pFile->zPath);\n  }\n\n  /* Also fsync the directory containing the file if the DIRSYNC flag\n  ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)\n  ** are unable to fsync a directory, so ignore errors on the fsync.\n  */\n  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){\n    int dirfd;\n    OSTRACE((\"DIRSYNC %s (have_fullfsync=%d fullsync=%d)\\n\", pFile->zPath,\n            HAVE_FULLFSYNC, isFullsync));\n    rc = osOpenDirectory(pFile->zPath, &dirfd);\n    if( rc==SQLITE_OK && dirfd>=0 ){\n      full_fsync(dirfd, 0, 0);\n      robust_close(pFile, dirfd, __LINE__);\n    }else if( rc==SQLITE_CANTOPEN ){\n      rc = SQLITE_OK;\n    }\n    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;\n  }\n  return rc;\n}\n\n/*\n** Truncate an open file to a specified size\n*/\nstatic int unixTruncate(sqlite3_file *id, i64 nByte){\n  unixFile *pFile = (unixFile *)id;\n  int rc;\n  assert( pFile );\n  SimulateIOError( return SQLITE_IOERR_TRUNCATE );\n\n  /* If the user has configured a chunk-size for this file, truncate the\n  ** file so that it consists of an integer number of chunks (i.e. the\n  ** actual file size after the operation may be larger than the requested\n  ** size).\n  */\n  if( pFile->szChunk>0 ){\n    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;\n  }\n\n  rc = robust_ftruncate(pFile->h, (off_t)nByte);\n  if( rc ){\n    pFile->lastErrno = errno;\n    return unixLogError(SQLITE_IOERR_TRUNCATE, \"ftruncate\", pFile->zPath);\n  }else{\n#ifdef SQLITE_DEBUG\n    /* If we are doing a normal write to a database file (as opposed to\n    ** doing a hot-journal rollback or a write to some file other than a\n    ** normal database file) and we truncate the file to zero length,\n    ** that effectively updates the change counter.  This might happen\n    ** when restoring a database using the backup API from a zero-length\n    ** source.\n    */\n    if( pFile->inNormalWrite && nByte==0 ){\n      pFile->transCntrChng = 1;\n    }\n#endif\n\n    return SQLITE_OK;\n  }\n}\n\n/*\n** Determine the current size of a file in bytes\n*/\nstatic int unixFileSize(sqlite3_file *id, i64 *pSize){\n  int rc;\n  struct stat buf;\n  assert( id );\n  rc = osFstat(((unixFile*)id)->h, &buf);\n  SimulateIOError( rc=1 );\n  if( rc!=0 ){\n    ((unixFile*)id)->lastErrno = errno;\n    return SQLITE_IOERR_FSTAT;\n  }\n  *pSize = buf.st_size;\n\n  /* When opening a zero-size database, the findInodeInfo() procedure\n  ** writes a single byte into that file in order to work around a bug\n  ** in the OS-X msdos filesystem.  In order to avoid problems with upper\n  ** layers, we need to report this file size as zero even though it is\n  ** really 1.   Ticket #3260.\n  */\n  if( *pSize==1 ) *pSize = 0;\n\n\n  return SQLITE_OK;\n}\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n/*\n** Handler for proxy-locking file-control verbs.  Defined below in the\n** proxying locking division.\n*/\nstatic int proxyFileControl(sqlite3_file*,int,void*);\n#endif\n\n/* \n** This function is called to handle the SQLITE_FCNTL_SIZE_HINT \n** file-control operation.  Enlarge the database to nBytes in size\n** (rounded up to the next chunk-size).  If the database is already\n** nBytes or larger, this routine is a no-op.\n*/\nstatic int fcntlSizeHint(unixFile *pFile, i64 nByte){\n  if( pFile->szChunk>0 ){\n    i64 nSize;                    /* Required file size */\n    struct stat buf;              /* Used to hold return values of fstat() */\n   \n    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;\n\n    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;\n    if( nSize>(i64)buf.st_size ){\n\n#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE\n      /* The code below is handling the return value of osFallocate() \n      ** correctly. posix_fallocate() is defined to \"returns zero on success, \n      ** or an error number on  failure\". See the manpage for details. */\n      int err;\n      do{\n        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);\n      }while( err==EINTR );\n      if( err ) return SQLITE_IOERR_WRITE;\n#else\n      /* If the OS does not have posix_fallocate(), fake it. First use\n      ** ftruncate() to set the file size, then write a single byte to\n      ** the last byte in each block within the extended region. This\n      ** is the same technique used by glibc to implement posix_fallocate()\n      ** on systems that do not have a real fallocate() system call.\n      */\n      int nBlk = buf.st_blksize;  /* File-system block size */\n      i64 iWrite;                 /* Next offset to write to */\n\n      if( robust_ftruncate(pFile->h, nSize) ){\n        pFile->lastErrno = errno;\n        return unixLogError(SQLITE_IOERR_TRUNCATE, \"ftruncate\", pFile->zPath);\n      }\n      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;\n      while( iWrite<nSize ){\n        int nWrite = seekAndWrite(pFile, iWrite, \"\", 1);\n        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;\n        iWrite += nBlk;\n      }\n#endif\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** If *pArg is inititially negative then this is a query.  Set *pArg to\n** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.\n**\n** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.\n*/\nstatic void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){\n  if( *pArg<0 ){\n    *pArg = (pFile->ctrlFlags & mask)!=0;\n  }else if( (*pArg)==0 ){\n    pFile->ctrlFlags &= ~mask;\n  }else{\n    pFile->ctrlFlags |= mask;\n  }\n}\n\n/*\n** Information and control of an open file handle.\n*/\nstatic int unixFileControl(sqlite3_file *id, int op, void *pArg){\n  unixFile *pFile = (unixFile*)id;\n  switch( op ){\n    case SQLITE_FCNTL_LOCKSTATE: {\n      *(int*)pArg = pFile->eFileLock;\n      return SQLITE_OK;\n    }\n    case SQLITE_LAST_ERRNO: {\n      *(int*)pArg = pFile->lastErrno;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_CHUNK_SIZE: {\n      pFile->szChunk = *(int *)pArg;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_SIZE_HINT: {\n      int rc;\n      SimulateIOErrorBenign(1);\n      rc = fcntlSizeHint(pFile, *(i64 *)pArg);\n      SimulateIOErrorBenign(0);\n      return rc;\n    }\n    case SQLITE_FCNTL_PERSIST_WAL: {\n      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {\n      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_VFSNAME: {\n      *(char**)pArg = sqlite3_mprintf(\"%s\", pFile->pVfs->zName);\n      return SQLITE_OK;\n    }\n#ifdef SQLITE_DEBUG\n    /* The pager calls this method to signal that it has done\n    ** a rollback and that the database is therefore unchanged and\n    ** it hence it is OK for the transaction change counter to be\n    ** unchanged.\n    */\n    case SQLITE_FCNTL_DB_UNCHANGED: {\n      ((unixFile*)id)->dbUpdate = 0;\n      return SQLITE_OK;\n    }\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n    case SQLITE_SET_LOCKPROXYFILE:\n    case SQLITE_GET_LOCKPROXYFILE: {\n      return proxyFileControl(id,op,pArg);\n    }\n#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */\n  }\n  return SQLITE_NOTFOUND;\n}\n\n/*\n** Return the sector size in bytes of the underlying block device for\n** the specified file. This is almost always 512 bytes, but may be\n** larger for some devices.\n**\n** SQLite code assumes this function cannot fail. It also assumes that\n** if two files are created in the same file-system directory (i.e.\n** a database and its journal file) that the sector size will be the\n** same for both.\n*/\nstatic int unixSectorSize(sqlite3_file *pFile){\n  (void)pFile;\n  return SQLITE_DEFAULT_SECTOR_SIZE;\n}\n\n/*\n** Return the device characteristics for the file.\n**\n** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.\n** However, that choice is contraversial since technically the underlying\n** file system does not always provide powersafe overwrites.  (In other\n** words, after a power-loss event, parts of the file that were never\n** written might end up being altered.)  However, non-PSOW behavior is very,\n** very rare.  And asserting PSOW makes a large reduction in the amount\n** of required I/O for journaling, since a lot of padding is eliminated.\n**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control\n** available to turn it off and URI query parameter available to turn it off.\n*/\nstatic int unixDeviceCharacteristics(sqlite3_file *id){\n  unixFile *p = (unixFile*)id;\n  if( p->ctrlFlags & UNIXFILE_PSOW ){\n    return SQLITE_IOCAP_POWERSAFE_OVERWRITE;\n  }else{\n    return 0;\n  }\n}\n\n#ifndef SQLITE_OMIT_WAL\n\n\n/*\n** Object used to represent an shared memory buffer.  \n**\n** When multiple threads all reference the same wal-index, each thread\n** has its own unixShm object, but they all point to a single instance\n** of this unixShmNode object.  In other words, each wal-index is opened\n** only once per process.\n**\n** Each unixShmNode object is connected to a single unixInodeInfo object.\n** We could coalesce this object into unixInodeInfo, but that would mean\n** every open file that does not use shared memory (in other words, most\n** open files) would have to carry around this extra information.  So\n** the unixInodeInfo object contains a pointer to this unixShmNode object\n** and the unixShmNode object is created only when needed.\n**\n** unixMutexHeld() must be true when creating or destroying\n** this object or while reading or writing the following fields:\n**\n**      nRef\n**\n** The following fields are read-only after the object is created:\n** \n**      fid\n**      zFilename\n**\n** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and\n** unixMutexHeld() is true when reading or writing any other field\n** in this structure.\n*/\nstruct unixShmNode {\n  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */\n  sqlite3_mutex *mutex;      /* Mutex to access this object */\n  char *zFilename;           /* Name of the mmapped file */\n  int h;                     /* Open file descriptor */\n  int szRegion;              /* Size of shared-memory regions */\n  u16 nRegion;               /* Size of array apRegion */\n  u8 isReadonly;             /* True if read-only */\n  char **apRegion;           /* Array of mapped shared-memory regions */\n  int nRef;                  /* Number of unixShm objects pointing to this */\n  unixShm *pFirst;           /* All unixShm objects pointing to this */\n#ifdef SQLITE_DEBUG\n  u8 exclMask;               /* Mask of exclusive locks held */\n  u8 sharedMask;             /* Mask of shared locks held */\n  u8 nextShmId;              /* Next available unixShm.id value */\n#endif\n};\n\n/*\n** Structure used internally by this VFS to record the state of an\n** open shared memory connection.\n**\n** The following fields are initialized when this object is created and\n** are read-only thereafter:\n**\n**    unixShm.pFile\n**    unixShm.id\n**\n** All other fields are read/write.  The unixShm.pFile->mutex must be held\n** while accessing any read/write fields.\n*/\nstruct unixShm {\n  unixShmNode *pShmNode;     /* The underlying unixShmNode object */\n  unixShm *pNext;            /* Next unixShm with the same unixShmNode */\n  u8 hasMutex;               /* True if holding the unixShmNode mutex */\n  u8 id;                     /* Id of this connection within its unixShmNode */\n  u16 sharedMask;            /* Mask of shared locks held */\n  u16 exclMask;              /* Mask of exclusive locks held */\n};\n\n/*\n** Constants used for locking\n*/\n#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */\n#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */\n\n/*\n** Apply posix advisory locks for all bytes from ofst through ofst+n-1.\n**\n** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking\n** otherwise.\n*/\nstatic int unixShmSystemLock(\n  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */\n  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */\n  int ofst,              /* First byte of the locking range */\n  int n                  /* Number of bytes to lock */\n){\n  struct flock f;       /* The posix advisory locking structure */\n  int rc = SQLITE_OK;   /* Result code form fcntl() */\n\n  /* Access to the unixShmNode object is serialized by the caller */\n  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );\n\n  /* Shared locks never span more than one byte */\n  assert( n==1 || lockType!=F_RDLCK );\n\n  /* Locks are within range */\n  assert( n>=1 && n<SQLITE_SHM_NLOCK );\n\n  if( pShmNode->h>=0 ){\n    /* Initialize the locking parameters */\n    memset(&f, 0, sizeof(f));\n    f.l_type = lockType;\n    f.l_whence = SEEK_SET;\n    f.l_start = ofst;\n    f.l_len = n;\n\n    rc = osFcntl(pShmNode->h, F_SETLK, &f);\n    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;\n  }\n\n  /* Update the global lock state and do debug tracing */\n#ifdef SQLITE_DEBUG\n  { u16 mask;\n  OSTRACE((\"SHM-LOCK \"));\n  mask = (1<<(ofst+n)) - (1<<ofst);\n  if( rc==SQLITE_OK ){\n    if( lockType==F_UNLCK ){\n      OSTRACE((\"unlock %d ok\", ofst));\n      pShmNode->exclMask &= ~mask;\n      pShmNode->sharedMask &= ~mask;\n    }else if( lockType==F_RDLCK ){\n      OSTRACE((\"read-lock %d ok\", ofst));\n      pShmNode->exclMask &= ~mask;\n      pShmNode->sharedMask |= mask;\n    }else{\n      assert( lockType==F_WRLCK );\n      OSTRACE((\"write-lock %d ok\", ofst));\n      pShmNode->exclMask |= mask;\n      pShmNode->sharedMask &= ~mask;\n    }\n  }else{\n    if( lockType==F_UNLCK ){\n      OSTRACE((\"unlock %d failed\", ofst));\n    }else if( lockType==F_RDLCK ){\n      OSTRACE((\"read-lock failed\"));\n    }else{\n      assert( lockType==F_WRLCK );\n      OSTRACE((\"write-lock %d failed\", ofst));\n    }\n  }\n  OSTRACE((\" - afterwards %03x,%03x\\n\",\n           pShmNode->sharedMask, pShmNode->exclMask));\n  }\n#endif\n\n  return rc;        \n}\n\n\n/*\n** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.\n**\n** This is not a VFS shared-memory method; it is a utility function called\n** by VFS shared-memory methods.\n*/\nstatic void unixShmPurge(unixFile *pFd){\n  unixShmNode *p = pFd->pInode->pShmNode;\n  assert( unixMutexHeld() );\n  if( p && p->nRef==0 ){\n    int i;\n    assert( p->pInode==pFd->pInode );\n    sqlite3_mutex_free(p->mutex);\n    for(i=0; i<p->nRegion; i++){\n      if( p->h>=0 ){\n        munmap(p->apRegion[i], p->szRegion);\n      }else{\n        sqlite3_free(p->apRegion[i]);\n      }\n    }\n    sqlite3_free(p->apRegion);\n    if( p->h>=0 ){\n      robust_close(pFd, p->h, __LINE__);\n      p->h = -1;\n    }\n    p->pInode->pShmNode = 0;\n    sqlite3_free(p);\n  }\n}\n\n/*\n** Open a shared-memory area associated with open database file pDbFd.  \n** This particular implementation uses mmapped files.\n**\n** The file used to implement shared-memory is in the same directory\n** as the open database file and has the same name as the open database\n** file with the \"-shm\" suffix added.  For example, if the database file\n** is \"/home/user1/config.db\" then the file that is created and mmapped\n** for shared memory will be called \"/home/user1/config.db-shm\".  \n**\n** Another approach to is to use files in /dev/shm or /dev/tmp or an\n** some other tmpfs mount. But if a file in a different directory\n** from the database file is used, then differing access permissions\n** or a chroot() might cause two different processes on the same\n** database to end up using different files for shared memory - \n** meaning that their memory would not really be shared - resulting\n** in database corruption.  Nevertheless, this tmpfs file usage\n** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY=\"/dev/shm\"\n** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time\n** option results in an incompatible build of SQLite;  builds of SQLite\n** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the\n** same database file at the same time, database corruption will likely\n** result. The SQLITE_SHM_DIRECTORY compile-time option is considered\n** \"unsupported\" and may go away in a future SQLite release.\n**\n** When opening a new shared-memory file, if no other instances of that\n** file are currently open, in this process or in other processes, then\n** the file must be truncated to zero length or have its header cleared.\n**\n** If the original database file (pDbFd) is using the \"unix-excl\" VFS\n** that means that an exclusive lock is held on the database file and\n** that no other processes are able to read or write the database.  In\n** that case, we do not really need shared memory.  No shared memory\n** file is created.  The shared memory will be simulated with heap memory.\n*/\nstatic int unixOpenSharedMemory(unixFile *pDbFd){\n  struct unixShm *p = 0;          /* The connection to be opened */\n  struct unixShmNode *pShmNode;   /* The underlying mmapped file */\n  int rc;                         /* Result code */\n  unixInodeInfo *pInode;          /* The inode of fd */\n  char *zShmFilename;             /* Name of the file used for SHM */\n  int nShmFilename;               /* Size of the SHM filename in bytes */\n\n  /* Allocate space for the new unixShm object. */\n  p = sqlite3_malloc( sizeof(*p) );\n  if( p==0 ) return SQLITE_NOMEM;\n  memset(p, 0, sizeof(*p));\n  assert( pDbFd->pShm==0 );\n\n  /* Check to see if a unixShmNode object already exists. Reuse an existing\n  ** one if present. Create a new one if necessary.\n  */\n  unixEnterMutex();\n  pInode = pDbFd->pInode;\n  pShmNode = pInode->pShmNode;\n  if( pShmNode==0 ){\n    struct stat sStat;                 /* fstat() info for database file */\n\n    /* Call fstat() to figure out the permissions on the database file. If\n    ** a new *-shm file is created, an attempt will be made to create it\n    ** with the same permissions.\n    */\n    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){\n      rc = SQLITE_IOERR_FSTAT;\n      goto shm_open_err;\n    }\n\n#ifdef SQLITE_SHM_DIRECTORY\n    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;\n#else\n    nShmFilename = 6 + (int)strlen(pDbFd->zPath);\n#endif\n    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );\n    if( pShmNode==0 ){\n      rc = SQLITE_NOMEM;\n      goto shm_open_err;\n    }\n    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);\n    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];\n#ifdef SQLITE_SHM_DIRECTORY\n    sqlite3_snprintf(nShmFilename, zShmFilename, \n                     SQLITE_SHM_DIRECTORY \"/sqlite-shm-%x-%x\",\n                     (u32)sStat.st_ino, (u32)sStat.st_dev);\n#else\n    sqlite3_snprintf(nShmFilename, zShmFilename, \"%s-shm\", pDbFd->zPath);\n    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);\n#endif\n    pShmNode->h = -1;\n    pDbFd->pInode->pShmNode = pShmNode;\n    pShmNode->pInode = pDbFd->pInode;\n    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);\n    if( pShmNode->mutex==0 ){\n      rc = SQLITE_NOMEM;\n      goto shm_open_err;\n    }\n\n    if( pInode->bProcessLock==0 ){\n      int openFlags = O_RDWR | O_CREAT;\n      if( sqlite3_uri_boolean(pDbFd->zPath, \"readonly_shm\", 0) ){\n        openFlags = O_RDONLY;\n        pShmNode->isReadonly = 1;\n      }\n      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));\n      if( pShmNode->h<0 ){\n        rc = unixLogError(SQLITE_CANTOPEN_BKPT, \"open\", zShmFilename);\n        goto shm_open_err;\n      }\n\n      /* If this process is running as root, make sure that the SHM file\n      ** is owned by the same user that owns the original database.  Otherwise,\n      ** the original owner will not be able to connect.\n      */\n      osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);\n  \n      /* Check to see if another process is holding the dead-man switch.\n      ** If not, truncate the file to zero length. \n      */\n      rc = SQLITE_OK;\n      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){\n        if( robust_ftruncate(pShmNode->h, 0) ){\n          rc = unixLogError(SQLITE_IOERR_SHMOPEN, \"ftruncate\", zShmFilename);\n        }\n      }\n      if( rc==SQLITE_OK ){\n        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);\n      }\n      if( rc ) goto shm_open_err;\n    }\n  }\n\n  /* Make the new connection a child of the unixShmNode */\n  p->pShmNode = pShmNode;\n#ifdef SQLITE_DEBUG\n  p->id = pShmNode->nextShmId++;\n#endif\n  pShmNode->nRef++;\n  pDbFd->pShm = p;\n  unixLeaveMutex();\n\n  /* The reference count on pShmNode has already been incremented under\n  ** the cover of the unixEnterMutex() mutex and the pointer from the\n  ** new (struct unixShm) object to the pShmNode has been set. All that is\n  ** left to do is to link the new object into the linked list starting\n  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex \n  ** mutex.\n  */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  p->pNext = pShmNode->pFirst;\n  pShmNode->pFirst = p;\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return SQLITE_OK;\n\n  /* Jump here on any error */\nshm_open_err:\n  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */\n  sqlite3_free(p);\n  unixLeaveMutex();\n  return rc;\n}\n\n/*\n** This function is called to obtain a pointer to region iRegion of the \n** shared-memory associated with the database file fd. Shared-memory regions \n** are numbered starting from zero. Each shared-memory region is szRegion \n** bytes in size.\n**\n** If an error occurs, an error code is returned and *pp is set to NULL.\n**\n** Otherwise, if the bExtend parameter is 0 and the requested shared-memory\n** region has not been allocated (by any client, including one running in a\n** separate process), then *pp is set to NULL and SQLITE_OK returned. If \n** bExtend is non-zero and the requested shared-memory region has not yet \n** been allocated, it is allocated by this function.\n**\n** If the shared-memory region has already been allocated or is allocated by\n** this call as described above, then it is mapped into this processes \n** address space (if it is not already), *pp is set to point to the mapped \n** memory and SQLITE_OK returned.\n*/\nstatic int unixShmMap(\n  sqlite3_file *fd,               /* Handle open on database file */\n  int iRegion,                    /* Region to retrieve */\n  int szRegion,                   /* Size of regions */\n  int bExtend,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Mapped memory */\n){\n  unixFile *pDbFd = (unixFile*)fd;\n  unixShm *p;\n  unixShmNode *pShmNode;\n  int rc = SQLITE_OK;\n\n  /* If the shared-memory file has not yet been opened, open it now. */\n  if( pDbFd->pShm==0 ){\n    rc = unixOpenSharedMemory(pDbFd);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  p = pDbFd->pShm;\n  pShmNode = p->pShmNode;\n  sqlite3_mutex_enter(pShmNode->mutex);\n  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );\n  assert( pShmNode->pInode==pDbFd->pInode );\n  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );\n  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );\n\n  if( pShmNode->nRegion<=iRegion ){\n    char **apNew;                      /* New apRegion[] array */\n    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */\n    struct stat sStat;                 /* Used by fstat() */\n\n    pShmNode->szRegion = szRegion;\n\n    if( pShmNode->h>=0 ){\n      /* The requested region is not mapped into this processes address space.\n      ** Check to see if it has been allocated (i.e. if the wal-index file is\n      ** large enough to contain the requested region).\n      */\n      if( osFstat(pShmNode->h, &sStat) ){\n        rc = SQLITE_IOERR_SHMSIZE;\n        goto shmpage_out;\n      }\n  \n      if( sStat.st_size<nByte ){\n        /* The requested memory region does not exist. If bExtend is set to\n        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.\n        **\n        ** Alternatively, if bExtend is true, use ftruncate() to allocate\n        ** the requested memory region.\n        */\n        if( !bExtend ) goto shmpage_out;\n        if( robust_ftruncate(pShmNode->h, nByte) ){\n          rc = unixLogError(SQLITE_IOERR_SHMSIZE, \"ftruncate\",\n                            pShmNode->zFilename);\n          goto shmpage_out;\n        }\n      }\n    }\n\n    /* Map the requested memory region into this processes address space. */\n    apNew = (char **)sqlite3_realloc(\n        pShmNode->apRegion, (iRegion+1)*sizeof(char *)\n    );\n    if( !apNew ){\n      rc = SQLITE_IOERR_NOMEM;\n      goto shmpage_out;\n    }\n    pShmNode->apRegion = apNew;\n    while(pShmNode->nRegion<=iRegion){\n      void *pMem;\n      if( pShmNode->h>=0 ){\n        pMem = mmap(0, szRegion,\n            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, \n            MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion\n        );\n        if( pMem==MAP_FAILED ){\n          rc = unixLogError(SQLITE_IOERR_SHMMAP, \"mmap\", pShmNode->zFilename);\n          goto shmpage_out;\n        }\n      }else{\n        pMem = sqlite3_malloc(szRegion);\n        if( pMem==0 ){\n          rc = SQLITE_NOMEM;\n          goto shmpage_out;\n        }\n        memset(pMem, 0, szRegion);\n      }\n      pShmNode->apRegion[pShmNode->nRegion] = pMem;\n      pShmNode->nRegion++;\n    }\n  }\n\nshmpage_out:\n  if( pShmNode->nRegion>iRegion ){\n    *pp = pShmNode->apRegion[iRegion];\n  }else{\n    *pp = 0;\n  }\n  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return rc;\n}\n\n/*\n** Change the lock state for a shared-memory segment.\n**\n** Note that the relationship between SHAREd and EXCLUSIVE locks is a little\n** different here than in posix.  In xShmLock(), one can go from unlocked\n** to shared and back or from unlocked to exclusive and back.  But one may\n** not go from shared to exclusive or from exclusive to shared.\n*/\nstatic int unixShmLock(\n  sqlite3_file *fd,          /* Database file holding the shared memory */\n  int ofst,                  /* First lock to acquire or release */\n  int n,                     /* Number of locks to acquire or release */\n  int flags                  /* What to do with the lock */\n){\n  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */\n  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */\n  unixShm *pX;                          /* For looping over all siblings */\n  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */\n  int rc = SQLITE_OK;                   /* Result code */\n  u16 mask;                             /* Mask of locks to take or release */\n\n  assert( pShmNode==pDbFd->pInode->pShmNode );\n  assert( pShmNode->pInode==pDbFd->pInode );\n  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );\n  assert( n>=1 );\n  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );\n  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );\n  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );\n  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );\n\n  mask = (1<<(ofst+n)) - (1<<ofst);\n  assert( n>1 || mask==(1<<ofst) );\n  sqlite3_mutex_enter(pShmNode->mutex);\n  if( flags & SQLITE_SHM_UNLOCK ){\n    u16 allMask = 0; /* Mask of locks held by siblings */\n\n    /* See if any siblings hold this same lock */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( pX==p ) continue;\n      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );\n      allMask |= pX->sharedMask;\n    }\n\n    /* Unlock the system-level locks */\n    if( (mask & allMask)==0 ){\n      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* Undo the local locks */\n    if( rc==SQLITE_OK ){\n      p->exclMask &= ~mask;\n      p->sharedMask &= ~mask;\n    } \n  }else if( flags & SQLITE_SHM_SHARED ){\n    u16 allShared = 0;  /* Union of locks held by connections other than \"p\" */\n\n    /* Find out which shared locks are already held by sibling connections.\n    ** If any sibling already holds an exclusive lock, go ahead and return\n    ** SQLITE_BUSY.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n      allShared |= pX->sharedMask;\n    }\n\n    /* Get shared locks at the system level, if necessary */\n    if( rc==SQLITE_OK ){\n      if( (allShared & mask)==0 ){\n        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);\n      }else{\n        rc = SQLITE_OK;\n      }\n    }\n\n    /* Get the local shared locks */\n    if( rc==SQLITE_OK ){\n      p->sharedMask |= mask;\n    }\n  }else{\n    /* Make sure no sibling connections hold locks that will block this\n    ** lock.  If any do, return SQLITE_BUSY right away.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n    }\n  \n    /* Get the exclusive locks at the system level.  Then if successful\n    ** also mark the local connection as being locked.\n    */\n    if( rc==SQLITE_OK ){\n      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);\n      if( rc==SQLITE_OK ){\n        assert( (p->sharedMask & mask)==0 );\n        p->exclMask |= mask;\n      }\n    }\n  }\n  sqlite3_mutex_leave(pShmNode->mutex);\n  OSTRACE((\"SHM-LOCK shmid-%d, pid-%d got %03x,%03x\\n\",\n           p->id, getpid(), p->sharedMask, p->exclMask));\n  return rc;\n}\n\n/*\n** Implement a memory barrier or memory fence on shared memory.  \n**\n** All loads and stores begun before the barrier must complete before\n** any load or store begun after the barrier.\n*/\nstatic void unixShmBarrier(\n  sqlite3_file *fd                /* Database file holding the shared memory */\n){\n  UNUSED_PARAMETER(fd);\n  unixEnterMutex();\n  unixLeaveMutex();\n}\n\n/*\n** Close a connection to shared-memory.  Delete the underlying \n** storage if deleteFlag is true.\n**\n** If there is no shared memory associated with the connection then this\n** routine is a harmless no-op.\n*/\nstatic int unixShmUnmap(\n  sqlite3_file *fd,               /* The underlying database file */\n  int deleteFlag                  /* Delete shared-memory if true */\n){\n  unixShm *p;                     /* The connection to be closed */\n  unixShmNode *pShmNode;          /* The underlying shared-memory file */\n  unixShm **pp;                   /* For looping over sibling connections */\n  unixFile *pDbFd;                /* The underlying database file */\n\n  pDbFd = (unixFile*)fd;\n  p = pDbFd->pShm;\n  if( p==0 ) return SQLITE_OK;\n  pShmNode = p->pShmNode;\n\n  assert( pShmNode==pDbFd->pInode->pShmNode );\n  assert( pShmNode->pInode==pDbFd->pInode );\n\n  /* Remove connection p from the set of connections associated\n  ** with pShmNode */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}\n  *pp = p->pNext;\n\n  /* Free the connection p */\n  sqlite3_free(p);\n  pDbFd->pShm = 0;\n  sqlite3_mutex_leave(pShmNode->mutex);\n\n  /* If pShmNode->nRef has reached 0, then close the underlying\n  ** shared-memory file, too */\n  unixEnterMutex();\n  assert( pShmNode->nRef>0 );\n  pShmNode->nRef--;\n  if( pShmNode->nRef==0 ){\n    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);\n    unixShmPurge(pDbFd);\n  }\n  unixLeaveMutex();\n\n  return SQLITE_OK;\n}\n\n\n#else\n# define unixShmMap     0\n# define unixShmLock    0\n# define unixShmBarrier 0\n# define unixShmUnmap   0\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n/*\n** Here ends the implementation of all sqlite3_file methods.\n**\n********************** End sqlite3_file Methods *******************************\n******************************************************************************/\n\n/*\n** This division contains definitions of sqlite3_io_methods objects that\n** implement various file locking strategies.  It also contains definitions\n** of \"finder\" functions.  A finder-function is used to locate the appropriate\n** sqlite3_io_methods object for a particular database file.  The pAppData\n** field of the sqlite3_vfs VFS objects are initialized to be pointers to\n** the correct finder-function for that VFS.\n**\n** Most finder functions return a pointer to a fixed sqlite3_io_methods\n** object.  The only interesting finder-function is autolockIoFinder, which\n** looks at the filesystem type and tries to guess the best locking\n** strategy from that.\n**\n** For finder-funtion F, two objects are created:\n**\n**    (1) The real finder-function named \"FImpt()\".\n**\n**    (2) A constant pointer to this function named just \"F\".\n**\n**\n** A pointer to the F pointer is used as the pAppData value for VFS\n** objects.  We have to do this instead of letting pAppData point\n** directly at the finder-function since C90 rules prevent a void*\n** from be cast into a function pointer.\n**\n**\n** Each instance of this macro generates two objects:\n**\n**   *  A constant sqlite3_io_methods object call METHOD that has locking\n**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.\n**\n**   *  An I/O method finder function called FINDER that returns a pointer\n**      to the METHOD object in the previous bullet.\n*/\n#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \\\nstatic const sqlite3_io_methods METHOD = {                                   \\\n   VERSION,                    /* iVersion */                                \\\n   CLOSE,                      /* xClose */                                  \\\n   unixRead,                   /* xRead */                                   \\\n   unixWrite,                  /* xWrite */                                  \\\n   unixTruncate,               /* xTruncate */                               \\\n   unixSync,                   /* xSync */                                   \\\n   unixFileSize,               /* xFileSize */                               \\\n   LOCK,                       /* xLock */                                   \\\n   UNLOCK,                     /* xUnlock */                                 \\\n   CKLOCK,                     /* xCheckReservedLock */                      \\\n   unixFileControl,            /* xFileControl */                            \\\n   unixSectorSize,             /* xSectorSize */                             \\\n   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \\\n   unixShmMap,                 /* xShmMap */                                 \\\n   unixShmLock,                /* xShmLock */                                \\\n   unixShmBarrier,             /* xShmBarrier */                             \\\n   unixShmUnmap                /* xShmUnmap */                               \\\n};                                                                           \\\nstatic const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \\\n  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \\\n  return &METHOD;                                                            \\\n}                                                                            \\\nstatic const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \\\n    = FINDER##Impl;\n\n/*\n** Here are all of the sqlite3_io_methods objects for each of the\n** locking strategies.  Functions that return pointers to these methods\n** are also created.\n*/\nIOMETHODS(\n  posixIoFinder,            /* Finder function name */\n  posixIoMethods,           /* sqlite3_io_methods object name */\n  2,                        /* shared memory is enabled */\n  unixClose,                /* xClose method */\n  unixLock,                 /* xLock method */\n  unixUnlock,               /* xUnlock method */\n  unixCheckReservedLock     /* xCheckReservedLock method */\n)\nIOMETHODS(\n  nolockIoFinder,           /* Finder function name */\n  nolockIoMethods,          /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  nolockClose,              /* xClose method */\n  nolockLock,               /* xLock method */\n  nolockUnlock,             /* xUnlock method */\n  nolockCheckReservedLock   /* xCheckReservedLock method */\n)\nIOMETHODS(\n  dotlockIoFinder,          /* Finder function name */\n  dotlockIoMethods,         /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  dotlockClose,             /* xClose method */\n  dotlockLock,              /* xLock method */\n  dotlockUnlock,            /* xUnlock method */\n  dotlockCheckReservedLock  /* xCheckReservedLock method */\n)\n\n#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS\nIOMETHODS(\n  flockIoFinder,            /* Finder function name */\n  flockIoMethods,           /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  flockClose,               /* xClose method */\n  flockLock,                /* xLock method */\n  flockUnlock,              /* xUnlock method */\n  flockCheckReservedLock    /* xCheckReservedLock method */\n)\n#endif\n\n#if OS_VXWORKS\nIOMETHODS(\n  semIoFinder,              /* Finder function name */\n  semIoMethods,             /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  semClose,                 /* xClose method */\n  semLock,                  /* xLock method */\n  semUnlock,                /* xUnlock method */\n  semCheckReservedLock      /* xCheckReservedLock method */\n)\n#endif\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nIOMETHODS(\n  afpIoFinder,              /* Finder function name */\n  afpIoMethods,             /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  afpClose,                 /* xClose method */\n  afpLock,                  /* xLock method */\n  afpUnlock,                /* xUnlock method */\n  afpCheckReservedLock      /* xCheckReservedLock method */\n)\n#endif\n\n/*\n** The proxy locking method is a \"super-method\" in the sense that it\n** opens secondary file descriptors for the conch and lock files and\n** it uses proxy, dot-file, AFP, and flock() locking methods on those\n** secondary files.  For this reason, the division that implements\n** proxy locking is located much further down in the file.  But we need\n** to go ahead and define the sqlite3_io_methods and finder function\n** for proxy locking here.  So we forward declare the I/O methods.\n*/\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nstatic int proxyClose(sqlite3_file*);\nstatic int proxyLock(sqlite3_file*, int);\nstatic int proxyUnlock(sqlite3_file*, int);\nstatic int proxyCheckReservedLock(sqlite3_file*, int*);\nIOMETHODS(\n  proxyIoFinder,            /* Finder function name */\n  proxyIoMethods,           /* sqlite3_io_methods object name */\n  1,                        /* shared memory is disabled */\n  proxyClose,               /* xClose method */\n  proxyLock,                /* xLock method */\n  proxyUnlock,              /* xUnlock method */\n  proxyCheckReservedLock    /* xCheckReservedLock method */\n)\n#endif\n\n/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\nIOMETHODS(\n  nfsIoFinder,               /* Finder function name */\n  nfsIoMethods,              /* sqlite3_io_methods object name */\n  1,                         /* shared memory is disabled */\n  unixClose,                 /* xClose method */\n  unixLock,                  /* xLock method */\n  nfsUnlock,                 /* xUnlock method */\n  unixCheckReservedLock      /* xCheckReservedLock method */\n)\n#endif\n\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n/* \n** This \"finder\" function attempts to determine the best locking strategy \n** for the database file \"filePath\".  It then returns the sqlite3_io_methods\n** object that implements that strategy.\n**\n** This is for MacOSX only.\n*/\nstatic const sqlite3_io_methods *autolockIoFinderImpl(\n  const char *filePath,    /* name of the database file */\n  unixFile *pNew           /* open file object for the database file */\n){\n  static const struct Mapping {\n    const char *zFilesystem;              /* Filesystem type name */\n    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */\n  } aMap[] = {\n    { \"hfs\",    &posixIoMethods },\n    { \"ufs\",    &posixIoMethods },\n    { \"afpfs\",  &afpIoMethods },\n    { \"smbfs\",  &afpIoMethods },\n    { \"webdav\", &nolockIoMethods },\n    { 0, 0 }\n  };\n  int i;\n  struct statfs fsInfo;\n  struct flock lockInfo;\n\n  if( !filePath ){\n    /* If filePath==NULL that means we are dealing with a transient file\n    ** that does not need to be locked. */\n    return &nolockIoMethods;\n  }\n  if( statfs(filePath, &fsInfo) != -1 ){\n    if( fsInfo.f_flags & MNT_RDONLY ){\n      return &nolockIoMethods;\n    }\n    for(i=0; aMap[i].zFilesystem; i++){\n      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){\n        return aMap[i].pMethods;\n      }\n    }\n  }\n\n  /* Default case. Handles, amongst others, \"nfs\".\n  ** Test byte-range lock using fcntl(). If the call succeeds, \n  ** assume that the file-system supports POSIX style locks. \n  */\n  lockInfo.l_len = 1;\n  lockInfo.l_start = 0;\n  lockInfo.l_whence = SEEK_SET;\n  lockInfo.l_type = F_RDLCK;\n  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {\n    if( strcmp(fsInfo.f_fstypename, \"nfs\")==0 ){\n      return &nfsIoMethods;\n    } else {\n      return &posixIoMethods;\n    }\n  }else{\n    return &dotlockIoMethods;\n  }\n}\nstatic const sqlite3_io_methods \n  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n\n#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE\n/* \n** This \"finder\" function attempts to determine the best locking strategy \n** for the database file \"filePath\".  It then returns the sqlite3_io_methods\n** object that implements that strategy.\n**\n** This is for VXWorks only.\n*/\nstatic const sqlite3_io_methods *autolockIoFinderImpl(\n  const char *filePath,    /* name of the database file */\n  unixFile *pNew           /* the open file object */\n){\n  struct flock lockInfo;\n\n  if( !filePath ){\n    /* If filePath==NULL that means we are dealing with a transient file\n    ** that does not need to be locked. */\n    return &nolockIoMethods;\n  }\n\n  /* Test if fcntl() is supported and use POSIX style locks.\n  ** Otherwise fall back to the named semaphore method.\n  */\n  lockInfo.l_len = 1;\n  lockInfo.l_start = 0;\n  lockInfo.l_whence = SEEK_SET;\n  lockInfo.l_type = F_RDLCK;\n  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {\n    return &posixIoMethods;\n  }else{\n    return &semIoMethods;\n  }\n}\nstatic const sqlite3_io_methods \n  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;\n\n#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */\n\n/*\n** An abstract type for a pointer to a IO method finder function:\n*/\ntypedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);\n\n\n/****************************************************************************\n**************************** sqlite3_vfs methods ****************************\n**\n** This division contains the implementation of methods on the\n** sqlite3_vfs object.\n*/\n\n/*\n** Initialize the contents of the unixFile structure pointed to by pId.\n*/\nstatic int fillInUnixFile(\n  sqlite3_vfs *pVfs,      /* Pointer to vfs object */\n  int h,                  /* Open file descriptor of file being opened */\n  sqlite3_file *pId,      /* Write to the unixFile structure here */\n  const char *zFilename,  /* Name of the file being opened */\n  int ctrlFlags           /* Zero or more UNIXFILE_* values */\n){\n  const sqlite3_io_methods *pLockingStyle;\n  unixFile *pNew = (unixFile *)pId;\n  int rc = SQLITE_OK;\n\n  assert( pNew->pInode==NULL );\n\n  /* Usually the path zFilename should not be a relative pathname. The\n  ** exception is when opening the proxy \"conch\" file in builds that\n  ** include the special Apple locking styles.\n  */\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n  assert( zFilename==0 || zFilename[0]=='/' \n    || pVfs->pAppData==(void*)&autolockIoFinder );\n#else\n  assert( zFilename==0 || zFilename[0]=='/' );\n#endif\n\n  /* No locking occurs in temporary files */\n  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );\n\n  OSTRACE((\"OPEN    %-3d %s\\n\", h, zFilename));\n  pNew->h = h;\n  pNew->pVfs = pVfs;\n  pNew->zPath = zFilename;\n  pNew->ctrlFlags = (u8)ctrlFlags;\n  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),\n                           \"psow\", SQLITE_POWERSAFE_OVERWRITE) ){\n    pNew->ctrlFlags |= UNIXFILE_PSOW;\n  }\n  if( memcmp(pVfs->zName,\"unix-excl\",10)==0 ){\n    pNew->ctrlFlags |= UNIXFILE_EXCL;\n  }\n\n#if OS_VXWORKS\n  pNew->pId = vxworksFindFileId(zFilename);\n  if( pNew->pId==0 ){\n    ctrlFlags |= UNIXFILE_NOLOCK;\n    rc = SQLITE_NOMEM;\n  }\n#endif\n\n  if( ctrlFlags & UNIXFILE_NOLOCK ){\n    pLockingStyle = &nolockIoMethods;\n  }else{\n    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);\n#if SQLITE_ENABLE_LOCKING_STYLE\n    /* Cache zFilename in the locking context (AFP and dotlock override) for\n    ** proxyLock activation is possible (remote proxy is based on db name)\n    ** zFilename remains valid until file is closed, to support */\n    pNew->lockingContext = (void*)zFilename;\n#endif\n  }\n\n  if( pLockingStyle == &posixIoMethods\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n    || pLockingStyle == &nfsIoMethods\n#endif\n  ){\n    unixEnterMutex();\n    rc = findInodeInfo(pNew, &pNew->pInode);\n    if( rc!=SQLITE_OK ){\n      /* If an error occured in findInodeInfo(), close the file descriptor\n      ** immediately, before releasing the mutex. findInodeInfo() may fail\n      ** in two scenarios:\n      **\n      **   (a) A call to fstat() failed.\n      **   (b) A malloc failed.\n      **\n      ** Scenario (b) may only occur if the process is holding no other\n      ** file descriptors open on the same file. If there were other file\n      ** descriptors on this file, then no malloc would be required by\n      ** findInodeInfo(). If this is the case, it is quite safe to close\n      ** handle h - as it is guaranteed that no posix locks will be released\n      ** by doing so.\n      **\n      ** If scenario (a) caused the error then things are not so safe. The\n      ** implicit assumption here is that if fstat() fails, things are in\n      ** such bad shape that dropping a lock or two doesn't matter much.\n      */\n      robust_close(pNew, h, __LINE__);\n      h = -1;\n    }\n    unixLeaveMutex();\n  }\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n  else if( pLockingStyle == &afpIoMethods ){\n    /* AFP locking uses the file path so it needs to be included in\n    ** the afpLockingContext.\n    */\n    afpLockingContext *pCtx;\n    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );\n    if( pCtx==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      /* NB: zFilename exists and remains valid until the file is closed\n      ** according to requirement F11141.  So we do not need to make a\n      ** copy of the filename. */\n      pCtx->dbPath = zFilename;\n      pCtx->reserved = 0;\n      srandomdev();\n      unixEnterMutex();\n      rc = findInodeInfo(pNew, &pNew->pInode);\n      if( rc!=SQLITE_OK ){\n        sqlite3_free(pNew->lockingContext);\n        robust_close(pNew, h, __LINE__);\n        h = -1;\n      }\n      unixLeaveMutex();        \n    }\n  }\n#endif\n\n  else if( pLockingStyle == &dotlockIoMethods ){\n    /* Dotfile locking uses the file path so it needs to be included in\n    ** the dotlockLockingContext \n    */\n    char *zLockFile;\n    int nFilename;\n    assert( zFilename!=0 );\n    nFilename = (int)strlen(zFilename) + 6;\n    zLockFile = (char *)sqlite3_malloc(nFilename);\n    if( zLockFile==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      sqlite3_snprintf(nFilename, zLockFile, \"%s\" DOTLOCK_SUFFIX, zFilename);\n    }\n    pNew->lockingContext = zLockFile;\n  }\n\n#if OS_VXWORKS\n  else if( pLockingStyle == &semIoMethods ){\n    /* Named semaphore locking uses the file path so it needs to be\n    ** included in the semLockingContext\n    */\n    unixEnterMutex();\n    rc = findInodeInfo(pNew, &pNew->pInode);\n    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){\n      char *zSemName = pNew->pInode->aSemName;\n      int n;\n      sqlite3_snprintf(MAX_PATHNAME, zSemName, \"/%s.sem\",\n                       pNew->pId->zCanonicalName);\n      for( n=1; zSemName[n]; n++ )\n        if( zSemName[n]=='/' ) zSemName[n] = '_';\n      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);\n      if( pNew->pInode->pSem == SEM_FAILED ){\n        rc = SQLITE_NOMEM;\n        pNew->pInode->aSemName[0] = '\\0';\n      }\n    }\n    unixLeaveMutex();\n  }\n#endif\n  \n  pNew->lastErrno = 0;\n#if OS_VXWORKS\n  if( rc!=SQLITE_OK ){\n    if( h>=0 ) robust_close(pNew, h, __LINE__);\n    h = -1;\n    osUnlink(zFilename);\n    isDelete = 0;\n  }\n  if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;\n#endif\n  if( rc!=SQLITE_OK ){\n    if( h>=0 ) robust_close(pNew, h, __LINE__);\n  }else{\n    pNew->pMethod = pLockingStyle;\n    OpenCounter(+1);\n  }\n  return rc;\n}\n\n/*\n** Return the name of a directory in which to put temporary files.\n** If no suitable temporary file directory can be found, return NULL.\n*/\nstatic const char *unixTempFileDir(void){\n  static const char *azDirs[] = {\n     0,\n     0,\n     \"/var/tmp\",\n     \"/usr/tmp\",\n     \"/tmp\",\n     0        /* List terminator */\n  };\n  unsigned int i;\n  struct stat buf;\n  const char *zDir = 0;\n\n  azDirs[0] = sqlite3_temp_directory;\n  if( !azDirs[1] ) azDirs[1] = getenv(\"TMPDIR\");\n  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){\n    if( zDir==0 ) continue;\n    if( osStat(zDir, &buf) ) continue;\n    if( !S_ISDIR(buf.st_mode) ) continue;\n    if( osAccess(zDir, 07) ) continue;\n    break;\n  }\n  return zDir;\n}\n\n/*\n** Create a temporary file name in zBuf.  zBuf must be allocated\n** by the calling process and must be big enough to hold at least\n** pVfs->mxPathname bytes.\n*/\nstatic int unixGetTempname(int nBuf, char *zBuf){\n  static const unsigned char zChars[] =\n    \"abcdefghijklmnopqrstuvwxyz\"\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    \"0123456789\";\n  unsigned int i, j;\n  const char *zDir;\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. \n  */\n  SimulateIOError( return SQLITE_IOERR );\n\n  zDir = unixTempFileDir();\n  if( zDir==0 ) zDir = \".\";\n\n  /* Check that the output buffer is large enough for the temporary file \n  ** name. If it is not, return SQLITE_ERROR.\n  */\n  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){\n    return SQLITE_ERROR;\n  }\n\n  do{\n    sqlite3_snprintf(nBuf-18, zBuf, \"%s/\"SQLITE_TEMP_FILE_PREFIX, zDir);\n    j = (int)strlen(zBuf);\n    sqlite3_randomness(15, &zBuf[j]);\n    for(i=0; i<15; i++, j++){\n      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];\n    }\n    zBuf[j] = 0;\n    zBuf[j+1] = 0;\n  }while( osAccess(zBuf,0)==0 );\n  return SQLITE_OK;\n}\n\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n/*\n** Routine to transform a unixFile into a proxy-locking unixFile.\n** Implementation in the proxy-lock division, but used by unixOpen()\n** if SQLITE_PREFER_PROXY_LOCKING is defined.\n*/\nstatic int proxyTransformUnixFile(unixFile*, const char*);\n#endif\n\n/*\n** Search for an unused file descriptor that was opened on the database \n** file (not a journal or master-journal file) identified by pathname\n** zPath with SQLITE_OPEN_XXX flags matching those passed as the second\n** argument to this function.\n**\n** Such a file descriptor may exist if a database connection was closed\n** but the associated file descriptor could not be closed because some\n** other file descriptor open on the same file is holding a file-lock.\n** Refer to comments in the unixClose() function and the lengthy comment\n** describing \"Posix Advisory Locking\" at the start of this file for \n** further details. Also, ticket #4018.\n**\n** If a suitable file descriptor is found, then it is returned. If no\n** such file descriptor is located, -1 is returned.\n*/\nstatic UnixUnusedFd *findReusableFd(const char *zPath, int flags){\n  UnixUnusedFd *pUnused = 0;\n\n  /* Do not search for an unused file descriptor on vxworks. Not because\n  ** vxworks would not benefit from the change (it might, we're not sure),\n  ** but because no way to test it is currently available. It is better \n  ** not to risk breaking vxworks support for the sake of such an obscure \n  ** feature.  */\n#if !OS_VXWORKS\n  struct stat sStat;                   /* Results of stat() call */\n\n  /* A stat() call may fail for various reasons. If this happens, it is\n  ** almost certain that an open() call on the same path will also fail.\n  ** For this reason, if an error occurs in the stat() call here, it is\n  ** ignored and -1 is returned. The caller will try to open a new file\n  ** descriptor on the same path, fail, and return an error to SQLite.\n  **\n  ** Even if a subsequent open() call does succeed, the consequences of\n  ** not searching for a resusable file descriptor are not dire.  */\n  if( 0==osStat(zPath, &sStat) ){\n    unixInodeInfo *pInode;\n\n    unixEnterMutex();\n    pInode = inodeList;\n    while( pInode && (pInode->fileId.dev!=sStat.st_dev\n                     || pInode->fileId.ino!=sStat.st_ino) ){\n       pInode = pInode->pNext;\n    }\n    if( pInode ){\n      UnixUnusedFd **pp;\n      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));\n      pUnused = *pp;\n      if( pUnused ){\n        *pp = pUnused->pNext;\n      }\n    }\n    unixLeaveMutex();\n  }\n#endif    /* if !OS_VXWORKS */\n  return pUnused;\n}\n\n/*\n** This function is called by unixOpen() to determine the unix permissions\n** to create new files with. If no error occurs, then SQLITE_OK is returned\n** and a value suitable for passing as the third argument to open(2) is\n** written to *pMode. If an IO error occurs, an SQLite error code is \n** returned and the value of *pMode is not modified.\n**\n** In most cases cases, this routine sets *pMode to 0, which will become\n** an indication to robust_open() to create the file using\n** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.\n** But if the file being opened is a WAL or regular journal file, then \n** this function queries the file-system for the permissions on the \n** corresponding database file and sets *pMode to this value. Whenever \n** possible, WAL and journal files are created using the same permissions \n** as the associated database file.\n**\n** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the\n** original filename is unavailable.  But 8_3_NAMES is only used for\n** FAT filesystems and permissions do not matter there, so just use\n** the default permissions.\n*/\nstatic int findCreateFileMode(\n  const char *zPath,              /* Path of file (possibly) being created */\n  int flags,                      /* Flags passed as 4th argument to xOpen() */\n  mode_t *pMode,                  /* OUT: Permissions to open file with */\n  uid_t *pUid,                    /* OUT: uid to set on the file */\n  gid_t *pGid                     /* OUT: gid to set on the file */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  *pMode = 0;\n  *pUid = 0;\n  *pGid = 0;\n  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){\n    char zDb[MAX_PATHNAME+1];     /* Database file path */\n    int nDb;                      /* Number of valid bytes in zDb */\n    struct stat sStat;            /* Output of stat() on database file */\n\n    /* zPath is a path to a WAL or journal file. The following block derives\n    ** the path to the associated database file from zPath. This block handles\n    ** the following naming conventions:\n    **\n    **   \"<path to db>-journal\"\n    **   \"<path to db>-wal\"\n    **   \"<path to db>-journalNN\"\n    **   \"<path to db>-walNN\"\n    **\n    ** where NN is a decimal number. The NN naming schemes are \n    ** used by the test_multiplex.c module.\n    */\n    nDb = sqlite3Strlen30(zPath) - 1; \n#ifdef SQLITE_ENABLE_8_3_NAMES\n    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;\n    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;\n#else\n    while( zPath[nDb]!='-' ){\n      assert( nDb>0 );\n      assert( zPath[nDb]!='\\n' );\n      nDb--;\n    }\n#endif\n    memcpy(zDb, zPath, nDb);\n    zDb[nDb] = '\\0';\n\n    if( 0==osStat(zDb, &sStat) ){\n      *pMode = sStat.st_mode & 0777;\n      *pUid = sStat.st_uid;\n      *pGid = sStat.st_gid;\n    }else{\n      rc = SQLITE_IOERR_FSTAT;\n    }\n  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){\n    *pMode = 0600;\n  }\n  return rc;\n}\n\n/*\n** Open the file zPath.\n** \n** Previously, the SQLite OS layer used three functions in place of this\n** one:\n**\n**     sqlite3OsOpenReadWrite();\n**     sqlite3OsOpenReadOnly();\n**     sqlite3OsOpenExclusive();\n**\n** These calls correspond to the following combinations of flags:\n**\n**     ReadWrite() ->     (READWRITE | CREATE)\n**     ReadOnly()  ->     (READONLY) \n**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)\n**\n** The old OpenExclusive() accepted a boolean argument - \"delFlag\". If\n** true, the file was configured to be automatically deleted when the\n** file handle closed. To achieve the same effect using this new \n** interface, add the DELETEONCLOSE flag to those specified above for \n** OpenExclusive().\n*/\nstatic int unixOpen(\n  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */\n  const char *zPath,           /* Pathname of file to be opened */\n  sqlite3_file *pFile,         /* The file descriptor to be filled in */\n  int flags,                   /* Input flags to control the opening */\n  int *pOutFlags               /* Output flags returned to SQLite core */\n){\n  unixFile *p = (unixFile *)pFile;\n  int fd = -1;                   /* File descriptor returned by open() */\n  int openFlags = 0;             /* Flags to pass to open() */\n  int eType = flags&0xFFFFFF00;  /* Type of file to open */\n  int noLock;                    /* True to omit locking primitives */\n  int rc = SQLITE_OK;            /* Function Return Code */\n  int ctrlFlags = 0;             /* UNIXFILE_* flags */\n\n  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);\n  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);\n  int isCreate     = (flags & SQLITE_OPEN_CREATE);\n  int isReadonly   = (flags & SQLITE_OPEN_READONLY);\n  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);\n#if SQLITE_ENABLE_LOCKING_STYLE\n  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);\n#endif\n#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE\n  struct statfs fsInfo;\n#endif\n\n  /* If creating a master or main-file journal, this function will open\n  ** a file-descriptor on the directory too. The first time unixSync()\n  ** is called the directory file descriptor will be fsync()ed and close()d.\n  */\n  int syncDir = (isCreate && (\n        eType==SQLITE_OPEN_MASTER_JOURNAL \n     || eType==SQLITE_OPEN_MAIN_JOURNAL \n     || eType==SQLITE_OPEN_WAL\n  ));\n\n  /* If argument zPath is a NULL pointer, this function is required to open\n  ** a temporary file. Use this buffer to store the file name in.\n  */\n  char zTmpname[MAX_PATHNAME+2];\n  const char *zName = zPath;\n\n  /* Check the following statements are true: \n  **\n  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and \n  **   (b) if CREATE is set, then READWRITE must also be set, and\n  **   (c) if EXCLUSIVE is set, then CREATE must also be set.\n  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.\n  */\n  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));\n  assert(isCreate==0 || isReadWrite);\n  assert(isExclusive==0 || isCreate);\n  assert(isDelete==0 || isCreate);\n\n  /* The main DB, main journal, WAL file and master journal are never \n  ** automatically deleted. Nor are they ever temporary files.  */\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );\n\n  /* Assert that the upper layer has set one of the \"file-type\" flags. */\n  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB \n       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL \n       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL \n       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL\n  );\n\n  memset(p, 0, sizeof(unixFile));\n\n  if( eType==SQLITE_OPEN_MAIN_DB ){\n    UnixUnusedFd *pUnused;\n    pUnused = findReusableFd(zName, flags);\n    if( pUnused ){\n      fd = pUnused->fd;\n    }else{\n      pUnused = sqlite3_malloc(sizeof(*pUnused));\n      if( !pUnused ){\n        return SQLITE_NOMEM;\n      }\n    }\n    p->pUnused = pUnused;\n\n    /* Database filenames are double-zero terminated if they are not\n    ** URIs with parameters.  Hence, they can always be passed into\n    ** sqlite3_uri_parameter(). */\n    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );\n\n  }else if( !zName ){\n    /* If zName is NULL, the upper layer is requesting a temp file. */\n    assert(isDelete && !syncDir);\n    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    zName = zTmpname;\n\n    /* Generated temporary filenames are always double-zero terminated\n    ** for use by sqlite3_uri_parameter(). */\n    assert( zName[strlen(zName)+1]==0 );\n  }\n\n  /* Determine the value of the flags parameter passed to POSIX function\n  ** open(). These must be calculated even if open() is not called, as\n  ** they may be stored as part of the file handle and used by the \n  ** 'conch file' locking functions later on.  */\n  if( isReadonly )  openFlags |= O_RDONLY;\n  if( isReadWrite ) openFlags |= O_RDWR;\n  if( isCreate )    openFlags |= O_CREAT;\n  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);\n  openFlags |= (O_LARGEFILE|O_BINARY);\n\n  if( fd<0 ){\n    mode_t openMode;              /* Permissions to create file with */\n    uid_t uid;                    /* Userid for the file */\n    gid_t gid;                    /* Groupid for the file */\n    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);\n    if( rc!=SQLITE_OK ){\n      assert( !p->pUnused );\n      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );\n      return rc;\n    }\n    fd = robust_open(zName, openFlags, openMode);\n    OSTRACE((\"OPENX   %-3d %s 0%o\\n\", fd, zName, openFlags));\n    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){\n      /* Failed to open the file for read/write access. Try read-only. */\n      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);\n      openFlags &= ~(O_RDWR|O_CREAT);\n      flags |= SQLITE_OPEN_READONLY;\n      openFlags |= O_RDONLY;\n      isReadonly = 1;\n      fd = robust_open(zName, openFlags, openMode);\n    }\n    if( fd<0 ){\n      rc = unixLogError(SQLITE_CANTOPEN_BKPT, \"open\", zName);\n      goto open_finished;\n    }\n\n    /* If this process is running as root and if creating a new rollback\n    ** journal or WAL file, set the ownership of the journal or WAL to be\n    ** the same as the original database.\n    */\n    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){\n      osFchown(fd, uid, gid);\n    }\n  }\n  assert( fd>=0 );\n  if( pOutFlags ){\n    *pOutFlags = flags;\n  }\n\n  if( p->pUnused ){\n    p->pUnused->fd = fd;\n    p->pUnused->flags = flags;\n  }\n\n  if( isDelete ){\n#if OS_VXWORKS\n    zPath = zName;\n#else\n    osUnlink(zName);\n#endif\n  }\n#if SQLITE_ENABLE_LOCKING_STYLE\n  else{\n    p->openFlags = openFlags;\n  }\n#endif\n\n  noLock = eType!=SQLITE_OPEN_MAIN_DB;\n\n  \n#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE\n  if( fstatfs(fd, &fsInfo) == -1 ){\n    ((unixFile*)pFile)->lastErrno = errno;\n    robust_close(p, fd, __LINE__);\n    return SQLITE_IOERR_ACCESS;\n  }\n  if (0 == strncmp(\"msdos\", fsInfo.f_fstypename, 5)) {\n    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;\n  }\n#endif\n\n  /* Set up appropriate ctrlFlags */\n  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;\n  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;\n  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;\n  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;\n  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;\n\n#if SQLITE_ENABLE_LOCKING_STYLE\n#if SQLITE_PREFER_PROXY_LOCKING\n  isAutoProxy = 1;\n#endif\n  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){\n    char *envforce = getenv(\"SQLITE_FORCE_PROXY_LOCKING\");\n    int useProxy = 0;\n\n    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means \n    ** never use proxy, NULL means use proxy for non-local files only.  */\n    if( envforce!=NULL ){\n      useProxy = atoi(envforce)>0;\n    }else{\n      if( statfs(zPath, &fsInfo) == -1 ){\n        /* In theory, the close(fd) call is sub-optimal. If the file opened\n        ** with fd is a database file, and there are other connections open\n        ** on that file that are currently holding advisory locks on it,\n        ** then the call to close() will cancel those locks. In practice,\n        ** we're assuming that statfs() doesn't fail very often. At least\n        ** not while other file descriptors opened by the same process on\n        ** the same file are working.  */\n        p->lastErrno = errno;\n        robust_close(p, fd, __LINE__);\n        rc = SQLITE_IOERR_ACCESS;\n        goto open_finished;\n      }\n      useProxy = !(fsInfo.f_flags&MNT_LOCAL);\n    }\n    if( useProxy ){\n      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);\n      if( rc==SQLITE_OK ){\n        rc = proxyTransformUnixFile((unixFile*)pFile, \":auto:\");\n        if( rc!=SQLITE_OK ){\n          /* Use unixClose to clean up the resources added in fillInUnixFile \n          ** and clear all the structure's references.  Specifically, \n          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op \n          */\n          unixClose(pFile);\n          return rc;\n        }\n      }\n      goto open_finished;\n    }\n  }\n#endif\n  \n  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);\n\nopen_finished:\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(p->pUnused);\n  }\n  return rc;\n}\n\n\n/*\n** Delete the file at zPath. If the dirSync argument is true, fsync()\n** the directory after deleting the file.\n*/\nstatic int unixDelete(\n  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */\n  const char *zPath,        /* Name of file to be deleted */\n  int dirSync               /* If true, fsync() directory after deleting file */\n){\n  int rc = SQLITE_OK;\n  UNUSED_PARAMETER(NotUsed);\n  SimulateIOError(return SQLITE_IOERR_DELETE);\n  if( osUnlink(zPath)==(-1) && errno!=ENOENT ){\n    return unixLogError(SQLITE_IOERR_DELETE, \"unlink\", zPath);\n  }\n#ifndef SQLITE_DISABLE_DIRSYNC\n  if( (dirSync & 1)!=0 ){\n    int fd;\n    rc = osOpenDirectory(zPath, &fd);\n    if( rc==SQLITE_OK ){\n#if OS_VXWORKS\n      if( fsync(fd)==-1 )\n#else\n      if( fsync(fd) )\n#endif\n      {\n        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, \"fsync\", zPath);\n      }\n      robust_close(0, fd, __LINE__);\n    }else if( rc==SQLITE_CANTOPEN ){\n      rc = SQLITE_OK;\n    }\n  }\n#endif\n  return rc;\n}\n\n/*\n** Test the existance of or access permissions of file zPath. The\n** test performed depends on the value of flags:\n**\n**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists\n**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.\n**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.\n**\n** Otherwise return 0.\n*/\nstatic int unixAccess(\n  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */\n  const char *zPath,      /* Path of the file to examine */\n  int flags,              /* What do we want to learn about the zPath file? */\n  int *pResOut            /* Write result boolean here */\n){\n  int amode = 0;\n  UNUSED_PARAMETER(NotUsed);\n  SimulateIOError( return SQLITE_IOERR_ACCESS; );\n  switch( flags ){\n    case SQLITE_ACCESS_EXISTS:\n      amode = F_OK;\n      break;\n    case SQLITE_ACCESS_READWRITE:\n      amode = W_OK|R_OK;\n      break;\n    case SQLITE_ACCESS_READ:\n      amode = R_OK;\n      break;\n\n    default:\n      assert(!\"Invalid flags argument\");\n  }\n  *pResOut = (osAccess(zPath, amode)==0);\n  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){\n    struct stat buf;\n    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){\n      *pResOut = 0;\n    }\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** Turn a relative pathname into a full pathname. The relative path\n** is stored as a nul-terminated string in the buffer pointed to by\n** zPath. \n**\n** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes \n** (in this case, MAX_PATHNAME bytes). The full-path is written to\n** this buffer before returning.\n*/\nstatic int unixFullPathname(\n  sqlite3_vfs *pVfs,            /* Pointer to vfs object */\n  const char *zPath,            /* Possibly relative input path */\n  int nOut,                     /* Size of output buffer in bytes */\n  char *zOut                    /* Output buffer */\n){\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. This function could fail if, for example, the\n  ** current working directory has been unlinked.\n  */\n  SimulateIOError( return SQLITE_ERROR );\n\n  assert( pVfs->mxPathname==MAX_PATHNAME );\n  UNUSED_PARAMETER(pVfs);\n\n  zOut[nOut-1] = '\\0';\n  if( zPath[0]=='/' ){\n    sqlite3_snprintf(nOut, zOut, \"%s\", zPath);\n  }else{\n    int nCwd;\n    if( osGetcwd(zOut, nOut-1)==0 ){\n      return unixLogError(SQLITE_CANTOPEN_BKPT, \"getcwd\", zPath);\n    }\n    nCwd = (int)strlen(zOut);\n    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], \"/%s\", zPath);\n  }\n  return SQLITE_OK;\n}\n\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Interfaces for opening a shared library, finding entry points\n** within the shared library, and closing the shared library.\n*/\n#include <dlfcn.h>\nstatic void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){\n  UNUSED_PARAMETER(NotUsed);\n  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);\n}\n\n/*\n** SQLite calls this function immediately after a call to unixDlSym() or\n** unixDlOpen() fails (returns a null pointer). If a more detailed error\n** message is available, it is written to zBufOut. If no error message\n** is available, zBufOut is left unmodified and SQLite uses a default\n** error message.\n*/\nstatic void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){\n  const char *zErr;\n  UNUSED_PARAMETER(NotUsed);\n  unixEnterMutex();\n  zErr = dlerror();\n  if( zErr ){\n    sqlite3_snprintf(nBuf, zBufOut, \"%s\", zErr);\n  }\n  unixLeaveMutex();\n}\nstatic void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){\n  /* \n  ** GCC with -pedantic-errors says that C90 does not allow a void* to be\n  ** cast into a pointer to a function.  And yet the library dlsym() routine\n  ** returns a void* which is really a pointer to a function.  So how do we\n  ** use dlsym() with -pedantic-errors?\n  **\n  ** Variable x below is defined to be a pointer to a function taking\n  ** parameters void* and const char* and returning a pointer to a function.\n  ** We initialize x by assigning it a pointer to the dlsym() function.\n  ** (That assignment requires a cast.)  Then we call the function that\n  ** x points to.  \n  **\n  ** This work-around is unlikely to work correctly on any system where\n  ** you really cannot cast a function pointer into void*.  But then, on the\n  ** other hand, dlsym() will not work on such a system either, so we have\n  ** not really lost anything.\n  */\n  void (*(*x)(void*,const char*))(void);\n  UNUSED_PARAMETER(NotUsed);\n  x = (void(*(*)(void*,const char*))(void))dlsym;\n  return (*x)(p, zSym);\n}\nstatic void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){\n  UNUSED_PARAMETER(NotUsed);\n  dlclose(pHandle);\n}\n#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */\n  #define unixDlOpen  0\n  #define unixDlError 0\n  #define unixDlSym   0\n  #define unixDlClose 0\n#endif\n\n/*\n** Write nBuf bytes of random data to the supplied buffer zBuf.\n*/\nstatic int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){\n  UNUSED_PARAMETER(NotUsed);\n  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));\n\n  /* We have to initialize zBuf to prevent valgrind from reporting\n  ** errors.  The reports issued by valgrind are incorrect - we would\n  ** prefer that the randomness be increased by making use of the\n  ** uninitialized space in zBuf - but valgrind errors tend to worry\n  ** some users.  Rather than argue, it seems easier just to initialize\n  ** the whole array and silence valgrind, even if that means less randomness\n  ** in the random seed.\n  **\n  ** When testing, initializing zBuf[] to zero is all we do.  That means\n  ** that we always use the same random number sequence.  This makes the\n  ** tests repeatable.\n  */\n  memset(zBuf, 0, nBuf);\n#if !defined(SQLITE_TEST)\n  {\n    int pid, fd, got;\n    fd = robust_open(\"/dev/urandom\", O_RDONLY, 0);\n    if( fd<0 ){\n      time_t t;\n      time(&t);\n      memcpy(zBuf, &t, sizeof(t));\n      pid = getpid();\n      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));\n      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );\n      nBuf = sizeof(t) + sizeof(pid);\n    }else{\n      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );\n      robust_close(0, fd, __LINE__);\n    }\n  }\n#endif\n  return nBuf;\n}\n\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n** The argument is the number of microseconds we want to sleep.\n** The return value is the number of microseconds of sleep actually\n** requested from the underlying operating system, a number which\n** might be greater than or equal to the argument, but not less\n** than the argument.\n*/\nstatic int unixSleep(sqlite3_vfs *NotUsed, int microseconds){\n#if OS_VXWORKS\n  struct timespec sp;\n\n  sp.tv_sec = microseconds / 1000000;\n  sp.tv_nsec = (microseconds % 1000000) * 1000;\n  nanosleep(&sp, NULL);\n  UNUSED_PARAMETER(NotUsed);\n  return microseconds;\n#elif defined(HAVE_USLEEP) && HAVE_USLEEP\n  usleep(microseconds);\n  UNUSED_PARAMETER(NotUsed);\n  return microseconds;\n#else\n  int seconds = (microseconds+999999)/1000000;\n  sleep(seconds);\n  UNUSED_PARAMETER(NotUsed);\n  return seconds*1000000;\n#endif\n}\n\n/*\n** The following variable, if set to a non-zero value, is interpreted as\n** the number of seconds since 1970 and is used to set the result of\n** sqlite3OsCurrentTime() during testing.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */\n#endif\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write into *piNow\n** the current time and date as a Julian Day number times 86_400_000.  In\n** other words, write into *piNow the number of milliseconds since the Julian\n** epoch of noon in Greenwich on November 24, 4714 B.C according to the\n** proleptic Gregorian calendar.\n**\n** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date \n** cannot be found.\n*/\nstatic int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){\n  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;\n  int rc = SQLITE_OK;\n#if defined(NO_GETTOD)\n  time_t t;\n  time(&t);\n  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;\n#elif OS_VXWORKS\n  struct timespec sNow;\n  clock_gettime(CLOCK_REALTIME, &sNow);\n  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;\n#else\n  struct timeval sNow;\n  if( gettimeofday(&sNow, 0)==0 ){\n    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;\n  }else{\n    rc = SQLITE_ERROR;\n  }\n#endif\n\n#ifdef SQLITE_TEST\n  if( sqlite3_current_time ){\n    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;\n  }\n#endif\n  UNUSED_PARAMETER(NotUsed);\n  return rc;\n}\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write the\n** current time and date as a Julian Day number into *prNow and\n** return 0.  Return 1 if the time and date cannot be found.\n*/\nstatic int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){\n  sqlite3_int64 i = 0;\n  int rc;\n  UNUSED_PARAMETER(NotUsed);\n  rc = unixCurrentTimeInt64(0, &i);\n  *prNow = i/86400000.0;\n  return rc;\n}\n\n/*\n** We added the xGetLastError() method with the intention of providing\n** better low-level error messages when operating-system problems come up\n** during SQLite operation.  But so far, none of that has been implemented\n** in the core.  So this routine is never called.  For now, it is merely\n** a place-holder.\n*/\nstatic int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){\n  UNUSED_PARAMETER(NotUsed);\n  UNUSED_PARAMETER(NotUsed2);\n  UNUSED_PARAMETER(NotUsed3);\n  return 0;\n}\n\n\n/*\n************************ End of sqlite3_vfs methods ***************************\n******************************************************************************/\n\n/******************************************************************************\n************************** Begin Proxy Locking ********************************\n**\n** Proxy locking is a \"uber-locking-method\" in this sense:  It uses the\n** other locking methods on secondary lock files.  Proxy locking is a\n** meta-layer over top of the primitive locking implemented above.  For\n** this reason, the division that implements of proxy locking is deferred\n** until late in the file (here) after all of the other I/O methods have\n** been defined - so that the primitive locking methods are available\n** as services to help with the implementation of proxy locking.\n**\n****\n**\n** The default locking schemes in SQLite use byte-range locks on the\n** database file to coordinate safe, concurrent access by multiple readers\n** and writers [http://sqlite.org/lockingv3.html].  The five file locking\n** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented\n** as POSIX read & write locks over fixed set of locations (via fsctl),\n** on AFP and SMB only exclusive byte-range locks are available via fsctl\n** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.\n** To simulate a F_RDLCK on the shared range, on AFP a randomly selected\n** address in the shared range is taken for a SHARED lock, the entire\n** shared range is taken for an EXCLUSIVE lock):\n**\n**      PENDING_BYTE        0x40000000\n**      RESERVED_BYTE       0x40000001\n**      SHARED_RANGE        0x40000002 -> 0x40000200\n**\n** This works well on the local file system, but shows a nearly 100x\n** slowdown in read performance on AFP because the AFP client disables\n** the read cache when byte-range locks are present.  Enabling the read\n** cache exposes a cache coherency problem that is present on all OS X\n** supported network file systems.  NFS and AFP both observe the\n** close-to-open semantics for ensuring cache coherency\n** [http://nfs.sourceforge.net/#faq_a8], which does not effectively\n** address the requirements for concurrent database access by multiple\n** readers and writers\n** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].\n**\n** To address the performance and cache coherency issues, proxy file locking\n** changes the way database access is controlled by limiting access to a\n** single host at a time and moving file locks off of the database file\n** and onto a proxy file on the local file system.  \n**\n**\n** Using proxy locks\n** -----------------\n**\n** C APIs\n**\n**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,\n**                       <proxy_path> | \":auto:\");\n**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);\n**\n**\n** SQL pragmas\n**\n**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:\n**  PRAGMA [database.]lock_proxy_file\n**\n** Specifying \":auto:\" means that if there is a conch file with a matching\n** host ID in it, the proxy path in the conch file will be used, otherwise\n** a proxy path based on the user's temp dir\n** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the\n** actual proxy file name is generated from the name and path of the\n** database file.  For example:\n**\n**       For database path \"/Users/me/foo.db\" \n**       The lock path will be \"<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:\")\n**\n** Once a lock proxy is configured for a database connection, it can not\n** be removed, however it may be switched to a different proxy path via\n** the above APIs (assuming the conch file is not being held by another\n** connection or process). \n**\n**\n** How proxy locking works\n** -----------------------\n**\n** Proxy file locking relies primarily on two new supporting files: \n**\n**   *  conch file to limit access to the database file to a single host\n**      at a time\n**\n**   *  proxy file to act as a proxy for the advisory locks normally\n**      taken on the database\n**\n** The conch file - to use a proxy file, sqlite must first \"hold the conch\"\n** by taking an sqlite-style shared lock on the conch file, reading the\n** contents and comparing the host's unique host ID (see below) and lock\n** proxy path against the values stored in the conch.  The conch file is\n** stored in the same directory as the database file and the file name\n** is patterned after the database file name as \".<databasename>-conch\".\n** If the conch file does not exist, or it's contents do not match the\n** host ID and/or proxy path, then the lock is escalated to an exclusive\n** lock and the conch file contents is updated with the host ID and proxy\n** path and the lock is downgraded to a shared lock again.  If the conch\n** is held by another process (with a shared lock), the exclusive lock\n** will fail and SQLITE_BUSY is returned.\n**\n** The proxy file - a single-byte file used for all advisory file locks\n** normally taken on the database file.   This allows for safe sharing\n** of the database file for multiple readers and writers on the same\n** host (the conch ensures that they all use the same local lock file).\n**\n** Requesting the lock proxy does not immediately take the conch, it is\n** only taken when the first request to lock database file is made.  \n** This matches the semantics of the traditional locking behavior, where\n** opening a connection to a database file does not take a lock on it.\n** The shared lock and an open file descriptor are maintained until \n** the connection to the database is closed. \n**\n** The proxy file and the lock file are never deleted so they only need\n** to be created the first time they are used.\n**\n** Configuration options\n** ---------------------\n**\n**  SQLITE_PREFER_PROXY_LOCKING\n**\n**       Database files accessed on non-local file systems are\n**       automatically configured for proxy locking, lock files are\n**       named automatically using the same logic as\n**       PRAGMA lock_proxy_file=\":auto:\"\n**    \n**  SQLITE_PROXY_DEBUG\n**\n**       Enables the logging of error messages during host id file\n**       retrieval and creation\n**\n**  LOCKPROXYDIR\n**\n**       Overrides the default directory used for lock proxy files that\n**       are named automatically via the \":auto:\" setting\n**\n**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS\n**\n**       Permissions to use when creating a directory for storing the\n**       lock proxy files, only used when LOCKPROXYDIR is not set.\n**    \n**    \n** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,\n** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will\n** force proxy locking to be used for every database file opened, and 0\n** will force automatic proxy locking to be disabled for all database\n** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or\n** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).\n*/\n\n/*\n** Proxy locking is only available on MacOSX \n*/\n#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE\n\n/*\n** The proxyLockingContext has the path and file structures for the remote \n** and local proxy files in it\n*/\ntypedef struct proxyLockingContext proxyLockingContext;\nstruct proxyLockingContext {\n  unixFile *conchFile;         /* Open conch file */\n  char *conchFilePath;         /* Name of the conch file */\n  unixFile *lockProxy;         /* Open proxy lock file */\n  char *lockProxyPath;         /* Name of the proxy lock file */\n  char *dbPath;                /* Name of the open file */\n  int conchHeld;               /* 1 if the conch is held, -1 if lockless */\n  void *oldLockingContext;     /* Original lockingcontext to restore on close */\n  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */\n};\n\n/* \n** The proxy lock file path for the database at dbPath is written into lPath, \n** which must point to valid, writable memory large enough for a maxLen length\n** file path. \n*/\nstatic int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){\n  int len;\n  int dbLen;\n  int i;\n\n#ifdef LOCKPROXYDIR\n  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);\n#else\n# ifdef _CS_DARWIN_USER_TEMP_DIR\n  {\n    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){\n      OSTRACE((\"GETLOCKPATH  failed %s errno=%d pid=%d\\n\",\n               lPath, errno, getpid()));\n      return SQLITE_IOERR_LOCK;\n    }\n    len = strlcat(lPath, \"sqliteplocks\", maxLen);    \n  }\n# else\n  len = strlcpy(lPath, \"/tmp/\", maxLen);\n# endif\n#endif\n\n  if( lPath[len-1]!='/' ){\n    len = strlcat(lPath, \"/\", maxLen);\n  }\n  \n  /* transform the db path to a unique cache name */\n  dbLen = (int)strlen(dbPath);\n  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){\n    char c = dbPath[i];\n    lPath[i+len] = (c=='/')?'_':c;\n  }\n  lPath[i+len]='\\0';\n  strlcat(lPath, \":auto:\", maxLen);\n  OSTRACE((\"GETLOCKPATH  proxy lock path=%s pid=%d\\n\", lPath, getpid()));\n  return SQLITE_OK;\n}\n\n/* \n ** Creates the lock file and any missing directories in lockPath\n */\nstatic int proxyCreateLockPath(const char *lockPath){\n  int i, len;\n  char buf[MAXPATHLEN];\n  int start = 0;\n  \n  assert(lockPath!=NULL);\n  /* try to create all the intermediate directories */\n  len = (int)strlen(lockPath);\n  buf[0] = lockPath[0];\n  for( i=1; i<len; i++ ){\n    if( lockPath[i] == '/' && (i - start > 0) ){\n      /* only mkdir if leaf dir != \".\" or \"/\" or \"..\" */\n      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') \n         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){\n        buf[i]='\\0';\n        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){\n          int err=errno;\n          if( err!=EEXIST ) {\n            OSTRACE((\"CREATELOCKPATH  FAILED creating %s, \"\n                     \"'%s' proxy lock path=%s pid=%d\\n\",\n                     buf, strerror(err), lockPath, getpid()));\n            return err;\n          }\n        }\n      }\n      start=i+1;\n    }\n    buf[i] = lockPath[i];\n  }\n  OSTRACE((\"CREATELOCKPATH  proxy lock path=%s pid=%d\\n\", lockPath, getpid()));\n  return 0;\n}\n\n/*\n** Create a new VFS file descriptor (stored in memory obtained from\n** sqlite3_malloc) and open the file named \"path\" in the file descriptor.\n**\n** The caller is responsible not only for closing the file descriptor\n** but also for freeing the memory associated with the file descriptor.\n*/\nstatic int proxyCreateUnixFile(\n    const char *path,        /* path for the new unixFile */\n    unixFile **ppFile,       /* unixFile created and returned by ref */\n    int islockfile           /* if non zero missing dirs will be created */\n) {\n  int fd = -1;\n  unixFile *pNew;\n  int rc = SQLITE_OK;\n  int openFlags = O_RDWR | O_CREAT;\n  sqlite3_vfs dummyVfs;\n  int terrno = 0;\n  UnixUnusedFd *pUnused = NULL;\n\n  /* 1. first try to open/create the file\n  ** 2. if that fails, and this is a lock file (not-conch), try creating\n  ** the parent directories and then try again.\n  ** 3. if that fails, try to open the file read-only\n  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file\n  */\n  pUnused = findReusableFd(path, openFlags);\n  if( pUnused ){\n    fd = pUnused->fd;\n  }else{\n    pUnused = sqlite3_malloc(sizeof(*pUnused));\n    if( !pUnused ){\n      return SQLITE_NOMEM;\n    }\n  }\n  if( fd<0 ){\n    fd = robust_open(path, openFlags, 0);\n    terrno = errno;\n    if( fd<0 && errno==ENOENT && islockfile ){\n      if( proxyCreateLockPath(path) == SQLITE_OK ){\n        fd = robust_open(path, openFlags, 0);\n      }\n    }\n  }\n  if( fd<0 ){\n    openFlags = O_RDONLY;\n    fd = robust_open(path, openFlags, 0);\n    terrno = errno;\n  }\n  if( fd<0 ){\n    if( islockfile ){\n      return SQLITE_BUSY;\n    }\n    switch (terrno) {\n      case EACCES:\n        return SQLITE_PERM;\n      case EIO: \n        return SQLITE_IOERR_LOCK; /* even though it is the conch */\n      default:\n        return SQLITE_CANTOPEN_BKPT;\n    }\n  }\n  \n  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));\n  if( pNew==NULL ){\n    rc = SQLITE_NOMEM;\n    goto end_create_proxy;\n  }\n  memset(pNew, 0, sizeof(unixFile));\n  pNew->openFlags = openFlags;\n  memset(&dummyVfs, 0, sizeof(dummyVfs));\n  dummyVfs.pAppData = (void*)&autolockIoFinder;\n  dummyVfs.zName = \"dummy\";\n  pUnused->fd = fd;\n  pUnused->flags = openFlags;\n  pNew->pUnused = pUnused;\n  \n  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);\n  if( rc==SQLITE_OK ){\n    *ppFile = pNew;\n    return SQLITE_OK;\n  }\nend_create_proxy:    \n  robust_close(pNew, fd, __LINE__);\n  sqlite3_free(pNew);\n  sqlite3_free(pUnused);\n  return rc;\n}\n\n#ifdef SQLITE_TEST\n/* simulate multiple hosts by creating unique hostid file paths */\nSQLITE_API int sqlite3_hostid_num = 0;\n#endif\n\n#define PROXY_HOSTIDLEN    16  /* conch file host id length */\n\n/* Not always defined in the headers as it ought to be */\nextern int gethostuuid(uuid_t id, const struct timespec *wait);\n\n/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN \n** bytes of writable memory.\n*/\nstatic int proxyGetHostID(unsigned char *pHostID, int *pError){\n  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));\n  memset(pHostID, 0, PROXY_HOSTIDLEN);\n#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\\\n               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050\n  {\n    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */\n    if( gethostuuid(pHostID, &timeout) ){\n      int err = errno;\n      if( pError ){\n        *pError = err;\n      }\n      return SQLITE_IOERR;\n    }\n  }\n#else\n  UNUSED_PARAMETER(pError);\n#endif\n#ifdef SQLITE_TEST\n  /* simulate multiple hosts by creating unique hostid file paths */\n  if( sqlite3_hostid_num != 0){\n    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));\n  }\n#endif\n  \n  return SQLITE_OK;\n}\n\n/* The conch file contains the header, host id and lock file path\n */\n#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */\n#define PROXY_HEADERLEN    1   /* conch file header length */\n#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)\n#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)\n\n/* \n** Takes an open conch file, copies the contents to a new path and then moves \n** it back.  The newly created file's file descriptor is assigned to the\n** conch file structure and finally the original conch file descriptor is \n** closed.  Returns zero if successful.\n*/\nstatic int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  unixFile *conchFile = pCtx->conchFile;\n  char tPath[MAXPATHLEN];\n  char buf[PROXY_MAXCONCHLEN];\n  char *cPath = pCtx->conchFilePath;\n  size_t readLen = 0;\n  size_t pathLen = 0;\n  char errmsg[64] = \"\";\n  int fd = -1;\n  int rc = -1;\n  UNUSED_PARAMETER(myHostID);\n\n  /* create a new path by replace the trailing '-conch' with '-break' */\n  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);\n  if( pathLen>MAXPATHLEN || pathLen<6 || \n     (strlcpy(&tPath[pathLen-5], \"break\", 6) != 5) ){\n    sqlite3_snprintf(sizeof(errmsg),errmsg,\"path error (len %d)\",(int)pathLen);\n    goto end_breaklock;\n  }\n  /* read the conch content */\n  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);\n  if( readLen<PROXY_PATHINDEX ){\n    sqlite3_snprintf(sizeof(errmsg),errmsg,\"read error (len %d)\",(int)readLen);\n    goto end_breaklock;\n  }\n  /* write it out to the temporary break file */\n  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);\n  if( fd<0 ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"create failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"write failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  if( rename(tPath, cPath) ){\n    sqlite3_snprintf(sizeof(errmsg), errmsg, \"rename failed (%d)\", errno);\n    goto end_breaklock;\n  }\n  rc = 0;\n  fprintf(stderr, \"broke stale lock on %s\\n\", cPath);\n  robust_close(pFile, conchFile->h, __LINE__);\n  conchFile->h = fd;\n  conchFile->openFlags = O_RDWR | O_CREAT;\n\nend_breaklock:\n  if( rc ){\n    if( fd>=0 ){\n      osUnlink(tPath);\n      robust_close(pFile, fd, __LINE__);\n    }\n    fprintf(stderr, \"failed to break stale lock on %s, %s\\n\", cPath, errmsg);\n  }\n  return rc;\n}\n\n/* Take the requested lock on the conch file and break a stale lock if the \n** host id matches.\n*/\nstatic int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  unixFile *conchFile = pCtx->conchFile;\n  int rc = SQLITE_OK;\n  int nTries = 0;\n  struct timespec conchModTime;\n  \n  memset(&conchModTime, 0, sizeof(conchModTime));\n  do {\n    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);\n    nTries ++;\n    if( rc==SQLITE_BUSY ){\n      /* If the lock failed (busy):\n       * 1st try: get the mod time of the conch, wait 0.5s and try again. \n       * 2nd try: fail if the mod time changed or host id is different, wait \n       *           10 sec and try again\n       * 3rd try: break the lock unless the mod time has changed.\n       */\n      struct stat buf;\n      if( osFstat(conchFile->h, &buf) ){\n        pFile->lastErrno = errno;\n        return SQLITE_IOERR_LOCK;\n      }\n      \n      if( nTries==1 ){\n        conchModTime = buf.st_mtimespec;\n        usleep(500000); /* wait 0.5 sec and try the lock again*/\n        continue;  \n      }\n\n      assert( nTries>1 );\n      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || \n         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){\n        return SQLITE_BUSY;\n      }\n      \n      if( nTries==2 ){  \n        char tBuf[PROXY_MAXCONCHLEN];\n        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);\n        if( len<0 ){\n          pFile->lastErrno = errno;\n          return SQLITE_IOERR_LOCK;\n        }\n        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){\n          /* don't break the lock if the host id doesn't match */\n          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){\n            return SQLITE_BUSY;\n          }\n        }else{\n          /* don't break the lock on short read or a version mismatch */\n          return SQLITE_BUSY;\n        }\n        usleep(10000000); /* wait 10 sec and try the lock again */\n        continue; \n      }\n      \n      assert( nTries==3 );\n      if( 0==proxyBreakConchLock(pFile, myHostID) ){\n        rc = SQLITE_OK;\n        if( lockType==EXCLUSIVE_LOCK ){\n          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          \n        }\n        if( !rc ){\n          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);\n        }\n      }\n    }\n  } while( rc==SQLITE_BUSY && nTries<3 );\n  \n  return rc;\n}\n\n/* Takes the conch by taking a shared lock and read the contents conch, if \n** lockPath is non-NULL, the host ID and lock file path must match.  A NULL \n** lockPath means that the lockPath in the conch file will be used if the \n** host IDs match, or a new lock path will be generated automatically \n** and written to the conch file.\n*/\nstatic int proxyTakeConch(unixFile *pFile){\n  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; \n  \n  if( pCtx->conchHeld!=0 ){\n    return SQLITE_OK;\n  }else{\n    unixFile *conchFile = pCtx->conchFile;\n    uuid_t myHostID;\n    int pError = 0;\n    char readBuf[PROXY_MAXCONCHLEN];\n    char lockPath[MAXPATHLEN];\n    char *tempLockPath = NULL;\n    int rc = SQLITE_OK;\n    int createConch = 0;\n    int hostIdMatch = 0;\n    int readLen = 0;\n    int tryOldLockPath = 0;\n    int forceNewLockPath = 0;\n    \n    OSTRACE((\"TAKECONCH  %d for %s pid=%d\\n\", conchFile->h,\n             (pCtx->lockProxyPath ? pCtx->lockProxyPath : \":auto:\"), getpid()));\n\n    rc = proxyGetHostID(myHostID, &pError);\n    if( (rc&0xff)==SQLITE_IOERR ){\n      pFile->lastErrno = pError;\n      goto end_takeconch;\n    }\n    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);\n    if( rc!=SQLITE_OK ){\n      goto end_takeconch;\n    }\n    /* read the existing conch file */\n    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);\n    if( readLen<0 ){\n      /* I/O error: lastErrno set by seekAndRead */\n      pFile->lastErrno = conchFile->lastErrno;\n      rc = SQLITE_IOERR_READ;\n      goto end_takeconch;\n    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || \n             readBuf[0]!=(char)PROXY_CONCHVERSION ){\n      /* a short read or version format mismatch means we need to create a new \n      ** conch file. \n      */\n      createConch = 1;\n    }\n    /* if the host id matches and the lock path already exists in the conch\n    ** we'll try to use the path there, if we can't open that path, we'll \n    ** retry with a new auto-generated path \n    */\n    do { /* in case we need to try again for an :auto: named lock file */\n\n      if( !createConch && !forceNewLockPath ){\n        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, \n                                  PROXY_HOSTIDLEN);\n        /* if the conch has data compare the contents */\n        if( !pCtx->lockProxyPath ){\n          /* for auto-named local lock file, just check the host ID and we'll\n           ** use the local lock file path that's already in there\n           */\n          if( hostIdMatch ){\n            size_t pathLen = (readLen - PROXY_PATHINDEX);\n            \n            if( pathLen>=MAXPATHLEN ){\n              pathLen=MAXPATHLEN-1;\n            }\n            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);\n            lockPath[pathLen] = 0;\n            tempLockPath = lockPath;\n            tryOldLockPath = 1;\n            /* create a copy of the lock path if the conch is taken */\n            goto end_takeconch;\n          }\n        }else if( hostIdMatch\n               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],\n                           readLen-PROXY_PATHINDEX)\n        ){\n          /* conch host and lock path match */\n          goto end_takeconch; \n        }\n      }\n      \n      /* if the conch isn't writable and doesn't match, we can't take it */\n      if( (conchFile->openFlags&O_RDWR) == 0 ){\n        rc = SQLITE_BUSY;\n        goto end_takeconch;\n      }\n      \n      /* either the conch didn't match or we need to create a new one */\n      if( !pCtx->lockProxyPath ){\n        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);\n        tempLockPath = lockPath;\n        /* create a copy of the lock path _only_ if the conch is taken */\n      }\n      \n      /* update conch with host and path (this will fail if other process\n      ** has a shared lock already), if the host id matches, use the big\n      ** stick.\n      */\n      futimes(conchFile->h, NULL);\n      if( hostIdMatch && !createConch ){\n        if( conchFile->pInode && conchFile->pInode->nShared>1 ){\n          /* We are trying for an exclusive lock but another thread in this\n           ** same process is still holding a shared lock. */\n          rc = SQLITE_BUSY;\n        } else {          \n          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);\n        }\n      }else{\n        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);\n      }\n      if( rc==SQLITE_OK ){\n        char writeBuffer[PROXY_MAXCONCHLEN];\n        int writeSize = 0;\n        \n        writeBuffer[0] = (char)PROXY_CONCHVERSION;\n        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);\n        if( pCtx->lockProxyPath!=NULL ){\n          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);\n        }else{\n          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);\n        }\n        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);\n        robust_ftruncate(conchFile->h, writeSize);\n        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);\n        fsync(conchFile->h);\n        /* If we created a new conch file (not just updated the contents of a \n         ** valid conch file), try to match the permissions of the database \n         */\n        if( rc==SQLITE_OK && createConch ){\n          struct stat buf;\n          int err = osFstat(pFile->h, &buf);\n          if( err==0 ){\n            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |\n                                        S_IROTH|S_IWOTH);\n            /* try to match the database file R/W permissions, ignore failure */\n#ifndef SQLITE_PROXY_DEBUG\n            osFchmod(conchFile->h, cmode);\n#else\n            do{\n              rc = osFchmod(conchFile->h, cmode);\n            }while( rc==(-1) && errno==EINTR );\n            if( rc!=0 ){\n              int code = errno;\n              fprintf(stderr, \"fchmod %o FAILED with %d %s\\n\",\n                      cmode, code, strerror(code));\n            } else {\n              fprintf(stderr, \"fchmod %o SUCCEDED\\n\",cmode);\n            }\n          }else{\n            int code = errno;\n            fprintf(stderr, \"STAT FAILED[%d] with %d %s\\n\", \n                    err, code, strerror(code));\n#endif\n          }\n        }\n      }\n      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);\n      \n    end_takeconch:\n      OSTRACE((\"TRANSPROXY: CLOSE  %d\\n\", pFile->h));\n      if( rc==SQLITE_OK && pFile->openFlags ){\n        int fd;\n        if( pFile->h>=0 ){\n          robust_close(pFile, pFile->h, __LINE__);\n        }\n        pFile->h = -1;\n        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);\n        OSTRACE((\"TRANSPROXY: OPEN  %d\\n\", fd));\n        if( fd>=0 ){\n          pFile->h = fd;\n        }else{\n          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called\n           during locking */\n        }\n      }\n      if( rc==SQLITE_OK && !pCtx->lockProxy ){\n        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;\n        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);\n        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){\n          /* we couldn't create the proxy lock file with the old lock file path\n           ** so try again via auto-naming \n           */\n          forceNewLockPath = 1;\n          tryOldLockPath = 0;\n          continue; /* go back to the do {} while start point, try again */\n        }\n      }\n      if( rc==SQLITE_OK ){\n        /* Need to make a copy of path if we extracted the value\n         ** from the conch file or the path was allocated on the stack\n         */\n        if( tempLockPath ){\n          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);\n          if( !pCtx->lockProxyPath ){\n            rc = SQLITE_NOMEM;\n          }\n        }\n      }\n      if( rc==SQLITE_OK ){\n        pCtx->conchHeld = 1;\n        \n        if( pCtx->lockProxy->pMethod == &afpIoMethods ){\n          afpLockingContext *afpCtx;\n          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;\n          afpCtx->dbPath = pCtx->lockProxyPath;\n        }\n      } else {\n        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);\n      }\n      OSTRACE((\"TAKECONCH  %d %s\\n\", conchFile->h,\n               rc==SQLITE_OK?\"ok\":\"failed\"));\n      return rc;\n    } while (1); /* in case we need to retry the :auto: lock file - \n                 ** we should never get here except via the 'continue' call. */\n  }\n}\n\n/*\n** If pFile holds a lock on a conch file, then release that lock.\n*/\nstatic int proxyReleaseConch(unixFile *pFile){\n  int rc = SQLITE_OK;         /* Subroutine return code */\n  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */\n  unixFile *conchFile;        /* Name of the conch file */\n\n  pCtx = (proxyLockingContext *)pFile->lockingContext;\n  conchFile = pCtx->conchFile;\n  OSTRACE((\"RELEASECONCH  %d for %s pid=%d\\n\", conchFile->h,\n           (pCtx->lockProxyPath ? pCtx->lockProxyPath : \":auto:\"), \n           getpid()));\n  if( pCtx->conchHeld>0 ){\n    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);\n  }\n  pCtx->conchHeld = 0;\n  OSTRACE((\"RELEASECONCH  %d %s\\n\", conchFile->h,\n           (rc==SQLITE_OK ? \"ok\" : \"failed\")));\n  return rc;\n}\n\n/*\n** Given the name of a database file, compute the name of its conch file.\n** Store the conch filename in memory obtained from sqlite3_malloc().\n** Make *pConchPath point to the new name.  Return SQLITE_OK on success\n** or SQLITE_NOMEM if unable to obtain memory.\n**\n** The caller is responsible for ensuring that the allocated memory\n** space is eventually freed.\n**\n** *pConchPath is set to NULL if a memory allocation error occurs.\n*/\nstatic int proxyCreateConchPathname(char *dbPath, char **pConchPath){\n  int i;                        /* Loop counter */\n  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */\n  char *conchPath;              /* buffer in which to construct conch name */\n\n  /* Allocate space for the conch filename and initialize the name to\n  ** the name of the original database file. */  \n  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);\n  if( conchPath==0 ){\n    return SQLITE_NOMEM;\n  }\n  memcpy(conchPath, dbPath, len+1);\n  \n  /* now insert a \".\" before the last / character */\n  for( i=(len-1); i>=0; i-- ){\n    if( conchPath[i]=='/' ){\n      i++;\n      break;\n    }\n  }\n  conchPath[i]='.';\n  while ( i<len ){\n    conchPath[i+1]=dbPath[i];\n    i++;\n  }\n\n  /* append the \"-conch\" suffix to the file */\n  memcpy(&conchPath[i+1], \"-conch\", 7);\n  assert( (int)strlen(conchPath) == len+7 );\n\n  return SQLITE_OK;\n}\n\n\n/* Takes a fully configured proxy locking-style unix file and switches\n** the local lock file path \n*/\nstatic int switchLockProxyPath(unixFile *pFile, const char *path) {\n  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;\n  char *oldPath = pCtx->lockProxyPath;\n  int rc = SQLITE_OK;\n\n  if( pFile->eFileLock!=NO_LOCK ){\n    return SQLITE_BUSY;\n  }  \n\n  /* nothing to do if the path is NULL, :auto: or matches the existing path */\n  if( !path || path[0]=='\\0' || !strcmp(path, \":auto:\") ||\n    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){\n    return SQLITE_OK;\n  }else{\n    unixFile *lockProxy = pCtx->lockProxy;\n    pCtx->lockProxy=NULL;\n    pCtx->conchHeld = 0;\n    if( lockProxy!=NULL ){\n      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);\n      if( rc ) return rc;\n      sqlite3_free(lockProxy);\n    }\n    sqlite3_free(oldPath);\n    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);\n  }\n  \n  return rc;\n}\n\n/*\n** pFile is a file that has been opened by a prior xOpen call.  dbPath\n** is a string buffer at least MAXPATHLEN+1 characters in size.\n**\n** This routine find the filename associated with pFile and writes it\n** int dbPath.\n*/\nstatic int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){\n#if defined(__APPLE__)\n  if( pFile->pMethod == &afpIoMethods ){\n    /* afp style keeps a reference to the db path in the filePath field \n    ** of the struct */\n    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );\n    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);\n  } else\n#endif\n  if( pFile->pMethod == &dotlockIoMethods ){\n    /* dot lock style uses the locking context to store the dot lock\n    ** file path */\n    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);\n    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);\n  }else{\n    /* all other styles use the locking context to store the db file path */\n    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );\n    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Takes an already filled in unix file and alters it so all file locking \n** will be performed on the local proxy lock file.  The following fields\n** are preserved in the locking context so that they can be restored and \n** the unix structure properly cleaned up at close time:\n**  ->lockingContext\n**  ->pMethod\n*/\nstatic int proxyTransformUnixFile(unixFile *pFile, const char *path) {\n  proxyLockingContext *pCtx;\n  char dbPath[MAXPATHLEN+1];       /* Name of the database file */\n  char *lockPath=NULL;\n  int rc = SQLITE_OK;\n  \n  if( pFile->eFileLock!=NO_LOCK ){\n    return SQLITE_BUSY;\n  }\n  proxyGetDbPathForUnixFile(pFile, dbPath);\n  if( !path || path[0]=='\\0' || !strcmp(path, \":auto:\") ){\n    lockPath=NULL;\n  }else{\n    lockPath=(char *)path;\n  }\n  \n  OSTRACE((\"TRANSPROXY  %d for %s pid=%d\\n\", pFile->h,\n           (lockPath ? lockPath : \":auto:\"), getpid()));\n\n  pCtx = sqlite3_malloc( sizeof(*pCtx) );\n  if( pCtx==0 ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCtx, 0, sizeof(*pCtx));\n\n  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);\n  if( rc==SQLITE_OK ){\n    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);\n    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){\n      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and\n      ** (c) the file system is read-only, then enable no-locking access.\n      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts\n      ** that openFlags will have only one of O_RDONLY or O_RDWR.\n      */\n      struct statfs fsInfo;\n      struct stat conchInfo;\n      int goLockless = 0;\n\n      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {\n        int err = errno;\n        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){\n          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;\n        }\n      }\n      if( goLockless ){\n        pCtx->conchHeld = -1; /* read only FS/ lockless */\n        rc = SQLITE_OK;\n      }\n    }\n  }  \n  if( rc==SQLITE_OK && lockPath ){\n    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);\n  }\n\n  if( rc==SQLITE_OK ){\n    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);\n    if( pCtx->dbPath==NULL ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n  if( rc==SQLITE_OK ){\n    /* all memory is allocated, proxys are created and assigned, \n    ** switch the locking context and pMethod then return.\n    */\n    pCtx->oldLockingContext = pFile->lockingContext;\n    pFile->lockingContext = pCtx;\n    pCtx->pOldMethod = pFile->pMethod;\n    pFile->pMethod = &proxyIoMethods;\n  }else{\n    if( pCtx->conchFile ){ \n      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);\n      sqlite3_free(pCtx->conchFile);\n    }\n    sqlite3DbFree(0, pCtx->lockProxyPath);\n    sqlite3_free(pCtx->conchFilePath); \n    sqlite3_free(pCtx);\n  }\n  OSTRACE((\"TRANSPROXY  %d %s\\n\", pFile->h,\n           (rc==SQLITE_OK ? \"ok\" : \"failed\")));\n  return rc;\n}\n\n\n/*\n** This routine handles sqlite3_file_control() calls that are specific\n** to proxy locking.\n*/\nstatic int proxyFileControl(sqlite3_file *id, int op, void *pArg){\n  switch( op ){\n    case SQLITE_GET_LOCKPROXYFILE: {\n      unixFile *pFile = (unixFile*)id;\n      if( pFile->pMethod == &proxyIoMethods ){\n        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;\n        proxyTakeConch(pFile);\n        if( pCtx->lockProxyPath ){\n          *(const char **)pArg = pCtx->lockProxyPath;\n        }else{\n          *(const char **)pArg = \":auto: (not held)\";\n        }\n      } else {\n        *(const char **)pArg = NULL;\n      }\n      return SQLITE_OK;\n    }\n    case SQLITE_SET_LOCKPROXYFILE: {\n      unixFile *pFile = (unixFile*)id;\n      int rc = SQLITE_OK;\n      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);\n      if( pArg==NULL || (const char *)pArg==0 ){\n        if( isProxyStyle ){\n          /* turn off proxy locking - not supported */\n          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;\n        }else{\n          /* turn off proxy locking - already off - NOOP */\n          rc = SQLITE_OK;\n        }\n      }else{\n        const char *proxyPath = (const char *)pArg;\n        if( isProxyStyle ){\n          proxyLockingContext *pCtx = \n            (proxyLockingContext*)pFile->lockingContext;\n          if( !strcmp(pArg, \":auto:\") \n           || (pCtx->lockProxyPath &&\n               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))\n          ){\n            rc = SQLITE_OK;\n          }else{\n            rc = switchLockProxyPath(pFile, proxyPath);\n          }\n        }else{\n          /* turn on proxy file locking */\n          rc = proxyTransformUnixFile(pFile, proxyPath);\n        }\n      }\n      return rc;\n    }\n    default: {\n      assert( 0 );  /* The call assures that only valid opcodes are sent */\n    }\n  }\n  /*NOTREACHED*/\n  return SQLITE_ERROR;\n}\n\n/*\n** Within this division (the proxying locking implementation) the procedures\n** above this point are all utilities.  The lock-related methods of the\n** proxy-locking sqlite3_io_method object follow.\n*/\n\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, set *pResOut\n** to a non-zero value otherwise *pResOut is set to zero.  The return value\n** is set to SQLITE_OK unless an I/O error occurs during lock checking.\n*/\nstatic int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);\n    }else{ /* conchHeld < 0 is lockless */\n      pResOut=0;\n    }\n  }\n  return rc;\n}\n\n/*\n** Lock the file with the lock specified by parameter eFileLock - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  Use the sqlite3OsUnlock()\n** routine to lower a locking level.\n*/\nstatic int proxyLock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);\n      pFile->eFileLock = proxy->eFileLock;\n    }else{\n      /* conchHeld < 0 is lockless */\n    }\n  }\n  return rc;\n}\n\n\n/*\n** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n*/\nstatic int proxyUnlock(sqlite3_file *id, int eFileLock) {\n  unixFile *pFile = (unixFile*)id;\n  int rc = proxyTakeConch(pFile);\n  if( rc==SQLITE_OK ){\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    if( pCtx->conchHeld>0 ){\n      unixFile *proxy = pCtx->lockProxy;\n      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);\n      pFile->eFileLock = proxy->eFileLock;\n    }else{\n      /* conchHeld < 0 is lockless */\n    }\n  }\n  return rc;\n}\n\n/*\n** Close a file that uses proxy locks.\n*/\nstatic int proxyClose(sqlite3_file *id) {\n  if( id ){\n    unixFile *pFile = (unixFile*)id;\n    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;\n    unixFile *lockProxy = pCtx->lockProxy;\n    unixFile *conchFile = pCtx->conchFile;\n    int rc = SQLITE_OK;\n    \n    if( lockProxy ){\n      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);\n      if( rc ) return rc;\n      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);\n      if( rc ) return rc;\n      sqlite3_free(lockProxy);\n      pCtx->lockProxy = 0;\n    }\n    if( conchFile ){\n      if( pCtx->conchHeld ){\n        rc = proxyReleaseConch(pFile);\n        if( rc ) return rc;\n      }\n      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);\n      if( rc ) return rc;\n      sqlite3_free(conchFile);\n    }\n    sqlite3DbFree(0, pCtx->lockProxyPath);\n    sqlite3_free(pCtx->conchFilePath);\n    sqlite3DbFree(0, pCtx->dbPath);\n    /* restore the original locking context and pMethod then close it */\n    pFile->lockingContext = pCtx->oldLockingContext;\n    pFile->pMethod = pCtx->pOldMethod;\n    sqlite3_free(pCtx);\n    return pFile->pMethod->xClose(id);\n  }\n  return SQLITE_OK;\n}\n\n\n\n#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */\n/*\n** The proxy locking style is intended for use with AFP filesystems.\n** And since AFP is only supported on MacOSX, the proxy locking is also\n** restricted to MacOSX.\n** \n**\n******************* End of the proxy lock implementation **********************\n******************************************************************************/\n\n/*\n** Initialize the operating system interface.\n**\n** This routine registers all VFS implementations for unix-like operating\n** systems.  This routine, and the sqlite3_os_end() routine that follows,\n** should be the only routines in this file that are visible from other\n** files.\n**\n** This routine is called once during SQLite initialization and by a\n** single thread.  The memory allocation and mutex subsystems have not\n** necessarily been initialized when this routine is called, and so they\n** should not be used.\n*/\nSQLITE_API int sqlite3_os_init(void){ \n  /* \n  ** The following macro defines an initializer for an sqlite3_vfs object.\n  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer\n  ** to the \"finder\" function.  (pAppData is a pointer to a pointer because\n  ** silly C90 rules prohibit a void* from being cast to a function pointer\n  ** and so we have to go through the intermediate pointer to avoid problems\n  ** when compiling with -pedantic-errors on GCC.)\n  **\n  ** The FINDER parameter to this macro is the name of the pointer to the\n  ** finder-function.  The finder-function returns a pointer to the\n  ** sqlite_io_methods object that implements the desired locking\n  ** behaviors.  See the division above that contains the IOMETHODS\n  ** macro for addition information on finder-functions.\n  **\n  ** Most finders simply return a pointer to a fixed sqlite3_io_methods\n  ** object.  But the \"autolockIoFinder\" available on MacOSX does a little\n  ** more than that; it looks at the filesystem type that hosts the \n  ** database file and tries to choose an locking method appropriate for\n  ** that filesystem time.\n  */\n  #define UNIXVFS(VFSNAME, FINDER) {                        \\\n    3,                    /* iVersion */                    \\\n    sizeof(unixFile),     /* szOsFile */                    \\\n    MAX_PATHNAME,         /* mxPathname */                  \\\n    0,                    /* pNext */                       \\\n    VFSNAME,              /* zName */                       \\\n    (void*)&FINDER,       /* pAppData */                    \\\n    unixOpen,             /* xOpen */                       \\\n    unixDelete,           /* xDelete */                     \\\n    unixAccess,           /* xAccess */                     \\\n    unixFullPathname,     /* xFullPathname */               \\\n    unixDlOpen,           /* xDlOpen */                     \\\n    unixDlError,          /* xDlError */                    \\\n    unixDlSym,            /* xDlSym */                      \\\n    unixDlClose,          /* xDlClose */                    \\\n    unixRandomness,       /* xRandomness */                 \\\n    unixSleep,            /* xSleep */                      \\\n    unixCurrentTime,      /* xCurrentTime */                \\\n    unixGetLastError,     /* xGetLastError */               \\\n    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \\\n    unixSetSystemCall,    /* xSetSystemCall */              \\\n    unixGetSystemCall,    /* xGetSystemCall */              \\\n    unixNextSystemCall,   /* xNextSystemCall */             \\\n  }\n\n  /*\n  ** All default VFSes for unix are contained in the following array.\n  **\n  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified\n  ** by the SQLite core when the VFS is registered.  So the following\n  ** array cannot be const.\n  */\n  static sqlite3_vfs aVfs[] = {\n#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))\n    UNIXVFS(\"unix\",          autolockIoFinder ),\n#else\n    UNIXVFS(\"unix\",          posixIoFinder ),\n#endif\n    UNIXVFS(\"unix-none\",     nolockIoFinder ),\n    UNIXVFS(\"unix-dotfile\",  dotlockIoFinder ),\n    UNIXVFS(\"unix-excl\",     posixIoFinder ),\n#if OS_VXWORKS\n    UNIXVFS(\"unix-namedsem\", semIoFinder ),\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE\n    UNIXVFS(\"unix-posix\",    posixIoFinder ),\n#if !OS_VXWORKS\n    UNIXVFS(\"unix-flock\",    flockIoFinder ),\n#endif\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)\n    UNIXVFS(\"unix-afp\",      afpIoFinder ),\n    UNIXVFS(\"unix-nfs\",      nfsIoFinder ),\n    UNIXVFS(\"unix-proxy\",    proxyIoFinder ),\n#endif\n  };\n  unsigned int i;          /* Loop counter */\n\n  /* Double-check that the aSyscall[] array has been constructed\n  ** correctly.  See ticket [bb3a86e890c8e96ab] */\n  assert( ArraySize(aSyscall)==22 );\n\n  /* Register all VFSes defined in the aVfs[] array */\n  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){\n    sqlite3_vfs_register(&aVfs[i], i==0);\n  }\n  return SQLITE_OK; \n}\n\n/*\n** Shutdown the operating system interface.\n**\n** Some operating systems might need to do some cleanup in this routine,\n** to release dynamically allocated objects.  But not on unix.\n** This routine is a no-op for unix.\n*/\nSQLITE_API int sqlite3_os_end(void){ \n  return SQLITE_OK; \n}\n \n#endif /* SQLITE_OS_UNIX */\n\n/************** End of os_unix.c *********************************************/\n/************** Begin file os_win.c ******************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains code that is specific to Windows.\n*/\n#if SQLITE_OS_WIN               /* This file is used for Windows only */\n\n#ifdef __CYGWIN__\n# include <sys/cygwin.h>\n#endif\n\n/*\n** Include code that is common to all os_*.c files\n*/\n/************** Include os_common.h in the middle of os_win.c ****************/\n/************** Begin file os_common.h ***************************************/\n/*\n** 2004 May 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains macros and a little bit of code that is common to\n** all of the platform-specific files (os_*.c) and is #included into those\n** files.\n**\n** This file should be #included by the os_*.c files only.  It is not a\n** general purpose header file.\n*/\n#ifndef _OS_COMMON_H_\n#define _OS_COMMON_H_\n\n/*\n** At least two bugs have slipped in because we changed the MEMORY_DEBUG\n** macro to SQLITE_DEBUG and some older makefiles have not yet made the\n** switch.  The following code should catch this problem at compile-time.\n*/\n#ifdef MEMORY_DEBUG\n# error \"The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead.\"\n#endif\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n# ifndef SQLITE_DEBUG_OS_TRACE\n#   define SQLITE_DEBUG_OS_TRACE 0\n# endif\n  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;\n# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X\n#else\n# define OSTRACE(X)\n#endif\n\n/*\n** Macros for performance tracing.  Normally turned off.  Only works\n** on i486 hardware.\n*/\n#ifdef SQLITE_PERFORMANCE_TRACE\n\n/* \n** hwtime.h contains inline assembler code for implementing \n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of os_common.h ****************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 class CPUs.\n*/\n#ifndef _HWTIME_H_\n#define _HWTIME_H_\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if (defined(__GNUC__) || defined(_MSC_VER)) && \\\n      (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  #error Need implementation of sqlite3Hwtime() for your platform.\n\n  /*\n  ** To compile without implementing sqlite3Hwtime() for your platform,\n  ** you can remove the above #error and use the following\n  ** stub function.  You will lose timing support for many\n  ** of the debugging and testing utilities, but it should at\n  ** least compile and run.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(_HWTIME_H_) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in os_common.h ******************/\n\nstatic sqlite_uint64 g_start;\nstatic sqlite_uint64 g_elapsed;\n#define TIMER_START       g_start=sqlite3Hwtime()\n#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start\n#define TIMER_ELAPSED     g_elapsed\n#else\n#define TIMER_START\n#define TIMER_END\n#define TIMER_ELAPSED     ((sqlite_uint64)0)\n#endif\n\n/*\n** If we compile with the SQLITE_TEST macro set, then the following block\n** of code will give us the ability to simulate a disk I/O error.  This\n** is used for testing the I/O recovery logic.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */\nSQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */\nSQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */\nSQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */\nSQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */\nSQLITE_API int sqlite3_diskfull_pending = 0;\nSQLITE_API int sqlite3_diskfull = 0;\n#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)\n#define SimulateIOError(CODE)  \\\n  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \\\n       || sqlite3_io_error_pending-- == 1 )  \\\n              { local_ioerr(); CODE; }\nstatic void local_ioerr(){\n  IOTRACE((\"IOERR\\n\"));\n  sqlite3_io_error_hit++;\n  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;\n}\n#define SimulateDiskfullError(CODE) \\\n   if( sqlite3_diskfull_pending ){ \\\n     if( sqlite3_diskfull_pending == 1 ){ \\\n       local_ioerr(); \\\n       sqlite3_diskfull = 1; \\\n       sqlite3_io_error_hit = 1; \\\n       CODE; \\\n     }else{ \\\n       sqlite3_diskfull_pending--; \\\n     } \\\n   }\n#else\n#define SimulateIOErrorBenign(X)\n#define SimulateIOError(A)\n#define SimulateDiskfullError(A)\n#endif\n\n/*\n** When testing, keep a count of the number of open files.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_open_file_count = 0;\n#define OpenCounter(X)  sqlite3_open_file_count+=(X)\n#else\n#define OpenCounter(X)\n#endif\n\n#endif /* !defined(_OS_COMMON_H_) */\n\n/************** End of os_common.h *******************************************/\n/************** Continuing where we left off in os_win.c *********************/\n\n/*\n** Macro to find the minimum of two numeric values.\n*/\n#ifndef MIN\n# define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n\n/*\n** Some Microsoft compilers lack this definition.\n*/\n#ifndef INVALID_FILE_ATTRIBUTES\n# define INVALID_FILE_ATTRIBUTES ((DWORD)-1) \n#endif\n\n#ifndef FILE_FLAG_MASK\n# define FILE_FLAG_MASK          (0xFF3C0000)\n#endif\n\n#ifndef FILE_ATTRIBUTE_MASK\n# define FILE_ATTRIBUTE_MASK     (0x0003FFF7)\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n/* Forward references */\ntypedef struct winShm winShm;           /* A connection to shared-memory */\ntypedef struct winShmNode winShmNode;   /* A region of shared-memory */\n#endif\n\n/*\n** WinCE lacks native support for file locking so we have to fake it\n** with some code of our own.\n*/\n#if SQLITE_OS_WINCE\ntypedef struct winceLock {\n  int nReaders;       /* Number of reader locks obtained */\n  BOOL bPending;      /* Indicates a pending lock has been obtained */\n  BOOL bReserved;     /* Indicates a reserved lock has been obtained */\n  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */\n} winceLock;\n#endif\n\n/*\n** The winFile structure is a subclass of sqlite3_file* specific to the win32\n** portability layer.\n*/\ntypedef struct winFile winFile;\nstruct winFile {\n  const sqlite3_io_methods *pMethod; /*** Must be first ***/\n  sqlite3_vfs *pVfs;      /* The VFS used to open this file */\n  HANDLE h;               /* Handle for accessing the file */\n  u8 locktype;            /* Type of lock currently held on this file */\n  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */\n  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */\n  DWORD lastErrno;        /* The Windows errno from the last I/O error */\n#ifndef SQLITE_OMIT_WAL\n  winShm *pShm;           /* Instance of shared memory on this file */\n#endif\n  const char *zPath;      /* Full pathname of this file */\n  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */\n#if SQLITE_OS_WINCE\n  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */\n  HANDLE hMutex;          /* Mutex used to control access to shared lock */  \n  HANDLE hShared;         /* Shared memory segment used for locking */\n  winceLock local;        /* Locks obtained by this instance of winFile */\n  winceLock *shared;      /* Global shared lock memory for the file  */\n#endif\n};\n\n/*\n** Allowed values for winFile.ctrlFlags\n*/\n#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */\n#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */\n\n/*\n * The size of the buffer used by sqlite3_win32_write_debug().\n */\n#ifndef SQLITE_WIN32_DBG_BUF_SIZE\n#  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))\n#endif\n\n/*\n * The value used with sqlite3_win32_set_directory() to specify that\n * the data directory should be changed.\n */\n#ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE\n#  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)\n#endif\n\n/*\n * The value used with sqlite3_win32_set_directory() to specify that\n * the temporary directory should be changed.\n */\n#ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE\n#  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)\n#endif\n\n/*\n * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the\n * various Win32 API heap functions instead of our own.\n */\n#ifdef SQLITE_WIN32_MALLOC\n\n/*\n * If this is non-zero, an isolated heap will be created by the native Win32\n * allocator subsystem; otherwise, the default process heap will be used.  This\n * setting has no effect when compiling for WinRT.  By default, this is enabled\n * and an isolated heap will be created to store all allocated data.\n *\n ******************************************************************************\n * WARNING: It is important to note that when this setting is non-zero and the\n *          winMemShutdown function is called (e.g. by the sqlite3_shutdown\n *          function), all data that was allocated using the isolated heap will\n *          be freed immediately and any attempt to access any of that freed\n *          data will almost certainly result in an immediate access violation.\n ******************************************************************************\n */\n#ifndef SQLITE_WIN32_HEAP_CREATE\n#  define SQLITE_WIN32_HEAP_CREATE    (TRUE)\n#endif\n\n/*\n * The initial size of the Win32-specific heap.  This value may be zero.\n */\n#ifndef SQLITE_WIN32_HEAP_INIT_SIZE\n#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \\\n                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)\n#endif\n\n/*\n * The maximum size of the Win32-specific heap.  This value may be zero.\n */\n#ifndef SQLITE_WIN32_HEAP_MAX_SIZE\n#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)\n#endif\n\n/*\n * The extra flags to use in calls to the Win32 heap APIs.  This value may be\n * zero for the default behavior.\n */\n#ifndef SQLITE_WIN32_HEAP_FLAGS\n#  define SQLITE_WIN32_HEAP_FLAGS     (0)\n#endif\n\n/*\n** The winMemData structure stores information required by the Win32-specific\n** sqlite3_mem_methods implementation.\n*/\ntypedef struct winMemData winMemData;\nstruct winMemData {\n#ifndef NDEBUG\n  u32 magic;    /* Magic number to detect structure corruption. */\n#endif\n  HANDLE hHeap; /* The handle to our heap. */\n  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */\n};\n\n#ifndef NDEBUG\n#define WINMEM_MAGIC     0x42b2830b\n#endif\n\nstatic struct winMemData win_mem_data = {\n#ifndef NDEBUG\n  WINMEM_MAGIC,\n#endif\n  NULL, FALSE\n};\n\n#ifndef NDEBUG\n#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )\n#else\n#define winMemAssertMagic()\n#endif\n\n#define winMemGetHeap() win_mem_data.hHeap\n\nstatic void *winMemMalloc(int nBytes);\nstatic void winMemFree(void *pPrior);\nstatic void *winMemRealloc(void *pPrior, int nBytes);\nstatic int winMemSize(void *p);\nstatic int winMemRoundup(int n);\nstatic int winMemInit(void *pAppData);\nstatic void winMemShutdown(void *pAppData);\n\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);\n#endif /* SQLITE_WIN32_MALLOC */\n\n/*\n** The following variable is (normally) set once and never changes\n** thereafter.  It records whether the operating system is Win9x\n** or WinNT.\n**\n** 0:   Operating system unknown.\n** 1:   Operating system is Win9x.\n** 2:   Operating system is WinNT.\n**\n** In order to facilitate testing on a WinNT system, the test fixture\n** can manually set this value to 1 to emulate Win98 behavior.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_os_type = 0;\n#else\nstatic int sqlite3_os_type = 0;\n#endif\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n#  define SQLITE_WIN32_HAS_ANSI\n#endif\n\n#if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT\n#  define SQLITE_WIN32_HAS_WIDE\n#endif\n\n#ifndef SYSCALL\n#  define SYSCALL sqlite3_syscall_ptr\n#endif\n\n/*\n** This function is not available on Windows CE or WinRT.\n */\n\n#if SQLITE_OS_WINCE || SQLITE_OS_WINRT\n#  define osAreFileApisANSI()       1\n#endif\n\n/*\n** Many system calls are accessed through pointer-to-functions so that\n** they may be overridden at runtime to facilitate fault injection during\n** testing and sandboxing.  The following array holds the names and pointers\n** to all overrideable system calls.\n*/\nstatic struct win_syscall {\n  const char *zName;            /* Name of the sytem call */\n  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */\n  sqlite3_syscall_ptr pDefault; /* Default value */\n} aSyscall[] = {\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"AreFileApisANSI\",         (SYSCALL)AreFileApisANSI,         0 },\n#else\n  { \"AreFileApisANSI\",         (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osAreFileApisANSI\n#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)\n#endif\n\n#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CharLowerW\",              (SYSCALL)CharLowerW,              0 },\n#else\n  { \"CharLowerW\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)\n\n#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CharUpperW\",              (SYSCALL)CharUpperW,              0 },\n#else\n  { \"CharUpperW\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)\n\n  { \"CloseHandle\",             (SYSCALL)CloseHandle,             0 },\n\n#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"CreateFileA\",             (SYSCALL)CreateFileA,             0 },\n#else\n  { \"CreateFileA\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \\\n        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CreateFileW\",             (SYSCALL)CreateFileW,             0 },\n#else\n  { \"CreateFileW\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \\\n        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)\n\n#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \\\n        !defined(SQLITE_OMIT_WAL))\n  { \"CreateFileMappingW\",      (SYSCALL)CreateFileMappingW,      0 },\n#else\n  { \"CreateFileMappingW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \\\n        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[6].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"CreateMutexW\",            (SYSCALL)CreateMutexW,            0 },\n#else\n  { \"CreateMutexW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \\\n        LPCWSTR))aSyscall[7].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"DeleteFileA\",             (SYSCALL)DeleteFileA,             0 },\n#else\n  { \"DeleteFileA\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[8].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"DeleteFileW\",             (SYSCALL)DeleteFileW,             0 },\n#else\n  { \"DeleteFileW\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[9].pCurrent)\n\n#if SQLITE_OS_WINCE\n  { \"FileTimeToLocalFileTime\", (SYSCALL)FileTimeToLocalFileTime, 0 },\n#else\n  { \"FileTimeToLocalFileTime\", (SYSCALL)0,                       0 },\n#endif\n\n#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \\\n        LPFILETIME))aSyscall[10].pCurrent)\n\n#if SQLITE_OS_WINCE\n  { \"FileTimeToSystemTime\",    (SYSCALL)FileTimeToSystemTime,    0 },\n#else\n  { \"FileTimeToSystemTime\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \\\n        LPSYSTEMTIME))aSyscall[11].pCurrent)\n\n  { \"FlushFileBuffers\",        (SYSCALL)FlushFileBuffers,        0 },\n\n#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[12].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"FormatMessageA\",          (SYSCALL)FormatMessageA,          0 },\n#else\n  { \"FormatMessageA\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \\\n        DWORD,va_list*))aSyscall[13].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"FormatMessageW\",          (SYSCALL)FormatMessageW,          0 },\n#else\n  { \"FormatMessageW\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \\\n        DWORD,va_list*))aSyscall[14].pCurrent)\n\n  { \"FreeLibrary\",             (SYSCALL)FreeLibrary,             0 },\n\n#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[15].pCurrent)\n\n  { \"GetCurrentProcessId\",     (SYSCALL)GetCurrentProcessId,     0 },\n\n#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[16].pCurrent)\n\n#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetDiskFreeSpaceA\",       (SYSCALL)GetDiskFreeSpaceA,       0 },\n#else\n  { \"GetDiskFreeSpaceA\",       (SYSCALL)0,                       0 },\n#endif\n\n#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \\\n        LPDWORD))aSyscall[17].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetDiskFreeSpaceW\",       (SYSCALL)GetDiskFreeSpaceW,       0 },\n#else\n  { \"GetDiskFreeSpaceW\",       (SYSCALL)0,                       0 },\n#endif\n\n#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \\\n        LPDWORD))aSyscall[18].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetFileAttributesA\",      (SYSCALL)GetFileAttributesA,      0 },\n#else\n  { \"GetFileAttributesA\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[19].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFileAttributesW\",      (SYSCALL)GetFileAttributesW,      0 },\n#else\n  { \"GetFileAttributesW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[20].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFileAttributesExW\",    (SYSCALL)GetFileAttributesExW,    0 },\n#else\n  { \"GetFileAttributesExW\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \\\n        LPVOID))aSyscall[21].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetFileSize\",             (SYSCALL)GetFileSize,             0 },\n#else\n  { \"GetFileSize\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[22].pCurrent)\n\n#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetFullPathNameA\",        (SYSCALL)GetFullPathNameA,        0 },\n#else\n  { \"GetFullPathNameA\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \\\n        LPSTR*))aSyscall[23].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetFullPathNameW\",        (SYSCALL)GetFullPathNameW,        0 },\n#else\n  { \"GetFullPathNameW\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \\\n        LPWSTR*))aSyscall[24].pCurrent)\n\n  { \"GetLastError\",            (SYSCALL)GetLastError,            0 },\n\n#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[25].pCurrent)\n\n#if SQLITE_OS_WINCE\n  /* The GetProcAddressA() routine is only available on Windows CE. */\n  { \"GetProcAddressA\",         (SYSCALL)GetProcAddressA,         0 },\n#else\n  /* All other Windows platforms expect GetProcAddress() to take\n  ** an ANSI string regardless of the _UNICODE setting */\n  { \"GetProcAddressA\",         (SYSCALL)GetProcAddress,          0 },\n#endif\n\n#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \\\n        LPCSTR))aSyscall[26].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetSystemInfo\",           (SYSCALL)GetSystemInfo,           0 },\n#else\n  { \"GetSystemInfo\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[27].pCurrent)\n\n  { \"GetSystemTime\",           (SYSCALL)GetSystemTime,           0 },\n\n#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[28].pCurrent)\n\n#if !SQLITE_OS_WINCE\n  { \"GetSystemTimeAsFileTime\", (SYSCALL)GetSystemTimeAsFileTime, 0 },\n#else\n  { \"GetSystemTimeAsFileTime\", (SYSCALL)0,                       0 },\n#endif\n\n#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \\\n        LPFILETIME))aSyscall[29].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetTempPathA\",            (SYSCALL)GetTempPathA,            0 },\n#else\n  { \"GetTempPathA\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[30].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"GetTempPathW\",            (SYSCALL)GetTempPathW,            0 },\n#else\n  { \"GetTempPathW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[31].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"GetTickCount\",            (SYSCALL)GetTickCount,            0 },\n#else\n  { \"GetTickCount\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[32].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"GetVersionExA\",           (SYSCALL)GetVersionExA,           0 },\n#else\n  { \"GetVersionExA\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osGetVersionExA ((BOOL(WINAPI*)( \\\n        LPOSVERSIONINFOA))aSyscall[33].pCurrent)\n\n  { \"HeapAlloc\",               (SYSCALL)HeapAlloc,               0 },\n\n#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \\\n        SIZE_T))aSyscall[34].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapCreate\",              (SYSCALL)HeapCreate,              0 },\n#else\n  { \"HeapCreate\",              (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \\\n        SIZE_T))aSyscall[35].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapDestroy\",             (SYSCALL)HeapDestroy,             0 },\n#else\n  { \"HeapDestroy\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[36].pCurrent)\n\n  { \"HeapFree\",                (SYSCALL)HeapFree,                0 },\n\n#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[37].pCurrent)\n\n  { \"HeapReAlloc\",             (SYSCALL)HeapReAlloc,             0 },\n\n#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \\\n        SIZE_T))aSyscall[38].pCurrent)\n\n  { \"HeapSize\",                (SYSCALL)HeapSize,                0 },\n\n#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \\\n        LPCVOID))aSyscall[39].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"HeapValidate\",            (SYSCALL)HeapValidate,            0 },\n#else\n  { \"HeapValidate\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \\\n        LPCVOID))aSyscall[40].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"LoadLibraryA\",            (SYSCALL)LoadLibraryA,            0 },\n#else\n  { \"LoadLibraryA\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[41].pCurrent)\n\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)\n  { \"LoadLibraryW\",            (SYSCALL)LoadLibraryW,            0 },\n#else\n  { \"LoadLibraryW\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[42].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"LocalFree\",               (SYSCALL)LocalFree,               0 },\n#else\n  { \"LocalFree\",               (SYSCALL)0,                       0 },\n#endif\n\n#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[43].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"LockFile\",                (SYSCALL)LockFile,                0 },\n#else\n  { \"LockFile\",                (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osLockFile\n#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        DWORD))aSyscall[44].pCurrent)\n#endif\n\n#if !SQLITE_OS_WINCE\n  { \"LockFileEx\",              (SYSCALL)LockFileEx,              0 },\n#else\n  { \"LockFileEx\",              (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osLockFileEx\n#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \\\n        LPOVERLAPPED))aSyscall[45].pCurrent)\n#endif\n\n#if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))\n  { \"MapViewOfFile\",           (SYSCALL)MapViewOfFile,           0 },\n#else\n  { \"MapViewOfFile\",           (SYSCALL)0,                       0 },\n#endif\n\n#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        SIZE_T))aSyscall[46].pCurrent)\n\n  { \"MultiByteToWideChar\",     (SYSCALL)MultiByteToWideChar,     0 },\n\n#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \\\n        int))aSyscall[47].pCurrent)\n\n  { \"QueryPerformanceCounter\", (SYSCALL)QueryPerformanceCounter, 0 },\n\n#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \\\n        LARGE_INTEGER*))aSyscall[48].pCurrent)\n\n  { \"ReadFile\",                (SYSCALL)ReadFile,                0 },\n\n#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \\\n        LPOVERLAPPED))aSyscall[49].pCurrent)\n\n  { \"SetEndOfFile\",            (SYSCALL)SetEndOfFile,            0 },\n\n#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[50].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"SetFilePointer\",          (SYSCALL)SetFilePointer,          0 },\n#else\n  { \"SetFilePointer\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \\\n        DWORD))aSyscall[51].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"Sleep\",                   (SYSCALL)Sleep,                   0 },\n#else\n  { \"Sleep\",                   (SYSCALL)0,                       0 },\n#endif\n\n#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[52].pCurrent)\n\n  { \"SystemTimeToFileTime\",    (SYSCALL)SystemTimeToFileTime,    0 },\n\n#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \\\n        LPFILETIME))aSyscall[53].pCurrent)\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT\n  { \"UnlockFile\",              (SYSCALL)UnlockFile,              0 },\n#else\n  { \"UnlockFile\",              (SYSCALL)0,                       0 },\n#endif\n\n#ifndef osUnlockFile\n#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        DWORD))aSyscall[54].pCurrent)\n#endif\n\n#if !SQLITE_OS_WINCE\n  { \"UnlockFileEx\",            (SYSCALL)UnlockFileEx,            0 },\n#else\n  { \"UnlockFileEx\",            (SYSCALL)0,                       0 },\n#endif\n\n#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \\\n        LPOVERLAPPED))aSyscall[55].pCurrent)\n\n#if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)\n  { \"UnmapViewOfFile\",         (SYSCALL)UnmapViewOfFile,         0 },\n#else\n  { \"UnmapViewOfFile\",         (SYSCALL)0,                       0 },\n#endif\n\n#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[56].pCurrent)\n\n  { \"WideCharToMultiByte\",     (SYSCALL)WideCharToMultiByte,     0 },\n\n#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \\\n        LPCSTR,LPBOOL))aSyscall[57].pCurrent)\n\n  { \"WriteFile\",               (SYSCALL)WriteFile,               0 },\n\n#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \\\n        LPOVERLAPPED))aSyscall[58].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"CreateEventExW\",          (SYSCALL)CreateEventExW,          0 },\n#else\n  { \"CreateEventExW\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \\\n        DWORD,DWORD))aSyscall[59].pCurrent)\n\n#if !SQLITE_OS_WINRT\n  { \"WaitForSingleObject\",     (SYSCALL)WaitForSingleObject,     0 },\n#else\n  { \"WaitForSingleObject\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \\\n        DWORD))aSyscall[60].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"WaitForSingleObjectEx\",   (SYSCALL)WaitForSingleObjectEx,   0 },\n#else\n  { \"WaitForSingleObjectEx\",   (SYSCALL)0,                       0 },\n#endif\n\n#define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \\\n        BOOL))aSyscall[61].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"SetFilePointerEx\",        (SYSCALL)SetFilePointerEx,        0 },\n#else\n  { \"SetFilePointerEx\",        (SYSCALL)0,                       0 },\n#endif\n\n#define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \\\n        PLARGE_INTEGER,DWORD))aSyscall[62].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetFileInformationByHandleEx\", (SYSCALL)GetFileInformationByHandleEx, 0 },\n#else\n  { \"GetFileInformationByHandleEx\", (SYSCALL)0,                  0 },\n#endif\n\n#define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \\\n        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[63].pCurrent)\n\n#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)\n  { \"MapViewOfFileFromApp\",    (SYSCALL)MapViewOfFileFromApp,    0 },\n#else\n  { \"MapViewOfFileFromApp\",    (SYSCALL)0,                       0 },\n#endif\n\n#define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \\\n        SIZE_T))aSyscall[64].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"CreateFile2\",             (SYSCALL)CreateFile2,             0 },\n#else\n  { \"CreateFile2\",             (SYSCALL)0,                       0 },\n#endif\n\n#define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \\\n        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[65].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"LoadPackagedLibrary\",     (SYSCALL)LoadPackagedLibrary,     0 },\n#else\n  { \"LoadPackagedLibrary\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \\\n        DWORD))aSyscall[66].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetTickCount64\",          (SYSCALL)GetTickCount64,          0 },\n#else\n  { \"GetTickCount64\",          (SYSCALL)0,                       0 },\n#endif\n\n#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[67].pCurrent)\n\n#if SQLITE_OS_WINRT\n  { \"GetNativeSystemInfo\",     (SYSCALL)GetNativeSystemInfo,     0 },\n#else\n  { \"GetNativeSystemInfo\",     (SYSCALL)0,                       0 },\n#endif\n\n#define osGetNativeSystemInfo ((VOID(WINAPI*)( \\\n        LPSYSTEM_INFO))aSyscall[68].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  { \"OutputDebugStringA\",      (SYSCALL)OutputDebugStringA,      0 },\n#else\n  { \"OutputDebugStringA\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[69].pCurrent)\n\n#if defined(SQLITE_WIN32_HAS_WIDE)\n  { \"OutputDebugStringW\",      (SYSCALL)OutputDebugStringW,      0 },\n#else\n  { \"OutputDebugStringW\",      (SYSCALL)0,                       0 },\n#endif\n\n#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[70].pCurrent)\n\n  { \"GetProcessHeap\",          (SYSCALL)GetProcessHeap,          0 },\n\n#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[71].pCurrent)\n\n#if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)\n  { \"CreateFileMappingFromApp\", (SYSCALL)CreateFileMappingFromApp, 0 },\n#else\n  { \"CreateFileMappingFromApp\", (SYSCALL)0,                      0 },\n#endif\n\n#define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \\\n        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[72].pCurrent)\n\n}; /* End of the overrideable system calls */\n\n/*\n** This is the xSetSystemCall() method of sqlite3_vfs for all of the\n** \"win32\" VFSes.  Return SQLITE_OK opon successfully updating the\n** system call pointer, or SQLITE_NOTFOUND if there is no configurable\n** system call named zName.\n*/\nstatic int winSetSystemCall(\n  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */\n  const char *zName,            /* Name of system call to override */\n  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */\n){\n  unsigned int i;\n  int rc = SQLITE_NOTFOUND;\n\n  UNUSED_PARAMETER(pNotUsed);\n  if( zName==0 ){\n    /* If no zName is given, restore all system calls to their default\n    ** settings and return NULL\n    */\n    rc = SQLITE_OK;\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( aSyscall[i].pDefault ){\n        aSyscall[i].pCurrent = aSyscall[i].pDefault;\n      }\n    }\n  }else{\n    /* If zName is specified, operate on only the one system call\n    ** specified.\n    */\n    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ){\n        if( aSyscall[i].pDefault==0 ){\n          aSyscall[i].pDefault = aSyscall[i].pCurrent;\n        }\n        rc = SQLITE_OK;\n        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;\n        aSyscall[i].pCurrent = pNewFunc;\n        break;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the value of a system call.  Return NULL if zName is not a\n** recognized system call name.  NULL is also returned if the system call\n** is currently undefined.\n*/\nstatic sqlite3_syscall_ptr winGetSystemCall(\n  sqlite3_vfs *pNotUsed,\n  const char *zName\n){\n  unsigned int i;\n\n  UNUSED_PARAMETER(pNotUsed);\n  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){\n    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;\n  }\n  return 0;\n}\n\n/*\n** Return the name of the first system call after zName.  If zName==NULL\n** then return the name of the first system call.  Return NULL if zName\n** is the last system call or if zName is not the name of a valid\n** system call.\n*/\nstatic const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){\n  int i = -1;\n\n  UNUSED_PARAMETER(p);\n  if( zName ){\n    for(i=0; i<ArraySize(aSyscall)-1; i++){\n      if( strcmp(zName, aSyscall[i].zName)==0 ) break;\n    }\n  }\n  for(i++; i<ArraySize(aSyscall); i++){\n    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;\n  }\n  return 0;\n}\n\n/*\n** This function outputs the specified (ANSI) string to the Win32 debugger\n** (if available).\n*/\n\nSQLITE_API void sqlite3_win32_write_debug(char *zBuf, int nBuf){\n  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];\n  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */\n  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */\n  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );\n#if defined(SQLITE_WIN32_HAS_ANSI)\n  if( nMin>0 ){\n    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n    memcpy(zDbgBuf, zBuf, nMin);\n    osOutputDebugStringA(zDbgBuf);\n  }else{\n    osOutputDebugStringA(zBuf);\n  }\n#elif defined(SQLITE_WIN32_HAS_WIDE)\n  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n  if ( osMultiByteToWideChar(\n          osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,\n          nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){\n    return;\n  }\n  osOutputDebugStringW((LPCWSTR)zDbgBuf);\n#else\n  if( nMin>0 ){\n    memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);\n    memcpy(zDbgBuf, zBuf, nMin);\n    fprintf(stderr, \"%s\", zDbgBuf);\n  }else{\n    fprintf(stderr, \"%s\", zBuf);\n  }\n#endif\n}\n\n/*\n** The following routine suspends the current thread for at least ms\n** milliseconds.  This is equivalent to the Win32 Sleep() interface.\n*/\n#if SQLITE_OS_WINRT\nstatic HANDLE sleepObj = NULL;\n#endif\n\nSQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){\n#if SQLITE_OS_WINRT\n  if ( sleepObj==NULL ){\n    sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,\n                                SYNCHRONIZE);\n  }\n  assert( sleepObj!=NULL );\n  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);\n#else\n  osSleep(milliseconds);\n#endif\n}\n\n/*\n** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,\n** or WinCE.  Return false (zero) for Win95, Win98, or WinME.\n**\n** Here is an interesting observation:  Win95, Win98, and WinME lack\n** the LockFileEx() API.  But we can still statically link against that\n** API as long as we don't call it when running Win95/98/ME.  A call to\n** this routine is used to determine if the host is Win95/98/ME or\n** WinNT/2K/XP so that we will know whether or not we can safely call\n** the LockFileEx() API.\n*/\n#if SQLITE_OS_WINCE || SQLITE_OS_WINRT\n# define isNT()  (1)\n#else\n  static int isNT(void){\n    if( sqlite3_os_type==0 ){\n      OSVERSIONINFOA sInfo;\n      sInfo.dwOSVersionInfoSize = sizeof(sInfo);\n      osGetVersionExA(&sInfo);\n      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;\n    }\n    return sqlite3_os_type==2;\n  }\n#endif /* SQLITE_OS_WINCE */\n\n#ifdef SQLITE_WIN32_MALLOC\n/*\n** Allocate nBytes of memory.\n*/\nstatic void *winMemMalloc(int nBytes){\n  HANDLE hHeap;\n  void *p;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n  assert( nBytes>=0 );\n  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);\n  if( !p ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapAlloc %u bytes (%d), heap=%p\",\n                nBytes, osGetLastError(), (void*)hHeap);\n  }\n  return p;\n}\n\n/*\n** Free memory.\n*/\nstatic void winMemFree(void *pPrior){\n  HANDLE hHeap;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );\n#endif\n  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */\n  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapFree block %p (%d), heap=%p\",\n                pPrior, osGetLastError(), (void*)hHeap);\n  }\n}\n\n/*\n** Change the size of an existing memory allocation\n*/\nstatic void *winMemRealloc(void *pPrior, int nBytes){\n  HANDLE hHeap;\n  void *p;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );\n#endif\n  assert( nBytes>=0 );\n  if( !pPrior ){\n    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);\n  }else{\n    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);\n  }\n  if( !p ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to %s %u bytes (%d), heap=%p\",\n                pPrior ? \"HeapReAlloc\" : \"HeapAlloc\", nBytes, osGetLastError(),\n                (void*)hHeap);\n  }\n  return p;\n}\n\n/*\n** Return the size of an outstanding allocation, in bytes.\n*/\nstatic int winMemSize(void *p){\n  HANDLE hHeap;\n  SIZE_T n;\n\n  winMemAssertMagic();\n  hHeap = winMemGetHeap();\n  assert( hHeap!=0 );\n  assert( hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n  if( !p ) return 0;\n  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);\n  if( n==(SIZE_T)-1 ){\n    sqlite3_log(SQLITE_NOMEM, \"failed to HeapSize block %p (%d), heap=%p\",\n                p, osGetLastError(), (void*)hHeap);\n    return 0;\n  }\n  return (int)n;\n}\n\n/*\n** Round up a request size to the next valid allocation size.\n*/\nstatic int winMemRoundup(int n){\n  return n;\n}\n\n/*\n** Initialize this module.\n*/\nstatic int winMemInit(void *pAppData){\n  winMemData *pWinMemData = (winMemData *)pAppData;\n\n  if( !pWinMemData ) return SQLITE_ERROR;\n  assert( pWinMemData->magic==WINMEM_MAGIC );\n\n#if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE\n  if( !pWinMemData->hHeap ){\n    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,\n                                      SQLITE_WIN32_HEAP_INIT_SIZE,\n                                      SQLITE_WIN32_HEAP_MAX_SIZE);\n    if( !pWinMemData->hHeap ){\n      sqlite3_log(SQLITE_NOMEM,\n          \"failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u\",\n          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,\n          SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);\n      return SQLITE_NOMEM;\n    }\n    pWinMemData->bOwned = TRUE;\n    assert( pWinMemData->bOwned );\n  }\n#else\n  pWinMemData->hHeap = osGetProcessHeap();\n  if( !pWinMemData->hHeap ){\n    sqlite3_log(SQLITE_NOMEM,\n        \"failed to GetProcessHeap (%d)\", osGetLastError());\n    return SQLITE_NOMEM;\n  }\n  pWinMemData->bOwned = FALSE;\n  assert( !pWinMemData->bOwned );\n#endif\n  assert( pWinMemData->hHeap!=0 );\n  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** Deinitialize this module.\n*/\nstatic void winMemShutdown(void *pAppData){\n  winMemData *pWinMemData = (winMemData *)pAppData;\n\n  if( !pWinMemData ) return;\n  if( pWinMemData->hHeap ){\n    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );\n#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)\n    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );\n#endif\n    if( pWinMemData->bOwned ){\n      if( !osHeapDestroy(pWinMemData->hHeap) ){\n        sqlite3_log(SQLITE_NOMEM, \"failed to HeapDestroy (%d), heap=%p\",\n                    osGetLastError(), (void*)pWinMemData->hHeap);\n      }\n      pWinMemData->bOwned = FALSE;\n    }\n    pWinMemData->hHeap = NULL;\n  }\n}\n\n/*\n** Populate the low-level memory allocation function pointers in\n** sqlite3GlobalConfig.m with pointers to the routines in this file. The\n** arguments specify the block of memory to manage.\n**\n** This routine is only called by sqlite3_config(), and therefore\n** is not required to be threadsafe (it is not).\n*/\nSQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){\n  static const sqlite3_mem_methods winMemMethods = {\n    winMemMalloc,\n    winMemFree,\n    winMemRealloc,\n    winMemSize,\n    winMemRoundup,\n    winMemInit,\n    winMemShutdown,\n    &win_mem_data\n  };\n  return &winMemMethods;\n}\n\nSQLITE_PRIVATE void sqlite3MemSetDefault(void){\n  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());\n}\n#endif /* SQLITE_WIN32_MALLOC */\n\n/*\n** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). \n**\n** Space to hold the returned string is obtained from malloc.\n*/\nstatic LPWSTR utf8ToUnicode(const char *zFilename){\n  int nChar;\n  LPWSTR zWideFilename;\n\n  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);\n  if( nChar==0 ){\n    return 0;\n  }\n  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );\n  if( zWideFilename==0 ){\n    return 0;\n  }\n  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,\n                                nChar);\n  if( nChar==0 ){\n    sqlite3_free(zWideFilename);\n    zWideFilename = 0;\n  }\n  return zWideFilename;\n}\n\n/*\n** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is\n** obtained from sqlite3_malloc().\n*/\nstatic char *unicodeToUtf8(LPCWSTR zWideFilename){\n  int nByte;\n  char *zFilename;\n\n  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);\n  if( nByte == 0 ){\n    return 0;\n  }\n  zFilename = sqlite3_malloc( nByte );\n  if( zFilename==0 ){\n    return 0;\n  }\n  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,\n                                0, 0);\n  if( nByte == 0 ){\n    sqlite3_free(zFilename);\n    zFilename = 0;\n  }\n  return zFilename;\n}\n\n/*\n** Convert an ANSI string to Microsoft Unicode, based on the\n** current codepage settings for file apis.\n** \n** Space to hold the returned string is obtained\n** from sqlite3_malloc.\n*/\nstatic LPWSTR mbcsToUnicode(const char *zFilename){\n  int nByte;\n  LPWSTR zMbcsFilename;\n  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;\n\n  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,\n                                0)*sizeof(WCHAR);\n  if( nByte==0 ){\n    return 0;\n  }\n  zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );\n  if( zMbcsFilename==0 ){\n    return 0;\n  }\n  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,\n                                nByte);\n  if( nByte==0 ){\n    sqlite3_free(zMbcsFilename);\n    zMbcsFilename = 0;\n  }\n  return zMbcsFilename;\n}\n\n/*\n** Convert Microsoft Unicode to multi-byte character string, based on the\n** user's ANSI codepage.\n**\n** Space to hold the returned string is obtained from\n** sqlite3_malloc().\n*/\nstatic char *unicodeToMbcs(LPCWSTR zWideFilename){\n  int nByte;\n  char *zFilename;\n  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;\n\n  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);\n  if( nByte == 0 ){\n    return 0;\n  }\n  zFilename = sqlite3_malloc( nByte );\n  if( zFilename==0 ){\n    return 0;\n  }\n  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,\n                                nByte, 0, 0);\n  if( nByte == 0 ){\n    sqlite3_free(zFilename);\n    zFilename = 0;\n  }\n  return zFilename;\n}\n\n/*\n** Convert multibyte character string to UTF-8.  Space to hold the\n** returned string is obtained from sqlite3_malloc().\n*/\nSQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){\n  char *zFilenameUtf8;\n  LPWSTR zTmpWide;\n\n  zTmpWide = mbcsToUnicode(zFilename);\n  if( zTmpWide==0 ){\n    return 0;\n  }\n  zFilenameUtf8 = unicodeToUtf8(zTmpWide);\n  sqlite3_free(zTmpWide);\n  return zFilenameUtf8;\n}\n\n/*\n** Convert UTF-8 to multibyte character string.  Space to hold the \n** returned string is obtained from sqlite3_malloc().\n*/\nSQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){\n  char *zFilenameMbcs;\n  LPWSTR zTmpWide;\n\n  zTmpWide = utf8ToUnicode(zFilename);\n  if( zTmpWide==0 ){\n    return 0;\n  }\n  zFilenameMbcs = unicodeToMbcs(zTmpWide);\n  sqlite3_free(zTmpWide);\n  return zFilenameMbcs;\n}\n\n/*\n** This function sets the data directory or the temporary directory based on\n** the provided arguments.  The type argument must be 1 in order to set the\n** data directory or 2 in order to set the temporary directory.  The zValue\n** argument is the name of the directory to use.  The return value will be\n** SQLITE_OK if successful.\n*/\nSQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){\n  char **ppDirectory = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  int rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){\n    ppDirectory = &sqlite3_data_directory;\n  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){\n    ppDirectory = &sqlite3_temp_directory;\n  }\n  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE\n          || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE\n  );\n  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );\n  if( ppDirectory ){\n    char *zValueUtf8 = 0;\n    if( zValue && zValue[0] ){\n      zValueUtf8 = unicodeToUtf8(zValue);\n      if ( zValueUtf8==0 ){\n        return SQLITE_NOMEM;\n      }\n    }\n    sqlite3_free(*ppDirectory);\n    *ppDirectory = zValueUtf8;\n    return SQLITE_OK;\n  }\n  return SQLITE_ERROR;\n}\n\n/*\n** The return value of getLastErrorMsg\n** is zero if the error message fits in the buffer, or non-zero\n** otherwise (if the message was truncated).\n*/\nstatic int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){\n  /* FormatMessage returns 0 on failure.  Otherwise it\n  ** returns the number of TCHARs written to the output\n  ** buffer, excluding the terminating null char.\n  */\n  DWORD dwLen = 0;\n  char *zOut = 0;\n\n  if( isNT() ){\n#if SQLITE_OS_WINRT\n    WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */\n    dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             zTempWide,\n                             MAX_PATH,\n                             0);\n#else\n    LPWSTR zTempWide = NULL;\n    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n                             FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             (LPWSTR) &zTempWide,\n                             0,\n                             0);\n#endif\n    if( dwLen > 0 ){\n      /* allocate a buffer and convert to UTF8 */\n      sqlite3BeginBenignMalloc();\n      zOut = unicodeToUtf8(zTempWide);\n      sqlite3EndBenignMalloc();\n#if !SQLITE_OS_WINRT\n      /* free the system buffer allocated by FormatMessage */\n      osLocalFree(zTempWide);\n#endif\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zTemp = NULL;\n    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |\n                             FORMAT_MESSAGE_FROM_SYSTEM |\n                             FORMAT_MESSAGE_IGNORE_INSERTS,\n                             NULL,\n                             lastErrno,\n                             0,\n                             (LPSTR) &zTemp,\n                             0,\n                             0);\n    if( dwLen > 0 ){\n      /* allocate a buffer and convert to UTF8 */\n      sqlite3BeginBenignMalloc();\n      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);\n      sqlite3EndBenignMalloc();\n      /* free the system buffer allocated by FormatMessage */\n      osLocalFree(zTemp);\n    }\n  }\n#endif\n  if( 0 == dwLen ){\n    sqlite3_snprintf(nBuf, zBuf, \"OsError 0x%x (%u)\", lastErrno, lastErrno);\n  }else{\n    /* copy a maximum of nBuf chars to output buffer */\n    sqlite3_snprintf(nBuf, zBuf, \"%s\", zOut);\n    /* free the UTF8 buffer */\n    sqlite3_free(zOut);\n  }\n  return 0;\n}\n\n/*\n**\n** This function - winLogErrorAtLine() - is only ever called via the macro\n** winLogError().\n**\n** This routine is invoked after an error occurs in an OS function.\n** It logs a message using sqlite3_log() containing the current value of\n** error code and, if possible, the human-readable equivalent from \n** FormatMessage.\n**\n** The first argument passed to the macro should be the error code that\n** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). \n** The two subsequent arguments should be the name of the OS function that\n** failed and the associated file-system path, if any.\n*/\n#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)\nstatic int winLogErrorAtLine(\n  int errcode,                    /* SQLite error code */\n  DWORD lastErrno,                /* Win32 last error */\n  const char *zFunc,              /* Name of OS function that failed */\n  const char *zPath,              /* File path associated with error */\n  int iLine                       /* Source line number where error occurred */\n){\n  char zMsg[500];                 /* Human readable error text */\n  int i;                          /* Loop counter */\n\n  zMsg[0] = 0;\n  getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);\n  assert( errcode!=SQLITE_OK );\n  if( zPath==0 ) zPath = \"\";\n  for(i=0; zMsg[i] && zMsg[i]!='\\r' && zMsg[i]!='\\n'; i++){}\n  zMsg[i] = 0;\n  sqlite3_log(errcode,\n      \"os_win.c:%d: (%d) %s(%s) - %s\",\n      iLine, lastErrno, zFunc, zPath, zMsg\n  );\n\n  return errcode;\n}\n\n/*\n** The number of times that a ReadFile(), WriteFile(), and DeleteFile()\n** will be retried following a locking error - probably caused by \n** antivirus software.  Also the initial delay before the first retry.\n** The delay increases linearly with each retry.\n*/\n#ifndef SQLITE_WIN32_IOERR_RETRY\n# define SQLITE_WIN32_IOERR_RETRY 10\n#endif\n#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY\n# define SQLITE_WIN32_IOERR_RETRY_DELAY 25\n#endif\nstatic int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;\nstatic int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;\n\n/*\n** If a ReadFile() or WriteFile() error occurs, invoke this routine\n** to see if it should be retried.  Return TRUE to retry.  Return FALSE\n** to give up with an error.\n*/\nstatic int retryIoerr(int *pnRetry, DWORD *pError){\n  DWORD e = osGetLastError();\n  if( *pnRetry>=win32IoerrRetry ){\n    if( pError ){\n      *pError = e;\n    }\n    return 0;\n  }\n  if( e==ERROR_ACCESS_DENIED ||\n      e==ERROR_LOCK_VIOLATION ||\n      e==ERROR_SHARING_VIOLATION ){\n    sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));\n    ++*pnRetry;\n    return 1;\n  }\n  if( pError ){\n    *pError = e;\n  }\n  return 0;\n}\n\n/*\n** Log a I/O error retry episode.\n*/\nstatic void logIoerr(int nRetry){\n  if( nRetry ){\n    sqlite3_log(SQLITE_IOERR, \n      \"delayed %dms for lock/sharing conflict\",\n      win32IoerrRetryDelay*nRetry*(nRetry+1)/2\n    );\n  }\n}\n\n#if SQLITE_OS_WINCE\n/*************************************************************************\n** This section contains code for WinCE only.\n*/\n/*\n** Windows CE does not have a localtime() function.  So create a\n** substitute.\n*/\n/* #include <time.h> */\nstruct tm *__cdecl localtime(const time_t *t)\n{\n  static struct tm y;\n  FILETIME uTm, lTm;\n  SYSTEMTIME pTm;\n  sqlite3_int64 t64;\n  t64 = *t;\n  t64 = (t64 + 11644473600)*10000000;\n  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);\n  uTm.dwHighDateTime= (DWORD)(t64 >> 32);\n  osFileTimeToLocalFileTime(&uTm,&lTm);\n  osFileTimeToSystemTime(&lTm,&pTm);\n  y.tm_year = pTm.wYear - 1900;\n  y.tm_mon = pTm.wMonth - 1;\n  y.tm_wday = pTm.wDayOfWeek;\n  y.tm_mday = pTm.wDay;\n  y.tm_hour = pTm.wHour;\n  y.tm_min = pTm.wMinute;\n  y.tm_sec = pTm.wSecond;\n  return &y;\n}\n\n#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]\n\n/*\n** Acquire a lock on the handle h\n*/\nstatic void winceMutexAcquire(HANDLE h){\n   DWORD dwErr;\n   do {\n     dwErr = osWaitForSingleObject(h, INFINITE);\n   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);\n}\n/*\n** Release a lock acquired by winceMutexAcquire()\n*/\n#define winceMutexRelease(h) ReleaseMutex(h)\n\n/*\n** Create the mutex and shared memory used for locking in the file\n** descriptor pFile\n*/\nstatic BOOL winceCreateLock(const char *zFilename, winFile *pFile){\n  LPWSTR zTok;\n  LPWSTR zName;\n  BOOL bInit = TRUE;\n\n  zName = utf8ToUnicode(zFilename);\n  if( zName==0 ){\n    /* out of memory */\n    return FALSE;\n  }\n\n  /* Initialize the local lockdata */\n  memset(&pFile->local, 0, sizeof(pFile->local));\n\n  /* Replace the backslashes from the filename and lowercase it\n  ** to derive a mutex name. */\n  zTok = osCharLowerW(zName);\n  for (;*zTok;zTok++){\n    if (*zTok == '\\\\') *zTok = '_';\n  }\n\n  /* Create/open the named mutex */\n  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);\n  if (!pFile->hMutex){\n    pFile->lastErrno = osGetLastError();\n    winLogError(SQLITE_ERROR, pFile->lastErrno, \"winceCreateLock1\", zFilename);\n    sqlite3_free(zName);\n    return FALSE;\n  }\n\n  /* Acquire the mutex before continuing */\n  winceMutexAcquire(pFile->hMutex);\n  \n  /* Since the names of named mutexes, semaphores, file mappings etc are \n  ** case-sensitive, take advantage of that by uppercasing the mutex name\n  ** and using that as the shared filemapping name.\n  */\n  osCharUpperW(zName);\n  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,\n                                        PAGE_READWRITE, 0, sizeof(winceLock),\n                                        zName);  \n\n  /* Set a flag that indicates we're the first to create the memory so it \n  ** must be zero-initialized */\n  if (osGetLastError() == ERROR_ALREADY_EXISTS){\n    bInit = FALSE;\n  }\n\n  sqlite3_free(zName);\n\n  /* If we succeeded in making the shared memory handle, map it. */\n  if (pFile->hShared){\n    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, \n             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));\n    /* If mapping failed, close the shared memory handle and erase it */\n    if (!pFile->shared){\n      pFile->lastErrno = osGetLastError();\n      winLogError(SQLITE_ERROR, pFile->lastErrno,\n               \"winceCreateLock2\", zFilename);\n      osCloseHandle(pFile->hShared);\n      pFile->hShared = NULL;\n    }\n  }\n\n  /* If shared memory could not be created, then close the mutex and fail */\n  if (pFile->hShared == NULL){\n    winceMutexRelease(pFile->hMutex);\n    osCloseHandle(pFile->hMutex);\n    pFile->hMutex = NULL;\n    return FALSE;\n  }\n  \n  /* Initialize the shared memory if we're supposed to */\n  if (bInit) {\n    memset(pFile->shared, 0, sizeof(winceLock));\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return TRUE;\n}\n\n/*\n** Destroy the part of winFile that deals with wince locks\n*/\nstatic void winceDestroyLock(winFile *pFile){\n  if (pFile->hMutex){\n    /* Acquire the mutex */\n    winceMutexAcquire(pFile->hMutex);\n\n    /* The following blocks should probably assert in debug mode, but they\n       are to cleanup in case any locks remained open */\n    if (pFile->local.nReaders){\n      pFile->shared->nReaders --;\n    }\n    if (pFile->local.bReserved){\n      pFile->shared->bReserved = FALSE;\n    }\n    if (pFile->local.bPending){\n      pFile->shared->bPending = FALSE;\n    }\n    if (pFile->local.bExclusive){\n      pFile->shared->bExclusive = FALSE;\n    }\n\n    /* De-reference and close our copy of the shared memory handle */\n    osUnmapViewOfFile(pFile->shared);\n    osCloseHandle(pFile->hShared);\n\n    /* Done with the mutex */\n    winceMutexRelease(pFile->hMutex);    \n    osCloseHandle(pFile->hMutex);\n    pFile->hMutex = NULL;\n  }\n}\n\n/* \n** An implementation of the LockFile() API of Windows for CE\n*/\nstatic BOOL winceLockFile(\n  LPHANDLE phFile,\n  DWORD dwFileOffsetLow,\n  DWORD dwFileOffsetHigh,\n  DWORD nNumberOfBytesToLockLow,\n  DWORD nNumberOfBytesToLockHigh\n){\n  winFile *pFile = HANDLE_TO_WINFILE(phFile);\n  BOOL bReturn = FALSE;\n\n  UNUSED_PARAMETER(dwFileOffsetHigh);\n  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);\n\n  if (!pFile->hMutex) return TRUE;\n  winceMutexAcquire(pFile->hMutex);\n\n  /* Wanting an exclusive lock? */\n  if (dwFileOffsetLow == (DWORD)SHARED_FIRST\n       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){\n    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){\n       pFile->shared->bExclusive = TRUE;\n       pFile->local.bExclusive = TRUE;\n       bReturn = TRUE;\n    }\n  }\n\n  /* Want a read-only lock? */\n  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&\n           nNumberOfBytesToLockLow == 1){\n    if (pFile->shared->bExclusive == 0){\n      pFile->local.nReaders ++;\n      if (pFile->local.nReaders == 1){\n        pFile->shared->nReaders ++;\n      }\n      bReturn = TRUE;\n    }\n  }\n\n  /* Want a pending lock? */\n  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){\n    /* If no pending lock has been acquired, then acquire it */\n    if (pFile->shared->bPending == 0) {\n      pFile->shared->bPending = TRUE;\n      pFile->local.bPending = TRUE;\n      bReturn = TRUE;\n    }\n  }\n\n  /* Want a reserved lock? */\n  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){\n    if (pFile->shared->bReserved == 0) {\n      pFile->shared->bReserved = TRUE;\n      pFile->local.bReserved = TRUE;\n      bReturn = TRUE;\n    }\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return bReturn;\n}\n\n/*\n** An implementation of the UnlockFile API of Windows for CE\n*/\nstatic BOOL winceUnlockFile(\n  LPHANDLE phFile,\n  DWORD dwFileOffsetLow,\n  DWORD dwFileOffsetHigh,\n  DWORD nNumberOfBytesToUnlockLow,\n  DWORD nNumberOfBytesToUnlockHigh\n){\n  winFile *pFile = HANDLE_TO_WINFILE(phFile);\n  BOOL bReturn = FALSE;\n\n  UNUSED_PARAMETER(dwFileOffsetHigh);\n  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);\n\n  if (!pFile->hMutex) return TRUE;\n  winceMutexAcquire(pFile->hMutex);\n\n  /* Releasing a reader lock or an exclusive lock */\n  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){\n    /* Did we have an exclusive lock? */\n    if (pFile->local.bExclusive){\n      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);\n      pFile->local.bExclusive = FALSE;\n      pFile->shared->bExclusive = FALSE;\n      bReturn = TRUE;\n    }\n\n    /* Did we just have a reader lock? */\n    else if (pFile->local.nReaders){\n      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);\n      pFile->local.nReaders --;\n      if (pFile->local.nReaders == 0)\n      {\n        pFile->shared->nReaders --;\n      }\n      bReturn = TRUE;\n    }\n  }\n\n  /* Releasing a pending lock */\n  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){\n    if (pFile->local.bPending){\n      pFile->local.bPending = FALSE;\n      pFile->shared->bPending = FALSE;\n      bReturn = TRUE;\n    }\n  }\n  /* Releasing a reserved lock */\n  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){\n    if (pFile->local.bReserved) {\n      pFile->local.bReserved = FALSE;\n      pFile->shared->bReserved = FALSE;\n      bReturn = TRUE;\n    }\n  }\n\n  winceMutexRelease(pFile->hMutex);\n  return bReturn;\n}\n/*\n** End of the special code for wince\n*****************************************************************************/\n#endif /* SQLITE_OS_WINCE */\n\n/*\n** Lock a file region.\n*/\nstatic BOOL winLockFile(\n  LPHANDLE phFile,\n  DWORD flags,\n  DWORD offsetLow,\n  DWORD offsetHigh,\n  DWORD numBytesLow,\n  DWORD numBytesHigh\n){\n#if SQLITE_OS_WINCE\n  /*\n  ** NOTE: Windows CE is handled differently here due its lack of the Win32\n  **       API LockFile.\n  */\n  return winceLockFile(phFile, offsetLow, offsetHigh,\n                       numBytesLow, numBytesHigh);\n#else\n  if( isNT() ){\n    OVERLAPPED ovlp;\n    memset(&ovlp, 0, sizeof(OVERLAPPED));\n    ovlp.Offset = offsetLow;\n    ovlp.OffsetHigh = offsetHigh;\n    return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);\n  }else{\n    return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,\n                      numBytesHigh);\n  }\n#endif\n}\n\n/*\n** Unlock a file region.\n */\nstatic BOOL winUnlockFile(\n  LPHANDLE phFile,\n  DWORD offsetLow,\n  DWORD offsetHigh,\n  DWORD numBytesLow,\n  DWORD numBytesHigh\n){\n#if SQLITE_OS_WINCE\n  /*\n  ** NOTE: Windows CE is handled differently here due its lack of the Win32\n  **       API UnlockFile.\n  */\n  return winceUnlockFile(phFile, offsetLow, offsetHigh,\n                         numBytesLow, numBytesHigh);\n#else\n  if( isNT() ){\n    OVERLAPPED ovlp;\n    memset(&ovlp, 0, sizeof(OVERLAPPED));\n    ovlp.Offset = offsetLow;\n    ovlp.OffsetHigh = offsetHigh;\n    return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);\n  }else{\n    return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,\n                        numBytesHigh);\n  }\n#endif\n}\n\n/*****************************************************************************\n** The next group of routines implement the I/O methods specified\n** by the sqlite3_io_methods object.\n******************************************************************************/\n\n/*\n** Some Microsoft compilers lack this definition.\n*/\n#ifndef INVALID_SET_FILE_POINTER\n# define INVALID_SET_FILE_POINTER ((DWORD)-1)\n#endif\n\n/*\n** Move the current position of the file handle passed as the first \n** argument to offset iOffset within the file. If successful, return 0. \n** Otherwise, set pFile->lastErrno and return non-zero.\n*/\nstatic int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){\n#if !SQLITE_OS_WINRT\n  LONG upperBits;                 /* Most sig. 32 bits of new offset */\n  LONG lowerBits;                 /* Least sig. 32 bits of new offset */\n  DWORD dwRet;                    /* Value returned by SetFilePointer() */\n  DWORD lastErrno;                /* Value returned by GetLastError() */\n\n  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);\n  lowerBits = (LONG)(iOffset & 0xffffffff);\n\n  /* API oddity: If successful, SetFilePointer() returns a dword \n  ** containing the lower 32-bits of the new file-offset. Or, if it fails,\n  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, \n  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine \n  ** whether an error has actually occured, it is also necessary to call \n  ** GetLastError().\n  */\n  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);\n\n  if( (dwRet==INVALID_SET_FILE_POINTER\n      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){\n    pFile->lastErrno = lastErrno;\n    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,\n             \"seekWinFile\", pFile->zPath);\n    return 1;\n  }\n\n  return 0;\n#else\n  /*\n  ** Same as above, except that this implementation works for WinRT.\n  */\n\n  LARGE_INTEGER x;                /* The new offset */\n  BOOL bRet;                      /* Value returned by SetFilePointerEx() */\n\n  x.QuadPart = iOffset;\n  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);\n\n  if(!bRet){\n    pFile->lastErrno = osGetLastError();\n    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,\n             \"seekWinFile\", pFile->zPath);\n    return 1;\n  }\n\n  return 0;\n#endif\n}\n\n/*\n** Close a file.\n**\n** It is reported that an attempt to close a handle might sometimes\n** fail.  This is a very unreasonable result, but Windows is notorious\n** for being unreasonable so I do not doubt that it might happen.  If\n** the close fails, we pause for 100 milliseconds and try again.  As\n** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before\n** giving up and returning an error.\n*/\n#define MX_CLOSE_ATTEMPT 3\nstatic int winClose(sqlite3_file *id){\n  int rc, cnt = 0;\n  winFile *pFile = (winFile*)id;\n\n  assert( id!=0 );\n#ifndef SQLITE_OMIT_WAL\n  assert( pFile->pShm==0 );\n#endif\n  OSTRACE((\"CLOSE %d\\n\", pFile->h));\n  do{\n    rc = osCloseHandle(pFile->h);\n    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */\n  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );\n#if SQLITE_OS_WINCE\n#define WINCE_DELETION_ATTEMPTS 3\n  winceDestroyLock(pFile);\n  if( pFile->zDeleteOnClose ){\n    int cnt = 0;\n    while(\n           osDeleteFileW(pFile->zDeleteOnClose)==0\n        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff \n        && cnt++ < WINCE_DELETION_ATTEMPTS\n    ){\n       sqlite3_win32_sleep(100);  /* Wait a little before trying again */\n    }\n    sqlite3_free(pFile->zDeleteOnClose);\n  }\n#endif\n  OSTRACE((\"CLOSE %d %s\\n\", pFile->h, rc ? \"ok\" : \"failed\"));\n  if( rc ){\n    pFile->h = NULL;\n  }\n  OpenCounter(-1);\n  return rc ? SQLITE_OK\n            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),\n                          \"winClose\", pFile->zPath);\n}\n\n/*\n** Read data from a file into a buffer.  Return SQLITE_OK if all\n** bytes were read successfully and SQLITE_IOERR if anything goes\n** wrong.\n*/\nstatic int winRead(\n  sqlite3_file *id,          /* File to read from */\n  void *pBuf,                /* Write content into this buffer */\n  int amt,                   /* Number of bytes to read */\n  sqlite3_int64 offset       /* Begin reading at this offset */\n){\n#if !SQLITE_OS_WINCE\n  OVERLAPPED overlapped;          /* The offset for ReadFile. */\n#endif\n  winFile *pFile = (winFile*)id;  /* file handle */\n  DWORD nRead;                    /* Number of bytes actually read from file */\n  int nRetry = 0;                 /* Number of retrys */\n\n  assert( id!=0 );\n  SimulateIOError(return SQLITE_IOERR_READ);\n  OSTRACE((\"READ %d lock=%d\\n\", pFile->h, pFile->locktype));\n\n#if SQLITE_OS_WINCE\n  if( seekWinFile(pFile, offset) ){\n    return SQLITE_FULL;\n  }\n  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){\n#else\n  memset(&overlapped, 0, sizeof(OVERLAPPED));\n  overlapped.Offset = (LONG)(offset & 0xffffffff);\n  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&\n         osGetLastError()!=ERROR_HANDLE_EOF ){\n#endif\n    DWORD lastErrno;\n    if( retryIoerr(&nRetry, &lastErrno) ) continue;\n    pFile->lastErrno = lastErrno;\n    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,\n             \"winRead\", pFile->zPath);\n  }\n  logIoerr(nRetry);\n  if( nRead<(DWORD)amt ){\n    /* Unread parts of the buffer must be zero-filled */\n    memset(&((char*)pBuf)[nRead], 0, amt-nRead);\n    return SQLITE_IOERR_SHORT_READ;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Write data from a buffer into a file.  Return SQLITE_OK on success\n** or some other error code on failure.\n*/\nstatic int winWrite(\n  sqlite3_file *id,               /* File to write into */\n  const void *pBuf,               /* The bytes to be written */\n  int amt,                        /* Number of bytes to write */\n  sqlite3_int64 offset            /* Offset into the file to begin writing at */\n){\n  int rc = 0;                     /* True if error has occured, else false */\n  winFile *pFile = (winFile*)id;  /* File handle */\n  int nRetry = 0;                 /* Number of retries */\n\n  assert( amt>0 );\n  assert( pFile );\n  SimulateIOError(return SQLITE_IOERR_WRITE);\n  SimulateDiskfullError(return SQLITE_FULL);\n\n  OSTRACE((\"WRITE %d lock=%d\\n\", pFile->h, pFile->locktype));\n\n#if SQLITE_OS_WINCE\n  rc = seekWinFile(pFile, offset);\n  if( rc==0 ){\n#else\n  {\n#endif\n#if !SQLITE_OS_WINCE\n    OVERLAPPED overlapped;        /* The offset for WriteFile. */\n#endif\n    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */\n    int nRem = amt;               /* Number of bytes yet to be written */\n    DWORD nWrite;                 /* Bytes written by each WriteFile() call */\n    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */\n\n#if !SQLITE_OS_WINCE\n    memset(&overlapped, 0, sizeof(OVERLAPPED));\n    overlapped.Offset = (LONG)(offset & 0xffffffff);\n    overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n#endif\n\n    while( nRem>0 ){\n#if SQLITE_OS_WINCE\n      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){\n#else\n      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){\n#endif\n        if( retryIoerr(&nRetry, &lastErrno) ) continue;\n        break;\n      }\n      if( nWrite<=0 ){\n        lastErrno = osGetLastError();\n        break;\n      }\n#if !SQLITE_OS_WINCE\n      offset += nWrite;\n      overlapped.Offset = (LONG)(offset & 0xffffffff);\n      overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);\n#endif\n      aRem += nWrite;\n      nRem -= nWrite;\n    }\n    if( nRem>0 ){\n      pFile->lastErrno = lastErrno;\n      rc = 1;\n    }\n  }\n\n  if( rc ){\n    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )\n       || ( pFile->lastErrno==ERROR_DISK_FULL )){\n      return SQLITE_FULL;\n    }\n    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,\n             \"winWrite\", pFile->zPath);\n  }else{\n    logIoerr(nRetry);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Truncate an open file to a specified size\n*/\nstatic int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){\n  winFile *pFile = (winFile*)id;  /* File handle object */\n  int rc = SQLITE_OK;             /* Return code for this function */\n\n  assert( pFile );\n\n  OSTRACE((\"TRUNCATE %d %lld\\n\", pFile->h, nByte));\n  SimulateIOError(return SQLITE_IOERR_TRUNCATE);\n\n  /* If the user has configured a chunk-size for this file, truncate the\n  ** file so that it consists of an integer number of chunks (i.e. the\n  ** actual file size after the operation may be larger than the requested\n  ** size).\n  */\n  if( pFile->szChunk>0 ){\n    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;\n  }\n\n  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */\n  if( seekWinFile(pFile, nByte) ){\n    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,\n             \"winTruncate1\", pFile->zPath);\n  }else if( 0==osSetEndOfFile(pFile->h) ){\n    pFile->lastErrno = osGetLastError();\n    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,\n             \"winTruncate2\", pFile->zPath);\n  }\n\n  OSTRACE((\"TRUNCATE %d %lld %s\\n\", pFile->h, nByte, rc ? \"failed\" : \"ok\"));\n  return rc;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Count the number of fullsyncs and normal syncs.  This is used to test\n** that syncs and fullsyncs are occuring at the right times.\n*/\nSQLITE_API int sqlite3_sync_count = 0;\nSQLITE_API int sqlite3_fullsync_count = 0;\n#endif\n\n/*\n** Make sure all writes to a particular file are committed to disk.\n*/\nstatic int winSync(sqlite3_file *id, int flags){\n#ifndef SQLITE_NO_SYNC\n  /*\n  ** Used only when SQLITE_NO_SYNC is not defined.\n   */\n  BOOL rc;\n#endif\n#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \\\n    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))\n  /*\n  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or\n  ** OSTRACE() macros.\n   */\n  winFile *pFile = (winFile*)id;\n#else\n  UNUSED_PARAMETER(id);\n#endif\n\n  assert( pFile );\n  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */\n  assert((flags&0x0F)==SQLITE_SYNC_NORMAL\n      || (flags&0x0F)==SQLITE_SYNC_FULL\n  );\n\n  OSTRACE((\"SYNC %d lock=%d\\n\", pFile->h, pFile->locktype));\n\n  /* Unix cannot, but some systems may return SQLITE_FULL from here. This\n  ** line is to test that doing so does not cause any problems.\n  */\n  SimulateDiskfullError( return SQLITE_FULL );\n\n#ifndef SQLITE_TEST\n  UNUSED_PARAMETER(flags);\n#else\n  if( (flags&0x0F)==SQLITE_SYNC_FULL ){\n    sqlite3_fullsync_count++;\n  }\n  sqlite3_sync_count++;\n#endif\n\n  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a\n  ** no-op\n  */\n#ifdef SQLITE_NO_SYNC\n  return SQLITE_OK;\n#else\n  rc = osFlushFileBuffers(pFile->h);\n  SimulateIOError( rc=FALSE );\n  if( rc ){\n    return SQLITE_OK;\n  }else{\n    pFile->lastErrno = osGetLastError();\n    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,\n             \"winSync\", pFile->zPath);\n  }\n#endif\n}\n\n/*\n** Determine the current size of a file in bytes\n*/\nstatic int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){\n  winFile *pFile = (winFile*)id;\n  int rc = SQLITE_OK;\n\n  assert( id!=0 );\n  SimulateIOError(return SQLITE_IOERR_FSTAT);\n#if SQLITE_OS_WINRT\n  {\n    FILE_STANDARD_INFO info;\n    if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,\n                                     &info, sizeof(info)) ){\n      *pSize = info.EndOfFile.QuadPart;\n    }else{\n      pFile->lastErrno = osGetLastError();\n      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,\n                       \"winFileSize\", pFile->zPath);\n    }\n  }\n#else\n  {\n    DWORD upperBits;\n    DWORD lowerBits;\n    DWORD lastErrno;\n\n    lowerBits = osGetFileSize(pFile->h, &upperBits);\n    *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;\n    if(   (lowerBits == INVALID_FILE_SIZE)\n       && ((lastErrno = osGetLastError())!=NO_ERROR) ){\n      pFile->lastErrno = lastErrno;\n      rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,\n             \"winFileSize\", pFile->zPath);\n    }\n  }\n#endif\n  return rc;\n}\n\n/*\n** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.\n*/\n#ifndef LOCKFILE_FAIL_IMMEDIATELY\n# define LOCKFILE_FAIL_IMMEDIATELY 1\n#endif\n\n#ifndef LOCKFILE_EXCLUSIVE_LOCK\n# define LOCKFILE_EXCLUSIVE_LOCK 2\n#endif\n\n/*\n** Historically, SQLite has used both the LockFile and LockFileEx functions.\n** When the LockFile function was used, it was always expected to fail\n** immediately if the lock could not be obtained.  Also, it always expected to\n** obtain an exclusive lock.  These flags are used with the LockFileEx function\n** and reflect those expectations; therefore, they should not be changed.\n*/\n#ifndef SQLITE_LOCKFILE_FLAGS\n# define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \\\n                                  LOCKFILE_EXCLUSIVE_LOCK)\n#endif\n\n/*\n** Currently, SQLite never calls the LockFileEx function without wanting the\n** call to fail immediately if the lock cannot be obtained.\n*/\n#ifndef SQLITE_LOCKFILEEX_FLAGS\n# define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)\n#endif\n\n/*\n** Acquire a reader lock.\n** Different API routines are called depending on whether or not this\n** is Win9x or WinNT.\n*/\nstatic int getReadLock(winFile *pFile){\n  int res;\n  if( isNT() ){\n#if SQLITE_OS_WINCE\n    /*\n    ** NOTE: Windows CE is handled differently here due its lack of the Win32\n    **       API LockFileEx.\n    */\n    res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);\n#else\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,\n                      SHARED_SIZE, 0);\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    int lk;\n    sqlite3_randomness(sizeof(lk), &lk);\n    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,\n                      SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);\n  }\n#endif\n  if( res == 0 ){\n    pFile->lastErrno = osGetLastError();\n    /* No need to log a failure to lock */\n  }\n  return res;\n}\n\n/*\n** Undo a readlock\n*/\nstatic int unlockReadLock(winFile *pFile){\n  int res;\n  DWORD lastErrno;\n  if( isNT() ){\n    res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);\n  }\n#endif\n  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){\n    pFile->lastErrno = lastErrno;\n    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,\n             \"unlockReadLock\", pFile->zPath);\n  }\n  return res;\n}\n\n/*\n** Lock the file with the lock specified by parameter locktype - one\n** of the following:\n**\n**     (1) SHARED_LOCK\n**     (2) RESERVED_LOCK\n**     (3) PENDING_LOCK\n**     (4) EXCLUSIVE_LOCK\n**\n** Sometimes when requesting one lock state, additional lock states\n** are inserted in between.  The locking might fail on one of the later\n** transitions leaving the lock state different from what it started but\n** still short of its goal.  The following chart shows the allowed\n** transitions and the inserted intermediate states:\n**\n**    UNLOCKED -> SHARED\n**    SHARED -> RESERVED\n**    SHARED -> (PENDING) -> EXCLUSIVE\n**    RESERVED -> (PENDING) -> EXCLUSIVE\n**    PENDING -> EXCLUSIVE\n**\n** This routine will only increase a lock.  The winUnlock() routine\n** erases all locks at once and returns us immediately to locking level 0.\n** It is not possible to lower the locking level one step at a time.  You\n** must go straight to locking level 0.\n*/\nstatic int winLock(sqlite3_file *id, int locktype){\n  int rc = SQLITE_OK;    /* Return code from subroutines */\n  int res = 1;           /* Result of a Windows lock call */\n  int newLocktype;       /* Set pFile->locktype to this value before exiting */\n  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */\n  winFile *pFile = (winFile*)id;\n  DWORD lastErrno = NO_ERROR;\n\n  assert( id!=0 );\n  OSTRACE((\"LOCK %d %d was %d(%d)\\n\",\n           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));\n\n  /* If there is already a lock of this type or more restrictive on the\n  ** OsFile, do nothing. Don't use the end_lock: exit path, as\n  ** sqlite3OsEnterMutex() hasn't been called yet.\n  */\n  if( pFile->locktype>=locktype ){\n    return SQLITE_OK;\n  }\n\n  /* Make sure the locking sequence is correct\n  */\n  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );\n  assert( locktype!=PENDING_LOCK );\n  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );\n\n  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or\n  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of\n  ** the PENDING_LOCK byte is temporary.\n  */\n  newLocktype = pFile->locktype;\n  if(   (pFile->locktype==NO_LOCK)\n     || (   (locktype==EXCLUSIVE_LOCK)\n         && (pFile->locktype==RESERVED_LOCK))\n  ){\n    int cnt = 3;\n    while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,\n                                         PENDING_BYTE, 0, 1, 0))==0 ){\n      /* Try 3 times to get the pending lock.  This is needed to work\n      ** around problems caused by indexing and/or anti-virus software on\n      ** Windows systems.\n      ** If you are using this code as a model for alternative VFSes, do not\n      ** copy this retry logic.  It is a hack intended for Windows only.\n      */\n      OSTRACE((\"could not get a PENDING lock. cnt=%d\\n\", cnt));\n      if( cnt ) sqlite3_win32_sleep(1);\n    }\n    gotPendingLock = res;\n    if( !res ){\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a shared lock\n  */\n  if( locktype==SHARED_LOCK && res ){\n    assert( pFile->locktype==NO_LOCK );\n    res = getReadLock(pFile);\n    if( res ){\n      newLocktype = SHARED_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a RESERVED lock\n  */\n  if( locktype==RESERVED_LOCK && res ){\n    assert( pFile->locktype==SHARED_LOCK );\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);\n    if( res ){\n      newLocktype = RESERVED_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n    }\n  }\n\n  /* Acquire a PENDING lock\n  */\n  if( locktype==EXCLUSIVE_LOCK && res ){\n    newLocktype = PENDING_LOCK;\n    gotPendingLock = 0;\n  }\n\n  /* Acquire an EXCLUSIVE lock\n  */\n  if( locktype==EXCLUSIVE_LOCK && res ){\n    assert( pFile->locktype>=SHARED_LOCK );\n    res = unlockReadLock(pFile);\n    OSTRACE((\"unreadlock = %d\\n\", res));\n    res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,\n                      SHARED_SIZE, 0);\n    if( res ){\n      newLocktype = EXCLUSIVE_LOCK;\n    }else{\n      lastErrno = osGetLastError();\n      OSTRACE((\"error-code = %d\\n\", lastErrno));\n      getReadLock(pFile);\n    }\n  }\n\n  /* If we are holding a PENDING lock that ought to be released, then\n  ** release it now.\n  */\n  if( gotPendingLock && locktype==SHARED_LOCK ){\n    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);\n  }\n\n  /* Update the state of the lock has held in the file descriptor then\n  ** return the appropriate result code.\n  */\n  if( res ){\n    rc = SQLITE_OK;\n  }else{\n    OSTRACE((\"LOCK FAILED %d trying for %d but got %d\\n\", pFile->h,\n           locktype, newLocktype));\n    pFile->lastErrno = lastErrno;\n    rc = SQLITE_BUSY;\n  }\n  pFile->locktype = (u8)newLocktype;\n  return rc;\n}\n\n/*\n** This routine checks if there is a RESERVED lock held on the specified\n** file by this or any other process. If such a lock is held, return\n** non-zero, otherwise zero.\n*/\nstatic int winCheckReservedLock(sqlite3_file *id, int *pResOut){\n  int rc;\n  winFile *pFile = (winFile*)id;\n\n  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );\n\n  assert( id!=0 );\n  if( pFile->locktype>=RESERVED_LOCK ){\n    rc = 1;\n    OSTRACE((\"TEST WR-LOCK %d %d (local)\\n\", pFile->h, rc));\n  }else{\n    rc = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);\n    if( rc ){\n      winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);\n    }\n    rc = !rc;\n    OSTRACE((\"TEST WR-LOCK %d %d (remote)\\n\", pFile->h, rc));\n  }\n  *pResOut = rc;\n  return SQLITE_OK;\n}\n\n/*\n** Lower the locking level on file descriptor id to locktype.  locktype\n** must be either NO_LOCK or SHARED_LOCK.\n**\n** If the locking level of the file descriptor is already at or below\n** the requested locking level, this routine is a no-op.\n**\n** It is not possible for this routine to fail if the second argument\n** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine\n** might return SQLITE_IOERR;\n*/\nstatic int winUnlock(sqlite3_file *id, int locktype){\n  int type;\n  winFile *pFile = (winFile*)id;\n  int rc = SQLITE_OK;\n  assert( pFile!=0 );\n  assert( locktype<=SHARED_LOCK );\n  OSTRACE((\"UNLOCK %d to %d was %d(%d)\\n\", pFile->h, locktype,\n          pFile->locktype, pFile->sharedLockByte));\n  type = pFile->locktype;\n  if( type>=EXCLUSIVE_LOCK ){\n    winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);\n    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){\n      /* This should never happen.  We should always be able to\n      ** reacquire the read lock */\n      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),\n               \"winUnlock\", pFile->zPath);\n    }\n  }\n  if( type>=RESERVED_LOCK ){\n    winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);\n  }\n  if( locktype==NO_LOCK && type>=SHARED_LOCK ){\n    unlockReadLock(pFile);\n  }\n  if( type>=PENDING_LOCK ){\n    winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);\n  }\n  pFile->locktype = (u8)locktype;\n  return rc;\n}\n\n/*\n** If *pArg is inititially negative then this is a query.  Set *pArg to\n** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.\n**\n** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.\n*/\nstatic void winModeBit(winFile *pFile, unsigned char mask, int *pArg){\n  if( *pArg<0 ){\n    *pArg = (pFile->ctrlFlags & mask)!=0;\n  }else if( (*pArg)==0 ){\n    pFile->ctrlFlags &= ~mask;\n  }else{\n    pFile->ctrlFlags |= mask;\n  }\n}\n\n/*\n** Control and query of the open file handle.\n*/\nstatic int winFileControl(sqlite3_file *id, int op, void *pArg){\n  winFile *pFile = (winFile*)id;\n  switch( op ){\n    case SQLITE_FCNTL_LOCKSTATE: {\n      *(int*)pArg = pFile->locktype;\n      return SQLITE_OK;\n    }\n    case SQLITE_LAST_ERRNO: {\n      *(int*)pArg = (int)pFile->lastErrno;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_CHUNK_SIZE: {\n      pFile->szChunk = *(int *)pArg;\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_SIZE_HINT: {\n      if( pFile->szChunk>0 ){\n        sqlite3_int64 oldSz;\n        int rc = winFileSize(id, &oldSz);\n        if( rc==SQLITE_OK ){\n          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;\n          if( newSz>oldSz ){\n            SimulateIOErrorBenign(1);\n            rc = winTruncate(id, newSz);\n            SimulateIOErrorBenign(0);\n          }\n        }\n        return rc;\n      }\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_PERSIST_WAL: {\n      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {\n      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_VFSNAME: {\n      *(char**)pArg = sqlite3_mprintf(\"win32\");\n      return SQLITE_OK;\n    }\n    case SQLITE_FCNTL_WIN32_AV_RETRY: {\n      int *a = (int*)pArg;\n      if( a[0]>0 ){\n        win32IoerrRetry = a[0];\n      }else{\n        a[0] = win32IoerrRetry;\n      }\n      if( a[1]>0 ){\n        win32IoerrRetryDelay = a[1];\n      }else{\n        a[1] = win32IoerrRetryDelay;\n      }\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_NOTFOUND;\n}\n\n/*\n** Return the sector size in bytes of the underlying block device for\n** the specified file. This is almost always 512 bytes, but may be\n** larger for some devices.\n**\n** SQLite code assumes this function cannot fail. It also assumes that\n** if two files are created in the same file-system directory (i.e.\n** a database and its journal file) that the sector size will be the\n** same for both.\n*/\nstatic int winSectorSize(sqlite3_file *id){\n  (void)id;\n  return SQLITE_DEFAULT_SECTOR_SIZE;\n}\n\n/*\n** Return a vector of device characteristics.\n*/\nstatic int winDeviceCharacteristics(sqlite3_file *id){\n  winFile *p = (winFile*)id;\n  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |\n         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);\n}\n\n#ifndef SQLITE_OMIT_WAL\n\n/* \n** Windows will only let you create file view mappings\n** on allocation size granularity boundaries.\n** During sqlite3_os_init() we do a GetSystemInfo()\n** to get the granularity size.\n*/\nSYSTEM_INFO winSysInfo;\n\n/*\n** Helper functions to obtain and relinquish the global mutex. The\n** global mutex is used to protect the winLockInfo objects used by \n** this file, all of which may be shared by multiple threads.\n**\n** Function winShmMutexHeld() is used to assert() that the global mutex \n** is held when required. This function is only used as part of assert() \n** statements. e.g.\n**\n**   winShmEnterMutex()\n**     assert( winShmMutexHeld() );\n**   winShmLeaveMutex()\n*/\nstatic void winShmEnterMutex(void){\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\nstatic void winShmLeaveMutex(void){\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n#ifdef SQLITE_DEBUG\nstatic int winShmMutexHeld(void) {\n  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n#endif\n\n/*\n** Object used to represent a single file opened and mmapped to provide\n** shared memory.  When multiple threads all reference the same\n** log-summary, each thread has its own winFile object, but they all\n** point to a single instance of this object.  In other words, each\n** log-summary is opened only once per process.\n**\n** winShmMutexHeld() must be true when creating or destroying\n** this object or while reading or writing the following fields:\n**\n**      nRef\n**      pNext \n**\n** The following fields are read-only after the object is created:\n** \n**      fid\n**      zFilename\n**\n** Either winShmNode.mutex must be held or winShmNode.nRef==0 and\n** winShmMutexHeld() is true when reading or writing any other field\n** in this structure.\n**\n*/\nstruct winShmNode {\n  sqlite3_mutex *mutex;      /* Mutex to access this object */\n  char *zFilename;           /* Name of the file */\n  winFile hFile;             /* File handle from winOpen */\n\n  int szRegion;              /* Size of shared-memory regions */\n  int nRegion;               /* Size of array apRegion */\n  struct ShmRegion {\n    HANDLE hMap;             /* File handle from CreateFileMapping */\n    void *pMap;\n  } *aRegion;\n  DWORD lastErrno;           /* The Windows errno from the last I/O error */\n\n  int nRef;                  /* Number of winShm objects pointing to this */\n  winShm *pFirst;            /* All winShm objects pointing to this */\n  winShmNode *pNext;         /* Next in list of all winShmNode objects */\n#ifdef SQLITE_DEBUG\n  u8 nextShmId;              /* Next available winShm.id value */\n#endif\n};\n\n/*\n** A global array of all winShmNode objects.\n**\n** The winShmMutexHeld() must be true while reading or writing this list.\n*/\nstatic winShmNode *winShmNodeList = 0;\n\n/*\n** Structure used internally by this VFS to record the state of an\n** open shared memory connection.\n**\n** The following fields are initialized when this object is created and\n** are read-only thereafter:\n**\n**    winShm.pShmNode\n**    winShm.id\n**\n** All other fields are read/write.  The winShm.pShmNode->mutex must be held\n** while accessing any read/write fields.\n*/\nstruct winShm {\n  winShmNode *pShmNode;      /* The underlying winShmNode object */\n  winShm *pNext;             /* Next winShm with the same winShmNode */\n  u8 hasMutex;               /* True if holding the winShmNode mutex */\n  u16 sharedMask;            /* Mask of shared locks held */\n  u16 exclMask;              /* Mask of exclusive locks held */\n#ifdef SQLITE_DEBUG\n  u8 id;                     /* Id of this connection with its winShmNode */\n#endif\n};\n\n/*\n** Constants used for locking\n*/\n#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */\n#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */\n\n/*\n** Apply advisory locks for all n bytes beginning at ofst.\n*/\n#define _SHM_UNLCK  1\n#define _SHM_RDLCK  2\n#define _SHM_WRLCK  3\nstatic int winShmSystemLock(\n  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */\n  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */\n  int ofst,             /* Offset to first byte to be locked/unlocked */\n  int nByte             /* Number of bytes to lock or unlock */\n){\n  int rc = 0;           /* Result code form Lock/UnlockFileEx() */\n\n  /* Access to the winShmNode object is serialized by the caller */\n  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );\n\n  /* Release/Acquire the system-level lock */\n  if( lockType==_SHM_UNLCK ){\n    rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);\n  }else{\n    /* Initialize the locking parameters */\n    DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;\n    if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;\n    rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);\n  }\n  \n  if( rc!= 0 ){\n    rc = SQLITE_OK;\n  }else{\n    pFile->lastErrno =  osGetLastError();\n    rc = SQLITE_BUSY;\n  }\n\n  OSTRACE((\"SHM-LOCK %d %s %s 0x%08lx\\n\", \n           pFile->hFile.h,\n           rc==SQLITE_OK ? \"ok\" : \"failed\",\n           lockType==_SHM_UNLCK ? \"UnlockFileEx\" : \"LockFileEx\",\n           pFile->lastErrno));\n\n  return rc;\n}\n\n/* Forward references to VFS methods */\nstatic int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);\nstatic int winDelete(sqlite3_vfs *,const char*,int);\n\n/*\n** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.\n**\n** This is not a VFS shared-memory method; it is a utility function called\n** by VFS shared-memory methods.\n*/\nstatic void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){\n  winShmNode **pp;\n  winShmNode *p;\n  BOOL bRc;\n  assert( winShmMutexHeld() );\n  pp = &winShmNodeList;\n  while( (p = *pp)!=0 ){\n    if( p->nRef==0 ){\n      int i;\n      if( p->mutex ) sqlite3_mutex_free(p->mutex);\n      for(i=0; i<p->nRegion; i++){\n        bRc = osUnmapViewOfFile(p->aRegion[i].pMap);\n        OSTRACE((\"SHM-PURGE pid-%d unmap region=%d %s\\n\",\n                 (int)osGetCurrentProcessId(), i,\n                 bRc ? \"ok\" : \"failed\"));\n        bRc = osCloseHandle(p->aRegion[i].hMap);\n        OSTRACE((\"SHM-PURGE pid-%d close region=%d %s\\n\",\n                 (int)osGetCurrentProcessId(), i,\n                 bRc ? \"ok\" : \"failed\"));\n      }\n      if( p->hFile.h != INVALID_HANDLE_VALUE ){\n        SimulateIOErrorBenign(1);\n        winClose((sqlite3_file *)&p->hFile);\n        SimulateIOErrorBenign(0);\n      }\n      if( deleteFlag ){\n        SimulateIOErrorBenign(1);\n        sqlite3BeginBenignMalloc();\n        winDelete(pVfs, p->zFilename, 0);\n        sqlite3EndBenignMalloc();\n        SimulateIOErrorBenign(0);\n      }\n      *pp = p->pNext;\n      sqlite3_free(p->aRegion);\n      sqlite3_free(p);\n    }else{\n      pp = &p->pNext;\n    }\n  }\n}\n\n/*\n** Open the shared-memory area associated with database file pDbFd.\n**\n** When opening a new shared-memory file, if no other instances of that\n** file are currently open, in this process or in other processes, then\n** the file must be truncated to zero length or have its header cleared.\n*/\nstatic int winOpenSharedMemory(winFile *pDbFd){\n  struct winShm *p;                  /* The connection to be opened */\n  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */\n  int rc;                            /* Result code */\n  struct winShmNode *pNew;           /* Newly allocated winShmNode */\n  int nName;                         /* Size of zName in bytes */\n\n  assert( pDbFd->pShm==0 );    /* Not previously opened */\n\n  /* Allocate space for the new sqlite3_shm object.  Also speculatively\n  ** allocate space for a new winShmNode and filename.\n  */\n  p = sqlite3_malloc( sizeof(*p) );\n  if( p==0 ) return SQLITE_IOERR_NOMEM;\n  memset(p, 0, sizeof(*p));\n  nName = sqlite3Strlen30(pDbFd->zPath);\n  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );\n  if( pNew==0 ){\n    sqlite3_free(p);\n    return SQLITE_IOERR_NOMEM;\n  }\n  memset(pNew, 0, sizeof(*pNew) + nName + 17);\n  pNew->zFilename = (char*)&pNew[1];\n  sqlite3_snprintf(nName+15, pNew->zFilename, \"%s-shm\", pDbFd->zPath);\n  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); \n\n  /* Look to see if there is an existing winShmNode that can be used.\n  ** If no matching winShmNode currently exists, create a new one.\n  */\n  winShmEnterMutex();\n  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){\n    /* TBD need to come up with better match here.  Perhaps\n    ** use FILE_ID_BOTH_DIR_INFO Structure.\n    */\n    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;\n  }\n  if( pShmNode ){\n    sqlite3_free(pNew);\n  }else{\n    pShmNode = pNew;\n    pNew = 0;\n    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;\n    pShmNode->pNext = winShmNodeList;\n    winShmNodeList = pShmNode;\n\n    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);\n    if( pShmNode->mutex==0 ){\n      rc = SQLITE_IOERR_NOMEM;\n      goto shm_open_err;\n    }\n\n    rc = winOpen(pDbFd->pVfs,\n                 pShmNode->zFilename,             /* Name of the file (UTF-8) */\n                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */\n                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */\n                 0);\n    if( SQLITE_OK!=rc ){\n      goto shm_open_err;\n    }\n\n    /* Check to see if another process is holding the dead-man switch.\n    ** If not, truncate the file to zero length. \n    */\n    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){\n      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);\n      if( rc!=SQLITE_OK ){\n        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),\n                 \"winOpenShm\", pDbFd->zPath);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);\n      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);\n    }\n    if( rc ) goto shm_open_err;\n  }\n\n  /* Make the new connection a child of the winShmNode */\n  p->pShmNode = pShmNode;\n#ifdef SQLITE_DEBUG\n  p->id = pShmNode->nextShmId++;\n#endif\n  pShmNode->nRef++;\n  pDbFd->pShm = p;\n  winShmLeaveMutex();\n\n  /* The reference count on pShmNode has already been incremented under\n  ** the cover of the winShmEnterMutex() mutex and the pointer from the\n  ** new (struct winShm) object to the pShmNode has been set. All that is\n  ** left to do is to link the new object into the linked list starting\n  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex \n  ** mutex.\n  */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  p->pNext = pShmNode->pFirst;\n  pShmNode->pFirst = p;\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return SQLITE_OK;\n\n  /* Jump here on any error */\nshm_open_err:\n  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);\n  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */\n  sqlite3_free(p);\n  sqlite3_free(pNew);\n  winShmLeaveMutex();\n  return rc;\n}\n\n/*\n** Close a connection to shared-memory.  Delete the underlying \n** storage if deleteFlag is true.\n*/\nstatic int winShmUnmap(\n  sqlite3_file *fd,          /* Database holding shared memory */\n  int deleteFlag             /* Delete after closing if true */\n){\n  winFile *pDbFd;       /* Database holding shared-memory */\n  winShm *p;            /* The connection to be closed */\n  winShmNode *pShmNode; /* The underlying shared-memory file */\n  winShm **pp;          /* For looping over sibling connections */\n\n  pDbFd = (winFile*)fd;\n  p = pDbFd->pShm;\n  if( p==0 ) return SQLITE_OK;\n  pShmNode = p->pShmNode;\n\n  /* Remove connection p from the set of connections associated\n  ** with pShmNode */\n  sqlite3_mutex_enter(pShmNode->mutex);\n  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}\n  *pp = p->pNext;\n\n  /* Free the connection p */\n  sqlite3_free(p);\n  pDbFd->pShm = 0;\n  sqlite3_mutex_leave(pShmNode->mutex);\n\n  /* If pShmNode->nRef has reached 0, then close the underlying\n  ** shared-memory file, too */\n  winShmEnterMutex();\n  assert( pShmNode->nRef>0 );\n  pShmNode->nRef--;\n  if( pShmNode->nRef==0 ){\n    winShmPurge(pDbFd->pVfs, deleteFlag);\n  }\n  winShmLeaveMutex();\n\n  return SQLITE_OK;\n}\n\n/*\n** Change the lock state for a shared-memory segment.\n*/\nstatic int winShmLock(\n  sqlite3_file *fd,          /* Database file holding the shared memory */\n  int ofst,                  /* First lock to acquire or release */\n  int n,                     /* Number of locks to acquire or release */\n  int flags                  /* What to do with the lock */\n){\n  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */\n  winShm *p = pDbFd->pShm;              /* The shared memory being locked */\n  winShm *pX;                           /* For looping over all siblings */\n  winShmNode *pShmNode = p->pShmNode;\n  int rc = SQLITE_OK;                   /* Result code */\n  u16 mask;                             /* Mask of locks to take or release */\n\n  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );\n  assert( n>=1 );\n  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)\n       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );\n  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );\n\n  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));\n  assert( n>1 || mask==(1<<ofst) );\n  sqlite3_mutex_enter(pShmNode->mutex);\n  if( flags & SQLITE_SHM_UNLOCK ){\n    u16 allMask = 0; /* Mask of locks held by siblings */\n\n    /* See if any siblings hold this same lock */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( pX==p ) continue;\n      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );\n      allMask |= pX->sharedMask;\n    }\n\n    /* Unlock the system-level locks */\n    if( (mask & allMask)==0 ){\n      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* Undo the local locks */\n    if( rc==SQLITE_OK ){\n      p->exclMask &= ~mask;\n      p->sharedMask &= ~mask;\n    } \n  }else if( flags & SQLITE_SHM_SHARED ){\n    u16 allShared = 0;  /* Union of locks held by connections other than \"p\" */\n\n    /* Find out which shared locks are already held by sibling connections.\n    ** If any sibling already holds an exclusive lock, go ahead and return\n    ** SQLITE_BUSY.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n      allShared |= pX->sharedMask;\n    }\n\n    /* Get shared locks at the system level, if necessary */\n    if( rc==SQLITE_OK ){\n      if( (allShared & mask)==0 ){\n        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);\n      }else{\n        rc = SQLITE_OK;\n      }\n    }\n\n    /* Get the local shared locks */\n    if( rc==SQLITE_OK ){\n      p->sharedMask |= mask;\n    }\n  }else{\n    /* Make sure no sibling connections hold locks that will block this\n    ** lock.  If any do, return SQLITE_BUSY right away.\n    */\n    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){\n      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){\n        rc = SQLITE_BUSY;\n        break;\n      }\n    }\n  \n    /* Get the exclusive locks at the system level.  Then if successful\n    ** also mark the local connection as being locked.\n    */\n    if( rc==SQLITE_OK ){\n      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);\n      if( rc==SQLITE_OK ){\n        assert( (p->sharedMask & mask)==0 );\n        p->exclMask |= mask;\n      }\n    }\n  }\n  sqlite3_mutex_leave(pShmNode->mutex);\n  OSTRACE((\"SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\\n\",\n           p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,\n           rc ? \"failed\" : \"ok\"));\n  return rc;\n}\n\n/*\n** Implement a memory barrier or memory fence on shared memory.  \n**\n** All loads and stores begun before the barrier must complete before\n** any load or store begun after the barrier.\n*/\nstatic void winShmBarrier(\n  sqlite3_file *fd          /* Database holding the shared memory */\n){\n  UNUSED_PARAMETER(fd);\n  /* MemoryBarrier(); // does not work -- do not know why not */\n  winShmEnterMutex();\n  winShmLeaveMutex();\n}\n\n/*\n** This function is called to obtain a pointer to region iRegion of the \n** shared-memory associated with the database file fd. Shared-memory regions \n** are numbered starting from zero. Each shared-memory region is szRegion \n** bytes in size.\n**\n** If an error occurs, an error code is returned and *pp is set to NULL.\n**\n** Otherwise, if the isWrite parameter is 0 and the requested shared-memory\n** region has not been allocated (by any client, including one running in a\n** separate process), then *pp is set to NULL and SQLITE_OK returned. If \n** isWrite is non-zero and the requested shared-memory region has not yet \n** been allocated, it is allocated by this function.\n**\n** If the shared-memory region has already been allocated or is allocated by\n** this call as described above, then it is mapped into this processes \n** address space (if it is not already), *pp is set to point to the mapped \n** memory and SQLITE_OK returned.\n*/\nstatic int winShmMap(\n  sqlite3_file *fd,               /* Handle open on database file */\n  int iRegion,                    /* Region to retrieve */\n  int szRegion,                   /* Size of regions */\n  int isWrite,                    /* True to extend file if necessary */\n  void volatile **pp              /* OUT: Mapped memory */\n){\n  winFile *pDbFd = (winFile*)fd;\n  winShm *p = pDbFd->pShm;\n  winShmNode *pShmNode;\n  int rc = SQLITE_OK;\n\n  if( !p ){\n    rc = winOpenSharedMemory(pDbFd);\n    if( rc!=SQLITE_OK ) return rc;\n    p = pDbFd->pShm;\n  }\n  pShmNode = p->pShmNode;\n\n  sqlite3_mutex_enter(pShmNode->mutex);\n  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );\n\n  if( pShmNode->nRegion<=iRegion ){\n    struct ShmRegion *apNew;           /* New aRegion[] array */\n    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */\n    sqlite3_int64 sz;                  /* Current size of wal-index file */\n\n    pShmNode->szRegion = szRegion;\n\n    /* The requested region is not mapped into this processes address space.\n    ** Check to see if it has been allocated (i.e. if the wal-index file is\n    ** large enough to contain the requested region).\n    */\n    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);\n    if( rc!=SQLITE_OK ){\n      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),\n               \"winShmMap1\", pDbFd->zPath);\n      goto shmpage_out;\n    }\n\n    if( sz<nByte ){\n      /* The requested memory region does not exist. If isWrite is set to\n      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.\n      **\n      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate\n      ** the requested memory region.\n      */\n      if( !isWrite ) goto shmpage_out;\n      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);\n      if( rc!=SQLITE_OK ){\n        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),\n                 \"winShmMap2\", pDbFd->zPath);\n        goto shmpage_out;\n      }\n    }\n\n    /* Map the requested memory region into this processes address space. */\n    apNew = (struct ShmRegion *)sqlite3_realloc(\n        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])\n    );\n    if( !apNew ){\n      rc = SQLITE_IOERR_NOMEM;\n      goto shmpage_out;\n    }\n    pShmNode->aRegion = apNew;\n\n    while( pShmNode->nRegion<=iRegion ){\n      HANDLE hMap;                /* file-mapping handle */\n      void *pMap = 0;             /* Mapped memory region */\n     \n#if SQLITE_OS_WINRT\n      hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,\n          NULL, PAGE_READWRITE, nByte, NULL\n      );\n#else\n      hMap = osCreateFileMappingW(pShmNode->hFile.h, \n          NULL, PAGE_READWRITE, 0, nByte, NULL\n      );\n#endif\n      OSTRACE((\"SHM-MAP pid-%d create region=%d nbyte=%d %s\\n\",\n               (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,\n               hMap ? \"ok\" : \"failed\"));\n      if( hMap ){\n        int iOffset = pShmNode->nRegion*szRegion;\n        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;\n#if SQLITE_OS_WINRT\n        pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,\n            iOffset - iOffsetShift, szRegion + iOffsetShift\n        );\n#else\n        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,\n            0, iOffset - iOffsetShift, szRegion + iOffsetShift\n        );\n#endif\n        OSTRACE((\"SHM-MAP pid-%d map region=%d offset=%d size=%d %s\\n\",\n                 (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,\n                 szRegion, pMap ? \"ok\" : \"failed\"));\n      }\n      if( !pMap ){\n        pShmNode->lastErrno = osGetLastError();\n        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,\n                 \"winShmMap3\", pDbFd->zPath);\n        if( hMap ) osCloseHandle(hMap);\n        goto shmpage_out;\n      }\n\n      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;\n      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;\n      pShmNode->nRegion++;\n    }\n  }\n\nshmpage_out:\n  if( pShmNode->nRegion>iRegion ){\n    int iOffset = iRegion*szRegion;\n    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;\n    char *p = (char *)pShmNode->aRegion[iRegion].pMap;\n    *pp = (void *)&p[iOffsetShift];\n  }else{\n    *pp = 0;\n  }\n  sqlite3_mutex_leave(pShmNode->mutex);\n  return rc;\n}\n\n#else\n# define winShmMap     0\n# define winShmLock    0\n# define winShmBarrier 0\n# define winShmUnmap   0\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n/*\n** Here ends the implementation of all sqlite3_file methods.\n**\n********************** End sqlite3_file Methods *******************************\n******************************************************************************/\n\n/*\n** This vector defines all the methods that can operate on an\n** sqlite3_file for win32.\n*/\nstatic const sqlite3_io_methods winIoMethod = {\n  2,                              /* iVersion */\n  winClose,                       /* xClose */\n  winRead,                        /* xRead */\n  winWrite,                       /* xWrite */\n  winTruncate,                    /* xTruncate */\n  winSync,                        /* xSync */\n  winFileSize,                    /* xFileSize */\n  winLock,                        /* xLock */\n  winUnlock,                      /* xUnlock */\n  winCheckReservedLock,           /* xCheckReservedLock */\n  winFileControl,                 /* xFileControl */\n  winSectorSize,                  /* xSectorSize */\n  winDeviceCharacteristics,       /* xDeviceCharacteristics */\n  winShmMap,                      /* xShmMap */\n  winShmLock,                     /* xShmLock */\n  winShmBarrier,                  /* xShmBarrier */\n  winShmUnmap                     /* xShmUnmap */\n};\n\n/****************************************************************************\n**************************** sqlite3_vfs methods ****************************\n**\n** This division contains the implementation of methods on the\n** sqlite3_vfs object.\n*/\n\n/*\n** Convert a UTF-8 filename into whatever form the underlying\n** operating system wants filenames in.  Space to hold the result\n** is obtained from malloc and must be freed by the calling\n** function.\n*/\nstatic void *convertUtf8Filename(const char *zFilename){\n  void *zConverted = 0;\n  if( isNT() ){\n    zConverted = utf8ToUnicode(zFilename);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);\n  }\n#endif\n  /* caller will handle out of memory */\n  return zConverted;\n}\n\n/*\n** Create a temporary file name in zBuf.  zBuf must be big enough to\n** hold at pVfs->mxPathname characters.\n*/\nstatic int getTempname(int nBuf, char *zBuf){\n  static char zChars[] =\n    \"abcdefghijklmnopqrstuvwxyz\"\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    \"0123456789\";\n  size_t i, j;\n  int nTempPath;\n  char zTempPath[MAX_PATH+2];\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. \n  */\n  SimulateIOError( return SQLITE_IOERR );\n\n  memset(zTempPath, 0, MAX_PATH+2);\n\n  if( sqlite3_temp_directory ){\n    sqlite3_snprintf(MAX_PATH-30, zTempPath, \"%s\", sqlite3_temp_directory);\n  }\n#if !SQLITE_OS_WINRT\n  else if( isNT() ){\n    char *zMulti;\n    WCHAR zWidePath[MAX_PATH];\n    osGetTempPathW(MAX_PATH-30, zWidePath);\n    zMulti = unicodeToUtf8(zWidePath);\n    if( zMulti ){\n      sqlite3_snprintf(MAX_PATH-30, zTempPath, \"%s\", zMulti);\n      sqlite3_free(zMulti);\n    }else{\n      return SQLITE_IOERR_NOMEM;\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zUtf8;\n    char zMbcsPath[MAX_PATH];\n    osGetTempPathA(MAX_PATH-30, zMbcsPath);\n    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);\n    if( zUtf8 ){\n      sqlite3_snprintf(MAX_PATH-30, zTempPath, \"%s\", zUtf8);\n      sqlite3_free(zUtf8);\n    }else{\n      return SQLITE_IOERR_NOMEM;\n    }\n  }\n#endif\n#endif\n\n  /* Check that the output buffer is large enough for the temporary file \n  ** name. If it is not, return SQLITE_ERROR.\n  */\n  nTempPath = sqlite3Strlen30(zTempPath);\n\n  if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){\n    return SQLITE_ERROR;\n  }\n\n  for(i=nTempPath; i>0 && zTempPath[i-1]=='\\\\'; i--){}\n  zTempPath[i] = 0;\n\n  sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?\n                       \"%s\\\\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,\n                   zTempPath);\n  j = sqlite3Strlen30(zBuf);\n  sqlite3_randomness(15, &zBuf[j]);\n  for(i=0; i<15; i++, j++){\n    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];\n  }\n  zBuf[j] = 0;\n  zBuf[j+1] = 0;\n\n  OSTRACE((\"TEMP FILENAME: %s\\n\", zBuf));\n  return SQLITE_OK; \n}\n\n/*\n** Return TRUE if the named file is really a directory.  Return false if\n** it is something other than a directory, or if there is any kind of memory\n** allocation failure.\n*/\nstatic int winIsDir(const void *zConverted){\n  DWORD attr;\n  int rc = 0;\n  DWORD lastErrno;\n\n  if( isNT() ){\n    int cnt = 0;\n    WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n    memset(&sAttrData, 0, sizeof(sAttrData));\n    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,\n                             GetFileExInfoStandard,\n                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}\n    if( !rc ){\n      return 0; /* Invalid name? */\n    }\n    attr = sAttrData.dwFileAttributes;\n#if SQLITE_OS_WINCE==0\n  }else{\n    attr = osGetFileAttributesA((char*)zConverted);\n#endif\n  }\n  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);\n}\n\n/*\n** Open a file.\n*/\nstatic int winOpen(\n  sqlite3_vfs *pVfs,        /* Not used */\n  const char *zName,        /* Name of the file (UTF-8) */\n  sqlite3_file *id,         /* Write the SQLite file handle here */\n  int flags,                /* Open mode flags */\n  int *pOutFlags            /* Status return flags */\n){\n  HANDLE h;\n  DWORD lastErrno;\n  DWORD dwDesiredAccess;\n  DWORD dwShareMode;\n  DWORD dwCreationDisposition;\n  DWORD dwFlagsAndAttributes = 0;\n#if SQLITE_OS_WINCE\n  int isTemp = 0;\n#endif\n  winFile *pFile = (winFile*)id;\n  void *zConverted;              /* Filename in OS encoding */\n  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */\n  int cnt = 0;\n\n  /* If argument zPath is a NULL pointer, this function is required to open\n  ** a temporary file. Use this buffer to store the file name in.\n  */\n  char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */\n\n  int rc = SQLITE_OK;            /* Function Return Code */\n#if !defined(NDEBUG) || SQLITE_OS_WINCE\n  int eType = flags&0xFFFFFF00;  /* Type of file to open */\n#endif\n\n  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);\n  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);\n  int isCreate     = (flags & SQLITE_OPEN_CREATE);\n#ifndef NDEBUG\n  int isReadonly   = (flags & SQLITE_OPEN_READONLY);\n#endif\n  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);\n\n#ifndef NDEBUG\n  int isOpenJournal = (isCreate && (\n        eType==SQLITE_OPEN_MASTER_JOURNAL \n     || eType==SQLITE_OPEN_MAIN_JOURNAL \n     || eType==SQLITE_OPEN_WAL\n  ));\n#endif\n\n  /* Check the following statements are true: \n  **\n  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and \n  **   (b) if CREATE is set, then READWRITE must also be set, and\n  **   (c) if EXCLUSIVE is set, then CREATE must also be set.\n  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.\n  */\n  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));\n  assert(isCreate==0 || isReadWrite);\n  assert(isExclusive==0 || isCreate);\n  assert(isDelete==0 || isCreate);\n\n  /* The main DB, main journal, WAL file and master journal are never \n  ** automatically deleted. Nor are they ever temporary files.  */\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );\n  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );\n\n  /* Assert that the upper layer has set one of the \"file-type\" flags. */\n  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB \n       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL \n       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL \n       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL\n  );\n\n  assert( id!=0 );\n  UNUSED_PARAMETER(pVfs);\n\n#if SQLITE_OS_WINRT\n  if( !sqlite3_temp_directory ){\n    sqlite3_log(SQLITE_ERROR,\n        \"sqlite3_temp_directory variable should be set for WinRT\");\n  }\n#endif\n\n  pFile->h = INVALID_HANDLE_VALUE;\n\n  /* If the second argument to this function is NULL, generate a \n  ** temporary file name to use \n  */\n  if( !zUtf8Name ){\n    assert(isDelete && !isOpenJournal);\n    rc = getTempname(MAX_PATH+2, zTmpname);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    zUtf8Name = zTmpname;\n  }\n\n  /* Database filenames are double-zero terminated if they are not\n  ** URIs with parameters.  Hence, they can always be passed into\n  ** sqlite3_uri_parameter().\n  */\n  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||\n        zUtf8Name[strlen(zUtf8Name)+1]==0 );\n\n  /* Convert the filename to the system encoding. */\n  zConverted = convertUtf8Filename(zUtf8Name);\n  if( zConverted==0 ){\n    return SQLITE_IOERR_NOMEM;\n  }\n\n  if( winIsDir(zConverted) ){\n    sqlite3_free(zConverted);\n    return SQLITE_CANTOPEN_ISDIR;\n  }\n\n  if( isReadWrite ){\n    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;\n  }else{\n    dwDesiredAccess = GENERIC_READ;\n  }\n\n  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is \n  ** created. SQLite doesn't use it to indicate \"exclusive access\" \n  ** as it is usually understood.\n  */\n  if( isExclusive ){\n    /* Creates a new file, only if it does not already exist. */\n    /* If the file exists, it fails. */\n    dwCreationDisposition = CREATE_NEW;\n  }else if( isCreate ){\n    /* Open existing file, or create if it doesn't exist */\n    dwCreationDisposition = OPEN_ALWAYS;\n  }else{\n    /* Opens a file, only if it exists. */\n    dwCreationDisposition = OPEN_EXISTING;\n  }\n\n  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;\n\n  if( isDelete ){\n#if SQLITE_OS_WINCE\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;\n    isTemp = 1;\n#else\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY\n                               | FILE_ATTRIBUTE_HIDDEN\n                               | FILE_FLAG_DELETE_ON_CLOSE;\n#endif\n  }else{\n    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;\n  }\n  /* Reports from the internet are that performance is always\n  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */\n#if SQLITE_OS_WINCE\n  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;\n#endif\n\n  if( isNT() ){\n#if SQLITE_OS_WINRT\n    CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;\n    extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);\n    extendedParameters.dwFileAttributes =\n            dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;\n    extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;\n    extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;\n    extendedParameters.lpSecurityAttributes = NULL;\n    extendedParameters.hTemplateFile = NULL;\n    while( (h = osCreateFile2((LPCWSTR)zConverted,\n                              dwDesiredAccess,\n                              dwShareMode,\n                              dwCreationDisposition,\n                              &extendedParameters))==INVALID_HANDLE_VALUE &&\n                              retryIoerr(&cnt, &lastErrno) ){\n               /* Noop */\n    }\n#else\n    while( (h = osCreateFileW((LPCWSTR)zConverted,\n                              dwDesiredAccess,\n                              dwShareMode, NULL,\n                              dwCreationDisposition,\n                              dwFlagsAndAttributes,\n                              NULL))==INVALID_HANDLE_VALUE &&\n                              retryIoerr(&cnt, &lastErrno) ){\n               /* Noop */\n    }\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    while( (h = osCreateFileA((LPCSTR)zConverted,\n                              dwDesiredAccess,\n                              dwShareMode, NULL,\n                              dwCreationDisposition,\n                              dwFlagsAndAttributes,\n                              NULL))==INVALID_HANDLE_VALUE &&\n                              retryIoerr(&cnt, &lastErrno) ){\n               /* Noop */\n    }\n  }\n#endif\n  logIoerr(cnt);\n\n  OSTRACE((\"OPEN %d %s 0x%lx %s\\n\", \n           h, zName, dwDesiredAccess, \n           h==INVALID_HANDLE_VALUE ? \"failed\" : \"ok\"));\n\n  if( h==INVALID_HANDLE_VALUE ){\n    pFile->lastErrno = lastErrno;\n    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, \"winOpen\", zUtf8Name);\n    sqlite3_free(zConverted);\n    if( isReadWrite && !isExclusive ){\n      return winOpen(pVfs, zName, id, \n             ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);\n    }else{\n      return SQLITE_CANTOPEN_BKPT;\n    }\n  }\n\n  if( pOutFlags ){\n    if( isReadWrite ){\n      *pOutFlags = SQLITE_OPEN_READWRITE;\n    }else{\n      *pOutFlags = SQLITE_OPEN_READONLY;\n    }\n  }\n\n  memset(pFile, 0, sizeof(*pFile));\n  pFile->pMethod = &winIoMethod;\n  pFile->h = h;\n  pFile->lastErrno = NO_ERROR;\n  pFile->pVfs = pVfs;\n#ifndef SQLITE_OMIT_WAL\n  pFile->pShm = 0;\n#endif\n  pFile->zPath = zName;\n  if( sqlite3_uri_boolean(zName, \"psow\", SQLITE_POWERSAFE_OVERWRITE) ){\n    pFile->ctrlFlags |= WINFILE_PSOW;\n  }\n\n#if SQLITE_OS_WINCE\n  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB\n       && !winceCreateLock(zName, pFile)\n  ){\n    osCloseHandle(h);\n    sqlite3_free(zConverted);\n    return SQLITE_CANTOPEN_BKPT;\n  }\n  if( isTemp ){\n    pFile->zDeleteOnClose = zConverted;\n  }else\n#endif\n  {\n    sqlite3_free(zConverted);\n  }\n\n  OpenCounter(+1);\n  return rc;\n}\n\n/*\n** Delete the named file.\n**\n** Note that Windows does not allow a file to be deleted if some other\n** process has it open.  Sometimes a virus scanner or indexing program\n** will open a journal file shortly after it is created in order to do\n** whatever it does.  While this other process is holding the\n** file open, we will be unable to delete it.  To work around this\n** problem, we delay 100 milliseconds and try to delete again.  Up\n** to MX_DELETION_ATTEMPTs deletion attempts are run before giving\n** up and returning an error.\n*/\nstatic int winDelete(\n  sqlite3_vfs *pVfs,          /* Not used on win32 */\n  const char *zFilename,      /* Name of file to delete */\n  int syncDir                 /* Not used on win32 */\n){\n  int cnt = 0;\n  int rc;\n  DWORD attr;\n  DWORD lastErrno;\n  void *zConverted;\n  UNUSED_PARAMETER(pVfs);\n  UNUSED_PARAMETER(syncDir);\n\n  SimulateIOError(return SQLITE_IOERR_DELETE);\n  zConverted = convertUtf8Filename(zFilename);\n  if( zConverted==0 ){\n    return SQLITE_IOERR_NOMEM;\n  }\n  if( isNT() ){\n    do {\n#if SQLITE_OS_WINRT\n      WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n      memset(&sAttrData, 0, sizeof(sAttrData));\n      if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,\n                                  &sAttrData) ){\n        attr = sAttrData.dwFileAttributes;\n      }else{\n        rc = SQLITE_OK; /* Already gone? */\n        break;\n      }\n#else\n      attr = osGetFileAttributesW(zConverted);\n#endif\n      if ( attr==INVALID_FILE_ATTRIBUTES ){\n        rc = SQLITE_OK; /* Already gone? */\n        break;\n      }\n      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){\n        rc = SQLITE_ERROR; /* Files only. */\n        break;\n      }\n      if ( osDeleteFileW(zConverted) ){\n        rc = SQLITE_OK; /* Deleted OK. */\n        break;\n      }\n      if ( !retryIoerr(&cnt, &lastErrno) ){\n        rc = SQLITE_ERROR; /* No more retries. */\n        break;\n      }\n    } while(1);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    do {\n      attr = osGetFileAttributesA(zConverted);\n      if ( attr==INVALID_FILE_ATTRIBUTES ){\n        rc = SQLITE_OK; /* Already gone? */\n        break;\n      }\n      if ( attr&FILE_ATTRIBUTE_DIRECTORY ){\n        rc = SQLITE_ERROR; /* Files only. */\n        break;\n      }\n      if ( osDeleteFileA(zConverted) ){\n        rc = SQLITE_OK; /* Deleted OK. */\n        break;\n      }\n      if ( !retryIoerr(&cnt, &lastErrno) ){\n        rc = SQLITE_ERROR; /* No more retries. */\n        break;\n      }\n    } while(1);\n  }\n#endif\n  if( rc ){\n    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,\n             \"winDelete\", zFilename);\n  }else{\n    logIoerr(cnt);\n  }\n  sqlite3_free(zConverted);\n  OSTRACE((\"DELETE \\\"%s\\\" %s\\n\", zFilename, (rc ? \"failed\" : \"ok\" )));\n  return rc;\n}\n\n/*\n** Check the existance and status of a file.\n*/\nstatic int winAccess(\n  sqlite3_vfs *pVfs,         /* Not used on win32 */\n  const char *zFilename,     /* Name of file to check */\n  int flags,                 /* Type of test to make on this file */\n  int *pResOut               /* OUT: Result */\n){\n  DWORD attr;\n  int rc = 0;\n  DWORD lastErrno;\n  void *zConverted;\n  UNUSED_PARAMETER(pVfs);\n\n  SimulateIOError( return SQLITE_IOERR_ACCESS; );\n  zConverted = convertUtf8Filename(zFilename);\n  if( zConverted==0 ){\n    return SQLITE_IOERR_NOMEM;\n  }\n  if( isNT() ){\n    int cnt = 0;\n    WIN32_FILE_ATTRIBUTE_DATA sAttrData;\n    memset(&sAttrData, 0, sizeof(sAttrData));\n    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,\n                             GetFileExInfoStandard, \n                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}\n    if( rc ){\n      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file\n      ** as if it does not exist.\n      */\n      if(    flags==SQLITE_ACCESS_EXISTS\n          && sAttrData.nFileSizeHigh==0 \n          && sAttrData.nFileSizeLow==0 ){\n        attr = INVALID_FILE_ATTRIBUTES;\n      }else{\n        attr = sAttrData.dwFileAttributes;\n      }\n    }else{\n      logIoerr(cnt);\n      if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){\n        winLogError(SQLITE_IOERR_ACCESS, lastErrno, \"winAccess\", zFilename);\n        sqlite3_free(zConverted);\n        return SQLITE_IOERR_ACCESS;\n      }else{\n        attr = INVALID_FILE_ATTRIBUTES;\n      }\n    }\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    attr = osGetFileAttributesA((char*)zConverted);\n  }\n#endif\n  sqlite3_free(zConverted);\n  switch( flags ){\n    case SQLITE_ACCESS_READ:\n    case SQLITE_ACCESS_EXISTS:\n      rc = attr!=INVALID_FILE_ATTRIBUTES;\n      break;\n    case SQLITE_ACCESS_READWRITE:\n      rc = attr!=INVALID_FILE_ATTRIBUTES &&\n             (attr & FILE_ATTRIBUTE_READONLY)==0;\n      break;\n    default:\n      assert(!\"Invalid flags argument\");\n  }\n  *pResOut = rc;\n  return SQLITE_OK;\n}\n\n\n/*\n** Returns non-zero if the specified path name should be used verbatim.  If\n** non-zero is returned from this function, the calling function must simply\n** use the provided path name verbatim -OR- resolve it into a full path name\n** using the GetFullPathName Win32 API function (if available).\n*/\nstatic BOOL winIsVerbatimPathname(\n  const char *zPathname\n){\n  /*\n  ** If the path name starts with a forward slash or a backslash, it is either\n  ** a legal UNC name, a volume relative path, or an absolute path name in the\n  ** \"Unix\" format on Windows.  There is no easy way to differentiate between\n  ** the final two cases; therefore, we return the safer return value of TRUE\n  ** so that callers of this function will simply use it verbatim.\n  */\n  if ( zPathname[0]=='/' || zPathname[0]=='\\\\' ){\n    return TRUE;\n  }\n\n  /*\n  ** If the path name starts with a letter and a colon it is either a volume\n  ** relative path or an absolute path.  Callers of this function must not\n  ** attempt to treat it as a relative path name (i.e. they should simply use\n  ** it verbatim).\n  */\n  if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){\n    return TRUE;\n  }\n\n  /*\n  ** If we get to this point, the path name should almost certainly be a purely\n  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).\n  */\n  return FALSE;\n}\n\n/*\n** Turn a relative pathname into a full pathname.  Write the full\n** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname\n** bytes in size.\n*/\nstatic int winFullPathname(\n  sqlite3_vfs *pVfs,            /* Pointer to vfs object */\n  const char *zRelative,        /* Possibly relative input path */\n  int nFull,                    /* Size of output buffer in bytes */\n  char *zFull                   /* Output buffer */\n){\n  \n#if defined(__CYGWIN__)\n  SimulateIOError( return SQLITE_ERROR );\n  UNUSED_PARAMETER(nFull);\n  assert( pVfs->mxPathname>=MAX_PATH );\n  assert( nFull>=pVfs->mxPathname );\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a slash.\n    */\n    char zOut[MAX_PATH+1];\n    memset(zOut, 0, MAX_PATH+1);\n    cygwin_conv_to_win32_path(zRelative, zOut); /* POSIX to Win32 */\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\\\\%s\",\n                     sqlite3_data_directory, zOut);\n  }else{\n    /*\n    ** NOTE: The Cygwin docs state that the maximum length needed\n    **       for the buffer passed to cygwin_conv_to_full_win32_path\n    **       is MAX_PATH.\n    */\n    cygwin_conv_to_full_win32_path(zRelative, zFull);\n  }\n  return SQLITE_OK;\n#endif\n\n#if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)\n  SimulateIOError( return SQLITE_ERROR );\n  /* WinCE has no concept of a relative pathname, or so I am told. */\n  /* WinRT has no way to convert a relative path to an absolute one. */\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a backslash.\n    */\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\\\\%s\",\n                     sqlite3_data_directory, zRelative);\n  }else{\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\", zRelative);\n  }\n  return SQLITE_OK;\n#endif\n\n#if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)\n  int nByte;\n  void *zConverted;\n  char *zOut;\n\n  /* If this path name begins with \"/X:\", where \"X\" is any alphabetic\n  ** character, discard the initial \"/\" from the pathname.\n  */\n  if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){\n    zRelative++;\n  }\n\n  /* It's odd to simulate an io-error here, but really this is just\n  ** using the io-error infrastructure to test that SQLite handles this\n  ** function failing. This function could fail if, for example, the\n  ** current working directory has been unlinked.\n  */\n  SimulateIOError( return SQLITE_ERROR );\n  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){\n    /*\n    ** NOTE: We are dealing with a relative path name and the data\n    **       directory has been set.  Therefore, use it as the basis\n    **       for converting the relative path name to an absolute\n    **       one by prepending the data directory and a backslash.\n    */\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\\\\%s\",\n                     sqlite3_data_directory, zRelative);\n    return SQLITE_OK;\n  }\n  zConverted = convertUtf8Filename(zRelative);\n  if( zConverted==0 ){\n    return SQLITE_IOERR_NOMEM;\n  }\n  if( isNT() ){\n    LPWSTR zTemp;\n    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;\n    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );\n    if( zTemp==0 ){\n      sqlite3_free(zConverted);\n      return SQLITE_IOERR_NOMEM;\n    }\n    osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);\n    sqlite3_free(zConverted);\n    zOut = unicodeToUtf8(zTemp);\n    sqlite3_free(zTemp);\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    char *zTemp;\n    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;\n    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );\n    if( zTemp==0 ){\n      sqlite3_free(zConverted);\n      return SQLITE_IOERR_NOMEM;\n    }\n    osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);\n    sqlite3_free(zConverted);\n    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);\n    sqlite3_free(zTemp);\n  }\n#endif\n  if( zOut ){\n    sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, \"%s\", zOut);\n    sqlite3_free(zOut);\n    return SQLITE_OK;\n  }else{\n    return SQLITE_IOERR_NOMEM;\n  }\n#endif\n}\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** Interfaces for opening a shared library, finding entry points\n** within the shared library, and closing the shared library.\n*/\n/*\n** Interfaces for opening a shared library, finding entry points\n** within the shared library, and closing the shared library.\n*/\nstatic void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){\n  HANDLE h;\n  void *zConverted = convertUtf8Filename(zFilename);\n  UNUSED_PARAMETER(pVfs);\n  if( zConverted==0 ){\n    return 0;\n  }\n  if( isNT() ){\n#if SQLITE_OS_WINRT\n    h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);\n#else\n    h = osLoadLibraryW((LPCWSTR)zConverted);\n#endif\n  }\n#ifdef SQLITE_WIN32_HAS_ANSI\n  else{\n    h = osLoadLibraryA((char*)zConverted);\n  }\n#endif\n  sqlite3_free(zConverted);\n  return (void*)h;\n}\nstatic void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){\n  UNUSED_PARAMETER(pVfs);\n  getLastErrorMsg(osGetLastError(), nBuf, zBufOut);\n}\nstatic void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){\n  UNUSED_PARAMETER(pVfs);\n  return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);\n}\nstatic void winDlClose(sqlite3_vfs *pVfs, void *pHandle){\n  UNUSED_PARAMETER(pVfs);\n  osFreeLibrary((HANDLE)pHandle);\n}\n#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */\n  #define winDlOpen  0\n  #define winDlError 0\n  #define winDlSym   0\n  #define winDlClose 0\n#endif\n\n\n/*\n** Write up to nBuf bytes of randomness into zBuf.\n*/\nstatic int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n  int n = 0;\n  UNUSED_PARAMETER(pVfs);\n#if defined(SQLITE_TEST)\n  n = nBuf;\n  memset(zBuf, 0, nBuf);\n#else\n  if( sizeof(SYSTEMTIME)<=nBuf-n ){\n    SYSTEMTIME x;\n    osGetSystemTime(&x);\n    memcpy(&zBuf[n], &x, sizeof(x));\n    n += sizeof(x);\n  }\n  if( sizeof(DWORD)<=nBuf-n ){\n    DWORD pid = osGetCurrentProcessId();\n    memcpy(&zBuf[n], &pid, sizeof(pid));\n    n += sizeof(pid);\n  }\n#if SQLITE_OS_WINRT\n  if( sizeof(ULONGLONG)<=nBuf-n ){\n    ULONGLONG cnt = osGetTickCount64();\n    memcpy(&zBuf[n], &cnt, sizeof(cnt));\n    n += sizeof(cnt);\n  }\n#else\n  if( sizeof(DWORD)<=nBuf-n ){\n    DWORD cnt = osGetTickCount();\n    memcpy(&zBuf[n], &cnt, sizeof(cnt));\n    n += sizeof(cnt);\n  }\n#endif\n  if( sizeof(LARGE_INTEGER)<=nBuf-n ){\n    LARGE_INTEGER i;\n    osQueryPerformanceCounter(&i);\n    memcpy(&zBuf[n], &i, sizeof(i));\n    n += sizeof(i);\n  }\n#endif\n  return n;\n}\n\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n*/\nstatic int winSleep(sqlite3_vfs *pVfs, int microsec){\n  sqlite3_win32_sleep((microsec+999)/1000);\n  UNUSED_PARAMETER(pVfs);\n  return ((microsec+999)/1000)*1000;\n}\n\n/*\n** The following variable, if set to a non-zero value, is interpreted as\n** the number of seconds since 1970 and is used to set the result of\n** sqlite3OsCurrentTime() during testing.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */\n#endif\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write into *piNow\n** the current time and date as a Julian Day number times 86_400_000.  In\n** other words, write into *piNow the number of milliseconds since the Julian\n** epoch of noon in Greenwich on November 24, 4714 B.C according to the\n** proleptic Gregorian calendar.\n**\n** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date \n** cannot be found.\n*/\nstatic int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){\n  /* FILETIME structure is a 64-bit value representing the number of \n     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). \n  */\n  FILETIME ft;\n  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;\n#ifdef SQLITE_TEST\n  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;\n#endif\n  /* 2^32 - to avoid use of LL and warnings in gcc */\n  static const sqlite3_int64 max32BitValue = \n      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;\n\n#if SQLITE_OS_WINCE\n  SYSTEMTIME time;\n  osGetSystemTime(&time);\n  /* if SystemTimeToFileTime() fails, it returns zero. */\n  if (!osSystemTimeToFileTime(&time,&ft)){\n    return SQLITE_ERROR;\n  }\n#else\n  osGetSystemTimeAsFileTime( &ft );\n#endif\n\n  *piNow = winFiletimeEpoch +\n            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + \n               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;\n\n#ifdef SQLITE_TEST\n  if( sqlite3_current_time ){\n    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;\n  }\n#endif\n  UNUSED_PARAMETER(pVfs);\n  return SQLITE_OK;\n}\n\n/*\n** Find the current time (in Universal Coordinated Time).  Write the\n** current time and date as a Julian Day number into *prNow and\n** return 0.  Return 1 if the time and date cannot be found.\n*/\nstatic int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){\n  int rc;\n  sqlite3_int64 i;\n  rc = winCurrentTimeInt64(pVfs, &i);\n  if( !rc ){\n    *prNow = i/86400000.0;\n  }\n  return rc;\n}\n\n/*\n** The idea is that this function works like a combination of\n** GetLastError() and FormatMessage() on Windows (or errno and\n** strerror_r() on Unix). After an error is returned by an OS\n** function, SQLite calls this function with zBuf pointing to\n** a buffer of nBuf bytes. The OS layer should populate the\n** buffer with a nul-terminated UTF-8 encoded error message\n** describing the last IO error to have occurred within the calling\n** thread.\n**\n** If the error message is too large for the supplied buffer,\n** it should be truncated. The return value of xGetLastError\n** is zero if the error message fits in the buffer, or non-zero\n** otherwise (if the message was truncated). If non-zero is returned,\n** then it is not necessary to include the nul-terminator character\n** in the output buffer.\n**\n** Not supplying an error message will have no adverse effect\n** on SQLite. It is fine to have an implementation that never\n** returns an error message:\n**\n**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n**     assert(zBuf[0]=='\\0');\n**     return 0;\n**   }\n**\n** However if an error message is supplied, it will be incorporated\n** by sqlite into the error message available to the user using\n** sqlite3_errmsg(), possibly making IO errors easier to debug.\n*/\nstatic int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){\n  UNUSED_PARAMETER(pVfs);\n  return getLastErrorMsg(osGetLastError(), nBuf, zBuf);\n}\n\n/*\n** Initialize and deinitialize the operating system interface.\n*/\nSQLITE_API int sqlite3_os_init(void){\n  static sqlite3_vfs winVfs = {\n    3,                   /* iVersion */\n    sizeof(winFile),     /* szOsFile */\n    MAX_PATH,            /* mxPathname */\n    0,                   /* pNext */\n    \"win32\",             /* zName */\n    0,                   /* pAppData */\n    winOpen,             /* xOpen */\n    winDelete,           /* xDelete */\n    winAccess,           /* xAccess */\n    winFullPathname,     /* xFullPathname */\n    winDlOpen,           /* xDlOpen */\n    winDlError,          /* xDlError */\n    winDlSym,            /* xDlSym */\n    winDlClose,          /* xDlClose */\n    winRandomness,       /* xRandomness */\n    winSleep,            /* xSleep */\n    winCurrentTime,      /* xCurrentTime */\n    winGetLastError,     /* xGetLastError */\n    winCurrentTimeInt64, /* xCurrentTimeInt64 */\n    winSetSystemCall,    /* xSetSystemCall */\n    winGetSystemCall,    /* xGetSystemCall */\n    winNextSystemCall,   /* xNextSystemCall */\n  };\n\n  /* Double-check that the aSyscall[] array has been constructed\n  ** correctly.  See ticket [bb3a86e890c8e96ab] */\n  assert( ArraySize(aSyscall)==73 );\n\n#ifndef SQLITE_OMIT_WAL\n  /* get memory map allocation granularity */\n  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));\n#if SQLITE_OS_WINRT\n  osGetNativeSystemInfo(&winSysInfo);\n#else\n  osGetSystemInfo(&winSysInfo);\n#endif\n  assert(winSysInfo.dwAllocationGranularity > 0);\n#endif\n\n  sqlite3_vfs_register(&winVfs, 1);\n  return SQLITE_OK; \n}\n\nSQLITE_API int sqlite3_os_end(void){ \n#if SQLITE_OS_WINRT\n  if( sleepObj != NULL ){\n    osCloseHandle(sleepObj);\n    sleepObj = NULL;\n  }\n#endif\n  return SQLITE_OK;\n}\n\n#endif /* SQLITE_OS_WIN */\n\n/************** End of os_win.c **********************************************/\n/************** Begin file bitvec.c ******************************************/\n/*\n** 2008 February 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements an object that represents a fixed-length\n** bitmap.  Bits are numbered starting with 1.\n**\n** A bitmap is used to record which pages of a database file have been\n** journalled during a transaction, or which pages have the \"dont-write\"\n** property.  Usually only a few pages are meet either condition.\n** So the bitmap is usually sparse and has low cardinality.\n** But sometimes (for example when during a DROP of a large table) most\n** or all of the pages in a database can get journalled.  In those cases, \n** the bitmap becomes dense with high cardinality.  The algorithm needs \n** to handle both cases well.\n**\n** The size of the bitmap is fixed when the object is created.\n**\n** All bits are clear when the bitmap is created.  Individual bits\n** may be set or cleared one at a time.\n**\n** Test operations are about 100 times more common that set operations.\n** Clear operations are exceedingly rare.  There are usually between\n** 5 and 500 set operations per Bitvec object, though the number of sets can\n** sometimes grow into tens of thousands or larger.  The size of the\n** Bitvec object is the number of pages in the database file at the\n** start of a transaction, and is thus usually less than a few thousand,\n** but can be as large as 2 billion for a really big database.\n*/\n\n/* Size of the Bitvec structure in bytes. */\n#define BITVEC_SZ        512\n\n/* Round the union size down to the nearest pointer boundary, since that's how \n** it will be aligned within the Bitvec struct. */\n#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))\n\n/* Type of the array \"element\" for the bitmap representation. \n** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. \n** Setting this to the \"natural word\" size of your CPU may improve\n** performance. */\n#define BITVEC_TELEM     u8\n/* Size, in bits, of the bitmap element. */\n#define BITVEC_SZELEM    8\n/* Number of elements in a bitmap array. */\n#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))\n/* Number of bits in the bitmap array. */\n#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)\n\n/* Number of u32 values in hash table. */\n#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))\n/* Maximum number of entries in hash table before \n** sub-dividing and re-hashing. */\n#define BITVEC_MXHASH    (BITVEC_NINT/2)\n/* Hashing function for the aHash representation.\n** Empirical testing showed that the *37 multiplier \n** (an arbitrary prime)in the hash function provided \n** no fewer collisions than the no-op *1. */\n#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)\n\n#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))\n\n\n/*\n** A bitmap is an instance of the following structure.\n**\n** This bitmap records the existance of zero or more bits\n** with values between 1 and iSize, inclusive.\n**\n** There are three possible representations of the bitmap.\n** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight\n** bitmap.  The least significant bit is bit 1.\n**\n** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is\n** a hash table that will hold up to BITVEC_MXHASH distinct values.\n**\n** Otherwise, the value i is redirected into one of BITVEC_NPTR\n** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap\n** handles up to iDivisor separate values of i.  apSub[0] holds\n** values between 1 and iDivisor.  apSub[1] holds values between\n** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between\n** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized\n** to hold deal with values between 1 and iDivisor.\n*/\nstruct Bitvec {\n  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */\n  u32 nSet;       /* Number of bits that are set - only valid for aHash\n                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,\n                  ** this would be 125. */\n  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */\n                  /* Should >=0 for apSub element. */\n                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */\n                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */\n  union {\n    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */\n    u32 aHash[BITVEC_NINT];      /* Hash table representation */\n    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */\n  } u;\n};\n\n/*\n** Create a new bitmap object able to handle bits between 0 and iSize,\n** inclusive.  Return a pointer to the new object.  Return NULL if \n** malloc fails.\n*/\nSQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){\n  Bitvec *p;\n  assert( sizeof(*p)==BITVEC_SZ );\n  p = sqlite3MallocZero( sizeof(*p) );\n  if( p ){\n    p->iSize = iSize;\n  }\n  return p;\n}\n\n/*\n** Check to see if the i-th bit is set.  Return true or false.\n** If p is NULL (if the bitmap has not been created) or if\n** i is out of range, then return false.\n*/\nSQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){\n  if( p==0 ) return 0;\n  if( i>p->iSize || i==0 ) return 0;\n  i--;\n  while( p->iDivisor ){\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    p = p->u.apSub[bin];\n    if (!p) {\n      return 0;\n    }\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;\n  } else{\n    u32 h = BITVEC_HASH(i++);\n    while( p->u.aHash[h] ){\n      if( p->u.aHash[h]==i ) return 1;\n      h = (h+1) % BITVEC_NINT;\n    }\n    return 0;\n  }\n}\n\n/*\n** Set the i-th bit.  Return 0 on success and an error code if\n** anything goes wrong.\n**\n** This routine might cause sub-bitmaps to be allocated.  Failing\n** to get the memory needed to hold the sub-bitmap is the only\n** that can go wrong with an insert, assuming p and i are valid.\n**\n** The calling function must ensure that p is a valid Bitvec object\n** and that the value for \"i\" is within range of the Bitvec object.\n** Otherwise the behavior is undefined.\n*/\nSQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){\n  u32 h;\n  if( p==0 ) return SQLITE_OK;\n  assert( i>0 );\n  assert( i<=p->iSize );\n  i--;\n  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    if( p->u.apSub[bin]==0 ){\n      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );\n      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;\n    }\n    p = p->u.apSub[bin];\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));\n    return SQLITE_OK;\n  }\n  h = BITVEC_HASH(i++);\n  /* if there wasn't a hash collision, and this doesn't */\n  /* completely fill the hash, then just add it without */\n  /* worring about sub-dividing and re-hashing. */\n  if( !p->u.aHash[h] ){\n    if (p->nSet<(BITVEC_NINT-1)) {\n      goto bitvec_set_end;\n    } else {\n      goto bitvec_set_rehash;\n    }\n  }\n  /* there was a collision, check to see if it's already */\n  /* in hash, if not, try to find a spot for it */\n  do {\n    if( p->u.aHash[h]==i ) return SQLITE_OK;\n    h++;\n    if( h>=BITVEC_NINT ) h = 0;\n  } while( p->u.aHash[h] );\n  /* we didn't find it in the hash.  h points to the first */\n  /* available free spot. check to see if this is going to */\n  /* make our hash too \"full\".  */\nbitvec_set_rehash:\n  if( p->nSet>=BITVEC_MXHASH ){\n    unsigned int j;\n    int rc;\n    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));\n    if( aiValues==0 ){\n      return SQLITE_NOMEM;\n    }else{\n      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));\n      memset(p->u.apSub, 0, sizeof(p->u.apSub));\n      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;\n      rc = sqlite3BitvecSet(p, i);\n      for(j=0; j<BITVEC_NINT; j++){\n        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);\n      }\n      sqlite3StackFree(0, aiValues);\n      return rc;\n    }\n  }\nbitvec_set_end:\n  p->nSet++;\n  p->u.aHash[h] = i;\n  return SQLITE_OK;\n}\n\n/*\n** Clear the i-th bit.\n**\n** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage\n** that BitvecClear can use to rebuilt its hash table.\n*/\nSQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){\n  if( p==0 ) return;\n  assert( i>0 );\n  i--;\n  while( p->iDivisor ){\n    u32 bin = i/p->iDivisor;\n    i = i%p->iDivisor;\n    p = p->u.apSub[bin];\n    if (!p) {\n      return;\n    }\n  }\n  if( p->iSize<=BITVEC_NBIT ){\n    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));\n  }else{\n    unsigned int j;\n    u32 *aiValues = pBuf;\n    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));\n    memset(p->u.aHash, 0, sizeof(p->u.aHash));\n    p->nSet = 0;\n    for(j=0; j<BITVEC_NINT; j++){\n      if( aiValues[j] && aiValues[j]!=(i+1) ){\n        u32 h = BITVEC_HASH(aiValues[j]-1);\n        p->nSet++;\n        while( p->u.aHash[h] ){\n          h++;\n          if( h>=BITVEC_NINT ) h = 0;\n        }\n        p->u.aHash[h] = aiValues[j];\n      }\n    }\n  }\n}\n\n/*\n** Destroy a bitmap object.  Reclaim all memory used.\n*/\nSQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){\n  if( p==0 ) return;\n  if( p->iDivisor ){\n    unsigned int i;\n    for(i=0; i<BITVEC_NPTR; i++){\n      sqlite3BitvecDestroy(p->u.apSub[i]);\n    }\n  }\n  sqlite3_free(p);\n}\n\n/*\n** Return the value of the iSize parameter specified when Bitvec *p\n** was created.\n*/\nSQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){\n  return p->iSize;\n}\n\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n/*\n** Let V[] be an array of unsigned characters sufficient to hold\n** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.\n** Then the following macros can be used to set, clear, or test\n** individual bits within V.\n*/\n#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))\n#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))\n#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0\n\n/*\n** This routine runs an extensive test of the Bitvec code.\n**\n** The input is an array of integers that acts as a program\n** to test the Bitvec.  The integers are opcodes followed\n** by 0, 1, or 3 operands, depending on the opcode.  Another\n** opcode follows immediately after the last operand.\n**\n** There are 6 opcodes numbered from 0 through 5.  0 is the\n** \"halt\" opcode and causes the test to end.\n**\n**    0          Halt and return the number of errors\n**    1 N S X    Set N bits beginning with S and incrementing by X\n**    2 N S X    Clear N bits beginning with S and incrementing by X\n**    3 N        Set N randomly chosen bits\n**    4 N        Clear N randomly chosen bits\n**    5 N S X    Set N bits from S increment X in array only, not in bitvec\n**\n** The opcodes 1 through 4 perform set and clear operations are performed\n** on both a Bitvec object and on a linear array of bits obtained from malloc.\n** Opcode 5 works on the linear array only, not on the Bitvec.\n** Opcode 5 is used to deliberately induce a fault in order to\n** confirm that error detection works.\n**\n** At the conclusion of the test the linear array is compared\n** against the Bitvec object.  If there are any differences,\n** an error is returned.  If they are the same, zero is returned.\n**\n** If a memory allocation error occurs, return -1.\n*/\nSQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){\n  Bitvec *pBitvec = 0;\n  unsigned char *pV = 0;\n  int rc = -1;\n  int i, nx, pc, op;\n  void *pTmpSpace;\n\n  /* Allocate the Bitvec to be tested and a linear array of\n  ** bits to act as the reference */\n  pBitvec = sqlite3BitvecCreate( sz );\n  pV = sqlite3MallocZero( (sz+7)/8 + 1 );\n  pTmpSpace = sqlite3_malloc(BITVEC_SZ);\n  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;\n\n  /* NULL pBitvec tests */\n  sqlite3BitvecSet(0, 1);\n  sqlite3BitvecClear(0, 1, pTmpSpace);\n\n  /* Run the program */\n  pc = 0;\n  while( (op = aOp[pc])!=0 ){\n    switch( op ){\n      case 1:\n      case 2:\n      case 5: {\n        nx = 4;\n        i = aOp[pc+2] - 1;\n        aOp[pc+2] += aOp[pc+3];\n        break;\n      }\n      case 3:\n      case 4: \n      default: {\n        nx = 2;\n        sqlite3_randomness(sizeof(i), &i);\n        break;\n      }\n    }\n    if( (--aOp[pc+1]) > 0 ) nx = 0;\n    pc += nx;\n    i = (i & 0x7fffffff)%sz;\n    if( (op & 1)!=0 ){\n      SETBIT(pV, (i+1));\n      if( op!=5 ){\n        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;\n      }\n    }else{\n      CLEARBIT(pV, (i+1));\n      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);\n    }\n  }\n\n  /* Test to make sure the linear array exactly matches the\n  ** Bitvec object.  Start with the assumption that they do\n  ** match (rc==0).  Change rc to non-zero if a discrepancy\n  ** is found.\n  */\n  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)\n          + sqlite3BitvecTest(pBitvec, 0)\n          + (sqlite3BitvecSize(pBitvec) - sz);\n  for(i=1; i<=sz; i++){\n    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){\n      rc = i;\n      break;\n    }\n  }\n\n  /* Free allocated structure */\nbitvec_end:\n  sqlite3_free(pTmpSpace);\n  sqlite3_free(pV);\n  sqlite3BitvecDestroy(pBitvec);\n  return rc;\n}\n#endif /* SQLITE_OMIT_BUILTIN_TEST */\n\n/************** End of bitvec.c **********************************************/\n/************** Begin file pcache.c ******************************************/\n/*\n** 2008 August 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements that page cache.\n*/\n\n/*\n** A complete page cache is an instance of this structure.\n*/\nstruct PCache {\n  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */\n  PgHdr *pSynced;                     /* Last synced page in dirty page list */\n  int nRef;                           /* Number of referenced pages */\n  int szCache;                        /* Configured cache size */\n  int szPage;                         /* Size of every page in this cache */\n  int szExtra;                        /* Size of extra space for each page */\n  int bPurgeable;                     /* True if pages are on backing store */\n  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */\n  void *pStress;                      /* Argument to xStress */\n  sqlite3_pcache *pCache;             /* Pluggable cache module */\n  PgHdr *pPage1;                      /* Reference to page 1 */\n};\n\n/*\n** Some of the assert() macros in this code are too expensive to run\n** even during normal debugging.  Use them only rarely on long-running\n** tests.  Enable the expensive asserts using the\n** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.\n*/\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n# define expensive_assert(X)  assert(X)\n#else\n# define expensive_assert(X)\n#endif\n\n/********************************** Linked List Management ********************/\n\n#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)\n/*\n** Check that the pCache->pSynced variable is set correctly. If it\n** is not, either fail an assert or return zero. Otherwise, return\n** non-zero. This is only used in debugging builds, as follows:\n**\n**   expensive_assert( pcacheCheckSynced(pCache) );\n*/\nstatic int pcacheCheckSynced(PCache *pCache){\n  PgHdr *p;\n  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){\n    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );\n  }\n  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);\n}\n#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */\n\n/*\n** Remove page pPage from the list of dirty pages.\n*/\nstatic void pcacheRemoveFromDirtyList(PgHdr *pPage){\n  PCache *p = pPage->pCache;\n\n  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );\n  assert( pPage->pDirtyPrev || pPage==p->pDirty );\n\n  /* Update the PCache1.pSynced variable if necessary. */\n  if( p->pSynced==pPage ){\n    PgHdr *pSynced = pPage->pDirtyPrev;\n    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){\n      pSynced = pSynced->pDirtyPrev;\n    }\n    p->pSynced = pSynced;\n  }\n\n  if( pPage->pDirtyNext ){\n    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;\n  }else{\n    assert( pPage==p->pDirtyTail );\n    p->pDirtyTail = pPage->pDirtyPrev;\n  }\n  if( pPage->pDirtyPrev ){\n    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;\n  }else{\n    assert( pPage==p->pDirty );\n    p->pDirty = pPage->pDirtyNext;\n  }\n  pPage->pDirtyNext = 0;\n  pPage->pDirtyPrev = 0;\n\n  expensive_assert( pcacheCheckSynced(p) );\n}\n\n/*\n** Add page pPage to the head of the dirty list (PCache1.pDirty is set to\n** pPage).\n*/\nstatic void pcacheAddToDirtyList(PgHdr *pPage){\n  PCache *p = pPage->pCache;\n\n  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );\n\n  pPage->pDirtyNext = p->pDirty;\n  if( pPage->pDirtyNext ){\n    assert( pPage->pDirtyNext->pDirtyPrev==0 );\n    pPage->pDirtyNext->pDirtyPrev = pPage;\n  }\n  p->pDirty = pPage;\n  if( !p->pDirtyTail ){\n    p->pDirtyTail = pPage;\n  }\n  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){\n    p->pSynced = pPage;\n  }\n  expensive_assert( pcacheCheckSynced(p) );\n}\n\n/*\n** Wrapper around the pluggable caches xUnpin method. If the cache is\n** being used for an in-memory database, this function is a no-op.\n*/\nstatic void pcacheUnpin(PgHdr *p){\n  PCache *pCache = p->pCache;\n  if( pCache->bPurgeable ){\n    if( p->pgno==1 ){\n      pCache->pPage1 = 0;\n    }\n    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);\n  }\n}\n\n/*************************************************** General Interfaces ******\n**\n** Initialize and shutdown the page cache subsystem. Neither of these \n** functions are threadsafe.\n*/\nSQLITE_PRIVATE int sqlite3PcacheInitialize(void){\n  if( sqlite3GlobalConfig.pcache2.xInit==0 ){\n    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the\n    ** built-in default page cache is used instead of the application defined\n    ** page cache. */\n    sqlite3PCacheSetDefault();\n  }\n  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);\n}\nSQLITE_PRIVATE void sqlite3PcacheShutdown(void){\n  if( sqlite3GlobalConfig.pcache2.xShutdown ){\n    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */\n    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);\n  }\n}\n\n/*\n** Return the size in bytes of a PCache object.\n*/\nSQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }\n\n/*\n** Create a new PCache object. Storage space to hold the object\n** has already been allocated and is passed in as the p pointer. \n** The caller discovers how much space needs to be allocated by \n** calling sqlite3PcacheSize().\n*/\nSQLITE_PRIVATE void sqlite3PcacheOpen(\n  int szPage,                  /* Size of every page */\n  int szExtra,                 /* Extra space associated with each page */\n  int bPurgeable,              /* True if pages are on backing store */\n  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */\n  void *pStress,               /* Argument to xStress */\n  PCache *p                    /* Preallocated space for the PCache */\n){\n  memset(p, 0, sizeof(PCache));\n  p->szPage = szPage;\n  p->szExtra = szExtra;\n  p->bPurgeable = bPurgeable;\n  p->xStress = xStress;\n  p->pStress = pStress;\n  p->szCache = 100;\n}\n\n/*\n** Change the page size for PCache object. The caller must ensure that there\n** are no outstanding page references when this function is called.\n*/\nSQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){\n  assert( pCache->nRef==0 && pCache->pDirty==0 );\n  if( pCache->pCache ){\n    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);\n    pCache->pCache = 0;\n    pCache->pPage1 = 0;\n  }\n  pCache->szPage = szPage;\n}\n\n/*\n** Compute the number of pages of cache requested.\n*/\nstatic int numberOfCachePages(PCache *p){\n  if( p->szCache>=0 ){\n    return p->szCache;\n  }else{\n    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));\n  }\n}\n\n/*\n** Try to obtain a page from the cache.\n*/\nSQLITE_PRIVATE int sqlite3PcacheFetch(\n  PCache *pCache,       /* Obtain the page from this cache */\n  Pgno pgno,            /* Page number to obtain */\n  int createFlag,       /* If true, create page if it does not exist already */\n  PgHdr **ppPage        /* Write the page here */\n){\n  sqlite3_pcache_page *pPage = 0;\n  PgHdr *pPgHdr = 0;\n  int eCreate;\n\n  assert( pCache!=0 );\n  assert( createFlag==1 || createFlag==0 );\n  assert( pgno>0 );\n\n  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,\n  ** allocate it now.\n  */\n  if( !pCache->pCache && createFlag ){\n    sqlite3_pcache *p;\n    p = sqlite3GlobalConfig.pcache2.xCreate(\n        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable\n    );\n    if( !p ){\n      return SQLITE_NOMEM;\n    }\n    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));\n    pCache->pCache = p;\n  }\n\n  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));\n  if( pCache->pCache ){\n    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);\n  }\n\n  if( !pPage && eCreate==1 ){\n    PgHdr *pPg;\n\n    /* Find a dirty page to write-out and recycle. First try to find a \n    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC\n    ** cleared), but if that is not possible settle for any other \n    ** unreferenced dirty page.\n    */\n    expensive_assert( pcacheCheckSynced(pCache) );\n    for(pPg=pCache->pSynced; \n        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); \n        pPg=pPg->pDirtyPrev\n    );\n    pCache->pSynced = pPg;\n    if( !pPg ){\n      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);\n    }\n    if( pPg ){\n      int rc;\n#ifdef SQLITE_LOG_CACHE_SPILL\n      sqlite3_log(SQLITE_FULL, \n                  \"spill page %d making room for %d - cache used: %d/%d\",\n                  pPg->pgno, pgno,\n                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),\n                  numberOfCachePages(pCache));\n#endif\n      rc = pCache->xStress(pCache->pStress, pPg);\n      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){\n        return rc;\n      }\n    }\n\n    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);\n  }\n\n  if( pPage ){\n    pPgHdr = (PgHdr *)pPage->pExtra;\n\n    if( !pPgHdr->pPage ){\n      memset(pPgHdr, 0, sizeof(PgHdr));\n      pPgHdr->pPage = pPage;\n      pPgHdr->pData = pPage->pBuf;\n      pPgHdr->pExtra = (void *)&pPgHdr[1];\n      memset(pPgHdr->pExtra, 0, pCache->szExtra);\n      pPgHdr->pCache = pCache;\n      pPgHdr->pgno = pgno;\n    }\n    assert( pPgHdr->pCache==pCache );\n    assert( pPgHdr->pgno==pgno );\n    assert( pPgHdr->pData==pPage->pBuf );\n    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );\n\n    if( 0==pPgHdr->nRef ){\n      pCache->nRef++;\n    }\n    pPgHdr->nRef++;\n    if( pgno==1 ){\n      pCache->pPage1 = pPgHdr;\n    }\n  }\n  *ppPage = pPgHdr;\n  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;\n}\n\n/*\n** Decrement the reference count on a page. If the page is clean and the\n** reference count drops to 0, then it is made elible for recycling.\n*/\nSQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){\n  assert( p->nRef>0 );\n  p->nRef--;\n  if( p->nRef==0 ){\n    PCache *pCache = p->pCache;\n    pCache->nRef--;\n    if( (p->flags&PGHDR_DIRTY)==0 ){\n      pcacheUnpin(p);\n    }else{\n      /* Move the page to the head of the dirty list. */\n      pcacheRemoveFromDirtyList(p);\n      pcacheAddToDirtyList(p);\n    }\n  }\n}\n\n/*\n** Increase the reference count of a supplied page by 1.\n*/\nSQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){\n  assert(p->nRef>0);\n  p->nRef++;\n}\n\n/*\n** Drop a page from the cache. There must be exactly one reference to the\n** page. This function deletes that reference, so after it returns the\n** page pointed to by p is invalid.\n*/\nSQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){\n  PCache *pCache;\n  assert( p->nRef==1 );\n  if( p->flags&PGHDR_DIRTY ){\n    pcacheRemoveFromDirtyList(p);\n  }\n  pCache = p->pCache;\n  pCache->nRef--;\n  if( p->pgno==1 ){\n    pCache->pPage1 = 0;\n  }\n  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);\n}\n\n/*\n** Make sure the page is marked as dirty. If it isn't dirty already,\n** make it so.\n*/\nSQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){\n  p->flags &= ~PGHDR_DONT_WRITE;\n  assert( p->nRef>0 );\n  if( 0==(p->flags & PGHDR_DIRTY) ){\n    p->flags |= PGHDR_DIRTY;\n    pcacheAddToDirtyList( p);\n  }\n}\n\n/*\n** Make sure the page is marked as clean. If it isn't clean already,\n** make it so.\n*/\nSQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){\n  if( (p->flags & PGHDR_DIRTY) ){\n    pcacheRemoveFromDirtyList(p);\n    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);\n    if( p->nRef==0 ){\n      pcacheUnpin(p);\n    }\n  }\n}\n\n/*\n** Make every page in the cache clean.\n*/\nSQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){\n  PgHdr *p;\n  while( (p = pCache->pDirty)!=0 ){\n    sqlite3PcacheMakeClean(p);\n  }\n}\n\n/*\n** Clear the PGHDR_NEED_SYNC flag from all dirty pages.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){\n  PgHdr *p;\n  for(p=pCache->pDirty; p; p=p->pDirtyNext){\n    p->flags &= ~PGHDR_NEED_SYNC;\n  }\n  pCache->pSynced = pCache->pDirtyTail;\n}\n\n/*\n** Change the page number of page p to newPgno. \n*/\nSQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){\n  PCache *pCache = p->pCache;\n  assert( p->nRef>0 );\n  assert( newPgno>0 );\n  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);\n  p->pgno = newPgno;\n  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){\n    pcacheRemoveFromDirtyList(p);\n    pcacheAddToDirtyList(p);\n  }\n}\n\n/*\n** Drop every cache entry whose page number is greater than \"pgno\". The\n** caller must ensure that there are no outstanding references to any pages\n** other than page 1 with a page number greater than pgno.\n**\n** If there is a reference to page 1 and the pgno parameter passed to this\n** function is 0, then the data area associated with page 1 is zeroed, but\n** the page object is not dropped.\n*/\nSQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){\n  if( pCache->pCache ){\n    PgHdr *p;\n    PgHdr *pNext;\n    for(p=pCache->pDirty; p; p=pNext){\n      pNext = p->pDirtyNext;\n      /* This routine never gets call with a positive pgno except right\n      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,\n      ** it must be that pgno==0.\n      */\n      assert( p->pgno>0 );\n      if( ALWAYS(p->pgno>pgno) ){\n        assert( p->flags&PGHDR_DIRTY );\n        sqlite3PcacheMakeClean(p);\n      }\n    }\n    if( pgno==0 && pCache->pPage1 ){\n      memset(pCache->pPage1->pData, 0, pCache->szPage);\n      pgno = 1;\n    }\n    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);\n  }\n}\n\n/*\n** Close a cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){\n  if( pCache->pCache ){\n    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);\n  }\n}\n\n/* \n** Discard the contents of the cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){\n  sqlite3PcacheTruncate(pCache, 0);\n}\n\n/*\n** Merge two lists of pages connected by pDirty and in pgno order.\n** Do not both fixing the pDirtyPrev pointers.\n*/\nstatic PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){\n  PgHdr result, *pTail;\n  pTail = &result;\n  while( pA && pB ){\n    if( pA->pgno<pB->pgno ){\n      pTail->pDirty = pA;\n      pTail = pA;\n      pA = pA->pDirty;\n    }else{\n      pTail->pDirty = pB;\n      pTail = pB;\n      pB = pB->pDirty;\n    }\n  }\n  if( pA ){\n    pTail->pDirty = pA;\n  }else if( pB ){\n    pTail->pDirty = pB;\n  }else{\n    pTail->pDirty = 0;\n  }\n  return result.pDirty;\n}\n\n/*\n** Sort the list of pages in accending order by pgno.  Pages are\n** connected by pDirty pointers.  The pDirtyPrev pointers are\n** corrupted by this sort.\n**\n** Since there cannot be more than 2^31 distinct pages in a database,\n** there cannot be more than 31 buckets required by the merge sorter.\n** One extra bucket is added to catch overflow in case something\n** ever changes to make the previous sentence incorrect.\n*/\n#define N_SORT_BUCKET  32\nstatic PgHdr *pcacheSortDirtyList(PgHdr *pIn){\n  PgHdr *a[N_SORT_BUCKET], *p;\n  int i;\n  memset(a, 0, sizeof(a));\n  while( pIn ){\n    p = pIn;\n    pIn = p->pDirty;\n    p->pDirty = 0;\n    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){\n      if( a[i]==0 ){\n        a[i] = p;\n        break;\n      }else{\n        p = pcacheMergeDirtyList(a[i], p);\n        a[i] = 0;\n      }\n    }\n    if( NEVER(i==N_SORT_BUCKET-1) ){\n      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in\n      ** the input list.  But that is impossible.\n      */\n      a[i] = pcacheMergeDirtyList(a[i], p);\n    }\n  }\n  p = a[0];\n  for(i=1; i<N_SORT_BUCKET; i++){\n    p = pcacheMergeDirtyList(p, a[i]);\n  }\n  return p;\n}\n\n/*\n** Return a list of all dirty pages in the cache, sorted by page number.\n*/\nSQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){\n  PgHdr *p;\n  for(p=pCache->pDirty; p; p=p->pDirtyNext){\n    p->pDirty = p->pDirtyNext;\n  }\n  return pcacheSortDirtyList(pCache->pDirty);\n}\n\n/* \n** Return the total number of referenced pages held by the cache.\n*/\nSQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){\n  return pCache->nRef;\n}\n\n/*\n** Return the number of references to the page supplied as an argument.\n*/\nSQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){\n  return p->nRef;\n}\n\n/* \n** Return the total number of pages in the cache.\n*/\nSQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){\n  int nPage = 0;\n  if( pCache->pCache ){\n    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);\n  }\n  return nPage;\n}\n\n#ifdef SQLITE_TEST\n/*\n** Get the suggested cache-size value.\n*/\nSQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){\n  return numberOfCachePages(pCache);\n}\n#endif\n\n/*\n** Set the suggested cache-size value.\n*/\nSQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){\n  pCache->szCache = mxPage;\n  if( pCache->pCache ){\n    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,\n                                           numberOfCachePages(pCache));\n  }\n}\n\n/*\n** Free up as much memory as possible from the page cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){\n  if( pCache->pCache ){\n    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);\n  }\n}\n\n#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)\n/*\n** For all dirty pages currently in the cache, invoke the specified\n** callback. This is only used if the SQLITE_CHECK_PAGES macro is\n** defined.\n*/\nSQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){\n  PgHdr *pDirty;\n  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){\n    xIter(pDirty);\n  }\n}\n#endif\n\n/************** End of pcache.c **********************************************/\n/************** Begin file pcache1.c *****************************************/\n/*\n** 2008 November 05\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements the default page cache implementation (the\n** sqlite3_pcache interface). It also contains part of the implementation\n** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.\n** If the default page cache implementation is overriden, then neither of\n** these two features are available.\n*/\n\n\ntypedef struct PCache1 PCache1;\ntypedef struct PgHdr1 PgHdr1;\ntypedef struct PgFreeslot PgFreeslot;\ntypedef struct PGroup PGroup;\n\n/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set \n** of one or more PCaches that are able to recycle each others unpinned\n** pages when they are under memory pressure.  A PGroup is an instance of\n** the following object.\n**\n** This page cache implementation works in one of two modes:\n**\n**   (1)  Every PCache is the sole member of its own PGroup.  There is\n**        one PGroup per PCache.\n**\n**   (2)  There is a single global PGroup that all PCaches are a member\n**        of.\n**\n** Mode 1 uses more memory (since PCache instances are not able to rob\n** unused pages from other PCaches) but it also operates without a mutex,\n** and is therefore often faster.  Mode 2 requires a mutex in order to be\n** threadsafe, but recycles pages more efficiently.\n**\n** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single\n** PGroup which is the pcache1.grp global variable and its mutex is\n** SQLITE_MUTEX_STATIC_LRU.\n*/\nstruct PGroup {\n  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */\n  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */\n  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */\n  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */\n  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */\n  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */\n};\n\n/* Each page cache is an instance of the following object.  Every\n** open database file (including each in-memory database and each\n** temporary or transient database) has a single page cache which\n** is an instance of this object.\n**\n** Pointers to structures of this type are cast and returned as \n** opaque sqlite3_pcache* handles.\n*/\nstruct PCache1 {\n  /* Cache configuration parameters. Page size (szPage) and the purgeable\n  ** flag (bPurgeable) are set when the cache is created. nMax may be \n  ** modified at any time by a call to the pcache1Cachesize() method.\n  ** The PGroup mutex must be held when accessing nMax.\n  */\n  PGroup *pGroup;                     /* PGroup this cache belongs to */\n  int szPage;                         /* Size of allocated pages in bytes */\n  int szExtra;                        /* Size of extra space in bytes */\n  int bPurgeable;                     /* True if cache is purgeable */\n  unsigned int nMin;                  /* Minimum number of pages reserved */\n  unsigned int nMax;                  /* Configured \"cache_size\" value */\n  unsigned int n90pct;                /* nMax*9/10 */\n  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */\n\n  /* Hash table of all pages. The following variables may only be accessed\n  ** when the accessor is holding the PGroup mutex.\n  */\n  unsigned int nRecyclable;           /* Number of pages in the LRU list */\n  unsigned int nPage;                 /* Total number of pages in apHash */\n  unsigned int nHash;                 /* Number of slots in apHash[] */\n  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */\n};\n\n/*\n** Each cache entry is represented by an instance of the following \n** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of\n** PgHdr1.pCache->szPage bytes is allocated directly before this structure \n** in memory.\n*/\nstruct PgHdr1 {\n  sqlite3_pcache_page page;\n  unsigned int iKey;             /* Key value (page number) */\n  PgHdr1 *pNext;                 /* Next in hash table chain */\n  PCache1 *pCache;               /* Cache that currently owns this page */\n  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */\n  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */\n};\n\n/*\n** Free slots in the allocator used to divide up the buffer provided using\n** the SQLITE_CONFIG_PAGECACHE mechanism.\n*/\nstruct PgFreeslot {\n  PgFreeslot *pNext;  /* Next free slot */\n};\n\n/*\n** Global data used by this cache.\n*/\nstatic SQLITE_WSD struct PCacheGlobal {\n  PGroup grp;                    /* The global PGroup for mode (2) */\n\n  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The\n  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all\n  ** fixed at sqlite3_initialize() time and do not require mutex protection.\n  ** The nFreeSlot and pFree values do require mutex protection.\n  */\n  int isInit;                    /* True if initialized */\n  int szSlot;                    /* Size of each free slot */\n  int nSlot;                     /* The number of pcache slots */\n  int nReserve;                  /* Try to keep nFreeSlot above this */\n  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */\n  /* Above requires no mutex.  Use mutex below for variable that follow. */\n  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */\n  PgFreeslot *pFree;             /* Free page blocks */\n  int nFreeSlot;                 /* Number of unused pcache slots */\n  /* The following value requires a mutex to change.  We skip the mutex on\n  ** reading because (1) most platforms read a 32-bit integer atomically and\n  ** (2) even if an incorrect value is read, no great harm is done since this\n  ** is really just an optimization. */\n  int bUnderPressure;            /* True if low on PAGECACHE memory */\n} pcache1_g;\n\n/*\n** All code in this file should access the global structure above via the\n** alias \"pcache1\". This ensures that the WSD emulation is used when\n** compiling for systems that do not support real WSD.\n*/\n#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))\n\n/*\n** Macros to enter and leave the PCache LRU mutex.\n*/\n#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)\n#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)\n\n/******************************************************************************/\n/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/\n\n/*\n** This function is called during initialization if a static buffer is \n** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE\n** verb to sqlite3_config(). Parameter pBuf points to an allocation large\n** enough to contain 'n' buffers of 'sz' bytes each.\n**\n** This routine is called from sqlite3_initialize() and so it is guaranteed\n** to be serialized already.  There is no need for further mutexing.\n*/\nSQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){\n  if( pcache1.isInit ){\n    PgFreeslot *p;\n    sz = ROUNDDOWN8(sz);\n    pcache1.szSlot = sz;\n    pcache1.nSlot = pcache1.nFreeSlot = n;\n    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);\n    pcache1.pStart = pBuf;\n    pcache1.pFree = 0;\n    pcache1.bUnderPressure = 0;\n    while( n-- ){\n      p = (PgFreeslot*)pBuf;\n      p->pNext = pcache1.pFree;\n      pcache1.pFree = p;\n      pBuf = (void*)&((char*)pBuf)[sz];\n    }\n    pcache1.pEnd = pBuf;\n  }\n}\n\n/*\n** Malloc function used within this file to allocate space from the buffer\n** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no \n** such buffer exists or there is no space left in it, this function falls \n** back to sqlite3Malloc().\n**\n** Multiple threads can run this routine at the same time.  Global variables\n** in pcache1 need to be protected via mutex.\n*/\nstatic void *pcache1Alloc(int nByte){\n  void *p = 0;\n  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );\n  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);\n  if( nByte<=pcache1.szSlot ){\n    sqlite3_mutex_enter(pcache1.mutex);\n    p = (PgHdr1 *)pcache1.pFree;\n    if( p ){\n      pcache1.pFree = pcache1.pFree->pNext;\n      pcache1.nFreeSlot--;\n      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;\n      assert( pcache1.nFreeSlot>=0 );\n      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);\n    }\n    sqlite3_mutex_leave(pcache1.mutex);\n  }\n  if( p==0 ){\n    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get\n    ** it from sqlite3Malloc instead.\n    */\n    p = sqlite3Malloc(nByte);\n#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS\n    if( p ){\n      int sz = sqlite3MallocSize(p);\n      sqlite3_mutex_enter(pcache1.mutex);\n      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);\n      sqlite3_mutex_leave(pcache1.mutex);\n    }\n#endif\n    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);\n  }\n  return p;\n}\n\n/*\n** Free an allocated buffer obtained from pcache1Alloc().\n*/\nstatic int pcache1Free(void *p){\n  int nFreed = 0;\n  if( p==0 ) return 0;\n  if( p>=pcache1.pStart && p<pcache1.pEnd ){\n    PgFreeslot *pSlot;\n    sqlite3_mutex_enter(pcache1.mutex);\n    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);\n    pSlot = (PgFreeslot*)p;\n    pSlot->pNext = pcache1.pFree;\n    pcache1.pFree = pSlot;\n    pcache1.nFreeSlot++;\n    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;\n    assert( pcache1.nFreeSlot<=pcache1.nSlot );\n    sqlite3_mutex_leave(pcache1.mutex);\n  }else{\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );\n    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n    nFreed = sqlite3MallocSize(p);\n#ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS\n    sqlite3_mutex_enter(pcache1.mutex);\n    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);\n    sqlite3_mutex_leave(pcache1.mutex);\n#endif\n    sqlite3_free(p);\n  }\n  return nFreed;\n}\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/*\n** Return the size of a pcache allocation\n*/\nstatic int pcache1MemSize(void *p){\n  if( p>=pcache1.pStart && p<pcache1.pEnd ){\n    return pcache1.szSlot;\n  }else{\n    int iSize;\n    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );\n    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);\n    iSize = sqlite3MallocSize(p);\n    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);\n    return iSize;\n  }\n}\n#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */\n\n/*\n** Allocate a new page object initially associated with cache pCache.\n*/\nstatic PgHdr1 *pcache1AllocPage(PCache1 *pCache){\n  PgHdr1 *p = 0;\n  void *pPg;\n\n  /* The group mutex must be released before pcache1Alloc() is called. This\n  ** is because it may call sqlite3_release_memory(), which assumes that \n  ** this mutex is not held. */\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  pcache1LeaveMutex(pCache->pGroup);\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n  pPg = pcache1Alloc(pCache->szPage);\n  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);\n  if( !pPg || !p ){\n    pcache1Free(pPg);\n    sqlite3_free(p);\n    pPg = 0;\n  }\n#else\n  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);\n  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];\n#endif\n  pcache1EnterMutex(pCache->pGroup);\n\n  if( pPg ){\n    p->page.pBuf = pPg;\n    p->page.pExtra = &p[1];\n    if( pCache->bPurgeable ){\n      pCache->pGroup->nCurrentPage++;\n    }\n    return p;\n  }\n  return 0;\n}\n\n/*\n** Free a page object allocated by pcache1AllocPage().\n**\n** The pointer is allowed to be NULL, which is prudent.  But it turns out\n** that the current implementation happens to never call this routine\n** with a NULL pointer, so we mark the NULL test with ALWAYS().\n*/\nstatic void pcache1FreePage(PgHdr1 *p){\n  if( ALWAYS(p) ){\n    PCache1 *pCache = p->pCache;\n    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );\n    pcache1Free(p->page.pBuf);\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n    sqlite3_free(p);\n#endif\n    if( pCache->bPurgeable ){\n      pCache->pGroup->nCurrentPage--;\n    }\n  }\n}\n\n/*\n** Malloc function used by SQLite to obtain space from the buffer configured\n** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer\n** exists, this function falls back to sqlite3Malloc().\n*/\nSQLITE_PRIVATE void *sqlite3PageMalloc(int sz){\n  return pcache1Alloc(sz);\n}\n\n/*\n** Free an allocated buffer obtained from sqlite3PageMalloc().\n*/\nSQLITE_PRIVATE void sqlite3PageFree(void *p){\n  pcache1Free(p);\n}\n\n\n/*\n** Return true if it desirable to avoid allocating a new page cache\n** entry.\n**\n** If memory was allocated specifically to the page cache using\n** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then\n** it is desirable to avoid allocating a new page cache entry because\n** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient\n** for all page cache needs and we should not need to spill the\n** allocation onto the heap.\n**\n** Or, the heap is used for all page cache memory but the heap is\n** under memory pressure, then again it is desirable to avoid\n** allocating a new page cache entry in order to avoid stressing\n** the heap even further.\n*/\nstatic int pcache1UnderMemoryPressure(PCache1 *pCache){\n  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){\n    return pcache1.bUnderPressure;\n  }else{\n    return sqlite3HeapNearlyFull();\n  }\n}\n\n/******************************************************************************/\n/******** General Implementation Functions ************************************/\n\n/*\n** This function is used to resize the hash table used by the cache passed\n** as the first argument.\n**\n** The PCache mutex must be held when this function is called.\n*/\nstatic int pcache1ResizeHash(PCache1 *p){\n  PgHdr1 **apNew;\n  unsigned int nNew;\n  unsigned int i;\n\n  assert( sqlite3_mutex_held(p->pGroup->mutex) );\n\n  nNew = p->nHash*2;\n  if( nNew<256 ){\n    nNew = 256;\n  }\n\n  pcache1LeaveMutex(p->pGroup);\n  if( p->nHash ){ sqlite3BeginBenignMalloc(); }\n  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);\n  if( p->nHash ){ sqlite3EndBenignMalloc(); }\n  pcache1EnterMutex(p->pGroup);\n  if( apNew ){\n    for(i=0; i<p->nHash; i++){\n      PgHdr1 *pPage;\n      PgHdr1 *pNext = p->apHash[i];\n      while( (pPage = pNext)!=0 ){\n        unsigned int h = pPage->iKey % nNew;\n        pNext = pPage->pNext;\n        pPage->pNext = apNew[h];\n        apNew[h] = pPage;\n      }\n    }\n    sqlite3_free(p->apHash);\n    p->apHash = apNew;\n    p->nHash = nNew;\n  }\n\n  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);\n}\n\n/*\n** This function is used internally to remove the page pPage from the \n** PGroup LRU list, if is part of it. If pPage is not part of the PGroup\n** LRU list, then this function is a no-op.\n**\n** The PGroup mutex must be held when this function is called.\n**\n** If pPage is NULL then this routine is a no-op.\n*/\nstatic void pcache1PinPage(PgHdr1 *pPage){\n  PCache1 *pCache;\n  PGroup *pGroup;\n\n  if( pPage==0 ) return;\n  pCache = pPage->pCache;\n  pGroup = pCache->pGroup;\n  assert( sqlite3_mutex_held(pGroup->mutex) );\n  if( pPage->pLruNext || pPage==pGroup->pLruTail ){\n    if( pPage->pLruPrev ){\n      pPage->pLruPrev->pLruNext = pPage->pLruNext;\n    }\n    if( pPage->pLruNext ){\n      pPage->pLruNext->pLruPrev = pPage->pLruPrev;\n    }\n    if( pGroup->pLruHead==pPage ){\n      pGroup->pLruHead = pPage->pLruNext;\n    }\n    if( pGroup->pLruTail==pPage ){\n      pGroup->pLruTail = pPage->pLruPrev;\n    }\n    pPage->pLruNext = 0;\n    pPage->pLruPrev = 0;\n    pPage->pCache->nRecyclable--;\n  }\n}\n\n\n/*\n** Remove the page supplied as an argument from the hash table \n** (PCache1.apHash structure) that it is currently stored in.\n**\n** The PGroup mutex must be held when this function is called.\n*/\nstatic void pcache1RemoveFromHash(PgHdr1 *pPage){\n  unsigned int h;\n  PCache1 *pCache = pPage->pCache;\n  PgHdr1 **pp;\n\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  h = pPage->iKey % pCache->nHash;\n  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);\n  *pp = (*pp)->pNext;\n\n  pCache->nPage--;\n}\n\n/*\n** If there are currently more than nMaxPage pages allocated, try\n** to recycle pages to reduce the number allocated to nMaxPage.\n*/\nstatic void pcache1EnforceMaxPage(PGroup *pGroup){\n  assert( sqlite3_mutex_held(pGroup->mutex) );\n  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){\n    PgHdr1 *p = pGroup->pLruTail;\n    assert( p->pCache->pGroup==pGroup );\n    pcache1PinPage(p);\n    pcache1RemoveFromHash(p);\n    pcache1FreePage(p);\n  }\n}\n\n/*\n** Discard all pages from cache pCache with a page number (key value) \n** greater than or equal to iLimit. Any pinned pages that meet this \n** criteria are unpinned before they are discarded.\n**\n** The PCache mutex must be held when this function is called.\n*/\nstatic void pcache1TruncateUnsafe(\n  PCache1 *pCache,             /* The cache to truncate */\n  unsigned int iLimit          /* Drop pages with this pgno or larger */\n){\n  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */\n  unsigned int h;\n  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );\n  for(h=0; h<pCache->nHash; h++){\n    PgHdr1 **pp = &pCache->apHash[h]; \n    PgHdr1 *pPage;\n    while( (pPage = *pp)!=0 ){\n      if( pPage->iKey>=iLimit ){\n        pCache->nPage--;\n        *pp = pPage->pNext;\n        pcache1PinPage(pPage);\n        pcache1FreePage(pPage);\n      }else{\n        pp = &pPage->pNext;\n        TESTONLY( nPage++; )\n      }\n    }\n  }\n  assert( pCache->nPage==nPage );\n}\n\n/******************************************************************************/\n/******** sqlite3_pcache Methods **********************************************/\n\n/*\n** Implementation of the sqlite3_pcache.xInit method.\n*/\nstatic int pcache1Init(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( pcache1.isInit==0 );\n  memset(&pcache1, 0, sizeof(pcache1));\n  if( sqlite3GlobalConfig.bCoreMutex ){\n    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);\n    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);\n  }\n  pcache1.grp.mxPinned = 10;\n  pcache1.isInit = 1;\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xShutdown method.\n** Note that the static mutex allocated in xInit does \n** not need to be freed.\n*/\nstatic void pcache1Shutdown(void *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  assert( pcache1.isInit!=0 );\n  memset(&pcache1, 0, sizeof(pcache1));\n}\n\n/*\n** Implementation of the sqlite3_pcache.xCreate method.\n**\n** Allocate a new cache.\n*/\nstatic sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){\n  PCache1 *pCache;      /* The newly created page cache */\n  PGroup *pGroup;       /* The group the new page cache will belong to */\n  int sz;               /* Bytes of memory required to allocate the new cache */\n\n  /*\n  ** The seperateCache variable is true if each PCache has its own private\n  ** PGroup.  In other words, separateCache is true for mode (1) where no\n  ** mutexing is required.\n  **\n  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT\n  **\n  **   *  Always use a unified cache in single-threaded applications\n  **\n  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)\n  **      use separate caches (mode-1)\n  */\n#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0\n  const int separateCache = 0;\n#else\n  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;\n#endif\n\n  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );\n  assert( szExtra < 300 );\n\n  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;\n  pCache = (PCache1 *)sqlite3MallocZero(sz);\n  if( pCache ){\n    if( separateCache ){\n      pGroup = (PGroup*)&pCache[1];\n      pGroup->mxPinned = 10;\n    }else{\n      pGroup = &pcache1.grp;\n    }\n    pCache->pGroup = pGroup;\n    pCache->szPage = szPage;\n    pCache->szExtra = szExtra;\n    pCache->bPurgeable = (bPurgeable ? 1 : 0);\n    if( bPurgeable ){\n      pCache->nMin = 10;\n      pcache1EnterMutex(pGroup);\n      pGroup->nMinPage += pCache->nMin;\n      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n      pcache1LeaveMutex(pGroup);\n    }\n  }\n  return (sqlite3_pcache *)pCache;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xCachesize method. \n**\n** Configure the cache_size limit for a cache.\n*/\nstatic void pcache1Cachesize(sqlite3_pcache *p, int nMax){\n  PCache1 *pCache = (PCache1 *)p;\n  if( pCache->bPurgeable ){\n    PGroup *pGroup = pCache->pGroup;\n    pcache1EnterMutex(pGroup);\n    pGroup->nMaxPage += (nMax - pCache->nMax);\n    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n    pCache->nMax = nMax;\n    pCache->n90pct = pCache->nMax*9/10;\n    pcache1EnforceMaxPage(pGroup);\n    pcache1LeaveMutex(pGroup);\n  }\n}\n\n/*\n** Implementation of the sqlite3_pcache.xShrink method. \n**\n** Free up as much memory as possible.\n*/\nstatic void pcache1Shrink(sqlite3_pcache *p){\n  PCache1 *pCache = (PCache1*)p;\n  if( pCache->bPurgeable ){\n    PGroup *pGroup = pCache->pGroup;\n    int savedMaxPage;\n    pcache1EnterMutex(pGroup);\n    savedMaxPage = pGroup->nMaxPage;\n    pGroup->nMaxPage = 0;\n    pcache1EnforceMaxPage(pGroup);\n    pGroup->nMaxPage = savedMaxPage;\n    pcache1LeaveMutex(pGroup);\n  }\n}\n\n/*\n** Implementation of the sqlite3_pcache.xPagecount method. \n*/\nstatic int pcache1Pagecount(sqlite3_pcache *p){\n  int n;\n  PCache1 *pCache = (PCache1*)p;\n  pcache1EnterMutex(pCache->pGroup);\n  n = pCache->nPage;\n  pcache1LeaveMutex(pCache->pGroup);\n  return n;\n}\n\n/*\n** Implementation of the sqlite3_pcache.xFetch method. \n**\n** Fetch a page by key value.\n**\n** Whether or not a new page may be allocated by this function depends on\n** the value of the createFlag argument.  0 means do not allocate a new\n** page.  1 means allocate a new page if space is easily available.  2 \n** means to try really hard to allocate a new page.\n**\n** For a non-purgeable cache (a cache used as the storage for an in-memory\n** database) there is really no difference between createFlag 1 and 2.  So\n** the calling function (pcache.c) will never have a createFlag of 1 on\n** a non-purgeable cache.\n**\n** There are three different approaches to obtaining space for a page,\n** depending on the value of parameter createFlag (which may be 0, 1 or 2).\n**\n**   1. Regardless of the value of createFlag, the cache is searched for a \n**      copy of the requested page. If one is found, it is returned.\n**\n**   2. If createFlag==0 and the page is not already in the cache, NULL is\n**      returned.\n**\n**   3. If createFlag is 1, and the page is not already in the cache, then\n**      return NULL (do not allocate a new page) if any of the following\n**      conditions are true:\n**\n**       (a) the number of pages pinned by the cache is greater than\n**           PCache1.nMax, or\n**\n**       (b) the number of pages pinned by the cache is greater than\n**           the sum of nMax for all purgeable caches, less the sum of \n**           nMin for all other purgeable caches, or\n**\n**   4. If none of the first three conditions apply and the cache is marked\n**      as purgeable, and if one of the following is true:\n**\n**       (a) The number of pages allocated for the cache is already \n**           PCache1.nMax, or\n**\n**       (b) The number of pages allocated for all purgeable caches is\n**           already equal to or greater than the sum of nMax for all\n**           purgeable caches,\n**\n**       (c) The system is under memory pressure and wants to avoid\n**           unnecessary pages cache entry allocations\n**\n**      then attempt to recycle a page from the LRU list. If it is the right\n**      size, return the recycled buffer. Otherwise, free the buffer and\n**      proceed to step 5. \n**\n**   5. Otherwise, allocate and return a new page buffer.\n*/\nstatic sqlite3_pcache_page *pcache1Fetch(\n  sqlite3_pcache *p, \n  unsigned int iKey, \n  int createFlag\n){\n  unsigned int nPinned;\n  PCache1 *pCache = (PCache1 *)p;\n  PGroup *pGroup;\n  PgHdr1 *pPage = 0;\n\n  assert( pCache->bPurgeable || createFlag!=1 );\n  assert( pCache->bPurgeable || pCache->nMin==0 );\n  assert( pCache->bPurgeable==0 || pCache->nMin==10 );\n  assert( pCache->nMin==0 || pCache->bPurgeable );\n  pcache1EnterMutex(pGroup = pCache->pGroup);\n\n  /* Step 1: Search the hash table for an existing entry. */\n  if( pCache->nHash>0 ){\n    unsigned int h = iKey % pCache->nHash;\n    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);\n  }\n\n  /* Step 2: Abort if no existing page is found and createFlag is 0 */\n  if( pPage || createFlag==0 ){\n    pcache1PinPage(pPage);\n    goto fetch_out;\n  }\n\n  /* The pGroup local variable will normally be initialized by the\n  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,\n  ** then pcache1EnterMutex() is a no-op, so we have to initialize the\n  ** local variable here.  Delaying the initialization of pGroup is an\n  ** optimization:  The common case is to exit the module before reaching\n  ** this point.\n  */\n#ifdef SQLITE_MUTEX_OMIT\n  pGroup = pCache->pGroup;\n#endif\n\n  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */\n  assert( pCache->nPage >= pCache->nRecyclable );\n  nPinned = pCache->nPage - pCache->nRecyclable;\n  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );\n  assert( pCache->n90pct == pCache->nMax*9/10 );\n  if( createFlag==1 && (\n        nPinned>=pGroup->mxPinned\n     || nPinned>=pCache->n90pct\n     || pcache1UnderMemoryPressure(pCache)\n  )){\n    goto fetch_out;\n  }\n\n  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){\n    goto fetch_out;\n  }\n\n  /* Step 4. Try to recycle a page. */\n  if( pCache->bPurgeable && pGroup->pLruTail && (\n         (pCache->nPage+1>=pCache->nMax)\n      || pGroup->nCurrentPage>=pGroup->nMaxPage\n      || pcache1UnderMemoryPressure(pCache)\n  )){\n    PCache1 *pOther;\n    pPage = pGroup->pLruTail;\n    pcache1RemoveFromHash(pPage);\n    pcache1PinPage(pPage);\n    pOther = pPage->pCache;\n\n    /* We want to verify that szPage and szExtra are the same for pOther\n    ** and pCache.  Assert that we can verify this by comparing sums. */\n    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );\n    assert( pCache->szExtra<512 );\n    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );\n    assert( pOther->szExtra<512 );\n\n    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){\n      pcache1FreePage(pPage);\n      pPage = 0;\n    }else{\n      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);\n    }\n  }\n\n  /* Step 5. If a usable page buffer has still not been found, \n  ** attempt to allocate a new one. \n  */\n  if( !pPage ){\n    if( createFlag==1 ) sqlite3BeginBenignMalloc();\n    pPage = pcache1AllocPage(pCache);\n    if( createFlag==1 ) sqlite3EndBenignMalloc();\n  }\n\n  if( pPage ){\n    unsigned int h = iKey % pCache->nHash;\n    pCache->nPage++;\n    pPage->iKey = iKey;\n    pPage->pNext = pCache->apHash[h];\n    pPage->pCache = pCache;\n    pPage->pLruPrev = 0;\n    pPage->pLruNext = 0;\n    *(void **)pPage->page.pExtra = 0;\n    pCache->apHash[h] = pPage;\n  }\n\nfetch_out:\n  if( pPage && iKey>pCache->iMaxKey ){\n    pCache->iMaxKey = iKey;\n  }\n  pcache1LeaveMutex(pGroup);\n  return &pPage->page;\n}\n\n\n/*\n** Implementation of the sqlite3_pcache.xUnpin method.\n**\n** Mark a page as unpinned (eligible for asynchronous recycling).\n*/\nstatic void pcache1Unpin(\n  sqlite3_pcache *p, \n  sqlite3_pcache_page *pPg, \n  int reuseUnlikely\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage = (PgHdr1 *)pPg;\n  PGroup *pGroup = pCache->pGroup;\n \n  assert( pPage->pCache==pCache );\n  pcache1EnterMutex(pGroup);\n\n  /* It is an error to call this function if the page is already \n  ** part of the PGroup LRU list.\n  */\n  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );\n  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );\n\n  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){\n    pcache1RemoveFromHash(pPage);\n    pcache1FreePage(pPage);\n  }else{\n    /* Add the page to the PGroup LRU list. */\n    if( pGroup->pLruHead ){\n      pGroup->pLruHead->pLruPrev = pPage;\n      pPage->pLruNext = pGroup->pLruHead;\n      pGroup->pLruHead = pPage;\n    }else{\n      pGroup->pLruTail = pPage;\n      pGroup->pLruHead = pPage;\n    }\n    pCache->nRecyclable++;\n  }\n\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xRekey method. \n*/\nstatic void pcache1Rekey(\n  sqlite3_pcache *p,\n  sqlite3_pcache_page *pPg,\n  unsigned int iOld,\n  unsigned int iNew\n){\n  PCache1 *pCache = (PCache1 *)p;\n  PgHdr1 *pPage = (PgHdr1 *)pPg;\n  PgHdr1 **pp;\n  unsigned int h; \n  assert( pPage->iKey==iOld );\n  assert( pPage->pCache==pCache );\n\n  pcache1EnterMutex(pCache->pGroup);\n\n  h = iOld%pCache->nHash;\n  pp = &pCache->apHash[h];\n  while( (*pp)!=pPage ){\n    pp = &(*pp)->pNext;\n  }\n  *pp = pPage->pNext;\n\n  h = iNew%pCache->nHash;\n  pPage->iKey = iNew;\n  pPage->pNext = pCache->apHash[h];\n  pCache->apHash[h] = pPage;\n  if( iNew>pCache->iMaxKey ){\n    pCache->iMaxKey = iNew;\n  }\n\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xTruncate method. \n**\n** Discard all unpinned pages in the cache with a page number equal to\n** or greater than parameter iLimit. Any pinned pages with a page number\n** equal to or greater than iLimit are implicitly unpinned.\n*/\nstatic void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){\n  PCache1 *pCache = (PCache1 *)p;\n  pcache1EnterMutex(pCache->pGroup);\n  if( iLimit<=pCache->iMaxKey ){\n    pcache1TruncateUnsafe(pCache, iLimit);\n    pCache->iMaxKey = iLimit-1;\n  }\n  pcache1LeaveMutex(pCache->pGroup);\n}\n\n/*\n** Implementation of the sqlite3_pcache.xDestroy method. \n**\n** Destroy a cache allocated using pcache1Create().\n*/\nstatic void pcache1Destroy(sqlite3_pcache *p){\n  PCache1 *pCache = (PCache1 *)p;\n  PGroup *pGroup = pCache->pGroup;\n  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );\n  pcache1EnterMutex(pGroup);\n  pcache1TruncateUnsafe(pCache, 0);\n  assert( pGroup->nMaxPage >= pCache->nMax );\n  pGroup->nMaxPage -= pCache->nMax;\n  assert( pGroup->nMinPage >= pCache->nMin );\n  pGroup->nMinPage -= pCache->nMin;\n  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;\n  pcache1EnforceMaxPage(pGroup);\n  pcache1LeaveMutex(pGroup);\n  sqlite3_free(pCache->apHash);\n  sqlite3_free(pCache);\n}\n\n/*\n** This function is called during initialization (sqlite3_initialize()) to\n** install the default pluggable cache module, assuming the user has not\n** already provided an alternative.\n*/\nSQLITE_PRIVATE void sqlite3PCacheSetDefault(void){\n  static const sqlite3_pcache_methods2 defaultMethods = {\n    1,                       /* iVersion */\n    0,                       /* pArg */\n    pcache1Init,             /* xInit */\n    pcache1Shutdown,         /* xShutdown */\n    pcache1Create,           /* xCreate */\n    pcache1Cachesize,        /* xCachesize */\n    pcache1Pagecount,        /* xPagecount */\n    pcache1Fetch,            /* xFetch */\n    pcache1Unpin,            /* xUnpin */\n    pcache1Rekey,            /* xRekey */\n    pcache1Truncate,         /* xTruncate */\n    pcache1Destroy,          /* xDestroy */\n    pcache1Shrink            /* xShrink */\n  };\n  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);\n}\n\n#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT\n/*\n** This function is called to free superfluous dynamically allocated memory\n** held by the pager system. Memory in use by any SQLite pager allocated\n** by the current thread may be sqlite3_free()ed.\n**\n** nReq is the number of bytes of memory required. Once this much has\n** been released, the function returns. The return value is the total number \n** of bytes of memory released.\n*/\nSQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){\n  int nFree = 0;\n  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );\n  assert( sqlite3_mutex_notheld(pcache1.mutex) );\n  if( pcache1.pStart==0 ){\n    PgHdr1 *p;\n    pcache1EnterMutex(&pcache1.grp);\n    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){\n      nFree += pcache1MemSize(p->page.pBuf);\n#ifdef SQLITE_PCACHE_SEPARATE_HEADER\n      nFree += sqlite3MemSize(p);\n#endif\n      pcache1PinPage(p);\n      pcache1RemoveFromHash(p);\n      pcache1FreePage(p);\n    }\n    pcache1LeaveMutex(&pcache1.grp);\n  }\n  return nFree;\n}\n#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */\n\n#ifdef SQLITE_TEST\n/*\n** This function is used by test procedures to inspect the internal state\n** of the global cache.\n*/\nSQLITE_PRIVATE void sqlite3PcacheStats(\n  int *pnCurrent,      /* OUT: Total number of pages cached */\n  int *pnMax,          /* OUT: Global maximum cache size */\n  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */\n  int *pnRecyclable    /* OUT: Total number of pages available for recycling */\n){\n  PgHdr1 *p;\n  int nRecyclable = 0;\n  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){\n    nRecyclable++;\n  }\n  *pnCurrent = pcache1.grp.nCurrentPage;\n  *pnMax = (int)pcache1.grp.nMaxPage;\n  *pnMin = (int)pcache1.grp.nMinPage;\n  *pnRecyclable = nRecyclable;\n}\n#endif\n\n/************** End of pcache1.c *********************************************/\n/************** Begin file rowset.c ******************************************/\n/*\n** 2008 December 3\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This module implements an object we call a \"RowSet\".\n**\n** The RowSet object is a collection of rowids.  Rowids\n** are inserted into the RowSet in an arbitrary order.  Inserts\n** can be intermixed with tests to see if a given rowid has been\n** previously inserted into the RowSet.\n**\n** After all inserts are finished, it is possible to extract the\n** elements of the RowSet in sorted order.  Once this extraction\n** process has started, no new elements may be inserted.\n**\n** Hence, the primitive operations for a RowSet are:\n**\n**    CREATE\n**    INSERT\n**    TEST\n**    SMALLEST\n**    DESTROY\n**\n** The CREATE and DESTROY primitives are the constructor and destructor,\n** obviously.  The INSERT primitive adds a new element to the RowSet.\n** TEST checks to see if an element is already in the RowSet.  SMALLEST\n** extracts the least value from the RowSet.\n**\n** The INSERT primitive might allocate additional memory.  Memory is\n** allocated in chunks so most INSERTs do no allocation.  There is an \n** upper bound on the size of allocated memory.  No memory is freed\n** until DESTROY.\n**\n** The TEST primitive includes a \"batch\" number.  The TEST primitive\n** will only see elements that were inserted before the last change\n** in the batch number.  In other words, if an INSERT occurs between\n** two TESTs where the TESTs have the same batch nubmer, then the\n** value added by the INSERT will not be visible to the second TEST.\n** The initial batch number is zero, so if the very first TEST contains\n** a non-zero batch number, it will see all prior INSERTs.\n**\n** No INSERTs may occurs after a SMALLEST.  An assertion will fail if\n** that is attempted.\n**\n** The cost of an INSERT is roughly constant.  (Sometime new memory\n** has to be allocated on an INSERT.)  The cost of a TEST with a new\n** batch number is O(NlogN) where N is the number of elements in the RowSet.\n** The cost of a TEST using the same batch number is O(logN).  The cost\n** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST\n** primitives are constant time.  The cost of DESTROY is O(N).\n**\n** There is an added cost of O(N) when switching between TEST and\n** SMALLEST primitives.\n*/\n\n\n/*\n** Target size for allocation chunks.\n*/\n#define ROWSET_ALLOCATION_SIZE 1024\n\n/*\n** The number of rowset entries per allocation chunk.\n*/\n#define ROWSET_ENTRY_PER_CHUNK  \\\n                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))\n\n/*\n** Each entry in a RowSet is an instance of the following object.\n**\n** This same object is reused to store a linked list of trees of RowSetEntry\n** objects.  In that alternative use, pRight points to the next entry\n** in the list, pLeft points to the tree, and v is unused.  The\n** RowSet.pForest value points to the head of this forest list.\n*/\nstruct RowSetEntry {            \n  i64 v;                        /* ROWID value for this entry */\n  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */\n  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */\n};\n\n/*\n** RowSetEntry objects are allocated in large chunks (instances of the\n** following structure) to reduce memory allocation overhead.  The\n** chunks are kept on a linked list so that they can be deallocated\n** when the RowSet is destroyed.\n*/\nstruct RowSetChunk {\n  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */\n  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */\n};\n\n/*\n** A RowSet in an instance of the following structure.\n**\n** A typedef of this structure if found in sqliteInt.h.\n*/\nstruct RowSet {\n  struct RowSetChunk *pChunk;    /* List of all chunk allocations */\n  sqlite3 *db;                   /* The database connection */\n  struct RowSetEntry *pEntry;    /* List of entries using pRight */\n  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */\n  struct RowSetEntry *pFresh;    /* Source of new entry objects */\n  struct RowSetEntry *pForest;   /* List of binary trees of entries */\n  u16 nFresh;                    /* Number of objects on pFresh */\n  u8 rsFlags;                    /* Various flags */\n  u8 iBatch;                     /* Current insert batch */\n};\n\n/*\n** Allowed values for RowSet.rsFlags\n*/\n#define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */\n#define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */\n\n/*\n** Turn bulk memory into a RowSet object.  N bytes of memory\n** are available at pSpace.  The db pointer is used as a memory context\n** for any subsequent allocations that need to occur.\n** Return a pointer to the new RowSet object.\n**\n** It must be the case that N is sufficient to make a Rowset.  If not\n** an assertion fault occurs.\n** \n** If N is larger than the minimum, use the surplus as an initial\n** allocation of entries available to be filled.\n*/\nSQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){\n  RowSet *p;\n  assert( N >= ROUND8(sizeof(*p)) );\n  p = pSpace;\n  p->pChunk = 0;\n  p->db = db;\n  p->pEntry = 0;\n  p->pLast = 0;\n  p->pForest = 0;\n  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);\n  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));\n  p->rsFlags = ROWSET_SORTED;\n  p->iBatch = 0;\n  return p;\n}\n\n/*\n** Deallocate all chunks from a RowSet.  This frees all memory that\n** the RowSet has allocated over its lifetime.  This routine is\n** the destructor for the RowSet.\n*/\nSQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){\n  struct RowSetChunk *pChunk, *pNextChunk;\n  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){\n    pNextChunk = pChunk->pNextChunk;\n    sqlite3DbFree(p->db, pChunk);\n  }\n  p->pChunk = 0;\n  p->nFresh = 0;\n  p->pEntry = 0;\n  p->pLast = 0;\n  p->pForest = 0;\n  p->rsFlags = ROWSET_SORTED;\n}\n\n/*\n** Allocate a new RowSetEntry object that is associated with the\n** given RowSet.  Return a pointer to the new and completely uninitialized\n** objected.\n**\n** In an OOM situation, the RowSet.db->mallocFailed flag is set and this\n** routine returns NULL.\n*/\nstatic struct RowSetEntry *rowSetEntryAlloc(RowSet *p){\n  assert( p!=0 );\n  if( p->nFresh==0 ){\n    struct RowSetChunk *pNew;\n    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));\n    if( pNew==0 ){\n      return 0;\n    }\n    pNew->pNextChunk = p->pChunk;\n    p->pChunk = pNew;\n    p->pFresh = pNew->aEntry;\n    p->nFresh = ROWSET_ENTRY_PER_CHUNK;\n  }\n  p->nFresh--;\n  return p->pFresh++;\n}\n\n/*\n** Insert a new value into a RowSet.\n**\n** The mallocFailed flag of the database connection is set if a\n** memory allocation fails.\n*/\nSQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){\n  struct RowSetEntry *pEntry;  /* The new entry */\n  struct RowSetEntry *pLast;   /* The last prior entry */\n\n  /* This routine is never called after sqlite3RowSetNext() */\n  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );\n\n  pEntry = rowSetEntryAlloc(p);\n  if( pEntry==0 ) return;\n  pEntry->v = rowid;\n  pEntry->pRight = 0;\n  pLast = p->pLast;\n  if( pLast ){\n    if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){\n      p->rsFlags &= ~ROWSET_SORTED;\n    }\n    pLast->pRight = pEntry;\n  }else{\n    p->pEntry = pEntry;\n  }\n  p->pLast = pEntry;\n}\n\n/*\n** Merge two lists of RowSetEntry objects.  Remove duplicates.\n**\n** The input lists are connected via pRight pointers and are \n** assumed to each already be in sorted order.\n*/\nstatic struct RowSetEntry *rowSetEntryMerge(\n  struct RowSetEntry *pA,    /* First sorted list to be merged */\n  struct RowSetEntry *pB     /* Second sorted list to be merged */\n){\n  struct RowSetEntry head;\n  struct RowSetEntry *pTail;\n\n  pTail = &head;\n  while( pA && pB ){\n    assert( pA->pRight==0 || pA->v<=pA->pRight->v );\n    assert( pB->pRight==0 || pB->v<=pB->pRight->v );\n    if( pA->v<pB->v ){\n      pTail->pRight = pA;\n      pA = pA->pRight;\n      pTail = pTail->pRight;\n    }else if( pB->v<pA->v ){\n      pTail->pRight = pB;\n      pB = pB->pRight;\n      pTail = pTail->pRight;\n    }else{\n      pA = pA->pRight;\n    }\n  }\n  if( pA ){\n    assert( pA->pRight==0 || pA->v<=pA->pRight->v );\n    pTail->pRight = pA;\n  }else{\n    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );\n    pTail->pRight = pB;\n  }\n  return head.pRight;\n}\n\n/*\n** Sort all elements on the list of RowSetEntry objects into order of\n** increasing v.\n*/ \nstatic struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){\n  unsigned int i;\n  struct RowSetEntry *pNext, *aBucket[40];\n\n  memset(aBucket, 0, sizeof(aBucket));\n  while( pIn ){\n    pNext = pIn->pRight;\n    pIn->pRight = 0;\n    for(i=0; aBucket[i]; i++){\n      pIn = rowSetEntryMerge(aBucket[i], pIn);\n      aBucket[i] = 0;\n    }\n    aBucket[i] = pIn;\n    pIn = pNext;\n  }\n  pIn = 0;\n  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){\n    pIn = rowSetEntryMerge(pIn, aBucket[i]);\n  }\n  return pIn;\n}\n\n\n/*\n** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.\n** Convert this tree into a linked list connected by the pRight pointers\n** and return pointers to the first and last elements of the new list.\n*/\nstatic void rowSetTreeToList(\n  struct RowSetEntry *pIn,         /* Root of the input tree */\n  struct RowSetEntry **ppFirst,    /* Write head of the output list here */\n  struct RowSetEntry **ppLast      /* Write tail of the output list here */\n){\n  assert( pIn!=0 );\n  if( pIn->pLeft ){\n    struct RowSetEntry *p;\n    rowSetTreeToList(pIn->pLeft, ppFirst, &p);\n    p->pRight = pIn;\n  }else{\n    *ppFirst = pIn;\n  }\n  if( pIn->pRight ){\n    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);\n  }else{\n    *ppLast = pIn;\n  }\n  assert( (*ppLast)->pRight==0 );\n}\n\n\n/*\n** Convert a sorted list of elements (connected by pRight) into a binary\n** tree with depth of iDepth.  A depth of 1 means the tree contains a single\n** node taken from the head of *ppList.  A depth of 2 means a tree with\n** three nodes.  And so forth.\n**\n** Use as many entries from the input list as required and update the\n** *ppList to point to the unused elements of the list.  If the input\n** list contains too few elements, then construct an incomplete tree\n** and leave *ppList set to NULL.\n**\n** Return a pointer to the root of the constructed binary tree.\n*/\nstatic struct RowSetEntry *rowSetNDeepTree(\n  struct RowSetEntry **ppList,\n  int iDepth\n){\n  struct RowSetEntry *p;         /* Root of the new tree */\n  struct RowSetEntry *pLeft;     /* Left subtree */\n  if( *ppList==0 ){\n    return 0;\n  }\n  if( iDepth==1 ){\n    p = *ppList;\n    *ppList = p->pRight;\n    p->pLeft = p->pRight = 0;\n    return p;\n  }\n  pLeft = rowSetNDeepTree(ppList, iDepth-1);\n  p = *ppList;\n  if( p==0 ){\n    return pLeft;\n  }\n  p->pLeft = pLeft;\n  *ppList = p->pRight;\n  p->pRight = rowSetNDeepTree(ppList, iDepth-1);\n  return p;\n}\n\n/*\n** Convert a sorted list of elements into a binary tree. Make the tree\n** as deep as it needs to be in order to contain the entire list.\n*/\nstatic struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){\n  int iDepth;           /* Depth of the tree so far */\n  struct RowSetEntry *p;       /* Current tree root */\n  struct RowSetEntry *pLeft;   /* Left subtree */\n\n  assert( pList!=0 );\n  p = pList;\n  pList = p->pRight;\n  p->pLeft = p->pRight = 0;\n  for(iDepth=1; pList; iDepth++){\n    pLeft = p;\n    p = pList;\n    pList = p->pRight;\n    p->pLeft = pLeft;\n    p->pRight = rowSetNDeepTree(&pList, iDepth);\n  }\n  return p;\n}\n\n/*\n** Take all the entries on p->pEntry and on the trees in p->pForest and\n** sort them all together into one big ordered list on p->pEntry.\n**\n** This routine should only be called once in the life of a RowSet.\n*/\nstatic void rowSetToList(RowSet *p){\n\n  /* This routine is called only once */\n  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );\n\n  if( (p->rsFlags & ROWSET_SORTED)==0 ){\n    p->pEntry = rowSetEntrySort(p->pEntry);\n  }\n\n  /* While this module could theoretically support it, sqlite3RowSetNext()\n  ** is never called after sqlite3RowSetText() for the same RowSet.  So\n  ** there is never a forest to deal with.  Should this change, simply\n  ** remove the assert() and the #if 0. */\n  assert( p->pForest==0 );\n#if 0\n  while( p->pForest ){\n    struct RowSetEntry *pTree = p->pForest->pLeft;\n    if( pTree ){\n      struct RowSetEntry *pHead, *pTail;\n      rowSetTreeToList(pTree, &pHead, &pTail);\n      p->pEntry = rowSetEntryMerge(p->pEntry, pHead);\n    }\n    p->pForest = p->pForest->pRight;\n  }\n#endif\n  p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */\n}\n\n/*\n** Extract the smallest element from the RowSet.\n** Write the element into *pRowid.  Return 1 on success.  Return\n** 0 if the RowSet is already empty.\n**\n** After this routine has been called, the sqlite3RowSetInsert()\n** routine may not be called again.  \n*/\nSQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){\n  assert( p!=0 );\n\n  /* Merge the forest into a single sorted list on first call */\n  if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);\n\n  /* Return the next entry on the list */\n  if( p->pEntry ){\n    *pRowid = p->pEntry->v;\n    p->pEntry = p->pEntry->pRight;\n    if( p->pEntry==0 ){\n      sqlite3RowSetClear(p);\n    }\n    return 1;\n  }else{\n    return 0;\n  }\n}\n\n/*\n** Check to see if element iRowid was inserted into the rowset as\n** part of any insert batch prior to iBatch.  Return 1 or 0.\n**\n** If this is the first test of a new batch and if there exist entires\n** on pRowSet->pEntry, then sort those entires into the forest at\n** pRowSet->pForest so that they can be tested.\n*/\nSQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){\n  struct RowSetEntry *p, *pTree;\n\n  /* This routine is never called after sqlite3RowSetNext() */\n  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );\n\n  /* Sort entries into the forest on the first test of a new batch \n  */\n  if( iBatch!=pRowSet->iBatch ){\n    p = pRowSet->pEntry;\n    if( p ){\n      struct RowSetEntry **ppPrevTree = &pRowSet->pForest;\n      if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){\n        p = rowSetEntrySort(p);\n      }\n      for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){\n        ppPrevTree = &pTree->pRight;\n        if( pTree->pLeft==0 ){\n          pTree->pLeft = rowSetListToTree(p);\n          break;\n        }else{\n          struct RowSetEntry *pAux, *pTail;\n          rowSetTreeToList(pTree->pLeft, &pAux, &pTail);\n          pTree->pLeft = 0;\n          p = rowSetEntryMerge(pAux, p);\n        }\n      }\n      if( pTree==0 ){\n        *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);\n        if( pTree ){\n          pTree->v = 0;\n          pTree->pRight = 0;\n          pTree->pLeft = rowSetListToTree(p);\n        }\n      }\n      pRowSet->pEntry = 0;\n      pRowSet->pLast = 0;\n      pRowSet->rsFlags |= ROWSET_SORTED;\n    }\n    pRowSet->iBatch = iBatch;\n  }\n\n  /* Test to see if the iRowid value appears anywhere in the forest.\n  ** Return 1 if it does and 0 if not.\n  */\n  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){\n    p = pTree->pLeft;\n    while( p ){\n      if( p->v<iRowid ){\n        p = p->pRight;\n      }else if( p->v>iRowid ){\n        p = p->pLeft;\n      }else{\n        return 1;\n      }\n    }\n  }\n  return 0;\n}\n\n/************** End of rowset.c **********************************************/\n/************** Begin file pager.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of the page cache subsystem or \"pager\".\n** \n** The pager is used to access a database disk file.  It implements\n** atomic commit and rollback through the use of a journal file that\n** is separate from the database file.  The pager also implements file\n** locking to prevent two processes from writing the same database\n** file simultaneously, or one process from reading the database while\n** another is writing.\n*/\n#ifndef SQLITE_OMIT_DISKIO\n/************** Include wal.h in the middle of pager.c ***********************/\n/************** Begin file wal.h *********************************************/\n/*\n** 2010 February 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface to the write-ahead logging \n** system. Refer to the comments below and the header comment attached to \n** the implementation of each function in log.c for further details.\n*/\n\n#ifndef _WAL_H_\n#define _WAL_H_\n\n\n/* Additional values that can be added to the sync_flags argument of\n** sqlite3WalFrames():\n*/\n#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */\n#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */\n\n#ifdef SQLITE_OMIT_WAL\n# define sqlite3WalOpen(x,y,z)                   0\n# define sqlite3WalLimit(x,y)\n# define sqlite3WalClose(w,x,y,z)                0\n# define sqlite3WalBeginReadTransaction(y,z)     0\n# define sqlite3WalEndReadTransaction(z)\n# define sqlite3WalRead(v,w,x,y,z)               0\n# define sqlite3WalDbsize(y)                     0\n# define sqlite3WalBeginWriteTransaction(y)      0\n# define sqlite3WalEndWriteTransaction(x)        0\n# define sqlite3WalUndo(x,y,z)                   0\n# define sqlite3WalSavepoint(y,z)\n# define sqlite3WalSavepointUndo(y,z)            0\n# define sqlite3WalFrames(u,v,w,x,y,z)           0\n# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0\n# define sqlite3WalCallback(z)                   0\n# define sqlite3WalExclusiveMode(y,z)            0\n# define sqlite3WalHeapMemory(z)                 0\n# define sqlite3WalFramesize(z)                  0\n#else\n\n#define WAL_SAVEPOINT_NDATA 4\n\n/* Connection to a write-ahead log (WAL) file. \n** There is one object of this type for each pager. \n*/\ntypedef struct Wal Wal;\n\n/* Open and close a connection to a write-ahead log. */\nSQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);\nSQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);\n\n/* Set the limiting size of a WAL file. */\nSQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);\n\n/* Used by readers to open (lock) and close (unlock) a snapshot.  A \n** snapshot is like a read-transaction.  It is the state of the database\n** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and\n** preserves the current state even if the other threads or processes\n** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the\n** transaction and releases the lock.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);\nSQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);\n\n/* Read a page from the write-ahead log, if it is present. */\nSQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);\n\n/* If the WAL is not empty, return the size of the database. */\nSQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);\n\n/* Obtain or release the WRITER lock. */\nSQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);\nSQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);\n\n/* Undo any frames written (but not committed) to the log */\nSQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);\n\n/* Return an integer that records the current (uncommitted) write\n** position in the WAL */\nSQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);\n\n/* Move the write position of the WAL back to iFrame.  Called in\n** response to a ROLLBACK TO command. */\nSQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);\n\n/* Write a frame or frames to the log. */\nSQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);\n\n/* Copy pages from the log to the database file */ \nSQLITE_PRIVATE int sqlite3WalCheckpoint(\n  Wal *pWal,                      /* Write-ahead log connection */\n  int eMode,                      /* One of PASSIVE, FULL and RESTART */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags to sync db file with (or 0) */\n  int nBuf,                       /* Size of buffer nBuf */\n  u8 *zBuf,                       /* Temporary buffer to use */\n  int *pnLog,                     /* OUT: Number of frames in WAL */\n  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */\n);\n\n/* Return the value to pass to a sqlite3_wal_hook callback, the\n** number of frames in the WAL at the point of the last commit since\n** sqlite3WalCallback() was called.  If no commits have occurred since\n** the last call, then return 0.\n*/\nSQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);\n\n/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)\n** by the pager layer on the database file.\n*/\nSQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);\n\n/* Return true if the argument is non-NULL and the WAL module is using\n** heap-memory for the wal-index. Otherwise, if the argument is NULL or the\n** WAL module is using shared-memory, return false. \n*/\nSQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/* If the WAL file is not empty, return the number of bytes of content\n** stored in each frame (i.e. the db page-size when the WAL was created).\n*/\nSQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);\n#endif\n\n#endif /* ifndef SQLITE_OMIT_WAL */\n#endif /* _WAL_H_ */\n\n/************** End of wal.h *************************************************/\n/************** Continuing where we left off in pager.c **********************/\n\n\n/******************* NOTES ON THE DESIGN OF THE PAGER ************************\n**\n** This comment block describes invariants that hold when using a rollback\n** journal.  These invariants do not apply for journal_mode=WAL,\n** journal_mode=MEMORY, or journal_mode=OFF.\n**\n** Within this comment block, a page is deemed to have been synced\n** automatically as soon as it is written when PRAGMA synchronous=OFF.\n** Otherwise, the page is not synced until the xSync method of the VFS\n** is called successfully on the file containing the page.\n**\n** Definition:  A page of the database file is said to be \"overwriteable\" if\n** one or more of the following are true about the page:\n** \n**     (a)  The original content of the page as it was at the beginning of\n**          the transaction has been written into the rollback journal and\n**          synced.\n** \n**     (b)  The page was a freelist leaf page at the start of the transaction.\n** \n**     (c)  The page number is greater than the largest page that existed in\n**          the database file at the start of the transaction.\n** \n** (1) A page of the database file is never overwritten unless one of the\n**     following are true:\n** \n**     (a) The page and all other pages on the same sector are overwriteable.\n** \n**     (b) The atomic page write optimization is enabled, and the entire\n**         transaction other than the update of the transaction sequence\n**         number consists of a single page change.\n** \n** (2) The content of a page written into the rollback journal exactly matches\n**     both the content in the database when the rollback journal was written\n**     and the content in the database at the beginning of the current\n**     transaction.\n** \n** (3) Writes to the database file are an integer multiple of the page size\n**     in length and are aligned on a page boundary.\n** \n** (4) Reads from the database file are either aligned on a page boundary and\n**     an integer multiple of the page size in length or are taken from the\n**     first 100 bytes of the database file.\n** \n** (5) All writes to the database file are synced prior to the rollback journal\n**     being deleted, truncated, or zeroed.\n** \n** (6) If a master journal file is used, then all writes to the database file\n**     are synced prior to the master journal being deleted.\n** \n** Definition: Two databases (or the same database at two points it time)\n** are said to be \"logically equivalent\" if they give the same answer to\n** all queries.  Note in particular the content of freelist leaf\n** pages can be changed arbitarily without effecting the logical equivalence\n** of the database.\n** \n** (7) At any time, if any subset, including the empty set and the total set,\n**     of the unsynced changes to a rollback journal are removed and the \n**     journal is rolled back, the resulting database file will be logical\n**     equivalent to the database file at the beginning of the transaction.\n** \n** (8) When a transaction is rolled back, the xTruncate method of the VFS\n**     is called to restore the database file to the same size it was at\n**     the beginning of the transaction.  (In some VFSes, the xTruncate\n**     method is a no-op, but that does not change the fact the SQLite will\n**     invoke it.)\n** \n** (9) Whenever the database file is modified, at least one bit in the range\n**     of bytes from 24 through 39 inclusive will be changed prior to releasing\n**     the EXCLUSIVE lock, thus signaling other connections on the same\n**     database to flush their caches.\n**\n** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less\n**      than one billion transactions.\n**\n** (11) A database file is well-formed at the beginning and at the conclusion\n**      of every transaction.\n**\n** (12) An EXCLUSIVE lock is held on the database file when writing to\n**      the database file.\n**\n** (13) A SHARED lock is held on the database file while reading any\n**      content out of the database file.\n**\n******************************************************************************/\n\n/*\n** Macros for troubleshooting.  Normally turned off\n*/\n#if 0\nint sqlite3PagerTrace=1;  /* True to enable tracing */\n#define sqlite3DebugPrintf printf\n#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }\n#else\n#define PAGERTRACE(X)\n#endif\n\n/*\n** The following two macros are used within the PAGERTRACE() macros above\n** to print out file-descriptors. \n**\n** PAGERID() takes a pointer to a Pager struct as its argument. The\n** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file\n** struct as its argument.\n*/\n#define PAGERID(p) ((int)(p->fd))\n#define FILEHANDLEID(fd) ((int)fd)\n\n/*\n** The Pager.eState variable stores the current 'state' of a pager. A\n** pager may be in any one of the seven states shown in the following\n** state diagram.\n**\n**                            OPEN <------+------+\n**                              |         |      |\n**                              V         |      |\n**               +---------> READER-------+      |\n**               |              |                |\n**               |              V                |\n**               |<-------WRITER_LOCKED------> ERROR\n**               |              |                ^  \n**               |              V                |\n**               |<------WRITER_CACHEMOD-------->|\n**               |              |                |\n**               |              V                |\n**               |<-------WRITER_DBMOD---------->|\n**               |              |                |\n**               |              V                |\n**               +<------WRITER_FINISHED-------->+\n**\n**\n** List of state transitions and the C [function] that performs each:\n** \n**   OPEN              -> READER              [sqlite3PagerSharedLock]\n**   READER            -> OPEN                [pager_unlock]\n**\n**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]\n**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]\n**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]\n**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]\n**   WRITER_***        -> READER              [pager_end_transaction]\n**\n**   WRITER_***        -> ERROR               [pager_error]\n**   ERROR             -> OPEN                [pager_unlock]\n** \n**\n**  OPEN:\n**\n**    The pager starts up in this state. Nothing is guaranteed in this\n**    state - the file may or may not be locked and the database size is\n**    unknown. The database may not be read or written.\n**\n**    * No read or write transaction is active.\n**    * Any lock, or no lock at all, may be held on the database file.\n**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.\n**\n**  READER:\n**\n**    In this state all the requirements for reading the database in \n**    rollback (non-WAL) mode are met. Unless the pager is (or recently\n**    was) in exclusive-locking mode, a user-level read transaction is \n**    open. The database size is known in this state.\n**\n**    A connection running with locking_mode=normal enters this state when\n**    it opens a read-transaction on the database and returns to state\n**    OPEN after the read-transaction is completed. However a connection\n**    running in locking_mode=exclusive (including temp databases) remains in\n**    this state even after the read-transaction is closed. The only way\n**    a locking_mode=exclusive connection can transition from READER to OPEN\n**    is via the ERROR state (see below).\n** \n**    * A read transaction may be active (but a write-transaction cannot).\n**    * A SHARED or greater lock is held on the database file.\n**    * The dbSize variable may be trusted (even if a user-level read \n**      transaction is not active). The dbOrigSize and dbFileSize variables\n**      may not be trusted at this point.\n**    * If the database is a WAL database, then the WAL connection is open.\n**    * Even if a read-transaction is not open, it is guaranteed that \n**      there is no hot-journal in the file-system.\n**\n**  WRITER_LOCKED:\n**\n**    The pager moves to this state from READER when a write-transaction\n**    is first opened on the database. In WRITER_LOCKED state, all locks \n**    required to start a write-transaction are held, but no actual \n**    modifications to the cache or database have taken place.\n**\n**    In rollback mode, a RESERVED or (if the transaction was opened with \n**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when\n**    moving to this state, but the journal file is not written to or opened \n**    to in this state. If the transaction is committed or rolled back while \n**    in WRITER_LOCKED state, all that is required is to unlock the database \n**    file.\n**\n**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.\n**    If the connection is running with locking_mode=exclusive, an attempt\n**    is made to obtain an EXCLUSIVE lock on the database file.\n**\n**    * A write transaction is active.\n**    * If the connection is open in rollback-mode, a RESERVED or greater \n**      lock is held on the database file.\n**    * If the connection is open in WAL-mode, a WAL write transaction\n**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully\n**      called).\n**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.\n**    * The contents of the pager cache have not been modified.\n**    * The journal file may or may not be open.\n**    * Nothing (not even the first header) has been written to the journal.\n**\n**  WRITER_CACHEMOD:\n**\n**    A pager moves from WRITER_LOCKED state to this state when a page is\n**    first modified by the upper layer. In rollback mode the journal file\n**    is opened (if it is not already open) and a header written to the\n**    start of it. The database file on disk has not been modified.\n**\n**    * A write transaction is active.\n**    * A RESERVED or greater lock is held on the database file.\n**    * The journal file is open and the first header has been written \n**      to it, but the header has not been synced to disk.\n**    * The contents of the page cache have been modified.\n**\n**  WRITER_DBMOD:\n**\n**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state\n**    when it modifies the contents of the database file. WAL connections\n**    never enter this state (since they do not modify the database file,\n**    just the log file).\n**\n**    * A write transaction is active.\n**    * An EXCLUSIVE or greater lock is held on the database file.\n**    * The journal file is open and the first header has been written \n**      and synced to disk.\n**    * The contents of the page cache have been modified (and possibly\n**      written to disk).\n**\n**  WRITER_FINISHED:\n**\n**    It is not possible for a WAL connection to enter this state.\n**\n**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD\n**    state after the entire transaction has been successfully written into the\n**    database file. In this state the transaction may be committed simply\n**    by finalizing the journal file. Once in WRITER_FINISHED state, it is \n**    not possible to modify the database further. At this point, the upper \n**    layer must either commit or rollback the transaction.\n**\n**    * A write transaction is active.\n**    * An EXCLUSIVE or greater lock is held on the database file.\n**    * All writing and syncing of journal and database data has finished.\n**      If no error occured, all that remains is to finalize the journal to\n**      commit the transaction. If an error did occur, the caller will need\n**      to rollback the transaction. \n**\n**  ERROR:\n**\n**    The ERROR state is entered when an IO or disk-full error (including\n**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it \n**    difficult to be sure that the in-memory pager state (cache contents, \n**    db size etc.) are consistent with the contents of the file-system.\n**\n**    Temporary pager files may enter the ERROR state, but in-memory pagers\n**    cannot.\n**\n**    For example, if an IO error occurs while performing a rollback, \n**    the contents of the page-cache may be left in an inconsistent state.\n**    At this point it would be dangerous to change back to READER state\n**    (as usually happens after a rollback). Any subsequent readers might\n**    report database corruption (due to the inconsistent cache), and if\n**    they upgrade to writers, they may inadvertently corrupt the database\n**    file. To avoid this hazard, the pager switches into the ERROR state\n**    instead of READER following such an error.\n**\n**    Once it has entered the ERROR state, any attempt to use the pager\n**    to read or write data returns an error. Eventually, once all \n**    outstanding transactions have been abandoned, the pager is able to\n**    transition back to OPEN state, discarding the contents of the \n**    page-cache and any other in-memory state at the same time. Everything\n**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)\n**    when a read-transaction is next opened on the pager (transitioning\n**    the pager into READER state). At that point the system has recovered \n**    from the error.\n**\n**    Specifically, the pager jumps into the ERROR state if:\n**\n**      1. An error occurs while attempting a rollback. This happens in\n**         function sqlite3PagerRollback().\n**\n**      2. An error occurs while attempting to finalize a journal file\n**         following a commit in function sqlite3PagerCommitPhaseTwo().\n**\n**      3. An error occurs while attempting to write to the journal or\n**         database file in function pagerStress() in order to free up\n**         memory.\n**\n**    In other cases, the error is returned to the b-tree layer. The b-tree\n**    layer then attempts a rollback operation. If the error condition \n**    persists, the pager enters the ERROR state via condition (1) above.\n**\n**    Condition (3) is necessary because it can be triggered by a read-only\n**    statement executed within a transaction. In this case, if the error\n**    code were simply returned to the user, the b-tree layer would not\n**    automatically attempt a rollback, as it assumes that an error in a\n**    read-only statement cannot leave the pager in an internally inconsistent \n**    state.\n**\n**    * The Pager.errCode variable is set to something other than SQLITE_OK.\n**    * There are one or more outstanding references to pages (after the\n**      last reference is dropped the pager should move back to OPEN state).\n**    * The pager is not an in-memory pager.\n**    \n**\n** Notes:\n**\n**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the\n**     connection is open in WAL mode. A WAL connection is always in one\n**     of the first four states.\n**\n**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN\n**     state. There are two exceptions: immediately after exclusive-mode has\n**     been turned on (and before any read or write transactions are \n**     executed), and when the pager is leaving the \"error state\".\n**\n**   * See also: assert_pager_state().\n*/\n#define PAGER_OPEN                  0\n#define PAGER_READER                1\n#define PAGER_WRITER_LOCKED         2\n#define PAGER_WRITER_CACHEMOD       3\n#define PAGER_WRITER_DBMOD          4\n#define PAGER_WRITER_FINISHED       5\n#define PAGER_ERROR                 6\n\n/*\n** The Pager.eLock variable is almost always set to one of the \n** following locking-states, according to the lock currently held on\n** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.\n** This variable is kept up to date as locks are taken and released by\n** the pagerLockDb() and pagerUnlockDb() wrappers.\n**\n** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY\n** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not\n** the operation was successful. In these circumstances pagerLockDb() and\n** pagerUnlockDb() take a conservative approach - eLock is always updated\n** when unlocking the file, and only updated when locking the file if the\n** VFS call is successful. This way, the Pager.eLock variable may be set\n** to a less exclusive (lower) value than the lock that is actually held\n** at the system level, but it is never set to a more exclusive value.\n**\n** This is usually safe. If an xUnlock fails or appears to fail, there may \n** be a few redundant xLock() calls or a lock may be held for longer than\n** required, but nothing really goes wrong.\n**\n** The exception is when the database file is unlocked as the pager moves\n** from ERROR to OPEN state. At this point there may be a hot-journal file \n** in the file-system that needs to be rolled back (as part of a OPEN->SHARED\n** transition, by the same pager or any other). If the call to xUnlock()\n** fails at this point and the pager is left holding an EXCLUSIVE lock, this\n** can confuse the call to xCheckReservedLock() call made later as part\n** of hot-journal detection.\n**\n** xCheckReservedLock() is defined as returning true \"if there is a RESERVED \n** lock held by this process or any others\". So xCheckReservedLock may \n** return true because the caller itself is holding an EXCLUSIVE lock (but\n** doesn't know it because of a previous error in xUnlock). If this happens\n** a hot-journal may be mistaken for a journal being created by an active\n** transaction in another process, causing SQLite to read from the database\n** without rolling it back.\n**\n** To work around this, if a call to xUnlock() fails when unlocking the\n** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It\n** is only changed back to a real locking state after a successful call\n** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition\n** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK \n** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE\n** lock on the database file before attempting to roll it back. See function\n** PagerSharedLock() for more detail.\n**\n** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in \n** PAGER_OPEN state.\n*/\n#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)\n\n/*\n** A macro used for invoking the codec if there is one\n*/\n#ifdef SQLITE_HAS_CODEC\n# define CODEC1(P,D,N,X,E) \\\n    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }\n# define CODEC2(P,D,N,X,E,O) \\\n    if( P->xCodec==0 ){ O=(char*)D; }else \\\n    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }\n#else\n# define CODEC1(P,D,N,X,E)   /* NO-OP */\n# define CODEC2(P,D,N,X,E,O) O=(char*)D\n#endif\n\n/*\n** The maximum allowed sector size. 64KiB. If the xSectorsize() method \n** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.\n** This could conceivably cause corruption following a power failure on\n** such a system. This is currently an undocumented limit.\n*/\n#define MAX_SECTOR_SIZE 0x10000\n\n/*\n** An instance of the following structure is allocated for each active\n** savepoint and statement transaction in the system. All such structures\n** are stored in the Pager.aSavepoint[] array, which is allocated and\n** resized using sqlite3Realloc().\n**\n** When a savepoint is created, the PagerSavepoint.iHdrOffset field is\n** set to 0. If a journal-header is written into the main journal while\n** the savepoint is active, then iHdrOffset is set to the byte offset \n** immediately following the last journal record written into the main\n** journal before the journal-header. This is required during savepoint\n** rollback (see pagerPlaybackSavepoint()).\n*/\ntypedef struct PagerSavepoint PagerSavepoint;\nstruct PagerSavepoint {\n  i64 iOffset;                 /* Starting offset in main journal */\n  i64 iHdrOffset;              /* See above */\n  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */\n  Pgno nOrig;                  /* Original number of pages in file */\n  Pgno iSubRec;                /* Index of first record in sub-journal */\n#ifndef SQLITE_OMIT_WAL\n  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */\n#endif\n};\n\n/*\n** A open page cache is an instance of struct Pager. A description of\n** some of the more important member variables follows:\n**\n** eState\n**\n**   The current 'state' of the pager object. See the comment and state\n**   diagram above for a description of the pager state.\n**\n** eLock\n**\n**   For a real on-disk database, the current lock held on the database file -\n**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.\n**\n**   For a temporary or in-memory database (neither of which require any\n**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such\n**   databases always have Pager.exclusiveMode==1, this tricks the pager\n**   logic into thinking that it already has all the locks it will ever\n**   need (and no reason to release them).\n**\n**   In some (obscure) circumstances, this variable may also be set to\n**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for\n**   details.\n**\n** changeCountDone\n**\n**   This boolean variable is used to make sure that the change-counter \n**   (the 4-byte header field at byte offset 24 of the database file) is \n**   not updated more often than necessary. \n**\n**   It is set to true when the change-counter field is updated, which \n**   can only happen if an exclusive lock is held on the database file.\n**   It is cleared (set to false) whenever an exclusive lock is \n**   relinquished on the database file. Each time a transaction is committed,\n**   The changeCountDone flag is inspected. If it is true, the work of\n**   updating the change-counter is omitted for the current transaction.\n**\n**   This mechanism means that when running in exclusive mode, a connection \n**   need only update the change-counter once, for the first transaction\n**   committed.\n**\n** setMaster\n**\n**   When PagerCommitPhaseOne() is called to commit a transaction, it may\n**   (or may not) specify a master-journal name to be written into the \n**   journal file before it is synced to disk.\n**\n**   Whether or not a journal file contains a master-journal pointer affects \n**   the way in which the journal file is finalized after the transaction is \n**   committed or rolled back when running in \"journal_mode=PERSIST\" mode.\n**   If a journal file does not contain a master-journal pointer, it is\n**   finalized by overwriting the first journal header with zeroes. If\n**   it does contain a master-journal pointer the journal file is finalized \n**   by truncating it to zero bytes, just as if the connection were \n**   running in \"journal_mode=truncate\" mode.\n**\n**   Journal files that contain master journal pointers cannot be finalized\n**   simply by overwriting the first journal-header with zeroes, as the\n**   master journal pointer could interfere with hot-journal rollback of any\n**   subsequently interrupted transaction that reuses the journal file.\n**\n**   The flag is cleared as soon as the journal file is finalized (either\n**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the\n**   journal file from being successfully finalized, the setMaster flag\n**   is cleared anyway (and the pager will move to ERROR state).\n**\n** doNotSpill, doNotSyncSpill\n**\n**   These two boolean variables control the behaviour of cache-spills\n**   (calls made by the pcache module to the pagerStress() routine to\n**   write cached data to the file-system in order to free up memory).\n**\n**   When doNotSpill is non-zero, writing to the database from pagerStress()\n**   is disabled altogether. This is done in a very obscure case that\n**   comes up during savepoint rollback that requires the pcache module\n**   to allocate a new page to prevent the journal file from being written\n**   while it is being traversed by code in pager_playback().\n** \n**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()\n**   is permitted, but syncing the journal file is not. This flag is set\n**   by sqlite3PagerWrite() when the file-system sector-size is larger than\n**   the database page-size in order to prevent a journal sync from happening \n**   in between the journalling of two pages on the same sector. \n**\n** subjInMemory\n**\n**   This is a boolean variable. If true, then any required sub-journal\n**   is opened as an in-memory journal file. If false, then in-memory\n**   sub-journals are only used for in-memory pager files.\n**\n**   This variable is updated by the upper layer each time a new \n**   write-transaction is opened.\n**\n** dbSize, dbOrigSize, dbFileSize\n**\n**   Variable dbSize is set to the number of pages in the database file.\n**   It is valid in PAGER_READER and higher states (all states except for\n**   OPEN and ERROR). \n**\n**   dbSize is set based on the size of the database file, which may be \n**   larger than the size of the database (the value stored at offset\n**   28 of the database header by the btree). If the size of the file\n**   is not an integer multiple of the page-size, the value stored in\n**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).\n**   Except, any file that is greater than 0 bytes in size is considered\n**   to have at least one page. (i.e. a 1KB file with 2K page-size leads\n**   to dbSize==1).\n**\n**   During a write-transaction, if pages with page-numbers greater than\n**   dbSize are modified in the cache, dbSize is updated accordingly.\n**   Similarly, if the database is truncated using PagerTruncateImage(), \n**   dbSize is updated.\n**\n**   Variables dbOrigSize and dbFileSize are valid in states \n**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize\n**   variable at the start of the transaction. It is used during rollback,\n**   and to determine whether or not pages need to be journalled before\n**   being modified.\n**\n**   Throughout a write-transaction, dbFileSize contains the size of\n**   the file on disk in pages. It is set to a copy of dbSize when the\n**   write-transaction is first opened, and updated when VFS calls are made\n**   to write or truncate the database file on disk. \n**\n**   The only reason the dbFileSize variable is required is to suppress \n**   unnecessary calls to xTruncate() after committing a transaction. If, \n**   when a transaction is committed, the dbFileSize variable indicates \n**   that the database file is larger than the database image (Pager.dbSize), \n**   pager_truncate() is called. The pager_truncate() call uses xFilesize()\n**   to measure the database file on disk, and then truncates it if required.\n**   dbFileSize is not used when rolling back a transaction. In this case\n**   pager_truncate() is called unconditionally (which means there may be\n**   a call to xFilesize() that is not strictly required). In either case,\n**   pager_truncate() may cause the file to become smaller or larger.\n**\n** dbHintSize\n**\n**   The dbHintSize variable is used to limit the number of calls made to\n**   the VFS xFileControl(FCNTL_SIZE_HINT) method. \n**\n**   dbHintSize is set to a copy of the dbSize variable when a\n**   write-transaction is opened (at the same time as dbFileSize and\n**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,\n**   dbHintSize is increased to the number of pages that correspond to the\n**   size-hint passed to the method call. See pager_write_pagelist() for \n**   details.\n**\n** errCode\n**\n**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It\n**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode \n**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX \n**   sub-codes.\n*/\nstruct Pager {\n  sqlite3_vfs *pVfs;          /* OS functions to use for IO */\n  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */\n  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */\n  u8 useJournal;              /* Use a rollback journal on this file */\n  u8 noSync;                  /* Do not sync the journal if true */\n  u8 fullSync;                /* Do extra syncs of the journal for robustness */\n  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */\n  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */\n  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */\n  u8 tempFile;                /* zFilename is a temporary file */\n  u8 readOnly;                /* True for a read-only database */\n  u8 memDb;                   /* True to inhibit all file I/O */\n\n  /**************************************************************************\n  ** The following block contains those class members that change during\n  ** routine opertion.  Class members not in this block are either fixed\n  ** when the pager is first created or else only change when there is a\n  ** significant mode change (such as changing the page_size, locking_mode,\n  ** or the journal_mode).  From another view, these class members describe\n  ** the \"state\" of the pager, while other class members describe the\n  ** \"configuration\" of the pager.\n  */\n  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */\n  u8 eLock;                   /* Current lock held on database file */\n  u8 changeCountDone;         /* Set after incrementing the change-counter */\n  u8 setMaster;               /* True if a m-j name has been written to jrnl */\n  u8 doNotSpill;              /* Do not spill the cache when non-zero */\n  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */\n  u8 subjInMemory;            /* True to use in-memory sub-journals */\n  Pgno dbSize;                /* Number of pages in the database */\n  Pgno dbOrigSize;            /* dbSize before the current transaction */\n  Pgno dbFileSize;            /* Number of pages in the database file */\n  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */\n  int errCode;                /* One of several kinds of errors */\n  int nRec;                   /* Pages journalled since last j-header written */\n  u32 cksumInit;              /* Quasi-random value added to every checksum */\n  u32 nSubRec;                /* Number of records written to sub-journal */\n  Bitvec *pInJournal;         /* One bit for each page in the database file */\n  sqlite3_file *fd;           /* File descriptor for database */\n  sqlite3_file *jfd;          /* File descriptor for main journal */\n  sqlite3_file *sjfd;         /* File descriptor for sub-journal */\n  i64 journalOff;             /* Current write offset in the journal file */\n  i64 journalHdr;             /* Byte offset to previous journal header */\n  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */\n  PagerSavepoint *aSavepoint; /* Array of active savepoints */\n  int nSavepoint;             /* Number of elements in aSavepoint[] */\n  char dbFileVers[16];        /* Changes whenever database file changes */\n  /*\n  ** End of the routinely-changing class members\n  ***************************************************************************/\n\n  u16 nExtra;                 /* Add this many bytes to each in-memory page */\n  i16 nReserve;               /* Number of unused bytes at end of each page */\n  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */\n  u32 sectorSize;             /* Assumed sector size during rollback */\n  int pageSize;               /* Number of bytes in a page */\n  Pgno mxPgno;                /* Maximum allowed size of the database */\n  i64 journalSizeLimit;       /* Size limit for persistent journal files */\n  char *zFilename;            /* Name of the database file */\n  char *zJournal;             /* Name of the journal file */\n  int (*xBusyHandler)(void*); /* Function to call when busy */\n  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */\n  int aStat[3];               /* Total cache hits, misses and writes */\n#ifdef SQLITE_TEST\n  int nRead;                  /* Database pages read */\n#endif\n  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */\n#ifdef SQLITE_HAS_CODEC\n  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */\n  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */\n  void (*xCodecFree)(void*);             /* Destructor for the codec */\n  void *pCodec;               /* First argument to xCodec... methods */\n#endif\n  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */\n  PCache *pPCache;            /* Pointer to page cache object */\n#ifndef SQLITE_OMIT_WAL\n  Wal *pWal;                  /* Write-ahead log used by \"journal_mode=wal\" */\n  char *zWal;                 /* File name for write-ahead log */\n#endif\n};\n\n/*\n** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains\n** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS \n** or CACHE_WRITE to sqlite3_db_status().\n*/\n#define PAGER_STAT_HIT   0\n#define PAGER_STAT_MISS  1\n#define PAGER_STAT_WRITE 2\n\n/*\n** The following global variables hold counters used for\n** testing purposes only.  These variables do not exist in\n** a non-testing build.  These variables are not thread-safe.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */\nSQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */\nSQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */\n# define PAGER_INCR(v)  v++\n#else\n# define PAGER_INCR(v)\n#endif\n\n\n\n/*\n** Journal files begin with the following magic string.  The data\n** was obtained from /dev/random.  It is used only as a sanity check.\n**\n** Since version 2.8.0, the journal format contains additional sanity\n** checking information.  If the power fails while the journal is being\n** written, semi-random garbage data might appear in the journal\n** file after power is restored.  If an attempt is then made\n** to roll the journal back, the database could be corrupted.  The additional\n** sanity checking data is an attempt to discover the garbage in the\n** journal and ignore it.\n**\n** The sanity checking information for the new journal format consists\n** of a 32-bit checksum on each page of data.  The checksum covers both\n** the page number and the pPager->pageSize bytes of data for the page.\n** This cksum is initialized to a 32-bit random value that appears in the\n** journal file right after the header.  The random initializer is important,\n** because garbage data that appears at the end of a journal is likely\n** data that was once in other files that have now been deleted.  If the\n** garbage data came from an obsolete journal file, the checksums might\n** be correct.  But by initializing the checksum to random value which\n** is different for every journal, we minimize that risk.\n*/\nstatic const unsigned char aJournalMagic[] = {\n  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,\n};\n\n/*\n** The size of the of each page record in the journal is given by\n** the following macro.\n*/\n#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)\n\n/*\n** The journal header size for this pager. This is usually the same \n** size as a single disk sector. See also setSectorSize().\n*/\n#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)\n\n/*\n** The macro MEMDB is true if we are dealing with an in-memory database.\n** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,\n** the value of MEMDB will be a constant and the compiler will optimize\n** out code that would never execute.\n*/\n#ifdef SQLITE_OMIT_MEMORYDB\n# define MEMDB 0\n#else\n# define MEMDB pPager->memDb\n#endif\n\n/*\n** The maximum legal page number is (2^31 - 1).\n*/\n#define PAGER_MAX_PGNO 2147483647\n\n/*\n** The argument to this macro is a file descriptor (type sqlite3_file*).\n** Return 0 if it is not open, or non-zero (but not 1) if it is.\n**\n** This is so that expressions can be written as:\n**\n**   if( isOpen(pPager->jfd) ){ ...\n**\n** instead of\n**\n**   if( pPager->jfd->pMethods ){ ...\n*/\n#define isOpen(pFd) ((pFd)->pMethods)\n\n/*\n** Return true if this pager uses a write-ahead log instead of the usual\n** rollback journal. Otherwise false.\n*/\n#ifndef SQLITE_OMIT_WAL\nstatic int pagerUseWal(Pager *pPager){\n  return (pPager->pWal!=0);\n}\n#else\n# define pagerUseWal(x) 0\n# define pagerRollbackWal(x) 0\n# define pagerWalFrames(v,w,x,y) 0\n# define pagerOpenWalIfPresent(z) SQLITE_OK\n# define pagerBeginReadTransaction(z) SQLITE_OK\n#endif\n\n#ifndef NDEBUG \n/*\n** Usage:\n**\n**   assert( assert_pager_state(pPager) );\n**\n** This function runs many asserts to try to find inconsistencies in\n** the internal state of the Pager object.\n*/\nstatic int assert_pager_state(Pager *p){\n  Pager *pPager = p;\n\n  /* State must be valid. */\n  assert( p->eState==PAGER_OPEN\n       || p->eState==PAGER_READER\n       || p->eState==PAGER_WRITER_LOCKED\n       || p->eState==PAGER_WRITER_CACHEMOD\n       || p->eState==PAGER_WRITER_DBMOD\n       || p->eState==PAGER_WRITER_FINISHED\n       || p->eState==PAGER_ERROR\n  );\n\n  /* Regardless of the current state, a temp-file connection always behaves\n  ** as if it has an exclusive lock on the database file. It never updates\n  ** the change-counter field, so the changeCountDone flag is always set.\n  */\n  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );\n  assert( p->tempFile==0 || pPager->changeCountDone );\n\n  /* If the useJournal flag is clear, the journal-mode must be \"OFF\". \n  ** And if the journal-mode is \"OFF\", the journal file must not be open.\n  */\n  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );\n  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );\n\n  /* Check that MEMDB implies noSync. And an in-memory journal. Since \n  ** this means an in-memory pager performs no IO at all, it cannot encounter \n  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing \n  ** a journal file. (although the in-memory journal implementation may \n  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It \n  ** is therefore not possible for an in-memory pager to enter the ERROR \n  ** state.\n  */\n  if( MEMDB ){\n    assert( p->noSync );\n    assert( p->journalMode==PAGER_JOURNALMODE_OFF \n         || p->journalMode==PAGER_JOURNALMODE_MEMORY \n    );\n    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );\n    assert( pagerUseWal(p)==0 );\n  }\n\n  /* If changeCountDone is set, a RESERVED lock or greater must be held\n  ** on the file.\n  */\n  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );\n  assert( p->eLock!=PENDING_LOCK );\n\n  switch( p->eState ){\n    case PAGER_OPEN:\n      assert( !MEMDB );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );\n      break;\n\n    case PAGER_READER:\n      assert( pPager->errCode==SQLITE_OK );\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( p->eLock>=SHARED_LOCK );\n      break;\n\n    case PAGER_WRITER_LOCKED:\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      if( !pagerUseWal(pPager) ){\n        assert( p->eLock>=RESERVED_LOCK );\n      }\n      assert( pPager->dbSize==pPager->dbOrigSize );\n      assert( pPager->dbOrigSize==pPager->dbFileSize );\n      assert( pPager->dbOrigSize==pPager->dbHintSize );\n      assert( pPager->setMaster==0 );\n      break;\n\n    case PAGER_WRITER_CACHEMOD:\n      assert( p->eLock!=UNKNOWN_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      if( !pagerUseWal(pPager) ){\n        /* It is possible that if journal_mode=wal here that neither the\n        ** journal file nor the WAL file are open. This happens during\n        ** a rollback transaction that switches from journal_mode=off\n        ** to journal_mode=wal.\n        */\n        assert( p->eLock>=RESERVED_LOCK );\n        assert( isOpen(p->jfd) \n             || p->journalMode==PAGER_JOURNALMODE_OFF \n             || p->journalMode==PAGER_JOURNALMODE_WAL \n        );\n      }\n      assert( pPager->dbOrigSize==pPager->dbFileSize );\n      assert( pPager->dbOrigSize==pPager->dbHintSize );\n      break;\n\n    case PAGER_WRITER_DBMOD:\n      assert( p->eLock==EXCLUSIVE_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( !pagerUseWal(pPager) );\n      assert( p->eLock>=EXCLUSIVE_LOCK );\n      assert( isOpen(p->jfd) \n           || p->journalMode==PAGER_JOURNALMODE_OFF \n           || p->journalMode==PAGER_JOURNALMODE_WAL \n      );\n      assert( pPager->dbOrigSize<=pPager->dbHintSize );\n      break;\n\n    case PAGER_WRITER_FINISHED:\n      assert( p->eLock==EXCLUSIVE_LOCK );\n      assert( pPager->errCode==SQLITE_OK );\n      assert( !pagerUseWal(pPager) );\n      assert( isOpen(p->jfd) \n           || p->journalMode==PAGER_JOURNALMODE_OFF \n           || p->journalMode==PAGER_JOURNALMODE_WAL \n      );\n      break;\n\n    case PAGER_ERROR:\n      /* There must be at least one outstanding reference to the pager if\n      ** in ERROR state. Otherwise the pager should have already dropped\n      ** back to OPEN state.\n      */\n      assert( pPager->errCode!=SQLITE_OK );\n      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );\n      break;\n  }\n\n  return 1;\n}\n#endif /* ifndef NDEBUG */\n\n#ifdef SQLITE_DEBUG \n/*\n** Return a pointer to a human readable string in a static buffer\n** containing the state of the Pager object passed as an argument. This\n** is intended to be used within debuggers. For example, as an alternative\n** to \"print *pPager\" in gdb:\n**\n** (gdb) printf \"%s\", print_pager_state(pPager)\n*/\nstatic char *print_pager_state(Pager *p){\n  static char zRet[1024];\n\n  sqlite3_snprintf(1024, zRet,\n      \"Filename:      %s\\n\"\n      \"State:         %s errCode=%d\\n\"\n      \"Lock:          %s\\n\"\n      \"Locking mode:  locking_mode=%s\\n\"\n      \"Journal mode:  journal_mode=%s\\n\"\n      \"Backing store: tempFile=%d memDb=%d useJournal=%d\\n\"\n      \"Journal:       journalOff=%lld journalHdr=%lld\\n\"\n      \"Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\\n\"\n      , p->zFilename\n      , p->eState==PAGER_OPEN            ? \"OPEN\" :\n        p->eState==PAGER_READER          ? \"READER\" :\n        p->eState==PAGER_WRITER_LOCKED   ? \"WRITER_LOCKED\" :\n        p->eState==PAGER_WRITER_CACHEMOD ? \"WRITER_CACHEMOD\" :\n        p->eState==PAGER_WRITER_DBMOD    ? \"WRITER_DBMOD\" :\n        p->eState==PAGER_WRITER_FINISHED ? \"WRITER_FINISHED\" :\n        p->eState==PAGER_ERROR           ? \"ERROR\" : \"?error?\"\n      , (int)p->errCode\n      , p->eLock==NO_LOCK         ? \"NO_LOCK\" :\n        p->eLock==RESERVED_LOCK   ? \"RESERVED\" :\n        p->eLock==EXCLUSIVE_LOCK  ? \"EXCLUSIVE\" :\n        p->eLock==SHARED_LOCK     ? \"SHARED\" :\n        p->eLock==UNKNOWN_LOCK    ? \"UNKNOWN\" : \"?error?\"\n      , p->exclusiveMode ? \"exclusive\" : \"normal\"\n      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? \"memory\" :\n        p->journalMode==PAGER_JOURNALMODE_OFF      ? \"off\" :\n        p->journalMode==PAGER_JOURNALMODE_DELETE   ? \"delete\" :\n        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? \"persist\" :\n        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? \"truncate\" :\n        p->journalMode==PAGER_JOURNALMODE_WAL      ? \"wal\" : \"?error?\"\n      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal\n      , p->journalOff, p->journalHdr\n      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize\n  );\n\n  return zRet;\n}\n#endif\n\n/*\n** Return true if it is necessary to write page *pPg into the sub-journal.\n** A page needs to be written into the sub-journal if there exists one\n** or more open savepoints for which:\n**\n**   * The page-number is less than or equal to PagerSavepoint.nOrig, and\n**   * The bit corresponding to the page-number is not set in\n**     PagerSavepoint.pInSavepoint.\n*/\nstatic int subjRequiresPage(PgHdr *pPg){\n  Pgno pgno = pPg->pgno;\n  Pager *pPager = pPg->pPager;\n  int i;\n  for(i=0; i<pPager->nSavepoint; i++){\n    PagerSavepoint *p = &pPager->aSavepoint[i];\n    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Return true if the page is already in the journal file.\n*/\nstatic int pageInJournal(PgHdr *pPg){\n  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);\n}\n\n/*\n** Read a 32-bit integer from the given file descriptor.  Store the integer\n** that is read in *pRes.  Return SQLITE_OK if everything worked, or an\n** error code is something goes wrong.\n**\n** All values are stored on disk as big-endian.\n*/\nstatic int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){\n  unsigned char ac[4];\n  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);\n  if( rc==SQLITE_OK ){\n    *pRes = sqlite3Get4byte(ac);\n  }\n  return rc;\n}\n\n/*\n** Write a 32-bit integer into a string buffer in big-endian byte order.\n*/\n#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)\n\n\n/*\n** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK\n** on success or an error code is something goes wrong.\n*/\nstatic int write32bits(sqlite3_file *fd, i64 offset, u32 val){\n  char ac[4];\n  put32bits(ac, val);\n  return sqlite3OsWrite(fd, ac, 4, offset);\n}\n\n/*\n** Unlock the database file to level eLock, which must be either NO_LOCK\n** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()\n** succeeds, set the Pager.eLock variable to match the (attempted) new lock.\n**\n** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is\n** called, do not modify it. See the comment above the #define of \n** UNKNOWN_LOCK for an explanation of this.\n*/\nstatic int pagerUnlockDb(Pager *pPager, int eLock){\n  int rc = SQLITE_OK;\n\n  assert( !pPager->exclusiveMode || pPager->eLock==eLock );\n  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );\n  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );\n  if( isOpen(pPager->fd) ){\n    assert( pPager->eLock>=eLock );\n    rc = sqlite3OsUnlock(pPager->fd, eLock);\n    if( pPager->eLock!=UNKNOWN_LOCK ){\n      pPager->eLock = (u8)eLock;\n    }\n    IOTRACE((\"UNLOCK %p %d\\n\", pPager, eLock))\n  }\n  return rc;\n}\n\n/*\n** Lock the database file to level eLock, which must be either SHARED_LOCK,\n** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the\n** Pager.eLock variable to the new locking state. \n**\n** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is \n** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. \n** See the comment above the #define of UNKNOWN_LOCK for an explanation \n** of this.\n*/\nstatic int pagerLockDb(Pager *pPager, int eLock){\n  int rc = SQLITE_OK;\n\n  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );\n  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){\n    rc = sqlite3OsLock(pPager->fd, eLock);\n    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){\n      pPager->eLock = (u8)eLock;\n      IOTRACE((\"LOCK %p %d\\n\", pPager, eLock))\n    }\n  }\n  return rc;\n}\n\n/*\n** This function determines whether or not the atomic-write optimization\n** can be used with this pager. The optimization can be used if:\n**\n**  (a) the value returned by OsDeviceCharacteristics() indicates that\n**      a database page may be written atomically, and\n**  (b) the value returned by OsSectorSize() is less than or equal\n**      to the page size.\n**\n** The optimization is also always enabled for temporary files. It is\n** an error to call this function if pPager is opened on an in-memory\n** database.\n**\n** If the optimization cannot be used, 0 is returned. If it can be used,\n** then the value returned is the size of the journal file when it\n** contains rollback data for exactly one page.\n*/\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\nstatic int jrnlBufferSize(Pager *pPager){\n  assert( !MEMDB );\n  if( !pPager->tempFile ){\n    int dc;                           /* Device characteristics */\n    int nSector;                      /* Sector size */\n    int szPage;                       /* Page size */\n\n    assert( isOpen(pPager->fd) );\n    dc = sqlite3OsDeviceCharacteristics(pPager->fd);\n    nSector = pPager->sectorSize;\n    szPage = pPager->pageSize;\n\n    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));\n    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));\n    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){\n      return 0;\n    }\n  }\n\n  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);\n}\n#endif\n\n/*\n** If SQLITE_CHECK_PAGES is defined then we do some sanity checking\n** on the cache using a hash function.  This is used for testing\n** and debugging only.\n*/\n#ifdef SQLITE_CHECK_PAGES\n/*\n** Return a 32-bit hash of the page data for pPage.\n*/\nstatic u32 pager_datahash(int nByte, unsigned char *pData){\n  u32 hash = 0;\n  int i;\n  for(i=0; i<nByte; i++){\n    hash = (hash*1039) + pData[i];\n  }\n  return hash;\n}\nstatic u32 pager_pagehash(PgHdr *pPage){\n  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);\n}\nstatic void pager_set_pagehash(PgHdr *pPage){\n  pPage->pageHash = pager_pagehash(pPage);\n}\n\n/*\n** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES\n** is defined, and NDEBUG is not defined, an assert() statement checks\n** that the page is either dirty or still matches the calculated page-hash.\n*/\n#define CHECK_PAGE(x) checkPage(x)\nstatic void checkPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );\n}\n\n#else\n#define pager_datahash(X,Y)  0\n#define pager_pagehash(X)  0\n#define pager_set_pagehash(X)\n#define CHECK_PAGE(x)\n#endif  /* SQLITE_CHECK_PAGES */\n\n/*\n** When this is called the journal file for pager pPager must be open.\n** This function attempts to read a master journal file name from the \n** end of the file and, if successful, copies it into memory supplied \n** by the caller. See comments above writeMasterJournal() for the format\n** used to store a master journal file name at the end of a journal file.\n**\n** zMaster must point to a buffer of at least nMaster bytes allocated by\n** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is\n** enough space to write the master journal name). If the master journal\n** name in the journal is longer than nMaster bytes (including a\n** nul-terminator), then this is handled as if no master journal name\n** were present in the journal.\n**\n** If a master journal file name is present at the end of the journal\n** file, then it is copied into the buffer pointed to by zMaster. A\n** nul-terminator byte is appended to the buffer following the master\n** journal file name.\n**\n** If it is determined that no master journal file name is present \n** zMaster[0] is set to 0 and SQLITE_OK returned.\n**\n** If an error occurs while reading from the journal file, an SQLite\n** error code is returned.\n*/\nstatic int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){\n  int rc;                    /* Return code */\n  u32 len;                   /* Length in bytes of master journal name */\n  i64 szJ;                   /* Total size in bytes of journal file pJrnl */\n  u32 cksum;                 /* MJ checksum value read from journal */\n  u32 u;                     /* Unsigned loop counter */\n  unsigned char aMagic[8];   /* A buffer to hold the magic header */\n  zMaster[0] = '\\0';\n\n  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))\n   || szJ<16\n   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))\n   || len>=nMaster \n   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))\n   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))\n   || memcmp(aMagic, aJournalMagic, 8)\n   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))\n  ){\n    return rc;\n  }\n\n  /* See if the checksum matches the master journal name */\n  for(u=0; u<len; u++){\n    cksum -= zMaster[u];\n  }\n  if( cksum ){\n    /* If the checksum doesn't add up, then one or more of the disk sectors\n    ** containing the master journal filename is corrupted. This means\n    ** definitely roll back, so just return SQLITE_OK and report a (nul)\n    ** master-journal filename.\n    */\n    len = 0;\n  }\n  zMaster[len] = '\\0';\n   \n  return SQLITE_OK;\n}\n\n/*\n** Return the offset of the sector boundary at or immediately \n** following the value in pPager->journalOff, assuming a sector \n** size of pPager->sectorSize bytes.\n**\n** i.e for a sector size of 512:\n**\n**   Pager.journalOff          Return value\n**   ---------------------------------------\n**   0                         0\n**   512                       512\n**   100                       512\n**   2000                      2048\n** \n*/\nstatic i64 journalHdrOffset(Pager *pPager){\n  i64 offset = 0;\n  i64 c = pPager->journalOff;\n  if( c ){\n    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);\n  }\n  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );\n  assert( offset>=c );\n  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );\n  return offset;\n}\n\n/*\n** The journal file must be open when this function is called.\n**\n** This function is a no-op if the journal file has not been written to\n** within the current transaction (i.e. if Pager.journalOff==0).\n**\n** If doTruncate is non-zero or the Pager.journalSizeLimit variable is\n** set to 0, then truncate the journal file to zero bytes in size. Otherwise,\n** zero the 28-byte header at the start of the journal file. In either case, \n** if the pager is not in no-sync mode, sync the journal file immediately \n** after writing or truncating it.\n**\n** If Pager.journalSizeLimit is set to a positive, non-zero value, and\n** following the truncation or zeroing described above the size of the \n** journal file in bytes is larger than this value, then truncate the\n** journal file to Pager.journalSizeLimit bytes. The journal file does\n** not need to be synced following this operation.\n**\n** If an IO error occurs, abandon processing and return the IO error code.\n** Otherwise, return SQLITE_OK.\n*/\nstatic int zeroJournalHdr(Pager *pPager, int doTruncate){\n  int rc = SQLITE_OK;                               /* Return code */\n  assert( isOpen(pPager->jfd) );\n  if( pPager->journalOff ){\n    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */\n\n    IOTRACE((\"JZEROHDR %p\\n\", pPager))\n    if( doTruncate || iLimit==0 ){\n      rc = sqlite3OsTruncate(pPager->jfd, 0);\n    }else{\n      static const char zeroHdr[28] = {0};\n      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);\n    }\n    if( rc==SQLITE_OK && !pPager->noSync ){\n      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);\n    }\n\n    /* At this point the transaction is committed but the write lock \n    ** is still held on the file. If there is a size limit configured for \n    ** the persistent journal and the journal file currently consumes more\n    ** space than that limit allows for, truncate it now. There is no need\n    ** to sync the file following this operation.\n    */\n    if( rc==SQLITE_OK && iLimit>0 ){\n      i64 sz;\n      rc = sqlite3OsFileSize(pPager->jfd, &sz);\n      if( rc==SQLITE_OK && sz>iLimit ){\n        rc = sqlite3OsTruncate(pPager->jfd, iLimit);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** The journal file must be open when this routine is called. A journal\n** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the\n** current location.\n**\n** The format for the journal header is as follows:\n** - 8 bytes: Magic identifying journal format.\n** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.\n** - 4 bytes: Random number used for page hash.\n** - 4 bytes: Initial database page count.\n** - 4 bytes: Sector size used by the process that wrote this journal.\n** - 4 bytes: Database page size.\n** \n** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.\n*/\nstatic int writeJournalHdr(Pager *pPager){\n  int rc = SQLITE_OK;                 /* Return code */\n  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */\n  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */\n  u32 nWrite;                         /* Bytes of header sector written */\n  int ii;                             /* Loop counter */\n\n  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */\n\n  if( nHeader>JOURNAL_HDR_SZ(pPager) ){\n    nHeader = JOURNAL_HDR_SZ(pPager);\n  }\n\n  /* If there are active savepoints and any of them were created \n  ** since the most recent journal header was written, update the \n  ** PagerSavepoint.iHdrOffset fields now.\n  */\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    if( pPager->aSavepoint[ii].iHdrOffset==0 ){\n      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;\n    }\n  }\n\n  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);\n\n  /* \n  ** Write the nRec Field - the number of page records that follow this\n  ** journal header. Normally, zero is written to this value at this time.\n  ** After the records are added to the journal (and the journal synced, \n  ** if in full-sync mode), the zero is overwritten with the true number\n  ** of records (see syncJournal()).\n  **\n  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When\n  ** reading the journal this value tells SQLite to assume that the\n  ** rest of the journal file contains valid page records. This assumption\n  ** is dangerous, as if a failure occurred whilst writing to the journal\n  ** file it may contain some garbage data. There are two scenarios\n  ** where this risk can be ignored:\n  **\n  **   * When the pager is in no-sync mode. Corruption can follow a\n  **     power failure in this case anyway.\n  **\n  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees\n  **     that garbage data is never appended to the journal file.\n  */\n  assert( isOpen(pPager->fd) || pPager->noSync );\n  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)\n   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) \n  ){\n    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));\n    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);\n  }else{\n    memset(zHeader, 0, sizeof(aJournalMagic)+4);\n  }\n\n  /* The random check-hash initialiser */ \n  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);\n  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);\n  /* The initial database size */\n  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);\n  /* The assumed sector size for this process */\n  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);\n\n  /* The page size */\n  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);\n\n  /* Initializing the tail of the buffer is not necessary.  Everything\n  ** works find if the following memset() is omitted.  But initializing\n  ** the memory prevents valgrind from complaining, so we are willing to\n  ** take the performance hit.\n  */\n  memset(&zHeader[sizeof(aJournalMagic)+20], 0,\n         nHeader-(sizeof(aJournalMagic)+20));\n\n  /* In theory, it is only necessary to write the 28 bytes that the \n  ** journal header consumes to the journal file here. Then increment the \n  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next \n  ** record is written to the following sector (leaving a gap in the file\n  ** that will be implicitly filled in by the OS).\n  **\n  ** However it has been discovered that on some systems this pattern can \n  ** be significantly slower than contiguously writing data to the file,\n  ** even if that means explicitly writing data to the block of \n  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what\n  ** is done. \n  **\n  ** The loop is required here in case the sector-size is larger than the \n  ** database page size. Since the zHeader buffer is only Pager.pageSize\n  ** bytes in size, more than one call to sqlite3OsWrite() may be required\n  ** to populate the entire journal header sector.\n  */ \n  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){\n    IOTRACE((\"JHDR %p %lld %d\\n\", pPager, pPager->journalHdr, nHeader))\n    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);\n    assert( pPager->journalHdr <= pPager->journalOff );\n    pPager->journalOff += nHeader;\n  }\n\n  return rc;\n}\n\n/*\n** The journal file must be open when this is called. A journal header file\n** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal\n** file. The current location in the journal file is given by\n** pPager->journalOff. See comments above function writeJournalHdr() for\n** a description of the journal header format.\n**\n** If the header is read successfully, *pNRec is set to the number of\n** page records following this header and *pDbSize is set to the size of the\n** database before the transaction began, in pages. Also, pPager->cksumInit\n** is set to the value read from the journal header. SQLITE_OK is returned\n** in this case.\n**\n** If the journal header file appears to be corrupted, SQLITE_DONE is\n** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes\n** cannot be read from the journal file an error code is returned.\n*/\nstatic int readJournalHdr(\n  Pager *pPager,               /* Pager object */\n  int isHot,\n  i64 journalSize,             /* Size of the open journal file in bytes */\n  u32 *pNRec,                  /* OUT: Value read from the nRec field */\n  u32 *pDbSize                 /* OUT: Value of original database size field */\n){\n  int rc;                      /* Return code */\n  unsigned char aMagic[8];     /* A buffer to hold the magic header */\n  i64 iHdrOff;                 /* Offset of journal header being read */\n\n  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */\n\n  /* Advance Pager.journalOff to the start of the next sector. If the\n  ** journal file is too small for there to be a header stored at this\n  ** point, return SQLITE_DONE.\n  */\n  pPager->journalOff = journalHdrOffset(pPager);\n  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){\n    return SQLITE_DONE;\n  }\n  iHdrOff = pPager->journalOff;\n\n  /* Read in the first 8 bytes of the journal header. If they do not match\n  ** the  magic string found at the start of each journal header, return\n  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,\n  ** proceed.\n  */\n  if( isHot || iHdrOff!=pPager->journalHdr ){\n    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);\n    if( rc ){\n      return rc;\n    }\n    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){\n      return SQLITE_DONE;\n    }\n  }\n\n  /* Read the first three 32-bit fields of the journal header: The nRec\n  ** field, the checksum-initializer and the database size at the start\n  ** of the transaction. Return an error code if anything goes wrong.\n  */\n  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))\n   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))\n   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))\n  ){\n    return rc;\n  }\n\n  if( pPager->journalOff==0 ){\n    u32 iPageSize;               /* Page-size field of journal header */\n    u32 iSectorSize;             /* Sector-size field of journal header */\n\n    /* Read the page-size and sector-size journal header fields. */\n    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))\n     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))\n    ){\n      return rc;\n    }\n\n    /* Versions of SQLite prior to 3.5.8 set the page-size field of the\n    ** journal header to zero. In this case, assume that the Pager.pageSize\n    ** variable is already set to the correct page size.\n    */\n    if( iPageSize==0 ){\n      iPageSize = pPager->pageSize;\n    }\n\n    /* Check that the values read from the page-size and sector-size fields\n    ** are within range. To be 'in range', both values need to be a power\n    ** of two greater than or equal to 512 or 32, and not greater than their \n    ** respective compile time maximum limits.\n    */\n    if( iPageSize<512                  || iSectorSize<32\n     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE\n     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 \n    ){\n      /* If the either the page-size or sector-size in the journal-header is \n      ** invalid, then the process that wrote the journal-header must have \n      ** crashed before the header was synced. In this case stop reading \n      ** the journal file here.\n      */\n      return SQLITE_DONE;\n    }\n\n    /* Update the page-size to match the value read from the journal. \n    ** Use a testcase() macro to make sure that malloc failure within \n    ** PagerSetPagesize() is tested.\n    */\n    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);\n    testcase( rc!=SQLITE_OK );\n\n    /* Update the assumed sector-size to match the value used by \n    ** the process that created this journal. If this journal was\n    ** created by a process other than this one, then this routine\n    ** is being called from within pager_playback(). The local value\n    ** of Pager.sectorSize is restored at the end of that routine.\n    */\n    pPager->sectorSize = iSectorSize;\n  }\n\n  pPager->journalOff += JOURNAL_HDR_SZ(pPager);\n  return rc;\n}\n\n\n/*\n** Write the supplied master journal name into the journal file for pager\n** pPager at the current location. The master journal name must be the last\n** thing written to a journal file. If the pager is in full-sync mode, the\n** journal file descriptor is advanced to the next sector boundary before\n** anything is written. The format is:\n**\n**   + 4 bytes: PAGER_MJ_PGNO.\n**   + N bytes: Master journal filename in utf-8.\n**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).\n**   + 4 bytes: Master journal name checksum.\n**   + 8 bytes: aJournalMagic[].\n**\n** The master journal page checksum is the sum of the bytes in the master\n** journal name, where each byte is interpreted as a signed 8-bit integer.\n**\n** If zMaster is a NULL pointer (occurs for a single database transaction), \n** this call is a no-op.\n*/\nstatic int writeMasterJournal(Pager *pPager, const char *zMaster){\n  int rc;                          /* Return code */\n  int nMaster;                     /* Length of string zMaster */\n  i64 iHdrOff;                     /* Offset of header in journal file */\n  i64 jrnlSize;                    /* Size of journal file on disk */\n  u32 cksum = 0;                   /* Checksum of string zMaster */\n\n  assert( pPager->setMaster==0 );\n  assert( !pagerUseWal(pPager) );\n\n  if( !zMaster \n   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY \n   || pPager->journalMode==PAGER_JOURNALMODE_OFF \n  ){\n    return SQLITE_OK;\n  }\n  pPager->setMaster = 1;\n  assert( isOpen(pPager->jfd) );\n  assert( pPager->journalHdr <= pPager->journalOff );\n\n  /* Calculate the length in bytes and the checksum of zMaster */\n  for(nMaster=0; zMaster[nMaster]; nMaster++){\n    cksum += zMaster[nMaster];\n  }\n\n  /* If in full-sync mode, advance to the next disk sector before writing\n  ** the master journal name. This is in case the previous page written to\n  ** the journal has already been synced.\n  */\n  if( pPager->fullSync ){\n    pPager->journalOff = journalHdrOffset(pPager);\n  }\n  iHdrOff = pPager->journalOff;\n\n  /* Write the master journal data to the end of the journal file. If\n  ** an error occurs, return the error code to the caller.\n  */\n  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))\n   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))\n   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))\n   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))\n   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))\n  ){\n    return rc;\n  }\n  pPager->journalOff += (nMaster+20);\n\n  /* If the pager is in peristent-journal mode, then the physical \n  ** journal-file may extend past the end of the master-journal name\n  ** and 8 bytes of magic data just written to the file. This is \n  ** dangerous because the code to rollback a hot-journal file\n  ** will not be able to find the master-journal name to determine \n  ** whether or not the journal is hot. \n  **\n  ** Easiest thing to do in this scenario is to truncate the journal \n  ** file to the required size.\n  */ \n  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))\n   && jrnlSize>pPager->journalOff\n  ){\n    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);\n  }\n  return rc;\n}\n\n/*\n** Find a page in the hash table given its page number. Return\n** a pointer to the page or NULL if the requested page is not \n** already in memory.\n*/\nstatic PgHdr *pager_lookup(Pager *pPager, Pgno pgno){\n  PgHdr *p;                         /* Return value */\n\n  /* It is not possible for a call to PcacheFetch() with createFlag==0 to\n  ** fail, since no attempt to allocate dynamic memory will be made.\n  */\n  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);\n  return p;\n}\n\n/*\n** Discard the entire contents of the in-memory page-cache.\n*/\nstatic void pager_reset(Pager *pPager){\n  sqlite3BackupRestart(pPager->pBackup);\n  sqlite3PcacheClear(pPager->pPCache);\n}\n\n/*\n** Free all structures in the Pager.aSavepoint[] array and set both\n** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal\n** if it is open and the pager is not in exclusive mode.\n*/\nstatic void releaseAllSavepoints(Pager *pPager){\n  int ii;               /* Iterator for looping through Pager.aSavepoint */\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);\n  }\n  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){\n    sqlite3OsClose(pPager->sjfd);\n  }\n  sqlite3_free(pPager->aSavepoint);\n  pPager->aSavepoint = 0;\n  pPager->nSavepoint = 0;\n  pPager->nSubRec = 0;\n}\n\n/*\n** Set the bit number pgno in the PagerSavepoint.pInSavepoint \n** bitvecs of all open savepoints. Return SQLITE_OK if successful\n** or SQLITE_NOMEM if a malloc failure occurs.\n*/\nstatic int addToSavepointBitvecs(Pager *pPager, Pgno pgno){\n  int ii;                   /* Loop counter */\n  int rc = SQLITE_OK;       /* Result code */\n\n  for(ii=0; ii<pPager->nSavepoint; ii++){\n    PagerSavepoint *p = &pPager->aSavepoint[ii];\n    if( pgno<=p->nOrig ){\n      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);\n      testcase( rc==SQLITE_NOMEM );\n      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is a no-op if the pager is in exclusive mode and not\n** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN\n** state.\n**\n** If the pager is not in exclusive-access mode, the database file is\n** completely unlocked. If the file is unlocked and the file-system does\n** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is\n** closed (if it is open).\n**\n** If the pager is in ERROR state when this function is called, the \n** contents of the pager cache are discarded before switching back to \n** the OPEN state. Regardless of whether the pager is in exclusive-mode\n** or not, any journal file left in the file-system will be treated\n** as a hot-journal and rolled back the next time a read-transaction\n** is opened (by this or by any other connection).\n*/\nstatic void pager_unlock(Pager *pPager){\n\n  assert( pPager->eState==PAGER_READER \n       || pPager->eState==PAGER_OPEN \n       || pPager->eState==PAGER_ERROR \n  );\n\n  sqlite3BitvecDestroy(pPager->pInJournal);\n  pPager->pInJournal = 0;\n  releaseAllSavepoints(pPager);\n\n  if( pagerUseWal(pPager) ){\n    assert( !isOpen(pPager->jfd) );\n    sqlite3WalEndReadTransaction(pPager->pWal);\n    pPager->eState = PAGER_OPEN;\n  }else if( !pPager->exclusiveMode ){\n    int rc;                       /* Error code returned by pagerUnlockDb() */\n    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;\n\n    /* If the operating system support deletion of open files, then\n    ** close the journal file when dropping the database lock.  Otherwise\n    ** another connection with journal_mode=delete might delete the file\n    ** out from under us.\n    */\n    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );\n    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );\n    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );\n    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)\n     || 1!=(pPager->journalMode & 5)\n    ){\n      sqlite3OsClose(pPager->jfd);\n    }\n\n    /* If the pager is in the ERROR state and the call to unlock the database\n    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment\n    ** above the #define for UNKNOWN_LOCK for an explanation of why this\n    ** is necessary.\n    */\n    rc = pagerUnlockDb(pPager, NO_LOCK);\n    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){\n      pPager->eLock = UNKNOWN_LOCK;\n    }\n\n    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here\n    ** without clearing the error code. This is intentional - the error\n    ** code is cleared and the cache reset in the block below.\n    */\n    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );\n    pPager->changeCountDone = 0;\n    pPager->eState = PAGER_OPEN;\n  }\n\n  /* If Pager.errCode is set, the contents of the pager cache cannot be\n  ** trusted. Now that there are no outstanding references to the pager,\n  ** it can safely move back to PAGER_OPEN state. This happens in both\n  ** normal and exclusive-locking mode.\n  */\n  if( pPager->errCode ){\n    assert( !MEMDB );\n    pager_reset(pPager);\n    pPager->changeCountDone = pPager->tempFile;\n    pPager->eState = PAGER_OPEN;\n    pPager->errCode = SQLITE_OK;\n  }\n\n  pPager->journalOff = 0;\n  pPager->journalHdr = 0;\n  pPager->setMaster = 0;\n}\n\n/*\n** This function is called whenever an IOERR or FULL error that requires\n** the pager to transition into the ERROR state may ahve occurred.\n** The first argument is a pointer to the pager structure, the second \n** the error-code about to be returned by a pager API function. The \n** value returned is a copy of the second argument to this function. \n**\n** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the\n** IOERR sub-codes, the pager enters the ERROR state and the error code\n** is stored in Pager.errCode. While the pager remains in the ERROR state,\n** all major API calls on the Pager will immediately return Pager.errCode.\n**\n** The ERROR state indicates that the contents of the pager-cache \n** cannot be trusted. This state can be cleared by completely discarding \n** the contents of the pager-cache. If a transaction was active when\n** the persistent error occurred, then the rollback journal may need\n** to be replayed to restore the contents of the database file (as if\n** it were a hot-journal).\n*/\nstatic int pager_error(Pager *pPager, int rc){\n  int rc2 = rc & 0xff;\n  assert( rc==SQLITE_OK || !MEMDB );\n  assert(\n       pPager->errCode==SQLITE_FULL ||\n       pPager->errCode==SQLITE_OK ||\n       (pPager->errCode & 0xff)==SQLITE_IOERR\n  );\n  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){\n    pPager->errCode = rc;\n    pPager->eState = PAGER_ERROR;\n  }\n  return rc;\n}\n\n/*\n** This routine ends a transaction. A transaction is usually ended by \n** either a COMMIT or a ROLLBACK operation. This routine may be called \n** after rollback of a hot-journal, or if an error occurs while opening\n** the journal file or writing the very first journal-header of a\n** database transaction.\n** \n** This routine is never called in PAGER_ERROR state. If it is called\n** in PAGER_NONE or PAGER_SHARED state and the lock held is less\n** exclusive than a RESERVED lock, it is a no-op.\n**\n** Otherwise, any active savepoints are released.\n**\n** If the journal file is open, then it is \"finalized\". Once a journal \n** file has been finalized it is not possible to use it to roll back a \n** transaction. Nor will it be considered to be a hot-journal by this\n** or any other database connection. Exactly how a journal is finalized\n** depends on whether or not the pager is running in exclusive mode and\n** the current journal-mode (Pager.journalMode value), as follows:\n**\n**   journalMode==MEMORY\n**     Journal file descriptor is simply closed. This destroys an \n**     in-memory journal.\n**\n**   journalMode==TRUNCATE\n**     Journal file is truncated to zero bytes in size.\n**\n**   journalMode==PERSIST\n**     The first 28 bytes of the journal file are zeroed. This invalidates\n**     the first journal header in the file, and hence the entire journal\n**     file. An invalid journal file cannot be rolled back.\n**\n**   journalMode==DELETE\n**     The journal file is closed and deleted using sqlite3OsDelete().\n**\n**     If the pager is running in exclusive mode, this method of finalizing\n**     the journal file is never used. Instead, if the journalMode is\n**     DELETE and the pager is in exclusive mode, the method described under\n**     journalMode==PERSIST is used instead.\n**\n** After the journal is finalized, the pager moves to PAGER_READER state.\n** If running in non-exclusive rollback mode, the lock on the file is \n** downgraded to a SHARED_LOCK.\n**\n** SQLITE_OK is returned if no error occurs. If an error occurs during\n** any of the IO operations to finalize the journal file or unlock the\n** database then the IO error code is returned to the user. If the \n** operation to finalize the journal file fails, then the code still\n** tries to unlock the database file if not in exclusive mode. If the\n** unlock operation fails as well, then the first error code related\n** to the first error encountered (the journal finalization one) is\n** returned.\n*/\nstatic int pager_end_transaction(Pager *pPager, int hasMaster){\n  int rc = SQLITE_OK;      /* Error code from journal finalization operation */\n  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */\n\n  /* Do nothing if the pager does not have an open write transaction\n  ** or at least a RESERVED lock. This function may be called when there\n  ** is no write-transaction active but a RESERVED or greater lock is\n  ** held under two circumstances:\n  **\n  **   1. After a successful hot-journal rollback, it is called with\n  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.\n  **\n  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE \n  **      lock switches back to locking_mode=normal and then executes a\n  **      read-transaction, this function is called with eState==PAGER_READER \n  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.\n  */\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState!=PAGER_ERROR );\n  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){\n    return SQLITE_OK;\n  }\n\n  releaseAllSavepoints(pPager);\n  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );\n  if( isOpen(pPager->jfd) ){\n    assert( !pagerUseWal(pPager) );\n\n    /* Finalize the journal file. */\n    if( sqlite3IsMemJournal(pPager->jfd) ){\n      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );\n      sqlite3OsClose(pPager->jfd);\n    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){\n      if( pPager->journalOff==0 ){\n        rc = SQLITE_OK;\n      }else{\n        rc = sqlite3OsTruncate(pPager->jfd, 0);\n      }\n      pPager->journalOff = 0;\n    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST\n      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)\n    ){\n      rc = zeroJournalHdr(pPager, hasMaster);\n      pPager->journalOff = 0;\n    }else{\n      /* This branch may be executed with Pager.journalMode==MEMORY if\n      ** a hot-journal was just rolled back. In this case the journal\n      ** file should be closed and deleted. If this connection writes to\n      ** the database file, it will do so using an in-memory journal. \n      */\n      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE \n           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY \n           || pPager->journalMode==PAGER_JOURNALMODE_WAL \n      );\n      sqlite3OsClose(pPager->jfd);\n      if( !pPager->tempFile ){\n        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);\n      }\n    }\n  }\n\n#ifdef SQLITE_CHECK_PAGES\n  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);\n  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){\n    PgHdr *p = pager_lookup(pPager, 1);\n    if( p ){\n      p->pageHash = 0;\n      sqlite3PagerUnref(p);\n    }\n  }\n#endif\n\n  sqlite3BitvecDestroy(pPager->pInJournal);\n  pPager->pInJournal = 0;\n  pPager->nRec = 0;\n  sqlite3PcacheCleanAll(pPager->pPCache);\n  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);\n\n  if( pagerUseWal(pPager) ){\n    /* Drop the WAL write-lock, if any. Also, if the connection was in \n    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE \n    ** lock held on the database file.\n    */\n    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);\n    assert( rc2==SQLITE_OK );\n  }\n  if( !pPager->exclusiveMode \n   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))\n  ){\n    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);\n    pPager->changeCountDone = 0;\n  }\n  pPager->eState = PAGER_READER;\n  pPager->setMaster = 0;\n\n  return (rc==SQLITE_OK?rc2:rc);\n}\n\n/*\n** Execute a rollback if a transaction is active and unlock the \n** database file. \n**\n** If the pager has already entered the ERROR state, do not attempt \n** the rollback at this time. Instead, pager_unlock() is called. The\n** call to pager_unlock() will discard all in-memory pages, unlock\n** the database file and move the pager back to OPEN state. If this \n** means that there is a hot-journal left in the file-system, the next \n** connection to obtain a shared lock on the pager (which may be this one) \n** will roll it back.\n**\n** If the pager has not already entered the ERROR state, but an IO or\n** malloc error occurs during a rollback, then this will itself cause \n** the pager to enter the ERROR state. Which will be cleared by the\n** call to pager_unlock(), as described above.\n*/\nstatic void pagerUnlockAndRollback(Pager *pPager){\n  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){\n    assert( assert_pager_state(pPager) );\n    if( pPager->eState>=PAGER_WRITER_LOCKED ){\n      sqlite3BeginBenignMalloc();\n      sqlite3PagerRollback(pPager);\n      sqlite3EndBenignMalloc();\n    }else if( !pPager->exclusiveMode ){\n      assert( pPager->eState==PAGER_READER );\n      pager_end_transaction(pPager, 0);\n    }\n  }\n  pager_unlock(pPager);\n}\n\n/*\n** Parameter aData must point to a buffer of pPager->pageSize bytes\n** of data. Compute and return a checksum based ont the contents of the \n** page of data and the current value of pPager->cksumInit.\n**\n** This is not a real checksum. It is really just the sum of the \n** random initial value (pPager->cksumInit) and every 200th byte\n** of the page data, starting with byte offset (pPager->pageSize%200).\n** Each byte is interpreted as an 8-bit unsigned integer.\n**\n** Changing the formula used to compute this checksum results in an\n** incompatible journal file format.\n**\n** If journal corruption occurs due to a power failure, the most likely \n** scenario is that one end or the other of the record will be changed. \n** It is much less likely that the two ends of the journal record will be\n** correct and the middle be corrupt.  Thus, this \"checksum\" scheme,\n** though fast and simple, catches the mostly likely kind of corruption.\n*/\nstatic u32 pager_cksum(Pager *pPager, const u8 *aData){\n  u32 cksum = pPager->cksumInit;         /* Checksum value to return */\n  int i = pPager->pageSize-200;          /* Loop counter */\n  while( i>0 ){\n    cksum += aData[i];\n    i -= 200;\n  }\n  return cksum;\n}\n\n/*\n** Report the current page size and number of reserved bytes back\n** to the codec.\n*/\n#ifdef SQLITE_HAS_CODEC\nstatic void pagerReportSize(Pager *pPager){\n  if( pPager->xCodecSizeChng ){\n    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,\n                           (int)pPager->nReserve);\n  }\n}\n#else\n# define pagerReportSize(X)     /* No-op if we do not support a codec */\n#endif\n\n/*\n** Read a single page from either the journal file (if isMainJrnl==1) or\n** from the sub-journal (if isMainJrnl==0) and playback that page.\n** The page begins at offset *pOffset into the file. The *pOffset\n** value is increased to the start of the next page in the journal.\n**\n** The main rollback journal uses checksums - the statement journal does \n** not.\n**\n** If the page number of the page record read from the (sub-)journal file\n** is greater than the current value of Pager.dbSize, then playback is\n** skipped and SQLITE_OK is returned.\n**\n** If pDone is not NULL, then it is a record of pages that have already\n** been played back.  If the page at *pOffset has already been played back\n** (if the corresponding pDone bit is set) then skip the playback.\n** Make sure the pDone bit corresponding to the *pOffset page is set\n** prior to returning.\n**\n** If the page record is successfully read from the (sub-)journal file\n** and played back, then SQLITE_OK is returned. If an IO error occurs\n** while reading the record from the (sub-)journal file or while writing\n** to the database file, then the IO error code is returned. If data\n** is successfully read from the (sub-)journal file but appears to be\n** corrupted, SQLITE_DONE is returned. Data is considered corrupted in\n** two circumstances:\n** \n**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or\n**   * If the record is being rolled back from the main journal file\n**     and the checksum field does not match the record content.\n**\n** Neither of these two scenarios are possible during a savepoint rollback.\n**\n** If this is a savepoint rollback, then memory may have to be dynamically\n** allocated by this function. If this is the case and an allocation fails,\n** SQLITE_NOMEM is returned.\n*/\nstatic int pager_playback_one_page(\n  Pager *pPager,                /* The pager being played back */\n  i64 *pOffset,                 /* Offset of record to playback */\n  Bitvec *pDone,                /* Bitvec of pages already played back */\n  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */\n  int isSavepnt                 /* True for a savepoint rollback */\n){\n  int rc;\n  PgHdr *pPg;                   /* An existing page in the cache */\n  Pgno pgno;                    /* The page number of a page in journal */\n  u32 cksum;                    /* Checksum used for sanity checking */\n  char *aData;                  /* Temporary storage for the page */\n  sqlite3_file *jfd;            /* The file descriptor for the journal file */\n  int isSynced;                 /* True if journal page is synced */\n\n  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */\n  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */\n  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */\n  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */\n\n  aData = pPager->pTmpSpace;\n  assert( aData );         /* Temp storage must have already been allocated */\n  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );\n\n  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction \n  ** or savepoint rollback done at the request of the caller) or this is\n  ** a hot-journal rollback. If it is a hot-journal rollback, the pager\n  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback\n  ** only reads from the main journal, not the sub-journal.\n  */\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD\n       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)\n  );\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );\n\n  /* Read the page number and page data from the journal or sub-journal\n  ** file. Return an error code to the caller if an IO error occurs.\n  */\n  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;\n  rc = read32bits(jfd, *pOffset, &pgno);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);\n  if( rc!=SQLITE_OK ) return rc;\n  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;\n\n  /* Sanity checking on the page.  This is more important that I originally\n  ** thought.  If a power failure occurs while the journal is being written,\n  ** it could cause invalid data to be written into the journal.  We need to\n  ** detect this invalid data (with high probability) and ignore it.\n  */\n  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){\n    assert( !isSavepnt );\n    return SQLITE_DONE;\n  }\n  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){\n    return SQLITE_OK;\n  }\n  if( isMainJrnl ){\n    rc = read32bits(jfd, (*pOffset)-4, &cksum);\n    if( rc ) return rc;\n    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){\n      return SQLITE_DONE;\n    }\n  }\n\n  /* If this page has already been played by before during the current\n  ** rollback, then don't bother to play it back again.\n  */\n  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* When playing back page 1, restore the nReserve setting\n  */\n  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){\n    pPager->nReserve = ((u8*)aData)[20];\n    pagerReportSize(pPager);\n  }\n\n  /* If the pager is in CACHEMOD state, then there must be a copy of this\n  ** page in the pager cache. In this case just update the pager cache,\n  ** not the database file. The page is left marked dirty in this case.\n  **\n  ** An exception to the above rule: If the database is in no-sync mode\n  ** and a page is moved during an incremental vacuum then the page may\n  ** not be in the pager cache. Later: if a malloc() or IO error occurs\n  ** during a Movepage() call, then the page may not be in the cache\n  ** either. So the condition described in the above paragraph is not\n  ** assert()able.\n  **\n  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the\n  ** pager cache if it exists and the main file. The page is then marked \n  ** not dirty. Since this code is only executed in PAGER_OPEN state for\n  ** a hot-journal rollback, it is guaranteed that the page-cache is empty\n  ** if the pager is in OPEN state.\n  **\n  ** Ticket #1171:  The statement journal might contain page content that is\n  ** different from the page content at the start of the transaction.\n  ** This occurs when a page is changed prior to the start of a statement\n  ** then changed again within the statement.  When rolling back such a\n  ** statement we must not write to the original database unless we know\n  ** for certain that original page contents are synced into the main rollback\n  ** journal.  Otherwise, a power loss might leave modified data in the\n  ** database file without an entry in the rollback journal that can\n  ** restore the database to its original form.  Two conditions must be\n  ** met before writing to the database files. (1) the database must be\n  ** locked.  (2) we know that the original page content is fully synced\n  ** in the main journal either because the page is not in cache or else\n  ** the page is marked as needSync==0.\n  **\n  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it\n  ** is possible to fail a statement on a database that does not yet exist.\n  ** Do not attempt to write if database file has never been opened.\n  */\n  if( pagerUseWal(pPager) ){\n    pPg = 0;\n  }else{\n    pPg = pager_lookup(pPager, pgno);\n  }\n  assert( pPg || !MEMDB );\n  assert( pPager->eState!=PAGER_OPEN || pPg==0 );\n  PAGERTRACE((\"PLAYBACK %d page %d hash(%08x) %s\\n\",\n           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),\n           (isMainJrnl?\"main-journal\":\"sub-journal\")\n  ));\n  if( isMainJrnl ){\n    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);\n  }else{\n    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));\n  }\n  if( isOpen(pPager->fd)\n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)\n   && isSynced\n  ){\n    i64 ofst = (pgno-1)*(i64)pPager->pageSize;\n    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );\n    assert( !pagerUseWal(pPager) );\n    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);\n    if( pgno>pPager->dbFileSize ){\n      pPager->dbFileSize = pgno;\n    }\n    if( pPager->pBackup ){\n      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);\n      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);\n      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);\n    }\n  }else if( !isMainJrnl && pPg==0 ){\n    /* If this is a rollback of a savepoint and data was not written to\n    ** the database and the page is not in-memory, there is a potential\n    ** problem. When the page is next fetched by the b-tree layer, it \n    ** will be read from the database file, which may or may not be \n    ** current. \n    **\n    ** There are a couple of different ways this can happen. All are quite\n    ** obscure. When running in synchronous mode, this can only happen \n    ** if the page is on the free-list at the start of the transaction, then\n    ** populated, then moved using sqlite3PagerMovepage().\n    **\n    ** The solution is to add an in-memory page to the cache containing\n    ** the data just read from the sub-journal. Mark the page as dirty \n    ** and if the pager requires a journal-sync, then mark the page as \n    ** requiring a journal-sync before it is written.\n    */\n    assert( isSavepnt );\n    assert( pPager->doNotSpill==0 );\n    pPager->doNotSpill++;\n    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);\n    assert( pPager->doNotSpill==1 );\n    pPager->doNotSpill--;\n    if( rc!=SQLITE_OK ) return rc;\n    pPg->flags &= ~PGHDR_NEED_READ;\n    sqlite3PcacheMakeDirty(pPg);\n  }\n  if( pPg ){\n    /* No page should ever be explicitly rolled back that is in use, except\n    ** for page 1 which is held in use in order to keep the lock on the\n    ** database active. However such a page may be rolled back as a result\n    ** of an internal error resulting in an automatic call to\n    ** sqlite3PagerRollback().\n    */\n    void *pData;\n    pData = pPg->pData;\n    memcpy(pData, (u8*)aData, pPager->pageSize);\n    pPager->xReiniter(pPg);\n    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){\n      /* If the contents of this page were just restored from the main \n      ** journal file, then its content must be as they were when the \n      ** transaction was first opened. In this case we can mark the page\n      ** as clean, since there will be no need to write it out to the\n      ** database.\n      **\n      ** There is one exception to this rule. If the page is being rolled\n      ** back as part of a savepoint (or statement) rollback from an \n      ** unsynced portion of the main journal file, then it is not safe\n      ** to mark the page as clean. This is because marking the page as\n      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is\n      ** already in the journal file (recorded in Pager.pInJournal) and\n      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to\n      ** again within this transaction, it will be marked as dirty but\n      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially\n      ** be written out into the database file before its journal file\n      ** segment is synced. If a crash occurs during or following this,\n      ** database corruption may ensue.\n      */\n      assert( !pagerUseWal(pPager) );\n      sqlite3PcacheMakeClean(pPg);\n    }\n    pager_set_pagehash(pPg);\n\n    /* If this was page 1, then restore the value of Pager.dbFileVers.\n    ** Do this before any decoding. */\n    if( pgno==1 ){\n      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));\n    }\n\n    /* Decode the page just read from disk */\n    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);\n    sqlite3PcacheRelease(pPg);\n  }\n  return rc;\n}\n\n/*\n** Parameter zMaster is the name of a master journal file. A single journal\n** file that referred to the master journal file has just been rolled back.\n** This routine checks if it is possible to delete the master journal file,\n** and does so if it is.\n**\n** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not \n** available for use within this function.\n**\n** When a master journal file is created, it is populated with the names \n** of all of its child journals, one after another, formatted as utf-8 \n** encoded text. The end of each child journal file is marked with a \n** nul-terminator byte (0x00). i.e. the entire contents of a master journal\n** file for a transaction involving two databases might be:\n**\n**   \"/home/bill/a.db-journal\\x00/home/bill/b.db-journal\\x00\"\n**\n** A master journal file may only be deleted once all of its child \n** journals have been rolled back.\n**\n** This function reads the contents of the master-journal file into \n** memory and loops through each of the child journal names. For\n** each child journal, it checks if:\n**\n**   * if the child journal exists, and if so\n**   * if the child journal contains a reference to master journal \n**     file zMaster\n**\n** If a child journal can be found that matches both of the criteria\n** above, this function returns without doing anything. Otherwise, if\n** no such child journal can be found, file zMaster is deleted from\n** the file-system using sqlite3OsDelete().\n**\n** If an IO error within this function, an error code is returned. This\n** function allocates memory by calling sqlite3Malloc(). If an allocation\n** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors \n** occur, SQLITE_OK is returned.\n**\n** TODO: This function allocates a single block of memory to load\n** the entire contents of the master journal file. This could be\n** a couple of kilobytes or so - potentially larger than the page \n** size.\n*/\nstatic int pager_delmaster(Pager *pPager, const char *zMaster){\n  sqlite3_vfs *pVfs = pPager->pVfs;\n  int rc;                   /* Return code */\n  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */\n  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */\n  char *zMasterJournal = 0; /* Contents of master journal file */\n  i64 nMasterJournal;       /* Size of master journal file */\n  char *zJournal;           /* Pointer to one journal within MJ file */\n  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */\n  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */\n\n  /* Allocate space for both the pJournal and pMaster file descriptors.\n  ** If successful, open the master journal file for reading.\n  */\n  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);\n  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);\n  if( !pMaster ){\n    rc = SQLITE_NOMEM;\n  }else{\n    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);\n    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);\n  }\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n\n  /* Load the entire master journal file into space obtained from\n  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain\n  ** sufficient space (in zMasterPtr) to hold the names of master\n  ** journal files extracted from regular rollback-journals.\n  */\n  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n  nMasterPtr = pVfs->mxPathname+1;\n  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);\n  if( !zMasterJournal ){\n    rc = SQLITE_NOMEM;\n    goto delmaster_out;\n  }\n  zMasterPtr = &zMasterJournal[nMasterJournal+1];\n  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);\n  if( rc!=SQLITE_OK ) goto delmaster_out;\n  zMasterJournal[nMasterJournal] = 0;\n\n  zJournal = zMasterJournal;\n  while( (zJournal-zMasterJournal)<nMasterJournal ){\n    int exists;\n    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);\n    if( rc!=SQLITE_OK ){\n      goto delmaster_out;\n    }\n    if( exists ){\n      /* One of the journals pointed to by the master journal exists.\n      ** Open it and check if it points at the master journal. If\n      ** so, return without deleting the master journal file.\n      */\n      int c;\n      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);\n      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);\n      if( rc!=SQLITE_OK ){\n        goto delmaster_out;\n      }\n\n      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);\n      sqlite3OsClose(pJournal);\n      if( rc!=SQLITE_OK ){\n        goto delmaster_out;\n      }\n\n      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;\n      if( c ){\n        /* We have a match. Do not delete the master journal file. */\n        goto delmaster_out;\n      }\n    }\n    zJournal += (sqlite3Strlen30(zJournal)+1);\n  }\n \n  sqlite3OsClose(pMaster);\n  rc = sqlite3OsDelete(pVfs, zMaster, 0);\n\ndelmaster_out:\n  sqlite3_free(zMasterJournal);\n  if( pMaster ){\n    sqlite3OsClose(pMaster);\n    assert( !isOpen(pJournal) );\n    sqlite3_free(pMaster);\n  }\n  return rc;\n}\n\n\n/*\n** This function is used to change the actual size of the database \n** file in the file-system. This only happens when committing a transaction,\n** or rolling back a transaction (including rolling back a hot-journal).\n**\n** If the main database file is not open, or the pager is not in either\n** DBMOD or OPEN state, this function is a no-op. Otherwise, the size \n** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). \n** If the file on disk is currently larger than nPage pages, then use the VFS\n** xTruncate() method to truncate it.\n**\n** Or, it might might be the case that the file on disk is smaller than \n** nPage pages. Some operating system implementations can get confused if \n** you try to truncate a file to some size that is larger than it \n** currently is, so detect this case and write a single zero byte to \n** the end of the new file instead.\n**\n** If successful, return SQLITE_OK. If an IO error occurs while modifying\n** the database file, return the error code to the caller.\n*/\nstatic int pager_truncate(Pager *pPager, Pgno nPage){\n  int rc = SQLITE_OK;\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( pPager->eState!=PAGER_READER );\n  \n  if( isOpen(pPager->fd) \n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) \n  ){\n    i64 currentSize, newSize;\n    int szPage = pPager->pageSize;\n    assert( pPager->eLock==EXCLUSIVE_LOCK );\n    /* TODO: Is it safe to use Pager.dbFileSize here? */\n    rc = sqlite3OsFileSize(pPager->fd, &currentSize);\n    newSize = szPage*(i64)nPage;\n    if( rc==SQLITE_OK && currentSize!=newSize ){\n      if( currentSize>newSize ){\n        rc = sqlite3OsTruncate(pPager->fd, newSize);\n      }else if( (currentSize+szPage)<=newSize ){\n        char *pTmp = pPager->pTmpSpace;\n        memset(pTmp, 0, szPage);\n        testcase( (newSize-szPage) == currentSize );\n        testcase( (newSize-szPage) >  currentSize );\n        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);\n      }\n      if( rc==SQLITE_OK ){\n        pPager->dbFileSize = nPage;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Set the value of the Pager.sectorSize variable for the given\n** pager based on the value returned by the xSectorSize method\n** of the open database file. The sector size will be used used \n** to determine the size and alignment of journal header and \n** master journal pointers within created journal files.\n**\n** For temporary files the effective sector size is always 512 bytes.\n**\n** Otherwise, for non-temporary files, the effective sector size is\n** the value returned by the xSectorSize() method rounded up to 32 if\n** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it\n** is greater than MAX_SECTOR_SIZE.\n**\n** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set\n** the effective sector size to its minimum value (512).  The purpose of\n** pPager->sectorSize is to define the \"blast radius\" of bytes that\n** might change if a crash occurs while writing to a single byte in\n** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero\n** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector\n** size.  For backwards compatibility of the rollback journal file format,\n** we cannot reduce the effective sector size below 512.\n*/\nstatic void setSectorSize(Pager *pPager){\n  assert( isOpen(pPager->fd) || pPager->tempFile );\n\n  if( pPager->tempFile\n   || (sqlite3OsDeviceCharacteristics(pPager->fd) & \n              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0\n  ){\n    /* Sector size doesn't matter for temporary files. Also, the file\n    ** may not have been opened yet, in which case the OsSectorSize()\n    ** call will segfault. */\n    pPager->sectorSize = 512;\n  }else{\n    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);\n    if( pPager->sectorSize<32 ){\n      pPager->sectorSize = 512;\n    }\n    if( pPager->sectorSize>MAX_SECTOR_SIZE ){\n      assert( MAX_SECTOR_SIZE>=512 );\n      pPager->sectorSize = MAX_SECTOR_SIZE;\n    }\n  }\n}\n\n/*\n** Playback the journal and thus restore the database file to\n** the state it was in before we started making changes.  \n**\n** The journal file format is as follows: \n**\n**  (1)  8 byte prefix.  A copy of aJournalMagic[].\n**  (2)  4 byte big-endian integer which is the number of valid page records\n**       in the journal.  If this value is 0xffffffff, then compute the\n**       number of page records from the journal size.\n**  (3)  4 byte big-endian integer which is the initial value for the \n**       sanity checksum.\n**  (4)  4 byte integer which is the number of pages to truncate the\n**       database to during a rollback.\n**  (5)  4 byte big-endian integer which is the sector size.  The header\n**       is this many bytes in size.\n**  (6)  4 byte big-endian integer which is the page size.\n**  (7)  zero padding out to the next sector size.\n**  (8)  Zero or more pages instances, each as follows:\n**        +  4 byte page number.\n**        +  pPager->pageSize bytes of data.\n**        +  4 byte checksum\n**\n** When we speak of the journal header, we mean the first 7 items above.\n** Each entry in the journal is an instance of the 8th item.\n**\n** Call the value from the second bullet \"nRec\".  nRec is the number of\n** valid page entries in the journal.  In most cases, you can compute the\n** value of nRec from the size of the journal file.  But if a power\n** failure occurred while the journal was being written, it could be the\n** case that the size of the journal file had already been increased but\n** the extra entries had not yet made it safely to disk.  In such a case,\n** the value of nRec computed from the file size would be too large.  For\n** that reason, we always use the nRec value in the header.\n**\n** If the nRec value is 0xffffffff it means that nRec should be computed\n** from the file size.  This value is used when the user selects the\n** no-sync option for the journal.  A power failure could lead to corruption\n** in this case.  But for things like temporary table (which will be\n** deleted when the power is restored) we don't care.  \n**\n** If the file opened as the journal file is not a well-formed\n** journal file then all pages up to the first corrupted page are rolled\n** back (or no pages if the journal header is corrupted). The journal file\n** is then deleted and SQLITE_OK returned, just as if no corruption had\n** been encountered.\n**\n** If an I/O or malloc() error occurs, the journal-file is not deleted\n** and an error code is returned.\n**\n** The isHot parameter indicates that we are trying to rollback a journal\n** that might be a hot journal.  Or, it could be that the journal is \n** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.\n** If the journal really is hot, reset the pager cache prior rolling\n** back any content.  If the journal is merely persistent, no reset is\n** needed.\n*/\nstatic int pager_playback(Pager *pPager, int isHot){\n  sqlite3_vfs *pVfs = pPager->pVfs;\n  i64 szJ;                 /* Size of the journal file in bytes */\n  u32 nRec;                /* Number of Records in the journal */\n  u32 u;                   /* Unsigned loop counter */\n  Pgno mxPg = 0;           /* Size of the original file in pages */\n  int rc;                  /* Result code of a subroutine */\n  int res = 1;             /* Value returned by sqlite3OsAccess() */\n  char *zMaster = 0;       /* Name of master journal file if any */\n  int needPagerReset;      /* True to reset page prior to first page rollback */\n\n  /* Figure out how many records are in the journal.  Abort early if\n  ** the journal is empty.\n  */\n  assert( isOpen(pPager->jfd) );\n  rc = sqlite3OsFileSize(pPager->jfd, &szJ);\n  if( rc!=SQLITE_OK ){\n    goto end_playback;\n  }\n\n  /* Read the master journal name from the journal, if it is present.\n  ** If a master journal file name is specified, but the file is not\n  ** present on disk, then the journal is not hot and does not need to be\n  ** played back.\n  **\n  ** TODO: Technically the following is an error because it assumes that\n  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that\n  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,\n  **  mxPathname is 512, which is the same as the minimum allowable value\n  ** for pageSize.\n  */\n  zMaster = pPager->pTmpSpace;\n  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);\n  if( rc==SQLITE_OK && zMaster[0] ){\n    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);\n  }\n  zMaster = 0;\n  if( rc!=SQLITE_OK || !res ){\n    goto end_playback;\n  }\n  pPager->journalOff = 0;\n  needPagerReset = isHot;\n\n  /* This loop terminates either when a readJournalHdr() or \n  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error \n  ** occurs. \n  */\n  while( 1 ){\n    /* Read the next journal header from the journal file.  If there are\n    ** not enough bytes left in the journal file for a complete header, or\n    ** it is corrupted, then a process must have failed while writing it.\n    ** This indicates nothing more needs to be rolled back.\n    */\n    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);\n    if( rc!=SQLITE_OK ){ \n      if( rc==SQLITE_DONE ){\n        rc = SQLITE_OK;\n      }\n      goto end_playback;\n    }\n\n    /* If nRec is 0xffffffff, then this journal was created by a process\n    ** working in no-sync mode. This means that the rest of the journal\n    ** file consists of pages, there are no more journal headers. Compute\n    ** the value of nRec based on this assumption.\n    */\n    if( nRec==0xffffffff ){\n      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );\n      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));\n    }\n\n    /* If nRec is 0 and this rollback is of a transaction created by this\n    ** process and if this is the final header in the journal, then it means\n    ** that this part of the journal was being filled but has not yet been\n    ** synced to disk.  Compute the number of pages based on the remaining\n    ** size of the file.\n    **\n    ** The third term of the test was added to fix ticket #2565.\n    ** When rolling back a hot journal, nRec==0 always means that the next\n    ** chunk of the journal contains zero pages to be rolled back.  But\n    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in\n    ** the journal, it means that the journal might contain additional\n    ** pages that need to be rolled back and that the number of pages \n    ** should be computed based on the journal file size.\n    */\n    if( nRec==0 && !isHot &&\n        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){\n      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));\n    }\n\n    /* If this is the first header read from the journal, truncate the\n    ** database file back to its original size.\n    */\n    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){\n      rc = pager_truncate(pPager, mxPg);\n      if( rc!=SQLITE_OK ){\n        goto end_playback;\n      }\n      pPager->dbSize = mxPg;\n    }\n\n    /* Copy original pages out of the journal and back into the \n    ** database file and/or page cache.\n    */\n    for(u=0; u<nRec; u++){\n      if( needPagerReset ){\n        pager_reset(pPager);\n        needPagerReset = 0;\n      }\n      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);\n      if( rc!=SQLITE_OK ){\n        if( rc==SQLITE_DONE ){\n          pPager->journalOff = szJ;\n          break;\n        }else if( rc==SQLITE_IOERR_SHORT_READ ){\n          /* If the journal has been truncated, simply stop reading and\n          ** processing the journal. This might happen if the journal was\n          ** not completely written and synced prior to a crash.  In that\n          ** case, the database should have never been written in the\n          ** first place so it is OK to simply abandon the rollback. */\n          rc = SQLITE_OK;\n          goto end_playback;\n        }else{\n          /* If we are unable to rollback, quit and return the error\n          ** code.  This will cause the pager to enter the error state\n          ** so that no further harm will be done.  Perhaps the next\n          ** process to come along will be able to rollback the database.\n          */\n          goto end_playback;\n        }\n      }\n    }\n  }\n  /*NOTREACHED*/\n  assert( 0 );\n\nend_playback:\n  /* Following a rollback, the database file should be back in its original\n  ** state prior to the start of the transaction, so invoke the\n  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the\n  ** assertion that the transaction counter was modified.\n  */\n#ifdef SQLITE_DEBUG\n  if( pPager->fd->pMethods ){\n    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);\n  }\n#endif\n\n  /* If this playback is happening automatically as a result of an IO or \n  ** malloc error that occurred after the change-counter was updated but \n  ** before the transaction was committed, then the change-counter \n  ** modification may just have been reverted. If this happens in exclusive \n  ** mode, then subsequent transactions performed by the connection will not\n  ** update the change-counter at all. This may lead to cache inconsistency\n  ** problems for other processes at some point in the future. So, just\n  ** in case this has happened, clear the changeCountDone flag now.\n  */\n  pPager->changeCountDone = pPager->tempFile;\n\n  if( rc==SQLITE_OK ){\n    zMaster = pPager->pTmpSpace;\n    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);\n    testcase( rc!=SQLITE_OK );\n  }\n  if( rc==SQLITE_OK\n   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)\n  ){\n    rc = sqlite3PagerSync(pPager);\n  }\n  if( rc==SQLITE_OK ){\n    rc = pager_end_transaction(pPager, zMaster[0]!='\\0');\n    testcase( rc!=SQLITE_OK );\n  }\n  if( rc==SQLITE_OK && zMaster[0] && res ){\n    /* If there was a master journal and this routine will return success,\n    ** see if it is possible to delete the master journal.\n    */\n    rc = pager_delmaster(pPager, zMaster);\n    testcase( rc!=SQLITE_OK );\n  }\n\n  /* The Pager.sectorSize variable may have been updated while rolling\n  ** back a journal created by a process with a different sector size\n  ** value. Reset it to the correct value for this process.\n  */\n  setSectorSize(pPager);\n  return rc;\n}\n\n\n/*\n** Read the content for page pPg out of the database file and into \n** pPg->pData. A shared lock or greater must be held on the database\n** file before this function is called.\n**\n** If page 1 is read, then the value of Pager.dbFileVers[] is set to\n** the value read from the database file.\n**\n** If an IO error occurs, then the IO error is returned to the caller.\n** Otherwise, SQLITE_OK is returned.\n*/\nstatic int readDbPage(PgHdr *pPg){\n  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */\n  Pgno pgno = pPg->pgno;       /* Page number to read */\n  int rc = SQLITE_OK;          /* Return code */\n  int isInWal = 0;             /* True if page is in log file */\n  int pgsz = pPager->pageSize; /* Number of bytes to read */\n\n  assert( pPager->eState>=PAGER_READER && !MEMDB );\n  assert( isOpen(pPager->fd) );\n\n  if( NEVER(!isOpen(pPager->fd)) ){\n    assert( pPager->tempFile );\n    memset(pPg->pData, 0, pPager->pageSize);\n    return SQLITE_OK;\n  }\n\n  if( pagerUseWal(pPager) ){\n    /* Try to pull the page from the write-ahead log. */\n    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);\n  }\n  if( rc==SQLITE_OK && !isInWal ){\n    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;\n    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);\n    if( rc==SQLITE_IOERR_SHORT_READ ){\n      rc = SQLITE_OK;\n    }\n  }\n\n  if( pgno==1 ){\n    if( rc ){\n      /* If the read is unsuccessful, set the dbFileVers[] to something\n      ** that will never be a valid file version.  dbFileVers[] is a copy\n      ** of bytes 24..39 of the database.  Bytes 28..31 should always be\n      ** zero or the size of the database in page. Bytes 32..35 and 35..39\n      ** should be page numbers which are never 0xffffffff.  So filling\n      ** pPager->dbFileVers[] with all 0xff bytes should suffice.\n      **\n      ** For an encrypted database, the situation is more complex:  bytes\n      ** 24..39 of the database are white noise.  But the probability of\n      ** white noising equaling 16 bytes of 0xff is vanishingly small so\n      ** we should still be ok.\n      */\n      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));\n    }else{\n      u8 *dbFileVers = &((u8*)pPg->pData)[24];\n      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));\n    }\n  }\n  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);\n\n  PAGER_INCR(sqlite3_pager_readdb_count);\n  PAGER_INCR(pPager->nRead);\n  IOTRACE((\"PGIN %p %d\\n\", pPager, pgno));\n  PAGERTRACE((\"FETCH %d page %d hash(%08x)\\n\",\n               PAGERID(pPager), pgno, pager_pagehash(pPg)));\n\n  return rc;\n}\n\n/*\n** Update the value of the change-counter at offsets 24 and 92 in\n** the header and the sqlite version number at offset 96.\n**\n** This is an unconditional update.  See also the pager_incr_changecounter()\n** routine which only updates the change-counter if the update is actually\n** needed, as determined by the pPager->changeCountDone state variable.\n*/\nstatic void pager_write_changecounter(PgHdr *pPg){\n  u32 change_counter;\n\n  /* Increment the value just read and write it back to byte 24. */\n  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;\n  put32bits(((char*)pPg->pData)+24, change_counter);\n\n  /* Also store the SQLite version number in bytes 96..99 and in\n  ** bytes 92..95 store the change counter for which the version number\n  ** is valid. */\n  put32bits(((char*)pPg->pData)+92, change_counter);\n  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** This function is invoked once for each page that has already been \n** written into the log file when a WAL transaction is rolled back.\n** Parameter iPg is the page number of said page. The pCtx argument \n** is actually a pointer to the Pager structure.\n**\n** If page iPg is present in the cache, and has no outstanding references,\n** it is discarded. Otherwise, if there are one or more outstanding\n** references, the page content is reloaded from the database. If the\n** attempt to reload content from the database is required and fails, \n** return an SQLite error code. Otherwise, SQLITE_OK.\n*/\nstatic int pagerUndoCallback(void *pCtx, Pgno iPg){\n  int rc = SQLITE_OK;\n  Pager *pPager = (Pager *)pCtx;\n  PgHdr *pPg;\n\n  pPg = sqlite3PagerLookup(pPager, iPg);\n  if( pPg ){\n    if( sqlite3PcachePageRefcount(pPg)==1 ){\n      sqlite3PcacheDrop(pPg);\n    }else{\n      rc = readDbPage(pPg);\n      if( rc==SQLITE_OK ){\n        pPager->xReiniter(pPg);\n      }\n      sqlite3PagerUnref(pPg);\n    }\n  }\n\n  /* Normally, if a transaction is rolled back, any backup processes are\n  ** updated as data is copied out of the rollback journal and into the\n  ** database. This is not generally possible with a WAL database, as\n  ** rollback involves simply truncating the log file. Therefore, if one\n  ** or more frames have already been written to the log (and therefore \n  ** also copied into the backup databases) as part of this transaction,\n  ** the backups must be restarted.\n  */\n  sqlite3BackupRestart(pPager->pBackup);\n\n  return rc;\n}\n\n/*\n** This function is called to rollback a transaction on a WAL database.\n*/\nstatic int pagerRollbackWal(Pager *pPager){\n  int rc;                         /* Return Code */\n  PgHdr *pList;                   /* List of dirty pages to revert */\n\n  /* For all pages in the cache that are currently dirty or have already\n  ** been written (but not committed) to the log file, do one of the \n  ** following:\n  **\n  **   + Discard the cached page (if refcount==0), or\n  **   + Reload page content from the database (if refcount>0).\n  */\n  pPager->dbSize = pPager->dbOrigSize;\n  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);\n  pList = sqlite3PcacheDirtyList(pPager->pPCache);\n  while( pList && rc==SQLITE_OK ){\n    PgHdr *pNext = pList->pDirty;\n    rc = pagerUndoCallback((void *)pPager, pList->pgno);\n    pList = pNext;\n  }\n\n  return rc;\n}\n\n/*\n** This function is a wrapper around sqlite3WalFrames(). As well as logging\n** the contents of the list of pages headed by pList (connected by pDirty),\n** this function notifies any active backup processes that the pages have\n** changed. \n**\n** The list of pages passed into this routine is always sorted by page number.\n** Hence, if page 1 appears anywhere on the list, it will be the first page.\n*/ \nstatic int pagerWalFrames(\n  Pager *pPager,                  /* Pager object */\n  PgHdr *pList,                   /* List of frames to log */\n  Pgno nTruncate,                 /* Database size after this commit */\n  int isCommit                    /* True if this is a commit */\n){\n  int rc;                         /* Return code */\n  int nList;                      /* Number of pages in pList */\n#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)\n  PgHdr *p;                       /* For looping over pages */\n#endif\n\n  assert( pPager->pWal );\n  assert( pList );\n#ifdef SQLITE_DEBUG\n  /* Verify that the page list is in accending order */\n  for(p=pList; p && p->pDirty; p=p->pDirty){\n    assert( p->pgno < p->pDirty->pgno );\n  }\n#endif\n\n  assert( pList->pDirty==0 || isCommit );\n  if( isCommit ){\n    /* If a WAL transaction is being committed, there is no point in writing\n    ** any pages with page numbers greater than nTruncate into the WAL file.\n    ** They will never be read by any client. So remove them from the pDirty\n    ** list here. */\n    PgHdr *p;\n    PgHdr **ppNext = &pList;\n    nList = 0;\n    for(p=pList; (*ppNext = p)!=0; p=p->pDirty){\n      if( p->pgno<=nTruncate ){\n        ppNext = &p->pDirty;\n        nList++;\n      }\n    }\n    assert( pList );\n  }else{\n    nList = 1;\n  }\n  pPager->aStat[PAGER_STAT_WRITE] += nList;\n\n  if( pList->pgno==1 ) pager_write_changecounter(pList);\n  rc = sqlite3WalFrames(pPager->pWal, \n      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags\n  );\n  if( rc==SQLITE_OK && pPager->pBackup ){\n    PgHdr *p;\n    for(p=pList; p; p=p->pDirty){\n      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);\n    }\n  }\n\n#ifdef SQLITE_CHECK_PAGES\n  pList = sqlite3PcacheDirtyList(pPager->pPCache);\n  for(p=pList; p; p=p->pDirty){\n    pager_set_pagehash(p);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** Begin a read transaction on the WAL.\n**\n** This routine used to be called \"pagerOpenSnapshot()\" because it essentially\n** makes a snapshot of the database at the current point in time and preserves\n** that snapshot for use by the reader in spite of concurrently changes by\n** other writers or checkpointers.\n*/\nstatic int pagerBeginReadTransaction(Pager *pPager){\n  int rc;                         /* Return code */\n  int changed = 0;                /* True if cache must be reset */\n\n  assert( pagerUseWal(pPager) );\n  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );\n\n  /* sqlite3WalEndReadTransaction() was not called for the previous\n  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we\n  ** are in locking_mode=NORMAL and EndRead() was previously called,\n  ** the duplicate call is harmless.\n  */\n  sqlite3WalEndReadTransaction(pPager->pWal);\n\n  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);\n  if( rc!=SQLITE_OK || changed ){\n    pager_reset(pPager);\n  }\n\n  return rc;\n}\n#endif\n\n/*\n** This function is called as part of the transition from PAGER_OPEN\n** to PAGER_READER state to determine the size of the database file\n** in pages (assuming the page size currently stored in Pager.pageSize).\n**\n** If no error occurs, SQLITE_OK is returned and the size of the database\n** in pages is stored in *pnPage. Otherwise, an error code (perhaps\n** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.\n*/\nstatic int pagerPagecount(Pager *pPager, Pgno *pnPage){\n  Pgno nPage;                     /* Value to return via *pnPage */\n\n  /* Query the WAL sub-system for the database size. The WalDbsize()\n  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or\n  ** if the database size is not available. The database size is not\n  ** available from the WAL sub-system if the log file is empty or\n  ** contains no valid committed transactions.\n  */\n  assert( pPager->eState==PAGER_OPEN );\n  assert( pPager->eLock>=SHARED_LOCK );\n  nPage = sqlite3WalDbsize(pPager->pWal);\n\n  /* If the database size was not available from the WAL sub-system,\n  ** determine it based on the size of the database file. If the size\n  ** of the database file is not an integer multiple of the page-size,\n  ** round down to the nearest page. Except, any file larger than 0\n  ** bytes in size is considered to contain at least one page.\n  */\n  if( nPage==0 ){\n    i64 n = 0;                    /* Size of db file in bytes */\n    assert( isOpen(pPager->fd) || pPager->tempFile );\n    if( isOpen(pPager->fd) ){\n      int rc = sqlite3OsFileSize(pPager->fd, &n);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }\n    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);\n  }\n\n  /* If the current number of pages in the file is greater than the\n  ** configured maximum pager number, increase the allowed limit so\n  ** that the file can be read.\n  */\n  if( nPage>pPager->mxPgno ){\n    pPager->mxPgno = (Pgno)nPage;\n  }\n\n  *pnPage = nPage;\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Check if the *-wal file that corresponds to the database opened by pPager\n** exists if the database is not empy, or verify that the *-wal file does\n** not exist (by deleting it) if the database file is empty.\n**\n** If the database is not empty and the *-wal file exists, open the pager\n** in WAL mode.  If the database is empty or if no *-wal file exists and\n** if no error occurs, make sure Pager.journalMode is not set to\n** PAGER_JOURNALMODE_WAL.\n**\n** Return SQLITE_OK or an error code.\n**\n** The caller must hold a SHARED lock on the database file to call this\n** function. Because an EXCLUSIVE lock on the db file is required to delete \n** a WAL on a none-empty database, this ensures there is no race condition \n** between the xAccess() below and an xDelete() being executed by some \n** other connection.\n*/\nstatic int pagerOpenWalIfPresent(Pager *pPager){\n  int rc = SQLITE_OK;\n  assert( pPager->eState==PAGER_OPEN );\n  assert( pPager->eLock>=SHARED_LOCK );\n\n  if( !pPager->tempFile ){\n    int isWal;                    /* True if WAL file exists */\n    Pgno nPage;                   /* Size of the database file */\n\n    rc = pagerPagecount(pPager, &nPage);\n    if( rc ) return rc;\n    if( nPage==0 ){\n      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);\n      isWal = 0;\n    }else{\n      rc = sqlite3OsAccess(\n          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal\n      );\n    }\n    if( rc==SQLITE_OK ){\n      if( isWal ){\n        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );\n        rc = sqlite3PagerOpenWal(pPager, 0);\n      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){\n        pPager->journalMode = PAGER_JOURNALMODE_DELETE;\n      }\n    }\n  }\n  return rc;\n}\n#endif\n\n/*\n** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback\n** the entire master journal file. The case pSavepoint==NULL occurs when \n** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction \n** savepoint.\n**\n** When pSavepoint is not NULL (meaning a non-transaction savepoint is \n** being rolled back), then the rollback consists of up to three stages,\n** performed in the order specified:\n**\n**   * Pages are played back from the main journal starting at byte\n**     offset PagerSavepoint.iOffset and continuing to \n**     PagerSavepoint.iHdrOffset, or to the end of the main journal\n**     file if PagerSavepoint.iHdrOffset is zero.\n**\n**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played\n**     back starting from the journal header immediately following \n**     PagerSavepoint.iHdrOffset to the end of the main journal file.\n**\n**   * Pages are then played back from the sub-journal file, starting\n**     with the PagerSavepoint.iSubRec and continuing to the end of\n**     the journal file.\n**\n** Throughout the rollback process, each time a page is rolled back, the\n** corresponding bit is set in a bitvec structure (variable pDone in the\n** implementation below). This is used to ensure that a page is only\n** rolled back the first time it is encountered in either journal.\n**\n** If pSavepoint is NULL, then pages are only played back from the main\n** journal file. There is no need for a bitvec in this case.\n**\n** In either case, before playback commences the Pager.dbSize variable\n** is reset to the value that it held at the start of the savepoint \n** (or transaction). No page with a page-number greater than this value\n** is played back. If one is encountered it is simply skipped.\n*/\nstatic int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){\n  i64 szJ;                 /* Effective size of the main journal */\n  i64 iHdrOff;             /* End of first segment of main-journal records */\n  int rc = SQLITE_OK;      /* Return code */\n  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */\n\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n\n  /* Allocate a bitvec to use to store the set of pages rolled back */\n  if( pSavepoint ){\n    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);\n    if( !pDone ){\n      return SQLITE_NOMEM;\n    }\n  }\n\n  /* Set the database size back to the value it was before the savepoint \n  ** being reverted was opened.\n  */\n  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;\n  pPager->changeCountDone = pPager->tempFile;\n\n  if( !pSavepoint && pagerUseWal(pPager) ){\n    return pagerRollbackWal(pPager);\n  }\n\n  /* Use pPager->journalOff as the effective size of the main rollback\n  ** journal.  The actual file might be larger than this in\n  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything\n  ** past pPager->journalOff is off-limits to us.\n  */\n  szJ = pPager->journalOff;\n  assert( pagerUseWal(pPager)==0 || szJ==0 );\n\n  /* Begin by rolling back records from the main journal starting at\n  ** PagerSavepoint.iOffset and continuing to the next journal header.\n  ** There might be records in the main journal that have a page number\n  ** greater than the current database size (pPager->dbSize) but those\n  ** will be skipped automatically.  Pages are added to pDone as they\n  ** are played back.\n  */\n  if( pSavepoint && !pagerUseWal(pPager) ){\n    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;\n    pPager->journalOff = pSavepoint->iOffset;\n    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){\n      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }else{\n    pPager->journalOff = 0;\n  }\n\n  /* Continue rolling back records out of the main journal starting at\n  ** the first journal header seen and continuing until the effective end\n  ** of the main journal file.  Continue to skip out-of-range pages and\n  ** continue adding pages rolled back to pDone.\n  */\n  while( rc==SQLITE_OK && pPager->journalOff<szJ ){\n    u32 ii;            /* Loop counter */\n    u32 nJRec = 0;     /* Number of Journal Records */\n    u32 dummy;\n    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);\n    assert( rc!=SQLITE_DONE );\n\n    /*\n    ** The \"pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff\"\n    ** test is related to ticket #2565.  See the discussion in the\n    ** pager_playback() function for additional information.\n    */\n    if( nJRec==0 \n     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff\n    ){\n      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));\n    }\n    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){\n      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }\n  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );\n\n  /* Finally,  rollback pages from the sub-journal.  Page that were\n  ** previously rolled back out of the main journal (and are hence in pDone)\n  ** will be skipped.  Out-of-range pages are also skipped.\n  */\n  if( pSavepoint ){\n    u32 ii;            /* Loop counter */\n    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);\n\n    if( pagerUseWal(pPager) ){\n      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);\n    }\n    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){\n      assert( offset==(i64)ii*(4+pPager->pageSize) );\n      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);\n    }\n    assert( rc!=SQLITE_DONE );\n  }\n\n  sqlite3BitvecDestroy(pDone);\n  if( rc==SQLITE_OK ){\n    pPager->journalOff = szJ;\n  }\n\n  return rc;\n}\n\n/*\n** Change the maximum number of in-memory pages that are allowed.\n*/\nSQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){\n  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);\n}\n\n/*\n** Free as much memory as possible from the pager.\n*/\nSQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){\n  sqlite3PcacheShrink(pPager->pPCache);\n}\n\n/*\n** Adjust the robustness of the database to damage due to OS crashes\n** or power failures by changing the number of syncs()s when writing\n** the rollback journal.  There are three levels:\n**\n**    OFF       sqlite3OsSync() is never called.  This is the default\n**              for temporary and transient files.\n**\n**    NORMAL    The journal is synced once before writes begin on the\n**              database.  This is normally adequate protection, but\n**              it is theoretically possible, though very unlikely,\n**              that an inopertune power failure could leave the journal\n**              in a state which would cause damage to the database\n**              when it is rolled back.\n**\n**    FULL      The journal is synced twice before writes begin on the\n**              database (with some additional information - the nRec field\n**              of the journal header - being written in between the two\n**              syncs).  If we assume that writing a\n**              single disk sector is atomic, then this mode provides\n**              assurance that the journal will not be corrupted to the\n**              point of causing damage to the database during rollback.\n**\n** The above is for a rollback-journal mode.  For WAL mode, OFF continues\n** to mean that no syncs ever occur.  NORMAL means that the WAL is synced\n** prior to the start of checkpoint and that the database file is synced\n** at the conclusion of the checkpoint if the entire content of the WAL\n** was written back into the database.  But no sync operations occur for\n** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL\n** file is synced following each commit operation, in addition to the\n** syncs associated with NORMAL.\n**\n** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The\n** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync\n** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an\n** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL\n** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the\n** synchronous=FULL versus synchronous=NORMAL setting determines when\n** the xSync primitive is called and is relevant to all platforms.\n**\n** Numeric values associated with these states are OFF==1, NORMAL=2,\n** and FULL=3.\n*/\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\nSQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(\n  Pager *pPager,        /* The pager to set safety level for */\n  int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  \n  int bFullFsync,       /* PRAGMA fullfsync */\n  int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */\n){\n  assert( level>=1 && level<=3 );\n  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;\n  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;\n  if( pPager->noSync ){\n    pPager->syncFlags = 0;\n    pPager->ckptSyncFlags = 0;\n  }else if( bFullFsync ){\n    pPager->syncFlags = SQLITE_SYNC_FULL;\n    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;\n  }else if( bCkptFullFsync ){\n    pPager->syncFlags = SQLITE_SYNC_NORMAL;\n    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;\n  }else{\n    pPager->syncFlags = SQLITE_SYNC_NORMAL;\n    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;\n  }\n  pPager->walSyncFlags = pPager->syncFlags;\n  if( pPager->fullSync ){\n    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;\n  }\n}\n#endif\n\n/*\n** The following global variable is incremented whenever the library\n** attempts to open a temporary file.  This information is used for\n** testing and analysis only.  \n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_opentemp_count = 0;\n#endif\n\n/*\n** Open a temporary file.\n**\n** Write the file descriptor into *pFile. Return SQLITE_OK on success \n** or some other error code if we fail. The OS will automatically \n** delete the temporary file when it is closed.\n**\n** The flags passed to the VFS layer xOpen() call are those specified\n** by parameter vfsFlags ORed with the following:\n**\n**     SQLITE_OPEN_READWRITE\n**     SQLITE_OPEN_CREATE\n**     SQLITE_OPEN_EXCLUSIVE\n**     SQLITE_OPEN_DELETEONCLOSE\n*/\nstatic int pagerOpentemp(\n  Pager *pPager,        /* The pager object */\n  sqlite3_file *pFile,  /* Write the file descriptor here */\n  int vfsFlags          /* Flags passed through to the VFS */\n){\n  int rc;               /* Return code */\n\n#ifdef SQLITE_TEST\n  sqlite3_opentemp_count++;  /* Used for testing and analysis only */\n#endif\n\n  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |\n            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;\n  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);\n  assert( rc!=SQLITE_OK || isOpen(pFile) );\n  return rc;\n}\n\n/*\n** Set the busy handler function.\n**\n** The pager invokes the busy-handler if sqlite3OsLock() returns \n** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,\n** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE \n** lock. It does *not* invoke the busy handler when upgrading from\n** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE\n** (which occurs during hot-journal rollback). Summary:\n**\n**   Transition                        | Invokes xBusyHandler\n**   --------------------------------------------------------\n**   NO_LOCK       -> SHARED_LOCK      | Yes\n**   SHARED_LOCK   -> RESERVED_LOCK    | No\n**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No\n**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes\n**\n** If the busy-handler callback returns non-zero, the lock is \n** retried. If it returns zero, then the SQLITE_BUSY error is\n** returned to the caller of the pager API function.\n*/\nSQLITE_PRIVATE void sqlite3PagerSetBusyhandler(\n  Pager *pPager,                       /* Pager object */\n  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */\n  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */\n){  \n  pPager->xBusyHandler = xBusyHandler;\n  pPager->pBusyHandlerArg = pBusyHandlerArg;\n}\n\n/*\n** Change the page size used by the Pager object. The new page size \n** is passed in *pPageSize.\n**\n** If the pager is in the error state when this function is called, it\n** is a no-op. The value returned is the error state error code (i.e. \n** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).\n**\n** Otherwise, if all of the following are true:\n**\n**   * the new page size (value of *pPageSize) is valid (a power \n**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and\n**\n**   * there are no outstanding page references, and\n**\n**   * the database is either not an in-memory database or it is\n**     an in-memory database that currently consists of zero pages.\n**\n** then the pager object page size is set to *pPageSize.\n**\n** If the page size is changed, then this function uses sqlite3PagerMalloc() \n** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt \n** fails, SQLITE_NOMEM is returned and the page size remains unchanged. \n** In all other cases, SQLITE_OK is returned.\n**\n** If the page size is not changed, either because one of the enumerated\n** conditions above is not true, the pager was in error state when this\n** function was called, or because the memory allocation attempt failed, \n** then *pPageSize is set to the old, retained page size before returning.\n*/\nSQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){\n  int rc = SQLITE_OK;\n\n  /* It is not possible to do a full assert_pager_state() here, as this\n  ** function may be called from within PagerOpen(), before the state\n  ** of the Pager object is internally consistent.\n  **\n  ** At one point this function returned an error if the pager was in \n  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that\n  ** there is at least one outstanding page reference, this function\n  ** is a no-op for that case anyhow.\n  */\n\n  u32 pageSize = *pPageSize;\n  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );\n  if( (pPager->memDb==0 || pPager->dbSize==0)\n   && sqlite3PcacheRefCount(pPager->pPCache)==0 \n   && pageSize && pageSize!=(u32)pPager->pageSize \n  ){\n    char *pNew = NULL;             /* New temp space */\n    i64 nByte = 0;\n\n    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){\n      rc = sqlite3OsFileSize(pPager->fd, &nByte);\n    }\n    if( rc==SQLITE_OK ){\n      pNew = (char *)sqlite3PageMalloc(pageSize);\n      if( !pNew ) rc = SQLITE_NOMEM;\n    }\n\n    if( rc==SQLITE_OK ){\n      pager_reset(pPager);\n      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);\n      pPager->pageSize = pageSize;\n      sqlite3PageFree(pPager->pTmpSpace);\n      pPager->pTmpSpace = pNew;\n      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);\n    }\n  }\n\n  *pPageSize = pPager->pageSize;\n  if( rc==SQLITE_OK ){\n    if( nReserve<0 ) nReserve = pPager->nReserve;\n    assert( nReserve>=0 && nReserve<1000 );\n    pPager->nReserve = (i16)nReserve;\n    pagerReportSize(pPager);\n  }\n  return rc;\n}\n\n/*\n** Return a pointer to the \"temporary page\" buffer held internally\n** by the pager.  This is a buffer that is big enough to hold the\n** entire content of a database page.  This buffer is used internally\n** during rollback and will be overwritten whenever a rollback\n** occurs.  But other modules are free to use it too, as long as\n** no rollbacks are happening.\n*/\nSQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){\n  return pPager->pTmpSpace;\n}\n\n/*\n** Attempt to set the maximum database page count if mxPage is positive. \n** Make no changes if mxPage is zero or negative.  And never reduce the\n** maximum page count below the current size of the database.\n**\n** Regardless of mxPage, return the current maximum page count.\n*/\nSQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){\n  if( mxPage>0 ){\n    pPager->mxPgno = mxPage;\n  }\n  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */\n  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */\n  return pPager->mxPgno;\n}\n\n/*\n** The following set of routines are used to disable the simulated\n** I/O error mechanism.  These routines are used to avoid simulated\n** errors in places where we do not care about errors.\n**\n** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops\n** and generate no code.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API extern int sqlite3_io_error_pending;\nSQLITE_API extern int sqlite3_io_error_hit;\nstatic int saved_cnt;\nvoid disable_simulated_io_errors(void){\n  saved_cnt = sqlite3_io_error_pending;\n  sqlite3_io_error_pending = -1;\n}\nvoid enable_simulated_io_errors(void){\n  sqlite3_io_error_pending = saved_cnt;\n}\n#else\n# define disable_simulated_io_errors()\n# define enable_simulated_io_errors()\n#endif\n\n/*\n** Read the first N bytes from the beginning of the file into memory\n** that pDest points to. \n**\n** If the pager was opened on a transient file (zFilename==\"\"), or\n** opened on a file less than N bytes in size, the output buffer is\n** zeroed and SQLITE_OK returned. The rationale for this is that this \n** function is used to read database headers, and a new transient or\n** zero sized database has a header than consists entirely of zeroes.\n**\n** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,\n** the error code is returned to the caller and the contents of the\n** output buffer undefined.\n*/\nSQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){\n  int rc = SQLITE_OK;\n  memset(pDest, 0, N);\n  assert( isOpen(pPager->fd) || pPager->tempFile );\n\n  /* This routine is only called by btree immediately after creating\n  ** the Pager object.  There has not been an opportunity to transition\n  ** to WAL mode yet.\n  */\n  assert( !pagerUseWal(pPager) );\n\n  if( isOpen(pPager->fd) ){\n    IOTRACE((\"DBHDR %p 0 %d\\n\", pPager, N))\n    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);\n    if( rc==SQLITE_IOERR_SHORT_READ ){\n      rc = SQLITE_OK;\n    }\n  }\n  return rc;\n}\n\n/*\n** This function may only be called when a read-transaction is open on\n** the pager. It returns the total number of pages in the database.\n**\n** However, if the file is between 1 and <page-size> bytes in size, then \n** this is considered a 1 page file.\n*/\nSQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){\n  assert( pPager->eState>=PAGER_READER );\n  assert( pPager->eState!=PAGER_WRITER_FINISHED );\n  *pnPage = (int)pPager->dbSize;\n}\n\n\n/*\n** Try to obtain a lock of type locktype on the database file. If\n** a similar or greater lock is already held, this function is a no-op\n** (returning SQLITE_OK immediately).\n**\n** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke \n** the busy callback if the lock is currently not available. Repeat \n** until the busy callback returns false or until the attempt to \n** obtain the lock succeeds.\n**\n** Return SQLITE_OK on success and an error code if we cannot obtain\n** the lock. If the lock is obtained successfully, set the Pager.state \n** variable to locktype before returning.\n*/\nstatic int pager_wait_on_lock(Pager *pPager, int locktype){\n  int rc;                              /* Return code */\n\n  /* Check that this is either a no-op (because the requested lock is \n  ** already held, or one of the transistions that the busy-handler\n  ** may be invoked during, according to the comment above\n  ** sqlite3PagerSetBusyhandler().\n  */\n  assert( (pPager->eLock>=locktype)\n       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)\n       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)\n  );\n\n  do {\n    rc = pagerLockDb(pPager, locktype);\n  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );\n  return rc;\n}\n\n/*\n** Function assertTruncateConstraint(pPager) checks that one of the \n** following is true for all dirty pages currently in the page-cache:\n**\n**   a) The page number is less than or equal to the size of the \n**      current database image, in pages, OR\n**\n**   b) if the page content were written at this time, it would not\n**      be necessary to write the current content out to the sub-journal\n**      (as determined by function subjRequiresPage()).\n**\n** If the condition asserted by this function were not true, and the\n** dirty page were to be discarded from the cache via the pagerStress()\n** routine, pagerStress() would not write the current page content to\n** the database file. If a savepoint transaction were rolled back after\n** this happened, the correct behaviour would be to restore the current\n** content of the page. However, since this content is not present in either\n** the database file or the portion of the rollback journal and \n** sub-journal rolled back the content could not be restored and the\n** database image would become corrupt. It is therefore fortunate that \n** this circumstance cannot arise.\n*/\n#if defined(SQLITE_DEBUG)\nstatic void assertTruncateConstraintCb(PgHdr *pPg){\n  assert( pPg->flags&PGHDR_DIRTY );\n  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );\n}\nstatic void assertTruncateConstraint(Pager *pPager){\n  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);\n}\n#else\n# define assertTruncateConstraint(pPager)\n#endif\n\n/*\n** Truncate the in-memory database file image to nPage pages. This \n** function does not actually modify the database file on disk. It \n** just sets the internal state of the pager object so that the \n** truncation will be done when the current transaction is committed.\n*/\nSQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){\n  assert( pPager->dbSize>=nPage );\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );\n  pPager->dbSize = nPage;\n  assertTruncateConstraint(pPager);\n}\n\n\n/*\n** This function is called before attempting a hot-journal rollback. It\n** syncs the journal file to disk, then sets pPager->journalHdr to the\n** size of the journal file so that the pager_playback() routine knows\n** that the entire journal file has been synced.\n**\n** Syncing a hot-journal to disk before attempting to roll it back ensures \n** that if a power-failure occurs during the rollback, the process that\n** attempts rollback following system recovery sees the same journal\n** content as this process.\n**\n** If everything goes as planned, SQLITE_OK is returned. Otherwise, \n** an SQLite error code.\n*/\nstatic int pagerSyncHotJournal(Pager *pPager){\n  int rc = SQLITE_OK;\n  if( !pPager->noSync ){\n    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);\n  }\n  if( rc==SQLITE_OK ){\n    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);\n  }\n  return rc;\n}\n\n/*\n** Shutdown the page cache.  Free all memory and close all files.\n**\n** If a transaction was in progress when this routine is called, that\n** transaction is rolled back.  All outstanding pages are invalidated\n** and their memory is freed.  Any attempt to use a page associated\n** with this page cache after this function returns will likely\n** result in a coredump.\n**\n** This function always succeeds. If a transaction is active an attempt\n** is made to roll it back. If an error occurs during the rollback \n** a hot journal may be left in the filesystem but no error is returned\n** to the caller.\n*/\nSQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){\n  u8 *pTmp = (u8 *)pPager->pTmpSpace;\n\n  assert( assert_pager_state(pPager) );\n  disable_simulated_io_errors();\n  sqlite3BeginBenignMalloc();\n  /* pPager->errCode = 0; */\n  pPager->exclusiveMode = 0;\n#ifndef SQLITE_OMIT_WAL\n  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);\n  pPager->pWal = 0;\n#endif\n  pager_reset(pPager);\n  if( MEMDB ){\n    pager_unlock(pPager);\n  }else{\n    /* If it is open, sync the journal file before calling UnlockAndRollback.\n    ** If this is not done, then an unsynced portion of the open journal \n    ** file may be played back into the database. If a power failure occurs \n    ** while this is happening, the database could become corrupt.\n    **\n    ** If an error occurs while trying to sync the journal, shift the pager\n    ** into the ERROR state. This causes UnlockAndRollback to unlock the\n    ** database and close the journal file without attempting to roll it\n    ** back or finalize it. The next database user will have to do hot-journal\n    ** rollback before accessing the database file.\n    */\n    if( isOpen(pPager->jfd) ){\n      pager_error(pPager, pagerSyncHotJournal(pPager));\n    }\n    pagerUnlockAndRollback(pPager);\n  }\n  sqlite3EndBenignMalloc();\n  enable_simulated_io_errors();\n  PAGERTRACE((\"CLOSE %d\\n\", PAGERID(pPager)));\n  IOTRACE((\"CLOSE %p\\n\", pPager))\n  sqlite3OsClose(pPager->jfd);\n  sqlite3OsClose(pPager->fd);\n  sqlite3PageFree(pTmp);\n  sqlite3PcacheClose(pPager->pPCache);\n\n#ifdef SQLITE_HAS_CODEC\n  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);\n#endif\n\n  assert( !pPager->aSavepoint && !pPager->pInJournal );\n  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );\n\n  sqlite3_free(pPager);\n  return SQLITE_OK;\n}\n\n#if !defined(NDEBUG) || defined(SQLITE_TEST)\n/*\n** Return the page number for page pPg.\n*/\nSQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){\n  return pPg->pgno;\n}\n#endif\n\n/*\n** Increment the reference count for page pPg.\n*/\nSQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){\n  sqlite3PcacheRef(pPg);\n}\n\n/*\n** Sync the journal. In other words, make sure all the pages that have\n** been written to the journal have actually reached the surface of the\n** disk and can be restored in the event of a hot-journal rollback.\n**\n** If the Pager.noSync flag is set, then this function is a no-op.\n** Otherwise, the actions required depend on the journal-mode and the \n** device characteristics of the file-system, as follows:\n**\n**   * If the journal file is an in-memory journal file, no action need\n**     be taken.\n**\n**   * Otherwise, if the device does not support the SAFE_APPEND property,\n**     then the nRec field of the most recently written journal header\n**     is updated to contain the number of journal records that have\n**     been written following it. If the pager is operating in full-sync\n**     mode, then the journal file is synced before this field is updated.\n**\n**   * If the device does not support the SEQUENTIAL property, then \n**     journal file is synced.\n**\n** Or, in pseudo-code:\n**\n**   if( NOT <in-memory journal> ){\n**     if( NOT SAFE_APPEND ){\n**       if( <full-sync mode> ) xSync(<journal file>);\n**       <update nRec field>\n**     } \n**     if( NOT SEQUENTIAL ) xSync(<journal file>);\n**   }\n**\n** If successful, this routine clears the PGHDR_NEED_SYNC flag of every \n** page currently held in memory before returning SQLITE_OK. If an IO\n** error is encountered, then the IO error code is returned to the caller.\n*/\nstatic int syncJournal(Pager *pPager, int newHdr){\n  int rc;                         /* Return code */\n\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n  assert( !pagerUseWal(pPager) );\n\n  rc = sqlite3PagerExclusiveLock(pPager);\n  if( rc!=SQLITE_OK ) return rc;\n\n  if( !pPager->noSync ){\n    assert( !pPager->tempFile );\n    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){\n      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);\n      assert( isOpen(pPager->jfd) );\n\n      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){\n        /* This block deals with an obscure problem. If the last connection\n        ** that wrote to this database was operating in persistent-journal\n        ** mode, then the journal file may at this point actually be larger\n        ** than Pager.journalOff bytes. If the next thing in the journal\n        ** file happens to be a journal-header (written as part of the\n        ** previous connection's transaction), and a crash or power-failure \n        ** occurs after nRec is updated but before this connection writes \n        ** anything else to the journal file (or commits/rolls back its \n        ** transaction), then SQLite may become confused when doing the \n        ** hot-journal rollback following recovery. It may roll back all\n        ** of this connections data, then proceed to rolling back the old,\n        ** out-of-date data that follows it. Database corruption.\n        **\n        ** To work around this, if the journal file does appear to contain\n        ** a valid header following Pager.journalOff, then write a 0x00\n        ** byte to the start of it to prevent it from being recognized.\n        **\n        ** Variable iNextHdrOffset is set to the offset at which this\n        ** problematic header will occur, if it exists. aMagic is used \n        ** as a temporary buffer to inspect the first couple of bytes of\n        ** the potential journal header.\n        */\n        i64 iNextHdrOffset;\n        u8 aMagic[8];\n        u8 zHeader[sizeof(aJournalMagic)+4];\n\n        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));\n        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);\n\n        iNextHdrOffset = journalHdrOffset(pPager);\n        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);\n        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){\n          static const u8 zerobyte = 0;\n          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);\n        }\n        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){\n          return rc;\n        }\n\n        /* Write the nRec value into the journal file header. If in\n        ** full-synchronous mode, sync the journal first. This ensures that\n        ** all data has really hit the disk before nRec is updated to mark\n        ** it as a candidate for rollback.\n        **\n        ** This is not required if the persistent media supports the\n        ** SAFE_APPEND property. Because in this case it is not possible \n        ** for garbage data to be appended to the file, the nRec field\n        ** is populated with 0xFFFFFFFF when the journal header is written\n        ** and never needs to be updated.\n        */\n        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){\n          PAGERTRACE((\"SYNC journal of %d\\n\", PAGERID(pPager)));\n          IOTRACE((\"JSYNC %p\\n\", pPager))\n          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);\n          if( rc!=SQLITE_OK ) return rc;\n        }\n        IOTRACE((\"JHDR %p %lld\\n\", pPager, pPager->journalHdr));\n        rc = sqlite3OsWrite(\n            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr\n        );\n        if( rc!=SQLITE_OK ) return rc;\n      }\n      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){\n        PAGERTRACE((\"SYNC journal of %d\\n\", PAGERID(pPager)));\n        IOTRACE((\"JSYNC %p\\n\", pPager))\n        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| \n          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)\n        );\n        if( rc!=SQLITE_OK ) return rc;\n      }\n\n      pPager->journalHdr = pPager->journalOff;\n      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){\n        pPager->nRec = 0;\n        rc = writeJournalHdr(pPager);\n        if( rc!=SQLITE_OK ) return rc;\n      }\n    }else{\n      pPager->journalHdr = pPager->journalOff;\n    }\n  }\n\n  /* Unless the pager is in noSync mode, the journal file was just \n  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on \n  ** all pages.\n  */\n  sqlite3PcacheClearSyncFlags(pPager->pPCache);\n  pPager->eState = PAGER_WRITER_DBMOD;\n  assert( assert_pager_state(pPager) );\n  return SQLITE_OK;\n}\n\n/*\n** The argument is the first in a linked list of dirty pages connected\n** by the PgHdr.pDirty pointer. This function writes each one of the\n** in-memory pages in the list to the database file. The argument may\n** be NULL, representing an empty list. In this case this function is\n** a no-op.\n**\n** The pager must hold at least a RESERVED lock when this function\n** is called. Before writing anything to the database file, this lock\n** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,\n** SQLITE_BUSY is returned and no data is written to the database file.\n** \n** If the pager is a temp-file pager and the actual file-system file\n** is not yet open, it is created and opened before any data is \n** written out.\n**\n** Once the lock has been upgraded and, if necessary, the file opened,\n** the pages are written out to the database file in list order. Writing\n** a page is skipped if it meets either of the following criteria:\n**\n**   * The page number is greater than Pager.dbSize, or\n**   * The PGHDR_DONT_WRITE flag is set on the page.\n**\n** If writing out a page causes the database file to grow, Pager.dbFileSize\n** is updated accordingly. If page 1 is written out, then the value cached\n** in Pager.dbFileVers[] is updated to match the new value stored in\n** the database file.\n**\n** If everything is successful, SQLITE_OK is returned. If an IO error \n** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot\n** be obtained, SQLITE_BUSY is returned.\n*/\nstatic int pager_write_pagelist(Pager *pPager, PgHdr *pList){\n  int rc = SQLITE_OK;                  /* Return code */\n\n  /* This function is only called for rollback pagers in WRITER_DBMOD state. */\n  assert( !pagerUseWal(pPager) );\n  assert( pPager->eState==PAGER_WRITER_DBMOD );\n  assert( pPager->eLock==EXCLUSIVE_LOCK );\n\n  /* If the file is a temp-file has not yet been opened, open it now. It\n  ** is not possible for rc to be other than SQLITE_OK if this branch\n  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.\n  */\n  if( !isOpen(pPager->fd) ){\n    assert( pPager->tempFile && rc==SQLITE_OK );\n    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);\n  }\n\n  /* Before the first write, give the VFS a hint of what the final\n  ** file size will be.\n  */\n  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );\n  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){\n    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;\n    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);\n    pPager->dbHintSize = pPager->dbSize;\n  }\n\n  while( rc==SQLITE_OK && pList ){\n    Pgno pgno = pList->pgno;\n\n    /* If there are dirty pages in the page cache with page numbers greater\n    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to\n    ** make the file smaller (presumably by auto-vacuum code). Do not write\n    ** any such pages to the file.\n    **\n    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag\n    ** set (set by sqlite3PagerDontWrite()).\n    */\n    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){\n      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */\n      char *pData;                                   /* Data to write */    \n\n      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );\n      if( pList->pgno==1 ) pager_write_changecounter(pList);\n\n      /* Encode the database */\n      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);\n\n      /* Write out the page data. */\n      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);\n\n      /* If page 1 was just written, update Pager.dbFileVers to match\n      ** the value now stored in the database file. If writing this \n      ** page caused the database file to grow, update dbFileSize. \n      */\n      if( pgno==1 ){\n        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));\n      }\n      if( pgno>pPager->dbFileSize ){\n        pPager->dbFileSize = pgno;\n      }\n      pPager->aStat[PAGER_STAT_WRITE]++;\n\n      /* Update any backup objects copying the contents of this pager. */\n      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);\n\n      PAGERTRACE((\"STORE %d page %d hash(%08x)\\n\",\n                   PAGERID(pPager), pgno, pager_pagehash(pList)));\n      IOTRACE((\"PGOUT %p %d\\n\", pPager, pgno));\n      PAGER_INCR(sqlite3_pager_writedb_count);\n    }else{\n      PAGERTRACE((\"NOSTORE %d page %d\\n\", PAGERID(pPager), pgno));\n    }\n    pager_set_pagehash(pList);\n    pList = pList->pDirty;\n  }\n\n  return rc;\n}\n\n/*\n** Ensure that the sub-journal file is open. If it is already open, this \n** function is a no-op.\n**\n** SQLITE_OK is returned if everything goes according to plan. An \n** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() \n** fails.\n*/\nstatic int openSubJournal(Pager *pPager){\n  int rc = SQLITE_OK;\n  if( !isOpen(pPager->sjfd) ){\n    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){\n      sqlite3MemJournalOpen(pPager->sjfd);\n    }else{\n      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);\n    }\n  }\n  return rc;\n}\n\n/*\n** Append a record of the current state of page pPg to the sub-journal. \n** It is the callers responsibility to use subjRequiresPage() to check \n** that it is really required before calling this function.\n**\n** If successful, set the bit corresponding to pPg->pgno in the bitvecs\n** for all open savepoints before returning.\n**\n** This function returns SQLITE_OK if everything is successful, an IO\n** error code if the attempt to write to the sub-journal fails, or \n** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint\n** bitvec.\n*/\nstatic int subjournalPage(PgHdr *pPg){\n  int rc = SQLITE_OK;\n  Pager *pPager = pPg->pPager;\n  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){\n\n    /* Open the sub-journal, if it has not already been opened */\n    assert( pPager->useJournal );\n    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );\n    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );\n    assert( pagerUseWal(pPager) \n         || pageInJournal(pPg) \n         || pPg->pgno>pPager->dbOrigSize \n    );\n    rc = openSubJournal(pPager);\n\n    /* If the sub-journal was opened successfully (or was already open),\n    ** write the journal record into the file.  */\n    if( rc==SQLITE_OK ){\n      void *pData = pPg->pData;\n      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);\n      char *pData2;\n  \n      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);\n      PAGERTRACE((\"STMT-JOURNAL %d page %d\\n\", PAGERID(pPager), pPg->pgno));\n      rc = write32bits(pPager->sjfd, offset, pPg->pgno);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    pPager->nSubRec++;\n    assert( pPager->nSavepoint>0 );\n    rc = addToSavepointBitvecs(pPager, pPg->pgno);\n  }\n  return rc;\n}\n\n/*\n** This function is called by the pcache layer when it has reached some\n** soft memory limit. The first argument is a pointer to a Pager object\n** (cast as a void*). The pager is always 'purgeable' (not an in-memory\n** database). The second argument is a reference to a page that is \n** currently dirty but has no outstanding references. The page\n** is always associated with the Pager object passed as the first \n** argument.\n**\n** The job of this function is to make pPg clean by writing its contents\n** out to the database file, if possible. This may involve syncing the\n** journal file. \n**\n** If successful, sqlite3PcacheMakeClean() is called on the page and\n** SQLITE_OK returned. If an IO error occurs while trying to make the\n** page clean, the IO error code is returned. If the page cannot be\n** made clean for some other reason, but no error occurs, then SQLITE_OK\n** is returned by sqlite3PcacheMakeClean() is not called.\n*/\nstatic int pagerStress(void *p, PgHdr *pPg){\n  Pager *pPager = (Pager *)p;\n  int rc = SQLITE_OK;\n\n  assert( pPg->pPager==pPager );\n  assert( pPg->flags&PGHDR_DIRTY );\n\n  /* The doNotSyncSpill flag is set during times when doing a sync of\n  ** journal (and adding a new header) is not allowed.  This occurs\n  ** during calls to sqlite3PagerWrite() while trying to journal multiple\n  ** pages belonging to the same sector.\n  **\n  ** The doNotSpill flag inhibits all cache spilling regardless of whether\n  ** or not a sync is required.  This is set during a rollback.\n  **\n  ** Spilling is also prohibited when in an error state since that could\n  ** lead to database corruption.   In the current implementaton it \n  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1\n  ** while in the error state, hence it is impossible for this routine to\n  ** be called in the error state.  Nevertheless, we include a NEVER()\n  ** test for the error state as a safeguard against future changes.\n  */\n  if( NEVER(pPager->errCode) ) return SQLITE_OK;\n  if( pPager->doNotSpill ) return SQLITE_OK;\n  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){\n    return SQLITE_OK;\n  }\n\n  pPg->pDirty = 0;\n  if( pagerUseWal(pPager) ){\n    /* Write a single frame for this page to the log. */\n    if( subjRequiresPage(pPg) ){ \n      rc = subjournalPage(pPg); \n    }\n    if( rc==SQLITE_OK ){\n      rc = pagerWalFrames(pPager, pPg, 0, 0);\n    }\n  }else{\n  \n    /* Sync the journal file if required. */\n    if( pPg->flags&PGHDR_NEED_SYNC \n     || pPager->eState==PAGER_WRITER_CACHEMOD\n    ){\n      rc = syncJournal(pPager, 1);\n    }\n  \n    /* If the page number of this page is larger than the current size of\n    ** the database image, it may need to be written to the sub-journal.\n    ** This is because the call to pager_write_pagelist() below will not\n    ** actually write data to the file in this case.\n    **\n    ** Consider the following sequence of events:\n    **\n    **   BEGIN;\n    **     <journal page X>\n    **     <modify page X>\n    **     SAVEPOINT sp;\n    **       <shrink database file to Y pages>\n    **       pagerStress(page X)\n    **     ROLLBACK TO sp;\n    **\n    ** If (X>Y), then when pagerStress is called page X will not be written\n    ** out to the database file, but will be dropped from the cache. Then,\n    ** following the \"ROLLBACK TO sp\" statement, reading page X will read\n    ** data from the database file. This will be the copy of page X as it\n    ** was when the transaction started, not as it was when \"SAVEPOINT sp\"\n    ** was executed.\n    **\n    ** The solution is to write the current data for page X into the \n    ** sub-journal file now (if it is not already there), so that it will\n    ** be restored to its current value when the \"ROLLBACK TO sp\" is \n    ** executed.\n    */\n    if( NEVER(\n        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)\n    ) ){\n      rc = subjournalPage(pPg);\n    }\n  \n    /* Write the contents of the page out to the database file. */\n    if( rc==SQLITE_OK ){\n      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );\n      rc = pager_write_pagelist(pPager, pPg);\n    }\n  }\n\n  /* Mark the page as clean. */\n  if( rc==SQLITE_OK ){\n    PAGERTRACE((\"STRESS %d page %d\\n\", PAGERID(pPager), pPg->pgno));\n    sqlite3PcacheMakeClean(pPg);\n  }\n\n  return pager_error(pPager, rc); \n}\n\n\n/*\n** Allocate and initialize a new Pager object and put a pointer to it\n** in *ppPager. The pager should eventually be freed by passing it\n** to sqlite3PagerClose().\n**\n** The zFilename argument is the path to the database file to open.\n** If zFilename is NULL then a randomly-named temporary file is created\n** and used as the file to be cached. Temporary files are be deleted\n** automatically when they are closed. If zFilename is \":memory:\" then \n** all information is held in cache. It is never written to disk. \n** This can be used to implement an in-memory database.\n**\n** The nExtra parameter specifies the number of bytes of space allocated\n** along with each page reference. This space is available to the user\n** via the sqlite3PagerGetExtra() API.\n**\n** The flags argument is used to specify properties that affect the\n** operation of the pager. It should be passed some bitwise combination\n** of the PAGER_* flags.\n**\n** The vfsFlags parameter is a bitmask to pass to the flags parameter\n** of the xOpen() method of the supplied VFS when opening files. \n**\n** If the pager object is allocated and the specified file opened \n** successfully, SQLITE_OK is returned and *ppPager set to point to\n** the new pager object. If an error occurs, *ppPager is set to NULL\n** and error code returned. This function may return SQLITE_NOMEM\n** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or \n** various SQLITE_IO_XXX errors.\n*/\nSQLITE_PRIVATE int sqlite3PagerOpen(\n  sqlite3_vfs *pVfs,       /* The virtual file system to use */\n  Pager **ppPager,         /* OUT: Return the Pager structure here */\n  const char *zFilename,   /* Name of the database file to open */\n  int nExtra,              /* Extra bytes append to each in-memory page */\n  int flags,               /* flags controlling this file */\n  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */\n  void (*xReinit)(DbPage*) /* Function to reinitialize pages */\n){\n  u8 *pPtr;\n  Pager *pPager = 0;       /* Pager object to allocate and return */\n  int rc = SQLITE_OK;      /* Return code */\n  int tempFile = 0;        /* True for temp files (incl. in-memory files) */\n  int memDb = 0;           /* True if this is an in-memory file */\n  int readOnly = 0;        /* True if this is a read-only file */\n  int journalFileSize;     /* Bytes to allocate for each journal fd */\n  char *zPathname = 0;     /* Full path to database file */\n  int nPathname = 0;       /* Number of bytes in zPathname */\n  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */\n  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */\n  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */\n  const char *zUri = 0;    /* URI args to copy */\n  int nUri = 0;            /* Number of bytes of URI args at *zUri */\n\n  /* Figure out how much space is required for each journal file-handle\n  ** (there are two of them, the main journal and the sub-journal). This\n  ** is the maximum space required for an in-memory journal file handle \n  ** and a regular journal file-handle. Note that a \"regular journal-handle\"\n  ** may be a wrapper capable of caching the first portion of the journal\n  ** file in memory to implement the atomic-write optimization (see \n  ** source file journal.c).\n  */\n  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){\n    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));\n  }else{\n    journalFileSize = ROUND8(sqlite3MemJournalSize());\n  }\n\n  /* Set the output variable to NULL in case an error occurs. */\n  *ppPager = 0;\n\n#ifndef SQLITE_OMIT_MEMORYDB\n  if( flags & PAGER_MEMORY ){\n    memDb = 1;\n    if( zFilename && zFilename[0] ){\n      zPathname = sqlite3DbStrDup(0, zFilename);\n      if( zPathname==0  ) return SQLITE_NOMEM;\n      nPathname = sqlite3Strlen30(zPathname);\n      zFilename = 0;\n    }\n  }\n#endif\n\n  /* Compute and store the full pathname in an allocated buffer pointed\n  ** to by zPathname, length nPathname. Or, if this is a temporary file,\n  ** leave both nPathname and zPathname set to 0.\n  */\n  if( zFilename && zFilename[0] ){\n    const char *z;\n    nPathname = pVfs->mxPathname+1;\n    zPathname = sqlite3DbMallocRaw(0, nPathname*2);\n    if( zPathname==0 ){\n      return SQLITE_NOMEM;\n    }\n    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */\n    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);\n    nPathname = sqlite3Strlen30(zPathname);\n    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];\n    while( *z ){\n      z += sqlite3Strlen30(z)+1;\n      z += sqlite3Strlen30(z)+1;\n    }\n    nUri = (int)(&z[1] - zUri);\n    assert( nUri>=0 );\n    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){\n      /* This branch is taken when the journal path required by\n      ** the database being opened will be more than pVfs->mxPathname\n      ** bytes in length. This means the database cannot be opened,\n      ** as it will not be possible to open the journal file or even\n      ** check for a hot-journal before reading.\n      */\n      rc = SQLITE_CANTOPEN_BKPT;\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(0, zPathname);\n      return rc;\n    }\n  }\n\n  /* Allocate memory for the Pager structure, PCache object, the\n  ** three file descriptors, the database file name and the journal \n  ** file name. The layout in memory is as follows:\n  **\n  **     Pager object                    (sizeof(Pager) bytes)\n  **     PCache object                   (sqlite3PcacheSize() bytes)\n  **     Database file handle            (pVfs->szOsFile bytes)\n  **     Sub-journal file handle         (journalFileSize bytes)\n  **     Main journal file handle        (journalFileSize bytes)\n  **     Database file name              (nPathname+1 bytes)\n  **     Journal file name               (nPathname+8+1 bytes)\n  */\n  pPtr = (u8 *)sqlite3MallocZero(\n    ROUND8(sizeof(*pPager)) +      /* Pager structure */\n    ROUND8(pcacheSize) +           /* PCache object */\n    ROUND8(pVfs->szOsFile) +       /* The main db file */\n    journalFileSize * 2 +          /* The two journal files */ \n    nPathname + 1 + nUri +         /* zFilename */\n    nPathname + 8 + 2              /* zJournal */\n#ifndef SQLITE_OMIT_WAL\n    + nPathname + 4 + 2            /* zWal */\n#endif\n  );\n  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );\n  if( !pPtr ){\n    sqlite3DbFree(0, zPathname);\n    return SQLITE_NOMEM;\n  }\n  pPager =              (Pager*)(pPtr);\n  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));\n  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));\n  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));\n  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);\n  pPager->zFilename =    (char*)(pPtr += journalFileSize);\n  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );\n\n  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */\n  if( zPathname ){\n    assert( nPathname>0 );\n    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);\n    memcpy(pPager->zFilename, zPathname, nPathname);\n    if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);\n    memcpy(pPager->zJournal, zPathname, nPathname);\n    memcpy(&pPager->zJournal[nPathname], \"-journal\\000\", 8+1);\n    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);\n#ifndef SQLITE_OMIT_WAL\n    pPager->zWal = &pPager->zJournal[nPathname+8+1];\n    memcpy(pPager->zWal, zPathname, nPathname);\n    memcpy(&pPager->zWal[nPathname], \"-wal\\000\", 4+1);\n    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);\n#endif\n    sqlite3DbFree(0, zPathname);\n  }\n  pPager->pVfs = pVfs;\n  pPager->vfsFlags = vfsFlags;\n\n  /* Open the pager file.\n  */\n  if( zFilename && zFilename[0] ){\n    int fout = 0;                    /* VFS flags returned by xOpen() */\n    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);\n    assert( !memDb );\n    readOnly = (fout&SQLITE_OPEN_READONLY);\n\n    /* If the file was successfully opened for read/write access,\n    ** choose a default page size in case we have to create the\n    ** database file. The default page size is the maximum of:\n    **\n    **    + SQLITE_DEFAULT_PAGE_SIZE,\n    **    + The value returned by sqlite3OsSectorSize()\n    **    + The largest page size that can be written atomically.\n    */\n    if( rc==SQLITE_OK && !readOnly ){\n      setSectorSize(pPager);\n      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);\n      if( szPageDflt<pPager->sectorSize ){\n        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){\n          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;\n        }else{\n          szPageDflt = (u32)pPager->sectorSize;\n        }\n      }\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n      {\n        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);\n        int ii;\n        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));\n        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));\n        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);\n        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){\n          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){\n            szPageDflt = ii;\n          }\n        }\n      }\n#endif\n    }\n  }else{\n    /* If a temporary file is requested, it is not opened immediately.\n    ** In this case we accept the default page size and delay actually\n    ** opening the file until the first call to OsWrite().\n    **\n    ** This branch is also run for an in-memory database. An in-memory\n    ** database is the same as a temp-file that is never written out to\n    ** disk and uses an in-memory rollback journal.\n    */ \n    tempFile = 1;\n    pPager->eState = PAGER_READER;\n    pPager->eLock = EXCLUSIVE_LOCK;\n    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);\n  }\n\n  /* The following call to PagerSetPagesize() serves to set the value of \n  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.\n  */\n  if( rc==SQLITE_OK ){\n    assert( pPager->memDb==0 );\n    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);\n    testcase( rc!=SQLITE_OK );\n  }\n\n  /* If an error occurred in either of the blocks above, free the \n  ** Pager structure and close the file.\n  */\n  if( rc!=SQLITE_OK ){\n    assert( !pPager->pTmpSpace );\n    sqlite3OsClose(pPager->fd);\n    sqlite3_free(pPager);\n    return rc;\n  }\n\n  /* Initialize the PCache object. */\n  assert( nExtra<1000 );\n  nExtra = ROUND8(nExtra);\n  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,\n                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);\n\n  PAGERTRACE((\"OPEN %d %s\\n\", FILEHANDLEID(pPager->fd), pPager->zFilename));\n  IOTRACE((\"OPEN %p %s\\n\", pPager, pPager->zFilename))\n\n  pPager->useJournal = (u8)useJournal;\n  /* pPager->stmtOpen = 0; */\n  /* pPager->stmtInUse = 0; */\n  /* pPager->nRef = 0; */\n  /* pPager->stmtSize = 0; */\n  /* pPager->stmtJSize = 0; */\n  /* pPager->nPage = 0; */\n  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;\n  /* pPager->state = PAGER_UNLOCK; */\n#if 0\n  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );\n#endif\n  /* pPager->errMask = 0; */\n  pPager->tempFile = (u8)tempFile;\n  assert( tempFile==PAGER_LOCKINGMODE_NORMAL \n          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );\n  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );\n  pPager->exclusiveMode = (u8)tempFile; \n  pPager->changeCountDone = pPager->tempFile;\n  pPager->memDb = (u8)memDb;\n  pPager->readOnly = (u8)readOnly;\n  assert( useJournal || pPager->tempFile );\n  pPager->noSync = pPager->tempFile;\n  if( pPager->noSync ){\n    assert( pPager->fullSync==0 );\n    assert( pPager->syncFlags==0 );\n    assert( pPager->walSyncFlags==0 );\n    assert( pPager->ckptSyncFlags==0 );\n  }else{\n    pPager->fullSync = 1;\n    pPager->syncFlags = SQLITE_SYNC_NORMAL;\n    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;\n    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;\n  }\n  /* pPager->pFirst = 0; */\n  /* pPager->pFirstSynced = 0; */\n  /* pPager->pLast = 0; */\n  pPager->nExtra = (u16)nExtra;\n  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;\n  assert( isOpen(pPager->fd) || tempFile );\n  setSectorSize(pPager);\n  if( !useJournal ){\n    pPager->journalMode = PAGER_JOURNALMODE_OFF;\n  }else if( memDb ){\n    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;\n  }\n  /* pPager->xBusyHandler = 0; */\n  /* pPager->pBusyHandlerArg = 0; */\n  pPager->xReiniter = xReinit;\n  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */\n\n  *ppPager = pPager;\n  return SQLITE_OK;\n}\n\n\n\n/*\n** This function is called after transitioning from PAGER_UNLOCK to\n** PAGER_SHARED state. It tests if there is a hot journal present in\n** the file-system for the given pager. A hot journal is one that \n** needs to be played back. According to this function, a hot-journal\n** file exists if the following criteria are met:\n**\n**   * The journal file exists in the file system, and\n**   * No process holds a RESERVED or greater lock on the database file, and\n**   * The database file itself is greater than 0 bytes in size, and\n**   * The first byte of the journal file exists and is not 0x00.\n**\n** If the current size of the database file is 0 but a journal file\n** exists, that is probably an old journal left over from a prior\n** database with the same name. In this case the journal file is\n** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK\n** is returned.\n**\n** This routine does not check if there is a master journal filename\n** at the end of the file. If there is, and that master journal file\n** does not exist, then the journal file is not really hot. In this\n** case this routine will return a false-positive. The pager_playback()\n** routine will discover that the journal file is not really hot and \n** will not roll it back. \n**\n** If a hot-journal file is found to exist, *pExists is set to 1 and \n** SQLITE_OK returned. If no hot-journal file is present, *pExists is\n** set to 0 and SQLITE_OK returned. If an IO error occurs while trying\n** to determine whether or not a hot-journal file exists, the IO error\n** code is returned and the value of *pExists is undefined.\n*/\nstatic int hasHotJournal(Pager *pPager, int *pExists){\n  sqlite3_vfs * const pVfs = pPager->pVfs;\n  int rc = SQLITE_OK;           /* Return code */\n  int exists = 1;               /* True if a journal file is present */\n  int jrnlOpen = !!isOpen(pPager->jfd);\n\n  assert( pPager->useJournal );\n  assert( isOpen(pPager->fd) );\n  assert( pPager->eState==PAGER_OPEN );\n\n  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &\n    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN\n  ));\n\n  *pExists = 0;\n  if( !jrnlOpen ){\n    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);\n  }\n  if( rc==SQLITE_OK && exists ){\n    int locked = 0;             /* True if some process holds a RESERVED lock */\n\n    /* Race condition here:  Another process might have been holding the\n    ** the RESERVED lock and have a journal open at the sqlite3OsAccess() \n    ** call above, but then delete the journal and drop the lock before\n    ** we get to the following sqlite3OsCheckReservedLock() call.  If that\n    ** is the case, this routine might think there is a hot journal when\n    ** in fact there is none.  This results in a false-positive which will\n    ** be dealt with by the playback routine.  Ticket #3883.\n    */\n    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);\n    if( rc==SQLITE_OK && !locked ){\n      Pgno nPage;                 /* Number of pages in database file */\n\n      /* Check the size of the database file. If it consists of 0 pages,\n      ** then delete the journal file. See the header comment above for \n      ** the reasoning here.  Delete the obsolete journal file under\n      ** a RESERVED lock to avoid race conditions and to avoid violating\n      ** [H33020].\n      */\n      rc = pagerPagecount(pPager, &nPage);\n      if( rc==SQLITE_OK ){\n        if( nPage==0 ){\n          sqlite3BeginBenignMalloc();\n          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){\n            sqlite3OsDelete(pVfs, pPager->zJournal, 0);\n            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);\n          }\n          sqlite3EndBenignMalloc();\n        }else{\n          /* The journal file exists and no other connection has a reserved\n          ** or greater lock on the database file. Now check that there is\n          ** at least one non-zero bytes at the start of the journal file.\n          ** If there is, then we consider this journal to be hot. If not, \n          ** it can be ignored.\n          */\n          if( !jrnlOpen ){\n            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;\n            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);\n          }\n          if( rc==SQLITE_OK ){\n            u8 first = 0;\n            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);\n            if( rc==SQLITE_IOERR_SHORT_READ ){\n              rc = SQLITE_OK;\n            }\n            if( !jrnlOpen ){\n              sqlite3OsClose(pPager->jfd);\n            }\n            *pExists = (first!=0);\n          }else if( rc==SQLITE_CANTOPEN ){\n            /* If we cannot open the rollback journal file in order to see if\n            ** its has a zero header, that might be due to an I/O error, or\n            ** it might be due to the race condition described above and in\n            ** ticket #3883.  Either way, assume that the journal is hot.\n            ** This might be a false positive.  But if it is, then the\n            ** automatic journal playback and recovery mechanism will deal\n            ** with it under an EXCLUSIVE lock where we do not need to\n            ** worry so much with race conditions.\n            */\n            *pExists = 1;\n            rc = SQLITE_OK;\n          }\n        }\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to obtain a shared lock on the database file.\n** It is illegal to call sqlite3PagerAcquire() until after this function\n** has been successfully called. If a shared-lock is already held when\n** this function is called, it is a no-op.\n**\n** The following operations are also performed by this function.\n**\n**   1) If the pager is currently in PAGER_OPEN state (no lock held\n**      on the database file), then an attempt is made to obtain a\n**      SHARED lock on the database file. Immediately after obtaining\n**      the SHARED lock, the file-system is checked for a hot-journal,\n**      which is played back if present. Following any hot-journal \n**      rollback, the contents of the cache are validated by checking\n**      the 'change-counter' field of the database file header and\n**      discarded if they are found to be invalid.\n**\n**   2) If the pager is running in exclusive-mode, and there are currently\n**      no outstanding references to any pages, and is in the error state,\n**      then an attempt is made to clear the error state by discarding\n**      the contents of the page cache and rolling back any open journal\n**      file.\n**\n** If everything is successful, SQLITE_OK is returned. If an IO error \n** occurs while locking the database, checking for a hot-journal file or \n** rolling back a journal file, the IO error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){\n  int rc = SQLITE_OK;                /* Return code */\n\n  /* This routine is only called from b-tree and only when there are no\n  ** outstanding pages. This implies that the pager state should either\n  ** be OPEN or READER. READER is only possible if the pager is or was in \n  ** exclusive access mode.\n  */\n  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );\n  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }\n\n  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){\n    int bHotJournal = 1;          /* True if there exists a hot journal-file */\n\n    assert( !MEMDB );\n\n    rc = pager_wait_on_lock(pPager, SHARED_LOCK);\n    if( rc!=SQLITE_OK ){\n      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );\n      goto failed;\n    }\n\n    /* If a journal file exists, and there is no RESERVED lock on the\n    ** database file, then it either needs to be played back or deleted.\n    */\n    if( pPager->eLock<=SHARED_LOCK ){\n      rc = hasHotJournal(pPager, &bHotJournal);\n    }\n    if( rc!=SQLITE_OK ){\n      goto failed;\n    }\n    if( bHotJournal ){\n      /* Get an EXCLUSIVE lock on the database file. At this point it is\n      ** important that a RESERVED lock is not obtained on the way to the\n      ** EXCLUSIVE lock. If it were, another process might open the\n      ** database file, detect the RESERVED lock, and conclude that the\n      ** database is safe to read while this process is still rolling the \n      ** hot-journal back.\n      ** \n      ** Because the intermediate RESERVED lock is not requested, any\n      ** other process attempting to access the database file will get to \n      ** this point in the code and fail to obtain its own EXCLUSIVE lock \n      ** on the database file.\n      **\n      ** Unless the pager is in locking_mode=exclusive mode, the lock is\n      ** downgraded to SHARED_LOCK before this function returns.\n      */\n      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n      if( rc!=SQLITE_OK ){\n        goto failed;\n      }\n \n      /* If it is not already open and the file exists on disk, open the \n      ** journal for read/write access. Write access is required because \n      ** in exclusive-access mode the file descriptor will be kept open \n      ** and possibly used for a transaction later on. Also, write-access \n      ** is usually required to finalize the journal in journal_mode=persist \n      ** mode (and also for journal_mode=truncate on some systems).\n      **\n      ** If the journal does not exist, it usually means that some \n      ** other connection managed to get in and roll it back before \n      ** this connection obtained the exclusive lock above. Or, it \n      ** may mean that the pager was in the error-state when this\n      ** function was called and the journal file does not exist.\n      */\n      if( !isOpen(pPager->jfd) ){\n        sqlite3_vfs * const pVfs = pPager->pVfs;\n        int bExists;              /* True if journal file exists */\n        rc = sqlite3OsAccess(\n            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);\n        if( rc==SQLITE_OK && bExists ){\n          int fout = 0;\n          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;\n          assert( !pPager->tempFile );\n          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);\n          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );\n          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){\n            rc = SQLITE_CANTOPEN_BKPT;\n            sqlite3OsClose(pPager->jfd);\n          }\n        }\n      }\n \n      /* Playback and delete the journal.  Drop the database write\n      ** lock and reacquire the read lock. Purge the cache before\n      ** playing back the hot-journal so that we don't end up with\n      ** an inconsistent cache.  Sync the hot journal before playing\n      ** it back since the process that crashed and left the hot journal\n      ** probably did not sync it and we are required to always sync\n      ** the journal before playing it back.\n      */\n      if( isOpen(pPager->jfd) ){\n        assert( rc==SQLITE_OK );\n        rc = pagerSyncHotJournal(pPager);\n        if( rc==SQLITE_OK ){\n          rc = pager_playback(pPager, 1);\n          pPager->eState = PAGER_OPEN;\n        }\n      }else if( !pPager->exclusiveMode ){\n        pagerUnlockDb(pPager, SHARED_LOCK);\n      }\n\n      if( rc!=SQLITE_OK ){\n        /* This branch is taken if an error occurs while trying to open\n        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The\n        ** pager_unlock() routine will be called before returning to unlock\n        ** the file. If the unlock attempt fails, then Pager.eLock must be\n        ** set to UNKNOWN_LOCK (see the comment above the #define for \n        ** UNKNOWN_LOCK above for an explanation). \n        **\n        ** In order to get pager_unlock() to do this, set Pager.eState to\n        ** PAGER_ERROR now. This is not actually counted as a transition\n        ** to ERROR state in the state diagram at the top of this file,\n        ** since we know that the same call to pager_unlock() will very\n        ** shortly transition the pager object to the OPEN state. Calling\n        ** assert_pager_state() would fail now, as it should not be possible\n        ** to be in ERROR state when there are zero outstanding page \n        ** references.\n        */\n        pager_error(pPager, rc);\n        goto failed;\n      }\n\n      assert( pPager->eState==PAGER_OPEN );\n      assert( (pPager->eLock==SHARED_LOCK)\n           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)\n      );\n    }\n\n    if( !pPager->tempFile \n     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0) \n    ){\n      /* The shared-lock has just been acquired on the database file\n      ** and there are already pages in the cache (from a previous\n      ** read or write transaction).  Check to see if the database\n      ** has been modified.  If the database has changed, flush the\n      ** cache.\n      **\n      ** Database changes is detected by looking at 15 bytes beginning\n      ** at offset 24 into the file.  The first 4 of these 16 bytes are\n      ** a 32-bit counter that is incremented with each change.  The\n      ** other bytes change randomly with each file change when\n      ** a codec is in use.\n      ** \n      ** There is a vanishingly small chance that a change will not be \n      ** detected.  The chance of an undetected change is so small that\n      ** it can be neglected.\n      */\n      Pgno nPage = 0;\n      char dbFileVers[sizeof(pPager->dbFileVers)];\n\n      rc = pagerPagecount(pPager, &nPage);\n      if( rc ) goto failed;\n\n      if( nPage>0 ){\n        IOTRACE((\"CKVERS %p %d\\n\", pPager, sizeof(dbFileVers)));\n        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);\n        if( rc!=SQLITE_OK ){\n          goto failed;\n        }\n      }else{\n        memset(dbFileVers, 0, sizeof(dbFileVers));\n      }\n\n      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){\n        pager_reset(pPager);\n      }\n    }\n\n    /* If there is a WAL file in the file-system, open this database in WAL\n    ** mode. Otherwise, the following function call is a no-op.\n    */\n    rc = pagerOpenWalIfPresent(pPager);\n#ifndef SQLITE_OMIT_WAL\n    assert( pPager->pWal==0 || rc==SQLITE_OK );\n#endif\n  }\n\n  if( pagerUseWal(pPager) ){\n    assert( rc==SQLITE_OK );\n    rc = pagerBeginReadTransaction(pPager);\n  }\n\n  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){\n    rc = pagerPagecount(pPager, &pPager->dbSize);\n  }\n\n failed:\n  if( rc!=SQLITE_OK ){\n    assert( !MEMDB );\n    pager_unlock(pPager);\n    assert( pPager->eState==PAGER_OPEN );\n  }else{\n    pPager->eState = PAGER_READER;\n  }\n  return rc;\n}\n\n/*\n** If the reference count has reached zero, rollback any active\n** transaction and unlock the pager.\n**\n** Except, in locking_mode=EXCLUSIVE when there is nothing to in\n** the rollback journal, the unlock is not performed and there is\n** nothing to rollback, so this routine is a no-op.\n*/ \nstatic void pagerUnlockIfUnused(Pager *pPager){\n  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){\n    pagerUnlockAndRollback(pPager);\n  }\n}\n\n/*\n** Acquire a reference to page number pgno in pager pPager (a page\n** reference has type DbPage*). If the requested reference is \n** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.\n**\n** If the requested page is already in the cache, it is returned. \n** Otherwise, a new page object is allocated and populated with data\n** read from the database file. In some cases, the pcache module may\n** choose not to allocate a new page object and may reuse an existing\n** object with no outstanding references.\n**\n** The extra data appended to a page is always initialized to zeros the \n** first time a page is loaded into memory. If the page requested is \n** already in the cache when this function is called, then the extra\n** data is left as it was when the page object was last used.\n**\n** If the database image is smaller than the requested page or if a \n** non-zero value is passed as the noContent parameter and the \n** requested page is not already stored in the cache, then no \n** actual disk read occurs. In this case the memory image of the \n** page is initialized to all zeros. \n**\n** If noContent is true, it means that we do not care about the contents\n** of the page. This occurs in two seperate scenarios:\n**\n**   a) When reading a free-list leaf page from the database, and\n**\n**   b) When a savepoint is being rolled back and we need to load\n**      a new page into the cache to be filled with the data read\n**      from the savepoint journal.\n**\n** If noContent is true, then the data returned is zeroed instead of\n** being read from the database. Additionally, the bits corresponding\n** to pgno in Pager.pInJournal (bitvec of pages already written to the\n** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open\n** savepoints are set. This means if the page is made writable at any\n** point in the future, using a call to sqlite3PagerWrite(), its contents\n** will not be journaled. This saves IO.\n**\n** The acquisition might fail for several reasons.  In all cases,\n** an appropriate error code is returned and *ppPage is set to NULL.\n**\n** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt\n** to find a page in the in-memory cache first.  If the page is not already\n** in memory, this routine goes to disk to read it in whereas Lookup()\n** just returns 0.  This routine acquires a read-lock the first time it\n** has to go to disk, and could also playback an old journal if necessary.\n** Since Lookup() never goes to disk, it never has to deal with locks\n** or journal files.\n*/\nSQLITE_PRIVATE int sqlite3PagerAcquire(\n  Pager *pPager,      /* The pager open on the database file */\n  Pgno pgno,          /* Page number to fetch */\n  DbPage **ppPage,    /* Write a pointer to the page here */\n  int noContent       /* Do not bother reading content from disk if true */\n){\n  int rc;\n  PgHdr *pPg;\n\n  assert( pPager->eState>=PAGER_READER );\n  assert( assert_pager_state(pPager) );\n\n  if( pgno==0 ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n\n  /* If the pager is in the error state, return an error immediately. \n  ** Otherwise, request the page from the PCache layer. */\n  if( pPager->errCode!=SQLITE_OK ){\n    rc = pPager->errCode;\n  }else{\n    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);\n  }\n\n  if( rc!=SQLITE_OK ){\n    /* Either the call to sqlite3PcacheFetch() returned an error or the\n    ** pager was already in the error-state when this function was called.\n    ** Set pPg to 0 and jump to the exception handler.  */\n    pPg = 0;\n    goto pager_acquire_err;\n  }\n  assert( (*ppPage)->pgno==pgno );\n  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );\n\n  if( (*ppPage)->pPager && !noContent ){\n    /* In this case the pcache already contains an initialized copy of\n    ** the page. Return without further ado.  */\n    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );\n    pPager->aStat[PAGER_STAT_HIT]++;\n    return SQLITE_OK;\n\n  }else{\n    /* The pager cache has created a new page. Its content needs to \n    ** be initialized.  */\n\n    pPg = *ppPage;\n    pPg->pPager = pPager;\n\n    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page\n    ** number greater than this, or the unused locking-page, is requested. */\n    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto pager_acquire_err;\n    }\n\n    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){\n      if( pgno>pPager->mxPgno ){\n        rc = SQLITE_FULL;\n        goto pager_acquire_err;\n      }\n      if( noContent ){\n        /* Failure to set the bits in the InJournal bit-vectors is benign.\n        ** It merely means that we might do some extra work to journal a \n        ** page that does not need to be journaled.  Nevertheless, be sure \n        ** to test the case where a malloc error occurs while trying to set \n        ** a bit in a bit vector.\n        */\n        sqlite3BeginBenignMalloc();\n        if( pgno<=pPager->dbOrigSize ){\n          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);\n          testcase( rc==SQLITE_NOMEM );\n        }\n        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);\n        testcase( rc==SQLITE_NOMEM );\n        sqlite3EndBenignMalloc();\n      }\n      memset(pPg->pData, 0, pPager->pageSize);\n      IOTRACE((\"ZERO %p %d\\n\", pPager, pgno));\n    }else{\n      assert( pPg->pPager==pPager );\n      pPager->aStat[PAGER_STAT_MISS]++;\n      rc = readDbPage(pPg);\n      if( rc!=SQLITE_OK ){\n        goto pager_acquire_err;\n      }\n    }\n    pager_set_pagehash(pPg);\n  }\n\n  return SQLITE_OK;\n\npager_acquire_err:\n  assert( rc!=SQLITE_OK );\n  if( pPg ){\n    sqlite3PcacheDrop(pPg);\n  }\n  pagerUnlockIfUnused(pPager);\n\n  *ppPage = 0;\n  return rc;\n}\n\n/*\n** Acquire a page if it is already in the in-memory cache.  Do\n** not read the page from disk.  Return a pointer to the page,\n** or 0 if the page is not in cache. \n**\n** See also sqlite3PagerGet().  The difference between this routine\n** and sqlite3PagerGet() is that _get() will go to the disk and read\n** in the page if the page is not already in cache.  This routine\n** returns NULL if the page is not in cache or if a disk I/O error \n** has ever happened.\n*/\nSQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){\n  PgHdr *pPg = 0;\n  assert( pPager!=0 );\n  assert( pgno!=0 );\n  assert( pPager->pPCache!=0 );\n  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );\n  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);\n  return pPg;\n}\n\n/*\n** Release a page reference.\n**\n** If the number of references to the page drop to zero, then the\n** page is added to the LRU list.  When all references to all pages\n** are released, a rollback occurs and the lock on the database is\n** removed.\n*/\nSQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){\n  if( pPg ){\n    Pager *pPager = pPg->pPager;\n    sqlite3PcacheRelease(pPg);\n    pagerUnlockIfUnused(pPager);\n  }\n}\n\n/*\n** This function is called at the start of every write transaction.\n** There must already be a RESERVED or EXCLUSIVE lock on the database \n** file when this routine is called.\n**\n** Open the journal file for pager pPager and write a journal header\n** to the start of it. If there are active savepoints, open the sub-journal\n** as well. This function is only used when the journal file is being \n** opened to write a rollback log for a transaction. It is not used \n** when opening a hot journal file to roll it back.\n**\n** If the journal file is already open (as it may be in exclusive mode),\n** then this function just writes a journal header to the start of the\n** already open file. \n**\n** Whether or not the journal file is opened by this function, the\n** Pager.pInJournal bitvec structure is allocated.\n**\n** Return SQLITE_OK if everything is successful. Otherwise, return \n** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or \n** an IO error code if opening or writing the journal file fails.\n*/\nstatic int pager_open_journal(Pager *pPager){\n  int rc = SQLITE_OK;                        /* Return code */\n  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n  assert( pPager->pInJournal==0 );\n  \n  /* If already in the error state, this function is a no-op.  But on\n  ** the other hand, this routine is never called if we are already in\n  ** an error state. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n\n  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){\n    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);\n    if( pPager->pInJournal==0 ){\n      return SQLITE_NOMEM;\n    }\n  \n    /* Open the journal file if it is not already open. */\n    if( !isOpen(pPager->jfd) ){\n      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){\n        sqlite3MemJournalOpen(pPager->jfd);\n      }else{\n        const int flags =                   /* VFS flags to open journal file */\n          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|\n          (pPager->tempFile ? \n            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):\n            (SQLITE_OPEN_MAIN_JOURNAL)\n          );\n  #ifdef SQLITE_ENABLE_ATOMIC_WRITE\n        rc = sqlite3JournalOpen(\n            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)\n        );\n  #else\n        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);\n  #endif\n      }\n      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );\n    }\n  \n  \n    /* Write the first journal header to the journal file and open \n    ** the sub-journal if necessary.\n    */\n    if( rc==SQLITE_OK ){\n      /* TODO: Check if all of these are really required. */\n      pPager->nRec = 0;\n      pPager->journalOff = 0;\n      pPager->setMaster = 0;\n      pPager->journalHdr = 0;\n      rc = writeJournalHdr(pPager);\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    sqlite3BitvecDestroy(pPager->pInJournal);\n    pPager->pInJournal = 0;\n  }else{\n    assert( pPager->eState==PAGER_WRITER_LOCKED );\n    pPager->eState = PAGER_WRITER_CACHEMOD;\n  }\n\n  return rc;\n}\n\n/*\n** Begin a write-transaction on the specified pager object. If a \n** write-transaction has already been opened, this function is a no-op.\n**\n** If the exFlag argument is false, then acquire at least a RESERVED\n** lock on the database file. If exFlag is true, then acquire at least\n** an EXCLUSIVE lock. If such a lock is already held, no locking \n** functions need be called.\n**\n** If the subjInMemory argument is non-zero, then any sub-journal opened\n** within this transaction will be opened as an in-memory file. This\n** has no effect if the sub-journal is already opened (as it may be when\n** running in exclusive mode) or if the transaction does not require a\n** sub-journal. If the subjInMemory argument is zero, then any required\n** sub-journal is implemented in-memory if pPager is an in-memory database, \n** or using a temporary file otherwise.\n*/\nSQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){\n  int rc = SQLITE_OK;\n\n  if( pPager->errCode ) return pPager->errCode;\n  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );\n  pPager->subjInMemory = (u8)subjInMemory;\n\n  if( ALWAYS(pPager->eState==PAGER_READER) ){\n    assert( pPager->pInJournal==0 );\n\n    if( pagerUseWal(pPager) ){\n      /* If the pager is configured to use locking_mode=exclusive, and an\n      ** exclusive lock on the database is not already held, obtain it now.\n      */\n      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){\n        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        sqlite3WalExclusiveMode(pPager->pWal, 1);\n      }\n\n      /* Grab the write lock on the log file. If successful, upgrade to\n      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.\n      ** The busy-handler is not invoked if another connection already\n      ** holds the write-lock. If possible, the upper layer will call it.\n      */\n      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);\n    }else{\n      /* Obtain a RESERVED lock on the database file. If the exFlag parameter\n      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The\n      ** busy-handler callback can be used when upgrading to the EXCLUSIVE\n      ** lock, but not when obtaining the RESERVED lock.\n      */\n      rc = pagerLockDb(pPager, RESERVED_LOCK);\n      if( rc==SQLITE_OK && exFlag ){\n        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);\n      }\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Change to WRITER_LOCKED state.\n      **\n      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD\n      ** when it has an open transaction, but never to DBMOD or FINISHED.\n      ** This is because in those states the code to roll back savepoint \n      ** transactions may copy data from the sub-journal into the database \n      ** file as well as into the page cache. Which would be incorrect in \n      ** WAL mode.\n      */\n      pPager->eState = PAGER_WRITER_LOCKED;\n      pPager->dbHintSize = pPager->dbSize;\n      pPager->dbFileSize = pPager->dbSize;\n      pPager->dbOrigSize = pPager->dbSize;\n      pPager->journalOff = 0;\n    }\n\n    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );\n    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );\n    assert( assert_pager_state(pPager) );\n  }\n\n  PAGERTRACE((\"TRANSACTION %d\\n\", PAGERID(pPager)));\n  return rc;\n}\n\n/*\n** Mark a single data page as writeable. The page is written into the \n** main journal or sub-journal as required. If the page is written into\n** one of the journals, the corresponding bit is set in the \n** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs\n** of any open savepoints as appropriate.\n*/\nstatic int pager_write(PgHdr *pPg){\n  void *pData = pPg->pData;\n  Pager *pPager = pPg->pPager;\n  int rc = SQLITE_OK;\n\n  /* This routine is not called unless a write-transaction has already \n  ** been started. The journal file may or may not be open at this point.\n  ** It is never called in the ERROR state.\n  */\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* If an error has been previously detected, report the same error\n  ** again. This should not happen, but the check provides robustness. */\n  if( NEVER(pPager->errCode) )  return pPager->errCode;\n\n  /* Higher-level routines never call this function if database is not\n  ** writable.  But check anyway, just for robustness. */\n  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;\n\n  CHECK_PAGE(pPg);\n\n  /* The journal file needs to be opened. Higher level routines have already\n  ** obtained the necessary locks to begin the write-transaction, but the\n  ** rollback journal might not yet be open. Open it now if this is the case.\n  **\n  ** This is done before calling sqlite3PcacheMakeDirty() on the page. \n  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then\n  ** an error might occur and the pager would end up in WRITER_LOCKED state\n  ** with pages marked as dirty in the cache.\n  */\n  if( pPager->eState==PAGER_WRITER_LOCKED ){\n    rc = pager_open_journal(pPager);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );\n  assert( assert_pager_state(pPager) );\n\n  /* Mark the page as dirty.  If the page has already been written\n  ** to the journal then we can return right away.\n  */\n  sqlite3PcacheMakeDirty(pPg);\n  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){\n    assert( !pagerUseWal(pPager) );\n  }else{\n  \n    /* The transaction journal now exists and we have a RESERVED or an\n    ** EXCLUSIVE lock on the main database file.  Write the current page to\n    ** the transaction journal if it is not there already.\n    */\n    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){\n      assert( pagerUseWal(pPager)==0 );\n      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){\n        u32 cksum;\n        char *pData2;\n        i64 iOff = pPager->journalOff;\n\n        /* We should never write to the journal file the page that\n        ** contains the database locks.  The following assert verifies\n        ** that we do not. */\n        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );\n\n        assert( pPager->journalHdr<=pPager->journalOff );\n        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);\n        cksum = pager_cksum(pPager, (u8*)pData2);\n\n        /* Even if an IO or diskfull error occurs while journalling the\n        ** page in the block above, set the need-sync flag for the page.\n        ** Otherwise, when the transaction is rolled back, the logic in\n        ** playback_one_page() will think that the page needs to be restored\n        ** in the database file. And if an IO error occurs while doing so,\n        ** then corruption may follow.\n        */\n        pPg->flags |= PGHDR_NEED_SYNC;\n\n        rc = write32bits(pPager->jfd, iOff, pPg->pgno);\n        if( rc!=SQLITE_OK ) return rc;\n        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);\n        if( rc!=SQLITE_OK ) return rc;\n        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);\n        if( rc!=SQLITE_OK ) return rc;\n\n        IOTRACE((\"JOUT %p %d %lld %d\\n\", pPager, pPg->pgno, \n                 pPager->journalOff, pPager->pageSize));\n        PAGER_INCR(sqlite3_pager_writej_count);\n        PAGERTRACE((\"JOURNAL %d page %d needSync=%d hash(%08x)\\n\",\n             PAGERID(pPager), pPg->pgno, \n             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));\n\n        pPager->journalOff += 8 + pPager->pageSize;\n        pPager->nRec++;\n        assert( pPager->pInJournal!=0 );\n        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);\n        testcase( rc==SQLITE_NOMEM );\n        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );\n        rc |= addToSavepointBitvecs(pPager, pPg->pgno);\n        if( rc!=SQLITE_OK ){\n          assert( rc==SQLITE_NOMEM );\n          return rc;\n        }\n      }else{\n        if( pPager->eState!=PAGER_WRITER_DBMOD ){\n          pPg->flags |= PGHDR_NEED_SYNC;\n        }\n        PAGERTRACE((\"APPEND %d page %d needSync=%d\\n\",\n                PAGERID(pPager), pPg->pgno,\n               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));\n      }\n    }\n  \n    /* If the statement journal is open and the page is not in it,\n    ** then write the current page to the statement journal.  Note that\n    ** the statement journal format differs from the standard journal format\n    ** in that it omits the checksums and the header.\n    */\n    if( subjRequiresPage(pPg) ){\n      rc = subjournalPage(pPg);\n    }\n  }\n\n  /* Update the database size and return.\n  */\n  if( pPager->dbSize<pPg->pgno ){\n    pPager->dbSize = pPg->pgno;\n  }\n  return rc;\n}\n\n/*\n** Mark a data page as writeable. This routine must be called before \n** making changes to a page. The caller must check the return value \n** of this function and be careful not to change any page data unless \n** this routine returns SQLITE_OK.\n**\n** The difference between this function and pager_write() is that this\n** function also deals with the special case where 2 or more pages\n** fit on a single disk sector. In this case all co-resident pages\n** must have been written to the journal file before returning.\n**\n** If an error occurs, SQLITE_NOMEM or an IO error code is returned\n** as appropriate. Otherwise, SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){\n  int rc = SQLITE_OK;\n\n  PgHdr *pPg = pDbPage;\n  Pager *pPager = pPg->pPager;\n  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);\n\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n  assert( pPager->eState!=PAGER_ERROR );\n  assert( assert_pager_state(pPager) );\n\n  if( nPagePerSector>1 ){\n    Pgno nPageCount;          /* Total number of pages in database file */\n    Pgno pg1;                 /* First page of the sector pPg is located on. */\n    int nPage = 0;            /* Number of pages starting at pg1 to journal */\n    int ii;                   /* Loop counter */\n    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */\n\n    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow\n    ** a journal header to be written between the pages journaled by\n    ** this function.\n    */\n    assert( !MEMDB );\n    assert( pPager->doNotSyncSpill==0 );\n    pPager->doNotSyncSpill++;\n\n    /* This trick assumes that both the page-size and sector-size are\n    ** an integer power of 2. It sets variable pg1 to the identifier\n    ** of the first page of the sector pPg is located on.\n    */\n    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;\n\n    nPageCount = pPager->dbSize;\n    if( pPg->pgno>nPageCount ){\n      nPage = (pPg->pgno - pg1)+1;\n    }else if( (pg1+nPagePerSector-1)>nPageCount ){\n      nPage = nPageCount+1-pg1;\n    }else{\n      nPage = nPagePerSector;\n    }\n    assert(nPage>0);\n    assert(pg1<=pPg->pgno);\n    assert((pg1+nPage)>pPg->pgno);\n\n    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){\n      Pgno pg = pg1+ii;\n      PgHdr *pPage;\n      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){\n        if( pg!=PAGER_MJ_PGNO(pPager) ){\n          rc = sqlite3PagerGet(pPager, pg, &pPage);\n          if( rc==SQLITE_OK ){\n            rc = pager_write(pPage);\n            if( pPage->flags&PGHDR_NEED_SYNC ){\n              needSync = 1;\n            }\n            sqlite3PagerUnref(pPage);\n          }\n        }\n      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){\n        if( pPage->flags&PGHDR_NEED_SYNC ){\n          needSync = 1;\n        }\n        sqlite3PagerUnref(pPage);\n      }\n    }\n\n    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages \n    ** starting at pg1, then it needs to be set for all of them. Because\n    ** writing to any of these nPage pages may damage the others, the\n    ** journal file must contain sync()ed copies of all of them\n    ** before any of them can be written out to the database file.\n    */\n    if( rc==SQLITE_OK && needSync ){\n      assert( !MEMDB );\n      for(ii=0; ii<nPage; ii++){\n        PgHdr *pPage = pager_lookup(pPager, pg1+ii);\n        if( pPage ){\n          pPage->flags |= PGHDR_NEED_SYNC;\n          sqlite3PagerUnref(pPage);\n        }\n      }\n    }\n\n    assert( pPager->doNotSyncSpill==1 );\n    pPager->doNotSyncSpill--;\n  }else{\n    rc = pager_write(pDbPage);\n  }\n  return rc;\n}\n\n/*\n** Return TRUE if the page given in the argument was previously passed\n** to sqlite3PagerWrite().  In other words, return TRUE if it is ok\n** to change the content of the page.\n*/\n#ifndef NDEBUG\nSQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){\n  return pPg->flags&PGHDR_DIRTY;\n}\n#endif\n\n/*\n** A call to this routine tells the pager that it is not necessary to\n** write the information on page pPg back to the disk, even though\n** that page might be marked as dirty.  This happens, for example, when\n** the page has been added as a leaf of the freelist and so its\n** content no longer matters.\n**\n** The overlying software layer calls this routine when all of the data\n** on the given page is unused. The pager marks the page as clean so\n** that it does not get written to disk.\n**\n** Tests show that this optimization can quadruple the speed of large \n** DELETE operations.\n*/\nSQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){\n  Pager *pPager = pPg->pPager;\n  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){\n    PAGERTRACE((\"DONT_WRITE page %d of %d\\n\", pPg->pgno, PAGERID(pPager)));\n    IOTRACE((\"CLEAN %p %d\\n\", pPager, pPg->pgno))\n    pPg->flags |= PGHDR_DONT_WRITE;\n    pager_set_pagehash(pPg);\n  }\n}\n\n/*\n** This routine is called to increment the value of the database file \n** change-counter, stored as a 4-byte big-endian integer starting at \n** byte offset 24 of the pager file.  The secondary change counter at\n** 92 is also updated, as is the SQLite version number at offset 96.\n**\n** But this only happens if the pPager->changeCountDone flag is false.\n** To avoid excess churning of page 1, the update only happens once.\n** See also the pager_write_changecounter() routine that does an \n** unconditional update of the change counters.\n**\n** If the isDirectMode flag is zero, then this is done by calling \n** sqlite3PagerWrite() on page 1, then modifying the contents of the\n** page data. In this case the file will be updated when the current\n** transaction is committed.\n**\n** The isDirectMode flag may only be non-zero if the library was compiled\n** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,\n** if isDirect is non-zero, then the database file is updated directly\n** by writing an updated version of page 1 using a call to the \n** sqlite3OsWrite() function.\n*/\nstatic int pager_incr_changecounter(Pager *pPager, int isDirectMode){\n  int rc = SQLITE_OK;\n\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* Declare and initialize constant integer 'isDirect'. If the\n  ** atomic-write optimization is enabled in this build, then isDirect\n  ** is initialized to the value passed as the isDirectMode parameter\n  ** to this function. Otherwise, it is always set to zero.\n  **\n  ** The idea is that if the atomic-write optimization is not\n  ** enabled at compile time, the compiler can omit the tests of\n  ** 'isDirect' below, as well as the block enclosed in the\n  ** \"if( isDirect )\" condition.\n  */\n#ifndef SQLITE_ENABLE_ATOMIC_WRITE\n# define DIRECT_MODE 0\n  assert( isDirectMode==0 );\n  UNUSED_PARAMETER(isDirectMode);\n#else\n# define DIRECT_MODE isDirectMode\n#endif\n\n  if( !pPager->changeCountDone && pPager->dbSize>0 ){\n    PgHdr *pPgHdr;                /* Reference to page 1 */\n\n    assert( !pPager->tempFile && isOpen(pPager->fd) );\n\n    /* Open page 1 of the file for writing. */\n    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);\n    assert( pPgHdr==0 || rc==SQLITE_OK );\n\n    /* If page one was fetched successfully, and this function is not\n    ** operating in direct-mode, make page 1 writable.  When not in \n    ** direct mode, page 1 is always held in cache and hence the PagerGet()\n    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.\n    */\n    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){\n      rc = sqlite3PagerWrite(pPgHdr);\n    }\n\n    if( rc==SQLITE_OK ){\n      /* Actually do the update of the change counter */\n      pager_write_changecounter(pPgHdr);\n\n      /* If running in direct mode, write the contents of page 1 to the file. */\n      if( DIRECT_MODE ){\n        const void *zBuf;\n        assert( pPager->dbFileSize>0 );\n        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);\n        if( rc==SQLITE_OK ){\n          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);\n          pPager->aStat[PAGER_STAT_WRITE]++;\n        }\n        if( rc==SQLITE_OK ){\n          pPager->changeCountDone = 1;\n        }\n      }else{\n        pPager->changeCountDone = 1;\n      }\n    }\n\n    /* Release the page reference. */\n    sqlite3PagerUnref(pPgHdr);\n  }\n  return rc;\n}\n\n/*\n** Sync the database file to disk. This is a no-op for in-memory databases\n** or pages with the Pager.noSync flag set.\n**\n** If successful, or if called on a pager for which it is a no-op, this\n** function returns SQLITE_OK. Otherwise, an IO error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){\n  int rc = SQLITE_OK;\n  if( !pPager->noSync ){\n    assert( !MEMDB );\n    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);\n  }else if( isOpen(pPager->fd) ){\n    assert( !MEMDB );\n    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);\n    if( rc==SQLITE_NOTFOUND ){\n      rc = SQLITE_OK;\n    }\n  }\n  return rc;\n}\n\n/*\n** This function may only be called while a write-transaction is active in\n** rollback. If the connection is in WAL mode, this call is a no-op. \n** Otherwise, if the connection does not already have an EXCLUSIVE lock on \n** the database file, an attempt is made to obtain one.\n**\n** If the EXCLUSIVE lock is already held or the attempt to obtain it is\n** successful, or the connection is in WAL mode, SQLITE_OK is returned.\n** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is \n** returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){\n  int rc = SQLITE_OK;\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD \n       || pPager->eState==PAGER_WRITER_DBMOD \n       || pPager->eState==PAGER_WRITER_LOCKED \n  );\n  assert( assert_pager_state(pPager) );\n  if( 0==pagerUseWal(pPager) ){\n    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);\n  }\n  return rc;\n}\n\n/*\n** Sync the database file for the pager pPager. zMaster points to the name\n** of a master journal file that should be written into the individual\n** journal file. zMaster may be NULL, which is interpreted as no master\n** journal (a single database transaction).\n**\n** This routine ensures that:\n**\n**   * The database file change-counter is updated,\n**   * the journal is synced (unless the atomic-write optimization is used),\n**   * all dirty pages are written to the database file, \n**   * the database file is truncated (if required), and\n**   * the database file synced. \n**\n** The only thing that remains to commit the transaction is to finalize \n** (delete, truncate or zero the first part of) the journal file (or \n** delete the master journal file if specified).\n**\n** Note that if zMaster==NULL, this does not overwrite a previous value\n** passed to an sqlite3PagerCommitPhaseOne() call.\n**\n** If the final parameter - noSync - is true, then the database file itself\n** is not synced. The caller must call sqlite3PagerSync() directly to\n** sync the database file before calling CommitPhaseTwo() to delete the\n** journal file in this case.\n*/\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(\n  Pager *pPager,                  /* Pager object */\n  const char *zMaster,            /* If not NULL, the master journal name */\n  int noSync                      /* True to omit the xSync on the db file */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n       || pPager->eState==PAGER_ERROR\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* If a prior error occurred, report that error again. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n\n  PAGERTRACE((\"DATABASE SYNC: File=%s zMaster=%s nSize=%d\\n\", \n      pPager->zFilename, zMaster, pPager->dbSize));\n\n  /* If no database changes have been made, return early. */\n  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;\n\n  if( MEMDB ){\n    /* If this is an in-memory db, or no pages have been written to, or this\n    ** function has already been called, it is mostly a no-op.  However, any\n    ** backup in progress needs to be restarted.\n    */\n    sqlite3BackupRestart(pPager->pBackup);\n  }else{\n    if( pagerUseWal(pPager) ){\n      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);\n      PgHdr *pPageOne = 0;\n      if( pList==0 ){\n        /* Must have at least one page for the WAL commit flag.\n        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */\n        rc = sqlite3PagerGet(pPager, 1, &pPageOne);\n        pList = pPageOne;\n        pList->pDirty = 0;\n      }\n      assert( rc==SQLITE_OK );\n      if( ALWAYS(pList) ){\n        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);\n      }\n      sqlite3PagerUnref(pPageOne);\n      if( rc==SQLITE_OK ){\n        sqlite3PcacheCleanAll(pPager->pPCache);\n      }\n    }else{\n      /* The following block updates the change-counter. Exactly how it\n      ** does this depends on whether or not the atomic-update optimization\n      ** was enabled at compile time, and if this transaction meets the \n      ** runtime criteria to use the operation: \n      **\n      **    * The file-system supports the atomic-write property for\n      **      blocks of size page-size, and \n      **    * This commit is not part of a multi-file transaction, and\n      **    * Exactly one page has been modified and store in the journal file.\n      **\n      ** If the optimization was not enabled at compile time, then the\n      ** pager_incr_changecounter() function is called to update the change\n      ** counter in 'indirect-mode'. If the optimization is compiled in but\n      ** is not applicable to this transaction, call sqlite3JournalCreate()\n      ** to make sure the journal file has actually been created, then call\n      ** pager_incr_changecounter() to update the change-counter in indirect\n      ** mode. \n      **\n      ** Otherwise, if the optimization is both enabled and applicable,\n      ** then call pager_incr_changecounter() to update the change-counter\n      ** in 'direct' mode. In this case the journal file will never be\n      ** created for this transaction.\n      */\n  #ifdef SQLITE_ENABLE_ATOMIC_WRITE\n      PgHdr *pPg;\n      assert( isOpen(pPager->jfd) \n           || pPager->journalMode==PAGER_JOURNALMODE_OFF \n           || pPager->journalMode==PAGER_JOURNALMODE_WAL \n      );\n      if( !zMaster && isOpen(pPager->jfd) \n       && pPager->journalOff==jrnlBufferSize(pPager) \n       && pPager->dbSize>=pPager->dbOrigSize\n       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)\n      ){\n        /* Update the db file change counter via the direct-write method. The \n        ** following call will modify the in-memory representation of page 1 \n        ** to include the updated change counter and then write page 1 \n        ** directly to the database file. Because of the atomic-write \n        ** property of the host file-system, this is safe.\n        */\n        rc = pager_incr_changecounter(pPager, 1);\n      }else{\n        rc = sqlite3JournalCreate(pPager->jfd);\n        if( rc==SQLITE_OK ){\n          rc = pager_incr_changecounter(pPager, 0);\n        }\n      }\n  #else\n      rc = pager_incr_changecounter(pPager, 0);\n  #endif\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n  \n      /* If this transaction has made the database smaller, then all pages\n      ** being discarded by the truncation must be written to the journal\n      ** file. This can only happen in auto-vacuum mode.\n      **\n      ** Before reading the pages with page numbers larger than the \n      ** current value of Pager.dbSize, set dbSize back to the value\n      ** that it took at the start of the transaction. Otherwise, the\n      ** calls to sqlite3PagerGet() return zeroed pages instead of \n      ** reading data from the database file.\n      */\n  #ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pPager->dbSize<pPager->dbOrigSize \n       && pPager->journalMode!=PAGER_JOURNALMODE_OFF\n      ){\n        Pgno i;                                   /* Iterator variable */\n        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */\n        const Pgno dbSize = pPager->dbSize;       /* Database image size */ \n        pPager->dbSize = pPager->dbOrigSize;\n        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){\n          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){\n            PgHdr *pPage;             /* Page to journal */\n            rc = sqlite3PagerGet(pPager, i, &pPage);\n            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n            rc = sqlite3PagerWrite(pPage);\n            sqlite3PagerUnref(pPage);\n            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n          }\n        }\n        pPager->dbSize = dbSize;\n      } \n  #endif\n  \n      /* Write the master journal name into the journal file. If a master \n      ** journal file name has already been written to the journal file, \n      ** or if zMaster is NULL (no master journal), then this call is a no-op.\n      */\n      rc = writeMasterJournal(pPager, zMaster);\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n  \n      /* Sync the journal file and write all dirty pages to the database.\n      ** If the atomic-update optimization is being used, this sync will not \n      ** create the journal file or perform any real IO.\n      **\n      ** Because the change-counter page was just modified, unless the\n      ** atomic-update optimization is used it is almost certain that the\n      ** journal requires a sync here. However, in locking_mode=exclusive\n      ** on a system under memory pressure it is just possible that this is \n      ** not the case. In this case it is likely enough that the redundant\n      ** xSync() call will be changed to a no-op by the OS anyhow. \n      */\n      rc = syncJournal(pPager, 0);\n      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n  \n      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));\n      if( rc!=SQLITE_OK ){\n        assert( rc!=SQLITE_IOERR_BLOCKED );\n        goto commit_phase_one_exit;\n      }\n      sqlite3PcacheCleanAll(pPager->pPCache);\n  \n      /* If the file on disk is not the same size as the database image,\n      ** then use pager_truncate to grow or shrink the file here.\n      */\n      if( pPager->dbSize!=pPager->dbFileSize ){\n        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));\n        assert( pPager->eState==PAGER_WRITER_DBMOD );\n        rc = pager_truncate(pPager, nNew);\n        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;\n      }\n  \n      /* Finally, sync the database file. */\n      if( !noSync ){\n        rc = sqlite3PagerSync(pPager);\n      }\n      IOTRACE((\"DBSYNC %p\\n\", pPager))\n    }\n  }\n\ncommit_phase_one_exit:\n  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){\n    pPager->eState = PAGER_WRITER_FINISHED;\n  }\n  return rc;\n}\n\n\n/*\n** When this function is called, the database file has been completely\n** updated to reflect the changes made by the current transaction and\n** synced to disk. The journal file still exists in the file-system \n** though, and if a failure occurs at this point it will eventually\n** be used as a hot-journal and the current transaction rolled back.\n**\n** This function finalizes the journal file, either by deleting, \n** truncating or partially zeroing it, so that it cannot be used \n** for hot-journal rollback. Once this is done the transaction is\n** irrevocably committed.\n**\n** If an error occurs, an IO error code is returned and the pager\n** moves into the error state. Otherwise, SQLITE_OK is returned.\n*/\nSQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){\n  int rc = SQLITE_OK;                  /* Return code */\n\n  /* This routine should not be called if a prior error has occurred.\n  ** But if (due to a coding error elsewhere in the system) it does get\n  ** called, just return the same error code without doing anything. */\n  if( NEVER(pPager->errCode) ) return pPager->errCode;\n\n  assert( pPager->eState==PAGER_WRITER_LOCKED\n       || pPager->eState==PAGER_WRITER_FINISHED\n       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* An optimization. If the database was not actually modified during\n  ** this transaction, the pager is running in exclusive-mode and is\n  ** using persistent journals, then this function is a no-op.\n  **\n  ** The start of the journal file currently contains a single journal \n  ** header with the nRec field set to 0. If such a journal is used as\n  ** a hot-journal during hot-journal rollback, 0 changes will be made\n  ** to the database file. So there is no need to zero the journal \n  ** header. Since the pager is in exclusive mode, there is no need\n  ** to drop any locks either.\n  */\n  if( pPager->eState==PAGER_WRITER_LOCKED \n   && pPager->exclusiveMode \n   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST\n  ){\n    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );\n    pPager->eState = PAGER_READER;\n    return SQLITE_OK;\n  }\n\n  PAGERTRACE((\"COMMIT %d\\n\", PAGERID(pPager)));\n  rc = pager_end_transaction(pPager, pPager->setMaster);\n  return pager_error(pPager, rc);\n}\n\n/*\n** If a write transaction is open, then all changes made within the \n** transaction are reverted and the current write-transaction is closed.\n** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR\n** state if an error occurs.\n**\n** If the pager is already in PAGER_ERROR state when this function is called,\n** it returns Pager.errCode immediately. No work is performed in this case.\n**\n** Otherwise, in rollback mode, this function performs two functions:\n**\n**   1) It rolls back the journal file, restoring all database file and \n**      in-memory cache pages to the state they were in when the transaction\n**      was opened, and\n**\n**   2) It finalizes the journal file, so that it is not used for hot\n**      rollback at any point in the future.\n**\n** Finalization of the journal file (task 2) is only performed if the \n** rollback is successful.\n**\n** In WAL mode, all cache-entries containing data modified within the\n** current transaction are either expelled from the cache or reverted to\n** their pre-transaction state by re-reading data from the database or\n** WAL files. The WAL transaction is then closed.\n*/\nSQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){\n  int rc = SQLITE_OK;                  /* Return code */\n  PAGERTRACE((\"ROLLBACK %d\\n\", PAGERID(pPager)));\n\n  /* PagerRollback() is a no-op if called in READER or OPEN state. If\n  ** the pager is already in the ERROR state, the rollback is not \n  ** attempted here. Instead, the error code is returned to the caller.\n  */\n  assert( assert_pager_state(pPager) );\n  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;\n  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;\n\n  if( pagerUseWal(pPager) ){\n    int rc2;\n    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);\n    rc2 = pager_end_transaction(pPager, pPager->setMaster);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){\n    int eState = pPager->eState;\n    rc = pager_end_transaction(pPager, 0);\n    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){\n      /* This can happen using journal_mode=off. Move the pager to the error \n      ** state to indicate that the contents of the cache may not be trusted.\n      ** Any active readers will get SQLITE_ABORT.\n      */\n      pPager->errCode = SQLITE_ABORT;\n      pPager->eState = PAGER_ERROR;\n      return rc;\n    }\n  }else{\n    rc = pager_playback(pPager, 0);\n  }\n\n  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );\n  assert( rc==SQLITE_OK || rc==SQLITE_FULL\n          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );\n\n  /* If an error occurs during a ROLLBACK, we can no longer trust the pager\n  ** cache. So call pager_error() on the way out to make any error persistent.\n  */\n  return pager_error(pPager, rc);\n}\n\n/*\n** Return TRUE if the database file is opened read-only.  Return FALSE\n** if the database is (in theory) writable.\n*/\nSQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){\n  return pPager->readOnly;\n}\n\n/*\n** Return the number of references to the pager.\n*/\nSQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){\n  return sqlite3PcacheRefCount(pPager->pPCache);\n}\n\n/*\n** Return the approximate number of bytes of memory currently\n** used by the pager and its associated cache.\n*/\nSQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){\n  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)\n                                     + 5*sizeof(void*);\n  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)\n           + sqlite3MallocSize(pPager)\n           + pPager->pageSize;\n}\n\n/*\n** Return the number of references to the specified page.\n*/\nSQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){\n  return sqlite3PcachePageRefcount(pPage);\n}\n\n#ifdef SQLITE_TEST\n/*\n** This routine is used for testing and analysis only.\n*/\nSQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){\n  static int a[11];\n  a[0] = sqlite3PcacheRefCount(pPager->pPCache);\n  a[1] = sqlite3PcachePagecount(pPager->pPCache);\n  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);\n  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;\n  a[4] = pPager->eState;\n  a[5] = pPager->errCode;\n  a[6] = pPager->aStat[PAGER_STAT_HIT];\n  a[7] = pPager->aStat[PAGER_STAT_MISS];\n  a[8] = 0;  /* Used to be pPager->nOvfl */\n  a[9] = pPager->nRead;\n  a[10] = pPager->aStat[PAGER_STAT_WRITE];\n  return a;\n}\n#endif\n\n/*\n** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or\n** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the\n** current cache hit or miss count, according to the value of eStat. If the \n** reset parameter is non-zero, the cache hit or miss count is zeroed before \n** returning.\n*/\nSQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){\n\n  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT\n       || eStat==SQLITE_DBSTATUS_CACHE_MISS\n       || eStat==SQLITE_DBSTATUS_CACHE_WRITE\n  );\n\n  assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );\n  assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );\n  assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );\n\n  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];\n  if( reset ){\n    pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;\n  }\n}\n\n/*\n** Return true if this is an in-memory pager.\n*/\nSQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){\n  return MEMDB;\n}\n\n/*\n** Check that there are at least nSavepoint savepoints open. If there are\n** currently less than nSavepoints open, then open one or more savepoints\n** to make up the difference. If the number of savepoints is already\n** equal to nSavepoint, then this function is a no-op.\n**\n** If a memory allocation fails, SQLITE_NOMEM is returned. If an error \n** occurs while opening the sub-journal file, then an IO error code is\n** returned. Otherwise, SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){\n  int rc = SQLITE_OK;                       /* Return code */\n  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */\n\n  assert( pPager->eState>=PAGER_WRITER_LOCKED );\n  assert( assert_pager_state(pPager) );\n\n  if( nSavepoint>nCurrent && pPager->useJournal ){\n    int ii;                                 /* Iterator variable */\n    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */\n\n    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM\n    ** if the allocation fails. Otherwise, zero the new portion in case a \n    ** malloc failure occurs while populating it in the for(...) loop below.\n    */\n    aNew = (PagerSavepoint *)sqlite3Realloc(\n        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint\n    );\n    if( !aNew ){\n      return SQLITE_NOMEM;\n    }\n    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));\n    pPager->aSavepoint = aNew;\n\n    /* Populate the PagerSavepoint structures just allocated. */\n    for(ii=nCurrent; ii<nSavepoint; ii++){\n      aNew[ii].nOrig = pPager->dbSize;\n      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){\n        aNew[ii].iOffset = pPager->journalOff;\n      }else{\n        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);\n      }\n      aNew[ii].iSubRec = pPager->nSubRec;\n      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);\n      if( !aNew[ii].pInSavepoint ){\n        return SQLITE_NOMEM;\n      }\n      if( pagerUseWal(pPager) ){\n        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);\n      }\n      pPager->nSavepoint = ii+1;\n    }\n    assert( pPager->nSavepoint==nSavepoint );\n    assertTruncateConstraint(pPager);\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to rollback or release (commit) a savepoint.\n** The savepoint to release or rollback need not be the most recently \n** created savepoint.\n**\n** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.\n** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with\n** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes\n** that have occurred since the specified savepoint was created.\n**\n** The savepoint to rollback or release is identified by parameter \n** iSavepoint. A value of 0 means to operate on the outermost savepoint\n** (the first created). A value of (Pager.nSavepoint-1) means operate\n** on the most recently created savepoint. If iSavepoint is greater than\n** (Pager.nSavepoint-1), then this function is a no-op.\n**\n** If a negative value is passed to this function, then the current\n** transaction is rolled back. This is different to calling \n** sqlite3PagerRollback() because this function does not terminate\n** the transaction or unlock the database, it just restores the \n** contents of the database to its original state. \n**\n** In any case, all savepoints with an index greater than iSavepoint \n** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),\n** then savepoint iSavepoint is also destroyed.\n**\n** This function may return SQLITE_NOMEM if a memory allocation fails,\n** or an IO error code if an IO error occurs while rolling back a \n** savepoint. If no errors occur, SQLITE_OK is returned.\n*/ \nSQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){\n  int rc = pPager->errCode;       /* Return code */\n\n  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );\n  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );\n\n  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){\n    int ii;            /* Iterator variable */\n    int nNew;          /* Number of remaining savepoints after this op. */\n\n    /* Figure out how many savepoints will still be active after this\n    ** operation. Store this value in nNew. Then free resources associated \n    ** with any savepoints that are destroyed by this operation.\n    */\n    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);\n    for(ii=nNew; ii<pPager->nSavepoint; ii++){\n      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);\n    }\n    pPager->nSavepoint = nNew;\n\n    /* If this is a release of the outermost savepoint, truncate \n    ** the sub-journal to zero bytes in size. */\n    if( op==SAVEPOINT_RELEASE ){\n      if( nNew==0 && isOpen(pPager->sjfd) ){\n        /* Only truncate if it is an in-memory sub-journal. */\n        if( sqlite3IsMemJournal(pPager->sjfd) ){\n          rc = sqlite3OsTruncate(pPager->sjfd, 0);\n          assert( rc==SQLITE_OK );\n        }\n        pPager->nSubRec = 0;\n      }\n    }\n    /* Else this is a rollback operation, playback the specified savepoint.\n    ** If this is a temp-file, it is possible that the journal file has\n    ** not yet been opened. In this case there have been no changes to\n    ** the database file, so the playback operation can be skipped.\n    */\n    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){\n      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];\n      rc = pagerPlaybackSavepoint(pPager, pSavepoint);\n      assert(rc!=SQLITE_DONE);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Return the full pathname of the database file.\n**\n** Except, if the pager is in-memory only, then return an empty string if\n** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when\n** used to report the filename to the user, for compatibility with legacy\n** behavior.  But when the Btree needs to know the filename for matching to\n** shared cache, it uses nullIfMemDb==0 so that in-memory databases can\n** participate in shared-cache.\n*/\nSQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){\n  return (nullIfMemDb && pPager->memDb) ? \"\" : pPager->zFilename;\n}\n\n/*\n** Return the VFS structure for the pager.\n*/\nSQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){\n  return pPager->pVfs;\n}\n\n/*\n** Return the file handle for the database file associated\n** with the pager.  This might return NULL if the file has\n** not yet been opened.\n*/\nSQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){\n  return pPager->fd;\n}\n\n/*\n** Return the full pathname of the journal file.\n*/\nSQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){\n  return pPager->zJournal;\n}\n\n/*\n** Return true if fsync() calls are disabled for this pager.  Return FALSE\n** if fsync()s are executed normally.\n*/\nSQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){\n  return pPager->noSync;\n}\n\n#ifdef SQLITE_HAS_CODEC\n/*\n** Set or retrieve the codec for this pager\n*/\nSQLITE_PRIVATE void sqlite3PagerSetCodec(\n  Pager *pPager,\n  void *(*xCodec)(void*,void*,Pgno,int),\n  void (*xCodecSizeChng)(void*,int,int),\n  void (*xCodecFree)(void*),\n  void *pCodec\n){\n  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);\n  pPager->xCodec = pPager->memDb ? 0 : xCodec;\n  pPager->xCodecSizeChng = xCodecSizeChng;\n  pPager->xCodecFree = xCodecFree;\n  pPager->pCodec = pCodec;\n  pagerReportSize(pPager);\n}\nSQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){\n  return pPager->pCodec;\n}\n#endif\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Move the page pPg to location pgno in the file.\n**\n** There must be no references to the page previously located at\n** pgno (which we call pPgOld) though that page is allowed to be\n** in cache.  If the page previously located at pgno is not already\n** in the rollback journal, it is not put there by by this routine.\n**\n** References to the page pPg remain valid. Updating any\n** meta-data associated with pPg (i.e. data stored in the nExtra bytes\n** allocated along with the page) is the responsibility of the caller.\n**\n** A transaction must be active when this routine is called. It used to be\n** required that a statement transaction was not active, but this restriction\n** has been removed (CREATE INDEX needs to move a page when a statement\n** transaction is active).\n**\n** If the fourth argument, isCommit, is non-zero, then this page is being\n** moved as part of a database reorganization just before the transaction \n** is being committed. In this case, it is guaranteed that the database page \n** pPg refers to will not be written to again within this transaction.\n**\n** This function may return SQLITE_NOMEM or an IO error code if an error\n** occurs. Otherwise, it returns SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){\n  PgHdr *pPgOld;               /* The page being overwritten. */\n  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */\n  int rc;                      /* Return code */\n  Pgno origPgno;               /* The original page number */\n\n  assert( pPg->nRef>0 );\n  assert( pPager->eState==PAGER_WRITER_CACHEMOD\n       || pPager->eState==PAGER_WRITER_DBMOD\n  );\n  assert( assert_pager_state(pPager) );\n\n  /* In order to be able to rollback, an in-memory database must journal\n  ** the page we are moving from.\n  */\n  if( MEMDB ){\n    rc = sqlite3PagerWrite(pPg);\n    if( rc ) return rc;\n  }\n\n  /* If the page being moved is dirty and has not been saved by the latest\n  ** savepoint, then save the current contents of the page into the \n  ** sub-journal now. This is required to handle the following scenario:\n  **\n  **   BEGIN;\n  **     <journal page X, then modify it in memory>\n  **     SAVEPOINT one;\n  **       <Move page X to location Y>\n  **     ROLLBACK TO one;\n  **\n  ** If page X were not written to the sub-journal here, it would not\n  ** be possible to restore its contents when the \"ROLLBACK TO one\"\n  ** statement were is processed.\n  **\n  ** subjournalPage() may need to allocate space to store pPg->pgno into\n  ** one or more savepoint bitvecs. This is the reason this function\n  ** may return SQLITE_NOMEM.\n  */\n  if( pPg->flags&PGHDR_DIRTY\n   && subjRequiresPage(pPg)\n   && SQLITE_OK!=(rc = subjournalPage(pPg))\n  ){\n    return rc;\n  }\n\n  PAGERTRACE((\"MOVE %d page %d (needSync=%d) moves to %d\\n\", \n      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));\n  IOTRACE((\"MOVE %p %d %d\\n\", pPager, pPg->pgno, pgno))\n\n  /* If the journal needs to be sync()ed before page pPg->pgno can\n  ** be written to, store pPg->pgno in local variable needSyncPgno.\n  **\n  ** If the isCommit flag is set, there is no need to remember that\n  ** the journal needs to be sync()ed before database page pPg->pgno \n  ** can be written to. The caller has already promised not to write to it.\n  */\n  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){\n    needSyncPgno = pPg->pgno;\n    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );\n    assert( pPg->flags&PGHDR_DIRTY );\n  }\n\n  /* If the cache contains a page with page-number pgno, remove it\n  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for \n  ** page pgno before the 'move' operation, it needs to be retained \n  ** for the page moved there.\n  */\n  pPg->flags &= ~PGHDR_NEED_SYNC;\n  pPgOld = pager_lookup(pPager, pgno);\n  assert( !pPgOld || pPgOld->nRef==1 );\n  if( pPgOld ){\n    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);\n    if( MEMDB ){\n      /* Do not discard pages from an in-memory database since we might\n      ** need to rollback later.  Just move the page out of the way. */\n      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);\n    }else{\n      sqlite3PcacheDrop(pPgOld);\n    }\n  }\n\n  origPgno = pPg->pgno;\n  sqlite3PcacheMove(pPg, pgno);\n  sqlite3PcacheMakeDirty(pPg);\n\n  /* For an in-memory database, make sure the original page continues\n  ** to exist, in case the transaction needs to roll back.  Use pPgOld\n  ** as the original page since it has already been allocated.\n  */\n  if( MEMDB ){\n    assert( pPgOld );\n    sqlite3PcacheMove(pPgOld, origPgno);\n    sqlite3PagerUnref(pPgOld);\n  }\n\n  if( needSyncPgno ){\n    /* If needSyncPgno is non-zero, then the journal file needs to be \n    ** sync()ed before any data is written to database file page needSyncPgno.\n    ** Currently, no such page exists in the page-cache and the \n    ** \"is journaled\" bitvec flag has been set. This needs to be remedied by\n    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC\n    ** flag.\n    **\n    ** If the attempt to load the page into the page-cache fails, (due\n    ** to a malloc() or IO failure), clear the bit in the pInJournal[]\n    ** array. Otherwise, if the page is loaded and written again in\n    ** this transaction, it may be written to the database file before\n    ** it is synced into the journal file. This way, it may end up in\n    ** the journal file twice, but that is not a problem.\n    */\n    PgHdr *pPgHdr;\n    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);\n    if( rc!=SQLITE_OK ){\n      if( needSyncPgno<=pPager->dbOrigSize ){\n        assert( pPager->pTmpSpace!=0 );\n        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);\n      }\n      return rc;\n    }\n    pPgHdr->flags |= PGHDR_NEED_SYNC;\n    sqlite3PcacheMakeDirty(pPgHdr);\n    sqlite3PagerUnref(pPgHdr);\n  }\n\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Return a pointer to the data for the specified page.\n*/\nSQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){\n  assert( pPg->nRef>0 || pPg->pPager->memDb );\n  return pPg->pData;\n}\n\n/*\n** Return a pointer to the Pager.nExtra bytes of \"extra\" space \n** allocated along with the specified page.\n*/\nSQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){\n  return pPg->pExtra;\n}\n\n/*\n** Get/set the locking-mode for this pager. Parameter eMode must be one\n** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or \n** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then\n** the locking-mode is set to the value specified.\n**\n** The returned value is either PAGER_LOCKINGMODE_NORMAL or\n** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)\n** locking-mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){\n  assert( eMode==PAGER_LOCKINGMODE_QUERY\n            || eMode==PAGER_LOCKINGMODE_NORMAL\n            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );\n  assert( PAGER_LOCKINGMODE_QUERY<0 );\n  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );\n  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );\n  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){\n    pPager->exclusiveMode = (u8)eMode;\n  }\n  return (int)pPager->exclusiveMode;\n}\n\n/*\n** Set the journal-mode for this pager. Parameter eMode must be one of:\n**\n**    PAGER_JOURNALMODE_DELETE\n**    PAGER_JOURNALMODE_TRUNCATE\n**    PAGER_JOURNALMODE_PERSIST\n**    PAGER_JOURNALMODE_OFF\n**    PAGER_JOURNALMODE_MEMORY\n**    PAGER_JOURNALMODE_WAL\n**\n** The journalmode is set to the value specified if the change is allowed.\n** The change may be disallowed for the following reasons:\n**\n**   *  An in-memory database can only have its journal_mode set to _OFF\n**      or _MEMORY.\n**\n**   *  Temporary databases cannot have _WAL journalmode.\n**\n** The returned indicate the current (possibly updated) journal-mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){\n  u8 eOld = pPager->journalMode;    /* Prior journalmode */\n\n#ifdef SQLITE_DEBUG\n  /* The print_pager_state() routine is intended to be used by the debugger\n  ** only.  We invoke it once here to suppress a compiler warning. */\n  print_pager_state(pPager);\n#endif\n\n\n  /* The eMode parameter is always valid */\n  assert(      eMode==PAGER_JOURNALMODE_DELETE\n            || eMode==PAGER_JOURNALMODE_TRUNCATE\n            || eMode==PAGER_JOURNALMODE_PERSIST\n            || eMode==PAGER_JOURNALMODE_OFF \n            || eMode==PAGER_JOURNALMODE_WAL \n            || eMode==PAGER_JOURNALMODE_MEMORY );\n\n  /* This routine is only called from the OP_JournalMode opcode, and\n  ** the logic there will never allow a temporary file to be changed\n  ** to WAL mode.\n  */\n  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );\n\n  /* Do allow the journalmode of an in-memory database to be set to\n  ** anything other than MEMORY or OFF\n  */\n  if( MEMDB ){\n    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );\n    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){\n      eMode = eOld;\n    }\n  }\n\n  if( eMode!=eOld ){\n\n    /* Change the journal mode. */\n    assert( pPager->eState!=PAGER_ERROR );\n    pPager->journalMode = (u8)eMode;\n\n    /* When transistioning from TRUNCATE or PERSIST to any other journal\n    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,\n    ** delete the journal file.\n    */\n    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );\n    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );\n    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );\n    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );\n    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );\n    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );\n\n    assert( isOpen(pPager->fd) || pPager->exclusiveMode );\n    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){\n\n      /* In this case we would like to delete the journal file. If it is\n      ** not possible, then that is not a problem. Deleting the journal file\n      ** here is an optimization only.\n      **\n      ** Before deleting the journal file, obtain a RESERVED lock on the\n      ** database file. This ensures that the journal file is not deleted\n      ** while it is in use by some other client.\n      */\n      sqlite3OsClose(pPager->jfd);\n      if( pPager->eLock>=RESERVED_LOCK ){\n        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);\n      }else{\n        int rc = SQLITE_OK;\n        int state = pPager->eState;\n        assert( state==PAGER_OPEN || state==PAGER_READER );\n        if( state==PAGER_OPEN ){\n          rc = sqlite3PagerSharedLock(pPager);\n        }\n        if( pPager->eState==PAGER_READER ){\n          assert( rc==SQLITE_OK );\n          rc = pagerLockDb(pPager, RESERVED_LOCK);\n        }\n        if( rc==SQLITE_OK ){\n          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);\n        }\n        if( rc==SQLITE_OK && state==PAGER_READER ){\n          pagerUnlockDb(pPager, SHARED_LOCK);\n        }else if( state==PAGER_OPEN ){\n          pager_unlock(pPager);\n        }\n        assert( state==pPager->eState );\n      }\n    }\n  }\n\n  /* Return the new journal mode */\n  return (int)pPager->journalMode;\n}\n\n/*\n** Return the current journal mode.\n*/\nSQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){\n  return (int)pPager->journalMode;\n}\n\n/*\n** Return TRUE if the pager is in a state where it is OK to change the\n** journalmode.  Journalmode changes can only happen when the database\n** is unmodified.\n*/\nSQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){\n  assert( assert_pager_state(pPager) );\n  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;\n  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;\n  return 1;\n}\n\n/*\n** Get/set the size-limit used for persistent journal files.\n**\n** Setting the size limit to -1 means no limit is enforced.\n** An attempt to set a limit smaller than -1 is a no-op.\n*/\nSQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){\n  if( iLimit>=-1 ){\n    pPager->journalSizeLimit = iLimit;\n    sqlite3WalLimit(pPager->pWal, iLimit);\n  }\n  return pPager->journalSizeLimit;\n}\n\n/*\n** Return a pointer to the pPager->pBackup variable. The backup module\n** in backup.c maintains the content of this variable. This module\n** uses it opaquely as an argument to sqlite3BackupRestart() and\n** sqlite3BackupUpdate() only.\n*/\nSQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){\n  return &pPager->pBackup;\n}\n\n#ifndef SQLITE_OMIT_VACUUM\n/*\n** Unless this is an in-memory or temporary database, clear the pager cache.\n*/\nSQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){\n  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);\n}\n#endif\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** This function is called when the user invokes \"PRAGMA wal_checkpoint\",\n** \"PRAGMA wal_blocking_checkpoint\" or calls the sqlite3_wal_checkpoint()\n** or wal_blocking_checkpoint() API functions.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.\n*/\nSQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){\n  int rc = SQLITE_OK;\n  if( pPager->pWal ){\n    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,\n        pPager->xBusyHandler, pPager->pBusyHandlerArg,\n        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,\n        pnLog, pnCkpt\n    );\n  }\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){\n  return sqlite3WalCallback(pPager->pWal);\n}\n\n/*\n** Return true if the underlying VFS for the given pager supports the\n** primitives necessary for write-ahead logging.\n*/\nSQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){\n  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;\n  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);\n}\n\n/*\n** Attempt to take an exclusive lock on the database file. If a PENDING lock\n** is obtained instead, immediately release it.\n*/\nstatic int pagerExclusiveLock(Pager *pPager){\n  int rc;                         /* Return code */\n\n  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );\n  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);\n  if( rc!=SQLITE_OK ){\n    /* If the attempt to grab the exclusive lock failed, release the \n    ** pending lock that may have been obtained instead.  */\n    pagerUnlockDb(pPager, SHARED_LOCK);\n  }\n\n  return rc;\n}\n\n/*\n** Call sqlite3WalOpen() to open the WAL handle. If the pager is in \n** exclusive-locking mode when this function is called, take an EXCLUSIVE\n** lock on the database file and use heap-memory to store the wal-index\n** in. Otherwise, use the normal shared-memory.\n*/\nstatic int pagerOpenWal(Pager *pPager){\n  int rc = SQLITE_OK;\n\n  assert( pPager->pWal==0 && pPager->tempFile==0 );\n  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );\n\n  /* If the pager is already in exclusive-mode, the WAL module will use \n  ** heap-memory for the wal-index instead of the VFS shared-memory \n  ** implementation. Take the exclusive lock now, before opening the WAL\n  ** file, to make sure this is safe.\n  */\n  if( pPager->exclusiveMode ){\n    rc = pagerExclusiveLock(pPager);\n  }\n\n  /* Open the connection to the log file. If this operation fails, \n  ** (e.g. due to malloc() failure), return an error code.\n  */\n  if( rc==SQLITE_OK ){\n    rc = sqlite3WalOpen(pPager->pVfs, \n        pPager->fd, pPager->zWal, pPager->exclusiveMode,\n        pPager->journalSizeLimit, &pPager->pWal\n    );\n  }\n\n  return rc;\n}\n\n\n/*\n** The caller must be holding a SHARED lock on the database file to call\n** this function.\n**\n** If the pager passed as the first argument is open on a real database\n** file (not a temp file or an in-memory database), and the WAL file\n** is not already open, make an attempt to open it now. If successful,\n** return SQLITE_OK. If an error occurs or the VFS used by the pager does \n** not support the xShmXXX() methods, return an error code. *pbOpen is\n** not modified in either case.\n**\n** If the pager is open on a temp-file (or in-memory database), or if\n** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK\n** without doing anything.\n*/\nSQLITE_PRIVATE int sqlite3PagerOpenWal(\n  Pager *pPager,                  /* Pager object */\n  int *pbOpen                     /* OUT: Set to true if call is a no-op */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( assert_pager_state(pPager) );\n  assert( pPager->eState==PAGER_OPEN   || pbOpen );\n  assert( pPager->eState==PAGER_READER || !pbOpen );\n  assert( pbOpen==0 || *pbOpen==0 );\n  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );\n\n  if( !pPager->tempFile && !pPager->pWal ){\n    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;\n\n    /* Close any rollback journal previously open */\n    sqlite3OsClose(pPager->jfd);\n\n    rc = pagerOpenWal(pPager);\n    if( rc==SQLITE_OK ){\n      pPager->journalMode = PAGER_JOURNALMODE_WAL;\n      pPager->eState = PAGER_OPEN;\n    }\n  }else{\n    *pbOpen = 1;\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to close the connection to the log file prior\n** to switching from WAL to rollback mode.\n**\n** Before closing the log file, this function attempts to take an \n** EXCLUSIVE lock on the database file. If this cannot be obtained, an\n** error (SQLITE_BUSY) is returned and the log connection is not closed.\n** If successful, the EXCLUSIVE lock is not released before returning.\n*/\nSQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){\n  int rc = SQLITE_OK;\n\n  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );\n\n  /* If the log file is not already open, but does exist in the file-system,\n  ** it may need to be checkpointed before the connection can switch to\n  ** rollback mode. Open it now so this can happen.\n  */\n  if( !pPager->pWal ){\n    int logexists = 0;\n    rc = pagerLockDb(pPager, SHARED_LOCK);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3OsAccess(\n          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists\n      );\n    }\n    if( rc==SQLITE_OK && logexists ){\n      rc = pagerOpenWal(pPager);\n    }\n  }\n    \n  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on\n  ** the database file, the log and log-summary files will be deleted.\n  */\n  if( rc==SQLITE_OK && pPager->pWal ){\n    rc = pagerExclusiveLock(pPager);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,\n                           pPager->pageSize, (u8*)pPager->pTmpSpace);\n      pPager->pWal = 0;\n    }\n  }\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/*\n** A read-lock must be held on the pager when this function is called. If\n** the pager is in WAL mode and the WAL file currently contains one or more\n** frames, return the size in bytes of the page images stored within the\n** WAL frames. Otherwise, if this is not a WAL database or the WAL file\n** is empty, return 0.\n*/\nSQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){\n  assert( pPager->eState==PAGER_READER );\n  return sqlite3WalFramesize(pPager->pWal);\n}\n#endif\n\n#ifdef SQLITE_HAS_CODEC\n/*\n** This function is called by the wal module when writing page content\n** into the log file.\n**\n** This function returns a pointer to a buffer containing the encrypted\n** page content. If a malloc fails, this function may return NULL.\n*/\nSQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){\n  void *aData = 0;\n  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);\n  return aData;\n}\n#endif /* SQLITE_HAS_CODEC */\n\n#endif /* !SQLITE_OMIT_WAL */\n\n#endif /* SQLITE_OMIT_DISKIO */\n\n/************** End of pager.c ***********************************************/\n/************** Begin file wal.c *********************************************/\n/*\n** 2010 February 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the implementation of a write-ahead log (WAL) used in \n** \"journal_mode=WAL\" mode.\n**\n** WRITE-AHEAD LOG (WAL) FILE FORMAT\n**\n** A WAL file consists of a header followed by zero or more \"frames\".\n** Each frame records the revised content of a single page from the\n** database file.  All changes to the database are recorded by writing\n** frames into the WAL.  Transactions commit when a frame is written that\n** contains a commit marker.  A single WAL can and usually does record \n** multiple transactions.  Periodically, the content of the WAL is\n** transferred back into the database file in an operation called a\n** \"checkpoint\".\n**\n** A single WAL file can be used multiple times.  In other words, the\n** WAL can fill up with frames and then be checkpointed and then new\n** frames can overwrite the old ones.  A WAL always grows from beginning\n** toward the end.  Checksums and counters attached to each frame are\n** used to determine which frames within the WAL are valid and which\n** are leftovers from prior checkpoints.\n**\n** The WAL header is 32 bytes in size and consists of the following eight\n** big-endian 32-bit unsigned integer values:\n**\n**     0: Magic number.  0x377f0682 or 0x377f0683\n**     4: File format version.  Currently 3007000\n**     8: Database page size.  Example: 1024\n**    12: Checkpoint sequence number\n**    16: Salt-1, random integer incremented with each checkpoint\n**    20: Salt-2, a different random integer changing with each ckpt\n**    24: Checksum-1 (first part of checksum for first 24 bytes of header).\n**    28: Checksum-2 (second part of checksum for first 24 bytes of header).\n**\n** Immediately following the wal-header are zero or more frames. Each\n** frame consists of a 24-byte frame-header followed by a <page-size> bytes\n** of page data. The frame-header is six big-endian 32-bit unsigned \n** integer values, as follows:\n**\n**     0: Page number.\n**     4: For commit records, the size of the database image in pages \n**        after the commit. For all other records, zero.\n**     8: Salt-1 (copied from the header)\n**    12: Salt-2 (copied from the header)\n**    16: Checksum-1.\n**    20: Checksum-2.\n**\n** A frame is considered valid if and only if the following conditions are\n** true:\n**\n**    (1) The salt-1 and salt-2 values in the frame-header match\n**        salt values in the wal-header\n**\n**    (2) The checksum values in the final 8 bytes of the frame-header\n**        exactly match the checksum computed consecutively on the\n**        WAL header and the first 8 bytes and the content of all frames\n**        up to and including the current frame.\n**\n** The checksum is computed using 32-bit big-endian integers if the\n** magic number in the first 4 bytes of the WAL is 0x377f0683 and it\n** is computed using little-endian if the magic number is 0x377f0682.\n** The checksum values are always stored in the frame header in a\n** big-endian format regardless of which byte order is used to compute\n** the checksum.  The checksum is computed by interpreting the input as\n** an even number of unsigned 32-bit integers: x[0] through x[N].  The\n** algorithm used for the checksum is as follows:\n** \n**   for i from 0 to n-1 step 2:\n**     s0 += x[i] + s1;\n**     s1 += x[i+1] + s0;\n**   endfor\n**\n** Note that s0 and s1 are both weighted checksums using fibonacci weights\n** in reverse order (the largest fibonacci weight occurs on the first element\n** of the sequence being summed.)  The s1 value spans all 32-bit \n** terms of the sequence whereas s0 omits the final term.\n**\n** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the\n** WAL is transferred into the database, then the database is VFS.xSync-ed.\n** The VFS.xSync operations serve as write barriers - all writes launched\n** before the xSync must complete before any write that launches after the\n** xSync begins.\n**\n** After each checkpoint, the salt-1 value is incremented and the salt-2\n** value is randomized.  This prevents old and new frames in the WAL from\n** being considered valid at the same time and being checkpointing together\n** following a crash.\n**\n** READER ALGORITHM\n**\n** To read a page from the database (call it page number P), a reader\n** first checks the WAL to see if it contains page P.  If so, then the\n** last valid instance of page P that is a followed by a commit frame\n** or is a commit frame itself becomes the value read.  If the WAL\n** contains no copies of page P that are valid and which are a commit\n** frame or are followed by a commit frame, then page P is read from\n** the database file.\n**\n** To start a read transaction, the reader records the index of the last\n** valid frame in the WAL.  The reader uses this recorded \"mxFrame\" value\n** for all subsequent read operations.  New transactions can be appended\n** to the WAL, but as long as the reader uses its original mxFrame value\n** and ignores the newly appended content, it will see a consistent snapshot\n** of the database from a single point in time.  This technique allows\n** multiple concurrent readers to view different versions of the database\n** content simultaneously.\n**\n** The reader algorithm in the previous paragraphs works correctly, but \n** because frames for page P can appear anywhere within the WAL, the\n** reader has to scan the entire WAL looking for page P frames.  If the\n** WAL is large (multiple megabytes is typical) that scan can be slow,\n** and read performance suffers.  To overcome this problem, a separate\n** data structure called the wal-index is maintained to expedite the\n** search for frames of a particular page.\n** \n** WAL-INDEX FORMAT\n**\n** Conceptually, the wal-index is shared memory, though VFS implementations\n** might choose to implement the wal-index using a mmapped file.  Because\n** the wal-index is shared memory, SQLite does not support journal_mode=WAL \n** on a network filesystem.  All users of the database must be able to\n** share memory.\n**\n** The wal-index is transient.  After a crash, the wal-index can (and should\n** be) reconstructed from the original WAL file.  In fact, the VFS is required\n** to either truncate or zero the header of the wal-index when the last\n** connection to it closes.  Because the wal-index is transient, it can\n** use an architecture-specific format; it does not have to be cross-platform.\n** Hence, unlike the database and WAL file formats which store all values\n** as big endian, the wal-index can store multi-byte values in the native\n** byte order of the host computer.\n**\n** The purpose of the wal-index is to answer this question quickly:  Given\n** a page number P and a maximum frame index M, return the index of the \n** last frame in the wal before frame M for page P in the WAL, or return\n** NULL if there are no frames for page P in the WAL prior to M.\n**\n** The wal-index consists of a header region, followed by an one or\n** more index blocks.  \n**\n** The wal-index header contains the total number of frames within the WAL\n** in the mxFrame field.\n**\n** Each index block except for the first contains information on \n** HASHTABLE_NPAGE frames. The first index block contains information on\n** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and \n** HASHTABLE_NPAGE are selected so that together the wal-index header and\n** first index block are the same size as all other index blocks in the\n** wal-index.\n**\n** Each index block contains two sections, a page-mapping that contains the\n** database page number associated with each wal frame, and a hash-table \n** that allows readers to query an index block for a specific page number.\n** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE\n** for the first index block) 32-bit page numbers. The first entry in the \n** first index-block contains the database page number corresponding to the\n** first frame in the WAL file. The first entry in the second index block\n** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in\n** the log, and so on.\n**\n** The last index block in a wal-index usually contains less than the full\n** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,\n** depending on the contents of the WAL file. This does not change the\n** allocated size of the page-mapping array - the page-mapping array merely\n** contains unused entries.\n**\n** Even without using the hash table, the last frame for page P\n** can be found by scanning the page-mapping sections of each index block\n** starting with the last index block and moving toward the first, and\n** within each index block, starting at the end and moving toward the\n** beginning.  The first entry that equals P corresponds to the frame\n** holding the content for that page.\n**\n** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.\n** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the\n** hash table for each page number in the mapping section, so the hash \n** table is never more than half full.  The expected number of collisions \n** prior to finding a match is 1.  Each entry of the hash table is an\n** 1-based index of an entry in the mapping section of the same\n** index block.   Let K be the 1-based index of the largest entry in\n** the mapping section.  (For index blocks other than the last, K will\n** always be exactly HASHTABLE_NPAGE (4096) and for the last index block\n** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table\n** contain a value of 0.\n**\n** To look for page P in the hash table, first compute a hash iKey on\n** P as follows:\n**\n**      iKey = (P * 383) % HASHTABLE_NSLOT\n**\n** Then start scanning entries of the hash table, starting with iKey\n** (wrapping around to the beginning when the end of the hash table is\n** reached) until an unused hash slot is found. Let the first unused slot\n** be at index iUnused.  (iUnused might be less than iKey if there was\n** wrap-around.) Because the hash table is never more than half full,\n** the search is guaranteed to eventually hit an unused entry.  Let \n** iMax be the value between iKey and iUnused, closest to iUnused,\n** where aHash[iMax]==P.  If there is no iMax entry (if there exists\n** no hash slot such that aHash[i]==p) then page P is not in the\n** current index block.  Otherwise the iMax-th mapping entry of the\n** current index block corresponds to the last entry that references \n** page P.\n**\n** A hash search begins with the last index block and moves toward the\n** first index block, looking for entries corresponding to page P.  On\n** average, only two or three slots in each index block need to be\n** examined in order to either find the last entry for page P, or to\n** establish that no such entry exists in the block.  Each index block\n** holds over 4000 entries.  So two or three index blocks are sufficient\n** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10\n** comparisons (on average) suffice to either locate a frame in the\n** WAL or to establish that the frame does not exist in the WAL.  This\n** is much faster than scanning the entire 10MB WAL.\n**\n** Note that entries are added in order of increasing K.  Hence, one\n** reader might be using some value K0 and a second reader that started\n** at a later time (after additional transactions were added to the WAL\n** and to the wal-index) might be using a different value K1, where K1>K0.\n** Both readers can use the same hash table and mapping section to get\n** the correct result.  There may be entries in the hash table with\n** K>K0 but to the first reader, those entries will appear to be unused\n** slots in the hash table and so the first reader will get an answer as\n** if no values greater than K0 had ever been inserted into the hash table\n** in the first place - which is what reader one wants.  Meanwhile, the\n** second reader using K1 will see additional values that were inserted\n** later, which is exactly what reader two wants.  \n**\n** When a rollback occurs, the value of K is decreased. Hash table entries\n** that correspond to frames greater than the new K value are removed\n** from the hash table at this point.\n*/\n#ifndef SQLITE_OMIT_WAL\n\n\n/*\n** Trace output macros\n*/\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\nSQLITE_PRIVATE int sqlite3WalTrace = 0;\n# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X\n#else\n# define WALTRACE(X)\n#endif\n\n/*\n** The maximum (and only) versions of the wal and wal-index formats\n** that may be interpreted by this version of SQLite.\n**\n** If a client begins recovering a WAL file and finds that (a) the checksum\n** values in the wal-header are correct and (b) the version field is not\n** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.\n**\n** Similarly, if a client successfully reads a wal-index header (i.e. the \n** checksum test is successful) and finds that the version field is not\n** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite\n** returns SQLITE_CANTOPEN.\n*/\n#define WAL_MAX_VERSION      3007000\n#define WALINDEX_MAX_VERSION 3007000\n\n/*\n** Indices of various locking bytes.   WAL_NREADER is the number\n** of available reader locks and should be at least 3.\n*/\n#define WAL_WRITE_LOCK         0\n#define WAL_ALL_BUT_WRITE      1\n#define WAL_CKPT_LOCK          1\n#define WAL_RECOVER_LOCK       2\n#define WAL_READ_LOCK(I)       (3+(I))\n#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)\n\n\n/* Object declarations */\ntypedef struct WalIndexHdr WalIndexHdr;\ntypedef struct WalIterator WalIterator;\ntypedef struct WalCkptInfo WalCkptInfo;\n\n\n/*\n** The following object holds a copy of the wal-index header content.\n**\n** The actual header in the wal-index consists of two copies of this\n** object.\n**\n** The szPage value can be any power of 2 between 512 and 32768, inclusive.\n** Or it can be 1 to represent a 65536-byte page.  The latter case was\n** added in 3.7.1 when support for 64K pages was added.  \n*/\nstruct WalIndexHdr {\n  u32 iVersion;                   /* Wal-index version */\n  u32 unused;                     /* Unused (padding) field */\n  u32 iChange;                    /* Counter incremented each transaction */\n  u8 isInit;                      /* 1 when initialized */\n  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */\n  u16 szPage;                     /* Database page size in bytes. 1==64K */\n  u32 mxFrame;                    /* Index of last valid frame in the WAL */\n  u32 nPage;                      /* Size of database in pages */\n  u32 aFrameCksum[2];             /* Checksum of last frame in log */\n  u32 aSalt[2];                   /* Two salt values copied from WAL header */\n  u32 aCksum[2];                  /* Checksum over all prior fields */\n};\n\n/*\n** A copy of the following object occurs in the wal-index immediately\n** following the second copy of the WalIndexHdr.  This object stores\n** information used by checkpoint.\n**\n** nBackfill is the number of frames in the WAL that have been written\n** back into the database. (We call the act of moving content from WAL to\n** database \"backfilling\".)  The nBackfill number is never greater than\n** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads\n** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).\n** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from\n** mxFrame back to zero when the WAL is reset.\n**\n** There is one entry in aReadMark[] for each reader lock.  If a reader\n** holds read-lock K, then the value in aReadMark[K] is no greater than\n** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)\n** for any aReadMark[] means that entry is unused.  aReadMark[0] is \n** a special case; its value is never used and it exists as a place-holder\n** to avoid having to offset aReadMark[] indexs by one.  Readers holding\n** WAL_READ_LOCK(0) always ignore the entire WAL and read all content\n** directly from the database.\n**\n** The value of aReadMark[K] may only be changed by a thread that\n** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of\n** aReadMark[K] cannot changed while there is a reader is using that mark\n** since the reader will be holding a shared lock on WAL_READ_LOCK(K).\n**\n** The checkpointer may only transfer frames from WAL to database where\n** the frame numbers are less than or equal to every aReadMark[] that is\n** in use (that is, every aReadMark[j] for which there is a corresponding\n** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the\n** largest value and will increase an unused aReadMark[] to mxFrame if there\n** is not already an aReadMark[] equal to mxFrame.  The exception to the\n** previous sentence is when nBackfill equals mxFrame (meaning that everything\n** in the WAL has been backfilled into the database) then new readers\n** will choose aReadMark[0] which has value 0 and hence such reader will\n** get all their all content directly from the database file and ignore \n** the WAL.\n**\n** Writers normally append new frames to the end of the WAL.  However,\n** if nBackfill equals mxFrame (meaning that all WAL content has been\n** written back into the database) and if no readers are using the WAL\n** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then\n** the writer will first \"reset\" the WAL back to the beginning and start\n** writing new content beginning at frame 1.\n**\n** We assume that 32-bit loads are atomic and so no locks are needed in\n** order to read from any aReadMark[] entries.\n*/\nstruct WalCkptInfo {\n  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */\n  u32 aReadMark[WAL_NREADER];     /* Reader marks */\n};\n#define READMARK_NOT_USED  0xffffffff\n\n\n/* A block of WALINDEX_LOCK_RESERVED bytes beginning at\n** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems\n** only support mandatory file-locks, we do not read or write data\n** from the region of the file on which locks are applied.\n*/\n#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))\n#define WALINDEX_LOCK_RESERVED 16\n#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)\n\n/* Size of header before each frame in wal */\n#define WAL_FRAME_HDRSIZE 24\n\n/* Size of write ahead log header, including checksum. */\n/* #define WAL_HDRSIZE 24 */\n#define WAL_HDRSIZE 32\n\n/* WAL magic value. Either this value, or the same value with the least\n** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit\n** big-endian format in the first 4 bytes of a WAL file.\n**\n** If the LSB is set, then the checksums for each frame within the WAL\n** file are calculated by treating all data as an array of 32-bit \n** big-endian words. Otherwise, they are calculated by interpreting \n** all data as 32-bit little-endian words.\n*/\n#define WAL_MAGIC 0x377f0682\n\n/*\n** Return the offset of frame iFrame in the write-ahead log file, \n** assuming a database page size of szPage bytes. The offset returned\n** is to the start of the write-ahead log frame-header.\n*/\n#define walFrameOffset(iFrame, szPage) (                               \\\n  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \\\n)\n\n/*\n** An open write-ahead log file is represented by an instance of the\n** following object.\n*/\nstruct Wal {\n  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */\n  sqlite3_file *pDbFd;       /* File handle for the database file */\n  sqlite3_file *pWalFd;      /* File handle for WAL file */\n  u32 iCallback;             /* Value to pass to log callback (or 0) */\n  i64 mxWalSize;             /* Truncate WAL to this size upon reset */\n  int nWiData;               /* Size of array apWiData */\n  int szFirstBlock;          /* Size of first block written to WAL file */\n  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */\n  u32 szPage;                /* Database page size */\n  i16 readLock;              /* Which read lock is being held.  -1 for none */\n  u8 syncFlags;              /* Flags to use to sync header writes */\n  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */\n  u8 writeLock;              /* True if in a write transaction */\n  u8 ckptLock;               /* True if holding a checkpoint lock */\n  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */\n  u8 truncateOnCommit;       /* True to truncate WAL file on commit */\n  u8 syncHeader;             /* Fsync the WAL header if true */\n  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */\n  WalIndexHdr hdr;           /* Wal-index header for current transaction */\n  const char *zWalName;      /* Name of WAL file */\n  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */\n#ifdef SQLITE_DEBUG\n  u8 lockError;              /* True if a locking error has occurred */\n#endif\n};\n\n/*\n** Candidate values for Wal.exclusiveMode.\n*/\n#define WAL_NORMAL_MODE     0\n#define WAL_EXCLUSIVE_MODE  1     \n#define WAL_HEAPMEMORY_MODE 2\n\n/*\n** Possible values for WAL.readOnly\n*/\n#define WAL_RDWR        0    /* Normal read/write connection */\n#define WAL_RDONLY      1    /* The WAL file is readonly */\n#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */\n\n/*\n** Each page of the wal-index mapping contains a hash-table made up of\n** an array of HASHTABLE_NSLOT elements of the following type.\n*/\ntypedef u16 ht_slot;\n\n/*\n** This structure is used to implement an iterator that loops through\n** all frames in the WAL in database page order. Where two or more frames\n** correspond to the same database page, the iterator visits only the \n** frame most recently written to the WAL (in other words, the frame with\n** the largest index).\n**\n** The internals of this structure are only accessed by:\n**\n**   walIteratorInit() - Create a new iterator,\n**   walIteratorNext() - Step an iterator,\n**   walIteratorFree() - Free an iterator.\n**\n** This functionality is used by the checkpoint code (see walCheckpoint()).\n*/\nstruct WalIterator {\n  int iPrior;                     /* Last result returned from the iterator */\n  int nSegment;                   /* Number of entries in aSegment[] */\n  struct WalSegment {\n    int iNext;                    /* Next slot in aIndex[] not yet returned */\n    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */\n    u32 *aPgno;                   /* Array of page numbers. */\n    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */\n    int iZero;                    /* Frame number associated with aPgno[0] */\n  } aSegment[1];                  /* One for every 32KB page in the wal-index */\n};\n\n/*\n** Define the parameters of the hash tables in the wal-index file. There\n** is a hash-table following every HASHTABLE_NPAGE page numbers in the\n** wal-index.\n**\n** Changing any of these constants will alter the wal-index format and\n** create incompatibilities.\n*/\n#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */\n#define HASHTABLE_HASH_1     383                  /* Should be prime */\n#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */\n\n/* \n** The block of page numbers associated with the first hash-table in a\n** wal-index is smaller than usual. This is so that there is a complete\n** hash-table on each aligned 32KB page of the wal-index.\n*/\n#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))\n\n/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */\n#define WALINDEX_PGSZ   (                                         \\\n    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \\\n)\n\n/*\n** Obtain a pointer to the iPage'th page of the wal-index. The wal-index\n** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are\n** numbered from zero.\n**\n** If this call is successful, *ppPage is set to point to the wal-index\n** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,\n** then an SQLite error code is returned and *ppPage is set to 0.\n*/\nstatic int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){\n  int rc = SQLITE_OK;\n\n  /* Enlarge the pWal->apWiData[] array if required */\n  if( pWal->nWiData<=iPage ){\n    int nByte = sizeof(u32*)*(iPage+1);\n    volatile u32 **apNew;\n    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);\n    if( !apNew ){\n      *ppPage = 0;\n      return SQLITE_NOMEM;\n    }\n    memset((void*)&apNew[pWal->nWiData], 0,\n           sizeof(u32*)*(iPage+1-pWal->nWiData));\n    pWal->apWiData = apNew;\n    pWal->nWiData = iPage+1;\n  }\n\n  /* Request a pointer to the required page from the VFS */\n  if( pWal->apWiData[iPage]==0 ){\n    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){\n      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);\n      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, \n          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]\n      );\n      if( rc==SQLITE_READONLY ){\n        pWal->readOnly |= WAL_SHM_RDONLY;\n        rc = SQLITE_OK;\n      }\n    }\n  }\n\n  *ppPage = pWal->apWiData[iPage];\n  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );\n  return rc;\n}\n\n/*\n** Return a pointer to the WalCkptInfo structure in the wal-index.\n*/\nstatic volatile WalCkptInfo *walCkptInfo(Wal *pWal){\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);\n}\n\n/*\n** Return a pointer to the WalIndexHdr structure in the wal-index.\n*/\nstatic volatile WalIndexHdr *walIndexHdr(Wal *pWal){\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n  return (volatile WalIndexHdr*)pWal->apWiData[0];\n}\n\n/*\n** The argument to this macro must be of type u32. On a little-endian\n** architecture, it returns the u32 value that results from interpreting\n** the 4 bytes as a big-endian value. On a big-endian architecture, it\n** returns the value that would be produced by intepreting the 4 bytes\n** of the input value as a little-endian integer.\n*/\n#define BYTESWAP32(x) ( \\\n    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \\\n  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \\\n)\n\n/*\n** Generate or extend an 8 byte checksum based on the data in \n** array aByte[] and the initial values of aIn[0] and aIn[1] (or\n** initial values of 0 and 0 if aIn==NULL).\n**\n** The checksum is written back into aOut[] before returning.\n**\n** nByte must be a positive multiple of 8.\n*/\nstatic void walChecksumBytes(\n  int nativeCksum, /* True for native byte-order, false for non-native */\n  u8 *a,           /* Content to be checksummed */\n  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */\n  const u32 *aIn,  /* Initial checksum value input */\n  u32 *aOut        /* OUT: Final checksum value output */\n){\n  u32 s1, s2;\n  u32 *aData = (u32 *)a;\n  u32 *aEnd = (u32 *)&a[nByte];\n\n  if( aIn ){\n    s1 = aIn[0];\n    s2 = aIn[1];\n  }else{\n    s1 = s2 = 0;\n  }\n\n  assert( nByte>=8 );\n  assert( (nByte&0x00000007)==0 );\n\n  if( nativeCksum ){\n    do {\n      s1 += *aData++ + s2;\n      s2 += *aData++ + s1;\n    }while( aData<aEnd );\n  }else{\n    do {\n      s1 += BYTESWAP32(aData[0]) + s2;\n      s2 += BYTESWAP32(aData[1]) + s1;\n      aData += 2;\n    }while( aData<aEnd );\n  }\n\n  aOut[0] = s1;\n  aOut[1] = s2;\n}\n\nstatic void walShmBarrier(Wal *pWal){\n  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){\n    sqlite3OsShmBarrier(pWal->pDbFd);\n  }\n}\n\n/*\n** Write the header information in pWal->hdr into the wal-index.\n**\n** The checksum on pWal->hdr is updated before it is written.\n*/\nstatic void walIndexWriteHdr(Wal *pWal){\n  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);\n  const int nCksum = offsetof(WalIndexHdr, aCksum);\n\n  assert( pWal->writeLock );\n  pWal->hdr.isInit = 1;\n  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;\n  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);\n  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));\n  walShmBarrier(pWal);\n  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));\n}\n\n/*\n** This function encodes a single frame header and writes it to a buffer\n** supplied by the caller. A frame-header is made up of a series of \n** 4-byte big-endian integers, as follows:\n**\n**     0: Page number.\n**     4: For commit records, the size of the database image in pages \n**        after the commit. For all other records, zero.\n**     8: Salt-1 (copied from the wal-header)\n**    12: Salt-2 (copied from the wal-header)\n**    16: Checksum-1.\n**    20: Checksum-2.\n*/\nstatic void walEncodeFrame(\n  Wal *pWal,                      /* The write-ahead log */\n  u32 iPage,                      /* Database page number for frame */\n  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */\n  u8 *aData,                      /* Pointer to page data */\n  u8 *aFrame                      /* OUT: Write encoded frame here */\n){\n  int nativeCksum;                /* True for native byte-order checksums */\n  u32 *aCksum = pWal->hdr.aFrameCksum;\n  assert( WAL_FRAME_HDRSIZE==24 );\n  sqlite3Put4byte(&aFrame[0], iPage);\n  sqlite3Put4byte(&aFrame[4], nTruncate);\n  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);\n\n  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);\n  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);\n  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);\n\n  sqlite3Put4byte(&aFrame[16], aCksum[0]);\n  sqlite3Put4byte(&aFrame[20], aCksum[1]);\n}\n\n/*\n** Check to see if the frame with header in aFrame[] and content\n** in aData[] is valid.  If it is a valid frame, fill *piPage and\n** *pnTruncate and return true.  Return if the frame is not valid.\n*/\nstatic int walDecodeFrame(\n  Wal *pWal,                      /* The write-ahead log */\n  u32 *piPage,                    /* OUT: Database page number for frame */\n  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */\n  u8 *aData,                      /* Pointer to page data (for checksum) */\n  u8 *aFrame                      /* Frame data */\n){\n  int nativeCksum;                /* True for native byte-order checksums */\n  u32 *aCksum = pWal->hdr.aFrameCksum;\n  u32 pgno;                       /* Page number of the frame */\n  assert( WAL_FRAME_HDRSIZE==24 );\n\n  /* A frame is only valid if the salt values in the frame-header\n  ** match the salt values in the wal-header. \n  */\n  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){\n    return 0;\n  }\n\n  /* A frame is only valid if the page number is creater than zero.\n  */\n  pgno = sqlite3Get4byte(&aFrame[0]);\n  if( pgno==0 ){\n    return 0;\n  }\n\n  /* A frame is only valid if a checksum of the WAL header,\n  ** all prior frams, the first 16 bytes of this frame-header, \n  ** and the frame-data matches the checksum in the last 8 \n  ** bytes of this frame-header.\n  */\n  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);\n  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);\n  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);\n  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) \n   || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) \n  ){\n    /* Checksum failed. */\n    return 0;\n  }\n\n  /* If we reach this point, the frame is valid.  Return the page number\n  ** and the new database size.\n  */\n  *piPage = pgno;\n  *pnTruncate = sqlite3Get4byte(&aFrame[4]);\n  return 1;\n}\n\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n/*\n** Names of locks.  This routine is used to provide debugging output and is not\n** a part of an ordinary build.\n*/\nstatic const char *walLockName(int lockIdx){\n  if( lockIdx==WAL_WRITE_LOCK ){\n    return \"WRITE-LOCK\";\n  }else if( lockIdx==WAL_CKPT_LOCK ){\n    return \"CKPT-LOCK\";\n  }else if( lockIdx==WAL_RECOVER_LOCK ){\n    return \"RECOVER-LOCK\";\n  }else{\n    static char zName[15];\n    sqlite3_snprintf(sizeof(zName), zName, \"READ-LOCK[%d]\",\n                     lockIdx-WAL_READ_LOCK(0));\n    return zName;\n  }\n}\n#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */\n    \n\n/*\n** Set or release locks on the WAL.  Locks are either shared or exclusive.\n** A lock cannot be moved directly between shared and exclusive - it must go\n** through the unlocked state first.\n**\n** In locking_mode=EXCLUSIVE, all of these routines become no-ops.\n*/\nstatic int walLockShared(Wal *pWal, int lockIdx){\n  int rc;\n  if( pWal->exclusiveMode ) return SQLITE_OK;\n  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,\n                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);\n  WALTRACE((\"WAL%p: acquire SHARED-%s %s\\n\", pWal,\n            walLockName(lockIdx), rc ? \"failed\" : \"ok\"));\n  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )\n  return rc;\n}\nstatic void walUnlockShared(Wal *pWal, int lockIdx){\n  if( pWal->exclusiveMode ) return;\n  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,\n                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);\n  WALTRACE((\"WAL%p: release SHARED-%s\\n\", pWal, walLockName(lockIdx)));\n}\nstatic int walLockExclusive(Wal *pWal, int lockIdx, int n){\n  int rc;\n  if( pWal->exclusiveMode ) return SQLITE_OK;\n  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,\n                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);\n  WALTRACE((\"WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\\n\", pWal,\n            walLockName(lockIdx), n, rc ? \"failed\" : \"ok\"));\n  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )\n  return rc;\n}\nstatic void walUnlockExclusive(Wal *pWal, int lockIdx, int n){\n  if( pWal->exclusiveMode ) return;\n  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,\n                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);\n  WALTRACE((\"WAL%p: release EXCLUSIVE-%s cnt=%d\\n\", pWal,\n             walLockName(lockIdx), n));\n}\n\n/*\n** Compute a hash on a page number.  The resulting hash value must land\n** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances\n** the hash to the next value in the event of a collision.\n*/\nstatic int walHash(u32 iPage){\n  assert( iPage>0 );\n  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );\n  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);\n}\nstatic int walNextHash(int iPriorHash){\n  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);\n}\n\n/* \n** Return pointers to the hash table and page number array stored on\n** page iHash of the wal-index. The wal-index is broken into 32KB pages\n** numbered starting from 0.\n**\n** Set output variable *paHash to point to the start of the hash table\n** in the wal-index file. Set *piZero to one less than the frame \n** number of the first frame indexed by this hash table. If a\n** slot in the hash table is set to N, it refers to frame number \n** (*piZero+N) in the log.\n**\n** Finally, set *paPgno so that *paPgno[1] is the page number of the\n** first frame indexed by the hash table, frame (*piZero+1).\n*/\nstatic int walHashGet(\n  Wal *pWal,                      /* WAL handle */\n  int iHash,                      /* Find the iHash'th table */\n  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */\n  volatile u32 **paPgno,          /* OUT: Pointer to page number array */\n  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */\n){\n  int rc;                         /* Return code */\n  volatile u32 *aPgno;\n\n  rc = walIndexPage(pWal, iHash, &aPgno);\n  assert( rc==SQLITE_OK || iHash>0 );\n\n  if( rc==SQLITE_OK ){\n    u32 iZero;\n    volatile ht_slot *aHash;\n\n    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];\n    if( iHash==0 ){\n      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];\n      iZero = 0;\n    }else{\n      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;\n    }\n  \n    *paPgno = &aPgno[-1];\n    *paHash = aHash;\n    *piZero = iZero;\n  }\n  return rc;\n}\n\n/*\n** Return the number of the wal-index page that contains the hash-table\n** and page-number array that contain entries corresponding to WAL frame\n** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages \n** are numbered starting from 0.\n*/\nstatic int walFramePage(u32 iFrame){\n  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;\n  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)\n       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)\n       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))\n       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)\n       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))\n  );\n  return iHash;\n}\n\n/*\n** Return the page number associated with frame iFrame in this WAL.\n*/\nstatic u32 walFramePgno(Wal *pWal, u32 iFrame){\n  int iHash = walFramePage(iFrame);\n  if( iHash==0 ){\n    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];\n  }\n  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];\n}\n\n/*\n** Remove entries from the hash table that point to WAL slots greater\n** than pWal->hdr.mxFrame.\n**\n** This function is called whenever pWal->hdr.mxFrame is decreased due\n** to a rollback or savepoint.\n**\n** At most only the hash table containing pWal->hdr.mxFrame needs to be\n** updated.  Any later hash tables will be automatically cleared when\n** pWal->hdr.mxFrame advances to the point where those hash tables are\n** actually needed.\n*/\nstatic void walCleanupHash(Wal *pWal){\n  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */\n  volatile u32 *aPgno = 0;        /* Page number array for hash table */\n  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */\n  int iLimit = 0;                 /* Zero values greater than this */\n  int nByte;                      /* Number of bytes to zero in aPgno[] */\n  int i;                          /* Used to iterate through aHash[] */\n\n  assert( pWal->writeLock );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );\n  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );\n\n  if( pWal->hdr.mxFrame==0 ) return;\n\n  /* Obtain pointers to the hash-table and page-number array containing \n  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed\n  ** that the page said hash-table and array reside on is already mapped.\n  */\n  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );\n  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );\n  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);\n\n  /* Zero all hash-table entries that correspond to frame numbers greater\n  ** than pWal->hdr.mxFrame.\n  */\n  iLimit = pWal->hdr.mxFrame - iZero;\n  assert( iLimit>0 );\n  for(i=0; i<HASHTABLE_NSLOT; i++){\n    if( aHash[i]>iLimit ){\n      aHash[i] = 0;\n    }\n  }\n  \n  /* Zero the entries in the aPgno array that correspond to frames with\n  ** frame numbers greater than pWal->hdr.mxFrame. \n  */\n  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);\n  memset((void *)&aPgno[iLimit+1], 0, nByte);\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n  /* Verify that the every entry in the mapping region is still reachable\n  ** via the hash table even after the cleanup.\n  */\n  if( iLimit ){\n    int i;           /* Loop counter */\n    int iKey;        /* Hash key */\n    for(i=1; i<=iLimit; i++){\n      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){\n        if( aHash[iKey]==i ) break;\n      }\n      assert( aHash[iKey]==i );\n    }\n  }\n#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */\n}\n\n\n/*\n** Set an entry in the wal-index that will map database page number\n** pPage into WAL frame iFrame.\n*/\nstatic int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){\n  int rc;                         /* Return code */\n  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */\n  volatile u32 *aPgno = 0;        /* Page number array */\n  volatile ht_slot *aHash = 0;    /* Hash table */\n\n  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);\n\n  /* Assuming the wal-index file was successfully mapped, populate the\n  ** page number array and hash table entry.\n  */\n  if( rc==SQLITE_OK ){\n    int iKey;                     /* Hash table key */\n    int idx;                      /* Value to write to hash-table slot */\n    int nCollide;                 /* Number of hash collisions */\n\n    idx = iFrame - iZero;\n    assert( idx <= HASHTABLE_NSLOT/2 + 1 );\n    \n    /* If this is the first entry to be added to this hash-table, zero the\n    ** entire hash table and aPgno[] array before proceding. \n    */\n    if( idx==1 ){\n      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);\n      memset((void*)&aPgno[1], 0, nByte);\n    }\n\n    /* If the entry in aPgno[] is already set, then the previous writer\n    ** must have exited unexpectedly in the middle of a transaction (after\n    ** writing one or more dirty pages to the WAL to free up memory). \n    ** Remove the remnants of that writers uncommitted transaction from \n    ** the hash-table before writing any new entries.\n    */\n    if( aPgno[idx] ){\n      walCleanupHash(pWal);\n      assert( !aPgno[idx] );\n    }\n\n    /* Write the aPgno[] array entry and the hash-table slot. */\n    nCollide = idx;\n    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){\n      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;\n    }\n    aPgno[idx] = iPage;\n    aHash[iKey] = (ht_slot)idx;\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n    /* Verify that the number of entries in the hash table exactly equals\n    ** the number of entries in the mapping region.\n    */\n    {\n      int i;           /* Loop counter */\n      int nEntry = 0;  /* Number of entries in the hash table */\n      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }\n      assert( nEntry==idx );\n    }\n\n    /* Verify that the every entry in the mapping region is reachable\n    ** via the hash table.  This turns out to be a really, really expensive\n    ** thing to check, so only do this occasionally - not on every\n    ** iteration.\n    */\n    if( (idx&0x3ff)==0 ){\n      int i;           /* Loop counter */\n      for(i=1; i<=idx; i++){\n        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){\n          if( aHash[iKey]==i ) break;\n        }\n        assert( aHash[iKey]==i );\n      }\n    }\n#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */\n  }\n\n\n  return rc;\n}\n\n\n/*\n** Recover the wal-index by reading the write-ahead log file. \n**\n** This routine first tries to establish an exclusive lock on the\n** wal-index to prevent other threads/processes from doing anything\n** with the WAL or wal-index while recovery is running.  The\n** WAL_RECOVER_LOCK is also held so that other threads will know\n** that this thread is running recovery.  If unable to establish\n** the necessary locks, this routine returns SQLITE_BUSY.\n*/\nstatic int walIndexRecover(Wal *pWal){\n  int rc;                         /* Return Code */\n  i64 nSize;                      /* Size of log file */\n  u32 aFrameCksum[2] = {0, 0};\n  int iLock;                      /* Lock offset to lock for checkpoint */\n  int nLock;                      /* Number of locks to hold */\n\n  /* Obtain an exclusive lock on all byte in the locking range not already\n  ** locked by the caller. The caller is guaranteed to have locked the\n  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.\n  ** If successful, the same bytes that are locked here are unlocked before\n  ** this function returns.\n  */\n  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );\n  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );\n  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );\n  assert( pWal->writeLock );\n  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;\n  nLock = SQLITE_SHM_NLOCK - iLock;\n  rc = walLockExclusive(pWal, iLock, nLock);\n  if( rc ){\n    return rc;\n  }\n  WALTRACE((\"WAL%p: recovery begin...\\n\", pWal));\n\n  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));\n\n  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);\n  if( rc!=SQLITE_OK ){\n    goto recovery_error;\n  }\n\n  if( nSize>WAL_HDRSIZE ){\n    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */\n    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */\n    int szFrame;                  /* Number of bytes in buffer aFrame[] */\n    u8 *aData;                    /* Pointer to data part of aFrame buffer */\n    int iFrame;                   /* Index of last frame read */\n    i64 iOffset;                  /* Next offset to read from log file */\n    int szPage;                   /* Page size according to the log */\n    u32 magic;                    /* Magic value read from WAL header */\n    u32 version;                  /* Magic value read from WAL header */\n    int isValid;                  /* True if this frame is valid */\n\n    /* Read in the WAL header. */\n    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);\n    if( rc!=SQLITE_OK ){\n      goto recovery_error;\n    }\n\n    /* If the database page size is not a power of two, or is greater than\n    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid \n    ** data. Similarly, if the 'magic' value is invalid, ignore the whole\n    ** WAL file.\n    */\n    magic = sqlite3Get4byte(&aBuf[0]);\n    szPage = sqlite3Get4byte(&aBuf[8]);\n    if( (magic&0xFFFFFFFE)!=WAL_MAGIC \n     || szPage&(szPage-1) \n     || szPage>SQLITE_MAX_PAGE_SIZE \n     || szPage<512 \n    ){\n      goto finished;\n    }\n    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);\n    pWal->szPage = szPage;\n    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);\n    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);\n\n    /* Verify that the WAL header checksum is correct */\n    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, \n        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum\n    );\n    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])\n     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])\n    ){\n      goto finished;\n    }\n\n    /* Verify that the version number on the WAL format is one that\n    ** are able to understand */\n    version = sqlite3Get4byte(&aBuf[4]);\n    if( version!=WAL_MAX_VERSION ){\n      rc = SQLITE_CANTOPEN_BKPT;\n      goto finished;\n    }\n\n    /* Malloc a buffer to read frames into. */\n    szFrame = szPage + WAL_FRAME_HDRSIZE;\n    aFrame = (u8 *)sqlite3_malloc(szFrame);\n    if( !aFrame ){\n      rc = SQLITE_NOMEM;\n      goto recovery_error;\n    }\n    aData = &aFrame[WAL_FRAME_HDRSIZE];\n\n    /* Read all frames from the log file. */\n    iFrame = 0;\n    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){\n      u32 pgno;                   /* Database page number for frame */\n      u32 nTruncate;              /* dbsize field from frame header */\n\n      /* Read and decode the next log frame. */\n      iFrame++;\n      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);\n      if( rc!=SQLITE_OK ) break;\n      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);\n      if( !isValid ) break;\n      rc = walIndexAppend(pWal, iFrame, pgno);\n      if( rc!=SQLITE_OK ) break;\n\n      /* If nTruncate is non-zero, this is a commit record. */\n      if( nTruncate ){\n        pWal->hdr.mxFrame = iFrame;\n        pWal->hdr.nPage = nTruncate;\n        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));\n        testcase( szPage<=32768 );\n        testcase( szPage>=65536 );\n        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];\n        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];\n      }\n    }\n\n    sqlite3_free(aFrame);\n  }\n\nfinished:\n  if( rc==SQLITE_OK ){\n    volatile WalCkptInfo *pInfo;\n    int i;\n    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];\n    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];\n    walIndexWriteHdr(pWal);\n\n    /* Reset the checkpoint-header. This is safe because this thread is \n    ** currently holding locks that exclude all other readers, writers and\n    ** checkpointers.\n    */\n    pInfo = walCkptInfo(pWal);\n    pInfo->nBackfill = 0;\n    pInfo->aReadMark[0] = 0;\n    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;\n    if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;\n\n    /* If more than one frame was recovered from the log file, report an\n    ** event via sqlite3_log(). This is to help with identifying performance\n    ** problems caused by applications routinely shutting down without\n    ** checkpointing the log file.\n    */\n    if( pWal->hdr.nPage ){\n      sqlite3_log(SQLITE_OK, \"Recovered %d frames from WAL file %s\",\n          pWal->hdr.nPage, pWal->zWalName\n      );\n    }\n  }\n\nrecovery_error:\n  WALTRACE((\"WAL%p: recovery %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n  walUnlockExclusive(pWal, iLock, nLock);\n  return rc;\n}\n\n/*\n** Close an open wal-index.\n*/\nstatic void walIndexClose(Wal *pWal, int isDelete){\n  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){\n    int i;\n    for(i=0; i<pWal->nWiData; i++){\n      sqlite3_free((void *)pWal->apWiData[i]);\n      pWal->apWiData[i] = 0;\n    }\n  }else{\n    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);\n  }\n}\n\n/* \n** Open a connection to the WAL file zWalName. The database file must \n** already be opened on connection pDbFd. The buffer that zWalName points\n** to must remain valid for the lifetime of the returned Wal* handle.\n**\n** A SHARED lock should be held on the database file when this function\n** is called. The purpose of this SHARED lock is to prevent any other\n** client from unlinking the WAL or wal-index file. If another process\n** were to do this just after this client opened one of these files, the\n** system would be badly broken.\n**\n** If the log file is successfully opened, SQLITE_OK is returned and \n** *ppWal is set to point to a new WAL handle. If an error occurs,\n** an SQLite error code is returned and *ppWal is left unmodified.\n*/\nSQLITE_PRIVATE int sqlite3WalOpen(\n  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */\n  sqlite3_file *pDbFd,            /* The open database file */\n  const char *zWalName,           /* Name of the WAL file */\n  int bNoShm,                     /* True to run in heap-memory mode */\n  i64 mxWalSize,                  /* Truncate WAL to this size on reset */\n  Wal **ppWal                     /* OUT: Allocated Wal handle */\n){\n  int rc;                         /* Return Code */\n  Wal *pRet;                      /* Object to allocate and return */\n  int flags;                      /* Flags passed to OsOpen() */\n\n  assert( zWalName && zWalName[0] );\n  assert( pDbFd );\n\n  /* In the amalgamation, the os_unix.c and os_win.c source files come before\n  ** this source file.  Verify that the #defines of the locking byte offsets\n  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.\n  */\n#ifdef WIN_SHM_BASE\n  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );\n#endif\n#ifdef UNIX_SHM_BASE\n  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );\n#endif\n\n\n  /* Allocate an instance of struct Wal to return. */\n  *ppWal = 0;\n  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);\n  if( !pRet ){\n    return SQLITE_NOMEM;\n  }\n\n  pRet->pVfs = pVfs;\n  pRet->pWalFd = (sqlite3_file *)&pRet[1];\n  pRet->pDbFd = pDbFd;\n  pRet->readLock = -1;\n  pRet->mxWalSize = mxWalSize;\n  pRet->zWalName = zWalName;\n  pRet->syncHeader = 1;\n  pRet->padToSectorBoundary = 1;\n  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);\n\n  /* Open file handle on the write-ahead log file. */\n  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);\n  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);\n  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){\n    pRet->readOnly = WAL_RDONLY;\n  }\n\n  if( rc!=SQLITE_OK ){\n    walIndexClose(pRet, 0);\n    sqlite3OsClose(pRet->pWalFd);\n    sqlite3_free(pRet);\n  }else{\n    int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);\n    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }\n    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){\n      pRet->padToSectorBoundary = 0;\n    }\n    *ppWal = pRet;\n    WALTRACE((\"WAL%d: opened\\n\", pRet));\n  }\n  return rc;\n}\n\n/*\n** Change the size to which the WAL file is trucated on each reset.\n*/\nSQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){\n  if( pWal ) pWal->mxWalSize = iLimit;\n}\n\n/*\n** Find the smallest page number out of all pages held in the WAL that\n** has not been returned by any prior invocation of this method on the\n** same WalIterator object.   Write into *piFrame the frame index where\n** that page was last written into the WAL.  Write into *piPage the page\n** number.\n**\n** Return 0 on success.  If there are no pages in the WAL with a page\n** number larger than *piPage, then return 1.\n*/\nstatic int walIteratorNext(\n  WalIterator *p,               /* Iterator */\n  u32 *piPage,                  /* OUT: The page number of the next page */\n  u32 *piFrame                  /* OUT: Wal frame index of next page */\n){\n  u32 iMin;                     /* Result pgno must be greater than iMin */\n  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */\n  int i;                        /* For looping through segments */\n\n  iMin = p->iPrior;\n  assert( iMin<0xffffffff );\n  for(i=p->nSegment-1; i>=0; i--){\n    struct WalSegment *pSegment = &p->aSegment[i];\n    while( pSegment->iNext<pSegment->nEntry ){\n      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];\n      if( iPg>iMin ){\n        if( iPg<iRet ){\n          iRet = iPg;\n          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];\n        }\n        break;\n      }\n      pSegment->iNext++;\n    }\n  }\n\n  *piPage = p->iPrior = iRet;\n  return (iRet==0xFFFFFFFF);\n}\n\n/*\n** This function merges two sorted lists into a single sorted list.\n**\n** aLeft[] and aRight[] are arrays of indices.  The sort key is\n** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following\n** is guaranteed for all J<K:\n**\n**        aContent[aLeft[J]] < aContent[aLeft[K]]\n**        aContent[aRight[J]] < aContent[aRight[K]]\n**\n** This routine overwrites aRight[] with a new (probably longer) sequence\n** of indices such that the aRight[] contains every index that appears in\n** either aLeft[] or the old aRight[] and such that the second condition\n** above is still met.\n**\n** The aContent[aLeft[X]] values will be unique for all X.  And the\n** aContent[aRight[X]] values will be unique too.  But there might be\n** one or more combinations of X and Y such that\n**\n**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]\n**\n** When that happens, omit the aLeft[X] and use the aRight[Y] index.\n*/\nstatic void walMerge(\n  const u32 *aContent,            /* Pages in wal - keys for the sort */\n  ht_slot *aLeft,                 /* IN: Left hand input list */\n  int nLeft,                      /* IN: Elements in array *paLeft */\n  ht_slot **paRight,              /* IN/OUT: Right hand input list */\n  int *pnRight,                   /* IN/OUT: Elements in *paRight */\n  ht_slot *aTmp                   /* Temporary buffer */\n){\n  int iLeft = 0;                  /* Current index in aLeft */\n  int iRight = 0;                 /* Current index in aRight */\n  int iOut = 0;                   /* Current index in output buffer */\n  int nRight = *pnRight;\n  ht_slot *aRight = *paRight;\n\n  assert( nLeft>0 && nRight>0 );\n  while( iRight<nRight || iLeft<nLeft ){\n    ht_slot logpage;\n    Pgno dbpage;\n\n    if( (iLeft<nLeft) \n     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])\n    ){\n      logpage = aLeft[iLeft++];\n    }else{\n      logpage = aRight[iRight++];\n    }\n    dbpage = aContent[logpage];\n\n    aTmp[iOut++] = logpage;\n    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;\n\n    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );\n    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );\n  }\n\n  *paRight = aLeft;\n  *pnRight = iOut;\n  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);\n}\n\n/*\n** Sort the elements in list aList using aContent[] as the sort key.\n** Remove elements with duplicate keys, preferring to keep the\n** larger aList[] values.\n**\n** The aList[] entries are indices into aContent[].  The values in\n** aList[] are to be sorted so that for all J<K:\n**\n**      aContent[aList[J]] < aContent[aList[K]]\n**\n** For any X and Y such that\n**\n**      aContent[aList[X]] == aContent[aList[Y]]\n**\n** Keep the larger of the two values aList[X] and aList[Y] and discard\n** the smaller.\n*/\nstatic void walMergesort(\n  const u32 *aContent,            /* Pages in wal */\n  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */\n  ht_slot *aList,                 /* IN/OUT: List to sort */\n  int *pnList                     /* IN/OUT: Number of elements in aList[] */\n){\n  struct Sublist {\n    int nList;                    /* Number of elements in aList */\n    ht_slot *aList;               /* Pointer to sub-list content */\n  };\n\n  const int nList = *pnList;      /* Size of input list */\n  int nMerge = 0;                 /* Number of elements in list aMerge */\n  ht_slot *aMerge = 0;            /* List to be merged */\n  int iList;                      /* Index into input list */\n  int iSub = 0;                   /* Index into aSub array */\n  struct Sublist aSub[13];        /* Array of sub-lists */\n\n  memset(aSub, 0, sizeof(aSub));\n  assert( nList<=HASHTABLE_NPAGE && nList>0 );\n  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );\n\n  for(iList=0; iList<nList; iList++){\n    nMerge = 1;\n    aMerge = &aList[iList];\n    for(iSub=0; iList & (1<<iSub); iSub++){\n      struct Sublist *p = &aSub[iSub];\n      assert( p->aList && p->nList<=(1<<iSub) );\n      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );\n      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);\n    }\n    aSub[iSub].aList = aMerge;\n    aSub[iSub].nList = nMerge;\n  }\n\n  for(iSub++; iSub<ArraySize(aSub); iSub++){\n    if( nList & (1<<iSub) ){\n      struct Sublist *p = &aSub[iSub];\n      assert( p->nList<=(1<<iSub) );\n      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );\n      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);\n    }\n  }\n  assert( aMerge==aList );\n  *pnList = nMerge;\n\n#ifdef SQLITE_DEBUG\n  {\n    int i;\n    for(i=1; i<*pnList; i++){\n      assert( aContent[aList[i]] > aContent[aList[i-1]] );\n    }\n  }\n#endif\n}\n\n/* \n** Free an iterator allocated by walIteratorInit().\n*/\nstatic void walIteratorFree(WalIterator *p){\n  sqlite3ScratchFree(p);\n}\n\n/*\n** Construct a WalInterator object that can be used to loop over all \n** pages in the WAL in ascending order. The caller must hold the checkpoint\n** lock.\n**\n** On success, make *pp point to the newly allocated WalInterator object\n** return SQLITE_OK. Otherwise, return an error code. If this routine\n** returns an error, the value of *pp is undefined.\n**\n** The calling routine should invoke walIteratorFree() to destroy the\n** WalIterator object when it has finished with it.\n*/\nstatic int walIteratorInit(Wal *pWal, WalIterator **pp){\n  WalIterator *p;                 /* Return value */\n  int nSegment;                   /* Number of segments to merge */\n  u32 iLast;                      /* Last frame in log */\n  int nByte;                      /* Number of bytes to allocate */\n  int i;                          /* Iterator variable */\n  ht_slot *aTmp;                  /* Temp space used by merge-sort */\n  int rc = SQLITE_OK;             /* Return Code */\n\n  /* This routine only runs while holding the checkpoint lock. And\n  ** it only runs if there is actually content in the log (mxFrame>0).\n  */\n  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );\n  iLast = pWal->hdr.mxFrame;\n\n  /* Allocate space for the WalIterator object. */\n  nSegment = walFramePage(iLast) + 1;\n  nByte = sizeof(WalIterator) \n        + (nSegment-1)*sizeof(struct WalSegment)\n        + iLast*sizeof(ht_slot);\n  p = (WalIterator *)sqlite3ScratchMalloc(nByte);\n  if( !p ){\n    return SQLITE_NOMEM;\n  }\n  memset(p, 0, nByte);\n  p->nSegment = nSegment;\n\n  /* Allocate temporary space used by the merge-sort routine. This block\n  ** of memory will be freed before this function returns.\n  */\n  aTmp = (ht_slot *)sqlite3ScratchMalloc(\n      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)\n  );\n  if( !aTmp ){\n    rc = SQLITE_NOMEM;\n  }\n\n  for(i=0; rc==SQLITE_OK && i<nSegment; i++){\n    volatile ht_slot *aHash;\n    u32 iZero;\n    volatile u32 *aPgno;\n\n    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);\n    if( rc==SQLITE_OK ){\n      int j;                      /* Counter variable */\n      int nEntry;                 /* Number of entries in this segment */\n      ht_slot *aIndex;            /* Sorted index for this segment */\n\n      aPgno++;\n      if( (i+1)==nSegment ){\n        nEntry = (int)(iLast - iZero);\n      }else{\n        nEntry = (int)((u32*)aHash - (u32*)aPgno);\n      }\n      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];\n      iZero++;\n  \n      for(j=0; j<nEntry; j++){\n        aIndex[j] = (ht_slot)j;\n      }\n      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);\n      p->aSegment[i].iZero = iZero;\n      p->aSegment[i].nEntry = nEntry;\n      p->aSegment[i].aIndex = aIndex;\n      p->aSegment[i].aPgno = (u32 *)aPgno;\n    }\n  }\n  sqlite3ScratchFree(aTmp);\n\n  if( rc!=SQLITE_OK ){\n    walIteratorFree(p);\n  }\n  *pp = p;\n  return rc;\n}\n\n/*\n** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and\n** n. If the attempt fails and parameter xBusy is not NULL, then it is a\n** busy-handler function. Invoke it and retry the lock until either the\n** lock is successfully obtained or the busy-handler returns 0.\n*/\nstatic int walBusyLock(\n  Wal *pWal,                      /* WAL connection */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int lockIdx,                    /* Offset of first byte to lock */\n  int n                           /* Number of bytes to lock */\n){\n  int rc;\n  do {\n    rc = walLockExclusive(pWal, lockIdx, n);\n  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );\n  return rc;\n}\n\n/*\n** The cache of the wal-index header must be valid to call this function.\n** Return the page-size in bytes used by the database.\n*/\nstatic int walPagesize(Wal *pWal){\n  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);\n}\n\n/*\n** Copy as much content as we can from the WAL back into the database file\n** in response to an sqlite3_wal_checkpoint() request or the equivalent.\n**\n** The amount of information copies from WAL to database might be limited\n** by active readers.  This routine will never overwrite a database page\n** that a concurrent reader might be using.\n**\n** All I/O barrier operations (a.k.a fsyncs) occur in this routine when\n** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if \n** checkpoints are always run by a background thread or background \n** process, foreground threads will never block on a lengthy fsync call.\n**\n** Fsync is called on the WAL before writing content out of the WAL and\n** into the database.  This ensures that if the new content is persistent\n** in the WAL and can be recovered following a power-loss or hard reset.\n**\n** Fsync is also called on the database file if (and only if) the entire\n** WAL content is copied into the database file.  This second fsync makes\n** it safe to delete the WAL since the new content will persist in the\n** database file.\n**\n** This routine uses and updates the nBackfill field of the wal-index header.\n** This is the only routine tha will increase the value of nBackfill.  \n** (A WAL reset or recovery will revert nBackfill to zero, but not increase\n** its value.)\n**\n** The caller must be holding sufficient locks to ensure that no other\n** checkpoint is running (in any other thread or process) at the same\n** time.\n*/\nstatic int walCheckpoint(\n  Wal *pWal,                      /* Wal connection */\n  int eMode,                      /* One of PASSIVE, FULL or RESTART */\n  int (*xBusyCall)(void*),        /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags for OsSync() (or 0) */\n  u8 *zBuf                        /* Temporary buffer to use */\n){\n  int rc;                         /* Return code */\n  int szPage;                     /* Database page-size */\n  WalIterator *pIter = 0;         /* Wal iterator context */\n  u32 iDbpage = 0;                /* Next database page to write */\n  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */\n  u32 mxSafeFrame;                /* Max frame that can be backfilled */\n  u32 mxPage;                     /* Max database page to write */\n  int i;                          /* Loop counter */\n  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */\n  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */\n\n  szPage = walPagesize(pWal);\n  testcase( szPage<=32768 );\n  testcase( szPage>=65536 );\n  pInfo = walCkptInfo(pWal);\n  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;\n\n  /* Allocate the iterator */\n  rc = walIteratorInit(pWal, &pIter);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  assert( pIter );\n\n  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;\n\n  /* Compute in mxSafeFrame the index of the last frame of the WAL that is\n  ** safe to write into the database.  Frames beyond mxSafeFrame might\n  ** overwrite database pages that are in use by active readers and thus\n  ** cannot be backfilled from the WAL.\n  */\n  mxSafeFrame = pWal->hdr.mxFrame;\n  mxPage = pWal->hdr.nPage;\n  for(i=1; i<WAL_NREADER; i++){\n    u32 y = pInfo->aReadMark[i];\n    if( mxSafeFrame>y ){\n      assert( y<=pWal->hdr.mxFrame );\n      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);\n      if( rc==SQLITE_OK ){\n        pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);\n        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);\n      }else if( rc==SQLITE_BUSY ){\n        mxSafeFrame = y;\n        xBusy = 0;\n      }else{\n        goto walcheckpoint_out;\n      }\n    }\n  }\n\n  if( pInfo->nBackfill<mxSafeFrame\n   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK\n  ){\n    i64 nSize;                    /* Current size of database file */\n    u32 nBackfill = pInfo->nBackfill;\n\n    /* Sync the WAL to disk */\n    if( sync_flags ){\n      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);\n    }\n\n    /* If the database file may grow as a result of this checkpoint, hint\n    ** about the eventual size of the db file to the VFS layer. \n    */\n    if( rc==SQLITE_OK ){\n      i64 nReq = ((i64)mxPage * szPage);\n      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);\n      if( rc==SQLITE_OK && nSize<nReq ){\n        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);\n      }\n    }\n\n    /* Iterate through the contents of the WAL, copying data to the db file. */\n    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){\n      i64 iOffset;\n      assert( walFramePgno(pWal, iFrame)==iDbpage );\n      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;\n      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;\n      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */\n      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);\n      if( rc!=SQLITE_OK ) break;\n      iOffset = (iDbpage-1)*(i64)szPage;\n      testcase( IS_BIG_INT(iOffset) );\n      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);\n      if( rc!=SQLITE_OK ) break;\n    }\n\n    /* If work was actually accomplished... */\n    if( rc==SQLITE_OK ){\n      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){\n        i64 szDb = pWal->hdr.nPage*(i64)szPage;\n        testcase( IS_BIG_INT(szDb) );\n        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);\n        if( rc==SQLITE_OK && sync_flags ){\n          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);\n        }\n      }\n      if( rc==SQLITE_OK ){\n        pInfo->nBackfill = mxSafeFrame;\n      }\n    }\n\n    /* Release the reader lock held while backfilling */\n    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);\n  }\n\n  if( rc==SQLITE_BUSY ){\n    /* Reset the return code so as not to report a checkpoint failure\n    ** just because there are active readers.  */\n    rc = SQLITE_OK;\n  }\n\n  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal\n  ** file has been copied into the database file, then block until all\n  ** readers have finished using the wal file. This ensures that the next\n  ** process to write to the database restarts the wal file.\n  */\n  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){\n    assert( pWal->writeLock );\n    if( pInfo->nBackfill<pWal->hdr.mxFrame ){\n      rc = SQLITE_BUSY;\n    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){\n      assert( mxSafeFrame==pWal->hdr.mxFrame );\n      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);\n      if( rc==SQLITE_OK ){\n        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      }\n    }\n  }\n\n walcheckpoint_out:\n  walIteratorFree(pIter);\n  return rc;\n}\n\n/*\n** If the WAL file is currently larger than nMax bytes in size, truncate\n** it to exactly nMax bytes. If an error occurs while doing so, ignore it.\n*/\nstatic void walLimitSize(Wal *pWal, i64 nMax){\n  i64 sz;\n  int rx;\n  sqlite3BeginBenignMalloc();\n  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);\n  if( rx==SQLITE_OK && (sz > nMax ) ){\n    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);\n  }\n  sqlite3EndBenignMalloc();\n  if( rx ){\n    sqlite3_log(rx, \"cannot limit WAL size: %s\", pWal->zWalName);\n  }\n}\n\n/*\n** Close a connection to a log file.\n*/\nSQLITE_PRIVATE int sqlite3WalClose(\n  Wal *pWal,                      /* Wal to close */\n  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */\n  int nBuf,\n  u8 *zBuf                        /* Buffer of at least nBuf bytes */\n){\n  int rc = SQLITE_OK;\n  if( pWal ){\n    int isDelete = 0;             /* True to unlink wal and wal-index files */\n\n    /* If an EXCLUSIVE lock can be obtained on the database file (using the\n    ** ordinary, rollback-mode locking methods, this guarantees that the\n    ** connection associated with this log file is the only connection to\n    ** the database. In this case checkpoint the database and unlink both\n    ** the wal and wal-index files.\n    **\n    ** The EXCLUSIVE lock is not released before returning.\n    */\n    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);\n    if( rc==SQLITE_OK ){\n      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){\n        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;\n      }\n      rc = sqlite3WalCheckpoint(\n          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0\n      );\n      if( rc==SQLITE_OK ){\n        int bPersist = -1;\n        sqlite3OsFileControlHint(\n            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist\n        );\n        if( bPersist!=1 ){\n          /* Try to delete the WAL file if the checkpoint completed and\n          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal\n          ** mode (!bPersist) */\n          isDelete = 1;\n        }else if( pWal->mxWalSize>=0 ){\n          /* Try to truncate the WAL file to zero bytes if the checkpoint\n          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent\n          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a\n          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate\n          ** to zero bytes as truncating to the journal_size_limit might\n          ** leave a corrupt WAL file on disk. */\n          walLimitSize(pWal, 0);\n        }\n      }\n    }\n\n    walIndexClose(pWal, isDelete);\n    sqlite3OsClose(pWal->pWalFd);\n    if( isDelete ){\n      sqlite3BeginBenignMalloc();\n      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);\n      sqlite3EndBenignMalloc();\n    }\n    WALTRACE((\"WAL%p: closed\\n\", pWal));\n    sqlite3_free((void *)pWal->apWiData);\n    sqlite3_free(pWal);\n  }\n  return rc;\n}\n\n/*\n** Try to read the wal-index header.  Return 0 on success and 1 if\n** there is a problem.\n**\n** The wal-index is in shared memory.  Another thread or process might\n** be writing the header at the same time this procedure is trying to\n** read it, which might result in inconsistency.  A dirty read is detected\n** by verifying that both copies of the header are the same and also by\n** a checksum on the header.\n**\n** If and only if the read is consistent and the header is different from\n** pWal->hdr, then pWal->hdr is updated to the content of the new header\n** and *pChanged is set to 1.\n**\n** If the checksum cannot be verified return non-zero. If the header\n** is read successfully and the checksum verified, return zero.\n*/\nstatic int walIndexTryHdr(Wal *pWal, int *pChanged){\n  u32 aCksum[2];                  /* Checksum on the header content */\n  WalIndexHdr h1, h2;             /* Two copies of the header content */\n  WalIndexHdr volatile *aHdr;     /* Header in shared memory */\n\n  /* The first page of the wal-index must be mapped at this point. */\n  assert( pWal->nWiData>0 && pWal->apWiData[0] );\n\n  /* Read the header. This might happen concurrently with a write to the\n  ** same area of shared memory on a different CPU in a SMP,\n  ** meaning it is possible that an inconsistent snapshot is read\n  ** from the file. If this happens, return non-zero.\n  **\n  ** There are two copies of the header at the beginning of the wal-index.\n  ** When reading, read [0] first then [1].  Writes are in the reverse order.\n  ** Memory barriers are used to prevent the compiler or the hardware from\n  ** reordering the reads and writes.\n  */\n  aHdr = walIndexHdr(pWal);\n  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));\n  walShmBarrier(pWal);\n  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));\n\n  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){\n    return 1;   /* Dirty read */\n  }  \n  if( h1.isInit==0 ){\n    return 1;   /* Malformed header - probably all zeros */\n  }\n  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);\n  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){\n    return 1;   /* Checksum does not match */\n  }\n\n  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){\n    *pChanged = 1;\n    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));\n    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);\n    testcase( pWal->szPage<=32768 );\n    testcase( pWal->szPage>=65536 );\n  }\n\n  /* The header was successfully read. Return zero. */\n  return 0;\n}\n\n/*\n** Read the wal-index header from the wal-index and into pWal->hdr.\n** If the wal-header appears to be corrupt, try to reconstruct the\n** wal-index from the WAL before returning.\n**\n** Set *pChanged to 1 if the wal-index header value in pWal->hdr is\n** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged\n** to 0.\n**\n** If the wal-index header is successfully read, return SQLITE_OK. \n** Otherwise an SQLite error code.\n*/\nstatic int walIndexReadHdr(Wal *pWal, int *pChanged){\n  int rc;                         /* Return code */\n  int badHdr;                     /* True if a header read failed */\n  volatile u32 *page0;            /* Chunk of wal-index containing header */\n\n  /* Ensure that page 0 of the wal-index (the page that contains the \n  ** wal-index header) is mapped. Return early if an error occurs here.\n  */\n  assert( pChanged );\n  rc = walIndexPage(pWal, 0, &page0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  };\n  assert( page0 || pWal->writeLock==0 );\n\n  /* If the first page of the wal-index has been mapped, try to read the\n  ** wal-index header immediately, without holding any lock. This usually\n  ** works, but may fail if the wal-index header is corrupt or currently \n  ** being modified by another thread or process.\n  */\n  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);\n\n  /* If the first attempt failed, it might have been due to a race\n  ** with a writer.  So get a WRITE lock and try again.\n  */\n  assert( badHdr==0 || pWal->writeLock==0 );\n  if( badHdr ){\n    if( pWal->readOnly & WAL_SHM_RDONLY ){\n      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){\n        walUnlockShared(pWal, WAL_WRITE_LOCK);\n        rc = SQLITE_READONLY_RECOVERY;\n      }\n    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){\n      pWal->writeLock = 1;\n      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){\n        badHdr = walIndexTryHdr(pWal, pChanged);\n        if( badHdr ){\n          /* If the wal-index header is still malformed even while holding\n          ** a WRITE lock, it can only mean that the header is corrupted and\n          ** needs to be reconstructed.  So run recovery to do exactly that.\n          */\n          rc = walIndexRecover(pWal);\n          *pChanged = 1;\n        }\n      }\n      pWal->writeLock = 0;\n      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    }\n  }\n\n  /* If the header is read successfully, check the version number to make\n  ** sure the wal-index was not constructed with some future format that\n  ** this version of SQLite cannot understand.\n  */\n  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){\n    rc = SQLITE_CANTOPEN_BKPT;\n  }\n\n  return rc;\n}\n\n/*\n** This is the value that walTryBeginRead returns when it needs to\n** be retried.\n*/\n#define WAL_RETRY  (-1)\n\n/*\n** Attempt to start a read transaction.  This might fail due to a race or\n** other transient condition.  When that happens, it returns WAL_RETRY to\n** indicate to the caller that it is safe to retry immediately.\n**\n** On success return SQLITE_OK.  On a permanent failure (such an\n** I/O error or an SQLITE_BUSY because another process is running\n** recovery) return a positive error code.\n**\n** The useWal parameter is true to force the use of the WAL and disable\n** the case where the WAL is bypassed because it has been completely\n** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() \n** to make a copy of the wal-index header into pWal->hdr.  If the \n** wal-index header has changed, *pChanged is set to 1 (as an indication \n** to the caller that the local paget cache is obsolete and needs to be \n** flushed.)  When useWal==1, the wal-index header is assumed to already\n** be loaded and the pChanged parameter is unused.\n**\n** The caller must set the cnt parameter to the number of prior calls to\n** this routine during the current read attempt that returned WAL_RETRY.\n** This routine will start taking more aggressive measures to clear the\n** race conditions after multiple WAL_RETRY returns, and after an excessive\n** number of errors will ultimately return SQLITE_PROTOCOL.  The\n** SQLITE_PROTOCOL return indicates that some other process has gone rogue\n** and is not honoring the locking protocol.  There is a vanishingly small\n** chance that SQLITE_PROTOCOL could be returned because of a run of really\n** bad luck when there is lots of contention for the wal-index, but that\n** possibility is so small that it can be safely neglected, we believe.\n**\n** On success, this routine obtains a read lock on \n** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is\n** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)\n** that means the Wal does not hold any read lock.  The reader must not\n** access any database page that is modified by a WAL frame up to and\n** including frame number aReadMark[pWal->readLock].  The reader will\n** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0\n** Or if pWal->readLock==0, then the reader will ignore the WAL\n** completely and get all content directly from the database file.\n** If the useWal parameter is 1 then the WAL will never be ignored and\n** this routine will always set pWal->readLock>0 on success.\n** When the read transaction is completed, the caller must release the\n** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.\n**\n** This routine uses the nBackfill and aReadMark[] fields of the header\n** to select a particular WAL_READ_LOCK() that strives to let the\n** checkpoint process do as much work as possible.  This routine might\n** update values of the aReadMark[] array in the header, but if it does\n** so it takes care to hold an exclusive lock on the corresponding\n** WAL_READ_LOCK() while changing values.\n*/\nstatic int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){\n  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */\n  u32 mxReadMark;                 /* Largest aReadMark[] value */\n  int mxI;                        /* Index of largest aReadMark[] value */\n  int i;                          /* Loop counter */\n  int rc = SQLITE_OK;             /* Return code  */\n\n  assert( pWal->readLock<0 );     /* Not currently locked */\n\n  /* Take steps to avoid spinning forever if there is a protocol error.\n  **\n  ** Circumstances that cause a RETRY should only last for the briefest\n  ** instances of time.  No I/O or other system calls are done while the\n  ** locks are held, so the locks should not be held for very long. But \n  ** if we are unlucky, another process that is holding a lock might get\n  ** paged out or take a page-fault that is time-consuming to resolve, \n  ** during the few nanoseconds that it is holding the lock.  In that case,\n  ** it might take longer than normal for the lock to free.\n  **\n  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few\n  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this\n  ** is more of a scheduler yield than an actual delay.  But on the 10th\n  ** an subsequent retries, the delays start becoming longer and longer, \n  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.\n  ** The total delay time before giving up is less than 1 second.\n  */\n  if( cnt>5 ){\n    int nDelay = 1;                      /* Pause time in microseconds */\n    if( cnt>100 ){\n      VVA_ONLY( pWal->lockError = 1; )\n      return SQLITE_PROTOCOL;\n    }\n    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */\n    sqlite3OsSleep(pWal->pVfs, nDelay);\n  }\n\n  if( !useWal ){\n    rc = walIndexReadHdr(pWal, pChanged);\n    if( rc==SQLITE_BUSY ){\n      /* If there is not a recovery running in another thread or process\n      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to\n      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here\n      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY\n      ** would be technically correct.  But the race is benign since with\n      ** WAL_RETRY this routine will be called again and will probably be\n      ** right on the second iteration.\n      */\n      if( pWal->apWiData[0]==0 ){\n        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.\n        ** We assume this is a transient condition, so return WAL_RETRY. The\n        ** xShmMap() implementation used by the default unix and win32 VFS \n        ** modules may return SQLITE_BUSY due to a race condition in the \n        ** code that determines whether or not the shared-memory region \n        ** must be zeroed before the requested page is returned.\n        */\n        rc = WAL_RETRY;\n      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){\n        walUnlockShared(pWal, WAL_RECOVER_LOCK);\n        rc = WAL_RETRY;\n      }else if( rc==SQLITE_BUSY ){\n        rc = SQLITE_BUSY_RECOVERY;\n      }\n    }\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n  }\n\n  pInfo = walCkptInfo(pWal);\n  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){\n    /* The WAL has been completely backfilled (or it is empty).\n    ** and can be safely ignored.\n    */\n    rc = walLockShared(pWal, WAL_READ_LOCK(0));\n    walShmBarrier(pWal);\n    if( rc==SQLITE_OK ){\n      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){\n        /* It is not safe to allow the reader to continue here if frames\n        ** may have been appended to the log before READ_LOCK(0) was obtained.\n        ** When holding READ_LOCK(0), the reader ignores the entire log file,\n        ** which implies that the database file contains a trustworthy\n        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from\n        ** happening, this is usually correct.\n        **\n        ** However, if frames have been appended to the log (or if the log \n        ** is wrapped and written for that matter) before the READ_LOCK(0)\n        ** is obtained, that is not necessarily true. A checkpointer may\n        ** have started to backfill the appended frames but crashed before\n        ** it finished. Leaving a corrupt image in the database file.\n        */\n        walUnlockShared(pWal, WAL_READ_LOCK(0));\n        return WAL_RETRY;\n      }\n      pWal->readLock = 0;\n      return SQLITE_OK;\n    }else if( rc!=SQLITE_BUSY ){\n      return rc;\n    }\n  }\n\n  /* If we get this far, it means that the reader will want to use\n  ** the WAL to get at content from recent commits.  The job now is\n  ** to select one of the aReadMark[] entries that is closest to\n  ** but not exceeding pWal->hdr.mxFrame and lock that entry.\n  */\n  mxReadMark = 0;\n  mxI = 0;\n  for(i=1; i<WAL_NREADER; i++){\n    u32 thisMark = pInfo->aReadMark[i];\n    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){\n      assert( thisMark!=READMARK_NOT_USED );\n      mxReadMark = thisMark;\n      mxI = i;\n    }\n  }\n  /* There was once an \"if\" here. The extra \"{\" is to preserve indentation. */\n  {\n    if( (pWal->readOnly & WAL_SHM_RDONLY)==0\n     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)\n    ){\n      for(i=1; i<WAL_NREADER; i++){\n        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);\n        if( rc==SQLITE_OK ){\n          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;\n          mxI = i;\n          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);\n          break;\n        }else if( rc!=SQLITE_BUSY ){\n          return rc;\n        }\n      }\n    }\n    if( mxI==0 ){\n      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );\n      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;\n    }\n\n    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));\n    if( rc ){\n      return rc==SQLITE_BUSY ? WAL_RETRY : rc;\n    }\n    /* Now that the read-lock has been obtained, check that neither the\n    ** value in the aReadMark[] array or the contents of the wal-index\n    ** header have changed.\n    **\n    ** It is necessary to check that the wal-index header did not change\n    ** between the time it was read and when the shared-lock was obtained\n    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility\n    ** that the log file may have been wrapped by a writer, or that frames\n    ** that occur later in the log than pWal->hdr.mxFrame may have been\n    ** copied into the database by a checkpointer. If either of these things\n    ** happened, then reading the database with the current value of\n    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry\n    ** instead.\n    **\n    ** This does not guarantee that the copy of the wal-index header is up to\n    ** date before proceeding. That would not be possible without somehow\n    ** blocking writers. It only guarantees that a dangerous checkpoint or \n    ** log-wrap (either of which would require an exclusive lock on\n    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.\n    */\n    walShmBarrier(pWal);\n    if( pInfo->aReadMark[mxI]!=mxReadMark\n     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))\n    ){\n      walUnlockShared(pWal, WAL_READ_LOCK(mxI));\n      return WAL_RETRY;\n    }else{\n      assert( mxReadMark<=pWal->hdr.mxFrame );\n      pWal->readLock = (i16)mxI;\n    }\n  }\n  return rc;\n}\n\n/*\n** Begin a read transaction on the database.\n**\n** This routine used to be called sqlite3OpenSnapshot() and with good reason:\n** it takes a snapshot of the state of the WAL and wal-index for the current\n** instant in time.  The current thread will continue to use this snapshot.\n** Other threads might append new content to the WAL and wal-index but\n** that extra content is ignored by the current thread.\n**\n** If the database contents have changes since the previous read\n** transaction, then *pChanged is set to 1 before returning.  The\n** Pager layer will use this to know that is cache is stale and\n** needs to be flushed.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){\n  int rc;                         /* Return code */\n  int cnt = 0;                    /* Number of TryBeginRead attempts */\n\n  do{\n    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);\n  }while( rc==WAL_RETRY );\n  testcase( (rc&0xff)==SQLITE_BUSY );\n  testcase( (rc&0xff)==SQLITE_IOERR );\n  testcase( rc==SQLITE_PROTOCOL );\n  testcase( rc==SQLITE_OK );\n  return rc;\n}\n\n/*\n** Finish with a read transaction.  All this does is release the\n** read-lock.\n*/\nSQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){\n  sqlite3WalEndWriteTransaction(pWal);\n  if( pWal->readLock>=0 ){\n    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));\n    pWal->readLock = -1;\n  }\n}\n\n/*\n** Read a page from the WAL, if it is present in the WAL and if the \n** current read transaction is configured to use the WAL.  \n**\n** The *pInWal is set to 1 if the requested page is in the WAL and\n** has been loaded.  Or *pInWal is set to 0 if the page was not in \n** the WAL and needs to be read out of the database.\n*/\nSQLITE_PRIVATE int sqlite3WalRead(\n  Wal *pWal,                      /* WAL handle */\n  Pgno pgno,                      /* Database page number to read data for */\n  int *pInWal,                    /* OUT: True if data is read from WAL */\n  int nOut,                       /* Size of buffer pOut in bytes */\n  u8 *pOut                        /* Buffer to write page data to */\n){\n  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */\n  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */\n  int iHash;                      /* Used to loop through N hash tables */\n\n  /* This routine is only be called from within a read transaction. */\n  assert( pWal->readLock>=0 || pWal->lockError );\n\n  /* If the \"last page\" field of the wal-index header snapshot is 0, then\n  ** no data will be read from the wal under any circumstances. Return early\n  ** in this case as an optimization.  Likewise, if pWal->readLock==0, \n  ** then the WAL is ignored by the reader so return early, as if the \n  ** WAL were empty.\n  */\n  if( iLast==0 || pWal->readLock==0 ){\n    *pInWal = 0;\n    return SQLITE_OK;\n  }\n\n  /* Search the hash table or tables for an entry matching page number\n  ** pgno. Each iteration of the following for() loop searches one\n  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).\n  **\n  ** This code might run concurrently to the code in walIndexAppend()\n  ** that adds entries to the wal-index (and possibly to this hash \n  ** table). This means the value just read from the hash \n  ** slot (aHash[iKey]) may have been added before or after the \n  ** current read transaction was opened. Values added after the\n  ** read transaction was opened may have been written incorrectly -\n  ** i.e. these slots may contain garbage data. However, we assume\n  ** that any slots written before the current read transaction was\n  ** opened remain unmodified.\n  **\n  ** For the reasons above, the if(...) condition featured in the inner\n  ** loop of the following block is more stringent that would be required \n  ** if we had exclusive access to the hash-table:\n  **\n  **   (aPgno[iFrame]==pgno): \n  **     This condition filters out normal hash-table collisions.\n  **\n  **   (iFrame<=iLast): \n  **     This condition filters out entries that were added to the hash\n  **     table after the current read-transaction had started.\n  */\n  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){\n    volatile ht_slot *aHash;      /* Pointer to hash table */\n    volatile u32 *aPgno;          /* Pointer to array of page numbers */\n    u32 iZero;                    /* Frame number corresponding to aPgno[0] */\n    int iKey;                     /* Hash slot index */\n    int nCollide;                 /* Number of hash collisions remaining */\n    int rc;                       /* Error code */\n\n    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    nCollide = HASHTABLE_NSLOT;\n    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){\n      u32 iFrame = aHash[iKey] + iZero;\n      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){\n        /* assert( iFrame>iRead ); -- not true if there is corruption */\n        iRead = iFrame;\n      }\n      if( (nCollide--)==0 ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n    }\n  }\n\n#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT\n  /* If expensive assert() statements are available, do a linear search\n  ** of the wal-index file content. Make sure the results agree with the\n  ** result obtained using the hash indexes above.  */\n  {\n    u32 iRead2 = 0;\n    u32 iTest;\n    for(iTest=iLast; iTest>0; iTest--){\n      if( walFramePgno(pWal, iTest)==pgno ){\n        iRead2 = iTest;\n        break;\n      }\n    }\n    assert( iRead==iRead2 );\n  }\n#endif\n\n  /* If iRead is non-zero, then it is the log frame number that contains the\n  ** required page. Read and return data from the log file.\n  */\n  if( iRead ){\n    int sz;\n    i64 iOffset;\n    sz = pWal->hdr.szPage;\n    sz = (sz&0xfe00) + ((sz&0x0001)<<16);\n    testcase( sz<=32768 );\n    testcase( sz>=65536 );\n    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;\n    *pInWal = 1;\n    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */\n    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);\n  }\n\n  *pInWal = 0;\n  return SQLITE_OK;\n}\n\n\n/* \n** Return the size of the database in pages (or zero, if unknown).\n*/\nSQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){\n  if( pWal && ALWAYS(pWal->readLock>=0) ){\n    return pWal->hdr.nPage;\n  }\n  return 0;\n}\n\n\n/* \n** This function starts a write transaction on the WAL.\n**\n** A read transaction must have already been started by a prior call\n** to sqlite3WalBeginReadTransaction().\n**\n** If another thread or process has written into the database since\n** the read transaction was started, then it is not possible for this\n** thread to write as doing so would cause a fork.  So this routine\n** returns SQLITE_BUSY in that case and no write transaction is started.\n**\n** There can only be a single writer active at a time.\n*/\nSQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){\n  int rc;\n\n  /* Cannot start a write transaction without first holding a read\n  ** transaction. */\n  assert( pWal->readLock>=0 );\n\n  if( pWal->readOnly ){\n    return SQLITE_READONLY;\n  }\n\n  /* Only one writer allowed at a time.  Get the write lock.  Return\n  ** SQLITE_BUSY if unable.\n  */\n  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);\n  if( rc ){\n    return rc;\n  }\n  pWal->writeLock = 1;\n\n  /* If another connection has written to the database file since the\n  ** time the read transaction on this connection was started, then\n  ** the write is disallowed.\n  */\n  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){\n    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    pWal->writeLock = 0;\n    rc = SQLITE_BUSY;\n  }\n\n  return rc;\n}\n\n/*\n** End a write transaction.  The commit has already been done.  This\n** routine merely releases the lock.\n*/\nSQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){\n  if( pWal->writeLock ){\n    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);\n    pWal->writeLock = 0;\n    pWal->truncateOnCommit = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** If any data has been written (but not committed) to the log file, this\n** function moves the write-pointer back to the start of the transaction.\n**\n** Additionally, the callback function is invoked for each frame written\n** to the WAL since the start of the transaction. If the callback returns\n** other than SQLITE_OK, it is not invoked again and the error code is\n** returned to the caller.\n**\n** Otherwise, if the callback function does not return an error, this\n** function returns SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){\n  int rc = SQLITE_OK;\n  if( ALWAYS(pWal->writeLock) ){\n    Pgno iMax = pWal->hdr.mxFrame;\n    Pgno iFrame;\n  \n    /* Restore the clients cache of the wal-index header to the state it\n    ** was in before the client began writing to the database. \n    */\n    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));\n\n    for(iFrame=pWal->hdr.mxFrame+1; \n        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; \n        iFrame++\n    ){\n      /* This call cannot fail. Unless the page for which the page number\n      ** is passed as the second argument is (a) in the cache and \n      ** (b) has an outstanding reference, then xUndo is either a no-op\n      ** (if (a) is false) or simply expels the page from the cache (if (b)\n      ** is false).\n      **\n      ** If the upper layer is doing a rollback, it is guaranteed that there\n      ** are no outstanding references to any page other than page 1. And\n      ** page 1 is never written to the log until the transaction is\n      ** committed. As a result, the call to xUndo may not fail.\n      */\n      assert( walFramePgno(pWal, iFrame)!=1 );\n      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));\n    }\n    walCleanupHash(pWal);\n  }\n  assert( rc==SQLITE_OK );\n  return rc;\n}\n\n/* \n** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 \n** values. This function populates the array with values required to \n** \"rollback\" the write position of the WAL handle back to the current \n** point in the event of a savepoint rollback (via WalSavepointUndo()).\n*/\nSQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){\n  assert( pWal->writeLock );\n  aWalData[0] = pWal->hdr.mxFrame;\n  aWalData[1] = pWal->hdr.aFrameCksum[0];\n  aWalData[2] = pWal->hdr.aFrameCksum[1];\n  aWalData[3] = pWal->nCkpt;\n}\n\n/* \n** Move the write position of the WAL back to the point identified by\n** the values in the aWalData[] array. aWalData must point to an array\n** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated\n** by a call to WalSavepoint().\n*/\nSQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){\n  int rc = SQLITE_OK;\n\n  assert( pWal->writeLock );\n  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );\n\n  if( aWalData[3]!=pWal->nCkpt ){\n    /* This savepoint was opened immediately after the write-transaction\n    ** was started. Right after that, the writer decided to wrap around\n    ** to the start of the log. Update the savepoint values to match.\n    */\n    aWalData[0] = 0;\n    aWalData[3] = pWal->nCkpt;\n  }\n\n  if( aWalData[0]<pWal->hdr.mxFrame ){\n    pWal->hdr.mxFrame = aWalData[0];\n    pWal->hdr.aFrameCksum[0] = aWalData[1];\n    pWal->hdr.aFrameCksum[1] = aWalData[2];\n    walCleanupHash(pWal);\n  }\n\n  return rc;\n}\n\n\n/*\n** This function is called just before writing a set of frames to the log\n** file (see sqlite3WalFrames()). It checks to see if, instead of appending\n** to the current log file, it is possible to overwrite the start of the\n** existing log file with the new frames (i.e. \"reset\" the log). If so,\n** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left\n** unchanged.\n**\n** SQLITE_OK is returned if no error is encountered (regardless of whether\n** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned\n** if an error occurs.\n*/\nstatic int walRestartLog(Wal *pWal){\n  int rc = SQLITE_OK;\n  int cnt;\n\n  if( pWal->readLock==0 ){\n    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);\n    assert( pInfo->nBackfill==pWal->hdr.mxFrame );\n    if( pInfo->nBackfill>0 ){\n      u32 salt1;\n      sqlite3_randomness(4, &salt1);\n      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      if( rc==SQLITE_OK ){\n        /* If all readers are using WAL_READ_LOCK(0) (in other words if no\n        ** readers are currently using the WAL), then the transactions\n        ** frames will overwrite the start of the existing log. Update the\n        ** wal-index header to reflect this.\n        **\n        ** In theory it would be Ok to update the cache of the header only\n        ** at this point. But updating the actual wal-index header is also\n        ** safe and means there is no special case for sqlite3WalUndo()\n        ** to handle if this transaction is rolled back.\n        */\n        int i;                    /* Loop counter */\n        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */\n\n        pWal->nCkpt++;\n        pWal->hdr.mxFrame = 0;\n        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));\n        aSalt[1] = salt1;\n        walIndexWriteHdr(pWal);\n        pInfo->nBackfill = 0;\n        pInfo->aReadMark[1] = 0;\n        for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;\n        assert( pInfo->aReadMark[0]==0 );\n        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);\n      }else if( rc!=SQLITE_BUSY ){\n        return rc;\n      }\n    }\n    walUnlockShared(pWal, WAL_READ_LOCK(0));\n    pWal->readLock = -1;\n    cnt = 0;\n    do{\n      int notUsed;\n      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);\n    }while( rc==WAL_RETRY );\n    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */\n    testcase( (rc&0xff)==SQLITE_IOERR );\n    testcase( rc==SQLITE_PROTOCOL );\n    testcase( rc==SQLITE_OK );\n  }\n  return rc;\n}\n\n/*\n** Information about the current state of the WAL file and where\n** the next fsync should occur - passed from sqlite3WalFrames() into\n** walWriteToLog().\n*/\ntypedef struct WalWriter {\n  Wal *pWal;                   /* The complete WAL information */\n  sqlite3_file *pFd;           /* The WAL file to which we write */\n  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */\n  int syncFlags;               /* Flags for the fsync */\n  int szPage;                  /* Size of one page */\n} WalWriter;\n\n/*\n** Write iAmt bytes of content into the WAL file beginning at iOffset.\n** Do a sync when crossing the p->iSyncPoint boundary.\n**\n** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,\n** first write the part before iSyncPoint, then sync, then write the\n** rest.\n*/\nstatic int walWriteToLog(\n  WalWriter *p,              /* WAL to write to */\n  void *pContent,            /* Content to be written */\n  int iAmt,                  /* Number of bytes to write */\n  sqlite3_int64 iOffset      /* Start writing at this offset */\n){\n  int rc;\n  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){\n    int iFirstAmt = (int)(p->iSyncPoint - iOffset);\n    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);\n    if( rc ) return rc;\n    iOffset += iFirstAmt;\n    iAmt -= iFirstAmt;\n    pContent = (void*)(iFirstAmt + (char*)pContent);\n    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );\n    rc = sqlite3OsSync(p->pFd, p->syncFlags);\n    if( iAmt==0 || rc ) return rc;\n  }\n  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);\n  return rc;\n}\n\n/*\n** Write out a single frame of the WAL\n*/\nstatic int walWriteOneFrame(\n  WalWriter *p,               /* Where to write the frame */\n  PgHdr *pPage,               /* The page of the frame to be written */\n  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */\n  sqlite3_int64 iOffset       /* Byte offset at which to write */\n){\n  int rc;                         /* Result code from subfunctions */\n  void *pData;                    /* Data actually written */\n  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */\n#if defined(SQLITE_HAS_CODEC)\n  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;\n#else\n  pData = pPage->pData;\n#endif\n  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);\n  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);\n  if( rc ) return rc;\n  /* Write the page data */\n  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));\n  return rc;\n}\n\n/* \n** Write a set of frames to the log. The caller must hold the write-lock\n** on the log file (obtained using sqlite3WalBeginWriteTransaction()).\n*/\nSQLITE_PRIVATE int sqlite3WalFrames(\n  Wal *pWal,                      /* Wal handle to write to */\n  int szPage,                     /* Database page-size in bytes */\n  PgHdr *pList,                   /* List of dirty pages to write */\n  Pgno nTruncate,                 /* Database size after this commit */\n  int isCommit,                   /* True if this is a commit */\n  int sync_flags                  /* Flags to pass to OsSync() (or 0) */\n){\n  int rc;                         /* Used to catch return codes */\n  u32 iFrame;                     /* Next frame address */\n  PgHdr *p;                       /* Iterator to run through pList with. */\n  PgHdr *pLast = 0;               /* Last frame in list */\n  int nExtra = 0;                 /* Number of extra copies of last page */\n  int szFrame;                    /* The size of a single frame */\n  i64 iOffset;                    /* Next byte to write in WAL file */\n  WalWriter w;                    /* The writer */\n\n  assert( pList );\n  assert( pWal->writeLock );\n\n  /* If this frame set completes a transaction, then nTruncate>0.  If\n  ** nTruncate==0 then this frame set does not complete the transaction. */\n  assert( (isCommit!=0)==(nTruncate!=0) );\n\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}\n    WALTRACE((\"WAL%p: frame write begin. %d frames. mxFrame=%d. %s\\n\",\n              pWal, cnt, pWal->hdr.mxFrame, isCommit ? \"Commit\" : \"Spill\"));\n  }\n#endif\n\n  /* See if it is possible to write these frames into the start of the\n  ** log file, instead of appending to it at pWal->hdr.mxFrame.\n  */\n  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){\n    return rc;\n  }\n\n  /* If this is the first frame written into the log, write the WAL\n  ** header to the start of the WAL file. See comments at the top of\n  ** this source file for a description of the WAL header format.\n  */\n  iFrame = pWal->hdr.mxFrame;\n  if( iFrame==0 ){\n    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */\n    u32 aCksum[2];                /* Checksum for wal-header */\n\n    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));\n    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);\n    sqlite3Put4byte(&aWalHdr[8], szPage);\n    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);\n    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);\n    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);\n    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);\n    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);\n    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);\n    \n    pWal->szPage = szPage;\n    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;\n    pWal->hdr.aFrameCksum[0] = aCksum[0];\n    pWal->hdr.aFrameCksum[1] = aCksum[1];\n    pWal->truncateOnCommit = 1;\n\n    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);\n    WALTRACE((\"WAL%p: wal-header write %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n\n    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless\n    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise\n    ** an out-of-order write following a WAL restart could result in\n    ** database corruption.  See the ticket:\n    **\n    **     http://localhost:591/sqlite/info/ff5be73dee\n    */\n    if( pWal->syncHeader && sync_flags ){\n      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);\n      if( rc ) return rc;\n    }\n  }\n  assert( (int)pWal->szPage==szPage );\n\n  /* Setup information needed to write frames into the WAL */\n  w.pWal = pWal;\n  w.pFd = pWal->pWalFd;\n  w.iSyncPoint = 0;\n  w.syncFlags = sync_flags;\n  w.szPage = szPage;\n  iOffset = walFrameOffset(iFrame+1, szPage);\n  szFrame = szPage + WAL_FRAME_HDRSIZE;\n\n  /* Write all frames into the log file exactly once */\n  for(p=pList; p; p=p->pDirty){\n    int nDbSize;   /* 0 normally.  Positive == commit flag */\n    iFrame++;\n    assert( iOffset==walFrameOffset(iFrame, szPage) );\n    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;\n    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);\n    if( rc ) return rc;\n    pLast = p;\n    iOffset += szFrame;\n  }\n\n  /* If this is the end of a transaction, then we might need to pad\n  ** the transaction and/or sync the WAL file.\n  **\n  ** Padding and syncing only occur if this set of frames complete a\n  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL\n  ** or synchonous==OFF, then no padding or syncing are needed.\n  **\n  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not\n  ** needed and only the sync is done.  If padding is needed, then the\n  ** final frame is repeated (with its commit mark) until the next sector\n  ** boundary is crossed.  Only the part of the WAL prior to the last\n  ** sector boundary is synced; the part of the last frame that extends\n  ** past the sector boundary is written after the sync.\n  */\n  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){\n    if( pWal->padToSectorBoundary ){\n      int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);\n      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;\n      while( iOffset<w.iSyncPoint ){\n        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);\n        if( rc ) return rc;\n        iOffset += szFrame;\n        nExtra++;\n      }\n    }else{\n      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);\n    }\n  }\n\n  /* If this frame set completes the first transaction in the WAL and\n  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the\n  ** journal size limit, if possible.\n  */\n  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){\n    i64 sz = pWal->mxWalSize;\n    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){\n      sz = walFrameOffset(iFrame+nExtra+1, szPage);\n    }\n    walLimitSize(pWal, sz);\n    pWal->truncateOnCommit = 0;\n  }\n\n  /* Append data to the wal-index. It is not necessary to lock the \n  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index\n  ** guarantees that there are no other writers, and no data that may\n  ** be in use by existing readers is being overwritten.\n  */\n  iFrame = pWal->hdr.mxFrame;\n  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){\n    iFrame++;\n    rc = walIndexAppend(pWal, iFrame, p->pgno);\n  }\n  while( rc==SQLITE_OK && nExtra>0 ){\n    iFrame++;\n    nExtra--;\n    rc = walIndexAppend(pWal, iFrame, pLast->pgno);\n  }\n\n  if( rc==SQLITE_OK ){\n    /* Update the private copy of the header. */\n    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));\n    testcase( szPage<=32768 );\n    testcase( szPage>=65536 );\n    pWal->hdr.mxFrame = iFrame;\n    if( isCommit ){\n      pWal->hdr.iChange++;\n      pWal->hdr.nPage = nTruncate;\n    }\n    /* If this is a commit, update the wal-index header too. */\n    if( isCommit ){\n      walIndexWriteHdr(pWal);\n      pWal->iCallback = iFrame;\n    }\n  }\n\n  WALTRACE((\"WAL%p: frame write %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n  return rc;\n}\n\n/* \n** This routine is called to implement sqlite3_wal_checkpoint() and\n** related interfaces.\n**\n** Obtain a CHECKPOINT lock and then backfill as much information as\n** we can from WAL into the database.\n**\n** If parameter xBusy is not NULL, it is a pointer to a busy-handler\n** callback. In this case this function runs a blocking checkpoint.\n*/\nSQLITE_PRIVATE int sqlite3WalCheckpoint(\n  Wal *pWal,                      /* Wal connection */\n  int eMode,                      /* PASSIVE, FULL or RESTART */\n  int (*xBusy)(void*),            /* Function to call when busy */\n  void *pBusyArg,                 /* Context argument for xBusyHandler */\n  int sync_flags,                 /* Flags to sync db file with (or 0) */\n  int nBuf,                       /* Size of temporary buffer */\n  u8 *zBuf,                       /* Temporary buffer to use */\n  int *pnLog,                     /* OUT: Number of frames in WAL */\n  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */\n){\n  int rc;                         /* Return code */\n  int isChanged = 0;              /* True if a new wal-index header is loaded */\n  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */\n\n  assert( pWal->ckptLock==0 );\n  assert( pWal->writeLock==0 );\n\n  if( pWal->readOnly ) return SQLITE_READONLY;\n  WALTRACE((\"WAL%p: checkpoint begins\\n\", pWal));\n  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);\n  if( rc ){\n    /* Usually this is SQLITE_BUSY meaning that another thread or process\n    ** is already running a checkpoint, or maybe a recovery.  But it might\n    ** also be SQLITE_IOERR. */\n    return rc;\n  }\n  pWal->ckptLock = 1;\n\n  /* If this is a blocking-checkpoint, then obtain the write-lock as well\n  ** to prevent any writers from running while the checkpoint is underway.\n  ** This has to be done before the call to walIndexReadHdr() below.\n  **\n  ** If the writer lock cannot be obtained, then a passive checkpoint is\n  ** run instead. Since the checkpointer is not holding the writer lock,\n  ** there is no point in blocking waiting for any readers. Assuming no \n  ** other error occurs, this function will return SQLITE_BUSY to the caller.\n  */\n  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){\n    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);\n    if( rc==SQLITE_OK ){\n      pWal->writeLock = 1;\n    }else if( rc==SQLITE_BUSY ){\n      eMode2 = SQLITE_CHECKPOINT_PASSIVE;\n      rc = SQLITE_OK;\n    }\n  }\n\n  /* Read the wal-index header. */\n  if( rc==SQLITE_OK ){\n    rc = walIndexReadHdr(pWal, &isChanged);\n  }\n\n  /* Copy data from the log to the database file. */\n  if( rc==SQLITE_OK ){\n    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);\n    }\n\n    /* If no error occurred, set the output variables. */\n    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){\n      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;\n      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);\n    }\n  }\n\n  if( isChanged ){\n    /* If a new wal-index header was loaded before the checkpoint was \n    ** performed, then the pager-cache associated with pWal is now\n    ** out of date. So zero the cached wal-index header to ensure that\n    ** next time the pager opens a snapshot on this database it knows that\n    ** the cache needs to be reset.\n    */\n    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));\n  }\n\n  /* Release the locks. */\n  sqlite3WalEndWriteTransaction(pWal);\n  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);\n  pWal->ckptLock = 0;\n  WALTRACE((\"WAL%p: checkpoint %s\\n\", pWal, rc ? \"failed\" : \"ok\"));\n  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);\n}\n\n/* Return the value to pass to a sqlite3_wal_hook callback, the\n** number of frames in the WAL at the point of the last commit since\n** sqlite3WalCallback() was called.  If no commits have occurred since\n** the last call, then return 0.\n*/\nSQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){\n  u32 ret = 0;\n  if( pWal ){\n    ret = pWal->iCallback;\n    pWal->iCallback = 0;\n  }\n  return (int)ret;\n}\n\n/*\n** This function is called to change the WAL subsystem into or out\n** of locking_mode=EXCLUSIVE.\n**\n** If op is zero, then attempt to change from locking_mode=EXCLUSIVE\n** into locking_mode=NORMAL.  This means that we must acquire a lock\n** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL\n** or if the acquisition of the lock fails, then return 0.  If the\n** transition out of exclusive-mode is successful, return 1.  This\n** operation must occur while the pager is still holding the exclusive\n** lock on the main database file.\n**\n** If op is one, then change from locking_mode=NORMAL into \n** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must\n** be released.  Return 1 if the transition is made and 0 if the\n** WAL is already in exclusive-locking mode - meaning that this\n** routine is a no-op.  The pager must already hold the exclusive lock\n** on the main database file before invoking this operation.\n**\n** If op is negative, then do a dry-run of the op==1 case but do\n** not actually change anything. The pager uses this to see if it\n** should acquire the database exclusive lock prior to invoking\n** the op==1 case.\n*/\nSQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){\n  int rc;\n  assert( pWal->writeLock==0 );\n  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );\n\n  /* pWal->readLock is usually set, but might be -1 if there was a \n  ** prior error while attempting to acquire are read-lock. This cannot \n  ** happen if the connection is actually in exclusive mode (as no xShmLock\n  ** locks are taken in this case). Nor should the pager attempt to\n  ** upgrade to exclusive-mode following such an error.\n  */\n  assert( pWal->readLock>=0 || pWal->lockError );\n  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );\n\n  if( op==0 ){\n    if( pWal->exclusiveMode ){\n      pWal->exclusiveMode = 0;\n      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){\n        pWal->exclusiveMode = 1;\n      }\n      rc = pWal->exclusiveMode==0;\n    }else{\n      /* Already in locking_mode=NORMAL */\n      rc = 0;\n    }\n  }else if( op>0 ){\n    assert( pWal->exclusiveMode==0 );\n    assert( pWal->readLock>=0 );\n    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));\n    pWal->exclusiveMode = 1;\n    rc = 1;\n  }else{\n    rc = pWal->exclusiveMode==0;\n  }\n  return rc;\n}\n\n/* \n** Return true if the argument is non-NULL and the WAL module is using\n** heap-memory for the wal-index. Otherwise, if the argument is NULL or the\n** WAL module is using shared-memory, return false. \n*/\nSQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){\n  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );\n}\n\n#ifdef SQLITE_ENABLE_ZIPVFS\n/*\n** If the argument is not NULL, it points to a Wal object that holds a\n** read-lock. This function returns the database page-size if it is known,\n** or zero if it is not (or if pWal is NULL).\n*/\nSQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){\n  assert( pWal==0 || pWal->readLock>=0 );\n  return (pWal ? pWal->szPage : 0);\n}\n#endif\n\n#endif /* #ifndef SQLITE_OMIT_WAL */\n\n/************** End of wal.c *************************************************/\n/************** Begin file btmutex.c *****************************************/\n/*\n** 2007 August 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to implement mutexes on Btree objects.\n** This code really belongs in btree.c.  But btree.c is getting too\n** big and we want to break it down some.  This packaged seemed like\n** a good breakout.\n*/\n/************** Include btreeInt.h in the middle of btmutex.c ****************/\n/************** Begin file btreeInt.h ****************************************/\n/*\n** 2004 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements a external (disk-based) database using BTrees.\n** For a detailed discussion of BTrees, refer to\n**\n**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:\n**     \"Sorting And Searching\", pages 473-480. Addison-Wesley\n**     Publishing Company, Reading, Massachusetts.\n**\n** The basic idea is that each page of the file contains N database\n** entries and N+1 pointers to subpages.\n**\n**   ----------------------------------------------------------------\n**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |\n**   ----------------------------------------------------------------\n**\n** All of the keys on the page that Ptr(0) points to have values less\n** than Key(0).  All of the keys on page Ptr(1) and its subpages have\n** values greater than Key(0) and less than Key(1).  All of the keys\n** on Ptr(N) and its subpages have values greater than Key(N-1).  And\n** so forth.\n**\n** Finding a particular key requires reading O(log(M)) pages from the \n** disk where M is the number of entries in the tree.\n**\n** In this implementation, a single file can hold one or more separate \n** BTrees.  Each BTree is identified by the index of its root page.  The\n** key and data for any entry are combined to form the \"payload\".  A\n** fixed amount of payload can be carried directly on the database\n** page.  If the payload is larger than the preset amount then surplus\n** bytes are stored on overflow pages.  The payload for an entry\n** and the preceding pointer are combined to form a \"Cell\".  Each \n** page has a small header which contains the Ptr(N) pointer and other\n** information such as the size of key and data.\n**\n** FORMAT DETAILS\n**\n** The file is divided into pages.  The first page is called page 1,\n** the second is page 2, and so forth.  A page number of zero indicates\n** \"no such page\".  The page size can be any power of 2 between 512 and 65536.\n** Each page can be either a btree page, a freelist page, an overflow\n** page, or a pointer-map page.\n**\n** The first page is always a btree page.  The first 100 bytes of the first\n** page contain a special header (the \"file header\") that describes the file.\n** The format of the file header is as follows:\n**\n**   OFFSET   SIZE    DESCRIPTION\n**      0      16     Header string: \"SQLite format 3\\000\"\n**     16       2     Page size in bytes.  \n**     18       1     File format write version\n**     19       1     File format read version\n**     20       1     Bytes of unused space at the end of each page\n**     21       1     Max embedded payload fraction\n**     22       1     Min embedded payload fraction\n**     23       1     Min leaf payload fraction\n**     24       4     File change counter\n**     28       4     Reserved for future use\n**     32       4     First freelist page\n**     36       4     Number of freelist pages in the file\n**     40      60     15 4-byte meta values passed to higher layers\n**\n**     40       4     Schema cookie\n**     44       4     File format of schema layer\n**     48       4     Size of page cache\n**     52       4     Largest root-page (auto/incr_vacuum)\n**     56       4     1=UTF-8 2=UTF16le 3=UTF16be\n**     60       4     User version\n**     64       4     Incremental vacuum mode\n**     68       4     unused\n**     72       4     unused\n**     76       4     unused\n**\n** All of the integer values are big-endian (most significant byte first).\n**\n** The file change counter is incremented when the database is changed\n** This counter allows other processes to know when the file has changed\n** and thus when they need to flush their cache.\n**\n** The max embedded payload fraction is the amount of the total usable\n** space in a page that can be consumed by a single cell for standard\n** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default\n** is to limit the maximum cell size so that at least 4 cells will fit\n** on one page.  Thus the default max embedded payload fraction is 64.\n**\n** If the payload for a cell is larger than the max payload, then extra\n** payload is spilled to overflow pages.  Once an overflow page is allocated,\n** as many bytes as possible are moved into the overflow pages without letting\n** the cell size drop below the min embedded payload fraction.\n**\n** The min leaf payload fraction is like the min embedded payload fraction\n** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum\n** payload fraction for a LEAFDATA tree is always 100% (or 255) and it\n** not specified in the header.\n**\n** Each btree pages is divided into three sections:  The header, the\n** cell pointer array, and the cell content area.  Page 1 also has a 100-byte\n** file header that occurs before the page header.\n**\n**      |----------------|\n**      | file header    |   100 bytes.  Page 1 only.\n**      |----------------|\n**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes\n**      |----------------|\n**      | cell pointer   |   |  2 bytes per cell.  Sorted order.\n**      | array          |   |  Grows downward\n**      |                |   v\n**      |----------------|\n**      | unallocated    |\n**      | space          |\n**      |----------------|   ^  Grows upwards\n**      | cell content   |   |  Arbitrary order interspersed with freeblocks.\n**      | area           |   |  and free space fragments.\n**      |----------------|\n**\n** The page headers looks like this:\n**\n**   OFFSET   SIZE     DESCRIPTION\n**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf\n**      1       2      byte offset to the first freeblock\n**      3       2      number of cells on this page\n**      5       2      first byte of the cell content area\n**      7       1      number of fragmented free bytes\n**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.\n**\n** The flags define the format of this btree page.  The leaf flag means that\n** this page has no children.  The zerodata flag means that this page carries\n** only keys and no data.  The intkey flag means that the key is a integer\n** which is stored in the key size entry of the cell header rather than in\n** the payload area.\n**\n** The cell pointer array begins on the first byte after the page header.\n** The cell pointer array contains zero or more 2-byte numbers which are\n** offsets from the beginning of the page to the cell content in the cell\n** content area.  The cell pointers occur in sorted order.  The system strives\n** to keep free space after the last cell pointer so that new cells can\n** be easily added without having to defragment the page.\n**\n** Cell content is stored at the very end of the page and grows toward the\n** beginning of the page.\n**\n** Unused space within the cell content area is collected into a linked list of\n** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset\n** to the first freeblock is given in the header.  Freeblocks occur in\n** increasing order.  Because a freeblock must be at least 4 bytes in size,\n** any group of 3 or fewer unused bytes in the cell content area cannot\n** exist on the freeblock chain.  A group of 3 or fewer free bytes is called\n** a fragment.  The total number of bytes in all fragments is recorded.\n** in the page header at offset 7.\n**\n**    SIZE    DESCRIPTION\n**      2     Byte offset of the next freeblock\n**      2     Bytes in this freeblock\n**\n** Cells are of variable length.  Cells are stored in the cell content area at\n** the end of the page.  Pointers to the cells are in the cell pointer array\n** that immediately follows the page header.  Cells is not necessarily\n** contiguous or in order, but cell pointers are contiguous and in order.\n**\n** Cell content makes use of variable length integers.  A variable\n** length integer is 1 to 9 bytes where the lower 7 bits of each \n** byte are used.  The integer consists of all bytes that have bit 8 set and\n** the first byte with bit 8 clear.  The most significant byte of the integer\n** appears first.  A variable-length integer may not be more than 9 bytes long.\n** As a special case, all 8 bytes of the 9th byte are used as data.  This\n** allows a 64-bit integer to be encoded in 9 bytes.\n**\n**    0x00                      becomes  0x00000000\n**    0x7f                      becomes  0x0000007f\n**    0x81 0x00                 becomes  0x00000080\n**    0x82 0x00                 becomes  0x00000100\n**    0x80 0x7f                 becomes  0x0000007f\n**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678\n**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081\n**\n** Variable length integers are used for rowids and to hold the number of\n** bytes of key and data in a btree cell.\n**\n** The content of a cell looks like this:\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of the left child. Omitted if leaf flag is set.\n**     var    Number of bytes of data. Omitted if the zerodata flag is set.\n**     var    Number of bytes of key. Or the key itself if intkey flag is set.\n**      *     Payload\n**      4     First page of the overflow chain.  Omitted if no overflow\n**\n** Overflow pages form a linked list.  Each page except the last is completely\n** filled with data (pagesize - 4 bytes).  The last page can have as little\n** as 1 byte of data.\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of next overflow page\n**      *     Data\n**\n** Freelist pages come in two subtypes: trunk pages and leaf pages.  The\n** file header points to the first in a linked list of trunk page.  Each trunk\n** page points to multiple leaf pages.  The content of a leaf page is\n** unspecified.  A trunk page looks like this:\n**\n**    SIZE    DESCRIPTION\n**      4     Page number of next trunk page\n**      4     Number of leaf pointers on this page\n**      *     zero or more pages numbers of leaves\n*/\n\n\n/* The following value is the maximum cell size assuming a maximum page\n** size give above.\n*/\n#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))\n\n/* The maximum number of cells on a single page of the database.  This\n** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself\n** plus 2 bytes for the index to the cell in the page header).  Such\n** small cells will be rare, but they are possible.\n*/\n#define MX_CELL(pBt) ((pBt->pageSize-8)/6)\n\n/* Forward declarations */\ntypedef struct MemPage MemPage;\ntypedef struct BtLock BtLock;\n\n/*\n** This is a magic string that appears at the beginning of every\n** SQLite database in order to identify the file as a real database.\n**\n** You can change this value at compile-time by specifying a\n** -DSQLITE_FILE_HEADER=\"...\" on the compiler command-line.  The\n** header must be exactly 16 bytes including the zero-terminator so\n** the string itself should be 15 characters long.  If you change\n** the header, then your custom library will not be able to read \n** databases generated by the standard tools and the standard tools\n** will not be able to read databases created by your custom library.\n*/\n#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */\n#  define SQLITE_FILE_HEADER \"SQLite format 3\"\n#endif\n\n/*\n** Page type flags.  An ORed combination of these flags appear as the\n** first byte of on-disk image of every BTree page.\n*/\n#define PTF_INTKEY    0x01\n#define PTF_ZERODATA  0x02\n#define PTF_LEAFDATA  0x04\n#define PTF_LEAF      0x08\n\n/*\n** As each page of the file is loaded into memory, an instance of the following\n** structure is appended and initialized to zero.  This structure stores\n** information about the page that is decoded from the raw file page.\n**\n** The pParent field points back to the parent page.  This allows us to\n** walk up the BTree from any leaf to the root.  Care must be taken to\n** unref() the parent page pointer when this page is no longer referenced.\n** The pageDestructor() routine handles that chore.\n**\n** Access to all fields of this structure is controlled by the mutex\n** stored in MemPage.pBt->mutex.\n*/\nstruct MemPage {\n  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */\n  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */\n  u8 intKey;           /* True if intkey flag is set */\n  u8 leaf;             /* True if leaf flag is set */\n  u8 hasData;          /* True if this page stores data */\n  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */\n  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */\n  u8 max1bytePayload;  /* min(maxLocal,127) */\n  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */\n  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */\n  u16 cellOffset;      /* Index in aData of first cell pointer */\n  u16 nFree;           /* Number of free bytes on the page */\n  u16 nCell;           /* Number of cells on this page, local and ovfl */\n  u16 maskPage;        /* Mask for page offset */\n  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th\n                       ** non-overflow cell */\n  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */\n  BtShared *pBt;       /* Pointer to BtShared that this page is part of */\n  u8 *aData;           /* Pointer to disk image of the page data */\n  u8 *aDataEnd;        /* One byte past the end of usable data */\n  u8 *aCellIdx;        /* The cell index area */\n  DbPage *pDbPage;     /* Pager page handle */\n  Pgno pgno;           /* Page number for this page */\n};\n\n/*\n** The in-memory image of a disk page has the auxiliary information appended\n** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold\n** that extra information.\n*/\n#define EXTRA_SIZE sizeof(MemPage)\n\n/*\n** A linked list of the following structures is stored at BtShared.pLock.\n** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor \n** is opened on the table with root page BtShared.iTable. Locks are removed\n** from this list when a transaction is committed or rolled back, or when\n** a btree handle is closed.\n*/\nstruct BtLock {\n  Btree *pBtree;        /* Btree handle holding this lock */\n  Pgno iTable;          /* Root page of table */\n  u8 eLock;             /* READ_LOCK or WRITE_LOCK */\n  BtLock *pNext;        /* Next in BtShared.pLock list */\n};\n\n/* Candidate values for BtLock.eLock */\n#define READ_LOCK     1\n#define WRITE_LOCK    2\n\n/* A Btree handle\n**\n** A database connection contains a pointer to an instance of\n** this object for every database file that it has open.  This structure\n** is opaque to the database connection.  The database connection cannot\n** see the internals of this structure and only deals with pointers to\n** this structure.\n**\n** For some database files, the same underlying database cache might be \n** shared between multiple connections.  In that case, each connection\n** has it own instance of this object.  But each instance of this object\n** points to the same BtShared object.  The database cache and the\n** schema associated with the database file are all contained within\n** the BtShared object.\n**\n** All fields in this structure are accessed under sqlite3.mutex.\n** The pBt pointer itself may not be changed while there exists cursors \n** in the referenced BtShared that point back to this Btree since those\n** cursors have to go through this Btree to find their BtShared and\n** they often do so without holding sqlite3.mutex.\n*/\nstruct Btree {\n  sqlite3 *db;       /* The database connection holding this btree */\n  BtShared *pBt;     /* Sharable content of this btree */\n  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */\n  u8 sharable;       /* True if we can share pBt with another db */\n  u8 locked;         /* True if db currently has pBt locked */\n  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */\n  int nBackup;       /* Number of backup operations reading this btree */\n  Btree *pNext;      /* List of other sharable Btrees from the same db */\n  Btree *pPrev;      /* Back pointer of the same list */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  BtLock lock;       /* Object used to lock page 1 */\n#endif\n};\n\n/*\n** Btree.inTrans may take one of the following values.\n**\n** If the shared-data extension is enabled, there may be multiple users\n** of the Btree structure. At most one of these may open a write transaction,\n** but any number may have active read transactions.\n*/\n#define TRANS_NONE  0\n#define TRANS_READ  1\n#define TRANS_WRITE 2\n\n/*\n** An instance of this object represents a single database file.\n** \n** A single database file can be in use at the same time by two\n** or more database connections.  When two or more connections are\n** sharing the same database file, each connection has it own\n** private Btree object for the file and each of those Btrees points\n** to this one BtShared object.  BtShared.nRef is the number of\n** connections currently sharing this database file.\n**\n** Fields in this structure are accessed under the BtShared.mutex\n** mutex, except for nRef and pNext which are accessed under the\n** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field\n** may not be modified once it is initially set as long as nRef>0.\n** The pSchema field may be set once under BtShared.mutex and\n** thereafter is unchanged as long as nRef>0.\n**\n** isPending:\n**\n**   If a BtShared client fails to obtain a write-lock on a database\n**   table (because there exists one or more read-locks on the table),\n**   the shared-cache enters 'pending-lock' state and isPending is\n**   set to true.\n**\n**   The shared-cache leaves the 'pending lock' state when either of\n**   the following occur:\n**\n**     1) The current writer (BtShared.pWriter) concludes its transaction, OR\n**     2) The number of locks held by other connections drops to zero.\n**\n**   while in the 'pending-lock' state, no connection may start a new\n**   transaction.\n**\n**   This feature is included to help prevent writer-starvation.\n*/\nstruct BtShared {\n  Pager *pPager;        /* The page cache */\n  sqlite3 *db;          /* Database connection currently using this Btree */\n  BtCursor *pCursor;    /* A list of all open cursors */\n  MemPage *pPage1;      /* First page of the database */\n  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  u8 autoVacuum;        /* True if auto-vacuum is enabled */\n  u8 incrVacuum;        /* True if incr-vacuum is enabled */\n#endif\n  u8 inTransaction;     /* Transaction state */\n  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */\n  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */\n  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */\n  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */\n  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */\n  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */\n  u32 pageSize;         /* Total number of bytes on a page */\n  u32 usableSize;       /* Number of usable bytes on each page */\n  int nTransaction;     /* Number of open transactions (read + write) */\n  u32 nPage;            /* Number of pages in the database */\n  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */\n  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */\n  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */\n  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  int nRef;             /* Number of references to this structure */\n  BtShared *pNext;      /* Next on a list of sharable BtShared structs */\n  BtLock *pLock;        /* List of locks held on this shared-btree struct */\n  Btree *pWriter;       /* Btree with currently open write transaction */\n#endif\n  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */\n};\n\n/*\n** Allowed values for BtShared.btsFlags\n*/\n#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */\n#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */\n#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */\n#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */\n#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */\n#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */\n#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */\n\n/*\n** An instance of the following structure is used to hold information\n** about a cell.  The parseCellPtr() function fills in this structure\n** based on information extract from the raw disk page.\n*/\ntypedef struct CellInfo CellInfo;\nstruct CellInfo {\n  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */\n  u8 *pCell;     /* Pointer to the start of cell content */\n  u32 nData;     /* Number of bytes of data */\n  u32 nPayload;  /* Total amount of payload */\n  u16 nHeader;   /* Size of the cell content header in bytes */\n  u16 nLocal;    /* Amount of payload held locally */\n  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */\n  u16 nSize;     /* Size of the cell content on the main b-tree page */\n};\n\n/*\n** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than\n** this will be declared corrupt. This value is calculated based on a\n** maximum database size of 2^31 pages a minimum fanout of 2 for a\n** root-node and 3 for all other internal nodes.\n**\n** If a tree that appears to be taller than this is encountered, it is\n** assumed that the database is corrupt.\n*/\n#define BTCURSOR_MAX_DEPTH 20\n\n/*\n** A cursor is a pointer to a particular entry within a particular\n** b-tree within a database file.\n**\n** The entry is identified by its MemPage and the index in\n** MemPage.aCell[] of the entry.\n**\n** A single database file can be shared by two more database connections,\n** but cursors cannot be shared.  Each cursor is associated with a\n** particular database connection identified BtCursor.pBtree.db.\n**\n** Fields in this structure are accessed under the BtShared.mutex\n** found at self->pBt->mutex. \n*/\nstruct BtCursor {\n  Btree *pBtree;            /* The Btree to which this cursor belongs */\n  BtShared *pBt;            /* The BtShared this cursor points to */\n  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */\n  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */\n#ifndef SQLITE_OMIT_INCRBLOB\n  Pgno *aOverflow;          /* Cache of overflow page locations */\n#endif\n  Pgno pgnoRoot;            /* The root page of this tree */\n  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */\n  CellInfo info;            /* A parse of the cell we are pointing at */\n  i64 nKey;        /* Size of pKey, or last integer key */\n  void *pKey;      /* Saved key that was cursor's last known position */\n  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */\n  u8 wrFlag;                /* True if writable */\n  u8 atLast;                /* Cursor pointing to the last entry */\n  u8 validNKey;             /* True if info.nKey is valid */\n  u8 eState;                /* One of the CURSOR_XXX constants (see below) */\n#ifndef SQLITE_OMIT_INCRBLOB\n  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */\n#endif\n  u8 hints;                             /* As configured by CursorSetHints() */\n  i16 iPage;                            /* Index of current page in apPage */\n  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */\n  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */\n};\n\n/*\n** Potential values for BtCursor.eState.\n**\n** CURSOR_VALID:\n**   Cursor points to a valid entry. getPayload() etc. may be called.\n**\n** CURSOR_INVALID:\n**   Cursor does not point to a valid entry. This can happen (for example) \n**   because the table is empty or because BtreeCursorFirst() has not been\n**   called.\n**\n** CURSOR_REQUIRESEEK:\n**   The table that this cursor was opened on still exists, but has been \n**   modified since the cursor was last used. The cursor position is saved\n**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in \n**   this state, restoreCursorPosition() can be called to attempt to\n**   seek the cursor to the saved position.\n**\n** CURSOR_FAULT:\n**   A unrecoverable error (an I/O error or a malloc failure) has occurred\n**   on a different connection that shares the BtShared cache with this\n**   cursor.  The error has left the cache in an inconsistent state.\n**   Do nothing else with this cursor.  Any attempt to use the cursor\n**   should return the error code stored in BtCursor.skip\n*/\n#define CURSOR_INVALID           0\n#define CURSOR_VALID             1\n#define CURSOR_REQUIRESEEK       2\n#define CURSOR_FAULT             3\n\n/* \n** The database page the PENDING_BYTE occupies. This page is never used.\n*/\n# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)\n\n/*\n** These macros define the location of the pointer-map entry for a \n** database page. The first argument to each is the number of usable\n** bytes on each page of the database (often 1024). The second is the\n** page number to look up in the pointer map.\n**\n** PTRMAP_PAGENO returns the database page number of the pointer-map\n** page that stores the required pointer. PTRMAP_PTROFFSET returns\n** the offset of the requested map entry.\n**\n** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,\n** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be\n** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements\n** this test.\n*/\n#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)\n#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))\n#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))\n\n/*\n** The pointer map is a lookup table that identifies the parent page for\n** each child page in the database file.  The parent page is the page that\n** contains a pointer to the child.  Every page in the database contains\n** 0 or 1 parent pages.  (In this context 'database page' refers\n** to any page that is not part of the pointer map itself.)  Each pointer map\n** entry consists of a single byte 'type' and a 4 byte parent page number.\n** The PTRMAP_XXX identifiers below are the valid types.\n**\n** The purpose of the pointer map is to facility moving pages from one\n** position in the file to another as part of autovacuum.  When a page\n** is moved, the pointer in its parent must be updated to point to the\n** new location.  The pointer map is used to locate the parent page quickly.\n**\n** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not\n**                  used in this case.\n**\n** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number \n**                  is not used in this case.\n**\n** PTRMAP_OVERFLOW1: The database page is the first page in a list of \n**                   overflow pages. The page number identifies the page that\n**                   contains the cell with a pointer to this overflow page.\n**\n** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of\n**                   overflow pages. The page-number identifies the previous\n**                   page in the overflow page list.\n**\n** PTRMAP_BTREE: The database page is a non-root btree page. The page number\n**               identifies the parent page in the btree.\n*/\n#define PTRMAP_ROOTPAGE 1\n#define PTRMAP_FREEPAGE 2\n#define PTRMAP_OVERFLOW1 3\n#define PTRMAP_OVERFLOW2 4\n#define PTRMAP_BTREE 5\n\n/* A bunch of assert() statements to check the transaction state variables\n** of handle p (type Btree*) are internally consistent.\n*/\n#define btreeIntegrity(p) \\\n  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \\\n  assert( p->pBt->inTransaction>=p->inTrans ); \n\n\n/*\n** The ISAUTOVACUUM macro is used within balance_nonroot() to determine\n** if the database supports auto-vacuum or not. Because it is used\n** within an expression that is an argument to another macro \n** (sqliteMallocRaw), it is not possible to use conditional compilation.\n** So, this macro is defined instead.\n*/\n#ifndef SQLITE_OMIT_AUTOVACUUM\n#define ISAUTOVACUUM (pBt->autoVacuum)\n#else\n#define ISAUTOVACUUM 0\n#endif\n\n\n/*\n** This structure is passed around through all the sanity checking routines\n** in order to keep track of some global state information.\n**\n** The aRef[] array is allocated so that there is 1 bit for each page in\n** the database. As the integrity-check proceeds, for each page used in\n** the database the corresponding bit is set. This allows integrity-check to \n** detect pages that are used twice and orphaned pages (both of which \n** indicate corruption).\n*/\ntypedef struct IntegrityCk IntegrityCk;\nstruct IntegrityCk {\n  BtShared *pBt;    /* The tree being checked out */\n  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */\n  u8 *aPgRef;       /* 1 bit per page in the db (see above) */\n  Pgno nPage;       /* Number of pages in the database */\n  int mxErr;        /* Stop accumulating errors when this reaches zero */\n  int nErr;         /* Number of messages written to zErrMsg so far */\n  int mallocFailed; /* A memory allocation error has occurred */\n  StrAccum errMsg;  /* Accumulate the error message text here */\n};\n\n/*\n** Routines to read or write a two- and four-byte big-endian integer values.\n*/\n#define get2byte(x)   ((x)[0]<<8 | (x)[1])\n#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))\n#define get4byte sqlite3Get4byte\n#define put4byte sqlite3Put4byte\n\n/************** End of btreeInt.h ********************************************/\n/************** Continuing where we left off in btmutex.c ********************/\n#ifndef SQLITE_OMIT_SHARED_CACHE\n#if SQLITE_THREADSAFE\n\n/*\n** Obtain the BtShared mutex associated with B-Tree handle p. Also,\n** set BtShared.db to the database handle associated with p and the\n** p->locked boolean to true.\n*/\nstatic void lockBtreeMutex(Btree *p){\n  assert( p->locked==0 );\n  assert( sqlite3_mutex_notheld(p->pBt->mutex) );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n\n  sqlite3_mutex_enter(p->pBt->mutex);\n  p->pBt->db = p->db;\n  p->locked = 1;\n}\n\n/*\n** Release the BtShared mutex associated with B-Tree handle p and\n** clear the p->locked boolean.\n*/\nstatic void unlockBtreeMutex(Btree *p){\n  BtShared *pBt = p->pBt;\n  assert( p->locked==1 );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  assert( p->db==pBt->db );\n\n  sqlite3_mutex_leave(pBt->mutex);\n  p->locked = 0;\n}\n\n/*\n** Enter a mutex on the given BTree object.\n**\n** If the object is not sharable, then no mutex is ever required\n** and this routine is a no-op.  The underlying mutex is non-recursive.\n** But we keep a reference count in Btree.wantToLock so the behavior\n** of this interface is recursive.\n**\n** To avoid deadlocks, multiple Btrees are locked in the same order\n** by all database connections.  The p->pNext is a list of other\n** Btrees belonging to the same database connection as the p Btree\n** which need to be locked after p.  If we cannot get a lock on\n** p, then first unlock all of the others on p->pNext, then wait\n** for the lock to become available on p, then relock all of the\n** subsequent Btrees that desire a lock.\n*/\nSQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){\n  Btree *pLater;\n\n  /* Some basic sanity checking on the Btree.  The list of Btrees\n  ** connected by pNext and pPrev should be in sorted order by\n  ** Btree.pBt value. All elements of the list should belong to\n  ** the same connection. Only shared Btrees are on the list. */\n  assert( p->pNext==0 || p->pNext->pBt>p->pBt );\n  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );\n  assert( p->pNext==0 || p->pNext->db==p->db );\n  assert( p->pPrev==0 || p->pPrev->db==p->db );\n  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );\n\n  /* Check for locking consistency */\n  assert( !p->locked || p->wantToLock>0 );\n  assert( p->sharable || p->wantToLock==0 );\n\n  /* We should already hold a lock on the database connection */\n  assert( sqlite3_mutex_held(p->db->mutex) );\n\n  /* Unless the database is sharable and unlocked, then BtShared.db\n  ** should already be set correctly. */\n  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );\n\n  if( !p->sharable ) return;\n  p->wantToLock++;\n  if( p->locked ) return;\n\n  /* In most cases, we should be able to acquire the lock we\n  ** want without having to go throught the ascending lock\n  ** procedure that follows.  Just be sure not to block.\n  */\n  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){\n    p->pBt->db = p->db;\n    p->locked = 1;\n    return;\n  }\n\n  /* To avoid deadlock, first release all locks with a larger\n  ** BtShared address.  Then acquire our lock.  Then reacquire\n  ** the other BtShared locks that we used to hold in ascending\n  ** order.\n  */\n  for(pLater=p->pNext; pLater; pLater=pLater->pNext){\n    assert( pLater->sharable );\n    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );\n    assert( !pLater->locked || pLater->wantToLock>0 );\n    if( pLater->locked ){\n      unlockBtreeMutex(pLater);\n    }\n  }\n  lockBtreeMutex(p);\n  for(pLater=p->pNext; pLater; pLater=pLater->pNext){\n    if( pLater->wantToLock ){\n      lockBtreeMutex(pLater);\n    }\n  }\n}\n\n/*\n** Exit the recursive mutex on a Btree.\n*/\nSQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){\n  if( p->sharable ){\n    assert( p->wantToLock>0 );\n    p->wantToLock--;\n    if( p->wantToLock==0 ){\n      unlockBtreeMutex(p);\n    }\n  }\n}\n\n#ifndef NDEBUG\n/*\n** Return true if the BtShared mutex is held on the btree, or if the\n** B-Tree is not marked as sharable.\n**\n** This routine is used only from within assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){\n  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );\n  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );\n  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );\n  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );\n\n  return (p->sharable==0 || p->locked);\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** Enter and leave a mutex on a Btree given a cursor owned by that\n** Btree.  These entry points are used by incremental I/O and can be\n** omitted if that module is not used.\n*/\nSQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){\n  sqlite3BtreeEnter(pCur->pBtree);\n}\nSQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){\n  sqlite3BtreeLeave(pCur->pBtree);\n}\n#endif /* SQLITE_OMIT_INCRBLOB */\n\n\n/*\n** Enter the mutex on every Btree associated with a database\n** connection.  This is needed (for example) prior to parsing\n** a statement since we will be comparing table and column names\n** against all schemas and we do not want those schemas being\n** reset out from under us.\n**\n** There is a corresponding leave-all procedures.\n**\n** Enter the mutexes in accending order by BtShared pointer address\n** to avoid the possibility of deadlock when two threads with\n** two or more btrees in common both try to lock all their btrees\n** at the same instant.\n*/\nSQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){\n  int i;\n  Btree *p;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nDb; i++){\n    p = db->aDb[i].pBt;\n    if( p ) sqlite3BtreeEnter(p);\n  }\n}\nSQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){\n  int i;\n  Btree *p;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nDb; i++){\n    p = db->aDb[i].pBt;\n    if( p ) sqlite3BtreeLeave(p);\n  }\n}\n\n/*\n** Return true if a particular Btree requires a lock.  Return FALSE if\n** no lock is ever required since it is not sharable.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){\n  return p->sharable;\n}\n\n#ifndef NDEBUG\n/*\n** Return true if the current thread holds the database connection\n** mutex and all required BtShared mutexes.\n**\n** This routine is used inside assert() statements only.\n*/\nSQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){\n  int i;\n  if( !sqlite3_mutex_held(db->mutex) ){\n    return 0;\n  }\n  for(i=0; i<db->nDb; i++){\n    Btree *p;\n    p = db->aDb[i].pBt;\n    if( p && p->sharable &&\n         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){\n      return 0;\n    }\n  }\n  return 1;\n}\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/*\n** Return true if the correct mutexes are held for accessing the\n** db->aDb[iDb].pSchema structure.  The mutexes required for schema\n** access are:\n**\n**   (1) The mutex on db\n**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.\n**\n** If pSchema is not NULL, then iDb is computed from pSchema and\n** db using sqlite3SchemaToIndex().\n*/\nSQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){\n  Btree *p;\n  assert( db!=0 );\n  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n  if( !sqlite3_mutex_held(db->mutex) ) return 0;\n  if( iDb==1 ) return 1;\n  p = db->aDb[iDb].pBt;\n  assert( p!=0 );\n  return p->sharable==0 || p->locked==1;\n}\n#endif /* NDEBUG */\n\n#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */\n/*\n** The following are special cases for mutex enter routines for use\n** in single threaded applications that use shared cache.  Except for\n** these two routines, all mutex operations are no-ops in that case and\n** are null #defines in btree.h.\n**\n** If shared cache is disabled, then all btree mutex routines, including\n** the ones below, are no-ops and are null #defines in btree.h.\n*/\n\nSQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){\n  p->pBt->db = p->db;\n}\nSQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Btree *p = db->aDb[i].pBt;\n    if( p ){\n      p->pBt->db = p->db;\n    }\n  }\n}\n#endif /* if SQLITE_THREADSAFE */\n#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */\n\n/************** End of btmutex.c *********************************************/\n/************** Begin file btree.c *******************************************/\n/*\n** 2004 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements a external (disk-based) database using BTrees.\n** See the header comment on \"btreeInt.h\" for additional information.\n** Including a description of file format and an overview of operation.\n*/\n\n/*\n** The header string that appears at the beginning of every\n** SQLite database.\n*/\nstatic const char zMagicHeader[] = SQLITE_FILE_HEADER;\n\n/*\n** Set this global variable to 1 to enable tracing using the TRACE\n** macro.\n*/\n#if 0\nint sqlite3BtreeTrace=1;  /* True to enable tracing */\n# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}\n#else\n# define TRACE(X)\n#endif\n\n/*\n** Extract a 2-byte big-endian integer from an array of unsigned bytes.\n** But if the value is zero, make it 65536.\n**\n** This routine is used to extract the \"offset to cell content area\" value\n** from the header of a btree page.  If the page size is 65536 and the page\n** is empty, the offset should be 65536, but the 2-byte value stores zero.\n** This routine makes the necessary adjustment to 65536.\n*/\n#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** A list of BtShared objects that are eligible for participation\n** in shared cache.  This variable has file scope during normal builds,\n** but the test harness needs to access it so we make it global for \n** test builds.\n**\n** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.\n*/\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;\n#else\nstatic BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;\n#endif\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Enable or disable the shared pager and schema features.\n**\n** This routine has no effect on existing database connections.\n** The shared cache setting effects only future calls to\n** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int enable){\n  sqlite3GlobalConfig.sharedCacheEnabled = enable;\n  return SQLITE_OK;\n}\n#endif\n\n\n\n#ifdef SQLITE_OMIT_SHARED_CACHE\n  /*\n  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),\n  ** and clearAllSharedCacheTableLocks()\n  ** manipulate entries in the BtShared.pLock linked list used to store\n  ** shared-cache table level locks. If the library is compiled with the\n  ** shared-cache feature disabled, then there is only ever one user\n  ** of each BtShared structure and so this locking is not necessary. \n  ** So define the lock related functions as no-ops.\n  */\n  #define querySharedCacheTableLock(a,b,c) SQLITE_OK\n  #define setSharedCacheTableLock(a,b,c) SQLITE_OK\n  #define clearAllSharedCacheTableLocks(a)\n  #define downgradeAllSharedCacheTableLocks(a)\n  #define hasSharedCacheTableLock(a,b,c,d) 1\n  #define hasReadConflicts(a, b) 0\n#endif\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n\n#ifdef SQLITE_DEBUG\n/*\n**** This function is only used as part of an assert() statement. ***\n**\n** Check to see if pBtree holds the required locks to read or write to the \n** table with root page iRoot.   Return 1 if it does and 0 if not.\n**\n** For example, when writing to a table with root-page iRoot via \n** Btree connection pBtree:\n**\n**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );\n**\n** When writing to an index that resides in a sharable database, the \n** caller should have first obtained a lock specifying the root page of\n** the corresponding table. This makes things a bit more complicated,\n** as this module treats each table as a separate structure. To determine\n** the table corresponding to the index being written, this\n** function has to search through the database schema.\n**\n** Instead of a lock on the table/index rooted at page iRoot, the caller may\n** hold a write-lock on the schema table (root page 1). This is also\n** acceptable.\n*/\nstatic int hasSharedCacheTableLock(\n  Btree *pBtree,         /* Handle that must hold lock */\n  Pgno iRoot,            /* Root page of b-tree */\n  int isIndex,           /* True if iRoot is the root of an index b-tree */\n  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */\n){\n  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;\n  Pgno iTab = 0;\n  BtLock *pLock;\n\n  /* If this database is not shareable, or if the client is reading\n  ** and has the read-uncommitted flag set, then no lock is required. \n  ** Return true immediately.\n  */\n  if( (pBtree->sharable==0)\n   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))\n  ){\n    return 1;\n  }\n\n  /* If the client is reading  or writing an index and the schema is\n  ** not loaded, then it is too difficult to actually check to see if\n  ** the correct locks are held.  So do not bother - just return true.\n  ** This case does not come up very often anyhow.\n  */\n  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){\n    return 1;\n  }\n\n  /* Figure out the root-page that the lock should be held on. For table\n  ** b-trees, this is just the root page of the b-tree being read or\n  ** written. For index b-trees, it is the root page of the associated\n  ** table.  */\n  if( isIndex ){\n    HashElem *p;\n    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){\n      Index *pIdx = (Index *)sqliteHashData(p);\n      if( pIdx->tnum==(int)iRoot ){\n        iTab = pIdx->pTable->tnum;\n      }\n    }\n  }else{\n    iTab = iRoot;\n  }\n\n  /* Search for the required lock. Either a write-lock on root-page iTab, a \n  ** write-lock on the schema table, or (if the client is reading) a\n  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */\n  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){\n    if( pLock->pBtree==pBtree \n     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))\n     && pLock->eLock>=eLockType \n    ){\n      return 1;\n    }\n  }\n\n  /* Failed to find the required lock. */\n  return 0;\n}\n#endif /* SQLITE_DEBUG */\n\n#ifdef SQLITE_DEBUG\n/*\n**** This function may be used as part of assert() statements only. ****\n**\n** Return true if it would be illegal for pBtree to write into the\n** table or index rooted at iRoot because other shared connections are\n** simultaneously reading that same table or index.\n**\n** It is illegal for pBtree to write if some other Btree object that\n** shares the same BtShared object is currently reading or writing\n** the iRoot table.  Except, if the other Btree object has the\n** read-uncommitted flag set, then it is OK for the other object to\n** have a read cursor.\n**\n** For example, before writing to any part of the table or index\n** rooted at page iRoot, one should call:\n**\n**    assert( !hasReadConflicts(pBtree, iRoot) );\n*/\nstatic int hasReadConflicts(Btree *pBtree, Pgno iRoot){\n  BtCursor *p;\n  for(p=pBtree->pBt->pCursor; p; p=p->pNext){\n    if( p->pgnoRoot==iRoot \n     && p->pBtree!=pBtree\n     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)\n    ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif    /* #ifdef SQLITE_DEBUG */\n\n/*\n** Query to see if Btree handle p may obtain a lock of type eLock \n** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return\n** SQLITE_OK if the lock may be obtained (by calling\n** setSharedCacheTableLock()), or SQLITE_LOCKED if not.\n*/\nstatic int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){\n  BtShared *pBt = p->pBt;\n  BtLock *pIter;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );\n  assert( p->db!=0 );\n  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );\n  \n  /* If requesting a write-lock, then the Btree must have an open write\n  ** transaction on this file. And, obviously, for this to be so there \n  ** must be an open write transaction on the file itself.\n  */\n  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );\n  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );\n  \n  /* This routine is a no-op if the shared-cache is not enabled */\n  if( !p->sharable ){\n    return SQLITE_OK;\n  }\n\n  /* If some other connection is holding an exclusive lock, the\n  ** requested lock may not be obtained.\n  */\n  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){\n    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);\n    return SQLITE_LOCKED_SHAREDCACHE;\n  }\n\n  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n    /* The condition (pIter->eLock!=eLock) in the following if(...) \n    ** statement is a simplification of:\n    **\n    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)\n    **\n    ** since we know that if eLock==WRITE_LOCK, then no other connection\n    ** may hold a WRITE_LOCK on any table in this file (since there can\n    ** only be a single writer).\n    */\n    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );\n    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);\n    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){\n      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);\n      if( eLock==WRITE_LOCK ){\n        assert( p==pBt->pWriter );\n        pBt->btsFlags |= BTS_PENDING;\n      }\n      return SQLITE_LOCKED_SHAREDCACHE;\n    }\n  }\n  return SQLITE_OK;\n}\n#endif /* !SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Add a lock on the table with root-page iTable to the shared-btree used\n** by Btree handle p. Parameter eLock must be either READ_LOCK or \n** WRITE_LOCK.\n**\n** This function assumes the following:\n**\n**   (a) The specified Btree object p is connected to a sharable\n**       database (one with the BtShared.sharable flag set), and\n**\n**   (b) No other Btree objects hold a lock that conflicts\n**       with the requested lock (i.e. querySharedCacheTableLock() has\n**       already been called and returned SQLITE_OK).\n**\n** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM \n** is returned if a malloc attempt fails.\n*/\nstatic int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){\n  BtShared *pBt = p->pBt;\n  BtLock *pLock = 0;\n  BtLock *pIter;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );\n  assert( p->db!=0 );\n\n  /* A connection with the read-uncommitted flag set will never try to\n  ** obtain a read-lock using this function. The only read-lock obtained\n  ** by a connection in read-uncommitted mode is on the sqlite_master \n  ** table, and that lock is obtained in BtreeBeginTrans().  */\n  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );\n\n  /* This function should only be called on a sharable b-tree after it \n  ** has been determined that no other b-tree holds a conflicting lock.  */\n  assert( p->sharable );\n  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );\n\n  /* First search the list for an existing lock on this table. */\n  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n    if( pIter->iTable==iTable && pIter->pBtree==p ){\n      pLock = pIter;\n      break;\n    }\n  }\n\n  /* If the above search did not find a BtLock struct associating Btree p\n  ** with table iTable, allocate one and link it into the list.\n  */\n  if( !pLock ){\n    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));\n    if( !pLock ){\n      return SQLITE_NOMEM;\n    }\n    pLock->iTable = iTable;\n    pLock->pBtree = p;\n    pLock->pNext = pBt->pLock;\n    pBt->pLock = pLock;\n  }\n\n  /* Set the BtLock.eLock variable to the maximum of the current lock\n  ** and the requested lock. This means if a write-lock was already held\n  ** and a read-lock requested, we don't incorrectly downgrade the lock.\n  */\n  assert( WRITE_LOCK>READ_LOCK );\n  if( eLock>pLock->eLock ){\n    pLock->eLock = eLock;\n  }\n\n  return SQLITE_OK;\n}\n#endif /* !SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Release all the table locks (locks obtained via calls to\n** the setSharedCacheTableLock() procedure) held by Btree object p.\n**\n** This function assumes that Btree p has an open read or write \n** transaction. If it does not, then the BTS_PENDING flag\n** may be incorrectly cleared.\n*/\nstatic void clearAllSharedCacheTableLocks(Btree *p){\n  BtShared *pBt = p->pBt;\n  BtLock **ppIter = &pBt->pLock;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( p->sharable || 0==*ppIter );\n  assert( p->inTrans>0 );\n\n  while( *ppIter ){\n    BtLock *pLock = *ppIter;\n    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );\n    assert( pLock->pBtree->inTrans>=pLock->eLock );\n    if( pLock->pBtree==p ){\n      *ppIter = pLock->pNext;\n      assert( pLock->iTable!=1 || pLock==&p->lock );\n      if( pLock->iTable!=1 ){\n        sqlite3_free(pLock);\n      }\n    }else{\n      ppIter = &pLock->pNext;\n    }\n  }\n\n  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );\n  if( pBt->pWriter==p ){\n    pBt->pWriter = 0;\n    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);\n  }else if( pBt->nTransaction==2 ){\n    /* This function is called when Btree p is concluding its \n    ** transaction. If there currently exists a writer, and p is not\n    ** that writer, then the number of locks held by connections other\n    ** than the writer must be about to drop to zero. In this case\n    ** set the BTS_PENDING flag to 0.\n    **\n    ** If there is not currently a writer, then BTS_PENDING must\n    ** be zero already. So this next line is harmless in that case.\n    */\n    pBt->btsFlags &= ~BTS_PENDING;\n  }\n}\n\n/*\n** This function changes all write-locks held by Btree p into read-locks.\n*/\nstatic void downgradeAllSharedCacheTableLocks(Btree *p){\n  BtShared *pBt = p->pBt;\n  if( pBt->pWriter==p ){\n    BtLock *pLock;\n    pBt->pWriter = 0;\n    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);\n    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){\n      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );\n      pLock->eLock = READ_LOCK;\n    }\n  }\n}\n\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\nstatic void releasePage(MemPage *pPage);  /* Forward reference */\n\n/*\n***** This routine is used inside of assert() only ****\n**\n** Verify that the cursor holds the mutex on its BtShared\n*/\n#ifdef SQLITE_DEBUG\nstatic int cursorHoldsMutex(BtCursor *p){\n  return sqlite3_mutex_held(p->pBt->mutex);\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** Invalidate the overflow page-list cache for cursor pCur, if any.\n*/\nstatic void invalidateOverflowCache(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  sqlite3_free(pCur->aOverflow);\n  pCur->aOverflow = 0;\n}\n\n/*\n** Invalidate the overflow page-list cache for all cursors opened\n** on the shared btree structure pBt.\n*/\nstatic void invalidateAllOverflowCache(BtShared *pBt){\n  BtCursor *p;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  for(p=pBt->pCursor; p; p=p->pNext){\n    invalidateOverflowCache(p);\n  }\n}\n\n/*\n** This function is called before modifying the contents of a table\n** to invalidate any incrblob cursors that are open on the\n** row or one of the rows being modified.\n**\n** If argument isClearTable is true, then the entire contents of the\n** table is about to be deleted. In this case invalidate all incrblob\n** cursors open on any row within the table with root-page pgnoRoot.\n**\n** Otherwise, if argument isClearTable is false, then the row with\n** rowid iRow is being replaced or deleted. In this case invalidate\n** only those incrblob cursors open on that specific row.\n*/\nstatic void invalidateIncrblobCursors(\n  Btree *pBtree,          /* The database file to check */\n  i64 iRow,               /* The rowid that might be changing */\n  int isClearTable        /* True if all rows are being deleted */\n){\n  BtCursor *p;\n  BtShared *pBt = pBtree->pBt;\n  assert( sqlite3BtreeHoldsMutex(pBtree) );\n  for(p=pBt->pCursor; p; p=p->pNext){\n    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){\n      p->eState = CURSOR_INVALID;\n    }\n  }\n}\n\n#else\n  /* Stub functions when INCRBLOB is omitted */\n  #define invalidateOverflowCache(x)\n  #define invalidateAllOverflowCache(x)\n  #define invalidateIncrblobCursors(x,y,z)\n#endif /* SQLITE_OMIT_INCRBLOB */\n\n/*\n** Set bit pgno of the BtShared.pHasContent bitvec. This is called \n** when a page that previously contained data becomes a free-list leaf \n** page.\n**\n** The BtShared.pHasContent bitvec exists to work around an obscure\n** bug caused by the interaction of two useful IO optimizations surrounding\n** free-list leaf pages:\n**\n**   1) When all data is deleted from a page and the page becomes\n**      a free-list leaf page, the page is not written to the database\n**      (as free-list leaf pages contain no meaningful data). Sometimes\n**      such a page is not even journalled (as it will not be modified,\n**      why bother journalling it?).\n**\n**   2) When a free-list leaf page is reused, its content is not read\n**      from the database or written to the journal file (why should it\n**      be, if it is not at all meaningful?).\n**\n** By themselves, these optimizations work fine and provide a handy\n** performance boost to bulk delete or insert operations. However, if\n** a page is moved to the free-list and then reused within the same\n** transaction, a problem comes up. If the page is not journalled when\n** it is moved to the free-list and it is also not journalled when it\n** is extracted from the free-list and reused, then the original data\n** may be lost. In the event of a rollback, it may not be possible\n** to restore the database to its original configuration.\n**\n** The solution is the BtShared.pHasContent bitvec. Whenever a page is \n** moved to become a free-list leaf page, the corresponding bit is\n** set in the bitvec. Whenever a leaf page is extracted from the free-list,\n** optimization 2 above is omitted if the corresponding bit is already\n** set in BtShared.pHasContent. The contents of the bitvec are cleared\n** at the end of every transaction.\n*/\nstatic int btreeSetHasContent(BtShared *pBt, Pgno pgno){\n  int rc = SQLITE_OK;\n  if( !pBt->pHasContent ){\n    assert( pgno<=pBt->nPage );\n    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);\n    if( !pBt->pHasContent ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){\n    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);\n  }\n  return rc;\n}\n\n/*\n** Query the BtShared.pHasContent vector.\n**\n** This function is called when a free-list leaf page is removed from the\n** free-list for reuse. It returns false if it is safe to retrieve the\n** page from the pager layer with the 'no-content' flag set. True otherwise.\n*/\nstatic int btreeGetHasContent(BtShared *pBt, Pgno pgno){\n  Bitvec *p = pBt->pHasContent;\n  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));\n}\n\n/*\n** Clear (destroy) the BtShared.pHasContent bitvec. This should be\n** invoked at the conclusion of each write-transaction.\n*/\nstatic void btreeClearHasContent(BtShared *pBt){\n  sqlite3BitvecDestroy(pBt->pHasContent);\n  pBt->pHasContent = 0;\n}\n\n/*\n** Save the current cursor position in the variables BtCursor.nKey \n** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.\n**\n** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)\n** prior to calling this routine.  \n*/\nstatic int saveCursorPosition(BtCursor *pCur){\n  int rc;\n\n  assert( CURSOR_VALID==pCur->eState );\n  assert( 0==pCur->pKey );\n  assert( cursorHoldsMutex(pCur) );\n\n  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);\n  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */\n\n  /* If this is an intKey table, then the above call to BtreeKeySize()\n  ** stores the integer key in pCur->nKey. In this case this value is\n  ** all that is required. Otherwise, if pCur is not open on an intKey\n  ** table, then malloc space for and store the pCur->nKey bytes of key \n  ** data.\n  */\n  if( 0==pCur->apPage[0]->intKey ){\n    void *pKey = sqlite3Malloc( (int)pCur->nKey );\n    if( pKey ){\n      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);\n      if( rc==SQLITE_OK ){\n        pCur->pKey = pKey;\n      }else{\n        sqlite3_free(pKey);\n      }\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }\n  assert( !pCur->apPage[0]->intKey || !pCur->pKey );\n\n  if( rc==SQLITE_OK ){\n    int i;\n    for(i=0; i<=pCur->iPage; i++){\n      releasePage(pCur->apPage[i]);\n      pCur->apPage[i] = 0;\n    }\n    pCur->iPage = -1;\n    pCur->eState = CURSOR_REQUIRESEEK;\n  }\n\n  invalidateOverflowCache(pCur);\n  return rc;\n}\n\n/*\n** Save the positions of all cursors (except pExcept) that are open on\n** the table  with root-page iRoot. Usually, this is called just before cursor\n** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).\n*/\nstatic int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){\n  BtCursor *p;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pExcept==0 || pExcept->pBt==pBt );\n  for(p=pBt->pCursor; p; p=p->pNext){\n    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && \n        p->eState==CURSOR_VALID ){\n      int rc = saveCursorPosition(p);\n      if( SQLITE_OK!=rc ){\n        return rc;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Clear the current cursor position.\n*/\nSQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  sqlite3_free(pCur->pKey);\n  pCur->pKey = 0;\n  pCur->eState = CURSOR_INVALID;\n}\n\n/*\n** In this version of BtreeMoveto, pKey is a packed index record\n** such as is generated by the OP_MakeRecord opcode.  Unpack the\n** record and then call BtreeMovetoUnpacked() to do the work.\n*/\nstatic int btreeMoveto(\n  BtCursor *pCur,     /* Cursor open on the btree to be searched */\n  const void *pKey,   /* Packed key if the btree is an index */\n  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */\n  int bias,           /* Bias search to the high end */\n  int *pRes           /* Write search results here */\n){\n  int rc;                    /* Status code */\n  UnpackedRecord *pIdxKey;   /* Unpacked index key */\n  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */\n  char *pFree = 0;\n\n  if( pKey ){\n    assert( nKey==(i64)(int)nKey );\n    pIdxKey = sqlite3VdbeAllocUnpackedRecord(\n        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree\n    );\n    if( pIdxKey==0 ) return SQLITE_NOMEM;\n    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);\n  }else{\n    pIdxKey = 0;\n  }\n  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);\n  if( pFree ){\n    sqlite3DbFree(pCur->pKeyInfo->db, pFree);\n  }\n  return rc;\n}\n\n/*\n** Restore the cursor to the position it was in (or as close to as possible)\n** when saveCursorPosition() was called. Note that this call deletes the \n** saved position info stored by saveCursorPosition(), so there can be\n** at most one effective restoreCursorPosition() call after each \n** saveCursorPosition().\n*/\nstatic int btreeRestoreCursorPosition(BtCursor *pCur){\n  int rc;\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState>=CURSOR_REQUIRESEEK );\n  if( pCur->eState==CURSOR_FAULT ){\n    return pCur->skipNext;\n  }\n  pCur->eState = CURSOR_INVALID;\n  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);\n  if( rc==SQLITE_OK ){\n    sqlite3_free(pCur->pKey);\n    pCur->pKey = 0;\n    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );\n  }\n  return rc;\n}\n\n#define restoreCursorPosition(p) \\\n  (p->eState>=CURSOR_REQUIRESEEK ? \\\n         btreeRestoreCursorPosition(p) : \\\n         SQLITE_OK)\n\n/*\n** Determine whether or not a cursor has moved from the position it\n** was last placed at.  Cursors can move when the row they are pointing\n** at is deleted out from under them.\n**\n** This routine returns an error code if something goes wrong.  The\n** integer *pHasMoved is set to one if the cursor has moved and 0 if not.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){\n  int rc;\n\n  rc = restoreCursorPosition(pCur);\n  if( rc ){\n    *pHasMoved = 1;\n    return rc;\n  }\n  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){\n    *pHasMoved = 1;\n  }else{\n    *pHasMoved = 0;\n  }\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Given a page number of a regular database page, return the page\n** number for the pointer-map page that contains the entry for the\n** input page number.\n**\n** Return 0 (not a valid page) for pgno==1 since there is\n** no pointer map associated with page 1.  The integrity_check logic\n** requires that ptrmapPageno(*,1)!=1.\n*/\nstatic Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){\n  int nPagesPerMapPage;\n  Pgno iPtrMap, ret;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pgno<2 ) return 0;\n  nPagesPerMapPage = (pBt->usableSize/5)+1;\n  iPtrMap = (pgno-2)/nPagesPerMapPage;\n  ret = (iPtrMap*nPagesPerMapPage) + 2; \n  if( ret==PENDING_BYTE_PAGE(pBt) ){\n    ret++;\n  }\n  return ret;\n}\n\n/*\n** Write an entry into the pointer map.\n**\n** This routine updates the pointer map entry for page number 'key'\n** so that it maps to type 'eType' and parent page number 'pgno'.\n**\n** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is\n** a no-op.  If an error occurs, the appropriate error code is written\n** into *pRC.\n*/\nstatic void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){\n  DbPage *pDbPage;  /* The pointer map page */\n  u8 *pPtrmap;      /* The pointer map data */\n  Pgno iPtrmap;     /* The pointer map page number */\n  int offset;       /* Offset in pointer map page */\n  int rc;           /* Return code from subfunctions */\n\n  if( *pRC ) return;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  /* The master-journal page number must never be used as a pointer map page */\n  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );\n\n  assert( pBt->autoVacuum );\n  if( key==0 ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    return;\n  }\n  iPtrmap = PTRMAP_PAGENO(pBt, key);\n  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);\n  if( rc!=SQLITE_OK ){\n    *pRC = rc;\n    return;\n  }\n  offset = PTRMAP_PTROFFSET(iPtrmap, key);\n  if( offset<0 ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    goto ptrmap_exit;\n  }\n  assert( offset <= (int)pBt->usableSize-5 );\n  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);\n\n  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){\n    TRACE((\"PTRMAP_UPDATE: %d->(%d,%d)\\n\", key, eType, parent));\n    *pRC= rc = sqlite3PagerWrite(pDbPage);\n    if( rc==SQLITE_OK ){\n      pPtrmap[offset] = eType;\n      put4byte(&pPtrmap[offset+1], parent);\n    }\n  }\n\nptrmap_exit:\n  sqlite3PagerUnref(pDbPage);\n}\n\n/*\n** Read an entry from the pointer map.\n**\n** This routine retrieves the pointer map entry for page 'key', writing\n** the type and parent page number to *pEType and *pPgno respectively.\n** An error code is returned if something goes wrong, otherwise SQLITE_OK.\n*/\nstatic int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){\n  DbPage *pDbPage;   /* The pointer map page */\n  int iPtrmap;       /* Pointer map page index */\n  u8 *pPtrmap;       /* Pointer map page data */\n  int offset;        /* Offset of entry in pointer map */\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n\n  iPtrmap = PTRMAP_PAGENO(pBt, key);\n  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);\n  if( rc!=0 ){\n    return rc;\n  }\n  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);\n\n  offset = PTRMAP_PTROFFSET(iPtrmap, key);\n  if( offset<0 ){\n    sqlite3PagerUnref(pDbPage);\n    return SQLITE_CORRUPT_BKPT;\n  }\n  assert( offset <= (int)pBt->usableSize-5 );\n  assert( pEType!=0 );\n  *pEType = pPtrmap[offset];\n  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);\n\n  sqlite3PagerUnref(pDbPage);\n  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;\n  return SQLITE_OK;\n}\n\n#else /* if defined SQLITE_OMIT_AUTOVACUUM */\n  #define ptrmapPut(w,x,y,z,rc)\n  #define ptrmapGet(w,x,y,z) SQLITE_OK\n  #define ptrmapPutOvflPtr(x, y, rc)\n#endif\n\n/*\n** Given a btree page and a cell index (0 means the first cell on\n** the page, 1 means the second cell, and so forth) return a pointer\n** to the cell content.\n**\n** This routine works only for pages that do not contain overflow cells.\n*/\n#define findCell(P,I) \\\n  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))\n#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))\n\n\n/*\n** This a more complex version of findCell() that works for\n** pages that do contain overflow cells.\n*/\nstatic u8 *findOverflowCell(MemPage *pPage, int iCell){\n  int i;\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  for(i=pPage->nOverflow-1; i>=0; i--){\n    int k;\n    k = pPage->aiOvfl[i];\n    if( k<=iCell ){\n      if( k==iCell ){\n        return pPage->apOvfl[i];\n      }\n      iCell--;\n    }\n  }\n  return findCell(pPage, iCell);\n}\n\n/*\n** Parse a cell content block and fill in the CellInfo structure.  There\n** are two versions of this function.  btreeParseCell() takes a \n** cell index as the second argument and btreeParseCellPtr() \n** takes a pointer to the body of the cell as its second argument.\n**\n** Within this file, the parseCell() macro can be called instead of\n** btreeParseCellPtr(). Using some compilers, this will be faster.\n*/\nstatic void btreeParseCellPtr(\n  MemPage *pPage,         /* Page containing the cell */\n  u8 *pCell,              /* Pointer to the cell text. */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  u16 n;                  /* Number bytes in cell content header */\n  u32 nPayload;           /* Number of bytes of cell payload */\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n\n  pInfo->pCell = pCell;\n  assert( pPage->leaf==0 || pPage->leaf==1 );\n  n = pPage->childPtrSize;\n  assert( n==4-4*pPage->leaf );\n  if( pPage->intKey ){\n    if( pPage->hasData ){\n      n += getVarint32(&pCell[n], nPayload);\n    }else{\n      nPayload = 0;\n    }\n    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);\n    pInfo->nData = nPayload;\n  }else{\n    pInfo->nData = 0;\n    n += getVarint32(&pCell[n], nPayload);\n    pInfo->nKey = nPayload;\n  }\n  pInfo->nPayload = nPayload;\n  pInfo->nHeader = n;\n  testcase( nPayload==pPage->maxLocal );\n  testcase( nPayload==pPage->maxLocal+1 );\n  if( likely(nPayload<=pPage->maxLocal) ){\n    /* This is the (easy) common case where the entire payload fits\n    ** on the local page.  No overflow is required.\n    */\n    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;\n    pInfo->nLocal = (u16)nPayload;\n    pInfo->iOverflow = 0;\n  }else{\n    /* If the payload will not fit completely on the local page, we have\n    ** to decide how much to store locally and how much to spill onto\n    ** overflow pages.  The strategy is to minimize the amount of unused\n    ** space on overflow pages while keeping the amount of local storage\n    ** in between minLocal and maxLocal.\n    **\n    ** Warning:  changing the way overflow payload is distributed in any\n    ** way will result in an incompatible file format.\n    */\n    int minLocal;  /* Minimum amount of payload held locally */\n    int maxLocal;  /* Maximum amount of payload held locally */\n    int surplus;   /* Overflow payload available for local storage */\n\n    minLocal = pPage->minLocal;\n    maxLocal = pPage->maxLocal;\n    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);\n    testcase( surplus==maxLocal );\n    testcase( surplus==maxLocal+1 );\n    if( surplus <= maxLocal ){\n      pInfo->nLocal = (u16)surplus;\n    }else{\n      pInfo->nLocal = (u16)minLocal;\n    }\n    pInfo->iOverflow = (u16)(pInfo->nLocal + n);\n    pInfo->nSize = pInfo->iOverflow + 4;\n  }\n}\n#define parseCell(pPage, iCell, pInfo) \\\n  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))\nstatic void btreeParseCell(\n  MemPage *pPage,         /* Page containing the cell */\n  int iCell,              /* The cell index.  First cell is 0 */\n  CellInfo *pInfo         /* Fill in this structure */\n){\n  parseCell(pPage, iCell, pInfo);\n}\n\n/*\n** Compute the total number of bytes that a Cell needs in the cell\n** data area of the btree-page.  The return number includes the cell\n** data header and the local payload, but not any overflow page or\n** the space used by the cell pointer.\n*/\nstatic u16 cellSizePtr(MemPage *pPage, u8 *pCell){\n  u8 *pIter = &pCell[pPage->childPtrSize];\n  u32 nSize;\n\n#ifdef SQLITE_DEBUG\n  /* The value returned by this function should always be the same as\n  ** the (CellInfo.nSize) value found by doing a full parse of the\n  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of\n  ** this function verifies that this invariant is not violated. */\n  CellInfo debuginfo;\n  btreeParseCellPtr(pPage, pCell, &debuginfo);\n#endif\n\n  if( pPage->intKey ){\n    u8 *pEnd;\n    if( pPage->hasData ){\n      pIter += getVarint32(pIter, nSize);\n    }else{\n      nSize = 0;\n    }\n\n    /* pIter now points at the 64-bit integer key value, a variable length \n    ** integer. The following block moves pIter to point at the first byte\n    ** past the end of the key value. */\n    pEnd = &pIter[9];\n    while( (*pIter++)&0x80 && pIter<pEnd );\n  }else{\n    pIter += getVarint32(pIter, nSize);\n  }\n\n  testcase( nSize==pPage->maxLocal );\n  testcase( nSize==pPage->maxLocal+1 );\n  if( nSize>pPage->maxLocal ){\n    int minLocal = pPage->minLocal;\n    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);\n    testcase( nSize==pPage->maxLocal );\n    testcase( nSize==pPage->maxLocal+1 );\n    if( nSize>pPage->maxLocal ){\n      nSize = minLocal;\n    }\n    nSize += 4;\n  }\n  nSize += (u32)(pIter - pCell);\n\n  /* The minimum size of any cell is 4 bytes. */\n  if( nSize<4 ){\n    nSize = 4;\n  }\n\n  assert( nSize==debuginfo.nSize );\n  return (u16)nSize;\n}\n\n#ifdef SQLITE_DEBUG\n/* This variation on cellSizePtr() is used inside of assert() statements\n** only. */\nstatic u16 cellSize(MemPage *pPage, int iCell){\n  return cellSizePtr(pPage, findCell(pPage, iCell));\n}\n#endif\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** If the cell pCell, part of page pPage contains a pointer\n** to an overflow page, insert an entry into the pointer-map\n** for the overflow page.\n*/\nstatic void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){\n  CellInfo info;\n  if( *pRC ) return;\n  assert( pCell!=0 );\n  btreeParseCellPtr(pPage, pCell, &info);\n  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );\n  if( info.iOverflow ){\n    Pgno ovfl = get4byte(&pCell[info.iOverflow]);\n    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);\n  }\n}\n#endif\n\n\n/*\n** Defragment the page given.  All Cells are moved to the\n** end of the page and all free space is collected into one\n** big FreeBlk that occurs in between the header and cell\n** pointer array and the cell content area.\n*/\nstatic int defragmentPage(MemPage *pPage){\n  int i;                     /* Loop counter */\n  int pc;                    /* Address of a i-th cell */\n  int hdr;                   /* Offset to the page header */\n  int size;                  /* Size of a cell */\n  int usableSize;            /* Number of usable bytes on a page */\n  int cellOffset;            /* Offset to the cell pointer array */\n  int cbrk;                  /* Offset to the cell content area */\n  int nCell;                 /* Number of cells on the page */\n  unsigned char *data;       /* The page data */\n  unsigned char *temp;       /* Temp area for cell content */\n  int iCellFirst;            /* First allowable cell index */\n  int iCellLast;             /* Last possible cell index */\n\n\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( pPage->pBt!=0 );\n  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );\n  assert( pPage->nOverflow==0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);\n  data = pPage->aData;\n  hdr = pPage->hdrOffset;\n  cellOffset = pPage->cellOffset;\n  nCell = pPage->nCell;\n  assert( nCell==get2byte(&data[hdr+3]) );\n  usableSize = pPage->pBt->usableSize;\n  cbrk = get2byte(&data[hdr+5]);\n  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);\n  cbrk = usableSize;\n  iCellFirst = cellOffset + 2*nCell;\n  iCellLast = usableSize - 4;\n  for(i=0; i<nCell; i++){\n    u8 *pAddr;     /* The i-th cell pointer */\n    pAddr = &data[cellOffset + i*2];\n    pc = get2byte(pAddr);\n    testcase( pc==iCellFirst );\n    testcase( pc==iCellLast );\n#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)\n    /* These conditions have already been verified in btreeInitPage()\n    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined \n    */\n    if( pc<iCellFirst || pc>iCellLast ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n#endif\n    assert( pc>=iCellFirst && pc<=iCellLast );\n    size = cellSizePtr(pPage, &temp[pc]);\n    cbrk -= size;\n#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)\n    if( cbrk<iCellFirst ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n#else\n    if( cbrk<iCellFirst || pc+size>usableSize ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n#endif\n    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );\n    testcase( cbrk+size==usableSize );\n    testcase( pc+size==usableSize );\n    memcpy(&data[cbrk], &temp[pc], size);\n    put2byte(pAddr, cbrk);\n  }\n  assert( cbrk>=iCellFirst );\n  put2byte(&data[hdr+5], cbrk);\n  data[hdr+1] = 0;\n  data[hdr+2] = 0;\n  data[hdr+7] = 0;\n  memset(&data[iCellFirst], 0, cbrk-iCellFirst);\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  if( cbrk-iCellFirst!=pPage->nFree ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Allocate nByte bytes of space from within the B-Tree page passed\n** as the first argument. Write into *pIdx the index into pPage->aData[]\n** of the first byte of allocated space. Return either SQLITE_OK or\n** an error code (usually SQLITE_CORRUPT).\n**\n** The caller guarantees that there is sufficient space to make the\n** allocation.  This routine might need to defragment in order to bring\n** all the space together, however.  This routine will avoid using\n** the first two bytes past the cell pointer area since presumably this\n** allocation is being made in order to insert a new cell, so we will\n** also end up needing a new cell pointer.\n*/\nstatic int allocateSpace(MemPage *pPage, int nByte, int *pIdx){\n  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */\n  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */\n  int nFrag;                           /* Number of fragmented bytes on pPage */\n  int top;                             /* First byte of cell content area */\n  int gap;        /* First byte of gap between cell pointers and cell content */\n  int rc;         /* Integer return code */\n  int usableSize; /* Usable size of the page */\n  \n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( pPage->pBt );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( nByte>=0 );  /* Minimum cell size is 4 */\n  assert( pPage->nFree>=nByte );\n  assert( pPage->nOverflow==0 );\n  usableSize = pPage->pBt->usableSize;\n  assert( nByte < usableSize-8 );\n\n  nFrag = data[hdr+7];\n  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );\n  gap = pPage->cellOffset + 2*pPage->nCell;\n  top = get2byteNotZero(&data[hdr+5]);\n  if( gap>top ) return SQLITE_CORRUPT_BKPT;\n  testcase( gap+2==top );\n  testcase( gap+1==top );\n  testcase( gap==top );\n\n  if( nFrag>=60 ){\n    /* Always defragment highly fragmented pages */\n    rc = defragmentPage(pPage);\n    if( rc ) return rc;\n    top = get2byteNotZero(&data[hdr+5]);\n  }else if( gap+2<=top ){\n    /* Search the freelist looking for a free slot big enough to satisfy \n    ** the request. The allocation is made from the first free slot in \n    ** the list that is large enough to accomadate it.\n    */\n    int pc, addr;\n    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){\n      int size;            /* Size of the free slot */\n      if( pc>usableSize-4 || pc<addr+4 ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      size = get2byte(&data[pc+2]);\n      if( size>=nByte ){\n        int x = size - nByte;\n        testcase( x==4 );\n        testcase( x==3 );\n        if( x<4 ){\n          /* Remove the slot from the free-list. Update the number of\n          ** fragmented bytes within the page. */\n          memcpy(&data[addr], &data[pc], 2);\n          data[hdr+7] = (u8)(nFrag + x);\n        }else if( size+pc > usableSize ){\n          return SQLITE_CORRUPT_BKPT;\n        }else{\n          /* The slot remains on the free-list. Reduce its size to account\n          ** for the portion used by the new allocation. */\n          put2byte(&data[pc+2], x);\n        }\n        *pIdx = pc + x;\n        return SQLITE_OK;\n      }\n    }\n  }\n\n  /* Check to make sure there is enough space in the gap to satisfy\n  ** the allocation.  If not, defragment.\n  */\n  testcase( gap+2+nByte==top );\n  if( gap+2+nByte>top ){\n    rc = defragmentPage(pPage);\n    if( rc ) return rc;\n    top = get2byteNotZero(&data[hdr+5]);\n    assert( gap+nByte<=top );\n  }\n\n\n  /* Allocate memory from the gap in between the cell pointer array\n  ** and the cell content area.  The btreeInitPage() call has already\n  ** validated the freelist.  Given that the freelist is valid, there\n  ** is no way that the allocation can extend off the end of the page.\n  ** The assert() below verifies the previous sentence.\n  */\n  top -= nByte;\n  put2byte(&data[hdr+5], top);\n  assert( top+nByte <= (int)pPage->pBt->usableSize );\n  *pIdx = top;\n  return SQLITE_OK;\n}\n\n/*\n** Return a section of the pPage->aData to the freelist.\n** The first byte of the new free block is pPage->aDisk[start]\n** and the size of the block is \"size\" bytes.\n**\n** Most of the effort here is involved in coalesing adjacent\n** free blocks into a single big free block.\n*/\nstatic int freeSpace(MemPage *pPage, int start, int size){\n  int addr, pbegin, hdr;\n  int iLast;                        /* Largest possible freeblock offset */\n  unsigned char *data = pPage->aData;\n\n  assert( pPage->pBt!=0 );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );\n  assert( (start + size) <= (int)pPage->pBt->usableSize );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( size>=0 );   /* Minimum cell size is 4 */\n\n  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){\n    /* Overwrite deleted information with zeros when the secure_delete\n    ** option is enabled */\n    memset(&data[start], 0, size);\n  }\n\n  /* Add the space back into the linked list of freeblocks.  Note that\n  ** even though the freeblock list was checked by btreeInitPage(),\n  ** btreeInitPage() did not detect overlapping cells or\n  ** freeblocks that overlapped cells.   Nor does it detect when the\n  ** cell content area exceeds the value in the page header.  If these\n  ** situations arise, then subsequent insert operations might corrupt\n  ** the freelist.  So we do need to check for corruption while scanning\n  ** the freelist.\n  */\n  hdr = pPage->hdrOffset;\n  addr = hdr + 1;\n  iLast = pPage->pBt->usableSize - 4;\n  assert( start<=iLast );\n  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){\n    if( pbegin<addr+4 ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n    addr = pbegin;\n  }\n  if( pbegin>iLast ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  assert( pbegin>addr || pbegin==0 );\n  put2byte(&data[addr], start);\n  put2byte(&data[start], pbegin);\n  put2byte(&data[start+2], size);\n  pPage->nFree = pPage->nFree + (u16)size;\n\n  /* Coalesce adjacent free blocks */\n  addr = hdr + 1;\n  while( (pbegin = get2byte(&data[addr]))>0 ){\n    int pnext, psize, x;\n    assert( pbegin>addr );\n    assert( pbegin <= (int)pPage->pBt->usableSize-4 );\n    pnext = get2byte(&data[pbegin]);\n    psize = get2byte(&data[pbegin+2]);\n    if( pbegin + psize + 3 >= pnext && pnext>0 ){\n      int frag = pnext - (pbegin+psize);\n      if( (frag<0) || (frag>(int)data[hdr+7]) ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      data[hdr+7] -= (u8)frag;\n      x = get2byte(&data[pnext]);\n      put2byte(&data[pbegin], x);\n      x = pnext + get2byte(&data[pnext+2]) - pbegin;\n      put2byte(&data[pbegin+2], x);\n    }else{\n      addr = pbegin;\n    }\n  }\n\n  /* If the cell content area begins with a freeblock, remove it. */\n  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){\n    int top;\n    pbegin = get2byte(&data[hdr+1]);\n    memcpy(&data[hdr+1], &data[pbegin], 2);\n    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);\n    put2byte(&data[hdr+5], top);\n  }\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  return SQLITE_OK;\n}\n\n/*\n** Decode the flags byte (the first byte of the header) for a page\n** and initialize fields of the MemPage structure accordingly.\n**\n** Only the following combinations are supported.  Anything different\n** indicates a corrupt database files:\n**\n**         PTF_ZERODATA\n**         PTF_ZERODATA | PTF_LEAF\n**         PTF_LEAFDATA | PTF_INTKEY\n**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF\n*/\nstatic int decodeFlags(MemPage *pPage, int flagByte){\n  BtShared *pBt;     /* A copy of pPage->pBt */\n\n  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );\n  flagByte &= ~PTF_LEAF;\n  pPage->childPtrSize = 4-4*pPage->leaf;\n  pBt = pPage->pBt;\n  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){\n    pPage->intKey = 1;\n    pPage->hasData = pPage->leaf;\n    pPage->maxLocal = pBt->maxLeaf;\n    pPage->minLocal = pBt->minLeaf;\n  }else if( flagByte==PTF_ZERODATA ){\n    pPage->intKey = 0;\n    pPage->hasData = 0;\n    pPage->maxLocal = pBt->maxLocal;\n    pPage->minLocal = pBt->minLocal;\n  }else{\n    return SQLITE_CORRUPT_BKPT;\n  }\n  pPage->max1bytePayload = pBt->max1bytePayload;\n  return SQLITE_OK;\n}\n\n/*\n** Initialize the auxiliary information for a disk block.\n**\n** Return SQLITE_OK on success.  If we see that the page does\n** not contain a well-formed database page, then return \n** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not\n** guarantee that the page is well-formed.  It only shows that\n** we failed to detect any corruption.\n*/\nstatic int btreeInitPage(MemPage *pPage){\n\n  assert( pPage->pBt!=0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );\n  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );\n  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );\n\n  if( !pPage->isInit ){\n    u16 pc;            /* Address of a freeblock within pPage->aData[] */\n    u8 hdr;            /* Offset to beginning of page header */\n    u8 *data;          /* Equal to pPage->aData */\n    BtShared *pBt;        /* The main btree structure */\n    int usableSize;    /* Amount of usable space on each page */\n    u16 cellOffset;    /* Offset from start of page to first cell pointer */\n    int nFree;         /* Number of unused bytes on the page */\n    int top;           /* First byte of the cell content area */\n    int iCellFirst;    /* First allowable cell or freeblock offset */\n    int iCellLast;     /* Last possible cell or freeblock offset */\n\n    pBt = pPage->pBt;\n\n    hdr = pPage->hdrOffset;\n    data = pPage->aData;\n    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;\n    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );\n    pPage->maskPage = (u16)(pBt->pageSize - 1);\n    pPage->nOverflow = 0;\n    usableSize = pBt->usableSize;\n    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;\n    pPage->aDataEnd = &data[usableSize];\n    pPage->aCellIdx = &data[cellOffset];\n    top = get2byteNotZero(&data[hdr+5]);\n    pPage->nCell = get2byte(&data[hdr+3]);\n    if( pPage->nCell>MX_CELL(pBt) ){\n      /* To many cells for a single page.  The page must be corrupt */\n      return SQLITE_CORRUPT_BKPT;\n    }\n    testcase( pPage->nCell==MX_CELL(pBt) );\n\n    /* A malformed database page might cause us to read past the end\n    ** of page when parsing a cell.  \n    **\n    ** The following block of code checks early to see if a cell extends\n    ** past the end of a page boundary and causes SQLITE_CORRUPT to be \n    ** returned if it does.\n    */\n    iCellFirst = cellOffset + 2*pPage->nCell;\n    iCellLast = usableSize - 4;\n#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)\n    {\n      int i;            /* Index into the cell pointer array */\n      int sz;           /* Size of a cell */\n\n      if( !pPage->leaf ) iCellLast--;\n      for(i=0; i<pPage->nCell; i++){\n        pc = get2byte(&data[cellOffset+i*2]);\n        testcase( pc==iCellFirst );\n        testcase( pc==iCellLast );\n        if( pc<iCellFirst || pc>iCellLast ){\n          return SQLITE_CORRUPT_BKPT;\n        }\n        sz = cellSizePtr(pPage, &data[pc]);\n        testcase( pc+sz==usableSize );\n        if( pc+sz>usableSize ){\n          return SQLITE_CORRUPT_BKPT;\n        }\n      }\n      if( !pPage->leaf ) iCellLast++;\n    }  \n#endif\n\n    /* Compute the total free space on the page */\n    pc = get2byte(&data[hdr+1]);\n    nFree = data[hdr+7] + top;\n    while( pc>0 ){\n      u16 next, size;\n      if( pc<iCellFirst || pc>iCellLast ){\n        /* Start of free block is off the page */\n        return SQLITE_CORRUPT_BKPT; \n      }\n      next = get2byte(&data[pc]);\n      size = get2byte(&data[pc+2]);\n      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){\n        /* Free blocks must be in ascending order. And the last byte of\n        ** the free-block must lie on the database page.  */\n        return SQLITE_CORRUPT_BKPT; \n      }\n      nFree = nFree + size;\n      pc = next;\n    }\n\n    /* At this point, nFree contains the sum of the offset to the start\n    ** of the cell-content area plus the number of free bytes within\n    ** the cell-content area. If this is greater than the usable-size\n    ** of the page, then the page must be corrupted. This check also\n    ** serves to verify that the offset to the start of the cell-content\n    ** area, according to the page header, lies within the page.\n    */\n    if( nFree>usableSize ){\n      return SQLITE_CORRUPT_BKPT; \n    }\n    pPage->nFree = (u16)(nFree - iCellFirst);\n    pPage->isInit = 1;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Set up a raw page so that it looks like a database page holding\n** no entries.\n*/\nstatic void zeroPage(MemPage *pPage, int flags){\n  unsigned char *data = pPage->aData;\n  BtShared *pBt = pPage->pBt;\n  u8 hdr = pPage->hdrOffset;\n  u16 first;\n\n  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );\n  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );\n  assert( sqlite3PagerGetData(pPage->pDbPage) == data );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pBt->btsFlags & BTS_SECURE_DELETE ){\n    memset(&data[hdr], 0, pBt->usableSize - hdr);\n  }\n  data[hdr] = (char)flags;\n  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);\n  memset(&data[hdr+1], 0, 4);\n  data[hdr+7] = 0;\n  put2byte(&data[hdr+5], pBt->usableSize);\n  pPage->nFree = (u16)(pBt->usableSize - first);\n  decodeFlags(pPage, flags);\n  pPage->hdrOffset = hdr;\n  pPage->cellOffset = first;\n  pPage->aDataEnd = &data[pBt->usableSize];\n  pPage->aCellIdx = &data[first];\n  pPage->nOverflow = 0;\n  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );\n  pPage->maskPage = (u16)(pBt->pageSize - 1);\n  pPage->nCell = 0;\n  pPage->isInit = 1;\n}\n\n\n/*\n** Convert a DbPage obtained from the pager into a MemPage used by\n** the btree layer.\n*/\nstatic MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){\n  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);\n  pPage->aData = sqlite3PagerGetData(pDbPage);\n  pPage->pDbPage = pDbPage;\n  pPage->pBt = pBt;\n  pPage->pgno = pgno;\n  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;\n  return pPage; \n}\n\n/*\n** Get a page from the pager.  Initialize the MemPage.pBt and\n** MemPage.aData elements if needed.\n**\n** If the noContent flag is set, it means that we do not care about\n** the content of the page at this time.  So do not go to the disk\n** to fetch the content.  Just fill in the content with zeros for now.\n** If in the future we call sqlite3PagerWrite() on this page, that\n** means we have started to be concerned about content and the disk\n** read should occur at that point.\n*/\nstatic int btreeGetPage(\n  BtShared *pBt,       /* The btree */\n  Pgno pgno,           /* Number of the page to fetch */\n  MemPage **ppPage,    /* Return the page in this parameter */\n  int noContent        /* Do not load page content if true */\n){\n  int rc;\n  DbPage *pDbPage;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);\n  if( rc ) return rc;\n  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);\n  return SQLITE_OK;\n}\n\n/*\n** Retrieve a page from the pager cache. If the requested page is not\n** already in the pager cache return NULL. Initialize the MemPage.pBt and\n** MemPage.aData elements if needed.\n*/\nstatic MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){\n  DbPage *pDbPage;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);\n  if( pDbPage ){\n    return btreePageFromDbPage(pDbPage, pgno, pBt);\n  }\n  return 0;\n}\n\n/*\n** Return the size of the database file in pages. If there is any kind of\n** error, return ((unsigned int)-1).\n*/\nstatic Pgno btreePagecount(BtShared *pBt){\n  return pBt->nPage;\n}\nSQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( ((p->pBt->nPage)&0x8000000)==0 );\n  return (int)btreePagecount(p->pBt);\n}\n\n/*\n** Get a page from the pager and initialize it.  This routine is just a\n** convenience wrapper around separate calls to btreeGetPage() and \n** btreeInitPage().\n**\n** If an error occurs, then the value *ppPage is set to is undefined. It\n** may remain unchanged, or it may be set to an invalid value.\n*/\nstatic int getAndInitPage(\n  BtShared *pBt,          /* The database file */\n  Pgno pgno,           /* Number of the page to get */\n  MemPage **ppPage     /* Write the page pointer here */\n){\n  int rc;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n\n  if( pgno>btreePagecount(pBt) ){\n    rc = SQLITE_CORRUPT_BKPT;\n  }else{\n    rc = btreeGetPage(pBt, pgno, ppPage, 0);\n    if( rc==SQLITE_OK ){\n      rc = btreeInitPage(*ppPage);\n      if( rc!=SQLITE_OK ){\n        releasePage(*ppPage);\n      }\n    }\n  }\n\n  testcase( pgno==0 );\n  assert( pgno!=0 || rc==SQLITE_CORRUPT );\n  return rc;\n}\n\n/*\n** Release a MemPage.  This should be called once for each prior\n** call to btreeGetPage.\n*/\nstatic void releasePage(MemPage *pPage){\n  if( pPage ){\n    assert( pPage->aData );\n    assert( pPage->pBt );\n    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );\n    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );\n    assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n    sqlite3PagerUnref(pPage->pDbPage);\n  }\n}\n\n/*\n** During a rollback, when the pager reloads information into the cache\n** so that the cache is restored to its original state at the start of\n** the transaction, for each page restored this routine is called.\n**\n** This routine needs to reset the extra data section at the end of the\n** page to agree with the restored data.\n*/\nstatic void pageReinit(DbPage *pData){\n  MemPage *pPage;\n  pPage = (MemPage *)sqlite3PagerGetExtra(pData);\n  assert( sqlite3PagerPageRefcount(pData)>0 );\n  if( pPage->isInit ){\n    assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n    pPage->isInit = 0;\n    if( sqlite3PagerPageRefcount(pData)>1 ){\n      /* pPage might not be a btree page;  it might be an overflow page\n      ** or ptrmap page or a free page.  In those cases, the following\n      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.\n      ** But no harm is done by this.  And it is very important that\n      ** btreeInitPage() be called on every btree page so we make\n      ** the call for every page that comes in for re-initing. */\n      btreeInitPage(pPage);\n    }\n  }\n}\n\n/*\n** Invoke the busy handler for a btree.\n*/\nstatic int btreeInvokeBusyHandler(void *pArg){\n  BtShared *pBt = (BtShared*)pArg;\n  assert( pBt->db );\n  assert( sqlite3_mutex_held(pBt->db->mutex) );\n  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);\n}\n\n/*\n** Open a database file.\n** \n** zFilename is the name of the database file.  If zFilename is NULL\n** then an ephemeral database is created.  The ephemeral database might\n** be exclusively in memory, or it might use a disk-based memory cache.\n** Either way, the ephemeral database will be automatically deleted \n** when sqlite3BtreeClose() is called.\n**\n** If zFilename is \":memory:\" then an in-memory database is created\n** that is automatically destroyed when it is closed.\n**\n** The \"flags\" parameter is a bitmask that might contain bits like\n** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.\n**\n** If the database is already opened in the same database connection\n** and we are in shared cache mode, then the open will fail with an\n** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared\n** objects in the same database connection since doing so will lead\n** to problems with locking.\n*/\nSQLITE_PRIVATE int sqlite3BtreeOpen(\n  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */\n  const char *zFilename,  /* Name of the file containing the BTree database */\n  sqlite3 *db,            /* Associated database handle */\n  Btree **ppBtree,        /* Pointer to new Btree object written here */\n  int flags,              /* Options */\n  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */\n){\n  BtShared *pBt = 0;             /* Shared part of btree structure */\n  Btree *p;                      /* Handle to return */\n  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */\n  int rc = SQLITE_OK;            /* Result code from this function */\n  u8 nReserve;                   /* Byte of unused space on each page */\n  unsigned char zDbHeader[100];  /* Database header content */\n\n  /* True if opening an ephemeral, temporary database */\n  const int isTempDb = zFilename==0 || zFilename[0]==0;\n\n  /* Set the variable isMemdb to true for an in-memory database, or \n  ** false for a file-based database.\n  */\n#ifdef SQLITE_OMIT_MEMORYDB\n  const int isMemdb = 0;\n#else\n  const int isMemdb = (zFilename && strcmp(zFilename, \":memory:\")==0)\n                       || (isTempDb && sqlite3TempInMemory(db))\n                       || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;\n#endif\n\n  assert( db!=0 );\n  assert( pVfs!=0 );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */\n\n  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */\n  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );\n\n  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */\n  assert( (flags & BTREE_SINGLE)==0 || isTempDb );\n\n  if( isMemdb ){\n    flags |= BTREE_MEMORY;\n  }\n  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){\n    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;\n  }\n  p = sqlite3MallocZero(sizeof(Btree));\n  if( !p ){\n    return SQLITE_NOMEM;\n  }\n  p->inTrans = TRANS_NONE;\n  p->db = db;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  p->lock.pBtree = p;\n  p->lock.iTable = 1;\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n  /*\n  ** If this Btree is a candidate for shared cache, try to find an\n  ** existing BtShared object that we can share with\n  */\n  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){\n    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){\n      int nFullPathname = pVfs->mxPathname+1;\n      char *zFullPathname = sqlite3Malloc(nFullPathname);\n      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )\n      p->sharable = 1;\n      if( !zFullPathname ){\n        sqlite3_free(p);\n        return SQLITE_NOMEM;\n      }\n      if( isMemdb ){\n        memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);\n      }else{\n        rc = sqlite3OsFullPathname(pVfs, zFilename,\n                                   nFullPathname, zFullPathname);\n        if( rc ){\n          sqlite3_free(zFullPathname);\n          sqlite3_free(p);\n          return rc;\n        }\n      }\n#if SQLITE_THREADSAFE\n      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);\n      sqlite3_mutex_enter(mutexOpen);\n      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n      sqlite3_mutex_enter(mutexShared);\n#endif\n      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){\n        assert( pBt->nRef>0 );\n        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))\n                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){\n          int iDb;\n          for(iDb=db->nDb-1; iDb>=0; iDb--){\n            Btree *pExisting = db->aDb[iDb].pBt;\n            if( pExisting && pExisting->pBt==pBt ){\n              sqlite3_mutex_leave(mutexShared);\n              sqlite3_mutex_leave(mutexOpen);\n              sqlite3_free(zFullPathname);\n              sqlite3_free(p);\n              return SQLITE_CONSTRAINT;\n            }\n          }\n          p->pBt = pBt;\n          pBt->nRef++;\n          break;\n        }\n      }\n      sqlite3_mutex_leave(mutexShared);\n      sqlite3_free(zFullPathname);\n    }\n#ifdef SQLITE_DEBUG\n    else{\n      /* In debug mode, we mark all persistent databases as sharable\n      ** even when they are not.  This exercises the locking code and\n      ** gives more opportunity for asserts(sqlite3_mutex_held())\n      ** statements to find locking problems.\n      */\n      p->sharable = 1;\n    }\n#endif\n  }\n#endif\n  if( pBt==0 ){\n    /*\n    ** The following asserts make sure that structures used by the btree are\n    ** the right size.  This is to guard against size changes that result\n    ** when compiling on a different architecture.\n    */\n    assert( sizeof(i64)==8 || sizeof(i64)==4 );\n    assert( sizeof(u64)==8 || sizeof(u64)==4 );\n    assert( sizeof(u32)==4 );\n    assert( sizeof(u16)==2 );\n    assert( sizeof(Pgno)==4 );\n  \n    pBt = sqlite3MallocZero( sizeof(*pBt) );\n    if( pBt==0 ){\n      rc = SQLITE_NOMEM;\n      goto btree_open_out;\n    }\n    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,\n                          EXTRA_SIZE, flags, vfsFlags, pageReinit);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);\n    }\n    if( rc!=SQLITE_OK ){\n      goto btree_open_out;\n    }\n    pBt->openFlags = (u8)flags;\n    pBt->db = db;\n    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);\n    p->pBt = pBt;\n  \n    pBt->pCursor = 0;\n    pBt->pPage1 = 0;\n    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;\n#ifdef SQLITE_SECURE_DELETE\n    pBt->btsFlags |= BTS_SECURE_DELETE;\n#endif\n    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);\n    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE\n         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){\n      pBt->pageSize = 0;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      /* If the magic name \":memory:\" will create an in-memory database, then\n      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if\n      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if\n      ** SQLITE_OMIT_MEMORYDB has been defined, then \":memory:\" is just a\n      ** regular file-name. In this case the auto-vacuum applies as per normal.\n      */\n      if( zFilename && !isMemdb ){\n        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);\n        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);\n      }\n#endif\n      nReserve = 0;\n    }else{\n      nReserve = zDbHeader[20];\n      pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);\n      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);\n#endif\n    }\n    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);\n    if( rc ) goto btree_open_out;\n    pBt->usableSize = pBt->pageSize - nReserve;\n    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */\n   \n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n    /* Add the new BtShared object to the linked list sharable BtShareds.\n    */\n    if( p->sharable ){\n      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )\n      pBt->nRef = 1;\n      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)\n      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){\n        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);\n        if( pBt->mutex==0 ){\n          rc = SQLITE_NOMEM;\n          db->mallocFailed = 0;\n          goto btree_open_out;\n        }\n      }\n      sqlite3_mutex_enter(mutexShared);\n      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);\n      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;\n      sqlite3_mutex_leave(mutexShared);\n    }\n#endif\n  }\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)\n  /* If the new Btree uses a sharable pBtShared, then link the new\n  ** Btree into the list of all sharable Btrees for the same connection.\n  ** The list is kept in ascending order by pBt address.\n  */\n  if( p->sharable ){\n    int i;\n    Btree *pSib;\n    for(i=0; i<db->nDb; i++){\n      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){\n        while( pSib->pPrev ){ pSib = pSib->pPrev; }\n        if( p->pBt<pSib->pBt ){\n          p->pNext = pSib;\n          p->pPrev = 0;\n          pSib->pPrev = p;\n        }else{\n          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){\n            pSib = pSib->pNext;\n          }\n          p->pNext = pSib->pNext;\n          p->pPrev = pSib;\n          if( p->pNext ){\n            p->pNext->pPrev = p;\n          }\n          pSib->pNext = p;\n        }\n        break;\n      }\n    }\n  }\n#endif\n  *ppBtree = p;\n\nbtree_open_out:\n  if( rc!=SQLITE_OK ){\n    if( pBt && pBt->pPager ){\n      sqlite3PagerClose(pBt->pPager);\n    }\n    sqlite3_free(pBt);\n    sqlite3_free(p);\n    *ppBtree = 0;\n  }else{\n    /* If the B-Tree was successfully opened, set the pager-cache size to the\n    ** default value. Except, when opening on an existing shared pager-cache,\n    ** do not change the pager-cache size.\n    */\n    if( sqlite3BtreeSchema(p, 0, 0)==0 ){\n      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);\n    }\n  }\n  if( mutexOpen ){\n    assert( sqlite3_mutex_held(mutexOpen) );\n    sqlite3_mutex_leave(mutexOpen);\n  }\n  return rc;\n}\n\n/*\n** Decrement the BtShared.nRef counter.  When it reaches zero,\n** remove the BtShared structure from the sharing list.  Return\n** true if the BtShared.nRef counter reaches zero and return\n** false if it is still positive.\n*/\nstatic int removeFromSharingList(BtShared *pBt){\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  MUTEX_LOGIC( sqlite3_mutex *pMaster; )\n  BtShared *pList;\n  int removed = 0;\n\n  assert( sqlite3_mutex_notheld(pBt->mutex) );\n  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(pMaster);\n  pBt->nRef--;\n  if( pBt->nRef<=0 ){\n    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){\n      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;\n    }else{\n      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);\n      while( ALWAYS(pList) && pList->pNext!=pBt ){\n        pList=pList->pNext;\n      }\n      if( ALWAYS(pList) ){\n        pList->pNext = pBt->pNext;\n      }\n    }\n    if( SQLITE_THREADSAFE ){\n      sqlite3_mutex_free(pBt->mutex);\n    }\n    removed = 1;\n  }\n  sqlite3_mutex_leave(pMaster);\n  return removed;\n#else\n  return 1;\n#endif\n}\n\n/*\n** Make sure pBt->pTmpSpace points to an allocation of \n** MX_CELL_SIZE(pBt) bytes.\n*/\nstatic void allocateTempSpace(BtShared *pBt){\n  if( !pBt->pTmpSpace ){\n    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );\n  }\n}\n\n/*\n** Free the pBt->pTmpSpace allocation\n*/\nstatic void freeTempSpace(BtShared *pBt){\n  sqlite3PageFree( pBt->pTmpSpace);\n  pBt->pTmpSpace = 0;\n}\n\n/*\n** Close an open database and invalidate all cursors.\n*/\nSQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){\n  BtShared *pBt = p->pBt;\n  BtCursor *pCur;\n\n  /* Close all cursors opened via this handle.  */\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  pCur = pBt->pCursor;\n  while( pCur ){\n    BtCursor *pTmp = pCur;\n    pCur = pCur->pNext;\n    if( pTmp->pBtree==p ){\n      sqlite3BtreeCloseCursor(pTmp);\n    }\n  }\n\n  /* Rollback any active transaction and free the handle structure.\n  ** The call to sqlite3BtreeRollback() drops any table-locks held by\n  ** this handle.\n  */\n  sqlite3BtreeRollback(p, SQLITE_OK);\n  sqlite3BtreeLeave(p);\n\n  /* If there are still other outstanding references to the shared-btree\n  ** structure, return now. The remainder of this procedure cleans \n  ** up the shared-btree.\n  */\n  assert( p->wantToLock==0 && p->locked==0 );\n  if( !p->sharable || removeFromSharingList(pBt) ){\n    /* The pBt is no longer on the sharing list, so we can access\n    ** it without having to hold the mutex.\n    **\n    ** Clean out and delete the BtShared object.\n    */\n    assert( !pBt->pCursor );\n    sqlite3PagerClose(pBt->pPager);\n    if( pBt->xFreeSchema && pBt->pSchema ){\n      pBt->xFreeSchema(pBt->pSchema);\n    }\n    sqlite3DbFree(0, pBt->pSchema);\n    freeTempSpace(pBt);\n    sqlite3_free(pBt);\n  }\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  assert( p->wantToLock==0 );\n  assert( p->locked==0 );\n  if( p->pPrev ) p->pPrev->pNext = p->pNext;\n  if( p->pNext ) p->pNext->pPrev = p->pPrev;\n#endif\n\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Change the limit on the number of pages allowed in the cache.\n**\n** The maximum number of cache pages is set to the absolute\n** value of mxPage.  If mxPage is negative, the pager will\n** operate asynchronously - it will not stop to do fsync()s\n** to insure data is written to the disk surface before\n** continuing.  Transactions still work if synchronous is off,\n** and the database cannot be corrupted if this program\n** crashes.  But if the operating system crashes or there is\n** an abrupt power failure when synchronous is off, the database\n** could be left in an inconsistent and unrecoverable state.\n** Synchronous is on by default so database corruption is not\n** normally a worry.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  sqlite3PagerSetCachesize(pBt->pPager, mxPage);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n\n/*\n** Change the way data is synced to disk in order to increase or decrease\n** how well the database resists damage due to OS crashes and power\n** failures.  Level 1 is the same as asynchronous (no syncs() occur and\n** there is a high probability of damage)  Level 2 is the default.  There\n** is a very low but non-zero probability of damage.  Level 3 reduces the\n** probability of damage to near zero but with a write performance reduction.\n*/\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\nSQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(\n  Btree *p,              /* The btree to set the safety level on */\n  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */\n  int fullSync,          /* PRAGMA fullfsync. */\n  int ckptFullSync       /* PRAGMA checkpoint_fullfync */\n){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  assert( level>=1 && level<=3 );\n  sqlite3BtreeEnter(p);\n  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Return TRUE if the given btree is set to safety level 1.  In other\n** words, return TRUE if no sync() occurs on the disk files.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){\n  BtShared *pBt = p->pBt;\n  int rc;\n  assert( sqlite3_mutex_held(p->db->mutex) );  \n  sqlite3BtreeEnter(p);\n  assert( pBt && pBt->pPager );\n  rc = sqlite3PagerNosync(pBt->pPager);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Change the default pages size and the number of reserved bytes per page.\n** Or, if the page size has already been fixed, return SQLITE_READONLY \n** without changing anything.\n**\n** The page size must be a power of 2 between 512 and 65536.  If the page\n** size supplied does not meet this constraint then the page size is not\n** changed.\n**\n** Page sizes are constrained to be a power of two so that the region\n** of the database file used for locking (beginning at PENDING_BYTE,\n** the first byte past the 1GB boundary, 0x40000000) needs to occur\n** at the beginning of a page.\n**\n** If parameter nReserve is less than zero, then the number of reserved\n** bytes per page is left unchanged.\n**\n** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size\n** and autovacuum mode can no longer be changed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){\n  int rc = SQLITE_OK;\n  BtShared *pBt = p->pBt;\n  assert( nReserve>=-1 && nReserve<=255 );\n  sqlite3BtreeEnter(p);\n  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){\n    sqlite3BtreeLeave(p);\n    return SQLITE_READONLY;\n  }\n  if( nReserve<0 ){\n    nReserve = pBt->pageSize - pBt->usableSize;\n  }\n  assert( nReserve>=0 && nReserve<=255 );\n  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&\n        ((pageSize-1)&pageSize)==0 ){\n    assert( (pageSize & 7)==0 );\n    assert( !pBt->pPage1 && !pBt->pCursor );\n    pBt->pageSize = (u32)pageSize;\n    freeTempSpace(pBt);\n  }\n  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);\n  pBt->usableSize = pBt->pageSize - (u16)nReserve;\n  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Return the currently defined page size\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){\n  return p->pBt->pageSize;\n}\n\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)\n/*\n** Return the number of bytes of space at the end of every page that\n** are intentually left unused.  This is the \"reserved\" space that is\n** sometimes used by extensions.\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){\n  int n;\n  sqlite3BtreeEnter(p);\n  n = p->pBt->pageSize - p->pBt->usableSize;\n  sqlite3BtreeLeave(p);\n  return n;\n}\n\n/*\n** Set the maximum page count for a database if mxPage is positive.\n** No changes are made if mxPage is 0 or negative.\n** Regardless of the value of mxPage, return the maximum page count.\n*/\nSQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){\n  int n;\n  sqlite3BtreeEnter(p);\n  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);\n  sqlite3BtreeLeave(p);\n  return n;\n}\n\n/*\n** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,\n** then make no changes.  Always return the value of the BTS_SECURE_DELETE\n** setting after the change.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){\n  int b;\n  if( p==0 ) return 0;\n  sqlite3BtreeEnter(p);\n  if( newFlag>=0 ){\n    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;\n    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;\n  } \n  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;\n  sqlite3BtreeLeave(p);\n  return b;\n}\n#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */\n\n/*\n** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'\n** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it\n** is disabled. The default value for the auto-vacuum property is \n** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  return SQLITE_READONLY;\n#else\n  BtShared *pBt = p->pBt;\n  int rc = SQLITE_OK;\n  u8 av = (u8)autoVacuum;\n\n  sqlite3BtreeEnter(p);\n  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){\n    rc = SQLITE_READONLY;\n  }else{\n    pBt->autoVacuum = av ?1:0;\n    pBt->incrVacuum = av==2 ?1:0;\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n#endif\n}\n\n/*\n** Return the value of the 'auto-vacuum' property. If auto-vacuum is \n** enabled 1 is returned. Otherwise 0.\n*/\nSQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  return BTREE_AUTOVACUUM_NONE;\n#else\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = (\n    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:\n    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:\n    BTREE_AUTOVACUUM_INCR\n  );\n  sqlite3BtreeLeave(p);\n  return rc;\n#endif\n}\n\n\n/*\n** Get a reference to pPage1 of the database file.  This will\n** also acquire a readlock on that file.\n**\n** SQLITE_OK is returned on success.  If the file is not a\n** well-formed database file, then SQLITE_CORRUPT is returned.\n** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM\n** is returned if we run out of memory. \n*/\nstatic int lockBtree(BtShared *pBt){\n  int rc;              /* Result code from subfunctions */\n  MemPage *pPage1;     /* Page 1 of the database file */\n  int nPage;           /* Number of pages in the database */\n  int nPageFile = 0;   /* Number of pages in the database file */\n  int nPageHeader;     /* Number of pages in the database according to hdr */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pBt->pPage1==0 );\n  rc = sqlite3PagerSharedLock(pBt->pPager);\n  if( rc!=SQLITE_OK ) return rc;\n  rc = btreeGetPage(pBt, 1, &pPage1, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Do some checking to help insure the file we opened really is\n  ** a valid database file. \n  */\n  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);\n  sqlite3PagerPagecount(pBt->pPager, &nPageFile);\n  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){\n    nPage = nPageFile;\n  }\n  if( nPage>0 ){\n    u32 pageSize;\n    u32 usableSize;\n    u8 *page1 = pPage1->aData;\n    rc = SQLITE_NOTADB;\n    if( memcmp(page1, zMagicHeader, 16)!=0 ){\n      goto page1_init_failed;\n    }\n\n#ifdef SQLITE_OMIT_WAL\n    if( page1[18]>1 ){\n      pBt->btsFlags |= BTS_READ_ONLY;\n    }\n    if( page1[19]>1 ){\n      goto page1_init_failed;\n    }\n#else\n    if( page1[18]>2 ){\n      pBt->btsFlags |= BTS_READ_ONLY;\n    }\n    if( page1[19]>2 ){\n      goto page1_init_failed;\n    }\n\n    /* If the write version is set to 2, this database should be accessed\n    ** in WAL mode. If the log is not already open, open it now. Then \n    ** return SQLITE_OK and return without populating BtShared.pPage1.\n    ** The caller detects this and calls this function again. This is\n    ** required as the version of page 1 currently in the page1 buffer\n    ** may not be the latest version - there may be a newer one in the log\n    ** file.\n    */\n    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){\n      int isOpen = 0;\n      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);\n      if( rc!=SQLITE_OK ){\n        goto page1_init_failed;\n      }else if( isOpen==0 ){\n        releasePage(pPage1);\n        return SQLITE_OK;\n      }\n      rc = SQLITE_NOTADB;\n    }\n#endif\n\n    /* The maximum embedded fraction must be exactly 25%.  And the minimum\n    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.\n    ** The original design allowed these amounts to vary, but as of\n    ** version 3.6.0, we require them to be fixed.\n    */\n    if( memcmp(&page1[21], \"\\100\\040\\040\",3)!=0 ){\n      goto page1_init_failed;\n    }\n    pageSize = (page1[16]<<8) | (page1[17]<<16);\n    if( ((pageSize-1)&pageSize)!=0\n     || pageSize>SQLITE_MAX_PAGE_SIZE \n     || pageSize<=256 \n    ){\n      goto page1_init_failed;\n    }\n    assert( (pageSize & 7)==0 );\n    usableSize = pageSize - page1[20];\n    if( (u32)pageSize!=pBt->pageSize ){\n      /* After reading the first page of the database assuming a page size\n      ** of BtShared.pageSize, we have discovered that the page-size is\n      ** actually pageSize. Unlock the database, leave pBt->pPage1 at\n      ** zero and return SQLITE_OK. The caller will call this function\n      ** again with the correct page-size.\n      */\n      releasePage(pPage1);\n      pBt->usableSize = usableSize;\n      pBt->pageSize = pageSize;\n      freeTempSpace(pBt);\n      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,\n                                   pageSize-usableSize);\n      return rc;\n    }\n    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto page1_init_failed;\n    }\n    if( usableSize<480 ){\n      goto page1_init_failed;\n    }\n    pBt->pageSize = pageSize;\n    pBt->usableSize = usableSize;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);\n    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);\n#endif\n  }\n\n  /* maxLocal is the maximum amount of payload to store locally for\n  ** a cell.  Make sure it is small enough so that at least minFanout\n  ** cells can will fit on one page.  We assume a 10-byte page header.\n  ** Besides the payload, the cell must store:\n  **     2-byte pointer to the cell\n  **     4-byte child pointer\n  **     9-byte nKey value\n  **     4-byte nData value\n  **     4-byte overflow page pointer\n  ** So a cell consists of a 2-byte pointer, a header which is as much as\n  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow\n  ** page pointer.\n  */\n  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);\n  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);\n  pBt->maxLeaf = (u16)(pBt->usableSize - 35);\n  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);\n  if( pBt->maxLocal>127 ){\n    pBt->max1bytePayload = 127;\n  }else{\n    pBt->max1bytePayload = (u8)pBt->maxLocal;\n  }\n  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );\n  pBt->pPage1 = pPage1;\n  pBt->nPage = nPage;\n  return SQLITE_OK;\n\npage1_init_failed:\n  releasePage(pPage1);\n  pBt->pPage1 = 0;\n  return rc;\n}\n\n/*\n** If there are no outstanding cursors and we are not in the middle\n** of a transaction but there is a read lock on the database, then\n** this routine unrefs the first page of the database file which \n** has the effect of releasing the read lock.\n**\n** If there is a transaction in progress, this routine is a no-op.\n*/\nstatic void unlockBtreeIfUnused(BtShared *pBt){\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );\n  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){\n    assert( pBt->pPage1->aData );\n    assert( sqlite3PagerRefcount(pBt->pPager)==1 );\n    assert( pBt->pPage1->aData );\n    releasePage(pBt->pPage1);\n    pBt->pPage1 = 0;\n  }\n}\n\n/*\n** If pBt points to an empty file then convert that empty file\n** into a new empty database by initializing the first page of\n** the database.\n*/\nstatic int newDatabase(BtShared *pBt){\n  MemPage *pP1;\n  unsigned char *data;\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pBt->nPage>0 ){\n    return SQLITE_OK;\n  }\n  pP1 = pBt->pPage1;\n  assert( pP1!=0 );\n  data = pP1->aData;\n  rc = sqlite3PagerWrite(pP1->pDbPage);\n  if( rc ) return rc;\n  memcpy(data, zMagicHeader, sizeof(zMagicHeader));\n  assert( sizeof(zMagicHeader)==16 );\n  data[16] = (u8)((pBt->pageSize>>8)&0xff);\n  data[17] = (u8)((pBt->pageSize>>16)&0xff);\n  data[18] = 1;\n  data[19] = 1;\n  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);\n  data[20] = (u8)(pBt->pageSize - pBt->usableSize);\n  data[21] = 64;\n  data[22] = 32;\n  data[23] = 32;\n  memset(&data[24], 0, 100-24);\n  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );\n  pBt->btsFlags |= BTS_PAGESIZE_FIXED;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );\n  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );\n  put4byte(&data[36 + 4*4], pBt->autoVacuum);\n  put4byte(&data[36 + 7*4], pBt->incrVacuum);\n#endif\n  pBt->nPage = 1;\n  data[31] = 1;\n  return SQLITE_OK;\n}\n\n/*\n** Attempt to start a new transaction. A write-transaction\n** is started if the second argument is nonzero, otherwise a read-\n** transaction.  If the second argument is 2 or more and exclusive\n** transaction is started, meaning that no other process is allowed\n** to access the database.  A preexisting transaction may not be\n** upgraded to exclusive by calling this routine a second time - the\n** exclusivity flag only works for a new transaction.\n**\n** A write-transaction must be started before attempting any \n** changes to the database.  None of the following routines \n** will work unless a transaction is started first:\n**\n**      sqlite3BtreeCreateTable()\n**      sqlite3BtreeCreateIndex()\n**      sqlite3BtreeClearTable()\n**      sqlite3BtreeDropTable()\n**      sqlite3BtreeInsert()\n**      sqlite3BtreeDelete()\n**      sqlite3BtreeUpdateMeta()\n**\n** If an initial attempt to acquire the lock fails because of lock contention\n** and the database was previously unlocked, then invoke the busy handler\n** if there is one.  But if there was previously a read-lock, do not\n** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is \n** returned when there is already a read-lock in order to avoid a deadlock.\n**\n** Suppose there are two processes A and B.  A has a read lock and B has\n** a reserved lock.  B tries to promote to exclusive but is blocked because\n** of A's read lock.  A tries to promote to reserved but is blocked by B.\n** One or the other of the two processes must give way or there can be\n** no progress.  By returning SQLITE_BUSY and not invoking the busy callback\n** when A already has a read lock, we encourage A to give up and let B\n** proceed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){\n  sqlite3 *pBlock = 0;\n  BtShared *pBt = p->pBt;\n  int rc = SQLITE_OK;\n\n  sqlite3BtreeEnter(p);\n  btreeIntegrity(p);\n\n  /* If the btree is already in a write-transaction, or it\n  ** is already in a read-transaction and a read-transaction\n  ** is requested, this is a no-op.\n  */\n  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){\n    goto trans_begun;\n  }\n\n  /* Write transactions are not possible on a read-only database */\n  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){\n    rc = SQLITE_READONLY;\n    goto trans_begun;\n  }\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  /* If another database handle has already opened a write transaction \n  ** on this shared-btree structure and a second write transaction is\n  ** requested, return SQLITE_LOCKED.\n  */\n  if( (wrflag && pBt->inTransaction==TRANS_WRITE)\n   || (pBt->btsFlags & BTS_PENDING)!=0\n  ){\n    pBlock = pBt->pWriter->db;\n  }else if( wrflag>1 ){\n    BtLock *pIter;\n    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){\n      if( pIter->pBtree!=p ){\n        pBlock = pIter->pBtree->db;\n        break;\n      }\n    }\n  }\n  if( pBlock ){\n    sqlite3ConnectionBlocked(p->db, pBlock);\n    rc = SQLITE_LOCKED_SHAREDCACHE;\n    goto trans_begun;\n  }\n#endif\n\n  /* Any read-only or read-write transaction implies a read-lock on \n  ** page 1. So if some other shared-cache client already has a write-lock \n  ** on page 1, the transaction cannot be opened. */\n  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);\n  if( SQLITE_OK!=rc ) goto trans_begun;\n\n  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;\n  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;\n  do {\n    /* Call lockBtree() until either pBt->pPage1 is populated or\n    ** lockBtree() returns something other than SQLITE_OK. lockBtree()\n    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after\n    ** reading page 1 it discovers that the page-size of the database \n    ** file is not pBt->pageSize. In this case lockBtree() will update\n    ** pBt->pageSize to the page-size of the file on disk.\n    */\n    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );\n\n    if( rc==SQLITE_OK && wrflag ){\n      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){\n        rc = SQLITE_READONLY;\n      }else{\n        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));\n        if( rc==SQLITE_OK ){\n          rc = newDatabase(pBt);\n        }\n      }\n    }\n  \n    if( rc!=SQLITE_OK ){\n      unlockBtreeIfUnused(pBt);\n    }\n  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&\n          btreeInvokeBusyHandler(pBt) );\n\n  if( rc==SQLITE_OK ){\n    if( p->inTrans==TRANS_NONE ){\n      pBt->nTransaction++;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n      if( p->sharable ){\n        assert( p->lock.pBtree==p && p->lock.iTable==1 );\n        p->lock.eLock = READ_LOCK;\n        p->lock.pNext = pBt->pLock;\n        pBt->pLock = &p->lock;\n      }\n#endif\n    }\n    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);\n    if( p->inTrans>pBt->inTransaction ){\n      pBt->inTransaction = p->inTrans;\n    }\n    if( wrflag ){\n      MemPage *pPage1 = pBt->pPage1;\n#ifndef SQLITE_OMIT_SHARED_CACHE\n      assert( !pBt->pWriter );\n      pBt->pWriter = p;\n      pBt->btsFlags &= ~BTS_EXCLUSIVE;\n      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;\n#endif\n\n      /* If the db-size header field is incorrect (as it may be if an old\n      ** client has been writing the database file), update it now. Doing\n      ** this sooner rather than later means the database size can safely \n      ** re-read the database size from page 1 if a savepoint or transaction\n      ** rollback occurs within the transaction.\n      */\n      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){\n        rc = sqlite3PagerWrite(pPage1->pDbPage);\n        if( rc==SQLITE_OK ){\n          put4byte(&pPage1->aData[28], pBt->nPage);\n        }\n      }\n    }\n  }\n\n\ntrans_begun:\n  if( rc==SQLITE_OK && wrflag ){\n    /* This call makes sure that the pager has the correct number of\n    ** open savepoints. If the second parameter is greater than 0 and\n    ** the sub-journal is not already open, then it will be opened here.\n    */\n    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);\n  }\n\n  btreeIntegrity(p);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n\n/*\n** Set the pointer-map entries for all children of page pPage. Also, if\n** pPage contains cells that point to overflow pages, set the pointer\n** map entries for the overflow pages as well.\n*/\nstatic int setChildPtrmaps(MemPage *pPage){\n  int i;                             /* Counter variable */\n  int nCell;                         /* Number of cells in page pPage */\n  int rc;                            /* Return code */\n  BtShared *pBt = pPage->pBt;\n  u8 isInitOrig = pPage->isInit;\n  Pgno pgno = pPage->pgno;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  rc = btreeInitPage(pPage);\n  if( rc!=SQLITE_OK ){\n    goto set_child_ptrmaps_out;\n  }\n  nCell = pPage->nCell;\n\n  for(i=0; i<nCell; i++){\n    u8 *pCell = findCell(pPage, i);\n\n    ptrmapPutOvflPtr(pPage, pCell, &rc);\n\n    if( !pPage->leaf ){\n      Pgno childPgno = get4byte(pCell);\n      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);\n    }\n  }\n\n  if( !pPage->leaf ){\n    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);\n  }\n\nset_child_ptrmaps_out:\n  pPage->isInit = isInitOrig;\n  return rc;\n}\n\n/*\n** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so\n** that it points to iTo. Parameter eType describes the type of pointer to\n** be modified, as  follows:\n**\n** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child \n**                   page of pPage.\n**\n** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow\n**                   page pointed to by one of the cells on pPage.\n**\n** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next\n**                   overflow page in the list.\n*/\nstatic int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  if( eType==PTRMAP_OVERFLOW2 ){\n    /* The pointer is always the first 4 bytes of the page in this case.  */\n    if( get4byte(pPage->aData)!=iFrom ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n    put4byte(pPage->aData, iTo);\n  }else{\n    u8 isInitOrig = pPage->isInit;\n    int i;\n    int nCell;\n\n    btreeInitPage(pPage);\n    nCell = pPage->nCell;\n\n    for(i=0; i<nCell; i++){\n      u8 *pCell = findCell(pPage, i);\n      if( eType==PTRMAP_OVERFLOW1 ){\n        CellInfo info;\n        btreeParseCellPtr(pPage, pCell, &info);\n        if( info.iOverflow\n         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage\n         && iFrom==get4byte(&pCell[info.iOverflow])\n        ){\n          put4byte(&pCell[info.iOverflow], iTo);\n          break;\n        }\n      }else{\n        if( get4byte(pCell)==iFrom ){\n          put4byte(pCell, iTo);\n          break;\n        }\n      }\n    }\n  \n    if( i==nCell ){\n      if( eType!=PTRMAP_BTREE || \n          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){\n        return SQLITE_CORRUPT_BKPT;\n      }\n      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);\n    }\n\n    pPage->isInit = isInitOrig;\n  }\n  return SQLITE_OK;\n}\n\n\n/*\n** Move the open database page pDbPage to location iFreePage in the \n** database. The pDbPage reference remains valid.\n**\n** The isCommit flag indicates that there is no need to remember that\n** the journal needs to be sync()ed before database page pDbPage->pgno \n** can be written to. The caller has already promised not to write to that\n** page.\n*/\nstatic int relocatePage(\n  BtShared *pBt,           /* Btree */\n  MemPage *pDbPage,        /* Open page to move */\n  u8 eType,                /* Pointer map 'type' entry for pDbPage */\n  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */\n  Pgno iFreePage,          /* The location to move pDbPage to */\n  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */\n){\n  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */\n  Pgno iDbPage = pDbPage->pgno;\n  Pager *pPager = pBt->pPager;\n  int rc;\n\n  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || \n      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( pDbPage->pBt==pBt );\n\n  /* Move page iDbPage from its current location to page number iFreePage */\n  TRACE((\"AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\\n\", \n      iDbPage, iFreePage, iPtrPage, eType));\n  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  pDbPage->pgno = iFreePage;\n\n  /* If pDbPage was a btree-page, then it may have child pages and/or cells\n  ** that point to overflow pages. The pointer map entries for all these\n  ** pages need to be changed.\n  **\n  ** If pDbPage is an overflow page, then the first 4 bytes may store a\n  ** pointer to a subsequent overflow page. If this is the case, then\n  ** the pointer map needs to be updated for the subsequent overflow page.\n  */\n  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){\n    rc = setChildPtrmaps(pDbPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n  }else{\n    Pgno nextOvfl = get4byte(pDbPage->aData);\n    if( nextOvfl!=0 ){\n      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }\n  }\n\n  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so\n  ** that it points at iFreePage. Also fix the pointer map entry for\n  ** iPtrPage.\n  */\n  if( eType!=PTRMAP_ROOTPAGE ){\n    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    rc = sqlite3PagerWrite(pPtrPage->pDbPage);\n    if( rc!=SQLITE_OK ){\n      releasePage(pPtrPage);\n      return rc;\n    }\n    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);\n    releasePage(pPtrPage);\n    if( rc==SQLITE_OK ){\n      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);\n    }\n  }\n  return rc;\n}\n\n/* Forward declaration required by incrVacuumStep(). */\nstatic int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);\n\n/*\n** Perform a single step of an incremental-vacuum. If successful,\n** return SQLITE_OK. If there is no work to do (and therefore no\n** point in calling this function again), return SQLITE_DONE.\n**\n** More specificly, this function attempts to re-organize the \n** database so that the last page of the file currently in use\n** is no longer in use.\n**\n** If the nFin parameter is non-zero, this function assumes\n** that the caller will keep calling incrVacuumStep() until\n** it returns SQLITE_DONE or an error, and that nFin is the\n** number of pages the database file will contain after this \n** process is complete.  If nFin is zero, it is assumed that\n** incrVacuumStep() will be called a finite amount of times\n** which may or may not empty the freelist.  A full autovacuum\n** has nFin>0.  A \"PRAGMA incremental_vacuum\" has nFin==0.\n*/\nstatic int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){\n  Pgno nFreeList;           /* Number of pages still on the free-list */\n  int rc;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( iLastPg>nFin );\n\n  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){\n    u8 eType;\n    Pgno iPtrPage;\n\n    nFreeList = get4byte(&pBt->pPage1->aData[36]);\n    if( nFreeList==0 ){\n      return SQLITE_DONE;\n    }\n\n    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    if( eType==PTRMAP_ROOTPAGE ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n\n    if( eType==PTRMAP_FREEPAGE ){\n      if( nFin==0 ){\n        /* Remove the page from the files free-list. This is not required\n        ** if nFin is non-zero. In that case, the free-list will be\n        ** truncated to zero after this function returns, so it doesn't \n        ** matter if it still contains some garbage entries.\n        */\n        Pgno iFreePg;\n        MemPage *pFreePg;\n        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        assert( iFreePg==iLastPg );\n        releasePage(pFreePg);\n      }\n    } else {\n      Pgno iFreePg;             /* Index of free page to move pLastPg to */\n      MemPage *pLastPg;\n\n      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n\n      /* If nFin is zero, this loop runs exactly once and page pLastPg\n      ** is swapped with the first free page pulled off the free list.\n      **\n      ** On the other hand, if nFin is greater than zero, then keep\n      ** looping until a free-page located within the first nFin pages\n      ** of the file is found.\n      */\n      do {\n        MemPage *pFreePg;\n        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);\n        if( rc!=SQLITE_OK ){\n          releasePage(pLastPg);\n          return rc;\n        }\n        releasePage(pFreePg);\n      }while( nFin!=0 && iFreePg>nFin );\n      assert( iFreePg<iLastPg );\n      \n      rc = sqlite3PagerWrite(pLastPg->pDbPage);\n      if( rc==SQLITE_OK ){\n        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);\n      }\n      releasePage(pLastPg);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n    }\n  }\n\n  if( nFin==0 ){\n    iLastPg--;\n    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){\n      if( PTRMAP_ISPAGE(pBt, iLastPg) ){\n        MemPage *pPg;\n        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        rc = sqlite3PagerWrite(pPg->pDbPage);\n        releasePage(pPg);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n      }\n      iLastPg--;\n    }\n    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);\n    pBt->nPage = iLastPg;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** A write-transaction must be opened before calling this function.\n** It performs a single unit of work towards an incremental vacuum.\n**\n** If the incremental vacuum is finished after this function has run,\n** SQLITE_DONE is returned. If it is not finished, but no error occurred,\n** SQLITE_OK is returned. Otherwise an SQLite error code. \n*/\nSQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){\n  int rc;\n  BtShared *pBt = p->pBt;\n\n  sqlite3BtreeEnter(p);\n  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );\n  if( !pBt->autoVacuum ){\n    rc = SQLITE_DONE;\n  }else{\n    invalidateAllOverflowCache(pBt);\n    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));\n    if( rc==SQLITE_OK ){\n      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n      put4byte(&pBt->pPage1->aData[28], pBt->nPage);\n    }\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** This routine is called prior to sqlite3PagerCommit when a transaction\n** is commited for an auto-vacuum database.\n**\n** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages\n** the database file should be truncated to during the commit process. \n** i.e. the database has been reorganized so that only the first *pnTrunc\n** pages are in use.\n*/\nstatic int autoVacuumCommit(BtShared *pBt){\n  int rc = SQLITE_OK;\n  Pager *pPager = pBt->pPager;\n  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  invalidateAllOverflowCache(pBt);\n  assert(pBt->autoVacuum);\n  if( !pBt->incrVacuum ){\n    Pgno nFin;         /* Number of pages in database after autovacuuming */\n    Pgno nFree;        /* Number of pages on the freelist initially */\n    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */\n    Pgno iFree;        /* The next page to be freed */\n    int nEntry;        /* Number of entries on one ptrmap page */\n    Pgno nOrig;        /* Database size before freeing */\n\n    nOrig = btreePagecount(pBt);\n    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){\n      /* It is not possible to create a database for which the final page\n      ** is either a pointer-map page or the pending-byte page. If one\n      ** is encountered, this indicates corruption.\n      */\n      return SQLITE_CORRUPT_BKPT;\n    }\n\n    nFree = get4byte(&pBt->pPage1->aData[36]);\n    nEntry = pBt->usableSize/5;\n    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;\n    nFin = nOrig - nFree - nPtrmap;\n    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){\n      nFin--;\n    }\n    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){\n      nFin--;\n    }\n    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;\n\n    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){\n      rc = incrVacuumStep(pBt, nFin, iFree);\n    }\n    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){\n      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n      put4byte(&pBt->pPage1->aData[32], 0);\n      put4byte(&pBt->pPage1->aData[36], 0);\n      put4byte(&pBt->pPage1->aData[28], nFin);\n      sqlite3PagerTruncateImage(pBt->pPager, nFin);\n      pBt->nPage = nFin;\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3PagerRollback(pPager);\n    }\n  }\n\n  assert( nRef==sqlite3PagerRefcount(pPager) );\n  return rc;\n}\n\n#else /* ifndef SQLITE_OMIT_AUTOVACUUM */\n# define setChildPtrmaps(x) SQLITE_OK\n#endif\n\n/*\n** This routine does the first phase of a two-phase commit.  This routine\n** causes a rollback journal to be created (if it does not already exist)\n** and populated with enough information so that if a power loss occurs\n** the database can be restored to its original state by playing back\n** the journal.  Then the contents of the journal are flushed out to\n** the disk.  After the journal is safely on oxide, the changes to the\n** database are written into the database file and flushed to oxide.\n** At the end of this call, the rollback journal still exists on the\n** disk and we are still holding all locks, so the transaction has not\n** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the\n** commit process.\n**\n** This call is a no-op if no write-transaction is currently active on pBt.\n**\n** Otherwise, sync the database file for the btree pBt. zMaster points to\n** the name of a master journal file that should be written into the\n** individual journal file, or is NULL, indicating no master journal file \n** (single database transaction).\n**\n** When this is called, the master journal should already have been\n** created, populated with this journal pointer and synced to disk.\n**\n** Once this is routine has returned, the only thing required to commit\n** the write-transaction for this database file is to delete the journal.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){\n  int rc = SQLITE_OK;\n  if( p->inTrans==TRANS_WRITE ){\n    BtShared *pBt = p->pBt;\n    sqlite3BtreeEnter(p);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum ){\n      rc = autoVacuumCommit(pBt);\n      if( rc!=SQLITE_OK ){\n        sqlite3BtreeLeave(p);\n        return rc;\n      }\n    }\n#endif\n    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n\n/*\n** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()\n** at the conclusion of a transaction.\n*/\nstatic void btreeEndTransaction(Btree *p){\n  BtShared *pBt = p->pBt;\n  assert( sqlite3BtreeHoldsMutex(p) );\n\n  btreeClearHasContent(pBt);\n  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){\n    /* If there are other active statements that belong to this database\n    ** handle, downgrade to a read-only transaction. The other statements\n    ** may still be reading from the database.  */\n    downgradeAllSharedCacheTableLocks(p);\n    p->inTrans = TRANS_READ;\n  }else{\n    /* If the handle had any kind of transaction open, decrement the \n    ** transaction count of the shared btree. If the transaction count \n    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()\n    ** call below will unlock the pager.  */\n    if( p->inTrans!=TRANS_NONE ){\n      clearAllSharedCacheTableLocks(p);\n      pBt->nTransaction--;\n      if( 0==pBt->nTransaction ){\n        pBt->inTransaction = TRANS_NONE;\n      }\n    }\n\n    /* Set the current transaction state to TRANS_NONE and unlock the \n    ** pager if this call closed the only read or write transaction.  */\n    p->inTrans = TRANS_NONE;\n    unlockBtreeIfUnused(pBt);\n  }\n\n  btreeIntegrity(p);\n}\n\n/*\n** Commit the transaction currently in progress.\n**\n** This routine implements the second phase of a 2-phase commit.  The\n** sqlite3BtreeCommitPhaseOne() routine does the first phase and should\n** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()\n** routine did all the work of writing information out to disk and flushing the\n** contents so that they are written onto the disk platter.  All this\n** routine has to do is delete or truncate or zero the header in the\n** the rollback journal (which causes the transaction to commit) and\n** drop locks.\n**\n** Normally, if an error occurs while the pager layer is attempting to \n** finalize the underlying journal file, this function returns an error and\n** the upper layer will attempt a rollback. However, if the second argument\n** is non-zero then this b-tree transaction is part of a multi-file \n** transaction. In this case, the transaction has already been committed \n** (by deleting a master journal file) and the caller will ignore this \n** functions return code. So, even if an error occurs in the pager layer,\n** reset the b-tree objects internal state to indicate that the write\n** transaction has been closed. This is quite safe, as the pager will have\n** transitioned to the error state.\n**\n** This will release the write lock on the database file.  If there\n** are no active cursors, it also releases the read lock.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){\n\n  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;\n  sqlite3BtreeEnter(p);\n  btreeIntegrity(p);\n\n  /* If the handle has a write-transaction open, commit the shared-btrees \n  ** transaction and set the shared state to TRANS_READ.\n  */\n  if( p->inTrans==TRANS_WRITE ){\n    int rc;\n    BtShared *pBt = p->pBt;\n    assert( pBt->inTransaction==TRANS_WRITE );\n    assert( pBt->nTransaction>0 );\n    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);\n    if( rc!=SQLITE_OK && bCleanup==0 ){\n      sqlite3BtreeLeave(p);\n      return rc;\n    }\n    pBt->inTransaction = TRANS_READ;\n  }\n\n  btreeEndTransaction(p);\n  sqlite3BtreeLeave(p);\n  return SQLITE_OK;\n}\n\n/*\n** Do both phases of a commit.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = sqlite3BtreeCommitPhaseOne(p, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3BtreeCommitPhaseTwo(p, 0);\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n#ifndef NDEBUG\n/*\n** Return the number of write-cursors open on this handle. This is for use\n** in assert() expressions, so it is only compiled if NDEBUG is not\n** defined.\n**\n** For the purposes of this routine, a write-cursor is any cursor that\n** is capable of writing to the databse.  That means the cursor was\n** originally opened for writing and the cursor has not be disabled\n** by having its state changed to CURSOR_FAULT.\n*/\nstatic int countWriteCursors(BtShared *pBt){\n  BtCursor *pCur;\n  int r = 0;\n  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){\n    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; \n  }\n  return r;\n}\n#endif\n\n/*\n** This routine sets the state to CURSOR_FAULT and the error\n** code to errCode for every cursor on BtShared that pBtree\n** references.\n**\n** Every cursor is tripped, including cursors that belong\n** to other database connections that happen to be sharing\n** the cache with pBtree.\n**\n** This routine gets called when a rollback occurs.\n** All cursors using the same cache must be tripped\n** to prevent them from trying to use the btree after\n** the rollback.  The rollback may have deleted tables\n** or moved root pages, so it is not sufficient to\n** save the state of the cursor.  The cursor must be\n** invalidated.\n*/\nSQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){\n  BtCursor *p;\n  if( pBtree==0 ) return;\n  sqlite3BtreeEnter(pBtree);\n  for(p=pBtree->pBt->pCursor; p; p=p->pNext){\n    int i;\n    sqlite3BtreeClearCursor(p);\n    p->eState = CURSOR_FAULT;\n    p->skipNext = errCode;\n    for(i=0; i<=p->iPage; i++){\n      releasePage(p->apPage[i]);\n      p->apPage[i] = 0;\n    }\n  }\n  sqlite3BtreeLeave(pBtree);\n}\n\n/*\n** Rollback the transaction in progress.  All cursors will be\n** invalided by this operation.  Any attempt to use a cursor\n** that was open at the beginning of this operation will result\n** in an error.\n**\n** This will release the write lock on the database file.  If there\n** are no active cursors, it also releases the read lock.\n*/\nSQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){\n  int rc;\n  BtShared *pBt = p->pBt;\n  MemPage *pPage1;\n\n  sqlite3BtreeEnter(p);\n  if( tripCode==SQLITE_OK ){\n    rc = tripCode = saveAllCursors(pBt, 0, 0);\n  }else{\n    rc = SQLITE_OK;\n  }\n  if( tripCode ){\n    sqlite3BtreeTripAllCursors(p, tripCode);\n  }\n  btreeIntegrity(p);\n\n  if( p->inTrans==TRANS_WRITE ){\n    int rc2;\n\n    assert( TRANS_WRITE==pBt->inTransaction );\n    rc2 = sqlite3PagerRollback(pBt->pPager);\n    if( rc2!=SQLITE_OK ){\n      rc = rc2;\n    }\n\n    /* The rollback may have destroyed the pPage1->aData value.  So\n    ** call btreeGetPage() on page 1 again to make\n    ** sure pPage1->aData is set correctly. */\n    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){\n      int nPage = get4byte(28+(u8*)pPage1->aData);\n      testcase( nPage==0 );\n      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);\n      testcase( pBt->nPage!=nPage );\n      pBt->nPage = nPage;\n      releasePage(pPage1);\n    }\n    assert( countWriteCursors(pBt)==0 );\n    pBt->inTransaction = TRANS_READ;\n  }\n\n  btreeEndTransaction(p);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Start a statement subtransaction. The subtransaction can can be rolled\n** back independently of the main transaction. You must start a transaction \n** before starting a subtransaction. The subtransaction is ended automatically \n** if the main transaction commits or rolls back.\n**\n** Statement subtransactions are used around individual SQL statements\n** that are contained within a BEGIN...COMMIT block.  If a constraint\n** error occurs within the statement, the effect of that one statement\n** can be rolled back without having to rollback the entire transaction.\n**\n** A statement sub-transaction is implemented as an anonymous savepoint. The\n** value passed as the second parameter is the total number of savepoints,\n** including the new anonymous savepoint, open on the B-Tree. i.e. if there\n** are no active savepoints and no other statement-transactions open,\n** iStatement is 1. This anonymous savepoint can be released or rolled back\n** using the sqlite3BtreeSavepoint() function.\n*/\nSQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){\n  int rc;\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( iStatement>0 );\n  assert( iStatement>p->db->nSavepoint );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  /* At the pager level, a statement transaction is a savepoint with\n  ** an index greater than all savepoints created explicitly using\n  ** SQL statements. It is illegal to open, release or rollback any\n  ** such savepoints while the statement transaction savepoint is active.\n  */\n  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** The second argument to this function, op, is always SAVEPOINT_ROLLBACK\n** or SAVEPOINT_RELEASE. This function either releases or rolls back the\n** savepoint identified by parameter iSavepoint, depending on the value \n** of op.\n**\n** Normally, iSavepoint is greater than or equal to zero. However, if op is\n** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the \n** contents of the entire transaction are rolled back. This is different\n** from a normal transaction rollback, as no locks are released and the\n** transaction remains open.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){\n  int rc = SQLITE_OK;\n  if( p && p->inTrans==TRANS_WRITE ){\n    BtShared *pBt = p->pBt;\n    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );\n    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );\n    sqlite3BtreeEnter(p);\n    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);\n    if( rc==SQLITE_OK ){\n      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){\n        pBt->nPage = 0;\n      }\n      rc = newDatabase(pBt);\n      pBt->nPage = get4byte(28 + pBt->pPage1->aData);\n\n      /* The database size was written into the offset 28 of the header\n      ** when the transaction started, so we know that the value at offset\n      ** 28 is nonzero. */\n      assert( pBt->nPage>0 );\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n\n/*\n** Create a new cursor for the BTree whose root is on the page\n** iTable. If a read-only cursor is requested, it is assumed that\n** the caller already has at least a read-only transaction open\n** on the database already. If a write-cursor is requested, then\n** the caller is assumed to have an open write transaction.\n**\n** If wrFlag==0, then the cursor can only be used for reading.\n** If wrFlag==1, then the cursor can be used for reading or for\n** writing if other conditions for writing are also met.  These\n** are the conditions that must be met in order for writing to\n** be allowed:\n**\n** 1:  The cursor must have been opened with wrFlag==1\n**\n** 2:  Other database connections that share the same pager cache\n**     but which are not in the READ_UNCOMMITTED state may not have\n**     cursors open with wrFlag==0 on the same table.  Otherwise\n**     the changes made by this write cursor would be visible to\n**     the read cursors in the other database connection.\n**\n** 3:  The database must be writable (not on read-only media)\n**\n** 4:  There must be an active transaction.\n**\n** No checking is done to make sure that page iTable really is the\n** root page of a b-tree.  If it is not, then the cursor acquired\n** will not work correctly.\n**\n** It is assumed that the sqlite3BtreeCursorZero() has been called\n** on pCur to initialize the memory space prior to invoking this routine.\n*/\nstatic int btreeCursor(\n  Btree *p,                              /* The btree */\n  int iTable,                            /* Root page of table to open */\n  int wrFlag,                            /* 1 to write. 0 read-only */\n  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */\n  BtCursor *pCur                         /* Space for new cursor */\n){\n  BtShared *pBt = p->pBt;                /* Shared b-tree handle */\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( wrFlag==0 || wrFlag==1 );\n\n  /* The following assert statements verify that if this is a sharable \n  ** b-tree database, the connection is holding the required table locks, \n  ** and that no other connection has any open cursor that conflicts with \n  ** this lock.  */\n  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );\n  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );\n\n  /* Assert that the caller has opened the required transaction. */\n  assert( p->inTrans>TRANS_NONE );\n  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );\n  assert( pBt->pPage1 && pBt->pPage1->aData );\n\n  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){\n    return SQLITE_READONLY;\n  }\n  if( iTable==1 && btreePagecount(pBt)==0 ){\n    assert( wrFlag==0 );\n    iTable = 0;\n  }\n\n  /* Now that no other errors can occur, finish filling in the BtCursor\n  ** variables and link the cursor into the BtShared list.  */\n  pCur->pgnoRoot = (Pgno)iTable;\n  pCur->iPage = -1;\n  pCur->pKeyInfo = pKeyInfo;\n  pCur->pBtree = p;\n  pCur->pBt = pBt;\n  pCur->wrFlag = (u8)wrFlag;\n  pCur->pNext = pBt->pCursor;\n  if( pCur->pNext ){\n    pCur->pNext->pPrev = pCur;\n  }\n  pBt->pCursor = pCur;\n  pCur->eState = CURSOR_INVALID;\n  pCur->cachedRowid = 0;\n  return SQLITE_OK;\n}\nSQLITE_PRIVATE int sqlite3BtreeCursor(\n  Btree *p,                                   /* The btree */\n  int iTable,                                 /* Root page of table to open */\n  int wrFlag,                                 /* 1 to write. 0 read-only */\n  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */\n  BtCursor *pCur                              /* Write new cursor here */\n){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Return the size of a BtCursor object in bytes.\n**\n** This interfaces is needed so that users of cursors can preallocate\n** sufficient storage to hold a cursor.  The BtCursor object is opaque\n** to users so they cannot do the sizeof() themselves - they must call\n** this routine.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorSize(void){\n  return ROUND8(sizeof(BtCursor));\n}\n\n/*\n** Initialize memory that will be converted into a BtCursor object.\n**\n** The simple approach here would be to memset() the entire object\n** to zero.  But it turns out that the apPage[] and aiIdx[] arrays\n** do not need to be zeroed and they are large, so we can save a lot\n** of run-time by skipping the initialization of those elements.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){\n  memset(p, 0, offsetof(BtCursor, iPage));\n}\n\n/*\n** Set the cached rowid value of every cursor in the same database file\n** as pCur and having the same root page number as pCur.  The value is\n** set to iRowid.\n**\n** Only positive rowid values are considered valid for this cache.\n** The cache is initialized to zero, indicating an invalid cache.\n** A btree will work fine with zero or negative rowids.  We just cannot\n** cache zero or negative rowids, which means tables that use zero or\n** negative rowids might run a little slower.  But in practice, zero\n** or negative rowids are very uncommon so this should not be a problem.\n*/\nSQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){\n  BtCursor *p;\n  for(p=pCur->pBt->pCursor; p; p=p->pNext){\n    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;\n  }\n  assert( pCur->cachedRowid==iRowid );\n}\n\n/*\n** Return the cached rowid for the given cursor.  A negative or zero\n** return value indicates that the rowid cache is invalid and should be\n** ignored.  If the rowid cache has never before been set, then a\n** zero is returned.\n*/\nSQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){\n  return pCur->cachedRowid;\n}\n\n/*\n** Close a cursor.  The read lock on the database file is released\n** when the last cursor is closed.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){\n  Btree *pBtree = pCur->pBtree;\n  if( pBtree ){\n    int i;\n    BtShared *pBt = pCur->pBt;\n    sqlite3BtreeEnter(pBtree);\n    sqlite3BtreeClearCursor(pCur);\n    if( pCur->pPrev ){\n      pCur->pPrev->pNext = pCur->pNext;\n    }else{\n      pBt->pCursor = pCur->pNext;\n    }\n    if( pCur->pNext ){\n      pCur->pNext->pPrev = pCur->pPrev;\n    }\n    for(i=0; i<=pCur->iPage; i++){\n      releasePage(pCur->apPage[i]);\n    }\n    unlockBtreeIfUnused(pBt);\n    invalidateOverflowCache(pCur);\n    /* sqlite3_free(pCur); */\n    sqlite3BtreeLeave(pBtree);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Make sure the BtCursor* given in the argument has a valid\n** BtCursor.info structure.  If it is not already valid, call\n** btreeParseCell() to fill it in.\n**\n** BtCursor.info is a cache of the information in the current cell.\n** Using this cache reduces the number of calls to btreeParseCell().\n**\n** 2007-06-25:  There is a bug in some versions of MSVC that cause the\n** compiler to crash when getCellInfo() is implemented as a macro.\n** But there is a measureable speed advantage to using the macro on gcc\n** (when less compiler optimizations like -Os or -O0 are used and the\n** compiler is not doing agressive inlining.)  So we use a real function\n** for MSVC and a macro for everything else.  Ticket #2457.\n*/\n#ifndef NDEBUG\n  static void assertCellInfo(BtCursor *pCur){\n    CellInfo info;\n    int iPage = pCur->iPage;\n    memset(&info, 0, sizeof(info));\n    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);\n    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );\n  }\n#else\n  #define assertCellInfo(x)\n#endif\n#ifdef _MSC_VER\n  /* Use a real function in MSVC to work around bugs in that compiler. */\n  static void getCellInfo(BtCursor *pCur){\n    if( pCur->info.nSize==0 ){\n      int iPage = pCur->iPage;\n      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);\n      pCur->validNKey = 1;\n    }else{\n      assertCellInfo(pCur);\n    }\n  }\n#else /* if not _MSC_VER */\n  /* Use a macro in all other compilers so that the function is inlined */\n#define getCellInfo(pCur)                                                      \\\n  if( pCur->info.nSize==0 ){                                                   \\\n    int iPage = pCur->iPage;                                                   \\\n    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \\\n    pCur->validNKey = 1;                                                       \\\n  }else{                                                                       \\\n    assertCellInfo(pCur);                                                      \\\n  }\n#endif /* _MSC_VER */\n\n#ifndef NDEBUG  /* The next routine used only within assert() statements */\n/*\n** Return true if the given BtCursor is valid.  A valid cursor is one\n** that is currently pointing to a row in a (non-empty) table.\n** This is a verification routine is used only within assert() statements.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){\n  return pCur && pCur->eState==CURSOR_VALID;\n}\n#endif /* NDEBUG */\n\n/*\n** Set *pSize to the size of the buffer needed to hold the value of\n** the key for the current entry.  If the cursor is not pointing\n** to a valid entry, *pSize is set to 0. \n**\n** For a table with the INTKEY flag set, this routine returns the key\n** itself, not the number of bytes in the key.\n**\n** The caller must position the cursor prior to invoking this routine.\n** \n** This routine cannot fail.  It always returns SQLITE_OK.  \n*/\nSQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );\n  if( pCur->eState!=CURSOR_VALID ){\n    *pSize = 0;\n  }else{\n    getCellInfo(pCur);\n    *pSize = pCur->info.nKey;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Set *pSize to the number of bytes of data in the entry the\n** cursor currently points to.\n**\n** The caller must guarantee that the cursor is pointing to a non-NULL\n** valid entry.  In other words, the calling procedure must guarantee\n** that the cursor has Cursor.eState==CURSOR_VALID.\n**\n** Failure is not possible.  This function always returns SQLITE_OK.\n** It might just as well be a procedure (returning void) but we continue\n** to return an integer result code for historical reasons.\n*/\nSQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  getCellInfo(pCur);\n  *pSize = pCur->info.nData;\n  return SQLITE_OK;\n}\n\n/*\n** Given the page number of an overflow page in the database (parameter\n** ovfl), this function finds the page number of the next page in the \n** linked list of overflow pages. If possible, it uses the auto-vacuum\n** pointer-map data instead of reading the content of page ovfl to do so. \n**\n** If an error occurs an SQLite error code is returned. Otherwise:\n**\n** The page number of the next overflow page in the linked list is \n** written to *pPgnoNext. If page ovfl is the last page in its linked \n** list, *pPgnoNext is set to zero. \n**\n** If ppPage is not NULL, and a reference to the MemPage object corresponding\n** to page number pOvfl was obtained, then *ppPage is set to point to that\n** reference. It is the responsibility of the caller to call releasePage()\n** on *ppPage to free the reference. In no reference was obtained (because\n** the pointer-map was used to obtain the value for *pPgnoNext), then\n** *ppPage is set to zero.\n*/\nstatic int getOverflowPage(\n  BtShared *pBt,               /* The database file */\n  Pgno ovfl,                   /* Current overflow page number */\n  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */\n  Pgno *pPgnoNext              /* OUT: Next overflow page number */\n){\n  Pgno next = 0;\n  MemPage *pPage = 0;\n  int rc = SQLITE_OK;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert(pPgnoNext);\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  /* Try to find the next page in the overflow list using the\n  ** autovacuum pointer-map pages. Guess that the next page in \n  ** the overflow list is page number (ovfl+1). If that guess turns \n  ** out to be wrong, fall back to loading the data of page \n  ** number ovfl to determine the next page number.\n  */\n  if( pBt->autoVacuum ){\n    Pgno pgno;\n    Pgno iGuess = ovfl+1;\n    u8 eType;\n\n    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){\n      iGuess++;\n    }\n\n    if( iGuess<=btreePagecount(pBt) ){\n      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);\n      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){\n        next = iGuess;\n        rc = SQLITE_DONE;\n      }\n    }\n  }\n#endif\n\n  assert( next==0 || rc==SQLITE_DONE );\n  if( rc==SQLITE_OK ){\n    rc = btreeGetPage(pBt, ovfl, &pPage, 0);\n    assert( rc==SQLITE_OK || pPage==0 );\n    if( rc==SQLITE_OK ){\n      next = get4byte(pPage->aData);\n    }\n  }\n\n  *pPgnoNext = next;\n  if( ppPage ){\n    *ppPage = pPage;\n  }else{\n    releasePage(pPage);\n  }\n  return (rc==SQLITE_DONE ? SQLITE_OK : rc);\n}\n\n/*\n** Copy data from a buffer to a page, or from a page to a buffer.\n**\n** pPayload is a pointer to data stored on database page pDbPage.\n** If argument eOp is false, then nByte bytes of data are copied\n** from pPayload to the buffer pointed at by pBuf. If eOp is true,\n** then sqlite3PagerWrite() is called on pDbPage and nByte bytes\n** of data are copied from the buffer pBuf to pPayload.\n**\n** SQLITE_OK is returned on success, otherwise an error code.\n*/\nstatic int copyPayload(\n  void *pPayload,           /* Pointer to page data */\n  void *pBuf,               /* Pointer to buffer */\n  int nByte,                /* Number of bytes to copy */\n  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */\n  DbPage *pDbPage           /* Page containing pPayload */\n){\n  if( eOp ){\n    /* Copy data from buffer to page (a write operation) */\n    int rc = sqlite3PagerWrite(pDbPage);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    memcpy(pPayload, pBuf, nByte);\n  }else{\n    /* Copy data from page to buffer (a read operation) */\n    memcpy(pBuf, pPayload, nByte);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This function is used to read or overwrite payload information\n** for the entry that the pCur cursor is pointing to. If the eOp\n** parameter is 0, this is a read operation (data copied into\n** buffer pBuf). If it is non-zero, a write (data copied from\n** buffer pBuf).\n**\n** A total of \"amt\" bytes are read or written beginning at \"offset\".\n** Data is read to or from the buffer pBuf.\n**\n** The content being read or written might appear on the main page\n** or be scattered out on multiple overflow pages.\n**\n** If the BtCursor.isIncrblobHandle flag is set, and the current\n** cursor entry uses one or more overflow pages, this function\n** allocates space for and lazily popluates the overflow page-list \n** cache array (BtCursor.aOverflow). Subsequent calls use this\n** cache to make seeking to the supplied offset more efficient.\n**\n** Once an overflow page-list cache has been allocated, it may be\n** invalidated if some other cursor writes to the same table, or if\n** the cursor is moved to a different row. Additionally, in auto-vacuum\n** mode, the following events may invalidate an overflow page-list cache.\n**\n**   * An incremental vacuum,\n**   * A commit in auto_vacuum=\"full\" mode,\n**   * Creating a table (may require moving an overflow page).\n*/\nstatic int accessPayload(\n  BtCursor *pCur,      /* Cursor pointing to entry to read from */\n  u32 offset,          /* Begin reading this far into payload */\n  u32 amt,             /* Read this many bytes */\n  unsigned char *pBuf, /* Write the bytes into this buffer */ \n  int eOp              /* zero to read. non-zero to write. */\n){\n  unsigned char *aPayload;\n  int rc = SQLITE_OK;\n  u32 nKey;\n  int iIdx = 0;\n  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */\n  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */\n\n  assert( pPage );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );\n  assert( cursorHoldsMutex(pCur) );\n\n  getCellInfo(pCur);\n  aPayload = pCur->info.pCell + pCur->info.nHeader;\n  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);\n\n  if( NEVER(offset+amt > nKey+pCur->info.nData) \n   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]\n  ){\n    /* Trying to read or write past the end of the data is an error */\n    return SQLITE_CORRUPT_BKPT;\n  }\n\n  /* Check if data must be read/written to/from the btree page itself. */\n  if( offset<pCur->info.nLocal ){\n    int a = amt;\n    if( a+offset>pCur->info.nLocal ){\n      a = pCur->info.nLocal - offset;\n    }\n    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);\n    offset = 0;\n    pBuf += a;\n    amt -= a;\n  }else{\n    offset -= pCur->info.nLocal;\n  }\n\n  if( rc==SQLITE_OK && amt>0 ){\n    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */\n    Pgno nextPage;\n\n    nextPage = get4byte(&aPayload[pCur->info.nLocal]);\n\n#ifndef SQLITE_OMIT_INCRBLOB\n    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]\n    ** has not been allocated, allocate it now. The array is sized at\n    ** one entry for each overflow page in the overflow chain. The\n    ** page number of the first overflow page is stored in aOverflow[0],\n    ** etc. A value of 0 in the aOverflow[] array means \"not yet known\"\n    ** (the cache is lazily populated).\n    */\n    if( pCur->isIncrblobHandle && !pCur->aOverflow ){\n      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;\n      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);\n      /* nOvfl is always positive.  If it were zero, fetchPayload would have\n      ** been used instead of this routine. */\n      if( ALWAYS(nOvfl) && !pCur->aOverflow ){\n        rc = SQLITE_NOMEM;\n      }\n    }\n\n    /* If the overflow page-list cache has been allocated and the\n    ** entry for the first required overflow page is valid, skip\n    ** directly to it.\n    */\n    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){\n      iIdx = (offset/ovflSize);\n      nextPage = pCur->aOverflow[iIdx];\n      offset = (offset%ovflSize);\n    }\n#endif\n\n    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){\n\n#ifndef SQLITE_OMIT_INCRBLOB\n      /* If required, populate the overflow page-list cache. */\n      if( pCur->aOverflow ){\n        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);\n        pCur->aOverflow[iIdx] = nextPage;\n      }\n#endif\n\n      if( offset>=ovflSize ){\n        /* The only reason to read this page is to obtain the page\n        ** number for the next page in the overflow chain. The page\n        ** data is not required. So first try to lookup the overflow\n        ** page-list cache, if any, then fall back to the getOverflowPage()\n        ** function.\n        */\n#ifndef SQLITE_OMIT_INCRBLOB\n        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){\n          nextPage = pCur->aOverflow[iIdx+1];\n        } else \n#endif\n          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);\n        offset -= ovflSize;\n      }else{\n        /* Need to read this page properly. It contains some of the\n        ** range of data that is being read (eOp==0) or written (eOp!=0).\n        */\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n        sqlite3_file *fd;\n#endif\n        int a = amt;\n        if( a + offset > ovflSize ){\n          a = ovflSize - offset;\n        }\n\n#ifdef SQLITE_DIRECT_OVERFLOW_READ\n        /* If all the following are true:\n        **\n        **   1) this is a read operation, and \n        **   2) data is required from the start of this overflow page, and\n        **   3) the database is file-backed, and\n        **   4) there is no open write-transaction, and\n        **   5) the database is not a WAL database,\n        **\n        ** then data can be read directly from the database file into the\n        ** output buffer, bypassing the page-cache altogether. This speeds\n        ** up loading large records that span many overflow pages.\n        */\n        if( eOp==0                                             /* (1) */\n         && offset==0                                          /* (2) */\n         && pBt->inTransaction==TRANS_READ                     /* (4) */\n         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */\n         && pBt->pPage1->aData[19]==0x01                       /* (5) */\n        ){\n          u8 aSave[4];\n          u8 *aWrite = &pBuf[-4];\n          memcpy(aSave, aWrite, 4);\n          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));\n          nextPage = get4byte(aWrite);\n          memcpy(aWrite, aSave, 4);\n        }else\n#endif\n\n        {\n          DbPage *pDbPage;\n          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);\n          if( rc==SQLITE_OK ){\n            aPayload = sqlite3PagerGetData(pDbPage);\n            nextPage = get4byte(aPayload);\n            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);\n            sqlite3PagerUnref(pDbPage);\n            offset = 0;\n          }\n        }\n        amt -= a;\n        pBuf += a;\n      }\n    }\n  }\n\n  if( rc==SQLITE_OK && amt>0 ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  return rc;\n}\n\n/*\n** Read part of the key associated with cursor pCur.  Exactly\n** \"amt\" bytes will be transfered into pBuf[].  The transfer\n** begins at \"offset\".\n**\n** The caller must ensure that pCur is pointing to a valid row\n** in the table.\n**\n** Return SQLITE_OK on success or an error code if anything goes\n** wrong.  An error is returned if \"offset+amt\" is larger than\n** the available payload.\n*/\nSQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );\n  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );\n  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);\n}\n\n/*\n** Read part of the data associated with cursor pCur.  Exactly\n** \"amt\" bytes will be transfered into pBuf[].  The transfer\n** begins at \"offset\".\n**\n** Return SQLITE_OK on success or an error code if anything goes\n** wrong.  An error is returned if \"offset+amt\" is larger than\n** the available payload.\n*/\nSQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){\n  int rc;\n\n#ifndef SQLITE_OMIT_INCRBLOB\n  if ( pCur->eState==CURSOR_INVALID ){\n    return SQLITE_ABORT;\n  }\n#endif\n\n  assert( cursorHoldsMutex(pCur) );\n  rc = restoreCursorPosition(pCur);\n  if( rc==SQLITE_OK ){\n    assert( pCur->eState==CURSOR_VALID );\n    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );\n    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );\n    rc = accessPayload(pCur, offset, amt, pBuf, 0);\n  }\n  return rc;\n}\n\n/*\n** Return a pointer to payload information from the entry that the \n** pCur cursor is pointing to.  The pointer is to the beginning of\n** the key if skipKey==0 and it points to the beginning of data if\n** skipKey==1.  The number of bytes of available key/data is written\n** into *pAmt.  If *pAmt==0, then the value returned will not be\n** a valid pointer.\n**\n** This routine is an optimization.  It is common for the entire key\n** and data to fit on the local page and for there to be no overflow\n** pages.  When that is so, this routine can be used to access the\n** key and data without making a copy.  If the key and/or data spills\n** onto overflow pages, then accessPayload() must be used to reassemble\n** the key/data and copy it into a preallocated buffer.\n**\n** The pointer returned by this routine looks directly into the cached\n** page of the database.  The data might change or move the next time\n** any btree routine is called.\n*/\nstatic const unsigned char *fetchPayload(\n  BtCursor *pCur,      /* Cursor pointing to entry to read from */\n  int *pAmt,           /* Write the number of available bytes here */\n  int skipKey          /* read beginning at data if this is true */\n){\n  unsigned char *aPayload;\n  MemPage *pPage;\n  u32 nKey;\n  u32 nLocal;\n\n  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);\n  assert( pCur->eState==CURSOR_VALID );\n  assert( cursorHoldsMutex(pCur) );\n  pPage = pCur->apPage[pCur->iPage];\n  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );\n  if( NEVER(pCur->info.nSize==0) ){\n    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],\n                   &pCur->info);\n  }\n  aPayload = pCur->info.pCell;\n  aPayload += pCur->info.nHeader;\n  if( pPage->intKey ){\n    nKey = 0;\n  }else{\n    nKey = (int)pCur->info.nKey;\n  }\n  if( skipKey ){\n    aPayload += nKey;\n    nLocal = pCur->info.nLocal - nKey;\n  }else{\n    nLocal = pCur->info.nLocal;\n    assert( nLocal<=nKey );\n  }\n  *pAmt = nLocal;\n  return aPayload;\n}\n\n\n/*\n** For the entry that cursor pCur is point to, return as\n** many bytes of the key or data as are available on the local\n** b-tree page.  Write the number of available bytes into *pAmt.\n**\n** The pointer returned is ephemeral.  The key/data may move\n** or be destroyed on the next call to any Btree routine,\n** including calls from other threads against the same cache.\n** Hence, a mutex on the BtShared should be held prior to calling\n** this routine.\n**\n** These routines is used to get quick access to key and data\n** in the common case where no overflow pages are used.\n*/\nSQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){\n  const void *p = 0;\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  assert( cursorHoldsMutex(pCur) );\n  if( ALWAYS(pCur->eState==CURSOR_VALID) ){\n    p = (const void*)fetchPayload(pCur, pAmt, 0);\n  }\n  return p;\n}\nSQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){\n  const void *p = 0;\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  assert( cursorHoldsMutex(pCur) );\n  if( ALWAYS(pCur->eState==CURSOR_VALID) ){\n    p = (const void*)fetchPayload(pCur, pAmt, 1);\n  }\n  return p;\n}\n\n\n/*\n** Move the cursor down to a new child page.  The newPgno argument is the\n** page number of the child page to move to.\n**\n** This function returns SQLITE_CORRUPT if the page-header flags field of\n** the new child page does not match the flags field of the parent (i.e.\n** if an intkey page appears to be the parent of a non-intkey page, or\n** vice-versa).\n*/\nstatic int moveToChild(BtCursor *pCur, u32 newPgno){\n  int rc;\n  int i = pCur->iPage;\n  MemPage *pNewPage;\n  BtShared *pBt = pCur->pBt;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );\n  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  rc = getAndInitPage(pBt, newPgno, &pNewPage);\n  if( rc ) return rc;\n  pCur->apPage[i+1] = pNewPage;\n  pCur->aiIdx[i+1] = 0;\n  pCur->iPage++;\n\n  pCur->info.nSize = 0;\n  pCur->validNKey = 0;\n  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  return SQLITE_OK;\n}\n\n#if 0\n/*\n** Page pParent is an internal (non-leaf) tree page. This function \n** asserts that page number iChild is the left-child if the iIdx'th\n** cell in page pParent. Or, if iIdx is equal to the total number of\n** cells in pParent, that page number iChild is the right-child of\n** the page.\n*/\nstatic void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){\n  assert( iIdx<=pParent->nCell );\n  if( iIdx==pParent->nCell ){\n    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );\n  }else{\n    assert( get4byte(findCell(pParent, iIdx))==iChild );\n  }\n}\n#else\n#  define assertParentIndex(x,y,z) \n#endif\n\n/*\n** Move the cursor up to the parent page.\n**\n** pCur->idx is set to the cell index that contains the pointer\n** to the page we are coming from.  If we are coming from the\n** right-most child page then pCur->idx is set to one more than\n** the largest cell index.\n*/\nstatic void moveToParent(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  assert( pCur->iPage>0 );\n  assert( pCur->apPage[pCur->iPage] );\n\n  /* UPDATE: It is actually possible for the condition tested by the assert\n  ** below to be untrue if the database file is corrupt. This can occur if\n  ** one cursor has modified page pParent while a reference to it is held \n  ** by a second cursor. Which can only happen if a single page is linked\n  ** into more than one b-tree structure in a corrupt database.  */\n#if 0\n  assertParentIndex(\n    pCur->apPage[pCur->iPage-1], \n    pCur->aiIdx[pCur->iPage-1], \n    pCur->apPage[pCur->iPage]->pgno\n  );\n#endif\n  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );\n\n  releasePage(pCur->apPage[pCur->iPage]);\n  pCur->iPage--;\n  pCur->info.nSize = 0;\n  pCur->validNKey = 0;\n}\n\n/*\n** Move the cursor to point to the root page of its b-tree structure.\n**\n** If the table has a virtual root page, then the cursor is moved to point\n** to the virtual root page instead of the actual root page. A table has a\n** virtual root page when the actual root page contains no cells and a \n** single child page. This can only happen with the table rooted at page 1.\n**\n** If the b-tree structure is empty, the cursor state is set to \n** CURSOR_INVALID. Otherwise, the cursor is set to point to the first\n** cell located on the root (or virtual root) page and the cursor state\n** is set to CURSOR_VALID.\n**\n** If this function returns successfully, it may be assumed that the\n** page-header flags indicate that the [virtual] root-page is the expected \n** kind of b-tree page (i.e. if when opening the cursor the caller did not\n** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,\n** indicating a table b-tree, or if the caller did specify a KeyInfo \n** structure the flags byte is set to 0x02 or 0x0A, indicating an index\n** b-tree).\n*/\nstatic int moveToRoot(BtCursor *pCur){\n  MemPage *pRoot;\n  int rc = SQLITE_OK;\n  Btree *p = pCur->pBtree;\n  BtShared *pBt = p->pBt;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );\n  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );\n  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );\n  if( pCur->eState>=CURSOR_REQUIRESEEK ){\n    if( pCur->eState==CURSOR_FAULT ){\n      assert( pCur->skipNext!=SQLITE_OK );\n      return pCur->skipNext;\n    }\n    sqlite3BtreeClearCursor(pCur);\n  }\n\n  if( pCur->iPage>=0 ){\n    int i;\n    for(i=1; i<=pCur->iPage; i++){\n      releasePage(pCur->apPage[i]);\n    }\n    pCur->iPage = 0;\n  }else if( pCur->pgnoRoot==0 ){\n    pCur->eState = CURSOR_INVALID;\n    return SQLITE_OK;\n  }else{\n    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);\n    if( rc!=SQLITE_OK ){\n      pCur->eState = CURSOR_INVALID;\n      return rc;\n    }\n    pCur->iPage = 0;\n\n    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor\n    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is\n    ** NULL, the caller expects a table b-tree. If this is not the case,\n    ** return an SQLITE_CORRUPT error.  */\n    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );\n    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n  }\n\n  /* Assert that the root page is of the correct type. This must be the\n  ** case as the call to this function that loaded the root-page (either\n  ** this call or a previous invocation) would have detected corruption \n  ** if the assumption were not true, and it is not possible for the flags \n  ** byte to have been modified while this cursor is holding a reference\n  ** to the page.  */\n  pRoot = pCur->apPage[0];\n  assert( pRoot->pgno==pCur->pgnoRoot );\n  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );\n\n  pCur->aiIdx[0] = 0;\n  pCur->info.nSize = 0;\n  pCur->atLast = 0;\n  pCur->validNKey = 0;\n\n  if( pRoot->nCell==0 && !pRoot->leaf ){\n    Pgno subpage;\n    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;\n    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);\n    pCur->eState = CURSOR_VALID;\n    rc = moveToChild(pCur, subpage);\n  }else{\n    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);\n  }\n  return rc;\n}\n\n/*\n** Move the cursor down to the left-most leaf entry beneath the\n** entry to which it is currently pointing.\n**\n** The left-most leaf is the one with the smallest key - the first\n** in ascending order.\n*/\nstatic int moveToLeftmost(BtCursor *pCur){\n  Pgno pgno;\n  int rc = SQLITE_OK;\n  MemPage *pPage;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){\n    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );\n    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));\n    rc = moveToChild(pCur, pgno);\n  }\n  return rc;\n}\n\n/*\n** Move the cursor down to the right-most leaf entry beneath the\n** page to which it is currently pointing.  Notice the difference\n** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()\n** finds the left-most entry beneath the *entry* whereas moveToRightmost()\n** finds the right-most entry beneath the *page*.\n**\n** The right-most entry is the one with the largest key - the last\n** key in ascending order.\n*/\nstatic int moveToRightmost(BtCursor *pCur){\n  Pgno pgno;\n  int rc = SQLITE_OK;\n  MemPage *pPage = 0;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->eState==CURSOR_VALID );\n  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){\n    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    pCur->aiIdx[pCur->iPage] = pPage->nCell;\n    rc = moveToChild(pCur, pgno);\n  }\n  if( rc==SQLITE_OK ){\n    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;\n    pCur->info.nSize = 0;\n    pCur->validNKey = 0;\n  }\n  return rc;\n}\n\n/* Move the cursor to the first entry in the table.  Return SQLITE_OK\n** on success.  Set *pRes to 0 if the cursor actually points to something\n** or set *pRes to 1 if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){\n  int rc;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  rc = moveToRoot(pCur);\n  if( rc==SQLITE_OK ){\n    if( pCur->eState==CURSOR_INVALID ){\n      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );\n      *pRes = 1;\n    }else{\n      assert( pCur->apPage[pCur->iPage]->nCell>0 );\n      *pRes = 0;\n      rc = moveToLeftmost(pCur);\n    }\n  }\n  return rc;\n}\n\n/* Move the cursor to the last entry in the table.  Return SQLITE_OK\n** on success.  Set *pRes to 0 if the cursor actually points to something\n** or set *pRes to 1 if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){\n  int rc;\n \n  assert( cursorHoldsMutex(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n\n  /* If the cursor already points to the last entry, this is a no-op. */\n  if( CURSOR_VALID==pCur->eState && pCur->atLast ){\n#ifdef SQLITE_DEBUG\n    /* This block serves to assert() that the cursor really does point \n    ** to the last entry in the b-tree. */\n    int ii;\n    for(ii=0; ii<pCur->iPage; ii++){\n      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );\n    }\n    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );\n    assert( pCur->apPage[pCur->iPage]->leaf );\n#endif\n    return SQLITE_OK;\n  }\n\n  rc = moveToRoot(pCur);\n  if( rc==SQLITE_OK ){\n    if( CURSOR_INVALID==pCur->eState ){\n      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );\n      *pRes = 1;\n    }else{\n      assert( pCur->eState==CURSOR_VALID );\n      *pRes = 0;\n      rc = moveToRightmost(pCur);\n      pCur->atLast = rc==SQLITE_OK ?1:0;\n    }\n  }\n  return rc;\n}\n\n/* Move the cursor so that it points to an entry near the key \n** specified by pIdxKey or intKey.   Return a success code.\n**\n** For INTKEY tables, the intKey parameter is used.  pIdxKey \n** must be NULL.  For index tables, pIdxKey is used and intKey\n** is ignored.\n**\n** If an exact match is not found, then the cursor is always\n** left pointing at a leaf page which would hold the entry if it\n** were present.  The cursor might point to an entry that comes\n** before or after the key.\n**\n** An integer is written into *pRes which is the result of\n** comparing the key with the entry to which the cursor is \n** pointing.  The meaning of the integer written into\n** *pRes is as follows:\n**\n**     *pRes<0      The cursor is left pointing at an entry that\n**                  is smaller than intKey/pIdxKey or if the table is empty\n**                  and the cursor is therefore left point to nothing.\n**\n**     *pRes==0     The cursor is left pointing at an entry that\n**                  exactly matches intKey/pIdxKey.\n**\n**     *pRes>0      The cursor is left pointing at an entry that\n**                  is larger than intKey/pIdxKey.\n**\n*/\nSQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(\n  BtCursor *pCur,          /* The cursor to be moved */\n  UnpackedRecord *pIdxKey, /* Unpacked index key */\n  i64 intKey,              /* The table key */\n  int biasRight,           /* If true, bias the search to the high end */\n  int *pRes                /* Write search results here */\n){\n  int rc;\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  assert( pRes );\n  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );\n\n  /* If the cursor is already positioned at the point we are trying\n  ** to move to, then just return without doing any work */\n  if( pCur->eState==CURSOR_VALID && pCur->validNKey \n   && pCur->apPage[0]->intKey \n  ){\n    if( pCur->info.nKey==intKey ){\n      *pRes = 0;\n      return SQLITE_OK;\n    }\n    if( pCur->atLast && pCur->info.nKey<intKey ){\n      *pRes = -1;\n      return SQLITE_OK;\n    }\n  }\n\n  rc = moveToRoot(pCur);\n  if( rc ){\n    return rc;\n  }\n  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );\n  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );\n  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );\n  if( pCur->eState==CURSOR_INVALID ){\n    *pRes = -1;\n    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );\n    return SQLITE_OK;\n  }\n  assert( pCur->apPage[0]->intKey || pIdxKey );\n  for(;;){\n    int lwr, upr, idx;\n    Pgno chldPg;\n    MemPage *pPage = pCur->apPage[pCur->iPage];\n    int c;\n\n    /* pPage->nCell must be greater than zero. If this is the root-page\n    ** the cursor would have been INVALID above and this for(;;) loop\n    ** not run. If this is not the root-page, then the moveToChild() routine\n    ** would have already detected db corruption. Similarly, pPage must\n    ** be the right kind (index or table) of b-tree page. Otherwise\n    ** a moveToChild() or moveToRoot() call would have detected corruption.  */\n    assert( pPage->nCell>0 );\n    assert( pPage->intKey==(pIdxKey==0) );\n    lwr = 0;\n    upr = pPage->nCell-1;\n    if( biasRight ){\n      pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);\n    }else{\n      pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);\n    }\n    for(;;){\n      u8 *pCell;                          /* Pointer to current cell in pPage */\n\n      assert( idx==pCur->aiIdx[pCur->iPage] );\n      pCur->info.nSize = 0;\n      pCell = findCell(pPage, idx) + pPage->childPtrSize;\n      if( pPage->intKey ){\n        i64 nCellKey;\n        if( pPage->hasData ){\n          u32 dummy;\n          pCell += getVarint32(pCell, dummy);\n        }\n        getVarint(pCell, (u64*)&nCellKey);\n        if( nCellKey==intKey ){\n          c = 0;\n        }else if( nCellKey<intKey ){\n          c = -1;\n        }else{\n          assert( nCellKey>intKey );\n          c = +1;\n        }\n        pCur->validNKey = 1;\n        pCur->info.nKey = nCellKey;\n      }else{\n        /* The maximum supported page-size is 65536 bytes. This means that\n        ** the maximum number of record bytes stored on an index B-Tree\n        ** page is less than 16384 bytes and may be stored as a 2-byte\n        ** varint. This information is used to attempt to avoid parsing \n        ** the entire cell by checking for the cases where the record is \n        ** stored entirely within the b-tree page by inspecting the first \n        ** 2 bytes of the cell.\n        */\n        int nCell = pCell[0];\n        if( nCell<=pPage->max1bytePayload\n         /* && (pCell+nCell)<pPage->aDataEnd */\n        ){\n          /* This branch runs if the record-size field of the cell is a\n          ** single byte varint and the record fits entirely on the main\n          ** b-tree page.  */\n          testcase( pCell+nCell+1==pPage->aDataEnd );\n          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);\n        }else if( !(pCell[1] & 0x80) \n          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal\n          /* && (pCell+nCell+2)<=pPage->aDataEnd */\n        ){\n          /* The record-size field is a 2 byte varint and the record \n          ** fits entirely on the main b-tree page.  */\n          testcase( pCell+nCell+2==pPage->aDataEnd );\n          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);\n        }else{\n          /* The record flows over onto one or more overflow pages. In\n          ** this case the whole cell needs to be parsed, a buffer allocated\n          ** and accessPayload() used to retrieve the record into the\n          ** buffer before VdbeRecordCompare() can be called. */\n          void *pCellKey;\n          u8 * const pCellBody = pCell - pPage->childPtrSize;\n          btreeParseCellPtr(pPage, pCellBody, &pCur->info);\n          nCell = (int)pCur->info.nKey;\n          pCellKey = sqlite3Malloc( nCell );\n          if( pCellKey==0 ){\n            rc = SQLITE_NOMEM;\n            goto moveto_finish;\n          }\n          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);\n          if( rc ){\n            sqlite3_free(pCellKey);\n            goto moveto_finish;\n          }\n          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);\n          sqlite3_free(pCellKey);\n        }\n      }\n      if( c==0 ){\n        if( pPage->intKey && !pPage->leaf ){\n          lwr = idx;\n          break;\n        }else{\n          *pRes = 0;\n          rc = SQLITE_OK;\n          goto moveto_finish;\n        }\n      }\n      if( c<0 ){\n        lwr = idx+1;\n      }else{\n        upr = idx-1;\n      }\n      if( lwr>upr ){\n        break;\n      }\n      pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);\n    }\n    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );\n    assert( pPage->isInit );\n    if( pPage->leaf ){\n      chldPg = 0;\n    }else if( lwr>=pPage->nCell ){\n      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    }else{\n      chldPg = get4byte(findCell(pPage, lwr));\n    }\n    if( chldPg==0 ){\n      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );\n      *pRes = c;\n      rc = SQLITE_OK;\n      goto moveto_finish;\n    }\n    pCur->aiIdx[pCur->iPage] = (u16)lwr;\n    pCur->info.nSize = 0;\n    pCur->validNKey = 0;\n    rc = moveToChild(pCur, chldPg);\n    if( rc ) goto moveto_finish;\n  }\nmoveto_finish:\n  return rc;\n}\n\n\n/*\n** Return TRUE if the cursor is not pointing at an entry of the table.\n**\n** TRUE will be returned after a call to sqlite3BtreeNext() moves\n** past the last entry in the table or sqlite3BtreePrev() moves past\n** the first entry.  TRUE is also returned if the table is empty.\n*/\nSQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){\n  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries\n  ** have been deleted? This API will need to change to return an error code\n  ** as well as the boolean result value.\n  */\n  return (CURSOR_VALID!=pCur->eState);\n}\n\n/*\n** Advance the cursor to the next entry in the database.  If\n** successful then set *pRes=0.  If the cursor\n** was already pointing to the last entry in the database before\n** this routine was called, then set *pRes=1.\n*/\nSQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){\n  int rc;\n  int idx;\n  MemPage *pPage;\n\n  assert( cursorHoldsMutex(pCur) );\n  rc = restoreCursorPosition(pCur);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  assert( pRes!=0 );\n  if( CURSOR_INVALID==pCur->eState ){\n    *pRes = 1;\n    return SQLITE_OK;\n  }\n  if( pCur->skipNext>0 ){\n    pCur->skipNext = 0;\n    *pRes = 0;\n    return SQLITE_OK;\n  }\n  pCur->skipNext = 0;\n\n  pPage = pCur->apPage[pCur->iPage];\n  idx = ++pCur->aiIdx[pCur->iPage];\n  assert( pPage->isInit );\n\n  /* If the database file is corrupt, it is possible for the value of idx \n  ** to be invalid here. This can only occur if a second cursor modifies\n  ** the page while cursor pCur is holding a reference to it. Which can\n  ** only happen if the database is corrupt in such a way as to link the\n  ** page into more than one b-tree structure. */\n  testcase( idx>pPage->nCell );\n\n  pCur->info.nSize = 0;\n  pCur->validNKey = 0;\n  if( idx>=pPage->nCell ){\n    if( !pPage->leaf ){\n      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));\n      if( rc ) return rc;\n      rc = moveToLeftmost(pCur);\n      *pRes = 0;\n      return rc;\n    }\n    do{\n      if( pCur->iPage==0 ){\n        *pRes = 1;\n        pCur->eState = CURSOR_INVALID;\n        return SQLITE_OK;\n      }\n      moveToParent(pCur);\n      pPage = pCur->apPage[pCur->iPage];\n    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );\n    *pRes = 0;\n    if( pPage->intKey ){\n      rc = sqlite3BtreeNext(pCur, pRes);\n    }else{\n      rc = SQLITE_OK;\n    }\n    return rc;\n  }\n  *pRes = 0;\n  if( pPage->leaf ){\n    return SQLITE_OK;\n  }\n  rc = moveToLeftmost(pCur);\n  return rc;\n}\n\n\n/*\n** Step the cursor to the back to the previous entry in the database.  If\n** successful then set *pRes=0.  If the cursor\n** was already pointing to the first entry in the database before\n** this routine was called, then set *pRes=1.\n*/\nSQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){\n  int rc;\n  MemPage *pPage;\n\n  assert( cursorHoldsMutex(pCur) );\n  rc = restoreCursorPosition(pCur);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  pCur->atLast = 0;\n  if( CURSOR_INVALID==pCur->eState ){\n    *pRes = 1;\n    return SQLITE_OK;\n  }\n  if( pCur->skipNext<0 ){\n    pCur->skipNext = 0;\n    *pRes = 0;\n    return SQLITE_OK;\n  }\n  pCur->skipNext = 0;\n\n  pPage = pCur->apPage[pCur->iPage];\n  assert( pPage->isInit );\n  if( !pPage->leaf ){\n    int idx = pCur->aiIdx[pCur->iPage];\n    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));\n    if( rc ){\n      return rc;\n    }\n    rc = moveToRightmost(pCur);\n  }else{\n    while( pCur->aiIdx[pCur->iPage]==0 ){\n      if( pCur->iPage==0 ){\n        pCur->eState = CURSOR_INVALID;\n        *pRes = 1;\n        return SQLITE_OK;\n      }\n      moveToParent(pCur);\n    }\n    pCur->info.nSize = 0;\n    pCur->validNKey = 0;\n\n    pCur->aiIdx[pCur->iPage]--;\n    pPage = pCur->apPage[pCur->iPage];\n    if( pPage->intKey && !pPage->leaf ){\n      rc = sqlite3BtreePrevious(pCur, pRes);\n    }else{\n      rc = SQLITE_OK;\n    }\n  }\n  *pRes = 0;\n  return rc;\n}\n\n/*\n** Allocate a new page from the database file.\n**\n** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()\n** has already been called on the new page.)  The new page has also\n** been referenced and the calling routine is responsible for calling\n** sqlite3PagerUnref() on the new page when it is done.\n**\n** SQLITE_OK is returned on success.  Any other return value indicates\n** an error.  *ppPage and *pPgno are undefined in the event of an error.\n** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.\n**\n** If the \"nearby\" parameter is not 0, then a (feeble) effort is made to \n** locate a page close to the page number \"nearby\".  This can be used in an\n** attempt to keep related pages close to each other in the database file,\n** which in turn can make database access faster.\n**\n** If the \"exact\" parameter is not 0, and the page-number nearby exists \n** anywhere on the free-list, then it is guarenteed to be returned. This\n** is only used by auto-vacuum databases when allocating a new table.\n*/\nstatic int allocateBtreePage(\n  BtShared *pBt, \n  MemPage **ppPage, \n  Pgno *pPgno, \n  Pgno nearby,\n  u8 exact\n){\n  MemPage *pPage1;\n  int rc;\n  u32 n;     /* Number of pages on the freelist */\n  u32 k;     /* Number of leaves on the trunk of the freelist */\n  MemPage *pTrunk = 0;\n  MemPage *pPrevTrunk = 0;\n  Pgno mxPage;     /* Total size of the database file */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  pPage1 = pBt->pPage1;\n  mxPage = btreePagecount(pBt);\n  n = get4byte(&pPage1->aData[36]);\n  testcase( n==mxPage-1 );\n  if( n>=mxPage ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n  if( n>0 ){\n    /* There are pages on the freelist.  Reuse one of those pages. */\n    Pgno iTrunk;\n    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */\n    \n    /* If the 'exact' parameter was true and a query of the pointer-map\n    ** shows that the page 'nearby' is somewhere on the free-list, then\n    ** the entire-list will be searched for that page.\n    */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( exact && nearby<=mxPage ){\n      u8 eType;\n      assert( nearby>0 );\n      assert( pBt->autoVacuum );\n      rc = ptrmapGet(pBt, nearby, &eType, 0);\n      if( rc ) return rc;\n      if( eType==PTRMAP_FREEPAGE ){\n        searchList = 1;\n      }\n      *pPgno = nearby;\n    }\n#endif\n\n    /* Decrement the free-list count by 1. Set iTrunk to the index of the\n    ** first free-list trunk page. iPrevTrunk is initially 1.\n    */\n    rc = sqlite3PagerWrite(pPage1->pDbPage);\n    if( rc ) return rc;\n    put4byte(&pPage1->aData[36], n-1);\n\n    /* The code within this loop is run only once if the 'searchList' variable\n    ** is not true. Otherwise, it runs once for each trunk-page on the\n    ** free-list until the page 'nearby' is located.\n    */\n    do {\n      pPrevTrunk = pTrunk;\n      if( pPrevTrunk ){\n        iTrunk = get4byte(&pPrevTrunk->aData[0]);\n      }else{\n        iTrunk = get4byte(&pPage1->aData[32]);\n      }\n      testcase( iTrunk==mxPage );\n      if( iTrunk>mxPage ){\n        rc = SQLITE_CORRUPT_BKPT;\n      }else{\n        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);\n      }\n      if( rc ){\n        pTrunk = 0;\n        goto end_allocate_page;\n      }\n      assert( pTrunk!=0 );\n      assert( pTrunk->aData!=0 );\n\n      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */\n      if( k==0 && !searchList ){\n        /* The trunk has no leaves and the list is not being searched. \n        ** So extract the trunk page itself and use it as the newly \n        ** allocated page */\n        assert( pPrevTrunk==0 );\n        rc = sqlite3PagerWrite(pTrunk->pDbPage);\n        if( rc ){\n          goto end_allocate_page;\n        }\n        *pPgno = iTrunk;\n        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);\n        *ppPage = pTrunk;\n        pTrunk = 0;\n        TRACE((\"ALLOCATE: %d trunk - %d free pages left\\n\", *pPgno, n-1));\n      }else if( k>(u32)(pBt->usableSize/4 - 2) ){\n        /* Value of k is out of range.  Database corruption */\n        rc = SQLITE_CORRUPT_BKPT;\n        goto end_allocate_page;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      }else if( searchList && nearby==iTrunk ){\n        /* The list is being searched and this trunk page is the page\n        ** to allocate, regardless of whether it has leaves.\n        */\n        assert( *pPgno==iTrunk );\n        *ppPage = pTrunk;\n        searchList = 0;\n        rc = sqlite3PagerWrite(pTrunk->pDbPage);\n        if( rc ){\n          goto end_allocate_page;\n        }\n        if( k==0 ){\n          if( !pPrevTrunk ){\n            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);\n          }else{\n            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);\n            if( rc!=SQLITE_OK ){\n              goto end_allocate_page;\n            }\n            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);\n          }\n        }else{\n          /* The trunk page is required by the caller but it contains \n          ** pointers to free-list leaves. The first leaf becomes a trunk\n          ** page in this case.\n          */\n          MemPage *pNewTrunk;\n          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);\n          if( iNewTrunk>mxPage ){ \n            rc = SQLITE_CORRUPT_BKPT;\n            goto end_allocate_page;\n          }\n          testcase( iNewTrunk==mxPage );\n          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);\n          if( rc!=SQLITE_OK ){\n            goto end_allocate_page;\n          }\n          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);\n          if( rc!=SQLITE_OK ){\n            releasePage(pNewTrunk);\n            goto end_allocate_page;\n          }\n          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);\n          put4byte(&pNewTrunk->aData[4], k-1);\n          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);\n          releasePage(pNewTrunk);\n          if( !pPrevTrunk ){\n            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );\n            put4byte(&pPage1->aData[32], iNewTrunk);\n          }else{\n            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);\n            if( rc ){\n              goto end_allocate_page;\n            }\n            put4byte(&pPrevTrunk->aData[0], iNewTrunk);\n          }\n        }\n        pTrunk = 0;\n        TRACE((\"ALLOCATE: %d trunk - %d free pages left\\n\", *pPgno, n-1));\n#endif\n      }else if( k>0 ){\n        /* Extract a leaf from the trunk */\n        u32 closest;\n        Pgno iPage;\n        unsigned char *aData = pTrunk->aData;\n        if( nearby>0 ){\n          u32 i;\n          int dist;\n          closest = 0;\n          dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);\n          for(i=1; i<k; i++){\n            int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);\n            if( d2<dist ){\n              closest = i;\n              dist = d2;\n            }\n          }\n        }else{\n          closest = 0;\n        }\n\n        iPage = get4byte(&aData[8+closest*4]);\n        testcase( iPage==mxPage );\n        if( iPage>mxPage ){\n          rc = SQLITE_CORRUPT_BKPT;\n          goto end_allocate_page;\n        }\n        testcase( iPage==mxPage );\n        if( !searchList || iPage==nearby ){\n          int noContent;\n          *pPgno = iPage;\n          TRACE((\"ALLOCATE: %d was leaf %d of %d on trunk %d\"\n                 \": %d more free pages\\n\",\n                 *pPgno, closest+1, k, pTrunk->pgno, n-1));\n          rc = sqlite3PagerWrite(pTrunk->pDbPage);\n          if( rc ) goto end_allocate_page;\n          if( closest<k-1 ){\n            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);\n          }\n          put4byte(&aData[4], k-1);\n          noContent = !btreeGetHasContent(pBt, *pPgno);\n          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);\n          if( rc==SQLITE_OK ){\n            rc = sqlite3PagerWrite((*ppPage)->pDbPage);\n            if( rc!=SQLITE_OK ){\n              releasePage(*ppPage);\n            }\n          }\n          searchList = 0;\n        }\n      }\n      releasePage(pPrevTrunk);\n      pPrevTrunk = 0;\n    }while( searchList );\n  }else{\n    /* There are no pages on the freelist, so create a new page at the\n    ** end of the file */\n    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n    if( rc ) return rc;\n    pBt->nPage++;\n    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){\n      /* If *pPgno refers to a pointer-map page, allocate two new pages\n      ** at the end of the file instead of one. The first allocated page\n      ** becomes a new pointer-map page, the second is used by the caller.\n      */\n      MemPage *pPg = 0;\n      TRACE((\"ALLOCATE: %d from end of file (pointer-map page)\\n\", pBt->nPage));\n      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );\n      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerWrite(pPg->pDbPage);\n        releasePage(pPg);\n      }\n      if( rc ) return rc;\n      pBt->nPage++;\n      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }\n    }\n#endif\n    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);\n    *pPgno = pBt->nPage;\n\n    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );\n    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);\n    if( rc ) return rc;\n    rc = sqlite3PagerWrite((*ppPage)->pDbPage);\n    if( rc!=SQLITE_OK ){\n      releasePage(*ppPage);\n    }\n    TRACE((\"ALLOCATE: %d from end of file\\n\", *pPgno));\n  }\n\n  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );\n\nend_allocate_page:\n  releasePage(pTrunk);\n  releasePage(pPrevTrunk);\n  if( rc==SQLITE_OK ){\n    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){\n      releasePage(*ppPage);\n      return SQLITE_CORRUPT_BKPT;\n    }\n    (*ppPage)->isInit = 0;\n  }else{\n    *ppPage = 0;\n  }\n  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );\n  return rc;\n}\n\n/*\n** This function is used to add page iPage to the database file free-list. \n** It is assumed that the page is not already a part of the free-list.\n**\n** The value passed as the second argument to this function is optional.\n** If the caller happens to have a pointer to the MemPage object \n** corresponding to page iPage handy, it may pass it as the second value. \n** Otherwise, it may pass NULL.\n**\n** If a pointer to a MemPage object is passed as the second argument,\n** its reference count is not altered by this function.\n*/\nstatic int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){\n  MemPage *pTrunk = 0;                /* Free-list trunk page */\n  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ \n  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */\n  MemPage *pPage;                     /* Page being freed. May be NULL. */\n  int rc;                             /* Return Code */\n  int nFree;                          /* Initial number of pages on free-list */\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( iPage>1 );\n  assert( !pMemPage || pMemPage->pgno==iPage );\n\n  if( pMemPage ){\n    pPage = pMemPage;\n    sqlite3PagerRef(pPage->pDbPage);\n  }else{\n    pPage = btreePageLookup(pBt, iPage);\n  }\n\n  /* Increment the free page count on pPage1 */\n  rc = sqlite3PagerWrite(pPage1->pDbPage);\n  if( rc ) goto freepage_out;\n  nFree = get4byte(&pPage1->aData[36]);\n  put4byte(&pPage1->aData[36], nFree+1);\n\n  if( pBt->btsFlags & BTS_SECURE_DELETE ){\n    /* If the secure_delete option is enabled, then\n    ** always fully overwrite deleted information with zeros.\n    */\n    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )\n     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)\n    ){\n      goto freepage_out;\n    }\n    memset(pPage->aData, 0, pPage->pBt->pageSize);\n  }\n\n  /* If the database supports auto-vacuum, write an entry in the pointer-map\n  ** to indicate that the page is free.\n  */\n  if( ISAUTOVACUUM ){\n    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);\n    if( rc ) goto freepage_out;\n  }\n\n  /* Now manipulate the actual database free-list structure. There are two\n  ** possibilities. If the free-list is currently empty, or if the first\n  ** trunk page in the free-list is full, then this page will become a\n  ** new free-list trunk page. Otherwise, it will become a leaf of the\n  ** first trunk page in the current free-list. This block tests if it\n  ** is possible to add the page as a new free-list leaf.\n  */\n  if( nFree!=0 ){\n    u32 nLeaf;                /* Initial number of leaf cells on trunk page */\n\n    iTrunk = get4byte(&pPage1->aData[32]);\n    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);\n    if( rc!=SQLITE_OK ){\n      goto freepage_out;\n    }\n\n    nLeaf = get4byte(&pTrunk->aData[4]);\n    assert( pBt->usableSize>32 );\n    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto freepage_out;\n    }\n    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){\n      /* In this case there is room on the trunk page to insert the page\n      ** being freed as a new leaf.\n      **\n      ** Note that the trunk page is not really full until it contains\n      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have\n      ** coded.  But due to a coding error in versions of SQLite prior to\n      ** 3.6.0, databases with freelist trunk pages holding more than\n      ** usableSize/4 - 8 entries will be reported as corrupt.  In order\n      ** to maintain backwards compatibility with older versions of SQLite,\n      ** we will continue to restrict the number of entries to usableSize/4 - 8\n      ** for now.  At some point in the future (once everyone has upgraded\n      ** to 3.6.0 or later) we should consider fixing the conditional above\n      ** to read \"usableSize/4-2\" instead of \"usableSize/4-8\".\n      */\n      rc = sqlite3PagerWrite(pTrunk->pDbPage);\n      if( rc==SQLITE_OK ){\n        put4byte(&pTrunk->aData[4], nLeaf+1);\n        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);\n        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){\n          sqlite3PagerDontWrite(pPage->pDbPage);\n        }\n        rc = btreeSetHasContent(pBt, iPage);\n      }\n      TRACE((\"FREE-PAGE: %d leaf on trunk page %d\\n\",pPage->pgno,pTrunk->pgno));\n      goto freepage_out;\n    }\n  }\n\n  /* If control flows to this point, then it was not possible to add the\n  ** the page being freed as a leaf page of the first trunk in the free-list.\n  ** Possibly because the free-list is empty, or possibly because the \n  ** first trunk in the free-list is full. Either way, the page being freed\n  ** will become the new first trunk page in the free-list.\n  */\n  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){\n    goto freepage_out;\n  }\n  rc = sqlite3PagerWrite(pPage->pDbPage);\n  if( rc!=SQLITE_OK ){\n    goto freepage_out;\n  }\n  put4byte(pPage->aData, iTrunk);\n  put4byte(&pPage->aData[4], 0);\n  put4byte(&pPage1->aData[32], iPage);\n  TRACE((\"FREE-PAGE: %d new trunk page replacing %d\\n\", pPage->pgno, iTrunk));\n\nfreepage_out:\n  if( pPage ){\n    pPage->isInit = 0;\n  }\n  releasePage(pPage);\n  releasePage(pTrunk);\n  return rc;\n}\nstatic void freePage(MemPage *pPage, int *pRC){\n  if( (*pRC)==SQLITE_OK ){\n    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);\n  }\n}\n\n/*\n** Free any overflow pages associated with the given Cell.\n*/\nstatic int clearCell(MemPage *pPage, unsigned char *pCell){\n  BtShared *pBt = pPage->pBt;\n  CellInfo info;\n  Pgno ovflPgno;\n  int rc;\n  int nOvfl;\n  u32 ovflPageSize;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  btreeParseCellPtr(pPage, pCell, &info);\n  if( info.iOverflow==0 ){\n    return SQLITE_OK;  /* No overflow pages. Return without doing anything */\n  }\n  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){\n    return SQLITE_CORRUPT;  /* Cell extends past end of page */\n  }\n  ovflPgno = get4byte(&pCell[info.iOverflow]);\n  assert( pBt->usableSize > 4 );\n  ovflPageSize = pBt->usableSize - 4;\n  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;\n  assert( ovflPgno==0 || nOvfl>0 );\n  while( nOvfl-- ){\n    Pgno iNext = 0;\n    MemPage *pOvfl = 0;\n    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){\n      /* 0 is not a legal page number and page 1 cannot be an \n      ** overflow page. Therefore if ovflPgno<2 or past the end of the \n      ** file the database must be corrupt. */\n      return SQLITE_CORRUPT_BKPT;\n    }\n    if( nOvfl ){\n      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);\n      if( rc ) return rc;\n    }\n\n    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )\n     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1\n    ){\n      /* There is no reason any cursor should have an outstanding reference \n      ** to an overflow page belonging to a cell that is being deleted/updated.\n      ** So if there exists more than one reference to this page, then it \n      ** must not really be an overflow page and the database must be corrupt. \n      ** It is helpful to detect this before calling freePage2(), as \n      ** freePage2() may zero the page contents if secure-delete mode is\n      ** enabled. If this 'overflow' page happens to be a page that the\n      ** caller is iterating through or using in some other way, this\n      ** can be problematic.\n      */\n      rc = SQLITE_CORRUPT_BKPT;\n    }else{\n      rc = freePage2(pBt, pOvfl, ovflPgno);\n    }\n\n    if( pOvfl ){\n      sqlite3PagerUnref(pOvfl->pDbPage);\n    }\n    if( rc ) return rc;\n    ovflPgno = iNext;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Create the byte sequence used to represent a cell on page pPage\n** and write that byte sequence into pCell[].  Overflow pages are\n** allocated and filled in as necessary.  The calling procedure\n** is responsible for making sure sufficient space has been allocated\n** for pCell[].\n**\n** Note that pCell does not necessary need to point to the pPage->aData\n** area.  pCell might point to some temporary storage.  The cell will\n** be constructed in this temporary area then copied into pPage->aData\n** later.\n*/\nstatic int fillInCell(\n  MemPage *pPage,                /* The page that contains the cell */\n  unsigned char *pCell,          /* Complete text of the cell */\n  const void *pKey, i64 nKey,    /* The key */\n  const void *pData,int nData,   /* The data */\n  int nZero,                     /* Extra zero bytes to append to pData */\n  int *pnSize                    /* Write cell size here */\n){\n  int nPayload;\n  const u8 *pSrc;\n  int nSrc, n, rc;\n  int spaceLeft;\n  MemPage *pOvfl = 0;\n  MemPage *pToRelease = 0;\n  unsigned char *pPrior;\n  unsigned char *pPayload;\n  BtShared *pBt = pPage->pBt;\n  Pgno pgnoOvfl = 0;\n  int nHeader;\n  CellInfo info;\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n\n  /* pPage is not necessarily writeable since pCell might be auxiliary\n  ** buffer space that is separate from the pPage buffer area */\n  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n  /* Fill in the header. */\n  nHeader = 0;\n  if( !pPage->leaf ){\n    nHeader += 4;\n  }\n  if( pPage->hasData ){\n    nHeader += putVarint(&pCell[nHeader], nData+nZero);\n  }else{\n    nData = nZero = 0;\n  }\n  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);\n  btreeParseCellPtr(pPage, pCell, &info);\n  assert( info.nHeader==nHeader );\n  assert( info.nKey==nKey );\n  assert( info.nData==(u32)(nData+nZero) );\n  \n  /* Fill in the payload */\n  nPayload = nData + nZero;\n  if( pPage->intKey ){\n    pSrc = pData;\n    nSrc = nData;\n    nData = 0;\n  }else{ \n    if( NEVER(nKey>0x7fffffff || pKey==0) ){\n      return SQLITE_CORRUPT_BKPT;\n    }\n    nPayload += (int)nKey;\n    pSrc = pKey;\n    nSrc = (int)nKey;\n  }\n  *pnSize = info.nSize;\n  spaceLeft = info.nLocal;\n  pPayload = &pCell[nHeader];\n  pPrior = &pCell[info.iOverflow];\n\n  while( nPayload>0 ){\n    if( spaceLeft==0 ){\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */\n      if( pBt->autoVacuum ){\n        do{\n          pgnoOvfl++;\n        } while( \n          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) \n        );\n      }\n#endif\n      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      /* If the database supports auto-vacuum, and the second or subsequent\n      ** overflow page is being allocated, add an entry to the pointer-map\n      ** for that page now. \n      **\n      ** If this is the first overflow page, then write a partial entry \n      ** to the pointer-map. If we write nothing to this pointer-map slot,\n      ** then the optimistic overflow chain processing in clearCell()\n      ** may misinterpret the uninitialised values and delete the\n      ** wrong pages from the database.\n      */\n      if( pBt->autoVacuum && rc==SQLITE_OK ){\n        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);\n        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);\n        if( rc ){\n          releasePage(pOvfl);\n        }\n      }\n#endif\n      if( rc ){\n        releasePage(pToRelease);\n        return rc;\n      }\n\n      /* If pToRelease is not zero than pPrior points into the data area\n      ** of pToRelease.  Make sure pToRelease is still writeable. */\n      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );\n\n      /* If pPrior is part of the data area of pPage, then make sure pPage\n      ** is still writeable */\n      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n      put4byte(pPrior, pgnoOvfl);\n      releasePage(pToRelease);\n      pToRelease = pOvfl;\n      pPrior = pOvfl->aData;\n      put4byte(pPrior, 0);\n      pPayload = &pOvfl->aData[4];\n      spaceLeft = pBt->usableSize - 4;\n    }\n    n = nPayload;\n    if( n>spaceLeft ) n = spaceLeft;\n\n    /* If pToRelease is not zero than pPayload points into the data area\n    ** of pToRelease.  Make sure pToRelease is still writeable. */\n    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );\n\n    /* If pPayload is part of the data area of pPage, then make sure pPage\n    ** is still writeable */\n    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]\n            || sqlite3PagerIswriteable(pPage->pDbPage) );\n\n    if( nSrc>0 ){\n      if( n>nSrc ) n = nSrc;\n      assert( pSrc );\n      memcpy(pPayload, pSrc, n);\n    }else{\n      memset(pPayload, 0, n);\n    }\n    nPayload -= n;\n    pPayload += n;\n    pSrc += n;\n    nSrc -= n;\n    spaceLeft -= n;\n    if( nSrc==0 ){\n      nSrc = nData;\n      pSrc = pData;\n    }\n  }\n  releasePage(pToRelease);\n  return SQLITE_OK;\n}\n\n/*\n** Remove the i-th cell from pPage.  This routine effects pPage only.\n** The cell content is not freed or deallocated.  It is assumed that\n** the cell content has been copied someplace else.  This routine just\n** removes the reference to the cell from pPage.\n**\n** \"sz\" must be the number of bytes in the cell.\n*/\nstatic void dropCell(MemPage *pPage, int idx, int sz, int *pRC){\n  u32 pc;         /* Offset to cell content of cell being deleted */\n  u8 *data;       /* pPage->aData */\n  u8 *ptr;        /* Used to move bytes around within data[] */\n  u8 *endPtr;     /* End of loop */\n  int rc;         /* The return code */\n  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */\n\n  if( *pRC ) return;\n\n  assert( idx>=0 && idx<pPage->nCell );\n  assert( sz==cellSize(pPage, idx) );\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  data = pPage->aData;\n  ptr = &pPage->aCellIdx[2*idx];\n  pc = get2byte(ptr);\n  hdr = pPage->hdrOffset;\n  testcase( pc==get2byte(&data[hdr+5]) );\n  testcase( pc+sz==pPage->pBt->usableSize );\n  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){\n    *pRC = SQLITE_CORRUPT_BKPT;\n    return;\n  }\n  rc = freeSpace(pPage, pc, sz);\n  if( rc ){\n    *pRC = rc;\n    return;\n  }\n  endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];\n  assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */\n  while( ptr<endPtr ){\n    *(u16*)ptr = *(u16*)&ptr[2];\n    ptr += 2;\n  }\n  pPage->nCell--;\n  put2byte(&data[hdr+3], pPage->nCell);\n  pPage->nFree += 2;\n}\n\n/*\n** Insert a new cell on pPage at cell index \"i\".  pCell points to the\n** content of the cell.\n**\n** If the cell content will fit on the page, then put it there.  If it\n** will not fit, then make a copy of the cell content into pTemp if\n** pTemp is not null.  Regardless of pTemp, allocate a new entry\n** in pPage->apOvfl[] and make it point to the cell content (either\n** in pTemp or the original pCell) and also record its index. \n** Allocating a new entry in pPage->aCell[] implies that \n** pPage->nOverflow is incremented.\n**\n** If nSkip is non-zero, then do not copy the first nSkip bytes of the\n** cell. The caller will overwrite them after this function returns. If\n** nSkip is non-zero, then pCell may not point to an invalid memory location \n** (but pCell+nSkip is always valid).\n*/\nstatic void insertCell(\n  MemPage *pPage,   /* Page into which we are copying */\n  int i,            /* New cell becomes the i-th cell of the page */\n  u8 *pCell,        /* Content of the new cell */\n  int sz,           /* Bytes of content in pCell */\n  u8 *pTemp,        /* Temp storage space for pCell, if needed */\n  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */\n  int *pRC          /* Read and write return code from here */\n){\n  int idx = 0;      /* Where to write new cell content in data[] */\n  int j;            /* Loop counter */\n  int end;          /* First byte past the last cell pointer in data[] */\n  int ins;          /* Index in data[] where new cell pointer is inserted */\n  int cellOffset;   /* Address of first cell pointer in data[] */\n  u8 *data;         /* The content of the whole page */\n  u8 *ptr;          /* Used for moving information around in data[] */\n  u8 *endPtr;       /* End of the loop */\n\n  int nSkip = (iChild ? 4 : 0);\n\n  if( *pRC ) return;\n\n  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );\n  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );\n  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );\n  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  /* The cell should normally be sized correctly.  However, when moving a\n  ** malformed cell from a leaf page to an interior page, if the cell size\n  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size\n  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence\n  ** the term after the || in the following assert(). */\n  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );\n  if( pPage->nOverflow || sz+2>pPage->nFree ){\n    if( pTemp ){\n      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);\n      pCell = pTemp;\n    }\n    if( iChild ){\n      put4byte(pCell, iChild);\n    }\n    j = pPage->nOverflow++;\n    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );\n    pPage->apOvfl[j] = pCell;\n    pPage->aiOvfl[j] = (u16)i;\n  }else{\n    int rc = sqlite3PagerWrite(pPage->pDbPage);\n    if( rc!=SQLITE_OK ){\n      *pRC = rc;\n      return;\n    }\n    assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n    data = pPage->aData;\n    cellOffset = pPage->cellOffset;\n    end = cellOffset + 2*pPage->nCell;\n    ins = cellOffset + 2*i;\n    rc = allocateSpace(pPage, sz, &idx);\n    if( rc ){ *pRC = rc; return; }\n    /* The allocateSpace() routine guarantees the following two properties\n    ** if it returns success */\n    assert( idx >= end+2 );\n    assert( idx+sz <= (int)pPage->pBt->usableSize );\n    pPage->nCell++;\n    pPage->nFree -= (u16)(2 + sz);\n    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);\n    if( iChild ){\n      put4byte(&data[idx], iChild);\n    }\n    ptr = &data[end];\n    endPtr = &data[ins];\n    assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */\n    while( ptr>endPtr ){\n      *(u16*)ptr = *(u16*)&ptr[-2];\n      ptr -= 2;\n    }\n    put2byte(&data[ins], idx);\n    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pPage->pBt->autoVacuum ){\n      /* The cell may contain a pointer to an overflow page. If so, write\n      ** the entry for the overflow page into the pointer map.\n      */\n      ptrmapPutOvflPtr(pPage, pCell, pRC);\n    }\n#endif\n  }\n}\n\n/*\n** Add a list of cells to a page.  The page should be initially empty.\n** The cells are guaranteed to fit on the page.\n*/\nstatic void assemblePage(\n  MemPage *pPage,   /* The page to be assemblied */\n  int nCell,        /* The number of cells to add to this page */\n  u8 **apCell,      /* Pointers to cell bodies */\n  u16 *aSize        /* Sizes of the cells */\n){\n  int i;            /* Loop counter */\n  u8 *pCellptr;     /* Address of next cell pointer */\n  int cellbody;     /* Address of next cell body */\n  u8 * const data = pPage->aData;             /* Pointer to data for pPage */\n  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */\n  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */\n\n  assert( pPage->nOverflow==0 );\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)\n            && (int)MX_CELL(pPage->pBt)<=10921);\n  assert( sqlite3PagerIswriteable(pPage->pDbPage) );\n\n  /* Check that the page has just been zeroed by zeroPage() */\n  assert( pPage->nCell==0 );\n  assert( get2byteNotZero(&data[hdr+5])==nUsable );\n\n  pCellptr = &pPage->aCellIdx[nCell*2];\n  cellbody = nUsable;\n  for(i=nCell-1; i>=0; i--){\n    u16 sz = aSize[i];\n    pCellptr -= 2;\n    cellbody -= sz;\n    put2byte(pCellptr, cellbody);\n    memcpy(&data[cellbody], apCell[i], sz);\n  }\n  put2byte(&data[hdr+3], nCell);\n  put2byte(&data[hdr+5], cellbody);\n  pPage->nFree -= (nCell*2 + nUsable - cellbody);\n  pPage->nCell = (u16)nCell;\n}\n\n/*\n** The following parameters determine how many adjacent pages get involved\n** in a balancing operation.  NN is the number of neighbors on either side\n** of the page that participate in the balancing operation.  NB is the\n** total number of pages that participate, including the target page and\n** NN neighbors on either side.\n**\n** The minimum value of NN is 1 (of course).  Increasing NN above 1\n** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance\n** in exchange for a larger degradation in INSERT and UPDATE performance.\n** The value of NN appears to give the best results overall.\n*/\n#define NN 1             /* Number of neighbors on either side of pPage */\n#define NB (NN*2+1)      /* Total pages involved in the balance */\n\n\n#ifndef SQLITE_OMIT_QUICKBALANCE\n/*\n** This version of balance() handles the common special case where\n** a new entry is being inserted on the extreme right-end of the\n** tree, in other words, when the new entry will become the largest\n** entry in the tree.\n**\n** Instead of trying to balance the 3 right-most leaf pages, just add\n** a new page to the right-hand side and put the one new entry in\n** that page.  This leaves the right side of the tree somewhat\n** unbalanced.  But odds are that we will be inserting new entries\n** at the end soon afterwards so the nearly empty page will quickly\n** fill up.  On average.\n**\n** pPage is the leaf page which is the right-most page in the tree.\n** pParent is its parent.  pPage must have a single overflow entry\n** which is also the right-most entry on the page.\n**\n** The pSpace buffer is used to store a temporary copy of the divider\n** cell that will be inserted into pParent. Such a cell consists of a 4\n** byte page number followed by a variable length integer. In other\n** words, at most 13 bytes. Hence the pSpace buffer must be at\n** least 13 bytes in size.\n*/\nstatic int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){\n  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */\n  MemPage *pNew;                       /* Newly allocated page */\n  int rc;                              /* Return Code */\n  Pgno pgnoNew;                        /* Page number of pNew */\n\n  assert( sqlite3_mutex_held(pPage->pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n  assert( pPage->nOverflow==1 );\n\n  /* This error condition is now caught prior to reaching this function */\n  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;\n\n  /* Allocate a new page. This page will become the right-sibling of \n  ** pPage. Make the parent page writable, so that the new divider cell\n  ** may be inserted. If both these operations are successful, proceed.\n  */\n  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);\n\n  if( rc==SQLITE_OK ){\n\n    u8 *pOut = &pSpace[4];\n    u8 *pCell = pPage->apOvfl[0];\n    u16 szCell = cellSizePtr(pPage, pCell);\n    u8 *pStop;\n\n    assert( sqlite3PagerIswriteable(pNew->pDbPage) );\n    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );\n    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);\n    assemblePage(pNew, 1, &pCell, &szCell);\n\n    /* If this is an auto-vacuum database, update the pointer map\n    ** with entries for the new page, and any pointer from the \n    ** cell on the page to an overflow page. If either of these\n    ** operations fails, the return code is set, but the contents\n    ** of the parent page are still manipulated by thh code below.\n    ** That is Ok, at this point the parent page is guaranteed to\n    ** be marked as dirty. Returning an error code will cause a\n    ** rollback, undoing any changes made to the parent page.\n    */\n    if( ISAUTOVACUUM ){\n      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);\n      if( szCell>pNew->minLocal ){\n        ptrmapPutOvflPtr(pNew, pCell, &rc);\n      }\n    }\n  \n    /* Create a divider cell to insert into pParent. The divider cell\n    ** consists of a 4-byte page number (the page number of pPage) and\n    ** a variable length key value (which must be the same value as the\n    ** largest key on pPage).\n    **\n    ** To find the largest key value on pPage, first find the right-most \n    ** cell on pPage. The first two fields of this cell are the \n    ** record-length (a variable length integer at most 32-bits in size)\n    ** and the key value (a variable length integer, may have any value).\n    ** The first of the while(...) loops below skips over the record-length\n    ** field. The second while(...) loop copies the key value from the\n    ** cell on pPage into the pSpace buffer.\n    */\n    pCell = findCell(pPage, pPage->nCell-1);\n    pStop = &pCell[9];\n    while( (*(pCell++)&0x80) && pCell<pStop );\n    pStop = &pCell[9];\n    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );\n\n    /* Insert the new divider cell into pParent. */\n    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),\n               0, pPage->pgno, &rc);\n\n    /* Set the right-child pointer of pParent to point to the new page. */\n    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);\n  \n    /* Release the reference to the new page. */\n    releasePage(pNew);\n  }\n\n  return rc;\n}\n#endif /* SQLITE_OMIT_QUICKBALANCE */\n\n#if 0\n/*\n** This function does not contribute anything to the operation of SQLite.\n** it is sometimes activated temporarily while debugging code responsible \n** for setting pointer-map entries.\n*/\nstatic int ptrmapCheckPages(MemPage **apPage, int nPage){\n  int i, j;\n  for(i=0; i<nPage; i++){\n    Pgno n;\n    u8 e;\n    MemPage *pPage = apPage[i];\n    BtShared *pBt = pPage->pBt;\n    assert( pPage->isInit );\n\n    for(j=0; j<pPage->nCell; j++){\n      CellInfo info;\n      u8 *z;\n     \n      z = findCell(pPage, j);\n      btreeParseCellPtr(pPage, z, &info);\n      if( info.iOverflow ){\n        Pgno ovfl = get4byte(&z[info.iOverflow]);\n        ptrmapGet(pBt, ovfl, &e, &n);\n        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );\n      }\n      if( !pPage->leaf ){\n        Pgno child = get4byte(z);\n        ptrmapGet(pBt, child, &e, &n);\n        assert( n==pPage->pgno && e==PTRMAP_BTREE );\n      }\n    }\n    if( !pPage->leaf ){\n      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n      ptrmapGet(pBt, child, &e, &n);\n      assert( n==pPage->pgno && e==PTRMAP_BTREE );\n    }\n  }\n  return 1;\n}\n#endif\n\n/*\n** This function is used to copy the contents of the b-tree node stored \n** on page pFrom to page pTo. If page pFrom was not a leaf page, then\n** the pointer-map entries for each child page are updated so that the\n** parent page stored in the pointer map is page pTo. If pFrom contained\n** any cells with overflow page pointers, then the corresponding pointer\n** map entries are also updated so that the parent page is page pTo.\n**\n** If pFrom is currently carrying any overflow cells (entries in the\n** MemPage.apOvfl[] array), they are not copied to pTo. \n**\n** Before returning, page pTo is reinitialized using btreeInitPage().\n**\n** The performance of this function is not critical. It is only used by \n** the balance_shallower() and balance_deeper() procedures, neither of\n** which are called often under normal circumstances.\n*/\nstatic void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){\n  if( (*pRC)==SQLITE_OK ){\n    BtShared * const pBt = pFrom->pBt;\n    u8 * const aFrom = pFrom->aData;\n    u8 * const aTo = pTo->aData;\n    int const iFromHdr = pFrom->hdrOffset;\n    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);\n    int rc;\n    int iData;\n  \n  \n    assert( pFrom->isInit );\n    assert( pFrom->nFree>=iToHdr );\n    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );\n  \n    /* Copy the b-tree node content from page pFrom to page pTo. */\n    iData = get2byte(&aFrom[iFromHdr+5]);\n    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);\n    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);\n  \n    /* Reinitialize page pTo so that the contents of the MemPage structure\n    ** match the new data. The initialization of pTo can actually fail under\n    ** fairly obscure circumstances, even though it is a copy of initialized \n    ** page pFrom.\n    */\n    pTo->isInit = 0;\n    rc = btreeInitPage(pTo);\n    if( rc!=SQLITE_OK ){\n      *pRC = rc;\n      return;\n    }\n  \n    /* If this is an auto-vacuum database, update the pointer-map entries\n    ** for any b-tree or overflow pages that pTo now contains the pointers to.\n    */\n    if( ISAUTOVACUUM ){\n      *pRC = setChildPtrmaps(pTo);\n    }\n  }\n}\n\n/*\n** This routine redistributes cells on the iParentIdx'th child of pParent\n** (hereafter \"the page\") and up to 2 siblings so that all pages have about the\n** same amount of free space. Usually a single sibling on either side of the\n** page are used in the balancing, though both siblings might come from one\n** side if the page is the first or last child of its parent. If the page \n** has fewer than 2 siblings (something which can only happen if the page\n** is a root page or a child of a root page) then all available siblings\n** participate in the balancing.\n**\n** The number of siblings of the page might be increased or decreased by \n** one or two in an effort to keep pages nearly full but not over full. \n**\n** Note that when this routine is called, some of the cells on the page\n** might not actually be stored in MemPage.aData[]. This can happen\n** if the page is overfull. This routine ensures that all cells allocated\n** to the page and its siblings fit into MemPage.aData[] before returning.\n**\n** In the course of balancing the page and its siblings, cells may be\n** inserted into or removed from the parent page (pParent). Doing so\n** may cause the parent page to become overfull or underfull. If this\n** happens, it is the responsibility of the caller to invoke the correct\n** balancing routine to fix this problem (see the balance() routine). \n**\n** If this routine fails for any reason, it might leave the database\n** in a corrupted state. So if this routine fails, the database should\n** be rolled back.\n**\n** The third argument to this function, aOvflSpace, is a pointer to a\n** buffer big enough to hold one page. If while inserting cells into the parent\n** page (pParent) the parent page becomes overfull, this buffer is\n** used to store the parent's overflow cells. Because this function inserts\n** a maximum of four divider cells into the parent page, and the maximum\n** size of a cell stored within an internal node is always less than 1/4\n** of the page-size, the aOvflSpace[] buffer is guaranteed to be large\n** enough for all overflow cells.\n**\n** If aOvflSpace is set to a null pointer, this function returns \n** SQLITE_NOMEM.\n*/\n#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)\n#pragma optimize(\"\", off)\n#endif\nstatic int balance_nonroot(\n  MemPage *pParent,               /* Parent page of siblings being balanced */\n  int iParentIdx,                 /* Index of \"the page\" in pParent */\n  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */\n  int isRoot,                     /* True if pParent is a root-page */\n  int bBulk                       /* True if this call is part of a bulk load */\n){\n  BtShared *pBt;               /* The whole database */\n  int nCell = 0;               /* Number of cells in apCell[] */\n  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */\n  int nNew = 0;                /* Number of pages in apNew[] */\n  int nOld;                    /* Number of pages in apOld[] */\n  int i, j, k;                 /* Loop counters */\n  int nxDiv;                   /* Next divider slot in pParent->aCell[] */\n  int rc = SQLITE_OK;          /* The return code */\n  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */\n  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */\n  int usableSpace;             /* Bytes in pPage beyond the header */\n  int pageFlags;               /* Value of pPage->aData[0] */\n  int subtotal;                /* Subtotal of bytes in cells on one page */\n  int iSpace1 = 0;             /* First unused byte of aSpace1[] */\n  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */\n  int szScratch;               /* Size of scratch memory requested */\n  MemPage *apOld[NB];          /* pPage and up to two siblings */\n  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */\n  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */\n  u8 *pRight;                  /* Location in parent of right-sibling pointer */\n  u8 *apDiv[NB-1];             /* Divider cells in pParent */\n  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */\n  int szNew[NB+2];             /* Combined size of cells place on i-th page */\n  u8 **apCell = 0;             /* All cells begin balanced */\n  u16 *szCell;                 /* Local size of all cells in apCell[] */\n  u8 *aSpace1;                 /* Space for copies of dividers cells */\n  Pgno pgno;                   /* Temp var to store a page number in */\n\n  pBt = pParent->pBt;\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n\n#if 0\n  TRACE((\"BALANCE: begin page %d child of %d\\n\", pPage->pgno, pParent->pgno));\n#endif\n\n  /* At this point pParent may have at most one overflow cell. And if\n  ** this overflow cell is present, it must be the cell with \n  ** index iParentIdx. This scenario comes about when this function\n  ** is called (indirectly) from sqlite3BtreeDelete().\n  */\n  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );\n  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );\n\n  if( !aOvflSpace ){\n    return SQLITE_NOMEM;\n  }\n\n  /* Find the sibling pages to balance. Also locate the cells in pParent \n  ** that divide the siblings. An attempt is made to find NN siblings on \n  ** either side of pPage. More siblings are taken from one side, however, \n  ** if there are fewer than NN siblings on the other side. If pParent\n  ** has NB or fewer children then all children of pParent are taken.  \n  **\n  ** This loop also drops the divider cells from the parent page. This\n  ** way, the remainder of the function does not have to deal with any\n  ** overflow cells in the parent page, since if any existed they will\n  ** have already been removed.\n  */\n  i = pParent->nOverflow + pParent->nCell;\n  if( i<2 ){\n    nxDiv = 0;\n  }else{\n    assert( bBulk==0 || bBulk==1 );\n    if( iParentIdx==0 ){                 \n      nxDiv = 0;\n    }else if( iParentIdx==i ){\n      nxDiv = i-2+bBulk;\n    }else{\n      assert( bBulk==0 );\n      nxDiv = iParentIdx-1;\n    }\n    i = 2-bBulk;\n  }\n  nOld = i+1;\n  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){\n    pRight = &pParent->aData[pParent->hdrOffset+8];\n  }else{\n    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);\n  }\n  pgno = get4byte(pRight);\n  while( 1 ){\n    rc = getAndInitPage(pBt, pgno, &apOld[i]);\n    if( rc ){\n      memset(apOld, 0, (i+1)*sizeof(MemPage*));\n      goto balance_cleanup;\n    }\n    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;\n    if( (i--)==0 ) break;\n\n    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){\n      apDiv[i] = pParent->apOvfl[0];\n      pgno = get4byte(apDiv[i]);\n      szNew[i] = cellSizePtr(pParent, apDiv[i]);\n      pParent->nOverflow = 0;\n    }else{\n      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);\n      pgno = get4byte(apDiv[i]);\n      szNew[i] = cellSizePtr(pParent, apDiv[i]);\n\n      /* Drop the cell from the parent page. apDiv[i] still points to\n      ** the cell within the parent, even though it has been dropped.\n      ** This is safe because dropping a cell only overwrites the first\n      ** four bytes of it, and this function does not need the first\n      ** four bytes of the divider cell. So the pointer is safe to use\n      ** later on.  \n      **\n      ** But not if we are in secure-delete mode. In secure-delete mode,\n      ** the dropCell() routine will overwrite the entire cell with zeroes.\n      ** In this case, temporarily copy the cell into the aOvflSpace[]\n      ** buffer. It will be copied out again as soon as the aSpace[] buffer\n      ** is allocated.  */\n      if( pBt->btsFlags & BTS_SECURE_DELETE ){\n        int iOff;\n\n        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);\n        if( (iOff+szNew[i])>(int)pBt->usableSize ){\n          rc = SQLITE_CORRUPT_BKPT;\n          memset(apOld, 0, (i+1)*sizeof(MemPage*));\n          goto balance_cleanup;\n        }else{\n          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);\n          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];\n        }\n      }\n      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);\n    }\n  }\n\n  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte\n  ** alignment */\n  nMaxCells = (nMaxCells + 3)&~3;\n\n  /*\n  ** Allocate space for memory structures\n  */\n  k = pBt->pageSize + ROUND8(sizeof(MemPage));\n  szScratch =\n       nMaxCells*sizeof(u8*)                       /* apCell */\n     + nMaxCells*sizeof(u16)                       /* szCell */\n     + pBt->pageSize                               /* aSpace1 */\n     + k*nOld;                                     /* Page copies (apCopy) */\n  apCell = sqlite3ScratchMalloc( szScratch ); \n  if( apCell==0 ){\n    rc = SQLITE_NOMEM;\n    goto balance_cleanup;\n  }\n  szCell = (u16*)&apCell[nMaxCells];\n  aSpace1 = (u8*)&szCell[nMaxCells];\n  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );\n\n  /*\n  ** Load pointers to all cells on sibling pages and the divider cells\n  ** into the local apCell[] array.  Make copies of the divider cells\n  ** into space obtained from aSpace1[] and remove the divider cells\n  ** from pParent.\n  **\n  ** If the siblings are on leaf pages, then the child pointers of the\n  ** divider cells are stripped from the cells before they are copied\n  ** into aSpace1[].  In this way, all cells in apCell[] are without\n  ** child pointers.  If siblings are not leaves, then all cell in\n  ** apCell[] include child pointers.  Either way, all cells in apCell[]\n  ** are alike.\n  **\n  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.\n  **       leafData:  1 if pPage holds key+data and pParent holds only keys.\n  */\n  leafCorrection = apOld[0]->leaf*4;\n  leafData = apOld[0]->hasData;\n  for(i=0; i<nOld; i++){\n    int limit;\n    \n    /* Before doing anything else, take a copy of the i'th original sibling\n    ** The rest of this function will use data from the copies rather\n    ** that the original pages since the original pages will be in the\n    ** process of being overwritten.  */\n    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];\n    memcpy(pOld, apOld[i], sizeof(MemPage));\n    pOld->aData = (void*)&pOld[1];\n    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);\n\n    limit = pOld->nCell+pOld->nOverflow;\n    if( pOld->nOverflow>0 ){\n      for(j=0; j<limit; j++){\n        assert( nCell<nMaxCells );\n        apCell[nCell] = findOverflowCell(pOld, j);\n        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);\n        nCell++;\n      }\n    }else{\n      u8 *aData = pOld->aData;\n      u16 maskPage = pOld->maskPage;\n      u16 cellOffset = pOld->cellOffset;\n      for(j=0; j<limit; j++){\n        assert( nCell<nMaxCells );\n        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);\n        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);\n        nCell++;\n      }\n    }       \n    if( i<nOld-1 && !leafData){\n      u16 sz = (u16)szNew[i];\n      u8 *pTemp;\n      assert( nCell<nMaxCells );\n      szCell[nCell] = sz;\n      pTemp = &aSpace1[iSpace1];\n      iSpace1 += sz;\n      assert( sz<=pBt->maxLocal+23 );\n      assert( iSpace1 <= (int)pBt->pageSize );\n      memcpy(pTemp, apDiv[i], sz);\n      apCell[nCell] = pTemp+leafCorrection;\n      assert( leafCorrection==0 || leafCorrection==4 );\n      szCell[nCell] = szCell[nCell] - leafCorrection;\n      if( !pOld->leaf ){\n        assert( leafCorrection==0 );\n        assert( pOld->hdrOffset==0 );\n        /* The right pointer of the child page pOld becomes the left\n        ** pointer of the divider cell */\n        memcpy(apCell[nCell], &pOld->aData[8], 4);\n      }else{\n        assert( leafCorrection==4 );\n        if( szCell[nCell]<4 ){\n          /* Do not allow any cells smaller than 4 bytes. */\n          szCell[nCell] = 4;\n        }\n      }\n      nCell++;\n    }\n  }\n\n  /*\n  ** Figure out the number of pages needed to hold all nCell cells.\n  ** Store this number in \"k\".  Also compute szNew[] which is the total\n  ** size of all cells on the i-th page and cntNew[] which is the index\n  ** in apCell[] of the cell that divides page i from page i+1.  \n  ** cntNew[k] should equal nCell.\n  **\n  ** Values computed by this block:\n  **\n  **           k: The total number of sibling pages\n  **    szNew[i]: Spaced used on the i-th sibling page.\n  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to\n  **              the right of the i-th sibling page.\n  ** usableSpace: Number of bytes of space available on each sibling.\n  ** \n  */\n  usableSpace = pBt->usableSize - 12 + leafCorrection;\n  for(subtotal=k=i=0; i<nCell; i++){\n    assert( i<nMaxCells );\n    subtotal += szCell[i] + 2;\n    if( subtotal > usableSpace ){\n      szNew[k] = subtotal - szCell[i];\n      cntNew[k] = i;\n      if( leafData ){ i--; }\n      subtotal = 0;\n      k++;\n      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }\n    }\n  }\n  szNew[k] = subtotal;\n  cntNew[k] = nCell;\n  k++;\n\n  /*\n  ** The packing computed by the previous block is biased toward the siblings\n  ** on the left side.  The left siblings are always nearly full, while the\n  ** right-most sibling might be nearly empty.  This block of code attempts\n  ** to adjust the packing of siblings to get a better balance.\n  **\n  ** This adjustment is more than an optimization.  The packing above might\n  ** be so out of balance as to be illegal.  For example, the right-most\n  ** sibling might be completely empty.  This adjustment is not optional.\n  */\n  for(i=k-1; i>0; i--){\n    int szRight = szNew[i];  /* Size of sibling on the right */\n    int szLeft = szNew[i-1]; /* Size of sibling on the left */\n    int r;              /* Index of right-most cell in left sibling */\n    int d;              /* Index of first cell to the left of right sibling */\n\n    r = cntNew[i-1] - 1;\n    d = r + 1 - leafData;\n    assert( d<nMaxCells );\n    assert( r<nMaxCells );\n    while( szRight==0 \n       || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) \n    ){\n      szRight += szCell[d] + 2;\n      szLeft -= szCell[r] + 2;\n      cntNew[i-1]--;\n      r = cntNew[i-1] - 1;\n      d = r + 1 - leafData;\n    }\n    szNew[i] = szRight;\n    szNew[i-1] = szLeft;\n  }\n\n  /* Either we found one or more cells (cntnew[0])>0) or pPage is\n  ** a virtual root page.  A virtual root page is when the real root\n  ** page is page 1 and we are the only child of that page.\n  **\n  ** UPDATE:  The assert() below is not necessarily true if the database\n  ** file is corrupt.  The corruption will be detected and reported later\n  ** in this procedure so there is no need to act upon it now.\n  */\n#if 0\n  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );\n#endif\n\n  TRACE((\"BALANCE: old: %d %d %d  \",\n    apOld[0]->pgno, \n    nOld>=2 ? apOld[1]->pgno : 0,\n    nOld>=3 ? apOld[2]->pgno : 0\n  ));\n\n  /*\n  ** Allocate k new pages.  Reuse old pages where possible.\n  */\n  if( apOld[0]->pgno<=1 ){\n    rc = SQLITE_CORRUPT_BKPT;\n    goto balance_cleanup;\n  }\n  pageFlags = apOld[0]->aData[0];\n  for(i=0; i<k; i++){\n    MemPage *pNew;\n    if( i<nOld ){\n      pNew = apNew[i] = apOld[i];\n      apOld[i] = 0;\n      rc = sqlite3PagerWrite(pNew->pDbPage);\n      nNew++;\n      if( rc ) goto balance_cleanup;\n    }else{\n      assert( i>0 );\n      rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);\n      if( rc ) goto balance_cleanup;\n      apNew[i] = pNew;\n      nNew++;\n\n      /* Set the pointer-map entry for the new sibling page. */\n      if( ISAUTOVACUUM ){\n        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);\n        if( rc!=SQLITE_OK ){\n          goto balance_cleanup;\n        }\n      }\n    }\n  }\n\n  /* Free any old pages that were not reused as new pages.\n  */\n  while( i<nOld ){\n    freePage(apOld[i], &rc);\n    if( rc ) goto balance_cleanup;\n    releasePage(apOld[i]);\n    apOld[i] = 0;\n    i++;\n  }\n\n  /*\n  ** Put the new pages in accending order.  This helps to\n  ** keep entries in the disk file in order so that a scan\n  ** of the table is a linear scan through the file.  That\n  ** in turn helps the operating system to deliver pages\n  ** from the disk more rapidly.\n  **\n  ** An O(n^2) insertion sort algorithm is used, but since\n  ** n is never more than NB (a small constant), that should\n  ** not be a problem.\n  **\n  ** When NB==3, this one optimization makes the database\n  ** about 25% faster for large insertions and deletions.\n  */\n  for(i=0; i<k-1; i++){\n    int minV = apNew[i]->pgno;\n    int minI = i;\n    for(j=i+1; j<k; j++){\n      if( apNew[j]->pgno<(unsigned)minV ){\n        minI = j;\n        minV = apNew[j]->pgno;\n      }\n    }\n    if( minI>i ){\n      MemPage *pT;\n      pT = apNew[i];\n      apNew[i] = apNew[minI];\n      apNew[minI] = pT;\n    }\n  }\n  TRACE((\"new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\\n\",\n    apNew[0]->pgno, szNew[0],\n    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,\n    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,\n    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,\n    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));\n\n  assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n  put4byte(pRight, apNew[nNew-1]->pgno);\n\n  /*\n  ** Evenly distribute the data in apCell[] across the new pages.\n  ** Insert divider cells into pParent as necessary.\n  */\n  j = 0;\n  for(i=0; i<nNew; i++){\n    /* Assemble the new sibling page. */\n    MemPage *pNew = apNew[i];\n    assert( j<nMaxCells );\n    zeroPage(pNew, pageFlags);\n    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);\n    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );\n    assert( pNew->nOverflow==0 );\n\n    j = cntNew[i];\n\n    /* If the sibling page assembled above was not the right-most sibling,\n    ** insert a divider cell into the parent page.\n    */\n    assert( i<nNew-1 || j==nCell );\n    if( j<nCell ){\n      u8 *pCell;\n      u8 *pTemp;\n      int sz;\n\n      assert( j<nMaxCells );\n      pCell = apCell[j];\n      sz = szCell[j] + leafCorrection;\n      pTemp = &aOvflSpace[iOvflSpace];\n      if( !pNew->leaf ){\n        memcpy(&pNew->aData[8], pCell, 4);\n      }else if( leafData ){\n        /* If the tree is a leaf-data tree, and the siblings are leaves, \n        ** then there is no divider cell in apCell[]. Instead, the divider \n        ** cell consists of the integer key for the right-most cell of \n        ** the sibling-page assembled above only.\n        */\n        CellInfo info;\n        j--;\n        btreeParseCellPtr(pNew, apCell[j], &info);\n        pCell = pTemp;\n        sz = 4 + putVarint(&pCell[4], info.nKey);\n        pTemp = 0;\n      }else{\n        pCell -= 4;\n        /* Obscure case for non-leaf-data trees: If the cell at pCell was\n        ** previously stored on a leaf node, and its reported size was 4\n        ** bytes, then it may actually be smaller than this \n        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of\n        ** any cell). But it is important to pass the correct size to \n        ** insertCell(), so reparse the cell now.\n        **\n        ** Note that this can never happen in an SQLite data file, as all\n        ** cells are at least 4 bytes. It only happens in b-trees used\n        ** to evaluate \"IN (SELECT ...)\" and similar clauses.\n        */\n        if( szCell[j]==4 ){\n          assert(leafCorrection==4);\n          sz = cellSizePtr(pParent, pCell);\n        }\n      }\n      iOvflSpace += sz;\n      assert( sz<=pBt->maxLocal+23 );\n      assert( iOvflSpace <= (int)pBt->pageSize );\n      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);\n      if( rc!=SQLITE_OK ) goto balance_cleanup;\n      assert( sqlite3PagerIswriteable(pParent->pDbPage) );\n\n      j++;\n      nxDiv++;\n    }\n  }\n  assert( j==nCell );\n  assert( nOld>0 );\n  assert( nNew>0 );\n  if( (pageFlags & PTF_LEAF)==0 ){\n    u8 *zChild = &apCopy[nOld-1]->aData[8];\n    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);\n  }\n\n  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){\n    /* The root page of the b-tree now contains no cells. The only sibling\n    ** page is the right-child of the parent. Copy the contents of the\n    ** child page into the parent, decreasing the overall height of the\n    ** b-tree structure by one. This is described as the \"balance-shallower\"\n    ** sub-algorithm in some documentation.\n    **\n    ** If this is an auto-vacuum database, the call to copyNodeContent() \n    ** sets all pointer-map entries corresponding to database image pages \n    ** for which the pointer is stored within the content being copied.\n    **\n    ** The second assert below verifies that the child page is defragmented\n    ** (it must be, as it was just reconstructed using assemblePage()). This\n    ** is important if the parent page happens to be page 1 of the database\n    ** image.  */\n    assert( nNew==1 );\n    assert( apNew[0]->nFree == \n        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) \n    );\n    copyNodeContent(apNew[0], pParent, &rc);\n    freePage(apNew[0], &rc);\n  }else if( ISAUTOVACUUM ){\n    /* Fix the pointer-map entries for all the cells that were shifted around. \n    ** There are several different types of pointer-map entries that need to\n    ** be dealt with by this routine. Some of these have been set already, but\n    ** many have not. The following is a summary:\n    **\n    **   1) The entries associated with new sibling pages that were not\n    **      siblings when this function was called. These have already\n    **      been set. We don't need to worry about old siblings that were\n    **      moved to the free-list - the freePage() code has taken care\n    **      of those.\n    **\n    **   2) The pointer-map entries associated with the first overflow\n    **      page in any overflow chains used by new divider cells. These \n    **      have also already been taken care of by the insertCell() code.\n    **\n    **   3) If the sibling pages are not leaves, then the child pages of\n    **      cells stored on the sibling pages may need to be updated.\n    **\n    **   4) If the sibling pages are not internal intkey nodes, then any\n    **      overflow pages used by these cells may need to be updated\n    **      (internal intkey nodes never contain pointers to overflow pages).\n    **\n    **   5) If the sibling pages are not leaves, then the pointer-map\n    **      entries for the right-child pages of each sibling may need\n    **      to be updated.\n    **\n    ** Cases 1 and 2 are dealt with above by other code. The next\n    ** block deals with cases 3 and 4 and the one after that, case 5. Since\n    ** setting a pointer map entry is a relatively expensive operation, this\n    ** code only sets pointer map entries for child or overflow pages that have\n    ** actually moved between pages.  */\n    MemPage *pNew = apNew[0];\n    MemPage *pOld = apCopy[0];\n    int nOverflow = pOld->nOverflow;\n    int iNextOld = pOld->nCell + nOverflow;\n    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);\n    j = 0;                             /* Current 'old' sibling page */\n    k = 0;                             /* Current 'new' sibling page */\n    for(i=0; i<nCell; i++){\n      int isDivider = 0;\n      while( i==iNextOld ){\n        /* Cell i is the cell immediately following the last cell on old\n        ** sibling page j. If the siblings are not leaf pages of an\n        ** intkey b-tree, then cell i was a divider cell. */\n        assert( j+1 < ArraySize(apCopy) );\n        assert( j+1 < nOld );\n        pOld = apCopy[++j];\n        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;\n        if( pOld->nOverflow ){\n          nOverflow = pOld->nOverflow;\n          iOverflow = i + !leafData + pOld->aiOvfl[0];\n        }\n        isDivider = !leafData;  \n      }\n\n      assert(nOverflow>0 || iOverflow<i );\n      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);\n      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);\n      if( i==iOverflow ){\n        isDivider = 1;\n        if( (--nOverflow)>0 ){\n          iOverflow++;\n        }\n      }\n\n      if( i==cntNew[k] ){\n        /* Cell i is the cell immediately following the last cell on new\n        ** sibling page k. If the siblings are not leaf pages of an\n        ** intkey b-tree, then cell i is a divider cell.  */\n        pNew = apNew[++k];\n        if( !leafData ) continue;\n      }\n      assert( j<nOld );\n      assert( k<nNew );\n\n      /* If the cell was originally divider cell (and is not now) or\n      ** an overflow cell, or if the cell was located on a different sibling\n      ** page before the balancing, then the pointer map entries associated\n      ** with any child or overflow pages need to be updated.  */\n      if( isDivider || pOld->pgno!=pNew->pgno ){\n        if( !leafCorrection ){\n          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);\n        }\n        if( szCell[i]>pNew->minLocal ){\n          ptrmapPutOvflPtr(pNew, apCell[i], &rc);\n        }\n      }\n    }\n\n    if( !leafCorrection ){\n      for(i=0; i<nNew; i++){\n        u32 key = get4byte(&apNew[i]->aData[8]);\n        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);\n      }\n    }\n\n#if 0\n    /* The ptrmapCheckPages() contains assert() statements that verify that\n    ** all pointer map pages are set correctly. This is helpful while \n    ** debugging. This is usually disabled because a corrupt database may\n    ** cause an assert() statement to fail.  */\n    ptrmapCheckPages(apNew, nNew);\n    ptrmapCheckPages(&pParent, 1);\n#endif\n  }\n\n  assert( pParent->isInit );\n  TRACE((\"BALANCE: finished: old=%d new=%d cells=%d\\n\",\n          nOld, nNew, nCell));\n\n  /*\n  ** Cleanup before returning.\n  */\nbalance_cleanup:\n  sqlite3ScratchFree(apCell);\n  for(i=0; i<nOld; i++){\n    releasePage(apOld[i]);\n  }\n  for(i=0; i<nNew; i++){\n    releasePage(apNew[i]);\n  }\n\n  return rc;\n}\n#if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)\n#pragma optimize(\"\", on)\n#endif\n\n\n/*\n** This function is called when the root page of a b-tree structure is\n** overfull (has one or more overflow pages).\n**\n** A new child page is allocated and the contents of the current root\n** page, including overflow cells, are copied into the child. The root\n** page is then overwritten to make it an empty page with the right-child \n** pointer pointing to the new page.\n**\n** Before returning, all pointer-map entries corresponding to pages \n** that the new child-page now contains pointers to are updated. The\n** entry corresponding to the new right-child pointer of the root\n** page is also updated.\n**\n** If successful, *ppChild is set to contain a reference to the child \n** page and SQLITE_OK is returned. In this case the caller is required\n** to call releasePage() on *ppChild exactly once. If an error occurs,\n** an error code is returned and *ppChild is set to 0.\n*/\nstatic int balance_deeper(MemPage *pRoot, MemPage **ppChild){\n  int rc;                        /* Return value from subprocedures */\n  MemPage *pChild = 0;           /* Pointer to a new child page */\n  Pgno pgnoChild = 0;            /* Page number of the new child page */\n  BtShared *pBt = pRoot->pBt;    /* The BTree */\n\n  assert( pRoot->nOverflow>0 );\n  assert( sqlite3_mutex_held(pBt->mutex) );\n\n  /* Make pRoot, the root page of the b-tree, writable. Allocate a new \n  ** page that will become the new right-child of pPage. Copy the contents\n  ** of the node stored on pRoot into the new child page.\n  */\n  rc = sqlite3PagerWrite(pRoot->pDbPage);\n  if( rc==SQLITE_OK ){\n    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);\n    copyNodeContent(pRoot, pChild, &rc);\n    if( ISAUTOVACUUM ){\n      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);\n    }\n  }\n  if( rc ){\n    *ppChild = 0;\n    releasePage(pChild);\n    return rc;\n  }\n  assert( sqlite3PagerIswriteable(pChild->pDbPage) );\n  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );\n  assert( pChild->nCell==pRoot->nCell );\n\n  TRACE((\"BALANCE: copy root %d into %d\\n\", pRoot->pgno, pChild->pgno));\n\n  /* Copy the overflow cells from pRoot to pChild */\n  memcpy(pChild->aiOvfl, pRoot->aiOvfl,\n         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));\n  memcpy(pChild->apOvfl, pRoot->apOvfl,\n         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));\n  pChild->nOverflow = pRoot->nOverflow;\n\n  /* Zero the contents of pRoot. Then install pChild as the right-child. */\n  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);\n  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);\n\n  *ppChild = pChild;\n  return SQLITE_OK;\n}\n\n/*\n** The page that pCur currently points to has just been modified in\n** some way. This function figures out if this modification means the\n** tree needs to be balanced, and if so calls the appropriate balancing \n** routine. Balancing routines are:\n**\n**   balance_quick()\n**   balance_deeper()\n**   balance_nonroot()\n*/\nstatic int balance(BtCursor *pCur){\n  int rc = SQLITE_OK;\n  const int nMin = pCur->pBt->usableSize * 2 / 3;\n  u8 aBalanceQuickSpace[13];\n  u8 *pFree = 0;\n\n  TESTONLY( int balance_quick_called = 0 );\n  TESTONLY( int balance_deeper_called = 0 );\n\n  do {\n    int iPage = pCur->iPage;\n    MemPage *pPage = pCur->apPage[iPage];\n\n    if( iPage==0 ){\n      if( pPage->nOverflow ){\n        /* The root page of the b-tree is overfull. In this case call the\n        ** balance_deeper() function to create a new child for the root-page\n        ** and copy the current contents of the root-page to it. The\n        ** next iteration of the do-loop will balance the child page.\n        */ \n        assert( (balance_deeper_called++)==0 );\n        rc = balance_deeper(pPage, &pCur->apPage[1]);\n        if( rc==SQLITE_OK ){\n          pCur->iPage = 1;\n          pCur->aiIdx[0] = 0;\n          pCur->aiIdx[1] = 0;\n          assert( pCur->apPage[1]->nOverflow );\n        }\n      }else{\n        break;\n      }\n    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){\n      break;\n    }else{\n      MemPage * const pParent = pCur->apPage[iPage-1];\n      int const iIdx = pCur->aiIdx[iPage-1];\n\n      rc = sqlite3PagerWrite(pParent->pDbPage);\n      if( rc==SQLITE_OK ){\n#ifndef SQLITE_OMIT_QUICKBALANCE\n        if( pPage->hasData\n         && pPage->nOverflow==1\n         && pPage->aiOvfl[0]==pPage->nCell\n         && pParent->pgno!=1\n         && pParent->nCell==iIdx\n        ){\n          /* Call balance_quick() to create a new sibling of pPage on which\n          ** to store the overflow cell. balance_quick() inserts a new cell\n          ** into pParent, which may cause pParent overflow. If this\n          ** happens, the next interation of the do-loop will balance pParent \n          ** use either balance_nonroot() or balance_deeper(). Until this\n          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]\n          ** buffer. \n          **\n          ** The purpose of the following assert() is to check that only a\n          ** single call to balance_quick() is made for each call to this\n          ** function. If this were not verified, a subtle bug involving reuse\n          ** of the aBalanceQuickSpace[] might sneak in.\n          */\n          assert( (balance_quick_called++)==0 );\n          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);\n        }else\n#endif\n        {\n          /* In this case, call balance_nonroot() to redistribute cells\n          ** between pPage and up to 2 of its sibling pages. This involves\n          ** modifying the contents of pParent, which may cause pParent to\n          ** become overfull or underfull. The next iteration of the do-loop\n          ** will balance the parent page to correct this.\n          ** \n          ** If the parent page becomes overfull, the overflow cell or cells\n          ** are stored in the pSpace buffer allocated immediately below. \n          ** A subsequent iteration of the do-loop will deal with this by\n          ** calling balance_nonroot() (balance_deeper() may be called first,\n          ** but it doesn't deal with overflow cells - just moves them to a\n          ** different page). Once this subsequent call to balance_nonroot() \n          ** has completed, it is safe to release the pSpace buffer used by\n          ** the previous call, as the overflow cell data will have been \n          ** copied either into the body of a database page or into the new\n          ** pSpace buffer passed to the latter call to balance_nonroot().\n          */\n          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);\n          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);\n          if( pFree ){\n            /* If pFree is not NULL, it points to the pSpace buffer used \n            ** by a previous call to balance_nonroot(). Its contents are\n            ** now stored either on real database pages or within the \n            ** new pSpace buffer, so it may be safely freed here. */\n            sqlite3PageFree(pFree);\n          }\n\n          /* The pSpace buffer will be freed after the next call to\n          ** balance_nonroot(), or just before this function returns, whichever\n          ** comes first. */\n          pFree = pSpace;\n        }\n      }\n\n      pPage->nOverflow = 0;\n\n      /* The next iteration of the do-loop balances the parent page. */\n      releasePage(pPage);\n      pCur->iPage--;\n    }\n  }while( rc==SQLITE_OK );\n\n  if( pFree ){\n    sqlite3PageFree(pFree);\n  }\n  return rc;\n}\n\n\n/*\n** Insert a new record into the BTree.  The key is given by (pKey,nKey)\n** and the data is given by (pData,nData).  The cursor is used only to\n** define what table the record should be inserted into.  The cursor\n** is left pointing at a random location.\n**\n** For an INTKEY table, only the nKey value of the key is used.  pKey is\n** ignored.  For a ZERODATA table, the pData and nData are both ignored.\n**\n** If the seekResult parameter is non-zero, then a successful call to\n** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already\n** been performed. seekResult is the search result returned (a negative\n** number if pCur points at an entry that is smaller than (pKey, nKey), or\n** a positive value if pCur points at an etry that is larger than \n** (pKey, nKey)). \n**\n** If the seekResult parameter is non-zero, then the caller guarantees that\n** cursor pCur is pointing at the existing copy of a row that is to be\n** overwritten.  If the seekResult parameter is 0, then cursor pCur may\n** point to any entry or to no entry at all and so this function has to seek\n** the cursor before the new key can be inserted.\n*/\nSQLITE_PRIVATE int sqlite3BtreeInsert(\n  BtCursor *pCur,                /* Insert data into the table of this cursor */\n  const void *pKey, i64 nKey,    /* The key of the new record */\n  const void *pData, int nData,  /* The data of the new record */\n  int nZero,                     /* Number of extra 0 bytes to append to data */\n  int appendBias,                /* True if this is likely an append */\n  int seekResult                 /* Result of prior MovetoUnpacked() call */\n){\n  int rc;\n  int loc = seekResult;          /* -1: before desired location  +1: after */\n  int szNew = 0;\n  int idx;\n  MemPage *pPage;\n  Btree *p = pCur->pBtree;\n  BtShared *pBt = p->pBt;\n  unsigned char *oldCell;\n  unsigned char *newCell = 0;\n\n  if( pCur->eState==CURSOR_FAULT ){\n    assert( pCur->skipNext!=SQLITE_OK );\n    return pCur->skipNext;\n  }\n\n  assert( cursorHoldsMutex(pCur) );\n  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE\n              && (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );\n\n  /* Assert that the caller has been consistent. If this cursor was opened\n  ** expecting an index b-tree, then the caller should be inserting blob\n  ** keys with no associated data. If the cursor was opened expecting an\n  ** intkey table, the caller should be inserting integer keys with a\n  ** blob of associated data.  */\n  assert( (pKey==0)==(pCur->pKeyInfo==0) );\n\n  /* Save the positions of any other cursors open on this table.\n  **\n  ** In some cases, the call to btreeMoveto() below is a no-op. For\n  ** example, when inserting data into a table with auto-generated integer\n  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the \n  ** integer key to use. It then calls this function to actually insert the \n  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes\n  ** that the cursor is already where it needs to be and returns without\n  ** doing any work. To avoid thwarting these optimizations, it is important\n  ** not to clear the cursor here.\n  */\n  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);\n  if( rc ) return rc;\n\n  /* If this is an insert into a table b-tree, invalidate any incrblob \n  ** cursors open on the row being replaced (assuming this is a replace\n  ** operation - if it is not, the following is a no-op).  */\n  if( pCur->pKeyInfo==0 ){\n    invalidateIncrblobCursors(p, nKey, 0);\n  }\n\n  if( !loc ){\n    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);\n    if( rc ) return rc;\n  }\n  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );\n\n  pPage = pCur->apPage[pCur->iPage];\n  assert( pPage->intKey || nKey>=0 );\n  assert( pPage->leaf || !pPage->intKey );\n\n  TRACE((\"INSERT: table=%d nkey=%lld ndata=%d page=%d %s\\n\",\n          pCur->pgnoRoot, nKey, nData, pPage->pgno,\n          loc==0 ? \"overwrite\" : \"new entry\"));\n  assert( pPage->isInit );\n  allocateTempSpace(pBt);\n  newCell = pBt->pTmpSpace;\n  if( newCell==0 ) return SQLITE_NOMEM;\n  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);\n  if( rc ) goto end_insert;\n  assert( szNew==cellSizePtr(pPage, newCell) );\n  assert( szNew <= MX_CELL_SIZE(pBt) );\n  idx = pCur->aiIdx[pCur->iPage];\n  if( loc==0 ){\n    u16 szOld;\n    assert( idx<pPage->nCell );\n    rc = sqlite3PagerWrite(pPage->pDbPage);\n    if( rc ){\n      goto end_insert;\n    }\n    oldCell = findCell(pPage, idx);\n    if( !pPage->leaf ){\n      memcpy(newCell, oldCell, 4);\n    }\n    szOld = cellSizePtr(pPage, oldCell);\n    rc = clearCell(pPage, oldCell);\n    dropCell(pPage, idx, szOld, &rc);\n    if( rc ) goto end_insert;\n  }else if( loc<0 && pPage->nCell>0 ){\n    assert( pPage->leaf );\n    idx = ++pCur->aiIdx[pCur->iPage];\n  }else{\n    assert( pPage->leaf );\n  }\n  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);\n  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );\n\n  /* If no error has occured and pPage has an overflow cell, call balance() \n  ** to redistribute the cells within the tree. Since balance() may move\n  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey\n  ** variables.\n  **\n  ** Previous versions of SQLite called moveToRoot() to move the cursor\n  ** back to the root page as balance() used to invalidate the contents\n  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,\n  ** set the cursor state to \"invalid\". This makes common insert operations\n  ** slightly faster.\n  **\n  ** There is a subtle but important optimization here too. When inserting\n  ** multiple records into an intkey b-tree using a single cursor (as can\n  ** happen while processing an \"INSERT INTO ... SELECT\" statement), it\n  ** is advantageous to leave the cursor pointing to the last entry in\n  ** the b-tree if possible. If the cursor is left pointing to the last\n  ** entry in the table, and the next row inserted has an integer key\n  ** larger than the largest existing key, it is possible to insert the\n  ** row without seeking the cursor. This can be a big performance boost.\n  */\n  pCur->info.nSize = 0;\n  pCur->validNKey = 0;\n  if( rc==SQLITE_OK && pPage->nOverflow ){\n    rc = balance(pCur);\n\n    /* Must make sure nOverflow is reset to zero even if the balance()\n    ** fails. Internal data structure corruption will result otherwise. \n    ** Also, set the cursor state to invalid. This stops saveCursorPosition()\n    ** from trying to save the current position of the cursor.  */\n    pCur->apPage[pCur->iPage]->nOverflow = 0;\n    pCur->eState = CURSOR_INVALID;\n  }\n  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );\n\nend_insert:\n  return rc;\n}\n\n/*\n** Delete the entry that the cursor is pointing to.  The cursor\n** is left pointing at a arbitrary location.\n*/\nSQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){\n  Btree *p = pCur->pBtree;\n  BtShared *pBt = p->pBt;              \n  int rc;                              /* Return code */\n  MemPage *pPage;                      /* Page to delete cell from */\n  unsigned char *pCell;                /* Pointer to cell to delete */\n  int iCellIdx;                        /* Index of cell to delete */\n  int iCellDepth;                      /* Depth of node containing pCell */ \n\n  assert( cursorHoldsMutex(pCur) );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n  assert( pCur->wrFlag );\n  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );\n  assert( !hasReadConflicts(p, pCur->pgnoRoot) );\n\n  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) \n   || NEVER(pCur->eState!=CURSOR_VALID)\n  ){\n    return SQLITE_ERROR;  /* Something has gone awry. */\n  }\n\n  iCellDepth = pCur->iPage;\n  iCellIdx = pCur->aiIdx[iCellDepth];\n  pPage = pCur->apPage[iCellDepth];\n  pCell = findCell(pPage, iCellIdx);\n\n  /* If the page containing the entry to delete is not a leaf page, move\n  ** the cursor to the largest entry in the tree that is smaller than\n  ** the entry being deleted. This cell will replace the cell being deleted\n  ** from the internal node. The 'previous' entry is used for this instead\n  ** of the 'next' entry, as the previous entry is always a part of the\n  ** sub-tree headed by the child page of the cell being deleted. This makes\n  ** balancing the tree following the delete operation easier.  */\n  if( !pPage->leaf ){\n    int notUsed;\n    rc = sqlite3BtreePrevious(pCur, &notUsed);\n    if( rc ) return rc;\n  }\n\n  /* Save the positions of any other cursors open on this table before\n  ** making any modifications. Make the page containing the entry to be \n  ** deleted writable. Then free any overflow pages associated with the \n  ** entry and finally remove the cell itself from within the page.  \n  */\n  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);\n  if( rc ) return rc;\n\n  /* If this is a delete operation to remove a row from a table b-tree,\n  ** invalidate any incrblob cursors open on the row being deleted.  */\n  if( pCur->pKeyInfo==0 ){\n    invalidateIncrblobCursors(p, pCur->info.nKey, 0);\n  }\n\n  rc = sqlite3PagerWrite(pPage->pDbPage);\n  if( rc ) return rc;\n  rc = clearCell(pPage, pCell);\n  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);\n  if( rc ) return rc;\n\n  /* If the cell deleted was not located on a leaf page, then the cursor\n  ** is currently pointing to the largest entry in the sub-tree headed\n  ** by the child-page of the cell that was just deleted from an internal\n  ** node. The cell from the leaf node needs to be moved to the internal\n  ** node to replace the deleted cell.  */\n  if( !pPage->leaf ){\n    MemPage *pLeaf = pCur->apPage[pCur->iPage];\n    int nCell;\n    Pgno n = pCur->apPage[iCellDepth+1]->pgno;\n    unsigned char *pTmp;\n\n    pCell = findCell(pLeaf, pLeaf->nCell-1);\n    nCell = cellSizePtr(pLeaf, pCell);\n    assert( MX_CELL_SIZE(pBt) >= nCell );\n\n    allocateTempSpace(pBt);\n    pTmp = pBt->pTmpSpace;\n\n    rc = sqlite3PagerWrite(pLeaf->pDbPage);\n    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);\n    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);\n    if( rc ) return rc;\n  }\n\n  /* Balance the tree. If the entry deleted was located on a leaf page,\n  ** then the cursor still points to that page. In this case the first\n  ** call to balance() repairs the tree, and the if(...) condition is\n  ** never true.\n  **\n  ** Otherwise, if the entry deleted was on an internal node page, then\n  ** pCur is pointing to the leaf page from which a cell was removed to\n  ** replace the cell deleted from the internal node. This is slightly\n  ** tricky as the leaf node may be underfull, and the internal node may\n  ** be either under or overfull. In this case run the balancing algorithm\n  ** on the leaf node first. If the balance proceeds far enough up the\n  ** tree that we can be sure that any problem in the internal node has\n  ** been corrected, so be it. Otherwise, after balancing the leaf node,\n  ** walk the cursor up the tree to the internal node and balance it as \n  ** well.  */\n  rc = balance(pCur);\n  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){\n    while( pCur->iPage>iCellDepth ){\n      releasePage(pCur->apPage[pCur->iPage--]);\n    }\n    rc = balance(pCur);\n  }\n\n  if( rc==SQLITE_OK ){\n    moveToRoot(pCur);\n  }\n  return rc;\n}\n\n/*\n** Create a new BTree table.  Write into *piTable the page\n** number for the root page of the new table.\n**\n** The type of type is determined by the flags parameter.  Only the\n** following values of flags are currently in use.  Other values for\n** flags might not work:\n**\n**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys\n**     BTREE_ZERODATA                  Used for SQL indices\n*/\nstatic int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){\n  BtShared *pBt = p->pBt;\n  MemPage *pRoot;\n  Pgno pgnoRoot;\n  int rc;\n  int ptfFlags;          /* Page-type flage for the root page of new table */\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( pBt->inTransaction==TRANS_WRITE );\n  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );\n\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);\n  if( rc ){\n    return rc;\n  }\n#else\n  if( pBt->autoVacuum ){\n    Pgno pgnoMove;      /* Move a page here to make room for the root-page */\n    MemPage *pPageMove; /* The page to move to. */\n\n    /* Creating a new table may probably require moving an existing database\n    ** to make room for the new tables root page. In case this page turns\n    ** out to be an overflow page, delete all overflow page-map caches\n    ** held by open cursors.\n    */\n    invalidateAllOverflowCache(pBt);\n\n    /* Read the value of meta[3] from the database to determine where the\n    ** root page of the new table should go. meta[3] is the largest root-page\n    ** created so far, so the new root-page is (meta[3]+1).\n    */\n    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);\n    pgnoRoot++;\n\n    /* The new root-page may not be allocated on a pointer-map page, or the\n    ** PENDING_BYTE page.\n    */\n    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||\n        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){\n      pgnoRoot++;\n    }\n    assert( pgnoRoot>=3 );\n\n    /* Allocate a page. The page that currently resides at pgnoRoot will\n    ** be moved to the allocated page (unless the allocated page happens\n    ** to reside at pgnoRoot).\n    */\n    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n\n    if( pgnoMove!=pgnoRoot ){\n      /* pgnoRoot is the page that will be used for the root-page of\n      ** the new table (assuming an error did not occur). But we were\n      ** allocated pgnoMove. If required (i.e. if it was not allocated\n      ** by extending the file), the current page at position pgnoMove\n      ** is already journaled.\n      */\n      u8 eType = 0;\n      Pgno iPtrPage = 0;\n\n      releasePage(pPageMove);\n\n      /* Move the page currently at pgnoRoot to pgnoMove. */\n      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);\n      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){\n        rc = SQLITE_CORRUPT_BKPT;\n      }\n      if( rc!=SQLITE_OK ){\n        releasePage(pRoot);\n        return rc;\n      }\n      assert( eType!=PTRMAP_ROOTPAGE );\n      assert( eType!=PTRMAP_FREEPAGE );\n      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);\n      releasePage(pRoot);\n\n      /* Obtain the page at pgnoRoot */\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      rc = sqlite3PagerWrite(pRoot->pDbPage);\n      if( rc!=SQLITE_OK ){\n        releasePage(pRoot);\n        return rc;\n      }\n    }else{\n      pRoot = pPageMove;\n    } \n\n    /* Update the pointer-map and meta-data with the new root-page number. */\n    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);\n    if( rc ){\n      releasePage(pRoot);\n      return rc;\n    }\n\n    /* When the new root page was allocated, page 1 was made writable in\n    ** order either to increase the database filesize, or to decrement the\n    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.\n    */\n    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );\n    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);\n    if( NEVER(rc) ){\n      releasePage(pRoot);\n      return rc;\n    }\n\n  }else{\n    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);\n    if( rc ) return rc;\n  }\n#endif\n  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );\n  if( createTabFlags & BTREE_INTKEY ){\n    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;\n  }else{\n    ptfFlags = PTF_ZERODATA | PTF_LEAF;\n  }\n  zeroPage(pRoot, ptfFlags);\n  sqlite3PagerUnref(pRoot->pDbPage);\n  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );\n  *piTable = (int)pgnoRoot;\n  return SQLITE_OK;\n}\nSQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeCreateTable(p, piTable, flags);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Erase the given database page and all its children.  Return\n** the page to the freelist.\n*/\nstatic int clearDatabasePage(\n  BtShared *pBt,           /* The BTree that contains the table */\n  Pgno pgno,               /* Page number to clear */\n  int freePageFlag,        /* Deallocate page if true */\n  int *pnChange            /* Add number of Cells freed to this counter */\n){\n  MemPage *pPage;\n  int rc;\n  unsigned char *pCell;\n  int i;\n\n  assert( sqlite3_mutex_held(pBt->mutex) );\n  if( pgno>btreePagecount(pBt) ){\n    return SQLITE_CORRUPT_BKPT;\n  }\n\n  rc = getAndInitPage(pBt, pgno, &pPage);\n  if( rc ) return rc;\n  for(i=0; i<pPage->nCell; i++){\n    pCell = findCell(pPage, i);\n    if( !pPage->leaf ){\n      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);\n      if( rc ) goto cleardatabasepage_out;\n    }\n    rc = clearCell(pPage, pCell);\n    if( rc ) goto cleardatabasepage_out;\n  }\n  if( !pPage->leaf ){\n    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);\n    if( rc ) goto cleardatabasepage_out;\n  }else if( pnChange ){\n    assert( pPage->intKey );\n    *pnChange += pPage->nCell;\n  }\n  if( freePageFlag ){\n    freePage(pPage, &rc);\n  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){\n    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);\n  }\n\ncleardatabasepage_out:\n  releasePage(pPage);\n  return rc;\n}\n\n/*\n** Delete all information from a single table in the database.  iTable is\n** the page number of the root of the table.  After this routine returns,\n** the root page is empty, but still exists.\n**\n** This routine will fail with SQLITE_LOCKED if there are any open\n** read cursors on the table.  Open write cursors are moved to the\n** root of the table.\n**\n** If pnChange is not NULL, then table iTable must be an intkey table. The\n** integer value pointed to by pnChange is incremented by the number of\n** entries in the table.\n*/\nSQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){\n  int rc;\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n\n  rc = saveAllCursors(pBt, (Pgno)iTable, 0);\n\n  if( SQLITE_OK==rc ){\n    /* Invalidate all incrblob cursors open on table iTable (assuming iTable\n    ** is the root of a table b-tree - if it is not, the following call is\n    ** a no-op).  */\n    invalidateIncrblobCursors(p, 0, 1);\n    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n/*\n** Erase all information in a table and add the root of the table to\n** the freelist.  Except, the root of the principle table (the one on\n** page 1) is never added to the freelist.\n**\n** This routine will fail with SQLITE_LOCKED if there are any open\n** cursors on the table.\n**\n** If AUTOVACUUM is enabled and the page at iTable is not the last\n** root page in the database file, then the last root page \n** in the database file is moved into the slot formerly occupied by\n** iTable and that last slot formerly occupied by the last root page\n** is added to the freelist instead of iTable.  In this say, all\n** root pages are kept at the beginning of the database file, which\n** is necessary for AUTOVACUUM to work right.  *piMoved is set to the \n** page number that used to be the last root page in the file before\n** the move.  If no page gets moved, *piMoved is set to 0.\n** The last root page is recorded in meta[3] and the value of\n** meta[3] is updated by this procedure.\n*/\nstatic int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){\n  int rc;\n  MemPage *pPage = 0;\n  BtShared *pBt = p->pBt;\n\n  assert( sqlite3BtreeHoldsMutex(p) );\n  assert( p->inTrans==TRANS_WRITE );\n\n  /* It is illegal to drop a table if any cursors are open on the\n  ** database. This is because in auto-vacuum mode the backend may\n  ** need to move another root-page to fill a gap left by the deleted\n  ** root page. If an open cursor was using this page a problem would \n  ** occur.\n  **\n  ** This error is caught long before control reaches this point.\n  */\n  if( NEVER(pBt->pCursor) ){\n    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);\n    return SQLITE_LOCKED_SHAREDCACHE;\n  }\n\n  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);\n  if( rc ) return rc;\n  rc = sqlite3BtreeClearTable(p, iTable, 0);\n  if( rc ){\n    releasePage(pPage);\n    return rc;\n  }\n\n  *piMoved = 0;\n\n  if( iTable>1 ){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n    freePage(pPage, &rc);\n    releasePage(pPage);\n#else\n    if( pBt->autoVacuum ){\n      Pgno maxRootPgno;\n      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);\n\n      if( iTable==maxRootPgno ){\n        /* If the table being dropped is the table with the largest root-page\n        ** number in the database, put the root page on the free list. \n        */\n        freePage(pPage, &rc);\n        releasePage(pPage);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n      }else{\n        /* The table being dropped does not have the largest root-page\n        ** number in the database. So move the page that does into the \n        ** gap left by the deleted root-page.\n        */\n        MemPage *pMove;\n        releasePage(pPage);\n        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);\n        releasePage(pMove);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        pMove = 0;\n        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);\n        freePage(pMove, &rc);\n        releasePage(pMove);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        *piMoved = maxRootPgno;\n      }\n\n      /* Set the new 'max-root-page' value in the database header. This\n      ** is the old value less one, less one more if that happens to\n      ** be a root-page number, less one again if that is the\n      ** PENDING_BYTE_PAGE.\n      */\n      maxRootPgno--;\n      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)\n             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){\n        maxRootPgno--;\n      }\n      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );\n\n      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);\n    }else{\n      freePage(pPage, &rc);\n      releasePage(pPage);\n    }\n#endif\n  }else{\n    /* If sqlite3BtreeDropTable was called on page 1.\n    ** This really never should happen except in a corrupt\n    ** database. \n    */\n    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );\n    releasePage(pPage);\n  }\n  return rc;  \n}\nSQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){\n  int rc;\n  sqlite3BtreeEnter(p);\n  rc = btreeDropTable(p, iTable, piMoved);\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n\n/*\n** This function may only be called if the b-tree connection already\n** has a read or write transaction open on the database.\n**\n** Read the meta-information out of a database file.  Meta[0]\n** is the number of free pages currently in the database.  Meta[1]\n** through meta[15] are available for use by higher layers.  Meta[0]\n** is read-only, the others are read/write.\n** \n** The schema layer numbers meta values differently.  At the schema\n** layer (and the SetCookie and ReadCookie opcodes) the number of\n** free pages is not visible.  So Cookie[0] is the same as Meta[1].\n*/\nSQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){\n  BtShared *pBt = p->pBt;\n\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans>TRANS_NONE );\n  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );\n  assert( pBt->pPage1 );\n  assert( idx>=0 && idx<=15 );\n\n  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);\n\n  /* If auto-vacuum is disabled in this build and this is an auto-vacuum\n  ** database, mark the database as read-only.  */\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){\n    pBt->btsFlags |= BTS_READ_ONLY;\n  }\n#endif\n\n  sqlite3BtreeLeave(p);\n}\n\n/*\n** Write meta-information back into the database.  Meta[0] is\n** read-only and may not be written.\n*/\nSQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){\n  BtShared *pBt = p->pBt;\n  unsigned char *pP1;\n  int rc;\n  assert( idx>=1 && idx<=15 );\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans==TRANS_WRITE );\n  assert( pBt->pPage1!=0 );\n  pP1 = pBt->pPage1->aData;\n  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n  if( rc==SQLITE_OK ){\n    put4byte(&pP1[36 + idx*4], iMeta);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( idx==BTREE_INCR_VACUUM ){\n      assert( pBt->autoVacuum || iMeta==0 );\n      assert( iMeta==0 || iMeta==1 );\n      pBt->incrVacuum = (u8)iMeta;\n    }\n#endif\n  }\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_BTREECOUNT\n/*\n** The first argument, pCur, is a cursor opened on some b-tree. Count the\n** number of entries in the b-tree and write the result to *pnEntry.\n**\n** SQLITE_OK is returned if the operation is successfully executed. \n** Otherwise, if an error is encountered (i.e. an IO error or database\n** corruption) an SQLite error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){\n  i64 nEntry = 0;                      /* Value to return in *pnEntry */\n  int rc;                              /* Return code */\n\n  if( pCur->pgnoRoot==0 ){\n    *pnEntry = 0;\n    return SQLITE_OK;\n  }\n  rc = moveToRoot(pCur);\n\n  /* Unless an error occurs, the following loop runs one iteration for each\n  ** page in the B-Tree structure (not including overflow pages). \n  */\n  while( rc==SQLITE_OK ){\n    int iIdx;                          /* Index of child node in parent */\n    MemPage *pPage;                    /* Current page of the b-tree */\n\n    /* If this is a leaf page or the tree is not an int-key tree, then \n    ** this page contains countable entries. Increment the entry counter\n    ** accordingly.\n    */\n    pPage = pCur->apPage[pCur->iPage];\n    if( pPage->leaf || !pPage->intKey ){\n      nEntry += pPage->nCell;\n    }\n\n    /* pPage is a leaf node. This loop navigates the cursor so that it \n    ** points to the first interior cell that it points to the parent of\n    ** the next page in the tree that has not yet been visited. The\n    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell\n    ** of the page, or to the number of cells in the page if the next page\n    ** to visit is the right-child of its parent.\n    **\n    ** If all pages in the tree have been visited, return SQLITE_OK to the\n    ** caller.\n    */\n    if( pPage->leaf ){\n      do {\n        if( pCur->iPage==0 ){\n          /* All pages of the b-tree have been visited. Return successfully. */\n          *pnEntry = nEntry;\n          return SQLITE_OK;\n        }\n        moveToParent(pCur);\n      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );\n\n      pCur->aiIdx[pCur->iPage]++;\n      pPage = pCur->apPage[pCur->iPage];\n    }\n\n    /* Descend to the child node of the cell that the cursor currently \n    ** points at. This is the right-child if (iIdx==pPage->nCell).\n    */\n    iIdx = pCur->aiIdx[pCur->iPage];\n    if( iIdx==pPage->nCell ){\n      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));\n    }else{\n      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));\n    }\n  }\n\n  /* An error has occurred. Return an error code. */\n  return rc;\n}\n#endif\n\n/*\n** Return the pager associated with a BTree.  This routine is used for\n** testing and debugging only.\n*/\nSQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){\n  return p->pBt->pPager;\n}\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** Append a message to the error message string.\n*/\nstatic void checkAppendMsg(\n  IntegrityCk *pCheck,\n  char *zMsg1,\n  const char *zFormat,\n  ...\n){\n  va_list ap;\n  if( !pCheck->mxErr ) return;\n  pCheck->mxErr--;\n  pCheck->nErr++;\n  va_start(ap, zFormat);\n  if( pCheck->errMsg.nChar ){\n    sqlite3StrAccumAppend(&pCheck->errMsg, \"\\n\", 1);\n  }\n  if( zMsg1 ){\n    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);\n  }\n  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);\n  va_end(ap);\n  if( pCheck->errMsg.mallocFailed ){\n    pCheck->mallocFailed = 1;\n  }\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n\n/*\n** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that\n** corresponds to page iPg is already set.\n*/\nstatic int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){\n  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );\n  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));\n}\n\n/*\n** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.\n*/\nstatic void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){\n  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );\n  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));\n}\n\n\n/*\n** Add 1 to the reference count for page iPage.  If this is the second\n** reference to the page, add an error message to pCheck->zErrMsg.\n** Return 1 if there are 2 ore more references to the page and 0 if\n** if this is the first reference to the page.\n**\n** Also check that the page number is in bounds.\n*/\nstatic int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){\n  if( iPage==0 ) return 1;\n  if( iPage>pCheck->nPage ){\n    checkAppendMsg(pCheck, zContext, \"invalid page number %d\", iPage);\n    return 1;\n  }\n  if( getPageReferenced(pCheck, iPage) ){\n    checkAppendMsg(pCheck, zContext, \"2nd reference to page %d\", iPage);\n    return 1;\n  }\n  setPageReferenced(pCheck, iPage);\n  return 0;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Check that the entry in the pointer-map for page iChild maps to \n** page iParent, pointer type ptrType. If not, append an error message\n** to pCheck.\n*/\nstatic void checkPtrmap(\n  IntegrityCk *pCheck,   /* Integrity check context */\n  Pgno iChild,           /* Child page number */\n  u8 eType,              /* Expected pointer map type */\n  Pgno iParent,          /* Expected pointer map parent page number */\n  char *zContext         /* Context description (used for error msg) */\n){\n  int rc;\n  u8 ePtrmapType;\n  Pgno iPtrmapParent;\n\n  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;\n    checkAppendMsg(pCheck, zContext, \"Failed to read ptrmap key=%d\", iChild);\n    return;\n  }\n\n  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){\n    checkAppendMsg(pCheck, zContext, \n      \"Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)\", \n      iChild, eType, iParent, ePtrmapType, iPtrmapParent);\n  }\n}\n#endif\n\n/*\n** Check the integrity of the freelist or of an overflow page list.\n** Verify that the number of pages on the list is N.\n*/\nstatic void checkList(\n  IntegrityCk *pCheck,  /* Integrity checking context */\n  int isFreeList,       /* True for a freelist.  False for overflow page list */\n  int iPage,            /* Page number for first page in the list */\n  int N,                /* Expected number of pages in the list */\n  char *zContext        /* Context for error messages */\n){\n  int i;\n  int expected = N;\n  int iFirst = iPage;\n  while( N-- > 0 && pCheck->mxErr ){\n    DbPage *pOvflPage;\n    unsigned char *pOvflData;\n    if( iPage<1 ){\n      checkAppendMsg(pCheck, zContext,\n         \"%d of %d pages missing from overflow list starting at %d\",\n          N+1, expected, iFirst);\n      break;\n    }\n    if( checkRef(pCheck, iPage, zContext) ) break;\n    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){\n      checkAppendMsg(pCheck, zContext, \"failed to get page %d\", iPage);\n      break;\n    }\n    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);\n    if( isFreeList ){\n      int n = get4byte(&pOvflData[4]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pCheck->pBt->autoVacuum ){\n        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);\n      }\n#endif\n      if( n>(int)pCheck->pBt->usableSize/4-2 ){\n        checkAppendMsg(pCheck, zContext,\n           \"freelist leaf count too big on page %d\", iPage);\n        N--;\n      }else{\n        for(i=0; i<n; i++){\n          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n          if( pCheck->pBt->autoVacuum ){\n            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);\n          }\n#endif\n          checkRef(pCheck, iFreePage, zContext);\n        }\n        N -= n;\n      }\n    }\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    else{\n      /* If this database supports auto-vacuum and iPage is not the last\n      ** page in this overflow list, check that the pointer-map entry for\n      ** the following page matches iPage.\n      */\n      if( pCheck->pBt->autoVacuum && N>0 ){\n        i = get4byte(pOvflData);\n        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);\n      }\n    }\n#endif\n    iPage = get4byte(pOvflData);\n    sqlite3PagerUnref(pOvflPage);\n  }\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** Do various sanity checks on a single page of a tree.  Return\n** the tree depth.  Root pages return 0.  Parents of root pages\n** return 1, and so forth.\n** \n** These checks are done:\n**\n**      1.  Make sure that cells and freeblocks do not overlap\n**          but combine to completely cover the page.\n**  NO  2.  Make sure cell keys are in order.\n**  NO  3.  Make sure no key is less than or equal to zLowerBound.\n**  NO  4.  Make sure no key is greater than or equal to zUpperBound.\n**      5.  Check the integrity of overflow pages.\n**      6.  Recursively call checkTreePage on all children.\n**      7.  Verify that the depth of all children is the same.\n**      8.  Make sure this page is at least 33% full or else it is\n**          the root of the tree.\n*/\nstatic int checkTreePage(\n  IntegrityCk *pCheck,  /* Context for the sanity check */\n  int iPage,            /* Page number of the page to check */\n  char *zParentContext, /* Parent context */\n  i64 *pnParentMinKey, \n  i64 *pnParentMaxKey\n){\n  MemPage *pPage;\n  int i, rc, depth, d2, pgno, cnt;\n  int hdr, cellStart;\n  int nCell;\n  u8 *data;\n  BtShared *pBt;\n  int usableSize;\n  char zContext[100];\n  char *hit = 0;\n  i64 nMinKey = 0;\n  i64 nMaxKey = 0;\n\n  sqlite3_snprintf(sizeof(zContext), zContext, \"Page %d: \", iPage);\n\n  /* Check that the page exists\n  */\n  pBt = pCheck->pBt;\n  usableSize = pBt->usableSize;\n  if( iPage==0 ) return 0;\n  if( checkRef(pCheck, iPage, zParentContext) ) return 0;\n  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){\n    checkAppendMsg(pCheck, zContext,\n       \"unable to get the page. error code=%d\", rc);\n    return 0;\n  }\n\n  /* Clear MemPage.isInit to make sure the corruption detection code in\n  ** btreeInitPage() is executed.  */\n  pPage->isInit = 0;\n  if( (rc = btreeInitPage(pPage))!=0 ){\n    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */\n    checkAppendMsg(pCheck, zContext, \n                   \"btreeInitPage() returns error code %d\", rc);\n    releasePage(pPage);\n    return 0;\n  }\n\n  /* Check out all the cells.\n  */\n  depth = 0;\n  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){\n    u8 *pCell;\n    u32 sz;\n    CellInfo info;\n\n    /* Check payload overflow pages\n    */\n    sqlite3_snprintf(sizeof(zContext), zContext,\n             \"On tree page %d cell %d: \", iPage, i);\n    pCell = findCell(pPage,i);\n    btreeParseCellPtr(pPage, pCell, &info);\n    sz = info.nData;\n    if( !pPage->intKey ) sz += (int)info.nKey;\n    /* For intKey pages, check that the keys are in order.\n    */\n    else if( i==0 ) nMinKey = nMaxKey = info.nKey;\n    else{\n      if( info.nKey <= nMaxKey ){\n        checkAppendMsg(pCheck, zContext, \n            \"Rowid %lld out of order (previous was %lld)\", info.nKey, nMaxKey);\n      }\n      nMaxKey = info.nKey;\n    }\n    assert( sz==info.nPayload );\n    if( (sz>info.nLocal) \n     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])\n    ){\n      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);\n      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pBt->autoVacuum ){\n        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);\n      }\n#endif\n      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);\n    }\n\n    /* Check sanity of left child page.\n    */\n    if( !pPage->leaf ){\n      pgno = get4byte(pCell);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n      if( pBt->autoVacuum ){\n        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);\n      }\n#endif\n      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);\n      if( i>0 && d2!=depth ){\n        checkAppendMsg(pCheck, zContext, \"Child page depth differs\");\n      }\n      depth = d2;\n    }\n  }\n\n  if( !pPage->leaf ){\n    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);\n    sqlite3_snprintf(sizeof(zContext), zContext, \n                     \"On page %d at right child: \", iPage);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum ){\n      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);\n    }\n#endif\n    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);\n  }\n \n  /* For intKey leaf pages, check that the min/max keys are in order\n  ** with any left/parent/right pages.\n  */\n  if( pPage->leaf && pPage->intKey ){\n    /* if we are a left child page */\n    if( pnParentMinKey ){\n      /* if we are the left most child page */\n      if( !pnParentMaxKey ){\n        if( nMaxKey > *pnParentMinKey ){\n          checkAppendMsg(pCheck, zContext, \n              \"Rowid %lld out of order (max larger than parent min of %lld)\",\n              nMaxKey, *pnParentMinKey);\n        }\n      }else{\n        if( nMinKey <= *pnParentMinKey ){\n          checkAppendMsg(pCheck, zContext, \n              \"Rowid %lld out of order (min less than parent min of %lld)\",\n              nMinKey, *pnParentMinKey);\n        }\n        if( nMaxKey > *pnParentMaxKey ){\n          checkAppendMsg(pCheck, zContext, \n              \"Rowid %lld out of order (max larger than parent max of %lld)\",\n              nMaxKey, *pnParentMaxKey);\n        }\n        *pnParentMinKey = nMaxKey;\n      }\n    /* else if we're a right child page */\n    } else if( pnParentMaxKey ){\n      if( nMinKey <= *pnParentMaxKey ){\n        checkAppendMsg(pCheck, zContext, \n            \"Rowid %lld out of order (min less than parent max of %lld)\",\n            nMinKey, *pnParentMaxKey);\n      }\n    }\n  }\n\n  /* Check for complete coverage of the page\n  */\n  data = pPage->aData;\n  hdr = pPage->hdrOffset;\n  hit = sqlite3PageMalloc( pBt->pageSize );\n  if( hit==0 ){\n    pCheck->mallocFailed = 1;\n  }else{\n    int contentOffset = get2byteNotZero(&data[hdr+5]);\n    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */\n    memset(hit+contentOffset, 0, usableSize-contentOffset);\n    memset(hit, 1, contentOffset);\n    nCell = get2byte(&data[hdr+3]);\n    cellStart = hdr + 12 - 4*pPage->leaf;\n    for(i=0; i<nCell; i++){\n      int pc = get2byte(&data[cellStart+i*2]);\n      u32 size = 65536;\n      int j;\n      if( pc<=usableSize-4 ){\n        size = cellSizePtr(pPage, &data[pc]);\n      }\n      if( (int)(pc+size-1)>=usableSize ){\n        checkAppendMsg(pCheck, 0, \n            \"Corruption detected in cell %d on page %d\",i,iPage);\n      }else{\n        for(j=pc+size-1; j>=pc; j--) hit[j]++;\n      }\n    }\n    i = get2byte(&data[hdr+1]);\n    while( i>0 ){\n      int size, j;\n      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */\n      size = get2byte(&data[i+2]);\n      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */\n      for(j=i+size-1; j>=i; j--) hit[j]++;\n      j = get2byte(&data[i]);\n      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */\n      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */\n      i = j;\n    }\n    for(i=cnt=0; i<usableSize; i++){\n      if( hit[i]==0 ){\n        cnt++;\n      }else if( hit[i]>1 ){\n        checkAppendMsg(pCheck, 0,\n          \"Multiple uses for byte %d of page %d\", i, iPage);\n        break;\n      }\n    }\n    if( cnt!=data[hdr+7] ){\n      checkAppendMsg(pCheck, 0, \n          \"Fragmentation of %d bytes reported as %d on page %d\",\n          cnt, data[hdr+7], iPage);\n    }\n  }\n  sqlite3PageFree(hit);\n  releasePage(pPage);\n  return depth+1;\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/*\n** This routine does a complete check of the given BTree file.  aRoot[] is\n** an array of pages numbers were each page number is the root page of\n** a table.  nRoot is the number of entries in aRoot.\n**\n** A read-only or read-write transaction must be opened before calling\n** this function.\n**\n** Write the number of error seen in *pnErr.  Except for some memory\n** allocation errors,  an error message held in memory obtained from\n** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is\n** returned.  If a memory allocation error occurs, NULL is returned.\n*/\nSQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(\n  Btree *p,     /* The btree to be checked */\n  int *aRoot,   /* An array of root pages numbers for individual trees */\n  int nRoot,    /* Number of entries in aRoot[] */\n  int mxErr,    /* Stop reporting errors after this many */\n  int *pnErr    /* Write number of errors seen to this variable */\n){\n  Pgno i;\n  int nRef;\n  IntegrityCk sCheck;\n  BtShared *pBt = p->pBt;\n  char zErr[100];\n\n  sqlite3BtreeEnter(p);\n  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );\n  nRef = sqlite3PagerRefcount(pBt->pPager);\n  sCheck.pBt = pBt;\n  sCheck.pPager = pBt->pPager;\n  sCheck.nPage = btreePagecount(sCheck.pBt);\n  sCheck.mxErr = mxErr;\n  sCheck.nErr = 0;\n  sCheck.mallocFailed = 0;\n  *pnErr = 0;\n  if( sCheck.nPage==0 ){\n    sqlite3BtreeLeave(p);\n    return 0;\n  }\n\n  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);\n  if( !sCheck.aPgRef ){\n    *pnErr = 1;\n    sqlite3BtreeLeave(p);\n    return 0;\n  }\n  i = PENDING_BYTE_PAGE(pBt);\n  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);\n  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);\n  sCheck.errMsg.useMalloc = 2;\n\n  /* Check the integrity of the freelist\n  */\n  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),\n            get4byte(&pBt->pPage1->aData[36]), \"Main freelist: \");\n\n  /* Check all the tables.\n  */\n  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){\n    if( aRoot[i]==0 ) continue;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( pBt->autoVacuum && aRoot[i]>1 ){\n      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);\n    }\n#endif\n    checkTreePage(&sCheck, aRoot[i], \"List of tree roots: \", NULL, NULL);\n  }\n\n  /* Make sure every page in the file is referenced\n  */\n  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n    if( getPageReferenced(&sCheck, i)==0 ){\n      checkAppendMsg(&sCheck, 0, \"Page %d is never used\", i);\n    }\n#else\n    /* If the database supports auto-vacuum, make sure no tables contain\n    ** references to pointer-map pages.\n    */\n    if( getPageReferenced(&sCheck, i)==0 && \n       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){\n      checkAppendMsg(&sCheck, 0, \"Page %d is never used\", i);\n    }\n    if( getPageReferenced(&sCheck, i)!=0 && \n       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){\n      checkAppendMsg(&sCheck, 0, \"Pointer map page %d is referenced\", i);\n    }\n#endif\n  }\n\n  /* Make sure this analysis did not leave any unref() pages.\n  ** This is an internal consistency check; an integrity check\n  ** of the integrity check.\n  */\n  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){\n    checkAppendMsg(&sCheck, 0, \n      \"Outstanding page count goes from %d to %d during this analysis\",\n      nRef, sqlite3PagerRefcount(pBt->pPager)\n    );\n  }\n\n  /* Clean  up and report errors.\n  */\n  sqlite3BtreeLeave(p);\n  sqlite3_free(sCheck.aPgRef);\n  if( sCheck.mallocFailed ){\n    sqlite3StrAccumReset(&sCheck.errMsg);\n    *pnErr = sCheck.nErr+1;\n    return 0;\n  }\n  *pnErr = sCheck.nErr;\n  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);\n  return sqlite3StrAccumFinish(&sCheck.errMsg);\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n/*\n** Return the full pathname of the underlying database file.  Return\n** an empty string if the database is in-memory or a TEMP database.\n**\n** The pager filename is invariant as long as the pager is\n** open so it is safe to access without the BtShared mutex.\n*/\nSQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){\n  assert( p->pBt->pPager!=0 );\n  return sqlite3PagerFilename(p->pBt->pPager, 1);\n}\n\n/*\n** Return the pathname of the journal file for this database. The return\n** value of this routine is the same regardless of whether the journal file\n** has been created or not.\n**\n** The pager journal filename is invariant as long as the pager is\n** open so it is safe to access without the BtShared mutex.\n*/\nSQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){\n  assert( p->pBt->pPager!=0 );\n  return sqlite3PagerJournalname(p->pBt->pPager);\n}\n\n/*\n** Return non-zero if a transaction is active.\n*/\nSQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){\n  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );\n  return (p && (p->inTrans==TRANS_WRITE));\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Run a checkpoint on the Btree passed as the first argument.\n**\n** Return SQLITE_LOCKED if this or any other connection has an open \n** transaction on the shared-cache the argument Btree is connected to.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){\n  int rc = SQLITE_OK;\n  if( p ){\n    BtShared *pBt = p->pBt;\n    sqlite3BtreeEnter(p);\n    if( pBt->inTransaction!=TRANS_NONE ){\n      rc = SQLITE_LOCKED;\n    }else{\n      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n#endif\n\n/*\n** Return non-zero if a read (or write) transaction is active.\n*/\nSQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){\n  assert( p );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  return p->inTrans!=TRANS_NONE;\n}\n\nSQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){\n  assert( p );\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  return p->nBackup!=0;\n}\n\n/*\n** This function returns a pointer to a blob of memory associated with\n** a single shared-btree. The memory is used by client code for its own\n** purposes (for example, to store a high-level schema associated with \n** the shared-btree). The btree layer manages reference counting issues.\n**\n** The first time this is called on a shared-btree, nBytes bytes of memory\n** are allocated, zeroed, and returned to the caller. For each subsequent \n** call the nBytes parameter is ignored and a pointer to the same blob\n** of memory returned. \n**\n** If the nBytes parameter is 0 and the blob of memory has not yet been\n** allocated, a null pointer is returned. If the blob has already been\n** allocated, it is returned as normal.\n**\n** Just before the shared-btree is closed, the function passed as the \n** xFree argument when the memory allocation was made is invoked on the \n** blob of allocated memory. The xFree function should not call sqlite3_free()\n** on the memory, the btree layer does that.\n*/\nSQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){\n  BtShared *pBt = p->pBt;\n  sqlite3BtreeEnter(p);\n  if( !pBt->pSchema && nBytes ){\n    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);\n    pBt->xFreeSchema = xFree;\n  }\n  sqlite3BtreeLeave(p);\n  return pBt->pSchema;\n}\n\n/*\n** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared \n** btree as the argument handle holds an exclusive lock on the \n** sqlite_master table. Otherwise SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){\n  int rc;\n  assert( sqlite3_mutex_held(p->db->mutex) );\n  sqlite3BtreeEnter(p);\n  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);\n  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );\n  sqlite3BtreeLeave(p);\n  return rc;\n}\n\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** Obtain a lock on the table whose root page is iTab.  The\n** lock is a write lock if isWritelock is true or a read lock\n** if it is false.\n*/\nSQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){\n  int rc = SQLITE_OK;\n  assert( p->inTrans!=TRANS_NONE );\n  if( p->sharable ){\n    u8 lockType = READ_LOCK + isWriteLock;\n    assert( READ_LOCK+1==WRITE_LOCK );\n    assert( isWriteLock==0 || isWriteLock==1 );\n\n    sqlite3BtreeEnter(p);\n    rc = querySharedCacheTableLock(p, iTab, lockType);\n    if( rc==SQLITE_OK ){\n      rc = setSharedCacheTableLock(p, iTab, lockType);\n    }\n    sqlite3BtreeLeave(p);\n  }\n  return rc;\n}\n#endif\n\n#ifndef SQLITE_OMIT_INCRBLOB\n/*\n** Argument pCsr must be a cursor opened for writing on an \n** INTKEY table currently pointing at a valid table entry. \n** This function modifies the data stored as part of that entry.\n**\n** Only the data content may only be modified, it is not possible to \n** change the length of the data stored. If this function is called with\n** parameters that attempt to write past the end of the existing data,\n** no modifications are made and SQLITE_CORRUPT is returned.\n*/\nSQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){\n  int rc;\n  assert( cursorHoldsMutex(pCsr) );\n  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );\n  assert( pCsr->isIncrblobHandle );\n\n  rc = restoreCursorPosition(pCsr);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n  assert( pCsr->eState!=CURSOR_REQUIRESEEK );\n  if( pCsr->eState!=CURSOR_VALID ){\n    return SQLITE_ABORT;\n  }\n\n  /* Check some assumptions: \n  **   (a) the cursor is open for writing,\n  **   (b) there is a read/write transaction open,\n  **   (c) the connection holds a write-lock on the table (if required),\n  **   (d) there are no conflicting read-locks, and\n  **   (e) the cursor points at a valid row of an intKey table.\n  */\n  if( !pCsr->wrFlag ){\n    return SQLITE_READONLY;\n  }\n  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0\n              && pCsr->pBt->inTransaction==TRANS_WRITE );\n  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );\n  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );\n  assert( pCsr->apPage[pCsr->iPage]->intKey );\n\n  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);\n}\n\n/* \n** Set a flag on this cursor to cache the locations of pages from the \n** overflow list for the current row. This is used by cursors opened\n** for incremental blob IO only.\n**\n** This function sets a flag only. The actual page location cache\n** (stored in BtCursor.aOverflow[]) is allocated and used by function\n** accessPayload() (the worker function for sqlite3BtreeData() and\n** sqlite3BtreePutData()).\n*/\nSQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){\n  assert( cursorHoldsMutex(pCur) );\n  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );\n  invalidateOverflowCache(pCur);\n  pCur->isIncrblobHandle = 1;\n}\n#endif\n\n/*\n** Set both the \"read version\" (single byte at byte offset 18) and \n** \"write version\" (single byte at byte offset 19) fields in the database\n** header to iVersion.\n*/\nSQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){\n  BtShared *pBt = pBtree->pBt;\n  int rc;                         /* Return code */\n \n  assert( iVersion==1 || iVersion==2 );\n\n  /* If setting the version fields to 1, do not automatically open the\n  ** WAL connection, even if the version fields are currently set to 2.\n  */\n  pBt->btsFlags &= ~BTS_NO_WAL;\n  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;\n\n  rc = sqlite3BtreeBeginTrans(pBtree, 0);\n  if( rc==SQLITE_OK ){\n    u8 *aData = pBt->pPage1->aData;\n    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){\n      rc = sqlite3BtreeBeginTrans(pBtree, 2);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);\n        if( rc==SQLITE_OK ){\n          aData[18] = (u8)iVersion;\n          aData[19] = (u8)iVersion;\n        }\n      }\n    }\n  }\n\n  pBt->btsFlags &= ~BTS_NO_WAL;\n  return rc;\n}\n\n/*\n** set the mask of hint flags for cursor pCsr. Currently the only valid\n** values are 0 and BTREE_BULKLOAD.\n*/\nSQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){\n  assert( mask==BTREE_BULKLOAD || mask==0 );\n  pCsr->hints = mask;\n}\n\n/************** End of btree.c ***********************************************/\n/************** Begin file backup.c ******************************************/\n/*\n** 2009 January 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation of the sqlite3_backup_XXX() \n** API functions and the related features.\n*/\n\n/* Macro to find the minimum of two numeric values.\n*/\n#ifndef MIN\n# define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n\n/*\n** Structure allocated for each backup operation.\n*/\nstruct sqlite3_backup {\n  sqlite3* pDestDb;        /* Destination database handle */\n  Btree *pDest;            /* Destination b-tree file */\n  u32 iDestSchema;         /* Original schema cookie in destination */\n  int bDestLocked;         /* True once a write-transaction is open on pDest */\n\n  Pgno iNext;              /* Page number of the next source page to copy */\n  sqlite3* pSrcDb;         /* Source database handle */\n  Btree *pSrc;             /* Source b-tree file */\n\n  int rc;                  /* Backup process error code */\n\n  /* These two variables are set by every call to backup_step(). They are\n  ** read by calls to backup_remaining() and backup_pagecount().\n  */\n  Pgno nRemaining;         /* Number of pages left to copy */\n  Pgno nPagecount;         /* Total number of pages to copy */\n\n  int isAttached;          /* True once backup has been registered with pager */\n  sqlite3_backup *pNext;   /* Next backup associated with source pager */\n};\n\n/*\n** THREAD SAFETY NOTES:\n**\n**   Once it has been created using backup_init(), a single sqlite3_backup\n**   structure may be accessed via two groups of thread-safe entry points:\n**\n**     * Via the sqlite3_backup_XXX() API function backup_step() and \n**       backup_finish(). Both these functions obtain the source database\n**       handle mutex and the mutex associated with the source BtShared \n**       structure, in that order.\n**\n**     * Via the BackupUpdate() and BackupRestart() functions, which are\n**       invoked by the pager layer to report various state changes in\n**       the page cache associated with the source database. The mutex\n**       associated with the source database BtShared structure will always \n**       be held when either of these functions are invoked.\n**\n**   The other sqlite3_backup_XXX() API functions, backup_remaining() and\n**   backup_pagecount() are not thread-safe functions. If they are called\n**   while some other thread is calling backup_step() or backup_finish(),\n**   the values returned may be invalid. There is no way for a call to\n**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()\n**   or backup_pagecount().\n**\n**   Depending on the SQLite configuration, the database handles and/or\n**   the Btree objects may have their own mutexes that require locking.\n**   Non-sharable Btrees (in-memory databases for example), do not have\n**   associated mutexes.\n*/\n\n/*\n** Return a pointer corresponding to database zDb (i.e. \"main\", \"temp\")\n** in connection handle pDb. If such a database cannot be found, return\n** a NULL pointer and write an error message to pErrorDb.\n**\n** If the \"temp\" database is requested, it may need to be opened by this \n** function. If an error occurs while doing so, return 0 and write an \n** error message to pErrorDb.\n*/\nstatic Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){\n  int i = sqlite3FindDbName(pDb, zDb);\n\n  if( i==1 ){\n    Parse *pParse;\n    int rc = 0;\n    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));\n    if( pParse==0 ){\n      sqlite3Error(pErrorDb, SQLITE_NOMEM, \"out of memory\");\n      rc = SQLITE_NOMEM;\n    }else{\n      pParse->db = pDb;\n      if( sqlite3OpenTempDatabase(pParse) ){\n        sqlite3Error(pErrorDb, pParse->rc, \"%s\", pParse->zErrMsg);\n        rc = SQLITE_ERROR;\n      }\n      sqlite3DbFree(pErrorDb, pParse->zErrMsg);\n      sqlite3StackFree(pErrorDb, pParse);\n    }\n    if( rc ){\n      return 0;\n    }\n  }\n\n  if( i<0 ){\n    sqlite3Error(pErrorDb, SQLITE_ERROR, \"unknown database %s\", zDb);\n    return 0;\n  }\n\n  return pDb->aDb[i].pBt;\n}\n\n/*\n** Attempt to set the page size of the destination to match the page size\n** of the source.\n*/\nstatic int setDestPgsz(sqlite3_backup *p){\n  int rc;\n  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);\n  return rc;\n}\n\n/*\n** Create an sqlite3_backup process to copy the contents of zSrcDb from\n** connection handle pSrcDb to zDestDb in pDestDb. If successful, return\n** a pointer to the new sqlite3_backup object.\n**\n** If an error occurs, NULL is returned and an error code and error message\n** stored in database handle pDestDb.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3* pDestDb,                     /* Database to write to */\n  const char *zDestDb,                  /* Name of database within pDestDb */\n  sqlite3* pSrcDb,                      /* Database connection to read from */\n  const char *zSrcDb                    /* Name of database within pSrcDb */\n){\n  sqlite3_backup *p;                    /* Value to return */\n\n  /* Lock the source database handle. The destination database\n  ** handle is not locked in this routine, but it is locked in\n  ** sqlite3_backup_step(). The user is required to ensure that no\n  ** other thread accesses the destination handle for the duration\n  ** of the backup operation.  Any attempt to use the destination\n  ** database connection while a backup is in progress may cause\n  ** a malfunction or a deadlock.\n  */\n  sqlite3_mutex_enter(pSrcDb->mutex);\n  sqlite3_mutex_enter(pDestDb->mutex);\n\n  if( pSrcDb==pDestDb ){\n    sqlite3Error(\n        pDestDb, SQLITE_ERROR, \"source and destination must be distinct\"\n    );\n    p = 0;\n  }else {\n    /* Allocate space for a new sqlite3_backup object...\n    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a\n    ** call to sqlite3_backup_init() and is destroyed by a call to\n    ** sqlite3_backup_finish(). */\n    p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));\n    if( !p ){\n      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);\n    }\n  }\n\n  /* If the allocation succeeded, populate the new object. */\n  if( p ){\n    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);\n    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);\n    p->pDestDb = pDestDb;\n    p->pSrcDb = pSrcDb;\n    p->iNext = 1;\n    p->isAttached = 0;\n\n    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){\n      /* One (or both) of the named databases did not exist or an OOM\n      ** error was hit.  The error has already been written into the\n      ** pDestDb handle.  All that is left to do here is free the\n      ** sqlite3_backup structure.\n      */\n      sqlite3_free(p);\n      p = 0;\n    }\n  }\n  if( p ){\n    p->pSrc->nBackup++;\n  }\n\n  sqlite3_mutex_leave(pDestDb->mutex);\n  sqlite3_mutex_leave(pSrcDb->mutex);\n  return p;\n}\n\n/*\n** Argument rc is an SQLite error code. Return true if this error is \n** considered fatal if encountered during a backup operation. All errors\n** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.\n*/\nstatic int isFatalError(int rc){\n  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));\n}\n\n/*\n** Parameter zSrcData points to a buffer containing the data for \n** page iSrcPg from the source database. Copy this data into the \n** destination database.\n*/\nstatic int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){\n  Pager * const pDestPager = sqlite3BtreePager(p->pDest);\n  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);\n  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);\n  const int nCopy = MIN(nSrcPgsz, nDestPgsz);\n  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;\n#ifdef SQLITE_HAS_CODEC\n  int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);\n  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);\n#endif\n\n  int rc = SQLITE_OK;\n  i64 iOff;\n\n  assert( p->bDestLocked );\n  assert( !isFatalError(p->rc) );\n  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );\n  assert( zSrcData );\n\n  /* Catch the case where the destination is an in-memory database and the\n  ** page sizes of the source and destination differ. \n  */\n  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){\n    rc = SQLITE_READONLY;\n  }\n\n#ifdef SQLITE_HAS_CODEC\n  /* Backup is not possible if the page size of the destination is changing\n  ** and a codec is in use.\n  */\n  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){\n    rc = SQLITE_READONLY;\n  }\n\n  /* Backup is not possible if the number of bytes of reserve space differ\n  ** between source and destination.  If there is a difference, try to\n  ** fix the destination to agree with the source.  If that is not possible,\n  ** then the backup cannot proceed.\n  */\n  if( nSrcReserve!=nDestReserve ){\n    u32 newPgsz = nSrcPgsz;\n    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);\n    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;\n  }\n#endif\n\n  /* This loop runs once for each destination page spanned by the source \n  ** page. For each iteration, variable iOff is set to the byte offset\n  ** of the destination page.\n  */\n  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){\n    DbPage *pDestPg = 0;\n    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;\n    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;\n    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))\n     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))\n    ){\n      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];\n      u8 *zDestData = sqlite3PagerGetData(pDestPg);\n      u8 *zOut = &zDestData[iOff%nDestPgsz];\n\n      /* Copy the data from the source page into the destination page.\n      ** Then clear the Btree layer MemPage.isInit flag. Both this module\n      ** and the pager code use this trick (clearing the first byte\n      ** of the page 'extra' space to invalidate the Btree layers\n      ** cached parse of the page). MemPage.isInit is marked \n      ** \"MUST BE FIRST\" for this purpose.\n      */\n      memcpy(zOut, zIn, nCopy);\n      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;\n    }\n    sqlite3PagerUnref(pDestPg);\n  }\n\n  return rc;\n}\n\n/*\n** If pFile is currently larger than iSize bytes, then truncate it to\n** exactly iSize bytes. If pFile is not larger than iSize bytes, then\n** this function is a no-op.\n**\n** Return SQLITE_OK if everything is successful, or an SQLite error \n** code if an error occurs.\n*/\nstatic int backupTruncateFile(sqlite3_file *pFile, i64 iSize){\n  i64 iCurrent;\n  int rc = sqlite3OsFileSize(pFile, &iCurrent);\n  if( rc==SQLITE_OK && iCurrent>iSize ){\n    rc = sqlite3OsTruncate(pFile, iSize);\n  }\n  return rc;\n}\n\n/*\n** Register this backup object with the associated source pager for\n** callbacks when pages are changed or the cache invalidated.\n*/\nstatic void attachBackupObject(sqlite3_backup *p){\n  sqlite3_backup **pp;\n  assert( sqlite3BtreeHoldsMutex(p->pSrc) );\n  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));\n  p->pNext = *pp;\n  *pp = p;\n  p->isAttached = 1;\n}\n\n/*\n** Copy nPage pages from the source b-tree to the destination.\n*/\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){\n  int rc;\n  int destMode;       /* Destination journal mode */\n  int pgszSrc = 0;    /* Source page size */\n  int pgszDest = 0;   /* Destination page size */\n\n  sqlite3_mutex_enter(p->pSrcDb->mutex);\n  sqlite3BtreeEnter(p->pSrc);\n  if( p->pDestDb ){\n    sqlite3_mutex_enter(p->pDestDb->mutex);\n  }\n\n  rc = p->rc;\n  if( !isFatalError(rc) ){\n    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */\n    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */\n    int ii;                            /* Iterator variable */\n    int nSrcPage = -1;                 /* Size of source db in pages */\n    int bCloseTrans = 0;               /* True if src db requires unlocking */\n\n    /* If the source pager is currently in a write-transaction, return\n    ** SQLITE_BUSY immediately.\n    */\n    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){\n      rc = SQLITE_BUSY;\n    }else{\n      rc = SQLITE_OK;\n    }\n\n    /* Lock the destination database, if it is not locked already. */\n    if( SQLITE_OK==rc && p->bDestLocked==0\n     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) \n    ){\n      p->bDestLocked = 1;\n      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);\n    }\n\n    /* If there is no open read-transaction on the source database, open\n    ** one now. If a transaction is opened here, then it will be closed\n    ** before this function exits.\n    */\n    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){\n      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);\n      bCloseTrans = 1;\n    }\n\n    /* Do not allow backup if the destination database is in WAL mode\n    ** and the page sizes are different between source and destination */\n    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);\n    pgszDest = sqlite3BtreeGetPageSize(p->pDest);\n    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));\n    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){\n      rc = SQLITE_READONLY;\n    }\n  \n    /* Now that there is a read-lock on the source database, query the\n    ** source pager for the number of pages in the database.\n    */\n    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);\n    assert( nSrcPage>=0 );\n    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){\n      const Pgno iSrcPg = p->iNext;                 /* Source page number */\n      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){\n        DbPage *pSrcPg;                             /* Source page object */\n        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);\n        if( rc==SQLITE_OK ){\n          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));\n          sqlite3PagerUnref(pSrcPg);\n        }\n      }\n      p->iNext++;\n    }\n    if( rc==SQLITE_OK ){\n      p->nPagecount = nSrcPage;\n      p->nRemaining = nSrcPage+1-p->iNext;\n      if( p->iNext>(Pgno)nSrcPage ){\n        rc = SQLITE_DONE;\n      }else if( !p->isAttached ){\n        attachBackupObject(p);\n      }\n    }\n  \n    /* Update the schema version field in the destination database. This\n    ** is to make sure that the schema-version really does change in\n    ** the case where the source and destination databases have the\n    ** same schema version.\n    */\n    if( rc==SQLITE_DONE ){\n      rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);\n      if( rc==SQLITE_OK ){\n        if( p->pDestDb ){\n          sqlite3ResetAllSchemasOfConnection(p->pDestDb);\n        }\n        if( destMode==PAGER_JOURNALMODE_WAL ){\n          rc = sqlite3BtreeSetVersion(p->pDest, 2);\n        }\n      }\n      if( rc==SQLITE_OK ){\n        int nDestTruncate;\n        /* Set nDestTruncate to the final number of pages in the destination\n        ** database. The complication here is that the destination page\n        ** size may be different to the source page size. \n        **\n        ** If the source page size is smaller than the destination page size, \n        ** round up. In this case the call to sqlite3OsTruncate() below will\n        ** fix the size of the file. However it is important to call\n        ** sqlite3PagerTruncateImage() here so that any pages in the \n        ** destination file that lie beyond the nDestTruncate page mark are\n        ** journalled by PagerCommitPhaseOne() before they are destroyed\n        ** by the file truncation.\n        */\n        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );\n        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );\n        if( pgszSrc<pgszDest ){\n          int ratio = pgszDest/pgszSrc;\n          nDestTruncate = (nSrcPage+ratio-1)/ratio;\n          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){\n            nDestTruncate--;\n          }\n        }else{\n          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);\n        }\n        sqlite3PagerTruncateImage(pDestPager, nDestTruncate);\n\n        if( pgszSrc<pgszDest ){\n          /* If the source page-size is smaller than the destination page-size,\n          ** two extra things may need to happen:\n          **\n          **   * The destination may need to be truncated, and\n          **\n          **   * Data stored on the pages immediately following the \n          **     pending-byte page in the source database may need to be\n          **     copied into the destination database.\n          */\n          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;\n          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);\n          i64 iOff;\n          i64 iEnd;\n\n          assert( pFile );\n          assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (\n                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)\n             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest\n          ));\n\n          /* This call ensures that all data required to recreate the original\n          ** database has been stored in the journal for pDestPager and the\n          ** journal synced to disk. So at this point we may safely modify\n          ** the database file in any way, knowing that if a power failure\n          ** occurs, the original database will be reconstructed from the \n          ** journal file.  */\n          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);\n\n          /* Write the extra pages and truncate the database file as required */\n          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);\n          for(\n            iOff=PENDING_BYTE+pgszSrc; \n            rc==SQLITE_OK && iOff<iEnd; \n            iOff+=pgszSrc\n          ){\n            PgHdr *pSrcPg = 0;\n            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);\n            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);\n            if( rc==SQLITE_OK ){\n              u8 *zData = sqlite3PagerGetData(pSrcPg);\n              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);\n            }\n            sqlite3PagerUnref(pSrcPg);\n          }\n          if( rc==SQLITE_OK ){\n            rc = backupTruncateFile(pFile, iSize);\n          }\n\n          /* Sync the database file to disk. */\n          if( rc==SQLITE_OK ){\n            rc = sqlite3PagerSync(pDestPager);\n          }\n        }else{\n          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);\n        }\n    \n        /* Finish committing the transaction to the destination database. */\n        if( SQLITE_OK==rc\n         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))\n        ){\n          rc = SQLITE_DONE;\n        }\n      }\n    }\n  \n    /* If bCloseTrans is true, then this function opened a read transaction\n    ** on the source database. Close the read transaction here. There is\n    ** no need to check the return values of the btree methods here, as\n    ** \"committing\" a read-only transaction cannot fail.\n    */\n    if( bCloseTrans ){\n      TESTONLY( int rc2 );\n      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);\n      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);\n      assert( rc2==SQLITE_OK );\n    }\n  \n    if( rc==SQLITE_IOERR_NOMEM ){\n      rc = SQLITE_NOMEM;\n    }\n    p->rc = rc;\n  }\n  if( p->pDestDb ){\n    sqlite3_mutex_leave(p->pDestDb->mutex);\n  }\n  sqlite3BtreeLeave(p->pSrc);\n  sqlite3_mutex_leave(p->pSrcDb->mutex);\n  return rc;\n}\n\n/*\n** Release all resources associated with an sqlite3_backup* handle.\n*/\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){\n  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */\n  sqlite3 *pSrcDb;                     /* Source database connection */\n  int rc;                              /* Value to return */\n\n  /* Enter the mutexes */\n  if( p==0 ) return SQLITE_OK;\n  pSrcDb = p->pSrcDb;\n  sqlite3_mutex_enter(pSrcDb->mutex);\n  sqlite3BtreeEnter(p->pSrc);\n  if( p->pDestDb ){\n    sqlite3_mutex_enter(p->pDestDb->mutex);\n  }\n\n  /* Detach this backup from the source pager. */\n  if( p->pDestDb ){\n    p->pSrc->nBackup--;\n  }\n  if( p->isAttached ){\n    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));\n    while( *pp!=p ){\n      pp = &(*pp)->pNext;\n    }\n    *pp = p->pNext;\n  }\n\n  /* If a transaction is still open on the Btree, roll it back. */\n  sqlite3BtreeRollback(p->pDest, SQLITE_OK);\n\n  /* Set the error code of the destination database handle. */\n  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;\n  sqlite3Error(p->pDestDb, rc, 0);\n\n  /* Exit the mutexes and free the backup context structure. */\n  if( p->pDestDb ){\n    sqlite3LeaveMutexAndCloseZombie(p->pDestDb);\n  }\n  sqlite3BtreeLeave(p->pSrc);\n  if( p->pDestDb ){\n    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a\n    ** call to sqlite3_backup_init() and is destroyed by a call to\n    ** sqlite3_backup_finish(). */\n    sqlite3_free(p);\n  }\n  sqlite3LeaveMutexAndCloseZombie(pSrcDb);\n  return rc;\n}\n\n/*\n** Return the number of pages still to be backed up as of the most recent\n** call to sqlite3_backup_step().\n*/\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){\n  return p->nRemaining;\n}\n\n/*\n** Return the total number of pages in the source database as of the most \n** recent call to sqlite3_backup_step().\n*/\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){\n  return p->nPagecount;\n}\n\n/*\n** This function is called after the contents of page iPage of the\n** source database have been modified. If page iPage has already been \n** copied into the destination database, then the data written to the\n** destination is now invalidated. The destination copy of iPage needs\n** to be updated with the new data before the backup operation is\n** complete.\n**\n** It is assumed that the mutex associated with the BtShared object\n** corresponding to the source database is held when this function is\n** called.\n*/\nSQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){\n  sqlite3_backup *p;                   /* Iterator variable */\n  for(p=pBackup; p; p=p->pNext){\n    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );\n    if( !isFatalError(p->rc) && iPage<p->iNext ){\n      /* The backup process p has already copied page iPage. But now it\n      ** has been modified by a transaction on the source pager. Copy\n      ** the new data into the backup.\n      */\n      int rc;\n      assert( p->pDestDb );\n      sqlite3_mutex_enter(p->pDestDb->mutex);\n      rc = backupOnePage(p, iPage, aData);\n      sqlite3_mutex_leave(p->pDestDb->mutex);\n      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );\n      if( rc!=SQLITE_OK ){\n        p->rc = rc;\n      }\n    }\n  }\n}\n\n/*\n** Restart the backup process. This is called when the pager layer\n** detects that the database has been modified by an external database\n** connection. In this case there is no way of knowing which of the\n** pages that have been copied into the destination database are still \n** valid and which are not, so the entire process needs to be restarted.\n**\n** It is assumed that the mutex associated with the BtShared object\n** corresponding to the source database is held when this function is\n** called.\n*/\nSQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){\n  sqlite3_backup *p;                   /* Iterator variable */\n  for(p=pBackup; p; p=p->pNext){\n    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );\n    p->iNext = 1;\n  }\n}\n\n#ifndef SQLITE_OMIT_VACUUM\n/*\n** Copy the complete content of pBtFrom into pBtTo.  A transaction\n** must be active for both files.\n**\n** The size of file pTo may be reduced by this operation. If anything \n** goes wrong, the transaction on pTo is rolled back. If successful, the \n** transaction is committed before returning.\n*/\nSQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){\n  int rc;\n  sqlite3_file *pFd;              /* File descriptor for database pTo */\n  sqlite3_backup b;\n  sqlite3BtreeEnter(pTo);\n  sqlite3BtreeEnter(pFrom);\n\n  assert( sqlite3BtreeIsInTrans(pTo) );\n  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));\n  if( pFd->pMethods ){\n    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);\n    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);\n    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;\n    if( rc ) goto copy_finished;\n  }\n\n  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set\n  ** to 0. This is used by the implementations of sqlite3_backup_step()\n  ** and sqlite3_backup_finish() to detect that they are being called\n  ** from this function, not directly by the user.\n  */\n  memset(&b, 0, sizeof(b));\n  b.pSrcDb = pFrom->db;\n  b.pSrc = pFrom;\n  b.pDest = pTo;\n  b.iNext = 1;\n\n  /* 0x7FFFFFFF is the hard limit for the number of pages in a database\n  ** file. By passing this as the number of pages to copy to\n  ** sqlite3_backup_step(), we can guarantee that the copy finishes \n  ** within a single call (unless an error occurs). The assert() statement\n  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE \n  ** or an error code.\n  */\n  sqlite3_backup_step(&b, 0x7FFFFFFF);\n  assert( b.rc!=SQLITE_OK );\n  rc = sqlite3_backup_finish(&b);\n  if( rc==SQLITE_OK ){\n    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;\n  }else{\n    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));\n  }\n\n  assert( sqlite3BtreeIsInTrans(pTo)==0 );\ncopy_finished:\n  sqlite3BtreeLeave(pFrom);\n  sqlite3BtreeLeave(pTo);\n  return rc;\n}\n#endif /* SQLITE_OMIT_VACUUM */\n\n/************** End of backup.c **********************************************/\n/************** Begin file vdbemem.c *****************************************/\n/*\n** 2004 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to manipulate \"Mem\" structure.  A \"Mem\"\n** stores a single value in the VDBE.  Mem is an opaque structure visible\n** only within the VDBE.  Interface routines refer to a Mem using the\n** name sqlite_value\n*/\n\n/*\n** If pMem is an object with a valid string representation, this routine\n** ensures the internal encoding for the string representation is\n** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.\n**\n** If pMem is not a string object, or the encoding of the string\n** representation is already stored using the requested encoding, then this\n** routine is a no-op.\n**\n** SQLITE_OK is returned if the conversion is successful (or not required).\n** SQLITE_NOMEM may be returned if a malloc() fails during conversion\n** between formats.\n*/\nSQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){\n  int rc;\n  assert( (pMem->flags&MEM_RowSet)==0 );\n  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE\n           || desiredEnc==SQLITE_UTF16BE );\n  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){\n    return SQLITE_OK;\n  }\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n#ifdef SQLITE_OMIT_UTF16\n  return SQLITE_ERROR;\n#else\n\n  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,\n  ** then the encoding of the value may not have changed.\n  */\n  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);\n  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);\n  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);\n  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);\n  return rc;\n#endif\n}\n\n/*\n** Make sure pMem->z points to a writable allocation of at least \n** n bytes.\n**\n** If the third argument passed to this function is true, then memory\n** cell pMem must contain a string or blob. In this case the content is\n** preserved. Otherwise, if the third parameter to this function is false,\n** any current string or blob value may be discarded.\n**\n** This function sets the MEM_Dyn flag and clears any xDel callback.\n** It also clears MEM_Ephem and MEM_Static. If the preserve flag is \n** not set, Mem.n is zeroed.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){\n  assert( 1 >=\n    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +\n    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + \n    ((pMem->flags&MEM_Ephem) ? 1 : 0) + \n    ((pMem->flags&MEM_Static) ? 1 : 0)\n  );\n  assert( (pMem->flags&MEM_RowSet)==0 );\n\n  /* If the preserve flag is set to true, then the memory cell must already\n  ** contain a valid string or blob value.  */\n  assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );\n\n  if( n<32 ) n = 32;\n  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){\n    if( preserve && pMem->z==pMem->zMalloc ){\n      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);\n      preserve = 0;\n    }else{\n      sqlite3DbFree(pMem->db, pMem->zMalloc);\n      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);\n    }\n  }\n\n  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){\n    memcpy(pMem->zMalloc, pMem->z, pMem->n);\n  }\n  if( pMem->flags&MEM_Dyn && pMem->xDel ){\n    assert( pMem->xDel!=SQLITE_DYNAMIC );\n    pMem->xDel((void *)(pMem->z));\n  }\n\n  pMem->z = pMem->zMalloc;\n  if( pMem->z==0 ){\n    pMem->flags = MEM_Null;\n  }else{\n    pMem->flags &= ~(MEM_Ephem|MEM_Static);\n  }\n  pMem->xDel = 0;\n  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);\n}\n\n/*\n** Make the given Mem object MEM_Dyn.  In other words, make it so\n** that any TEXT or BLOB content is stored in memory obtained from\n** malloc().  In this way, we know that the memory is safe to be\n** overwritten or altered.\n**\n** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){\n  int f;\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( (pMem->flags&MEM_RowSet)==0 );\n  ExpandBlob(pMem);\n  f = pMem->flags;\n  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){\n    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){\n      return SQLITE_NOMEM;\n    }\n    pMem->z[pMem->n] = 0;\n    pMem->z[pMem->n+1] = 0;\n    pMem->flags |= MEM_Term;\n#ifdef SQLITE_DEBUG\n    pMem->pScopyFrom = 0;\n#endif\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** If the given Mem* has a zero-filled tail, turn it into an ordinary\n** blob stored in dynamically allocated space.\n*/\n#ifndef SQLITE_OMIT_INCRBLOB\nSQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){\n  if( pMem->flags & MEM_Zero ){\n    int nByte;\n    assert( pMem->flags&MEM_Blob );\n    assert( (pMem->flags&MEM_RowSet)==0 );\n    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n\n    /* Set nByte to the number of bytes required to store the expanded blob. */\n    nByte = pMem->n + pMem->u.nZero;\n    if( nByte<=0 ){\n      nByte = 1;\n    }\n    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){\n      return SQLITE_NOMEM;\n    }\n\n    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);\n    pMem->n += pMem->u.nZero;\n    pMem->flags &= ~(MEM_Zero|MEM_Term);\n  }\n  return SQLITE_OK;\n}\n#endif\n\n\n/*\n** Make sure the given Mem is \\u0000 terminated.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){\n    return SQLITE_OK;   /* Nothing to do */\n  }\n  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){\n    return SQLITE_NOMEM;\n  }\n  pMem->z[pMem->n] = 0;\n  pMem->z[pMem->n+1] = 0;\n  pMem->flags |= MEM_Term;\n  return SQLITE_OK;\n}\n\n/*\n** Add MEM_Str to the set of representations for the given Mem.  Numbers\n** are converted using sqlite3_snprintf().  Converting a BLOB to a string\n** is a no-op.\n**\n** Existing representations MEM_Int and MEM_Real are *not* invalidated.\n**\n** A MEM_Null value will never be passed to this function. This function is\n** used for converting values to text for returning to the user (i.e. via\n** sqlite3_value_text()), or for ensuring that values to be used as btree\n** keys are strings. In the former case a NULL pointer is returned the\n** user and the later is an internal programming error.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){\n  int rc = SQLITE_OK;\n  int fg = pMem->flags;\n  const int nByte = 32;\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( !(fg&MEM_Zero) );\n  assert( !(fg&(MEM_Str|MEM_Blob)) );\n  assert( fg&(MEM_Int|MEM_Real) );\n  assert( (pMem->flags&MEM_RowSet)==0 );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n\n  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){\n    return SQLITE_NOMEM;\n  }\n\n  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8\n  ** string representation of the value. Then, if the required encoding\n  ** is UTF-16le or UTF-16be do a translation.\n  ** \n  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.\n  */\n  if( fg & MEM_Int ){\n    sqlite3_snprintf(nByte, pMem->z, \"%lld\", pMem->u.i);\n  }else{\n    assert( fg & MEM_Real );\n    sqlite3_snprintf(nByte, pMem->z, \"%!.15g\", pMem->r);\n  }\n  pMem->n = sqlite3Strlen30(pMem->z);\n  pMem->enc = SQLITE_UTF8;\n  pMem->flags |= MEM_Str|MEM_Term;\n  sqlite3VdbeChangeEncoding(pMem, enc);\n  return rc;\n}\n\n/*\n** Memory cell pMem contains the context of an aggregate function.\n** This routine calls the finalize method for that function.  The\n** result of the aggregate is stored back into pMem.\n**\n** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK\n** otherwise.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){\n  int rc = SQLITE_OK;\n  if( ALWAYS(pFunc && pFunc->xFinalize) ){\n    sqlite3_context ctx;\n    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );\n    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n    memset(&ctx, 0, sizeof(ctx));\n    ctx.s.flags = MEM_Null;\n    ctx.s.db = pMem->db;\n    ctx.pMem = pMem;\n    ctx.pFunc = pFunc;\n    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */\n    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );\n    sqlite3DbFree(pMem->db, pMem->zMalloc);\n    memcpy(pMem, &ctx.s, sizeof(ctx.s));\n    rc = ctx.isError;\n  }\n  return rc;\n}\n\n/*\n** If the memory cell contains a string value that must be freed by\n** invoking an external callback, free it now. Calling this function\n** does not free any Mem.zMalloc buffer.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){\n  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );\n  if( p->flags&MEM_Agg ){\n    sqlite3VdbeMemFinalize(p, p->u.pDef);\n    assert( (p->flags & MEM_Agg)==0 );\n    sqlite3VdbeMemRelease(p);\n  }else if( p->flags&MEM_Dyn && p->xDel ){\n    assert( (p->flags&MEM_RowSet)==0 );\n    assert( p->xDel!=SQLITE_DYNAMIC );\n    p->xDel((void *)p->z);\n    p->xDel = 0;\n  }else if( p->flags&MEM_RowSet ){\n    sqlite3RowSetClear(p->u.pRowSet);\n  }else if( p->flags&MEM_Frame ){\n    sqlite3VdbeMemSetNull(p);\n  }\n}\n\n/*\n** Release any memory held by the Mem. This may leave the Mem in an\n** inconsistent state, for example with (Mem.z==0) and\n** (Mem.type==SQLITE_TEXT).\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){\n  VdbeMemRelease(p);\n  sqlite3DbFree(p->db, p->zMalloc);\n  p->z = 0;\n  p->zMalloc = 0;\n  p->xDel = 0;\n}\n\n/*\n** Convert a 64-bit IEEE double into a 64-bit signed integer.\n** If the double is too large, return 0x8000000000000000.\n**\n** Most systems appear to do this simply by assigning\n** variables and without the extra range tests.  But\n** there are reports that windows throws an expection\n** if the floating point value is out of range. (See ticket #2880.)\n** Because we do not completely understand the problem, we will\n** take the conservative approach and always do range tests\n** before attempting the conversion.\n*/\nstatic i64 doubleToInt64(double r){\n#ifdef SQLITE_OMIT_FLOATING_POINT\n  /* When floating-point is omitted, double and int64 are the same thing */\n  return r;\n#else\n  /*\n  ** Many compilers we encounter do not define constants for the\n  ** minimum and maximum 64-bit integers, or they define them\n  ** inconsistently.  And many do not understand the \"LL\" notation.\n  ** So we define our own static constants here using nothing\n  ** larger than a 32-bit integer constant.\n  */\n  static const i64 maxInt = LARGEST_INT64;\n  static const i64 minInt = SMALLEST_INT64;\n\n  if( r<(double)minInt ){\n    return minInt;\n  }else if( r>(double)maxInt ){\n    /* minInt is correct here - not maxInt.  It turns out that assigning\n    ** a very large positive number to an integer results in a very large\n    ** negative integer.  This makes no sense, but it is what x86 hardware\n    ** does so for compatibility we will do the same in software. */\n    return minInt;\n  }else{\n    return (i64)r;\n  }\n#endif\n}\n\n/*\n** Return some kind of integer value which is the best we can do\n** at representing the value that *pMem describes as an integer.\n** If pMem is an integer, then the value is exact.  If pMem is\n** a floating-point then the value returned is the integer part.\n** If pMem is a string or blob, then we make an attempt to convert\n** it into a integer and return that.  If pMem represents an\n** an SQL-NULL value, return 0.\n**\n** If pMem represents a string value, its encoding might be changed.\n*/\nSQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){\n  int flags;\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  flags = pMem->flags;\n  if( flags & MEM_Int ){\n    return pMem->u.i;\n  }else if( flags & MEM_Real ){\n    return doubleToInt64(pMem->r);\n  }else if( flags & (MEM_Str|MEM_Blob) ){\n    i64 value = 0;\n    assert( pMem->z || pMem->n==0 );\n    testcase( pMem->z==0 );\n    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);\n    return value;\n  }else{\n    return 0;\n  }\n}\n\n/*\n** Return the best representation of pMem that we can get into a\n** double.  If pMem is already a double or an integer, return its\n** value.  If it is a string or blob, try to convert it to a double.\n** If it is a NULL, return 0.0.\n*/\nSQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  if( pMem->flags & MEM_Real ){\n    return pMem->r;\n  }else if( pMem->flags & MEM_Int ){\n    return (double)pMem->u.i;\n  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){\n    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n    double val = (double)0;\n    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);\n    return val;\n  }else{\n    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n    return (double)0;\n  }\n}\n\n/*\n** The MEM structure is already a MEM_Real.  Try to also make it a\n** MEM_Int if we can.\n*/\nSQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){\n  assert( pMem->flags & MEM_Real );\n  assert( (pMem->flags & MEM_RowSet)==0 );\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  pMem->u.i = doubleToInt64(pMem->r);\n\n  /* Only mark the value as an integer if\n  **\n  **    (1) the round-trip conversion real->int->real is a no-op, and\n  **    (2) The integer is neither the largest nor the smallest\n  **        possible integer (ticket #3922)\n  **\n  ** The second and third terms in the following conditional enforces\n  ** the second condition under the assumption that addition overflow causes\n  ** values to wrap around.  On x86 hardware, the third term is always\n  ** true and could be omitted.  But we leave it in because other\n  ** architectures might behave differently.\n  */\n  if( pMem->r==(double)pMem->u.i\n   && pMem->u.i>SMALLEST_INT64\n#if defined(__i486__) || defined(__x86_64__)\n   && ALWAYS(pMem->u.i<LARGEST_INT64)\n#else\n   && pMem->u.i<LARGEST_INT64\n#endif\n  ){\n    pMem->flags |= MEM_Int;\n  }\n}\n\n/*\n** Convert pMem to type integer.  Invalidate any prior representations.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( (pMem->flags & MEM_RowSet)==0 );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  pMem->u.i = sqlite3VdbeIntValue(pMem);\n  MemSetTypeFlag(pMem, MEM_Int);\n  return SQLITE_OK;\n}\n\n/*\n** Convert pMem so that it is of type MEM_Real.\n** Invalidate any prior representations.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n\n  pMem->r = sqlite3VdbeRealValue(pMem);\n  MemSetTypeFlag(pMem, MEM_Real);\n  return SQLITE_OK;\n}\n\n/*\n** Convert pMem so that it has types MEM_Real or MEM_Int or both.\n** Invalidate any prior representations.\n**\n** Every effort is made to force the conversion, even if the input\n** is a string that does not look completely like a number.  Convert\n** as much of the string as we can and ignore the rest.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){\n  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){\n    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );\n    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){\n      MemSetTypeFlag(pMem, MEM_Int);\n    }else{\n      pMem->r = sqlite3VdbeRealValue(pMem);\n      MemSetTypeFlag(pMem, MEM_Real);\n      sqlite3VdbeIntegerAffinity(pMem);\n    }\n  }\n  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );\n  pMem->flags &= ~(MEM_Str|MEM_Blob);\n  return SQLITE_OK;\n}\n\n/*\n** Delete any previous value and set the value stored in *pMem to NULL.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){\n  if( pMem->flags & MEM_Frame ){\n    VdbeFrame *pFrame = pMem->u.pFrame;\n    pFrame->pParent = pFrame->v->pDelFrame;\n    pFrame->v->pDelFrame = pFrame;\n  }\n  if( pMem->flags & MEM_RowSet ){\n    sqlite3RowSetClear(pMem->u.pRowSet);\n  }\n  MemSetTypeFlag(pMem, MEM_Null);\n  pMem->type = SQLITE_NULL;\n}\n\n/*\n** Delete any previous value and set the value to be a BLOB of length\n** n containing all zeros.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){\n  sqlite3VdbeMemRelease(pMem);\n  pMem->flags = MEM_Blob|MEM_Zero;\n  pMem->type = SQLITE_BLOB;\n  pMem->n = 0;\n  if( n<0 ) n = 0;\n  pMem->u.nZero = n;\n  pMem->enc = SQLITE_UTF8;\n\n#ifdef SQLITE_OMIT_INCRBLOB\n  sqlite3VdbeMemGrow(pMem, n, 0);\n  if( pMem->z ){\n    pMem->n = n;\n    memset(pMem->z, 0, n);\n  }\n#endif\n}\n\n/*\n** Delete any previous value and set the value stored in *pMem to val,\n** manifest type INTEGER.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){\n  sqlite3VdbeMemRelease(pMem);\n  pMem->u.i = val;\n  pMem->flags = MEM_Int;\n  pMem->type = SQLITE_INTEGER;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Delete any previous value and set the value stored in *pMem to val,\n** manifest type REAL.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){\n  if( sqlite3IsNaN(val) ){\n    sqlite3VdbeMemSetNull(pMem);\n  }else{\n    sqlite3VdbeMemRelease(pMem);\n    pMem->r = val;\n    pMem->flags = MEM_Real;\n    pMem->type = SQLITE_FLOAT;\n  }\n}\n#endif\n\n/*\n** Delete any previous value and set the value of pMem to be an\n** empty boolean index.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){\n  sqlite3 *db = pMem->db;\n  assert( db!=0 );\n  assert( (pMem->flags & MEM_RowSet)==0 );\n  sqlite3VdbeMemRelease(pMem);\n  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);\n  if( db->mallocFailed ){\n    pMem->flags = MEM_Null;\n  }else{\n    assert( pMem->zMalloc );\n    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, \n                                       sqlite3DbMallocSize(db, pMem->zMalloc));\n    assert( pMem->u.pRowSet!=0 );\n    pMem->flags = MEM_RowSet;\n  }\n}\n\n/*\n** Return true if the Mem object contains a TEXT or BLOB that is\n** too large - whose size exceeds SQLITE_MAX_LENGTH.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){\n  assert( p->db!=0 );\n  if( p->flags & (MEM_Str|MEM_Blob) ){\n    int n = p->n;\n    if( p->flags & MEM_Zero ){\n      n += p->u.nZero;\n    }\n    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];\n  }\n  return 0; \n}\n\n#ifdef SQLITE_DEBUG\n/*\n** This routine prepares a memory cell for modication by breaking\n** its link to a shallow copy and by marking any current shallow\n** copies of this cell as invalid.\n**\n** This is used for testing and debugging only - to make sure shallow\n** copies are not misused.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){\n  int i;\n  Mem *pX;\n  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){\n    if( pX->pScopyFrom==pMem ){\n      pX->flags |= MEM_Invalid;\n      pX->pScopyFrom = 0;\n    }\n  }\n  pMem->pScopyFrom = 0;\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** Size of struct Mem not including the Mem.zMalloc member.\n*/\n#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))\n\n/*\n** Make an shallow copy of pFrom into pTo.  Prior contents of\n** pTo are freed.  The pFrom->z field is not duplicated.  If\n** pFrom->z is used, then pTo->z points to the same thing as pFrom->z\n** and flags gets srcType (either MEM_Ephem or MEM_Static).\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){\n  assert( (pFrom->flags & MEM_RowSet)==0 );\n  VdbeMemRelease(pTo);\n  memcpy(pTo, pFrom, MEMCELLSIZE);\n  pTo->xDel = 0;\n  if( (pFrom->flags&MEM_Static)==0 ){\n    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);\n    assert( srcType==MEM_Ephem || srcType==MEM_Static );\n    pTo->flags |= srcType;\n  }\n}\n\n/*\n** Make a full copy of pFrom into pTo.  Prior contents of pTo are\n** freed before the copy is made.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){\n  int rc = SQLITE_OK;\n\n  assert( (pFrom->flags & MEM_RowSet)==0 );\n  VdbeMemRelease(pTo);\n  memcpy(pTo, pFrom, MEMCELLSIZE);\n  pTo->flags &= ~MEM_Dyn;\n\n  if( pTo->flags&(MEM_Str|MEM_Blob) ){\n    if( 0==(pFrom->flags&MEM_Static) ){\n      pTo->flags |= MEM_Ephem;\n      rc = sqlite3VdbeMemMakeWriteable(pTo);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Transfer the contents of pFrom to pTo. Any existing value in pTo is\n** freed. If pFrom contains ephemeral data, a copy is made.\n**\n** pFrom contains an SQL NULL when this routine returns.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){\n  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );\n  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );\n  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );\n\n  sqlite3VdbeMemRelease(pTo);\n  memcpy(pTo, pFrom, sizeof(Mem));\n  pFrom->flags = MEM_Null;\n  pFrom->xDel = 0;\n  pFrom->zMalloc = 0;\n}\n\n/*\n** Change the value of a Mem to be a string or a BLOB.\n**\n** The memory management strategy depends on the value of the xDel\n** parameter. If the value passed is SQLITE_TRANSIENT, then the \n** string is copied into a (possibly existing) buffer managed by the \n** Mem structure. Otherwise, any existing buffer is freed and the\n** pointer copied.\n**\n** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH\n** size limit) then no memory allocation occurs.  If the string can be\n** stored without allocating memory, then it is.  If a memory allocation\n** is required to store the string, then value of pMem is unchanged.  In\n** either case, SQLITE_TOOBIG is returned.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemSetStr(\n  Mem *pMem,          /* Memory cell to set to string value */\n  const char *z,      /* String pointer */\n  int n,              /* Bytes in string, or negative */\n  u8 enc,             /* Encoding of z.  0 for BLOBs */\n  void (*xDel)(void*) /* Destructor function */\n){\n  int nByte = n;      /* New value for pMem->n */\n  int iLimit;         /* Maximum allowed string or blob size */\n  u16 flags = 0;      /* New value for pMem->flags */\n\n  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );\n  assert( (pMem->flags & MEM_RowSet)==0 );\n\n  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */\n  if( !z ){\n    sqlite3VdbeMemSetNull(pMem);\n    return SQLITE_OK;\n  }\n\n  if( pMem->db ){\n    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];\n  }else{\n    iLimit = SQLITE_MAX_LENGTH;\n  }\n  flags = (enc==0?MEM_Blob:MEM_Str);\n  if( nByte<0 ){\n    assert( enc!=0 );\n    if( enc==SQLITE_UTF8 ){\n      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}\n    }else{\n      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}\n    }\n    flags |= MEM_Term;\n  }\n\n  /* The following block sets the new values of Mem.z and Mem.xDel. It\n  ** also sets a flag in local variable \"flags\" to indicate the memory\n  ** management (one of MEM_Dyn or MEM_Static).\n  */\n  if( xDel==SQLITE_TRANSIENT ){\n    int nAlloc = nByte;\n    if( flags&MEM_Term ){\n      nAlloc += (enc==SQLITE_UTF8?1:2);\n    }\n    if( nByte>iLimit ){\n      return SQLITE_TOOBIG;\n    }\n    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){\n      return SQLITE_NOMEM;\n    }\n    memcpy(pMem->z, z, nAlloc);\n  }else if( xDel==SQLITE_DYNAMIC ){\n    sqlite3VdbeMemRelease(pMem);\n    pMem->zMalloc = pMem->z = (char *)z;\n    pMem->xDel = 0;\n  }else{\n    sqlite3VdbeMemRelease(pMem);\n    pMem->z = (char *)z;\n    pMem->xDel = xDel;\n    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);\n  }\n\n  pMem->n = nByte;\n  pMem->flags = flags;\n  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);\n  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);\n\n#ifndef SQLITE_OMIT_UTF16\n  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){\n    return SQLITE_NOMEM;\n  }\n#endif\n\n  if( nByte>iLimit ){\n    return SQLITE_TOOBIG;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Compare the values contained by the two memory cells, returning\n** negative, zero or positive if pMem1 is less than, equal to, or greater\n** than pMem2. Sorting order is NULL's first, followed by numbers (integers\n** and reals) sorted numerically, followed by text ordered by the collating\n** sequence pColl and finally blob's ordered by memcmp().\n**\n** Two NULL values are considered equal by this function.\n*/\nSQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){\n  int rc;\n  int f1, f2;\n  int combined_flags;\n\n  f1 = pMem1->flags;\n  f2 = pMem2->flags;\n  combined_flags = f1|f2;\n  assert( (combined_flags & MEM_RowSet)==0 );\n \n  /* If one value is NULL, it is less than the other. If both values\n  ** are NULL, return 0.\n  */\n  if( combined_flags&MEM_Null ){\n    return (f2&MEM_Null) - (f1&MEM_Null);\n  }\n\n  /* If one value is a number and the other is not, the number is less.\n  ** If both are numbers, compare as reals if one is a real, or as integers\n  ** if both values are integers.\n  */\n  if( combined_flags&(MEM_Int|MEM_Real) ){\n    if( !(f1&(MEM_Int|MEM_Real)) ){\n      return 1;\n    }\n    if( !(f2&(MEM_Int|MEM_Real)) ){\n      return -1;\n    }\n    if( (f1 & f2 & MEM_Int)==0 ){\n      double r1, r2;\n      if( (f1&MEM_Real)==0 ){\n        r1 = (double)pMem1->u.i;\n      }else{\n        r1 = pMem1->r;\n      }\n      if( (f2&MEM_Real)==0 ){\n        r2 = (double)pMem2->u.i;\n      }else{\n        r2 = pMem2->r;\n      }\n      if( r1<r2 ) return -1;\n      if( r1>r2 ) return 1;\n      return 0;\n    }else{\n      assert( f1&MEM_Int );\n      assert( f2&MEM_Int );\n      if( pMem1->u.i < pMem2->u.i ) return -1;\n      if( pMem1->u.i > pMem2->u.i ) return 1;\n      return 0;\n    }\n  }\n\n  /* If one value is a string and the other is a blob, the string is less.\n  ** If both are strings, compare using the collating functions.\n  */\n  if( combined_flags&MEM_Str ){\n    if( (f1 & MEM_Str)==0 ){\n      return 1;\n    }\n    if( (f2 & MEM_Str)==0 ){\n      return -1;\n    }\n\n    assert( pMem1->enc==pMem2->enc );\n    assert( pMem1->enc==SQLITE_UTF8 || \n            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );\n\n    /* The collation sequence must be defined at this point, even if\n    ** the user deletes the collation sequence after the vdbe program is\n    ** compiled (this was not always the case).\n    */\n    assert( !pColl || pColl->xCmp );\n\n    if( pColl ){\n      if( pMem1->enc==pColl->enc ){\n        /* The strings are already in the correct encoding.  Call the\n        ** comparison function directly */\n        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);\n      }else{\n        const void *v1, *v2;\n        int n1, n2;\n        Mem c1;\n        Mem c2;\n        memset(&c1, 0, sizeof(c1));\n        memset(&c2, 0, sizeof(c2));\n        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);\n        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);\n        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);\n        n1 = v1==0 ? 0 : c1.n;\n        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);\n        n2 = v2==0 ? 0 : c2.n;\n        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);\n        sqlite3VdbeMemRelease(&c1);\n        sqlite3VdbeMemRelease(&c2);\n        return rc;\n      }\n    }\n    /* If a NULL pointer was passed as the collate function, fall through\n    ** to the blob case and use memcmp().  */\n  }\n \n  /* Both values must be blobs.  Compare using memcmp().  */\n  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);\n  if( rc==0 ){\n    rc = pMem1->n - pMem2->n;\n  }\n  return rc;\n}\n\n/*\n** Move data out of a btree key or data field and into a Mem structure.\n** The data or key is taken from the entry that pCur is currently pointing\n** to.  offset and amt determine what portion of the data or key to retrieve.\n** key is true to get the key or false to get data.  The result is written\n** into the pMem element.\n**\n** The pMem structure is assumed to be uninitialized.  Any prior content\n** is overwritten without being freed.\n**\n** If this routine fails for any reason (malloc returns NULL or unable\n** to read from the disk) then the pMem is left in an inconsistent state.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMemFromBtree(\n  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */\n  int offset,       /* Offset from the start of data to return bytes from. */\n  int amt,          /* Number of bytes to return. */\n  int key,          /* If true, retrieve from the btree key, not data. */\n  Mem *pMem         /* OUT: Return data in this Mem structure. */\n){\n  char *zData;        /* Data from the btree layer */\n  int available = 0;  /* Number of bytes available on the local btree page */\n  int rc = SQLITE_OK; /* Return code */\n\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n\n  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() \n  ** that both the BtShared and database handle mutexes are held. */\n  assert( (pMem->flags & MEM_RowSet)==0 );\n  if( key ){\n    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);\n  }else{\n    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);\n  }\n  assert( zData!=0 );\n\n  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){\n    sqlite3VdbeMemRelease(pMem);\n    pMem->z = &zData[offset];\n    pMem->flags = MEM_Blob|MEM_Ephem;\n  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){\n    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;\n    pMem->enc = 0;\n    pMem->type = SQLITE_BLOB;\n    if( key ){\n      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);\n    }else{\n      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);\n    }\n    pMem->z[amt] = 0;\n    pMem->z[amt+1] = 0;\n    if( rc!=SQLITE_OK ){\n      sqlite3VdbeMemRelease(pMem);\n    }\n  }\n  pMem->n = amt;\n\n  return rc;\n}\n\n/* This function is only available internally, it is not part of the\n** external API. It works in a similar way to sqlite3_value_text(),\n** except the data returned is in the encoding specified by the second\n** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or\n** SQLITE_UTF8.\n**\n** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.\n** If that is the case, then the result must be aligned on an even byte\n** boundary.\n*/\nSQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){\n  if( !pVal ) return 0;\n\n  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );\n  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );\n  assert( (pVal->flags & MEM_RowSet)==0 );\n\n  if( pVal->flags&MEM_Null ){\n    return 0;\n  }\n  assert( (MEM_Blob>>3) == MEM_Str );\n  pVal->flags |= (pVal->flags & MEM_Blob)>>3;\n  ExpandBlob(pVal);\n  if( pVal->flags&MEM_Str ){\n    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);\n    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){\n      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );\n      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){\n        return 0;\n      }\n    }\n    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */\n  }else{\n    assert( (pVal->flags&MEM_Blob)==0 );\n    sqlite3VdbeMemStringify(pVal, enc);\n    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );\n  }\n  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0\n              || pVal->db->mallocFailed );\n  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){\n    return pVal->z;\n  }else{\n    return 0;\n  }\n}\n\n/*\n** Create a new sqlite3_value object.\n*/\nSQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){\n  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));\n  if( p ){\n    p->flags = MEM_Null;\n    p->type = SQLITE_NULL;\n    p->db = db;\n  }\n  return p;\n}\n\n/*\n** Create a new sqlite3_value object, containing the value of pExpr.\n**\n** This only works for very simple expressions that consist of one constant\n** token (i.e. \"5\", \"5.1\", \"'a string'\"). If the expression can\n** be converted directly into a value, then the value is allocated and\n** a pointer written to *ppVal. The caller is responsible for deallocating\n** the value by passing it to sqlite3ValueFree() later on. If the expression\n** cannot be converted to a value, then *ppVal is set to NULL.\n*/\nSQLITE_PRIVATE int sqlite3ValueFromExpr(\n  sqlite3 *db,              /* The database connection */\n  Expr *pExpr,              /* The expression to evaluate */\n  u8 enc,                   /* Encoding to use */\n  u8 affinity,              /* Affinity to use */\n  sqlite3_value **ppVal     /* Write the new value here */\n){\n  int op;\n  char *zVal = 0;\n  sqlite3_value *pVal = 0;\n  int negInt = 1;\n  const char *zNeg = \"\";\n\n  if( !pExpr ){\n    *ppVal = 0;\n    return SQLITE_OK;\n  }\n  op = pExpr->op;\n\n  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.\n  ** The ifdef here is to enable us to achieve 100% branch test coverage even\n  ** when SQLITE_ENABLE_STAT3 is omitted.\n  */\n#ifdef SQLITE_ENABLE_STAT3\n  if( op==TK_REGISTER ) op = pExpr->op2;\n#else\n  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;\n#endif\n\n  /* Handle negative integers in a single step.  This is needed in the\n  ** case when the value is -9223372036854775808.\n  */\n  if( op==TK_UMINUS\n   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){\n    pExpr = pExpr->pLeft;\n    op = pExpr->op;\n    negInt = -1;\n    zNeg = \"-\";\n  }\n\n  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){\n    pVal = sqlite3ValueNew(db);\n    if( pVal==0 ) goto no_mem;\n    if( ExprHasProperty(pExpr, EP_IntValue) ){\n      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);\n    }else{\n      zVal = sqlite3MPrintf(db, \"%s%s\", zNeg, pExpr->u.zToken);\n      if( zVal==0 ) goto no_mem;\n      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);\n      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;\n    }\n    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){\n      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);\n    }else{\n      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);\n    }\n    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;\n    if( enc!=SQLITE_UTF8 ){\n      sqlite3VdbeChangeEncoding(pVal, enc);\n    }\n  }else if( op==TK_UMINUS ) {\n    /* This branch happens for multiple negative signs.  Ex: -(-5) */\n    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){\n      sqlite3VdbeMemNumerify(pVal);\n      if( pVal->u.i==SMALLEST_INT64 ){\n        pVal->flags &= MEM_Int;\n        pVal->flags |= MEM_Real;\n        pVal->r = (double)LARGEST_INT64;\n      }else{\n        pVal->u.i = -pVal->u.i;\n      }\n      pVal->r = -pVal->r;\n      sqlite3ValueApplyAffinity(pVal, affinity, enc);\n    }\n  }else if( op==TK_NULL ){\n    pVal = sqlite3ValueNew(db);\n    if( pVal==0 ) goto no_mem;\n  }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n  else if( op==TK_BLOB ){\n    int nVal;\n    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );\n    assert( pExpr->u.zToken[1]=='\\'' );\n    pVal = sqlite3ValueNew(db);\n    if( !pVal ) goto no_mem;\n    zVal = &pExpr->u.zToken[2];\n    nVal = sqlite3Strlen30(zVal)-1;\n    assert( zVal[nVal]=='\\'' );\n    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,\n                         0, SQLITE_DYNAMIC);\n  }\n#endif\n\n  if( pVal ){\n    sqlite3VdbeMemStoreType(pVal);\n  }\n  *ppVal = pVal;\n  return SQLITE_OK;\n\nno_mem:\n  db->mallocFailed = 1;\n  sqlite3DbFree(db, zVal);\n  sqlite3ValueFree(pVal);\n  *ppVal = 0;\n  return SQLITE_NOMEM;\n}\n\n/*\n** Change the string value of an sqlite3_value object\n*/\nSQLITE_PRIVATE void sqlite3ValueSetStr(\n  sqlite3_value *v,     /* Value to be set */\n  int n,                /* Length of string z */\n  const void *z,        /* Text of the new string */\n  u8 enc,               /* Encoding to use */\n  void (*xDel)(void*)   /* Destructor for the string */\n){\n  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);\n}\n\n/*\n** Free an sqlite3_value object\n*/\nSQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){\n  if( !v ) return;\n  sqlite3VdbeMemRelease((Mem *)v);\n  sqlite3DbFree(((Mem*)v)->db, v);\n}\n\n/*\n** Return the number of bytes in the sqlite3_value object assuming\n** that it uses the encoding \"enc\"\n*/\nSQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){\n  Mem *p = (Mem*)pVal;\n  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){\n    if( p->flags & MEM_Zero ){\n      return p->n + p->u.nZero;\n    }else{\n      return p->n;\n    }\n  }\n  return 0;\n}\n\n/************** End of vdbemem.c *********************************************/\n/************** Begin file vdbeaux.c *****************************************/\n/*\n** 2003 September 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used for creating, destroying, and populating\n** a VDBE (or an \"sqlite3_stmt\" as it is known to the outside world.)  Prior\n** to version 2.8.7, all this code was combined into the vdbe.c source file.\n** But that file was getting too big so this subroutines were split out.\n*/\n\n\n\n/*\n** When debugging the code generator in a symbolic debugger, one can\n** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed\n** as they are added to the instruction stream.\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;\n#endif\n\n\n/*\n** Create a new virtual database engine.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){\n  Vdbe *p;\n  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );\n  if( p==0 ) return 0;\n  p->db = db;\n  if( db->pVdbe ){\n    db->pVdbe->pPrev = p;\n  }\n  p->pNext = db->pVdbe;\n  p->pPrev = 0;\n  db->pVdbe = p;\n  p->magic = VDBE_MAGIC_INIT;\n  return p;\n}\n\n/*\n** Remember the SQL string for a prepared statement.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){\n  assert( isPrepareV2==1 || isPrepareV2==0 );\n  if( p==0 ) return;\n#ifdef SQLITE_OMIT_TRACE\n  if( !isPrepareV2 ) return;\n#endif\n  assert( p->zSql==0 );\n  p->zSql = sqlite3DbStrNDup(p->db, z, n);\n  p->isPrepareV2 = (u8)isPrepareV2;\n}\n\n/*\n** Return the SQL associated with a prepared statement\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe *)pStmt;\n  return (p && p->isPrepareV2) ? p->zSql : 0;\n}\n\n/*\n** Swap all content between two VDBE structures.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){\n  Vdbe tmp, *pTmp;\n  char *zTmp;\n  tmp = *pA;\n  *pA = *pB;\n  *pB = tmp;\n  pTmp = pA->pNext;\n  pA->pNext = pB->pNext;\n  pB->pNext = pTmp;\n  pTmp = pA->pPrev;\n  pA->pPrev = pB->pPrev;\n  pB->pPrev = pTmp;\n  zTmp = pA->zSql;\n  pA->zSql = pB->zSql;\n  pB->zSql = zTmp;\n  pB->isPrepareV2 = pA->isPrepareV2;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Turn tracing on or off\n*/\nSQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){\n  p->trace = trace;\n}\n#endif\n\n/*\n** Resize the Vdbe.aOp array so that it is at least one op larger than \n** it was.\n**\n** If an out-of-memory error occurs while resizing the array, return\n** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain \n** unchanged (this is so that any opcodes already allocated can be \n** correctly deallocated along with the rest of the Vdbe).\n*/\nstatic int growOpArray(Vdbe *p){\n  VdbeOp *pNew;\n  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));\n  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));\n  if( pNew ){\n    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);\n    p->aOp = pNew;\n  }\n  return (pNew ? SQLITE_OK : SQLITE_NOMEM);\n}\n\n/*\n** Add a new instruction to the list of instructions current in the\n** VDBE.  Return the address of the new instruction.\n**\n** Parameters:\n**\n**    p               Pointer to the VDBE\n**\n**    op              The opcode for this instruction\n**\n**    p1, p2, p3      Operands\n**\n** Use the sqlite3VdbeResolveLabel() function to fix an address and\n** the sqlite3VdbeChangeP4() function to change the value of the P4\n** operand.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){\n  int i;\n  VdbeOp *pOp;\n\n  i = p->nOp;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  assert( op>0 && op<0xff );\n  if( p->nOpAlloc<=i ){\n    if( growOpArray(p) ){\n      return 1;\n    }\n  }\n  p->nOp++;\n  pOp = &p->aOp[i];\n  pOp->opcode = (u8)op;\n  pOp->p5 = 0;\n  pOp->p1 = p1;\n  pOp->p2 = p2;\n  pOp->p3 = p3;\n  pOp->p4.p = 0;\n  pOp->p4type = P4_NOTUSED;\n#ifdef SQLITE_DEBUG\n  pOp->zComment = 0;\n  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);\n#endif\n#ifdef VDBE_PROFILE\n  pOp->cycles = 0;\n  pOp->cnt = 0;\n#endif\n  return i;\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){\n  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){\n  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);\n}\nSQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){\n  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);\n}\n\n\n/*\n** Add an opcode that includes the p4 value as a pointer.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp4(\n  Vdbe *p,            /* Add the opcode to this VM */\n  int op,             /* The new opcode */\n  int p1,             /* The P1 operand */\n  int p2,             /* The P2 operand */\n  int p3,             /* The P3 operand */\n  const char *zP4,    /* The P4 operand */\n  int p4type          /* P4 operand type */\n){\n  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);\n  sqlite3VdbeChangeP4(p, addr, zP4, p4type);\n  return addr;\n}\n\n/*\n** Add an OP_ParseSchema opcode.  This routine is broken out from\n** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees\n** as having been used.\n**\n** The zWhere string must have been obtained from sqlite3_malloc().\n** This routine will take ownership of the allocated memory.\n*/\nSQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){\n  int j;\n  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);\n  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);\n  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);\n}\n\n/*\n** Add an opcode that includes the p4 value as an integer.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOp4Int(\n  Vdbe *p,            /* Add the opcode to this VM */\n  int op,             /* The new opcode */\n  int p1,             /* The P1 operand */\n  int p2,             /* The P2 operand */\n  int p3,             /* The P3 operand */\n  int p4              /* The P4 operand as an integer */\n){\n  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);\n  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);\n  return addr;\n}\n\n/*\n** Create a new symbolic label for an instruction that has yet to be\n** coded.  The symbolic label is really just a negative number.  The\n** label can be used as the P2 value of an operation.  Later, when\n** the label is resolved to a specific address, the VDBE will scan\n** through its operation list and change all values of P2 which match\n** the label into the resolved address.\n**\n** The VDBE knows that a P2 value is a label because labels are\n** always negative and P2 values are suppose to be non-negative.\n** Hence, a negative P2 value is a label that has yet to be resolved.\n**\n** Zero is returned if a malloc() fails.\n*/\nSQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){\n  int i = p->nLabel++;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( (i & (i-1))==0 ){\n    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, \n                                       (i*2+1)*sizeof(p->aLabel[0]));\n  }\n  if( p->aLabel ){\n    p->aLabel[i] = -1;\n  }\n  return -1-i;\n}\n\n/*\n** Resolve label \"x\" to be the address of the next instruction to\n** be inserted.  The parameter \"x\" must have been obtained from\n** a prior call to sqlite3VdbeMakeLabel().\n*/\nSQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){\n  int j = -1-x;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  assert( j>=0 && j<p->nLabel );\n  if( p->aLabel ){\n    p->aLabel[j] = p->nOp;\n  }\n}\n\n/*\n** Mark the VDBE as one that can only be run one time.\n*/\nSQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){\n  p->runOnlyOnce = 1;\n}\n\n#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */\n\n/*\n** The following type and function are used to iterate through all opcodes\n** in a Vdbe main program and each of the sub-programs (triggers) it may \n** invoke directly or indirectly. It should be used as follows:\n**\n**   Op *pOp;\n**   VdbeOpIter sIter;\n**\n**   memset(&sIter, 0, sizeof(sIter));\n**   sIter.v = v;                            // v is of type Vdbe* \n**   while( (pOp = opIterNext(&sIter)) ){\n**     // Do something with pOp\n**   }\n**   sqlite3DbFree(v->db, sIter.apSub);\n** \n*/\ntypedef struct VdbeOpIter VdbeOpIter;\nstruct VdbeOpIter {\n  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */\n  SubProgram **apSub;        /* Array of subprograms */\n  int nSub;                  /* Number of entries in apSub */\n  int iAddr;                 /* Address of next instruction to return */\n  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */\n};\nstatic Op *opIterNext(VdbeOpIter *p){\n  Vdbe *v = p->v;\n  Op *pRet = 0;\n  Op *aOp;\n  int nOp;\n\n  if( p->iSub<=p->nSub ){\n\n    if( p->iSub==0 ){\n      aOp = v->aOp;\n      nOp = v->nOp;\n    }else{\n      aOp = p->apSub[p->iSub-1]->aOp;\n      nOp = p->apSub[p->iSub-1]->nOp;\n    }\n    assert( p->iAddr<nOp );\n\n    pRet = &aOp[p->iAddr];\n    p->iAddr++;\n    if( p->iAddr==nOp ){\n      p->iSub++;\n      p->iAddr = 0;\n    }\n  \n    if( pRet->p4type==P4_SUBPROGRAM ){\n      int nByte = (p->nSub+1)*sizeof(SubProgram*);\n      int j;\n      for(j=0; j<p->nSub; j++){\n        if( p->apSub[j]==pRet->p4.pProgram ) break;\n      }\n      if( j==p->nSub ){\n        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);\n        if( !p->apSub ){\n          pRet = 0;\n        }else{\n          p->apSub[p->nSub++] = pRet->p4.pProgram;\n        }\n      }\n    }\n  }\n\n  return pRet;\n}\n\n/*\n** Check if the program stored in the VM associated with pParse may\n** throw an ABORT exception (causing the statement, but not entire transaction\n** to be rolled back). This condition is true if the main program or any\n** sub-programs contains any of the following:\n**\n**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.\n**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.\n**   *  OP_Destroy\n**   *  OP_VUpdate\n**   *  OP_VRename\n**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)\n**\n** Then check that the value of Parse.mayAbort is true if an\n** ABORT may be thrown, or false otherwise. Return true if it does\n** match, or false otherwise. This function is intended to be used as\n** part of an assert statement in the compiler. Similar to:\n**\n**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );\n*/\nSQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){\n  int hasAbort = 0;\n  Op *pOp;\n  VdbeOpIter sIter;\n  memset(&sIter, 0, sizeof(sIter));\n  sIter.v = v;\n\n  while( (pOp = opIterNext(&sIter))!=0 ){\n    int opcode = pOp->opcode;\n    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename \n#ifndef SQLITE_OMIT_FOREIGN_KEY\n     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) \n#endif\n     || ((opcode==OP_Halt || opcode==OP_HaltIfNull) \n      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))\n    ){\n      hasAbort = 1;\n      break;\n    }\n  }\n  sqlite3DbFree(v->db, sIter.apSub);\n\n  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.\n  ** If malloc failed, then the while() loop above may not have iterated\n  ** through all opcodes and hasAbort may be set incorrectly. Return\n  ** true for this case to prevent the assert() in the callers frame\n  ** from failing.  */\n  return ( v->db->mallocFailed || hasAbort==mayAbort );\n}\n#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */\n\n/*\n** Loop through the program looking for P2 values that are negative\n** on jump instructions.  Each such value is a label.  Resolve the\n** label by setting the P2 value to its correct non-zero value.\n**\n** This routine is called once after all opcodes have been inserted.\n**\n** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument \n** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by \n** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.\n**\n** The Op.opflags field is set on all opcodes.\n*/\nstatic void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){\n  int i;\n  int nMaxArgs = *pMaxFuncArgs;\n  Op *pOp;\n  int *aLabel = p->aLabel;\n  p->readOnly = 1;\n  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){\n    u8 opcode = pOp->opcode;\n\n    pOp->opflags = sqlite3OpcodeProperty[opcode];\n    if( opcode==OP_Function || opcode==OP_AggStep ){\n      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;\n    }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){\n      p->readOnly = 0;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    }else if( opcode==OP_VUpdate ){\n      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;\n    }else if( opcode==OP_VFilter ){\n      int n;\n      assert( p->nOp - i >= 3 );\n      assert( pOp[-1].opcode==OP_Integer );\n      n = pOp[-1].p1;\n      if( n>nMaxArgs ) nMaxArgs = n;\n#endif\n    }else if( opcode==OP_Next || opcode==OP_SorterNext ){\n      pOp->p4.xAdvance = sqlite3BtreeNext;\n      pOp->p4type = P4_ADVANCE;\n    }else if( opcode==OP_Prev ){\n      pOp->p4.xAdvance = sqlite3BtreePrevious;\n      pOp->p4type = P4_ADVANCE;\n    }\n\n    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){\n      assert( -1-pOp->p2<p->nLabel );\n      pOp->p2 = aLabel[-1-pOp->p2];\n    }\n  }\n  sqlite3DbFree(p->db, p->aLabel);\n  p->aLabel = 0;\n\n  *pMaxFuncArgs = nMaxArgs;\n}\n\n/*\n** Return the address of the next instruction to be inserted.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){\n  assert( p->magic==VDBE_MAGIC_INIT );\n  return p->nOp;\n}\n\n/*\n** This function returns a pointer to the array of opcodes associated with\n** the Vdbe passed as the first argument. It is the callers responsibility\n** to arrange for the returned array to be eventually freed using the \n** vdbeFreeOpArray() function.\n**\n** Before returning, *pnOp is set to the number of entries in the returned\n** array. Also, *pnMaxArg is set to the larger of its current value and \n** the number of entries in the Vdbe.apArg[] array required to execute the \n** returned program.\n*/\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){\n  VdbeOp *aOp = p->aOp;\n  assert( aOp && !p->db->mallocFailed );\n\n  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */\n  assert( p->btreeMask==0 );\n\n  resolveP2Values(p, pnMaxArg);\n  *pnOp = p->nOp;\n  p->aOp = 0;\n  return aOp;\n}\n\n/*\n** Add a whole list of operations to the operation stack.  Return the\n** address of the first operation added.\n*/\nSQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){\n  int addr;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){\n    return 0;\n  }\n  addr = p->nOp;\n  if( ALWAYS(nOp>0) ){\n    int i;\n    VdbeOpList const *pIn = aOp;\n    for(i=0; i<nOp; i++, pIn++){\n      int p2 = pIn->p2;\n      VdbeOp *pOut = &p->aOp[i+addr];\n      pOut->opcode = pIn->opcode;\n      pOut->p1 = pIn->p1;\n      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){\n        pOut->p2 = addr + ADDR(p2);\n      }else{\n        pOut->p2 = p2;\n      }\n      pOut->p3 = pIn->p3;\n      pOut->p4type = P4_NOTUSED;\n      pOut->p4.p = 0;\n      pOut->p5 = 0;\n#ifdef SQLITE_DEBUG\n      pOut->zComment = 0;\n      if( sqlite3VdbeAddopTrace ){\n        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);\n      }\n#endif\n    }\n    p->nOp += nOp;\n  }\n  return addr;\n}\n\n/*\n** Change the value of the P1 operand for a specific instruction.\n** This routine is useful when a large program is loaded from a\n** static array using sqlite3VdbeAddOpList but we want to make a\n** few minor changes to the program.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){\n  assert( p!=0 );\n  if( ((u32)p->nOp)>addr ){\n    p->aOp[addr].p1 = val;\n  }\n}\n\n/*\n** Change the value of the P2 operand for a specific instruction.\n** This routine is useful for setting a jump destination.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){\n  assert( p!=0 );\n  if( ((u32)p->nOp)>addr ){\n    p->aOp[addr].p2 = val;\n  }\n}\n\n/*\n** Change the value of the P3 operand for a specific instruction.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){\n  assert( p!=0 );\n  if( ((u32)p->nOp)>addr ){\n    p->aOp[addr].p3 = val;\n  }\n}\n\n/*\n** Change the value of the P5 operand for the most recently\n** added operation.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){\n  assert( p!=0 );\n  if( p->aOp ){\n    assert( p->nOp>0 );\n    p->aOp[p->nOp-1].p5 = val;\n  }\n}\n\n/*\n** Change the P2 operand of instruction addr so that it points to\n** the address of the next instruction to be coded.\n*/\nSQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){\n  assert( addr>=0 || p->db->mallocFailed );\n  if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);\n}\n\n\n/*\n** If the input FuncDef structure is ephemeral, then free it.  If\n** the FuncDef is not ephermal, then do nothing.\n*/\nstatic void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){\n  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){\n    sqlite3DbFree(db, pDef);\n  }\n}\n\nstatic void vdbeFreeOpArray(sqlite3 *, Op *, int);\n\n/*\n** Delete a P4 value if necessary.\n*/\nstatic void freeP4(sqlite3 *db, int p4type, void *p4){\n  if( p4 ){\n    assert( db );\n    switch( p4type ){\n      case P4_REAL:\n      case P4_INT64:\n      case P4_DYNAMIC:\n      case P4_KEYINFO:\n      case P4_INTARRAY:\n      case P4_KEYINFO_HANDOFF: {\n        sqlite3DbFree(db, p4);\n        break;\n      }\n      case P4_MPRINTF: {\n        if( db->pnBytesFreed==0 ) sqlite3_free(p4);\n        break;\n      }\n      case P4_VDBEFUNC: {\n        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;\n        freeEphemeralFunction(db, pVdbeFunc->pFunc);\n        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);\n        sqlite3DbFree(db, pVdbeFunc);\n        break;\n      }\n      case P4_FUNCDEF: {\n        freeEphemeralFunction(db, (FuncDef*)p4);\n        break;\n      }\n      case P4_MEM: {\n        if( db->pnBytesFreed==0 ){\n          sqlite3ValueFree((sqlite3_value*)p4);\n        }else{\n          Mem *p = (Mem*)p4;\n          sqlite3DbFree(db, p->zMalloc);\n          sqlite3DbFree(db, p);\n        }\n        break;\n      }\n      case P4_VTAB : {\n        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);\n        break;\n      }\n    }\n  }\n}\n\n/*\n** Free the space allocated for aOp and any p4 values allocated for the\n** opcodes contained within. If aOp is not NULL it is assumed to contain \n** nOp entries. \n*/\nstatic void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){\n  if( aOp ){\n    Op *pOp;\n    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){\n      freeP4(db, pOp->p4type, pOp->p4.p);\n#ifdef SQLITE_DEBUG\n      sqlite3DbFree(db, pOp->zComment);\n#endif     \n    }\n  }\n  sqlite3DbFree(db, aOp);\n}\n\n/*\n** Link the SubProgram object passed as the second argument into the linked\n** list at Vdbe.pSubProgram. This list is used to delete all sub-program\n** objects when the VM is no longer required.\n*/\nSQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){\n  p->pNext = pVdbe->pProgram;\n  pVdbe->pProgram = p;\n}\n\n/*\n** Change the opcode at addr into OP_Noop\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){\n  if( p->aOp ){\n    VdbeOp *pOp = &p->aOp[addr];\n    sqlite3 *db = p->db;\n    freeP4(db, pOp->p4type, pOp->p4.p);\n    memset(pOp, 0, sizeof(pOp[0]));\n    pOp->opcode = OP_Noop;\n  }\n}\n\n/*\n** Change the value of the P4 operand for a specific instruction.\n** This routine is useful when a large program is loaded from a\n** static array using sqlite3VdbeAddOpList but we want to make a\n** few minor changes to the program.\n**\n** If n>=0 then the P4 operand is dynamic, meaning that a copy of\n** the string is made into memory obtained from sqlite3_malloc().\n** A value of n==0 means copy bytes of zP4 up to and including the\n** first null byte.  If n>0 then copy n+1 bytes of zP4.\n**\n** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.\n** A copy is made of the KeyInfo structure into memory obtained from\n** sqlite3_malloc, to be freed when the Vdbe is finalized.\n** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure\n** stored in memory that the caller has obtained from sqlite3_malloc. The \n** caller should not free the allocation, it will be freed when the Vdbe is\n** finalized.\n** \n** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points\n** to a string or structure that is guaranteed to exist for the lifetime of\n** the Vdbe. In these cases we can just copy the pointer.\n**\n** If addr<0 then change P4 on the most recently inserted instruction.\n*/\nSQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){\n  Op *pOp;\n  sqlite3 *db;\n  assert( p!=0 );\n  db = p->db;\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( p->aOp==0 || db->mallocFailed ){\n    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {\n      freeP4(db, n, (void*)*(char**)&zP4);\n    }\n    return;\n  }\n  assert( p->nOp>0 );\n  assert( addr<p->nOp );\n  if( addr<0 ){\n    addr = p->nOp - 1;\n  }\n  pOp = &p->aOp[addr];\n  freeP4(db, pOp->p4type, pOp->p4.p);\n  pOp->p4.p = 0;\n  if( n==P4_INT32 ){\n    /* Note: this cast is safe, because the origin data point was an int\n    ** that was cast to a (const char *). */\n    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);\n    pOp->p4type = P4_INT32;\n  }else if( zP4==0 ){\n    pOp->p4.p = 0;\n    pOp->p4type = P4_NOTUSED;\n  }else if( n==P4_KEYINFO ){\n    KeyInfo *pKeyInfo;\n    int nField, nByte;\n\n    nField = ((KeyInfo*)zP4)->nField;\n    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;\n    pKeyInfo = sqlite3DbMallocRaw(0, nByte);\n    pOp->p4.pKeyInfo = pKeyInfo;\n    if( pKeyInfo ){\n      u8 *aSortOrder;\n      memcpy((char*)pKeyInfo, zP4, nByte - nField);\n      aSortOrder = pKeyInfo->aSortOrder;\n      if( aSortOrder ){\n        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];\n        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);\n      }\n      pOp->p4type = P4_KEYINFO;\n    }else{\n      p->db->mallocFailed = 1;\n      pOp->p4type = P4_NOTUSED;\n    }\n  }else if( n==P4_KEYINFO_HANDOFF ){\n    pOp->p4.p = (void*)zP4;\n    pOp->p4type = P4_KEYINFO;\n  }else if( n==P4_VTAB ){\n    pOp->p4.p = (void*)zP4;\n    pOp->p4type = P4_VTAB;\n    sqlite3VtabLock((VTable *)zP4);\n    assert( ((VTable *)zP4)->db==p->db );\n  }else if( n<0 ){\n    pOp->p4.p = (void*)zP4;\n    pOp->p4type = (signed char)n;\n  }else{\n    if( n==0 ) n = sqlite3Strlen30(zP4);\n    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);\n    pOp->p4type = P4_DYNAMIC;\n  }\n}\n\n#ifndef NDEBUG\n/*\n** Change the comment on the most recently coded instruction.  Or\n** insert a No-op and add the comment to that new instruction.  This\n** makes the code easier to read during debugging.  None of this happens\n** in a production build.\n*/\nstatic void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){\n  assert( p->nOp>0 || p->aOp==0 );\n  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );\n  if( p->nOp ){\n    assert( p->aOp );\n    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);\n    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){\n  va_list ap;\n  if( p ){\n    va_start(ap, zFormat);\n    vdbeVComment(p, zFormat, ap);\n    va_end(ap);\n  }\n}\nSQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){\n  va_list ap;\n  if( p ){\n    sqlite3VdbeAddOp0(p, OP_Noop);\n    va_start(ap, zFormat);\n    vdbeVComment(p, zFormat, ap);\n    va_end(ap);\n  }\n}\n#endif  /* NDEBUG */\n\n/*\n** Return the opcode for a given address.  If the address is -1, then\n** return the most recently inserted opcode.\n**\n** If a memory allocation error has occurred prior to the calling of this\n** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode\n** is readable but not writable, though it is cast to a writable value.\n** The return of a dummy opcode allows the call to continue functioning\n** after a OOM fault without having to check to see if the return from \n** this routine is a valid pointer.  But because the dummy.opcode is 0,\n** dummy will never be written to.  This is verified by code inspection and\n** by running with Valgrind.\n**\n** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called\n** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,\n** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as\n** a new VDBE is created.  So we are free to set addr to p->nOp-1 without\n** having to double-check to make sure that the result is non-negative. But\n** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to\n** check the value of p->nOp-1 before continuing.\n*/\nSQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){\n  /* C89 specifies that the constant \"dummy\" will be initialized to all\n  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */\n  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */\n  assert( p->magic==VDBE_MAGIC_INIT );\n  if( addr<0 ){\n#ifdef SQLITE_OMIT_TRACE\n    if( p->nOp==0 ) return (VdbeOp*)&dummy;\n#endif\n    addr = p->nOp - 1;\n  }\n  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );\n  if( p->db->mallocFailed ){\n    return (VdbeOp*)&dummy;\n  }else{\n    return &p->aOp[addr];\n  }\n}\n\n#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \\\n     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)\n/*\n** Compute a string that describes the P4 parameter for an opcode.\n** Use zTemp for any required temporary buffer space.\n*/\nstatic char *displayP4(Op *pOp, char *zTemp, int nTemp){\n  char *zP4 = zTemp;\n  assert( nTemp>=20 );\n  switch( pOp->p4type ){\n    case P4_KEYINFO_STATIC:\n    case P4_KEYINFO: {\n      int i, j;\n      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;\n      sqlite3_snprintf(nTemp, zTemp, \"keyinfo(%d\", pKeyInfo->nField);\n      i = sqlite3Strlen30(zTemp);\n      for(j=0; j<pKeyInfo->nField; j++){\n        CollSeq *pColl = pKeyInfo->aColl[j];\n        if( pColl ){\n          int n = sqlite3Strlen30(pColl->zName);\n          if( i+n>nTemp-6 ){\n            memcpy(&zTemp[i],\",...\",4);\n            break;\n          }\n          zTemp[i++] = ',';\n          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){\n            zTemp[i++] = '-';\n          }\n          memcpy(&zTemp[i], pColl->zName,n+1);\n          i += n;\n        }else if( i+4<nTemp-6 ){\n          memcpy(&zTemp[i],\",nil\",4);\n          i += 4;\n        }\n      }\n      zTemp[i++] = ')';\n      zTemp[i] = 0;\n      assert( i<nTemp );\n      break;\n    }\n    case P4_COLLSEQ: {\n      CollSeq *pColl = pOp->p4.pColl;\n      sqlite3_snprintf(nTemp, zTemp, \"collseq(%.20s)\", pColl->zName);\n      break;\n    }\n    case P4_FUNCDEF: {\n      FuncDef *pDef = pOp->p4.pFunc;\n      sqlite3_snprintf(nTemp, zTemp, \"%s(%d)\", pDef->zName, pDef->nArg);\n      break;\n    }\n    case P4_INT64: {\n      sqlite3_snprintf(nTemp, zTemp, \"%lld\", *pOp->p4.pI64);\n      break;\n    }\n    case P4_INT32: {\n      sqlite3_snprintf(nTemp, zTemp, \"%d\", pOp->p4.i);\n      break;\n    }\n    case P4_REAL: {\n      sqlite3_snprintf(nTemp, zTemp, \"%.16g\", *pOp->p4.pReal);\n      break;\n    }\n    case P4_MEM: {\n      Mem *pMem = pOp->p4.pMem;\n      if( pMem->flags & MEM_Str ){\n        zP4 = pMem->z;\n      }else if( pMem->flags & MEM_Int ){\n        sqlite3_snprintf(nTemp, zTemp, \"%lld\", pMem->u.i);\n      }else if( pMem->flags & MEM_Real ){\n        sqlite3_snprintf(nTemp, zTemp, \"%.16g\", pMem->r);\n      }else if( pMem->flags & MEM_Null ){\n        sqlite3_snprintf(nTemp, zTemp, \"NULL\");\n      }else{\n        assert( pMem->flags & MEM_Blob );\n        zP4 = \"(blob)\";\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    case P4_VTAB: {\n      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;\n      sqlite3_snprintf(nTemp, zTemp, \"vtab:%p:%p\", pVtab, pVtab->pModule);\n      break;\n    }\n#endif\n    case P4_INTARRAY: {\n      sqlite3_snprintf(nTemp, zTemp, \"intarray\");\n      break;\n    }\n    case P4_SUBPROGRAM: {\n      sqlite3_snprintf(nTemp, zTemp, \"program\");\n      break;\n    }\n    case P4_ADVANCE: {\n      zTemp[0] = 0;\n      break;\n    }\n    default: {\n      zP4 = pOp->p4.z;\n      if( zP4==0 ){\n        zP4 = zTemp;\n        zTemp[0] = 0;\n      }\n    }\n  }\n  assert( zP4!=0 );\n  return zP4;\n}\n#endif\n\n/*\n** Declare to the Vdbe that the BTree object at db->aDb[i] is used.\n**\n** The prepared statements need to know in advance the complete set of\n** attached databases that will be use.  A mask of these databases\n** is maintained in p->btreeMask.  The p->lockMask value is the subset of\n** p->btreeMask of databases that will require a lock.\n*/\nSQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){\n  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );\n  assert( i<(int)sizeof(p->btreeMask)*8 );\n  p->btreeMask |= ((yDbMask)1)<<i;\n  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){\n    p->lockMask |= ((yDbMask)1)<<i;\n  }\n}\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0\n/*\n** If SQLite is compiled to support shared-cache mode and to be threadsafe,\n** this routine obtains the mutex associated with each BtShared structure\n** that may be accessed by the VM passed as an argument. In doing so it also\n** sets the BtShared.db member of each of the BtShared structures, ensuring\n** that the correct busy-handler callback is invoked if required.\n**\n** If SQLite is not threadsafe but does support shared-cache mode, then\n** sqlite3BtreeEnter() is invoked to set the BtShared.db variables\n** of all of BtShared structures accessible via the database handle \n** associated with the VM.\n**\n** If SQLite is not threadsafe and does not support shared-cache mode, this\n** function is a no-op.\n**\n** The p->btreeMask field is a bitmask of all btrees that the prepared \n** statement p will ever use.  Let N be the number of bits in p->btreeMask\n** corresponding to btrees that use shared cache.  Then the runtime of\n** this routine is N*N.  But as N is rarely more than 1, this should not\n** be a problem.\n*/\nSQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){\n  int i;\n  yDbMask mask;\n  sqlite3 *db;\n  Db *aDb;\n  int nDb;\n  if( p->lockMask==0 ) return;  /* The common case */\n  db = p->db;\n  aDb = db->aDb;\n  nDb = db->nDb;\n  for(i=0, mask=1; i<nDb; i++, mask += mask){\n    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){\n      sqlite3BtreeEnter(aDb[i].pBt);\n    }\n  }\n}\n#endif\n\n#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0\n/*\n** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().\n*/\nSQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){\n  int i;\n  yDbMask mask;\n  sqlite3 *db;\n  Db *aDb;\n  int nDb;\n  if( p->lockMask==0 ) return;  /* The common case */\n  db = p->db;\n  aDb = db->aDb;\n  nDb = db->nDb;\n  for(i=0, mask=1; i<nDb; i++, mask += mask){\n    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){\n      sqlite3BtreeLeave(aDb[i].pBt);\n    }\n  }\n}\n#endif\n\n#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)\n/*\n** Print a single opcode.  This routine is used for debugging only.\n*/\nSQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){\n  char *zP4;\n  char zPtr[50];\n  static const char *zFormat1 = \"%4d %-13s %4d %4d %4d %-4s %.2X %s\\n\";\n  if( pOut==0 ) pOut = stdout;\n  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));\n  fprintf(pOut, zFormat1, pc, \n      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,\n#ifdef SQLITE_DEBUG\n      pOp->zComment ? pOp->zComment : \"\"\n#else\n      \"\"\n#endif\n  );\n  fflush(pOut);\n}\n#endif\n\n/*\n** Release an array of N Mem elements\n*/\nstatic void releaseMemArray(Mem *p, int N){\n  if( p && N ){\n    Mem *pEnd;\n    sqlite3 *db = p->db;\n    u8 malloc_failed = db->mallocFailed;\n    if( db->pnBytesFreed ){\n      for(pEnd=&p[N]; p<pEnd; p++){\n        sqlite3DbFree(db, p->zMalloc);\n      }\n      return;\n    }\n    for(pEnd=&p[N]; p<pEnd; p++){\n      assert( (&p[1])==pEnd || p[0].db==p[1].db );\n\n      /* This block is really an inlined version of sqlite3VdbeMemRelease()\n      ** that takes advantage of the fact that the memory cell value is \n      ** being set to NULL after releasing any dynamic resources.\n      **\n      ** The justification for duplicating code is that according to \n      ** callgrind, this causes a certain test case to hit the CPU 4.7 \n      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if \n      ** sqlite3MemRelease() were called from here. With -O2, this jumps\n      ** to 6.6 percent. The test case is inserting 1000 rows into a table \n      ** with no indexes using a single prepared INSERT statement, bind() \n      ** and reset(). Inserts are grouped into a transaction.\n      */\n      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){\n        sqlite3VdbeMemRelease(p);\n      }else if( p->zMalloc ){\n        sqlite3DbFree(db, p->zMalloc);\n        p->zMalloc = 0;\n      }\n\n      p->flags = MEM_Invalid;\n    }\n    db->mallocFailed = malloc_failed;\n  }\n}\n\n/*\n** Delete a VdbeFrame object and its contents. VdbeFrame objects are\n** allocated by the OP_Program opcode in sqlite3VdbeExec().\n*/\nSQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){\n  int i;\n  Mem *aMem = VdbeFrameMem(p);\n  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];\n  for(i=0; i<p->nChildCsr; i++){\n    sqlite3VdbeFreeCursor(p->v, apCsr[i]);\n  }\n  releaseMemArray(aMem, p->nChildMem);\n  sqlite3DbFree(p->v->db, p);\n}\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** Give a listing of the program in the virtual machine.\n**\n** The interface is the same as sqlite3VdbeExec().  But instead of\n** running the code, it invokes the callback once for each instruction.\n** This feature is used to implement \"EXPLAIN\".\n**\n** When p->explain==1, each instruction is listed.  When\n** p->explain==2, only OP_Explain instructions are listed and these\n** are shown in a different format.  p->explain==2 is used to implement\n** EXPLAIN QUERY PLAN.\n**\n** When p->explain==1, first the main program is listed, then each of\n** the trigger subprograms are listed one by one.\n*/\nSQLITE_PRIVATE int sqlite3VdbeList(\n  Vdbe *p                   /* The VDBE */\n){\n  int nRow;                            /* Stop when row count reaches this */\n  int nSub = 0;                        /* Number of sub-vdbes seen so far */\n  SubProgram **apSub = 0;              /* Array of sub-vdbes */\n  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */\n  sqlite3 *db = p->db;                 /* The database connection */\n  int i;                               /* Loop counter */\n  int rc = SQLITE_OK;                  /* Return code */\n  Mem *pMem = &p->aMem[1];             /* First Mem of result set */\n\n  assert( p->explain );\n  assert( p->magic==VDBE_MAGIC_RUN );\n  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );\n\n  /* Even though this opcode does not use dynamic strings for\n  ** the result, result columns may become dynamic if the user calls\n  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.\n  */\n  releaseMemArray(pMem, 8);\n  p->pResultSet = 0;\n\n  if( p->rc==SQLITE_NOMEM ){\n    /* This happens if a malloc() inside a call to sqlite3_column_text() or\n    ** sqlite3_column_text16() failed.  */\n    db->mallocFailed = 1;\n    return SQLITE_ERROR;\n  }\n\n  /* When the number of output rows reaches nRow, that means the\n  ** listing has finished and sqlite3_step() should return SQLITE_DONE.\n  ** nRow is the sum of the number of rows in the main program, plus\n  ** the sum of the number of rows in all trigger subprograms encountered\n  ** so far.  The nRow value will increase as new trigger subprograms are\n  ** encountered, but p->pc will eventually catch up to nRow.\n  */\n  nRow = p->nOp;\n  if( p->explain==1 ){\n    /* The first 8 memory cells are used for the result set.  So we will\n    ** commandeer the 9th cell to use as storage for an array of pointers\n    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9\n    ** cells.  */\n    assert( p->nMem>9 );\n    pSub = &p->aMem[9];\n    if( pSub->flags&MEM_Blob ){\n      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is\n      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */\n      nSub = pSub->n/sizeof(Vdbe*);\n      apSub = (SubProgram **)pSub->z;\n    }\n    for(i=0; i<nSub; i++){\n      nRow += apSub[i]->nOp;\n    }\n  }\n\n  do{\n    i = p->pc++;\n  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );\n  if( i>=nRow ){\n    p->rc = SQLITE_OK;\n    rc = SQLITE_DONE;\n  }else if( db->u1.isInterrupted ){\n    p->rc = SQLITE_INTERRUPT;\n    rc = SQLITE_ERROR;\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3ErrStr(p->rc));\n  }else{\n    char *z;\n    Op *pOp;\n    if( i<p->nOp ){\n      /* The output line number is small enough that we are still in the\n      ** main program. */\n      pOp = &p->aOp[i];\n    }else{\n      /* We are currently listing subprograms.  Figure out which one and\n      ** pick up the appropriate opcode. */\n      int j;\n      i -= p->nOp;\n      for(j=0; i>=apSub[j]->nOp; j++){\n        i -= apSub[j]->nOp;\n      }\n      pOp = &apSub[j]->aOp[i];\n    }\n    if( p->explain==1 ){\n      pMem->flags = MEM_Int;\n      pMem->type = SQLITE_INTEGER;\n      pMem->u.i = i;                                /* Program counter */\n      pMem++;\n  \n      pMem->flags = MEM_Static|MEM_Str|MEM_Term;\n      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */\n      assert( pMem->z!=0 );\n      pMem->n = sqlite3Strlen30(pMem->z);\n      pMem->type = SQLITE_TEXT;\n      pMem->enc = SQLITE_UTF8;\n      pMem++;\n\n      /* When an OP_Program opcode is encounter (the only opcode that has\n      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms\n      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram\n      ** has not already been seen.\n      */\n      if( pOp->p4type==P4_SUBPROGRAM ){\n        int nByte = (nSub+1)*sizeof(SubProgram*);\n        int j;\n        for(j=0; j<nSub; j++){\n          if( apSub[j]==pOp->p4.pProgram ) break;\n        }\n        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){\n          apSub = (SubProgram **)pSub->z;\n          apSub[nSub++] = pOp->p4.pProgram;\n          pSub->flags |= MEM_Blob;\n          pSub->n = nSub*sizeof(SubProgram*);\n        }\n      }\n    }\n\n    pMem->flags = MEM_Int;\n    pMem->u.i = pOp->p1;                          /* P1 */\n    pMem->type = SQLITE_INTEGER;\n    pMem++;\n\n    pMem->flags = MEM_Int;\n    pMem->u.i = pOp->p2;                          /* P2 */\n    pMem->type = SQLITE_INTEGER;\n    pMem++;\n\n    pMem->flags = MEM_Int;\n    pMem->u.i = pOp->p3;                          /* P3 */\n    pMem->type = SQLITE_INTEGER;\n    pMem++;\n\n    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */\n      assert( p->db->mallocFailed );\n      return SQLITE_ERROR;\n    }\n    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;\n    z = displayP4(pOp, pMem->z, 32);\n    if( z!=pMem->z ){\n      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);\n    }else{\n      assert( pMem->z!=0 );\n      pMem->n = sqlite3Strlen30(pMem->z);\n      pMem->enc = SQLITE_UTF8;\n    }\n    pMem->type = SQLITE_TEXT;\n    pMem++;\n\n    if( p->explain==1 ){\n      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){\n        assert( p->db->mallocFailed );\n        return SQLITE_ERROR;\n      }\n      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;\n      pMem->n = 2;\n      sqlite3_snprintf(3, pMem->z, \"%.2x\", pOp->p5);   /* P5 */\n      pMem->type = SQLITE_TEXT;\n      pMem->enc = SQLITE_UTF8;\n      pMem++;\n  \n#ifdef SQLITE_DEBUG\n      if( pOp->zComment ){\n        pMem->flags = MEM_Str|MEM_Term;\n        pMem->z = pOp->zComment;\n        pMem->n = sqlite3Strlen30(pMem->z);\n        pMem->enc = SQLITE_UTF8;\n        pMem->type = SQLITE_TEXT;\n      }else\n#endif\n      {\n        pMem->flags = MEM_Null;                       /* Comment */\n        pMem->type = SQLITE_NULL;\n      }\n    }\n\n    p->nResColumn = 8 - 4*(p->explain-1);\n    p->pResultSet = &p->aMem[1];\n    p->rc = SQLITE_OK;\n    rc = SQLITE_ROW;\n  }\n  return rc;\n}\n#endif /* SQLITE_OMIT_EXPLAIN */\n\n#ifdef SQLITE_DEBUG\n/*\n** Print the SQL that was used to generate a VDBE program.\n*/\nSQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){\n  int nOp = p->nOp;\n  VdbeOp *pOp;\n  if( nOp<1 ) return;\n  pOp = &p->aOp[0];\n  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){\n    const char *z = pOp->p4.z;\n    while( sqlite3Isspace(*z) ) z++;\n    printf(\"SQL: [%s]\\n\", z);\n  }\n}\n#endif\n\n#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)\n/*\n** Print an IOTRACE message showing SQL content.\n*/\nSQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){\n  int nOp = p->nOp;\n  VdbeOp *pOp;\n  if( sqlite3IoTrace==0 ) return;\n  if( nOp<1 ) return;\n  pOp = &p->aOp[0];\n  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){\n    int i, j;\n    char z[1000];\n    sqlite3_snprintf(sizeof(z), z, \"%s\", pOp->p4.z);\n    for(i=0; sqlite3Isspace(z[i]); i++){}\n    for(j=0; z[i]; i++){\n      if( sqlite3Isspace(z[i]) ){\n        if( z[i-1]!=' ' ){\n          z[j++] = ' ';\n        }\n      }else{\n        z[j++] = z[i];\n      }\n    }\n    z[j] = 0;\n    sqlite3IoTrace(\"SQL %s\\n\", z);\n  }\n}\n#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */\n\n/*\n** Allocate space from a fixed size buffer and return a pointer to\n** that space.  If insufficient space is available, return NULL.\n**\n** The pBuf parameter is the initial value of a pointer which will\n** receive the new memory.  pBuf is normally NULL.  If pBuf is not\n** NULL, it means that memory space has already been allocated and that\n** this routine should not allocate any new memory.  When pBuf is not\n** NULL simply return pBuf.  Only allocate new memory space when pBuf\n** is NULL.\n**\n** nByte is the number of bytes of space needed.\n**\n** *ppFrom points to available space and pEnd points to the end of the\n** available space.  When space is allocated, *ppFrom is advanced past\n** the end of the allocated space.\n**\n** *pnByte is a counter of the number of bytes of space that have failed\n** to allocate.  If there is insufficient space in *ppFrom to satisfy the\n** request, then increment *pnByte by the amount of the request.\n*/\nstatic void *allocSpace(\n  void *pBuf,          /* Where return pointer will be stored */\n  int nByte,           /* Number of bytes to allocate */\n  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */\n  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */\n  int *pnByte          /* If allocation cannot be made, increment *pnByte */\n){\n  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );\n  if( pBuf ) return pBuf;\n  nByte = ROUND8(nByte);\n  if( &(*ppFrom)[nByte] <= pEnd ){\n    pBuf = (void*)*ppFrom;\n    *ppFrom += nByte;\n  }else{\n    *pnByte += nByte;\n  }\n  return pBuf;\n}\n\n/*\n** Rewind the VDBE back to the beginning in preparation for\n** running it.\n*/\nSQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){\n#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)\n  int i;\n#endif\n  assert( p!=0 );\n  assert( p->magic==VDBE_MAGIC_INIT );\n\n  /* There should be at least one opcode.\n  */\n  assert( p->nOp>0 );\n\n  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */\n  p->magic = VDBE_MAGIC_RUN;\n\n#ifdef SQLITE_DEBUG\n  for(i=1; i<p->nMem; i++){\n    assert( p->aMem[i].db==p->db );\n  }\n#endif\n  p->pc = -1;\n  p->rc = SQLITE_OK;\n  p->errorAction = OE_Abort;\n  p->magic = VDBE_MAGIC_RUN;\n  p->nChange = 0;\n  p->cacheCtr = 1;\n  p->minWriteFileFormat = 255;\n  p->iStatement = 0;\n  p->nFkConstraint = 0;\n#ifdef VDBE_PROFILE\n  for(i=0; i<p->nOp; i++){\n    p->aOp[i].cnt = 0;\n    p->aOp[i].cycles = 0;\n  }\n#endif\n}\n\n/*\n** Prepare a virtual machine for execution for the first time after\n** creating the virtual machine.  This involves things such\n** as allocating stack space and initializing the program counter.\n** After the VDBE has be prepped, it can be executed by one or more\n** calls to sqlite3VdbeExec().  \n**\n** This function may be called exact once on a each virtual machine.\n** After this routine is called the VM has been \"packaged\" and is ready\n** to run.  After this routine is called, futher calls to \n** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects\n** the Vdbe from the Parse object that helped generate it so that the\n** the Vdbe becomes an independent entity and the Parse object can be\n** destroyed.\n**\n** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back\n** to its initial state after it has been run.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMakeReady(\n  Vdbe *p,                       /* The VDBE */\n  Parse *pParse                  /* Parsing context */\n){\n  sqlite3 *db;                   /* The database connection */\n  int nVar;                      /* Number of parameters */\n  int nMem;                      /* Number of VM memory registers */\n  int nCursor;                   /* Number of cursors required */\n  int nArg;                      /* Number of arguments in subprograms */\n  int nOnce;                     /* Number of OP_Once instructions */\n  int n;                         /* Loop counter */\n  u8 *zCsr;                      /* Memory available for allocation */\n  u8 *zEnd;                      /* First byte past allocated memory */\n  int nByte;                     /* How much extra memory is needed */\n\n  assert( p!=0 );\n  assert( p->nOp>0 );\n  assert( pParse!=0 );\n  assert( p->magic==VDBE_MAGIC_INIT );\n  db = p->db;\n  assert( db->mallocFailed==0 );\n  nVar = pParse->nVar;\n  nMem = pParse->nMem;\n  nCursor = pParse->nTab;\n  nArg = pParse->nMaxArg;\n  nOnce = pParse->nOnce;\n  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */\n  \n  /* For each cursor required, also allocate a memory cell. Memory\n  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by\n  ** the vdbe program. Instead they are used to allocate space for\n  ** VdbeCursor/BtCursor structures. The blob of memory associated with \n  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)\n  ** stores the blob of memory associated with cursor 1, etc.\n  **\n  ** See also: allocateCursor().\n  */\n  nMem += nCursor;\n\n  /* Allocate space for memory registers, SQL variables, VDBE cursors and \n  ** an array to marshal SQL function arguments in.\n  */\n  zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */\n  zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */\n\n  resolveP2Values(p, &nArg);\n  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);\n  if( pParse->explain && nMem<10 ){\n    nMem = 10;\n  }\n  memset(zCsr, 0, zEnd-zCsr);\n  zCsr += (zCsr - (u8*)0)&7;\n  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );\n  p->expired = 0;\n\n  /* Memory for registers, parameters, cursor, etc, is allocated in two\n  ** passes.  On the first pass, we try to reuse unused space at the \n  ** end of the opcode array.  If we are unable to satisfy all memory\n  ** requirements by reusing the opcode array tail, then the second\n  ** pass will fill in the rest using a fresh allocation.  \n  **\n  ** This two-pass approach that reuses as much memory as possible from\n  ** the leftover space at the end of the opcode array can significantly\n  ** reduce the amount of memory held by a prepared statement.\n  */\n  do {\n    nByte = 0;\n    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);\n    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);\n    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);\n    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);\n    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),\n                          &zCsr, zEnd, &nByte);\n    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);\n    if( nByte ){\n      p->pFree = sqlite3DbMallocZero(db, nByte);\n    }\n    zCsr = p->pFree;\n    zEnd = &zCsr[nByte];\n  }while( nByte && !db->mallocFailed );\n\n  p->nCursor = (u16)nCursor;\n  p->nOnceFlag = nOnce;\n  if( p->aVar ){\n    p->nVar = (ynVar)nVar;\n    for(n=0; n<nVar; n++){\n      p->aVar[n].flags = MEM_Null;\n      p->aVar[n].db = db;\n    }\n  }\n  if( p->azVar ){\n    p->nzVar = pParse->nzVar;\n    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));\n    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));\n  }\n  if( p->aMem ){\n    p->aMem--;                      /* aMem[] goes from 1..nMem */\n    p->nMem = nMem;                 /*       not from 0..nMem-1 */\n    for(n=1; n<=nMem; n++){\n      p->aMem[n].flags = MEM_Invalid;\n      p->aMem[n].db = db;\n    }\n  }\n  p->explain = pParse->explain;\n  sqlite3VdbeRewind(p);\n}\n\n/*\n** Close a VDBE cursor and release all the resources that cursor \n** happens to hold.\n*/\nSQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){\n  if( pCx==0 ){\n    return;\n  }\n  sqlite3VdbeSorterClose(p->db, pCx);\n  if( pCx->pBt ){\n    sqlite3BtreeClose(pCx->pBt);\n    /* The pCx->pCursor will be close automatically, if it exists, by\n    ** the call above. */\n  }else if( pCx->pCursor ){\n    sqlite3BtreeCloseCursor(pCx->pCursor);\n  }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pCx->pVtabCursor ){\n    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;\n    const sqlite3_module *pModule = pCx->pModule;\n    p->inVtabMethod = 1;\n    pModule->xClose(pVtabCursor);\n    p->inVtabMethod = 0;\n  }\n#endif\n}\n\n/*\n** Copy the values stored in the VdbeFrame structure to its Vdbe. This\n** is used, for example, when a trigger sub-program is halted to restore\n** control to the main program.\n*/\nSQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){\n  Vdbe *v = pFrame->v;\n  v->aOnceFlag = pFrame->aOnceFlag;\n  v->nOnceFlag = pFrame->nOnceFlag;\n  v->aOp = pFrame->aOp;\n  v->nOp = pFrame->nOp;\n  v->aMem = pFrame->aMem;\n  v->nMem = pFrame->nMem;\n  v->apCsr = pFrame->apCsr;\n  v->nCursor = pFrame->nCursor;\n  v->db->lastRowid = pFrame->lastRowid;\n  v->nChange = pFrame->nChange;\n  return pFrame->pc;\n}\n\n/*\n** Close all cursors.\n**\n** Also release any dynamic memory held by the VM in the Vdbe.aMem memory \n** cell array. This is necessary as the memory cell array may contain\n** pointers to VdbeFrame objects, which may in turn contain pointers to\n** open cursors.\n*/\nstatic void closeAllCursors(Vdbe *p){\n  if( p->pFrame ){\n    VdbeFrame *pFrame;\n    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);\n    sqlite3VdbeFrameRestore(pFrame);\n  }\n  p->pFrame = 0;\n  p->nFrame = 0;\n\n  if( p->apCsr ){\n    int i;\n    for(i=0; i<p->nCursor; i++){\n      VdbeCursor *pC = p->apCsr[i];\n      if( pC ){\n        sqlite3VdbeFreeCursor(p, pC);\n        p->apCsr[i] = 0;\n      }\n    }\n  }\n  if( p->aMem ){\n    releaseMemArray(&p->aMem[1], p->nMem);\n  }\n  while( p->pDelFrame ){\n    VdbeFrame *pDel = p->pDelFrame;\n    p->pDelFrame = pDel->pParent;\n    sqlite3VdbeFrameDelete(pDel);\n  }\n}\n\n/*\n** Clean up the VM after execution.\n**\n** This routine will automatically close any cursors, lists, and/or\n** sorters that were left open.  It also deletes the values of\n** variables in the aVar[] array.\n*/\nstatic void Cleanup(Vdbe *p){\n  sqlite3 *db = p->db;\n\n#ifdef SQLITE_DEBUG\n  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and \n  ** Vdbe.aMem[] arrays have already been cleaned up.  */\n  int i;\n  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );\n  if( p->aMem ){\n    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );\n  }\n#endif\n\n  sqlite3DbFree(db, p->zErrMsg);\n  p->zErrMsg = 0;\n  p->pResultSet = 0;\n}\n\n/*\n** Set the number of result columns that will be returned by this SQL\n** statement. This is now set at compile time, rather than during\n** execution of the vdbe program so that sqlite3_column_count() can\n** be called on an SQL statement before sqlite3_step().\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){\n  Mem *pColName;\n  int n;\n  sqlite3 *db = p->db;\n\n  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);\n  sqlite3DbFree(db, p->aColName);\n  n = nResColumn*COLNAME_N;\n  p->nResColumn = (u16)nResColumn;\n  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );\n  if( p->aColName==0 ) return;\n  while( n-- > 0 ){\n    pColName->flags = MEM_Null;\n    pColName->db = p->db;\n    pColName++;\n  }\n}\n\n/*\n** Set the name of the idx'th column to be returned by the SQL statement.\n** zName must be a pointer to a nul terminated string.\n**\n** This call must be made after a call to sqlite3VdbeSetNumCols().\n**\n** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC\n** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed\n** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSetColName(\n  Vdbe *p,                         /* Vdbe being configured */\n  int idx,                         /* Index of column zName applies to */\n  int var,                         /* One of the COLNAME_* constants */\n  const char *zName,               /* Pointer to buffer containing name */\n  void (*xDel)(void*)              /* Memory management strategy for zName */\n){\n  int rc;\n  Mem *pColName;\n  assert( idx<p->nResColumn );\n  assert( var<COLNAME_N );\n  if( p->db->mallocFailed ){\n    assert( !zName || xDel!=SQLITE_DYNAMIC );\n    return SQLITE_NOMEM;\n  }\n  assert( p->aColName!=0 );\n  pColName = &(p->aColName[idx+var*p->nResColumn]);\n  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);\n  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );\n  return rc;\n}\n\n/*\n** A read or write transaction may or may not be active on database handle\n** db. If a transaction is active, commit it. If there is a\n** write-transaction spanning more than one database file, this routine\n** takes care of the master journal trickery.\n*/\nstatic int vdbeCommit(sqlite3 *db, Vdbe *p){\n  int i;\n  int nTrans = 0;  /* Number of databases with an active write-transaction */\n  int rc = SQLITE_OK;\n  int needXcommit = 0;\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n  /* With this option, sqlite3VtabSync() is defined to be simply \n  ** SQLITE_OK so p is not used. \n  */\n  UNUSED_PARAMETER(p);\n#endif\n\n  /* Before doing anything else, call the xSync() callback for any\n  ** virtual module tables written in this transaction. This has to\n  ** be done before determining whether a master journal file is \n  ** required, as an xSync() callback may add an attached database\n  ** to the transaction.\n  */\n  rc = sqlite3VtabSync(db, &p->zErrMsg);\n\n  /* This loop determines (a) if the commit hook should be invoked and\n  ** (b) how many database files have open write transactions, not \n  ** including the temp database. (b) is important because if more than \n  ** one database file has an open write transaction, a master journal\n  ** file is required for an atomic commit.\n  */ \n  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ \n    Btree *pBt = db->aDb[i].pBt;\n    if( sqlite3BtreeIsInTrans(pBt) ){\n      needXcommit = 1;\n      if( i!=1 ) nTrans++;\n      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));\n    }\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* If there are any write-transactions at all, invoke the commit hook */\n  if( needXcommit && db->xCommitCallback ){\n    rc = db->xCommitCallback(db->pCommitArg);\n    if( rc ){\n      return SQLITE_CONSTRAINT;\n    }\n  }\n\n  /* The simple case - no more than one database file (not counting the\n  ** TEMP database) has a transaction active.   There is no need for the\n  ** master-journal.\n  **\n  ** If the return value of sqlite3BtreeGetFilename() is a zero length\n  ** string, it means the main database is :memory: or a temp file.  In \n  ** that case we do not support atomic multi-file commits, so use the \n  ** simple case then too.\n  */\n  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))\n   || nTrans<=1\n  ){\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);\n      }\n    }\n\n    /* Do the commit only if all databases successfully complete phase 1. \n    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an\n    ** IO error while deleting or truncating a journal file. It is unlikely,\n    ** but could happen. In this case abandon processing and return the error.\n    */\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);\n      }\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3VtabCommit(db);\n    }\n  }\n\n  /* The complex case - There is a multi-file write-transaction active.\n  ** This requires a master journal file to ensure the transaction is\n  ** committed atomicly.\n  */\n#ifndef SQLITE_OMIT_DISKIO\n  else{\n    sqlite3_vfs *pVfs = db->pVfs;\n    int needSync = 0;\n    char *zMaster = 0;   /* File-name for the master journal */\n    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);\n    sqlite3_file *pMaster = 0;\n    i64 offset = 0;\n    int res;\n    int retryCount = 0;\n    int nMainFile;\n\n    /* Select a master journal file name */\n    nMainFile = sqlite3Strlen30(zMainFile);\n    zMaster = sqlite3MPrintf(db, \"%s-mjXXXXXX9XXz\", zMainFile);\n    if( zMaster==0 ) return SQLITE_NOMEM;\n    do {\n      u32 iRandom;\n      if( retryCount ){\n        if( retryCount>100 ){\n          sqlite3_log(SQLITE_FULL, \"MJ delete: %s\", zMaster);\n          sqlite3OsDelete(pVfs, zMaster, 0);\n          break;\n        }else if( retryCount==1 ){\n          sqlite3_log(SQLITE_FULL, \"MJ collide: %s\", zMaster);\n        }\n      }\n      retryCount++;\n      sqlite3_randomness(sizeof(iRandom), &iRandom);\n      sqlite3_snprintf(13, &zMaster[nMainFile], \"-mj%06X9%02X\",\n                               (iRandom>>8)&0xffffff, iRandom&0xff);\n      /* The antipenultimate character of the master journal name must\n      ** be \"9\" to avoid name collisions when using 8+3 filenames. */\n      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );\n      sqlite3FileSuffix3(zMainFile, zMaster);\n      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);\n    }while( rc==SQLITE_OK && res );\n    if( rc==SQLITE_OK ){\n      /* Open the master journal. */\n      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, \n          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|\n          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0\n      );\n    }\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(db, zMaster);\n      return rc;\n    }\n \n    /* Write the name of each database file in the transaction into the new\n    ** master journal file. If an error occurs at this point close\n    ** and delete the master journal file. All the individual journal files\n    ** still have 'null' as the master journal pointer, so they will roll\n    ** back independently if a failure occurs.\n    */\n    for(i=0; i<db->nDb; i++){\n      Btree *pBt = db->aDb[i].pBt;\n      if( sqlite3BtreeIsInTrans(pBt) ){\n        char const *zFile = sqlite3BtreeGetJournalname(pBt);\n        if( zFile==0 ){\n          continue;  /* Ignore TEMP and :memory: databases */\n        }\n        assert( zFile[0]!=0 );\n        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){\n          needSync = 1;\n        }\n        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);\n        offset += sqlite3Strlen30(zFile)+1;\n        if( rc!=SQLITE_OK ){\n          sqlite3OsCloseFree(pMaster);\n          sqlite3OsDelete(pVfs, zMaster, 0);\n          sqlite3DbFree(db, zMaster);\n          return rc;\n        }\n      }\n    }\n\n    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device\n    ** flag is set this is not required.\n    */\n    if( needSync \n     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)\n     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))\n    ){\n      sqlite3OsCloseFree(pMaster);\n      sqlite3OsDelete(pVfs, zMaster, 0);\n      sqlite3DbFree(db, zMaster);\n      return rc;\n    }\n\n    /* Sync all the db files involved in the transaction. The same call\n    ** sets the master journal pointer in each individual journal. If\n    ** an error occurs here, do not delete the master journal file.\n    **\n    ** If the error occurs during the first call to\n    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the\n    ** master journal file will be orphaned. But we cannot delete it,\n    ** in case the master journal file name was written into the journal\n    ** file before the failure occurred.\n    */\n    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ \n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);\n      }\n    }\n    sqlite3OsCloseFree(pMaster);\n    assert( rc!=SQLITE_BUSY );\n    if( rc!=SQLITE_OK ){\n      sqlite3DbFree(db, zMaster);\n      return rc;\n    }\n\n    /* Delete the master journal file. This commits the transaction. After\n    ** doing this the directory is synced again before any individual\n    ** transaction files are deleted.\n    */\n    rc = sqlite3OsDelete(pVfs, zMaster, 1);\n    sqlite3DbFree(db, zMaster);\n    zMaster = 0;\n    if( rc ){\n      return rc;\n    }\n\n    /* All files and directories have already been synced, so the following\n    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and\n    ** deleting or truncating journals. If something goes wrong while\n    ** this is happening we don't really care. The integrity of the\n    ** transaction is already guaranteed, but some stray 'cold' journals\n    ** may be lying around. Returning an error code won't help matters.\n    */\n    disable_simulated_io_errors();\n    sqlite3BeginBenignMalloc();\n    for(i=0; i<db->nDb; i++){ \n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        sqlite3BtreeCommitPhaseTwo(pBt, 1);\n      }\n    }\n    sqlite3EndBenignMalloc();\n    enable_simulated_io_errors();\n\n    sqlite3VtabCommit(db);\n  }\n#endif\n\n  return rc;\n}\n\n/* \n** This routine checks that the sqlite3.activeVdbeCnt count variable\n** matches the number of vdbe's in the list sqlite3.pVdbe that are\n** currently active. An assertion fails if the two counts do not match.\n** This is an internal self-check only - it is not an essential processing\n** step.\n**\n** This is a no-op if NDEBUG is defined.\n*/\n#ifndef NDEBUG\nstatic void checkActiveVdbeCnt(sqlite3 *db){\n  Vdbe *p;\n  int cnt = 0;\n  int nWrite = 0;\n  p = db->pVdbe;\n  while( p ){\n    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){\n      cnt++;\n      if( p->readOnly==0 ) nWrite++;\n    }\n    p = p->pNext;\n  }\n  assert( cnt==db->activeVdbeCnt );\n  assert( nWrite==db->writeVdbeCnt );\n}\n#else\n#define checkActiveVdbeCnt(x)\n#endif\n\n/*\n** If the Vdbe passed as the first argument opened a statement-transaction,\n** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or\n** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement\n** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the \n** statement transaction is commtted.\n**\n** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. \n** Otherwise SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){\n  sqlite3 *const db = p->db;\n  int rc = SQLITE_OK;\n\n  /* If p->iStatement is greater than zero, then this Vdbe opened a \n  ** statement transaction that should be closed here. The only exception\n  ** is that an IO error may have occured, causing an emergency rollback.\n  ** In this case (db->nStatement==0), and there is nothing to do.\n  */\n  if( db->nStatement && p->iStatement ){\n    int i;\n    const int iSavepoint = p->iStatement-1;\n\n    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);\n    assert( db->nStatement>0 );\n    assert( p->iStatement==(db->nStatement+db->nSavepoint) );\n\n    for(i=0; i<db->nDb; i++){ \n      int rc2 = SQLITE_OK;\n      Btree *pBt = db->aDb[i].pBt;\n      if( pBt ){\n        if( eOp==SAVEPOINT_ROLLBACK ){\n          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);\n        }\n        if( rc2==SQLITE_OK ){\n          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);\n        }\n        if( rc==SQLITE_OK ){\n          rc = rc2;\n        }\n      }\n    }\n    db->nStatement--;\n    p->iStatement = 0;\n\n    if( rc==SQLITE_OK ){\n      if( eOp==SAVEPOINT_ROLLBACK ){\n        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);\n      }\n      if( rc==SQLITE_OK ){\n        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);\n      }\n    }\n\n    /* If the statement transaction is being rolled back, also restore the \n    ** database handles deferred constraint counter to the value it had when \n    ** the statement transaction was opened.  */\n    if( eOp==SAVEPOINT_ROLLBACK ){\n      db->nDeferredCons = p->nStmtDefCons;\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is called when a transaction opened by the database \n** handle associated with the VM passed as an argument is about to be \n** committed. If there are outstanding deferred foreign key constraint\n** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.\n**\n** If there are outstanding FK violations and this function returns \n** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write\n** an error message to it. Then return SQLITE_ERROR.\n*/\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nSQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){\n  sqlite3 *db = p->db;\n  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){\n    p->rc = SQLITE_CONSTRAINT;\n    p->errorAction = OE_Abort;\n    sqlite3SetString(&p->zErrMsg, db, \"foreign key constraint failed\");\n    return SQLITE_ERROR;\n  }\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** This routine is called the when a VDBE tries to halt.  If the VDBE\n** has made changes and is in autocommit mode, then commit those\n** changes.  If a rollback is needed, then do the rollback.\n**\n** This routine is the only way to move the state of a VM from\n** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to\n** call this on a VM that is in the SQLITE_MAGIC_HALT state.\n**\n** Return an error code.  If the commit could not complete because of\n** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it\n** means the close did not happen and needs to be repeated.\n*/\nSQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){\n  int rc;                         /* Used to store transient return codes */\n  sqlite3 *db = p->db;\n\n  /* This function contains the logic that determines if a statement or\n  ** transaction will be committed or rolled back as a result of the\n  ** execution of this virtual machine. \n  **\n  ** If any of the following errors occur:\n  **\n  **     SQLITE_NOMEM\n  **     SQLITE_IOERR\n  **     SQLITE_FULL\n  **     SQLITE_INTERRUPT\n  **\n  ** Then the internal cache might have been left in an inconsistent\n  ** state.  We need to rollback the statement transaction, if there is\n  ** one, or the complete transaction if there is no statement transaction.\n  */\n\n  if( p->db->mallocFailed ){\n    p->rc = SQLITE_NOMEM;\n  }\n  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);\n  closeAllCursors(p);\n  if( p->magic!=VDBE_MAGIC_RUN ){\n    return SQLITE_OK;\n  }\n  checkActiveVdbeCnt(db);\n\n  /* No commit or rollback needed if the program never started */\n  if( p->pc>=0 ){\n    int mrc;   /* Primary error code from p->rc */\n    int eStatementOp = 0;\n    int isSpecialError;            /* Set to true if a 'special' error */\n\n    /* Lock all btrees used by the statement */\n    sqlite3VdbeEnter(p);\n\n    /* Check for one of the special errors */\n    mrc = p->rc & 0xff;\n    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */\n    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR\n                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;\n    if( isSpecialError ){\n      /* If the query was read-only and the error code is SQLITE_INTERRUPT, \n      ** no rollback is necessary. Otherwise, at least a savepoint \n      ** transaction must be rolled back to restore the database to a \n      ** consistent state.\n      **\n      ** Even if the statement is read-only, it is important to perform\n      ** a statement or transaction rollback operation. If the error \n      ** occured while writing to the journal, sub-journal or database\n      ** file as part of an effort to free up cache space (see function\n      ** pagerStress() in pager.c), the rollback is required to restore \n      ** the pager to a consistent state.\n      */\n      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){\n        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){\n          eStatementOp = SAVEPOINT_ROLLBACK;\n        }else{\n          /* We are forced to roll back the active transaction. Before doing\n          ** so, abort any other statements this handle currently has active.\n          */\n          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n          sqlite3CloseSavepoints(db);\n          db->autoCommit = 1;\n        }\n      }\n    }\n\n    /* Check for immediate foreign key violations. */\n    if( p->rc==SQLITE_OK ){\n      sqlite3VdbeCheckFk(p, 0);\n    }\n  \n    /* If the auto-commit flag is set and this is the only active writer \n    ** VM, then we do either a commit or rollback of the current transaction. \n    **\n    ** Note: This block also runs if one of the special errors handled \n    ** above has occurred. \n    */\n    if( !sqlite3VtabInSync(db) \n     && db->autoCommit \n     && db->writeVdbeCnt==(p->readOnly==0) \n    ){\n      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){\n        rc = sqlite3VdbeCheckFk(p, 1);\n        if( rc!=SQLITE_OK ){\n          if( NEVER(p->readOnly) ){\n            sqlite3VdbeLeave(p);\n            return SQLITE_ERROR;\n          }\n          rc = SQLITE_CONSTRAINT;\n        }else{ \n          /* The auto-commit flag is true, the vdbe program was successful \n          ** or hit an 'OR FAIL' constraint and there are no deferred foreign\n          ** key constraints to hold up the transaction. This means a commit \n          ** is required. */\n          rc = vdbeCommit(db, p);\n        }\n        if( rc==SQLITE_BUSY && p->readOnly ){\n          sqlite3VdbeLeave(p);\n          return SQLITE_BUSY;\n        }else if( rc!=SQLITE_OK ){\n          p->rc = rc;\n          sqlite3RollbackAll(db, SQLITE_OK);\n        }else{\n          db->nDeferredCons = 0;\n          sqlite3CommitInternalChanges(db);\n        }\n      }else{\n        sqlite3RollbackAll(db, SQLITE_OK);\n      }\n      db->nStatement = 0;\n    }else if( eStatementOp==0 ){\n      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){\n        eStatementOp = SAVEPOINT_RELEASE;\n      }else if( p->errorAction==OE_Abort ){\n        eStatementOp = SAVEPOINT_ROLLBACK;\n      }else{\n        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n        sqlite3CloseSavepoints(db);\n        db->autoCommit = 1;\n      }\n    }\n  \n    /* If eStatementOp is non-zero, then a statement transaction needs to\n    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to\n    ** do so. If this operation returns an error, and the current statement\n    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the\n    ** current statement error code.\n    */\n    if( eStatementOp ){\n      rc = sqlite3VdbeCloseStatement(p, eStatementOp);\n      if( rc ){\n        if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){\n          p->rc = rc;\n          sqlite3DbFree(db, p->zErrMsg);\n          p->zErrMsg = 0;\n        }\n        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n        sqlite3CloseSavepoints(db);\n        db->autoCommit = 1;\n      }\n    }\n  \n    /* If this was an INSERT, UPDATE or DELETE and no statement transaction\n    ** has been rolled back, update the database connection change-counter. \n    */\n    if( p->changeCntOn ){\n      if( eStatementOp!=SAVEPOINT_ROLLBACK ){\n        sqlite3VdbeSetChanges(db, p->nChange);\n      }else{\n        sqlite3VdbeSetChanges(db, 0);\n      }\n      p->nChange = 0;\n    }\n\n    /* Release the locks */\n    sqlite3VdbeLeave(p);\n  }\n\n  /* We have successfully halted and closed the VM.  Record this fact. */\n  if( p->pc>=0 ){\n    db->activeVdbeCnt--;\n    if( !p->readOnly ){\n      db->writeVdbeCnt--;\n    }\n    assert( db->activeVdbeCnt>=db->writeVdbeCnt );\n  }\n  p->magic = VDBE_MAGIC_HALT;\n  checkActiveVdbeCnt(db);\n  if( p->db->mallocFailed ){\n    p->rc = SQLITE_NOMEM;\n  }\n\n  /* If the auto-commit flag is set to true, then any locks that were held\n  ** by connection db have now been released. Call sqlite3ConnectionUnlocked() \n  ** to invoke any required unlock-notify callbacks.\n  */\n  if( db->autoCommit ){\n    sqlite3ConnectionUnlocked(db);\n  }\n\n  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );\n  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);\n}\n\n\n/*\n** Each VDBE holds the result of the most recent sqlite3_step() call\n** in p->rc.  This routine sets that result back to SQLITE_OK.\n*/\nSQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){\n  p->rc = SQLITE_OK;\n}\n\n/*\n** Copy the error code and error message belonging to the VDBE passed\n** as the first argument to its database handle (so that they will be \n** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).\n**\n** This function does not clear the VDBE error code or message, just\n** copies them to the database handle.\n*/\nSQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){\n  sqlite3 *db = p->db;\n  int rc = p->rc;\n  if( p->zErrMsg ){\n    u8 mallocFailed = db->mallocFailed;\n    sqlite3BeginBenignMalloc();\n    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);\n    sqlite3EndBenignMalloc();\n    db->mallocFailed = mallocFailed;\n    db->errCode = rc;\n  }else{\n    sqlite3Error(db, rc, 0);\n  }\n  return rc;\n}\n\n/*\n** Clean up a VDBE after execution but do not delete the VDBE just yet.\n** Write any error messages into *pzErrMsg.  Return the result code.\n**\n** After this routine is run, the VDBE should be ready to be executed\n** again.\n**\n** To look at it another way, this routine resets the state of the\n** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to\n** VDBE_MAGIC_INIT.\n*/\nSQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){\n  sqlite3 *db;\n  db = p->db;\n\n  /* If the VM did not run to completion or if it encountered an\n  ** error, then it might not have been halted properly.  So halt\n  ** it now.\n  */\n  sqlite3VdbeHalt(p);\n\n  /* If the VDBE has be run even partially, then transfer the error code\n  ** and error message from the VDBE into the main database structure.  But\n  ** if the VDBE has just been set to run but has not actually executed any\n  ** instructions yet, leave the main database error information unchanged.\n  */\n  if( p->pc>=0 ){\n    sqlite3VdbeTransferError(p);\n    sqlite3DbFree(db, p->zErrMsg);\n    p->zErrMsg = 0;\n    if( p->runOnlyOnce ) p->expired = 1;\n  }else if( p->rc && p->expired ){\n    /* The expired flag was set on the VDBE before the first call\n    ** to sqlite3_step(). For consistency (since sqlite3_step() was\n    ** called), set the database error in this case as well.\n    */\n    sqlite3Error(db, p->rc, 0);\n    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);\n    sqlite3DbFree(db, p->zErrMsg);\n    p->zErrMsg = 0;\n  }\n\n  /* Reclaim all memory used by the VDBE\n  */\n  Cleanup(p);\n\n  /* Save profiling information from this VDBE run.\n  */\n#ifdef VDBE_PROFILE\n  {\n    FILE *out = fopen(\"vdbe_profile.out\", \"a\");\n    if( out ){\n      int i;\n      fprintf(out, \"---- \");\n      for(i=0; i<p->nOp; i++){\n        fprintf(out, \"%02x\", p->aOp[i].opcode);\n      }\n      fprintf(out, \"\\n\");\n      for(i=0; i<p->nOp; i++){\n        fprintf(out, \"%6d %10lld %8lld \",\n           p->aOp[i].cnt,\n           p->aOp[i].cycles,\n           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0\n        );\n        sqlite3VdbePrintOp(out, i, &p->aOp[i]);\n      }\n      fclose(out);\n    }\n  }\n#endif\n  p->magic = VDBE_MAGIC_INIT;\n  return p->rc & db->errMask;\n}\n \n/*\n** Clean up and delete a VDBE after execution.  Return an integer which is\n** the result code.  Write any error message text into *pzErrMsg.\n*/\nSQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){\n  int rc = SQLITE_OK;\n  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){\n    rc = sqlite3VdbeReset(p);\n    assert( (rc & p->db->errMask)==rc );\n  }\n  sqlite3VdbeDelete(p);\n  return rc;\n}\n\n/*\n** Call the destructor for each auxdata entry in pVdbeFunc for which\n** the corresponding bit in mask is clear.  Auxdata entries beyond 31\n** are always destroyed.  To destroy all auxdata entries, call this\n** routine with mask==0.\n*/\nSQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){\n  int i;\n  for(i=0; i<pVdbeFunc->nAux; i++){\n    struct AuxData *pAux = &pVdbeFunc->apAux[i];\n    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){\n      if( pAux->xDelete ){\n        pAux->xDelete(pAux->pAux);\n      }\n      pAux->pAux = 0;\n    }\n  }\n}\n\n/*\n** Free all memory associated with the Vdbe passed as the second argument.\n** The difference between this function and sqlite3VdbeDelete() is that\n** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with\n** the database connection.\n*/\nSQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){\n  SubProgram *pSub, *pNext;\n  int i;\n  assert( p->db==0 || p->db==db );\n  releaseMemArray(p->aVar, p->nVar);\n  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);\n  for(pSub=p->pProgram; pSub; pSub=pNext){\n    pNext = pSub->pNext;\n    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);\n    sqlite3DbFree(db, pSub);\n  }\n  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);\n  vdbeFreeOpArray(db, p->aOp, p->nOp);\n  sqlite3DbFree(db, p->aLabel);\n  sqlite3DbFree(db, p->aColName);\n  sqlite3DbFree(db, p->zSql);\n  sqlite3DbFree(db, p->pFree);\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n  sqlite3DbFree(db, p->zExplain);\n  sqlite3DbFree(db, p->pExplain);\n#endif\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Delete an entire VDBE.\n*/\nSQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){\n  sqlite3 *db;\n\n  if( NEVER(p==0) ) return;\n  db = p->db;\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( p->pPrev ){\n    p->pPrev->pNext = p->pNext;\n  }else{\n    assert( db->pVdbe==p );\n    db->pVdbe = p->pNext;\n  }\n  if( p->pNext ){\n    p->pNext->pPrev = p->pPrev;\n  }\n  p->magic = VDBE_MAGIC_DEAD;\n  p->db = 0;\n  sqlite3VdbeDeleteObject(db, p);\n}\n\n/*\n** Make sure the cursor p is ready to read or write the row to which it\n** was last positioned.  Return an error code if an OOM fault or I/O error\n** prevents us from positioning the cursor to its correct position.\n**\n** If a MoveTo operation is pending on the given cursor, then do that\n** MoveTo now.  If no move is pending, check to see if the row has been\n** deleted out from under the cursor and if it has, mark the row as\n** a NULL row.\n**\n** If the cursor is already pointing to the correct row and that row has\n** not been deleted out from under the cursor, then this routine is a no-op.\n*/\nSQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){\n  if( p->deferredMoveto ){\n    int res, rc;\n#ifdef SQLITE_TEST\n    extern int sqlite3_search_count;\n#endif\n    assert( p->isTable );\n    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);\n    if( rc ) return rc;\n    p->lastRowid = p->movetoTarget;\n    if( res!=0 ) return SQLITE_CORRUPT_BKPT;\n    p->rowidIsValid = 1;\n#ifdef SQLITE_TEST\n    sqlite3_search_count++;\n#endif\n    p->deferredMoveto = 0;\n    p->cacheStatus = CACHE_STALE;\n  }else if( ALWAYS(p->pCursor) ){\n    int hasMoved;\n    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);\n    if( rc ) return rc;\n    if( hasMoved ){\n      p->cacheStatus = CACHE_STALE;\n      p->nullRow = 1;\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** The following functions:\n**\n** sqlite3VdbeSerialType()\n** sqlite3VdbeSerialTypeLen()\n** sqlite3VdbeSerialLen()\n** sqlite3VdbeSerialPut()\n** sqlite3VdbeSerialGet()\n**\n** encapsulate the code that serializes values for storage in SQLite\n** data and index records. Each serialized value consists of a\n** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned\n** integer, stored as a varint.\n**\n** In an SQLite index record, the serial type is stored directly before\n** the blob of data that it corresponds to. In a table record, all serial\n** types are stored at the start of the record, and the blobs of data at\n** the end. Hence these functions allow the caller to handle the\n** serial-type and data blob seperately.\n**\n** The following table describes the various storage classes for data:\n**\n**   serial type        bytes of data      type\n**   --------------     ---------------    ---------------\n**      0                     0            NULL\n**      1                     1            signed integer\n**      2                     2            signed integer\n**      3                     3            signed integer\n**      4                     4            signed integer\n**      5                     6            signed integer\n**      6                     8            signed integer\n**      7                     8            IEEE float\n**      8                     0            Integer constant 0\n**      9                     0            Integer constant 1\n**     10,11                               reserved for expansion\n**    N>=12 and even       (N-12)/2        BLOB\n**    N>=13 and odd        (N-13)/2        text\n**\n** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions\n** of SQLite will not understand those serial types.\n*/\n\n/*\n** Return the serial-type for the value stored in pMem.\n*/\nSQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){\n  int flags = pMem->flags;\n  int n;\n\n  if( flags&MEM_Null ){\n    return 0;\n  }\n  if( flags&MEM_Int ){\n    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */\n#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)\n    i64 i = pMem->u.i;\n    u64 u;\n    if( file_format>=4 && (i&1)==i ){\n      return 8+(u32)i;\n    }\n    if( i<0 ){\n      if( i<(-MAX_6BYTE) ) return 6;\n      /* Previous test prevents:  u = -(-9223372036854775808) */\n      u = -i;\n    }else{\n      u = i;\n    }\n    if( u<=127 ) return 1;\n    if( u<=32767 ) return 2;\n    if( u<=8388607 ) return 3;\n    if( u<=2147483647 ) return 4;\n    if( u<=MAX_6BYTE ) return 5;\n    return 6;\n  }\n  if( flags&MEM_Real ){\n    return 7;\n  }\n  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );\n  n = pMem->n;\n  if( flags & MEM_Zero ){\n    n += pMem->u.nZero;\n  }\n  assert( n>=0 );\n  return ((n*2) + 12 + ((flags&MEM_Str)!=0));\n}\n\n/*\n** Return the length of the data corresponding to the supplied serial-type.\n*/\nSQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){\n  if( serial_type>=12 ){\n    return (serial_type-12)/2;\n  }else{\n    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };\n    return aSize[serial_type];\n  }\n}\n\n/*\n** If we are on an architecture with mixed-endian floating \n** points (ex: ARM7) then swap the lower 4 bytes with the \n** upper 4 bytes.  Return the result.\n**\n** For most architectures, this is a no-op.\n**\n** (later):  It is reported to me that the mixed-endian problem\n** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems\n** that early versions of GCC stored the two words of a 64-bit\n** float in the wrong order.  And that error has been propagated\n** ever since.  The blame is not necessarily with GCC, though.\n** GCC might have just copying the problem from a prior compiler.\n** I am also told that newer versions of GCC that follow a different\n** ABI get the byte order right.\n**\n** Developers using SQLite on an ARM7 should compile and run their\n** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG\n** enabled, some asserts below will ensure that the byte order of\n** floating point values is correct.\n**\n** (2007-08-30)  Frank van Vugt has studied this problem closely\n** and has send his findings to the SQLite developers.  Frank\n** writes that some Linux kernels offer floating point hardware\n** emulation that uses only 32-bit mantissas instead of a full \n** 48-bits as required by the IEEE standard.  (This is the\n** CONFIG_FPE_FASTFPE option.)  On such systems, floating point\n** byte swapping becomes very complicated.  To avoid problems,\n** the necessary byte swapping is carried out using a 64-bit integer\n** rather than a 64-bit float.  Frank assures us that the code here\n** works for him.  We, the developers, have no way to independently\n** verify this, but Frank seems to know what he is talking about\n** so we trust him.\n*/\n#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT\nstatic u64 floatSwap(u64 in){\n  union {\n    u64 r;\n    u32 i[2];\n  } u;\n  u32 t;\n\n  u.r = in;\n  t = u.i[0];\n  u.i[0] = u.i[1];\n  u.i[1] = t;\n  return u.r;\n}\n# define swapMixedEndianFloat(X)  X = floatSwap(X)\n#else\n# define swapMixedEndianFloat(X)\n#endif\n\n/*\n** Write the serialized data blob for the value stored in pMem into \n** buf. It is assumed that the caller has allocated sufficient space.\n** Return the number of bytes written.\n**\n** nBuf is the amount of space left in buf[].  nBuf must always be\n** large enough to hold the entire field.  Except, if the field is\n** a blob with a zero-filled tail, then buf[] might be just the right\n** size to hold everything except for the zero-filled tail.  If buf[]\n** is only big enough to hold the non-zero prefix, then only write that\n** prefix into buf[].  But if buf[] is large enough to hold both the\n** prefix and the tail then write the prefix and set the tail to all\n** zeros.\n**\n** Return the number of bytes actually written into buf[].  The number\n** of bytes in the zero-filled tail is included in the return value only\n** if those bytes were zeroed in buf[].\n*/ \nSQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){\n  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);\n  u32 len;\n\n  /* Integer and Real */\n  if( serial_type<=7 && serial_type>0 ){\n    u64 v;\n    u32 i;\n    if( serial_type==7 ){\n      assert( sizeof(v)==sizeof(pMem->r) );\n      memcpy(&v, &pMem->r, sizeof(v));\n      swapMixedEndianFloat(v);\n    }else{\n      v = pMem->u.i;\n    }\n    len = i = sqlite3VdbeSerialTypeLen(serial_type);\n    assert( len<=(u32)nBuf );\n    while( i-- ){\n      buf[i] = (u8)(v&0xFF);\n      v >>= 8;\n    }\n    return len;\n  }\n\n  /* String or blob */\n  if( serial_type>=12 ){\n    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)\n             == (int)sqlite3VdbeSerialTypeLen(serial_type) );\n    assert( pMem->n<=nBuf );\n    len = pMem->n;\n    memcpy(buf, pMem->z, len);\n    if( pMem->flags & MEM_Zero ){\n      len += pMem->u.nZero;\n      assert( nBuf>=0 );\n      if( len > (u32)nBuf ){\n        len = (u32)nBuf;\n      }\n      memset(&buf[pMem->n], 0, len-pMem->n);\n    }\n    return len;\n  }\n\n  /* NULL or constants 0 or 1 */\n  return 0;\n}\n\n/*\n** Deserialize the data blob pointed to by buf as serial type serial_type\n** and store the result in pMem.  Return the number of bytes read.\n*/ \nSQLITE_PRIVATE u32 sqlite3VdbeSerialGet(\n  const unsigned char *buf,     /* Buffer to deserialize from */\n  u32 serial_type,              /* Serial type to deserialize */\n  Mem *pMem                     /* Memory cell to write value into */\n){\n  switch( serial_type ){\n    case 10:   /* Reserved for future use */\n    case 11:   /* Reserved for future use */\n    case 0: {  /* NULL */\n      pMem->flags = MEM_Null;\n      break;\n    }\n    case 1: { /* 1-byte signed integer */\n      pMem->u.i = (signed char)buf[0];\n      pMem->flags = MEM_Int;\n      return 1;\n    }\n    case 2: { /* 2-byte signed integer */\n      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];\n      pMem->flags = MEM_Int;\n      return 2;\n    }\n    case 3: { /* 3-byte signed integer */\n      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];\n      pMem->flags = MEM_Int;\n      return 3;\n    }\n    case 4: { /* 4-byte signed integer */\n      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];\n      pMem->flags = MEM_Int;\n      return 4;\n    }\n    case 5: { /* 6-byte signed integer */\n      u64 x = (((signed char)buf[0])<<8) | buf[1];\n      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];\n      x = (x<<32) | y;\n      pMem->u.i = *(i64*)&x;\n      pMem->flags = MEM_Int;\n      return 6;\n    }\n    case 6:   /* 8-byte signed integer */\n    case 7: { /* IEEE floating point */\n      u64 x;\n      u32 y;\n#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)\n      /* Verify that integers and floating point values use the same\n      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is\n      ** defined that 64-bit floating point values really are mixed\n      ** endian.\n      */\n      static const u64 t1 = ((u64)0x3ff00000)<<32;\n      static const double r1 = 1.0;\n      u64 t2 = t1;\n      swapMixedEndianFloat(t2);\n      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );\n#endif\n\n      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];\n      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];\n      x = (x<<32) | y;\n      if( serial_type==6 ){\n        pMem->u.i = *(i64*)&x;\n        pMem->flags = MEM_Int;\n      }else{\n        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );\n        swapMixedEndianFloat(x);\n        memcpy(&pMem->r, &x, sizeof(x));\n        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;\n      }\n      return 8;\n    }\n    case 8:    /* Integer 0 */\n    case 9: {  /* Integer 1 */\n      pMem->u.i = serial_type-8;\n      pMem->flags = MEM_Int;\n      return 0;\n    }\n    default: {\n      u32 len = (serial_type-12)/2;\n      pMem->z = (char *)buf;\n      pMem->n = len;\n      pMem->xDel = 0;\n      if( serial_type&0x01 ){\n        pMem->flags = MEM_Str | MEM_Ephem;\n      }else{\n        pMem->flags = MEM_Blob | MEM_Ephem;\n      }\n      return len;\n    }\n  }\n  return 0;\n}\n\n/*\n** This routine is used to allocate sufficient space for an UnpackedRecord\n** structure large enough to be used with sqlite3VdbeRecordUnpack() if\n** the first argument is a pointer to KeyInfo structure pKeyInfo.\n**\n** The space is either allocated using sqlite3DbMallocRaw() or from within\n** the unaligned buffer passed via the second and third arguments (presumably\n** stack space). If the former, then *ppFree is set to a pointer that should\n** be eventually freed by the caller using sqlite3DbFree(). Or, if the \n** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL\n** before returning.\n**\n** If an OOM error occurs, NULL is returned.\n*/\nSQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(\n  KeyInfo *pKeyInfo,              /* Description of the record */\n  char *pSpace,                   /* Unaligned space available */\n  int szSpace,                    /* Size of pSpace[] in bytes */\n  char **ppFree                   /* OUT: Caller should free this pointer */\n){\n  UnpackedRecord *p;              /* Unpacked record to return */\n  int nOff;                       /* Increment pSpace by nOff to align it */\n  int nByte;                      /* Number of bytes required for *p */\n\n  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.\n  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift \n  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.\n  */\n  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;\n  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);\n  if( nByte>szSpace+nOff ){\n    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);\n    *ppFree = (char *)p;\n    if( !p ) return 0;\n  }else{\n    p = (UnpackedRecord*)&pSpace[nOff];\n    *ppFree = 0;\n  }\n\n  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];\n  p->pKeyInfo = pKeyInfo;\n  p->nField = pKeyInfo->nField + 1;\n  return p;\n}\n\n/*\n** Given the nKey-byte encoding of a record in pKey[], populate the \n** UnpackedRecord structure indicated by the fourth argument with the\n** contents of the decoded record.\n*/ \nSQLITE_PRIVATE void sqlite3VdbeRecordUnpack(\n  KeyInfo *pKeyInfo,     /* Information about the record format */\n  int nKey,              /* Size of the binary record */\n  const void *pKey,      /* The binary record */\n  UnpackedRecord *p      /* Populate this structure before returning. */\n){\n  const unsigned char *aKey = (const unsigned char *)pKey;\n  int d; \n  u32 idx;                        /* Offset in aKey[] to read from */\n  u16 u;                          /* Unsigned loop counter */\n  u32 szHdr;\n  Mem *pMem = p->aMem;\n\n  p->flags = 0;\n  assert( EIGHT_BYTE_ALIGNMENT(pMem) );\n  idx = getVarint32(aKey, szHdr);\n  d = szHdr;\n  u = 0;\n  while( idx<szHdr && u<p->nField && d<=nKey ){\n    u32 serial_type;\n\n    idx += getVarint32(&aKey[idx], serial_type);\n    pMem->enc = pKeyInfo->enc;\n    pMem->db = pKeyInfo->db;\n    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */\n    pMem->zMalloc = 0;\n    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);\n    pMem++;\n    u++;\n  }\n  assert( u<=pKeyInfo->nField + 1 );\n  p->nField = u;\n}\n\n/*\n** This function compares the two table rows or index records\n** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero\n** or positive integer if key1 is less than, equal to or \n** greater than key2.  The {nKey1, pKey1} key must be a blob\n** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2\n** key must be a parsed key such as obtained from\n** sqlite3VdbeParseRecord.\n**\n** Key1 and Key2 do not have to contain the same number of fields.\n** The key with fewer fields is usually compares less than the \n** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set\n** and the common prefixes are equal, then key1 is less than key2.\n** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are\n** equal, then the keys are considered to be equal and\n** the parts beyond the common prefix are ignored.\n*/\nSQLITE_PRIVATE int sqlite3VdbeRecordCompare(\n  int nKey1, const void *pKey1, /* Left key */\n  UnpackedRecord *pPKey2        /* Right key */\n){\n  int d1;            /* Offset into aKey[] of next data element */\n  u32 idx1;          /* Offset into aKey[] of next header element */\n  u32 szHdr1;        /* Number of bytes in header */\n  int i = 0;\n  int nField;\n  int rc = 0;\n  const unsigned char *aKey1 = (const unsigned char *)pKey1;\n  KeyInfo *pKeyInfo;\n  Mem mem1;\n\n  pKeyInfo = pPKey2->pKeyInfo;\n  mem1.enc = pKeyInfo->enc;\n  mem1.db = pKeyInfo->db;\n  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */\n  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */\n\n  /* Compilers may complain that mem1.u.i is potentially uninitialized.\n  ** We could initialize it, as shown here, to silence those complaints.\n  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing \n  ** the unnecessary initialization has a measurable negative performance\n  ** impact, since this routine is a very high runner.  And so, we choose\n  ** to ignore the compiler warnings and leave this variable uninitialized.\n  */\n  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */\n  \n  idx1 = getVarint32(aKey1, szHdr1);\n  d1 = szHdr1;\n  nField = pKeyInfo->nField;\n  while( idx1<szHdr1 && i<pPKey2->nField ){\n    u32 serial_type1;\n\n    /* Read the serial types for the next element in each key. */\n    idx1 += getVarint32( aKey1+idx1, serial_type1 );\n    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;\n\n    /* Extract the values to be compared.\n    */\n    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);\n\n    /* Do the comparison\n    */\n    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],\n                           i<nField ? pKeyInfo->aColl[i] : 0);\n    if( rc!=0 ){\n      assert( mem1.zMalloc==0 );  /* See comment below */\n\n      /* Invert the result if we are using DESC sort order. */\n      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){\n        rc = -rc;\n      }\n    \n      /* If the PREFIX_SEARCH flag is set and all fields except the final\n      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set \n      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).\n      ** This is used by the OP_IsUnique opcode.\n      */\n      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){\n        assert( idx1==szHdr1 && rc );\n        assert( mem1.flags & MEM_Int );\n        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;\n        pPKey2->rowid = mem1.u.i;\n      }\n    \n      return rc;\n    }\n    i++;\n  }\n\n  /* No memory allocation is ever used on mem1.  Prove this using\n  ** the following assert().  If the assert() fails, it indicates a\n  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).\n  */\n  assert( mem1.zMalloc==0 );\n\n  /* rc==0 here means that one of the keys ran out of fields and\n  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY\n  ** flag is set, then break the tie by treating key2 as larger.\n  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes\n  ** are considered to be equal.  Otherwise, the longer key is the \n  ** larger.  As it happens, the pPKey2 will always be the longer\n  ** if there is a difference.\n  */\n  assert( rc==0 );\n  if( pPKey2->flags & UNPACKED_INCRKEY ){\n    rc = -1;\n  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){\n    /* Leave rc==0 */\n  }else if( idx1<szHdr1 ){\n    rc = 1;\n  }\n  return rc;\n}\n \n\n/*\n** pCur points at an index entry created using the OP_MakeRecord opcode.\n** Read the rowid (the last field in the record) and store it in *rowid.\n** Return SQLITE_OK if everything works, or an error code otherwise.\n**\n** pCur might be pointing to text obtained from a corrupt database file.\n** So the content cannot be trusted.  Do appropriate checks on the content.\n*/\nSQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){\n  i64 nCellKey = 0;\n  int rc;\n  u32 szHdr;        /* Size of the header */\n  u32 typeRowid;    /* Serial type of the rowid */\n  u32 lenRowid;     /* Size of the rowid */\n  Mem m, v;\n\n  UNUSED_PARAMETER(db);\n\n  /* Get the size of the index entry.  Only indices entries of less\n  ** than 2GiB are support - anything large must be database corruption.\n  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so\n  ** this code can safely assume that nCellKey is 32-bits  \n  */\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);\n  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */\n  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );\n\n  /* Read in the complete content of the index entry */\n  memset(&m, 0, sizeof(m));\n  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);\n  if( rc ){\n    return rc;\n  }\n\n  /* The index entry must begin with a header size */\n  (void)getVarint32((u8*)m.z, szHdr);\n  testcase( szHdr==3 );\n  testcase( szHdr==m.n );\n  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){\n    goto idx_rowid_corruption;\n  }\n\n  /* The last field of the index should be an integer - the ROWID.\n  ** Verify that the last entry really is an integer. */\n  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);\n  testcase( typeRowid==1 );\n  testcase( typeRowid==2 );\n  testcase( typeRowid==3 );\n  testcase( typeRowid==4 );\n  testcase( typeRowid==5 );\n  testcase( typeRowid==6 );\n  testcase( typeRowid==8 );\n  testcase( typeRowid==9 );\n  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){\n    goto idx_rowid_corruption;\n  }\n  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);\n  testcase( (u32)m.n==szHdr+lenRowid );\n  if( unlikely((u32)m.n<szHdr+lenRowid) ){\n    goto idx_rowid_corruption;\n  }\n\n  /* Fetch the integer off the end of the index record */\n  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);\n  *rowid = v.u.i;\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_OK;\n\n  /* Jump here if database corruption is detected after m has been\n  ** allocated.  Free the m object and return SQLITE_CORRUPT. */\nidx_rowid_corruption:\n  testcase( m.zMalloc!=0 );\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_CORRUPT_BKPT;\n}\n\n/*\n** Compare the key of the index entry that cursor pC is pointing to against\n** the key string in pUnpacked.  Write into *pRes a number\n** that is negative, zero, or positive if pC is less than, equal to,\n** or greater than pUnpacked.  Return SQLITE_OK on success.\n**\n** pUnpacked is either created without a rowid or is truncated so that it\n** omits the rowid at the end.  The rowid at the end of the index entry\n** is ignored as well.  Hence, this routine only compares the prefixes \n** of the keys prior to the final rowid, not the entire key.\n*/\nSQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(\n  VdbeCursor *pC,             /* The cursor to compare against */\n  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */\n  int *res                    /* Write the comparison result here */\n){\n  i64 nCellKey = 0;\n  int rc;\n  BtCursor *pCur = pC->pCursor;\n  Mem m;\n\n  assert( sqlite3BtreeCursorIsValid(pCur) );\n  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);\n  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */\n  /* nCellKey will always be between 0 and 0xffffffff because of the say\n  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */\n  if( nCellKey<=0 || nCellKey>0x7fffffff ){\n    *res = 0;\n    return SQLITE_CORRUPT_BKPT;\n  }\n  memset(&m, 0, sizeof(m));\n  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);\n  if( rc ){\n    return rc;\n  }\n  assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );\n  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);\n  sqlite3VdbeMemRelease(&m);\n  return SQLITE_OK;\n}\n\n/*\n** This routine sets the value to be returned by subsequent calls to\n** sqlite3_changes() on the database handle 'db'. \n*/\nSQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){\n  assert( sqlite3_mutex_held(db->mutex) );\n  db->nChange = nChange;\n  db->nTotalChange += nChange;\n}\n\n/*\n** Set a flag in the vdbe to update the change counter when it is finalised\n** or reset.\n*/\nSQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){\n  v->changeCntOn = 1;\n}\n\n/*\n** Mark every prepared statement associated with a database connection\n** as expired.\n**\n** An expired statement means that recompilation of the statement is\n** recommend.  Statements expire when things happen that make their\n** programs obsolete.  Removing user-defined functions or collating\n** sequences, or changing an authorization function are the types of\n** things that make prepared statements obsolete.\n*/\nSQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){\n  Vdbe *p;\n  for(p = db->pVdbe; p; p=p->pNext){\n    p->expired = 1;\n  }\n}\n\n/*\n** Return the database associated with the Vdbe.\n*/\nSQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){\n  return v->db;\n}\n\n/*\n** Return a pointer to an sqlite3_value structure containing the value bound\n** parameter iVar of VM v. Except, if the value is an SQL NULL, return \n** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*\n** constants) to the value before returning it.\n**\n** The returned value must be freed by the caller using sqlite3ValueFree().\n*/\nSQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){\n  assert( iVar>0 );\n  if( v ){\n    Mem *pMem = &v->aVar[iVar-1];\n    if( 0==(pMem->flags & MEM_Null) ){\n      sqlite3_value *pRet = sqlite3ValueNew(v->db);\n      if( pRet ){\n        sqlite3VdbeMemCopy((Mem *)pRet, pMem);\n        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);\n        sqlite3VdbeMemStoreType((Mem *)pRet);\n      }\n      return pRet;\n    }\n  }\n  return 0;\n}\n\n/*\n** Configure SQL variable iVar so that binding a new value to it signals\n** to sqlite3_reoptimize() that re-preparing the statement may result\n** in a better query plan.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){\n  assert( iVar>0 );\n  if( iVar>32 ){\n    v->expmask = 0xffffffff;\n  }else{\n    v->expmask |= ((u32)1 << (iVar-1));\n  }\n}\n\n/************** End of vdbeaux.c *********************************************/\n/************** Begin file vdbeapi.c *****************************************/\n/*\n** 2004 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to implement APIs that are part of the\n** VDBE.\n*/\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Return TRUE (non-zero) of the statement supplied as an argument needs\n** to be recompiled.  A statement needs to be recompiled whenever the\n** execution environment changes in a way that would alter the program\n** that sqlite3_prepare() generates.  For example, if new functions or\n** collating sequences are registered or if an authorizer function is\n** added or changed.\n*/\nSQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe*)pStmt;\n  return p==0 || p->expired;\n}\n#endif\n\n/*\n** Check on a Vdbe to make sure it has not been finalized.  Log\n** an error and return true if it has been finalized (or is otherwise\n** invalid).  Return false if it is ok.\n*/\nstatic int vdbeSafety(Vdbe *p){\n  if( p->db==0 ){\n    sqlite3_log(SQLITE_MISUSE, \"API called with finalized prepared statement\");\n    return 1;\n  }else{\n    return 0;\n  }\n}\nstatic int vdbeSafetyNotNull(Vdbe *p){\n  if( p==0 ){\n    sqlite3_log(SQLITE_MISUSE, \"API called with NULL prepared statement\");\n    return 1;\n  }else{\n    return vdbeSafety(p);\n  }\n}\n\n/*\n** The following routine destroys a virtual machine that is created by\n** the sqlite3_compile() routine. The integer returned is an SQLITE_\n** success/failure code that describes the result of executing the virtual\n** machine.\n**\n** This routine sets the error code and string returned by\n** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){\n  int rc;\n  if( pStmt==0 ){\n    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL\n    ** pointer is a harmless no-op. */\n    rc = SQLITE_OK;\n  }else{\n    Vdbe *v = (Vdbe*)pStmt;\n    sqlite3 *db = v->db;\n    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;\n    sqlite3_mutex_enter(db->mutex);\n    rc = sqlite3VdbeFinalize(v);\n    rc = sqlite3ApiExit(db, rc);\n    sqlite3LeaveMutexAndCloseZombie(db);\n  }\n  return rc;\n}\n\n/*\n** Terminate the current execution of an SQL statement and reset it\n** back to its starting state so that it can be reused. A success code from\n** the prior execution is returned.\n**\n** This routine sets the error code and string returned by\n** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){\n  int rc;\n  if( pStmt==0 ){\n    rc = SQLITE_OK;\n  }else{\n    Vdbe *v = (Vdbe*)pStmt;\n    sqlite3_mutex_enter(v->db->mutex);\n    rc = sqlite3VdbeReset(v);\n    sqlite3VdbeRewind(v);\n    assert( (rc & (v->db->errMask))==rc );\n    rc = sqlite3ApiExit(v->db, rc);\n    sqlite3_mutex_leave(v->db->mutex);\n  }\n  return rc;\n}\n\n/*\n** Set all the parameters in the compiled SQL statement to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){\n  int i;\n  int rc = SQLITE_OK;\n  Vdbe *p = (Vdbe*)pStmt;\n#if SQLITE_THREADSAFE\n  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;\n#endif\n  sqlite3_mutex_enter(mutex);\n  for(i=0; i<p->nVar; i++){\n    sqlite3VdbeMemRelease(&p->aVar[i]);\n    p->aVar[i].flags = MEM_Null;\n  }\n  if( p->isPrepareV2 && p->expmask ){\n    p->expired = 1;\n  }\n  sqlite3_mutex_leave(mutex);\n  return rc;\n}\n\n\n/**************************** sqlite3_value_  *******************************\n** The following routines extract information from a Mem or sqlite3_value\n** structure.\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){\n  Mem *p = (Mem*)pVal;\n  if( p->flags & (MEM_Blob|MEM_Str) ){\n    sqlite3VdbeMemExpandBlob(p);\n    p->flags &= ~MEM_Str;\n    p->flags |= MEM_Blob;\n    return p->n ? p->z : 0;\n  }else{\n    return sqlite3_value_text(pVal);\n  }\n}\nSQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){\n  return sqlite3ValueBytes(pVal, SQLITE_UTF8);\n}\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){\n  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);\n}\nSQLITE_API double sqlite3_value_double(sqlite3_value *pVal){\n  return sqlite3VdbeRealValue((Mem*)pVal);\n}\nSQLITE_API int sqlite3_value_int(sqlite3_value *pVal){\n  return (int)sqlite3VdbeIntValue((Mem*)pVal);\n}\nSQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){\n  return sqlite3VdbeIntValue((Mem*)pVal);\n}\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){\n  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);\n}\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16BE);\n}\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){\n  return sqlite3ValueText(pVal, SQLITE_UTF16LE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API int sqlite3_value_type(sqlite3_value* pVal){\n  return pVal->type;\n}\n\n/**************************** sqlite3_result_  *******************************\n** The following routines are used by user-defined functions to specify\n** the function result.\n**\n** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the\n** result as a string or blob but if the string or blob is too large, it\n** then sets the error code to SQLITE_TOOBIG\n*/\nstatic void setResultStrOrError(\n  sqlite3_context *pCtx,  /* Function context */\n  const char *z,          /* String pointer */\n  int n,                  /* Bytes in string, or negative */\n  u8 enc,                 /* Encoding of z.  0 for BLOBs */\n  void (*xDel)(void*)     /* Destructor function */\n){\n  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){\n    sqlite3_result_error_toobig(pCtx);\n  }\n}\nSQLITE_API void sqlite3_result_blob(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( n>=0 );\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  setResultStrOrError(pCtx, z, n, 0, xDel);\n}\nSQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);\n}\nSQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  pCtx->isError = SQLITE_ERROR;\n  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  pCtx->isError = SQLITE_ERROR;\n  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);\n}\n#endif\nSQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);\n}\nSQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);\n}\nSQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetNull(&pCtx->s);\n}\nSQLITE_API void sqlite3_result_text(\n  sqlite3_context *pCtx, \n  const char *z, \n  int n,\n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API void sqlite3_result_text16(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);\n}\nSQLITE_API void sqlite3_result_text16be(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);\n}\nSQLITE_API void sqlite3_result_text16le(\n  sqlite3_context *pCtx, \n  const void *z, \n  int n, \n  void (*xDel)(void *)\n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemCopy(&pCtx->s, pValue);\n}\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);\n}\nSQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){\n  pCtx->isError = errCode;\n  if( pCtx->s.flags & MEM_Null ){\n    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, \n                         SQLITE_UTF8, SQLITE_STATIC);\n  }\n}\n\n/* Force an SQLITE_TOOBIG error. */\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  pCtx->isError = SQLITE_TOOBIG;\n  sqlite3VdbeMemSetStr(&pCtx->s, \"string or blob too big\", -1, \n                       SQLITE_UTF8, SQLITE_STATIC);\n}\n\n/* An SQLITE_NOMEM error. */\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  sqlite3VdbeMemSetNull(&pCtx->s);\n  pCtx->isError = SQLITE_NOMEM;\n  pCtx->s.db->mallocFailed = 1;\n}\n\n/*\n** This function is called after a transaction has been committed. It \n** invokes callbacks registered with sqlite3_wal_hook() as required.\n*/\nstatic int doWalCallbacks(sqlite3 *db){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_WAL\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));\n      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){\n        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);\n      }\n    }\n  }\n#endif\n  return rc;\n}\n\n/*\n** Execute the statement pStmt, either until a row of data is ready, the\n** statement is completely executed or an error occurs.\n**\n** This routine implements the bulk of the logic behind the sqlite_step()\n** API.  The only thing omitted is the automatic recompile if a \n** schema change has occurred.  That detail is handled by the\n** outer sqlite3_step() wrapper procedure.\n*/\nstatic int sqlite3Step(Vdbe *p){\n  sqlite3 *db;\n  int rc;\n\n  assert(p);\n  if( p->magic!=VDBE_MAGIC_RUN ){\n    /* We used to require that sqlite3_reset() be called before retrying\n    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning\n    ** with version 3.7.0, we changed this so that sqlite3_reset() would\n    ** be called automatically instead of throwing the SQLITE_MISUSE error.\n    ** This \"automatic-reset\" change is not technically an incompatibility, \n    ** since any application that receives an SQLITE_MISUSE is broken by\n    ** definition.\n    **\n    ** Nevertheless, some published applications that were originally written\n    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE \n    ** returns, and those were broken by the automatic-reset change.  As a\n    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the\n    ** legacy behavior of returning SQLITE_MISUSE for cases where the \n    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED\n    ** or SQLITE_BUSY error.\n    */\n#ifdef SQLITE_OMIT_AUTORESET\n    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){\n      sqlite3_reset((sqlite3_stmt*)p);\n    }else{\n      return SQLITE_MISUSE_BKPT;\n    }\n#else\n    sqlite3_reset((sqlite3_stmt*)p);\n#endif\n  }\n\n  /* Check that malloc() has not failed. If it has, return early. */\n  db = p->db;\n  if( db->mallocFailed ){\n    p->rc = SQLITE_NOMEM;\n    return SQLITE_NOMEM;\n  }\n\n  if( p->pc<=0 && p->expired ){\n    p->rc = SQLITE_SCHEMA;\n    rc = SQLITE_ERROR;\n    goto end_of_step;\n  }\n  if( p->pc<0 ){\n    /* If there are no other statements currently running, then\n    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt\n    ** from interrupting a statement that has not yet started.\n    */\n    if( db->activeVdbeCnt==0 ){\n      db->u1.isInterrupted = 0;\n    }\n\n    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );\n\n#ifndef SQLITE_OMIT_TRACE\n    if( db->xProfile && !db->init.busy ){\n      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);\n    }\n#endif\n\n    db->activeVdbeCnt++;\n    if( p->readOnly==0 ) db->writeVdbeCnt++;\n    p->pc = 0;\n  }\n#ifndef SQLITE_OMIT_EXPLAIN\n  if( p->explain ){\n    rc = sqlite3VdbeList(p);\n  }else\n#endif /* SQLITE_OMIT_EXPLAIN */\n  {\n    db->vdbeExecCnt++;\n    rc = sqlite3VdbeExec(p);\n    db->vdbeExecCnt--;\n  }\n\n#ifndef SQLITE_OMIT_TRACE\n  /* Invoke the profile callback if there is one\n  */\n  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){\n    sqlite3_int64 iNow;\n    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);\n    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);\n  }\n#endif\n\n  if( rc==SQLITE_DONE ){\n    assert( p->rc==SQLITE_OK );\n    p->rc = doWalCallbacks(db);\n    if( p->rc!=SQLITE_OK ){\n      rc = SQLITE_ERROR;\n    }\n  }\n\n  db->errCode = rc;\n  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){\n    p->rc = SQLITE_NOMEM;\n  }\nend_of_step:\n  /* At this point local variable rc holds the value that should be \n  ** returned if this statement was compiled using the legacy \n  ** sqlite3_prepare() interface. According to the docs, this can only\n  ** be one of the values in the first assert() below. Variable p->rc \n  ** contains the value that would be returned if sqlite3_finalize() \n  ** were called on statement p.\n  */\n  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR \n       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE\n  );\n  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );\n  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){\n    /* If this statement was prepared using sqlite3_prepare_v2(), and an\n    ** error has occured, then return the error code in p->rc to the\n    ** caller. Set the error code in the database handle to the same value.\n    */ \n    rc = sqlite3VdbeTransferError(p);\n  }\n  return (rc&db->errMask);\n}\n\n/*\n** The maximum number of times that a statement will try to reparse\n** itself before giving up and returning SQLITE_SCHEMA.\n*/\n#ifndef SQLITE_MAX_SCHEMA_RETRY\n# define SQLITE_MAX_SCHEMA_RETRY 5\n#endif\n\n/*\n** This is the top-level implementation of sqlite3_step().  Call\n** sqlite3Step() to do most of the work.  If a schema error occurs,\n** call sqlite3Reprepare() and try again.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){\n  int rc = SQLITE_OK;      /* Result from sqlite3Step() */\n  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */\n  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */\n  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */\n  sqlite3 *db;             /* The database connection */\n\n  if( vdbeSafetyNotNull(v) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  db = v->db;\n  sqlite3_mutex_enter(db->mutex);\n  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA\n         && cnt++ < SQLITE_MAX_SCHEMA_RETRY\n         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){\n    sqlite3_reset(pStmt);\n    assert( v->expired==0 );\n  }\n  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){\n    /* This case occurs after failing to recompile an sql statement. \n    ** The error message from the SQL compiler has already been loaded \n    ** into the database handle. This block copies the error message \n    ** from the database handle into the statement and sets the statement\n    ** program counter to 0 to ensure that when the statement is \n    ** finalized or reset the parser error message is available via\n    ** sqlite3_errmsg() and sqlite3_errcode().\n    */\n    const char *zErr = (const char *)sqlite3_value_text(db->pErr); \n    sqlite3DbFree(db, v->zErrMsg);\n    if( !db->mallocFailed ){\n      v->zErrMsg = sqlite3DbStrDup(db, zErr);\n      v->rc = rc2;\n    } else {\n      v->zErrMsg = 0;\n      v->rc = rc = SQLITE_NOMEM;\n    }\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Extract the user data from a sqlite3_context structure and return a\n** pointer to it.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context *p){\n  assert( p && p->pFunc );\n  return p->pFunc->pUserData;\n}\n\n/*\n** Extract the user data from a sqlite3_context structure and return a\n** pointer to it.\n**\n** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface\n** returns a copy of the pointer to the database connection (the 1st\n** parameter) of the sqlite3_create_function() and\n** sqlite3_create_function16() routines that originally registered the\n** application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){\n  assert( p && p->pFunc );\n  return p->s.db;\n}\n\n/*\n** The following is the implementation of an SQL function that always\n** fails with an error message stating that the function is used in the\n** wrong context.  The sqlite3_overload_function() API might construct\n** SQL function that use this routine so that the functions will exist\n** for name resolution but are actually overloaded by the xFindFunction\n** method of virtual tables.\n*/\nSQLITE_PRIVATE void sqlite3InvalidFunction(\n  sqlite3_context *context,  /* The function calling context */\n  int NotUsed,               /* Number of arguments to the function */\n  sqlite3_value **NotUsed2   /* Value of each argument */\n){\n  const char *zName = context->pFunc->zName;\n  char *zErr;\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  zErr = sqlite3_mprintf(\n      \"unable to use function %s in the requested context\", zName);\n  sqlite3_result_error(context, zErr, -1);\n  sqlite3_free(zErr);\n}\n\n/*\n** Allocate or return the aggregate context for a user function.  A new\n** context is allocated on the first call.  Subsequent calls return the\n** same context that was returned on prior calls.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){\n  Mem *pMem;\n  assert( p && p->pFunc && p->pFunc->xStep );\n  assert( sqlite3_mutex_held(p->s.db->mutex) );\n  pMem = p->pMem;\n  testcase( nByte<0 );\n  if( (pMem->flags & MEM_Agg)==0 ){\n    if( nByte<=0 ){\n      sqlite3VdbeMemReleaseExternal(pMem);\n      pMem->flags = MEM_Null;\n      pMem->z = 0;\n    }else{\n      sqlite3VdbeMemGrow(pMem, nByte, 0);\n      pMem->flags = MEM_Agg;\n      pMem->u.pDef = p->pFunc;\n      if( pMem->z ){\n        memset(pMem->z, 0, nByte);\n      }\n    }\n  }\n  return (void*)pMem->z;\n}\n\n/*\n** Return the auxilary data pointer, if any, for the iArg'th argument to\n** the user-function defined by pCtx.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){\n  VdbeFunc *pVdbeFunc;\n\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  pVdbeFunc = pCtx->pVdbeFunc;\n  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){\n    return 0;\n  }\n  return pVdbeFunc->apAux[iArg].pAux;\n}\n\n/*\n** Set the auxilary data pointer and delete function, for the iArg'th\n** argument to the user-function defined by pCtx. Any previous value is\n** deleted by calling the delete function specified when it was set.\n*/\nSQLITE_API void sqlite3_set_auxdata(\n  sqlite3_context *pCtx, \n  int iArg, \n  void *pAux, \n  void (*xDelete)(void*)\n){\n  struct AuxData *pAuxData;\n  VdbeFunc *pVdbeFunc;\n  if( iArg<0 ) goto failed;\n\n  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );\n  pVdbeFunc = pCtx->pVdbeFunc;\n  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){\n    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);\n    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;\n    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);\n    if( !pVdbeFunc ){\n      goto failed;\n    }\n    pCtx->pVdbeFunc = pVdbeFunc;\n    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));\n    pVdbeFunc->nAux = iArg+1;\n    pVdbeFunc->pFunc = pCtx->pFunc;\n  }\n\n  pAuxData = &pVdbeFunc->apAux[iArg];\n  if( pAuxData->pAux && pAuxData->xDelete ){\n    pAuxData->xDelete(pAuxData->pAux);\n  }\n  pAuxData->pAux = pAux;\n  pAuxData->xDelete = xDelete;\n  return;\n\nfailed:\n  if( xDelete ){\n    xDelete(pAux);\n  }\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Return the number of times the Step function of a aggregate has been \n** called.\n**\n** This function is deprecated.  Do not use it for new code.  It is\n** provide only to avoid breaking legacy code.  New aggregate function\n** implementations should keep their own counts within their aggregate\n** context.\n*/\nSQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){\n  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );\n  return p->pMem->n;\n}\n#endif\n\n/*\n** Return the number of columns in the result set for the statement pStmt.\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){\n  Vdbe *pVm = (Vdbe *)pStmt;\n  return pVm ? pVm->nResColumn : 0;\n}\n\n/*\n** Return the number of values available from the current row of the\n** currently executing statement pStmt.\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){\n  Vdbe *pVm = (Vdbe *)pStmt;\n  if( pVm==0 || pVm->pResultSet==0 ) return 0;\n  return pVm->nResColumn;\n}\n\n\n/*\n** Check to see if column iCol of the given statement is valid.  If\n** it is, return a pointer to the Mem for the value of that column.\n** If iCol is not valid, return a pointer to a Mem which has a value\n** of NULL.\n*/\nstatic Mem *columnMem(sqlite3_stmt *pStmt, int i){\n  Vdbe *pVm;\n  Mem *pOut;\n\n  pVm = (Vdbe *)pStmt;\n  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){\n    sqlite3_mutex_enter(pVm->db->mutex);\n    pOut = &pVm->pResultSet[i];\n  }else{\n    /* If the value passed as the second argument is out of range, return\n    ** a pointer to the following static Mem object which contains the\n    ** value SQL NULL. Even though the Mem structure contains an element\n    ** of type i64, on certain architectures (x86) with certain compiler\n    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary\n    ** instead of an 8-byte one. This all works fine, except that when\n    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s\n    ** that a Mem structure is located on an 8-byte boundary. To prevent\n    ** these assert()s from failing, when building with SQLITE_DEBUG defined\n    ** using gcc, we force nullMem to be 8-byte aligned using the magical\n    ** __attribute__((aligned(8))) macro.  */\n    static const Mem nullMem \n#if defined(SQLITE_DEBUG) && defined(__GNUC__)\n      __attribute__((aligned(8))) \n#endif\n      = {0, \"\", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,\n#ifdef SQLITE_DEBUG\n         0, 0,  /* pScopyFrom, pFiller */\n#endif\n         0, 0 };\n\n    if( pVm && ALWAYS(pVm->db) ){\n      sqlite3_mutex_enter(pVm->db->mutex);\n      sqlite3Error(pVm->db, SQLITE_RANGE, 0);\n    }\n    pOut = (Mem*)&nullMem;\n  }\n  return pOut;\n}\n\n/*\n** This function is called after invoking an sqlite3_value_XXX function on a \n** column value (i.e. a value returned by evaluating an SQL expression in the\n** select list of a SELECT statement) that may cause a malloc() failure. If \n** malloc() has failed, the threads mallocFailed flag is cleared and the result\n** code of statement pStmt set to SQLITE_NOMEM.\n**\n** Specifically, this is called from within:\n**\n**     sqlite3_column_int()\n**     sqlite3_column_int64()\n**     sqlite3_column_text()\n**     sqlite3_column_text16()\n**     sqlite3_column_real()\n**     sqlite3_column_bytes()\n**     sqlite3_column_bytes16()\n**     sqiite3_column_blob()\n*/\nstatic void columnMallocFailure(sqlite3_stmt *pStmt)\n{\n  /* If malloc() failed during an encoding conversion within an\n  ** sqlite3_column_XXX API, then set the return code of the statement to\n  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR\n  ** and _finalize() will return NOMEM.\n  */\n  Vdbe *p = (Vdbe *)pStmt;\n  if( p ){\n    p->rc = sqlite3ApiExit(p->db, p->rc);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n}\n\n/**************************** sqlite3_column_  *******************************\n** The following routines are used to access elements of the current row\n** in the result set.\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){\n  const void *val;\n  val = sqlite3_value_blob( columnMem(pStmt,i) );\n  /* Even though there is no encoding conversion, value_blob() might\n  ** need to call malloc() to expand the result of a zeroblob() \n  ** expression. \n  */\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_bytes( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){\n  double val = sqlite3_value_double( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){\n  int val = sqlite3_value_int( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){\n  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){\n  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){\n  Mem *pOut = columnMem(pStmt, i);\n  if( pOut->flags&MEM_Static ){\n    pOut->flags &= ~MEM_Static;\n    pOut->flags |= MEM_Ephem;\n  }\n  columnMallocFailure(pStmt);\n  return (sqlite3_value *)pOut;\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){\n  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return val;\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){\n  int iType = sqlite3_value_type( columnMem(pStmt,i) );\n  columnMallocFailure(pStmt);\n  return iType;\n}\n\n/* The following function is experimental and subject to change or\n** removal */\n/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){\n**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );\n**}\n*/\n\n/*\n** Convert the N-th element of pStmt->pColName[] into a string using\n** xFunc() then return that string.  If N is out of range, return 0.\n**\n** There are up to 5 names for each column.  useType determines which\n** name is returned.  Here are the names:\n**\n**    0      The column name as it should be displayed for output\n**    1      The datatype name for the column\n**    2      The name of the database that the column derives from\n**    3      The name of the table that the column derives from\n**    4      The name of the table column that the result column derives from\n**\n** If the result is not a simple column reference (if it is an expression\n** or a constant) then useTypes 2, 3, and 4 return NULL.\n*/\nstatic const void *columnName(\n  sqlite3_stmt *pStmt,\n  int N,\n  const void *(*xFunc)(Mem*),\n  int useType\n){\n  const void *ret = 0;\n  Vdbe *p = (Vdbe *)pStmt;\n  int n;\n  sqlite3 *db = p->db;\n  \n  assert( db!=0 );\n  n = sqlite3_column_count(pStmt);\n  if( N<n && N>=0 ){\n    N += useType*n;\n    sqlite3_mutex_enter(db->mutex);\n    assert( db->mallocFailed==0 );\n    ret = xFunc(&p->aColName[N]);\n     /* A malloc may have failed inside of the xFunc() call. If this\n    ** is the case, clear the mallocFailed flag and return NULL.\n    */\n    if( db->mallocFailed ){\n      db->mallocFailed = 0;\n      ret = 0;\n    }\n    sqlite3_mutex_leave(db->mutex);\n  }\n  return ret;\n}\n\n/*\n** Return the name of the Nth column of the result set returned by SQL\n** statement pStmt.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);\n}\n#endif\n\n/*\n** Constraint:  If you have ENABLE_COLUMN_METADATA then you must\n** not define OMIT_DECLTYPE.\n*/\n#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)\n# error \"Must not define both SQLITE_OMIT_DECLTYPE \\\n         and SQLITE_ENABLE_COLUMN_METADATA\"\n#endif\n\n#ifndef SQLITE_OMIT_DECLTYPE\n/*\n** Return the column declaration type (if applicable) of the 'i'th column\n** of the result set of SQL statement pStmt.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_OMIT_DECLTYPE */\n\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n/*\n** Return the name of the database from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unabiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the name of the table from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unabiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the name of the table column from which a result column derives.\n** NULL is returned if the result column is an expression or constant or\n** anything else which is not an unabiguous reference to a database column.\n*/\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){\n  return columnName(\n      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_ENABLE_COLUMN_METADATA */\n\n\n/******************************* sqlite3_bind_  ***************************\n** \n** Routines used to attach values to wildcards in a compiled SQL statement.\n*/\n/*\n** Unbind the value bound to variable i in virtual machine p. This is the \n** the same as binding a NULL value to the column. If the \"i\" parameter is\n** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.\n**\n** A successful evaluation of this routine acquires the mutex on p.\n** the mutex is released if any kind of error occurs.\n**\n** The error code stored in database p->db is overwritten with the return\n** value in any case.\n*/\nstatic int vdbeUnbind(Vdbe *p, int i){\n  Mem *pVar;\n  if( vdbeSafetyNotNull(p) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(p->db->mutex);\n  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){\n    sqlite3Error(p->db, SQLITE_MISUSE, 0);\n    sqlite3_mutex_leave(p->db->mutex);\n    sqlite3_log(SQLITE_MISUSE, \n        \"bind on a busy prepared statement: [%s]\", p->zSql);\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( i<1 || i>p->nVar ){\n    sqlite3Error(p->db, SQLITE_RANGE, 0);\n    sqlite3_mutex_leave(p->db->mutex);\n    return SQLITE_RANGE;\n  }\n  i--;\n  pVar = &p->aVar[i];\n  sqlite3VdbeMemRelease(pVar);\n  pVar->flags = MEM_Null;\n  sqlite3Error(p->db, SQLITE_OK, 0);\n\n  /* If the bit corresponding to this variable in Vdbe.expmask is set, then \n  ** binding a new value to this variable invalidates the current query plan.\n  **\n  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host\n  ** parameter in the WHERE clause might influence the choice of query plan\n  ** for a statement, then the statement will be automatically recompiled,\n  ** as if there had been a schema change, on the first sqlite3_step() call\n  ** following any change to the bindings of that parameter.\n  */\n  if( p->isPrepareV2 &&\n     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)\n  ){\n    p->expired = 1;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Bind a text or BLOB value.\n*/\nstatic int bindText(\n  sqlite3_stmt *pStmt,   /* The statement to bind against */\n  int i,                 /* Index of the parameter to bind */\n  const void *zData,     /* Pointer to the data to be bound */\n  int nData,             /* Number of bytes of data to be bound */\n  void (*xDel)(void*),   /* Destructor for the data */\n  u8 encoding            /* Encoding for the data */\n){\n  Vdbe *p = (Vdbe *)pStmt;\n  Mem *pVar;\n  int rc;\n\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    if( zData!=0 ){\n      pVar = &p->aVar[i-1];\n      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);\n      if( rc==SQLITE_OK && encoding!=0 ){\n        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));\n      }\n      sqlite3Error(p->db, rc, 0);\n      rc = sqlite3ApiExit(p->db, rc);\n    }\n    sqlite3_mutex_leave(p->db->mutex);\n  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){\n    xDel((void*)zData);\n  }\n  return rc;\n}\n\n\n/*\n** Bind a blob value to an SQL statement variable.\n*/\nSQLITE_API int sqlite3_bind_blob(\n  sqlite3_stmt *pStmt, \n  int i, \n  const void *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n  return bindText(pStmt, i, zData, nData, xDel, 0);\n}\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){\n  return sqlite3_bind_int64(p, i, (i64)iValue);\n}\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){\n  int rc;\n  Vdbe *p = (Vdbe*)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_text( \n  sqlite3_stmt *pStmt, \n  int i, \n  const char *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);\n}\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API int sqlite3_bind_text16(\n  sqlite3_stmt *pStmt, \n  int i, \n  const void *zData, \n  int nData, \n  void (*xDel)(void*)\n){\n  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);\n}\n#endif /* SQLITE_OMIT_UTF16 */\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){\n  int rc;\n  switch( pValue->type ){\n    case SQLITE_INTEGER: {\n      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);\n      break;\n    }\n    case SQLITE_FLOAT: {\n      rc = sqlite3_bind_double(pStmt, i, pValue->r);\n      break;\n    }\n    case SQLITE_BLOB: {\n      if( pValue->flags & MEM_Zero ){\n        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);\n      }else{\n        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);\n      }\n      break;\n    }\n    case SQLITE_TEXT: {\n      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,\n                              pValue->enc);\n      break;\n    }\n    default: {\n      rc = sqlite3_bind_null(pStmt, i);\n      break;\n    }\n  }\n  return rc;\n}\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){\n  int rc;\n  Vdbe *p = (Vdbe *)pStmt;\n  rc = vdbeUnbind(p, i);\n  if( rc==SQLITE_OK ){\n    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);\n    sqlite3_mutex_leave(p->db->mutex);\n  }\n  return rc;\n}\n\n/*\n** Return the number of wildcards that can be potentially bound to.\n** This routine is added to support DBD::SQLite.  \n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){\n  Vdbe *p = (Vdbe*)pStmt;\n  return p ? p->nVar : 0;\n}\n\n/*\n** Return the name of a wildcard parameter.  Return NULL if the index\n** is out of range or if the wildcard is unnamed.\n**\n** The result is always UTF-8.\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){\n  Vdbe *p = (Vdbe*)pStmt;\n  if( p==0 || i<1 || i>p->nzVar ){\n    return 0;\n  }\n  return p->azVar[i-1];\n}\n\n/*\n** Given a wildcard parameter name, return the index of the variable\n** with that name.  If there is no variable with the given name,\n** return 0.\n*/\nSQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){\n  int i;\n  if( p==0 ){\n    return 0;\n  }\n  if( zName ){\n    for(i=0; i<p->nzVar; i++){\n      const char *z = p->azVar[i];\n      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){\n        return i+1;\n      }\n    }\n  }\n  return 0;\n}\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){\n  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));\n}\n\n/*\n** Transfer all bindings from the first statement over to the second.\n*/\nSQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){\n  Vdbe *pFrom = (Vdbe*)pFromStmt;\n  Vdbe *pTo = (Vdbe*)pToStmt;\n  int i;\n  assert( pTo->db==pFrom->db );\n  assert( pTo->nVar==pFrom->nVar );\n  sqlite3_mutex_enter(pTo->db->mutex);\n  for(i=0; i<pFrom->nVar; i++){\n    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);\n  }\n  sqlite3_mutex_leave(pTo->db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** Deprecated external interface.  Internal/core SQLite code\n** should call sqlite3TransferBindings.\n**\n** Is is misuse to call this routine with statements from different\n** database connections.  But as this is a deprecated interface, we\n** will not bother to check for that condition.\n**\n** If the two statements contain a different number of bindings, then\n** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise\n** SQLITE_OK is returned.\n*/\nSQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){\n  Vdbe *pFrom = (Vdbe*)pFromStmt;\n  Vdbe *pTo = (Vdbe*)pToStmt;\n  if( pFrom->nVar!=pTo->nVar ){\n    return SQLITE_ERROR;\n  }\n  if( pTo->isPrepareV2 && pTo->expmask ){\n    pTo->expired = 1;\n  }\n  if( pFrom->isPrepareV2 && pFrom->expmask ){\n    pFrom->expired = 1;\n  }\n  return sqlite3TransferBindings(pFromStmt, pToStmt);\n}\n#endif\n\n/*\n** Return the sqlite3* database handle to which the prepared statement given\n** in the argument belongs.  This is the same database handle that was\n** the first argument to the sqlite3_prepare() that was used to create\n** the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){\n  return pStmt ? ((Vdbe*)pStmt)->db : 0;\n}\n\n/*\n** Return true if the prepared statement is guaranteed to not modify the\n** database.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){\n  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;\n}\n\n/*\n** Return true if the prepared statement is in need of being reset.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){\n  Vdbe *v = (Vdbe*)pStmt;\n  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;\n}\n\n/*\n** Return a pointer to the next prepared statement after pStmt associated\n** with database connection pDb.  If pStmt is NULL, return the first\n** prepared statement for the database connection.  Return NULL if there\n** are no more.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){\n  sqlite3_stmt *pNext;\n  sqlite3_mutex_enter(pDb->mutex);\n  if( pStmt==0 ){\n    pNext = (sqlite3_stmt*)pDb->pVdbe;\n  }else{\n    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;\n  }\n  sqlite3_mutex_leave(pDb->mutex);\n  return pNext;\n}\n\n/*\n** Return the value of a status counter for a prepared statement\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){\n  Vdbe *pVdbe = (Vdbe*)pStmt;\n  int v = pVdbe->aCounter[op-1];\n  if( resetFlag ) pVdbe->aCounter[op-1] = 0;\n  return v;\n}\n\n/************** End of vdbeapi.c *********************************************/\n/************** Begin file vdbetrace.c ***************************************/\n/*\n** 2009 November 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to insert the values of host parameters\n** (aka \"wildcards\") into the SQL text output by sqlite3_trace().\n**\n** The Vdbe parse-tree explainer is also found here.\n*/\n\n#ifndef SQLITE_OMIT_TRACE\n\n/*\n** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of\n** bytes in this text up to but excluding the first character in\n** a host parameter.  If the text contains no host parameters, return\n** the total number of bytes in the text.\n*/\nstatic int findNextHostParameter(const char *zSql, int *pnToken){\n  int tokenType;\n  int nTotal = 0;\n  int n;\n\n  *pnToken = 0;\n  while( zSql[0] ){\n    n = sqlite3GetToken((u8*)zSql, &tokenType);\n    assert( n>0 && tokenType!=TK_ILLEGAL );\n    if( tokenType==TK_VARIABLE ){\n      *pnToken = n;\n      break;\n    }\n    nTotal += n;\n    zSql += n;\n  }\n  return nTotal;\n}\n\n/*\n** This function returns a pointer to a nul-terminated string in memory\n** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the\n** string contains a copy of zRawSql but with host parameters expanded to \n** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, \n** then the returned string holds a copy of zRawSql with \"-- \" prepended\n** to each line of text.\n**\n** The calling function is responsible for making sure the memory returned\n** is eventually freed.\n**\n** ALGORITHM:  Scan the input string looking for host parameters in any of\n** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within\n** string literals, quoted identifier names, and comments.  For text forms,\n** the host parameter index is found by scanning the perpared\n** statement for the corresponding OP_Variable opcode.  Once the host\n** parameter index is known, locate the value in p->aVar[].  Then render\n** the value as a literal in place of the host parameter name.\n*/\nSQLITE_PRIVATE char *sqlite3VdbeExpandSql(\n  Vdbe *p,                 /* The prepared statement being evaluated */\n  const char *zRawSql      /* Raw text of the SQL statement */\n){\n  sqlite3 *db;             /* The database connection */\n  int idx = 0;             /* Index of a host parameter */\n  int nextIndex = 1;       /* Index of next ? host parameter */\n  int n;                   /* Length of a token prefix */\n  int nToken;              /* Length of the parameter token */\n  int i;                   /* Loop counter */\n  Mem *pVar;               /* Value of a host parameter */\n  StrAccum out;            /* Accumulate the output here */\n  char zBase[100];         /* Initial working space */\n\n  db = p->db;\n  sqlite3StrAccumInit(&out, zBase, sizeof(zBase), \n                      db->aLimit[SQLITE_LIMIT_LENGTH]);\n  out.db = db;\n  if( db->vdbeExecCnt>1 ){\n    while( *zRawSql ){\n      const char *zStart = zRawSql;\n      while( *(zRawSql++)!='\\n' && *zRawSql );\n      sqlite3StrAccumAppend(&out, \"-- \", 3);\n      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));\n    }\n  }else{\n    while( zRawSql[0] ){\n      n = findNextHostParameter(zRawSql, &nToken);\n      assert( n>0 );\n      sqlite3StrAccumAppend(&out, zRawSql, n);\n      zRawSql += n;\n      assert( zRawSql[0] || nToken==0 );\n      if( nToken==0 ) break;\n      if( zRawSql[0]=='?' ){\n        if( nToken>1 ){\n          assert( sqlite3Isdigit(zRawSql[1]) );\n          sqlite3GetInt32(&zRawSql[1], &idx);\n        }else{\n          idx = nextIndex;\n        }\n      }else{\n        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );\n        testcase( zRawSql[0]==':' );\n        testcase( zRawSql[0]=='$' );\n        testcase( zRawSql[0]=='@' );\n        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);\n        assert( idx>0 );\n      }\n      zRawSql += nToken;\n      nextIndex = idx + 1;\n      assert( idx>0 && idx<=p->nVar );\n      pVar = &p->aVar[idx-1];\n      if( pVar->flags & MEM_Null ){\n        sqlite3StrAccumAppend(&out, \"NULL\", 4);\n      }else if( pVar->flags & MEM_Int ){\n        sqlite3XPrintf(&out, \"%lld\", pVar->u.i);\n      }else if( pVar->flags & MEM_Real ){\n        sqlite3XPrintf(&out, \"%!.15g\", pVar->r);\n      }else if( pVar->flags & MEM_Str ){\n#ifndef SQLITE_OMIT_UTF16\n        u8 enc = ENC(db);\n        if( enc!=SQLITE_UTF8 ){\n          Mem utf8;\n          memset(&utf8, 0, sizeof(utf8));\n          utf8.db = db;\n          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);\n          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);\n          sqlite3XPrintf(&out, \"'%.*q'\", utf8.n, utf8.z);\n          sqlite3VdbeMemRelease(&utf8);\n        }else\n#endif\n        {\n          sqlite3XPrintf(&out, \"'%.*q'\", pVar->n, pVar->z);\n        }\n      }else if( pVar->flags & MEM_Zero ){\n        sqlite3XPrintf(&out, \"zeroblob(%d)\", pVar->u.nZero);\n      }else{\n        assert( pVar->flags & MEM_Blob );\n        sqlite3StrAccumAppend(&out, \"x'\", 2);\n        for(i=0; i<pVar->n; i++){\n          sqlite3XPrintf(&out, \"%02x\", pVar->z[i]&0xff);\n        }\n        sqlite3StrAccumAppend(&out, \"'\", 1);\n      }\n    }\n  }\n  return sqlite3StrAccumFinish(&out);\n}\n\n#endif /* #ifndef SQLITE_OMIT_TRACE */\n\n/*****************************************************************************\n** The following code implements the data-structure explaining logic\n** for the Vdbe.\n*/\n\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n\n/*\n** Allocate a new Explain object\n*/\nSQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){\n  if( pVdbe ){\n    Explain *p;\n    sqlite3BeginBenignMalloc();\n    p = (Explain *)sqlite3MallocZero( sizeof(Explain) );\n    if( p ){\n      p->pVdbe = pVdbe;\n      sqlite3_free(pVdbe->pExplain);\n      pVdbe->pExplain = p;\n      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),\n                          SQLITE_MAX_LENGTH);\n      p->str.useMalloc = 2;\n    }else{\n      sqlite3EndBenignMalloc();\n    }\n  }\n}\n\n/*\n** Return true if the Explain ends with a new-line.\n*/\nstatic int endsWithNL(Explain *p){\n  return p && p->str.zText && p->str.nChar\n           && p->str.zText[p->str.nChar-1]=='\\n';\n}\n    \n/*\n** Append text to the indentation\n*/\nSQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){\n  Explain *p;\n  if( pVdbe && (p = pVdbe->pExplain)!=0 ){\n    va_list ap;\n    if( p->nIndent && endsWithNL(p) ){\n      int n = p->nIndent;\n      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);\n      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);\n    }   \n    va_start(ap, zFormat);\n    sqlite3VXPrintf(&p->str, 1, zFormat, ap);\n    va_end(ap);\n  }\n}\n\n/*\n** Append a '\\n' if there is not already one.\n*/\nSQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){\n  Explain *p;\n  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){\n    sqlite3StrAccumAppend(&p->str, \"\\n\", 1);\n  }\n}\n\n/*\n** Push a new indentation level.  Subsequent lines will be indented\n** so that they begin at the current cursor position.\n*/\nSQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){\n  Explain *p;\n  if( pVdbe && (p = pVdbe->pExplain)!=0 ){\n    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){\n      const char *z = p->str.zText;\n      int i = p->str.nChar-1;\n      int x;\n      while( i>=0 && z[i]!='\\n' ){ i--; }\n      x = (p->str.nChar - 1) - i;\n      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){\n        x = p->aIndent[p->nIndent-1];\n      }\n      p->aIndent[p->nIndent] = x;\n    }\n    p->nIndent++;\n  }\n}\n\n/*\n** Pop the indentation stack by one level.\n*/\nSQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){\n  if( p && p->pExplain ) p->pExplain->nIndent--;\n}\n\n/*\n** Free the indentation structure\n*/\nSQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){\n  if( pVdbe && pVdbe->pExplain ){\n    sqlite3_free(pVdbe->zExplain);\n    sqlite3ExplainNL(pVdbe);\n    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);\n    sqlite3_free(pVdbe->pExplain);\n    pVdbe->pExplain = 0;\n    sqlite3EndBenignMalloc();\n  }\n}\n\n/*\n** Return the explanation of a virtual machine.\n*/\nSQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){\n  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;\n}\n#endif /* defined(SQLITE_DEBUG) */\n\n/************** End of vdbetrace.c *******************************************/\n/************** Begin file vdbe.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** The code in this file implements execution method of the \n** Virtual Database Engine (VDBE).  A separate file (\"vdbeaux.c\")\n** handles housekeeping details such as creating and deleting\n** VDBE instances.  This file is solely interested in executing\n** the VDBE program.\n**\n** In the external interface, an \"sqlite3_stmt*\" is an opaque pointer\n** to a VDBE.\n**\n** The SQL parser generates a program which is then executed by\n** the VDBE to do the work of the SQL statement.  VDBE programs are \n** similar in form to assembly language.  The program consists of\n** a linear sequence of operations.  Each operation has an opcode \n** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 \n** is a null-terminated string.  Operand P5 is an unsigned character.\n** Few opcodes use all 5 operands.\n**\n** Computation results are stored on a set of registers numbered beginning\n** with 1 and going up to Vdbe.nMem.  Each register can store\n** either an integer, a null-terminated string, a floating point\n** number, or the SQL \"NULL\" value.  An implicit conversion from one\n** type to the other occurs as necessary.\n** \n** Most of the code in this file is taken up by the sqlite3VdbeExec()\n** function which does the work of interpreting a VDBE program.\n** But other routines are also provided to help in building up\n** a program instruction by instruction.\n**\n** Various scripts scan this source file in order to generate HTML\n** documentation, headers files, or other derived files.  The formatting\n** of the code in this file is, therefore, important.  See other comments\n** in this file for details.  If in doubt, do not deviate from existing\n** commenting and indentation practices when changing or adding code.\n*/\n\n/*\n** Invoke this macro on memory cells just prior to changing the\n** value of the cell.  This macro verifies that shallow copies are\n** not misused.\n*/\n#ifdef SQLITE_DEBUG\n# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)\n#else\n# define memAboutToChange(P,M)\n#endif\n\n/*\n** The following global variable is incremented every time a cursor\n** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test\n** procedures use this information to make sure that indices are\n** working correctly.  This variable has no function other than to\n** help verify the correct operation of the library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_search_count = 0;\n#endif\n\n/*\n** When this global variable is positive, it gets decremented once before\n** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted\n** field of the sqlite3 structure is set in order to simulate an interrupt.\n**\n** This facility is used for testing purposes only.  It does not function\n** in an ordinary build.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_interrupt_count = 0;\n#endif\n\n/*\n** The next global variable is incremented each type the OP_Sort opcode\n** is executed.  The test procedures use this information to make sure that\n** sorting is occurring or not occurring at appropriate times.   This variable\n** has no function other than to help verify the correct operation of the\n** library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_sort_count = 0;\n#endif\n\n/*\n** The next global variable records the size of the largest MEM_Blob\n** or MEM_Str that has been used by a VDBE opcode.  The test procedures\n** use this information to make sure that the zero-blob functionality\n** is working correctly.   This variable has no function other than to\n** help verify the correct operation of the library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_max_blobsize = 0;\nstatic void updateMaxBlobsize(Mem *p){\n  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){\n    sqlite3_max_blobsize = p->n;\n  }\n}\n#endif\n\n/*\n** The next global variable is incremented each type the OP_Found opcode\n** is executed. This is used to test whether or not the foreign key\n** operation implemented using OP_FkIsZero is working. This variable\n** has no function other than to help verify the correct operation of the\n** library.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_found_count = 0;\n#endif\n\n/*\n** Test a register to see if it exceeds the current maximum blob size.\n** If it does, record the new maximum blob size.\n*/\n#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)\n# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)\n#else\n# define UPDATE_MAX_BLOBSIZE(P)\n#endif\n\n/*\n** Convert the given register into a string if it isn't one\n** already. Return non-zero if a malloc() fails.\n*/\n#define Stringify(P, enc) \\\n   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \\\n     { goto no_mem; }\n\n/*\n** An ephemeral string value (signified by the MEM_Ephem flag) contains\n** a pointer to a dynamically allocated string where some other entity\n** is responsible for deallocating that string.  Because the register\n** does not control the string, it might be deleted without the register\n** knowing it.\n**\n** This routine converts an ephemeral string into a dynamically allocated\n** string that the register itself controls.  In other words, it\n** converts an MEM_Ephem string into an MEM_Dyn string.\n*/\n#define Deephemeralize(P) \\\n   if( ((P)->flags&MEM_Ephem)!=0 \\\n       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}\n\n/* Return true if the cursor was opened using the OP_OpenSorter opcode. */\n#ifdef SQLITE_OMIT_MERGE_SORT\n# define isSorter(x) 0\n#else\n# define isSorter(x) ((x)->pSorter!=0)\n#endif\n\n/*\n** Argument pMem points at a register that will be passed to a\n** user-defined function or returned to the user as the result of a query.\n** This routine sets the pMem->type variable used by the sqlite3_value_*() \n** routines.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){\n  int flags = pMem->flags;\n  if( flags & MEM_Null ){\n    pMem->type = SQLITE_NULL;\n  }\n  else if( flags & MEM_Int ){\n    pMem->type = SQLITE_INTEGER;\n  }\n  else if( flags & MEM_Real ){\n    pMem->type = SQLITE_FLOAT;\n  }\n  else if( flags & MEM_Str ){\n    pMem->type = SQLITE_TEXT;\n  }else{\n    pMem->type = SQLITE_BLOB;\n  }\n}\n\n/*\n** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL\n** if we run out of memory.\n*/\nstatic VdbeCursor *allocateCursor(\n  Vdbe *p,              /* The virtual machine */\n  int iCur,             /* Index of the new VdbeCursor */\n  int nField,           /* Number of fields in the table or index */\n  int iDb,              /* Database the cursor belongs to, or -1 */\n  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */\n){\n  /* Find the memory cell that will be used to store the blob of memory\n  ** required for this VdbeCursor structure. It is convenient to use a \n  ** vdbe memory cell to manage the memory allocation required for a\n  ** VdbeCursor structure for the following reasons:\n  **\n  **   * Sometimes cursor numbers are used for a couple of different\n  **     purposes in a vdbe program. The different uses might require\n  **     different sized allocations. Memory cells provide growable\n  **     allocations.\n  **\n  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can\n  **     be freed lazily via the sqlite3_release_memory() API. This\n  **     minimizes the number of malloc calls made by the system.\n  **\n  ** Memory cells for cursors are allocated at the top of the address\n  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for\n  ** cursor 1 is managed by memory cell (p->nMem-1), etc.\n  */\n  Mem *pMem = &p->aMem[p->nMem-iCur];\n\n  int nByte;\n  VdbeCursor *pCx = 0;\n  nByte = \n      ROUND8(sizeof(VdbeCursor)) + \n      (isBtreeCursor?sqlite3BtreeCursorSize():0) + \n      2*nField*sizeof(u32);\n\n  assert( iCur<p->nCursor );\n  if( p->apCsr[iCur] ){\n    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);\n    p->apCsr[iCur] = 0;\n  }\n  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){\n    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;\n    memset(pCx, 0, sizeof(VdbeCursor));\n    pCx->iDb = iDb;\n    pCx->nField = nField;\n    if( nField ){\n      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];\n    }\n    if( isBtreeCursor ){\n      pCx->pCursor = (BtCursor*)\n          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];\n      sqlite3BtreeCursorZero(pCx->pCursor);\n    }\n  }\n  return pCx;\n}\n\n/*\n** Try to convert a value into a numeric representation if we can\n** do so without loss of information.  In other words, if the string\n** looks like a number, convert it into a number.  If it does not\n** look like a number, leave it alone.\n*/\nstatic void applyNumericAffinity(Mem *pRec){\n  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){\n    double rValue;\n    i64 iValue;\n    u8 enc = pRec->enc;\n    if( (pRec->flags&MEM_Str)==0 ) return;\n    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;\n    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){\n      pRec->u.i = iValue;\n      pRec->flags |= MEM_Int;\n    }else{\n      pRec->r = rValue;\n      pRec->flags |= MEM_Real;\n    }\n  }\n}\n\n/*\n** Processing is determine by the affinity parameter:\n**\n** SQLITE_AFF_INTEGER:\n** SQLITE_AFF_REAL:\n** SQLITE_AFF_NUMERIC:\n**    Try to convert pRec to an integer representation or a \n**    floating-point representation if an integer representation\n**    is not possible.  Note that the integer representation is\n**    always preferred, even if the affinity is REAL, because\n**    an integer representation is more space efficient on disk.\n**\n** SQLITE_AFF_TEXT:\n**    Convert pRec to a text representation.\n**\n** SQLITE_AFF_NONE:\n**    No-op.  pRec is unchanged.\n*/\nstatic void applyAffinity(\n  Mem *pRec,          /* The value to apply affinity to */\n  char affinity,      /* The affinity to be applied */\n  u8 enc              /* Use this text encoding */\n){\n  if( affinity==SQLITE_AFF_TEXT ){\n    /* Only attempt the conversion to TEXT if there is an integer or real\n    ** representation (blob and NULL do not get converted) but no string\n    ** representation.\n    */\n    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){\n      sqlite3VdbeMemStringify(pRec, enc);\n    }\n    pRec->flags &= ~(MEM_Real|MEM_Int);\n  }else if( affinity!=SQLITE_AFF_NONE ){\n    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL\n             || affinity==SQLITE_AFF_NUMERIC );\n    applyNumericAffinity(pRec);\n    if( pRec->flags & MEM_Real ){\n      sqlite3VdbeIntegerAffinity(pRec);\n    }\n  }\n}\n\n/*\n** Try to convert the type of a function argument or a result column\n** into a numeric representation.  Use either INTEGER or REAL whichever\n** is appropriate.  But only do the conversion if it is possible without\n** loss of information and return the revised type of the argument.\n*/\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){\n  Mem *pMem = (Mem*)pVal;\n  if( pMem->type==SQLITE_TEXT ){\n    applyNumericAffinity(pMem);\n    sqlite3VdbeMemStoreType(pMem);\n  }\n  return pMem->type;\n}\n\n/*\n** Exported version of applyAffinity(). This one works on sqlite3_value*, \n** not the internal Mem* type.\n*/\nSQLITE_PRIVATE void sqlite3ValueApplyAffinity(\n  sqlite3_value *pVal, \n  u8 affinity, \n  u8 enc\n){\n  applyAffinity((Mem *)pVal, affinity, enc);\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** Write a nice string representation of the contents of cell pMem\n** into buffer zBuf, length nBuf.\n*/\nSQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){\n  char *zCsr = zBuf;\n  int f = pMem->flags;\n\n  static const char *const encnames[] = {\"(X)\", \"(8)\", \"(16LE)\", \"(16BE)\"};\n\n  if( f&MEM_Blob ){\n    int i;\n    char c;\n    if( f & MEM_Dyn ){\n      c = 'z';\n      assert( (f & (MEM_Static|MEM_Ephem))==0 );\n    }else if( f & MEM_Static ){\n      c = 't';\n      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );\n    }else if( f & MEM_Ephem ){\n      c = 'e';\n      assert( (f & (MEM_Static|MEM_Dyn))==0 );\n    }else{\n      c = 's';\n    }\n\n    sqlite3_snprintf(100, zCsr, \"%c\", c);\n    zCsr += sqlite3Strlen30(zCsr);\n    sqlite3_snprintf(100, zCsr, \"%d[\", pMem->n);\n    zCsr += sqlite3Strlen30(zCsr);\n    for(i=0; i<16 && i<pMem->n; i++){\n      sqlite3_snprintf(100, zCsr, \"%02X\", ((int)pMem->z[i] & 0xFF));\n      zCsr += sqlite3Strlen30(zCsr);\n    }\n    for(i=0; i<16 && i<pMem->n; i++){\n      char z = pMem->z[i];\n      if( z<32 || z>126 ) *zCsr++ = '.';\n      else *zCsr++ = z;\n    }\n\n    sqlite3_snprintf(100, zCsr, \"]%s\", encnames[pMem->enc]);\n    zCsr += sqlite3Strlen30(zCsr);\n    if( f & MEM_Zero ){\n      sqlite3_snprintf(100, zCsr,\"+%dz\",pMem->u.nZero);\n      zCsr += sqlite3Strlen30(zCsr);\n    }\n    *zCsr = '\\0';\n  }else if( f & MEM_Str ){\n    int j, k;\n    zBuf[0] = ' ';\n    if( f & MEM_Dyn ){\n      zBuf[1] = 'z';\n      assert( (f & (MEM_Static|MEM_Ephem))==0 );\n    }else if( f & MEM_Static ){\n      zBuf[1] = 't';\n      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );\n    }else if( f & MEM_Ephem ){\n      zBuf[1] = 'e';\n      assert( (f & (MEM_Static|MEM_Dyn))==0 );\n    }else{\n      zBuf[1] = 's';\n    }\n    k = 2;\n    sqlite3_snprintf(100, &zBuf[k], \"%d\", pMem->n);\n    k += sqlite3Strlen30(&zBuf[k]);\n    zBuf[k++] = '[';\n    for(j=0; j<15 && j<pMem->n; j++){\n      u8 c = pMem->z[j];\n      if( c>=0x20 && c<0x7f ){\n        zBuf[k++] = c;\n      }else{\n        zBuf[k++] = '.';\n      }\n    }\n    zBuf[k++] = ']';\n    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);\n    k += sqlite3Strlen30(&zBuf[k]);\n    zBuf[k++] = 0;\n  }\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n/*\n** Print the value of a register for tracing purposes:\n*/\nstatic void memTracePrint(FILE *out, Mem *p){\n  if( p->flags & MEM_Null ){\n    fprintf(out, \" NULL\");\n  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){\n    fprintf(out, \" si:%lld\", p->u.i);\n  }else if( p->flags & MEM_Int ){\n    fprintf(out, \" i:%lld\", p->u.i);\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  }else if( p->flags & MEM_Real ){\n    fprintf(out, \" r:%g\", p->r);\n#endif\n  }else if( p->flags & MEM_RowSet ){\n    fprintf(out, \" (rowset)\");\n  }else{\n    char zBuf[200];\n    sqlite3VdbeMemPrettyPrint(p, zBuf);\n    fprintf(out, \" \");\n    fprintf(out, \"%s\", zBuf);\n  }\n}\nstatic void registerTrace(FILE *out, int iReg, Mem *p){\n  fprintf(out, \"REG[%d] = \", iReg);\n  memTracePrint(out, p);\n  fprintf(out, \"\\n\");\n}\n#endif\n\n#ifdef SQLITE_DEBUG\n#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)\n#else\n#  define REGISTER_TRACE(R,M)\n#endif\n\n\n#ifdef VDBE_PROFILE\n\n/* \n** hwtime.h contains inline assembler code for implementing \n** high-performance timing routines.\n*/\n/************** Include hwtime.h in the middle of vdbe.c *********************/\n/************** Begin file hwtime.h ******************************************/\n/*\n** 2008 May 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file contains inline asm code for retrieving \"high-performance\"\n** counters for x86 class CPUs.\n*/\n#ifndef _HWTIME_H_\n#define _HWTIME_H_\n\n/*\n** The following routine only works on pentium-class (or newer) processors.\n** It uses the RDTSC opcode to read the cycle count value out of the\n** processor and returns that value.  This can be used for high-res\n** profiling.\n*/\n#if (defined(__GNUC__) || defined(_MSC_VER)) && \\\n      (defined(i386) || defined(__i386__) || defined(_M_IX86))\n\n  #if defined(__GNUC__)\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n     unsigned int lo, hi;\n     __asm__ __volatile__ (\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n     return (sqlite_uint64)hi << 32 | lo;\n  }\n\n  #elif defined(_MSC_VER)\n\n  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){\n     __asm {\n        rdtsc\n        ret       ; return value at EDX:EAX\n     }\n  }\n\n  #endif\n\n#elif (defined(__GNUC__) && defined(__x86_64__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long val;\n      __asm__ __volatile__ (\"rdtsc\" : \"=A\" (val));\n      return val;\n  }\n \n#elif (defined(__GNUC__) && defined(__ppc__))\n\n  __inline__ sqlite_uint64 sqlite3Hwtime(void){\n      unsigned long long retval;\n      unsigned long junk;\n      __asm__ __volatile__ (\"\\n\\\n          1:      mftbu   %1\\n\\\n                  mftb    %L0\\n\\\n                  mftbu   %0\\n\\\n                  cmpw    %0,%1\\n\\\n                  bne     1b\"\n                  : \"=r\" (retval), \"=r\" (junk));\n      return retval;\n  }\n\n#else\n\n  #error Need implementation of sqlite3Hwtime() for your platform.\n\n  /*\n  ** To compile without implementing sqlite3Hwtime() for your platform,\n  ** you can remove the above #error and use the following\n  ** stub function.  You will lose timing support for many\n  ** of the debugging and testing utilities, but it should at\n  ** least compile and run.\n  */\nSQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }\n\n#endif\n\n#endif /* !defined(_HWTIME_H_) */\n\n/************** End of hwtime.h **********************************************/\n/************** Continuing where we left off in vdbe.c ***********************/\n\n#endif\n\n/*\n** The CHECK_FOR_INTERRUPT macro defined here looks to see if the\n** sqlite3_interrupt() routine has been called.  If it has been, then\n** processing of the VDBE program is interrupted.\n**\n** This macro added to every instruction that does a jump in order to\n** implement a loop.  This test used to be on every single instruction,\n** but that meant we more testing than we needed.  By only testing the\n** flag on jump instructions, we get a (small) speed improvement.\n*/\n#define CHECK_FOR_INTERRUPT \\\n   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;\n\n\n#ifndef NDEBUG\n/*\n** This function is only called from within an assert() expression. It\n** checks that the sqlite3.nTransaction variable is correctly set to\n** the number of non-transaction savepoints currently in the \n** linked list starting at sqlite3.pSavepoint.\n** \n** Usage:\n**\n**     assert( checkSavepointCount(db) );\n*/\nstatic int checkSavepointCount(sqlite3 *db){\n  int n = 0;\n  Savepoint *p;\n  for(p=db->pSavepoint; p; p=p->pNext) n++;\n  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );\n  return 1;\n}\n#endif\n\n/*\n** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored\n** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored\n** in memory obtained from sqlite3DbMalloc).\n*/\nstatic void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){\n  sqlite3 *db = p->db;\n  sqlite3DbFree(db, p->zErrMsg);\n  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);\n  sqlite3_free(pVtab->zErrMsg);\n  pVtab->zErrMsg = 0;\n}\n\n\n/*\n** Execute as much of a VDBE program as we can then return.\n**\n** sqlite3VdbeMakeReady() must be called before this routine in order to\n** close the program with a final OP_Halt and to set up the callbacks\n** and the error message pointer.\n**\n** Whenever a row or result data is available, this routine will either\n** invoke the result callback (if there is one) or return with\n** SQLITE_ROW.\n**\n** If an attempt is made to open a locked database, then this routine\n** will either invoke the busy callback (if there is one) or it will\n** return SQLITE_BUSY.\n**\n** If an error occurs, an error message is written to memory obtained\n** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.\n** The error code is stored in p->rc and this routine returns SQLITE_ERROR.\n**\n** If the callback ever returns non-zero, then the program exits\n** immediately.  There will be no error message but the p->rc field is\n** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.\n**\n** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this\n** routine to return SQLITE_ERROR.\n**\n** Other fatal errors return SQLITE_ERROR.\n**\n** After this routine has finished, sqlite3VdbeFinalize() should be\n** used to clean up the mess that was left behind.\n*/\nSQLITE_PRIVATE int sqlite3VdbeExec(\n  Vdbe *p                    /* The VDBE */\n){\n  int pc=0;                  /* The program counter */\n  Op *aOp = p->aOp;          /* Copy of p->aOp */\n  Op *pOp;                   /* Current operation */\n  int rc = SQLITE_OK;        /* Value to return */\n  sqlite3 *db = p->db;       /* The database */\n  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */\n  u8 encoding = ENC(db);     /* The database encoding */\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  int checkProgress;         /* True if progress callbacks are enabled */\n  int nProgressOps = 0;      /* Opcodes executed since progress callback. */\n#endif\n  Mem *aMem = p->aMem;       /* Copy of p->aMem */\n  Mem *pIn1 = 0;             /* 1st input operand */\n  Mem *pIn2 = 0;             /* 2nd input operand */\n  Mem *pIn3 = 0;             /* 3rd input operand */\n  Mem *pOut = 0;             /* Output operand */\n  int iCompare = 0;          /* Result of last OP_Compare operation */\n  int *aPermute = 0;         /* Permutation of columns for OP_Compare */\n  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */\n#ifdef VDBE_PROFILE\n  u64 start;                 /* CPU clock count at start of opcode */\n  int origPc;                /* Program counter at start of opcode */\n#endif\n  /********************************************************************\n  ** Automatically generated code\n  **\n  ** The following union is automatically generated by the\n  ** vdbe-compress.tcl script.  The purpose of this union is to\n  ** reduce the amount of stack space required by this function.\n  ** See comments in the vdbe-compress.tcl script for details.\n  */\n  union vdbeExecUnion {\n    struct OP_Yield_stack_vars {\n      int pcDest;\n    } aa;\n    struct OP_Null_stack_vars {\n      int cnt;\n    } ab;\n    struct OP_Variable_stack_vars {\n      Mem *pVar;       /* Value being transferred */\n    } ac;\n    struct OP_Move_stack_vars {\n      char *zMalloc;   /* Holding variable for allocated memory */\n      int n;           /* Number of registers left to copy */\n      int p1;          /* Register to copy from */\n      int p2;          /* Register to copy to */\n    } ad;\n    struct OP_ResultRow_stack_vars {\n      Mem *pMem;\n      int i;\n    } ae;\n    struct OP_Concat_stack_vars {\n      i64 nByte;\n    } af;\n    struct OP_Remainder_stack_vars {\n      int flags;      /* Combined MEM_* flags from both inputs */\n      i64 iA;         /* Integer value of left operand */\n      i64 iB;         /* Integer value of right operand */\n      double rA;      /* Real value of left operand */\n      double rB;      /* Real value of right operand */\n    } ag;\n    struct OP_Function_stack_vars {\n      int i;\n      Mem *pArg;\n      sqlite3_context ctx;\n      sqlite3_value **apVal;\n      int n;\n    } ah;\n    struct OP_ShiftRight_stack_vars {\n      i64 iA;\n      u64 uA;\n      i64 iB;\n      u8 op;\n    } ai;\n    struct OP_Ge_stack_vars {\n      int res;            /* Result of the comparison of pIn1 against pIn3 */\n      char affinity;      /* Affinity to use for comparison */\n      u16 flags1;         /* Copy of initial value of pIn1->flags */\n      u16 flags3;         /* Copy of initial value of pIn3->flags */\n    } aj;\n    struct OP_Compare_stack_vars {\n      int n;\n      int i;\n      int p1;\n      int p2;\n      const KeyInfo *pKeyInfo;\n      int idx;\n      CollSeq *pColl;    /* Collating sequence to use on this term */\n      int bRev;          /* True for DESCENDING sort order */\n    } ak;\n    struct OP_Or_stack_vars {\n      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n    } al;\n    struct OP_IfNot_stack_vars {\n      int c;\n    } am;\n    struct OP_Column_stack_vars {\n      u32 payloadSize;   /* Number of bytes in the record */\n      i64 payloadSize64; /* Number of bytes in the record */\n      int p1;            /* P1 value of the opcode */\n      int p2;            /* column number to retrieve */\n      VdbeCursor *pC;    /* The VDBE cursor */\n      char *zRec;        /* Pointer to complete record-data */\n      BtCursor *pCrsr;   /* The BTree cursor */\n      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */\n      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */\n      int nField;        /* number of fields in the record */\n      int len;           /* The length of the serialized data for the column */\n      int i;             /* Loop counter */\n      char *zData;       /* Part of the record being decoded */\n      Mem *pDest;        /* Where to write the extracted value */\n      Mem sMem;          /* For storing the record being decoded */\n      u8 *zIdx;          /* Index into header */\n      u8 *zEndHdr;       /* Pointer to first byte after the header */\n      u32 offset;        /* Offset into the data */\n      u32 szField;       /* Number of bytes in the content of a field */\n      int szHdr;         /* Size of the header size field at start of record */\n      int avail;         /* Number of bytes of available data */\n      u32 t;             /* A type code from the record header */\n      Mem *pReg;         /* PseudoTable input register */\n    } an;\n    struct OP_Affinity_stack_vars {\n      const char *zAffinity;   /* The affinity to be applied */\n      char cAff;               /* A single character of affinity */\n    } ao;\n    struct OP_MakeRecord_stack_vars {\n      u8 *zNewRecord;        /* A buffer to hold the data for the new record */\n      Mem *pRec;             /* The new record */\n      u64 nData;             /* Number of bytes of data space */\n      int nHdr;              /* Number of bytes of header space */\n      i64 nByte;             /* Data space required for this record */\n      int nZero;             /* Number of zero bytes at the end of the record */\n      int nVarint;           /* Number of bytes in a varint */\n      u32 serial_type;       /* Type field */\n      Mem *pData0;           /* First field to be combined into the record */\n      Mem *pLast;            /* Last field of the record */\n      int nField;            /* Number of fields in the record */\n      char *zAffinity;       /* The affinity string for the record */\n      int file_format;       /* File format to use for encoding */\n      int i;                 /* Space used in zNewRecord[] */\n      int len;               /* Length of a field */\n    } ap;\n    struct OP_Count_stack_vars {\n      i64 nEntry;\n      BtCursor *pCrsr;\n    } aq;\n    struct OP_Savepoint_stack_vars {\n      int p1;                         /* Value of P1 operand */\n      char *zName;                    /* Name of savepoint */\n      int nName;\n      Savepoint *pNew;\n      Savepoint *pSavepoint;\n      Savepoint *pTmp;\n      int iSavepoint;\n      int ii;\n    } ar;\n    struct OP_AutoCommit_stack_vars {\n      int desiredAutoCommit;\n      int iRollback;\n      int turnOnAC;\n    } as;\n    struct OP_Transaction_stack_vars {\n      Btree *pBt;\n    } at;\n    struct OP_ReadCookie_stack_vars {\n      int iMeta;\n      int iDb;\n      int iCookie;\n    } au;\n    struct OP_SetCookie_stack_vars {\n      Db *pDb;\n    } av;\n    struct OP_VerifyCookie_stack_vars {\n      int iMeta;\n      int iGen;\n      Btree *pBt;\n    } aw;\n    struct OP_OpenWrite_stack_vars {\n      int nField;\n      KeyInfo *pKeyInfo;\n      int p2;\n      int iDb;\n      int wrFlag;\n      Btree *pX;\n      VdbeCursor *pCur;\n      Db *pDb;\n    } ax;\n    struct OP_OpenEphemeral_stack_vars {\n      VdbeCursor *pCx;\n    } ay;\n    struct OP_SorterOpen_stack_vars {\n      VdbeCursor *pCx;\n    } az;\n    struct OP_OpenPseudo_stack_vars {\n      VdbeCursor *pCx;\n    } ba;\n    struct OP_SeekGt_stack_vars {\n      int res;\n      int oc;\n      VdbeCursor *pC;\n      UnpackedRecord r;\n      int nField;\n      i64 iKey;      /* The rowid we are to seek to */\n    } bb;\n    struct OP_Seek_stack_vars {\n      VdbeCursor *pC;\n    } bc;\n    struct OP_Found_stack_vars {\n      int alreadyExists;\n      VdbeCursor *pC;\n      int res;\n      char *pFree;\n      UnpackedRecord *pIdxKey;\n      UnpackedRecord r;\n      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];\n    } bd;\n    struct OP_IsUnique_stack_vars {\n      u16 ii;\n      VdbeCursor *pCx;\n      BtCursor *pCrsr;\n      u16 nField;\n      Mem *aMx;\n      UnpackedRecord r;                  /* B-Tree index search key */\n      i64 R;                             /* Rowid stored in register P3 */\n    } be;\n    struct OP_NotExists_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      int res;\n      u64 iKey;\n    } bf;\n    struct OP_NewRowid_stack_vars {\n      i64 v;                 /* The new rowid */\n      VdbeCursor *pC;        /* Cursor of table to get the new rowid */\n      int res;               /* Result of an sqlite3BtreeLast() */\n      int cnt;               /* Counter to limit the number of searches */\n      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */\n      VdbeFrame *pFrame;     /* Root frame of VDBE */\n    } bg;\n    struct OP_InsertInt_stack_vars {\n      Mem *pData;       /* MEM cell holding data for the record to be inserted */\n      Mem *pKey;        /* MEM cell holding key  for the record */\n      i64 iKey;         /* The integer ROWID or key for the record to be inserted */\n      VdbeCursor *pC;   /* Cursor to table into which insert is written */\n      int nZero;        /* Number of zero-bytes to append */\n      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */\n      const char *zDb;  /* database name - used by the update hook */\n      const char *zTbl; /* Table name - used by the opdate hook */\n      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */\n    } bh;\n    struct OP_Delete_stack_vars {\n      i64 iKey;\n      VdbeCursor *pC;\n    } bi;\n    struct OP_SorterCompare_stack_vars {\n      VdbeCursor *pC;\n      int res;\n    } bj;\n    struct OP_SorterData_stack_vars {\n      VdbeCursor *pC;\n    } bk;\n    struct OP_RowData_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      u32 n;\n      i64 n64;\n    } bl;\n    struct OP_Rowid_stack_vars {\n      VdbeCursor *pC;\n      i64 v;\n      sqlite3_vtab *pVtab;\n      const sqlite3_module *pModule;\n    } bm;\n    struct OP_NullRow_stack_vars {\n      VdbeCursor *pC;\n    } bn;\n    struct OP_Last_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      int res;\n    } bo;\n    struct OP_Rewind_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      int res;\n    } bp;\n    struct OP_Next_stack_vars {\n      VdbeCursor *pC;\n      int res;\n    } bq;\n    struct OP_IdxInsert_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      int nKey;\n      const char *zKey;\n    } br;\n    struct OP_IdxDelete_stack_vars {\n      VdbeCursor *pC;\n      BtCursor *pCrsr;\n      int res;\n      UnpackedRecord r;\n    } bs;\n    struct OP_IdxRowid_stack_vars {\n      BtCursor *pCrsr;\n      VdbeCursor *pC;\n      i64 rowid;\n    } bt;\n    struct OP_IdxGE_stack_vars {\n      VdbeCursor *pC;\n      int res;\n      UnpackedRecord r;\n    } bu;\n    struct OP_Destroy_stack_vars {\n      int iMoved;\n      int iCnt;\n      Vdbe *pVdbe;\n      int iDb;\n    } bv;\n    struct OP_Clear_stack_vars {\n      int nChange;\n    } bw;\n    struct OP_CreateTable_stack_vars {\n      int pgno;\n      int flags;\n      Db *pDb;\n    } bx;\n    struct OP_ParseSchema_stack_vars {\n      int iDb;\n      const char *zMaster;\n      char *zSql;\n      InitData initData;\n    } by;\n    struct OP_IntegrityCk_stack_vars {\n      int nRoot;      /* Number of tables to check.  (Number of root pages.) */\n      int *aRoot;     /* Array of rootpage numbers for tables to be checked */\n      int j;          /* Loop counter */\n      int nErr;       /* Number of errors reported */\n      char *z;        /* Text of the error report */\n      Mem *pnErr;     /* Register keeping track of errors remaining */\n    } bz;\n    struct OP_RowSetRead_stack_vars {\n      i64 val;\n    } ca;\n    struct OP_RowSetTest_stack_vars {\n      int iSet;\n      int exists;\n    } cb;\n    struct OP_Program_stack_vars {\n      int nMem;               /* Number of memory registers for sub-program */\n      int nByte;              /* Bytes of runtime space required for sub-program */\n      Mem *pRt;               /* Register to allocate runtime space */\n      Mem *pMem;              /* Used to iterate through memory cells */\n      Mem *pEnd;              /* Last memory cell in new array */\n      VdbeFrame *pFrame;      /* New vdbe frame to execute in */\n      SubProgram *pProgram;   /* Sub-program to execute */\n      void *t;                /* Token identifying trigger */\n    } cc;\n    struct OP_Param_stack_vars {\n      VdbeFrame *pFrame;\n      Mem *pIn;\n    } cd;\n    struct OP_MemMax_stack_vars {\n      Mem *pIn1;\n      VdbeFrame *pFrame;\n    } ce;\n    struct OP_AggStep_stack_vars {\n      int n;\n      int i;\n      Mem *pMem;\n      Mem *pRec;\n      sqlite3_context ctx;\n      sqlite3_value **apVal;\n    } cf;\n    struct OP_AggFinal_stack_vars {\n      Mem *pMem;\n    } cg;\n    struct OP_Checkpoint_stack_vars {\n      int i;                          /* Loop counter */\n      int aRes[3];                    /* Results */\n      Mem *pMem;                      /* Write results here */\n    } ch;\n    struct OP_JournalMode_stack_vars {\n      Btree *pBt;                     /* Btree to change journal mode of */\n      Pager *pPager;                  /* Pager associated with pBt */\n      int eNew;                       /* New journal mode */\n      int eOld;                       /* The old journal mode */\n      const char *zFilename;          /* Name of database file for pPager */\n    } ci;\n    struct OP_IncrVacuum_stack_vars {\n      Btree *pBt;\n    } cj;\n    struct OP_VBegin_stack_vars {\n      VTable *pVTab;\n    } ck;\n    struct OP_VOpen_stack_vars {\n      VdbeCursor *pCur;\n      sqlite3_vtab_cursor *pVtabCursor;\n      sqlite3_vtab *pVtab;\n      sqlite3_module *pModule;\n    } cl;\n    struct OP_VFilter_stack_vars {\n      int nArg;\n      int iQuery;\n      const sqlite3_module *pModule;\n      Mem *pQuery;\n      Mem *pArgc;\n      sqlite3_vtab_cursor *pVtabCursor;\n      sqlite3_vtab *pVtab;\n      VdbeCursor *pCur;\n      int res;\n      int i;\n      Mem **apArg;\n    } cm;\n    struct OP_VColumn_stack_vars {\n      sqlite3_vtab *pVtab;\n      const sqlite3_module *pModule;\n      Mem *pDest;\n      sqlite3_context sContext;\n    } cn;\n    struct OP_VNext_stack_vars {\n      sqlite3_vtab *pVtab;\n      const sqlite3_module *pModule;\n      int res;\n      VdbeCursor *pCur;\n    } co;\n    struct OP_VRename_stack_vars {\n      sqlite3_vtab *pVtab;\n      Mem *pName;\n    } cp;\n    struct OP_VUpdate_stack_vars {\n      sqlite3_vtab *pVtab;\n      sqlite3_module *pModule;\n      int nArg;\n      int i;\n      sqlite_int64 rowid;\n      Mem **apArg;\n      Mem *pX;\n    } cq;\n    struct OP_Trace_stack_vars {\n      char *zTrace;\n      char *z;\n    } cr;\n  } u;\n  /* End automatically generated code\n  ********************************************************************/\n\n  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */\n  sqlite3VdbeEnter(p);\n  if( p->rc==SQLITE_NOMEM ){\n    /* This happens if a malloc() inside a call to sqlite3_column_text() or\n    ** sqlite3_column_text16() failed.  */\n    goto no_mem;\n  }\n  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );\n  p->rc = SQLITE_OK;\n  assert( p->explain==0 );\n  p->pResultSet = 0;\n  db->busyHandler.nBusy = 0;\n  CHECK_FOR_INTERRUPT;\n  sqlite3VdbeIOTraceSql(p);\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n  checkProgress = db->xProgress!=0;\n#endif\n#ifdef SQLITE_DEBUG\n  sqlite3BeginBenignMalloc();\n  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){\n    int i;\n    printf(\"VDBE Program Listing:\\n\");\n    sqlite3VdbePrintSql(p);\n    for(i=0; i<p->nOp; i++){\n      sqlite3VdbePrintOp(stdout, i, &aOp[i]);\n    }\n  }\n  sqlite3EndBenignMalloc();\n#endif\n  for(pc=p->pc; rc==SQLITE_OK; pc++){\n    assert( pc>=0 && pc<p->nOp );\n    if( db->mallocFailed ) goto no_mem;\n#ifdef VDBE_PROFILE\n    origPc = pc;\n    start = sqlite3Hwtime();\n#endif\n    pOp = &aOp[pc];\n\n    /* Only allow tracing if SQLITE_DEBUG is defined.\n    */\n#ifdef SQLITE_DEBUG\n    if( p->trace ){\n      if( pc==0 ){\n        printf(\"VDBE Execution Trace:\\n\");\n        sqlite3VdbePrintSql(p);\n      }\n      sqlite3VdbePrintOp(p->trace, pc, pOp);\n    }\n#endif\n      \n\n    /* Check to see if we need to simulate an interrupt.  This only happens\n    ** if we have a special test build.\n    */\n#ifdef SQLITE_TEST\n    if( sqlite3_interrupt_count>0 ){\n      sqlite3_interrupt_count--;\n      if( sqlite3_interrupt_count==0 ){\n        sqlite3_interrupt(db);\n      }\n    }\n#endif\n\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n    /* Call the progress callback if it is configured and the required number\n    ** of VDBE ops have been executed (either since this invocation of\n    ** sqlite3VdbeExec() or since last time the progress callback was called).\n    ** If the progress callback returns non-zero, exit the virtual machine with\n    ** a return code SQLITE_ABORT.\n    */\n    if( checkProgress ){\n      if( db->nProgressOps==nProgressOps ){\n        int prc;\n        prc = db->xProgress(db->pProgressArg);\n        if( prc!=0 ){\n          rc = SQLITE_INTERRUPT;\n          goto vdbe_error_halt;\n        }\n        nProgressOps = 0;\n      }\n      nProgressOps++;\n    }\n#endif\n\n    /* On any opcode with the \"out2-prerelease\" tag, free any\n    ** external allocations out of mem[p2] and set mem[p2] to be\n    ** an undefined integer.  Opcodes will either fill in the integer\n    ** value or convert mem[p2] to a different type.\n    */\n    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );\n    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){\n      assert( pOp->p2>0 );\n      assert( pOp->p2<=p->nMem );\n      pOut = &aMem[pOp->p2];\n      memAboutToChange(p, pOut);\n      VdbeMemRelease(pOut);\n      pOut->flags = MEM_Int;\n    }\n\n    /* Sanity checking on other operands */\n#ifdef SQLITE_DEBUG\n    if( (pOp->opflags & OPFLG_IN1)!=0 ){\n      assert( pOp->p1>0 );\n      assert( pOp->p1<=p->nMem );\n      assert( memIsValid(&aMem[pOp->p1]) );\n      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);\n    }\n    if( (pOp->opflags & OPFLG_IN2)!=0 ){\n      assert( pOp->p2>0 );\n      assert( pOp->p2<=p->nMem );\n      assert( memIsValid(&aMem[pOp->p2]) );\n      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);\n    }\n    if( (pOp->opflags & OPFLG_IN3)!=0 ){\n      assert( pOp->p3>0 );\n      assert( pOp->p3<=p->nMem );\n      assert( memIsValid(&aMem[pOp->p3]) );\n      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);\n    }\n    if( (pOp->opflags & OPFLG_OUT2)!=0 ){\n      assert( pOp->p2>0 );\n      assert( pOp->p2<=p->nMem );\n      memAboutToChange(p, &aMem[pOp->p2]);\n    }\n    if( (pOp->opflags & OPFLG_OUT3)!=0 ){\n      assert( pOp->p3>0 );\n      assert( pOp->p3<=p->nMem );\n      memAboutToChange(p, &aMem[pOp->p3]);\n    }\n#endif\n  \n    switch( pOp->opcode ){\n\n/*****************************************************************************\n** What follows is a massive switch statement where each case implements a\n** separate instruction in the virtual machine.  If we follow the usual\n** indentation conventions, each case should be indented by 6 spaces.  But\n** that is a lot of wasted space on the left margin.  So the code within\n** the switch statement will break with convention and be flush-left. Another\n** big comment (similar to this one) will mark the point in the code where\n** we transition back to normal indentation.\n**\n** The formatting of each case is important.  The makefile for SQLite\n** generates two C files \"opcodes.h\" and \"opcodes.c\" by scanning this\n** file looking for lines that begin with \"case OP_\".  The opcodes.h files\n** will be filled with #defines that give unique integer values to each\n** opcode and the opcodes.c file is filled with an array of strings where\n** each string is the symbolic name for the corresponding opcode.  If the\n** case statement is followed by a comment of the form \"/# same as ... #/\"\n** that comment is used to determine the particular value of the opcode.\n**\n** Other keywords in the comment that follows each case are used to\n** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].\n** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See\n** the mkopcodeh.awk script for additional information.\n**\n** Documentation about VDBE opcodes is generated by scanning this file\n** for lines of that contain \"Opcode:\".  That line and all subsequent\n** comment lines are used in the generation of the opcode.html documentation\n** file.\n**\n** SUMMARY:\n**\n**     Formatting is important to scripts that scan this file.\n**     Do not deviate from the formatting style currently in use.\n**\n*****************************************************************************/\n\n/* Opcode:  Goto * P2 * * *\n**\n** An unconditional jump to address P2.\n** The next instruction executed will be \n** the one at index P2 from the beginning of\n** the program.\n*/\ncase OP_Goto: {             /* jump */\n  CHECK_FOR_INTERRUPT;\n  pc = pOp->p2 - 1;\n  break;\n}\n\n/* Opcode:  Gosub P1 P2 * * *\n**\n** Write the current address onto register P1\n** and then jump to address P2.\n*/\ncase OP_Gosub: {            /* jump */\n  assert( pOp->p1>0 && pOp->p1<=p->nMem );\n  pIn1 = &aMem[pOp->p1];\n  assert( (pIn1->flags & MEM_Dyn)==0 );\n  memAboutToChange(p, pIn1);\n  pIn1->flags = MEM_Int;\n  pIn1->u.i = pc;\n  REGISTER_TRACE(pOp->p1, pIn1);\n  pc = pOp->p2 - 1;\n  break;\n}\n\n/* Opcode:  Return P1 * * * *\n**\n** Jump to the next instruction after the address in register P1.\n*/\ncase OP_Return: {           /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags & MEM_Int );\n  pc = (int)pIn1->u.i;\n  break;\n}\n\n/* Opcode:  Yield P1 * * * *\n**\n** Swap the program counter with the value in register P1.\n*/\ncase OP_Yield: {            /* in1 */\n#if 0  /* local variables moved into u.aa */\n  int pcDest;\n#endif /* local variables moved into u.aa */\n  pIn1 = &aMem[pOp->p1];\n  assert( (pIn1->flags & MEM_Dyn)==0 );\n  pIn1->flags = MEM_Int;\n  u.aa.pcDest = (int)pIn1->u.i;\n  pIn1->u.i = pc;\n  REGISTER_TRACE(pOp->p1, pIn1);\n  pc = u.aa.pcDest;\n  break;\n}\n\n/* Opcode:  HaltIfNull  P1 P2 P3 P4 *\n**\n** Check the value in register P3.  If it is NULL then Halt using\n** parameter P1, P2, and P4 as if this were a Halt instruction.  If the\n** value in register P3 is not NULL, then this routine is a no-op.\n*/\ncase OP_HaltIfNull: {      /* in3 */\n  pIn3 = &aMem[pOp->p3];\n  if( (pIn3->flags & MEM_Null)==0 ) break;\n  /* Fall through into OP_Halt */\n}\n\n/* Opcode:  Halt P1 P2 * P4 *\n**\n** Exit immediately.  All open cursors, etc are closed\n** automatically.\n**\n** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),\n** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).\n** For errors, it can be some other value.  If P1!=0 then P2 will determine\n** whether or not to rollback the current transaction.  Do not rollback\n** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,\n** then back out all changes that have occurred during this execution of the\n** VDBE, but do not rollback the transaction. \n**\n** If P4 is not null then it is an error message string.\n**\n** There is an implied \"Halt 0 0 0\" instruction inserted at the very end of\n** every program.  So a jump past the last instruction of the program\n** is the same as executing Halt.\n*/\ncase OP_Halt: {\n  if( pOp->p1==SQLITE_OK && p->pFrame ){\n    /* Halt the sub-program. Return control to the parent frame. */\n    VdbeFrame *pFrame = p->pFrame;\n    p->pFrame = pFrame->pParent;\n    p->nFrame--;\n    sqlite3VdbeSetChanges(db, p->nChange);\n    pc = sqlite3VdbeFrameRestore(pFrame);\n    lastRowid = db->lastRowid;\n    if( pOp->p2==OE_Ignore ){\n      /* Instruction pc is the OP_Program that invoked the sub-program \n      ** currently being halted. If the p2 instruction of this OP_Halt\n      ** instruction is set to OE_Ignore, then the sub-program is throwing\n      ** an IGNORE exception. In this case jump to the address specified\n      ** as the p2 of the calling OP_Program.  */\n      pc = p->aOp[pc].p2-1;\n    }\n    aOp = p->aOp;\n    aMem = p->aMem;\n    break;\n  }\n\n  p->rc = pOp->p1;\n  p->errorAction = (u8)pOp->p2;\n  p->pc = pc;\n  if( pOp->p4.z ){\n    assert( p->rc!=SQLITE_OK );\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", pOp->p4.z);\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(pOp->p1, \"abort at %d in [%s]: %s\", pc, p->zSql, pOp->p4.z);\n  }else if( p->rc ){\n    testcase( sqlite3GlobalConfig.xLog!=0 );\n    sqlite3_log(pOp->p1, \"constraint failed at %d in [%s]\", pc, p->zSql);\n  }\n  rc = sqlite3VdbeHalt(p);\n  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );\n  if( rc==SQLITE_BUSY ){\n    p->rc = rc = SQLITE_BUSY;\n  }else{\n    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );\n    assert( rc==SQLITE_OK || db->nDeferredCons>0 );\n    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;\n  }\n  goto vdbe_return;\n}\n\n/* Opcode: Integer P1 P2 * * *\n**\n** The 32-bit integer value P1 is written into register P2.\n*/\ncase OP_Integer: {         /* out2-prerelease */\n  pOut->u.i = pOp->p1;\n  break;\n}\n\n/* Opcode: Int64 * P2 * P4 *\n**\n** P4 is a pointer to a 64-bit integer value.\n** Write that value into register P2.\n*/\ncase OP_Int64: {           /* out2-prerelease */\n  assert( pOp->p4.pI64!=0 );\n  pOut->u.i = *pOp->p4.pI64;\n  break;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/* Opcode: Real * P2 * P4 *\n**\n** P4 is a pointer to a 64-bit floating point value.\n** Write that value into register P2.\n*/\ncase OP_Real: {            /* same as TK_FLOAT, out2-prerelease */\n  pOut->flags = MEM_Real;\n  assert( !sqlite3IsNaN(*pOp->p4.pReal) );\n  pOut->r = *pOp->p4.pReal;\n  break;\n}\n#endif\n\n/* Opcode: String8 * P2 * P4 *\n**\n** P4 points to a nul terminated UTF-8 string. This opcode is transformed \n** into an OP_String before it is executed for the first time.\n*/\ncase OP_String8: {         /* same as TK_STRING, out2-prerelease */\n  assert( pOp->p4.z!=0 );\n  pOp->opcode = OP_String;\n  pOp->p1 = sqlite3Strlen30(pOp->p4.z);\n\n#ifndef SQLITE_OMIT_UTF16\n  if( encoding!=SQLITE_UTF8 ){\n    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);\n    if( rc==SQLITE_TOOBIG ) goto too_big;\n    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;\n    assert( pOut->zMalloc==pOut->z );\n    assert( pOut->flags & MEM_Dyn );\n    pOut->zMalloc = 0;\n    pOut->flags |= MEM_Static;\n    pOut->flags &= ~MEM_Dyn;\n    if( pOp->p4type==P4_DYNAMIC ){\n      sqlite3DbFree(db, pOp->p4.z);\n    }\n    pOp->p4type = P4_DYNAMIC;\n    pOp->p4.z = pOut->z;\n    pOp->p1 = pOut->n;\n  }\n#endif\n  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n  /* Fall through to the next case, OP_String */\n}\n  \n/* Opcode: String P1 P2 * P4 *\n**\n** The string value P4 of length P1 (bytes) is stored in register P2.\n*/\ncase OP_String: {          /* out2-prerelease */\n  assert( pOp->p4.z!=0 );\n  pOut->flags = MEM_Str|MEM_Static|MEM_Term;\n  pOut->z = pOp->p4.z;\n  pOut->n = pOp->p1;\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Null * P2 P3 * *\n**\n** Write a NULL into registers P2.  If P3 greater than P2, then also write\n** NULL into register P3 and ever register in between P2 and P3.  If P3\n** is less than P2 (typically P3 is zero) then only register P2 is\n** set to NULL\n*/\ncase OP_Null: {           /* out2-prerelease */\n#if 0  /* local variables moved into u.ab */\n  int cnt;\n#endif /* local variables moved into u.ab */\n  u.ab.cnt = pOp->p3-pOp->p2;\n  assert( pOp->p3<=p->nMem );\n  pOut->flags = MEM_Null;\n  while( u.ab.cnt>0 ){\n    pOut++;\n    memAboutToChange(p, pOut);\n    VdbeMemRelease(pOut);\n    pOut->flags = MEM_Null;\n    u.ab.cnt--;\n  }\n  break;\n}\n\n\n/* Opcode: Blob P1 P2 * P4\n**\n** P4 points to a blob of data P1 bytes long.  Store this\n** blob in register P2.\n*/\ncase OP_Blob: {                /* out2-prerelease */\n  assert( pOp->p1 <= SQLITE_MAX_LENGTH );\n  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Variable P1 P2 * P4 *\n**\n** Transfer the values of bound parameter P1 into register P2\n**\n** If the parameter is named, then its name appears in P4 and P3==1.\n** The P4 value is used by sqlite3_bind_parameter_name().\n*/\ncase OP_Variable: {            /* out2-prerelease */\n#if 0  /* local variables moved into u.ac */\n  Mem *pVar;       /* Value being transferred */\n#endif /* local variables moved into u.ac */\n\n  assert( pOp->p1>0 && pOp->p1<=p->nVar );\n  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );\n  u.ac.pVar = &p->aVar[pOp->p1 - 1];\n  if( sqlite3VdbeMemTooBig(u.ac.pVar) ){\n    goto too_big;\n  }\n  sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Move P1 P2 P3 * *\n**\n** Move the values in register P1..P1+P3-1 over into\n** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are\n** left holding a NULL.  It is an error for register ranges\n** P1..P1+P3-1 and P2..P2+P3-1 to overlap.\n*/\ncase OP_Move: {\n#if 0  /* local variables moved into u.ad */\n  char *zMalloc;   /* Holding variable for allocated memory */\n  int n;           /* Number of registers left to copy */\n  int p1;          /* Register to copy from */\n  int p2;          /* Register to copy to */\n#endif /* local variables moved into u.ad */\n\n  u.ad.n = pOp->p3;\n  u.ad.p1 = pOp->p1;\n  u.ad.p2 = pOp->p2;\n  assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );\n  assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );\n\n  pIn1 = &aMem[u.ad.p1];\n  pOut = &aMem[u.ad.p2];\n  while( u.ad.n-- ){\n    assert( pOut<=&aMem[p->nMem] );\n    assert( pIn1<=&aMem[p->nMem] );\n    assert( memIsValid(pIn1) );\n    memAboutToChange(p, pOut);\n    u.ad.zMalloc = pOut->zMalloc;\n    pOut->zMalloc = 0;\n    sqlite3VdbeMemMove(pOut, pIn1);\n#ifdef SQLITE_DEBUG\n    if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){\n      pOut->pScopyFrom += u.ad.p1 - pOp->p2;\n    }\n#endif\n    pIn1->zMalloc = u.ad.zMalloc;\n    REGISTER_TRACE(u.ad.p2++, pOut);\n    pIn1++;\n    pOut++;\n  }\n  break;\n}\n\n/* Opcode: Copy P1 P2 * * *\n**\n** Make a copy of register P1 into register P2.\n**\n** This instruction makes a deep copy of the value.  A duplicate\n** is made of any string or blob constant.  See also OP_SCopy.\n*/\ncase OP_Copy: {             /* in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  assert( pOut!=pIn1 );\n  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);\n  Deephemeralize(pOut);\n  REGISTER_TRACE(pOp->p2, pOut);\n  break;\n}\n\n/* Opcode: SCopy P1 P2 * * *\n**\n** Make a shallow copy of register P1 into register P2.\n**\n** This instruction makes a shallow copy of the value.  If the value\n** is a string or blob, then the copy is only a pointer to the\n** original and hence if the original changes so will the copy.\n** Worse, if the original is deallocated, the copy becomes invalid.\n** Thus the program must guarantee that the original will not change\n** during the lifetime of the copy.  Use OP_Copy to make a complete\n** copy.\n*/\ncase OP_SCopy: {            /* in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  assert( pOut!=pIn1 );\n  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);\n#ifdef SQLITE_DEBUG\n  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;\n#endif\n  REGISTER_TRACE(pOp->p2, pOut);\n  break;\n}\n\n/* Opcode: ResultRow P1 P2 * * *\n**\n** The registers P1 through P1+P2-1 contain a single row of\n** results. This opcode causes the sqlite3_step() call to terminate\n** with an SQLITE_ROW return code and it sets up the sqlite3_stmt\n** structure to provide access to the top P1 values as the result\n** row.\n*/\ncase OP_ResultRow: {\n#if 0  /* local variables moved into u.ae */\n  Mem *pMem;\n  int i;\n#endif /* local variables moved into u.ae */\n  assert( p->nResColumn==pOp->p2 );\n  assert( pOp->p1>0 );\n  assert( pOp->p1+pOp->p2<=p->nMem+1 );\n\n  /* If this statement has violated immediate foreign key constraints, do\n  ** not return the number of rows modified. And do not RELEASE the statement\n  ** transaction. It needs to be rolled back.  */\n  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){\n    assert( db->flags&SQLITE_CountRows );\n    assert( p->usesStmtJournal );\n    break;\n  }\n\n  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then\n  ** DML statements invoke this opcode to return the number of rows\n  ** modified to the user. This is the only way that a VM that\n  ** opens a statement transaction may invoke this opcode.\n  **\n  ** In case this is such a statement, close any statement transaction\n  ** opened by this VM before returning control to the user. This is to\n  ** ensure that statement-transactions are always nested, not overlapping.\n  ** If the open statement-transaction is not closed here, then the user\n  ** may step another VM that opens its own statement transaction. This\n  ** may lead to overlapping statement transactions.\n  **\n  ** The statement transaction is never a top-level transaction.  Hence\n  ** the RELEASE call below can never fail.\n  */\n  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );\n  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);\n  if( NEVER(rc!=SQLITE_OK) ){\n    break;\n  }\n\n  /* Invalidate all ephemeral cursor row caches */\n  p->cacheCtr = (p->cacheCtr + 2)|1;\n\n  /* Make sure the results of the current row are \\000 terminated\n  ** and have an assigned type.  The results are de-ephemeralized as\n  ** a side effect.\n  */\n  u.ae.pMem = p->pResultSet = &aMem[pOp->p1];\n  for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){\n    assert( memIsValid(&u.ae.pMem[u.ae.i]) );\n    Deephemeralize(&u.ae.pMem[u.ae.i]);\n    assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0\n            || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );\n    sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);\n    sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);\n    REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);\n  }\n  if( db->mallocFailed ) goto no_mem;\n\n  /* Return SQLITE_ROW\n  */\n  p->pc = pc + 1;\n  rc = SQLITE_ROW;\n  goto vdbe_return;\n}\n\n/* Opcode: Concat P1 P2 P3 * *\n**\n** Add the text in register P1 onto the end of the text in\n** register P2 and store the result in register P3.\n** If either the P1 or P2 text are NULL then store NULL in P3.\n**\n**   P3 = P2 || P1\n**\n** It is illegal for P1 and P3 to be the same register. Sometimes,\n** if P3 is the same register as P2, the implementation is able\n** to avoid a memcpy().\n*/\ncase OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */\n#if 0  /* local variables moved into u.af */\n  i64 nByte;\n#endif /* local variables moved into u.af */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  pOut = &aMem[pOp->p3];\n  assert( pIn1!=pOut );\n  if( (pIn1->flags | pIn2->flags) & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n    break;\n  }\n  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;\n  Stringify(pIn1, encoding);\n  Stringify(pIn2, encoding);\n  u.af.nByte = pIn1->n + pIn2->n;\n  if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n  MemSetTypeFlag(pOut, MEM_Str);\n  if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){\n    goto no_mem;\n  }\n  if( pOut!=pIn2 ){\n    memcpy(pOut->z, pIn2->z, pIn2->n);\n  }\n  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);\n  pOut->z[u.af.nByte] = 0;\n  pOut->z[u.af.nByte+1] = 0;\n  pOut->flags |= MEM_Term;\n  pOut->n = (int)u.af.nByte;\n  pOut->enc = encoding;\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Add P1 P2 P3 * *\n**\n** Add the value in register P1 to the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Multiply P1 P2 P3 * *\n**\n**\n** Multiply the value in register P1 by the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Subtract P1 P2 P3 * *\n**\n** Subtract the value in register P1 from the value in register P2\n** and store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: Divide P1 P2 P3 * *\n**\n** Divide the value in register P1 by the value in register P2\n** and store the result in register P3 (P3=P2/P1). If the value in \n** register P1 is zero, then the result is NULL. If either input is \n** NULL, the result is NULL.\n*/\n/* Opcode: Remainder P1 P2 P3 * *\n**\n** Compute the remainder after integer division of the value in\n** register P1 by the value in register P2 and store the result in P3. \n** If the value in register P2 is zero the result is NULL.\n** If either operand is NULL, the result is NULL.\n*/\ncase OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */\ncase OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */\ncase OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */\ncase OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */\ncase OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */\n#if 0  /* local variables moved into u.ag */\n  int flags;      /* Combined MEM_* flags from both inputs */\n  i64 iA;         /* Integer value of left operand */\n  i64 iB;         /* Integer value of right operand */\n  double rA;      /* Real value of left operand */\n  double rB;      /* Real value of right operand */\n#endif /* local variables moved into u.ag */\n\n  pIn1 = &aMem[pOp->p1];\n  applyNumericAffinity(pIn1);\n  pIn2 = &aMem[pOp->p2];\n  applyNumericAffinity(pIn2);\n  pOut = &aMem[pOp->p3];\n  u.ag.flags = pIn1->flags | pIn2->flags;\n  if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;\n  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){\n    u.ag.iA = pIn1->u.i;\n    u.ag.iB = pIn2->u.i;\n    switch( pOp->opcode ){\n      case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;\n      case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;\n      case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;\n      case OP_Divide: {\n        if( u.ag.iA==0 ) goto arithmetic_result_is_null;\n        if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;\n        u.ag.iB /= u.ag.iA;\n        break;\n      }\n      default: {\n        if( u.ag.iA==0 ) goto arithmetic_result_is_null;\n        if( u.ag.iA==-1 ) u.ag.iA = 1;\n        u.ag.iB %= u.ag.iA;\n        break;\n      }\n    }\n    pOut->u.i = u.ag.iB;\n    MemSetTypeFlag(pOut, MEM_Int);\n  }else{\nfp_math:\n    u.ag.rA = sqlite3VdbeRealValue(pIn1);\n    u.ag.rB = sqlite3VdbeRealValue(pIn2);\n    switch( pOp->opcode ){\n      case OP_Add:         u.ag.rB += u.ag.rA;       break;\n      case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;\n      case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;\n      case OP_Divide: {\n        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n        if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;\n        u.ag.rB /= u.ag.rA;\n        break;\n      }\n      default: {\n        u.ag.iA = (i64)u.ag.rA;\n        u.ag.iB = (i64)u.ag.rB;\n        if( u.ag.iA==0 ) goto arithmetic_result_is_null;\n        if( u.ag.iA==-1 ) u.ag.iA = 1;\n        u.ag.rB = (double)(u.ag.iB % u.ag.iA);\n        break;\n      }\n    }\n#ifdef SQLITE_OMIT_FLOATING_POINT\n    pOut->u.i = u.ag.rB;\n    MemSetTypeFlag(pOut, MEM_Int);\n#else\n    if( sqlite3IsNaN(u.ag.rB) ){\n      goto arithmetic_result_is_null;\n    }\n    pOut->r = u.ag.rB;\n    MemSetTypeFlag(pOut, MEM_Real);\n    if( (u.ag.flags & MEM_Real)==0 ){\n      sqlite3VdbeIntegerAffinity(pOut);\n    }\n#endif\n  }\n  break;\n\narithmetic_result_is_null:\n  sqlite3VdbeMemSetNull(pOut);\n  break;\n}\n\n/* Opcode: CollSeq P1 * * P4\n**\n** P4 is a pointer to a CollSeq struct. If the next call to a user function\n** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will\n** be returned. This is used by the built-in min(), max() and nullif()\n** functions.\n**\n** If P1 is not zero, then it is a register that a subsequent min() or\n** max() aggregate will set to 1 if the current row is not the minimum or\n** maximum.  The P1 register is initialized to 0 by this instruction.\n**\n** The interface used by the implementation of the aforementioned functions\n** to retrieve the collation sequence set by this opcode is not available\n** publicly, only to user functions defined in func.c.\n*/\ncase OP_CollSeq: {\n  assert( pOp->p4type==P4_COLLSEQ );\n  if( pOp->p1 ){\n    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);\n  }\n  break;\n}\n\n/* Opcode: Function P1 P2 P3 P4 P5\n**\n** Invoke a user function (P4 is a pointer to a Function structure that\n** defines the function) with P5 arguments taken from register P2 and\n** successors.  The result of the function is stored in register P3.\n** Register P3 must not be one of the function inputs.\n**\n** P1 is a 32-bit bitmask indicating whether or not each argument to the \n** function was determined to be constant at compile time. If the first\n** argument was constant then bit 0 of P1 is set. This is used to determine\n** whether meta data associated with a user function argument using the\n** sqlite3_set_auxdata() API may be safely retained until the next\n** invocation of this opcode.\n**\n** See also: AggStep and AggFinal\n*/\ncase OP_Function: {\n#if 0  /* local variables moved into u.ah */\n  int i;\n  Mem *pArg;\n  sqlite3_context ctx;\n  sqlite3_value **apVal;\n  int n;\n#endif /* local variables moved into u.ah */\n\n  u.ah.n = pOp->p5;\n  u.ah.apVal = p->apArg;\n  assert( u.ah.apVal || u.ah.n==0 );\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  pOut = &aMem[pOp->p3];\n  memAboutToChange(p, pOut);\n\n  assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );\n  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );\n  u.ah.pArg = &aMem[pOp->p2];\n  for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){\n    assert( memIsValid(u.ah.pArg) );\n    u.ah.apVal[u.ah.i] = u.ah.pArg;\n    Deephemeralize(u.ah.pArg);\n    sqlite3VdbeMemStoreType(u.ah.pArg);\n    REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);\n  }\n\n  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );\n  if( pOp->p4type==P4_FUNCDEF ){\n    u.ah.ctx.pFunc = pOp->p4.pFunc;\n    u.ah.ctx.pVdbeFunc = 0;\n  }else{\n    u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;\n    u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;\n  }\n\n  u.ah.ctx.s.flags = MEM_Null;\n  u.ah.ctx.s.db = db;\n  u.ah.ctx.s.xDel = 0;\n  u.ah.ctx.s.zMalloc = 0;\n\n  /* The output cell may already have a buffer allocated. Move\n  ** the pointer to u.ah.ctx.s so in case the user-function can use\n  ** the already allocated buffer instead of allocating a new one.\n  */\n  sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);\n  MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);\n\n  u.ah.ctx.isError = 0;\n  if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){\n    assert( pOp>aOp );\n    assert( pOp[-1].p4type==P4_COLLSEQ );\n    assert( pOp[-1].opcode==OP_CollSeq );\n    u.ah.ctx.pColl = pOp[-1].p4.pColl;\n  }\n  db->lastRowid = lastRowid;\n  (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */\n  lastRowid = db->lastRowid;\n\n  /* If any auxiliary data functions have been called by this user function,\n  ** immediately call the destructor for any non-static values.\n  */\n  if( u.ah.ctx.pVdbeFunc ){\n    sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);\n    pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;\n    pOp->p4type = P4_VDBEFUNC;\n  }\n\n  if( db->mallocFailed ){\n    /* Even though a malloc() has failed, the implementation of the\n    ** user function may have called an sqlite3_result_XXX() function\n    ** to return a value. The following call releases any resources\n    ** associated with such a value.\n    */\n    sqlite3VdbeMemRelease(&u.ah.ctx.s);\n    goto no_mem;\n  }\n\n  /* If the function returned an error, throw an exception */\n  if( u.ah.ctx.isError ){\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3_value_text(&u.ah.ctx.s));\n    rc = u.ah.ctx.isError;\n  }\n\n  /* Copy the result of the function into register P3 */\n  sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);\n  sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);\n  if( sqlite3VdbeMemTooBig(pOut) ){\n    goto too_big;\n  }\n\n#if 0\n  /* The app-defined function has done something that as caused this\n  ** statement to expire.  (Perhaps the function called sqlite3_exec()\n  ** with a CREATE TABLE statement.)\n  */\n  if( p->expired ) rc = SQLITE_ABORT;\n#endif\n\n  REGISTER_TRACE(pOp->p3, pOut);\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: BitAnd P1 P2 P3 * *\n**\n** Take the bit-wise AND of the values in register P1 and P2 and\n** store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: BitOr P1 P2 P3 * *\n**\n** Take the bit-wise OR of the values in register P1 and P2 and\n** store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: ShiftLeft P1 P2 P3 * *\n**\n** Shift the integer value in register P2 to the left by the\n** number of bits specified by the integer in register P1.\n** Store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\n/* Opcode: ShiftRight P1 P2 P3 * *\n**\n** Shift the integer value in register P2 to the right by the\n** number of bits specified by the integer in register P1.\n** Store the result in register P3.\n** If either input is NULL, the result is NULL.\n*/\ncase OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */\ncase OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */\ncase OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */\ncase OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */\n#if 0  /* local variables moved into u.ai */\n  i64 iA;\n  u64 uA;\n  i64 iB;\n  u8 op;\n#endif /* local variables moved into u.ai */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  pOut = &aMem[pOp->p3];\n  if( (pIn1->flags | pIn2->flags) & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n    break;\n  }\n  u.ai.iA = sqlite3VdbeIntValue(pIn2);\n  u.ai.iB = sqlite3VdbeIntValue(pIn1);\n  u.ai.op = pOp->opcode;\n  if( u.ai.op==OP_BitAnd ){\n    u.ai.iA &= u.ai.iB;\n  }else if( u.ai.op==OP_BitOr ){\n    u.ai.iA |= u.ai.iB;\n  }else if( u.ai.iB!=0 ){\n    assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );\n\n    /* If shifting by a negative amount, shift in the other direction */\n    if( u.ai.iB<0 ){\n      assert( OP_ShiftRight==OP_ShiftLeft+1 );\n      u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;\n      u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;\n    }\n\n    if( u.ai.iB>=64 ){\n      u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;\n    }else{\n      memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));\n      if( u.ai.op==OP_ShiftLeft ){\n        u.ai.uA <<= u.ai.iB;\n      }else{\n        u.ai.uA >>= u.ai.iB;\n        /* Sign-extend on a right shift of a negative number */\n        if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);\n      }\n      memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));\n    }\n  }\n  pOut->u.i = u.ai.iA;\n  MemSetTypeFlag(pOut, MEM_Int);\n  break;\n}\n\n/* Opcode: AddImm  P1 P2 * * *\n** \n** Add the constant P2 to the value in register P1.\n** The result is always an integer.\n**\n** To force any register to be an integer, just add 0.\n*/\ncase OP_AddImm: {            /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  memAboutToChange(p, pIn1);\n  sqlite3VdbeMemIntegerify(pIn1);\n  pIn1->u.i += pOp->p2;\n  break;\n}\n\n/* Opcode: MustBeInt P1 P2 * * *\n** \n** Force the value in register P1 to be an integer.  If the value\n** in P1 is not an integer and cannot be converted into an integer\n** without data loss, then jump immediately to P2, or if P2==0\n** raise an SQLITE_MISMATCH exception.\n*/\ncase OP_MustBeInt: {            /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);\n  if( (pIn1->flags & MEM_Int)==0 ){\n    if( pOp->p2==0 ){\n      rc = SQLITE_MISMATCH;\n      goto abort_due_to_error;\n    }else{\n      pc = pOp->p2 - 1;\n    }\n  }else{\n    MemSetTypeFlag(pIn1, MEM_Int);\n  }\n  break;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/* Opcode: RealAffinity P1 * * * *\n**\n** If register P1 holds an integer convert it to a real value.\n**\n** This opcode is used when extracting information from a column that\n** has REAL affinity.  Such column values may still be stored as\n** integers, for space efficiency, but after extraction we want them\n** to have only a real value.\n*/\ncase OP_RealAffinity: {                  /* in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( pIn1->flags & MEM_Int ){\n    sqlite3VdbeMemRealify(pIn1);\n  }\n  break;\n}\n#endif\n\n#ifndef SQLITE_OMIT_CAST\n/* Opcode: ToText P1 * * * *\n**\n** Force the value in register P1 to be text.\n** If the value is numeric, convert it to a string using the\n** equivalent of printf().  Blob values are unchanged and\n** are afterwards simply interpreted as text.\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_ToText: {                  /* same as TK_TO_TEXT, in1 */\n  pIn1 = &aMem[pOp->p1];\n  memAboutToChange(p, pIn1);\n  if( pIn1->flags & MEM_Null ) break;\n  assert( MEM_Str==(MEM_Blob>>3) );\n  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;\n  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);\n  rc = ExpandBlob(pIn1);\n  assert( pIn1->flags & MEM_Str || db->mallocFailed );\n  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);\n  UPDATE_MAX_BLOBSIZE(pIn1);\n  break;\n}\n\n/* Opcode: ToBlob P1 * * * *\n**\n** Force the value in register P1 to be a BLOB.\n** If the value is numeric, convert it to a string first.\n** Strings are simply reinterpreted as blobs with no change\n** to the underlying data.\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( pIn1->flags & MEM_Null ) break;\n  if( (pIn1->flags & MEM_Blob)==0 ){\n    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);\n    assert( pIn1->flags & MEM_Str || db->mallocFailed );\n    MemSetTypeFlag(pIn1, MEM_Blob);\n  }else{\n    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);\n  }\n  UPDATE_MAX_BLOBSIZE(pIn1);\n  break;\n}\n\n/* Opcode: ToNumeric P1 * * * *\n**\n** Force the value in register P1 to be numeric (either an\n** integer or a floating-point number.)\n** If the value is text or blob, try to convert it to an using the\n** equivalent of atoi() or atof() and store 0 if no such conversion \n** is possible.\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */\n  pIn1 = &aMem[pOp->p1];\n  sqlite3VdbeMemNumerify(pIn1);\n  break;\n}\n#endif /* SQLITE_OMIT_CAST */\n\n/* Opcode: ToInt P1 * * * *\n**\n** Force the value in register P1 to be an integer.  If\n** The value is currently a real number, drop its fractional part.\n** If the value is text or blob, try to convert it to an integer using the\n** equivalent of atoi() and store 0 if no such conversion is possible.\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_ToInt: {                  /* same as TK_TO_INT, in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( (pIn1->flags & MEM_Null)==0 ){\n    sqlite3VdbeMemIntegerify(pIn1);\n  }\n  break;\n}\n\n#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)\n/* Opcode: ToReal P1 * * * *\n**\n** Force the value in register P1 to be a floating point number.\n** If The value is currently an integer, convert it.\n** If the value is text or blob, try to convert it to an integer using the\n** equivalent of atoi() and store 0.0 if no such conversion is possible.\n**\n** A NULL value is not changed by this routine.  It remains NULL.\n*/\ncase OP_ToReal: {                  /* same as TK_TO_REAL, in1 */\n  pIn1 = &aMem[pOp->p1];\n  memAboutToChange(p, pIn1);\n  if( (pIn1->flags & MEM_Null)==0 ){\n    sqlite3VdbeMemRealify(pIn1);\n  }\n  break;\n}\n#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */\n\n/* Opcode: Lt P1 P2 P3 P4 P5\n**\n** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then\n** jump to address P2.  \n**\n** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or\n** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL \n** bit is clear then fall through if either operand is NULL.\n**\n** The SQLITE_AFF_MASK portion of P5 must be an affinity character -\n** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made \n** to coerce both inputs according to this affinity before the\n** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric\n** affinity is used. Note that the affinity conversions are stored\n** back into the input registers P1 and P3.  So this opcode can cause\n** persistent changes to registers P1 and P3.\n**\n** Once any conversions have taken place, and neither value is NULL, \n** the values are compared. If both values are blobs then memcmp() is\n** used to determine the results of the comparison.  If both values\n** are text, then the appropriate collating function specified in\n** P4 is  used to do the comparison.  If P4 is not specified then\n** memcmp() is used to compare text string.  If both values are\n** numeric, then a numeric comparison is used. If the two values\n** are of different types, then numbers are considered less than\n** strings and strings are considered less than blobs.\n**\n** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,\n** store a boolean result (either 0, or 1, or NULL) in register P2.\n*/\n/* Opcode: Ne P1 P2 P3 P4 P5\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the operands in registers P1 and P3 are not equal.  See the Lt opcode for\n** additional information.\n**\n** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either\n** true or false and is never NULL.  If both operands are NULL then the result\n** of comparison is false.  If either operand is NULL then the result is true.\n** If neither operand is NULL the result is the same as it would be if\n** the SQLITE_NULLEQ flag were omitted from P5.\n*/\n/* Opcode: Eq P1 P2 P3 P4 P5\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the operands in registers P1 and P3 are equal.\n** See the Lt opcode for additional information.\n**\n** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either\n** true or false and is never NULL.  If both operands are NULL then the result\n** of comparison is true.  If either operand is NULL then the result is false.\n** If neither operand is NULL the result is the same as it would be if\n** the SQLITE_NULLEQ flag were omitted from P5.\n*/\n/* Opcode: Le P1 P2 P3 P4 P5\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is less than or equal to the content of\n** register P1.  See the Lt opcode for additional information.\n*/\n/* Opcode: Gt P1 P2 P3 P4 P5\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is greater than the content of\n** register P1.  See the Lt opcode for additional information.\n*/\n/* Opcode: Ge P1 P2 P3 P4 P5\n**\n** This works just like the Lt opcode except that the jump is taken if\n** the content of register P3 is greater than or equal to the content of\n** register P1.  See the Lt opcode for additional information.\n*/\ncase OP_Eq:               /* same as TK_EQ, jump, in1, in3 */\ncase OP_Ne:               /* same as TK_NE, jump, in1, in3 */\ncase OP_Lt:               /* same as TK_LT, jump, in1, in3 */\ncase OP_Le:               /* same as TK_LE, jump, in1, in3 */\ncase OP_Gt:               /* same as TK_GT, jump, in1, in3 */\ncase OP_Ge: {             /* same as TK_GE, jump, in1, in3 */\n#if 0  /* local variables moved into u.aj */\n  int res;            /* Result of the comparison of pIn1 against pIn3 */\n  char affinity;      /* Affinity to use for comparison */\n  u16 flags1;         /* Copy of initial value of pIn1->flags */\n  u16 flags3;         /* Copy of initial value of pIn3->flags */\n#endif /* local variables moved into u.aj */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn3 = &aMem[pOp->p3];\n  u.aj.flags1 = pIn1->flags;\n  u.aj.flags3 = pIn3->flags;\n  if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){\n    /* One or both operands are NULL */\n    if( pOp->p5 & SQLITE_NULLEQ ){\n      /* If SQLITE_NULLEQ is set (which will only happen if the operator is\n      ** OP_Eq or OP_Ne) then take the jump or not depending on whether\n      ** or not both operands are null.\n      */\n      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );\n      u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;\n    }else{\n      /* SQLITE_NULLEQ is clear and at least one operand is NULL,\n      ** then the result is always NULL.\n      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.\n      */\n      if( pOp->p5 & SQLITE_STOREP2 ){\n        pOut = &aMem[pOp->p2];\n        MemSetTypeFlag(pOut, MEM_Null);\n        REGISTER_TRACE(pOp->p2, pOut);\n      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){\n        pc = pOp->p2-1;\n      }\n      break;\n    }\n  }else{\n    /* Neither operand is NULL.  Do a comparison. */\n    u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;\n    if( u.aj.affinity ){\n      applyAffinity(pIn1, u.aj.affinity, encoding);\n      applyAffinity(pIn3, u.aj.affinity, encoding);\n      if( db->mallocFailed ) goto no_mem;\n    }\n\n    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );\n    ExpandBlob(pIn1);\n    ExpandBlob(pIn3);\n    u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);\n  }\n  switch( pOp->opcode ){\n    case OP_Eq:    u.aj.res = u.aj.res==0;     break;\n    case OP_Ne:    u.aj.res = u.aj.res!=0;     break;\n    case OP_Lt:    u.aj.res = u.aj.res<0;      break;\n    case OP_Le:    u.aj.res = u.aj.res<=0;     break;\n    case OP_Gt:    u.aj.res = u.aj.res>0;      break;\n    default:       u.aj.res = u.aj.res>=0;     break;\n  }\n\n  if( pOp->p5 & SQLITE_STOREP2 ){\n    pOut = &aMem[pOp->p2];\n    memAboutToChange(p, pOut);\n    MemSetTypeFlag(pOut, MEM_Int);\n    pOut->u.i = u.aj.res;\n    REGISTER_TRACE(pOp->p2, pOut);\n  }else if( u.aj.res ){\n    pc = pOp->p2-1;\n  }\n\n  /* Undo any changes made by applyAffinity() to the input registers. */\n  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);\n  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);\n  break;\n}\n\n/* Opcode: Permutation * * * P4 *\n**\n** Set the permutation used by the OP_Compare operator to be the array\n** of integers in P4.\n**\n** The permutation is only valid until the next OP_Permutation, OP_Compare,\n** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur\n** immediately prior to the OP_Compare.\n*/\ncase OP_Permutation: {\n  assert( pOp->p4type==P4_INTARRAY );\n  assert( pOp->p4.ai );\n  aPermute = pOp->p4.ai;\n  break;\n}\n\n/* Opcode: Compare P1 P2 P3 P4 *\n**\n** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this\n** vector \"A\") and in reg(P2)..reg(P2+P3-1) (\"B\").  Save the result of\n** the comparison for use by the next OP_Jump instruct.\n**\n** P4 is a KeyInfo structure that defines collating sequences and sort\n** orders for the comparison.  The permutation applies to registers\n** only.  The KeyInfo elements are used sequentially.\n**\n** The comparison is a sort comparison, so NULLs compare equal,\n** NULLs are less than numbers, numbers are less than strings,\n** and strings are less than blobs.\n*/\ncase OP_Compare: {\n#if 0  /* local variables moved into u.ak */\n  int n;\n  int i;\n  int p1;\n  int p2;\n  const KeyInfo *pKeyInfo;\n  int idx;\n  CollSeq *pColl;    /* Collating sequence to use on this term */\n  int bRev;          /* True for DESCENDING sort order */\n#endif /* local variables moved into u.ak */\n\n  u.ak.n = pOp->p3;\n  u.ak.pKeyInfo = pOp->p4.pKeyInfo;\n  assert( u.ak.n>0 );\n  assert( u.ak.pKeyInfo!=0 );\n  u.ak.p1 = pOp->p1;\n  u.ak.p2 = pOp->p2;\n#if SQLITE_DEBUG\n  if( aPermute ){\n    int k, mx = 0;\n    for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];\n    assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );\n    assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );\n  }else{\n    assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );\n    assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );\n  }\n#endif /* SQLITE_DEBUG */\n  for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){\n    u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;\n    assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );\n    assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );\n    REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);\n    REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);\n    assert( u.ak.i<u.ak.pKeyInfo->nField );\n    u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];\n    u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];\n    iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);\n    if( iCompare ){\n      if( u.ak.bRev ) iCompare = -iCompare;\n      break;\n    }\n  }\n  aPermute = 0;\n  break;\n}\n\n/* Opcode: Jump P1 P2 P3 * *\n**\n** Jump to the instruction at address P1, P2, or P3 depending on whether\n** in the most recent OP_Compare instruction the P1 vector was less than\n** equal to, or greater than the P2 vector, respectively.\n*/\ncase OP_Jump: {             /* jump */\n  if( iCompare<0 ){\n    pc = pOp->p1 - 1;\n  }else if( iCompare==0 ){\n    pc = pOp->p2 - 1;\n  }else{\n    pc = pOp->p3 - 1;\n  }\n  break;\n}\n\n/* Opcode: And P1 P2 P3 * *\n**\n** Take the logical AND of the values in registers P1 and P2 and\n** write the result into register P3.\n**\n** If either P1 or P2 is 0 (false) then the result is 0 even if\n** the other input is NULL.  A NULL and true or two NULLs give\n** a NULL output.\n*/\n/* Opcode: Or P1 P2 P3 * *\n**\n** Take the logical OR of the values in register P1 and P2 and\n** store the answer in register P3.\n**\n** If either P1 or P2 is nonzero (true) then the result is 1 (true)\n** even if the other input is NULL.  A NULL and false or two NULLs\n** give a NULL output.\n*/\ncase OP_And:              /* same as TK_AND, in1, in2, out3 */\ncase OP_Or: {             /* same as TK_OR, in1, in2, out3 */\n#if 0  /* local variables moved into u.al */\n  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */\n#endif /* local variables moved into u.al */\n\n  pIn1 = &aMem[pOp->p1];\n  if( pIn1->flags & MEM_Null ){\n    u.al.v1 = 2;\n  }else{\n    u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;\n  }\n  pIn2 = &aMem[pOp->p2];\n  if( pIn2->flags & MEM_Null ){\n    u.al.v2 = 2;\n  }else{\n    u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;\n  }\n  if( pOp->opcode==OP_And ){\n    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };\n    u.al.v1 = and_logic[u.al.v1*3+u.al.v2];\n  }else{\n    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };\n    u.al.v1 = or_logic[u.al.v1*3+u.al.v2];\n  }\n  pOut = &aMem[pOp->p3];\n  if( u.al.v1==2 ){\n    MemSetTypeFlag(pOut, MEM_Null);\n  }else{\n    pOut->u.i = u.al.v1;\n    MemSetTypeFlag(pOut, MEM_Int);\n  }\n  break;\n}\n\n/* Opcode: Not P1 P2 * * *\n**\n** Interpret the value in register P1 as a boolean value.  Store the\n** boolean complement in register P2.  If the value in register P1 is \n** NULL, then a NULL is stored in P2.\n*/\ncase OP_Not: {                /* same as TK_NOT, in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  if( pIn1->flags & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n  }else{\n    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));\n  }\n  break;\n}\n\n/* Opcode: BitNot P1 P2 * * *\n**\n** Interpret the content of register P1 as an integer.  Store the\n** ones-complement of the P1 value into register P2.  If P1 holds\n** a NULL then store a NULL in P2.\n*/\ncase OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */\n  pIn1 = &aMem[pOp->p1];\n  pOut = &aMem[pOp->p2];\n  if( pIn1->flags & MEM_Null ){\n    sqlite3VdbeMemSetNull(pOut);\n  }else{\n    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));\n  }\n  break;\n}\n\n/* Opcode: Once P1 P2 * * *\n**\n** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,\n** set the flag and fall through to the next instruction.\n**\n** See also: JumpOnce\n*/\ncase OP_Once: {             /* jump */\n  assert( pOp->p1<p->nOnceFlag );\n  if( p->aOnceFlag[pOp->p1] ){\n    pc = pOp->p2-1;\n  }else{\n    p->aOnceFlag[pOp->p1] = 1;\n  }\n  break;\n}\n\n/* Opcode: If P1 P2 P3 * *\n**\n** Jump to P2 if the value in register P1 is true.  The value\n** is considered true if it is numeric and non-zero.  If the value\n** in P1 is NULL then take the jump if P3 is non-zero.\n*/\n/* Opcode: IfNot P1 P2 P3 * *\n**\n** Jump to P2 if the value in register P1 is False.  The value\n** is considered false if it has a numeric value of zero.  If the value\n** in P1 is NULL then take the jump if P3 is zero.\n*/\ncase OP_If:                 /* jump, in1 */\ncase OP_IfNot: {            /* jump, in1 */\n#if 0  /* local variables moved into u.am */\n  int c;\n#endif /* local variables moved into u.am */\n  pIn1 = &aMem[pOp->p1];\n  if( pIn1->flags & MEM_Null ){\n    u.am.c = pOp->p3;\n  }else{\n#ifdef SQLITE_OMIT_FLOATING_POINT\n    u.am.c = sqlite3VdbeIntValue(pIn1)!=0;\n#else\n    u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;\n#endif\n    if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;\n  }\n  if( u.am.c ){\n    pc = pOp->p2-1;\n  }\n  break;\n}\n\n/* Opcode: IsNull P1 P2 * * *\n**\n** Jump to P2 if the value in register P1 is NULL.\n*/\ncase OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( (pIn1->flags & MEM_Null)!=0 ){\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: NotNull P1 P2 * * *\n**\n** Jump to P2 if the value in register P1 is not NULL.  \n*/\ncase OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  if( (pIn1->flags & MEM_Null)==0 ){\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: Column P1 P2 P3 P4 P5\n**\n** Interpret the data that cursor P1 points to as a structure built using\n** the MakeRecord instruction.  (See the MakeRecord opcode for additional\n** information about the format of the data.)  Extract the P2-th column\n** from this record.  If there are less that (P2+1) \n** values in the record, extract a NULL.\n**\n** The value extracted is stored in register P3.\n**\n** If the column contains fewer than P2 fields, then extract a NULL.  Or,\n** if the P4 argument is a P4_MEM use the value of the P4 argument as\n** the result.\n**\n** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,\n** then the cache of the cursor is reset prior to extracting the column.\n** The first OP_Column against a pseudo-table after the value of the content\n** register has changed should have this bit set.\n**\n** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when\n** the result is guaranteed to only be used as the argument of a length()\n** or typeof() function, respectively.  The loading of large blobs can be\n** skipped for length() and all content loading can be skipped for typeof().\n*/\ncase OP_Column: {\n#if 0  /* local variables moved into u.an */\n  u32 payloadSize;   /* Number of bytes in the record */\n  i64 payloadSize64; /* Number of bytes in the record */\n  int p1;            /* P1 value of the opcode */\n  int p2;            /* column number to retrieve */\n  VdbeCursor *pC;    /* The VDBE cursor */\n  char *zRec;        /* Pointer to complete record-data */\n  BtCursor *pCrsr;   /* The BTree cursor */\n  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */\n  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */\n  int nField;        /* number of fields in the record */\n  int len;           /* The length of the serialized data for the column */\n  int i;             /* Loop counter */\n  char *zData;       /* Part of the record being decoded */\n  Mem *pDest;        /* Where to write the extracted value */\n  Mem sMem;          /* For storing the record being decoded */\n  u8 *zIdx;          /* Index into header */\n  u8 *zEndHdr;       /* Pointer to first byte after the header */\n  u32 offset;        /* Offset into the data */\n  u32 szField;       /* Number of bytes in the content of a field */\n  int szHdr;         /* Size of the header size field at start of record */\n  int avail;         /* Number of bytes of available data */\n  u32 t;             /* A type code from the record header */\n  Mem *pReg;         /* PseudoTable input register */\n#endif /* local variables moved into u.an */\n\n\n  u.an.p1 = pOp->p1;\n  u.an.p2 = pOp->p2;\n  u.an.pC = 0;\n  memset(&u.an.sMem, 0, sizeof(u.an.sMem));\n  assert( u.an.p1<p->nCursor );\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  u.an.pDest = &aMem[pOp->p3];\n  memAboutToChange(p, u.an.pDest);\n  u.an.zRec = 0;\n\n  /* This block sets the variable u.an.payloadSize to be the total number of\n  ** bytes in the record.\n  **\n  ** u.an.zRec is set to be the complete text of the record if it is available.\n  ** The complete record text is always available for pseudo-tables\n  ** If the record is stored in a cursor, the complete record text\n  ** might be available in the  u.an.pC->aRow cache.  Or it might not be.\n  ** If the data is unavailable,  u.an.zRec is set to NULL.\n  **\n  ** We also compute the number of columns in the record.  For cursors,\n  ** the number of columns is stored in the VdbeCursor.nField element.\n  */\n  u.an.pC = p->apCsr[u.an.p1];\n  assert( u.an.pC!=0 );\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  assert( u.an.pC->pVtabCursor==0 );\n#endif\n  u.an.pCrsr = u.an.pC->pCursor;\n  if( u.an.pCrsr!=0 ){\n    /* The record is stored in a B-Tree */\n    rc = sqlite3VdbeCursorMoveto(u.an.pC);\n    if( rc ) goto abort_due_to_error;\n    if( u.an.pC->nullRow ){\n      u.an.payloadSize = 0;\n    }else if( u.an.pC->cacheStatus==p->cacheCtr ){\n      u.an.payloadSize = u.an.pC->payloadSize;\n      u.an.zRec = (char*)u.an.pC->aRow;\n    }else if( u.an.pC->isIndex ){\n      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );\n      VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);\n      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */\n      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the\n      ** payload size, so it is impossible for u.an.payloadSize64 to be\n      ** larger than 32 bits. */\n      assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );\n      u.an.payloadSize = (u32)u.an.payloadSize64;\n    }else{\n      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );\n      VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);\n      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */\n    }\n  }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){\n    u.an.pReg = &aMem[u.an.pC->pseudoTableReg];\n    assert( u.an.pReg->flags & MEM_Blob );\n    assert( memIsValid(u.an.pReg) );\n    u.an.payloadSize = u.an.pReg->n;\n    u.an.zRec = u.an.pReg->z;\n    u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;\n    assert( u.an.payloadSize==0 || u.an.zRec!=0 );\n  }else{\n    /* Consider the row to be NULL */\n    u.an.payloadSize = 0;\n  }\n\n  /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of\n  ** nullRow or because of a corrupt database. */\n  if( u.an.payloadSize==0 ){\n    MemSetTypeFlag(u.an.pDest, MEM_Null);\n    goto op_column_out;\n  }\n  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );\n  if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n\n  u.an.nField = u.an.pC->nField;\n  assert( u.an.p2<u.an.nField );\n\n  /* Read and parse the table header.  Store the results of the parse\n  ** into the record header cache fields of the cursor.\n  */\n  u.an.aType = u.an.pC->aType;\n  if( u.an.pC->cacheStatus==p->cacheCtr ){\n    u.an.aOffset = u.an.pC->aOffset;\n  }else{\n    assert(u.an.aType);\n    u.an.avail = 0;\n    u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];\n    u.an.pC->payloadSize = u.an.payloadSize;\n    u.an.pC->cacheStatus = p->cacheCtr;\n\n    /* Figure out how many bytes are in the header */\n    if( u.an.zRec ){\n      u.an.zData = u.an.zRec;\n    }else{\n      if( u.an.pC->isIndex ){\n        u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);\n      }else{\n        u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);\n      }\n      /* If KeyFetch()/DataFetch() managed to get the entire payload,\n      ** save the payload in the u.an.pC->aRow cache.  That will save us from\n      ** having to make additional calls to fetch the content portion of\n      ** the record.\n      */\n      assert( u.an.avail>=0 );\n      if( u.an.payloadSize <= (u32)u.an.avail ){\n        u.an.zRec = u.an.zData;\n        u.an.pC->aRow = (u8*)u.an.zData;\n      }else{\n        u.an.pC->aRow = 0;\n      }\n    }\n    /* The following assert is true in all cases except when\n    ** the database file has been corrupted externally.\n    **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */\n    u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);\n\n    /* Make sure a corrupt database has not given us an oversize header.\n    ** Do this now to avoid an oversize memory allocation.\n    **\n    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte\n    ** types use so much data space that there can only be 4096 and 32 of\n    ** them, respectively.  So the maximum header length results from a\n    ** 3-byte type for each of the maximum of 32768 columns plus three\n    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.\n    */\n    if( u.an.offset > 98307 ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto op_column_out;\n    }\n\n    /* Compute in u.an.len the number of bytes of data we need to read in order\n    ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But\n    ** u.an.nField might be significantly less than the true number of columns\n    ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.\n    ** We want to minimize u.an.len in order to limit the size of the memory\n    ** allocation, especially if a corrupt database file has caused u.an.offset\n    ** to be oversized. Offset is limited to 98307 above.  But 98307 might\n    ** still exceed Robson memory allocation limits on some configurations.\n    ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3\n    ** will likely be much smaller since u.an.nField will likely be less than\n    ** 20 or so.  This insures that Robson memory allocation limits are\n    ** not exceeded even for corrupt database files.\n    */\n    u.an.len = u.an.nField*5 + 3;\n    if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;\n\n    /* The KeyFetch() or DataFetch() above are fast and will get the entire\n    ** record header in most cases.  But they will fail to get the complete\n    ** record header if the record header does not fit on a single page\n    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to\n    ** acquire the complete header text.\n    */\n    if( !u.an.zRec && u.an.avail<u.an.len ){\n      u.an.sMem.flags = 0;\n      u.an.sMem.db = 0;\n      rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);\n      if( rc!=SQLITE_OK ){\n        goto op_column_out;\n      }\n      u.an.zData = u.an.sMem.z;\n    }\n    u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];\n    u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];\n\n    /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]\n    ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th\n    ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning\n    ** of the record to the start of the data for the u.an.i-th column\n    */\n    for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){\n      if( u.an.zIdx<u.an.zEndHdr ){\n        u.an.aOffset[u.an.i] = u.an.offset;\n        if( u.an.zIdx[0]<0x80 ){\n          u.an.t = u.an.zIdx[0];\n          u.an.zIdx++;\n        }else{\n          u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);\n        }\n        u.an.aType[u.an.i] = u.an.t;\n        u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);\n        u.an.offset += u.an.szField;\n        if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */\n          u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */\n          break;\n        }\n      }else{\n        /* If u.an.i is less that u.an.nField, then there are fewer fields in this\n        ** record than SetNumColumns indicated there are columns in the\n        ** table. Set the u.an.offset for any extra columns not present in\n        ** the record to 0. This tells code below to store the default value\n        ** for the column instead of deserializing a value from the record.\n        */\n        u.an.aOffset[u.an.i] = 0;\n      }\n    }\n    sqlite3VdbeMemRelease(&u.an.sMem);\n    u.an.sMem.flags = MEM_Null;\n\n    /* If we have read more header data than was contained in the header,\n    ** or if the end of the last field appears to be past the end of the\n    ** record, or if the end of the last field appears to be before the end\n    ** of the record (when all fields present), then we must be dealing\n    ** with a corrupt database.\n    */\n    if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)\n         || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){\n      rc = SQLITE_CORRUPT_BKPT;\n      goto op_column_out;\n    }\n  }\n\n  /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then\n  ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,\n  ** then there are not enough fields in the record to satisfy the\n  ** request.  In this case, set the value NULL or to P4 if P4 is\n  ** a pointer to a Mem object.\n  */\n  if( u.an.aOffset[u.an.p2] ){\n    assert( rc==SQLITE_OK );\n    if( u.an.zRec ){\n      /* This is the common case where the whole row fits on a single page */\n      VdbeMemRelease(u.an.pDest);\n      sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);\n    }else{\n      /* This branch happens only when the row overflows onto multiple pages */\n      u.an.t = u.an.aType[u.an.p2];\n      if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0\n       && ((u.an.t>=12 && (u.an.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)\n      ){\n        /* Content is irrelevant for the typeof() function and for\n        ** the length(X) function if X is a blob.  So we might as well use\n        ** bogus content rather than reading content from disk.  NULL works\n        ** for text and blob and whatever is in the u.an.payloadSize64 variable\n        ** will work for everything else. */\n        u.an.zData = u.an.t<12 ? (char*)&u.an.payloadSize64 : 0;\n      }else{\n        u.an.len = sqlite3VdbeSerialTypeLen(u.an.t);\n        sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);\n        rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len,  u.an.pC->isIndex,\n                                     &u.an.sMem);\n        if( rc!=SQLITE_OK ){\n          goto op_column_out;\n        }\n        u.an.zData = u.an.sMem.z;\n      }\n      sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.t, u.an.pDest);\n    }\n    u.an.pDest->enc = encoding;\n  }else{\n    if( pOp->p4type==P4_MEM ){\n      sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);\n    }else{\n      MemSetTypeFlag(u.an.pDest, MEM_Null);\n    }\n  }\n\n  /* If we dynamically allocated space to hold the data (in the\n  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that\n  ** dynamically allocated space over to the u.an.pDest structure.\n  ** This prevents a memory copy.\n  */\n  if( u.an.sMem.zMalloc ){\n    assert( u.an.sMem.z==u.an.sMem.zMalloc );\n    assert( !(u.an.pDest->flags & MEM_Dyn) );\n    assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );\n    u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);\n    u.an.pDest->flags |= MEM_Term;\n    u.an.pDest->z = u.an.sMem.z;\n    u.an.pDest->zMalloc = u.an.sMem.zMalloc;\n  }\n\n  rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);\n\nop_column_out:\n  UPDATE_MAX_BLOBSIZE(u.an.pDest);\n  REGISTER_TRACE(pOp->p3, u.an.pDest);\n  break;\n}\n\n/* Opcode: Affinity P1 P2 * P4 *\n**\n** Apply affinities to a range of P2 registers starting with P1.\n**\n** P4 is a string that is P2 characters long. The nth character of the\n** string indicates the column affinity that should be used for the nth\n** memory cell in the range.\n*/\ncase OP_Affinity: {\n#if 0  /* local variables moved into u.ao */\n  const char *zAffinity;   /* The affinity to be applied */\n  char cAff;               /* A single character of affinity */\n#endif /* local variables moved into u.ao */\n\n  u.ao.zAffinity = pOp->p4.z;\n  assert( u.ao.zAffinity!=0 );\n  assert( u.ao.zAffinity[pOp->p2]==0 );\n  pIn1 = &aMem[pOp->p1];\n  while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){\n    assert( pIn1 <= &p->aMem[p->nMem] );\n    assert( memIsValid(pIn1) );\n    ExpandBlob(pIn1);\n    applyAffinity(pIn1, u.ao.cAff, encoding);\n    pIn1++;\n  }\n  break;\n}\n\n/* Opcode: MakeRecord P1 P2 P3 P4 *\n**\n** Convert P2 registers beginning with P1 into the [record format]\n** use as a data record in a database table or as a key\n** in an index.  The OP_Column opcode can decode the record later.\n**\n** P4 may be a string that is P2 characters long.  The nth character of the\n** string indicates the column affinity that should be used for the nth\n** field of the index key.\n**\n** The mapping from character to affinity is given by the SQLITE_AFF_\n** macros defined in sqliteInt.h.\n**\n** If P4 is NULL then all index fields have the affinity NONE.\n*/\ncase OP_MakeRecord: {\n#if 0  /* local variables moved into u.ap */\n  u8 *zNewRecord;        /* A buffer to hold the data for the new record */\n  Mem *pRec;             /* The new record */\n  u64 nData;             /* Number of bytes of data space */\n  int nHdr;              /* Number of bytes of header space */\n  i64 nByte;             /* Data space required for this record */\n  int nZero;             /* Number of zero bytes at the end of the record */\n  int nVarint;           /* Number of bytes in a varint */\n  u32 serial_type;       /* Type field */\n  Mem *pData0;           /* First field to be combined into the record */\n  Mem *pLast;            /* Last field of the record */\n  int nField;            /* Number of fields in the record */\n  char *zAffinity;       /* The affinity string for the record */\n  int file_format;       /* File format to use for encoding */\n  int i;                 /* Space used in zNewRecord[] */\n  int len;               /* Length of a field */\n#endif /* local variables moved into u.ap */\n\n  /* Assuming the record contains N fields, the record format looks\n  ** like this:\n  **\n  ** ------------------------------------------------------------------------\n  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |\n  ** ------------------------------------------------------------------------\n  **\n  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1\n  ** and so froth.\n  **\n  ** Each type field is a varint representing the serial type of the\n  ** corresponding data element (see sqlite3VdbeSerialType()). The\n  ** hdr-size field is also a varint which is the offset from the beginning\n  ** of the record to data0.\n  */\n  u.ap.nData = 0;         /* Number of bytes of data space */\n  u.ap.nHdr = 0;          /* Number of bytes of header space */\n  u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */\n  u.ap.nField = pOp->p1;\n  u.ap.zAffinity = pOp->p4.z;\n  assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );\n  u.ap.pData0 = &aMem[u.ap.nField];\n  u.ap.nField = pOp->p2;\n  u.ap.pLast = &u.ap.pData0[u.ap.nField-1];\n  u.ap.file_format = p->minWriteFileFormat;\n\n  /* Identify the output register */\n  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );\n  pOut = &aMem[pOp->p3];\n  memAboutToChange(p, pOut);\n\n  /* Loop through the elements that will make up the record to figure\n  ** out how much space is required for the new record.\n  */\n  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){\n    assert( memIsValid(u.ap.pRec) );\n    if( u.ap.zAffinity ){\n      applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);\n    }\n    if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){\n      sqlite3VdbeMemExpandBlob(u.ap.pRec);\n    }\n    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);\n    u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);\n    u.ap.nData += u.ap.len;\n    u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);\n    if( u.ap.pRec->flags & MEM_Zero ){\n      /* Only pure zero-filled BLOBs can be input to this Opcode.\n      ** We do not allow blobs with a prefix and a zero-filled tail. */\n      u.ap.nZero += u.ap.pRec->u.nZero;\n    }else if( u.ap.len ){\n      u.ap.nZero = 0;\n    }\n  }\n\n  /* Add the initial header varint and total the size */\n  u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);\n  if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){\n    u.ap.nHdr++;\n  }\n  u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;\n  if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    goto too_big;\n  }\n\n  /* Make sure the output register has a buffer large enough to store\n  ** the new record. The output register (pOp->p3) is not allowed to\n  ** be one of the input registers (because the following call to\n  ** sqlite3VdbeMemGrow() could clobber the value before it is used).\n  */\n  if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){\n    goto no_mem;\n  }\n  u.ap.zNewRecord = (u8 *)pOut->z;\n\n  /* Write the record */\n  u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);\n  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){\n    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);\n    u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */\n  }\n  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */\n    u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);\n  }\n  assert( u.ap.i==u.ap.nByte );\n\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  pOut->n = (int)u.ap.nByte;\n  pOut->flags = MEM_Blob | MEM_Dyn;\n  pOut->xDel = 0;\n  if( u.ap.nZero ){\n    pOut->u.nZero = u.ap.nZero;\n    pOut->flags |= MEM_Zero;\n  }\n  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */\n  REGISTER_TRACE(pOp->p3, pOut);\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Count P1 P2 * * *\n**\n** Store the number of entries (an integer value) in the table or index \n** opened by cursor P1 in register P2\n*/\n#ifndef SQLITE_OMIT_BTREECOUNT\ncase OP_Count: {         /* out2-prerelease */\n#if 0  /* local variables moved into u.aq */\n  i64 nEntry;\n  BtCursor *pCrsr;\n#endif /* local variables moved into u.aq */\n\n  u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;\n  if( ALWAYS(u.aq.pCrsr) ){\n    rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);\n  }else{\n    u.aq.nEntry = 0;\n  }\n  pOut->u.i = u.aq.nEntry;\n  break;\n}\n#endif\n\n/* Opcode: Savepoint P1 * * P4 *\n**\n** Open, release or rollback the savepoint named by parameter P4, depending\n** on the value of P1. To open a new savepoint, P1==0. To release (commit) an\n** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.\n*/\ncase OP_Savepoint: {\n#if 0  /* local variables moved into u.ar */\n  int p1;                         /* Value of P1 operand */\n  char *zName;                    /* Name of savepoint */\n  int nName;\n  Savepoint *pNew;\n  Savepoint *pSavepoint;\n  Savepoint *pTmp;\n  int iSavepoint;\n  int ii;\n#endif /* local variables moved into u.ar */\n\n  u.ar.p1 = pOp->p1;\n  u.ar.zName = pOp->p4.z;\n\n  /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open\n  ** transaction, then there cannot be any savepoints.\n  */\n  assert( db->pSavepoint==0 || db->autoCommit==0 );\n  assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );\n  assert( db->pSavepoint || db->isTransactionSavepoint==0 );\n  assert( checkSavepointCount(db) );\n\n  if( u.ar.p1==SAVEPOINT_BEGIN ){\n    if( db->writeVdbeCnt>0 ){\n      /* A new savepoint cannot be created if there are active write\n      ** statements (i.e. open read/write incremental blob handles).\n      */\n      sqlite3SetString(&p->zErrMsg, db, \"cannot open savepoint - \"\n        \"SQL statements in progress\");\n      rc = SQLITE_BUSY;\n    }else{\n      u.ar.nName = sqlite3Strlen30(u.ar.zName);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      /* This call is Ok even if this savepoint is actually a transaction\n      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.\n      ** If this is a transaction savepoint being opened, it is guaranteed\n      ** that the db->aVTrans[] array is empty.  */\n      assert( db->autoCommit==0 || db->nVTrans==0 );\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,\n                                db->nStatement+db->nSavepoint);\n      if( rc!=SQLITE_OK ) goto abort_due_to_error;\n#endif\n\n      /* Create a new savepoint structure. */\n      u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);\n      if( u.ar.pNew ){\n        u.ar.pNew->zName = (char *)&u.ar.pNew[1];\n        memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);\n\n        /* If there is no open transaction, then mark this as a special\n        ** \"transaction savepoint\". */\n        if( db->autoCommit ){\n          db->autoCommit = 0;\n          db->isTransactionSavepoint = 1;\n        }else{\n          db->nSavepoint++;\n        }\n\n        /* Link the new savepoint into the database handle's list. */\n        u.ar.pNew->pNext = db->pSavepoint;\n        db->pSavepoint = u.ar.pNew;\n        u.ar.pNew->nDeferredCons = db->nDeferredCons;\n      }\n    }\n  }else{\n    u.ar.iSavepoint = 0;\n\n    /* Find the named savepoint. If there is no such savepoint, then an\n    ** an error is returned to the user.  */\n    for(\n      u.ar.pSavepoint = db->pSavepoint;\n      u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);\n      u.ar.pSavepoint = u.ar.pSavepoint->pNext\n    ){\n      u.ar.iSavepoint++;\n    }\n    if( !u.ar.pSavepoint ){\n      sqlite3SetString(&p->zErrMsg, db, \"no such savepoint: %s\", u.ar.zName);\n      rc = SQLITE_ERROR;\n    }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){\n      /* It is not possible to release (commit) a savepoint if there are\n      ** active write statements.\n      */\n      sqlite3SetString(&p->zErrMsg, db,\n        \"cannot release savepoint - SQL statements in progress\"\n      );\n      rc = SQLITE_BUSY;\n    }else{\n\n      /* Determine whether or not this is a transaction savepoint. If so,\n      ** and this is a RELEASE command, then the current transaction\n      ** is committed.\n      */\n      int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;\n      if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){\n        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){\n          goto vdbe_return;\n        }\n        db->autoCommit = 1;\n        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){\n          p->pc = pc;\n          db->autoCommit = 0;\n          p->rc = rc = SQLITE_BUSY;\n          goto vdbe_return;\n        }\n        db->isTransactionSavepoint = 0;\n        rc = p->rc;\n      }else{\n        u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;\n        if( u.ar.p1==SAVEPOINT_ROLLBACK ){\n          for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){\n            sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);\n          }\n        }\n        for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){\n          rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);\n          if( rc!=SQLITE_OK ){\n            goto abort_due_to_error;\n          }\n        }\n        if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){\n          sqlite3ExpirePreparedStatements(db);\n          sqlite3ResetAllSchemasOfConnection(db);\n          db->flags = (db->flags | SQLITE_InternChanges);\n        }\n      }\n\n      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all\n      ** savepoints nested inside of the savepoint being operated on. */\n      while( db->pSavepoint!=u.ar.pSavepoint ){\n        u.ar.pTmp = db->pSavepoint;\n        db->pSavepoint = u.ar.pTmp->pNext;\n        sqlite3DbFree(db, u.ar.pTmp);\n        db->nSavepoint--;\n      }\n\n      /* If it is a RELEASE, then destroy the savepoint being operated on\n      ** too. If it is a ROLLBACK TO, then set the number of deferred\n      ** constraint violations present in the database to the value stored\n      ** when the savepoint was created.  */\n      if( u.ar.p1==SAVEPOINT_RELEASE ){\n        assert( u.ar.pSavepoint==db->pSavepoint );\n        db->pSavepoint = u.ar.pSavepoint->pNext;\n        sqlite3DbFree(db, u.ar.pSavepoint);\n        if( !isTransaction ){\n          db->nSavepoint--;\n        }\n      }else{\n        db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;\n      }\n\n      if( !isTransaction ){\n        rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);\n        if( rc!=SQLITE_OK ) goto abort_due_to_error;\n      }\n    }\n  }\n\n  break;\n}\n\n/* Opcode: AutoCommit P1 P2 * * *\n**\n** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll\n** back any currently active btree transactions. If there are any active\n** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if\n** there are active writing VMs or active VMs that use shared cache.\n**\n** This instruction causes the VM to halt.\n*/\ncase OP_AutoCommit: {\n#if 0  /* local variables moved into u.as */\n  int desiredAutoCommit;\n  int iRollback;\n  int turnOnAC;\n#endif /* local variables moved into u.as */\n\n  u.as.desiredAutoCommit = pOp->p1;\n  u.as.iRollback = pOp->p2;\n  u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;\n  assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );\n  assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );\n  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */\n\n#if 0\n  if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){\n    /* If this instruction implements a ROLLBACK and other VMs are\n    ** still running, and a transaction is active, return an error indicating\n    ** that the other VMs must complete first.\n    */\n    sqlite3SetString(&p->zErrMsg, db, \"cannot rollback transaction - \"\n        \"SQL statements in progress\");\n    rc = SQLITE_BUSY;\n  }else\n#endif\n  if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){\n    /* If this instruction implements a COMMIT and other VMs are writing\n    ** return an error indicating that the other VMs must complete first.\n    */\n    sqlite3SetString(&p->zErrMsg, db, \"cannot commit transaction - \"\n        \"SQL statements in progress\");\n    rc = SQLITE_BUSY;\n  }else if( u.as.desiredAutoCommit!=db->autoCommit ){\n    if( u.as.iRollback ){\n      assert( u.as.desiredAutoCommit==1 );\n      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);\n      db->autoCommit = 1;\n    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){\n      goto vdbe_return;\n    }else{\n      db->autoCommit = (u8)u.as.desiredAutoCommit;\n      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){\n        p->pc = pc;\n        db->autoCommit = (u8)(1-u.as.desiredAutoCommit);\n        p->rc = rc = SQLITE_BUSY;\n        goto vdbe_return;\n      }\n    }\n    assert( db->nStatement==0 );\n    sqlite3CloseSavepoints(db);\n    if( p->rc==SQLITE_OK ){\n      rc = SQLITE_DONE;\n    }else{\n      rc = SQLITE_ERROR;\n    }\n    goto vdbe_return;\n  }else{\n    sqlite3SetString(&p->zErrMsg, db,\n        (!u.as.desiredAutoCommit)?\"cannot start a transaction within a transaction\":(\n        (u.as.iRollback)?\"cannot rollback - no transaction is active\":\n                   \"cannot commit - no transaction is active\"));\n\n    rc = SQLITE_ERROR;\n  }\n  break;\n}\n\n/* Opcode: Transaction P1 P2 * * *\n**\n** Begin a transaction.  The transaction ends when a Commit or Rollback\n** opcode is encountered.  Depending on the ON CONFLICT setting, the\n** transaction might also be rolled back if an error is encountered.\n**\n** P1 is the index of the database file on which the transaction is\n** started.  Index 0 is the main database file and index 1 is the\n** file used for temporary tables.  Indices of 2 or more are used for\n** attached databases.\n**\n** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is\n** obtained on the database file when a write-transaction is started.  No\n** other process can start another write transaction while this transaction is\n** underway.  Starting a write transaction also creates a rollback journal. A\n** write transaction must be started before any changes can be made to the\n** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained\n** on the file.\n**\n** If a write-transaction is started and the Vdbe.usesStmtJournal flag is\n** true (this flag is set if the Vdbe may modify more than one row and may\n** throw an ABORT exception), a statement transaction may also be opened.\n** More specifically, a statement transaction is opened iff the database\n** connection is currently not in autocommit mode, or if there are other\n** active statements. A statement transaction allows the changes made by this\n** VDBE to be rolled back after an error without having to roll back the\n** entire transaction. If no error is encountered, the statement transaction\n** will automatically commit when the VDBE halts.\n**\n** If P2 is zero, then a read-lock is obtained on the database file.\n*/\ncase OP_Transaction: {\n#if 0  /* local variables moved into u.at */\n  Btree *pBt;\n#endif /* local variables moved into u.at */\n\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );\n  u.at.pBt = db->aDb[pOp->p1].pBt;\n\n  if( u.at.pBt ){\n    rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);\n    if( rc==SQLITE_BUSY ){\n      p->pc = pc;\n      p->rc = rc = SQLITE_BUSY;\n      goto vdbe_return;\n    }\n    if( rc!=SQLITE_OK ){\n      goto abort_due_to_error;\n    }\n\n    if( pOp->p2 && p->usesStmtJournal\n     && (db->autoCommit==0 || db->activeVdbeCnt>1)\n    ){\n      assert( sqlite3BtreeIsInTrans(u.at.pBt) );\n      if( p->iStatement==0 ){\n        assert( db->nStatement>=0 && db->nSavepoint>=0 );\n        db->nStatement++;\n        p->iStatement = db->nSavepoint + db->nStatement;\n      }\n\n      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);\n      }\n\n      /* Store the current value of the database handles deferred constraint\n      ** counter. If the statement transaction needs to be rolled back,\n      ** the value of this counter needs to be restored too.  */\n      p->nStmtDefCons = db->nDeferredCons;\n    }\n  }\n  break;\n}\n\n/* Opcode: ReadCookie P1 P2 P3 * *\n**\n** Read cookie number P3 from database P1 and write it into register P2.\n** P3==1 is the schema version.  P3==2 is the database format.\n** P3==3 is the recommended pager cache size, and so forth.  P1==0 is\n** the main database file and P1==1 is the database file used to store\n** temporary tables.\n**\n** There must be a read-lock on the database (either a transaction\n** must be started or there must be an open cursor) before\n** executing this instruction.\n*/\ncase OP_ReadCookie: {               /* out2-prerelease */\n#if 0  /* local variables moved into u.au */\n  int iMeta;\n  int iDb;\n  int iCookie;\n#endif /* local variables moved into u.au */\n\n  u.au.iDb = pOp->p1;\n  u.au.iCookie = pOp->p3;\n  assert( pOp->p3<SQLITE_N_BTREE_META );\n  assert( u.au.iDb>=0 && u.au.iDb<db->nDb );\n  assert( db->aDb[u.au.iDb].pBt!=0 );\n  assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );\n\n  sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);\n  pOut->u.i = u.au.iMeta;\n  break;\n}\n\n/* Opcode: SetCookie P1 P2 P3 * *\n**\n** Write the content of register P3 (interpreted as an integer)\n** into cookie number P2 of database P1.  P2==1 is the schema version.  \n** P2==2 is the database format. P2==3 is the recommended pager cache \n** size, and so forth.  P1==0 is the main database file and P1==1 is the \n** database file used to store temporary tables.\n**\n** A transaction must be started before executing this opcode.\n*/\ncase OP_SetCookie: {       /* in3 */\n#if 0  /* local variables moved into u.av */\n  Db *pDb;\n#endif /* local variables moved into u.av */\n  assert( pOp->p2<SQLITE_N_BTREE_META );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );\n  u.av.pDb = &db->aDb[pOp->p1];\n  assert( u.av.pDb->pBt!=0 );\n  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );\n  pIn3 = &aMem[pOp->p3];\n  sqlite3VdbeMemIntegerify(pIn3);\n  /* See note about index shifting on OP_ReadCookie */\n  rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);\n  if( pOp->p2==BTREE_SCHEMA_VERSION ){\n    /* When the schema cookie changes, record the new cookie internally */\n    u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;\n    db->flags |= SQLITE_InternChanges;\n  }else if( pOp->p2==BTREE_FILE_FORMAT ){\n    /* Record changes in the file format */\n    u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;\n  }\n  if( pOp->p1==1 ){\n    /* Invalidate all prepared statements whenever the TEMP database\n    ** schema is changed.  Ticket #1644 */\n    sqlite3ExpirePreparedStatements(db);\n    p->expired = 0;\n  }\n  break;\n}\n\n/* Opcode: VerifyCookie P1 P2 P3 * *\n**\n** Check the value of global database parameter number 0 (the\n** schema version) and make sure it is equal to P2 and that the\n** generation counter on the local schema parse equals P3.\n**\n** P1 is the database number which is 0 for the main database file\n** and 1 for the file holding temporary tables and some higher number\n** for auxiliary databases.\n**\n** The cookie changes its value whenever the database schema changes.\n** This operation is used to detect when that the cookie has changed\n** and that the current process needs to reread the schema.\n**\n** Either a transaction needs to have been started or an OP_Open needs\n** to be executed (to establish a read lock) before this opcode is\n** invoked.\n*/\ncase OP_VerifyCookie: {\n#if 0  /* local variables moved into u.aw */\n  int iMeta;\n  int iGen;\n  Btree *pBt;\n#endif /* local variables moved into u.aw */\n\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );\n  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );\n  u.aw.pBt = db->aDb[pOp->p1].pBt;\n  if( u.aw.pBt ){\n    sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);\n    u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;\n  }else{\n    u.aw.iGen = u.aw.iMeta = 0;\n  }\n  if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){\n    sqlite3DbFree(db, p->zErrMsg);\n    p->zErrMsg = sqlite3DbStrDup(db, \"database schema has changed\");\n    /* If the schema-cookie from the database file matches the cookie\n    ** stored with the in-memory representation of the schema, do\n    ** not reload the schema from the database file.\n    **\n    ** If virtual-tables are in use, this is not just an optimization.\n    ** Often, v-tables store their data in other SQLite tables, which\n    ** are queried from within xNext() and other v-table methods using\n    ** prepared queries. If such a query is out-of-date, we do not want to\n    ** discard the database schema, as the user code implementing the\n    ** v-table would have to be ready for the sqlite3_vtab structure itself\n    ** to be invalidated whenever sqlite3_step() is called from within\n    ** a v-table method.\n    */\n    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){\n      sqlite3ResetOneSchema(db, pOp->p1);\n    }\n\n    p->expired = 1;\n    rc = SQLITE_SCHEMA;\n  }\n  break;\n}\n\n/* Opcode: OpenRead P1 P2 P3 P4 P5\n**\n** Open a read-only cursor for the database table whose root page is\n** P2 in a database file.  The database file is determined by P3. \n** P3==0 means the main database, P3==1 means the database used for \n** temporary tables, and P3>1 means used the corresponding attached\n** database.  Give the new cursor an identifier of P1.  The P1\n** values need not be contiguous but all P1 values should be small integers.\n** It is an error for P1 to be negative.\n**\n** If P5!=0 then use the content of register P2 as the root page, not\n** the value of P2 itself.\n**\n** There will be a read lock on the database whenever there is an\n** open cursor.  If the database was unlocked prior to this instruction\n** then a read lock is acquired as part of this instruction.  A read\n** lock allows other processes to read the database but prohibits\n** any other process from modifying the database.  The read lock is\n** released when all cursors are closed.  If this instruction attempts\n** to get a read lock but fails, the script terminates with an\n** SQLITE_BUSY error code.\n**\n** The P4 value may be either an integer (P4_INT32) or a pointer to\n** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo \n** structure, then said structure defines the content and collating \n** sequence of the index being opened. Otherwise, if P4 is an integer \n** value, it is set to the number of columns in the table.\n**\n** See also OpenWrite.\n*/\n/* Opcode: OpenWrite P1 P2 P3 P4 P5\n**\n** Open a read/write cursor named P1 on the table or index whose root\n** page is P2.  Or if P5!=0 use the content of register P2 to find the\n** root page.\n**\n** The P4 value may be either an integer (P4_INT32) or a pointer to\n** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo \n** structure, then said structure defines the content and collating \n** sequence of the index being opened. Otherwise, if P4 is an integer \n** value, it is set to the number of columns in the table, or to the\n** largest index of any column of the table that is actually used.\n**\n** This instruction works just like OpenRead except that it opens the cursor\n** in read/write mode.  For a given table, there can be one or more read-only\n** cursors or a single read/write cursor but not both.\n**\n** See also OpenRead.\n*/\ncase OP_OpenRead:\ncase OP_OpenWrite: {\n#if 0  /* local variables moved into u.ax */\n  int nField;\n  KeyInfo *pKeyInfo;\n  int p2;\n  int iDb;\n  int wrFlag;\n  Btree *pX;\n  VdbeCursor *pCur;\n  Db *pDb;\n#endif /* local variables moved into u.ax */\n\n  assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );\n  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );\n\n  if( p->expired ){\n    rc = SQLITE_ABORT;\n    break;\n  }\n\n  u.ax.nField = 0;\n  u.ax.pKeyInfo = 0;\n  u.ax.p2 = pOp->p2;\n  u.ax.iDb = pOp->p3;\n  assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );\n  u.ax.pDb = &db->aDb[u.ax.iDb];\n  u.ax.pX = u.ax.pDb->pBt;\n  assert( u.ax.pX!=0 );\n  if( pOp->opcode==OP_OpenWrite ){\n    u.ax.wrFlag = 1;\n    assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );\n    if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){\n      p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;\n    }\n  }else{\n    u.ax.wrFlag = 0;\n  }\n  if( pOp->p5 & OPFLAG_P2ISREG ){\n    assert( u.ax.p2>0 );\n    assert( u.ax.p2<=p->nMem );\n    pIn2 = &aMem[u.ax.p2];\n    assert( memIsValid(pIn2) );\n    assert( (pIn2->flags & MEM_Int)!=0 );\n    sqlite3VdbeMemIntegerify(pIn2);\n    u.ax.p2 = (int)pIn2->u.i;\n    /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and\n    ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.\n    ** If there were a failure, the prepared statement would have halted\n    ** before reaching this instruction. */\n    if( NEVER(u.ax.p2<2) ) {\n      rc = SQLITE_CORRUPT_BKPT;\n      goto abort_due_to_error;\n    }\n  }\n  if( pOp->p4type==P4_KEYINFO ){\n    u.ax.pKeyInfo = pOp->p4.pKeyInfo;\n    u.ax.pKeyInfo->enc = ENC(p->db);\n    u.ax.nField = u.ax.pKeyInfo->nField+1;\n  }else if( pOp->p4type==P4_INT32 ){\n    u.ax.nField = pOp->p4.i;\n  }\n  assert( pOp->p1>=0 );\n  u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);\n  if( u.ax.pCur==0 ) goto no_mem;\n  u.ax.pCur->nullRow = 1;\n  u.ax.pCur->isOrdered = 1;\n  rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);\n  u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;\n  assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );\n  sqlite3BtreeCursorHints(u.ax.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));\n\n  /* Since it performs no memory allocation or IO, the only value that\n  ** sqlite3BtreeCursor() may return is SQLITE_OK. */\n  assert( rc==SQLITE_OK );\n\n  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of\n  ** SQLite used to check if the root-page flags were sane at this point\n  ** and report database corruption if they were not, but this check has\n  ** since moved into the btree layer.  */\n  u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;\n  u.ax.pCur->isIndex = !u.ax.pCur->isTable;\n  break;\n}\n\n/* Opcode: OpenEphemeral P1 P2 * P4 P5\n**\n** Open a new cursor P1 to a transient table.\n** The cursor is always opened read/write even if \n** the main database is read-only.  The ephemeral\n** table is deleted automatically when the cursor is closed.\n**\n** P2 is the number of columns in the ephemeral table.\n** The cursor points to a BTree table if P4==0 and to a BTree index\n** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure\n** that defines the format of keys in the index.\n**\n** This opcode was once called OpenTemp.  But that created\n** confusion because the term \"temp table\", might refer either\n** to a TEMP table at the SQL level, or to a table opened by\n** this opcode.  Then this opcode was call OpenVirtual.  But\n** that created confusion with the whole virtual-table idea.\n**\n** The P5 parameter can be a mask of the BTREE_* flags defined\n** in btree.h.  These flags control aspects of the operation of\n** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are\n** added automatically.\n*/\n/* Opcode: OpenAutoindex P1 P2 * P4 *\n**\n** This opcode works the same as OP_OpenEphemeral.  It has a\n** different name to distinguish its use.  Tables created using\n** by this opcode will be used for automatically created transient\n** indices in joins.\n*/\ncase OP_OpenAutoindex: \ncase OP_OpenEphemeral: {\n#if 0  /* local variables moved into u.ay */\n  VdbeCursor *pCx;\n#endif /* local variables moved into u.ay */\n  static const int vfsFlags =\n      SQLITE_OPEN_READWRITE |\n      SQLITE_OPEN_CREATE |\n      SQLITE_OPEN_EXCLUSIVE |\n      SQLITE_OPEN_DELETEONCLOSE |\n      SQLITE_OPEN_TRANSIENT_DB;\n\n  assert( pOp->p1>=0 );\n  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);\n  if( u.ay.pCx==0 ) goto no_mem;\n  u.ay.pCx->nullRow = 1;\n  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,\n                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);\n  }\n  if( rc==SQLITE_OK ){\n    /* If a transient index is required, create it by calling\n    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before\n    ** opening it. If a transient table is required, just use the\n    ** automatically created table with root-page 1 (an BLOB_INTKEY table).\n    */\n    if( pOp->p4.pKeyInfo ){\n      int pgno;\n      assert( pOp->p4type==P4_KEYINFO );\n      rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);\n      if( rc==SQLITE_OK ){\n        assert( pgno==MASTER_ROOT+1 );\n        rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,\n                                (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);\n        u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;\n        u.ay.pCx->pKeyInfo->enc = ENC(p->db);\n      }\n      u.ay.pCx->isTable = 0;\n    }else{\n      rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);\n      u.ay.pCx->isTable = 1;\n    }\n  }\n  u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);\n  u.ay.pCx->isIndex = !u.ay.pCx->isTable;\n  break;\n}\n\n/* Opcode: OpenSorter P1 P2 * P4 *\n**\n** This opcode works like OP_OpenEphemeral except that it opens\n** a transient index that is specifically designed to sort large\n** tables using an external merge-sort algorithm.\n*/\ncase OP_SorterOpen: {\n#if 0  /* local variables moved into u.az */\n  VdbeCursor *pCx;\n#endif /* local variables moved into u.az */\n#ifndef SQLITE_OMIT_MERGE_SORT\n  u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);\n  if( u.az.pCx==0 ) goto no_mem;\n  u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;\n  u.az.pCx->pKeyInfo->enc = ENC(p->db);\n  u.az.pCx->isSorter = 1;\n  rc = sqlite3VdbeSorterInit(db, u.az.pCx);\n#else\n  pOp->opcode = OP_OpenEphemeral;\n  pc--;\n#endif\n  break;\n}\n\n/* Opcode: OpenPseudo P1 P2 P3 * *\n**\n** Open a new cursor that points to a fake table that contains a single\n** row of data.  The content of that one row in the content of memory\n** register P2.  In other words, cursor P1 becomes an alias for the \n** MEM_Blob content contained in register P2.\n**\n** A pseudo-table created by this opcode is used to hold a single\n** row output from the sorter so that the row can be decomposed into\n** individual columns using the OP_Column opcode.  The OP_Column opcode\n** is the only cursor opcode that works with a pseudo-table.\n**\n** P3 is the number of fields in the records that will be stored by\n** the pseudo-table.\n*/\ncase OP_OpenPseudo: {\n#if 0  /* local variables moved into u.ba */\n  VdbeCursor *pCx;\n#endif /* local variables moved into u.ba */\n\n  assert( pOp->p1>=0 );\n  u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);\n  if( u.ba.pCx==0 ) goto no_mem;\n  u.ba.pCx->nullRow = 1;\n  u.ba.pCx->pseudoTableReg = pOp->p2;\n  u.ba.pCx->isTable = 1;\n  u.ba.pCx->isIndex = 0;\n  break;\n}\n\n/* Opcode: Close P1 * * * *\n**\n** Close a cursor previously opened as P1.  If P1 is not\n** currently open, this instruction is a no-op.\n*/\ncase OP_Close: {\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);\n  p->apCsr[pOp->p1] = 0;\n  break;\n}\n\n/* Opcode: SeekGe P1 P2 P3 P4 *\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as the key.  If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that  it points to the smallest entry that \n** is greater than or equal to the key value. If there are no records \n** greater than or equal to the key and P2 is not zero, then jump to P2.\n**\n** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe\n*/\n/* Opcode: SeekGt P1 P2 P3 P4 *\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that  it points to the smallest entry that \n** is greater than the key value. If there are no records greater than \n** the key and P2 is not zero, then jump to P2.\n**\n** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe\n*/\n/* Opcode: SeekLt P1 P2 P3 P4 * \n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that  it points to the largest entry that \n** is less than the key value. If there are no records less than \n** the key and P2 is not zero, then jump to P2.\n**\n** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe\n*/\n/* Opcode: SeekLe P1 P2 P3 P4 *\n**\n** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), \n** use the value in register P3 as a key. If cursor P1 refers \n** to an SQL index, then P3 is the first in an array of P4 registers \n** that are used as an unpacked index key. \n**\n** Reposition cursor P1 so that it points to the largest entry that \n** is less than or equal to the key value. If there are no records \n** less than or equal to the key and P2 is not zero, then jump to P2.\n**\n** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt\n*/\ncase OP_SeekLt:         /* jump, in3 */\ncase OP_SeekLe:         /* jump, in3 */\ncase OP_SeekGe:         /* jump, in3 */\ncase OP_SeekGt: {       /* jump, in3 */\n#if 0  /* local variables moved into u.bb */\n  int res;\n  int oc;\n  VdbeCursor *pC;\n  UnpackedRecord r;\n  int nField;\n  i64 iKey;      /* The rowid we are to seek to */\n#endif /* local variables moved into u.bb */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p2!=0 );\n  u.bb.pC = p->apCsr[pOp->p1];\n  assert( u.bb.pC!=0 );\n  assert( u.bb.pC->pseudoTableReg==0 );\n  assert( OP_SeekLe == OP_SeekLt+1 );\n  assert( OP_SeekGe == OP_SeekLt+2 );\n  assert( OP_SeekGt == OP_SeekLt+3 );\n  assert( u.bb.pC->isOrdered );\n  if( ALWAYS(u.bb.pC->pCursor!=0) ){\n    u.bb.oc = pOp->opcode;\n    u.bb.pC->nullRow = 0;\n    if( u.bb.pC->isTable ){\n      /* The input value in P3 might be of any type: integer, real, string,\n      ** blob, or NULL.  But it needs to be an integer before we can do\n      ** the seek, so covert it. */\n      pIn3 = &aMem[pOp->p3];\n      applyNumericAffinity(pIn3);\n      u.bb.iKey = sqlite3VdbeIntValue(pIn3);\n      u.bb.pC->rowidIsValid = 0;\n\n      /* If the P3 value could not be converted into an integer without\n      ** loss of information, then special processing is required... */\n      if( (pIn3->flags & MEM_Int)==0 ){\n        if( (pIn3->flags & MEM_Real)==0 ){\n          /* If the P3 value cannot be converted into any kind of a number,\n          ** then the seek is not possible, so jump to P2 */\n          pc = pOp->p2 - 1;\n          break;\n        }\n        /* If we reach this point, then the P3 value must be a floating\n        ** point number. */\n        assert( (pIn3->flags & MEM_Real)!=0 );\n\n        if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){\n          /* The P3 value is too large in magnitude to be expressed as an\n          ** integer. */\n          u.bb.res = 1;\n          if( pIn3->r<0 ){\n            if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );\n              rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);\n              if( rc!=SQLITE_OK ) goto abort_due_to_error;\n            }\n          }else{\n            if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );\n              rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);\n              if( rc!=SQLITE_OK ) goto abort_due_to_error;\n            }\n          }\n          if( u.bb.res ){\n            pc = pOp->p2 - 1;\n          }\n          break;\n        }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){\n          /* Use the ceiling() function to convert real->int */\n          if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;\n        }else{\n          /* Use the floor() function to convert real->int */\n          assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );\n          if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;\n        }\n      }\n      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);\n      if( rc!=SQLITE_OK ){\n        goto abort_due_to_error;\n      }\n      if( u.bb.res==0 ){\n        u.bb.pC->rowidIsValid = 1;\n        u.bb.pC->lastRowid = u.bb.iKey;\n      }\n    }else{\n      u.bb.nField = pOp->p4.i;\n      assert( pOp->p4type==P4_INT32 );\n      assert( u.bb.nField>0 );\n      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;\n      u.bb.r.nField = (u16)u.bb.nField;\n\n      /* The next line of code computes as follows, only faster:\n      **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){\n      **     u.bb.r.flags = UNPACKED_INCRKEY;\n      **   }else{\n      **     u.bb.r.flags = 0;\n      **   }\n      */\n      u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));\n      assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );\n      assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );\n      assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );\n      assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );\n\n      u.bb.r.aMem = &aMem[pOp->p3];\n#ifdef SQLITE_DEBUG\n      { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }\n#endif\n      ExpandBlob(u.bb.r.aMem);\n      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);\n      if( rc!=SQLITE_OK ){\n        goto abort_due_to_error;\n      }\n      u.bb.pC->rowidIsValid = 0;\n    }\n    u.bb.pC->deferredMoveto = 0;\n    u.bb.pC->cacheStatus = CACHE_STALE;\n#ifdef SQLITE_TEST\n    sqlite3_search_count++;\n#endif\n    if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );\n      if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){\n        rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);\n        if( rc!=SQLITE_OK ) goto abort_due_to_error;\n        u.bb.pC->rowidIsValid = 0;\n      }else{\n        u.bb.res = 0;\n      }\n    }else{\n      assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );\n      if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){\n        rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);\n        if( rc!=SQLITE_OK ) goto abort_due_to_error;\n        u.bb.pC->rowidIsValid = 0;\n      }else{\n        /* u.bb.res might be negative because the table is empty.  Check to\n        ** see if this is the case.\n        */\n        u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);\n      }\n    }\n    assert( pOp->p2>0 );\n    if( u.bb.res ){\n      pc = pOp->p2 - 1;\n    }\n  }else{\n    /* This happens when attempting to open the sqlite3_master table\n    ** for read access returns SQLITE_EMPTY. In this case always\n    ** take the jump (since there are no records in the table).\n    */\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: Seek P1 P2 * * *\n**\n** P1 is an open table cursor and P2 is a rowid integer.  Arrange\n** for P1 to move so that it points to the rowid given by P2.\n**\n** This is actually a deferred seek.  Nothing actually happens until\n** the cursor is used to read a record.  That way, if no reads\n** occur, no unnecessary I/O happens.\n*/\ncase OP_Seek: {    /* in2 */\n#if 0  /* local variables moved into u.bc */\n  VdbeCursor *pC;\n#endif /* local variables moved into u.bc */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bc.pC = p->apCsr[pOp->p1];\n  assert( u.bc.pC!=0 );\n  if( ALWAYS(u.bc.pC->pCursor!=0) ){\n    assert( u.bc.pC->isTable );\n    u.bc.pC->nullRow = 0;\n    pIn2 = &aMem[pOp->p2];\n    u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);\n    u.bc.pC->rowidIsValid = 0;\n    u.bc.pC->deferredMoveto = 1;\n  }\n  break;\n}\n  \n\n/* Opcode: Found P1 P2 P3 P4 *\n**\n** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If\n** P4>0 then register P3 is the first of P4 registers that form an unpacked\n** record.\n**\n** Cursor P1 is on an index btree.  If the record identified by P3 and P4\n** is a prefix of any entry in P1 then a jump is made to P2 and\n** P1 is left pointing at the matching entry.\n*/\n/* Opcode: NotFound P1 P2 P3 P4 *\n**\n** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If\n** P4>0 then register P3 is the first of P4 registers that form an unpacked\n** record.\n** \n** Cursor P1 is on an index btree.  If the record identified by P3 and P4\n** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 \n** does contain an entry whose prefix matches the P3/P4 record then control\n** falls through to the next instruction and P1 is left pointing at the\n** matching entry.\n**\n** See also: Found, NotExists, IsUnique\n*/\ncase OP_NotFound:       /* jump, in3 */\ncase OP_Found: {        /* jump, in3 */\n#if 0  /* local variables moved into u.bd */\n  int alreadyExists;\n  VdbeCursor *pC;\n  int res;\n  char *pFree;\n  UnpackedRecord *pIdxKey;\n  UnpackedRecord r;\n  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];\n#endif /* local variables moved into u.bd */\n\n#ifdef SQLITE_TEST\n  sqlite3_found_count++;\n#endif\n\n  u.bd.alreadyExists = 0;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p4type==P4_INT32 );\n  u.bd.pC = p->apCsr[pOp->p1];\n  assert( u.bd.pC!=0 );\n  pIn3 = &aMem[pOp->p3];\n  if( ALWAYS(u.bd.pC->pCursor!=0) ){\n\n    assert( u.bd.pC->isTable==0 );\n    if( pOp->p4.i>0 ){\n      u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;\n      u.bd.r.nField = (u16)pOp->p4.i;\n      u.bd.r.aMem = pIn3;\n#ifdef SQLITE_DEBUG\n      { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }\n#endif\n      u.bd.r.flags = UNPACKED_PREFIX_MATCH;\n      u.bd.pIdxKey = &u.bd.r;\n    }else{\n      u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(\n          u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree\n      );\n      if( u.bd.pIdxKey==0 ) goto no_mem;\n      assert( pIn3->flags & MEM_Blob );\n      assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */\n      sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);\n      u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;\n    }\n    rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);\n    if( pOp->p4.i==0 ){\n      sqlite3DbFree(db, u.bd.pFree);\n    }\n    if( rc!=SQLITE_OK ){\n      break;\n    }\n    u.bd.alreadyExists = (u.bd.res==0);\n    u.bd.pC->deferredMoveto = 0;\n    u.bd.pC->cacheStatus = CACHE_STALE;\n  }\n  if( pOp->opcode==OP_Found ){\n    if( u.bd.alreadyExists ) pc = pOp->p2 - 1;\n  }else{\n    if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: IsUnique P1 P2 P3 P4 *\n**\n** Cursor P1 is open on an index b-tree - that is to say, a btree which\n** no data and where the key are records generated by OP_MakeRecord with\n** the list field being the integer ROWID of the entry that the index\n** entry refers to.\n**\n** The P3 register contains an integer record number. Call this record \n** number R. Register P4 is the first in a set of N contiguous registers\n** that make up an unpacked index key that can be used with cursor P1.\n** The value of N can be inferred from the cursor. N includes the rowid\n** value appended to the end of the index record. This rowid value may\n** or may not be the same as R.\n**\n** If any of the N registers beginning with register P4 contains a NULL\n** value, jump immediately to P2.\n**\n** Otherwise, this instruction checks if cursor P1 contains an entry\n** where the first (N-1) fields match but the rowid value at the end\n** of the index entry is not R. If there is no such entry, control jumps\n** to instruction P2. Otherwise, the rowid of the conflicting index\n** entry is copied to register P3 and control falls through to the next\n** instruction.\n**\n** See also: NotFound, NotExists, Found\n*/\ncase OP_IsUnique: {        /* jump, in3 */\n#if 0  /* local variables moved into u.be */\n  u16 ii;\n  VdbeCursor *pCx;\n  BtCursor *pCrsr;\n  u16 nField;\n  Mem *aMx;\n  UnpackedRecord r;                  /* B-Tree index search key */\n  i64 R;                             /* Rowid stored in register P3 */\n#endif /* local variables moved into u.be */\n\n  pIn3 = &aMem[pOp->p3];\n  u.be.aMx = &aMem[pOp->p4.i];\n  /* Assert that the values of parameters P1 and P4 are in range. */\n  assert( pOp->p4type==P4_INT32 );\n  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n\n  /* Find the index cursor. */\n  u.be.pCx = p->apCsr[pOp->p1];\n  assert( u.be.pCx->deferredMoveto==0 );\n  u.be.pCx->seekResult = 0;\n  u.be.pCx->cacheStatus = CACHE_STALE;\n  u.be.pCrsr = u.be.pCx->pCursor;\n\n  /* If any of the values are NULL, take the jump. */\n  u.be.nField = u.be.pCx->pKeyInfo->nField;\n  for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){\n    if( u.be.aMx[u.be.ii].flags & MEM_Null ){\n      pc = pOp->p2 - 1;\n      u.be.pCrsr = 0;\n      break;\n    }\n  }\n  assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );\n\n  if( u.be.pCrsr!=0 ){\n    /* Populate the index search key. */\n    u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;\n    u.be.r.nField = u.be.nField + 1;\n    u.be.r.flags = UNPACKED_PREFIX_SEARCH;\n    u.be.r.aMem = u.be.aMx;\n#ifdef SQLITE_DEBUG\n    { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }\n#endif\n\n    /* Extract the value of u.be.R from register P3. */\n    sqlite3VdbeMemIntegerify(pIn3);\n    u.be.R = pIn3->u.i;\n\n    /* Search the B-Tree index. If no conflicting record is found, jump\n    ** to P2. Otherwise, copy the rowid of the conflicting record to\n    ** register P3 and fall through to the next instruction.  */\n    rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);\n    if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){\n      pc = pOp->p2 - 1;\n    }else{\n      pIn3->u.i = u.be.r.rowid;\n    }\n  }\n  break;\n}\n\n/* Opcode: NotExists P1 P2 P3 * *\n**\n** Use the content of register P3 as an integer key.  If a record \n** with that key does not exist in table of P1, then jump to P2. \n** If the record does exist, then fall through.  The cursor is left \n** pointing to the record if it exists.\n**\n** The difference between this operation and NotFound is that this\n** operation assumes the key is an integer and that P1 is a table whereas\n** NotFound assumes key is a blob constructed from MakeRecord and\n** P1 is an index.\n**\n** See also: Found, NotFound, IsUnique\n*/\ncase OP_NotExists: {        /* jump, in3 */\n#if 0  /* local variables moved into u.bf */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n  u64 iKey;\n#endif /* local variables moved into u.bf */\n\n  pIn3 = &aMem[pOp->p3];\n  assert( pIn3->flags & MEM_Int );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bf.pC = p->apCsr[pOp->p1];\n  assert( u.bf.pC!=0 );\n  assert( u.bf.pC->isTable );\n  assert( u.bf.pC->pseudoTableReg==0 );\n  u.bf.pCrsr = u.bf.pC->pCursor;\n  if( ALWAYS(u.bf.pCrsr!=0) ){\n    u.bf.res = 0;\n    u.bf.iKey = pIn3->u.i;\n    rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);\n    u.bf.pC->lastRowid = pIn3->u.i;\n    u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;\n    u.bf.pC->nullRow = 0;\n    u.bf.pC->cacheStatus = CACHE_STALE;\n    u.bf.pC->deferredMoveto = 0;\n    if( u.bf.res!=0 ){\n      pc = pOp->p2 - 1;\n      assert( u.bf.pC->rowidIsValid==0 );\n    }\n    u.bf.pC->seekResult = u.bf.res;\n  }else{\n    /* This happens when an attempt to open a read cursor on the\n    ** sqlite_master table returns SQLITE_EMPTY.\n    */\n    pc = pOp->p2 - 1;\n    assert( u.bf.pC->rowidIsValid==0 );\n    u.bf.pC->seekResult = 0;\n  }\n  break;\n}\n\n/* Opcode: Sequence P1 P2 * * *\n**\n** Find the next available sequence number for cursor P1.\n** Write the sequence number into register P2.\n** The sequence number on the cursor is incremented after this\n** instruction.  \n*/\ncase OP_Sequence: {           /* out2-prerelease */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( p->apCsr[pOp->p1]!=0 );\n  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;\n  break;\n}\n\n\n/* Opcode: NewRowid P1 P2 P3 * *\n**\n** Get a new integer record number (a.k.a \"rowid\") used as the key to a table.\n** The record number is not previously used as a key in the database\n** table that cursor P1 points to.  The new record number is written\n** written to register P2.\n**\n** If P3>0 then P3 is a register in the root frame of this VDBE that holds \n** the largest previously generated record number. No new record numbers are\n** allowed to be less than this value. When this value reaches its maximum, \n** an SQLITE_FULL error is generated. The P3 register is updated with the '\n** generated record number. This P3 mechanism is used to help implement the\n** AUTOINCREMENT feature.\n*/\ncase OP_NewRowid: {           /* out2-prerelease */\n#if 0  /* local variables moved into u.bg */\n  i64 v;                 /* The new rowid */\n  VdbeCursor *pC;        /* Cursor of table to get the new rowid */\n  int res;               /* Result of an sqlite3BtreeLast() */\n  int cnt;               /* Counter to limit the number of searches */\n  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */\n  VdbeFrame *pFrame;     /* Root frame of VDBE */\n#endif /* local variables moved into u.bg */\n\n  u.bg.v = 0;\n  u.bg.res = 0;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bg.pC = p->apCsr[pOp->p1];\n  assert( u.bg.pC!=0 );\n  if( NEVER(u.bg.pC->pCursor==0) ){\n    /* The zero initialization above is all that is needed */\n  }else{\n    /* The next rowid or record number (different terms for the same\n    ** thing) is obtained in a two-step algorithm.\n    **\n    ** First we attempt to find the largest existing rowid and add one\n    ** to that.  But if the largest existing rowid is already the maximum\n    ** positive integer, we have to fall through to the second\n    ** probabilistic algorithm\n    **\n    ** The second algorithm is to select a rowid at random and see if\n    ** it already exists in the table.  If it does not exist, we have\n    ** succeeded.  If the random rowid does exist, we select a new one\n    ** and try again, up to 100 times.\n    */\n    assert( u.bg.pC->isTable );\n\n#ifdef SQLITE_32BIT_ROWID\n#   define MAX_ROWID 0x7fffffff\n#else\n    /* Some compilers complain about constants of the form 0x7fffffffffffffff.\n    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems\n    ** to provide the constant while making all compilers happy.\n    */\n#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )\n#endif\n\n    if( !u.bg.pC->useRandomRowid ){\n      u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);\n      if( u.bg.v==0 ){\n        rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);\n        if( rc!=SQLITE_OK ){\n          goto abort_due_to_error;\n        }\n        if( u.bg.res ){\n          u.bg.v = 1;   /* IMP: R-61914-48074 */\n        }else{\n          assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );\n          rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);\n          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */\n          if( u.bg.v>=MAX_ROWID ){\n            u.bg.pC->useRandomRowid = 1;\n          }else{\n            u.bg.v++;   /* IMP: R-29538-34987 */\n          }\n        }\n      }\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n      if( pOp->p3 ){\n        /* Assert that P3 is a valid memory cell. */\n        assert( pOp->p3>0 );\n        if( p->pFrame ){\n          for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);\n          /* Assert that P3 is a valid memory cell. */\n          assert( pOp->p3<=u.bg.pFrame->nMem );\n          u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];\n        }else{\n          /* Assert that P3 is a valid memory cell. */\n          assert( pOp->p3<=p->nMem );\n          u.bg.pMem = &aMem[pOp->p3];\n          memAboutToChange(p, u.bg.pMem);\n        }\n        assert( memIsValid(u.bg.pMem) );\n\n        REGISTER_TRACE(pOp->p3, u.bg.pMem);\n        sqlite3VdbeMemIntegerify(u.bg.pMem);\n        assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */\n        if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){\n          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */\n          goto abort_due_to_error;\n        }\n        if( u.bg.v<u.bg.pMem->u.i+1 ){\n          u.bg.v = u.bg.pMem->u.i + 1;\n        }\n        u.bg.pMem->u.i = u.bg.v;\n      }\n#endif\n\n      sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);\n    }\n    if( u.bg.pC->useRandomRowid ){\n      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the\n      ** largest possible integer (9223372036854775807) then the database\n      ** engine starts picking positive candidate ROWIDs at random until\n      ** it finds one that is not previously used. */\n      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is\n                             ** an AUTOINCREMENT table. */\n      /* on the first attempt, simply do one more than previous */\n      u.bg.v = lastRowid;\n      u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */\n      u.bg.v++; /* ensure non-zero */\n      u.bg.cnt = 0;\n      while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,\n                                                 0, &u.bg.res))==SQLITE_OK)\n            && (u.bg.res==0)\n            && (++u.bg.cnt<100)){\n        /* collision - try another random rowid */\n        sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);\n        if( u.bg.cnt<5 ){\n          /* try \"small\" random rowids for the initial attempts */\n          u.bg.v &= 0xffffff;\n        }else{\n          u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */\n        }\n        u.bg.v++; /* ensure non-zero */\n      }\n      if( rc==SQLITE_OK && u.bg.res==0 ){\n        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */\n        goto abort_due_to_error;\n      }\n      assert( u.bg.v>0 );  /* EV: R-40812-03570 */\n    }\n    u.bg.pC->rowidIsValid = 0;\n    u.bg.pC->deferredMoveto = 0;\n    u.bg.pC->cacheStatus = CACHE_STALE;\n  }\n  pOut->u.i = u.bg.v;\n  break;\n}\n\n/* Opcode: Insert P1 P2 P3 P4 P5\n**\n** Write an entry into the table of cursor P1.  A new entry is\n** created if it doesn't already exist or the data for an existing\n** entry is overwritten.  The data is the value MEM_Blob stored in register\n** number P2. The key is stored in register P3. The key must\n** be a MEM_Int.\n**\n** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is\n** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,\n** then rowid is stored for subsequent return by the\n** sqlite3_last_insert_rowid() function (otherwise it is unmodified).\n**\n** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of\n** the last seek operation (OP_NotExists) was a success, then this\n** operation will not attempt to find the appropriate row before doing\n** the insert but will instead overwrite the row that the cursor is\n** currently pointing to.  Presumably, the prior OP_NotExists opcode\n** has already positioned the cursor correctly.  This is an optimization\n** that boosts performance by avoiding redundant seeks.\n**\n** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an\n** UPDATE operation.  Otherwise (if the flag is clear) then this opcode\n** is part of an INSERT operation.  The difference is only important to\n** the update hook.\n**\n** Parameter P4 may point to a string containing the table-name, or\n** may be NULL. If it is not NULL, then the update-hook \n** (sqlite3.xUpdateCallback) is invoked following a successful insert.\n**\n** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically\n** allocated, then ownership of P2 is transferred to the pseudo-cursor\n** and register P2 becomes ephemeral.  If the cursor is changed, the\n** value of register P2 will then change.  Make sure this does not\n** cause any problems.)\n**\n** This instruction only works on tables.  The equivalent instruction\n** for indices is OP_IdxInsert.\n*/\n/* Opcode: InsertInt P1 P2 P3 P4 P5\n**\n** This works exactly like OP_Insert except that the key is the\n** integer value P3, not the value of the integer stored in register P3.\n*/\ncase OP_Insert: \ncase OP_InsertInt: {\n#if 0  /* local variables moved into u.bh */\n  Mem *pData;       /* MEM cell holding data for the record to be inserted */\n  Mem *pKey;        /* MEM cell holding key  for the record */\n  i64 iKey;         /* The integer ROWID or key for the record to be inserted */\n  VdbeCursor *pC;   /* Cursor to table into which insert is written */\n  int nZero;        /* Number of zero-bytes to append */\n  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */\n  const char *zDb;  /* database name - used by the update hook */\n  const char *zTbl; /* Table name - used by the opdate hook */\n  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */\n#endif /* local variables moved into u.bh */\n\n  u.bh.pData = &aMem[pOp->p2];\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( memIsValid(u.bh.pData) );\n  u.bh.pC = p->apCsr[pOp->p1];\n  assert( u.bh.pC!=0 );\n  assert( u.bh.pC->pCursor!=0 );\n  assert( u.bh.pC->pseudoTableReg==0 );\n  assert( u.bh.pC->isTable );\n  REGISTER_TRACE(pOp->p2, u.bh.pData);\n\n  if( pOp->opcode==OP_Insert ){\n    u.bh.pKey = &aMem[pOp->p3];\n    assert( u.bh.pKey->flags & MEM_Int );\n    assert( memIsValid(u.bh.pKey) );\n    REGISTER_TRACE(pOp->p3, u.bh.pKey);\n    u.bh.iKey = u.bh.pKey->u.i;\n  }else{\n    assert( pOp->opcode==OP_InsertInt );\n    u.bh.iKey = pOp->p3;\n  }\n\n  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;\n  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;\n  if( u.bh.pData->flags & MEM_Null ){\n    u.bh.pData->z = 0;\n    u.bh.pData->n = 0;\n  }else{\n    assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );\n  }\n  u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);\n  if( u.bh.pData->flags & MEM_Zero ){\n    u.bh.nZero = u.bh.pData->u.nZero;\n  }else{\n    u.bh.nZero = 0;\n  }\n  sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);\n  rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,\n                          u.bh.pData->z, u.bh.pData->n, u.bh.nZero,\n                          pOp->p5 & OPFLAG_APPEND, u.bh.seekResult\n  );\n  u.bh.pC->rowidIsValid = 0;\n  u.bh.pC->deferredMoveto = 0;\n  u.bh.pC->cacheStatus = CACHE_STALE;\n\n  /* Invoke the update-hook if required. */\n  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){\n    u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;\n    u.bh.zTbl = pOp->p4.z;\n    u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);\n    assert( u.bh.pC->isTable );\n    db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);\n    assert( u.bh.pC->iDb>=0 );\n  }\n  break;\n}\n\n/* Opcode: Delete P1 P2 * P4 *\n**\n** Delete the record at which the P1 cursor is currently pointing.\n**\n** The cursor will be left pointing at either the next or the previous\n** record in the table. If it is left pointing at the next record, then\n** the next Next instruction will be a no-op.  Hence it is OK to delete\n** a record from within an Next loop.\n**\n** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is\n** incremented (otherwise not).\n**\n** P1 must not be pseudo-table.  It has to be a real table with\n** multiple rows.\n**\n** If P4 is not NULL, then it is the name of the table that P1 is\n** pointing to.  The update hook will be invoked, if it exists.\n** If P4 is not NULL then the P1 cursor must have been positioned\n** using OP_NotFound prior to invoking this opcode.\n*/\ncase OP_Delete: {\n#if 0  /* local variables moved into u.bi */\n  i64 iKey;\n  VdbeCursor *pC;\n#endif /* local variables moved into u.bi */\n\n  u.bi.iKey = 0;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bi.pC = p->apCsr[pOp->p1];\n  assert( u.bi.pC!=0 );\n  assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */\n\n  /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the\n  ** row being deleted.\n  */\n  if( db->xUpdateCallback && pOp->p4.z ){\n    assert( u.bi.pC->isTable );\n    assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */\n    u.bi.iKey = u.bi.pC->lastRowid;\n  }\n\n  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or\n  ** OP_Column on the same table without any intervening operations that\n  ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing\n  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation\n  ** below is always a no-op and cannot fail.  We will run it anyhow, though,\n  ** to guard against future changes to the code generator.\n  **/\n  assert( u.bi.pC->deferredMoveto==0 );\n  rc = sqlite3VdbeCursorMoveto(u.bi.pC);\n  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;\n\n  sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);\n  rc = sqlite3BtreeDelete(u.bi.pC->pCursor);\n  u.bi.pC->cacheStatus = CACHE_STALE;\n\n  /* Invoke the update-hook if required. */\n  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){\n    const char *zDb = db->aDb[u.bi.pC->iDb].zName;\n    const char *zTbl = pOp->p4.z;\n    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);\n    assert( u.bi.pC->iDb>=0 );\n  }\n  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;\n  break;\n}\n/* Opcode: ResetCount * * * * *\n**\n** The value of the change counter is copied to the database handle\n** change counter (returned by subsequent calls to sqlite3_changes()).\n** Then the VMs internal change counter resets to 0.\n** This is used by trigger programs.\n*/\ncase OP_ResetCount: {\n  sqlite3VdbeSetChanges(db, p->nChange);\n  p->nChange = 0;\n  break;\n}\n\n/* Opcode: SorterCompare P1 P2 P3\n**\n** P1 is a sorter cursor. This instruction compares the record blob in \n** register P3 with the entry that the sorter cursor currently points to.\n** If, excluding the rowid fields at the end, the two records are a match,\n** fall through to the next instruction. Otherwise, jump to instruction P2.\n*/\ncase OP_SorterCompare: {\n#if 0  /* local variables moved into u.bj */\n  VdbeCursor *pC;\n  int res;\n#endif /* local variables moved into u.bj */\n\n  u.bj.pC = p->apCsr[pOp->p1];\n  assert( isSorter(u.bj.pC) );\n  pIn3 = &aMem[pOp->p3];\n  rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);\n  if( u.bj.res ){\n    pc = pOp->p2-1;\n  }\n  break;\n};\n\n/* Opcode: SorterData P1 P2 * * *\n**\n** Write into register P2 the current sorter data for sorter cursor P1.\n*/\ncase OP_SorterData: {\n#if 0  /* local variables moved into u.bk */\n  VdbeCursor *pC;\n#endif /* local variables moved into u.bk */\n#ifndef SQLITE_OMIT_MERGE_SORT\n  pOut = &aMem[pOp->p2];\n  u.bk.pC = p->apCsr[pOp->p1];\n  assert( u.bk.pC->isSorter );\n  rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);\n#else\n  pOp->opcode = OP_RowKey;\n  pc--;\n#endif\n  break;\n}\n\n/* Opcode: RowData P1 P2 * * *\n**\n** Write into register P2 the complete row data for cursor P1.\n** There is no interpretation of the data.  \n** It is just copied onto the P2 register exactly as \n** it is found in the database file.\n**\n** If the P1 cursor must be pointing to a valid row (not a NULL row)\n** of a real table, not a pseudo-table.\n*/\n/* Opcode: RowKey P1 P2 * * *\n**\n** Write into register P2 the complete row key for cursor P1.\n** There is no interpretation of the data.  \n** The key is copied onto the P3 register exactly as \n** it is found in the database file.\n**\n** If the P1 cursor must be pointing to a valid row (not a NULL row)\n** of a real table, not a pseudo-table.\n*/\ncase OP_RowKey:\ncase OP_RowData: {\n#if 0  /* local variables moved into u.bl */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  u32 n;\n  i64 n64;\n#endif /* local variables moved into u.bl */\n\n  pOut = &aMem[pOp->p2];\n  memAboutToChange(p, pOut);\n\n  /* Note that RowKey and RowData are really exactly the same instruction */\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bl.pC = p->apCsr[pOp->p1];\n  assert( u.bl.pC->isSorter==0 );\n  assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );\n  assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );\n  assert( u.bl.pC!=0 );\n  assert( u.bl.pC->nullRow==0 );\n  assert( u.bl.pC->pseudoTableReg==0 );\n  assert( u.bl.pC->pCursor!=0 );\n  u.bl.pCrsr = u.bl.pC->pCursor;\n  assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );\n\n  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or\n  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate\n  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always\n  ** a no-op and can never fail.  But we leave it in place as a safety.\n  */\n  assert( u.bl.pC->deferredMoveto==0 );\n  rc = sqlite3VdbeCursorMoveto(u.bl.pC);\n  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;\n\n  if( u.bl.pC->isIndex ){\n    assert( !u.bl.pC->isTable );\n    VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);\n    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */\n    if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n      goto too_big;\n    }\n    u.bl.n = (u32)u.bl.n64;\n  }else{\n    VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);\n    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */\n    if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){\n      goto too_big;\n    }\n  }\n  if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){\n    goto no_mem;\n  }\n  pOut->n = u.bl.n;\n  MemSetTypeFlag(pOut, MEM_Blob);\n  if( u.bl.pC->isIndex ){\n    rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);\n  }else{\n    rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);\n  }\n  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */\n  UPDATE_MAX_BLOBSIZE(pOut);\n  break;\n}\n\n/* Opcode: Rowid P1 P2 * * *\n**\n** Store in register P2 an integer which is the key of the table entry that\n** P1 is currently point to.\n**\n** P1 can be either an ordinary table or a virtual table.  There used to\n** be a separate OP_VRowid opcode for use with virtual tables, but this\n** one opcode now works for both table types.\n*/\ncase OP_Rowid: {                 /* out2-prerelease */\n#if 0  /* local variables moved into u.bm */\n  VdbeCursor *pC;\n  i64 v;\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n#endif /* local variables moved into u.bm */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bm.pC = p->apCsr[pOp->p1];\n  assert( u.bm.pC!=0 );\n  assert( u.bm.pC->pseudoTableReg==0 );\n  if( u.bm.pC->nullRow ){\n    pOut->flags = MEM_Null;\n    break;\n  }else if( u.bm.pC->deferredMoveto ){\n    u.bm.v = u.bm.pC->movetoTarget;\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  }else if( u.bm.pC->pVtabCursor ){\n    u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;\n    u.bm.pModule = u.bm.pVtab->pModule;\n    assert( u.bm.pModule->xRowid );\n    rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);\n    importVtabErrMsg(p, u.bm.pVtab);\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n  }else{\n    assert( u.bm.pC->pCursor!=0 );\n    rc = sqlite3VdbeCursorMoveto(u.bm.pC);\n    if( rc ) goto abort_due_to_error;\n    if( u.bm.pC->rowidIsValid ){\n      u.bm.v = u.bm.pC->lastRowid;\n    }else{\n      rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);\n      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */\n    }\n  }\n  pOut->u.i = u.bm.v;\n  break;\n}\n\n/* Opcode: NullRow P1 * * * *\n**\n** Move the cursor P1 to a null row.  Any OP_Column operations\n** that occur while the cursor is on the null row will always\n** write a NULL.\n*/\ncase OP_NullRow: {\n#if 0  /* local variables moved into u.bn */\n  VdbeCursor *pC;\n#endif /* local variables moved into u.bn */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bn.pC = p->apCsr[pOp->p1];\n  assert( u.bn.pC!=0 );\n  u.bn.pC->nullRow = 1;\n  u.bn.pC->rowidIsValid = 0;\n  assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );\n  if( u.bn.pC->pCursor ){\n    sqlite3BtreeClearCursor(u.bn.pC->pCursor);\n  }\n  break;\n}\n\n/* Opcode: Last P1 P2 * * *\n**\n** The next use of the Rowid or Column or Next instruction for P1 \n** will refer to the last entry in the database table or index.\n** If the table or index is empty and P2>0, then jump immediately to P2.\n** If P2 is 0 or if the table or index is not empty, fall through\n** to the following instruction.\n*/\ncase OP_Last: {        /* jump */\n#if 0  /* local variables moved into u.bo */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n#endif /* local variables moved into u.bo */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bo.pC = p->apCsr[pOp->p1];\n  assert( u.bo.pC!=0 );\n  u.bo.pCrsr = u.bo.pC->pCursor;\n  u.bo.res = 0;\n  if( ALWAYS(u.bo.pCrsr!=0) ){\n    rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);\n  }\n  u.bo.pC->nullRow = (u8)u.bo.res;\n  u.bo.pC->deferredMoveto = 0;\n  u.bo.pC->rowidIsValid = 0;\n  u.bo.pC->cacheStatus = CACHE_STALE;\n  if( pOp->p2>0 && u.bo.res ){\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n\n/* Opcode: Sort P1 P2 * * *\n**\n** This opcode does exactly the same thing as OP_Rewind except that\n** it increments an undocumented global variable used for testing.\n**\n** Sorting is accomplished by writing records into a sorting index,\n** then rewinding that index and playing it back from beginning to\n** end.  We use the OP_Sort opcode instead of OP_Rewind to do the\n** rewinding so that the global variable will be incremented and\n** regression tests can determine whether or not the optimizer is\n** correctly optimizing out sorts.\n*/\ncase OP_SorterSort:    /* jump */\n#ifdef SQLITE_OMIT_MERGE_SORT\n  pOp->opcode = OP_Sort;\n#endif\ncase OP_Sort: {        /* jump */\n#ifdef SQLITE_TEST\n  sqlite3_sort_count++;\n  sqlite3_search_count--;\n#endif\n  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;\n  /* Fall through into OP_Rewind */\n}\n/* Opcode: Rewind P1 P2 * * *\n**\n** The next use of the Rowid or Column or Next instruction for P1 \n** will refer to the first entry in the database table or index.\n** If the table or index is empty and P2>0, then jump immediately to P2.\n** If P2 is 0 or if the table or index is not empty, fall through\n** to the following instruction.\n*/\ncase OP_Rewind: {        /* jump */\n#if 0  /* local variables moved into u.bp */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n#endif /* local variables moved into u.bp */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bp.pC = p->apCsr[pOp->p1];\n  assert( u.bp.pC!=0 );\n  assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );\n  u.bp.res = 1;\n  if( isSorter(u.bp.pC) ){\n    rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);\n  }else{\n    u.bp.pCrsr = u.bp.pC->pCursor;\n    assert( u.bp.pCrsr );\n    rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);\n    u.bp.pC->atFirst = u.bp.res==0 ?1:0;\n    u.bp.pC->deferredMoveto = 0;\n    u.bp.pC->cacheStatus = CACHE_STALE;\n    u.bp.pC->rowidIsValid = 0;\n  }\n  u.bp.pC->nullRow = (u8)u.bp.res;\n  assert( pOp->p2>0 && pOp->p2<p->nOp );\n  if( u.bp.res ){\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: Next P1 P2 * P4 P5\n**\n** Advance cursor P1 so that it points to the next key/data pair in its\n** table or index.  If there are no more key/value pairs then fall through\n** to the following instruction.  But if the cursor advance was successful,\n** jump immediately to P2.\n**\n** The P1 cursor must be for a real table, not a pseudo-table.\n**\n** P4 is always of type P4_ADVANCE. The function pointer points to\n** sqlite3BtreeNext().\n**\n** If P5 is positive and the jump is taken, then event counter\n** number P5-1 in the prepared statement is incremented.\n**\n** See also: Prev\n*/\n/* Opcode: Prev P1 P2 * * P5\n**\n** Back up cursor P1 so that it points to the previous key/data pair in its\n** table or index.  If there is no previous key/value pairs then fall through\n** to the following instruction.  But if the cursor backup was successful,\n** jump immediately to P2.\n**\n** The P1 cursor must be for a real table, not a pseudo-table.\n**\n** P4 is always of type P4_ADVANCE. The function pointer points to\n** sqlite3BtreePrevious().\n**\n** If P5 is positive and the jump is taken, then event counter\n** number P5-1 in the prepared statement is incremented.\n*/\ncase OP_SorterNext:    /* jump */\n#ifdef SQLITE_OMIT_MERGE_SORT\n  pOp->opcode = OP_Next;\n#endif\ncase OP_Prev:          /* jump */\ncase OP_Next: {        /* jump */\n#if 0  /* local variables moved into u.bq */\n  VdbeCursor *pC;\n  int res;\n#endif /* local variables moved into u.bq */\n\n  CHECK_FOR_INTERRUPT;\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  assert( pOp->p5<=ArraySize(p->aCounter) );\n  u.bq.pC = p->apCsr[pOp->p1];\n  if( u.bq.pC==0 ){\n    break;  /* See ticket #2273 */\n  }\n  assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );\n  if( isSorter(u.bq.pC) ){\n    assert( pOp->opcode==OP_SorterNext );\n    rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);\n  }else{\n    u.bq.res = 1;\n    assert( u.bq.pC->deferredMoveto==0 );\n    assert( u.bq.pC->pCursor );\n    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );\n    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );\n    rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);\n  }\n  u.bq.pC->nullRow = (u8)u.bq.res;\n  u.bq.pC->cacheStatus = CACHE_STALE;\n  if( u.bq.res==0 ){\n    pc = pOp->p2 - 1;\n    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;\n#ifdef SQLITE_TEST\n    sqlite3_search_count++;\n#endif\n  }\n  u.bq.pC->rowidIsValid = 0;\n  break;\n}\n\n/* Opcode: IdxInsert P1 P2 P3 * P5\n**\n** Register P2 holds an SQL index key made using the\n** MakeRecord instructions.  This opcode writes that key\n** into the index P1.  Data for the entry is nil.\n**\n** P3 is a flag that provides a hint to the b-tree layer that this\n** insert is likely to be an append.\n**\n** This instruction only works for indices.  The equivalent instruction\n** for tables is OP_Insert.\n*/\ncase OP_SorterInsert:       /* in2 */\n#ifdef SQLITE_OMIT_MERGE_SORT\n  pOp->opcode = OP_IdxInsert;\n#endif\ncase OP_IdxInsert: {        /* in2 */\n#if 0  /* local variables moved into u.br */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int nKey;\n  const char *zKey;\n#endif /* local variables moved into u.br */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.br.pC = p->apCsr[pOp->p1];\n  assert( u.br.pC!=0 );\n  assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );\n  pIn2 = &aMem[pOp->p2];\n  assert( pIn2->flags & MEM_Blob );\n  u.br.pCrsr = u.br.pC->pCursor;\n  if( ALWAYS(u.br.pCrsr!=0) ){\n    assert( u.br.pC->isTable==0 );\n    rc = ExpandBlob(pIn2);\n    if( rc==SQLITE_OK ){\n      if( isSorter(u.br.pC) ){\n        rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);\n      }else{\n        u.br.nKey = pIn2->n;\n        u.br.zKey = pIn2->z;\n        rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, \"\", 0, 0, pOp->p3,\n            ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)\n            );\n        assert( u.br.pC->deferredMoveto==0 );\n        u.br.pC->cacheStatus = CACHE_STALE;\n      }\n    }\n  }\n  break;\n}\n\n/* Opcode: IdxDelete P1 P2 P3 * *\n**\n** The content of P3 registers starting at register P2 form\n** an unpacked index key. This opcode removes that entry from the \n** index opened by cursor P1.\n*/\ncase OP_IdxDelete: {\n#if 0  /* local variables moved into u.bs */\n  VdbeCursor *pC;\n  BtCursor *pCrsr;\n  int res;\n  UnpackedRecord r;\n#endif /* local variables moved into u.bs */\n\n  assert( pOp->p3>0 );\n  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bs.pC = p->apCsr[pOp->p1];\n  assert( u.bs.pC!=0 );\n  u.bs.pCrsr = u.bs.pC->pCursor;\n  if( ALWAYS(u.bs.pCrsr!=0) ){\n    u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;\n    u.bs.r.nField = (u16)pOp->p3;\n    u.bs.r.flags = 0;\n    u.bs.r.aMem = &aMem[pOp->p2];\n#ifdef SQLITE_DEBUG\n    { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }\n#endif\n    rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);\n    if( rc==SQLITE_OK && u.bs.res==0 ){\n      rc = sqlite3BtreeDelete(u.bs.pCrsr);\n    }\n    assert( u.bs.pC->deferredMoveto==0 );\n    u.bs.pC->cacheStatus = CACHE_STALE;\n  }\n  break;\n}\n\n/* Opcode: IdxRowid P1 P2 * * *\n**\n** Write into register P2 an integer which is the last entry in the record at\n** the end of the index key pointed to by cursor P1.  This integer should be\n** the rowid of the table entry to which this index entry points.\n**\n** See also: Rowid, MakeRecord.\n*/\ncase OP_IdxRowid: {              /* out2-prerelease */\n#if 0  /* local variables moved into u.bt */\n  BtCursor *pCrsr;\n  VdbeCursor *pC;\n  i64 rowid;\n#endif /* local variables moved into u.bt */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bt.pC = p->apCsr[pOp->p1];\n  assert( u.bt.pC!=0 );\n  u.bt.pCrsr = u.bt.pC->pCursor;\n  pOut->flags = MEM_Null;\n  if( ALWAYS(u.bt.pCrsr!=0) ){\n    rc = sqlite3VdbeCursorMoveto(u.bt.pC);\n    if( NEVER(rc) ) goto abort_due_to_error;\n    assert( u.bt.pC->deferredMoveto==0 );\n    assert( u.bt.pC->isTable==0 );\n    if( !u.bt.pC->nullRow ){\n      rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);\n      if( rc!=SQLITE_OK ){\n        goto abort_due_to_error;\n      }\n      pOut->u.i = u.bt.rowid;\n      pOut->flags = MEM_Int;\n    }\n  }\n  break;\n}\n\n/* Opcode: IdxGE P1 P2 P3 P4 P5\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the ROWID.  Compare this key value against the index \n** that P1 is currently pointing to, ignoring the ROWID on the P1 index.\n**\n** If the P1 index entry is greater than or equal to the key value\n** then jump to P2.  Otherwise fall through to the next instruction.\n**\n** If P5 is non-zero then the key value is increased by an epsilon \n** prior to the comparison.  This make the opcode work like IdxGT except\n** that if the key from register P3 is a prefix of the key in the cursor,\n** the result is false whereas it would be true with IdxGT.\n*/\n/* Opcode: IdxLT P1 P2 P3 P4 P5\n**\n** The P4 register values beginning with P3 form an unpacked index \n** key that omits the ROWID.  Compare this key value against the index \n** that P1 is currently pointing to, ignoring the ROWID on the P1 index.\n**\n** If the P1 index entry is less than the key value then jump to P2.\n** Otherwise fall through to the next instruction.\n**\n** If P5 is non-zero then the key value is increased by an epsilon prior \n** to the comparison.  This makes the opcode work like IdxLE.\n*/\ncase OP_IdxLT:          /* jump */\ncase OP_IdxGE: {        /* jump */\n#if 0  /* local variables moved into u.bu */\n  VdbeCursor *pC;\n  int res;\n  UnpackedRecord r;\n#endif /* local variables moved into u.bu */\n\n  assert( pOp->p1>=0 && pOp->p1<p->nCursor );\n  u.bu.pC = p->apCsr[pOp->p1];\n  assert( u.bu.pC!=0 );\n  assert( u.bu.pC->isOrdered );\n  if( ALWAYS(u.bu.pC->pCursor!=0) ){\n    assert( u.bu.pC->deferredMoveto==0 );\n    assert( pOp->p5==0 || pOp->p5==1 );\n    assert( pOp->p4type==P4_INT32 );\n    u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;\n    u.bu.r.nField = (u16)pOp->p4.i;\n    if( pOp->p5 ){\n      u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;\n    }else{\n      u.bu.r.flags = UNPACKED_PREFIX_MATCH;\n    }\n    u.bu.r.aMem = &aMem[pOp->p3];\n#ifdef SQLITE_DEBUG\n    { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }\n#endif\n    rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);\n    if( pOp->opcode==OP_IdxLT ){\n      u.bu.res = -u.bu.res;\n    }else{\n      assert( pOp->opcode==OP_IdxGE );\n      u.bu.res++;\n    }\n    if( u.bu.res>0 ){\n      pc = pOp->p2 - 1 ;\n    }\n  }\n  break;\n}\n\n/* Opcode: Destroy P1 P2 P3 * *\n**\n** Delete an entire database table or index whose root page in the database\n** file is given by P1.\n**\n** The table being destroyed is in the main database file if P3==0.  If\n** P3==1 then the table to be clear is in the auxiliary database file\n** that is used to store tables create using CREATE TEMPORARY TABLE.\n**\n** If AUTOVACUUM is enabled then it is possible that another root page\n** might be moved into the newly deleted root page in order to keep all\n** root pages contiguous at the beginning of the database.  The former\n** value of the root page that moved - its value before the move occurred -\n** is stored in register P2.  If no page \n** movement was required (because the table being dropped was already \n** the last one in the database) then a zero is stored in register P2.\n** If AUTOVACUUM is disabled then a zero is stored in register P2.\n**\n** See also: Clear\n*/\ncase OP_Destroy: {     /* out2-prerelease */\n#if 0  /* local variables moved into u.bv */\n  int iMoved;\n  int iCnt;\n  Vdbe *pVdbe;\n  int iDb;\n#endif /* local variables moved into u.bv */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  u.bv.iCnt = 0;\n  for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){\n    if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){\n      u.bv.iCnt++;\n    }\n  }\n#else\n  u.bv.iCnt = db->activeVdbeCnt;\n#endif\n  pOut->flags = MEM_Null;\n  if( u.bv.iCnt>1 ){\n    rc = SQLITE_LOCKED;\n    p->errorAction = OE_Abort;\n  }else{\n    u.bv.iDb = pOp->p3;\n    assert( u.bv.iCnt==1 );\n    assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );\n    rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);\n    pOut->flags = MEM_Int;\n    pOut->u.i = u.bv.iMoved;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    if( rc==SQLITE_OK && u.bv.iMoved!=0 ){\n      sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);\n      /* All OP_Destroy operations occur on the same btree */\n      assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );\n      resetSchemaOnFault = u.bv.iDb+1;\n    }\n#endif\n  }\n  break;\n}\n\n/* Opcode: Clear P1 P2 P3\n**\n** Delete all contents of the database table or index whose root page\n** in the database file is given by P1.  But, unlike Destroy, do not\n** remove the table or index from the database file.\n**\n** The table being clear is in the main database file if P2==0.  If\n** P2==1 then the table to be clear is in the auxiliary database file\n** that is used to store tables create using CREATE TEMPORARY TABLE.\n**\n** If the P3 value is non-zero, then the table referred to must be an\n** intkey table (an SQL table, not an index). In this case the row change \n** count is incremented by the number of rows in the table being cleared. \n** If P3 is greater than zero, then the value stored in register P3 is\n** also incremented by the number of rows in the table being cleared.\n**\n** See also: Destroy\n*/\ncase OP_Clear: {\n#if 0  /* local variables moved into u.bw */\n  int nChange;\n#endif /* local variables moved into u.bw */\n\n  u.bw.nChange = 0;\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );\n  rc = sqlite3BtreeClearTable(\n      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)\n  );\n  if( pOp->p3 ){\n    p->nChange += u.bw.nChange;\n    if( pOp->p3>0 ){\n      assert( memIsValid(&aMem[pOp->p3]) );\n      memAboutToChange(p, &aMem[pOp->p3]);\n      aMem[pOp->p3].u.i += u.bw.nChange;\n    }\n  }\n  break;\n}\n\n/* Opcode: CreateTable P1 P2 * * *\n**\n** Allocate a new table in the main database file if P1==0 or in the\n** auxiliary database file if P1==1 or in an attached database if\n** P1>1.  Write the root page number of the new table into\n** register P2\n**\n** The difference between a table and an index is this:  A table must\n** have a 4-byte integer key and can have arbitrary data.  An index\n** has an arbitrary key but no data.\n**\n** See also: CreateIndex\n*/\n/* Opcode: CreateIndex P1 P2 * * *\n**\n** Allocate a new index in the main database file if P1==0 or in the\n** auxiliary database file if P1==1 or in an attached database if\n** P1>1.  Write the root page number of the new table into\n** register P2.\n**\n** See documentation on OP_CreateTable for additional information.\n*/\ncase OP_CreateIndex:            /* out2-prerelease */\ncase OP_CreateTable: {          /* out2-prerelease */\n#if 0  /* local variables moved into u.bx */\n  int pgno;\n  int flags;\n  Db *pDb;\n#endif /* local variables moved into u.bx */\n\n  u.bx.pgno = 0;\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );\n  u.bx.pDb = &db->aDb[pOp->p1];\n  assert( u.bx.pDb->pBt!=0 );\n  if( pOp->opcode==OP_CreateTable ){\n    /* u.bx.flags = BTREE_INTKEY; */\n    u.bx.flags = BTREE_INTKEY;\n  }else{\n    u.bx.flags = BTREE_BLOBKEY;\n  }\n  rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);\n  pOut->u.i = u.bx.pgno;\n  break;\n}\n\n/* Opcode: ParseSchema P1 * * P4 *\n**\n** Read and parse all entries from the SQLITE_MASTER table of database P1\n** that match the WHERE clause P4. \n**\n** This opcode invokes the parser to create a new virtual machine,\n** then runs the new virtual machine.  It is thus a re-entrant opcode.\n*/\ncase OP_ParseSchema: {\n#if 0  /* local variables moved into u.by */\n  int iDb;\n  const char *zMaster;\n  char *zSql;\n  InitData initData;\n#endif /* local variables moved into u.by */\n\n  /* Any prepared statement that invokes this opcode will hold mutexes\n  ** on every btree.  This is a prerequisite for invoking\n  ** sqlite3InitCallback().\n  */\n#ifdef SQLITE_DEBUG\n  for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){\n    assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );\n  }\n#endif\n\n  u.by.iDb = pOp->p1;\n  assert( u.by.iDb>=0 && u.by.iDb<db->nDb );\n  assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );\n  /* Used to be a conditional */ {\n    u.by.zMaster = SCHEMA_TABLE(u.by.iDb);\n    u.by.initData.db = db;\n    u.by.initData.iDb = pOp->p1;\n    u.by.initData.pzErrMsg = &p->zErrMsg;\n    u.by.zSql = sqlite3MPrintf(db,\n       \"SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid\",\n       db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);\n    if( u.by.zSql==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      assert( db->init.busy==0 );\n      db->init.busy = 1;\n      u.by.initData.rc = SQLITE_OK;\n      assert( !db->mallocFailed );\n      rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);\n      if( rc==SQLITE_OK ) rc = u.by.initData.rc;\n      sqlite3DbFree(db, u.by.zSql);\n      db->init.busy = 0;\n    }\n  }\n  if( rc ) sqlite3ResetAllSchemasOfConnection(db);\n  if( rc==SQLITE_NOMEM ){\n    goto no_mem;\n  }\n  break;\n}\n\n#if !defined(SQLITE_OMIT_ANALYZE)\n/* Opcode: LoadAnalysis P1 * * * *\n**\n** Read the sqlite_stat1 table for database P1 and load the content\n** of that table into the internal index hash table.  This will cause\n** the analysis to be used when preparing all subsequent queries.\n*/\ncase OP_LoadAnalysis: {\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  rc = sqlite3AnalysisLoad(db, pOp->p1);\n  break;  \n}\n#endif /* !defined(SQLITE_OMIT_ANALYZE) */\n\n/* Opcode: DropTable P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the table named P4 in database P1.  This is called after a table\n** is dropped in order to keep the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropTable: {\n  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n/* Opcode: DropIndex P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the index named P4 in database P1.  This is called after an index\n** is dropped in order to keep the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropIndex: {\n  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n/* Opcode: DropTrigger P1 * * P4 *\n**\n** Remove the internal (in-memory) data structures that describe\n** the trigger named P4 in database P1.  This is called after a trigger\n** is dropped in order to keep the internal representation of the\n** schema consistent with what is on disk.\n*/\ncase OP_DropTrigger: {\n  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);\n  break;\n}\n\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n/* Opcode: IntegrityCk P1 P2 P3 * P5\n**\n** Do an analysis of the currently open database.  Store in\n** register P1 the text of an error message describing any problems.\n** If no problems are found, store a NULL in register P1.\n**\n** The register P3 contains the maximum number of allowed errors.\n** At most reg(P3) errors will be reported.\n** In other words, the analysis stops as soon as reg(P1) errors are \n** seen.  Reg(P1) is updated with the number of errors remaining.\n**\n** The root page numbers of all tables in the database are integer\n** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables\n** total.\n**\n** If P5 is not zero, the check is done on the auxiliary database\n** file, not the main database file.\n**\n** This opcode is used to implement the integrity_check pragma.\n*/\ncase OP_IntegrityCk: {\n#if 0  /* local variables moved into u.bz */\n  int nRoot;      /* Number of tables to check.  (Number of root pages.) */\n  int *aRoot;     /* Array of rootpage numbers for tables to be checked */\n  int j;          /* Loop counter */\n  int nErr;       /* Number of errors reported */\n  char *z;        /* Text of the error report */\n  Mem *pnErr;     /* Register keeping track of errors remaining */\n#endif /* local variables moved into u.bz */\n\n  u.bz.nRoot = pOp->p2;\n  assert( u.bz.nRoot>0 );\n  u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );\n  if( u.bz.aRoot==0 ) goto no_mem;\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  u.bz.pnErr = &aMem[pOp->p3];\n  assert( (u.bz.pnErr->flags & MEM_Int)!=0 );\n  assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );\n  pIn1 = &aMem[pOp->p1];\n  for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){\n    u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);\n  }\n  u.bz.aRoot[u.bz.j] = 0;\n  assert( pOp->p5<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );\n  u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,\n                                 (int)u.bz.pnErr->u.i, &u.bz.nErr);\n  sqlite3DbFree(db, u.bz.aRoot);\n  u.bz.pnErr->u.i -= u.bz.nErr;\n  sqlite3VdbeMemSetNull(pIn1);\n  if( u.bz.nErr==0 ){\n    assert( u.bz.z==0 );\n  }else if( u.bz.z==0 ){\n    goto no_mem;\n  }else{\n    sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);\n  }\n  UPDATE_MAX_BLOBSIZE(pIn1);\n  sqlite3VdbeChangeEncoding(pIn1, encoding);\n  break;\n}\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n/* Opcode: RowSetAdd P1 P2 * * *\n**\n** Insert the integer value held by register P2 into a boolean index\n** held in register P1.\n**\n** An assertion fails if P2 is not an integer.\n*/\ncase OP_RowSetAdd: {       /* in1, in2 */\n  pIn1 = &aMem[pOp->p1];\n  pIn2 = &aMem[pOp->p2];\n  assert( (pIn2->flags & MEM_Int)!=0 );\n  if( (pIn1->flags & MEM_RowSet)==0 ){\n    sqlite3VdbeMemSetRowSet(pIn1);\n    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;\n  }\n  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);\n  break;\n}\n\n/* Opcode: RowSetRead P1 P2 P3 * *\n**\n** Extract the smallest value from boolean index P1 and put that value into\n** register P3.  Or, if boolean index P1 is initially empty, leave P3\n** unchanged and jump to instruction P2.\n*/\ncase OP_RowSetRead: {       /* jump, in1, out3 */\n#if 0  /* local variables moved into u.ca */\n  i64 val;\n#endif /* local variables moved into u.ca */\n  CHECK_FOR_INTERRUPT;\n  pIn1 = &aMem[pOp->p1];\n  if( (pIn1->flags & MEM_RowSet)==0\n   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0\n  ){\n    /* The boolean index is empty */\n    sqlite3VdbeMemSetNull(pIn1);\n    pc = pOp->p2 - 1;\n  }else{\n    /* A value was pulled from the index */\n    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);\n  }\n  break;\n}\n\n/* Opcode: RowSetTest P1 P2 P3 P4\n**\n** Register P3 is assumed to hold a 64-bit integer value. If register P1\n** contains a RowSet object and that RowSet object contains\n** the value held in P3, jump to register P2. Otherwise, insert the\n** integer in P3 into the RowSet and continue on to the\n** next opcode.\n**\n** The RowSet object is optimized for the case where successive sets\n** of integers, where each set contains no duplicates. Each set\n** of values is identified by a unique P4 value. The first set\n** must have P4==0, the final set P4=-1.  P4 must be either -1 or\n** non-negative.  For non-negative values of P4 only the lower 4\n** bits are significant.\n**\n** This allows optimizations: (a) when P4==0 there is no need to test\n** the rowset object for P3, as it is guaranteed not to contain it,\n** (b) when P4==-1 there is no need to insert the value, as it will\n** never be tested for, and (c) when a value that is part of set X is\n** inserted, there is no need to search to see if the same value was\n** previously inserted as part of set X (only if it was previously\n** inserted as part of some other set).\n*/\ncase OP_RowSetTest: {                     /* jump, in1, in3 */\n#if 0  /* local variables moved into u.cb */\n  int iSet;\n  int exists;\n#endif /* local variables moved into u.cb */\n\n  pIn1 = &aMem[pOp->p1];\n  pIn3 = &aMem[pOp->p3];\n  u.cb.iSet = pOp->p4.i;\n  assert( pIn3->flags&MEM_Int );\n\n  /* If there is anything other than a rowset object in memory cell P1,\n  ** delete it now and initialize P1 with an empty rowset\n  */\n  if( (pIn1->flags & MEM_RowSet)==0 ){\n    sqlite3VdbeMemSetRowSet(pIn1);\n    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;\n  }\n\n  assert( pOp->p4type==P4_INT32 );\n  assert( u.cb.iSet==-1 || u.cb.iSet>=0 );\n  if( u.cb.iSet ){\n    u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,\n                               (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),\n                               pIn3->u.i);\n    if( u.cb.exists ){\n      pc = pOp->p2 - 1;\n      break;\n    }\n  }\n  if( u.cb.iSet>=0 ){\n    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);\n  }\n  break;\n}\n\n\n#ifndef SQLITE_OMIT_TRIGGER\n\n/* Opcode: Program P1 P2 P3 P4 *\n**\n** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). \n**\n** P1 contains the address of the memory cell that contains the first memory \n** cell in an array of values used as arguments to the sub-program. P2 \n** contains the address to jump to if the sub-program throws an IGNORE \n** exception using the RAISE() function. Register P3 contains the address \n** of a memory cell in this (the parent) VM that is used to allocate the \n** memory required by the sub-vdbe at runtime.\n**\n** P4 is a pointer to the VM containing the trigger program.\n*/\ncase OP_Program: {        /* jump */\n#if 0  /* local variables moved into u.cc */\n  int nMem;               /* Number of memory registers for sub-program */\n  int nByte;              /* Bytes of runtime space required for sub-program */\n  Mem *pRt;               /* Register to allocate runtime space */\n  Mem *pMem;              /* Used to iterate through memory cells */\n  Mem *pEnd;              /* Last memory cell in new array */\n  VdbeFrame *pFrame;      /* New vdbe frame to execute in */\n  SubProgram *pProgram;   /* Sub-program to execute */\n  void *t;                /* Token identifying trigger */\n#endif /* local variables moved into u.cc */\n\n  u.cc.pProgram = pOp->p4.pProgram;\n  u.cc.pRt = &aMem[pOp->p3];\n  assert( u.cc.pProgram->nOp>0 );\n\n  /* If the p5 flag is clear, then recursive invocation of triggers is\n  ** disabled for backwards compatibility (p5 is set if this sub-program\n  ** is really a trigger, not a foreign key action, and the flag set\n  ** and cleared by the \"PRAGMA recursive_triggers\" command is clear).\n  **\n  ** It is recursive invocation of triggers, at the SQL level, that is\n  ** disabled. In some cases a single trigger may generate more than one\n  ** SubProgram (if the trigger may be executed with more than one different\n  ** ON CONFLICT algorithm). SubProgram structures associated with a\n  ** single trigger all have the same value for the SubProgram.token\n  ** variable.  */\n  if( pOp->p5 ){\n    u.cc.t = u.cc.pProgram->token;\n    for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);\n    if( u.cc.pFrame ) break;\n  }\n\n  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){\n    rc = SQLITE_ERROR;\n    sqlite3SetString(&p->zErrMsg, db, \"too many levels of trigger recursion\");\n    break;\n  }\n\n  /* Register u.cc.pRt is used to store the memory required to save the state\n  ** of the current program, and the memory required at runtime to execute\n  ** the trigger program. If this trigger has been fired before, then u.cc.pRt\n  ** is already allocated. Otherwise, it must be initialized.  */\n  if( (u.cc.pRt->flags&MEM_Frame)==0 ){\n    /* SubProgram.nMem is set to the number of memory cells used by the\n    ** program stored in SubProgram.aOp. As well as these, one memory\n    ** cell is required for each cursor used by the program. Set local\n    ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.\n    */\n    u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;\n    u.cc.nByte = ROUND8(sizeof(VdbeFrame))\n              + u.cc.nMem * sizeof(Mem)\n              + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)\n              + u.cc.pProgram->nOnce * sizeof(u8);\n    u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);\n    if( !u.cc.pFrame ){\n      goto no_mem;\n    }\n    sqlite3VdbeMemRelease(u.cc.pRt);\n    u.cc.pRt->flags = MEM_Frame;\n    u.cc.pRt->u.pFrame = u.cc.pFrame;\n\n    u.cc.pFrame->v = p;\n    u.cc.pFrame->nChildMem = u.cc.nMem;\n    u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;\n    u.cc.pFrame->pc = pc;\n    u.cc.pFrame->aMem = p->aMem;\n    u.cc.pFrame->nMem = p->nMem;\n    u.cc.pFrame->apCsr = p->apCsr;\n    u.cc.pFrame->nCursor = p->nCursor;\n    u.cc.pFrame->aOp = p->aOp;\n    u.cc.pFrame->nOp = p->nOp;\n    u.cc.pFrame->token = u.cc.pProgram->token;\n    u.cc.pFrame->aOnceFlag = p->aOnceFlag;\n    u.cc.pFrame->nOnceFlag = p->nOnceFlag;\n\n    u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];\n    for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){\n      u.cc.pMem->flags = MEM_Invalid;\n      u.cc.pMem->db = db;\n    }\n  }else{\n    u.cc.pFrame = u.cc.pRt->u.pFrame;\n    assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );\n    assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );\n    assert( pc==u.cc.pFrame->pc );\n  }\n\n  p->nFrame++;\n  u.cc.pFrame->pParent = p->pFrame;\n  u.cc.pFrame->lastRowid = lastRowid;\n  u.cc.pFrame->nChange = p->nChange;\n  p->nChange = 0;\n  p->pFrame = u.cc.pFrame;\n  p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];\n  p->nMem = u.cc.pFrame->nChildMem;\n  p->nCursor = (u16)u.cc.pFrame->nChildCsr;\n  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];\n  p->aOp = aOp = u.cc.pProgram->aOp;\n  p->nOp = u.cc.pProgram->nOp;\n  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];\n  p->nOnceFlag = u.cc.pProgram->nOnce;\n  pc = -1;\n  memset(p->aOnceFlag, 0, p->nOnceFlag);\n\n  break;\n}\n\n/* Opcode: Param P1 P2 * * *\n**\n** This opcode is only ever present in sub-programs called via the \n** OP_Program instruction. Copy a value currently stored in a memory \n** cell of the calling (parent) frame to cell P2 in the current frames \n** address space. This is used by trigger programs to access the new.* \n** and old.* values.\n**\n** The address of the cell in the parent frame is determined by adding\n** the value of the P1 argument to the value of the P1 argument to the\n** calling OP_Program instruction.\n*/\ncase OP_Param: {           /* out2-prerelease */\n#if 0  /* local variables moved into u.cd */\n  VdbeFrame *pFrame;\n  Mem *pIn;\n#endif /* local variables moved into u.cd */\n  u.cd.pFrame = p->pFrame;\n  u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];\n  sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);\n  break;\n}\n\n#endif /* #ifndef SQLITE_OMIT_TRIGGER */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n/* Opcode: FkCounter P1 P2 * * *\n**\n** Increment a \"constraint counter\" by P2 (P2 may be negative or positive).\n** If P1 is non-zero, the database constraint counter is incremented \n** (deferred foreign key constraints). Otherwise, if P1 is zero, the \n** statement counter is incremented (immediate foreign key constraints).\n*/\ncase OP_FkCounter: {\n  if( pOp->p1 ){\n    db->nDeferredCons += pOp->p2;\n  }else{\n    p->nFkConstraint += pOp->p2;\n  }\n  break;\n}\n\n/* Opcode: FkIfZero P1 P2 * * *\n**\n** This opcode tests if a foreign key constraint-counter is currently zero.\n** If so, jump to instruction P2. Otherwise, fall through to the next \n** instruction.\n**\n** If P1 is non-zero, then the jump is taken if the database constraint-counter\n** is zero (the one that counts deferred constraint violations). If P1 is\n** zero, the jump is taken if the statement constraint-counter is zero\n** (immediate foreign key constraint violations).\n*/\ncase OP_FkIfZero: {         /* jump */\n  if( pOp->p1 ){\n    if( db->nDeferredCons==0 ) pc = pOp->p2-1;\n  }else{\n    if( p->nFkConstraint==0 ) pc = pOp->p2-1;\n  }\n  break;\n}\n#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n/* Opcode: MemMax P1 P2 * * *\n**\n** P1 is a register in the root frame of this VM (the root frame is\n** different from the current frame if this instruction is being executed\n** within a sub-program). Set the value of register P1 to the maximum of \n** its current value and the value in register P2.\n**\n** This instruction throws an error if the memory cell is not initially\n** an integer.\n*/\ncase OP_MemMax: {        /* in2 */\n#if 0  /* local variables moved into u.ce */\n  Mem *pIn1;\n  VdbeFrame *pFrame;\n#endif /* local variables moved into u.ce */\n  if( p->pFrame ){\n    for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);\n    u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];\n  }else{\n    u.ce.pIn1 = &aMem[pOp->p1];\n  }\n  assert( memIsValid(u.ce.pIn1) );\n  sqlite3VdbeMemIntegerify(u.ce.pIn1);\n  pIn2 = &aMem[pOp->p2];\n  sqlite3VdbeMemIntegerify(pIn2);\n  if( u.ce.pIn1->u.i<pIn2->u.i){\n    u.ce.pIn1->u.i = pIn2->u.i;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_AUTOINCREMENT */\n\n/* Opcode: IfPos P1 P2 * * *\n**\n** If the value of register P1 is 1 or greater, jump to P2.\n**\n** It is illegal to use this instruction on a register that does\n** not contain an integer.  An assertion fault will result if you try.\n*/\ncase OP_IfPos: {        /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  if( pIn1->u.i>0 ){\n     pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: IfNeg P1 P2 * * *\n**\n** If the value of register P1 is less than zero, jump to P2. \n**\n** It is illegal to use this instruction on a register that does\n** not contain an integer.  An assertion fault will result if you try.\n*/\ncase OP_IfNeg: {        /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  if( pIn1->u.i<0 ){\n     pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: IfZero P1 P2 P3 * *\n**\n** The register P1 must contain an integer.  Add literal P3 to the\n** value in register P1.  If the result is exactly 0, jump to P2. \n**\n** It is illegal to use this instruction on a register that does\n** not contain an integer.  An assertion fault will result if you try.\n*/\ncase OP_IfZero: {        /* jump, in1 */\n  pIn1 = &aMem[pOp->p1];\n  assert( pIn1->flags&MEM_Int );\n  pIn1->u.i += pOp->p3;\n  if( pIn1->u.i==0 ){\n     pc = pOp->p2 - 1;\n  }\n  break;\n}\n\n/* Opcode: AggStep * P2 P3 P4 P5\n**\n** Execute the step function for an aggregate.  The\n** function has P5 arguments.   P4 is a pointer to the FuncDef\n** structure that specifies the function.  Use register\n** P3 as the accumulator.\n**\n** The P5 arguments are taken from register P2 and its\n** successors.\n*/\ncase OP_AggStep: {\n#if 0  /* local variables moved into u.cf */\n  int n;\n  int i;\n  Mem *pMem;\n  Mem *pRec;\n  sqlite3_context ctx;\n  sqlite3_value **apVal;\n#endif /* local variables moved into u.cf */\n\n  u.cf.n = pOp->p5;\n  assert( u.cf.n>=0 );\n  u.cf.pRec = &aMem[pOp->p2];\n  u.cf.apVal = p->apArg;\n  assert( u.cf.apVal || u.cf.n==0 );\n  for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){\n    assert( memIsValid(u.cf.pRec) );\n    u.cf.apVal[u.cf.i] = u.cf.pRec;\n    memAboutToChange(p, u.cf.pRec);\n    sqlite3VdbeMemStoreType(u.cf.pRec);\n  }\n  u.cf.ctx.pFunc = pOp->p4.pFunc;\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];\n  u.cf.pMem->n++;\n  u.cf.ctx.s.flags = MEM_Null;\n  u.cf.ctx.s.z = 0;\n  u.cf.ctx.s.zMalloc = 0;\n  u.cf.ctx.s.xDel = 0;\n  u.cf.ctx.s.db = db;\n  u.cf.ctx.isError = 0;\n  u.cf.ctx.pColl = 0;\n  u.cf.ctx.skipFlag = 0;\n  if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){\n    assert( pOp>p->aOp );\n    assert( pOp[-1].p4type==P4_COLLSEQ );\n    assert( pOp[-1].opcode==OP_CollSeq );\n    u.cf.ctx.pColl = pOp[-1].p4.pColl;\n  }\n  (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */\n  if( u.cf.ctx.isError ){\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3_value_text(&u.cf.ctx.s));\n    rc = u.cf.ctx.isError;\n  }\n  if( u.cf.ctx.skipFlag ){\n    assert( pOp[-1].opcode==OP_CollSeq );\n    u.cf.i = pOp[-1].p1;\n    if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);\n  }\n\n  sqlite3VdbeMemRelease(&u.cf.ctx.s);\n\n  break;\n}\n\n/* Opcode: AggFinal P1 P2 * P4 *\n**\n** Execute the finalizer function for an aggregate.  P1 is\n** the memory location that is the accumulator for the aggregate.\n**\n** P2 is the number of arguments that the step function takes and\n** P4 is a pointer to the FuncDef for this function.  The P2\n** argument is not used by this opcode.  It is only there to disambiguate\n** functions that can take varying numbers of arguments.  The\n** P4 argument is only needed for the degenerate case where\n** the step function was not previously called.\n*/\ncase OP_AggFinal: {\n#if 0  /* local variables moved into u.cg */\n  Mem *pMem;\n#endif /* local variables moved into u.cg */\n  assert( pOp->p1>0 && pOp->p1<=p->nMem );\n  u.cg.pMem = &aMem[pOp->p1];\n  assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );\n  rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);\n  if( rc ){\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3_value_text(u.cg.pMem));\n  }\n  sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);\n  UPDATE_MAX_BLOBSIZE(u.cg.pMem);\n  if( sqlite3VdbeMemTooBig(u.cg.pMem) ){\n    goto too_big;\n  }\n  break;\n}\n\n#ifndef SQLITE_OMIT_WAL\n/* Opcode: Checkpoint P1 P2 P3 * *\n**\n** Checkpoint database P1. This is a no-op if P1 is not currently in\n** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL\n** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns\n** SQLITE_BUSY or not, respectively.  Write the number of pages in the\n** WAL after the checkpoint into mem[P3+1] and the number of pages\n** in the WAL that have been checkpointed after the checkpoint\n** completes into mem[P3+2].  However on an error, mem[P3+1] and\n** mem[P3+2] are initialized to -1.\n*/\ncase OP_Checkpoint: {\n#if 0  /* local variables moved into u.ch */\n  int i;                          /* Loop counter */\n  int aRes[3];                    /* Results */\n  Mem *pMem;                      /* Write results here */\n#endif /* local variables moved into u.ch */\n\n  u.ch.aRes[0] = 0;\n  u.ch.aRes[1] = u.ch.aRes[2] = -1;\n  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE\n       || pOp->p2==SQLITE_CHECKPOINT_FULL\n       || pOp->p2==SQLITE_CHECKPOINT_RESTART\n  );\n  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);\n  if( rc==SQLITE_BUSY ){\n    rc = SQLITE_OK;\n    u.ch.aRes[0] = 1;\n  }\n  for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){\n    sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);\n  }\n  break;\n};  \n#endif\n\n#ifndef SQLITE_OMIT_PRAGMA\n/* Opcode: JournalMode P1 P2 P3 * P5\n**\n** Change the journal mode of database P1 to P3. P3 must be one of the\n** PAGER_JOURNALMODE_XXX values. If changing between the various rollback\n** modes (delete, truncate, persist, off and memory), this is a simple\n** operation. No IO is required.\n**\n** If changing into or out of WAL mode the procedure is more complicated.\n**\n** Write a string containing the final journal-mode to register P2.\n*/\ncase OP_JournalMode: {    /* out2-prerelease */\n#if 0  /* local variables moved into u.ci */\n  Btree *pBt;                     /* Btree to change journal mode of */\n  Pager *pPager;                  /* Pager associated with pBt */\n  int eNew;                       /* New journal mode */\n  int eOld;                       /* The old journal mode */\n  const char *zFilename;          /* Name of database file for pPager */\n#endif /* local variables moved into u.ci */\n\n  u.ci.eNew = pOp->p3;\n  assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE\n       || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE\n       || u.ci.eNew==PAGER_JOURNALMODE_PERSIST\n       || u.ci.eNew==PAGER_JOURNALMODE_OFF\n       || u.ci.eNew==PAGER_JOURNALMODE_MEMORY\n       || u.ci.eNew==PAGER_JOURNALMODE_WAL\n       || u.ci.eNew==PAGER_JOURNALMODE_QUERY\n  );\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n\n  u.ci.pBt = db->aDb[pOp->p1].pBt;\n  u.ci.pPager = sqlite3BtreePager(u.ci.pBt);\n  u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);\n  if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;\n  if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;\n\n#ifndef SQLITE_OMIT_WAL\n  u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager, 1);\n\n  /* Do not allow a transition to journal_mode=WAL for a database\n  ** in temporary storage or if the VFS does not support shared memory\n  */\n  if( u.ci.eNew==PAGER_JOURNALMODE_WAL\n   && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */\n       || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */\n  ){\n    u.ci.eNew = u.ci.eOld;\n  }\n\n  if( (u.ci.eNew!=u.ci.eOld)\n   && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)\n  ){\n    if( !db->autoCommit || db->activeVdbeCnt>1 ){\n      rc = SQLITE_ERROR;\n      sqlite3SetString(&p->zErrMsg, db,\n          \"cannot change %s wal mode from within a transaction\",\n          (u.ci.eNew==PAGER_JOURNALMODE_WAL ? \"into\" : \"out of\")\n      );\n      break;\n    }else{\n\n      if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){\n        /* If leaving WAL mode, close the log file. If successful, the call\n        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log\n        ** file. An EXCLUSIVE lock may still be held on the database file\n        ** after a successful return.\n        */\n        rc = sqlite3PagerCloseWal(u.ci.pPager);\n        if( rc==SQLITE_OK ){\n          sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);\n        }\n      }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){\n        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF\n        ** as an intermediate */\n        sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);\n      }\n\n      /* Open a transaction on the database file. Regardless of the journal\n      ** mode, this transaction always uses a rollback journal.\n      */\n      assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );\n      if( rc==SQLITE_OK ){\n        rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));\n      }\n    }\n  }\n#endif /* ifndef SQLITE_OMIT_WAL */\n\n  if( rc ){\n    u.ci.eNew = u.ci.eOld;\n  }\n  u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);\n\n  pOut = &aMem[pOp->p2];\n  pOut->flags = MEM_Str|MEM_Static|MEM_Term;\n  pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);\n  pOut->n = sqlite3Strlen30(pOut->z);\n  pOut->enc = SQLITE_UTF8;\n  sqlite3VdbeChangeEncoding(pOut, encoding);\n  break;\n};\n#endif /* SQLITE_OMIT_PRAGMA */\n\n#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)\n/* Opcode: Vacuum * * * * *\n**\n** Vacuum the entire database.  This opcode will cause other virtual\n** machines to be created and run.  It may not be called from within\n** a transaction.\n*/\ncase OP_Vacuum: {\n  rc = sqlite3RunVacuum(&p->zErrMsg, db);\n  break;\n}\n#endif\n\n#if !defined(SQLITE_OMIT_AUTOVACUUM)\n/* Opcode: IncrVacuum P1 P2 * * *\n**\n** Perform a single step of the incremental vacuum procedure on\n** the P1 database. If the vacuum has finished, jump to instruction\n** P2. Otherwise, fall through to the next instruction.\n*/\ncase OP_IncrVacuum: {        /* jump */\n#if 0  /* local variables moved into u.cj */\n  Btree *pBt;\n#endif /* local variables moved into u.cj */\n\n  assert( pOp->p1>=0 && pOp->p1<db->nDb );\n  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );\n  u.cj.pBt = db->aDb[pOp->p1].pBt;\n  rc = sqlite3BtreeIncrVacuum(u.cj.pBt);\n  if( rc==SQLITE_DONE ){\n    pc = pOp->p2 - 1;\n    rc = SQLITE_OK;\n  }\n  break;\n}\n#endif\n\n/* Opcode: Expire P1 * * * *\n**\n** Cause precompiled statements to become expired. An expired statement\n** fails with an error code of SQLITE_SCHEMA if it is ever executed \n** (via sqlite3_step()).\n** \n** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,\n** then only the currently executing statement is affected. \n*/\ncase OP_Expire: {\n  if( !pOp->p1 ){\n    sqlite3ExpirePreparedStatements(db);\n  }else{\n    p->expired = 1;\n  }\n  break;\n}\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/* Opcode: TableLock P1 P2 P3 P4 *\n**\n** Obtain a lock on a particular table. This instruction is only used when\n** the shared-cache feature is enabled. \n**\n** P1 is the index of the database in sqlite3.aDb[] of the database\n** on which the lock is acquired.  A readlock is obtained if P3==0 or\n** a write lock if P3==1.\n**\n** P2 contains the root-page of the table to lock.\n**\n** P4 contains a pointer to the name of the table being locked. This is only\n** used to generate an error message if the lock cannot be obtained.\n*/\ncase OP_TableLock: {\n  u8 isWriteLock = (u8)pOp->p3;\n  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){\n    int p1 = pOp->p1; \n    assert( p1>=0 && p1<db->nDb );\n    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );\n    assert( isWriteLock==0 || isWriteLock==1 );\n    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);\n    if( (rc&0xFF)==SQLITE_LOCKED ){\n      const char *z = pOp->p4.z;\n      sqlite3SetString(&p->zErrMsg, db, \"database table is locked: %s\", z);\n    }\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_SHARED_CACHE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VBegin * * * P4 *\n**\n** P4 may be a pointer to an sqlite3_vtab structure. If so, call the \n** xBegin method for that table.\n**\n** Also, whether or not P4 is set, check that this is not being called from\n** within a callback to a virtual table xSync() method. If it is, the error\n** code will be set to SQLITE_LOCKED.\n*/\ncase OP_VBegin: {\n#if 0  /* local variables moved into u.ck */\n  VTable *pVTab;\n#endif /* local variables moved into u.ck */\n  u.ck.pVTab = pOp->p4.pVtab;\n  rc = sqlite3VtabBegin(db, u.ck.pVTab);\n  if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VCreate P1 * * P4 *\n**\n** P4 is the name of a virtual table in database P1. Call the xCreate method\n** for that table.\n*/\ncase OP_VCreate: {\n  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VDestroy P1 * * P4 *\n**\n** P4 is the name of a virtual table in database P1.  Call the xDestroy method\n** of that table.\n*/\ncase OP_VDestroy: {\n  p->inVtabMethod = 2;\n  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);\n  p->inVtabMethod = 0;\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VOpen P1 * * P4 *\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** P1 is a cursor number.  This opcode opens a cursor to the virtual\n** table and stores that cursor in P1.\n*/\ncase OP_VOpen: {\n#if 0  /* local variables moved into u.cl */\n  VdbeCursor *pCur;\n  sqlite3_vtab_cursor *pVtabCursor;\n  sqlite3_vtab *pVtab;\n  sqlite3_module *pModule;\n#endif /* local variables moved into u.cl */\n\n  u.cl.pCur = 0;\n  u.cl.pVtabCursor = 0;\n  u.cl.pVtab = pOp->p4.pVtab->pVtab;\n  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;\n  assert(u.cl.pVtab && u.cl.pModule);\n  rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);\n  importVtabErrMsg(p, u.cl.pVtab);\n  if( SQLITE_OK==rc ){\n    /* Initialize sqlite3_vtab_cursor base class */\n    u.cl.pVtabCursor->pVtab = u.cl.pVtab;\n\n    /* Initialise vdbe cursor object */\n    u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);\n    if( u.cl.pCur ){\n      u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;\n      u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;\n    }else{\n      db->mallocFailed = 1;\n      u.cl.pModule->xClose(u.cl.pVtabCursor);\n    }\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VFilter P1 P2 P3 P4 *\n**\n** P1 is a cursor opened using VOpen.  P2 is an address to jump to if\n** the filtered result set is empty.\n**\n** P4 is either NULL or a string that was generated by the xBestIndex\n** method of the module.  The interpretation of the P4 string is left\n** to the module implementation.\n**\n** This opcode invokes the xFilter method on the virtual table specified\n** by P1.  The integer query plan parameter to xFilter is stored in register\n** P3. Register P3+1 stores the argc parameter to be passed to the\n** xFilter method. Registers P3+2..P3+1+argc are the argc\n** additional parameters which are passed to\n** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.\n**\n** A jump is made to P2 if the result set after filtering would be empty.\n*/\ncase OP_VFilter: {   /* jump */\n#if 0  /* local variables moved into u.cm */\n  int nArg;\n  int iQuery;\n  const sqlite3_module *pModule;\n  Mem *pQuery;\n  Mem *pArgc;\n  sqlite3_vtab_cursor *pVtabCursor;\n  sqlite3_vtab *pVtab;\n  VdbeCursor *pCur;\n  int res;\n  int i;\n  Mem **apArg;\n#endif /* local variables moved into u.cm */\n\n  u.cm.pQuery = &aMem[pOp->p3];\n  u.cm.pArgc = &u.cm.pQuery[1];\n  u.cm.pCur = p->apCsr[pOp->p1];\n  assert( memIsValid(u.cm.pQuery) );\n  REGISTER_TRACE(pOp->p3, u.cm.pQuery);\n  assert( u.cm.pCur->pVtabCursor );\n  u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;\n  u.cm.pVtab = u.cm.pVtabCursor->pVtab;\n  u.cm.pModule = u.cm.pVtab->pModule;\n\n  /* Grab the index number and argc parameters */\n  assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );\n  u.cm.nArg = (int)u.cm.pArgc->u.i;\n  u.cm.iQuery = (int)u.cm.pQuery->u.i;\n\n  /* Invoke the xFilter method */\n  {\n    u.cm.res = 0;\n    u.cm.apArg = p->apArg;\n    for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){\n      u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];\n      sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);\n    }\n\n    p->inVtabMethod = 1;\n    rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);\n    p->inVtabMethod = 0;\n    importVtabErrMsg(p, u.cm.pVtab);\n    if( rc==SQLITE_OK ){\n      u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);\n    }\n\n    if( u.cm.res ){\n      pc = pOp->p2 - 1;\n    }\n  }\n  u.cm.pCur->nullRow = 0;\n\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VColumn P1 P2 P3 * *\n**\n** Store the value of the P2-th column of\n** the row of the virtual-table that the \n** P1 cursor is pointing to into register P3.\n*/\ncase OP_VColumn: {\n#if 0  /* local variables moved into u.cn */\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n  Mem *pDest;\n  sqlite3_context sContext;\n#endif /* local variables moved into u.cn */\n\n  VdbeCursor *pCur = p->apCsr[pOp->p1];\n  assert( pCur->pVtabCursor );\n  assert( pOp->p3>0 && pOp->p3<=p->nMem );\n  u.cn.pDest = &aMem[pOp->p3];\n  memAboutToChange(p, u.cn.pDest);\n  if( pCur->nullRow ){\n    sqlite3VdbeMemSetNull(u.cn.pDest);\n    break;\n  }\n  u.cn.pVtab = pCur->pVtabCursor->pVtab;\n  u.cn.pModule = u.cn.pVtab->pModule;\n  assert( u.cn.pModule->xColumn );\n  memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));\n\n  /* The output cell may already have a buffer allocated. Move\n  ** the current contents to u.cn.sContext.s so in case the user-function\n  ** can use the already allocated buffer instead of allocating a\n  ** new one.\n  */\n  sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);\n  MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);\n\n  rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);\n  importVtabErrMsg(p, u.cn.pVtab);\n  if( u.cn.sContext.isError ){\n    rc = u.cn.sContext.isError;\n  }\n\n  /* Copy the result of the function to the P3 register. We\n  ** do this regardless of whether or not an error occurred to ensure any\n  ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.\n  */\n  sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);\n  sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);\n  REGISTER_TRACE(pOp->p3, u.cn.pDest);\n  UPDATE_MAX_BLOBSIZE(u.cn.pDest);\n\n  if( sqlite3VdbeMemTooBig(u.cn.pDest) ){\n    goto too_big;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VNext P1 P2 * * *\n**\n** Advance virtual table P1 to the next row in its result set and\n** jump to instruction P2.  Or, if the virtual table has reached\n** the end of its result set, then fall through to the next instruction.\n*/\ncase OP_VNext: {   /* jump */\n#if 0  /* local variables moved into u.co */\n  sqlite3_vtab *pVtab;\n  const sqlite3_module *pModule;\n  int res;\n  VdbeCursor *pCur;\n#endif /* local variables moved into u.co */\n\n  u.co.res = 0;\n  u.co.pCur = p->apCsr[pOp->p1];\n  assert( u.co.pCur->pVtabCursor );\n  if( u.co.pCur->nullRow ){\n    break;\n  }\n  u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;\n  u.co.pModule = u.co.pVtab->pModule;\n  assert( u.co.pModule->xNext );\n\n  /* Invoke the xNext() method of the module. There is no way for the\n  ** underlying implementation to return an error if one occurs during\n  ** xNext(). Instead, if an error occurs, true is returned (indicating that\n  ** data is available) and the error code returned when xColumn or\n  ** some other method is next invoked on the save virtual table cursor.\n  */\n  p->inVtabMethod = 1;\n  rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);\n  p->inVtabMethod = 0;\n  importVtabErrMsg(p, u.co.pVtab);\n  if( rc==SQLITE_OK ){\n    u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);\n  }\n\n  if( !u.co.res ){\n    /* If there is data, jump to P2 */\n    pc = pOp->p2 - 1;\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VRename P1 * * P4 *\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** This opcode invokes the corresponding xRename method. The value\n** in register P1 is passed as the zName argument to the xRename method.\n*/\ncase OP_VRename: {\n#if 0  /* local variables moved into u.cp */\n  sqlite3_vtab *pVtab;\n  Mem *pName;\n#endif /* local variables moved into u.cp */\n\n  u.cp.pVtab = pOp->p4.pVtab->pVtab;\n  u.cp.pName = &aMem[pOp->p1];\n  assert( u.cp.pVtab->pModule->xRename );\n  assert( memIsValid(u.cp.pName) );\n  REGISTER_TRACE(pOp->p1, u.cp.pName);\n  assert( u.cp.pName->flags & MEM_Str );\n  testcase( u.cp.pName->enc==SQLITE_UTF8 );\n  testcase( u.cp.pName->enc==SQLITE_UTF16BE );\n  testcase( u.cp.pName->enc==SQLITE_UTF16LE );\n  rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);\n  if( rc==SQLITE_OK ){\n    rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);\n    importVtabErrMsg(p, u.cp.pVtab);\n    p->expired = 0;\n  }\n  break;\n}\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Opcode: VUpdate P1 P2 P3 P4 *\n**\n** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.\n** This opcode invokes the corresponding xUpdate method. P2 values\n** are contiguous memory cells starting at P3 to pass to the xUpdate \n** invocation. The value in register (P3+P2-1) corresponds to the \n** p2th element of the argv array passed to xUpdate.\n**\n** The xUpdate method will do a DELETE or an INSERT or both.\n** The argv[0] element (which corresponds to memory cell P3)\n** is the rowid of a row to delete.  If argv[0] is NULL then no \n** deletion occurs.  The argv[1] element is the rowid of the new \n** row.  This can be NULL to have the virtual table select the new \n** rowid for itself.  The subsequent elements in the array are \n** the values of columns in the new row.\n**\n** If P2==1 then no insert is performed.  argv[0] is the rowid of\n** a row to delete.\n**\n** P1 is a boolean flag. If it is set to true and the xUpdate call\n** is successful, then the value returned by sqlite3_last_insert_rowid() \n** is set to the value of the rowid for the row just inserted.\n*/\ncase OP_VUpdate: {\n#if 0  /* local variables moved into u.cq */\n  sqlite3_vtab *pVtab;\n  sqlite3_module *pModule;\n  int nArg;\n  int i;\n  sqlite_int64 rowid;\n  Mem **apArg;\n  Mem *pX;\n#endif /* local variables moved into u.cq */\n\n  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback\n       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace\n  );\n  u.cq.pVtab = pOp->p4.pVtab->pVtab;\n  u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;\n  u.cq.nArg = pOp->p2;\n  assert( pOp->p4type==P4_VTAB );\n  if( ALWAYS(u.cq.pModule->xUpdate) ){\n    u8 vtabOnConflict = db->vtabOnConflict;\n    u.cq.apArg = p->apArg;\n    u.cq.pX = &aMem[pOp->p3];\n    for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){\n      assert( memIsValid(u.cq.pX) );\n      memAboutToChange(p, u.cq.pX);\n      sqlite3VdbeMemStoreType(u.cq.pX);\n      u.cq.apArg[u.cq.i] = u.cq.pX;\n      u.cq.pX++;\n    }\n    db->vtabOnConflict = pOp->p5;\n    rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);\n    db->vtabOnConflict = vtabOnConflict;\n    importVtabErrMsg(p, u.cq.pVtab);\n    if( rc==SQLITE_OK && pOp->p1 ){\n      assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );\n      db->lastRowid = lastRowid = u.cq.rowid;\n    }\n    if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){\n      if( pOp->p5==OE_Ignore ){\n        rc = SQLITE_OK;\n      }else{\n        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);\n      }\n    }else{\n      p->nChange++;\n    }\n  }\n  break;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifndef  SQLITE_OMIT_PAGER_PRAGMAS\n/* Opcode: Pagecount P1 P2 * * *\n**\n** Write the current number of pages in database P1 to memory cell P2.\n*/\ncase OP_Pagecount: {            /* out2-prerelease */\n  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);\n  break;\n}\n#endif\n\n\n#ifndef  SQLITE_OMIT_PAGER_PRAGMAS\n/* Opcode: MaxPgcnt P1 P2 P3 * *\n**\n** Try to set the maximum page count for database P1 to the value in P3.\n** Do not let the maximum page count fall below the current page count and\n** do not change the maximum page count value if P3==0.\n**\n** Store the maximum page count after the change in register P2.\n*/\ncase OP_MaxPgcnt: {            /* out2-prerelease */\n  unsigned int newMax;\n  Btree *pBt;\n\n  pBt = db->aDb[pOp->p1].pBt;\n  newMax = 0;\n  if( pOp->p3 ){\n    newMax = sqlite3BtreeLastPage(pBt);\n    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;\n  }\n  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);\n  break;\n}\n#endif\n\n\n#ifndef SQLITE_OMIT_TRACE\n/* Opcode: Trace * * * P4 *\n**\n** If tracing is enabled (by the sqlite3_trace()) interface, then\n** the UTF-8 string contained in P4 is emitted on the trace callback.\n*/\ncase OP_Trace: {\n#if 0  /* local variables moved into u.cr */\n  char *zTrace;\n  char *z;\n#endif /* local variables moved into u.cr */\n\n  if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){\n    u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);\n    db->xTrace(db->pTraceArg, u.cr.z);\n    sqlite3DbFree(db, u.cr.z);\n  }\n#ifdef SQLITE_DEBUG\n  if( (db->flags & SQLITE_SqlTrace)!=0\n   && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0\n  ){\n    sqlite3DebugPrintf(\"SQL-trace: %s\\n\", u.cr.zTrace);\n  }\n#endif /* SQLITE_DEBUG */\n  break;\n}\n#endif\n\n\n/* Opcode: Noop * * * * *\n**\n** Do nothing.  This instruction is often useful as a jump\n** destination.\n*/\n/*\n** The magic Explain opcode are only inserted when explain==2 (which\n** is to say when the EXPLAIN QUERY PLAN syntax is used.)\n** This opcode records information from the optimizer.  It is the\n** the same as a no-op.  This opcodesnever appears in a real VM program.\n*/\ndefault: {          /* This is really OP_Noop and OP_Explain */\n  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );\n  break;\n}\n\n/*****************************************************************************\n** The cases of the switch statement above this line should all be indented\n** by 6 spaces.  But the left-most 6 spaces have been removed to improve the\n** readability.  From this point on down, the normal indentation rules are\n** restored.\n*****************************************************************************/\n    }\n\n#ifdef VDBE_PROFILE\n    {\n      u64 elapsed = sqlite3Hwtime() - start;\n      pOp->cycles += elapsed;\n      pOp->cnt++;\n#if 0\n        fprintf(stdout, \"%10llu \", elapsed);\n        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);\n#endif\n    }\n#endif\n\n    /* The following code adds nothing to the actual functionality\n    ** of the program.  It is only here for testing and debugging.\n    ** On the other hand, it does burn CPU cycles every time through\n    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.\n    */\n#ifndef NDEBUG\n    assert( pc>=-1 && pc<p->nOp );\n\n#ifdef SQLITE_DEBUG\n    if( p->trace ){\n      if( rc!=0 ) fprintf(p->trace,\"rc=%d\\n\",rc);\n      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){\n        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);\n      }\n      if( pOp->opflags & OPFLG_OUT3 ){\n        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);\n      }\n    }\n#endif  /* SQLITE_DEBUG */\n#endif  /* NDEBUG */\n  }  /* The end of the for(;;) loop the loops through opcodes */\n\n  /* If we reach this point, it means that execution is finished with\n  ** an error of some kind.\n  */\nvdbe_error_halt:\n  assert( rc );\n  p->rc = rc;\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  sqlite3_log(rc, \"statement aborts at %d: [%s] %s\", \n                   pc, p->zSql, p->zErrMsg);\n  sqlite3VdbeHalt(p);\n  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;\n  rc = SQLITE_ERROR;\n  if( resetSchemaOnFault>0 ){\n    sqlite3ResetOneSchema(db, resetSchemaOnFault-1);\n  }\n\n  /* This is the only way out of this procedure.  We have to\n  ** release the mutexes on btrees that were acquired at the\n  ** top. */\nvdbe_return:\n  db->lastRowid = lastRowid;\n  sqlite3VdbeLeave(p);\n  return rc;\n\n  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH\n  ** is encountered.\n  */\ntoo_big:\n  sqlite3SetString(&p->zErrMsg, db, \"string or blob too big\");\n  rc = SQLITE_TOOBIG;\n  goto vdbe_error_halt;\n\n  /* Jump to here if a malloc() fails.\n  */\nno_mem:\n  db->mallocFailed = 1;\n  sqlite3SetString(&p->zErrMsg, db, \"out of memory\");\n  rc = SQLITE_NOMEM;\n  goto vdbe_error_halt;\n\n  /* Jump to here for any other kind of fatal error.  The \"rc\" variable\n  ** should hold the error number.\n  */\nabort_due_to_error:\n  assert( p->zErrMsg==0 );\n  if( db->mallocFailed ) rc = SQLITE_NOMEM;\n  if( rc!=SQLITE_IOERR_NOMEM ){\n    sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3ErrStr(rc));\n  }\n  goto vdbe_error_halt;\n\n  /* Jump to here if the sqlite3_interrupt() API sets the interrupt\n  ** flag.\n  */\nabort_due_to_interrupt:\n  assert( db->u1.isInterrupted );\n  rc = SQLITE_INTERRUPT;\n  p->rc = rc;\n  sqlite3SetString(&p->zErrMsg, db, \"%s\", sqlite3ErrStr(rc));\n  goto vdbe_error_halt;\n}\n\n/************** End of vdbe.c ************************************************/\n/************** Begin file vdbeblob.c ****************************************/\n/*\n** 2007 May 1\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code used to implement incremental BLOB I/O.\n*/\n\n\n#ifndef SQLITE_OMIT_INCRBLOB\n\n/*\n** Valid sqlite3_blob* handles point to Incrblob structures.\n*/\ntypedef struct Incrblob Incrblob;\nstruct Incrblob {\n  int flags;              /* Copy of \"flags\" passed to sqlite3_blob_open() */\n  int nByte;              /* Size of open blob, in bytes */\n  int iOffset;            /* Byte offset of blob in cursor data */\n  int iCol;               /* Table column this handle is open on */\n  BtCursor *pCsr;         /* Cursor pointing at blob row */\n  sqlite3_stmt *pStmt;    /* Statement holding cursor open */\n  sqlite3 *db;            /* The associated database */\n};\n\n\n/*\n** This function is used by both blob_open() and blob_reopen(). It seeks\n** the b-tree cursor associated with blob handle p to point to row iRow.\n** If successful, SQLITE_OK is returned and subsequent calls to\n** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.\n**\n** If an error occurs, or if the specified row does not exist or does not\n** contain a value of type TEXT or BLOB in the column nominated when the\n** blob handle was opened, then an error code is returned and *pzErr may\n** be set to point to a buffer containing an error message. It is the\n** responsibility of the caller to free the error message buffer using\n** sqlite3DbFree().\n**\n** If an error does occur, then the b-tree cursor is closed. All subsequent\n** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will \n** immediately return SQLITE_ABORT.\n*/\nstatic int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){\n  int rc;                         /* Error code */\n  char *zErr = 0;                 /* Error message */\n  Vdbe *v = (Vdbe *)p->pStmt;\n\n  /* Set the value of the SQL statements only variable to integer iRow. \n  ** This is done directly instead of using sqlite3_bind_int64() to avoid \n  ** triggering asserts related to mutexes.\n  */\n  assert( v->aVar[0].flags&MEM_Int );\n  v->aVar[0].u.i = iRow;\n\n  rc = sqlite3_step(p->pStmt);\n  if( rc==SQLITE_ROW ){\n    u32 type = v->apCsr[0]->aType[p->iCol];\n    if( type<12 ){\n      zErr = sqlite3MPrintf(p->db, \"cannot open value of type %s\",\n          type==0?\"null\": type==7?\"real\": \"integer\"\n      );\n      rc = SQLITE_ERROR;\n      sqlite3_finalize(p->pStmt);\n      p->pStmt = 0;\n    }else{\n      p->iOffset = v->apCsr[0]->aOffset[p->iCol];\n      p->nByte = sqlite3VdbeSerialTypeLen(type);\n      p->pCsr =  v->apCsr[0]->pCursor;\n      sqlite3BtreeEnterCursor(p->pCsr);\n      sqlite3BtreeCacheOverflow(p->pCsr);\n      sqlite3BtreeLeaveCursor(p->pCsr);\n    }\n  }\n\n  if( rc==SQLITE_ROW ){\n    rc = SQLITE_OK;\n  }else if( p->pStmt ){\n    rc = sqlite3_finalize(p->pStmt);\n    p->pStmt = 0;\n    if( rc==SQLITE_OK ){\n      zErr = sqlite3MPrintf(p->db, \"no such rowid: %lld\", iRow);\n      rc = SQLITE_ERROR;\n    }else{\n      zErr = sqlite3MPrintf(p->db, \"%s\", sqlite3_errmsg(p->db));\n    }\n  }\n\n  assert( rc!=SQLITE_OK || zErr==0 );\n  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );\n\n  *pzErr = zErr;\n  return rc;\n}\n\n/*\n** Open a blob handle.\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3* db,            /* The database connection */\n  const char *zDb,        /* The attached database containing the blob */\n  const char *zTable,     /* The table containing the blob */\n  const char *zColumn,    /* The column containing the blob */\n  sqlite_int64 iRow,      /* The row containing the glob */\n  int flags,              /* True -> read/write access, false -> read-only */\n  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */\n){\n  int nAttempt = 0;\n  int iCol;               /* Index of zColumn in row-record */\n\n  /* This VDBE program seeks a btree cursor to the identified \n  ** db/table/row entry. The reason for using a vdbe program instead\n  ** of writing code to use the b-tree layer directly is that the\n  ** vdbe program will take advantage of the various transaction,\n  ** locking and error handling infrastructure built into the vdbe.\n  **\n  ** After seeking the cursor, the vdbe executes an OP_ResultRow.\n  ** Code external to the Vdbe then \"borrows\" the b-tree cursor and\n  ** uses it to implement the blob_read(), blob_write() and \n  ** blob_bytes() functions.\n  **\n  ** The sqlite3_blob_close() function finalizes the vdbe program,\n  ** which closes the b-tree cursor and (possibly) commits the \n  ** transaction.\n  */\n  static const VdbeOpList openBlob[] = {\n    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */\n    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */\n    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */\n\n    /* One of the following two instructions is replaced by an OP_Noop. */\n    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */\n    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */\n\n    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */\n    {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */\n    {OP_Column, 0, 0, 1},          /* 7  */\n    {OP_ResultRow, 1, 0, 0},       /* 8  */\n    {OP_Goto, 0, 5, 0},            /* 9  */\n    {OP_Close, 0, 0, 0},           /* 10 */\n    {OP_Halt, 0, 0, 0},            /* 11 */\n  };\n\n  int rc = SQLITE_OK;\n  char *zErr = 0;\n  Table *pTab;\n  Parse *pParse = 0;\n  Incrblob *pBlob = 0;\n\n  flags = !!flags;                /* flags = (flags ? 1 : 0); */\n  *ppBlob = 0;\n\n  sqlite3_mutex_enter(db->mutex);\n\n  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));\n  if( !pBlob ) goto blob_open_out;\n  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));\n  if( !pParse ) goto blob_open_out;\n\n  do {\n    memset(pParse, 0, sizeof(Parse));\n    pParse->db = db;\n    sqlite3DbFree(db, zErr);\n    zErr = 0;\n\n    sqlite3BtreeEnterAll(db);\n    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);\n    if( pTab && IsVirtual(pTab) ){\n      pTab = 0;\n      sqlite3ErrorMsg(pParse, \"cannot open virtual table: %s\", zTable);\n    }\n#ifndef SQLITE_OMIT_VIEW\n    if( pTab && pTab->pSelect ){\n      pTab = 0;\n      sqlite3ErrorMsg(pParse, \"cannot open view: %s\", zTable);\n    }\n#endif\n    if( !pTab ){\n      if( pParse->zErrMsg ){\n        sqlite3DbFree(db, zErr);\n        zErr = pParse->zErrMsg;\n        pParse->zErrMsg = 0;\n      }\n      rc = SQLITE_ERROR;\n      sqlite3BtreeLeaveAll(db);\n      goto blob_open_out;\n    }\n\n    /* Now search pTab for the exact column. */\n    for(iCol=0; iCol<pTab->nCol; iCol++) {\n      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){\n        break;\n      }\n    }\n    if( iCol==pTab->nCol ){\n      sqlite3DbFree(db, zErr);\n      zErr = sqlite3MPrintf(db, \"no such column: \\\"%s\\\"\", zColumn);\n      rc = SQLITE_ERROR;\n      sqlite3BtreeLeaveAll(db);\n      goto blob_open_out;\n    }\n\n    /* If the value is being opened for writing, check that the\n    ** column is not indexed, and that it is not part of a foreign key. \n    ** It is against the rules to open a column to which either of these\n    ** descriptions applies for writing.  */\n    if( flags ){\n      const char *zFault = 0;\n      Index *pIdx;\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n      if( db->flags&SQLITE_ForeignKeys ){\n        /* Check that the column is not part of an FK child key definition. It\n        ** is not necessary to check if it is part of a parent key, as parent\n        ** key columns must be indexed. The check below will pick up this \n        ** case.  */\n        FKey *pFKey;\n        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n          int j;\n          for(j=0; j<pFKey->nCol; j++){\n            if( pFKey->aCol[j].iFrom==iCol ){\n              zFault = \"foreign key\";\n            }\n          }\n        }\n      }\n#endif\n      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n        int j;\n        for(j=0; j<pIdx->nColumn; j++){\n          if( pIdx->aiColumn[j]==iCol ){\n            zFault = \"indexed\";\n          }\n        }\n      }\n      if( zFault ){\n        sqlite3DbFree(db, zErr);\n        zErr = sqlite3MPrintf(db, \"cannot open %s column for writing\", zFault);\n        rc = SQLITE_ERROR;\n        sqlite3BtreeLeaveAll(db);\n        goto blob_open_out;\n      }\n    }\n\n    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);\n    assert( pBlob->pStmt || db->mallocFailed );\n    if( pBlob->pStmt ){\n      Vdbe *v = (Vdbe *)pBlob->pStmt;\n      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n\n      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);\n\n\n      /* Configure the OP_Transaction */\n      sqlite3VdbeChangeP1(v, 0, iDb);\n      sqlite3VdbeChangeP2(v, 0, flags);\n\n      /* Configure the OP_VerifyCookie */\n      sqlite3VdbeChangeP1(v, 1, iDb);\n      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);\n      sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);\n\n      /* Make sure a mutex is held on the table to be accessed */\n      sqlite3VdbeUsesBtree(v, iDb); \n\n      /* Configure the OP_TableLock instruction */\n#ifdef SQLITE_OMIT_SHARED_CACHE\n      sqlite3VdbeChangeToNoop(v, 2);\n#else\n      sqlite3VdbeChangeP1(v, 2, iDb);\n      sqlite3VdbeChangeP2(v, 2, pTab->tnum);\n      sqlite3VdbeChangeP3(v, 2, flags);\n      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);\n#endif\n\n      /* Remove either the OP_OpenWrite or OpenRead. Set the P2 \n      ** parameter of the other to pTab->tnum.  */\n      sqlite3VdbeChangeToNoop(v, 4 - flags);\n      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);\n      sqlite3VdbeChangeP3(v, 3 + flags, iDb);\n\n      /* Configure the number of columns. Configure the cursor to\n      ** think that the table has one more column than it really\n      ** does. An OP_Column to retrieve this imaginary column will\n      ** always return an SQL NULL. This is useful because it means\n      ** we can invoke OP_Column to fill in the vdbe cursors type \n      ** and offset cache without causing any IO.\n      */\n      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);\n      sqlite3VdbeChangeP2(v, 7, pTab->nCol);\n      if( !db->mallocFailed ){\n        pParse->nVar = 1;\n        pParse->nMem = 1;\n        pParse->nTab = 1;\n        sqlite3VdbeMakeReady(v, pParse);\n      }\n    }\n   \n    pBlob->flags = flags;\n    pBlob->iCol = iCol;\n    pBlob->db = db;\n    sqlite3BtreeLeaveAll(db);\n    if( db->mallocFailed ){\n      goto blob_open_out;\n    }\n    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);\n    rc = blobSeekToRow(pBlob, iRow, &zErr);\n  } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );\n\nblob_open_out:\n  if( rc==SQLITE_OK && db->mallocFailed==0 ){\n    *ppBlob = (sqlite3_blob *)pBlob;\n  }else{\n    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);\n    sqlite3DbFree(db, pBlob);\n  }\n  sqlite3Error(db, rc, (zErr ? \"%s\" : 0), zErr);\n  sqlite3DbFree(db, zErr);\n  sqlite3StackFree(db, pParse);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Close a blob handle that was previously created using\n** sqlite3_blob_open().\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){\n  Incrblob *p = (Incrblob *)pBlob;\n  int rc;\n  sqlite3 *db;\n\n  if( p ){\n    db = p->db;\n    sqlite3_mutex_enter(db->mutex);\n    rc = sqlite3_finalize(p->pStmt);\n    sqlite3DbFree(db, p);\n    sqlite3_mutex_leave(db->mutex);\n  }else{\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/*\n** Perform a read or write operation on a blob\n*/\nstatic int blobReadWrite(\n  sqlite3_blob *pBlob, \n  void *z, \n  int n, \n  int iOffset, \n  int (*xCall)(BtCursor*, u32, u32, void*)\n){\n  int rc;\n  Incrblob *p = (Incrblob *)pBlob;\n  Vdbe *v;\n  sqlite3 *db;\n\n  if( p==0 ) return SQLITE_MISUSE_BKPT;\n  db = p->db;\n  sqlite3_mutex_enter(db->mutex);\n  v = (Vdbe*)p->pStmt;\n\n  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){\n    /* Request is out of range. Return a transient error. */\n    rc = SQLITE_ERROR;\n    sqlite3Error(db, SQLITE_ERROR, 0);\n  }else if( v==0 ){\n    /* If there is no statement handle, then the blob-handle has\n    ** already been invalidated. Return SQLITE_ABORT in this case.\n    */\n    rc = SQLITE_ABORT;\n  }else{\n    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is\n    ** returned, clean-up the statement handle.\n    */\n    assert( db == v->db );\n    sqlite3BtreeEnterCursor(p->pCsr);\n    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);\n    sqlite3BtreeLeaveCursor(p->pCsr);\n    if( rc==SQLITE_ABORT ){\n      sqlite3VdbeFinalize(v);\n      p->pStmt = 0;\n    }else{\n      db->errCode = rc;\n      v->rc = rc;\n    }\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Read data from a blob handle.\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){\n  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);\n}\n\n/*\n** Write data to a blob handle.\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){\n  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);\n}\n\n/*\n** Query a blob handle for the size of the data.\n**\n** The Incrblob.nByte field is fixed for the lifetime of the Incrblob\n** so no mutex is required for access.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){\n  Incrblob *p = (Incrblob *)pBlob;\n  return (p && p->pStmt) ? p->nByte : 0;\n}\n\n/*\n** Move an existing blob handle to point to a different row of the same\n** database table.\n**\n** If an error occurs, or if the specified row does not exist or does not\n** contain a blob or text value, then an error code is returned and the\n** database handle error code and message set. If this happens, then all \n** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) \n** immediately return SQLITE_ABORT.\n*/\nSQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){\n  int rc;\n  Incrblob *p = (Incrblob *)pBlob;\n  sqlite3 *db;\n\n  if( p==0 ) return SQLITE_MISUSE_BKPT;\n  db = p->db;\n  sqlite3_mutex_enter(db->mutex);\n\n  if( p->pStmt==0 ){\n    /* If there is no statement handle, then the blob-handle has\n    ** already been invalidated. Return SQLITE_ABORT in this case.\n    */\n    rc = SQLITE_ABORT;\n  }else{\n    char *zErr;\n    rc = blobSeekToRow(p, iRow, &zErr);\n    if( rc!=SQLITE_OK ){\n      sqlite3Error(db, rc, (zErr ? \"%s\" : 0), zErr);\n      sqlite3DbFree(db, zErr);\n    }\n    assert( rc!=SQLITE_SCHEMA );\n  }\n\n  rc = sqlite3ApiExit(db, rc);\n  assert( rc==SQLITE_OK || p->pStmt==0 );\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#endif /* #ifndef SQLITE_OMIT_INCRBLOB */\n\n/************** End of vdbeblob.c ********************************************/\n/************** Begin file vdbesort.c ****************************************/\n/*\n** 2011 July 9\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code for the VdbeSorter object, used in concert with\n** a VdbeCursor to sort large numbers of keys (as may be required, for\n** example, by CREATE INDEX statements on tables too large to fit in main\n** memory).\n*/\n\n\n#ifndef SQLITE_OMIT_MERGE_SORT\n\ntypedef struct VdbeSorterIter VdbeSorterIter;\ntypedef struct SorterRecord SorterRecord;\ntypedef struct FileWriter FileWriter;\n\n/*\n** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:\n**\n** As keys are added to the sorter, they are written to disk in a series\n** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly\n** the same as the cache-size allowed for temporary databases. In order\n** to allow the caller to extract keys from the sorter in sorted order,\n** all PMAs currently stored on disk must be merged together. This comment\n** describes the data structure used to do so. The structure supports \n** merging any number of arrays in a single pass with no redundant comparison \n** operations.\n**\n** The aIter[] array contains an iterator for each of the PMAs being merged.\n** An aIter[] iterator either points to a valid key or else is at EOF. For \n** the purposes of the paragraphs below, we assume that the array is actually \n** N elements in size, where N is the smallest power of 2 greater to or equal \n** to the number of iterators being merged. The extra aIter[] elements are \n** treated as if they are empty (always at EOF).\n**\n** The aTree[] array is also N elements in size. The value of N is stored in\n** the VdbeSorter.nTree variable.\n**\n** The final (N/2) elements of aTree[] contain the results of comparing\n** pairs of iterator keys together. Element i contains the result of \n** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the\n** aTree element is set to the index of it. \n**\n** For the purposes of this comparison, EOF is considered greater than any\n** other key value. If the keys are equal (only possible with two EOF\n** values), it doesn't matter which index is stored.\n**\n** The (N/4) elements of aTree[] that preceed the final (N/2) described \n** above contains the index of the smallest of each block of 4 iterators.\n** And so on. So that aTree[1] contains the index of the iterator that \n** currently points to the smallest key value. aTree[0] is unused.\n**\n** Example:\n**\n**     aIter[0] -> Banana\n**     aIter[1] -> Feijoa\n**     aIter[2] -> Elderberry\n**     aIter[3] -> Currant\n**     aIter[4] -> Grapefruit\n**     aIter[5] -> Apple\n**     aIter[6] -> Durian\n**     aIter[7] -> EOF\n**\n**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }\n**\n** The current element is \"Apple\" (the value of the key indicated by \n** iterator 5). When the Next() operation is invoked, iterator 5 will\n** be advanced to the next key in its segment. Say the next key is\n** \"Eggplant\":\n**\n**     aIter[5] -> Eggplant\n**\n** The contents of aTree[] are updated first by comparing the new iterator\n** 5 key to the current key of iterator 4 (still \"Grapefruit\"). The iterator\n** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.\n** The value of iterator 6 - \"Durian\" - is now smaller than that of iterator\n** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),\n** so the value written into element 1 of the array is 0. As follows:\n**\n**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }\n**\n** In other words, each time we advance to the next sorter element, log2(N)\n** key comparison operations are required, where N is the number of segments\n** being merged (rounded up to the next power of 2).\n*/\nstruct VdbeSorter {\n  i64 iWriteOff;                  /* Current write offset within file pTemp1 */\n  i64 iReadOff;                   /* Current read offset within file pTemp1 */\n  int nInMemory;                  /* Current size of pRecord list as PMA */\n  int nTree;                      /* Used size of aTree/aIter (power of 2) */\n  int nPMA;                       /* Number of PMAs stored in pTemp1 */\n  int mnPmaSize;                  /* Minimum PMA size, in bytes */\n  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */\n  VdbeSorterIter *aIter;          /* Array of iterators to merge */\n  int *aTree;                     /* Current state of incremental merge */\n  sqlite3_file *pTemp1;           /* PMA file 1 */\n  SorterRecord *pRecord;          /* Head of in-memory record list */\n  UnpackedRecord *pUnpacked;      /* Used to unpack keys */\n};\n\n/*\n** The following type is an iterator for a PMA. It caches the current key in \n** variables nKey/aKey. If the iterator is at EOF, pFile==0.\n*/\nstruct VdbeSorterIter {\n  i64 iReadOff;                   /* Current read offset */\n  i64 iEof;                       /* 1 byte past EOF for this iterator */\n  int nAlloc;                     /* Bytes of space at aAlloc */\n  int nKey;                       /* Number of bytes in key */\n  sqlite3_file *pFile;            /* File iterator is reading from */\n  u8 *aAlloc;                     /* Allocated space */\n  u8 *aKey;                       /* Pointer to current key */\n  u8 *aBuffer;                    /* Current read buffer */\n  int nBuffer;                    /* Size of read buffer in bytes */\n};\n\n/*\n** An instance of this structure is used to organize the stream of records\n** being written to files by the merge-sort code into aligned, page-sized\n** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go\n** faster on many operating systems.\n*/\nstruct FileWriter {\n  int eFWErr;                     /* Non-zero if in an error state */\n  u8 *aBuffer;                    /* Pointer to write buffer */\n  int nBuffer;                    /* Size of write buffer in bytes */\n  int iBufStart;                  /* First byte of buffer to write */\n  int iBufEnd;                    /* Last byte of buffer to write */\n  i64 iWriteOff;                  /* Offset of start of buffer in file */\n  sqlite3_file *pFile;            /* File to write to */\n};\n\n/*\n** A structure to store a single record. All in-memory records are connected\n** together into a linked list headed at VdbeSorter.pRecord using the \n** SorterRecord.pNext pointer.\n*/\nstruct SorterRecord {\n  void *pVal;\n  int nVal;\n  SorterRecord *pNext;\n};\n\n/* Minimum allowable value for the VdbeSorter.nWorking variable */\n#define SORTER_MIN_WORKING 10\n\n/* Maximum number of segments to merge in a single pass. */\n#define SORTER_MAX_MERGE_COUNT 16\n\n/*\n** Free all memory belonging to the VdbeSorterIter object passed as the second\n** argument. All structure fields are set to zero before returning.\n*/\nstatic void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){\n  sqlite3DbFree(db, pIter->aAlloc);\n  sqlite3DbFree(db, pIter->aBuffer);\n  memset(pIter, 0, sizeof(VdbeSorterIter));\n}\n\n/*\n** Read nByte bytes of data from the stream of data iterated by object p.\n** If successful, set *ppOut to point to a buffer containing the data\n** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite\n** error code.\n**\n** The buffer indicated by *ppOut may only be considered valid until the\n** next call to this function.\n*/\nstatic int vdbeSorterIterRead(\n  sqlite3 *db,                    /* Database handle (for malloc) */\n  VdbeSorterIter *p,              /* Iterator */\n  int nByte,                      /* Bytes of data to read */\n  u8 **ppOut                      /* OUT: Pointer to buffer containing data */\n){\n  int iBuf;                       /* Offset within buffer to read from */\n  int nAvail;                     /* Bytes of data available in buffer */\n  assert( p->aBuffer );\n\n  /* If there is no more data to be read from the buffer, read the next \n  ** p->nBuffer bytes of data from the file into it. Or, if there are less\n  ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */\n  iBuf = p->iReadOff % p->nBuffer;\n  if( iBuf==0 ){\n    int nRead;                    /* Bytes to read from disk */\n    int rc;                       /* sqlite3OsRead() return code */\n\n    /* Determine how many bytes of data to read. */\n    nRead = (int)(p->iEof - p->iReadOff);\n    if( nRead>p->nBuffer ) nRead = p->nBuffer;\n    assert( nRead>0 );\n\n    /* Read data from the file. Return early if an error occurs. */\n    rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);\n    assert( rc!=SQLITE_IOERR_SHORT_READ );\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  nAvail = p->nBuffer - iBuf; \n\n  if( nByte<=nAvail ){\n    /* The requested data is available in the in-memory buffer. In this\n    ** case there is no need to make a copy of the data, just return a \n    ** pointer into the buffer to the caller.  */\n    *ppOut = &p->aBuffer[iBuf];\n    p->iReadOff += nByte;\n  }else{\n    /* The requested data is not all available in the in-memory buffer.\n    ** In this case, allocate space at p->aAlloc[] to copy the requested\n    ** range into. Then return a copy of pointer p->aAlloc to the caller.  */\n    int nRem;                     /* Bytes remaining to copy */\n\n    /* Extend the p->aAlloc[] allocation if required. */\n    if( p->nAlloc<nByte ){\n      int nNew = p->nAlloc*2;\n      while( nByte>nNew ) nNew = nNew*2;\n      p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);\n      if( !p->aAlloc ) return SQLITE_NOMEM;\n      p->nAlloc = nNew;\n    }\n\n    /* Copy as much data as is available in the buffer into the start of\n    ** p->aAlloc[].  */\n    memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);\n    p->iReadOff += nAvail;\n    nRem = nByte - nAvail;\n\n    /* The following loop copies up to p->nBuffer bytes per iteration into\n    ** the p->aAlloc[] buffer.  */\n    while( nRem>0 ){\n      int rc;                     /* vdbeSorterIterRead() return code */\n      int nCopy;                  /* Number of bytes to copy */\n      u8 *aNext;                  /* Pointer to buffer to copy data from */\n\n      nCopy = nRem;\n      if( nRem>p->nBuffer ) nCopy = p->nBuffer;\n      rc = vdbeSorterIterRead(db, p, nCopy, &aNext);\n      if( rc!=SQLITE_OK ) return rc;\n      assert( aNext!=p->aAlloc );\n      memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);\n      nRem -= nCopy;\n    }\n\n    *ppOut = p->aAlloc;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Read a varint from the stream of data accessed by p. Set *pnOut to\n** the value read.\n*/\nstatic int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){\n  int iBuf;\n\n  iBuf = p->iReadOff % p->nBuffer;\n  if( iBuf && (p->nBuffer-iBuf)>=9 ){\n    p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);\n  }else{\n    u8 aVarint[16], *a;\n    int i = 0, rc;\n    do{\n      rc = vdbeSorterIterRead(db, p, 1, &a);\n      if( rc ) return rc;\n      aVarint[(i++)&0xf] = a[0];\n    }while( (a[0]&0x80)!=0 );\n    sqlite3GetVarint(aVarint, pnOut);\n  }\n\n  return SQLITE_OK;\n}\n\n\n/*\n** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if\n** no error occurs, or an SQLite error code if one does.\n*/\nstatic int vdbeSorterIterNext(\n  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */\n  VdbeSorterIter *pIter           /* Iterator to advance */\n){\n  int rc;                         /* Return Code */\n  u64 nRec = 0;                   /* Size of record in bytes */\n\n  if( pIter->iReadOff>=pIter->iEof ){\n    /* This is an EOF condition */\n    vdbeSorterIterZero(db, pIter);\n    return SQLITE_OK;\n  }\n\n  rc = vdbeSorterIterVarint(db, pIter, &nRec);\n  if( rc==SQLITE_OK ){\n    pIter->nKey = (int)nRec;\n    rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);\n  }\n\n  return rc;\n}\n\n/*\n** Initialize iterator pIter to scan through the PMA stored in file pFile\n** starting at offset iStart and ending at offset iEof-1. This function \n** leaves the iterator pointing to the first key in the PMA (or EOF if the \n** PMA is empty).\n*/\nstatic int vdbeSorterIterInit(\n  sqlite3 *db,                    /* Database handle */\n  const VdbeSorter *pSorter,      /* Sorter object */\n  i64 iStart,                     /* Start offset in pFile */\n  VdbeSorterIter *pIter,          /* Iterator to populate */\n  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */\n){\n  int rc = SQLITE_OK;\n  int nBuf;\n\n  nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);\n\n  assert( pSorter->iWriteOff>iStart );\n  assert( pIter->aAlloc==0 );\n  assert( pIter->aBuffer==0 );\n  pIter->pFile = pSorter->pTemp1;\n  pIter->iReadOff = iStart;\n  pIter->nAlloc = 128;\n  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);\n  pIter->nBuffer = nBuf;\n  pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);\n\n  if( !pIter->aBuffer ){\n    rc = SQLITE_NOMEM;\n  }else{\n    int iBuf;\n\n    iBuf = iStart % nBuf;\n    if( iBuf ){\n      int nRead = nBuf - iBuf;\n      if( (iStart + nRead) > pSorter->iWriteOff ){\n        nRead = (int)(pSorter->iWriteOff - iStart);\n      }\n      rc = sqlite3OsRead(\n          pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart\n      );\n      assert( rc!=SQLITE_IOERR_SHORT_READ );\n    }\n\n    if( rc==SQLITE_OK ){\n      u64 nByte;                       /* Size of PMA in bytes */\n      pIter->iEof = pSorter->iWriteOff;\n      rc = vdbeSorterIterVarint(db, pIter, &nByte);\n      pIter->iEof = pIter->iReadOff + nByte;\n      *pnByte += nByte;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = vdbeSorterIterNext(db, pIter);\n  }\n  return rc;\n}\n\n\n/*\n** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, \n** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions\n** used by the comparison. If an error occurs, return an SQLite error code.\n** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive\n** value, depending on whether key1 is smaller, equal to or larger than key2.\n**\n** If the bOmitRowid argument is non-zero, assume both keys end in a rowid\n** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid\n** is true and key1 contains even a single NULL value, it is considered to\n** be less than key2. Even if key2 also contains NULL values.\n**\n** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace\n** has been allocated and contains an unpacked record that is used as key2.\n*/\nstatic void vdbeSorterCompare(\n  const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */\n  int bOmitRowid,                 /* Ignore rowid field at end of keys */\n  const void *pKey1, int nKey1,   /* Left side of comparison */\n  const void *pKey2, int nKey2,   /* Right side of comparison */\n  int *pRes                       /* OUT: Result of comparison */\n){\n  KeyInfo *pKeyInfo = pCsr->pKeyInfo;\n  VdbeSorter *pSorter = pCsr->pSorter;\n  UnpackedRecord *r2 = pSorter->pUnpacked;\n  int i;\n\n  if( pKey2 ){\n    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);\n  }\n\n  if( bOmitRowid ){\n    r2->nField = pKeyInfo->nField;\n    assert( r2->nField>0 );\n    for(i=0; i<r2->nField; i++){\n      if( r2->aMem[i].flags & MEM_Null ){\n        *pRes = -1;\n        return;\n      }\n    }\n    r2->flags |= UNPACKED_PREFIX_MATCH;\n  }\n\n  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);\n}\n\n/*\n** This function is called to compare two iterator keys when merging \n** multiple b-tree segments. Parameter iOut is the index of the aTree[] \n** value to recalculate.\n*/\nstatic int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  int i1;\n  int i2;\n  int iRes;\n  VdbeSorterIter *p1;\n  VdbeSorterIter *p2;\n\n  assert( iOut<pSorter->nTree && iOut>0 );\n\n  if( iOut>=(pSorter->nTree/2) ){\n    i1 = (iOut - pSorter->nTree/2) * 2;\n    i2 = i1 + 1;\n  }else{\n    i1 = pSorter->aTree[iOut*2];\n    i2 = pSorter->aTree[iOut*2+1];\n  }\n\n  p1 = &pSorter->aIter[i1];\n  p2 = &pSorter->aIter[i2];\n\n  if( p1->pFile==0 ){\n    iRes = i2;\n  }else if( p2->pFile==0 ){\n    iRes = i1;\n  }else{\n    int res;\n    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */\n    vdbeSorterCompare(\n        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res\n    );\n    if( res<=0 ){\n      iRes = i1;\n    }else{\n      iRes = i2;\n    }\n  }\n\n  pSorter->aTree[iOut] = iRes;\n  return SQLITE_OK;\n}\n\n/*\n** Initialize the temporary index cursor just opened as a sorter cursor.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){\n  int pgsz;                       /* Page size of main database */\n  int mxCache;                    /* Cache size */\n  VdbeSorter *pSorter;            /* The new sorter */\n  char *d;                        /* Dummy */\n\n  assert( pCsr->pKeyInfo && pCsr->pBt==0 );\n  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));\n  if( pSorter==0 ){\n    return SQLITE_NOMEM;\n  }\n  \n  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);\n  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;\n  assert( pSorter->pUnpacked==(UnpackedRecord *)d );\n\n  if( !sqlite3TempInMemory(db) ){\n    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);\n    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;\n    mxCache = db->aDb[0].pSchema->cache_size;\n    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;\n    pSorter->mxPmaSize = mxCache * pgsz;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Free the list of sorted records starting at pRecord.\n*/\nstatic void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){\n  SorterRecord *p;\n  SorterRecord *pNext;\n  for(p=pRecord; p; p=pNext){\n    pNext = p->pNext;\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.\n*/\nSQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  if( pSorter ){\n    if( pSorter->aIter ){\n      int i;\n      for(i=0; i<pSorter->nTree; i++){\n        vdbeSorterIterZero(db, &pSorter->aIter[i]);\n      }\n      sqlite3DbFree(db, pSorter->aIter);\n    }\n    if( pSorter->pTemp1 ){\n      sqlite3OsCloseFree(pSorter->pTemp1);\n    }\n    vdbeSorterRecordFree(db, pSorter->pRecord);\n    sqlite3DbFree(db, pSorter->pUnpacked);\n    sqlite3DbFree(db, pSorter);\n    pCsr->pSorter = 0;\n  }\n}\n\n/*\n** Allocate space for a file-handle and open a temporary file. If successful,\n** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.\n** Otherwise, set *ppFile to 0 and return an SQLite error code.\n*/\nstatic int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){\n  int dummy;\n  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,\n      SQLITE_OPEN_TEMP_JOURNAL |\n      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |\n      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy\n  );\n}\n\n/*\n** Merge the two sorted lists p1 and p2 into a single list.\n** Set *ppOut to the head of the new list.\n*/\nstatic void vdbeSorterMerge(\n  const VdbeCursor *pCsr,         /* For pKeyInfo */\n  SorterRecord *p1,               /* First list to merge */\n  SorterRecord *p2,               /* Second list to merge */\n  SorterRecord **ppOut            /* OUT: Head of merged list */\n){\n  SorterRecord *pFinal = 0;\n  SorterRecord **pp = &pFinal;\n  void *pVal2 = p2 ? p2->pVal : 0;\n\n  while( p1 && p2 ){\n    int res;\n    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);\n    if( res<=0 ){\n      *pp = p1;\n      pp = &p1->pNext;\n      p1 = p1->pNext;\n      pVal2 = 0;\n    }else{\n      *pp = p2;\n       pp = &p2->pNext;\n      p2 = p2->pNext;\n      if( p2==0 ) break;\n      pVal2 = p2->pVal;\n    }\n  }\n  *pp = p1 ? p1 : p2;\n  *ppOut = pFinal;\n}\n\n/*\n** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK\n** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error\n** occurs.\n*/\nstatic int vdbeSorterSort(const VdbeCursor *pCsr){\n  int i;\n  SorterRecord **aSlot;\n  SorterRecord *p;\n  VdbeSorter *pSorter = pCsr->pSorter;\n\n  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));\n  if( !aSlot ){\n    return SQLITE_NOMEM;\n  }\n\n  p = pSorter->pRecord;\n  while( p ){\n    SorterRecord *pNext = p->pNext;\n    p->pNext = 0;\n    for(i=0; aSlot[i]; i++){\n      vdbeSorterMerge(pCsr, p, aSlot[i], &p);\n      aSlot[i] = 0;\n    }\n    aSlot[i] = p;\n    p = pNext;\n  }\n\n  p = 0;\n  for(i=0; i<64; i++){\n    vdbeSorterMerge(pCsr, p, aSlot[i], &p);\n  }\n  pSorter->pRecord = p;\n\n  sqlite3_free(aSlot);\n  return SQLITE_OK;\n}\n\n/*\n** Initialize a file-writer object.\n*/\nstatic void fileWriterInit(\n  sqlite3 *db,                    /* Database (for malloc) */\n  sqlite3_file *pFile,            /* File to write to */\n  FileWriter *p,                  /* Object to populate */\n  i64 iStart                      /* Offset of pFile to begin writing at */\n){\n  int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);\n\n  memset(p, 0, sizeof(FileWriter));\n  p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);\n  if( !p->aBuffer ){\n    p->eFWErr = SQLITE_NOMEM;\n  }else{\n    p->iBufEnd = p->iBufStart = (iStart % nBuf);\n    p->iWriteOff = iStart - p->iBufStart;\n    p->nBuffer = nBuf;\n    p->pFile = pFile;\n  }\n}\n\n/*\n** Write nData bytes of data to the file-write object. Return SQLITE_OK\n** if successful, or an SQLite error code if an error occurs.\n*/\nstatic void fileWriterWrite(FileWriter *p, u8 *pData, int nData){\n  int nRem = nData;\n  while( nRem>0 && p->eFWErr==0 ){\n    int nCopy = nRem;\n    if( nCopy>(p->nBuffer - p->iBufEnd) ){\n      nCopy = p->nBuffer - p->iBufEnd;\n    }\n\n    memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);\n    p->iBufEnd += nCopy;\n    if( p->iBufEnd==p->nBuffer ){\n      p->eFWErr = sqlite3OsWrite(p->pFile, \n          &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, \n          p->iWriteOff + p->iBufStart\n      );\n      p->iBufStart = p->iBufEnd = 0;\n      p->iWriteOff += p->nBuffer;\n    }\n    assert( p->iBufEnd<p->nBuffer );\n\n    nRem -= nCopy;\n  }\n}\n\n/*\n** Flush any buffered data to disk and clean up the file-writer object.\n** The results of using the file-writer after this call are undefined.\n** Return SQLITE_OK if flushing the buffered data succeeds or is not \n** required. Otherwise, return an SQLite error code.\n**\n** Before returning, set *piEof to the offset immediately following the\n** last byte written to the file.\n*/\nstatic int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){\n  int rc;\n  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){\n    p->eFWErr = sqlite3OsWrite(p->pFile, \n        &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, \n        p->iWriteOff + p->iBufStart\n    );\n  }\n  *piEof = (p->iWriteOff + p->iBufEnd);\n  sqlite3DbFree(db, p->aBuffer);\n  rc = p->eFWErr;\n  memset(p, 0, sizeof(FileWriter));\n  return rc;\n}\n\n/*\n** Write value iVal encoded as a varint to the file-write object. Return \n** SQLITE_OK if successful, or an SQLite error code if an error occurs.\n*/\nstatic void fileWriterWriteVarint(FileWriter *p, u64 iVal){\n  int nByte; \n  u8 aByte[10];\n  nByte = sqlite3PutVarint(aByte, iVal);\n  fileWriterWrite(p, aByte, nByte);\n}\n\n/*\n** Write the current contents of the in-memory linked-list to a PMA. Return\n** SQLITE_OK if successful, or an SQLite error code otherwise.\n**\n** The format of a PMA is:\n**\n**     * A varint. This varint contains the total number of bytes of content\n**       in the PMA (not including the varint itself).\n**\n**     * One or more records packed end-to-end in order of ascending keys. \n**       Each record consists of a varint followed by a blob of data (the \n**       key). The varint is the number of bytes in the blob of data.\n*/\nstatic int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){\n  int rc = SQLITE_OK;             /* Return code */\n  VdbeSorter *pSorter = pCsr->pSorter;\n  FileWriter writer;\n\n  memset(&writer, 0, sizeof(FileWriter));\n\n  if( pSorter->nInMemory==0 ){\n    assert( pSorter->pRecord==0 );\n    return rc;\n  }\n\n  rc = vdbeSorterSort(pCsr);\n\n  /* If the first temporary PMA file has not been opened, open it now. */\n  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){\n    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);\n    assert( rc!=SQLITE_OK || pSorter->pTemp1 );\n    assert( pSorter->iWriteOff==0 );\n    assert( pSorter->nPMA==0 );\n  }\n\n  if( rc==SQLITE_OK ){\n    SorterRecord *p;\n    SorterRecord *pNext = 0;\n\n    fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);\n    pSorter->nPMA++;\n    fileWriterWriteVarint(&writer, pSorter->nInMemory);\n    for(p=pSorter->pRecord; p; p=pNext){\n      pNext = p->pNext;\n      fileWriterWriteVarint(&writer, p->nVal);\n      fileWriterWrite(&writer, p->pVal, p->nVal);\n      sqlite3DbFree(db, p);\n    }\n    pSorter->pRecord = p;\n    rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);\n  }\n\n  return rc;\n}\n\n/*\n** Add a record to the sorter.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterWrite(\n  sqlite3 *db,                    /* Database handle */\n  const VdbeCursor *pCsr,               /* Sorter cursor */\n  Mem *pVal                       /* Memory cell containing record */\n){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  int rc = SQLITE_OK;             /* Return Code */\n  SorterRecord *pNew;             /* New list element */\n\n  assert( pSorter );\n  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;\n\n  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));\n  if( pNew==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    pNew->pVal = (void *)&pNew[1];\n    memcpy(pNew->pVal, pVal->z, pVal->n);\n    pNew->nVal = pVal->n;\n    pNew->pNext = pSorter->pRecord;\n    pSorter->pRecord = pNew;\n  }\n\n  /* See if the contents of the sorter should now be written out. They\n  ** are written out when either of the following are true:\n  **\n  **   * The total memory allocated for the in-memory list is greater \n  **     than (page-size * cache-size), or\n  **\n  **   * The total memory allocated for the in-memory list is greater \n  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.\n  */\n  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (\n        (pSorter->nInMemory>pSorter->mxPmaSize)\n     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())\n  )){\n#ifdef SQLITE_DEBUG\n    i64 nExpect = pSorter->iWriteOff\n                + sqlite3VarintLen(pSorter->nInMemory)\n                + pSorter->nInMemory;\n#endif\n    rc = vdbeSorterListToPMA(db, pCsr);\n    pSorter->nInMemory = 0;\n    assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );\n  }\n\n  return rc;\n}\n\n/*\n** Helper function for sqlite3VdbeSorterRewind(). \n*/\nstatic int vdbeSorterInitMerge(\n  sqlite3 *db,                    /* Database handle */\n  const VdbeCursor *pCsr,         /* Cursor handle for this sorter */\n  i64 *pnByte                     /* Sum of bytes in all opened PMAs */\n){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Used to iterator through aIter[] */\n  i64 nByte = 0;                  /* Total bytes in all opened PMAs */\n\n  /* Initialize the iterators. */\n  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){\n    VdbeSorterIter *pIter = &pSorter->aIter[i];\n    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);\n    pSorter->iReadOff = pIter->iEof;\n    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );\n    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;\n  }\n\n  /* Initialize the aTree[] array. */\n  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){\n    rc = vdbeSorterDoCompare(pCsr, i);\n  }\n\n  *pnByte = nByte;\n  return rc;\n}\n\n/*\n** Once the sorter has been populated, this function is called to prepare\n** for iterating through its contents in sorted order.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  int rc;                         /* Return code */\n  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */\n  i64 iWrite2 = 0;                /* Write offset for pTemp2 */\n  int nIter;                      /* Number of iterators used */\n  int nByte;                      /* Bytes of space required for aIter/aTree */\n  int N = 2;                      /* Power of 2 >= nIter */\n\n  assert( pSorter );\n\n  /* If no data has been written to disk, then do not do so now. Instead,\n  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly\n  ** from the in-memory list.  */\n  if( pSorter->nPMA==0 ){\n    *pbEof = !pSorter->pRecord;\n    assert( pSorter->aTree==0 );\n    return vdbeSorterSort(pCsr);\n  }\n\n  /* Write the current in-memory list to a PMA. */\n  rc = vdbeSorterListToPMA(db, pCsr);\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Allocate space for aIter[] and aTree[]. */\n  nIter = pSorter->nPMA;\n  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;\n  assert( nIter>0 );\n  while( N<nIter ) N += N;\n  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));\n  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);\n  if( !pSorter->aIter ) return SQLITE_NOMEM;\n  pSorter->aTree = (int *)&pSorter->aIter[N];\n  pSorter->nTree = N;\n\n  do {\n    int iNew;                     /* Index of new, merged, PMA */\n\n    for(iNew=0; \n        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; \n        iNew++\n    ){\n      int rc2;                    /* Return code from fileWriterFinish() */\n      FileWriter writer;          /* Object used to write to disk */\n      i64 nWrite;                 /* Number of bytes in new PMA */\n\n      memset(&writer, 0, sizeof(FileWriter));\n\n      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,\n      ** initialize an iterator for each of them and break out of the loop.\n      ** These iterators will be incrementally merged as the VDBE layer calls\n      ** sqlite3VdbeSorterNext().\n      **\n      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,\n      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs\n      ** are merged into a single PMA that is written to file pTemp2.\n      */\n      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);\n      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );\n      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){\n        break;\n      }\n\n      /* Open the second temp file, if it is not already open. */\n      if( pTemp2==0 ){\n        assert( iWrite2==0 );\n        rc = vdbeSorterOpenTempFile(db, &pTemp2);\n      }\n\n      if( rc==SQLITE_OK ){\n        int bEof = 0;\n        fileWriterInit(db, pTemp2, &writer, iWrite2);\n        fileWriterWriteVarint(&writer, nWrite);\n        while( rc==SQLITE_OK && bEof==0 ){\n          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];\n          assert( pIter->pFile );\n\n          fileWriterWriteVarint(&writer, pIter->nKey);\n          fileWriterWrite(&writer, pIter->aKey, pIter->nKey);\n          rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);\n        }\n        rc2 = fileWriterFinish(db, &writer, &iWrite2);\n        if( rc==SQLITE_OK ) rc = rc2;\n      }\n    }\n\n    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){\n      break;\n    }else{\n      sqlite3_file *pTmp = pSorter->pTemp1;\n      pSorter->nPMA = iNew;\n      pSorter->pTemp1 = pTemp2;\n      pTemp2 = pTmp;\n      pSorter->iWriteOff = iWrite2;\n      pSorter->iReadOff = 0;\n      iWrite2 = 0;\n    }\n  }while( rc==SQLITE_OK );\n\n  if( pTemp2 ){\n    sqlite3OsCloseFree(pTemp2);\n  }\n  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);\n  return rc;\n}\n\n/*\n** Advance to the next element in the sorter.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  int rc;                         /* Return code */\n\n  if( pSorter->aTree ){\n    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */\n    int i;                        /* Index of aTree[] to recalculate */\n\n    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);\n    for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){\n      rc = vdbeSorterDoCompare(pCsr, i);\n    }\n\n    *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);\n  }else{\n    SorterRecord *pFree = pSorter->pRecord;\n    pSorter->pRecord = pFree->pNext;\n    pFree->pNext = 0;\n    vdbeSorterRecordFree(db, pFree);\n    *pbEof = !pSorter->pRecord;\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/*\n** Return a pointer to a buffer owned by the sorter that contains the \n** current key.\n*/\nstatic void *vdbeSorterRowkey(\n  const VdbeSorter *pSorter,      /* Sorter object */\n  int *pnKey                      /* OUT: Size of current key in bytes */\n){\n  void *pKey;\n  if( pSorter->aTree ){\n    VdbeSorterIter *pIter;\n    pIter = &pSorter->aIter[ pSorter->aTree[1] ];\n    *pnKey = pIter->nKey;\n    pKey = pIter->aKey;\n  }else{\n    *pnKey = pSorter->pRecord->nVal;\n    pKey = pSorter->pRecord->pVal;\n  }\n  return pKey;\n}\n\n/*\n** Copy the current sorter key into the memory cell pOut.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  void *pKey; int nKey;           /* Sorter key to copy into pOut */\n\n  pKey = vdbeSorterRowkey(pSorter, &nKey);\n  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){\n    return SQLITE_NOMEM;\n  }\n  pOut->n = nKey;\n  MemSetTypeFlag(pOut, MEM_Blob);\n  memcpy(pOut->z, pKey, nKey);\n\n  return SQLITE_OK;\n}\n\n/*\n** Compare the key in memory cell pVal with the key that the sorter cursor\n** passed as the first argument currently points to. For the purposes of\n** the comparison, ignore the rowid field at the end of each record.\n**\n** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).\n** Otherwise, set *pRes to a negative, zero or positive value if the\n** key in pVal is smaller than, equal to or larger than the current sorter\n** key.\n*/\nSQLITE_PRIVATE int sqlite3VdbeSorterCompare(\n  const VdbeCursor *pCsr,         /* Sorter cursor */\n  Mem *pVal,                      /* Value to compare to current sorter key */\n  int *pRes                       /* OUT: Result of comparison */\n){\n  VdbeSorter *pSorter = pCsr->pSorter;\n  void *pKey; int nKey;           /* Sorter key to compare pVal with */\n\n  pKey = vdbeSorterRowkey(pSorter, &nKey);\n  vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);\n  return SQLITE_OK;\n}\n\n#endif /* #ifndef SQLITE_OMIT_MERGE_SORT */\n\n/************** End of vdbesort.c ********************************************/\n/************** Begin file journal.c *****************************************/\n/*\n** 2007 August 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file implements a special kind of sqlite3_file object used\n** by SQLite to create journal files if the atomic-write optimization\n** is enabled.\n**\n** The distinctive characteristic of this sqlite3_file is that the\n** actual on disk file is created lazily. When the file is created,\n** the caller specifies a buffer size for an in-memory buffer to\n** be used to service read() and write() requests. The actual file\n** on disk is not created or populated until either:\n**\n**   1) The in-memory representation grows too large for the allocated \n**      buffer, or\n**   2) The sqlite3JournalCreate() function is called.\n*/\n#ifdef SQLITE_ENABLE_ATOMIC_WRITE\n\n\n/*\n** A JournalFile object is a subclass of sqlite3_file used by\n** as an open file handle for journal files.\n*/\nstruct JournalFile {\n  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */\n  int nBuf;                       /* Size of zBuf[] in bytes */\n  char *zBuf;                     /* Space to buffer journal writes */\n  int iSize;                      /* Amount of zBuf[] currently used */\n  int flags;                      /* xOpen flags */\n  sqlite3_vfs *pVfs;              /* The \"real\" underlying VFS */\n  sqlite3_file *pReal;            /* The \"real\" underlying file descriptor */\n  const char *zJournal;           /* Name of the journal file */\n};\ntypedef struct JournalFile JournalFile;\n\n/*\n** If it does not already exists, create and populate the on-disk file \n** for JournalFile p.\n*/\nstatic int createFile(JournalFile *p){\n  int rc = SQLITE_OK;\n  if( !p->pReal ){\n    sqlite3_file *pReal = (sqlite3_file *)&p[1];\n    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);\n    if( rc==SQLITE_OK ){\n      p->pReal = pReal;\n      if( p->iSize>0 ){\n        assert(p->iSize<=p->nBuf);\n        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Close the file.\n*/\nstatic int jrnlClose(sqlite3_file *pJfd){\n  JournalFile *p = (JournalFile *)pJfd;\n  if( p->pReal ){\n    sqlite3OsClose(p->pReal);\n  }\n  sqlite3_free(p->zBuf);\n  return SQLITE_OK;\n}\n\n/*\n** Read data from the file.\n*/\nstatic int jrnlRead(\n  sqlite3_file *pJfd,    /* The journal file from which to read */\n  void *zBuf,            /* Put the results here */\n  int iAmt,              /* Number of bytes to read */\n  sqlite_int64 iOfst     /* Begin reading at this offset */\n){\n  int rc = SQLITE_OK;\n  JournalFile *p = (JournalFile *)pJfd;\n  if( p->pReal ){\n    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);\n  }else if( (iAmt+iOfst)>p->iSize ){\n    rc = SQLITE_IOERR_SHORT_READ;\n  }else{\n    memcpy(zBuf, &p->zBuf[iOfst], iAmt);\n  }\n  return rc;\n}\n\n/*\n** Write data to the file.\n*/\nstatic int jrnlWrite(\n  sqlite3_file *pJfd,    /* The journal file into which to write */\n  const void *zBuf,      /* Take data to be written from here */\n  int iAmt,              /* Number of bytes to write */\n  sqlite_int64 iOfst     /* Begin writing at this offset into the file */\n){\n  int rc = SQLITE_OK;\n  JournalFile *p = (JournalFile *)pJfd;\n  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){\n    rc = createFile(p);\n  }\n  if( rc==SQLITE_OK ){\n    if( p->pReal ){\n      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);\n    }else{\n      memcpy(&p->zBuf[iOfst], zBuf, iAmt);\n      if( p->iSize<(iOfst+iAmt) ){\n        p->iSize = (iOfst+iAmt);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Truncate the file.\n*/\nstatic int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){\n  int rc = SQLITE_OK;\n  JournalFile *p = (JournalFile *)pJfd;\n  if( p->pReal ){\n    rc = sqlite3OsTruncate(p->pReal, size);\n  }else if( size<p->iSize ){\n    p->iSize = size;\n  }\n  return rc;\n}\n\n/*\n** Sync the file.\n*/\nstatic int jrnlSync(sqlite3_file *pJfd, int flags){\n  int rc;\n  JournalFile *p = (JournalFile *)pJfd;\n  if( p->pReal ){\n    rc = sqlite3OsSync(p->pReal, flags);\n  }else{\n    rc = SQLITE_OK;\n  }\n  return rc;\n}\n\n/*\n** Query the size of the file in bytes.\n*/\nstatic int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){\n  int rc = SQLITE_OK;\n  JournalFile *p = (JournalFile *)pJfd;\n  if( p->pReal ){\n    rc = sqlite3OsFileSize(p->pReal, pSize);\n  }else{\n    *pSize = (sqlite_int64) p->iSize;\n  }\n  return rc;\n}\n\n/*\n** Table of methods for JournalFile sqlite3_file object.\n*/\nstatic struct sqlite3_io_methods JournalFileMethods = {\n  1,             /* iVersion */\n  jrnlClose,     /* xClose */\n  jrnlRead,      /* xRead */\n  jrnlWrite,     /* xWrite */\n  jrnlTruncate,  /* xTruncate */\n  jrnlSync,      /* xSync */\n  jrnlFileSize,  /* xFileSize */\n  0,             /* xLock */\n  0,             /* xUnlock */\n  0,             /* xCheckReservedLock */\n  0,             /* xFileControl */\n  0,             /* xSectorSize */\n  0,             /* xDeviceCharacteristics */\n  0,             /* xShmMap */\n  0,             /* xShmLock */\n  0,             /* xShmBarrier */\n  0              /* xShmUnmap */\n};\n\n/* \n** Open a journal file.\n*/\nSQLITE_PRIVATE int sqlite3JournalOpen(\n  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */\n  const char *zName,         /* Name of the journal file */\n  sqlite3_file *pJfd,        /* Preallocated, blank file handle */\n  int flags,                 /* Opening flags */\n  int nBuf                   /* Bytes buffered before opening the file */\n){\n  JournalFile *p = (JournalFile *)pJfd;\n  memset(p, 0, sqlite3JournalSize(pVfs));\n  if( nBuf>0 ){\n    p->zBuf = sqlite3MallocZero(nBuf);\n    if( !p->zBuf ){\n      return SQLITE_NOMEM;\n    }\n  }else{\n    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);\n  }\n  p->pMethod = &JournalFileMethods;\n  p->nBuf = nBuf;\n  p->flags = flags;\n  p->zJournal = zName;\n  p->pVfs = pVfs;\n  return SQLITE_OK;\n}\n\n/*\n** If the argument p points to a JournalFile structure, and the underlying\n** file has not yet been created, create it now.\n*/\nSQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){\n  if( p->pMethods!=&JournalFileMethods ){\n    return SQLITE_OK;\n  }\n  return createFile((JournalFile *)p);\n}\n\n/* \n** Return the number of bytes required to store a JournalFile that uses vfs\n** pVfs to create the underlying on-disk files.\n*/\nSQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){\n  return (pVfs->szOsFile+sizeof(JournalFile));\n}\n#endif\n\n/************** End of journal.c *********************************************/\n/************** Begin file memjournal.c **************************************/\n/*\n** 2008 October 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains code use to implement an in-memory rollback journal.\n** The in-memory rollback journal is used to journal transactions for\n** \":memory:\" databases and when the journal_mode=MEMORY pragma is used.\n*/\n\n/* Forward references to internal structures */\ntypedef struct MemJournal MemJournal;\ntypedef struct FilePoint FilePoint;\ntypedef struct FileChunk FileChunk;\n\n/* Space to hold the rollback journal is allocated in increments of\n** this many bytes.\n**\n** The size chosen is a little less than a power of two.  That way,\n** the FileChunk object will have a size that almost exactly fills\n** a power-of-two allocation.  This mimimizes wasted space in power-of-two\n** memory allocators.\n*/\n#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))\n\n/* Macro to find the minimum of two numeric values.\n*/\n#ifndef MIN\n# define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n\n/*\n** The rollback journal is composed of a linked list of these structures.\n*/\nstruct FileChunk {\n  FileChunk *pNext;               /* Next chunk in the journal */\n  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */\n};\n\n/*\n** An instance of this object serves as a cursor into the rollback journal.\n** The cursor can be either for reading or writing.\n*/\nstruct FilePoint {\n  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */\n  FileChunk *pChunk;              /* Specific chunk into which cursor points */\n};\n\n/*\n** This subclass is a subclass of sqlite3_file.  Each open memory-journal\n** is an instance of this class.\n*/\nstruct MemJournal {\n  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */\n  FileChunk *pFirst;              /* Head of in-memory chunk-list */\n  FilePoint endpoint;             /* Pointer to the end of the file */\n  FilePoint readpoint;            /* Pointer to the end of the last xRead() */\n};\n\n/*\n** Read data from the in-memory journal file.  This is the implementation\n** of the sqlite3_vfs.xRead method.\n*/\nstatic int memjrnlRead(\n  sqlite3_file *pJfd,    /* The journal file from which to read */\n  void *zBuf,            /* Put the results here */\n  int iAmt,              /* Number of bytes to read */\n  sqlite_int64 iOfst     /* Begin reading at this offset */\n){\n  MemJournal *p = (MemJournal *)pJfd;\n  u8 *zOut = zBuf;\n  int nRead = iAmt;\n  int iChunkOffset;\n  FileChunk *pChunk;\n\n  /* SQLite never tries to read past the end of a rollback journal file */\n  assert( iOfst+iAmt<=p->endpoint.iOffset );\n\n  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){\n    sqlite3_int64 iOff = 0;\n    for(pChunk=p->pFirst; \n        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;\n        pChunk=pChunk->pNext\n    ){\n      iOff += JOURNAL_CHUNKSIZE;\n    }\n  }else{\n    pChunk = p->readpoint.pChunk;\n  }\n\n  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);\n  do {\n    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;\n    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));\n    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);\n    zOut += nCopy;\n    nRead -= iSpace;\n    iChunkOffset = 0;\n  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );\n  p->readpoint.iOffset = iOfst+iAmt;\n  p->readpoint.pChunk = pChunk;\n\n  return SQLITE_OK;\n}\n\n/*\n** Write data to the file.\n*/\nstatic int memjrnlWrite(\n  sqlite3_file *pJfd,    /* The journal file into which to write */\n  const void *zBuf,      /* Take data to be written from here */\n  int iAmt,              /* Number of bytes to write */\n  sqlite_int64 iOfst     /* Begin writing at this offset into the file */\n){\n  MemJournal *p = (MemJournal *)pJfd;\n  int nWrite = iAmt;\n  u8 *zWrite = (u8 *)zBuf;\n\n  /* An in-memory journal file should only ever be appended to. Random\n  ** access writes are not required by sqlite.\n  */\n  assert( iOfst==p->endpoint.iOffset );\n  UNUSED_PARAMETER(iOfst);\n\n  while( nWrite>0 ){\n    FileChunk *pChunk = p->endpoint.pChunk;\n    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);\n    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);\n\n    if( iChunkOffset==0 ){\n      /* New chunk is required to extend the file. */\n      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));\n      if( !pNew ){\n        return SQLITE_IOERR_NOMEM;\n      }\n      pNew->pNext = 0;\n      if( pChunk ){\n        assert( p->pFirst );\n        pChunk->pNext = pNew;\n      }else{\n        assert( !p->pFirst );\n        p->pFirst = pNew;\n      }\n      p->endpoint.pChunk = pNew;\n    }\n\n    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);\n    zWrite += iSpace;\n    nWrite -= iSpace;\n    p->endpoint.iOffset += iSpace;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Truncate the file.\n*/\nstatic int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){\n  MemJournal *p = (MemJournal *)pJfd;\n  FileChunk *pChunk;\n  assert(size==0);\n  UNUSED_PARAMETER(size);\n  pChunk = p->pFirst;\n  while( pChunk ){\n    FileChunk *pTmp = pChunk;\n    pChunk = pChunk->pNext;\n    sqlite3_free(pTmp);\n  }\n  sqlite3MemJournalOpen(pJfd);\n  return SQLITE_OK;\n}\n\n/*\n** Close the file.\n*/\nstatic int memjrnlClose(sqlite3_file *pJfd){\n  memjrnlTruncate(pJfd, 0);\n  return SQLITE_OK;\n}\n\n\n/*\n** Sync the file.\n**\n** Syncing an in-memory journal is a no-op.  And, in fact, this routine\n** is never called in a working implementation.  This implementation\n** exists purely as a contingency, in case some malfunction in some other\n** part of SQLite causes Sync to be called by mistake.\n*/\nstatic int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return SQLITE_OK;\n}\n\n/*\n** Query the size of the file in bytes.\n*/\nstatic int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){\n  MemJournal *p = (MemJournal *)pJfd;\n  *pSize = (sqlite_int64) p->endpoint.iOffset;\n  return SQLITE_OK;\n}\n\n/*\n** Table of methods for MemJournal sqlite3_file object.\n*/\nstatic const struct sqlite3_io_methods MemJournalMethods = {\n  1,                /* iVersion */\n  memjrnlClose,     /* xClose */\n  memjrnlRead,      /* xRead */\n  memjrnlWrite,     /* xWrite */\n  memjrnlTruncate,  /* xTruncate */\n  memjrnlSync,      /* xSync */\n  memjrnlFileSize,  /* xFileSize */\n  0,                /* xLock */\n  0,                /* xUnlock */\n  0,                /* xCheckReservedLock */\n  0,                /* xFileControl */\n  0,                /* xSectorSize */\n  0,                /* xDeviceCharacteristics */\n  0,                /* xShmMap */\n  0,                /* xShmLock */\n  0,                /* xShmBarrier */\n  0                 /* xShmUnlock */\n};\n\n/* \n** Open a journal file.\n*/\nSQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){\n  MemJournal *p = (MemJournal *)pJfd;\n  assert( EIGHT_BYTE_ALIGNMENT(p) );\n  memset(p, 0, sqlite3MemJournalSize());\n  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;\n}\n\n/*\n** Return true if the file-handle passed as an argument is \n** an in-memory journal \n*/\nSQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){\n  return pJfd->pMethods==&MemJournalMethods;\n}\n\n/* \n** Return the number of bytes required to store a MemJournal file descriptor.\n*/\nSQLITE_PRIVATE int sqlite3MemJournalSize(void){\n  return sizeof(MemJournal);\n}\n\n/************** End of memjournal.c ******************************************/\n/************** Begin file walker.c ******************************************/\n/*\n** 2008 August 16\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used for walking the parser tree for\n** an SQL statement.\n*/\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n\n/*\n** Walk an expression tree.  Invoke the callback once for each node\n** of the expression, while decending.  (In other words, the callback\n** is invoked before visiting children.)\n**\n** The return value from the callback should be one of the WRC_*\n** constants to specify how to proceed with the walk.\n**\n**    WRC_Continue      Continue descending down the tree.\n**\n**    WRC_Prune         Do not descend into child nodes.  But allow\n**                      the walk to continue with sibling nodes.\n**\n**    WRC_Abort         Do no more callbacks.  Unwind the stack and\n**                      return the top-level walk call.\n**\n** The return value from this routine is WRC_Abort to abandon the tree walk\n** and WRC_Continue to continue.\n*/\nSQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){\n  int rc;\n  if( pExpr==0 ) return WRC_Continue;\n  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );\n  testcase( ExprHasProperty(pExpr, EP_Reduced) );\n  rc = pWalker->xExprCallback(pWalker, pExpr);\n  if( rc==WRC_Continue\n              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){\n    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;\n    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;\n    }else{\n      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;\n    }\n  }\n  return rc & WRC_Abort;\n}\n\n/*\n** Call sqlite3WalkExpr() for every expression in list p or until\n** an abort request is seen.\n*/\nSQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){\n  int i;\n  struct ExprList_item *pItem;\n  if( p ){\n    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){\n      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Walk all expressions associated with SELECT statement p.  Do\n** not invoke the SELECT callback on p, but do (of course) invoke\n** any expr callbacks and SELECT callbacks that come from subqueries.\n** Return WRC_Abort or WRC_Continue.\n*/\nSQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){\n  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;\n  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;\n  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;\n  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;\n  return WRC_Continue;\n}\n\n/*\n** Walk the parse trees associated with all subqueries in the\n** FROM clause of SELECT statement p.  Do not invoke the select\n** callback on p, but do invoke it on each FROM clause subquery\n** and on any subqueries further down in the tree.  Return \n** WRC_Abort or WRC_Continue;\n*/\nSQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){\n  SrcList *pSrc;\n  int i;\n  struct SrcList_item *pItem;\n\n  pSrc = p->pSrc;\n  if( ALWAYS(pSrc) ){\n    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){\n      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){\n        return WRC_Abort;\n      }\n    }\n  }\n  return WRC_Continue;\n} \n\n/*\n** Call sqlite3WalkExpr() for every expression in Select statement p.\n** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and\n** on the compound select chain, p->pPrior.\n**\n** Return WRC_Continue under normal conditions.  Return WRC_Abort if\n** there is an abort request.\n**\n** If the Walker does not have an xSelectCallback() then this routine\n** is a no-op returning WRC_Continue.\n*/\nSQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){\n  int rc;\n  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;\n  rc = WRC_Continue;\n  pWalker->walkerDepth++;\n  while( p ){\n    rc = pWalker->xSelectCallback(pWalker, p);\n    if( rc ) break;\n    if( sqlite3WalkSelectExpr(pWalker, p)\n     || sqlite3WalkSelectFrom(pWalker, p)\n    ){\n      pWalker->walkerDepth--;\n      return WRC_Abort;\n    }\n    p = p->pPrior;\n  }\n  pWalker->walkerDepth--;\n  return rc & WRC_Abort;\n}\n\n/************** End of walker.c **********************************************/\n/************** Begin file resolve.c *****************************************/\n/*\n** 2008 August 18\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains routines used for walking the parser tree and\n** resolve all identifiers by associating them with a particular\n** table and column.\n*/\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n/*\n** Walk the expression tree pExpr and increase the aggregate function\n** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.\n** This needs to occur when copying a TK_AGG_FUNCTION node from an\n** outer query into an inner subquery.\n**\n** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)\n** is a helper function - a callback for the tree walker.\n*/\nstatic int incrAggDepth(Walker *pWalker, Expr *pExpr){\n  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;\n  return WRC_Continue;\n}\nstatic void incrAggFunctionDepth(Expr *pExpr, int N){\n  if( N>0 ){\n    Walker w;\n    memset(&w, 0, sizeof(w));\n    w.xExprCallback = incrAggDepth;\n    w.u.i = N;\n    sqlite3WalkExpr(&w, pExpr);\n  }\n}\n\n/*\n** Turn the pExpr expression into an alias for the iCol-th column of the\n** result set in pEList.\n**\n** If the result set column is a simple column reference, then this routine\n** makes an exact copy.  But for any other kind of expression, this\n** routine make a copy of the result set column as the argument to the\n** TK_AS operator.  The TK_AS operator causes the expression to be\n** evaluated just once and then reused for each alias.\n**\n** The reason for suppressing the TK_AS term when the expression is a simple\n** column reference is so that the column reference will be recognized as\n** usable by indices within the WHERE clause processing logic. \n**\n** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means\n** that in a GROUP BY clause, the expression is evaluated twice.  Hence:\n**\n**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x\n**\n** Is equivalent to:\n**\n**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5\n**\n** The result of random()%5 in the GROUP BY clause is probably different\n** from the result in the result-set.  We might fix this someday.  Or\n** then again, we might not...\n**\n** The nSubquery parameter specifies how many levels of subquery the\n** alias is removed from the original expression.  The usually value is\n** zero but it might be more if the alias is contained within a subquery\n** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION\n** structures must be increased by the nSubquery amount.\n*/\nstatic void resolveAlias(\n  Parse *pParse,         /* Parsing context */\n  ExprList *pEList,      /* A result set */\n  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */\n  Expr *pExpr,           /* Transform this into an alias to the result set */\n  const char *zType,     /* \"GROUP\" or \"ORDER\" or \"\" */\n  int nSubquery          /* Number of subqueries that the label is moving */\n){\n  Expr *pOrig;           /* The iCol-th column of the result set */\n  Expr *pDup;            /* Copy of pOrig */\n  sqlite3 *db;           /* The database connection */\n\n  assert( iCol>=0 && iCol<pEList->nExpr );\n  pOrig = pEList->a[iCol].pExpr;\n  assert( pOrig!=0 );\n  assert( pOrig->flags & EP_Resolved );\n  db = pParse->db;\n  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){\n    pDup = sqlite3ExprDup(db, pOrig, 0);\n    incrAggFunctionDepth(pDup, nSubquery);\n    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);\n    if( pDup==0 ) return;\n    if( pEList->a[iCol].iAlias==0 ){\n      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);\n    }\n    pDup->iTable = pEList->a[iCol].iAlias;\n  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){\n    pDup = sqlite3ExprDup(db, pOrig, 0);\n    if( pDup==0 ) return;\n  }else{\n    char *zToken = pOrig->u.zToken;\n    assert( zToken!=0 );\n    pOrig->u.zToken = 0;\n    pDup = sqlite3ExprDup(db, pOrig, 0);\n    pOrig->u.zToken = zToken;\n    if( pDup==0 ) return;\n    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );\n    pDup->flags2 |= EP2_MallocedToken;\n    pDup->u.zToken = sqlite3DbStrDup(db, zToken);\n  }\n  if( pExpr->flags & EP_ExpCollate ){\n    pDup->pColl = pExpr->pColl;\n    pDup->flags |= EP_ExpCollate;\n  }\n\n  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This \n  ** prevents ExprDelete() from deleting the Expr structure itself,\n  ** allowing it to be repopulated by the memcpy() on the following line.\n  */\n  ExprSetProperty(pExpr, EP_Static);\n  sqlite3ExprDelete(db, pExpr);\n  memcpy(pExpr, pDup, sizeof(*pExpr));\n  sqlite3DbFree(db, pDup);\n}\n\n\n/*\n** Return TRUE if the name zCol occurs anywhere in the USING clause.\n**\n** Return FALSE if the USING clause is NULL or if it does not contain\n** zCol.\n*/\nstatic int nameInUsingClause(IdList *pUsing, const char *zCol){\n  if( pUsing ){\n    int k;\n    for(k=0; k<pUsing->nId; k++){\n      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;\n    }\n  }\n  return 0;\n}\n\n\n/*\n** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up\n** that name in the set of source tables in pSrcList and make the pExpr \n** expression node refer back to that source column.  The following changes\n** are made to pExpr:\n**\n**    pExpr->iDb           Set the index in db->aDb[] of the database X\n**                         (even if X is implied).\n**    pExpr->iTable        Set to the cursor number for the table obtained\n**                         from pSrcList.\n**    pExpr->pTab          Points to the Table structure of X.Y (even if\n**                         X and/or Y are implied.)\n**    pExpr->iColumn       Set to the column number within the table.\n**    pExpr->op            Set to TK_COLUMN.\n**    pExpr->pLeft         Any expression this points to is deleted\n**    pExpr->pRight        Any expression this points to is deleted.\n**\n** The zDb variable is the name of the database (the \"X\").  This value may be\n** NULL meaning that name is of the form Y.Z or Z.  Any available database\n** can be used.  The zTable variable is the name of the table (the \"Y\").  This\n** value can be NULL if zDb is also NULL.  If zTable is NULL it\n** means that the form of the name is Z and that columns from any table\n** can be used.\n**\n** If the name cannot be resolved unambiguously, leave an error message\n** in pParse and return WRC_Abort.  Return WRC_Prune on success.\n*/\nstatic int lookupName(\n  Parse *pParse,       /* The parsing context */\n  const char *zDb,     /* Name of the database containing table, or NULL */\n  const char *zTab,    /* Name of table containing column, or NULL */\n  const char *zCol,    /* Name of the column. */\n  NameContext *pNC,    /* The name context used to resolve the name */\n  Expr *pExpr          /* Make this EXPR node point to the selected column */\n){\n  int i, j;                         /* Loop counters */\n  int cnt = 0;                      /* Number of matching column names */\n  int cntTab = 0;                   /* Number of matching table names */\n  int nSubquery = 0;                /* How many levels of subquery */\n  sqlite3 *db = pParse->db;         /* The database connection */\n  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */\n  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */\n  NameContext *pTopNC = pNC;        /* First namecontext in the list */\n  Schema *pSchema = 0;              /* Schema of the expression */\n  int isTrigger = 0;\n\n  assert( pNC );     /* the name context cannot be NULL. */\n  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */\n  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n\n  /* Initialize the node to no-match */\n  pExpr->iTable = -1;\n  pExpr->pTab = 0;\n  ExprSetIrreducible(pExpr);\n\n  /* Start at the inner-most context and move outward until a match is found */\n  while( pNC && cnt==0 ){\n    ExprList *pEList;\n    SrcList *pSrcList = pNC->pSrcList;\n\n    if( pSrcList ){\n      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){\n        Table *pTab;\n        int iDb;\n        Column *pCol;\n  \n        pTab = pItem->pTab;\n        assert( pTab!=0 && pTab->zName!=0 );\n        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n        assert( pTab->nCol>0 );\n        if( zTab ){\n          if( pItem->zAlias ){\n            char *zTabName = pItem->zAlias;\n            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;\n          }else{\n            char *zTabName = pTab->zName;\n            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){\n              continue;\n            }\n            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){\n              continue;\n            }\n          }\n        }\n        if( 0==(cntTab++) ){\n          pExpr->iTable = pItem->iCursor;\n          pExpr->pTab = pTab;\n          pSchema = pTab->pSchema;\n          pMatch = pItem;\n        }\n        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){\n          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n            /* If there has been exactly one prior match and this match\n            ** is for the right-hand table of a NATURAL JOIN or is in a \n            ** USING clause, then skip this match.\n            */\n            if( cnt==1 ){\n              if( pItem->jointype & JT_NATURAL ) continue;\n              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;\n            }\n            cnt++;\n            pExpr->iTable = pItem->iCursor;\n            pExpr->pTab = pTab;\n            pMatch = pItem;\n            pSchema = pTab->pSchema;\n            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */\n            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;\n            break;\n          }\n        }\n      }\n    }\n\n#ifndef SQLITE_OMIT_TRIGGER\n    /* If we have not already resolved the name, then maybe \n    ** it is a new.* or old.* trigger argument reference\n    */\n    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){\n      int op = pParse->eTriggerOp;\n      Table *pTab = 0;\n      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );\n      if( op!=TK_DELETE && sqlite3StrICmp(\"new\",zTab) == 0 ){\n        pExpr->iTable = 1;\n        pTab = pParse->pTriggerTab;\n      }else if( op!=TK_INSERT && sqlite3StrICmp(\"old\",zTab)==0 ){\n        pExpr->iTable = 0;\n        pTab = pParse->pTriggerTab;\n      }\n\n      if( pTab ){ \n        int iCol;\n        pSchema = pTab->pSchema;\n        cntTab++;\n        for(iCol=0; iCol<pTab->nCol; iCol++){\n          Column *pCol = &pTab->aCol[iCol];\n          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){\n            if( iCol==pTab->iPKey ){\n              iCol = -1;\n            }\n            break;\n          }\n        }\n        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){\n          iCol = -1;        /* IMP: R-44911-55124 */\n        }\n        if( iCol<pTab->nCol ){\n          cnt++;\n          if( iCol<0 ){\n            pExpr->affinity = SQLITE_AFF_INTEGER;\n          }else if( pExpr->iTable==0 ){\n            testcase( iCol==31 );\n            testcase( iCol==32 );\n            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));\n          }else{\n            testcase( iCol==31 );\n            testcase( iCol==32 );\n            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));\n          }\n          pExpr->iColumn = (i16)iCol;\n          pExpr->pTab = pTab;\n          isTrigger = 1;\n        }\n      }\n    }\n#endif /* !defined(SQLITE_OMIT_TRIGGER) */\n\n    /*\n    ** Perhaps the name is a reference to the ROWID\n    */\n    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){\n      cnt = 1;\n      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */\n      pExpr->affinity = SQLITE_AFF_INTEGER;\n    }\n\n    /*\n    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z\n    ** might refer to an result-set alias.  This happens, for example, when\n    ** we are resolving names in the WHERE clause of the following command:\n    **\n    **     SELECT a+b AS x FROM table WHERE x<10;\n    **\n    ** In cases like this, replace pExpr with a copy of the expression that\n    ** forms the result set entry (\"a+b\" in the example) and return immediately.\n    ** Note that the expression in the result set should have already been\n    ** resolved by the time the WHERE clause is resolved.\n    */\n    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){\n      for(j=0; j<pEList->nExpr; j++){\n        char *zAs = pEList->a[j].zName;\n        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){\n          Expr *pOrig;\n          assert( pExpr->pLeft==0 && pExpr->pRight==0 );\n          assert( pExpr->x.pList==0 );\n          assert( pExpr->x.pSelect==0 );\n          pOrig = pEList->a[j].pExpr;\n          if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){\n            sqlite3ErrorMsg(pParse, \"misuse of aliased aggregate %s\", zAs);\n            return WRC_Abort;\n          }\n          resolveAlias(pParse, pEList, j, pExpr, \"\", nSubquery);\n          cnt = 1;\n          pMatch = 0;\n          assert( zTab==0 && zDb==0 );\n          goto lookupname_end;\n        }\n      } \n    }\n\n    /* Advance to the next name context.  The loop will exit when either\n    ** we have a match (cnt>0) or when we run out of name contexts.\n    */\n    if( cnt==0 ){\n      pNC = pNC->pNext;\n      nSubquery++;\n    }\n  }\n\n  /*\n  ** If X and Y are NULL (in other words if only the column name Z is\n  ** supplied) and the value of Z is enclosed in double-quotes, then\n  ** Z is a string literal if it doesn't match any column names.  In that\n  ** case, we need to return right away and not make any changes to\n  ** pExpr.\n  **\n  ** Because no reference was made to outer contexts, the pNC->nRef\n  ** fields are not changed in any context.\n  */\n  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){\n    pExpr->op = TK_STRING;\n    pExpr->pTab = 0;\n    return WRC_Prune;\n  }\n\n  /*\n  ** cnt==0 means there was not match.  cnt>1 means there were two or\n  ** more matches.  Either way, we have an error.\n  */\n  if( cnt!=1 ){\n    const char *zErr;\n    zErr = cnt==0 ? \"no such column\" : \"ambiguous column name\";\n    if( zDb ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s.%s\", zErr, zDb, zTab, zCol);\n    }else if( zTab ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zErr, zTab, zCol);\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s: %s\", zErr, zCol);\n    }\n    pParse->checkSchema = 1;\n    pTopNC->nErr++;\n  }\n\n  /* If a column from a table in pSrcList is referenced, then record\n  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes\n  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the\n  ** column number is greater than the number of bits in the bitmask\n  ** then set the high-order bit of the bitmask.\n  */\n  if( pExpr->iColumn>=0 && pMatch!=0 ){\n    int n = pExpr->iColumn;\n    testcase( n==BMS-1 );\n    if( n>=BMS ){\n      n = BMS-1;\n    }\n    assert( pMatch->iCursor==pExpr->iTable );\n    pMatch->colUsed |= ((Bitmask)1)<<n;\n  }\n\n  /* Clean up and return\n  */\n  sqlite3ExprDelete(db, pExpr->pLeft);\n  pExpr->pLeft = 0;\n  sqlite3ExprDelete(db, pExpr->pRight);\n  pExpr->pRight = 0;\n  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);\nlookupname_end:\n  if( cnt==1 ){\n    assert( pNC!=0 );\n    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);\n    /* Increment the nRef value on all name contexts from TopNC up to\n    ** the point where the name matched. */\n    for(;;){\n      assert( pTopNC!=0 );\n      pTopNC->nRef++;\n      if( pTopNC==pNC ) break;\n      pTopNC = pTopNC->pNext;\n    }\n    return WRC_Prune;\n  } else {\n    return WRC_Abort;\n  }\n}\n\n/*\n** Allocate and return a pointer to an expression to load the column iCol\n** from datasource iSrc in SrcList pSrc.\n*/\nSQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){\n  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);\n  if( p ){\n    struct SrcList_item *pItem = &pSrc->a[iSrc];\n    p->pTab = pItem->pTab;\n    p->iTable = pItem->iCursor;\n    if( p->pTab->iPKey==iCol ){\n      p->iColumn = -1;\n    }else{\n      p->iColumn = (ynVar)iCol;\n      testcase( iCol==BMS );\n      testcase( iCol==BMS-1 );\n      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);\n    }\n    ExprSetProperty(p, EP_Resolved);\n  }\n  return p;\n}\n\n/*\n** This routine is callback for sqlite3WalkExpr().\n**\n** Resolve symbolic names into TK_COLUMN operators for the current\n** node in the expression tree.  Return 0 to continue the search down\n** the tree or 2 to abort the tree walk.\n**\n** This routine also does error checking and name resolution for\n** function names.  The operator for aggregate functions is changed\n** to TK_AGG_FUNCTION.\n*/\nstatic int resolveExprStep(Walker *pWalker, Expr *pExpr){\n  NameContext *pNC;\n  Parse *pParse;\n\n  pNC = pWalker->u.pNC;\n  assert( pNC!=0 );\n  pParse = pNC->pParse;\n  assert( pParse==pWalker->pParse );\n\n  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;\n  ExprSetProperty(pExpr, EP_Resolved);\n#ifndef NDEBUG\n  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){\n    SrcList *pSrcList = pNC->pSrcList;\n    int i;\n    for(i=0; i<pNC->pSrcList->nSrc; i++){\n      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);\n    }\n  }\n#endif\n  switch( pExpr->op ){\n\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\n    /* The special operator TK_ROW means use the rowid for the first\n    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY\n    ** clause processing on UPDATE and DELETE statements.\n    */\n    case TK_ROW: {\n      SrcList *pSrcList = pNC->pSrcList;\n      struct SrcList_item *pItem;\n      assert( pSrcList && pSrcList->nSrc==1 );\n      pItem = pSrcList->a; \n      pExpr->op = TK_COLUMN;\n      pExpr->pTab = pItem->pTab;\n      pExpr->iTable = pItem->iCursor;\n      pExpr->iColumn = -1;\n      pExpr->affinity = SQLITE_AFF_INTEGER;\n      break;\n    }\n#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */\n\n    /* A lone identifier is the name of a column.\n    */\n    case TK_ID: {\n      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);\n    }\n  \n    /* A table name and column name:     ID.ID\n    ** Or a database, table and column:  ID.ID.ID\n    */\n    case TK_DOT: {\n      const char *zColumn;\n      const char *zTable;\n      const char *zDb;\n      Expr *pRight;\n\n      /* if( pSrcList==0 ) break; */\n      pRight = pExpr->pRight;\n      if( pRight->op==TK_ID ){\n        zDb = 0;\n        zTable = pExpr->pLeft->u.zToken;\n        zColumn = pRight->u.zToken;\n      }else{\n        assert( pRight->op==TK_DOT );\n        zDb = pExpr->pLeft->u.zToken;\n        zTable = pRight->pLeft->u.zToken;\n        zColumn = pRight->pRight->u.zToken;\n      }\n      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);\n    }\n\n    /* Resolve function names\n    */\n    case TK_CONST_FUNC:\n    case TK_FUNCTION: {\n      ExprList *pList = pExpr->x.pList;    /* The argument list */\n      int n = pList ? pList->nExpr : 0;    /* Number of arguments */\n      int no_such_func = 0;       /* True if no such function exists */\n      int wrong_num_args = 0;     /* True if wrong number of arguments */\n      int is_agg = 0;             /* True if is an aggregate function */\n      int auth;                   /* Authorization to use the function */\n      int nId;                    /* Number of characters in function name */\n      const char *zId;            /* The function name. */\n      FuncDef *pDef;              /* Information about the function */\n      u8 enc = ENC(pParse->db);   /* The database encoding */\n\n      testcase( pExpr->op==TK_CONST_FUNC );\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      zId = pExpr->u.zToken;\n      nId = sqlite3Strlen30(zId);\n      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);\n      if( pDef==0 ){\n        pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);\n        if( pDef==0 ){\n          no_such_func = 1;\n        }else{\n          wrong_num_args = 1;\n        }\n      }else{\n        is_agg = pDef->xFunc==0;\n      }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n      if( pDef ){\n        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);\n        if( auth!=SQLITE_OK ){\n          if( auth==SQLITE_DENY ){\n            sqlite3ErrorMsg(pParse, \"not authorized to use function: %s\",\n                                    pDef->zName);\n            pNC->nErr++;\n          }\n          pExpr->op = TK_NULL;\n          return WRC_Prune;\n        }\n      }\n#endif\n      if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){\n        sqlite3ErrorMsg(pParse, \"misuse of aggregate function %.*s()\", nId,zId);\n        pNC->nErr++;\n        is_agg = 0;\n      }else if( no_such_func ){\n        sqlite3ErrorMsg(pParse, \"no such function: %.*s\", nId, zId);\n        pNC->nErr++;\n      }else if( wrong_num_args ){\n        sqlite3ErrorMsg(pParse,\"wrong number of arguments to function %.*s()\",\n             nId, zId);\n        pNC->nErr++;\n      }\n      if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;\n      sqlite3WalkExprList(pWalker, pList);\n      if( is_agg ){\n        NameContext *pNC2 = pNC;\n        pExpr->op = TK_AGG_FUNCTION;\n        pExpr->op2 = 0;\n        while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){\n          pExpr->op2++;\n          pNC2 = pNC2->pNext;\n        }\n        if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;\n        pNC->ncFlags |= NC_AllowAgg;\n      }\n      /* FIX ME:  Compute pExpr->affinity based on the expected return\n      ** type of the function \n      */\n      return WRC_Prune;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_SELECT:\n    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );\n#endif\n    case TK_IN: {\n      testcase( pExpr->op==TK_IN );\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        int nRef = pNC->nRef;\n#ifndef SQLITE_OMIT_CHECK\n        if( (pNC->ncFlags & NC_IsCheck)!=0 ){\n          sqlite3ErrorMsg(pParse,\"subqueries prohibited in CHECK constraints\");\n        }\n#endif\n        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);\n        assert( pNC->nRef>=nRef );\n        if( nRef!=pNC->nRef ){\n          ExprSetProperty(pExpr, EP_VarSelect);\n        }\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_CHECK\n    case TK_VARIABLE: {\n      if( (pNC->ncFlags & NC_IsCheck)!=0 ){\n        sqlite3ErrorMsg(pParse,\"parameters prohibited in CHECK constraints\");\n      }\n      break;\n    }\n#endif\n  }\n  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;\n}\n\n/*\n** pEList is a list of expressions which are really the result set of the\n** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.\n** This routine checks to see if pE is a simple identifier which corresponds\n** to the AS-name of one of the terms of the expression list.  If it is,\n** this routine return an integer between 1 and N where N is the number of\n** elements in pEList, corresponding to the matching entry.  If there is\n** no match, or if pE is not a simple identifier, then this routine\n** return 0.\n**\n** pEList has been resolved.  pE has not.\n*/\nstatic int resolveAsName(\n  Parse *pParse,     /* Parsing context for error messages */\n  ExprList *pEList,  /* List of expressions to scan */\n  Expr *pE           /* Expression we are trying to match */\n){\n  int i;             /* Loop counter */\n\n  UNUSED_PARAMETER(pParse);\n\n  if( pE->op==TK_ID ){\n    char *zCol = pE->u.zToken;\n    for(i=0; i<pEList->nExpr; i++){\n      char *zAs = pEList->a[i].zName;\n      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){\n        return i+1;\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** pE is a pointer to an expression which is a single term in the\n** ORDER BY of a compound SELECT.  The expression has not been\n** name resolved.\n**\n** At the point this routine is called, we already know that the\n** ORDER BY term is not an integer index into the result set.  That\n** case is handled by the calling routine.\n**\n** Attempt to match pE against result set columns in the left-most\n** SELECT statement.  Return the index i of the matching column,\n** as an indication to the caller that it should sort by the i-th column.\n** The left-most column is 1.  In other words, the value returned is the\n** same integer value that would be used in the SQL statement to indicate\n** the column.\n**\n** If there is no match, return 0.  Return -1 if an error occurs.\n*/\nstatic int resolveOrderByTermToExprList(\n  Parse *pParse,     /* Parsing context for error messages */\n  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */\n  Expr *pE           /* The specific ORDER BY term */\n){\n  int i;             /* Loop counter */\n  ExprList *pEList;  /* The columns of the result set */\n  NameContext nc;    /* Name context for resolving pE */\n  sqlite3 *db;       /* Database connection */\n  int rc;            /* Return code from subprocedures */\n  u8 savedSuppErr;   /* Saved value of db->suppressErr */\n\n  assert( sqlite3ExprIsInteger(pE, &i)==0 );\n  pEList = pSelect->pEList;\n\n  /* Resolve all names in the ORDER BY term expression\n  */\n  memset(&nc, 0, sizeof(nc));\n  nc.pParse = pParse;\n  nc.pSrcList = pSelect->pSrc;\n  nc.pEList = pEList;\n  nc.ncFlags = NC_AllowAgg;\n  nc.nErr = 0;\n  db = pParse->db;\n  savedSuppErr = db->suppressErr;\n  db->suppressErr = 1;\n  rc = sqlite3ResolveExprNames(&nc, pE);\n  db->suppressErr = savedSuppErr;\n  if( rc ) return 0;\n\n  /* Try to match the ORDER BY expression against an expression\n  ** in the result set.  Return an 1-based index of the matching\n  ** result-set entry.\n  */\n  for(i=0; i<pEList->nExpr; i++){\n    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){\n      return i+1;\n    }\n  }\n\n  /* If no match, return 0. */\n  return 0;\n}\n\n/*\n** Generate an ORDER BY or GROUP BY term out-of-range error.\n*/\nstatic void resolveOutOfRangeError(\n  Parse *pParse,         /* The error context into which to write the error */\n  const char *zType,     /* \"ORDER\" or \"GROUP\" */\n  int i,                 /* The index (1-based) of the term out of range */\n  int mx                 /* Largest permissible value of i */\n){\n  sqlite3ErrorMsg(pParse, \n    \"%r %s BY term out of range - should be \"\n    \"between 1 and %d\", i, zType, mx);\n}\n\n/*\n** Analyze the ORDER BY clause in a compound SELECT statement.   Modify\n** each term of the ORDER BY clause is a constant integer between 1\n** and N where N is the number of columns in the compound SELECT.\n**\n** ORDER BY terms that are already an integer between 1 and N are\n** unmodified.  ORDER BY terms that are integers outside the range of\n** 1 through N generate an error.  ORDER BY terms that are expressions\n** are matched against result set expressions of compound SELECT\n** beginning with the left-most SELECT and working toward the right.\n** At the first match, the ORDER BY expression is transformed into\n** the integer column number.\n**\n** Return the number of errors seen.\n*/\nstatic int resolveCompoundOrderBy(\n  Parse *pParse,        /* Parsing context.  Leave error messages here */\n  Select *pSelect       /* The SELECT statement containing the ORDER BY */\n){\n  int i;\n  ExprList *pOrderBy;\n  ExprList *pEList;\n  sqlite3 *db;\n  int moreToDo = 1;\n\n  pOrderBy = pSelect->pOrderBy;\n  if( pOrderBy==0 ) return 0;\n  db = pParse->db;\n#if SQLITE_MAX_COLUMN\n  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many terms in ORDER BY clause\");\n    return 1;\n  }\n#endif\n  for(i=0; i<pOrderBy->nExpr; i++){\n    pOrderBy->a[i].done = 0;\n  }\n  pSelect->pNext = 0;\n  while( pSelect->pPrior ){\n    pSelect->pPrior->pNext = pSelect;\n    pSelect = pSelect->pPrior;\n  }\n  while( pSelect && moreToDo ){\n    struct ExprList_item *pItem;\n    moreToDo = 0;\n    pEList = pSelect->pEList;\n    assert( pEList!=0 );\n    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n      int iCol = -1;\n      Expr *pE, *pDup;\n      if( pItem->done ) continue;\n      pE = pItem->pExpr;\n      if( sqlite3ExprIsInteger(pE, &iCol) ){\n        if( iCol<=0 || iCol>pEList->nExpr ){\n          resolveOutOfRangeError(pParse, \"ORDER\", i+1, pEList->nExpr);\n          return 1;\n        }\n      }else{\n        iCol = resolveAsName(pParse, pEList, pE);\n        if( iCol==0 ){\n          pDup = sqlite3ExprDup(db, pE, 0);\n          if( !db->mallocFailed ){\n            assert(pDup);\n            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);\n          }\n          sqlite3ExprDelete(db, pDup);\n        }\n      }\n      if( iCol>0 ){\n        CollSeq *pColl = pE->pColl;\n        int flags = pE->flags & EP_ExpCollate;\n        sqlite3ExprDelete(db, pE);\n        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);\n        if( pE==0 ) return 1;\n        pE->pColl = pColl;\n        pE->flags |= EP_IntValue | flags;\n        pE->u.iValue = iCol;\n        pItem->iOrderByCol = (u16)iCol;\n        pItem->done = 1;\n      }else{\n        moreToDo = 1;\n      }\n    }\n    pSelect = pSelect->pNext;\n  }\n  for(i=0; i<pOrderBy->nExpr; i++){\n    if( pOrderBy->a[i].done==0 ){\n      sqlite3ErrorMsg(pParse, \"%r ORDER BY term does not match any \"\n            \"column in the result set\", i+1);\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Check every term in the ORDER BY or GROUP BY clause pOrderBy of\n** the SELECT statement pSelect.  If any term is reference to a\n** result set expression (as determined by the ExprList.a.iCol field)\n** then convert that term into a copy of the corresponding result set\n** column.\n**\n** If any errors are detected, add an error message to pParse and\n** return non-zero.  Return zero if no errors are seen.\n*/\nSQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(\n  Parse *pParse,        /* Parsing context.  Leave error messages here */\n  Select *pSelect,      /* The SELECT statement containing the clause */\n  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */\n  const char *zType     /* \"ORDER\" or \"GROUP\" */\n){\n  int i;\n  sqlite3 *db = pParse->db;\n  ExprList *pEList;\n  struct ExprList_item *pItem;\n\n  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;\n#if SQLITE_MAX_COLUMN\n  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many terms in %s BY clause\", zType);\n    return 1;\n  }\n#endif\n  pEList = pSelect->pEList;\n  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */\n  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n    if( pItem->iOrderByCol ){\n      if( pItem->iOrderByCol>pEList->nExpr ){\n        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);\n        return 1;\n      }\n      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);\n    }\n  }\n  return 0;\n}\n\n/*\n** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.\n** The Name context of the SELECT statement is pNC.  zType is either\n** \"ORDER\" or \"GROUP\" depending on which type of clause pOrderBy is.\n**\n** This routine resolves each term of the clause into an expression.\n** If the order-by term is an integer I between 1 and N (where N is the\n** number of columns in the result set of the SELECT) then the expression\n** in the resolution is a copy of the I-th result-set expression.  If\n** the order-by term is an identify that corresponds to the AS-name of\n** a result-set expression, then the term resolves to a copy of the\n** result-set expression.  Otherwise, the expression is resolved in\n** the usual way - using sqlite3ResolveExprNames().\n**\n** This routine returns the number of errors.  If errors occur, then\n** an appropriate error message might be left in pParse.  (OOM errors\n** excepted.)\n*/\nstatic int resolveOrderGroupBy(\n  NameContext *pNC,     /* The name context of the SELECT statement */\n  Select *pSelect,      /* The SELECT statement holding pOrderBy */\n  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */\n  const char *zType     /* Either \"ORDER\" or \"GROUP\", as appropriate */\n){\n  int i, j;                      /* Loop counters */\n  int iCol;                      /* Column number */\n  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */\n  Parse *pParse;                 /* Parsing context */\n  int nResult;                   /* Number of terms in the result set */\n\n  if( pOrderBy==0 ) return 0;\n  nResult = pSelect->pEList->nExpr;\n  pParse = pNC->pParse;\n  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){\n    Expr *pE = pItem->pExpr;\n    iCol = resolveAsName(pParse, pSelect->pEList, pE);\n    if( iCol>0 ){\n      /* If an AS-name match is found, mark this ORDER BY column as being\n      ** a copy of the iCol-th result-set column.  The subsequent call to\n      ** sqlite3ResolveOrderGroupBy() will convert the expression to a\n      ** copy of the iCol-th result-set expression. */\n      pItem->iOrderByCol = (u16)iCol;\n      continue;\n    }\n    if( sqlite3ExprIsInteger(pE, &iCol) ){\n      /* The ORDER BY term is an integer constant.  Again, set the column\n      ** number so that sqlite3ResolveOrderGroupBy() will convert the\n      ** order-by term to a copy of the result-set expression */\n      if( iCol<1 ){\n        resolveOutOfRangeError(pParse, zType, i+1, nResult);\n        return 1;\n      }\n      pItem->iOrderByCol = (u16)iCol;\n      continue;\n    }\n\n    /* Otherwise, treat the ORDER BY term as an ordinary expression */\n    pItem->iOrderByCol = 0;\n    if( sqlite3ResolveExprNames(pNC, pE) ){\n      return 1;\n    }\n    for(j=0; j<pSelect->pEList->nExpr; j++){\n      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){\n        pItem->iOrderByCol = j+1;\n      }\n    }\n  }\n  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);\n}\n\n/*\n** Resolve names in the SELECT statement p and all of its descendents.\n*/\nstatic int resolveSelectStep(Walker *pWalker, Select *p){\n  NameContext *pOuterNC;  /* Context that contains this SELECT */\n  NameContext sNC;        /* Name context of this SELECT */\n  int isCompound;         /* True if p is a compound select */\n  int nCompound;          /* Number of compound terms processed so far */\n  Parse *pParse;          /* Parsing context */\n  ExprList *pEList;       /* Result set expression list */\n  int i;                  /* Loop counter */\n  ExprList *pGroupBy;     /* The GROUP BY clause */\n  Select *pLeftmost;      /* Left-most of SELECT of a compound */\n  sqlite3 *db;            /* Database connection */\n  \n\n  assert( p!=0 );\n  if( p->selFlags & SF_Resolved ){\n    return WRC_Prune;\n  }\n  pOuterNC = pWalker->u.pNC;\n  pParse = pWalker->pParse;\n  db = pParse->db;\n\n  /* Normally sqlite3SelectExpand() will be called first and will have\n  ** already expanded this SELECT.  However, if this is a subquery within\n  ** an expression, sqlite3ResolveExprNames() will be called without a\n  ** prior call to sqlite3SelectExpand().  When that happens, let\n  ** sqlite3SelectPrep() do all of the processing for this SELECT.\n  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and\n  ** this routine in the correct order.\n  */\n  if( (p->selFlags & SF_Expanded)==0 ){\n    sqlite3SelectPrep(pParse, p, pOuterNC);\n    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;\n  }\n\n  isCompound = p->pPrior!=0;\n  nCompound = 0;\n  pLeftmost = p;\n  while( p ){\n    assert( (p->selFlags & SF_Expanded)!=0 );\n    assert( (p->selFlags & SF_Resolved)==0 );\n    p->selFlags |= SF_Resolved;\n\n    /* Resolve the expressions in the LIMIT and OFFSET clauses. These\n    ** are not allowed to refer to any names, so pass an empty NameContext.\n    */\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||\n        sqlite3ResolveExprNames(&sNC, p->pOffset) ){\n      return WRC_Abort;\n    }\n  \n    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to\n    ** resolve the result-set expression list.\n    */\n    sNC.ncFlags = NC_AllowAgg;\n    sNC.pSrcList = p->pSrc;\n    sNC.pNext = pOuterNC;\n  \n    /* Resolve names in the result set. */\n    pEList = p->pEList;\n    assert( pEList!=0 );\n    for(i=0; i<pEList->nExpr; i++){\n      Expr *pX = pEList->a[i].pExpr;\n      if( sqlite3ResolveExprNames(&sNC, pX) ){\n        return WRC_Abort;\n      }\n    }\n  \n    /* Recursively resolve names in all subqueries\n    */\n    for(i=0; i<p->pSrc->nSrc; i++){\n      struct SrcList_item *pItem = &p->pSrc->a[i];\n      if( pItem->pSelect ){\n        NameContext *pNC;         /* Used to iterate name contexts */\n        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */\n        const char *zSavedContext = pParse->zAuthContext;\n\n        /* Count the total number of references to pOuterNC and all of its\n        ** parent contexts. After resolving references to expressions in\n        ** pItem->pSelect, check if this value has changed. If so, then\n        ** SELECT statement pItem->pSelect must be correlated. Set the\n        ** pItem->isCorrelated flag if this is the case. */\n        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;\n\n        if( pItem->zName ) pParse->zAuthContext = pItem->zName;\n        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);\n        pParse->zAuthContext = zSavedContext;\n        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;\n\n        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;\n        assert( pItem->isCorrelated==0 && nRef<=0 );\n        pItem->isCorrelated = (nRef!=0);\n      }\n    }\n  \n    /* If there are no aggregate functions in the result-set, and no GROUP BY \n    ** expression, do not allow aggregates in any of the other expressions.\n    */\n    assert( (p->selFlags & SF_Aggregate)==0 );\n    pGroupBy = p->pGroupBy;\n    if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){\n      p->selFlags |= SF_Aggregate;\n    }else{\n      sNC.ncFlags &= ~NC_AllowAgg;\n    }\n  \n    /* If a HAVING clause is present, then there must be a GROUP BY clause.\n    */\n    if( p->pHaving && !pGroupBy ){\n      sqlite3ErrorMsg(pParse, \"a GROUP BY clause is required before HAVING\");\n      return WRC_Abort;\n    }\n  \n    /* Add the expression list to the name-context before parsing the\n    ** other expressions in the SELECT statement. This is so that\n    ** expressions in the WHERE clause (etc.) can refer to expressions by\n    ** aliases in the result set.\n    **\n    ** Minor point: If this is the case, then the expression will be\n    ** re-evaluated for each reference to it.\n    */\n    sNC.pEList = p->pEList;\n    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||\n       sqlite3ResolveExprNames(&sNC, p->pHaving)\n    ){\n      return WRC_Abort;\n    }\n\n    /* The ORDER BY and GROUP BY clauses may not refer to terms in\n    ** outer queries \n    */\n    sNC.pNext = 0;\n    sNC.ncFlags |= NC_AllowAgg;\n\n    /* Process the ORDER BY clause for singleton SELECT statements.\n    ** The ORDER BY clause for compounds SELECT statements is handled\n    ** below, after all of the result-sets for all of the elements of\n    ** the compound have been resolved.\n    */\n    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, \"ORDER\") ){\n      return WRC_Abort;\n    }\n    if( db->mallocFailed ){\n      return WRC_Abort;\n    }\n  \n    /* Resolve the GROUP BY clause.  At the same time, make sure \n    ** the GROUP BY clause does not contain aggregate functions.\n    */\n    if( pGroupBy ){\n      struct ExprList_item *pItem;\n    \n      if( resolveOrderGroupBy(&sNC, p, pGroupBy, \"GROUP\") || db->mallocFailed ){\n        return WRC_Abort;\n      }\n      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){\n        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){\n          sqlite3ErrorMsg(pParse, \"aggregate functions are not allowed in \"\n              \"the GROUP BY clause\");\n          return WRC_Abort;\n        }\n      }\n    }\n\n    /* Advance to the next term of the compound\n    */\n    p = p->pPrior;\n    nCompound++;\n  }\n\n  /* Resolve the ORDER BY on a compound SELECT after all terms of\n  ** the compound have been resolved.\n  */\n  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){\n    return WRC_Abort;\n  }\n\n  return WRC_Prune;\n}\n\n/*\n** This routine walks an expression tree and resolves references to\n** table columns and result-set columns.  At the same time, do error\n** checking on function usage and set a flag if any aggregate functions\n** are seen.\n**\n** To resolve table columns references we look for nodes (or subtrees) of the \n** form X.Y.Z or Y.Z or just Z where\n**\n**      X:   The name of a database.  Ex:  \"main\" or \"temp\" or\n**           the symbolic name assigned to an ATTACH-ed database.\n**\n**      Y:   The name of a table in a FROM clause.  Or in a trigger\n**           one of the special names \"old\" or \"new\".\n**\n**      Z:   The name of a column in table Y.\n**\n** The node at the root of the subtree is modified as follows:\n**\n**    Expr.op        Changed to TK_COLUMN\n**    Expr.pTab      Points to the Table object for X.Y\n**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.\n**    Expr.iTable    The VDBE cursor number for X.Y\n**\n**\n** To resolve result-set references, look for expression nodes of the\n** form Z (with no X and Y prefix) where the Z matches the right-hand\n** size of an AS clause in the result-set of a SELECT.  The Z expression\n** is replaced by a copy of the left-hand side of the result-set expression.\n** Table-name and function resolution occurs on the substituted expression\n** tree.  For example, in:\n**\n**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;\n**\n** The \"x\" term of the order by is replaced by \"a+b\" to render:\n**\n**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;\n**\n** Function calls are checked to make sure that the function is \n** defined and that the correct number of arguments are specified.\n** If the function is an aggregate function, then the NC_HasAgg flag is\n** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.\n** If an expression contains aggregate functions then the EP_Agg\n** property on the expression is set.\n**\n** An error message is left in pParse if anything is amiss.  The number\n** if errors is returned.\n*/\nSQLITE_PRIVATE int sqlite3ResolveExprNames( \n  NameContext *pNC,       /* Namespace to resolve expressions in. */\n  Expr *pExpr             /* The expression to be analyzed. */\n){\n  u8 savedHasAgg;\n  Walker w;\n\n  if( pExpr==0 ) return 0;\n#if SQLITE_MAX_EXPR_DEPTH>0\n  {\n    Parse *pParse = pNC->pParse;\n    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){\n      return 1;\n    }\n    pParse->nHeight += pExpr->nHeight;\n  }\n#endif\n  savedHasAgg = pNC->ncFlags & NC_HasAgg;\n  pNC->ncFlags &= ~NC_HasAgg;\n  w.xExprCallback = resolveExprStep;\n  w.xSelectCallback = resolveSelectStep;\n  w.pParse = pNC->pParse;\n  w.u.pNC = pNC;\n  sqlite3WalkExpr(&w, pExpr);\n#if SQLITE_MAX_EXPR_DEPTH>0\n  pNC->pParse->nHeight -= pExpr->nHeight;\n#endif\n  if( pNC->nErr>0 || w.pParse->nErr>0 ){\n    ExprSetProperty(pExpr, EP_Error);\n  }\n  if( pNC->ncFlags & NC_HasAgg ){\n    ExprSetProperty(pExpr, EP_Agg);\n  }else if( savedHasAgg ){\n    pNC->ncFlags |= NC_HasAgg;\n  }\n  return ExprHasProperty(pExpr, EP_Error);\n}\n\n\n/*\n** Resolve all names in all expressions of a SELECT and in all\n** decendents of the SELECT, including compounds off of p->pPrior,\n** subqueries in expressions, and subqueries used as FROM clause\n** terms.\n**\n** See sqlite3ResolveExprNames() for a description of the kinds of\n** transformations that occur.\n**\n** All SELECT statements should have been expanded using\n** sqlite3SelectExpand() prior to invoking this routine.\n*/\nSQLITE_PRIVATE void sqlite3ResolveSelectNames(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  NameContext *pOuterNC  /* Name context for parent SELECT statement */\n){\n  Walker w;\n\n  assert( p!=0 );\n  w.xExprCallback = resolveExprStep;\n  w.xSelectCallback = resolveSelectStep;\n  w.pParse = pParse;\n  w.u.pNC = pOuterNC;\n  sqlite3WalkSelect(&w, p);\n}\n\n/************** End of resolve.c *********************************************/\n/************** Begin file expr.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains routines used for analyzing expressions and\n** for generating VDBE code that evaluates expressions in SQLite.\n*/\n\n/*\n** Return the 'affinity' of the expression pExpr if any.\n**\n** If pExpr is a column, a reference to a column via an 'AS' alias,\n** or a sub-select with a column as the return value, then the \n** affinity of that column is returned. Otherwise, 0x00 is returned,\n** indicating no affinity for the expression.\n**\n** i.e. the WHERE clause expresssions in the following statements all\n** have an affinity:\n**\n** CREATE TABLE t1(a);\n** SELECT * FROM t1 WHERE a;\n** SELECT a AS b FROM t1 WHERE b;\n** SELECT * FROM t1 WHERE (select a from t1);\n*/\nSQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){\n  int op = pExpr->op;\n  if( op==TK_SELECT ){\n    assert( pExpr->flags&EP_xIsSelect );\n    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);\n  }\n#ifndef SQLITE_OMIT_CAST\n  if( op==TK_CAST ){\n    assert( !ExprHasProperty(pExpr, EP_IntValue) );\n    return sqlite3AffinityType(pExpr->u.zToken);\n  }\n#endif\n  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) \n   && pExpr->pTab!=0\n  ){\n    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally\n    ** a TK_COLUMN but was previously evaluated and cached in a register */\n    int j = pExpr->iColumn;\n    if( j<0 ) return SQLITE_AFF_INTEGER;\n    assert( pExpr->pTab && j<pExpr->pTab->nCol );\n    return pExpr->pTab->aCol[j].affinity;\n  }\n  return pExpr->affinity;\n}\n\n/*\n** Set the explicit collating sequence for an expression to the\n** collating sequence supplied in the second argument.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){\n  if( pExpr && pColl ){\n    pExpr->pColl = pColl;\n    pExpr->flags |= EP_ExpCollate;\n  }\n  return pExpr;\n}\n\n/*\n** Set the collating sequence for expression pExpr to be the collating\n** sequence named by pToken.   Return a pointer to the revised expression.\n** The collating sequence is marked as \"explicit\" using the EP_ExpCollate\n** flag.  An explicit collating sequence will override implicit\n** collating sequences.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){\n  char *zColl = 0;            /* Dequoted name of collation sequence */\n  CollSeq *pColl;\n  sqlite3 *db = pParse->db;\n  zColl = sqlite3NameFromToken(db, pCollName);\n  pColl = sqlite3LocateCollSeq(pParse, zColl);\n  sqlite3ExprSetColl(pExpr, pColl);\n  sqlite3DbFree(db, zColl);\n  return pExpr;\n}\n\n/*\n** Return the default collation sequence for the expression pExpr. If\n** there is no default collation type, return 0.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){\n  CollSeq *pColl = 0;\n  Expr *p = pExpr;\n  while( p ){\n    int op;\n    pColl = p->pColl;\n    if( pColl ) break;\n    op = p->op;\n    if( p->pTab!=0 && (\n        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER\n    )){\n      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally\n      ** a TK_COLUMN but was previously evaluated and cached in a register */\n      const char *zColl;\n      int j = p->iColumn;\n      if( j>=0 ){\n        sqlite3 *db = pParse->db;\n        zColl = p->pTab->aCol[j].zColl;\n        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);\n        pExpr->pColl = pColl;\n      }\n      break;\n    }\n    if( op!=TK_CAST && op!=TK_UPLUS ){\n      break;\n    }\n    p = p->pLeft;\n  }\n  if( sqlite3CheckCollSeq(pParse, pColl) ){ \n    pColl = 0;\n  }\n  return pColl;\n}\n\n/*\n** pExpr is an operand of a comparison operator.  aff2 is the\n** type affinity of the other operand.  This routine returns the\n** type affinity that should be used for the comparison operator.\n*/\nSQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){\n  char aff1 = sqlite3ExprAffinity(pExpr);\n  if( aff1 && aff2 ){\n    /* Both sides of the comparison are columns. If one has numeric\n    ** affinity, use that. Otherwise use no affinity.\n    */\n    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){\n      return SQLITE_AFF_NUMERIC;\n    }else{\n      return SQLITE_AFF_NONE;\n    }\n  }else if( !aff1 && !aff2 ){\n    /* Neither side of the comparison is a column.  Compare the\n    ** results directly.\n    */\n    return SQLITE_AFF_NONE;\n  }else{\n    /* One side is a column, the other is not. Use the columns affinity. */\n    assert( aff1==0 || aff2==0 );\n    return (aff1 + aff2);\n  }\n}\n\n/*\n** pExpr is a comparison operator.  Return the type affinity that should\n** be applied to both operands prior to doing the comparison.\n*/\nstatic char comparisonAffinity(Expr *pExpr){\n  char aff;\n  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||\n          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||\n          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );\n  assert( pExpr->pLeft );\n  aff = sqlite3ExprAffinity(pExpr->pLeft);\n  if( pExpr->pRight ){\n    aff = sqlite3CompareAffinity(pExpr->pRight, aff);\n  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);\n  }else if( !aff ){\n    aff = SQLITE_AFF_NONE;\n  }\n  return aff;\n}\n\n/*\n** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.\n** idx_affinity is the affinity of an indexed column. Return true\n** if the index with affinity idx_affinity may be used to implement\n** the comparison in pExpr.\n*/\nSQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){\n  char aff = comparisonAffinity(pExpr);\n  switch( aff ){\n    case SQLITE_AFF_NONE:\n      return 1;\n    case SQLITE_AFF_TEXT:\n      return idx_affinity==SQLITE_AFF_TEXT;\n    default:\n      return sqlite3IsNumericAffinity(idx_affinity);\n  }\n}\n\n/*\n** Return the P5 value that should be used for a binary comparison\n** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.\n*/\nstatic u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){\n  u8 aff = (char)sqlite3ExprAffinity(pExpr2);\n  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;\n  return aff;\n}\n\n/*\n** Return a pointer to the collation sequence that should be used by\n** a binary comparison operator comparing pLeft and pRight.\n**\n** If the left hand expression has a collating sequence type, then it is\n** used. Otherwise the collation sequence for the right hand expression\n** is used, or the default (BINARY) if neither expression has a collating\n** type.\n**\n** Argument pRight (but not pLeft) may be a null pointer. In this case,\n** it is not considered.\n*/\nSQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(\n  Parse *pParse, \n  Expr *pLeft, \n  Expr *pRight\n){\n  CollSeq *pColl;\n  assert( pLeft );\n  if( pLeft->flags & EP_ExpCollate ){\n    assert( pLeft->pColl );\n    pColl = pLeft->pColl;\n  }else if( pRight && pRight->flags & EP_ExpCollate ){\n    assert( pRight->pColl );\n    pColl = pRight->pColl;\n  }else{\n    pColl = sqlite3ExprCollSeq(pParse, pLeft);\n    if( !pColl ){\n      pColl = sqlite3ExprCollSeq(pParse, pRight);\n    }\n  }\n  return pColl;\n}\n\n/*\n** Generate code for a comparison operator.\n*/\nstatic int codeCompare(\n  Parse *pParse,    /* The parsing (and code generating) context */\n  Expr *pLeft,      /* The left operand */\n  Expr *pRight,     /* The right operand */\n  int opcode,       /* The comparison opcode */\n  int in1, int in2, /* Register holding operands */\n  int dest,         /* Jump here if true.  */\n  int jumpIfNull    /* If true, jump if either operand is NULL */\n){\n  int p5;\n  int addr;\n  CollSeq *p4;\n\n  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);\n  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);\n  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,\n                           (void*)p4, P4_COLLSEQ);\n  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);\n  return addr;\n}\n\n#if SQLITE_MAX_EXPR_DEPTH>0\n/*\n** Check that argument nHeight is less than or equal to the maximum\n** expression depth allowed. If it is not, leave an error message in\n** pParse.\n*/\nSQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){\n  int rc = SQLITE_OK;\n  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];\n  if( nHeight>mxHeight ){\n    sqlite3ErrorMsg(pParse, \n       \"Expression tree is too large (maximum depth %d)\", mxHeight\n    );\n    rc = SQLITE_ERROR;\n  }\n  return rc;\n}\n\n/* The following three functions, heightOfExpr(), heightOfExprList()\n** and heightOfSelect(), are used to determine the maximum height\n** of any expression tree referenced by the structure passed as the\n** first argument.\n**\n** If this maximum height is greater than the current value pointed\n** to by pnHeight, the second parameter, then set *pnHeight to that\n** value.\n*/\nstatic void heightOfExpr(Expr *p, int *pnHeight){\n  if( p ){\n    if( p->nHeight>*pnHeight ){\n      *pnHeight = p->nHeight;\n    }\n  }\n}\nstatic void heightOfExprList(ExprList *p, int *pnHeight){\n  if( p ){\n    int i;\n    for(i=0; i<p->nExpr; i++){\n      heightOfExpr(p->a[i].pExpr, pnHeight);\n    }\n  }\n}\nstatic void heightOfSelect(Select *p, int *pnHeight){\n  if( p ){\n    heightOfExpr(p->pWhere, pnHeight);\n    heightOfExpr(p->pHaving, pnHeight);\n    heightOfExpr(p->pLimit, pnHeight);\n    heightOfExpr(p->pOffset, pnHeight);\n    heightOfExprList(p->pEList, pnHeight);\n    heightOfExprList(p->pGroupBy, pnHeight);\n    heightOfExprList(p->pOrderBy, pnHeight);\n    heightOfSelect(p->pPrior, pnHeight);\n  }\n}\n\n/*\n** Set the Expr.nHeight variable in the structure passed as an \n** argument. An expression with no children, Expr.pList or \n** Expr.pSelect member has a height of 1. Any other expression\n** has a height equal to the maximum height of any other \n** referenced Expr plus one.\n*/\nstatic void exprSetHeight(Expr *p){\n  int nHeight = 0;\n  heightOfExpr(p->pLeft, &nHeight);\n  heightOfExpr(p->pRight, &nHeight);\n  if( ExprHasProperty(p, EP_xIsSelect) ){\n    heightOfSelect(p->x.pSelect, &nHeight);\n  }else{\n    heightOfExprList(p->x.pList, &nHeight);\n  }\n  p->nHeight = nHeight + 1;\n}\n\n/*\n** Set the Expr.nHeight variable using the exprSetHeight() function. If\n** the height is greater than the maximum allowed expression depth,\n** leave an error in pParse.\n*/\nSQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){\n  exprSetHeight(p);\n  sqlite3ExprCheckHeight(pParse, p->nHeight);\n}\n\n/*\n** Return the maximum height of any expression tree referenced\n** by the select statement passed as an argument.\n*/\nSQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){\n  int nHeight = 0;\n  heightOfSelect(p, &nHeight);\n  return nHeight;\n}\n#else\n  #define exprSetHeight(y)\n#endif /* SQLITE_MAX_EXPR_DEPTH>0 */\n\n/*\n** This routine is the core allocator for Expr nodes.\n**\n** Construct a new expression node and return a pointer to it.  Memory\n** for this node and for the pToken argument is a single allocation\n** obtained from sqlite3DbMalloc().  The calling function\n** is responsible for making sure the node eventually gets freed.\n**\n** If dequote is true, then the token (if it exists) is dequoted.\n** If dequote is false, no dequoting is performance.  The deQuote\n** parameter is ignored if pToken is NULL or if the token does not\n** appear to be quoted.  If the quotes were of the form \"...\" (double-quotes)\n** then the EP_DblQuoted flag is set on the expression node.\n**\n** Special case:  If op==TK_INTEGER and pToken points to a string that\n** can be translated into a 32-bit integer, then the token is not\n** stored in u.zToken.  Instead, the integer values is written\n** into u.iValue and the EP_IntValue flag is set.  No extra storage\n** is allocated to hold the integer text and the dequote flag is ignored.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprAlloc(\n  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */\n  int op,                 /* Expression opcode */\n  const Token *pToken,    /* Token argument.  Might be NULL */\n  int dequote             /* True to dequote */\n){\n  Expr *pNew;\n  int nExtra = 0;\n  int iValue = 0;\n\n  if( pToken ){\n    if( op!=TK_INTEGER || pToken->z==0\n          || sqlite3GetInt32(pToken->z, &iValue)==0 ){\n      nExtra = pToken->n+1;\n      assert( iValue>=0 );\n    }\n  }\n  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);\n  if( pNew ){\n    pNew->op = (u8)op;\n    pNew->iAgg = -1;\n    if( pToken ){\n      if( nExtra==0 ){\n        pNew->flags |= EP_IntValue;\n        pNew->u.iValue = iValue;\n      }else{\n        int c;\n        pNew->u.zToken = (char*)&pNew[1];\n        assert( pToken->z!=0 || pToken->n==0 );\n        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);\n        pNew->u.zToken[pToken->n] = 0;\n        if( dequote && nExtra>=3 \n             && ((c = pToken->z[0])=='\\'' || c=='\"' || c=='[' || c=='`') ){\n          sqlite3Dequote(pNew->u.zToken);\n          if( c=='\"' ) pNew->flags |= EP_DblQuoted;\n        }\n      }\n    }\n#if SQLITE_MAX_EXPR_DEPTH>0\n    pNew->nHeight = 1;\n#endif  \n  }\n  return pNew;\n}\n\n/*\n** Allocate a new expression node from a zero-terminated token that has\n** already been dequoted.\n*/\nSQLITE_PRIVATE Expr *sqlite3Expr(\n  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */\n  int op,                 /* Expression opcode */\n  const char *zToken      /* Token argument.  Might be NULL */\n){\n  Token x;\n  x.z = zToken;\n  x.n = zToken ? sqlite3Strlen30(zToken) : 0;\n  return sqlite3ExprAlloc(db, op, &x, 0);\n}\n\n/*\n** Attach subtrees pLeft and pRight to the Expr node pRoot.\n**\n** If pRoot==NULL that means that a memory allocation error has occurred.\n** In that case, delete the subtrees pLeft and pRight.\n*/\nSQLITE_PRIVATE void sqlite3ExprAttachSubtrees(\n  sqlite3 *db,\n  Expr *pRoot,\n  Expr *pLeft,\n  Expr *pRight\n){\n  if( pRoot==0 ){\n    assert( db->mallocFailed );\n    sqlite3ExprDelete(db, pLeft);\n    sqlite3ExprDelete(db, pRight);\n  }else{\n    if( pRight ){\n      pRoot->pRight = pRight;\n      if( pRight->flags & EP_ExpCollate ){\n        pRoot->flags |= EP_ExpCollate;\n        pRoot->pColl = pRight->pColl;\n      }\n    }\n    if( pLeft ){\n      pRoot->pLeft = pLeft;\n      if( pLeft->flags & EP_ExpCollate ){\n        pRoot->flags |= EP_ExpCollate;\n        pRoot->pColl = pLeft->pColl;\n      }\n    }\n    exprSetHeight(pRoot);\n  }\n}\n\n/*\n** Allocate a Expr node which joins as many as two subtrees.\n**\n** One or both of the subtrees can be NULL.  Return a pointer to the new\n** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,\n** free the subtrees and return NULL.\n*/\nSQLITE_PRIVATE Expr *sqlite3PExpr(\n  Parse *pParse,          /* Parsing context */\n  int op,                 /* Expression opcode */\n  Expr *pLeft,            /* Left operand */\n  Expr *pRight,           /* Right operand */\n  const Token *pToken     /* Argument token */\n){\n  Expr *p;\n  if( op==TK_AND && pLeft && pRight ){\n    /* Take advantage of short-circuit false optimization for AND */\n    p = sqlite3ExprAnd(pParse->db, pLeft, pRight);\n  }else{\n    p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);\n    sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);\n  }\n  if( p ) {\n    sqlite3ExprCheckHeight(pParse, p->nHeight);\n  }\n  return p;\n}\n\n/*\n** Return 1 if an expression must be FALSE in all cases and 0 if the\n** expression might be true.  This is an optimization.  If is OK to\n** return 0 here even if the expression really is always false (a \n** false negative).  But it is a bug to return 1 if the expression\n** might be true in some rare circumstances (a false positive.)\n**\n** Note that if the expression is part of conditional for a\n** LEFT JOIN, then we cannot determine at compile-time whether or not\n** is it true or false, so always return 0.\n*/\nstatic int exprAlwaysFalse(Expr *p){\n  int v = 0;\n  if( ExprHasProperty(p, EP_FromJoin) ) return 0;\n  if( !sqlite3ExprIsInteger(p, &v) ) return 0;\n  return v==0;\n}\n\n/*\n** Join two expressions using an AND operator.  If either expression is\n** NULL, then just return the other expression.\n**\n** If one side or the other of the AND is known to be false, then instead\n** of returning an AND expression, just return a constant expression with\n** a value of false.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){\n  if( pLeft==0 ){\n    return pRight;\n  }else if( pRight==0 ){\n    return pLeft;\n  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){\n    sqlite3ExprDelete(db, pLeft);\n    sqlite3ExprDelete(db, pRight);\n    return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);\n  }else{\n    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);\n    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);\n    return pNew;\n  }\n}\n\n/*\n** Construct a new expression node for a function with multiple\n** arguments.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){\n  Expr *pNew;\n  sqlite3 *db = pParse->db;\n  assert( pToken );\n  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);\n  if( pNew==0 ){\n    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */\n    return 0;\n  }\n  pNew->x.pList = pList;\n  assert( !ExprHasProperty(pNew, EP_xIsSelect) );\n  sqlite3ExprSetHeight(pParse, pNew);\n  return pNew;\n}\n\n/*\n** Assign a variable number to an expression that encodes a wildcard\n** in the original SQL statement.  \n**\n** Wildcards consisting of a single \"?\" are assigned the next sequential\n** variable number.\n**\n** Wildcards of the form \"?nnn\" are assigned the number \"nnn\".  We make\n** sure \"nnn\" is not too be to avoid a denial of service attack when\n** the SQL statement comes from an external source.\n**\n** Wildcards of the form \":aaa\", \"@aaa\", or \"$aaa\" are assigned the same number\n** as the previous instance of the same wildcard.  Or if this is the first\n** instance of the wildcard, the next sequenial variable number is\n** assigned.\n*/\nSQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){\n  sqlite3 *db = pParse->db;\n  const char *z;\n\n  if( pExpr==0 ) return;\n  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );\n  z = pExpr->u.zToken;\n  assert( z!=0 );\n  assert( z[0]!=0 );\n  if( z[1]==0 ){\n    /* Wildcard of the form \"?\".  Assign the next variable number */\n    assert( z[0]=='?' );\n    pExpr->iColumn = (ynVar)(++pParse->nVar);\n  }else{\n    ynVar x = 0;\n    u32 n = sqlite3Strlen30(z);\n    if( z[0]=='?' ){\n      /* Wildcard of the form \"?nnn\".  Convert \"nnn\" to an integer and\n      ** use it as the variable number */\n      i64 i;\n      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);\n      pExpr->iColumn = x = (ynVar)i;\n      testcase( i==0 );\n      testcase( i==1 );\n      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );\n      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );\n      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){\n        sqlite3ErrorMsg(pParse, \"variable number must be between ?1 and ?%d\",\n            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);\n        x = 0;\n      }\n      if( i>pParse->nVar ){\n        pParse->nVar = (int)i;\n      }\n    }else{\n      /* Wildcards like \":aaa\", \"$aaa\" or \"@aaa\".  Reuse the same variable\n      ** number as the prior appearance of the same name, or if the name\n      ** has never appeared before, reuse the same variable number\n      */\n      ynVar i;\n      for(i=0; i<pParse->nzVar; i++){\n        if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){\n          pExpr->iColumn = x = (ynVar)i+1;\n          break;\n        }\n      }\n      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);\n    }\n    if( x>0 ){\n      if( x>pParse->nzVar ){\n        char **a;\n        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));\n        if( a==0 ) return;  /* Error reported through db->mallocFailed */\n        pParse->azVar = a;\n        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));\n        pParse->nzVar = x;\n      }\n      if( z[0]!='?' || pParse->azVar[x-1]==0 ){\n        sqlite3DbFree(db, pParse->azVar[x-1]);\n        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);\n      }\n    }\n  } \n  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){\n    sqlite3ErrorMsg(pParse, \"too many SQL variables\");\n  }\n}\n\n/*\n** Recursively delete an expression tree.\n*/\nSQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){\n  if( p==0 ) return;\n  /* Sanity check: Assert that the IntValue is non-negative if it exists */\n  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );\n  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){\n    sqlite3ExprDelete(db, p->pLeft);\n    sqlite3ExprDelete(db, p->pRight);\n    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){\n      sqlite3DbFree(db, p->u.zToken);\n    }\n    if( ExprHasProperty(p, EP_xIsSelect) ){\n      sqlite3SelectDelete(db, p->x.pSelect);\n    }else{\n      sqlite3ExprListDelete(db, p->x.pList);\n    }\n  }\n  if( !ExprHasProperty(p, EP_Static) ){\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Return the number of bytes allocated for the expression structure \n** passed as the first argument. This is always one of EXPR_FULLSIZE,\n** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.\n*/\nstatic int exprStructSize(Expr *p){\n  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;\n  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;\n  return EXPR_FULLSIZE;\n}\n\n/*\n** The dupedExpr*Size() routines each return the number of bytes required\n** to store a copy of an expression or expression tree.  They differ in\n** how much of the tree is measured.\n**\n**     dupedExprStructSize()     Size of only the Expr structure \n**     dupedExprNodeSize()       Size of Expr + space for token\n**     dupedExprSize()           Expr + token + subtree components\n**\n***************************************************************************\n**\n** The dupedExprStructSize() function returns two values OR-ed together:  \n** (1) the space required for a copy of the Expr structure only and \n** (2) the EP_xxx flags that indicate what the structure size should be.\n** The return values is always one of:\n**\n**      EXPR_FULLSIZE\n**      EXPR_REDUCEDSIZE   | EP_Reduced\n**      EXPR_TOKENONLYSIZE | EP_TokenOnly\n**\n** The size of the structure can be found by masking the return value\n** of this routine with 0xfff.  The flags can be found by masking the\n** return value with EP_Reduced|EP_TokenOnly.\n**\n** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size\n** (unreduced) Expr objects as they or originally constructed by the parser.\n** During expression analysis, extra information is computed and moved into\n** later parts of teh Expr object and that extra information might get chopped\n** off if the expression is reduced.  Note also that it does not work to\n** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal\n** to reduce a pristine expression tree from the parser.  The implementation\n** of dupedExprStructSize() contain multiple assert() statements that attempt\n** to enforce this constraint.\n*/\nstatic int dupedExprStructSize(Expr *p, int flags){\n  int nSize;\n  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */\n  if( 0==(flags&EXPRDUP_REDUCE) ){\n    nSize = EXPR_FULLSIZE;\n  }else{\n    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );\n    assert( !ExprHasProperty(p, EP_FromJoin) ); \n    assert( (p->flags2 & EP2_MallocedToken)==0 );\n    assert( (p->flags2 & EP2_Irreducible)==0 );\n    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){\n      nSize = EXPR_REDUCEDSIZE | EP_Reduced;\n    }else{\n      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;\n    }\n  }\n  return nSize;\n}\n\n/*\n** This function returns the space in bytes required to store the copy \n** of the Expr structure and a copy of the Expr.u.zToken string (if that\n** string is defined.)\n*/\nstatic int dupedExprNodeSize(Expr *p, int flags){\n  int nByte = dupedExprStructSize(p, flags) & 0xfff;\n  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){\n    nByte += sqlite3Strlen30(p->u.zToken)+1;\n  }\n  return ROUND8(nByte);\n}\n\n/*\n** Return the number of bytes required to create a duplicate of the \n** expression passed as the first argument. The second argument is a\n** mask containing EXPRDUP_XXX flags.\n**\n** The value returned includes space to create a copy of the Expr struct\n** itself and the buffer referred to by Expr.u.zToken, if any.\n**\n** If the EXPRDUP_REDUCE flag is set, then the return value includes \n** space to duplicate all Expr nodes in the tree formed by Expr.pLeft \n** and Expr.pRight variables (but not for any structures pointed to or \n** descended from the Expr.x.pList or Expr.x.pSelect variables).\n*/\nstatic int dupedExprSize(Expr *p, int flags){\n  int nByte = 0;\n  if( p ){\n    nByte = dupedExprNodeSize(p, flags);\n    if( flags&EXPRDUP_REDUCE ){\n      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);\n    }\n  }\n  return nByte;\n}\n\n/*\n** This function is similar to sqlite3ExprDup(), except that if pzBuffer \n** is not NULL then *pzBuffer is assumed to point to a buffer large enough \n** to store the copy of expression p, the copies of p->u.zToken\n** (if applicable), and the copies of the p->pLeft and p->pRight expressions,\n** if any. Before returning, *pzBuffer is set to the first byte passed the\n** portion of the buffer copied into by this function.\n*/\nstatic Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){\n  Expr *pNew = 0;                      /* Value to return */\n  if( p ){\n    const int isReduced = (flags&EXPRDUP_REDUCE);\n    u8 *zAlloc;\n    u32 staticFlag = 0;\n\n    assert( pzBuffer==0 || isReduced );\n\n    /* Figure out where to write the new Expr structure. */\n    if( pzBuffer ){\n      zAlloc = *pzBuffer;\n      staticFlag = EP_Static;\n    }else{\n      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));\n    }\n    pNew = (Expr *)zAlloc;\n\n    if( pNew ){\n      /* Set nNewSize to the size allocated for the structure pointed to\n      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or\n      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed\n      ** by the copy of the p->u.zToken string (if any).\n      */\n      const unsigned nStructSize = dupedExprStructSize(p, flags);\n      const int nNewSize = nStructSize & 0xfff;\n      int nToken;\n      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){\n        nToken = sqlite3Strlen30(p->u.zToken) + 1;\n      }else{\n        nToken = 0;\n      }\n      if( isReduced ){\n        assert( ExprHasProperty(p, EP_Reduced)==0 );\n        memcpy(zAlloc, p, nNewSize);\n      }else{\n        int nSize = exprStructSize(p);\n        memcpy(zAlloc, p, nSize);\n        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);\n      }\n\n      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */\n      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);\n      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);\n      pNew->flags |= staticFlag;\n\n      /* Copy the p->u.zToken string, if any. */\n      if( nToken ){\n        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];\n        memcpy(zToken, p->u.zToken, nToken);\n      }\n\n      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){\n        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */\n        if( ExprHasProperty(p, EP_xIsSelect) ){\n          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);\n        }else{\n          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);\n        }\n      }\n\n      /* Fill in pNew->pLeft and pNew->pRight. */\n      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){\n        zAlloc += dupedExprNodeSize(p, flags);\n        if( ExprHasProperty(pNew, EP_Reduced) ){\n          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);\n          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);\n        }\n        if( pzBuffer ){\n          *pzBuffer = zAlloc;\n        }\n      }else{\n        pNew->flags2 = 0;\n        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){\n          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);\n          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);\n        }\n      }\n\n    }\n  }\n  return pNew;\n}\n\n/*\n** The following group of routines make deep copies of expressions,\n** expression lists, ID lists, and select statements.  The copies can\n** be deleted (by being passed to their respective ...Delete() routines)\n** without effecting the originals.\n**\n** The expression list, ID, and source lists return by sqlite3ExprListDup(),\n** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded \n** by subsequent calls to sqlite*ListAppend() routines.\n**\n** Any tables that the SrcList might point to are not duplicated.\n**\n** The flags parameter contains a combination of the EXPRDUP_XXX flags.\n** If the EXPRDUP_REDUCE flag is set, then the structure returned is a\n** truncated version of the usual Expr structure that will be stored as\n** part of the in-memory representation of the database schema.\n*/\nSQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){\n  return exprDup(db, p, flags, 0);\n}\nSQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){\n  ExprList *pNew;\n  struct ExprList_item *pItem, *pOldItem;\n  int i;\n  if( p==0 ) return 0;\n  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );\n  if( pNew==0 ) return 0;\n  pNew->iECursor = 0;\n  pNew->nExpr = i = p->nExpr;\n  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}\n  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );\n  if( pItem==0 ){\n    sqlite3DbFree(db, pNew);\n    return 0;\n  } \n  pOldItem = p->a;\n  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){\n    Expr *pOldExpr = pOldItem->pExpr;\n    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);\n    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);\n    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);\n    pItem->sortOrder = pOldItem->sortOrder;\n    pItem->done = 0;\n    pItem->iOrderByCol = pOldItem->iOrderByCol;\n    pItem->iAlias = pOldItem->iAlias;\n  }\n  return pNew;\n}\n\n/*\n** If cursors, triggers, views and subqueries are all omitted from\n** the build, then none of the following routines, except for \n** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes\n** called with a NULL argument.\n*/\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \\\n || !defined(SQLITE_OMIT_SUBQUERY)\nSQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){\n  SrcList *pNew;\n  int i;\n  int nByte;\n  if( p==0 ) return 0;\n  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);\n  pNew = sqlite3DbMallocRaw(db, nByte );\n  if( pNew==0 ) return 0;\n  pNew->nSrc = pNew->nAlloc = p->nSrc;\n  for(i=0; i<p->nSrc; i++){\n    struct SrcList_item *pNewItem = &pNew->a[i];\n    struct SrcList_item *pOldItem = &p->a[i];\n    Table *pTab;\n    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);\n    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);\n    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);\n    pNewItem->jointype = pOldItem->jointype;\n    pNewItem->iCursor = pOldItem->iCursor;\n    pNewItem->addrFillSub = pOldItem->addrFillSub;\n    pNewItem->regReturn = pOldItem->regReturn;\n    pNewItem->isCorrelated = pOldItem->isCorrelated;\n    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);\n    pNewItem->notIndexed = pOldItem->notIndexed;\n    pNewItem->pIndex = pOldItem->pIndex;\n    pTab = pNewItem->pTab = pOldItem->pTab;\n    if( pTab ){\n      pTab->nRef++;\n    }\n    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);\n    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);\n    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);\n    pNewItem->colUsed = pOldItem->colUsed;\n  }\n  return pNew;\n}\nSQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){\n  IdList *pNew;\n  int i;\n  if( p==0 ) return 0;\n  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );\n  if( pNew==0 ) return 0;\n  pNew->nId = p->nId;\n  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );\n  if( pNew->a==0 ){\n    sqlite3DbFree(db, pNew);\n    return 0;\n  }\n  /* Note that because the size of the allocation for p->a[] is not\n  ** necessarily a power of two, sqlite3IdListAppend() may not be called\n  ** on the duplicate created by this function. */\n  for(i=0; i<p->nId; i++){\n    struct IdList_item *pNewItem = &pNew->a[i];\n    struct IdList_item *pOldItem = &p->a[i];\n    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);\n    pNewItem->idx = pOldItem->idx;\n  }\n  return pNew;\n}\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){\n  Select *pNew, *pPrior;\n  if( p==0 ) return 0;\n  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );\n  if( pNew==0 ) return 0;\n  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);\n  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);\n  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);\n  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);\n  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);\n  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);\n  pNew->op = p->op;\n  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);\n  if( pPrior ) pPrior->pNext = pNew;\n  pNew->pNext = 0;\n  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);\n  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);\n  pNew->iLimit = 0;\n  pNew->iOffset = 0;\n  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;\n  pNew->pRightmost = 0;\n  pNew->addrOpenEphm[0] = -1;\n  pNew->addrOpenEphm[1] = -1;\n  pNew->addrOpenEphm[2] = -1;\n  return pNew;\n}\n#else\nSQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){\n  assert( p==0 );\n  return 0;\n}\n#endif\n\n\n/*\n** Add a new element to the end of an expression list.  If pList is\n** initially NULL, then create a new expression list.\n**\n** If a memory allocation error occurs, the entire list is freed and\n** NULL is returned.  If non-NULL is returned, then it is guaranteed\n** that the new entry was successfully appended.\n*/\nSQLITE_PRIVATE ExprList *sqlite3ExprListAppend(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to append. Might be NULL */\n  Expr *pExpr             /* Expression to be appended. Might be NULL */\n){\n  sqlite3 *db = pParse->db;\n  if( pList==0 ){\n    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );\n    if( pList==0 ){\n      goto no_mem;\n    }\n    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));\n    if( pList->a==0 ) goto no_mem;\n  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){\n    struct ExprList_item *a;\n    assert( pList->nExpr>0 );\n    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));\n    if( a==0 ){\n      goto no_mem;\n    }\n    pList->a = a;\n  }\n  assert( pList->a!=0 );\n  if( 1 ){\n    struct ExprList_item *pItem = &pList->a[pList->nExpr++];\n    memset(pItem, 0, sizeof(*pItem));\n    pItem->pExpr = pExpr;\n  }\n  return pList;\n\nno_mem:     \n  /* Avoid leaking memory if malloc has failed. */\n  sqlite3ExprDelete(db, pExpr);\n  sqlite3ExprListDelete(db, pList);\n  return 0;\n}\n\n/*\n** Set the ExprList.a[].zName element of the most recently added item\n** on the expression list.\n**\n** pList might be NULL following an OOM error.  But pName should never be\n** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag\n** is set.\n*/\nSQLITE_PRIVATE void sqlite3ExprListSetName(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to add the span. */\n  Token *pName,           /* Name to be added */\n  int dequote             /* True to cause the name to be dequoted */\n){\n  assert( pList!=0 || pParse->db->mallocFailed!=0 );\n  if( pList ){\n    struct ExprList_item *pItem;\n    assert( pList->nExpr>0 );\n    pItem = &pList->a[pList->nExpr-1];\n    assert( pItem->zName==0 );\n    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);\n    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);\n  }\n}\n\n/*\n** Set the ExprList.a[].zSpan element of the most recently added item\n** on the expression list.\n**\n** pList might be NULL following an OOM error.  But pSpan should never be\n** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag\n** is set.\n*/\nSQLITE_PRIVATE void sqlite3ExprListSetSpan(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pList,        /* List to which to add the span. */\n  ExprSpan *pSpan         /* The span to be added */\n){\n  sqlite3 *db = pParse->db;\n  assert( pList!=0 || db->mallocFailed!=0 );\n  if( pList ){\n    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];\n    assert( pList->nExpr>0 );\n    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );\n    sqlite3DbFree(db, pItem->zSpan);\n    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,\n                                    (int)(pSpan->zEnd - pSpan->zStart));\n  }\n}\n\n/*\n** If the expression list pEList contains more than iLimit elements,\n** leave an error message in pParse.\n*/\nSQLITE_PRIVATE void sqlite3ExprListCheckLength(\n  Parse *pParse,\n  ExprList *pEList,\n  const char *zObject\n){\n  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];\n  testcase( pEList && pEList->nExpr==mx );\n  testcase( pEList && pEList->nExpr==mx+1 );\n  if( pEList && pEList->nExpr>mx ){\n    sqlite3ErrorMsg(pParse, \"too many columns in %s\", zObject);\n  }\n}\n\n/*\n** Delete an entire expression list.\n*/\nSQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){\n  int i;\n  struct ExprList_item *pItem;\n  if( pList==0 ) return;\n  assert( pList->a!=0 || pList->nExpr==0 );\n  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){\n    sqlite3ExprDelete(db, pItem->pExpr);\n    sqlite3DbFree(db, pItem->zName);\n    sqlite3DbFree(db, pItem->zSpan);\n  }\n  sqlite3DbFree(db, pList->a);\n  sqlite3DbFree(db, pList);\n}\n\n/*\n** These routines are Walker callbacks.  Walker.u.pi is a pointer\n** to an integer.  These routines are checking an expression to see\n** if it is a constant.  Set *Walker.u.pi to 0 if the expression is\n** not constant.\n**\n** These callback routines are used to implement the following:\n**\n**     sqlite3ExprIsConstant()\n**     sqlite3ExprIsConstantNotJoin()\n**     sqlite3ExprIsConstantOrFunction()\n**\n*/\nstatic int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){\n\n  /* If pWalker->u.i is 3 then any term of the expression that comes from\n  ** the ON or USING clauses of a join disqualifies the expression\n  ** from being considered constant. */\n  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){\n    pWalker->u.i = 0;\n    return WRC_Abort;\n  }\n\n  switch( pExpr->op ){\n    /* Consider functions to be constant if all their arguments are constant\n    ** and pWalker->u.i==2 */\n    case TK_FUNCTION:\n      if( pWalker->u.i==2 ) return 0;\n      /* Fall through */\n    case TK_ID:\n    case TK_COLUMN:\n    case TK_AGG_FUNCTION:\n    case TK_AGG_COLUMN:\n      testcase( pExpr->op==TK_ID );\n      testcase( pExpr->op==TK_COLUMN );\n      testcase( pExpr->op==TK_AGG_FUNCTION );\n      testcase( pExpr->op==TK_AGG_COLUMN );\n      pWalker->u.i = 0;\n      return WRC_Abort;\n    default:\n      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */\n      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */\n      return WRC_Continue;\n  }\n}\nstatic int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){\n  UNUSED_PARAMETER(NotUsed);\n  pWalker->u.i = 0;\n  return WRC_Abort;\n}\nstatic int exprIsConst(Expr *p, int initFlag){\n  Walker w;\n  w.u.i = initFlag;\n  w.xExprCallback = exprNodeIsConstant;\n  w.xSelectCallback = selectNodeIsConstant;\n  sqlite3WalkExpr(&w, p);\n  return w.u.i;\n}\n\n/*\n** Walk an expression tree.  Return 1 if the expression is constant\n** and 0 if it involves variables or function calls.\n**\n** For the purposes of this function, a double-quoted string (ex: \"abc\")\n** is considered a variable but a single-quoted string (ex: 'abc') is\n** a constant.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){\n  return exprIsConst(p, 1);\n}\n\n/*\n** Walk an expression tree.  Return 1 if the expression is constant\n** that does no originate from the ON or USING clauses of a join.\n** Return 0 if it involves variables or function calls or terms from\n** an ON or USING clause.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){\n  return exprIsConst(p, 3);\n}\n\n/*\n** Walk an expression tree.  Return 1 if the expression is constant\n** or a function call with constant arguments.  Return and 0 if there\n** are any variables.\n**\n** For the purposes of this function, a double-quoted string (ex: \"abc\")\n** is considered a variable but a single-quoted string (ex: 'abc') is\n** a constant.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){\n  return exprIsConst(p, 2);\n}\n\n/*\n** If the expression p codes a constant integer that is small enough\n** to fit in a 32-bit integer, return 1 and put the value of the integer\n** in *pValue.  If the expression is not an integer or if it is too big\n** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.\n*/\nSQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){\n  int rc = 0;\n\n  /* If an expression is an integer literal that fits in a signed 32-bit\n  ** integer, then the EP_IntValue flag will have already been set */\n  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0\n           || sqlite3GetInt32(p->u.zToken, &rc)==0 );\n\n  if( p->flags & EP_IntValue ){\n    *pValue = p->u.iValue;\n    return 1;\n  }\n  switch( p->op ){\n    case TK_UPLUS: {\n      rc = sqlite3ExprIsInteger(p->pLeft, pValue);\n      break;\n    }\n    case TK_UMINUS: {\n      int v;\n      if( sqlite3ExprIsInteger(p->pLeft, &v) ){\n        *pValue = -v;\n        rc = 1;\n      }\n      break;\n    }\n    default: break;\n  }\n  return rc;\n}\n\n/*\n** Return FALSE if there is no chance that the expression can be NULL.\n**\n** If the expression might be NULL or if the expression is too complex\n** to tell return TRUE.  \n**\n** This routine is used as an optimization, to skip OP_IsNull opcodes\n** when we know that a value cannot be NULL.  Hence, a false positive\n** (returning TRUE when in fact the expression can never be NULL) might\n** be a small performance hit but is otherwise harmless.  On the other\n** hand, a false negative (returning FALSE when the result could be NULL)\n** will likely result in an incorrect answer.  So when in doubt, return\n** TRUE.\n*/\nSQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){\n  u8 op;\n  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }\n  op = p->op;\n  if( op==TK_REGISTER ) op = p->op2;\n  switch( op ){\n    case TK_INTEGER:\n    case TK_STRING:\n    case TK_FLOAT:\n    case TK_BLOB:\n      return 0;\n    default:\n      return 1;\n  }\n}\n\n/*\n** Generate an OP_IsNull instruction that tests register iReg and jumps\n** to location iDest if the value in iReg is NULL.  The value in iReg \n** was computed by pExpr.  If we can look at pExpr at compile-time and\n** determine that it can never generate a NULL, then the OP_IsNull operation\n** can be omitted.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(\n  Vdbe *v,            /* The VDBE under construction */\n  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */\n  int iReg,           /* Test the value in this register for NULL */\n  int iDest           /* Jump here if the value is null */\n){\n  if( sqlite3ExprCanBeNull(pExpr) ){\n    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);\n  }\n}\n\n/*\n** Return TRUE if the given expression is a constant which would be\n** unchanged by OP_Affinity with the affinity given in the second\n** argument.\n**\n** This routine is used to determine if the OP_Affinity operation\n** can be omitted.  When in doubt return FALSE.  A false negative\n** is harmless.  A false positive, however, can result in the wrong\n** answer.\n*/\nSQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){\n  u8 op;\n  if( aff==SQLITE_AFF_NONE ) return 1;\n  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }\n  op = p->op;\n  if( op==TK_REGISTER ) op = p->op2;\n  switch( op ){\n    case TK_INTEGER: {\n      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;\n    }\n    case TK_FLOAT: {\n      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;\n    }\n    case TK_STRING: {\n      return aff==SQLITE_AFF_TEXT;\n    }\n    case TK_BLOB: {\n      return 1;\n    }\n    case TK_COLUMN: {\n      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */\n      return p->iColumn<0\n          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);\n    }\n    default: {\n      return 0;\n    }\n  }\n}\n\n/*\n** Return TRUE if the given string is a row-id column name.\n*/\nSQLITE_PRIVATE int sqlite3IsRowid(const char *z){\n  if( sqlite3StrICmp(z, \"_ROWID_\")==0 ) return 1;\n  if( sqlite3StrICmp(z, \"ROWID\")==0 ) return 1;\n  if( sqlite3StrICmp(z, \"OID\")==0 ) return 1;\n  return 0;\n}\n\n/*\n** Return true if we are able to the IN operator optimization on a\n** query of the form\n**\n**       x IN (SELECT ...)\n**\n** Where the SELECT... clause is as specified by the parameter to this\n** routine.\n**\n** The Select object passed in has already been preprocessed and no\n** errors have been found.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nstatic int isCandidateForInOpt(Select *p){\n  SrcList *pSrc;\n  ExprList *pEList;\n  Table *pTab;\n  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */\n  if( p->pPrior ) return 0;              /* Not a compound SELECT */\n  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){\n    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );\n    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );\n    return 0; /* No DISTINCT keyword and no aggregate functions */\n  }\n  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */\n  if( p->pLimit ) return 0;              /* Has no LIMIT clause */\n  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */\n  if( p->pWhere ) return 0;              /* Has no WHERE clause */\n  pSrc = p->pSrc;\n  assert( pSrc!=0 );\n  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */\n  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */\n  pTab = pSrc->a[0].pTab;\n  if( NEVER(pTab==0) ) return 0;\n  assert( pTab->pSelect==0 );            /* FROM clause is not a view */\n  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */\n  pEList = p->pEList;\n  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */\n  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */\n  return 1;\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n/*\n** Code an OP_Once instruction and allocate space for its flag. Return the \n** address of the new instruction.\n*/\nSQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){\n  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */\n  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);\n}\n\n/*\n** This function is used by the implementation of the IN (...) operator.\n** It's job is to find or create a b-tree structure that may be used\n** either to test for membership of the (...) set or to iterate through\n** its members, skipping duplicates.\n**\n** The index of the cursor opened on the b-tree (database table, database index \n** or ephermal table) is stored in pX->iTable before this function returns.\n** The returned value of this function indicates the b-tree type, as follows:\n**\n**   IN_INDEX_ROWID - The cursor was opened on a database table.\n**   IN_INDEX_INDEX - The cursor was opened on a database index.\n**   IN_INDEX_EPH -   The cursor was opened on a specially created and\n**                    populated epheremal table.\n**\n** An existing b-tree may only be used if the SELECT is of the simple\n** form:\n**\n**     SELECT <column> FROM <table>\n**\n** If the prNotFound parameter is 0, then the b-tree will be used to iterate\n** through the set members, skipping any duplicates. In this case an\n** epheremal table must be used unless the selected <column> is guaranteed\n** to be unique - either because it is an INTEGER PRIMARY KEY or it\n** has a UNIQUE constraint or UNIQUE index.\n**\n** If the prNotFound parameter is not 0, then the b-tree will be used \n** for fast set membership tests. In this case an epheremal table must \n** be used unless <column> is an INTEGER PRIMARY KEY or an index can \n** be found with <column> as its left-most column.\n**\n** When the b-tree is being used for membership tests, the calling function\n** needs to know whether or not the structure contains an SQL NULL \n** value in order to correctly evaluate expressions like \"X IN (Y, Z)\".\n** If there is any chance that the (...) might contain a NULL value at\n** runtime, then a register is allocated and the register number written\n** to *prNotFound. If there is no chance that the (...) contains a\n** NULL value, then *prNotFound is left unchanged.\n**\n** If a register is allocated and its location stored in *prNotFound, then\n** its initial value is NULL.  If the (...) does not remain constant\n** for the duration of the query (i.e. the SELECT within the (...)\n** is a correlated subquery) then the value of the allocated register is\n** reset to NULL each time the subquery is rerun. This allows the\n** caller to use vdbe code equivalent to the following:\n**\n**   if( register==NULL ){\n**     has_null = <test if data structure contains null>\n**     register = 1\n**   }\n**\n** in order to avoid running the <test if data structure contains null>\n** test more often than is necessary.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nSQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){\n  Select *p;                            /* SELECT to the right of IN operator */\n  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */\n  int iTab = pParse->nTab++;            /* Cursor of the RHS table */\n  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */\n  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */\n\n  assert( pX->op==TK_IN );\n\n  /* Check to see if an existing table or index can be used to\n  ** satisfy the query.  This is preferable to generating a new \n  ** ephemeral table.\n  */\n  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);\n  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){\n    sqlite3 *db = pParse->db;              /* Database connection */\n    Table *pTab;                           /* Table <table>. */\n    Expr *pExpr;                           /* Expression <column> */\n    int iCol;                              /* Index of column <column> */\n    int iDb;                               /* Database idx for pTab */\n\n    assert( p );                        /* Because of isCandidateForInOpt(p) */\n    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */\n    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */\n    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */\n    pTab = p->pSrc->a[0].pTab;\n    pExpr = p->pEList->a[0].pExpr;\n    iCol = pExpr->iColumn;\n   \n    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    sqlite3CodeVerifySchema(pParse, iDb);\n    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n    /* This function is only called from two places. In both cases the vdbe\n    ** has already been allocated. So assume sqlite3GetVdbe() is always\n    ** successful here.\n    */\n    assert(v);\n    if( iCol<0 ){\n      int iAddr;\n\n      iAddr = sqlite3CodeOnce(pParse);\n\n      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);\n      eType = IN_INDEX_ROWID;\n\n      sqlite3VdbeJumpHere(v, iAddr);\n    }else{\n      Index *pIdx;                         /* Iterator variable */\n\n      /* The collation sequence used by the comparison. If an index is to\n      ** be used in place of a temp-table, it must be ordered according\n      ** to this collation sequence.  */\n      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);\n\n      /* Check that the affinity that will be used to perform the \n      ** comparison is the same as the affinity of the column. If\n      ** it is not, it is not possible to use any index.\n      */\n      char aff = comparisonAffinity(pX);\n      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);\n\n      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){\n        if( (pIdx->aiColumn[0]==iCol)\n         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq\n         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))\n        ){\n          int iAddr;\n          char *pKey;\n  \n          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);\n          iAddr = sqlite3CodeOnce(pParse);\n  \n          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,\n                               pKey,P4_KEYINFO_HANDOFF);\n          VdbeComment((v, \"%s\", pIdx->zName));\n          eType = IN_INDEX_INDEX;\n\n          sqlite3VdbeJumpHere(v, iAddr);\n          if( prNotFound && !pTab->aCol[iCol].notNull ){\n            *prNotFound = ++pParse->nMem;\n            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);\n          }\n        }\n      }\n    }\n  }\n\n  if( eType==0 ){\n    /* Could not found an existing table or index to use as the RHS b-tree.\n    ** We will have to generate an ephemeral table to do the job.\n    */\n    double savedNQueryLoop = pParse->nQueryLoop;\n    int rMayHaveNull = 0;\n    eType = IN_INDEX_EPH;\n    if( prNotFound ){\n      *prNotFound = rMayHaveNull = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);\n    }else{\n      testcase( pParse->nQueryLoop>(double)1 );\n      pParse->nQueryLoop = (double)1;\n      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){\n        eType = IN_INDEX_ROWID;\n      }\n    }\n    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);\n    pParse->nQueryLoop = savedNQueryLoop;\n  }else{\n    pX->iTable = iTab;\n  }\n  return eType;\n}\n#endif\n\n/*\n** Generate code for scalar subqueries used as a subquery expression, EXISTS,\n** or IN operators.  Examples:\n**\n**     (SELECT a FROM b)          -- subquery\n**     EXISTS (SELECT a FROM b)   -- EXISTS subquery\n**     x IN (4,5,11)              -- IN operator with list on right-hand side\n**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right\n**\n** The pExpr parameter describes the expression that contains the IN\n** operator or subquery.\n**\n** If parameter isRowid is non-zero, then expression pExpr is guaranteed\n** to be of the form \"<rowid> IN (?, ?, ?)\", where <rowid> is a reference\n** to some integer key column of a table B-Tree. In this case, use an\n** intkey B-Tree to store the set of IN(...) values instead of the usual\n** (slower) variable length keys B-Tree.\n**\n** If rMayHaveNull is non-zero, that means that the operation is an IN\n** (not a SELECT or EXISTS) and that the RHS might contains NULLs.\n** Furthermore, the IN is in a WHERE clause and that we really want\n** to iterate over the RHS of the IN operator in order to quickly locate\n** all corresponding LHS elements.  All this routine does is initialize\n** the register given by rMayHaveNull to NULL.  Calling routines will take\n** care of changing this register value to non-NULL if the RHS is NULL-free.\n**\n** If rMayHaveNull is zero, that means that the subquery is being used\n** for membership testing only.  There is no need to initialize any\n** registers to indicate the presense or absence of NULLs on the RHS.\n**\n** For a SELECT or EXISTS operator, return the register that holds the\n** result.  For IN operators or if an error occurs, the return value is 0.\n*/\n#ifndef SQLITE_OMIT_SUBQUERY\nSQLITE_PRIVATE int sqlite3CodeSubselect(\n  Parse *pParse,          /* Parsing context */\n  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */\n  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */\n  int isRowid             /* If true, LHS of IN operator is a rowid */\n){\n  int testAddr = -1;                      /* One-time test address */\n  int rReg = 0;                           /* Register storing resulting */\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( NEVER(v==0) ) return 0;\n  sqlite3ExprCachePush(pParse);\n\n  /* This code must be run in its entirety every time it is encountered\n  ** if any of the following is true:\n  **\n  **    *  The right-hand side is a correlated subquery\n  **    *  The right-hand side is an expression list containing variables\n  **    *  We are inside a trigger\n  **\n  ** If all of the above are false, then we can run this code just once\n  ** save the results, and reuse the same result on subsequent invocations.\n  */\n  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){\n    testAddr = sqlite3CodeOnce(pParse);\n  }\n\n#ifndef SQLITE_OMIT_EXPLAIN\n  if( pParse->explain==2 ){\n    char *zMsg = sqlite3MPrintf(\n        pParse->db, \"EXECUTE %s%s SUBQUERY %d\", testAddr>=0?\"\":\"CORRELATED \",\n        pExpr->op==TK_IN?\"LIST\":\"SCALAR\", pParse->iNextSelectId\n    );\n    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);\n  }\n#endif\n\n  switch( pExpr->op ){\n    case TK_IN: {\n      char affinity;              /* Affinity of the LHS of the IN */\n      KeyInfo keyInfo;            /* Keyinfo for the generated table */\n      int addr;                   /* Address of OP_OpenEphemeral instruction */\n      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */\n\n      if( rMayHaveNull ){\n        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);\n      }\n\n      affinity = sqlite3ExprAffinity(pLeft);\n\n      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'\n      ** expression it is handled the same way.  An ephemeral table is \n      ** filled with single-field index keys representing the results\n      ** from the SELECT or the <exprlist>.\n      **\n      ** If the 'x' expression is a column value, or the SELECT...\n      ** statement returns a column value, then the affinity of that\n      ** column is used to build the index keys. If both 'x' and the\n      ** SELECT... statement are columns, then numeric affinity is used\n      ** if either column has NUMERIC or INTEGER affinity. If neither\n      ** 'x' nor the SELECT... statement are columns, then numeric affinity\n      ** is used.\n      */\n      pExpr->iTable = pParse->nTab++;\n      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);\n      if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n      memset(&keyInfo, 0, sizeof(keyInfo));\n      keyInfo.nField = 1;\n\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        /* Case 1:     expr IN (SELECT ...)\n        **\n        ** Generate code to write the results of the select into the temporary\n        ** table allocated and opened above.\n        */\n        SelectDest dest;\n        ExprList *pEList;\n\n        assert( !isRowid );\n        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);\n        dest.affSdst = (u8)affinity;\n        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );\n        pExpr->x.pSelect->iLimit = 0;\n        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){\n          return 0;\n        }\n        pEList = pExpr->x.pSelect->pEList;\n        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ \n          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,\n              pEList->a[0].pExpr);\n        }\n      }else if( ALWAYS(pExpr->x.pList!=0) ){\n        /* Case 2:     expr IN (exprlist)\n        **\n        ** For each expression, build an index key from the evaluation and\n        ** store it in the temporary table. If <expr> is a column, then use\n        ** that columns affinity when building index keys. If <expr> is not\n        ** a column, use numeric affinity.\n        */\n        int i;\n        ExprList *pList = pExpr->x.pList;\n        struct ExprList_item *pItem;\n        int r1, r2, r3;\n\n        if( !affinity ){\n          affinity = SQLITE_AFF_NONE;\n        }\n        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);\n\n        /* Loop through each expression in <exprlist>. */\n        r1 = sqlite3GetTempReg(pParse);\n        r2 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);\n        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){\n          Expr *pE2 = pItem->pExpr;\n          int iValToIns;\n\n          /* If the expression is not constant then we will need to\n          ** disable the test that was generated above that makes sure\n          ** this code only executes once.  Because for a non-constant\n          ** expression we need to rerun this code each time.\n          */\n          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){\n            sqlite3VdbeChangeToNoop(v, testAddr);\n            testAddr = -1;\n          }\n\n          /* Evaluate the expression and insert it into the temp table */\n          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){\n            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);\n          }else{\n            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);\n            if( isRowid ){\n              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,\n                                sqlite3VdbeCurrentAddr(v)+2);\n              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);\n            }else{\n              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);\n              sqlite3ExprCacheAffinityChange(pParse, r3, 1);\n              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);\n            }\n          }\n        }\n        sqlite3ReleaseTempReg(pParse, r1);\n        sqlite3ReleaseTempReg(pParse, r2);\n      }\n      if( !isRowid ){\n        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);\n      }\n      break;\n    }\n\n    case TK_EXISTS:\n    case TK_SELECT:\n    default: {\n      /* If this has to be a scalar SELECT.  Generate code to put the\n      ** value of this select in a memory cell and record the number\n      ** of the memory cell in iColumn.  If this is an EXISTS, write\n      ** an integer 0 (not exists) or 1 (exists) into a memory cell\n      ** and record that memory cell in iColumn.\n      */\n      Select *pSel;                         /* SELECT statement to encode */\n      SelectDest dest;                      /* How to deal with SELECt result */\n\n      testcase( pExpr->op==TK_EXISTS );\n      testcase( pExpr->op==TK_SELECT );\n      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );\n\n      assert( ExprHasProperty(pExpr, EP_xIsSelect) );\n      pSel = pExpr->x.pSelect;\n      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);\n      if( pExpr->op==TK_SELECT ){\n        dest.eDest = SRT_Mem;\n        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);\n        VdbeComment((v, \"Init subquery result\"));\n      }else{\n        dest.eDest = SRT_Exists;\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);\n        VdbeComment((v, \"Init EXISTS result\"));\n      }\n      sqlite3ExprDelete(pParse->db, pSel->pLimit);\n      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,\n                                  &sqlite3IntTokens[1]);\n      pSel->iLimit = 0;\n      if( sqlite3Select(pParse, pSel, &dest) ){\n        return 0;\n      }\n      rReg = dest.iSDParm;\n      ExprSetIrreducible(pExpr);\n      break;\n    }\n  }\n\n  if( testAddr>=0 ){\n    sqlite3VdbeJumpHere(v, testAddr);\n  }\n  sqlite3ExprCachePop(pParse, 1);\n\n  return rReg;\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Generate code for an IN expression.\n**\n**      x IN (SELECT ...)\n**      x IN (value, value, ...)\n**\n** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)\n** is an array of zero or more values.  The expression is true if the LHS is\n** contained within the RHS.  The value of the expression is unknown (NULL)\n** if the LHS is NULL or if the LHS is not contained within the RHS and the\n** RHS contains one or more NULL values.\n**\n** This routine generates code will jump to destIfFalse if the LHS is not \n** contained within the RHS.  If due to NULLs we cannot determine if the LHS\n** is contained in the RHS then jump to destIfNull.  If the LHS is contained\n** within the RHS then fall through.\n*/\nstatic void sqlite3ExprCodeIN(\n  Parse *pParse,        /* Parsing and code generating context */\n  Expr *pExpr,          /* The IN expression */\n  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */\n  int destIfNull        /* Jump here if the results are unknown due to NULLs */\n){\n  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */\n  char affinity;        /* Comparison affinity to use */\n  int eType;            /* Type of the RHS */\n  int r1;               /* Temporary use register */\n  Vdbe *v;              /* Statement under construction */\n\n  /* Compute the RHS.   After this step, the table with cursor\n  ** pExpr->iTable will contains the values that make up the RHS.\n  */\n  v = pParse->pVdbe;\n  assert( v!=0 );       /* OOM detected prior to this routine */\n  VdbeNoopComment((v, \"begin IN expr\"));\n  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);\n\n  /* Figure out the affinity to use to create a key from the results\n  ** of the expression. affinityStr stores a static string suitable for\n  ** P4 of OP_MakeRecord.\n  */\n  affinity = comparisonAffinity(pExpr);\n\n  /* Code the LHS, the <expr> from \"<expr> IN (...)\".\n  */\n  sqlite3ExprCachePush(pParse);\n  r1 = sqlite3GetTempReg(pParse);\n  sqlite3ExprCode(pParse, pExpr->pLeft, r1);\n\n  /* If the LHS is NULL, then the result is either false or NULL depending\n  ** on whether the RHS is empty or not, respectively.\n  */\n  if( destIfNull==destIfFalse ){\n    /* Shortcut for the common case where the false and NULL outcomes are\n    ** the same. */\n    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);\n  }else{\n    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);\n    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);\n    sqlite3VdbeJumpHere(v, addr1);\n  }\n\n  if( eType==IN_INDEX_ROWID ){\n    /* In this case, the RHS is the ROWID of table b-tree\n    */\n    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);\n    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);\n  }else{\n    /* In this case, the RHS is an index b-tree.\n    */\n    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);\n\n    /* If the set membership test fails, then the result of the \n    ** \"x IN (...)\" expression must be either 0 or NULL. If the set\n    ** contains no NULL values, then the result is 0. If the set \n    ** contains one or more NULL values, then the result of the\n    ** expression is also NULL.\n    */\n    if( rRhsHasNull==0 || destIfFalse==destIfNull ){\n      /* This branch runs if it is known at compile time that the RHS\n      ** cannot contain NULL values. This happens as the result\n      ** of a \"NOT NULL\" constraint in the database schema.\n      **\n      ** Also run this branch if NULL is equivalent to FALSE\n      ** for this particular IN operator.\n      */\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);\n\n    }else{\n      /* In this branch, the RHS of the IN might contain a NULL and\n      ** the presence of a NULL on the RHS makes a difference in the\n      ** outcome.\n      */\n      int j1, j2, j3;\n\n      /* First check to see if the LHS is contained in the RHS.  If so,\n      ** then the presence of NULLs in the RHS does not matter, so jump\n      ** over all of the code that follows.\n      */\n      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);\n\n      /* Here we begin generating code that runs if the LHS is not\n      ** contained within the RHS.  Generate additional code that\n      ** tests the RHS for NULLs.  If the RHS contains a NULL then\n      ** jump to destIfNull.  If there are no NULLs in the RHS then\n      ** jump to destIfFalse.\n      */\n      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);\n      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);\n      sqlite3VdbeJumpHere(v, j3);\n      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);\n      sqlite3VdbeJumpHere(v, j2);\n\n      /* Jump to the appropriate target depending on whether or not\n      ** the RHS contains a NULL\n      */\n      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);\n\n      /* The OP_Found at the top of this branch jumps here when true, \n      ** causing the overall IN expression evaluation to fall through.\n      */\n      sqlite3VdbeJumpHere(v, j1);\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, r1);\n  sqlite3ExprCachePop(pParse, 1);\n  VdbeComment((v, \"end IN expr\"));\n}\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n/*\n** Duplicate an 8-byte value\n*/\nstatic char *dup8bytes(Vdbe *v, const char *in){\n  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);\n  if( out ){\n    memcpy(out, in, 8);\n  }\n  return out;\n}\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n/*\n** Generate an instruction that will put the floating point\n** value described by z[0..n-1] into register iMem.\n**\n** The z[] string will probably not be zero-terminated.  But the \n** z[n] character is guaranteed to be something that does not look\n** like the continuation of the number.\n*/\nstatic void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){\n  if( ALWAYS(z!=0) ){\n    double value;\n    char *zV;\n    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);\n    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */\n    if( negateFlag ) value = -value;\n    zV = dup8bytes(v, (char*)&value);\n    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);\n  }\n}\n#endif\n\n\n/*\n** Generate an instruction that will put the integer describe by\n** text z[0..n-1] into register iMem.\n**\n** Expr.u.zToken is always UTF8 and zero-terminated.\n*/\nstatic void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){\n  Vdbe *v = pParse->pVdbe;\n  if( pExpr->flags & EP_IntValue ){\n    int i = pExpr->u.iValue;\n    assert( i>=0 );\n    if( negFlag ) i = -i;\n    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);\n  }else{\n    int c;\n    i64 value;\n    const char *z = pExpr->u.zToken;\n    assert( z!=0 );\n    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);\n    if( c==0 || (c==2 && negFlag) ){\n      char *zV;\n      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }\n      zV = dup8bytes(v, (char*)&value);\n      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);\n    }else{\n#ifdef SQLITE_OMIT_FLOATING_POINT\n      sqlite3ErrorMsg(pParse, \"oversized integer: %s%s\", negFlag ? \"-\" : \"\", z);\n#else\n      codeReal(v, z, negFlag, iMem);\n#endif\n    }\n  }\n}\n\n/*\n** Clear a cache entry.\n*/\nstatic void cacheEntryClear(Parse *pParse, struct yColCache *p){\n  if( p->tempReg ){\n    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){\n      pParse->aTempReg[pParse->nTempReg++] = p->iReg;\n    }\n    p->tempReg = 0;\n  }\n}\n\n\n/*\n** Record in the column cache that a particular column from a\n** particular table is stored in a particular register.\n*/\nSQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){\n  int i;\n  int minLru;\n  int idxLru;\n  struct yColCache *p;\n\n  assert( iReg>0 );  /* Register numbers are always positive */\n  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */\n\n  /* The SQLITE_ColumnCache flag disables the column cache.  This is used\n  ** for testing only - to verify that SQLite always gets the same answer\n  ** with and without the column cache.\n  */\n  if( pParse->db->flags & SQLITE_ColumnCache ) return;\n\n  /* First replace any existing entry.\n  **\n  ** Actually, the way the column cache is currently used, we are guaranteed\n  ** that the object will never already be in cache.  Verify this guarantee.\n  */\n#ifndef NDEBUG\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );\n  }\n#endif\n\n  /* Find an empty slot and replace it */\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->iReg==0 ){\n      p->iLevel = pParse->iCacheLevel;\n      p->iTable = iTab;\n      p->iColumn = iCol;\n      p->iReg = iReg;\n      p->tempReg = 0;\n      p->lru = pParse->iCacheCnt++;\n      return;\n    }\n  }\n\n  /* Replace the last recently used */\n  minLru = 0x7fffffff;\n  idxLru = -1;\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->lru<minLru ){\n      idxLru = i;\n      minLru = p->lru;\n    }\n  }\n  if( ALWAYS(idxLru>=0) ){\n    p = &pParse->aColCache[idxLru];\n    p->iLevel = pParse->iCacheLevel;\n    p->iTable = iTab;\n    p->iColumn = iCol;\n    p->iReg = iReg;\n    p->tempReg = 0;\n    p->lru = pParse->iCacheCnt++;\n    return;\n  }\n}\n\n/*\n** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.\n** Purge the range of registers from the column cache.\n*/\nSQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){\n  int i;\n  int iLast = iReg + nReg - 1;\n  struct yColCache *p;\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    int r = p->iReg;\n    if( r>=iReg && r<=iLast ){\n      cacheEntryClear(pParse, p);\n      p->iReg = 0;\n    }\n  }\n}\n\n/*\n** Remember the current column cache context.  Any new entries added\n** added to the column cache after this call are removed when the\n** corresponding pop occurs.\n*/\nSQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){\n  pParse->iCacheLevel++;\n}\n\n/*\n** Remove from the column cache any entries that were added since the\n** the previous N Push operations.  In other words, restore the cache\n** to the state it was in N Pushes ago.\n*/\nSQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){\n  int i;\n  struct yColCache *p;\n  assert( N>0 );\n  assert( pParse->iCacheLevel>=N );\n  pParse->iCacheLevel -= N;\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->iReg && p->iLevel>pParse->iCacheLevel ){\n      cacheEntryClear(pParse, p);\n      p->iReg = 0;\n    }\n  }\n}\n\n/*\n** When a cached column is reused, make sure that its register is\n** no longer available as a temp register.  ticket #3879:  that same\n** register might be in the cache in multiple places, so be sure to\n** get them all.\n*/\nstatic void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){\n  int i;\n  struct yColCache *p;\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->iReg==iReg ){\n      p->tempReg = 0;\n    }\n  }\n}\n\n/*\n** Generate code to extract the value of the iCol-th column of a table.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(\n  Vdbe *v,        /* The VDBE under construction */\n  Table *pTab,    /* The table containing the value */\n  int iTabCur,    /* The cursor for this table */\n  int iCol,       /* Index of the column to extract */\n  int regOut      /* Extract the valud into this register */\n){\n  if( iCol<0 || iCol==pTab->iPKey ){\n    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);\n  }else{\n    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;\n    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);\n  }\n  if( iCol>=0 ){\n    sqlite3ColumnDefault(v, pTab, iCol, regOut);\n  }\n}\n\n/*\n** Generate code that will extract the iColumn-th column from\n** table pTab and store the column value in a register.  An effort\n** is made to store the column value in register iReg, but this is\n** not guaranteed.  The location of the column value is returned.\n**\n** There must be an open cursor to pTab in iTable when this routine\n** is called.  If iColumn<0 then code is generated that extracts the rowid.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeGetColumn(\n  Parse *pParse,   /* Parsing and code generating context */\n  Table *pTab,     /* Description of the table we are reading from */\n  int iColumn,     /* Index of the table column */\n  int iTable,      /* The cursor pointing to the table */\n  int iReg,        /* Store results here */\n  u8 p5            /* P5 value for OP_Column */\n){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  struct yColCache *p;\n\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){\n      p->lru = pParse->iCacheCnt++;\n      sqlite3ExprCachePinRegister(pParse, p->iReg);\n      return p->iReg;\n    }\n  }  \n  assert( v!=0 );\n  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);\n  if( p5 ){\n    sqlite3VdbeChangeP5(v, p5);\n  }else{   \n    sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);\n  }\n  return iReg;\n}\n\n/*\n** Clear all column cache entries.\n*/\nSQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){\n  int i;\n  struct yColCache *p;\n\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    if( p->iReg ){\n      cacheEntryClear(pParse, p);\n      p->iReg = 0;\n    }\n  }\n}\n\n/*\n** Record the fact that an affinity change has occurred on iCount\n** registers starting with iStart.\n*/\nSQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){\n  sqlite3ExprCacheRemove(pParse, iStart, iCount);\n}\n\n/*\n** Generate code to move content from registers iFrom...iFrom+nReg-1\n** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){\n  int i;\n  struct yColCache *p;\n  if( NEVER(iFrom==iTo) ) return;\n  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    int x = p->iReg;\n    if( x>=iFrom && x<iFrom+nReg ){\n      p->iReg += iTo-iFrom;\n    }\n  }\n}\n\n/*\n** Generate code to copy content from registers iFrom...iFrom+nReg-1\n** over to iTo..iTo+nReg-1.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){\n  int i;\n  if( NEVER(iFrom==iTo) ) return;\n  for(i=0; i<nReg; i++){\n    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);\n  }\n}\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)\n/*\n** Return true if any register in the range iFrom..iTo (inclusive)\n** is used as part of the column cache.\n**\n** This routine is used within assert() and testcase() macros only\n** and does not appear in a normal build.\n*/\nstatic int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){\n  int i;\n  struct yColCache *p;\n  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n    int r = p->iReg;\n    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/\n  }\n  return 0;\n}\n#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */\n\n/*\n** Generate code into the current Vdbe to evaluate the given\n** expression.  Attempt to store the results in register \"target\".\n** Return the register where results are stored.\n**\n** With this routine, there is no guarantee that results will\n** be stored in target.  The result might be stored in some other\n** register if it is convenient to do so.  The calling function\n** must check the return code and move the results to the desired\n** register.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){\n  Vdbe *v = pParse->pVdbe;  /* The VM under construction */\n  int op;                   /* The opcode being coded */\n  int inReg = target;       /* Results stored in register inReg */\n  int regFree1 = 0;         /* If non-zero free this temporary register */\n  int regFree2 = 0;         /* If non-zero free this temporary register */\n  int r1, r2, r3, r4;       /* Various register numbers */\n  sqlite3 *db = pParse->db; /* The database connection */\n\n  assert( target>0 && target<=pParse->nMem );\n  if( v==0 ){\n    assert( pParse->db->mallocFailed );\n    return 0;\n  }\n\n  if( pExpr==0 ){\n    op = TK_NULL;\n  }else{\n    op = pExpr->op;\n  }\n  switch( op ){\n    case TK_AGG_COLUMN: {\n      AggInfo *pAggInfo = pExpr->pAggInfo;\n      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];\n      if( !pAggInfo->directMode ){\n        assert( pCol->iMem>0 );\n        inReg = pCol->iMem;\n        break;\n      }else if( pAggInfo->useSortingIdx ){\n        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,\n                              pCol->iSorterColumn, target);\n        break;\n      }\n      /* Otherwise, fall thru into the TK_COLUMN case */\n    }\n    case TK_COLUMN: {\n      if( pExpr->iTable<0 ){\n        /* This only happens when coding check constraints */\n        assert( pParse->ckBase>0 );\n        inReg = pExpr->iColumn + pParse->ckBase;\n      }else{\n        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,\n                                 pExpr->iColumn, pExpr->iTable, target,\n                                 pExpr->op2);\n      }\n      break;\n    }\n    case TK_INTEGER: {\n      codeInteger(pParse, pExpr, 0, target);\n      break;\n    }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    case TK_FLOAT: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      codeReal(v, pExpr->u.zToken, 0, target);\n      break;\n    }\n#endif\n    case TK_STRING: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);\n      break;\n    }\n    case TK_NULL: {\n      sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      break;\n    }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case TK_BLOB: {\n      int n;\n      const char *z;\n      char *zBlob;\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );\n      assert( pExpr->u.zToken[1]=='\\'' );\n      z = &pExpr->u.zToken[2];\n      n = sqlite3Strlen30(z) - 1;\n      assert( z[n]=='\\'' );\n      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);\n      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);\n      break;\n    }\n#endif\n    case TK_VARIABLE: {\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      assert( pExpr->u.zToken!=0 );\n      assert( pExpr->u.zToken[0]!=0 );\n      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);\n      if( pExpr->u.zToken[1]!=0 ){\n        assert( pExpr->u.zToken[0]=='?' \n             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );\n        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);\n      }\n      break;\n    }\n    case TK_REGISTER: {\n      inReg = pExpr->iTable;\n      break;\n    }\n    case TK_AS: {\n      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);\n      break;\n    }\n#ifndef SQLITE_OMIT_CAST\n    case TK_CAST: {\n      /* Expressions of the form:   CAST(pLeft AS token) */\n      int aff, to_op;\n      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      aff = sqlite3AffinityType(pExpr->u.zToken);\n      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;\n      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );\n      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );\n      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );\n      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );\n      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );\n      testcase( to_op==OP_ToText );\n      testcase( to_op==OP_ToBlob );\n      testcase( to_op==OP_ToNumeric );\n      testcase( to_op==OP_ToInt );\n      testcase( to_op==OP_ToReal );\n      if( inReg!=target ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);\n        inReg = target;\n      }\n      sqlite3VdbeAddOp1(v, to_op, inReg);\n      testcase( usedAsColumnCache(pParse, inReg, inReg) );\n      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);\n      break;\n    }\n#endif /* SQLITE_OMIT_CAST */\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      assert( TK_LT==OP_Lt );\n      assert( TK_LE==OP_Le );\n      assert( TK_GT==OP_Gt );\n      assert( TK_GE==OP_Ge );\n      assert( TK_EQ==OP_Eq );\n      assert( TK_NE==OP_Ne );\n      testcase( op==TK_LT );\n      testcase( op==TK_LE );\n      testcase( op==TK_GT );\n      testcase( op==TK_GE );\n      testcase( op==TK_EQ );\n      testcase( op==TK_NE );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, inReg, SQLITE_STOREP2);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT: {\n      testcase( op==TK_IS );\n      testcase( op==TK_ISNOT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      op = (op==TK_IS) ? TK_EQ : TK_NE;\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_AND:\n    case TK_OR:\n    case TK_PLUS:\n    case TK_STAR:\n    case TK_MINUS:\n    case TK_REM:\n    case TK_BITAND:\n    case TK_BITOR:\n    case TK_SLASH:\n    case TK_LSHIFT:\n    case TK_RSHIFT: \n    case TK_CONCAT: {\n      assert( TK_AND==OP_And );\n      assert( TK_OR==OP_Or );\n      assert( TK_PLUS==OP_Add );\n      assert( TK_MINUS==OP_Subtract );\n      assert( TK_REM==OP_Remainder );\n      assert( TK_BITAND==OP_BitAnd );\n      assert( TK_BITOR==OP_BitOr );\n      assert( TK_SLASH==OP_Divide );\n      assert( TK_LSHIFT==OP_ShiftLeft );\n      assert( TK_RSHIFT==OP_ShiftRight );\n      assert( TK_CONCAT==OP_Concat );\n      testcase( op==TK_AND );\n      testcase( op==TK_OR );\n      testcase( op==TK_PLUS );\n      testcase( op==TK_MINUS );\n      testcase( op==TK_REM );\n      testcase( op==TK_BITAND );\n      testcase( op==TK_BITOR );\n      testcase( op==TK_SLASH );\n      testcase( op==TK_LSHIFT );\n      testcase( op==TK_RSHIFT );\n      testcase( op==TK_CONCAT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      sqlite3VdbeAddOp3(v, op, r2, r1, target);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_UMINUS: {\n      Expr *pLeft = pExpr->pLeft;\n      assert( pLeft );\n      if( pLeft->op==TK_INTEGER ){\n        codeInteger(pParse, pLeft, 1, target);\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      }else if( pLeft->op==TK_FLOAT ){\n        assert( !ExprHasProperty(pExpr, EP_IntValue) );\n        codeReal(v, pLeft->u.zToken, 1, target);\n#endif\n      }else{\n        regFree1 = r1 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);\n        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);\n        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);\n        testcase( regFree2==0 );\n      }\n      inReg = target;\n      break;\n    }\n    case TK_BITNOT:\n    case TK_NOT: {\n      assert( TK_BITNOT==OP_BitNot );\n      assert( TK_NOT==OP_Not );\n      testcase( op==TK_BITNOT );\n      testcase( op==TK_NOT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      testcase( regFree1==0 );\n      inReg = target;\n      sqlite3VdbeAddOp2(v, op, r1, inReg);\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      int addr;\n      assert( TK_ISNULL==OP_IsNull );\n      assert( TK_NOTNULL==OP_NotNull );\n      testcase( op==TK_ISNULL );\n      testcase( op==TK_NOTNULL );\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      testcase( regFree1==0 );\n      addr = sqlite3VdbeAddOp1(v, op, r1);\n      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);\n      sqlite3VdbeJumpHere(v, addr);\n      break;\n    }\n    case TK_AGG_FUNCTION: {\n      AggInfo *pInfo = pExpr->pAggInfo;\n      if( pInfo==0 ){\n        assert( !ExprHasProperty(pExpr, EP_IntValue) );\n        sqlite3ErrorMsg(pParse, \"misuse of aggregate: %s()\", pExpr->u.zToken);\n      }else{\n        inReg = pInfo->aFunc[pExpr->iAgg].iMem;\n      }\n      break;\n    }\n    case TK_CONST_FUNC:\n    case TK_FUNCTION: {\n      ExprList *pFarg;       /* List of function arguments */\n      int nFarg;             /* Number of function arguments */\n      FuncDef *pDef;         /* The function definition object */\n      int nId;               /* Length of the function name in bytes */\n      const char *zId;       /* The function name */\n      int constMask = 0;     /* Mask of function arguments that are constant */\n      int i;                 /* Loop counter */\n      u8 enc = ENC(db);      /* The text encoding used by this database */\n      CollSeq *pColl = 0;    /* A collating sequence */\n\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      testcase( op==TK_CONST_FUNC );\n      testcase( op==TK_FUNCTION );\n      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){\n        pFarg = 0;\n      }else{\n        pFarg = pExpr->x.pList;\n      }\n      nFarg = pFarg ? pFarg->nExpr : 0;\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      zId = pExpr->u.zToken;\n      nId = sqlite3Strlen30(zId);\n      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);\n      if( pDef==0 ){\n        sqlite3ErrorMsg(pParse, \"unknown function: %.*s()\", nId, zId);\n        break;\n      }\n\n      /* Attempt a direct implementation of the built-in COALESCE() and\n      ** IFNULL() functions.  This avoids unnecessary evalation of\n      ** arguments past the first non-NULL argument.\n      */\n      if( pDef->flags & SQLITE_FUNC_COALESCE ){\n        int endCoalesce = sqlite3VdbeMakeLabel(v);\n        assert( nFarg>=2 );\n        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);\n        for(i=1; i<nFarg; i++){\n          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);\n          sqlite3ExprCacheRemove(pParse, target, 1);\n          sqlite3ExprCachePush(pParse);\n          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);\n          sqlite3ExprCachePop(pParse, 1);\n        }\n        sqlite3VdbeResolveLabel(v, endCoalesce);\n        break;\n      }\n\n\n      if( pFarg ){\n        r1 = sqlite3GetTempRange(pParse, nFarg);\n\n        /* For length() and typeof() functions with a column argument,\n        ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG\n        ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data\n        ** loading.\n        */\n        if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){\n          u8 exprOp;\n          assert( nFarg==1 );\n          assert( pFarg->a[0].pExpr!=0 );\n          exprOp = pFarg->a[0].pExpr->op;\n          if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){\n            assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );\n            assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );\n            testcase( pDef->flags==SQLITE_FUNC_LENGTH );\n            pFarg->a[0].pExpr->op2 = pDef->flags;\n          }\n        }\n\n        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */\n        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);\n        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */\n      }else{\n        r1 = 0;\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      /* Possibly overload the function if the first argument is\n      ** a virtual table column.\n      **\n      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the\n      ** second argument, not the first, as the argument to test to\n      ** see if it is a column in a virtual table.  This is done because\n      ** the left operand of infix functions (the operand we want to\n      ** control overloading) ends up as the second argument to the\n      ** function.  The expression \"A glob B\" is equivalent to \n      ** \"glob(B,A).  We want to use the A in \"A glob B\" to test\n      ** for function overloading.  But we use the B term in \"glob(B,A)\".\n      */\n      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){\n        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);\n      }else if( nFarg>0 ){\n        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);\n      }\n#endif\n      for(i=0; i<nFarg; i++){\n        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){\n          constMask |= (1<<i);\n        }\n        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){\n          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);\n        }\n      }\n      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){\n        if( !pColl ) pColl = db->pDfltColl; \n        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);\n      }\n      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,\n                        (char*)pDef, P4_FUNCDEF);\n      sqlite3VdbeChangeP5(v, (u8)nFarg);\n      if( nFarg ){\n        sqlite3ReleaseTempRange(pParse, r1, nFarg);\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_EXISTS:\n    case TK_SELECT: {\n      testcase( op==TK_EXISTS );\n      testcase( op==TK_SELECT );\n      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);\n      break;\n    }\n    case TK_IN: {\n      int destIfFalse = sqlite3VdbeMakeLabel(v);\n      int destIfNull = sqlite3VdbeMakeLabel(v);\n      sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);\n      sqlite3VdbeResolveLabel(v, destIfFalse);\n      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);\n      sqlite3VdbeResolveLabel(v, destIfNull);\n      break;\n    }\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n\n    /*\n    **    x BETWEEN y AND z\n    **\n    ** This is equivalent to\n    **\n    **    x>=y AND x<=z\n    **\n    ** X is stored in pExpr->pLeft.\n    ** Y is stored in pExpr->pList->a[0].pExpr.\n    ** Z is stored in pExpr->pList->a[1].pExpr.\n    */\n    case TK_BETWEEN: {\n      Expr *pLeft = pExpr->pLeft;\n      struct ExprList_item *pLItem = pExpr->x.pList->a;\n      Expr *pRight = pLItem->pExpr;\n\n      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      r3 = sqlite3GetTempReg(pParse);\n      r4 = sqlite3GetTempReg(pParse);\n      codeCompare(pParse, pLeft, pRight, OP_Ge,\n                  r1, r2, r3, SQLITE_STOREP2);\n      pLItem++;\n      pRight = pLItem->pExpr;\n      sqlite3ReleaseTempReg(pParse, regFree2);\n      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);\n      testcase( regFree2==0 );\n      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);\n      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);\n      sqlite3ReleaseTempReg(pParse, r3);\n      sqlite3ReleaseTempReg(pParse, r4);\n      break;\n    }\n    case TK_UPLUS: {\n      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);\n      break;\n    }\n\n    case TK_TRIGGER: {\n      /* If the opcode is TK_TRIGGER, then the expression is a reference\n      ** to a column in the new.* or old.* pseudo-tables available to\n      ** trigger programs. In this case Expr.iTable is set to 1 for the\n      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn\n      ** is set to the column of the pseudo-table to read, or to -1 to\n      ** read the rowid field.\n      **\n      ** The expression is implemented using an OP_Param opcode. The p1\n      ** parameter is set to 0 for an old.rowid reference, or to (i+1)\n      ** to reference another column of the old.* pseudo-table, where \n      ** i is the index of the column. For a new.rowid reference, p1 is\n      ** set to (n+1), where n is the number of columns in each pseudo-table.\n      ** For a reference to any other column in the new.* pseudo-table, p1\n      ** is set to (n+2+i), where n and i are as defined previously. For\n      ** example, if the table on which triggers are being fired is\n      ** declared as:\n      **\n      **   CREATE TABLE t1(a, b);\n      **\n      ** Then p1 is interpreted as follows:\n      **\n      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid\n      **   p1==1   ->    old.a         p1==4   ->    new.a\n      **   p1==2   ->    old.b         p1==5   ->    new.b       \n      */\n      Table *pTab = pExpr->pTab;\n      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;\n\n      assert( pExpr->iTable==0 || pExpr->iTable==1 );\n      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );\n      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );\n      assert( p1>=0 && p1<(pTab->nCol*2+2) );\n\n      sqlite3VdbeAddOp2(v, OP_Param, p1, target);\n      VdbeComment((v, \"%s.%s -> $%d\",\n        (pExpr->iTable ? \"new\" : \"old\"),\n        (pExpr->iColumn<0 ? \"rowid\" : pExpr->pTab->aCol[pExpr->iColumn].zName),\n        target\n      ));\n\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      /* If the column has REAL affinity, it may currently be stored as an\n      ** integer. Use OP_RealAffinity to make sure it is really real.  */\n      if( pExpr->iColumn>=0 \n       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL\n      ){\n        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);\n      }\n#endif\n      break;\n    }\n\n\n    /*\n    ** Form A:\n    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END\n    **\n    ** Form B:\n    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END\n    **\n    ** Form A is can be transformed into the equivalent form B as follows:\n    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...\n    **        WHEN x=eN THEN rN ELSE y END\n    **\n    ** X (if it exists) is in pExpr->pLeft.\n    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no\n    ** ELSE clause and no other term matches, then the result of the\n    ** exprssion is NULL.\n    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].\n    **\n    ** The result of the expression is the Ri for the first matching Ei,\n    ** or if there is no matching Ei, the ELSE term Y, or if there is\n    ** no ELSE term, NULL.\n    */\n    default: assert( op==TK_CASE ); {\n      int endLabel;                     /* GOTO label for end of CASE stmt */\n      int nextCase;                     /* GOTO label for next WHEN clause */\n      int nExpr;                        /* 2x number of WHEN terms */\n      int i;                            /* Loop counter */\n      ExprList *pEList;                 /* List of WHEN terms */\n      struct ExprList_item *aListelem;  /* Array of WHEN terms */\n      Expr opCompare;                   /* The X==Ei expression */\n      Expr cacheX;                      /* Cached expression X */\n      Expr *pX;                         /* The X expression */\n      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */\n      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )\n\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );\n      assert((pExpr->x.pList->nExpr % 2) == 0);\n      assert(pExpr->x.pList->nExpr > 0);\n      pEList = pExpr->x.pList;\n      aListelem = pEList->a;\n      nExpr = pEList->nExpr;\n      endLabel = sqlite3VdbeMakeLabel(v);\n      if( (pX = pExpr->pLeft)!=0 ){\n        cacheX = *pX;\n        testcase( pX->op==TK_COLUMN );\n        testcase( pX->op==TK_REGISTER );\n        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);\n        testcase( regFree1==0 );\n        cacheX.op = TK_REGISTER;\n        opCompare.op = TK_EQ;\n        opCompare.pLeft = &cacheX;\n        pTest = &opCompare;\n        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:\n        ** The value in regFree1 might get SCopy-ed into the file result.\n        ** So make sure that the regFree1 register is not reused for other\n        ** purposes and possibly overwritten.  */\n        regFree1 = 0;\n      }\n      for(i=0; i<nExpr; i=i+2){\n        sqlite3ExprCachePush(pParse);\n        if( pX ){\n          assert( pTest!=0 );\n          opCompare.pRight = aListelem[i].pExpr;\n        }else{\n          pTest = aListelem[i].pExpr;\n        }\n        nextCase = sqlite3VdbeMakeLabel(v);\n        testcase( pTest->op==TK_COLUMN );\n        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);\n        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );\n        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );\n        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);\n        sqlite3ExprCachePop(pParse, 1);\n        sqlite3VdbeResolveLabel(v, nextCase);\n      }\n      if( pExpr->pRight ){\n        sqlite3ExprCachePush(pParse);\n        sqlite3ExprCode(pParse, pExpr->pRight, target);\n        sqlite3ExprCachePop(pParse, 1);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, target);\n      }\n      assert( db->mallocFailed || pParse->nErr>0 \n           || pParse->iCacheLevel==iCacheLevel );\n      sqlite3VdbeResolveLabel(v, endLabel);\n      break;\n    }\n#ifndef SQLITE_OMIT_TRIGGER\n    case TK_RAISE: {\n      assert( pExpr->affinity==OE_Rollback \n           || pExpr->affinity==OE_Abort\n           || pExpr->affinity==OE_Fail\n           || pExpr->affinity==OE_Ignore\n      );\n      if( !pParse->pTriggerTab ){\n        sqlite3ErrorMsg(pParse,\n                       \"RAISE() may only be used within a trigger-program\");\n        return 0;\n      }\n      if( pExpr->affinity==OE_Abort ){\n        sqlite3MayAbort(pParse);\n      }\n      assert( !ExprHasProperty(pExpr, EP_IntValue) );\n      if( pExpr->affinity==OE_Ignore ){\n        sqlite3VdbeAddOp4(\n            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);\n      }else{\n        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);\n      }\n\n      break;\n    }\n#endif\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);\n  return inReg;\n}\n\n/*\n** Generate code to evaluate an expression and store the results\n** into a register.  Return the register number where the results\n** are stored.\n**\n** If the register is a temporary register that can be deallocated,\n** then write its number into *pReg.  If the result register is not\n** a temporary, then set *pReg to zero.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){\n  int r1 = sqlite3GetTempReg(pParse);\n  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);\n  if( r2==r1 ){\n    *pReg = r1;\n  }else{\n    sqlite3ReleaseTempReg(pParse, r1);\n    *pReg = 0;\n  }\n  return r2;\n}\n\n/*\n** Generate code that will evaluate expression pExpr and store the\n** results in register target.  The results are guaranteed to appear\n** in register target.\n*/\nSQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){\n  int inReg;\n\n  assert( target>0 && target<=pParse->nMem );\n  if( pExpr && pExpr->op==TK_REGISTER ){\n    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);\n  }else{\n    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);\n    assert( pParse->pVdbe || pParse->db->mallocFailed );\n    if( inReg!=target && pParse->pVdbe ){\n      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);\n    }\n  }\n  return target;\n}\n\n/*\n** Generate code that evalutes the given expression and puts the result\n** in register target.\n**\n** Also make a copy of the expression results into another \"cache\" register\n** and modify the expression so that the next time it is evaluated,\n** the result is a copy of the cache register.\n**\n** This routine is used for expressions that are used multiple \n** times.  They are evaluated once and the results of the expression\n** are reused.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){\n  Vdbe *v = pParse->pVdbe;\n  int inReg;\n  inReg = sqlite3ExprCode(pParse, pExpr, target);\n  assert( target>0 );\n  /* This routine is called for terms to INSERT or UPDATE.  And the only\n  ** other place where expressions can be converted into TK_REGISTER is\n  ** in WHERE clause processing.  So as currently implemented, there is\n  ** no way for a TK_REGISTER to exist here.  But it seems prudent to\n  ** keep the ALWAYS() in case the conditions above change with future\n  ** modifications or enhancements. */\n  if( ALWAYS(pExpr->op!=TK_REGISTER) ){  \n    int iMem;\n    iMem = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);\n    pExpr->iTable = iMem;\n    pExpr->op2 = pExpr->op;\n    pExpr->op = TK_REGISTER;\n  }\n  return inReg;\n}\n\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n/*\n** Generate a human-readable explanation of an expression tree.\n*/\nSQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){\n  int op;                   /* The opcode being coded */\n  const char *zBinOp = 0;   /* Binary operator */\n  const char *zUniOp = 0;   /* Unary operator */\n  if( pExpr==0 ){\n    op = TK_NULL;\n  }else{\n    op = pExpr->op;\n  }\n  switch( op ){\n    case TK_AGG_COLUMN: {\n      sqlite3ExplainPrintf(pOut, \"AGG{%d:%d}\",\n            pExpr->iTable, pExpr->iColumn);\n      break;\n    }\n    case TK_COLUMN: {\n      if( pExpr->iTable<0 ){\n        /* This only happens when coding check constraints */\n        sqlite3ExplainPrintf(pOut, \"COLUMN(%d)\", pExpr->iColumn);\n      }else{\n        sqlite3ExplainPrintf(pOut, \"{%d:%d}\",\n                             pExpr->iTable, pExpr->iColumn);\n      }\n      break;\n    }\n    case TK_INTEGER: {\n      if( pExpr->flags & EP_IntValue ){\n        sqlite3ExplainPrintf(pOut, \"%d\", pExpr->u.iValue);\n      }else{\n        sqlite3ExplainPrintf(pOut, \"%s\", pExpr->u.zToken);\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    case TK_FLOAT: {\n      sqlite3ExplainPrintf(pOut,\"%s\", pExpr->u.zToken);\n      break;\n    }\n#endif\n    case TK_STRING: {\n      sqlite3ExplainPrintf(pOut,\"%Q\", pExpr->u.zToken);\n      break;\n    }\n    case TK_NULL: {\n      sqlite3ExplainPrintf(pOut,\"NULL\");\n      break;\n    }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case TK_BLOB: {\n      sqlite3ExplainPrintf(pOut,\"%s\", pExpr->u.zToken);\n      break;\n    }\n#endif\n    case TK_VARIABLE: {\n      sqlite3ExplainPrintf(pOut,\"VARIABLE(%s,%d)\",\n                           pExpr->u.zToken, pExpr->iColumn);\n      break;\n    }\n    case TK_REGISTER: {\n      sqlite3ExplainPrintf(pOut,\"REGISTER(%d)\", pExpr->iTable);\n      break;\n    }\n    case TK_AS: {\n      sqlite3ExplainExpr(pOut, pExpr->pLeft);\n      break;\n    }\n#ifndef SQLITE_OMIT_CAST\n    case TK_CAST: {\n      /* Expressions of the form:   CAST(pLeft AS token) */\n      const char *zAff = \"unk\";\n      switch( sqlite3AffinityType(pExpr->u.zToken) ){\n        case SQLITE_AFF_TEXT:    zAff = \"TEXT\";     break;\n        case SQLITE_AFF_NONE:    zAff = \"NONE\";     break;\n        case SQLITE_AFF_NUMERIC: zAff = \"NUMERIC\";  break;\n        case SQLITE_AFF_INTEGER: zAff = \"INTEGER\";  break;\n        case SQLITE_AFF_REAL:    zAff = \"REAL\";     break;\n      }\n      sqlite3ExplainPrintf(pOut, \"CAST-%s(\", zAff);\n      sqlite3ExplainExpr(pOut, pExpr->pLeft);\n      sqlite3ExplainPrintf(pOut, \")\");\n      break;\n    }\n#endif /* SQLITE_OMIT_CAST */\n    case TK_LT:      zBinOp = \"LT\";     break;\n    case TK_LE:      zBinOp = \"LE\";     break;\n    case TK_GT:      zBinOp = \"GT\";     break;\n    case TK_GE:      zBinOp = \"GE\";     break;\n    case TK_NE:      zBinOp = \"NE\";     break;\n    case TK_EQ:      zBinOp = \"EQ\";     break;\n    case TK_IS:      zBinOp = \"IS\";     break;\n    case TK_ISNOT:   zBinOp = \"ISNOT\";  break;\n    case TK_AND:     zBinOp = \"AND\";    break;\n    case TK_OR:      zBinOp = \"OR\";     break;\n    case TK_PLUS:    zBinOp = \"ADD\";    break;\n    case TK_STAR:    zBinOp = \"MUL\";    break;\n    case TK_MINUS:   zBinOp = \"SUB\";    break;\n    case TK_REM:     zBinOp = \"REM\";    break;\n    case TK_BITAND:  zBinOp = \"BITAND\"; break;\n    case TK_BITOR:   zBinOp = \"BITOR\";  break;\n    case TK_SLASH:   zBinOp = \"DIV\";    break;\n    case TK_LSHIFT:  zBinOp = \"LSHIFT\"; break;\n    case TK_RSHIFT:  zBinOp = \"RSHIFT\"; break;\n    case TK_CONCAT:  zBinOp = \"CONCAT\"; break;\n\n    case TK_UMINUS:  zUniOp = \"UMINUS\"; break;\n    case TK_UPLUS:   zUniOp = \"UPLUS\";  break;\n    case TK_BITNOT:  zUniOp = \"BITNOT\"; break;\n    case TK_NOT:     zUniOp = \"NOT\";    break;\n    case TK_ISNULL:  zUniOp = \"ISNULL\"; break;\n    case TK_NOTNULL: zUniOp = \"NOTNULL\"; break;\n\n    case TK_AGG_FUNCTION:\n    case TK_CONST_FUNC:\n    case TK_FUNCTION: {\n      ExprList *pFarg;       /* List of function arguments */\n      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){\n        pFarg = 0;\n      }else{\n        pFarg = pExpr->x.pList;\n      }\n      if( op==TK_AGG_FUNCTION ){\n        sqlite3ExplainPrintf(pOut, \"AGG_FUNCTION%d:%s(\",\n                             pExpr->op2, pExpr->u.zToken);\n      }else{\n        sqlite3ExplainPrintf(pOut, \"FUNCTION:%s(\", pExpr->u.zToken);\n      }\n      if( pFarg ){\n        sqlite3ExplainExprList(pOut, pFarg);\n      }\n      sqlite3ExplainPrintf(pOut, \")\");\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_EXISTS: {\n      sqlite3ExplainPrintf(pOut, \"EXISTS(\");\n      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);\n      sqlite3ExplainPrintf(pOut,\")\");\n      break;\n    }\n    case TK_SELECT: {\n      sqlite3ExplainPrintf(pOut, \"(\");\n      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);\n      sqlite3ExplainPrintf(pOut, \")\");\n      break;\n    }\n    case TK_IN: {\n      sqlite3ExplainPrintf(pOut, \"IN(\");\n      sqlite3ExplainExpr(pOut, pExpr->pLeft);\n      sqlite3ExplainPrintf(pOut, \",\");\n      if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);\n      }else{\n        sqlite3ExplainExprList(pOut, pExpr->x.pList);\n      }\n      sqlite3ExplainPrintf(pOut, \")\");\n      break;\n    }\n#endif /* SQLITE_OMIT_SUBQUERY */\n\n    /*\n    **    x BETWEEN y AND z\n    **\n    ** This is equivalent to\n    **\n    **    x>=y AND x<=z\n    **\n    ** X is stored in pExpr->pLeft.\n    ** Y is stored in pExpr->pList->a[0].pExpr.\n    ** Z is stored in pExpr->pList->a[1].pExpr.\n    */\n    case TK_BETWEEN: {\n      Expr *pX = pExpr->pLeft;\n      Expr *pY = pExpr->x.pList->a[0].pExpr;\n      Expr *pZ = pExpr->x.pList->a[1].pExpr;\n      sqlite3ExplainPrintf(pOut, \"BETWEEN(\");\n      sqlite3ExplainExpr(pOut, pX);\n      sqlite3ExplainPrintf(pOut, \",\");\n      sqlite3ExplainExpr(pOut, pY);\n      sqlite3ExplainPrintf(pOut, \",\");\n      sqlite3ExplainExpr(pOut, pZ);\n      sqlite3ExplainPrintf(pOut, \")\");\n      break;\n    }\n    case TK_TRIGGER: {\n      /* If the opcode is TK_TRIGGER, then the expression is a reference\n      ** to a column in the new.* or old.* pseudo-tables available to\n      ** trigger programs. In this case Expr.iTable is set to 1 for the\n      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn\n      ** is set to the column of the pseudo-table to read, or to -1 to\n      ** read the rowid field.\n      */\n      sqlite3ExplainPrintf(pOut, \"%s(%d)\", \n          pExpr->iTable ? \"NEW\" : \"OLD\", pExpr->iColumn);\n      break;\n    }\n    case TK_CASE: {\n      sqlite3ExplainPrintf(pOut, \"CASE(\");\n      sqlite3ExplainExpr(pOut, pExpr->pLeft);\n      sqlite3ExplainPrintf(pOut, \",\");\n      sqlite3ExplainExprList(pOut, pExpr->x.pList);\n      break;\n    }\n#ifndef SQLITE_OMIT_TRIGGER\n    case TK_RAISE: {\n      const char *zType = \"unk\";\n      switch( pExpr->affinity ){\n        case OE_Rollback:   zType = \"rollback\";  break;\n        case OE_Abort:      zType = \"abort\";     break;\n        case OE_Fail:       zType = \"fail\";      break;\n        case OE_Ignore:     zType = \"ignore\";    break;\n      }\n      sqlite3ExplainPrintf(pOut, \"RAISE-%s(%s)\", zType, pExpr->u.zToken);\n      break;\n    }\n#endif\n  }\n  if( zBinOp ){\n    sqlite3ExplainPrintf(pOut,\"%s(\", zBinOp);\n    sqlite3ExplainExpr(pOut, pExpr->pLeft);\n    sqlite3ExplainPrintf(pOut,\",\");\n    sqlite3ExplainExpr(pOut, pExpr->pRight);\n    sqlite3ExplainPrintf(pOut,\")\");\n  }else if( zUniOp ){\n    sqlite3ExplainPrintf(pOut,\"%s(\", zUniOp);\n    sqlite3ExplainExpr(pOut, pExpr->pLeft);\n    sqlite3ExplainPrintf(pOut,\")\");\n  }\n}\n#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */\n\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n/*\n** Generate a human-readable explanation of an expression list.\n*/\nSQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){\n  int i;\n  if( pList==0 || pList->nExpr==0 ){\n    sqlite3ExplainPrintf(pOut, \"(empty-list)\");\n    return;\n  }else if( pList->nExpr==1 ){\n    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);\n  }else{\n    sqlite3ExplainPush(pOut);\n    for(i=0; i<pList->nExpr; i++){\n      sqlite3ExplainPrintf(pOut, \"item[%d] = \", i);\n      sqlite3ExplainPush(pOut);\n      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);\n      sqlite3ExplainPop(pOut);\n      if( i<pList->nExpr-1 ){\n        sqlite3ExplainNL(pOut);\n      }\n    }\n    sqlite3ExplainPop(pOut);\n  }\n}\n#endif /* SQLITE_DEBUG */\n\n/*\n** Return TRUE if pExpr is an constant expression that is appropriate\n** for factoring out of a loop.  Appropriate expressions are:\n**\n**    *  Any expression that evaluates to two or more opcodes.\n**\n**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, \n**       or OP_Variable that does not need to be placed in a \n**       specific register.\n**\n** There is no point in factoring out single-instruction constant\n** expressions that need to be placed in a particular register.  \n** We could factor them out, but then we would end up adding an\n** OP_SCopy instruction to move the value into the correct register\n** later.  We might as well just use the original instruction and\n** avoid the OP_SCopy.\n*/\nstatic int isAppropriateForFactoring(Expr *p){\n  if( !sqlite3ExprIsConstantNotJoin(p) ){\n    return 0;  /* Only constant expressions are appropriate for factoring */\n  }\n  if( (p->flags & EP_FixedDest)==0 ){\n    return 1;  /* Any constant without a fixed destination is appropriate */\n  }\n  while( p->op==TK_UPLUS ) p = p->pLeft;\n  switch( p->op ){\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case TK_BLOB:\n#endif\n    case TK_VARIABLE:\n    case TK_INTEGER:\n    case TK_FLOAT:\n    case TK_NULL:\n    case TK_STRING: {\n      testcase( p->op==TK_BLOB );\n      testcase( p->op==TK_VARIABLE );\n      testcase( p->op==TK_INTEGER );\n      testcase( p->op==TK_FLOAT );\n      testcase( p->op==TK_NULL );\n      testcase( p->op==TK_STRING );\n      /* Single-instruction constants with a fixed destination are\n      ** better done in-line.  If we factor them, they will just end\n      ** up generating an OP_SCopy to move the value to the destination\n      ** register. */\n      return 0;\n    }\n    case TK_UMINUS: {\n      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){\n        return 0;\n      }\n      break;\n    }\n    default: {\n      break;\n    }\n  }\n  return 1;\n}\n\n/*\n** If pExpr is a constant expression that is appropriate for\n** factoring out of a loop, then evaluate the expression\n** into a register and convert the expression into a TK_REGISTER\n** expression.\n*/\nstatic int evalConstExpr(Walker *pWalker, Expr *pExpr){\n  Parse *pParse = pWalker->pParse;\n  switch( pExpr->op ){\n    case TK_IN:\n    case TK_REGISTER: {\n      return WRC_Prune;\n    }\n    case TK_FUNCTION:\n    case TK_AGG_FUNCTION:\n    case TK_CONST_FUNC: {\n      /* The arguments to a function have a fixed destination.\n      ** Mark them this way to avoid generated unneeded OP_SCopy\n      ** instructions. \n      */\n      ExprList *pList = pExpr->x.pList;\n      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n      if( pList ){\n        int i = pList->nExpr;\n        struct ExprList_item *pItem = pList->a;\n        for(; i>0; i--, pItem++){\n          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;\n        }\n      }\n      break;\n    }\n  }\n  if( isAppropriateForFactoring(pExpr) ){\n    int r1 = ++pParse->nMem;\n    int r2;\n    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);\n    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);\n    pExpr->op2 = pExpr->op;\n    pExpr->op = TK_REGISTER;\n    pExpr->iTable = r2;\n    return WRC_Prune;\n  }\n  return WRC_Continue;\n}\n\n/*\n** Preevaluate constant subexpressions within pExpr and store the\n** results in registers.  Modify pExpr so that the constant subexpresions\n** are TK_REGISTER opcodes that refer to the precomputed values.\n**\n** This routine is a no-op if the jump to the cookie-check code has\n** already occur.  Since the cookie-check jump is generated prior to\n** any other serious processing, this check ensures that there is no\n** way to accidently bypass the constant initializations.\n**\n** This routine is also a no-op if the SQLITE_FactorOutConst optimization\n** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)\n** interface.  This allows test logic to verify that the same answer is\n** obtained for queries regardless of whether or not constants are\n** precomputed into registers or if they are inserted in-line.\n*/\nSQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){\n  Walker w;\n  if( pParse->cookieGoto ) return;\n  if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;\n  w.xExprCallback = evalConstExpr;\n  w.xSelectCallback = 0;\n  w.pParse = pParse;\n  sqlite3WalkExpr(&w, pExpr);\n}\n\n\n/*\n** Generate code that pushes the value of every element of the given\n** expression list into a sequence of registers beginning at target.\n**\n** Return the number of elements evaluated.\n*/\nSQLITE_PRIVATE int sqlite3ExprCodeExprList(\n  Parse *pParse,     /* Parsing context */\n  ExprList *pList,   /* The expression list to be coded */\n  int target,        /* Where to write results */\n  int doHardCopy     /* Make a hard copy of every element */\n){\n  struct ExprList_item *pItem;\n  int i, n;\n  assert( pList!=0 );\n  assert( target>0 );\n  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */\n  n = pList->nExpr;\n  for(pItem=pList->a, i=0; i<n; i++, pItem++){\n    Expr *pExpr = pItem->pExpr;\n    int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);\n    if( inReg!=target+i ){\n      sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,\n                        inReg, target+i);\n    }\n  }\n  return n;\n}\n\n/*\n** Generate code for a BETWEEN operator.\n**\n**    x BETWEEN y AND z\n**\n** The above is equivalent to \n**\n**    x>=y AND x<=z\n**\n** Code it as such, taking care to do the common subexpression\n** elementation of x.\n*/\nstatic void exprCodeBetween(\n  Parse *pParse,    /* Parsing and code generating context */\n  Expr *pExpr,      /* The BETWEEN expression */\n  int dest,         /* Jump here if the jump is taken */\n  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */\n  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */\n){\n  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */\n  Expr compLeft;    /* The  x>=y  term */\n  Expr compRight;   /* The  x<=z  term */\n  Expr exprX;       /* The  x  subexpression */\n  int regFree1 = 0; /* Temporary use register */\n\n  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n  exprX = *pExpr->pLeft;\n  exprAnd.op = TK_AND;\n  exprAnd.pLeft = &compLeft;\n  exprAnd.pRight = &compRight;\n  compLeft.op = TK_GE;\n  compLeft.pLeft = &exprX;\n  compLeft.pRight = pExpr->x.pList->a[0].pExpr;\n  compRight.op = TK_LE;\n  compRight.pLeft = &exprX;\n  compRight.pRight = pExpr->x.pList->a[1].pExpr;\n  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);\n  exprX.op = TK_REGISTER;\n  if( jumpIfTrue ){\n    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);\n  }else{\n    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n\n  /* Ensure adequate test coverage */\n  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );\n  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );\n  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );\n  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );\n  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );\n  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );\n  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );\n  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );\n}\n\n/*\n** Generate code for a boolean expression such that a jump is made\n** to the label \"dest\" if the expression is true but execution\n** continues straight thru if the expression is false.\n**\n** If the expression evaluates to NULL (neither true nor false), then\n** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.\n**\n** This code depends on the fact that certain token values (ex: TK_EQ)\n** are the same as opcode values (ex: OP_Eq) that implement the corresponding\n** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in\n** the make process cause these values to align.  Assert()s in the code\n** below verify that the numbers are aligned correctly.\n*/\nSQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){\n  Vdbe *v = pParse->pVdbe;\n  int op = 0;\n  int regFree1 = 0;\n  int regFree2 = 0;\n  int r1, r2;\n\n  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );\n  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */\n  if( NEVER(pExpr==0) ) return;  /* No way this can happen */\n  op = pExpr->op;\n  switch( op ){\n    case TK_AND: {\n      int d2 = sqlite3VdbeMakeLabel(v);\n      testcase( jumpIfNull==0 );\n      sqlite3ExprCachePush(pParse);\n      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);\n      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);\n      sqlite3VdbeResolveLabel(v, d2);\n      sqlite3ExprCachePop(pParse, 1);\n      break;\n    }\n    case TK_OR: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);\n      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);\n      break;\n    }\n    case TK_NOT: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);\n      break;\n    }\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      assert( TK_LT==OP_Lt );\n      assert( TK_LE==OP_Le );\n      assert( TK_GT==OP_Gt );\n      assert( TK_GE==OP_Ge );\n      assert( TK_EQ==OP_Eq );\n      assert( TK_NE==OP_Ne );\n      testcase( op==TK_LT );\n      testcase( op==TK_LE );\n      testcase( op==TK_GT );\n      testcase( op==TK_GE );\n      testcase( op==TK_EQ );\n      testcase( op==TK_NE );\n      testcase( jumpIfNull==0 );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, jumpIfNull);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT: {\n      testcase( op==TK_IS );\n      testcase( op==TK_ISNOT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      op = (op==TK_IS) ? TK_EQ : TK_NE;\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, SQLITE_NULLEQ);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      assert( TK_ISNULL==OP_IsNull );\n      assert( TK_NOTNULL==OP_NotNull );\n      testcase( op==TK_ISNULL );\n      testcase( op==TK_NOTNULL );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      sqlite3VdbeAddOp2(v, op, r1, dest);\n      testcase( regFree1==0 );\n      break;\n    }\n    case TK_BETWEEN: {\n      testcase( jumpIfNull==0 );\n      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_IN: {\n      int destIfFalse = sqlite3VdbeMakeLabel(v);\n      int destIfNull = jumpIfNull ? dest : destIfFalse;\n      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);\n      sqlite3VdbeResolveLabel(v, destIfFalse);\n      break;\n    }\n#endif\n    default: {\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);\n      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);\n      testcase( regFree1==0 );\n      testcase( jumpIfNull==0 );\n      break;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);  \n}\n\n/*\n** Generate code for a boolean expression such that a jump is made\n** to the label \"dest\" if the expression is false but execution\n** continues straight thru if the expression is true.\n**\n** If the expression evaluates to NULL (neither true nor false) then\n** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull\n** is 0.\n*/\nSQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){\n  Vdbe *v = pParse->pVdbe;\n  int op = 0;\n  int regFree1 = 0;\n  int regFree2 = 0;\n  int r1, r2;\n\n  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );\n  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */\n  if( pExpr==0 )    return;\n\n  /* The value of pExpr->op and op are related as follows:\n  **\n  **       pExpr->op            op\n  **       ---------          ----------\n  **       TK_ISNULL          OP_NotNull\n  **       TK_NOTNULL         OP_IsNull\n  **       TK_NE              OP_Eq\n  **       TK_EQ              OP_Ne\n  **       TK_GT              OP_Le\n  **       TK_LE              OP_Gt\n  **       TK_GE              OP_Lt\n  **       TK_LT              OP_Ge\n  **\n  ** For other values of pExpr->op, op is undefined and unused.\n  ** The value of TK_ and OP_ constants are arranged such that we\n  ** can compute the mapping above using the following expression.\n  ** Assert()s verify that the computation is correct.\n  */\n  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);\n\n  /* Verify correct alignment of TK_ and OP_ constants\n  */\n  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );\n  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );\n  assert( pExpr->op!=TK_NE || op==OP_Eq );\n  assert( pExpr->op!=TK_EQ || op==OP_Ne );\n  assert( pExpr->op!=TK_LT || op==OP_Ge );\n  assert( pExpr->op!=TK_LE || op==OP_Gt );\n  assert( pExpr->op!=TK_GT || op==OP_Le );\n  assert( pExpr->op!=TK_GE || op==OP_Lt );\n\n  switch( pExpr->op ){\n    case TK_AND: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);\n      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);\n      break;\n    }\n    case TK_OR: {\n      int d2 = sqlite3VdbeMakeLabel(v);\n      testcase( jumpIfNull==0 );\n      sqlite3ExprCachePush(pParse);\n      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);\n      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);\n      sqlite3VdbeResolveLabel(v, d2);\n      sqlite3ExprCachePop(pParse, 1);\n      break;\n    }\n    case TK_NOT: {\n      testcase( jumpIfNull==0 );\n      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);\n      break;\n    }\n    case TK_LT:\n    case TK_LE:\n    case TK_GT:\n    case TK_GE:\n    case TK_NE:\n    case TK_EQ: {\n      testcase( op==TK_LT );\n      testcase( op==TK_LE );\n      testcase( op==TK_GT );\n      testcase( op==TK_GE );\n      testcase( op==TK_EQ );\n      testcase( op==TK_NE );\n      testcase( jumpIfNull==0 );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, jumpIfNull);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_IS:\n    case TK_ISNOT: {\n      testcase( pExpr->op==TK_IS );\n      testcase( pExpr->op==TK_ISNOT );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);\n      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;\n      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,\n                  r1, r2, dest, SQLITE_NULLEQ);\n      testcase( regFree1==0 );\n      testcase( regFree2==0 );\n      break;\n    }\n    case TK_ISNULL:\n    case TK_NOTNULL: {\n      testcase( op==TK_ISNULL );\n      testcase( op==TK_NOTNULL );\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);\n      sqlite3VdbeAddOp2(v, op, r1, dest);\n      testcase( regFree1==0 );\n      break;\n    }\n    case TK_BETWEEN: {\n      testcase( jumpIfNull==0 );\n      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_IN: {\n      if( jumpIfNull ){\n        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);\n      }else{\n        int destIfNull = sqlite3VdbeMakeLabel(v);\n        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);\n        sqlite3VdbeResolveLabel(v, destIfNull);\n      }\n      break;\n    }\n#endif\n    default: {\n      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);\n      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);\n      testcase( regFree1==0 );\n      testcase( jumpIfNull==0 );\n      break;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, regFree1);\n  sqlite3ReleaseTempReg(pParse, regFree2);\n}\n\n/*\n** Do a deep comparison of two expression trees.  Return 0 if the two\n** expressions are completely identical.  Return 1 if they differ only\n** by a COLLATE operator at the top level.  Return 2 if there are differences\n** other than the top-level COLLATE operator.\n**\n** Sometimes this routine will return 2 even if the two expressions\n** really are equivalent.  If we cannot prove that the expressions are\n** identical, we return 2 just to be safe.  So if this routine\n** returns 2, then you do not really know for certain if the two\n** expressions are the same.  But if you get a 0 or 1 return, then you\n** can be sure the expressions are the same.  In the places where\n** this routine is used, it does not hurt to get an extra 2 - that\n** just might result in some slightly slower code.  But returning\n** an incorrect 0 or 1 could lead to a malfunction.\n*/\nSQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){\n  if( pA==0||pB==0 ){\n    return pB==pA ? 0 : 2;\n  }\n  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );\n  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );\n  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){\n    return 2;\n  }\n  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;\n  if( pA->op!=pB->op ) return 2;\n  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;\n  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;\n  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;\n  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;\n  if( ExprHasProperty(pA, EP_IntValue) ){\n    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){\n      return 2;\n    }\n  }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){\n    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;\n    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){\n      return 2;\n    }\n  }\n  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;\n  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;\n  return 0;\n}\n\n/*\n** Compare two ExprList objects.  Return 0 if they are identical and \n** non-zero if they differ in any way.\n**\n** This routine might return non-zero for equivalent ExprLists.  The\n** only consequence will be disabled optimizations.  But this routine\n** must never return 0 if the two ExprList objects are different, or\n** a malfunction will result.\n**\n** Two NULL pointers are considered to be the same.  But a NULL pointer\n** always differs from a non-NULL pointer.\n*/\nSQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){\n  int i;\n  if( pA==0 && pB==0 ) return 0;\n  if( pA==0 || pB==0 ) return 1;\n  if( pA->nExpr!=pB->nExpr ) return 1;\n  for(i=0; i<pA->nExpr; i++){\n    Expr *pExprA = pA->a[i].pExpr;\n    Expr *pExprB = pB->a[i].pExpr;\n    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;\n    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;\n  }\n  return 0;\n}\n\n/*\n** An instance of the following structure is used by the tree walker\n** to count references to table columns in the arguments of an \n** aggregate function, in order to implement the\n** sqlite3FunctionThisSrc() routine.\n*/\nstruct SrcCount {\n  SrcList *pSrc;   /* One particular FROM clause in a nested query */\n  int nThis;       /* Number of references to columns in pSrcList */\n  int nOther;      /* Number of references to columns in other FROM clauses */\n};\n\n/*\n** Count the number of references to columns.\n*/\nstatic int exprSrcCount(Walker *pWalker, Expr *pExpr){\n  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()\n  ** is always called before sqlite3ExprAnalyzeAggregates() and so the\n  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If\n  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the\n  ** NEVER() will need to be removed. */\n  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){\n    int i;\n    struct SrcCount *p = pWalker->u.pSrcCount;\n    SrcList *pSrc = p->pSrc;\n    for(i=0; i<pSrc->nSrc; i++){\n      if( pExpr->iTable==pSrc->a[i].iCursor ) break;\n    }\n    if( i<pSrc->nSrc ){\n      p->nThis++;\n    }else{\n      p->nOther++;\n    }\n  }\n  return WRC_Continue;\n}\n\n/*\n** Determine if any of the arguments to the pExpr Function reference\n** pSrcList.  Return true if they do.  Also return true if the function\n** has no arguments or has only constant arguments.  Return false if pExpr\n** references columns but not columns of tables found in pSrcList.\n*/\nSQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){\n  Walker w;\n  struct SrcCount cnt;\n  assert( pExpr->op==TK_AGG_FUNCTION );\n  memset(&w, 0, sizeof(w));\n  w.xExprCallback = exprSrcCount;\n  w.u.pSrcCount = &cnt;\n  cnt.pSrc = pSrcList;\n  cnt.nThis = 0;\n  cnt.nOther = 0;\n  sqlite3WalkExprList(&w, pExpr->x.pList);\n  return cnt.nThis>0 || cnt.nOther==0;\n}\n\n/*\n** Add a new element to the pAggInfo->aCol[] array.  Return the index of\n** the new element.  Return a negative number if malloc fails.\n*/\nstatic int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){\n  int i;\n  pInfo->aCol = sqlite3ArrayAllocate(\n       db,\n       pInfo->aCol,\n       sizeof(pInfo->aCol[0]),\n       &pInfo->nColumn,\n       &i\n  );\n  return i;\n}    \n\n/*\n** Add a new element to the pAggInfo->aFunc[] array.  Return the index of\n** the new element.  Return a negative number if malloc fails.\n*/\nstatic int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){\n  int i;\n  pInfo->aFunc = sqlite3ArrayAllocate(\n       db, \n       pInfo->aFunc,\n       sizeof(pInfo->aFunc[0]),\n       &pInfo->nFunc,\n       &i\n  );\n  return i;\n}    \n\n/*\n** This is the xExprCallback for a tree walker.  It is used to\n** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates\n** for additional information.\n*/\nstatic int analyzeAggregate(Walker *pWalker, Expr *pExpr){\n  int i;\n  NameContext *pNC = pWalker->u.pNC;\n  Parse *pParse = pNC->pParse;\n  SrcList *pSrcList = pNC->pSrcList;\n  AggInfo *pAggInfo = pNC->pAggInfo;\n\n  switch( pExpr->op ){\n    case TK_AGG_COLUMN:\n    case TK_COLUMN: {\n      testcase( pExpr->op==TK_AGG_COLUMN );\n      testcase( pExpr->op==TK_COLUMN );\n      /* Check to see if the column is in one of the tables in the FROM\n      ** clause of the aggregate query */\n      if( ALWAYS(pSrcList!=0) ){\n        struct SrcList_item *pItem = pSrcList->a;\n        for(i=0; i<pSrcList->nSrc; i++, pItem++){\n          struct AggInfo_col *pCol;\n          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n          if( pExpr->iTable==pItem->iCursor ){\n            /* If we reach this point, it means that pExpr refers to a table\n            ** that is in the FROM clause of the aggregate query.  \n            **\n            ** Make an entry for the column in pAggInfo->aCol[] if there\n            ** is not an entry there already.\n            */\n            int k;\n            pCol = pAggInfo->aCol;\n            for(k=0; k<pAggInfo->nColumn; k++, pCol++){\n              if( pCol->iTable==pExpr->iTable &&\n                  pCol->iColumn==pExpr->iColumn ){\n                break;\n              }\n            }\n            if( (k>=pAggInfo->nColumn)\n             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 \n            ){\n              pCol = &pAggInfo->aCol[k];\n              pCol->pTab = pExpr->pTab;\n              pCol->iTable = pExpr->iTable;\n              pCol->iColumn = pExpr->iColumn;\n              pCol->iMem = ++pParse->nMem;\n              pCol->iSorterColumn = -1;\n              pCol->pExpr = pExpr;\n              if( pAggInfo->pGroupBy ){\n                int j, n;\n                ExprList *pGB = pAggInfo->pGroupBy;\n                struct ExprList_item *pTerm = pGB->a;\n                n = pGB->nExpr;\n                for(j=0; j<n; j++, pTerm++){\n                  Expr *pE = pTerm->pExpr;\n                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&\n                      pE->iColumn==pExpr->iColumn ){\n                    pCol->iSorterColumn = j;\n                    break;\n                  }\n                }\n              }\n              if( pCol->iSorterColumn<0 ){\n                pCol->iSorterColumn = pAggInfo->nSortingColumn++;\n              }\n            }\n            /* There is now an entry for pExpr in pAggInfo->aCol[] (either\n            ** because it was there before or because we just created it).\n            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that\n            ** pAggInfo->aCol[] entry.\n            */\n            ExprSetIrreducible(pExpr);\n            pExpr->pAggInfo = pAggInfo;\n            pExpr->op = TK_AGG_COLUMN;\n            pExpr->iAgg = (i16)k;\n            break;\n          } /* endif pExpr->iTable==pItem->iCursor */\n        } /* end loop over pSrcList */\n      }\n      return WRC_Prune;\n    }\n    case TK_AGG_FUNCTION: {\n      if( (pNC->ncFlags & NC_InAggFunc)==0\n       && pWalker->walkerDepth==pExpr->op2\n      ){\n        /* Check to see if pExpr is a duplicate of another aggregate \n        ** function that is already in the pAggInfo structure\n        */\n        struct AggInfo_func *pItem = pAggInfo->aFunc;\n        for(i=0; i<pAggInfo->nFunc; i++, pItem++){\n          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){\n            break;\n          }\n        }\n        if( i>=pAggInfo->nFunc ){\n          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]\n          */\n          u8 enc = ENC(pParse->db);\n          i = addAggInfoFunc(pParse->db, pAggInfo);\n          if( i>=0 ){\n            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n            pItem = &pAggInfo->aFunc[i];\n            pItem->pExpr = pExpr;\n            pItem->iMem = ++pParse->nMem;\n            assert( !ExprHasProperty(pExpr, EP_IntValue) );\n            pItem->pFunc = sqlite3FindFunction(pParse->db,\n                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),\n                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);\n            if( pExpr->flags & EP_Distinct ){\n              pItem->iDistinct = pParse->nTab++;\n            }else{\n              pItem->iDistinct = -1;\n            }\n          }\n        }\n        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry\n        */\n        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );\n        ExprSetIrreducible(pExpr);\n        pExpr->iAgg = (i16)i;\n        pExpr->pAggInfo = pAggInfo;\n      }\n      return WRC_Prune;\n    }\n  }\n  return WRC_Continue;\n}\nstatic int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){\n  UNUSED_PARAMETER(pWalker);\n  UNUSED_PARAMETER(pSelect);\n  return WRC_Continue;\n}\n\n/*\n** Analyze the given expression looking for aggregate functions and\n** for variables that need to be added to the pParse->aAgg[] array.\n** Make additional entries to the pParse->aAgg[] array as necessary.\n**\n** This routine should only be called after the expression has been\n** analyzed by sqlite3ResolveExprNames().\n*/\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){\n  Walker w;\n  memset(&w, 0, sizeof(w));\n  w.xExprCallback = analyzeAggregate;\n  w.xSelectCallback = analyzeAggregatesInSelect;\n  w.u.pNC = pNC;\n  assert( pNC->pSrcList!=0 );\n  sqlite3WalkExpr(&w, pExpr);\n}\n\n/*\n** Call sqlite3ExprAnalyzeAggregates() for every expression in an\n** expression list.  Return the number of errors.\n**\n** If an error is found, the analysis is cut short.\n*/\nSQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){\n  struct ExprList_item *pItem;\n  int i;\n  if( pList ){\n    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){\n      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);\n    }\n  }\n}\n\n/*\n** Allocate a single new register for use to hold some intermediate result.\n*/\nSQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){\n  if( pParse->nTempReg==0 ){\n    return ++pParse->nMem;\n  }\n  return pParse->aTempReg[--pParse->nTempReg];\n}\n\n/*\n** Deallocate a register, making available for reuse for some other\n** purpose.\n**\n** If a register is currently being used by the column cache, then\n** the dallocation is deferred until the column cache line that uses\n** the register becomes stale.\n*/\nSQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){\n  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){\n    int i;\n    struct yColCache *p;\n    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){\n      if( p->iReg==iReg ){\n        p->tempReg = 1;\n        return;\n      }\n    }\n    pParse->aTempReg[pParse->nTempReg++] = iReg;\n  }\n}\n\n/*\n** Allocate or deallocate a block of nReg consecutive registers\n*/\nSQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){\n  int i, n;\n  i = pParse->iRangeReg;\n  n = pParse->nRangeReg;\n  if( nReg<=n ){\n    assert( !usedAsColumnCache(pParse, i, i+n-1) );\n    pParse->iRangeReg += nReg;\n    pParse->nRangeReg -= nReg;\n  }else{\n    i = pParse->nMem+1;\n    pParse->nMem += nReg;\n  }\n  return i;\n}\nSQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){\n  sqlite3ExprCacheRemove(pParse, iReg, nReg);\n  if( nReg>pParse->nRangeReg ){\n    pParse->nRangeReg = nReg;\n    pParse->iRangeReg = iReg;\n  }\n}\n\n/*\n** Mark all temporary registers as being unavailable for reuse.\n*/\nSQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){\n  pParse->nTempReg = 0;\n  pParse->nRangeReg = 0;\n}\n\n/************** End of expr.c ************************************************/\n/************** Begin file alter.c *******************************************/\n/*\n** 2005 February 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that used to generate VDBE code\n** that implements the ALTER TABLE command.\n*/\n\n/*\n** The code in this file only exists if we are not omitting the\n** ALTER TABLE logic from the build.\n*/\n#ifndef SQLITE_OMIT_ALTERTABLE\n\n\n/*\n** This function is used by SQL generated to implement the \n** ALTER TABLE command. The first argument is the text of a CREATE TABLE or\n** CREATE INDEX command. The second is a table name. The table name in \n** the CREATE TABLE or CREATE INDEX statement is replaced with the third\n** argument and the result returned. Examples:\n**\n** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')\n**     -> 'CREATE TABLE def(a, b, c)'\n**\n** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')\n**     -> 'CREATE INDEX i ON def(a, b, c)'\n*/\nstatic void renameTableFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  unsigned char const *zSql = sqlite3_value_text(argv[0]);\n  unsigned char const *zTableName = sqlite3_value_text(argv[1]);\n\n  int token;\n  Token tname;\n  unsigned char const *zCsr = zSql;\n  int len = 0;\n  char *zRet;\n\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  UNUSED_PARAMETER(NotUsed);\n\n  /* The principle used to locate the table name in the CREATE TABLE \n  ** statement is that the table name is the first non-space token that\n  ** is immediately followed by a TK_LP or TK_USING token.\n  */\n  if( zSql ){\n    do {\n      if( !*zCsr ){\n        /* Ran out of input before finding an opening bracket. Return NULL. */\n        return;\n      }\n\n      /* Store the token that zCsr points to in tname. */\n      tname.z = (char*)zCsr;\n      tname.n = len;\n\n      /* Advance zCsr to the next token. Store that token type in 'token',\n      ** and its length in 'len' (to be used next iteration of this loop).\n      */\n      do {\n        zCsr += len;\n        len = sqlite3GetToken(zCsr, &token);\n      } while( token==TK_SPACE );\n      assert( len>0 );\n    } while( token!=TK_LP && token!=TK_USING );\n\n    zRet = sqlite3MPrintf(db, \"%.*s\\\"%w\\\"%s\", ((u8*)tname.z) - zSql, zSql, \n       zTableName, tname.z+tname.n);\n    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);\n  }\n}\n\n/*\n** This C function implements an SQL user function that is used by SQL code\n** generated by the ALTER TABLE ... RENAME command to modify the definition\n** of any foreign key constraints that use the table being renamed as the \n** parent table. It is passed three arguments:\n**\n**   1) The complete text of the CREATE TABLE statement being modified,\n**   2) The old name of the table being renamed, and\n**   3) The new name of the table being renamed.\n**\n** It returns the new CREATE TABLE statement. For example:\n**\n**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')\n**       -> 'CREATE TABLE t1(a REFERENCES t3)'\n*/\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nstatic void renameParentFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  char *zOutput = 0;\n  char *zResult;\n  unsigned char const *zInput = sqlite3_value_text(argv[0]);\n  unsigned char const *zOld = sqlite3_value_text(argv[1]);\n  unsigned char const *zNew = sqlite3_value_text(argv[2]);\n\n  unsigned const char *z;         /* Pointer to token */\n  int n;                          /* Length of token z */\n  int token;                      /* Type of token */\n\n  UNUSED_PARAMETER(NotUsed);\n  for(z=zInput; *z; z=z+n){\n    n = sqlite3GetToken(z, &token);\n    if( token==TK_REFERENCES ){\n      char *zParent;\n      do {\n        z += n;\n        n = sqlite3GetToken(z, &token);\n      }while( token==TK_SPACE );\n\n      zParent = sqlite3DbStrNDup(db, (const char *)z, n);\n      if( zParent==0 ) break;\n      sqlite3Dequote(zParent);\n      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){\n        char *zOut = sqlite3MPrintf(db, \"%s%.*s\\\"%w\\\"\", \n            (zOutput?zOutput:\"\"), z-zInput, zInput, (const char *)zNew\n        );\n        sqlite3DbFree(db, zOutput);\n        zOutput = zOut;\n        zInput = &z[n];\n      }\n      sqlite3DbFree(db, zParent);\n    }\n  }\n\n  zResult = sqlite3MPrintf(db, \"%s%s\", (zOutput?zOutput:\"\"), zInput), \n  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);\n  sqlite3DbFree(db, zOutput);\n}\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\n/* This function is used by SQL generated to implement the\n** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER \n** statement. The second is a table name. The table name in the CREATE \n** TRIGGER statement is replaced with the third argument and the result \n** returned. This is analagous to renameTableFunc() above, except for CREATE\n** TRIGGER, not CREATE INDEX and CREATE TABLE.\n*/\nstatic void renameTriggerFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  unsigned char const *zSql = sqlite3_value_text(argv[0]);\n  unsigned char const *zTableName = sqlite3_value_text(argv[1]);\n\n  int token;\n  Token tname;\n  int dist = 3;\n  unsigned char const *zCsr = zSql;\n  int len = 0;\n  char *zRet;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  UNUSED_PARAMETER(NotUsed);\n\n  /* The principle used to locate the table name in the CREATE TRIGGER \n  ** statement is that the table name is the first token that is immediatedly\n  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one\n  ** of TK_WHEN, TK_BEGIN or TK_FOR.\n  */\n  if( zSql ){\n    do {\n\n      if( !*zCsr ){\n        /* Ran out of input before finding the table name. Return NULL. */\n        return;\n      }\n\n      /* Store the token that zCsr points to in tname. */\n      tname.z = (char*)zCsr;\n      tname.n = len;\n\n      /* Advance zCsr to the next token. Store that token type in 'token',\n      ** and its length in 'len' (to be used next iteration of this loop).\n      */\n      do {\n        zCsr += len;\n        len = sqlite3GetToken(zCsr, &token);\n      }while( token==TK_SPACE );\n      assert( len>0 );\n\n      /* Variable 'dist' stores the number of tokens read since the most\n      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN \n      ** token is read and 'dist' equals 2, the condition stated above\n      ** to be met.\n      **\n      ** Note that ON cannot be a database, table or column name, so\n      ** there is no need to worry about syntax like \n      ** \"CREATE TRIGGER ... ON ON.ON BEGIN ...\" etc.\n      */\n      dist++;\n      if( token==TK_DOT || token==TK_ON ){\n        dist = 0;\n      }\n    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );\n\n    /* Variable tname now contains the token that is the old table-name\n    ** in the CREATE TRIGGER statement.\n    */\n    zRet = sqlite3MPrintf(db, \"%.*s\\\"%w\\\"%s\", ((u8*)tname.z) - zSql, zSql, \n       zTableName, tname.z+tname.n);\n    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);\n  }\n}\n#endif   /* !SQLITE_OMIT_TRIGGER */\n\n/*\n** Register built-in functions used to help implement ALTER TABLE\n*/\nSQLITE_PRIVATE void sqlite3AlterFunctions(void){\n  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {\n    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),\n#ifndef SQLITE_OMIT_TRIGGER\n    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),\n#endif\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),\n#endif\n  };\n  int i;\n  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);\n  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);\n\n  for(i=0; i<ArraySize(aAlterTableFuncs); i++){\n    sqlite3FuncDefInsert(pHash, &aFunc[i]);\n  }\n}\n\n/*\n** This function is used to create the text of expressions of the form:\n**\n**   name=<constant1> OR name=<constant2> OR ...\n**\n** If argument zWhere is NULL, then a pointer string containing the text \n** \"name=<constant>\" is returned, where <constant> is the quoted version\n** of the string passed as argument zConstant. The returned buffer is\n** allocated using sqlite3DbMalloc(). It is the responsibility of the\n** caller to ensure that it is eventually freed.\n**\n** If argument zWhere is not NULL, then the string returned is \n** \"<where> OR name=<constant>\", where <where> is the contents of zWhere.\n** In this case zWhere is passed to sqlite3DbFree() before returning.\n** \n*/\nstatic char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){\n  char *zNew;\n  if( !zWhere ){\n    zNew = sqlite3MPrintf(db, \"name=%Q\", zConstant);\n  }else{\n    zNew = sqlite3MPrintf(db, \"%s OR name=%Q\", zWhere, zConstant);\n    sqlite3DbFree(db, zWhere);\n  }\n  return zNew;\n}\n\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n/*\n** Generate the text of a WHERE expression which can be used to select all\n** tables that have foreign key constraints that refer to table pTab (i.e.\n** constraints for which pTab is the parent table) from the sqlite_master\n** table.\n*/\nstatic char *whereForeignKeys(Parse *pParse, Table *pTab){\n  FKey *p;\n  char *zWhere = 0;\n  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);\n  }\n  return zWhere;\n}\n#endif\n\n/*\n** Generate the text of a WHERE expression which can be used to select all\n** temporary triggers on table pTab from the sqlite_temp_master table. If\n** table pTab has no temporary triggers, or is itself stored in the \n** temporary database, NULL is returned.\n*/\nstatic char *whereTempTriggers(Parse *pParse, Table *pTab){\n  Trigger *pTrig;\n  char *zWhere = 0;\n  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */\n\n  /* If the table is not located in the temp-db (in which case NULL is \n  ** returned, loop through the tables list of triggers. For each trigger\n  ** that is not part of the temp-db schema, add a clause to the WHERE \n  ** expression being built up in zWhere.\n  */\n  if( pTab->pSchema!=pTempSchema ){\n    sqlite3 *db = pParse->db;\n    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){\n      if( pTrig->pSchema==pTempSchema ){\n        zWhere = whereOrName(db, zWhere, pTrig->zName);\n      }\n    }\n  }\n  if( zWhere ){\n    char *zNew = sqlite3MPrintf(pParse->db, \"type='trigger' AND (%s)\", zWhere);\n    sqlite3DbFree(pParse->db, zWhere);\n    zWhere = zNew;\n  }\n  return zWhere;\n}\n\n/*\n** Generate code to drop and reload the internal representation of table\n** pTab from the database, including triggers and temporary triggers.\n** Argument zName is the name of the table in the database schema at\n** the time the generated code is executed. This can be different from\n** pTab->zName if this function is being called to code part of an \n** \"ALTER TABLE RENAME TO\" statement.\n*/\nstatic void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){\n  Vdbe *v;\n  char *zWhere;\n  int iDb;                   /* Index of database containing pTab */\n#ifndef SQLITE_OMIT_TRIGGER\n  Trigger *pTrig;\n#endif\n\n  v = sqlite3GetVdbe(pParse);\n  if( NEVER(v==0) ) return;\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  assert( iDb>=0 );\n\n#ifndef SQLITE_OMIT_TRIGGER\n  /* Drop any table triggers from the internal schema. */\n  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){\n    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);\n    assert( iTrigDb==iDb || iTrigDb==1 );\n    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);\n  }\n#endif\n\n  /* Drop the table and index from the internal schema.  */\n  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);\n\n  /* Reload the table, index and permanent trigger schemas. */\n  zWhere = sqlite3MPrintf(pParse->db, \"tbl_name=%Q\", zName);\n  if( !zWhere ) return;\n  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);\n\n#ifndef SQLITE_OMIT_TRIGGER\n  /* Now, if the table is not stored in the temp database, reload any temp \n  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. \n  */\n  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){\n    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);\n  }\n#endif\n}\n\n/*\n** Parameter zName is the name of a table that is about to be altered\n** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).\n** If the table is a system table, this function leaves an error message\n** in pParse->zErr (system tables may not be altered) and returns non-zero.\n**\n** Or, if zName is not a system table, zero is returned.\n*/\nstatic int isSystemTable(Parse *pParse, const char *zName){\n  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, \"sqlite_\", 7) ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be altered\", zName);\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** Generate code to implement the \"ALTER TABLE xxx RENAME TO yyy\" \n** command. \n*/\nSQLITE_PRIVATE void sqlite3AlterRenameTable(\n  Parse *pParse,            /* Parser context. */\n  SrcList *pSrc,            /* The table to rename. */\n  Token *pName              /* The new table name. */\n){\n  int iDb;                  /* Database that contains the table */\n  char *zDb;                /* Name of database iDb */\n  Table *pTab;              /* Table being renamed */\n  char *zName = 0;          /* NULL-terminated version of pName */ \n  sqlite3 *db = pParse->db; /* Database connection */\n  int nTabName;             /* Number of UTF-8 characters in zTabName */\n  const char *zTabName;     /* Original name of the table */\n  Vdbe *v;\n#ifndef SQLITE_OMIT_TRIGGER\n  char *zWhere = 0;         /* Where clause to locate temp triggers */\n#endif\n  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */\n  int savedDbFlags;         /* Saved value of db->flags */\n\n  savedDbFlags = db->flags;  \n  if( NEVER(db->mallocFailed) ) goto exit_rename_table;\n  assert( pSrc->nSrc==1 );\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n\n  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);\n  if( !pTab ) goto exit_rename_table;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  zDb = db->aDb[iDb].zName;\n  db->flags |= SQLITE_PreferBuiltin;\n\n  /* Get a NULL terminated version of the new table name. */\n  zName = sqlite3NameFromToken(db, pName);\n  if( !zName ) goto exit_rename_table;\n\n  /* Check that a table or index named 'zName' does not already exist\n  ** in database iDb. If so, this is an error.\n  */\n  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){\n    sqlite3ErrorMsg(pParse, \n        \"there is already another table or index with this name: %s\", zName);\n    goto exit_rename_table;\n  }\n\n  /* Make sure it is not a system table being altered, or a reserved name\n  ** that the table is being renamed to.\n  */\n  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){\n    goto exit_rename_table;\n  }\n  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto\n    exit_rename_table;\n  }\n\n#ifndef SQLITE_OMIT_VIEW\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"view %s may not be altered\", pTab->zName);\n    goto exit_rename_table;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Invoke the authorization callback. */\n  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){\n    goto exit_rename_table;\n  }\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto exit_rename_table;\n  }\n  if( IsVirtual(pTab) ){\n    pVTab = sqlite3GetVTable(db, pTab);\n    if( pVTab->pVtab->pModule->xRename==0 ){\n      pVTab = 0;\n    }\n  }\n#endif\n\n  /* Begin a transaction and code the VerifyCookie for database iDb. \n  ** Then modify the schema cookie (since the ALTER TABLE modifies the\n  ** schema). Open a statement transaction if the table is a virtual\n  ** table.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ){\n    goto exit_rename_table;\n  }\n  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);\n  sqlite3ChangeCookie(pParse, iDb);\n\n  /* If this is a virtual table, invoke the xRename() function if\n  ** one is defined. The xRename() callback will modify the names\n  ** of any resources used by the v-table implementation (including other\n  ** SQLite tables) that are identified by the name of the virtual table.\n  */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pVTab ){\n    int i = ++pParse->nMem;\n    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);\n    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);\n    sqlite3MayAbort(pParse);\n  }\n#endif\n\n  /* figure out how many UTF-8 characters are in zName */\n  zTabName = pTab->zName;\n  nTabName = sqlite3Utf8CharLen(zTabName, -1);\n\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n  if( db->flags&SQLITE_ForeignKeys ){\n    /* If foreign-key support is enabled, rewrite the CREATE TABLE \n    ** statements corresponding to all child tables of foreign key constraints\n    ** for which the renamed table is the parent table.  */\n    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){\n      sqlite3NestedParse(pParse, \n          \"UPDATE \\\"%w\\\".%s SET \"\n              \"sql = sqlite_rename_parent(sql, %Q, %Q) \"\n              \"WHERE %s;\", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);\n      sqlite3DbFree(db, zWhere);\n    }\n  }\n#endif\n\n  /* Modify the sqlite_master table to use the new table name. */\n  sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s SET \"\n#ifdef SQLITE_OMIT_TRIGGER\n          \"sql = sqlite_rename_table(sql, %Q), \"\n#else\n          \"sql = CASE \"\n            \"WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)\"\n            \"ELSE sqlite_rename_table(sql, %Q) END, \"\n#endif\n          \"tbl_name = %Q, \"\n          \"name = CASE \"\n            \"WHEN type='table' THEN %Q \"\n            \"WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN \"\n             \"'sqlite_autoindex_' || %Q || substr(name,%d+18) \"\n            \"ELSE name END \"\n      \"WHERE tbl_name=%Q COLLATE nocase AND \"\n          \"(type='table' OR type='index' OR type='trigger');\", \n      zDb, SCHEMA_TABLE(iDb), zName, zName, zName, \n#ifndef SQLITE_OMIT_TRIGGER\n      zName,\n#endif\n      zName, nTabName, zTabName\n  );\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  /* If the sqlite_sequence table exists in this database, then update \n  ** it with the new table name.\n  */\n  if( sqlite3FindTable(db, \"sqlite_sequence\", zDb) ){\n    sqlite3NestedParse(pParse,\n        \"UPDATE \\\"%w\\\".sqlite_sequence set name = %Q WHERE name = %Q\",\n        zDb, zName, pTab->zName);\n  }\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\n  /* If there are TEMP triggers on this table, modify the sqlite_temp_master\n  ** table. Don't do this if the table being ALTERed is itself located in\n  ** the temp database.\n  */\n  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){\n    sqlite3NestedParse(pParse, \n        \"UPDATE sqlite_temp_master SET \"\n            \"sql = sqlite_rename_trigger(sql, %Q), \"\n            \"tbl_name = %Q \"\n            \"WHERE %s;\", zName, zName, zWhere);\n    sqlite3DbFree(db, zWhere);\n  }\n#endif\n\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n  if( db->flags&SQLITE_ForeignKeys ){\n    FKey *p;\n    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n      Table *pFrom = p->pFrom;\n      if( pFrom!=pTab ){\n        reloadTableSchema(pParse, p->pFrom, pFrom->zName);\n      }\n    }\n  }\n#endif\n\n  /* Drop and reload the internal table schema. */\n  reloadTableSchema(pParse, pTab, zName);\n\nexit_rename_table:\n  sqlite3SrcListDelete(db, pSrc);\n  sqlite3DbFree(db, zName);\n  db->flags = savedDbFlags;\n}\n\n\n/*\n** Generate code to make sure the file format number is at least minFormat.\n** The generated code will increase the file format number if necessary.\n*/\nSQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){\n  Vdbe *v;\n  v = sqlite3GetVdbe(pParse);\n  /* The VDBE should have been allocated before this routine is called.\n  ** If that allocation failed, we would have quit before reaching this\n  ** point */\n  if( ALWAYS(v) ){\n    int r1 = sqlite3GetTempReg(pParse);\n    int r2 = sqlite3GetTempReg(pParse);\n    int j1;\n    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);\n    sqlite3VdbeUsesBtree(v, iDb);\n    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);\n    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);\n    sqlite3VdbeJumpHere(v, j1);\n    sqlite3ReleaseTempReg(pParse, r1);\n    sqlite3ReleaseTempReg(pParse, r2);\n  }\n}\n\n/*\n** This function is called after an \"ALTER TABLE ... ADD\" statement\n** has been parsed. Argument pColDef contains the text of the new\n** column definition.\n**\n** The Table structure pParse->pNewTable was extended to include\n** the new column during parsing.\n*/\nSQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){\n  Table *pNew;              /* Copy of pParse->pNewTable */\n  Table *pTab;              /* Table being altered */\n  int iDb;                  /* Database number */\n  const char *zDb;          /* Database name */\n  const char *zTab;         /* Table name */\n  char *zCol;               /* Null-terminated column definition */\n  Column *pCol;             /* The new column */\n  Expr *pDflt;              /* Default value for the new column */\n  sqlite3 *db;              /* The database connection; */\n\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ) return;\n  pNew = pParse->pNewTable;\n  assert( pNew );\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);\n  zDb = db->aDb[iDb].zName;\n  zTab = &pNew->zName[16];  /* Skip the \"sqlite_altertab_\" prefix on the name */\n  pCol = &pNew->aCol[pNew->nCol-1];\n  pDflt = pCol->pDflt;\n  pTab = sqlite3FindTable(db, zTab, zDb);\n  assert( pTab );\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Invoke the authorization callback. */\n  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){\n    return;\n  }\n#endif\n\n  /* If the default value for the new column was specified with a \n  ** literal NULL, then set pDflt to 0. This simplifies checking\n  ** for an SQL NULL default below.\n  */\n  if( pDflt && pDflt->op==TK_NULL ){\n    pDflt = 0;\n  }\n\n  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.\n  ** If there is a NOT NULL constraint, then the default value for the\n  ** column must not be NULL.\n  */\n  if( pCol->isPrimKey ){\n    sqlite3ErrorMsg(pParse, \"Cannot add a PRIMARY KEY column\");\n    return;\n  }\n  if( pNew->pIndex ){\n    sqlite3ErrorMsg(pParse, \"Cannot add a UNIQUE column\");\n    return;\n  }\n  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){\n    sqlite3ErrorMsg(pParse, \n        \"Cannot add a REFERENCES column with non-NULL default value\");\n    return;\n  }\n  if( pCol->notNull && !pDflt ){\n    sqlite3ErrorMsg(pParse, \n        \"Cannot add a NOT NULL column with default value NULL\");\n    return;\n  }\n\n  /* Ensure the default expression is something that sqlite3ValueFromExpr()\n  ** can handle (i.e. not CURRENT_TIME etc.)\n  */\n  if( pDflt ){\n    sqlite3_value *pVal;\n    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){\n      db->mallocFailed = 1;\n      return;\n    }\n    if( !pVal ){\n      sqlite3ErrorMsg(pParse, \"Cannot add a column with non-constant default\");\n      return;\n    }\n    sqlite3ValueFree(pVal);\n  }\n\n  /* Modify the CREATE TABLE statement. */\n  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);\n  if( zCol ){\n    char *zEnd = &zCol[pColDef->n-1];\n    int savedDbFlags = db->flags;\n    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){\n      *zEnd-- = '\\0';\n    }\n    db->flags |= SQLITE_PreferBuiltin;\n    sqlite3NestedParse(pParse, \n        \"UPDATE \\\"%w\\\".%s SET \"\n          \"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) \"\n        \"WHERE type = 'table' AND name = %Q\", \n      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,\n      zTab\n    );\n    sqlite3DbFree(db, zCol);\n    db->flags = savedDbFlags;\n  }\n\n  /* If the default value of the new column is NULL, then set the file\n  ** format to 2. If the default value of the new column is not NULL,\n  ** the file format becomes 3.\n  */\n  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);\n\n  /* Reload the schema of the modified table. */\n  reloadTableSchema(pParse, pTab, pTab->zName);\n}\n\n/*\n** This function is called by the parser after the table-name in\n** an \"ALTER TABLE <table-name> ADD\" statement is parsed. Argument \n** pSrc is the full-name of the table being altered.\n**\n** This routine makes a (partial) copy of the Table structure\n** for the table being altered and sets Parse.pNewTable to point\n** to it. Routines called by the parser as the column definition\n** is parsed (i.e. sqlite3AddColumn()) add the new Column data to \n** the copy. The copy of the Table structure is deleted by tokenize.c \n** after parsing is finished.\n**\n** Routine sqlite3AlterFinishAddColumn() will be called to complete\n** coding the \"ALTER TABLE ... ADD\" statement.\n*/\nSQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){\n  Table *pNew;\n  Table *pTab;\n  Vdbe *v;\n  int iDb;\n  int i;\n  int nAlloc;\n  sqlite3 *db = pParse->db;\n\n  /* Look up the table being altered. */\n  assert( pParse->pNewTable==0 );\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  if( db->mallocFailed ) goto exit_begin_add_column;\n  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);\n  if( !pTab ) goto exit_begin_add_column;\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"virtual tables may not be altered\");\n    goto exit_begin_add_column;\n  }\n#endif\n\n  /* Make sure this is not an attempt to ALTER a view. */\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"Cannot add a column to a view\");\n    goto exit_begin_add_column;\n  }\n  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){\n    goto exit_begin_add_column;\n  }\n\n  assert( pTab->addColOffset>0 );\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n\n  /* Put a copy of the Table struct in Parse.pNewTable for the\n  ** sqlite3AddColumn() function and friends to modify.  But modify\n  ** the name by adding an \"sqlite_altertab_\" prefix.  By adding this\n  ** prefix, we insure that the name will not collide with an existing\n  ** table because user table are not allowed to have the \"sqlite_\"\n  ** prefix on their name.\n  */\n  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));\n  if( !pNew ) goto exit_begin_add_column;\n  pParse->pNewTable = pNew;\n  pNew->nRef = 1;\n  pNew->nCol = pTab->nCol;\n  assert( pNew->nCol>0 );\n  nAlloc = (((pNew->nCol-1)/8)*8)+8;\n  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );\n  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);\n  pNew->zName = sqlite3MPrintf(db, \"sqlite_altertab_%s\", pTab->zName);\n  if( !pNew->aCol || !pNew->zName ){\n    db->mallocFailed = 1;\n    goto exit_begin_add_column;\n  }\n  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);\n  for(i=0; i<pNew->nCol; i++){\n    Column *pCol = &pNew->aCol[i];\n    pCol->zName = sqlite3DbStrDup(db, pCol->zName);\n    pCol->zColl = 0;\n    pCol->zType = 0;\n    pCol->pDflt = 0;\n    pCol->zDflt = 0;\n  }\n  pNew->pSchema = db->aDb[iDb].pSchema;\n  pNew->addColOffset = pTab->addColOffset;\n  pNew->nRef = 1;\n\n  /* Begin a transaction and increment the schema cookie.  */\n  sqlite3BeginWriteOperation(pParse, 0, iDb);\n  v = sqlite3GetVdbe(pParse);\n  if( !v ) goto exit_begin_add_column;\n  sqlite3ChangeCookie(pParse, iDb);\n\nexit_begin_add_column:\n  sqlite3SrcListDelete(db, pSrc);\n  return;\n}\n#endif  /* SQLITE_ALTER_TABLE */\n\n/************** End of alter.c ***********************************************/\n/************** Begin file analyze.c *****************************************/\n/*\n** 2005 July 8\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code associated with the ANALYZE command.\n**\n** The ANALYZE command gather statistics about the content of tables\n** and indices.  These statistics are made available to the query planner\n** to help it make better decisions about how to perform queries.\n**\n** The following system tables are or have been supported:\n**\n**    CREATE TABLE sqlite_stat1(tbl, idx, stat);\n**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);\n**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);\n**\n** Additional tables might be added in future releases of SQLite.\n** The sqlite_stat2 table is not created or used unless the SQLite version\n** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled\n** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.\n** The sqlite_stat2 table is superceded by sqlite_stat3, which is only\n** created and used by SQLite versions 3.7.9 and later and with\n** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3\n** is a superset of sqlite_stat2.  \n**\n** Format of sqlite_stat1:\n**\n** There is normally one row per index, with the index identified by the\n** name in the idx column.  The tbl column is the name of the table to\n** which the index belongs.  In each such row, the stat column will be\n** a string consisting of a list of integers.  The first integer in this\n** list is the number of rows in the index and in the table.  The second\n** integer is the average number of rows in the index that have the same\n** value in the first column of the index.  The third integer is the average\n** number of rows in the index that have the same value for the first two\n** columns.  The N-th integer (for N>1) is the average number of rows in \n** the index which have the same value for the first N-1 columns.  For\n** a K-column index, there will be K+1 integers in the stat column.  If\n** the index is unique, then the last integer will be 1.\n**\n** The list of integers in the stat column can optionally be followed\n** by the keyword \"unordered\".  The \"unordered\" keyword, if it is present,\n** must be separated from the last integer by a single space.  If the\n** \"unordered\" keyword is present, then the query planner assumes that\n** the index is unordered and will not use the index for a range query.\n** \n** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat\n** column contains a single integer which is the (estimated) number of\n** rows in the table identified by sqlite_stat1.tbl.\n**\n** Format of sqlite_stat2:\n**\n** The sqlite_stat2 is only created and is only used if SQLite is compiled\n** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between\n** 3.6.18 and 3.7.8.  The \"stat2\" table contains additional information\n** about the distribution of keys within an index.  The index is identified by\n** the \"idx\" column and the \"tbl\" column is the name of the table to which\n** the index belongs.  There are usually 10 rows in the sqlite_stat2\n** table for each index.\n**\n** The sqlite_stat2 entries for an index that have sampleno between 0 and 9\n** inclusive are samples of the left-most key value in the index taken at\n** evenly spaced points along the index.  Let the number of samples be S\n** (10 in the standard build) and let C be the number of rows in the index.\n** Then the sampled rows are given by:\n**\n**     rownumber = (i*C*2 + C)/(S*2)\n**\n** For i between 0 and S-1.  Conceptually, the index space is divided into\n** S uniform buckets and the samples are the middle row from each bucket.\n**\n** The format for sqlite_stat2 is recorded here for legacy reference.  This\n** version of SQLite does not support sqlite_stat2.  It neither reads nor\n** writes the sqlite_stat2 table.  This version of SQLite only supports\n** sqlite_stat3.\n**\n** Format for sqlite_stat3:\n**\n** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is\n** used to avoid compatibility problems.  \n**\n** The format of the sqlite_stat3 table is similar to the format of\n** the sqlite_stat2 table.  There are multiple entries for each index.\n** The idx column names the index and the tbl column is the table of the\n** index.  If the idx and tbl columns are the same, then the sample is\n** of the INTEGER PRIMARY KEY.  The sample column is a value taken from\n** the left-most column of the index.  The nEq column is the approximate\n** number of entires in the index whose left-most column exactly matches\n** the sample.  nLt is the approximate number of entires whose left-most\n** column is less than the sample.  The nDLt column is the approximate\n** number of distinct left-most entries in the index that are less than\n** the sample.\n**\n** Future versions of SQLite might change to store a string containing\n** multiple integers values in the nDLt column of sqlite_stat3.  The first\n** integer will be the number of prior index entires that are distinct in\n** the left-most column.  The second integer will be the number of prior index\n** entries that are distinct in the first two columns.  The third integer\n** will be the number of prior index entries that are distinct in the first\n** three columns.  And so forth.  With that extension, the nDLt field is\n** similar in function to the sqlite_stat1.stat field.\n**\n** There can be an arbitrary number of sqlite_stat3 entries per index.\n** The ANALYZE command will typically generate sqlite_stat3 tables\n** that contain between 10 and 40 samples which are distributed across\n** the key space, though not uniformly, and which include samples with\n** largest possible nEq values.\n*/\n#ifndef SQLITE_OMIT_ANALYZE\n\n/*\n** This routine generates code that opens the sqlite_stat1 table for\n** writing with cursor iStatCur. If the library was built with the\n** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is\n** opened for writing using cursor (iStatCur+1)\n**\n** If the sqlite_stat1 tables does not previously exist, it is created.\n** Similarly, if the sqlite_stat3 table does not exist and the library\n** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. \n**\n** Argument zWhere may be a pointer to a buffer containing a table name,\n** or it may be a NULL pointer. If it is not NULL, then all entries in\n** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated\n** with the named table are deleted. If zWhere==0, then code is generated\n** to delete all stat table entries.\n*/\nstatic void openStatTable(\n  Parse *pParse,          /* Parsing context */\n  int iDb,                /* The database we are looking in */\n  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */\n  const char *zWhere,     /* Delete entries for this table or index */\n  const char *zWhereType  /* Either \"tbl\" or \"idx\" */\n){\n  static const struct {\n    const char *zName;\n    const char *zCols;\n  } aTable[] = {\n    { \"sqlite_stat1\", \"tbl,idx,stat\" },\n#ifdef SQLITE_ENABLE_STAT3\n    { \"sqlite_stat3\", \"tbl,idx,neq,nlt,ndlt,sample\" },\n#endif\n  };\n\n  int aRoot[] = {0, 0};\n  u8 aCreateTbl[] = {0, 0};\n\n  int i;\n  sqlite3 *db = pParse->db;\n  Db *pDb;\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( v==0 ) return;\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3VdbeDb(v)==db );\n  pDb = &db->aDb[iDb];\n\n  /* Create new statistic tables if they do not exist, or clear them\n  ** if they do already exist.\n  */\n  for(i=0; i<ArraySize(aTable); i++){\n    const char *zTab = aTable[i].zName;\n    Table *pStat;\n    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){\n      /* The sqlite_stat[12] table does not exist. Create it. Note that a \n      ** side-effect of the CREATE TABLE statement is to leave the rootpage \n      ** of the new table in register pParse->regRoot. This is important \n      ** because the OpenWrite opcode below will be needing it. */\n      sqlite3NestedParse(pParse,\n          \"CREATE TABLE %Q.%s(%s)\", pDb->zName, zTab, aTable[i].zCols\n      );\n      aRoot[i] = pParse->regRoot;\n      aCreateTbl[i] = OPFLAG_P2ISREG;\n    }else{\n      /* The table already exists. If zWhere is not NULL, delete all entries \n      ** associated with the table zWhere. If zWhere is NULL, delete the\n      ** entire contents of the table. */\n      aRoot[i] = pStat->tnum;\n      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);\n      if( zWhere ){\n        sqlite3NestedParse(pParse,\n           \"DELETE FROM %Q.%s WHERE %s=%Q\", pDb->zName, zTab, zWhereType, zWhere\n        );\n      }else{\n        /* The sqlite_stat[12] table already exists.  Delete all rows. */\n        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);\n      }\n    }\n  }\n\n  /* Open the sqlite_stat[13] tables for writing. */\n  for(i=0; i<ArraySize(aTable); i++){\n    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);\n    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);\n    sqlite3VdbeChangeP5(v, aCreateTbl[i]);\n  }\n}\n\n/*\n** Recommended number of samples for sqlite_stat3\n*/\n#ifndef SQLITE_STAT3_SAMPLES\n# define SQLITE_STAT3_SAMPLES 24\n#endif\n\n/*\n** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -\n** share an instance of the following structure to hold their state\n** information.\n*/\ntypedef struct Stat3Accum Stat3Accum;\nstruct Stat3Accum {\n  tRowcnt nRow;             /* Number of rows in the entire table */\n  tRowcnt nPSample;         /* How often to do a periodic sample */\n  int iMin;                 /* Index of entry with minimum nEq and hash */\n  int mxSample;             /* Maximum number of samples to accumulate */\n  int nSample;              /* Current number of samples */\n  u32 iPrn;                 /* Pseudo-random number used for sampling */\n  struct Stat3Sample {\n    i64 iRowid;                /* Rowid in main table of the key */\n    tRowcnt nEq;               /* sqlite_stat3.nEq */\n    tRowcnt nLt;               /* sqlite_stat3.nLt */\n    tRowcnt nDLt;              /* sqlite_stat3.nDLt */\n    u8 isPSample;              /* True if a periodic sample */\n    u32 iHash;                 /* Tiebreaker hash */\n  } *a;                     /* An array of samples */\n};\n\n#ifdef SQLITE_ENABLE_STAT3\n/*\n** Implementation of the stat3_init(C,S) SQL function.  The two parameters\n** are the number of rows in the table or index (C) and the number of samples\n** to accumulate (S).\n**\n** This routine allocates the Stat3Accum object.\n**\n** The return value is the Stat3Accum object (P).\n*/\nstatic void stat3Init(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Stat3Accum *p;\n  tRowcnt nRow;\n  int mxSample;\n  int n;\n\n  UNUSED_PARAMETER(argc);\n  nRow = (tRowcnt)sqlite3_value_int64(argv[0]);\n  mxSample = sqlite3_value_int(argv[1]);\n  n = sizeof(*p) + sizeof(p->a[0])*mxSample;\n  p = sqlite3MallocZero( n );\n  if( p==0 ){\n    sqlite3_result_error_nomem(context);\n    return;\n  }\n  p->a = (struct Stat3Sample*)&p[1];\n  p->nRow = nRow;\n  p->mxSample = mxSample;\n  p->nPSample = p->nRow/(mxSample/3+1) + 1;\n  sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);\n  sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);\n}\nstatic const FuncDef stat3InitFuncdef = {\n  2,                /* nArg */\n  SQLITE_UTF8,      /* iPrefEnc */\n  0,                /* flags */\n  0,                /* pUserData */\n  0,                /* pNext */\n  stat3Init,        /* xFunc */\n  0,                /* xStep */\n  0,                /* xFinalize */\n  \"stat3_init\",     /* zName */\n  0,                /* pHash */\n  0                 /* pDestructor */\n};\n\n\n/*\n** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The\n** arguments describe a single key instance.  This routine makes the \n** decision about whether or not to retain this key for the sqlite_stat3\n** table.\n**\n** The return value is NULL.\n*/\nstatic void stat3Push(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);\n  tRowcnt nEq = sqlite3_value_int64(argv[0]);\n  tRowcnt nLt = sqlite3_value_int64(argv[1]);\n  tRowcnt nDLt = sqlite3_value_int64(argv[2]);\n  i64 rowid = sqlite3_value_int64(argv[3]);\n  u8 isPSample = 0;\n  u8 doInsert = 0;\n  int iMin = p->iMin;\n  struct Stat3Sample *pSample;\n  int i;\n  u32 h;\n\n  UNUSED_PARAMETER(context);\n  UNUSED_PARAMETER(argc);\n  if( nEq==0 ) return;\n  h = p->iPrn = p->iPrn*1103515245 + 12345;\n  if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){\n    doInsert = isPSample = 1;\n  }else if( p->nSample<p->mxSample ){\n    doInsert = 1;\n  }else{\n    if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){\n      doInsert = 1;\n    }\n  }\n  if( !doInsert ) return;\n  if( p->nSample==p->mxSample ){\n    assert( p->nSample - iMin - 1 >= 0 );\n    memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));\n    pSample = &p->a[p->nSample-1];\n  }else{\n    pSample = &p->a[p->nSample++];\n  }\n  pSample->iRowid = rowid;\n  pSample->nEq = nEq;\n  pSample->nLt = nLt;\n  pSample->nDLt = nDLt;\n  pSample->iHash = h;\n  pSample->isPSample = isPSample;\n\n  /* Find the new minimum */\n  if( p->nSample==p->mxSample ){\n    pSample = p->a;\n    i = 0;\n    while( pSample->isPSample ){\n      i++;\n      pSample++;\n      assert( i<p->nSample );\n    }\n    nEq = pSample->nEq;\n    h = pSample->iHash;\n    iMin = i;\n    for(i++, pSample++; i<p->nSample; i++, pSample++){\n      if( pSample->isPSample ) continue;\n      if( pSample->nEq<nEq\n       || (pSample->nEq==nEq && pSample->iHash<h)\n      ){\n        iMin = i;\n        nEq = pSample->nEq;\n        h = pSample->iHash;\n      }\n    }\n    p->iMin = iMin;\n  }\n}\nstatic const FuncDef stat3PushFuncdef = {\n  5,                /* nArg */\n  SQLITE_UTF8,      /* iPrefEnc */\n  0,                /* flags */\n  0,                /* pUserData */\n  0,                /* pNext */\n  stat3Push,        /* xFunc */\n  0,                /* xStep */\n  0,                /* xFinalize */\n  \"stat3_push\",     /* zName */\n  0,                /* pHash */\n  0                 /* pDestructor */\n};\n\n/*\n** Implementation of the stat3_get(P,N,...) SQL function.  This routine is\n** used to query the results.  Content is returned for the Nth sqlite_stat3\n** row where N is between 0 and S-1 and S is the number of samples.  The\n** value returned depends on the number of arguments.\n**\n**   argc==2    result:  rowid\n**   argc==3    result:  nEq\n**   argc==4    result:  nLt\n**   argc==5    result:  nDLt\n*/\nstatic void stat3Get(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int n = sqlite3_value_int(argv[1]);\n  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);\n\n  assert( p!=0 );\n  if( p->nSample<=n ) return;\n  switch( argc ){\n    case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;\n    case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;\n    case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;\n    default: sqlite3_result_int64(context, p->a[n].nDLt);   break;\n  }\n}\nstatic const FuncDef stat3GetFuncdef = {\n  -1,               /* nArg */\n  SQLITE_UTF8,      /* iPrefEnc */\n  0,                /* flags */\n  0,                /* pUserData */\n  0,                /* pNext */\n  stat3Get,         /* xFunc */\n  0,                /* xStep */\n  0,                /* xFinalize */\n  \"stat3_get\",     /* zName */\n  0,                /* pHash */\n  0                 /* pDestructor */\n};\n#endif /* SQLITE_ENABLE_STAT3 */\n\n\n\n\n/*\n** Generate code to do an analysis of all indices associated with\n** a single table.\n*/\nstatic void analyzeOneTable(\n  Parse *pParse,   /* Parser context */\n  Table *pTab,     /* Table whose indices are to be analyzed */\n  Index *pOnlyIdx, /* If not NULL, only analyze this one index */\n  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */\n  int iMem         /* Available memory locations begin here */\n){\n  sqlite3 *db = pParse->db;    /* Database handle */\n  Index *pIdx;                 /* An index to being analyzed */\n  int iIdxCur;                 /* Cursor open on index being analyzed */\n  Vdbe *v;                     /* The virtual machine being built up */\n  int i;                       /* Loop counter */\n  int topOfLoop;               /* The top of the loop */\n  int endOfLoop;               /* The end of the loop */\n  int jZeroRows = -1;          /* Jump from here if number of rows is zero */\n  int iDb;                     /* Index of database containing pTab */\n  int regTabname = iMem++;     /* Register containing table name */\n  int regIdxname = iMem++;     /* Register containing index name */\n  int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */\n#ifdef SQLITE_ENABLE_STAT3\n  int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */\n  int regNumLt = iMem++;       /* Number of keys less than regSample */\n  int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */\n  int regSample = iMem++;      /* The next sample value */\n  int regRowid = regSample;    /* Rowid of a sample */\n  int regAccum = iMem++;       /* Register to hold Stat3Accum object */\n  int regLoop = iMem++;        /* Loop counter */\n  int regCount = iMem++;       /* Number of rows in the table or index */\n  int regTemp1 = iMem++;       /* Intermediate register */\n  int regTemp2 = iMem++;       /* Intermediate register */\n  int once = 1;                /* One-time initialization */\n  int shortJump = 0;           /* Instruction address */\n  int iTabCur = pParse->nTab++; /* Table cursor */\n#endif\n  int regCol = iMem++;         /* Content of a column in analyzed table */\n  int regRec = iMem++;         /* Register holding completed record */\n  int regTemp = iMem++;        /* Temporary use register */\n  int regNewRowid = iMem++;    /* Rowid for the inserted record */\n\n\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 || NEVER(pTab==0) ){\n    return;\n  }\n  if( pTab->tnum==0 ){\n    /* Do not gather statistics on views or virtual tables */\n    return;\n  }\n  if( memcmp(pTab->zName, \"sqlite_\", 7)==0 ){\n    /* Do not gather statistics on system tables */\n    return;\n  }\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb>=0 );\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,\n      db->aDb[iDb].zName ) ){\n    return;\n  }\n#endif\n\n  /* Establish a read-lock on the table at the shared-cache level. */\n  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n  iIdxCur = pParse->nTab++;\n  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    int nCol;\n    KeyInfo *pKey;\n    int addrIfNot = 0;           /* address of OP_IfNot */\n    int *aChngAddr;              /* Array of jump instruction addresses */\n\n    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;\n    VdbeNoopComment((v, \"Begin analysis of %s\", pIdx->zName));\n    nCol = pIdx->nColumn;\n    aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);\n    if( aChngAddr==0 ) continue;\n    pKey = sqlite3IndexKeyinfo(pParse, pIdx);\n    if( iMem+1+(nCol*2)>pParse->nMem ){\n      pParse->nMem = iMem+1+(nCol*2);\n    }\n\n    /* Open a cursor to the index to be analyzed. */\n    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );\n    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,\n        (char *)pKey, P4_KEYINFO_HANDOFF);\n    VdbeComment((v, \"%s\", pIdx->zName));\n\n    /* Populate the register containing the index name. */\n    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);\n\n#ifdef SQLITE_ENABLE_STAT3\n    if( once ){\n      once = 0;\n      sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);\n    }\n    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);\n    sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);\n    sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);\n    sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,\n                      (char*)&stat3InitFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 2);\n#endif /* SQLITE_ENABLE_STAT3 */\n\n    /* The block of memory cells initialized here is used as follows.\n    **\n    **    iMem:                \n    **        The total number of rows in the table.\n    **\n    **    iMem+1 .. iMem+nCol: \n    **        Number of distinct entries in index considering the \n    **        left-most N columns only, where N is between 1 and nCol, \n    **        inclusive.\n    **\n    **    iMem+nCol+1 .. Mem+2*nCol:  \n    **        Previous value of indexed columns, from left to right.\n    **\n    ** Cells iMem through iMem+nCol are initialized to 0. The others are \n    ** initialized to contain an SQL NULL.\n    */\n    for(i=0; i<=nCol; i++){\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);\n    }\n    for(i=0; i<nCol; i++){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);\n    }\n\n    /* Start the analysis loop. This loop runs through all the entries in\n    ** the index b-tree.  */\n    endOfLoop = sqlite3VdbeMakeLabel(v);\n    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);\n    topOfLoop = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */\n\n    for(i=0; i<nCol; i++){\n      CollSeq *pColl;\n      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);\n      if( i==0 ){\n        /* Always record the very first row */\n        addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);\n      }\n      assert( pIdx->azColl!=0 );\n      assert( pIdx->azColl[i]!=0 );\n      pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);\n      aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,\n                                      (char*)pColl, P4_COLLSEQ);\n      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);\n      VdbeComment((v, \"jump if column %d changed\", i));\n#ifdef SQLITE_ENABLE_STAT3\n      if( i==0 ){\n        sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);\n        VdbeComment((v, \"incr repeat count\"));\n      }\n#endif\n    }\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);\n    for(i=0; i<nCol; i++){\n      sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */\n      if( i==0 ){\n        sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */\n#ifdef SQLITE_ENABLE_STAT3\n        sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,\n                          (char*)&stat3PushFuncdef, P4_FUNCDEF);\n        sqlite3VdbeChangeP5(v, 5);\n        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);\n        sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);\n        sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);\n        sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);\n#endif        \n      }\n      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);\n      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);\n    }\n    sqlite3DbFree(db, aChngAddr);\n\n    /* Always jump here after updating the iMem+1...iMem+1+nCol counters */\n    sqlite3VdbeResolveLabel(v, endOfLoop);\n\n    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);\n    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);\n#ifdef SQLITE_ENABLE_STAT3\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,\n                      (char*)&stat3PushFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 5);\n    sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);\n    shortJump = \n    sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,\n                      (char*)&stat3GetFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 2);\n    sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);\n    sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);\n    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);\n    sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,\n                      (char*)&stat3GetFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 3);\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,\n                      (char*)&stat3GetFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 4);\n    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,\n                      (char*)&stat3GetFuncdef, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, 5);\n    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, \"bbbbbb\", 0);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);\n    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);\n    sqlite3VdbeJumpHere(v, shortJump+2);\n#endif        \n\n    /* Store the results in sqlite_stat1.\n    **\n    ** The result is a single row of the sqlite_stat1 table.  The first\n    ** two columns are the names of the table and index.  The third column\n    ** is a string composed of a list of integer statistics about the\n    ** index.  The first integer in the list is the total number of entries\n    ** in the index.  There is one additional integer in the list for each\n    ** column of the table.  This additional integer is a guess of how many\n    ** rows of the table the index will select.  If D is the count of distinct\n    ** values and K is the total number of rows, then the integer is computed\n    ** as:\n    **\n    **        I = (K+D-1)/D\n    **\n    ** If K==0 then no entry is made into the sqlite_stat1 table.  \n    ** If K>0 then it is always the case the D>0 so division by zero\n    ** is never possible.\n    */\n    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);\n    if( jZeroRows<0 ){\n      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);\n    }\n    for(i=0; i<nCol; i++){\n      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, \" \", 0);\n      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);\n      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);\n      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);\n      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);\n      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);\n      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);\n    }\n    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, \"aaa\", 0);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);\n    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n  }\n\n  /* If the table has no indices, create a single sqlite_stat1 entry\n  ** containing NULL as the index name and the row count as the content.\n  */\n  if( pTab->pIndex==0 ){\n    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);\n    VdbeComment((v, \"%s\", pTab->zName));\n    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);\n    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);\n    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);\n  }else{\n    sqlite3VdbeJumpHere(v, jZeroRows);\n    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);\n  }\n  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);\n  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, \"aaa\", 0);\n  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);\n  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);\n  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n  if( pParse->nMem<regRec ) pParse->nMem = regRec;\n  sqlite3VdbeJumpHere(v, jZeroRows);\n}\n\n\n/*\n** Generate code that will cause the most recent index analysis to\n** be loaded into internal hash tables where is can be used.\n*/\nstatic void loadAnalysis(Parse *pParse, int iDb){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);\n  }\n}\n\n/*\n** Generate code that will do an analysis of an entire database\n*/\nstatic void analyzeDatabase(Parse *pParse, int iDb){\n  sqlite3 *db = pParse->db;\n  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */\n  HashElem *k;\n  int iStatCur;\n  int iMem;\n\n  sqlite3BeginWriteOperation(pParse, 0, iDb);\n  iStatCur = pParse->nTab;\n  pParse->nTab += 3;\n  openStatTable(pParse, iDb, iStatCur, 0, 0);\n  iMem = pParse->nMem+1;\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){\n    Table *pTab = (Table*)sqliteHashData(k);\n    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);\n  }\n  loadAnalysis(pParse, iDb);\n}\n\n/*\n** Generate code that will do an analysis of a single table in\n** a database.  If pOnlyIdx is not NULL then it is a single index\n** in pTab that should be analyzed.\n*/\nstatic void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){\n  int iDb;\n  int iStatCur;\n\n  assert( pTab!=0 );\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  sqlite3BeginWriteOperation(pParse, 0, iDb);\n  iStatCur = pParse->nTab;\n  pParse->nTab += 3;\n  if( pOnlyIdx ){\n    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, \"idx\");\n  }else{\n    openStatTable(pParse, iDb, iStatCur, pTab->zName, \"tbl\");\n  }\n  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);\n  loadAnalysis(pParse, iDb);\n}\n\n/*\n** Generate code for the ANALYZE command.  The parser calls this routine\n** when it recognizes an ANALYZE command.\n**\n**        ANALYZE                            -- 1\n**        ANALYZE  <database>                -- 2\n**        ANALYZE  ?<database>.?<tablename>  -- 3\n**\n** Form 1 causes all indices in all attached databases to be analyzed.\n** Form 2 analyzes all indices the single database named.\n** Form 3 analyzes all indices associated with the named table.\n*/\nSQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){\n  sqlite3 *db = pParse->db;\n  int iDb;\n  int i;\n  char *z, *zDb;\n  Table *pTab;\n  Index *pIdx;\n  Token *pTableName;\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    return;\n  }\n\n  assert( pName2!=0 || pName1==0 );\n  if( pName1==0 ){\n    /* Form 1:  Analyze everything */\n    for(i=0; i<db->nDb; i++){\n      if( i==1 ) continue;  /* Do not analyze the TEMP database */\n      analyzeDatabase(pParse, i);\n    }\n  }else if( pName2->n==0 ){\n    /* Form 2:  Analyze the database or table named */\n    iDb = sqlite3FindDb(db, pName1);\n    if( iDb>=0 ){\n      analyzeDatabase(pParse, iDb);\n    }else{\n      z = sqlite3NameFromToken(db, pName1);\n      if( z ){\n        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){\n          analyzeTable(pParse, pIdx->pTable, pIdx);\n        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){\n          analyzeTable(pParse, pTab, 0);\n        }\n        sqlite3DbFree(db, z);\n      }\n    }\n  }else{\n    /* Form 3: Analyze the fully qualified table name */\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);\n    if( iDb>=0 ){\n      zDb = db->aDb[iDb].zName;\n      z = sqlite3NameFromToken(db, pTableName);\n      if( z ){\n        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){\n          analyzeTable(pParse, pIdx->pTable, pIdx);\n        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){\n          analyzeTable(pParse, pTab, 0);\n        }\n        sqlite3DbFree(db, z);\n      }\n    }   \n  }\n}\n\n/*\n** Used to pass information from the analyzer reader through to the\n** callback routine.\n*/\ntypedef struct analysisInfo analysisInfo;\nstruct analysisInfo {\n  sqlite3 *db;\n  const char *zDatabase;\n};\n\n/*\n** This callback is invoked once for each index when reading the\n** sqlite_stat1 table.  \n**\n**     argv[0] = name of the table\n**     argv[1] = name of the index (might be NULL)\n**     argv[2] = results of analysis - on integer for each column\n**\n** Entries for which argv[1]==NULL simply record the number of rows in\n** the table.\n*/\nstatic int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){\n  analysisInfo *pInfo = (analysisInfo*)pData;\n  Index *pIndex;\n  Table *pTable;\n  int i, c, n;\n  tRowcnt v;\n  const char *z;\n\n  assert( argc==3 );\n  UNUSED_PARAMETER2(NotUsed, argc);\n\n  if( argv==0 || argv[0]==0 || argv[2]==0 ){\n    return 0;\n  }\n  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);\n  if( pTable==0 ){\n    return 0;\n  }\n  if( argv[1] ){\n    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);\n  }else{\n    pIndex = 0;\n  }\n  n = pIndex ? pIndex->nColumn : 0;\n  z = argv[2];\n  for(i=0; *z && i<=n; i++){\n    v = 0;\n    while( (c=z[0])>='0' && c<='9' ){\n      v = v*10 + c - '0';\n      z++;\n    }\n    if( i==0 ) pTable->nRowEst = v;\n    if( pIndex==0 ) break;\n    pIndex->aiRowEst[i] = v;\n    if( *z==' ' ) z++;\n    if( memcmp(z, \"unordered\", 10)==0 ){\n      pIndex->bUnordered = 1;\n      break;\n    }\n  }\n  return 0;\n}\n\n/*\n** If the Index.aSample variable is not NULL, delete the aSample[] array\n** and its contents.\n*/\nSQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){\n#ifdef SQLITE_ENABLE_STAT3\n  if( pIdx->aSample ){\n    int j;\n    for(j=0; j<pIdx->nSample; j++){\n      IndexSample *p = &pIdx->aSample[j];\n      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){\n        sqlite3DbFree(db, p->u.z);\n      }\n    }\n    sqlite3DbFree(db, pIdx->aSample);\n  }\n  if( db && db->pnBytesFreed==0 ){\n    pIdx->nSample = 0;\n    pIdx->aSample = 0;\n  }\n#else\n  UNUSED_PARAMETER(db);\n  UNUSED_PARAMETER(pIdx);\n#endif\n}\n\n#ifdef SQLITE_ENABLE_STAT3\n/*\n** Load content from the sqlite_stat3 table into the Index.aSample[]\n** arrays of all indices.\n*/\nstatic int loadStat3(sqlite3 *db, const char *zDb){\n  int rc;                       /* Result codes from subroutines */\n  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */\n  char *zSql;                   /* Text of the SQL statement */\n  Index *pPrevIdx = 0;          /* Previous index in the loop */\n  int idx = 0;                  /* slot in pIdx->aSample[] for next sample */\n  int eType;                    /* Datatype of a sample */\n  IndexSample *pSample;         /* A slot in pIdx->aSample[] */\n\n  assert( db->lookaside.bEnabled==0 );\n  if( !sqlite3FindTable(db, \"sqlite_stat3\", zDb) ){\n    return SQLITE_OK;\n  }\n\n  zSql = sqlite3MPrintf(db, \n      \"SELECT idx,count(*) FROM %Q.sqlite_stat3\"\n      \" GROUP BY idx\", zDb);\n  if( !zSql ){\n    return SQLITE_NOMEM;\n  }\n  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  sqlite3DbFree(db, zSql);\n  if( rc ) return rc;\n\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    char *zIndex;   /* Index name */\n    Index *pIdx;    /* Pointer to the index object */\n    int nSample;    /* Number of samples */\n\n    zIndex = (char *)sqlite3_column_text(pStmt, 0);\n    if( zIndex==0 ) continue;\n    nSample = sqlite3_column_int(pStmt, 1);\n    pIdx = sqlite3FindIndex(db, zIndex, zDb);\n    if( pIdx==0 ) continue;\n    assert( pIdx->nSample==0 );\n    pIdx->nSample = nSample;\n    pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));\n    pIdx->avgEq = pIdx->aiRowEst[1];\n    if( pIdx->aSample==0 ){\n      db->mallocFailed = 1;\n      sqlite3_finalize(pStmt);\n      return SQLITE_NOMEM;\n    }\n  }\n  rc = sqlite3_finalize(pStmt);\n  if( rc ) return rc;\n\n  zSql = sqlite3MPrintf(db, \n      \"SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3\", zDb);\n  if( !zSql ){\n    return SQLITE_NOMEM;\n  }\n  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  sqlite3DbFree(db, zSql);\n  if( rc ) return rc;\n\n  while( sqlite3_step(pStmt)==SQLITE_ROW ){\n    char *zIndex;   /* Index name */\n    Index *pIdx;    /* Pointer to the index object */\n    int i;          /* Loop counter */\n    tRowcnt sumEq;  /* Sum of the nEq values */\n\n    zIndex = (char *)sqlite3_column_text(pStmt, 0);\n    if( zIndex==0 ) continue;\n    pIdx = sqlite3FindIndex(db, zIndex, zDb);\n    if( pIdx==0 ) continue;\n    if( pIdx==pPrevIdx ){\n      idx++;\n    }else{\n      pPrevIdx = pIdx;\n      idx = 0;\n    }\n    assert( idx<pIdx->nSample );\n    pSample = &pIdx->aSample[idx];\n    pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);\n    pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);\n    pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);\n    if( idx==pIdx->nSample-1 ){\n      if( pSample->nDLt>0 ){\n        for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;\n        pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;\n      }\n      if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;\n    }\n    eType = sqlite3_column_type(pStmt, 4);\n    pSample->eType = (u8)eType;\n    switch( eType ){\n      case SQLITE_INTEGER: {\n        pSample->u.i = sqlite3_column_int64(pStmt, 4);\n        break;\n      }\n      case SQLITE_FLOAT: {\n        pSample->u.r = sqlite3_column_double(pStmt, 4);\n        break;\n      }\n      case SQLITE_NULL: {\n        break;\n      }\n      default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {\n        const char *z = (const char *)(\n              (eType==SQLITE_BLOB) ?\n              sqlite3_column_blob(pStmt, 4):\n              sqlite3_column_text(pStmt, 4)\n           );\n        int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;\n        pSample->nByte = n;\n        if( n < 1){\n          pSample->u.z = 0;\n        }else{\n          pSample->u.z = sqlite3DbMallocRaw(db, n);\n          if( pSample->u.z==0 ){\n            db->mallocFailed = 1;\n            sqlite3_finalize(pStmt);\n            return SQLITE_NOMEM;\n          }\n          memcpy(pSample->u.z, z, n);\n        }\n      }\n    }\n  }\n  return sqlite3_finalize(pStmt);\n}\n#endif /* SQLITE_ENABLE_STAT3 */\n\n/*\n** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The\n** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]\n** arrays. The contents of sqlite_stat3 are used to populate the\n** Index.aSample[] arrays.\n**\n** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR\n** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined \n** during compilation and the sqlite_stat3 table is present, no data is \n** read from it.\n**\n** If SQLITE_ENABLE_STAT3 was defined during compilation and the \n** sqlite_stat3 table is not present in the database, SQLITE_ERROR is\n** returned. However, in this case, data is read from the sqlite_stat1\n** table (if it is present) before returning.\n**\n** If an OOM error occurs, this function always sets db->mallocFailed.\n** This means if the caller does not care about other errors, the return\n** code may be ignored.\n*/\nSQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){\n  analysisInfo sInfo;\n  HashElem *i;\n  char *zSql;\n  int rc;\n\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( db->aDb[iDb].pBt!=0 );\n\n  /* Clear any prior statistics */\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){\n    Index *pIdx = sqliteHashData(i);\n    sqlite3DefaultRowEst(pIdx);\n#ifdef SQLITE_ENABLE_STAT3\n    sqlite3DeleteIndexSamples(db, pIdx);\n    pIdx->aSample = 0;\n#endif\n  }\n\n  /* Check to make sure the sqlite_stat1 table exists */\n  sInfo.db = db;\n  sInfo.zDatabase = db->aDb[iDb].zName;\n  if( sqlite3FindTable(db, \"sqlite_stat1\", sInfo.zDatabase)==0 ){\n    return SQLITE_ERROR;\n  }\n\n  /* Load new statistics out of the sqlite_stat1 table */\n  zSql = sqlite3MPrintf(db, \n      \"SELECT tbl,idx,stat FROM %Q.sqlite_stat1\", sInfo.zDatabase);\n  if( zSql==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);\n    sqlite3DbFree(db, zSql);\n  }\n\n\n  /* Load the statistics from the sqlite_stat3 table. */\n#ifdef SQLITE_ENABLE_STAT3\n  if( rc==SQLITE_OK ){\n    int lookasideEnabled = db->lookaside.bEnabled;\n    db->lookaside.bEnabled = 0;\n    rc = loadStat3(db, sInfo.zDatabase);\n    db->lookaside.bEnabled = lookasideEnabled;\n  }\n#endif\n\n  if( rc==SQLITE_NOMEM ){\n    db->mallocFailed = 1;\n  }\n  return rc;\n}\n\n\n#endif /* SQLITE_OMIT_ANALYZE */\n\n/************** End of analyze.c *********************************************/\n/************** Begin file attach.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the ATTACH and DETACH commands.\n*/\n\n#ifndef SQLITE_OMIT_ATTACH\n/*\n** Resolve an expression that was part of an ATTACH or DETACH statement. This\n** is slightly different from resolving a normal SQL expression, because simple\n** identifiers are treated as strings, not possible column names or aliases.\n**\n** i.e. if the parser sees:\n**\n**     ATTACH DATABASE abc AS def\n**\n** it treats the two expressions as literal strings 'abc' and 'def' instead of\n** looking for columns of the same name.\n**\n** This only applies to the root node of pExpr, so the statement:\n**\n**     ATTACH DATABASE abc||def AS 'db2'\n**\n** will fail because neither abc or def can be resolved.\n*/\nstatic int resolveAttachExpr(NameContext *pName, Expr *pExpr)\n{\n  int rc = SQLITE_OK;\n  if( pExpr ){\n    if( pExpr->op!=TK_ID ){\n      rc = sqlite3ResolveExprNames(pName, pExpr);\n      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){\n        sqlite3ErrorMsg(pName->pParse, \"invalid name: \\\"%s\\\"\", pExpr->u.zToken);\n        return SQLITE_ERROR;\n      }\n    }else{\n      pExpr->op = TK_STRING;\n    }\n  }\n  return rc;\n}\n\n/*\n** An SQL user-function registered to do the work of an ATTACH statement. The\n** three arguments to the function come directly from an attach statement:\n**\n**     ATTACH DATABASE x AS y KEY z\n**\n**     SELECT sqlite_attach(x, y, z)\n**\n** If the optional \"KEY z\" syntax is omitted, an SQL NULL is passed as the\n** third argument.\n*/\nstatic void attachFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  int i;\n  int rc = 0;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  const char *zName;\n  const char *zFile;\n  char *zPath = 0;\n  char *zErr = 0;\n  unsigned int flags;\n  Db *aNew;\n  char *zErrDyn = 0;\n  sqlite3_vfs *pVfs;\n\n  UNUSED_PARAMETER(NotUsed);\n\n  zFile = (const char *)sqlite3_value_text(argv[0]);\n  zName = (const char *)sqlite3_value_text(argv[1]);\n  if( zFile==0 ) zFile = \"\";\n  if( zName==0 ) zName = \"\";\n\n  /* Check for the following errors:\n  **\n  **     * Too many attached databases,\n  **     * Transaction currently open\n  **     * Specified database name already being used.\n  */\n  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){\n    zErrDyn = sqlite3MPrintf(db, \"too many attached databases - max %d\", \n      db->aLimit[SQLITE_LIMIT_ATTACHED]\n    );\n    goto attach_error;\n  }\n  if( !db->autoCommit ){\n    zErrDyn = sqlite3MPrintf(db, \"cannot ATTACH database within transaction\");\n    goto attach_error;\n  }\n  for(i=0; i<db->nDb; i++){\n    char *z = db->aDb[i].zName;\n    assert( z && zName );\n    if( sqlite3StrICmp(z, zName)==0 ){\n      zErrDyn = sqlite3MPrintf(db, \"database %s is already in use\", zName);\n      goto attach_error;\n    }\n  }\n\n  /* Allocate the new entry in the db->aDb[] array and initialise the schema\n  ** hash tables.\n  */\n  if( db->aDb==db->aDbStatic ){\n    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );\n    if( aNew==0 ) return;\n    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);\n  }else{\n    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );\n    if( aNew==0 ) return;\n  }\n  db->aDb = aNew;\n  aNew = &db->aDb[db->nDb];\n  memset(aNew, 0, sizeof(*aNew));\n\n  /* Open the database file. If the btree is successfully opened, use\n  ** it to obtain the database schema. At this point the schema may\n  ** or may not be initialised.\n  */\n  flags = db->openFlags;\n  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;\n    sqlite3_result_error(context, zErr, -1);\n    sqlite3_free(zErr);\n    return;\n  }\n  assert( pVfs );\n  flags |= SQLITE_OPEN_MAIN_DB;\n  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);\n  sqlite3_free( zPath );\n  db->nDb++;\n  if( rc==SQLITE_CONSTRAINT ){\n    rc = SQLITE_ERROR;\n    zErrDyn = sqlite3MPrintf(db, \"database is already attached\");\n  }else if( rc==SQLITE_OK ){\n    Pager *pPager;\n    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);\n    if( !aNew->pSchema ){\n      rc = SQLITE_NOMEM;\n    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){\n      zErrDyn = sqlite3MPrintf(db, \n        \"attached databases must use the same text encoding as main database\");\n      rc = SQLITE_ERROR;\n    }\n    pPager = sqlite3BtreePager(aNew->pBt);\n    sqlite3PagerLockingMode(pPager, db->dfltLockMode);\n    sqlite3BtreeSecureDelete(aNew->pBt,\n                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );\n  }\n  aNew->safety_level = 3;\n  aNew->zName = sqlite3DbStrDup(db, zName);\n  if( rc==SQLITE_OK && aNew->zName==0 ){\n    rc = SQLITE_NOMEM;\n  }\n\n\n#ifdef SQLITE_HAS_CODEC\n  if( rc==SQLITE_OK ){\n    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);\n    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);\n    int nKey;\n    char *zKey;\n    int t = sqlite3_value_type(argv[2]);\n    switch( t ){\n      case SQLITE_INTEGER:\n      case SQLITE_FLOAT:\n        zErrDyn = sqlite3DbStrDup(db, \"Invalid key value\");\n        rc = SQLITE_ERROR;\n        break;\n        \n      case SQLITE_TEXT:\n      case SQLITE_BLOB:\n        nKey = sqlite3_value_bytes(argv[2]);\n        zKey = (char *)sqlite3_value_blob(argv[2]);\n        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);\n        break;\n\n      case SQLITE_NULL:\n        /* No key specified.  Use the key from the main database */\n        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);\n        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){\n          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);\n        }\n        break;\n    }\n  }\n#endif\n\n  /* If the file was opened successfully, read the schema for the new database.\n  ** If this fails, or if opening the file failed, then close the file and \n  ** remove the entry from the db->aDb[] array. i.e. put everything back the way\n  ** we found it.\n  */\n  if( rc==SQLITE_OK ){\n    sqlite3BtreeEnterAll(db);\n    rc = sqlite3Init(db, &zErrDyn);\n    sqlite3BtreeLeaveAll(db);\n  }\n  if( rc ){\n    int iDb = db->nDb - 1;\n    assert( iDb>=2 );\n    if( db->aDb[iDb].pBt ){\n      sqlite3BtreeClose(db->aDb[iDb].pBt);\n      db->aDb[iDb].pBt = 0;\n      db->aDb[iDb].pSchema = 0;\n    }\n    sqlite3ResetAllSchemasOfConnection(db);\n    db->nDb = iDb;\n    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n      db->mallocFailed = 1;\n      sqlite3DbFree(db, zErrDyn);\n      zErrDyn = sqlite3MPrintf(db, \"out of memory\");\n    }else if( zErrDyn==0 ){\n      zErrDyn = sqlite3MPrintf(db, \"unable to open database: %s\", zFile);\n    }\n    goto attach_error;\n  }\n  \n  return;\n\nattach_error:\n  /* Return an error if we get here */\n  if( zErrDyn ){\n    sqlite3_result_error(context, zErrDyn, -1);\n    sqlite3DbFree(db, zErrDyn);\n  }\n  if( rc ) sqlite3_result_error_code(context, rc);\n}\n\n/*\n** An SQL user-function registered to do the work of an DETACH statement. The\n** three arguments to the function come directly from a detach statement:\n**\n**     DETACH DATABASE x\n**\n**     SELECT sqlite_detach(x)\n*/\nstatic void detachFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  const char *zName = (const char *)sqlite3_value_text(argv[0]);\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  int i;\n  Db *pDb = 0;\n  char zErr[128];\n\n  UNUSED_PARAMETER(NotUsed);\n\n  if( zName==0 ) zName = \"\";\n  for(i=0; i<db->nDb; i++){\n    pDb = &db->aDb[i];\n    if( pDb->pBt==0 ) continue;\n    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;\n  }\n\n  if( i>=db->nDb ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"no such database: %s\", zName);\n    goto detach_error;\n  }\n  if( i<2 ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"cannot detach database %s\", zName);\n    goto detach_error;\n  }\n  if( !db->autoCommit ){\n    sqlite3_snprintf(sizeof(zErr), zErr,\n                     \"cannot DETACH database within transaction\");\n    goto detach_error;\n  }\n  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){\n    sqlite3_snprintf(sizeof(zErr),zErr, \"database %s is locked\", zName);\n    goto detach_error;\n  }\n\n  sqlite3BtreeClose(pDb->pBt);\n  pDb->pBt = 0;\n  pDb->pSchema = 0;\n  sqlite3ResetAllSchemasOfConnection(db);\n  return;\n\ndetach_error:\n  sqlite3_result_error(context, zErr, -1);\n}\n\n/*\n** This procedure generates VDBE code for a single invocation of either the\n** sqlite_detach() or sqlite_attach() SQL user functions.\n*/\nstatic void codeAttach(\n  Parse *pParse,       /* The parser context */\n  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */\n  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */\n  Expr *pAuthArg,      /* Expression to pass to authorization callback */\n  Expr *pFilename,     /* Name of database file */\n  Expr *pDbname,       /* Name of the database to use internally */\n  Expr *pKey           /* Database key for encryption extension */\n){\n  int rc;\n  NameContext sName;\n  Vdbe *v;\n  sqlite3* db = pParse->db;\n  int regArgs;\n\n  memset(&sName, 0, sizeof(NameContext));\n  sName.pParse = pParse;\n\n  if( \n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||\n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||\n      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))\n  ){\n    pParse->nErr++;\n    goto attach_end;\n  }\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( pAuthArg ){\n    char *zAuthArg;\n    if( pAuthArg->op==TK_STRING ){\n      zAuthArg = pAuthArg->u.zToken;\n    }else{\n      zAuthArg = 0;\n    }\n    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);\n    if(rc!=SQLITE_OK ){\n      goto attach_end;\n    }\n  }\n#endif /* SQLITE_OMIT_AUTHORIZATION */\n\n\n  v = sqlite3GetVdbe(pParse);\n  regArgs = sqlite3GetTempRange(pParse, 4);\n  sqlite3ExprCode(pParse, pFilename, regArgs);\n  sqlite3ExprCode(pParse, pDbname, regArgs+1);\n  sqlite3ExprCode(pParse, pKey, regArgs+2);\n\n  assert( v || db->mallocFailed );\n  if( v ){\n    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);\n    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );\n    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));\n    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);\n\n    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this\n    ** statement only). For DETACH, set it to false (expire all existing\n    ** statements).\n    */\n    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));\n  }\n  \nattach_end:\n  sqlite3ExprDelete(db, pFilename);\n  sqlite3ExprDelete(db, pDbname);\n  sqlite3ExprDelete(db, pKey);\n}\n\n/*\n** Called by the parser to compile a DETACH statement.\n**\n**     DETACH pDbname\n*/\nSQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){\n  static const FuncDef detach_func = {\n    1,                /* nArg */\n    SQLITE_UTF8,      /* iPrefEnc */\n    0,                /* flags */\n    0,                /* pUserData */\n    0,                /* pNext */\n    detachFunc,       /* xFunc */\n    0,                /* xStep */\n    0,                /* xFinalize */\n    \"sqlite_detach\",  /* zName */\n    0,                /* pHash */\n    0                 /* pDestructor */\n  };\n  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);\n}\n\n/*\n** Called by the parser to compile an ATTACH statement.\n**\n**     ATTACH p AS pDbname KEY pKey\n*/\nSQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){\n  static const FuncDef attach_func = {\n    3,                /* nArg */\n    SQLITE_UTF8,      /* iPrefEnc */\n    0,                /* flags */\n    0,                /* pUserData */\n    0,                /* pNext */\n    attachFunc,       /* xFunc */\n    0,                /* xStep */\n    0,                /* xFinalize */\n    \"sqlite_attach\",  /* zName */\n    0,                /* pHash */\n    0                 /* pDestructor */\n  };\n  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);\n}\n#endif /* SQLITE_OMIT_ATTACH */\n\n/*\n** Initialize a DbFixer structure.  This routine must be called prior\n** to passing the structure to one of the sqliteFixAAAA() routines below.\n**\n** The return value indicates whether or not fixation is required.  TRUE\n** means we do need to fix the database references, FALSE means we do not.\n*/\nSQLITE_PRIVATE int sqlite3FixInit(\n  DbFixer *pFix,      /* The fixer to be initialized */\n  Parse *pParse,      /* Error messages will be written here */\n  int iDb,            /* This is the database that must be used */\n  const char *zType,  /* \"view\", \"trigger\", or \"index\" */\n  const Token *pName  /* Name of the view, trigger, or index */\n){\n  sqlite3 *db;\n\n  if( NEVER(iDb<0) || iDb==1 ) return 0;\n  db = pParse->db;\n  assert( db->nDb>iDb );\n  pFix->pParse = pParse;\n  pFix->zDb = db->aDb[iDb].zName;\n  pFix->zType = zType;\n  pFix->pName = pName;\n  return 1;\n}\n\n/*\n** The following set of routines walk through the parse tree and assign\n** a specific database to all table references where the database name\n** was left unspecified in the original SQL statement.  The pFix structure\n** must have been initialized by a prior call to sqlite3FixInit().\n**\n** These routines are used to make sure that an index, trigger, or\n** view in one database does not refer to objects in a different database.\n** (Exception: indices, triggers, and views in the TEMP database are\n** allowed to refer to anything.)  If a reference is explicitly made\n** to an object in a different database, an error message is added to\n** pParse->zErrMsg and these routines return non-zero.  If everything\n** checks out, these routines return 0.\n*/\nSQLITE_PRIVATE int sqlite3FixSrcList(\n  DbFixer *pFix,       /* Context of the fixation */\n  SrcList *pList       /* The Source list to check and modify */\n){\n  int i;\n  const char *zDb;\n  struct SrcList_item *pItem;\n\n  if( NEVER(pList==0) ) return 0;\n  zDb = pFix->zDb;\n  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){\n    if( pItem->zDatabase==0 ){\n      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);\n    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){\n      sqlite3ErrorMsg(pFix->pParse,\n         \"%s %T cannot reference objects in database %s\",\n         pFix->zType, pFix->pName, pItem->zDatabase);\n      return 1;\n    }\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)\n    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;\n    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;\n#endif\n  }\n  return 0;\n}\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)\nSQLITE_PRIVATE int sqlite3FixSelect(\n  DbFixer *pFix,       /* Context of the fixation */\n  Select *pSelect      /* The SELECT statement to be fixed to one database */\n){\n  while( pSelect ){\n    if( sqlite3FixExprList(pFix, pSelect->pEList) ){\n      return 1;\n    }\n    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){\n      return 1;\n    }\n    pSelect = pSelect->pPrior;\n  }\n  return 0;\n}\nSQLITE_PRIVATE int sqlite3FixExpr(\n  DbFixer *pFix,     /* Context of the fixation */\n  Expr *pExpr        /* The expression to be fixed to one database */\n){\n  while( pExpr ){\n    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;\n    }else{\n      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;\n    }\n    if( sqlite3FixExpr(pFix, pExpr->pRight) ){\n      return 1;\n    }\n    pExpr = pExpr->pLeft;\n  }\n  return 0;\n}\nSQLITE_PRIVATE int sqlite3FixExprList(\n  DbFixer *pFix,     /* Context of the fixation */\n  ExprList *pList    /* The expression to be fixed to one database */\n){\n  int i;\n  struct ExprList_item *pItem;\n  if( pList==0 ) return 0;\n  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){\n    if( sqlite3FixExpr(pFix, pItem->pExpr) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif\n\n#ifndef SQLITE_OMIT_TRIGGER\nSQLITE_PRIVATE int sqlite3FixTriggerStep(\n  DbFixer *pFix,     /* Context of the fixation */\n  TriggerStep *pStep /* The trigger step be fixed to one database */\n){\n  while( pStep ){\n    if( sqlite3FixSelect(pFix, pStep->pSelect) ){\n      return 1;\n    }\n    if( sqlite3FixExpr(pFix, pStep->pWhere) ){\n      return 1;\n    }\n    if( sqlite3FixExprList(pFix, pStep->pExprList) ){\n      return 1;\n    }\n    pStep = pStep->pNext;\n  }\n  return 0;\n}\n#endif\n\n/************** End of attach.c **********************************************/\n/************** Begin file auth.c ********************************************/\n/*\n** 2003 January 11\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the sqlite3_set_authorizer()\n** API.  This facility is an optional feature of the library.  Embedded\n** systems that do not need this facility may omit it by recompiling\n** the library with -DSQLITE_OMIT_AUTHORIZATION=1\n*/\n\n/*\n** All of the code in this file may be omitted by defining a single\n** macro.\n*/\n#ifndef SQLITE_OMIT_AUTHORIZATION\n\n/*\n** Set or clear the access authorization function.\n**\n** The access authorization function is be called during the compilation\n** phase to verify that the user has read and/or write access permission on\n** various fields of the database.  The first argument to the auth function\n** is a copy of the 3rd argument to this routine.  The second argument\n** to the auth function is one of these constants:\n**\n**       SQLITE_CREATE_INDEX\n**       SQLITE_CREATE_TABLE\n**       SQLITE_CREATE_TEMP_INDEX\n**       SQLITE_CREATE_TEMP_TABLE\n**       SQLITE_CREATE_TEMP_TRIGGER\n**       SQLITE_CREATE_TEMP_VIEW\n**       SQLITE_CREATE_TRIGGER\n**       SQLITE_CREATE_VIEW\n**       SQLITE_DELETE\n**       SQLITE_DROP_INDEX\n**       SQLITE_DROP_TABLE\n**       SQLITE_DROP_TEMP_INDEX\n**       SQLITE_DROP_TEMP_TABLE\n**       SQLITE_DROP_TEMP_TRIGGER\n**       SQLITE_DROP_TEMP_VIEW\n**       SQLITE_DROP_TRIGGER\n**       SQLITE_DROP_VIEW\n**       SQLITE_INSERT\n**       SQLITE_PRAGMA\n**       SQLITE_READ\n**       SQLITE_SELECT\n**       SQLITE_TRANSACTION\n**       SQLITE_UPDATE\n**\n** The third and fourth arguments to the auth function are the name of\n** the table and the column that are being accessed.  The auth function\n** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If\n** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY\n** means that the SQL statement will never-run - the sqlite3_exec() call\n** will return with an error.  SQLITE_IGNORE means that the SQL statement\n** should run but attempts to read the specified column will return NULL\n** and attempts to write the column will be ignored.\n**\n** Setting the auth function to NULL disables this hook.  The default\n** setting of the auth function is NULL.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3 *db,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pArg\n){\n  sqlite3_mutex_enter(db->mutex);\n  db->xAuth = xAuth;\n  db->pAuthArg = pArg;\n  sqlite3ExpirePreparedStatements(db);\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Write an error message into pParse->zErrMsg that explains that the\n** user-supplied authorization function returned an illegal value.\n*/\nstatic void sqliteAuthBadReturnCode(Parse *pParse){\n  sqlite3ErrorMsg(pParse, \"authorizer malfunction\");\n  pParse->rc = SQLITE_ERROR;\n}\n\n/*\n** Invoke the authorization callback for permission to read column zCol from\n** table zTab in database zDb. This function assumes that an authorization\n** callback has been registered (i.e. that sqlite3.xAuth is not NULL).\n**\n** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed\n** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE\n** is treated as SQLITE_DENY. In this case an error is left in pParse.\n*/\nSQLITE_PRIVATE int sqlite3AuthReadCol(\n  Parse *pParse,                  /* The parser context */\n  const char *zTab,               /* Table name */\n  const char *zCol,               /* Column name */\n  int iDb                         /* Index of containing database. */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  char *zDb = db->aDb[iDb].zName; /* Name of attached database */\n  int rc;                         /* Auth callback return code */\n\n  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);\n  if( rc==SQLITE_DENY ){\n    if( db->nDb>2 || iDb!=0 ){\n      sqlite3ErrorMsg(pParse, \"access to %s.%s.%s is prohibited\",zDb,zTab,zCol);\n    }else{\n      sqlite3ErrorMsg(pParse, \"access to %s.%s is prohibited\", zTab, zCol);\n    }\n    pParse->rc = SQLITE_AUTH;\n  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){\n    sqliteAuthBadReturnCode(pParse);\n  }\n  return rc;\n}\n\n/*\n** The pExpr should be a TK_COLUMN expression.  The table referred to\n** is in pTabList or else it is the NEW or OLD table of a trigger.  \n** Check to see if it is OK to read this particular column.\n**\n** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN \n** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,\n** then generate an error.\n*/\nSQLITE_PRIVATE void sqlite3AuthRead(\n  Parse *pParse,        /* The parser context */\n  Expr *pExpr,          /* The expression to check authorization on */\n  Schema *pSchema,      /* The schema of the expression */\n  SrcList *pTabList     /* All table that pExpr might refer to */\n){\n  sqlite3 *db = pParse->db;\n  Table *pTab = 0;      /* The table being read */\n  const char *zCol;     /* Name of the column of the table */\n  int iSrc;             /* Index in pTabList->a[] of table being read */\n  int iDb;              /* The index of the database the expression refers to */\n  int iCol;             /* Index of column in table */\n\n  if( db->xAuth==0 ) return;\n  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);\n  if( iDb<0 ){\n    /* An attempt to read a column out of a subquery or other\n    ** temporary table. */\n    return;\n  }\n\n  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );\n  if( pExpr->op==TK_TRIGGER ){\n    pTab = pParse->pTriggerTab;\n  }else{\n    assert( pTabList );\n    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){\n      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){\n        pTab = pTabList->a[iSrc].pTab;\n        break;\n      }\n    }\n  }\n  iCol = pExpr->iColumn;\n  if( NEVER(pTab==0) ) return;\n\n  if( iCol>=0 ){\n    assert( iCol<pTab->nCol );\n    zCol = pTab->aCol[iCol].zName;\n  }else if( pTab->iPKey>=0 ){\n    assert( pTab->iPKey<pTab->nCol );\n    zCol = pTab->aCol[pTab->iPKey].zName;\n  }else{\n    zCol = \"ROWID\";\n  }\n  assert( iDb>=0 && iDb<db->nDb );\n  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){\n    pExpr->op = TK_NULL;\n  }\n}\n\n/*\n** Do an authorization check using the code and arguments given.  Return\n** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY\n** is returned, then the error count and error message in pParse are\n** modified appropriately.\n*/\nSQLITE_PRIVATE int sqlite3AuthCheck(\n  Parse *pParse,\n  int code,\n  const char *zArg1,\n  const char *zArg2,\n  const char *zArg3\n){\n  sqlite3 *db = pParse->db;\n  int rc;\n\n  /* Don't do any authorization checks if the database is initialising\n  ** or if the parser is being invoked from within sqlite3_declare_vtab.\n  */\n  if( db->init.busy || IN_DECLARE_VTAB ){\n    return SQLITE_OK;\n  }\n\n  if( db->xAuth==0 ){\n    return SQLITE_OK;\n  }\n  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);\n  if( rc==SQLITE_DENY ){\n    sqlite3ErrorMsg(pParse, \"not authorized\");\n    pParse->rc = SQLITE_AUTH;\n  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){\n    rc = SQLITE_DENY;\n    sqliteAuthBadReturnCode(pParse);\n  }\n  return rc;\n}\n\n/*\n** Push an authorization context.  After this routine is called, the\n** zArg3 argument to authorization callbacks will be zContext until\n** popped.  Or if pParse==0, this routine is a no-op.\n*/\nSQLITE_PRIVATE void sqlite3AuthContextPush(\n  Parse *pParse,\n  AuthContext *pContext, \n  const char *zContext\n){\n  assert( pParse );\n  pContext->pParse = pParse;\n  pContext->zAuthContext = pParse->zAuthContext;\n  pParse->zAuthContext = zContext;\n}\n\n/*\n** Pop an authorization context that was previously pushed\n** by sqlite3AuthContextPush\n*/\nSQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){\n  if( pContext->pParse ){\n    pContext->pParse->zAuthContext = pContext->zAuthContext;\n    pContext->pParse = 0;\n  }\n}\n\n#endif /* SQLITE_OMIT_AUTHORIZATION */\n\n/************** End of auth.c ************************************************/\n/************** Begin file build.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the SQLite parser\n** when syntax rules are reduced.  The routines in this file handle the\n** following kinds of SQL syntax:\n**\n**     CREATE TABLE\n**     DROP TABLE\n**     CREATE INDEX\n**     DROP INDEX\n**     creating ID lists\n**     BEGIN TRANSACTION\n**     COMMIT\n**     ROLLBACK\n*/\n\n/*\n** This routine is called when a new SQL statement is beginning to\n** be parsed.  Initialize the pParse structure as needed.\n*/\nSQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){\n  pParse->explain = (u8)explainFlag;\n  pParse->nVar = 0;\n}\n\n#ifndef SQLITE_OMIT_SHARED_CACHE\n/*\n** The TableLock structure is only used by the sqlite3TableLock() and\n** codeTableLocks() functions.\n*/\nstruct TableLock {\n  int iDb;             /* The database containing the table to be locked */\n  int iTab;            /* The root page of the table to be locked */\n  u8 isWriteLock;      /* True for write lock.  False for a read lock */\n  const char *zName;   /* Name of the table */\n};\n\n/*\n** Record the fact that we want to lock a table at run-time.  \n**\n** The table to be locked has root page iTab and is found in database iDb.\n** A read or a write lock can be taken depending on isWritelock.\n**\n** This routine just records the fact that the lock is desired.  The\n** code to make the lock occur is generated by a later call to\n** codeTableLocks() which occurs during sqlite3FinishCoding().\n*/\nSQLITE_PRIVATE void sqlite3TableLock(\n  Parse *pParse,     /* Parsing context */\n  int iDb,           /* Index of the database containing the table to lock */\n  int iTab,          /* Root page number of the table to be locked */\n  u8 isWriteLock,    /* True for a write lock */\n  const char *zName  /* Name of the table to be locked */\n){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  int i;\n  int nBytes;\n  TableLock *p;\n  assert( iDb>=0 );\n\n  for(i=0; i<pToplevel->nTableLock; i++){\n    p = &pToplevel->aTableLock[i];\n    if( p->iDb==iDb && p->iTab==iTab ){\n      p->isWriteLock = (p->isWriteLock || isWriteLock);\n      return;\n    }\n  }\n\n  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);\n  pToplevel->aTableLock =\n      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);\n  if( pToplevel->aTableLock ){\n    p = &pToplevel->aTableLock[pToplevel->nTableLock++];\n    p->iDb = iDb;\n    p->iTab = iTab;\n    p->isWriteLock = isWriteLock;\n    p->zName = zName;\n  }else{\n    pToplevel->nTableLock = 0;\n    pToplevel->db->mallocFailed = 1;\n  }\n}\n\n/*\n** Code an OP_TableLock instruction for each table locked by the\n** statement (configured by calls to sqlite3TableLock()).\n*/\nstatic void codeTableLocks(Parse *pParse){\n  int i;\n  Vdbe *pVdbe; \n\n  pVdbe = sqlite3GetVdbe(pParse);\n  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */\n\n  for(i=0; i<pParse->nTableLock; i++){\n    TableLock *p = &pParse->aTableLock[i];\n    int p1 = p->iDb;\n    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,\n                      p->zName, P4_STATIC);\n  }\n}\n#else\n  #define codeTableLocks(x)\n#endif\n\n/*\n** This routine is called after a single SQL statement has been\n** parsed and a VDBE program to execute that statement has been\n** prepared.  This routine puts the finishing touches on the\n** VDBE program and resets the pParse structure for the next\n** parse.\n**\n** Note that if an error occurred, it might be the case that\n** no VDBE code was generated.\n*/\nSQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){\n  sqlite3 *db;\n  Vdbe *v;\n\n  db = pParse->db;\n  if( db->mallocFailed ) return;\n  if( pParse->nested ) return;\n  if( pParse->nErr ) return;\n\n  /* Begin by generating some termination code at the end of the\n  ** vdbe program\n  */\n  v = sqlite3GetVdbe(pParse);\n  assert( !pParse->isMultiWrite \n       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));\n  if( v ){\n    sqlite3VdbeAddOp0(v, OP_Halt);\n\n    /* The cookie mask contains one bit for each database file open.\n    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are\n    ** set for each database that is used.  Generate code to start a\n    ** transaction on each used database and to verify the schema cookie\n    ** on each used database.\n    */\n    if( pParse->cookieGoto>0 ){\n      yDbMask mask;\n      int iDb;\n      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);\n      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){\n        if( (mask & pParse->cookieMask)==0 ) continue;\n        sqlite3VdbeUsesBtree(v, iDb);\n        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);\n        if( db->init.busy==0 ){\n          assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n          sqlite3VdbeAddOp3(v, OP_VerifyCookie,\n                            iDb, pParse->cookieValue[iDb],\n                            db->aDb[iDb].pSchema->iGeneration);\n        }\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n      {\n        int i;\n        for(i=0; i<pParse->nVtabLock; i++){\n          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);\n          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);\n        }\n        pParse->nVtabLock = 0;\n      }\n#endif\n\n      /* Once all the cookies have been verified and transactions opened, \n      ** obtain the required table-locks. This is a no-op unless the \n      ** shared-cache feature is enabled.\n      */\n      codeTableLocks(pParse);\n\n      /* Initialize any AUTOINCREMENT data structures required.\n      */\n      sqlite3AutoincrementBegin(pParse);\n\n      /* Finally, jump back to the beginning of the executable code. */\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);\n    }\n  }\n\n\n  /* Get the VDBE program ready for execution\n  */\n  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){\n#ifdef SQLITE_DEBUG\n    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;\n    sqlite3VdbeTrace(v, trace);\n#endif\n    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */\n    /* A minimum of one cursor is required if autoincrement is used\n    *  See ticket [a696379c1f08866] */\n    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;\n    sqlite3VdbeMakeReady(v, pParse);\n    pParse->rc = SQLITE_DONE;\n    pParse->colNamesSet = 0;\n  }else{\n    pParse->rc = SQLITE_ERROR;\n  }\n  pParse->nTab = 0;\n  pParse->nMem = 0;\n  pParse->nSet = 0;\n  pParse->nVar = 0;\n  pParse->cookieMask = 0;\n  pParse->cookieGoto = 0;\n}\n\n/*\n** Run the parser and code generator recursively in order to generate\n** code for the SQL statement given onto the end of the pParse context\n** currently under construction.  When the parser is run recursively\n** this way, the final OP_Halt is not appended and other initialization\n** and finalization steps are omitted because those are handling by the\n** outermost parser.\n**\n** Not everything is nestable.  This facility is designed to permit\n** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use\n** care if you decide to try to use this routine for some other purposes.\n*/\nSQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){\n  va_list ap;\n  char *zSql;\n  char *zErrMsg = 0;\n  sqlite3 *db = pParse->db;\n# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))\n  char saveBuf[SAVE_SZ];\n\n  if( pParse->nErr ) return;\n  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */\n  va_start(ap, zFormat);\n  zSql = sqlite3VMPrintf(db, zFormat, ap);\n  va_end(ap);\n  if( zSql==0 ){\n    return;   /* A malloc must have failed */\n  }\n  pParse->nested++;\n  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);\n  memset(&pParse->nVar, 0, SAVE_SZ);\n  sqlite3RunParser(pParse, zSql, &zErrMsg);\n  sqlite3DbFree(db, zErrMsg);\n  sqlite3DbFree(db, zSql);\n  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);\n  pParse->nested--;\n}\n\n/*\n** Locate the in-memory structure that describes a particular database\n** table given the name of that table and (optionally) the name of the\n** database containing the table.  Return NULL if not found.\n**\n** If zDatabase is 0, all databases are searched for the table and the\n** first matching table is returned.  (No checking for duplicate table\n** names is done.)  The search order is TEMP first, then MAIN, then any\n** auxiliary databases added using the ATTACH command.\n**\n** See also sqlite3LocateTable().\n*/\nSQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){\n  Table *p = 0;\n  int i;\n  int nName;\n  assert( zName!=0 );\n  nName = sqlite3Strlen30(zName);\n  /* All mutexes are required for schema access.  Make sure we hold them. */\n  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n  for(i=OMIT_TEMPDB; i<db->nDb; i++){\n    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */\n    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;\n    assert( sqlite3SchemaMutexHeld(db, j, 0) );\n    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);\n    if( p ) break;\n  }\n  return p;\n}\n\n/*\n** Locate the in-memory structure that describes a particular database\n** table given the name of that table and (optionally) the name of the\n** database containing the table.  Return NULL if not found.  Also leave an\n** error message in pParse->zErrMsg.\n**\n** The difference between this routine and sqlite3FindTable() is that this\n** routine leaves an error message in pParse->zErrMsg where\n** sqlite3FindTable() does not.\n*/\nSQLITE_PRIVATE Table *sqlite3LocateTable(\n  Parse *pParse,         /* context in which to report errors */\n  int isView,            /* True if looking for a VIEW rather than a TABLE */\n  const char *zName,     /* Name of the table we are looking for */\n  const char *zDbase     /* Name of the database.  Might be NULL */\n){\n  Table *p;\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    return 0;\n  }\n\n  p = sqlite3FindTable(pParse->db, zName, zDbase);\n  if( p==0 ){\n    const char *zMsg = isView ? \"no such view\" : \"no such table\";\n    if( zDbase ){\n      sqlite3ErrorMsg(pParse, \"%s: %s.%s\", zMsg, zDbase, zName);\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s: %s\", zMsg, zName);\n    }\n    pParse->checkSchema = 1;\n  }\n  return p;\n}\n\n/*\n** Locate the in-memory structure that describes \n** a particular index given the name of that index\n** and the name of the database that contains the index.\n** Return NULL if not found.\n**\n** If zDatabase is 0, all databases are searched for the\n** table and the first matching index is returned.  (No checking\n** for duplicate index names is done.)  The search order is\n** TEMP first, then MAIN, then any auxiliary databases added\n** using the ATTACH command.\n*/\nSQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){\n  Index *p = 0;\n  int i;\n  int nName = sqlite3Strlen30(zName);\n  /* All mutexes are required for schema access.  Make sure we hold them. */\n  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n  for(i=OMIT_TEMPDB; i<db->nDb; i++){\n    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */\n    Schema *pSchema = db->aDb[j].pSchema;\n    assert( pSchema );\n    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;\n    assert( sqlite3SchemaMutexHeld(db, j, 0) );\n    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);\n    if( p ) break;\n  }\n  return p;\n}\n\n/*\n** Reclaim the memory used by an index\n*/\nstatic void freeIndex(sqlite3 *db, Index *p){\n#ifndef SQLITE_OMIT_ANALYZE\n  sqlite3DeleteIndexSamples(db, p);\n#endif\n  sqlite3DbFree(db, p->zColAff);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** For the index called zIdxName which is found in the database iDb,\n** unlike that index from its Table then remove the index from\n** the index hash table and free all memory structures associated\n** with the index.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){\n  Index *pIndex;\n  int len;\n  Hash *pHash;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pHash = &db->aDb[iDb].pSchema->idxHash;\n  len = sqlite3Strlen30(zIdxName);\n  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);\n  if( ALWAYS(pIndex) ){\n    if( pIndex->pTable->pIndex==pIndex ){\n      pIndex->pTable->pIndex = pIndex->pNext;\n    }else{\n      Index *p;\n      /* Justification of ALWAYS();  The index must be on the list of\n      ** indices. */\n      p = pIndex->pTable->pIndex;\n      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }\n      if( ALWAYS(p && p->pNext==pIndex) ){\n        p->pNext = pIndex->pNext;\n      }\n    }\n    freeIndex(db, pIndex);\n  }\n  db->flags |= SQLITE_InternChanges;\n}\n\n/*\n** Look through the list of open database files in db->aDb[] and if\n** any have been closed, remove them from the list.  Reallocate the\n** db->aDb[] structure to a smaller size, if possible.\n**\n** Entry 0 (the \"main\" database) and entry 1 (the \"temp\" database)\n** are never candidates for being collapsed.\n*/\nSQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){\n  int i, j;\n  for(i=j=2; i<db->nDb; i++){\n    struct Db *pDb = &db->aDb[i];\n    if( pDb->pBt==0 ){\n      sqlite3DbFree(db, pDb->zName);\n      pDb->zName = 0;\n      continue;\n    }\n    if( j<i ){\n      db->aDb[j] = db->aDb[i];\n    }\n    j++;\n  }\n  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));\n  db->nDb = j;\n  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){\n    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));\n    sqlite3DbFree(db, db->aDb);\n    db->aDb = db->aDbStatic;\n  }\n}\n\n/*\n** Reset the schema for the database at index iDb.  Also reset the\n** TEMP schema.\n*/\nSQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){\n  Db *pDb;\n  assert( iDb<db->nDb );\n\n  /* Case 1:  Reset the single schema identified by iDb */\n  pDb = &db->aDb[iDb];\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  assert( pDb->pSchema!=0 );\n  sqlite3SchemaClear(pDb->pSchema);\n\n  /* If any database other than TEMP is reset, then also reset TEMP\n  ** since TEMP might be holding triggers that reference tables in the\n  ** other database.\n  */\n  if( iDb!=1 ){\n    pDb = &db->aDb[1];\n    assert( pDb->pSchema!=0 );\n    sqlite3SchemaClear(pDb->pSchema);\n  }\n  return;\n}\n\n/*\n** Erase all schema information from all attached databases (including\n** \"main\" and \"temp\") for a single database connection.\n*/\nSQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){\n  int i;\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Db *pDb = &db->aDb[i];\n    if( pDb->pSchema ){\n      sqlite3SchemaClear(pDb->pSchema);\n    }\n  }\n  db->flags &= ~SQLITE_InternChanges;\n  sqlite3VtabUnlockList(db);\n  sqlite3BtreeLeaveAll(db);\n  sqlite3CollapseDatabaseArray(db);\n}\n\n/*\n** This routine is called when a commit occurs.\n*/\nSQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){\n  db->flags &= ~SQLITE_InternChanges;\n}\n\n/*\n** Delete memory allocated for the column names of a table or view (the\n** Table.aCol[] array).\n*/\nstatic void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){\n  int i;\n  Column *pCol;\n  assert( pTable!=0 );\n  if( (pCol = pTable->aCol)!=0 ){\n    for(i=0; i<pTable->nCol; i++, pCol++){\n      sqlite3DbFree(db, pCol->zName);\n      sqlite3ExprDelete(db, pCol->pDflt);\n      sqlite3DbFree(db, pCol->zDflt);\n      sqlite3DbFree(db, pCol->zType);\n      sqlite3DbFree(db, pCol->zColl);\n    }\n    sqlite3DbFree(db, pTable->aCol);\n  }\n}\n\n/*\n** Remove the memory data structures associated with the given\n** Table.  No changes are made to disk by this routine.\n**\n** This routine just deletes the data structure.  It does not unlink\n** the table data structure from the hash table.  But it does destroy\n** memory structures of the indices and foreign keys associated with \n** the table.\n**\n** The db parameter is optional.  It is needed if the Table object \n** contains lookaside memory.  (Table objects in the schema do not use\n** lookaside memory, but some ephemeral Table objects do.)  Or the\n** db parameter can be used with db->pnBytesFreed to measure the memory\n** used by the Table object.\n*/\nSQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){\n  Index *pIndex, *pNext;\n  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */\n\n  assert( !pTable || pTable->nRef>0 );\n\n  /* Do not delete the table until the reference count reaches zero. */\n  if( !pTable ) return;\n  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;\n\n  /* Record the number of outstanding lookaside allocations in schema Tables\n  ** prior to doing any free() operations.  Since schema Tables do not use\n  ** lookaside, this number should not change. */\n  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?\n                         db->lookaside.nOut : 0 );\n\n  /* Delete all indices associated with this table. */\n  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){\n    pNext = pIndex->pNext;\n    assert( pIndex->pSchema==pTable->pSchema );\n    if( !db || db->pnBytesFreed==0 ){\n      char *zName = pIndex->zName; \n      TESTONLY ( Index *pOld = ) sqlite3HashInsert(\n         &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0\n      );\n      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );\n      assert( pOld==pIndex || pOld==0 );\n    }\n    freeIndex(db, pIndex);\n  }\n\n  /* Delete any foreign keys attached to this table. */\n  sqlite3FkDelete(db, pTable);\n\n  /* Delete the Table structure itself.\n  */\n  sqliteDeleteColumnNames(db, pTable);\n  sqlite3DbFree(db, pTable->zName);\n  sqlite3DbFree(db, pTable->zColAff);\n  sqlite3SelectDelete(db, pTable->pSelect);\n#ifndef SQLITE_OMIT_CHECK\n  sqlite3ExprListDelete(db, pTable->pCheck);\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3VtabClear(db, pTable);\n#endif\n  sqlite3DbFree(db, pTable);\n\n  /* Verify that no lookaside memory was used by schema tables */\n  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );\n}\n\n/*\n** Unlink the given table from the hash tables and the delete the\n** table structure with all its indices and foreign keys.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){\n  Table *p;\n  Db *pDb;\n\n  assert( db!=0 );\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( zTabName );\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */\n  pDb = &db->aDb[iDb];\n  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,\n                        sqlite3Strlen30(zTabName),0);\n  sqlite3DeleteTable(db, p);\n  db->flags |= SQLITE_InternChanges;\n}\n\n/*\n** Given a token, return a string that consists of the text of that\n** token.  Space to hold the returned string\n** is obtained from sqliteMalloc() and must be freed by the calling\n** function.\n**\n** Any quotation marks (ex:  \"name\", 'name', [name], or `name`) that\n** surround the body of the token are removed.\n**\n** Tokens are often just pointers into the original SQL text and so\n** are not \\000 terminated and are not persistent.  The returned string\n** is \\000 terminated and is persistent.\n*/\nSQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){\n  char *zName;\n  if( pName ){\n    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);\n    sqlite3Dequote(zName);\n  }else{\n    zName = 0;\n  }\n  return zName;\n}\n\n/*\n** Open the sqlite_master table stored in database number iDb for\n** writing. The table is opened using cursor 0.\n*/\nSQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){\n  Vdbe *v = sqlite3GetVdbe(p);\n  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));\n  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);\n  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */\n  if( p->nTab==0 ){\n    p->nTab = 1;\n  }\n}\n\n/*\n** Parameter zName points to a nul-terminated buffer containing the name\n** of a database (\"main\", \"temp\" or the name of an attached db). This\n** function returns the index of the named database in db->aDb[], or\n** -1 if the named db cannot be found.\n*/\nSQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){\n  int i = -1;         /* Database number */\n  if( zName ){\n    Db *pDb;\n    int n = sqlite3Strlen30(zName);\n    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){\n      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && \n          0==sqlite3StrICmp(pDb->zName, zName) ){\n        break;\n      }\n    }\n  }\n  return i;\n}\n\n/*\n** The token *pName contains the name of a database (either \"main\" or\n** \"temp\" or the name of an attached db). This routine returns the\n** index of the named database in db->aDb[], or -1 if the named db \n** does not exist.\n*/\nSQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){\n  int i;                               /* Database number */\n  char *zName;                         /* Name we are searching for */\n  zName = sqlite3NameFromToken(db, pName);\n  i = sqlite3FindDbName(db, zName);\n  sqlite3DbFree(db, zName);\n  return i;\n}\n\n/* The table or view or trigger name is passed to this routine via tokens\n** pName1 and pName2. If the table name was fully qualified, for example:\n**\n** CREATE TABLE xxx.yyy (...);\n** \n** Then pName1 is set to \"xxx\" and pName2 \"yyy\". On the other hand if\n** the table name is not fully qualified, i.e.:\n**\n** CREATE TABLE yyy(...);\n**\n** Then pName1 is set to \"yyy\" and pName2 is \"\".\n**\n** This routine sets the *ppUnqual pointer to point at the token (pName1 or\n** pName2) that stores the unqualified table name.  The index of the\n** database \"xxx\" is returned.\n*/\nSQLITE_PRIVATE int sqlite3TwoPartName(\n  Parse *pParse,      /* Parsing and code generating context */\n  Token *pName1,      /* The \"xxx\" in the name \"xxx.yyy\" or \"xxx\" */\n  Token *pName2,      /* The \"yyy\" in the name \"xxx.yyy\" */\n  Token **pUnqual     /* Write the unqualified object name here */\n){\n  int iDb;                    /* Database holding the object */\n  sqlite3 *db = pParse->db;\n\n  if( ALWAYS(pName2!=0) && pName2->n>0 ){\n    if( db->init.busy ) {\n      sqlite3ErrorMsg(pParse, \"corrupt database\");\n      pParse->nErr++;\n      return -1;\n    }\n    *pUnqual = pName2;\n    iDb = sqlite3FindDb(db, pName1);\n    if( iDb<0 ){\n      sqlite3ErrorMsg(pParse, \"unknown database %T\", pName1);\n      pParse->nErr++;\n      return -1;\n    }\n  }else{\n    assert( db->init.iDb==0 || db->init.busy );\n    iDb = db->init.iDb;\n    *pUnqual = pName1;\n  }\n  return iDb;\n}\n\n/*\n** This routine is used to check if the UTF-8 string zName is a legal\n** unqualified name for a new schema object (table, index, view or\n** trigger). All names are legal except those that begin with the string\n** \"sqlite_\" (in upper, lower or mixed case). This portion of the namespace\n** is reserved for internal use.\n*/\nSQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){\n  if( !pParse->db->init.busy && pParse->nested==0 \n          && (pParse->db->flags & SQLITE_WriteSchema)==0\n          && 0==sqlite3StrNICmp(zName, \"sqlite_\", 7) ){\n    sqlite3ErrorMsg(pParse, \"object name reserved for internal use: %s\", zName);\n    return SQLITE_ERROR;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Begin constructing a new table representation in memory.  This is\n** the first of several action routines that get called in response\n** to a CREATE TABLE statement.  In particular, this routine is called\n** after seeing tokens \"CREATE\" and \"TABLE\" and the table name. The isTemp\n** flag is true if the table should be stored in the auxiliary database\n** file instead of in the main database file.  This is normally the case\n** when the \"TEMP\" or \"TEMPORARY\" keyword occurs in between\n** CREATE and TABLE.\n**\n** The new table record is initialized and put in pParse->pNewTable.\n** As more of the CREATE TABLE statement is parsed, additional action\n** routines will be called to add more information to this record.\n** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine\n** is called to complete the construction of the new table record.\n*/\nSQLITE_PRIVATE void sqlite3StartTable(\n  Parse *pParse,   /* Parser context */\n  Token *pName1,   /* First part of the name of the table or view */\n  Token *pName2,   /* Second part of the name of the table or view */\n  int isTemp,      /* True if this is a TEMP table */\n  int isView,      /* True if this is a VIEW */\n  int isVirtual,   /* True if this is a VIRTUAL table */\n  int noErr        /* Do nothing if table already exists */\n){\n  Table *pTable;\n  char *zName = 0; /* The name of the new table */\n  sqlite3 *db = pParse->db;\n  Vdbe *v;\n  int iDb;         /* Database number to create the table in */\n  Token *pName;    /* Unqualified name of the table to create */\n\n  /* The table or view name to create is passed to this routine via tokens\n  ** pName1 and pName2. If the table name was fully qualified, for example:\n  **\n  ** CREATE TABLE xxx.yyy (...);\n  ** \n  ** Then pName1 is set to \"xxx\" and pName2 \"yyy\". On the other hand if\n  ** the table name is not fully qualified, i.e.:\n  **\n  ** CREATE TABLE yyy(...);\n  **\n  ** Then pName1 is set to \"yyy\" and pName2 is \"\".\n  **\n  ** The call below sets the pName pointer to point at the token (pName1 or\n  ** pName2) that stores the unqualified table name. The variable iDb is\n  ** set to the index of the database that the table or view is to be\n  ** created in.\n  */\n  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n  if( iDb<0 ) return;\n  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){\n    /* If creating a temp table, the name may not be qualified. Unless \n    ** the database name is \"temp\" anyway.  */\n    sqlite3ErrorMsg(pParse, \"temporary table name must be unqualified\");\n    return;\n  }\n  if( !OMIT_TEMPDB && isTemp ) iDb = 1;\n\n  pParse->sNameToken = *pName;\n  zName = sqlite3NameFromToken(db, pName);\n  if( zName==0 ) return;\n  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){\n    goto begin_table_error;\n  }\n  if( db->init.iDb==1 ) isTemp = 1;\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  assert( (isTemp & 1)==isTemp );\n  {\n    int code;\n    char *zDb = db->aDb[iDb].zName;\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){\n      goto begin_table_error;\n    }\n    if( isView ){\n      if( !OMIT_TEMPDB && isTemp ){\n        code = SQLITE_CREATE_TEMP_VIEW;\n      }else{\n        code = SQLITE_CREATE_VIEW;\n      }\n    }else{\n      if( !OMIT_TEMPDB && isTemp ){\n        code = SQLITE_CREATE_TEMP_TABLE;\n      }else{\n        code = SQLITE_CREATE_TABLE;\n      }\n    }\n    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){\n      goto begin_table_error;\n    }\n  }\n#endif\n\n  /* Make sure the new table name does not collide with an existing\n  ** index or table name in the same database.  Issue an error message if\n  ** it does. The exception is if the statement being parsed was passed\n  ** to an sqlite3_declare_vtab() call. In that case only the column names\n  ** and types will be used, so there is no need to test for namespace\n  ** collisions.\n  */\n  if( !IN_DECLARE_VTAB ){\n    char *zDb = db->aDb[iDb].zName;\n    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n      goto begin_table_error;\n    }\n    pTable = sqlite3FindTable(db, zName, zDb);\n    if( pTable ){\n      if( !noErr ){\n        sqlite3ErrorMsg(pParse, \"table %T already exists\", pName);\n      }else{\n        assert( !db->init.busy );\n        sqlite3CodeVerifySchema(pParse, iDb);\n      }\n      goto begin_table_error;\n    }\n    if( sqlite3FindIndex(db, zName, zDb)!=0 ){\n      sqlite3ErrorMsg(pParse, \"there is already an index named %s\", zName);\n      goto begin_table_error;\n    }\n  }\n\n  pTable = sqlite3DbMallocZero(db, sizeof(Table));\n  if( pTable==0 ){\n    db->mallocFailed = 1;\n    pParse->rc = SQLITE_NOMEM;\n    pParse->nErr++;\n    goto begin_table_error;\n  }\n  pTable->zName = zName;\n  pTable->iPKey = -1;\n  pTable->pSchema = db->aDb[iDb].pSchema;\n  pTable->nRef = 1;\n  pTable->nRowEst = 1000000;\n  assert( pParse->pNewTable==0 );\n  pParse->pNewTable = pTable;\n\n  /* If this is the magic sqlite_sequence table used by autoincrement,\n  ** then record a pointer to this table in the main database structure\n  ** so that INSERT can find the table easily.\n  */\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  if( !pParse->nested && strcmp(zName, \"sqlite_sequence\")==0 ){\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    pTable->pSchema->pSeqTab = pTable;\n  }\n#endif\n\n  /* Begin generating the code that will insert the table record into\n  ** the SQLITE_MASTER table.  Note in particular that we must go ahead\n  ** and allocate the record number for the table entry now.  Before any\n  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause\n  ** indices to be created and the table record must come before the \n  ** indices.  Hence, the record number for the table must be allocated\n  ** now.\n  */\n  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){\n    int j1;\n    int fileFormat;\n    int reg1, reg2, reg3;\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( isVirtual ){\n      sqlite3VdbeAddOp0(v, OP_VBegin);\n    }\n#endif\n\n    /* If the file format and encoding in the database have not been set, \n    ** set them now.\n    */\n    reg1 = pParse->regRowid = ++pParse->nMem;\n    reg2 = pParse->regRoot = ++pParse->nMem;\n    reg3 = ++pParse->nMem;\n    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);\n    sqlite3VdbeUsesBtree(v, iDb);\n    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);\n    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?\n                  1 : SQLITE_MAX_FILE_FORMAT;\n    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);\n    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);\n    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);\n    sqlite3VdbeJumpHere(v, j1);\n\n    /* This just creates a place-holder record in the sqlite_master table.\n    ** The record created does not contain anything yet.  It will be replaced\n    ** by the real entry in code generated at sqlite3EndTable().\n    **\n    ** The rowid for the new entry is left in register pParse->regRowid.\n    ** The root page number of the new table is left in reg pParse->regRoot.\n    ** The rowid and root page number values are needed by the code that\n    ** sqlite3EndTable will generate.\n    */\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n    if( isView || isVirtual ){\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);\n    }else\n#endif\n    {\n      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);\n    }\n    sqlite3OpenMasterTable(pParse, iDb);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);\n    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);\n    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n    sqlite3VdbeAddOp0(v, OP_Close);\n  }\n\n  /* Normal (non-error) return. */\n  return;\n\n  /* If an error occurs, we jump here */\nbegin_table_error:\n  sqlite3DbFree(db, zName);\n  return;\n}\n\n/*\n** This macro is used to compare two strings in a case-insensitive manner.\n** It is slightly faster than calling sqlite3StrICmp() directly, but\n** produces larger code.\n**\n** WARNING: This macro is not compatible with the strcmp() family. It\n** returns true if the two strings are equal, otherwise false.\n*/\n#define STRICMP(x, y) (\\\nsqlite3UpperToLower[*(unsigned char *)(x)]==   \\\nsqlite3UpperToLower[*(unsigned char *)(y)]     \\\n&& sqlite3StrICmp((x)+1,(y)+1)==0 )\n\n/*\n** Add a new column to the table currently being constructed.\n**\n** The parser calls this routine once for each column declaration\n** in a CREATE TABLE statement.  sqlite3StartTable() gets called\n** first to get things going.  Then this routine is called for each\n** column.\n*/\nSQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){\n  Table *p;\n  int i;\n  char *z;\n  Column *pCol;\n  sqlite3 *db = pParse->db;\n  if( (p = pParse->pNewTable)==0 ) return;\n#if SQLITE_MAX_COLUMN\n  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many columns on %s\", p->zName);\n    return;\n  }\n#endif\n  z = sqlite3NameFromToken(db, pName);\n  if( z==0 ) return;\n  for(i=0; i<p->nCol; i++){\n    if( STRICMP(z, p->aCol[i].zName) ){\n      sqlite3ErrorMsg(pParse, \"duplicate column name: %s\", z);\n      sqlite3DbFree(db, z);\n      return;\n    }\n  }\n  if( (p->nCol & 0x7)==0 ){\n    Column *aNew;\n    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));\n    if( aNew==0 ){\n      sqlite3DbFree(db, z);\n      return;\n    }\n    p->aCol = aNew;\n  }\n  pCol = &p->aCol[p->nCol];\n  memset(pCol, 0, sizeof(p->aCol[0]));\n  pCol->zName = z;\n \n  /* If there is no type specified, columns have the default affinity\n  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will\n  ** be called next to set pCol->affinity correctly.\n  */\n  pCol->affinity = SQLITE_AFF_NONE;\n  p->nCol++;\n}\n\n/*\n** This routine is called by the parser while in the middle of\n** parsing a CREATE TABLE statement.  A \"NOT NULL\" constraint has\n** been seen on a column.  This routine sets the notNull flag on\n** the column currently under construction.\n*/\nSQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){\n  Table *p;\n  p = pParse->pNewTable;\n  if( p==0 || NEVER(p->nCol<1) ) return;\n  p->aCol[p->nCol-1].notNull = (u8)onError;\n}\n\n/*\n** Scan the column type name zType (length nType) and return the\n** associated affinity type.\n**\n** This routine does a case-independent search of zType for the \n** substrings in the following table. If one of the substrings is\n** found, the corresponding affinity is returned. If zType contains\n** more than one of the substrings, entries toward the top of \n** the table take priority. For example, if zType is 'BLOBINT', \n** SQLITE_AFF_INTEGER is returned.\n**\n** Substring     | Affinity\n** --------------------------------\n** 'INT'         | SQLITE_AFF_INTEGER\n** 'CHAR'        | SQLITE_AFF_TEXT\n** 'CLOB'        | SQLITE_AFF_TEXT\n** 'TEXT'        | SQLITE_AFF_TEXT\n** 'BLOB'        | SQLITE_AFF_NONE\n** 'REAL'        | SQLITE_AFF_REAL\n** 'FLOA'        | SQLITE_AFF_REAL\n** 'DOUB'        | SQLITE_AFF_REAL\n**\n** If none of the substrings in the above table are found,\n** SQLITE_AFF_NUMERIC is returned.\n*/\nSQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){\n  u32 h = 0;\n  char aff = SQLITE_AFF_NUMERIC;\n\n  if( zIn ) while( zIn[0] ){\n    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];\n    zIn++;\n    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */\n      aff = SQLITE_AFF_TEXT; \n    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */\n      aff = SQLITE_AFF_TEXT;\n    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */\n      aff = SQLITE_AFF_TEXT;\n    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */\n        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){\n      aff = SQLITE_AFF_NONE;\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */\n        && aff==SQLITE_AFF_NUMERIC ){\n      aff = SQLITE_AFF_REAL;\n#endif\n    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */\n      aff = SQLITE_AFF_INTEGER;\n      break;\n    }\n  }\n\n  return aff;\n}\n\n/*\n** This routine is called by the parser while in the middle of\n** parsing a CREATE TABLE statement.  The pFirst token is the first\n** token in the sequence of tokens that describe the type of the\n** column currently under construction.   pLast is the last token\n** in the sequence.  Use this information to construct a string\n** that contains the typename of the column and store that string\n** in zType.\n*/ \nSQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){\n  Table *p;\n  Column *pCol;\n\n  p = pParse->pNewTable;\n  if( p==0 || NEVER(p->nCol<1) ) return;\n  pCol = &p->aCol[p->nCol-1];\n  assert( pCol->zType==0 );\n  pCol->zType = sqlite3NameFromToken(pParse->db, pType);\n  pCol->affinity = sqlite3AffinityType(pCol->zType);\n}\n\n/*\n** The expression is the default value for the most recently added column\n** of the table currently under construction.\n**\n** Default value expressions must be constant.  Raise an exception if this\n** is not the case.\n**\n** This routine is called by the parser while in the middle of\n** parsing a CREATE TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){\n  Table *p;\n  Column *pCol;\n  sqlite3 *db = pParse->db;\n  p = pParse->pNewTable;\n  if( p!=0 ){\n    pCol = &(p->aCol[p->nCol-1]);\n    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){\n      sqlite3ErrorMsg(pParse, \"default value of column [%s] is not constant\",\n          pCol->zName);\n    }else{\n      /* A copy of pExpr is used instead of the original, as pExpr contains\n      ** tokens that point to volatile memory. The 'span' of the expression\n      ** is required by pragma table_info.\n      */\n      sqlite3ExprDelete(db, pCol->pDflt);\n      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);\n      sqlite3DbFree(db, pCol->zDflt);\n      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,\n                                     (int)(pSpan->zEnd - pSpan->zStart));\n    }\n  }\n  sqlite3ExprDelete(db, pSpan->pExpr);\n}\n\n/*\n** Designate the PRIMARY KEY for the table.  pList is a list of names \n** of columns that form the primary key.  If pList is NULL, then the\n** most recently added column of the table is the primary key.\n**\n** A table can have at most one primary key.  If the table already has\n** a primary key (and this is the second primary key) then create an\n** error.\n**\n** If the PRIMARY KEY is on a single column whose datatype is INTEGER,\n** then we will try to use that column as the rowid.  Set the Table.iPKey\n** field of the table under construction to be the index of the\n** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is\n** no INTEGER PRIMARY KEY.\n**\n** If the key is not an INTEGER PRIMARY KEY, then create a unique\n** index for the key.  No index is created for INTEGER PRIMARY KEYs.\n*/\nSQLITE_PRIVATE void sqlite3AddPrimaryKey(\n  Parse *pParse,    /* Parsing context */\n  ExprList *pList,  /* List of field names to be indexed */\n  int onError,      /* What to do with a uniqueness conflict */\n  int autoInc,      /* True if the AUTOINCREMENT keyword is present */\n  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */\n){\n  Table *pTab = pParse->pNewTable;\n  char *zType = 0;\n  int iCol = -1, i;\n  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;\n  if( pTab->tabFlags & TF_HasPrimaryKey ){\n    sqlite3ErrorMsg(pParse, \n      \"table \\\"%s\\\" has more than one primary key\", pTab->zName);\n    goto primary_key_exit;\n  }\n  pTab->tabFlags |= TF_HasPrimaryKey;\n  if( pList==0 ){\n    iCol = pTab->nCol - 1;\n    pTab->aCol[iCol].isPrimKey = 1;\n  }else{\n    for(i=0; i<pList->nExpr; i++){\n      for(iCol=0; iCol<pTab->nCol; iCol++){\n        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){\n          break;\n        }\n      }\n      if( iCol<pTab->nCol ){\n        pTab->aCol[iCol].isPrimKey = 1;\n      }\n    }\n    if( pList->nExpr>1 ) iCol = -1;\n  }\n  if( iCol>=0 && iCol<pTab->nCol ){\n    zType = pTab->aCol[iCol].zType;\n  }\n  if( zType && sqlite3StrICmp(zType, \"INTEGER\")==0\n        && sortOrder==SQLITE_SO_ASC ){\n    pTab->iPKey = iCol;\n    pTab->keyConf = (u8)onError;\n    assert( autoInc==0 || autoInc==1 );\n    pTab->tabFlags |= autoInc*TF_Autoincrement;\n  }else if( autoInc ){\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n    sqlite3ErrorMsg(pParse, \"AUTOINCREMENT is only allowed on an \"\n       \"INTEGER PRIMARY KEY\");\n#endif\n  }else{\n    Index *p;\n    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);\n    if( p ){\n      p->autoIndex = 2;\n    }\n    pList = 0;\n  }\n\nprimary_key_exit:\n  sqlite3ExprListDelete(pParse->db, pList);\n  return;\n}\n\n/*\n** Add a new CHECK constraint to the table currently under construction.\n*/\nSQLITE_PRIVATE void sqlite3AddCheckConstraint(\n  Parse *pParse,    /* Parsing context */\n  Expr *pCheckExpr  /* The check expression */\n){\n#ifndef SQLITE_OMIT_CHECK\n  Table *pTab = pParse->pNewTable;\n  if( pTab && !IN_DECLARE_VTAB ){\n    pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);\n    if( pParse->constraintName.n ){\n      sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);\n    }\n  }else\n#endif\n  {\n    sqlite3ExprDelete(pParse->db, pCheckExpr);\n  }\n}\n\n/*\n** Set the collation function of the most recently parsed table column\n** to the CollSeq given.\n*/\nSQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){\n  Table *p;\n  int i;\n  char *zColl;              /* Dequoted name of collation sequence */\n  sqlite3 *db;\n\n  if( (p = pParse->pNewTable)==0 ) return;\n  i = p->nCol-1;\n  db = pParse->db;\n  zColl = sqlite3NameFromToken(db, pToken);\n  if( !zColl ) return;\n\n  if( sqlite3LocateCollSeq(pParse, zColl) ){\n    Index *pIdx;\n    p->aCol[i].zColl = zColl;\n  \n    /* If the column is declared as \"<name> PRIMARY KEY COLLATE <type>\",\n    ** then an index may have been created on this column before the\n    ** collation type was added. Correct this if it is the case.\n    */\n    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){\n      assert( pIdx->nColumn==1 );\n      if( pIdx->aiColumn[0]==i ){\n        pIdx->azColl[0] = p->aCol[i].zColl;\n      }\n    }\n  }else{\n    sqlite3DbFree(db, zColl);\n  }\n}\n\n/*\n** This function returns the collation sequence for database native text\n** encoding identified by the string zName, length nName.\n**\n** If the requested collation sequence is not available, or not available\n** in the database native encoding, the collation factory is invoked to\n** request it. If the collation factory does not supply such a sequence,\n** and the sequence is available in another text encoding, then that is\n** returned instead.\n**\n** If no versions of the requested collations sequence are available, or\n** another error occurs, NULL is returned and an error message written into\n** pParse.\n**\n** This routine is a wrapper around sqlite3FindCollSeq().  This routine\n** invokes the collation factory if the named collation cannot be found\n** and generates an error message.\n**\n** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){\n  sqlite3 *db = pParse->db;\n  u8 enc = ENC(db);\n  u8 initbusy = db->init.busy;\n  CollSeq *pColl;\n\n  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);\n  if( !initbusy && (!pColl || !pColl->xCmp) ){\n    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);\n    if( !pColl ){\n      sqlite3ErrorMsg(pParse, \"no such collation sequence: %s\", zName);\n    }\n  }\n\n  return pColl;\n}\n\n\n/*\n** Generate code that will increment the schema cookie.\n**\n** The schema cookie is used to determine when the schema for the\n** database changes.  After each schema change, the cookie value\n** changes.  When a process first reads the schema it records the\n** cookie.  Thereafter, whenever it goes to access the database,\n** it checks the cookie to make sure the schema has not changed\n** since it was last read.\n**\n** This plan is not completely bullet-proof.  It is possible for\n** the schema to change multiple times and for the cookie to be\n** set back to prior value.  But schema changes are infrequent\n** and the probability of hitting the same cookie value is only\n** 1 chance in 2^32.  So we're safe enough.\n*/\nSQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){\n  int r1 = sqlite3GetTempReg(pParse);\n  sqlite3 *db = pParse->db;\n  Vdbe *v = pParse->pVdbe;\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);\n  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);\n  sqlite3ReleaseTempReg(pParse, r1);\n}\n\n/*\n** Measure the number of characters needed to output the given\n** identifier.  The number returned includes any quotes used\n** but does not include the null terminator.\n**\n** The estimate is conservative.  It might be larger that what is\n** really needed.\n*/\nstatic int identLength(const char *z){\n  int n;\n  for(n=0; *z; n++, z++){\n    if( *z=='\"' ){ n++; }\n  }\n  return n + 2;\n}\n\n/*\n** The first parameter is a pointer to an output buffer. The second \n** parameter is a pointer to an integer that contains the offset at\n** which to write into the output buffer. This function copies the\n** nul-terminated string pointed to by the third parameter, zSignedIdent,\n** to the specified offset in the buffer and updates *pIdx to refer\n** to the first byte after the last byte written before returning.\n** \n** If the string zSignedIdent consists entirely of alpha-numeric\n** characters, does not begin with a digit and is not an SQL keyword,\n** then it is copied to the output buffer exactly as it is. Otherwise,\n** it is quoted using double-quotes.\n*/\nstatic void identPut(char *z, int *pIdx, char *zSignedIdent){\n  unsigned char *zIdent = (unsigned char*)zSignedIdent;\n  int i, j, needQuote;\n  i = *pIdx;\n\n  for(j=0; zIdent[j]; j++){\n    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;\n  }\n  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;\n  if( !needQuote ){\n    needQuote = zIdent[j];\n  }\n\n  if( needQuote ) z[i++] = '\"';\n  for(j=0; zIdent[j]; j++){\n    z[i++] = zIdent[j];\n    if( zIdent[j]=='\"' ) z[i++] = '\"';\n  }\n  if( needQuote ) z[i++] = '\"';\n  z[i] = 0;\n  *pIdx = i;\n}\n\n/*\n** Generate a CREATE TABLE statement appropriate for the given\n** table.  Memory to hold the text of the statement is obtained\n** from sqliteMalloc() and must be freed by the calling function.\n*/\nstatic char *createTableStmt(sqlite3 *db, Table *p){\n  int i, k, n;\n  char *zStmt;\n  char *zSep, *zSep2, *zEnd;\n  Column *pCol;\n  n = 0;\n  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){\n    n += identLength(pCol->zName) + 5;\n  }\n  n += identLength(p->zName);\n  if( n<50 ){ \n    zSep = \"\";\n    zSep2 = \",\";\n    zEnd = \")\";\n  }else{\n    zSep = \"\\n  \";\n    zSep2 = \",\\n  \";\n    zEnd = \"\\n)\";\n  }\n  n += 35 + 6*p->nCol;\n  zStmt = sqlite3DbMallocRaw(0, n);\n  if( zStmt==0 ){\n    db->mallocFailed = 1;\n    return 0;\n  }\n  sqlite3_snprintf(n, zStmt, \"CREATE TABLE \");\n  k = sqlite3Strlen30(zStmt);\n  identPut(zStmt, &k, p->zName);\n  zStmt[k++] = '(';\n  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){\n    static const char * const azType[] = {\n        /* SQLITE_AFF_TEXT    */ \" TEXT\",\n        /* SQLITE_AFF_NONE    */ \"\",\n        /* SQLITE_AFF_NUMERIC */ \" NUM\",\n        /* SQLITE_AFF_INTEGER */ \" INT\",\n        /* SQLITE_AFF_REAL    */ \" REAL\"\n    };\n    int len;\n    const char *zType;\n\n    sqlite3_snprintf(n-k, &zStmt[k], zSep);\n    k += sqlite3Strlen30(&zStmt[k]);\n    zSep = zSep2;\n    identPut(zStmt, &k, pCol->zName);\n    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );\n    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );\n    testcase( pCol->affinity==SQLITE_AFF_TEXT );\n    testcase( pCol->affinity==SQLITE_AFF_NONE );\n    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );\n    testcase( pCol->affinity==SQLITE_AFF_INTEGER );\n    testcase( pCol->affinity==SQLITE_AFF_REAL );\n    \n    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];\n    len = sqlite3Strlen30(zType);\n    assert( pCol->affinity==SQLITE_AFF_NONE \n            || pCol->affinity==sqlite3AffinityType(zType) );\n    memcpy(&zStmt[k], zType, len);\n    k += len;\n    assert( k<=n );\n  }\n  sqlite3_snprintf(n-k, &zStmt[k], \"%s\", zEnd);\n  return zStmt;\n}\n\n/*\n** This routine is called to report the final \")\" that terminates\n** a CREATE TABLE statement.\n**\n** The table structure that other action routines have been building\n** is added to the internal hash tables, assuming no errors have\n** occurred.\n**\n** An entry for the table is made in the master table on disk, unless\n** this is a temporary table or db->init.busy==1.  When db->init.busy==1\n** it means we are reading the sqlite_master table because we just\n** connected to the database or because the sqlite_master table has\n** recently changed, so the entry for this table already exists in\n** the sqlite_master table.  We do not want to create it again.\n**\n** If the pSelect argument is not NULL, it means that this routine\n** was called to create a table generated from a \n** \"CREATE TABLE ... AS SELECT ...\" statement.  The column names of\n** the new table will match the result set of the SELECT.\n*/\nSQLITE_PRIVATE void sqlite3EndTable(\n  Parse *pParse,          /* Parse context */\n  Token *pCons,           /* The ',' token after the last column defn. */\n  Token *pEnd,            /* The final ')' token in the CREATE TABLE */\n  Select *pSelect         /* Select from a \"CREATE ... AS SELECT\" */\n){\n  Table *p;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){\n    return;\n  }\n  p = pParse->pNewTable;\n  if( p==0 ) return;\n\n  assert( !db->init.busy || !pSelect );\n\n  iDb = sqlite3SchemaToIndex(db, p->pSchema);\n\n#ifndef SQLITE_OMIT_CHECK\n  /* Resolve names in all CHECK constraint expressions.\n  */\n  if( p->pCheck ){\n    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */\n    NameContext sNC;                /* Name context for pParse->pNewTable */\n    ExprList *pList;                /* List of all CHECK constraints */\n    int i;                          /* Loop counter */\n\n    memset(&sNC, 0, sizeof(sNC));\n    memset(&sSrc, 0, sizeof(sSrc));\n    sSrc.nSrc = 1;\n    sSrc.a[0].zName = p->zName;\n    sSrc.a[0].pTab = p;\n    sSrc.a[0].iCursor = -1;\n    sNC.pParse = pParse;\n    sNC.pSrcList = &sSrc;\n    sNC.ncFlags = NC_IsCheck;\n    pList = p->pCheck;\n    for(i=0; i<pList->nExpr; i++){\n      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){\n        return;\n      }\n    }\n  }\n#endif /* !defined(SQLITE_OMIT_CHECK) */\n\n  /* If the db->init.busy is 1 it means we are reading the SQL off the\n  ** \"sqlite_master\" or \"sqlite_temp_master\" table on the disk.\n  ** So do not write to the disk again.  Extract the root page number\n  ** for the table from the db->init.newTnum field.  (The page number\n  ** should have been put there by the sqliteOpenCb routine.)\n  */\n  if( db->init.busy ){\n    p->tnum = db->init.newTnum;\n  }\n\n  /* If not initializing, then create a record for the new table\n  ** in the SQLITE_MASTER table of the database.\n  **\n  ** If this is a TEMPORARY table, write the entry into the auxiliary\n  ** file instead of into the main database file.\n  */\n  if( !db->init.busy ){\n    int n;\n    Vdbe *v;\n    char *zType;    /* \"view\" or \"table\" */\n    char *zType2;   /* \"VIEW\" or \"TABLE\" */\n    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */\n\n    v = sqlite3GetVdbe(pParse);\n    if( NEVER(v==0) ) return;\n\n    sqlite3VdbeAddOp1(v, OP_Close, 0);\n\n    /* \n    ** Initialize zType for the new view or table.\n    */\n    if( p->pSelect==0 ){\n      /* A regular table */\n      zType = \"table\";\n      zType2 = \"TABLE\";\n#ifndef SQLITE_OMIT_VIEW\n    }else{\n      /* A view */\n      zType = \"view\";\n      zType2 = \"VIEW\";\n#endif\n    }\n\n    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT\n    ** statement to populate the new table. The root-page number for the\n    ** new table is in register pParse->regRoot.\n    **\n    ** Once the SELECT has been coded by sqlite3Select(), it is in a\n    ** suitable state to query for the column names and types to be used\n    ** by the new table.\n    **\n    ** A shared-cache write-lock is not required to write to the new table,\n    ** as a schema-lock must have already been obtained to create it. Since\n    ** a schema-lock excludes all other database users, the write-lock would\n    ** be redundant.\n    */\n    if( pSelect ){\n      SelectDest dest;\n      Table *pSelTab;\n\n      assert(pParse->nTab==1);\n      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);\n      sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);\n      pParse->nTab = 2;\n      sqlite3SelectDestInit(&dest, SRT_Table, 1);\n      sqlite3Select(pParse, pSelect, &dest);\n      sqlite3VdbeAddOp1(v, OP_Close, 1);\n      if( pParse->nErr==0 ){\n        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);\n        if( pSelTab==0 ) return;\n        assert( p->aCol==0 );\n        p->nCol = pSelTab->nCol;\n        p->aCol = pSelTab->aCol;\n        pSelTab->nCol = 0;\n        pSelTab->aCol = 0;\n        sqlite3DeleteTable(db, pSelTab);\n      }\n    }\n\n    /* Compute the complete text of the CREATE statement */\n    if( pSelect ){\n      zStmt = createTableStmt(db, p);\n    }else{\n      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;\n      zStmt = sqlite3MPrintf(db, \n          \"CREATE %s %.*s\", zType2, n, pParse->sNameToken.z\n      );\n    }\n\n    /* A slot for the record has already been allocated in the \n    ** SQLITE_MASTER table.  We just need to update that slot with all\n    ** the information we've collected.\n    */\n    sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s \"\n         \"SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q \"\n       \"WHERE rowid=#%d\",\n      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),\n      zType,\n      p->zName,\n      p->zName,\n      pParse->regRoot,\n      zStmt,\n      pParse->regRowid\n    );\n    sqlite3DbFree(db, zStmt);\n    sqlite3ChangeCookie(pParse, iDb);\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n    /* Check to see if we need to create an sqlite_sequence table for\n    ** keeping track of autoincrement keys.\n    */\n    if( p->tabFlags & TF_Autoincrement ){\n      Db *pDb = &db->aDb[iDb];\n      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n      if( pDb->pSchema->pSeqTab==0 ){\n        sqlite3NestedParse(pParse,\n          \"CREATE TABLE %Q.sqlite_sequence(name,seq)\",\n          pDb->zName\n        );\n      }\n    }\n#endif\n\n    /* Reparse everything to update our internal data structures */\n    sqlite3VdbeAddParseSchemaOp(v, iDb,\n               sqlite3MPrintf(db, \"tbl_name='%q'\", p->zName));\n  }\n\n\n  /* Add the table to the in-memory representation of the database.\n  */\n  if( db->init.busy ){\n    Table *pOld;\n    Schema *pSchema = p->pSchema;\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,\n                             sqlite3Strlen30(p->zName),p);\n    if( pOld ){\n      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */\n      db->mallocFailed = 1;\n      return;\n    }\n    pParse->pNewTable = 0;\n    db->flags |= SQLITE_InternChanges;\n\n#ifndef SQLITE_OMIT_ALTERTABLE\n    if( !p->pSelect ){\n      const char *zName = (const char *)pParse->sNameToken.z;\n      int nName;\n      assert( !pSelect && pCons && pEnd );\n      if( pCons->z==0 ){\n        pCons = pEnd;\n      }\n      nName = (int)((const char *)pCons->z - zName);\n      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);\n    }\n#endif\n  }\n}\n\n#ifndef SQLITE_OMIT_VIEW\n/*\n** The parser calls this routine in order to create a new VIEW\n*/\nSQLITE_PRIVATE void sqlite3CreateView(\n  Parse *pParse,     /* The parsing context */\n  Token *pBegin,     /* The CREATE token that begins the statement */\n  Token *pName1,     /* The token that holds the name of the view */\n  Token *pName2,     /* The token that holds the name of the view */\n  Select *pSelect,   /* A SELECT statement that will become the new view */\n  int isTemp,        /* TRUE for a TEMPORARY view */\n  int noErr          /* Suppress error messages if VIEW already exists */\n){\n  Table *p;\n  int n;\n  const char *z;\n  Token sEnd;\n  DbFixer sFix;\n  Token *pName = 0;\n  int iDb;\n  sqlite3 *db = pParse->db;\n\n  if( pParse->nVar>0 ){\n    sqlite3ErrorMsg(pParse, \"parameters are not allowed in views\");\n    sqlite3SelectDelete(db, pSelect);\n    return;\n  }\n  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);\n  p = pParse->pNewTable;\n  if( p==0 || pParse->nErr ){\n    sqlite3SelectDelete(db, pSelect);\n    return;\n  }\n  sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n  iDb = sqlite3SchemaToIndex(db, p->pSchema);\n  if( sqlite3FixInit(&sFix, pParse, iDb, \"view\", pName)\n    && sqlite3FixSelect(&sFix, pSelect)\n  ){\n    sqlite3SelectDelete(db, pSelect);\n    return;\n  }\n\n  /* Make a copy of the entire SELECT statement that defines the view.\n  ** This will force all the Expr.token.z values to be dynamically\n  ** allocated rather than point to the input string - which means that\n  ** they will persist after the current sqlite3_exec() call returns.\n  */\n  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n  sqlite3SelectDelete(db, pSelect);\n  if( db->mallocFailed ){\n    return;\n  }\n  if( !db->init.busy ){\n    sqlite3ViewGetColumnNames(pParse, p);\n  }\n\n  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to\n  ** the end.\n  */\n  sEnd = pParse->sLastToken;\n  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){\n    sEnd.z += sEnd.n;\n  }\n  sEnd.n = 0;\n  n = (int)(sEnd.z - pBegin->z);\n  z = pBegin->z;\n  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }\n  sEnd.z = &z[n-1];\n  sEnd.n = 1;\n\n  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */\n  sqlite3EndTable(pParse, 0, &sEnd, 0);\n  return;\n}\n#endif /* SQLITE_OMIT_VIEW */\n\n#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)\n/*\n** The Table structure pTable is really a VIEW.  Fill in the names of\n** the columns of the view in the pTable structure.  Return the number\n** of errors.  If an error is seen leave an error message in pParse->zErrMsg.\n*/\nSQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){\n  Table *pSelTab;   /* A fake table from which we get the result set */\n  Select *pSel;     /* Copy of the SELECT that implements the view */\n  int nErr = 0;     /* Number of errors encountered */\n  int n;            /* Temporarily holds the number of cursors assigned */\n  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);\n\n  assert( pTable );\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( sqlite3VtabCallConnect(pParse, pTable) ){\n    return SQLITE_ERROR;\n  }\n  if( IsVirtual(pTable) ) return 0;\n#endif\n\n#ifndef SQLITE_OMIT_VIEW\n  /* A positive nCol means the columns names for this view are\n  ** already known.\n  */\n  if( pTable->nCol>0 ) return 0;\n\n  /* A negative nCol is a special marker meaning that we are currently\n  ** trying to compute the column names.  If we enter this routine with\n  ** a negative nCol, it means two or more views form a loop, like this:\n  **\n  **     CREATE VIEW one AS SELECT * FROM two;\n  **     CREATE VIEW two AS SELECT * FROM one;\n  **\n  ** Actually, the error above is now caught prior to reaching this point.\n  ** But the following test is still important as it does come up\n  ** in the following:\n  ** \n  **     CREATE TABLE main.ex1(a);\n  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;\n  **     SELECT * FROM temp.ex1;\n  */\n  if( pTable->nCol<0 ){\n    sqlite3ErrorMsg(pParse, \"view %s is circularly defined\", pTable->zName);\n    return 1;\n  }\n  assert( pTable->nCol>=0 );\n\n  /* If we get this far, it means we need to compute the table names.\n  ** Note that the call to sqlite3ResultSetOfSelect() will expand any\n  ** \"*\" elements in the results set of the view and will assign cursors\n  ** to the elements of the FROM clause.  But we do not want these changes\n  ** to be permanent.  So the computation is done on a copy of the SELECT\n  ** statement that defines the view.\n  */\n  assert( pTable->pSelect );\n  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);\n  if( pSel ){\n    u8 enableLookaside = db->lookaside.bEnabled;\n    n = pParse->nTab;\n    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);\n    pTable->nCol = -1;\n    db->lookaside.bEnabled = 0;\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    xAuth = db->xAuth;\n    db->xAuth = 0;\n    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);\n    db->xAuth = xAuth;\n#else\n    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);\n#endif\n    db->lookaside.bEnabled = enableLookaside;\n    pParse->nTab = n;\n    if( pSelTab ){\n      assert( pTable->aCol==0 );\n      pTable->nCol = pSelTab->nCol;\n      pTable->aCol = pSelTab->aCol;\n      pSelTab->nCol = 0;\n      pSelTab->aCol = 0;\n      sqlite3DeleteTable(db, pSelTab);\n      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );\n      pTable->pSchema->flags |= DB_UnresetViews;\n    }else{\n      pTable->nCol = 0;\n      nErr++;\n    }\n    sqlite3SelectDelete(db, pSel);\n  } else {\n    nErr++;\n  }\n#endif /* SQLITE_OMIT_VIEW */\n  return nErr;  \n}\n#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */\n\n#ifndef SQLITE_OMIT_VIEW\n/*\n** Clear the column names from every VIEW in database idx.\n*/\nstatic void sqliteViewResetAll(sqlite3 *db, int idx){\n  HashElem *i;\n  assert( sqlite3SchemaMutexHeld(db, idx, 0) );\n  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;\n  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){\n    Table *pTab = sqliteHashData(i);\n    if( pTab->pSelect ){\n      sqliteDeleteColumnNames(db, pTab);\n      pTab->aCol = 0;\n      pTab->nCol = 0;\n    }\n  }\n  DbClearProperty(db, idx, DB_UnresetViews);\n}\n#else\n# define sqliteViewResetAll(A,B)\n#endif /* SQLITE_OMIT_VIEW */\n\n/*\n** This function is called by the VDBE to adjust the internal schema\n** used by SQLite when the btree layer moves a table root page. The\n** root-page of a table or index in database iDb has changed from iFrom\n** to iTo.\n**\n** Ticket #1728:  The symbol table might still contain information\n** on tables and/or indices that are the process of being deleted.\n** If you are unlucky, one of those deleted indices or tables might\n** have the same rootpage number as the real table or index that is\n** being moved.  So we cannot stop searching after the first match \n** because the first match might be for one of the deleted indices\n** or tables and not the table/index that is actually being moved.\n** We must continue looping until all tables and indices with\n** rootpage==iFrom have been converted to have a rootpage of iTo\n** in order to be certain that we got the right one.\n*/\n#ifndef SQLITE_OMIT_AUTOVACUUM\nSQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){\n  HashElem *pElem;\n  Hash *pHash;\n  Db *pDb;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pDb = &db->aDb[iDb];\n  pHash = &pDb->pSchema->tblHash;\n  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){\n    Table *pTab = sqliteHashData(pElem);\n    if( pTab->tnum==iFrom ){\n      pTab->tnum = iTo;\n    }\n  }\n  pHash = &pDb->pSchema->idxHash;\n  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){\n    Index *pIdx = sqliteHashData(pElem);\n    if( pIdx->tnum==iFrom ){\n      pIdx->tnum = iTo;\n    }\n  }\n}\n#endif\n\n/*\n** Write code to erase the table with root-page iTable from database iDb.\n** Also write code to modify the sqlite_master table and internal schema\n** if a root-page of another table is moved by the btree-layer whilst\n** erasing iTable (this can happen with an auto-vacuum database).\n*/ \nstatic void destroyRootPage(Parse *pParse, int iTable, int iDb){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int r1 = sqlite3GetTempReg(pParse);\n  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);\n  sqlite3MayAbort(pParse);\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  /* OP_Destroy stores an in integer r1. If this integer\n  ** is non-zero, then it is the root page number of a table moved to\n  ** location iTable. The following code modifies the sqlite_master table to\n  ** reflect this.\n  **\n  ** The \"#NNN\" in the SQL is a special constant that means whatever value\n  ** is in register NNN.  See grammar rules associated with the TK_REGISTER\n  ** token for additional information.\n  */\n  sqlite3NestedParse(pParse, \n     \"UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d\",\n     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);\n#endif\n  sqlite3ReleaseTempReg(pParse, r1);\n}\n\n/*\n** Write VDBE code to erase table pTab and all associated indices on disk.\n** Code to update the sqlite_master tables and internal schema definitions\n** in case a root-page belonging to another table is moved by the btree layer\n** is also added (this can happen with an auto-vacuum database).\n*/\nstatic void destroyTable(Parse *pParse, Table *pTab){\n#ifdef SQLITE_OMIT_AUTOVACUUM\n  Index *pIdx;\n  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  destroyRootPage(pParse, pTab->tnum, iDb);\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    destroyRootPage(pParse, pIdx->tnum, iDb);\n  }\n#else\n  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM\n  ** is not defined), then it is important to call OP_Destroy on the\n  ** table and index root-pages in order, starting with the numerically \n  ** largest root-page number. This guarantees that none of the root-pages\n  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the\n  ** following were coded:\n  **\n  ** OP_Destroy 4 0\n  ** ...\n  ** OP_Destroy 5 0\n  **\n  ** and root page 5 happened to be the largest root-page number in the\n  ** database, then root page 5 would be moved to page 4 by the \n  ** \"OP_Destroy 4 0\" opcode. The subsequent \"OP_Destroy 5 0\" would hit\n  ** a free-list page.\n  */\n  int iTab = pTab->tnum;\n  int iDestroyed = 0;\n\n  while( 1 ){\n    Index *pIdx;\n    int iLargest = 0;\n\n    if( iDestroyed==0 || iTab<iDestroyed ){\n      iLargest = iTab;\n    }\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      int iIdx = pIdx->tnum;\n      assert( pIdx->pSchema==pTab->pSchema );\n      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){\n        iLargest = iIdx;\n      }\n    }\n    if( iLargest==0 ){\n      return;\n    }else{\n      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n      destroyRootPage(pParse, iLargest, iDb);\n      iDestroyed = iLargest;\n    }\n  }\n#endif\n}\n\n/*\n** Remove entries from the sqlite_statN tables (for N in (1,2,3))\n** after a DROP INDEX or DROP TABLE command.\n*/\nstatic void sqlite3ClearStatTables(\n  Parse *pParse,         /* The parsing context */\n  int iDb,               /* The database number */\n  const char *zType,     /* \"idx\" or \"tbl\" */\n  const char *zName      /* Name of index or table */\n){\n  int i;\n  const char *zDbName = pParse->db->aDb[iDb].zName;\n  for(i=1; i<=3; i++){\n    char zTab[24];\n    sqlite3_snprintf(sizeof(zTab),zTab,\"sqlite_stat%d\",i);\n    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){\n      sqlite3NestedParse(pParse,\n        \"DELETE FROM %Q.%s WHERE %s=%Q\",\n        zDbName, zTab, zType, zName\n      );\n    }\n  }\n}\n\n/*\n** Generate code to drop a table.\n*/\nSQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  Trigger *pTrigger;\n  Db *pDb = &db->aDb[iDb];\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3VdbeAddOp0(v, OP_VBegin);\n  }\n#endif\n\n  /* Drop all triggers associated with the table being dropped. Code\n  ** is generated to remove entries from sqlite_master and/or\n  ** sqlite_temp_master if required.\n  */\n  pTrigger = sqlite3TriggerList(pParse, pTab);\n  while( pTrigger ){\n    assert( pTrigger->pSchema==pTab->pSchema || \n        pTrigger->pSchema==db->aDb[1].pSchema );\n    sqlite3DropTriggerPtr(pParse, pTrigger);\n    pTrigger = pTrigger->pNext;\n  }\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n  /* Remove any entries of the sqlite_sequence table associated with\n  ** the table being dropped. This is done before the table is dropped\n  ** at the btree level, in case the sqlite_sequence table needs to\n  ** move as a result of the drop (can happen in auto-vacuum mode).\n  */\n  if( pTab->tabFlags & TF_Autoincrement ){\n    sqlite3NestedParse(pParse,\n      \"DELETE FROM %Q.sqlite_sequence WHERE name=%Q\",\n      pDb->zName, pTab->zName\n    );\n  }\n#endif\n\n  /* Drop all SQLITE_MASTER table and index entries that refer to the\n  ** table. The program name loops through the master table and deletes\n  ** every row that refers to a table of the same name as the one being\n  ** dropped. Triggers are handled seperately because a trigger can be\n  ** created in the temp database that refers to a table in another\n  ** database.\n  */\n  sqlite3NestedParse(pParse, \n      \"DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'\",\n      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);\n  if( !isView && !IsVirtual(pTab) ){\n    destroyTable(pParse, pTab);\n  }\n\n  /* Remove the table entry from SQLite's internal schema and modify\n  ** the schema cookie.\n  */\n  if( IsVirtual(pTab) ){\n    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);\n  }\n  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);\n  sqlite3ChangeCookie(pParse, iDb);\n  sqliteViewResetAll(db, iDb);\n}\n\n/*\n** This routine is called to do the work of a DROP TABLE statement.\n** pName is the name of the table to be dropped.\n*/\nSQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){\n  Table *pTab;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  if( db->mallocFailed ){\n    goto exit_drop_table;\n  }\n  assert( pParse->nErr==0 );\n  assert( pName->nSrc==1 );\n  if( noErr ) db->suppressErr++;\n  pTab = sqlite3LocateTable(pParse, isView, \n                            pName->a[0].zName, pName->a[0].zDatabase);\n  if( noErr ) db->suppressErr--;\n\n  if( pTab==0 ){\n    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);\n    goto exit_drop_table;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n\n  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure\n  ** it is initialized.\n  */\n  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto exit_drop_table;\n  }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    const char *zDb = db->aDb[iDb].zName;\n    const char *zArg2 = 0;\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){\n      goto exit_drop_table;\n    }\n    if( isView ){\n      if( !OMIT_TEMPDB && iDb==1 ){\n        code = SQLITE_DROP_TEMP_VIEW;\n      }else{\n        code = SQLITE_DROP_VIEW;\n      }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    }else if( IsVirtual(pTab) ){\n      code = SQLITE_DROP_VTABLE;\n      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;\n#endif\n    }else{\n      if( !OMIT_TEMPDB && iDb==1 ){\n        code = SQLITE_DROP_TEMP_TABLE;\n      }else{\n        code = SQLITE_DROP_TABLE;\n      }\n    }\n    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){\n      goto exit_drop_table;\n    }\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){\n      goto exit_drop_table;\n    }\n  }\n#endif\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 \n    && sqlite3StrNICmp(pTab->zName, \"sqlite_stat\", 11)!=0 ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be dropped\", pTab->zName);\n    goto exit_drop_table;\n  }\n\n#ifndef SQLITE_OMIT_VIEW\n  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used\n  ** on a table.\n  */\n  if( isView && pTab->pSelect==0 ){\n    sqlite3ErrorMsg(pParse, \"use DROP TABLE to delete table %s\", pTab->zName);\n    goto exit_drop_table;\n  }\n  if( !isView && pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"use DROP VIEW to delete view %s\", pTab->zName);\n    goto exit_drop_table;\n  }\n#endif\n\n  /* Generate code to remove the table from the master table\n  ** on disk.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n    sqlite3ClearStatTables(pParse, iDb, \"tbl\", pTab->zName);\n    sqlite3FkDropTable(pParse, pName, pTab);\n    sqlite3CodeDropTable(pParse, pTab, iDb, isView);\n  }\n\nexit_drop_table:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** This routine is called to create a new foreign key on the table\n** currently under construction.  pFromCol determines which columns\n** in the current table point to the foreign key.  If pFromCol==0 then\n** connect the key to the last column inserted.  pTo is the name of\n** the table referred to.  pToCol is a list of tables in the other\n** pTo table that the foreign key points to.  flags contains all\n** information about the conflict resolution algorithms specified\n** in the ON DELETE, ON UPDATE and ON INSERT clauses.\n**\n** An FKey structure is created and added to the table currently\n** under construction in the pParse->pNewTable field.\n**\n** The foreign key is set for IMMEDIATE processing.  A subsequent call\n** to sqlite3DeferForeignKey() might change this to DEFERRED.\n*/\nSQLITE_PRIVATE void sqlite3CreateForeignKey(\n  Parse *pParse,       /* Parsing context */\n  ExprList *pFromCol,  /* Columns in this table that point to other table */\n  Token *pTo,          /* Name of the other table */\n  ExprList *pToCol,    /* Columns in the other table */\n  int flags            /* Conflict resolution algorithms. */\n){\n  sqlite3 *db = pParse->db;\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  FKey *pFKey = 0;\n  FKey *pNextTo;\n  Table *p = pParse->pNewTable;\n  int nByte;\n  int i;\n  int nCol;\n  char *z;\n\n  assert( pTo!=0 );\n  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;\n  if( pFromCol==0 ){\n    int iCol = p->nCol-1;\n    if( NEVER(iCol<0) ) goto fk_end;\n    if( pToCol && pToCol->nExpr!=1 ){\n      sqlite3ErrorMsg(pParse, \"foreign key on %s\"\n         \" should reference only one column of table %T\",\n         p->aCol[iCol].zName, pTo);\n      goto fk_end;\n    }\n    nCol = 1;\n  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){\n    sqlite3ErrorMsg(pParse,\n        \"number of columns in foreign key does not match the number of \"\n        \"columns in the referenced table\");\n    goto fk_end;\n  }else{\n    nCol = pFromCol->nExpr;\n  }\n  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;\n  if( pToCol ){\n    for(i=0; i<pToCol->nExpr; i++){\n      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;\n    }\n  }\n  pFKey = sqlite3DbMallocZero(db, nByte );\n  if( pFKey==0 ){\n    goto fk_end;\n  }\n  pFKey->pFrom = p;\n  pFKey->pNextFrom = p->pFKey;\n  z = (char*)&pFKey->aCol[nCol];\n  pFKey->zTo = z;\n  memcpy(z, pTo->z, pTo->n);\n  z[pTo->n] = 0;\n  sqlite3Dequote(z);\n  z += pTo->n+1;\n  pFKey->nCol = nCol;\n  if( pFromCol==0 ){\n    pFKey->aCol[0].iFrom = p->nCol-1;\n  }else{\n    for(i=0; i<nCol; i++){\n      int j;\n      for(j=0; j<p->nCol; j++){\n        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){\n          pFKey->aCol[i].iFrom = j;\n          break;\n        }\n      }\n      if( j>=p->nCol ){\n        sqlite3ErrorMsg(pParse, \n          \"unknown column \\\"%s\\\" in foreign key definition\", \n          pFromCol->a[i].zName);\n        goto fk_end;\n      }\n    }\n  }\n  if( pToCol ){\n    for(i=0; i<nCol; i++){\n      int n = sqlite3Strlen30(pToCol->a[i].zName);\n      pFKey->aCol[i].zCol = z;\n      memcpy(z, pToCol->a[i].zName, n);\n      z[n] = 0;\n      z += n+1;\n    }\n  }\n  pFKey->isDeferred = 0;\n  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */\n  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */\n\n  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );\n  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, \n      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey\n  );\n  if( pNextTo==pFKey ){\n    db->mallocFailed = 1;\n    goto fk_end;\n  }\n  if( pNextTo ){\n    assert( pNextTo->pPrevTo==0 );\n    pFKey->pNextTo = pNextTo;\n    pNextTo->pPrevTo = pFKey;\n  }\n\n  /* Link the foreign key to the table as the last step.\n  */\n  p->pFKey = pFKey;\n  pFKey = 0;\n\nfk_end:\n  sqlite3DbFree(db, pFKey);\n#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */\n  sqlite3ExprListDelete(db, pFromCol);\n  sqlite3ExprListDelete(db, pToCol);\n}\n\n/*\n** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED\n** clause is seen as part of a foreign key definition.  The isDeferred\n** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.\n** The behavior of the most recently created foreign key is adjusted\n** accordingly.\n*/\nSQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  Table *pTab;\n  FKey *pFKey;\n  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;\n  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */\n  pFKey->isDeferred = (u8)isDeferred;\n#endif\n}\n\n/*\n** Generate code that will erase and refill index *pIdx.  This is\n** used to initialize a newly created index or to recompute the\n** content of an index in response to a REINDEX command.\n**\n** if memRootPage is not negative, it means that the index is newly\n** created.  The register specified by memRootPage contains the\n** root page number of the index.  If memRootPage is negative, then\n** the index already exists and must be cleared before being refilled and\n** the root page number of the index is taken from pIndex->tnum.\n*/\nstatic void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){\n  Table *pTab = pIndex->pTable;  /* The table that is indexed */\n  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */\n  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */\n  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */\n  int addr1;                     /* Address of top of loop */\n  int addr2;                     /* Address to jump to for next iteration */\n  int tnum;                      /* Root page of index */\n  Vdbe *v;                       /* Generate code into this virtual machine */\n  KeyInfo *pKey;                 /* KeyInfo for index */\n#ifdef SQLITE_OMIT_MERGE_SORT\n  int regIdxKey;                 /* Registers containing the index key */\n#endif\n  int regRecord;                 /* Register holding assemblied index record */\n  sqlite3 *db = pParse->db;      /* The database connection */\n  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,\n      db->aDb[iDb].zName ) ){\n    return;\n  }\n#endif\n\n  /* Require a write-lock on the table to perform this operation */\n  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);\n\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) return;\n  if( memRootPage>=0 ){\n    tnum = memRootPage;\n  }else{\n    tnum = pIndex->tnum;\n    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);\n  }\n  pKey = sqlite3IndexKeyinfo(pParse, pIndex);\n  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, \n                    (char *)pKey, P4_KEYINFO_HANDOFF);\n  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));\n\n#ifndef SQLITE_OMIT_MERGE_SORT\n  /* Open the sorter cursor if we are to use one. */\n  iSorter = pParse->nTab++;\n  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);\n#else\n  iSorter = iTab;\n#endif\n\n  /* Open the table. Loop through all rows of the table, inserting index\n  ** records into the sorter. */\n  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);\n  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);\n  regRecord = sqlite3GetTempReg(pParse);\n\n#ifndef SQLITE_OMIT_MERGE_SORT\n  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);\n  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);\n  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);\n  sqlite3VdbeJumpHere(v, addr1);\n  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);\n  if( pIndex->onError!=OE_None ){\n    int j2 = sqlite3VdbeCurrentAddr(v) + 3;\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);\n    addr2 = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);\n    sqlite3HaltConstraint(\n        pParse, OE_Abort, \"indexed columns are not unique\", P4_STATIC\n    );\n  }else{\n    addr2 = sqlite3VdbeCurrentAddr(v);\n  }\n  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);\n  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n#else\n  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);\n  addr2 = addr1 + 1;\n  if( pIndex->onError!=OE_None ){\n    const int regRowid = regIdxKey + pIndex->nColumn;\n    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;\n    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);\n\n    /* The registers accessed by the OP_IsUnique opcode were allocated\n    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()\n    ** call above. Just before that function was freed they were released\n    ** (made available to the compiler for reuse) using \n    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique\n    ** opcode use the values stored within seems dangerous. However, since\n    ** we can be sure that no other temp registers have been allocated\n    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.\n    */\n    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);\n    sqlite3HaltConstraint(\n        pParse, OE_Abort, \"indexed columns are not unique\", P4_STATIC);\n  }\n  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n#endif\n  sqlite3ReleaseTempReg(pParse, regRecord);\n  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);\n  sqlite3VdbeJumpHere(v, addr1);\n\n  sqlite3VdbeAddOp1(v, OP_Close, iTab);\n  sqlite3VdbeAddOp1(v, OP_Close, iIdx);\n  sqlite3VdbeAddOp1(v, OP_Close, iSorter);\n}\n\n/*\n** Create a new index for an SQL table.  pName1.pName2 is the name of the index \n** and pTblList is the name of the table that is to be indexed.  Both will \n** be NULL for a primary key or an index that is created to satisfy a\n** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable\n** as the table to be indexed.  pParse->pNewTable is a table that is\n** currently being constructed by a CREATE TABLE statement.\n**\n** pList is a list of columns to be indexed.  pList will be NULL if this\n** is a primary key or unique-constraint on the most recent column added\n** to the table currently under construction.  \n**\n** If the index is created successfully, return a pointer to the new Index\n** structure. This is used by sqlite3AddPrimaryKey() to mark the index\n** as the tables primary key (Index.autoIndex==2).\n*/\nSQLITE_PRIVATE Index *sqlite3CreateIndex(\n  Parse *pParse,     /* All information about this parse */\n  Token *pName1,     /* First part of index name. May be NULL */\n  Token *pName2,     /* Second part of index name. May be NULL */\n  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */\n  ExprList *pList,   /* A list of columns to be indexed */\n  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */\n  Token *pStart,     /* The CREATE token that begins this statement */\n  Token *pEnd,       /* The \")\" that closes the CREATE INDEX statement */\n  int sortOrder,     /* Sort order of primary key when pList==NULL */\n  int ifNotExist     /* Omit error if index already exists */\n){\n  Index *pRet = 0;     /* Pointer to return */\n  Table *pTab = 0;     /* Table to be indexed */\n  Index *pIndex = 0;   /* The index to be created */\n  char *zName = 0;     /* Name of the index */\n  int nName;           /* Number of characters in zName */\n  int i, j;\n  Token nullId;        /* Fake token for an empty ID list */\n  DbFixer sFix;        /* For assigning database names to pTable */\n  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */\n  sqlite3 *db = pParse->db;\n  Db *pDb;             /* The specific table containing the indexed database */\n  int iDb;             /* Index of the database that is being written */\n  Token *pName = 0;    /* Unqualified name of the index to create */\n  struct ExprList_item *pListItem; /* For looping over pList */\n  int nCol;\n  int nExtra = 0;\n  char *zExtra;\n\n  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */\n  assert( pParse->nErr==0 );      /* Never called with prior errors */\n  if( db->mallocFailed || IN_DECLARE_VTAB ){\n    goto exit_create_index;\n  }\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto exit_create_index;\n  }\n\n  /*\n  ** Find the table that is to be indexed.  Return early if not found.\n  */\n  if( pTblName!=0 ){\n\n    /* Use the two-part index name to determine the database \n    ** to search for the table. 'Fix' the table name to this db\n    ** before looking up the table.\n    */\n    assert( pName1 && pName2 );\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n    if( iDb<0 ) goto exit_create_index;\n    assert( pName && pName->z );\n\n#ifndef SQLITE_OMIT_TEMPDB\n    /* If the index name was unqualified, check if the table\n    ** is a temp table. If so, set the database to 1. Do not do this\n    ** if initialising a database schema.\n    */\n    if( !db->init.busy ){\n      pTab = sqlite3SrcListLookup(pParse, pTblName);\n      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){\n        iDb = 1;\n      }\n    }\n#endif\n\n    if( sqlite3FixInit(&sFix, pParse, iDb, \"index\", pName) &&\n        sqlite3FixSrcList(&sFix, pTblName)\n    ){\n      /* Because the parser constructs pTblName from a single identifier,\n      ** sqlite3FixSrcList can never fail. */\n      assert(0);\n    }\n    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, \n        pTblName->a[0].zDatabase);\n    if( !pTab || db->mallocFailed ) goto exit_create_index;\n    assert( db->aDb[iDb].pSchema==pTab->pSchema );\n  }else{\n    assert( pName==0 );\n    assert( pStart==0 );\n    pTab = pParse->pNewTable;\n    if( !pTab ) goto exit_create_index;\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  }\n  pDb = &db->aDb[iDb];\n\n  assert( pTab!=0 );\n  assert( pParse->nErr==0 );\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 \n       && memcmp(&pTab->zName[7],\"altertab_\",9)!=0 ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be indexed\", pTab->zName);\n    goto exit_create_index;\n  }\n#ifndef SQLITE_OMIT_VIEW\n  if( pTab->pSelect ){\n    sqlite3ErrorMsg(pParse, \"views may not be indexed\");\n    goto exit_create_index;\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"virtual tables may not be indexed\");\n    goto exit_create_index;\n  }\n#endif\n\n  /*\n  ** Find the name of the index.  Make sure there is not already another\n  ** index or table with the same name.  \n  **\n  ** Exception:  If we are reading the names of permanent indices from the\n  ** sqlite_master table (because some other process changed the schema) and\n  ** one of the index names collides with the name of a temporary table or\n  ** index, then we will continue to process this index.\n  **\n  ** If pName==0 it means that we are\n  ** dealing with a primary key or UNIQUE constraint.  We have to invent our\n  ** own name.\n  */\n  if( pName ){\n    zName = sqlite3NameFromToken(db, pName);\n    if( zName==0 ) goto exit_create_index;\n    assert( pName->z!=0 );\n    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){\n      goto exit_create_index;\n    }\n    if( !db->init.busy ){\n      if( sqlite3FindTable(db, zName, 0)!=0 ){\n        sqlite3ErrorMsg(pParse, \"there is already a table named %s\", zName);\n        goto exit_create_index;\n      }\n    }\n    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){\n      if( !ifNotExist ){\n        sqlite3ErrorMsg(pParse, \"index %s already exists\", zName);\n      }else{\n        assert( !db->init.busy );\n        sqlite3CodeVerifySchema(pParse, iDb);\n      }\n      goto exit_create_index;\n    }\n  }else{\n    int n;\n    Index *pLoop;\n    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}\n    zName = sqlite3MPrintf(db, \"sqlite_autoindex_%s_%d\", pTab->zName, n);\n    if( zName==0 ){\n      goto exit_create_index;\n    }\n  }\n\n  /* Check for authorization to create an index.\n  */\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    const char *zDb = pDb->zName;\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){\n      goto exit_create_index;\n    }\n    i = SQLITE_CREATE_INDEX;\n    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;\n    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){\n      goto exit_create_index;\n    }\n  }\n#endif\n\n  /* If pList==0, it means this routine was called to make a primary\n  ** key out of the last column added to the table under construction.\n  ** So create a fake list to simulate this.\n  */\n  if( pList==0 ){\n    nullId.z = pTab->aCol[pTab->nCol-1].zName;\n    nullId.n = sqlite3Strlen30((char*)nullId.z);\n    pList = sqlite3ExprListAppend(pParse, 0, 0);\n    if( pList==0 ) goto exit_create_index;\n    sqlite3ExprListSetName(pParse, pList, &nullId, 0);\n    pList->a[0].sortOrder = (u8)sortOrder;\n  }\n\n  /* Figure out how many bytes of space are required to store explicitly\n  ** specified collation sequence names.\n  */\n  for(i=0; i<pList->nExpr; i++){\n    Expr *pExpr = pList->a[i].pExpr;\n    if( pExpr ){\n      CollSeq *pColl = pExpr->pColl;\n      /* Either pColl!=0 or there was an OOM failure.  But if an OOM\n      ** failure we have quit before reaching this point. */\n      if( ALWAYS(pColl) ){\n        nExtra += (1 + sqlite3Strlen30(pColl->zName));\n      }\n    }\n  }\n\n  /* \n  ** Allocate the index structure. \n  */\n  nName = sqlite3Strlen30(zName);\n  nCol = pList->nExpr;\n  pIndex = sqlite3DbMallocZero(db, \n      ROUND8(sizeof(Index)) +              /* Index structure  */\n      ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */\n      sizeof(char *)*nCol +                /* Index.azColl     */\n      sizeof(int)*nCol +                   /* Index.aiColumn   */\n      sizeof(u8)*nCol +                    /* Index.aSortOrder */\n      nName + 1 +                          /* Index.zName      */\n      nExtra                               /* Collation sequence names */\n  );\n  if( db->mallocFailed ){\n    goto exit_create_index;\n  }\n  zExtra = (char*)pIndex;\n  pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];\n  pIndex->azColl = (char**)\n     ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));\n  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );\n  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );\n  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);\n  pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);\n  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);\n  zExtra = (char *)(&pIndex->zName[nName+1]);\n  memcpy(pIndex->zName, zName, nName+1);\n  pIndex->pTable = pTab;\n  pIndex->nColumn = pList->nExpr;\n  pIndex->onError = (u8)onError;\n  pIndex->autoIndex = (u8)(pName==0);\n  pIndex->pSchema = db->aDb[iDb].pSchema;\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n\n  /* Check to see if we should honor DESC requests on index columns\n  */\n  if( pDb->pSchema->file_format>=4 ){\n    sortOrderMask = -1;   /* Honor DESC */\n  }else{\n    sortOrderMask = 0;    /* Ignore DESC */\n  }\n\n  /* Scan the names of the columns of the table to be indexed and\n  ** load the column indices into the Index structure.  Report an error\n  ** if any column is not found.\n  **\n  ** TODO:  Add a test to make sure that the same column is not named\n  ** more than once within the same index.  Only the first instance of\n  ** the column will ever be used by the optimizer.  Note that using the\n  ** same column more than once cannot be an error because that would \n  ** break backwards compatibility - it needs to be a warning.\n  */\n  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){\n    const char *zColName = pListItem->zName;\n    Column *pTabCol;\n    int requestedSortOrder;\n    char *zColl;                   /* Collation sequence name */\n\n    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){\n      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;\n    }\n    if( j>=pTab->nCol ){\n      sqlite3ErrorMsg(pParse, \"table %s has no column named %s\",\n        pTab->zName, zColName);\n      pParse->checkSchema = 1;\n      goto exit_create_index;\n    }\n    pIndex->aiColumn[i] = j;\n    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of\n    ** the way the \"idxlist\" non-terminal is constructed by the parser,\n    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl\n    ** must exist or else there must have been an OOM error.  But if there\n    ** was an OOM error, we would never reach this point. */\n    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){\n      int nColl;\n      zColl = pListItem->pExpr->pColl->zName;\n      nColl = sqlite3Strlen30(zColl) + 1;\n      assert( nExtra>=nColl );\n      memcpy(zExtra, zColl, nColl);\n      zColl = zExtra;\n      zExtra += nColl;\n      nExtra -= nColl;\n    }else{\n      zColl = pTab->aCol[j].zColl;\n      if( !zColl ){\n        zColl = \"BINARY\";\n      }\n    }\n    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){\n      goto exit_create_index;\n    }\n    pIndex->azColl[i] = zColl;\n    requestedSortOrder = pListItem->sortOrder & sortOrderMask;\n    pIndex->aSortOrder[i] = (u8)requestedSortOrder;\n  }\n  sqlite3DefaultRowEst(pIndex);\n\n  if( pTab==pParse->pNewTable ){\n    /* This routine has been called to create an automatic index as a\n    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or\n    ** a PRIMARY KEY or UNIQUE clause following the column definitions.\n    ** i.e. one of:\n    **\n    ** CREATE TABLE t(x PRIMARY KEY, y);\n    ** CREATE TABLE t(x, y, UNIQUE(x, y));\n    **\n    ** Either way, check to see if the table already has such an index. If\n    ** so, don't bother creating this one. This only applies to\n    ** automatically created indices. Users can do as they wish with\n    ** explicit indices.\n    **\n    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent\n    ** (and thus suppressing the second one) even if they have different\n    ** sort orders.\n    **\n    ** If there are different collating sequences or if the columns of\n    ** the constraint occur in different orders, then the constraints are\n    ** considered distinct and both result in separate indices.\n    */\n    Index *pIdx;\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      int k;\n      assert( pIdx->onError!=OE_None );\n      assert( pIdx->autoIndex );\n      assert( pIndex->onError!=OE_None );\n\n      if( pIdx->nColumn!=pIndex->nColumn ) continue;\n      for(k=0; k<pIdx->nColumn; k++){\n        const char *z1;\n        const char *z2;\n        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;\n        z1 = pIdx->azColl[k];\n        z2 = pIndex->azColl[k];\n        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;\n      }\n      if( k==pIdx->nColumn ){\n        if( pIdx->onError!=pIndex->onError ){\n          /* This constraint creates the same index as a previous\n          ** constraint specified somewhere in the CREATE TABLE statement.\n          ** However the ON CONFLICT clauses are different. If both this \n          ** constraint and the previous equivalent constraint have explicit\n          ** ON CONFLICT clauses this is an error. Otherwise, use the\n          ** explicitly specified behaviour for the index.\n          */\n          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){\n            sqlite3ErrorMsg(pParse, \n                \"conflicting ON CONFLICT clauses specified\", 0);\n          }\n          if( pIdx->onError==OE_Default ){\n            pIdx->onError = pIndex->onError;\n          }\n        }\n        goto exit_create_index;\n      }\n    }\n  }\n\n  /* Link the new Index structure to its table and to the other\n  ** in-memory database structures. \n  */\n  if( db->init.busy ){\n    Index *p;\n    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );\n    p = sqlite3HashInsert(&pIndex->pSchema->idxHash, \n                          pIndex->zName, sqlite3Strlen30(pIndex->zName),\n                          pIndex);\n    if( p ){\n      assert( p==pIndex );  /* Malloc must have failed */\n      db->mallocFailed = 1;\n      goto exit_create_index;\n    }\n    db->flags |= SQLITE_InternChanges;\n    if( pTblName!=0 ){\n      pIndex->tnum = db->init.newTnum;\n    }\n  }\n\n  /* If the db->init.busy is 0 then create the index on disk.  This\n  ** involves writing the index into the master table and filling in the\n  ** index with the current table contents.\n  **\n  ** The db->init.busy is 0 when the user first enters a CREATE INDEX \n  ** command.  db->init.busy is 1 when a database is opened and \n  ** CREATE INDEX statements are read out of the master table.  In\n  ** the latter case the index already exists on disk, which is why\n  ** we don't want to recreate it.\n  **\n  ** If pTblName==0 it means this index is generated as a primary key\n  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table\n  ** has just been created, it contains no data and the index initialization\n  ** step can be skipped.\n  */\n  else{ /* if( db->init.busy==0 ) */\n    Vdbe *v;\n    char *zStmt;\n    int iMem = ++pParse->nMem;\n\n    v = sqlite3GetVdbe(pParse);\n    if( v==0 ) goto exit_create_index;\n\n\n    /* Create the rootpage for the index\n    */\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);\n\n    /* Gather the complete text of the CREATE INDEX statement into\n    ** the zStmt variable\n    */\n    if( pStart ){\n      assert( pEnd!=0 );\n      /* A named index with an explicit CREATE INDEX statement */\n      zStmt = sqlite3MPrintf(db, \"CREATE%s INDEX %.*s\",\n        onError==OE_None ? \"\" : \" UNIQUE\",\n        (int)(pEnd->z - pName->z) + 1,\n        pName->z);\n    }else{\n      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */\n      /* zStmt = sqlite3MPrintf(\"\"); */\n      zStmt = 0;\n    }\n\n    /* Add an entry in sqlite_master for this index\n    */\n    sqlite3NestedParse(pParse, \n        \"INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);\",\n        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),\n        pIndex->zName,\n        pTab->zName,\n        iMem,\n        zStmt\n    );\n    sqlite3DbFree(db, zStmt);\n\n    /* Fill the index with data and reparse the schema. Code an OP_Expire\n    ** to invalidate all pre-compiled statements.\n    */\n    if( pTblName ){\n      sqlite3RefillIndex(pParse, pIndex, iMem);\n      sqlite3ChangeCookie(pParse, iDb);\n      sqlite3VdbeAddParseSchemaOp(v, iDb,\n         sqlite3MPrintf(db, \"name='%q' AND type='index'\", pIndex->zName));\n      sqlite3VdbeAddOp1(v, OP_Expire, 0);\n    }\n  }\n\n  /* When adding an index to the list of indices for a table, make\n  ** sure all indices labeled OE_Replace come after all those labeled\n  ** OE_Ignore.  This is necessary for the correct constraint check\n  ** processing (in sqlite3GenerateConstraintChecks()) as part of\n  ** UPDATE and INSERT statements.  \n  */\n  if( db->init.busy || pTblName==0 ){\n    if( onError!=OE_Replace || pTab->pIndex==0\n         || pTab->pIndex->onError==OE_Replace){\n      pIndex->pNext = pTab->pIndex;\n      pTab->pIndex = pIndex;\n    }else{\n      Index *pOther = pTab->pIndex;\n      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){\n        pOther = pOther->pNext;\n      }\n      pIndex->pNext = pOther->pNext;\n      pOther->pNext = pIndex;\n    }\n    pRet = pIndex;\n    pIndex = 0;\n  }\n\n  /* Clean up before exiting */\nexit_create_index:\n  if( pIndex ){\n    sqlite3DbFree(db, pIndex->zColAff);\n    sqlite3DbFree(db, pIndex);\n  }\n  sqlite3ExprListDelete(db, pList);\n  sqlite3SrcListDelete(db, pTblName);\n  sqlite3DbFree(db, zName);\n  return pRet;\n}\n\n/*\n** Fill the Index.aiRowEst[] array with default information - information\n** to be used when we have not run the ANALYZE command.\n**\n** aiRowEst[0] is suppose to contain the number of elements in the index.\n** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the\n** number of rows in the table that match any particular value of the\n** first column of the index.  aiRowEst[2] is an estimate of the number\n** of rows that match any particular combiniation of the first 2 columns\n** of the index.  And so forth.  It must always be the case that\n*\n**           aiRowEst[N]<=aiRowEst[N-1]\n**           aiRowEst[N]>=1\n**\n** Apart from that, we have little to go on besides intuition as to\n** how aiRowEst[] should be initialized.  The numbers generated here\n** are based on typical values found in actual indices.\n*/\nSQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){\n  tRowcnt *a = pIdx->aiRowEst;\n  int i;\n  tRowcnt n;\n  assert( a!=0 );\n  a[0] = pIdx->pTable->nRowEst;\n  if( a[0]<10 ) a[0] = 10;\n  n = 10;\n  for(i=1; i<=pIdx->nColumn; i++){\n    a[i] = n;\n    if( n>5 ) n--;\n  }\n  if( pIdx->onError!=OE_None ){\n    a[pIdx->nColumn] = 1;\n  }\n}\n\n/*\n** This routine will drop an existing named index.  This routine\n** implements the DROP INDEX statement.\n*/\nSQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){\n  Index *pIndex;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  assert( pParse->nErr==0 );   /* Never called with prior errors */\n  if( db->mallocFailed ){\n    goto exit_drop_index;\n  }\n  assert( pName->nSrc==1 );\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto exit_drop_index;\n  }\n  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);\n  if( pIndex==0 ){\n    if( !ifExists ){\n      sqlite3ErrorMsg(pParse, \"no such index: %S\", pName, 0);\n    }else{\n      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);\n    }\n    pParse->checkSchema = 1;\n    goto exit_drop_index;\n  }\n  if( pIndex->autoIndex ){\n    sqlite3ErrorMsg(pParse, \"index associated with UNIQUE \"\n      \"or PRIMARY KEY constraint cannot be dropped\", 0);\n    goto exit_drop_index;\n  }\n  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code = SQLITE_DROP_INDEX;\n    Table *pTab = pIndex->pTable;\n    const char *zDb = db->aDb[iDb].zName;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){\n      goto exit_drop_index;\n    }\n    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;\n    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){\n      goto exit_drop_index;\n    }\n  }\n#endif\n\n  /* Generate code to remove the index and from the master table */\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3BeginWriteOperation(pParse, 1, iDb);\n    sqlite3NestedParse(pParse,\n       \"DELETE FROM %Q.%s WHERE name=%Q AND type='index'\",\n       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName\n    );\n    sqlite3ClearStatTables(pParse, iDb, \"idx\", pIndex->zName);\n    sqlite3ChangeCookie(pParse, iDb);\n    destroyRootPage(pParse, pIndex->tnum, iDb);\n    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);\n  }\n\nexit_drop_index:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** pArray is a pointer to an array of objects. Each object in the\n** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()\n** to extend the array so that there is space for a new object at the end.\n**\n** When this function is called, *pnEntry contains the current size of\n** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes\n** in total).\n**\n** If the realloc() is successful (i.e. if no OOM condition occurs), the\n** space allocated for the new object is zeroed, *pnEntry updated to\n** reflect the new size of the array and a pointer to the new allocation\n** returned. *pIdx is set to the index of the new array entry in this case.\n**\n** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains\n** unchanged and a copy of pArray returned.\n*/\nSQLITE_PRIVATE void *sqlite3ArrayAllocate(\n  sqlite3 *db,      /* Connection to notify of malloc failures */\n  void *pArray,     /* Array of objects.  Might be reallocated */\n  int szEntry,      /* Size of each object in the array */\n  int *pnEntry,     /* Number of objects currently in use */\n  int *pIdx         /* Write the index of a new slot here */\n){\n  char *z;\n  int n = *pnEntry;\n  if( (n & (n-1))==0 ){\n    int sz = (n==0) ? 1 : 2*n;\n    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);\n    if( pNew==0 ){\n      *pIdx = -1;\n      return pArray;\n    }\n    pArray = pNew;\n  }\n  z = (char*)pArray;\n  memset(&z[n * szEntry], 0, szEntry);\n  *pIdx = n;\n  ++*pnEntry;\n  return pArray;\n}\n\n/*\n** Append a new element to the given IdList.  Create a new IdList if\n** need be.\n**\n** A new IdList is returned, or NULL if malloc() fails.\n*/\nSQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){\n  int i;\n  if( pList==0 ){\n    pList = sqlite3DbMallocZero(db, sizeof(IdList) );\n    if( pList==0 ) return 0;\n  }\n  pList->a = sqlite3ArrayAllocate(\n      db,\n      pList->a,\n      sizeof(pList->a[0]),\n      &pList->nId,\n      &i\n  );\n  if( i<0 ){\n    sqlite3IdListDelete(db, pList);\n    return 0;\n  }\n  pList->a[i].zName = sqlite3NameFromToken(db, pToken);\n  return pList;\n}\n\n/*\n** Delete an IdList.\n*/\nSQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){\n  int i;\n  if( pList==0 ) return;\n  for(i=0; i<pList->nId; i++){\n    sqlite3DbFree(db, pList->a[i].zName);\n  }\n  sqlite3DbFree(db, pList->a);\n  sqlite3DbFree(db, pList);\n}\n\n/*\n** Return the index in pList of the identifier named zId.  Return -1\n** if not found.\n*/\nSQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){\n  int i;\n  if( pList==0 ) return -1;\n  for(i=0; i<pList->nId; i++){\n    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;\n  }\n  return -1;\n}\n\n/*\n** Expand the space allocated for the given SrcList object by\n** creating nExtra new slots beginning at iStart.  iStart is zero based.\n** New slots are zeroed.\n**\n** For example, suppose a SrcList initially contains two entries: A,B.\n** To append 3 new entries onto the end, do this:\n**\n**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);\n**\n** After the call above it would contain:  A, B, nil, nil, nil.\n** If the iStart argument had been 1 instead of 2, then the result\n** would have been:  A, nil, nil, nil, B.  To prepend the new slots,\n** the iStart value would be 0.  The result then would\n** be: nil, nil, nil, A, B.\n**\n** If a memory allocation fails the SrcList is unchanged.  The\n** db->mallocFailed flag will be set to true.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(\n  sqlite3 *db,       /* Database connection to notify of OOM errors */\n  SrcList *pSrc,     /* The SrcList to be enlarged */\n  int nExtra,        /* Number of new slots to add to pSrc->a[] */\n  int iStart         /* Index in pSrc->a[] of first new slot */\n){\n  int i;\n\n  /* Sanity checking on calling parameters */\n  assert( iStart>=0 );\n  assert( nExtra>=1 );\n  assert( pSrc!=0 );\n  assert( iStart<=pSrc->nSrc );\n\n  /* Allocate additional space if needed */\n  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){\n    SrcList *pNew;\n    int nAlloc = pSrc->nSrc+nExtra;\n    int nGot;\n    pNew = sqlite3DbRealloc(db, pSrc,\n               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );\n    if( pNew==0 ){\n      assert( db->mallocFailed );\n      return pSrc;\n    }\n    pSrc = pNew;\n    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;\n    pSrc->nAlloc = (u16)nGot;\n  }\n\n  /* Move existing slots that come after the newly inserted slots\n  ** out of the way */\n  for(i=pSrc->nSrc-1; i>=iStart; i--){\n    pSrc->a[i+nExtra] = pSrc->a[i];\n  }\n  pSrc->nSrc += (i16)nExtra;\n\n  /* Zero the newly allocated slots */\n  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);\n  for(i=iStart; i<iStart+nExtra; i++){\n    pSrc->a[i].iCursor = -1;\n  }\n\n  /* Return a pointer to the enlarged SrcList */\n  return pSrc;\n}\n\n\n/*\n** Append a new table name to the given SrcList.  Create a new SrcList if\n** need be.  A new entry is created in the SrcList even if pTable is NULL.\n**\n** A SrcList is returned, or NULL if there is an OOM error.  The returned\n** SrcList might be the same as the SrcList that was input or it might be\n** a new one.  If an OOM error does occurs, then the prior value of pList\n** that is input to this routine is automatically freed.\n**\n** If pDatabase is not null, it means that the table has an optional\n** database name prefix.  Like this:  \"database.table\".  The pDatabase\n** points to the table name and the pTable points to the database name.\n** The SrcList.a[].zName field is filled with the table name which might\n** come from pTable (if pDatabase is NULL) or from pDatabase.  \n** SrcList.a[].zDatabase is filled with the database name from pTable,\n** or with NULL if no database is specified.\n**\n** In other words, if call like this:\n**\n**         sqlite3SrcListAppend(D,A,B,0);\n**\n** Then B is a table name and the database name is unspecified.  If called\n** like this:\n**\n**         sqlite3SrcListAppend(D,A,B,C);\n**\n** Then C is the table name and B is the database name.  If C is defined\n** then so is B.  In other words, we never have a case where:\n**\n**         sqlite3SrcListAppend(D,A,0,C);\n**\n** Both pTable and pDatabase are assumed to be quoted.  They are dequoted\n** before being added to the SrcList.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppend(\n  sqlite3 *db,        /* Connection to notify of malloc failures */\n  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */\n  Token *pTable,      /* Table to append */\n  Token *pDatabase    /* Database of the table */\n){\n  struct SrcList_item *pItem;\n  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */\n  if( pList==0 ){\n    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );\n    if( pList==0 ) return 0;\n    pList->nAlloc = 1;\n  }\n  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);\n  if( db->mallocFailed ){\n    sqlite3SrcListDelete(db, pList);\n    return 0;\n  }\n  pItem = &pList->a[pList->nSrc-1];\n  if( pDatabase && pDatabase->z==0 ){\n    pDatabase = 0;\n  }\n  if( pDatabase ){\n    Token *pTemp = pDatabase;\n    pDatabase = pTable;\n    pTable = pTemp;\n  }\n  pItem->zName = sqlite3NameFromToken(db, pTable);\n  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);\n  return pList;\n}\n\n/*\n** Assign VdbeCursor index numbers to all tables in a SrcList\n*/\nSQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){\n  int i;\n  struct SrcList_item *pItem;\n  assert(pList || pParse->db->mallocFailed );\n  if( pList ){\n    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){\n      if( pItem->iCursor>=0 ) break;\n      pItem->iCursor = pParse->nTab++;\n      if( pItem->pSelect ){\n        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);\n      }\n    }\n  }\n}\n\n/*\n** Delete an entire SrcList including all its substructure.\n*/\nSQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){\n  int i;\n  struct SrcList_item *pItem;\n  if( pList==0 ) return;\n  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){\n    sqlite3DbFree(db, pItem->zDatabase);\n    sqlite3DbFree(db, pItem->zName);\n    sqlite3DbFree(db, pItem->zAlias);\n    sqlite3DbFree(db, pItem->zIndex);\n    sqlite3DeleteTable(db, pItem->pTab);\n    sqlite3SelectDelete(db, pItem->pSelect);\n    sqlite3ExprDelete(db, pItem->pOn);\n    sqlite3IdListDelete(db, pItem->pUsing);\n  }\n  sqlite3DbFree(db, pList);\n}\n\n/*\n** This routine is called by the parser to add a new term to the\n** end of a growing FROM clause.  The \"p\" parameter is the part of\n** the FROM clause that has already been constructed.  \"p\" is NULL\n** if this is the first term of the FROM clause.  pTable and pDatabase\n** are the name of the table and database named in the FROM clause term.\n** pDatabase is NULL if the database name qualifier is missing - the\n** usual case.  If the term has a alias, then pAlias points to the\n** alias token.  If the term is a subquery, then pSubquery is the\n** SELECT statement that the subquery encodes.  The pTable and\n** pDatabase parameters are NULL for subqueries.  The pOn and pUsing\n** parameters are the content of the ON and USING clauses.\n**\n** Return a new SrcList which encodes is the FROM with the new\n** term added.\n*/\nSQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(\n  Parse *pParse,          /* Parsing context */\n  SrcList *p,             /* The left part of the FROM clause already seen */\n  Token *pTable,          /* Name of the table to add to the FROM clause */\n  Token *pDatabase,       /* Name of the database containing pTable */\n  Token *pAlias,          /* The right-hand side of the AS subexpression */\n  Select *pSubquery,      /* A subquery used in place of a table name */\n  Expr *pOn,              /* The ON clause of a join */\n  IdList *pUsing          /* The USING clause of a join */\n){\n  struct SrcList_item *pItem;\n  sqlite3 *db = pParse->db;\n  if( !p && (pOn || pUsing) ){\n    sqlite3ErrorMsg(pParse, \"a JOIN clause is required before %s\", \n      (pOn ? \"ON\" : \"USING\")\n    );\n    goto append_from_error;\n  }\n  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);\n  if( p==0 || NEVER(p->nSrc==0) ){\n    goto append_from_error;\n  }\n  pItem = &p->a[p->nSrc-1];\n  assert( pAlias!=0 );\n  if( pAlias->n ){\n    pItem->zAlias = sqlite3NameFromToken(db, pAlias);\n  }\n  pItem->pSelect = pSubquery;\n  pItem->pOn = pOn;\n  pItem->pUsing = pUsing;\n  return p;\n\n append_from_error:\n  assert( p==0 );\n  sqlite3ExprDelete(db, pOn);\n  sqlite3IdListDelete(db, pUsing);\n  sqlite3SelectDelete(db, pSubquery);\n  return 0;\n}\n\n/*\n** Add an INDEXED BY or NOT INDEXED clause to the most recently added \n** element of the source-list passed as the second argument.\n*/\nSQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){\n  assert( pIndexedBy!=0 );\n  if( p && ALWAYS(p->nSrc>0) ){\n    struct SrcList_item *pItem = &p->a[p->nSrc-1];\n    assert( pItem->notIndexed==0 && pItem->zIndex==0 );\n    if( pIndexedBy->n==1 && !pIndexedBy->z ){\n      /* A \"NOT INDEXED\" clause was supplied. See parse.y \n      ** construct \"indexed_opt\" for details. */\n      pItem->notIndexed = 1;\n    }else{\n      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);\n    }\n  }\n}\n\n/*\n** When building up a FROM clause in the parser, the join operator\n** is initially attached to the left operand.  But the code generator\n** expects the join operator to be on the right operand.  This routine\n** Shifts all join operators from left to right for an entire FROM\n** clause.\n**\n** Example: Suppose the join is like this:\n**\n**           A natural cross join B\n**\n** The operator is \"natural cross join\".  The A and B operands are stored\n** in p->a[0] and p->a[1], respectively.  The parser initially stores the\n** operator with A.  This routine shifts that operator over to B.\n*/\nSQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){\n  if( p ){\n    int i;\n    assert( p->a || p->nSrc==0 );\n    for(i=p->nSrc-1; i>0; i--){\n      p->a[i].jointype = p->a[i-1].jointype;\n    }\n    p->a[0].jointype = 0;\n  }\n}\n\n/*\n** Begin a transaction\n*/\nSQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){\n  sqlite3 *db;\n  Vdbe *v;\n  int i;\n\n  assert( pParse!=0 );\n  db = pParse->db;\n  assert( db!=0 );\n/*  if( db->aDb[0].pBt==0 ) return; */\n  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, \"BEGIN\", 0, 0) ){\n    return;\n  }\n  v = sqlite3GetVdbe(pParse);\n  if( !v ) return;\n  if( type!=TK_DEFERRED ){\n    for(i=0; i<db->nDb; i++){\n      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);\n      sqlite3VdbeUsesBtree(v, i);\n    }\n  }\n  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);\n}\n\n/*\n** Commit a transaction\n*/\nSQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){\n  Vdbe *v;\n\n  assert( pParse!=0 );\n  assert( pParse->db!=0 );\n  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, \"COMMIT\", 0, 0) ){\n    return;\n  }\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);\n  }\n}\n\n/*\n** Rollback a transaction\n*/\nSQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){\n  Vdbe *v;\n\n  assert( pParse!=0 );\n  assert( pParse->db!=0 );\n  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, \"ROLLBACK\", 0, 0) ){\n    return;\n  }\n  v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);\n  }\n}\n\n/*\n** This function is called by the parser when it parses a command to create,\n** release or rollback an SQL savepoint. \n*/\nSQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){\n  char *zName = sqlite3NameFromToken(pParse->db, pName);\n  if( zName ){\n    Vdbe *v = sqlite3GetVdbe(pParse);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    static const char * const az[] = { \"BEGIN\", \"RELEASE\", \"ROLLBACK\" };\n    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );\n#endif\n    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){\n      sqlite3DbFree(pParse->db, zName);\n      return;\n    }\n    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);\n  }\n}\n\n/*\n** Make sure the TEMP database is open and available for use.  Return\n** the number of errors.  Leave any error messages in the pParse structure.\n*/\nSQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  if( db->aDb[1].pBt==0 && !pParse->explain ){\n    int rc;\n    Btree *pBt;\n    static const int flags = \n          SQLITE_OPEN_READWRITE |\n          SQLITE_OPEN_CREATE |\n          SQLITE_OPEN_EXCLUSIVE |\n          SQLITE_OPEN_DELETEONCLOSE |\n          SQLITE_OPEN_TEMP_DB;\n\n    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);\n    if( rc!=SQLITE_OK ){\n      sqlite3ErrorMsg(pParse, \"unable to open a temporary database \"\n        \"file for storing temporary tables\");\n      pParse->rc = rc;\n      return 1;\n    }\n    db->aDb[1].pBt = pBt;\n    assert( db->aDb[1].pSchema );\n    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){\n      db->mallocFailed = 1;\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** Generate VDBE code that will verify the schema cookie and start\n** a read-transaction for all named database files.\n**\n** It is important that all schema cookies be verified and all\n** read transactions be started before anything else happens in\n** the VDBE program.  But this routine can be called after much other\n** code has been generated.  So here is what we do:\n**\n** The first time this routine is called, we code an OP_Goto that\n** will jump to a subroutine at the end of the program.  Then we\n** record every database that needs its schema verified in the\n** pParse->cookieMask field.  Later, after all other code has been\n** generated, the subroutine that does the cookie verifications and\n** starts the transactions will be coded and the OP_Goto P2 value\n** will be made to point to that subroutine.  The generation of the\n** cookie verification subroutine code happens in sqlite3FinishCoding().\n**\n** If iDb<0 then code the OP_Goto only - don't set flag to verify the\n** schema on any databases.  This can be used to position the OP_Goto\n** early in the code, before we know if any database tables will be used.\n*/\nSQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n\n  if( pToplevel->cookieGoto==0 ){\n    Vdbe *v = sqlite3GetVdbe(pToplevel);\n    if( v==0 ) return;  /* This only happens if there was a prior error */\n    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;\n  }\n  if( iDb>=0 ){\n    sqlite3 *db = pToplevel->db;\n    yDbMask mask;\n\n    assert( iDb<db->nDb );\n    assert( db->aDb[iDb].pBt!=0 || iDb==1 );\n    assert( iDb<SQLITE_MAX_ATTACHED+2 );\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    mask = ((yDbMask)1)<<iDb;\n    if( (pToplevel->cookieMask & mask)==0 ){\n      pToplevel->cookieMask |= mask;\n      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;\n      if( !OMIT_TEMPDB && iDb==1 ){\n        sqlite3OpenTempDatabase(pToplevel);\n      }\n    }\n  }\n}\n\n/*\n** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each \n** attached database. Otherwise, invoke it for the database named zDb only.\n*/\nSQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){\n  sqlite3 *db = pParse->db;\n  int i;\n  for(i=0; i<db->nDb; i++){\n    Db *pDb = &db->aDb[i];\n    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){\n      sqlite3CodeVerifySchema(pParse, i);\n    }\n  }\n}\n\n/*\n** Generate VDBE code that prepares for doing an operation that\n** might change the database.\n**\n** This routine starts a new transaction if we are not already within\n** a transaction.  If we are already within a transaction, then a checkpoint\n** is set if the setStatement parameter is true.  A checkpoint should\n** be set for operations that might fail (due to a constraint) part of\n** the way through and which will need to undo some writes without having to\n** rollback the whole transaction.  For operations where all constraints\n** can be checked before any changes are made to the database, it is never\n** necessary to undo a write and the checkpoint should not be set.\n*/\nSQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  sqlite3CodeVerifySchema(pParse, iDb);\n  pToplevel->writeMask |= ((yDbMask)1)<<iDb;\n  pToplevel->isMultiWrite |= setStatement;\n}\n\n/*\n** Indicate that the statement currently under construction might write\n** more than one entry (example: deleting one row then inserting another,\n** inserting multiple rows in a table, or inserting a row and index entries.)\n** If an abort occurs after some of these writes have completed, then it will\n** be necessary to undo the completed writes.\n*/\nSQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  pToplevel->isMultiWrite = 1;\n}\n\n/* \n** The code generator calls this routine if is discovers that it is\n** possible to abort a statement prior to completion.  In order to \n** perform this abort without corrupting the database, we need to make\n** sure that the statement is protected by a statement transaction.\n**\n** Technically, we only need to set the mayAbort flag if the\n** isMultiWrite flag was previously set.  There is a time dependency\n** such that the abort must occur after the multiwrite.  This makes\n** some statements involving the REPLACE conflict resolution algorithm\n** go a little faster.  But taking advantage of this time dependency\n** makes it more difficult to prove that the code is correct (in \n** particular, it prevents us from writing an effective\n** implementation of sqlite3AssertMayAbort()) and so we have chosen\n** to take the safe route and skip the optimization.\n*/\nSQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  pToplevel->mayAbort = 1;\n}\n\n/*\n** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT\n** error. The onError parameter determines which (if any) of the statement\n** and/or current transaction is rolled back.\n*/\nSQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( onError==OE_Abort ){\n    sqlite3MayAbort(pParse);\n  }\n  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);\n}\n\n/*\n** Check to see if pIndex uses the collating sequence pColl.  Return\n** true if it does and false if it does not.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic int collationMatch(const char *zColl, Index *pIndex){\n  int i;\n  assert( zColl!=0 );\n  for(i=0; i<pIndex->nColumn; i++){\n    const char *z = pIndex->azColl[i];\n    assert( z!=0 );\n    if( 0==sqlite3StrICmp(z, zColl) ){\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif\n\n/*\n** Recompute all indices of pTab that use the collating sequence pColl.\n** If pColl==0 then recompute all indices of pTab.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic void reindexTable(Parse *pParse, Table *pTab, char const *zColl){\n  Index *pIndex;              /* An index associated with pTab */\n\n  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){\n    if( zColl==0 || collationMatch(zColl, pIndex) ){\n      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n      sqlite3BeginWriteOperation(pParse, 0, iDb);\n      sqlite3RefillIndex(pParse, pIndex, -1);\n    }\n  }\n}\n#endif\n\n/*\n** Recompute all indices of all tables in all databases where the\n** indices use the collating sequence pColl.  If pColl==0 then recompute\n** all indices everywhere.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nstatic void reindexDatabases(Parse *pParse, char const *zColl){\n  Db *pDb;                    /* A single database */\n  int iDb;                    /* The database index number */\n  sqlite3 *db = pParse->db;   /* The database connection */\n  HashElem *k;                /* For looping over tables in pDb */\n  Table *pTab;                /* A table in the database */\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */\n  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){\n    assert( pDb!=0 );\n    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){\n      pTab = (Table*)sqliteHashData(k);\n      reindexTable(pParse, pTab, zColl);\n    }\n  }\n}\n#endif\n\n/*\n** Generate code for the REINDEX command.\n**\n**        REINDEX                            -- 1\n**        REINDEX  <collation>               -- 2\n**        REINDEX  ?<database>.?<tablename>  -- 3\n**        REINDEX  ?<database>.?<indexname>  -- 4\n**\n** Form 1 causes all indices in all attached databases to be rebuilt.\n** Form 2 rebuilds all indices in all databases that use the named\n** collating function.  Forms 3 and 4 rebuild the named index or all\n** indices associated with the named table.\n*/\n#ifndef SQLITE_OMIT_REINDEX\nSQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){\n  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */\n  char *z;                    /* Name of a table or index */\n  const char *zDb;            /* Name of the database */\n  Table *pTab;                /* A table in the database */\n  Index *pIndex;              /* An index associated with pTab */\n  int iDb;                    /* The database index number */\n  sqlite3 *db = pParse->db;   /* The database connection */\n  Token *pObjName;            /* Name of the table or index to be reindexed */\n\n  /* Read the database schema. If an error occurs, leave an error message\n  ** and code in pParse and return NULL. */\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    return;\n  }\n\n  if( pName1==0 ){\n    reindexDatabases(pParse, 0);\n    return;\n  }else if( NEVER(pName2==0) || pName2->z==0 ){\n    char *zColl;\n    assert( pName1->z );\n    zColl = sqlite3NameFromToken(pParse->db, pName1);\n    if( !zColl ) return;\n    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);\n    if( pColl ){\n      reindexDatabases(pParse, zColl);\n      sqlite3DbFree(db, zColl);\n      return;\n    }\n    sqlite3DbFree(db, zColl);\n  }\n  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);\n  if( iDb<0 ) return;\n  z = sqlite3NameFromToken(db, pObjName);\n  if( z==0 ) return;\n  zDb = db->aDb[iDb].zName;\n  pTab = sqlite3FindTable(db, z, zDb);\n  if( pTab ){\n    reindexTable(pParse, pTab, 0);\n    sqlite3DbFree(db, z);\n    return;\n  }\n  pIndex = sqlite3FindIndex(db, z, zDb);\n  sqlite3DbFree(db, z);\n  if( pIndex ){\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    sqlite3RefillIndex(pParse, pIndex, -1);\n    return;\n  }\n  sqlite3ErrorMsg(pParse, \"unable to identify the object to be reindexed\");\n}\n#endif\n\n/*\n** Return a dynamicly allocated KeyInfo structure that can be used\n** with OP_OpenRead or OP_OpenWrite to access database index pIdx.\n**\n** If successful, a pointer to the new structure is returned. In this case\n** the caller is responsible for calling sqlite3DbFree(db, ) on the returned \n** pointer. If an error occurs (out of memory or missing collation \n** sequence), NULL is returned and the state of pParse updated to reflect\n** the error.\n*/\nSQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){\n  int i;\n  int nCol = pIdx->nColumn;\n  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;\n  sqlite3 *db = pParse->db;\n  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);\n\n  if( pKey ){\n    pKey->db = pParse->db;\n    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);\n    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );\n    for(i=0; i<nCol; i++){\n      char *zColl = pIdx->azColl[i];\n      assert( zColl );\n      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);\n      pKey->aSortOrder[i] = pIdx->aSortOrder[i];\n    }\n    pKey->nField = (u16)nCol;\n  }\n\n  if( pParse->nErr ){\n    sqlite3DbFree(db, pKey);\n    pKey = 0;\n  }\n  return pKey;\n}\n\n/************** End of build.c ***********************************************/\n/************** Begin file callback.c ****************************************/\n/*\n** 2005 May 23 \n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains functions used to access the internal hash tables\n** of user defined functions and collation sequences.\n*/\n\n\n/*\n** Invoke the 'collation needed' callback to request a collation sequence\n** in the encoding enc of name zName, length nName.\n*/\nstatic void callCollNeeded(sqlite3 *db, int enc, const char *zName){\n  assert( !db->xCollNeeded || !db->xCollNeeded16 );\n  if( db->xCollNeeded ){\n    char *zExternal = sqlite3DbStrDup(db, zName);\n    if( !zExternal ) return;\n    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);\n    sqlite3DbFree(db, zExternal);\n  }\n#ifndef SQLITE_OMIT_UTF16\n  if( db->xCollNeeded16 ){\n    char const *zExternal;\n    sqlite3_value *pTmp = sqlite3ValueNew(db);\n    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);\n    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);\n    if( zExternal ){\n      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);\n    }\n    sqlite3ValueFree(pTmp);\n  }\n#endif\n}\n\n/*\n** This routine is called if the collation factory fails to deliver a\n** collation function in the best encoding but there may be other versions\n** of this collation function (for other text encodings) available. Use one\n** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if\n** possible.\n*/\nstatic int synthCollSeq(sqlite3 *db, CollSeq *pColl){\n  CollSeq *pColl2;\n  char *z = pColl->zName;\n  int i;\n  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };\n  for(i=0; i<3; i++){\n    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);\n    if( pColl2->xCmp!=0 ){\n      memcpy(pColl, pColl2, sizeof(CollSeq));\n      pColl->xDel = 0;         /* Do not copy the destructor */\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_ERROR;\n}\n\n/*\n** This function is responsible for invoking the collation factory callback\n** or substituting a collation sequence of a different encoding when the\n** requested collation sequence is not available in the desired encoding.\n** \n** If it is not NULL, then pColl must point to the database native encoding \n** collation sequence with name zName, length nName.\n**\n** The return value is either the collation sequence to be used in database\n** db for collation type name zName, length nName, or NULL, if no collation\n** sequence can be found.\n**\n** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(\n  sqlite3* db,          /* The database connection */\n  u8 enc,               /* The desired encoding for the collating sequence */\n  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */\n  const char *zName     /* Collating sequence name */\n){\n  CollSeq *p;\n\n  p = pColl;\n  if( !p ){\n    p = sqlite3FindCollSeq(db, enc, zName, 0);\n  }\n  if( !p || !p->xCmp ){\n    /* No collation sequence of this type for this encoding is registered.\n    ** Call the collation factory to see if it can supply us with one.\n    */\n    callCollNeeded(db, enc, zName);\n    p = sqlite3FindCollSeq(db, enc, zName, 0);\n  }\n  if( p && !p->xCmp && synthCollSeq(db, p) ){\n    p = 0;\n  }\n  assert( !p || p->xCmp );\n  return p;\n}\n\n/*\n** This routine is called on a collation sequence before it is used to\n** check that it is defined. An undefined collation sequence exists when\n** a database is loaded that contains references to collation sequences\n** that have not been defined by sqlite3_create_collation() etc.\n**\n** If required, this routine calls the 'collation needed' callback to\n** request a definition of the collating sequence. If this doesn't work, \n** an equivalent collating sequence that uses a text encoding different\n** from the main database is substituted, if one is available.\n*/\nSQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){\n  if( pColl ){\n    const char *zName = pColl->zName;\n    sqlite3 *db = pParse->db;\n    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);\n    if( !p ){\n      sqlite3ErrorMsg(pParse, \"no such collation sequence: %s\", zName);\n      pParse->nErr++;\n      return SQLITE_ERROR;\n    }\n    assert( p==pColl );\n  }\n  return SQLITE_OK;\n}\n\n\n\n/*\n** Locate and return an entry from the db.aCollSeq hash table. If the entry\n** specified by zName and nName is not found and parameter 'create' is\n** true, then create a new entry. Otherwise return NULL.\n**\n** Each pointer stored in the sqlite3.aCollSeq hash table contains an\n** array of three CollSeq structures. The first is the collation sequence\n** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.\n**\n** Stored immediately after the three collation sequences is a copy of\n** the collation sequence name. A pointer to this string is stored in\n** each collation sequence structure.\n*/\nstatic CollSeq *findCollSeqEntry(\n  sqlite3 *db,          /* Database connection */\n  const char *zName,    /* Name of the collating sequence */\n  int create            /* Create a new entry if true */\n){\n  CollSeq *pColl;\n  int nName = sqlite3Strlen30(zName);\n  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);\n\n  if( 0==pColl && create ){\n    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );\n    if( pColl ){\n      CollSeq *pDel = 0;\n      pColl[0].zName = (char*)&pColl[3];\n      pColl[0].enc = SQLITE_UTF8;\n      pColl[1].zName = (char*)&pColl[3];\n      pColl[1].enc = SQLITE_UTF16LE;\n      pColl[2].zName = (char*)&pColl[3];\n      pColl[2].enc = SQLITE_UTF16BE;\n      memcpy(pColl[0].zName, zName, nName);\n      pColl[0].zName[nName] = 0;\n      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);\n\n      /* If a malloc() failure occurred in sqlite3HashInsert(), it will \n      ** return the pColl pointer to be deleted (because it wasn't added\n      ** to the hash table).\n      */\n      assert( pDel==0 || pDel==pColl );\n      if( pDel!=0 ){\n        db->mallocFailed = 1;\n        sqlite3DbFree(db, pDel);\n        pColl = 0;\n      }\n    }\n  }\n  return pColl;\n}\n\n/*\n** Parameter zName points to a UTF-8 encoded string nName bytes long.\n** Return the CollSeq* pointer for the collation sequence named zName\n** for the encoding 'enc' from the database 'db'.\n**\n** If the entry specified is not found and 'create' is true, then create a\n** new entry.  Otherwise return NULL.\n**\n** A separate function sqlite3LocateCollSeq() is a wrapper around\n** this routine.  sqlite3LocateCollSeq() invokes the collation factory\n** if necessary and generates an error message if the collating sequence\n** cannot be found.\n**\n** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()\n*/\nSQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(\n  sqlite3 *db,\n  u8 enc,\n  const char *zName,\n  int create\n){\n  CollSeq *pColl;\n  if( zName ){\n    pColl = findCollSeqEntry(db, zName, create);\n  }else{\n    pColl = db->pDfltColl;\n  }\n  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );\n  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );\n  if( pColl ) pColl += enc-1;\n  return pColl;\n}\n\n/* During the search for the best function definition, this procedure\n** is called to test how well the function passed as the first argument\n** matches the request for a function with nArg arguments in a system\n** that uses encoding enc. The value returned indicates how well the\n** request is matched. A higher value indicates a better match.\n**\n** If nArg is -1 that means to only return a match (non-zero) if p->nArg\n** is also -1.  In other words, we are searching for a function that\n** takes a variable number of arguments.\n**\n** If nArg is -2 that means that we are searching for any function \n** regardless of the number of arguments it uses, so return a positive\n** match score for any\n**\n** The returned value is always between 0 and 6, as follows:\n**\n** 0: Not a match.\n** 1: UTF8/16 conversion required and function takes any number of arguments.\n** 2: UTF16 byte order change required and function takes any number of args.\n** 3: encoding matches and function takes any number of arguments\n** 4: UTF8/16 conversion required - argument count matches exactly\n** 5: UTF16 byte order conversion required - argument count matches exactly\n** 6: Perfect match:  encoding and argument count match exactly.\n**\n** If nArg==(-2) then any function with a non-null xStep or xFunc is\n** a perfect match and any function with both xStep and xFunc NULL is\n** a non-match.\n*/\n#define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */\nstatic int matchQuality(\n  FuncDef *p,     /* The function we are evaluating for match quality */\n  int nArg,       /* Desired number of arguments.  (-1)==any */\n  u8 enc          /* Desired text encoding */\n){\n  int match;\n\n  /* nArg of -2 is a special case */\n  if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;\n\n  /* Wrong number of arguments means \"no match\" */\n  if( p->nArg!=nArg && p->nArg>=0 ) return 0;\n\n  /* Give a better score to a function with a specific number of arguments\n  ** than to function that accepts any number of arguments. */\n  if( p->nArg==nArg ){\n    match = 4;\n  }else{\n    match = 1;\n  }\n\n  /* Bonus points if the text encoding matches */\n  if( enc==p->iPrefEnc ){\n    match += 2;  /* Exact encoding match */\n  }else if( (enc & p->iPrefEnc & 2)!=0 ){\n    match += 1;  /* Both are UTF16, but with different byte orders */\n  }\n\n  return match;\n}\n\n/*\n** Search a FuncDefHash for a function with the given name.  Return\n** a pointer to the matching FuncDef if found, or 0 if there is no match.\n*/\nstatic FuncDef *functionSearch(\n  FuncDefHash *pHash,  /* Hash table to search */\n  int h,               /* Hash of the name */\n  const char *zFunc,   /* Name of function */\n  int nFunc            /* Number of bytes in zFunc */\n){\n  FuncDef *p;\n  for(p=pHash->a[h]; p; p=p->pHash){\n    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){\n      return p;\n    }\n  }\n  return 0;\n}\n\n/*\n** Insert a new FuncDef into a FuncDefHash hash table.\n*/\nSQLITE_PRIVATE void sqlite3FuncDefInsert(\n  FuncDefHash *pHash,  /* The hash table into which to insert */\n  FuncDef *pDef        /* The function definition to insert */\n){\n  FuncDef *pOther;\n  int nName = sqlite3Strlen30(pDef->zName);\n  u8 c1 = (u8)pDef->zName[0];\n  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);\n  pOther = functionSearch(pHash, h, pDef->zName, nName);\n  if( pOther ){\n    assert( pOther!=pDef && pOther->pNext!=pDef );\n    pDef->pNext = pOther->pNext;\n    pOther->pNext = pDef;\n  }else{\n    pDef->pNext = 0;\n    pDef->pHash = pHash->a[h];\n    pHash->a[h] = pDef;\n  }\n}\n  \n  \n\n/*\n** Locate a user function given a name, a number of arguments and a flag\n** indicating whether the function prefers UTF-16 over UTF-8.  Return a\n** pointer to the FuncDef structure that defines that function, or return\n** NULL if the function does not exist.\n**\n** If the createFlag argument is true, then a new (blank) FuncDef\n** structure is created and liked into the \"db\" structure if a\n** no matching function previously existed.\n**\n** If nArg is -2, then the first valid function found is returned.  A\n** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)\n** case is used to see if zName is a valid function name for some number\n** of arguments.  If nArg is -2, then createFlag must be 0.\n**\n** If createFlag is false, then a function with the required name and\n** number of arguments may be returned even if the eTextRep flag does not\n** match that requested.\n*/\nSQLITE_PRIVATE FuncDef *sqlite3FindFunction(\n  sqlite3 *db,       /* An open database */\n  const char *zName, /* Name of the function.  Not null-terminated */\n  int nName,         /* Number of characters in the name */\n  int nArg,          /* Number of arguments.  -1 means any number */\n  u8 enc,            /* Preferred text encoding */\n  u8 createFlag      /* Create new entry if true and does not otherwise exist */\n){\n  FuncDef *p;         /* Iterator variable */\n  FuncDef *pBest = 0; /* Best match found so far */\n  int bestScore = 0;  /* Score of best match */\n  int h;              /* Hash value */\n\n  assert( nArg>=(-2) );\n  assert( nArg>=(-1) || createFlag==0 );\n  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );\n  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);\n\n  /* First search for a match amongst the application-defined functions.\n  */\n  p = functionSearch(&db->aFunc, h, zName, nName);\n  while( p ){\n    int score = matchQuality(p, nArg, enc);\n    if( score>bestScore ){\n      pBest = p;\n      bestScore = score;\n    }\n    p = p->pNext;\n  }\n\n  /* If no match is found, search the built-in functions.\n  **\n  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in\n  ** functions even if a prior app-defined function was found.  And give\n  ** priority to built-in functions.\n  **\n  ** Except, if createFlag is true, that means that we are trying to\n  ** install a new function.  Whatever FuncDef structure is returned it will\n  ** have fields overwritten with new information appropriate for the\n  ** new function.  But the FuncDefs for built-in functions are read-only.\n  ** So we must not search for built-ins when creating a new function.\n  */ \n  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){\n    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);\n    bestScore = 0;\n    p = functionSearch(pHash, h, zName, nName);\n    while( p ){\n      int score = matchQuality(p, nArg, enc);\n      if( score>bestScore ){\n        pBest = p;\n        bestScore = score;\n      }\n      p = p->pNext;\n    }\n  }\n\n  /* If the createFlag parameter is true and the search did not reveal an\n  ** exact match for the name, number of arguments and encoding, then add a\n  ** new entry to the hash table and return it.\n  */\n  if( createFlag && bestScore<FUNC_PERFECT_MATCH && \n      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){\n    pBest->zName = (char *)&pBest[1];\n    pBest->nArg = (u16)nArg;\n    pBest->iPrefEnc = enc;\n    memcpy(pBest->zName, zName, nName);\n    pBest->zName[nName] = 0;\n    sqlite3FuncDefInsert(&db->aFunc, pBest);\n  }\n\n  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){\n    return pBest;\n  }\n  return 0;\n}\n\n/*\n** Free all resources held by the schema structure. The void* argument points\n** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the \n** pointer itself, it just cleans up subsidiary resources (i.e. the contents\n** of the schema hash tables).\n**\n** The Schema.cache_size variable is not cleared.\n*/\nSQLITE_PRIVATE void sqlite3SchemaClear(void *p){\n  Hash temp1;\n  Hash temp2;\n  HashElem *pElem;\n  Schema *pSchema = (Schema *)p;\n\n  temp1 = pSchema->tblHash;\n  temp2 = pSchema->trigHash;\n  sqlite3HashInit(&pSchema->trigHash);\n  sqlite3HashClear(&pSchema->idxHash);\n  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){\n    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));\n  }\n  sqlite3HashClear(&temp2);\n  sqlite3HashInit(&pSchema->tblHash);\n  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){\n    Table *pTab = sqliteHashData(pElem);\n    sqlite3DeleteTable(0, pTab);\n  }\n  sqlite3HashClear(&temp1);\n  sqlite3HashClear(&pSchema->fkeyHash);\n  pSchema->pSeqTab = 0;\n  if( pSchema->flags & DB_SchemaLoaded ){\n    pSchema->iGeneration++;\n    pSchema->flags &= ~DB_SchemaLoaded;\n  }\n}\n\n/*\n** Find and return the schema associated with a BTree.  Create\n** a new one if necessary.\n*/\nSQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){\n  Schema * p;\n  if( pBt ){\n    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);\n  }else{\n    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));\n  }\n  if( !p ){\n    db->mallocFailed = 1;\n  }else if ( 0==p->file_format ){\n    sqlite3HashInit(&p->tblHash);\n    sqlite3HashInit(&p->idxHash);\n    sqlite3HashInit(&p->trigHash);\n    sqlite3HashInit(&p->fkeyHash);\n    p->enc = SQLITE_UTF8;\n  }\n  return p;\n}\n\n/************** End of callback.c ********************************************/\n/************** Begin file delete.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** in order to generate code for DELETE FROM statements.\n*/\n\n/*\n** While a SrcList can in general represent multiple tables and subqueries\n** (as in the FROM clause of a SELECT statement) in this case it contains\n** the name of a single table, as one might find in an INSERT, DELETE,\n** or UPDATE statement.  Look up that table in the symbol table and\n** return a pointer.  Set an error message and return NULL if the table \n** name is not found or if any other error occurs.\n**\n** The following fields are initialized appropriate in pSrc:\n**\n**    pSrc->a[0].pTab       Pointer to the Table object\n**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one\n**\n*/\nSQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){\n  struct SrcList_item *pItem = pSrc->a;\n  Table *pTab;\n  assert( pItem && pSrc->nSrc==1 );\n  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);\n  sqlite3DeleteTable(pParse->db, pItem->pTab);\n  pItem->pTab = pTab;\n  if( pTab ){\n    pTab->nRef++;\n  }\n  if( sqlite3IndexedByLookup(pParse, pItem) ){\n    pTab = 0;\n  }\n  return pTab;\n}\n\n/*\n** Check to make sure the given table is writable.  If it is not\n** writable, generate an error message and return 1.  If it is\n** writable return 0;\n*/\nSQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){\n  /* A table is not writable under the following circumstances:\n  **\n  **   1) It is a virtual table and no implementation of the xUpdate method\n  **      has been provided, or\n  **   2) It is a system table (i.e. sqlite_master), this call is not\n  **      part of a nested parse and writable_schema pragma has not \n  **      been specified.\n  **\n  ** In either case leave an error message in pParse and return non-zero.\n  */\n  if( ( IsVirtual(pTab) \n     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )\n   || ( (pTab->tabFlags & TF_Readonly)!=0\n     && (pParse->db->flags & SQLITE_WriteSchema)==0\n     && pParse->nested==0 )\n  ){\n    sqlite3ErrorMsg(pParse, \"table %s may not be modified\", pTab->zName);\n    return 1;\n  }\n\n#ifndef SQLITE_OMIT_VIEW\n  if( !viewOk && pTab->pSelect ){\n    sqlite3ErrorMsg(pParse,\"cannot modify %s because it is a view\",pTab->zName);\n    return 1;\n  }\n#endif\n  return 0;\n}\n\n\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n/*\n** Evaluate a view and store its result in an ephemeral table.  The\n** pWhere argument is an optional WHERE clause that restricts the\n** set of rows in the view that are to be added to the ephemeral table.\n*/\nSQLITE_PRIVATE void sqlite3MaterializeView(\n  Parse *pParse,       /* Parsing context */\n  Table *pView,        /* View definition */\n  Expr *pWhere,        /* Optional WHERE clause to be added */\n  int iCur             /* Cursor number for ephemerial table */\n){\n  SelectDest dest;\n  Select *pDup;\n  sqlite3 *db = pParse->db;\n\n  pDup = sqlite3SelectDup(db, pView->pSelect, 0);\n  if( pWhere ){\n    SrcList *pFrom;\n    \n    pWhere = sqlite3ExprDup(db, pWhere, 0);\n    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);\n    if( pFrom ){\n      assert( pFrom->nSrc==1 );\n      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);\n      pFrom->a[0].pSelect = pDup;\n      assert( pFrom->a[0].pOn==0 );\n      assert( pFrom->a[0].pUsing==0 );\n    }else{\n      sqlite3SelectDelete(db, pDup);\n    }\n    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);\n  }\n  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);\n  sqlite3Select(pParse, pDup, &dest);\n  sqlite3SelectDelete(db, pDup);\n}\n#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */\n\n#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)\n/*\n** Generate an expression tree to implement the WHERE, ORDER BY,\n** and LIMIT/OFFSET portion of DELETE and UPDATE statements.\n**\n**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;\n**                            \\__________________________/\n**                               pLimitWhere (pInClause)\n*/\nSQLITE_PRIVATE Expr *sqlite3LimitWhere(\n  Parse *pParse,               /* The parser context */\n  SrcList *pSrc,               /* the FROM clause -- which tables to scan */\n  Expr *pWhere,                /* The WHERE clause.  May be null */\n  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */\n  Expr *pLimit,                /* The LIMIT clause.  May be null */\n  Expr *pOffset,               /* The OFFSET clause.  May be null */\n  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */\n){\n  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */\n  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */\n  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */\n  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */\n  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */\n  Select *pSelect = NULL;      /* Complete SELECT tree */\n\n  /* Check that there isn't an ORDER BY without a LIMIT clause.\n  */\n  if( pOrderBy && (pLimit == 0) ) {\n    sqlite3ErrorMsg(pParse, \"ORDER BY without LIMIT on %s\", zStmtType);\n    goto limit_where_cleanup_2;\n  }\n\n  /* We only need to generate a select expression if there\n  ** is a limit/offset term to enforce.\n  */\n  if( pLimit == 0 ) {\n    /* if pLimit is null, pOffset will always be null as well. */\n    assert( pOffset == 0 );\n    return pWhere;\n  }\n\n  /* Generate a select expression tree to enforce the limit/offset \n  ** term for the DELETE or UPDATE statement.  For example:\n  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1\n  ** becomes:\n  **   DELETE FROM table_a WHERE rowid IN ( \n  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1\n  **   );\n  */\n\n  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);\n  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;\n  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);\n  if( pEList == 0 ) goto limit_where_cleanup_2;\n\n  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree\n  ** and the SELECT subtree. */\n  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);\n  if( pSelectSrc == 0 ) {\n    sqlite3ExprListDelete(pParse->db, pEList);\n    goto limit_where_cleanup_2;\n  }\n\n  /* generate the SELECT expression tree. */\n  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,\n                             pOrderBy,0,pLimit,pOffset);\n  if( pSelect == 0 ) return 0;\n\n  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */\n  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);\n  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;\n  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);\n  if( pInClause == 0 ) goto limit_where_cleanup_1;\n\n  pInClause->x.pSelect = pSelect;\n  pInClause->flags |= EP_xIsSelect;\n  sqlite3ExprSetHeight(pParse, pInClause);\n  return pInClause;\n\n  /* something went wrong. clean up anything allocated. */\nlimit_where_cleanup_1:\n  sqlite3SelectDelete(pParse->db, pSelect);\n  return 0;\n\nlimit_where_cleanup_2:\n  sqlite3ExprDelete(pParse->db, pWhere);\n  sqlite3ExprListDelete(pParse->db, pOrderBy);\n  sqlite3ExprDelete(pParse->db, pLimit);\n  sqlite3ExprDelete(pParse->db, pOffset);\n  return 0;\n}\n#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */\n\n/*\n** Generate code for a DELETE FROM statement.\n**\n**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;\n**                 \\________/       \\________________/\n**                  pTabList              pWhere\n*/\nSQLITE_PRIVATE void sqlite3DeleteFrom(\n  Parse *pParse,         /* The parser context */\n  SrcList *pTabList,     /* The table from which we should delete things */\n  Expr *pWhere           /* The WHERE clause.  May be null */\n){\n  Vdbe *v;               /* The virtual database engine */\n  Table *pTab;           /* The table from which records will be deleted */\n  const char *zDb;       /* Name of database holding pTab */\n  int end, addr = 0;     /* A couple addresses of generated code */\n  int i;                 /* Loop counter */\n  WhereInfo *pWInfo;     /* Information about the WHERE clause */\n  Index *pIdx;           /* For looping over indices of the table */\n  int iCur;              /* VDBE Cursor number for pTab */\n  sqlite3 *db;           /* Main database structure */\n  AuthContext sContext;  /* Authorization context */\n  NameContext sNC;       /* Name context to resolve expressions in */\n  int iDb;               /* Database number */\n  int memCnt = -1;       /* Memory cell used for change counting */\n  int rcauth;            /* Value returned by authorization callback */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;                  /* True if attempting to delete from a view */\n  Trigger *pTrigger;           /* List of table triggers, if required */\n#endif\n\n  memset(&sContext, 0, sizeof(sContext));\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ){\n    goto delete_from_cleanup;\n  }\n  assert( pTabList->nSrc==1 );\n\n  /* Locate the table which we want to delete.  This table has to be\n  ** put in an SrcList structure because some of the subroutines we\n  ** will be calling are designed to work with multiple tables and expect\n  ** an SrcList* parameter instead of just a Table* parameter.\n  */\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 )  goto delete_from_cleanup;\n\n  /* Figure out if we have any triggers and if the table being\n  ** deleted from is a view\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);\n  isView = pTab->pSelect!=0;\n#else\n# define pTrigger 0\n# define isView 0\n#endif\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n\n  /* If pTab is really a view, make sure it has been initialized.\n  */\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto delete_from_cleanup;\n  }\n\n  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){\n    goto delete_from_cleanup;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb<db->nDb );\n  zDb = db->aDb[iDb].zName;\n  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);\n  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );\n  if( rcauth==SQLITE_DENY ){\n    goto delete_from_cleanup;\n  }\n  assert(!isView || pTrigger);\n\n  /* Assign  cursor number to the table and all its indices.\n  */\n  assert( pTabList->nSrc==1 );\n  iCur = pTabList->a[0].iCursor = pParse->nTab++;\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    pParse->nTab++;\n  }\n\n  /* Start the view context\n  */\n  if( isView ){\n    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);\n  }\n\n  /* Begin generating code.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ){\n    goto delete_from_cleanup;\n  }\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n  /* If we are trying to delete from a view, realize that view into\n  ** a ephemeral table.\n  */\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n  if( isView ){\n    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);\n  }\n#endif\n\n  /* Resolve the column names in the WHERE clause.\n  */\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  sNC.pSrcList = pTabList;\n  if( sqlite3ResolveExprNames(&sNC, pWhere) ){\n    goto delete_from_cleanup;\n  }\n\n  /* Initialize the counter of the number of rows deleted, if\n  ** we are counting rows.\n  */\n  if( db->flags & SQLITE_CountRows ){\n    memCnt = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);\n  }\n\n#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION\n  /* Special case: A DELETE without a WHERE clause deletes everything.\n  ** It is easier just to erase the whole table. Prior to version 3.6.5,\n  ** this optimization caused the row change count (the value returned by \n  ** API function sqlite3_count_changes) to be set incorrectly.  */\n  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) \n   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)\n  ){\n    assert( !isView );\n    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,\n                      pTab->zName, P4_STATIC);\n    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n      assert( pIdx->pSchema==pTab->pSchema );\n      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);\n    }\n  }else\n#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */\n  /* The usual case: There is a WHERE clause so we have to scan through\n  ** the table and pick which records to delete.\n  */\n  {\n    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */\n    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */\n    int regRowid;                   /* Actual register containing rowids */\n\n    /* Collect rowids of every row to be deleted.\n    */\n    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);\n    pWInfo = sqlite3WhereBegin(\n        pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0\n    );\n    if( pWInfo==0 ) goto delete_from_cleanup;\n    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);\n    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);\n    if( db->flags & SQLITE_CountRows ){\n      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);\n    }\n    sqlite3WhereEnd(pWInfo);\n\n    /* Delete every item whose key was written to the list during the\n    ** database scan.  We have to delete items after the scan is complete\n    ** because deleting an item can change the scan order.  */\n    end = sqlite3VdbeMakeLabel(v);\n\n    /* Unless this is a view, open cursors for the table we are \n    ** deleting from and all its indices. If this is a view, then the\n    ** only effect this statement has is to fire the INSTEAD OF \n    ** triggers.  */\n    if( !isView ){\n      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);\n    }\n\n    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);\n\n    /* Delete the row */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( IsVirtual(pTab) ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      sqlite3VtabMakeWritable(pParse, pTab);\n      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);\n      sqlite3VdbeChangeP5(v, OE_Abort);\n      sqlite3MayAbort(pParse);\n    }else\n#endif\n    {\n      int count = (pParse->nested==0);    /* True to count changes */\n      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);\n    }\n\n    /* End of the delete loop */\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);\n    sqlite3VdbeResolveLabel(v, end);\n\n    /* Close the cursors open on the table and its indexes. */\n    if( !isView && !IsVirtual(pTab) ){\n      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){\n        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);\n      }\n      sqlite3VdbeAddOp1(v, OP_Close, iCur);\n    }\n  }\n\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /* Return the number of rows that were deleted. If this routine is \n  ** generating code because of a call to sqlite3NestedParse(), do not\n  ** invoke the callback function.\n  */\n  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows deleted\", SQLITE_STATIC);\n  }\n\ndelete_from_cleanup:\n  sqlite3AuthContextPop(&sContext);\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprDelete(db, pWhere);\n  return;\n}\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** thely may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n\n/*\n** This routine generates VDBE code that causes a single row of a\n** single table to be deleted.\n**\n** The VDBE must be in a particular state when this routine is called.\n** These are the requirements:\n**\n**   1.  A read/write cursor pointing to pTab, the table containing the row\n**       to be deleted, must be opened as cursor number $iCur.\n**\n**   2.  Read/write cursors for all indices of pTab must be open as\n**       cursor number base+i for the i-th index.\n**\n**   3.  The record number of the row to be deleted must be stored in\n**       memory cell iRowid.\n**\n** This routine generates code to remove both the table record and all \n** index entries that point to that record.\n*/\nSQLITE_PRIVATE void sqlite3GenerateRowDelete(\n  Parse *pParse,     /* Parsing context */\n  Table *pTab,       /* Table containing the row to be deleted */\n  int iCur,          /* Cursor number for the table */\n  int iRowid,        /* Memory cell that contains the rowid to delete */\n  int count,         /* If non-zero, increment the row change counter */\n  Trigger *pTrigger, /* List of triggers to (potentially) fire */\n  int onconf         /* Default ON CONFLICT policy for triggers */\n){\n  Vdbe *v = pParse->pVdbe;        /* Vdbe */\n  int iOld = 0;                   /* First register in OLD.* array */\n  int iLabel;                     /* Label resolved to end of generated code */\n\n  /* Vdbe is guaranteed to have been allocated by this stage. */\n  assert( v );\n\n  /* Seek cursor iCur to the row to delete. If this row no longer exists \n  ** (this can happen if a trigger program has already deleted it), do\n  ** not attempt to delete it or fire any DELETE triggers.  */\n  iLabel = sqlite3VdbeMakeLabel(v);\n  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);\n \n  /* If there are any triggers to fire, allocate a range of registers to\n  ** use for the old.* references in the triggers.  */\n  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){\n    u32 mask;                     /* Mask of OLD.* columns in use */\n    int iCol;                     /* Iterator used while populating OLD.* */\n\n    /* TODO: Could use temporary registers here. Also could attempt to\n    ** avoid copying the contents of the rowid register.  */\n    mask = sqlite3TriggerColmask(\n        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf\n    );\n    mask |= sqlite3FkOldmask(pParse, pTab);\n    iOld = pParse->nMem+1;\n    pParse->nMem += (1 + pTab->nCol);\n\n    /* Populate the OLD.* pseudo-table register array. These values will be \n    ** used by any BEFORE and AFTER triggers that exist.  */\n    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);\n    for(iCol=0; iCol<pTab->nCol; iCol++){\n      if( mask==0xffffffff || mask&(1<<iCol) ){\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);\n      }\n    }\n\n    /* Invoke BEFORE DELETE trigger programs. */\n    sqlite3CodeRowTrigger(pParse, pTrigger, \n        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel\n    );\n\n    /* Seek the cursor to the row to be deleted again. It may be that\n    ** the BEFORE triggers coded above have already removed the row\n    ** being deleted. Do not attempt to delete the row a second time, and \n    ** do not fire AFTER triggers.  */\n    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);\n\n    /* Do FK processing. This call checks that any FK constraints that\n    ** refer to this table (i.e. constraints attached to other tables) \n    ** are not violated by deleting this row.  */\n    sqlite3FkCheck(pParse, pTab, iOld, 0);\n  }\n\n  /* Delete the index and table entries. Skip this step if pTab is really\n  ** a view (in which case the only effect of the DELETE statement is to\n  ** fire the INSTEAD OF triggers).  */ \n  if( pTab->pSelect==0 ){\n    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);\n    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));\n    if( count ){\n      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);\n    }\n  }\n\n  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to\n  ** handle rows (possibly in other tables) that refer via a foreign key\n  ** to the row just deleted. */ \n  sqlite3FkActions(pParse, pTab, 0, iOld);\n\n  /* Invoke AFTER DELETE trigger programs. */\n  sqlite3CodeRowTrigger(pParse, pTrigger, \n      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel\n  );\n\n  /* Jump here if the row had already been deleted before any BEFORE\n  ** trigger programs were invoked. Or if a trigger program throws a \n  ** RAISE(IGNORE) exception.  */\n  sqlite3VdbeResolveLabel(v, iLabel);\n}\n\n/*\n** This routine generates VDBE code that causes the deletion of all\n** index entries associated with a single row of a single table.\n**\n** The VDBE must be in a particular state when this routine is called.\n** These are the requirements:\n**\n**   1.  A read/write cursor pointing to pTab, the table containing the row\n**       to be deleted, must be opened as cursor number \"iCur\".\n**\n**   2.  Read/write cursors for all indices of pTab must be open as\n**       cursor number iCur+i for the i-th index.\n**\n**   3.  The \"iCur\" cursor must be pointing to the row that is to be\n**       deleted.\n*/\nSQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(\n  Parse *pParse,     /* Parsing and code generating context */\n  Table *pTab,       /* Table containing the row to be deleted */\n  int iCur,          /* Cursor number for the table */\n  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */\n){\n  int i;\n  Index *pIdx;\n  int r1;\n\n  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){\n    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;\n    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);\n    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);\n  }\n}\n\n/*\n** Generate code that will assemble an index key and put it in register\n** regOut.  The key with be for index pIdx which is an index on pTab.\n** iCur is the index of a cursor open on the pTab table and pointing to\n** the entry that needs indexing.\n**\n** Return a register number which is the first in a block of\n** registers that holds the elements of the index key.  The\n** block of registers has already been deallocated by the time\n** this routine returns.\n*/\nSQLITE_PRIVATE int sqlite3GenerateIndexKey(\n  Parse *pParse,     /* Parsing context */\n  Index *pIdx,       /* The index for which to generate a key */\n  int iCur,          /* Cursor number for the pIdx->pTable table */\n  int regOut,        /* Write the new index key to this register */\n  int doMakeRec      /* Run the OP_MakeRecord instruction if true */\n){\n  Vdbe *v = pParse->pVdbe;\n  int j;\n  Table *pTab = pIdx->pTable;\n  int regBase;\n  int nCol;\n\n  nCol = pIdx->nColumn;\n  regBase = sqlite3GetTempRange(pParse, nCol+1);\n  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);\n  for(j=0; j<nCol; j++){\n    int idx = pIdx->aiColumn[j];\n    if( idx==pTab->iPKey ){\n      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);\n      sqlite3ColumnDefault(v, pTab, idx, -1);\n    }\n  }\n  if( doMakeRec ){\n    const char *zAff;\n    if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){\n      zAff = 0;\n    }else{\n      zAff = sqlite3IndexAffinityStr(v, pIdx);\n    }\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);\n    sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);\n  }\n  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);\n  return regBase;\n}\n\n/************** End of delete.c **********************************************/\n/************** Begin file func.c ********************************************/\n/*\n** 2002 February 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the C functions that implement various SQL\n** functions of SQLite.  \n**\n** There is only one exported symbol in this file - the function\n** sqliteRegisterBuildinFunctions() found at the bottom of the file.\n** All other code has file scope.\n*/\n/* #include <stdlib.h> */\n/* #include <assert.h> */\n\n/*\n** Return the collating function associated with a function.\n*/\nstatic CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){\n  return context->pColl;\n}\n\n/*\n** Indicate that the accumulator load should be skipped on this\n** iteration of the aggregate loop.\n*/\nstatic void sqlite3SkipAccumulatorLoad(sqlite3_context *context){\n  context->skipFlag = 1;\n}\n\n/*\n** Implementation of the non-aggregate min() and max() functions\n*/\nstatic void minmaxFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  int mask;    /* 0 for min() or 0xffffffff for max() */\n  int iBest;\n  CollSeq *pColl;\n\n  assert( argc>1 );\n  mask = sqlite3_user_data(context)==0 ? 0 : -1;\n  pColl = sqlite3GetFuncCollSeq(context);\n  assert( pColl );\n  assert( mask==-1 || mask==0 );\n  iBest = 0;\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  for(i=1; i<argc; i++){\n    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;\n    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){\n      testcase( mask==0 );\n      iBest = i;\n    }\n  }\n  sqlite3_result_value(context, argv[iBest]);\n}\n\n/*\n** Return the type of the argument.\n*/\nstatic void typeofFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  const char *z = 0;\n  UNUSED_PARAMETER(NotUsed);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_INTEGER: z = \"integer\"; break;\n    case SQLITE_TEXT:    z = \"text\";    break;\n    case SQLITE_FLOAT:   z = \"real\";    break;\n    case SQLITE_BLOB:    z = \"blob\";    break;\n    default:             z = \"null\";    break;\n  }\n  sqlite3_result_text(context, z, -1, SQLITE_STATIC);\n}\n\n\n/*\n** Implementation of the length() function\n*/\nstatic void lengthFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int len;\n\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_BLOB:\n    case SQLITE_INTEGER:\n    case SQLITE_FLOAT: {\n      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));\n      break;\n    }\n    case SQLITE_TEXT: {\n      const unsigned char *z = sqlite3_value_text(argv[0]);\n      if( z==0 ) return;\n      len = 0;\n      while( *z ){\n        len++;\n        SQLITE_SKIP_UTF8(z);\n      }\n      sqlite3_result_int(context, len);\n      break;\n    }\n    default: {\n      sqlite3_result_null(context);\n      break;\n    }\n  }\n}\n\n/*\n** Implementation of the abs() function.\n**\n** IMP: R-23979-26855 The abs(X) function returns the absolute value of\n** the numeric argument X. \n*/\nstatic void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_INTEGER: {\n      i64 iVal = sqlite3_value_int64(argv[0]);\n      if( iVal<0 ){\n        if( (iVal<<1)==0 ){\n          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then\n          ** abs(X) throws an integer overflow error since there is no\n          ** equivalent positive 64-bit two complement value. */\n          sqlite3_result_error(context, \"integer overflow\", -1);\n          return;\n        }\n        iVal = -iVal;\n      } \n      sqlite3_result_int64(context, iVal);\n      break;\n    }\n    case SQLITE_NULL: {\n      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */\n      sqlite3_result_null(context);\n      break;\n    }\n    default: {\n      /* Because sqlite3_value_double() returns 0.0 if the argument is not\n      ** something that can be converted into a number, we have:\n      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that\n      ** cannot be converted to a numeric value. \n      */\n      double rVal = sqlite3_value_double(argv[0]);\n      if( rVal<0 ) rVal = -rVal;\n      sqlite3_result_double(context, rVal);\n      break;\n    }\n  }\n}\n\n/*\n** Implementation of the substr() function.\n**\n** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.\n** p1 is 1-indexed.  So substr(x,1,1) returns the first character\n** of x.  If x is text, then we actually count UTF-8 characters.\n** If x is a blob, then we count bytes.\n**\n** If p1 is negative, then we begin abs(p1) from the end of x[].\n**\n** If p2 is negative, return the p2 characters preceeding p1.\n*/\nstatic void substrFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *z;\n  const unsigned char *z2;\n  int len;\n  int p0type;\n  i64 p1, p2;\n  int negP2 = 0;\n\n  assert( argc==3 || argc==2 );\n  if( sqlite3_value_type(argv[1])==SQLITE_NULL\n   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)\n  ){\n    return;\n  }\n  p0type = sqlite3_value_type(argv[0]);\n  p1 = sqlite3_value_int(argv[1]);\n  if( p0type==SQLITE_BLOB ){\n    len = sqlite3_value_bytes(argv[0]);\n    z = sqlite3_value_blob(argv[0]);\n    if( z==0 ) return;\n    assert( len==sqlite3_value_bytes(argv[0]) );\n  }else{\n    z = sqlite3_value_text(argv[0]);\n    if( z==0 ) return;\n    len = 0;\n    if( p1<0 ){\n      for(z2=z; *z2; len++){\n        SQLITE_SKIP_UTF8(z2);\n      }\n    }\n  }\n  if( argc==3 ){\n    p2 = sqlite3_value_int(argv[2]);\n    if( p2<0 ){\n      p2 = -p2;\n      negP2 = 1;\n    }\n  }else{\n    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];\n  }\n  if( p1<0 ){\n    p1 += len;\n    if( p1<0 ){\n      p2 += p1;\n      if( p2<0 ) p2 = 0;\n      p1 = 0;\n    }\n  }else if( p1>0 ){\n    p1--;\n  }else if( p2>0 ){\n    p2--;\n  }\n  if( negP2 ){\n    p1 -= p2;\n    if( p1<0 ){\n      p2 += p1;\n      p1 = 0;\n    }\n  }\n  assert( p1>=0 && p2>=0 );\n  if( p0type!=SQLITE_BLOB ){\n    while( *z && p1 ){\n      SQLITE_SKIP_UTF8(z);\n      p1--;\n    }\n    for(z2=z; *z2 && p2; p2--){\n      SQLITE_SKIP_UTF8(z2);\n    }\n    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);\n  }else{\n    if( p1+p2>len ){\n      p2 = len-p1;\n      if( p2<0 ) p2 = 0;\n    }\n    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);\n  }\n}\n\n/*\n** Implementation of the round() function\n*/\n#ifndef SQLITE_OMIT_FLOATING_POINT\nstatic void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  int n = 0;\n  double r;\n  char *zBuf;\n  assert( argc==1 || argc==2 );\n  if( argc==2 ){\n    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;\n    n = sqlite3_value_int(argv[1]);\n    if( n>30 ) n = 30;\n    if( n<0 ) n = 0;\n  }\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  r = sqlite3_value_double(argv[0]);\n  /* If Y==0 and X will fit in a 64-bit int,\n  ** handle the rounding directly,\n  ** otherwise use printf.\n  */\n  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){\n    r = (double)((sqlite_int64)(r+0.5));\n  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){\n    r = -(double)((sqlite_int64)((-r)+0.5));\n  }else{\n    zBuf = sqlite3_mprintf(\"%.*f\",n,r);\n    if( zBuf==0 ){\n      sqlite3_result_error_nomem(context);\n      return;\n    }\n    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);\n    sqlite3_free(zBuf);\n  }\n  sqlite3_result_double(context, r);\n}\n#endif\n\n/*\n** Allocate nByte bytes of space using sqlite3_malloc(). If the\n** allocation fails, call sqlite3_result_error_nomem() to notify\n** the database handle that malloc() has failed and return NULL.\n** If nByte is larger than the maximum string or blob length, then\n** raise an SQLITE_TOOBIG exception and return NULL.\n*/\nstatic void *contextMalloc(sqlite3_context *context, i64 nByte){\n  char *z;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  assert( nByte>0 );\n  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );\n  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );\n  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    sqlite3_result_error_toobig(context);\n    z = 0;\n  }else{\n    z = sqlite3Malloc((int)nByte);\n    if( !z ){\n      sqlite3_result_error_nomem(context);\n    }\n  }\n  return z;\n}\n\n/*\n** Implementation of the upper() and lower() SQL functions.\n*/\nstatic void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  char *z1;\n  const char *z2;\n  int i, n;\n  UNUSED_PARAMETER(argc);\n  z2 = (char*)sqlite3_value_text(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  /* Verify that the call to _bytes() does not invalidate the _text() pointer */\n  assert( z2==(char*)sqlite3_value_text(argv[0]) );\n  if( z2 ){\n    z1 = contextMalloc(context, ((i64)n)+1);\n    if( z1 ){\n      for(i=0; i<n; i++){\n        z1[i] = (char)sqlite3Toupper(z2[i]);\n      }\n      sqlite3_result_text(context, z1, n, sqlite3_free);\n    }\n  }\n}\nstatic void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  char *z1;\n  const char *z2;\n  int i, n;\n  UNUSED_PARAMETER(argc);\n  z2 = (char*)sqlite3_value_text(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  /* Verify that the call to _bytes() does not invalidate the _text() pointer */\n  assert( z2==(char*)sqlite3_value_text(argv[0]) );\n  if( z2 ){\n    z1 = contextMalloc(context, ((i64)n)+1);\n    if( z1 ){\n      for(i=0; i<n; i++){\n        z1[i] = sqlite3Tolower(z2[i]);\n      }\n      sqlite3_result_text(context, z1, n, sqlite3_free);\n    }\n  }\n}\n\n\n#if 0  /* This function is never used. */\n/*\n** The COALESCE() and IFNULL() functions used to be implemented as shown\n** here.  But now they are implemented as VDBE code so that unused arguments\n** do not have to be computed.  This legacy implementation is retained as\n** comment.\n*/\n/*\n** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  \n** All three do the same thing.  They return the first non-NULL\n** argument.\n*/\nstatic void ifnullFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i;\n  for(i=0; i<argc; i++){\n    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){\n      sqlite3_result_value(context, argv[i]);\n      break;\n    }\n  }\n}\n#endif /* NOT USED */\n#define ifnullFunc versionFunc   /* Substitute function - never called */\n\n/*\n** Implementation of random().  Return a random integer.  \n*/\nstatic void randomFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite_int64 r;\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  sqlite3_randomness(sizeof(r), &r);\n  if( r<0 ){\n    /* We need to prevent a random number of 0x8000000000000000 \n    ** (or -9223372036854775808) since when you do abs() of that\n    ** number of you get the same value back again.  To do this\n    ** in a way that is testable, mask the sign bit off of negative\n    ** values, resulting in a positive value.  Then take the \n    ** 2s complement of that positive value.  The end result can\n    ** therefore be no less than -9223372036854775807.\n    */\n    r = -(r & LARGEST_INT64);\n  }\n  sqlite3_result_int64(context, r);\n}\n\n/*\n** Implementation of randomblob(N).  Return a random blob\n** that is N bytes long.\n*/\nstatic void randomBlob(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int n;\n  unsigned char *p;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  n = sqlite3_value_int(argv[0]);\n  if( n<1 ){\n    n = 1;\n  }\n  p = contextMalloc(context, n);\n  if( p ){\n    sqlite3_randomness(n, p);\n    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);\n  }\n}\n\n/*\n** Implementation of the last_insert_rowid() SQL function.  The return\n** value is the same as the sqlite3_last_insert_rowid() API function.\n*/\nstatic void last_insert_rowid(\n  sqlite3_context *context, \n  int NotUsed, \n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a\n  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface\n  ** function. */\n  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));\n}\n\n/*\n** Implementation of the changes() SQL function.\n**\n** IMP: R-62073-11209 The changes() SQL function is a wrapper\n** around the sqlite3_changes() C/C++ function and hence follows the same\n** rules for counting changes.\n*/\nstatic void changes(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  sqlite3_result_int(context, sqlite3_changes(db));\n}\n\n/*\n** Implementation of the total_changes() SQL function.  The return value is\n** the same as the sqlite3_total_changes() API function.\n*/\nstatic void total_changes(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-52756-41993 This function is a wrapper around the\n  ** sqlite3_total_changes() C/C++ interface. */\n  sqlite3_result_int(context, sqlite3_total_changes(db));\n}\n\n/*\n** A structure defining how to do GLOB-style comparisons.\n*/\nstruct compareInfo {\n  u8 matchAll;\n  u8 matchOne;\n  u8 matchSet;\n  u8 noCase;\n};\n\n/*\n** For LIKE and GLOB matching on EBCDIC machines, assume that every\n** character is exactly one byte in size.  Also, all characters are\n** able to participate in upper-case-to-lower-case mappings in EBCDIC\n** whereas only characters less than 0x80 do in ASCII.\n*/\n#if defined(SQLITE_EBCDIC)\n# define sqlite3Utf8Read(A,C)  (*(A++))\n# define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]\n#else\n# define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }\n#endif\n\nstatic const struct compareInfo globInfo = { '*', '?', '[', 0 };\n/* The correct SQL-92 behavior is for the LIKE operator to ignore\n** case.  Thus  'a' LIKE 'A' would be true. */\nstatic const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };\n/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator\n** is case sensitive causing 'a' LIKE 'A' to be false */\nstatic const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };\n\n/*\n** Compare two UTF-8 strings for equality where the first string can\n** potentially be a \"glob\" expression.  Return true (1) if they\n** are the same and false (0) if they are different.\n**\n** Globbing rules:\n**\n**      '*'       Matches any sequence of zero or more characters.\n**\n**      '?'       Matches exactly one character.\n**\n**     [...]      Matches one character from the enclosed list of\n**                characters.\n**\n**     [^...]     Matches one character not in the enclosed list.\n**\n** With the [...] and [^...] matching, a ']' character can be included\n** in the list by making it the first character after '[' or '^'.  A\n** range of characters can be specified using '-'.  Example:\n** \"[a-z]\" matches any single lower-case letter.  To match a '-', make\n** it the last character in the list.\n**\n** This routine is usually quick, but can be N**2 in the worst case.\n**\n** Hints: to match '*' or '?', put them in \"[]\".  Like this:\n**\n**         abc[*]xyz        Matches \"abc*xyz\" only\n*/\nstatic int patternCompare(\n  const u8 *zPattern,              /* The glob pattern */\n  const u8 *zString,               /* The string to compare against the glob */\n  const struct compareInfo *pInfo, /* Information about how to do the compare */\n  u32 esc                          /* The escape character */\n){\n  u32 c, c2;\n  int invert;\n  int seen;\n  u8 matchOne = pInfo->matchOne;\n  u8 matchAll = pInfo->matchAll;\n  u8 matchSet = pInfo->matchSet;\n  u8 noCase = pInfo->noCase; \n  int prevEscape = 0;     /* True if the previous character was 'escape' */\n\n  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){\n    if( !prevEscape && c==matchAll ){\n      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll\n               || c == matchOne ){\n        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){\n          return 0;\n        }\n      }\n      if( c==0 ){\n        return 1;\n      }else if( c==esc ){\n        c = sqlite3Utf8Read(zPattern, &zPattern);\n        if( c==0 ){\n          return 0;\n        }\n      }else if( c==matchSet ){\n        assert( esc==0 );         /* This is GLOB, not LIKE */\n        assert( matchSet<0x80 );  /* '[' is a single-byte character */\n        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){\n          SQLITE_SKIP_UTF8(zString);\n        }\n        return *zString!=0;\n      }\n      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){\n        if( noCase ){\n          GlogUpperToLower(c2);\n          GlogUpperToLower(c);\n          while( c2 != 0 && c2 != c ){\n            c2 = sqlite3Utf8Read(zString, &zString);\n            GlogUpperToLower(c2);\n          }\n        }else{\n          while( c2 != 0 && c2 != c ){\n            c2 = sqlite3Utf8Read(zString, &zString);\n          }\n        }\n        if( c2==0 ) return 0;\n        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;\n      }\n      return 0;\n    }else if( !prevEscape && c==matchOne ){\n      if( sqlite3Utf8Read(zString, &zString)==0 ){\n        return 0;\n      }\n    }else if( c==matchSet ){\n      u32 prior_c = 0;\n      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */\n      seen = 0;\n      invert = 0;\n      c = sqlite3Utf8Read(zString, &zString);\n      if( c==0 ) return 0;\n      c2 = sqlite3Utf8Read(zPattern, &zPattern);\n      if( c2=='^' ){\n        invert = 1;\n        c2 = sqlite3Utf8Read(zPattern, &zPattern);\n      }\n      if( c2==']' ){\n        if( c==']' ) seen = 1;\n        c2 = sqlite3Utf8Read(zPattern, &zPattern);\n      }\n      while( c2 && c2!=']' ){\n        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){\n          c2 = sqlite3Utf8Read(zPattern, &zPattern);\n          if( c>=prior_c && c<=c2 ) seen = 1;\n          prior_c = 0;\n        }else{\n          if( c==c2 ){\n            seen = 1;\n          }\n          prior_c = c2;\n        }\n        c2 = sqlite3Utf8Read(zPattern, &zPattern);\n      }\n      if( c2==0 || (seen ^ invert)==0 ){\n        return 0;\n      }\n    }else if( esc==c && !prevEscape ){\n      prevEscape = 1;\n    }else{\n      c2 = sqlite3Utf8Read(zString, &zString);\n      if( noCase ){\n        GlogUpperToLower(c);\n        GlogUpperToLower(c2);\n      }\n      if( c!=c2 ){\n        return 0;\n      }\n      prevEscape = 0;\n    }\n  }\n  return *zString==0;\n}\n\n/*\n** Count the number of times that the LIKE operator (or GLOB which is\n** just a variation of LIKE) gets called.  This is used for testing\n** only.\n*/\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_like_count = 0;\n#endif\n\n\n/*\n** Implementation of the like() SQL function.  This function implements\n** the build-in LIKE operator.  The first argument to the function is the\n** pattern and the second argument is the string.  So, the SQL statements:\n**\n**       A LIKE B\n**\n** is implemented as like(B,A).\n**\n** This same function (with a different compareInfo structure) computes\n** the GLOB operator.\n*/\nstatic void likeFunc(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const unsigned char *zA, *zB;\n  u32 escape = 0;\n  int nPat;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  zB = sqlite3_value_text(argv[0]);\n  zA = sqlite3_value_text(argv[1]);\n\n  /* Limit the length of the LIKE or GLOB pattern to avoid problems\n  ** of deep recursion and N*N behavior in patternCompare().\n  */\n  nPat = sqlite3_value_bytes(argv[0]);\n  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );\n  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );\n  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){\n    sqlite3_result_error(context, \"LIKE or GLOB pattern too complex\", -1);\n    return;\n  }\n  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */\n\n  if( argc==3 ){\n    /* The escape character string must consist of a single UTF-8 character.\n    ** Otherwise, return an error.\n    */\n    const unsigned char *zEsc = sqlite3_value_text(argv[2]);\n    if( zEsc==0 ) return;\n    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){\n      sqlite3_result_error(context, \n          \"ESCAPE expression must be a single character\", -1);\n      return;\n    }\n    escape = sqlite3Utf8Read(zEsc, &zEsc);\n  }\n  if( zA && zB ){\n    struct compareInfo *pInfo = sqlite3_user_data(context);\n#ifdef SQLITE_TEST\n    sqlite3_like_count++;\n#endif\n    \n    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));\n  }\n}\n\n/*\n** Implementation of the NULLIF(x,y) function.  The result is the first\n** argument if the arguments are different.  The result is NULL if the\n** arguments are equal to each other.\n*/\nstatic void nullifFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **argv\n){\n  CollSeq *pColl = sqlite3GetFuncCollSeq(context);\n  UNUSED_PARAMETER(NotUsed);\n  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){\n    sqlite3_result_value(context, argv[0]);\n  }\n}\n\n/*\n** Implementation of the sqlite_version() function.  The result is the version\n** of the SQLite library that is running.\n*/\nstatic void versionFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-48699-48617 This function is an SQL wrapper around the\n  ** sqlite3_libversion() C-interface. */\n  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);\n}\n\n/*\n** Implementation of the sqlite_source_id() function. The result is a string\n** that identifies the particular version of the source code used to build\n** SQLite.\n*/\nstatic void sourceidFunc(\n  sqlite3_context *context,\n  int NotUsed,\n  sqlite3_value **NotUsed2\n){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  /* IMP: R-24470-31136 This function is an SQL wrapper around the\n  ** sqlite3_sourceid() C interface. */\n  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);\n}\n\n/*\n** Implementation of the sqlite_log() function.  This is a wrapper around\n** sqlite3_log().  The return value is NULL.  The function exists purely for\n** its side-effects.\n*/\nstatic void errlogFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(context);\n  sqlite3_log(sqlite3_value_int(argv[0]), \"%s\", sqlite3_value_text(argv[1]));\n}\n\n/*\n** Implementation of the sqlite_compileoption_used() function.\n** The result is an integer that identifies if the compiler option\n** was used to build SQLite.\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nstatic void compileoptionusedFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zOptName;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL\n  ** function is a wrapper around the sqlite3_compileoption_used() C/C++\n  ** function.\n  */\n  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){\n    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));\n  }\n}\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/*\n** Implementation of the sqlite_compileoption_get() function. \n** The result is a string that identifies the compiler options \n** used to build SQLite.\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nstatic void compileoptiongetFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int n;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function\n  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.\n  */\n  n = sqlite3_value_int(argv[0]);\n  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);\n}\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n/* Array for converting from half-bytes (nybbles) into ASCII hex\n** digits. */\nstatic const char hexdigits[] = {\n  '0', '1', '2', '3', '4', '5', '6', '7',\n  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' \n};\n\n/*\n** EXPERIMENTAL - This is not an official function.  The interface may\n** change.  This function may disappear.  Do not write code that depends\n** on this function.\n**\n** Implementation of the QUOTE() function.  This function takes a single\n** argument.  If the argument is numeric, the return value is the same as\n** the argument.  If the argument is NULL, the return value is the string\n** \"NULL\".  Otherwise, the argument is enclosed in single quotes with\n** single-quote escapes.\n*/\nstatic void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  switch( sqlite3_value_type(argv[0]) ){\n    case SQLITE_FLOAT: {\n      double r1, r2;\n      char zBuf[50];\n      r1 = sqlite3_value_double(argv[0]);\n      sqlite3_snprintf(sizeof(zBuf), zBuf, \"%!.15g\", r1);\n      sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);\n      if( r1!=r2 ){\n        sqlite3_snprintf(sizeof(zBuf), zBuf, \"%!.20e\", r1);\n      }\n      sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n      break;\n    }\n    case SQLITE_INTEGER: {\n      sqlite3_result_value(context, argv[0]);\n      break;\n    }\n    case SQLITE_BLOB: {\n      char *zText = 0;\n      char const *zBlob = sqlite3_value_blob(argv[0]);\n      int nBlob = sqlite3_value_bytes(argv[0]);\n      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */\n      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); \n      if( zText ){\n        int i;\n        for(i=0; i<nBlob; i++){\n          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];\n          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];\n        }\n        zText[(nBlob*2)+2] = '\\'';\n        zText[(nBlob*2)+3] = '\\0';\n        zText[0] = 'X';\n        zText[1] = '\\'';\n        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);\n        sqlite3_free(zText);\n      }\n      break;\n    }\n    case SQLITE_TEXT: {\n      int i,j;\n      u64 n;\n      const unsigned char *zArg = sqlite3_value_text(argv[0]);\n      char *z;\n\n      if( zArg==0 ) return;\n      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\\'' ) n++; }\n      z = contextMalloc(context, ((i64)i)+((i64)n)+3);\n      if( z ){\n        z[0] = '\\'';\n        for(i=0, j=1; zArg[i]; i++){\n          z[j++] = zArg[i];\n          if( zArg[i]=='\\'' ){\n            z[j++] = '\\'';\n          }\n        }\n        z[j++] = '\\'';\n        z[j] = 0;\n        sqlite3_result_text(context, z, j, sqlite3_free);\n      }\n      break;\n    }\n    default: {\n      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );\n      sqlite3_result_text(context, \"NULL\", 4, SQLITE_STATIC);\n      break;\n    }\n  }\n}\n\n/*\n** The hex() function.  Interpret the argument as a blob.  Return\n** a hexadecimal rendering as text.\n*/\nstatic void hexFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int i, n;\n  const unsigned char *pBlob;\n  char *zHex, *z;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  pBlob = sqlite3_value_blob(argv[0]);\n  n = sqlite3_value_bytes(argv[0]);\n  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */\n  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);\n  if( zHex ){\n    for(i=0; i<n; i++, pBlob++){\n      unsigned char c = *pBlob;\n      *(z++) = hexdigits[(c>>4)&0xf];\n      *(z++) = hexdigits[c&0xf];\n    }\n    *z = 0;\n    sqlite3_result_text(context, zHex, n*2, sqlite3_free);\n  }\n}\n\n/*\n** The zeroblob(N) function returns a zero-filled blob of size N bytes.\n*/\nstatic void zeroblobFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  i64 n;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  n = sqlite3_value_int64(argv[0]);\n  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );\n  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );\n  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n    sqlite3_result_error_toobig(context);\n  }else{\n    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */\n  }\n}\n\n/*\n** The replace() function.  Three arguments are all strings: call\n** them A, B, and C. The result is also a string which is derived\n** from A by replacing every occurance of B with C.  The match\n** must be exact.  Collating sequences are not used.\n*/\nstatic void replaceFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *zStr;        /* The input string A */\n  const unsigned char *zPattern;    /* The pattern string B */\n  const unsigned char *zRep;        /* The replacement string C */\n  unsigned char *zOut;              /* The output */\n  int nStr;                /* Size of zStr */\n  int nPattern;            /* Size of zPattern */\n  int nRep;                /* Size of zRep */\n  i64 nOut;                /* Maximum size of zOut */\n  int loopLimit;           /* Last zStr[] that might match zPattern[] */\n  int i, j;                /* Loop counters */\n\n  assert( argc==3 );\n  UNUSED_PARAMETER(argc);\n  zStr = sqlite3_value_text(argv[0]);\n  if( zStr==0 ) return;\n  nStr = sqlite3_value_bytes(argv[0]);\n  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */\n  zPattern = sqlite3_value_text(argv[1]);\n  if( zPattern==0 ){\n    assert( sqlite3_value_type(argv[1])==SQLITE_NULL\n            || sqlite3_context_db_handle(context)->mallocFailed );\n    return;\n  }\n  if( zPattern[0]==0 ){\n    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );\n    sqlite3_result_value(context, argv[0]);\n    return;\n  }\n  nPattern = sqlite3_value_bytes(argv[1]);\n  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */\n  zRep = sqlite3_value_text(argv[2]);\n  if( zRep==0 ) return;\n  nRep = sqlite3_value_bytes(argv[2]);\n  assert( zRep==sqlite3_value_text(argv[2]) );\n  nOut = nStr + 1;\n  assert( nOut<SQLITE_MAX_LENGTH );\n  zOut = contextMalloc(context, (i64)nOut);\n  if( zOut==0 ){\n    return;\n  }\n  loopLimit = nStr - nPattern;  \n  for(i=j=0; i<=loopLimit; i++){\n    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){\n      zOut[j++] = zStr[i];\n    }else{\n      u8 *zOld;\n      sqlite3 *db = sqlite3_context_db_handle(context);\n      nOut += nRep - nPattern;\n      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );\n      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );\n      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){\n        sqlite3_result_error_toobig(context);\n        sqlite3_free(zOut);\n        return;\n      }\n      zOld = zOut;\n      zOut = sqlite3_realloc(zOut, (int)nOut);\n      if( zOut==0 ){\n        sqlite3_result_error_nomem(context);\n        sqlite3_free(zOld);\n        return;\n      }\n      memcpy(&zOut[j], zRep, nRep);\n      j += nRep;\n      i += nPattern-1;\n    }\n  }\n  assert( j+nStr-i+1==nOut );\n  memcpy(&zOut[j], &zStr[i], nStr-i);\n  j += nStr - i;\n  assert( j<=nOut );\n  zOut[j] = 0;\n  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);\n}\n\n/*\n** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.\n** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.\n*/\nstatic void trimFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const unsigned char *zIn;         /* Input string */\n  const unsigned char *zCharSet;    /* Set of characters to trim */\n  int nIn;                          /* Number of bytes in input */\n  int flags;                        /* 1: trimleft  2: trimright  3: trim */\n  int i;                            /* Loop counter */\n  unsigned char *aLen = 0;          /* Length of each character in zCharSet */\n  unsigned char **azChar = 0;       /* Individual characters in zCharSet */\n  int nChar;                        /* Number of characters in zCharSet */\n\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){\n    return;\n  }\n  zIn = sqlite3_value_text(argv[0]);\n  if( zIn==0 ) return;\n  nIn = sqlite3_value_bytes(argv[0]);\n  assert( zIn==sqlite3_value_text(argv[0]) );\n  if( argc==1 ){\n    static const unsigned char lenOne[] = { 1 };\n    static unsigned char * const azOne[] = { (u8*)\" \" };\n    nChar = 1;\n    aLen = (u8*)lenOne;\n    azChar = (unsigned char **)azOne;\n    zCharSet = 0;\n  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){\n    return;\n  }else{\n    const unsigned char *z;\n    for(z=zCharSet, nChar=0; *z; nChar++){\n      SQLITE_SKIP_UTF8(z);\n    }\n    if( nChar>0 ){\n      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));\n      if( azChar==0 ){\n        return;\n      }\n      aLen = (unsigned char*)&azChar[nChar];\n      for(z=zCharSet, nChar=0; *z; nChar++){\n        azChar[nChar] = (unsigned char *)z;\n        SQLITE_SKIP_UTF8(z);\n        aLen[nChar] = (u8)(z - azChar[nChar]);\n      }\n    }\n  }\n  if( nChar>0 ){\n    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));\n    if( flags & 1 ){\n      while( nIn>0 ){\n        int len = 0;\n        for(i=0; i<nChar; i++){\n          len = aLen[i];\n          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;\n        }\n        if( i>=nChar ) break;\n        zIn += len;\n        nIn -= len;\n      }\n    }\n    if( flags & 2 ){\n      while( nIn>0 ){\n        int len = 0;\n        for(i=0; i<nChar; i++){\n          len = aLen[i];\n          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;\n        }\n        if( i>=nChar ) break;\n        nIn -= len;\n      }\n    }\n    if( zCharSet ){\n      sqlite3_free(azChar);\n    }\n  }\n  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);\n}\n\n\n/* IMP: R-25361-16150 This function is omitted from SQLite by default. It\n** is only available if the SQLITE_SOUNDEX compile-time option is used\n** when SQLite is built.\n*/\n#ifdef SQLITE_SOUNDEX\n/*\n** Compute the soundex encoding of a word.\n**\n** IMP: R-59782-00072 The soundex(X) function returns a string that is the\n** soundex encoding of the string X. \n*/\nstatic void soundexFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  char zResult[8];\n  const u8 *zIn;\n  int i, j;\n  static const unsigned char iCode[] = {\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,\n    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,\n    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,\n    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,\n  };\n  assert( argc==1 );\n  zIn = (u8*)sqlite3_value_text(argv[0]);\n  if( zIn==0 ) zIn = (u8*)\"\";\n  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}\n  if( zIn[i] ){\n    u8 prevcode = iCode[zIn[i]&0x7f];\n    zResult[0] = sqlite3Toupper(zIn[i]);\n    for(j=1; j<4 && zIn[i]; i++){\n      int code = iCode[zIn[i]&0x7f];\n      if( code>0 ){\n        if( code!=prevcode ){\n          prevcode = code;\n          zResult[j++] = code + '0';\n        }\n      }else{\n        prevcode = 0;\n      }\n    }\n    while( j<4 ){\n      zResult[j++] = '0';\n    }\n    zResult[j] = 0;\n    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);\n  }else{\n    /* IMP: R-64894-50321 The string \"?000\" is returned if the argument\n    ** is NULL or contains no ASCII alphabetic characters. */\n    sqlite3_result_text(context, \"?000\", 4, SQLITE_STATIC);\n  }\n}\n#endif /* SQLITE_SOUNDEX */\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n/*\n** A function that loads a shared-library extension then returns NULL.\n*/\nstatic void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){\n  const char *zFile = (const char *)sqlite3_value_text(argv[0]);\n  const char *zProc;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n  char *zErrMsg = 0;\n\n  if( argc==2 ){\n    zProc = (const char *)sqlite3_value_text(argv[1]);\n  }else{\n    zProc = 0;\n  }\n  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){\n    sqlite3_result_error(context, zErrMsg, -1);\n    sqlite3_free(zErrMsg);\n  }\n}\n#endif\n\n\n/*\n** An instance of the following structure holds the context of a\n** sum() or avg() aggregate computation.\n*/\ntypedef struct SumCtx SumCtx;\nstruct SumCtx {\n  double rSum;      /* Floating point sum */\n  i64 iSum;         /* Integer sum */   \n  i64 cnt;          /* Number of elements summed */\n  u8 overflow;      /* True if integer overflow seen */\n  u8 approx;        /* True if non-integer value was input to the sum */\n};\n\n/*\n** Routines used to compute the sum, average, and total.\n**\n** The SUM() function follows the (broken) SQL standard which means\n** that it returns NULL if it sums over no inputs.  TOTAL returns\n** 0.0 in that case.  In addition, TOTAL always returns a float where\n** SUM might return an integer if it never encounters a floating point\n** value.  TOTAL never fails, but SUM might through an exception if\n** it overflows an integer.\n*/\nstatic void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){\n  SumCtx *p;\n  int type;\n  assert( argc==1 );\n  UNUSED_PARAMETER(argc);\n  p = sqlite3_aggregate_context(context, sizeof(*p));\n  type = sqlite3_value_numeric_type(argv[0]);\n  if( p && type!=SQLITE_NULL ){\n    p->cnt++;\n    if( type==SQLITE_INTEGER ){\n      i64 v = sqlite3_value_int64(argv[0]);\n      p->rSum += v;\n      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){\n        p->overflow = 1;\n      }\n    }else{\n      p->rSum += sqlite3_value_double(argv[0]);\n      p->approx = 1;\n    }\n  }\n}\nstatic void sumFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  if( p && p->cnt>0 ){\n    if( p->overflow ){\n      sqlite3_result_error(context,\"integer overflow\",-1);\n    }else if( p->approx ){\n      sqlite3_result_double(context, p->rSum);\n    }else{\n      sqlite3_result_int64(context, p->iSum);\n    }\n  }\n}\nstatic void avgFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  if( p && p->cnt>0 ){\n    sqlite3_result_double(context, p->rSum/(double)p->cnt);\n  }\n}\nstatic void totalFinalize(sqlite3_context *context){\n  SumCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n  sqlite3_result_double(context, p ? p->rSum : (double)0);\n}\n\n/*\n** The following structure keeps track of state information for the\n** count() aggregate function.\n*/\ntypedef struct CountCtx CountCtx;\nstruct CountCtx {\n  i64 n;\n};\n\n/*\n** Routines to implement the count() aggregate function.\n*/\nstatic void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){\n  CountCtx *p;\n  p = sqlite3_aggregate_context(context, sizeof(*p));\n  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){\n    p->n++;\n  }\n\n#ifndef SQLITE_OMIT_DEPRECATED\n  /* The sqlite3_aggregate_count() function is deprecated.  But just to make\n  ** sure it still operates correctly, verify that its count agrees with our \n  ** internal count when using count(*) and when the total count can be\n  ** expressed as a 32-bit integer. */\n  assert( argc==1 || p==0 || p->n>0x7fffffff\n          || p->n==sqlite3_aggregate_count(context) );\n#endif\n}   \nstatic void countFinalize(sqlite3_context *context){\n  CountCtx *p;\n  p = sqlite3_aggregate_context(context, 0);\n  sqlite3_result_int64(context, p ? p->n : 0);\n}\n\n/*\n** Routines to implement min() and max() aggregate functions.\n*/\nstatic void minmaxStep(\n  sqlite3_context *context, \n  int NotUsed, \n  sqlite3_value **argv\n){\n  Mem *pArg  = (Mem *)argv[0];\n  Mem *pBest;\n  UNUSED_PARAMETER(NotUsed);\n\n  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));\n  if( !pBest ) return;\n\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){\n    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);\n  }else if( pBest->flags ){\n    int max;\n    int cmp;\n    CollSeq *pColl = sqlite3GetFuncCollSeq(context);\n    /* This step function is used for both the min() and max() aggregates,\n    ** the only difference between the two being that the sense of the\n    ** comparison is inverted. For the max() aggregate, the\n    ** sqlite3_user_data() function returns (void *)-1. For min() it\n    ** returns (void *)db, where db is the sqlite3* database pointer.\n    ** Therefore the next statement sets variable 'max' to 1 for the max()\n    ** aggregate, or 0 for min().\n    */\n    max = sqlite3_user_data(context)!=0;\n    cmp = sqlite3MemCompare(pBest, pArg, pColl);\n    if( (max && cmp<0) || (!max && cmp>0) ){\n      sqlite3VdbeMemCopy(pBest, pArg);\n    }else{\n      sqlite3SkipAccumulatorLoad(context);\n    }\n  }else{\n    sqlite3VdbeMemCopy(pBest, pArg);\n  }\n}\nstatic void minMaxFinalize(sqlite3_context *context){\n  sqlite3_value *pRes;\n  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);\n  if( pRes ){\n    if( pRes->flags ){\n      sqlite3_result_value(context, pRes);\n    }\n    sqlite3VdbeMemRelease(pRes);\n  }\n}\n\n/*\n** group_concat(EXPR, ?SEPARATOR?)\n*/\nstatic void groupConcatStep(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  const char *zVal;\n  StrAccum *pAccum;\n  const char *zSep;\n  int nVal, nSep;\n  assert( argc==1 || argc==2 );\n  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;\n  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));\n\n  if( pAccum ){\n    sqlite3 *db = sqlite3_context_db_handle(context);\n    int firstTerm = pAccum->useMalloc==0;\n    pAccum->useMalloc = 2;\n    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];\n    if( !firstTerm ){\n      if( argc==2 ){\n        zSep = (char*)sqlite3_value_text(argv[1]);\n        nSep = sqlite3_value_bytes(argv[1]);\n      }else{\n        zSep = \",\";\n        nSep = 1;\n      }\n      sqlite3StrAccumAppend(pAccum, zSep, nSep);\n    }\n    zVal = (char*)sqlite3_value_text(argv[0]);\n    nVal = sqlite3_value_bytes(argv[0]);\n    sqlite3StrAccumAppend(pAccum, zVal, nVal);\n  }\n}\nstatic void groupConcatFinalize(sqlite3_context *context){\n  StrAccum *pAccum;\n  pAccum = sqlite3_aggregate_context(context, 0);\n  if( pAccum ){\n    if( pAccum->tooBig ){\n      sqlite3_result_error_toobig(context);\n    }else if( pAccum->mallocFailed ){\n      sqlite3_result_error_nomem(context);\n    }else{    \n      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, \n                          sqlite3_free);\n    }\n  }\n}\n\n/*\n** This routine does per-connection function registration.  Most\n** of the built-in functions above are part of the global function set.\n** This routine only deals with those that are not global.\n*/\nSQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){\n  int rc = sqlite3_overload_function(db, \"MATCH\", 2);\n  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );\n  if( rc==SQLITE_NOMEM ){\n    db->mallocFailed = 1;\n  }\n}\n\n/*\n** Set the LIKEOPT flag on the 2-argument function with the given name.\n*/\nstatic void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){\n  FuncDef *pDef;\n  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),\n                             2, SQLITE_UTF8, 0);\n  if( ALWAYS(pDef) ){\n    pDef->flags = flagVal;\n  }\n}\n\n/*\n** Register the built-in LIKE and GLOB functions.  The caseSensitive\n** parameter determines whether or not the LIKE operator is case\n** sensitive.  GLOB is always case sensitive.\n*/\nSQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){\n  struct compareInfo *pInfo;\n  if( caseSensitive ){\n    pInfo = (struct compareInfo*)&likeInfoAlt;\n  }else{\n    pInfo = (struct compareInfo*)&likeInfoNorm;\n  }\n  sqlite3CreateFunc(db, \"like\", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);\n  sqlite3CreateFunc(db, \"like\", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);\n  sqlite3CreateFunc(db, \"glob\", 2, SQLITE_UTF8, \n      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);\n  setLikeOptFlag(db, \"glob\", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);\n  setLikeOptFlag(db, \"like\", \n      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);\n}\n\n/*\n** pExpr points to an expression which implements a function.  If\n** it is appropriate to apply the LIKE optimization to that function\n** then set aWc[0] through aWc[2] to the wildcard characters and\n** return TRUE.  If the function is not a LIKE-style function then\n** return FALSE.\n*/\nSQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){\n  FuncDef *pDef;\n  if( pExpr->op!=TK_FUNCTION \n   || !pExpr->x.pList \n   || pExpr->x.pList->nExpr!=2\n  ){\n    return 0;\n  }\n  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );\n  pDef = sqlite3FindFunction(db, pExpr->u.zToken, \n                             sqlite3Strlen30(pExpr->u.zToken),\n                             2, SQLITE_UTF8, 0);\n  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){\n    return 0;\n  }\n\n  /* The memcpy() statement assumes that the wildcard characters are\n  ** the first three statements in the compareInfo structure.  The\n  ** asserts() that follow verify that assumption\n  */\n  memcpy(aWc, pDef->pUserData, 3);\n  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );\n  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );\n  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );\n  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;\n  return 1;\n}\n\n/*\n** All all of the FuncDef structures in the aBuiltinFunc[] array above\n** to the global function hash table.  This occurs at start-time (as\n** a consequence of calling sqlite3_initialize()).\n**\n** After this routine runs\n*/\nSQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){\n  /*\n  ** The following array holds FuncDef structures for all of the functions\n  ** defined in this file.\n  **\n  ** The array cannot be constant since changes are made to the\n  ** FuncDef.pHash elements at start-time.  The elements of this array\n  ** are read-only after initialization is complete.\n  */\n  static SQLITE_WSD FuncDef aBuiltinFunc[] = {\n    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),\n    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),\n    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),\n    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),\n    FUNCTION(trim,               1, 3, 0, trimFunc         ),\n    FUNCTION(trim,               2, 3, 0, trimFunc         ),\n    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),\n    FUNCTION(min,                0, 0, 1, 0                ),\n    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),\n    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),\n    FUNCTION(max,                0, 1, 1, 0                ),\n    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),\n    FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),\n    FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),\n    FUNCTION(substr,             2, 0, 0, substrFunc       ),\n    FUNCTION(substr,             3, 0, 0, substrFunc       ),\n    FUNCTION(abs,                1, 0, 0, absFunc          ),\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    FUNCTION(round,              1, 0, 0, roundFunc        ),\n    FUNCTION(round,              2, 0, 0, roundFunc        ),\n#endif\n    FUNCTION(upper,              1, 0, 0, upperFunc        ),\n    FUNCTION(lower,              1, 0, 0, lowerFunc        ),\n    FUNCTION(coalesce,           1, 0, 0, 0                ),\n    FUNCTION(coalesce,           0, 0, 0, 0                ),\n    FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),\n    FUNCTION(hex,                1, 0, 0, hexFunc          ),\n    FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),\n    FUNCTION(random,             0, 0, 0, randomFunc       ),\n    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),\n    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),\n    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),\n    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),\n    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),\n    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n    FUNCTION(quote,              1, 0, 0, quoteFunc        ),\n    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),\n    FUNCTION(changes,            0, 0, 0, changes          ),\n    FUNCTION(total_changes,      0, 0, 0, total_changes    ),\n    FUNCTION(replace,            3, 0, 0, replaceFunc      ),\n    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),\n  #ifdef SQLITE_SOUNDEX\n    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),\n  #endif\n  #ifndef SQLITE_OMIT_LOAD_EXTENSION\n    FUNCTION(load_extension,     1, 0, 0, loadExt          ),\n    FUNCTION(load_extension,     2, 0, 0, loadExt          ),\n  #endif\n    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),\n    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),\n    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),\n /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */\n    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,\"count\",0,0},\n    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),\n    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),\n    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),\n  \n    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n  #ifdef SQLITE_CASE_SENSITIVE_LIKE\n    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),\n  #else\n    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),\n    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),\n  #endif\n  };\n\n  int i;\n  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);\n  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);\n\n  for(i=0; i<ArraySize(aBuiltinFunc); i++){\n    sqlite3FuncDefInsert(pHash, &aFunc[i]);\n  }\n  sqlite3RegisterDateTimeFunctions();\n#ifndef SQLITE_OMIT_ALTERTABLE\n  sqlite3AlterFunctions();\n#endif\n}\n\n/************** End of func.c ************************************************/\n/************** Begin file fkey.c ********************************************/\n/*\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used by the compiler to add foreign key\n** support to compiled SQL statements.\n*/\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n#ifndef SQLITE_OMIT_TRIGGER\n\n/*\n** Deferred and Immediate FKs\n** --------------------------\n**\n** Foreign keys in SQLite come in two flavours: deferred and immediate.\n** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT\n** is returned and the current statement transaction rolled back. If a \n** deferred foreign key constraint is violated, no action is taken \n** immediately. However if the application attempts to commit the \n** transaction before fixing the constraint violation, the attempt fails.\n**\n** Deferred constraints are implemented using a simple counter associated\n** with the database handle. The counter is set to zero each time a \n** database transaction is opened. Each time a statement is executed \n** that causes a foreign key violation, the counter is incremented. Each\n** time a statement is executed that removes an existing violation from\n** the database, the counter is decremented. When the transaction is\n** committed, the commit fails if the current value of the counter is\n** greater than zero. This scheme has two big drawbacks:\n**\n**   * When a commit fails due to a deferred foreign key constraint, \n**     there is no way to tell which foreign constraint is not satisfied,\n**     or which row it is not satisfied for.\n**\n**   * If the database contains foreign key violations when the \n**     transaction is opened, this may cause the mechanism to malfunction.\n**\n** Despite these problems, this approach is adopted as it seems simpler\n** than the alternatives.\n**\n** INSERT operations:\n**\n**   I.1) For each FK for which the table is the child table, search\n**        the parent table for a match. If none is found increment the\n**        constraint counter.\n**\n**   I.2) For each FK for which the table is the parent table, \n**        search the child table for rows that correspond to the new\n**        row in the parent table. Decrement the counter for each row\n**        found (as the constraint is now satisfied).\n**\n** DELETE operations:\n**\n**   D.1) For each FK for which the table is the child table, \n**        search the parent table for a row that corresponds to the \n**        deleted row in the child table. If such a row is not found, \n**        decrement the counter.\n**\n**   D.2) For each FK for which the table is the parent table, search \n**        the child table for rows that correspond to the deleted row \n**        in the parent table. For each found increment the counter.\n**\n** UPDATE operations:\n**\n**   An UPDATE command requires that all 4 steps above are taken, but only\n**   for FK constraints for which the affected columns are actually \n**   modified (values must be compared at runtime).\n**\n** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.\n** This simplifies the implementation a bit.\n**\n** For the purposes of immediate FK constraints, the OR REPLACE conflict\n** resolution is considered to delete rows before the new row is inserted.\n** If a delete caused by OR REPLACE violates an FK constraint, an exception\n** is thrown, even if the FK constraint would be satisfied after the new \n** row is inserted.\n**\n** Immediate constraints are usually handled similarly. The only difference \n** is that the counter used is stored as part of each individual statement\n** object (struct Vdbe). If, after the statement has run, its immediate\n** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT\n** and the statement transaction is rolled back. An exception is an INSERT\n** statement that inserts a single row only (no triggers). In this case,\n** instead of using a counter, an exception is thrown immediately if the\n** INSERT violates a foreign key constraint. This is necessary as such\n** an INSERT does not open a statement transaction.\n**\n** TODO: How should dropping a table be handled? How should renaming a \n** table be handled?\n**\n**\n** Query API Notes\n** ---------------\n**\n** Before coding an UPDATE or DELETE row operation, the code-generator\n** for those two operations needs to know whether or not the operation\n** requires any FK processing and, if so, which columns of the original\n** row are required by the FK processing VDBE code (i.e. if FKs were\n** implemented using triggers, which of the old.* columns would be \n** accessed). No information is required by the code-generator before\n** coding an INSERT operation. The functions used by the UPDATE/DELETE\n** generation code to query for this information are:\n**\n**   sqlite3FkRequired() - Test to see if FK processing is required.\n**   sqlite3FkOldmask()  - Query for the set of required old.* columns.\n**\n**\n** Externally accessible module functions\n** --------------------------------------\n**\n**   sqlite3FkCheck()    - Check for foreign key violations.\n**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.\n**   sqlite3FkDelete()   - Delete an FKey structure.\n*/\n\n/*\n** VDBE Calling Convention\n** -----------------------\n**\n** Example:\n**\n**   For the following INSERT statement:\n**\n**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);\n**     INSERT INTO t1 VALUES(1, 2, 3.1);\n**\n**   Register (x):        2    (type integer)\n**   Register (x+1):      1    (type integer)\n**   Register (x+2):      NULL (type NULL)\n**   Register (x+3):      3.1  (type real)\n*/\n\n/*\n** A foreign key constraint requires that the key columns in the parent\n** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.\n** Given that pParent is the parent table for foreign key constraint pFKey, \n** search the schema a unique index on the parent key columns. \n**\n** If successful, zero is returned. If the parent key is an INTEGER PRIMARY \n** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx \n** is set to point to the unique index. \n** \n** If the parent key consists of a single column (the foreign key constraint\n** is not a composite foreign key), output variable *paiCol is set to NULL.\n** Otherwise, it is set to point to an allocated array of size N, where\n** N is the number of columns in the parent key. The first element of the\n** array is the index of the child table column that is mapped by the FK\n** constraint to the parent table column stored in the left-most column\n** of index *ppIdx. The second element of the array is the index of the\n** child table column that corresponds to the second left-most column of\n** *ppIdx, and so on.\n**\n** If the required index cannot be found, either because:\n**\n**   1) The named parent key columns do not exist, or\n**\n**   2) The named parent key columns do exist, but are not subject to a\n**      UNIQUE or PRIMARY KEY constraint, or\n**\n**   3) No parent key columns were provided explicitly as part of the\n**      foreign key definition, and the parent table does not have a\n**      PRIMARY KEY, or\n**\n**   4) No parent key columns were provided explicitly as part of the\n**      foreign key definition, and the PRIMARY KEY of the parent table \n**      consists of a a different number of columns to the child key in \n**      the child table.\n**\n** then non-zero is returned, and a \"foreign key mismatch\" error loaded\n** into pParse. If an OOM error occurs, non-zero is returned and the\n** pParse->db->mallocFailed flag is set.\n*/\nstatic int locateFkeyIndex(\n  Parse *pParse,                  /* Parse context to store any error in */\n  Table *pParent,                 /* Parent table of FK constraint pFKey */\n  FKey *pFKey,                    /* Foreign key to find index for */\n  Index **ppIdx,                  /* OUT: Unique index on parent table */\n  int **paiCol                    /* OUT: Map of index columns in pFKey */\n){\n  Index *pIdx = 0;                    /* Value to return via *ppIdx */\n  int *aiCol = 0;                     /* Value to return via *paiCol */\n  int nCol = pFKey->nCol;             /* Number of columns in parent key */\n  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */\n\n  /* The caller is responsible for zeroing output parameters. */\n  assert( ppIdx && *ppIdx==0 );\n  assert( !paiCol || *paiCol==0 );\n  assert( pParse );\n\n  /* If this is a non-composite (single column) foreign key, check if it \n  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx \n  ** and *paiCol set to zero and return early. \n  **\n  ** Otherwise, for a composite foreign key (more than one column), allocate\n  ** space for the aiCol array (returned via output parameter *paiCol).\n  ** Non-composite foreign keys do not require the aiCol array.\n  */\n  if( nCol==1 ){\n    /* The FK maps to the IPK if any of the following are true:\n    **\n    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly \n    **      mapped to the primary key of table pParent, or\n    **   2) The FK is explicitly mapped to a column declared as INTEGER\n    **      PRIMARY KEY.\n    */\n    if( pParent->iPKey>=0 ){\n      if( !zKey ) return 0;\n      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;\n    }\n  }else if( paiCol ){\n    assert( nCol>1 );\n    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));\n    if( !aiCol ) return 1;\n    *paiCol = aiCol;\n  }\n\n  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){\n    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ \n      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number\n      ** of columns. If each indexed column corresponds to a foreign key\n      ** column of pFKey, then this index is a winner.  */\n\n      if( zKey==0 ){\n        /* If zKey is NULL, then this foreign key is implicitly mapped to \n        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be \n        ** identified by the test (Index.autoIndex==2).  */\n        if( pIdx->autoIndex==2 ){\n          if( aiCol ){\n            int i;\n            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;\n          }\n          break;\n        }\n      }else{\n        /* If zKey is non-NULL, then this foreign key was declared to\n        ** map to an explicit list of columns in table pParent. Check if this\n        ** index matches those columns. Also, check that the index uses\n        ** the default collation sequences for each column. */\n        int i, j;\n        for(i=0; i<nCol; i++){\n          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */\n          char *zDfltColl;                  /* Def. collation for column */\n          char *zIdxCol;                    /* Name of indexed column */\n\n          /* If the index uses a collation sequence that is different from\n          ** the default collation sequence for the column, this index is\n          ** unusable. Bail out early in this case.  */\n          zDfltColl = pParent->aCol[iCol].zColl;\n          if( !zDfltColl ){\n            zDfltColl = \"BINARY\";\n          }\n          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;\n\n          zIdxCol = pParent->aCol[iCol].zName;\n          for(j=0; j<nCol; j++){\n            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){\n              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;\n              break;\n            }\n          }\n          if( j==nCol ) break;\n        }\n        if( i==nCol ) break;      /* pIdx is usable */\n      }\n    }\n  }\n\n  if( !pIdx ){\n    if( !pParse->disableTriggers ){\n      sqlite3ErrorMsg(pParse, \"foreign key mismatch\");\n    }\n    sqlite3DbFree(pParse->db, aiCol);\n    return 1;\n  }\n\n  *ppIdx = pIdx;\n  return 0;\n}\n\n/*\n** This function is called when a row is inserted into or deleted from the \n** child table of foreign key constraint pFKey. If an SQL UPDATE is executed \n** on the child table of pFKey, this function is invoked twice for each row\n** affected - once to \"delete\" the old row, and then again to \"insert\" the\n** new row.\n**\n** Each time it is called, this function generates VDBE code to locate the\n** row in the parent table that corresponds to the row being inserted into \n** or deleted from the child table. If the parent row can be found, no \n** special action is taken. Otherwise, if the parent row can *not* be\n** found in the parent table:\n**\n**   Operation | FK type   | Action taken\n**   --------------------------------------------------------------------------\n**   INSERT      immediate   Increment the \"immediate constraint counter\".\n**\n**   DELETE      immediate   Decrement the \"immediate constraint counter\".\n**\n**   INSERT      deferred    Increment the \"deferred constraint counter\".\n**\n**   DELETE      deferred    Decrement the \"deferred constraint counter\".\n**\n** These operations are identified in the comment at the top of this file \n** (fkey.c) as \"I.1\" and \"D.1\".\n*/\nstatic void fkLookupParent(\n  Parse *pParse,        /* Parse context */\n  int iDb,              /* Index of database housing pTab */\n  Table *pTab,          /* Parent table of FK pFKey */\n  Index *pIdx,          /* Unique index on parent key columns in pTab */\n  FKey *pFKey,          /* Foreign key constraint */\n  int *aiCol,           /* Map from parent key columns to child table columns */\n  int regData,          /* Address of array containing child table row */\n  int nIncr,            /* Increment constraint counter by this */\n  int isIgnore          /* If true, pretend pTab contains all NULL values */\n){\n  int i;                                    /* Iterator variable */\n  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */\n  int iCur = pParse->nTab - 1;              /* Cursor number to use */\n  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */\n\n  /* If nIncr is less than zero, then check at runtime if there are any\n  ** outstanding constraints to resolve. If there are not, there is no need\n  ** to check if deleting this row resolves any outstanding violations.\n  **\n  ** Check if any of the key columns in the child table row are NULL. If \n  ** any are, then the constraint is considered satisfied. No need to \n  ** search for a matching row in the parent table.  */\n  if( nIncr<0 ){\n    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);\n  }\n  for(i=0; i<pFKey->nCol; i++){\n    int iReg = aiCol[i] + regData + 1;\n    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);\n  }\n\n  if( isIgnore==0 ){\n    if( pIdx==0 ){\n      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY\n      ** column of the parent table (table pTab).  */\n      int iMustBeInt;               /* Address of MustBeInt instruction */\n      int regTemp = sqlite3GetTempReg(pParse);\n  \n      /* Invoke MustBeInt to coerce the child key value to an integer (i.e. \n      ** apply the affinity of the parent key). If this fails, then there\n      ** is no matching parent key. Before using MustBeInt, make a copy of\n      ** the value. Otherwise, the value inserted into the child key column\n      ** will have INTEGER affinity applied to it, which may not be correct.  */\n      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);\n      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);\n  \n      /* If the parent table is the same as the child table, and we are about\n      ** to increment the constraint-counter (i.e. this is an INSERT operation),\n      ** then check if the row being inserted matches itself. If so, do not\n      ** increment the constraint-counter.  */\n      if( pTab==pFKey->pFrom && nIncr==1 ){\n        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);\n      }\n  \n      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);\n      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);\n      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);\n      sqlite3VdbeJumpHere(v, iMustBeInt);\n      sqlite3ReleaseTempReg(pParse, regTemp);\n    }else{\n      int nCol = pFKey->nCol;\n      int regTemp = sqlite3GetTempRange(pParse, nCol);\n      int regRec = sqlite3GetTempReg(pParse);\n      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);\n  \n      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);\n      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);\n      for(i=0; i<nCol; i++){\n        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);\n      }\n  \n      /* If the parent table is the same as the child table, and we are about\n      ** to increment the constraint-counter (i.e. this is an INSERT operation),\n      ** then check if the row being inserted matches itself. If so, do not\n      ** increment the constraint-counter. \n      **\n      ** If any of the parent-key values are NULL, then the row cannot match \n      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any\n      ** of the parent-key values are NULL (at this point it is known that\n      ** none of the child key values are).\n      */\n      if( pTab==pFKey->pFrom && nIncr==1 ){\n        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;\n        for(i=0; i<nCol; i++){\n          int iChild = aiCol[i]+1+regData;\n          int iParent = pIdx->aiColumn[i]+1+regData;\n          assert( aiCol[i]!=pTab->iPKey );\n          if( pIdx->aiColumn[i]==pTab->iPKey ){\n            /* The parent key is a composite key that includes the IPK column */\n            iParent = regData;\n          }\n          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);\n          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);\n        }\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);\n      }\n  \n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);\n      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);\n      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);\n  \n      sqlite3ReleaseTempReg(pParse, regRec);\n      sqlite3ReleaseTempRange(pParse, regTemp, nCol);\n    }\n  }\n\n  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){\n    /* Special case: If this is an INSERT statement that will insert exactly\n    ** one row into the table, raise a constraint immediately instead of\n    ** incrementing a counter. This is necessary as the VM code is being\n    ** generated for will not open a statement transaction.  */\n    assert( nIncr==1 );\n    sqlite3HaltConstraint(\n        pParse, OE_Abort, \"foreign key constraint failed\", P4_STATIC\n    );\n  }else{\n    if( nIncr>0 && pFKey->isDeferred==0 ){\n      sqlite3ParseToplevel(pParse)->mayAbort = 1;\n    }\n    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);\n  }\n\n  sqlite3VdbeResolveLabel(v, iOk);\n  sqlite3VdbeAddOp1(v, OP_Close, iCur);\n}\n\n/*\n** This function is called to generate code executed when a row is deleted\n** from the parent table of foreign key constraint pFKey and, if pFKey is \n** deferred, when a row is inserted into the same table. When generating\n** code for an SQL UPDATE operation, this function may be called twice -\n** once to \"delete\" the old row and once to \"insert\" the new row.\n**\n** The code generated by this function scans through the rows in the child\n** table that correspond to the parent table row being deleted or inserted.\n** For each child row found, one of the following actions is taken:\n**\n**   Operation | FK type   | Action taken\n**   --------------------------------------------------------------------------\n**   DELETE      immediate   Increment the \"immediate constraint counter\".\n**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,\n**                           throw a \"foreign key constraint failed\" exception.\n**\n**   INSERT      immediate   Decrement the \"immediate constraint counter\".\n**\n**   DELETE      deferred    Increment the \"deferred constraint counter\".\n**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,\n**                           throw a \"foreign key constraint failed\" exception.\n**\n**   INSERT      deferred    Decrement the \"deferred constraint counter\".\n**\n** These operations are identified in the comment at the top of this file \n** (fkey.c) as \"I.2\" and \"D.2\".\n*/\nstatic void fkScanChildren(\n  Parse *pParse,                  /* Parse context */\n  SrcList *pSrc,                  /* SrcList containing the table to scan */\n  Table *pTab,\n  Index *pIdx,                    /* Foreign key index */\n  FKey *pFKey,                    /* Foreign key relationship */\n  int *aiCol,                     /* Map from pIdx cols to child table cols */\n  int regData,                    /* Referenced table data starts here */\n  int nIncr                       /* Amount to increment deferred counter by */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  int i;                          /* Iterator variable */\n  Expr *pWhere = 0;               /* WHERE clause to scan with */\n  NameContext sNameContext;       /* Context used to resolve WHERE clause */\n  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */\n  int iFkIfZero = 0;              /* Address of OP_FkIfZero */\n  Vdbe *v = sqlite3GetVdbe(pParse);\n\n  assert( !pIdx || pIdx->pTable==pTab );\n\n  if( nIncr<0 ){\n    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);\n  }\n\n  /* Create an Expr object representing an SQL expression like:\n  **\n  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...\n  **\n  ** The collation sequence used for the comparison should be that of\n  ** the parent key columns. The affinity of the parent key column should\n  ** be applied to each child key value before the comparison takes place.\n  */\n  for(i=0; i<pFKey->nCol; i++){\n    Expr *pLeft;                  /* Value from parent table row */\n    Expr *pRight;                 /* Column ref to child table */\n    Expr *pEq;                    /* Expression (pLeft = pRight) */\n    int iCol;                     /* Index of column in child table */ \n    const char *zCol;             /* Name of column in child table */\n\n    pLeft = sqlite3Expr(db, TK_REGISTER, 0);\n    if( pLeft ){\n      /* Set the collation sequence and affinity of the LHS of each TK_EQ\n      ** expression to the parent key column defaults.  */\n      if( pIdx ){\n        Column *pCol;\n        iCol = pIdx->aiColumn[i];\n        pCol = &pTab->aCol[iCol];\n        if( pTab->iPKey==iCol ) iCol = -1;\n        pLeft->iTable = regData+iCol+1;\n        pLeft->affinity = pCol->affinity;\n        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);\n      }else{\n        pLeft->iTable = regData;\n        pLeft->affinity = SQLITE_AFF_INTEGER;\n      }\n    }\n    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;\n    assert( iCol>=0 );\n    zCol = pFKey->pFrom->aCol[iCol].zName;\n    pRight = sqlite3Expr(db, TK_ID, zCol);\n    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);\n    pWhere = sqlite3ExprAnd(db, pWhere, pEq);\n  }\n\n  /* If the child table is the same as the parent table, and this scan\n  ** is taking place as part of a DELETE operation (operation D.2), omit the\n  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE \n  ** clause, where $rowid is the rowid of the row being deleted.  */\n  if( pTab==pFKey->pFrom && nIncr>0 ){\n    Expr *pEq;                    /* Expression (pLeft = pRight) */\n    Expr *pLeft;                  /* Value from parent table row */\n    Expr *pRight;                 /* Column ref to child table */\n    pLeft = sqlite3Expr(db, TK_REGISTER, 0);\n    pRight = sqlite3Expr(db, TK_COLUMN, 0);\n    if( pLeft && pRight ){\n      pLeft->iTable = regData;\n      pLeft->affinity = SQLITE_AFF_INTEGER;\n      pRight->iTable = pSrc->a[0].iCursor;\n      pRight->iColumn = -1;\n    }\n    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);\n    pWhere = sqlite3ExprAnd(db, pWhere, pEq);\n  }\n\n  /* Resolve the references in the WHERE clause. */\n  memset(&sNameContext, 0, sizeof(NameContext));\n  sNameContext.pSrcList = pSrc;\n  sNameContext.pParse = pParse;\n  sqlite3ResolveExprNames(&sNameContext, pWhere);\n\n  /* Create VDBE to loop through the entries in pSrc that match the WHERE\n  ** clause. If the constraint is not deferred, throw an exception for\n  ** each row found. Otherwise, for deferred constraints, increment the\n  ** deferred constraint counter by nIncr for each row selected.  */\n  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);\n  if( nIncr>0 && pFKey->isDeferred==0 ){\n    sqlite3ParseToplevel(pParse)->mayAbort = 1;\n  }\n  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);\n  if( pWInfo ){\n    sqlite3WhereEnd(pWInfo);\n  }\n\n  /* Clean up the WHERE clause constructed above. */\n  sqlite3ExprDelete(db, pWhere);\n  if( iFkIfZero ){\n    sqlite3VdbeJumpHere(v, iFkIfZero);\n  }\n}\n\n/*\n** This function returns a pointer to the head of a linked list of FK\n** constraints for which table pTab is the parent table. For example,\n** given the following schema:\n**\n**   CREATE TABLE t1(a PRIMARY KEY);\n**   CREATE TABLE t2(b REFERENCES t1(a);\n**\n** Calling this function with table \"t1\" as an argument returns a pointer\n** to the FKey structure representing the foreign key constraint on table\n** \"t2\". Calling this function with \"t2\" as the argument would return a\n** NULL pointer (as there are no FK constraints for which t2 is the parent\n** table).\n*/\nSQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){\n  int nName = sqlite3Strlen30(pTab->zName);\n  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);\n}\n\n/*\n** The second argument is a Trigger structure allocated by the \n** fkActionTrigger() routine. This function deletes the Trigger structure\n** and all of its sub-components.\n**\n** The Trigger structure or any of its sub-components may be allocated from\n** the lookaside buffer belonging to database handle dbMem.\n*/\nstatic void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){\n  if( p ){\n    TriggerStep *pStep = p->step_list;\n    sqlite3ExprDelete(dbMem, pStep->pWhere);\n    sqlite3ExprListDelete(dbMem, pStep->pExprList);\n    sqlite3SelectDelete(dbMem, pStep->pSelect);\n    sqlite3ExprDelete(dbMem, p->pWhen);\n    sqlite3DbFree(dbMem, p);\n  }\n}\n\n/*\n** This function is called to generate code that runs when table pTab is\n** being dropped from the database. The SrcList passed as the second argument\n** to this function contains a single entry guaranteed to resolve to\n** table pTab.\n**\n** Normally, no code is required. However, if either\n**\n**   (a) The table is the parent table of a FK constraint, or\n**   (b) The table is the child table of a deferred FK constraint and it is\n**       determined at runtime that there are outstanding deferred FK \n**       constraint violations in the database,\n**\n** then the equivalent of \"DELETE FROM <tbl>\" is executed before dropping\n** the table from the database. Triggers are disabled while running this\n** DELETE, but foreign key actions are not.\n*/\nSQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){\n  sqlite3 *db = pParse->db;\n  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){\n    int iSkip = 0;\n    Vdbe *v = sqlite3GetVdbe(pParse);\n\n    assert( v );                  /* VDBE has already been allocated */\n    if( sqlite3FkReferences(pTab)==0 ){\n      /* Search for a deferred foreign key constraint for which this table\n      ** is the child table. If one cannot be found, return without \n      ** generating any VDBE code. If one can be found, then jump over\n      ** the entire DELETE if there are no outstanding deferred constraints\n      ** when this statement is run.  */\n      FKey *p;\n      for(p=pTab->pFKey; p; p=p->pNextFrom){\n        if( p->isDeferred ) break;\n      }\n      if( !p ) return;\n      iSkip = sqlite3VdbeMakeLabel(v);\n      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);\n    }\n\n    pParse->disableTriggers = 1;\n    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);\n    pParse->disableTriggers = 0;\n\n    /* If the DELETE has generated immediate foreign key constraint \n    ** violations, halt the VDBE and return an error at this point, before\n    ** any modifications to the schema are made. This is because statement\n    ** transactions are not able to rollback schema changes.  */\n    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);\n    sqlite3HaltConstraint(\n        pParse, OE_Abort, \"foreign key constraint failed\", P4_STATIC\n    );\n\n    if( iSkip ){\n      sqlite3VdbeResolveLabel(v, iSkip);\n    }\n  }\n}\n\n/*\n** This function is called when inserting, deleting or updating a row of\n** table pTab to generate VDBE code to perform foreign key constraint \n** processing for the operation.\n**\n** For a DELETE operation, parameter regOld is passed the index of the\n** first register in an array of (pTab->nCol+1) registers containing the\n** rowid of the row being deleted, followed by each of the column values\n** of the row being deleted, from left to right. Parameter regNew is passed\n** zero in this case.\n**\n** For an INSERT operation, regOld is passed zero and regNew is passed the\n** first register of an array of (pTab->nCol+1) registers containing the new\n** row data.\n**\n** For an UPDATE operation, this function is called twice. Once before\n** the original record is deleted from the table using the calling convention\n** described for DELETE. Then again after the original record is deleted\n** but before the new record is inserted using the INSERT convention. \n*/\nSQLITE_PRIVATE void sqlite3FkCheck(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Row is being deleted from this table */ \n  int regOld,                     /* Previous row data is stored here */\n  int regNew                      /* New row data is stored here */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  FKey *pFKey;                    /* Used to iterate through FKs */\n  int iDb;                        /* Index of database containing pTab */\n  const char *zDb;                /* Name of database containing pTab */\n  int isIgnoreErrors = pParse->disableTriggers;\n\n  /* Exactly one of regOld and regNew should be non-zero. */\n  assert( (regOld==0)!=(regNew==0) );\n\n  /* If foreign-keys are disabled, this function is a no-op. */\n  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;\n\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  zDb = db->aDb[iDb].zName;\n\n  /* Loop through all the foreign key constraints for which pTab is the\n  ** child table (the table that the foreign key definition is part of).  */\n  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){\n    Table *pTo;                   /* Parent table of foreign key pFKey */\n    Index *pIdx = 0;              /* Index on key columns in pTo */\n    int *aiFree = 0;\n    int *aiCol;\n    int iCol;\n    int i;\n    int isIgnore = 0;\n\n    /* Find the parent table of this foreign key. Also find a unique index \n    ** on the parent key columns in the parent table. If either of these \n    ** schema items cannot be located, set an error in pParse and return \n    ** early.  */\n    if( pParse->disableTriggers ){\n      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);\n    }else{\n      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);\n    }\n    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){\n      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );\n      if( !isIgnoreErrors || db->mallocFailed ) return;\n      if( pTo==0 ){\n        /* If isIgnoreErrors is true, then a table is being dropped. In this\n        ** case SQLite runs a \"DELETE FROM xxx\" on the table being dropped\n        ** before actually dropping it in order to check FK constraints.\n        ** If the parent table of an FK constraint on the current table is\n        ** missing, behave as if it is empty. i.e. decrement the relevant\n        ** FK counter for each row of the current table with non-NULL keys.\n        */\n        Vdbe *v = sqlite3GetVdbe(pParse);\n        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;\n        for(i=0; i<pFKey->nCol; i++){\n          int iReg = pFKey->aCol[i].iFrom + regOld + 1;\n          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);\n        }\n        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);\n      }\n      continue;\n    }\n    assert( pFKey->nCol==1 || (aiFree && pIdx) );\n\n    if( aiFree ){\n      aiCol = aiFree;\n    }else{\n      iCol = pFKey->aCol[0].iFrom;\n      aiCol = &iCol;\n    }\n    for(i=0; i<pFKey->nCol; i++){\n      if( aiCol[i]==pTab->iPKey ){\n        aiCol[i] = -1;\n      }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n      /* Request permission to read the parent key columns. If the \n      ** authorization callback returns SQLITE_IGNORE, behave as if any\n      ** values read from the parent table are NULL. */\n      if( db->xAuth ){\n        int rcauth;\n        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;\n        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);\n        isIgnore = (rcauth==SQLITE_IGNORE);\n      }\n#endif\n    }\n\n    /* Take a shared-cache advisory read-lock on the parent table. Allocate \n    ** a cursor to use to search the unique index on the parent key columns \n    ** in the parent table.  */\n    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);\n    pParse->nTab++;\n\n    if( regOld!=0 ){\n      /* A row is being removed from the child table. Search for the parent.\n      ** If the parent does not exist, removing the child row resolves an \n      ** outstanding foreign key constraint violation. */\n      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);\n    }\n    if( regNew!=0 ){\n      /* A row is being added to the child table. If a parent row cannot\n      ** be found, adding the child row has violated the FK constraint. */ \n      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);\n    }\n\n    sqlite3DbFree(db, aiFree);\n  }\n\n  /* Loop through all the foreign key constraints that refer to this table */\n  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){\n    Index *pIdx = 0;              /* Foreign key index for pFKey */\n    SrcList *pSrc;\n    int *aiCol = 0;\n\n    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){\n      assert( regOld==0 && regNew!=0 );\n      /* Inserting a single row into a parent table cannot cause an immediate\n      ** foreign key violation. So do nothing in this case.  */\n      continue;\n    }\n\n    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){\n      if( !isIgnoreErrors || db->mallocFailed ) return;\n      continue;\n    }\n    assert( aiCol || pFKey->nCol==1 );\n\n    /* Create a SrcList structure containing a single table (the table \n    ** the foreign key that refers to this table is attached to). This\n    ** is required for the sqlite3WhereXXX() interface.  */\n    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);\n    if( pSrc ){\n      struct SrcList_item *pItem = pSrc->a;\n      pItem->pTab = pFKey->pFrom;\n      pItem->zName = pFKey->pFrom->zName;\n      pItem->pTab->nRef++;\n      pItem->iCursor = pParse->nTab++;\n  \n      if( regNew!=0 ){\n        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);\n      }\n      if( regOld!=0 ){\n        /* If there is a RESTRICT action configured for the current operation\n        ** on the parent table of this FK, then throw an exception \n        ** immediately if the FK constraint is violated, even if this is a\n        ** deferred trigger. That's what RESTRICT means. To defer checking\n        ** the constraint, the FK should specify NO ACTION (represented\n        ** using OE_None). NO ACTION is the default.  */\n        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);\n      }\n      pItem->zName = 0;\n      sqlite3SrcListDelete(db, pSrc);\n    }\n    sqlite3DbFree(db, aiCol);\n  }\n}\n\n#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))\n\n/*\n** This function is called before generating code to update or delete a \n** row contained in table pTab.\n*/\nSQLITE_PRIVATE u32 sqlite3FkOldmask(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab                     /* Table being modified */\n){\n  u32 mask = 0;\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    FKey *p;\n    int i;\n    for(p=pTab->pFKey; p; p=p->pNextFrom){\n      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);\n    }\n    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n      Index *pIdx = 0;\n      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);\n      if( pIdx ){\n        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);\n      }\n    }\n  }\n  return mask;\n}\n\n/*\n** This function is called before generating code to update or delete a \n** row contained in table pTab. If the operation is a DELETE, then\n** parameter aChange is passed a NULL value. For an UPDATE, aChange points\n** to an array of size N, where N is the number of columns in table pTab.\n** If the i'th column is not modified by the UPDATE, then the corresponding \n** entry in the aChange[] array is set to -1. If the column is modified,\n** the value is 0 or greater. Parameter chngRowid is set to true if the\n** UPDATE statement modifies the rowid fields of the table.\n**\n** If any foreign key processing will be required, this function returns\n** true. If there is no foreign key related processing, this function \n** returns false.\n*/\nSQLITE_PRIVATE int sqlite3FkRequired(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being modified */\n  int *aChange,                   /* Non-NULL for UPDATE operations */\n  int chngRowid                   /* True for UPDATE that affects rowid */\n){\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    if( !aChange ){\n      /* A DELETE operation. Foreign key processing is required if the \n      ** table in question is either the child or parent table for any \n      ** foreign key constraint.  */\n      return (sqlite3FkReferences(pTab) || pTab->pFKey);\n    }else{\n      /* This is an UPDATE. Foreign key processing is only required if the\n      ** operation modifies one or more child or parent key columns. */\n      int i;\n      FKey *p;\n\n      /* Check if any child key columns are being modified. */\n      for(p=pTab->pFKey; p; p=p->pNextFrom){\n        for(i=0; i<p->nCol; i++){\n          int iChildKey = p->aCol[i].iFrom;\n          if( aChange[iChildKey]>=0 ) return 1;\n          if( iChildKey==pTab->iPKey && chngRowid ) return 1;\n        }\n      }\n\n      /* Check if any parent key columns are being modified. */\n      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){\n        for(i=0; i<p->nCol; i++){\n          char *zKey = p->aCol[i].zCol;\n          int iKey;\n          for(iKey=0; iKey<pTab->nCol; iKey++){\n            Column *pCol = &pTab->aCol[iKey];\n            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){\n              if( aChange[iKey]>=0 ) return 1;\n              if( iKey==pTab->iPKey && chngRowid ) return 1;\n            }\n          }\n        }\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** This function is called when an UPDATE or DELETE operation is being \n** compiled on table pTab, which is the parent table of foreign-key pFKey.\n** If the current operation is an UPDATE, then the pChanges parameter is\n** passed a pointer to the list of columns being modified. If it is a\n** DELETE, pChanges is passed a NULL pointer.\n**\n** It returns a pointer to a Trigger structure containing a trigger\n** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.\n** If the action is \"NO ACTION\" or \"RESTRICT\", then a NULL pointer is\n** returned (these actions require no special handling by the triggers\n** sub-system, code for them is created by fkScanChildren()).\n**\n** For example, if pFKey is the foreign key and pTab is table \"p\" in \n** the following schema:\n**\n**   CREATE TABLE p(pk PRIMARY KEY);\n**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);\n**\n** then the returned trigger structure is equivalent to:\n**\n**   CREATE TRIGGER ... DELETE ON p BEGIN\n**     DELETE FROM c WHERE ck = old.pk;\n**   END;\n**\n** The returned pointer is cached as part of the foreign key object. It\n** is eventually freed along with the rest of the foreign key object by \n** sqlite3FkDelete().\n*/\nstatic Trigger *fkActionTrigger(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being updated or deleted from */\n  FKey *pFKey,                    /* Foreign key to get action for */\n  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */\n){\n  sqlite3 *db = pParse->db;       /* Database handle */\n  int action;                     /* One of OE_None, OE_Cascade etc. */\n  Trigger *pTrigger;              /* Trigger definition to return */\n  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */\n\n  action = pFKey->aAction[iAction];\n  pTrigger = pFKey->apTrigger[iAction];\n\n  if( action!=OE_None && !pTrigger ){\n    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */\n    char const *zFrom;            /* Name of child table */\n    int nFrom;                    /* Length in bytes of zFrom */\n    Index *pIdx = 0;              /* Parent key index for this FK */\n    int *aiCol = 0;               /* child table cols -> parent key cols */\n    TriggerStep *pStep = 0;        /* First (only) step of trigger program */\n    Expr *pWhere = 0;             /* WHERE clause of trigger step */\n    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */\n    Select *pSelect = 0;          /* If RESTRICT, \"SELECT RAISE(...)\" */\n    int i;                        /* Iterator variable */\n    Expr *pWhen = 0;              /* WHEN clause for the trigger */\n\n    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;\n    assert( aiCol || pFKey->nCol==1 );\n\n    for(i=0; i<pFKey->nCol; i++){\n      Token tOld = { \"old\", 3 };  /* Literal \"old\" token */\n      Token tNew = { \"new\", 3 };  /* Literal \"new\" token */\n      Token tFromCol;             /* Name of column in child table */\n      Token tToCol;               /* Name of column in parent table */\n      int iFromCol;               /* Idx of column in child table */\n      Expr *pEq;                  /* tFromCol = OLD.tToCol */\n\n      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;\n      assert( iFromCol>=0 );\n      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : \"oid\";\n      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;\n\n      tToCol.n = sqlite3Strlen30(tToCol.z);\n      tFromCol.n = sqlite3Strlen30(tFromCol.z);\n\n      /* Create the expression \"OLD.zToCol = zFromCol\". It is important\n      ** that the \"OLD.zToCol\" term is on the LHS of the = operator, so\n      ** that the affinity and collation sequence associated with the\n      ** parent table are used for the comparison. */\n      pEq = sqlite3PExpr(pParse, TK_EQ,\n          sqlite3PExpr(pParse, TK_DOT, \n            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),\n            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)\n          , 0),\n          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)\n      , 0);\n      pWhere = sqlite3ExprAnd(db, pWhere, pEq);\n\n      /* For ON UPDATE, construct the next term of the WHEN clause.\n      ** The final WHEN clause will be like this:\n      **\n      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)\n      */\n      if( pChanges ){\n        pEq = sqlite3PExpr(pParse, TK_IS,\n            sqlite3PExpr(pParse, TK_DOT, \n              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),\n              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),\n              0),\n            sqlite3PExpr(pParse, TK_DOT, \n              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),\n              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),\n              0),\n            0);\n        pWhen = sqlite3ExprAnd(db, pWhen, pEq);\n      }\n  \n      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){\n        Expr *pNew;\n        if( action==OE_Cascade ){\n          pNew = sqlite3PExpr(pParse, TK_DOT, \n            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),\n            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)\n          , 0);\n        }else if( action==OE_SetDflt ){\n          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;\n          if( pDflt ){\n            pNew = sqlite3ExprDup(db, pDflt, 0);\n          }else{\n            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);\n          }\n        }else{\n          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);\n        }\n        pList = sqlite3ExprListAppend(pParse, pList, pNew);\n        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);\n      }\n    }\n    sqlite3DbFree(db, aiCol);\n\n    zFrom = pFKey->pFrom->zName;\n    nFrom = sqlite3Strlen30(zFrom);\n\n    if( action==OE_Restrict ){\n      Token tFrom;\n      Expr *pRaise; \n\n      tFrom.z = zFrom;\n      tFrom.n = nFrom;\n      pRaise = sqlite3Expr(db, TK_RAISE, \"foreign key constraint failed\");\n      if( pRaise ){\n        pRaise->affinity = OE_Abort;\n      }\n      pSelect = sqlite3SelectNew(pParse, \n          sqlite3ExprListAppend(pParse, 0, pRaise),\n          sqlite3SrcListAppend(db, 0, &tFrom, 0),\n          pWhere,\n          0, 0, 0, 0, 0, 0\n      );\n      pWhere = 0;\n    }\n\n    /* Disable lookaside memory allocation */\n    enableLookaside = db->lookaside.bEnabled;\n    db->lookaside.bEnabled = 0;\n\n    pTrigger = (Trigger *)sqlite3DbMallocZero(db, \n        sizeof(Trigger) +         /* struct Trigger */\n        sizeof(TriggerStep) +     /* Single step in trigger program */\n        nFrom + 1                 /* Space for pStep->target.z */\n    );\n    if( pTrigger ){\n      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];\n      pStep->target.z = (char *)&pStep[1];\n      pStep->target.n = nFrom;\n      memcpy((char *)pStep->target.z, zFrom, nFrom);\n  \n      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);\n      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n      if( pWhen ){\n        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);\n        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);\n      }\n    }\n\n    /* Re-enable the lookaside buffer, if it was disabled earlier. */\n    db->lookaside.bEnabled = enableLookaside;\n\n    sqlite3ExprDelete(db, pWhere);\n    sqlite3ExprDelete(db, pWhen);\n    sqlite3ExprListDelete(db, pList);\n    sqlite3SelectDelete(db, pSelect);\n    if( db->mallocFailed==1 ){\n      fkTriggerDelete(db, pTrigger);\n      return 0;\n    }\n    assert( pStep!=0 );\n\n    switch( action ){\n      case OE_Restrict:\n        pStep->op = TK_SELECT; \n        break;\n      case OE_Cascade: \n        if( !pChanges ){ \n          pStep->op = TK_DELETE; \n          break; \n        }\n      default:\n        pStep->op = TK_UPDATE;\n    }\n    pStep->pTrig = pTrigger;\n    pTrigger->pSchema = pTab->pSchema;\n    pTrigger->pTabSchema = pTab->pSchema;\n    pFKey->apTrigger[iAction] = pTrigger;\n    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);\n  }\n\n  return pTrigger;\n}\n\n/*\n** This function is called when deleting or updating a row to implement\n** any required CASCADE, SET NULL or SET DEFAULT actions.\n*/\nSQLITE_PRIVATE void sqlite3FkActions(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being updated or deleted from */\n  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */\n  int regOld                      /* Address of array containing old row */\n){\n  /* If foreign-key support is enabled, iterate through all FKs that \n  ** refer to table pTab. If there is an action associated with the FK \n  ** for this operation (either update or delete), invoke the associated \n  ** trigger sub-program.  */\n  if( pParse->db->flags&SQLITE_ForeignKeys ){\n    FKey *pFKey;                  /* Iterator variable */\n    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){\n      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);\n      if( pAction ){\n        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);\n      }\n    }\n  }\n}\n\n#endif /* ifndef SQLITE_OMIT_TRIGGER */\n\n/*\n** Free all memory associated with foreign key definitions attached to\n** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash\n** hash table.\n*/\nSQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){\n  FKey *pFKey;                    /* Iterator variable */\n  FKey *pNext;                    /* Copy of pFKey->pNextFrom */\n\n  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );\n  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){\n\n    /* Remove the FK from the fkeyHash hash table. */\n    if( !db || db->pnBytesFreed==0 ){\n      if( pFKey->pPrevTo ){\n        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;\n      }else{\n        void *p = (void *)pFKey->pNextTo;\n        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);\n        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);\n      }\n      if( pFKey->pNextTo ){\n        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;\n      }\n    }\n\n    /* EV: R-30323-21917 Each foreign key constraint in SQLite is\n    ** classified as either immediate or deferred.\n    */\n    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );\n\n    /* Delete any triggers created to implement actions for this FK. */\n#ifndef SQLITE_OMIT_TRIGGER\n    fkTriggerDelete(db, pFKey->apTrigger[0]);\n    fkTriggerDelete(db, pFKey->apTrigger[1]);\n#endif\n\n    pNext = pFKey->pNextFrom;\n    sqlite3DbFree(db, pFKey);\n  }\n}\n#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */\n\n/************** End of fkey.c ************************************************/\n/************** Begin file insert.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle INSERT statements in SQLite.\n*/\n\n/*\n** Generate code that will open a table for reading.\n*/\nSQLITE_PRIVATE void sqlite3OpenTable(\n  Parse *p,       /* Generate code into this VDBE */\n  int iCur,       /* The cursor number of the table */\n  int iDb,        /* The database index in sqlite3.aDb[] */\n  Table *pTab,    /* The table to be opened */\n  int opcode      /* OP_OpenRead or OP_OpenWrite */\n){\n  Vdbe *v;\n  if( IsVirtual(pTab) ) return;\n  v = sqlite3GetVdbe(p);\n  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );\n  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);\n  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);\n  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);\n  VdbeComment((v, \"%s\", pTab->zName));\n}\n\n/*\n** Return a pointer to the column affinity string associated with index\n** pIdx. A column affinity string has one character for each column in \n** the table, according to the affinity of the column:\n**\n**  Character      Column affinity\n**  ------------------------------\n**  'a'            TEXT\n**  'b'            NONE\n**  'c'            NUMERIC\n**  'd'            INTEGER\n**  'e'            REAL\n**\n** An extra 'd' is appended to the end of the string to cover the\n** rowid that appears as the last column in every index.\n**\n** Memory for the buffer containing the column index affinity string\n** is managed along with the rest of the Index structure. It will be\n** released when sqlite3DeleteIndex() is called.\n*/\nSQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){\n  if( !pIdx->zColAff ){\n    /* The first time a column affinity string for a particular index is\n    ** required, it is allocated and populated here. It is then stored as\n    ** a member of the Index structure for subsequent use.\n    **\n    ** The column affinity string will eventually be deleted by\n    ** sqliteDeleteIndex() when the Index structure itself is cleaned\n    ** up.\n    */\n    int n;\n    Table *pTab = pIdx->pTable;\n    sqlite3 *db = sqlite3VdbeDb(v);\n    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);\n    if( !pIdx->zColAff ){\n      db->mallocFailed = 1;\n      return 0;\n    }\n    for(n=0; n<pIdx->nColumn; n++){\n      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;\n    }\n    pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;\n    pIdx->zColAff[n] = 0;\n  }\n \n  return pIdx->zColAff;\n}\n\n/*\n** Set P4 of the most recently inserted opcode to a column affinity\n** string for table pTab. A column affinity string has one character\n** for each column indexed by the index, according to the affinity of the\n** column:\n**\n**  Character      Column affinity\n**  ------------------------------\n**  'a'            TEXT\n**  'b'            NONE\n**  'c'            NUMERIC\n**  'd'            INTEGER\n**  'e'            REAL\n*/\nSQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){\n  /* The first time a column affinity string for a particular table\n  ** is required, it is allocated and populated here. It is then \n  ** stored as a member of the Table structure for subsequent use.\n  **\n  ** The column affinity string will eventually be deleted by\n  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.\n  */\n  if( !pTab->zColAff ){\n    char *zColAff;\n    int i;\n    sqlite3 *db = sqlite3VdbeDb(v);\n\n    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);\n    if( !zColAff ){\n      db->mallocFailed = 1;\n      return;\n    }\n\n    for(i=0; i<pTab->nCol; i++){\n      zColAff[i] = pTab->aCol[i].affinity;\n    }\n    zColAff[pTab->nCol] = '\\0';\n\n    pTab->zColAff = zColAff;\n  }\n\n  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);\n}\n\n/*\n** Return non-zero if the table pTab in database iDb or any of its indices\n** have been opened at any point in the VDBE program beginning at location\n** iStartAddr throught the end of the program.  This is used to see if \n** a statement of the form  \"INSERT INTO <iDb, pTab> SELECT ...\" can \n** run without using temporary table for the results of the SELECT. \n*/\nstatic int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){\n  Vdbe *v = sqlite3GetVdbe(p);\n  int i;\n  int iEnd = sqlite3VdbeCurrentAddr(v);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;\n#endif\n\n  for(i=iStartAddr; i<iEnd; i++){\n    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);\n    assert( pOp!=0 );\n    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){\n      Index *pIndex;\n      int tnum = pOp->p2;\n      if( tnum==pTab->tnum ){\n        return 1;\n      }\n      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){\n        if( tnum==pIndex->tnum ){\n          return 1;\n        }\n      }\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){\n      assert( pOp->p4.pVtab!=0 );\n      assert( pOp->p4type==P4_VTAB );\n      return 1;\n    }\n#endif\n  }\n  return 0;\n}\n\n#ifndef SQLITE_OMIT_AUTOINCREMENT\n/*\n** Locate or create an AutoincInfo structure associated with table pTab\n** which is in database iDb.  Return the register number for the register\n** that holds the maximum rowid.\n**\n** There is at most one AutoincInfo structure per table even if the\n** same table is autoincremented multiple times due to inserts within\n** triggers.  A new AutoincInfo structure is created if this is the\n** first use of table pTab.  On 2nd and subsequent uses, the original\n** AutoincInfo structure is used.\n**\n** Three memory locations are allocated:\n**\n**   (1)  Register to hold the name of the pTab table.\n**   (2)  Register to hold the maximum ROWID of pTab.\n**   (3)  Register to hold the rowid in sqlite_sequence of pTab\n**\n** The 2nd register is the one that is returned.  That is all the\n** insert routine needs to know about.\n*/\nstatic int autoIncBegin(\n  Parse *pParse,      /* Parsing context */\n  int iDb,            /* Index of the database holding pTab */\n  Table *pTab         /* The table we are writing to */\n){\n  int memId = 0;      /* Register holding maximum rowid */\n  if( pTab->tabFlags & TF_Autoincrement ){\n    Parse *pToplevel = sqlite3ParseToplevel(pParse);\n    AutoincInfo *pInfo;\n\n    pInfo = pToplevel->pAinc;\n    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }\n    if( pInfo==0 ){\n      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));\n      if( pInfo==0 ) return 0;\n      pInfo->pNext = pToplevel->pAinc;\n      pToplevel->pAinc = pInfo;\n      pInfo->pTab = pTab;\n      pInfo->iDb = iDb;\n      pToplevel->nMem++;                  /* Register to hold name of table */\n      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */\n      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */\n    }\n    memId = pInfo->regCtr;\n  }\n  return memId;\n}\n\n/*\n** This routine generates code that will initialize all of the\n** register used by the autoincrement tracker.  \n*/\nSQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){\n  AutoincInfo *p;            /* Information about an AUTOINCREMENT */\n  sqlite3 *db = pParse->db;  /* The database connection */\n  Db *pDb;                   /* Database only autoinc table */\n  int memId;                 /* Register holding max rowid */\n  int addr;                  /* A VDBE address */\n  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */\n\n  /* This routine is never called during trigger-generation.  It is\n  ** only called from the top-level */\n  assert( pParse->pTriggerTab==0 );\n  assert( pParse==sqlite3ParseToplevel(pParse) );\n\n  assert( v );   /* We failed long ago if this is not so */\n  for(p = pParse->pAinc; p; p = p->pNext){\n    pDb = &db->aDb[p->iDb];\n    memId = p->regCtr;\n    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );\n    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);\n    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);\n    addr = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);\n    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);\n    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);\n    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);\n    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);\n    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);\n    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);\n    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);\n    sqlite3VdbeAddOp0(v, OP_Close);\n  }\n}\n\n/*\n** Update the maximum rowid for an autoincrement calculation.\n**\n** This routine should be called when the top of the stack holds a\n** new rowid that is about to be inserted.  If that new rowid is\n** larger than the maximum rowid in the memId memory cell, then the\n** memory cell is updated.  The stack is unchanged.\n*/\nstatic void autoIncStep(Parse *pParse, int memId, int regRowid){\n  if( memId>0 ){\n    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);\n  }\n}\n\n/*\n** This routine generates the code needed to write autoincrement\n** maximum rowid values back into the sqlite_sequence register.\n** Every statement that might do an INSERT into an autoincrement\n** table (either directly or through triggers) needs to call this\n** routine just before the \"exit\" code.\n*/\nSQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){\n  AutoincInfo *p;\n  Vdbe *v = pParse->pVdbe;\n  sqlite3 *db = pParse->db;\n\n  assert( v );\n  for(p = pParse->pAinc; p; p = p->pNext){\n    Db *pDb = &db->aDb[p->iDb];\n    int j1, j2, j3, j4, j5;\n    int iRec;\n    int memId = p->regCtr;\n\n    iRec = sqlite3GetTempReg(pParse);\n    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );\n    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);\n    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);\n    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);\n    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);\n    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);\n    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);\n    sqlite3VdbeJumpHere(v, j2);\n    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);\n    j5 = sqlite3VdbeAddOp0(v, OP_Goto);\n    sqlite3VdbeJumpHere(v, j4);\n    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);\n    sqlite3VdbeJumpHere(v, j1);\n    sqlite3VdbeJumpHere(v, j5);\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);\n    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);\n    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n    sqlite3VdbeAddOp0(v, OP_Close);\n    sqlite3ReleaseTempReg(pParse, iRec);\n  }\n}\n#else\n/*\n** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines\n** above are all no-ops\n*/\n# define autoIncBegin(A,B,C) (0)\n# define autoIncStep(A,B,C)\n#endif /* SQLITE_OMIT_AUTOINCREMENT */\n\n\n/* Forward declaration */\nstatic int xferOptimization(\n  Parse *pParse,        /* Parser context */\n  Table *pDest,         /* The table we are inserting into */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  int onError,          /* How to handle constraint errors */\n  int iDbDest           /* The database of pDest */\n);\n\n/*\n** This routine is call to handle SQL of the following forms:\n**\n**    insert into TABLE (IDLIST) values(EXPRLIST)\n**    insert into TABLE (IDLIST) select\n**\n** The IDLIST following the table name is always optional.  If omitted,\n** then a list of all columns for the table is substituted.  The IDLIST\n** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.\n**\n** The pList parameter holds EXPRLIST in the first form of the INSERT\n** statement above, and pSelect is NULL.  For the second form, pList is\n** NULL and pSelect is a pointer to the select statement used to generate\n** data for the insert.\n**\n** The code generated follows one of four templates.  For a simple\n** select with data coming from a VALUES clause, the code executes\n** once straight down through.  Pseudo-code follows (we call this\n** the \"1st template\"):\n**\n**         open write cursor to <table> and its indices\n**         puts VALUES clause expressions onto the stack\n**         write the resulting record into <table>\n**         cleanup\n**\n** The three remaining templates assume the statement is of the form\n**\n**   INSERT INTO <table> SELECT ...\n**\n** If the SELECT clause is of the restricted form \"SELECT * FROM <table2>\" -\n** in other words if the SELECT pulls all columns from a single table\n** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and\n** if <table2> and <table1> are distinct tables but have identical\n** schemas, including all the same indices, then a special optimization\n** is invoked that copies raw records from <table2> over to <table1>.\n** See the xferOptimization() function for the implementation of this\n** template.  This is the 2nd template.\n**\n**         open a write cursor to <table>\n**         open read cursor on <table2>\n**         transfer all records in <table2> over to <table>\n**         close cursors\n**         foreach index on <table>\n**           open a write cursor on the <table> index\n**           open a read cursor on the corresponding <table2> index\n**           transfer all records from the read to the write cursors\n**           close cursors\n**         end foreach\n**\n** The 3rd template is for when the second template does not apply\n** and the SELECT clause does not read from <table> at any time.\n** The generated code follows this template:\n**\n**         EOF <- 0\n**         X <- A\n**         goto B\n**      A: setup for the SELECT\n**         loop over the rows in the SELECT\n**           load values into registers R..R+n\n**           yield X\n**         end loop\n**         cleanup after the SELECT\n**         EOF <- 1\n**         yield X\n**         goto A\n**      B: open write cursor to <table> and its indices\n**      C: yield X\n**         if EOF goto D\n**         insert the select result into <table> from R..R+n\n**         goto C\n**      D: cleanup\n**\n** The 4th template is used if the insert statement takes its\n** values from a SELECT but the data is being inserted into a table\n** that is also read as part of the SELECT.  In the third form,\n** we have to use a intermediate table to store the results of\n** the select.  The template is like this:\n**\n**         EOF <- 0\n**         X <- A\n**         goto B\n**      A: setup for the SELECT\n**         loop over the tables in the SELECT\n**           load value into register R..R+n\n**           yield X\n**         end loop\n**         cleanup after the SELECT\n**         EOF <- 1\n**         yield X\n**         halt-error\n**      B: open temp table\n**      L: yield X\n**         if EOF goto M\n**         insert row from R..R+n into temp table\n**         goto L\n**      M: open write cursor to <table> and its indices\n**         rewind temp table\n**      C: loop over rows of intermediate table\n**           transfer values form intermediate table into <table>\n**         end loop\n**      D: cleanup\n*/\nSQLITE_PRIVATE void sqlite3Insert(\n  Parse *pParse,        /* Parser context */\n  SrcList *pTabList,    /* Name of table into which we are inserting */\n  ExprList *pList,      /* List of values to be inserted */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  IdList *pColumn,      /* Column names corresponding to IDLIST. */\n  int onError           /* How to handle constraint errors */\n){\n  sqlite3 *db;          /* The main database structure */\n  Table *pTab;          /* The table to insert into.  aka TABLE */\n  char *zTab;           /* Name of the table into which we are inserting */\n  const char *zDb;      /* Name of the database holding this table */\n  int i, j, idx;        /* Loop counters */\n  Vdbe *v;              /* Generate code into this virtual machine */\n  Index *pIdx;          /* For looping over indices of the table */\n  int nColumn;          /* Number of columns in the data */\n  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */\n  int baseCur = 0;      /* VDBE Cursor number for pTab */\n  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */\n  int endOfLoop;        /* Label for the end of the insertion loop */\n  int useTempTable = 0; /* Store SELECT results in intermediate table */\n  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */\n  int addrInsTop = 0;   /* Jump to label \"D\" */\n  int addrCont = 0;     /* Top of insert loop. Label \"C\" in templates 3 and 4 */\n  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */\n  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */\n  int iDb;              /* Index of database holding TABLE */\n  Db *pDb;              /* The database containing table being inserted into */\n  int appendFlag = 0;   /* True if the insert is likely to be an append */\n\n  /* Register allocations */\n  int regFromSelect = 0;/* Base register for data coming from SELECT */\n  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */\n  int regRowCount = 0;  /* Memory cell used for the row counter */\n  int regIns;           /* Block of regs holding rowid+data being inserted */\n  int regRowid;         /* registers holding insert rowid */\n  int regData;          /* register holding first column to insert */\n  int regEof = 0;       /* Register recording end of SELECT data */\n  int *aRegIdx = 0;     /* One register allocated to each index */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;                 /* True if attempting to insert into a view */\n  Trigger *pTrigger;          /* List of triggers on pTab, if required */\n  int tmask;                  /* Mask of trigger times */\n#endif\n\n  db = pParse->db;\n  memset(&dest, 0, sizeof(dest));\n  if( pParse->nErr || db->mallocFailed ){\n    goto insert_cleanup;\n  }\n\n  /* Locate the table into which we will be inserting new information.\n  */\n  assert( pTabList->nSrc==1 );\n  zTab = pTabList->a[0].zName;\n  if( NEVER(zTab==0) ) goto insert_cleanup;\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 ){\n    goto insert_cleanup;\n  }\n  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n  assert( iDb<db->nDb );\n  pDb = &db->aDb[iDb];\n  zDb = pDb->zName;\n  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){\n    goto insert_cleanup;\n  }\n\n  /* Figure out if we have any triggers and if the table being\n  ** inserted into is a view\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);\n  isView = pTab->pSelect!=0;\n#else\n# define pTrigger 0\n# define tmask 0\n# define isView 0\n#endif\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );\n\n  /* If pTab is really a view, make sure it has been initialized.\n  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual \n  ** module table).\n  */\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto insert_cleanup;\n  }\n\n  /* Ensure that:\n  *  (a) the table is not read-only, \n  *  (b) that if it is a view then ON INSERT triggers exist\n  */\n  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){\n    goto insert_cleanup;\n  }\n\n  /* Allocate a VDBE\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) goto insert_cleanup;\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);\n\n#ifndef SQLITE_OMIT_XFER_OPT\n  /* If the statement is of the form\n  **\n  **       INSERT INTO <table1> SELECT * FROM <table2>;\n  **\n  ** Then special optimizations can be applied that make the transfer\n  ** very fast and which reduce fragmentation of indices.\n  **\n  ** This is the 2nd template.\n  */\n  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){\n    assert( !pTrigger );\n    assert( pList==0 );\n    goto insert_end;\n  }\n#endif /* SQLITE_OMIT_XFER_OPT */\n\n  /* If this is an AUTOINCREMENT table, look up the sequence number in the\n  ** sqlite_sequence table and store it in memory cell regAutoinc.\n  */\n  regAutoinc = autoIncBegin(pParse, iDb, pTab);\n\n  /* Figure out how many columns of data are supplied.  If the data\n  ** is coming from a SELECT statement, then generate a co-routine that\n  ** produces a single row of the SELECT on each invocation.  The\n  ** co-routine is the common header to the 3rd and 4th templates.\n  */\n  if( pSelect ){\n    /* Data is coming from a SELECT.  Generate code to implement that SELECT\n    ** as a co-routine.  The code is common to both the 3rd and 4th\n    ** templates:\n    **\n    **         EOF <- 0\n    **         X <- A\n    **         goto B\n    **      A: setup for the SELECT\n    **         loop over the tables in the SELECT\n    **           load value into register R..R+n\n    **           yield X\n    **         end loop\n    **         cleanup after the SELECT\n    **         EOF <- 1\n    **         yield X\n    **         halt-error\n    **\n    ** On each invocation of the co-routine, it puts a single row of the\n    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.\n    ** (These output registers are allocated by sqlite3Select().)  When\n    ** the SELECT completes, it sets the EOF flag stored in regEof.\n    */\n    int rc, j1;\n\n    regEof = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */\n    VdbeComment((v, \"SELECT eof flag\"));\n    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);\n    addrSelect = sqlite3VdbeCurrentAddr(v)+2;\n    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iSDParm);\n    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);\n    VdbeComment((v, \"Jump over SELECT coroutine\"));\n\n    /* Resolve the expressions in the SELECT statement and execute it. */\n    rc = sqlite3Select(pParse, pSelect, &dest);\n    assert( pParse->nErr==0 || rc );\n    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){\n      goto insert_cleanup;\n    }\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */\n    sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);   /* yield X */\n    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);\n    VdbeComment((v, \"End of SELECT coroutine\"));\n    sqlite3VdbeJumpHere(v, j1);                          /* label B: */\n\n    regFromSelect = dest.iSdst;\n    assert( pSelect->pEList );\n    nColumn = pSelect->pEList->nExpr;\n    assert( dest.nSdst==nColumn );\n\n    /* Set useTempTable to TRUE if the result of the SELECT statement\n    ** should be written into a temporary table (template 4).  Set to\n    ** FALSE if each* row of the SELECT can be written directly into\n    ** the destination table (template 3).\n    **\n    ** A temp table must be used if the table being updated is also one\n    ** of the tables being read by the SELECT statement.  Also use a \n    ** temp table in the case of row triggers.\n    */\n    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){\n      useTempTable = 1;\n    }\n\n    if( useTempTable ){\n      /* Invoke the coroutine to extract information from the SELECT\n      ** and add it to a transient table srcTab.  The code generated\n      ** here is from the 4th template:\n      **\n      **      B: open temp table\n      **      L: yield X\n      **         if EOF goto M\n      **         insert row from R..R+n into temp table\n      **         goto L\n      **      M: ...\n      */\n      int regRec;          /* Register to hold packed record */\n      int regTempRowid;    /* Register to hold temp table ROWID */\n      int addrTop;         /* Label \"L\" */\n      int addrIf;          /* Address of jump to M */\n\n      srcTab = pParse->nTab++;\n      regRec = sqlite3GetTempReg(pParse);\n      regTempRowid = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);\n      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);\n      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);\n      sqlite3VdbeJumpHere(v, addrIf);\n      sqlite3ReleaseTempReg(pParse, regRec);\n      sqlite3ReleaseTempReg(pParse, regTempRowid);\n    }\n  }else{\n    /* This is the case if the data for the INSERT is coming from a VALUES\n    ** clause\n    */\n    NameContext sNC;\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    srcTab = -1;\n    assert( useTempTable==0 );\n    nColumn = pList ? pList->nExpr : 0;\n    for(i=0; i<nColumn; i++){\n      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){\n        goto insert_cleanup;\n      }\n    }\n  }\n\n  /* Make sure the number of columns in the source data matches the number\n  ** of columns to be inserted into the table.\n  */\n  if( IsVirtual(pTab) ){\n    for(i=0; i<pTab->nCol; i++){\n      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);\n    }\n  }\n  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){\n    sqlite3ErrorMsg(pParse, \n       \"table %S has %d columns but %d values were supplied\",\n       pTabList, 0, pTab->nCol-nHidden, nColumn);\n    goto insert_cleanup;\n  }\n  if( pColumn!=0 && nColumn!=pColumn->nId ){\n    sqlite3ErrorMsg(pParse, \"%d values for %d columns\", nColumn, pColumn->nId);\n    goto insert_cleanup;\n  }\n\n  /* If the INSERT statement included an IDLIST term, then make sure\n  ** all elements of the IDLIST really are columns of the table and \n  ** remember the column indices.\n  **\n  ** If the table has an INTEGER PRIMARY KEY column and that column\n  ** is named in the IDLIST, then record in the keyColumn variable\n  ** the index into IDLIST of the primary key column.  keyColumn is\n  ** the index of the primary key as it appears in IDLIST, not as\n  ** is appears in the original table.  (The index of the primary\n  ** key in the original table is pTab->iPKey.)\n  */\n  if( pColumn ){\n    for(i=0; i<pColumn->nId; i++){\n      pColumn->a[i].idx = -1;\n    }\n    for(i=0; i<pColumn->nId; i++){\n      for(j=0; j<pTab->nCol; j++){\n        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){\n          pColumn->a[i].idx = j;\n          if( j==pTab->iPKey ){\n            keyColumn = i;\n          }\n          break;\n        }\n      }\n      if( j>=pTab->nCol ){\n        if( sqlite3IsRowid(pColumn->a[i].zName) ){\n          keyColumn = i;\n        }else{\n          sqlite3ErrorMsg(pParse, \"table %S has no column named %s\",\n              pTabList, 0, pColumn->a[i].zName);\n          pParse->checkSchema = 1;\n          goto insert_cleanup;\n        }\n      }\n    }\n  }\n\n  /* If there is no IDLIST term but the table has an integer primary\n  ** key, the set the keyColumn variable to the primary key column index\n  ** in the original table definition.\n  */\n  if( pColumn==0 && nColumn>0 ){\n    keyColumn = pTab->iPKey;\n  }\n    \n  /* Initialize the count of rows to be inserted\n  */\n  if( db->flags & SQLITE_CountRows ){\n    regRowCount = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);\n  }\n\n  /* If this is not a view, open the table and and all indices */\n  if( !isView ){\n    int nIdx;\n\n    baseCur = pParse->nTab;\n    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);\n    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));\n    if( aRegIdx==0 ){\n      goto insert_cleanup;\n    }\n    for(i=0; i<nIdx; i++){\n      aRegIdx[i] = ++pParse->nMem;\n    }\n  }\n\n  /* This is the top of the main insertion loop */\n  if( useTempTable ){\n    /* This block codes the top of loop only.  The complete loop is the\n    ** following pseudocode (template 4):\n    **\n    **         rewind temp table\n    **      C: loop over rows of intermediate table\n    **           transfer values form intermediate table into <table>\n    **         end loop\n    **      D: ...\n    */\n    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);\n    addrCont = sqlite3VdbeCurrentAddr(v);\n  }else if( pSelect ){\n    /* This block codes the top of loop only.  The complete loop is the\n    ** following pseudocode (template 3):\n    **\n    **      C: yield X\n    **         if EOF goto D\n    **         insert the select result into <table> from R..R+n\n    **         goto C\n    **      D: ...\n    */\n    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);\n    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);\n  }\n\n  /* Allocate registers for holding the rowid of the new row,\n  ** the content of the new row, and the assemblied row record.\n  */\n  regRowid = regIns = pParse->nMem+1;\n  pParse->nMem += pTab->nCol + 1;\n  if( IsVirtual(pTab) ){\n    regRowid++;\n    pParse->nMem++;\n  }\n  regData = regRowid+1;\n\n  /* Run the BEFORE and INSTEAD OF triggers, if there are any\n  */\n  endOfLoop = sqlite3VdbeMakeLabel(v);\n  if( tmask & TRIGGER_BEFORE ){\n    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);\n\n    /* build the NEW.* reference row.  Note that if there is an INTEGER\n    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be\n    ** translated into a unique ID for the row.  But on a BEFORE trigger,\n    ** we do not know what the unique ID will be (because the insert has\n    ** not happened yet) so we substitute a rowid of -1\n    */\n    if( keyColumn<0 ){\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);\n    }else{\n      int j1;\n      if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);\n      }else{\n        assert( pSelect==0 );  /* Otherwise useTempTable is true */\n        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);\n      }\n      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);\n      sqlite3VdbeJumpHere(v, j1);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);\n    }\n\n    /* Cannot have triggers on a virtual table. If it were possible,\n    ** this block would have to account for hidden column.\n    */\n    assert( !IsVirtual(pTab) );\n\n    /* Create the new column data\n    */\n    for(i=0; i<pTab->nCol; i++){\n      if( pColumn==0 ){\n        j = i;\n      }else{\n        for(j=0; j<pColumn->nId; j++){\n          if( pColumn->a[j].idx==i ) break;\n        }\n      }\n      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){\n        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);\n      }else if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); \n      }else{\n        assert( pSelect==0 ); /* Otherwise useTempTable is true */\n        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);\n      }\n    }\n\n    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,\n    ** do not attempt any conversions before assembling the record.\n    ** If this is a real table, attempt conversions as required by the\n    ** table column affinities.\n    */\n    if( !isView ){\n      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);\n      sqlite3TableAffinityStr(v, pTab);\n    }\n\n    /* Fire BEFORE or INSTEAD OF triggers */\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, \n        pTab, regCols-pTab->nCol-1, onError, endOfLoop);\n\n    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);\n  }\n\n  /* Push the record number for the new entry onto the stack.  The\n  ** record number is a randomly generate integer created by NewRowid\n  ** except when the table has an INTEGER PRIMARY KEY column, in which\n  ** case the record number is the same as that column. \n  */\n  if( !isView ){\n    if( IsVirtual(pTab) ){\n      /* The row that the VUpdate opcode will delete: none */\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);\n    }\n    if( keyColumn>=0 ){\n      if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);\n      }else if( pSelect ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);\n      }else{\n        VdbeOp *pOp;\n        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);\n        pOp = sqlite3VdbeGetOp(v, -1);\n        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){\n          appendFlag = 1;\n          pOp->opcode = OP_NewRowid;\n          pOp->p1 = baseCur;\n          pOp->p2 = regRowid;\n          pOp->p3 = regAutoinc;\n        }\n      }\n      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid\n      ** to generate a unique primary key value.\n      */\n      if( !appendFlag ){\n        int j1;\n        if( !IsVirtual(pTab) ){\n          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);\n          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);\n          sqlite3VdbeJumpHere(v, j1);\n        }else{\n          j1 = sqlite3VdbeCurrentAddr(v);\n          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);\n        }\n        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);\n      }\n    }else if( IsVirtual(pTab) ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);\n      appendFlag = 1;\n    }\n    autoIncStep(pParse, regAutoinc, regRowid);\n\n    /* Push onto the stack, data for all columns of the new entry, beginning\n    ** with the first column.\n    */\n    nHidden = 0;\n    for(i=0; i<pTab->nCol; i++){\n      int iRegStore = regRowid+1+i;\n      if( i==pTab->iPKey ){\n        /* The value of the INTEGER PRIMARY KEY column is always a NULL.\n        ** Whenever this column is read, the record number will be substituted\n        ** in its place.  So will fill this column with a NULL to avoid\n        ** taking up data space with information that will never be used. */\n        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);\n        continue;\n      }\n      if( pColumn==0 ){\n        if( IsHiddenColumn(&pTab->aCol[i]) ){\n          assert( IsVirtual(pTab) );\n          j = -1;\n          nHidden++;\n        }else{\n          j = i - nHidden;\n        }\n      }else{\n        for(j=0; j<pColumn->nId; j++){\n          if( pColumn->a[j].idx==i ) break;\n        }\n      }\n      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){\n        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);\n      }else if( useTempTable ){\n        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); \n      }else if( pSelect ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);\n      }else{\n        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);\n      }\n    }\n\n    /* Generate code to check constraints and generate index keys and\n    ** do the insertion.\n    */\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( IsVirtual(pTab) ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      sqlite3VtabMakeWritable(pParse, pTab);\n      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);\n      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);\n      sqlite3MayAbort(pParse);\n    }else\n#endif\n    {\n      int isReplace;    /* Set to true if constraints may cause a replace */\n      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,\n          keyColumn>=0, 0, onError, endOfLoop, &isReplace\n      );\n      sqlite3FkCheck(pParse, pTab, 0, regIns);\n      sqlite3CompleteInsertion(\n          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0\n      );\n    }\n  }\n\n  /* Update the count of rows that are inserted\n  */\n  if( (db->flags & SQLITE_CountRows)!=0 ){\n    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);\n  }\n\n  if( pTrigger ){\n    /* Code AFTER triggers */\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, \n        pTab, regData-2-pTab->nCol, onError, endOfLoop);\n  }\n\n  /* The bottom of the main insertion loop, if the data source\n  ** is a SELECT statement.\n  */\n  sqlite3VdbeResolveLabel(v, endOfLoop);\n  if( useTempTable ){\n    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);\n    sqlite3VdbeJumpHere(v, addrInsTop);\n    sqlite3VdbeAddOp1(v, OP_Close, srcTab);\n  }else if( pSelect ){\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);\n    sqlite3VdbeJumpHere(v, addrInsTop);\n  }\n\n  if( !IsVirtual(pTab) && !isView ){\n    /* Close all tables opened */\n    sqlite3VdbeAddOp1(v, OP_Close, baseCur);\n    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){\n      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);\n    }\n  }\n\ninsert_end:\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /*\n  ** Return the number of rows inserted. If this routine is \n  ** generating code because of a call to sqlite3NestedParse(), do not\n  ** invoke the callback function.\n  */\n  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows inserted\", SQLITE_STATIC);\n  }\n\ninsert_cleanup:\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprListDelete(db, pList);\n  sqlite3SelectDelete(db, pSelect);\n  sqlite3IdListDelete(db, pColumn);\n  sqlite3DbFree(db, aRegIdx);\n}\n\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** thely may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n#ifdef tmask\n #undef tmask\n#endif\n\n\n/*\n** Generate code to do constraint checks prior to an INSERT or an UPDATE.\n**\n** The input is a range of consecutive registers as follows:\n**\n**    1.  The rowid of the row after the update.\n**\n**    2.  The data in the first column of the entry after the update.\n**\n**    i.  Data from middle columns...\n**\n**    N.  The data in the last column of the entry after the update.\n**\n** The regRowid parameter is the index of the register containing (1).\n**\n** If isUpdate is true and rowidChng is non-zero, then rowidChng contains\n** the address of a register containing the rowid before the update takes\n** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate\n** is false, indicating an INSERT statement, then a non-zero rowidChng \n** indicates that the rowid was explicitly specified as part of the\n** INSERT statement. If rowidChng is false, it means that  the rowid is\n** computed automatically in an insert or that the rowid value is not \n** modified by an update.\n**\n** The code generated by this routine store new index entries into\n** registers identified by aRegIdx[].  No index entry is created for\n** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is\n** the same as the order of indices on the linked list of indices\n** attached to the table.\n**\n** This routine also generates code to check constraints.  NOT NULL,\n** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,\n** then the appropriate action is performed.  There are five possible\n** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.\n**\n**  Constraint type  Action       What Happens\n**  ---------------  ----------   ----------------------------------------\n**  any              ROLLBACK     The current transaction is rolled back and\n**                                sqlite3_exec() returns immediately with a\n**                                return code of SQLITE_CONSTRAINT.\n**\n**  any              ABORT        Back out changes from the current command\n**                                only (do not do a complete rollback) then\n**                                cause sqlite3_exec() to return immediately\n**                                with SQLITE_CONSTRAINT.\n**\n**  any              FAIL         Sqlite3_exec() returns immediately with a\n**                                return code of SQLITE_CONSTRAINT.  The\n**                                transaction is not rolled back and any\n**                                prior changes are retained.\n**\n**  any              IGNORE       The record number and data is popped from\n**                                the stack and there is an immediate jump\n**                                to label ignoreDest.\n**\n**  NOT NULL         REPLACE      The NULL value is replace by the default\n**                                value for that column.  If the default value\n**                                is NULL, the action is the same as ABORT.\n**\n**  UNIQUE           REPLACE      The other row that conflicts with the row\n**                                being inserted is removed.\n**\n**  CHECK            REPLACE      Illegal.  The results in an exception.\n**\n** Which action to take is determined by the overrideError parameter.\n** Or if overrideError==OE_Default, then the pParse->onError parameter\n** is used.  Or if pParse->onError==OE_Default then the onError value\n** for the constraint is used.\n**\n** The calling routine must open a read/write cursor for pTab with\n** cursor number \"baseCur\".  All indices of pTab must also have open\n** read/write cursors with cursor number baseCur+i for the i-th cursor.\n** Except, if there is no possibility of a REPLACE action then\n** cursors do not need to be open for indices where aRegIdx[i]==0.\n*/\nSQLITE_PRIVATE void sqlite3GenerateConstraintChecks(\n  Parse *pParse,      /* The parser context */\n  Table *pTab,        /* the table into which we are inserting */\n  int baseCur,        /* Index of a read/write cursor pointing at pTab */\n  int regRowid,       /* Index of the range of input registers */\n  int *aRegIdx,       /* Register used by each index.  0 for unused indices */\n  int rowidChng,      /* True if the rowid might collide with existing entry */\n  int isUpdate,       /* True for UPDATE, False for INSERT */\n  int overrideError,  /* Override onError to this if not OE_Default */\n  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */\n  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */\n){\n  int i;              /* loop counter */\n  Vdbe *v;            /* VDBE under constrution */\n  int nCol;           /* Number of columns */\n  int onError;        /* Conflict resolution strategy */\n  int j1;             /* Addresss of jump instruction */\n  int j2 = 0, j3;     /* Addresses of jump instructions */\n  int regData;        /* Register containing first data column */\n  int iCur;           /* Table cursor number */\n  Index *pIdx;         /* Pointer to one of the indices */\n  sqlite3 *db;         /* Database connection */\n  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */\n  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;\n\n  db = pParse->db;\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  assert( pTab->pSelect==0 );  /* This table is not a VIEW */\n  nCol = pTab->nCol;\n  regData = regRowid + 1;\n\n  /* Test all NOT NULL constraints.\n  */\n  for(i=0; i<nCol; i++){\n    if( i==pTab->iPKey ){\n      continue;\n    }\n    onError = pTab->aCol[i].notNull;\n    if( onError==OE_None ) continue;\n    if( overrideError!=OE_Default ){\n      onError = overrideError;\n    }else if( onError==OE_Default ){\n      onError = OE_Abort;\n    }\n    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){\n      onError = OE_Abort;\n    }\n    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail\n        || onError==OE_Ignore || onError==OE_Replace );\n    switch( onError ){\n      case OE_Abort:\n        sqlite3MayAbort(pParse);\n      case OE_Rollback:\n      case OE_Fail: {\n        char *zMsg;\n        sqlite3VdbeAddOp3(v, OP_HaltIfNull,\n                                  SQLITE_CONSTRAINT, onError, regData+i);\n        zMsg = sqlite3MPrintf(db, \"%s.%s may not be NULL\",\n                              pTab->zName, pTab->aCol[i].zName);\n        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);\n        break;\n      }\n      case OE_Ignore: {\n        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);\n        break;\n      }\n      default: {\n        assert( onError==OE_Replace );\n        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);\n        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);\n        sqlite3VdbeJumpHere(v, j1);\n        break;\n      }\n    }\n  }\n\n  /* Test all CHECK constraints\n  */\n#ifndef SQLITE_OMIT_CHECK\n  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){\n    ExprList *pCheck = pTab->pCheck;\n    pParse->ckBase = regData;\n    onError = overrideError!=OE_Default ? overrideError : OE_Abort;\n    for(i=0; i<pCheck->nExpr; i++){\n      int allOk = sqlite3VdbeMakeLabel(v);\n      sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);\n      if( onError==OE_Ignore ){\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);\n      }else{\n        char *zConsName = pCheck->a[i].zName;\n        if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */\n        if( zConsName ){\n          zConsName = sqlite3MPrintf(db, \"constraint %s failed\", zConsName);\n        }else{\n          zConsName = 0;\n        }\n        sqlite3HaltConstraint(pParse, onError, zConsName, P4_DYNAMIC);\n      }\n      sqlite3VdbeResolveLabel(v, allOk);\n    }\n  }\n#endif /* !defined(SQLITE_OMIT_CHECK) */\n\n  /* If we have an INTEGER PRIMARY KEY, make sure the primary key\n  ** of the new record does not previously exist.  Except, if this\n  ** is an UPDATE and the primary key is not changing, that is OK.\n  */\n  if( rowidChng ){\n    onError = pTab->keyConf;\n    if( overrideError!=OE_Default ){\n      onError = overrideError;\n    }else if( onError==OE_Default ){\n      onError = OE_Abort;\n    }\n    \n    if( isUpdate ){\n      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);\n    }\n    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);\n    switch( onError ){\n      default: {\n        onError = OE_Abort;\n        /* Fall thru into the next case */\n      }\n      case OE_Rollback:\n      case OE_Abort:\n      case OE_Fail: {\n        sqlite3HaltConstraint(\n          pParse, onError, \"PRIMARY KEY must be unique\", P4_STATIC);\n        break;\n      }\n      case OE_Replace: {\n        /* If there are DELETE triggers on this table and the\n        ** recursive-triggers flag is set, call GenerateRowDelete() to\n        ** remove the conflicting row from the table. This will fire\n        ** the triggers and remove both the table and index b-tree entries.\n        **\n        ** Otherwise, if there are no triggers or the recursive-triggers\n        ** flag is not set, but the table has one or more indexes, call \n        ** GenerateRowIndexDelete(). This removes the index b-tree entries \n        ** only. The table b-tree entry will be replaced by the new entry \n        ** when it is inserted.  \n        **\n        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,\n        ** also invoke MultiWrite() to indicate that this VDBE may require\n        ** statement rollback (if the statement is aborted after the delete\n        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,\n        ** but being more selective here allows statements like:\n        **\n        **   REPLACE INTO t(rowid) VALUES($newrowid)\n        **\n        ** to run without a statement journal if there are no indexes on the\n        ** table.\n        */\n        Trigger *pTrigger = 0;\n        if( db->flags&SQLITE_RecTriggers ){\n          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);\n        }\n        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){\n          sqlite3MultiWrite(pParse);\n          sqlite3GenerateRowDelete(\n              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace\n          );\n        }else if( pTab->pIndex ){\n          sqlite3MultiWrite(pParse);\n          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);\n        }\n        seenReplace = 1;\n        break;\n      }\n      case OE_Ignore: {\n        assert( seenReplace==0 );\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);\n        break;\n      }\n    }\n    sqlite3VdbeJumpHere(v, j3);\n    if( isUpdate ){\n      sqlite3VdbeJumpHere(v, j2);\n    }\n  }\n\n  /* Test all UNIQUE constraints by creating entries for each UNIQUE\n  ** index and making sure that duplicate entries do not already exist.\n  ** Add the new records to the indices as we go.\n  */\n  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){\n    int regIdx;\n    int regR;\n\n    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */\n\n    /* Create a key for accessing the index entry */\n    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);\n    for(i=0; i<pIdx->nColumn; i++){\n      int idx = pIdx->aiColumn[i];\n      if( idx==pTab->iPKey ){\n        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);\n    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);\n    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);\n    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);\n\n    /* Find out what action to take in case there is an indexing conflict */\n    onError = pIdx->onError;\n    if( onError==OE_None ){ \n      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);\n      continue;  /* pIdx is not a UNIQUE index */\n    }\n    if( overrideError!=OE_Default ){\n      onError = overrideError;\n    }else if( onError==OE_Default ){\n      onError = OE_Abort;\n    }\n    if( seenReplace ){\n      if( onError==OE_Ignore ) onError = OE_Replace;\n      else if( onError==OE_Fail ) onError = OE_Abort;\n    }\n    \n    /* Check to see if the new index entry will be unique */\n    regR = sqlite3GetTempReg(pParse);\n    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);\n    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,\n                           regR, SQLITE_INT_TO_PTR(regIdx),\n                           P4_INT32);\n    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);\n\n    /* Generate code that executes if the new index entry is not unique */\n    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail\n        || onError==OE_Ignore || onError==OE_Replace );\n    switch( onError ){\n      case OE_Rollback:\n      case OE_Abort:\n      case OE_Fail: {\n        int j;\n        StrAccum errMsg;\n        const char *zSep;\n        char *zErr;\n\n        sqlite3StrAccumInit(&errMsg, 0, 0, 200);\n        errMsg.db = db;\n        zSep = pIdx->nColumn>1 ? \"columns \" : \"column \";\n        for(j=0; j<pIdx->nColumn; j++){\n          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;\n          sqlite3StrAccumAppend(&errMsg, zSep, -1);\n          zSep = \", \";\n          sqlite3StrAccumAppend(&errMsg, zCol, -1);\n        }\n        sqlite3StrAccumAppend(&errMsg,\n            pIdx->nColumn>1 ? \" are not unique\" : \" is not unique\", -1);\n        zErr = sqlite3StrAccumFinish(&errMsg);\n        sqlite3HaltConstraint(pParse, onError, zErr, 0);\n        sqlite3DbFree(errMsg.db, zErr);\n        break;\n      }\n      case OE_Ignore: {\n        assert( seenReplace==0 );\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);\n        break;\n      }\n      default: {\n        Trigger *pTrigger = 0;\n        assert( onError==OE_Replace );\n        sqlite3MultiWrite(pParse);\n        if( db->flags&SQLITE_RecTriggers ){\n          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);\n        }\n        sqlite3GenerateRowDelete(\n            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace\n        );\n        seenReplace = 1;\n        break;\n      }\n    }\n    sqlite3VdbeJumpHere(v, j3);\n    sqlite3ReleaseTempReg(pParse, regR);\n  }\n  \n  if( pbMayReplace ){\n    *pbMayReplace = seenReplace;\n  }\n}\n\n/*\n** This routine generates code to finish the INSERT or UPDATE operation\n** that was started by a prior call to sqlite3GenerateConstraintChecks.\n** A consecutive range of registers starting at regRowid contains the\n** rowid and the content to be inserted.\n**\n** The arguments to this routine should be the same as the first six\n** arguments to sqlite3GenerateConstraintChecks.\n*/\nSQLITE_PRIVATE void sqlite3CompleteInsertion(\n  Parse *pParse,      /* The parser context */\n  Table *pTab,        /* the table into which we are inserting */\n  int baseCur,        /* Index of a read/write cursor pointing at pTab */\n  int regRowid,       /* Range of content */\n  int *aRegIdx,       /* Register used by each index.  0 for unused indices */\n  int isUpdate,       /* True for UPDATE, False for INSERT */\n  int appendBias,     /* True if this is likely to be an append */\n  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */\n){\n  int i;\n  Vdbe *v;\n  int nIdx;\n  Index *pIdx;\n  u8 pik_flags;\n  int regData;\n  int regRec;\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  assert( pTab->pSelect==0 );  /* This table is not a VIEW */\n  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}\n  for(i=nIdx-1; i>=0; i--){\n    if( aRegIdx[i]==0 ) continue;\n    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);\n    if( useSeekResult ){\n      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n    }\n  }\n  regData = regRowid + 1;\n  regRec = sqlite3GetTempReg(pParse);\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);\n  sqlite3TableAffinityStr(v, pTab);\n  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);\n  if( pParse->nested ){\n    pik_flags = 0;\n  }else{\n    pik_flags = OPFLAG_NCHANGE;\n    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);\n  }\n  if( appendBias ){\n    pik_flags |= OPFLAG_APPEND;\n  }\n  if( useSeekResult ){\n    pik_flags |= OPFLAG_USESEEKRESULT;\n  }\n  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);\n  if( !pParse->nested ){\n    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);\n  }\n  sqlite3VdbeChangeP5(v, pik_flags);\n}\n\n/*\n** Generate code that will open cursors for a table and for all\n** indices of that table.  The \"baseCur\" parameter is the cursor number used\n** for the table.  Indices are opened on subsequent cursors.\n**\n** Return the number of indices on the table.\n*/\nSQLITE_PRIVATE int sqlite3OpenTableAndIndices(\n  Parse *pParse,   /* Parsing context */\n  Table *pTab,     /* Table to be opened */\n  int baseCur,     /* Cursor number assigned to the table */\n  int op           /* OP_OpenRead or OP_OpenWrite */\n){\n  int i;\n  int iDb;\n  Index *pIdx;\n  Vdbe *v;\n\n  if( IsVirtual(pTab) ) return 0;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );\n  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);\n  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){\n    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);\n    assert( pIdx->pSchema==pTab->pSchema );\n    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,\n                      (char*)pKey, P4_KEYINFO_HANDOFF);\n    VdbeComment((v, \"%s\", pIdx->zName));\n  }\n  if( pParse->nTab<baseCur+i ){\n    pParse->nTab = baseCur+i;\n  }\n  return i-1;\n}\n\n\n#ifdef SQLITE_TEST\n/*\n** The following global variable is incremented whenever the\n** transfer optimization is used.  This is used for testing\n** purposes only - to make sure the transfer optimization really\n** is happening when it is suppose to.\n*/\nSQLITE_API int sqlite3_xferopt_count;\n#endif /* SQLITE_TEST */\n\n\n#ifndef SQLITE_OMIT_XFER_OPT\n/*\n** Check to collation names to see if they are compatible.\n*/\nstatic int xferCompatibleCollation(const char *z1, const char *z2){\n  if( z1==0 ){\n    return z2==0;\n  }\n  if( z2==0 ){\n    return 0;\n  }\n  return sqlite3StrICmp(z1, z2)==0;\n}\n\n\n/*\n** Check to see if index pSrc is compatible as a source of data\n** for index pDest in an insert transfer optimization.  The rules\n** for a compatible index:\n**\n**    *   The index is over the same set of columns\n**    *   The same DESC and ASC markings occurs on all columns\n**    *   The same onError processing (OE_Abort, OE_Ignore, etc)\n**    *   The same collating sequence on each column\n*/\nstatic int xferCompatibleIndex(Index *pDest, Index *pSrc){\n  int i;\n  assert( pDest && pSrc );\n  assert( pDest->pTable!=pSrc->pTable );\n  if( pDest->nColumn!=pSrc->nColumn ){\n    return 0;   /* Different number of columns */\n  }\n  if( pDest->onError!=pSrc->onError ){\n    return 0;   /* Different conflict resolution strategies */\n  }\n  for(i=0; i<pSrc->nColumn; i++){\n    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){\n      return 0;   /* Different columns indexed */\n    }\n    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){\n      return 0;   /* Different sort orders */\n    }\n    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){\n      return 0;   /* Different collating sequences */\n    }\n  }\n\n  /* If no test above fails then the indices must be compatible */\n  return 1;\n}\n\n/*\n** Attempt the transfer optimization on INSERTs of the form\n**\n**     INSERT INTO tab1 SELECT * FROM tab2;\n**\n** The xfer optimization transfers raw records from tab2 over to tab1.  \n** Columns are not decoded and reassemblied, which greatly improves\n** performance.  Raw index records are transferred in the same way.\n**\n** The xfer optimization is only attempted if tab1 and tab2 are compatible.\n** There are lots of rules for determining compatibility - see comments\n** embedded in the code for details.\n**\n** This routine returns TRUE if the optimization is guaranteed to be used.\n** Sometimes the xfer optimization will only work if the destination table\n** is empty - a factor that can only be determined at run-time.  In that\n** case, this routine generates code for the xfer optimization but also\n** does a test to see if the destination table is empty and jumps over the\n** xfer optimization code if the test fails.  In that case, this routine\n** returns FALSE so that the caller will know to go ahead and generate\n** an unoptimized transfer.  This routine also returns FALSE if there\n** is no chance that the xfer optimization can be applied.\n**\n** This optimization is particularly useful at making VACUUM run faster.\n*/\nstatic int xferOptimization(\n  Parse *pParse,        /* Parser context */\n  Table *pDest,         /* The table we are inserting into */\n  Select *pSelect,      /* A SELECT statement to use as the data source */\n  int onError,          /* How to handle constraint errors */\n  int iDbDest           /* The database of pDest */\n){\n  ExprList *pEList;                /* The result set of the SELECT */\n  Table *pSrc;                     /* The table in the FROM clause of SELECT */\n  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */\n  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */\n  int i;                           /* Loop counter */\n  int iDbSrc;                      /* The database of pSrc */\n  int iSrc, iDest;                 /* Cursors from source and destination */\n  int addr1, addr2;                /* Loop addresses */\n  int emptyDestTest;               /* Address of test for empty pDest */\n  int emptySrcTest;                /* Address of test for empty pSrc */\n  Vdbe *v;                         /* The VDBE we are building */\n  KeyInfo *pKey;                   /* Key information for an index */\n  int regAutoinc;                  /* Memory register used by AUTOINC */\n  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */\n  int regData, regRowid;           /* Registers holding data and rowid */\n\n  if( pSelect==0 ){\n    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */\n  }\n  if( sqlite3TriggerList(pParse, pDest) ){\n    return 0;   /* tab1 must not have triggers */\n  }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pDest->tabFlags & TF_Virtual ){\n    return 0;   /* tab1 must not be a virtual table */\n  }\n#endif\n  if( onError==OE_Default ){\n    if( pDest->iPKey>=0 ) onError = pDest->keyConf;\n    if( onError==OE_Default ) onError = OE_Abort;\n  }\n  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */\n  if( pSelect->pSrc->nSrc!=1 ){\n    return 0;   /* FROM clause must have exactly one term */\n  }\n  if( pSelect->pSrc->a[0].pSelect ){\n    return 0;   /* FROM clause cannot contain a subquery */\n  }\n  if( pSelect->pWhere ){\n    return 0;   /* SELECT may not have a WHERE clause */\n  }\n  if( pSelect->pOrderBy ){\n    return 0;   /* SELECT may not have an ORDER BY clause */\n  }\n  /* Do not need to test for a HAVING clause.  If HAVING is present but\n  ** there is no ORDER BY, we will get an error. */\n  if( pSelect->pGroupBy ){\n    return 0;   /* SELECT may not have a GROUP BY clause */\n  }\n  if( pSelect->pLimit ){\n    return 0;   /* SELECT may not have a LIMIT clause */\n  }\n  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */\n  if( pSelect->pPrior ){\n    return 0;   /* SELECT may not be a compound query */\n  }\n  if( pSelect->selFlags & SF_Distinct ){\n    return 0;   /* SELECT may not be DISTINCT */\n  }\n  pEList = pSelect->pEList;\n  assert( pEList!=0 );\n  if( pEList->nExpr!=1 ){\n    return 0;   /* The result set must have exactly one column */\n  }\n  assert( pEList->a[0].pExpr );\n  if( pEList->a[0].pExpr->op!=TK_ALL ){\n    return 0;   /* The result set must be the special operator \"*\" */\n  }\n\n  /* At this point we have established that the statement is of the\n  ** correct syntactic form to participate in this optimization.  Now\n  ** we have to check the semantics.\n  */\n  pItem = pSelect->pSrc->a;\n  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);\n  if( pSrc==0 ){\n    return 0;   /* FROM clause does not contain a real table */\n  }\n  if( pSrc==pDest ){\n    return 0;   /* tab1 and tab2 may not be the same table */\n  }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( pSrc->tabFlags & TF_Virtual ){\n    return 0;   /* tab2 must not be a virtual table */\n  }\n#endif\n  if( pSrc->pSelect ){\n    return 0;   /* tab2 may not be a view */\n  }\n  if( pDest->nCol!=pSrc->nCol ){\n    return 0;   /* Number of columns must be the same in tab1 and tab2 */\n  }\n  if( pDest->iPKey!=pSrc->iPKey ){\n    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */\n  }\n  for(i=0; i<pDest->nCol; i++){\n    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){\n      return 0;    /* Affinity must be the same on all columns */\n    }\n    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){\n      return 0;    /* Collating sequence must be the same on all columns */\n    }\n    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){\n      return 0;    /* tab2 must be NOT NULL if tab1 is */\n    }\n  }\n  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){\n    if( pDestIdx->onError!=OE_None ){\n      destHasUniqueIdx = 1;\n    }\n    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){\n      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;\n    }\n    if( pSrcIdx==0 ){\n      return 0;    /* pDestIdx has no corresponding index in pSrc */\n    }\n  }\n#ifndef SQLITE_OMIT_CHECK\n  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){\n    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */\n  }\n#endif\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  /* Disallow the transfer optimization if the destination table constains\n  ** any foreign key constraints.  This is more restrictive than necessary.\n  ** But the main beneficiary of the transfer optimization is the VACUUM \n  ** command, and the VACUUM command disables foreign key constraints.  So\n  ** the extra complication to make this rule less restrictive is probably\n  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]\n  */\n  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){\n    return 0;\n  }\n#endif\n  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){\n    return 0;  /* xfer opt does not play well with PRAGMA count_changes */\n  }\n\n  /* If we get this far, it means that the xfer optimization is at\n  ** least a possibility, though it might only work if the destination\n  ** table (tab1) is initially empty.\n  */\n#ifdef SQLITE_TEST\n  sqlite3_xferopt_count++;\n#endif\n  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);\n  v = sqlite3GetVdbe(pParse);\n  sqlite3CodeVerifySchema(pParse, iDbSrc);\n  iSrc = pParse->nTab++;\n  iDest = pParse->nTab++;\n  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);\n  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);\n  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */\n   || destHasUniqueIdx                              /* (2) */\n   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */\n  ){\n    /* In some circumstances, we are able to run the xfer optimization\n    ** only if the destination table is initially empty.  This code makes\n    ** that determination.  Conditions under which the destination must\n    ** be empty:\n    **\n    ** (1) There is no INTEGER PRIMARY KEY but there are indices.\n    **     (If the destination is not initially empty, the rowid fields\n    **     of index entries might need to change.)\n    **\n    ** (2) The destination has a unique index.  (The xfer optimization \n    **     is unable to test uniqueness.)\n    **\n    ** (3) onError is something other than OE_Abort and OE_Rollback.\n    */\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);\n    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);\n    sqlite3VdbeJumpHere(v, addr1);\n  }else{\n    emptyDestTest = 0;\n  }\n  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);\n  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);\n  regData = sqlite3GetTempReg(pParse);\n  regRowid = sqlite3GetTempReg(pParse);\n  if( pDest->iPKey>=0 ){\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);\n    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);\n    sqlite3HaltConstraint(\n        pParse, onError, \"PRIMARY KEY must be unique\", P4_STATIC);\n    sqlite3VdbeJumpHere(v, addr2);\n    autoIncStep(pParse, regAutoinc, regRowid);\n  }else if( pDest->pIndex==0 ){\n    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);\n  }else{\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);\n    assert( (pDest->tabFlags & TF_Autoincrement)==0 );\n  }\n  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);\n  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);\n  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);\n  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);\n  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);\n  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){\n    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){\n      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;\n    }\n    assert( pSrcIdx );\n    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);\n    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);\n    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,\n                      (char*)pKey, P4_KEYINFO_HANDOFF);\n    VdbeComment((v, \"%s\", pSrcIdx->zName));\n    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);\n    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,\n                      (char*)pKey, P4_KEYINFO_HANDOFF);\n    VdbeComment((v, \"%s\", pDestIdx->zName));\n    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);\n    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);\n    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);\n    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);\n    sqlite3VdbeJumpHere(v, addr1);\n  }\n  sqlite3VdbeJumpHere(v, emptySrcTest);\n  sqlite3ReleaseTempReg(pParse, regRowid);\n  sqlite3ReleaseTempReg(pParse, regData);\n  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);\n  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n  if( emptyDestTest ){\n    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);\n    sqlite3VdbeJumpHere(v, emptyDestTest);\n    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);\n    return 0;\n  }else{\n    return 1;\n  }\n}\n#endif /* SQLITE_OMIT_XFER_OPT */\n\n/************** End of insert.c **********************************************/\n/************** Begin file legacy.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Main file for the SQLite library.  The routines in this file\n** implement the programmer interface to the library.  Routines in\n** other files are for internal use by SQLite and should not be\n** accessed by users of the library.\n*/\n\n\n/*\n** Execute SQL code.  Return one of the SQLITE_ success/failure\n** codes.  Also write an error message into memory obtained from\n** malloc() and make *pzErrMsg point to that message.\n**\n** If the SQL is a query, then for each row in the query result\n** the xCallback() function is called.  pArg becomes the first\n** argument to xCallback().  If xCallback=NULL then no callback\n** is invoked, even for queries.\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3 *db,                /* The database on which the SQL executes */\n  const char *zSql,           /* The SQL to be executed */\n  sqlite3_callback xCallback, /* Invoke this callback routine */\n  void *pArg,                 /* First argument to xCallback() */\n  char **pzErrMsg             /* Write error messages here */\n){\n  int rc = SQLITE_OK;         /* Return code */\n  const char *zLeftover;      /* Tail of unprocessed SQL */\n  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */\n  char **azCols = 0;          /* Names of result columns */\n  int nRetry = 0;             /* Number of retry attempts */\n  int callbackIsInit;         /* True if callback data is initialized */\n\n  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;\n  if( zSql==0 ) zSql = \"\";\n\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3Error(db, SQLITE_OK, 0);\n  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){\n    int nCol;\n    char **azVals = 0;\n\n    pStmt = 0;\n    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);\n    assert( rc==SQLITE_OK || pStmt==0 );\n    if( rc!=SQLITE_OK ){\n      continue;\n    }\n    if( !pStmt ){\n      /* this happens for a comment or white-space */\n      zSql = zLeftover;\n      continue;\n    }\n\n    callbackIsInit = 0;\n    nCol = sqlite3_column_count(pStmt);\n\n    while( 1 ){\n      int i;\n      rc = sqlite3_step(pStmt);\n\n      /* Invoke the callback function if required */\n      if( xCallback && (SQLITE_ROW==rc || \n          (SQLITE_DONE==rc && !callbackIsInit\n                           && db->flags&SQLITE_NullCallback)) ){\n        if( !callbackIsInit ){\n          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);\n          if( azCols==0 ){\n            goto exec_out;\n          }\n          for(i=0; i<nCol; i++){\n            azCols[i] = (char *)sqlite3_column_name(pStmt, i);\n            /* sqlite3VdbeSetColName() installs column names as UTF8\n            ** strings so there is no way for sqlite3_column_name() to fail. */\n            assert( azCols[i]!=0 );\n          }\n          callbackIsInit = 1;\n        }\n        if( rc==SQLITE_ROW ){\n          azVals = &azCols[nCol];\n          for(i=0; i<nCol; i++){\n            azVals[i] = (char *)sqlite3_column_text(pStmt, i);\n            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){\n              db->mallocFailed = 1;\n              goto exec_out;\n            }\n          }\n        }\n        if( xCallback(pArg, nCol, azVals, azCols) ){\n          rc = SQLITE_ABORT;\n          sqlite3VdbeFinalize((Vdbe *)pStmt);\n          pStmt = 0;\n          sqlite3Error(db, SQLITE_ABORT, 0);\n          goto exec_out;\n        }\n      }\n\n      if( rc!=SQLITE_ROW ){\n        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);\n        pStmt = 0;\n        if( rc!=SQLITE_SCHEMA ){\n          nRetry = 0;\n          zSql = zLeftover;\n          while( sqlite3Isspace(zSql[0]) ) zSql++;\n        }\n        break;\n      }\n    }\n\n    sqlite3DbFree(db, azCols);\n    azCols = 0;\n  }\n\nexec_out:\n  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);\n  sqlite3DbFree(db, azCols);\n\n  rc = sqlite3ApiExit(db, rc);\n  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){\n    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));\n    *pzErrMsg = sqlite3Malloc(nErrMsg);\n    if( *pzErrMsg ){\n      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);\n    }else{\n      rc = SQLITE_NOMEM;\n      sqlite3Error(db, SQLITE_NOMEM, 0);\n    }\n  }else if( pzErrMsg ){\n    *pzErrMsg = 0;\n  }\n\n  assert( (rc&db->errMask)==rc );\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/************** End of legacy.c **********************************************/\n/************** Begin file loadext.c *****************************************/\n/*\n** 2006 June 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to dynamically load extensions into\n** the SQLite library.\n*/\n\n#ifndef SQLITE_CORE\n  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */\n#endif\n/************** Include sqlite3ext.h in the middle of loadext.c **************/\n/************** Begin file sqlite3ext.h **************************************/\n/*\n** 2006 June 7\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the SQLite interface for use by\n** shared libraries that want to be imported as extensions into\n** an SQLite instance.  Shared libraries that intend to be loaded\n** as extensions by SQLite should #include this file instead of \n** sqlite3.h.\n*/\n#ifndef _SQLITE3EXT_H_\n#define _SQLITE3EXT_H_\n\ntypedef struct sqlite3_api_routines sqlite3_api_routines;\n\n/*\n** The following structure holds pointers to all of the SQLite API\n** routines.\n**\n** WARNING:  In order to maintain backwards compatibility, add new\n** interfaces to the end of this structure only.  If you insert new\n** interfaces in the middle of this structure, then older different\n** versions of SQLite will not be able to load each others' shared\n** libraries!\n*/\nstruct sqlite3_api_routines {\n  void * (*aggregate_context)(sqlite3_context*,int nBytes);\n  int  (*aggregate_count)(sqlite3_context*);\n  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));\n  int  (*bind_double)(sqlite3_stmt*,int,double);\n  int  (*bind_int)(sqlite3_stmt*,int,int);\n  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);\n  int  (*bind_null)(sqlite3_stmt*,int);\n  int  (*bind_parameter_count)(sqlite3_stmt*);\n  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);\n  const char * (*bind_parameter_name)(sqlite3_stmt*,int);\n  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));\n  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));\n  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);\n  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);\n  int  (*busy_timeout)(sqlite3*,int ms);\n  int  (*changes)(sqlite3*);\n  int  (*close)(sqlite3*);\n  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                           int eTextRep,const char*));\n  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,\n                             int eTextRep,const void*));\n  const void * (*column_blob)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes)(sqlite3_stmt*,int iCol);\n  int  (*column_bytes16)(sqlite3_stmt*,int iCol);\n  int  (*column_count)(sqlite3_stmt*pStmt);\n  const char * (*column_database_name)(sqlite3_stmt*,int);\n  const void * (*column_database_name16)(sqlite3_stmt*,int);\n  const char * (*column_decltype)(sqlite3_stmt*,int i);\n  const void * (*column_decltype16)(sqlite3_stmt*,int);\n  double  (*column_double)(sqlite3_stmt*,int iCol);\n  int  (*column_int)(sqlite3_stmt*,int iCol);\n  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);\n  const char * (*column_name)(sqlite3_stmt*,int);\n  const void * (*column_name16)(sqlite3_stmt*,int);\n  const char * (*column_origin_name)(sqlite3_stmt*,int);\n  const void * (*column_origin_name16)(sqlite3_stmt*,int);\n  const char * (*column_table_name)(sqlite3_stmt*,int);\n  const void * (*column_table_name16)(sqlite3_stmt*,int);\n  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);\n  const void * (*column_text16)(sqlite3_stmt*,int iCol);\n  int  (*column_type)(sqlite3_stmt*,int iCol);\n  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);\n  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);\n  int  (*complete)(const char*sql);\n  int  (*complete16)(const void*sql);\n  int  (*create_collation)(sqlite3*,const char*,int,void*,\n                           int(*)(void*,int,const void*,int,const void*));\n  int  (*create_collation16)(sqlite3*,const void*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*));\n  int  (*create_function)(sqlite3*,const char*,int,int,void*,\n                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                          void (*xFinal)(sqlite3_context*));\n  int  (*create_function16)(sqlite3*,const void*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*));\n  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);\n  int  (*data_count)(sqlite3_stmt*pStmt);\n  sqlite3 * (*db_handle)(sqlite3_stmt*);\n  int (*declare_vtab)(sqlite3*,const char*);\n  int  (*enable_shared_cache)(int);\n  int  (*errcode)(sqlite3*db);\n  const char * (*errmsg)(sqlite3*);\n  const void * (*errmsg16)(sqlite3*);\n  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);\n  int  (*expired)(sqlite3_stmt*);\n  int  (*finalize)(sqlite3_stmt*pStmt);\n  void  (*free)(void*);\n  void  (*free_table)(char**result);\n  int  (*get_autocommit)(sqlite3*);\n  void * (*get_auxdata)(sqlite3_context*,int);\n  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);\n  int  (*global_recover)(void);\n  void  (*interruptx)(sqlite3*);\n  sqlite_int64  (*last_insert_rowid)(sqlite3*);\n  const char * (*libversion)(void);\n  int  (*libversion_number)(void);\n  void *(*malloc)(int);\n  char * (*mprintf)(const char*,...);\n  int  (*open)(const char*,sqlite3**);\n  int  (*open16)(const void*,sqlite3**);\n  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);\n  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);\n  void *(*realloc)(void*,int);\n  int  (*reset)(sqlite3_stmt*pStmt);\n  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_double)(sqlite3_context*,double);\n  void  (*result_error)(sqlite3_context*,const char*,int);\n  void  (*result_error16)(sqlite3_context*,const void*,int);\n  void  (*result_int)(sqlite3_context*,int);\n  void  (*result_int64)(sqlite3_context*,sqlite_int64);\n  void  (*result_null)(sqlite3_context*);\n  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));\n  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));\n  void  (*result_value)(sqlite3_context*,sqlite3_value*);\n  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);\n  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,\n                         const char*,const char*),void*);\n  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));\n  char * (*snprintf)(int,char*,const char*,...);\n  int  (*step)(sqlite3_stmt*);\n  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,\n                                char const**,char const**,int*,int*,int*);\n  void  (*thread_cleanup)(void);\n  int  (*total_changes)(sqlite3*);\n  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);\n  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);\n  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,\n                                         sqlite_int64),void*);\n  void * (*user_data)(sqlite3_context*);\n  const void * (*value_blob)(sqlite3_value*);\n  int  (*value_bytes)(sqlite3_value*);\n  int  (*value_bytes16)(sqlite3_value*);\n  double  (*value_double)(sqlite3_value*);\n  int  (*value_int)(sqlite3_value*);\n  sqlite_int64  (*value_int64)(sqlite3_value*);\n  int  (*value_numeric_type)(sqlite3_value*);\n  const unsigned char * (*value_text)(sqlite3_value*);\n  const void * (*value_text16)(sqlite3_value*);\n  const void * (*value_text16be)(sqlite3_value*);\n  const void * (*value_text16le)(sqlite3_value*);\n  int  (*value_type)(sqlite3_value*);\n  char *(*vmprintf)(const char*,va_list);\n  /* Added ??? */\n  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);\n  /* Added by 3.3.13 */\n  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);\n  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);\n  int (*clear_bindings)(sqlite3_stmt*);\n  /* Added by 3.4.1 */\n  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,\n                          void (*xDestroy)(void *));\n  /* Added by 3.5.0 */\n  int (*bind_zeroblob)(sqlite3_stmt*,int,int);\n  int (*blob_bytes)(sqlite3_blob*);\n  int (*blob_close)(sqlite3_blob*);\n  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,\n                   int,sqlite3_blob**);\n  int (*blob_read)(sqlite3_blob*,void*,int,int);\n  int (*blob_write)(sqlite3_blob*,const void*,int,int);\n  int (*create_collation_v2)(sqlite3*,const char*,int,void*,\n                             int(*)(void*,int,const void*,int,const void*),\n                             void(*)(void*));\n  int (*file_control)(sqlite3*,const char*,int,void*);\n  sqlite3_int64 (*memory_highwater)(int);\n  sqlite3_int64 (*memory_used)(void);\n  sqlite3_mutex *(*mutex_alloc)(int);\n  void (*mutex_enter)(sqlite3_mutex*);\n  void (*mutex_free)(sqlite3_mutex*);\n  void (*mutex_leave)(sqlite3_mutex*);\n  int (*mutex_try)(sqlite3_mutex*);\n  int (*open_v2)(const char*,sqlite3**,int,const char*);\n  int (*release_memory)(int);\n  void (*result_error_nomem)(sqlite3_context*);\n  void (*result_error_toobig)(sqlite3_context*);\n  int (*sleep)(int);\n  void (*soft_heap_limit)(int);\n  sqlite3_vfs *(*vfs_find)(const char*);\n  int (*vfs_register)(sqlite3_vfs*,int);\n  int (*vfs_unregister)(sqlite3_vfs*);\n  int (*xthreadsafe)(void);\n  void (*result_zeroblob)(sqlite3_context*,int);\n  void (*result_error_code)(sqlite3_context*,int);\n  int (*test_control)(int, ...);\n  void (*randomness)(int,void*);\n  sqlite3 *(*context_db_handle)(sqlite3_context*);\n  int (*extended_result_codes)(sqlite3*,int);\n  int (*limit)(sqlite3*,int,int);\n  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);\n  const char *(*sql)(sqlite3_stmt*);\n  int (*status)(int,int*,int*,int);\n  int (*backup_finish)(sqlite3_backup*);\n  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);\n  int (*backup_pagecount)(sqlite3_backup*);\n  int (*backup_remaining)(sqlite3_backup*);\n  int (*backup_step)(sqlite3_backup*,int);\n  const char *(*compileoption_get)(int);\n  int (*compileoption_used)(const char*);\n  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,\n                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n                            void (*xFinal)(sqlite3_context*),\n                            void(*xDestroy)(void*));\n  int (*db_config)(sqlite3*,int,...);\n  sqlite3_mutex *(*db_mutex)(sqlite3*);\n  int (*db_status)(sqlite3*,int,int*,int*,int);\n  int (*extended_errcode)(sqlite3*);\n  void (*log)(int,const char*,...);\n  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);\n  const char *(*sourceid)(void);\n  int (*stmt_status)(sqlite3_stmt*,int,int);\n  int (*strnicmp)(const char*,const char*,int);\n  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);\n  int (*wal_autocheckpoint)(sqlite3*,int);\n  int (*wal_checkpoint)(sqlite3*,const char*);\n  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);\n  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);\n  int (*vtab_config)(sqlite3*,int op,...);\n  int (*vtab_on_conflict)(sqlite3*);\n};\n\n/*\n** The following macros redefine the API routines so that they are\n** redirected throught the global sqlite3_api structure.\n**\n** This header file is also used by the loadext.c source file\n** (part of the main SQLite library - not an extension) so that\n** it can get access to the sqlite3_api_routines structure\n** definition.  But the main library does not want to redefine\n** the API.  So the redefinition macros are only valid if the\n** SQLITE_CORE macros is undefined.\n*/\n#ifndef SQLITE_CORE\n#define sqlite3_aggregate_context      sqlite3_api->aggregate_context\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_aggregate_count        sqlite3_api->aggregate_count\n#endif\n#define sqlite3_bind_blob              sqlite3_api->bind_blob\n#define sqlite3_bind_double            sqlite3_api->bind_double\n#define sqlite3_bind_int               sqlite3_api->bind_int\n#define sqlite3_bind_int64             sqlite3_api->bind_int64\n#define sqlite3_bind_null              sqlite3_api->bind_null\n#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count\n#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index\n#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name\n#define sqlite3_bind_text              sqlite3_api->bind_text\n#define sqlite3_bind_text16            sqlite3_api->bind_text16\n#define sqlite3_bind_value             sqlite3_api->bind_value\n#define sqlite3_busy_handler           sqlite3_api->busy_handler\n#define sqlite3_busy_timeout           sqlite3_api->busy_timeout\n#define sqlite3_changes                sqlite3_api->changes\n#define sqlite3_close                  sqlite3_api->close\n#define sqlite3_collation_needed       sqlite3_api->collation_needed\n#define sqlite3_collation_needed16     sqlite3_api->collation_needed16\n#define sqlite3_column_blob            sqlite3_api->column_blob\n#define sqlite3_column_bytes           sqlite3_api->column_bytes\n#define sqlite3_column_bytes16         sqlite3_api->column_bytes16\n#define sqlite3_column_count           sqlite3_api->column_count\n#define sqlite3_column_database_name   sqlite3_api->column_database_name\n#define sqlite3_column_database_name16 sqlite3_api->column_database_name16\n#define sqlite3_column_decltype        sqlite3_api->column_decltype\n#define sqlite3_column_decltype16      sqlite3_api->column_decltype16\n#define sqlite3_column_double          sqlite3_api->column_double\n#define sqlite3_column_int             sqlite3_api->column_int\n#define sqlite3_column_int64           sqlite3_api->column_int64\n#define sqlite3_column_name            sqlite3_api->column_name\n#define sqlite3_column_name16          sqlite3_api->column_name16\n#define sqlite3_column_origin_name     sqlite3_api->column_origin_name\n#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16\n#define sqlite3_column_table_name      sqlite3_api->column_table_name\n#define sqlite3_column_table_name16    sqlite3_api->column_table_name16\n#define sqlite3_column_text            sqlite3_api->column_text\n#define sqlite3_column_text16          sqlite3_api->column_text16\n#define sqlite3_column_type            sqlite3_api->column_type\n#define sqlite3_column_value           sqlite3_api->column_value\n#define sqlite3_commit_hook            sqlite3_api->commit_hook\n#define sqlite3_complete               sqlite3_api->complete\n#define sqlite3_complete16             sqlite3_api->complete16\n#define sqlite3_create_collation       sqlite3_api->create_collation\n#define sqlite3_create_collation16     sqlite3_api->create_collation16\n#define sqlite3_create_function        sqlite3_api->create_function\n#define sqlite3_create_function16      sqlite3_api->create_function16\n#define sqlite3_create_module          sqlite3_api->create_module\n#define sqlite3_create_module_v2       sqlite3_api->create_module_v2\n#define sqlite3_data_count             sqlite3_api->data_count\n#define sqlite3_db_handle              sqlite3_api->db_handle\n#define sqlite3_declare_vtab           sqlite3_api->declare_vtab\n#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache\n#define sqlite3_errcode                sqlite3_api->errcode\n#define sqlite3_errmsg                 sqlite3_api->errmsg\n#define sqlite3_errmsg16               sqlite3_api->errmsg16\n#define sqlite3_exec                   sqlite3_api->exec\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_expired                sqlite3_api->expired\n#endif\n#define sqlite3_finalize               sqlite3_api->finalize\n#define sqlite3_free                   sqlite3_api->free\n#define sqlite3_free_table             sqlite3_api->free_table\n#define sqlite3_get_autocommit         sqlite3_api->get_autocommit\n#define sqlite3_get_auxdata            sqlite3_api->get_auxdata\n#define sqlite3_get_table              sqlite3_api->get_table\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_global_recover         sqlite3_api->global_recover\n#endif\n#define sqlite3_interrupt              sqlite3_api->interruptx\n#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid\n#define sqlite3_libversion             sqlite3_api->libversion\n#define sqlite3_libversion_number      sqlite3_api->libversion_number\n#define sqlite3_malloc                 sqlite3_api->malloc\n#define sqlite3_mprintf                sqlite3_api->mprintf\n#define sqlite3_open                   sqlite3_api->open\n#define sqlite3_open16                 sqlite3_api->open16\n#define sqlite3_prepare                sqlite3_api->prepare\n#define sqlite3_prepare16              sqlite3_api->prepare16\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_profile                sqlite3_api->profile\n#define sqlite3_progress_handler       sqlite3_api->progress_handler\n#define sqlite3_realloc                sqlite3_api->realloc\n#define sqlite3_reset                  sqlite3_api->reset\n#define sqlite3_result_blob            sqlite3_api->result_blob\n#define sqlite3_result_double          sqlite3_api->result_double\n#define sqlite3_result_error           sqlite3_api->result_error\n#define sqlite3_result_error16         sqlite3_api->result_error16\n#define sqlite3_result_int             sqlite3_api->result_int\n#define sqlite3_result_int64           sqlite3_api->result_int64\n#define sqlite3_result_null            sqlite3_api->result_null\n#define sqlite3_result_text            sqlite3_api->result_text\n#define sqlite3_result_text16          sqlite3_api->result_text16\n#define sqlite3_result_text16be        sqlite3_api->result_text16be\n#define sqlite3_result_text16le        sqlite3_api->result_text16le\n#define sqlite3_result_value           sqlite3_api->result_value\n#define sqlite3_rollback_hook          sqlite3_api->rollback_hook\n#define sqlite3_set_authorizer         sqlite3_api->set_authorizer\n#define sqlite3_set_auxdata            sqlite3_api->set_auxdata\n#define sqlite3_snprintf               sqlite3_api->snprintf\n#define sqlite3_step                   sqlite3_api->step\n#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata\n#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup\n#define sqlite3_total_changes          sqlite3_api->total_changes\n#define sqlite3_trace                  sqlite3_api->trace\n#ifndef SQLITE_OMIT_DEPRECATED\n#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings\n#endif\n#define sqlite3_update_hook            sqlite3_api->update_hook\n#define sqlite3_user_data              sqlite3_api->user_data\n#define sqlite3_value_blob             sqlite3_api->value_blob\n#define sqlite3_value_bytes            sqlite3_api->value_bytes\n#define sqlite3_value_bytes16          sqlite3_api->value_bytes16\n#define sqlite3_value_double           sqlite3_api->value_double\n#define sqlite3_value_int              sqlite3_api->value_int\n#define sqlite3_value_int64            sqlite3_api->value_int64\n#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type\n#define sqlite3_value_text             sqlite3_api->value_text\n#define sqlite3_value_text16           sqlite3_api->value_text16\n#define sqlite3_value_text16be         sqlite3_api->value_text16be\n#define sqlite3_value_text16le         sqlite3_api->value_text16le\n#define sqlite3_value_type             sqlite3_api->value_type\n#define sqlite3_vmprintf               sqlite3_api->vmprintf\n#define sqlite3_overload_function      sqlite3_api->overload_function\n#define sqlite3_prepare_v2             sqlite3_api->prepare_v2\n#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2\n#define sqlite3_clear_bindings         sqlite3_api->clear_bindings\n#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob\n#define sqlite3_blob_bytes             sqlite3_api->blob_bytes\n#define sqlite3_blob_close             sqlite3_api->blob_close\n#define sqlite3_blob_open              sqlite3_api->blob_open\n#define sqlite3_blob_read              sqlite3_api->blob_read\n#define sqlite3_blob_write             sqlite3_api->blob_write\n#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2\n#define sqlite3_file_control           sqlite3_api->file_control\n#define sqlite3_memory_highwater       sqlite3_api->memory_highwater\n#define sqlite3_memory_used            sqlite3_api->memory_used\n#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc\n#define sqlite3_mutex_enter            sqlite3_api->mutex_enter\n#define sqlite3_mutex_free             sqlite3_api->mutex_free\n#define sqlite3_mutex_leave            sqlite3_api->mutex_leave\n#define sqlite3_mutex_try              sqlite3_api->mutex_try\n#define sqlite3_open_v2                sqlite3_api->open_v2\n#define sqlite3_release_memory         sqlite3_api->release_memory\n#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem\n#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig\n#define sqlite3_sleep                  sqlite3_api->sleep\n#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit\n#define sqlite3_vfs_find               sqlite3_api->vfs_find\n#define sqlite3_vfs_register           sqlite3_api->vfs_register\n#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister\n#define sqlite3_threadsafe             sqlite3_api->xthreadsafe\n#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob\n#define sqlite3_result_error_code      sqlite3_api->result_error_code\n#define sqlite3_test_control           sqlite3_api->test_control\n#define sqlite3_randomness             sqlite3_api->randomness\n#define sqlite3_context_db_handle      sqlite3_api->context_db_handle\n#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes\n#define sqlite3_limit                  sqlite3_api->limit\n#define sqlite3_next_stmt              sqlite3_api->next_stmt\n#define sqlite3_sql                    sqlite3_api->sql\n#define sqlite3_status                 sqlite3_api->status\n#define sqlite3_backup_finish          sqlite3_api->backup_finish\n#define sqlite3_backup_init            sqlite3_api->backup_init\n#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount\n#define sqlite3_backup_remaining       sqlite3_api->backup_remaining\n#define sqlite3_backup_step            sqlite3_api->backup_step\n#define sqlite3_compileoption_get      sqlite3_api->compileoption_get\n#define sqlite3_compileoption_used     sqlite3_api->compileoption_used\n#define sqlite3_create_function_v2     sqlite3_api->create_function_v2\n#define sqlite3_db_config              sqlite3_api->db_config\n#define sqlite3_db_mutex               sqlite3_api->db_mutex\n#define sqlite3_db_status              sqlite3_api->db_status\n#define sqlite3_extended_errcode       sqlite3_api->extended_errcode\n#define sqlite3_log                    sqlite3_api->log\n#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64\n#define sqlite3_sourceid               sqlite3_api->sourceid\n#define sqlite3_stmt_status            sqlite3_api->stmt_status\n#define sqlite3_strnicmp               sqlite3_api->strnicmp\n#define sqlite3_unlock_notify          sqlite3_api->unlock_notify\n#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint\n#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint\n#define sqlite3_wal_hook               sqlite3_api->wal_hook\n#define sqlite3_blob_reopen            sqlite3_api->blob_reopen\n#define sqlite3_vtab_config            sqlite3_api->vtab_config\n#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict\n#endif /* SQLITE_CORE */\n\n#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;\n#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;\n\n#endif /* _SQLITE3EXT_H_ */\n\n/************** End of sqlite3ext.h ******************************************/\n/************** Continuing where we left off in loadext.c ********************/\n/* #include <string.h> */\n\n#ifndef SQLITE_OMIT_LOAD_EXTENSION\n\n/*\n** Some API routines are omitted when various features are\n** excluded from a build of SQLite.  Substitute a NULL pointer\n** for any missing APIs.\n*/\n#ifndef SQLITE_ENABLE_COLUMN_METADATA\n# define sqlite3_column_database_name   0\n# define sqlite3_column_database_name16 0\n# define sqlite3_column_table_name      0\n# define sqlite3_column_table_name16    0\n# define sqlite3_column_origin_name     0\n# define sqlite3_column_origin_name16   0\n# define sqlite3_table_column_metadata  0\n#endif\n\n#ifdef SQLITE_OMIT_AUTHORIZATION\n# define sqlite3_set_authorizer         0\n#endif\n\n#ifdef SQLITE_OMIT_UTF16\n# define sqlite3_bind_text16            0\n# define sqlite3_collation_needed16     0\n# define sqlite3_column_decltype16      0\n# define sqlite3_column_name16          0\n# define sqlite3_column_text16          0\n# define sqlite3_complete16             0\n# define sqlite3_create_collation16     0\n# define sqlite3_create_function16      0\n# define sqlite3_errmsg16               0\n# define sqlite3_open16                 0\n# define sqlite3_prepare16              0\n# define sqlite3_prepare16_v2           0\n# define sqlite3_result_error16         0\n# define sqlite3_result_text16          0\n# define sqlite3_result_text16be        0\n# define sqlite3_result_text16le        0\n# define sqlite3_value_text16           0\n# define sqlite3_value_text16be         0\n# define sqlite3_value_text16le         0\n# define sqlite3_column_database_name16 0\n# define sqlite3_column_table_name16    0\n# define sqlite3_column_origin_name16   0\n#endif\n\n#ifdef SQLITE_OMIT_COMPLETE\n# define sqlite3_complete 0\n# define sqlite3_complete16 0\n#endif\n\n#ifdef SQLITE_OMIT_DECLTYPE\n# define sqlite3_column_decltype16      0\n# define sqlite3_column_decltype        0\n#endif\n\n#ifdef SQLITE_OMIT_PROGRESS_CALLBACK\n# define sqlite3_progress_handler 0\n#endif\n\n#ifdef SQLITE_OMIT_VIRTUALTABLE\n# define sqlite3_create_module 0\n# define sqlite3_create_module_v2 0\n# define sqlite3_declare_vtab 0\n# define sqlite3_vtab_config 0\n# define sqlite3_vtab_on_conflict 0\n#endif\n\n#ifdef SQLITE_OMIT_SHARED_CACHE\n# define sqlite3_enable_shared_cache 0\n#endif\n\n#ifdef SQLITE_OMIT_TRACE\n# define sqlite3_profile       0\n# define sqlite3_trace         0\n#endif\n\n#ifdef SQLITE_OMIT_GET_TABLE\n# define sqlite3_free_table    0\n# define sqlite3_get_table     0\n#endif\n\n#ifdef SQLITE_OMIT_INCRBLOB\n#define sqlite3_bind_zeroblob  0\n#define sqlite3_blob_bytes     0\n#define sqlite3_blob_close     0\n#define sqlite3_blob_open      0\n#define sqlite3_blob_read      0\n#define sqlite3_blob_write     0\n#define sqlite3_blob_reopen    0\n#endif\n\n/*\n** The following structure contains pointers to all SQLite API routines.\n** A pointer to this structure is passed into extensions when they are\n** loaded so that the extension can make calls back into the SQLite\n** library.\n**\n** When adding new APIs, add them to the bottom of this structure\n** in order to preserve backwards compatibility.\n**\n** Extensions that use newer APIs should first call the\n** sqlite3_libversion_number() to make sure that the API they\n** intend to use is supported by the library.  Extensions should\n** also check to make sure that the pointer to the function is\n** not NULL before calling it.\n*/\nstatic const sqlite3_api_routines sqlite3Apis = {\n  sqlite3_aggregate_context,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_aggregate_count,\n#else\n  0,\n#endif\n  sqlite3_bind_blob,\n  sqlite3_bind_double,\n  sqlite3_bind_int,\n  sqlite3_bind_int64,\n  sqlite3_bind_null,\n  sqlite3_bind_parameter_count,\n  sqlite3_bind_parameter_index,\n  sqlite3_bind_parameter_name,\n  sqlite3_bind_text,\n  sqlite3_bind_text16,\n  sqlite3_bind_value,\n  sqlite3_busy_handler,\n  sqlite3_busy_timeout,\n  sqlite3_changes,\n  sqlite3_close,\n  sqlite3_collation_needed,\n  sqlite3_collation_needed16,\n  sqlite3_column_blob,\n  sqlite3_column_bytes,\n  sqlite3_column_bytes16,\n  sqlite3_column_count,\n  sqlite3_column_database_name,\n  sqlite3_column_database_name16,\n  sqlite3_column_decltype,\n  sqlite3_column_decltype16,\n  sqlite3_column_double,\n  sqlite3_column_int,\n  sqlite3_column_int64,\n  sqlite3_column_name,\n  sqlite3_column_name16,\n  sqlite3_column_origin_name,\n  sqlite3_column_origin_name16,\n  sqlite3_column_table_name,\n  sqlite3_column_table_name16,\n  sqlite3_column_text,\n  sqlite3_column_text16,\n  sqlite3_column_type,\n  sqlite3_column_value,\n  sqlite3_commit_hook,\n  sqlite3_complete,\n  sqlite3_complete16,\n  sqlite3_create_collation,\n  sqlite3_create_collation16,\n  sqlite3_create_function,\n  sqlite3_create_function16,\n  sqlite3_create_module,\n  sqlite3_data_count,\n  sqlite3_db_handle,\n  sqlite3_declare_vtab,\n  sqlite3_enable_shared_cache,\n  sqlite3_errcode,\n  sqlite3_errmsg,\n  sqlite3_errmsg16,\n  sqlite3_exec,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_expired,\n#else\n  0,\n#endif\n  sqlite3_finalize,\n  sqlite3_free,\n  sqlite3_free_table,\n  sqlite3_get_autocommit,\n  sqlite3_get_auxdata,\n  sqlite3_get_table,\n  0,     /* Was sqlite3_global_recover(), but that function is deprecated */\n  sqlite3_interrupt,\n  sqlite3_last_insert_rowid,\n  sqlite3_libversion,\n  sqlite3_libversion_number,\n  sqlite3_malloc,\n  sqlite3_mprintf,\n  sqlite3_open,\n  sqlite3_open16,\n  sqlite3_prepare,\n  sqlite3_prepare16,\n  sqlite3_profile,\n  sqlite3_progress_handler,\n  sqlite3_realloc,\n  sqlite3_reset,\n  sqlite3_result_blob,\n  sqlite3_result_double,\n  sqlite3_result_error,\n  sqlite3_result_error16,\n  sqlite3_result_int,\n  sqlite3_result_int64,\n  sqlite3_result_null,\n  sqlite3_result_text,\n  sqlite3_result_text16,\n  sqlite3_result_text16be,\n  sqlite3_result_text16le,\n  sqlite3_result_value,\n  sqlite3_rollback_hook,\n  sqlite3_set_authorizer,\n  sqlite3_set_auxdata,\n  sqlite3_snprintf,\n  sqlite3_step,\n  sqlite3_table_column_metadata,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_thread_cleanup,\n#else\n  0,\n#endif\n  sqlite3_total_changes,\n  sqlite3_trace,\n#ifndef SQLITE_OMIT_DEPRECATED\n  sqlite3_transfer_bindings,\n#else\n  0,\n#endif\n  sqlite3_update_hook,\n  sqlite3_user_data,\n  sqlite3_value_blob,\n  sqlite3_value_bytes,\n  sqlite3_value_bytes16,\n  sqlite3_value_double,\n  sqlite3_value_int,\n  sqlite3_value_int64,\n  sqlite3_value_numeric_type,\n  sqlite3_value_text,\n  sqlite3_value_text16,\n  sqlite3_value_text16be,\n  sqlite3_value_text16le,\n  sqlite3_value_type,\n  sqlite3_vmprintf,\n  /*\n  ** The original API set ends here.  All extensions can call any\n  ** of the APIs above provided that the pointer is not NULL.  But\n  ** before calling APIs that follow, extension should check the\n  ** sqlite3_libversion_number() to make sure they are dealing with\n  ** a library that is new enough to support that API.\n  *************************************************************************\n  */\n  sqlite3_overload_function,\n\n  /*\n  ** Added after 3.3.13\n  */\n  sqlite3_prepare_v2,\n  sqlite3_prepare16_v2,\n  sqlite3_clear_bindings,\n\n  /*\n  ** Added for 3.4.1\n  */\n  sqlite3_create_module_v2,\n\n  /*\n  ** Added for 3.5.0\n  */\n  sqlite3_bind_zeroblob,\n  sqlite3_blob_bytes,\n  sqlite3_blob_close,\n  sqlite3_blob_open,\n  sqlite3_blob_read,\n  sqlite3_blob_write,\n  sqlite3_create_collation_v2,\n  sqlite3_file_control,\n  sqlite3_memory_highwater,\n  sqlite3_memory_used,\n#ifdef SQLITE_MUTEX_OMIT\n  0, \n  0, \n  0,\n  0,\n  0,\n#else\n  sqlite3_mutex_alloc,\n  sqlite3_mutex_enter,\n  sqlite3_mutex_free,\n  sqlite3_mutex_leave,\n  sqlite3_mutex_try,\n#endif\n  sqlite3_open_v2,\n  sqlite3_release_memory,\n  sqlite3_result_error_nomem,\n  sqlite3_result_error_toobig,\n  sqlite3_sleep,\n  sqlite3_soft_heap_limit,\n  sqlite3_vfs_find,\n  sqlite3_vfs_register,\n  sqlite3_vfs_unregister,\n\n  /*\n  ** Added for 3.5.8\n  */\n  sqlite3_threadsafe,\n  sqlite3_result_zeroblob,\n  sqlite3_result_error_code,\n  sqlite3_test_control,\n  sqlite3_randomness,\n  sqlite3_context_db_handle,\n\n  /*\n  ** Added for 3.6.0\n  */\n  sqlite3_extended_result_codes,\n  sqlite3_limit,\n  sqlite3_next_stmt,\n  sqlite3_sql,\n  sqlite3_status,\n\n  /*\n  ** Added for 3.7.4\n  */\n  sqlite3_backup_finish,\n  sqlite3_backup_init,\n  sqlite3_backup_pagecount,\n  sqlite3_backup_remaining,\n  sqlite3_backup_step,\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n  sqlite3_compileoption_get,\n  sqlite3_compileoption_used,\n#else\n  0,\n  0,\n#endif\n  sqlite3_create_function_v2,\n  sqlite3_db_config,\n  sqlite3_db_mutex,\n  sqlite3_db_status,\n  sqlite3_extended_errcode,\n  sqlite3_log,\n  sqlite3_soft_heap_limit64,\n  sqlite3_sourceid,\n  sqlite3_stmt_status,\n  sqlite3_strnicmp,\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n  sqlite3_unlock_notify,\n#else\n  0,\n#endif\n#ifndef SQLITE_OMIT_WAL\n  sqlite3_wal_autocheckpoint,\n  sqlite3_wal_checkpoint,\n  sqlite3_wal_hook,\n#else\n  0,\n  0,\n  0,\n#endif\n  sqlite3_blob_reopen,\n  sqlite3_vtab_config,\n  sqlite3_vtab_on_conflict,\n};\n\n/*\n** Attempt to load an SQLite extension library contained in the file\n** zFile.  The entry point is zProc.  zProc may be 0 in which case a\n** default entry point name (sqlite3_extension_init) is used.  Use\n** of the default name is recommended.\n**\n** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.\n**\n** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with \n** error message text.  The calling function should free this memory\n** by calling sqlite3DbFree(db, ).\n*/\nstatic int sqlite3LoadExtension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Use \"sqlite3_extension_init\" if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n){\n  sqlite3_vfs *pVfs = db->pVfs;\n  void *handle;\n  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);\n  char *zErrmsg = 0;\n  void **aHandle;\n  int nMsg = 300 + sqlite3Strlen30(zFile);\n\n  if( pzErrMsg ) *pzErrMsg = 0;\n\n  /* Ticket #1863.  To avoid a creating security problems for older\n  ** applications that relink against newer versions of SQLite, the\n  ** ability to run load_extension is turned off by default.  One\n  ** must call sqlite3_enable_load_extension() to turn on extension\n  ** loading.  Otherwise you get the following error.\n  */\n  if( (db->flags & SQLITE_LoadExtension)==0 ){\n    if( pzErrMsg ){\n      *pzErrMsg = sqlite3_mprintf(\"not authorized\");\n    }\n    return SQLITE_ERROR;\n  }\n\n  if( zProc==0 ){\n    zProc = \"sqlite3_extension_init\";\n  }\n\n  handle = sqlite3OsDlOpen(pVfs, zFile);\n  if( handle==0 ){\n    if( pzErrMsg ){\n      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);\n      if( zErrmsg ){\n        sqlite3_snprintf(nMsg, zErrmsg, \n            \"unable to open shared library [%s]\", zFile);\n        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);\n      }\n    }\n    return SQLITE_ERROR;\n  }\n  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))\n                   sqlite3OsDlSym(pVfs, handle, zProc);\n  if( xInit==0 ){\n    if( pzErrMsg ){\n      nMsg += sqlite3Strlen30(zProc);\n      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);\n      if( zErrmsg ){\n        sqlite3_snprintf(nMsg, zErrmsg,\n            \"no entry point [%s] in shared library [%s]\", zProc,zFile);\n        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);\n      }\n      sqlite3OsDlClose(pVfs, handle);\n    }\n    return SQLITE_ERROR;\n  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){\n    if( pzErrMsg ){\n      *pzErrMsg = sqlite3_mprintf(\"error during initialization: %s\", zErrmsg);\n    }\n    sqlite3_free(zErrmsg);\n    sqlite3OsDlClose(pVfs, handle);\n    return SQLITE_ERROR;\n  }\n\n  /* Append the new shared library handle to the db->aExtension array. */\n  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));\n  if( aHandle==0 ){\n    return SQLITE_NOMEM;\n  }\n  if( db->nExtension>0 ){\n    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);\n  }\n  sqlite3DbFree(db, db->aExtension);\n  db->aExtension = aHandle;\n\n  db->aExtension[db->nExtension++] = handle;\n  return SQLITE_OK;\n}\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Use \"sqlite3_extension_init\" if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n){\n  int rc;\n  sqlite3_mutex_enter(db->mutex);\n  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Call this routine when the database connection is closing in order\n** to clean up loaded extensions\n*/\nSQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){\n  int i;\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(i=0; i<db->nExtension; i++){\n    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);\n  }\n  sqlite3DbFree(db, db->aExtension);\n}\n\n/*\n** Enable or disable extension loading.  Extension loading is disabled by\n** default so as not to open security holes in older applications.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){\n  sqlite3_mutex_enter(db->mutex);\n  if( onoff ){\n    db->flags |= SQLITE_LoadExtension;\n  }else{\n    db->flags &= ~SQLITE_LoadExtension;\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#endif /* SQLITE_OMIT_LOAD_EXTENSION */\n\n/*\n** The auto-extension code added regardless of whether or not extension\n** loading is supported.  We need a dummy sqlite3Apis pointer for that\n** code if regular extension loading is not available.  This is that\n** dummy pointer.\n*/\n#ifdef SQLITE_OMIT_LOAD_EXTENSION\nstatic const sqlite3_api_routines sqlite3Apis = { 0 };\n#endif\n\n\n/*\n** The following object holds the list of automatically loaded\n** extensions.\n**\n** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER\n** mutex must be held while accessing this list.\n*/\ntypedef struct sqlite3AutoExtList sqlite3AutoExtList;\nstatic SQLITE_WSD struct sqlite3AutoExtList {\n  int nExt;              /* Number of entries in aExt[] */          \n  void (**aExt)(void);   /* Pointers to the extension init functions */\n} sqlite3Autoext = { 0, 0 };\n\n/* The \"wsdAutoext\" macro will resolve to the autoextension\n** state vector.  If writable static data is unsupported on the target,\n** we have to locate the state vector at run-time.  In the more common\n** case where writable static data is supported, wsdStat can refer directly\n** to the \"sqlite3Autoext\" state vector declared above.\n*/\n#ifdef SQLITE_OMIT_WSD\n# define wsdAutoextInit \\\n  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)\n# define wsdAutoext x[0]\n#else\n# define wsdAutoextInit\n# define wsdAutoext sqlite3Autoext\n#endif\n\n\n/*\n** Register a statically linked extension that is automatically\n** loaded by every new database connection.\n*/\nSQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){\n  int rc = SQLITE_OK;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ){\n    return rc;\n  }else\n#endif\n  {\n    int i;\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n    wsdAutoextInit;\n    sqlite3_mutex_enter(mutex);\n    for(i=0; i<wsdAutoext.nExt; i++){\n      if( wsdAutoext.aExt[i]==xInit ) break;\n    }\n    if( i==wsdAutoext.nExt ){\n      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);\n      void (**aNew)(void);\n      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);\n      if( aNew==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        wsdAutoext.aExt = aNew;\n        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;\n        wsdAutoext.nExt++;\n      }\n    }\n    sqlite3_mutex_leave(mutex);\n    assert( (rc&0xff)==rc );\n    return rc;\n  }\n}\n\n/*\n** Reset the automatic extension loading mechanism.\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void){\n#ifndef SQLITE_OMIT_AUTOINIT\n  if( sqlite3_initialize()==SQLITE_OK )\n#endif\n  {\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n    wsdAutoextInit;\n    sqlite3_mutex_enter(mutex);\n    sqlite3_free(wsdAutoext.aExt);\n    wsdAutoext.aExt = 0;\n    wsdAutoext.nExt = 0;\n    sqlite3_mutex_leave(mutex);\n  }\n}\n\n/*\n** Load all automatic extensions.\n**\n** If anything goes wrong, set an error in the database connection.\n*/\nSQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){\n  int i;\n  int go = 1;\n  int rc;\n  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);\n\n  wsdAutoextInit;\n  if( wsdAutoext.nExt==0 ){\n    /* Common case: early out without every having to acquire a mutex */\n    return;\n  }\n  for(i=0; go; i++){\n    char *zErrmsg;\n#if SQLITE_THREADSAFE\n    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);\n#endif\n    sqlite3_mutex_enter(mutex);\n    if( i>=wsdAutoext.nExt ){\n      xInit = 0;\n      go = 0;\n    }else{\n      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))\n              wsdAutoext.aExt[i];\n    }\n    sqlite3_mutex_leave(mutex);\n    zErrmsg = 0;\n    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){\n      sqlite3Error(db, rc,\n            \"automatic extension loading failed: %s\", zErrmsg);\n      go = 0;\n    }\n    sqlite3_free(zErrmsg);\n  }\n}\n\n/************** End of loadext.c *********************************************/\n/************** Begin file pragma.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the PRAGMA command.\n*/\n\n/*\n** Interpret the given string as a safety level.  Return 0 for OFF,\n** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or \n** unrecognized string argument.  The FULL option is disallowed\n** if the omitFull parameter it 1.\n**\n** Note that the values returned are one less that the values that\n** should be passed into sqlite3BtreeSetSafetyLevel().  The is done\n** to support legacy SQL code.  The safety level used to be boolean\n** and older scripts may have used numbers 0 for OFF and 1 for ON.\n*/\nstatic u8 getSafetyLevel(const char *z, int omitFull, int dflt){\n                             /* 123456789 123456789 */\n  static const char zText[] = \"onoffalseyestruefull\";\n  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};\n  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};\n  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};\n  int i, n;\n  if( sqlite3Isdigit(*z) ){\n    return (u8)sqlite3Atoi(z);\n  }\n  n = sqlite3Strlen30(z);\n  for(i=0; i<ArraySize(iLength)-omitFull; i++){\n    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){\n      return iValue[i];\n    }\n  }\n  return dflt;\n}\n\n/*\n** Interpret the given string as a boolean value.\n*/\nSQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){\n  return getSafetyLevel(z,1,dflt)!=0;\n}\n\n/* The sqlite3GetBoolean() function is used by other modules but the\n** remainder of this file is specific to PRAGMA processing.  So omit\n** the rest of the file if PRAGMAs are omitted from the build.\n*/\n#if !defined(SQLITE_OMIT_PRAGMA)\n\n/*\n** Interpret the given string as a locking mode value.\n*/\nstatic int getLockingMode(const char *z){\n  if( z ){\n    if( 0==sqlite3StrICmp(z, \"exclusive\") ) return PAGER_LOCKINGMODE_EXCLUSIVE;\n    if( 0==sqlite3StrICmp(z, \"normal\") ) return PAGER_LOCKINGMODE_NORMAL;\n  }\n  return PAGER_LOCKINGMODE_QUERY;\n}\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n/*\n** Interpret the given string as an auto-vacuum mode value.\n**\n** The following strings, \"none\", \"full\" and \"incremental\" are \n** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.\n*/\nstatic int getAutoVacuum(const char *z){\n  int i;\n  if( 0==sqlite3StrICmp(z, \"none\") ) return BTREE_AUTOVACUUM_NONE;\n  if( 0==sqlite3StrICmp(z, \"full\") ) return BTREE_AUTOVACUUM_FULL;\n  if( 0==sqlite3StrICmp(z, \"incremental\") ) return BTREE_AUTOVACUUM_INCR;\n  i = sqlite3Atoi(z);\n  return (u8)((i>=0&&i<=2)?i:0);\n}\n#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** Interpret the given string as a temp db location. Return 1 for file\n** backed temporary databases, 2 for the Red-Black tree in memory database\n** and 0 to use the compile-time default.\n*/\nstatic int getTempStore(const char *z){\n  if( z[0]>='0' && z[0]<='2' ){\n    return z[0] - '0';\n  }else if( sqlite3StrICmp(z, \"file\")==0 ){\n    return 1;\n  }else if( sqlite3StrICmp(z, \"memory\")==0 ){\n    return 2;\n  }else{\n    return 0;\n  }\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** Invalidate temp storage, either when the temp storage is changed\n** from default, or when 'file' and the temp_store_directory has changed\n*/\nstatic int invalidateTempStorage(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  if( db->aDb[1].pBt!=0 ){\n    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){\n      sqlite3ErrorMsg(pParse, \"temporary storage cannot be changed \"\n        \"from within a transaction\");\n      return SQLITE_ERROR;\n    }\n    sqlite3BtreeClose(db->aDb[1].pBt);\n    db->aDb[1].pBt = 0;\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n  return SQLITE_OK;\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n/*\n** If the TEMP database is open, close it and mark the database schema\n** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE\n** or DEFAULT_TEMP_STORE pragmas.\n*/\nstatic int changeTempStorage(Parse *pParse, const char *zStorageType){\n  int ts = getTempStore(zStorageType);\n  sqlite3 *db = pParse->db;\n  if( db->temp_store==ts ) return SQLITE_OK;\n  if( invalidateTempStorage( pParse ) != SQLITE_OK ){\n    return SQLITE_ERROR;\n  }\n  db->temp_store = (u8)ts;\n  return SQLITE_OK;\n}\n#endif /* SQLITE_PAGER_PRAGMAS */\n\n/*\n** Generate code to return a single integer value.\n*/\nstatic void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  int mem = ++pParse->nMem;\n  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));\n  if( pI64 ){\n    memcpy(pI64, &value, sizeof(value));\n  }\n  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);\n  sqlite3VdbeSetNumCols(v, 1);\n  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);\n  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);\n}\n\n#ifndef SQLITE_OMIT_FLAG_PRAGMAS\n/*\n** Check to see if zRight and zLeft refer to a pragma that queries\n** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.\n** Also, implement the pragma.\n*/\nstatic int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){\n  static const struct sPragmaType {\n    const char *zName;  /* Name of the pragma */\n    int mask;           /* Mask for the db->flags value */\n  } aPragma[] = {\n    { \"full_column_names\",        SQLITE_FullColNames  },\n    { \"short_column_names\",       SQLITE_ShortColNames },\n    { \"count_changes\",            SQLITE_CountRows     },\n    { \"empty_result_callbacks\",   SQLITE_NullCallback  },\n    { \"legacy_file_format\",       SQLITE_LegacyFileFmt },\n    { \"fullfsync\",                SQLITE_FullFSync     },\n    { \"checkpoint_fullfsync\",     SQLITE_CkptFullFSync },\n    { \"reverse_unordered_selects\", SQLITE_ReverseOrder  },\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n    { \"automatic_index\",          SQLITE_AutoIndex     },\n#endif\n#ifdef SQLITE_DEBUG\n    { \"sql_trace\",                SQLITE_SqlTrace      },\n    { \"vdbe_listing\",             SQLITE_VdbeListing   },\n    { \"vdbe_trace\",               SQLITE_VdbeTrace     },\n#endif\n#ifndef SQLITE_OMIT_CHECK\n    { \"ignore_check_constraints\", SQLITE_IgnoreChecks  },\n#endif\n    /* The following is VERY experimental */\n    { \"writable_schema\",          SQLITE_WriteSchema|SQLITE_RecoveryMode },\n\n    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted\n    ** flag if there are any active statements. */\n    { \"read_uncommitted\",         SQLITE_ReadUncommitted },\n    { \"recursive_triggers\",       SQLITE_RecTriggers },\n\n    /* This flag may only be set if both foreign-key and trigger support\n    ** are present in the build.  */\n#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)\n    { \"foreign_keys\",             SQLITE_ForeignKeys },\n#endif\n  };\n  int i;\n  const struct sPragmaType *p;\n  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){\n    if( sqlite3StrICmp(zLeft, p->zName)==0 ){\n      sqlite3 *db = pParse->db;\n      Vdbe *v;\n      v = sqlite3GetVdbe(pParse);\n      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */\n      if( ALWAYS(v) ){\n        if( zRight==0 ){\n          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );\n        }else{\n          int mask = p->mask;          /* Mask of bits to set or clear. */\n          if( db->autoCommit==0 ){\n            /* Foreign key support may not be enabled or disabled while not\n            ** in auto-commit mode.  */\n            mask &= ~(SQLITE_ForeignKeys);\n          }\n\n          if( sqlite3GetBoolean(zRight, 0) ){\n            db->flags |= mask;\n          }else{\n            db->flags &= ~mask;\n          }\n\n          /* Many of the flag-pragmas modify the code generated by the SQL \n          ** compiler (eg. count_changes). So add an opcode to expire all\n          ** compiled SQL statements after modifying a pragma value.\n          */\n          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);\n        }\n      }\n\n      return 1;\n    }\n  }\n  return 0;\n}\n#endif /* SQLITE_OMIT_FLAG_PRAGMAS */\n\n/*\n** Return a human-readable name for a constraint resolution action.\n*/\n#ifndef SQLITE_OMIT_FOREIGN_KEY\nstatic const char *actionName(u8 action){\n  const char *zName;\n  switch( action ){\n    case OE_SetNull:  zName = \"SET NULL\";        break;\n    case OE_SetDflt:  zName = \"SET DEFAULT\";     break;\n    case OE_Cascade:  zName = \"CASCADE\";         break;\n    case OE_Restrict: zName = \"RESTRICT\";        break;\n    default:          zName = \"NO ACTION\";  \n                      assert( action==OE_None ); break;\n  }\n  return zName;\n}\n#endif\n\n\n/*\n** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants\n** defined in pager.h. This function returns the associated lowercase\n** journal-mode name.\n*/\nSQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){\n  static char * const azModeName[] = {\n    \"delete\", \"persist\", \"off\", \"truncate\", \"memory\"\n#ifndef SQLITE_OMIT_WAL\n     , \"wal\"\n#endif\n  };\n  assert( PAGER_JOURNALMODE_DELETE==0 );\n  assert( PAGER_JOURNALMODE_PERSIST==1 );\n  assert( PAGER_JOURNALMODE_OFF==2 );\n  assert( PAGER_JOURNALMODE_TRUNCATE==3 );\n  assert( PAGER_JOURNALMODE_MEMORY==4 );\n  assert( PAGER_JOURNALMODE_WAL==5 );\n  assert( eMode>=0 && eMode<=ArraySize(azModeName) );\n\n  if( eMode==ArraySize(azModeName) ) return 0;\n  return azModeName[eMode];\n}\n\n/*\n** Process a pragma statement.  \n**\n** Pragmas are of this form:\n**\n**      PRAGMA [database.]id [= value]\n**\n** The identifier might also be a string.  The value is a string, and\n** identifier, or a number.  If minusFlag is true, then the value is\n** a number that was preceded by a minus sign.\n**\n** If the left side is \"database.id\" then pId1 is the database name\n** and pId2 is the id.  If the left side is just \"id\" then pId1 is the\n** id and pId2 is any empty string.\n*/\nSQLITE_PRIVATE void sqlite3Pragma(\n  Parse *pParse, \n  Token *pId1,        /* First part of [database.]id field */\n  Token *pId2,        /* Second part of [database.]id field, or NULL */\n  Token *pValue,      /* Token for <value>, or NULL */\n  int minusFlag       /* True if a '-' sign preceded <value> */\n){\n  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */\n  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */\n  const char *zDb = 0;   /* The database name */\n  Token *pId;            /* Pointer to <id> token */\n  int iDb;               /* Database index for <database> */\n  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */\n  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */\n  sqlite3 *db = pParse->db;    /* The database connection */\n  Db *pDb;                     /* The specific database being pragmaed */\n  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */\n\n  if( v==0 ) return;\n  sqlite3VdbeRunOnlyOnce(v);\n  pParse->nMem = 2;\n\n  /* Interpret the [database.] part of the pragma statement. iDb is the\n  ** index of the database this pragma is being applied to in db.aDb[]. */\n  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);\n  if( iDb<0 ) return;\n  pDb = &db->aDb[iDb];\n\n  /* If the temp database has been explicitly named as part of the \n  ** pragma, make sure it is open. \n  */\n  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){\n    return;\n  }\n\n  zLeft = sqlite3NameFromToken(db, pId);\n  if( !zLeft ) return;\n  if( minusFlag ){\n    zRight = sqlite3MPrintf(db, \"-%T\", pValue);\n  }else{\n    zRight = sqlite3NameFromToken(db, pValue);\n  }\n\n  assert( pId2 );\n  zDb = pId2->n>0 ? pDb->zName : 0;\n  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){\n    goto pragma_out;\n  }\n\n  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS\n  ** connection.  If it returns SQLITE_OK, then assume that the VFS\n  ** handled the pragma and generate a no-op prepared statement.\n  */\n  aFcntl[0] = 0;\n  aFcntl[1] = zLeft;\n  aFcntl[2] = zRight;\n  aFcntl[3] = 0;\n  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);\n  if( rc==SQLITE_OK ){\n    if( aFcntl[0] ){\n      int mem = ++pParse->nMem;\n      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);\n      sqlite3VdbeSetNumCols(v, 1);\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"result\", SQLITE_STATIC);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);\n      sqlite3_free(aFcntl[0]);\n    }\n  }else if( rc!=SQLITE_NOTFOUND ){\n    if( aFcntl[0] ){\n      sqlite3ErrorMsg(pParse, \"%s\", aFcntl[0]);\n      sqlite3_free(aFcntl[0]);\n    }\n    pParse->nErr++;\n    pParse->rc = rc;\n  }else\n                            \n \n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)\n  /*\n  **  PRAGMA [database.]default_cache_size\n  **  PRAGMA [database.]default_cache_size=N\n  **\n  ** The first form reports the current persistent setting for the\n  ** page cache size.  The value returned is the maximum number of\n  ** pages in the page cache.  The second form sets both the current\n  ** page cache size value and the persistent page cache size value\n  ** stored in the database file.\n  **\n  ** Older versions of SQLite would set the default cache size to a\n  ** negative number to indicate synchronous=OFF.  These days, synchronous\n  ** is always on by default regardless of the sign of the default cache\n  ** size.  But continue to take the absolute value of the default cache\n  ** size of historical compatibility.\n  */\n  if( sqlite3StrICmp(zLeft,\"default_cache_size\")==0 ){\n    static const VdbeOpList getCacheSize[] = {\n      { OP_Transaction, 0, 0,        0},                         /* 0 */\n      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */\n      { OP_IfPos,       1, 7,        0},\n      { OP_Integer,     0, 2,        0},\n      { OP_Subtract,    1, 2,        1},\n      { OP_IfPos,       1, 7,        0},\n      { OP_Integer,     0, 1,        0},                         /* 6 */\n      { OP_ResultRow,   1, 1,        0},\n    };\n    int addr;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    sqlite3VdbeUsesBtree(v, iDb);\n    if( !zRight ){\n      sqlite3VdbeSetNumCols(v, 1);\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"cache_size\", SQLITE_STATIC);\n      pParse->nMem += 2;\n      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);\n      sqlite3VdbeChangeP1(v, addr, iDb);\n      sqlite3VdbeChangeP1(v, addr+1, iDb);\n      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);\n    }else{\n      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));\n      sqlite3BeginWriteOperation(pParse, 0, iDb);\n      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);\n      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);\n      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n      pDb->pSchema->cache_size = size;\n      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n    }\n  }else\n#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */\n\n#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)\n  /*\n  **  PRAGMA [database.]page_size\n  **  PRAGMA [database.]page_size=N\n  **\n  ** The first form reports the current setting for the\n  ** database page size in bytes.  The second form sets the\n  ** database page size value.  The value can only be set if\n  ** the database has not yet been created.\n  */\n  if( sqlite3StrICmp(zLeft,\"page_size\")==0 ){\n    Btree *pBt = pDb->pBt;\n    assert( pBt!=0 );\n    if( !zRight ){\n      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;\n      returnSingleInt(pParse, \"page_size\", size);\n    }else{\n      /* Malloc may fail when setting the page-size, as there is an internal\n      ** buffer that the pager module resizes using sqlite3_realloc().\n      */\n      db->nextPagesize = sqlite3Atoi(zRight);\n      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){\n        db->mallocFailed = 1;\n      }\n    }\n  }else\n\n  /*\n  **  PRAGMA [database.]secure_delete\n  **  PRAGMA [database.]secure_delete=ON/OFF\n  **\n  ** The first form reports the current setting for the\n  ** secure_delete flag.  The second form changes the secure_delete\n  ** flag setting and reports thenew value.\n  */\n  if( sqlite3StrICmp(zLeft,\"secure_delete\")==0 ){\n    Btree *pBt = pDb->pBt;\n    int b = -1;\n    assert( pBt!=0 );\n    if( zRight ){\n      b = sqlite3GetBoolean(zRight, 0);\n    }\n    if( pId2->n==0 && b>=0 ){\n      int ii;\n      for(ii=0; ii<db->nDb; ii++){\n        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);\n      }\n    }\n    b = sqlite3BtreeSecureDelete(pBt, b);\n    returnSingleInt(pParse, \"secure_delete\", b);\n  }else\n\n  /*\n  **  PRAGMA [database.]max_page_count\n  **  PRAGMA [database.]max_page_count=N\n  **\n  ** The first form reports the current setting for the\n  ** maximum number of pages in the database file.  The \n  ** second form attempts to change this setting.  Both\n  ** forms return the current setting.\n  **\n  ** The absolute value of N is used.  This is undocumented and might\n  ** change.  The only purpose is to provide an easy way to test\n  ** the sqlite3AbsInt32() function.\n  **\n  **  PRAGMA [database.]page_count\n  **\n  ** Return the number of pages in the specified database.\n  */\n  if( sqlite3StrICmp(zLeft,\"page_count\")==0\n   || sqlite3StrICmp(zLeft,\"max_page_count\")==0\n  ){\n    int iReg;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    sqlite3CodeVerifySchema(pParse, iDb);\n    iReg = ++pParse->nMem;\n    if( sqlite3Tolower(zLeft[0])=='p' ){\n      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);\n    }else{\n      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, \n                        sqlite3AbsInt32(sqlite3Atoi(zRight)));\n    }\n    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);\n  }else\n\n  /*\n  **  PRAGMA [database.]locking_mode\n  **  PRAGMA [database.]locking_mode = (normal|exclusive)\n  */\n  if( sqlite3StrICmp(zLeft,\"locking_mode\")==0 ){\n    const char *zRet = \"normal\";\n    int eMode = getLockingMode(zRight);\n\n    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){\n      /* Simple \"PRAGMA locking_mode;\" statement. This is a query for\n      ** the current default locking mode (which may be different to\n      ** the locking-mode of the main database).\n      */\n      eMode = db->dfltLockMode;\n    }else{\n      Pager *pPager;\n      if( pId2->n==0 ){\n        /* This indicates that no database name was specified as part\n        ** of the PRAGMA command. In this case the locking-mode must be\n        ** set on all attached databases, as well as the main db file.\n        **\n        ** Also, the sqlite3.dfltLockMode variable is set so that\n        ** any subsequently attached databases also use the specified\n        ** locking mode.\n        */\n        int ii;\n        assert(pDb==&db->aDb[0]);\n        for(ii=2; ii<db->nDb; ii++){\n          pPager = sqlite3BtreePager(db->aDb[ii].pBt);\n          sqlite3PagerLockingMode(pPager, eMode);\n        }\n        db->dfltLockMode = (u8)eMode;\n      }\n      pPager = sqlite3BtreePager(pDb->pBt);\n      eMode = sqlite3PagerLockingMode(pPager, eMode);\n    }\n\n    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);\n    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){\n      zRet = \"exclusive\";\n    }\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"locking_mode\", SQLITE_STATIC);\n    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n  }else\n\n  /*\n  **  PRAGMA [database.]journal_mode\n  **  PRAGMA [database.]journal_mode =\n  **                      (delete|persist|off|truncate|memory|wal|off)\n  */\n  if( sqlite3StrICmp(zLeft,\"journal_mode\")==0 ){\n    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */\n    int ii;           /* Loop counter */\n\n    /* Force the schema to be loaded on all databases.  This causes all\n    ** database files to be opened and the journal_modes set.  This is\n    ** necessary because subsequent processing must know if the databases\n    ** are in WAL mode. */\n    if( sqlite3ReadSchema(pParse) ){\n      goto pragma_out;\n    }\n\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"journal_mode\", SQLITE_STATIC);\n\n    if( zRight==0 ){\n      /* If there is no \"=MODE\" part of the pragma, do a query for the\n      ** current mode */\n      eMode = PAGER_JOURNALMODE_QUERY;\n    }else{\n      const char *zMode;\n      int n = sqlite3Strlen30(zRight);\n      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){\n        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;\n      }\n      if( !zMode ){\n        /* If the \"=MODE\" part does not match any known journal mode,\n        ** then do a query */\n        eMode = PAGER_JOURNALMODE_QUERY;\n      }\n    }\n    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){\n      /* Convert \"PRAGMA journal_mode\" into \"PRAGMA main.journal_mode\" */\n      iDb = 0;\n      pId2->n = 1;\n    }\n    for(ii=db->nDb-1; ii>=0; ii--){\n      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){\n        sqlite3VdbeUsesBtree(v, ii);\n        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n  }else\n\n  /*\n  **  PRAGMA [database.]journal_size_limit\n  **  PRAGMA [database.]journal_size_limit=N\n  **\n  ** Get or set the size limit on rollback journal files.\n  */\n  if( sqlite3StrICmp(zLeft,\"journal_size_limit\")==0 ){\n    Pager *pPager = sqlite3BtreePager(pDb->pBt);\n    i64 iLimit = -2;\n    if( zRight ){\n      sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);\n      if( iLimit<-1 ) iLimit = -1;\n    }\n    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);\n    returnSingleInt(pParse, \"journal_size_limit\", iLimit);\n  }else\n\n#endif /* SQLITE_OMIT_PAGER_PRAGMAS */\n\n  /*\n  **  PRAGMA [database.]auto_vacuum\n  **  PRAGMA [database.]auto_vacuum=N\n  **\n  ** Get or set the value of the database 'auto-vacuum' parameter.\n  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL\n  */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  if( sqlite3StrICmp(zLeft,\"auto_vacuum\")==0 ){\n    Btree *pBt = pDb->pBt;\n    assert( pBt!=0 );\n    if( sqlite3ReadSchema(pParse) ){\n      goto pragma_out;\n    }\n    if( !zRight ){\n      int auto_vacuum;\n      if( ALWAYS(pBt) ){\n         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);\n      }else{\n         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;\n      }\n      returnSingleInt(pParse, \"auto_vacuum\", auto_vacuum);\n    }else{\n      int eAuto = getAutoVacuum(zRight);\n      assert( eAuto>=0 && eAuto<=2 );\n      db->nextAutovac = (u8)eAuto;\n      if( ALWAYS(eAuto>=0) ){\n        /* Call SetAutoVacuum() to set initialize the internal auto and\n        ** incr-vacuum flags. This is required in case this connection\n        ** creates the database file. It is important that it is created\n        ** as an auto-vacuum capable db.\n        */\n        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);\n        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){\n          /* When setting the auto_vacuum mode to either \"full\" or \n          ** \"incremental\", write the value of meta[6] in the database\n          ** file. Before writing to meta[6], check that meta[3] indicates\n          ** that this really is an auto-vacuum capable database.\n          */\n          static const VdbeOpList setMeta6[] = {\n            { OP_Transaction,    0,         1,                 0},    /* 0 */\n            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},\n            { OP_If,             1,         0,                 0},    /* 2 */\n            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */\n            { OP_Integer,        0,         1,                 0},    /* 4 */\n            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */\n          };\n          int iAddr;\n          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);\n          sqlite3VdbeChangeP1(v, iAddr, iDb);\n          sqlite3VdbeChangeP1(v, iAddr+1, iDb);\n          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);\n          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);\n          sqlite3VdbeChangeP1(v, iAddr+5, iDb);\n          sqlite3VdbeUsesBtree(v, iDb);\n        }\n      }\n    }\n  }else\n#endif\n\n  /*\n  **  PRAGMA [database.]incremental_vacuum(N)\n  **\n  ** Do N steps of incremental vacuuming on a database.\n  */\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  if( sqlite3StrICmp(zLeft,\"incremental_vacuum\")==0 ){\n    int iLimit, addr;\n    if( sqlite3ReadSchema(pParse) ){\n      goto pragma_out;\n    }\n    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){\n      iLimit = 0x7fffffff;\n    }\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);\n    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);\n    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);\n    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);\n    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);\n    sqlite3VdbeJumpHere(v, addr);\n  }else\n#endif\n\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n  /*\n  **  PRAGMA [database.]cache_size\n  **  PRAGMA [database.]cache_size=N\n  **\n  ** The first form reports the current local setting for the\n  ** page cache size. The second form sets the local\n  ** page cache size value.  If N is positive then that is the\n  ** number of pages in the cache.  If N is negative, then the\n  ** number of pages is adjusted so that the cache uses -N kibibytes\n  ** of memory.\n  */\n  if( sqlite3StrICmp(zLeft,\"cache_size\")==0 ){\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( !zRight ){\n      returnSingleInt(pParse, \"cache_size\", pDb->pSchema->cache_size);\n    }else{\n      int size = sqlite3Atoi(zRight);\n      pDb->pSchema->cache_size = size;\n      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n    }\n  }else\n\n  /*\n  **   PRAGMA temp_store\n  **   PRAGMA temp_store = \"default\"|\"memory\"|\"file\"\n  **\n  ** Return or set the local value of the temp_store flag.  Changing\n  ** the local value does not make changes to the disk file and the default\n  ** value will be restored the next time the database is opened.\n  **\n  ** Note that it is possible for the library compile-time options to\n  ** override this setting\n  */\n  if( sqlite3StrICmp(zLeft, \"temp_store\")==0 ){\n    if( !zRight ){\n      returnSingleInt(pParse, \"temp_store\", db->temp_store);\n    }else{\n      changeTempStorage(pParse, zRight);\n    }\n  }else\n\n  /*\n  **   PRAGMA temp_store_directory\n  **   PRAGMA temp_store_directory = \"\"|\"directory_name\"\n  **\n  ** Return or set the local value of the temp_store_directory flag.  Changing\n  ** the value sets a specific directory to be used for temporary files.\n  ** Setting to a null string reverts to the default temporary directory search.\n  ** If temporary directory is changed, then invalidateTempStorage.\n  **\n  */\n  if( sqlite3StrICmp(zLeft, \"temp_store_directory\")==0 ){\n    if( !zRight ){\n      if( sqlite3_temp_directory ){\n        sqlite3VdbeSetNumCols(v, 1);\n        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \n            \"temp_store_directory\", SQLITE_STATIC);\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n      }\n    }else{\n#ifndef SQLITE_OMIT_WSD\n      if( zRight[0] ){\n        int res;\n        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);\n        if( rc!=SQLITE_OK || res==0 ){\n          sqlite3ErrorMsg(pParse, \"not a writable directory\");\n          goto pragma_out;\n        }\n      }\n      if( SQLITE_TEMP_STORE==0\n       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)\n       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)\n      ){\n        invalidateTempStorage(pParse);\n      }\n      sqlite3_free(sqlite3_temp_directory);\n      if( zRight[0] ){\n        sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zRight);\n      }else{\n        sqlite3_temp_directory = 0;\n      }\n#endif /* SQLITE_OMIT_WSD */\n    }\n  }else\n\n#if SQLITE_OS_WIN\n  /*\n  **   PRAGMA data_store_directory\n  **   PRAGMA data_store_directory = \"\"|\"directory_name\"\n  **\n  ** Return or set the local value of the data_store_directory flag.  Changing\n  ** the value sets a specific directory to be used for database files that\n  ** were specified with a relative pathname.  Setting to a null string reverts\n  ** to the default database directory, which for database files specified with\n  ** a relative path will probably be based on the current directory for the\n  ** process.  Database file specified with an absolute path are not impacted\n  ** by this setting, regardless of its value.\n  **\n  */\n  if( sqlite3StrICmp(zLeft, \"data_store_directory\")==0 ){\n    if( !zRight ){\n      if( sqlite3_data_directory ){\n        sqlite3VdbeSetNumCols(v, 1);\n        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \n            \"data_store_directory\", SQLITE_STATIC);\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n      }\n    }else{\n#ifndef SQLITE_OMIT_WSD\n      if( zRight[0] ){\n        int res;\n        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);\n        if( rc!=SQLITE_OK || res==0 ){\n          sqlite3ErrorMsg(pParse, \"not a writable directory\");\n          goto pragma_out;\n        }\n      }\n      sqlite3_free(sqlite3_data_directory);\n      if( zRight[0] ){\n        sqlite3_data_directory = sqlite3_mprintf(\"%s\", zRight);\n      }else{\n        sqlite3_data_directory = 0;\n      }\n#endif /* SQLITE_OMIT_WSD */\n    }\n  }else\n#endif\n\n#if !defined(SQLITE_ENABLE_LOCKING_STYLE)\n#  if defined(__APPLE__)\n#    define SQLITE_ENABLE_LOCKING_STYLE 1\n#  else\n#    define SQLITE_ENABLE_LOCKING_STYLE 0\n#  endif\n#endif\n#if SQLITE_ENABLE_LOCKING_STYLE\n  /*\n   **   PRAGMA [database.]lock_proxy_file\n   **   PRAGMA [database.]lock_proxy_file = \":auto:\"|\"lock_file_path\"\n   **\n   ** Return or set the value of the lock_proxy_file flag.  Changing\n   ** the value sets a specific file to be used for database access locks.\n   **\n   */\n  if( sqlite3StrICmp(zLeft, \"lock_proxy_file\")==0 ){\n    if( !zRight ){\n      Pager *pPager = sqlite3BtreePager(pDb->pBt);\n      char *proxy_file_path = NULL;\n      sqlite3_file *pFile = sqlite3PagerFile(pPager);\n      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, \n                           &proxy_file_path);\n      \n      if( proxy_file_path ){\n        sqlite3VdbeSetNumCols(v, 1);\n        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \n                              \"lock_proxy_file\", SQLITE_STATIC);\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n      }\n    }else{\n      Pager *pPager = sqlite3BtreePager(pDb->pBt);\n      sqlite3_file *pFile = sqlite3PagerFile(pPager);\n      int res;\n      if( zRight[0] ){\n        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, \n                                     zRight);\n      } else {\n        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, \n                                     NULL);\n      }\n      if( res!=SQLITE_OK ){\n        sqlite3ErrorMsg(pParse, \"failed to set lock proxy file\");\n        goto pragma_out;\n      }\n    }\n  }else\n#endif /* SQLITE_ENABLE_LOCKING_STYLE */      \n    \n  /*\n  **   PRAGMA [database.]synchronous\n  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL\n  **\n  ** Return or set the local value of the synchronous flag.  Changing\n  ** the local value does not make changes to the disk file and the\n  ** default value will be restored the next time the database is\n  ** opened.\n  */\n  if( sqlite3StrICmp(zLeft,\"synchronous\")==0 ){\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    if( !zRight ){\n      returnSingleInt(pParse, \"synchronous\", pDb->safety_level-1);\n    }else{\n      if( !db->autoCommit ){\n        sqlite3ErrorMsg(pParse, \n            \"Safety level may not be changed inside a transaction\");\n      }else{\n        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;\n      }\n    }\n  }else\n#endif /* SQLITE_OMIT_PAGER_PRAGMAS */\n\n#ifndef SQLITE_OMIT_FLAG_PRAGMAS\n  if( flagPragma(pParse, zLeft, zRight) ){\n    /* The flagPragma() subroutine also generates any necessary code\n    ** there is nothing more to do here */\n  }else\n#endif /* SQLITE_OMIT_FLAG_PRAGMAS */\n\n#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS\n  /*\n  **   PRAGMA table_info(<table>)\n  **\n  ** Return a single row for each column of the named table. The columns of\n  ** the returned data set are:\n  **\n  ** cid:        Column id (numbered from left to right, starting at 0)\n  ** name:       Column name\n  ** type:       Column declaration type.\n  ** notnull:    True if 'NOT NULL' is part of column declaration\n  ** dflt_value: The default value for the column, if any.\n  */\n  if( sqlite3StrICmp(zLeft, \"table_info\")==0 && zRight ){\n    Table *pTab;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    pTab = sqlite3FindTable(db, zRight, zDb);\n    if( pTab ){\n      int i;\n      int nHidden = 0;\n      Column *pCol;\n      sqlite3VdbeSetNumCols(v, 6);\n      pParse->nMem = 6;\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"cid\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"name\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"type\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, \"notnull\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, \"dflt_value\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, \"pk\", SQLITE_STATIC);\n      sqlite3ViewGetColumnNames(pParse, pTab);\n      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){\n        if( IsHiddenColumn(pCol) ){\n          nHidden++;\n          continue;\n        }\n        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,\n           pCol->zType ? pCol->zType : \"\", 0);\n        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);\n        if( pCol->zDflt ){\n          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);\n        }else{\n          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);\n        }\n        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);\n      }\n    }\n  }else\n\n  if( sqlite3StrICmp(zLeft, \"index_info\")==0 && zRight ){\n    Index *pIdx;\n    Table *pTab;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    pIdx = sqlite3FindIndex(db, zRight, zDb);\n    if( pIdx ){\n      int i;\n      pTab = pIdx->pTable;\n      sqlite3VdbeSetNumCols(v, 3);\n      pParse->nMem = 3;\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"seqno\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"cid\", SQLITE_STATIC);\n      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"name\", SQLITE_STATIC);\n      for(i=0; i<pIdx->nColumn; i++){\n        int cnum = pIdx->aiColumn[i];\n        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);\n        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);\n        assert( pTab->nCol>cnum );\n        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);\n        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);\n      }\n    }\n  }else\n\n  if( sqlite3StrICmp(zLeft, \"index_list\")==0 && zRight ){\n    Index *pIdx;\n    Table *pTab;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    pTab = sqlite3FindTable(db, zRight, zDb);\n    if( pTab ){\n      v = sqlite3GetVdbe(pParse);\n      pIdx = pTab->pIndex;\n      if( pIdx ){\n        int i = 0; \n        sqlite3VdbeSetNumCols(v, 3);\n        pParse->nMem = 3;\n        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"seq\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"name\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"unique\", SQLITE_STATIC);\n        while(pIdx){\n          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);\n          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);\n          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);\n          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);\n          ++i;\n          pIdx = pIdx->pNext;\n        }\n      }\n    }\n  }else\n\n  if( sqlite3StrICmp(zLeft, \"database_list\")==0 ){\n    int i;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    sqlite3VdbeSetNumCols(v, 3);\n    pParse->nMem = 3;\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"seq\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"name\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"file\", SQLITE_STATIC);\n    for(i=0; i<db->nDb; i++){\n      if( db->aDb[i].pBt==0 ) continue;\n      assert( db->aDb[i].zName!=0 );\n      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,\n           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);\n    }\n  }else\n\n  if( sqlite3StrICmp(zLeft, \"collation_list\")==0 ){\n    int i = 0;\n    HashElem *p;\n    sqlite3VdbeSetNumCols(v, 2);\n    pParse->nMem = 2;\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"seq\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"name\", SQLITE_STATIC);\n    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){\n      CollSeq *pColl = (CollSeq *)sqliteHashData(p);\n      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);\n    }\n  }else\n#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */\n\n#ifndef SQLITE_OMIT_FOREIGN_KEY\n  if( sqlite3StrICmp(zLeft, \"foreign_key_list\")==0 && zRight ){\n    FKey *pFK;\n    Table *pTab;\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    pTab = sqlite3FindTable(db, zRight, zDb);\n    if( pTab ){\n      v = sqlite3GetVdbe(pParse);\n      pFK = pTab->pFKey;\n      if( pFK ){\n        int i = 0; \n        sqlite3VdbeSetNumCols(v, 8);\n        pParse->nMem = 8;\n        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"id\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"seq\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"table\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, \"from\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, \"to\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, \"on_update\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, \"on_delete\", SQLITE_STATIC);\n        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, \"match\", SQLITE_STATIC);\n        while(pFK){\n          int j;\n          for(j=0; j<pFK->nCol; j++){\n            char *zCol = pFK->aCol[j].zCol;\n            char *zOnDelete = (char *)actionName(pFK->aAction[0]);\n            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);\n            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);\n            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,\n                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);\n            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);\n            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, \"NONE\", 0);\n            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);\n          }\n          ++i;\n          pFK = pFK->pNextFrom;\n        }\n      }\n    }\n  }else\n#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */\n\n#ifndef NDEBUG\n  if( sqlite3StrICmp(zLeft, \"parser_trace\")==0 ){\n    if( zRight ){\n      if( sqlite3GetBoolean(zRight, 0) ){\n        sqlite3ParserTrace(stderr, \"parser: \");\n      }else{\n        sqlite3ParserTrace(0, 0);\n      }\n    }\n  }else\n#endif\n\n  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE\n  ** used will be case sensitive or not depending on the RHS.\n  */\n  if( sqlite3StrICmp(zLeft, \"case_sensitive_like\")==0 ){\n    if( zRight ){\n      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));\n    }\n  }else\n\n#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX\n# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100\n#endif\n\n#ifndef SQLITE_OMIT_INTEGRITY_CHECK\n  /* Pragma \"quick_check\" is an experimental reduced version of \n  ** integrity_check designed to detect most database corruption\n  ** without most of the overhead of a full integrity-check.\n  */\n  if( sqlite3StrICmp(zLeft, \"integrity_check\")==0\n   || sqlite3StrICmp(zLeft, \"quick_check\")==0 \n  ){\n    int i, j, addr, mxErr;\n\n    /* Code that appears at the end of the integrity check.  If no error\n    ** messages have been generated, output OK.  Otherwise output the\n    ** error message\n    */\n    static const VdbeOpList endCode[] = {\n      { OP_AddImm,      1, 0,        0},    /* 0 */\n      { OP_IfNeg,       1, 0,        0},    /* 1 */\n      { OP_String8,     0, 3,        0},    /* 2 */\n      { OP_ResultRow,   3, 1,        0},\n    };\n\n    int isQuick = (sqlite3Tolower(zLeft[0])=='q');\n\n    /* If the PRAGMA command was of the form \"PRAGMA <db>.integrity_check\",\n    ** then iDb is set to the index of the database identified by <db>.\n    ** In this case, the integrity of database iDb only is verified by\n    ** the VDBE created below.\n    **\n    ** Otherwise, if the command was simply \"PRAGMA integrity_check\" (or\n    ** \"PRAGMA quick_check\"), then iDb is set to 0. In this case, set iDb\n    ** to -1 here, to indicate that the VDBE should verify the integrity\n    ** of all attached databases.  */\n    assert( iDb>=0 );\n    assert( iDb==0 || pId2->z );\n    if( pId2->z==0 ) iDb = -1;\n\n    /* Initialize the VDBE program */\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    pParse->nMem = 6;\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"integrity_check\", SQLITE_STATIC);\n\n    /* Set the maximum error count */\n    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;\n    if( zRight ){\n      sqlite3GetInt32(zRight, &mxErr);\n      if( mxErr<=0 ){\n        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;\n      }\n    }\n    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */\n\n    /* Do an integrity check on each database file */\n    for(i=0; i<db->nDb; i++){\n      HashElem *x;\n      Hash *pTbls;\n      int cnt = 0;\n\n      if( OMIT_TEMPDB && i==1 ) continue;\n      if( iDb>=0 && i!=iDb ) continue;\n\n      sqlite3CodeVerifySchema(pParse, i);\n      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */\n      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);\n      sqlite3VdbeJumpHere(v, addr);\n\n      /* Do an integrity check of the B-Tree\n      **\n      ** Begin by filling registers 2, 3, ... with the root pages numbers\n      ** for all tables and indices in the database.\n      */\n      assert( sqlite3SchemaMutexHeld(db, i, 0) );\n      pTbls = &db->aDb[i].pSchema->tblHash;\n      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){\n        Table *pTab = sqliteHashData(x);\n        Index *pIdx;\n        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);\n        cnt++;\n        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);\n          cnt++;\n        }\n      }\n\n      /* Make sure sufficient number of registers have been allocated */\n      if( pParse->nMem < cnt+4 ){\n        pParse->nMem = cnt+4;\n      }\n\n      /* Do the b-tree integrity checks */\n      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);\n      sqlite3VdbeChangeP5(v, (u8)i);\n      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,\n         sqlite3MPrintf(db, \"*** in database %s ***\\n\", db->aDb[i].zName),\n         P4_DYNAMIC);\n      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);\n      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);\n      sqlite3VdbeJumpHere(v, addr);\n\n      /* Make sure all the indices are constructed correctly.\n      */\n      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){\n        Table *pTab = sqliteHashData(x);\n        Index *pIdx;\n        int loopTop;\n\n        if( pTab->pIndex==0 ) continue;\n        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */\n        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);\n        sqlite3VdbeJumpHere(v, addr);\n        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */\n        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);\n        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */\n        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n          int jmp2;\n          int r1;\n          static const VdbeOpList idxErr[] = {\n            { OP_AddImm,      1, -1,  0},\n            { OP_String8,     0,  3,  0},    /* 1 */\n            { OP_Rowid,       1,  4,  0},\n            { OP_String8,     0,  5,  0},    /* 3 */\n            { OP_String8,     0,  6,  0},    /* 4 */\n            { OP_Concat,      4,  3,  3},\n            { OP_Concat,      5,  3,  3},\n            { OP_Concat,      6,  3,  3},\n            { OP_ResultRow,   3,  1,  0},\n            { OP_IfPos,       1,  0,  0},    /* 9 */\n            { OP_Halt,        0,  0,  0},\n          };\n          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);\n          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);\n          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);\n          sqlite3VdbeChangeP4(v, addr+1, \"rowid \", P4_STATIC);\n          sqlite3VdbeChangeP4(v, addr+3, \" missing from index \", P4_STATIC);\n          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);\n          sqlite3VdbeJumpHere(v, addr+9);\n          sqlite3VdbeJumpHere(v, jmp2);\n        }\n        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);\n        sqlite3VdbeJumpHere(v, loopTop);\n        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n          static const VdbeOpList cntIdx[] = {\n             { OP_Integer,      0,  3,  0},\n             { OP_Rewind,       0,  0,  0},  /* 1 */\n             { OP_AddImm,       3,  1,  0},\n             { OP_Next,         0,  0,  0},  /* 3 */\n             { OP_Eq,           2,  0,  3},  /* 4 */\n             { OP_AddImm,       1, -1,  0},\n             { OP_String8,      0,  2,  0},  /* 6 */\n             { OP_String8,      0,  3,  0},  /* 7 */\n             { OP_Concat,       3,  2,  2},\n             { OP_ResultRow,    2,  1,  0},\n          };\n          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);\n          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);\n          sqlite3VdbeJumpHere(v, addr);\n          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);\n          sqlite3VdbeChangeP1(v, addr+1, j+2);\n          sqlite3VdbeChangeP2(v, addr+1, addr+4);\n          sqlite3VdbeChangeP1(v, addr+3, j+2);\n          sqlite3VdbeChangeP2(v, addr+3, addr+2);\n          sqlite3VdbeJumpHere(v, addr+4);\n          sqlite3VdbeChangeP4(v, addr+6, \n                     \"wrong # of entries in index \", P4_STATIC);\n          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);\n        }\n      } \n    }\n    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);\n    sqlite3VdbeChangeP2(v, addr, -mxErr);\n    sqlite3VdbeJumpHere(v, addr+1);\n    sqlite3VdbeChangeP4(v, addr+2, \"ok\", P4_STATIC);\n  }else\n#endif /* SQLITE_OMIT_INTEGRITY_CHECK */\n\n#ifndef SQLITE_OMIT_UTF16\n  /*\n  **   PRAGMA encoding\n  **   PRAGMA encoding = \"utf-8\"|\"utf-16\"|\"utf-16le\"|\"utf-16be\"\n  **\n  ** In its first form, this pragma returns the encoding of the main\n  ** database. If the database is not initialized, it is initialized now.\n  **\n  ** The second form of this pragma is a no-op if the main database file\n  ** has not already been initialized. In this case it sets the default\n  ** encoding that will be used for the main database file if a new file\n  ** is created. If an existing main database file is opened, then the\n  ** default text encoding for the existing database is used.\n  ** \n  ** In all cases new databases created using the ATTACH command are\n  ** created to use the same default text encoding as the main database. If\n  ** the main database has not been initialized and/or created when ATTACH\n  ** is executed, this is done before the ATTACH operation.\n  **\n  ** In the second form this pragma sets the text encoding to be used in\n  ** new database files created using this database handle. It is only\n  ** useful if invoked immediately after the main database i\n  */\n  if( sqlite3StrICmp(zLeft, \"encoding\")==0 ){\n    static const struct EncName {\n      char *zName;\n      u8 enc;\n    } encnames[] = {\n      { \"UTF8\",     SQLITE_UTF8        },\n      { \"UTF-8\",    SQLITE_UTF8        },  /* Must be element [1] */\n      { \"UTF-16le\", SQLITE_UTF16LE     },  /* Must be element [2] */\n      { \"UTF-16be\", SQLITE_UTF16BE     },  /* Must be element [3] */\n      { \"UTF16le\",  SQLITE_UTF16LE     },\n      { \"UTF16be\",  SQLITE_UTF16BE     },\n      { \"UTF-16\",   0                  }, /* SQLITE_UTF16NATIVE */\n      { \"UTF16\",    0                  }, /* SQLITE_UTF16NATIVE */\n      { 0, 0 }\n    };\n    const struct EncName *pEnc;\n    if( !zRight ){    /* \"PRAGMA encoding\" */\n      if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n      sqlite3VdbeSetNumCols(v, 1);\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"encoding\", SQLITE_STATIC);\n      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);\n      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );\n      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );\n      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );\n      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n    }else{                        /* \"PRAGMA encoding = XXX\" */\n      /* Only change the value of sqlite.enc if the database handle is not\n      ** initialized. If the main database exists, the new sqlite.enc value\n      ** will be overwritten when the schema is next loaded. If it does not\n      ** already exists, it will be created to use the new encoding value.\n      */\n      if( \n        !(DbHasProperty(db, 0, DB_SchemaLoaded)) || \n        DbHasProperty(db, 0, DB_Empty) \n      ){\n        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){\n          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){\n            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;\n            break;\n          }\n        }\n        if( !pEnc->zName ){\n          sqlite3ErrorMsg(pParse, \"unsupported encoding: %s\", zRight);\n        }\n      }\n    }\n  }else\n#endif /* SQLITE_OMIT_UTF16 */\n\n#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS\n  /*\n  **   PRAGMA [database.]schema_version\n  **   PRAGMA [database.]schema_version = <integer>\n  **\n  **   PRAGMA [database.]user_version\n  **   PRAGMA [database.]user_version = <integer>\n  **\n  ** The pragma's schema_version and user_version are used to set or get\n  ** the value of the schema-version and user-version, respectively. Both\n  ** the schema-version and the user-version are 32-bit signed integers\n  ** stored in the database header.\n  **\n  ** The schema-cookie is usually only manipulated internally by SQLite. It\n  ** is incremented by SQLite whenever the database schema is modified (by\n  ** creating or dropping a table or index). The schema version is used by\n  ** SQLite each time a query is executed to ensure that the internal cache\n  ** of the schema used when compiling the SQL query matches the schema of\n  ** the database against which the compiled query is actually executed.\n  ** Subverting this mechanism by using \"PRAGMA schema_version\" to modify\n  ** the schema-version is potentially dangerous and may lead to program\n  ** crashes or database corruption. Use with caution!\n  **\n  ** The user-version is not used internally by SQLite. It may be used by\n  ** applications for any purpose.\n  */\n  if( sqlite3StrICmp(zLeft, \"schema_version\")==0 \n   || sqlite3StrICmp(zLeft, \"user_version\")==0 \n   || sqlite3StrICmp(zLeft, \"freelist_count\")==0 \n  ){\n    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */\n    sqlite3VdbeUsesBtree(v, iDb);\n    switch( zLeft[0] ){\n      case 'f': case 'F':\n        iCookie = BTREE_FREE_PAGE_COUNT;\n        break;\n      case 's': case 'S':\n        iCookie = BTREE_SCHEMA_VERSION;\n        break;\n      default:\n        iCookie = BTREE_USER_VERSION;\n        break;\n    }\n\n    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){\n      /* Write the specified cookie value */\n      static const VdbeOpList setCookie[] = {\n        { OP_Transaction,    0,  1,  0},    /* 0 */\n        { OP_Integer,        0,  1,  0},    /* 1 */\n        { OP_SetCookie,      0,  0,  1},    /* 2 */\n      };\n      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);\n      sqlite3VdbeChangeP1(v, addr, iDb);\n      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));\n      sqlite3VdbeChangeP1(v, addr+2, iDb);\n      sqlite3VdbeChangeP2(v, addr+2, iCookie);\n    }else{\n      /* Read the specified cookie value */\n      static const VdbeOpList readCookie[] = {\n        { OP_Transaction,     0,  0,  0},    /* 0 */\n        { OP_ReadCookie,      0,  1,  0},    /* 1 */\n        { OP_ResultRow,       1,  1,  0}\n      };\n      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);\n      sqlite3VdbeChangeP1(v, addr, iDb);\n      sqlite3VdbeChangeP1(v, addr+1, iDb);\n      sqlite3VdbeChangeP3(v, addr+1, iCookie);\n      sqlite3VdbeSetNumCols(v, 1);\n      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);\n    }\n  }else\n#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */\n\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\n  /*\n  **   PRAGMA compile_options\n  **\n  ** Return the names of all compile-time options used in this build,\n  ** one option per row.\n  */\n  if( sqlite3StrICmp(zLeft, \"compile_options\")==0 ){\n    int i = 0;\n    const char *zOpt;\n    sqlite3VdbeSetNumCols(v, 1);\n    pParse->nMem = 1;\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"compile_option\", SQLITE_STATIC);\n    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);\n    }\n  }else\n#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */\n\n#ifndef SQLITE_OMIT_WAL\n  /*\n  **   PRAGMA [database.]wal_checkpoint = passive|full|restart\n  **\n  ** Checkpoint the database.\n  */\n  if( sqlite3StrICmp(zLeft, \"wal_checkpoint\")==0 ){\n    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);\n    int eMode = SQLITE_CHECKPOINT_PASSIVE;\n    if( zRight ){\n      if( sqlite3StrICmp(zRight, \"full\")==0 ){\n        eMode = SQLITE_CHECKPOINT_FULL;\n      }else if( sqlite3StrICmp(zRight, \"restart\")==0 ){\n        eMode = SQLITE_CHECKPOINT_RESTART;\n      }\n    }\n    if( sqlite3ReadSchema(pParse) ) goto pragma_out;\n    sqlite3VdbeSetNumCols(v, 3);\n    pParse->nMem = 3;\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"busy\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"log\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, \"checkpointed\", SQLITE_STATIC);\n\n    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);\n    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);\n  }else\n\n  /*\n  **   PRAGMA wal_autocheckpoint\n  **   PRAGMA wal_autocheckpoint = N\n  **\n  ** Configure a database connection to automatically checkpoint a database\n  ** after accumulating N frames in the log. Or query for the current value\n  ** of N.\n  */\n  if( sqlite3StrICmp(zLeft, \"wal_autocheckpoint\")==0 ){\n    if( zRight ){\n      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));\n    }\n    returnSingleInt(pParse, \"wal_autocheckpoint\", \n       db->xWalCallback==sqlite3WalDefaultHook ? \n           SQLITE_PTR_TO_INT(db->pWalArg) : 0);\n  }else\n#endif\n\n  /*\n  **  PRAGMA shrink_memory\n  **\n  ** This pragma attempts to free as much memory as possible from the\n  ** current database connection.\n  */\n  if( sqlite3StrICmp(zLeft, \"shrink_memory\")==0 ){\n    sqlite3_db_release_memory(db);\n  }else\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)\n  /*\n  ** Report the current state of file logs for all databases\n  */\n  if( sqlite3StrICmp(zLeft, \"lock_status\")==0 ){\n    static const char *const azLockName[] = {\n      \"unlocked\", \"shared\", \"reserved\", \"pending\", \"exclusive\"\n    };\n    int i;\n    sqlite3VdbeSetNumCols(v, 2);\n    pParse->nMem = 2;\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"database\", SQLITE_STATIC);\n    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, \"status\", SQLITE_STATIC);\n    for(i=0; i<db->nDb; i++){\n      Btree *pBt;\n      Pager *pPager;\n      const char *zState = \"unknown\";\n      int j;\n      if( db->aDb[i].zName==0 ) continue;\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);\n      pBt = db->aDb[i].pBt;\n      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){\n        zState = \"closed\";\n      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, \n                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){\n         zState = azLockName[j];\n      }\n      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);\n      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);\n    }\n\n  }else\n#endif\n\n#ifdef SQLITE_HAS_CODEC\n  if( sqlite3StrICmp(zLeft, \"key\")==0 && zRight ){\n    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));\n  }else\n  if( sqlite3StrICmp(zLeft, \"rekey\")==0 && zRight ){\n    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));\n  }else\n  if( zRight && (sqlite3StrICmp(zLeft, \"hexkey\")==0 ||\n                 sqlite3StrICmp(zLeft, \"hexrekey\")==0) ){\n    int i, h1, h2;\n    char zKey[40];\n    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){\n      h1 += 9*(1&(h1>>6));\n      h2 += 9*(1&(h2>>6));\n      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);\n    }\n    if( (zLeft[3] & 0xf)==0xb ){\n      sqlite3_key(db, zKey, i/2);\n    }else{\n      sqlite3_rekey(db, zKey, i/2);\n    }\n  }else\n#endif\n#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)\n  if( sqlite3StrICmp(zLeft, \"activate_extensions\")==0 ){\n#ifdef SQLITE_HAS_CODEC\n    if( sqlite3StrNICmp(zRight, \"see-\", 4)==0 ){\n      sqlite3_activate_see(&zRight[4]);\n    }\n#endif\n#ifdef SQLITE_ENABLE_CEROD\n    if( sqlite3StrNICmp(zRight, \"cerod-\", 6)==0 ){\n      sqlite3_activate_cerod(&zRight[6]);\n    }\n#endif\n  }else\n#endif\n\n \n  {/* Empty ELSE clause */}\n\n  /*\n  ** Reset the safety level, in case the fullfsync flag or synchronous\n  ** setting changed.\n  */\n#ifndef SQLITE_OMIT_PAGER_PRAGMAS\n  if( db->autoCommit ){\n    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,\n               (db->flags&SQLITE_FullFSync)!=0,\n               (db->flags&SQLITE_CkptFullFSync)!=0);\n  }\n#endif\npragma_out:\n  sqlite3DbFree(db, zLeft);\n  sqlite3DbFree(db, zRight);\n}\n\n#endif /* SQLITE_OMIT_PRAGMA */\n\n/************** End of pragma.c **********************************************/\n/************** Begin file prepare.c *****************************************/\n/*\n** 2005 May 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation of the sqlite3_prepare()\n** interface, and routines that contribute to loading the database schema\n** from disk.\n*/\n\n/*\n** Fill the InitData structure with an error message that indicates\n** that the database is corrupt.\n*/\nstatic void corruptSchema(\n  InitData *pData,     /* Initialization context */\n  const char *zObj,    /* Object being parsed at the point of error */\n  const char *zExtra   /* Error information */\n){\n  sqlite3 *db = pData->db;\n  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){\n    if( zObj==0 ) zObj = \"?\";\n    sqlite3SetString(pData->pzErrMsg, db,\n      \"malformed database schema (%s)\", zObj);\n    if( zExtra ){\n      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, \n                                 \"%s - %s\", *pData->pzErrMsg, zExtra);\n    }\n  }\n  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;\n}\n\n/*\n** This is the callback routine for the code that initializes the\n** database.  See sqlite3Init() below for additional information.\n** This routine is also called from the OP_ParseSchema opcode of the VDBE.\n**\n** Each callback contains the following information:\n**\n**     argv[0] = name of thing being created\n**     argv[1] = root page number for table or index. 0 for trigger or view.\n**     argv[2] = SQL text for the CREATE statement.\n**\n*/\nSQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){\n  InitData *pData = (InitData*)pInit;\n  sqlite3 *db = pData->db;\n  int iDb = pData->iDb;\n\n  assert( argc==3 );\n  UNUSED_PARAMETER2(NotUsed, argc);\n  assert( sqlite3_mutex_held(db->mutex) );\n  DbClearProperty(db, iDb, DB_Empty);\n  if( db->mallocFailed ){\n    corruptSchema(pData, argv[0], 0);\n    return 1;\n  }\n\n  assert( iDb>=0 && iDb<db->nDb );\n  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */\n  if( argv[1]==0 ){\n    corruptSchema(pData, argv[0], 0);\n  }else if( argv[2] && argv[2][0] ){\n    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.\n    ** But because db->init.busy is set to 1, no VDBE code is generated\n    ** or executed.  All the parser does is build the internal data\n    ** structures that describe the table, index, or view.\n    */\n    int rc;\n    sqlite3_stmt *pStmt;\n    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */\n\n    assert( db->init.busy );\n    db->init.iDb = iDb;\n    db->init.newTnum = sqlite3Atoi(argv[1]);\n    db->init.orphanTrigger = 0;\n    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);\n    rc = db->errCode;\n    assert( (rc&0xFF)==(rcp&0xFF) );\n    db->init.iDb = 0;\n    if( SQLITE_OK!=rc ){\n      if( db->init.orphanTrigger ){\n        assert( iDb==1 );\n      }else{\n        pData->rc = rc;\n        if( rc==SQLITE_NOMEM ){\n          db->mallocFailed = 1;\n        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){\n          corruptSchema(pData, argv[0], sqlite3_errmsg(db));\n        }\n      }\n    }\n    sqlite3_finalize(pStmt);\n  }else if( argv[0]==0 ){\n    corruptSchema(pData, 0, 0);\n  }else{\n    /* If the SQL column is blank it means this is an index that\n    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE\n    ** constraint for a CREATE TABLE.  The index should have already\n    ** been created when we processed the CREATE TABLE.  All we have\n    ** to do here is record the root page number for that index.\n    */\n    Index *pIndex;\n    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);\n    if( pIndex==0 ){\n      /* This can occur if there exists an index on a TEMP table which\n      ** has the same name as another index on a permanent index.  Since\n      ** the permanent table is hidden by the TEMP table, we can also\n      ** safely ignore the index on the permanent table.\n      */\n      /* Do Nothing */;\n    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){\n      corruptSchema(pData, argv[0], \"invalid rootpage\");\n    }\n  }\n  return 0;\n}\n\n/*\n** Attempt to read the database schema and initialize internal\n** data structures for a single database file.  The index of the\n** database file is given by iDb.  iDb==0 is used for the main\n** database.  iDb==1 should never be used.  iDb>=2 is used for\n** auxiliary databases.  Return one of the SQLITE_ error codes to\n** indicate success or failure.\n*/\nstatic int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){\n  int rc;\n  int i;\n  int size;\n  Table *pTab;\n  Db *pDb;\n  char const *azArg[4];\n  int meta[5];\n  InitData initData;\n  char const *zMasterSchema;\n  char const *zMasterName;\n  int openedTransaction = 0;\n\n  /*\n  ** The master database table has a structure like this\n  */\n  static const char master_schema[] = \n     \"CREATE TABLE sqlite_master(\\n\"\n     \"  type text,\\n\"\n     \"  name text,\\n\"\n     \"  tbl_name text,\\n\"\n     \"  rootpage integer,\\n\"\n     \"  sql text\\n\"\n     \")\"\n  ;\n#ifndef SQLITE_OMIT_TEMPDB\n  static const char temp_master_schema[] = \n     \"CREATE TEMP TABLE sqlite_temp_master(\\n\"\n     \"  type text,\\n\"\n     \"  name text,\\n\"\n     \"  tbl_name text,\\n\"\n     \"  rootpage integer,\\n\"\n     \"  sql text\\n\"\n     \")\"\n  ;\n#else\n  #define temp_master_schema 0\n#endif\n\n  assert( iDb>=0 && iDb<db->nDb );\n  assert( db->aDb[iDb].pSchema );\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );\n\n  /* zMasterSchema and zInitScript are set to point at the master schema\n  ** and initialisation script appropriate for the database being\n  ** initialised. zMasterName is the name of the master table.\n  */\n  if( !OMIT_TEMPDB && iDb==1 ){\n    zMasterSchema = temp_master_schema;\n  }else{\n    zMasterSchema = master_schema;\n  }\n  zMasterName = SCHEMA_TABLE(iDb);\n\n  /* Construct the schema tables.  */\n  azArg[0] = zMasterName;\n  azArg[1] = \"1\";\n  azArg[2] = zMasterSchema;\n  azArg[3] = 0;\n  initData.db = db;\n  initData.iDb = iDb;\n  initData.rc = SQLITE_OK;\n  initData.pzErrMsg = pzErrMsg;\n  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);\n  if( initData.rc ){\n    rc = initData.rc;\n    goto error_out;\n  }\n  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);\n  if( ALWAYS(pTab) ){\n    pTab->tabFlags |= TF_Readonly;\n  }\n\n  /* Create a cursor to hold the database open\n  */\n  pDb = &db->aDb[iDb];\n  if( pDb->pBt==0 ){\n    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){\n      DbSetProperty(db, 1, DB_SchemaLoaded);\n    }\n    return SQLITE_OK;\n  }\n\n  /* If there is not already a read-only (or read-write) transaction opened\n  ** on the b-tree database, open one now. If a transaction is opened, it \n  ** will be closed before this function returns.  */\n  sqlite3BtreeEnter(pDb->pBt);\n  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){\n    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);\n    if( rc!=SQLITE_OK ){\n      sqlite3SetString(pzErrMsg, db, \"%s\", sqlite3ErrStr(rc));\n      goto initone_error_out;\n    }\n    openedTransaction = 1;\n  }\n\n  /* Get the database meta information.\n  **\n  ** Meta values are as follows:\n  **    meta[0]   Schema cookie.  Changes with each schema change.\n  **    meta[1]   File format of schema layer.\n  **    meta[2]   Size of the page cache.\n  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)\n  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE\n  **    meta[5]   User version\n  **    meta[6]   Incremental vacuum mode\n  **    meta[7]   unused\n  **    meta[8]   unused\n  **    meta[9]   unused\n  **\n  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to\n  ** the possible values of meta[4].\n  */\n  for(i=0; i<ArraySize(meta); i++){\n    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);\n  }\n  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];\n\n  /* If opening a non-empty database, check the text encoding. For the\n  ** main database, set sqlite3.enc to the encoding of the main database.\n  ** For an attached db, it is an error if the encoding is not the same\n  ** as sqlite3.enc.\n  */\n  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */\n    if( iDb==0 ){\n      u8 encoding;\n      /* If opening the main database, set ENC(db). */\n      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;\n      if( encoding==0 ) encoding = SQLITE_UTF8;\n      ENC(db) = encoding;\n    }else{\n      /* If opening an attached database, the encoding much match ENC(db) */\n      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){\n        sqlite3SetString(pzErrMsg, db, \"attached databases must use the same\"\n            \" text encoding as main database\");\n        rc = SQLITE_ERROR;\n        goto initone_error_out;\n      }\n    }\n  }else{\n    DbSetProperty(db, iDb, DB_Empty);\n  }\n  pDb->pSchema->enc = ENC(db);\n\n  if( pDb->pSchema->cache_size==0 ){\n#ifndef SQLITE_OMIT_DEPRECATED\n    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);\n    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }\n    pDb->pSchema->cache_size = size;\n#else\n    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;\n#endif\n    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);\n  }\n\n  /*\n  ** file_format==1    Version 3.0.0.\n  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN\n  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults\n  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants\n  */\n  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];\n  if( pDb->pSchema->file_format==0 ){\n    pDb->pSchema->file_format = 1;\n  }\n  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){\n    sqlite3SetString(pzErrMsg, db, \"unsupported file format\");\n    rc = SQLITE_ERROR;\n    goto initone_error_out;\n  }\n\n  /* Ticket #2804:  When we open a database in the newer file format,\n  ** clear the legacy_file_format pragma flag so that a VACUUM will\n  ** not downgrade the database and thus invalidate any descending\n  ** indices that the user might have created.\n  */\n  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){\n    db->flags &= ~SQLITE_LegacyFileFmt;\n  }\n\n  /* Read the schema information out of the schema tables\n  */\n  assert( db->init.busy );\n  {\n    char *zSql;\n    zSql = sqlite3MPrintf(db, \n        \"SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid\",\n        db->aDb[iDb].zName, zMasterName);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    {\n      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);\n      xAuth = db->xAuth;\n      db->xAuth = 0;\n#endif\n      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);\n#ifndef SQLITE_OMIT_AUTHORIZATION\n      db->xAuth = xAuth;\n    }\n#endif\n    if( rc==SQLITE_OK ) rc = initData.rc;\n    sqlite3DbFree(db, zSql);\n#ifndef SQLITE_OMIT_ANALYZE\n    if( rc==SQLITE_OK ){\n      sqlite3AnalysisLoad(db, iDb);\n    }\n#endif\n  }\n  if( db->mallocFailed ){\n    rc = SQLITE_NOMEM;\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){\n    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider\n    ** the schema loaded, even if errors occurred. In this situation the \n    ** current sqlite3_prepare() operation will fail, but the following one\n    ** will attempt to compile the supplied statement against whatever subset\n    ** of the schema was loaded before the error occurred. The primary\n    ** purpose of this is to allow access to the sqlite_master table\n    ** even when its contents have been corrupted.\n    */\n    DbSetProperty(db, iDb, DB_SchemaLoaded);\n    rc = SQLITE_OK;\n  }\n\n  /* Jump here for an error that occurs after successfully allocating\n  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs\n  ** before that point, jump to error_out.\n  */\ninitone_error_out:\n  if( openedTransaction ){\n    sqlite3BtreeCommit(pDb->pBt);\n  }\n  sqlite3BtreeLeave(pDb->pBt);\n\nerror_out:\n  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n    db->mallocFailed = 1;\n  }\n  return rc;\n}\n\n/*\n** Initialize all database files - the main database file, the file\n** used to store temporary tables, and any additional database files\n** created using ATTACH statements.  Return a success code.  If an\n** error occurs, write an error message into *pzErrMsg.\n**\n** After a database is initialized, the DB_SchemaLoaded bit is set\n** bit is set in the flags field of the Db structure. If the database\n** file was of zero-length, then the DB_Empty flag is also set.\n*/\nSQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){\n  int i, rc;\n  int commit_internal = !(db->flags&SQLITE_InternChanges);\n  \n  assert( sqlite3_mutex_held(db->mutex) );\n  rc = SQLITE_OK;\n  db->init.busy = 1;\n  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){\n    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;\n    rc = sqlite3InitOne(db, i, pzErrMsg);\n    if( rc ){\n      sqlite3ResetOneSchema(db, i);\n    }\n  }\n\n  /* Once all the other databases have been initialised, load the schema\n  ** for the TEMP database. This is loaded last, as the TEMP database\n  ** schema may contain references to objects in other databases.\n  */\n#ifndef SQLITE_OMIT_TEMPDB\n  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)\n                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){\n    rc = sqlite3InitOne(db, 1, pzErrMsg);\n    if( rc ){\n      sqlite3ResetOneSchema(db, 1);\n    }\n  }\n#endif\n\n  db->init.busy = 0;\n  if( rc==SQLITE_OK && commit_internal ){\n    sqlite3CommitInternalChanges(db);\n  }\n\n  return rc; \n}\n\n/*\n** This routine is a no-op if the database schema is already initialised.\n** Otherwise, the schema is loaded. An error code is returned.\n*/\nSQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){\n  int rc = SQLITE_OK;\n  sqlite3 *db = pParse->db;\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( !db->init.busy ){\n    rc = sqlite3Init(db, &pParse->zErrMsg);\n  }\n  if( rc!=SQLITE_OK ){\n    pParse->rc = rc;\n    pParse->nErr++;\n  }\n  return rc;\n}\n\n\n/*\n** Check schema cookies in all databases.  If any cookie is out\n** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies\n** make no changes to pParse->rc.\n*/\nstatic void schemaIsValid(Parse *pParse){\n  sqlite3 *db = pParse->db;\n  int iDb;\n  int rc;\n  int cookie;\n\n  assert( pParse->checkSchema );\n  assert( sqlite3_mutex_held(db->mutex) );\n  for(iDb=0; iDb<db->nDb; iDb++){\n    int openedTransaction = 0;         /* True if a transaction is opened */\n    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */\n    if( pBt==0 ) continue;\n\n    /* If there is not already a read-only (or read-write) transaction opened\n    ** on the b-tree database, open one now. If a transaction is opened, it \n    ** will be closed immediately after reading the meta-value. */\n    if( !sqlite3BtreeIsInReadTrans(pBt) ){\n      rc = sqlite3BtreeBeginTrans(pBt, 0);\n      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){\n        db->mallocFailed = 1;\n      }\n      if( rc!=SQLITE_OK ) return;\n      openedTransaction = 1;\n    }\n\n    /* Read the schema cookie from the database. If it does not match the \n    ** value stored as part of the in-memory schema representation,\n    ** set Parse.rc to SQLITE_SCHEMA. */\n    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){\n      sqlite3ResetOneSchema(db, iDb);\n      pParse->rc = SQLITE_SCHEMA;\n    }\n\n    /* Close the transaction, if one was opened. */\n    if( openedTransaction ){\n      sqlite3BtreeCommit(pBt);\n    }\n  }\n}\n\n/*\n** Convert a schema pointer into the iDb index that indicates\n** which database file in db->aDb[] the schema refers to.\n**\n** If the same database is attached more than once, the first\n** attached database is returned.\n*/\nSQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){\n  int i = -1000000;\n\n  /* If pSchema is NULL, then return -1000000. This happens when code in \n  ** expr.c is trying to resolve a reference to a transient table (i.e. one\n  ** created by a sub-select). In this case the return value of this \n  ** function should never be used.\n  **\n  ** We return -1000000 instead of the more usual -1 simply because using\n  ** -1000000 as the incorrect index into db->aDb[] is much \n  ** more likely to cause a segfault than -1 (of course there are assert()\n  ** statements too, but it never hurts to play the odds).\n  */\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( pSchema ){\n    for(i=0; ALWAYS(i<db->nDb); i++){\n      if( db->aDb[i].pSchema==pSchema ){\n        break;\n      }\n    }\n    assert( i>=0 && i<db->nDb );\n  }\n  return i;\n}\n\n/*\n** Compile the UTF-8 encoded SQL statement zSql into a statement handle.\n*/\nstatic int sqlite3Prepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */\n  Vdbe *pReprepare,         /* VM being reprepared */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  Parse *pParse;            /* Parsing context */\n  char *zErrMsg = 0;        /* Error message */\n  int rc = SQLITE_OK;       /* Result code */\n  int i;                    /* Loop counter */\n\n  /* Allocate the parsing context */\n  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));\n  if( pParse==0 ){\n    rc = SQLITE_NOMEM;\n    goto end_prepare;\n  }\n  pParse->pReprepare = pReprepare;\n  assert( ppStmt && *ppStmt==0 );\n  assert( !db->mallocFailed );\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  /* Check to verify that it is possible to get a read lock on all\n  ** database schemas.  The inability to get a read lock indicates that\n  ** some other database connection is holding a write-lock, which in\n  ** turn means that the other connection has made uncommitted changes\n  ** to the schema.\n  **\n  ** Were we to proceed and prepare the statement against the uncommitted\n  ** schema changes and if those schema changes are subsequently rolled\n  ** back and different changes are made in their place, then when this\n  ** prepared statement goes to run the schema cookie would fail to detect\n  ** the schema change.  Disaster would follow.\n  **\n  ** This thread is currently holding mutexes on all Btrees (because\n  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it\n  ** is not possible for another thread to start a new schema change\n  ** while this routine is running.  Hence, we do not need to hold \n  ** locks on the schema, we just need to make sure nobody else is \n  ** holding them.\n  **\n  ** Note that setting READ_UNCOMMITTED overrides most lock detection,\n  ** but it does *not* override schema lock detection, so this all still\n  ** works even if READ_UNCOMMITTED is set.\n  */\n  for(i=0; i<db->nDb; i++) {\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      assert( sqlite3BtreeHoldsMutex(pBt) );\n      rc = sqlite3BtreeSchemaLocked(pBt);\n      if( rc ){\n        const char *zDb = db->aDb[i].zName;\n        sqlite3Error(db, rc, \"database schema is locked: %s\", zDb);\n        testcase( db->flags & SQLITE_ReadUncommitted );\n        goto end_prepare;\n      }\n    }\n  }\n\n  sqlite3VtabUnlockList(db);\n\n  pParse->db = db;\n  pParse->nQueryLoop = (double)1;\n  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){\n    char *zSqlCopy;\n    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];\n    testcase( nBytes==mxLen );\n    testcase( nBytes==mxLen+1 );\n    if( nBytes>mxLen ){\n      sqlite3Error(db, SQLITE_TOOBIG, \"statement too long\");\n      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);\n      goto end_prepare;\n    }\n    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);\n    if( zSqlCopy ){\n      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);\n      sqlite3DbFree(db, zSqlCopy);\n      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];\n    }else{\n      pParse->zTail = &zSql[nBytes];\n    }\n  }else{\n    sqlite3RunParser(pParse, zSql, &zErrMsg);\n  }\n  assert( 1==(int)pParse->nQueryLoop );\n\n  if( db->mallocFailed ){\n    pParse->rc = SQLITE_NOMEM;\n  }\n  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;\n  if( pParse->checkSchema ){\n    schemaIsValid(pParse);\n  }\n  if( db->mallocFailed ){\n    pParse->rc = SQLITE_NOMEM;\n  }\n  if( pzTail ){\n    *pzTail = pParse->zTail;\n  }\n  rc = pParse->rc;\n\n#ifndef SQLITE_OMIT_EXPLAIN\n  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){\n    static const char * const azColName[] = {\n       \"addr\", \"opcode\", \"p1\", \"p2\", \"p3\", \"p4\", \"p5\", \"comment\",\n       \"selectid\", \"order\", \"from\", \"detail\"\n    };\n    int iFirst, mx;\n    if( pParse->explain==2 ){\n      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);\n      iFirst = 8;\n      mx = 12;\n    }else{\n      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);\n      iFirst = 0;\n      mx = 8;\n    }\n    for(i=iFirst; i<mx; i++){\n      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,\n                            azColName[i], SQLITE_STATIC);\n    }\n  }\n#endif\n\n  assert( db->init.busy==0 || saveSqlFlag==0 );\n  if( db->init.busy==0 ){\n    Vdbe *pVdbe = pParse->pVdbe;\n    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);\n  }\n  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){\n    sqlite3VdbeFinalize(pParse->pVdbe);\n    assert(!(*ppStmt));\n  }else{\n    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;\n  }\n\n  if( zErrMsg ){\n    sqlite3Error(db, rc, \"%s\", zErrMsg);\n    sqlite3DbFree(db, zErrMsg);\n  }else{\n    sqlite3Error(db, rc, 0);\n  }\n\n  /* Delete any TriggerPrg structures allocated while parsing this statement. */\n  while( pParse->pTriggerPrg ){\n    TriggerPrg *pT = pParse->pTriggerPrg;\n    pParse->pTriggerPrg = pT->pNext;\n    sqlite3DbFree(db, pT);\n  }\n\nend_prepare:\n\n  sqlite3StackFree(db, pParse);\n  rc = sqlite3ApiExit(db, rc);\n  assert( (rc&db->errMask)==rc );\n  return rc;\n}\nstatic int sqlite3LockAndPrepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */\n  Vdbe *pOld,               /* VM being reprepared */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  assert( ppStmt!=0 );\n  *ppStmt = 0;\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);\n  if( rc==SQLITE_SCHEMA ){\n    sqlite3_finalize(*ppStmt);\n    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);\n  }\n  sqlite3BtreeLeaveAll(db);\n  sqlite3_mutex_leave(db->mutex);\n  assert( rc==SQLITE_OK || *ppStmt==0 );\n  return rc;\n}\n\n/*\n** Rerun the compilation of a statement after a schema change.\n**\n** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,\n** if the statement cannot be recompiled because another connection has\n** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error\n** occurs, return SQLITE_SCHEMA.\n*/\nSQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){\n  int rc;\n  sqlite3_stmt *pNew;\n  const char *zSql;\n  sqlite3 *db;\n\n  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );\n  zSql = sqlite3_sql((sqlite3_stmt *)p);\n  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */\n  db = sqlite3VdbeDb(p);\n  assert( sqlite3_mutex_held(db->mutex) );\n  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);\n  if( rc ){\n    if( rc==SQLITE_NOMEM ){\n      db->mallocFailed = 1;\n    }\n    assert( pNew==0 );\n    return rc;\n  }else{\n    assert( pNew!=0 );\n  }\n  sqlite3VdbeSwap((Vdbe*)pNew, p);\n  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);\n  sqlite3VdbeResetStepResult((Vdbe*)pNew);\n  sqlite3VdbeFinalize((Vdbe*)pNew);\n  return SQLITE_OK;\n}\n\n\n/*\n** Two versions of the official API.  Legacy and new use.  In the legacy\n** version, the original SQL text is not saved in the prepared statement\n** and so if a schema change occurs, SQLITE_SCHEMA is returned by\n** sqlite3_step().  In the new version, the original SQL text is retained\n** and the statement is automatically recompiled if an schema change\n** occurs.\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,              /* Database handle. */\n  const char *zSql,         /* UTF-8 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const char **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\n\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Compile the UTF-16 encoded SQL statement zSql into a statement handle.\n*/\nstatic int sqlite3Prepare16(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  /* This function currently works by first transforming the UTF-16\n  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The\n  ** tricky bit is figuring out the pointer to return in *pzTail.\n  */\n  char *zSql8;\n  const char *zTail8 = 0;\n  int rc = SQLITE_OK;\n\n  assert( ppStmt );\n  *ppStmt = 0;\n  if( !sqlite3SafetyCheckOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);\n  if( zSql8 ){\n    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);\n  }\n\n  if( zTail8 && pzTail ){\n    /* If sqlite3_prepare returns a tail pointer, we calculate the\n    ** equivalent pointer into the UTF-16 string by counting the unicode\n    ** characters between zSql8 and zTail8, and then returning a pointer\n    ** the same number of characters into the UTF-16 string.\n    */\n    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));\n    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);\n  }\n  sqlite3DbFree(db, zSql8); \n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Two versions of the official API.  Legacy and new use.  In the legacy\n** version, the original SQL text is not saved in the prepared statement\n** and so if a schema change occurs, SQLITE_SCHEMA is returned by\n** sqlite3_step().  In the new version, the original SQL text is retained\n** and the statement is automatically recompiled if an schema change\n** occurs.\n*/\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,              /* Database handle. */ \n  const void *zSql,         /* UTF-16 encoded SQL statement. */\n  int nBytes,               /* Length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */\n  const void **pzTail       /* OUT: End of parsed string */\n){\n  int rc;\n  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);\n  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */\n  return rc;\n}\n\n#endif /* SQLITE_OMIT_UTF16 */\n\n/************** End of prepare.c *********************************************/\n/************** Begin file select.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle SELECT statements in SQLite.\n*/\n\n\n/*\n** Delete all the content of a Select structure but do not deallocate\n** the select structure itself.\n*/\nstatic void clearSelect(sqlite3 *db, Select *p){\n  sqlite3ExprListDelete(db, p->pEList);\n  sqlite3SrcListDelete(db, p->pSrc);\n  sqlite3ExprDelete(db, p->pWhere);\n  sqlite3ExprListDelete(db, p->pGroupBy);\n  sqlite3ExprDelete(db, p->pHaving);\n  sqlite3ExprListDelete(db, p->pOrderBy);\n  sqlite3SelectDelete(db, p->pPrior);\n  sqlite3ExprDelete(db, p->pLimit);\n  sqlite3ExprDelete(db, p->pOffset);\n}\n\n/*\n** Initialize a SelectDest structure.\n*/\nSQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){\n  pDest->eDest = (u8)eDest;\n  pDest->iSDParm = iParm;\n  pDest->affSdst = 0;\n  pDest->iSdst = 0;\n  pDest->nSdst = 0;\n}\n\n\n/*\n** Allocate a new Select structure and return a pointer to that\n** structure.\n*/\nSQLITE_PRIVATE Select *sqlite3SelectNew(\n  Parse *pParse,        /* Parsing context */\n  ExprList *pEList,     /* which columns to include in the result */\n  SrcList *pSrc,        /* the FROM clause -- which tables to scan */\n  Expr *pWhere,         /* the WHERE clause */\n  ExprList *pGroupBy,   /* the GROUP BY clause */\n  Expr *pHaving,        /* the HAVING clause */\n  ExprList *pOrderBy,   /* the ORDER BY clause */\n  int isDistinct,       /* true if the DISTINCT keyword is present */\n  Expr *pLimit,         /* LIMIT value.  NULL means not used */\n  Expr *pOffset         /* OFFSET value.  NULL means no offset */\n){\n  Select *pNew;\n  Select standin;\n  sqlite3 *db = pParse->db;\n  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );\n  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */\n  if( pNew==0 ){\n    assert( db->mallocFailed );\n    pNew = &standin;\n    memset(pNew, 0, sizeof(*pNew));\n  }\n  if( pEList==0 ){\n    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));\n  }\n  pNew->pEList = pEList;\n  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));\n  pNew->pSrc = pSrc;\n  pNew->pWhere = pWhere;\n  pNew->pGroupBy = pGroupBy;\n  pNew->pHaving = pHaving;\n  pNew->pOrderBy = pOrderBy;\n  pNew->selFlags = isDistinct ? SF_Distinct : 0;\n  pNew->op = TK_SELECT;\n  pNew->pLimit = pLimit;\n  pNew->pOffset = pOffset;\n  assert( pOffset==0 || pLimit!=0 );\n  pNew->addrOpenEphm[0] = -1;\n  pNew->addrOpenEphm[1] = -1;\n  pNew->addrOpenEphm[2] = -1;\n  if( db->mallocFailed ) {\n    clearSelect(db, pNew);\n    if( pNew!=&standin ) sqlite3DbFree(db, pNew);\n    pNew = 0;\n  }else{\n    assert( pNew->pSrc!=0 || pParse->nErr>0 );\n  }\n  assert( pNew!=&standin );\n  return pNew;\n}\n\n/*\n** Delete the given Select structure and all of its substructures.\n*/\nSQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){\n  if( p ){\n    clearSelect(db, p);\n    sqlite3DbFree(db, p);\n  }\n}\n\n/*\n** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the\n** type of join.  Return an integer constant that expresses that type\n** in terms of the following bit values:\n**\n**     JT_INNER\n**     JT_CROSS\n**     JT_OUTER\n**     JT_NATURAL\n**     JT_LEFT\n**     JT_RIGHT\n**\n** A full outer join is the combination of JT_LEFT and JT_RIGHT.\n**\n** If an illegal or unsupported join type is seen, then still return\n** a join type, but put an error in the pParse structure.\n*/\nSQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){\n  int jointype = 0;\n  Token *apAll[3];\n  Token *p;\n                             /*   0123456789 123456789 123456789 123 */\n  static const char zKeyText[] = \"naturaleftouterightfullinnercross\";\n  static const struct {\n    u8 i;        /* Beginning of keyword text in zKeyText[] */\n    u8 nChar;    /* Length of the keyword in characters */\n    u8 code;     /* Join type mask */\n  } aKeyword[] = {\n    /* natural */ { 0,  7, JT_NATURAL                },\n    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },\n    /* outer   */ { 10, 5, JT_OUTER                  },\n    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },\n    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },\n    /* inner   */ { 23, 5, JT_INNER                  },\n    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },\n  };\n  int i, j;\n  apAll[0] = pA;\n  apAll[1] = pB;\n  apAll[2] = pC;\n  for(i=0; i<3 && apAll[i]; i++){\n    p = apAll[i];\n    for(j=0; j<ArraySize(aKeyword); j++){\n      if( p->n==aKeyword[j].nChar \n          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){\n        jointype |= aKeyword[j].code;\n        break;\n      }\n    }\n    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );\n    if( j>=ArraySize(aKeyword) ){\n      jointype |= JT_ERROR;\n      break;\n    }\n  }\n  if(\n     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||\n     (jointype & JT_ERROR)!=0\n  ){\n    const char *zSp = \" \";\n    assert( pB!=0 );\n    if( pC==0 ){ zSp++; }\n    sqlite3ErrorMsg(pParse, \"unknown or unsupported join type: \"\n       \"%T %T%s%T\", pA, pB, zSp, pC);\n    jointype = JT_INNER;\n  }else if( (jointype & JT_OUTER)!=0 \n         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){\n    sqlite3ErrorMsg(pParse, \n      \"RIGHT and FULL OUTER JOINs are not currently supported\");\n    jointype = JT_INNER;\n  }\n  return jointype;\n}\n\n/*\n** Return the index of a column in a table.  Return -1 if the column\n** is not contained in the table.\n*/\nstatic int columnIndex(Table *pTab, const char *zCol){\n  int i;\n  for(i=0; i<pTab->nCol; i++){\n    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;\n  }\n  return -1;\n}\n\n/*\n** Search the first N tables in pSrc, from left to right, looking for a\n** table that has a column named zCol.  \n**\n** When found, set *piTab and *piCol to the table index and column index\n** of the matching column and return TRUE.\n**\n** If not found, return FALSE.\n*/\nstatic int tableAndColumnIndex(\n  SrcList *pSrc,       /* Array of tables to search */\n  int N,               /* Number of tables in pSrc->a[] to search */\n  const char *zCol,    /* Name of the column we are looking for */\n  int *piTab,          /* Write index of pSrc->a[] here */\n  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */\n){\n  int i;               /* For looping over tables in pSrc */\n  int iCol;            /* Index of column matching zCol */\n\n  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */\n  for(i=0; i<N; i++){\n    iCol = columnIndex(pSrc->a[i].pTab, zCol);\n    if( iCol>=0 ){\n      if( piTab ){\n        *piTab = i;\n        *piCol = iCol;\n      }\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** This function is used to add terms implied by JOIN syntax to the\n** WHERE clause expression of a SELECT statement. The new term, which\n** is ANDed with the existing WHERE clause, is of the form:\n**\n**    (tab1.col1 = tab2.col2)\n**\n** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the \n** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is\n** column iColRight of tab2.\n*/\nstatic void addWhereTerm(\n  Parse *pParse,                  /* Parsing context */\n  SrcList *pSrc,                  /* List of tables in FROM clause */\n  int iLeft,                      /* Index of first table to join in pSrc */\n  int iColLeft,                   /* Index of column in first table */\n  int iRight,                     /* Index of second table in pSrc */\n  int iColRight,                  /* Index of column in second table */\n  int isOuterJoin,                /* True if this is an OUTER join */\n  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */\n){\n  sqlite3 *db = pParse->db;\n  Expr *pE1;\n  Expr *pE2;\n  Expr *pEq;\n\n  assert( iLeft<iRight );\n  assert( pSrc->nSrc>iRight );\n  assert( pSrc->a[iLeft].pTab );\n  assert( pSrc->a[iRight].pTab );\n\n  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);\n  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);\n\n  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);\n  if( pEq && isOuterJoin ){\n    ExprSetProperty(pEq, EP_FromJoin);\n    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );\n    ExprSetIrreducible(pEq);\n    pEq->iRightJoinTable = (i16)pE2->iTable;\n  }\n  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);\n}\n\n/*\n** Set the EP_FromJoin property on all terms of the given expression.\n** And set the Expr.iRightJoinTable to iTable for every term in the\n** expression.\n**\n** The EP_FromJoin property is used on terms of an expression to tell\n** the LEFT OUTER JOIN processing logic that this term is part of the\n** join restriction specified in the ON or USING clause and not a part\n** of the more general WHERE clause.  These terms are moved over to the\n** WHERE clause during join processing but we need to remember that they\n** originated in the ON or USING clause.\n**\n** The Expr.iRightJoinTable tells the WHERE clause processing that the\n** expression depends on table iRightJoinTable even if that table is not\n** explicitly mentioned in the expression.  That information is needed\n** for cases like this:\n**\n**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5\n**\n** The where clause needs to defer the handling of the t1.x=5\n** term until after the t2 loop of the join.  In that way, a\n** NULL t2 row will be inserted whenever t1.x!=5.  If we do not\n** defer the handling of t1.x=5, it will be processed immediately\n** after the t1 loop and rows with t1.x!=5 will never appear in\n** the output, which is incorrect.\n*/\nstatic void setJoinExpr(Expr *p, int iTable){\n  while( p ){\n    ExprSetProperty(p, EP_FromJoin);\n    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );\n    ExprSetIrreducible(p);\n    p->iRightJoinTable = (i16)iTable;\n    setJoinExpr(p->pLeft, iTable);\n    p = p->pRight;\n  } \n}\n\n/*\n** This routine processes the join information for a SELECT statement.\n** ON and USING clauses are converted into extra terms of the WHERE clause.\n** NATURAL joins also create extra WHERE clause terms.\n**\n** The terms of a FROM clause are contained in the Select.pSrc structure.\n** The left most table is the first entry in Select.pSrc.  The right-most\n** table is the last entry.  The join operator is held in the entry to\n** the left.  Thus entry 0 contains the join operator for the join between\n** entries 0 and 1.  Any ON or USING clauses associated with the join are\n** also attached to the left entry.\n**\n** This routine returns the number of errors encountered.\n*/\nstatic int sqliteProcessJoin(Parse *pParse, Select *p){\n  SrcList *pSrc;                  /* All tables in the FROM clause */\n  int i, j;                       /* Loop counters */\n  struct SrcList_item *pLeft;     /* Left table being joined */\n  struct SrcList_item *pRight;    /* Right table being joined */\n\n  pSrc = p->pSrc;\n  pLeft = &pSrc->a[0];\n  pRight = &pLeft[1];\n  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){\n    Table *pLeftTab = pLeft->pTab;\n    Table *pRightTab = pRight->pTab;\n    int isOuter;\n\n    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;\n    isOuter = (pRight->jointype & JT_OUTER)!=0;\n\n    /* When the NATURAL keyword is present, add WHERE clause terms for\n    ** every column that the two tables have in common.\n    */\n    if( pRight->jointype & JT_NATURAL ){\n      if( pRight->pOn || pRight->pUsing ){\n        sqlite3ErrorMsg(pParse, \"a NATURAL join may not have \"\n           \"an ON or USING clause\", 0);\n        return 1;\n      }\n      for(j=0; j<pRightTab->nCol; j++){\n        char *zName;   /* Name of column in the right table */\n        int iLeft;     /* Matching left table */\n        int iLeftCol;  /* Matching column in the left table */\n\n        zName = pRightTab->aCol[j].zName;\n        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){\n          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,\n                       isOuter, &p->pWhere);\n        }\n      }\n    }\n\n    /* Disallow both ON and USING clauses in the same join\n    */\n    if( pRight->pOn && pRight->pUsing ){\n      sqlite3ErrorMsg(pParse, \"cannot have both ON and USING \"\n        \"clauses in the same join\");\n      return 1;\n    }\n\n    /* Add the ON clause to the end of the WHERE clause, connected by\n    ** an AND operator.\n    */\n    if( pRight->pOn ){\n      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);\n      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);\n      pRight->pOn = 0;\n    }\n\n    /* Create extra terms on the WHERE clause for each column named\n    ** in the USING clause.  Example: If the two tables to be joined are \n    ** A and B and the USING clause names X, Y, and Z, then add this\n    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z\n    ** Report an error if any column mentioned in the USING clause is\n    ** not contained in both tables to be joined.\n    */\n    if( pRight->pUsing ){\n      IdList *pList = pRight->pUsing;\n      for(j=0; j<pList->nId; j++){\n        char *zName;     /* Name of the term in the USING clause */\n        int iLeft;       /* Table on the left with matching column name */\n        int iLeftCol;    /* Column number of matching column on the left */\n        int iRightCol;   /* Column number of matching column on the right */\n\n        zName = pList->a[j].zName;\n        iRightCol = columnIndex(pRightTab, zName);\n        if( iRightCol<0\n         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)\n        ){\n          sqlite3ErrorMsg(pParse, \"cannot join using column %s - column \"\n            \"not present in both tables\", zName);\n          return 1;\n        }\n        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,\n                     isOuter, &p->pWhere);\n      }\n    }\n  }\n  return 0;\n}\n\n/*\n** Insert code into \"v\" that will push the record on the top of the\n** stack into the sorter.\n*/\nstatic void pushOntoSorter(\n  Parse *pParse,         /* Parser context */\n  ExprList *pOrderBy,    /* The ORDER BY clause */\n  Select *pSelect,       /* The whole SELECT statement */\n  int regData            /* Register holding data to be sorted */\n){\n  Vdbe *v = pParse->pVdbe;\n  int nExpr = pOrderBy->nExpr;\n  int regBase = sqlite3GetTempRange(pParse, nExpr+2);\n  int regRecord = sqlite3GetTempReg(pParse);\n  int op;\n  sqlite3ExprCacheClear(pParse);\n  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);\n  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);\n  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);\n  if( pSelect->selFlags & SF_UseSorter ){\n    op = OP_SorterInsert;\n  }else{\n    op = OP_IdxInsert;\n  }\n  sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);\n  sqlite3ReleaseTempReg(pParse, regRecord);\n  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);\n  if( pSelect->iLimit ){\n    int addr1, addr2;\n    int iLimit;\n    if( pSelect->iOffset ){\n      iLimit = pSelect->iOffset+1;\n    }else{\n      iLimit = pSelect->iLimit;\n    }\n    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);\n    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);\n    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);\n    sqlite3VdbeJumpHere(v, addr1);\n    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);\n    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);\n    sqlite3VdbeJumpHere(v, addr2);\n  }\n}\n\n/*\n** Add code to implement the OFFSET\n*/\nstatic void codeOffset(\n  Vdbe *v,          /* Generate code into this VM */\n  Select *p,        /* The SELECT statement being coded */\n  int iContinue     /* Jump here to skip the current record */\n){\n  if( p->iOffset && iContinue!=0 ){\n    int addr;\n    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);\n    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);\n    VdbeComment((v, \"skip OFFSET records\"));\n    sqlite3VdbeJumpHere(v, addr);\n  }\n}\n\n/*\n** Add code that will check to make sure the N registers starting at iMem\n** form a distinct entry.  iTab is a sorting index that holds previously\n** seen combinations of the N values.  A new entry is made in iTab\n** if the current N values are new.\n**\n** A jump to addrRepeat is made and the N+1 values are popped from the\n** stack if the top N elements are not distinct.\n*/\nstatic void codeDistinct(\n  Parse *pParse,     /* Parsing and code generating context */\n  int iTab,          /* A sorting index used to test for distinctness */\n  int addrRepeat,    /* Jump to here if not distinct */\n  int N,             /* Number of elements */\n  int iMem           /* First element */\n){\n  Vdbe *v;\n  int r1;\n\n  v = pParse->pVdbe;\n  r1 = sqlite3GetTempReg(pParse);\n  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);\n  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);\n  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);\n  sqlite3ReleaseTempReg(pParse, r1);\n}\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** Generate an error message when a SELECT is used within a subexpression\n** (example:  \"a IN (SELECT * FROM table)\") but it has more than 1 result\n** column.  We do this in a subroutine because the error used to occur\n** in multiple places.  (The error only occurs in one place now, but we\n** retain the subroutine to minimize code disruption.)\n*/\nstatic int checkForMultiColumnSelectError(\n  Parse *pParse,       /* Parse context. */\n  SelectDest *pDest,   /* Destination of SELECT results */\n  int nExpr            /* Number of result columns returned by SELECT */\n){\n  int eDest = pDest->eDest;\n  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){\n    sqlite3ErrorMsg(pParse, \"only a single result allowed for \"\n       \"a SELECT that is part of an expression\");\n    return 1;\n  }else{\n    return 0;\n  }\n}\n#endif\n\n/*\n** This routine generates the code for the inside of the inner loop\n** of a SELECT.\n**\n** If srcTab and nColumn are both zero, then the pEList expressions\n** are evaluated in order to get the data for this row.  If nColumn>0\n** then data is pulled from srcTab and pEList is used only to get the\n** datatypes for each column.\n*/\nstatic void selectInnerLoop(\n  Parse *pParse,          /* The parser context */\n  Select *p,              /* The complete select statement being coded */\n  ExprList *pEList,       /* List of values being extracted */\n  int srcTab,             /* Pull data from this table */\n  int nColumn,            /* Number of columns in the source table */\n  ExprList *pOrderBy,     /* If not NULL, sort results using this key */\n  int distinct,           /* If >=0, make sure results are distinct */\n  SelectDest *pDest,      /* How to dispose of the results */\n  int iContinue,          /* Jump here to continue with next row */\n  int iBreak              /* Jump here to break out of the inner loop */\n){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  int hasDistinct;        /* True if the DISTINCT keyword is present */\n  int regResult;              /* Start of memory holding result set */\n  int eDest = pDest->eDest;   /* How to dispose of results */\n  int iParm = pDest->iSDParm; /* First argument to disposal method */\n  int nResultCol;             /* Number of result columns */\n\n  assert( v );\n  if( NEVER(v==0) ) return;\n  assert( pEList!=0 );\n  hasDistinct = distinct>=0;\n  if( pOrderBy==0 && !hasDistinct ){\n    codeOffset(v, p, iContinue);\n  }\n\n  /* Pull the requested columns.\n  */\n  if( nColumn>0 ){\n    nResultCol = nColumn;\n  }else{\n    nResultCol = pEList->nExpr;\n  }\n  if( pDest->iSdst==0 ){\n    pDest->iSdst = pParse->nMem+1;\n    pDest->nSdst = nResultCol;\n    pParse->nMem += nResultCol;\n  }else{ \n    assert( pDest->nSdst==nResultCol );\n  }\n  regResult = pDest->iSdst;\n  if( nColumn>0 ){\n    for(i=0; i<nColumn; i++){\n      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);\n    }\n  }else if( eDest!=SRT_Exists ){\n    /* If the destination is an EXISTS(...) expression, the actual\n    ** values returned by the SELECT are not required.\n    */\n    sqlite3ExprCacheClear(pParse);\n    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);\n  }\n  nColumn = nResultCol;\n\n  /* If the DISTINCT keyword was present on the SELECT statement\n  ** and this row has been seen before, then do not make this row\n  ** part of the result.\n  */\n  if( hasDistinct ){\n    assert( pEList!=0 );\n    assert( pEList->nExpr==nColumn );\n    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);\n    if( pOrderBy==0 ){\n      codeOffset(v, p, iContinue);\n    }\n  }\n\n  switch( eDest ){\n    /* In this mode, write each query result to the key of the temporary\n    ** table iParm.\n    */\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n    case SRT_Union: {\n      int r1;\n      r1 = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);\n      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n    /* Construct a record from the query result, but instead of\n    ** saving that record, use it as a key to delete elements from\n    ** the temporary table iParm.\n    */\n    case SRT_Except: {\n      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);\n      break;\n    }\n#endif\n\n    /* Store the result as data using a unique key.\n    */\n    case SRT_Table:\n    case SRT_EphemTab: {\n      int r1 = sqlite3GetTempReg(pParse);\n      testcase( eDest==SRT_Table );\n      testcase( eDest==SRT_EphemTab );\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);\n      if( pOrderBy ){\n        pushOntoSorter(pParse, pOrderBy, p, r1);\n      }else{\n        int r2 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);\n        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);\n        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n        sqlite3ReleaseTempReg(pParse, r2);\n      }\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n#ifndef SQLITE_OMIT_SUBQUERY\n    /* If we are creating a set for an \"expr IN (SELECT ...)\" construct,\n    ** then there should be a single item on the stack.  Write this\n    ** item into the set table with bogus data.\n    */\n    case SRT_Set: {\n      assert( nColumn==1 );\n      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);\n      if( pOrderBy ){\n        /* At first glance you would think we could optimize out the\n        ** ORDER BY in this case since the order of entries in the set\n        ** does not matter.  But there might be a LIMIT clause, in which\n        ** case the order does matter */\n        pushOntoSorter(pParse, pOrderBy, p, regResult);\n      }else{\n        int r1 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);\n        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);\n        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);\n        sqlite3ReleaseTempReg(pParse, r1);\n      }\n      break;\n    }\n\n    /* If any row exist in the result set, record that fact and abort.\n    */\n    case SRT_Exists: {\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);\n      /* The LIMIT clause will terminate the loop for us */\n      break;\n    }\n\n    /* If this is a scalar select that is part of an expression, then\n    ** store the results in the appropriate memory cell and break out\n    ** of the scan loop.\n    */\n    case SRT_Mem: {\n      assert( nColumn==1 );\n      if( pOrderBy ){\n        pushOntoSorter(pParse, pOrderBy, p, regResult);\n      }else{\n        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);\n        /* The LIMIT clause will jump out of the loop for us */\n      }\n      break;\n    }\n#endif /* #ifndef SQLITE_OMIT_SUBQUERY */\n\n    /* Send the data to the callback function or to a subroutine.  In the\n    ** case of a subroutine, the subroutine itself is responsible for\n    ** popping the data from the stack.\n    */\n    case SRT_Coroutine:\n    case SRT_Output: {\n      testcase( eDest==SRT_Coroutine );\n      testcase( eDest==SRT_Output );\n      if( pOrderBy ){\n        int r1 = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);\n        pushOntoSorter(pParse, pOrderBy, p, r1);\n        sqlite3ReleaseTempReg(pParse, r1);\n      }else if( eDest==SRT_Coroutine ){\n        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);\n        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);\n      }\n      break;\n    }\n\n#if !defined(SQLITE_OMIT_TRIGGER)\n    /* Discard the results.  This is used for SELECT statements inside\n    ** the body of a TRIGGER.  The purpose of such selects is to call\n    ** user-defined functions that have side effects.  We do not care\n    ** about the actual results of the select.\n    */\n    default: {\n      assert( eDest==SRT_Discard );\n      break;\n    }\n#endif\n  }\n\n  /* Jump to the end of the loop if the LIMIT is reached.  Except, if\n  ** there is a sorter, in which case the sorter has already limited\n  ** the output for us.\n  */\n  if( pOrderBy==0 && p->iLimit ){\n    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);\n  }\n}\n\n/*\n** Given an expression list, generate a KeyInfo structure that records\n** the collating sequence for each expression in that expression list.\n**\n** If the ExprList is an ORDER BY or GROUP BY clause then the resulting\n** KeyInfo structure is appropriate for initializing a virtual index to\n** implement that clause.  If the ExprList is the result set of a SELECT\n** then the KeyInfo structure is appropriate for initializing a virtual\n** index to implement a DISTINCT test.\n**\n** Space to hold the KeyInfo structure is obtain from malloc.  The calling\n** function is responsible for seeing that this structure is eventually\n** freed.  Add the KeyInfo structure to the P4 field of an opcode using\n** P4_KEYINFO_HANDOFF is the usual way of dealing with this.\n*/\nstatic KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){\n  sqlite3 *db = pParse->db;\n  int nExpr;\n  KeyInfo *pInfo;\n  struct ExprList_item *pItem;\n  int i;\n\n  nExpr = pList->nExpr;\n  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );\n  if( pInfo ){\n    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];\n    pInfo->nField = (u16)nExpr;\n    pInfo->enc = ENC(db);\n    pInfo->db = db;\n    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){\n      CollSeq *pColl;\n      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);\n      if( !pColl ){\n        pColl = db->pDfltColl;\n      }\n      pInfo->aColl[i] = pColl;\n      pInfo->aSortOrder[i] = pItem->sortOrder;\n    }\n  }\n  return pInfo;\n}\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n/*\n** Name of the connection operator, used for error messages.\n*/\nstatic const char *selectOpName(int id){\n  char *z;\n  switch( id ){\n    case TK_ALL:       z = \"UNION ALL\";   break;\n    case TK_INTERSECT: z = \"INTERSECT\";   break;\n    case TK_EXCEPT:    z = \"EXCEPT\";      break;\n    default:           z = \"UNION\";       break;\n  }\n  return z;\n}\n#endif /* SQLITE_OMIT_COMPOUND_SELECT */\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** Unless an \"EXPLAIN QUERY PLAN\" command is being processed, this function\n** is a no-op. Otherwise, it adds a single row of output to the EQP result,\n** where the caption is of the form:\n**\n**   \"USE TEMP B-TREE FOR xxx\"\n**\n** where xxx is one of \"DISTINCT\", \"ORDER BY\" or \"GROUP BY\". Exactly which\n** is determined by the zUsage argument.\n*/\nstatic void explainTempTable(Parse *pParse, const char *zUsage){\n  if( pParse->explain==2 ){\n    Vdbe *v = pParse->pVdbe;\n    char *zMsg = sqlite3MPrintf(pParse->db, \"USE TEMP B-TREE FOR %s\", zUsage);\n    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);\n  }\n}\n\n/*\n** Assign expression b to lvalue a. A second, no-op, version of this macro\n** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code\n** in sqlite3Select() to assign values to structure member variables that\n** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the\n** code with #ifndef directives.\n*/\n# define explainSetInteger(a, b) a = b\n\n#else\n/* No-op versions of the explainXXX() functions and macros. */\n# define explainTempTable(y,z)\n# define explainSetInteger(y,z)\n#endif\n\n#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)\n/*\n** Unless an \"EXPLAIN QUERY PLAN\" command is being processed, this function\n** is a no-op. Otherwise, it adds a single row of output to the EQP result,\n** where the caption is of one of the two forms:\n**\n**   \"COMPOSITE SUBQUERIES iSub1 and iSub2 (op)\"\n**   \"COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)\"\n**\n** where iSub1 and iSub2 are the integers passed as the corresponding\n** function parameters, and op is the text representation of the parameter\n** of the same name. The parameter \"op\" must be one of TK_UNION, TK_EXCEPT,\n** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is \n** false, or the second form if it is true.\n*/\nstatic void explainComposite(\n  Parse *pParse,                  /* Parse context */\n  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */\n  int iSub1,                      /* Subquery id 1 */\n  int iSub2,                      /* Subquery id 2 */\n  int bUseTmp                     /* True if a temp table was used */\n){\n  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );\n  if( pParse->explain==2 ){\n    Vdbe *v = pParse->pVdbe;\n    char *zMsg = sqlite3MPrintf(\n        pParse->db, \"COMPOUND SUBQUERIES %d AND %d %s(%s)\", iSub1, iSub2,\n        bUseTmp?\"USING TEMP B-TREE \":\"\", selectOpName(op)\n    );\n    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);\n  }\n}\n#else\n/* No-op versions of the explainXXX() functions and macros. */\n# define explainComposite(v,w,x,y,z)\n#endif\n\n/*\n** If the inner loop was generated using a non-null pOrderBy argument,\n** then the results were placed in a sorter.  After the loop is terminated\n** we need to run the sorter and output the results.  The following\n** routine generates the code needed to do that.\n*/\nstatic void generateSortTail(\n  Parse *pParse,    /* Parsing context */\n  Select *p,        /* The SELECT statement */\n  Vdbe *v,          /* Generate code into this VDBE */\n  int nColumn,      /* Number of columns of data */\n  SelectDest *pDest /* Write the sorted results here */\n){\n  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */\n  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */\n  int addr;\n  int iTab;\n  int pseudoTab = 0;\n  ExprList *pOrderBy = p->pOrderBy;\n\n  int eDest = pDest->eDest;\n  int iParm = pDest->iSDParm;\n\n  int regRow;\n  int regRowid;\n\n  iTab = pOrderBy->iECursor;\n  regRow = sqlite3GetTempReg(pParse);\n  if( eDest==SRT_Output || eDest==SRT_Coroutine ){\n    pseudoTab = pParse->nTab++;\n    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);\n    regRowid = 0;\n  }else{\n    regRowid = sqlite3GetTempReg(pParse);\n  }\n  if( p->selFlags & SF_UseSorter ){\n    int regSortOut = ++pParse->nMem;\n    int ptab2 = pParse->nTab++;\n    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);\n    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);\n    codeOffset(v, p, addrContinue);\n    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);\n    sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);\n    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);\n  }else{\n    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);\n    codeOffset(v, p, addrContinue);\n    sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);\n  }\n  switch( eDest ){\n    case SRT_Table:\n    case SRT_EphemTab: {\n      testcase( eDest==SRT_Table );\n      testcase( eDest==SRT_EphemTab );\n      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);\n      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);\n      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case SRT_Set: {\n      assert( nColumn==1 );\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);\n      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);\n      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);\n      break;\n    }\n    case SRT_Mem: {\n      assert( nColumn==1 );\n      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);\n      /* The LIMIT clause will terminate the loop for us */\n      break;\n    }\n#endif\n    default: {\n      int i;\n      assert( eDest==SRT_Output || eDest==SRT_Coroutine ); \n      testcase( eDest==SRT_Output );\n      testcase( eDest==SRT_Coroutine );\n      for(i=0; i<nColumn; i++){\n        assert( regRow!=pDest->iSdst+i );\n        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);\n        if( i==0 ){\n          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);\n        }\n      }\n      if( eDest==SRT_Output ){\n        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);\n        sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);\n      }else{\n        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      }\n      break;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, regRow);\n  sqlite3ReleaseTempReg(pParse, regRowid);\n\n  /* The bottom of the loop\n  */\n  sqlite3VdbeResolveLabel(v, addrContinue);\n  if( p->selFlags & SF_UseSorter ){\n    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);\n  }else{\n    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);\n  }\n  sqlite3VdbeResolveLabel(v, addrBreak);\n  if( eDest==SRT_Output || eDest==SRT_Coroutine ){\n    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);\n  }\n}\n\n/*\n** Return a pointer to a string containing the 'declaration type' of the\n** expression pExpr. The string may be treated as static by the caller.\n**\n** The declaration type is the exact datatype definition extracted from the\n** original CREATE TABLE statement if the expression is a column. The\n** declaration type for a ROWID field is INTEGER. Exactly when an expression\n** is considered a column can be complex in the presence of subqueries. The\n** result-set expression in all of the following SELECT statements is \n** considered a column by this function.\n**\n**   SELECT col FROM tbl;\n**   SELECT (SELECT col FROM tbl;\n**   SELECT (SELECT col FROM tbl);\n**   SELECT abc FROM (SELECT col AS abc FROM tbl);\n** \n** The declaration type for any expression other than a column is NULL.\n*/\nstatic const char *columnType(\n  NameContext *pNC, \n  Expr *pExpr,\n  const char **pzOriginDb,\n  const char **pzOriginTab,\n  const char **pzOriginCol\n){\n  char const *zType = 0;\n  char const *zOriginDb = 0;\n  char const *zOriginTab = 0;\n  char const *zOriginCol = 0;\n  int j;\n  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;\n\n  switch( pExpr->op ){\n    case TK_AGG_COLUMN:\n    case TK_COLUMN: {\n      /* The expression is a column. Locate the table the column is being\n      ** extracted from in NameContext.pSrcList. This table may be real\n      ** database table or a subquery.\n      */\n      Table *pTab = 0;            /* Table structure column is extracted from */\n      Select *pS = 0;             /* Select the column is extracted from */\n      int iCol = pExpr->iColumn;  /* Index of column in pTab */\n      testcase( pExpr->op==TK_AGG_COLUMN );\n      testcase( pExpr->op==TK_COLUMN );\n      while( pNC && !pTab ){\n        SrcList *pTabList = pNC->pSrcList;\n        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);\n        if( j<pTabList->nSrc ){\n          pTab = pTabList->a[j].pTab;\n          pS = pTabList->a[j].pSelect;\n        }else{\n          pNC = pNC->pNext;\n        }\n      }\n\n      if( pTab==0 ){\n        /* At one time, code such as \"SELECT new.x\" within a trigger would\n        ** cause this condition to run.  Since then, we have restructured how\n        ** trigger code is generated and so this condition is no longer \n        ** possible. However, it can still be true for statements like\n        ** the following:\n        **\n        **   CREATE TABLE t1(col INTEGER);\n        **   SELECT (SELECT t1.col) FROM FROM t1;\n        **\n        ** when columnType() is called on the expression \"t1.col\" in the \n        ** sub-select. In this case, set the column type to NULL, even\n        ** though it should really be \"INTEGER\".\n        **\n        ** This is not a problem, as the column type of \"t1.col\" is never\n        ** used. When columnType() is called on the expression \n        ** \"(SELECT t1.col)\", the correct type is returned (see the TK_SELECT\n        ** branch below.  */\n        break;\n      }\n\n      assert( pTab && pExpr->pTab==pTab );\n      if( pS ){\n        /* The \"table\" is actually a sub-select or a view in the FROM clause\n        ** of the SELECT statement. Return the declaration type and origin\n        ** data for the result-set column of the sub-select.\n        */\n        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){\n          /* If iCol is less than zero, then the expression requests the\n          ** rowid of the sub-select or view. This expression is legal (see \n          ** test case misc2.2.2) - it always evaluates to NULL.\n          */\n          NameContext sNC;\n          Expr *p = pS->pEList->a[iCol].pExpr;\n          sNC.pSrcList = pS->pSrc;\n          sNC.pNext = pNC;\n          sNC.pParse = pNC->pParse;\n          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); \n        }\n      }else if( ALWAYS(pTab->pSchema) ){\n        /* A real table */\n        assert( !pS );\n        if( iCol<0 ) iCol = pTab->iPKey;\n        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );\n        if( iCol<0 ){\n          zType = \"INTEGER\";\n          zOriginCol = \"rowid\";\n        }else{\n          zType = pTab->aCol[iCol].zType;\n          zOriginCol = pTab->aCol[iCol].zName;\n        }\n        zOriginTab = pTab->zName;\n        if( pNC->pParse ){\n          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);\n          zOriginDb = pNC->pParse->db->aDb[iDb].zName;\n        }\n      }\n      break;\n    }\n#ifndef SQLITE_OMIT_SUBQUERY\n    case TK_SELECT: {\n      /* The expression is a sub-select. Return the declaration type and\n      ** origin info for the single column in the result set of the SELECT\n      ** statement.\n      */\n      NameContext sNC;\n      Select *pS = pExpr->x.pSelect;\n      Expr *p = pS->pEList->a[0].pExpr;\n      assert( ExprHasProperty(pExpr, EP_xIsSelect) );\n      sNC.pSrcList = pS->pSrc;\n      sNC.pNext = pNC;\n      sNC.pParse = pNC->pParse;\n      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); \n      break;\n    }\n#endif\n  }\n  \n  if( pzOriginDb ){\n    assert( pzOriginTab && pzOriginCol );\n    *pzOriginDb = zOriginDb;\n    *pzOriginTab = zOriginTab;\n    *pzOriginCol = zOriginCol;\n  }\n  return zType;\n}\n\n/*\n** Generate code that will tell the VDBE the declaration types of columns\n** in the result set.\n*/\nstatic void generateColumnTypes(\n  Parse *pParse,      /* Parser context */\n  SrcList *pTabList,  /* List of tables */\n  ExprList *pEList    /* Expressions defining the result set */\n){\n#ifndef SQLITE_OMIT_DECLTYPE\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  NameContext sNC;\n  sNC.pSrcList = pTabList;\n  sNC.pParse = pParse;\n  for(i=0; i<pEList->nExpr; i++){\n    Expr *p = pEList->a[i].pExpr;\n    const char *zType;\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\n    const char *zOrigDb = 0;\n    const char *zOrigTab = 0;\n    const char *zOrigCol = 0;\n    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);\n\n    /* The vdbe must make its own copy of the column-type and other \n    ** column specific strings, in case the schema is reset before this\n    ** virtual machine is deleted.\n    */\n    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);\n    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);\n    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);\n#else\n    zType = columnType(&sNC, p, 0, 0, 0);\n#endif\n    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);\n  }\n#endif /* SQLITE_OMIT_DECLTYPE */\n}\n\n/*\n** Generate code that will tell the VDBE the names of columns\n** in the result set.  This information is used to provide the\n** azCol[] values in the callback.\n*/\nstatic void generateColumnNames(\n  Parse *pParse,      /* Parser context */\n  SrcList *pTabList,  /* List of tables */\n  ExprList *pEList    /* Expressions defining the result set */\n){\n  Vdbe *v = pParse->pVdbe;\n  int i, j;\n  sqlite3 *db = pParse->db;\n  int fullNames, shortNames;\n\n#ifndef SQLITE_OMIT_EXPLAIN\n  /* If this is an EXPLAIN, skip this step */\n  if( pParse->explain ){\n    return;\n  }\n#endif\n\n  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;\n  pParse->colNamesSet = 1;\n  fullNames = (db->flags & SQLITE_FullColNames)!=0;\n  shortNames = (db->flags & SQLITE_ShortColNames)!=0;\n  sqlite3VdbeSetNumCols(v, pEList->nExpr);\n  for(i=0; i<pEList->nExpr; i++){\n    Expr *p;\n    p = pEList->a[i].pExpr;\n    if( NEVER(p==0) ) continue;\n    if( pEList->a[i].zName ){\n      char *zName = pEList->a[i].zName;\n      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);\n    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){\n      Table *pTab;\n      char *zCol;\n      int iCol = p->iColumn;\n      for(j=0; ALWAYS(j<pTabList->nSrc); j++){\n        if( pTabList->a[j].iCursor==p->iTable ) break;\n      }\n      assert( j<pTabList->nSrc );\n      pTab = pTabList->a[j].pTab;\n      if( iCol<0 ) iCol = pTab->iPKey;\n      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );\n      if( iCol<0 ){\n        zCol = \"rowid\";\n      }else{\n        zCol = pTab->aCol[iCol].zName;\n      }\n      if( !shortNames && !fullNames ){\n        sqlite3VdbeSetColName(v, i, COLNAME_NAME, \n            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);\n      }else if( fullNames ){\n        char *zName = 0;\n        zName = sqlite3MPrintf(db, \"%s.%s\", pTab->zName, zCol);\n        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);\n      }else{\n        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);\n      }\n    }else{\n      sqlite3VdbeSetColName(v, i, COLNAME_NAME, \n          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);\n    }\n  }\n  generateColumnTypes(pParse, pTabList, pEList);\n}\n\n/*\n** Given a an expression list (which is really the list of expressions\n** that form the result set of a SELECT statement) compute appropriate\n** column names for a table that would hold the expression list.\n**\n** All column names will be unique.\n**\n** Only the column names are computed.  Column.zType, Column.zColl,\n** and other fields of Column are zeroed.\n**\n** Return SQLITE_OK on success.  If a memory allocation error occurs,\n** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.\n*/\nstatic int selectColumnsFromExprList(\n  Parse *pParse,          /* Parsing context */\n  ExprList *pEList,       /* Expr list from which to derive column names */\n  int *pnCol,             /* Write the number of columns here */\n  Column **paCol          /* Write the new column list here */\n){\n  sqlite3 *db = pParse->db;   /* Database connection */\n  int i, j;                   /* Loop counters */\n  int cnt;                    /* Index added to make the name unique */\n  Column *aCol, *pCol;        /* For looping over result columns */\n  int nCol;                   /* Number of columns in the result set */\n  Expr *p;                    /* Expression for a single result column */\n  char *zName;                /* Column name */\n  int nName;                  /* Size of name in zName[] */\n\n  if( pEList ){\n    nCol = pEList->nExpr;\n    aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);\n    testcase( aCol==0 );\n  }else{\n    nCol = 0;\n    aCol = 0;\n  }\n  *pnCol = nCol;\n  *paCol = aCol;\n\n  for(i=0, pCol=aCol; i<nCol; i++, pCol++){\n    /* Get an appropriate name for the column\n    */\n    p = pEList->a[i].pExpr;\n    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)\n               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );\n    if( (zName = pEList->a[i].zName)!=0 ){\n      /* If the column contains an \"AS <name>\" phrase, use <name> as the name */\n      zName = sqlite3DbStrDup(db, zName);\n    }else{\n      Expr *pColExpr = p;  /* The expression that is the result column name */\n      Table *pTab;         /* Table associated with this expression */\n      while( pColExpr->op==TK_DOT ){\n        pColExpr = pColExpr->pRight;\n        assert( pColExpr!=0 );\n      }\n      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){\n        /* For columns use the column name name */\n        int iCol = pColExpr->iColumn;\n        pTab = pColExpr->pTab;\n        if( iCol<0 ) iCol = pTab->iPKey;\n        zName = sqlite3MPrintf(db, \"%s\",\n                 iCol>=0 ? pTab->aCol[iCol].zName : \"rowid\");\n      }else if( pColExpr->op==TK_ID ){\n        assert( !ExprHasProperty(pColExpr, EP_IntValue) );\n        zName = sqlite3MPrintf(db, \"%s\", pColExpr->u.zToken);\n      }else{\n        /* Use the original text of the column expression as its name */\n        zName = sqlite3MPrintf(db, \"%s\", pEList->a[i].zSpan);\n      }\n    }\n    if( db->mallocFailed ){\n      sqlite3DbFree(db, zName);\n      break;\n    }\n\n    /* Make sure the column name is unique.  If the name is not unique,\n    ** append a integer to the name so that it becomes unique.\n    */\n    nName = sqlite3Strlen30(zName);\n    for(j=cnt=0; j<i; j++){\n      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){\n        char *zNewName;\n        zName[nName] = 0;\n        zNewName = sqlite3MPrintf(db, \"%s:%d\", zName, ++cnt);\n        sqlite3DbFree(db, zName);\n        zName = zNewName;\n        j = -1;\n        if( zName==0 ) break;\n      }\n    }\n    pCol->zName = zName;\n  }\n  if( db->mallocFailed ){\n    for(j=0; j<i; j++){\n      sqlite3DbFree(db, aCol[j].zName);\n    }\n    sqlite3DbFree(db, aCol);\n    *paCol = 0;\n    *pnCol = 0;\n    return SQLITE_NOMEM;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Add type and collation information to a column list based on\n** a SELECT statement.\n** \n** The column list presumably came from selectColumnNamesFromExprList().\n** The column list has only names, not types or collations.  This\n** routine goes through and adds the types and collations.\n**\n** This routine requires that all identifiers in the SELECT\n** statement be resolved.\n*/\nstatic void selectAddColumnTypeAndCollation(\n  Parse *pParse,        /* Parsing contexts */\n  int nCol,             /* Number of columns */\n  Column *aCol,         /* List of columns */\n  Select *pSelect       /* SELECT used to determine types and collations */\n){\n  sqlite3 *db = pParse->db;\n  NameContext sNC;\n  Column *pCol;\n  CollSeq *pColl;\n  int i;\n  Expr *p;\n  struct ExprList_item *a;\n\n  assert( pSelect!=0 );\n  assert( (pSelect->selFlags & SF_Resolved)!=0 );\n  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );\n  if( db->mallocFailed ) return;\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pSrcList = pSelect->pSrc;\n  a = pSelect->pEList->a;\n  for(i=0, pCol=aCol; i<nCol; i++, pCol++){\n    p = a[i].pExpr;\n    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));\n    pCol->affinity = sqlite3ExprAffinity(p);\n    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;\n    pColl = sqlite3ExprCollSeq(pParse, p);\n    if( pColl ){\n      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);\n    }\n  }\n}\n\n/*\n** Given a SELECT statement, generate a Table structure that describes\n** the result set of that SELECT.\n*/\nSQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){\n  Table *pTab;\n  sqlite3 *db = pParse->db;\n  int savedFlags;\n\n  savedFlags = db->flags;\n  db->flags &= ~SQLITE_FullColNames;\n  db->flags |= SQLITE_ShortColNames;\n  sqlite3SelectPrep(pParse, pSelect, 0);\n  if( pParse->nErr ) return 0;\n  while( pSelect->pPrior ) pSelect = pSelect->pPrior;\n  db->flags = savedFlags;\n  pTab = sqlite3DbMallocZero(db, sizeof(Table) );\n  if( pTab==0 ){\n    return 0;\n  }\n  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside\n  ** is disabled */\n  assert( db->lookaside.bEnabled==0 );\n  pTab->nRef = 1;\n  pTab->zName = 0;\n  pTab->nRowEst = 1000000;\n  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);\n  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);\n  pTab->iPKey = -1;\n  if( db->mallocFailed ){\n    sqlite3DeleteTable(db, pTab);\n    return 0;\n  }\n  return pTab;\n}\n\n/*\n** Get a VDBE for the given parser context.  Create a new one if necessary.\n** If an error occurs, return NULL and leave a message in pParse.\n*/\nSQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){\n  Vdbe *v = pParse->pVdbe;\n  if( v==0 ){\n    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);\n#ifndef SQLITE_OMIT_TRACE\n    if( v ){\n      sqlite3VdbeAddOp0(v, OP_Trace);\n    }\n#endif\n  }\n  return v;\n}\n\n\n/*\n** Compute the iLimit and iOffset fields of the SELECT based on the\n** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions\n** that appear in the original SQL statement after the LIMIT and OFFSET\n** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset \n** are the integer memory register numbers for counters used to compute \n** the limit and offset.  If there is no limit and/or offset, then \n** iLimit and iOffset are negative.\n**\n** This routine changes the values of iLimit and iOffset only if\n** a limit or offset is defined by pLimit and pOffset.  iLimit and\n** iOffset should have been preset to appropriate default values\n** (usually but not always -1) prior to calling this routine.\n** Only if pLimit!=0 or pOffset!=0 do the limit registers get\n** redefined.  The UNION ALL operator uses this property to force\n** the reuse of the same limit and offset registers across multiple\n** SELECT statements.\n*/\nstatic void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){\n  Vdbe *v = 0;\n  int iLimit = 0;\n  int iOffset;\n  int addr1, n;\n  if( p->iLimit ) return;\n\n  /* \n  ** \"LIMIT -1\" always shows all rows.  There is some\n  ** contraversy about what the correct behavior should be.\n  ** The current implementation interprets \"LIMIT 0\" to mean\n  ** no rows.\n  */\n  sqlite3ExprCacheClear(pParse);\n  assert( p->pOffset==0 || p->pLimit!=0 );\n  if( p->pLimit ){\n    p->iLimit = iLimit = ++pParse->nMem;\n    v = sqlite3GetVdbe(pParse);\n    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */\n    if( sqlite3ExprIsInteger(p->pLimit, &n) ){\n      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);\n      VdbeComment((v, \"LIMIT counter\"));\n      if( n==0 ){\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);\n      }else{\n        if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;\n      }\n    }else{\n      sqlite3ExprCode(pParse, p->pLimit, iLimit);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);\n      VdbeComment((v, \"LIMIT counter\"));\n      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);\n    }\n    if( p->pOffset ){\n      p->iOffset = iOffset = ++pParse->nMem;\n      pParse->nMem++;   /* Allocate an extra register for limit+offset */\n      sqlite3ExprCode(pParse, p->pOffset, iOffset);\n      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);\n      VdbeComment((v, \"OFFSET counter\"));\n      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);\n      sqlite3VdbeJumpHere(v, addr1);\n      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);\n      VdbeComment((v, \"LIMIT+OFFSET\"));\n      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);\n      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);\n      sqlite3VdbeJumpHere(v, addr1);\n    }\n  }\n}\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n/*\n** Return the appropriate collating sequence for the iCol-th column of\n** the result set for the compound-select statement \"p\".  Return NULL if\n** the column has no default collating sequence.\n**\n** The collating sequence for the compound select is taken from the\n** left-most term of the select that has a collating sequence.\n*/\nstatic CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){\n  CollSeq *pRet;\n  if( p->pPrior ){\n    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);\n  }else{\n    pRet = 0;\n  }\n  assert( iCol>=0 );\n  if( pRet==0 && iCol<p->pEList->nExpr ){\n    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);\n  }\n  return pRet;\n}\n#endif /* SQLITE_OMIT_COMPOUND_SELECT */\n\n/* Forward reference */\nstatic int multiSelectOrderBy(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n);\n\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n/*\n** This routine is called to process a compound query form from\n** two or more separate queries using UNION, UNION ALL, EXCEPT, or\n** INTERSECT\n**\n** \"p\" points to the right-most of the two queries.  the query on the\n** left is p->pPrior.  The left query could also be a compound query\n** in which case this routine will be called recursively. \n**\n** The results of the total query are to be written into a destination\n** of type eDest with parameter iParm.\n**\n** Example 1:  Consider a three-way compound SQL statement.\n**\n**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3\n**\n** This statement is parsed up as follows:\n**\n**     SELECT c FROM t3\n**      |\n**      `----->  SELECT b FROM t2\n**                |\n**                `------>  SELECT a FROM t1\n**\n** The arrows in the diagram above represent the Select.pPrior pointer.\n** So if this routine is called with p equal to the t3 query, then\n** pPrior will be the t2 query.  p->op will be TK_UNION in this case.\n**\n** Notice that because of the way SQLite parses compound SELECTs, the\n** individual selects always group from left to right.\n*/\nstatic int multiSelect(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  int rc = SQLITE_OK;   /* Success code from a subroutine */\n  Select *pPrior;       /* Another SELECT immediately to our left */\n  Vdbe *v;              /* Generate code to this VDBE */\n  SelectDest dest;      /* Alternative data destination */\n  Select *pDelete = 0;  /* Chain of simple selects to delete */\n  sqlite3 *db;          /* Database connection */\n#ifndef SQLITE_OMIT_EXPLAIN\n  int iSub1;            /* EQP id of left-hand query */\n  int iSub2;            /* EQP id of right-hand query */\n#endif\n\n  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only\n  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.\n  */\n  assert( p && p->pPrior );  /* Calling function guarantees this much */\n  db = pParse->db;\n  pPrior = p->pPrior;\n  assert( pPrior->pRightmost!=pPrior );\n  assert( pPrior->pRightmost==p->pRightmost );\n  dest = *pDest;\n  if( pPrior->pOrderBy ){\n    sqlite3ErrorMsg(pParse,\"ORDER BY clause should come after %s not before\",\n      selectOpName(p->op));\n    rc = 1;\n    goto multi_select_end;\n  }\n  if( pPrior->pLimit ){\n    sqlite3ErrorMsg(pParse,\"LIMIT clause should come after %s not before\",\n      selectOpName(p->op));\n    rc = 1;\n    goto multi_select_end;\n  }\n\n  v = sqlite3GetVdbe(pParse);\n  assert( v!=0 );  /* The VDBE already created by calling function */\n\n  /* Create the destination temporary table if necessary\n  */\n  if( dest.eDest==SRT_EphemTab ){\n    assert( p->pEList );\n    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);\n    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n    dest.eDest = SRT_Table;\n  }\n\n  /* Make sure all SELECTs in the statement have the same number of elements\n  ** in their result sets.\n  */\n  assert( p->pEList && pPrior->pEList );\n  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){\n    if( p->selFlags & SF_Values ){\n      sqlite3ErrorMsg(pParse, \"all VALUES must have the same number of terms\");\n    }else{\n      sqlite3ErrorMsg(pParse, \"SELECTs to the left and right of %s\"\n        \" do not have the same number of result columns\", selectOpName(p->op));\n    }\n    rc = 1;\n    goto multi_select_end;\n  }\n\n  /* Compound SELECTs that have an ORDER BY clause are handled separately.\n  */\n  if( p->pOrderBy ){\n    return multiSelectOrderBy(pParse, p, pDest);\n  }\n\n  /* Generate code for the left and right SELECT statements.\n  */\n  switch( p->op ){\n    case TK_ALL: {\n      int addr = 0;\n      int nLimit;\n      assert( !pPrior->pLimit );\n      pPrior->pLimit = p->pLimit;\n      pPrior->pOffset = p->pOffset;\n      explainSetInteger(iSub1, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, pPrior, &dest);\n      p->pLimit = 0;\n      p->pOffset = 0;\n      if( rc ){\n        goto multi_select_end;\n      }\n      p->pPrior = 0;\n      p->iLimit = pPrior->iLimit;\n      p->iOffset = pPrior->iOffset;\n      if( p->iLimit ){\n        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);\n        VdbeComment((v, \"Jump ahead if LIMIT reached\"));\n      }\n      explainSetInteger(iSub2, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, p, &dest);\n      testcase( rc!=SQLITE_OK );\n      pDelete = p->pPrior;\n      p->pPrior = pPrior;\n      p->nSelectRow += pPrior->nSelectRow;\n      if( pPrior->pLimit\n       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)\n       && p->nSelectRow > (double)nLimit \n      ){\n        p->nSelectRow = (double)nLimit;\n      }\n      if( addr ){\n        sqlite3VdbeJumpHere(v, addr);\n      }\n      break;\n    }\n    case TK_EXCEPT:\n    case TK_UNION: {\n      int unionTab;    /* Cursor number of the temporary table holding result */\n      u8 op = 0;       /* One of the SRT_ operations to apply to self */\n      int priorOp;     /* The SRT_ operation to apply to prior selects */\n      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */\n      int addr;\n      SelectDest uniondest;\n\n      testcase( p->op==TK_EXCEPT );\n      testcase( p->op==TK_UNION );\n      priorOp = SRT_Union;\n      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){\n        /* We can reuse a temporary table generated by a SELECT to our\n        ** right.\n        */\n        assert( p->pRightmost!=p );  /* Can only happen for leftward elements\n                                     ** of a 3-way or more compound */\n        assert( p->pLimit==0 );      /* Not allowed on leftward elements */\n        assert( p->pOffset==0 );     /* Not allowed on leftward elements */\n        unionTab = dest.iSDParm;\n      }else{\n        /* We will need to create our own temporary table to hold the\n        ** intermediate results.\n        */\n        unionTab = pParse->nTab++;\n        assert( p->pOrderBy==0 );\n        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);\n        assert( p->addrOpenEphm[0] == -1 );\n        p->addrOpenEphm[0] = addr;\n        p->pRightmost->selFlags |= SF_UsesEphemeral;\n        assert( p->pEList );\n      }\n\n      /* Code the SELECT statements to our left\n      */\n      assert( !pPrior->pOrderBy );\n      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);\n      explainSetInteger(iSub1, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, pPrior, &uniondest);\n      if( rc ){\n        goto multi_select_end;\n      }\n\n      /* Code the current SELECT statement\n      */\n      if( p->op==TK_EXCEPT ){\n        op = SRT_Except;\n      }else{\n        assert( p->op==TK_UNION );\n        op = SRT_Union;\n      }\n      p->pPrior = 0;\n      pLimit = p->pLimit;\n      p->pLimit = 0;\n      pOffset = p->pOffset;\n      p->pOffset = 0;\n      uniondest.eDest = op;\n      explainSetInteger(iSub2, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, p, &uniondest);\n      testcase( rc!=SQLITE_OK );\n      /* Query flattening in sqlite3Select() might refill p->pOrderBy.\n      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */\n      sqlite3ExprListDelete(db, p->pOrderBy);\n      pDelete = p->pPrior;\n      p->pPrior = pPrior;\n      p->pOrderBy = 0;\n      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;\n      sqlite3ExprDelete(db, p->pLimit);\n      p->pLimit = pLimit;\n      p->pOffset = pOffset;\n      p->iLimit = 0;\n      p->iOffset = 0;\n\n      /* Convert the data in the temporary table into whatever form\n      ** it is that we currently need.\n      */\n      assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );\n      if( dest.eDest!=priorOp ){\n        int iCont, iBreak, iStart;\n        assert( p->pEList );\n        if( dest.eDest==SRT_Output ){\n          Select *pFirst = p;\n          while( pFirst->pPrior ) pFirst = pFirst->pPrior;\n          generateColumnNames(pParse, 0, pFirst->pEList);\n        }\n        iBreak = sqlite3VdbeMakeLabel(v);\n        iCont = sqlite3VdbeMakeLabel(v);\n        computeLimitRegisters(pParse, p, iBreak);\n        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);\n        iStart = sqlite3VdbeCurrentAddr(v);\n        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,\n                        0, -1, &dest, iCont, iBreak);\n        sqlite3VdbeResolveLabel(v, iCont);\n        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);\n        sqlite3VdbeResolveLabel(v, iBreak);\n        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);\n      }\n      break;\n    }\n    default: assert( p->op==TK_INTERSECT ); {\n      int tab1, tab2;\n      int iCont, iBreak, iStart;\n      Expr *pLimit, *pOffset;\n      int addr;\n      SelectDest intersectdest;\n      int r1;\n\n      /* INTERSECT is different from the others since it requires\n      ** two temporary tables.  Hence it has its own case.  Begin\n      ** by allocating the tables we will need.\n      */\n      tab1 = pParse->nTab++;\n      tab2 = pParse->nTab++;\n      assert( p->pOrderBy==0 );\n\n      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);\n      assert( p->addrOpenEphm[0] == -1 );\n      p->addrOpenEphm[0] = addr;\n      p->pRightmost->selFlags |= SF_UsesEphemeral;\n      assert( p->pEList );\n\n      /* Code the SELECTs to our left into temporary table \"tab1\".\n      */\n      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);\n      explainSetInteger(iSub1, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, pPrior, &intersectdest);\n      if( rc ){\n        goto multi_select_end;\n      }\n\n      /* Code the current SELECT into temporary table \"tab2\"\n      */\n      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);\n      assert( p->addrOpenEphm[1] == -1 );\n      p->addrOpenEphm[1] = addr;\n      p->pPrior = 0;\n      pLimit = p->pLimit;\n      p->pLimit = 0;\n      pOffset = p->pOffset;\n      p->pOffset = 0;\n      intersectdest.iSDParm = tab2;\n      explainSetInteger(iSub2, pParse->iNextSelectId);\n      rc = sqlite3Select(pParse, p, &intersectdest);\n      testcase( rc!=SQLITE_OK );\n      pDelete = p->pPrior;\n      p->pPrior = pPrior;\n      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;\n      sqlite3ExprDelete(db, p->pLimit);\n      p->pLimit = pLimit;\n      p->pOffset = pOffset;\n\n      /* Generate code to take the intersection of the two temporary\n      ** tables.\n      */\n      assert( p->pEList );\n      if( dest.eDest==SRT_Output ){\n        Select *pFirst = p;\n        while( pFirst->pPrior ) pFirst = pFirst->pPrior;\n        generateColumnNames(pParse, 0, pFirst->pEList);\n      }\n      iBreak = sqlite3VdbeMakeLabel(v);\n      iCont = sqlite3VdbeMakeLabel(v);\n      computeLimitRegisters(pParse, p, iBreak);\n      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);\n      r1 = sqlite3GetTempReg(pParse);\n      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);\n      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);\n      sqlite3ReleaseTempReg(pParse, r1);\n      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,\n                      0, -1, &dest, iCont, iBreak);\n      sqlite3VdbeResolveLabel(v, iCont);\n      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);\n      sqlite3VdbeResolveLabel(v, iBreak);\n      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);\n      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);\n      break;\n    }\n  }\n\n  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);\n\n  /* Compute collating sequences used by \n  ** temporary tables needed to implement the compound select.\n  ** Attach the KeyInfo structure to all temporary tables.\n  **\n  ** This section is run by the right-most SELECT statement only.\n  ** SELECT statements to the left always skip this part.  The right-most\n  ** SELECT might also skip this part if it has no ORDER BY clause and\n  ** no temp tables are required.\n  */\n  if( p->selFlags & SF_UsesEphemeral ){\n    int i;                        /* Loop counter */\n    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */\n    Select *pLoop;                /* For looping through SELECT statements */\n    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */\n    int nCol;                     /* Number of columns in result set */\n\n    assert( p->pRightmost==p );\n    nCol = p->pEList->nExpr;\n    pKeyInfo = sqlite3DbMallocZero(db,\n                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));\n    if( !pKeyInfo ){\n      rc = SQLITE_NOMEM;\n      goto multi_select_end;\n    }\n\n    pKeyInfo->enc = ENC(db);\n    pKeyInfo->nField = (u16)nCol;\n\n    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){\n      *apColl = multiSelectCollSeq(pParse, p, i);\n      if( 0==*apColl ){\n        *apColl = db->pDfltColl;\n      }\n    }\n\n    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){\n      for(i=0; i<2; i++){\n        int addr = pLoop->addrOpenEphm[i];\n        if( addr<0 ){\n          /* If [0] is unused then [1] is also unused.  So we can\n          ** always safely abort as soon as the first unused slot is found */\n          assert( pLoop->addrOpenEphm[1]<0 );\n          break;\n        }\n        sqlite3VdbeChangeP2(v, addr, nCol);\n        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);\n        pLoop->addrOpenEphm[i] = -1;\n      }\n    }\n    sqlite3DbFree(db, pKeyInfo);\n  }\n\nmulti_select_end:\n  pDest->iSdst = dest.iSdst;\n  pDest->nSdst = dest.nSdst;\n  sqlite3SelectDelete(db, pDelete);\n  return rc;\n}\n#endif /* SQLITE_OMIT_COMPOUND_SELECT */\n\n/*\n** Code an output subroutine for a coroutine implementation of a\n** SELECT statment.\n**\n** The data to be output is contained in pIn->iSdst.  There are\n** pIn->nSdst columns to be output.  pDest is where the output should\n** be sent.\n**\n** regReturn is the number of the register holding the subroutine\n** return address.\n**\n** If regPrev>0 then it is the first register in a vector that\n** records the previous output.  mem[regPrev] is a flag that is false\n** if there has been no previous output.  If regPrev>0 then code is\n** generated to suppress duplicates.  pKeyInfo is used for comparing\n** keys.\n**\n** If the LIMIT found in p->iLimit is reached, jump immediately to\n** iBreak.\n*/\nstatic int generateOutputSubroutine(\n  Parse *pParse,          /* Parsing context */\n  Select *p,              /* The SELECT statement */\n  SelectDest *pIn,        /* Coroutine supplying data */\n  SelectDest *pDest,      /* Where to send the data */\n  int regReturn,          /* The return address register */\n  int regPrev,            /* Previous result register.  No uniqueness if 0 */\n  KeyInfo *pKeyInfo,      /* For comparing with previous entry */\n  int p4type,             /* The p4 type for pKeyInfo */\n  int iBreak              /* Jump here if we hit the LIMIT */\n){\n  Vdbe *v = pParse->pVdbe;\n  int iContinue;\n  int addr;\n\n  addr = sqlite3VdbeCurrentAddr(v);\n  iContinue = sqlite3VdbeMakeLabel(v);\n\n  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT \n  */\n  if( regPrev ){\n    int j1, j2;\n    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);\n    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,\n                              (char*)pKeyInfo, p4type);\n    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);\n    sqlite3VdbeJumpHere(v, j1);\n    sqlite3ExprCodeCopy(pParse, pIn->iSdst, regPrev+1, pIn->nSdst);\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);\n  }\n  if( pParse->db->mallocFailed ) return 0;\n\n  /* Suppress the first OFFSET entries if there is an OFFSET clause\n  */\n  codeOffset(v, p, iContinue);\n\n  switch( pDest->eDest ){\n    /* Store the result as data using a unique key.\n    */\n    case SRT_Table:\n    case SRT_EphemTab: {\n      int r1 = sqlite3GetTempReg(pParse);\n      int r2 = sqlite3GetTempReg(pParse);\n      testcase( pDest->eDest==SRT_Table );\n      testcase( pDest->eDest==SRT_EphemTab );\n      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);\n      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);\n      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);\n      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);\n      sqlite3ReleaseTempReg(pParse, r2);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n#ifndef SQLITE_OMIT_SUBQUERY\n    /* If we are creating a set for an \"expr IN (SELECT ...)\" construct,\n    ** then there should be a single item on the stack.  Write this\n    ** item into the set table with bogus data.\n    */\n    case SRT_Set: {\n      int r1;\n      assert( pIn->nSdst==1 );\n      p->affinity = \n         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);\n      r1 = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &p->affinity, 1);\n      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);\n      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);\n      sqlite3ReleaseTempReg(pParse, r1);\n      break;\n    }\n\n#if 0  /* Never occurs on an ORDER BY query */\n    /* If any row exist in the result set, record that fact and abort.\n    */\n    case SRT_Exists: {\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);\n      /* The LIMIT clause will terminate the loop for us */\n      break;\n    }\n#endif\n\n    /* If this is a scalar select that is part of an expression, then\n    ** store the results in the appropriate memory cell and break out\n    ** of the scan loop.\n    */\n    case SRT_Mem: {\n      assert( pIn->nSdst==1 );\n      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);\n      /* The LIMIT clause will jump out of the loop for us */\n      break;\n    }\n#endif /* #ifndef SQLITE_OMIT_SUBQUERY */\n\n    /* The results are stored in a sequence of registers\n    ** starting at pDest->iSdst.  Then the co-routine yields.\n    */\n    case SRT_Coroutine: {\n      if( pDest->iSdst==0 ){\n        pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);\n        pDest->nSdst = pIn->nSdst;\n      }\n      sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);\n      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);\n      break;\n    }\n\n    /* If none of the above, then the result destination must be\n    ** SRT_Output.  This routine is never called with any other\n    ** destination other than the ones handled above or SRT_Output.\n    **\n    ** For SRT_Output, results are stored in a sequence of registers.  \n    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to\n    ** return the next row of result.\n    */\n    default: {\n      assert( pDest->eDest==SRT_Output );\n      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);\n      sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);\n      break;\n    }\n  }\n\n  /* Jump to the end of the loop if the LIMIT is reached.\n  */\n  if( p->iLimit ){\n    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);\n  }\n\n  /* Generate the subroutine return\n  */\n  sqlite3VdbeResolveLabel(v, iContinue);\n  sqlite3VdbeAddOp1(v, OP_Return, regReturn);\n\n  return addr;\n}\n\n/*\n** Alternative compound select code generator for cases when there\n** is an ORDER BY clause.\n**\n** We assume a query of the following form:\n**\n**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>\n**\n** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea\n** is to code both <selectA> and <selectB> with the ORDER BY clause as\n** co-routines.  Then run the co-routines in parallel and merge the results\n** into the output.  In addition to the two coroutines (called selectA and\n** selectB) there are 7 subroutines:\n**\n**    outA:    Move the output of the selectA coroutine into the output\n**             of the compound query.\n**\n**    outB:    Move the output of the selectB coroutine into the output\n**             of the compound query.  (Only generated for UNION and\n**             UNION ALL.  EXCEPT and INSERTSECT never output a row that\n**             appears only in B.)\n**\n**    AltB:    Called when there is data from both coroutines and A<B.\n**\n**    AeqB:    Called when there is data from both coroutines and A==B.\n**\n**    AgtB:    Called when there is data from both coroutines and A>B.\n**\n**    EofA:    Called when data is exhausted from selectA.\n**\n**    EofB:    Called when data is exhausted from selectB.\n**\n** The implementation of the latter five subroutines depend on which \n** <operator> is used:\n**\n**\n**             UNION ALL         UNION            EXCEPT          INTERSECT\n**          -------------  -----------------  --------------  -----------------\n**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA\n**\n**   AeqB:   outA, nextA         nextA             nextA         outA, nextA\n**\n**   AgtB:   outB, nextB      outB, nextB          nextB            nextB\n**\n**   EofA:   outB, nextB      outB, nextB          halt             halt\n**\n**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt\n**\n** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA\n** causes an immediate jump to EofA and an EOF on B following nextB causes\n** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or\n** following nextX causes a jump to the end of the select processing.\n**\n** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled\n** within the output subroutine.  The regPrev register set holds the previously\n** output value.  A comparison is made against this value and the output\n** is skipped if the next results would be the same as the previous.\n**\n** The implementation plan is to implement the two coroutines and seven\n** subroutines first, then put the control logic at the bottom.  Like this:\n**\n**          goto Init\n**     coA: coroutine for left query (A)\n**     coB: coroutine for right query (B)\n**    outA: output one row of A\n**    outB: output one row of B (UNION and UNION ALL only)\n**    EofA: ...\n**    EofB: ...\n**    AltB: ...\n**    AeqB: ...\n**    AgtB: ...\n**    Init: initialize coroutine registers\n**          yield coA\n**          if eof(A) goto EofA\n**          yield coB\n**          if eof(B) goto EofB\n**    Cmpr: Compare A, B\n**          Jump AltB, AeqB, AgtB\n**     End: ...\n**\n** We call AltB, AeqB, AgtB, EofA, and EofB \"subroutines\" but they are not\n** actually called using Gosub and they do not Return.  EofA and EofB loop\n** until all data is exhausted then jump to the \"end\" labe.  AltB, AeqB,\n** and AgtB jump to either L2 or to one of EofA or EofB.\n*/\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\nstatic int multiSelectOrderBy(\n  Parse *pParse,        /* Parsing context */\n  Select *p,            /* The right-most of SELECTs to be coded */\n  SelectDest *pDest     /* What to do with query results */\n){\n  int i, j;             /* Loop counters */\n  Select *pPrior;       /* Another SELECT immediately to our left */\n  Vdbe *v;              /* Generate code to this VDBE */\n  SelectDest destA;     /* Destination for coroutine A */\n  SelectDest destB;     /* Destination for coroutine B */\n  int regAddrA;         /* Address register for select-A coroutine */\n  int regEofA;          /* Flag to indicate when select-A is complete */\n  int regAddrB;         /* Address register for select-B coroutine */\n  int regEofB;          /* Flag to indicate when select-B is complete */\n  int addrSelectA;      /* Address of the select-A coroutine */\n  int addrSelectB;      /* Address of the select-B coroutine */\n  int regOutA;          /* Address register for the output-A subroutine */\n  int regOutB;          /* Address register for the output-B subroutine */\n  int addrOutA;         /* Address of the output-A subroutine */\n  int addrOutB = 0;     /* Address of the output-B subroutine */\n  int addrEofA;         /* Address of the select-A-exhausted subroutine */\n  int addrEofB;         /* Address of the select-B-exhausted subroutine */\n  int addrAltB;         /* Address of the A<B subroutine */\n  int addrAeqB;         /* Address of the A==B subroutine */\n  int addrAgtB;         /* Address of the A>B subroutine */\n  int regLimitA;        /* Limit register for select-A */\n  int regLimitB;        /* Limit register for select-A */\n  int regPrev;          /* A range of registers to hold previous output */\n  int savedLimit;       /* Saved value of p->iLimit */\n  int savedOffset;      /* Saved value of p->iOffset */\n  int labelCmpr;        /* Label for the start of the merge algorithm */\n  int labelEnd;         /* Label for the end of the overall SELECT stmt */\n  int j1;               /* Jump instructions that get retargetted */\n  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */\n  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */\n  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */\n  sqlite3 *db;          /* Database connection */\n  ExprList *pOrderBy;   /* The ORDER BY clause */\n  int nOrderBy;         /* Number of terms in the ORDER BY clause */\n  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */\n#ifndef SQLITE_OMIT_EXPLAIN\n  int iSub1;            /* EQP id of left-hand query */\n  int iSub2;            /* EQP id of right-hand query */\n#endif\n\n  assert( p->pOrderBy!=0 );\n  assert( pKeyDup==0 ); /* \"Managed\" code needs this.  Ticket #3382. */\n  db = pParse->db;\n  v = pParse->pVdbe;\n  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */\n  labelEnd = sqlite3VdbeMakeLabel(v);\n  labelCmpr = sqlite3VdbeMakeLabel(v);\n\n\n  /* Patch up the ORDER BY clause\n  */\n  op = p->op;  \n  pPrior = p->pPrior;\n  assert( pPrior->pOrderBy==0 );\n  pOrderBy = p->pOrderBy;\n  assert( pOrderBy );\n  nOrderBy = pOrderBy->nExpr;\n\n  /* For operators other than UNION ALL we have to make sure that\n  ** the ORDER BY clause covers every term of the result set.  Add\n  ** terms to the ORDER BY clause as necessary.\n  */\n  if( op!=TK_ALL ){\n    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){\n      struct ExprList_item *pItem;\n      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){\n        assert( pItem->iOrderByCol>0 );\n        if( pItem->iOrderByCol==i ) break;\n      }\n      if( j==nOrderBy ){\n        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);\n        if( pNew==0 ) return SQLITE_NOMEM;\n        pNew->flags |= EP_IntValue;\n        pNew->u.iValue = i;\n        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);\n        if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;\n      }\n    }\n  }\n\n  /* Compute the comparison permutation and keyinfo that is used with\n  ** the permutation used to determine if the next\n  ** row of results comes from selectA or selectB.  Also add explicit\n  ** collations to the ORDER BY clause terms so that when the subqueries\n  ** to the right and the left are evaluated, they use the correct\n  ** collation.\n  */\n  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);\n  if( aPermute ){\n    struct ExprList_item *pItem;\n    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){\n      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );\n      aPermute[i] = pItem->iOrderByCol - 1;\n    }\n    pKeyMerge =\n      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));\n    if( pKeyMerge ){\n      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];\n      pKeyMerge->nField = (u16)nOrderBy;\n      pKeyMerge->enc = ENC(db);\n      for(i=0; i<nOrderBy; i++){\n        CollSeq *pColl;\n        Expr *pTerm = pOrderBy->a[i].pExpr;\n        if( pTerm->flags & EP_ExpCollate ){\n          pColl = pTerm->pColl;\n        }else{\n          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);\n          pTerm->flags |= EP_ExpCollate;\n          pTerm->pColl = pColl;\n        }\n        pKeyMerge->aColl[i] = pColl;\n        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;\n      }\n    }\n  }else{\n    pKeyMerge = 0;\n  }\n\n  /* Reattach the ORDER BY clause to the query.\n  */\n  p->pOrderBy = pOrderBy;\n  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);\n\n  /* Allocate a range of temporary registers and the KeyInfo needed\n  ** for the logic that removes duplicate result rows when the\n  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).\n  */\n  if( op==TK_ALL ){\n    regPrev = 0;\n  }else{\n    int nExpr = p->pEList->nExpr;\n    assert( nOrderBy>=nExpr || db->mallocFailed );\n    regPrev = sqlite3GetTempRange(pParse, nExpr+1);\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);\n    pKeyDup = sqlite3DbMallocZero(db,\n                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );\n    if( pKeyDup ){\n      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];\n      pKeyDup->nField = (u16)nExpr;\n      pKeyDup->enc = ENC(db);\n      for(i=0; i<nExpr; i++){\n        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);\n        pKeyDup->aSortOrder[i] = 0;\n      }\n    }\n  }\n \n  /* Separate the left and the right query from one another\n  */\n  p->pPrior = 0;\n  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, \"ORDER\");\n  if( pPrior->pPrior==0 ){\n    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, \"ORDER\");\n  }\n\n  /* Compute the limit registers */\n  computeLimitRegisters(pParse, p, labelEnd);\n  if( p->iLimit && op==TK_ALL ){\n    regLimitA = ++pParse->nMem;\n    regLimitB = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,\n                                  regLimitA);\n    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);\n  }else{\n    regLimitA = regLimitB = 0;\n  }\n  sqlite3ExprDelete(db, p->pLimit);\n  p->pLimit = 0;\n  sqlite3ExprDelete(db, p->pOffset);\n  p->pOffset = 0;\n\n  regAddrA = ++pParse->nMem;\n  regEofA = ++pParse->nMem;\n  regAddrB = ++pParse->nMem;\n  regEofB = ++pParse->nMem;\n  regOutA = ++pParse->nMem;\n  regOutB = ++pParse->nMem;\n  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);\n  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);\n\n  /* Jump past the various subroutines and coroutines to the main\n  ** merge loop\n  */\n  j1 = sqlite3VdbeAddOp0(v, OP_Goto);\n  addrSelectA = sqlite3VdbeCurrentAddr(v);\n\n\n  /* Generate a coroutine to evaluate the SELECT statement to the\n  ** left of the compound operator - the \"A\" select.\n  */\n  VdbeNoopComment((v, \"Begin coroutine for left SELECT\"));\n  pPrior->iLimit = regLimitA;\n  explainSetInteger(iSub1, pParse->iNextSelectId);\n  sqlite3Select(pParse, pPrior, &destA);\n  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);\n  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);\n  VdbeNoopComment((v, \"End coroutine for left SELECT\"));\n\n  /* Generate a coroutine to evaluate the SELECT statement on \n  ** the right - the \"B\" select\n  */\n  addrSelectB = sqlite3VdbeCurrentAddr(v);\n  VdbeNoopComment((v, \"Begin coroutine for right SELECT\"));\n  savedLimit = p->iLimit;\n  savedOffset = p->iOffset;\n  p->iLimit = regLimitB;\n  p->iOffset = 0;  \n  explainSetInteger(iSub2, pParse->iNextSelectId);\n  sqlite3Select(pParse, p, &destB);\n  p->iLimit = savedLimit;\n  p->iOffset = savedOffset;\n  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);\n  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);\n  VdbeNoopComment((v, \"End coroutine for right SELECT\"));\n\n  /* Generate a subroutine that outputs the current row of the A\n  ** select as the next output row of the compound select.\n  */\n  VdbeNoopComment((v, \"Output routine for A\"));\n  addrOutA = generateOutputSubroutine(pParse,\n                 p, &destA, pDest, regOutA,\n                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);\n  \n  /* Generate a subroutine that outputs the current row of the B\n  ** select as the next output row of the compound select.\n  */\n  if( op==TK_ALL || op==TK_UNION ){\n    VdbeNoopComment((v, \"Output routine for B\"));\n    addrOutB = generateOutputSubroutine(pParse,\n                 p, &destB, pDest, regOutB,\n                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);\n  }\n\n  /* Generate a subroutine to run when the results from select A\n  ** are exhausted and only data in select B remains.\n  */\n  VdbeNoopComment((v, \"eof-A subroutine\"));\n  if( op==TK_EXCEPT || op==TK_INTERSECT ){\n    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);\n  }else{  \n    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);\n    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);\n    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);\n    p->nSelectRow += pPrior->nSelectRow;\n  }\n\n  /* Generate a subroutine to run when the results from select B\n  ** are exhausted and only data in select A remains.\n  */\n  if( op==TK_INTERSECT ){\n    addrEofB = addrEofA;\n    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;\n  }else{  \n    VdbeNoopComment((v, \"eof-B subroutine\"));\n    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);\n    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);\n    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);\n  }\n\n  /* Generate code to handle the case of A<B\n  */\n  VdbeNoopComment((v, \"A-lt-B subroutine\"));\n  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);\n  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);\n  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);\n  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);\n\n  /* Generate code to handle the case of A==B\n  */\n  if( op==TK_ALL ){\n    addrAeqB = addrAltB;\n  }else if( op==TK_INTERSECT ){\n    addrAeqB = addrAltB;\n    addrAltB++;\n  }else{\n    VdbeNoopComment((v, \"A-eq-B subroutine\"));\n    addrAeqB =\n    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);\n    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);\n  }\n\n  /* Generate code to handle the case of A>B\n  */\n  VdbeNoopComment((v, \"A-gt-B subroutine\"));\n  addrAgtB = sqlite3VdbeCurrentAddr(v);\n  if( op==TK_ALL || op==TK_UNION ){\n    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);\n  }\n  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);\n  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);\n  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);\n\n  /* This code runs once to initialize everything.\n  */\n  sqlite3VdbeJumpHere(v, j1);\n  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);\n  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);\n  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);\n  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);\n  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);\n  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);\n\n  /* Implement the main merge loop\n  */\n  sqlite3VdbeResolveLabel(v, labelCmpr);\n  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);\n  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,\n                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);\n  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);\n\n  /* Release temporary registers\n  */\n  if( regPrev ){\n    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);\n  }\n\n  /* Jump to the this point in order to terminate the query.\n  */\n  sqlite3VdbeResolveLabel(v, labelEnd);\n\n  /* Set the number of output columns\n  */\n  if( pDest->eDest==SRT_Output ){\n    Select *pFirst = pPrior;\n    while( pFirst->pPrior ) pFirst = pFirst->pPrior;\n    generateColumnNames(pParse, 0, pFirst->pEList);\n  }\n\n  /* Reassembly the compound query so that it will be freed correctly\n  ** by the calling function */\n  if( p->pPrior ){\n    sqlite3SelectDelete(db, p->pPrior);\n  }\n  p->pPrior = pPrior;\n\n  /*** TBD:  Insert subroutine calls to close cursors on incomplete\n  **** subqueries ****/\n  explainComposite(pParse, p->op, iSub1, iSub2, 0);\n  return SQLITE_OK;\n}\n#endif\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n/* Forward Declarations */\nstatic void substExprList(sqlite3*, ExprList*, int, ExprList*);\nstatic void substSelect(sqlite3*, Select *, int, ExprList *);\n\n/*\n** Scan through the expression pExpr.  Replace every reference to\n** a column in table number iTable with a copy of the iColumn-th\n** entry in pEList.  (But leave references to the ROWID column \n** unchanged.)\n**\n** This routine is part of the flattening procedure.  A subquery\n** whose result set is defined by pEList appears as entry in the\n** FROM clause of a SELECT such that the VDBE cursor assigned to that\n** FORM clause entry is iTable.  This routine make the necessary \n** changes to pExpr so that it refers directly to the source table\n** of the subquery rather the result set of the subquery.\n*/\nstatic Expr *substExpr(\n  sqlite3 *db,        /* Report malloc errors to this connection */\n  Expr *pExpr,        /* Expr in which substitution occurs */\n  int iTable,         /* Table to be substituted */\n  ExprList *pEList    /* Substitute expressions */\n){\n  if( pExpr==0 ) return 0;\n  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){\n    if( pExpr->iColumn<0 ){\n      pExpr->op = TK_NULL;\n    }else{\n      Expr *pNew;\n      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );\n      assert( pExpr->pLeft==0 && pExpr->pRight==0 );\n      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);\n      if( pNew && pExpr->pColl ){\n        pNew->pColl = pExpr->pColl;\n      }\n      sqlite3ExprDelete(db, pExpr);\n      pExpr = pNew;\n    }\n  }else{\n    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);\n    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      substSelect(db, pExpr->x.pSelect, iTable, pEList);\n    }else{\n      substExprList(db, pExpr->x.pList, iTable, pEList);\n    }\n  }\n  return pExpr;\n}\nstatic void substExprList(\n  sqlite3 *db,         /* Report malloc errors here */\n  ExprList *pList,     /* List to scan and in which to make substitutes */\n  int iTable,          /* Table to be substituted */\n  ExprList *pEList     /* Substitute values */\n){\n  int i;\n  if( pList==0 ) return;\n  for(i=0; i<pList->nExpr; i++){\n    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);\n  }\n}\nstatic void substSelect(\n  sqlite3 *db,         /* Report malloc errors here */\n  Select *p,           /* SELECT statement in which to make substitutions */\n  int iTable,          /* Table to be replaced */\n  ExprList *pEList     /* Substitute values */\n){\n  SrcList *pSrc;\n  struct SrcList_item *pItem;\n  int i;\n  if( !p ) return;\n  substExprList(db, p->pEList, iTable, pEList);\n  substExprList(db, p->pGroupBy, iTable, pEList);\n  substExprList(db, p->pOrderBy, iTable, pEList);\n  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);\n  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);\n  substSelect(db, p->pPrior, iTable, pEList);\n  pSrc = p->pSrc;\n  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */\n  if( ALWAYS(pSrc) ){\n    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){\n      substSelect(db, pItem->pSelect, iTable, pEList);\n    }\n  }\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n/*\n** This routine attempts to flatten subqueries as a performance optimization.\n** This routine returns 1 if it makes changes and 0 if no flattening occurs.\n**\n** To understand the concept of flattening, consider the following\n** query:\n**\n**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5\n**\n** The default way of implementing this query is to execute the\n** subquery first and store the results in a temporary table, then\n** run the outer query on that temporary table.  This requires two\n** passes over the data.  Furthermore, because the temporary table\n** has no indices, the WHERE clause on the outer query cannot be\n** optimized.\n**\n** This routine attempts to rewrite queries such as the above into\n** a single flat select, like this:\n**\n**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5\n**\n** The code generated for this simpification gives the same result\n** but only has to scan the data once.  And because indices might \n** exist on the table t1, a complete scan of the data might be\n** avoided.\n**\n** Flattening is only attempted if all of the following are true:\n**\n**   (1)  The subquery and the outer query do not both use aggregates.\n**\n**   (2)  The subquery is not an aggregate or the outer query is not a join.\n**\n**   (3)  The subquery is not the right operand of a left outer join\n**        (Originally ticket #306.  Strengthened by ticket #3300)\n**\n**   (4)  The subquery is not DISTINCT.\n**\n**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT\n**        sub-queries that were excluded from this optimization. Restriction \n**        (4) has since been expanded to exclude all DISTINCT subqueries.\n**\n**   (6)  The subquery does not use aggregates or the outer query is not\n**        DISTINCT.\n**\n**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without\n**        A FROM clause, consider adding a FROM close with the special\n**        table sqlite_once that consists of a single row containing a\n**        single NULL.\n**\n**   (8)  The subquery does not use LIMIT or the outer query is not a join.\n**\n**   (9)  The subquery does not use LIMIT or the outer query does not use\n**        aggregates.\n**\n**  (10)  The subquery does not use aggregates or the outer query does not\n**        use LIMIT.\n**\n**  (11)  The subquery and the outer query do not both have ORDER BY clauses.\n**\n**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously\n**        a separate restriction deriving from ticket #350.\n**\n**  (13)  The subquery and outer query do not both use LIMIT.\n**\n**  (14)  The subquery does not use OFFSET.\n**\n**  (15)  The outer query is not part of a compound select or the\n**        subquery does not have a LIMIT clause.\n**        (See ticket #2339 and ticket [02a8e81d44]).\n**\n**  (16)  The outer query is not an aggregate or the subquery does\n**        not contain ORDER BY.  (Ticket #2942)  This used to not matter\n**        until we introduced the group_concat() function.  \n**\n**  (17)  The sub-query is not a compound select, or it is a UNION ALL \n**        compound clause made up entirely of non-aggregate queries, and \n**        the parent query:\n**\n**          * is not itself part of a compound select,\n**          * is not an aggregate or DISTINCT query, and\n**          * is not a join\n**\n**        The parent and sub-query may contain WHERE clauses. Subject to\n**        rules (11), (13) and (14), they may also contain ORDER BY,\n**        LIMIT and OFFSET clauses.  The subquery cannot use any compound\n**        operator other than UNION ALL because all the other compound\n**        operators have an implied DISTINCT which is disallowed by\n**        restriction (4).\n**\n**        Also, each component of the sub-query must return the same number\n**        of result columns. This is actually a requirement for any compound\n**        SELECT statement, but all the code here does is make sure that no\n**        such (illegal) sub-query is flattened. The caller will detect the\n**        syntax error and return a detailed message.\n**\n**  (18)  If the sub-query is a compound select, then all terms of the\n**        ORDER by clause of the parent must be simple references to \n**        columns of the sub-query.\n**\n**  (19)  The subquery does not use LIMIT or the outer query does not\n**        have a WHERE clause.\n**\n**  (20)  If the sub-query is a compound select, then it must not use\n**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint\n**        somewhat by saying that the terms of the ORDER BY clause must\n**        appear as unmodified result columns in the outer query.  But we\n**        have other optimizations in mind to deal with that case.\n**\n**  (21)  The subquery does not use LIMIT or the outer query is not\n**        DISTINCT.  (See ticket [752e1646fc]).\n**\n** In this routine, the \"p\" parameter is a pointer to the outer query.\n** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query\n** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.\n**\n** If flattening is not attempted, this routine is a no-op and returns 0.\n** If flattening is attempted this routine returns 1.\n**\n** All of the expression analysis must occur on both the outer query and\n** the subquery before this routine runs.\n*/\nstatic int flattenSubquery(\n  Parse *pParse,       /* Parsing context */\n  Select *p,           /* The parent or outer SELECT statement */\n  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */\n  int isAgg,           /* True if outer SELECT uses aggregate functions */\n  int subqueryIsAgg    /* True if the subquery uses aggregate functions */\n){\n  const char *zSavedAuthContext = pParse->zAuthContext;\n  Select *pParent;\n  Select *pSub;       /* The inner query or \"subquery\" */\n  Select *pSub1;      /* Pointer to the rightmost select in sub-query */\n  SrcList *pSrc;      /* The FROM clause of the outer query */\n  SrcList *pSubSrc;   /* The FROM clause of the subquery */\n  ExprList *pList;    /* The result set of the outer query */\n  int iParent;        /* VDBE cursor number of the pSub result set temp table */\n  int i;              /* Loop counter */\n  Expr *pWhere;                    /* The WHERE clause */\n  struct SrcList_item *pSubitem;   /* The subquery */\n  sqlite3 *db = pParse->db;\n\n  /* Check to see if flattening is permitted.  Return 0 if not.\n  */\n  assert( p!=0 );\n  assert( p->pPrior==0 );  /* Unable to flatten compound queries */\n  if( db->flags & SQLITE_QueryFlattener ) return 0;\n  pSrc = p->pSrc;\n  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );\n  pSubitem = &pSrc->a[iFrom];\n  iParent = pSubitem->iCursor;\n  pSub = pSubitem->pSelect;\n  assert( pSub!=0 );\n  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */\n  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */\n  pSubSrc = pSub->pSrc;\n  assert( pSubSrc );\n  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,\n  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET\n  ** because they could be computed at compile-time.  But when LIMIT and OFFSET\n  ** became arbitrary expressions, we were forced to add restrictions (13)\n  ** and (14). */\n  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */\n  if( pSub->pOffset ) return 0;                          /* Restriction (14) */\n  if( p->pRightmost && pSub->pLimit ){\n    return 0;                                            /* Restriction (15) */\n  }\n  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */\n  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */\n  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){\n     return 0;         /* Restrictions (8)(9) */\n  }\n  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){\n     return 0;         /* Restriction (6)  */\n  }\n  if( p->pOrderBy && pSub->pOrderBy ){\n     return 0;                                           /* Restriction (11) */\n  }\n  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */\n  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */\n  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){\n     return 0;         /* Restriction (21) */\n  }\n\n  /* OBSOLETE COMMENT 1:\n  ** Restriction 3:  If the subquery is a join, make sure the subquery is \n  ** not used as the right operand of an outer join.  Examples of why this\n  ** is not allowed:\n  **\n  **         t1 LEFT OUTER JOIN (t2 JOIN t3)\n  **\n  ** If we flatten the above, we would get\n  **\n  **         (t1 LEFT OUTER JOIN t2) JOIN t3\n  **\n  ** which is not at all the same thing.\n  **\n  ** OBSOLETE COMMENT 2:\n  ** Restriction 12:  If the subquery is the right operand of a left outer\n  ** join, make sure the subquery has no WHERE clause.\n  ** An examples of why this is not allowed:\n  **\n  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)\n  **\n  ** If we flatten the above, we would get\n  **\n  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0\n  **\n  ** But the t2.x>0 test will always fail on a NULL row of t2, which\n  ** effectively converts the OUTER JOIN into an INNER JOIN.\n  **\n  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:\n  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN\n  ** is fraught with danger.  Best to avoid the whole thing.  If the\n  ** subquery is the right term of a LEFT JOIN, then do not flatten.\n  */\n  if( (pSubitem->jointype & JT_OUTER)!=0 ){\n    return 0;\n  }\n\n  /* Restriction 17: If the sub-query is a compound SELECT, then it must\n  ** use only the UNION ALL operator. And none of the simple select queries\n  ** that make up the compound SELECT are allowed to be aggregate or distinct\n  ** queries.\n  */\n  if( pSub->pPrior ){\n    if( pSub->pOrderBy ){\n      return 0;  /* Restriction 20 */\n    }\n    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){\n      return 0;\n    }\n    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){\n      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );\n      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );\n      assert( pSub->pSrc!=0 );\n      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0\n       || (pSub1->pPrior && pSub1->op!=TK_ALL) \n       || pSub1->pSrc->nSrc<1\n       || pSub->pEList->nExpr!=pSub1->pEList->nExpr\n      ){\n        return 0;\n      }\n      testcase( pSub1->pSrc->nSrc>1 );\n    }\n\n    /* Restriction 18. */\n    if( p->pOrderBy ){\n      int ii;\n      for(ii=0; ii<p->pOrderBy->nExpr; ii++){\n        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;\n      }\n    }\n  }\n\n  /***** If we reach this point, flattening is permitted. *****/\n\n  /* Authorize the subquery */\n  pParse->zAuthContext = pSubitem->zName;\n  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);\n  testcase( i==SQLITE_DENY );\n  pParse->zAuthContext = zSavedAuthContext;\n\n  /* If the sub-query is a compound SELECT statement, then (by restrictions\n  ** 17 and 18 above) it must be a UNION ALL and the parent query must \n  ** be of the form:\n  **\n  **     SELECT <expr-list> FROM (<sub-query>) <where-clause> \n  **\n  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block\n  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or \n  ** OFFSET clauses and joins them to the left-hand-side of the original\n  ** using UNION ALL operators. In this case N is the number of simple\n  ** select statements in the compound sub-query.\n  **\n  ** Example:\n  **\n  **     SELECT a+1 FROM (\n  **        SELECT x FROM tab\n  **        UNION ALL\n  **        SELECT y FROM tab\n  **        UNION ALL\n  **        SELECT abs(z*2) FROM tab2\n  **     ) WHERE a!=5 ORDER BY 1\n  **\n  ** Transformed into:\n  **\n  **     SELECT x+1 FROM tab WHERE x+1!=5\n  **     UNION ALL\n  **     SELECT y+1 FROM tab WHERE y+1!=5\n  **     UNION ALL\n  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5\n  **     ORDER BY 1\n  **\n  ** We call this the \"compound-subquery flattening\".\n  */\n  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){\n    Select *pNew;\n    ExprList *pOrderBy = p->pOrderBy;\n    Expr *pLimit = p->pLimit;\n    Select *pPrior = p->pPrior;\n    p->pOrderBy = 0;\n    p->pSrc = 0;\n    p->pPrior = 0;\n    p->pLimit = 0;\n    pNew = sqlite3SelectDup(db, p, 0);\n    p->pLimit = pLimit;\n    p->pOrderBy = pOrderBy;\n    p->pSrc = pSrc;\n    p->op = TK_ALL;\n    p->pRightmost = 0;\n    if( pNew==0 ){\n      pNew = pPrior;\n    }else{\n      pNew->pPrior = pPrior;\n      pNew->pRightmost = 0;\n    }\n    p->pPrior = pNew;\n    if( db->mallocFailed ) return 1;\n  }\n\n  /* Begin flattening the iFrom-th entry of the FROM clause \n  ** in the outer query.\n  */\n  pSub = pSub1 = pSubitem->pSelect;\n\n  /* Delete the transient table structure associated with the\n  ** subquery\n  */\n  sqlite3DbFree(db, pSubitem->zDatabase);\n  sqlite3DbFree(db, pSubitem->zName);\n  sqlite3DbFree(db, pSubitem->zAlias);\n  pSubitem->zDatabase = 0;\n  pSubitem->zName = 0;\n  pSubitem->zAlias = 0;\n  pSubitem->pSelect = 0;\n\n  /* Defer deleting the Table object associated with the\n  ** subquery until code generation is\n  ** complete, since there may still exist Expr.pTab entries that\n  ** refer to the subquery even after flattening.  Ticket #3346.\n  **\n  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.\n  */\n  if( ALWAYS(pSubitem->pTab!=0) ){\n    Table *pTabToDel = pSubitem->pTab;\n    if( pTabToDel->nRef==1 ){\n      Parse *pToplevel = sqlite3ParseToplevel(pParse);\n      pTabToDel->pNextZombie = pToplevel->pZombieTab;\n      pToplevel->pZombieTab = pTabToDel;\n    }else{\n      pTabToDel->nRef--;\n    }\n    pSubitem->pTab = 0;\n  }\n\n  /* The following loop runs once for each term in a compound-subquery\n  ** flattening (as described above).  If we are doing a different kind\n  ** of flattening - a flattening other than a compound-subquery flattening -\n  ** then this loop only runs once.\n  **\n  ** This loop moves all of the FROM elements of the subquery into the\n  ** the FROM clause of the outer query.  Before doing this, remember\n  ** the cursor number for the original outer query FROM element in\n  ** iParent.  The iParent cursor will never be used.  Subsequent code\n  ** will scan expressions looking for iParent references and replace\n  ** those references with expressions that resolve to the subquery FROM\n  ** elements we are now copying in.\n  */\n  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){\n    int nSubSrc;\n    u8 jointype = 0;\n    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */\n    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */\n    pSrc = pParent->pSrc;     /* FROM clause of the outer query */\n\n    if( pSrc ){\n      assert( pParent==p );  /* First time through the loop */\n      jointype = pSubitem->jointype;\n    }else{\n      assert( pParent!=p );  /* 2nd and subsequent times through the loop */\n      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);\n      if( pSrc==0 ){\n        assert( db->mallocFailed );\n        break;\n      }\n    }\n\n    /* The subquery uses a single slot of the FROM clause of the outer\n    ** query.  If the subquery has more than one element in its FROM clause,\n    ** then expand the outer query to make space for it to hold all elements\n    ** of the subquery.\n    **\n    ** Example:\n    **\n    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;\n    **\n    ** The outer query has 3 slots in its FROM clause.  One slot of the\n    ** outer query (the middle slot) is used by the subquery.  The next\n    ** block of code will expand the out query to 4 slots.  The middle\n    ** slot is expanded to two slots in order to make space for the\n    ** two elements in the FROM clause of the subquery.\n    */\n    if( nSubSrc>1 ){\n      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);\n      if( db->mallocFailed ){\n        break;\n      }\n    }\n\n    /* Transfer the FROM clause terms from the subquery into the\n    ** outer query.\n    */\n    for(i=0; i<nSubSrc; i++){\n      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);\n      pSrc->a[i+iFrom] = pSubSrc->a[i];\n      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));\n    }\n    pSrc->a[iFrom].jointype = jointype;\n  \n    /* Now begin substituting subquery result set expressions for \n    ** references to the iParent in the outer query.\n    ** \n    ** Example:\n    **\n    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;\n    **   \\                     \\_____________ subquery __________/          /\n    **    \\_____________________ outer query ______________________________/\n    **\n    ** We look at every expression in the outer query and every place we see\n    ** \"a\" we substitute \"x*3\" and every place we see \"b\" we substitute \"y+10\".\n    */\n    pList = pParent->pEList;\n    for(i=0; i<pList->nExpr; i++){\n      if( pList->a[i].zName==0 ){\n        const char *zSpan = pList->a[i].zSpan;\n        if( ALWAYS(zSpan) ){\n          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);\n        }\n      }\n    }\n    substExprList(db, pParent->pEList, iParent, pSub->pEList);\n    if( isAgg ){\n      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);\n      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);\n    }\n    if( pSub->pOrderBy ){\n      assert( pParent->pOrderBy==0 );\n      pParent->pOrderBy = pSub->pOrderBy;\n      pSub->pOrderBy = 0;\n    }else if( pParent->pOrderBy ){\n      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);\n    }\n    if( pSub->pWhere ){\n      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);\n    }else{\n      pWhere = 0;\n    }\n    if( subqueryIsAgg ){\n      assert( pParent->pHaving==0 );\n      pParent->pHaving = pParent->pWhere;\n      pParent->pWhere = pWhere;\n      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);\n      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, \n                                  sqlite3ExprDup(db, pSub->pHaving, 0));\n      assert( pParent->pGroupBy==0 );\n      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);\n    }else{\n      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);\n      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);\n    }\n  \n    /* The flattened query is distinct if either the inner or the\n    ** outer query is distinct. \n    */\n    pParent->selFlags |= pSub->selFlags & SF_Distinct;\n  \n    /*\n    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;\n    **\n    ** One is tempted to try to add a and b to combine the limits.  But this\n    ** does not work if either limit is negative.\n    */\n    if( pSub->pLimit ){\n      pParent->pLimit = pSub->pLimit;\n      pSub->pLimit = 0;\n    }\n  }\n\n  /* Finially, delete what is left of the subquery and return\n  ** success.\n  */\n  sqlite3SelectDelete(db, pSub1);\n\n  return 1;\n}\n#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */\n\n/*\n** Analyze the SELECT statement passed as an argument to see if it\n** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if \n** it is, or 0 otherwise. At present, a query is considered to be\n** a min()/max() query if:\n**\n**   1. There is a single object in the FROM clause.\n**\n**   2. There is a single expression in the result set, and it is\n**      either min(x) or max(x), where x is a column reference.\n*/\nstatic u8 minMaxQuery(Select *p){\n  Expr *pExpr;\n  ExprList *pEList = p->pEList;\n\n  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;\n  pExpr = pEList->a[0].pExpr;\n  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;\n  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;\n  pEList = pExpr->x.pList;\n  if( pEList==0 || pEList->nExpr!=1 ) return 0;\n  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;\n  assert( !ExprHasProperty(pExpr, EP_IntValue) );\n  if( sqlite3StrICmp(pExpr->u.zToken,\"min\")==0 ){\n    return WHERE_ORDERBY_MIN;\n  }else if( sqlite3StrICmp(pExpr->u.zToken,\"max\")==0 ){\n    return WHERE_ORDERBY_MAX;\n  }\n  return WHERE_ORDERBY_NORMAL;\n}\n\n/*\n** The select statement passed as the first argument is an aggregate query.\n** The second argment is the associated aggregate-info object. This \n** function tests if the SELECT is of the form:\n**\n**   SELECT count(*) FROM <tbl>\n**\n** where table is a database table, not a sub-select or view. If the query\n** does match this pattern, then a pointer to the Table object representing\n** <tbl> is returned. Otherwise, 0 is returned.\n*/\nstatic Table *isSimpleCount(Select *p, AggInfo *pAggInfo){\n  Table *pTab;\n  Expr *pExpr;\n\n  assert( !p->pGroupBy );\n\n  if( p->pWhere || p->pEList->nExpr!=1 \n   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect\n  ){\n    return 0;\n  }\n  pTab = p->pSrc->a[0].pTab;\n  pExpr = p->pEList->a[0].pExpr;\n  assert( pTab && !pTab->pSelect && pExpr );\n\n  if( IsVirtual(pTab) ) return 0;\n  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;\n  if( NEVER(pAggInfo->nFunc==0) ) return 0;\n  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;\n  if( pExpr->flags&EP_Distinct ) return 0;\n\n  return pTab;\n}\n\n/*\n** If the source-list item passed as an argument was augmented with an\n** INDEXED BY clause, then try to locate the specified index. If there\n** was such a clause and the named index cannot be found, return \n** SQLITE_ERROR and leave an error in pParse. Otherwise, populate \n** pFrom->pIndex and return SQLITE_OK.\n*/\nSQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){\n  if( pFrom->pTab && pFrom->zIndex ){\n    Table *pTab = pFrom->pTab;\n    char *zIndex = pFrom->zIndex;\n    Index *pIdx;\n    for(pIdx=pTab->pIndex; \n        pIdx && sqlite3StrICmp(pIdx->zName, zIndex); \n        pIdx=pIdx->pNext\n    );\n    if( !pIdx ){\n      sqlite3ErrorMsg(pParse, \"no such index: %s\", zIndex, 0);\n      pParse->checkSchema = 1;\n      return SQLITE_ERROR;\n    }\n    pFrom->pIndex = pIdx;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This routine is a Walker callback for \"expanding\" a SELECT statement.\n** \"Expanding\" means to do the following:\n**\n**    (1)  Make sure VDBE cursor numbers have been assigned to every\n**         element of the FROM clause.\n**\n**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that \n**         defines FROM clause.  When views appear in the FROM clause,\n**         fill pTabList->a[].pSelect with a copy of the SELECT statement\n**         that implements the view.  A copy is made of the view's SELECT\n**         statement so that we can freely modify or delete that statement\n**         without worrying about messing up the presistent representation\n**         of the view.\n**\n**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword\n**         on joins and the ON and USING clause of joins.\n**\n**    (4)  Scan the list of columns in the result set (pEList) looking\n**         for instances of the \"*\" operator or the TABLE.* operator.\n**         If found, expand each \"*\" to be every column in every table\n**         and TABLE.* to be every column in TABLE.\n**\n*/\nstatic int selectExpander(Walker *pWalker, Select *p){\n  Parse *pParse = pWalker->pParse;\n  int i, j, k;\n  SrcList *pTabList;\n  ExprList *pEList;\n  struct SrcList_item *pFrom;\n  sqlite3 *db = pParse->db;\n\n  if( db->mallocFailed  ){\n    return WRC_Abort;\n  }\n  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){\n    return WRC_Prune;\n  }\n  p->selFlags |= SF_Expanded;\n  pTabList = p->pSrc;\n  pEList = p->pEList;\n\n  /* Make sure cursor numbers have been assigned to all entries in\n  ** the FROM clause of the SELECT statement.\n  */\n  sqlite3SrcListAssignCursors(pParse, pTabList);\n\n  /* Look up every table named in the FROM clause of the select.  If\n  ** an entry of the FROM clause is a subquery instead of a table or view,\n  ** then create a transient table structure to describe the subquery.\n  */\n  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n    Table *pTab;\n    if( pFrom->pTab!=0 ){\n      /* This statement has already been prepared.  There is no need\n      ** to go further. */\n      assert( i==0 );\n      return WRC_Prune;\n    }\n    if( pFrom->zName==0 ){\n#ifndef SQLITE_OMIT_SUBQUERY\n      Select *pSel = pFrom->pSelect;\n      /* A sub-query in the FROM clause of a SELECT */\n      assert( pSel!=0 );\n      assert( pFrom->pTab==0 );\n      sqlite3WalkSelect(pWalker, pSel);\n      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));\n      if( pTab==0 ) return WRC_Abort;\n      pTab->nRef = 1;\n      pTab->zName = sqlite3MPrintf(db, \"sqlite_subquery_%p_\", (void*)pTab);\n      while( pSel->pPrior ){ pSel = pSel->pPrior; }\n      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);\n      pTab->iPKey = -1;\n      pTab->nRowEst = 1000000;\n      pTab->tabFlags |= TF_Ephemeral;\n#endif\n    }else{\n      /* An ordinary table or view name in the FROM clause */\n      assert( pFrom->pTab==0 );\n      pFrom->pTab = pTab = \n        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);\n      if( pTab==0 ) return WRC_Abort;\n      pTab->nRef++;\n#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)\n      if( pTab->pSelect || IsVirtual(pTab) ){\n        /* We reach here if the named table is a really a view */\n        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;\n        assert( pFrom->pSelect==0 );\n        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);\n        sqlite3WalkSelect(pWalker, pFrom->pSelect);\n      }\n#endif\n    }\n\n    /* Locate the index named by the INDEXED BY clause, if any. */\n    if( sqlite3IndexedByLookup(pParse, pFrom) ){\n      return WRC_Abort;\n    }\n  }\n\n  /* Process NATURAL keywords, and ON and USING clauses of joins.\n  */\n  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){\n    return WRC_Abort;\n  }\n\n  /* For every \"*\" that occurs in the column list, insert the names of\n  ** all columns in all tables.  And for every TABLE.* insert the names\n  ** of all columns in TABLE.  The parser inserted a special expression\n  ** with the TK_ALL operator for each \"*\" that it found in the column list.\n  ** The following code just has to locate the TK_ALL expressions and expand\n  ** each one to the list of all columns in all tables.\n  **\n  ** The first loop just checks to see if there are any \"*\" operators\n  ** that need expanding.\n  */\n  for(k=0; k<pEList->nExpr; k++){\n    Expr *pE = pEList->a[k].pExpr;\n    if( pE->op==TK_ALL ) break;\n    assert( pE->op!=TK_DOT || pE->pRight!=0 );\n    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );\n    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;\n  }\n  if( k<pEList->nExpr ){\n    /*\n    ** If we get here it means the result set contains one or more \"*\"\n    ** operators that need to be expanded.  Loop through each expression\n    ** in the result set and expand them one by one.\n    */\n    struct ExprList_item *a = pEList->a;\n    ExprList *pNew = 0;\n    int flags = pParse->db->flags;\n    int longNames = (flags & SQLITE_FullColNames)!=0\n                      && (flags & SQLITE_ShortColNames)==0;\n\n    for(k=0; k<pEList->nExpr; k++){\n      Expr *pE = a[k].pExpr;\n      assert( pE->op!=TK_DOT || pE->pRight!=0 );\n      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){\n        /* This particular expression does not need to be expanded.\n        */\n        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);\n        if( pNew ){\n          pNew->a[pNew->nExpr-1].zName = a[k].zName;\n          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;\n          a[k].zName = 0;\n          a[k].zSpan = 0;\n        }\n        a[k].pExpr = 0;\n      }else{\n        /* This expression is a \"*\" or a \"TABLE.*\" and needs to be\n        ** expanded. */\n        int tableSeen = 0;      /* Set to 1 when TABLE matches */\n        char *zTName;            /* text of name of TABLE */\n        if( pE->op==TK_DOT ){\n          assert( pE->pLeft!=0 );\n          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );\n          zTName = pE->pLeft->u.zToken;\n        }else{\n          zTName = 0;\n        }\n        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n          Table *pTab = pFrom->pTab;\n          char *zTabName = pFrom->zAlias;\n          if( zTabName==0 ){\n            zTabName = pTab->zName;\n          }\n          if( db->mallocFailed ) break;\n          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){\n            continue;\n          }\n          tableSeen = 1;\n          for(j=0; j<pTab->nCol; j++){\n            Expr *pExpr, *pRight;\n            char *zName = pTab->aCol[j].zName;\n            char *zColname;  /* The computed column name */\n            char *zToFree;   /* Malloced string that needs to be freed */\n            Token sColname;  /* Computed column name as a token */\n\n            /* If a column is marked as 'hidden' (currently only possible\n            ** for virtual tables), do not include it in the expanded\n            ** result-set list.\n            */\n            if( IsHiddenColumn(&pTab->aCol[j]) ){\n              assert(IsVirtual(pTab));\n              continue;\n            }\n\n            if( i>0 && zTName==0 ){\n              if( (pFrom->jointype & JT_NATURAL)!=0\n                && tableAndColumnIndex(pTabList, i, zName, 0, 0)\n              ){\n                /* In a NATURAL join, omit the join columns from the \n                ** table to the right of the join */\n                continue;\n              }\n              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){\n                /* In a join with a USING clause, omit columns in the\n                ** using clause from the table on the right. */\n                continue;\n              }\n            }\n            pRight = sqlite3Expr(db, TK_ID, zName);\n            zColname = zName;\n            zToFree = 0;\n            if( longNames || pTabList->nSrc>1 ){\n              Expr *pLeft;\n              pLeft = sqlite3Expr(db, TK_ID, zTabName);\n              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);\n              if( longNames ){\n                zColname = sqlite3MPrintf(db, \"%s.%s\", zTabName, zName);\n                zToFree = zColname;\n              }\n            }else{\n              pExpr = pRight;\n            }\n            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);\n            sColname.z = zColname;\n            sColname.n = sqlite3Strlen30(zColname);\n            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);\n            sqlite3DbFree(db, zToFree);\n          }\n        }\n        if( !tableSeen ){\n          if( zTName ){\n            sqlite3ErrorMsg(pParse, \"no such table: %s\", zTName);\n          }else{\n            sqlite3ErrorMsg(pParse, \"no tables specified\");\n          }\n        }\n      }\n    }\n    sqlite3ExprListDelete(db, pEList);\n    p->pEList = pNew;\n  }\n#if SQLITE_MAX_COLUMN\n  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){\n    sqlite3ErrorMsg(pParse, \"too many columns in result set\");\n  }\n#endif\n  return WRC_Continue;\n}\n\n/*\n** No-op routine for the parse-tree walker.\n**\n** When this routine is the Walker.xExprCallback then expression trees\n** are walked without any actions being taken at each node.  Presumably,\n** when this routine is used for Walker.xExprCallback then \n** Walker.xSelectCallback is set to do something useful for every \n** subquery in the parser tree.\n*/\nstatic int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){\n  UNUSED_PARAMETER2(NotUsed, NotUsed2);\n  return WRC_Continue;\n}\n\n/*\n** This routine \"expands\" a SELECT statement and all of its subqueries.\n** For additional information on what it means to \"expand\" a SELECT\n** statement, see the comment on the selectExpand worker callback above.\n**\n** Expanding a SELECT statement is the first step in processing a\n** SELECT statement.  The SELECT statement must be expanded before\n** name resolution is performed.\n**\n** If anything goes wrong, an error message is written into pParse.\n** The calling function can detect the problem by looking at pParse->nErr\n** and/or pParse->db->mallocFailed.\n*/\nstatic void sqlite3SelectExpand(Parse *pParse, Select *pSelect){\n  Walker w;\n  w.xSelectCallback = selectExpander;\n  w.xExprCallback = exprWalkNoop;\n  w.pParse = pParse;\n  sqlite3WalkSelect(&w, pSelect);\n}\n\n\n#ifndef SQLITE_OMIT_SUBQUERY\n/*\n** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()\n** interface.\n**\n** For each FROM-clause subquery, add Column.zType and Column.zColl\n** information to the Table structure that represents the result set\n** of that subquery.\n**\n** The Table structure that represents the result set was constructed\n** by selectExpander() but the type and collation information was omitted\n** at that point because identifiers had not yet been resolved.  This\n** routine is called after identifier resolution.\n*/\nstatic int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){\n  Parse *pParse;\n  int i;\n  SrcList *pTabList;\n  struct SrcList_item *pFrom;\n\n  assert( p->selFlags & SF_Resolved );\n  if( (p->selFlags & SF_HasTypeInfo)==0 ){\n    p->selFlags |= SF_HasTypeInfo;\n    pParse = pWalker->pParse;\n    pTabList = p->pSrc;\n    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){\n      Table *pTab = pFrom->pTab;\n      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){\n        /* A sub-query in the FROM clause of a SELECT */\n        Select *pSel = pFrom->pSelect;\n        assert( pSel );\n        while( pSel->pPrior ) pSel = pSel->pPrior;\n        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);\n      }\n    }\n  }\n  return WRC_Continue;\n}\n#endif\n\n\n/*\n** This routine adds datatype and collating sequence information to\n** the Table structures of all FROM-clause subqueries in a\n** SELECT statement.\n**\n** Use this routine after name resolution.\n*/\nstatic void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){\n#ifndef SQLITE_OMIT_SUBQUERY\n  Walker w;\n  w.xSelectCallback = selectAddSubqueryTypeInfo;\n  w.xExprCallback = exprWalkNoop;\n  w.pParse = pParse;\n  sqlite3WalkSelect(&w, pSelect);\n#endif\n}\n\n\n/*\n** This routine sets up a SELECT statement for processing.  The\n** following is accomplished:\n**\n**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.\n**     *  Ephemeral Table objects are created for all FROM-clause subqueries.\n**     *  ON and USING clauses are shifted into WHERE statements\n**     *  Wildcards \"*\" and \"TABLE.*\" in result sets are expanded.\n**     *  Identifiers in expression are matched to tables.\n**\n** This routine acts recursively on all subqueries within the SELECT.\n*/\nSQLITE_PRIVATE void sqlite3SelectPrep(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  NameContext *pOuterNC  /* Name context for container */\n){\n  sqlite3 *db;\n  if( NEVER(p==0) ) return;\n  db = pParse->db;\n  if( p->selFlags & SF_HasTypeInfo ) return;\n  sqlite3SelectExpand(pParse, p);\n  if( pParse->nErr || db->mallocFailed ) return;\n  sqlite3ResolveSelectNames(pParse, p, pOuterNC);\n  if( pParse->nErr || db->mallocFailed ) return;\n  sqlite3SelectAddTypeInfo(pParse, p);\n}\n\n/*\n** Reset the aggregate accumulator.\n**\n** The aggregate accumulator is a set of memory cells that hold\n** intermediate results while calculating an aggregate.  This\n** routine generates code that stores NULLs in all of those memory\n** cells.\n*/\nstatic void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  struct AggInfo_func *pFunc;\n  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){\n    return;\n  }\n  for(i=0; i<pAggInfo->nColumn; i++){\n    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);\n  }\n  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){\n    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);\n    if( pFunc->iDistinct>=0 ){\n      Expr *pE = pFunc->pExpr;\n      assert( !ExprHasProperty(pE, EP_xIsSelect) );\n      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){\n        sqlite3ErrorMsg(pParse, \"DISTINCT aggregates must have exactly one \"\n           \"argument\");\n        pFunc->iDistinct = -1;\n      }else{\n        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);\n        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,\n                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);\n      }\n    }\n  }\n}\n\n/*\n** Invoke the OP_AggFinalize opcode for every aggregate function\n** in the AggInfo structure.\n*/\nstatic void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  struct AggInfo_func *pF;\n  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){\n    ExprList *pList = pF->pExpr->x.pList;\n    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );\n    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,\n                      (void*)pF->pFunc, P4_FUNCDEF);\n  }\n}\n\n/*\n** Update the accumulator memory cells for an aggregate based on\n** the current cursor position.\n*/\nstatic void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  int regHit = 0;\n  int addrHitTest = 0;\n  struct AggInfo_func *pF;\n  struct AggInfo_col *pC;\n\n  pAggInfo->directMode = 1;\n  sqlite3ExprCacheClear(pParse);\n  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){\n    int nArg;\n    int addrNext = 0;\n    int regAgg;\n    ExprList *pList = pF->pExpr->x.pList;\n    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );\n    if( pList ){\n      nArg = pList->nExpr;\n      regAgg = sqlite3GetTempRange(pParse, nArg);\n      sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);\n    }else{\n      nArg = 0;\n      regAgg = 0;\n    }\n    if( pF->iDistinct>=0 ){\n      addrNext = sqlite3VdbeMakeLabel(v);\n      assert( nArg==1 );\n      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);\n    }\n    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){\n      CollSeq *pColl = 0;\n      struct ExprList_item *pItem;\n      int j;\n      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */\n      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){\n        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);\n      }\n      if( !pColl ){\n        pColl = pParse->db->pDfltColl;\n      }\n      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;\n      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);\n    }\n    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,\n                      (void*)pF->pFunc, P4_FUNCDEF);\n    sqlite3VdbeChangeP5(v, (u8)nArg);\n    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);\n    sqlite3ReleaseTempRange(pParse, regAgg, nArg);\n    if( addrNext ){\n      sqlite3VdbeResolveLabel(v, addrNext);\n      sqlite3ExprCacheClear(pParse);\n    }\n  }\n\n  /* Before populating the accumulator registers, clear the column cache.\n  ** Otherwise, if any of the required column values are already present \n  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value\n  ** to pC->iMem. But by the time the value is used, the original register\n  ** may have been used, invalidating the underlying buffer holding the\n  ** text or blob value. See ticket [883034dcb5].\n  **\n  ** Another solution would be to change the OP_SCopy used to copy cached\n  ** values to an OP_Copy.\n  */\n  if( regHit ){\n    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);\n  }\n  sqlite3ExprCacheClear(pParse);\n  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){\n    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);\n  }\n  pAggInfo->directMode = 0;\n  sqlite3ExprCacheClear(pParse);\n  if( addrHitTest ){\n    sqlite3VdbeJumpHere(v, addrHitTest);\n  }\n}\n\n/*\n** Add a single OP_Explain instruction to the VDBE to explain a simple\n** count(*) query (\"SELECT count(*) FROM pTab\").\n*/\n#ifndef SQLITE_OMIT_EXPLAIN\nstatic void explainSimpleCount(\n  Parse *pParse,                  /* Parse context */\n  Table *pTab,                    /* Table being queried */\n  Index *pIdx                     /* Index used to optimize scan, or NULL */\n){\n  if( pParse->explain==2 ){\n    char *zEqp = sqlite3MPrintf(pParse->db, \"SCAN TABLE %s %s%s(~%d rows)\",\n        pTab->zName, \n        pIdx ? \"USING COVERING INDEX \" : \"\",\n        pIdx ? pIdx->zName : \"\",\n        pTab->nRowEst\n    );\n    sqlite3VdbeAddOp4(\n        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC\n    );\n  }\n}\n#else\n# define explainSimpleCount(a,b,c)\n#endif\n\n/*\n** Generate code for the SELECT statement given in the p argument.  \n**\n** The results are distributed in various ways depending on the\n** contents of the SelectDest structure pointed to by argument pDest\n** as follows:\n**\n**     pDest->eDest    Result\n**     ------------    -------------------------------------------\n**     SRT_Output      Generate a row of output (using the OP_ResultRow\n**                     opcode) for each row in the result set.\n**\n**     SRT_Mem         Only valid if the result is a single column.\n**                     Store the first column of the first result row\n**                     in register pDest->iSDParm then abandon the rest\n**                     of the query.  This destination implies \"LIMIT 1\".\n**\n**     SRT_Set         The result must be a single column.  Store each\n**                     row of result as the key in table pDest->iSDParm. \n**                     Apply the affinity pDest->affSdst before storing\n**                     results.  Used to implement \"IN (SELECT ...)\".\n**\n**     SRT_Union       Store results as a key in a temporary table \n**                     identified by pDest->iSDParm.\n**\n**     SRT_Except      Remove results from the temporary table pDest->iSDParm.\n**\n**     SRT_Table       Store results in temporary table pDest->iSDParm.\n**                     This is like SRT_EphemTab except that the table\n**                     is assumed to already be open.\n**\n**     SRT_EphemTab    Create an temporary table pDest->iSDParm and store\n**                     the result there. The cursor is left open after\n**                     returning.  This is like SRT_Table except that\n**                     this destination uses OP_OpenEphemeral to create\n**                     the table first.\n**\n**     SRT_Coroutine   Generate a co-routine that returns a new row of\n**                     results each time it is invoked.  The entry point\n**                     of the co-routine is stored in register pDest->iSDParm.\n**\n**     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result\n**                     set is not empty.\n**\n**     SRT_Discard     Throw the results away.  This is used by SELECT\n**                     statements within triggers whose only purpose is\n**                     the side-effects of functions.\n**\n** This routine returns the number of errors.  If any errors are\n** encountered, then an appropriate error message is left in\n** pParse->zErrMsg.\n**\n** This routine does NOT free the Select structure passed in.  The\n** calling function needs to do that.\n*/\nSQLITE_PRIVATE int sqlite3Select(\n  Parse *pParse,         /* The parser context */\n  Select *p,             /* The SELECT statement being coded. */\n  SelectDest *pDest      /* What to do with the query results */\n){\n  int i, j;              /* Loop counters */\n  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */\n  Vdbe *v;               /* The virtual machine under construction */\n  int isAgg;             /* True for select lists like \"count(*)\" */\n  ExprList *pEList;      /* List of columns to extract. */\n  SrcList *pTabList;     /* List of tables to select from */\n  Expr *pWhere;          /* The WHERE clause.  May be NULL */\n  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */\n  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */\n  Expr *pHaving;         /* The HAVING clause.  May be NULL */\n  int isDistinct;        /* True if the DISTINCT keyword is present */\n  int distinct;          /* Table to use for the distinct set */\n  int rc = 1;            /* Value to return from this function */\n  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */\n  int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */\n  AggInfo sAggInfo;      /* Information used by aggregate queries */\n  int iEnd;              /* Address of the end of the query */\n  sqlite3 *db;           /* The database connection */\n\n#ifndef SQLITE_OMIT_EXPLAIN\n  int iRestoreSelectId = pParse->iSelectId;\n  pParse->iSelectId = pParse->iNextSelectId++;\n#endif\n\n  db = pParse->db;\n  if( p==0 || db->mallocFailed || pParse->nErr ){\n    return 1;\n  }\n  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;\n  memset(&sAggInfo, 0, sizeof(sAggInfo));\n\n  if( IgnorableOrderby(pDest) ){\n    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || \n           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);\n    /* If ORDER BY makes no difference in the output then neither does\n    ** DISTINCT so it can be removed too. */\n    sqlite3ExprListDelete(db, p->pOrderBy);\n    p->pOrderBy = 0;\n    p->selFlags &= ~SF_Distinct;\n  }\n  sqlite3SelectPrep(pParse, p, 0);\n  pOrderBy = p->pOrderBy;\n  pTabList = p->pSrc;\n  pEList = p->pEList;\n  if( pParse->nErr || db->mallocFailed ){\n    goto select_end;\n  }\n  isAgg = (p->selFlags & SF_Aggregate)!=0;\n  assert( pEList!=0 );\n\n  /* Begin generating code.\n  */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) goto select_end;\n\n  /* If writing to memory or generating a set\n  ** only a single column may be output.\n  */\n#ifndef SQLITE_OMIT_SUBQUERY\n  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){\n    goto select_end;\n  }\n#endif\n\n  /* Generate code for all sub-queries in the FROM clause\n  */\n#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)\n  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){\n    struct SrcList_item *pItem = &pTabList->a[i];\n    SelectDest dest;\n    Select *pSub = pItem->pSelect;\n    int isAggSub;\n\n    if( pSub==0 ) continue;\n    if( pItem->addrFillSub ){\n      sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);\n      continue;\n    }\n\n    /* Increment Parse.nHeight by the height of the largest expression\n    ** tree refered to by this, the parent select. The child select\n    ** may contain expression trees of at most\n    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit\n    ** more conservative than necessary, but much easier than enforcing\n    ** an exact limit.\n    */\n    pParse->nHeight += sqlite3SelectExprHeight(p);\n\n    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;\n    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){\n      /* This subquery can be absorbed into its parent. */\n      if( isAggSub ){\n        isAgg = 1;\n        p->selFlags |= SF_Aggregate;\n      }\n      i = -1;\n    }else{\n      /* Generate a subroutine that will fill an ephemeral table with\n      ** the content of this subquery.  pItem->addrFillSub will point\n      ** to the address of the generated subroutine.  pItem->regReturn\n      ** is a register allocated to hold the subroutine return address\n      */\n      int topAddr;\n      int onceAddr = 0;\n      int retAddr;\n      assert( pItem->addrFillSub==0 );\n      pItem->regReturn = ++pParse->nMem;\n      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);\n      pItem->addrFillSub = topAddr+1;\n      VdbeNoopComment((v, \"materialize %s\", pItem->pTab->zName));\n      if( pItem->isCorrelated==0 ){\n        /* If the subquery is no correlated and if we are not inside of\n        ** a trigger, then we only need to compute the value of the subquery\n        ** once. */\n        onceAddr = sqlite3CodeOnce(pParse);\n      }\n      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);\n      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);\n      sqlite3Select(pParse, pSub, &dest);\n      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;\n      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);\n      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);\n      VdbeComment((v, \"end %s\", pItem->pTab->zName));\n      sqlite3VdbeChangeP1(v, topAddr, retAddr);\n      sqlite3ClearTempRegCache(pParse);\n    }\n    if( /*pParse->nErr ||*/ db->mallocFailed ){\n      goto select_end;\n    }\n    pParse->nHeight -= sqlite3SelectExprHeight(p);\n    pTabList = p->pSrc;\n    if( !IgnorableOrderby(pDest) ){\n      pOrderBy = p->pOrderBy;\n    }\n  }\n  pEList = p->pEList;\n#endif\n  pWhere = p->pWhere;\n  pGroupBy = p->pGroupBy;\n  pHaving = p->pHaving;\n  isDistinct = (p->selFlags & SF_Distinct)!=0;\n\n#ifndef SQLITE_OMIT_COMPOUND_SELECT\n  /* If there is are a sequence of queries, do the earlier ones first.\n  */\n  if( p->pPrior ){\n    if( p->pRightmost==0 ){\n      Select *pLoop, *pRight = 0;\n      int cnt = 0;\n      int mxSelect;\n      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){\n        pLoop->pRightmost = p;\n        pLoop->pNext = pRight;\n        pRight = pLoop;\n      }\n      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];\n      if( mxSelect && cnt>mxSelect ){\n        sqlite3ErrorMsg(pParse, \"too many terms in compound SELECT\");\n        goto select_end;\n      }\n    }\n    rc = multiSelect(pParse, p, pDest);\n    explainSetInteger(pParse->iSelectId, iRestoreSelectId);\n    return rc;\n  }\n#endif\n\n  /* If there is both a GROUP BY and an ORDER BY clause and they are\n  ** identical, then disable the ORDER BY clause since the GROUP BY\n  ** will cause elements to come out in the correct order.  This is\n  ** an optimization - the correct answer should result regardless.\n  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER\n  ** to disable this optimization for testing purposes.\n  */\n  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0\n         && (db->flags & SQLITE_GroupByOrder)==0 ){\n    pOrderBy = 0;\n  }\n\n  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and \n  ** if the select-list is the same as the ORDER BY list, then this query\n  ** can be rewritten as a GROUP BY. In other words, this:\n  **\n  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz\n  **\n  ** is transformed to:\n  **\n  **     SELECT xyz FROM ... GROUP BY xyz\n  **\n  ** The second form is preferred as a single index (or temp-table) may be \n  ** used for both the ORDER BY and DISTINCT processing. As originally \n  ** written the query must use a temp-table for at least one of the ORDER \n  ** BY and DISTINCT, and an index or separate temp-table for the other.\n  */\n  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct \n   && sqlite3ExprListCompare(pOrderBy, p->pEList)==0\n  ){\n    p->selFlags &= ~SF_Distinct;\n    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);\n    pGroupBy = p->pGroupBy;\n    pOrderBy = 0;\n  }\n\n  /* If there is an ORDER BY clause, then this sorting\n  ** index might end up being unused if the data can be \n  ** extracted in pre-sorted order.  If that is the case, then the\n  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once\n  ** we figure out that the sorting index is not needed.  The addrSortIndex\n  ** variable is used to facilitate that change.\n  */\n  if( pOrderBy ){\n    KeyInfo *pKeyInfo;\n    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);\n    pOrderBy->iECursor = pParse->nTab++;\n    p->addrOpenEphm[2] = addrSortIndex =\n      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,\n                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,\n                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);\n  }else{\n    addrSortIndex = -1;\n  }\n\n  /* If the output is destined for a temporary table, open that table.\n  */\n  if( pDest->eDest==SRT_EphemTab ){\n    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);\n  }\n\n  /* Set the limiter.\n  */\n  iEnd = sqlite3VdbeMakeLabel(v);\n  p->nSelectRow = (double)LARGEST_INT64;\n  computeLimitRegisters(pParse, p, iEnd);\n  if( p->iLimit==0 && addrSortIndex>=0 ){\n    sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;\n    p->selFlags |= SF_UseSorter;\n  }\n\n  /* Open a virtual index to use for the distinct set.\n  */\n  if( p->selFlags & SF_Distinct ){\n    KeyInfo *pKeyInfo;\n    distinct = pParse->nTab++;\n    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);\n    addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,\n        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);\n    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n  }else{\n    distinct = addrDistinctIndex = -1;\n  }\n\n  /* Aggregate and non-aggregate queries are handled differently */\n  if( !isAgg && pGroupBy==0 ){\n    ExprList *pDist = (isDistinct ? p->pEList : 0);\n\n    /* Begin the database scan. */\n    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0,0);\n    if( pWInfo==0 ) goto select_end;\n    if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;\n\n    /* If sorting index that was created by a prior OP_OpenEphemeral \n    ** instruction ended up not being needed, then change the OP_OpenEphemeral\n    ** into an OP_Noop.\n    */\n    if( addrSortIndex>=0 && pOrderBy==0 ){\n      sqlite3VdbeChangeToNoop(v, addrSortIndex);\n      p->addrOpenEphm[2] = -1;\n    }\n\n    if( pWInfo->eDistinct ){\n      VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */\n     \n      assert( addrDistinctIndex>=0 );\n      pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);\n\n      assert( isDistinct );\n      assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED \n           || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE \n      );\n      distinct = -1;\n      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){\n        int iJump;\n        int iExpr;\n        int iFlag = ++pParse->nMem;\n        int iBase = pParse->nMem+1;\n        int iBase2 = iBase + pEList->nExpr;\n        pParse->nMem += (pEList->nExpr*2);\n\n        /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The\n        ** OP_Integer initializes the \"first row\" flag.  */\n        pOp->opcode = OP_Integer;\n        pOp->p1 = 1;\n        pOp->p2 = iFlag;\n\n        sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);\n        iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;\n        sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);\n        for(iExpr=0; iExpr<pEList->nExpr; iExpr++){\n          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);\n          sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);\n          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);\n          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);\n        }\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);\n\n        sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);\n        assert( sqlite3VdbeCurrentAddr(v)==iJump );\n        sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);\n      }else{\n        pOp->opcode = OP_Noop;\n      }\n    }\n\n    /* Use the standard inner loop. */\n    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,\n                    pWInfo->iContinue, pWInfo->iBreak);\n\n    /* End the database scan loop.\n    */\n    sqlite3WhereEnd(pWInfo);\n  }else{\n    /* This is the processing for aggregate queries */\n    NameContext sNC;    /* Name context for processing aggregate information */\n    int iAMem;          /* First Mem address for storing current GROUP BY */\n    int iBMem;          /* First Mem address for previous GROUP BY */\n    int iUseFlag;       /* Mem address holding flag indicating that at least\n                        ** one row of the input to the aggregator has been\n                        ** processed */\n    int iAbortFlag;     /* Mem address which causes query abort if positive */\n    int groupBySort;    /* Rows come from source in GROUP BY order */\n    int addrEnd;        /* End of processing for this SELECT */\n    int sortPTab = 0;   /* Pseudotable used to decode sorting results */\n    int sortOut = 0;    /* Output register from the sorter */\n\n    /* Remove any and all aliases between the result set and the\n    ** GROUP BY clause.\n    */\n    if( pGroupBy ){\n      int k;                        /* Loop counter */\n      struct ExprList_item *pItem;  /* For looping over expression in a list */\n\n      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){\n        pItem->iAlias = 0;\n      }\n      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){\n        pItem->iAlias = 0;\n      }\n      if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;\n    }else{\n      p->nSelectRow = (double)1;\n    }\n\n \n    /* Create a label to jump to when we want to abort the query */\n    addrEnd = sqlite3VdbeMakeLabel(v);\n\n    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in\n    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the\n    ** SELECT statement.\n    */\n    memset(&sNC, 0, sizeof(sNC));\n    sNC.pParse = pParse;\n    sNC.pSrcList = pTabList;\n    sNC.pAggInfo = &sAggInfo;\n    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;\n    sAggInfo.pGroupBy = pGroupBy;\n    sqlite3ExprAnalyzeAggList(&sNC, pEList);\n    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);\n    if( pHaving ){\n      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);\n    }\n    sAggInfo.nAccumulator = sAggInfo.nColumn;\n    for(i=0; i<sAggInfo.nFunc; i++){\n      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );\n      sNC.ncFlags |= NC_InAggFunc;\n      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);\n      sNC.ncFlags &= ~NC_InAggFunc;\n    }\n    if( db->mallocFailed ) goto select_end;\n\n    /* Processing for aggregates with GROUP BY is very different and\n    ** much more complex than aggregates without a GROUP BY.\n    */\n    if( pGroupBy ){\n      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */\n      int j1;             /* A-vs-B comparision jump */\n      int addrOutputRow;  /* Start of subroutine that outputs a result row */\n      int regOutputRow;   /* Return address register for output subroutine */\n      int addrSetAbort;   /* Set the abort flag and return */\n      int addrTopOfLoop;  /* Top of the input loop */\n      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */\n      int addrReset;      /* Subroutine for resetting the accumulator */\n      int regReset;       /* Return address register for reset subroutine */\n\n      /* If there is a GROUP BY clause we might need a sorting index to\n      ** implement it.  Allocate that sorting index now.  If it turns out\n      ** that we do not need it after all, the OP_SorterOpen instruction\n      ** will be converted into a Noop.  \n      */\n      sAggInfo.sortingIdx = pParse->nTab++;\n      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);\n      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, \n          sAggInfo.sortingIdx, sAggInfo.nSortingColumn, \n          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);\n\n      /* Initialize memory locations used by GROUP BY aggregate processing\n      */\n      iUseFlag = ++pParse->nMem;\n      iAbortFlag = ++pParse->nMem;\n      regOutputRow = ++pParse->nMem;\n      addrOutputRow = sqlite3VdbeMakeLabel(v);\n      regReset = ++pParse->nMem;\n      addrReset = sqlite3VdbeMakeLabel(v);\n      iAMem = pParse->nMem + 1;\n      pParse->nMem += pGroupBy->nExpr;\n      iBMem = pParse->nMem + 1;\n      pParse->nMem += pGroupBy->nExpr;\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);\n      VdbeComment((v, \"clear abort flag\"));\n      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);\n      VdbeComment((v, \"indicate accumulator empty\"));\n      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);\n\n      /* Begin a loop that will extract all source rows in GROUP BY order.\n      ** This might involve two separate loops with an OP_Sort in between, or\n      ** it might be a single loop that uses an index to extract information\n      ** in the right order to begin with.\n      */\n      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0, 0);\n      if( pWInfo==0 ) goto select_end;\n      if( pGroupBy==0 ){\n        /* The optimizer is able to deliver rows in group by order so\n        ** we do not have to sort.  The OP_OpenEphemeral table will be\n        ** cancelled later because we still need to use the pKeyInfo\n        */\n        pGroupBy = p->pGroupBy;\n        groupBySort = 0;\n      }else{\n        /* Rows are coming out in undetermined order.  We have to push\n        ** each row into a sorting index, terminate the first loop,\n        ** then loop over the sorting index in order to get the output\n        ** in sorted order\n        */\n        int regBase;\n        int regRecord;\n        int nCol;\n        int nGroupBy;\n\n        explainTempTable(pParse, \n            isDistinct && !(p->selFlags&SF_Distinct)?\"DISTINCT\":\"GROUP BY\");\n\n        groupBySort = 1;\n        nGroupBy = pGroupBy->nExpr;\n        nCol = nGroupBy + 1;\n        j = nGroupBy+1;\n        for(i=0; i<sAggInfo.nColumn; i++){\n          if( sAggInfo.aCol[i].iSorterColumn>=j ){\n            nCol++;\n            j++;\n          }\n        }\n        regBase = sqlite3GetTempRange(pParse, nCol);\n        sqlite3ExprCacheClear(pParse);\n        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);\n        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);\n        j = nGroupBy+1;\n        for(i=0; i<sAggInfo.nColumn; i++){\n          struct AggInfo_col *pCol = &sAggInfo.aCol[i];\n          if( pCol->iSorterColumn>=j ){\n            int r1 = j + regBase;\n            int r2;\n\n            r2 = sqlite3ExprCodeGetColumn(pParse, \n                               pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);\n            if( r1!=r2 ){\n              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);\n            }\n            j++;\n          }\n        }\n        regRecord = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);\n        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);\n        sqlite3ReleaseTempReg(pParse, regRecord);\n        sqlite3ReleaseTempRange(pParse, regBase, nCol);\n        sqlite3WhereEnd(pWInfo);\n        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;\n        sortOut = sqlite3GetTempReg(pParse);\n        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);\n        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);\n        VdbeComment((v, \"GROUP BY sort\"));\n        sAggInfo.useSortingIdx = 1;\n        sqlite3ExprCacheClear(pParse);\n      }\n\n      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...\n      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)\n      ** Then compare the current GROUP BY terms against the GROUP BY terms\n      ** from the previous row currently stored in a0, a1, a2...\n      */\n      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);\n      sqlite3ExprCacheClear(pParse);\n      if( groupBySort ){\n        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);\n      }\n      for(j=0; j<pGroupBy->nExpr; j++){\n        if( groupBySort ){\n          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);\n          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);\n        }else{\n          sAggInfo.directMode = 1;\n          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);\n        }\n      }\n      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,\n                          (char*)pKeyInfo, P4_KEYINFO);\n      j1 = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);\n\n      /* Generate code that runs whenever the GROUP BY changes.\n      ** Changes in the GROUP BY are detected by the previous code\n      ** block.  If there were no changes, this block is skipped.\n      **\n      ** This code copies current group by terms in b0,b1,b2,...\n      ** over to a0,a1,a2.  It then calls the output subroutine\n      ** and resets the aggregate accumulator registers in preparation\n      ** for the next GROUP BY batch.\n      */\n      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);\n      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n      VdbeComment((v, \"output one row\"));\n      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);\n      VdbeComment((v, \"check abort flag\"));\n      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);\n      VdbeComment((v, \"reset accumulator\"));\n\n      /* Update the aggregate accumulators based on the content of\n      ** the current row\n      */\n      sqlite3VdbeJumpHere(v, j1);\n      updateAccumulator(pParse, &sAggInfo);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);\n      VdbeComment((v, \"indicate data in accumulator\"));\n\n      /* End of the loop\n      */\n      if( groupBySort ){\n        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);\n      }else{\n        sqlite3WhereEnd(pWInfo);\n        sqlite3VdbeChangeToNoop(v, addrSortingIdx);\n      }\n\n      /* Output the final row of result\n      */\n      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);\n      VdbeComment((v, \"output final row\"));\n\n      /* Jump over the subroutines\n      */\n      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);\n\n      /* Generate a subroutine that outputs a single row of the result\n      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag\n      ** is less than or equal to zero, the subroutine is a no-op.  If\n      ** the processing calls for the query to abort, this subroutine\n      ** increments the iAbortFlag memory location before returning in\n      ** order to signal the caller to abort.\n      */\n      addrSetAbort = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);\n      VdbeComment((v, \"set abort flag\"));\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      sqlite3VdbeResolveLabel(v, addrOutputRow);\n      addrOutputRow = sqlite3VdbeCurrentAddr(v);\n      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);\n      VdbeComment((v, \"Groupby result generator entry point\"));\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      finalizeAggFunctions(pParse, &sAggInfo);\n      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);\n      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,\n                      distinct, pDest,\n                      addrOutputRow+1, addrSetAbort);\n      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);\n      VdbeComment((v, \"end groupby result generator\"));\n\n      /* Generate a subroutine that will reset the group-by accumulator\n      */\n      sqlite3VdbeResolveLabel(v, addrReset);\n      resetAccumulator(pParse, &sAggInfo);\n      sqlite3VdbeAddOp1(v, OP_Return, regReset);\n     \n    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */\n    else {\n      ExprList *pDel = 0;\n#ifndef SQLITE_OMIT_BTREECOUNT\n      Table *pTab;\n      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){\n        /* If isSimpleCount() returns a pointer to a Table structure, then\n        ** the SQL statement is of the form:\n        **\n        **   SELECT count(*) FROM <tbl>\n        **\n        ** where the Table structure returned represents table <tbl>.\n        **\n        ** This statement is so common that it is optimized specially. The\n        ** OP_Count instruction is executed either on the intkey table that\n        ** contains the data for table <tbl> or on one of its indexes. It\n        ** is better to execute the op on an index, as indexes are almost\n        ** always spread across less pages than their corresponding tables.\n        */\n        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */\n        Index *pIdx;                         /* Iterator variable */\n        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */\n        Index *pBest = 0;                    /* Best index found so far */\n        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */\n\n        sqlite3CodeVerifySchema(pParse, iDb);\n        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n\n        /* Search for the index that has the least amount of columns. If\n        ** there is such an index, and it has less columns than the table\n        ** does, then we can assume that it consumes less space on disk and\n        ** will therefore be cheaper to scan to determine the query result.\n        ** In this case set iRoot to the root page number of the index b-tree\n        ** and pKeyInfo to the KeyInfo structure required to navigate the\n        ** index.\n        **\n        ** (2011-04-15) Do not do a full scan of an unordered index.\n        **\n        ** In practice the KeyInfo structure will not be used. It is only \n        ** passed to keep OP_OpenRead happy.\n        */\n        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n          if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){\n            pBest = pIdx;\n          }\n        }\n        if( pBest && pBest->nColumn<pTab->nCol ){\n          iRoot = pBest->tnum;\n          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);\n        }\n\n        /* Open a read-only cursor, execute the OP_Count, close the cursor. */\n        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);\n        if( pKeyInfo ){\n          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);\n        }\n        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);\n        sqlite3VdbeAddOp1(v, OP_Close, iCsr);\n        explainSimpleCount(pParse, pTab, pBest);\n      }else\n#endif /* SQLITE_OMIT_BTREECOUNT */\n      {\n        /* Check if the query is of one of the following forms:\n        **\n        **   SELECT min(x) FROM ...\n        **   SELECT max(x) FROM ...\n        **\n        ** If it is, then ask the code in where.c to attempt to sort results\n        ** as if there was an \"ORDER ON x\" or \"ORDER ON x DESC\" clause. \n        ** If where.c is able to produce results sorted in this order, then\n        ** add vdbe code to break out of the processing loop after the \n        ** first iteration (since the first iteration of the loop is \n        ** guaranteed to operate on the row with the minimum or maximum \n        ** value of x, the only row required).\n        **\n        ** A special flag must be passed to sqlite3WhereBegin() to slightly\n        ** modify behaviour as follows:\n        **\n        **   + If the query is a \"SELECT min(x)\", then the loop coded by\n        **     where.c should not iterate over any values with a NULL value\n        **     for x.\n        **\n        **   + The optimizer code in where.c (the thing that decides which\n        **     index or indices to use) should place a different priority on \n        **     satisfying the 'ORDER BY' clause than it does in other cases.\n        **     Refer to code and comments in where.c for details.\n        */\n        ExprList *pMinMax = 0;\n        u8 flag = minMaxQuery(p);\n        if( flag ){\n          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );\n          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);\n          pDel = pMinMax;\n          if( pMinMax && !db->mallocFailed ){\n            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;\n            pMinMax->a[0].pExpr->op = TK_COLUMN;\n          }\n        }\n  \n        /* This case runs if the aggregate has no GROUP BY clause.  The\n        ** processing is much simpler since there is only a single row\n        ** of output.\n        */\n        resetAccumulator(pParse, &sAggInfo);\n        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax,0,flag,0);\n        if( pWInfo==0 ){\n          sqlite3ExprListDelete(db, pDel);\n          goto select_end;\n        }\n        updateAccumulator(pParse, &sAggInfo);\n        if( !pMinMax && flag ){\n          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);\n          VdbeComment((v, \"%s() by index\",\n                (flag==WHERE_ORDERBY_MIN?\"min\":\"max\")));\n        }\n        sqlite3WhereEnd(pWInfo);\n        finalizeAggFunctions(pParse, &sAggInfo);\n      }\n\n      pOrderBy = 0;\n      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);\n      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, \n                      pDest, addrEnd, addrEnd);\n      sqlite3ExprListDelete(db, pDel);\n    }\n    sqlite3VdbeResolveLabel(v, addrEnd);\n    \n  } /* endif aggregate query */\n\n  if( distinct>=0 ){\n    explainTempTable(pParse, \"DISTINCT\");\n  }\n\n  /* If there is an ORDER BY clause, then we need to sort the results\n  ** and send them to the callback one by one.\n  */\n  if( pOrderBy ){\n    explainTempTable(pParse, \"ORDER BY\");\n    generateSortTail(pParse, p, v, pEList->nExpr, pDest);\n  }\n\n  /* Jump here to skip this query\n  */\n  sqlite3VdbeResolveLabel(v, iEnd);\n\n  /* The SELECT was successfully coded.   Set the return code to 0\n  ** to indicate no errors.\n  */\n  rc = 0;\n\n  /* Control jumps to here if an error is encountered above, or upon\n  ** successful coding of the SELECT.\n  */\nselect_end:\n  explainSetInteger(pParse->iSelectId, iRestoreSelectId);\n\n  /* Identify column names if results of the SELECT are to be output.\n  */\n  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){\n    generateColumnNames(pParse, pTabList, pEList);\n  }\n\n  sqlite3DbFree(db, sAggInfo.aCol);\n  sqlite3DbFree(db, sAggInfo.aFunc);\n  return rc;\n}\n\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n/*\n** Generate a human-readable description of a the Select object.\n*/\nstatic void explainOneSelect(Vdbe *pVdbe, Select *p){\n  sqlite3ExplainPrintf(pVdbe, \"SELECT \");\n  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){\n    if( p->selFlags & SF_Distinct ){\n      sqlite3ExplainPrintf(pVdbe, \"DISTINCT \");\n    }\n    if( p->selFlags & SF_Aggregate ){\n      sqlite3ExplainPrintf(pVdbe, \"agg_flag \");\n    }\n    sqlite3ExplainNL(pVdbe);\n    sqlite3ExplainPrintf(pVdbe, \"   \");\n  }\n  sqlite3ExplainExprList(pVdbe, p->pEList);\n  sqlite3ExplainNL(pVdbe);\n  if( p->pSrc && p->pSrc->nSrc ){\n    int i;\n    sqlite3ExplainPrintf(pVdbe, \"FROM \");\n    sqlite3ExplainPush(pVdbe);\n    for(i=0; i<p->pSrc->nSrc; i++){\n      struct SrcList_item *pItem = &p->pSrc->a[i];\n      sqlite3ExplainPrintf(pVdbe, \"{%d,*} = \", pItem->iCursor);\n      if( pItem->pSelect ){\n        sqlite3ExplainSelect(pVdbe, pItem->pSelect);\n        if( pItem->pTab ){\n          sqlite3ExplainPrintf(pVdbe, \" (tabname=%s)\", pItem->pTab->zName);\n        }\n      }else if( pItem->zName ){\n        sqlite3ExplainPrintf(pVdbe, \"%s\", pItem->zName);\n      }\n      if( pItem->zAlias ){\n        sqlite3ExplainPrintf(pVdbe, \" (AS %s)\", pItem->zAlias);\n      }\n      if( pItem->jointype & JT_LEFT ){\n        sqlite3ExplainPrintf(pVdbe, \" LEFT-JOIN\");\n      }\n      sqlite3ExplainNL(pVdbe);\n    }\n    sqlite3ExplainPop(pVdbe);\n  }\n  if( p->pWhere ){\n    sqlite3ExplainPrintf(pVdbe, \"WHERE \");\n    sqlite3ExplainExpr(pVdbe, p->pWhere);\n    sqlite3ExplainNL(pVdbe);\n  }\n  if( p->pGroupBy ){\n    sqlite3ExplainPrintf(pVdbe, \"GROUPBY \");\n    sqlite3ExplainExprList(pVdbe, p->pGroupBy);\n    sqlite3ExplainNL(pVdbe);\n  }\n  if( p->pHaving ){\n    sqlite3ExplainPrintf(pVdbe, \"HAVING \");\n    sqlite3ExplainExpr(pVdbe, p->pHaving);\n    sqlite3ExplainNL(pVdbe);\n  }\n  if( p->pOrderBy ){\n    sqlite3ExplainPrintf(pVdbe, \"ORDERBY \");\n    sqlite3ExplainExprList(pVdbe, p->pOrderBy);\n    sqlite3ExplainNL(pVdbe);\n  }\n  if( p->pLimit ){\n    sqlite3ExplainPrintf(pVdbe, \"LIMIT \");\n    sqlite3ExplainExpr(pVdbe, p->pLimit);\n    sqlite3ExplainNL(pVdbe);\n  }\n  if( p->pOffset ){\n    sqlite3ExplainPrintf(pVdbe, \"OFFSET \");\n    sqlite3ExplainExpr(pVdbe, p->pOffset);\n    sqlite3ExplainNL(pVdbe);\n  }\n}\nSQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){\n  if( p==0 ){\n    sqlite3ExplainPrintf(pVdbe, \"(null-select)\");\n    return;\n  }\n  while( p->pPrior ) p = p->pPrior;\n  sqlite3ExplainPush(pVdbe);\n  while( p ){\n    explainOneSelect(pVdbe, p);\n    p = p->pNext;\n    if( p==0 ) break;\n    sqlite3ExplainNL(pVdbe);\n    sqlite3ExplainPrintf(pVdbe, \"%s\\n\", selectOpName(p->op));\n  }\n  sqlite3ExplainPrintf(pVdbe, \"END\");\n  sqlite3ExplainPop(pVdbe);\n}\n\n/* End of the structure debug printing code\n*****************************************************************************/\n#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */\n\n/************** End of select.c **********************************************/\n/************** Begin file table.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the sqlite3_get_table() and sqlite3_free_table()\n** interface routines.  These are just wrappers around the main\n** interface routine of sqlite3_exec().\n**\n** These routines are in a separate files so that they will not be linked\n** if they are not used.\n*/\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n#ifndef SQLITE_OMIT_GET_TABLE\n\n/*\n** This structure is used to pass data from sqlite3_get_table() through\n** to the callback function is uses to build the result.\n*/\ntypedef struct TabResult {\n  char **azResult;   /* Accumulated output */\n  char *zErrMsg;     /* Error message text, if an error occurs */\n  int nAlloc;        /* Slots allocated for azResult[] */\n  int nRow;          /* Number of rows in the result */\n  int nColumn;       /* Number of columns in the result */\n  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */\n  int rc;            /* Return code from sqlite3_exec() */\n} TabResult;\n\n/*\n** This routine is called once for each row in the result table.  Its job\n** is to fill in the TabResult structure appropriately, allocating new\n** memory as necessary.\n*/\nstatic int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){\n  TabResult *p = (TabResult*)pArg;  /* Result accumulator */\n  int need;                         /* Slots needed in p->azResult[] */\n  int i;                            /* Loop counter */\n  char *z;                          /* A single column of result */\n\n  /* Make sure there is enough space in p->azResult to hold everything\n  ** we need to remember from this invocation of the callback.\n  */\n  if( p->nRow==0 && argv!=0 ){\n    need = nCol*2;\n  }else{\n    need = nCol;\n  }\n  if( p->nData + need > p->nAlloc ){\n    char **azNew;\n    p->nAlloc = p->nAlloc*2 + need;\n    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );\n    if( azNew==0 ) goto malloc_failed;\n    p->azResult = azNew;\n  }\n\n  /* If this is the first row, then generate an extra row containing\n  ** the names of all columns.\n  */\n  if( p->nRow==0 ){\n    p->nColumn = nCol;\n    for(i=0; i<nCol; i++){\n      z = sqlite3_mprintf(\"%s\", colv[i]);\n      if( z==0 ) goto malloc_failed;\n      p->azResult[p->nData++] = z;\n    }\n  }else if( p->nColumn!=nCol ){\n    sqlite3_free(p->zErrMsg);\n    p->zErrMsg = sqlite3_mprintf(\n       \"sqlite3_get_table() called with two or more incompatible queries\"\n    );\n    p->rc = SQLITE_ERROR;\n    return 1;\n  }\n\n  /* Copy over the row data\n  */\n  if( argv!=0 ){\n    for(i=0; i<nCol; i++){\n      if( argv[i]==0 ){\n        z = 0;\n      }else{\n        int n = sqlite3Strlen30(argv[i])+1;\n        z = sqlite3_malloc( n );\n        if( z==0 ) goto malloc_failed;\n        memcpy(z, argv[i], n);\n      }\n      p->azResult[p->nData++] = z;\n    }\n    p->nRow++;\n  }\n  return 0;\n\nmalloc_failed:\n  p->rc = SQLITE_NOMEM;\n  return 1;\n}\n\n/*\n** Query the database.  But instead of invoking a callback for each row,\n** malloc() for space to hold the result and return the entire results\n** at the conclusion of the call.\n**\n** The result that is written to ***pazResult is held in memory obtained\n** from malloc().  But the caller cannot free this memory directly.  \n** Instead, the entire table should be passed to sqlite3_free_table() when\n** the calling procedure is finished using it.\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,                /* The database on which the SQL executes */\n  const char *zSql,           /* The SQL to be executed */\n  char ***pazResult,          /* Write the result table here */\n  int *pnRow,                 /* Write the number of rows in the result here */\n  int *pnColumn,              /* Write the number of columns of result here */\n  char **pzErrMsg             /* Write error messages here */\n){\n  int rc;\n  TabResult res;\n\n  *pazResult = 0;\n  if( pnColumn ) *pnColumn = 0;\n  if( pnRow ) *pnRow = 0;\n  if( pzErrMsg ) *pzErrMsg = 0;\n  res.zErrMsg = 0;\n  res.nRow = 0;\n  res.nColumn = 0;\n  res.nData = 1;\n  res.nAlloc = 20;\n  res.rc = SQLITE_OK;\n  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );\n  if( res.azResult==0 ){\n     db->errCode = SQLITE_NOMEM;\n     return SQLITE_NOMEM;\n  }\n  res.azResult[0] = 0;\n  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);\n  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );\n  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);\n  if( (rc&0xff)==SQLITE_ABORT ){\n    sqlite3_free_table(&res.azResult[1]);\n    if( res.zErrMsg ){\n      if( pzErrMsg ){\n        sqlite3_free(*pzErrMsg);\n        *pzErrMsg = sqlite3_mprintf(\"%s\",res.zErrMsg);\n      }\n      sqlite3_free(res.zErrMsg);\n    }\n    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */\n    return res.rc;\n  }\n  sqlite3_free(res.zErrMsg);\n  if( rc!=SQLITE_OK ){\n    sqlite3_free_table(&res.azResult[1]);\n    return rc;\n  }\n  if( res.nAlloc>res.nData ){\n    char **azNew;\n    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );\n    if( azNew==0 ){\n      sqlite3_free_table(&res.azResult[1]);\n      db->errCode = SQLITE_NOMEM;\n      return SQLITE_NOMEM;\n    }\n    res.azResult = azNew;\n  }\n  *pazResult = &res.azResult[1];\n  if( pnColumn ) *pnColumn = res.nColumn;\n  if( pnRow ) *pnRow = res.nRow;\n  return rc;\n}\n\n/*\n** This routine frees the space the sqlite3_get_table() malloced.\n*/\nSQLITE_API void sqlite3_free_table(\n  char **azResult            /* Result returned from from sqlite3_get_table() */\n){\n  if( azResult ){\n    int i, n;\n    azResult--;\n    assert( azResult!=0 );\n    n = SQLITE_PTR_TO_INT(azResult[0]);\n    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }\n    sqlite3_free(azResult);\n  }\n}\n\n#endif /* SQLITE_OMIT_GET_TABLE */\n\n/************** End of table.c ***********************************************/\n/************** Begin file trigger.c *****************************************/\n/*\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains the implementation for TRIGGERs\n*/\n\n#ifndef SQLITE_OMIT_TRIGGER\n/*\n** Delete a linked list of TriggerStep structures.\n*/\nSQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){\n  while( pTriggerStep ){\n    TriggerStep * pTmp = pTriggerStep;\n    pTriggerStep = pTriggerStep->pNext;\n\n    sqlite3ExprDelete(db, pTmp->pWhere);\n    sqlite3ExprListDelete(db, pTmp->pExprList);\n    sqlite3SelectDelete(db, pTmp->pSelect);\n    sqlite3IdListDelete(db, pTmp->pIdList);\n\n    sqlite3DbFree(db, pTmp);\n  }\n}\n\n/*\n** Given table pTab, return a list of all the triggers attached to \n** the table. The list is connected by Trigger.pNext pointers.\n**\n** All of the triggers on pTab that are in the same database as pTab\n** are already attached to pTab->pTrigger.  But there might be additional\n** triggers on pTab in the TEMP schema.  This routine prepends all\n** TEMP triggers on pTab to the beginning of the pTab->pTrigger list\n** and returns the combined list.\n**\n** To state it another way:  This routine returns a list of all triggers\n** that fire off of pTab.  The list will include any TEMP triggers on\n** pTab as well as the triggers lised in pTab->pTrigger.\n*/\nSQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){\n  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;\n  Trigger *pList = 0;                  /* List of triggers to return */\n\n  if( pParse->disableTriggers ){\n    return 0;\n  }\n\n  if( pTmpSchema!=pTab->pSchema ){\n    HashElem *p;\n    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );\n    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){\n      Trigger *pTrig = (Trigger *)sqliteHashData(p);\n      if( pTrig->pTabSchema==pTab->pSchema\n       && 0==sqlite3StrICmp(pTrig->table, pTab->zName) \n      ){\n        pTrig->pNext = (pList ? pList : pTab->pTrigger);\n        pList = pTrig;\n      }\n    }\n  }\n\n  return (pList ? pList : pTab->pTrigger);\n}\n\n/*\n** This is called by the parser when it sees a CREATE TRIGGER statement\n** up to the point of the BEGIN before the trigger actions.  A Trigger\n** structure is generated based on the information available and stored\n** in pParse->pNewTrigger.  After the trigger actions have been parsed, the\n** sqlite3FinishTrigger() function is called to complete the trigger\n** construction process.\n*/\nSQLITE_PRIVATE void sqlite3BeginTrigger(\n  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */\n  Token *pName1,      /* The name of the trigger */\n  Token *pName2,      /* The name of the trigger */\n  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */\n  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */\n  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */\n  SrcList *pTableName,/* The name of the table/view the trigger applies to */\n  Expr *pWhen,        /* WHEN clause */\n  int isTemp,         /* True if the TEMPORARY keyword is present */\n  int noErr           /* Suppress errors if the trigger already exists */\n){\n  Trigger *pTrigger = 0;  /* The new trigger */\n  Table *pTab;            /* Table that the trigger fires off of */\n  char *zName = 0;        /* Name of the trigger */\n  sqlite3 *db = pParse->db;  /* The database connection */\n  int iDb;                /* The database to store the trigger in */\n  Token *pName;           /* The unqualified db name */\n  DbFixer sFix;           /* State vector for the DB fixer */\n  int iTabDb;             /* Index of the database holding pTab */\n\n  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */\n  assert( pName2!=0 );\n  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );\n  assert( op>0 && op<0xff );\n  if( isTemp ){\n    /* If TEMP was specified, then the trigger name may not be qualified. */\n    if( pName2->n>0 ){\n      sqlite3ErrorMsg(pParse, \"temporary trigger may not have qualified name\");\n      goto trigger_cleanup;\n    }\n    iDb = 1;\n    pName = pName1;\n  }else{\n    /* Figure out the db that the trigger will be created in */\n    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);\n    if( iDb<0 ){\n      goto trigger_cleanup;\n    }\n  }\n  if( !pTableName || db->mallocFailed ){\n    goto trigger_cleanup;\n  }\n\n  /* A long-standing parser bug is that this syntax was allowed:\n  **\n  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....\n  **                                                 ^^^^^^^^\n  **\n  ** To maintain backwards compatibility, ignore the database\n  ** name on pTableName if we are reparsing our of SQLITE_MASTER.\n  */\n  if( db->init.busy && iDb!=1 ){\n    sqlite3DbFree(db, pTableName->a[0].zDatabase);\n    pTableName->a[0].zDatabase = 0;\n  }\n\n  /* If the trigger name was unqualified, and the table is a temp table,\n  ** then set iDb to 1 to create the trigger in the temporary database.\n  ** If sqlite3SrcListLookup() returns 0, indicating the table does not\n  ** exist, the error is caught by the block below.\n  */\n  pTab = sqlite3SrcListLookup(pParse, pTableName);\n  if( db->init.busy==0 && pName2->n==0 && pTab\n        && pTab->pSchema==db->aDb[1].pSchema ){\n    iDb = 1;\n  }\n\n  /* Ensure the table name matches database name and that the table exists */\n  if( db->mallocFailed ) goto trigger_cleanup;\n  assert( pTableName->nSrc==1 );\n  if( sqlite3FixInit(&sFix, pParse, iDb, \"trigger\", pName) && \n      sqlite3FixSrcList(&sFix, pTableName) ){\n    goto trigger_cleanup;\n  }\n  pTab = sqlite3SrcListLookup(pParse, pTableName);\n  if( !pTab ){\n    /* The table does not exist. */\n    if( db->init.iDb==1 ){\n      /* Ticket #3810.\n      ** Normally, whenever a table is dropped, all associated triggers are\n      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table\n      ** and the table is dropped by a different database connection, the\n      ** trigger is not visible to the database connection that does the\n      ** drop so the trigger cannot be dropped.  This results in an\n      ** \"orphaned trigger\" - a trigger whose associated table is missing.\n      */\n      db->init.orphanTrigger = 1;\n    }\n    goto trigger_cleanup;\n  }\n  if( IsVirtual(pTab) ){\n    sqlite3ErrorMsg(pParse, \"cannot create triggers on virtual tables\");\n    goto trigger_cleanup;\n  }\n\n  /* Check that the trigger name is not reserved and that no trigger of the\n  ** specified name exists */\n  zName = sqlite3NameFromToken(db, pName);\n  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){\n    goto trigger_cleanup;\n  }\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),\n                      zName, sqlite3Strlen30(zName)) ){\n    if( !noErr ){\n      sqlite3ErrorMsg(pParse, \"trigger %T already exists\", pName);\n    }else{\n      assert( !db->init.busy );\n      sqlite3CodeVerifySchema(pParse, iDb);\n    }\n    goto trigger_cleanup;\n  }\n\n  /* Do not create a trigger on a system table */\n  if( sqlite3StrNICmp(pTab->zName, \"sqlite_\", 7)==0 ){\n    sqlite3ErrorMsg(pParse, \"cannot create trigger on system table\");\n    pParse->nErr++;\n    goto trigger_cleanup;\n  }\n\n  /* INSTEAD of triggers are only for views and views only support INSTEAD\n  ** of triggers.\n  */\n  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){\n    sqlite3ErrorMsg(pParse, \"cannot create %s trigger on view: %S\", \n        (tr_tm == TK_BEFORE)?\"BEFORE\":\"AFTER\", pTableName, 0);\n    goto trigger_cleanup;\n  }\n  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){\n    sqlite3ErrorMsg(pParse, \"cannot create INSTEAD OF\"\n        \" trigger on table: %S\", pTableName, 0);\n    goto trigger_cleanup;\n  }\n  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code = SQLITE_CREATE_TRIGGER;\n    const char *zDb = db->aDb[iTabDb].zName;\n    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;\n    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;\n    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){\n      goto trigger_cleanup;\n    }\n    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){\n      goto trigger_cleanup;\n    }\n  }\n#endif\n\n  /* INSTEAD OF triggers can only appear on views and BEFORE triggers\n  ** cannot appear on views.  So we might as well translate every\n  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code\n  ** elsewhere.\n  */\n  if (tr_tm == TK_INSTEAD){\n    tr_tm = TK_BEFORE;\n  }\n\n  /* Build the Trigger object */\n  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));\n  if( pTrigger==0 ) goto trigger_cleanup;\n  pTrigger->zName = zName;\n  zName = 0;\n  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);\n  pTrigger->pSchema = db->aDb[iDb].pSchema;\n  pTrigger->pTabSchema = pTab->pSchema;\n  pTrigger->op = (u8)op;\n  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;\n  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);\n  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);\n  assert( pParse->pNewTrigger==0 );\n  pParse->pNewTrigger = pTrigger;\n\ntrigger_cleanup:\n  sqlite3DbFree(db, zName);\n  sqlite3SrcListDelete(db, pTableName);\n  sqlite3IdListDelete(db, pColumns);\n  sqlite3ExprDelete(db, pWhen);\n  if( !pParse->pNewTrigger ){\n    sqlite3DeleteTrigger(db, pTrigger);\n  }else{\n    assert( pParse->pNewTrigger==pTrigger );\n  }\n}\n\n/*\n** This routine is called after all of the trigger actions have been parsed\n** in order to complete the process of building the trigger.\n*/\nSQLITE_PRIVATE void sqlite3FinishTrigger(\n  Parse *pParse,          /* Parser context */\n  TriggerStep *pStepList, /* The triggered program */\n  Token *pAll             /* Token that describes the complete CREATE TRIGGER */\n){\n  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */\n  char *zName;                            /* Name of trigger */\n  sqlite3 *db = pParse->db;               /* The database */\n  DbFixer sFix;                           /* Fixer object */\n  int iDb;                                /* Database containing the trigger */\n  Token nameToken;                        /* Trigger name for error reporting */\n\n  pParse->pNewTrigger = 0;\n  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;\n  zName = pTrig->zName;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);\n  pTrig->step_list = pStepList;\n  while( pStepList ){\n    pStepList->pTrig = pTrig;\n    pStepList = pStepList->pNext;\n  }\n  nameToken.z = pTrig->zName;\n  nameToken.n = sqlite3Strlen30(nameToken.z);\n  if( sqlite3FixInit(&sFix, pParse, iDb, \"trigger\", &nameToken) \n          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){\n    goto triggerfinish_cleanup;\n  }\n\n  /* if we are not initializing,\n  ** build the sqlite_master entry\n  */\n  if( !db->init.busy ){\n    Vdbe *v;\n    char *z;\n\n    /* Make an entry in the sqlite_master table */\n    v = sqlite3GetVdbe(pParse);\n    if( v==0 ) goto triggerfinish_cleanup;\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);\n    sqlite3NestedParse(pParse,\n       \"INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')\",\n       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,\n       pTrig->table, z);\n    sqlite3DbFree(db, z);\n    sqlite3ChangeCookie(pParse, iDb);\n    sqlite3VdbeAddParseSchemaOp(v, iDb,\n        sqlite3MPrintf(db, \"type='trigger' AND name='%q'\", zName));\n  }\n\n  if( db->init.busy ){\n    Trigger *pLink = pTrig;\n    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;\n    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);\n    if( pTrig ){\n      db->mallocFailed = 1;\n    }else if( pLink->pSchema==pLink->pTabSchema ){\n      Table *pTab;\n      int n = sqlite3Strlen30(pLink->table);\n      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);\n      assert( pTab!=0 );\n      pLink->pNext = pTab->pTrigger;\n      pTab->pTrigger = pLink;\n    }\n  }\n\ntriggerfinish_cleanup:\n  sqlite3DeleteTrigger(db, pTrig);\n  assert( !pParse->pNewTrigger );\n  sqlite3DeleteTriggerStep(db, pStepList);\n}\n\n/*\n** Turn a SELECT statement (that the pSelect parameter points to) into\n** a trigger step.  Return a pointer to a TriggerStep structure.\n**\n** The parser calls this routine when it finds a SELECT statement in\n** body of a TRIGGER.  \n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){\n  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));\n  if( pTriggerStep==0 ) {\n    sqlite3SelectDelete(db, pSelect);\n    return 0;\n  }\n  pTriggerStep->op = TK_SELECT;\n  pTriggerStep->pSelect = pSelect;\n  pTriggerStep->orconf = OE_Default;\n  return pTriggerStep;\n}\n\n/*\n** Allocate space to hold a new trigger step.  The allocated space\n** holds both the TriggerStep object and the TriggerStep.target.z string.\n**\n** If an OOM error occurs, NULL is returned and db->mallocFailed is set.\n*/\nstatic TriggerStep *triggerStepAllocate(\n  sqlite3 *db,                /* Database connection */\n  u8 op,                      /* Trigger opcode */\n  Token *pName                /* The target name */\n){\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);\n  if( pTriggerStep ){\n    char *z = (char*)&pTriggerStep[1];\n    memcpy(z, pName->z, pName->n);\n    pTriggerStep->target.z = z;\n    pTriggerStep->target.n = pName->n;\n    pTriggerStep->op = op;\n  }\n  return pTriggerStep;\n}\n\n/*\n** Build a trigger step out of an INSERT statement.  Return a pointer\n** to the new trigger step.\n**\n** The parser calls this routine when it sees an INSERT inside the\n** body of a trigger.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(\n  sqlite3 *db,        /* The database connection */\n  Token *pTableName,  /* Name of the table into which we insert */\n  IdList *pColumn,    /* List of columns in pTableName to insert into */\n  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */\n  Select *pSelect,    /* A SELECT statement that supplies values */\n  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */\n){\n  TriggerStep *pTriggerStep;\n\n  assert(pEList == 0 || pSelect == 0);\n  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);\n\n  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);\n  if( pTriggerStep ){\n    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);\n    pTriggerStep->pIdList = pColumn;\n    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);\n    pTriggerStep->orconf = orconf;\n  }else{\n    sqlite3IdListDelete(db, pColumn);\n  }\n  sqlite3ExprListDelete(db, pEList);\n  sqlite3SelectDelete(db, pSelect);\n\n  return pTriggerStep;\n}\n\n/*\n** Construct a trigger step that implements an UPDATE statement and return\n** a pointer to that trigger step.  The parser calls this routine when it\n** sees an UPDATE statement inside the body of a CREATE TRIGGER.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(\n  sqlite3 *db,         /* The database connection */\n  Token *pTableName,   /* Name of the table to be updated */\n  ExprList *pEList,    /* The SET clause: list of column and new values */\n  Expr *pWhere,        /* The WHERE clause */\n  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */\n){\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);\n  if( pTriggerStep ){\n    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);\n    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n    pTriggerStep->orconf = orconf;\n  }\n  sqlite3ExprListDelete(db, pEList);\n  sqlite3ExprDelete(db, pWhere);\n  return pTriggerStep;\n}\n\n/*\n** Construct a trigger step that implements a DELETE statement and return\n** a pointer to that trigger step.  The parser calls this routine when it\n** sees a DELETE statement inside the body of a CREATE TRIGGER.\n*/\nSQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(\n  sqlite3 *db,            /* Database connection */\n  Token *pTableName,      /* The table from which rows are deleted */\n  Expr *pWhere            /* The WHERE clause */\n){\n  TriggerStep *pTriggerStep;\n\n  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);\n  if( pTriggerStep ){\n    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);\n    pTriggerStep->orconf = OE_Default;\n  }\n  sqlite3ExprDelete(db, pWhere);\n  return pTriggerStep;\n}\n\n/* \n** Recursively delete a Trigger structure\n*/\nSQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){\n  if( pTrigger==0 ) return;\n  sqlite3DeleteTriggerStep(db, pTrigger->step_list);\n  sqlite3DbFree(db, pTrigger->zName);\n  sqlite3DbFree(db, pTrigger->table);\n  sqlite3ExprDelete(db, pTrigger->pWhen);\n  sqlite3IdListDelete(db, pTrigger->pColumns);\n  sqlite3DbFree(db, pTrigger);\n}\n\n/*\n** This function is called to drop a trigger from the database schema. \n**\n** This may be called directly from the parser and therefore identifies\n** the trigger by name.  The sqlite3DropTriggerPtr() routine does the\n** same job as this routine except it takes a pointer to the trigger\n** instead of the trigger name.\n**/\nSQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){\n  Trigger *pTrigger = 0;\n  int i;\n  const char *zDb;\n  const char *zName;\n  int nName;\n  sqlite3 *db = pParse->db;\n\n  if( db->mallocFailed ) goto drop_trigger_cleanup;\n  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){\n    goto drop_trigger_cleanup;\n  }\n\n  assert( pName->nSrc==1 );\n  zDb = pName->a[0].zDatabase;\n  zName = pName->a[0].zName;\n  nName = sqlite3Strlen30(zName);\n  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );\n  for(i=OMIT_TEMPDB; i<db->nDb; i++){\n    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */\n    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;\n    assert( sqlite3SchemaMutexHeld(db, j, 0) );\n    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);\n    if( pTrigger ) break;\n  }\n  if( !pTrigger ){\n    if( !noErr ){\n      sqlite3ErrorMsg(pParse, \"no such trigger: %S\", pName, 0);\n    }else{\n      sqlite3CodeVerifyNamedSchema(pParse, zDb);\n    }\n    pParse->checkSchema = 1;\n    goto drop_trigger_cleanup;\n  }\n  sqlite3DropTriggerPtr(pParse, pTrigger);\n\ndrop_trigger_cleanup:\n  sqlite3SrcListDelete(db, pName);\n}\n\n/*\n** Return a pointer to the Table structure for the table that a trigger\n** is set on.\n*/\nstatic Table *tableOfTrigger(Trigger *pTrigger){\n  int n = sqlite3Strlen30(pTrigger->table);\n  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);\n}\n\n\n/*\n** Drop a trigger given a pointer to that trigger. \n*/\nSQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){\n  Table   *pTable;\n  Vdbe *v;\n  sqlite3 *db = pParse->db;\n  int iDb;\n\n  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);\n  assert( iDb>=0 && iDb<db->nDb );\n  pTable = tableOfTrigger(pTrigger);\n  assert( pTable );\n  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  {\n    int code = SQLITE_DROP_TRIGGER;\n    const char *zDb = db->aDb[iDb].zName;\n    const char *zTab = SCHEMA_TABLE(iDb);\n    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;\n    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||\n      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){\n      return;\n    }\n  }\n#endif\n\n  /* Generate code to destroy the database record of the trigger.\n  */\n  assert( pTable!=0 );\n  if( (v = sqlite3GetVdbe(pParse))!=0 ){\n    int base;\n    static const VdbeOpList dropTrigger[] = {\n      { OP_Rewind,     0, ADDR(9),  0},\n      { OP_String8,    0, 1,        0}, /* 1 */\n      { OP_Column,     0, 1,        2},\n      { OP_Ne,         2, ADDR(8),  1},\n      { OP_String8,    0, 1,        0}, /* 4: \"trigger\" */\n      { OP_Column,     0, 0,        2},\n      { OP_Ne,         2, ADDR(8),  1},\n      { OP_Delete,     0, 0,        0},\n      { OP_Next,       0, ADDR(1),  0}, /* 8 */\n    };\n\n    sqlite3BeginWriteOperation(pParse, 0, iDb);\n    sqlite3OpenMasterTable(pParse, iDb);\n    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);\n    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);\n    sqlite3VdbeChangeP4(v, base+4, \"trigger\", P4_STATIC);\n    sqlite3ChangeCookie(pParse, iDb);\n    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);\n    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);\n    if( pParse->nMem<3 ){\n      pParse->nMem = 3;\n    }\n  }\n}\n\n/*\n** Remove a trigger from the hash tables of the sqlite* pointer.\n*/\nSQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){\n  Trigger *pTrigger;\n  Hash *pHash;\n\n  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );\n  pHash = &(db->aDb[iDb].pSchema->trigHash);\n  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);\n  if( ALWAYS(pTrigger) ){\n    if( pTrigger->pSchema==pTrigger->pTabSchema ){\n      Table *pTab = tableOfTrigger(pTrigger);\n      Trigger **pp;\n      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));\n      *pp = (*pp)->pNext;\n    }\n    sqlite3DeleteTrigger(db, pTrigger);\n    db->flags |= SQLITE_InternChanges;\n  }\n}\n\n/*\n** pEList is the SET clause of an UPDATE statement.  Each entry\n** in pEList is of the format <id>=<expr>.  If any of the entries\n** in pEList have an <id> which matches an identifier in pIdList,\n** then return TRUE.  If pIdList==NULL, then it is considered a\n** wildcard that matches anything.  Likewise if pEList==NULL then\n** it matches anything so always return true.  Return false only\n** if there is no match.\n*/\nstatic int checkColumnOverlap(IdList *pIdList, ExprList *pEList){\n  int e;\n  if( pIdList==0 || NEVER(pEList==0) ) return 1;\n  for(e=0; e<pEList->nExpr; e++){\n    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;\n  }\n  return 0; \n}\n\n/*\n** Return a list of all triggers on table pTab if there exists at least\n** one trigger that must be fired when an operation of type 'op' is \n** performed on the table, and, if that operation is an UPDATE, if at\n** least one of the columns in pChanges is being modified.\n*/\nSQLITE_PRIVATE Trigger *sqlite3TriggersExist(\n  Parse *pParse,          /* Parse context */\n  Table *pTab,            /* The table the contains the triggers */\n  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */\n  ExprList *pChanges,     /* Columns that change in an UPDATE statement */\n  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n){\n  int mask = 0;\n  Trigger *pList = 0;\n  Trigger *p;\n\n  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){\n    pList = sqlite3TriggerList(pParse, pTab);\n  }\n  assert( pList==0 || IsVirtual(pTab)==0 );\n  for(p=pList; p; p=p->pNext){\n    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){\n      mask |= p->tr_tm;\n    }\n  }\n  if( pMask ){\n    *pMask = mask;\n  }\n  return (mask ? pList : 0);\n}\n\n/*\n** Convert the pStep->target token into a SrcList and return a pointer\n** to that SrcList.\n**\n** This routine adds a specific database name, if needed, to the target when\n** forming the SrcList.  This prevents a trigger in one database from\n** referring to a target in another database.  An exception is when the\n** trigger is in TEMP in which case it can refer to any other database it\n** wants.\n*/\nstatic SrcList *targetSrcList(\n  Parse *pParse,       /* The parsing context */\n  TriggerStep *pStep   /* The trigger containing the target token */\n){\n  int iDb;             /* Index of the database to use */\n  SrcList *pSrc;       /* SrcList to be returned */\n\n  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);\n  if( pSrc ){\n    assert( pSrc->nSrc>0 );\n    assert( pSrc->a!=0 );\n    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);\n    if( iDb==0 || iDb>=2 ){\n      sqlite3 *db = pParse->db;\n      assert( iDb<pParse->db->nDb );\n      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);\n    }\n  }\n  return pSrc;\n}\n\n/*\n** Generate VDBE code for the statements inside the body of a single \n** trigger.\n*/\nstatic int codeTriggerProgram(\n  Parse *pParse,            /* The parser context */\n  TriggerStep *pStepList,   /* List of statements inside the trigger body */\n  int orconf                /* Conflict algorithm. (OE_Abort, etc) */  \n){\n  TriggerStep *pStep;\n  Vdbe *v = pParse->pVdbe;\n  sqlite3 *db = pParse->db;\n\n  assert( pParse->pTriggerTab && pParse->pToplevel );\n  assert( pStepList );\n  assert( v!=0 );\n  for(pStep=pStepList; pStep; pStep=pStep->pNext){\n    /* Figure out the ON CONFLICT policy that will be used for this step\n    ** of the trigger program. If the statement that caused this trigger\n    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use\n    ** the ON CONFLICT policy that was specified as part of the trigger\n    ** step statement. Example:\n    **\n    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;\n    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);\n    **   END;\n    **\n    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy\n    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy\n    */\n    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;\n\n    switch( pStep->op ){\n      case TK_UPDATE: {\n        sqlite3Update(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3ExprListDup(db, pStep->pExprList, 0), \n          sqlite3ExprDup(db, pStep->pWhere, 0), \n          pParse->eOrconf\n        );\n        break;\n      }\n      case TK_INSERT: {\n        sqlite3Insert(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3ExprListDup(db, pStep->pExprList, 0), \n          sqlite3SelectDup(db, pStep->pSelect, 0), \n          sqlite3IdListDup(db, pStep->pIdList), \n          pParse->eOrconf\n        );\n        break;\n      }\n      case TK_DELETE: {\n        sqlite3DeleteFrom(pParse, \n          targetSrcList(pParse, pStep),\n          sqlite3ExprDup(db, pStep->pWhere, 0)\n        );\n        break;\n      }\n      default: assert( pStep->op==TK_SELECT ); {\n        SelectDest sDest;\n        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);\n        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);\n        sqlite3Select(pParse, pSelect, &sDest);\n        sqlite3SelectDelete(db, pSelect);\n        break;\n      }\n    } \n    if( pStep->op!=TK_SELECT ){\n      sqlite3VdbeAddOp0(v, OP_ResetCount);\n    }\n  }\n\n  return 0;\n}\n\n#ifdef SQLITE_DEBUG\n/*\n** This function is used to add VdbeComment() annotations to a VDBE\n** program. It is not used in production code, only for debugging.\n*/\nstatic const char *onErrorText(int onError){\n  switch( onError ){\n    case OE_Abort:    return \"abort\";\n    case OE_Rollback: return \"rollback\";\n    case OE_Fail:     return \"fail\";\n    case OE_Replace:  return \"replace\";\n    case OE_Ignore:   return \"ignore\";\n    case OE_Default:  return \"default\";\n  }\n  return \"n/a\";\n}\n#endif\n\n/*\n** Parse context structure pFrom has just been used to create a sub-vdbe\n** (trigger program). If an error has occurred, transfer error information\n** from pFrom to pTo.\n*/\nstatic void transferParseError(Parse *pTo, Parse *pFrom){\n  assert( pFrom->zErrMsg==0 || pFrom->nErr );\n  assert( pTo->zErrMsg==0 || pTo->nErr );\n  if( pTo->nErr==0 ){\n    pTo->zErrMsg = pFrom->zErrMsg;\n    pTo->nErr = pFrom->nErr;\n  }else{\n    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);\n  }\n}\n\n/*\n** Create and populate a new TriggerPrg object with a sub-program \n** implementing trigger pTrigger with ON CONFLICT policy orconf.\n*/\nstatic TriggerPrg *codeRowTrigger(\n  Parse *pParse,       /* Current parse context */\n  Trigger *pTrigger,   /* Trigger to code */\n  Table *pTab,         /* The table pTrigger is attached to */\n  int orconf           /* ON CONFLICT policy to code trigger program with */\n){\n  Parse *pTop = sqlite3ParseToplevel(pParse);\n  sqlite3 *db = pParse->db;   /* Database handle */\n  TriggerPrg *pPrg;           /* Value to return */\n  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */\n  Vdbe *v;                    /* Temporary VM */\n  NameContext sNC;            /* Name context for sub-vdbe */\n  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */\n  Parse *pSubParse;           /* Parse context for sub-vdbe */\n  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */\n\n  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );\n  assert( pTop->pVdbe );\n\n  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they\n  ** are freed if an error occurs, link them into the Parse.pTriggerPrg \n  ** list of the top-level Parse object sooner rather than later.  */\n  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));\n  if( !pPrg ) return 0;\n  pPrg->pNext = pTop->pTriggerPrg;\n  pTop->pTriggerPrg = pPrg;\n  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));\n  if( !pProgram ) return 0;\n  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);\n  pPrg->pTrigger = pTrigger;\n  pPrg->orconf = orconf;\n  pPrg->aColmask[0] = 0xffffffff;\n  pPrg->aColmask[1] = 0xffffffff;\n\n  /* Allocate and populate a new Parse context to use for coding the \n  ** trigger sub-program.  */\n  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));\n  if( !pSubParse ) return 0;\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pSubParse;\n  pSubParse->db = db;\n  pSubParse->pTriggerTab = pTab;\n  pSubParse->pToplevel = pTop;\n  pSubParse->zAuthContext = pTrigger->zName;\n  pSubParse->eTriggerOp = pTrigger->op;\n  pSubParse->nQueryLoop = pParse->nQueryLoop;\n\n  v = sqlite3GetVdbe(pSubParse);\n  if( v ){\n    VdbeComment((v, \"Start: %s.%s (%s %s%s%s ON %s)\", \n      pTrigger->zName, onErrorText(orconf),\n      (pTrigger->tr_tm==TRIGGER_BEFORE ? \"BEFORE\" : \"AFTER\"),\n        (pTrigger->op==TK_UPDATE ? \"UPDATE\" : \"\"),\n        (pTrigger->op==TK_INSERT ? \"INSERT\" : \"\"),\n        (pTrigger->op==TK_DELETE ? \"DELETE\" : \"\"),\n      pTab->zName\n    ));\n#ifndef SQLITE_OMIT_TRACE\n    sqlite3VdbeChangeP4(v, -1, \n      sqlite3MPrintf(db, \"-- TRIGGER %s\", pTrigger->zName), P4_DYNAMIC\n    );\n#endif\n\n    /* If one was specified, code the WHEN clause. If it evaluates to false\n    ** (or NULL) the sub-vdbe is immediately halted by jumping to the \n    ** OP_Halt inserted at the end of the program.  */\n    if( pTrigger->pWhen ){\n      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);\n      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) \n       && db->mallocFailed==0 \n      ){\n        iEndTrigger = sqlite3VdbeMakeLabel(v);\n        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);\n      }\n      sqlite3ExprDelete(db, pWhen);\n    }\n\n    /* Code the trigger program into the sub-vdbe. */\n    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);\n\n    /* Insert an OP_Halt at the end of the sub-program. */\n    if( iEndTrigger ){\n      sqlite3VdbeResolveLabel(v, iEndTrigger);\n    }\n    sqlite3VdbeAddOp0(v, OP_Halt);\n    VdbeComment((v, \"End: %s.%s\", pTrigger->zName, onErrorText(orconf)));\n\n    transferParseError(pParse, pSubParse);\n    if( db->mallocFailed==0 ){\n      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);\n    }\n    pProgram->nMem = pSubParse->nMem;\n    pProgram->nCsr = pSubParse->nTab;\n    pProgram->nOnce = pSubParse->nOnce;\n    pProgram->token = (void *)pTrigger;\n    pPrg->aColmask[0] = pSubParse->oldmask;\n    pPrg->aColmask[1] = pSubParse->newmask;\n    sqlite3VdbeDelete(v);\n  }\n\n  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );\n  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );\n  sqlite3StackFree(db, pSubParse);\n\n  return pPrg;\n}\n    \n/*\n** Return a pointer to a TriggerPrg object containing the sub-program for\n** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such\n** TriggerPrg object exists, a new object is allocated and populated before\n** being returned.\n*/\nstatic TriggerPrg *getRowTrigger(\n  Parse *pParse,       /* Current parse context */\n  Trigger *pTrigger,   /* Trigger to code */\n  Table *pTab,         /* The table trigger pTrigger is attached to */\n  int orconf           /* ON CONFLICT algorithm. */\n){\n  Parse *pRoot = sqlite3ParseToplevel(pParse);\n  TriggerPrg *pPrg;\n\n  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );\n\n  /* It may be that this trigger has already been coded (or is in the\n  ** process of being coded). If this is the case, then an entry with\n  ** a matching TriggerPrg.pTrigger field will be present somewhere\n  ** in the Parse.pTriggerPrg list. Search for such an entry.  */\n  for(pPrg=pRoot->pTriggerPrg; \n      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); \n      pPrg=pPrg->pNext\n  );\n\n  /* If an existing TriggerPrg could not be located, create a new one. */\n  if( !pPrg ){\n    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);\n  }\n\n  return pPrg;\n}\n\n/*\n** Generate code for the trigger program associated with trigger p on \n** table pTab. The reg, orconf and ignoreJump parameters passed to this\n** function are the same as those described in the header function for\n** sqlite3CodeRowTrigger()\n*/\nSQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(\n  Parse *pParse,       /* Parse context */\n  Trigger *p,          /* Trigger to code */\n  Table *pTab,         /* The table to code triggers from */\n  int reg,             /* Reg array containing OLD.* and NEW.* values */\n  int orconf,          /* ON CONFLICT policy */\n  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */\n){\n  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */\n  TriggerPrg *pPrg;\n  pPrg = getRowTrigger(pParse, p, pTab, orconf);\n  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );\n\n  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program \n  ** is a pointer to the sub-vdbe containing the trigger program.  */\n  if( pPrg ){\n    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));\n\n    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);\n    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);\n    VdbeComment(\n        (v, \"Call: %s.%s\", (p->zName?p->zName:\"fkey\"), onErrorText(orconf)));\n\n    /* Set the P5 operand of the OP_Program instruction to non-zero if\n    ** recursive invocation of this trigger program is disallowed. Recursive\n    ** invocation is disallowed if (a) the sub-program is really a trigger,\n    ** not a foreign key action, and (b) the flag to enable recursive triggers\n    ** is clear.  */\n    sqlite3VdbeChangeP5(v, (u8)bRecursive);\n  }\n}\n\n/*\n** This is called to code the required FOR EACH ROW triggers for an operation\n** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)\n** is given by the op paramater. The tr_tm parameter determines whether the\n** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then\n** parameter pChanges is passed the list of columns being modified.\n**\n** If there are no triggers that fire at the specified time for the specified\n** operation on pTab, this function is a no-op.\n**\n** The reg argument is the address of the first in an array of registers \n** that contain the values substituted for the new.* and old.* references\n** in the trigger program. If N is the number of columns in table pTab\n** (a copy of pTab->nCol), then registers are populated as follows:\n**\n**   Register       Contains\n**   ------------------------------------------------------\n**   reg+0          OLD.rowid\n**   reg+1          OLD.* value of left-most column of pTab\n**   ...            ...\n**   reg+N          OLD.* value of right-most column of pTab\n**   reg+N+1        NEW.rowid\n**   reg+N+2        OLD.* value of left-most column of pTab\n**   ...            ...\n**   reg+N+N+1      NEW.* value of right-most column of pTab\n**\n** For ON DELETE triggers, the registers containing the NEW.* values will\n** never be accessed by the trigger program, so they are not allocated or \n** populated by the caller (there is no data to populate them with anyway). \n** Similarly, for ON INSERT triggers the values stored in the OLD.* registers\n** are never accessed, and so are not allocated by the caller. So, for an\n** ON INSERT trigger, the value passed to this function as parameter reg\n** is not a readable register, although registers (reg+N) through \n** (reg+N+N+1) are.\n**\n** Parameter orconf is the default conflict resolution algorithm for the\n** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump\n** is the instruction that control should jump to if a trigger program\n** raises an IGNORE exception.\n*/\nSQLITE_PRIVATE void sqlite3CodeRowTrigger(\n  Parse *pParse,       /* Parse context */\n  Trigger *pTrigger,   /* List of triggers on table pTab */\n  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */\n  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */\n  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */\n  Table *pTab,         /* The table to code triggers from */\n  int reg,             /* The first in an array of registers (see above) */\n  int orconf,          /* ON CONFLICT policy */\n  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */\n){\n  Trigger *p;          /* Used to iterate through pTrigger list */\n\n  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );\n  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );\n  assert( (op==TK_UPDATE)==(pChanges!=0) );\n\n  for(p=pTrigger; p; p=p->pNext){\n\n    /* Sanity checking:  The schema for the trigger and for the table are\n    ** always defined.  The trigger must be in the same schema as the table\n    ** or else it must be a TEMP trigger. */\n    assert( p->pSchema!=0 );\n    assert( p->pTabSchema!=0 );\n    assert( p->pSchema==p->pTabSchema \n         || p->pSchema==pParse->db->aDb[1].pSchema );\n\n    /* Determine whether we should code this trigger */\n    if( p->op==op \n     && p->tr_tm==tr_tm \n     && checkColumnOverlap(p->pColumns, pChanges)\n    ){\n      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);\n    }\n  }\n}\n\n/*\n** Triggers may access values stored in the old.* or new.* pseudo-table. \n** This function returns a 32-bit bitmask indicating which columns of the \n** old.* or new.* tables actually are used by triggers. This information \n** may be used by the caller, for example, to avoid having to load the entire\n** old.* record into memory when executing an UPDATE or DELETE command.\n**\n** Bit 0 of the returned mask is set if the left-most column of the\n** table may be accessed using an [old|new].<col> reference. Bit 1 is set if\n** the second leftmost column value is required, and so on. If there\n** are more than 32 columns in the table, and at least one of the columns\n** with an index greater than 32 may be accessed, 0xffffffff is returned.\n**\n** It is not possible to determine if the old.rowid or new.rowid column is \n** accessed by triggers. The caller must always assume that it is.\n**\n** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned\n** applies to the old.* table. If 1, the new.* table.\n**\n** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE\n** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only\n** included in the returned mask if the TRIGGER_BEFORE bit is set in the\n** tr_tm parameter. Similarly, values accessed by AFTER triggers are only\n** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.\n*/\nSQLITE_PRIVATE u32 sqlite3TriggerColmask(\n  Parse *pParse,       /* Parse context */\n  Trigger *pTrigger,   /* List of triggers on table pTab */\n  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */\n  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */\n  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n  Table *pTab,         /* The table to code triggers from */\n  int orconf           /* Default ON CONFLICT policy for trigger steps */\n){\n  const int op = pChanges ? TK_UPDATE : TK_DELETE;\n  u32 mask = 0;\n  Trigger *p;\n\n  assert( isNew==1 || isNew==0 );\n  for(p=pTrigger; p; p=p->pNext){\n    if( p->op==op && (tr_tm&p->tr_tm)\n     && checkColumnOverlap(p->pColumns,pChanges)\n    ){\n      TriggerPrg *pPrg;\n      pPrg = getRowTrigger(pParse, p, pTab, orconf);\n      if( pPrg ){\n        mask |= pPrg->aColmask[isNew];\n      }\n    }\n  }\n\n  return mask;\n}\n\n#endif /* !defined(SQLITE_OMIT_TRIGGER) */\n\n/************** End of trigger.c *********************************************/\n/************** Begin file update.c ******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains C code routines that are called by the parser\n** to handle UPDATE statements.\n*/\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/* Forward declaration */\nstatic void updateVirtualTable(\n  Parse *pParse,       /* The parsing context */\n  SrcList *pSrc,       /* The virtual table to be modified */\n  Table *pTab,         /* The virtual table */\n  ExprList *pChanges,  /* The columns to change in the UPDATE statement */\n  Expr *pRowidExpr,    /* Expression used to recompute the rowid */\n  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */\n  Expr *pWhere,        /* WHERE clause of the UPDATE statement */\n  int onError          /* ON CONFLICT strategy */\n);\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** The most recently coded instruction was an OP_Column to retrieve the\n** i-th column of table pTab. This routine sets the P4 parameter of the \n** OP_Column to the default value, if any.\n**\n** The default value of a column is specified by a DEFAULT clause in the \n** column definition. This was either supplied by the user when the table\n** was created, or added later to the table definition by an ALTER TABLE\n** command. If the latter, then the row-records in the table btree on disk\n** may not contain a value for the column and the default value, taken\n** from the P4 parameter of the OP_Column instruction, is returned instead.\n** If the former, then all row-records are guaranteed to include a value\n** for the column and the P4 value is not required.\n**\n** Column definitions created by an ALTER TABLE command may only have \n** literal default values specified: a number, null or a string. (If a more\n** complicated default expression value was provided, it is evaluated \n** when the ALTER TABLE is executed and one of the literal values written\n** into the sqlite_master table.)\n**\n** Therefore, the P4 parameter is only required if the default value for\n** the column is a literal number, string or null. The sqlite3ValueFromExpr()\n** function is capable of transforming these types of expressions into\n** sqlite3_value objects.\n**\n** If parameter iReg is not negative, code an OP_RealAffinity instruction\n** on register iReg. This is used when an equivalent integer value is \n** stored in place of an 8-byte floating point value in order to save \n** space.\n*/\nSQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){\n  assert( pTab!=0 );\n  if( !pTab->pSelect ){\n    sqlite3_value *pValue;\n    u8 enc = ENC(sqlite3VdbeDb(v));\n    Column *pCol = &pTab->aCol[i];\n    VdbeComment((v, \"%s.%s\", pTab->zName, pCol->zName));\n    assert( i<pTab->nCol );\n    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, \n                         pCol->affinity, &pValue);\n    if( pValue ){\n      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);\n    }\n#ifndef SQLITE_OMIT_FLOATING_POINT\n    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){\n      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);\n    }\n#endif\n  }\n}\n\n/*\n** Process an UPDATE statement.\n**\n**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;\n**          \\_______/ \\________/     \\______/       \\________________/\n*            onError   pTabList      pChanges             pWhere\n*/\nSQLITE_PRIVATE void sqlite3Update(\n  Parse *pParse,         /* The parser context */\n  SrcList *pTabList,     /* The table in which we should change things */\n  ExprList *pChanges,    /* Things to be changed */\n  Expr *pWhere,          /* The WHERE clause.  May be null */\n  int onError            /* How to handle constraint errors */\n){\n  int i, j;              /* Loop counters */\n  Table *pTab;           /* The table to be updated */\n  int addr = 0;          /* VDBE instruction address of the start of the loop */\n  WhereInfo *pWInfo;     /* Information about the WHERE clause */\n  Vdbe *v;               /* The virtual database engine */\n  Index *pIdx;           /* For looping over indices */\n  int nIdx;              /* Number of indices that need updating */\n  int iCur;              /* VDBE Cursor number of pTab */\n  sqlite3 *db;           /* The database structure */\n  int *aRegIdx = 0;      /* One register assigned to each index to be updated */\n  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the\n                         ** an expression for the i-th column of the table.\n                         ** aXRef[i]==-1 if the i-th column is not changed. */\n  int chngRowid;         /* True if the record number is being changed */\n  Expr *pRowidExpr = 0;  /* Expression defining the new record number */\n  int openAll = 0;       /* True if all indices need to be opened */\n  AuthContext sContext;  /* The authorization context */\n  NameContext sNC;       /* The name-context to resolve expressions in */\n  int iDb;               /* Database containing the table being updated */\n  int okOnePass;         /* True for one-pass algorithm without the FIFO */\n  int hasFK;             /* True if foreign key processing is required */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  int isView;            /* True when updating a view (INSTEAD OF trigger) */\n  Trigger *pTrigger;     /* List of triggers on pTab, if required */\n  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */\n#endif\n  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */\n\n  /* Register Allocations */\n  int regRowCount = 0;   /* A count of rows changed */\n  int regOldRowid;       /* The old rowid */\n  int regNewRowid;       /* The new rowid */\n  int regNew;            /* Content of the NEW.* table in triggers */\n  int regOld = 0;        /* Content of OLD.* table in triggers */\n  int regRowSet = 0;     /* Rowset of rows to be updated */\n\n  memset(&sContext, 0, sizeof(sContext));\n  db = pParse->db;\n  if( pParse->nErr || db->mallocFailed ){\n    goto update_cleanup;\n  }\n  assert( pTabList->nSrc==1 );\n\n  /* Locate the table which we want to update. \n  */\n  pTab = sqlite3SrcListLookup(pParse, pTabList);\n  if( pTab==0 ) goto update_cleanup;\n  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);\n\n  /* Figure out if we have any triggers and if the table being\n  ** updated is a view.\n  */\n#ifndef SQLITE_OMIT_TRIGGER\n  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);\n  isView = pTab->pSelect!=0;\n  assert( pTrigger || tmask==0 );\n#else\n# define pTrigger 0\n# define isView 0\n# define tmask 0\n#endif\n#ifdef SQLITE_OMIT_VIEW\n# undef isView\n# define isView 0\n#endif\n\n  if( sqlite3ViewGetColumnNames(pParse, pTab) ){\n    goto update_cleanup;\n  }\n  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){\n    goto update_cleanup;\n  }\n  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );\n  if( aXRef==0 ) goto update_cleanup;\n  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;\n\n  /* Allocate a cursors for the main database table and for all indices.\n  ** The index cursors might not be used, but if they are used they\n  ** need to occur right after the database cursor.  So go ahead and\n  ** allocate enough space, just in case.\n  */\n  pTabList->a[0].iCursor = iCur = pParse->nTab++;\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    pParse->nTab++;\n  }\n\n  /* Initialize the name-context */\n  memset(&sNC, 0, sizeof(sNC));\n  sNC.pParse = pParse;\n  sNC.pSrcList = pTabList;\n\n  /* Resolve the column names in all the expressions of the\n  ** of the UPDATE statement.  Also find the column index\n  ** for each column to be updated in the pChanges array.  For each\n  ** column to be updated, make sure we have authorization to change\n  ** that column.\n  */\n  chngRowid = 0;\n  for(i=0; i<pChanges->nExpr; i++){\n    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){\n      goto update_cleanup;\n    }\n    for(j=0; j<pTab->nCol; j++){\n      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){\n        if( j==pTab->iPKey ){\n          chngRowid = 1;\n          pRowidExpr = pChanges->a[i].pExpr;\n        }\n        aXRef[j] = i;\n        break;\n      }\n    }\n    if( j>=pTab->nCol ){\n      if( sqlite3IsRowid(pChanges->a[i].zName) ){\n        chngRowid = 1;\n        pRowidExpr = pChanges->a[i].pExpr;\n      }else{\n        sqlite3ErrorMsg(pParse, \"no such column: %s\", pChanges->a[i].zName);\n        pParse->checkSchema = 1;\n        goto update_cleanup;\n      }\n    }\n#ifndef SQLITE_OMIT_AUTHORIZATION\n    {\n      int rc;\n      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,\n                           pTab->aCol[j].zName, db->aDb[iDb].zName);\n      if( rc==SQLITE_DENY ){\n        goto update_cleanup;\n      }else if( rc==SQLITE_IGNORE ){\n        aXRef[j] = -1;\n      }\n    }\n#endif\n  }\n\n  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);\n\n  /* Allocate memory for the array aRegIdx[].  There is one entry in the\n  ** array for each index associated with table being updated.  Fill in\n  ** the value with a register number for indices that are to be used\n  ** and with zero for unused indices.\n  */\n  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}\n  if( nIdx>0 ){\n    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );\n    if( aRegIdx==0 ) goto update_cleanup;\n  }\n  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){\n    int reg;\n    if( hasFK || chngRowid ){\n      reg = ++pParse->nMem;\n    }else{\n      reg = 0;\n      for(i=0; i<pIdx->nColumn; i++){\n        if( aXRef[pIdx->aiColumn[i]]>=0 ){\n          reg = ++pParse->nMem;\n          break;\n        }\n      }\n    }\n    aRegIdx[j] = reg;\n  }\n\n  /* Begin generating code. */\n  v = sqlite3GetVdbe(pParse);\n  if( v==0 ) goto update_cleanup;\n  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);\n  sqlite3BeginWriteOperation(pParse, 1, iDb);\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  /* Virtual tables must be handled separately */\n  if( IsVirtual(pTab) ){\n    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,\n                       pWhere, onError);\n    pWhere = 0;\n    pTabList = 0;\n    goto update_cleanup;\n  }\n#endif\n\n  /* Allocate required registers. */\n  regRowSet = ++pParse->nMem;\n  regOldRowid = regNewRowid = ++pParse->nMem;\n  if( pTrigger || hasFK ){\n    regOld = pParse->nMem + 1;\n    pParse->nMem += pTab->nCol;\n  }\n  if( chngRowid || pTrigger || hasFK ){\n    regNewRowid = ++pParse->nMem;\n  }\n  regNew = pParse->nMem + 1;\n  pParse->nMem += pTab->nCol;\n\n  /* Start the view context. */\n  if( isView ){\n    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);\n  }\n\n  /* If we are trying to update a view, realize that view into\n  ** a ephemeral table.\n  */\n#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)\n  if( isView ){\n    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);\n  }\n#endif\n\n  /* Resolve the column names in all the expressions in the\n  ** WHERE clause.\n  */\n  if( sqlite3ResolveExprNames(&sNC, pWhere) ){\n    goto update_cleanup;\n  }\n\n  /* Begin the database scan\n  */\n  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);\n  pWInfo = sqlite3WhereBegin(\n      pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0\n  );\n  if( pWInfo==0 ) goto update_cleanup;\n  okOnePass = pWInfo->okOnePass;\n\n  /* Remember the rowid of every item to be updated.\n  */\n  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);\n  if( !okOnePass ){\n    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);\n  }\n\n  /* End the database scan loop.\n  */\n  sqlite3WhereEnd(pWInfo);\n\n  /* Initialize the count of updated rows\n  */\n  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){\n    regRowCount = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);\n  }\n\n  if( !isView ){\n    /* \n    ** Open every index that needs updating.  Note that if any\n    ** index could potentially invoke a REPLACE conflict resolution \n    ** action, then we need to open all indices because we might need\n    ** to be deleting some records.\n    */\n    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); \n    if( onError==OE_Replace ){\n      openAll = 1;\n    }else{\n      openAll = 0;\n      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n        if( pIdx->onError==OE_Replace ){\n          openAll = 1;\n          break;\n        }\n      }\n    }\n    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){\n      assert( aRegIdx );\n      if( openAll || aRegIdx[i]>0 ){\n        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);\n        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,\n                       (char*)pKey, P4_KEYINFO_HANDOFF);\n        assert( pParse->nTab>iCur+i+1 );\n      }\n    }\n  }\n\n  /* Top of the update loop */\n  if( okOnePass ){\n    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);\n    addr = sqlite3VdbeAddOp0(v, OP_Goto);\n    sqlite3VdbeJumpHere(v, a1);\n  }else{\n    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);\n  }\n\n  /* Make cursor iCur point to the record that is being updated. If\n  ** this record does not exist for some reason (deleted by a trigger,\n  ** for example, then jump to the next iteration of the RowSet loop.  */\n  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);\n\n  /* If the record number will change, set register regNewRowid to\n  ** contain the new value. If the record number is not being modified,\n  ** then regNewRowid is the same register as regOldRowid, which is\n  ** already populated.  */\n  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );\n  if( chngRowid ){\n    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);\n    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);\n  }\n\n  /* If there are triggers on this table, populate an array of registers \n  ** with the required old.* column data.  */\n  if( hasFK || pTrigger ){\n    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);\n    oldmask |= sqlite3TriggerColmask(pParse, \n        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError\n    );\n    for(i=0; i<pTab->nCol; i++){\n      if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){\n        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);\n      }\n    }\n    if( chngRowid==0 ){\n      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);\n    }\n  }\n\n  /* Populate the array of registers beginning at regNew with the new\n  ** row data. This array is used to check constaints, create the new\n  ** table and index records, and as the values for any new.* references\n  ** made by triggers.\n  **\n  ** If there are one or more BEFORE triggers, then do not populate the\n  ** registers associated with columns that are (a) not modified by\n  ** this UPDATE statement and (b) not accessed by new.* references. The\n  ** values for registers not modified by the UPDATE must be reloaded from \n  ** the database after the BEFORE triggers are fired anyway (as the trigger \n  ** may have modified them). So not loading those that are not going to\n  ** be used eliminates some redundant opcodes.\n  */\n  newmask = sqlite3TriggerColmask(\n      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError\n  );\n  sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);\n  for(i=0; i<pTab->nCol; i++){\n    if( i==pTab->iPKey ){\n      /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/\n    }else{\n      j = aXRef[i];\n      if( j>=0 ){\n        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);\n      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){\n        /* This branch loads the value of a column that will not be changed \n        ** into a register. This is done if there are no BEFORE triggers, or\n        ** if there are one or more BEFORE triggers that use this value via\n        ** a new.* reference in a trigger program.\n        */\n        testcase( i==31 );\n        testcase( i==32 );\n        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);\n        sqlite3ColumnDefault(v, pTab, i, regNew+i);\n      }\n    }\n  }\n\n  /* Fire any BEFORE UPDATE triggers. This happens before constraints are\n  ** verified. One could argue that this is wrong.\n  */\n  if( tmask&TRIGGER_BEFORE ){\n    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);\n    sqlite3TableAffinityStr(v, pTab);\n    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, \n        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);\n\n    /* The row-trigger may have deleted the row being updated. In this\n    ** case, jump to the next row. No updates or AFTER triggers are \n    ** required. This behaviour - what happens when the row being updated\n    ** is deleted or renamed by a BEFORE trigger - is left undefined in the\n    ** documentation.\n    */\n    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);\n\n    /* If it did not delete it, the row-trigger may still have modified \n    ** some of the columns of the row being updated. Load the values for \n    ** all columns not modified by the update statement into their \n    ** registers in case this has happened.\n    */\n    for(i=0; i<pTab->nCol; i++){\n      if( aXRef[i]<0 && i!=pTab->iPKey ){\n        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);\n        sqlite3ColumnDefault(v, pTab, i, regNew+i);\n      }\n    }\n  }\n\n  if( !isView ){\n    int j1;                       /* Address of jump instruction */\n\n    /* Do constraint checks. */\n    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,\n        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);\n\n    /* Do FK constraint checks. */\n    if( hasFK ){\n      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);\n    }\n\n    /* Delete the index entries associated with the current record.  */\n    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);\n    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);\n  \n    /* If changing the record number, delete the old record.  */\n    if( hasFK || chngRowid ){\n      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);\n    }\n    sqlite3VdbeJumpHere(v, j1);\n\n    if( hasFK ){\n      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);\n    }\n  \n    /* Insert the new index entries and the new record. */\n    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);\n\n    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to\n    ** handle rows (possibly in other tables) that refer via a foreign key\n    ** to the row just updated. */ \n    if( hasFK ){\n      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);\n    }\n  }\n\n  /* Increment the row counter \n  */\n  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){\n    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);\n  }\n\n  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, \n      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);\n\n  /* Repeat the above with the next record to be updated, until\n  ** all record selected by the WHERE clause have been updated.\n  */\n  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);\n  sqlite3VdbeJumpHere(v, addr);\n\n  /* Close all tables */\n  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){\n    assert( aRegIdx );\n    if( openAll || aRegIdx[i]>0 ){\n      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);\n    }\n  }\n  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);\n\n  /* Update the sqlite_sequence table by storing the content of the\n  ** maximum rowid counter values recorded while inserting into\n  ** autoincrement tables.\n  */\n  if( pParse->nested==0 && pParse->pTriggerTab==0 ){\n    sqlite3AutoincrementEnd(pParse);\n  }\n\n  /*\n  ** Return the number of rows that were changed. If this routine is \n  ** generating code because of a call to sqlite3NestedParse(), do not\n  ** invoke the callback function.\n  */\n  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){\n    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);\n    sqlite3VdbeSetNumCols(v, 1);\n    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, \"rows updated\", SQLITE_STATIC);\n  }\n\nupdate_cleanup:\n  sqlite3AuthContextPop(&sContext);\n  sqlite3DbFree(db, aRegIdx);\n  sqlite3DbFree(db, aXRef);\n  sqlite3SrcListDelete(db, pTabList);\n  sqlite3ExprListDelete(db, pChanges);\n  sqlite3ExprDelete(db, pWhere);\n  return;\n}\n/* Make sure \"isView\" and other macros defined above are undefined. Otherwise\n** thely may interfere with compilation of other functions in this file\n** (or in another file, if this file becomes part of the amalgamation).  */\n#ifdef isView\n #undef isView\n#endif\n#ifdef pTrigger\n #undef pTrigger\n#endif\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Generate code for an UPDATE of a virtual table.\n**\n** The strategy is that we create an ephemerial table that contains\n** for each row to be changed:\n**\n**   (A)  The original rowid of that row.\n**   (B)  The revised rowid for the row. (note1)\n**   (C)  The content of every column in the row.\n**\n** Then we loop over this ephemeral table and for each row in\n** the ephermeral table call VUpdate.\n**\n** When finished, drop the ephemeral table.\n**\n** (note1) Actually, if we know in advance that (A) is always the same\n** as (B) we only store (A), then duplicate (A) when pulling\n** it out of the ephemeral table before calling VUpdate.\n*/\nstatic void updateVirtualTable(\n  Parse *pParse,       /* The parsing context */\n  SrcList *pSrc,       /* The virtual table to be modified */\n  Table *pTab,         /* The virtual table */\n  ExprList *pChanges,  /* The columns to change in the UPDATE statement */\n  Expr *pRowid,        /* Expression used to recompute the rowid */\n  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */\n  Expr *pWhere,        /* WHERE clause of the UPDATE statement */\n  int onError          /* ON CONFLICT strategy */\n){\n  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */\n  ExprList *pEList = 0;     /* The result set of the SELECT statement */\n  Select *pSelect = 0;      /* The SELECT statement */\n  Expr *pExpr;              /* Temporary expression */\n  int ephemTab;             /* Table holding the result of the SELECT */\n  int i;                    /* Loop counter */\n  int addr;                 /* Address of top of loop */\n  int iReg;                 /* First register in set passed to OP_VUpdate */\n  sqlite3 *db = pParse->db; /* Database connection */\n  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);\n  SelectDest dest;\n\n  /* Construct the SELECT statement that will find the new values for\n  ** all updated rows. \n  */\n  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, \"_rowid_\"));\n  if( pRowid ){\n    pEList = sqlite3ExprListAppend(pParse, pEList,\n                                   sqlite3ExprDup(db, pRowid, 0));\n  }\n  assert( pTab->iPKey<0 );\n  for(i=0; i<pTab->nCol; i++){\n    if( aXRef[i]>=0 ){\n      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);\n    }else{\n      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);\n    }\n    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);\n  }\n  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);\n  \n  /* Create the ephemeral table into which the update results will\n  ** be stored.\n  */\n  assert( v );\n  ephemTab = pParse->nTab++;\n  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));\n  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);\n\n  /* fill the ephemeral table \n  */\n  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);\n  sqlite3Select(pParse, pSelect, &dest);\n\n  /* Generate code to scan the ephemeral table and call VUpdate. */\n  iReg = ++pParse->nMem;\n  pParse->nMem += pTab->nCol+1;\n  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);\n  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);\n  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);\n  for(i=0; i<pTab->nCol; i++){\n    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);\n  }\n  sqlite3VtabMakeWritable(pParse, pTab);\n  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);\n  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);\n  sqlite3MayAbort(pParse);\n  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);\n  sqlite3VdbeJumpHere(v, addr);\n  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);\n\n  /* Cleanup */\n  sqlite3SelectDelete(db, pSelect);  \n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/************** End of update.c **********************************************/\n/************** Begin file vacuum.c ******************************************/\n/*\n** 2003 April 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to implement the VACUUM command.\n**\n** Most of the code in this file may be omitted by defining the\n** SQLITE_OMIT_VACUUM macro.\n*/\n\n#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)\n/*\n** Finalize a prepared statement.  If there was an error, store the\n** text of the error message in *pzErrMsg.  Return the result code.\n*/\nstatic int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){\n  int rc;\n  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);\n  if( rc ){\n    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));\n  }\n  return rc;\n}\n\n/*\n** Execute zSql on database db. Return an error code.\n*/\nstatic int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){\n  sqlite3_stmt *pStmt;\n  VVA_ONLY( int rc; )\n  if( !zSql ){\n    return SQLITE_NOMEM;\n  }\n  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){\n    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));\n    return sqlite3_errcode(db);\n  }\n  VVA_ONLY( rc = ) sqlite3_step(pStmt);\n  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );\n  return vacuumFinalize(db, pStmt, pzErrMsg);\n}\n\n/*\n** Execute zSql on database db. The statement returns exactly\n** one column. Execute this as SQL on the same database.\n*/\nstatic int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){\n  sqlite3_stmt *pStmt;\n  int rc;\n\n  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  while( SQLITE_ROW==sqlite3_step(pStmt) ){\n    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));\n    if( rc!=SQLITE_OK ){\n      vacuumFinalize(db, pStmt, pzErrMsg);\n      return rc;\n    }\n  }\n\n  return vacuumFinalize(db, pStmt, pzErrMsg);\n}\n\n/*\n** The non-standard VACUUM command is used to clean up the database,\n** collapse free space, etc.  It is modelled after the VACUUM command\n** in PostgreSQL.\n**\n** In version 1.0.x of SQLite, the VACUUM command would call\n** gdbm_reorganize() on all the database tables.  But beginning\n** with 2.0.0, SQLite no longer uses GDBM so this command has\n** become a no-op.\n*/\nSQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){\n  Vdbe *v = sqlite3GetVdbe(pParse);\n  if( v ){\n    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);\n  }\n  return;\n}\n\n/*\n** This routine implements the OP_Vacuum opcode of the VDBE.\n*/\nSQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){\n  int rc = SQLITE_OK;     /* Return code from service routines */\n  Btree *pMain;           /* The database being vacuumed */\n  Btree *pTemp;           /* The temporary database we vacuum into */\n  char *zSql = 0;         /* SQL statements */\n  int saved_flags;        /* Saved value of the db->flags */\n  int saved_nChange;      /* Saved value of db->nChange */\n  int saved_nTotalChange; /* Saved value of db->nTotalChange */\n  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */\n  Db *pDb = 0;            /* Database to detach at end of vacuum */\n  int isMemDb;            /* True if vacuuming a :memory: database */\n  int nRes;               /* Bytes of reserved space at the end of each page */\n  int nDb;                /* Number of attached databases */\n\n  if( !db->autoCommit ){\n    sqlite3SetString(pzErrMsg, db, \"cannot VACUUM from within a transaction\");\n    return SQLITE_ERROR;\n  }\n  if( db->activeVdbeCnt>1 ){\n    sqlite3SetString(pzErrMsg, db,\"cannot VACUUM - SQL statements in progress\");\n    return SQLITE_ERROR;\n  }\n\n  /* Save the current value of the database flags so that it can be \n  ** restored before returning. Then set the writable-schema flag, and\n  ** disable CHECK and foreign key constraints.  */\n  saved_flags = db->flags;\n  saved_nChange = db->nChange;\n  saved_nTotalChange = db->nTotalChange;\n  saved_xTrace = db->xTrace;\n  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;\n  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);\n  db->xTrace = 0;\n\n  pMain = db->aDb[0].pBt;\n  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));\n\n  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma\n  ** can be set to 'off' for this file, as it is not recovered if a crash\n  ** occurs anyway. The integrity of the database is maintained by a\n  ** (possibly synchronous) transaction opened on the main database before\n  ** sqlite3BtreeCopyFile() is called.\n  **\n  ** An optimisation would be to use a non-journaled pager.\n  ** (Later:) I tried setting \"PRAGMA vacuum_db.journal_mode=OFF\" but\n  ** that actually made the VACUUM run slower.  Very little journalling\n  ** actually occurs when doing a vacuum since the vacuum_db is initially\n  ** empty.  Only the journal header is written.  Apparently it takes more\n  ** time to parse and run the PRAGMA to turn journalling off than it does\n  ** to write the journal header file.\n  */\n  nDb = db->nDb;\n  if( sqlite3TempInMemory(db) ){\n    zSql = \"ATTACH ':memory:' AS vacuum_db;\";\n  }else{\n    zSql = \"ATTACH '' AS vacuum_db;\";\n  }\n  rc = execSql(db, pzErrMsg, zSql);\n  if( db->nDb>nDb ){\n    pDb = &db->aDb[db->nDb-1];\n    assert( strcmp(pDb->zName,\"vacuum_db\")==0 );\n  }\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  pTemp = db->aDb[db->nDb-1].pBt;\n\n  /* The call to execSql() to attach the temp database has left the file\n  ** locked (as there was more than one active statement when the transaction\n  ** to read the schema was concluded. Unlock it here so that this doesn't\n  ** cause problems for the call to BtreeSetPageSize() below.  */\n  sqlite3BtreeCommit(pTemp);\n\n  nRes = sqlite3BtreeGetReserve(pMain);\n\n  /* A VACUUM cannot change the pagesize of an encrypted database. */\n#ifdef SQLITE_HAS_CODEC\n  if( db->nextPagesize ){\n    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);\n    int nKey;\n    char *zKey;\n    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);\n    if( nKey ) db->nextPagesize = 0;\n  }\n#endif\n\n  rc = execSql(db, pzErrMsg, \"PRAGMA vacuum_db.synchronous=OFF\");\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Begin a transaction and take an exclusive lock on the main database\n  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,\n  ** to ensure that we do not try to change the page-size on a WAL database.\n  */\n  rc = execSql(db, pzErrMsg, \"BEGIN;\");\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = sqlite3BtreeBeginTrans(pMain, 2);\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Do not attempt to change the page size for a WAL database */\n  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))\n                                               ==PAGER_JOURNALMODE_WAL ){\n    db->nextPagesize = 0;\n  }\n\n  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)\n   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))\n   || NEVER(db->mallocFailed)\n  ){\n    rc = SQLITE_NOMEM;\n    goto end_of_vacuum;\n  }\n\n#ifndef SQLITE_OMIT_AUTOVACUUM\n  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :\n                                           sqlite3BtreeGetAutoVacuum(pMain));\n#endif\n\n  /* Query the schema of the main database. Create a mirror schema\n  ** in the temporary database.\n  */\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) \"\n      \"  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'\"\n      \"   AND rootpage>0\"\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)\"\n      \"  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' \");\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) \"\n      \"  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'\");\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Loop through the tables in the main database. For each, do\n  ** an \"INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;\" to copy\n  ** the contents to the temporary database.\n  */\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'INSERT INTO vacuum_db.' || quote(name) \"\n      \"|| ' SELECT * FROM main.' || quote(name) || ';'\"\n      \"FROM main.sqlite_master \"\n      \"WHERE type = 'table' AND name!='sqlite_sequence' \"\n      \"  AND rootpage>0\"\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n  /* Copy over the sequence table\n  */\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' \"\n      \"FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' \"\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n  rc = execExecSql(db, pzErrMsg,\n      \"SELECT 'INSERT INTO vacuum_db.' || quote(name) \"\n      \"|| ' SELECT * FROM main.' || quote(name) || ';' \"\n      \"FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';\"\n  );\n  if( rc!=SQLITE_OK ) goto end_of_vacuum;\n\n\n  /* Copy the triggers, views, and virtual tables from the main database\n  ** over to the temporary database.  None of these objects has any\n  ** associated storage, so all we have to do is copy their entries\n  ** from the SQLITE_MASTER table.\n  */\n  rc = execSql(db, pzErrMsg,\n      \"INSERT INTO vacuum_db.sqlite_master \"\n      \"  SELECT type, name, tbl_name, rootpage, sql\"\n      \"    FROM main.sqlite_master\"\n      \"   WHERE type='view' OR type='trigger'\"\n      \"      OR (type='table' AND rootpage=0)\"\n  );\n  if( rc ) goto end_of_vacuum;\n\n  /* At this point, there is a write transaction open on both the \n  ** vacuum database and the main database. Assuming no error occurs,\n  ** both transactions are closed by this block - the main database\n  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit\n  ** call to sqlite3BtreeCommit().\n  */\n  {\n    u32 meta;\n    int i;\n\n    /* This array determines which meta meta values are preserved in the\n    ** vacuum.  Even entries are the meta value number and odd entries\n    ** are an increment to apply to the meta value after the vacuum.\n    ** The increment is used to increase the schema cookie so that other\n    ** connections to the same database will know to reread the schema.\n    */\n    static const unsigned char aCopy[] = {\n       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */\n       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */\n       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */\n       BTREE_USER_VERSION,       0,  /* Preserve the user version */\n    };\n\n    assert( 1==sqlite3BtreeIsInTrans(pTemp) );\n    assert( 1==sqlite3BtreeIsInTrans(pMain) );\n\n    /* Copy Btree meta values */\n    for(i=0; i<ArraySize(aCopy); i+=2){\n      /* GetMeta() and UpdateMeta() cannot fail in this context because\n      ** we already have page 1 loaded into cache and marked dirty. */\n      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);\n      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);\n      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;\n    }\n\n    rc = sqlite3BtreeCopyFile(pMain, pTemp);\n    if( rc!=SQLITE_OK ) goto end_of_vacuum;\n    rc = sqlite3BtreeCommit(pTemp);\n    if( rc!=SQLITE_OK ) goto end_of_vacuum;\n#ifndef SQLITE_OMIT_AUTOVACUUM\n    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));\n#endif\n  }\n\n  assert( rc==SQLITE_OK );\n  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);\n\nend_of_vacuum:\n  /* Restore the original value of db->flags */\n  db->flags = saved_flags;\n  db->nChange = saved_nChange;\n  db->nTotalChange = saved_nTotalChange;\n  db->xTrace = saved_xTrace;\n  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);\n\n  /* Currently there is an SQL level transaction open on the vacuum\n  ** database. No locks are held on any other files (since the main file\n  ** was committed at the btree level). So it safe to end the transaction\n  ** by manually setting the autoCommit flag to true and detaching the\n  ** vacuum database. The vacuum_db journal file is deleted when the pager\n  ** is closed by the DETACH.\n  */\n  db->autoCommit = 1;\n\n  if( pDb ){\n    sqlite3BtreeClose(pDb->pBt);\n    pDb->pBt = 0;\n    pDb->pSchema = 0;\n  }\n\n  /* This both clears the schemas and reduces the size of the db->aDb[]\n  ** array. */ \n  sqlite3ResetAllSchemasOfConnection(db);\n\n  return rc;\n}\n\n#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */\n\n/************** End of vacuum.c **********************************************/\n/************** Begin file vtab.c ********************************************/\n/*\n** 2006 June 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code used to help implement virtual tables.\n*/\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n\n/*\n** Before a virtual table xCreate() or xConnect() method is invoked, the\n** sqlite3.pVtabCtx member variable is set to point to an instance of\n** this struct allocated on the stack. It is used by the implementation of \n** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which\n** are invoked only from within xCreate and xConnect methods.\n*/\nstruct VtabCtx {\n  VTable *pVTable;    /* The virtual table being constructed */\n  Table *pTab;        /* The Table object to which the virtual table belongs */\n};\n\n/*\n** The actual function that does the work of creating a new module.\n** This function implements the sqlite3_create_module() and\n** sqlite3_create_module_v2() interfaces.\n*/\nstatic int createModule(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux,                     /* Context pointer for xCreate/xConnect */\n  void (*xDestroy)(void *)        /* Module destructor function */\n){\n  int rc = SQLITE_OK;\n  int nName;\n\n  sqlite3_mutex_enter(db->mutex);\n  nName = sqlite3Strlen30(zName);\n  if( sqlite3HashFind(&db->aModule, zName, nName) ){\n    rc = SQLITE_MISUSE_BKPT;\n  }else{\n    Module *pMod;\n    pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);\n    if( pMod ){\n      Module *pDel;\n      char *zCopy = (char *)(&pMod[1]);\n      memcpy(zCopy, zName, nName+1);\n      pMod->zName = zCopy;\n      pMod->pModule = pModule;\n      pMod->pAux = pAux;\n      pMod->xDestroy = xDestroy;\n      pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);\n      assert( pDel==0 || pDel==pMod );\n      if( pDel ){\n        db->mallocFailed = 1;\n        sqlite3DbFree(db, pDel);\n      }\n    }\n  }\n  rc = sqlite3ApiExit(db, rc);\n  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);\n\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n\n/*\n** External API function used to create a new virtual-table module.\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux                      /* Context pointer for xCreate/xConnect */\n){\n  return createModule(db, zName, pModule, pAux, 0);\n}\n\n/*\n** External API function used to create a new virtual-table module.\n*/\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,                    /* Database in which module is registered */\n  const char *zName,              /* Name assigned to this module */\n  const sqlite3_module *pModule,  /* The definition of the module */\n  void *pAux,                     /* Context pointer for xCreate/xConnect */\n  void (*xDestroy)(void *)        /* Module destructor function */\n){\n  return createModule(db, zName, pModule, pAux, xDestroy);\n}\n\n/*\n** Lock the virtual table so that it cannot be disconnected.\n** Locks nest.  Every lock should have a corresponding unlock.\n** If an unlock is omitted, resources leaks will occur.  \n**\n** If a disconnect is attempted while a virtual table is locked,\n** the disconnect is deferred until all locks have been removed.\n*/\nSQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){\n  pVTab->nRef++;\n}\n\n\n/*\n** pTab is a pointer to a Table structure representing a virtual-table.\n** Return a pointer to the VTable object used by connection db to access \n** this virtual-table, if one has been created, or NULL otherwise.\n*/\nSQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){\n  VTable *pVtab;\n  assert( IsVirtual(pTab) );\n  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);\n  return pVtab;\n}\n\n/*\n** Decrement the ref-count on a virtual table object. When the ref-count\n** reaches zero, call the xDisconnect() method to delete the object.\n*/\nSQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){\n  sqlite3 *db = pVTab->db;\n\n  assert( db );\n  assert( pVTab->nRef>0 );\n  assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );\n\n  pVTab->nRef--;\n  if( pVTab->nRef==0 ){\n    sqlite3_vtab *p = pVTab->pVtab;\n    if( p ){\n      p->pModule->xDisconnect(p);\n    }\n    sqlite3DbFree(db, pVTab);\n  }\n}\n\n/*\n** Table p is a virtual table. This function moves all elements in the\n** p->pVTable list to the sqlite3.pDisconnect lists of their associated\n** database connections to be disconnected at the next opportunity. \n** Except, if argument db is not NULL, then the entry associated with\n** connection db is left in the p->pVTable list.\n*/\nstatic VTable *vtabDisconnectAll(sqlite3 *db, Table *p){\n  VTable *pRet = 0;\n  VTable *pVTable = p->pVTable;\n  p->pVTable = 0;\n\n  /* Assert that the mutex (if any) associated with the BtShared database \n  ** that contains table p is held by the caller. See header comments \n  ** above function sqlite3VtabUnlockList() for an explanation of why\n  ** this makes it safe to access the sqlite3.pDisconnect list of any\n  ** database connection that may have an entry in the p->pVTable list.\n  */\n  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );\n\n  while( pVTable ){\n    sqlite3 *db2 = pVTable->db;\n    VTable *pNext = pVTable->pNext;\n    assert( db2 );\n    if( db2==db ){\n      pRet = pVTable;\n      p->pVTable = pRet;\n      pRet->pNext = 0;\n    }else{\n      pVTable->pNext = db2->pDisconnect;\n      db2->pDisconnect = pVTable;\n    }\n    pVTable = pNext;\n  }\n\n  assert( !db || pRet );\n  return pRet;\n}\n\n/*\n** Table *p is a virtual table. This function removes the VTable object\n** for table *p associated with database connection db from the linked\n** list in p->pVTab. It also decrements the VTable ref count. This is\n** used when closing database connection db to free all of its VTable\n** objects without disturbing the rest of the Schema object (which may\n** be being used by other shared-cache connections).\n*/\nSQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){\n  VTable **ppVTab;\n\n  assert( IsVirtual(p) );\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){\n    if( (*ppVTab)->db==db  ){\n      VTable *pVTab = *ppVTab;\n      *ppVTab = pVTab->pNext;\n      sqlite3VtabUnlock(pVTab);\n      break;\n    }\n  }\n}\n\n\n/*\n** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.\n**\n** This function may only be called when the mutexes associated with all\n** shared b-tree databases opened using connection db are held by the \n** caller. This is done to protect the sqlite3.pDisconnect list. The\n** sqlite3.pDisconnect list is accessed only as follows:\n**\n**   1) By this function. In this case, all BtShared mutexes and the mutex\n**      associated with the database handle itself must be held.\n**\n**   2) By function vtabDisconnectAll(), when it adds a VTable entry to\n**      the sqlite3.pDisconnect list. In this case either the BtShared mutex\n**      associated with the database the virtual table is stored in is held\n**      or, if the virtual table is stored in a non-sharable database, then\n**      the database handle mutex is held.\n**\n** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously \n** by multiple threads. It is thread-safe.\n*/\nSQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){\n  VTable *p = db->pDisconnect;\n  db->pDisconnect = 0;\n\n  assert( sqlite3BtreeHoldsAllMutexes(db) );\n  assert( sqlite3_mutex_held(db->mutex) );\n\n  if( p ){\n    sqlite3ExpirePreparedStatements(db);\n    do {\n      VTable *pNext = p->pNext;\n      sqlite3VtabUnlock(p);\n      p = pNext;\n    }while( p );\n  }\n}\n\n/*\n** Clear any and all virtual-table information from the Table record.\n** This routine is called, for example, just before deleting the Table\n** record.\n**\n** Since it is a virtual-table, the Table structure contains a pointer\n** to the head of a linked list of VTable structures. Each VTable \n** structure is associated with a single sqlite3* user of the schema.\n** The reference count of the VTable structure associated with database \n** connection db is decremented immediately (which may lead to the \n** structure being xDisconnected and free). Any other VTable structures\n** in the list are moved to the sqlite3.pDisconnect list of the associated \n** database connection.\n*/\nSQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){\n  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);\n  if( p->azModuleArg ){\n    int i;\n    for(i=0; i<p->nModuleArg; i++){\n      sqlite3DbFree(db, p->azModuleArg[i]);\n    }\n    sqlite3DbFree(db, p->azModuleArg);\n  }\n}\n\n/*\n** Add a new module argument to pTable->azModuleArg[].\n** The string is not copied - the pointer is stored.  The\n** string will be freed automatically when the table is\n** deleted.\n*/\nstatic void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){\n  int i = pTable->nModuleArg++;\n  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);\n  char **azModuleArg;\n  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);\n  if( azModuleArg==0 ){\n    int j;\n    for(j=0; j<i; j++){\n      sqlite3DbFree(db, pTable->azModuleArg[j]);\n    }\n    sqlite3DbFree(db, zArg);\n    sqlite3DbFree(db, pTable->azModuleArg);\n    pTable->nModuleArg = 0;\n  }else{\n    azModuleArg[i] = zArg;\n    azModuleArg[i+1] = 0;\n  }\n  pTable->azModuleArg = azModuleArg;\n}\n\n/*\n** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE\n** statement.  The module name has been parsed, but the optional list\n** of parameters that follow the module name are still pending.\n*/\nSQLITE_PRIVATE void sqlite3VtabBeginParse(\n  Parse *pParse,        /* Parsing context */\n  Token *pName1,        /* Name of new table, or database name */\n  Token *pName2,        /* Name of new table or NULL */\n  Token *pModuleName,   /* Name of the module for the virtual table */\n  int ifNotExists       /* No error if the table already exists */\n){\n  int iDb;              /* The database the table is being created in */\n  Table *pTable;        /* The new virtual table */\n  sqlite3 *db;          /* Database connection */\n\n  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);\n  pTable = pParse->pNewTable;\n  if( pTable==0 ) return;\n  assert( 0==pTable->pIndex );\n\n  db = pParse->db;\n  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);\n  assert( iDb>=0 );\n\n  pTable->tabFlags |= TF_Virtual;\n  pTable->nModuleArg = 0;\n  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));\n  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));\n  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));\n  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);\n\n#ifndef SQLITE_OMIT_AUTHORIZATION\n  /* Creating a virtual table invokes the authorization callback twice.\n  ** The first invocation, to obtain permission to INSERT a row into the\n  ** sqlite_master table, has already been made by sqlite3StartTable().\n  ** The second call, to obtain permission to create the table, is made now.\n  */\n  if( pTable->azModuleArg ){\n    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, \n            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);\n  }\n#endif\n}\n\n/*\n** This routine takes the module argument that has been accumulating\n** in pParse->zArg[] and appends it to the list of arguments on the\n** virtual table currently under construction in pParse->pTable.\n*/\nstatic void addArgumentToVtab(Parse *pParse){\n  if( pParse->sArg.z && pParse->pNewTable ){\n    const char *z = (const char*)pParse->sArg.z;\n    int n = pParse->sArg.n;\n    sqlite3 *db = pParse->db;\n    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));\n  }\n}\n\n/*\n** The parser calls this routine after the CREATE VIRTUAL TABLE statement\n** has been completely parsed.\n*/\nSQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){\n  Table *pTab = pParse->pNewTable;  /* The table being constructed */\n  sqlite3 *db = pParse->db;         /* The database connection */\n\n  if( pTab==0 ) return;\n  addArgumentToVtab(pParse);\n  pParse->sArg.z = 0;\n  if( pTab->nModuleArg<1 ) return;\n  \n  /* If the CREATE VIRTUAL TABLE statement is being entered for the\n  ** first time (in other words if the virtual table is actually being\n  ** created now instead of just being read out of sqlite_master) then\n  ** do additional initialization work and store the statement text\n  ** in the sqlite_master table.\n  */\n  if( !db->init.busy ){\n    char *zStmt;\n    char *zWhere;\n    int iDb;\n    Vdbe *v;\n\n    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */\n    if( pEnd ){\n      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;\n    }\n    zStmt = sqlite3MPrintf(db, \"CREATE VIRTUAL TABLE %T\", &pParse->sNameToken);\n\n    /* A slot for the record has already been allocated in the \n    ** SQLITE_MASTER table.  We just need to update that slot with all\n    ** the information we've collected.  \n    **\n    ** The VM register number pParse->regRowid holds the rowid of an\n    ** entry in the sqlite_master table tht was created for this vtab\n    ** by sqlite3StartTable().\n    */\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    sqlite3NestedParse(pParse,\n      \"UPDATE %Q.%s \"\n         \"SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q \"\n       \"WHERE rowid=#%d\",\n      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),\n      pTab->zName,\n      pTab->zName,\n      zStmt,\n      pParse->regRowid\n    );\n    sqlite3DbFree(db, zStmt);\n    v = sqlite3GetVdbe(pParse);\n    sqlite3ChangeCookie(pParse, iDb);\n\n    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);\n    zWhere = sqlite3MPrintf(db, \"name='%q' AND type='table'\", pTab->zName);\n    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);\n    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, \n                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);\n  }\n\n  /* If we are rereading the sqlite_master table create the in-memory\n  ** record of the table. The xConnect() method is not called until\n  ** the first time the virtual table is used in an SQL statement. This\n  ** allows a schema that contains virtual tables to be loaded before\n  ** the required virtual table implementations are registered.  */\n  else {\n    Table *pOld;\n    Schema *pSchema = pTab->pSchema;\n    const char *zName = pTab->zName;\n    int nName = sqlite3Strlen30(zName);\n    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );\n    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);\n    if( pOld ){\n      db->mallocFailed = 1;\n      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */\n      return;\n    }\n    pParse->pNewTable = 0;\n  }\n}\n\n/*\n** The parser calls this routine when it sees the first token\n** of an argument to the module name in a CREATE VIRTUAL TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){\n  addArgumentToVtab(pParse);\n  pParse->sArg.z = 0;\n  pParse->sArg.n = 0;\n}\n\n/*\n** The parser calls this routine for each token after the first token\n** in an argument to the module name in a CREATE VIRTUAL TABLE statement.\n*/\nSQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){\n  Token *pArg = &pParse->sArg;\n  if( pArg->z==0 ){\n    pArg->z = p->z;\n    pArg->n = p->n;\n  }else{\n    assert(pArg->z < p->z);\n    pArg->n = (int)(&p->z[p->n] - pArg->z);\n  }\n}\n\n/*\n** Invoke a virtual table constructor (either xCreate or xConnect). The\n** pointer to the function to invoke is passed as the fourth parameter\n** to this procedure.\n*/\nstatic int vtabCallConstructor(\n  sqlite3 *db, \n  Table *pTab,\n  Module *pMod,\n  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),\n  char **pzErr\n){\n  VtabCtx sCtx, *pPriorCtx;\n  VTable *pVTable;\n  int rc;\n  const char *const*azArg = (const char *const*)pTab->azModuleArg;\n  int nArg = pTab->nModuleArg;\n  char *zErr = 0;\n  char *zModuleName = sqlite3MPrintf(db, \"%s\", pTab->zName);\n\n  if( !zModuleName ){\n    return SQLITE_NOMEM;\n  }\n\n  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));\n  if( !pVTable ){\n    sqlite3DbFree(db, zModuleName);\n    return SQLITE_NOMEM;\n  }\n  pVTable->db = db;\n  pVTable->pMod = pMod;\n\n  /* Invoke the virtual table constructor */\n  assert( &db->pVtabCtx );\n  assert( xConstruct );\n  sCtx.pTab = pTab;\n  sCtx.pVTable = pVTable;\n  pPriorCtx = db->pVtabCtx;\n  db->pVtabCtx = &sCtx;\n  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);\n  db->pVtabCtx = pPriorCtx;\n  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;\n\n  if( SQLITE_OK!=rc ){\n    if( zErr==0 ){\n      *pzErr = sqlite3MPrintf(db, \"vtable constructor failed: %s\", zModuleName);\n    }else {\n      *pzErr = sqlite3MPrintf(db, \"%s\", zErr);\n      sqlite3_free(zErr);\n    }\n    sqlite3DbFree(db, pVTable);\n  }else if( ALWAYS(pVTable->pVtab) ){\n    /* Justification of ALWAYS():  A correct vtab constructor must allocate\n    ** the sqlite3_vtab object if successful.  */\n    pVTable->pVtab->pModule = pMod->pModule;\n    pVTable->nRef = 1;\n    if( sCtx.pTab ){\n      const char *zFormat = \"vtable constructor did not declare schema: %s\";\n      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);\n      sqlite3VtabUnlock(pVTable);\n      rc = SQLITE_ERROR;\n    }else{\n      int iCol;\n      /* If everything went according to plan, link the new VTable structure\n      ** into the linked list headed by pTab->pVTable. Then loop through the \n      ** columns of the table to see if any of them contain the token \"hidden\".\n      ** If so, set the Column.isHidden flag and remove the token from\n      ** the type string.  */\n      pVTable->pNext = pTab->pVTable;\n      pTab->pVTable = pVTable;\n\n      for(iCol=0; iCol<pTab->nCol; iCol++){\n        char *zType = pTab->aCol[iCol].zType;\n        int nType;\n        int i = 0;\n        if( !zType ) continue;\n        nType = sqlite3Strlen30(zType);\n        if( sqlite3StrNICmp(\"hidden\", zType, 6)||(zType[6] && zType[6]!=' ') ){\n          for(i=0; i<nType; i++){\n            if( (0==sqlite3StrNICmp(\" hidden\", &zType[i], 7))\n             && (zType[i+7]=='\\0' || zType[i+7]==' ')\n            ){\n              i++;\n              break;\n            }\n          }\n        }\n        if( i<nType ){\n          int j;\n          int nDel = 6 + (zType[i+6] ? 1 : 0);\n          for(j=i; (j+nDel)<=nType; j++){\n            zType[j] = zType[j+nDel];\n          }\n          if( zType[i]=='\\0' && i>0 ){\n            assert(zType[i-1]==' ');\n            zType[i-1] = '\\0';\n          }\n          pTab->aCol[iCol].isHidden = 1;\n        }\n      }\n    }\n  }\n\n  sqlite3DbFree(db, zModuleName);\n  return rc;\n}\n\n/*\n** This function is invoked by the parser to call the xConnect() method\n** of the virtual table pTab. If an error occurs, an error code is returned \n** and an error left in pParse.\n**\n** This call is a no-op if table pTab is not a virtual table.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){\n  sqlite3 *db = pParse->db;\n  const char *zMod;\n  Module *pMod;\n  int rc;\n\n  assert( pTab );\n  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){\n    return SQLITE_OK;\n  }\n\n  /* Locate the required virtual table module */\n  zMod = pTab->azModuleArg[0];\n  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));\n\n  if( !pMod ){\n    const char *zModule = pTab->azModuleArg[0];\n    sqlite3ErrorMsg(pParse, \"no such module: %s\", zModule);\n    rc = SQLITE_ERROR;\n  }else{\n    char *zErr = 0;\n    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);\n    if( rc!=SQLITE_OK ){\n      sqlite3ErrorMsg(pParse, \"%s\", zErr);\n    }\n    sqlite3DbFree(db, zErr);\n  }\n\n  return rc;\n}\n/*\n** Grow the db->aVTrans[] array so that there is room for at least one\n** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.\n*/\nstatic int growVTrans(sqlite3 *db){\n  const int ARRAY_INCR = 5;\n\n  /* Grow the sqlite3.aVTrans array if required */\n  if( (db->nVTrans%ARRAY_INCR)==0 ){\n    VTable **aVTrans;\n    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);\n    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);\n    if( !aVTrans ){\n      return SQLITE_NOMEM;\n    }\n    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);\n    db->aVTrans = aVTrans;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should\n** have already been reserved using growVTrans().\n*/\nstatic void addToVTrans(sqlite3 *db, VTable *pVTab){\n  /* Add pVtab to the end of sqlite3.aVTrans */\n  db->aVTrans[db->nVTrans++] = pVTab;\n  sqlite3VtabLock(pVTab);\n}\n\n/*\n** This function is invoked by the vdbe to call the xCreate method\n** of the virtual table named zTab in database iDb. \n**\n** If an error occurs, *pzErr is set to point an an English language\n** description of the error and an SQLITE_XXX error code is returned.\n** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){\n  int rc = SQLITE_OK;\n  Table *pTab;\n  Module *pMod;\n  const char *zMod;\n\n  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);\n  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );\n\n  /* Locate the required virtual table module */\n  zMod = pTab->azModuleArg[0];\n  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));\n\n  /* If the module has been registered and includes a Create method, \n  ** invoke it now. If the module has not been registered, return an \n  ** error. Otherwise, do nothing.\n  */\n  if( !pMod ){\n    *pzErr = sqlite3MPrintf(db, \"no such module: %s\", zMod);\n    rc = SQLITE_ERROR;\n  }else{\n    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);\n  }\n\n  /* Justification of ALWAYS():  The xConstructor method is required to\n  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */\n  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){\n    rc = growVTrans(db);\n    if( rc==SQLITE_OK ){\n      addToVTrans(db, sqlite3GetVTable(db, pTab));\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function is used to set the schema of a virtual table.  It is only\n** valid to call this function from within the xCreate() or xConnect() of a\n** virtual table module.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){\n  Parse *pParse;\n\n  int rc = SQLITE_OK;\n  Table *pTab;\n  char *zErr = 0;\n\n  sqlite3_mutex_enter(db->mutex);\n  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){\n    sqlite3Error(db, SQLITE_MISUSE, 0);\n    sqlite3_mutex_leave(db->mutex);\n    return SQLITE_MISUSE_BKPT;\n  }\n  assert( (pTab->tabFlags & TF_Virtual)!=0 );\n\n  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));\n  if( pParse==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    pParse->declareVtab = 1;\n    pParse->db = db;\n    pParse->nQueryLoop = 1;\n  \n    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) \n     && pParse->pNewTable\n     && !db->mallocFailed\n     && !pParse->pNewTable->pSelect\n     && (pParse->pNewTable->tabFlags & TF_Virtual)==0\n    ){\n      if( !pTab->aCol ){\n        pTab->aCol = pParse->pNewTable->aCol;\n        pTab->nCol = pParse->pNewTable->nCol;\n        pParse->pNewTable->nCol = 0;\n        pParse->pNewTable->aCol = 0;\n      }\n      db->pVtabCtx->pTab = 0;\n    }else{\n      sqlite3Error(db, SQLITE_ERROR, (zErr ? \"%s\" : 0), zErr);\n      sqlite3DbFree(db, zErr);\n      rc = SQLITE_ERROR;\n    }\n    pParse->declareVtab = 0;\n  \n    if( pParse->pVdbe ){\n      sqlite3VdbeFinalize(pParse->pVdbe);\n    }\n    sqlite3DeleteTable(db, pParse->pNewTable);\n    sqlite3StackFree(db, pParse);\n  }\n\n  assert( (rc&0xff)==rc );\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** This function is invoked by the vdbe to call the xDestroy method\n** of the virtual table named zTab in database iDb. This occurs\n** when a DROP TABLE is mentioned.\n**\n** This call is a no-op if zTab is not a virtual table.\n*/\nSQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){\n  int rc = SQLITE_OK;\n  Table *pTab;\n\n  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);\n  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){\n    VTable *p = vtabDisconnectAll(db, pTab);\n\n    assert( rc==SQLITE_OK );\n    rc = p->pMod->pModule->xDestroy(p->pVtab);\n\n    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */\n    if( rc==SQLITE_OK ){\n      assert( pTab->pVTable==p && p->pNext==0 );\n      p->pVtab = 0;\n      pTab->pVTable = 0;\n      sqlite3VtabUnlock(p);\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function invokes either the xRollback or xCommit method\n** of each of the virtual tables in the sqlite3.aVTrans array. The method\n** called is identified by the second argument, \"offset\", which is\n** the offset of the method to call in the sqlite3_module structure.\n**\n** The array is cleared after invoking the callbacks. \n*/\nstatic void callFinaliser(sqlite3 *db, int offset){\n  int i;\n  if( db->aVTrans ){\n    for(i=0; i<db->nVTrans; i++){\n      VTable *pVTab = db->aVTrans[i];\n      sqlite3_vtab *p = pVTab->pVtab;\n      if( p ){\n        int (*x)(sqlite3_vtab *);\n        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);\n        if( x ) x(p);\n      }\n      pVTab->iSavepoint = 0;\n      sqlite3VtabUnlock(pVTab);\n    }\n    sqlite3DbFree(db, db->aVTrans);\n    db->nVTrans = 0;\n    db->aVTrans = 0;\n  }\n}\n\n/*\n** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans\n** array. Return the error code for the first error that occurs, or\n** SQLITE_OK if all xSync operations are successful.\n**\n** Set *pzErrmsg to point to a buffer that should be released using \n** sqlite3DbFree() containing an error message, if one is available.\n*/\nSQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){\n  int i;\n  int rc = SQLITE_OK;\n  VTable **aVTrans = db->aVTrans;\n\n  db->aVTrans = 0;\n  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){\n    int (*x)(sqlite3_vtab *);\n    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;\n    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){\n      rc = x(pVtab);\n      sqlite3DbFree(db, *pzErrmsg);\n      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);\n      sqlite3_free(pVtab->zErrMsg);\n    }\n  }\n  db->aVTrans = aVTrans;\n  return rc;\n}\n\n/*\n** Invoke the xRollback method of all virtual tables in the \n** sqlite3.aVTrans array. Then clear the array itself.\n*/\nSQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){\n  callFinaliser(db, offsetof(sqlite3_module,xRollback));\n  return SQLITE_OK;\n}\n\n/*\n** Invoke the xCommit method of all virtual tables in the \n** sqlite3.aVTrans array. Then clear the array itself.\n*/\nSQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){\n  callFinaliser(db, offsetof(sqlite3_module,xCommit));\n  return SQLITE_OK;\n}\n\n/*\n** If the virtual table pVtab supports the transaction interface\n** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is\n** not currently open, invoke the xBegin method now.\n**\n** If the xBegin call is successful, place the sqlite3_vtab pointer\n** in the sqlite3.aVTrans array.\n*/\nSQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){\n  int rc = SQLITE_OK;\n  const sqlite3_module *pModule;\n\n  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater\n  ** than zero, then this function is being called from within a\n  ** virtual module xSync() callback. It is illegal to write to \n  ** virtual module tables in this case, so return SQLITE_LOCKED.\n  */\n  if( sqlite3VtabInSync(db) ){\n    return SQLITE_LOCKED;\n  }\n  if( !pVTab ){\n    return SQLITE_OK;\n  } \n  pModule = pVTab->pVtab->pModule;\n\n  if( pModule->xBegin ){\n    int i;\n\n    /* If pVtab is already in the aVTrans array, return early */\n    for(i=0; i<db->nVTrans; i++){\n      if( db->aVTrans[i]==pVTab ){\n        return SQLITE_OK;\n      }\n    }\n\n    /* Invoke the xBegin method. If successful, add the vtab to the \n    ** sqlite3.aVTrans[] array. */\n    rc = growVTrans(db);\n    if( rc==SQLITE_OK ){\n      rc = pModule->xBegin(pVTab->pVtab);\n      if( rc==SQLITE_OK ){\n        addToVTrans(db, pVTab);\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Invoke either the xSavepoint, xRollbackTo or xRelease method of all\n** virtual tables that currently have an open transaction. Pass iSavepoint\n** as the second argument to the virtual table method invoked.\n**\n** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is\n** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is \n** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with\n** an open transaction is invoked.\n**\n** If any virtual table method returns an error code other than SQLITE_OK, \n** processing is abandoned and the error returned to the caller of this\n** function immediately. If all calls to virtual table methods are successful,\n** SQLITE_OK is returned.\n*/\nSQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){\n  int rc = SQLITE_OK;\n\n  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );\n  assert( iSavepoint>=0 );\n  if( db->aVTrans ){\n    int i;\n    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){\n      VTable *pVTab = db->aVTrans[i];\n      const sqlite3_module *pMod = pVTab->pMod->pModule;\n      if( pVTab->pVtab && pMod->iVersion>=2 ){\n        int (*xMethod)(sqlite3_vtab *, int);\n        switch( op ){\n          case SAVEPOINT_BEGIN:\n            xMethod = pMod->xSavepoint;\n            pVTab->iSavepoint = iSavepoint+1;\n            break;\n          case SAVEPOINT_ROLLBACK:\n            xMethod = pMod->xRollbackTo;\n            break;\n          default:\n            xMethod = pMod->xRelease;\n            break;\n        }\n        if( xMethod && pVTab->iSavepoint>iSavepoint ){\n          rc = xMethod(pVTab->pVtab, iSavepoint);\n        }\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** The first parameter (pDef) is a function implementation.  The\n** second parameter (pExpr) is the first argument to this function.\n** If pExpr is a column in a virtual table, then let the virtual\n** table implementation have an opportunity to overload the function.\n**\n** This routine is used to allow virtual table implementations to\n** overload MATCH, LIKE, GLOB, and REGEXP operators.\n**\n** Return either the pDef argument (indicating no change) or a \n** new FuncDef structure that is marked as ephemeral using the\n** SQLITE_FUNC_EPHEM flag.\n*/\nSQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(\n  sqlite3 *db,    /* Database connection for reporting malloc problems */\n  FuncDef *pDef,  /* Function to possibly overload */\n  int nArg,       /* Number of arguments to the function */\n  Expr *pExpr     /* First argument to the function */\n){\n  Table *pTab;\n  sqlite3_vtab *pVtab;\n  sqlite3_module *pMod;\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;\n  void *pArg = 0;\n  FuncDef *pNew;\n  int rc = 0;\n  char *zLowerName;\n  unsigned char *z;\n\n\n  /* Check to see the left operand is a column in a virtual table */\n  if( NEVER(pExpr==0) ) return pDef;\n  if( pExpr->op!=TK_COLUMN ) return pDef;\n  pTab = pExpr->pTab;\n  if( NEVER(pTab==0) ) return pDef;\n  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;\n  pVtab = sqlite3GetVTable(db, pTab)->pVtab;\n  assert( pVtab!=0 );\n  assert( pVtab->pModule!=0 );\n  pMod = (sqlite3_module *)pVtab->pModule;\n  if( pMod->xFindFunction==0 ) return pDef;\n \n  /* Call the xFindFunction method on the virtual table implementation\n  ** to see if the implementation wants to overload this function \n  */\n  zLowerName = sqlite3DbStrDup(db, pDef->zName);\n  if( zLowerName ){\n    for(z=(unsigned char*)zLowerName; *z; z++){\n      *z = sqlite3UpperToLower[*z];\n    }\n    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);\n    sqlite3DbFree(db, zLowerName);\n  }\n  if( rc==0 ){\n    return pDef;\n  }\n\n  /* Create a new ephemeral function definition for the overloaded\n  ** function */\n  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)\n                             + sqlite3Strlen30(pDef->zName) + 1);\n  if( pNew==0 ){\n    return pDef;\n  }\n  *pNew = *pDef;\n  pNew->zName = (char *)&pNew[1];\n  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);\n  pNew->xFunc = xFunc;\n  pNew->pUserData = pArg;\n  pNew->flags |= SQLITE_FUNC_EPHEM;\n  return pNew;\n}\n\n/*\n** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]\n** array so that an OP_VBegin will get generated for it.  Add pTab to the\n** array if it is missing.  If pTab is already in the array, this routine\n** is a no-op.\n*/\nSQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){\n  Parse *pToplevel = sqlite3ParseToplevel(pParse);\n  int i, n;\n  Table **apVtabLock;\n\n  assert( IsVirtual(pTab) );\n  for(i=0; i<pToplevel->nVtabLock; i++){\n    if( pTab==pToplevel->apVtabLock[i] ) return;\n  }\n  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);\n  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);\n  if( apVtabLock ){\n    pToplevel->apVtabLock = apVtabLock;\n    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;\n  }else{\n    pToplevel->db->mallocFailed = 1;\n  }\n}\n\n/*\n** Return the ON CONFLICT resolution mode in effect for the virtual\n** table update operation currently in progress.\n**\n** The results of this routine are undefined unless it is called from\n** within an xUpdate method.\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){\n  static const unsigned char aMap[] = { \n    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE \n  };\n  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );\n  assert( OE_Ignore==4 && OE_Replace==5 );\n  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );\n  return (int)aMap[db->vtabOnConflict-1];\n}\n\n/*\n** Call from within the xCreate() or xConnect() methods to provide \n** the SQLite core with additional information about the behavior\n** of the virtual table being implemented.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){\n  va_list ap;\n  int rc = SQLITE_OK;\n\n  sqlite3_mutex_enter(db->mutex);\n\n  va_start(ap, op);\n  switch( op ){\n    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {\n      VtabCtx *p = db->pVtabCtx;\n      if( !p ){\n        rc = SQLITE_MISUSE_BKPT;\n      }else{\n        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );\n        p->pVTable->bConstraint = (u8)va_arg(ap, int);\n      }\n      break;\n    }\n    default:\n      rc = SQLITE_MISUSE_BKPT;\n      break;\n  }\n  va_end(ap);\n\n  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/************** End of vtab.c ************************************************/\n/************** Begin file where.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This module contains C code that generates VDBE code used to process\n** the WHERE clause of SQL statements.  This module is responsible for\n** generating the code that loops through a table looking for applicable\n** rows.  Indices are selected and used to speed the search when doing\n** so is applicable.  Because this module is responsible for selecting\n** indices, you might also think of this module as the \"query optimizer\".\n*/\n\n\n/*\n** Trace output macros\n*/\n#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)\nSQLITE_PRIVATE int sqlite3WhereTrace = 0;\n#endif\n#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)\n# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X\n#else\n# define WHERETRACE(X)\n#endif\n\n/* Forward reference\n*/\ntypedef struct WhereClause WhereClause;\ntypedef struct WhereMaskSet WhereMaskSet;\ntypedef struct WhereOrInfo WhereOrInfo;\ntypedef struct WhereAndInfo WhereAndInfo;\ntypedef struct WhereCost WhereCost;\n\n/*\n** The query generator uses an array of instances of this structure to\n** help it analyze the subexpressions of the WHERE clause.  Each WHERE\n** clause subexpression is separated from the others by AND operators,\n** usually, or sometimes subexpressions separated by OR.\n**\n** All WhereTerms are collected into a single WhereClause structure.  \n** The following identity holds:\n**\n**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm\n**\n** When a term is of the form:\n**\n**              X <op> <expr>\n**\n** where X is a column name and <op> is one of certain operators,\n** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the\n** cursor number and column number for X.  WhereTerm.eOperator records\n** the <op> using a bitmask encoding defined by WO_xxx below.  The\n** use of a bitmask encoding for the operator allows us to search\n** quickly for terms that match any of several different operators.\n**\n** A WhereTerm might also be two or more subterms connected by OR:\n**\n**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....\n**\n** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR\n** and the WhereTerm.u.pOrInfo field points to auxiliary information that\n** is collected about the\n**\n** If a term in the WHERE clause does not match either of the two previous\n** categories, then eOperator==0.  The WhereTerm.pExpr field is still set\n** to the original subexpression content and wtFlags is set up appropriately\n** but no other fields in the WhereTerm object are meaningful.\n**\n** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,\n** but they do so indirectly.  A single WhereMaskSet structure translates\n** cursor number into bits and the translated bit is stored in the prereq\n** fields.  The translation is used in order to maximize the number of\n** bits that will fit in a Bitmask.  The VDBE cursor numbers might be\n** spread out over the non-negative integers.  For example, the cursor\n** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet\n** translates these sparse cursor numbers into consecutive integers\n** beginning with 0 in order to make the best possible use of the available\n** bits in the Bitmask.  So, in the example above, the cursor numbers\n** would be mapped into integers 0 through 7.\n**\n** The number of terms in a join is limited by the number of bits\n** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite\n** is only able to process joins with 64 or fewer tables.\n*/\ntypedef struct WhereTerm WhereTerm;\nstruct WhereTerm {\n  Expr *pExpr;            /* Pointer to the subexpression that is this term */\n  int iParent;            /* Disable pWC->a[iParent] when this term disabled */\n  int leftCursor;         /* Cursor number of X in \"X <op> <expr>\" */\n  union {\n    int leftColumn;         /* Column number of X in \"X <op> <expr>\" */\n    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */\n    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */\n  } u;\n  u16 eOperator;          /* A WO_xx value describing <op> */\n  u8 wtFlags;             /* TERM_xxx bit flags.  See below */\n  u8 nChild;              /* Number of children that must disable us */\n  WhereClause *pWC;       /* The clause this term is part of */\n  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */\n  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */\n};\n\n/*\n** Allowed values of WhereTerm.wtFlags\n*/\n#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */\n#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */\n#define TERM_CODED      0x04   /* This term is already coded */\n#define TERM_COPIED     0x08   /* Has a child */\n#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */\n#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */\n#define TERM_OR_OK      0x40   /* Used during OR-clause processing */\n#ifdef SQLITE_ENABLE_STAT3\n#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */\n#else\n#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */\n#endif\n\n/*\n** An instance of the following structure holds all information about a\n** WHERE clause.  Mostly this is a container for one or more WhereTerms.\n**\n** Explanation of pOuter:  For a WHERE clause of the form\n**\n**           a AND ((b AND c) OR (d AND e)) AND f\n**\n** There are separate WhereClause objects for the whole clause and for\n** the subclauses \"(b AND c)\" and \"(d AND e)\".  The pOuter field of the\n** subclauses points to the WhereClause object for the whole clause.\n*/\nstruct WhereClause {\n  Parse *pParse;           /* The parser context */\n  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */\n  Bitmask vmask;           /* Bitmask identifying virtual table cursors */\n  WhereClause *pOuter;     /* Outer conjunction */\n  u8 op;                   /* Split operator.  TK_AND or TK_OR */\n  u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */\n  int nTerm;               /* Number of terms */\n  int nSlot;               /* Number of entries in a[] */\n  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */\n#if defined(SQLITE_SMALL_STACK)\n  WhereTerm aStatic[1];    /* Initial static space for a[] */\n#else\n  WhereTerm aStatic[8];    /* Initial static space for a[] */\n#endif\n};\n\n/*\n** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to\n** a dynamically allocated instance of the following structure.\n*/\nstruct WhereOrInfo {\n  WhereClause wc;          /* Decomposition into subterms */\n  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */\n};\n\n/*\n** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to\n** a dynamically allocated instance of the following structure.\n*/\nstruct WhereAndInfo {\n  WhereClause wc;          /* The subexpression broken out */\n};\n\n/*\n** An instance of the following structure keeps track of a mapping\n** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.\n**\n** The VDBE cursor numbers are small integers contained in \n** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE \n** clause, the cursor numbers might not begin with 0 and they might\n** contain gaps in the numbering sequence.  But we want to make maximum\n** use of the bits in our bitmasks.  This structure provides a mapping\n** from the sparse cursor numbers into consecutive integers beginning\n** with 0.\n**\n** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask\n** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.\n**\n** For example, if the WHERE clause expression used these VDBE\n** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure\n** would map those cursor numbers into bits 0 through 5.\n**\n** Note that the mapping is not necessarily ordered.  In the example\n** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,\n** 57->5, 73->4.  Or one of 719 other combinations might be used. It\n** does not really matter.  What is important is that sparse cursor\n** numbers all get mapped into bit numbers that begin with 0 and contain\n** no gaps.\n*/\nstruct WhereMaskSet {\n  int n;                        /* Number of assigned cursor values */\n  int ix[BMS];                  /* Cursor assigned to each bit */\n};\n\n/*\n** A WhereCost object records a lookup strategy and the estimated\n** cost of pursuing that strategy.\n*/\nstruct WhereCost {\n  WherePlan plan;    /* The lookup strategy */\n  double rCost;      /* Overall cost of pursuing this search strategy */\n  Bitmask used;      /* Bitmask of cursors used by this plan */\n};\n\n/*\n** Bitmasks for the operators that indices are able to exploit.  An\n** OR-ed combination of these values can be used when searching for\n** terms in the where clause.\n*/\n#define WO_IN     0x001\n#define WO_EQ     0x002\n#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))\n#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))\n#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))\n#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))\n#define WO_MATCH  0x040\n#define WO_ISNULL 0x080\n#define WO_OR     0x100       /* Two or more OR-connected terms */\n#define WO_AND    0x200       /* Two or more AND-connected terms */\n#define WO_NOOP   0x800       /* This term does not restrict search space */\n\n#define WO_ALL    0xfff       /* Mask of all possible WO_* values */\n#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */\n\n/*\n** Value for wsFlags returned by bestIndex() and stored in\n** WhereLevel.wsFlags.  These flags determine which search\n** strategies are appropriate.\n**\n** The least significant 12 bits is reserved as a mask for WO_ values above.\n** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.\n** But if the table is the right table of a left join, WhereLevel.wsFlags\n** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as\n** the \"op\" parameter to findTerm when we are resolving equality constraints.\n** ISNULL constraints will then not be used on the right table of a left\n** join.  Tickets #2177 and #2189.\n*/\n#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */\n#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */\n#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */\n#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */\n#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */\n#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */\n#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */\n#define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */\n#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */\n#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */\n#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */\n#define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */\n#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */\n#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */\n#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */\n#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */\n#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */\n#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */\n#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */\n#define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */\n\n/*\n** Initialize a preallocated WhereClause structure.\n*/\nstatic void whereClauseInit(\n  WhereClause *pWC,        /* The WhereClause to be initialized */\n  Parse *pParse,           /* The parsing context */\n  WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */\n  u16 wctrlFlags           /* Might include WHERE_AND_ONLY */\n){\n  pWC->pParse = pParse;\n  pWC->pMaskSet = pMaskSet;\n  pWC->pOuter = 0;\n  pWC->nTerm = 0;\n  pWC->nSlot = ArraySize(pWC->aStatic);\n  pWC->a = pWC->aStatic;\n  pWC->vmask = 0;\n  pWC->wctrlFlags = wctrlFlags;\n}\n\n/* Forward reference */\nstatic void whereClauseClear(WhereClause*);\n\n/*\n** Deallocate all memory associated with a WhereOrInfo object.\n*/\nstatic void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){\n  whereClauseClear(&p->wc);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Deallocate all memory associated with a WhereAndInfo object.\n*/\nstatic void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){\n  whereClauseClear(&p->wc);\n  sqlite3DbFree(db, p);\n}\n\n/*\n** Deallocate a WhereClause structure.  The WhereClause structure\n** itself is not freed.  This routine is the inverse of whereClauseInit().\n*/\nstatic void whereClauseClear(WhereClause *pWC){\n  int i;\n  WhereTerm *a;\n  sqlite3 *db = pWC->pParse->db;\n  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){\n    if( a->wtFlags & TERM_DYNAMIC ){\n      sqlite3ExprDelete(db, a->pExpr);\n    }\n    if( a->wtFlags & TERM_ORINFO ){\n      whereOrInfoDelete(db, a->u.pOrInfo);\n    }else if( a->wtFlags & TERM_ANDINFO ){\n      whereAndInfoDelete(db, a->u.pAndInfo);\n    }\n  }\n  if( pWC->a!=pWC->aStatic ){\n    sqlite3DbFree(db, pWC->a);\n  }\n}\n\n/*\n** Add a single new WhereTerm entry to the WhereClause object pWC.\n** The new WhereTerm object is constructed from Expr p and with wtFlags.\n** The index in pWC->a[] of the new WhereTerm is returned on success.\n** 0 is returned if the new WhereTerm could not be added due to a memory\n** allocation error.  The memory allocation failure will be recorded in\n** the db->mallocFailed flag so that higher-level functions can detect it.\n**\n** This routine will increase the size of the pWC->a[] array as necessary.\n**\n** If the wtFlags argument includes TERM_DYNAMIC, then responsibility\n** for freeing the expression p is assumed by the WhereClause object pWC.\n** This is true even if this routine fails to allocate a new WhereTerm.\n**\n** WARNING:  This routine might reallocate the space used to store\n** WhereTerms.  All pointers to WhereTerms should be invalidated after\n** calling this routine.  Such pointers may be reinitialized by referencing\n** the pWC->a[] array.\n*/\nstatic int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){\n  WhereTerm *pTerm;\n  int idx;\n  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */\n  if( pWC->nTerm>=pWC->nSlot ){\n    WhereTerm *pOld = pWC->a;\n    sqlite3 *db = pWC->pParse->db;\n    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );\n    if( pWC->a==0 ){\n      if( wtFlags & TERM_DYNAMIC ){\n        sqlite3ExprDelete(db, p);\n      }\n      pWC->a = pOld;\n      return 0;\n    }\n    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);\n    if( pOld!=pWC->aStatic ){\n      sqlite3DbFree(db, pOld);\n    }\n    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);\n  }\n  pTerm = &pWC->a[idx = pWC->nTerm++];\n  pTerm->pExpr = p;\n  pTerm->wtFlags = wtFlags;\n  pTerm->pWC = pWC;\n  pTerm->iParent = -1;\n  return idx;\n}\n\n/*\n** This routine identifies subexpressions in the WHERE clause where\n** each subexpression is separated by the AND operator or some other\n** operator specified in the op parameter.  The WhereClause structure\n** is filled with pointers to subexpressions.  For example:\n**\n**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)\n**           \\________/     \\_______________/     \\________________/\n**            slot[0]            slot[1]               slot[2]\n**\n** The original WHERE clause in pExpr is unaltered.  All this routine\n** does is make slot[] entries point to substructure within pExpr.\n**\n** In the previous sentence and in the diagram, \"slot[]\" refers to\n** the WhereClause.a[] array.  The slot[] array grows as needed to contain\n** all terms of the WHERE clause.\n*/\nstatic void whereSplit(WhereClause *pWC, Expr *pExpr, int op){\n  pWC->op = (u8)op;\n  if( pExpr==0 ) return;\n  if( pExpr->op!=op ){\n    whereClauseInsert(pWC, pExpr, 0);\n  }else{\n    whereSplit(pWC, pExpr->pLeft, op);\n    whereSplit(pWC, pExpr->pRight, op);\n  }\n}\n\n/*\n** Initialize an expression mask set (a WhereMaskSet object)\n*/\n#define initMaskSet(P)  memset(P, 0, sizeof(*P))\n\n/*\n** Return the bitmask for the given cursor number.  Return 0 if\n** iCursor is not in the set.\n*/\nstatic Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){\n  int i;\n  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );\n  for(i=0; i<pMaskSet->n; i++){\n    if( pMaskSet->ix[i]==iCursor ){\n      return ((Bitmask)1)<<i;\n    }\n  }\n  return 0;\n}\n\n/*\n** Create a new mask for cursor iCursor.\n**\n** There is one cursor per table in the FROM clause.  The number of\n** tables in the FROM clause is limited by a test early in the\n** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]\n** array will never overflow.\n*/\nstatic void createMask(WhereMaskSet *pMaskSet, int iCursor){\n  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );\n  pMaskSet->ix[pMaskSet->n++] = iCursor;\n}\n\n/*\n** This routine walks (recursively) an expression tree and generates\n** a bitmask indicating which tables are used in that expression\n** tree.\n**\n** In order for this routine to work, the calling function must have\n** previously invoked sqlite3ResolveExprNames() on the expression.  See\n** the header comment on that routine for additional information.\n** The sqlite3ResolveExprNames() routines looks for column names and\n** sets their opcodes to TK_COLUMN and their Expr.iTable fields to\n** the VDBE cursor number of the table.  This routine just has to\n** translate the cursor numbers into bitmask values and OR all\n** the bitmasks together.\n*/\nstatic Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);\nstatic Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);\nstatic Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){\n  Bitmask mask = 0;\n  if( p==0 ) return 0;\n  if( p->op==TK_COLUMN ){\n    mask = getMask(pMaskSet, p->iTable);\n    return mask;\n  }\n  mask = exprTableUsage(pMaskSet, p->pRight);\n  mask |= exprTableUsage(pMaskSet, p->pLeft);\n  if( ExprHasProperty(p, EP_xIsSelect) ){\n    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);\n  }else{\n    mask |= exprListTableUsage(pMaskSet, p->x.pList);\n  }\n  return mask;\n}\nstatic Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){\n  int i;\n  Bitmask mask = 0;\n  if( pList ){\n    for(i=0; i<pList->nExpr; i++){\n      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);\n    }\n  }\n  return mask;\n}\nstatic Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){\n  Bitmask mask = 0;\n  while( pS ){\n    SrcList *pSrc = pS->pSrc;\n    mask |= exprListTableUsage(pMaskSet, pS->pEList);\n    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);\n    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);\n    mask |= exprTableUsage(pMaskSet, pS->pWhere);\n    mask |= exprTableUsage(pMaskSet, pS->pHaving);\n    if( ALWAYS(pSrc!=0) ){\n      int i;\n      for(i=0; i<pSrc->nSrc; i++){\n        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);\n        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);\n      }\n    }\n    pS = pS->pPrior;\n  }\n  return mask;\n}\n\n/*\n** Return TRUE if the given operator is one of the operators that is\n** allowed for an indexable WHERE clause term.  The allowed operators are\n** \"=\", \"<\", \">\", \"<=\", \">=\", and \"IN\".\n**\n** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be\n** of one of the following forms: column = expression column > expression\n** column >= expression column < expression column <= expression\n** expression = column expression > column expression >= column\n** expression < column expression <= column column IN\n** (expression-list) column IN (subquery) column IS NULL\n*/\nstatic int allowedOp(int op){\n  assert( TK_GT>TK_EQ && TK_GT<TK_GE );\n  assert( TK_LT>TK_EQ && TK_LT<TK_GE );\n  assert( TK_LE>TK_EQ && TK_LE<TK_GE );\n  assert( TK_GE==TK_EQ+4 );\n  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;\n}\n\n/*\n** Swap two objects of type TYPE.\n*/\n#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}\n\n/*\n** Commute a comparison operator.  Expressions of the form \"X op Y\"\n** are converted into \"Y op X\".\n**\n** If a collation sequence is associated with either the left or right\n** side of the comparison, it remains associated with the same side after\n** the commutation. So \"Y collate NOCASE op X\" becomes \n** \"X collate NOCASE op Y\". This is because any collation sequence on\n** the left hand side of a comparison overrides any collation sequence \n** attached to the right. For the same reason the EP_ExpCollate flag\n** is not commuted.\n*/\nstatic void exprCommute(Parse *pParse, Expr *pExpr){\n  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);\n  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);\n  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );\n  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);\n  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);\n  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);\n  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;\n  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;\n  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);\n  if( pExpr->op>=TK_GT ){\n    assert( TK_LT==TK_GT+2 );\n    assert( TK_GE==TK_LE+2 );\n    assert( TK_GT>TK_EQ );\n    assert( TK_GT<TK_LE );\n    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );\n    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;\n  }\n}\n\n/*\n** Translate from TK_xx operator to WO_xx bitmask.\n*/\nstatic u16 operatorMask(int op){\n  u16 c;\n  assert( allowedOp(op) );\n  if( op==TK_IN ){\n    c = WO_IN;\n  }else if( op==TK_ISNULL ){\n    c = WO_ISNULL;\n  }else{\n    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );\n    c = (u16)(WO_EQ<<(op-TK_EQ));\n  }\n  assert( op!=TK_ISNULL || c==WO_ISNULL );\n  assert( op!=TK_IN || c==WO_IN );\n  assert( op!=TK_EQ || c==WO_EQ );\n  assert( op!=TK_LT || c==WO_LT );\n  assert( op!=TK_LE || c==WO_LE );\n  assert( op!=TK_GT || c==WO_GT );\n  assert( op!=TK_GE || c==WO_GE );\n  return c;\n}\n\n/*\n** Search for a term in the WHERE clause that is of the form \"X <op> <expr>\"\n** where X is a reference to the iColumn of table iCur and <op> is one of\n** the WO_xx operator codes specified by the op parameter.\n** Return a pointer to the term.  Return 0 if not found.\n*/\nstatic WhereTerm *findTerm(\n  WhereClause *pWC,     /* The WHERE clause to be searched */\n  int iCur,             /* Cursor number of LHS */\n  int iColumn,          /* Column number of LHS */\n  Bitmask notReady,     /* RHS must not overlap with this mask */\n  u32 op,               /* Mask of WO_xx values describing operator */\n  Index *pIdx           /* Must be compatible with this index, if not NULL */\n){\n  WhereTerm *pTerm;\n  int k;\n  assert( iCur>=0 );\n  op &= WO_ALL;\n  for(; pWC; pWC=pWC->pOuter){\n    for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){\n      if( pTerm->leftCursor==iCur\n         && (pTerm->prereqRight & notReady)==0\n         && pTerm->u.leftColumn==iColumn\n         && (pTerm->eOperator & op)!=0\n      ){\n        if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){\n          Expr *pX = pTerm->pExpr;\n          CollSeq *pColl;\n          char idxaff;\n          int j;\n          Parse *pParse = pWC->pParse;\n  \n          idxaff = pIdx->pTable->aCol[iColumn].affinity;\n          if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;\n  \n          /* Figure out the collation sequence required from an index for\n          ** it to be useful for optimising expression pX. Store this\n          ** value in variable pColl.\n          */\n          assert(pX->pLeft);\n          pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);\n          assert(pColl || pParse->nErr);\n  \n          for(j=0; pIdx->aiColumn[j]!=iColumn; j++){\n            if( NEVER(j>=pIdx->nColumn) ) return 0;\n          }\n          if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;\n        }\n        return pTerm;\n      }\n    }\n  }\n  return 0;\n}\n\n/* Forward reference */\nstatic void exprAnalyze(SrcList*, WhereClause*, int);\n\n/*\n** Call exprAnalyze on all terms in a WHERE clause.  \n**\n**\n*/\nstatic void exprAnalyzeAll(\n  SrcList *pTabList,       /* the FROM clause */\n  WhereClause *pWC         /* the WHERE clause to be analyzed */\n){\n  int i;\n  for(i=pWC->nTerm-1; i>=0; i--){\n    exprAnalyze(pTabList, pWC, i);\n  }\n}\n\n#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION\n/*\n** Check to see if the given expression is a LIKE or GLOB operator that\n** can be optimized using inequality constraints.  Return TRUE if it is\n** so and false if not.\n**\n** In order for the operator to be optimizible, the RHS must be a string\n** literal that does not begin with a wildcard.  \n*/\nstatic int isLikeOrGlob(\n  Parse *pParse,    /* Parsing and code generating context */\n  Expr *pExpr,      /* Test this expression */\n  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */\n  int *pisComplete, /* True if the only wildcard is % in the last character */\n  int *pnoCase      /* True if uppercase is equivalent to lowercase */\n){\n  const char *z = 0;         /* String on RHS of LIKE operator */\n  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */\n  ExprList *pList;           /* List of operands to the LIKE operator */\n  int c;                     /* One character in z[] */\n  int cnt;                   /* Number of non-wildcard prefix characters */\n  char wc[3];                /* Wildcard characters */\n  sqlite3 *db = pParse->db;  /* Database connection */\n  sqlite3_value *pVal = 0;\n  int op;                    /* Opcode of pRight */\n\n  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){\n    return 0;\n  }\n#ifdef SQLITE_EBCDIC\n  if( *pnoCase ) return 0;\n#endif\n  pList = pExpr->x.pList;\n  pLeft = pList->a[1].pExpr;\n  if( pLeft->op!=TK_COLUMN \n   || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT \n   || IsVirtual(pLeft->pTab)\n  ){\n    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must\n    ** be the name of an indexed column with TEXT affinity. */\n    return 0;\n  }\n  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */\n\n  pRight = pList->a[0].pExpr;\n  op = pRight->op;\n  if( op==TK_REGISTER ){\n    op = pRight->op2;\n  }\n  if( op==TK_VARIABLE ){\n    Vdbe *pReprepare = pParse->pReprepare;\n    int iCol = pRight->iColumn;\n    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);\n    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){\n      z = (char *)sqlite3_value_text(pVal);\n    }\n    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);\n    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );\n  }else if( op==TK_STRING ){\n    z = pRight->u.zToken;\n  }\n  if( z ){\n    cnt = 0;\n    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){\n      cnt++;\n    }\n    if( cnt!=0 && 255!=(u8)z[cnt-1] ){\n      Expr *pPrefix;\n      *pisComplete = c==wc[0] && z[cnt+1]==0;\n      pPrefix = sqlite3Expr(db, TK_STRING, z);\n      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;\n      *ppPrefix = pPrefix;\n      if( op==TK_VARIABLE ){\n        Vdbe *v = pParse->pVdbe;\n        sqlite3VdbeSetVarmask(v, pRight->iColumn);\n        if( *pisComplete && pRight->u.zToken[1] ){\n          /* If the rhs of the LIKE expression is a variable, and the current\n          ** value of the variable means there is no need to invoke the LIKE\n          ** function, then no OP_Variable will be added to the program.\n          ** This causes problems for the sqlite3_bind_parameter_name()\n          ** API. To workaround them, add a dummy OP_Variable here.\n          */ \n          int r1 = sqlite3GetTempReg(pParse);\n          sqlite3ExprCodeTarget(pParse, pRight, r1);\n          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);\n          sqlite3ReleaseTempReg(pParse, r1);\n        }\n      }\n    }else{\n      z = 0;\n    }\n  }\n\n  sqlite3ValueFree(pVal);\n  return (z!=0);\n}\n#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */\n\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Check to see if the given expression is of the form\n**\n**         column MATCH expr\n**\n** If it is then return TRUE.  If not, return FALSE.\n*/\nstatic int isMatchOfColumn(\n  Expr *pExpr      /* Test this expression */\n){\n  ExprList *pList;\n\n  if( pExpr->op!=TK_FUNCTION ){\n    return 0;\n  }\n  if( sqlite3StrICmp(pExpr->u.zToken,\"match\")!=0 ){\n    return 0;\n  }\n  pList = pExpr->x.pList;\n  if( pList->nExpr!=2 ){\n    return 0;\n  }\n  if( pList->a[1].pExpr->op != TK_COLUMN ){\n    return 0;\n  }\n  return 1;\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n/*\n** If the pBase expression originated in the ON or USING clause of\n** a join, then transfer the appropriate markings over to derived.\n*/\nstatic void transferJoinMarkings(Expr *pDerived, Expr *pBase){\n  pDerived->flags |= pBase->flags & EP_FromJoin;\n  pDerived->iRightJoinTable = pBase->iRightJoinTable;\n}\n\n#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)\n/*\n** Analyze a term that consists of two or more OR-connected\n** subterms.  So in:\n**\n**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)\n**                          ^^^^^^^^^^^^^^^^^^^^\n**\n** This routine analyzes terms such as the middle term in the above example.\n** A WhereOrTerm object is computed and attached to the term under\n** analysis, regardless of the outcome of the analysis.  Hence:\n**\n**     WhereTerm.wtFlags   |=  TERM_ORINFO\n**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object\n**\n** The term being analyzed must have two or more of OR-connected subterms.\n** A single subterm might be a set of AND-connected sub-subterms.\n** Examples of terms under analysis:\n**\n**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5\n**     (B)     x=expr1 OR expr2=x OR x=expr3\n**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)\n**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')\n**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)\n**\n** CASE 1:\n**\n** If all subterms are of the form T.C=expr for some single column of C\n** a single table T (as shown in example B above) then create a new virtual\n** term that is an equivalent IN expression.  In other words, if the term\n** being analyzed is:\n**\n**      x = expr1  OR  expr2 = x  OR  x = expr3\n**\n** then create a new virtual term like this:\n**\n**      x IN (expr1,expr2,expr3)\n**\n** CASE 2:\n**\n** If all subterms are indexable by a single table T, then set\n**\n**     WhereTerm.eOperator              =  WO_OR\n**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T\n**\n** A subterm is \"indexable\" if it is of the form\n** \"T.C <op> <expr>\" where C is any column of table T and \n** <op> is one of \"=\", \"<\", \"<=\", \">\", \">=\", \"IS NULL\", or \"IN\".\n** A subterm is also indexable if it is an AND of two or more\n** subsubterms at least one of which is indexable.  Indexable AND \n** subterms have their eOperator set to WO_AND and they have\n** u.pAndInfo set to a dynamically allocated WhereAndTerm object.\n**\n** From another point of view, \"indexable\" means that the subterm could\n** potentially be used with an index if an appropriate index exists.\n** This analysis does not consider whether or not the index exists; that\n** is something the bestIndex() routine will determine.  This analysis\n** only looks at whether subterms appropriate for indexing exist.\n**\n** All examples A through E above all satisfy case 2.  But if a term\n** also statisfies case 1 (such as B) we know that the optimizer will\n** always prefer case 1, so in that case we pretend that case 2 is not\n** satisfied.\n**\n** It might be the case that multiple tables are indexable.  For example,\n** (E) above is indexable on tables P, Q, and R.\n**\n** Terms that satisfy case 2 are candidates for lookup by using\n** separate indices to find rowids for each subterm and composing\n** the union of all rowids using a RowSet object.  This is similar\n** to \"bitmap indices\" in other database engines.\n**\n** OTHERWISE:\n**\n** If neither case 1 nor case 2 apply, then leave the eOperator set to\n** zero.  This term is not useful for search.\n*/\nstatic void exprAnalyzeOrTerm(\n  SrcList *pSrc,            /* the FROM clause */\n  WhereClause *pWC,         /* the complete WHERE clause */\n  int idxTerm               /* Index of the OR-term to be analyzed */\n){\n  Parse *pParse = pWC->pParse;            /* Parser context */\n  sqlite3 *db = pParse->db;               /* Database connection */\n  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */\n  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */\n  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */\n  int i;                                  /* Loop counters */\n  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */\n  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */\n  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */\n  Bitmask chngToIN;         /* Tables that might satisfy case 1 */\n  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */\n\n  /*\n  ** Break the OR clause into its separate subterms.  The subterms are\n  ** stored in a WhereClause structure containing within the WhereOrInfo\n  ** object that is attached to the original OR clause term.\n  */\n  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );\n  assert( pExpr->op==TK_OR );\n  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));\n  if( pOrInfo==0 ) return;\n  pTerm->wtFlags |= TERM_ORINFO;\n  pOrWc = &pOrInfo->wc;\n  whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);\n  whereSplit(pOrWc, pExpr, TK_OR);\n  exprAnalyzeAll(pSrc, pOrWc);\n  if( db->mallocFailed ) return;\n  assert( pOrWc->nTerm>=2 );\n\n  /*\n  ** Compute the set of tables that might satisfy cases 1 or 2.\n  */\n  indexable = ~(Bitmask)0;\n  chngToIN = ~(pWC->vmask);\n  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){\n    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){\n      WhereAndInfo *pAndInfo;\n      assert( pOrTerm->eOperator==0 );\n      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );\n      chngToIN = 0;\n      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));\n      if( pAndInfo ){\n        WhereClause *pAndWC;\n        WhereTerm *pAndTerm;\n        int j;\n        Bitmask b = 0;\n        pOrTerm->u.pAndInfo = pAndInfo;\n        pOrTerm->wtFlags |= TERM_ANDINFO;\n        pOrTerm->eOperator = WO_AND;\n        pAndWC = &pAndInfo->wc;\n        whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);\n        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);\n        exprAnalyzeAll(pSrc, pAndWC);\n        pAndWC->pOuter = pWC;\n        testcase( db->mallocFailed );\n        if( !db->mallocFailed ){\n          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){\n            assert( pAndTerm->pExpr );\n            if( allowedOp(pAndTerm->pExpr->op) ){\n              b |= getMask(pMaskSet, pAndTerm->leftCursor);\n            }\n          }\n        }\n        indexable &= b;\n      }\n    }else if( pOrTerm->wtFlags & TERM_COPIED ){\n      /* Skip this term for now.  We revisit it when we process the\n      ** corresponding TERM_VIRTUAL term */\n    }else{\n      Bitmask b;\n      b = getMask(pMaskSet, pOrTerm->leftCursor);\n      if( pOrTerm->wtFlags & TERM_VIRTUAL ){\n        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];\n        b |= getMask(pMaskSet, pOther->leftCursor);\n      }\n      indexable &= b;\n      if( pOrTerm->eOperator!=WO_EQ ){\n        chngToIN = 0;\n      }else{\n        chngToIN &= b;\n      }\n    }\n  }\n\n  /*\n  ** Record the set of tables that satisfy case 2.  The set might be\n  ** empty.\n  */\n  pOrInfo->indexable = indexable;\n  pTerm->eOperator = indexable==0 ? 0 : WO_OR;\n\n  /*\n  ** chngToIN holds a set of tables that *might* satisfy case 1.  But\n  ** we have to do some additional checking to see if case 1 really\n  ** is satisfied.\n  **\n  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means\n  ** that there is no possibility of transforming the OR clause into an\n  ** IN operator because one or more terms in the OR clause contain\n  ** something other than == on a column in the single table.  The 1-bit\n  ** case means that every term of the OR clause is of the form\n  ** \"table.column=expr\" for some single table.  The one bit that is set\n  ** will correspond to the common table.  We still need to check to make\n  ** sure the same column is used on all terms.  The 2-bit case is when\n  ** the all terms are of the form \"table1.column=table2.column\".  It\n  ** might be possible to form an IN operator with either table1.column\n  ** or table2.column as the LHS if either is common to every term of\n  ** the OR clause.\n  **\n  ** Note that terms of the form \"table.column1=table.column2\" (the\n  ** same table on both sizes of the ==) cannot be optimized.\n  */\n  if( chngToIN ){\n    int okToChngToIN = 0;     /* True if the conversion to IN is valid */\n    int iColumn = -1;         /* Column index on lhs of IN operator */\n    int iCursor = -1;         /* Table cursor common to all terms */\n    int j = 0;                /* Loop counter */\n\n    /* Search for a table and column that appears on one side or the\n    ** other of the == operator in every subterm.  That table and column\n    ** will be recorded in iCursor and iColumn.  There might not be any\n    ** such table and column.  Set okToChngToIN if an appropriate table\n    ** and column is found but leave okToChngToIN false if not found.\n    */\n    for(j=0; j<2 && !okToChngToIN; j++){\n      pOrTerm = pOrWc->a;\n      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){\n        assert( pOrTerm->eOperator==WO_EQ );\n        pOrTerm->wtFlags &= ~TERM_OR_OK;\n        if( pOrTerm->leftCursor==iCursor ){\n          /* This is the 2-bit case and we are on the second iteration and\n          ** current term is from the first iteration.  So skip this term. */\n          assert( j==1 );\n          continue;\n        }\n        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){\n          /* This term must be of the form t1.a==t2.b where t2 is in the\n          ** chngToIN set but t1 is not.  This term will be either preceeded\n          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term \n          ** and use its inversion. */\n          testcase( pOrTerm->wtFlags & TERM_COPIED );\n          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );\n          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );\n          continue;\n        }\n        iColumn = pOrTerm->u.leftColumn;\n        iCursor = pOrTerm->leftCursor;\n        break;\n      }\n      if( i<0 ){\n        /* No candidate table+column was found.  This can only occur\n        ** on the second iteration */\n        assert( j==1 );\n        assert( (chngToIN&(chngToIN-1))==0 );\n        assert( chngToIN==getMask(pMaskSet, iCursor) );\n        break;\n      }\n      testcase( j==1 );\n\n      /* We have found a candidate table and column.  Check to see if that\n      ** table and column is common to every term in the OR clause */\n      okToChngToIN = 1;\n      for(; i>=0 && okToChngToIN; i--, pOrTerm++){\n        assert( pOrTerm->eOperator==WO_EQ );\n        if( pOrTerm->leftCursor!=iCursor ){\n          pOrTerm->wtFlags &= ~TERM_OR_OK;\n        }else if( pOrTerm->u.leftColumn!=iColumn ){\n          okToChngToIN = 0;\n        }else{\n          int affLeft, affRight;\n          /* If the right-hand side is also a column, then the affinities\n          ** of both right and left sides must be such that no type\n          ** conversions are required on the right.  (Ticket #2249)\n          */\n          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);\n          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);\n          if( affRight!=0 && affRight!=affLeft ){\n            okToChngToIN = 0;\n          }else{\n            pOrTerm->wtFlags |= TERM_OR_OK;\n          }\n        }\n      }\n    }\n\n    /* At this point, okToChngToIN is true if original pTerm satisfies\n    ** case 1.  In that case, construct a new virtual term that is \n    ** pTerm converted into an IN operator.\n    **\n    ** EV: R-00211-15100\n    */\n    if( okToChngToIN ){\n      Expr *pDup;            /* A transient duplicate expression */\n      ExprList *pList = 0;   /* The RHS of the IN operator */\n      Expr *pLeft = 0;       /* The LHS of the IN operator */\n      Expr *pNew;            /* The complete IN operator */\n\n      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){\n        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;\n        assert( pOrTerm->eOperator==WO_EQ );\n        assert( pOrTerm->leftCursor==iCursor );\n        assert( pOrTerm->u.leftColumn==iColumn );\n        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);\n        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);\n        pLeft = pOrTerm->pExpr->pLeft;\n      }\n      assert( pLeft!=0 );\n      pDup = sqlite3ExprDup(db, pLeft, 0);\n      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);\n      if( pNew ){\n        int idxNew;\n        transferJoinMarkings(pNew, pExpr);\n        assert( !ExprHasProperty(pNew, EP_xIsSelect) );\n        pNew->x.pList = pList;\n        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);\n        testcase( idxNew==0 );\n        exprAnalyze(pSrc, pWC, idxNew);\n        pTerm = &pWC->a[idxTerm];\n        pWC->a[idxNew].iParent = idxTerm;\n        pTerm->nChild = 1;\n      }else{\n        sqlite3ExprListDelete(db, pList);\n      }\n      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */\n    }\n  }\n}\n#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */\n\n\n/*\n** The input to this routine is an WhereTerm structure with only the\n** \"pExpr\" field filled in.  The job of this routine is to analyze the\n** subexpression and populate all the other fields of the WhereTerm\n** structure.\n**\n** If the expression is of the form \"<expr> <op> X\" it gets commuted\n** to the standard form of \"X <op> <expr>\".\n**\n** If the expression is of the form \"X <op> Y\" where both X and Y are\n** columns, then the original expression is unchanged and a new virtual\n** term of the form \"Y <op> X\" is added to the WHERE clause and\n** analyzed separately.  The original term is marked with TERM_COPIED\n** and the new term is marked with TERM_DYNAMIC (because it's pExpr\n** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it\n** is a commuted copy of a prior term.)  The original term has nChild=1\n** and the copy has idxParent set to the index of the original term.\n*/\nstatic void exprAnalyze(\n  SrcList *pSrc,            /* the FROM clause */\n  WhereClause *pWC,         /* the WHERE clause */\n  int idxTerm               /* Index of the term to be analyzed */\n){\n  WhereTerm *pTerm;                /* The term to be analyzed */\n  WhereMaskSet *pMaskSet;          /* Set of table index masks */\n  Expr *pExpr;                     /* The expression to be analyzed */\n  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */\n  Bitmask prereqAll;               /* Prerequesites of pExpr */\n  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */\n  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */\n  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */\n  int noCase = 0;                  /* LIKE/GLOB distinguishes case */\n  int op;                          /* Top-level operator.  pExpr->op */\n  Parse *pParse = pWC->pParse;     /* Parsing context */\n  sqlite3 *db = pParse->db;        /* Database connection */\n\n  if( db->mallocFailed ){\n    return;\n  }\n  pTerm = &pWC->a[idxTerm];\n  pMaskSet = pWC->pMaskSet;\n  pExpr = pTerm->pExpr;\n  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);\n  op = pExpr->op;\n  if( op==TK_IN ){\n    assert( pExpr->pRight==0 );\n    if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);\n    }else{\n      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);\n    }\n  }else if( op==TK_ISNULL ){\n    pTerm->prereqRight = 0;\n  }else{\n    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);\n  }\n  prereqAll = exprTableUsage(pMaskSet, pExpr);\n  if( ExprHasProperty(pExpr, EP_FromJoin) ){\n    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);\n    prereqAll |= x;\n    extraRight = x-1;  /* ON clause terms may not be used with an index\n                       ** on left table of a LEFT JOIN.  Ticket #3015 */\n  }\n  pTerm->prereqAll = prereqAll;\n  pTerm->leftCursor = -1;\n  pTerm->iParent = -1;\n  pTerm->eOperator = 0;\n  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){\n    Expr *pLeft = pExpr->pLeft;\n    Expr *pRight = pExpr->pRight;\n    if( pLeft->op==TK_COLUMN ){\n      pTerm->leftCursor = pLeft->iTable;\n      pTerm->u.leftColumn = pLeft->iColumn;\n      pTerm->eOperator = operatorMask(op);\n    }\n    if( pRight && pRight->op==TK_COLUMN ){\n      WhereTerm *pNew;\n      Expr *pDup;\n      if( pTerm->leftCursor>=0 ){\n        int idxNew;\n        pDup = sqlite3ExprDup(db, pExpr, 0);\n        if( db->mallocFailed ){\n          sqlite3ExprDelete(db, pDup);\n          return;\n        }\n        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);\n        if( idxNew==0 ) return;\n        pNew = &pWC->a[idxNew];\n        pNew->iParent = idxTerm;\n        pTerm = &pWC->a[idxTerm];\n        pTerm->nChild = 1;\n        pTerm->wtFlags |= TERM_COPIED;\n      }else{\n        pDup = pExpr;\n        pNew = pTerm;\n      }\n      exprCommute(pParse, pDup);\n      pLeft = pDup->pLeft;\n      pNew->leftCursor = pLeft->iTable;\n      pNew->u.leftColumn = pLeft->iColumn;\n      testcase( (prereqLeft | extraRight) != prereqLeft );\n      pNew->prereqRight = prereqLeft | extraRight;\n      pNew->prereqAll = prereqAll;\n      pNew->eOperator = operatorMask(pDup->op);\n    }\n  }\n\n#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION\n  /* If a term is the BETWEEN operator, create two new virtual terms\n  ** that define the range that the BETWEEN implements.  For example:\n  **\n  **      a BETWEEN b AND c\n  **\n  ** is converted into:\n  **\n  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)\n  **\n  ** The two new terms are added onto the end of the WhereClause object.\n  ** The new terms are \"dynamic\" and are children of the original BETWEEN\n  ** term.  That means that if the BETWEEN term is coded, the children are\n  ** skipped.  Or, if the children are satisfied by an index, the original\n  ** BETWEEN term is skipped.\n  */\n  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){\n    ExprList *pList = pExpr->x.pList;\n    int i;\n    static const u8 ops[] = {TK_GE, TK_LE};\n    assert( pList!=0 );\n    assert( pList->nExpr==2 );\n    for(i=0; i<2; i++){\n      Expr *pNewExpr;\n      int idxNew;\n      pNewExpr = sqlite3PExpr(pParse, ops[i], \n                             sqlite3ExprDup(db, pExpr->pLeft, 0),\n                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);\n      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);\n      testcase( idxNew==0 );\n      exprAnalyze(pSrc, pWC, idxNew);\n      pTerm = &pWC->a[idxTerm];\n      pWC->a[idxNew].iParent = idxTerm;\n    }\n    pTerm->nChild = 2;\n  }\n#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */\n\n#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)\n  /* Analyze a term that is composed of two or more subterms connected by\n  ** an OR operator.\n  */\n  else if( pExpr->op==TK_OR ){\n    assert( pWC->op==TK_AND );\n    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);\n    pTerm = &pWC->a[idxTerm];\n  }\n#endif /* SQLITE_OMIT_OR_OPTIMIZATION */\n\n#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION\n  /* Add constraints to reduce the search space on a LIKE or GLOB\n  ** operator.\n  **\n  ** A like pattern of the form \"x LIKE 'abc%'\" is changed into constraints\n  **\n  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'\n  **\n  ** The last character of the prefix \"abc\" is incremented to form the\n  ** termination condition \"abd\".\n  */\n  if( pWC->op==TK_AND \n   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)\n  ){\n    Expr *pLeft;       /* LHS of LIKE/GLOB operator */\n    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */\n    Expr *pNewExpr1;\n    Expr *pNewExpr2;\n    int idxNew1;\n    int idxNew2;\n    CollSeq *pColl;    /* Collating sequence to use */\n\n    pLeft = pExpr->x.pList->a[1].pExpr;\n    pStr2 = sqlite3ExprDup(db, pStr1, 0);\n    if( !db->mallocFailed ){\n      u8 c, *pC;       /* Last character before the first wildcard */\n      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];\n      c = *pC;\n      if( noCase ){\n        /* The point is to increment the last character before the first\n        ** wildcard.  But if we increment '@', that will push it into the\n        ** alphabetic range where case conversions will mess up the \n        ** inequality.  To avoid this, make sure to also run the full\n        ** LIKE on all candidate expressions by clearing the isComplete flag\n        */\n        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */\n\n\n        c = sqlite3UpperToLower[c];\n      }\n      *pC = c + 1;\n    }\n    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? \"NOCASE\" : \"BINARY\",0);\n    pNewExpr1 = sqlite3PExpr(pParse, TK_GE, \n                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),\n                     pStr1, 0);\n    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);\n    testcase( idxNew1==0 );\n    exprAnalyze(pSrc, pWC, idxNew1);\n    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,\n                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),\n                     pStr2, 0);\n    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);\n    testcase( idxNew2==0 );\n    exprAnalyze(pSrc, pWC, idxNew2);\n    pTerm = &pWC->a[idxTerm];\n    if( isComplete ){\n      pWC->a[idxNew1].iParent = idxTerm;\n      pWC->a[idxNew2].iParent = idxTerm;\n      pTerm->nChild = 2;\n    }\n  }\n#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  /* Add a WO_MATCH auxiliary term to the constraint set if the\n  ** current expression is of the form:  column MATCH expr.\n  ** This information is used by the xBestIndex methods of\n  ** virtual tables.  The native query optimizer does not attempt\n  ** to do anything with MATCH functions.\n  */\n  if( isMatchOfColumn(pExpr) ){\n    int idxNew;\n    Expr *pRight, *pLeft;\n    WhereTerm *pNewTerm;\n    Bitmask prereqColumn, prereqExpr;\n\n    pRight = pExpr->x.pList->a[0].pExpr;\n    pLeft = pExpr->x.pList->a[1].pExpr;\n    prereqExpr = exprTableUsage(pMaskSet, pRight);\n    prereqColumn = exprTableUsage(pMaskSet, pLeft);\n    if( (prereqExpr & prereqColumn)==0 ){\n      Expr *pNewExpr;\n      pNewExpr = sqlite3PExpr(pParse, TK_MATCH, \n                              0, sqlite3ExprDup(db, pRight, 0), 0);\n      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);\n      testcase( idxNew==0 );\n      pNewTerm = &pWC->a[idxNew];\n      pNewTerm->prereqRight = prereqExpr;\n      pNewTerm->leftCursor = pLeft->iTable;\n      pNewTerm->u.leftColumn = pLeft->iColumn;\n      pNewTerm->eOperator = WO_MATCH;\n      pNewTerm->iParent = idxTerm;\n      pTerm = &pWC->a[idxTerm];\n      pTerm->nChild = 1;\n      pTerm->wtFlags |= TERM_COPIED;\n      pNewTerm->prereqAll = pTerm->prereqAll;\n    }\n  }\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifdef SQLITE_ENABLE_STAT3\n  /* When sqlite_stat3 histogram data is available an operator of the\n  ** form \"x IS NOT NULL\" can sometimes be evaluated more efficiently\n  ** as \"x>NULL\" if x is not an INTEGER PRIMARY KEY.  So construct a\n  ** virtual term of that form.\n  **\n  ** Note that the virtual term must be tagged with TERM_VNULL.  This\n  ** TERM_VNULL tag will suppress the not-null check at the beginning\n  ** of the loop.  Without the TERM_VNULL flag, the not-null check at\n  ** the start of the loop will prevent any results from being returned.\n  */\n  if( pExpr->op==TK_NOTNULL\n   && pExpr->pLeft->op==TK_COLUMN\n   && pExpr->pLeft->iColumn>=0\n  ){\n    Expr *pNewExpr;\n    Expr *pLeft = pExpr->pLeft;\n    int idxNew;\n    WhereTerm *pNewTerm;\n\n    pNewExpr = sqlite3PExpr(pParse, TK_GT,\n                            sqlite3ExprDup(db, pLeft, 0),\n                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);\n\n    idxNew = whereClauseInsert(pWC, pNewExpr,\n                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);\n    if( idxNew ){\n      pNewTerm = &pWC->a[idxNew];\n      pNewTerm->prereqRight = 0;\n      pNewTerm->leftCursor = pLeft->iTable;\n      pNewTerm->u.leftColumn = pLeft->iColumn;\n      pNewTerm->eOperator = WO_GT;\n      pNewTerm->iParent = idxTerm;\n      pTerm = &pWC->a[idxTerm];\n      pTerm->nChild = 1;\n      pTerm->wtFlags |= TERM_COPIED;\n      pNewTerm->prereqAll = pTerm->prereqAll;\n    }\n  }\n#endif /* SQLITE_ENABLE_STAT */\n\n  /* Prevent ON clause terms of a LEFT JOIN from being used to drive\n  ** an index for tables to the left of the join.\n  */\n  pTerm->prereqRight |= extraRight;\n}\n\n/*\n** Return TRUE if any of the expressions in pList->a[iFirst...] contain\n** a reference to any table other than the iBase table.\n*/\nstatic int referencesOtherTables(\n  ExprList *pList,          /* Search expressions in ths list */\n  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */\n  int iFirst,               /* Be searching with the iFirst-th expression */\n  int iBase                 /* Ignore references to this table */\n){\n  Bitmask allowed = ~getMask(pMaskSet, iBase);\n  while( iFirst<pList->nExpr ){\n    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){\n      return 1;\n    }\n  }\n  return 0;\n}\n\n/*\n** This function searches the expression list passed as the second argument\n** for an expression of type TK_COLUMN that refers to the same column and\n** uses the same collation sequence as the iCol'th column of index pIdx.\n** Argument iBase is the cursor number used for the table that pIdx refers\n** to.\n**\n** If such an expression is found, its index in pList->a[] is returned. If\n** no expression is found, -1 is returned.\n*/\nstatic int findIndexCol(\n  Parse *pParse,                  /* Parse context */\n  ExprList *pList,                /* Expression list to search */\n  int iBase,                      /* Cursor for table associated with pIdx */\n  Index *pIdx,                    /* Index to match column of */\n  int iCol                        /* Column of index to match */\n){\n  int i;\n  const char *zColl = pIdx->azColl[iCol];\n\n  for(i=0; i<pList->nExpr; i++){\n    Expr *p = pList->a[i].pExpr;\n    if( p->op==TK_COLUMN\n     && p->iColumn==pIdx->aiColumn[iCol]\n     && p->iTable==iBase\n    ){\n      CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);\n      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){\n        return i;\n      }\n    }\n  }\n\n  return -1;\n}\n\n/*\n** This routine determines if pIdx can be used to assist in processing a\n** DISTINCT qualifier. In other words, it tests whether or not using this\n** index for the outer loop guarantees that rows with equal values for\n** all expressions in the pDistinct list are delivered grouped together.\n**\n** For example, the query \n**\n**   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?\n**\n** can benefit from any index on columns \"b\" and \"c\".\n*/\nstatic int isDistinctIndex(\n  Parse *pParse,                  /* Parsing context */\n  WhereClause *pWC,               /* The WHERE clause */\n  Index *pIdx,                    /* The index being considered */\n  int base,                       /* Cursor number for the table pIdx is on */\n  ExprList *pDistinct,            /* The DISTINCT expressions */\n  int nEqCol                      /* Number of index columns with == */\n){\n  Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */\n  int i;                          /* Iterator variable */\n\n  if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;\n  testcase( pDistinct->nExpr==BMS-1 );\n\n  /* Loop through all the expressions in the distinct list. If any of them\n  ** are not simple column references, return early. Otherwise, test if the\n  ** WHERE clause contains a \"col=X\" clause. If it does, the expression\n  ** can be ignored. If it does not, and the column does not belong to the\n  ** same table as index pIdx, return early. Finally, if there is no\n  ** matching \"col=X\" expression and the column is on the same table as pIdx,\n  ** set the corresponding bit in variable mask.\n  */\n  for(i=0; i<pDistinct->nExpr; i++){\n    WhereTerm *pTerm;\n    Expr *p = pDistinct->a[i].pExpr;\n    if( p->op!=TK_COLUMN ) return 0;\n    pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);\n    if( pTerm ){\n      Expr *pX = pTerm->pExpr;\n      CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);\n      CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);\n      if( p1==p2 ) continue;\n    }\n    if( p->iTable!=base ) return 0;\n    mask |= (((Bitmask)1) << i);\n  }\n\n  for(i=nEqCol; mask && i<pIdx->nColumn; i++){\n    int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);\n    if( iExpr<0 ) break;\n    mask &= ~(((Bitmask)1) << iExpr);\n  }\n\n  return (mask==0);\n}\n\n\n/*\n** Return true if the DISTINCT expression-list passed as the third argument\n** is redundant. A DISTINCT list is redundant if the database contains a\n** UNIQUE index that guarantees that the result of the query will be distinct\n** anyway.\n*/\nstatic int isDistinctRedundant(\n  Parse *pParse,\n  SrcList *pTabList,\n  WhereClause *pWC,\n  ExprList *pDistinct\n){\n  Table *pTab;\n  Index *pIdx;\n  int i;                          \n  int iBase;\n\n  /* If there is more than one table or sub-select in the FROM clause of\n  ** this query, then it will not be possible to show that the DISTINCT \n  ** clause is redundant. */\n  if( pTabList->nSrc!=1 ) return 0;\n  iBase = pTabList->a[0].iCursor;\n  pTab = pTabList->a[0].pTab;\n\n  /* If any of the expressions is an IPK column on table iBase, then return \n  ** true. Note: The (p->iTable==iBase) part of this test may be false if the\n  ** current SELECT is a correlated sub-query.\n  */\n  for(i=0; i<pDistinct->nExpr; i++){\n    Expr *p = pDistinct->a[i].pExpr;\n    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;\n  }\n\n  /* Loop through all indices on the table, checking each to see if it makes\n  ** the DISTINCT qualifier redundant. It does so if:\n  **\n  **   1. The index is itself UNIQUE, and\n  **\n  **   2. All of the columns in the index are either part of the pDistinct\n  **      list, or else the WHERE clause contains a term of the form \"col=X\",\n  **      where X is a constant value. The collation sequences of the\n  **      comparison and select-list expressions must match those of the index.\n  **\n  **   3. All of those index columns for which the WHERE clause does not\n  **      contain a \"col=X\" term are subject to a NOT NULL constraint.\n  */\n  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){\n    if( pIdx->onError==OE_None ) continue;\n    for(i=0; i<pIdx->nColumn; i++){\n      int iCol = pIdx->aiColumn[i];\n      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){\n        int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);\n        if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){\n          break;\n        }\n      }\n    }\n    if( i==pIdx->nColumn ){\n      /* This index implies that the DISTINCT qualifier is redundant. */\n      return 1;\n    }\n  }\n\n  return 0;\n}\n\n/*\n** This routine decides if pIdx can be used to satisfy the ORDER BY\n** clause.  If it can, it returns 1.  If pIdx cannot satisfy the\n** ORDER BY clause, this routine returns 0.\n**\n** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the\n** left-most table in the FROM clause of that same SELECT statement and\n** the table has a cursor number of \"base\".  pIdx is an index on pTab.\n**\n** nEqCol is the number of columns of pIdx that are used as equality\n** constraints.  Any of these columns may be missing from the ORDER BY\n** clause and the match can still be a success.\n**\n** All terms of the ORDER BY that match against the index must be either\n** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE\n** index do not need to satisfy this constraint.)  The *pbRev value is\n** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if\n** the ORDER BY clause is all ASC.\n*/\nstatic int isSortingIndex(\n  Parse *pParse,          /* Parsing context */\n  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */\n  Index *pIdx,            /* The index we are testing */\n  int base,               /* Cursor number for the table to be sorted */\n  ExprList *pOrderBy,     /* The ORDER BY clause */\n  int nEqCol,             /* Number of index columns with == constraints */\n  int wsFlags,            /* Index usages flags */\n  int *pbRev              /* Set to 1 if ORDER BY is DESC */\n){\n  int i, j;                       /* Loop counters */\n  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */\n  int nTerm;                      /* Number of ORDER BY terms */\n  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */\n  sqlite3 *db = pParse->db;\n\n  if( !pOrderBy ) return 0;\n  if( wsFlags & WHERE_COLUMN_IN ) return 0;\n  if( pIdx->bUnordered ) return 0;\n\n  nTerm = pOrderBy->nExpr;\n  assert( nTerm>0 );\n\n  /* Argument pIdx must either point to a 'real' named index structure, \n  ** or an index structure allocated on the stack by bestBtreeIndex() to\n  ** represent the rowid index that is part of every table.  */\n  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );\n\n  /* Match terms of the ORDER BY clause against columns of\n  ** the index.\n  **\n  ** Note that indices have pIdx->nColumn regular columns plus\n  ** one additional column containing the rowid.  The rowid column\n  ** of the index is also allowed to match against the ORDER BY\n  ** clause.\n  */\n  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){\n    Expr *pExpr;       /* The expression of the ORDER BY pTerm */\n    CollSeq *pColl;    /* The collating sequence of pExpr */\n    int termSortOrder; /* Sort order for this term */\n    int iColumn;       /* The i-th column of the index.  -1 for rowid */\n    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */\n    const char *zColl; /* Name of the collating sequence for i-th index term */\n\n    pExpr = pTerm->pExpr;\n    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){\n      /* Can not use an index sort on anything that is not a column in the\n      ** left-most table of the FROM clause */\n      break;\n    }\n    pColl = sqlite3ExprCollSeq(pParse, pExpr);\n    if( !pColl ){\n      pColl = db->pDfltColl;\n    }\n    if( pIdx->zName && i<pIdx->nColumn ){\n      iColumn = pIdx->aiColumn[i];\n      if( iColumn==pIdx->pTable->iPKey ){\n        iColumn = -1;\n      }\n      iSortOrder = pIdx->aSortOrder[i];\n      zColl = pIdx->azColl[i];\n    }else{\n      iColumn = -1;\n      iSortOrder = 0;\n      zColl = pColl->zName;\n    }\n    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){\n      /* Term j of the ORDER BY clause does not match column i of the index */\n      if( i<nEqCol ){\n        /* If an index column that is constrained by == fails to match an\n        ** ORDER BY term, that is OK.  Just ignore that column of the index\n        */\n        continue;\n      }else if( i==pIdx->nColumn ){\n        /* Index column i is the rowid.  All other terms match. */\n        break;\n      }else{\n        /* If an index column fails to match and is not constrained by ==\n        ** then the index cannot satisfy the ORDER BY constraint.\n        */\n        return 0;\n      }\n    }\n    assert( pIdx->aSortOrder!=0 || iColumn==-1 );\n    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );\n    assert( iSortOrder==0 || iSortOrder==1 );\n    termSortOrder = iSortOrder ^ pTerm->sortOrder;\n    if( i>nEqCol ){\n      if( termSortOrder!=sortOrder ){\n        /* Indices can only be used if all ORDER BY terms past the\n        ** equality constraints are all either DESC or ASC. */\n        return 0;\n      }\n    }else{\n      sortOrder = termSortOrder;\n    }\n    j++;\n    pTerm++;\n    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){\n      /* If the indexed column is the primary key and everything matches\n      ** so far and none of the ORDER BY terms to the right reference other\n      ** tables in the join, then we are assured that the index can be used \n      ** to sort because the primary key is unique and so none of the other\n      ** columns will make any difference\n      */\n      j = nTerm;\n    }\n  }\n\n  *pbRev = sortOrder!=0;\n  if( j>=nTerm ){\n    /* All terms of the ORDER BY clause are covered by this index so\n    ** this index can be used for sorting. */\n    return 1;\n  }\n  if( pIdx->onError!=OE_None && i==pIdx->nColumn\n      && (wsFlags & WHERE_COLUMN_NULL)==0\n      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) \n  ){\n    Column *aCol = pIdx->pTable->aCol;\n\n    /* All terms of this index match some prefix of the ORDER BY clause,\n    ** the index is UNIQUE, and no terms on the tail of the ORDER BY\n    ** refer to other tables in a join. So, assuming that the index entries\n    ** visited contain no NULL values, then this index delivers rows in\n    ** the required order.\n    **\n    ** It is not possible for any of the first nEqCol index fields to be\n    ** NULL (since the corresponding \"=\" operator in the WHERE clause would \n    ** not be true). So if all remaining index columns have NOT NULL \n    ** constaints attached to them, we can be confident that the visited\n    ** index entries are free of NULLs.  */\n    for(i=nEqCol; i<pIdx->nColumn; i++){\n      if( aCol[pIdx->aiColumn[i]].notNull==0 ) break;\n    }\n    return (i==pIdx->nColumn);\n  }\n  return 0;\n}\n\n/*\n** Prepare a crude estimate of the logarithm of the input value.\n** The results need not be exact.  This is only used for estimating\n** the total cost of performing operations with O(logN) or O(NlogN)\n** complexity.  Because N is just a guess, it is no great tragedy if\n** logN is a little off.\n*/\nstatic double estLog(double N){\n  double logN = 1;\n  double x = 10;\n  while( N>x ){\n    logN += 1;\n    x *= 10;\n  }\n  return logN;\n}\n\n/*\n** Two routines for printing the content of an sqlite3_index_info\n** structure.  Used for testing and debugging only.  If neither\n** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines\n** are no-ops.\n*/\n#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)\nstatic void TRACE_IDX_INPUTS(sqlite3_index_info *p){\n  int i;\n  if( !sqlite3WhereTrace ) return;\n  for(i=0; i<p->nConstraint; i++){\n    sqlite3DebugPrintf(\"  constraint[%d]: col=%d termid=%d op=%d usabled=%d\\n\",\n       i,\n       p->aConstraint[i].iColumn,\n       p->aConstraint[i].iTermOffset,\n       p->aConstraint[i].op,\n       p->aConstraint[i].usable);\n  }\n  for(i=0; i<p->nOrderBy; i++){\n    sqlite3DebugPrintf(\"  orderby[%d]: col=%d desc=%d\\n\",\n       i,\n       p->aOrderBy[i].iColumn,\n       p->aOrderBy[i].desc);\n  }\n}\nstatic void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){\n  int i;\n  if( !sqlite3WhereTrace ) return;\n  for(i=0; i<p->nConstraint; i++){\n    sqlite3DebugPrintf(\"  usage[%d]: argvIdx=%d omit=%d\\n\",\n       i,\n       p->aConstraintUsage[i].argvIndex,\n       p->aConstraintUsage[i].omit);\n  }\n  sqlite3DebugPrintf(\"  idxNum=%d\\n\", p->idxNum);\n  sqlite3DebugPrintf(\"  idxStr=%s\\n\", p->idxStr);\n  sqlite3DebugPrintf(\"  orderByConsumed=%d\\n\", p->orderByConsumed);\n  sqlite3DebugPrintf(\"  estimatedCost=%g\\n\", p->estimatedCost);\n}\n#else\n#define TRACE_IDX_INPUTS(A)\n#define TRACE_IDX_OUTPUTS(A)\n#endif\n\n/* \n** Required because bestIndex() is called by bestOrClauseIndex() \n*/\nstatic void bestIndex(\n    Parse*, WhereClause*, struct SrcList_item*,\n    Bitmask, Bitmask, ExprList*, WhereCost*);\n\n/*\n** This routine attempts to find an scanning strategy that can be used \n** to optimize an 'OR' expression that is part of a WHERE clause. \n**\n** The table associated with FROM clause term pSrc may be either a\n** regular B-Tree table or a virtual table.\n*/\nstatic void bestOrClauseIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to search */\n  Bitmask notReady,           /* Mask of cursors not available for indexing */\n  Bitmask notValid,           /* Cursors not available for any purpose */\n  ExprList *pOrderBy,         /* The ORDER BY clause */\n  WhereCost *pCost            /* Lowest cost query plan */\n){\n#ifndef SQLITE_OMIT_OR_OPTIMIZATION\n  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */\n  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */\n  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */\n  WhereTerm *pTerm;                 /* A single term of the WHERE clause */\n\n  /* The OR-clause optimization is disallowed if the INDEXED BY or\n  ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */\n  if( pSrc->notIndexed || pSrc->pIndex!=0 ){\n    return;\n  }\n  if( pWC->wctrlFlags & WHERE_AND_ONLY ){\n    return;\n  }\n\n  /* Search the WHERE clause terms for a usable WO_OR term. */\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    if( pTerm->eOperator==WO_OR \n     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0\n     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 \n    ){\n      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;\n      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];\n      WhereTerm *pOrTerm;\n      int flags = WHERE_MULTI_OR;\n      double rTotal = 0;\n      double nRow = 0;\n      Bitmask used = 0;\n\n      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){\n        WhereCost sTermCost;\n        WHERETRACE((\"... Multi-index OR testing for term %d of %d....\\n\", \n          (pOrTerm - pOrWC->a), (pTerm - pWC->a)\n        ));\n        if( pOrTerm->eOperator==WO_AND ){\n          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;\n          bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);\n        }else if( pOrTerm->leftCursor==iCur ){\n          WhereClause tempWC;\n          tempWC.pParse = pWC->pParse;\n          tempWC.pMaskSet = pWC->pMaskSet;\n          tempWC.pOuter = pWC;\n          tempWC.op = TK_AND;\n          tempWC.a = pOrTerm;\n          tempWC.wctrlFlags = 0;\n          tempWC.nTerm = 1;\n          bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);\n        }else{\n          continue;\n        }\n        rTotal += sTermCost.rCost;\n        nRow += sTermCost.plan.nRow;\n        used |= sTermCost.used;\n        if( rTotal>=pCost->rCost ) break;\n      }\n\n      /* If there is an ORDER BY clause, increase the scan cost to account \n      ** for the cost of the sort. */\n      if( pOrderBy!=0 ){\n        WHERETRACE((\"... sorting increases OR cost %.9g to %.9g\\n\",\n                    rTotal, rTotal+nRow*estLog(nRow)));\n        rTotal += nRow*estLog(nRow);\n      }\n\n      /* If the cost of scanning using this OR term for optimization is\n      ** less than the current cost stored in pCost, replace the contents\n      ** of pCost. */\n      WHERETRACE((\"... multi-index OR cost=%.9g nrow=%.9g\\n\", rTotal, nRow));\n      if( rTotal<pCost->rCost ){\n        pCost->rCost = rTotal;\n        pCost->used = used;\n        pCost->plan.nRow = nRow;\n        pCost->plan.wsFlags = flags;\n        pCost->plan.u.pTerm = pTerm;\n      }\n    }\n  }\n#endif /* SQLITE_OMIT_OR_OPTIMIZATION */\n}\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n/*\n** Return TRUE if the WHERE clause term pTerm is of a form where it\n** could be used with an index to access pSrc, assuming an appropriate\n** index existed.\n*/\nstatic int termCanDriveIndex(\n  WhereTerm *pTerm,              /* WHERE clause term to check */\n  struct SrcList_item *pSrc,     /* Table we are trying to access */\n  Bitmask notReady               /* Tables in outer loops of the join */\n){\n  char aff;\n  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;\n  if( pTerm->eOperator!=WO_EQ ) return 0;\n  if( (pTerm->prereqRight & notReady)!=0 ) return 0;\n  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;\n  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;\n  return 1;\n}\n#endif\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n/*\n** If the query plan for pSrc specified in pCost is a full table scan\n** and indexing is allows (if there is no NOT INDEXED clause) and it\n** possible to construct a transient index that would perform better\n** than a full table scan even when the cost of constructing the index\n** is taken into account, then alter the query plan to use the\n** transient index.\n*/\nstatic void bestAutomaticIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to search */\n  Bitmask notReady,           /* Mask of cursors that are not available */\n  WhereCost *pCost            /* Lowest cost query plan */\n){\n  double nTableRow;           /* Rows in the input table */\n  double logN;                /* log(nTableRow) */\n  double costTempIdx;         /* per-query cost of the transient index */\n  WhereTerm *pTerm;           /* A single term of the WHERE clause */\n  WhereTerm *pWCEnd;          /* End of pWC->a[] */\n  Table *pTable;              /* Table tht might be indexed */\n\n  if( pParse->nQueryLoop<=(double)1 ){\n    /* There is no point in building an automatic index for a single scan */\n    return;\n  }\n  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){\n    /* Automatic indices are disabled at run-time */\n    return;\n  }\n  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){\n    /* We already have some kind of index in use for this query. */\n    return;\n  }\n  if( pSrc->notIndexed ){\n    /* The NOT INDEXED clause appears in the SQL. */\n    return;\n  }\n  if( pSrc->isCorrelated ){\n    /* The source is a correlated sub-query. No point in indexing it. */\n    return;\n  }\n\n  assert( pParse->nQueryLoop >= (double)1 );\n  pTable = pSrc->pTab;\n  nTableRow = pTable->nRowEst;\n  logN = estLog(nTableRow);\n  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);\n  if( costTempIdx>=pCost->rCost ){\n    /* The cost of creating the transient table would be greater than\n    ** doing the full table scan */\n    return;\n  }\n\n  /* Search for any equality comparison term */\n  pWCEnd = &pWC->a[pWC->nTerm];\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    if( termCanDriveIndex(pTerm, pSrc, notReady) ){\n      WHERETRACE((\"auto-index reduces cost from %.1f to %.1f\\n\",\n                    pCost->rCost, costTempIdx));\n      pCost->rCost = costTempIdx;\n      pCost->plan.nRow = logN + 1;\n      pCost->plan.wsFlags = WHERE_TEMP_INDEX;\n      pCost->used = pTerm->prereqRight;\n      break;\n    }\n  }\n}\n#else\n# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */\n#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */\n\n\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n/*\n** Generate code to construct the Index object for an automatic index\n** and to set up the WhereLevel object pLevel so that the code generator\n** makes use of the automatic index.\n*/\nstatic void constructAutomaticIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */\n  Bitmask notReady,           /* Mask of cursors that are not available */\n  WhereLevel *pLevel          /* Write new index here */\n){\n  int nColumn;                /* Number of columns in the constructed index */\n  WhereTerm *pTerm;           /* A single term of the WHERE clause */\n  WhereTerm *pWCEnd;          /* End of pWC->a[] */\n  int nByte;                  /* Byte of memory needed for pIdx */\n  Index *pIdx;                /* Object describing the transient index */\n  Vdbe *v;                    /* Prepared statement under construction */\n  int addrInit;               /* Address of the initialization bypass jump */\n  Table *pTable;              /* The table being indexed */\n  KeyInfo *pKeyinfo;          /* Key information for the index */   \n  int addrTop;                /* Top of the index fill loop */\n  int regRecord;              /* Register holding an index record */\n  int n;                      /* Column counter */\n  int i;                      /* Loop counter */\n  int mxBitCol;               /* Maximum column in pSrc->colUsed */\n  CollSeq *pColl;             /* Collating sequence to on a column */\n  Bitmask idxCols;            /* Bitmap of columns used for indexing */\n  Bitmask extraCols;          /* Bitmap of additional columns */\n\n  /* Generate code to skip over the creation and initialization of the\n  ** transient index on 2nd and subsequent iterations of the loop. */\n  v = pParse->pVdbe;\n  assert( v!=0 );\n  addrInit = sqlite3CodeOnce(pParse);\n\n  /* Count the number of columns that will be added to the index\n  ** and used to match WHERE clause constraints */\n  nColumn = 0;\n  pTable = pSrc->pTab;\n  pWCEnd = &pWC->a[pWC->nTerm];\n  idxCols = 0;\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    if( termCanDriveIndex(pTerm, pSrc, notReady) ){\n      int iCol = pTerm->u.leftColumn;\n      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;\n      testcase( iCol==BMS );\n      testcase( iCol==BMS-1 );\n      if( (idxCols & cMask)==0 ){\n        nColumn++;\n        idxCols |= cMask;\n      }\n    }\n  }\n  assert( nColumn>0 );\n  pLevel->plan.nEq = nColumn;\n\n  /* Count the number of additional columns needed to create a\n  ** covering index.  A \"covering index\" is an index that contains all\n  ** columns that are needed by the query.  With a covering index, the\n  ** original table never needs to be accessed.  Automatic indices must\n  ** be a covering index because the index will not be updated if the\n  ** original table changes and the index and table cannot both be used\n  ** if they go out of sync.\n  */\n  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));\n  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;\n  testcase( pTable->nCol==BMS-1 );\n  testcase( pTable->nCol==BMS-2 );\n  for(i=0; i<mxBitCol; i++){\n    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;\n  }\n  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){\n    nColumn += pTable->nCol - BMS + 1;\n  }\n  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;\n\n  /* Construct the Index object to describe this index */\n  nByte = sizeof(Index);\n  nByte += nColumn*sizeof(int);     /* Index.aiColumn */\n  nByte += nColumn*sizeof(char*);   /* Index.azColl */\n  nByte += nColumn;                 /* Index.aSortOrder */\n  pIdx = sqlite3DbMallocZero(pParse->db, nByte);\n  if( pIdx==0 ) return;\n  pLevel->plan.u.pIdx = pIdx;\n  pIdx->azColl = (char**)&pIdx[1];\n  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];\n  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];\n  pIdx->zName = \"auto-index\";\n  pIdx->nColumn = nColumn;\n  pIdx->pTable = pTable;\n  n = 0;\n  idxCols = 0;\n  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){\n    if( termCanDriveIndex(pTerm, pSrc, notReady) ){\n      int iCol = pTerm->u.leftColumn;\n      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;\n      if( (idxCols & cMask)==0 ){\n        Expr *pX = pTerm->pExpr;\n        idxCols |= cMask;\n        pIdx->aiColumn[n] = pTerm->u.leftColumn;\n        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);\n        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : \"BINARY\";\n        n++;\n      }\n    }\n  }\n  assert( (u32)n==pLevel->plan.nEq );\n\n  /* Add additional columns needed to make the automatic index into\n  ** a covering index */\n  for(i=0; i<mxBitCol; i++){\n    if( extraCols & (((Bitmask)1)<<i) ){\n      pIdx->aiColumn[n] = i;\n      pIdx->azColl[n] = \"BINARY\";\n      n++;\n    }\n  }\n  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){\n    for(i=BMS-1; i<pTable->nCol; i++){\n      pIdx->aiColumn[n] = i;\n      pIdx->azColl[n] = \"BINARY\";\n      n++;\n    }\n  }\n  assert( n==nColumn );\n\n  /* Create the automatic index */\n  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);\n  assert( pLevel->iIdxCur>=0 );\n  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,\n                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);\n  VdbeComment((v, \"for %s\", pTable->zName));\n\n  /* Fill the automatic index with content */\n  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);\n  regRecord = sqlite3GetTempReg(pParse);\n  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);\n  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);\n  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);\n  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);\n  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);\n  sqlite3VdbeJumpHere(v, addrTop);\n  sqlite3ReleaseTempReg(pParse, regRecord);\n  \n  /* Jump here when skipping the initialization */\n  sqlite3VdbeJumpHere(v, addrInit);\n}\n#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n/*\n** Allocate and populate an sqlite3_index_info structure. It is the \n** responsibility of the caller to eventually release the structure\n** by passing the pointer returned by this function to sqlite3_free().\n*/\nstatic sqlite3_index_info *allocateIndexInfo(\n  Parse *pParse, \n  WhereClause *pWC,\n  struct SrcList_item *pSrc,\n  ExprList *pOrderBy\n){\n  int i, j;\n  int nTerm;\n  struct sqlite3_index_constraint *pIdxCons;\n  struct sqlite3_index_orderby *pIdxOrderBy;\n  struct sqlite3_index_constraint_usage *pUsage;\n  WhereTerm *pTerm;\n  int nOrderBy;\n  sqlite3_index_info *pIdxInfo;\n\n  WHERETRACE((\"Recomputing index info for %s...\\n\", pSrc->pTab->zName));\n\n  /* Count the number of possible WHERE clause constraints referring\n  ** to this virtual table */\n  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    if( pTerm->leftCursor != pSrc->iCursor ) continue;\n    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );\n    testcase( pTerm->eOperator==WO_IN );\n    testcase( pTerm->eOperator==WO_ISNULL );\n    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;\n    if( pTerm->wtFlags & TERM_VNULL ) continue;\n    nTerm++;\n  }\n\n  /* If the ORDER BY clause contains only columns in the current \n  ** virtual table then allocate space for the aOrderBy part of\n  ** the sqlite3_index_info structure.\n  */\n  nOrderBy = 0;\n  if( pOrderBy ){\n    for(i=0; i<pOrderBy->nExpr; i++){\n      Expr *pExpr = pOrderBy->a[i].pExpr;\n      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;\n    }\n    if( i==pOrderBy->nExpr ){\n      nOrderBy = pOrderBy->nExpr;\n    }\n  }\n\n  /* Allocate the sqlite3_index_info structure\n  */\n  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)\n                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm\n                           + sizeof(*pIdxOrderBy)*nOrderBy );\n  if( pIdxInfo==0 ){\n    sqlite3ErrorMsg(pParse, \"out of memory\");\n    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */\n    return 0;\n  }\n\n  /* Initialize the structure.  The sqlite3_index_info structure contains\n  ** many fields that are declared \"const\" to prevent xBestIndex from\n  ** changing them.  We have to do some funky casting in order to\n  ** initialize those fields.\n  */\n  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];\n  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];\n  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];\n  *(int*)&pIdxInfo->nConstraint = nTerm;\n  *(int*)&pIdxInfo->nOrderBy = nOrderBy;\n  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;\n  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;\n  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =\n                                                                   pUsage;\n\n  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){\n    if( pTerm->leftCursor != pSrc->iCursor ) continue;\n    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );\n    testcase( pTerm->eOperator==WO_IN );\n    testcase( pTerm->eOperator==WO_ISNULL );\n    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;\n    if( pTerm->wtFlags & TERM_VNULL ) continue;\n    pIdxCons[j].iColumn = pTerm->u.leftColumn;\n    pIdxCons[j].iTermOffset = i;\n    pIdxCons[j].op = (u8)pTerm->eOperator;\n    /* The direct assignment in the previous line is possible only because\n    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The\n    ** following asserts verify this fact. */\n    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );\n    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );\n    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );\n    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );\n    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );\n    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );\n    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );\n    j++;\n  }\n  for(i=0; i<nOrderBy; i++){\n    Expr *pExpr = pOrderBy->a[i].pExpr;\n    pIdxOrderBy[i].iColumn = pExpr->iColumn;\n    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;\n  }\n\n  return pIdxInfo;\n}\n\n/*\n** The table object reference passed as the second argument to this function\n** must represent a virtual table. This function invokes the xBestIndex()\n** method of the virtual table with the sqlite3_index_info pointer passed\n** as the argument.\n**\n** If an error occurs, pParse is populated with an error message and a\n** non-zero value is returned. Otherwise, 0 is returned and the output\n** part of the sqlite3_index_info structure is left populated.\n**\n** Whether or not an error is returned, it is the responsibility of the\n** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates\n** that this is required.\n*/\nstatic int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){\n  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;\n  int i;\n  int rc;\n\n  WHERETRACE((\"xBestIndex for %s\\n\", pTab->zName));\n  TRACE_IDX_INPUTS(p);\n  rc = pVtab->pModule->xBestIndex(pVtab, p);\n  TRACE_IDX_OUTPUTS(p);\n\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM ){\n      pParse->db->mallocFailed = 1;\n    }else if( !pVtab->zErrMsg ){\n      sqlite3ErrorMsg(pParse, \"%s\", sqlite3ErrStr(rc));\n    }else{\n      sqlite3ErrorMsg(pParse, \"%s\", pVtab->zErrMsg);\n    }\n  }\n  sqlite3_free(pVtab->zErrMsg);\n  pVtab->zErrMsg = 0;\n\n  for(i=0; i<p->nConstraint; i++){\n    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){\n      sqlite3ErrorMsg(pParse, \n          \"table %s: xBestIndex returned an invalid plan\", pTab->zName);\n    }\n  }\n\n  return pParse->nErr;\n}\n\n\n/*\n** Compute the best index for a virtual table.\n**\n** The best index is computed by the xBestIndex method of the virtual\n** table module.  This routine is really just a wrapper that sets up\n** the sqlite3_index_info structure that is used to communicate with\n** xBestIndex.\n**\n** In a join, this routine might be called multiple times for the\n** same virtual table.  The sqlite3_index_info structure is created\n** and initialized on the first invocation and reused on all subsequent\n** invocations.  The sqlite3_index_info structure is also used when\n** code is generated to access the virtual table.  The whereInfoDelete() \n** routine takes care of freeing the sqlite3_index_info structure after\n** everybody has finished with it.\n*/\nstatic void bestVirtualIndex(\n  Parse *pParse,                  /* The parsing context */\n  WhereClause *pWC,               /* The WHERE clause */\n  struct SrcList_item *pSrc,      /* The FROM clause term to search */\n  Bitmask notReady,               /* Mask of cursors not available for index */\n  Bitmask notValid,               /* Cursors not valid for any purpose */\n  ExprList *pOrderBy,             /* The order by clause */\n  WhereCost *pCost,               /* Lowest cost query plan */\n  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */\n){\n  Table *pTab = pSrc->pTab;\n  sqlite3_index_info *pIdxInfo;\n  struct sqlite3_index_constraint *pIdxCons;\n  struct sqlite3_index_constraint_usage *pUsage;\n  WhereTerm *pTerm;\n  int i, j;\n  int nOrderBy;\n  double rCost;\n\n  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the \n  ** malloc in allocateIndexInfo() fails and this function returns leaving\n  ** wsFlags in an uninitialized state, the caller may behave unpredictably.\n  */\n  memset(pCost, 0, sizeof(*pCost));\n  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;\n\n  /* If the sqlite3_index_info structure has not been previously\n  ** allocated and initialized, then allocate and initialize it now.\n  */\n  pIdxInfo = *ppIdxInfo;\n  if( pIdxInfo==0 ){\n    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);\n  }\n  if( pIdxInfo==0 ){\n    return;\n  }\n\n  /* At this point, the sqlite3_index_info structure that pIdxInfo points\n  ** to will have been initialized, either during the current invocation or\n  ** during some prior invocation.  Now we just have to customize the\n  ** details of pIdxInfo for the current invocation and pass it to\n  ** xBestIndex.\n  */\n\n  /* The module name must be defined. Also, by this point there must\n  ** be a pointer to an sqlite3_vtab structure. Otherwise\n  ** sqlite3ViewGetColumnNames() would have picked up the error. \n  */\n  assert( pTab->azModuleArg && pTab->azModuleArg[0] );\n  assert( sqlite3GetVTable(pParse->db, pTab) );\n\n  /* Set the aConstraint[].usable fields and initialize all \n  ** output variables to zero.\n  **\n  ** aConstraint[].usable is true for constraints where the right-hand\n  ** side contains only references to tables to the left of the current\n  ** table.  In other words, if the constraint is of the form:\n  **\n  **           column = expr\n  **\n  ** and we are evaluating a join, then the constraint on column is \n  ** only valid if all tables referenced in expr occur to the left\n  ** of the table containing column.\n  **\n  ** The aConstraints[] array contains entries for all constraints\n  ** on the current table.  That way we only have to compute it once\n  ** even though we might try to pick the best index multiple times.\n  ** For each attempt at picking an index, the order of tables in the\n  ** join might be different so we have to recompute the usable flag\n  ** each time.\n  */\n  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;\n  pUsage = pIdxInfo->aConstraintUsage;\n  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){\n    j = pIdxCons->iTermOffset;\n    pTerm = &pWC->a[j];\n    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;\n  }\n  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);\n  if( pIdxInfo->needToFreeIdxStr ){\n    sqlite3_free(pIdxInfo->idxStr);\n  }\n  pIdxInfo->idxStr = 0;\n  pIdxInfo->idxNum = 0;\n  pIdxInfo->needToFreeIdxStr = 0;\n  pIdxInfo->orderByConsumed = 0;\n  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */\n  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);\n  nOrderBy = pIdxInfo->nOrderBy;\n  if( !pOrderBy ){\n    pIdxInfo->nOrderBy = 0;\n  }\n\n  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){\n    return;\n  }\n\n  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;\n  for(i=0; i<pIdxInfo->nConstraint; i++){\n    if( pUsage[i].argvIndex>0 ){\n      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;\n    }\n  }\n\n  /* If there is an ORDER BY clause, and the selected virtual table index\n  ** does not satisfy it, increase the cost of the scan accordingly. This\n  ** matches the processing for non-virtual tables in bestBtreeIndex().\n  */\n  rCost = pIdxInfo->estimatedCost;\n  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){\n    rCost += estLog(rCost)*rCost;\n  }\n\n  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the\n  ** inital value of lowestCost in this loop. If it is, then the\n  ** (cost<lowestCost) test below will never be true.\n  ** \n  ** Use \"(double)2\" instead of \"2.0\" in case OMIT_FLOATING_POINT \n  ** is defined.\n  */\n  if( (SQLITE_BIG_DBL/((double)2))<rCost ){\n    pCost->rCost = (SQLITE_BIG_DBL/((double)2));\n  }else{\n    pCost->rCost = rCost;\n  }\n  pCost->plan.u.pVtabIdx = pIdxInfo;\n  if( pIdxInfo->orderByConsumed ){\n    pCost->plan.wsFlags |= WHERE_ORDERBY;\n  }\n  pCost->plan.nEq = 0;\n  pIdxInfo->nOrderBy = nOrderBy;\n\n  /* Try to find a more efficient access pattern by using multiple indexes\n  ** to optimize an OR expression within the WHERE clause. \n  */\n  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);\n}\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n#ifdef SQLITE_ENABLE_STAT3\n/*\n** Estimate the location of a particular key among all keys in an\n** index.  Store the results in aStat as follows:\n**\n**    aStat[0]      Est. number of rows less than pVal\n**    aStat[1]      Est. number of rows equal to pVal\n**\n** Return SQLITE_OK on success.\n*/\nstatic int whereKeyStats(\n  Parse *pParse,              /* Database connection */\n  Index *pIdx,                /* Index to consider domain of */\n  sqlite3_value *pVal,        /* Value to consider */\n  int roundUp,                /* Round up if true.  Round down if false */\n  tRowcnt *aStat              /* OUT: stats written here */\n){\n  tRowcnt n;\n  IndexSample *aSample;\n  int i, eType;\n  int isEq = 0;\n  i64 v;\n  double r, rS;\n\n  assert( roundUp==0 || roundUp==1 );\n  assert( pIdx->nSample>0 );\n  if( pVal==0 ) return SQLITE_ERROR;\n  n = pIdx->aiRowEst[0];\n  aSample = pIdx->aSample;\n  eType = sqlite3_value_type(pVal);\n\n  if( eType==SQLITE_INTEGER ){\n    v = sqlite3_value_int64(pVal);\n    r = (i64)v;\n    for(i=0; i<pIdx->nSample; i++){\n      if( aSample[i].eType==SQLITE_NULL ) continue;\n      if( aSample[i].eType>=SQLITE_TEXT ) break;\n      if( aSample[i].eType==SQLITE_INTEGER ){\n        if( aSample[i].u.i>=v ){\n          isEq = aSample[i].u.i==v;\n          break;\n        }\n      }else{\n        assert( aSample[i].eType==SQLITE_FLOAT );\n        if( aSample[i].u.r>=r ){\n          isEq = aSample[i].u.r==r;\n          break;\n        }\n      }\n    }\n  }else if( eType==SQLITE_FLOAT ){\n    r = sqlite3_value_double(pVal);\n    for(i=0; i<pIdx->nSample; i++){\n      if( aSample[i].eType==SQLITE_NULL ) continue;\n      if( aSample[i].eType>=SQLITE_TEXT ) break;\n      if( aSample[i].eType==SQLITE_FLOAT ){\n        rS = aSample[i].u.r;\n      }else{\n        rS = aSample[i].u.i;\n      }\n      if( rS>=r ){\n        isEq = rS==r;\n        break;\n      }\n    }\n  }else if( eType==SQLITE_NULL ){\n    i = 0;\n    if( aSample[0].eType==SQLITE_NULL ) isEq = 1;\n  }else{\n    assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );\n    for(i=0; i<pIdx->nSample; i++){\n      if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){\n        break;\n      }\n    }\n    if( i<pIdx->nSample ){      \n      sqlite3 *db = pParse->db;\n      CollSeq *pColl;\n      const u8 *z;\n      if( eType==SQLITE_BLOB ){\n        z = (const u8 *)sqlite3_value_blob(pVal);\n        pColl = db->pDfltColl;\n        assert( pColl->enc==SQLITE_UTF8 );\n      }else{\n        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);\n        if( pColl==0 ){\n          sqlite3ErrorMsg(pParse, \"no such collation sequence: %s\",\n                          *pIdx->azColl);\n          return SQLITE_ERROR;\n        }\n        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);\n        if( !z ){\n          return SQLITE_NOMEM;\n        }\n        assert( z && pColl && pColl->xCmp );\n      }\n      n = sqlite3ValueBytes(pVal, pColl->enc);\n  \n      for(; i<pIdx->nSample; i++){\n        int c;\n        int eSampletype = aSample[i].eType;\n        if( eSampletype<eType ) continue;\n        if( eSampletype!=eType ) break;\n#ifndef SQLITE_OMIT_UTF16\n        if( pColl->enc!=SQLITE_UTF8 ){\n          int nSample;\n          char *zSample = sqlite3Utf8to16(\n              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample\n          );\n          if( !zSample ){\n            assert( db->mallocFailed );\n            return SQLITE_NOMEM;\n          }\n          c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);\n          sqlite3DbFree(db, zSample);\n        }else\n#endif\n        {\n          c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);\n        }\n        if( c>=0 ){\n          if( c==0 ) isEq = 1;\n          break;\n        }\n      }\n    }\n  }\n\n  /* At this point, aSample[i] is the first sample that is greater than\n  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less\n  ** than pVal.  If aSample[i]==pVal, then isEq==1.\n  */\n  if( isEq ){\n    assert( i<pIdx->nSample );\n    aStat[0] = aSample[i].nLt;\n    aStat[1] = aSample[i].nEq;\n  }else{\n    tRowcnt iLower, iUpper, iGap;\n    if( i==0 ){\n      iLower = 0;\n      iUpper = aSample[0].nLt;\n    }else{\n      iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;\n      iLower = aSample[i-1].nEq + aSample[i-1].nLt;\n    }\n    aStat[1] = pIdx->avgEq;\n    if( iLower>=iUpper ){\n      iGap = 0;\n    }else{\n      iGap = iUpper - iLower;\n    }\n    if( roundUp ){\n      iGap = (iGap*2)/3;\n    }else{\n      iGap = iGap/3;\n    }\n    aStat[0] = iLower + iGap;\n  }\n  return SQLITE_OK;\n}\n#endif /* SQLITE_ENABLE_STAT3 */\n\n/*\n** If expression pExpr represents a literal value, set *pp to point to\n** an sqlite3_value structure containing the same value, with affinity\n** aff applied to it, before returning. It is the responsibility of the \n** caller to eventually release this structure by passing it to \n** sqlite3ValueFree().\n**\n** If the current parse is a recompile (sqlite3Reprepare()) and pExpr\n** is an SQL variable that currently has a non-NULL value bound to it,\n** create an sqlite3_value structure containing this value, again with\n** affinity aff applied to it, instead.\n**\n** If neither of the above apply, set *pp to NULL.\n**\n** If an error occurs, return an error code. Otherwise, SQLITE_OK.\n*/\n#ifdef SQLITE_ENABLE_STAT3\nstatic int valueFromExpr(\n  Parse *pParse, \n  Expr *pExpr, \n  u8 aff, \n  sqlite3_value **pp\n){\n  if( pExpr->op==TK_VARIABLE\n   || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)\n  ){\n    int iVar = pExpr->iColumn;\n    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);\n    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);\n    return SQLITE_OK;\n  }\n  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);\n}\n#endif\n\n/*\n** This function is used to estimate the number of rows that will be visited\n** by scanning an index for a range of values. The range may have an upper\n** bound, a lower bound, or both. The WHERE clause terms that set the upper\n** and lower bounds are represented by pLower and pUpper respectively. For\n** example, assuming that index p is on t1(a):\n**\n**   ... FROM t1 WHERE a > ? AND a < ? ...\n**                    |_____|   |_____|\n**                       |         |\n**                     pLower    pUpper\n**\n** If either of the upper or lower bound is not present, then NULL is passed in\n** place of the corresponding WhereTerm.\n**\n** The nEq parameter is passed the index of the index column subject to the\n** range constraint. Or, equivalently, the number of equality constraints\n** optimized by the proposed index scan. For example, assuming index p is\n** on t1(a, b), and the SQL query is:\n**\n**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...\n**\n** then nEq should be passed the value 1 (as the range restricted column,\n** b, is the second left-most column of the index). Or, if the query is:\n**\n**   ... FROM t1 WHERE a > ? AND a < ? ...\n**\n** then nEq should be passed 0.\n**\n** The returned value is an integer divisor to reduce the estimated\n** search space.  A return value of 1 means that range constraints are\n** no help at all.  A return value of 2 means range constraints are\n** expected to reduce the search space by half.  And so forth...\n**\n** In the absence of sqlite_stat3 ANALYZE data, each range inequality\n** reduces the search space by a factor of 4.  Hence a single constraint (x>?)\n** results in a return of 4 and a range constraint (x>? AND x<?) results\n** in a return of 16.\n*/\nstatic int whereRangeScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  Index *p,            /* The index containing the range-compared column; \"x\" */\n  int nEq,             /* index into p->aCol[] of the range-compared column */\n  WhereTerm *pLower,   /* Lower bound on the range. ex: \"x>123\" Might be NULL */\n  WhereTerm *pUpper,   /* Upper bound on the range. ex: \"x<455\" Might be NULL */\n  double *pRangeDiv   /* OUT: Reduce search space by this divisor */\n){\n  int rc = SQLITE_OK;\n\n#ifdef SQLITE_ENABLE_STAT3\n\n  if( nEq==0 && p->nSample ){\n    sqlite3_value *pRangeVal;\n    tRowcnt iLower = 0;\n    tRowcnt iUpper = p->aiRowEst[0];\n    tRowcnt a[2];\n    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;\n\n    if( pLower ){\n      Expr *pExpr = pLower->pExpr->pRight;\n      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);\n      assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );\n      if( rc==SQLITE_OK\n       && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK\n      ){\n        iLower = a[0];\n        if( pLower->eOperator==WO_GT ) iLower += a[1];\n      }\n      sqlite3ValueFree(pRangeVal);\n    }\n    if( rc==SQLITE_OK && pUpper ){\n      Expr *pExpr = pUpper->pExpr->pRight;\n      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);\n      assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );\n      if( rc==SQLITE_OK\n       && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK\n      ){\n        iUpper = a[0];\n        if( pUpper->eOperator==WO_LE ) iUpper += a[1];\n      }\n      sqlite3ValueFree(pRangeVal);\n    }\n    if( rc==SQLITE_OK ){\n      if( iUpper<=iLower ){\n        *pRangeDiv = (double)p->aiRowEst[0];\n      }else{\n        *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);\n      }\n      WHERETRACE((\"range scan regions: %u..%u  div=%g\\n\",\n                  (u32)iLower, (u32)iUpper, *pRangeDiv));\n      return SQLITE_OK;\n    }\n  }\n#else\n  UNUSED_PARAMETER(pParse);\n  UNUSED_PARAMETER(p);\n  UNUSED_PARAMETER(nEq);\n#endif\n  assert( pLower || pUpper );\n  *pRangeDiv = (double)1;\n  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;\n  if( pUpper ) *pRangeDiv *= (double)4;\n  return rc;\n}\n\n#ifdef SQLITE_ENABLE_STAT3\n/*\n** Estimate the number of rows that will be returned based on\n** an equality constraint x=VALUE and where that VALUE occurs in\n** the histogram data.  This only works when x is the left-most\n** column of an index and sqlite_stat3 histogram data is available\n** for that index.  When pExpr==NULL that means the constraint is\n** \"x IS NULL\" instead of \"x=VALUE\".\n**\n** Write the estimated row count into *pnRow and return SQLITE_OK. \n** If unable to make an estimate, leave *pnRow unchanged and return\n** non-zero.\n**\n** This routine can fail if it is unable to load a collating sequence\n** required for string comparison, or if unable to allocate memory\n** for a UTF conversion required for comparison.  The error is stored\n** in the pParse structure.\n*/\nstatic int whereEqualScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  Index *p,            /* The index whose left-most column is pTerm */\n  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */\n  double *pnRow        /* Write the revised row estimate here */\n){\n  sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */\n  u8 aff;                   /* Column affinity */\n  int rc;                   /* Subfunction return code */\n  tRowcnt a[2];             /* Statistics */\n\n  assert( p->aSample!=0 );\n  assert( p->nSample>0 );\n  aff = p->pTable->aCol[p->aiColumn[0]].affinity;\n  if( pExpr ){\n    rc = valueFromExpr(pParse, pExpr, aff, &pRhs);\n    if( rc ) goto whereEqualScanEst_cancel;\n  }else{\n    pRhs = sqlite3ValueNew(pParse->db);\n  }\n  if( pRhs==0 ) return SQLITE_NOTFOUND;\n  rc = whereKeyStats(pParse, p, pRhs, 0, a);\n  if( rc==SQLITE_OK ){\n    WHERETRACE((\"equality scan regions: %d\\n\", (int)a[1]));\n    *pnRow = a[1];\n  }\nwhereEqualScanEst_cancel:\n  sqlite3ValueFree(pRhs);\n  return rc;\n}\n#endif /* defined(SQLITE_ENABLE_STAT3) */\n\n#ifdef SQLITE_ENABLE_STAT3\n/*\n** Estimate the number of rows that will be returned based on\n** an IN constraint where the right-hand side of the IN operator\n** is a list of values.  Example:\n**\n**        WHERE x IN (1,2,3,4)\n**\n** Write the estimated row count into *pnRow and return SQLITE_OK. \n** If unable to make an estimate, leave *pnRow unchanged and return\n** non-zero.\n**\n** This routine can fail if it is unable to load a collating sequence\n** required for string comparison, or if unable to allocate memory\n** for a UTF conversion required for comparison.  The error is stored\n** in the pParse structure.\n*/\nstatic int whereInScanEst(\n  Parse *pParse,       /* Parsing & code generating context */\n  Index *p,            /* The index whose left-most column is pTerm */\n  ExprList *pList,     /* The value list on the RHS of \"x IN (v1,v2,v3,...)\" */\n  double *pnRow        /* Write the revised row estimate here */\n){\n  int rc = SQLITE_OK;         /* Subfunction return code */\n  double nEst;                /* Number of rows for a single term */\n  double nRowEst = (double)0; /* New estimate of the number of rows */\n  int i;                      /* Loop counter */\n\n  assert( p->aSample!=0 );\n  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){\n    nEst = p->aiRowEst[0];\n    rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);\n    nRowEst += nEst;\n  }\n  if( rc==SQLITE_OK ){\n    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];\n    *pnRow = nRowEst;\n    WHERETRACE((\"IN row estimate: est=%g\\n\", nRowEst));\n  }\n  return rc;\n}\n#endif /* defined(SQLITE_ENABLE_STAT3) */\n\n\n/*\n** Find the best query plan for accessing a particular table.  Write the\n** best query plan and its cost into the WhereCost object supplied as the\n** last parameter.\n**\n** The lowest cost plan wins.  The cost is an estimate of the amount of\n** CPU and disk I/O needed to process the requested result.\n** Factors that influence cost include:\n**\n**    *  The estimated number of rows that will be retrieved.  (The\n**       fewer the better.)\n**\n**    *  Whether or not sorting must occur.\n**\n**    *  Whether or not there must be separate lookups in the\n**       index and in the main table.\n**\n** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in\n** the SQL statement, then this function only considers plans using the \n** named index. If no such plan is found, then the returned cost is\n** SQLITE_BIG_DBL. If a plan is found that uses the named index, \n** then the cost is calculated in the usual way.\n**\n** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table \n** in the SELECT statement, then no indexes are considered. However, the \n** selected plan may still take advantage of the built-in rowid primary key\n** index.\n*/\nstatic void bestBtreeIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to search */\n  Bitmask notReady,           /* Mask of cursors not available for indexing */\n  Bitmask notValid,           /* Cursors not available for any purpose */\n  ExprList *pOrderBy,         /* The ORDER BY clause */\n  ExprList *pDistinct,        /* The select-list if query is DISTINCT */\n  WhereCost *pCost            /* Lowest cost query plan */\n){\n  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */\n  Index *pProbe;              /* An index we are evaluating */\n  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */\n  int eqTermMask;             /* Current mask of valid equality operators */\n  int idxEqTermMask;          /* Index mask of valid equality operators */\n  Index sPk;                  /* A fake index object for the primary key */\n  tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */\n  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */\n  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */\n\n  /* Initialize the cost to a worst-case value */\n  memset(pCost, 0, sizeof(*pCost));\n  pCost->rCost = SQLITE_BIG_DBL;\n\n  /* If the pSrc table is the right table of a LEFT JOIN then we may not\n  ** use an index to satisfy IS NULL constraints on that table.  This is\n  ** because columns might end up being NULL if the table does not match -\n  ** a circumstance which the index cannot help us discover.  Ticket #2177.\n  */\n  if( pSrc->jointype & JT_LEFT ){\n    idxEqTermMask = WO_EQ|WO_IN;\n  }else{\n    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;\n  }\n\n  if( pSrc->pIndex ){\n    /* An INDEXED BY clause specifies a particular index to use */\n    pIdx = pProbe = pSrc->pIndex;\n    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);\n    eqTermMask = idxEqTermMask;\n  }else{\n    /* There is no INDEXED BY clause.  Create a fake Index object in local\n    ** variable sPk to represent the rowid primary key index.  Make this\n    ** fake index the first in a chain of Index objects with all of the real\n    ** indices to follow */\n    Index *pFirst;                  /* First of real indices on the table */\n    memset(&sPk, 0, sizeof(Index));\n    sPk.nColumn = 1;\n    sPk.aiColumn = &aiColumnPk;\n    sPk.aiRowEst = aiRowEstPk;\n    sPk.onError = OE_Replace;\n    sPk.pTable = pSrc->pTab;\n    aiRowEstPk[0] = pSrc->pTab->nRowEst;\n    aiRowEstPk[1] = 1;\n    pFirst = pSrc->pTab->pIndex;\n    if( pSrc->notIndexed==0 ){\n      /* The real indices of the table are only considered if the\n      ** NOT INDEXED qualifier is omitted from the FROM clause */\n      sPk.pNext = pFirst;\n    }\n    pProbe = &sPk;\n    wsFlagMask = ~(\n        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE\n    );\n    eqTermMask = WO_EQ|WO_IN;\n    pIdx = 0;\n  }\n\n  /* Loop over all indices looking for the best one to use\n  */\n  for(; pProbe; pIdx=pProbe=pProbe->pNext){\n    const tRowcnt * const aiRowEst = pProbe->aiRowEst;\n    double cost;                /* Cost of using pProbe */\n    double nRow;                /* Estimated number of rows in result set */\n    double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */\n    int rev;                    /* True to scan in reverse order */\n    int wsFlags = 0;\n    Bitmask used = 0;\n\n    /* The following variables are populated based on the properties of\n    ** index being evaluated. They are then used to determine the expected\n    ** cost and number of rows returned.\n    **\n    **  nEq: \n    **    Number of equality terms that can be implemented using the index.\n    **    In other words, the number of initial fields in the index that\n    **    are used in == or IN or NOT NULL constraints of the WHERE clause.\n    **\n    **  nInMul:  \n    **    The \"in-multiplier\". This is an estimate of how many seek operations \n    **    SQLite must perform on the index in question. For example, if the \n    **    WHERE clause is:\n    **\n    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)\n    **\n    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is \n    **    set to 9. Given the same schema and either of the following WHERE \n    **    clauses:\n    **\n    **      WHERE a =  1\n    **      WHERE a >= 2\n    **\n    **    nInMul is set to 1.\n    **\n    **    If there exists a WHERE term of the form \"x IN (SELECT ...)\", then \n    **    the sub-select is assumed to return 25 rows for the purposes of \n    **    determining nInMul.\n    **\n    **  bInEst:  \n    **    Set to true if there was at least one \"x IN (SELECT ...)\" term used \n    **    in determining the value of nInMul.  Note that the RHS of the\n    **    IN operator must be a SELECT, not a value list, for this variable\n    **    to be true.\n    **\n    **  rangeDiv:\n    **    An estimate of a divisor by which to reduce the search space due\n    **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE\n    **    data, a single inequality reduces the search space to 1/4rd its\n    **    original size (rangeDiv==4).  Two inequalities reduce the search\n    **    space to 1/16th of its original size (rangeDiv==16).\n    **\n    **  bSort:   \n    **    Boolean. True if there is an ORDER BY clause that will require an \n    **    external sort (i.e. scanning the index being evaluated will not \n    **    correctly order records).\n    **\n    **  bLookup: \n    **    Boolean. True if a table lookup is required for each index entry\n    **    visited.  In other words, true if this is not a covering index.\n    **    This is always false for the rowid primary key index of a table.\n    **    For other indexes, it is true unless all the columns of the table\n    **    used by the SELECT statement are present in the index (such an\n    **    index is sometimes described as a covering index).\n    **    For example, given the index on (a, b), the second of the following \n    **    two queries requires table b-tree lookups in order to find the value\n    **    of column c, but the first does not because columns a and b are\n    **    both available in the index.\n    **\n    **             SELECT a, b    FROM tbl WHERE a = 1;\n    **             SELECT a, b, c FROM tbl WHERE a = 1;\n    */\n    int nEq;                      /* Number of == or IN terms matching index */\n    int bInEst = 0;               /* True if \"x IN (SELECT...)\" seen */\n    int nInMul = 1;               /* Number of distinct equalities to lookup */\n    double rangeDiv = (double)1;  /* Estimated reduction in search space */\n    int nBound = 0;               /* Number of range constraints seen */\n    int bSort = !!pOrderBy;       /* True if external sort required */\n    int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */\n    int bLookup = 0;              /* True if not a covering index */\n    WhereTerm *pTerm;             /* A single term of the WHERE clause */\n#ifdef SQLITE_ENABLE_STAT3\n    WhereTerm *pFirstTerm = 0;    /* First term matching the index */\n#endif\n\n    /* Determine the values of nEq and nInMul */\n    for(nEq=0; nEq<pProbe->nColumn; nEq++){\n      int j = pProbe->aiColumn[nEq];\n      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);\n      if( pTerm==0 ) break;\n      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);\n      testcase( pTerm->pWC!=pWC );\n      if( pTerm->eOperator & WO_IN ){\n        Expr *pExpr = pTerm->pExpr;\n        wsFlags |= WHERE_COLUMN_IN;\n        if( ExprHasProperty(pExpr, EP_xIsSelect) ){\n          /* \"x IN (SELECT ...)\":  Assume the SELECT returns 25 rows */\n          nInMul *= 25;\n          bInEst = 1;\n        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){\n          /* \"x IN (value, value, ...)\" */\n          nInMul *= pExpr->x.pList->nExpr;\n        }\n      }else if( pTerm->eOperator & WO_ISNULL ){\n        wsFlags |= WHERE_COLUMN_NULL;\n      }\n#ifdef SQLITE_ENABLE_STAT3\n      if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;\n#endif\n      used |= pTerm->prereqRight;\n    }\n \n    /* If the index being considered is UNIQUE, and there is an equality \n    ** constraint for all columns in the index, then this search will find\n    ** at most a single row. In this case set the WHERE_UNIQUE flag to \n    ** indicate this to the caller.\n    **\n    ** Otherwise, if the search may find more than one row, test to see if\n    ** there is a range constraint on indexed column (nEq+1) that can be \n    ** optimized using the index. \n    */\n    if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){\n      testcase( wsFlags & WHERE_COLUMN_IN );\n      testcase( wsFlags & WHERE_COLUMN_NULL );\n      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){\n        wsFlags |= WHERE_UNIQUE;\n      }\n    }else if( pProbe->bUnordered==0 ){\n      int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);\n      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){\n        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);\n        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);\n        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);\n        if( pTop ){\n          nBound = 1;\n          wsFlags |= WHERE_TOP_LIMIT;\n          used |= pTop->prereqRight;\n          testcase( pTop->pWC!=pWC );\n        }\n        if( pBtm ){\n          nBound++;\n          wsFlags |= WHERE_BTM_LIMIT;\n          used |= pBtm->prereqRight;\n          testcase( pBtm->pWC!=pWC );\n        }\n        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);\n      }\n    }\n\n    /* If there is an ORDER BY clause and the index being considered will\n    ** naturally scan rows in the required order, set the appropriate flags\n    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index\n    ** will scan rows in a different order, set the bSort variable.  */\n    if( isSortingIndex(\n          pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)\n    ){\n      bSort = 0;\n      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;\n      wsFlags |= (rev ? WHERE_REVERSE : 0);\n    }\n\n    /* If there is a DISTINCT qualifier and this index will scan rows in\n    ** order of the DISTINCT expressions, clear bDist and set the appropriate\n    ** flags in wsFlags. */\n    if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)\n     && (wsFlags & WHERE_COLUMN_IN)==0\n    ){\n      bDist = 0;\n      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;\n    }\n\n    /* If currently calculating the cost of using an index (not the IPK\n    ** index), determine if all required column data may be obtained without \n    ** using the main table (i.e. if the index is a covering\n    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in\n    ** wsFlags. Otherwise, set the bLookup variable to true.  */\n    if( pIdx && wsFlags ){\n      Bitmask m = pSrc->colUsed;\n      int j;\n      for(j=0; j<pIdx->nColumn; j++){\n        int x = pIdx->aiColumn[j];\n        if( x<BMS-1 ){\n          m &= ~(((Bitmask)1)<<x);\n        }\n      }\n      if( m==0 ){\n        wsFlags |= WHERE_IDX_ONLY;\n      }else{\n        bLookup = 1;\n      }\n    }\n\n    /*\n    ** Estimate the number of rows of output.  For an \"x IN (SELECT...)\"\n    ** constraint, do not let the estimate exceed half the rows in the table.\n    */\n    nRow = (double)(aiRowEst[nEq] * nInMul);\n    if( bInEst && nRow*2>aiRowEst[0] ){\n      nRow = aiRowEst[0]/2;\n      nInMul = (int)(nRow / aiRowEst[nEq]);\n    }\n\n#ifdef SQLITE_ENABLE_STAT3\n    /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)\n    ** and we do not think that values of x are unique and if histogram\n    ** data is available for column x, then it might be possible\n    ** to get a better estimate on the number of rows based on\n    ** VALUE and how common that value is according to the histogram.\n    */\n    if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){\n      assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );\n      if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){\n        testcase( pFirstTerm->eOperator==WO_EQ );\n        testcase( pFirstTerm->eOperator==WO_ISNULL );\n        whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);\n      }else if( bInEst==0 ){\n        assert( pFirstTerm->eOperator==WO_IN );\n        whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);\n      }\n    }\n#endif /* SQLITE_ENABLE_STAT3 */\n\n    /* Adjust the number of output rows and downward to reflect rows\n    ** that are excluded by range constraints.\n    */\n    nRow = nRow/rangeDiv;\n    if( nRow<1 ) nRow = 1;\n\n    /* Experiments run on real SQLite databases show that the time needed\n    ** to do a binary search to locate a row in a table or index is roughly\n    ** log10(N) times the time to move from one row to the next row within\n    ** a table or index.  The actual times can vary, with the size of\n    ** records being an important factor.  Both moves and searches are\n    ** slower with larger records, presumably because fewer records fit\n    ** on one page and hence more pages have to be fetched.\n    **\n    ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do\n    ** not give us data on the relative sizes of table and index records.\n    ** So this computation assumes table records are about twice as big\n    ** as index records\n    */\n    if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){\n      /* The cost of a full table scan is a number of move operations equal\n      ** to the number of rows in the table.\n      **\n      ** We add an additional 4x penalty to full table scans.  This causes\n      ** the cost function to err on the side of choosing an index over\n      ** choosing a full scan.  This 4x full-scan penalty is an arguable\n      ** decision and one which we expect to revisit in the future.  But\n      ** it seems to be working well enough at the moment.\n      */\n      cost = aiRowEst[0]*4;\n    }else{\n      log10N = estLog(aiRowEst[0]);\n      cost = nRow;\n      if( pIdx ){\n        if( bLookup ){\n          /* For an index lookup followed by a table lookup:\n          **    nInMul index searches to find the start of each index range\n          **  + nRow steps through the index\n          **  + nRow table searches to lookup the table entry using the rowid\n          */\n          cost += (nInMul + nRow)*log10N;\n        }else{\n          /* For a covering index:\n          **     nInMul index searches to find the initial entry \n          **   + nRow steps through the index\n          */\n          cost += nInMul*log10N;\n        }\n      }else{\n        /* For a rowid primary key lookup:\n        **    nInMult table searches to find the initial entry for each range\n        **  + nRow steps through the table\n        */\n        cost += nInMul*log10N;\n      }\n    }\n\n    /* Add in the estimated cost of sorting the result.  Actual experimental\n    ** measurements of sorting performance in SQLite show that sorting time\n    ** adds C*N*log10(N) to the cost, where N is the number of rows to be \n    ** sorted and C is a factor between 1.95 and 4.3.  We will split the\n    ** difference and select C of 3.0.\n    */\n    if( bSort ){\n      cost += nRow*estLog(nRow)*3;\n    }\n    if( bDist ){\n      cost += nRow*estLog(nRow)*3;\n    }\n\n    /**** Cost of using this index has now been computed ****/\n\n    /* If there are additional constraints on this table that cannot\n    ** be used with the current index, but which might lower the number\n    ** of output rows, adjust the nRow value accordingly.  This only \n    ** matters if the current index is the least costly, so do not bother\n    ** with this step if we already know this index will not be chosen.\n    ** Also, never reduce the output row count below 2 using this step.\n    **\n    ** It is critical that the notValid mask be used here instead of\n    ** the notReady mask.  When computing an \"optimal\" index, the notReady\n    ** mask will only have one bit set - the bit for the current table.\n    ** The notValid mask, on the other hand, always has all bits set for\n    ** tables that are not in outer loops.  If notReady is used here instead\n    ** of notValid, then a optimal index that depends on inner joins loops\n    ** might be selected even when there exists an optimal index that has\n    ** no such dependency.\n    */\n    if( nRow>2 && cost<=pCost->rCost ){\n      int k;                       /* Loop counter */\n      int nSkipEq = nEq;           /* Number of == constraints to skip */\n      int nSkipRange = nBound;     /* Number of < constraints to skip */\n      Bitmask thisTab;             /* Bitmap for pSrc */\n\n      thisTab = getMask(pWC->pMaskSet, iCur);\n      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){\n        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;\n        if( (pTerm->prereqAll & notValid)!=thisTab ) continue;\n        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){\n          if( nSkipEq ){\n            /* Ignore the first nEq equality matches since the index\n            ** has already accounted for these */\n            nSkipEq--;\n          }else{\n            /* Assume each additional equality match reduces the result\n            ** set size by a factor of 10 */\n            nRow /= 10;\n          }\n        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){\n          if( nSkipRange ){\n            /* Ignore the first nSkipRange range constraints since the index\n            ** has already accounted for these */\n            nSkipRange--;\n          }else{\n            /* Assume each additional range constraint reduces the result\n            ** set size by a factor of 3.  Indexed range constraints reduce\n            ** the search space by a larger factor: 4.  We make indexed range\n            ** more selective intentionally because of the subjective \n            ** observation that indexed range constraints really are more\n            ** selective in practice, on average. */\n            nRow /= 3;\n          }\n        }else if( pTerm->eOperator!=WO_NOOP ){\n          /* Any other expression lowers the output row count by half */\n          nRow /= 2;\n        }\n      }\n      if( nRow<2 ) nRow = 2;\n    }\n\n\n    WHERETRACE((\n      \"%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\\n\"\n      \"         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\\n\",\n      pSrc->pTab->zName, (pIdx ? pIdx->zName : \"ipk\"), \n      nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,\n      notReady, log10N, nRow, cost, used\n    ));\n\n    /* If this index is the best we have seen so far, then record this\n    ** index and its cost in the pCost structure.\n    */\n    if( (!pIdx || wsFlags)\n     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))\n    ){\n      pCost->rCost = cost;\n      pCost->used = used;\n      pCost->plan.nRow = nRow;\n      pCost->plan.wsFlags = (wsFlags&wsFlagMask);\n      pCost->plan.nEq = nEq;\n      pCost->plan.u.pIdx = pIdx;\n    }\n\n    /* If there was an INDEXED BY clause, then only that one index is\n    ** considered. */\n    if( pSrc->pIndex ) break;\n\n    /* Reset masks for the next index in the loop */\n    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);\n    eqTermMask = idxEqTermMask;\n  }\n\n  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag\n  ** is set, then reverse the order that the index will be scanned\n  ** in. This is used for application testing, to help find cases\n  ** where application behaviour depends on the (undefined) order that\n  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */\n  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){\n    pCost->plan.wsFlags |= WHERE_REVERSE;\n  }\n\n  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );\n  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );\n  assert( pSrc->pIndex==0 \n       || pCost->plan.u.pIdx==0 \n       || pCost->plan.u.pIdx==pSrc->pIndex \n  );\n\n  WHERETRACE((\"best index is: %s\\n\", \n    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? \"none\" : \n         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : \"ipk\")\n  ));\n  \n  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);\n  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);\n  pCost->plan.wsFlags |= eqTermMask;\n}\n\n/*\n** Find the query plan for accessing table pSrc->pTab. Write the\n** best query plan and its cost into the WhereCost object supplied \n** as the last parameter. This function may calculate the cost of\n** both real and virtual table scans.\n*/\nstatic void bestIndex(\n  Parse *pParse,              /* The parsing context */\n  WhereClause *pWC,           /* The WHERE clause */\n  struct SrcList_item *pSrc,  /* The FROM clause term to search */\n  Bitmask notReady,           /* Mask of cursors not available for indexing */\n  Bitmask notValid,           /* Cursors not available for any purpose */\n  ExprList *pOrderBy,         /* The ORDER BY clause */\n  WhereCost *pCost            /* Lowest cost query plan */\n){\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if( IsVirtual(pSrc->pTab) ){\n    sqlite3_index_info *p = 0;\n    bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);\n    if( p->needToFreeIdxStr ){\n      sqlite3_free(p->idxStr);\n    }\n    sqlite3DbFree(pParse->db, p);\n  }else\n#endif\n  {\n    bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);\n  }\n}\n\n/*\n** Disable a term in the WHERE clause.  Except, do not disable the term\n** if it controls a LEFT OUTER JOIN and it did not originate in the ON\n** or USING clause of that join.\n**\n** Consider the term t2.z='ok' in the following queries:\n**\n**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'\n**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'\n**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'\n**\n** The t2.z='ok' is disabled in the in (2) because it originates\n** in the ON clause.  The term is disabled in (3) because it is not part\n** of a LEFT OUTER JOIN.  In (1), the term is not disabled.\n**\n** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are\n** completely satisfied by indices.\n**\n** Disabling a term causes that term to not be tested in the inner loop\n** of the join.  Disabling is an optimization.  When terms are satisfied\n** by indices, we disable them to prevent redundant tests in the inner\n** loop.  We would get the correct results if nothing were ever disabled,\n** but joins might run a little slower.  The trick is to disable as much\n** as we can without disabling too much.  If we disabled in (1), we'd get\n** the wrong answer.  See ticket #813.\n*/\nstatic void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){\n  if( pTerm\n      && (pTerm->wtFlags & TERM_CODED)==0\n      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))\n  ){\n    pTerm->wtFlags |= TERM_CODED;\n    if( pTerm->iParent>=0 ){\n      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];\n      if( (--pOther->nChild)==0 ){\n        disableTerm(pLevel, pOther);\n      }\n    }\n  }\n}\n\n/*\n** Code an OP_Affinity opcode to apply the column affinity string zAff\n** to the n registers starting at base. \n**\n** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the\n** beginning and end of zAff are ignored.  If all entries in zAff are\n** SQLITE_AFF_NONE, then no code gets generated.\n**\n** This routine makes its own copy of zAff so that the caller is free\n** to modify zAff after this routine returns.\n*/\nstatic void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){\n  Vdbe *v = pParse->pVdbe;\n  if( zAff==0 ){\n    assert( pParse->db->mallocFailed );\n    return;\n  }\n  assert( v!=0 );\n\n  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning\n  ** and end of the affinity string.\n  */\n  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){\n    n--;\n    base++;\n    zAff++;\n  }\n  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){\n    n--;\n  }\n\n  /* Code the OP_Affinity opcode if there is anything left to do. */\n  if( n>0 ){\n    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);\n    sqlite3VdbeChangeP4(v, -1, zAff, n);\n    sqlite3ExprCacheAffinityChange(pParse, base, n);\n  }\n}\n\n\n/*\n** Generate code for a single equality term of the WHERE clause.  An equality\n** term can be either X=expr or X IN (...).   pTerm is the term to be \n** coded.\n**\n** The current value for the constraint is left in register iReg.\n**\n** For a constraint of the form X=expr, the expression is evaluated and its\n** result is left on the stack.  For constraints of the form X IN (...)\n** this routine sets up a loop that will iterate over all values of X.\n*/\nstatic int codeEqualityTerm(\n  Parse *pParse,      /* The parsing context */\n  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */\n  WhereLevel *pLevel, /* When level of the FROM clause we are working on */\n  int iTarget         /* Attempt to leave results in this register */\n){\n  Expr *pX = pTerm->pExpr;\n  Vdbe *v = pParse->pVdbe;\n  int iReg;                  /* Register holding results */\n\n  assert( iTarget>0 );\n  if( pX->op==TK_EQ ){\n    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);\n  }else if( pX->op==TK_ISNULL ){\n    iReg = iTarget;\n    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);\n#ifndef SQLITE_OMIT_SUBQUERY\n  }else{\n    int eType;\n    int iTab;\n    struct InLoop *pIn;\n\n    assert( pX->op==TK_IN );\n    iReg = iTarget;\n    eType = sqlite3FindInIndex(pParse, pX, 0);\n    iTab = pX->iTable;\n    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);\n    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );\n    if( pLevel->u.in.nIn==0 ){\n      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);\n    }\n    pLevel->u.in.nIn++;\n    pLevel->u.in.aInLoop =\n       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,\n                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);\n    pIn = pLevel->u.in.aInLoop;\n    if( pIn ){\n      pIn += pLevel->u.in.nIn - 1;\n      pIn->iCur = iTab;\n      if( eType==IN_INDEX_ROWID ){\n        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);\n      }else{\n        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);\n      }\n      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);\n    }else{\n      pLevel->u.in.nIn = 0;\n    }\n#endif\n  }\n  disableTerm(pLevel, pTerm);\n  return iReg;\n}\n\n/*\n** Generate code that will evaluate all == and IN constraints for an\n** index.\n**\n** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).\n** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10\n** The index has as many as three equality constraints, but in this\n** example, the third \"c\" value is an inequality.  So only two \n** constraints are coded.  This routine will generate code to evaluate\n** a==5 and b IN (1,2,3).  The current values for a and b will be stored\n** in consecutive registers and the index of the first register is returned.\n**\n** In the example above nEq==2.  But this subroutine works for any value\n** of nEq including 0.  If nEq==0, this routine is nearly a no-op.\n** The only thing it does is allocate the pLevel->iMem memory cell and\n** compute the affinity string.\n**\n** This routine always allocates at least one memory cell and returns\n** the index of that memory cell. The code that\n** calls this routine will use that memory cell to store the termination\n** key value of the loop.  If one or more IN operators appear, then\n** this routine allocates an additional nEq memory cells for internal\n** use.\n**\n** Before returning, *pzAff is set to point to a buffer containing a\n** copy of the column affinity string of the index allocated using\n** sqlite3DbMalloc(). Except, entries in the copy of the string associated\n** with equality constraints that use NONE affinity are set to\n** SQLITE_AFF_NONE. This is to deal with SQL such as the following:\n**\n**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);\n**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;\n**\n** In the example above, the index on t1(a) has TEXT affinity. But since\n** the right hand side of the equality constraint (t2.b) has NONE affinity,\n** no conversion should be attempted before using a t2.b value as part of\n** a key to search the index. Hence the first byte in the returned affinity\n** string in this example would be set to SQLITE_AFF_NONE.\n*/\nstatic int codeAllEqualityTerms(\n  Parse *pParse,        /* Parsing context */\n  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */\n  WhereClause *pWC,     /* The WHERE clause */\n  Bitmask notReady,     /* Which parts of FROM have not yet been coded */\n  int nExtraReg,        /* Number of extra registers to allocate */\n  char **pzAff          /* OUT: Set to point to affinity string */\n){\n  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */\n  Vdbe *v = pParse->pVdbe;      /* The vm under construction */\n  Index *pIdx;                  /* The index being used for this loop */\n  int iCur = pLevel->iTabCur;   /* The cursor of the table */\n  WhereTerm *pTerm;             /* A single constraint term */\n  int j;                        /* Loop counter */\n  int regBase;                  /* Base register */\n  int nReg;                     /* Number of registers to allocate */\n  char *zAff;                   /* Affinity string to return */\n\n  /* This module is only called on query plans that use an index. */\n  assert( pLevel->plan.wsFlags & WHERE_INDEXED );\n  pIdx = pLevel->plan.u.pIdx;\n\n  /* Figure out how many memory cells we will need then allocate them.\n  */\n  regBase = pParse->nMem + 1;\n  nReg = pLevel->plan.nEq + nExtraReg;\n  pParse->nMem += nReg;\n\n  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));\n  if( !zAff ){\n    pParse->db->mallocFailed = 1;\n  }\n\n  /* Evaluate the equality constraints\n  */\n  assert( pIdx->nColumn>=nEq );\n  for(j=0; j<nEq; j++){\n    int r1;\n    int k = pIdx->aiColumn[j];\n    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);\n    if( pTerm==0 ) break;\n    /* The following true for indices with redundant columns. \n    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */\n    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );\n    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);\n    if( r1!=regBase+j ){\n      if( nReg==1 ){\n        sqlite3ReleaseTempReg(pParse, regBase);\n        regBase = r1;\n      }else{\n        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);\n      }\n    }\n    testcase( pTerm->eOperator & WO_ISNULL );\n    testcase( pTerm->eOperator & WO_IN );\n    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){\n      Expr *pRight = pTerm->pExpr->pRight;\n      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);\n      if( zAff ){\n        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){\n          zAff[j] = SQLITE_AFF_NONE;\n        }\n        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){\n          zAff[j] = SQLITE_AFF_NONE;\n        }\n      }\n    }\n  }\n  *pzAff = zAff;\n  return regBase;\n}\n\n#ifndef SQLITE_OMIT_EXPLAIN\n/*\n** This routine is a helper for explainIndexRange() below\n**\n** pStr holds the text of an expression that we are building up one term\n** at a time.  This routine adds a new term to the end of the expression.\n** Terms are separated by AND so add the \"AND\" text for second and subsequent\n** terms only.\n*/\nstatic void explainAppendTerm(\n  StrAccum *pStr,             /* The text expression being built */\n  int iTerm,                  /* Index of this term.  First is zero */\n  const char *zColumn,        /* Name of the column */\n  const char *zOp             /* Name of the operator */\n){\n  if( iTerm ) sqlite3StrAccumAppend(pStr, \" AND \", 5);\n  sqlite3StrAccumAppend(pStr, zColumn, -1);\n  sqlite3StrAccumAppend(pStr, zOp, 1);\n  sqlite3StrAccumAppend(pStr, \"?\", 1);\n}\n\n/*\n** Argument pLevel describes a strategy for scanning table pTab. This \n** function returns a pointer to a string buffer containing a description\n** of the subset of table rows scanned by the strategy in the form of an\n** SQL expression. Or, if all rows are scanned, NULL is returned.\n**\n** For example, if the query:\n**\n**   SELECT * FROM t1 WHERE a=1 AND b>2;\n**\n** is run and there is an index on (a, b), then this function returns a\n** string similar to:\n**\n**   \"a=? AND b>?\"\n**\n** The returned pointer points to memory obtained from sqlite3DbMalloc().\n** It is the responsibility of the caller to free the buffer when it is\n** no longer required.\n*/\nstatic char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){\n  WherePlan *pPlan = &pLevel->plan;\n  Index *pIndex = pPlan->u.pIdx;\n  int nEq = pPlan->nEq;\n  int i, j;\n  Column *aCol = pTab->aCol;\n  int *aiColumn = pIndex->aiColumn;\n  StrAccum txt;\n\n  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){\n    return 0;\n  }\n  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);\n  txt.db = db;\n  sqlite3StrAccumAppend(&txt, \" (\", 2);\n  for(i=0; i<nEq; i++){\n    explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, \"=\");\n  }\n\n  j = i;\n  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){\n    char *z = (j==pIndex->nColumn ) ? \"rowid\" : aCol[aiColumn[j]].zName;\n    explainAppendTerm(&txt, i++, z, \">\");\n  }\n  if( pPlan->wsFlags&WHERE_TOP_LIMIT ){\n    char *z = (j==pIndex->nColumn ) ? \"rowid\" : aCol[aiColumn[j]].zName;\n    explainAppendTerm(&txt, i, z, \"<\");\n  }\n  sqlite3StrAccumAppend(&txt, \")\", 1);\n  return sqlite3StrAccumFinish(&txt);\n}\n\n/*\n** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN\n** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single\n** record is added to the output to describe the table scan strategy in \n** pLevel.\n*/\nstatic void explainOneScan(\n  Parse *pParse,                  /* Parse context */\n  SrcList *pTabList,              /* Table list this loop refers to */\n  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */\n  int iLevel,                     /* Value for \"level\" column of output */\n  int iFrom,                      /* Value for \"from\" column of output */\n  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */\n){\n  if( pParse->explain==2 ){\n    u32 flags = pLevel->plan.wsFlags;\n    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];\n    Vdbe *v = pParse->pVdbe;      /* VM being constructed */\n    sqlite3 *db = pParse->db;     /* Database handle */\n    char *zMsg;                   /* Text to add to EQP output */\n    sqlite3_int64 nRow;           /* Expected number of rows visited by scan */\n    int iId = pParse->iSelectId;  /* Select id (left-most output column) */\n    int isSearch;                 /* True for a SEARCH. False for SCAN. */\n\n    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;\n\n    isSearch = (pLevel->plan.nEq>0)\n             || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0\n             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));\n\n    zMsg = sqlite3MPrintf(db, \"%s\", isSearch?\"SEARCH\":\"SCAN\");\n    if( pItem->pSelect ){\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s SUBQUERY %d\", zMsg,pItem->iSelectId);\n    }else{\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s TABLE %s\", zMsg, pItem->zName);\n    }\n\n    if( pItem->zAlias ){\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s AS %s\", zMsg, pItem->zAlias);\n    }\n    if( (flags & WHERE_INDEXED)!=0 ){\n      char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s USING %s%sINDEX%s%s%s\", zMsg, \n          ((flags & WHERE_TEMP_INDEX)?\"AUTOMATIC \":\"\"),\n          ((flags & WHERE_IDX_ONLY)?\"COVERING \":\"\"),\n          ((flags & WHERE_TEMP_INDEX)?\"\":\" \"),\n          ((flags & WHERE_TEMP_INDEX)?\"\": pLevel->plan.u.pIdx->zName),\n          zWhere\n      );\n      sqlite3DbFree(db, zWhere);\n    }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s USING INTEGER PRIMARY KEY\", zMsg);\n\n      if( flags&WHERE_ROWID_EQ ){\n        zMsg = sqlite3MAppendf(db, zMsg, \"%s (rowid=?)\", zMsg);\n      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){\n        zMsg = sqlite3MAppendf(db, zMsg, \"%s (rowid>? AND rowid<?)\", zMsg);\n      }else if( flags&WHERE_BTM_LIMIT ){\n        zMsg = sqlite3MAppendf(db, zMsg, \"%s (rowid>?)\", zMsg);\n      }else if( flags&WHERE_TOP_LIMIT ){\n        zMsg = sqlite3MAppendf(db, zMsg, \"%s (rowid<?)\", zMsg);\n      }\n    }\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){\n      sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;\n      zMsg = sqlite3MAppendf(db, zMsg, \"%s VIRTUAL TABLE INDEX %d:%s\", zMsg,\n                  pVtabIdx->idxNum, pVtabIdx->idxStr);\n    }\n#endif\n    if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){\n      testcase( wctrlFlags & WHERE_ORDERBY_MIN );\n      nRow = 1;\n    }else{\n      nRow = (sqlite3_int64)pLevel->plan.nRow;\n    }\n    zMsg = sqlite3MAppendf(db, zMsg, \"%s (~%lld rows)\", zMsg, nRow);\n    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);\n  }\n}\n#else\n# define explainOneScan(u,v,w,x,y,z)\n#endif /* SQLITE_OMIT_EXPLAIN */\n\n\n/*\n** Generate code for the start of the iLevel-th loop in the WHERE clause\n** implementation described by pWInfo.\n*/\nstatic Bitmask codeOneLoopStart(\n  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */\n  int iLevel,          /* Which level of pWInfo->a[] should be coded */\n  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */\n  Bitmask notReady     /* Which tables are currently available */\n){\n  int j, k;            /* Loop counters */\n  int iCur;            /* The VDBE cursor for the table */\n  int addrNxt;         /* Where to jump to continue with the next IN case */\n  int omitTable;       /* True if we use the index only */\n  int bRev;            /* True if we need to scan in reverse order */\n  WhereLevel *pLevel;  /* The where level to be coded */\n  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */\n  WhereTerm *pTerm;               /* A WHERE clause term */\n  Parse *pParse;                  /* Parsing context */\n  Vdbe *v;                        /* The prepared stmt under constructions */\n  struct SrcList_item *pTabItem;  /* FROM clause term being coded */\n  int addrBrk;                    /* Jump here to break out of the loop */\n  int addrCont;                   /* Jump here to continue with next cycle */\n  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */\n  int iReleaseReg = 0;      /* Temp register to free before returning */\n\n  pParse = pWInfo->pParse;\n  v = pParse->pVdbe;\n  pWC = pWInfo->pWC;\n  pLevel = &pWInfo->a[iLevel];\n  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];\n  iCur = pTabItem->iCursor;\n  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;\n  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 \n           && (wctrlFlags & WHERE_FORCE_TABLE)==0;\n\n  /* Create labels for the \"break\" and \"continue\" instructions\n  ** for the current loop.  Jump to addrBrk to break out of a loop.\n  ** Jump to cont to go immediately to the next iteration of the\n  ** loop.\n  **\n  ** When there is an IN operator, we also have a \"addrNxt\" label that\n  ** means to continue with the next IN value combination.  When\n  ** there are no IN operators in the constraints, the \"addrNxt\" label\n  ** is the same as \"addrBrk\".\n  */\n  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);\n  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);\n\n  /* If this is the right table of a LEFT OUTER JOIN, allocate and\n  ** initialize a memory cell that records if this table matches any\n  ** row of the left table of the join.\n  */\n  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){\n    pLevel->iLeftJoin = ++pParse->nMem;\n    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);\n    VdbeComment((v, \"init LEFT JOIN no-match flag\"));\n  }\n\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){\n    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext\n    **          to access the data.\n    */\n    int iReg;   /* P3 Value for OP_VFilter */\n    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;\n    int nConstraint = pVtabIdx->nConstraint;\n    struct sqlite3_index_constraint_usage *aUsage =\n                                                pVtabIdx->aConstraintUsage;\n    const struct sqlite3_index_constraint *aConstraint =\n                                                pVtabIdx->aConstraint;\n\n    sqlite3ExprCachePush(pParse);\n    iReg = sqlite3GetTempRange(pParse, nConstraint+2);\n    for(j=1; j<=nConstraint; j++){\n      for(k=0; k<nConstraint; k++){\n        if( aUsage[k].argvIndex==j ){\n          int iTerm = aConstraint[k].iTermOffset;\n          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);\n          break;\n        }\n      }\n      if( k==nConstraint ) break;\n    }\n    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);\n    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);\n    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,\n                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);\n    pVtabIdx->needToFreeIdxStr = 0;\n    for(j=0; j<nConstraint; j++){\n      if( aUsage[j].omit ){\n        int iTerm = aConstraint[j].iTermOffset;\n        disableTerm(pLevel, &pWC->a[iTerm]);\n      }\n    }\n    pLevel->op = OP_VNext;\n    pLevel->p1 = iCur;\n    pLevel->p2 = sqlite3VdbeCurrentAddr(v);\n    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);\n    sqlite3ExprCachePop(pParse, 1);\n  }else\n#endif /* SQLITE_OMIT_VIRTUALTABLE */\n\n  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){\n    /* Case 1:  We can directly reference a single row using an\n    **          equality comparison against the ROWID field.  Or\n    **          we reference multiple rows using a \"rowid IN (...)\"\n    **          construct.\n    */\n    iReleaseReg = sqlite3GetTempReg(pParse);\n    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);\n    assert( pTerm!=0 );\n    assert( pTerm->pExpr!=0 );\n    assert( pTerm->leftCursor==iCur );\n    assert( omitTable==0 );\n    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);\n    addrNxt = pLevel->addrNxt;\n    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);\n    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);\n    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);\n    VdbeComment((v, \"pk\"));\n    pLevel->op = OP_Noop;\n  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){\n    /* Case 2:  We have an inequality comparison against the ROWID field.\n    */\n    int testOp = OP_Noop;\n    int start;\n    int memEndValue = 0;\n    WhereTerm *pStart, *pEnd;\n\n    assert( omitTable==0 );\n    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);\n    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);\n    if( bRev ){\n      pTerm = pStart;\n      pStart = pEnd;\n      pEnd = pTerm;\n    }\n    if( pStart ){\n      Expr *pX;             /* The expression that defines the start bound */\n      int r1, rTemp;        /* Registers for holding the start boundary */\n\n      /* The following constant maps TK_xx codes into corresponding \n      ** seek opcodes.  It depends on a particular ordering of TK_xx\n      */\n      const u8 aMoveOp[] = {\n           /* TK_GT */  OP_SeekGt,\n           /* TK_LE */  OP_SeekLe,\n           /* TK_LT */  OP_SeekLt,\n           /* TK_GE */  OP_SeekGe\n      };\n      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */\n      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */\n      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */\n\n      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n      pX = pStart->pExpr;\n      assert( pX!=0 );\n      assert( pStart->leftCursor==iCur );\n      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);\n      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);\n      VdbeComment((v, \"pk\"));\n      sqlite3ExprCacheAffinityChange(pParse, r1, 1);\n      sqlite3ReleaseTempReg(pParse, rTemp);\n      disableTerm(pLevel, pStart);\n    }else{\n      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);\n    }\n    if( pEnd ){\n      Expr *pX;\n      pX = pEnd->pExpr;\n      assert( pX!=0 );\n      assert( pEnd->leftCursor==iCur );\n      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n      memEndValue = ++pParse->nMem;\n      sqlite3ExprCode(pParse, pX->pRight, memEndValue);\n      if( pX->op==TK_LT || pX->op==TK_GT ){\n        testOp = bRev ? OP_Le : OP_Ge;\n      }else{\n        testOp = bRev ? OP_Lt : OP_Gt;\n      }\n      disableTerm(pLevel, pEnd);\n    }\n    start = sqlite3VdbeCurrentAddr(v);\n    pLevel->op = bRev ? OP_Prev : OP_Next;\n    pLevel->p1 = iCur;\n    pLevel->p2 = start;\n    if( pStart==0 && pEnd==0 ){\n      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;\n    }else{\n      assert( pLevel->p5==0 );\n    }\n    if( testOp!=OP_Noop ){\n      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);\n      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);\n      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);\n      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);\n    }\n  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){\n    /* Case 3: A scan using an index.\n    **\n    **         The WHERE clause may contain zero or more equality \n    **         terms (\"==\" or \"IN\" operators) that refer to the N\n    **         left-most columns of the index. It may also contain\n    **         inequality constraints (>, <, >= or <=) on the indexed\n    **         column that immediately follows the N equalities. Only \n    **         the right-most column can be an inequality - the rest must\n    **         use the \"==\" and \"IN\" operators. For example, if the \n    **         index is on (x,y,z), then the following clauses are all \n    **         optimized:\n    **\n    **            x=5\n    **            x=5 AND y=10\n    **            x=5 AND y<10\n    **            x=5 AND y>5 AND y<10\n    **            x=5 AND y=5 AND z<=10\n    **\n    **         The z<10 term of the following cannot be used, only\n    **         the x=5 term:\n    **\n    **            x=5 AND z<10\n    **\n    **         N may be zero if there are inequality constraints.\n    **         If there are no inequality constraints, then N is at\n    **         least one.\n    **\n    **         This case is also used when there are no WHERE clause\n    **         constraints but an index is selected anyway, in order\n    **         to force the output order to conform to an ORDER BY.\n    */  \n    static const u8 aStartOp[] = {\n      0,\n      0,\n      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */\n      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */\n      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */\n      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */\n      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */\n      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */\n    };\n    static const u8 aEndOp[] = {\n      OP_Noop,             /* 0: (!end_constraints) */\n      OP_IdxGE,            /* 1: (end_constraints && !bRev) */\n      OP_IdxLT             /* 2: (end_constraints && bRev) */\n    };\n    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */\n    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */\n    int regBase;                 /* Base register holding constraint values */\n    int r1;                      /* Temp register */\n    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */\n    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */\n    int startEq;                 /* True if range start uses ==, >= or <= */\n    int endEq;                   /* True if range end uses ==, >= or <= */\n    int start_constraints;       /* Start of range is constrained */\n    int nConstraint;             /* Number of constraint terms */\n    Index *pIdx;                 /* The index we will be using */\n    int iIdxCur;                 /* The VDBE cursor for the index */\n    int nExtraReg = 0;           /* Number of extra registers needed */\n    int op;                      /* Instruction opcode */\n    char *zStartAff;             /* Affinity for start of range constraint */\n    char *zEndAff;               /* Affinity for end of range constraint */\n\n    pIdx = pLevel->plan.u.pIdx;\n    iIdxCur = pLevel->iIdxCur;\n    k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);\n\n    /* If this loop satisfies a sort order (pOrderBy) request that \n    ** was passed to this function to implement a \"SELECT min(x) ...\" \n    ** query, then the caller will only allow the loop to run for\n    ** a single iteration. This means that the first row returned\n    ** should not have a NULL value stored in 'x'. If column 'x' is\n    ** the first one after the nEq equality constraints in the index,\n    ** this requires some special handling.\n    */\n    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0\n     && (pLevel->plan.wsFlags&WHERE_ORDERBY)\n     && (pIdx->nColumn>nEq)\n    ){\n      /* assert( pOrderBy->nExpr==1 ); */\n      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */\n      isMinQuery = 1;\n      nExtraReg = 1;\n    }\n\n    /* Find any inequality constraint terms for the start and end \n    ** of the range. \n    */\n    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){\n      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);\n      nExtraReg = 1;\n    }\n    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){\n      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);\n      nExtraReg = 1;\n    }\n\n    /* Generate code to evaluate all constraint terms using == or IN\n    ** and store the values of those terms in an array of registers\n    ** starting at regBase.\n    */\n    regBase = codeAllEqualityTerms(\n        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff\n    );\n    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);\n    addrNxt = pLevel->addrNxt;\n\n    /* If we are doing a reverse order scan on an ascending index, or\n    ** a forward order scan on a descending index, interchange the \n    ** start and end terms (pRangeStart and pRangeEnd).\n    */\n    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))\n     || (bRev && pIdx->nColumn==nEq)\n    ){\n      SWAP(WhereTerm *, pRangeEnd, pRangeStart);\n    }\n\n    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );\n    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );\n    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );\n    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );\n    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);\n    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);\n    start_constraints = pRangeStart || nEq>0;\n\n    /* Seek the index cursor to the start of the range. */\n    nConstraint = nEq;\n    if( pRangeStart ){\n      Expr *pRight = pRangeStart->pExpr->pRight;\n      sqlite3ExprCode(pParse, pRight, regBase+nEq);\n      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){\n        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);\n      }\n      if( zStartAff ){\n        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){\n          /* Since the comparison is to be performed with no conversions\n          ** applied to the operands, set the affinity to apply to pRight to \n          ** SQLITE_AFF_NONE.  */\n          zStartAff[nEq] = SQLITE_AFF_NONE;\n        }\n        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){\n          zStartAff[nEq] = SQLITE_AFF_NONE;\n        }\n      }  \n      nConstraint++;\n      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n    }else if( isMinQuery ){\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);\n      nConstraint++;\n      startEq = 0;\n      start_constraints = 1;\n    }\n    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);\n    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];\n    assert( op!=0 );\n    testcase( op==OP_Rewind );\n    testcase( op==OP_Last );\n    testcase( op==OP_SeekGt );\n    testcase( op==OP_SeekGe );\n    testcase( op==OP_SeekLe );\n    testcase( op==OP_SeekLt );\n    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);\n\n    /* Load the value for the inequality constraint at the end of the\n    ** range (if any).\n    */\n    nConstraint = nEq;\n    if( pRangeEnd ){\n      Expr *pRight = pRangeEnd->pExpr->pRight;\n      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);\n      sqlite3ExprCode(pParse, pRight, regBase+nEq);\n      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){\n        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);\n      }\n      if( zEndAff ){\n        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){\n          /* Since the comparison is to be performed with no conversions\n          ** applied to the operands, set the affinity to apply to pRight to \n          ** SQLITE_AFF_NONE.  */\n          zEndAff[nEq] = SQLITE_AFF_NONE;\n        }\n        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){\n          zEndAff[nEq] = SQLITE_AFF_NONE;\n        }\n      }  \n      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);\n      nConstraint++;\n      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */\n    }\n    sqlite3DbFree(pParse->db, zStartAff);\n    sqlite3DbFree(pParse->db, zEndAff);\n\n    /* Top of the loop body */\n    pLevel->p2 = sqlite3VdbeCurrentAddr(v);\n\n    /* Check if the index cursor is past the end of the range. */\n    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];\n    testcase( op==OP_Noop );\n    testcase( op==OP_IdxGE );\n    testcase( op==OP_IdxLT );\n    if( op!=OP_Noop ){\n      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);\n      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);\n    }\n\n    /* If there are inequality constraints, check that the value\n    ** of the table column that the inequality contrains is not NULL.\n    ** If it is, jump to the next iteration of the loop.\n    */\n    r1 = sqlite3GetTempReg(pParse);\n    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );\n    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );\n    if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){\n      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);\n      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);\n    }\n    sqlite3ReleaseTempReg(pParse, r1);\n\n    /* Seek the table cursor, if required */\n    disableTerm(pLevel, pRangeStart);\n    disableTerm(pLevel, pRangeEnd);\n    if( !omitTable ){\n      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);\n      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);\n      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);\n      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */\n    }\n\n    /* Record the instruction used to terminate the loop. Disable \n    ** WHERE clause terms made redundant by the index range scan.\n    */\n    if( pLevel->plan.wsFlags & WHERE_UNIQUE ){\n      pLevel->op = OP_Noop;\n    }else if( bRev ){\n      pLevel->op = OP_Prev;\n    }else{\n      pLevel->op = OP_Next;\n    }\n    pLevel->p1 = iIdxCur;\n  }else\n\n#ifndef SQLITE_OMIT_OR_OPTIMIZATION\n  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){\n    /* Case 4:  Two or more separately indexed terms connected by OR\n    **\n    ** Example:\n    **\n    **   CREATE TABLE t1(a,b,c,d);\n    **   CREATE INDEX i1 ON t1(a);\n    **   CREATE INDEX i2 ON t1(b);\n    **   CREATE INDEX i3 ON t1(c);\n    **\n    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)\n    **\n    ** In the example, there are three indexed terms connected by OR.\n    ** The top of the loop looks like this:\n    **\n    **          Null       1                # Zero the rowset in reg 1\n    **\n    ** Then, for each indexed term, the following. The arguments to\n    ** RowSetTest are such that the rowid of the current row is inserted\n    ** into the RowSet. If it is already present, control skips the\n    ** Gosub opcode and jumps straight to the code generated by WhereEnd().\n    **\n    **        sqlite3WhereBegin(<term>)\n    **          RowSetTest                  # Insert rowid into rowset\n    **          Gosub      2 A\n    **        sqlite3WhereEnd()\n    **\n    ** Following the above, code to terminate the loop. Label A, the target\n    ** of the Gosub above, jumps to the instruction right after the Goto.\n    **\n    **          Null       1                # Zero the rowset in reg 1\n    **          Goto       B                # The loop is finished.\n    **\n    **       A: <loop body>                 # Return data, whatever.\n    **\n    **          Return     2                # Jump back to the Gosub\n    **\n    **       B: <after the loop>\n    **\n    */\n    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */\n    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */\n    Index *pCov = 0;             /* Potential covering index (or NULL) */\n    int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */\n\n    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */\n    int regRowset = 0;                        /* Register for RowSet object */\n    int regRowid = 0;                         /* Register holding rowid */\n    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */\n    int iRetInit;                             /* Address of regReturn init */\n    int untestedTerms = 0;             /* Some terms not completely tested */\n    int ii;                            /* Loop counter */\n    Expr *pAndExpr = 0;                /* An \".. AND (...)\" expression */\n   \n    pTerm = pLevel->plan.u.pTerm;\n    assert( pTerm!=0 );\n    assert( pTerm->eOperator==WO_OR );\n    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );\n    pOrWc = &pTerm->u.pOrInfo->wc;\n    pLevel->op = OP_Return;\n    pLevel->p1 = regReturn;\n\n    /* Set up a new SrcList in pOrTab containing the table being scanned\n    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.\n    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().\n    */\n    if( pWInfo->nLevel>1 ){\n      int nNotReady;                 /* The number of notReady tables */\n      struct SrcList_item *origSrc;     /* Original list of tables */\n      nNotReady = pWInfo->nLevel - iLevel - 1;\n      pOrTab = sqlite3StackAllocRaw(pParse->db,\n                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));\n      if( pOrTab==0 ) return notReady;\n      pOrTab->nAlloc = (i16)(nNotReady + 1);\n      pOrTab->nSrc = pOrTab->nAlloc;\n      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));\n      origSrc = pWInfo->pTabList->a;\n      for(k=1; k<=nNotReady; k++){\n        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));\n      }\n    }else{\n      pOrTab = pWInfo->pTabList;\n    }\n\n    /* Initialize the rowset register to contain NULL. An SQL NULL is \n    ** equivalent to an empty rowset.\n    **\n    ** Also initialize regReturn to contain the address of the instruction \n    ** immediately following the OP_Return at the bottom of the loop. This\n    ** is required in a few obscure LEFT JOIN cases where control jumps\n    ** over the top of the loop into the body of it. In this case the \n    ** correct response for the end-of-loop code (the OP_Return) is to \n    ** fall through to the next instruction, just as an OP_Next does if\n    ** called on an uninitialized cursor.\n    */\n    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){\n      regRowset = ++pParse->nMem;\n      regRowid = ++pParse->nMem;\n      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);\n    }\n    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);\n\n    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y\n    ** Then for every term xN, evaluate as the subexpression: xN AND z\n    ** That way, terms in y that are factored into the disjunction will\n    ** be picked up by the recursive calls to sqlite3WhereBegin() below.\n    **\n    ** Actually, each subexpression is converted to \"xN AND w\" where w is\n    ** the \"interesting\" terms of z - terms that did not originate in the\n    ** ON or USING clause of a LEFT JOIN, and terms that are usable as \n    ** indices.\n    */\n    if( pWC->nTerm>1 ){\n      int iTerm;\n      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){\n        Expr *pExpr = pWC->a[iTerm].pExpr;\n        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;\n        if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;\n        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;\n        pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);\n        pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);\n      }\n      if( pAndExpr ){\n        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);\n      }\n    }\n\n    for(ii=0; ii<pOrWc->nTerm; ii++){\n      WhereTerm *pOrTerm = &pOrWc->a[ii];\n      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){\n        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */\n        Expr *pOrExpr = pOrTerm->pExpr;\n        if( pAndExpr ){\n          pAndExpr->pLeft = pOrExpr;\n          pOrExpr = pAndExpr;\n        }\n        /* Loop through table entries that match term pOrTerm. */\n        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,\n                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |\n                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);\n        assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );\n        if( pSubWInfo ){\n          WhereLevel *pLvl;\n          explainOneScan(\n              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0\n          );\n          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){\n            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);\n            int r;\n            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, \n                                         regRowid, 0);\n            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,\n                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);\n          }\n          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);\n\n          /* The pSubWInfo->untestedTerms flag means that this OR term\n          ** contained one or more AND term from a notReady table.  The\n          ** terms from the notReady table could not be tested and will\n          ** need to be tested later.\n          */\n          if( pSubWInfo->untestedTerms ) untestedTerms = 1;\n\n          /* If all of the OR-connected terms are optimized using the same\n          ** index, and the index is opened using the same cursor number\n          ** by each call to sqlite3WhereBegin() made by this loop, it may\n          ** be possible to use that index as a covering index.\n          **\n          ** If the call to sqlite3WhereBegin() above resulted in a scan that\n          ** uses an index, and this is either the first OR-connected term\n          ** processed or the index is the same as that used by all previous\n          ** terms, set pCov to the candidate covering index. Otherwise, set \n          ** pCov to NULL to indicate that no candidate covering index will \n          ** be available.\n          */\n          pLvl = &pSubWInfo->a[0];\n          if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0\n           && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0\n           && (ii==0 || pLvl->plan.u.pIdx==pCov)\n          ){\n            assert( pLvl->iIdxCur==iCovCur );\n            pCov = pLvl->plan.u.pIdx;\n          }else{\n            pCov = 0;\n          }\n\n          /* Finish the loop through table entries that match term pOrTerm. */\n          sqlite3WhereEnd(pSubWInfo);\n        }\n      }\n    }\n    pLevel->u.pCovidx = pCov;\n    if( pCov ) pLevel->iIdxCur = iCovCur;\n    if( pAndExpr ){\n      pAndExpr->pLeft = 0;\n      sqlite3ExprDelete(pParse->db, pAndExpr);\n    }\n    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));\n    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);\n    sqlite3VdbeResolveLabel(v, iLoopBody);\n\n    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);\n    if( !untestedTerms ) disableTerm(pLevel, pTerm);\n  }else\n#endif /* SQLITE_OMIT_OR_OPTIMIZATION */\n\n  {\n    /* Case 5:  There is no usable index.  We must do a complete\n    **          scan of the entire table.\n    */\n    static const u8 aStep[] = { OP_Next, OP_Prev };\n    static const u8 aStart[] = { OP_Rewind, OP_Last };\n    assert( bRev==0 || bRev==1 );\n    assert( omitTable==0 );\n    pLevel->op = aStep[bRev];\n    pLevel->p1 = iCur;\n    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);\n    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;\n  }\n  notReady &= ~getMask(pWC->pMaskSet, iCur);\n\n  /* Insert code to test every subexpression that can be completely\n  ** computed using the current set of tables.\n  **\n  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through\n  ** the use of indices become tests that are evaluated against each row of\n  ** the relevant input tables.\n  */\n  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){\n    Expr *pE;\n    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */\n    testcase( pTerm->wtFlags & TERM_CODED );\n    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n    if( (pTerm->prereqAll & notReady)!=0 ){\n      testcase( pWInfo->untestedTerms==0\n               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );\n      pWInfo->untestedTerms = 1;\n      continue;\n    }\n    pE = pTerm->pExpr;\n    assert( pE!=0 );\n    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){\n      continue;\n    }\n    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);\n    pTerm->wtFlags |= TERM_CODED;\n  }\n\n  /* For a LEFT OUTER JOIN, generate code that will record the fact that\n  ** at least one row of the right table has matched the left table.  \n  */\n  if( pLevel->iLeftJoin ){\n    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);\n    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);\n    VdbeComment((v, \"record LEFT JOIN hit\"));\n    sqlite3ExprCacheClear(pParse);\n    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){\n      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */\n      testcase( pTerm->wtFlags & TERM_CODED );\n      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;\n      if( (pTerm->prereqAll & notReady)!=0 ){\n        assert( pWInfo->untestedTerms );\n        continue;\n      }\n      assert( pTerm->pExpr );\n      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);\n      pTerm->wtFlags |= TERM_CODED;\n    }\n  }\n  sqlite3ReleaseTempReg(pParse, iReleaseReg);\n\n  return notReady;\n}\n\n#if defined(SQLITE_TEST)\n/*\n** The following variable holds a text description of query plan generated\n** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin\n** overwrites the previous.  This information is used for testing and\n** analysis only.\n*/\nSQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */\nstatic int nQPlan = 0;              /* Next free slow in _query_plan[] */\n\n#endif /* SQLITE_TEST */\n\n\n/*\n** Free a WhereInfo structure\n*/\nstatic void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){\n  if( ALWAYS(pWInfo) ){\n    int i;\n    for(i=0; i<pWInfo->nLevel; i++){\n      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;\n      if( pInfo ){\n        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */\n        if( pInfo->needToFreeIdxStr ){\n          sqlite3_free(pInfo->idxStr);\n        }\n        sqlite3DbFree(db, pInfo);\n      }\n      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){\n        Index *pIdx = pWInfo->a[i].plan.u.pIdx;\n        if( pIdx ){\n          sqlite3DbFree(db, pIdx->zColAff);\n          sqlite3DbFree(db, pIdx);\n        }\n      }\n    }\n    whereClauseClear(pWInfo->pWC);\n    sqlite3DbFree(db, pWInfo);\n  }\n}\n\n\n/*\n** Generate the beginning of the loop used for WHERE clause processing.\n** The return value is a pointer to an opaque structure that contains\n** information needed to terminate the loop.  Later, the calling routine\n** should invoke sqlite3WhereEnd() with the return value of this function\n** in order to complete the WHERE clause processing.\n**\n** If an error occurs, this routine returns NULL.\n**\n** The basic idea is to do a nested loop, one loop for each table in\n** the FROM clause of a select.  (INSERT and UPDATE statements are the\n** same as a SELECT with only a single table in the FROM clause.)  For\n** example, if the SQL is this:\n**\n**       SELECT * FROM t1, t2, t3 WHERE ...;\n**\n** Then the code generated is conceptually like the following:\n**\n**      foreach row1 in t1 do       \\    Code generated\n**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()\n**          foreach row3 in t3 do   /\n**            ...\n**          end                     \\    Code generated\n**        end                        |-- by sqlite3WhereEnd()\n**      end                         /\n**\n** Note that the loops might not be nested in the order in which they\n** appear in the FROM clause if a different order is better able to make\n** use of indices.  Note also that when the IN operator appears in\n** the WHERE clause, it might result in additional nested loops for\n** scanning through all values on the right-hand side of the IN.\n**\n** There are Btree cursors associated with each table.  t1 uses cursor\n** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.\n** And so forth.  This routine generates code to open those VDBE cursors\n** and sqlite3WhereEnd() generates the code to close them.\n**\n** The code that sqlite3WhereBegin() generates leaves the cursors named\n** in pTabList pointing at their appropriate entries.  The [...] code\n** can use OP_Column and OP_Rowid opcodes on these cursors to extract\n** data from the various tables of the loop.\n**\n** If the WHERE clause is empty, the foreach loops must each scan their\n** entire tables.  Thus a three-way join is an O(N^3) operation.  But if\n** the tables have indices and there are terms in the WHERE clause that\n** refer to those indices, a complete table scan can be avoided and the\n** code will run much faster.  Most of the work of this routine is checking\n** to see if there are indices that can be used to speed up the loop.\n**\n** Terms of the WHERE clause are also used to limit which rows actually\n** make it to the \"...\" in the middle of the loop.  After each \"foreach\",\n** terms of the WHERE clause that use only terms in that loop and outer\n** loops are evaluated and if false a jump is made around all subsequent\n** inner loops (or around the \"...\" if the test occurs within the inner-\n** most loop)\n**\n** OUTER JOINS\n**\n** An outer join of tables t1 and t2 is conceptally coded as follows:\n**\n**    foreach row1 in t1 do\n**      flag = 0\n**      foreach row2 in t2 do\n**        start:\n**          ...\n**          flag = 1\n**      end\n**      if flag==0 then\n**        move the row2 cursor to a null row\n**        goto start\n**      fi\n**    end\n**\n** ORDER BY CLAUSE PROCESSING\n**\n** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,\n** if there is one.  If there is no ORDER BY clause or if this routine\n** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.\n**\n** If an index can be used so that the natural output order of the table\n** scan is correct for the ORDER BY clause, then that index is used and\n** *ppOrderBy is set to NULL.  This is an optimization that prevents an\n** unnecessary sort of the result set if an index appropriate for the\n** ORDER BY clause already exists.\n**\n** If the where clause loops cannot be arranged to provide the correct\n** output order, then the *ppOrderBy is unchanged.\n*/\nSQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(\n  Parse *pParse,        /* The parser context */\n  SrcList *pTabList,    /* A list of all tables to be scanned */\n  Expr *pWhere,         /* The WHERE clause */\n  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */\n  ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */\n  u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */\n  int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */\n){\n  int i;                     /* Loop counter */\n  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */\n  int nTabList;              /* Number of elements in pTabList */\n  WhereInfo *pWInfo;         /* Will become the return value of this function */\n  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */\n  Bitmask notReady;          /* Cursors that are not yet positioned */\n  WhereMaskSet *pMaskSet;    /* The expression mask set */\n  WhereClause *pWC;               /* Decomposition of the WHERE clause */\n  struct SrcList_item *pTabItem;  /* A single entry from pTabList */\n  WhereLevel *pLevel;             /* A single level in the pWInfo list */\n  int iFrom;                      /* First unused FROM clause element */\n  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */\n  sqlite3 *db;               /* Database connection */\n\n  /* The number of tables in the FROM clause is limited by the number of\n  ** bits in a Bitmask \n  */\n  testcase( pTabList->nSrc==BMS );\n  if( pTabList->nSrc>BMS ){\n    sqlite3ErrorMsg(pParse, \"at most %d tables in a join\", BMS);\n    return 0;\n  }\n\n  /* This function normally generates a nested loop for all tables in \n  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should\n  ** only generate code for the first table in pTabList and assume that\n  ** any cursors associated with subsequent tables are uninitialized.\n  */\n  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;\n\n  /* Allocate and initialize the WhereInfo structure that will become the\n  ** return value. A single allocation is used to store the WhereInfo\n  ** struct, the contents of WhereInfo.a[], the WhereClause structure\n  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte\n  ** field (type Bitmask) it must be aligned on an 8-byte boundary on\n  ** some architectures. Hence the ROUND8() below.\n  */\n  db = pParse->db;\n  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));\n  pWInfo = sqlite3DbMallocZero(db, \n      nByteWInfo + \n      sizeof(WhereClause) +\n      sizeof(WhereMaskSet)\n  );\n  if( db->mallocFailed ){\n    sqlite3DbFree(db, pWInfo);\n    pWInfo = 0;\n    goto whereBeginError;\n  }\n  pWInfo->nLevel = nTabList;\n  pWInfo->pParse = pParse;\n  pWInfo->pTabList = pTabList;\n  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);\n  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];\n  pWInfo->wctrlFlags = wctrlFlags;\n  pWInfo->savedNQueryLoop = pParse->nQueryLoop;\n  pMaskSet = (WhereMaskSet*)&pWC[1];\n\n  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via\n  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */\n  if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;\n\n  /* Split the WHERE clause into separate subexpressions where each\n  ** subexpression is separated by an AND operator.\n  */\n  initMaskSet(pMaskSet);\n  whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);\n  sqlite3ExprCodeConstants(pParse, pWhere);\n  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */\n    \n  /* Special case: a WHERE clause that is constant.  Evaluate the\n  ** expression and either jump over all of the code or fall thru.\n  */\n  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){\n    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);\n    pWhere = 0;\n  }\n\n  /* Assign a bit from the bitmask to every term in the FROM clause.\n  **\n  ** When assigning bitmask values to FROM clause cursors, it must be\n  ** the case that if X is the bitmask for the N-th FROM clause term then\n  ** the bitmask for all FROM clause terms to the left of the N-th term\n  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use\n  ** its Expr.iRightJoinTable value to find the bitmask of the right table\n  ** of the join.  Subtracting one from the right table bitmask gives a\n  ** bitmask for all tables to the left of the join.  Knowing the bitmask\n  ** for all tables to the left of a left join is important.  Ticket #3015.\n  **\n  ** Configure the WhereClause.vmask variable so that bits that correspond\n  ** to virtual table cursors are set. This is used to selectively disable \n  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful \n  ** with virtual tables.\n  **\n  ** Note that bitmasks are created for all pTabList->nSrc tables in\n  ** pTabList, not just the first nTabList tables.  nTabList is normally\n  ** equal to pTabList->nSrc but might be shortened to 1 if the\n  ** WHERE_ONETABLE_ONLY flag is set.\n  */\n  assert( pWC->vmask==0 && pMaskSet->n==0 );\n  for(i=0; i<pTabList->nSrc; i++){\n    createMask(pMaskSet, pTabList->a[i].iCursor);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){\n      pWC->vmask |= ((Bitmask)1 << i);\n    }\n#endif\n  }\n#ifndef NDEBUG\n  {\n    Bitmask toTheLeft = 0;\n    for(i=0; i<pTabList->nSrc; i++){\n      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);\n      assert( (m-1)==toTheLeft );\n      toTheLeft |= m;\n    }\n  }\n#endif\n\n  /* Analyze all of the subexpressions.  Note that exprAnalyze() might\n  ** add new virtual terms onto the end of the WHERE clause.  We do not\n  ** want to analyze these virtual terms, so start analyzing at the end\n  ** and work forward so that the added virtual terms are never processed.\n  */\n  exprAnalyzeAll(pTabList, pWC);\n  if( db->mallocFailed ){\n    goto whereBeginError;\n  }\n\n  /* Check if the DISTINCT qualifier, if there is one, is redundant. \n  ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to\n  ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.\n  */\n  if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){\n    pDistinct = 0;\n    pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;\n  }\n\n  /* Chose the best index to use for each table in the FROM clause.\n  **\n  ** This loop fills in the following fields:\n  **\n  **   pWInfo->a[].pIdx      The index to use for this level of the loop.\n  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx\n  **   pWInfo->a[].nEq       The number of == and IN constraints\n  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded\n  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table\n  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index\n  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term\n  **\n  ** This loop also figures out the nesting order of tables in the FROM\n  ** clause.\n  */\n  notReady = ~(Bitmask)0;\n  andFlags = ~0;\n  WHERETRACE((\"*** Optimizer Start ***\\n\"));\n  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){\n    WhereCost bestPlan;         /* Most efficient plan seen so far */\n    Index *pIdx;                /* Index for FROM table at pTabItem */\n    int j;                      /* For looping over FROM tables */\n    int bestJ = -1;             /* The value of j */\n    Bitmask m;                  /* Bitmask value for j or bestJ */\n    int isOptimal;              /* Iterator for optimal/non-optimal search */\n    int nUnconstrained;         /* Number tables without INDEXED BY */\n    Bitmask notIndexed;         /* Mask of tables that cannot use an index */\n\n    memset(&bestPlan, 0, sizeof(bestPlan));\n    bestPlan.rCost = SQLITE_BIG_DBL;\n    WHERETRACE((\"*** Begin search for loop %d ***\\n\", i));\n\n    /* Loop through the remaining entries in the FROM clause to find the\n    ** next nested loop. The loop tests all FROM clause entries\n    ** either once or twice. \n    **\n    ** The first test is always performed if there are two or more entries\n    ** remaining and never performed if there is only one FROM clause entry\n    ** to choose from.  The first test looks for an \"optimal\" scan.  In\n    ** this context an optimal scan is one that uses the same strategy\n    ** for the given FROM clause entry as would be selected if the entry\n    ** were used as the innermost nested loop.  In other words, a table\n    ** is chosen such that the cost of running that table cannot be reduced\n    ** by waiting for other tables to run first.  This \"optimal\" test works\n    ** by first assuming that the FROM clause is on the inner loop and finding\n    ** its query plan, then checking to see if that query plan uses any\n    ** other FROM clause terms that are notReady.  If no notReady terms are\n    ** used then the \"optimal\" query plan works.\n    **\n    ** Note that the WhereCost.nRow parameter for an optimal scan might\n    ** not be as small as it would be if the table really were the innermost\n    ** join.  The nRow value can be reduced by WHERE clause constraints\n    ** that do not use indices.  But this nRow reduction only happens if the\n    ** table really is the innermost join.  \n    **\n    ** The second loop iteration is only performed if no optimal scan\n    ** strategies were found by the first iteration. This second iteration\n    ** is used to search for the lowest cost scan overall.\n    **\n    ** Previous versions of SQLite performed only the second iteration -\n    ** the next outermost loop was always that with the lowest overall\n    ** cost. However, this meant that SQLite could select the wrong plan\n    ** for scripts such as the following:\n    **   \n    **   CREATE TABLE t1(a, b); \n    **   CREATE TABLE t2(c, d);\n    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;\n    **\n    ** The best strategy is to iterate through table t1 first. However it\n    ** is not possible to determine this with a simple greedy algorithm.\n    ** Since the cost of a linear scan through table t2 is the same \n    ** as the cost of a linear scan through table t1, a simple greedy \n    ** algorithm may choose to use t2 for the outer loop, which is a much\n    ** costlier approach.\n    */\n    nUnconstrained = 0;\n    notIndexed = 0;\n    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){\n      Bitmask mask;             /* Mask of tables not yet ready */\n      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){\n        int doNotReorder;    /* True if this table should not be reordered */\n        WhereCost sCost;     /* Cost information from best[Virtual]Index() */\n        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */\n        ExprList *pDist;     /* DISTINCT clause for index to optimize */\n  \n        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;\n        if( j!=iFrom && doNotReorder ) break;\n        m = getMask(pMaskSet, pTabItem->iCursor);\n        if( (m & notReady)==0 ){\n          if( j==iFrom ) iFrom++;\n          continue;\n        }\n        mask = (isOptimal ? m : notReady);\n        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);\n        pDist = (i==0 ? pDistinct : 0);\n        if( pTabItem->pIndex==0 ) nUnconstrained++;\n  \n        WHERETRACE((\"=== trying table %d with isOptimal=%d ===\\n\",\n                    j, isOptimal));\n        assert( pTabItem->pTab );\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n        if( IsVirtual(pTabItem->pTab) ){\n          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;\n          bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,\n                           &sCost, pp);\n        }else \n#endif\n        {\n          bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,\n              pDist, &sCost);\n        }\n        assert( isOptimal || (sCost.used&notReady)==0 );\n\n        /* If an INDEXED BY clause is present, then the plan must use that\n        ** index if it uses any index at all */\n        assert( pTabItem->pIndex==0 \n                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0\n                  || sCost.plan.u.pIdx==pTabItem->pIndex );\n\n        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){\n          notIndexed |= m;\n        }\n\n        /* Conditions under which this table becomes the best so far:\n        **\n        **   (1) The table must not depend on other tables that have not\n        **       yet run.\n        **\n        **   (2) A full-table-scan plan cannot supercede indexed plan unless\n        **       the full-table-scan is an \"optimal\" plan as defined above.\n        **\n        **   (3) All tables have an INDEXED BY clause or this table lacks an\n        **       INDEXED BY clause or this table uses the specific\n        **       index specified by its INDEXED BY clause.  This rule ensures\n        **       that a best-so-far is always selected even if an impossible\n        **       combination of INDEXED BY clauses are given.  The error\n        **       will be detected and relayed back to the application later.\n        **       The NEVER() comes about because rule (2) above prevents\n        **       An indexable full-table-scan from reaching rule (3).\n        **\n        **   (4) The plan cost must be lower than prior plans or else the\n        **       cost must be the same and the number of rows must be lower.\n        */\n        if( (sCost.used&notReady)==0                       /* (1) */\n            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */\n                || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0\n                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)\n            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */\n                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))\n            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */\n                || (sCost.rCost<=bestPlan.rCost \n                 && sCost.plan.nRow<bestPlan.plan.nRow))\n        ){\n          WHERETRACE((\"=== table %d is best so far\"\n                      \" with cost=%g and nRow=%g\\n\",\n                      j, sCost.rCost, sCost.plan.nRow));\n          bestPlan = sCost;\n          bestJ = j;\n        }\n        if( doNotReorder ) break;\n      }\n    }\n    assert( bestJ>=0 );\n    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );\n    WHERETRACE((\"*** Optimizer selects table %d for loop %d\"\n                \" with cost=%g and nRow=%g\\n\",\n                bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));\n    /* The ALWAYS() that follows was added to hush up clang scan-build */\n    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){\n      *ppOrderBy = 0;\n    }\n    if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){\n      assert( pWInfo->eDistinct==0 );\n      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;\n    }\n    andFlags &= bestPlan.plan.wsFlags;\n    pLevel->plan = bestPlan.plan;\n    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );\n    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );\n    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){\n      if( (wctrlFlags & WHERE_ONETABLE_ONLY) \n       && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0 \n      ){\n        pLevel->iIdxCur = iIdxCur;\n      }else{\n        pLevel->iIdxCur = pParse->nTab++;\n      }\n    }else{\n      pLevel->iIdxCur = -1;\n    }\n    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);\n    pLevel->iFrom = (u8)bestJ;\n    if( bestPlan.plan.nRow>=(double)1 ){\n      pParse->nQueryLoop *= bestPlan.plan.nRow;\n    }\n\n    /* Check that if the table scanned by this loop iteration had an\n    ** INDEXED BY clause attached to it, that the named index is being\n    ** used for the scan. If not, then query compilation has failed.\n    ** Return an error.\n    */\n    pIdx = pTabList->a[bestJ].pIndex;\n    if( pIdx ){\n      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){\n        sqlite3ErrorMsg(pParse, \"cannot use index: %s\", pIdx->zName);\n        goto whereBeginError;\n      }else{\n        /* If an INDEXED BY clause is used, the bestIndex() function is\n        ** guaranteed to find the index specified in the INDEXED BY clause\n        ** if it find an index at all. */\n        assert( bestPlan.plan.u.pIdx==pIdx );\n      }\n    }\n  }\n  WHERETRACE((\"*** Optimizer Finished ***\\n\"));\n  if( pParse->nErr || db->mallocFailed ){\n    goto whereBeginError;\n  }\n\n  /* If the total query only selects a single row, then the ORDER BY\n  ** clause is irrelevant.\n  */\n  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){\n    *ppOrderBy = 0;\n  }\n\n  /* If the caller is an UPDATE or DELETE statement that is requesting\n  ** to use a one-pass algorithm, determine if this is appropriate.\n  ** The one-pass algorithm only works if the WHERE clause constraints\n  ** the statement to update a single row.\n  */\n  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );\n  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){\n    pWInfo->okOnePass = 1;\n    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;\n  }\n\n  /* Open all tables in the pTabList and any indices selected for\n  ** searching those tables.\n  */\n  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */\n  notReady = ~(Bitmask)0;\n  pWInfo->nRowOut = (double)1;\n  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){\n    Table *pTab;     /* Table to open */\n    int iDb;         /* Index of database containing table/index */\n\n    pTabItem = &pTabList->a[pLevel->iFrom];\n    pTab = pTabItem->pTab;\n    pLevel->iTabCur = pTabItem->iCursor;\n    pWInfo->nRowOut *= pLevel->plan.nRow;\n    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);\n    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){\n      /* Do nothing */\n    }else\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){\n      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);\n      int iCur = pTabItem->iCursor;\n      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);\n    }else\n#endif\n    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0\n         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){\n      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;\n      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);\n      testcase( pTab->nCol==BMS-1 );\n      testcase( pTab->nCol==BMS );\n      if( !pWInfo->okOnePass && pTab->nCol<BMS ){\n        Bitmask b = pTabItem->colUsed;\n        int n = 0;\n        for(; b; b=b>>1, n++){}\n        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, \n                            SQLITE_INT_TO_PTR(n), P4_INT32);\n        assert( n<=pTab->nCol );\n      }\n    }else{\n      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);\n    }\n#ifndef SQLITE_OMIT_AUTOMATIC_INDEX\n    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){\n      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);\n    }else\n#endif\n    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){\n      Index *pIx = pLevel->plan.u.pIdx;\n      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);\n      int iIndexCur = pLevel->iIdxCur;\n      assert( pIx->pSchema==pTab->pSchema );\n      assert( iIndexCur>=0 );\n      sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,\n                        (char*)pKey, P4_KEYINFO_HANDOFF);\n      VdbeComment((v, \"%s\", pIx->zName));\n    }\n    sqlite3CodeVerifySchema(pParse, iDb);\n    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);\n  }\n  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);\n  if( db->mallocFailed ) goto whereBeginError;\n\n  /* Generate the code to do the search.  Each iteration of the for\n  ** loop below generates code for a single nested loop of the VM\n  ** program.\n  */\n  notReady = ~(Bitmask)0;\n  for(i=0; i<nTabList; i++){\n    pLevel = &pWInfo->a[i];\n    explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);\n    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);\n    pWInfo->iContinue = pLevel->addrCont;\n  }\n\n#ifdef SQLITE_TEST  /* For testing and debugging use only */\n  /* Record in the query plan information about the current table\n  ** and the index used to access it (if any).  If the table itself\n  ** is not used, its name is just '{}'.  If no index is used\n  ** the index is listed as \"{}\".  If the primary key is used the\n  ** index name is '*'.\n  */\n  for(i=0; i<nTabList; i++){\n    char *z;\n    int n;\n    pLevel = &pWInfo->a[i];\n    pTabItem = &pTabList->a[pLevel->iFrom];\n    z = pTabItem->zAlias;\n    if( z==0 ) z = pTabItem->pTab->zName;\n    n = sqlite3Strlen30(z);\n    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){\n      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){\n        memcpy(&sqlite3_query_plan[nQPlan], \"{}\", 2);\n        nQPlan += 2;\n      }else{\n        memcpy(&sqlite3_query_plan[nQPlan], z, n);\n        nQPlan += n;\n      }\n      sqlite3_query_plan[nQPlan++] = ' ';\n    }\n    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );\n    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );\n    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){\n      memcpy(&sqlite3_query_plan[nQPlan], \"* \", 2);\n      nQPlan += 2;\n    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){\n      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);\n      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){\n        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);\n        nQPlan += n;\n        sqlite3_query_plan[nQPlan++] = ' ';\n      }\n    }else{\n      memcpy(&sqlite3_query_plan[nQPlan], \"{} \", 3);\n      nQPlan += 3;\n    }\n  }\n  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){\n    sqlite3_query_plan[--nQPlan] = 0;\n  }\n  sqlite3_query_plan[nQPlan] = 0;\n  nQPlan = 0;\n#endif /* SQLITE_TEST // Testing and debugging use only */\n\n  /* Record the continuation address in the WhereInfo structure.  Then\n  ** clean up and return.\n  */\n  return pWInfo;\n\n  /* Jump here if malloc fails */\nwhereBeginError:\n  if( pWInfo ){\n    pParse->nQueryLoop = pWInfo->savedNQueryLoop;\n    whereInfoFree(db, pWInfo);\n  }\n  return 0;\n}\n\n/*\n** Generate the end of the WHERE loop.  See comments on \n** sqlite3WhereBegin() for additional information.\n*/\nSQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){\n  Parse *pParse = pWInfo->pParse;\n  Vdbe *v = pParse->pVdbe;\n  int i;\n  WhereLevel *pLevel;\n  SrcList *pTabList = pWInfo->pTabList;\n  sqlite3 *db = pParse->db;\n\n  /* Generate loop termination code.\n  */\n  sqlite3ExprCacheClear(pParse);\n  for(i=pWInfo->nLevel-1; i>=0; i--){\n    pLevel = &pWInfo->a[i];\n    sqlite3VdbeResolveLabel(v, pLevel->addrCont);\n    if( pLevel->op!=OP_Noop ){\n      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);\n      sqlite3VdbeChangeP5(v, pLevel->p5);\n    }\n    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){\n      struct InLoop *pIn;\n      int j;\n      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);\n      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){\n        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);\n        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);\n        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);\n      }\n      sqlite3DbFree(db, pLevel->u.in.aInLoop);\n    }\n    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);\n    if( pLevel->iLeftJoin ){\n      int addr;\n      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);\n      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0\n           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );\n      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){\n        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);\n      }\n      if( pLevel->iIdxCur>=0 ){\n        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);\n      }\n      if( pLevel->op==OP_Return ){\n        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);\n      }else{\n        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);\n      }\n      sqlite3VdbeJumpHere(v, addr);\n    }\n  }\n\n  /* The \"break\" point is here, just past the end of the outer loop.\n  ** Set it.\n  */\n  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);\n\n  /* Close all of the cursors that were opened by sqlite3WhereBegin.\n  */\n  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );\n  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){\n    Index *pIdx = 0;\n    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];\n    Table *pTab = pTabItem->pTab;\n    assert( pTab!=0 );\n    if( (pTab->tabFlags & TF_Ephemeral)==0\n     && pTab->pSelect==0\n     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0\n    ){\n      int ws = pLevel->plan.wsFlags;\n      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){\n        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);\n      }\n      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){\n        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);\n      }\n    }\n\n    /* If this scan uses an index, make code substitutions to read data\n    ** from the index in preference to the table. Sometimes, this means\n    ** the table need never be read from. This is a performance boost,\n    ** as the vdbe level waits until the table is read before actually\n    ** seeking the table cursor to the record corresponding to the current\n    ** position in the index.\n    ** \n    ** Calls to the code generator in between sqlite3WhereBegin and\n    ** sqlite3WhereEnd will have created code that references the table\n    ** directly.  This loop scans all that code looking for opcodes\n    ** that reference the table and converts them into opcodes that\n    ** reference the index.\n    */\n    if( pLevel->plan.wsFlags & WHERE_INDEXED ){\n      pIdx = pLevel->plan.u.pIdx;\n    }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){\n      pIdx = pLevel->u.pCovidx;\n    }\n    if( pIdx && !db->mallocFailed){\n      int k, j, last;\n      VdbeOp *pOp;\n\n      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);\n      last = sqlite3VdbeCurrentAddr(v);\n      for(k=pWInfo->iTop; k<last; k++, pOp++){\n        if( pOp->p1!=pLevel->iTabCur ) continue;\n        if( pOp->opcode==OP_Column ){\n          for(j=0; j<pIdx->nColumn; j++){\n            if( pOp->p2==pIdx->aiColumn[j] ){\n              pOp->p2 = j;\n              pOp->p1 = pLevel->iIdxCur;\n              break;\n            }\n          }\n          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0\n               || j<pIdx->nColumn );\n        }else if( pOp->opcode==OP_Rowid ){\n          pOp->p1 = pLevel->iIdxCur;\n          pOp->opcode = OP_IdxRowid;\n        }\n      }\n    }\n  }\n\n  /* Final cleanup\n  */\n  pParse->nQueryLoop = pWInfo->savedNQueryLoop;\n  whereInfoFree(db, pWInfo);\n  return;\n}\n\n/************** End of where.c ***********************************************/\n/************** Begin file parse.c *******************************************/\n/* Driver template for the LEMON parser generator.\n** The author disclaims copyright to this source code.\n**\n** This version of \"lempar.c\" is modified, slightly, for use by SQLite.\n** The only modifications are the addition of a couple of NEVER()\n** macros to disable tests that are needed in the case of a general\n** LALR(1) grammar but which are always false in the\n** specific grammar used by SQLite.\n*/\n/* First off, code is included that follows the \"include\" declaration\n** in the input grammar file. */\n/* #include <stdio.h> */\n\n\n/*\n** Disable all error recovery processing in the parser push-down\n** automaton.\n*/\n#define YYNOERRORRECOVERY 1\n\n/*\n** Make yytestcase() the same as testcase()\n*/\n#define yytestcase(X) testcase(X)\n\n/*\n** An instance of this structure holds information about the\n** LIMIT clause of a SELECT statement.\n*/\nstruct LimitVal {\n  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */\n  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */\n};\n\n/*\n** An instance of this structure is used to store the LIKE,\n** GLOB, NOT LIKE, and NOT GLOB operators.\n*/\nstruct LikeOp {\n  Token eOperator;  /* \"like\" or \"glob\" or \"regexp\" */\n  int bNot;         /* True if the NOT keyword is present */\n};\n\n/*\n** An instance of the following structure describes the event of a\n** TRIGGER.  \"a\" is the event type, one of TK_UPDATE, TK_INSERT,\n** TK_DELETE, or TK_INSTEAD.  If the event is of the form\n**\n**      UPDATE ON (a,b,c)\n**\n** Then the \"b\" IdList records the list \"a,b,c\".\n*/\nstruct TrigEvent { int a; IdList * b; };\n\n/*\n** An instance of this structure holds the ATTACH key and the key type.\n*/\nstruct AttachKey { int type;  Token key; };\n\n/*\n** One or more VALUES claues\n*/\nstruct ValueList {\n  ExprList *pList;\n  Select *pSelect;\n};\n\n\n  /* This is a utility routine used to set the ExprSpan.zStart and\n  ** ExprSpan.zEnd values of pOut so that the span covers the complete\n  ** range of text beginning with pStart and going to the end of pEnd.\n  */\n  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){\n    pOut->zStart = pStart->z;\n    pOut->zEnd = &pEnd->z[pEnd->n];\n  }\n\n  /* Construct a new Expr object from a single identifier.  Use the\n  ** new Expr to populate pOut.  Set the span of pOut to be the identifier\n  ** that created the expression.\n  */\n  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){\n    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);\n    pOut->zStart = pValue->z;\n    pOut->zEnd = &pValue->z[pValue->n];\n  }\n\n  /* This routine constructs a binary expression node out of two ExprSpan\n  ** objects and uses the result to populate a new ExprSpan object.\n  */\n  static void spanBinaryExpr(\n    ExprSpan *pOut,     /* Write the result here */\n    Parse *pParse,      /* The parsing context.  Errors accumulate here */\n    int op,             /* The binary operation */\n    ExprSpan *pLeft,    /* The left operand */\n    ExprSpan *pRight    /* The right operand */\n  ){\n    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);\n    pOut->zStart = pLeft->zStart;\n    pOut->zEnd = pRight->zEnd;\n  }\n\n  /* Construct an expression node for a unary postfix operator\n  */\n  static void spanUnaryPostfix(\n    ExprSpan *pOut,        /* Write the new expression node here */\n    Parse *pParse,         /* Parsing context to record errors */\n    int op,                /* The operator */\n    ExprSpan *pOperand,    /* The operand */\n    Token *pPostOp         /* The operand token for setting the span */\n  ){\n    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);\n    pOut->zStart = pOperand->zStart;\n    pOut->zEnd = &pPostOp->z[pPostOp->n];\n  }                           \n\n  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a\n  ** unary TK_ISNULL or TK_NOTNULL expression. */\n  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){\n    sqlite3 *db = pParse->db;\n    if( db->mallocFailed==0 && pY->op==TK_NULL ){\n      pA->op = (u8)op;\n      sqlite3ExprDelete(db, pA->pRight);\n      pA->pRight = 0;\n    }\n  }\n\n  /* Construct an expression node for a unary prefix operator\n  */\n  static void spanUnaryPrefix(\n    ExprSpan *pOut,        /* Write the new expression node here */\n    Parse *pParse,         /* Parsing context to record errors */\n    int op,                /* The operator */\n    ExprSpan *pOperand,    /* The operand */\n    Token *pPreOp         /* The operand token for setting the span */\n  ){\n    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);\n    pOut->zStart = pPreOp->z;\n    pOut->zEnd = pOperand->zEnd;\n  }\n/* Next is all token values, in a form suitable for use by makeheaders.\n** This section will be null unless lemon is run with the -m switch.\n*/\n/* \n** These constants (all generated automatically by the parser generator)\n** specify the various kinds of tokens (terminals) that the parser\n** understands. \n**\n** Each symbol here is a terminal symbol in the grammar.\n*/\n/* Make sure the INTERFACE macro is defined.\n*/\n#ifndef INTERFACE\n# define INTERFACE 1\n#endif\n/* The next thing included is series of defines which control\n** various aspects of the generated parser.\n**    YYCODETYPE         is the data type used for storing terminal\n**                       and nonterminal numbers.  \"unsigned char\" is\n**                       used if there are fewer than 250 terminals\n**                       and nonterminals.  \"int\" is used otherwise.\n**    YYNOCODE           is a number of type YYCODETYPE which corresponds\n**                       to no legal terminal or nonterminal number.  This\n**                       number is used to fill in empty slots of the hash \n**                       table.\n**    YYFALLBACK         If defined, this indicates that one or more tokens\n**                       have fall-back values which should be used if the\n**                       original value of the token will not parse.\n**    YYACTIONTYPE       is the data type used for storing terminal\n**                       and nonterminal numbers.  \"unsigned char\" is\n**                       used if there are fewer than 250 rules and\n**                       states combined.  \"int\" is used otherwise.\n**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given \n**                       directly to the parser from the tokenizer.\n**    YYMINORTYPE        is the data type used for all minor tokens.\n**                       This is typically a union of many types, one of\n**                       which is sqlite3ParserTOKENTYPE.  The entry in the union\n**                       for base tokens is called \"yy0\".\n**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If\n**                       zero the stack is dynamically sized using realloc()\n**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument\n**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument\n**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser\n**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser\n**    YYNSTATE           the combined number of states.\n**    YYNRULE            the number of rules in the grammar\n**    YYERRORSYMBOL      is the code number of the error symbol.  If not\n**                       defined, then do no error processing.\n*/\n#define YYCODETYPE unsigned char\n#define YYNOCODE 251\n#define YYACTIONTYPE unsigned short int\n#define YYWILDCARD 67\n#define sqlite3ParserTOKENTYPE Token\ntypedef union {\n  int yyinit;\n  sqlite3ParserTOKENTYPE yy0;\n  struct LimitVal yy64;\n  Expr* yy122;\n  Select* yy159;\n  IdList* yy180;\n  struct {int value; int mask;} yy207;\n  u8 yy258;\n  struct LikeOp yy318;\n  TriggerStep* yy327;\n  ExprSpan yy342;\n  SrcList* yy347;\n  int yy392;\n  struct TrigEvent yy410;\n  ExprList* yy442;\n  struct ValueList yy487;\n} YYMINORTYPE;\n#ifndef YYSTACKDEPTH\n#define YYSTACKDEPTH 100\n#endif\n#define sqlite3ParserARG_SDECL Parse *pParse;\n#define sqlite3ParserARG_PDECL ,Parse *pParse\n#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse\n#define sqlite3ParserARG_STORE yypParser->pParse = pParse\n#define YYNSTATE 627\n#define YYNRULE 327\n#define YYFALLBACK 1\n#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)\n#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)\n#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)\n\n/* The yyzerominor constant is used to initialize instances of\n** YYMINORTYPE objects to zero. */\nstatic const YYMINORTYPE yyzerominor = { 0 };\n\n/* Define the yytestcase() macro to be a no-op if is not already defined\n** otherwise.\n**\n** Applications can choose to define yytestcase() in the %include section\n** to a macro that can assist in verifying code coverage.  For production\n** code the yytestcase() macro should be turned off.  But it is useful\n** for testing.\n*/\n#ifndef yytestcase\n# define yytestcase(X)\n#endif\n\n\n/* Next are the tables used to determine what action to take based on the\n** current state and lookahead token.  These tables are used to implement\n** functions that take a state number and lookahead value and return an\n** action integer.  \n**\n** Suppose the action integer is N.  Then the action is determined as\n** follows\n**\n**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead\n**                                      token onto the stack and goto state N.\n**\n**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.\n**\n**   N == YYNSTATE+YYNRULE              A syntax error has occurred.\n**\n**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.\n**\n**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused\n**                                      slots in the yy_action[] table.\n**\n** The action table is constructed as a single large table named yy_action[].\n** Given state S and lookahead X, the action is computed as\n**\n**      yy_action[ yy_shift_ofst[S] + X ]\n**\n** If the index value yy_shift_ofst[S]+X is out of range or if the value\n** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]\n** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table\n** and that yy_default[S] should be used instead.  \n**\n** The formula above is for computing the action when the lookahead is\n** a terminal symbol.  If the lookahead is a non-terminal (as occurs after\n** a reduce action) then the yy_reduce_ofst[] array is used in place of\n** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of\n** YY_SHIFT_USE_DFLT.\n**\n** The following are the tables generated in this section:\n**\n**  yy_action[]        A single table containing all actions.\n**  yy_lookahead[]     A table containing the lookahead for each entry in\n**                     yy_action.  Used to detect hash collisions.\n**  yy_shift_ofst[]    For each state, the offset into yy_action for\n**                     shifting terminals.\n**  yy_reduce_ofst[]   For each state, the offset into yy_action for\n**                     shifting non-terminals after a reduce.\n**  yy_default[]       Default action for each state.\n*/\n#define YY_ACTTAB_COUNT (1564)\nstatic const YYACTIONTYPE yy_action[] = {\n /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,\n /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,\n /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,\n /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,\n /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,\n /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,\n /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,\n /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,\n /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,\n /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,\n /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,\n /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,\n /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,\n /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,\n /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,\n /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,\n /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,\n /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,\n /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,\n /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,\n /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,\n /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,\n /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,\n /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,\n /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,\n /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,\n /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,\n /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,\n /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,\n /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,\n /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,\n /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,\n /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,\n /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,\n /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,\n /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,\n /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,\n /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,\n /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,\n /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,\n /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,\n /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,\n /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,\n /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,\n /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,\n /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,\n /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,\n /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,\n /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,\n /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,\n /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,\n /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,\n /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,\n /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,\n /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,\n /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,\n /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,\n /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,\n /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,\n /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,\n /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,\n /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,\n /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,\n /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,\n /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,\n /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,\n /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,\n /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,\n /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,\n /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,\n /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,\n /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,\n /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,\n /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,\n /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,\n /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,\n /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,\n /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,\n /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,\n /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,\n /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,\n /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,\n /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,\n /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,\n /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,\n /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,\n /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,\n /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,\n /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,\n /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,\n /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,\n /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,\n /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,\n /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,\n /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,\n /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,\n /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,\n /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,\n /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,\n /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,\n /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,\n /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,\n /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,\n /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,\n /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,\n /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,\n /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,\n /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,\n /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,\n /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,\n /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,\n /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,\n /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,\n /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,\n /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,\n /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,\n /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,\n /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,\n /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,\n /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,\n /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,\n /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,\n /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,\n /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,\n /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,\n /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,\n /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,\n /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,\n /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,\n /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,\n /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,\n /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,\n /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,\n /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,\n /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,\n /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,\n /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,\n /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,\n /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,\n /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,\n /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,\n /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,\n /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,\n /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,\n /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,\n /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,\n /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,\n /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,\n /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,\n /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,\n /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,\n /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,\n /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,\n /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,\n /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,\n /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,\n /*  1560 */   295,  498,  956,  488,\n};\nstatic const YYCODETYPE yy_lookahead[] = {\n /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,\n /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,\n /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,\n /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,\n /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,\n /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,\n /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,\n /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,\n /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,\n /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,\n /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,\n /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,\n /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,\n /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,\n /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,\n /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,\n /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,\n /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,\n /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,\n /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,\n /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,\n /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,\n /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,\n /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,\n /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,\n /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,\n /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,\n /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,\n /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,\n /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,\n /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,\n /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,\n /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,\n /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,\n /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,\n /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,\n /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,\n /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,\n /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,\n /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,\n /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,\n /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,\n /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,\n /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,\n /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,\n /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,\n /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,\n /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,\n /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,\n /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,\n /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,\n /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,\n /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,\n /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,\n /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,\n /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,\n /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,\n /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,\n /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,\n /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,\n /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,\n /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,\n /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,\n /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,\n /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,\n /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,\n /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,\n /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,\n /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,\n /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,\n /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,\n /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,\n /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,\n /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,\n /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,\n /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,\n /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,\n /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,\n /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,\n /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,\n /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,\n /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,\n /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,\n /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,\n /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,\n /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,\n /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,\n /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,\n /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,\n /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,\n /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,\n /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,\n /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,\n /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,\n /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,\n /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,\n /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,\n /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,\n /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,\n /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,\n /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,\n /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,\n /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,\n /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,\n /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,\n /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,\n /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,\n /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,\n /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,\n /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,\n /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,\n /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,\n /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,\n /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,\n /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,\n /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,\n /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,\n /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,\n /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,\n /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,\n /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,\n /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,\n /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,\n /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,\n /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,\n /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,\n /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,\n /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,\n /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,\n /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,\n /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,\n /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,\n /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,\n /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,\n /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,\n /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,\n /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,\n /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,\n /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,\n /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,\n /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,\n /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,\n /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,\n /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,\n /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,\n /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,\n /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,\n /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,\n /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,\n /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,\n /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,\n /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,\n /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,\n /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,\n /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,\n /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,\n /*  1560 */   195,  182,  250,  186,\n};\n#define YY_SHIFT_USE_DFLT (-70)\n#define YY_SHIFT_COUNT (416)\n#define YY_SHIFT_MIN   (-69)\n#define YY_SHIFT_MAX   (1487)\nstatic const short yy_shift_ofst[] = {\n /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,\n /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,\n /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,\n /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,\n /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,\n /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,\n /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,\n /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,\n /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,\n /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,\n /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,\n /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,\n /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,\n /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,\n /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,\n /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,\n /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,\n /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,\n /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,\n /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,\n /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,\n /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,\n /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,\n /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,\n /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,\n /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,\n /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,\n /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,\n /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,\n /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,\n /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,\n /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,\n /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,\n /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,\n /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,\n /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,\n /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,\n /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,\n /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,\n /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,\n /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,\n /*   410 */    92,   75,   45,  114,   25,   11,    5,\n};\n#define YY_REDUCE_USE_DFLT (-169)\n#define YY_REDUCE_COUNT (308)\n#define YY_REDUCE_MIN   (-168)\n#define YY_REDUCE_MAX   (1391)\nstatic const short yy_reduce_ofst[] = {\n /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,\n /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,\n /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,\n /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,\n /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,\n /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,\n /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,\n /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,\n /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,\n /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,\n /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,\n /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,\n /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,\n /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,\n /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,\n /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,\n /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,\n /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,\n /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,\n /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,\n /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,\n /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,\n /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,\n /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,\n /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,\n /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,\n /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,\n /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,\n /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,\n /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,\n /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,\n};\nstatic const YYACTIONTYPE yy_default[] = {\n /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,\n /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,\n /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,\n /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,\n /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,\n /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,\n /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,\n /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,\n /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,\n /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,\n /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,\n /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,\n /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,\n /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,\n /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,\n /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,\n /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,\n /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,\n /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,\n /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,\n /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,\n /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,\n /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,\n /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,\n /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,\n /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,\n /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,\n /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,\n /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,\n /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,\n /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,\n /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,\n /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,\n /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,\n /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,\n /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,\n /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,\n /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,\n /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,\n /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,\n /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,\n /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,\n /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,\n /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,\n /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,\n /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,\n /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,\n /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,\n /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,\n /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,\n /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,\n /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,\n /*   620 */   665,  639,  636,  635,  631,  630,  628,\n};\n\n/* The next table maps tokens into fallback tokens.  If a construct\n** like the following:\n** \n**      %fallback ID X Y Z.\n**\n** appears in the grammar, then ID becomes a fallback token for X, Y,\n** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser\n** but it does not parse, the type of the token is changed to ID and\n** the parse is retried before an error is thrown.\n*/\n#ifdef YYFALLBACK\nstatic const YYCODETYPE yyFallback[] = {\n    0,  /*          $ => nothing */\n    0,  /*       SEMI => nothing */\n   26,  /*    EXPLAIN => ID */\n   26,  /*      QUERY => ID */\n   26,  /*       PLAN => ID */\n   26,  /*      BEGIN => ID */\n    0,  /* TRANSACTION => nothing */\n   26,  /*   DEFERRED => ID */\n   26,  /*  IMMEDIATE => ID */\n   26,  /*  EXCLUSIVE => ID */\n    0,  /*     COMMIT => nothing */\n   26,  /*        END => ID */\n   26,  /*   ROLLBACK => ID */\n   26,  /*  SAVEPOINT => ID */\n   26,  /*    RELEASE => ID */\n    0,  /*         TO => nothing */\n    0,  /*      TABLE => nothing */\n    0,  /*     CREATE => nothing */\n   26,  /*         IF => ID */\n    0,  /*        NOT => nothing */\n    0,  /*     EXISTS => nothing */\n   26,  /*       TEMP => ID */\n    0,  /*         LP => nothing */\n    0,  /*         RP => nothing */\n    0,  /*         AS => nothing */\n    0,  /*      COMMA => nothing */\n    0,  /*         ID => nothing */\n    0,  /*    INDEXED => nothing */\n   26,  /*      ABORT => ID */\n   26,  /*     ACTION => ID */\n   26,  /*      AFTER => ID */\n   26,  /*    ANALYZE => ID */\n   26,  /*        ASC => ID */\n   26,  /*     ATTACH => ID */\n   26,  /*     BEFORE => ID */\n   26,  /*         BY => ID */\n   26,  /*    CASCADE => ID */\n   26,  /*       CAST => ID */\n   26,  /*   COLUMNKW => ID */\n   26,  /*   CONFLICT => ID */\n   26,  /*   DATABASE => ID */\n   26,  /*       DESC => ID */\n   26,  /*     DETACH => ID */\n   26,  /*       EACH => ID */\n   26,  /*       FAIL => ID */\n   26,  /*        FOR => ID */\n   26,  /*     IGNORE => ID */\n   26,  /*  INITIALLY => ID */\n   26,  /*    INSTEAD => ID */\n   26,  /*    LIKE_KW => ID */\n   26,  /*      MATCH => ID */\n   26,  /*         NO => ID */\n   26,  /*        KEY => ID */\n   26,  /*         OF => ID */\n   26,  /*     OFFSET => ID */\n   26,  /*     PRAGMA => ID */\n   26,  /*      RAISE => ID */\n   26,  /*    REPLACE => ID */\n   26,  /*   RESTRICT => ID */\n   26,  /*        ROW => ID */\n   26,  /*    TRIGGER => ID */\n   26,  /*     VACUUM => ID */\n   26,  /*       VIEW => ID */\n   26,  /*    VIRTUAL => ID */\n   26,  /*    REINDEX => ID */\n   26,  /*     RENAME => ID */\n   26,  /*   CTIME_KW => ID */\n};\n#endif /* YYFALLBACK */\n\n/* The following structure represents a single element of the\n** parser's stack.  Information stored includes:\n**\n**   +  The state number for the parser at this level of the stack.\n**\n**   +  The value of the token stored at this level of the stack.\n**      (In other words, the \"major\" token.)\n**\n**   +  The semantic value stored at this level of the stack.  This is\n**      the information used by the action routines in the grammar.\n**      It is sometimes called the \"minor\" token.\n*/\nstruct yyStackEntry {\n  YYACTIONTYPE stateno;  /* The state-number */\n  YYCODETYPE major;      /* The major token value.  This is the code\n                         ** number for the token at this stack level */\n  YYMINORTYPE minor;     /* The user-supplied minor token value.  This\n                         ** is the value of the token  */\n};\ntypedef struct yyStackEntry yyStackEntry;\n\n/* The state of the parser is completely contained in an instance of\n** the following structure */\nstruct yyParser {\n  int yyidx;                    /* Index of top element in stack */\n#ifdef YYTRACKMAXSTACKDEPTH\n  int yyidxMax;                 /* Maximum value of yyidx */\n#endif\n  int yyerrcnt;                 /* Shifts left before out of the error */\n  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */\n#if YYSTACKDEPTH<=0\n  int yystksz;                  /* Current side of the stack */\n  yyStackEntry *yystack;        /* The parser's stack */\n#else\n  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */\n#endif\n};\ntypedef struct yyParser yyParser;\n\n#ifndef NDEBUG\n/* #include <stdio.h> */\nstatic FILE *yyTraceFILE = 0;\nstatic char *yyTracePrompt = 0;\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/* \n** Turn parser tracing on by giving a stream to which to write the trace\n** and a prompt to preface each trace message.  Tracing is turned off\n** by making either argument NULL \n**\n** Inputs:\n** <ul>\n** <li> A FILE* to which trace output should be written.\n**      If NULL, then tracing is turned off.\n** <li> A prefix string written at the beginning of every\n**      line of trace output.  If NULL, then tracing is\n**      turned off.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nSQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){\n  yyTraceFILE = TraceFILE;\n  yyTracePrompt = zTracePrompt;\n  if( yyTraceFILE==0 ) yyTracePrompt = 0;\n  else if( yyTracePrompt==0 ) yyTraceFILE = 0;\n}\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/* For tracing shifts, the names of all terminals and nonterminals\n** are required.  The following table supplies these names */\nstatic const char *const yyTokenName[] = { \n  \"$\",             \"SEMI\",          \"EXPLAIN\",       \"QUERY\",       \n  \"PLAN\",          \"BEGIN\",         \"TRANSACTION\",   \"DEFERRED\",    \n  \"IMMEDIATE\",     \"EXCLUSIVE\",     \"COMMIT\",        \"END\",         \n  \"ROLLBACK\",      \"SAVEPOINT\",     \"RELEASE\",       \"TO\",          \n  \"TABLE\",         \"CREATE\",        \"IF\",            \"NOT\",         \n  \"EXISTS\",        \"TEMP\",          \"LP\",            \"RP\",          \n  \"AS\",            \"COMMA\",         \"ID\",            \"INDEXED\",     \n  \"ABORT\",         \"ACTION\",        \"AFTER\",         \"ANALYZE\",     \n  \"ASC\",           \"ATTACH\",        \"BEFORE\",        \"BY\",          \n  \"CASCADE\",       \"CAST\",          \"COLUMNKW\",      \"CONFLICT\",    \n  \"DATABASE\",      \"DESC\",          \"DETACH\",        \"EACH\",        \n  \"FAIL\",          \"FOR\",           \"IGNORE\",        \"INITIALLY\",   \n  \"INSTEAD\",       \"LIKE_KW\",       \"MATCH\",         \"NO\",          \n  \"KEY\",           \"OF\",            \"OFFSET\",        \"PRAGMA\",      \n  \"RAISE\",         \"REPLACE\",       \"RESTRICT\",      \"ROW\",         \n  \"TRIGGER\",       \"VACUUM\",        \"VIEW\",          \"VIRTUAL\",     \n  \"REINDEX\",       \"RENAME\",        \"CTIME_KW\",      \"ANY\",         \n  \"OR\",            \"AND\",           \"IS\",            \"BETWEEN\",     \n  \"IN\",            \"ISNULL\",        \"NOTNULL\",       \"NE\",          \n  \"EQ\",            \"GT\",            \"LE\",            \"LT\",          \n  \"GE\",            \"ESCAPE\",        \"BITAND\",        \"BITOR\",       \n  \"LSHIFT\",        \"RSHIFT\",        \"PLUS\",          \"MINUS\",       \n  \"STAR\",          \"SLASH\",         \"REM\",           \"CONCAT\",      \n  \"COLLATE\",       \"BITNOT\",        \"STRING\",        \"JOIN_KW\",     \n  \"CONSTRAINT\",    \"DEFAULT\",       \"NULL\",          \"PRIMARY\",     \n  \"UNIQUE\",        \"CHECK\",         \"REFERENCES\",    \"AUTOINCR\",    \n  \"ON\",            \"INSERT\",        \"DELETE\",        \"UPDATE\",      \n  \"SET\",           \"DEFERRABLE\",    \"FOREIGN\",       \"DROP\",        \n  \"UNION\",         \"ALL\",           \"EXCEPT\",        \"INTERSECT\",   \n  \"SELECT\",        \"DISTINCT\",      \"DOT\",           \"FROM\",        \n  \"JOIN\",          \"USING\",         \"ORDER\",         \"GROUP\",       \n  \"HAVING\",        \"LIMIT\",         \"WHERE\",         \"INTO\",        \n  \"VALUES\",        \"INTEGER\",       \"FLOAT\",         \"BLOB\",        \n  \"REGISTER\",      \"VARIABLE\",      \"CASE\",          \"WHEN\",        \n  \"THEN\",          \"ELSE\",          \"INDEX\",         \"ALTER\",       \n  \"ADD\",           \"error\",         \"input\",         \"cmdlist\",     \n  \"ecmd\",          \"explain\",       \"cmdx\",          \"cmd\",         \n  \"transtype\",     \"trans_opt\",     \"nm\",            \"savepoint_opt\",\n  \"create_table\",  \"create_table_args\",  \"createkw\",      \"temp\",        \n  \"ifnotexists\",   \"dbnm\",          \"columnlist\",    \"conslist_opt\",\n  \"select\",        \"column\",        \"columnid\",      \"type\",        \n  \"carglist\",      \"id\",            \"ids\",           \"typetoken\",   \n  \"typename\",      \"signed\",        \"plus_num\",      \"minus_num\",   \n  \"ccons\",         \"term\",          \"expr\",          \"onconf\",      \n  \"sortorder\",     \"autoinc\",       \"idxlist_opt\",   \"refargs\",     \n  \"defer_subclause\",  \"refarg\",        \"refact\",        \"init_deferred_pred_opt\",\n  \"conslist\",      \"tconscomma\",    \"tcons\",         \"idxlist\",     \n  \"defer_subclause_opt\",  \"orconf\",        \"resolvetype\",   \"raisetype\",   \n  \"ifexists\",      \"fullname\",      \"oneselect\",     \"multiselect_op\",\n  \"distinct\",      \"selcollist\",    \"from\",          \"where_opt\",   \n  \"groupby_opt\",   \"having_opt\",    \"orderby_opt\",   \"limit_opt\",   \n  \"sclp\",          \"as\",            \"seltablist\",    \"stl_prefix\",  \n  \"joinop\",        \"indexed_opt\",   \"on_opt\",        \"using_opt\",   \n  \"joinop2\",       \"inscollist\",    \"sortlist\",      \"nexprlist\",   \n  \"setlist\",       \"insert_cmd\",    \"inscollist_opt\",  \"valuelist\",   \n  \"exprlist\",      \"likeop\",        \"between_op\",    \"in_op\",       \n  \"case_operand\",  \"case_exprlist\",  \"case_else\",     \"uniqueflag\",  \n  \"collate\",       \"nmnum\",         \"number\",        \"trigger_decl\",\n  \"trigger_cmd_list\",  \"trigger_time\",  \"trigger_event\",  \"foreach_clause\",\n  \"when_clause\",   \"trigger_cmd\",   \"trnm\",          \"tridxby\",     \n  \"database_kw_opt\",  \"key_opt\",       \"add_column_fullname\",  \"kwcolumn_opt\",\n  \"create_vtab\",   \"vtabarglist\",   \"vtabarg\",       \"vtabargtoken\",\n  \"lp\",            \"anylist\",     \n};\n#endif /* NDEBUG */\n\n#ifndef NDEBUG\n/* For tracing reduce actions, the names of all rules are required.\n*/\nstatic const char *const yyRuleName[] = {\n /*   0 */ \"input ::= cmdlist\",\n /*   1 */ \"cmdlist ::= cmdlist ecmd\",\n /*   2 */ \"cmdlist ::= ecmd\",\n /*   3 */ \"ecmd ::= SEMI\",\n /*   4 */ \"ecmd ::= explain cmdx SEMI\",\n /*   5 */ \"explain ::=\",\n /*   6 */ \"explain ::= EXPLAIN\",\n /*   7 */ \"explain ::= EXPLAIN QUERY PLAN\",\n /*   8 */ \"cmdx ::= cmd\",\n /*   9 */ \"cmd ::= BEGIN transtype trans_opt\",\n /*  10 */ \"trans_opt ::=\",\n /*  11 */ \"trans_opt ::= TRANSACTION\",\n /*  12 */ \"trans_opt ::= TRANSACTION nm\",\n /*  13 */ \"transtype ::=\",\n /*  14 */ \"transtype ::= DEFERRED\",\n /*  15 */ \"transtype ::= IMMEDIATE\",\n /*  16 */ \"transtype ::= EXCLUSIVE\",\n /*  17 */ \"cmd ::= COMMIT trans_opt\",\n /*  18 */ \"cmd ::= END trans_opt\",\n /*  19 */ \"cmd ::= ROLLBACK trans_opt\",\n /*  20 */ \"savepoint_opt ::= SAVEPOINT\",\n /*  21 */ \"savepoint_opt ::=\",\n /*  22 */ \"cmd ::= SAVEPOINT nm\",\n /*  23 */ \"cmd ::= RELEASE savepoint_opt nm\",\n /*  24 */ \"cmd ::= ROLLBACK trans_opt TO savepoint_opt nm\",\n /*  25 */ \"cmd ::= create_table create_table_args\",\n /*  26 */ \"create_table ::= createkw temp TABLE ifnotexists nm dbnm\",\n /*  27 */ \"createkw ::= CREATE\",\n /*  28 */ \"ifnotexists ::=\",\n /*  29 */ \"ifnotexists ::= IF NOT EXISTS\",\n /*  30 */ \"temp ::= TEMP\",\n /*  31 */ \"temp ::=\",\n /*  32 */ \"create_table_args ::= LP columnlist conslist_opt RP\",\n /*  33 */ \"create_table_args ::= AS select\",\n /*  34 */ \"columnlist ::= columnlist COMMA column\",\n /*  35 */ \"columnlist ::= column\",\n /*  36 */ \"column ::= columnid type carglist\",\n /*  37 */ \"columnid ::= nm\",\n /*  38 */ \"id ::= ID\",\n /*  39 */ \"id ::= INDEXED\",\n /*  40 */ \"ids ::= ID|STRING\",\n /*  41 */ \"nm ::= id\",\n /*  42 */ \"nm ::= STRING\",\n /*  43 */ \"nm ::= JOIN_KW\",\n /*  44 */ \"type ::=\",\n /*  45 */ \"type ::= typetoken\",\n /*  46 */ \"typetoken ::= typename\",\n /*  47 */ \"typetoken ::= typename LP signed RP\",\n /*  48 */ \"typetoken ::= typename LP signed COMMA signed RP\",\n /*  49 */ \"typename ::= ids\",\n /*  50 */ \"typename ::= typename ids\",\n /*  51 */ \"signed ::= plus_num\",\n /*  52 */ \"signed ::= minus_num\",\n /*  53 */ \"carglist ::= carglist ccons\",\n /*  54 */ \"carglist ::=\",\n /*  55 */ \"ccons ::= CONSTRAINT nm\",\n /*  56 */ \"ccons ::= DEFAULT term\",\n /*  57 */ \"ccons ::= DEFAULT LP expr RP\",\n /*  58 */ \"ccons ::= DEFAULT PLUS term\",\n /*  59 */ \"ccons ::= DEFAULT MINUS term\",\n /*  60 */ \"ccons ::= DEFAULT id\",\n /*  61 */ \"ccons ::= NULL onconf\",\n /*  62 */ \"ccons ::= NOT NULL onconf\",\n /*  63 */ \"ccons ::= PRIMARY KEY sortorder onconf autoinc\",\n /*  64 */ \"ccons ::= UNIQUE onconf\",\n /*  65 */ \"ccons ::= CHECK LP expr RP\",\n /*  66 */ \"ccons ::= REFERENCES nm idxlist_opt refargs\",\n /*  67 */ \"ccons ::= defer_subclause\",\n /*  68 */ \"ccons ::= COLLATE ids\",\n /*  69 */ \"autoinc ::=\",\n /*  70 */ \"autoinc ::= AUTOINCR\",\n /*  71 */ \"refargs ::=\",\n /*  72 */ \"refargs ::= refargs refarg\",\n /*  73 */ \"refarg ::= MATCH nm\",\n /*  74 */ \"refarg ::= ON INSERT refact\",\n /*  75 */ \"refarg ::= ON DELETE refact\",\n /*  76 */ \"refarg ::= ON UPDATE refact\",\n /*  77 */ \"refact ::= SET NULL\",\n /*  78 */ \"refact ::= SET DEFAULT\",\n /*  79 */ \"refact ::= CASCADE\",\n /*  80 */ \"refact ::= RESTRICT\",\n /*  81 */ \"refact ::= NO ACTION\",\n /*  82 */ \"defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt\",\n /*  83 */ \"defer_subclause ::= DEFERRABLE init_deferred_pred_opt\",\n /*  84 */ \"init_deferred_pred_opt ::=\",\n /*  85 */ \"init_deferred_pred_opt ::= INITIALLY DEFERRED\",\n /*  86 */ \"init_deferred_pred_opt ::= INITIALLY IMMEDIATE\",\n /*  87 */ \"conslist_opt ::=\",\n /*  88 */ \"conslist_opt ::= COMMA conslist\",\n /*  89 */ \"conslist ::= conslist tconscomma tcons\",\n /*  90 */ \"conslist ::= tcons\",\n /*  91 */ \"tconscomma ::= COMMA\",\n /*  92 */ \"tconscomma ::=\",\n /*  93 */ \"tcons ::= CONSTRAINT nm\",\n /*  94 */ \"tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf\",\n /*  95 */ \"tcons ::= UNIQUE LP idxlist RP onconf\",\n /*  96 */ \"tcons ::= CHECK LP expr RP onconf\",\n /*  97 */ \"tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt\",\n /*  98 */ \"defer_subclause_opt ::=\",\n /*  99 */ \"defer_subclause_opt ::= defer_subclause\",\n /* 100 */ \"onconf ::=\",\n /* 101 */ \"onconf ::= ON CONFLICT resolvetype\",\n /* 102 */ \"orconf ::=\",\n /* 103 */ \"orconf ::= OR resolvetype\",\n /* 104 */ \"resolvetype ::= raisetype\",\n /* 105 */ \"resolvetype ::= IGNORE\",\n /* 106 */ \"resolvetype ::= REPLACE\",\n /* 107 */ \"cmd ::= DROP TABLE ifexists fullname\",\n /* 108 */ \"ifexists ::= IF EXISTS\",\n /* 109 */ \"ifexists ::=\",\n /* 110 */ \"cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select\",\n /* 111 */ \"cmd ::= DROP VIEW ifexists fullname\",\n /* 112 */ \"cmd ::= select\",\n /* 113 */ \"select ::= oneselect\",\n /* 114 */ \"select ::= select multiselect_op oneselect\",\n /* 115 */ \"multiselect_op ::= UNION\",\n /* 116 */ \"multiselect_op ::= UNION ALL\",\n /* 117 */ \"multiselect_op ::= EXCEPT|INTERSECT\",\n /* 118 */ \"oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt\",\n /* 119 */ \"distinct ::= DISTINCT\",\n /* 120 */ \"distinct ::= ALL\",\n /* 121 */ \"distinct ::=\",\n /* 122 */ \"sclp ::= selcollist COMMA\",\n /* 123 */ \"sclp ::=\",\n /* 124 */ \"selcollist ::= sclp expr as\",\n /* 125 */ \"selcollist ::= sclp STAR\",\n /* 126 */ \"selcollist ::= sclp nm DOT STAR\",\n /* 127 */ \"as ::= AS nm\",\n /* 128 */ \"as ::= ids\",\n /* 129 */ \"as ::=\",\n /* 130 */ \"from ::=\",\n /* 131 */ \"from ::= FROM seltablist\",\n /* 132 */ \"stl_prefix ::= seltablist joinop\",\n /* 133 */ \"stl_prefix ::=\",\n /* 134 */ \"seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt\",\n /* 135 */ \"seltablist ::= stl_prefix LP select RP as on_opt using_opt\",\n /* 136 */ \"seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt\",\n /* 137 */ \"dbnm ::=\",\n /* 138 */ \"dbnm ::= DOT nm\",\n /* 139 */ \"fullname ::= nm dbnm\",\n /* 140 */ \"joinop ::= COMMA|JOIN\",\n /* 141 */ \"joinop ::= JOIN_KW JOIN\",\n /* 142 */ \"joinop ::= JOIN_KW nm JOIN\",\n /* 143 */ \"joinop ::= JOIN_KW nm nm JOIN\",\n /* 144 */ \"on_opt ::= ON expr\",\n /* 145 */ \"on_opt ::=\",\n /* 146 */ \"indexed_opt ::=\",\n /* 147 */ \"indexed_opt ::= INDEXED BY nm\",\n /* 148 */ \"indexed_opt ::= NOT INDEXED\",\n /* 149 */ \"using_opt ::= USING LP inscollist RP\",\n /* 150 */ \"using_opt ::=\",\n /* 151 */ \"orderby_opt ::=\",\n /* 152 */ \"orderby_opt ::= ORDER BY sortlist\",\n /* 153 */ \"sortlist ::= sortlist COMMA expr sortorder\",\n /* 154 */ \"sortlist ::= expr sortorder\",\n /* 155 */ \"sortorder ::= ASC\",\n /* 156 */ \"sortorder ::= DESC\",\n /* 157 */ \"sortorder ::=\",\n /* 158 */ \"groupby_opt ::=\",\n /* 159 */ \"groupby_opt ::= GROUP BY nexprlist\",\n /* 160 */ \"having_opt ::=\",\n /* 161 */ \"having_opt ::= HAVING expr\",\n /* 162 */ \"limit_opt ::=\",\n /* 163 */ \"limit_opt ::= LIMIT expr\",\n /* 164 */ \"limit_opt ::= LIMIT expr OFFSET expr\",\n /* 165 */ \"limit_opt ::= LIMIT expr COMMA expr\",\n /* 166 */ \"cmd ::= DELETE FROM fullname indexed_opt where_opt\",\n /* 167 */ \"where_opt ::=\",\n /* 168 */ \"where_opt ::= WHERE expr\",\n /* 169 */ \"cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt\",\n /* 170 */ \"setlist ::= setlist COMMA nm EQ expr\",\n /* 171 */ \"setlist ::= nm EQ expr\",\n /* 172 */ \"cmd ::= insert_cmd INTO fullname inscollist_opt valuelist\",\n /* 173 */ \"cmd ::= insert_cmd INTO fullname inscollist_opt select\",\n /* 174 */ \"cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES\",\n /* 175 */ \"insert_cmd ::= INSERT orconf\",\n /* 176 */ \"insert_cmd ::= REPLACE\",\n /* 177 */ \"valuelist ::= VALUES LP nexprlist RP\",\n /* 178 */ \"valuelist ::= valuelist COMMA LP exprlist RP\",\n /* 179 */ \"inscollist_opt ::=\",\n /* 180 */ \"inscollist_opt ::= LP inscollist RP\",\n /* 181 */ \"inscollist ::= inscollist COMMA nm\",\n /* 182 */ \"inscollist ::= nm\",\n /* 183 */ \"expr ::= term\",\n /* 184 */ \"expr ::= LP expr RP\",\n /* 185 */ \"term ::= NULL\",\n /* 186 */ \"expr ::= id\",\n /* 187 */ \"expr ::= JOIN_KW\",\n /* 188 */ \"expr ::= nm DOT nm\",\n /* 189 */ \"expr ::= nm DOT nm DOT nm\",\n /* 190 */ \"term ::= INTEGER|FLOAT|BLOB\",\n /* 191 */ \"term ::= STRING\",\n /* 192 */ \"expr ::= REGISTER\",\n /* 193 */ \"expr ::= VARIABLE\",\n /* 194 */ \"expr ::= expr COLLATE ids\",\n /* 195 */ \"expr ::= CAST LP expr AS typetoken RP\",\n /* 196 */ \"expr ::= ID LP distinct exprlist RP\",\n /* 197 */ \"expr ::= ID LP STAR RP\",\n /* 198 */ \"term ::= CTIME_KW\",\n /* 199 */ \"expr ::= expr AND expr\",\n /* 200 */ \"expr ::= expr OR expr\",\n /* 201 */ \"expr ::= expr LT|GT|GE|LE expr\",\n /* 202 */ \"expr ::= expr EQ|NE expr\",\n /* 203 */ \"expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr\",\n /* 204 */ \"expr ::= expr PLUS|MINUS expr\",\n /* 205 */ \"expr ::= expr STAR|SLASH|REM expr\",\n /* 206 */ \"expr ::= expr CONCAT expr\",\n /* 207 */ \"likeop ::= LIKE_KW\",\n /* 208 */ \"likeop ::= NOT LIKE_KW\",\n /* 209 */ \"likeop ::= MATCH\",\n /* 210 */ \"likeop ::= NOT MATCH\",\n /* 211 */ \"expr ::= expr likeop expr\",\n /* 212 */ \"expr ::= expr likeop expr ESCAPE expr\",\n /* 213 */ \"expr ::= expr ISNULL|NOTNULL\",\n /* 214 */ \"expr ::= expr NOT NULL\",\n /* 215 */ \"expr ::= expr IS expr\",\n /* 216 */ \"expr ::= expr IS NOT expr\",\n /* 217 */ \"expr ::= NOT expr\",\n /* 218 */ \"expr ::= BITNOT expr\",\n /* 219 */ \"expr ::= MINUS expr\",\n /* 220 */ \"expr ::= PLUS expr\",\n /* 221 */ \"between_op ::= BETWEEN\",\n /* 222 */ \"between_op ::= NOT BETWEEN\",\n /* 223 */ \"expr ::= expr between_op expr AND expr\",\n /* 224 */ \"in_op ::= IN\",\n /* 225 */ \"in_op ::= NOT IN\",\n /* 226 */ \"expr ::= expr in_op LP exprlist RP\",\n /* 227 */ \"expr ::= LP select RP\",\n /* 228 */ \"expr ::= expr in_op LP select RP\",\n /* 229 */ \"expr ::= expr in_op nm dbnm\",\n /* 230 */ \"expr ::= EXISTS LP select RP\",\n /* 231 */ \"expr ::= CASE case_operand case_exprlist case_else END\",\n /* 232 */ \"case_exprlist ::= case_exprlist WHEN expr THEN expr\",\n /* 233 */ \"case_exprlist ::= WHEN expr THEN expr\",\n /* 234 */ \"case_else ::= ELSE expr\",\n /* 235 */ \"case_else ::=\",\n /* 236 */ \"case_operand ::= expr\",\n /* 237 */ \"case_operand ::=\",\n /* 238 */ \"exprlist ::= nexprlist\",\n /* 239 */ \"exprlist ::=\",\n /* 240 */ \"nexprlist ::= nexprlist COMMA expr\",\n /* 241 */ \"nexprlist ::= expr\",\n /* 242 */ \"cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP\",\n /* 243 */ \"uniqueflag ::= UNIQUE\",\n /* 244 */ \"uniqueflag ::=\",\n /* 245 */ \"idxlist_opt ::=\",\n /* 246 */ \"idxlist_opt ::= LP idxlist RP\",\n /* 247 */ \"idxlist ::= idxlist COMMA nm collate sortorder\",\n /* 248 */ \"idxlist ::= nm collate sortorder\",\n /* 249 */ \"collate ::=\",\n /* 250 */ \"collate ::= COLLATE ids\",\n /* 251 */ \"cmd ::= DROP INDEX ifexists fullname\",\n /* 252 */ \"cmd ::= VACUUM\",\n /* 253 */ \"cmd ::= VACUUM nm\",\n /* 254 */ \"cmd ::= PRAGMA nm dbnm\",\n /* 255 */ \"cmd ::= PRAGMA nm dbnm EQ nmnum\",\n /* 256 */ \"cmd ::= PRAGMA nm dbnm LP nmnum RP\",\n /* 257 */ \"cmd ::= PRAGMA nm dbnm EQ minus_num\",\n /* 258 */ \"cmd ::= PRAGMA nm dbnm LP minus_num RP\",\n /* 259 */ \"nmnum ::= plus_num\",\n /* 260 */ \"nmnum ::= nm\",\n /* 261 */ \"nmnum ::= ON\",\n /* 262 */ \"nmnum ::= DELETE\",\n /* 263 */ \"nmnum ::= DEFAULT\",\n /* 264 */ \"plus_num ::= PLUS number\",\n /* 265 */ \"plus_num ::= number\",\n /* 266 */ \"minus_num ::= MINUS number\",\n /* 267 */ \"number ::= INTEGER|FLOAT\",\n /* 268 */ \"cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END\",\n /* 269 */ \"trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause\",\n /* 270 */ \"trigger_time ::= BEFORE\",\n /* 271 */ \"trigger_time ::= AFTER\",\n /* 272 */ \"trigger_time ::= INSTEAD OF\",\n /* 273 */ \"trigger_time ::=\",\n /* 274 */ \"trigger_event ::= DELETE|INSERT\",\n /* 275 */ \"trigger_event ::= UPDATE\",\n /* 276 */ \"trigger_event ::= UPDATE OF inscollist\",\n /* 277 */ \"foreach_clause ::=\",\n /* 278 */ \"foreach_clause ::= FOR EACH ROW\",\n /* 279 */ \"when_clause ::=\",\n /* 280 */ \"when_clause ::= WHEN expr\",\n /* 281 */ \"trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI\",\n /* 282 */ \"trigger_cmd_list ::= trigger_cmd SEMI\",\n /* 283 */ \"trnm ::= nm\",\n /* 284 */ \"trnm ::= nm DOT nm\",\n /* 285 */ \"tridxby ::=\",\n /* 286 */ \"tridxby ::= INDEXED BY nm\",\n /* 287 */ \"tridxby ::= NOT INDEXED\",\n /* 288 */ \"trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt\",\n /* 289 */ \"trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist\",\n /* 290 */ \"trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select\",\n /* 291 */ \"trigger_cmd ::= DELETE FROM trnm tridxby where_opt\",\n /* 292 */ \"trigger_cmd ::= select\",\n /* 293 */ \"expr ::= RAISE LP IGNORE RP\",\n /* 294 */ \"expr ::= RAISE LP raisetype COMMA nm RP\",\n /* 295 */ \"raisetype ::= ROLLBACK\",\n /* 296 */ \"raisetype ::= ABORT\",\n /* 297 */ \"raisetype ::= FAIL\",\n /* 298 */ \"cmd ::= DROP TRIGGER ifexists fullname\",\n /* 299 */ \"cmd ::= ATTACH database_kw_opt expr AS expr key_opt\",\n /* 300 */ \"cmd ::= DETACH database_kw_opt expr\",\n /* 301 */ \"key_opt ::=\",\n /* 302 */ \"key_opt ::= KEY expr\",\n /* 303 */ \"database_kw_opt ::= DATABASE\",\n /* 304 */ \"database_kw_opt ::=\",\n /* 305 */ \"cmd ::= REINDEX\",\n /* 306 */ \"cmd ::= REINDEX nm dbnm\",\n /* 307 */ \"cmd ::= ANALYZE\",\n /* 308 */ \"cmd ::= ANALYZE nm dbnm\",\n /* 309 */ \"cmd ::= ALTER TABLE fullname RENAME TO nm\",\n /* 310 */ \"cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column\",\n /* 311 */ \"add_column_fullname ::= fullname\",\n /* 312 */ \"kwcolumn_opt ::=\",\n /* 313 */ \"kwcolumn_opt ::= COLUMNKW\",\n /* 314 */ \"cmd ::= create_vtab\",\n /* 315 */ \"cmd ::= create_vtab LP vtabarglist RP\",\n /* 316 */ \"create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm\",\n /* 317 */ \"vtabarglist ::= vtabarg\",\n /* 318 */ \"vtabarglist ::= vtabarglist COMMA vtabarg\",\n /* 319 */ \"vtabarg ::=\",\n /* 320 */ \"vtabarg ::= vtabarg vtabargtoken\",\n /* 321 */ \"vtabargtoken ::= ANY\",\n /* 322 */ \"vtabargtoken ::= lp anylist RP\",\n /* 323 */ \"lp ::= LP\",\n /* 324 */ \"anylist ::=\",\n /* 325 */ \"anylist ::= anylist LP anylist RP\",\n /* 326 */ \"anylist ::= anylist ANY\",\n};\n#endif /* NDEBUG */\n\n\n#if YYSTACKDEPTH<=0\n/*\n** Try to increase the size of the parser stack.\n*/\nstatic void yyGrowStack(yyParser *p){\n  int newSize;\n  yyStackEntry *pNew;\n\n  newSize = p->yystksz*2 + 100;\n  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));\n  if( pNew ){\n    p->yystack = pNew;\n    p->yystksz = newSize;\n#ifndef NDEBUG\n    if( yyTraceFILE ){\n      fprintf(yyTraceFILE,\"%sStack grows to %d entries!\\n\",\n              yyTracePrompt, p->yystksz);\n    }\n#endif\n  }\n}\n#endif\n\n/* \n** This function allocates a new parser.\n** The only argument is a pointer to a function which works like\n** malloc.\n**\n** Inputs:\n** A pointer to the function used to allocate memory.\n**\n** Outputs:\n** A pointer to a parser.  This pointer is used in subsequent calls\n** to sqlite3Parser and sqlite3ParserFree.\n*/\nSQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){\n  yyParser *pParser;\n  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );\n  if( pParser ){\n    pParser->yyidx = -1;\n#ifdef YYTRACKMAXSTACKDEPTH\n    pParser->yyidxMax = 0;\n#endif\n#if YYSTACKDEPTH<=0\n    pParser->yystack = NULL;\n    pParser->yystksz = 0;\n    yyGrowStack(pParser);\n#endif\n  }\n  return pParser;\n}\n\n/* The following function deletes the value associated with a\n** symbol.  The symbol can be either a terminal or nonterminal.\n** \"yymajor\" is the symbol code, and \"yypminor\" is a pointer to\n** the value.\n*/\nstatic void yy_destructor(\n  yyParser *yypParser,    /* The parser */\n  YYCODETYPE yymajor,     /* Type code for object to destroy */\n  YYMINORTYPE *yypminor   /* The object to be destroyed */\n){\n  sqlite3ParserARG_FETCH;\n  switch( yymajor ){\n    /* Here is inserted the actions which take place when a\n    ** terminal or non-terminal is destroyed.  This can happen\n    ** when the symbol is popped from the stack during a\n    ** reduce or during error processing or when a parser is \n    ** being destroyed before it is finished parsing.\n    **\n    ** Note: during a reduce, the only symbols destroyed are those\n    ** which appear on the RHS of the rule, but which are not used\n    ** inside the C code.\n    */\n    case 160: /* select */\n    case 194: /* oneselect */\n{\nsqlite3SelectDelete(pParse->db, (yypminor->yy159));\n}\n      break;\n    case 173: /* term */\n    case 174: /* expr */\n{\nsqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);\n}\n      break;\n    case 178: /* idxlist_opt */\n    case 187: /* idxlist */\n    case 197: /* selcollist */\n    case 200: /* groupby_opt */\n    case 202: /* orderby_opt */\n    case 204: /* sclp */\n    case 214: /* sortlist */\n    case 215: /* nexprlist */\n    case 216: /* setlist */\n    case 220: /* exprlist */\n    case 225: /* case_exprlist */\n{\nsqlite3ExprListDelete(pParse->db, (yypminor->yy442));\n}\n      break;\n    case 193: /* fullname */\n    case 198: /* from */\n    case 206: /* seltablist */\n    case 207: /* stl_prefix */\n{\nsqlite3SrcListDelete(pParse->db, (yypminor->yy347));\n}\n      break;\n    case 199: /* where_opt */\n    case 201: /* having_opt */\n    case 210: /* on_opt */\n    case 224: /* case_operand */\n    case 226: /* case_else */\n    case 236: /* when_clause */\n    case 241: /* key_opt */\n{\nsqlite3ExprDelete(pParse->db, (yypminor->yy122));\n}\n      break;\n    case 211: /* using_opt */\n    case 213: /* inscollist */\n    case 218: /* inscollist_opt */\n{\nsqlite3IdListDelete(pParse->db, (yypminor->yy180));\n}\n      break;\n    case 219: /* valuelist */\n{\n\n  sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);\n  sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);\n\n}\n      break;\n    case 232: /* trigger_cmd_list */\n    case 237: /* trigger_cmd */\n{\nsqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));\n}\n      break;\n    case 234: /* trigger_event */\n{\nsqlite3IdListDelete(pParse->db, (yypminor->yy410).b);\n}\n      break;\n    default:  break;   /* If no destructor action specified: do nothing */\n  }\n}\n\n/*\n** Pop the parser's stack once.\n**\n** If there is a destructor routine associated with the token which\n** is popped from the stack, then call it.\n**\n** Return the major token number for the symbol popped.\n*/\nstatic int yy_pop_parser_stack(yyParser *pParser){\n  YYCODETYPE yymajor;\n  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];\n\n  /* There is no mechanism by which the parser stack can be popped below\n  ** empty in SQLite.  */\n  if( NEVER(pParser->yyidx<0) ) return 0;\n#ifndef NDEBUG\n  if( yyTraceFILE && pParser->yyidx>=0 ){\n    fprintf(yyTraceFILE,\"%sPopping %s\\n\",\n      yyTracePrompt,\n      yyTokenName[yytos->major]);\n  }\n#endif\n  yymajor = yytos->major;\n  yy_destructor(pParser, yymajor, &yytos->minor);\n  pParser->yyidx--;\n  return yymajor;\n}\n\n/* \n** Deallocate and destroy a parser.  Destructors are all called for\n** all stack elements before shutting the parser down.\n**\n** Inputs:\n** <ul>\n** <li>  A pointer to the parser.  This should be a pointer\n**       obtained from sqlite3ParserAlloc.\n** <li>  A pointer to a function used to reclaim memory obtained\n**       from malloc.\n** </ul>\n*/\nSQLITE_PRIVATE void sqlite3ParserFree(\n  void *p,                    /* The parser to be deleted */\n  void (*freeProc)(void*)     /* Function used to reclaim memory */\n){\n  yyParser *pParser = (yyParser*)p;\n  /* In SQLite, we never try to destroy a parser that was not successfully\n  ** created in the first place. */\n  if( NEVER(pParser==0) ) return;\n  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);\n#if YYSTACKDEPTH<=0\n  free(pParser->yystack);\n#endif\n  (*freeProc)((void*)pParser);\n}\n\n/*\n** Return the peak depth of the stack for a parser.\n*/\n#ifdef YYTRACKMAXSTACKDEPTH\nSQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){\n  yyParser *pParser = (yyParser*)p;\n  return pParser->yyidxMax;\n}\n#endif\n\n/*\n** Find the appropriate action for a parser given the terminal\n** look-ahead token iLookAhead.\n**\n** If the look-ahead token is YYNOCODE, then check to see if the action is\n** independent of the look-ahead.  If it is, return the action, otherwise\n** return YY_NO_ACTION.\n*/\nstatic int yy_find_shift_action(\n  yyParser *pParser,        /* The parser */\n  YYCODETYPE iLookAhead     /* The look-ahead token */\n){\n  int i;\n  int stateno = pParser->yystack[pParser->yyidx].stateno;\n \n  if( stateno>YY_SHIFT_COUNT\n   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){\n    return yy_default[stateno];\n  }\n  assert( iLookAhead!=YYNOCODE );\n  i += iLookAhead;\n  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){\n    if( iLookAhead>0 ){\n#ifdef YYFALLBACK\n      YYCODETYPE iFallback;            /* Fallback token */\n      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])\n             && (iFallback = yyFallback[iLookAhead])!=0 ){\n#ifndef NDEBUG\n        if( yyTraceFILE ){\n          fprintf(yyTraceFILE, \"%sFALLBACK %s => %s\\n\",\n             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);\n        }\n#endif\n        return yy_find_shift_action(pParser, iFallback);\n      }\n#endif\n#ifdef YYWILDCARD\n      {\n        int j = i - iLookAhead + YYWILDCARD;\n        if( \n#if YY_SHIFT_MIN+YYWILDCARD<0\n          j>=0 &&\n#endif\n#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT\n          j<YY_ACTTAB_COUNT &&\n#endif\n          yy_lookahead[j]==YYWILDCARD\n        ){\n#ifndef NDEBUG\n          if( yyTraceFILE ){\n            fprintf(yyTraceFILE, \"%sWILDCARD %s => %s\\n\",\n               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);\n          }\n#endif /* NDEBUG */\n          return yy_action[j];\n        }\n      }\n#endif /* YYWILDCARD */\n    }\n    return yy_default[stateno];\n  }else{\n    return yy_action[i];\n  }\n}\n\n/*\n** Find the appropriate action for a parser given the non-terminal\n** look-ahead token iLookAhead.\n**\n** If the look-ahead token is YYNOCODE, then check to see if the action is\n** independent of the look-ahead.  If it is, return the action, otherwise\n** return YY_NO_ACTION.\n*/\nstatic int yy_find_reduce_action(\n  int stateno,              /* Current state number */\n  YYCODETYPE iLookAhead     /* The look-ahead token */\n){\n  int i;\n#ifdef YYERRORSYMBOL\n  if( stateno>YY_REDUCE_COUNT ){\n    return yy_default[stateno];\n  }\n#else\n  assert( stateno<=YY_REDUCE_COUNT );\n#endif\n  i = yy_reduce_ofst[stateno];\n  assert( i!=YY_REDUCE_USE_DFLT );\n  assert( iLookAhead!=YYNOCODE );\n  i += iLookAhead;\n#ifdef YYERRORSYMBOL\n  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){\n    return yy_default[stateno];\n  }\n#else\n  assert( i>=0 && i<YY_ACTTAB_COUNT );\n  assert( yy_lookahead[i]==iLookAhead );\n#endif\n  return yy_action[i];\n}\n\n/*\n** The following routine is called if the stack overflows.\n*/\nstatic void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){\n   sqlite3ParserARG_FETCH;\n   yypParser->yyidx--;\n#ifndef NDEBUG\n   if( yyTraceFILE ){\n     fprintf(yyTraceFILE,\"%sStack Overflow!\\n\",yyTracePrompt);\n   }\n#endif\n   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);\n   /* Here code is inserted which will execute if the parser\n   ** stack every overflows */\n\n  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */\n  sqlite3ErrorMsg(pParse, \"parser stack overflow\");\n   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */\n}\n\n/*\n** Perform a shift action.\n*/\nstatic void yy_shift(\n  yyParser *yypParser,          /* The parser to be shifted */\n  int yyNewState,               /* The new state to shift in */\n  int yyMajor,                  /* The major token to shift in */\n  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */\n){\n  yyStackEntry *yytos;\n  yypParser->yyidx++;\n#ifdef YYTRACKMAXSTACKDEPTH\n  if( yypParser->yyidx>yypParser->yyidxMax ){\n    yypParser->yyidxMax = yypParser->yyidx;\n  }\n#endif\n#if YYSTACKDEPTH>0 \n  if( yypParser->yyidx>=YYSTACKDEPTH ){\n    yyStackOverflow(yypParser, yypMinor);\n    return;\n  }\n#else\n  if( yypParser->yyidx>=yypParser->yystksz ){\n    yyGrowStack(yypParser);\n    if( yypParser->yyidx>=yypParser->yystksz ){\n      yyStackOverflow(yypParser, yypMinor);\n      return;\n    }\n  }\n#endif\n  yytos = &yypParser->yystack[yypParser->yyidx];\n  yytos->stateno = (YYACTIONTYPE)yyNewState;\n  yytos->major = (YYCODETYPE)yyMajor;\n  yytos->minor = *yypMinor;\n#ifndef NDEBUG\n  if( yyTraceFILE && yypParser->yyidx>0 ){\n    int i;\n    fprintf(yyTraceFILE,\"%sShift %d\\n\",yyTracePrompt,yyNewState);\n    fprintf(yyTraceFILE,\"%sStack:\",yyTracePrompt);\n    for(i=1; i<=yypParser->yyidx; i++)\n      fprintf(yyTraceFILE,\" %s\",yyTokenName[yypParser->yystack[i].major]);\n    fprintf(yyTraceFILE,\"\\n\");\n  }\n#endif\n}\n\n/* The following table contains information about every rule that\n** is used during the reduce.\n*/\nstatic const struct {\n  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */\n  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */\n} yyRuleInfo[] = {\n  { 142, 1 },\n  { 143, 2 },\n  { 143, 1 },\n  { 144, 1 },\n  { 144, 3 },\n  { 145, 0 },\n  { 145, 1 },\n  { 145, 3 },\n  { 146, 1 },\n  { 147, 3 },\n  { 149, 0 },\n  { 149, 1 },\n  { 149, 2 },\n  { 148, 0 },\n  { 148, 1 },\n  { 148, 1 },\n  { 148, 1 },\n  { 147, 2 },\n  { 147, 2 },\n  { 147, 2 },\n  { 151, 1 },\n  { 151, 0 },\n  { 147, 2 },\n  { 147, 3 },\n  { 147, 5 },\n  { 147, 2 },\n  { 152, 6 },\n  { 154, 1 },\n  { 156, 0 },\n  { 156, 3 },\n  { 155, 1 },\n  { 155, 0 },\n  { 153, 4 },\n  { 153, 2 },\n  { 158, 3 },\n  { 158, 1 },\n  { 161, 3 },\n  { 162, 1 },\n  { 165, 1 },\n  { 165, 1 },\n  { 166, 1 },\n  { 150, 1 },\n  { 150, 1 },\n  { 150, 1 },\n  { 163, 0 },\n  { 163, 1 },\n  { 167, 1 },\n  { 167, 4 },\n  { 167, 6 },\n  { 168, 1 },\n  { 168, 2 },\n  { 169, 1 },\n  { 169, 1 },\n  { 164, 2 },\n  { 164, 0 },\n  { 172, 2 },\n  { 172, 2 },\n  { 172, 4 },\n  { 172, 3 },\n  { 172, 3 },\n  { 172, 2 },\n  { 172, 2 },\n  { 172, 3 },\n  { 172, 5 },\n  { 172, 2 },\n  { 172, 4 },\n  { 172, 4 },\n  { 172, 1 },\n  { 172, 2 },\n  { 177, 0 },\n  { 177, 1 },\n  { 179, 0 },\n  { 179, 2 },\n  { 181, 2 },\n  { 181, 3 },\n  { 181, 3 },\n  { 181, 3 },\n  { 182, 2 },\n  { 182, 2 },\n  { 182, 1 },\n  { 182, 1 },\n  { 182, 2 },\n  { 180, 3 },\n  { 180, 2 },\n  { 183, 0 },\n  { 183, 2 },\n  { 183, 2 },\n  { 159, 0 },\n  { 159, 2 },\n  { 184, 3 },\n  { 184, 1 },\n  { 185, 1 },\n  { 185, 0 },\n  { 186, 2 },\n  { 186, 7 },\n  { 186, 5 },\n  { 186, 5 },\n  { 186, 10 },\n  { 188, 0 },\n  { 188, 1 },\n  { 175, 0 },\n  { 175, 3 },\n  { 189, 0 },\n  { 189, 2 },\n  { 190, 1 },\n  { 190, 1 },\n  { 190, 1 },\n  { 147, 4 },\n  { 192, 2 },\n  { 192, 0 },\n  { 147, 8 },\n  { 147, 4 },\n  { 147, 1 },\n  { 160, 1 },\n  { 160, 3 },\n  { 195, 1 },\n  { 195, 2 },\n  { 195, 1 },\n  { 194, 9 },\n  { 196, 1 },\n  { 196, 1 },\n  { 196, 0 },\n  { 204, 2 },\n  { 204, 0 },\n  { 197, 3 },\n  { 197, 2 },\n  { 197, 4 },\n  { 205, 2 },\n  { 205, 1 },\n  { 205, 0 },\n  { 198, 0 },\n  { 198, 2 },\n  { 207, 2 },\n  { 207, 0 },\n  { 206, 7 },\n  { 206, 7 },\n  { 206, 7 },\n  { 157, 0 },\n  { 157, 2 },\n  { 193, 2 },\n  { 208, 1 },\n  { 208, 2 },\n  { 208, 3 },\n  { 208, 4 },\n  { 210, 2 },\n  { 210, 0 },\n  { 209, 0 },\n  { 209, 3 },\n  { 209, 2 },\n  { 211, 4 },\n  { 211, 0 },\n  { 202, 0 },\n  { 202, 3 },\n  { 214, 4 },\n  { 214, 2 },\n  { 176, 1 },\n  { 176, 1 },\n  { 176, 0 },\n  { 200, 0 },\n  { 200, 3 },\n  { 201, 0 },\n  { 201, 2 },\n  { 203, 0 },\n  { 203, 2 },\n  { 203, 4 },\n  { 203, 4 },\n  { 147, 5 },\n  { 199, 0 },\n  { 199, 2 },\n  { 147, 7 },\n  { 216, 5 },\n  { 216, 3 },\n  { 147, 5 },\n  { 147, 5 },\n  { 147, 6 },\n  { 217, 2 },\n  { 217, 1 },\n  { 219, 4 },\n  { 219, 5 },\n  { 218, 0 },\n  { 218, 3 },\n  { 213, 3 },\n  { 213, 1 },\n  { 174, 1 },\n  { 174, 3 },\n  { 173, 1 },\n  { 174, 1 },\n  { 174, 1 },\n  { 174, 3 },\n  { 174, 5 },\n  { 173, 1 },\n  { 173, 1 },\n  { 174, 1 },\n  { 174, 1 },\n  { 174, 3 },\n  { 174, 6 },\n  { 174, 5 },\n  { 174, 4 },\n  { 173, 1 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 3 },\n  { 221, 1 },\n  { 221, 2 },\n  { 221, 1 },\n  { 221, 2 },\n  { 174, 3 },\n  { 174, 5 },\n  { 174, 2 },\n  { 174, 3 },\n  { 174, 3 },\n  { 174, 4 },\n  { 174, 2 },\n  { 174, 2 },\n  { 174, 2 },\n  { 174, 2 },\n  { 222, 1 },\n  { 222, 2 },\n  { 174, 5 },\n  { 223, 1 },\n  { 223, 2 },\n  { 174, 5 },\n  { 174, 3 },\n  { 174, 5 },\n  { 174, 4 },\n  { 174, 4 },\n  { 174, 5 },\n  { 225, 5 },\n  { 225, 4 },\n  { 226, 2 },\n  { 226, 0 },\n  { 224, 1 },\n  { 224, 0 },\n  { 220, 1 },\n  { 220, 0 },\n  { 215, 3 },\n  { 215, 1 },\n  { 147, 11 },\n  { 227, 1 },\n  { 227, 0 },\n  { 178, 0 },\n  { 178, 3 },\n  { 187, 5 },\n  { 187, 3 },\n  { 228, 0 },\n  { 228, 2 },\n  { 147, 4 },\n  { 147, 1 },\n  { 147, 2 },\n  { 147, 3 },\n  { 147, 5 },\n  { 147, 6 },\n  { 147, 5 },\n  { 147, 6 },\n  { 229, 1 },\n  { 229, 1 },\n  { 229, 1 },\n  { 229, 1 },\n  { 229, 1 },\n  { 170, 2 },\n  { 170, 1 },\n  { 171, 2 },\n  { 230, 1 },\n  { 147, 5 },\n  { 231, 11 },\n  { 233, 1 },\n  { 233, 1 },\n  { 233, 2 },\n  { 233, 0 },\n  { 234, 1 },\n  { 234, 1 },\n  { 234, 3 },\n  { 235, 0 },\n  { 235, 3 },\n  { 236, 0 },\n  { 236, 2 },\n  { 232, 3 },\n  { 232, 2 },\n  { 238, 1 },\n  { 238, 3 },\n  { 239, 0 },\n  { 239, 3 },\n  { 239, 2 },\n  { 237, 7 },\n  { 237, 5 },\n  { 237, 5 },\n  { 237, 5 },\n  { 237, 1 },\n  { 174, 4 },\n  { 174, 6 },\n  { 191, 1 },\n  { 191, 1 },\n  { 191, 1 },\n  { 147, 4 },\n  { 147, 6 },\n  { 147, 3 },\n  { 241, 0 },\n  { 241, 2 },\n  { 240, 1 },\n  { 240, 0 },\n  { 147, 1 },\n  { 147, 3 },\n  { 147, 1 },\n  { 147, 3 },\n  { 147, 6 },\n  { 147, 6 },\n  { 242, 1 },\n  { 243, 0 },\n  { 243, 1 },\n  { 147, 1 },\n  { 147, 4 },\n  { 244, 8 },\n  { 245, 1 },\n  { 245, 3 },\n  { 246, 0 },\n  { 246, 2 },\n  { 247, 1 },\n  { 247, 3 },\n  { 248, 1 },\n  { 249, 0 },\n  { 249, 4 },\n  { 249, 2 },\n};\n\nstatic void yy_accept(yyParser*);  /* Forward Declaration */\n\n/*\n** Perform a reduce action and the shift that must immediately\n** follow the reduce.\n*/\nstatic void yy_reduce(\n  yyParser *yypParser,         /* The parser */\n  int yyruleno                 /* Number of the rule by which to reduce */\n){\n  int yygoto;                     /* The next state */\n  int yyact;                      /* The next action */\n  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */\n  yyStackEntry *yymsp;            /* The top of the parser's stack */\n  int yysize;                     /* Amount to pop the stack */\n  sqlite3ParserARG_FETCH;\n  yymsp = &yypParser->yystack[yypParser->yyidx];\n#ifndef NDEBUG\n  if( yyTraceFILE && yyruleno>=0 \n        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){\n    fprintf(yyTraceFILE, \"%sReduce [%s].\\n\", yyTracePrompt,\n      yyRuleName[yyruleno]);\n  }\n#endif /* NDEBUG */\n\n  /* Silence complaints from purify about yygotominor being uninitialized\n  ** in some cases when it is copied into the stack after the following\n  ** switch.  yygotominor is uninitialized when a rule reduces that does\n  ** not set the value of its left-hand side nonterminal.  Leaving the\n  ** value of the nonterminal uninitialized is utterly harmless as long\n  ** as the value is never used.  So really the only thing this code\n  ** accomplishes is to quieten purify.  \n  **\n  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that\n  ** without this code, their parser segfaults.  I'm not sure what there\n  ** parser is doing to make this happen.  This is the second bug report\n  ** from wireshark this week.  Clearly they are stressing Lemon in ways\n  ** that it has not been previously stressed...  (SQLite ticket #2172)\n  */\n  /*memset(&yygotominor, 0, sizeof(yygotominor));*/\n  yygotominor = yyzerominor;\n\n\n  switch( yyruleno ){\n  /* Beginning here are the reduction cases.  A typical example\n  ** follows:\n  **   case 0:\n  **  #line <lineno> <grammarfile>\n  **     { ... }           // User supplied code\n  **  #line <lineno> <thisfile>\n  **     break;\n  */\n      case 5: /* explain ::= */\n{ sqlite3BeginParse(pParse, 0); }\n        break;\n      case 6: /* explain ::= EXPLAIN */\n{ sqlite3BeginParse(pParse, 1); }\n        break;\n      case 7: /* explain ::= EXPLAIN QUERY PLAN */\n{ sqlite3BeginParse(pParse, 2); }\n        break;\n      case 8: /* cmdx ::= cmd */\n{ sqlite3FinishCoding(pParse); }\n        break;\n      case 9: /* cmd ::= BEGIN transtype trans_opt */\n{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}\n        break;\n      case 13: /* transtype ::= */\n{yygotominor.yy392 = TK_DEFERRED;}\n        break;\n      case 14: /* transtype ::= DEFERRED */\n      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);\n      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);\n      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);\n      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);\n{yygotominor.yy392 = yymsp[0].major;}\n        break;\n      case 17: /* cmd ::= COMMIT trans_opt */\n      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);\n{sqlite3CommitTransaction(pParse);}\n        break;\n      case 19: /* cmd ::= ROLLBACK trans_opt */\n{sqlite3RollbackTransaction(pParse);}\n        break;\n      case 22: /* cmd ::= SAVEPOINT nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);\n}\n        break;\n      case 23: /* cmd ::= RELEASE savepoint_opt nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);\n}\n        break;\n      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */\n{\n  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);\n}\n        break;\n      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */\n{\n   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);\n}\n        break;\n      case 27: /* createkw ::= CREATE */\n{\n  pParse->db->lookaside.bEnabled = 0;\n  yygotominor.yy0 = yymsp[0].minor.yy0;\n}\n        break;\n      case 28: /* ifnotexists ::= */\n      case 31: /* temp ::= */ yytestcase(yyruleno==31);\n      case 69: /* autoinc ::= */ yytestcase(yyruleno==69);\n      case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);\n      case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);\n      case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);\n      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);\n      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);\n      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);\n      case 121: /* distinct ::= */ yytestcase(yyruleno==121);\n      case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);\n      case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);\n{yygotominor.yy392 = 0;}\n        break;\n      case 29: /* ifnotexists ::= IF NOT EXISTS */\n      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);\n      case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);\n      case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);\n      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);\n      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);\n      case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);\n      case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);\n{yygotominor.yy392 = 1;}\n        break;\n      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */\n{\n  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);\n}\n        break;\n      case 33: /* create_table_args ::= AS select */\n{\n  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);\n  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);\n}\n        break;\n      case 36: /* column ::= columnid type carglist */\n{\n  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;\n  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;\n}\n        break;\n      case 37: /* columnid ::= nm */\n{\n  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);\n  yygotominor.yy0 = yymsp[0].minor.yy0;\n  pParse->constraintName.n = 0;\n}\n        break;\n      case 38: /* id ::= ID */\n      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);\n      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);\n      case 41: /* nm ::= id */ yytestcase(yyruleno==41);\n      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);\n      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);\n      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);\n      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);\n      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);\n      case 128: /* as ::= ids */ yytestcase(yyruleno==128);\n      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);\n      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);\n      case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);\n      case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);\n      case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);\n      case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);\n      case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);\n      case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);\n      case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);\n      case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);\n      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);\n      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);\n      case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);\n{yygotominor.yy0 = yymsp[0].minor.yy0;}\n        break;\n      case 45: /* type ::= typetoken */\n{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}\n        break;\n      case 47: /* typetoken ::= typename LP signed RP */\n{\n  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;\n  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);\n}\n        break;\n      case 48: /* typetoken ::= typename LP signed COMMA signed RP */\n{\n  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;\n  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);\n}\n        break;\n      case 50: /* typename ::= typename ids */\n{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}\n        break;\n      case 55: /* ccons ::= CONSTRAINT nm */\n      case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);\n{pParse->constraintName = yymsp[0].minor.yy0;}\n        break;\n      case 56: /* ccons ::= DEFAULT term */\n      case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);\n{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}\n        break;\n      case 57: /* ccons ::= DEFAULT LP expr RP */\n{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}\n        break;\n      case 59: /* ccons ::= DEFAULT MINUS term */\n{\n  ExprSpan v;\n  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);\n  v.zStart = yymsp[-1].minor.yy0.z;\n  v.zEnd = yymsp[0].minor.yy342.zEnd;\n  sqlite3AddDefaultValue(pParse,&v);\n}\n        break;\n      case 60: /* ccons ::= DEFAULT id */\n{\n  ExprSpan v;\n  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);\n  sqlite3AddDefaultValue(pParse,&v);\n}\n        break;\n      case 62: /* ccons ::= NOT NULL onconf */\n{sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}\n        break;\n      case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */\n{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}\n        break;\n      case 64: /* ccons ::= UNIQUE onconf */\n{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}\n        break;\n      case 65: /* ccons ::= CHECK LP expr RP */\n{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}\n        break;\n      case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */\n{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}\n        break;\n      case 67: /* ccons ::= defer_subclause */\n{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}\n        break;\n      case 68: /* ccons ::= COLLATE ids */\n{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}\n        break;\n      case 71: /* refargs ::= */\n{ yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}\n        break;\n      case 72: /* refargs ::= refargs refarg */\n{ yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }\n        break;\n      case 73: /* refarg ::= MATCH nm */\n      case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);\n{ yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }\n        break;\n      case 75: /* refarg ::= ON DELETE refact */\n{ yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }\n        break;\n      case 76: /* refarg ::= ON UPDATE refact */\n{ yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }\n        break;\n      case 77: /* refact ::= SET NULL */\n{ yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}\n        break;\n      case 78: /* refact ::= SET DEFAULT */\n{ yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}\n        break;\n      case 79: /* refact ::= CASCADE */\n{ yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}\n        break;\n      case 80: /* refact ::= RESTRICT */\n{ yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}\n        break;\n      case 81: /* refact ::= NO ACTION */\n{ yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}\n        break;\n      case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */\n      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);\n      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);\n      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);\n{yygotominor.yy392 = yymsp[0].minor.yy392;}\n        break;\n      case 87: /* conslist_opt ::= */\n{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}\n        break;\n      case 88: /* conslist_opt ::= COMMA conslist */\n{yygotominor.yy0 = yymsp[-1].minor.yy0;}\n        break;\n      case 91: /* tconscomma ::= COMMA */\n{pParse->constraintName.n = 0;}\n        break;\n      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */\n{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}\n        break;\n      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */\n{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}\n        break;\n      case 96: /* tcons ::= CHECK LP expr RP onconf */\n{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}\n        break;\n      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */\n{\n    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);\n    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);\n}\n        break;\n      case 100: /* onconf ::= */\n{yygotominor.yy392 = OE_Default;}\n        break;\n      case 102: /* orconf ::= */\n{yygotominor.yy258 = OE_Default;}\n        break;\n      case 103: /* orconf ::= OR resolvetype */\n{yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}\n        break;\n      case 105: /* resolvetype ::= IGNORE */\n{yygotominor.yy392 = OE_Ignore;}\n        break;\n      case 106: /* resolvetype ::= REPLACE */\n{yygotominor.yy392 = OE_Replace;}\n        break;\n      case 107: /* cmd ::= DROP TABLE ifexists fullname */\n{\n  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);\n}\n        break;\n      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */\n{\n  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);\n}\n        break;\n      case 111: /* cmd ::= DROP VIEW ifexists fullname */\n{\n  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);\n}\n        break;\n      case 112: /* cmd ::= select */\n{\n  SelectDest dest = {SRT_Output, 0, 0, 0, 0};\n  sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);\n  sqlite3ExplainBegin(pParse->pVdbe);\n  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);\n  sqlite3ExplainFinish(pParse->pVdbe);\n  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);\n}\n        break;\n      case 113: /* select ::= oneselect */\n{yygotominor.yy159 = yymsp[0].minor.yy159;}\n        break;\n      case 114: /* select ::= select multiselect_op oneselect */\n{\n  if( yymsp[0].minor.yy159 ){\n    yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;\n    yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;\n  }else{\n    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);\n  }\n  yygotominor.yy159 = yymsp[0].minor.yy159;\n}\n        break;\n      case 116: /* multiselect_op ::= UNION ALL */\n{yygotominor.yy392 = TK_ALL;}\n        break;\n      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */\n{\n  yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);\n}\n        break;\n      case 122: /* sclp ::= selcollist COMMA */\n      case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);\n{yygotominor.yy442 = yymsp[-1].minor.yy442;}\n        break;\n      case 123: /* sclp ::= */\n      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);\n      case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);\n      case 239: /* exprlist ::= */ yytestcase(yyruleno==239);\n      case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);\n{yygotominor.yy442 = 0;}\n        break;\n      case 124: /* selcollist ::= sclp expr as */\n{\n   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);\n   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);\n   sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);\n}\n        break;\n      case 125: /* selcollist ::= sclp STAR */\n{\n  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);\n}\n        break;\n      case 126: /* selcollist ::= sclp nm DOT STAR */\n{\n  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);\n  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);\n  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);\n}\n        break;\n      case 129: /* as ::= */\n{yygotominor.yy0.n = 0;}\n        break;\n      case 130: /* from ::= */\n{yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}\n        break;\n      case 131: /* from ::= FROM seltablist */\n{\n  yygotominor.yy347 = yymsp[0].minor.yy347;\n  sqlite3SrcListShiftJoinType(yygotominor.yy347);\n}\n        break;\n      case 132: /* stl_prefix ::= seltablist joinop */\n{\n   yygotominor.yy347 = yymsp[-1].minor.yy347;\n   if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;\n}\n        break;\n      case 133: /* stl_prefix ::= */\n{yygotominor.yy347 = 0;}\n        break;\n      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */\n{\n  yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);\n  sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);\n}\n        break;\n      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */\n{\n    yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);\n  }\n        break;\n      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */\n{\n    if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){\n      yygotominor.yy347 = yymsp[-4].minor.yy347;\n    }else{\n      Select *pSubquery;\n      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);\n      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);\n      yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);\n    }\n  }\n        break;\n      case 137: /* dbnm ::= */\n      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);\n{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}\n        break;\n      case 139: /* fullname ::= nm dbnm */\n{yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}\n        break;\n      case 140: /* joinop ::= COMMA|JOIN */\n{ yygotominor.yy392 = JT_INNER; }\n        break;\n      case 141: /* joinop ::= JOIN_KW JOIN */\n{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }\n        break;\n      case 142: /* joinop ::= JOIN_KW nm JOIN */\n{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }\n        break;\n      case 143: /* joinop ::= JOIN_KW nm nm JOIN */\n{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }\n        break;\n      case 144: /* on_opt ::= ON expr */\n      case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);\n      case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);\n      case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);\n      case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);\n{yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}\n        break;\n      case 145: /* on_opt ::= */\n      case 160: /* having_opt ::= */ yytestcase(yyruleno==160);\n      case 167: /* where_opt ::= */ yytestcase(yyruleno==167);\n      case 235: /* case_else ::= */ yytestcase(yyruleno==235);\n      case 237: /* case_operand ::= */ yytestcase(yyruleno==237);\n{yygotominor.yy122 = 0;}\n        break;\n      case 148: /* indexed_opt ::= NOT INDEXED */\n{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}\n        break;\n      case 149: /* using_opt ::= USING LP inscollist RP */\n      case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);\n{yygotominor.yy180 = yymsp[-1].minor.yy180;}\n        break;\n      case 150: /* using_opt ::= */\n      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);\n{yygotominor.yy180 = 0;}\n        break;\n      case 152: /* orderby_opt ::= ORDER BY sortlist */\n      case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);\n      case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);\n{yygotominor.yy442 = yymsp[0].minor.yy442;}\n        break;\n      case 153: /* sortlist ::= sortlist COMMA expr sortorder */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);\n  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;\n}\n        break;\n      case 154: /* sortlist ::= expr sortorder */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);\n  if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;\n}\n        break;\n      case 155: /* sortorder ::= ASC */\n      case 157: /* sortorder ::= */ yytestcase(yyruleno==157);\n{yygotominor.yy392 = SQLITE_SO_ASC;}\n        break;\n      case 156: /* sortorder ::= DESC */\n{yygotominor.yy392 = SQLITE_SO_DESC;}\n        break;\n      case 162: /* limit_opt ::= */\n{yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}\n        break;\n      case 163: /* limit_opt ::= LIMIT expr */\n{yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}\n        break;\n      case 164: /* limit_opt ::= LIMIT expr OFFSET expr */\n{yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}\n        break;\n      case 165: /* limit_opt ::= LIMIT expr COMMA expr */\n{yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}\n        break;\n      case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */\n{\n  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);\n  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);\n}\n        break;\n      case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */\n{\n  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);\n  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,\"set list\"); \n  sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);\n}\n        break;\n      case 170: /* setlist ::= setlist COMMA nm EQ expr */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);\n  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);\n}\n        break;\n      case 171: /* setlist ::= nm EQ expr */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);\n  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);\n}\n        break;\n      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */\n{sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}\n        break;\n      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */\n{sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}\n        break;\n      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */\n{sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}\n        break;\n      case 175: /* insert_cmd ::= INSERT orconf */\n{yygotominor.yy258 = yymsp[0].minor.yy258;}\n        break;\n      case 176: /* insert_cmd ::= REPLACE */\n{yygotominor.yy258 = OE_Replace;}\n        break;\n      case 177: /* valuelist ::= VALUES LP nexprlist RP */\n{\n  yygotominor.yy487.pList = yymsp[-1].minor.yy442;\n  yygotominor.yy487.pSelect = 0;\n}\n        break;\n      case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */\n{\n  Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);\n  if( yymsp[-4].minor.yy487.pList ){\n    yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);\n    yymsp[-4].minor.yy487.pList = 0;\n  }\n  yygotominor.yy487.pList = 0;\n  if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){\n    sqlite3SelectDelete(pParse->db, pRight);\n    sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);\n    yygotominor.yy487.pSelect = 0;\n  }else{\n    pRight->op = TK_ALL;\n    pRight->pPrior = yymsp[-4].minor.yy487.pSelect;\n    pRight->selFlags |= SF_Values;\n    pRight->pPrior->selFlags |= SF_Values;\n    yygotominor.yy487.pSelect = pRight;\n  }\n}\n        break;\n      case 181: /* inscollist ::= inscollist COMMA nm */\n{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}\n        break;\n      case 182: /* inscollist ::= nm */\n{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}\n        break;\n      case 183: /* expr ::= term */\n{yygotominor.yy342 = yymsp[0].minor.yy342;}\n        break;\n      case 184: /* expr ::= LP expr RP */\n{yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}\n        break;\n      case 185: /* term ::= NULL */\n      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);\n      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);\n{spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}\n        break;\n      case 186: /* expr ::= id */\n      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);\n{spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}\n        break;\n      case 188: /* expr ::= nm DOT nm */\n{\n  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);\n  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);\n  spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);\n}\n        break;\n      case 189: /* expr ::= nm DOT nm DOT nm */\n{\n  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);\n  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);\n  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);\n  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);\n  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);\n}\n        break;\n      case 192: /* expr ::= REGISTER */\n{\n  /* When doing a nested parse, one can include terms in an expression\n  ** that look like this:   #1 #2 ...  These terms refer to registers\n  ** in the virtual machine.  #N is the N-th register. */\n  if( pParse->nested==0 ){\n    sqlite3ErrorMsg(pParse, \"near \\\"%T\\\": syntax error\", &yymsp[0].minor.yy0);\n    yygotominor.yy342.pExpr = 0;\n  }else{\n    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);\n    if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);\n  }\n  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);\n}\n        break;\n      case 193: /* expr ::= VARIABLE */\n{\n  spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);\n  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);\n  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);\n}\n        break;\n      case 194: /* expr ::= expr COLLATE ids */\n{\n  yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);\n  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;\n  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n}\n        break;\n      case 195: /* expr ::= CAST LP expr AS typetoken RP */\n{\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);\n  spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);\n}\n        break;\n      case 196: /* expr ::= ID LP distinct exprlist RP */\n{\n  if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){\n    sqlite3ErrorMsg(pParse, \"too many arguments on function %T\", &yymsp[-4].minor.yy0);\n  }\n  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);\n  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);\n  if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){\n    yygotominor.yy342.pExpr->flags |= EP_Distinct;\n  }\n}\n        break;\n      case 197: /* expr ::= ID LP STAR RP */\n{\n  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);\n  spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);\n}\n        break;\n      case 198: /* term ::= CTIME_KW */\n{\n  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are\n  ** treated as functions that return constants */\n  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);\n  if( yygotominor.yy342.pExpr ){\n    yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  \n  }\n  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);\n}\n        break;\n      case 199: /* expr ::= expr AND expr */\n      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);\n      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);\n      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);\n      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);\n      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);\n      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);\n      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);\n{spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}\n        break;\n      case 207: /* likeop ::= LIKE_KW */\n      case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);\n{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}\n        break;\n      case 208: /* likeop ::= NOT LIKE_KW */\n      case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);\n{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}\n        break;\n      case 211: /* expr ::= expr likeop expr */\n{\n  ExprList *pList;\n  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);\n  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);\n  if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;\n  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;\n  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;\n}\n        break;\n      case 212: /* expr ::= expr likeop expr ESCAPE expr */\n{\n  ExprList *pList;\n  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);\n  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);\n  if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;\n  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;\n  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;\n}\n        break;\n      case 213: /* expr ::= expr ISNULL|NOTNULL */\n{spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}\n        break;\n      case 214: /* expr ::= expr NOT NULL */\n{spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}\n        break;\n      case 215: /* expr ::= expr IS expr */\n{\n  spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);\n  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);\n}\n        break;\n      case 216: /* expr ::= expr IS NOT expr */\n{\n  spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);\n  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);\n}\n        break;\n      case 217: /* expr ::= NOT expr */\n      case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);\n{spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}\n        break;\n      case 219: /* expr ::= MINUS expr */\n{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}\n        break;\n      case 220: /* expr ::= PLUS expr */\n{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}\n        break;\n      case 223: /* expr ::= expr between_op expr AND expr */\n{\n  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);\n  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);\n  if( yygotominor.yy342.pExpr ){\n    yygotominor.yy342.pExpr->x.pList = pList;\n  }else{\n    sqlite3ExprListDelete(pParse->db, pList);\n  } \n  if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;\n  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;\n}\n        break;\n      case 226: /* expr ::= expr in_op LP exprlist RP */\n{\n    if( yymsp[-1].minor.yy442==0 ){\n      /* Expressions of the form\n      **\n      **      expr1 IN ()\n      **      expr1 NOT IN ()\n      **\n      ** simplify to constants 0 (false) and 1 (true), respectively,\n      ** regardless of the value of expr1.\n      */\n      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);\n      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);\n    }else{\n      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);\n      if( yygotominor.yy342.pExpr ){\n        yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;\n        sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);\n      }else{\n        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);\n      }\n      if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n    }\n    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;\n    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n  }\n        break;\n      case 227: /* expr ::= LP select RP */\n{\n    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);\n    if( yygotominor.yy342.pExpr ){\n      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;\n      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);\n      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);\n    }else{\n      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);\n    }\n    yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;\n    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n  }\n        break;\n      case 228: /* expr ::= expr in_op LP select RP */\n{\n    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);\n    if( yygotominor.yy342.pExpr ){\n      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;\n      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);\n      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);\n    }else{\n      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);\n    }\n    if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;\n    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n  }\n        break;\n      case 229: /* expr ::= expr in_op nm dbnm */\n{\n    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);\n    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);\n    if( yygotominor.yy342.pExpr ){\n      yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);\n      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);\n      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);\n    }else{\n      sqlite3SrcListDelete(pParse->db, pSrc);\n    }\n    if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);\n    yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;\n    yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];\n  }\n        break;\n      case 230: /* expr ::= EXISTS LP select RP */\n{\n    Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);\n    if( p ){\n      p->x.pSelect = yymsp[-1].minor.yy159;\n      ExprSetProperty(p, EP_xIsSelect);\n      sqlite3ExprSetHeight(pParse, p);\n    }else{\n      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);\n    }\n    yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;\n    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n  }\n        break;\n      case 231: /* expr ::= CASE case_operand case_exprlist case_else END */\n{\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);\n  if( yygotominor.yy342.pExpr ){\n    yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;\n    sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);\n  }else{\n    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);\n  }\n  yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;\n  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n}\n        break;\n      case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);\n}\n        break;\n      case 233: /* case_exprlist ::= WHEN expr THEN expr */\n{\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);\n}\n        break;\n      case 240: /* nexprlist ::= nexprlist COMMA expr */\n{yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}\n        break;\n      case 241: /* nexprlist ::= expr */\n{yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}\n        break;\n      case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */\n{\n  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, \n                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,\n                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);\n}\n        break;\n      case 243: /* uniqueflag ::= UNIQUE */\n      case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);\n{yygotominor.yy392 = OE_Abort;}\n        break;\n      case 244: /* uniqueflag ::= */\n{yygotominor.yy392 = OE_None;}\n        break;\n      case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */\n{\n  Expr *p = 0;\n  if( yymsp[-1].minor.yy0.n>0 ){\n    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);\n    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);\n  }\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);\n  sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);\n  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, \"index\");\n  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;\n}\n        break;\n      case 248: /* idxlist ::= nm collate sortorder */\n{\n  Expr *p = 0;\n  if( yymsp[-1].minor.yy0.n>0 ){\n    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);\n    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);\n  }\n  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);\n  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);\n  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, \"index\");\n  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;\n}\n        break;\n      case 249: /* collate ::= */\n{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}\n        break;\n      case 251: /* cmd ::= DROP INDEX ifexists fullname */\n{sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}\n        break;\n      case 252: /* cmd ::= VACUUM */\n      case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);\n{sqlite3Vacuum(pParse);}\n        break;\n      case 254: /* cmd ::= PRAGMA nm dbnm */\n{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}\n        break;\n      case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */\n{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}\n        break;\n      case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */\n{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}\n        break;\n      case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */\n{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}\n        break;\n      case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */\n{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}\n        break;\n      case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */\n{\n  Token all;\n  all.z = yymsp[-3].minor.yy0.z;\n  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;\n  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);\n}\n        break;\n      case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */\n{\n  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);\n  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);\n}\n        break;\n      case 270: /* trigger_time ::= BEFORE */\n      case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);\n{ yygotominor.yy392 = TK_BEFORE; }\n        break;\n      case 271: /* trigger_time ::= AFTER */\n{ yygotominor.yy392 = TK_AFTER;  }\n        break;\n      case 272: /* trigger_time ::= INSTEAD OF */\n{ yygotominor.yy392 = TK_INSTEAD;}\n        break;\n      case 274: /* trigger_event ::= DELETE|INSERT */\n      case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);\n{yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}\n        break;\n      case 276: /* trigger_event ::= UPDATE OF inscollist */\n{yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}\n        break;\n      case 279: /* when_clause ::= */\n      case 301: /* key_opt ::= */ yytestcase(yyruleno==301);\n{ yygotominor.yy122 = 0; }\n        break;\n      case 280: /* when_clause ::= WHEN expr */\n      case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);\n{ yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }\n        break;\n      case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */\n{\n  assert( yymsp[-2].minor.yy327!=0 );\n  yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;\n  yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;\n  yygotominor.yy327 = yymsp[-2].minor.yy327;\n}\n        break;\n      case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */\n{ \n  assert( yymsp[-1].minor.yy327!=0 );\n  yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;\n  yygotominor.yy327 = yymsp[-1].minor.yy327;\n}\n        break;\n      case 284: /* trnm ::= nm DOT nm */\n{\n  yygotominor.yy0 = yymsp[0].minor.yy0;\n  sqlite3ErrorMsg(pParse, \n        \"qualified table names are not allowed on INSERT, UPDATE, and DELETE \"\n        \"statements within triggers\");\n}\n        break;\n      case 286: /* tridxby ::= INDEXED BY nm */\n{\n  sqlite3ErrorMsg(pParse,\n        \"the INDEXED BY clause is not allowed on UPDATE or DELETE statements \"\n        \"within triggers\");\n}\n        break;\n      case 287: /* tridxby ::= NOT INDEXED */\n{\n  sqlite3ErrorMsg(pParse,\n        \"the NOT INDEXED clause is not allowed on UPDATE or DELETE statements \"\n        \"within triggers\");\n}\n        break;\n      case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */\n{ yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }\n        break;\n      case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */\n{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}\n        break;\n      case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */\n{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}\n        break;\n      case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */\n{yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}\n        break;\n      case 292: /* trigger_cmd ::= select */\n{yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }\n        break;\n      case 293: /* expr ::= RAISE LP IGNORE RP */\n{\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); \n  if( yygotominor.yy342.pExpr ){\n    yygotominor.yy342.pExpr->affinity = OE_Ignore;\n  }\n  yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;\n  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n}\n        break;\n      case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */\n{\n  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); \n  if( yygotominor.yy342.pExpr ) {\n    yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;\n  }\n  yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;\n  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];\n}\n        break;\n      case 295: /* raisetype ::= ROLLBACK */\n{yygotominor.yy392 = OE_Rollback;}\n        break;\n      case 297: /* raisetype ::= FAIL */\n{yygotominor.yy392 = OE_Fail;}\n        break;\n      case 298: /* cmd ::= DROP TRIGGER ifexists fullname */\n{\n  sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);\n}\n        break;\n      case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */\n{\n  sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);\n}\n        break;\n      case 300: /* cmd ::= DETACH database_kw_opt expr */\n{\n  sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);\n}\n        break;\n      case 305: /* cmd ::= REINDEX */\n{sqlite3Reindex(pParse, 0, 0);}\n        break;\n      case 306: /* cmd ::= REINDEX nm dbnm */\n{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}\n        break;\n      case 307: /* cmd ::= ANALYZE */\n{sqlite3Analyze(pParse, 0, 0);}\n        break;\n      case 308: /* cmd ::= ANALYZE nm dbnm */\n{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}\n        break;\n      case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */\n{\n  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);\n}\n        break;\n      case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */\n{\n  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);\n}\n        break;\n      case 311: /* add_column_fullname ::= fullname */\n{\n  pParse->db->lookaside.bEnabled = 0;\n  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);\n}\n        break;\n      case 314: /* cmd ::= create_vtab */\n{sqlite3VtabFinishParse(pParse,0);}\n        break;\n      case 315: /* cmd ::= create_vtab LP vtabarglist RP */\n{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}\n        break;\n      case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */\n{\n    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);\n}\n        break;\n      case 319: /* vtabarg ::= */\n{sqlite3VtabArgInit(pParse);}\n        break;\n      case 321: /* vtabargtoken ::= ANY */\n      case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);\n      case 323: /* lp ::= LP */ yytestcase(yyruleno==323);\n{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}\n        break;\n      default:\n      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);\n      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);\n      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);\n      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);\n      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);\n      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);\n      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);\n      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);\n      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);\n      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);\n      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);\n      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);\n      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);\n      /* (44) type ::= */ yytestcase(yyruleno==44);\n      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);\n      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);\n      /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);\n      /* (54) carglist ::= */ yytestcase(yyruleno==54);\n      /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);\n      /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);\n      /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);\n      /* (92) tconscomma ::= */ yytestcase(yyruleno==92);\n      /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);\n      /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);\n      /* (285) tridxby ::= */ yytestcase(yyruleno==285);\n      /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);\n      /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);\n      /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);\n      /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);\n      /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);\n      /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);\n      /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);\n      /* (324) anylist ::= */ yytestcase(yyruleno==324);\n      /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);\n      /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);\n        break;\n  };\n  yygoto = yyRuleInfo[yyruleno].lhs;\n  yysize = yyRuleInfo[yyruleno].nrhs;\n  yypParser->yyidx -= yysize;\n  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);\n  if( yyact < YYNSTATE ){\n#ifdef NDEBUG\n    /* If we are not debugging and the reduce action popped at least\n    ** one element off the stack, then we can push the new element back\n    ** onto the stack here, and skip the stack overflow test in yy_shift().\n    ** That gives a significant speed improvement. */\n    if( yysize ){\n      yypParser->yyidx++;\n      yymsp -= yysize-1;\n      yymsp->stateno = (YYACTIONTYPE)yyact;\n      yymsp->major = (YYCODETYPE)yygoto;\n      yymsp->minor = yygotominor;\n    }else\n#endif\n    {\n      yy_shift(yypParser,yyact,yygoto,&yygotominor);\n    }\n  }else{\n    assert( yyact == YYNSTATE + YYNRULE + 1 );\n    yy_accept(yypParser);\n  }\n}\n\n/*\n** The following code executes when the parse fails\n*/\n#ifndef YYNOERRORRECOVERY\nstatic void yy_parse_failed(\n  yyParser *yypParser           /* The parser */\n){\n  sqlite3ParserARG_FETCH;\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sFail!\\n\",yyTracePrompt);\n  }\n#endif\n  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);\n  /* Here code is inserted which will be executed whenever the\n  ** parser fails */\n  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */\n}\n#endif /* YYNOERRORRECOVERY */\n\n/*\n** The following code executes when a syntax error first occurs.\n*/\nstatic void yy_syntax_error(\n  yyParser *yypParser,           /* The parser */\n  int yymajor,                   /* The major type of the error token */\n  YYMINORTYPE yyminor            /* The minor type of the error token */\n){\n  sqlite3ParserARG_FETCH;\n#define TOKEN (yyminor.yy0)\n\n  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */\n  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */\n  sqlite3ErrorMsg(pParse, \"near \\\"%T\\\": syntax error\", &TOKEN);\n  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */\n}\n\n/*\n** The following is executed when the parser accepts\n*/\nstatic void yy_accept(\n  yyParser *yypParser           /* The parser */\n){\n  sqlite3ParserARG_FETCH;\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sAccept!\\n\",yyTracePrompt);\n  }\n#endif\n  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);\n  /* Here code is inserted which will be executed whenever the\n  ** parser accepts */\n  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */\n}\n\n/* The main parser program.\n** The first argument is a pointer to a structure obtained from\n** \"sqlite3ParserAlloc\" which describes the current state of the parser.\n** The second argument is the major token number.  The third is\n** the minor token.  The fourth optional argument is whatever the\n** user wants (and specified in the grammar) and is available for\n** use by the action routines.\n**\n** Inputs:\n** <ul>\n** <li> A pointer to the parser (an opaque structure.)\n** <li> The major token number.\n** <li> The minor token number.\n** <li> An option argument of a grammar-specified type.\n** </ul>\n**\n** Outputs:\n** None.\n*/\nSQLITE_PRIVATE void sqlite3Parser(\n  void *yyp,                   /* The parser */\n  int yymajor,                 /* The major token code number */\n  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */\n  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */\n){\n  YYMINORTYPE yyminorunion;\n  int yyact;            /* The parser action. */\n#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)\n  int yyendofinput;     /* True if we are at the end of input */\n#endif\n#ifdef YYERRORSYMBOL\n  int yyerrorhit = 0;   /* True if yymajor has invoked an error */\n#endif\n  yyParser *yypParser;  /* The parser */\n\n  /* (re)initialize the parser, if necessary */\n  yypParser = (yyParser*)yyp;\n  if( yypParser->yyidx<0 ){\n#if YYSTACKDEPTH<=0\n    if( yypParser->yystksz <=0 ){\n      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/\n      yyminorunion = yyzerominor;\n      yyStackOverflow(yypParser, &yyminorunion);\n      return;\n    }\n#endif\n    yypParser->yyidx = 0;\n    yypParser->yyerrcnt = -1;\n    yypParser->yystack[0].stateno = 0;\n    yypParser->yystack[0].major = 0;\n  }\n  yyminorunion.yy0 = yyminor;\n#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)\n  yyendofinput = (yymajor==0);\n#endif\n  sqlite3ParserARG_STORE;\n\n#ifndef NDEBUG\n  if( yyTraceFILE ){\n    fprintf(yyTraceFILE,\"%sInput %s\\n\",yyTracePrompt,yyTokenName[yymajor]);\n  }\n#endif\n\n  do{\n    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);\n    if( yyact<YYNSTATE ){\n      yy_shift(yypParser,yyact,yymajor,&yyminorunion);\n      yypParser->yyerrcnt--;\n      yymajor = YYNOCODE;\n    }else if( yyact < YYNSTATE + YYNRULE ){\n      yy_reduce(yypParser,yyact-YYNSTATE);\n    }else{\n      assert( yyact == YY_ERROR_ACTION );\n#ifdef YYERRORSYMBOL\n      int yymx;\n#endif\n#ifndef NDEBUG\n      if( yyTraceFILE ){\n        fprintf(yyTraceFILE,\"%sSyntax Error!\\n\",yyTracePrompt);\n      }\n#endif\n#ifdef YYERRORSYMBOL\n      /* A syntax error has occurred.\n      ** The response to an error depends upon whether or not the\n      ** grammar defines an error token \"ERROR\".  \n      **\n      ** This is what we do if the grammar does define ERROR:\n      **\n      **  * Call the %syntax_error function.\n      **\n      **  * Begin popping the stack until we enter a state where\n      **    it is legal to shift the error symbol, then shift\n      **    the error symbol.\n      **\n      **  * Set the error count to three.\n      **\n      **  * Begin accepting and shifting new tokens.  No new error\n      **    processing will occur until three tokens have been\n      **    shifted successfully.\n      **\n      */\n      if( yypParser->yyerrcnt<0 ){\n        yy_syntax_error(yypParser,yymajor,yyminorunion);\n      }\n      yymx = yypParser->yystack[yypParser->yyidx].major;\n      if( yymx==YYERRORSYMBOL || yyerrorhit ){\n#ifndef NDEBUG\n        if( yyTraceFILE ){\n          fprintf(yyTraceFILE,\"%sDiscard input token %s\\n\",\n             yyTracePrompt,yyTokenName[yymajor]);\n        }\n#endif\n        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);\n        yymajor = YYNOCODE;\n      }else{\n         while(\n          yypParser->yyidx >= 0 &&\n          yymx != YYERRORSYMBOL &&\n          (yyact = yy_find_reduce_action(\n                        yypParser->yystack[yypParser->yyidx].stateno,\n                        YYERRORSYMBOL)) >= YYNSTATE\n        ){\n          yy_pop_parser_stack(yypParser);\n        }\n        if( yypParser->yyidx < 0 || yymajor==0 ){\n          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n          yy_parse_failed(yypParser);\n          yymajor = YYNOCODE;\n        }else if( yymx!=YYERRORSYMBOL ){\n          YYMINORTYPE u2;\n          u2.YYERRSYMDT = 0;\n          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);\n        }\n      }\n      yypParser->yyerrcnt = 3;\n      yyerrorhit = 1;\n#elif defined(YYNOERRORRECOVERY)\n      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to\n      ** do any kind of error recovery.  Instead, simply invoke the syntax\n      ** error routine and continue going as if nothing had happened.\n      **\n      ** Applications can set this macro (for example inside %include) if\n      ** they intend to abandon the parse upon the first syntax error seen.\n      */\n      yy_syntax_error(yypParser,yymajor,yyminorunion);\n      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n      yymajor = YYNOCODE;\n      \n#else  /* YYERRORSYMBOL is not defined */\n      /* This is what we do if the grammar does not define ERROR:\n      **\n      **  * Report an error message, and throw away the input token.\n      **\n      **  * If the input token is $, then fail the parse.\n      **\n      ** As before, subsequent error messages are suppressed until\n      ** three input tokens have been successfully shifted.\n      */\n      if( yypParser->yyerrcnt<=0 ){\n        yy_syntax_error(yypParser,yymajor,yyminorunion);\n      }\n      yypParser->yyerrcnt = 3;\n      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);\n      if( yyendofinput ){\n        yy_parse_failed(yypParser);\n      }\n      yymajor = YYNOCODE;\n#endif\n    }\n  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );\n  return;\n}\n\n/************** End of parse.c ***********************************************/\n/************** Begin file tokenize.c ****************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** An tokenizer for SQL\n**\n** This file contains C code that splits an SQL input string up into\n** individual tokens and sends those tokens one-by-one over to the\n** parser for analysis.\n*/\n/* #include <stdlib.h> */\n\n/*\n** The charMap() macro maps alphabetic characters into their\n** lower-case ASCII equivalent.  On ASCII machines, this is just\n** an upper-to-lower case map.  On EBCDIC machines we also need\n** to adjust the encoding.  Only alphabetic characters and underscores\n** need to be translated.\n*/\n#ifdef SQLITE_ASCII\n# define charMap(X) sqlite3UpperToLower[(unsigned char)X]\n#endif\n#ifdef SQLITE_EBCDIC\n# define charMap(X) ebcdicToAscii[(unsigned char)X]\nconst unsigned char ebcdicToAscii[] = {\n/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */\n   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */\n   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */\n   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */\n   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */\n   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */\n   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */\n   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */\n};\n#endif\n\n/*\n** The sqlite3KeywordCode function looks up an identifier to determine if\n** it is a keyword.  If it is a keyword, the token code of that keyword is \n** returned.  If the input is not a keyword, TK_ID is returned.\n**\n** The implementation of this routine was generated by a program,\n** mkkeywordhash.h, located in the tool subdirectory of the distribution.\n** The output of the mkkeywordhash.c program is written into a file\n** named keywordhash.h and then included into this source file by\n** the #include below.\n*/\n/************** Include keywordhash.h in the middle of tokenize.c ************/\n/************** Begin file keywordhash.h *************************************/\n/***** This file contains automatically generated code ******\n**\n** The code in this file has been automatically generated by\n**\n**   sqlite/tool/mkkeywordhash.c\n**\n** The code in this file implements a function that determines whether\n** or not a given identifier is really an SQL keyword.  The same thing\n** might be implemented more directly using a hand-written hash table.\n** But by using this automatically generated code, the size of the code\n** is substantially reduced.  This is important for embedded applications\n** on platforms with limited memory.\n*/\n/* Hash score: 175 */\nstatic int keywordCode(const char *z, int n){\n  /* zText[] encodes 811 bytes of keywords in 541 bytes */\n  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */\n  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */\n  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */\n  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */\n  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */\n  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */\n  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */\n  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */\n  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */\n  /*   INITIALLY                                                          */\n  static const char zText[540] = {\n    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',\n    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',\n    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',\n    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',\n    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',\n    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',\n    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',\n    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',\n    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',\n    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',\n    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',\n    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',\n    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',\n    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',\n    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',\n    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',\n    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',\n    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',\n    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',\n    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',\n    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',\n    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',\n    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',\n    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',\n    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',\n    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',\n    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',\n    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',\n    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',\n    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',\n  };\n  static const unsigned char aHash[127] = {\n      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,\n      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,\n     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,\n       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,\n       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,\n      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,\n      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,\n      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,\n      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,\n      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,\n  };\n  static const unsigned char aNext[121] = {\n       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,\n       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,\n       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,\n       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,\n       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,\n      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,\n      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,\n       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,\n     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,\n      35,  64,   0,   0,\n  };\n  static const unsigned char aLen[121] = {\n       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,\n       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,\n      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,\n       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,\n       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,\n       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,\n       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,\n       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,\n       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,\n       6,   4,   9,   3,\n  };\n  static const unsigned short int aOffset[121] = {\n       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,\n      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,\n      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,\n     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,\n     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,\n     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,\n     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,\n     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,\n     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,\n     521, 527, 531, 536,\n  };\n  static const unsigned char aCode[121] = {\n    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     \n    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    \n    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    \n    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      \n    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       \n    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    \n    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  \n    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       \n    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       \n    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     \n    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    \n    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       \n    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       \n    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  \n    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    \n    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      \n    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    \n    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         \n    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    \n    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   \n    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    \n    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      \n    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        \n    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  \n    TK_ALL,        \n  };\n  int h, i;\n  if( n<2 ) return TK_ID;\n  h = ((charMap(z[0])*4) ^\n      (charMap(z[n-1])*3) ^\n      n) % 127;\n  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){\n    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){\n      testcase( i==0 ); /* REINDEX */\n      testcase( i==1 ); /* INDEXED */\n      testcase( i==2 ); /* INDEX */\n      testcase( i==3 ); /* DESC */\n      testcase( i==4 ); /* ESCAPE */\n      testcase( i==5 ); /* EACH */\n      testcase( i==6 ); /* CHECK */\n      testcase( i==7 ); /* KEY */\n      testcase( i==8 ); /* BEFORE */\n      testcase( i==9 ); /* FOREIGN */\n      testcase( i==10 ); /* FOR */\n      testcase( i==11 ); /* IGNORE */\n      testcase( i==12 ); /* REGEXP */\n      testcase( i==13 ); /* EXPLAIN */\n      testcase( i==14 ); /* INSTEAD */\n      testcase( i==15 ); /* ADD */\n      testcase( i==16 ); /* DATABASE */\n      testcase( i==17 ); /* AS */\n      testcase( i==18 ); /* SELECT */\n      testcase( i==19 ); /* TABLE */\n      testcase( i==20 ); /* LEFT */\n      testcase( i==21 ); /* THEN */\n      testcase( i==22 ); /* END */\n      testcase( i==23 ); /* DEFERRABLE */\n      testcase( i==24 ); /* ELSE */\n      testcase( i==25 ); /* EXCEPT */\n      testcase( i==26 ); /* TRANSACTION */\n      testcase( i==27 ); /* ACTION */\n      testcase( i==28 ); /* ON */\n      testcase( i==29 ); /* NATURAL */\n      testcase( i==30 ); /* ALTER */\n      testcase( i==31 ); /* RAISE */\n      testcase( i==32 ); /* EXCLUSIVE */\n      testcase( i==33 ); /* EXISTS */\n      testcase( i==34 ); /* SAVEPOINT */\n      testcase( i==35 ); /* INTERSECT */\n      testcase( i==36 ); /* TRIGGER */\n      testcase( i==37 ); /* REFERENCES */\n      testcase( i==38 ); /* CONSTRAINT */\n      testcase( i==39 ); /* INTO */\n      testcase( i==40 ); /* OFFSET */\n      testcase( i==41 ); /* OF */\n      testcase( i==42 ); /* SET */\n      testcase( i==43 ); /* TEMPORARY */\n      testcase( i==44 ); /* TEMP */\n      testcase( i==45 ); /* OR */\n      testcase( i==46 ); /* UNIQUE */\n      testcase( i==47 ); /* QUERY */\n      testcase( i==48 ); /* ATTACH */\n      testcase( i==49 ); /* HAVING */\n      testcase( i==50 ); /* GROUP */\n      testcase( i==51 ); /* UPDATE */\n      testcase( i==52 ); /* BEGIN */\n      testcase( i==53 ); /* INNER */\n      testcase( i==54 ); /* RELEASE */\n      testcase( i==55 ); /* BETWEEN */\n      testcase( i==56 ); /* NOTNULL */\n      testcase( i==57 ); /* NOT */\n      testcase( i==58 ); /* NO */\n      testcase( i==59 ); /* NULL */\n      testcase( i==60 ); /* LIKE */\n      testcase( i==61 ); /* CASCADE */\n      testcase( i==62 ); /* ASC */\n      testcase( i==63 ); /* DELETE */\n      testcase( i==64 ); /* CASE */\n      testcase( i==65 ); /* COLLATE */\n      testcase( i==66 ); /* CREATE */\n      testcase( i==67 ); /* CURRENT_DATE */\n      testcase( i==68 ); /* DETACH */\n      testcase( i==69 ); /* IMMEDIATE */\n      testcase( i==70 ); /* JOIN */\n      testcase( i==71 ); /* INSERT */\n      testcase( i==72 ); /* MATCH */\n      testcase( i==73 ); /* PLAN */\n      testcase( i==74 ); /* ANALYZE */\n      testcase( i==75 ); /* PRAGMA */\n      testcase( i==76 ); /* ABORT */\n      testcase( i==77 ); /* VALUES */\n      testcase( i==78 ); /* VIRTUAL */\n      testcase( i==79 ); /* LIMIT */\n      testcase( i==80 ); /* WHEN */\n      testcase( i==81 ); /* WHERE */\n      testcase( i==82 ); /* RENAME */\n      testcase( i==83 ); /* AFTER */\n      testcase( i==84 ); /* REPLACE */\n      testcase( i==85 ); /* AND */\n      testcase( i==86 ); /* DEFAULT */\n      testcase( i==87 ); /* AUTOINCREMENT */\n      testcase( i==88 ); /* TO */\n      testcase( i==89 ); /* IN */\n      testcase( i==90 ); /* CAST */\n      testcase( i==91 ); /* COLUMN */\n      testcase( i==92 ); /* COMMIT */\n      testcase( i==93 ); /* CONFLICT */\n      testcase( i==94 ); /* CROSS */\n      testcase( i==95 ); /* CURRENT_TIMESTAMP */\n      testcase( i==96 ); /* CURRENT_TIME */\n      testcase( i==97 ); /* PRIMARY */\n      testcase( i==98 ); /* DEFERRED */\n      testcase( i==99 ); /* DISTINCT */\n      testcase( i==100 ); /* IS */\n      testcase( i==101 ); /* DROP */\n      testcase( i==102 ); /* FAIL */\n      testcase( i==103 ); /* FROM */\n      testcase( i==104 ); /* FULL */\n      testcase( i==105 ); /* GLOB */\n      testcase( i==106 ); /* BY */\n      testcase( i==107 ); /* IF */\n      testcase( i==108 ); /* ISNULL */\n      testcase( i==109 ); /* ORDER */\n      testcase( i==110 ); /* RESTRICT */\n      testcase( i==111 ); /* OUTER */\n      testcase( i==112 ); /* RIGHT */\n      testcase( i==113 ); /* ROLLBACK */\n      testcase( i==114 ); /* ROW */\n      testcase( i==115 ); /* UNION */\n      testcase( i==116 ); /* USING */\n      testcase( i==117 ); /* VACUUM */\n      testcase( i==118 ); /* VIEW */\n      testcase( i==119 ); /* INITIALLY */\n      testcase( i==120 ); /* ALL */\n      return aCode[i];\n    }\n  }\n  return TK_ID;\n}\nSQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){\n  return keywordCode((char*)z, n);\n}\n#define SQLITE_N_KEYWORD 121\n\n/************** End of keywordhash.h *****************************************/\n/************** Continuing where we left off in tokenize.c *******************/\n\n\n/*\n** If X is a character that can be used in an identifier then\n** IdChar(X) will be true.  Otherwise it is false.\n**\n** For ASCII, any character with the high-order bit set is\n** allowed in an identifier.  For 7-bit characters, \n** sqlite3IsIdChar[X] must be 1.\n**\n** For EBCDIC, the rules are more complex but have the same\n** end result.\n**\n** Ticket #1066.  the SQL standard does not allow '$' in the\n** middle of identfiers.  But many SQL implementations do. \n** SQLite will allow '$' in identifiers for compatibility.\n** But the feature is undocumented.\n*/\n#ifdef SQLITE_ASCII\n#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)\n#endif\n#ifdef SQLITE_EBCDIC\nSQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {\n/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */\n    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */\n    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */\n    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */\n};\n#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))\n#endif\n\n\n/*\n** Return the length of the token that begins at z[0]. \n** Store the token type in *tokenType before returning.\n*/\nSQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){\n  int i, c;\n  switch( *z ){\n    case ' ': case '\\t': case '\\n': case '\\f': case '\\r': {\n      testcase( z[0]==' ' );\n      testcase( z[0]=='\\t' );\n      testcase( z[0]=='\\n' );\n      testcase( z[0]=='\\f' );\n      testcase( z[0]=='\\r' );\n      for(i=1; sqlite3Isspace(z[i]); i++){}\n      *tokenType = TK_SPACE;\n      return i;\n    }\n    case '-': {\n      if( z[1]=='-' ){\n        /* IMP: R-50417-27976 -- syntax diagram for comments */\n        for(i=2; (c=z[i])!=0 && c!='\\n'; i++){}\n        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */\n        return i;\n      }\n      *tokenType = TK_MINUS;\n      return 1;\n    }\n    case '(': {\n      *tokenType = TK_LP;\n      return 1;\n    }\n    case ')': {\n      *tokenType = TK_RP;\n      return 1;\n    }\n    case ';': {\n      *tokenType = TK_SEMI;\n      return 1;\n    }\n    case '+': {\n      *tokenType = TK_PLUS;\n      return 1;\n    }\n    case '*': {\n      *tokenType = TK_STAR;\n      return 1;\n    }\n    case '/': {\n      if( z[1]!='*' || z[2]==0 ){\n        *tokenType = TK_SLASH;\n        return 1;\n      }\n      /* IMP: R-50417-27976 -- syntax diagram for comments */\n      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}\n      if( c ) i++;\n      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */\n      return i;\n    }\n    case '%': {\n      *tokenType = TK_REM;\n      return 1;\n    }\n    case '=': {\n      *tokenType = TK_EQ;\n      return 1 + (z[1]=='=');\n    }\n    case '<': {\n      if( (c=z[1])=='=' ){\n        *tokenType = TK_LE;\n        return 2;\n      }else if( c=='>' ){\n        *tokenType = TK_NE;\n        return 2;\n      }else if( c=='<' ){\n        *tokenType = TK_LSHIFT;\n        return 2;\n      }else{\n        *tokenType = TK_LT;\n        return 1;\n      }\n    }\n    case '>': {\n      if( (c=z[1])=='=' ){\n        *tokenType = TK_GE;\n        return 2;\n      }else if( c=='>' ){\n        *tokenType = TK_RSHIFT;\n        return 2;\n      }else{\n        *tokenType = TK_GT;\n        return 1;\n      }\n    }\n    case '!': {\n      if( z[1]!='=' ){\n        *tokenType = TK_ILLEGAL;\n        return 2;\n      }else{\n        *tokenType = TK_NE;\n        return 2;\n      }\n    }\n    case '|': {\n      if( z[1]!='|' ){\n        *tokenType = TK_BITOR;\n        return 1;\n      }else{\n        *tokenType = TK_CONCAT;\n        return 2;\n      }\n    }\n    case ',': {\n      *tokenType = TK_COMMA;\n      return 1;\n    }\n    case '&': {\n      *tokenType = TK_BITAND;\n      return 1;\n    }\n    case '~': {\n      *tokenType = TK_BITNOT;\n      return 1;\n    }\n    case '`':\n    case '\\'':\n    case '\"': {\n      int delim = z[0];\n      testcase( delim=='`' );\n      testcase( delim=='\\'' );\n      testcase( delim=='\"' );\n      for(i=1; (c=z[i])!=0; i++){\n        if( c==delim ){\n          if( z[i+1]==delim ){\n            i++;\n          }else{\n            break;\n          }\n        }\n      }\n      if( c=='\\'' ){\n        *tokenType = TK_STRING;\n        return i+1;\n      }else if( c!=0 ){\n        *tokenType = TK_ID;\n        return i+1;\n      }else{\n        *tokenType = TK_ILLEGAL;\n        return i;\n      }\n    }\n    case '.': {\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      if( !sqlite3Isdigit(z[1]) )\n#endif\n      {\n        *tokenType = TK_DOT;\n        return 1;\n      }\n      /* If the next character is a digit, this is a floating point\n      ** number that begins with \".\".  Fall thru into the next case */\n    }\n    case '0': case '1': case '2': case '3': case '4':\n    case '5': case '6': case '7': case '8': case '9': {\n      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );\n      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );\n      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );\n      testcase( z[0]=='9' );\n      *tokenType = TK_INTEGER;\n      for(i=0; sqlite3Isdigit(z[i]); i++){}\n#ifndef SQLITE_OMIT_FLOATING_POINT\n      if( z[i]=='.' ){\n        i++;\n        while( sqlite3Isdigit(z[i]) ){ i++; }\n        *tokenType = TK_FLOAT;\n      }\n      if( (z[i]=='e' || z[i]=='E') &&\n           ( sqlite3Isdigit(z[i+1]) \n            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))\n           )\n      ){\n        i += 2;\n        while( sqlite3Isdigit(z[i]) ){ i++; }\n        *tokenType = TK_FLOAT;\n      }\n#endif\n      while( IdChar(z[i]) ){\n        *tokenType = TK_ILLEGAL;\n        i++;\n      }\n      return i;\n    }\n    case '[': {\n      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}\n      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;\n      return i;\n    }\n    case '?': {\n      *tokenType = TK_VARIABLE;\n      for(i=1; sqlite3Isdigit(z[i]); i++){}\n      return i;\n    }\n    case '#': {\n      for(i=1; sqlite3Isdigit(z[i]); i++){}\n      if( i>1 ){\n        /* Parameters of the form #NNN (where NNN is a number) are used\n        ** internally by sqlite3NestedParse.  */\n        *tokenType = TK_REGISTER;\n        return i;\n      }\n      /* Fall through into the next case if the '#' is not followed by\n      ** a digit. Try to match #AAAA where AAAA is a parameter name. */\n    }\n#ifndef SQLITE_OMIT_TCL_VARIABLE\n    case '$':\n#endif\n    case '@':  /* For compatibility with MS SQL Server */\n    case ':': {\n      int n = 0;\n      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );\n      *tokenType = TK_VARIABLE;\n      for(i=1; (c=z[i])!=0; i++){\n        if( IdChar(c) ){\n          n++;\n#ifndef SQLITE_OMIT_TCL_VARIABLE\n        }else if( c=='(' && n>0 ){\n          do{\n            i++;\n          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );\n          if( c==')' ){\n            i++;\n          }else{\n            *tokenType = TK_ILLEGAL;\n          }\n          break;\n        }else if( c==':' && z[i+1]==':' ){\n          i++;\n#endif\n        }else{\n          break;\n        }\n      }\n      if( n==0 ) *tokenType = TK_ILLEGAL;\n      return i;\n    }\n#ifndef SQLITE_OMIT_BLOB_LITERAL\n    case 'x': case 'X': {\n      testcase( z[0]=='x' ); testcase( z[0]=='X' );\n      if( z[1]=='\\'' ){\n        *tokenType = TK_BLOB;\n        for(i=2; sqlite3Isxdigit(z[i]); i++){}\n        if( z[i]!='\\'' || i%2 ){\n          *tokenType = TK_ILLEGAL;\n          while( z[i] && z[i]!='\\'' ){ i++; }\n        }\n        if( z[i] ) i++;\n        return i;\n      }\n      /* Otherwise fall through to the next case */\n    }\n#endif\n    default: {\n      if( !IdChar(*z) ){\n        break;\n      }\n      for(i=1; IdChar(z[i]); i++){}\n      *tokenType = keywordCode((char*)z, i);\n      return i;\n    }\n  }\n  *tokenType = TK_ILLEGAL;\n  return 1;\n}\n\n/*\n** Run the parser on the given SQL string.  The parser structure is\n** passed in.  An SQLITE_ status code is returned.  If an error occurs\n** then an and attempt is made to write an error message into \n** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that\n** error message.\n*/\nSQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){\n  int nErr = 0;                   /* Number of errors encountered */\n  int i;                          /* Loop counter */\n  void *pEngine;                  /* The LEMON-generated LALR(1) parser */\n  int tokenType;                  /* type of the next token */\n  int lastTokenParsed = -1;       /* type of the previous token */\n  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */\n  sqlite3 *db = pParse->db;       /* The database connection */\n  int mxSqlLen;                   /* Max length of an SQL string */\n\n\n  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];\n  if( db->activeVdbeCnt==0 ){\n    db->u1.isInterrupted = 0;\n  }\n  pParse->rc = SQLITE_OK;\n  pParse->zTail = zSql;\n  i = 0;\n  assert( pzErrMsg!=0 );\n  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);\n  if( pEngine==0 ){\n    db->mallocFailed = 1;\n    return SQLITE_NOMEM;\n  }\n  assert( pParse->pNewTable==0 );\n  assert( pParse->pNewTrigger==0 );\n  assert( pParse->nVar==0 );\n  assert( pParse->nzVar==0 );\n  assert( pParse->azVar==0 );\n  enableLookaside = db->lookaside.bEnabled;\n  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;\n  while( !db->mallocFailed && zSql[i]!=0 ){\n    assert( i>=0 );\n    pParse->sLastToken.z = &zSql[i];\n    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);\n    i += pParse->sLastToken.n;\n    if( i>mxSqlLen ){\n      pParse->rc = SQLITE_TOOBIG;\n      break;\n    }\n    switch( tokenType ){\n      case TK_SPACE: {\n        if( db->u1.isInterrupted ){\n          sqlite3ErrorMsg(pParse, \"interrupt\");\n          pParse->rc = SQLITE_INTERRUPT;\n          goto abort_parse;\n        }\n        break;\n      }\n      case TK_ILLEGAL: {\n        sqlite3DbFree(db, *pzErrMsg);\n        *pzErrMsg = sqlite3MPrintf(db, \"unrecognized token: \\\"%T\\\"\",\n                        &pParse->sLastToken);\n        nErr++;\n        goto abort_parse;\n      }\n      case TK_SEMI: {\n        pParse->zTail = &zSql[i];\n        /* Fall thru into the default case */\n      }\n      default: {\n        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);\n        lastTokenParsed = tokenType;\n        if( pParse->rc!=SQLITE_OK ){\n          goto abort_parse;\n        }\n        break;\n      }\n    }\n  }\nabort_parse:\n  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){\n    if( lastTokenParsed!=TK_SEMI ){\n      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);\n      pParse->zTail = &zSql[i];\n    }\n    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);\n  }\n#ifdef YYTRACKMAXSTACKDEPTH\n  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,\n      sqlite3ParserStackPeak(pEngine)\n  );\n#endif /* YYDEBUG */\n  sqlite3ParserFree(pEngine, sqlite3_free);\n  db->lookaside.bEnabled = enableLookaside;\n  if( db->mallocFailed ){\n    pParse->rc = SQLITE_NOMEM;\n  }\n  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){\n    sqlite3SetString(&pParse->zErrMsg, db, \"%s\", sqlite3ErrStr(pParse->rc));\n  }\n  assert( pzErrMsg!=0 );\n  if( pParse->zErrMsg ){\n    *pzErrMsg = pParse->zErrMsg;\n    sqlite3_log(pParse->rc, \"%s\", *pzErrMsg);\n    pParse->zErrMsg = 0;\n    nErr++;\n  }\n  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){\n    sqlite3VdbeDelete(pParse->pVdbe);\n    pParse->pVdbe = 0;\n  }\n#ifndef SQLITE_OMIT_SHARED_CACHE\n  if( pParse->nested==0 ){\n    sqlite3DbFree(db, pParse->aTableLock);\n    pParse->aTableLock = 0;\n    pParse->nTableLock = 0;\n  }\n#endif\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3_free(pParse->apVtabLock);\n#endif\n\n  if( !IN_DECLARE_VTAB ){\n    /* If the pParse->declareVtab flag is set, do not delete any table \n    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)\n    ** will take responsibility for freeing the Table structure.\n    */\n    sqlite3DeleteTable(db, pParse->pNewTable);\n  }\n\n  sqlite3DeleteTrigger(db, pParse->pNewTrigger);\n  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);\n  sqlite3DbFree(db, pParse->azVar);\n  sqlite3DbFree(db, pParse->aAlias);\n  while( pParse->pAinc ){\n    AutoincInfo *p = pParse->pAinc;\n    pParse->pAinc = p->pNext;\n    sqlite3DbFree(db, p);\n  }\n  while( pParse->pZombieTab ){\n    Table *p = pParse->pZombieTab;\n    pParse->pZombieTab = p->pNextZombie;\n    sqlite3DeleteTable(db, p);\n  }\n  if( nErr>0 && pParse->rc==SQLITE_OK ){\n    pParse->rc = SQLITE_ERROR;\n  }\n  return nErr;\n}\n\n/************** End of tokenize.c ********************************************/\n/************** Begin file complete.c ****************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** An tokenizer for SQL\n**\n** This file contains C code that implements the sqlite3_complete() API.\n** This code used to be part of the tokenizer.c source file.  But by\n** separating it out, the code will be automatically omitted from\n** static links that do not use it.\n*/\n#ifndef SQLITE_OMIT_COMPLETE\n\n/*\n** This is defined in tokenize.c.  We just have to import the definition.\n*/\n#ifndef SQLITE_AMALGAMATION\n#ifdef SQLITE_ASCII\n#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)\n#endif\n#ifdef SQLITE_EBCDIC\nSQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];\n#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))\n#endif\n#endif /* SQLITE_AMALGAMATION */\n\n\n/*\n** Token types used by the sqlite3_complete() routine.  See the header\n** comments on that procedure for additional information.\n*/\n#define tkSEMI    0\n#define tkWS      1\n#define tkOTHER   2\n#ifndef SQLITE_OMIT_TRIGGER\n#define tkEXPLAIN 3\n#define tkCREATE  4\n#define tkTEMP    5\n#define tkTRIGGER 6\n#define tkEND     7\n#endif\n\n/*\n** Return TRUE if the given SQL string ends in a semicolon.\n**\n** Special handling is require for CREATE TRIGGER statements.\n** Whenever the CREATE TRIGGER keywords are seen, the statement\n** must end with \";END;\".\n**\n** This implementation uses a state machine with 8 states:\n**\n**   (0) INVALID   We have not yet seen a non-whitespace character.\n**\n**   (1) START     At the beginning or end of an SQL statement.  This routine\n**                 returns 1 if it ends in the START state and 0 if it ends\n**                 in any other state.\n**\n**   (2) NORMAL    We are in the middle of statement which ends with a single\n**                 semicolon.\n**\n**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of \n**                 a statement.\n**\n**   (4) CREATE    The keyword CREATE has been seen at the beginning of a\n**                 statement, possibly preceeded by EXPLAIN and/or followed by\n**                 TEMP or TEMPORARY\n**\n**   (5) TRIGGER   We are in the middle of a trigger definition that must be\n**                 ended by a semicolon, the keyword END, and another semicolon.\n**\n**   (6) SEMI      We've seen the first semicolon in the \";END;\" that occurs at\n**                 the end of a trigger definition.\n**\n**   (7) END       We've seen the \";END\" of the \";END;\" that occurs at the end\n**                 of a trigger difinition.\n**\n** Transitions between states above are determined by tokens extracted\n** from the input.  The following tokens are significant:\n**\n**   (0) tkSEMI      A semicolon.\n**   (1) tkWS        Whitespace.\n**   (2) tkOTHER     Any other SQL token.\n**   (3) tkEXPLAIN   The \"explain\" keyword.\n**   (4) tkCREATE    The \"create\" keyword.\n**   (5) tkTEMP      The \"temp\" or \"temporary\" keyword.\n**   (6) tkTRIGGER   The \"trigger\" keyword.\n**   (7) tkEND       The \"end\" keyword.\n**\n** Whitespace never causes a state transition and is always ignored.\n** This means that a SQL string of all whitespace is invalid.\n**\n** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed\n** to recognize the end of a trigger can be omitted.  All we have to do\n** is look for a semicolon that is not part of an string or comment.\n*/\nSQLITE_API int sqlite3_complete(const char *zSql){\n  u8 state = 0;   /* Current state, using numbers defined in header comment */\n  u8 token;       /* Value of the next token */\n\n#ifndef SQLITE_OMIT_TRIGGER\n  /* A complex statement machine used to detect the end of a CREATE TRIGGER\n  ** statement.  This is the normal case.\n  */\n  static const u8 trans[8][8] = {\n                     /* Token:                                                */\n     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */\n     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },\n     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },\n     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },\n     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },\n     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },\n     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },\n     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },\n     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },\n  };\n#else\n  /* If triggers are not supported by this compile then the statement machine\n  ** used to detect the end of a statement is much simplier\n  */\n  static const u8 trans[3][3] = {\n                     /* Token:           */\n     /* State:       **  SEMI  WS  OTHER */\n     /* 0 INVALID: */ {    1,  0,     2, },\n     /* 1   START: */ {    1,  1,     2, },\n     /* 2  NORMAL: */ {    1,  2,     2, },\n  };\n#endif /* SQLITE_OMIT_TRIGGER */\n\n  while( *zSql ){\n    switch( *zSql ){\n      case ';': {  /* A semicolon */\n        token = tkSEMI;\n        break;\n      }\n      case ' ':\n      case '\\r':\n      case '\\t':\n      case '\\n':\n      case '\\f': {  /* White space is ignored */\n        token = tkWS;\n        break;\n      }\n      case '/': {   /* C-style comments */\n        if( zSql[1]!='*' ){\n          token = tkOTHER;\n          break;\n        }\n        zSql += 2;\n        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }\n        if( zSql[0]==0 ) return 0;\n        zSql++;\n        token = tkWS;\n        break;\n      }\n      case '-': {   /* SQL-style comments from \"--\" to end of line */\n        if( zSql[1]!='-' ){\n          token = tkOTHER;\n          break;\n        }\n        while( *zSql && *zSql!='\\n' ){ zSql++; }\n        if( *zSql==0 ) return state==1;\n        token = tkWS;\n        break;\n      }\n      case '[': {   /* Microsoft-style identifiers in [...] */\n        zSql++;\n        while( *zSql && *zSql!=']' ){ zSql++; }\n        if( *zSql==0 ) return 0;\n        token = tkOTHER;\n        break;\n      }\n      case '`':     /* Grave-accent quoted symbols used by MySQL */\n      case '\"':     /* single- and double-quoted strings */\n      case '\\'': {\n        int c = *zSql;\n        zSql++;\n        while( *zSql && *zSql!=c ){ zSql++; }\n        if( *zSql==0 ) return 0;\n        token = tkOTHER;\n        break;\n      }\n      default: {\n#ifdef SQLITE_EBCDIC\n        unsigned char c;\n#endif\n        if( IdChar((u8)*zSql) ){\n          /* Keywords and unquoted identifiers */\n          int nId;\n          for(nId=1; IdChar(zSql[nId]); nId++){}\n#ifdef SQLITE_OMIT_TRIGGER\n          token = tkOTHER;\n#else\n          switch( *zSql ){\n            case 'c': case 'C': {\n              if( nId==6 && sqlite3StrNICmp(zSql, \"create\", 6)==0 ){\n                token = tkCREATE;\n              }else{\n                token = tkOTHER;\n              }\n              break;\n            }\n            case 't': case 'T': {\n              if( nId==7 && sqlite3StrNICmp(zSql, \"trigger\", 7)==0 ){\n                token = tkTRIGGER;\n              }else if( nId==4 && sqlite3StrNICmp(zSql, \"temp\", 4)==0 ){\n                token = tkTEMP;\n              }else if( nId==9 && sqlite3StrNICmp(zSql, \"temporary\", 9)==0 ){\n                token = tkTEMP;\n              }else{\n                token = tkOTHER;\n              }\n              break;\n            }\n            case 'e':  case 'E': {\n              if( nId==3 && sqlite3StrNICmp(zSql, \"end\", 3)==0 ){\n                token = tkEND;\n              }else\n#ifndef SQLITE_OMIT_EXPLAIN\n              if( nId==7 && sqlite3StrNICmp(zSql, \"explain\", 7)==0 ){\n                token = tkEXPLAIN;\n              }else\n#endif\n              {\n                token = tkOTHER;\n              }\n              break;\n            }\n            default: {\n              token = tkOTHER;\n              break;\n            }\n          }\n#endif /* SQLITE_OMIT_TRIGGER */\n          zSql += nId-1;\n        }else{\n          /* Operators and special symbols */\n          token = tkOTHER;\n        }\n        break;\n      }\n    }\n    state = trans[state][token];\n    zSql++;\n  }\n  return state==1;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** This routine is the same as the sqlite3_complete() routine described\n** above, except that the parameter is required to be UTF-16 encoded, not\n** UTF-8.\n*/\nSQLITE_API int sqlite3_complete16(const void *zSql){\n  sqlite3_value *pVal;\n  char const *zSql8;\n  int rc = SQLITE_NOMEM;\n\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  pVal = sqlite3ValueNew(0);\n  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);\n  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);\n  if( zSql8 ){\n    rc = sqlite3_complete(zSql8);\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n  sqlite3ValueFree(pVal);\n  return sqlite3ApiExit(0, rc);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n#endif /* SQLITE_OMIT_COMPLETE */\n\n/************** End of complete.c ********************************************/\n/************** Begin file main.c ********************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Main file for the SQLite library.  The routines in this file\n** implement the programmer interface to the library.  Routines in\n** other files are for internal use by SQLite and should not be\n** accessed by users of the library.\n*/\n\n#ifdef SQLITE_ENABLE_FTS3\n/************** Include fts3.h in the middle of main.c ***********************/\n/************** Begin file fts3.h ********************************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.\n*/\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n/************** End of fts3.h ************************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n#ifdef SQLITE_ENABLE_RTREE\n/************** Include rtree.h in the middle of main.c **********************/\n/************** Begin file rtree.h *******************************************/\n/*\n** 2008 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.\n*/\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n/************** End of rtree.h ***********************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n#ifdef SQLITE_ENABLE_ICU\n/************** Include sqliteicu.h in the middle of main.c ******************/\n/************** Begin file sqliteicu.h ***************************************/\n/*\n** 2008 May 26\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This header file is used by programs that want to link against the\n** ICU extension.  All it does is declare the sqlite3IcuInit() interface.\n*/\n\n#if 0\nextern \"C\" {\n#endif  /* __cplusplus */\n\nSQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);\n\n#if 0\n}  /* extern \"C\" */\n#endif  /* __cplusplus */\n\n\n/************** End of sqliteicu.h *******************************************/\n/************** Continuing where we left off in main.c ***********************/\n#endif\n\n#ifndef SQLITE_AMALGAMATION\n/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant\n** contains the text of SQLITE_VERSION macro. \n*/\nSQLITE_API const char sqlite3_version[] = SQLITE_VERSION;\n#endif\n\n/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns\n** a pointer to the to the sqlite3_version[] string constant. \n*/\nSQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }\n\n/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a\n** pointer to a string constant whose value is the same as the\n** SQLITE_SOURCE_ID C preprocessor macro. \n*/\nSQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }\n\n/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function\n** returns an integer equal to SQLITE_VERSION_NUMBER.\n*/\nSQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }\n\n/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns\n** zero if and only if SQLite was compiled with mutexing code omitted due to\n** the SQLITE_THREADSAFE compile-time option being set to 0.\n*/\nSQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }\n\n#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)\n/*\n** If the following function pointer is not NULL and if\n** SQLITE_ENABLE_IOTRACE is enabled, then messages describing\n** I/O active are written using this function.  These messages\n** are intended for debugging activity only.\n*/\nSQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;\n#endif\n\n/*\n** If the following global variable points to a string which is the\n** name of a directory, then that directory will be used to store\n** temporary files.\n**\n** See also the \"PRAGMA temp_store_directory\" SQL command.\n*/\nSQLITE_API char *sqlite3_temp_directory = 0;\n\n/*\n** If the following global variable points to a string which is the\n** name of a directory, then that directory will be used to store\n** all database files specified with a relative pathname.\n**\n** See also the \"PRAGMA data_store_directory\" SQL command.\n*/\nSQLITE_API char *sqlite3_data_directory = 0;\n\n/*\n** Initialize SQLite.  \n**\n** This routine must be called to initialize the memory allocation,\n** VFS, and mutex subsystems prior to doing any serious work with\n** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT\n** this routine will be called automatically by key routines such as\n** sqlite3_open().  \n**\n** This routine is a no-op except on its very first call for the process,\n** or for the first call after a call to sqlite3_shutdown.\n**\n** The first thread to call this routine runs the initialization to\n** completion.  If subsequent threads call this routine before the first\n** thread has finished the initialization process, then the subsequent\n** threads must block until the first thread finishes with the initialization.\n**\n** The first thread might call this routine recursively.  Recursive\n** calls to this routine should not block, of course.  Otherwise the\n** initialization process would never complete.\n**\n** Let X be the first thread to enter this routine.  Let Y be some other\n** thread.  Then while the initial invocation of this routine by X is\n** incomplete, it is required that:\n**\n**    *  Calls to this routine from Y must block until the outer-most\n**       call by X completes.\n**\n**    *  Recursive calls to this routine from thread X return immediately\n**       without blocking.\n*/\nSQLITE_API int sqlite3_initialize(void){\n  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */\n  int rc;                                      /* Result code */\n\n#ifdef SQLITE_OMIT_WSD\n  rc = sqlite3_wsd_init(4096, 24);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n#endif\n\n  /* If SQLite is already completely initialized, then this call\n  ** to sqlite3_initialize() should be a no-op.  But the initialization\n  ** must be complete.  So isInit must not be set until the very end\n  ** of this routine.\n  */\n  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;\n\n  /* Make sure the mutex subsystem is initialized.  If unable to \n  ** initialize the mutex subsystem, return early with the error.\n  ** If the system is so sick that we are unable to allocate a mutex,\n  ** there is not much SQLite is going to be able to do.\n  **\n  ** The mutex subsystem must take care of serializing its own\n  ** initialization.\n  */\n  rc = sqlite3MutexInit();\n  if( rc ) return rc;\n\n  /* Initialize the malloc() system and the recursive pInitMutex mutex.\n  ** This operation is protected by the STATIC_MASTER mutex.  Note that\n  ** MutexAlloc() is called for a static mutex prior to initializing the\n  ** malloc subsystem - this implies that the allocation of a static\n  ** mutex must not require support from the malloc subsystem.\n  */\n  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )\n  sqlite3_mutex_enter(pMaster);\n  sqlite3GlobalConfig.isMutexInit = 1;\n  if( !sqlite3GlobalConfig.isMallocInit ){\n    rc = sqlite3MallocInit();\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3GlobalConfig.isMallocInit = 1;\n    if( !sqlite3GlobalConfig.pInitMutex ){\n      sqlite3GlobalConfig.pInitMutex =\n           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);\n      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){\n        rc = SQLITE_NOMEM;\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3GlobalConfig.nRefInitMutex++;\n  }\n  sqlite3_mutex_leave(pMaster);\n\n  /* If rc is not SQLITE_OK at this point, then either the malloc\n  ** subsystem could not be initialized or the system failed to allocate\n  ** the pInitMutex mutex. Return an error in either case.  */\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Do the rest of the initialization under the recursive mutex so\n  ** that we will be able to handle recursive calls into\n  ** sqlite3_initialize().  The recursive calls normally come through\n  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other\n  ** recursive calls might also be possible.\n  **\n  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls\n  ** to the xInit method, so the xInit method need not be threadsafe.\n  **\n  ** The following mutex is what serializes access to the appdef pcache xInit\n  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the\n  ** call to sqlite3PcacheInitialize().\n  */\n  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);\n  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){\n    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);\n    sqlite3GlobalConfig.inProgress = 1;\n    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));\n    sqlite3RegisterGlobalFunctions();\n    if( sqlite3GlobalConfig.isPCacheInit==0 ){\n      rc = sqlite3PcacheInitialize();\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3GlobalConfig.isPCacheInit = 1;\n      rc = sqlite3OsInit();\n    }\n    if( rc==SQLITE_OK ){\n      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, \n          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);\n      sqlite3GlobalConfig.isInit = 1;\n    }\n    sqlite3GlobalConfig.inProgress = 0;\n  }\n  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);\n\n  /* Go back under the static mutex and clean up the recursive\n  ** mutex to prevent a resource leak.\n  */\n  sqlite3_mutex_enter(pMaster);\n  sqlite3GlobalConfig.nRefInitMutex--;\n  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){\n    assert( sqlite3GlobalConfig.nRefInitMutex==0 );\n    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);\n    sqlite3GlobalConfig.pInitMutex = 0;\n  }\n  sqlite3_mutex_leave(pMaster);\n\n  /* The following is just a sanity check to make sure SQLite has\n  ** been compiled correctly.  It is important to run this code, but\n  ** we don't want to run it too often and soak up CPU cycles for no\n  ** reason.  So we run it once during initialization.\n  */\n#ifndef NDEBUG\n#ifndef SQLITE_OMIT_FLOATING_POINT\n  /* This section of code's only \"output\" is via assert() statements. */\n  if ( rc==SQLITE_OK ){\n    u64 x = (((u64)1)<<63)-1;\n    double y;\n    assert(sizeof(x)==8);\n    assert(sizeof(x)==sizeof(y));\n    memcpy(&y, &x, 8);\n    assert( sqlite3IsNaN(y) );\n  }\n#endif\n#endif\n\n  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT\n  ** compile-time option.\n  */\n#ifdef SQLITE_EXTRA_INIT\n  if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){\n    int SQLITE_EXTRA_INIT(const char*);\n    rc = SQLITE_EXTRA_INIT(0);\n  }\n#endif\n\n  return rc;\n}\n\n/*\n** Undo the effects of sqlite3_initialize().  Must not be called while\n** there are outstanding database connections or memory allocations or\n** while any part of SQLite is otherwise in use in any thread.  This\n** routine is not threadsafe.  But it is safe to invoke this routine\n** on when SQLite is already shut down.  If SQLite is already shut down\n** when this routine is invoked, then this routine is a harmless no-op.\n*/\nSQLITE_API int sqlite3_shutdown(void){\n  if( sqlite3GlobalConfig.isInit ){\n#ifdef SQLITE_EXTRA_SHUTDOWN\n    void SQLITE_EXTRA_SHUTDOWN(void);\n    SQLITE_EXTRA_SHUTDOWN();\n#endif\n    sqlite3_os_end();\n    sqlite3_reset_auto_extension();\n    sqlite3GlobalConfig.isInit = 0;\n  }\n  if( sqlite3GlobalConfig.isPCacheInit ){\n    sqlite3PcacheShutdown();\n    sqlite3GlobalConfig.isPCacheInit = 0;\n  }\n  if( sqlite3GlobalConfig.isMallocInit ){\n    sqlite3MallocEnd();\n    sqlite3GlobalConfig.isMallocInit = 0;\n\n#ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES\n    /* The heap subsystem has now been shutdown and these values are supposed\n    ** to be NULL or point to memory that was obtained from sqlite3_malloc(),\n    ** which would rely on that heap subsystem; therefore, make sure these\n    ** values cannot refer to heap memory that was just invalidated when the\n    ** heap subsystem was shutdown.  This is only done if the current call to\n    ** this function resulted in the heap subsystem actually being shutdown.\n    */\n    sqlite3_data_directory = 0;\n    sqlite3_temp_directory = 0;\n#endif\n  }\n  if( sqlite3GlobalConfig.isMutexInit ){\n    sqlite3MutexEnd();\n    sqlite3GlobalConfig.isMutexInit = 0;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This API allows applications to modify the global configuration of\n** the SQLite library at run-time.\n**\n** This routine should only be called when there are no outstanding\n** database connections or memory allocations.  This routine is not\n** threadsafe.  Failure to heed these warnings can lead to unpredictable\n** behavior.\n*/\nSQLITE_API int sqlite3_config(int op, ...){\n  va_list ap;\n  int rc = SQLITE_OK;\n\n  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while\n  ** the SQLite library is in use. */\n  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;\n\n  va_start(ap, op);\n  switch( op ){\n\n    /* Mutex configuration options are only available in a threadsafe\n    ** compile. \n    */\n#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0\n    case SQLITE_CONFIG_SINGLETHREAD: {\n      /* Disable all mutexing */\n      sqlite3GlobalConfig.bCoreMutex = 0;\n      sqlite3GlobalConfig.bFullMutex = 0;\n      break;\n    }\n    case SQLITE_CONFIG_MULTITHREAD: {\n      /* Disable mutexing of database connections */\n      /* Enable mutexing of core data structures */\n      sqlite3GlobalConfig.bCoreMutex = 1;\n      sqlite3GlobalConfig.bFullMutex = 0;\n      break;\n    }\n    case SQLITE_CONFIG_SERIALIZED: {\n      /* Enable all mutexing */\n      sqlite3GlobalConfig.bCoreMutex = 1;\n      sqlite3GlobalConfig.bFullMutex = 1;\n      break;\n    }\n    case SQLITE_CONFIG_MUTEX: {\n      /* Specify an alternative mutex implementation */\n      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);\n      break;\n    }\n    case SQLITE_CONFIG_GETMUTEX: {\n      /* Retrieve the current mutex implementation */\n      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;\n      break;\n    }\n#endif\n\n\n    case SQLITE_CONFIG_MALLOC: {\n      /* Specify an alternative malloc implementation */\n      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);\n      break;\n    }\n    case SQLITE_CONFIG_GETMALLOC: {\n      /* Retrieve the current malloc() implementation */\n      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();\n      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;\n      break;\n    }\n    case SQLITE_CONFIG_MEMSTATUS: {\n      /* Enable or disable the malloc status collection */\n      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);\n      break;\n    }\n    case SQLITE_CONFIG_SCRATCH: {\n      /* Designate a buffer for scratch memory space */\n      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);\n      sqlite3GlobalConfig.szScratch = va_arg(ap, int);\n      sqlite3GlobalConfig.nScratch = va_arg(ap, int);\n      break;\n    }\n    case SQLITE_CONFIG_PAGECACHE: {\n      /* Designate a buffer for page cache memory space */\n      sqlite3GlobalConfig.pPage = va_arg(ap, void*);\n      sqlite3GlobalConfig.szPage = va_arg(ap, int);\n      sqlite3GlobalConfig.nPage = va_arg(ap, int);\n      break;\n    }\n\n    case SQLITE_CONFIG_PCACHE: {\n      /* no-op */\n      break;\n    }\n    case SQLITE_CONFIG_GETPCACHE: {\n      /* now an error */\n      rc = SQLITE_ERROR;\n      break;\n    }\n\n    case SQLITE_CONFIG_PCACHE2: {\n      /* Specify an alternative page cache implementation */\n      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);\n      break;\n    }\n    case SQLITE_CONFIG_GETPCACHE2: {\n      if( sqlite3GlobalConfig.pcache2.xInit==0 ){\n        sqlite3PCacheSetDefault();\n      }\n      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;\n      break;\n    }\n\n#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)\n    case SQLITE_CONFIG_HEAP: {\n      /* Designate a buffer for heap memory space */\n      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);\n      sqlite3GlobalConfig.nHeap = va_arg(ap, int);\n      sqlite3GlobalConfig.mnReq = va_arg(ap, int);\n\n      if( sqlite3GlobalConfig.mnReq<1 ){\n        sqlite3GlobalConfig.mnReq = 1;\n      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){\n        /* cap min request size at 2^12 */\n        sqlite3GlobalConfig.mnReq = (1<<12);\n      }\n\n      if( sqlite3GlobalConfig.pHeap==0 ){\n        /* If the heap pointer is NULL, then restore the malloc implementation\n        ** back to NULL pointers too.  This will cause the malloc to go\n        ** back to its default implementation when sqlite3_initialize() is\n        ** run.\n        */\n        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));\n      }else{\n        /* The heap pointer is not NULL, then install one of the\n        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor\n        ** ENABLE_MEMSYS5 is defined, return an error.\n        */\n#ifdef SQLITE_ENABLE_MEMSYS3\n        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();\n#endif\n#ifdef SQLITE_ENABLE_MEMSYS5\n        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();\n#endif\n      }\n      break;\n    }\n#endif\n\n    case SQLITE_CONFIG_LOOKASIDE: {\n      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);\n      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);\n      break;\n    }\n    \n    /* Record a pointer to the logger funcction and its first argument.\n    ** The default is NULL.  Logging is disabled if the function pointer is\n    ** NULL.\n    */\n    case SQLITE_CONFIG_LOG: {\n      /* MSVC is picky about pulling func ptrs from va lists.\n      ** http://support.microsoft.com/kb/47961\n      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));\n      */\n      typedef void(*LOGFUNC_t)(void*,int,const char*);\n      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);\n      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);\n      break;\n    }\n\n    case SQLITE_CONFIG_URI: {\n      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);\n      break;\n    }\n\n    default: {\n      rc = SQLITE_ERROR;\n      break;\n    }\n  }\n  va_end(ap);\n  return rc;\n}\n\n/*\n** Set up the lookaside buffers for a database connection.\n** Return SQLITE_OK on success.  \n** If lookaside is already active, return SQLITE_BUSY.\n**\n** The sz parameter is the number of bytes in each lookaside slot.\n** The cnt parameter is the number of slots.  If pStart is NULL the\n** space for the lookaside memory is obtained from sqlite3_malloc().\n** If pStart is not NULL then it is sz*cnt bytes of memory to use for\n** the lookaside memory.\n*/\nstatic int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){\n  void *pStart;\n  if( db->lookaside.nOut ){\n    return SQLITE_BUSY;\n  }\n  /* Free any existing lookaside buffer for this handle before\n  ** allocating a new one so we don't have to have space for \n  ** both at the same time.\n  */\n  if( db->lookaside.bMalloced ){\n    sqlite3_free(db->lookaside.pStart);\n  }\n  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger\n  ** than a pointer to be useful.\n  */\n  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */\n  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;\n  if( cnt<0 ) cnt = 0;\n  if( sz==0 || cnt==0 ){\n    sz = 0;\n    pStart = 0;\n  }else if( pBuf==0 ){\n    sqlite3BeginBenignMalloc();\n    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */\n    sqlite3EndBenignMalloc();\n    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;\n  }else{\n    pStart = pBuf;\n  }\n  db->lookaside.pStart = pStart;\n  db->lookaside.pFree = 0;\n  db->lookaside.sz = (u16)sz;\n  if( pStart ){\n    int i;\n    LookasideSlot *p;\n    assert( sz > (int)sizeof(LookasideSlot*) );\n    p = (LookasideSlot*)pStart;\n    for(i=cnt-1; i>=0; i--){\n      p->pNext = db->lookaside.pFree;\n      db->lookaside.pFree = p;\n      p = (LookasideSlot*)&((u8*)p)[sz];\n    }\n    db->lookaside.pEnd = p;\n    db->lookaside.bEnabled = 1;\n    db->lookaside.bMalloced = pBuf==0 ?1:0;\n  }else{\n    db->lookaside.pEnd = 0;\n    db->lookaside.bEnabled = 0;\n    db->lookaside.bMalloced = 0;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Return the mutex associated with a database connection.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){\n  return db->mutex;\n}\n\n/*\n** Free up as much memory as we can from the given database\n** connection.\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3 *db){\n  int i;\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Btree *pBt = db->aDb[i].pBt;\n    if( pBt ){\n      Pager *pPager = sqlite3BtreePager(pBt);\n      sqlite3PagerShrink(pPager);\n    }\n  }\n  sqlite3BtreeLeaveAll(db);\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Configuration settings for an individual database connection\n*/\nSQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){\n  va_list ap;\n  int rc;\n  va_start(ap, op);\n  switch( op ){\n    case SQLITE_DBCONFIG_LOOKASIDE: {\n      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */\n      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */\n      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */\n      rc = setupLookaside(db, pBuf, sz, cnt);\n      break;\n    }\n    default: {\n      static const struct {\n        int op;      /* The opcode */\n        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */\n      } aFlagOp[] = {\n        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },\n        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },\n      };\n      unsigned int i;\n      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */\n      for(i=0; i<ArraySize(aFlagOp); i++){\n        if( aFlagOp[i].op==op ){\n          int onoff = va_arg(ap, int);\n          int *pRes = va_arg(ap, int*);\n          int oldFlags = db->flags;\n          if( onoff>0 ){\n            db->flags |= aFlagOp[i].mask;\n          }else if( onoff==0 ){\n            db->flags &= ~aFlagOp[i].mask;\n          }\n          if( oldFlags!=db->flags ){\n            sqlite3ExpirePreparedStatements(db);\n          }\n          if( pRes ){\n            *pRes = (db->flags & aFlagOp[i].mask)!=0;\n          }\n          rc = SQLITE_OK;\n          break;\n        }\n      }\n      break;\n    }\n  }\n  va_end(ap);\n  return rc;\n}\n\n\n/*\n** Return true if the buffer z[0..n-1] contains all spaces.\n*/\nstatic int allSpaces(const char *z, int n){\n  while( n>0 && z[n-1]==' ' ){ n--; }\n  return n==0;\n}\n\n/*\n** This is the default collating function named \"BINARY\" which is always\n** available.\n**\n** If the padFlag argument is not NULL then space padding at the end\n** of strings is ignored.  This implements the RTRIM collation.\n*/\nstatic int binCollFunc(\n  void *padFlag,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  int rc, n;\n  n = nKey1<nKey2 ? nKey1 : nKey2;\n  rc = memcmp(pKey1, pKey2, n);\n  if( rc==0 ){\n    if( padFlag\n     && allSpaces(((char*)pKey1)+n, nKey1-n)\n     && allSpaces(((char*)pKey2)+n, nKey2-n)\n    ){\n      /* Leave rc unchanged at 0 */\n    }else{\n      rc = nKey1 - nKey2;\n    }\n  }\n  return rc;\n}\n\n/*\n** Another built-in collating sequence: NOCASE. \n**\n** This collating sequence is intended to be used for \"case independant\n** comparison\". SQLite's knowledge of upper and lower case equivalents\n** extends only to the 26 characters used in the English language.\n**\n** At the moment there is only a UTF-8 implementation.\n*/\nstatic int nocaseCollatingFunc(\n  void *NotUsed,\n  int nKey1, const void *pKey1,\n  int nKey2, const void *pKey2\n){\n  int r = sqlite3StrNICmp(\n      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);\n  UNUSED_PARAMETER(NotUsed);\n  if( 0==r ){\n    r = nKey1-nKey2;\n  }\n  return r;\n}\n\n/*\n** Return the ROWID of the most recent insert\n*/\nSQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){\n  return db->lastRowid;\n}\n\n/*\n** Return the number of changes in the most recent call to sqlite3_exec().\n*/\nSQLITE_API int sqlite3_changes(sqlite3 *db){\n  return db->nChange;\n}\n\n/*\n** Return the number of changes since the database handle was opened.\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3 *db){\n  return db->nTotalChange;\n}\n\n/*\n** Close all open savepoints. This function only manipulates fields of the\n** database handle object, it does not close any savepoints that may be open\n** at the b-tree/pager level.\n*/\nSQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){\n  while( db->pSavepoint ){\n    Savepoint *pTmp = db->pSavepoint;\n    db->pSavepoint = pTmp->pNext;\n    sqlite3DbFree(db, pTmp);\n  }\n  db->nSavepoint = 0;\n  db->nStatement = 0;\n  db->isTransactionSavepoint = 0;\n}\n\n/*\n** Invoke the destructor function associated with FuncDef p, if any. Except,\n** if this is not the last copy of the function, do not invoke it. Multiple\n** copies of a single function are created when create_function() is called\n** with SQLITE_ANY as the encoding.\n*/\nstatic void functionDestroy(sqlite3 *db, FuncDef *p){\n  FuncDestructor *pDestructor = p->pDestructor;\n  if( pDestructor ){\n    pDestructor->nRef--;\n    if( pDestructor->nRef==0 ){\n      pDestructor->xDestroy(pDestructor->pUserData);\n      sqlite3DbFree(db, pDestructor);\n    }\n  }\n}\n\n/*\n** Disconnect all sqlite3_vtab objects that belong to database connection\n** db. This is called when db is being closed.\n*/\nstatic void disconnectAllVtab(sqlite3 *db){\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  int i;\n  sqlite3BtreeEnterAll(db);\n  for(i=0; i<db->nDb; i++){\n    Schema *pSchema = db->aDb[i].pSchema;\n    if( db->aDb[i].pSchema ){\n      HashElem *p;\n      for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){\n        Table *pTab = (Table *)sqliteHashData(p);\n        if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);\n      }\n    }\n  }\n  sqlite3BtreeLeaveAll(db);\n#else\n  UNUSED_PARAMETER(db);\n#endif\n}\n\n/*\n** Return TRUE if database connection db has unfinalized prepared\n** statements or unfinished sqlite3_backup objects.  \n*/\nstatic int connectionIsBusy(sqlite3 *db){\n  int j;\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( db->pVdbe ) return 1;\n  for(j=0; j<db->nDb; j++){\n    Btree *pBt = db->aDb[j].pBt;\n    if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;\n  }\n  return 0;\n}\n\n/*\n** Close an existing SQLite database\n*/\nstatic int sqlite3Close(sqlite3 *db, int forceZombie){\n  if( !db ){\n    return SQLITE_OK;\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  sqlite3_mutex_enter(db->mutex);\n\n  /* Force xDisconnect calls on all virtual tables */\n  disconnectAllVtab(db);\n\n  /* If a transaction is open, the disconnectAllVtab() call above\n  ** will not have called the xDisconnect() method on any virtual\n  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()\n  ** call will do so. We need to do this before the check for active\n  ** SQL statements below, as the v-table implementation may be storing\n  ** some prepared statements internally.\n  */\n  sqlite3VtabRollback(db);\n\n  /* Legacy behavior (sqlite3_close() behavior) is to return\n  ** SQLITE_BUSY if the connection can not be closed immediately.\n  */\n  if( !forceZombie && connectionIsBusy(db) ){\n    sqlite3Error(db, SQLITE_BUSY, \"unable to close due to unfinalized \"\n       \"statements or unfinished backups\");\n    sqlite3_mutex_leave(db->mutex);\n    return SQLITE_BUSY;\n  }\n\n  /* Convert the connection into a zombie and then close it.\n  */\n  db->magic = SQLITE_MAGIC_ZOMBIE;\n  sqlite3LeaveMutexAndCloseZombie(db);\n  return SQLITE_OK;\n}\n\n/*\n** Two variations on the public interface for closing a database\n** connection. The sqlite3_close() version returns SQLITE_BUSY and\n** leaves the connection option if there are unfinalized prepared\n** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()\n** version forces the connection to become a zombie if there are\n** unclosed resources, and arranges for deallocation when the last\n** prepare statement or sqlite3_backup closes.\n*/\nSQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }\nSQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }\n\n\n/*\n** Close the mutex on database connection db.\n**\n** Furthermore, if database connection db is a zombie (meaning that there\n** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and\n** every sqlite3_stmt has now been finalized and every sqlite3_backup has\n** finished, then free all resources.\n*/\nSQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){\n  HashElem *i;                    /* Hash table iterator */\n  int j;\n\n  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects\n  ** or if the connection has not yet been closed by sqlite3_close_v2(),\n  ** then just leave the mutex and return.\n  */\n  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){\n    sqlite3_mutex_leave(db->mutex);\n    return;\n  }\n\n  /* If we reach this point, it means that the database connection has\n  ** closed all sqlite3_stmt and sqlite3_backup objects and has been\n  ** pased to sqlite3_close (meaning that it is a zombie).  Therefore,\n  ** go ahead and free all resources.\n  */\n\n  /* Free any outstanding Savepoint structures. */\n  sqlite3CloseSavepoints(db);\n\n  /* Close all database connections */\n  for(j=0; j<db->nDb; j++){\n    struct Db *pDb = &db->aDb[j];\n    if( pDb->pBt ){\n      sqlite3BtreeClose(pDb->pBt);\n      pDb->pBt = 0;\n      if( j!=1 ){\n        pDb->pSchema = 0;\n      }\n    }\n  }\n  /* Clear the TEMP schema separately and last */\n  if( db->aDb[1].pSchema ){\n    sqlite3SchemaClear(db->aDb[1].pSchema);\n  }\n  sqlite3VtabUnlockList(db);\n\n  /* Free up the array of auxiliary databases */\n  sqlite3CollapseDatabaseArray(db);\n  assert( db->nDb<=2 );\n  assert( db->aDb==db->aDbStatic );\n\n  /* Tell the code in notify.c that the connection no longer holds any\n  ** locks and does not require any further unlock-notify callbacks.\n  */\n  sqlite3ConnectionClosed(db);\n\n  for(j=0; j<ArraySize(db->aFunc.a); j++){\n    FuncDef *pNext, *pHash, *p;\n    for(p=db->aFunc.a[j]; p; p=pHash){\n      pHash = p->pHash;\n      while( p ){\n        functionDestroy(db, p);\n        pNext = p->pNext;\n        sqlite3DbFree(db, p);\n        p = pNext;\n      }\n    }\n  }\n  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){\n    CollSeq *pColl = (CollSeq *)sqliteHashData(i);\n    /* Invoke any destructors registered for collation sequence user data. */\n    for(j=0; j<3; j++){\n      if( pColl[j].xDel ){\n        pColl[j].xDel(pColl[j].pUser);\n      }\n    }\n    sqlite3DbFree(db, pColl);\n  }\n  sqlite3HashClear(&db->aCollSeq);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){\n    Module *pMod = (Module *)sqliteHashData(i);\n    if( pMod->xDestroy ){\n      pMod->xDestroy(pMod->pAux);\n    }\n    sqlite3DbFree(db, pMod);\n  }\n  sqlite3HashClear(&db->aModule);\n#endif\n\n  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */\n  if( db->pErr ){\n    sqlite3ValueFree(db->pErr);\n  }\n  sqlite3CloseExtensions(db);\n\n  db->magic = SQLITE_MAGIC_ERROR;\n\n  /* The temp-database schema is allocated differently from the other schema\n  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).\n  ** So it needs to be freed here. Todo: Why not roll the temp schema into\n  ** the same sqliteMalloc() as the one that allocates the database \n  ** structure?\n  */\n  sqlite3DbFree(db, db->aDb[1].pSchema);\n  sqlite3_mutex_leave(db->mutex);\n  db->magic = SQLITE_MAGIC_CLOSED;\n  sqlite3_mutex_free(db->mutex);\n  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */\n  if( db->lookaside.bMalloced ){\n    sqlite3_free(db->lookaside.pStart);\n  }\n  sqlite3_free(db);\n}\n\n/*\n** Rollback all database files.  If tripCode is not SQLITE_OK, then\n** any open cursors are invalidated (\"tripped\" - as in \"tripping a circuit\n** breaker\") and made to return tripCode if there are any further\n** attempts to use that cursor.\n*/\nSQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){\n  int i;\n  int inTrans = 0;\n  assert( sqlite3_mutex_held(db->mutex) );\n  sqlite3BeginBenignMalloc();\n  for(i=0; i<db->nDb; i++){\n    Btree *p = db->aDb[i].pBt;\n    if( p ){\n      if( sqlite3BtreeIsInTrans(p) ){\n        inTrans = 1;\n      }\n      sqlite3BtreeRollback(p, tripCode);\n      db->aDb[i].inTrans = 0;\n    }\n  }\n  sqlite3VtabRollback(db);\n  sqlite3EndBenignMalloc();\n\n  if( db->flags&SQLITE_InternChanges ){\n    sqlite3ExpirePreparedStatements(db);\n    sqlite3ResetAllSchemasOfConnection(db);\n  }\n\n  /* Any deferred constraint violations have now been resolved. */\n  db->nDeferredCons = 0;\n\n  /* If one has been configured, invoke the rollback-hook callback */\n  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){\n    db->xRollbackCallback(db->pRollbackArg);\n  }\n}\n\n/*\n** Return a static string that describes the kind of error specified in the\n** argument.\n*/\nSQLITE_PRIVATE const char *sqlite3ErrStr(int rc){\n  static const char* const aMsg[] = {\n    /* SQLITE_OK          */ \"not an error\",\n    /* SQLITE_ERROR       */ \"SQL logic error or missing database\",\n    /* SQLITE_INTERNAL    */ 0,\n    /* SQLITE_PERM        */ \"access permission denied\",\n    /* SQLITE_ABORT       */ \"callback requested query abort\",\n    /* SQLITE_BUSY        */ \"database is locked\",\n    /* SQLITE_LOCKED      */ \"database table is locked\",\n    /* SQLITE_NOMEM       */ \"out of memory\",\n    /* SQLITE_READONLY    */ \"attempt to write a readonly database\",\n    /* SQLITE_INTERRUPT   */ \"interrupted\",\n    /* SQLITE_IOERR       */ \"disk I/O error\",\n    /* SQLITE_CORRUPT     */ \"database disk image is malformed\",\n    /* SQLITE_NOTFOUND    */ \"unknown operation\",\n    /* SQLITE_FULL        */ \"database or disk is full\",\n    /* SQLITE_CANTOPEN    */ \"unable to open database file\",\n    /* SQLITE_PROTOCOL    */ \"locking protocol\",\n    /* SQLITE_EMPTY       */ \"table contains no data\",\n    /* SQLITE_SCHEMA      */ \"database schema has changed\",\n    /* SQLITE_TOOBIG      */ \"string or blob too big\",\n    /* SQLITE_CONSTRAINT  */ \"constraint failed\",\n    /* SQLITE_MISMATCH    */ \"datatype mismatch\",\n    /* SQLITE_MISUSE      */ \"library routine called out of sequence\",\n    /* SQLITE_NOLFS       */ \"large file support is disabled\",\n    /* SQLITE_AUTH        */ \"authorization denied\",\n    /* SQLITE_FORMAT      */ \"auxiliary database format error\",\n    /* SQLITE_RANGE       */ \"bind or column index out of range\",\n    /* SQLITE_NOTADB      */ \"file is encrypted or is not a database\",\n  };\n  const char *zErr = \"unknown error\";\n  switch( rc ){\n    case SQLITE_ABORT_ROLLBACK: {\n      zErr = \"abort due to ROLLBACK\";\n      break;\n    }\n    default: {\n      rc &= 0xff;\n      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){\n        zErr = aMsg[rc];\n      }\n      break;\n    }\n  }\n  return zErr;\n}\n\n/*\n** This routine implements a busy callback that sleeps and tries\n** again until a timeout value is reached.  The timeout value is\n** an integer number of milliseconds passed in as the first\n** argument.\n*/\nstatic int sqliteDefaultBusyCallback(\n void *ptr,               /* Database connection */\n int count                /* Number of times table has been busy */\n){\n#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)\n  static const u8 delays[] =\n     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };\n  static const u8 totals[] =\n     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };\n# define NDELAY ArraySize(delays)\n  sqlite3 *db = (sqlite3 *)ptr;\n  int timeout = db->busyTimeout;\n  int delay, prior;\n\n  assert( count>=0 );\n  if( count < NDELAY ){\n    delay = delays[count];\n    prior = totals[count];\n  }else{\n    delay = delays[NDELAY-1];\n    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));\n  }\n  if( prior + delay > timeout ){\n    delay = timeout - prior;\n    if( delay<=0 ) return 0;\n  }\n  sqlite3OsSleep(db->pVfs, delay*1000);\n  return 1;\n#else\n  sqlite3 *db = (sqlite3 *)ptr;\n  int timeout = ((sqlite3 *)ptr)->busyTimeout;\n  if( (count+1)*1000 > timeout ){\n    return 0;\n  }\n  sqlite3OsSleep(db->pVfs, 1000000);\n  return 1;\n#endif\n}\n\n/*\n** Invoke the given busy handler.\n**\n** This routine is called when an operation failed with a lock.\n** If this routine returns non-zero, the lock is retried.  If it\n** returns 0, the operation aborts with an SQLITE_BUSY error.\n*/\nSQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){\n  int rc;\n  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;\n  rc = p->xFunc(p->pArg, p->nBusy);\n  if( rc==0 ){\n    p->nBusy = -1;\n  }else{\n    p->nBusy++;\n  }\n  return rc; \n}\n\n/*\n** This routine sets the busy callback for an Sqlite database to the\n** given callback function with the given argument.\n*/\nSQLITE_API int sqlite3_busy_handler(\n  sqlite3 *db,\n  int (*xBusy)(void*,int),\n  void *pArg\n){\n  sqlite3_mutex_enter(db->mutex);\n  db->busyHandler.xFunc = xBusy;\n  db->busyHandler.pArg = pArg;\n  db->busyHandler.nBusy = 0;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_PROGRESS_CALLBACK\n/*\n** This routine sets the progress callback for an Sqlite database to the\n** given callback function with the given argument. The progress callback will\n** be invoked every nOps opcodes.\n*/\nSQLITE_API void sqlite3_progress_handler(\n  sqlite3 *db, \n  int nOps,\n  int (*xProgress)(void*), \n  void *pArg\n){\n  sqlite3_mutex_enter(db->mutex);\n  if( nOps>0 ){\n    db->xProgress = xProgress;\n    db->nProgressOps = nOps;\n    db->pProgressArg = pArg;\n  }else{\n    db->xProgress = 0;\n    db->nProgressOps = 0;\n    db->pProgressArg = 0;\n  }\n  sqlite3_mutex_leave(db->mutex);\n}\n#endif\n\n\n/*\n** This routine installs a default busy handler that waits for the\n** specified number of milliseconds before returning 0.\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){\n  if( ms>0 ){\n    db->busyTimeout = ms;\n    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);\n  }else{\n    sqlite3_busy_handler(db, 0, 0);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Cause any pending operation to stop at its earliest opportunity.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3 *db){\n  db->u1.isInterrupted = 1;\n}\n\n\n/*\n** This function is exactly the same as sqlite3_create_function(), except\n** that it is designed to be called by internal code. The difference is\n** that if a malloc() fails in sqlite3_create_function(), an error code\n** is returned and the mallocFailed flag cleared. \n*/\nSQLITE_PRIVATE int sqlite3CreateFunc(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int enc,\n  void *pUserData,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*),\n  FuncDestructor *pDestructor\n){\n  FuncDef *p;\n  int nName;\n\n  assert( sqlite3_mutex_held(db->mutex) );\n  if( zFunctionName==0 ||\n      (xFunc && (xFinal || xStep)) || \n      (!xFunc && (xFinal && !xStep)) ||\n      (!xFunc && (!xFinal && xStep)) ||\n      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||\n      (255<(nName = sqlite3Strlen30( zFunctionName))) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  \n#ifndef SQLITE_OMIT_UTF16\n  /* If SQLITE_UTF16 is specified as the encoding type, transform this\n  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the\n  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.\n  **\n  ** If SQLITE_ANY is specified, add three versions of the function\n  ** to the hash table.\n  */\n  if( enc==SQLITE_UTF16 ){\n    enc = SQLITE_UTF16NATIVE;\n  }else if( enc==SQLITE_ANY ){\n    int rc;\n    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,\n         pUserData, xFunc, xStep, xFinal, pDestructor);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,\n          pUserData, xFunc, xStep, xFinal, pDestructor);\n    }\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    enc = SQLITE_UTF16BE;\n  }\n#else\n  enc = SQLITE_UTF8;\n#endif\n  \n  /* Check if an existing function is being overridden or deleted. If so,\n  ** and there are active VMs, then return SQLITE_BUSY. If a function\n  ** is being overridden/deleted but there are no active VMs, allow the\n  ** operation to continue but invalidate all precompiled statements.\n  */\n  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);\n  if( p && p->iPrefEnc==enc && p->nArg==nArg ){\n    if( db->activeVdbeCnt ){\n      sqlite3Error(db, SQLITE_BUSY, \n        \"unable to delete/modify user-function due to active statements\");\n      assert( !db->mallocFailed );\n      return SQLITE_BUSY;\n    }else{\n      sqlite3ExpirePreparedStatements(db);\n    }\n  }\n\n  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);\n  assert(p || db->mallocFailed);\n  if( !p ){\n    return SQLITE_NOMEM;\n  }\n\n  /* If an older version of the function with a configured destructor is\n  ** being replaced invoke the destructor function here. */\n  functionDestroy(db, p);\n\n  if( pDestructor ){\n    pDestructor->nRef++;\n  }\n  p->pDestructor = pDestructor;\n  p->flags = 0;\n  p->xFunc = xFunc;\n  p->xStep = xStep;\n  p->xFinalize = xFinal;\n  p->pUserData = pUserData;\n  p->nArg = (u16)nArg;\n  return SQLITE_OK;\n}\n\n/*\n** Create new user functions.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*)\n){\n  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,\n                                    xFinal, 0);\n}\n\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunc,\n  int nArg,\n  int enc,\n  void *p,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value **),\n  void (*xFinal)(sqlite3_context*),\n  void (*xDestroy)(void *)\n){\n  int rc = SQLITE_ERROR;\n  FuncDestructor *pArg = 0;\n  sqlite3_mutex_enter(db->mutex);\n  if( xDestroy ){\n    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));\n    if( !pArg ){\n      xDestroy(p);\n      goto out;\n    }\n    pArg->xDestroy = xDestroy;\n    pArg->pUserData = p;\n  }\n  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);\n  if( pArg && pArg->nRef==0 ){\n    assert( rc!=SQLITE_OK );\n    xDestroy(p);\n    sqlite3DbFree(db, pArg);\n  }\n\n out:\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_UTF16\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *p,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n){\n  int rc;\n  char *zFunc8;\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);\n  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);\n  sqlite3DbFree(db, zFunc8);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n#endif\n\n\n/*\n** Declare that a function has been overloaded by a virtual table.\n**\n** If the function already exists as a regular global function, then\n** this routine is a no-op.  If the function does not exist, then create\n** a new one that always throws a run-time error.  \n**\n** When virtual tables intend to provide an overloaded function, they\n** should call this routine to make sure the global function exists.\n** A global function must exist in order for name resolution to work\n** properly.\n*/\nSQLITE_API int sqlite3_overload_function(\n  sqlite3 *db,\n  const char *zName,\n  int nArg\n){\n  int nName = sqlite3Strlen30(zName);\n  int rc = SQLITE_OK;\n  sqlite3_mutex_enter(db->mutex);\n  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){\n    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,\n                           0, sqlite3InvalidFunction, 0, 0, 0);\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_TRACE\n/*\n** Register a trace function.  The pArg from the previously registered trace\n** is returned.  \n**\n** A NULL trace function means that no tracing is executes.  A non-NULL\n** trace is a pointer to a function that is invoked at the start of each\n** SQL statement.\n*/\nSQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){\n  void *pOld;\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pTraceArg;\n  db->xTrace = xTrace;\n  db->pTraceArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n/*\n** Register a profile function.  The pArg from the previously registered \n** profile function is returned.  \n**\n** A NULL profile function means that no profiling is executes.  A non-NULL\n** profile is a pointer to a function that is invoked at the conclusion of\n** each SQL statement that is run.\n*/\nSQLITE_API void *sqlite3_profile(\n  sqlite3 *db,\n  void (*xProfile)(void*,const char*,sqlite_uint64),\n  void *pArg\n){\n  void *pOld;\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pProfileArg;\n  db->xProfile = xProfile;\n  db->pProfileArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n#endif /* SQLITE_OMIT_TRACE */\n\n/*\n** Register a function to be invoked when a transaction commits.\n** If the invoked function returns non-zero, then the commit becomes a\n** rollback.\n*/\nSQLITE_API void *sqlite3_commit_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  int (*xCallback)(void*),  /* Function to invoke on each commit */\n  void *pArg                /* Argument to the function */\n){\n  void *pOld;\n  sqlite3_mutex_enter(db->mutex);\n  pOld = db->pCommitArg;\n  db->xCommitCallback = xCallback;\n  db->pCommitArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pOld;\n}\n\n/*\n** Register a callback to be invoked each time a row is updated,\n** inserted or deleted using this database connection.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),\n  void *pArg                /* Argument to the function */\n){\n  void *pRet;\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pUpdateArg;\n  db->xUpdateCallback = xCallback;\n  db->pUpdateArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n}\n\n/*\n** Register a callback to be invoked each time a transaction is rolled\n** back by this database connection.\n*/\nSQLITE_API void *sqlite3_rollback_hook(\n  sqlite3 *db,              /* Attach the hook to this database */\n  void (*xCallback)(void*), /* Callback function */\n  void *pArg                /* Argument to the function */\n){\n  void *pRet;\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pRollbackArg;\n  db->xRollbackCallback = xCallback;\n  db->pRollbackArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().\n** Invoke sqlite3_wal_checkpoint if the number of frames in the log file\n** is greater than sqlite3.pWalArg cast to an integer (the value configured by\n** wal_autocheckpoint()).\n*/ \nSQLITE_PRIVATE int sqlite3WalDefaultHook(\n  void *pClientData,     /* Argument */\n  sqlite3 *db,           /* Connection */\n  const char *zDb,       /* Database */\n  int nFrame             /* Size of WAL */\n){\n  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){\n    sqlite3BeginBenignMalloc();\n    sqlite3_wal_checkpoint(db, zDb);\n    sqlite3EndBenignMalloc();\n  }\n  return SQLITE_OK;\n}\n#endif /* SQLITE_OMIT_WAL */\n\n/*\n** Configure an sqlite3_wal_hook() callback to automatically checkpoint\n** a database after committing a transaction if there are nFrame or\n** more frames in the log file. Passing zero or a negative value as the\n** nFrame parameter disables automatic checkpoints entirely.\n**\n** The callback registered by this function replaces any existing callback\n** registered using sqlite3_wal_hook(). Likewise, registering a callback\n** using sqlite3_wal_hook() disables the automatic checkpoint mechanism\n** configured by this function.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){\n#ifdef SQLITE_OMIT_WAL\n  UNUSED_PARAMETER(db);\n  UNUSED_PARAMETER(nFrame);\n#else\n  if( nFrame>0 ){\n    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));\n  }else{\n    sqlite3_wal_hook(db, 0, 0);\n  }\n#endif\n  return SQLITE_OK;\n}\n\n/*\n** Register a callback to be invoked each time a transaction is written\n** into the write-ahead-log by this database connection.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3 *db,                    /* Attach the hook to this db handle */\n  int(*xCallback)(void *, sqlite3*, const char*, int),\n  void *pArg                      /* First argument passed to xCallback() */\n){\n#ifndef SQLITE_OMIT_WAL\n  void *pRet;\n  sqlite3_mutex_enter(db->mutex);\n  pRet = db->pWalArg;\n  db->xWalCallback = xCallback;\n  db->pWalArg = pArg;\n  sqlite3_mutex_leave(db->mutex);\n  return pRet;\n#else\n  return 0;\n#endif\n}\n\n/*\n** Checkpoint database zDb.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n){\n#ifdef SQLITE_OMIT_WAL\n  return SQLITE_OK;\n#else\n  int rc;                         /* Return code */\n  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */\n\n  /* Initialize the output variables to -1 in case an error occurs. */\n  if( pnLog ) *pnLog = -1;\n  if( pnCkpt ) *pnCkpt = -1;\n\n  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );\n  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );\n  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );\n  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){\n    return SQLITE_MISUSE;\n  }\n\n  sqlite3_mutex_enter(db->mutex);\n  if( zDb && zDb[0] ){\n    iDb = sqlite3FindDbName(db, zDb);\n  }\n  if( iDb<0 ){\n    rc = SQLITE_ERROR;\n    sqlite3Error(db, SQLITE_ERROR, \"unknown database: %s\", zDb);\n  }else{\n    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);\n    sqlite3Error(db, rc, 0);\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n#endif\n}\n\n\n/*\n** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points\n** to contains a zero-length string, all attached databases are \n** checkpointed.\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){\n  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);\n}\n\n#ifndef SQLITE_OMIT_WAL\n/*\n** Run a checkpoint on database iDb. This is a no-op if database iDb is\n** not currently open in WAL mode.\n**\n** If a transaction is open on the database being checkpointed, this \n** function returns SQLITE_LOCKED and a checkpoint is not attempted. If \n** an error occurs while running the checkpoint, an SQLite error code is \n** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.\n**\n** The mutex on database handle db should be held by the caller. The mutex\n** associated with the specific b-tree being checkpointed is taken by\n** this function while the checkpoint is running.\n**\n** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are\n** checkpointed. If an error is encountered it is returned immediately -\n** no attempt is made to checkpoint any remaining databases.\n**\n** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.\n*/\nSQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Used to iterate through attached dbs */\n  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */\n\n  assert( sqlite3_mutex_held(db->mutex) );\n  assert( !pnLog || *pnLog==-1 );\n  assert( !pnCkpt || *pnCkpt==-1 );\n\n  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){\n    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){\n      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);\n      pnLog = 0;\n      pnCkpt = 0;\n      if( rc==SQLITE_BUSY ){\n        bBusy = 1;\n        rc = SQLITE_OK;\n      }\n    }\n  }\n\n  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;\n}\n#endif /* SQLITE_OMIT_WAL */\n\n/*\n** This function returns true if main-memory should be used instead of\n** a temporary file for transient pager files and statement journals.\n** The value returned depends on the value of db->temp_store (runtime\n** parameter) and the compile time value of SQLITE_TEMP_STORE. The\n** following table describes the relationship between these two values\n** and this functions return value.\n**\n**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database\n**   -----------------     --------------     ------------------------------\n**   0                     any                file      (return 0)\n**   1                     1                  file      (return 0)\n**   1                     2                  memory    (return 1)\n**   1                     0                  file      (return 0)\n**   2                     1                  file      (return 0)\n**   2                     2                  memory    (return 1)\n**   2                     0                  memory    (return 1)\n**   3                     any                memory    (return 1)\n*/\nSQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){\n#if SQLITE_TEMP_STORE==1\n  return ( db->temp_store==2 );\n#endif\n#if SQLITE_TEMP_STORE==2\n  return ( db->temp_store!=1 );\n#endif\n#if SQLITE_TEMP_STORE==3\n  return 1;\n#endif\n#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3\n  return 0;\n#endif\n}\n\n/*\n** Return UTF-8 encoded English language explanation of the most recent\n** error.\n*/\nSQLITE_API const char *sqlite3_errmsg(sqlite3 *db){\n  const char *z;\n  if( !db ){\n    return sqlite3ErrStr(SQLITE_NOMEM);\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);\n  }\n  sqlite3_mutex_enter(db->mutex);\n  if( db->mallocFailed ){\n    z = sqlite3ErrStr(SQLITE_NOMEM);\n  }else{\n    z = (char*)sqlite3_value_text(db->pErr);\n    assert( !db->mallocFailed );\n    if( z==0 ){\n      z = sqlite3ErrStr(db->errCode);\n    }\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return z;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Return UTF-16 encoded English language explanation of the most recent\n** error.\n*/\nSQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){\n  static const u16 outOfMem[] = {\n    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0\n  };\n  static const u16 misuse[] = {\n    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', \n    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', \n    'c', 'a', 'l', 'l', 'e', 'd', ' ', \n    'o', 'u', 't', ' ', \n    'o', 'f', ' ', \n    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0\n  };\n\n  const void *z;\n  if( !db ){\n    return (void *)outOfMem;\n  }\n  if( !sqlite3SafetyCheckSickOrOk(db) ){\n    return (void *)misuse;\n  }\n  sqlite3_mutex_enter(db->mutex);\n  if( db->mallocFailed ){\n    z = (void *)outOfMem;\n  }else{\n    z = sqlite3_value_text16(db->pErr);\n    if( z==0 ){\n      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),\n           SQLITE_UTF8, SQLITE_STATIC);\n      z = sqlite3_value_text16(db->pErr);\n    }\n    /* A malloc() may have failed within the call to sqlite3_value_text16()\n    ** above. If this is the case, then the db->mallocFailed flag needs to\n    ** be cleared before returning. Do this directly, instead of via\n    ** sqlite3ApiExit(), to avoid setting the database handle error message.\n    */\n    db->mallocFailed = 0;\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return z;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Return the most recent error code generated by an SQLite routine. If NULL is\n** passed to this function, we assume a malloc() failed during sqlite3_open().\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db){\n  if( db && !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( !db || db->mallocFailed ){\n    return SQLITE_NOMEM;\n  }\n  return db->errCode & db->errMask;\n}\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db){\n  if( db && !sqlite3SafetyCheckSickOrOk(db) ){\n    return SQLITE_MISUSE_BKPT;\n  }\n  if( !db || db->mallocFailed ){\n    return SQLITE_NOMEM;\n  }\n  return db->errCode;\n}\n\n/*\n** Create a new collating function for database \"db\".  The name is zName\n** and the encoding is enc.\n*/\nstatic int createCollation(\n  sqlite3* db,\n  const char *zName, \n  u8 enc,\n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDel)(void*)\n){\n  CollSeq *pColl;\n  int enc2;\n  int nName = sqlite3Strlen30(zName);\n  \n  assert( sqlite3_mutex_held(db->mutex) );\n\n  /* If SQLITE_UTF16 is specified as the encoding type, transform this\n  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the\n  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.\n  */\n  enc2 = enc;\n  testcase( enc2==SQLITE_UTF16 );\n  testcase( enc2==SQLITE_UTF16_ALIGNED );\n  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){\n    enc2 = SQLITE_UTF16NATIVE;\n  }\n  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){\n    return SQLITE_MISUSE_BKPT;\n  }\n\n  /* Check if this call is removing or replacing an existing collation \n  ** sequence. If so, and there are active VMs, return busy. If there\n  ** are no active VMs, invalidate any pre-compiled statements.\n  */\n  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);\n  if( pColl && pColl->xCmp ){\n    if( db->activeVdbeCnt ){\n      sqlite3Error(db, SQLITE_BUSY, \n        \"unable to delete/modify collation sequence due to active statements\");\n      return SQLITE_BUSY;\n    }\n    sqlite3ExpirePreparedStatements(db);\n\n    /* If collation sequence pColl was created directly by a call to\n    ** sqlite3_create_collation, and not generated by synthCollSeq(),\n    ** then any copies made by synthCollSeq() need to be invalidated.\n    ** Also, collation destructor - CollSeq.xDel() - function may need\n    ** to be called.\n    */ \n    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){\n      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);\n      int j;\n      for(j=0; j<3; j++){\n        CollSeq *p = &aColl[j];\n        if( p->enc==pColl->enc ){\n          if( p->xDel ){\n            p->xDel(p->pUser);\n          }\n          p->xCmp = 0;\n        }\n      }\n    }\n  }\n\n  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);\n  if( pColl==0 ) return SQLITE_NOMEM;\n  pColl->xCmp = xCompare;\n  pColl->pUser = pCtx;\n  pColl->xDel = xDel;\n  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));\n  sqlite3Error(db, SQLITE_OK, 0);\n  return SQLITE_OK;\n}\n\n\n/*\n** This array defines hard upper bounds on limit values.  The\n** initializer must be kept in sync with the SQLITE_LIMIT_*\n** #defines in sqlite3.h.\n*/\nstatic const int aHardLimit[] = {\n  SQLITE_MAX_LENGTH,\n  SQLITE_MAX_SQL_LENGTH,\n  SQLITE_MAX_COLUMN,\n  SQLITE_MAX_EXPR_DEPTH,\n  SQLITE_MAX_COMPOUND_SELECT,\n  SQLITE_MAX_VDBE_OP,\n  SQLITE_MAX_FUNCTION_ARG,\n  SQLITE_MAX_ATTACHED,\n  SQLITE_MAX_LIKE_PATTERN_LENGTH,\n  SQLITE_MAX_VARIABLE_NUMBER,\n  SQLITE_MAX_TRIGGER_DEPTH,\n};\n\n/*\n** Make sure the hard limits are set to reasonable values\n*/\n#if SQLITE_MAX_LENGTH<100\n# error SQLITE_MAX_LENGTH must be at least 100\n#endif\n#if SQLITE_MAX_SQL_LENGTH<100\n# error SQLITE_MAX_SQL_LENGTH must be at least 100\n#endif\n#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH\n# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH\n#endif\n#if SQLITE_MAX_COMPOUND_SELECT<2\n# error SQLITE_MAX_COMPOUND_SELECT must be at least 2\n#endif\n#if SQLITE_MAX_VDBE_OP<40\n# error SQLITE_MAX_VDBE_OP must be at least 40\n#endif\n#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000\n# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000\n#endif\n#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62\n# error SQLITE_MAX_ATTACHED must be between 0 and 62\n#endif\n#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1\n# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1\n#endif\n#if SQLITE_MAX_COLUMN>32767\n# error SQLITE_MAX_COLUMN must not exceed 32767\n#endif\n#if SQLITE_MAX_TRIGGER_DEPTH<1\n# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1\n#endif\n\n\n/*\n** Change the value of a limit.  Report the old value.\n** If an invalid limit index is supplied, report -1.\n** Make no changes but still report the old value if the\n** new limit is negative.\n**\n** A new lower limit does not shrink existing constructs.\n** It merely prevents new constructs that exceed the limit\n** from forming.\n*/\nSQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){\n  int oldLimit;\n\n\n  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME\n  ** there is a hard upper bound set at compile-time by a C preprocessor\n  ** macro called SQLITE_MAX_NAME. (The \"_LIMIT_\" in the name is changed to\n  ** \"_MAX_\".)\n  */\n  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );\n  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );\n  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);\n  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );\n  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );\n  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );\n  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==\n                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );\n  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);\n  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );\n  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );\n\n\n  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){\n    return -1;\n  }\n  oldLimit = db->aLimit[limitId];\n  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */\n    if( newLimit>aHardLimit[limitId] ){\n      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */\n    }\n    db->aLimit[limitId] = newLimit;\n  }\n  return oldLimit;                     /* IMP: R-53341-35419 */\n}\n\n/*\n** This function is used to parse both URIs and non-URI filenames passed by the\n** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database\n** URIs specified as part of ATTACH statements.\n**\n** The first argument to this function is the name of the VFS to use (or\n** a NULL to signify the default VFS) if the URI does not contain a \"vfs=xxx\"\n** query parameter. The second argument contains the URI (or non-URI filename)\n** itself. When this function is called the *pFlags variable should contain\n** the default flags to open the database handle with. The value stored in\n** *pFlags may be updated before returning if the URI filename contains \n** \"cache=xxx\" or \"mode=xxx\" query parameters.\n**\n** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to\n** the VFS that should be used to open the database file. *pzFile is set to\n** point to a buffer containing the name of the file to open. It is the \n** responsibility of the caller to eventually call sqlite3_free() to release\n** this buffer.\n**\n** If an error occurs, then an SQLite error code is returned and *pzErrMsg\n** may be set to point to a buffer containing an English language error \n** message. It is the responsibility of the caller to eventually release\n** this buffer by calling sqlite3_free().\n*/\nSQLITE_PRIVATE int sqlite3ParseUri(\n  const char *zDefaultVfs,        /* VFS to use if no \"vfs=xxx\" query option */\n  const char *zUri,               /* Nul-terminated URI to parse */\n  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */\n  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ \n  char **pzFile,                  /* OUT: Filename component of URI */\n  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */\n){\n  int rc = SQLITE_OK;\n  unsigned int flags = *pFlags;\n  const char *zVfs = zDefaultVfs;\n  char *zFile;\n  char c;\n  int nUri = sqlite3Strlen30(zUri);\n\n  assert( *pzErrMsg==0 );\n\n  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) \n   && nUri>=5 && memcmp(zUri, \"file:\", 5)==0 \n  ){\n    char *zOpt;\n    int eState;                   /* Parser state when parsing URI */\n    int iIn;                      /* Input character index */\n    int iOut = 0;                 /* Output character index */\n    int nByte = nUri+2;           /* Bytes of space to allocate */\n\n    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen \n    ** method that there may be extra parameters following the file-name.  */\n    flags |= SQLITE_OPEN_URI;\n\n    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');\n    zFile = sqlite3_malloc(nByte);\n    if( !zFile ) return SQLITE_NOMEM;\n\n    /* Discard the scheme and authority segments of the URI. */\n    if( zUri[5]=='/' && zUri[6]=='/' ){\n      iIn = 7;\n      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;\n\n      if( iIn!=7 && (iIn!=16 || memcmp(\"localhost\", &zUri[7], 9)) ){\n        *pzErrMsg = sqlite3_mprintf(\"invalid uri authority: %.*s\", \n            iIn-7, &zUri[7]);\n        rc = SQLITE_ERROR;\n        goto parse_uri_out;\n      }\n    }else{\n      iIn = 5;\n    }\n\n    /* Copy the filename and any query parameters into the zFile buffer. \n    ** Decode %HH escape codes along the way. \n    **\n    ** Within this loop, variable eState may be set to 0, 1 or 2, depending\n    ** on the parsing context. As follows:\n    **\n    **   0: Parsing file-name.\n    **   1: Parsing name section of a name=value query parameter.\n    **   2: Parsing value section of a name=value query parameter.\n    */\n    eState = 0;\n    while( (c = zUri[iIn])!=0 && c!='#' ){\n      iIn++;\n      if( c=='%' \n       && sqlite3Isxdigit(zUri[iIn]) \n       && sqlite3Isxdigit(zUri[iIn+1]) \n      ){\n        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);\n        octet += sqlite3HexToInt(zUri[iIn++]);\n\n        assert( octet>=0 && octet<256 );\n        if( octet==0 ){\n          /* This branch is taken when \"%00\" appears within the URI. In this\n          ** case we ignore all text in the remainder of the path, name or\n          ** value currently being parsed. So ignore the current character\n          ** and skip to the next \"?\", \"=\" or \"&\", as appropriate. */\n          while( (c = zUri[iIn])!=0 && c!='#' \n              && (eState!=0 || c!='?')\n              && (eState!=1 || (c!='=' && c!='&'))\n              && (eState!=2 || c!='&')\n          ){\n            iIn++;\n          }\n          continue;\n        }\n        c = octet;\n      }else if( eState==1 && (c=='&' || c=='=') ){\n        if( zFile[iOut-1]==0 ){\n          /* An empty option name. Ignore this option altogether. */\n          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;\n          continue;\n        }\n        if( c=='&' ){\n          zFile[iOut++] = '\\0';\n        }else{\n          eState = 2;\n        }\n        c = 0;\n      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){\n        c = 0;\n        eState = 1;\n      }\n      zFile[iOut++] = c;\n    }\n    if( eState==1 ) zFile[iOut++] = '\\0';\n    zFile[iOut++] = '\\0';\n    zFile[iOut++] = '\\0';\n\n    /* Check if there were any options specified that should be interpreted \n    ** here. Options that are interpreted here include \"vfs\" and those that\n    ** correspond to flags that may be passed to the sqlite3_open_v2()\n    ** method. */\n    zOpt = &zFile[sqlite3Strlen30(zFile)+1];\n    while( zOpt[0] ){\n      int nOpt = sqlite3Strlen30(zOpt);\n      char *zVal = &zOpt[nOpt+1];\n      int nVal = sqlite3Strlen30(zVal);\n\n      if( nOpt==3 && memcmp(\"vfs\", zOpt, 3)==0 ){\n        zVfs = zVal;\n      }else{\n        struct OpenMode {\n          const char *z;\n          int mode;\n        } *aMode = 0;\n        char *zModeType = 0;\n        int mask = 0;\n        int limit = 0;\n\n        if( nOpt==5 && memcmp(\"cache\", zOpt, 5)==0 ){\n          static struct OpenMode aCacheMode[] = {\n            { \"shared\",  SQLITE_OPEN_SHAREDCACHE },\n            { \"private\", SQLITE_OPEN_PRIVATECACHE },\n            { 0, 0 }\n          };\n\n          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;\n          aMode = aCacheMode;\n          limit = mask;\n          zModeType = \"cache\";\n        }\n        if( nOpt==4 && memcmp(\"mode\", zOpt, 4)==0 ){\n          static struct OpenMode aOpenMode[] = {\n            { \"ro\",  SQLITE_OPEN_READONLY },\n            { \"rw\",  SQLITE_OPEN_READWRITE }, \n            { \"rwc\", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },\n            { \"memory\", SQLITE_OPEN_MEMORY },\n            { 0, 0 }\n          };\n\n          mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE\n                   | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;\n          aMode = aOpenMode;\n          limit = mask & flags;\n          zModeType = \"access\";\n        }\n\n        if( aMode ){\n          int i;\n          int mode = 0;\n          for(i=0; aMode[i].z; i++){\n            const char *z = aMode[i].z;\n            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){\n              mode = aMode[i].mode;\n              break;\n            }\n          }\n          if( mode==0 ){\n            *pzErrMsg = sqlite3_mprintf(\"no such %s mode: %s\", zModeType, zVal);\n            rc = SQLITE_ERROR;\n            goto parse_uri_out;\n          }\n          if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){\n            *pzErrMsg = sqlite3_mprintf(\"%s mode not allowed: %s\",\n                                        zModeType, zVal);\n            rc = SQLITE_PERM;\n            goto parse_uri_out;\n          }\n          flags = (flags & ~mask) | mode;\n        }\n      }\n\n      zOpt = &zVal[nVal+1];\n    }\n\n  }else{\n    zFile = sqlite3_malloc(nUri+2);\n    if( !zFile ) return SQLITE_NOMEM;\n    memcpy(zFile, zUri, nUri);\n    zFile[nUri] = '\\0';\n    zFile[nUri+1] = '\\0';\n    flags &= ~SQLITE_OPEN_URI;\n  }\n\n  *ppVfs = sqlite3_vfs_find(zVfs);\n  if( *ppVfs==0 ){\n    *pzErrMsg = sqlite3_mprintf(\"no such vfs: %s\", zVfs);\n    rc = SQLITE_ERROR;\n  }\n parse_uri_out:\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(zFile);\n    zFile = 0;\n  }\n  *pFlags = flags;\n  *pzFile = zFile;\n  return rc;\n}\n\n\n/*\n** This routine does the work of opening a database on behalf of\n** sqlite3_open() and sqlite3_open16(). The database filename \"zFilename\"  \n** is UTF-8 encoded.\n*/\nstatic int openDatabase(\n  const char *zFilename, /* Database filename UTF-8 encoded */\n  sqlite3 **ppDb,        /* OUT: Returned database handle */\n  unsigned int flags,    /* Operational flags */\n  const char *zVfs       /* Name of the VFS to use */\n){\n  sqlite3 *db;                    /* Store allocated handle here */\n  int rc;                         /* Return code */\n  int isThreadsafe;               /* True for threadsafe connections */\n  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */\n  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */\n\n  *ppDb = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n\n  /* Only allow sensible combinations of bits in the flags argument.  \n  ** Throw an error if any non-sense combination is used.  If we\n  ** do not block illegal combinations here, it could trigger\n  ** assert() statements in deeper layers.  Sensible combinations\n  ** are:\n  **\n  **  1:  SQLITE_OPEN_READONLY\n  **  2:  SQLITE_OPEN_READWRITE\n  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE\n  */\n  assert( SQLITE_OPEN_READONLY  == 0x01 );\n  assert( SQLITE_OPEN_READWRITE == 0x02 );\n  assert( SQLITE_OPEN_CREATE    == 0x04 );\n  testcase( (1<<(flags&7))==0x02 ); /* READONLY */\n  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */\n  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */\n  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;\n\n  if( sqlite3GlobalConfig.bCoreMutex==0 ){\n    isThreadsafe = 0;\n  }else if( flags & SQLITE_OPEN_NOMUTEX ){\n    isThreadsafe = 0;\n  }else if( flags & SQLITE_OPEN_FULLMUTEX ){\n    isThreadsafe = 1;\n  }else{\n    isThreadsafe = sqlite3GlobalConfig.bFullMutex;\n  }\n  if( flags & SQLITE_OPEN_PRIVATECACHE ){\n    flags &= ~SQLITE_OPEN_SHAREDCACHE;\n  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){\n    flags |= SQLITE_OPEN_SHAREDCACHE;\n  }\n\n  /* Remove harmful bits from the flags parameter\n  **\n  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were\n  ** dealt with in the previous code block.  Besides these, the only\n  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,\n  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,\n  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask\n  ** off all other flags.\n  */\n  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |\n               SQLITE_OPEN_EXCLUSIVE |\n               SQLITE_OPEN_MAIN_DB |\n               SQLITE_OPEN_TEMP_DB | \n               SQLITE_OPEN_TRANSIENT_DB | \n               SQLITE_OPEN_MAIN_JOURNAL | \n               SQLITE_OPEN_TEMP_JOURNAL | \n               SQLITE_OPEN_SUBJOURNAL | \n               SQLITE_OPEN_MASTER_JOURNAL |\n               SQLITE_OPEN_NOMUTEX |\n               SQLITE_OPEN_FULLMUTEX |\n               SQLITE_OPEN_WAL\n             );\n\n  /* Allocate the sqlite data structure */\n  db = sqlite3MallocZero( sizeof(sqlite3) );\n  if( db==0 ) goto opendb_out;\n  if( isThreadsafe ){\n    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);\n    if( db->mutex==0 ){\n      sqlite3_free(db);\n      db = 0;\n      goto opendb_out;\n    }\n  }\n  sqlite3_mutex_enter(db->mutex);\n  db->errMask = 0xff;\n  db->nDb = 2;\n  db->magic = SQLITE_MAGIC_BUSY;\n  db->aDb = db->aDbStatic;\n\n  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );\n  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));\n  db->autoCommit = 1;\n  db->nextAutovac = -1;\n  db->nextPagesize = 0;\n  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger\n#if SQLITE_DEFAULT_FILE_FORMAT<4\n                 | SQLITE_LegacyFileFmt\n#endif\n#ifdef SQLITE_ENABLE_LOAD_EXTENSION\n                 | SQLITE_LoadExtension\n#endif\n#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS\n                 | SQLITE_RecTriggers\n#endif\n#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS\n                 | SQLITE_ForeignKeys\n#endif\n      ;\n  sqlite3HashInit(&db->aCollSeq);\n#ifndef SQLITE_OMIT_VIRTUALTABLE\n  sqlite3HashInit(&db->aModule);\n#endif\n\n  /* Add the default collation sequence BINARY. BINARY works for both UTF-8\n  ** and UTF-16, so add a version for each to avoid any unnecessary\n  ** conversions. The only error that can occur here is a malloc() failure.\n  */\n  createCollation(db, \"BINARY\", SQLITE_UTF8, 0, binCollFunc, 0);\n  createCollation(db, \"BINARY\", SQLITE_UTF16BE, 0, binCollFunc, 0);\n  createCollation(db, \"BINARY\", SQLITE_UTF16LE, 0, binCollFunc, 0);\n  createCollation(db, \"RTRIM\", SQLITE_UTF8, (void*)1, binCollFunc, 0);\n  if( db->mallocFailed ){\n    goto opendb_out;\n  }\n  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, \"BINARY\", 0);\n  assert( db->pDfltColl!=0 );\n\n  /* Also add a UTF-8 case-insensitive collation sequence. */\n  createCollation(db, \"NOCASE\", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);\n\n  /* Parse the filename/URI argument. */\n  db->openFlags = flags;\n  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;\n    sqlite3Error(db, rc, zErrMsg ? \"%s\" : 0, zErrMsg);\n    sqlite3_free(zErrMsg);\n    goto opendb_out;\n  }\n\n  /* Open the backend database driver */\n  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,\n                        flags | SQLITE_OPEN_MAIN_DB);\n  if( rc!=SQLITE_OK ){\n    if( rc==SQLITE_IOERR_NOMEM ){\n      rc = SQLITE_NOMEM;\n    }\n    sqlite3Error(db, rc, 0);\n    goto opendb_out;\n  }\n  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);\n  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);\n\n\n  /* The default safety_level for the main database is 'full'; for the temp\n  ** database it is 'NONE'. This matches the pager layer defaults.  \n  */\n  db->aDb[0].zName = \"main\";\n  db->aDb[0].safety_level = 3;\n  db->aDb[1].zName = \"temp\";\n  db->aDb[1].safety_level = 1;\n\n  db->magic = SQLITE_MAGIC_OPEN;\n  if( db->mallocFailed ){\n    goto opendb_out;\n  }\n\n  /* Register all built-in functions, but do not attempt to read the\n  ** database schema yet. This is delayed until the first time the database\n  ** is accessed.\n  */\n  sqlite3Error(db, SQLITE_OK, 0);\n  sqlite3RegisterBuiltinFunctions(db);\n\n  /* Load automatic extensions - extensions that have been registered\n  ** using the sqlite3_automatic_extension() API.\n  */\n  rc = sqlite3_errcode(db);\n  if( rc==SQLITE_OK ){\n    sqlite3AutoLoadExtensions(db);\n    rc = sqlite3_errcode(db);\n    if( rc!=SQLITE_OK ){\n      goto opendb_out;\n    }\n  }\n\n#ifdef SQLITE_ENABLE_FTS1\n  if( !db->mallocFailed ){\n    extern int sqlite3Fts1Init(sqlite3*);\n    rc = sqlite3Fts1Init(db);\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_FTS2\n  if( !db->mallocFailed && rc==SQLITE_OK ){\n    extern int sqlite3Fts2Init(sqlite3*);\n    rc = sqlite3Fts2Init(db);\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_FTS3\n  if( !db->mallocFailed && rc==SQLITE_OK ){\n    rc = sqlite3Fts3Init(db);\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_ICU\n  if( !db->mallocFailed && rc==SQLITE_OK ){\n    rc = sqlite3IcuInit(db);\n  }\n#endif\n\n#ifdef SQLITE_ENABLE_RTREE\n  if( !db->mallocFailed && rc==SQLITE_OK){\n    rc = sqlite3RtreeInit(db);\n  }\n#endif\n\n  sqlite3Error(db, rc, 0);\n\n  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking\n  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking\n  ** mode.  Doing nothing at all also makes NORMAL the default.\n  */\n#ifdef SQLITE_DEFAULT_LOCKING_MODE\n  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;\n  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),\n                          SQLITE_DEFAULT_LOCKING_MODE);\n#endif\n\n  /* Enable the lookaside-malloc subsystem */\n  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,\n                        sqlite3GlobalConfig.nLookaside);\n\n  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);\n\nopendb_out:\n  sqlite3_free(zOpen);\n  if( db ){\n    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );\n    sqlite3_mutex_leave(db->mutex);\n  }\n  rc = sqlite3_errcode(db);\n  assert( db!=0 || rc==SQLITE_NOMEM );\n  if( rc==SQLITE_NOMEM ){\n    sqlite3_close(db);\n    db = 0;\n  }else if( rc!=SQLITE_OK ){\n    db->magic = SQLITE_MAGIC_SICK;\n  }\n  *ppDb = db;\n  return sqlite3ApiExit(0, rc);\n}\n\n/*\n** Open a new database handle.\n*/\nSQLITE_API int sqlite3_open(\n  const char *zFilename, \n  sqlite3 **ppDb \n){\n  return openDatabase(zFilename, ppDb,\n                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);\n}\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n){\n  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Open a new database handle.\n*/\nSQLITE_API int sqlite3_open16(\n  const void *zFilename, \n  sqlite3 **ppDb\n){\n  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */\n  sqlite3_value *pVal;\n  int rc;\n\n  assert( zFilename );\n  assert( ppDb );\n  *ppDb = 0;\n#ifndef SQLITE_OMIT_AUTOINIT\n  rc = sqlite3_initialize();\n  if( rc ) return rc;\n#endif\n  pVal = sqlite3ValueNew(0);\n  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);\n  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);\n  if( zFilename8 ){\n    rc = openDatabase(zFilename8, ppDb,\n                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);\n    assert( *ppDb || rc==SQLITE_NOMEM );\n    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){\n      ENC(*ppDb) = SQLITE_UTF16NATIVE;\n    }\n  }else{\n    rc = SQLITE_NOMEM;\n  }\n  sqlite3ValueFree(pVal);\n\n  return sqlite3ApiExit(0, rc);\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3* db, \n  const char *zName, \n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n){\n  int rc;\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3* db, \n  const char *zName, \n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDel)(void*)\n){\n  int rc;\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Register a new collation sequence with the database handle db.\n*/\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3* db, \n  const void *zName,\n  int enc, \n  void* pCtx,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n){\n  int rc = SQLITE_OK;\n  char *zName8;\n  sqlite3_mutex_enter(db->mutex);\n  assert( !db->mallocFailed );\n  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);\n  if( zName8 ){\n    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);\n    sqlite3DbFree(db, zName8);\n  }\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n/*\n** Register a collation sequence factory callback with the database handle\n** db. Replace any previously installed collation sequence factory.\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3 *db, \n  void *pCollNeededArg, \n  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)\n){\n  sqlite3_mutex_enter(db->mutex);\n  db->xCollNeeded = xCollNeeded;\n  db->xCollNeeded16 = 0;\n  db->pCollNeededArg = pCollNeededArg;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n#ifndef SQLITE_OMIT_UTF16\n/*\n** Register a collation sequence factory callback with the database handle\n** db. Replace any previously installed collation sequence factory.\n*/\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3 *db, \n  void *pCollNeededArg, \n  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)\n){\n  sqlite3_mutex_enter(db->mutex);\n  db->xCollNeeded = 0;\n  db->xCollNeeded16 = xCollNeeded16;\n  db->pCollNeededArg = pCollNeededArg;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n#endif /* SQLITE_OMIT_UTF16 */\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** This function is now an anachronism. It used to be used to recover from a\n** malloc() failure, but SQLite now does this automatically.\n*/\nSQLITE_API int sqlite3_global_recover(void){\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** Test to see whether or not the database connection is in autocommit\n** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on\n** by default.  Autocommit is disabled by a BEGIN statement and reenabled\n** by the next COMMIT or ROLLBACK.\n**\n******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3 *db){\n  return db->autoCommit;\n}\n\n/*\n** The following routines are subtitutes for constants SQLITE_CORRUPT,\n** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error\n** constants.  They server two purposes:\n**\n**   1.  Serve as a convenient place to set a breakpoint in a debugger\n**       to detect when version error conditions occurs.\n**\n**   2.  Invoke sqlite3_log() to provide the source code location where\n**       a low-level error is first detected.\n*/\nSQLITE_PRIVATE int sqlite3CorruptError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  sqlite3_log(SQLITE_CORRUPT,\n              \"database corruption at line %d of [%.10s]\",\n              lineno, 20+sqlite3_sourceid());\n  return SQLITE_CORRUPT;\n}\nSQLITE_PRIVATE int sqlite3MisuseError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  sqlite3_log(SQLITE_MISUSE, \n              \"misuse at line %d of [%.10s]\",\n              lineno, 20+sqlite3_sourceid());\n  return SQLITE_MISUSE;\n}\nSQLITE_PRIVATE int sqlite3CantopenError(int lineno){\n  testcase( sqlite3GlobalConfig.xLog!=0 );\n  sqlite3_log(SQLITE_CANTOPEN, \n              \"cannot open file at line %d of [%.10s]\",\n              lineno, 20+sqlite3_sourceid());\n  return SQLITE_CANTOPEN;\n}\n\n\n#ifndef SQLITE_OMIT_DEPRECATED\n/*\n** This is a convenience routine that makes sure that all thread-specific\n** data for this thread has been deallocated.\n**\n** SQLite no longer uses thread-specific data so this routine is now a\n** no-op.  It is retained for historical compatibility.\n*/\nSQLITE_API void sqlite3_thread_cleanup(void){\n}\n#endif\n\n/*\n** Return meta information about a specific column of a database table.\n** See comment in sqlite3.h (sqlite.h.in) for details.\n*/\n#ifdef SQLITE_ENABLE_COLUMN_METADATA\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n){\n  int rc;\n  char *zErrMsg = 0;\n  Table *pTab = 0;\n  Column *pCol = 0;\n  int iCol;\n\n  char const *zDataType = 0;\n  char const *zCollSeq = 0;\n  int notnull = 0;\n  int primarykey = 0;\n  int autoinc = 0;\n\n  /* Ensure the database schema has been loaded */\n  sqlite3_mutex_enter(db->mutex);\n  sqlite3BtreeEnterAll(db);\n  rc = sqlite3Init(db, &zErrMsg);\n  if( SQLITE_OK!=rc ){\n    goto error_out;\n  }\n\n  /* Locate the table in question */\n  pTab = sqlite3FindTable(db, zTableName, zDbName);\n  if( !pTab || pTab->pSelect ){\n    pTab = 0;\n    goto error_out;\n  }\n\n  /* Find the column for which info is requested */\n  if( sqlite3IsRowid(zColumnName) ){\n    iCol = pTab->iPKey;\n    if( iCol>=0 ){\n      pCol = &pTab->aCol[iCol];\n    }\n  }else{\n    for(iCol=0; iCol<pTab->nCol; iCol++){\n      pCol = &pTab->aCol[iCol];\n      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){\n        break;\n      }\n    }\n    if( iCol==pTab->nCol ){\n      pTab = 0;\n      goto error_out;\n    }\n  }\n\n  /* The following block stores the meta information that will be returned\n  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey\n  ** and autoinc. At this point there are two possibilities:\n  ** \n  **     1. The specified column name was rowid\", \"oid\" or \"_rowid_\" \n  **        and there is no explicitly declared IPK column. \n  **\n  **     2. The table is not a view and the column name identified an \n  **        explicitly declared column. Copy meta information from *pCol.\n  */ \n  if( pCol ){\n    zDataType = pCol->zType;\n    zCollSeq = pCol->zColl;\n    notnull = pCol->notNull!=0;\n    primarykey  = pCol->isPrimKey!=0;\n    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;\n  }else{\n    zDataType = \"INTEGER\";\n    primarykey = 1;\n  }\n  if( !zCollSeq ){\n    zCollSeq = \"BINARY\";\n  }\n\nerror_out:\n  sqlite3BtreeLeaveAll(db);\n\n  /* Whether the function call succeeded or failed, set the output parameters\n  ** to whatever their local counterparts contain. If an error did occur,\n  ** this has the effect of zeroing all output parameters.\n  */\n  if( pzDataType ) *pzDataType = zDataType;\n  if( pzCollSeq ) *pzCollSeq = zCollSeq;\n  if( pNotNull ) *pNotNull = notnull;\n  if( pPrimaryKey ) *pPrimaryKey = primarykey;\n  if( pAutoinc ) *pAutoinc = autoinc;\n\n  if( SQLITE_OK==rc && !pTab ){\n    sqlite3DbFree(db, zErrMsg);\n    zErrMsg = sqlite3MPrintf(db, \"no such table column: %s.%s\", zTableName,\n        zColumnName);\n    rc = SQLITE_ERROR;\n  }\n  sqlite3Error(db, rc, (zErrMsg?\"%s\":0), zErrMsg);\n  sqlite3DbFree(db, zErrMsg);\n  rc = sqlite3ApiExit(db, rc);\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n#endif\n\n/*\n** Sleep for a little while.  Return the amount of time slept.\n*/\nSQLITE_API int sqlite3_sleep(int ms){\n  sqlite3_vfs *pVfs;\n  int rc;\n  pVfs = sqlite3_vfs_find(0);\n  if( pVfs==0 ) return 0;\n\n  /* This function works in milliseconds, but the underlying OsSleep() \n  ** API uses microseconds. Hence the 1000's.\n  */\n  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);\n  return rc;\n}\n\n/*\n** Enable or disable the extended result codes.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){\n  sqlite3_mutex_enter(db->mutex);\n  db->errMask = onoff ? 0xffffffff : 0xff;\n  sqlite3_mutex_leave(db->mutex);\n  return SQLITE_OK;\n}\n\n/*\n** Invoke the xFileControl method on a particular database.\n*/\nSQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){\n  int rc = SQLITE_ERROR;\n  Btree *pBtree;\n\n  sqlite3_mutex_enter(db->mutex);\n  pBtree = sqlite3DbNameToBtree(db, zDbName);\n  if( pBtree ){\n    Pager *pPager;\n    sqlite3_file *fd;\n    sqlite3BtreeEnter(pBtree);\n    pPager = sqlite3BtreePager(pBtree);\n    assert( pPager!=0 );\n    fd = sqlite3PagerFile(pPager);\n    assert( fd!=0 );\n    if( op==SQLITE_FCNTL_FILE_POINTER ){\n      *(sqlite3_file**)pArg = fd;\n      rc = SQLITE_OK;\n    }else if( fd->pMethods ){\n      rc = sqlite3OsFileControl(fd, op, pArg);\n    }else{\n      rc = SQLITE_NOTFOUND;\n    }\n    sqlite3BtreeLeave(pBtree);\n  }\n  sqlite3_mutex_leave(db->mutex);\n  return rc;   \n}\n\n/*\n** Interface to the testing logic.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...){\n  int rc = 0;\n#ifndef SQLITE_OMIT_BUILTIN_TEST\n  va_list ap;\n  va_start(ap, op);\n  switch( op ){\n\n    /*\n    ** Save the current state of the PRNG.\n    */\n    case SQLITE_TESTCTRL_PRNG_SAVE: {\n      sqlite3PrngSaveState();\n      break;\n    }\n\n    /*\n    ** Restore the state of the PRNG to the last state saved using\n    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then\n    ** this verb acts like PRNG_RESET.\n    */\n    case SQLITE_TESTCTRL_PRNG_RESTORE: {\n      sqlite3PrngRestoreState();\n      break;\n    }\n\n    /*\n    ** Reset the PRNG back to its uninitialized state.  The next call\n    ** to sqlite3_randomness() will reseed the PRNG using a single call\n    ** to the xRandomness method of the default VFS.\n    */\n    case SQLITE_TESTCTRL_PRNG_RESET: {\n      sqlite3PrngResetState();\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(BITVEC_TEST, size, program)\n    **\n    ** Run a test against a Bitvec object of size.  The program argument\n    ** is an array of integers that defines the test.  Return -1 on a\n    ** memory allocation error, 0 on success, or non-zero for an error.\n    ** See the sqlite3BitvecBuiltinTest() for additional information.\n    */\n    case SQLITE_TESTCTRL_BITVEC_TEST: {\n      int sz = va_arg(ap, int);\n      int *aProg = va_arg(ap, int*);\n      rc = sqlite3BitvecBuiltinTest(sz, aProg);\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)\n    **\n    ** Register hooks to call to indicate which malloc() failures \n    ** are benign.\n    */\n    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {\n      typedef void (*void_function)(void);\n      void_function xBenignBegin;\n      void_function xBenignEnd;\n      xBenignBegin = va_arg(ap, void_function);\n      xBenignEnd = va_arg(ap, void_function);\n      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)\n    **\n    ** Set the PENDING byte to the value in the argument, if X>0.\n    ** Make no changes if X==0.  Return the value of the pending byte\n    ** as it existing before this routine was called.\n    **\n    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in\n    ** an incompatible database file format.  Changing the PENDING byte\n    ** while any database connection is open results in undefined and\n    ** dileterious behavior.\n    */\n    case SQLITE_TESTCTRL_PENDING_BYTE: {\n      rc = PENDING_BYTE;\n#ifndef SQLITE_OMIT_WSD\n      {\n        unsigned int newVal = va_arg(ap, unsigned int);\n        if( newVal ) sqlite3PendingByte = newVal;\n      }\n#endif\n      break;\n    }\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)\n    **\n    ** This action provides a run-time test to see whether or not\n    ** assert() was enabled at compile-time.  If X is true and assert()\n    ** is enabled, then the return value is true.  If X is true and\n    ** assert() is disabled, then the return value is zero.  If X is\n    ** false and assert() is enabled, then the assertion fires and the\n    ** process aborts.  If X is false and assert() is disabled, then the\n    ** return value is zero.\n    */\n    case SQLITE_TESTCTRL_ASSERT: {\n      volatile int x = 0;\n      assert( (x = va_arg(ap,int))!=0 );\n      rc = x;\n      break;\n    }\n\n\n    /*\n    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)\n    **\n    ** This action provides a run-time test to see how the ALWAYS and\n    ** NEVER macros were defined at compile-time.\n    **\n    ** The return value is ALWAYS(X).  \n    **\n    ** The recommended test is X==2.  If the return value is 2, that means\n    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the\n    ** default setting.  If the return value is 1, then ALWAYS() is either\n    ** hard-coded to true or else it asserts if its argument is false.\n    ** The first behavior (hard-coded to true) is the case if\n    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second\n    ** behavior (assert if the argument to ALWAYS() is false) is the case if\n    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.\n    **\n    ** The run-time test procedure might look something like this:\n    **\n    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){\n    **      // ALWAYS() and NEVER() are no-op pass-through macros\n    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){\n    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.\n    **    }else{\n    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.\n    **    }\n    */\n    case SQLITE_TESTCTRL_ALWAYS: {\n      int x = va_arg(ap,int);\n      rc = ALWAYS(x);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)\n    **\n    ** Set the nReserve size to N for the main database on the database\n    ** connection db.\n    */\n    case SQLITE_TESTCTRL_RESERVE: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      int x = va_arg(ap,int);\n      sqlite3_mutex_enter(db->mutex);\n      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);\n      sqlite3_mutex_leave(db->mutex);\n      break;\n    }\n\n    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)\n    **\n    ** Enable or disable various optimizations for testing purposes.  The \n    ** argument N is a bitmask of optimizations to be disabled.  For normal\n    ** operation N should be 0.  The idea is that a test program (like the\n    ** SQL Logic Test or SLT test module) can run the same SQL multiple times\n    ** with various optimizations disabled to verify that the same answer\n    ** is obtained in every case.\n    */\n    case SQLITE_TESTCTRL_OPTIMIZATIONS: {\n      sqlite3 *db = va_arg(ap, sqlite3*);\n      int x = va_arg(ap,int);\n      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);\n      break;\n    }\n\n#ifdef SQLITE_N_KEYWORD\n    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)\n    **\n    ** If zWord is a keyword recognized by the parser, then return the\n    ** number of keywords.  Or if zWord is not a keyword, return 0.\n    ** \n    ** This test feature is only available in the amalgamation since\n    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite\n    ** is built using separate source files.\n    */\n    case SQLITE_TESTCTRL_ISKEYWORD: {\n      const char *zWord = va_arg(ap, const char*);\n      int n = sqlite3Strlen30(zWord);\n      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;\n      break;\n    }\n#endif \n\n    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);\n    **\n    ** Pass pFree into sqlite3ScratchFree(). \n    ** If sz>0 then allocate a scratch buffer into pNew.  \n    */\n    case SQLITE_TESTCTRL_SCRATCHMALLOC: {\n      void *pFree, **ppNew;\n      int sz;\n      sz = va_arg(ap, int);\n      ppNew = va_arg(ap, void**);\n      pFree = va_arg(ap, void*);\n      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);\n      sqlite3ScratchFree(pFree);\n      break;\n    }\n\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);\n    **\n    ** If parameter onoff is non-zero, configure the wrappers so that all\n    ** subsequent calls to localtime() and variants fail. If onoff is zero,\n    ** undo this setting.\n    */\n    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {\n      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);\n      break;\n    }\n\n#if defined(SQLITE_ENABLE_TREE_EXPLAIN)\n    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,\n    **                        sqlite3_stmt*,const char**);\n    **\n    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds\n    ** a string that describes the optimized parse tree.  This test-control\n    ** returns a pointer to that string.\n    */\n    case SQLITE_TESTCTRL_EXPLAIN_STMT: {\n      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);\n      const char **pzRet = va_arg(ap, const char**);\n      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);\n      break;\n    }\n#endif\n\n  }\n  va_end(ap);\n#endif /* SQLITE_OMIT_BUILTIN_TEST */\n  return rc;\n}\n\n/*\n** This is a utility routine, useful to VFS implementations, that checks\n** to see if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of the query parameter.\n**\n** The zFilename argument is the filename pointer passed into the xOpen()\n** method of a VFS implementation.  The zParam argument is the name of the\n** query parameter we seek.  This routine returns the value of the zParam\n** parameter if it exists.  If the parameter does not exist, this routine\n** returns a NULL pointer.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){\n  if( zFilename==0 ) return 0;\n  zFilename += sqlite3Strlen30(zFilename) + 1;\n  while( zFilename[0] ){\n    int x = strcmp(zFilename, zParam);\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n    if( x==0 ) return zFilename;\n    zFilename += sqlite3Strlen30(zFilename) + 1;\n  }\n  return 0;\n}\n\n/*\n** Return a boolean value for a query parameter.\n*/\nSQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){\n  const char *z = sqlite3_uri_parameter(zFilename, zParam);\n  bDflt = bDflt!=0;\n  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;\n}\n\n/*\n** Return a 64-bit integer value for a query parameter.\n*/\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(\n  const char *zFilename,    /* Filename as passed to xOpen */\n  const char *zParam,       /* URI parameter sought */\n  sqlite3_int64 bDflt       /* return if parameter is missing */\n){\n  const char *z = sqlite3_uri_parameter(zFilename, zParam);\n  sqlite3_int64 v;\n  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){\n    bDflt = v;\n  }\n  return bDflt;\n}\n\n/*\n** Return the Btree pointer identified by zDbName.  Return NULL if not found.\n*/\nSQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){\n  int i;\n  for(i=0; i<db->nDb; i++){\n    if( db->aDb[i].pBt\n     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)\n    ){\n      return db->aDb[i].pBt;\n    }\n  }\n  return 0;\n}\n\n/*\n** Return the filename of the database associated with a database\n** connection.\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){\n  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);\n  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;\n}\n\n/*\n** Return 1 if database is read-only or 0 if read/write.  Return -1 if\n** no such database exists.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){\n  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);\n  return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;\n}\n\n/************** End of main.c ************************************************/\n/************** Begin file notify.c ******************************************/\n/*\n** 2009 March 3\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n**\n** This file contains the implementation of the sqlite3_unlock_notify()\n** API method and its associated functionality.\n*/\n\n/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */\n#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY\n\n/*\n** Public interfaces:\n**\n**   sqlite3ConnectionBlocked()\n**   sqlite3ConnectionUnlocked()\n**   sqlite3ConnectionClosed()\n**   sqlite3_unlock_notify()\n*/\n\n#define assertMutexHeld() \\\n  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )\n\n/*\n** Head of a linked list of all sqlite3 objects created by this process\n** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection\n** is not NULL. This variable may only accessed while the STATIC_MASTER\n** mutex is held.\n*/\nstatic sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;\n\n#ifndef NDEBUG\n/*\n** This function is a complex assert() that verifies the following \n** properties of the blocked connections list:\n**\n**   1) Each entry in the list has a non-NULL value for either \n**      pUnlockConnection or pBlockingConnection, or both.\n**\n**   2) All entries in the list that share a common value for \n**      xUnlockNotify are grouped together.\n**\n**   3) If the argument db is not NULL, then none of the entries in the\n**      blocked connections list have pUnlockConnection or pBlockingConnection\n**      set to db. This is used when closing connection db.\n*/\nstatic void checkListProperties(sqlite3 *db){\n  sqlite3 *p;\n  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){\n    int seen = 0;\n    sqlite3 *p2;\n\n    /* Verify property (1) */\n    assert( p->pUnlockConnection || p->pBlockingConnection );\n\n    /* Verify property (2) */\n    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){\n      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;\n      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );\n      assert( db==0 || p->pUnlockConnection!=db );\n      assert( db==0 || p->pBlockingConnection!=db );\n    }\n  }\n}\n#else\n# define checkListProperties(x)\n#endif\n\n/*\n** Remove connection db from the blocked connections list. If connection\n** db is not currently a part of the list, this function is a no-op.\n*/\nstatic void removeFromBlockedList(sqlite3 *db){\n  sqlite3 **pp;\n  assertMutexHeld();\n  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){\n    if( *pp==db ){\n      *pp = (*pp)->pNextBlocked;\n      break;\n    }\n  }\n}\n\n/*\n** Add connection db to the blocked connections list. It is assumed\n** that it is not already a part of the list.\n*/\nstatic void addToBlockedList(sqlite3 *db){\n  sqlite3 **pp;\n  assertMutexHeld();\n  for(\n    pp=&sqlite3BlockedList; \n    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; \n    pp=&(*pp)->pNextBlocked\n  );\n  db->pNextBlocked = *pp;\n  *pp = db;\n}\n\n/*\n** Obtain the STATIC_MASTER mutex.\n*/\nstatic void enterMutex(void){\n  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n  checkListProperties(0);\n}\n\n/*\n** Release the STATIC_MASTER mutex.\n*/\nstatic void leaveMutex(void){\n  assertMutexHeld();\n  checkListProperties(0);\n  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));\n}\n\n/*\n** Register an unlock-notify callback.\n**\n** This is called after connection \"db\" has attempted some operation\n** but has received an SQLITE_LOCKED error because another connection\n** (call it pOther) in the same process was busy using the same shared\n** cache.  pOther is found by looking at db->pBlockingConnection.\n**\n** If there is no blocking connection, the callback is invoked immediately,\n** before this routine returns.\n**\n** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate\n** a deadlock.\n**\n** Otherwise, make arrangements to invoke xNotify when pOther drops\n** its locks.\n**\n** Each call to this routine overrides any prior callbacks registered\n** on the same \"db\".  If xNotify==0 then any prior callbacks are immediately\n** cancelled.\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *db,\n  void (*xNotify)(void **, int),\n  void *pArg\n){\n  int rc = SQLITE_OK;\n\n  sqlite3_mutex_enter(db->mutex);\n  enterMutex();\n\n  if( xNotify==0 ){\n    removeFromBlockedList(db);\n    db->pBlockingConnection = 0;\n    db->pUnlockConnection = 0;\n    db->xUnlockNotify = 0;\n    db->pUnlockArg = 0;\n  }else if( 0==db->pBlockingConnection ){\n    /* The blocking transaction has been concluded. Or there never was a \n    ** blocking transaction. In either case, invoke the notify callback\n    ** immediately. \n    */\n    xNotify(&pArg, 1);\n  }else{\n    sqlite3 *p;\n\n    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}\n    if( p ){\n      rc = SQLITE_LOCKED;              /* Deadlock detected. */\n    }else{\n      db->pUnlockConnection = db->pBlockingConnection;\n      db->xUnlockNotify = xNotify;\n      db->pUnlockArg = pArg;\n      removeFromBlockedList(db);\n      addToBlockedList(db);\n    }\n  }\n\n  leaveMutex();\n  assert( !db->mallocFailed );\n  sqlite3Error(db, rc, (rc?\"database is deadlocked\":0));\n  sqlite3_mutex_leave(db->mutex);\n  return rc;\n}\n\n/*\n** This function is called while stepping or preparing a statement \n** associated with connection db. The operation will return SQLITE_LOCKED\n** to the user because it requires a lock that will not be available\n** until connection pBlocker concludes its current transaction.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){\n  enterMutex();\n  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){\n    addToBlockedList(db);\n  }\n  db->pBlockingConnection = pBlocker;\n  leaveMutex();\n}\n\n/*\n** This function is called when\n** the transaction opened by database db has just finished. Locks held \n** by database connection db have been released.\n**\n** This function loops through each entry in the blocked connections\n** list and does the following:\n**\n**   1) If the sqlite3.pBlockingConnection member of a list entry is\n**      set to db, then set pBlockingConnection=0.\n**\n**   2) If the sqlite3.pUnlockConnection member of a list entry is\n**      set to db, then invoke the configured unlock-notify callback and\n**      set pUnlockConnection=0.\n**\n**   3) If the two steps above mean that pBlockingConnection==0 and\n**      pUnlockConnection==0, remove the entry from the blocked connections\n**      list.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){\n  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */\n  int nArg = 0;                            /* Number of entries in aArg[] */\n  sqlite3 **pp;                            /* Iterator variable */\n  void **aArg;               /* Arguments to the unlock callback */\n  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */\n  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */\n\n  aArg = aStatic;\n  enterMutex();         /* Enter STATIC_MASTER mutex */\n\n  /* This loop runs once for each entry in the blocked-connections list. */\n  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){\n    sqlite3 *p = *pp;\n\n    /* Step 1. */\n    if( p->pBlockingConnection==db ){\n      p->pBlockingConnection = 0;\n    }\n\n    /* Step 2. */\n    if( p->pUnlockConnection==db ){\n      assert( p->xUnlockNotify );\n      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){\n        xUnlockNotify(aArg, nArg);\n        nArg = 0;\n      }\n\n      sqlite3BeginBenignMalloc();\n      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );\n      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );\n      if( (!aDyn && nArg==(int)ArraySize(aStatic))\n       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))\n      ){\n        /* The aArg[] array needs to grow. */\n        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);\n        if( pNew ){\n          memcpy(pNew, aArg, nArg*sizeof(void *));\n          sqlite3_free(aDyn);\n          aDyn = aArg = pNew;\n        }else{\n          /* This occurs when the array of context pointers that need to\n          ** be passed to the unlock-notify callback is larger than the\n          ** aStatic[] array allocated on the stack and the attempt to \n          ** allocate a larger array from the heap has failed.\n          **\n          ** This is a difficult situation to handle. Returning an error\n          ** code to the caller is insufficient, as even if an error code\n          ** is returned the transaction on connection db will still be\n          ** closed and the unlock-notify callbacks on blocked connections\n          ** will go unissued. This might cause the application to wait\n          ** indefinitely for an unlock-notify callback that will never \n          ** arrive.\n          **\n          ** Instead, invoke the unlock-notify callback with the context\n          ** array already accumulated. We can then clear the array and\n          ** begin accumulating any further context pointers without \n          ** requiring any dynamic allocation. This is sub-optimal because\n          ** it means that instead of one callback with a large array of\n          ** context pointers the application will receive two or more\n          ** callbacks with smaller arrays of context pointers, which will\n          ** reduce the applications ability to prioritize multiple \n          ** connections. But it is the best that can be done under the\n          ** circumstances.\n          */\n          xUnlockNotify(aArg, nArg);\n          nArg = 0;\n        }\n      }\n      sqlite3EndBenignMalloc();\n\n      aArg[nArg++] = p->pUnlockArg;\n      xUnlockNotify = p->xUnlockNotify;\n      p->pUnlockConnection = 0;\n      p->xUnlockNotify = 0;\n      p->pUnlockArg = 0;\n    }\n\n    /* Step 3. */\n    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){\n      /* Remove connection p from the blocked connections list. */\n      *pp = p->pNextBlocked;\n      p->pNextBlocked = 0;\n    }else{\n      pp = &p->pNextBlocked;\n    }\n  }\n\n  if( nArg!=0 ){\n    xUnlockNotify(aArg, nArg);\n  }\n  sqlite3_free(aDyn);\n  leaveMutex();         /* Leave STATIC_MASTER mutex */\n}\n\n/*\n** This is called when the database connection passed as an argument is \n** being closed. The connection is removed from the blocked list.\n*/\nSQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){\n  sqlite3ConnectionUnlocked(db);\n  enterMutex();\n  removeFromBlockedList(db);\n  checkListProperties(db);\n  leaveMutex();\n}\n#endif\n\n/************** End of notify.c **********************************************/\n/************** Begin file fts3.c ********************************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is an SQLite module implementing full-text search.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n\n/* The full-text index is stored in a series of b+tree (-like)\n** structures called segments which map terms to doclists.  The\n** structures are like b+trees in layout, but are constructed from the\n** bottom up in optimal fashion and are not updatable.  Since trees\n** are built from the bottom up, things will be described from the\n** bottom up.\n**\n**\n**** Varints ****\n** The basic unit of encoding is a variable-length integer called a\n** varint.  We encode variable-length integers in little-endian order\n** using seven bits * per byte as follows:\n**\n** KEY:\n**         A = 0xxxxxxx    7 bits of data and one flag bit\n**         B = 1xxxxxxx    7 bits of data and one flag bit\n**\n**  7 bits - A\n** 14 bits - BA\n** 21 bits - BBA\n** and so on.\n**\n** This is similar in concept to how sqlite encodes \"varints\" but\n** the encoding is not the same.  SQLite varints are big-endian\n** are are limited to 9 bytes in length whereas FTS3 varints are\n** little-endian and can be up to 10 bytes in length (in theory).\n**\n** Example encodings:\n**\n**     1:    0x01\n**   127:    0x7f\n**   128:    0x81 0x00\n**\n**\n**** Document lists ****\n** A doclist (document list) holds a docid-sorted list of hits for a\n** given term.  Doclists hold docids and associated token positions.\n** A docid is the unique integer identifier for a single document.\n** A position is the index of a word within the document.  The first \n** word of the document has a position of 0.\n**\n** FTS3 used to optionally store character offsets using a compile-time\n** option.  But that functionality is no longer supported.\n**\n** A doclist is stored like this:\n**\n** array {\n**   varint docid;          (delta from previous doclist)\n**   array {                (position list for column 0)\n**     varint position;     (2 more than the delta from previous position)\n**   }\n**   array {\n**     varint POS_COLUMN;   (marks start of position list for new column)\n**     varint column;       (index of new column)\n**     array {\n**       varint position;   (2 more than the delta from previous position)\n**     }\n**   }\n**   varint POS_END;        (marks end of positions for this document.\n** }\n**\n** Here, array { X } means zero or more occurrences of X, adjacent in\n** memory.  A \"position\" is an index of a token in the token stream\n** generated by the tokenizer. Note that POS_END and POS_COLUMN occur \n** in the same logical place as the position element, and act as sentinals\n** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.\n** The positions numbers are not stored literally but rather as two more\n** than the difference from the prior position, or the just the position plus\n** 2 for the first position.  Example:\n**\n**   label:       A B C D E  F  G H   I  J K\n**   value:     123 5 9 1 1 14 35 0 234 72 0\n**\n** The 123 value is the first docid.  For column zero in this document\n** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1\n** at D signals the start of a new column; the 1 at E indicates that the\n** new column is column number 1.  There are two positions at 12 and 45\n** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The\n** 234 at I is the delta to next docid (357).  It has one position 70\n** (72-2) and then terminates with the 0 at K.\n**\n** A \"position-list\" is the list of positions for multiple columns for\n** a single docid.  A \"column-list\" is the set of positions for a single\n** column.  Hence, a position-list consists of one or more column-lists,\n** a document record consists of a docid followed by a position-list and\n** a doclist consists of one or more document records.\n**\n** A bare doclist omits the position information, becoming an \n** array of varint-encoded docids.\n**\n**** Segment leaf nodes ****\n** Segment leaf nodes store terms and doclists, ordered by term.  Leaf\n** nodes are written using LeafWriter, and read using LeafReader (to\n** iterate through a single leaf node's data) and LeavesReader (to\n** iterate through a segment's entire leaf layer).  Leaf nodes have\n** the format:\n**\n** varint iHeight;             (height from leaf level, always 0)\n** varint nTerm;               (length of first term)\n** char pTerm[nTerm];          (content of first term)\n** varint nDoclist;            (length of term's associated doclist)\n** char pDoclist[nDoclist];    (content of doclist)\n** array {\n**                             (further terms are delta-encoded)\n**   varint nPrefix;           (length of prefix shared with previous term)\n**   varint nSuffix;           (length of unshared suffix)\n**   char pTermSuffix[nSuffix];(unshared suffix of next term)\n**   varint nDoclist;          (length of term's associated doclist)\n**   char pDoclist[nDoclist];  (content of doclist)\n** }\n**\n** Here, array { X } means zero or more occurrences of X, adjacent in\n** memory.\n**\n** Leaf nodes are broken into blocks which are stored contiguously in\n** the %_segments table in sorted order.  This means that when the end\n** of a node is reached, the next term is in the node with the next\n** greater node id.\n**\n** New data is spilled to a new leaf node when the current node\n** exceeds LEAF_MAX bytes (default 2048).  New data which itself is\n** larger than STANDALONE_MIN (default 1024) is placed in a standalone\n** node (a leaf node with a single term and doclist).  The goal of\n** these settings is to pack together groups of small doclists while\n** making it efficient to directly access large doclists.  The\n** assumption is that large doclists represent terms which are more\n** likely to be query targets.\n**\n** TODO(shess) It may be useful for blocking decisions to be more\n** dynamic.  For instance, it may make more sense to have a 2.5k leaf\n** node rather than splitting into 2k and .5k nodes.  My intuition is\n** that this might extend through 2x or 4x the pagesize.\n**\n**\n**** Segment interior nodes ****\n** Segment interior nodes store blockids for subtree nodes and terms\n** to describe what data is stored by the each subtree.  Interior\n** nodes are written using InteriorWriter, and read using\n** InteriorReader.  InteriorWriters are created as needed when\n** SegmentWriter creates new leaf nodes, or when an interior node\n** itself grows too big and must be split.  The format of interior\n** nodes:\n**\n** varint iHeight;           (height from leaf level, always >0)\n** varint iBlockid;          (block id of node's leftmost subtree)\n** optional {\n**   varint nTerm;           (length of first term)\n**   char pTerm[nTerm];      (content of first term)\n**   array {\n**                                (further terms are delta-encoded)\n**     varint nPrefix;            (length of shared prefix with previous term)\n**     varint nSuffix;            (length of unshared suffix)\n**     char pTermSuffix[nSuffix]; (unshared suffix of next term)\n**   }\n** }\n**\n** Here, optional { X } means an optional element, while array { X }\n** means zero or more occurrences of X, adjacent in memory.\n**\n** An interior node encodes n terms separating n+1 subtrees.  The\n** subtree blocks are contiguous, so only the first subtree's blockid\n** is encoded.  The subtree at iBlockid will contain all terms less\n** than the first term encoded (or all terms if no term is encoded).\n** Otherwise, for terms greater than or equal to pTerm[i] but less\n** than pTerm[i+1], the subtree for that term will be rooted at\n** iBlockid+i.  Interior nodes only store enough term data to\n** distinguish adjacent children (if the rightmost term of the left\n** child is \"something\", and the leftmost term of the right child is\n** \"wicked\", only \"w\" is stored).\n**\n** New data is spilled to a new interior node at the same height when\n** the current node exceeds INTERIOR_MAX bytes (default 2048).\n** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing\n** interior nodes and making the tree too skinny.  The interior nodes\n** at a given height are naturally tracked by interior nodes at\n** height+1, and so on.\n**\n**\n**** Segment directory ****\n** The segment directory in table %_segdir stores meta-information for\n** merging and deleting segments, and also the root node of the\n** segment's tree.\n**\n** The root node is the top node of the segment's tree after encoding\n** the entire segment, restricted to ROOT_MAX bytes (default 1024).\n** This could be either a leaf node or an interior node.  If the top\n** node requires more than ROOT_MAX bytes, it is flushed to %_segments\n** and a new root interior node is generated (which should always fit\n** within ROOT_MAX because it only needs space for 2 varints, the\n** height and the blockid of the previous root).\n**\n** The meta-information in the segment directory is:\n**   level               - segment level (see below)\n**   idx                 - index within level\n**                       - (level,idx uniquely identify a segment)\n**   start_block         - first leaf node\n**   leaves_end_block    - last leaf node\n**   end_block           - last block (including interior nodes)\n**   root                - contents of root node\n**\n** If the root node is a leaf node, then start_block,\n** leaves_end_block, and end_block are all 0.\n**\n**\n**** Segment merging ****\n** To amortize update costs, segments are grouped into levels and\n** merged in batches.  Each increase in level represents exponentially\n** more documents.\n**\n** New documents (actually, document updates) are tokenized and\n** written individually (using LeafWriter) to a level 0 segment, with\n** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all\n** level 0 segments are merged into a single level 1 segment.  Level 1\n** is populated like level 0, and eventually MERGE_COUNT level 1\n** segments are merged to a single level 2 segment (representing\n** MERGE_COUNT^2 updates), and so on.\n**\n** A segment merge traverses all segments at a given level in\n** parallel, performing a straightforward sorted merge.  Since segment\n** leaf nodes are written in to the %_segments table in order, this\n** merge traverses the underlying sqlite disk structures efficiently.\n** After the merge, all segment blocks from the merged level are\n** deleted.\n**\n** MERGE_COUNT controls how often we merge segments.  16 seems to be\n** somewhat of a sweet spot for insertion performance.  32 and 64 show\n** very similar performance numbers to 16 on insertion, though they're\n** a tiny bit slower (perhaps due to more overhead in merge-time\n** sorting).  8 is about 20% slower than 16, 4 about 50% slower than\n** 16, 2 about 66% slower than 16.\n**\n** At query time, high MERGE_COUNT increases the number of segments\n** which need to be scanned and merged.  For instance, with 100k docs\n** inserted:\n**\n**    MERGE_COUNT   segments\n**       16           25\n**        8           12\n**        4           10\n**        2            6\n**\n** This appears to have only a moderate impact on queries for very\n** frequent terms (which are somewhat dominated by segment merge\n** costs), and infrequent and non-existent terms still seem to be fast\n** even with many segments.\n**\n** TODO(shess) That said, it would be nice to have a better query-side\n** argument for MERGE_COUNT of 16.  Also, it is possible/likely that\n** optimizations to things like doclist merging will swing the sweet\n** spot around.\n**\n**\n**\n**** Handling of deletions and updates ****\n** Since we're using a segmented structure, with no docid-oriented\n** index into the term index, we clearly cannot simply update the term\n** index when a document is deleted or updated.  For deletions, we\n** write an empty doclist (varint(docid) varint(POS_END)), for updates\n** we simply write the new doclist.  Segment merges overwrite older\n** data for a particular docid with newer data, so deletes or updates\n** will eventually overtake the earlier data and knock it out.  The\n** query logic likewise merges doclists so that newer data knocks out\n** older data.\n*/\n\n/************** Include fts3Int.h in the middle of fts3.c ********************/\n/************** Begin file fts3Int.h *****************************************/\n/*\n** 2009 Nov 12\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n#ifndef _FTSINT_H\n#define _FTSINT_H\n\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n\n/*\n** FTS4 is really an extension for FTS3.  It is enabled using the\n** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all\n** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.\n*/\n#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)\n# define SQLITE_ENABLE_FTS3\n#endif\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* If not building as part of the core, include sqlite3ext.h. */\n#ifndef SQLITE_CORE\nSQLITE_API extern const sqlite3_api_routines *sqlite3_api;\n#endif\n\n/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/\n/************** Begin file fts3_tokenizer.h **********************************/\n/*\n** 2006 July 10\n**\n** The author disclaims copyright to this source code.\n**\n*************************************************************************\n** Defines the interface to tokenizers used by fulltext-search.  There\n** are three basic components:\n**\n** sqlite3_tokenizer_module is a singleton defining the tokenizer\n** interface functions.  This is essentially the class structure for\n** tokenizers.\n**\n** sqlite3_tokenizer is used to define a particular tokenizer, perhaps\n** including customization information defined at creation time.\n**\n** sqlite3_tokenizer_cursor is generated by a tokenizer to generate\n** tokens from a particular input.\n*/\n#ifndef _FTS3_TOKENIZER_H_\n#define _FTS3_TOKENIZER_H_\n\n/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.\n** If tokenizers are to be allowed to call sqlite3_*() functions, then\n** we will need a way to register the API consistently.\n*/\n\n/*\n** Structures used by the tokenizer interface. When a new tokenizer\n** implementation is registered, the caller provides a pointer to\n** an sqlite3_tokenizer_module containing pointers to the callback\n** functions that make up an implementation.\n**\n** When an fts3 table is created, it passes any arguments passed to\n** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the\n** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer\n** implementation. The xCreate() function in turn returns an \n** sqlite3_tokenizer structure representing the specific tokenizer to\n** be used for the fts3 table (customized by the tokenizer clause arguments).\n**\n** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()\n** method is called. It returns an sqlite3_tokenizer_cursor object\n** that may be used to tokenize a specific input buffer based on\n** the tokenization rules supplied by a specific sqlite3_tokenizer\n** object.\n*/\ntypedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;\ntypedef struct sqlite3_tokenizer sqlite3_tokenizer;\ntypedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;\n\nstruct sqlite3_tokenizer_module {\n\n  /*\n  ** Structure version. Should always be set to 0 or 1.\n  */\n  int iVersion;\n\n  /*\n  ** Create a new tokenizer. The values in the argv[] array are the\n  ** arguments passed to the \"tokenizer\" clause of the CREATE VIRTUAL\n  ** TABLE statement that created the fts3 table. For example, if\n  ** the following SQL is executed:\n  **\n  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)\n  **\n  ** then argc is set to 2, and the argv[] array contains pointers\n  ** to the strings \"arg1\" and \"arg2\".\n  **\n  ** This method should return either SQLITE_OK (0), or an SQLite error \n  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set\n  ** to point at the newly created tokenizer structure. The generic\n  ** sqlite3_tokenizer.pModule variable should not be initialised by\n  ** this callback. The caller will do so.\n  */\n  int (*xCreate)(\n    int argc,                           /* Size of argv array */\n    const char *const*argv,             /* Tokenizer argument strings */\n    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */\n  );\n\n  /*\n  ** Destroy an existing tokenizer. The fts3 module calls this method\n  ** exactly once for each successful call to xCreate().\n  */\n  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);\n\n  /*\n  ** Create a tokenizer cursor to tokenize an input buffer. The caller\n  ** is responsible for ensuring that the input buffer remains valid\n  ** until the cursor is closed (using the xClose() method). \n  */\n  int (*xOpen)(\n    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */\n    const char *pInput, int nBytes,      /* Input buffer */\n    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */\n  );\n\n  /*\n  ** Destroy an existing tokenizer cursor. The fts3 module calls this \n  ** method exactly once for each successful call to xOpen().\n  */\n  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);\n\n  /*\n  ** Retrieve the next token from the tokenizer cursor pCursor. This\n  ** method should either return SQLITE_OK and set the values of the\n  ** \"OUT\" variables identified below, or SQLITE_DONE to indicate that\n  ** the end of the buffer has been reached, or an SQLite error code.\n  **\n  ** *ppToken should be set to point at a buffer containing the \n  ** normalized version of the token (i.e. after any case-folding and/or\n  ** stemming has been performed). *pnBytes should be set to the length\n  ** of this buffer in bytes. The input text that generated the token is\n  ** identified by the byte offsets returned in *piStartOffset and\n  ** *piEndOffset. *piStartOffset should be set to the index of the first\n  ** byte of the token in the input buffer. *piEndOffset should be set\n  ** to the index of the first byte just past the end of the token in\n  ** the input buffer.\n  **\n  ** The buffer *ppToken is set to point at is managed by the tokenizer\n  ** implementation. It is only required to be valid until the next call\n  ** to xNext() or xClose(). \n  */\n  /* TODO(shess) current implementation requires pInput to be\n  ** nul-terminated.  This should either be fixed, or pInput/nBytes\n  ** should be converted to zInput.\n  */\n  int (*xNext)(\n    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */\n    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */\n    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */\n    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */\n    int *piPosition      /* OUT: Number of tokens returned before this one */\n  );\n\n  /***********************************************************************\n  ** Methods below this point are only available if iVersion>=1.\n  */\n\n  /* \n  ** Configure the language id of a tokenizer cursor.\n  */\n  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);\n};\n\nstruct sqlite3_tokenizer {\n  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */\n  /* Tokenizer implementations will typically add additional fields */\n};\n\nstruct sqlite3_tokenizer_cursor {\n  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */\n  /* Tokenizer implementations will typically add additional fields */\n};\n\nint fts3_global_term_cnt(int iTerm, int iCol);\nint fts3_term_cnt(int iTerm, int iCol);\n\n\n#endif /* _FTS3_TOKENIZER_H_ */\n\n/************** End of fts3_tokenizer.h **************************************/\n/************** Continuing where we left off in fts3Int.h ********************/\n/************** Include fts3_hash.h in the middle of fts3Int.h ***************/\n/************** Begin file fts3_hash.h ***************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the header file for the generic hash-table implemenation\n** used in SQLite.  We've modified it slightly to serve as a standalone\n** hash table implementation for the full-text indexing module.\n**\n*/\n#ifndef _FTS3_HASH_H_\n#define _FTS3_HASH_H_\n\n/* Forward declarations of structures. */\ntypedef struct Fts3Hash Fts3Hash;\ntypedef struct Fts3HashElem Fts3HashElem;\n\n/* A complete hash table is an instance of the following structure.\n** The internals of this structure are intended to be opaque -- client\n** code should not attempt to access or modify the fields of this structure\n** directly.  Change this structure only by using the routines below.\n** However, many of the \"procedures\" and \"functions\" for modifying and\n** accessing this structure are really macros, so we can't really make\n** this structure opaque.\n*/\nstruct Fts3Hash {\n  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */\n  char copyKey;           /* True if copy of key made on insert */\n  int count;              /* Number of entries in this table */\n  Fts3HashElem *first;    /* The first element of the array */\n  int htsize;             /* Number of buckets in the hash table */\n  struct _fts3ht {        /* the hash table */\n    int count;               /* Number of entries with this hash */\n    Fts3HashElem *chain;     /* Pointer to first entry with this hash */\n  } *ht;\n};\n\n/* Each element in the hash table is an instance of the following \n** structure.  All elements are stored on a single doubly-linked list.\n**\n** Again, this structure is intended to be opaque, but it can't really\n** be opaque because it is used by macros.\n*/\nstruct Fts3HashElem {\n  Fts3HashElem *next, *prev; /* Next and previous elements in the table */\n  void *data;                /* Data associated with this element */\n  void *pKey; int nKey;      /* Key associated with this element */\n};\n\n/*\n** There are 2 different modes of operation for a hash table:\n**\n**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long\n**                           (including the null-terminator, if any).  Case\n**                           is respected in comparisons.\n**\n**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. \n**                           memcmp() is used to compare keys.\n**\n** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  \n*/\n#define FTS3_HASH_STRING    1\n#define FTS3_HASH_BINARY    2\n\n/*\n** Access routines.  To delete, insert a NULL pointer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);\nSQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);\nSQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);\nSQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);\nSQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);\n\n/*\n** Shorthand for the functions above\n*/\n#define fts3HashInit     sqlite3Fts3HashInit\n#define fts3HashInsert   sqlite3Fts3HashInsert\n#define fts3HashFind     sqlite3Fts3HashFind\n#define fts3HashClear    sqlite3Fts3HashClear\n#define fts3HashFindElem sqlite3Fts3HashFindElem\n\n/*\n** Macros for looping over all elements of a hash table.  The idiom is\n** like this:\n**\n**   Fts3Hash h;\n**   Fts3HashElem *p;\n**   ...\n**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){\n**     SomeStructure *pData = fts3HashData(p);\n**     // do something with pData\n**   }\n*/\n#define fts3HashFirst(H)  ((H)->first)\n#define fts3HashNext(E)   ((E)->next)\n#define fts3HashData(E)   ((E)->data)\n#define fts3HashKey(E)    ((E)->pKey)\n#define fts3HashKeysize(E) ((E)->nKey)\n\n/*\n** Number of entries in a hash table\n*/\n#define fts3HashCount(H)  ((H)->count)\n\n#endif /* _FTS3_HASH_H_ */\n\n/************** End of fts3_hash.h *******************************************/\n/************** Continuing where we left off in fts3Int.h ********************/\n\n/*\n** This constant controls how often segments are merged. Once there are\n** FTS3_MERGE_COUNT segments of level N, they are merged into a single\n** segment of level N+1.\n*/\n#define FTS3_MERGE_COUNT 16\n\n/*\n** This is the maximum amount of data (in bytes) to store in the \n** Fts3Table.pendingTerms hash table. Normally, the hash table is\n** populated as documents are inserted/updated/deleted in a transaction\n** and used to create a new segment when the transaction is committed.\n** However if this limit is reached midway through a transaction, a new \n** segment is created and the hash table cleared immediately.\n*/\n#define FTS3_MAX_PENDING_DATA (1*1024*1024)\n\n/*\n** Macro to return the number of elements in an array. SQLite has a\n** similar macro called ArraySize(). Use a different name to avoid\n** a collision when building an amalgamation with built-in FTS3.\n*/\n#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))\n\n\n#ifndef MIN\n# define MIN(x,y) ((x)<(y)?(x):(y))\n#endif\n#ifndef MAX\n# define MAX(x,y) ((x)>(y)?(x):(y))\n#endif\n\n/*\n** Maximum length of a varint encoded integer. The varint format is different\n** from that used by SQLite, so the maximum length is 10, not 9.\n*/\n#define FTS3_VARINT_MAX 10\n\n/*\n** FTS4 virtual tables may maintain multiple indexes - one index of all terms\n** in the document set and zero or more prefix indexes. All indexes are stored\n** as one or more b+-trees in the %_segments and %_segdir tables. \n**\n** It is possible to determine which index a b+-tree belongs to based on the\n** value stored in the \"%_segdir.level\" column. Given this value L, the index\n** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with\n** level values between 0 and 1023 (inclusive) belong to index 0, all levels\n** between 1024 and 2047 to index 1, and so on.\n**\n** It is considered impossible for an index to use more than 1024 levels. In \n** theory though this may happen, but only after at least \n** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.\n*/\n#define FTS3_SEGDIR_MAXLEVEL      1024\n#define FTS3_SEGDIR_MAXLEVEL_STR \"1024\"\n\n/*\n** The testcase() macro is only used by the amalgamation.  If undefined,\n** make it a no-op.\n*/\n#ifndef testcase\n# define testcase(X)\n#endif\n\n/*\n** Terminator values for position-lists and column-lists.\n*/\n#define POS_COLUMN  (1)     /* Column-list terminator */\n#define POS_END     (0)     /* Position-list terminator */ \n\n/*\n** This section provides definitions to allow the\n** FTS3 extension to be compiled outside of the \n** amalgamation.\n*/\n#ifndef SQLITE_AMALGAMATION\n/*\n** Macros indicating that conditional expressions are always true or\n** false.\n*/\n#ifdef SQLITE_COVERAGE_TEST\n# define ALWAYS(x) (1)\n# define NEVER(X)  (0)\n#else\n# define ALWAYS(x) (x)\n# define NEVER(x)  (x)\n#endif\n\n/*\n** Internal types used by SQLite.\n*/\ntypedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */\ntypedef short int i16;            /* 2-byte (or larger) signed integer */\ntypedef unsigned int u32;         /* 4-byte unsigned integer */\ntypedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */\ntypedef sqlite3_int64 i64;        /* 8-byte signed integer */\n\n/*\n** Macro used to suppress compiler warnings for unused parameters.\n*/\n#define UNUSED_PARAMETER(x) (void)(x)\n\n/*\n** Activate assert() only if SQLITE_TEST is enabled.\n*/\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n\n/*\n** The TESTONLY macro is used to enclose variable declarations or\n** other bits of code that are needed to support the arguments\n** within testcase() and assert() macros.\n*/\n#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)\n# define TESTONLY(X)  X\n#else\n# define TESTONLY(X)\n#endif\n\n#endif /* SQLITE_AMALGAMATION */\n\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3Fts3Corrupt(void);\n# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()\n#else\n# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB\n#endif\n\ntypedef struct Fts3Table Fts3Table;\ntypedef struct Fts3Cursor Fts3Cursor;\ntypedef struct Fts3Expr Fts3Expr;\ntypedef struct Fts3Phrase Fts3Phrase;\ntypedef struct Fts3PhraseToken Fts3PhraseToken;\n\ntypedef struct Fts3Doclist Fts3Doclist;\ntypedef struct Fts3SegFilter Fts3SegFilter;\ntypedef struct Fts3DeferredToken Fts3DeferredToken;\ntypedef struct Fts3SegReader Fts3SegReader;\ntypedef struct Fts3MultiSegReader Fts3MultiSegReader;\n\n/*\n** A connection to a fulltext index is an instance of the following\n** structure. The xCreate and xConnect methods create an instance\n** of this structure and xDestroy and xDisconnect free that instance.\n** All other methods receive a pointer to the structure as one of their\n** arguments.\n*/\nstruct Fts3Table {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  sqlite3 *db;                    /* The database connection */\n  const char *zDb;                /* logical database name */\n  const char *zName;              /* virtual table name */\n  int nColumn;                    /* number of named columns in virtual table */\n  char **azColumn;                /* column names.  malloced */\n  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */\n  char *zContentTbl;              /* content=xxx option, or NULL */\n  char *zLanguageid;              /* languageid=xxx option, or NULL */\n  u8 bAutoincrmerge;              /* True if automerge=1 */\n  u32 nLeafAdd;                   /* Number of leaf blocks added this trans */\n\n  /* Precompiled statements used by the implementation. Each of these \n  ** statements is run and reset within a single virtual table API call. \n  */\n  sqlite3_stmt *aStmt[37];\n\n  char *zReadExprlist;\n  char *zWriteExprlist;\n\n  int nNodeSize;                  /* Soft limit for node size */\n  u8 bFts4;                       /* True for FTS4, false for FTS3 */\n  u8 bHasStat;                    /* True if %_stat table exists */\n  u8 bHasDocsize;                 /* True if %_docsize table exists */\n  u8 bDescIdx;                    /* True if doclists are in reverse order */\n  u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */\n  int nPgsz;                      /* Page size for host database */\n  char *zSegmentsTbl;             /* Name of %_segments table */\n  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */\n\n  /* \n  ** The following array of hash tables is used to buffer pending index \n  ** updates during transactions. All pending updates buffered at any one\n  ** time must share a common language-id (see the FTS4 langid= feature).\n  ** The current language id is stored in variable iPrevLangid.\n  **\n  ** A single FTS4 table may have multiple full-text indexes. For each index\n  ** there is an entry in the aIndex[] array. Index 0 is an index of all the\n  ** terms that appear in the document set. Each subsequent index in aIndex[]\n  ** is an index of prefixes of a specific length.\n  **\n  ** Variable nPendingData contains an estimate the memory consumed by the \n  ** pending data structures, including hash table overhead, but not including\n  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash\n  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most \n  ** recently inserted record.\n  */\n  int nIndex;                     /* Size of aIndex[] */\n  struct Fts3Index {\n    int nPrefix;                  /* Prefix length (0 for main terms index) */\n    Fts3Hash hPending;            /* Pending terms table for this index */\n  } *aIndex;\n  int nMaxPendingData;            /* Max pending data before flush to disk */\n  int nPendingData;               /* Current bytes of pending data */\n  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */\n  int iPrevLangid;                /* Langid of recently inserted document */\n\n#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)\n  /* State variables used for validating that the transaction control\n  ** methods of the virtual table are called at appropriate times.  These\n  ** values do not contribute to FTS functionality; they are used for\n  ** verifying the operation of the SQLite core.\n  */\n  int inTransaction;     /* True after xBegin but before xCommit/xRollback */\n  int mxSavepoint;       /* Largest valid xSavepoint integer */\n#endif\n};\n\n/*\n** When the core wants to read from the virtual table, it creates a\n** virtual table cursor (an instance of the following structure) using\n** the xOpen method. Cursors are destroyed using the xClose method.\n*/\nstruct Fts3Cursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  i16 eSearch;                    /* Search strategy (see below) */\n  u8 isEof;                       /* True if at End Of Results */\n  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */\n  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */\n  Fts3Expr *pExpr;                /* Parsed MATCH query string */\n  int iLangid;                    /* Language being queried for */\n  int nPhrase;                    /* Number of matchable phrases in query */\n  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */\n  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */\n  char *pNextId;                  /* Pointer into the body of aDoclist */\n  char *aDoclist;                 /* List of docids for full-text queries */\n  int nDoclist;                   /* Size of buffer at aDoclist */\n  u8 bDesc;                       /* True to sort in descending order */\n  int eEvalmode;                  /* An FTS3_EVAL_XX constant */\n  int nRowAvg;                    /* Average size of database rows, in pages */\n  sqlite3_int64 nDoc;             /* Documents in table */\n\n  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */\n  u32 *aMatchinfo;                /* Information about most recent match */\n  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */\n  char *zMatchinfo;               /* Matchinfo specification */\n};\n\n#define FTS3_EVAL_FILTER    0\n#define FTS3_EVAL_NEXT      1\n#define FTS3_EVAL_MATCHINFO 2\n\n/*\n** The Fts3Cursor.eSearch member is always set to one of the following.\n** Actualy, Fts3Cursor.eSearch can be greater than or equal to\n** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index\n** of the column to be searched.  For example, in\n**\n**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);\n**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';\n** \n** Because the LHS of the MATCH operator is 2nd column \"b\",\n** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,\n** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were \"ex1\" \n** indicating that all columns should be searched,\n** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.\n*/\n#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */\n#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */\n#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */\n\n\nstruct Fts3Doclist {\n  char *aAll;                    /* Array containing doclist (or NULL) */\n  int nAll;                      /* Size of a[] in bytes */\n  char *pNextDocid;              /* Pointer to next docid */\n\n  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */\n  int bFreeList;                 /* True if pList should be sqlite3_free()d */\n  char *pList;                   /* Pointer to position list following iDocid */\n  int nList;                     /* Length of position list */\n};\n\n/*\n** A \"phrase\" is a sequence of one or more tokens that must match in\n** sequence.  A single token is the base case and the most common case.\n** For a sequence of tokens contained in double-quotes (i.e. \"one two three\")\n** nToken will be the number of tokens in the string.\n*/\nstruct Fts3PhraseToken {\n  char *z;                        /* Text of the token */\n  int n;                          /* Number of bytes in buffer z */\n  int isPrefix;                   /* True if token ends with a \"*\" character */\n  int bFirst;                     /* True if token must appear at position 0 */\n\n  /* Variables above this point are populated when the expression is\n  ** parsed (by code in fts3_expr.c). Below this point the variables are\n  ** used when evaluating the expression. */\n  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */\n  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */\n};\n\nstruct Fts3Phrase {\n  /* Cache of doclist for this phrase. */\n  Fts3Doclist doclist;\n  int bIncr;                 /* True if doclist is loaded incrementally */\n  int iDoclistToken;\n\n  /* Variables below this point are populated by fts3_expr.c when parsing \n  ** a MATCH expression. Everything above is part of the evaluation phase. \n  */\n  int nToken;                /* Number of tokens in the phrase */\n  int iColumn;               /* Index of column this phrase must match */\n  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */\n};\n\n/*\n** A tree of these objects forms the RHS of a MATCH operator.\n**\n** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist \n** points to a malloced buffer, size nDoclist bytes, containing the results \n** of this phrase query in FTS3 doclist format. As usual, the initial \n** \"Length\" field found in doclists stored on disk is omitted from this \n** buffer.\n**\n** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global\n** matchinfo data. If it is not NULL, it points to an array of size nCol*3,\n** where nCol is the number of columns in the queried FTS table. The array\n** is populated as follows:\n**\n**   aMI[iCol*3 + 0] = Undefined\n**   aMI[iCol*3 + 1] = Number of occurrences\n**   aMI[iCol*3 + 2] = Number of rows containing at least one instance\n**\n** The aMI array is allocated using sqlite3_malloc(). It should be freed \n** when the expression node is.\n*/\nstruct Fts3Expr {\n  int eType;                 /* One of the FTSQUERY_XXX values defined below */\n  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */\n  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */\n  Fts3Expr *pLeft;           /* Left operand */\n  Fts3Expr *pRight;          /* Right operand */\n  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */\n\n  /* The following are used by the fts3_eval.c module. */\n  sqlite3_int64 iDocid;      /* Current docid */\n  u8 bEof;                   /* True this expression is at EOF already */\n  u8 bStart;                 /* True if iDocid is valid */\n  u8 bDeferred;              /* True if this expression is entirely deferred */\n\n  u32 *aMI;\n};\n\n/*\n** Candidate values for Fts3Query.eType. Note that the order of the first\n** four values is in order of precedence when parsing expressions. For \n** example, the following:\n**\n**   \"a OR b AND c NOT d NEAR e\"\n**\n** is equivalent to:\n**\n**   \"a OR (b AND (c NOT (d NEAR e)))\"\n*/\n#define FTSQUERY_NEAR   1\n#define FTSQUERY_NOT    2\n#define FTSQUERY_AND    3\n#define FTSQUERY_OR     4\n#define FTSQUERY_PHRASE 5\n\n\n/* fts3_write.c */\nSQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);\nSQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);\nSQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,\n  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderPending(\n  Fts3Table*,int,const char*,int,int,Fts3SegReader**);\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);\nSQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);\nSQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);\nSQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);\n\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);\nSQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);\nSQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);\nSQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);\n#else\n# define sqlite3Fts3FreeDeferredTokens(x)\n# define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK\n# define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK\n# define sqlite3Fts3FreeDeferredDoclists(x)\n# define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK\n#endif\n\nSQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);\nSQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);\n\n/* Special values interpreted by sqlite3SegReaderCursor() */\n#define FTS3_SEGCURSOR_PENDING        -1\n#define FTS3_SEGCURSOR_ALL            -2\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, \n    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);\n\n/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */\n#define FTS3_SEGMENT_REQUIRE_POS   0x00000001\n#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002\n#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004\n#define FTS3_SEGMENT_PREFIX        0x00000008\n#define FTS3_SEGMENT_SCAN          0x00000010\n#define FTS3_SEGMENT_FIRST         0x00000020\n\n/* Type passed as 4th argument to SegmentReaderIterate() */\nstruct Fts3SegFilter {\n  const char *zTerm;\n  int nTerm;\n  int iCol;\n  int flags;\n};\n\nstruct Fts3MultiSegReader {\n  /* Used internally by sqlite3Fts3SegReaderXXX() calls */\n  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */\n  int nSegment;                   /* Size of apSegment array */\n  int nAdvance;                   /* How many seg-readers to advance */\n  Fts3SegFilter *pFilter;         /* Pointer to filter object */\n  char *aBuffer;                  /* Buffer to merge doclists in */\n  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */\n\n  int iColFilter;                 /* If >=0, filter for this column */\n  int bRestart;\n\n  /* Used by fts3.c only. */\n  int nCost;                      /* Cost of running iterator */\n  int bLookup;                    /* True if a lookup of a single entry. */\n\n  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */\n  char *zTerm;                    /* Pointer to term buffer */\n  int nTerm;                      /* Size of zTerm in bytes */\n  char *aDoclist;                 /* Pointer to doclist buffer */\n  int nDoclist;                   /* Size of aDoclist[] in bytes */\n};\n\nSQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);\n\n/* fts3.c */\nSQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);\nSQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);\nSQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);\nSQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);\nSQLITE_PRIVATE void sqlite3Fts3Dequote(char *);\nSQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);\nSQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);\nSQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);\nSQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);\n\n/* fts3_tokenizer.c */\nSQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);\nSQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);\nSQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, \n    sqlite3_tokenizer **, char **\n);\nSQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);\n\n/* fts3_snippet.c */\nSQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);\nSQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,\n  const char *, const char *, int, int\n);\nSQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);\n\n/* fts3_expr.c */\nSQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,\n  char **, int, int, int, const char *, int, Fts3Expr **\n);\nSQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);\n#ifdef SQLITE_TEST\nSQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);\nSQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);\n#endif\n\nSQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,\n  sqlite3_tokenizer_cursor **\n);\n\n/* fts3_aux.c */\nSQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);\n\nSQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(\n    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(\n    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);\nSQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); \nSQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);\n\n/* fts3_unicode2.c (functions generated by parsing unicode text files) */\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\nSQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);\n#endif\n\n#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */\n#endif /* _FTSINT_H */\n\n/************** End of fts3Int.h *********************************************/\n/************** Continuing where we left off in fts3.c ***********************/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)\n# define SQLITE_CORE 1\n#endif\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stddef.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n/* #include <stdarg.h> */\n\n#ifndef SQLITE_CORE \n  SQLITE_EXTENSION_INIT1\n#endif\n\nstatic int fts3EvalNext(Fts3Cursor *pCsr);\nstatic int fts3EvalStart(Fts3Cursor *pCsr);\nstatic int fts3TermSegReaderCursor(\n    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);\n\n/* \n** Write a 64-bit variable-length integer to memory starting at p[0].\n** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.\n** The number of bytes written is returned.\n*/\nSQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){\n  unsigned char *q = (unsigned char *) p;\n  sqlite_uint64 vu = v;\n  do{\n    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);\n    vu >>= 7;\n  }while( vu!=0 );\n  q[-1] &= 0x7f;  /* turn off high bit in final byte */\n  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );\n  return (int) (q - (unsigned char *)p);\n}\n\n/* \n** Read a 64-bit variable-length integer from memory starting at p[0].\n** Return the number of bytes read, or 0 on error.\n** The value is stored in *v.\n*/\nSQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){\n  const unsigned char *q = (const unsigned char *) p;\n  sqlite_uint64 x = 0, y = 1;\n  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){\n    x += y * (*q++ & 0x7f);\n    y <<= 7;\n  }\n  x += y * (*q++);\n  *v = (sqlite_int64) x;\n  return (int) (q - (unsigned char *)p);\n}\n\n/*\n** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a\n** 32-bit integer before it is returned.\n*/\nSQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){\n sqlite_int64 i;\n int ret = sqlite3Fts3GetVarint(p, &i);\n *pi = (int) i;\n return ret;\n}\n\n/*\n** Return the number of bytes required to encode v as a varint\n*/\nSQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){\n  int i = 0;\n  do{\n    i++;\n    v >>= 7;\n  }while( v!=0 );\n  return i;\n}\n\n/*\n** Convert an SQL-style quoted string into a normal string by removing\n** the quote characters.  The conversion is done in-place.  If the\n** input does not begin with a quote character, then this routine\n** is a no-op.\n**\n** Examples:\n**\n**     \"abc\"   becomes   abc\n**     'xyz'   becomes   xyz\n**     [pqr]   becomes   pqr\n**     `mno`   becomes   mno\n**\n*/\nSQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){\n  char quote;                     /* Quote character (if any ) */\n\n  quote = z[0];\n  if( quote=='[' || quote=='\\'' || quote=='\"' || quote=='`' ){\n    int iIn = 1;                  /* Index of next byte to read from input */\n    int iOut = 0;                 /* Index of next byte to write to output */\n\n    /* If the first byte was a '[', then the close-quote character is a ']' */\n    if( quote=='[' ) quote = ']';  \n\n    while( ALWAYS(z[iIn]) ){\n      if( z[iIn]==quote ){\n        if( z[iIn+1]!=quote ) break;\n        z[iOut++] = quote;\n        iIn += 2;\n      }else{\n        z[iOut++] = z[iIn++];\n      }\n    }\n    z[iOut] = '\\0';\n  }\n}\n\n/*\n** Read a single varint from the doclist at *pp and advance *pp to point\n** to the first byte past the end of the varint.  Add the value of the varint\n** to *pVal.\n*/\nstatic void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){\n  sqlite3_int64 iVal;\n  *pp += sqlite3Fts3GetVarint(*pp, &iVal);\n  *pVal += iVal;\n}\n\n/*\n** When this function is called, *pp points to the first byte following a\n** varint that is part of a doclist (or position-list, or any other list\n** of varints). This function moves *pp to point to the start of that varint,\n** and sets *pVal by the varint value.\n**\n** Argument pStart points to the first byte of the doclist that the\n** varint is part of.\n*/\nstatic void fts3GetReverseVarint(\n  char **pp, \n  char *pStart, \n  sqlite3_int64 *pVal\n){\n  sqlite3_int64 iVal;\n  char *p;\n\n  /* Pointer p now points at the first byte past the varint we are \n  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is\n  ** clear on character p[-1]. */\n  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);\n  p++;\n  *pp = p;\n\n  sqlite3Fts3GetVarint(p, &iVal);\n  *pVal = iVal;\n}\n\n/*\n** The xDisconnect() virtual table method.\n*/\nstatic int fts3DisconnectMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int i;\n\n  assert( p->nPendingData==0 );\n  assert( p->pSegments==0 );\n\n  /* Free any prepared statements held */\n  for(i=0; i<SizeofArray(p->aStmt); i++){\n    sqlite3_finalize(p->aStmt[i]);\n  }\n  sqlite3_free(p->zSegmentsTbl);\n  sqlite3_free(p->zReadExprlist);\n  sqlite3_free(p->zWriteExprlist);\n  sqlite3_free(p->zContentTbl);\n  sqlite3_free(p->zLanguageid);\n\n  /* Invoke the tokenizer destructor to free the tokenizer. */\n  p->pTokenizer->pModule->xDestroy(p->pTokenizer);\n\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Construct one or more SQL statements from the format string given\n** and then evaluate those statements. The success code is written\n** into *pRc.\n**\n** If *pRc is initially non-zero then this routine is a no-op.\n*/\nstatic void fts3DbExec(\n  int *pRc,              /* Success code */\n  sqlite3 *db,           /* Database in which to run SQL */\n  const char *zFormat,   /* Format string for SQL */\n  ...                    /* Arguments to the format string */\n){\n  va_list ap;\n  char *zSql;\n  if( *pRc ) return;\n  va_start(ap, zFormat);\n  zSql = sqlite3_vmprintf(zFormat, ap);\n  va_end(ap);\n  if( zSql==0 ){\n    *pRc = SQLITE_NOMEM;\n  }else{\n    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);\n    sqlite3_free(zSql);\n  }\n}\n\n/*\n** The xDestroy() virtual table method.\n*/\nstatic int fts3DestroyMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int rc = SQLITE_OK;              /* Return code */\n  const char *zDb = p->zDb;        /* Name of database (e.g. \"main\", \"temp\") */\n  sqlite3 *db = p->db;             /* Database handle */\n\n  /* Drop the shadow tables */\n  if( p->zContentTbl==0 ){\n    fts3DbExec(&rc, db, \"DROP TABLE IF EXISTS %Q.'%q_content'\", zDb, p->zName);\n  }\n  fts3DbExec(&rc, db, \"DROP TABLE IF EXISTS %Q.'%q_segments'\", zDb,p->zName);\n  fts3DbExec(&rc, db, \"DROP TABLE IF EXISTS %Q.'%q_segdir'\", zDb, p->zName);\n  fts3DbExec(&rc, db, \"DROP TABLE IF EXISTS %Q.'%q_docsize'\", zDb, p->zName);\n  fts3DbExec(&rc, db, \"DROP TABLE IF EXISTS %Q.'%q_stat'\", zDb, p->zName);\n\n  /* If everything has worked, invoke fts3DisconnectMethod() to free the\n  ** memory associated with the Fts3Table structure and return SQLITE_OK.\n  ** Otherwise, return an SQLite error code.\n  */\n  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);\n}\n\n\n/*\n** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table\n** passed as the first argument. This is done as part of the xConnect()\n** and xCreate() methods.\n**\n** If *pRc is non-zero when this function is called, it is a no-op. \n** Otherwise, if an error occurs, an SQLite error code is stored in *pRc\n** before returning.\n*/\nstatic void fts3DeclareVtab(int *pRc, Fts3Table *p){\n  if( *pRc==SQLITE_OK ){\n    int i;                        /* Iterator variable */\n    int rc;                       /* Return code */\n    char *zSql;                   /* SQL statement passed to declare_vtab() */\n    char *zCols;                  /* List of user defined columns */\n    const char *zLanguageid;\n\n    zLanguageid = (p->zLanguageid ? p->zLanguageid : \"__langid\");\n    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);\n\n    /* Create a list of user columns for the virtual table */\n    zCols = sqlite3_mprintf(\"%Q, \", p->azColumn[0]);\n    for(i=1; zCols && i<p->nColumn; i++){\n      zCols = sqlite3_mprintf(\"%z%Q, \", zCols, p->azColumn[i]);\n    }\n\n    /* Create the whole \"CREATE TABLE\" statement to pass to SQLite */\n    zSql = sqlite3_mprintf(\n        \"CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)\", \n        zCols, p->zName, zLanguageid\n    );\n    if( !zCols || !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_declare_vtab(p->db, zSql);\n    }\n\n    sqlite3_free(zSql);\n    sqlite3_free(zCols);\n    *pRc = rc;\n  }\n}\n\n/*\n** Create the %_stat table if it does not already exist.\n*/\nSQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){\n  fts3DbExec(pRc, p->db, \n      \"CREATE TABLE IF NOT EXISTS %Q.'%q_stat'\"\n          \"(id INTEGER PRIMARY KEY, value BLOB);\",\n      p->zDb, p->zName\n  );\n  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;\n}\n\n/*\n** Create the backing store tables (%_content, %_segments and %_segdir)\n** required by the FTS3 table passed as the only argument. This is done\n** as part of the vtab xCreate() method.\n**\n** If the p->bHasDocsize boolean is true (indicating that this is an\n** FTS4 table, not an FTS3 table) then also create the %_docsize and\n** %_stat tables required by FTS4.\n*/\nstatic int fts3CreateTables(Fts3Table *p){\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Iterator variable */\n  sqlite3 *db = p->db;            /* The database connection */\n\n  if( p->zContentTbl==0 ){\n    const char *zLanguageid = p->zLanguageid;\n    char *zContentCols;           /* Columns of %_content table */\n\n    /* Create a list of user columns for the content table */\n    zContentCols = sqlite3_mprintf(\"docid INTEGER PRIMARY KEY\");\n    for(i=0; zContentCols && i<p->nColumn; i++){\n      char *z = p->azColumn[i];\n      zContentCols = sqlite3_mprintf(\"%z, 'c%d%q'\", zContentCols, i, z);\n    }\n    if( zLanguageid && zContentCols ){\n      zContentCols = sqlite3_mprintf(\"%z, langid\", zContentCols, zLanguageid);\n    }\n    if( zContentCols==0 ) rc = SQLITE_NOMEM;\n  \n    /* Create the content table */\n    fts3DbExec(&rc, db, \n       \"CREATE TABLE %Q.'%q_content'(%s)\",\n       p->zDb, p->zName, zContentCols\n    );\n    sqlite3_free(zContentCols);\n  }\n\n  /* Create other tables */\n  fts3DbExec(&rc, db, \n      \"CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);\",\n      p->zDb, p->zName\n  );\n  fts3DbExec(&rc, db, \n      \"CREATE TABLE %Q.'%q_segdir'(\"\n        \"level INTEGER,\"\n        \"idx INTEGER,\"\n        \"start_block INTEGER,\"\n        \"leaves_end_block INTEGER,\"\n        \"end_block INTEGER,\"\n        \"root BLOB,\"\n        \"PRIMARY KEY(level, idx)\"\n      \");\",\n      p->zDb, p->zName\n  );\n  if( p->bHasDocsize ){\n    fts3DbExec(&rc, db, \n        \"CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);\",\n        p->zDb, p->zName\n    );\n  }\n  assert( p->bHasStat==p->bFts4 );\n  if( p->bHasStat ){\n    sqlite3Fts3CreateStatTable(&rc, p);\n  }\n  return rc;\n}\n\n/*\n** Store the current database page-size in bytes in p->nPgsz.\n**\n** If *pRc is non-zero when this function is called, it is a no-op. \n** Otherwise, if an error occurs, an SQLite error code is stored in *pRc\n** before returning.\n*/\nstatic void fts3DatabasePageSize(int *pRc, Fts3Table *p){\n  if( *pRc==SQLITE_OK ){\n    int rc;                       /* Return code */\n    char *zSql;                   /* SQL text \"PRAGMA %Q.page_size\" */\n    sqlite3_stmt *pStmt;          /* Compiled \"PRAGMA %Q.page_size\" statement */\n  \n    zSql = sqlite3_mprintf(\"PRAGMA %Q.page_size\", p->zDb);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);\n      if( rc==SQLITE_OK ){\n        sqlite3_step(pStmt);\n        p->nPgsz = sqlite3_column_int(pStmt, 0);\n        rc = sqlite3_finalize(pStmt);\n      }else if( rc==SQLITE_AUTH ){\n        p->nPgsz = 1024;\n        rc = SQLITE_OK;\n      }\n    }\n    assert( p->nPgsz>0 || rc!=SQLITE_OK );\n    sqlite3_free(zSql);\n    *pRc = rc;\n  }\n}\n\n/*\n** \"Special\" FTS4 arguments are column specifications of the following form:\n**\n**   <key> = <value>\n**\n** There may not be whitespace surrounding the \"=\" character. The <value> \n** term may be quoted, but the <key> may not.\n*/\nstatic int fts3IsSpecialColumn(\n  const char *z, \n  int *pnKey,\n  char **pzValue\n){\n  char *zValue;\n  const char *zCsr = z;\n\n  while( *zCsr!='=' ){\n    if( *zCsr=='\\0' ) return 0;\n    zCsr++;\n  }\n\n  *pnKey = (int)(zCsr-z);\n  zValue = sqlite3_mprintf(\"%s\", &zCsr[1]);\n  if( zValue ){\n    sqlite3Fts3Dequote(zValue);\n  }\n  *pzValue = zValue;\n  return 1;\n}\n\n/*\n** Append the output of a printf() style formatting to an existing string.\n*/\nstatic void fts3Appendf(\n  int *pRc,                       /* IN/OUT: Error code */\n  char **pz,                      /* IN/OUT: Pointer to string buffer */\n  const char *zFormat,            /* Printf format string to append */\n  ...                             /* Arguments for printf format string */\n){\n  if( *pRc==SQLITE_OK ){\n    va_list ap;\n    char *z;\n    va_start(ap, zFormat);\n    z = sqlite3_vmprintf(zFormat, ap);\n    va_end(ap);\n    if( z && *pz ){\n      char *z2 = sqlite3_mprintf(\"%s%s\", *pz, z);\n      sqlite3_free(z);\n      z = z2;\n    }\n    if( z==0 ) *pRc = SQLITE_NOMEM;\n    sqlite3_free(*pz);\n    *pz = z;\n  }\n}\n\n/*\n** Return a copy of input string zInput enclosed in double-quotes (\") and\n** with all double quote characters escaped. For example:\n**\n**     fts3QuoteId(\"un \\\"zip\\\"\")   ->    \"un \\\"\\\"zip\\\"\\\"\"\n**\n** The pointer returned points to memory obtained from sqlite3_malloc(). It\n** is the callers responsibility to call sqlite3_free() to release this\n** memory.\n*/\nstatic char *fts3QuoteId(char const *zInput){\n  int nRet;\n  char *zRet;\n  nRet = 2 + (int)strlen(zInput)*2 + 1;\n  zRet = sqlite3_malloc(nRet);\n  if( zRet ){\n    int i;\n    char *z = zRet;\n    *(z++) = '\"';\n    for(i=0; zInput[i]; i++){\n      if( zInput[i]=='\"' ) *(z++) = '\"';\n      *(z++) = zInput[i];\n    }\n    *(z++) = '\"';\n    *(z++) = '\\0';\n  }\n  return zRet;\n}\n\n/*\n** Return a list of comma separated SQL expressions and a FROM clause that \n** could be used in a SELECT statement such as the following:\n**\n**     SELECT <list of expressions> FROM %_content AS x ...\n**\n** to return the docid, followed by each column of text data in order\n** from left to write. If parameter zFunc is not NULL, then instead of\n** being returned directly each column of text data is passed to an SQL\n** function named zFunc first. For example, if zFunc is \"unzip\" and the\n** table has the three user-defined columns \"a\", \"b\", and \"c\", the following\n** string is returned:\n**\n**     \"docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x\"\n**\n** The pointer returned points to a buffer allocated by sqlite3_malloc(). It\n** is the responsibility of the caller to eventually free it.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and\n** a NULL pointer is returned). Otherwise, if an OOM error is encountered\n** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If\n** no error occurs, *pRc is left unmodified.\n*/\nstatic char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){\n  char *zRet = 0;\n  char *zFree = 0;\n  char *zFunction;\n  int i;\n\n  if( p->zContentTbl==0 ){\n    if( !zFunc ){\n      zFunction = \"\";\n    }else{\n      zFree = zFunction = fts3QuoteId(zFunc);\n    }\n    fts3Appendf(pRc, &zRet, \"docid\");\n    for(i=0; i<p->nColumn; i++){\n      fts3Appendf(pRc, &zRet, \",%s(x.'c%d%q')\", zFunction, i, p->azColumn[i]);\n    }\n    if( p->zLanguageid ){\n      fts3Appendf(pRc, &zRet, \", x.%Q\", \"langid\");\n    }\n    sqlite3_free(zFree);\n  }else{\n    fts3Appendf(pRc, &zRet, \"rowid\");\n    for(i=0; i<p->nColumn; i++){\n      fts3Appendf(pRc, &zRet, \", x.'%q'\", p->azColumn[i]);\n    }\n    if( p->zLanguageid ){\n      fts3Appendf(pRc, &zRet, \", x.%Q\", p->zLanguageid);\n    }\n  }\n  fts3Appendf(pRc, &zRet, \" FROM '%q'.'%q%s' AS x\", \n      p->zDb,\n      (p->zContentTbl ? p->zContentTbl : p->zName),\n      (p->zContentTbl ? \"\" : \"_content\")\n  );\n  return zRet;\n}\n\n/*\n** Return a list of N comma separated question marks, where N is the number\n** of columns in the %_content table (one for the docid plus one for each\n** user-defined text column).\n**\n** If argument zFunc is not NULL, then all but the first question mark\n** is preceded by zFunc and an open bracket, and followed by a closed\n** bracket. For example, if zFunc is \"zip\" and the FTS3 table has three \n** user-defined text columns, the following string is returned:\n**\n**     \"?, zip(?), zip(?), zip(?)\"\n**\n** The pointer returned points to a buffer allocated by sqlite3_malloc(). It\n** is the responsibility of the caller to eventually free it.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and\n** a NULL pointer is returned). Otherwise, if an OOM error is encountered\n** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If\n** no error occurs, *pRc is left unmodified.\n*/\nstatic char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){\n  char *zRet = 0;\n  char *zFree = 0;\n  char *zFunction;\n  int i;\n\n  if( !zFunc ){\n    zFunction = \"\";\n  }else{\n    zFree = zFunction = fts3QuoteId(zFunc);\n  }\n  fts3Appendf(pRc, &zRet, \"?\");\n  for(i=0; i<p->nColumn; i++){\n    fts3Appendf(pRc, &zRet, \",%s(?)\", zFunction);\n  }\n  if( p->zLanguageid ){\n    fts3Appendf(pRc, &zRet, \", ?\");\n  }\n  sqlite3_free(zFree);\n  return zRet;\n}\n\n/*\n** This function interprets the string at (*pp) as a non-negative integer\n** value. It reads the integer and sets *pnOut to the value read, then \n** sets *pp to point to the byte immediately following the last byte of\n** the integer value.\n**\n** Only decimal digits ('0'..'9') may be part of an integer value. \n**\n** If *pp does not being with a decimal digit SQLITE_ERROR is returned and\n** the output value undefined. Otherwise SQLITE_OK is returned.\n**\n** This function is used when parsing the \"prefix=\" FTS4 parameter.\n*/\nstatic int fts3GobbleInt(const char **pp, int *pnOut){\n  const char *p;                  /* Iterator pointer */\n  int nInt = 0;                   /* Output value */\n\n  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){\n    nInt = nInt * 10 + (p[0] - '0');\n  }\n  if( p==*pp ) return SQLITE_ERROR;\n  *pnOut = nInt;\n  *pp = p;\n  return SQLITE_OK;\n}\n\n/*\n** This function is called to allocate an array of Fts3Index structures\n** representing the indexes maintained by the current FTS table. FTS tables\n** always maintain the main \"terms\" index, but may also maintain one or\n** more \"prefix\" indexes, depending on the value of the \"prefix=\" parameter\n** (if any) specified as part of the CREATE VIRTUAL TABLE statement.\n**\n** Argument zParam is passed the value of the \"prefix=\" option if one was\n** specified, or NULL otherwise.\n**\n** If no error occurs, SQLITE_OK is returned and *apIndex set to point to\n** the allocated array. *pnIndex is set to the number of elements in the\n** array. If an error does occur, an SQLite error code is returned.\n**\n** Regardless of whether or not an error is returned, it is the responsibility\n** of the caller to call sqlite3_free() on the output array to free it.\n*/\nstatic int fts3PrefixParameter(\n  const char *zParam,             /* ABC in prefix=ABC parameter to parse */\n  int *pnIndex,                   /* OUT: size of *apIndex[] array */\n  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */\n){\n  struct Fts3Index *aIndex;       /* Allocated array */\n  int nIndex = 1;                 /* Number of entries in array */\n\n  if( zParam && zParam[0] ){\n    const char *p;\n    nIndex++;\n    for(p=zParam; *p; p++){\n      if( *p==',' ) nIndex++;\n    }\n  }\n\n  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);\n  *apIndex = aIndex;\n  *pnIndex = nIndex;\n  if( !aIndex ){\n    return SQLITE_NOMEM;\n  }\n\n  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);\n  if( zParam ){\n    const char *p = zParam;\n    int i;\n    for(i=1; i<nIndex; i++){\n      int nPrefix;\n      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;\n      aIndex[i].nPrefix = nPrefix;\n      p++;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This function is called when initializing an FTS4 table that uses the\n** content=xxx option. It determines the number of and names of the columns\n** of the new FTS4 table.\n**\n** The third argument passed to this function is the value passed to the\n** config=xxx option (i.e. \"xxx\"). This function queries the database for\n** a table of that name. If found, the output variables are populated\n** as follows:\n**\n**   *pnCol:   Set to the number of columns table xxx has,\n**\n**   *pnStr:   Set to the total amount of space required to store a copy\n**             of each columns name, including the nul-terminator.\n**\n**   *pazCol:  Set to point to an array of *pnCol strings. Each string is\n**             the name of the corresponding column in table xxx. The array\n**             and its contents are allocated using a single allocation. It\n**             is the responsibility of the caller to free this allocation\n**             by eventually passing the *pazCol value to sqlite3_free().\n**\n** If the table cannot be found, an error code is returned and the output\n** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is\n** returned (and the output variables are undefined).\n*/\nstatic int fts3ContentColumns(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of db (i.e. \"main\", \"temp\" etc.) */\n  const char *zTbl,               /* Name of content table */\n  const char ***pazCol,           /* OUT: Malloc'd array of column names */\n  int *pnCol,                     /* OUT: Size of array *pazCol */\n  int *pnStr                      /* OUT: Bytes of string content */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  char *zSql;                     /* \"SELECT *\" statement on zTbl */  \n  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */\n\n  zSql = sqlite3_mprintf(\"SELECT * FROM %Q.%Q\", zDb, zTbl);\n  if( !zSql ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);\n  }\n  sqlite3_free(zSql);\n\n  if( rc==SQLITE_OK ){\n    const char **azCol;           /* Output array */\n    int nStr = 0;                 /* Size of all column names (incl. 0x00) */\n    int nCol;                     /* Number of table columns */\n    int i;                        /* Used to iterate through columns */\n\n    /* Loop through the returned columns. Set nStr to the number of bytes of\n    ** space required to store a copy of each column name, including the\n    ** nul-terminator byte.  */\n    nCol = sqlite3_column_count(pStmt);\n    for(i=0; i<nCol; i++){\n      const char *zCol = sqlite3_column_name(pStmt, i);\n      nStr += (int)strlen(zCol) + 1;\n    }\n\n    /* Allocate and populate the array to return. */\n    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);\n    if( azCol==0 ){\n      rc = SQLITE_NOMEM;\n    }else{\n      char *p = (char *)&azCol[nCol];\n      for(i=0; i<nCol; i++){\n        const char *zCol = sqlite3_column_name(pStmt, i);\n        int n = (int)strlen(zCol)+1;\n        memcpy(p, zCol, n);\n        azCol[i] = p;\n        p += n;\n      }\n    }\n    sqlite3_finalize(pStmt);\n\n    /* Set the output variables. */\n    *pnCol = nCol;\n    *pnStr = nStr;\n    *pazCol = azCol;\n  }\n\n  return rc;\n}\n\n/*\n** This function is the implementation of both the xConnect and xCreate\n** methods of the FTS3 virtual table.\n**\n** The argv[] array contains the following:\n**\n**   argv[0]   -> module name  (\"fts3\" or \"fts4\")\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> \"column name\" and other module argument fields.\n*/\nstatic int fts3InitVtab(\n  int isCreate,                   /* True for xCreate, false for xConnect */\n  sqlite3 *db,                    /* The SQLite database connection */\n  void *pAux,                     /* Hash table containing tokenizers */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */\n  char **pzErr                    /* Write any error message here */\n){\n  Fts3Hash *pHash = (Fts3Hash *)pAux;\n  Fts3Table *p = 0;               /* Pointer to allocated vtab */\n  int rc = SQLITE_OK;             /* Return code */\n  int i;                          /* Iterator variable */\n  int nByte;                      /* Size of allocation used for *p */\n  int iCol;                       /* Column index */\n  int nString = 0;                /* Bytes required to hold all column names */\n  int nCol = 0;                   /* Number of columns in the FTS table */\n  char *zCsr;                     /* Space for holding column names */\n  int nDb;                        /* Bytes required to hold database name */\n  int nName;                      /* Bytes required to hold table name */\n  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */\n  const char **aCol;              /* Array of column names */\n  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */\n\n  int nIndex;                     /* Size of aIndex[] array */\n  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */\n\n  /* The results of parsing supported FTS4 key=value options: */\n  int bNoDocsize = 0;             /* True to omit %_docsize table */\n  int bDescIdx = 0;               /* True to store descending indexes */\n  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */\n  char *zCompress = 0;            /* compress=? parameter (or NULL) */\n  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */\n  char *zContent = 0;             /* content=? parameter (or NULL) */\n  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */\n\n  assert( strlen(argv[0])==4 );\n  assert( (sqlite3_strnicmp(argv[0], \"fts4\", 4)==0 && isFts4)\n       || (sqlite3_strnicmp(argv[0], \"fts3\", 4)==0 && !isFts4)\n  );\n\n  nDb = (int)strlen(argv[1]) + 1;\n  nName = (int)strlen(argv[2]) + 1;\n\n  aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );\n  if( !aCol ) return SQLITE_NOMEM;\n  memset((void *)aCol, 0, sizeof(const char *) * (argc-2));\n\n  /* Loop through all of the arguments passed by the user to the FTS3/4\n  ** module (i.e. all the column names and special arguments). This loop\n  ** does the following:\n  **\n  **   + Figures out the number of columns the FTSX table will have, and\n  **     the number of bytes of space that must be allocated to store copies\n  **     of the column names.\n  **\n  **   + If there is a tokenizer specification included in the arguments,\n  **     initializes the tokenizer pTokenizer.\n  */\n  for(i=3; rc==SQLITE_OK && i<argc; i++){\n    char const *z = argv[i];\n    int nKey;\n    char *zVal;\n\n    /* Check if this is a tokenizer specification */\n    if( !pTokenizer \n     && strlen(z)>8\n     && 0==sqlite3_strnicmp(z, \"tokenize\", 8) \n     && 0==sqlite3Fts3IsIdChar(z[8])\n    ){\n      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);\n    }\n\n    /* Check if it is an FTS4 special argument. */\n    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){\n      struct Fts4Option {\n        const char *zOpt;\n        int nOpt;\n      } aFts4Opt[] = {\n        { \"matchinfo\",   9 },     /* 0 -> MATCHINFO */\n        { \"prefix\",      6 },     /* 1 -> PREFIX */\n        { \"compress\",    8 },     /* 2 -> COMPRESS */\n        { \"uncompress\", 10 },     /* 3 -> UNCOMPRESS */\n        { \"order\",       5 },     /* 4 -> ORDER */\n        { \"content\",     7 },     /* 5 -> CONTENT */\n        { \"languageid\", 10 }      /* 6 -> LANGUAGEID */\n      };\n\n      int iOpt;\n      if( !zVal ){\n        rc = SQLITE_NOMEM;\n      }else{\n        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){\n          struct Fts4Option *pOp = &aFts4Opt[iOpt];\n          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){\n            break;\n          }\n        }\n        if( iOpt==SizeofArray(aFts4Opt) ){\n          *pzErr = sqlite3_mprintf(\"unrecognized parameter: %s\", z);\n          rc = SQLITE_ERROR;\n        }else{\n          switch( iOpt ){\n            case 0:               /* MATCHINFO */\n              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, \"fts3\", 4) ){\n                *pzErr = sqlite3_mprintf(\"unrecognized matchinfo: %s\", zVal);\n                rc = SQLITE_ERROR;\n              }\n              bNoDocsize = 1;\n              break;\n\n            case 1:               /* PREFIX */\n              sqlite3_free(zPrefix);\n              zPrefix = zVal;\n              zVal = 0;\n              break;\n\n            case 2:               /* COMPRESS */\n              sqlite3_free(zCompress);\n              zCompress = zVal;\n              zVal = 0;\n              break;\n\n            case 3:               /* UNCOMPRESS */\n              sqlite3_free(zUncompress);\n              zUncompress = zVal;\n              zVal = 0;\n              break;\n\n            case 4:               /* ORDER */\n              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, \"asc\", 3)) \n               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, \"desc\", 4)) \n              ){\n                *pzErr = sqlite3_mprintf(\"unrecognized order: %s\", zVal);\n                rc = SQLITE_ERROR;\n              }\n              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');\n              break;\n\n            case 5:              /* CONTENT */\n              sqlite3_free(zContent);\n              zContent = zVal;\n              zVal = 0;\n              break;\n\n            case 6:              /* LANGUAGEID */\n              assert( iOpt==6 );\n              sqlite3_free(zLanguageid);\n              zLanguageid = zVal;\n              zVal = 0;\n              break;\n          }\n        }\n        sqlite3_free(zVal);\n      }\n    }\n\n    /* Otherwise, the argument is a column name. */\n    else {\n      nString += (int)(strlen(z) + 1);\n      aCol[nCol++] = z;\n    }\n  }\n\n  /* If a content=xxx option was specified, the following:\n  **\n  **   1. Ignore any compress= and uncompress= options.\n  **\n  **   2. If no column names were specified as part of the CREATE VIRTUAL\n  **      TABLE statement, use all columns from the content table.\n  */\n  if( rc==SQLITE_OK && zContent ){\n    sqlite3_free(zCompress); \n    sqlite3_free(zUncompress); \n    zCompress = 0;\n    zUncompress = 0;\n    if( nCol==0 ){\n      sqlite3_free((void*)aCol); \n      aCol = 0;\n      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);\n\n      /* If a languageid= option was specified, remove the language id\n      ** column from the aCol[] array. */ \n      if( rc==SQLITE_OK && zLanguageid ){\n        int j;\n        for(j=0; j<nCol; j++){\n          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){\n            int k;\n            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];\n            nCol--;\n            break;\n          }\n        }\n      }\n    }\n  }\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  if( nCol==0 ){\n    assert( nString==0 );\n    aCol[0] = \"content\";\n    nString = 8;\n    nCol = 1;\n  }\n\n  if( pTokenizer==0 ){\n    rc = sqlite3Fts3InitTokenizer(pHash, \"simple\", &pTokenizer, pzErr);\n    if( rc!=SQLITE_OK ) goto fts3_init_out;\n  }\n  assert( pTokenizer );\n\n  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);\n  if( rc==SQLITE_ERROR ){\n    assert( zPrefix );\n    *pzErr = sqlite3_mprintf(\"error parsing prefix parameter: %s\", zPrefix);\n  }\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  /* Allocate and populate the Fts3Table structure. */\n  nByte = sizeof(Fts3Table) +                  /* Fts3Table */\n          nCol * sizeof(char *) +              /* azColumn */\n          nIndex * sizeof(struct Fts3Index) +  /* aIndex */\n          nName +                              /* zName */\n          nDb +                                /* zDb */\n          nString;                             /* Space for azColumn strings */\n  p = (Fts3Table*)sqlite3_malloc(nByte);\n  if( p==0 ){\n    rc = SQLITE_NOMEM;\n    goto fts3_init_out;\n  }\n  memset(p, 0, nByte);\n  p->db = db;\n  p->nColumn = nCol;\n  p->nPendingData = 0;\n  p->azColumn = (char **)&p[1];\n  p->pTokenizer = pTokenizer;\n  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;\n  p->bHasDocsize = (isFts4 && bNoDocsize==0);\n  p->bHasStat = isFts4;\n  p->bFts4 = isFts4;\n  p->bDescIdx = bDescIdx;\n  p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */\n  p->zContentTbl = zContent;\n  p->zLanguageid = zLanguageid;\n  zContent = 0;\n  zLanguageid = 0;\n  TESTONLY( p->inTransaction = -1 );\n  TESTONLY( p->mxSavepoint = -1 );\n\n  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];\n  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);\n  p->nIndex = nIndex;\n  for(i=0; i<nIndex; i++){\n    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);\n  }\n\n  /* Fill in the zName and zDb fields of the vtab structure. */\n  zCsr = (char *)&p->aIndex[nIndex];\n  p->zName = zCsr;\n  memcpy(zCsr, argv[2], nName);\n  zCsr += nName;\n  p->zDb = zCsr;\n  memcpy(zCsr, argv[1], nDb);\n  zCsr += nDb;\n\n  /* Fill in the azColumn array */\n  for(iCol=0; iCol<nCol; iCol++){\n    char *z; \n    int n = 0;\n    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);\n    memcpy(zCsr, z, n);\n    zCsr[n] = '\\0';\n    sqlite3Fts3Dequote(zCsr);\n    p->azColumn[iCol] = zCsr;\n    zCsr += n+1;\n    assert( zCsr <= &((char *)p)[nByte] );\n  }\n\n  if( (zCompress==0)!=(zUncompress==0) ){\n    char const *zMiss = (zCompress==0 ? \"compress\" : \"uncompress\");\n    rc = SQLITE_ERROR;\n    *pzErr = sqlite3_mprintf(\"missing %s parameter in fts4 constructor\", zMiss);\n  }\n  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);\n  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);\n  if( rc!=SQLITE_OK ) goto fts3_init_out;\n\n  /* If this is an xCreate call, create the underlying tables in the \n  ** database. TODO: For xConnect(), it could verify that said tables exist.\n  */\n  if( isCreate ){\n    rc = fts3CreateTables(p);\n  }\n\n  /* Check to see if a legacy fts3 table has been \"upgraded\" by the\n  ** addition of a %_stat table so that it can use incremental merge.\n  */\n  if( !isFts4 && !isCreate ){\n    int rc2 = SQLITE_OK;\n    fts3DbExec(&rc2, db, \"SELECT 1 FROM %Q.'%q_stat' WHERE id=2\",\n               p->zDb, p->zName);\n    if( rc2==SQLITE_OK ) p->bHasStat = 1;\n  }\n\n  /* Figure out the page-size for the database. This is required in order to\n  ** estimate the cost of loading large doclists from the database.  */\n  fts3DatabasePageSize(&rc, p);\n  p->nNodeSize = p->nPgsz-35;\n\n  /* Declare the table schema to SQLite. */\n  fts3DeclareVtab(&rc, p);\n\nfts3_init_out:\n  sqlite3_free(zPrefix);\n  sqlite3_free(aIndex);\n  sqlite3_free(zCompress);\n  sqlite3_free(zUncompress);\n  sqlite3_free(zContent);\n  sqlite3_free(zLanguageid);\n  sqlite3_free((void *)aCol);\n  if( rc!=SQLITE_OK ){\n    if( p ){\n      fts3DisconnectMethod((sqlite3_vtab *)p);\n    }else if( pTokenizer ){\n      pTokenizer->pModule->xDestroy(pTokenizer);\n    }\n  }else{\n    assert( p->pSegments==0 );\n    *ppVTab = &p->base;\n  }\n  return rc;\n}\n\n/*\n** The xConnect() and xCreate() methods for the virtual table. All the\n** work is done in function fts3InitVtab().\n*/\nstatic int fts3ConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);\n}\nstatic int fts3CreateMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pAux,                     /* Pointer to tokenizer hash table */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);\n}\n\n/* \n** Implementation of the xBestIndex method for FTS3 tables. There\n** are three possible strategies, in order of preference:\n**\n**   1. Direct lookup by rowid or docid. \n**   2. Full-text search using a MATCH operator on a non-docid column.\n**   3. Linear scan of %_content table.\n*/\nstatic int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){\n  Fts3Table *p = (Fts3Table *)pVTab;\n  int i;                          /* Iterator variable */\n  int iCons = -1;                 /* Index of constraint to use */\n  int iLangidCons = -1;           /* Index of langid=x constraint, if present */\n\n  /* By default use a full table scan. This is an expensive option,\n  ** so search through the constraints to see if a more efficient \n  ** strategy is possible.\n  */\n  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;\n  pInfo->estimatedCost = 500000;\n  for(i=0; i<pInfo->nConstraint; i++){\n    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];\n    if( pCons->usable==0 ) continue;\n\n    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */\n    if( iCons<0 \n     && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ \n     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )\n    ){\n      pInfo->idxNum = FTS3_DOCID_SEARCH;\n      pInfo->estimatedCost = 1.0;\n      iCons = i;\n    }\n\n    /* A MATCH constraint. Use a full-text search.\n    **\n    ** If there is more than one MATCH constraint available, use the first\n    ** one encountered. If there is both a MATCH constraint and a direct\n    ** rowid/docid lookup, prefer the MATCH strategy. This is done even \n    ** though the rowid/docid lookup is faster than a MATCH query, selecting\n    ** it would lead to an \"unable to use function MATCH in the requested \n    ** context\" error.\n    */\n    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH \n     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn\n    ){\n      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;\n      pInfo->estimatedCost = 2.0;\n      iCons = i;\n    }\n\n    /* Equality constraint on the langid column */\n    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ \n     && pCons->iColumn==p->nColumn + 2\n    ){\n      iLangidCons = i;\n    }\n  }\n\n  if( iCons>=0 ){\n    pInfo->aConstraintUsage[iCons].argvIndex = 1;\n    pInfo->aConstraintUsage[iCons].omit = 1;\n  } \n  if( iLangidCons>=0 ){\n    pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;\n  } \n\n  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or\n  ** docid) order. Both ascending and descending are possible. \n  */\n  if( pInfo->nOrderBy==1 ){\n    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];\n    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){\n      if( pOrder->desc ){\n        pInfo->idxStr = \"DESC\";\n      }else{\n        pInfo->idxStr = \"ASC\";\n      }\n      pInfo->orderByConsumed = 1;\n    }\n  }\n\n  assert( p->pSegments==0 );\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xOpen method.\n*/\nstatic int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */\n\n  UNUSED_PARAMETER(pVTab);\n\n  /* Allocate a buffer large enough for an Fts3Cursor structure. If the\n  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, \n  ** if the allocation fails, return SQLITE_NOMEM.\n  */\n  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));\n  if( !pCsr ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(Fts3Cursor));\n  return SQLITE_OK;\n}\n\n/*\n** Close the cursor.  For additional information see the documentation\n** on the xClose method of the virtual table interface.\n*/\nstatic int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  sqlite3_finalize(pCsr->pStmt);\n  sqlite3Fts3ExprFree(pCsr->pExpr);\n  sqlite3Fts3FreeDeferredTokens(pCsr);\n  sqlite3_free(pCsr->aDoclist);\n  sqlite3_free(pCsr->aMatchinfo);\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then\n** compose and prepare an SQL statement of the form:\n**\n**    \"SELECT <columns> FROM %_content WHERE rowid = ?\"\n**\n** (or the equivalent for a content=xxx table) and set pCsr->pStmt to\n** it. If an error occurs, return an SQLite error code.\n**\n** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.\n*/\nstatic int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){\n  int rc = SQLITE_OK;\n  if( pCsr->pStmt==0 ){\n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n    char *zSql;\n    zSql = sqlite3_mprintf(\"SELECT %s WHERE rowid = ?\", p->zReadExprlist);\n    if( !zSql ) return SQLITE_NOMEM;\n    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);\n    sqlite3_free(zSql);\n  }\n  *ppStmt = pCsr->pStmt;\n  return rc;\n}\n\n/*\n** Position the pCsr->pStmt statement so that it is on the row\n** of the %_content table that contains the last match.  Return\n** SQLITE_OK on success.  \n*/\nstatic int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;\n  if( pCsr->isRequireSeek ){\n    sqlite3_stmt *pStmt = 0;\n\n    rc = fts3CursorSeekStmt(pCsr, &pStmt);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);\n      pCsr->isRequireSeek = 0;\n      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){\n        return SQLITE_OK;\n      }else{\n        rc = sqlite3_reset(pCsr->pStmt);\n        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){\n          /* If no row was found and no error has occured, then the %_content\n          ** table is missing a row that is present in the full-text index.\n          ** The data structures are corrupt.  */\n          rc = FTS_CORRUPT_VTAB;\n          pCsr->isEof = 1;\n        }\n      }\n    }\n  }\n\n  if( rc!=SQLITE_OK && pContext ){\n    sqlite3_result_error_code(pContext, rc);\n  }\n  return rc;\n}\n\n/*\n** This function is used to process a single interior node when searching\n** a b-tree for a term or term prefix. The node data is passed to this \n** function via the zNode/nNode parameters. The term to search for is\n** passed in zTerm/nTerm.\n**\n** If piFirst is not NULL, then this function sets *piFirst to the blockid\n** of the child node that heads the sub-tree that may contain the term.\n**\n** If piLast is not NULL, then *piLast is set to the right-most child node\n** that heads a sub-tree that may contain a term for which zTerm/nTerm is\n** a prefix.\n**\n** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.\n*/\nstatic int fts3ScanInteriorNode(\n  const char *zTerm,              /* Term to select leaves for */\n  int nTerm,                      /* Size of term zTerm in bytes */\n  const char *zNode,              /* Buffer containing segment interior node */\n  int nNode,                      /* Size of buffer at zNode */\n  sqlite3_int64 *piFirst,         /* OUT: Selected child node */\n  sqlite3_int64 *piLast           /* OUT: Selected child node */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  const char *zCsr = zNode;       /* Cursor to iterate through node */\n  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */\n  char *zBuffer = 0;              /* Buffer to load terms into */\n  int nAlloc = 0;                 /* Size of allocated buffer */\n  int isFirstTerm = 1;            /* True when processing first term on page */\n  sqlite3_int64 iChild;           /* Block id of child node to descend to */\n\n  /* Skip over the 'height' varint that occurs at the start of every \n  ** interior node. Then load the blockid of the left-child of the b-tree\n  ** node into variable iChild.  \n  **\n  ** Even if the data structure on disk is corrupted, this (reading two\n  ** varints from the buffer) does not risk an overread. If zNode is a\n  ** root node, then the buffer comes from a SELECT statement. SQLite does\n  ** not make this guarantee explicitly, but in practice there are always\n  ** either more than 20 bytes of allocated space following the nNode bytes of\n  ** contents, or two zero bytes. Or, if the node is read from the %_segments\n  ** table, then there are always 20 bytes of zeroed padding following the\n  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).\n  */\n  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);\n  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);\n  if( zCsr>zEnd ){\n    return FTS_CORRUPT_VTAB;\n  }\n  \n  while( zCsr<zEnd && (piFirst || piLast) ){\n    int cmp;                      /* memcmp() result */\n    int nSuffix;                  /* Size of term suffix */\n    int nPrefix = 0;              /* Size of term prefix */\n    int nBuffer;                  /* Total term size */\n  \n    /* Load the next term on the node into zBuffer. Use realloc() to expand\n    ** the size of zBuffer if required.  */\n    if( !isFirstTerm ){\n      zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);\n    }\n    isFirstTerm = 0;\n    zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);\n    \n    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){\n      rc = FTS_CORRUPT_VTAB;\n      goto finish_scan;\n    }\n    if( nPrefix+nSuffix>nAlloc ){\n      char *zNew;\n      nAlloc = (nPrefix+nSuffix) * 2;\n      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);\n      if( !zNew ){\n        rc = SQLITE_NOMEM;\n        goto finish_scan;\n      }\n      zBuffer = zNew;\n    }\n    assert( zBuffer );\n    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);\n    nBuffer = nPrefix + nSuffix;\n    zCsr += nSuffix;\n\n    /* Compare the term we are searching for with the term just loaded from\n    ** the interior node. If the specified term is greater than or equal\n    ** to the term from the interior node, then all terms on the sub-tree \n    ** headed by node iChild are smaller than zTerm. No need to search \n    ** iChild.\n    **\n    ** If the interior node term is larger than the specified term, then\n    ** the tree headed by iChild may contain the specified term.\n    */\n    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));\n    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){\n      *piFirst = iChild;\n      piFirst = 0;\n    }\n\n    if( piLast && cmp<0 ){\n      *piLast = iChild;\n      piLast = 0;\n    }\n\n    iChild++;\n  };\n\n  if( piFirst ) *piFirst = iChild;\n  if( piLast ) *piLast = iChild;\n\n finish_scan:\n  sqlite3_free(zBuffer);\n  return rc;\n}\n\n\n/*\n** The buffer pointed to by argument zNode (size nNode bytes) contains an\n** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)\n** contains a term. This function searches the sub-tree headed by the zNode\n** node for the range of leaf nodes that may contain the specified term\n** or terms for which the specified term is a prefix.\n**\n** If piLeaf is not NULL, then *piLeaf is set to the blockid of the \n** left-most leaf node in the tree that may contain the specified term.\n** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the\n** right-most leaf node that may contain a term for which the specified\n** term is a prefix.\n**\n** It is possible that the range of returned leaf nodes does not contain \n** the specified term or any terms for which it is a prefix. However, if the \n** segment does contain any such terms, they are stored within the identified\n** range. Because this function only inspects interior segment nodes (and\n** never loads leaf nodes into memory), it is not possible to be sure.\n**\n** If an error occurs, an error code other than SQLITE_OK is returned.\n*/ \nstatic int fts3SelectLeaf(\n  Fts3Table *p,                   /* Virtual table handle */\n  const char *zTerm,              /* Term to select leaves for */\n  int nTerm,                      /* Size of term zTerm in bytes */\n  const char *zNode,              /* Buffer containing segment interior node */\n  int nNode,                      /* Size of buffer at zNode */\n  sqlite3_int64 *piLeaf,          /* Selected leaf node */\n  sqlite3_int64 *piLeaf2          /* Selected leaf node */\n){\n  int rc;                         /* Return code */\n  int iHeight;                    /* Height of this node in tree */\n\n  assert( piLeaf || piLeaf2 );\n\n  sqlite3Fts3GetVarint32(zNode, &iHeight);\n  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);\n  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );\n\n  if( rc==SQLITE_OK && iHeight>1 ){\n    char *zBlob = 0;              /* Blob read from %_segments table */\n    int nBlob;                    /* Size of zBlob in bytes */\n\n    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){\n      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);\n      if( rc==SQLITE_OK ){\n        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);\n      }\n      sqlite3_free(zBlob);\n      piLeaf = 0;\n      zBlob = 0;\n    }\n\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);\n    }\n    sqlite3_free(zBlob);\n  }\n\n  return rc;\n}\n\n/*\n** This function is used to create delta-encoded serialized lists of FTS3 \n** varints. Each call to this function appends a single varint to a list.\n*/\nstatic void fts3PutDeltaVarint(\n  char **pp,                      /* IN/OUT: Output pointer */\n  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */\n  sqlite3_int64 iVal              /* Write this value to the list */\n){\n  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );\n  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);\n  *piPrev = iVal;\n}\n\n/*\n** When this function is called, *ppPoslist is assumed to point to the \n** start of a position-list. After it returns, *ppPoslist points to the\n** first byte after the position-list.\n**\n** A position list is list of positions (delta encoded) and columns for \n** a single document record of a doclist.  So, in other words, this\n** routine advances *ppPoslist so that it points to the next docid in\n** the doclist, or to the first byte past the end of the doclist.\n**\n** If pp is not NULL, then the contents of the position list are copied\n** to *pp. *pp is set to point to the first byte past the last byte copied\n** before this function returns.\n*/\nstatic void fts3PoslistCopy(char **pp, char **ppPoslist){\n  char *pEnd = *ppPoslist;\n  char c = 0;\n\n  /* The end of a position list is marked by a zero encoded as an FTS3 \n  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by\n  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail\n  ** of some other, multi-byte, value.\n  **\n  ** The following while-loop moves pEnd to point to the first byte that is not \n  ** immediately preceded by a byte with the 0x80 bit set. Then increments\n  ** pEnd once more so that it points to the byte immediately following the\n  ** last byte in the position-list.\n  */\n  while( *pEnd | c ){\n    c = *pEnd++ & 0x80;\n    testcase( c!=0 && (*pEnd)==0 );\n  }\n  pEnd++;  /* Advance past the POS_END terminator byte */\n\n  if( pp ){\n    int n = (int)(pEnd - *ppPoslist);\n    char *p = *pp;\n    memcpy(p, *ppPoslist, n);\n    p += n;\n    *pp = p;\n  }\n  *ppPoslist = pEnd;\n}\n\n/*\n** When this function is called, *ppPoslist is assumed to point to the \n** start of a column-list. After it returns, *ppPoslist points to the\n** to the terminator (POS_COLUMN or POS_END) byte of the column-list.\n**\n** A column-list is list of delta-encoded positions for a single column\n** within a single document within a doclist.\n**\n** The column-list is terminated either by a POS_COLUMN varint (1) or\n** a POS_END varint (0).  This routine leaves *ppPoslist pointing to\n** the POS_COLUMN or POS_END that terminates the column-list.\n**\n** If pp is not NULL, then the contents of the column-list are copied\n** to *pp. *pp is set to point to the first byte past the last byte copied\n** before this function returns.  The POS_COLUMN or POS_END terminator\n** is not copied into *pp.\n*/\nstatic void fts3ColumnlistCopy(char **pp, char **ppPoslist){\n  char *pEnd = *ppPoslist;\n  char c = 0;\n\n  /* A column-list is terminated by either a 0x01 or 0x00 byte that is\n  ** not part of a multi-byte varint.\n  */\n  while( 0xFE & (*pEnd | c) ){\n    c = *pEnd++ & 0x80;\n    testcase( c!=0 && ((*pEnd)&0xfe)==0 );\n  }\n  if( pp ){\n    int n = (int)(pEnd - *ppPoslist);\n    char *p = *pp;\n    memcpy(p, *ppPoslist, n);\n    p += n;\n    *pp = p;\n  }\n  *ppPoslist = pEnd;\n}\n\n/*\n** Value used to signify the end of an position-list. This is safe because\n** it is not possible to have a document with 2^31 terms.\n*/\n#define POSITION_LIST_END 0x7fffffff\n\n/*\n** This function is used to help parse position-lists. When this function is\n** called, *pp may point to the start of the next varint in the position-list\n** being parsed, or it may point to 1 byte past the end of the position-list\n** (in which case **pp will be a terminator bytes POS_END (0) or\n** (1)).\n**\n** If *pp points past the end of the current position-list, set *pi to \n** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,\n** increment the current value of *pi by the value read, and set *pp to\n** point to the next value before returning.\n**\n** Before calling this routine *pi must be initialized to the value of\n** the previous position, or zero if we are reading the first position\n** in the position-list.  Because positions are delta-encoded, the value\n** of the previous position is needed in order to compute the value of\n** the next position.\n*/\nstatic void fts3ReadNextPos(\n  char **pp,                    /* IN/OUT: Pointer into position-list buffer */\n  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */\n){\n  if( (**pp)&0xFE ){\n    fts3GetDeltaVarint(pp, pi);\n    *pi -= 2;\n  }else{\n    *pi = POSITION_LIST_END;\n  }\n}\n\n/*\n** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by\n** the value of iCol encoded as a varint to *pp.   This will start a new\n** column list.\n**\n** Set *pp to point to the byte just after the last byte written before \n** returning (do not modify it if iCol==0). Return the total number of bytes\n** written (0 if iCol==0).\n*/\nstatic int fts3PutColNumber(char **pp, int iCol){\n  int n = 0;                      /* Number of bytes written */\n  if( iCol ){\n    char *p = *pp;                /* Output pointer */\n    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);\n    *p = 0x01;\n    *pp = &p[n];\n  }\n  return n;\n}\n\n/*\n** Compute the union of two position lists.  The output written\n** into *pp contains all positions of both *pp1 and *pp2 in sorted\n** order and with any duplicates removed.  All pointers are\n** updated appropriately.   The caller is responsible for insuring\n** that there is enough space in *pp to hold the complete output.\n*/\nstatic void fts3PoslistMerge(\n  char **pp,                      /* Output buffer */\n  char **pp1,                     /* Left input list */\n  char **pp2                      /* Right input list */\n){\n  char *p = *pp;\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n\n  while( *p1 || *p2 ){\n    int iCol1;         /* The current column index in pp1 */\n    int iCol2;         /* The current column index in pp2 */\n\n    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);\n    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;\n    else iCol1 = 0;\n\n    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);\n    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;\n    else iCol2 = 0;\n\n    if( iCol1==iCol2 ){\n      sqlite3_int64 i1 = 0;       /* Last position from pp1 */\n      sqlite3_int64 i2 = 0;       /* Last position from pp2 */\n      sqlite3_int64 iPrev = 0;\n      int n = fts3PutColNumber(&p, iCol1);\n      p1 += n;\n      p2 += n;\n\n      /* At this point, both p1 and p2 point to the start of column-lists\n      ** for the same column (the column with index iCol1 and iCol2).\n      ** A column-list is a list of non-negative delta-encoded varints, each \n      ** incremented by 2 before being stored. Each list is terminated by a\n      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists\n      ** and writes the results to buffer p. p is left pointing to the byte\n      ** after the list written. No terminator (POS_END or POS_COLUMN) is\n      ** written to the output.\n      */\n      fts3GetDeltaVarint(&p1, &i1);\n      fts3GetDeltaVarint(&p2, &i2);\n      do {\n        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); \n        iPrev -= 2;\n        if( i1==i2 ){\n          fts3ReadNextPos(&p1, &i1);\n          fts3ReadNextPos(&p2, &i2);\n        }else if( i1<i2 ){\n          fts3ReadNextPos(&p1, &i1);\n        }else{\n          fts3ReadNextPos(&p2, &i2);\n        }\n      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );\n    }else if( iCol1<iCol2 ){\n      p1 += fts3PutColNumber(&p, iCol1);\n      fts3ColumnlistCopy(&p, &p1);\n    }else{\n      p2 += fts3PutColNumber(&p, iCol2);\n      fts3ColumnlistCopy(&p, &p2);\n    }\n  }\n\n  *p++ = POS_END;\n  *pp = p;\n  *pp1 = p1 + 1;\n  *pp2 = p2 + 1;\n}\n\n/*\n** This function is used to merge two position lists into one. When it is\n** called, *pp1 and *pp2 must both point to position lists. A position-list is\n** the part of a doclist that follows each document id. For example, if a row\n** contains:\n**\n**     'a b c'|'x y z'|'a b b a'\n**\n** Then the position list for this row for token 'b' would consist of:\n**\n**     0x02 0x01 0x02 0x03 0x03 0x00\n**\n** When this function returns, both *pp1 and *pp2 are left pointing to the\n** byte following the 0x00 terminator of their respective position lists.\n**\n** If isSaveLeft is 0, an entry is added to the output position list for \n** each position in *pp2 for which there exists one or more positions in\n** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.\n** when the *pp1 token appears before the *pp2 token, but not more than nToken\n** slots before it.\n**\n** e.g. nToken==1 searches for adjacent positions.\n*/\nstatic int fts3PoslistPhraseMerge(\n  char **pp,                      /* IN/OUT: Preallocated output buffer */\n  int nToken,                     /* Maximum difference in token positions */\n  int isSaveLeft,                 /* Save the left position */\n  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */\n  char **pp1,                     /* IN/OUT: Left input list */\n  char **pp2                      /* IN/OUT: Right input list */\n){\n  char *p = *pp;\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n  int iCol1 = 0;\n  int iCol2 = 0;\n\n  /* Never set both isSaveLeft and isExact for the same invocation. */\n  assert( isSaveLeft==0 || isExact==0 );\n\n  assert( p!=0 && *p1!=0 && *p2!=0 );\n  if( *p1==POS_COLUMN ){ \n    p1++;\n    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);\n  }\n  if( *p2==POS_COLUMN ){ \n    p2++;\n    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);\n  }\n\n  while( 1 ){\n    if( iCol1==iCol2 ){\n      char *pSave = p;\n      sqlite3_int64 iPrev = 0;\n      sqlite3_int64 iPos1 = 0;\n      sqlite3_int64 iPos2 = 0;\n\n      if( iCol1 ){\n        *p++ = POS_COLUMN;\n        p += sqlite3Fts3PutVarint(p, iCol1);\n      }\n\n      assert( *p1!=POS_END && *p1!=POS_COLUMN );\n      assert( *p2!=POS_END && *p2!=POS_COLUMN );\n      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;\n      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;\n\n      while( 1 ){\n        if( iPos2==iPos1+nToken \n         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) \n        ){\n          sqlite3_int64 iSave;\n          iSave = isSaveLeft ? iPos1 : iPos2;\n          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;\n          pSave = 0;\n          assert( p );\n        }\n        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){\n          if( (*p2&0xFE)==0 ) break;\n          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;\n        }else{\n          if( (*p1&0xFE)==0 ) break;\n          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;\n        }\n      }\n\n      if( pSave ){\n        assert( pp && p );\n        p = pSave;\n      }\n\n      fts3ColumnlistCopy(0, &p1);\n      fts3ColumnlistCopy(0, &p2);\n      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );\n      if( 0==*p1 || 0==*p2 ) break;\n\n      p1++;\n      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);\n      p2++;\n      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);\n    }\n\n    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of\n    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the\n    ** end of the position list, or the 0x01 that precedes the next \n    ** column-number in the position list. \n    */\n    else if( iCol1<iCol2 ){\n      fts3ColumnlistCopy(0, &p1);\n      if( 0==*p1 ) break;\n      p1++;\n      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);\n    }else{\n      fts3ColumnlistCopy(0, &p2);\n      if( 0==*p2 ) break;\n      p2++;\n      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);\n    }\n  }\n\n  fts3PoslistCopy(0, &p2);\n  fts3PoslistCopy(0, &p1);\n  *pp1 = p1;\n  *pp2 = p2;\n  if( *pp==p ){\n    return 0;\n  }\n  *p++ = 0x00;\n  *pp = p;\n  return 1;\n}\n\n/*\n** Merge two position-lists as required by the NEAR operator. The argument\n** position lists correspond to the left and right phrases of an expression \n** like:\n**\n**     \"phrase 1\" NEAR \"phrase number 2\"\n**\n** Position list *pp1 corresponds to the left-hand side of the NEAR \n** expression and *pp2 to the right. As usual, the indexes in the position \n** lists are the offsets of the last token in each phrase (tokens \"1\" and \"2\" \n** in the example above).\n**\n** The output position list - written to *pp - is a copy of *pp2 with those\n** entries that are not sufficiently NEAR entries in *pp1 removed.\n*/\nstatic int fts3PoslistNearMerge(\n  char **pp,                      /* Output buffer */\n  char *aTmp,                     /* Temporary buffer space */\n  int nRight,                     /* Maximum difference in token positions */\n  int nLeft,                      /* Maximum difference in token positions */\n  char **pp1,                     /* IN/OUT: Left input list */\n  char **pp2                      /* IN/OUT: Right input list */\n){\n  char *p1 = *pp1;\n  char *p2 = *pp2;\n\n  char *pTmp1 = aTmp;\n  char *pTmp2;\n  char *aTmp2;\n  int res = 1;\n\n  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);\n  aTmp2 = pTmp2 = pTmp1;\n  *pp1 = p1;\n  *pp2 = p2;\n  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);\n  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){\n    fts3PoslistMerge(pp, &aTmp, &aTmp2);\n  }else if( pTmp1!=aTmp ){\n    fts3PoslistCopy(pp, &aTmp);\n  }else if( pTmp2!=aTmp2 ){\n    fts3PoslistCopy(pp, &aTmp2);\n  }else{\n    res = 0;\n  }\n\n  return res;\n}\n\n/* \n** An instance of this function is used to merge together the (potentially\n** large number of) doclists for each term that matches a prefix query.\n** See function fts3TermSelectMerge() for details.\n*/\ntypedef struct TermSelect TermSelect;\nstruct TermSelect {\n  char *aaOutput[16];             /* Malloc'd output buffers */\n  int anOutput[16];               /* Size each output buffer in bytes */\n};\n\n/*\n** This function is used to read a single varint from a buffer. Parameter\n** pEnd points 1 byte past the end of the buffer. When this function is\n** called, if *pp points to pEnd or greater, then the end of the buffer\n** has been reached. In this case *pp is set to 0 and the function returns.\n**\n** If *pp does not point to or past pEnd, then a single varint is read\n** from *pp. *pp is then set to point 1 byte past the end of the read varint.\n**\n** If bDescIdx is false, the value read is added to *pVal before returning.\n** If it is true, the value read is subtracted from *pVal before this \n** function returns.\n*/\nstatic void fts3GetDeltaVarint3(\n  char **pp,                      /* IN/OUT: Point to read varint from */\n  char *pEnd,                     /* End of buffer */\n  int bDescIdx,                   /* True if docids are descending */\n  sqlite3_int64 *pVal             /* IN/OUT: Integer value */\n){\n  if( *pp>=pEnd ){\n    *pp = 0;\n  }else{\n    sqlite3_int64 iVal;\n    *pp += sqlite3Fts3GetVarint(*pp, &iVal);\n    if( bDescIdx ){\n      *pVal -= iVal;\n    }else{\n      *pVal += iVal;\n    }\n  }\n}\n\n/*\n** This function is used to write a single varint to a buffer. The varint\n** is written to *pp. Before returning, *pp is set to point 1 byte past the\n** end of the value written.\n**\n** If *pbFirst is zero when this function is called, the value written to\n** the buffer is that of parameter iVal. \n**\n** If *pbFirst is non-zero when this function is called, then the value \n** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)\n** (if bDescIdx is non-zero).\n**\n** Before returning, this function always sets *pbFirst to 1 and *piPrev\n** to the value of parameter iVal.\n*/\nstatic void fts3PutDeltaVarint3(\n  char **pp,                      /* IN/OUT: Output pointer */\n  int bDescIdx,                   /* True for descending docids */\n  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */\n  int *pbFirst,                   /* IN/OUT: True after first int written */\n  sqlite3_int64 iVal              /* Write this value to the list */\n){\n  sqlite3_int64 iWrite;\n  if( bDescIdx==0 || *pbFirst==0 ){\n    iWrite = iVal - *piPrev;\n  }else{\n    iWrite = *piPrev - iVal;\n  }\n  assert( *pbFirst || *piPrev==0 );\n  assert( *pbFirst==0 || iWrite>0 );\n  *pp += sqlite3Fts3PutVarint(*pp, iWrite);\n  *piPrev = iVal;\n  *pbFirst = 1;\n}\n\n\n/*\n** This macro is used by various functions that merge doclists. The two\n** arguments are 64-bit docid values. If the value of the stack variable\n** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). \n** Otherwise, (i2-i1).\n**\n** Using this makes it easier to write code that can merge doclists that are\n** sorted in either ascending or descending order.\n*/\n#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))\n\n/*\n** This function does an \"OR\" merge of two doclists (output contains all\n** positions contained in either argument doclist). If the docids in the \n** input doclists are sorted in ascending order, parameter bDescDoclist\n** should be false. If they are sorted in ascending order, it should be\n** passed a non-zero value.\n**\n** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer\n** containing the output doclist and SQLITE_OK is returned. In this case\n** *pnOut is set to the number of bytes in the output doclist.\n**\n** If an error occurs, an SQLite error code is returned. The output values\n** are undefined in this case.\n*/\nstatic int fts3DoclistOrMerge(\n  int bDescDoclist,               /* True if arguments are desc */\n  char *a1, int n1,               /* First doclist */\n  char *a2, int n2,               /* Second doclist */\n  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */\n){\n  sqlite3_int64 i1 = 0;\n  sqlite3_int64 i2 = 0;\n  sqlite3_int64 iPrev = 0;\n  char *pEnd1 = &a1[n1];\n  char *pEnd2 = &a2[n2];\n  char *p1 = a1;\n  char *p2 = a2;\n  char *p;\n  char *aOut;\n  int bFirstOut = 0;\n\n  *paOut = 0;\n  *pnOut = 0;\n\n  /* Allocate space for the output. Both the input and output doclists\n  ** are delta encoded. If they are in ascending order (bDescDoclist==0),\n  ** then the first docid in each list is simply encoded as a varint. For\n  ** each subsequent docid, the varint stored is the difference between the\n  ** current and previous docid (a positive number - since the list is in\n  ** ascending order).\n  **\n  ** The first docid written to the output is therefore encoded using the \n  ** same number of bytes as it is in whichever of the input lists it is\n  ** read from. And each subsequent docid read from the same input list \n  ** consumes either the same or less bytes as it did in the input (since\n  ** the difference between it and the previous value in the output must\n  ** be a positive value less than or equal to the delta value read from \n  ** the input list). The same argument applies to all but the first docid\n  ** read from the 'other' list. And to the contents of all position lists\n  ** that will be copied and merged from the input to the output.\n  **\n  ** However, if the first docid copied to the output is a negative number,\n  ** then the encoding of the first docid from the 'other' input list may\n  ** be larger in the output than it was in the input (since the delta value\n  ** may be a larger positive integer than the actual docid).\n  **\n  ** The space required to store the output is therefore the sum of the\n  ** sizes of the two inputs, plus enough space for exactly one of the input\n  ** docids to grow. \n  **\n  ** A symetric argument may be made if the doclists are in descending \n  ** order.\n  */\n  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);\n  if( !aOut ) return SQLITE_NOMEM;\n\n  p = aOut;\n  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);\n  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);\n  while( p1 || p2 ){\n    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);\n\n    if( p2 && p1 && iDiff==0 ){\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      fts3PoslistMerge(&p, &p1, &p2);\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }else if( !p2 || (p1 && iDiff<0) ){\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      fts3PoslistCopy(&p, &p1);\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n    }else{\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);\n      fts3PoslistCopy(&p, &p2);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }\n  }\n\n  *paOut = aOut;\n  *pnOut = (int)(p-aOut);\n  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );\n  return SQLITE_OK;\n}\n\n/*\n** This function does a \"phrase\" merge of two doclists. In a phrase merge,\n** the output contains a copy of each position from the right-hand input\n** doclist for which there is a position in the left-hand input doclist\n** exactly nDist tokens before it.\n**\n** If the docids in the input doclists are sorted in ascending order,\n** parameter bDescDoclist should be false. If they are sorted in ascending \n** order, it should be passed a non-zero value.\n**\n** The right-hand input doclist is overwritten by this function.\n*/\nstatic void fts3DoclistPhraseMerge(\n  int bDescDoclist,               /* True if arguments are desc */\n  int nDist,                      /* Distance from left to right (1=adjacent) */\n  char *aLeft, int nLeft,         /* Left doclist */\n  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */\n){\n  sqlite3_int64 i1 = 0;\n  sqlite3_int64 i2 = 0;\n  sqlite3_int64 iPrev = 0;\n  char *pEnd1 = &aLeft[nLeft];\n  char *pEnd2 = &aRight[*pnRight];\n  char *p1 = aLeft;\n  char *p2 = aRight;\n  char *p;\n  int bFirstOut = 0;\n  char *aOut = aRight;\n\n  assert( nDist>0 );\n\n  p = aOut;\n  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);\n  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);\n\n  while( p1 && p2 ){\n    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);\n    if( iDiff==0 ){\n      char *pSave = p;\n      sqlite3_int64 iPrevSave = iPrev;\n      int bFirstOutSave = bFirstOut;\n\n      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);\n      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){\n        p = pSave;\n        iPrev = iPrevSave;\n        bFirstOut = bFirstOutSave;\n      }\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }else if( iDiff<0 ){\n      fts3PoslistCopy(0, &p1);\n      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);\n    }else{\n      fts3PoslistCopy(0, &p2);\n      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);\n    }\n  }\n\n  *pnRight = (int)(p - aOut);\n}\n\n/*\n** Argument pList points to a position list nList bytes in size. This\n** function checks to see if the position list contains any entries for\n** a token in position 0 (of any column). If so, it writes argument iDelta\n** to the output buffer pOut, followed by a position list consisting only\n** of the entries from pList at position 0, and terminated by an 0x00 byte.\n** The value returned is the number of bytes written to pOut (if any).\n*/\nSQLITE_PRIVATE int sqlite3Fts3FirstFilter(\n  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */\n  char *pList,                    /* Position list (no 0x00 term) */\n  int nList,                      /* Size of pList in bytes */\n  char *pOut                      /* Write output here */\n){\n  int nOut = 0;\n  int bWritten = 0;               /* True once iDelta has been written */\n  char *p = pList;\n  char *pEnd = &pList[nList];\n\n  if( *p!=0x01 ){\n    if( *p==0x02 ){\n      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);\n      pOut[nOut++] = 0x02;\n      bWritten = 1;\n    }\n    fts3ColumnlistCopy(0, &p);\n  }\n\n  while( p<pEnd && *p==0x01 ){\n    sqlite3_int64 iCol;\n    p++;\n    p += sqlite3Fts3GetVarint(p, &iCol);\n    if( *p==0x02 ){\n      if( bWritten==0 ){\n        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);\n        bWritten = 1;\n      }\n      pOut[nOut++] = 0x01;\n      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);\n      pOut[nOut++] = 0x02;\n    }\n    fts3ColumnlistCopy(0, &p);\n  }\n  if( bWritten ){\n    pOut[nOut++] = 0x00;\n  }\n\n  return nOut;\n}\n\n\n/*\n** Merge all doclists in the TermSelect.aaOutput[] array into a single\n** doclist stored in TermSelect.aaOutput[0]. If successful, delete all\n** other doclists (except the aaOutput[0] one) and return SQLITE_OK.\n**\n** If an OOM error occurs, return SQLITE_NOMEM. In this case it is\n** the responsibility of the caller to free any doclists left in the\n** TermSelect.aaOutput[] array.\n*/\nstatic int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){\n  char *aOut = 0;\n  int nOut = 0;\n  int i;\n\n  /* Loop through the doclists in the aaOutput[] array. Merge them all\n  ** into a single doclist.\n  */\n  for(i=0; i<SizeofArray(pTS->aaOutput); i++){\n    if( pTS->aaOutput[i] ){\n      if( !aOut ){\n        aOut = pTS->aaOutput[i];\n        nOut = pTS->anOutput[i];\n        pTS->aaOutput[i] = 0;\n      }else{\n        int nNew;\n        char *aNew;\n\n        int rc = fts3DoclistOrMerge(p->bDescIdx, \n            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew\n        );\n        if( rc!=SQLITE_OK ){\n          sqlite3_free(aOut);\n          return rc;\n        }\n\n        sqlite3_free(pTS->aaOutput[i]);\n        sqlite3_free(aOut);\n        pTS->aaOutput[i] = 0;\n        aOut = aNew;\n        nOut = nNew;\n      }\n    }\n  }\n\n  pTS->aaOutput[0] = aOut;\n  pTS->anOutput[0] = nOut;\n  return SQLITE_OK;\n}\n\n/*\n** Merge the doclist aDoclist/nDoclist into the TermSelect object passed\n** as the first argument. The merge is an \"OR\" merge (see function\n** fts3DoclistOrMerge() for details).\n**\n** This function is called with the doclist for each term that matches\n** a queried prefix. It merges all these doclists into one, the doclist\n** for the specified prefix. Since there can be a very large number of\n** doclists to merge, the merging is done pair-wise using the TermSelect\n** object.\n**\n** This function returns SQLITE_OK if the merge is successful, or an\n** SQLite error code (SQLITE_NOMEM) if an error occurs.\n*/\nstatic int fts3TermSelectMerge(\n  Fts3Table *p,                   /* FTS table handle */\n  TermSelect *pTS,                /* TermSelect object to merge into */\n  char *aDoclist,                 /* Pointer to doclist */\n  int nDoclist                    /* Size of aDoclist in bytes */\n){\n  if( pTS->aaOutput[0]==0 ){\n    /* If this is the first term selected, copy the doclist to the output\n    ** buffer using memcpy(). */\n    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);\n    pTS->anOutput[0] = nDoclist;\n    if( pTS->aaOutput[0] ){\n      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);\n    }else{\n      return SQLITE_NOMEM;\n    }\n  }else{\n    char *aMerge = aDoclist;\n    int nMerge = nDoclist;\n    int iOut;\n\n    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){\n      if( pTS->aaOutput[iOut]==0 ){\n        assert( iOut>0 );\n        pTS->aaOutput[iOut] = aMerge;\n        pTS->anOutput[iOut] = nMerge;\n        break;\n      }else{\n        char *aNew;\n        int nNew;\n\n        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, \n            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew\n        );\n        if( rc!=SQLITE_OK ){\n          if( aMerge!=aDoclist ) sqlite3_free(aMerge);\n          return rc;\n        }\n\n        if( aMerge!=aDoclist ) sqlite3_free(aMerge);\n        sqlite3_free(pTS->aaOutput[iOut]);\n        pTS->aaOutput[iOut] = 0;\n  \n        aMerge = aNew;\n        nMerge = nNew;\n        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){\n          pTS->aaOutput[iOut] = aMerge;\n          pTS->anOutput[iOut] = nMerge;\n        }\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Append SegReader object pNew to the end of the pCsr->apSegment[] array.\n*/\nstatic int fts3SegReaderCursorAppend(\n  Fts3MultiSegReader *pCsr, \n  Fts3SegReader *pNew\n){\n  if( (pCsr->nSegment%16)==0 ){\n    Fts3SegReader **apNew;\n    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);\n    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);\n    if( !apNew ){\n      sqlite3Fts3SegReaderFree(pNew);\n      return SQLITE_NOMEM;\n    }\n    pCsr->apSegment = apNew;\n  }\n  pCsr->apSegment[pCsr->nSegment++] = pNew;\n  return SQLITE_OK;\n}\n\n/*\n** Add seg-reader objects to the Fts3MultiSegReader object passed as the\n** 8th argument.\n**\n** This function returns SQLITE_OK if successful, or an SQLite error code\n** otherwise.\n*/\nstatic int fts3SegReaderCursor(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */\n  int iLevel,                     /* Level of segments to scan */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  int isScan,                     /* True to scan from zTerm to EOF */\n  Fts3MultiSegReader *pCsr        /* Cursor object to populate */\n){\n  int rc = SQLITE_OK;             /* Error code */\n  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */\n  int rc2;                        /* Result of sqlite3_reset() */\n\n  /* If iLevel is less than 0 and this is not a scan, include a seg-reader \n  ** for the pending-terms. If this is a scan, then this call must be being\n  ** made by an fts4aux module, not an FTS table. In this case calling\n  ** Fts3SegReaderPending might segfault, as the data structures used by \n  ** fts4aux are not completely populated. So it's easiest to filter these\n  ** calls out here.  */\n  if( iLevel<0 && p->aIndex ){\n    Fts3SegReader *pSeg = 0;\n    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);\n    if( rc==SQLITE_OK && pSeg ){\n      rc = fts3SegReaderCursorAppend(pCsr, pSeg);\n    }\n  }\n\n  if( iLevel!=FTS3_SEGCURSOR_PENDING ){\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){\n      Fts3SegReader *pSeg = 0;\n\n      /* Read the values returned by the SELECT into local variables. */\n      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);\n      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);\n      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);\n      int nRoot = sqlite3_column_bytes(pStmt, 4);\n      char const *zRoot = sqlite3_column_blob(pStmt, 4);\n\n      /* If zTerm is not NULL, and this segment is not stored entirely on its\n      ** root node, the range of leaves scanned can be reduced. Do this. */\n      if( iStartBlock && zTerm ){\n        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);\n        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);\n        if( rc!=SQLITE_OK ) goto finished;\n        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;\n      }\n \n      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, \n          (isPrefix==0 && isScan==0),\n          iStartBlock, iLeavesEndBlock, \n          iEndBlock, zRoot, nRoot, &pSeg\n      );\n      if( rc!=SQLITE_OK ) goto finished;\n      rc = fts3SegReaderCursorAppend(pCsr, pSeg);\n    }\n  }\n\n finished:\n  rc2 = sqlite3_reset(pStmt);\n  if( rc==SQLITE_DONE ) rc = rc2;\n\n  return rc;\n}\n\n/*\n** Set up a cursor object for iterating through a full-text index or a \n** single level therein.\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language-id to search */\n  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */\n  int iLevel,                     /* Level of segments to scan */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  int isScan,                     /* True to scan from zTerm to EOF */\n  Fts3MultiSegReader *pCsr       /* Cursor object to populate */\n){\n  assert( iIndex>=0 && iIndex<p->nIndex );\n  assert( iLevel==FTS3_SEGCURSOR_ALL\n      ||  iLevel==FTS3_SEGCURSOR_PENDING \n      ||  iLevel>=0\n  );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );\n  assert( isPrefix==0 || isScan==0 );\n\n  memset(pCsr, 0, sizeof(Fts3MultiSegReader));\n  return fts3SegReaderCursor(\n      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr\n  );\n}\n\n/*\n** In addition to its current configuration, have the Fts3MultiSegReader\n** passed as the 4th argument also scan the doclist for term zTerm/nTerm.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3SegReaderCursorAddZero(\n  Fts3Table *p,                   /* FTS virtual table handle */\n  int iLangid,\n  const char *zTerm,              /* Term to scan doclist of */\n  int nTerm,                      /* Number of bytes in zTerm */\n  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */\n){\n  return fts3SegReaderCursor(p, \n      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr\n  );\n}\n\n/*\n** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,\n** if isPrefix is true, to scan the doclist for all terms for which \n** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write\n** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return\n** an SQLite error code.\n**\n** It is the responsibility of the caller to free this object by eventually\n** passing it to fts3SegReaderCursorFree() \n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n** Output parameter *ppSegcsr is set to 0 if an error occurs.\n*/\nstatic int fts3TermSegReaderCursor(\n  Fts3Cursor *pCsr,               /* Virtual table cursor handle */\n  const char *zTerm,              /* Term to query for */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int isPrefix,                   /* True for a prefix search */\n  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */\n){\n  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */\n  int rc = SQLITE_NOMEM;          /* Return code */\n\n  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));\n  if( pSegcsr ){\n    int i;\n    int bFound = 0;               /* True once an index has been found */\n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n\n    if( isPrefix ){\n      for(i=1; bFound==0 && i<p->nIndex; i++){\n        if( p->aIndex[i].nPrefix==nTerm ){\n          bFound = 1;\n          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr\n          );\n          pSegcsr->bLookup = 1;\n        }\n      }\n\n      for(i=1; bFound==0 && i<p->nIndex; i++){\n        if( p->aIndex[i].nPrefix==nTerm+1 ){\n          bFound = 1;\n          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr\n          );\n          if( rc==SQLITE_OK ){\n            rc = fts3SegReaderCursorAddZero(\n                p, pCsr->iLangid, zTerm, nTerm, pSegcsr\n            );\n          }\n        }\n      }\n    }\n\n    if( bFound==0 ){\n      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, \n          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr\n      );\n      pSegcsr->bLookup = !isPrefix;\n    }\n  }\n\n  *ppSegcsr = pSegcsr;\n  return rc;\n}\n\n/*\n** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().\n*/\nstatic void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){\n  sqlite3Fts3SegReaderFinish(pSegcsr);\n  sqlite3_free(pSegcsr);\n}\n\n/*\n** This function retreives the doclist for the specified term (or term\n** prefix) from the database.\n*/\nstatic int fts3TermSelect(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3PhraseToken *pTok,          /* Token to query for */\n  int iColumn,                    /* Column to query (or -ve for all columns) */\n  int *pnOut,                     /* OUT: Size of buffer at *ppOut */\n  char **ppOut                    /* OUT: Malloced result buffer */\n){\n  int rc;                         /* Return code */\n  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */\n  TermSelect tsc;                 /* Object for pair-wise doclist merging */\n  Fts3SegFilter filter;           /* Segment term filter configuration */\n\n  pSegcsr = pTok->pSegcsr;\n  memset(&tsc, 0, sizeof(TermSelect));\n\n  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS\n        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)\n        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)\n        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);\n  filter.iCol = iColumn;\n  filter.zTerm = pTok->z;\n  filter.nTerm = pTok->n;\n\n  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);\n  while( SQLITE_OK==rc\n      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) \n  ){\n    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts3TermSelectFinishMerge(p, &tsc);\n  }\n  if( rc==SQLITE_OK ){\n    *ppOut = tsc.aaOutput[0];\n    *pnOut = tsc.anOutput[0];\n  }else{\n    int i;\n    for(i=0; i<SizeofArray(tsc.aaOutput); i++){\n      sqlite3_free(tsc.aaOutput[i]);\n    }\n  }\n\n  fts3SegReaderCursorFree(pSegcsr);\n  pTok->pSegcsr = 0;\n  return rc;\n}\n\n/*\n** This function counts the total number of docids in the doclist stored\n** in buffer aList[], size nList bytes.\n**\n** If the isPoslist argument is true, then it is assumed that the doclist\n** contains a position-list following each docid. Otherwise, it is assumed\n** that the doclist is simply a list of docids stored as delta encoded \n** varints.\n*/\nstatic int fts3DoclistCountDocids(char *aList, int nList){\n  int nDoc = 0;                   /* Return value */\n  if( aList ){\n    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */\n    char *p = aList;              /* Cursor */\n    while( p<aEnd ){\n      nDoc++;\n      while( (*p++)&0x80 );     /* Skip docid varint */\n      fts3PoslistCopy(0, &p);   /* Skip over position list */\n    }\n  }\n\n  return nDoc;\n}\n\n/*\n** Advance the cursor to the next row in the %_content table that\n** matches the search criteria.  For a MATCH search, this will be\n** the next row that matches. For a full-table scan, this will be\n** simply the next row in the %_content table.  For a docid lookup,\n** this routine simply sets the EOF flag.\n**\n** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned\n** even if we reach end-of-file.  The fts3EofMethod() will be called\n** subsequently to determine whether or not an EOF was hit.\n*/\nstatic int fts3NextMethod(sqlite3_vtab_cursor *pCursor){\n  int rc;\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){\n    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){\n      pCsr->isEof = 1;\n      rc = sqlite3_reset(pCsr->pStmt);\n    }else{\n      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);\n      rc = SQLITE_OK;\n    }\n  }else{\n    rc = fts3EvalNext((Fts3Cursor *)pCursor);\n  }\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  return rc;\n}\n\n/*\n** This is the xFilter interface for the virtual table.  See\n** the virtual table xFilter method documentation for additional\n** information.\n**\n** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against\n** the %_content table.\n**\n** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry\n** in the %_content table.\n**\n** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The\n** column on the left-hand side of the MATCH operator is column\n** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand\n** side of the MATCH operator.\n*/\nstatic int fts3FilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  int rc;\n  char *zSql;                     /* SQL statement used to access %_content */\n  Fts3Table *p = (Fts3Table *)pCursor->pVtab;\n  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;\n\n  UNUSED_PARAMETER(idxStr);\n  UNUSED_PARAMETER(nVal);\n\n  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );\n  assert( nVal==0 || nVal==1 || nVal==2 );\n  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );\n  assert( p->pSegments==0 );\n\n  /* In case the cursor has been used before, clear it now. */\n  sqlite3_finalize(pCsr->pStmt);\n  sqlite3_free(pCsr->aDoclist);\n  sqlite3Fts3ExprFree(pCsr->pExpr);\n  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));\n\n  if( idxStr ){\n    pCsr->bDesc = (idxStr[0]=='D');\n  }else{\n    pCsr->bDesc = p->bDescIdx;\n  }\n  pCsr->eSearch = (i16)idxNum;\n\n  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){\n    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;\n    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);\n\n    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){\n      return SQLITE_NOMEM;\n    }\n\n    pCsr->iLangid = 0;\n    if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);\n\n    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,\n        p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr\n    );\n    if( rc!=SQLITE_OK ){\n      if( rc==SQLITE_ERROR ){\n        static const char *zErr = \"malformed MATCH expression: [%s]\";\n        p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);\n      }\n      return rc;\n    }\n\n    rc = sqlite3Fts3ReadLock(p);\n    if( rc!=SQLITE_OK ) return rc;\n\n    rc = fts3EvalStart(pCsr);\n\n    sqlite3Fts3SegmentsClose(p);\n    if( rc!=SQLITE_OK ) return rc;\n    pCsr->pNextId = pCsr->aDoclist;\n    pCsr->iPrevId = 0;\n  }\n\n  /* Compile a SELECT statement for this cursor. For a full-table-scan, the\n  ** statement loops through all rows of the %_content table. For a\n  ** full-text query or docid lookup, the statement retrieves a single\n  ** row by docid.\n  */\n  if( idxNum==FTS3_FULLSCAN_SEARCH ){\n    zSql = sqlite3_mprintf(\n        \"SELECT %s ORDER BY rowid %s\",\n        p->zReadExprlist, (pCsr->bDesc ? \"DESC\" : \"ASC\")\n    );\n    if( zSql ){\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);\n      sqlite3_free(zSql);\n    }else{\n      rc = SQLITE_NOMEM;\n    }\n  }else if( idxNum==FTS3_DOCID_SEARCH ){\n    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);\n    }\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  return fts3NextMethod(pCursor);\n}\n\n/* \n** This is the xEof method of the virtual table. SQLite calls this \n** routine to find out if it has reached the end of a result set.\n*/\nstatic int fts3EofMethod(sqlite3_vtab_cursor *pCursor){\n  return ((Fts3Cursor *)pCursor)->isEof;\n}\n\n/* \n** This is the xRowid method. The SQLite core calls this routine to\n** retrieve the rowid for the current row of the result set. fts3\n** exposes %_content.docid as the rowid for the virtual table. The\n** rowid should be written to *pRowid.\n*/\nstatic int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){\n  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;\n  *pRowid = pCsr->iPrevId;\n  return SQLITE_OK;\n}\n\n/* \n** This is the xColumn method, called by SQLite to request a value from\n** the row that the supplied cursor currently points to.\n**\n** If:\n**\n**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.\n**   (iCol == p->nColumn)   -> Magic column with the same name as the table.\n**   (iCol == p->nColumn+1) -> Docid column\n**   (iCol == p->nColumn+2) -> Langid column\n*/\nstatic int fts3ColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;\n  Fts3Table *p = (Fts3Table *)pCursor->pVtab;\n\n  /* The column value supplied by SQLite must be in range. */\n  assert( iCol>=0 && iCol<=p->nColumn+2 );\n\n  if( iCol==p->nColumn+1 ){\n    /* This call is a request for the \"docid\" column. Since \"docid\" is an \n    ** alias for \"rowid\", use the xRowid() method to obtain the value.\n    */\n    sqlite3_result_int64(pCtx, pCsr->iPrevId);\n  }else if( iCol==p->nColumn ){\n    /* The extra column whose name is the same as the table.\n    ** Return a blob which is a pointer to the cursor.  */\n    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);\n  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){\n    sqlite3_result_int64(pCtx, pCsr->iLangid);\n  }else{\n    /* The requested column is either a user column (one that contains \n    ** indexed data), or the language-id column.  */\n    rc = fts3CursorSeek(0, pCsr);\n\n    if( rc==SQLITE_OK ){\n      if( iCol==p->nColumn+2 ){\n        int iLangid = 0;\n        if( p->zLanguageid ){\n          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);\n        }\n        sqlite3_result_int(pCtx, iLangid);\n      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){\n        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));\n      }\n    }\n  }\n\n  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );\n  return rc;\n}\n\n/* \n** This function is the implementation of the xUpdate callback used by \n** FTS3 virtual tables. It is invoked by SQLite each time a row is to be\n** inserted, updated or deleted.\n*/\nstatic int fts3UpdateMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Size of argument array */\n  sqlite3_value **apVal,          /* Array of arguments */\n  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */\n){\n  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);\n}\n\n/*\n** Implementation of xSync() method. Flush the contents of the pending-terms\n** hash-table to the database.\n*/\nstatic int fts3SyncMethod(sqlite3_vtab *pVtab){\n\n  /* Following an incremental-merge operation, assuming that the input\n  ** segments are not completely consumed (the usual case), they are updated\n  ** in place to remove the entries that have already been merged. This\n  ** involves updating the leaf block that contains the smallest unmerged\n  ** entry and each block (if any) between the leaf and the root node. So\n  ** if the height of the input segment b-trees is N, and input segments\n  ** are merged eight at a time, updating the input segments at the end\n  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually\n  ** small - often between 0 and 2. So the overhead of the incremental\n  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead\n  ** dwarfing the actual productive work accomplished, the incremental merge\n  ** is only attempted if it will write at least 64 leaf blocks. Hence\n  ** nMinMerge.\n  **\n  ** Of course, updating the input segments also involves deleting a bunch\n  ** of blocks from the segments table. But this is not considered overhead\n  ** as it would also be required by a crisis-merge that used the same input \n  ** segments.\n  */\n  const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */\n\n  Fts3Table *p = (Fts3Table*)pVtab;\n  int rc = sqlite3Fts3PendingTermsFlush(p);\n\n  if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){\n    int mxLevel = 0;              /* Maximum relative level value in db */\n    int A;                        /* Incr-merge parameter A */\n\n    rc = sqlite3Fts3MaxLevel(p, &mxLevel);\n    assert( rc==SQLITE_OK || mxLevel==0 );\n    A = p->nLeafAdd * mxLevel;\n    A += (A/2);\n    if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);\n  }\n  sqlite3Fts3SegmentsClose(p);\n  return rc;\n}\n\n/*\n** Implementation of xBegin() method. This is a no-op.\n*/\nstatic int fts3BeginMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  UNUSED_PARAMETER(pVtab);\n  assert( p->pSegments==0 );\n  assert( p->nPendingData==0 );\n  assert( p->inTransaction!=1 );\n  TESTONLY( p->inTransaction = 1 );\n  TESTONLY( p->mxSavepoint = -1; );\n  p->nLeafAdd = 0;\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xCommit() method. This is a no-op. The contents of\n** the pending-terms hash-table have already been flushed into the database\n** by fts3SyncMethod().\n*/\nstatic int fts3CommitMethod(sqlite3_vtab *pVtab){\n  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );\n  UNUSED_PARAMETER(pVtab);\n  assert( p->nPendingData==0 );\n  assert( p->inTransaction!=0 );\n  assert( p->pSegments==0 );\n  TESTONLY( p->inTransaction = 0 );\n  TESTONLY( p->mxSavepoint = -1; );\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of xRollback(). Discard the contents of the pending-terms\n** hash-table. Any changes made to the database are reverted by SQLite.\n*/\nstatic int fts3RollbackMethod(sqlite3_vtab *pVtab){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  sqlite3Fts3PendingTermsClear(p);\n  assert( p->inTransaction!=0 );\n  TESTONLY( p->inTransaction = 0 );\n  TESTONLY( p->mxSavepoint = -1; );\n  return SQLITE_OK;\n}\n\n/*\n** When called, *ppPoslist must point to the byte immediately following the\n** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function\n** moves *ppPoslist so that it instead points to the first byte of the\n** same position list.\n*/\nstatic void fts3ReversePoslist(char *pStart, char **ppPoslist){\n  char *p = &(*ppPoslist)[-2];\n  char c = 0;\n\n  while( p>pStart && (c=*p--)==0 );\n  while( p>pStart && (*p & 0x80) | c ){ \n    c = *p--; \n  }\n  if( p>pStart ){ p = &p[2]; }\n  while( *p++&0x80 );\n  *ppPoslist = p;\n}\n\n/*\n** Helper function used by the implementation of the overloaded snippet(),\n** offsets() and optimize() SQL functions.\n**\n** If the value passed as the third argument is a blob of size\n** sizeof(Fts3Cursor*), then the blob contents are copied to the \n** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error\n** message is written to context pContext and SQLITE_ERROR returned. The\n** string passed via zFunc is used as part of the error message.\n*/\nstatic int fts3FunctionArg(\n  sqlite3_context *pContext,      /* SQL function call context */\n  const char *zFunc,              /* Function name */\n  sqlite3_value *pVal,            /* argv[0] passed to function */\n  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */\n){\n  Fts3Cursor *pRet;\n  if( sqlite3_value_type(pVal)!=SQLITE_BLOB \n   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)\n  ){\n    char *zErr = sqlite3_mprintf(\"illegal first argument to %s\", zFunc);\n    sqlite3_result_error(pContext, zErr, -1);\n    sqlite3_free(zErr);\n    return SQLITE_ERROR;\n  }\n  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));\n  *ppCsr = pRet;\n  return SQLITE_OK;\n}\n\n/*\n** Implementation of the snippet() function for FTS3\n*/\nstatic void fts3SnippetFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of apVal[] array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n  const char *zStart = \"<b>\";\n  const char *zEnd = \"</b>\";\n  const char *zEllipsis = \"<b>...</b>\";\n  int iCol = -1;\n  int nToken = 15;                /* Default number of tokens in snippet */\n\n  /* There must be at least one argument passed to this function (otherwise\n  ** the non-overloaded version would have been called instead of this one).\n  */\n  assert( nVal>=1 );\n\n  if( nVal>6 ){\n    sqlite3_result_error(pContext, \n        \"wrong number of arguments to function snippet()\", -1);\n    return;\n  }\n  if( fts3FunctionArg(pContext, \"snippet\", apVal[0], &pCsr) ) return;\n\n  switch( nVal ){\n    case 6: nToken = sqlite3_value_int(apVal[5]);\n    case 5: iCol = sqlite3_value_int(apVal[4]);\n    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);\n    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);\n    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);\n  }\n  if( !zEllipsis || !zEnd || !zStart ){\n    sqlite3_result_error_nomem(pContext);\n  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){\n    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);\n  }\n}\n\n/*\n** Implementation of the offsets() function for FTS3\n*/\nstatic void fts3OffsetsFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n\n  UNUSED_PARAMETER(nVal);\n\n  assert( nVal==1 );\n  if( fts3FunctionArg(pContext, \"offsets\", apVal[0], &pCsr) ) return;\n  assert( pCsr );\n  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){\n    sqlite3Fts3Offsets(pContext, pCsr);\n  }\n}\n\n/* \n** Implementation of the special optimize() function for FTS3. This \n** function merges all segments in the database to a single segment.\n** Example usage is:\n**\n**   SELECT optimize(t) FROM t LIMIT 1;\n**\n** where 't' is the name of an FTS3 table.\n*/\nstatic void fts3OptimizeFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  int rc;                         /* Return code */\n  Fts3Table *p;                   /* Virtual table handle */\n  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */\n\n  UNUSED_PARAMETER(nVal);\n\n  assert( nVal==1 );\n  if( fts3FunctionArg(pContext, \"optimize\", apVal[0], &pCursor) ) return;\n  p = (Fts3Table *)pCursor->base.pVtab;\n  assert( p );\n\n  rc = sqlite3Fts3Optimize(p);\n\n  switch( rc ){\n    case SQLITE_OK:\n      sqlite3_result_text(pContext, \"Index optimized\", -1, SQLITE_STATIC);\n      break;\n    case SQLITE_DONE:\n      sqlite3_result_text(pContext, \"Index already optimal\", -1, SQLITE_STATIC);\n      break;\n    default:\n      sqlite3_result_error_code(pContext, rc);\n      break;\n  }\n}\n\n/*\n** Implementation of the matchinfo() function for FTS3\n*/\nstatic void fts3MatchinfoFunc(\n  sqlite3_context *pContext,      /* SQLite function call context */\n  int nVal,                       /* Size of argument array */\n  sqlite3_value **apVal           /* Array of arguments */\n){\n  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */\n  assert( nVal==1 || nVal==2 );\n  if( SQLITE_OK==fts3FunctionArg(pContext, \"matchinfo\", apVal[0], &pCsr) ){\n    const char *zArg = 0;\n    if( nVal>1 ){\n      zArg = (const char *)sqlite3_value_text(apVal[1]);\n    }\n    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);\n  }\n}\n\n/*\n** This routine implements the xFindFunction method for the FTS3\n** virtual table.\n*/\nstatic int fts3FindFunctionMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  int nArg,                       /* Number of SQL function arguments */\n  const char *zName,              /* Name of SQL function */\n  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */\n  void **ppArg                    /* Unused */\n){\n  struct Overloaded {\n    const char *zName;\n    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n  } aOverload[] = {\n    { \"snippet\", fts3SnippetFunc },\n    { \"offsets\", fts3OffsetsFunc },\n    { \"optimize\", fts3OptimizeFunc },\n    { \"matchinfo\", fts3MatchinfoFunc },\n  };\n  int i;                          /* Iterator variable */\n\n  UNUSED_PARAMETER(pVtab);\n  UNUSED_PARAMETER(nArg);\n  UNUSED_PARAMETER(ppArg);\n\n  for(i=0; i<SizeofArray(aOverload); i++){\n    if( strcmp(zName, aOverload[i].zName)==0 ){\n      *pxFunc = aOverload[i].xFunc;\n      return 1;\n    }\n  }\n\n  /* No function of the specified name was found. Return 0. */\n  return 0;\n}\n\n/*\n** Implementation of FTS3 xRename method. Rename an fts3 table.\n*/\nstatic int fts3RenameMethod(\n  sqlite3_vtab *pVtab,            /* Virtual table handle */\n  const char *zName               /* New name of table */\n){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  sqlite3 *db = p->db;            /* Database connection */\n  int rc;                         /* Return Code */\n\n  /* As it happens, the pending terms table is always empty here. This is\n  ** because an \"ALTER TABLE RENAME TABLE\" statement inside a transaction \n  ** always opens a savepoint transaction. And the xSavepoint() method \n  ** flushes the pending terms table. But leave the (no-op) call to\n  ** PendingTermsFlush() in in case that changes.\n  */\n  assert( p->nPendingData==0 );\n  rc = sqlite3Fts3PendingTermsFlush(p);\n\n  if( p->zContentTbl==0 ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';\",\n      p->zDb, p->zName, zName\n    );\n  }\n\n  if( p->bHasDocsize ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';\",\n      p->zDb, p->zName, zName\n    );\n  }\n  if( p->bHasStat ){\n    fts3DbExec(&rc, db,\n      \"ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';\",\n      p->zDb, p->zName, zName\n    );\n  }\n  fts3DbExec(&rc, db,\n    \"ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';\",\n    p->zDb, p->zName, zName\n  );\n  fts3DbExec(&rc, db,\n    \"ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';\",\n    p->zDb, p->zName, zName\n  );\n  return rc;\n}\n\n/*\n** The xSavepoint() method.\n**\n** Flush the contents of the pending-terms table to disk.\n*/\nstatic int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  int rc = SQLITE_OK;\n  UNUSED_PARAMETER(iSavepoint);\n  assert( ((Fts3Table *)pVtab)->inTransaction );\n  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );\n  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );\n  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){\n    rc = fts3SyncMethod(pVtab);\n  }\n  return rc;\n}\n\n/*\n** The xRelease() method.\n**\n** This is a no-op.\n*/\nstatic int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );\n  UNUSED_PARAMETER(iSavepoint);\n  UNUSED_PARAMETER(pVtab);\n  assert( p->inTransaction );\n  assert( p->mxSavepoint >= iSavepoint );\n  TESTONLY( p->mxSavepoint = iSavepoint-1 );\n  return SQLITE_OK;\n}\n\n/*\n** The xRollbackTo() method.\n**\n** Discard the contents of the pending terms table.\n*/\nstatic int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){\n  Fts3Table *p = (Fts3Table*)pVtab;\n  UNUSED_PARAMETER(iSavepoint);\n  assert( p->inTransaction );\n  assert( p->mxSavepoint >= iSavepoint );\n  TESTONLY( p->mxSavepoint = iSavepoint );\n  sqlite3Fts3PendingTermsClear(p);\n  return SQLITE_OK;\n}\n\nstatic const sqlite3_module fts3Module = {\n  /* iVersion      */ 2,\n  /* xCreate       */ fts3CreateMethod,\n  /* xConnect      */ fts3ConnectMethod,\n  /* xBestIndex    */ fts3BestIndexMethod,\n  /* xDisconnect   */ fts3DisconnectMethod,\n  /* xDestroy      */ fts3DestroyMethod,\n  /* xOpen         */ fts3OpenMethod,\n  /* xClose        */ fts3CloseMethod,\n  /* xFilter       */ fts3FilterMethod,\n  /* xNext         */ fts3NextMethod,\n  /* xEof          */ fts3EofMethod,\n  /* xColumn       */ fts3ColumnMethod,\n  /* xRowid        */ fts3RowidMethod,\n  /* xUpdate       */ fts3UpdateMethod,\n  /* xBegin        */ fts3BeginMethod,\n  /* xSync         */ fts3SyncMethod,\n  /* xCommit       */ fts3CommitMethod,\n  /* xRollback     */ fts3RollbackMethod,\n  /* xFindFunction */ fts3FindFunctionMethod,\n  /* xRename */       fts3RenameMethod,\n  /* xSavepoint    */ fts3SavepointMethod,\n  /* xRelease      */ fts3ReleaseMethod,\n  /* xRollbackTo   */ fts3RollbackToMethod,\n};\n\n/*\n** This function is registered as the module destructor (called when an\n** FTS3 enabled database connection is closed). It frees the memory\n** allocated for the tokenizer hash table.\n*/\nstatic void hashDestroy(void *p){\n  Fts3Hash *pHash = (Fts3Hash *)p;\n  sqlite3Fts3HashClear(pHash);\n  sqlite3_free(pHash);\n}\n\n/*\n** The fts3 built-in tokenizers - \"simple\", \"porter\" and \"icu\"- are \n** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c\n** respectively. The following three forward declarations are for functions\n** declared in these files used to retrieve the respective implementations.\n**\n** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed\n** to by the argument to point to the \"simple\" tokenizer implementation.\n** And so on.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);\nSQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\nSQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);\n#endif\n#ifdef SQLITE_ENABLE_ICU\nSQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n#endif\n\n/*\n** Initialise the fts3 extension. If this extension is built as part\n** of the sqlite library, then this function is called directly by\n** SQLite. If fts3 is built as a dynamically loadable extension, this\n** function is called by the sqlite3_extension_init() entry point.\n*/\nSQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){\n  int rc = SQLITE_OK;\n  Fts3Hash *pHash = 0;\n  const sqlite3_tokenizer_module *pSimple = 0;\n  const sqlite3_tokenizer_module *pPorter = 0;\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\n  const sqlite3_tokenizer_module *pUnicode = 0;\n#endif\n\n#ifdef SQLITE_ENABLE_ICU\n  const sqlite3_tokenizer_module *pIcu = 0;\n  sqlite3Fts3IcuTokenizerModule(&pIcu);\n#endif\n\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\n  sqlite3Fts3UnicodeTokenizer(&pUnicode);\n#endif\n\n#ifdef SQLITE_TEST\n  rc = sqlite3Fts3InitTerm(db);\n  if( rc!=SQLITE_OK ) return rc;\n#endif\n\n  rc = sqlite3Fts3InitAux(db);\n  if( rc!=SQLITE_OK ) return rc;\n\n  sqlite3Fts3SimpleTokenizerModule(&pSimple);\n  sqlite3Fts3PorterTokenizerModule(&pPorter);\n\n  /* Allocate and initialise the hash-table used to store tokenizers. */\n  pHash = sqlite3_malloc(sizeof(Fts3Hash));\n  if( !pHash ){\n    rc = SQLITE_NOMEM;\n  }else{\n    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);\n  }\n\n  /* Load the built-in tokenizers into the hash table */\n  if( rc==SQLITE_OK ){\n    if( sqlite3Fts3HashInsert(pHash, \"simple\", 7, (void *)pSimple)\n     || sqlite3Fts3HashInsert(pHash, \"porter\", 7, (void *)pPorter) \n\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\n     || sqlite3Fts3HashInsert(pHash, \"unicode61\", 10, (void *)pUnicode) \n#endif\n#ifdef SQLITE_ENABLE_ICU\n     || (pIcu && sqlite3Fts3HashInsert(pHash, \"icu\", 4, (void *)pIcu))\n#endif\n    ){\n      rc = SQLITE_NOMEM;\n    }\n  }\n\n#ifdef SQLITE_TEST\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3ExprInitTestInterface(db);\n  }\n#endif\n\n  /* Create the virtual table wrapper around the hash-table and overload \n  ** the two scalar functions. If this is successful, register the\n  ** module with sqlite.\n  */\n  if( SQLITE_OK==rc \n   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, \"fts3_tokenizer\"))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"snippet\", -1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"offsets\", 1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"matchinfo\", 1))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"matchinfo\", 2))\n   && SQLITE_OK==(rc = sqlite3_overload_function(db, \"optimize\", 1))\n  ){\n    rc = sqlite3_create_module_v2(\n        db, \"fts3\", &fts3Module, (void *)pHash, hashDestroy\n    );\n    if( rc==SQLITE_OK ){\n      rc = sqlite3_create_module_v2(\n          db, \"fts4\", &fts3Module, (void *)pHash, 0\n      );\n    }\n    return rc;\n  }\n\n  /* An error has occurred. Delete the hash table and return the error code. */\n  assert( rc!=SQLITE_OK );\n  if( pHash ){\n    sqlite3Fts3HashClear(pHash);\n    sqlite3_free(pHash);\n  }\n  return rc;\n}\n\n/*\n** Allocate an Fts3MultiSegReader for each token in the expression headed\n** by pExpr. \n**\n** An Fts3SegReader object is a cursor that can seek or scan a range of\n** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple\n** Fts3SegReader objects internally to provide an interface to seek or scan\n** within the union of all segments of a b-tree. Hence the name.\n**\n** If the allocated Fts3MultiSegReader just seeks to a single entry in a\n** segment b-tree (if the term is not a prefix or it is a prefix for which\n** there exists prefix b-tree of the right length) then it may be traversed\n** and merged incrementally. Otherwise, it has to be merged into an in-memory \n** doclist and then traversed.\n*/\nstatic void fts3EvalAllocateReaders(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Allocate readers for this expression */\n  int *pnToken,                   /* OUT: Total number of tokens in phrase. */\n  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( pExpr && SQLITE_OK==*pRc ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      int i;\n      int nToken = pExpr->pPhrase->nToken;\n      *pnToken += nToken;\n      for(i=0; i<nToken; i++){\n        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];\n        int rc = fts3TermSegReaderCursor(pCsr, \n            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr\n        );\n        if( rc!=SQLITE_OK ){\n          *pRc = rc;\n          return;\n        }\n      }\n      assert( pExpr->pPhrase->iDoclistToken==0 );\n      pExpr->pPhrase->iDoclistToken = -1;\n    }else{\n      *pnOr += (pExpr->eType==FTSQUERY_OR);\n      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);\n      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);\n    }\n  }\n}\n\n/*\n** Arguments pList/nList contain the doclist for token iToken of phrase p.\n** It is merged into the main doclist stored in p->doclist.aAll/nAll.\n**\n** This function assumes that pList points to a buffer allocated using\n** sqlite3_malloc(). This function takes responsibility for eventually\n** freeing the buffer.\n*/\nstatic void fts3EvalPhraseMergeToken(\n  Fts3Table *pTab,                /* FTS Table pointer */\n  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */\n  int iToken,                     /* Token pList/nList corresponds to */\n  char *pList,                    /* Pointer to doclist */\n  int nList                       /* Number of bytes in pList */\n){\n  assert( iToken!=p->iDoclistToken );\n\n  if( pList==0 ){\n    sqlite3_free(p->doclist.aAll);\n    p->doclist.aAll = 0;\n    p->doclist.nAll = 0;\n  }\n\n  else if( p->iDoclistToken<0 ){\n    p->doclist.aAll = pList;\n    p->doclist.nAll = nList;\n  }\n\n  else if( p->doclist.aAll==0 ){\n    sqlite3_free(pList);\n  }\n\n  else {\n    char *pLeft;\n    char *pRight;\n    int nLeft;\n    int nRight;\n    int nDiff;\n\n    if( p->iDoclistToken<iToken ){\n      pLeft = p->doclist.aAll;\n      nLeft = p->doclist.nAll;\n      pRight = pList;\n      nRight = nList;\n      nDiff = iToken - p->iDoclistToken;\n    }else{\n      pRight = p->doclist.aAll;\n      nRight = p->doclist.nAll;\n      pLeft = pList;\n      nLeft = nList;\n      nDiff = p->iDoclistToken - iToken;\n    }\n\n    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);\n    sqlite3_free(pLeft);\n    p->doclist.aAll = pRight;\n    p->doclist.nAll = nRight;\n  }\n\n  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;\n}\n\n/*\n** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist\n** does not take deferred tokens into account.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalPhraseLoad(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Phrase *p                   /* Phrase object */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int iToken;\n  int rc = SQLITE_OK;\n\n  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){\n    Fts3PhraseToken *pToken = &p->aToken[iToken];\n    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );\n\n    if( pToken->pSegcsr ){\n      int nThis = 0;\n      char *pThis = 0;\n      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);\n      if( rc==SQLITE_OK ){\n        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);\n      }\n    }\n    assert( pToken->pSegcsr==0 );\n  }\n\n  return rc;\n}\n\n/*\n** This function is called on each phrase after the position lists for\n** any deferred tokens have been loaded into memory. It updates the phrases\n** current position list to include only those positions that are really\n** instances of the phrase (after considering deferred tokens). If this\n** means that the phrase does not appear in the current row, doclist.pList\n** and doclist.nList are both zeroed.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){\n  int iToken;                     /* Used to iterate through phrase tokens */\n  char *aPoslist = 0;             /* Position list for deferred tokens */\n  int nPoslist = 0;               /* Number of bytes in aPoslist */\n  int iPrev = -1;                 /* Token number of previous deferred token */\n\n  assert( pPhrase->doclist.bFreeList==0 );\n\n  for(iToken=0; iToken<pPhrase->nToken; iToken++){\n    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];\n    Fts3DeferredToken *pDeferred = pToken->pDeferred;\n\n    if( pDeferred ){\n      char *pList;\n      int nList;\n      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);\n      if( rc!=SQLITE_OK ) return rc;\n\n      if( pList==0 ){\n        sqlite3_free(aPoslist);\n        pPhrase->doclist.pList = 0;\n        pPhrase->doclist.nList = 0;\n        return SQLITE_OK;\n\n      }else if( aPoslist==0 ){\n        aPoslist = pList;\n        nPoslist = nList;\n\n      }else{\n        char *aOut = pList;\n        char *p1 = aPoslist;\n        char *p2 = aOut;\n\n        assert( iPrev>=0 );\n        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);\n        sqlite3_free(aPoslist);\n        aPoslist = pList;\n        nPoslist = (int)(aOut - aPoslist);\n        if( nPoslist==0 ){\n          sqlite3_free(aPoslist);\n          pPhrase->doclist.pList = 0;\n          pPhrase->doclist.nList = 0;\n          return SQLITE_OK;\n        }\n      }\n      iPrev = iToken;\n    }\n  }\n\n  if( iPrev>=0 ){\n    int nMaxUndeferred = pPhrase->iDoclistToken;\n    if( nMaxUndeferred<0 ){\n      pPhrase->doclist.pList = aPoslist;\n      pPhrase->doclist.nList = nPoslist;\n      pPhrase->doclist.iDocid = pCsr->iPrevId;\n      pPhrase->doclist.bFreeList = 1;\n    }else{\n      int nDistance;\n      char *p1;\n      char *p2;\n      char *aOut;\n\n      if( nMaxUndeferred>iPrev ){\n        p1 = aPoslist;\n        p2 = pPhrase->doclist.pList;\n        nDistance = nMaxUndeferred - iPrev;\n      }else{\n        p1 = pPhrase->doclist.pList;\n        p2 = aPoslist;\n        nDistance = iPrev - nMaxUndeferred;\n      }\n\n      aOut = (char *)sqlite3_malloc(nPoslist+8);\n      if( !aOut ){\n        sqlite3_free(aPoslist);\n        return SQLITE_NOMEM;\n      }\n      \n      pPhrase->doclist.pList = aOut;\n      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){\n        pPhrase->doclist.bFreeList = 1;\n        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);\n      }else{\n        sqlite3_free(aOut);\n        pPhrase->doclist.pList = 0;\n        pPhrase->doclist.nList = 0;\n      }\n      sqlite3_free(aPoslist);\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** This function is called for each Fts3Phrase in a full-text query \n** expression to initialize the mechanism for returning rows. Once this\n** function has been called successfully on an Fts3Phrase, it may be\n** used with fts3EvalPhraseNext() to iterate through the matching docids.\n**\n** If parameter bOptOk is true, then the phrase may (or may not) use the\n** incremental loading strategy. Otherwise, the entire doclist is loaded into\n** memory within this call.\n**\n** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.\n*/\nstatic int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){\n  int rc;                         /* Error code */\n  Fts3PhraseToken *pFirst = &p->aToken[0];\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n\n  if( pCsr->bDesc==pTab->bDescIdx \n   && bOptOk==1 \n   && p->nToken==1 \n   && pFirst->pSegcsr \n   && pFirst->pSegcsr->bLookup \n   && pFirst->bFirst==0\n  ){\n    /* Use the incremental approach. */\n    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);\n    rc = sqlite3Fts3MsrIncrStart(\n        pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);\n    p->bIncr = 1;\n\n  }else{\n    /* Load the full doclist for the phrase into memory. */\n    rc = fts3EvalPhraseLoad(pCsr, p);\n    p->bIncr = 0;\n  }\n\n  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );\n  return rc;\n}\n\n/*\n** This function is used to iterate backwards (from the end to start) \n** through doclists. It is used by this module to iterate through phrase\n** doclists in reverse and by the fts3_write.c module to iterate through\n** pending-terms lists when writing to databases with \"order=desc\".\n**\n** The doclist may be sorted in ascending (parameter bDescIdx==0) or \n** descending (parameter bDescIdx==1) order of docid. Regardless, this\n** function iterates from the end of the doclist to the beginning.\n*/\nSQLITE_PRIVATE void sqlite3Fts3DoclistPrev(\n  int bDescIdx,                   /* True if the doclist is desc */\n  char *aDoclist,                 /* Pointer to entire doclist */\n  int nDoclist,                   /* Length of aDoclist in bytes */\n  char **ppIter,                  /* IN/OUT: Iterator pointer */\n  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */\n  int *pnList,                    /* OUT: List length pointer */\n  u8 *pbEof                       /* OUT: End-of-file flag */\n){\n  char *p = *ppIter;\n\n  assert( nDoclist>0 );\n  assert( *pbEof==0 );\n  assert( p || *piDocid==0 );\n  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );\n\n  if( p==0 ){\n    sqlite3_int64 iDocid = 0;\n    char *pNext = 0;\n    char *pDocid = aDoclist;\n    char *pEnd = &aDoclist[nDoclist];\n    int iMul = 1;\n\n    while( pDocid<pEnd ){\n      sqlite3_int64 iDelta;\n      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);\n      iDocid += (iMul * iDelta);\n      pNext = pDocid;\n      fts3PoslistCopy(0, &pDocid);\n      while( pDocid<pEnd && *pDocid==0 ) pDocid++;\n      iMul = (bDescIdx ? -1 : 1);\n    }\n\n    *pnList = (int)(pEnd - pNext);\n    *ppIter = pNext;\n    *piDocid = iDocid;\n  }else{\n    int iMul = (bDescIdx ? -1 : 1);\n    sqlite3_int64 iDelta;\n    fts3GetReverseVarint(&p, aDoclist, &iDelta);\n    *piDocid -= (iMul * iDelta);\n\n    if( p==aDoclist ){\n      *pbEof = 1;\n    }else{\n      char *pSave = p;\n      fts3ReversePoslist(aDoclist, &p);\n      *pnList = (int)(pSave - p);\n    }\n    *ppIter = p;\n  }\n}\n\n/*\n** Iterate forwards through a doclist.\n*/\nSQLITE_PRIVATE void sqlite3Fts3DoclistNext(\n  int bDescIdx,                   /* True if the doclist is desc */\n  char *aDoclist,                 /* Pointer to entire doclist */\n  int nDoclist,                   /* Length of aDoclist in bytes */\n  char **ppIter,                  /* IN/OUT: Iterator pointer */\n  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */\n  u8 *pbEof                       /* OUT: End-of-file flag */\n){\n  char *p = *ppIter;\n\n  assert( nDoclist>0 );\n  assert( *pbEof==0 );\n  assert( p || *piDocid==0 );\n  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );\n\n  if( p==0 ){\n    p = aDoclist;\n    p += sqlite3Fts3GetVarint(p, piDocid);\n  }else{\n    fts3PoslistCopy(0, &p);\n    if( p>=&aDoclist[nDoclist] ){\n      *pbEof = 1;\n    }else{\n      sqlite3_int64 iVar;\n      p += sqlite3Fts3GetVarint(p, &iVar);\n      *piDocid += ((bDescIdx ? -1 : 1) * iVar);\n    }\n  }\n\n  *ppIter = p;\n}\n\n/*\n** Attempt to move the phrase iterator to point to the next matching docid. \n** If an error occurs, return an SQLite error code. Otherwise, return \n** SQLITE_OK.\n**\n** If there is no \"next\" entry and no error occurs, then *pbEof is set to\n** 1 before returning. Otherwise, if no error occurs and the iterator is\n** successfully advanced, *pbEof is set to 0.\n*/\nstatic int fts3EvalPhraseNext(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Phrase *p,                  /* Phrase object to advance to next docid */\n  u8 *pbEof                       /* OUT: Set to 1 if EOF */\n){\n  int rc = SQLITE_OK;\n  Fts3Doclist *pDL = &p->doclist;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n\n  if( p->bIncr ){\n    assert( p->nToken==1 );\n    assert( pDL->pNextDocid==0 );\n    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, \n        &pDL->iDocid, &pDL->pList, &pDL->nList\n    );\n    if( rc==SQLITE_OK && !pDL->pList ){\n      *pbEof = 1;\n    }\n  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){\n    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, \n        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof\n    );\n    pDL->pList = pDL->pNextDocid;\n  }else{\n    char *pIter;                            /* Used to iterate through aAll */\n    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */\n    if( pDL->pNextDocid ){\n      pIter = pDL->pNextDocid;\n    }else{\n      pIter = pDL->aAll;\n    }\n\n    if( pIter>=pEnd ){\n      /* We have already reached the end of this doclist. EOF. */\n      *pbEof = 1;\n    }else{\n      sqlite3_int64 iDelta;\n      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);\n      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){\n        pDL->iDocid += iDelta;\n      }else{\n        pDL->iDocid -= iDelta;\n      }\n      pDL->pList = pIter;\n      fts3PoslistCopy(0, &pIter);\n      pDL->nList = (int)(pIter - pDL->pList);\n\n      /* pIter now points just past the 0x00 that terminates the position-\n      ** list for document pDL->iDocid. However, if this position-list was\n      ** edited in place by fts3EvalNearTrim(), then pIter may not actually\n      ** point to the start of the next docid value. The following line deals\n      ** with this case by advancing pIter past the zero-padding added by\n      ** fts3EvalNearTrim().  */\n      while( pIter<pEnd && *pIter==0 ) pIter++;\n\n      pDL->pNextDocid = pIter;\n      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );\n      *pbEof = 0;\n    }\n  }\n\n  return rc;\n}\n\n/*\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, fts3EvalPhraseStart() is called on all phrases within the\n** expression. Also the Fts3Expr.bDeferred variable is set to true for any\n** expressions for which all descendent tokens are deferred.\n**\n** If parameter bOptOk is zero, then it is guaranteed that the\n** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for\n** each phrase in the expression (subject to deferred token processing).\n** Or, if bOptOk is non-zero, then one or more tokens within the expression\n** may be loaded incrementally, meaning doclist.aAll/nAll is not available.\n**\n** If an error occurs within this function, *pRc is set to an SQLite error\n** code before returning.\n*/\nstatic void fts3EvalStartReaders(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pExpr,                /* Expression to initialize phrases in */\n  int bOptOk,                     /* True to enable incremental loading */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( pExpr && SQLITE_OK==*pRc ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      int i;\n      int nToken = pExpr->pPhrase->nToken;\n      for(i=0; i<nToken; i++){\n        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;\n      }\n      pExpr->bDeferred = (i==nToken);\n      *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);\n    }else{\n      fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);\n      fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);\n      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);\n    }\n  }\n}\n\n/*\n** An array of the following structures is assembled as part of the process\n** of selecting tokens to defer before the query starts executing (as part\n** of the xFilter() method). There is one element in the array for each\n** token in the FTS expression.\n**\n** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong\n** to phrases that are connected only by AND and NEAR operators (not OR or\n** NOT). When determining tokens to defer, each AND/NEAR cluster is considered\n** separately. The root of a tokens AND/NEAR cluster is stored in \n** Fts3TokenAndCost.pRoot.\n*/\ntypedef struct Fts3TokenAndCost Fts3TokenAndCost;\nstruct Fts3TokenAndCost {\n  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */\n  int iToken;                     /* Position of token in phrase */\n  Fts3PhraseToken *pToken;        /* The token itself */\n  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */\n  int nOvfl;                      /* Number of overflow pages to load doclist */\n  int iCol;                       /* The column the token must match */\n};\n\n/*\n** This function is used to populate an allocated Fts3TokenAndCost array.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, if an error occurs during execution, *pRc is set to an\n** SQLite error code.\n*/\nstatic void fts3EvalTokenCosts(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */\n  Fts3Expr *pExpr,                /* Expression to consider */\n  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */\n  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( *pRc==SQLITE_OK ){\n    if( pExpr->eType==FTSQUERY_PHRASE ){\n      Fts3Phrase *pPhrase = pExpr->pPhrase;\n      int i;\n      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){\n        Fts3TokenAndCost *pTC = (*ppTC)++;\n        pTC->pPhrase = pPhrase;\n        pTC->iToken = i;\n        pTC->pRoot = pRoot;\n        pTC->pToken = &pPhrase->aToken[i];\n        pTC->iCol = pPhrase->iColumn;\n        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);\n      }\n    }else if( pExpr->eType!=FTSQUERY_NOT ){\n      assert( pExpr->eType==FTSQUERY_OR\n           || pExpr->eType==FTSQUERY_AND\n           || pExpr->eType==FTSQUERY_NEAR\n      );\n      assert( pExpr->pLeft && pExpr->pRight );\n      if( pExpr->eType==FTSQUERY_OR ){\n        pRoot = pExpr->pLeft;\n        **ppOr = pRoot;\n        (*ppOr)++;\n      }\n      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);\n      if( pExpr->eType==FTSQUERY_OR ){\n        pRoot = pExpr->pRight;\n        **ppOr = pRoot;\n        (*ppOr)++;\n      }\n      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);\n    }\n  }\n}\n\n/*\n** Determine the average document (row) size in pages. If successful,\n** write this value to *pnPage and return SQLITE_OK. Otherwise, return\n** an SQLite error code.\n**\n** The average document size in pages is calculated by first calculating \n** determining the average size in bytes, B. If B is less than the amount\n** of data that will fit on a single leaf page of an intkey table in\n** this database, then the average docsize is 1. Otherwise, it is 1 plus\n** the number of overflow pages consumed by a record B bytes in size.\n*/\nstatic int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){\n  if( pCsr->nRowAvg==0 ){\n    /* The average document size, which is required to calculate the cost\n    ** of each doclist, has not yet been determined. Read the required \n    ** data from the %_stat table to calculate it.\n    **\n    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 \n    ** varints, where nCol is the number of columns in the FTS3 table.\n    ** The first varint is the number of documents currently stored in\n    ** the table. The following nCol varints contain the total amount of\n    ** data stored in all rows of each column of the table, from left\n    ** to right.\n    */\n    int rc;\n    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;\n    sqlite3_stmt *pStmt;\n    sqlite3_int64 nDoc = 0;\n    sqlite3_int64 nByte = 0;\n    const char *pEnd;\n    const char *a;\n\n    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);\n    if( rc!=SQLITE_OK ) return rc;\n    a = sqlite3_column_blob(pStmt, 0);\n    assert( a );\n\n    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];\n    a += sqlite3Fts3GetVarint(a, &nDoc);\n    while( a<pEnd ){\n      a += sqlite3Fts3GetVarint(a, &nByte);\n    }\n    if( nDoc==0 || nByte==0 ){\n      sqlite3_reset(pStmt);\n      return FTS_CORRUPT_VTAB;\n    }\n\n    pCsr->nDoc = nDoc;\n    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);\n    assert( pCsr->nRowAvg>0 ); \n    rc = sqlite3_reset(pStmt);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  *pnPage = pCsr->nRowAvg;\n  return SQLITE_OK;\n}\n\n/*\n** This function is called to select the tokens (if any) that will be \n** deferred. The array aTC[] has already been populated when this is\n** called.\n**\n** This function is called once for each AND/NEAR cluster in the \n** expression. Each invocation determines which tokens to defer within\n** the cluster with root node pRoot. See comments above the definition\n** of struct Fts3TokenAndCost for more details.\n**\n** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()\n** called on each token to defer. Otherwise, an SQLite error code is\n** returned.\n*/\nstatic int fts3EvalSelectDeferred(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pRoot,                /* Consider tokens with this root node */\n  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */\n  int nTC                         /* Number of entries in aTC[] */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int nDocSize = 0;               /* Number of pages per doc loaded */\n  int rc = SQLITE_OK;             /* Return code */\n  int ii;                         /* Iterator variable for various purposes */\n  int nOvfl = 0;                  /* Total overflow pages used by doclists */\n  int nToken = 0;                 /* Total number of tokens in cluster */\n\n  int nMinEst = 0;                /* The minimum count for any phrase so far. */\n  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */\n\n  /* Tokens are never deferred for FTS tables created using the content=xxx\n  ** option. The reason being that it is not guaranteed that the content\n  ** table actually contains the same data as the index. To prevent this from\n  ** causing any problems, the deferred token optimization is completely\n  ** disabled for content=xxx tables. */\n  if( pTab->zContentTbl ){\n    return SQLITE_OK;\n  }\n\n  /* Count the tokens in this AND/NEAR cluster. If none of the doclists\n  ** associated with the tokens spill onto overflow pages, or if there is\n  ** only 1 token, exit early. No tokens to defer in this case. */\n  for(ii=0; ii<nTC; ii++){\n    if( aTC[ii].pRoot==pRoot ){\n      nOvfl += aTC[ii].nOvfl;\n      nToken++;\n    }\n  }\n  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;\n\n  /* Obtain the average docsize (in pages). */\n  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);\n  assert( rc!=SQLITE_OK || nDocSize>0 );\n\n\n  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order \n  ** of the number of overflow pages that will be loaded by the pager layer \n  ** to retrieve the entire doclist for the token from the full-text index.\n  ** Load the doclists for tokens that are either:\n  **\n  **   a. The cheapest token in the entire query (i.e. the one visited by the\n  **      first iteration of this loop), or\n  **\n  **   b. Part of a multi-token phrase.\n  **\n  ** After each token doclist is loaded, merge it with the others from the\n  ** same phrase and count the number of documents that the merged doclist\n  ** contains. Set variable \"nMinEst\" to the smallest number of documents in \n  ** any phrase doclist for which 1 or more token doclists have been loaded.\n  ** Let nOther be the number of other phrases for which it is certain that\n  ** one or more tokens will not be deferred.\n  **\n  ** Then, for each token, defer it if loading the doclist would result in\n  ** loading N or more overflow pages into memory, where N is computed as:\n  **\n  **    (nMinEst + 4^nOther - 1) / (4^nOther)\n  */\n  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){\n    int iTC;                      /* Used to iterate through aTC[] array. */\n    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */\n\n    /* Set pTC to point to the cheapest remaining token. */\n    for(iTC=0; iTC<nTC; iTC++){\n      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot \n       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) \n      ){\n        pTC = &aTC[iTC];\n      }\n    }\n    assert( pTC );\n\n    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){\n      /* The number of overflow pages to load for this (and therefore all\n      ** subsequent) tokens is greater than the estimated number of pages \n      ** that will be loaded if all subsequent tokens are deferred.\n      */\n      Fts3PhraseToken *pToken = pTC->pToken;\n      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);\n      fts3SegReaderCursorFree(pToken->pSegcsr);\n      pToken->pSegcsr = 0;\n    }else{\n      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the\n      ** for-loop. Except, limit the value to 2^24 to prevent it from \n      ** overflowing the 32-bit integer it is stored in. */\n      if( ii<12 ) nLoad4 = nLoad4*4;\n\n      if( ii==0 || pTC->pPhrase->nToken>1 ){\n        /* Either this is the cheapest token in the entire query, or it is\n        ** part of a multi-token phrase. Either way, the entire doclist will\n        ** (eventually) be loaded into memory. It may as well be now. */\n        Fts3PhraseToken *pToken = pTC->pToken;\n        int nList = 0;\n        char *pList = 0;\n        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);\n        assert( rc==SQLITE_OK || pList==0 );\n        if( rc==SQLITE_OK ){\n          int nCount;\n          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);\n          nCount = fts3DoclistCountDocids(\n              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll\n          );\n          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;\n        }\n      }\n    }\n    pTC->pToken = 0;\n  }\n\n  return rc;\n}\n\n/*\n** This function is called from within the xFilter method. It initializes\n** the full-text query currently stored in pCsr->pExpr. To iterate through\n** the results of a query, the caller does:\n**\n**    fts3EvalStart(pCsr);\n**    while( 1 ){\n**      fts3EvalNext(pCsr);\n**      if( pCsr->bEof ) break;\n**      ... return row pCsr->iPrevId to the caller ...\n**    }\n*/\nstatic int fts3EvalStart(Fts3Cursor *pCsr){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int nToken = 0;\n  int nOr = 0;\n\n  /* Allocate a MultiSegReader for each token in the expression. */\n  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);\n\n  /* Determine which, if any, tokens in the expression should be deferred. */\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){\n    Fts3TokenAndCost *aTC;\n    Fts3Expr **apOr;\n    aTC = (Fts3TokenAndCost *)sqlite3_malloc(\n        sizeof(Fts3TokenAndCost) * nToken\n      + sizeof(Fts3Expr *) * nOr * 2\n    );\n    apOr = (Fts3Expr **)&aTC[nToken];\n\n    if( !aTC ){\n      rc = SQLITE_NOMEM;\n    }else{\n      int ii;\n      Fts3TokenAndCost *pTC = aTC;\n      Fts3Expr **ppOr = apOr;\n\n      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);\n      nToken = (int)(pTC-aTC);\n      nOr = (int)(ppOr-apOr);\n\n      if( rc==SQLITE_OK ){\n        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);\n        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){\n          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);\n        }\n      }\n\n      sqlite3_free(aTC);\n    }\n  }\n#endif\n\n  fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);\n  return rc;\n}\n\n/*\n** Invalidate the current position list for phrase pPhrase.\n*/\nstatic void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){\n  if( pPhrase->doclist.bFreeList ){\n    sqlite3_free(pPhrase->doclist.pList);\n  }\n  pPhrase->doclist.pList = 0;\n  pPhrase->doclist.nList = 0;\n  pPhrase->doclist.bFreeList = 0;\n}\n\n/*\n** This function is called to edit the position list associated with\n** the phrase object passed as the fifth argument according to a NEAR\n** condition. For example:\n**\n**     abc NEAR/5 \"def ghi\"\n**\n** Parameter nNear is passed the NEAR distance of the expression (5 in\n** the example above). When this function is called, *paPoslist points to\n** the position list, and *pnToken is the number of phrase tokens in, the\n** phrase on the other side of the NEAR operator to pPhrase. For example,\n** if pPhrase refers to the \"def ghi\" phrase, then *paPoslist points to\n** the position list associated with phrase \"abc\".\n**\n** All positions in the pPhrase position list that are not sufficiently\n** close to a position in the *paPoslist position list are removed. If this\n** leaves 0 positions, zero is returned. Otherwise, non-zero.\n**\n** Before returning, *paPoslist is set to point to the position lsit \n** associated with pPhrase. And *pnToken is set to the number of tokens in\n** pPhrase.\n*/\nstatic int fts3EvalNearTrim(\n  int nNear,                      /* NEAR distance. As in \"NEAR/nNear\". */\n  char *aTmp,                     /* Temporary space to use */\n  char **paPoslist,               /* IN/OUT: Position list */\n  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */\n  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */\n){\n  int nParam1 = nNear + pPhrase->nToken;\n  int nParam2 = nNear + *pnToken;\n  int nNew;\n  char *p2; \n  char *pOut; \n  int res;\n\n  assert( pPhrase->doclist.pList );\n\n  p2 = pOut = pPhrase->doclist.pList;\n  res = fts3PoslistNearMerge(\n    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2\n  );\n  if( res ){\n    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;\n    assert( pPhrase->doclist.pList[nNew]=='\\0' );\n    assert( nNew<=pPhrase->doclist.nList && nNew>0 );\n    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);\n    pPhrase->doclist.nList = nNew;\n    *paPoslist = pPhrase->doclist.pList;\n    *pnToken = pPhrase->nToken;\n  }\n\n  return res;\n}\n\n/*\n** This function is a no-op if *pRc is other than SQLITE_OK when it is called.\n** Otherwise, it advances the expression passed as the second argument to\n** point to the next matching row in the database. Expressions iterate through\n** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,\n** or descending if it is non-zero.\n**\n** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if\n** successful, the following variables in pExpr are set:\n**\n**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)\n**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)\n**\n** If the expression is of type FTSQUERY_PHRASE, and the expression is not\n** at EOF, then the following variables are populated with the position list\n** for the phrase for the visited row:\n**\n**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)\n**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)\n**\n** It says above that this function advances the expression to the next\n** matching row. This is usually true, but there are the following exceptions:\n**\n**   1. Deferred tokens are not taken into account. If a phrase consists\n**      entirely of deferred tokens, it is assumed to match every row in\n**      the db. In this case the position-list is not populated at all. \n**\n**      Or, if a phrase contains one or more deferred tokens and one or\n**      more non-deferred tokens, then the expression is advanced to the \n**      next possible match, considering only non-deferred tokens. In other\n**      words, if the phrase is \"A B C\", and \"B\" is deferred, the expression\n**      is advanced to the next row that contains an instance of \"A * C\", \n**      where \"*\" may match any single token. The position list in this case\n**      is populated as for \"A * C\" before returning.\n**\n**   2. NEAR is treated as AND. If the expression is \"x NEAR y\", it is \n**      advanced to point to the next row that matches \"x AND y\".\n** \n** See fts3EvalTestDeferredAndNear() for details on testing if a row is\n** really a match, taking into account deferred tokens and NEAR operators.\n*/\nstatic void fts3EvalNextRow(\n  Fts3Cursor *pCsr,               /* FTS Cursor handle */\n  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  if( *pRc==SQLITE_OK ){\n    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */\n    assert( pExpr->bEof==0 );\n    pExpr->bStart = 1;\n\n    switch( pExpr->eType ){\n      case FTSQUERY_NEAR:\n      case FTSQUERY_AND: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n        assert( !pLeft->bDeferred || !pRight->bDeferred );\n\n        if( pLeft->bDeferred ){\n          /* LHS is entirely deferred. So we assume it matches every row.\n          ** Advance the RHS iterator to find the next row visited. */\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          pExpr->iDocid = pRight->iDocid;\n          pExpr->bEof = pRight->bEof;\n        }else if( pRight->bDeferred ){\n          /* RHS is entirely deferred. So we assume it matches every row.\n          ** Advance the LHS iterator to find the next row visited. */\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          pExpr->iDocid = pLeft->iDocid;\n          pExpr->bEof = pLeft->bEof;\n        }else{\n          /* Neither the RHS or LHS are deferred. */\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){\n            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n            if( iDiff==0 ) break;\n            if( iDiff<0 ){\n              fts3EvalNextRow(pCsr, pLeft, pRc);\n            }else{\n              fts3EvalNextRow(pCsr, pRight, pRc);\n            }\n          }\n          pExpr->iDocid = pLeft->iDocid;\n          pExpr->bEof = (pLeft->bEof || pRight->bEof);\n        }\n        break;\n      }\n  \n      case FTSQUERY_OR: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n\n        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );\n        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );\n\n        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){\n          fts3EvalNextRow(pCsr, pRight, pRc);\n        }else{\n          fts3EvalNextRow(pCsr, pLeft, pRc);\n          fts3EvalNextRow(pCsr, pRight, pRc);\n        }\n\n        pExpr->bEof = (pLeft->bEof && pRight->bEof);\n        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);\n        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){\n          pExpr->iDocid = pLeft->iDocid;\n        }else{\n          pExpr->iDocid = pRight->iDocid;\n        }\n\n        break;\n      }\n\n      case FTSQUERY_NOT: {\n        Fts3Expr *pLeft = pExpr->pLeft;\n        Fts3Expr *pRight = pExpr->pRight;\n\n        if( pRight->bStart==0 ){\n          fts3EvalNextRow(pCsr, pRight, pRc);\n          assert( *pRc!=SQLITE_OK || pRight->bStart );\n        }\n\n        fts3EvalNextRow(pCsr, pLeft, pRc);\n        if( pLeft->bEof==0 ){\n          while( !*pRc \n              && !pRight->bEof \n              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 \n          ){\n            fts3EvalNextRow(pCsr, pRight, pRc);\n          }\n        }\n        pExpr->iDocid = pLeft->iDocid;\n        pExpr->bEof = pLeft->bEof;\n        break;\n      }\n\n      default: {\n        Fts3Phrase *pPhrase = pExpr->pPhrase;\n        fts3EvalInvalidatePoslist(pPhrase);\n        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);\n        pExpr->iDocid = pPhrase->doclist.iDocid;\n        break;\n      }\n    }\n  }\n}\n\n/*\n** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR\n** cluster, then this function returns 1 immediately.\n**\n** Otherwise, it checks if the current row really does match the NEAR \n** expression, using the data currently stored in the position lists \n** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. \n**\n** If the current row is a match, the position list associated with each\n** phrase in the NEAR expression is edited in place to contain only those\n** phrase instances sufficiently close to their peers to satisfy all NEAR\n** constraints. In this case it returns 1. If the NEAR expression does not \n** match the current row, 0 is returned. The position lists may or may not\n** be edited if 0 is returned.\n*/\nstatic int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){\n  int res = 1;\n\n  /* The following block runs if pExpr is the root of a NEAR query.\n  ** For example, the query:\n  **\n  **         \"w\" NEAR \"x\" NEAR \"y\" NEAR \"z\"\n  **\n  ** which is represented in tree form as:\n  **\n  **                               |\n  **                          +--NEAR--+      <-- root of NEAR query\n  **                          |        |\n  **                     +--NEAR--+   \"z\"\n  **                     |        |\n  **                +--NEAR--+   \"y\"\n  **                |        |\n  **               \"w\"      \"x\"\n  **\n  ** The right-hand child of a NEAR node is always a phrase. The \n  ** left-hand child may be either a phrase or a NEAR node. There are\n  ** no exceptions to this - it's the way the parser in fts3_expr.c works.\n  */\n  if( *pRc==SQLITE_OK \n   && pExpr->eType==FTSQUERY_NEAR \n   && pExpr->bEof==0\n   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)\n  ){\n    Fts3Expr *p; \n    int nTmp = 0;                 /* Bytes of temp space */\n    char *aTmp;                   /* Temp space for PoslistNearMerge() */\n\n    /* Allocate temporary working space. */\n    for(p=pExpr; p->pLeft; p=p->pLeft){\n      nTmp += p->pRight->pPhrase->doclist.nList;\n    }\n    nTmp += p->pPhrase->doclist.nList;\n    aTmp = sqlite3_malloc(nTmp*2);\n    if( !aTmp ){\n      *pRc = SQLITE_NOMEM;\n      res = 0;\n    }else{\n      char *aPoslist = p->pPhrase->doclist.pList;\n      int nToken = p->pPhrase->nToken;\n\n      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){\n        Fts3Phrase *pPhrase = p->pRight->pPhrase;\n        int nNear = p->nNear;\n        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);\n      }\n  \n      aPoslist = pExpr->pRight->pPhrase->doclist.pList;\n      nToken = pExpr->pRight->pPhrase->nToken;\n      for(p=pExpr->pLeft; p && res; p=p->pLeft){\n        int nNear;\n        Fts3Phrase *pPhrase;\n        assert( p->pParent && p->pParent->pLeft==p );\n        nNear = p->pParent->nNear;\n        pPhrase = (\n            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase\n        );\n        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);\n      }\n    }\n\n    sqlite3_free(aTmp);\n  }\n\n  return res;\n}\n\n/*\n** This function is a helper function for fts3EvalTestDeferredAndNear().\n** Assuming no error occurs or has occurred, It returns non-zero if the\n** expression passed as the second argument matches the row that pCsr \n** currently points to, or zero if it does not.\n**\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** If an error occurs during execution of this function, *pRc is set to \n** the appropriate SQLite error code. In this case the returned value is \n** undefined.\n*/\nstatic int fts3EvalTestExpr(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  int bHit = 1;                   /* Return value */\n  if( *pRc==SQLITE_OK ){\n    switch( pExpr->eType ){\n      case FTSQUERY_NEAR:\n      case FTSQUERY_AND:\n        bHit = (\n            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)\n         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)\n         && fts3EvalNearTest(pExpr, pRc)\n        );\n\n        /* If the NEAR expression does not match any rows, zero the doclist for \n        ** all phrases involved in the NEAR. This is because the snippet(),\n        ** offsets() and matchinfo() functions are not supposed to recognize \n        ** any instances of phrases that are part of unmatched NEAR queries. \n        ** For example if this expression:\n        **\n        **    ... MATCH 'a OR (b NEAR c)'\n        **\n        ** is matched against a row containing:\n        **\n        **        'a b d e'\n        **\n        ** then any snippet() should ony highlight the \"a\" term, not the \"b\"\n        ** (as \"b\" is part of a non-matching NEAR clause).\n        */\n        if( bHit==0 \n         && pExpr->eType==FTSQUERY_NEAR \n         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)\n        ){\n          Fts3Expr *p;\n          for(p=pExpr; p->pPhrase==0; p=p->pLeft){\n            if( p->pRight->iDocid==pCsr->iPrevId ){\n              fts3EvalInvalidatePoslist(p->pRight->pPhrase);\n            }\n          }\n          if( p->iDocid==pCsr->iPrevId ){\n            fts3EvalInvalidatePoslist(p->pPhrase);\n          }\n        }\n\n        break;\n\n      case FTSQUERY_OR: {\n        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);\n        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);\n        bHit = bHit1 || bHit2;\n        break;\n      }\n\n      case FTSQUERY_NOT:\n        bHit = (\n            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)\n         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)\n        );\n        break;\n\n      default: {\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n        if( pCsr->pDeferred \n         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)\n        ){\n          Fts3Phrase *pPhrase = pExpr->pPhrase;\n          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );\n          if( pExpr->bDeferred ){\n            fts3EvalInvalidatePoslist(pPhrase);\n          }\n          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);\n          bHit = (pPhrase->doclist.pList!=0);\n          pExpr->iDocid = pCsr->iPrevId;\n        }else\n#endif\n        {\n          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);\n        }\n        break;\n      }\n    }\n  }\n  return bHit;\n}\n\n/*\n** This function is called as the second part of each xNext operation when\n** iterating through the results of a full-text query. At this point the\n** cursor points to a row that matches the query expression, with the\n** following caveats:\n**\n**   * Up until this point, \"NEAR\" operators in the expression have been\n**     treated as \"AND\".\n**\n**   * Deferred tokens have not yet been considered.\n**\n** If *pRc is not SQLITE_OK when this function is called, it immediately\n** returns 0. Otherwise, it tests whether or not after considering NEAR\n** operators and deferred tokens the current row is still a match for the\n** expression. It returns 1 if both of the following are true:\n**\n**   1. *pRc is SQLITE_OK when this function returns, and\n**\n**   2. After scanning the current FTS table row for the deferred tokens,\n**      it is determined that the row does *not* match the query.\n**\n** Or, if no error occurs and it seems the current row does match the FTS\n** query, return 0.\n*/\nstatic int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){\n  int rc = *pRc;\n  int bMiss = 0;\n  if( rc==SQLITE_OK ){\n\n    /* If there are one or more deferred tokens, load the current row into\n    ** memory and scan it to determine the position list for each deferred\n    ** token. Then, see if this row is really a match, considering deferred\n    ** tokens and NEAR operators (neither of which were taken into account\n    ** earlier, by fts3EvalNextRow()). \n    */\n    if( pCsr->pDeferred ){\n      rc = fts3CursorSeek(0, pCsr);\n      if( rc==SQLITE_OK ){\n        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);\n      }\n    }\n    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));\n\n    /* Free the position-lists accumulated for each deferred token above. */\n    sqlite3Fts3FreeDeferredDoclists(pCsr);\n    *pRc = rc;\n  }\n  return (rc==SQLITE_OK && bMiss);\n}\n\n/*\n** Advance to the next document that matches the FTS expression in\n** Fts3Cursor.pExpr.\n*/\nstatic int fts3EvalNext(Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Expr *pExpr = pCsr->pExpr;\n  assert( pCsr->isEof==0 );\n  if( pExpr==0 ){\n    pCsr->isEof = 1;\n  }else{\n    do {\n      if( pCsr->isRequireSeek==0 ){\n        sqlite3_reset(pCsr->pStmt);\n      }\n      assert( sqlite3_data_count(pCsr->pStmt)==0 );\n      fts3EvalNextRow(pCsr, pExpr, &rc);\n      pCsr->isEof = pExpr->bEof;\n      pCsr->isRequireSeek = 1;\n      pCsr->isMatchinfoNeeded = 1;\n      pCsr->iPrevId = pExpr->iDocid;\n    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );\n  }\n  return rc;\n}\n\n/*\n** Restart interation for expression pExpr so that the next call to\n** fts3EvalNext() visits the first row. Do not allow incremental \n** loading or merging of phrase doclists for this iteration.\n**\n** If *pRc is other than SQLITE_OK when this function is called, it is\n** a no-op. If an error occurs within this function, *pRc is set to an\n** SQLite error code before returning.\n*/\nstatic void fts3EvalRestart(\n  Fts3Cursor *pCsr,\n  Fts3Expr *pExpr,\n  int *pRc\n){\n  if( pExpr && *pRc==SQLITE_OK ){\n    Fts3Phrase *pPhrase = pExpr->pPhrase;\n\n    if( pPhrase ){\n      fts3EvalInvalidatePoslist(pPhrase);\n      if( pPhrase->bIncr ){\n        assert( pPhrase->nToken==1 );\n        assert( pPhrase->aToken[0].pSegcsr );\n        sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);\n        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);\n      }\n\n      pPhrase->doclist.pNextDocid = 0;\n      pPhrase->doclist.iDocid = 0;\n    }\n\n    pExpr->iDocid = 0;\n    pExpr->bEof = 0;\n    pExpr->bStart = 0;\n\n    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);\n    fts3EvalRestart(pCsr, pExpr->pRight, pRc);\n  }\n}\n\n/*\n** After allocating the Fts3Expr.aMI[] array for each phrase in the \n** expression rooted at pExpr, the cursor iterates through all rows matched\n** by pExpr, calling this function for each row. This function increments\n** the values in Fts3Expr.aMI[] according to the position-list currently\n** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase \n** expression nodes.\n*/\nstatic void fts3EvalUpdateCounts(Fts3Expr *pExpr){\n  if( pExpr ){\n    Fts3Phrase *pPhrase = pExpr->pPhrase;\n    if( pPhrase && pPhrase->doclist.pList ){\n      int iCol = 0;\n      char *p = pPhrase->doclist.pList;\n\n      assert( *p );\n      while( 1 ){\n        u8 c = 0;\n        int iCnt = 0;\n        while( 0xFE & (*p | c) ){\n          if( (c&0x80)==0 ) iCnt++;\n          c = *p++ & 0x80;\n        }\n\n        /* aMI[iCol*3 + 1] = Number of occurrences\n        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance\n        */\n        pExpr->aMI[iCol*3 + 1] += iCnt;\n        pExpr->aMI[iCol*3 + 2] += (iCnt>0);\n        if( *p==0x00 ) break;\n        p++;\n        p += sqlite3Fts3GetVarint32(p, &iCol);\n      }\n    }\n\n    fts3EvalUpdateCounts(pExpr->pLeft);\n    fts3EvalUpdateCounts(pExpr->pRight);\n  }\n}\n\n/*\n** Expression pExpr must be of type FTSQUERY_PHRASE.\n**\n** If it is not already allocated and populated, this function allocates and\n** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part\n** of a NEAR expression, then it also allocates and populates the same array\n** for all other phrases that are part of the NEAR expression.\n**\n** SQLITE_OK is returned if the aMI[] array is successfully allocated and\n** populated. Otherwise, if an error occurs, an SQLite error code is returned.\n*/\nstatic int fts3EvalGatherStats(\n  Fts3Cursor *pCsr,               /* Cursor object */\n  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */\n){\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( pExpr->eType==FTSQUERY_PHRASE );\n  if( pExpr->aMI==0 ){\n    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n    Fts3Expr *pRoot;                /* Root of NEAR expression */\n    Fts3Expr *p;                    /* Iterator used for several purposes */\n\n    sqlite3_int64 iPrevId = pCsr->iPrevId;\n    sqlite3_int64 iDocid;\n    u8 bEof;\n\n    /* Find the root of the NEAR expression */\n    pRoot = pExpr;\n    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){\n      pRoot = pRoot->pParent;\n    }\n    iDocid = pRoot->iDocid;\n    bEof = pRoot->bEof;\n    assert( pRoot->bStart );\n\n    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */\n    for(p=pRoot; p; p=p->pLeft){\n      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);\n      assert( pE->aMI==0 );\n      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));\n      if( !pE->aMI ) return SQLITE_NOMEM;\n      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));\n    }\n\n    fts3EvalRestart(pCsr, pRoot, &rc);\n\n    while( pCsr->isEof==0 && rc==SQLITE_OK ){\n\n      do {\n        /* Ensure the %_content statement is reset. */\n        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);\n        assert( sqlite3_data_count(pCsr->pStmt)==0 );\n\n        /* Advance to the next document */\n        fts3EvalNextRow(pCsr, pRoot, &rc);\n        pCsr->isEof = pRoot->bEof;\n        pCsr->isRequireSeek = 1;\n        pCsr->isMatchinfoNeeded = 1;\n        pCsr->iPrevId = pRoot->iDocid;\n      }while( pCsr->isEof==0 \n           && pRoot->eType==FTSQUERY_NEAR \n           && fts3EvalTestDeferredAndNear(pCsr, &rc) \n      );\n\n      if( rc==SQLITE_OK && pCsr->isEof==0 ){\n        fts3EvalUpdateCounts(pRoot);\n      }\n    }\n\n    pCsr->isEof = 0;\n    pCsr->iPrevId = iPrevId;\n\n    if( bEof ){\n      pRoot->bEof = bEof;\n    }else{\n      /* Caution: pRoot may iterate through docids in ascending or descending\n      ** order. For this reason, even though it seems more defensive, the \n      ** do loop can not be written:\n      **\n      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );\n      */\n      fts3EvalRestart(pCsr, pRoot, &rc);\n      do {\n        fts3EvalNextRow(pCsr, pRoot, &rc);\n        assert( pRoot->bEof==0 );\n      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );\n      fts3EvalTestDeferredAndNear(pCsr, &rc);\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is used by the matchinfo() module to query a phrase \n** expression node for the following information:\n**\n**   1. The total number of occurrences of the phrase in each column of \n**      the FTS table (considering all rows), and\n**\n**   2. For each column, the number of rows in the table for which the\n**      column contains at least one instance of the phrase.\n**\n** If no error occurs, SQLITE_OK is returned and the values for each column\n** written into the array aiOut as follows:\n**\n**   aiOut[iCol*3 + 1] = Number of occurrences\n**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance\n**\n** Caveats:\n**\n**   * If a phrase consists entirely of deferred tokens, then all output \n**     values are set to the number of documents in the table. In other\n**     words we assume that very common tokens occur exactly once in each \n**     column of each row of the table.\n**\n**   * If a phrase contains some deferred tokens (and some non-deferred \n**     tokens), count the potential occurrence identified by considering\n**     the non-deferred tokens instead of actual phrase occurrences.\n**\n**   * If the phrase is part of a NEAR expression, then only phrase instances\n**     that meet the NEAR constraint are included in the counts.\n*/\nSQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(\n  Fts3Cursor *pCsr,               /* FTS cursor handle */\n  Fts3Expr *pExpr,                /* Phrase expression */\n  u32 *aiOut                      /* Array to write results into (see above) */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int iCol;\n\n  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){\n    assert( pCsr->nDoc>0 );\n    for(iCol=0; iCol<pTab->nColumn; iCol++){\n      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;\n      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;\n    }\n  }else{\n    rc = fts3EvalGatherStats(pCsr, pExpr);\n    if( rc==SQLITE_OK ){\n      assert( pExpr->aMI );\n      for(iCol=0; iCol<pTab->nColumn; iCol++){\n        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];\n        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The expression pExpr passed as the second argument to this function\n** must be of type FTSQUERY_PHRASE. \n**\n** The returned value is either NULL or a pointer to a buffer containing\n** a position-list indicating the occurrences of the phrase in column iCol\n** of the current row. \n**\n** More specifically, the returned buffer contains 1 varint for each \n** occurence of the phrase in the column, stored using the normal (delta+2) \n** compression and is terminated by either an 0x01 or 0x00 byte. For example,\n** if the requested column contains \"a b X c d X X\" and the position-list\n** for 'X' is requested, the buffer returned may contain:\n**\n**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00\n**\n** This function works regardless of whether or not the phrase is deferred,\n** incremental, or neither.\n*/\nSQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(\n  Fts3Cursor *pCsr,               /* FTS3 cursor object */\n  Fts3Expr *pExpr,                /* Phrase to return doclist for */\n  int iCol,                       /* Column to return position list for */\n  char **ppOut                    /* OUT: Pointer to position list */\n){\n  Fts3Phrase *pPhrase = pExpr->pPhrase;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  char *pIter;\n  int iThis;\n  sqlite3_int64 iDocid;\n\n  /* If this phrase is applies specifically to some column other than \n  ** column iCol, return a NULL pointer.  */\n  *ppOut = 0;\n  assert( iCol>=0 && iCol<pTab->nColumn );\n  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){\n    return SQLITE_OK;\n  }\n\n  iDocid = pExpr->iDocid;\n  pIter = pPhrase->doclist.pList;\n  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){\n    int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */\n    int bOr = 0;\n    u8 bEof = 0;\n    Fts3Expr *p;\n\n    /* Check if this phrase descends from an OR expression node. If not, \n    ** return NULL. Otherwise, the entry that corresponds to docid \n    ** pCsr->iPrevId may lie earlier in the doclist buffer. */\n    for(p=pExpr->pParent; p; p=p->pParent){\n      if( p->eType==FTSQUERY_OR ) bOr = 1;\n    }\n    if( bOr==0 ) return SQLITE_OK;\n\n    /* This is the descendent of an OR node. In this case we cannot use\n    ** an incremental phrase. Load the entire doclist for the phrase\n    ** into memory in this case.  */\n    if( pPhrase->bIncr ){\n      int rc = SQLITE_OK;\n      int bEofSave = pExpr->bEof;\n      fts3EvalRestart(pCsr, pExpr, &rc);\n      while( rc==SQLITE_OK && !pExpr->bEof ){\n        fts3EvalNextRow(pCsr, pExpr, &rc);\n        if( bEofSave==0 && pExpr->iDocid==iDocid ) break;\n      }\n      pIter = pPhrase->doclist.pList;\n      assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );\n      if( rc!=SQLITE_OK ) return rc;\n    }\n\n    if( pExpr->bEof ){\n      pIter = 0;\n      iDocid = 0;\n    }\n    bEof = (pPhrase->doclist.nAll==0);\n    assert( bDescDoclist==0 || bDescDoclist==1 );\n    assert( pCsr->bDesc==0 || pCsr->bDesc==1 );\n\n    if( pCsr->bDesc==bDescDoclist ){\n      int dummy;\n      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){\n        sqlite3Fts3DoclistPrev(\n            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, \n            &pIter, &iDocid, &dummy, &bEof\n        );\n      }\n    }else{\n      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){\n        sqlite3Fts3DoclistNext(\n            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, \n            &pIter, &iDocid, &bEof\n        );\n      }\n    }\n\n    if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;\n  }\n  if( pIter==0 ) return SQLITE_OK;\n\n  if( *pIter==0x01 ){\n    pIter++;\n    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);\n  }else{\n    iThis = 0;\n  }\n  while( iThis<iCol ){\n    fts3ColumnlistCopy(0, &pIter);\n    if( *pIter==0x00 ) return 0;\n    pIter++;\n    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);\n  }\n\n  *ppOut = ((iCol==iThis)?pIter:0);\n  return SQLITE_OK;\n}\n\n/*\n** Free all components of the Fts3Phrase structure that were allocated by\n** the eval module. Specifically, this means to free:\n**\n**   * the contents of pPhrase->doclist, and\n**   * any Fts3MultiSegReader objects held by phrase tokens.\n*/\nSQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){\n  if( pPhrase ){\n    int i;\n    sqlite3_free(pPhrase->doclist.aAll);\n    fts3EvalInvalidatePoslist(pPhrase);\n    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));\n    for(i=0; i<pPhrase->nToken; i++){\n      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);\n      pPhrase->aToken[i].pSegcsr = 0;\n    }\n  }\n}\n\n\n/*\n** Return SQLITE_CORRUPT_VTAB.\n*/\n#ifdef SQLITE_DEBUG\nSQLITE_PRIVATE int sqlite3Fts3Corrupt(){\n  return SQLITE_CORRUPT_VTAB;\n}\n#endif\n\n#if !SQLITE_CORE\n/*\n** Initialize API pointer table, if required.\n*/\nSQLITE_API int sqlite3_extension_init(\n  sqlite3 *db, \n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3Fts3Init(db);\n}\n#endif\n\n#endif\n\n/************** End of fts3.c ************************************************/\n/************** Begin file fts3_aux.c ****************************************/\n/*\n** 2011 Jan 27\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\ntypedef struct Fts3auxTable Fts3auxTable;\ntypedef struct Fts3auxCursor Fts3auxCursor;\n\nstruct Fts3auxTable {\n  sqlite3_vtab base;              /* Base class used by SQLite core */\n  Fts3Table *pFts3Tab;\n};\n\nstruct Fts3auxCursor {\n  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */\n  Fts3MultiSegReader csr;        /* Must be right after \"base\" */\n  Fts3SegFilter filter;\n  char *zStop;\n  int nStop;                      /* Byte-length of string zStop */\n  int isEof;                      /* True if cursor is at EOF */\n  sqlite3_int64 iRowid;           /* Current rowid */\n\n  int iCol;                       /* Current value of 'col' column */\n  int nStat;                      /* Size of aStat[] array */\n  struct Fts3auxColstats {\n    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */\n    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */\n  } *aStat;\n};\n\n/*\n** Schema of the terms table.\n*/\n#define FTS3_TERMS_SCHEMA \"CREATE TABLE x(term, col, documents, occurrences)\"\n\n/*\n** This function does all the work for both the xConnect and xCreate methods.\n** These tables have no persistent representation of their own, so xConnect\n** and xCreate are identical operations.\n*/\nstatic int fts3auxConnectMethod(\n  sqlite3 *db,                    /* Database connection */\n  void *pUnused,                  /* Unused */\n  int argc,                       /* Number of elements in argv array */\n  const char * const *argv,       /* xCreate/xConnect argument array */\n  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */\n  char **pzErr                    /* OUT: sqlite3_malloc'd error message */\n){\n  char const *zDb;                /* Name of database (e.g. \"main\") */\n  char const *zFts3;              /* Name of fts3 table */\n  int nDb;                        /* Result of strlen(zDb) */\n  int nFts3;                      /* Result of strlen(zFts3) */\n  int nByte;                      /* Bytes of space to allocate here */\n  int rc;                         /* value returned by declare_vtab() */\n  Fts3auxTable *p;                /* Virtual table object to return */\n\n  UNUSED_PARAMETER(pUnused);\n\n  /* The user should specify a single argument - the name of an fts3 table. */\n  if( argc!=4 ){\n    *pzErr = sqlite3_mprintf(\n        \"wrong number of arguments to fts4aux constructor\"\n    );\n    return SQLITE_ERROR;\n  }\n\n  zDb = argv[1]; \n  nDb = (int)strlen(zDb);\n  zFts3 = argv[3];\n  nFts3 = (int)strlen(zFts3);\n\n  rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;\n  p = (Fts3auxTable *)sqlite3_malloc(nByte);\n  if( !p ) return SQLITE_NOMEM;\n  memset(p, 0, nByte);\n\n  p->pFts3Tab = (Fts3Table *)&p[1];\n  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];\n  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];\n  p->pFts3Tab->db = db;\n  p->pFts3Tab->nIndex = 1;\n\n  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);\n  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);\n  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);\n\n  *ppVtab = (sqlite3_vtab *)p;\n  return SQLITE_OK;\n}\n\n/*\n** This function does the work for both the xDisconnect and xDestroy methods.\n** These tables have no persistent representation of their own, so xDisconnect\n** and xDestroy are identical operations.\n*/\nstatic int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){\n  Fts3auxTable *p = (Fts3auxTable *)pVtab;\n  Fts3Table *pFts3 = p->pFts3Tab;\n  int i;\n\n  /* Free any prepared statements held */\n  for(i=0; i<SizeofArray(pFts3->aStmt); i++){\n    sqlite3_finalize(pFts3->aStmt[i]);\n  }\n  sqlite3_free(pFts3->zSegmentsTbl);\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n#define FTS4AUX_EQ_CONSTRAINT 1\n#define FTS4AUX_GE_CONSTRAINT 2\n#define FTS4AUX_LE_CONSTRAINT 4\n\n/*\n** xBestIndex - Analyze a WHERE and ORDER BY clause.\n*/\nstatic int fts3auxBestIndexMethod(\n  sqlite3_vtab *pVTab, \n  sqlite3_index_info *pInfo\n){\n  int i;\n  int iEq = -1;\n  int iGe = -1;\n  int iLe = -1;\n\n  UNUSED_PARAMETER(pVTab);\n\n  /* This vtab delivers always results in \"ORDER BY term ASC\" order. */\n  if( pInfo->nOrderBy==1 \n   && pInfo->aOrderBy[0].iColumn==0 \n   && pInfo->aOrderBy[0].desc==0\n  ){\n    pInfo->orderByConsumed = 1;\n  }\n\n  /* Search for equality and range constraints on the \"term\" column. */\n  for(i=0; i<pInfo->nConstraint; i++){\n    if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){\n      int op = pInfo->aConstraint[i].op;\n      if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;\n      if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;\n      if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;\n      if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;\n      if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;\n    }\n  }\n\n  if( iEq>=0 ){\n    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;\n    pInfo->aConstraintUsage[iEq].argvIndex = 1;\n    pInfo->estimatedCost = 5;\n  }else{\n    pInfo->idxNum = 0;\n    pInfo->estimatedCost = 20000;\n    if( iGe>=0 ){\n      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;\n      pInfo->aConstraintUsage[iGe].argvIndex = 1;\n      pInfo->estimatedCost /= 2;\n    }\n    if( iLe>=0 ){\n      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;\n      pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);\n      pInfo->estimatedCost /= 2;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** xOpen - Open a cursor.\n*/\nstatic int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){\n  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */\n\n  UNUSED_PARAMETER(pVTab);\n\n  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));\n  if( !pCsr ) return SQLITE_NOMEM;\n  memset(pCsr, 0, sizeof(Fts3auxCursor));\n\n  *ppCsr = (sqlite3_vtab_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** xClose - Close a cursor.\n*/\nstatic int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n\n  sqlite3Fts3SegmentsClose(pFts3);\n  sqlite3Fts3SegReaderFinish(&pCsr->csr);\n  sqlite3_free((void *)pCsr->filter.zTerm);\n  sqlite3_free(pCsr->zStop);\n  sqlite3_free(pCsr->aStat);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\nstatic int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){\n  if( nSize>pCsr->nStat ){\n    struct Fts3auxColstats *aNew;\n    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, \n        sizeof(struct Fts3auxColstats) * nSize\n    );\n    if( aNew==0 ) return SQLITE_NOMEM;\n    memset(&aNew[pCsr->nStat], 0, \n        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)\n    );\n    pCsr->aStat = aNew;\n    pCsr->nStat = nSize;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** xNext - Advance the cursor to the next row, if any.\n*/\nstatic int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  int rc;\n\n  /* Increment our pretend rowid value. */\n  pCsr->iRowid++;\n\n  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){\n    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;\n  }\n\n  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);\n  if( rc==SQLITE_ROW ){\n    int i = 0;\n    int nDoclist = pCsr->csr.nDoclist;\n    char *aDoclist = pCsr->csr.aDoclist;\n    int iCol;\n\n    int eState = 0;\n\n    if( pCsr->zStop ){\n      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;\n      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);\n      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){\n        pCsr->isEof = 1;\n        return SQLITE_OK;\n      }\n    }\n\n    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;\n    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);\n    iCol = 0;\n\n    while( i<nDoclist ){\n      sqlite3_int64 v = 0;\n\n      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);\n      switch( eState ){\n        /* State 0. In this state the integer just read was a docid. */\n        case 0:\n          pCsr->aStat[0].nDoc++;\n          eState = 1;\n          iCol = 0;\n          break;\n\n        /* State 1. In this state we are expecting either a 1, indicating\n        ** that the following integer will be a column number, or the\n        ** start of a position list for column 0.  \n        ** \n        ** The only difference between state 1 and state 2 is that if the\n        ** integer encountered in state 1 is not 0 or 1, then we need to\n        ** increment the column 0 \"nDoc\" count for this term.\n        */\n        case 1:\n          assert( iCol==0 );\n          if( v>1 ){\n            pCsr->aStat[1].nDoc++;\n          }\n          eState = 2;\n          /* fall through */\n\n        case 2:\n          if( v==0 ){       /* 0x00. Next integer will be a docid. */\n            eState = 0;\n          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */\n            eState = 3;\n          }else{            /* 2 or greater. A position. */\n            pCsr->aStat[iCol+1].nOcc++;\n            pCsr->aStat[0].nOcc++;\n          }\n          break;\n\n        /* State 3. The integer just read is a column number. */\n        default: assert( eState==3 );\n          iCol = (int)v;\n          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;\n          pCsr->aStat[iCol+1].nDoc++;\n          eState = 2;\n          break;\n      }\n    }\n\n    pCsr->iCol = 0;\n    rc = SQLITE_OK;\n  }else{\n    pCsr->isEof = 1;\n  }\n  return rc;\n}\n\n/*\n** xFilter - Initialize a cursor to point at the start of its data.\n*/\nstatic int fts3auxFilterMethod(\n  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */\n  int idxNum,                     /* Strategy index */\n  const char *idxStr,             /* Unused */\n  int nVal,                       /* Number of elements in apVal */\n  sqlite3_value **apVal           /* Arguments for the indexing scheme */\n){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;\n  int rc;\n  int isScan;\n\n  UNUSED_PARAMETER(nVal);\n  UNUSED_PARAMETER(idxStr);\n\n  assert( idxStr==0 );\n  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0\n       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT\n       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)\n  );\n  isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);\n\n  /* In case this cursor is being reused, close and zero it. */\n  testcase(pCsr->filter.zTerm);\n  sqlite3Fts3SegReaderFinish(&pCsr->csr);\n  sqlite3_free((void *)pCsr->filter.zTerm);\n  sqlite3_free(pCsr->aStat);\n  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);\n\n  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;\n  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;\n\n  if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){\n    const unsigned char *zStr = sqlite3_value_text(apVal[0]);\n    if( zStr ){\n      pCsr->filter.zTerm = sqlite3_mprintf(\"%s\", zStr);\n      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);\n      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;\n    }\n  }\n  if( idxNum&FTS4AUX_LE_CONSTRAINT ){\n    int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;\n    pCsr->zStop = sqlite3_mprintf(\"%s\", sqlite3_value_text(apVal[iIdx]));\n    pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);\n    if( pCsr->zStop==0 ) return SQLITE_NOMEM;\n  }\n\n  rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,\n      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);\n  }\n\n  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);\n  return rc;\n}\n\n/*\n** xEof - Return true if the cursor is at EOF, or false otherwise.\n*/\nstatic int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  return pCsr->isEof;\n}\n\n/*\n** xColumn - Return a column value.\n*/\nstatic int fts3auxColumnMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */\n  int iCol                        /* Index of column to read value from */\n){\n  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;\n\n  assert( p->isEof==0 );\n  if( iCol==0 ){        /* Column \"term\" */\n    sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);\n  }else if( iCol==1 ){  /* Column \"col\" */\n    if( p->iCol ){\n      sqlite3_result_int(pContext, p->iCol-1);\n    }else{\n      sqlite3_result_text(pContext, \"*\", -1, SQLITE_STATIC);\n    }\n  }else if( iCol==2 ){  /* Column \"documents\" */\n    sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);\n  }else{                /* Column \"occurrences\" */\n    sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** xRowid - Return the current rowid for the cursor.\n*/\nstatic int fts3auxRowidMethod(\n  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */\n  sqlite_int64 *pRowid            /* OUT: Rowid value */\n){\n  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;\n  *pRowid = pCsr->iRowid;\n  return SQLITE_OK;\n}\n\n/*\n** Register the fts3aux module with database connection db. Return SQLITE_OK\n** if successful or an error code if sqlite3_create_module() fails.\n*/\nSQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){\n  static const sqlite3_module fts3aux_module = {\n     0,                           /* iVersion      */\n     fts3auxConnectMethod,        /* xCreate       */\n     fts3auxConnectMethod,        /* xConnect      */\n     fts3auxBestIndexMethod,      /* xBestIndex    */\n     fts3auxDisconnectMethod,     /* xDisconnect   */\n     fts3auxDisconnectMethod,     /* xDestroy      */\n     fts3auxOpenMethod,           /* xOpen         */\n     fts3auxCloseMethod,          /* xClose        */\n     fts3auxFilterMethod,         /* xFilter       */\n     fts3auxNextMethod,           /* xNext         */\n     fts3auxEofMethod,            /* xEof          */\n     fts3auxColumnMethod,         /* xColumn       */\n     fts3auxRowidMethod,          /* xRowid        */\n     0,                           /* xUpdate       */\n     0,                           /* xBegin        */\n     0,                           /* xSync         */\n     0,                           /* xCommit       */\n     0,                           /* xRollback     */\n     0,                           /* xFindFunction */\n     0,                           /* xRename       */\n     0,                           /* xSavepoint    */\n     0,                           /* xRelease      */\n     0                            /* xRollbackTo   */\n  };\n  int rc;                         /* Return code */\n\n  rc = sqlite3_create_module(db, \"fts4aux\", &fts3aux_module, 0);\n  return rc;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_aux.c ********************************************/\n/************** Begin file fts3_expr.c ***************************************/\n/*\n** 2008 Nov 28\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This module contains code that implements a parser for fts3 query strings\n** (the right-hand argument to the MATCH operator). Because the supported \n** syntax is relatively simple, the whole tokenizer/parser system is\n** hand-coded. \n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/*\n** By default, this module parses the legacy syntax that has been \n** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS\n** is defined, then it uses the new syntax. The differences between\n** the new and the old syntaxes are:\n**\n**  a) The new syntax supports parenthesis. The old does not.\n**\n**  b) The new syntax supports the AND and NOT operators. The old does not.\n**\n**  c) The old syntax supports the \"-\" token qualifier. This is not \n**     supported by the new syntax (it is replaced by the NOT operator).\n**\n**  d) When using the old syntax, the OR operator has a greater precedence\n**     than an implicit AND. When using the new, both implicity and explicit\n**     AND operators have a higher precedence than OR.\n**\n** If compiled with SQLITE_TEST defined, then this module exports the\n** symbol \"int sqlite3_fts3_enable_parentheses\". Setting this variable\n** to zero causes the module to use the old syntax. If it is set to \n** non-zero the new syntax is activated. This is so both syntaxes can\n** be tested using a single build of testfixture.\n**\n** The following describes the syntax supported by the fts3 MATCH\n** operator in a similar format to that used by the lemon parser\n** generator. This module does not use actually lemon, it uses a\n** custom parser.\n**\n**   query ::= andexpr (OR andexpr)*.\n**\n**   andexpr ::= notexpr (AND? notexpr)*.\n**\n**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.\n**   notexpr ::= LP query RP.\n**\n**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.\n**\n**   distance_opt ::= .\n**   distance_opt ::= / INTEGER.\n**\n**   phrase ::= TOKEN.\n**   phrase ::= COLUMN:TOKEN.\n**   phrase ::= \"TOKEN TOKEN TOKEN...\".\n*/\n\n#ifdef SQLITE_TEST\nSQLITE_API int sqlite3_fts3_enable_parentheses = 0;\n#else\n# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS \n#  define sqlite3_fts3_enable_parentheses 1\n# else\n#  define sqlite3_fts3_enable_parentheses 0\n# endif\n#endif\n\n/*\n** Default span for NEAR operators.\n*/\n#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n/*\n** isNot:\n**   This variable is used by function getNextNode(). When getNextNode() is\n**   called, it sets ParseContext.isNot to true if the 'next node' is a \n**   FTSQUERY_PHRASE with a unary \"-\" attached to it. i.e. \"mysql\" in the\n**   FTS3 query \"sqlite -mysql\". Otherwise, ParseContext.isNot is set to\n**   zero.\n*/\ntypedef struct ParseContext ParseContext;\nstruct ParseContext {\n  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */\n  int iLangid;                        /* Language id used with tokenizer */\n  const char **azCol;                 /* Array of column names for fts3 table */\n  int bFts4;                          /* True to allow FTS4-only syntax */\n  int nCol;                           /* Number of entries in azCol[] */\n  int iDefaultCol;                    /* Default column to query */\n  int isNot;                          /* True if getNextNode() sees a unary - */\n  sqlite3_context *pCtx;              /* Write error message here */\n  int nNest;                          /* Number of nested brackets */\n};\n\n/*\n** This function is equivalent to the standard isspace() function. \n**\n** The standard isspace() can be awkward to use safely, because although it\n** is defined to accept an argument of type int, its behaviour when passed\n** an integer that falls outside of the range of the unsigned char type\n** is undefined (and sometimes, \"undefined\" means segfault). This wrapper\n** is defined to accept an argument of type char, and always returns 0 for\n** any values that fall outside of the range of the unsigned char type (i.e.\n** negative values).\n*/\nstatic int fts3isspace(char c){\n  return c==' ' || c=='\\t' || c=='\\n' || c=='\\r' || c=='\\v' || c=='\\f';\n}\n\n/*\n** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,\n** zero the memory before returning a pointer to it. If unsuccessful, \n** return NULL.\n*/\nstatic void *fts3MallocZero(int nByte){\n  void *pRet = sqlite3_malloc(nByte);\n  if( pRet ) memset(pRet, 0, nByte);\n  return pRet;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(\n  sqlite3_tokenizer *pTokenizer,\n  int iLangid,\n  const char *z,\n  int n,\n  sqlite3_tokenizer_cursor **ppCsr\n){\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  sqlite3_tokenizer_cursor *pCsr = 0;\n  int rc;\n\n  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);\n  assert( rc==SQLITE_OK || pCsr==0 );\n  if( rc==SQLITE_OK ){\n    pCsr->pTokenizer = pTokenizer;\n    if( pModule->iVersion>=1 ){\n      rc = pModule->xLanguageid(pCsr, iLangid);\n      if( rc!=SQLITE_OK ){\n        pModule->xClose(pCsr);\n        pCsr = 0;\n      }\n    }\n  }\n  *ppCsr = pCsr;\n  return rc;\n}\n\n\n/*\n** Extract the next token from buffer z (length n) using the tokenizer\n** and other information (column names etc.) in pParse. Create an Fts3Expr\n** structure of type FTSQUERY_PHRASE containing a phrase consisting of this\n** single token and set *ppExpr to point to it. If the end of the buffer is\n** reached before a token is found, set *ppExpr to zero. It is the\n** responsibility of the caller to eventually deallocate the allocated \n** Fts3Expr structure (if any) by passing it to sqlite3_free().\n**\n** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation\n** fails.\n*/\nstatic int getNextToken(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  int iCol,                               /* Value for Fts3Phrase.iColumn */\n  const char *z, int n,                   /* Input string */\n  Fts3Expr **ppExpr,                      /* OUT: expression */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  int rc;\n  sqlite3_tokenizer_cursor *pCursor;\n  Fts3Expr *pRet = 0;\n  int nConsumed = 0;\n\n  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);\n  if( rc==SQLITE_OK ){\n    const char *zToken;\n    int nToken, iStart, iEnd, iPosition;\n    int nByte;                               /* total space to allocate */\n\n    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);\n    if( rc==SQLITE_OK ){\n      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;\n      pRet = (Fts3Expr *)fts3MallocZero(nByte);\n      if( !pRet ){\n        rc = SQLITE_NOMEM;\n      }else{\n        pRet->eType = FTSQUERY_PHRASE;\n        pRet->pPhrase = (Fts3Phrase *)&pRet[1];\n        pRet->pPhrase->nToken = 1;\n        pRet->pPhrase->iColumn = iCol;\n        pRet->pPhrase->aToken[0].n = nToken;\n        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];\n        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);\n\n        if( iEnd<n && z[iEnd]=='*' ){\n          pRet->pPhrase->aToken[0].isPrefix = 1;\n          iEnd++;\n        }\n\n        while( 1 ){\n          if( !sqlite3_fts3_enable_parentheses \n           && iStart>0 && z[iStart-1]=='-' \n          ){\n            pParse->isNot = 1;\n            iStart--;\n          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){\n            pRet->pPhrase->aToken[0].bFirst = 1;\n            iStart--;\n          }else{\n            break;\n          }\n        }\n\n      }\n      nConsumed = iEnd;\n    }\n\n    pModule->xClose(pCursor);\n  }\n  \n  *pnConsumed = nConsumed;\n  *ppExpr = pRet;\n  return rc;\n}\n\n\n/*\n** Enlarge a memory allocation.  If an out-of-memory allocation occurs,\n** then free the old allocation.\n*/\nstatic void *fts3ReallocOrFree(void *pOrig, int nNew){\n  void *pRet = sqlite3_realloc(pOrig, nNew);\n  if( !pRet ){\n    sqlite3_free(pOrig);\n  }\n  return pRet;\n}\n\n/*\n** Buffer zInput, length nInput, contains the contents of a quoted string\n** that appeared as part of an fts3 query expression. Neither quote character\n** is included in the buffer. This function attempts to tokenize the entire\n** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE \n** containing the results.\n**\n** If successful, SQLITE_OK is returned and *ppExpr set to point at the\n** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory\n** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set\n** to 0.\n*/\nstatic int getNextString(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *zInput, int nInput,         /* Input string */\n  Fts3Expr **ppExpr                       /* OUT: expression */\n){\n  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  int rc;\n  Fts3Expr *p = 0;\n  sqlite3_tokenizer_cursor *pCursor = 0;\n  char *zTemp = 0;\n  int nTemp = 0;\n\n  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);\n  int nToken = 0;\n\n  /* The final Fts3Expr data structure, including the Fts3Phrase,\n  ** Fts3PhraseToken structures token buffers are all stored as a single \n  ** allocation so that the expression can be freed with a single call to\n  ** sqlite3_free(). Setting this up requires a two pass approach.\n  **\n  ** The first pass, in the block below, uses a tokenizer cursor to iterate\n  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()\n  ** to assemble data in two dynamic buffers:\n  **\n  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase\n  **             structure, followed by the array of Fts3PhraseToken \n  **             structures. This pass only populates the Fts3PhraseToken array.\n  **\n  **   Buffer zTemp: Contains copies of all tokens.\n  **\n  ** The second pass, in the block that begins \"if( rc==SQLITE_DONE )\" below,\n  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase\n  ** structures.\n  */\n  rc = sqlite3Fts3OpenTokenizer(\n      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);\n  if( rc==SQLITE_OK ){\n    int ii;\n    for(ii=0; rc==SQLITE_OK; ii++){\n      const char *zByte;\n      int nByte, iBegin, iEnd, iPos;\n      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);\n      if( rc==SQLITE_OK ){\n        Fts3PhraseToken *pToken;\n\n        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));\n        if( !p ) goto no_mem;\n\n        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);\n        if( !zTemp ) goto no_mem;\n\n        assert( nToken==ii );\n        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];\n        memset(pToken, 0, sizeof(Fts3PhraseToken));\n\n        memcpy(&zTemp[nTemp], zByte, nByte);\n        nTemp += nByte;\n\n        pToken->n = nByte;\n        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');\n        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');\n        nToken = ii+1;\n      }\n    }\n\n    pModule->xClose(pCursor);\n    pCursor = 0;\n  }\n\n  if( rc==SQLITE_DONE ){\n    int jj;\n    char *zBuf = 0;\n\n    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);\n    if( !p ) goto no_mem;\n    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);\n    p->eType = FTSQUERY_PHRASE;\n    p->pPhrase = (Fts3Phrase *)&p[1];\n    p->pPhrase->iColumn = pParse->iDefaultCol;\n    p->pPhrase->nToken = nToken;\n\n    zBuf = (char *)&p->pPhrase->aToken[nToken];\n    if( zTemp ){\n      memcpy(zBuf, zTemp, nTemp);\n      sqlite3_free(zTemp);\n    }else{\n      assert( nTemp==0 );\n    }\n\n    for(jj=0; jj<p->pPhrase->nToken; jj++){\n      p->pPhrase->aToken[jj].z = zBuf;\n      zBuf += p->pPhrase->aToken[jj].n;\n    }\n    rc = SQLITE_OK;\n  }\n\n  *ppExpr = p;\n  return rc;\nno_mem:\n\n  if( pCursor ){\n    pModule->xClose(pCursor);\n  }\n  sqlite3_free(zTemp);\n  sqlite3_free(p);\n  *ppExpr = 0;\n  return SQLITE_NOMEM;\n}\n\n/*\n** Function getNextNode(), which is called by fts3ExprParse(), may itself\n** call fts3ExprParse(). So this forward declaration is required.\n*/\nstatic int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);\n\n/*\n** The output variable *ppExpr is populated with an allocated Fts3Expr \n** structure, or set to 0 if the end of the input buffer is reached.\n**\n** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM\n** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.\n** If SQLITE_ERROR is returned, pContext is populated with an error message.\n*/\nstatic int getNextNode(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *z, int n,                   /* Input string */\n  Fts3Expr **ppExpr,                      /* OUT: expression */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  static const struct Fts3Keyword {\n    char *z;                              /* Keyword text */\n    unsigned char n;                      /* Length of the keyword */\n    unsigned char parenOnly;              /* Only valid in paren mode */\n    unsigned char eType;                  /* Keyword code */\n  } aKeyword[] = {\n    { \"OR\" ,  2, 0, FTSQUERY_OR   },\n    { \"AND\",  3, 1, FTSQUERY_AND  },\n    { \"NOT\",  3, 1, FTSQUERY_NOT  },\n    { \"NEAR\", 4, 0, FTSQUERY_NEAR }\n  };\n  int ii;\n  int iCol;\n  int iColLen;\n  int rc;\n  Fts3Expr *pRet = 0;\n\n  const char *zInput = z;\n  int nInput = n;\n\n  pParse->isNot = 0;\n\n  /* Skip over any whitespace before checking for a keyword, an open or\n  ** close bracket, or a quoted string. \n  */\n  while( nInput>0 && fts3isspace(*zInput) ){\n    nInput--;\n    zInput++;\n  }\n  if( nInput==0 ){\n    return SQLITE_DONE;\n  }\n\n  /* See if we are dealing with a keyword. */\n  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){\n    const struct Fts3Keyword *pKey = &aKeyword[ii];\n\n    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){\n      continue;\n    }\n\n    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){\n      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;\n      int nKey = pKey->n;\n      char cNext;\n\n      /* If this is a \"NEAR\" keyword, check for an explicit nearness. */\n      if( pKey->eType==FTSQUERY_NEAR ){\n        assert( nKey==4 );\n        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){\n          nNear = 0;\n          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){\n            nNear = nNear * 10 + (zInput[nKey] - '0');\n          }\n        }\n      }\n\n      /* At this point this is probably a keyword. But for that to be true,\n      ** the next byte must contain either whitespace, an open or close\n      ** parenthesis, a quote character, or EOF. \n      */\n      cNext = zInput[nKey];\n      if( fts3isspace(cNext) \n       || cNext=='\"' || cNext=='(' || cNext==')' || cNext==0\n      ){\n        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));\n        if( !pRet ){\n          return SQLITE_NOMEM;\n        }\n        pRet->eType = pKey->eType;\n        pRet->nNear = nNear;\n        *ppExpr = pRet;\n        *pnConsumed = (int)((zInput - z) + nKey);\n        return SQLITE_OK;\n      }\n\n      /* Turns out that wasn't a keyword after all. This happens if the\n      ** user has supplied a token such as \"ORacle\". Continue.\n      */\n    }\n  }\n\n  /* Check for an open bracket. */\n  if( sqlite3_fts3_enable_parentheses ){\n    if( *zInput=='(' ){\n      int nConsumed;\n      pParse->nNest++;\n      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);\n      if( rc==SQLITE_OK && !*ppExpr ){\n        rc = SQLITE_DONE;\n      }\n      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);\n      return rc;\n    }\n  \n    /* Check for a close bracket. */\n    if( *zInput==')' ){\n      pParse->nNest--;\n      *pnConsumed = (int)((zInput - z) + 1);\n      return SQLITE_DONE;\n    }\n  }\n\n  /* See if we are dealing with a quoted phrase. If this is the case, then\n  ** search for the closing quote and pass the whole string to getNextString()\n  ** for processing. This is easy to do, as fts3 has no syntax for escaping\n  ** a quote character embedded in a string.\n  */\n  if( *zInput=='\"' ){\n    for(ii=1; ii<nInput && zInput[ii]!='\"'; ii++);\n    *pnConsumed = (int)((zInput - z) + ii + 1);\n    if( ii==nInput ){\n      return SQLITE_ERROR;\n    }\n    return getNextString(pParse, &zInput[1], ii-1, ppExpr);\n  }\n\n\n  /* If control flows to this point, this must be a regular token, or \n  ** the end of the input. Read a regular token using the sqlite3_tokenizer\n  ** interface. Before doing so, figure out if there is an explicit\n  ** column specifier for the token. \n  **\n  ** TODO: Strangely, it is not possible to associate a column specifier\n  ** with a quoted phrase, only with a single token. Not sure if this was\n  ** an implementation artifact or an intentional decision when fts3 was\n  ** first implemented. Whichever it was, this module duplicates the \n  ** limitation.\n  */\n  iCol = pParse->iDefaultCol;\n  iColLen = 0;\n  for(ii=0; ii<pParse->nCol; ii++){\n    const char *zStr = pParse->azCol[ii];\n    int nStr = (int)strlen(zStr);\n    if( nInput>nStr && zInput[nStr]==':' \n     && sqlite3_strnicmp(zStr, zInput, nStr)==0 \n    ){\n      iCol = ii;\n      iColLen = (int)((zInput - z) + nStr + 1);\n      break;\n    }\n  }\n  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);\n  *pnConsumed += iColLen;\n  return rc;\n}\n\n/*\n** The argument is an Fts3Expr structure for a binary operator (any type\n** except an FTSQUERY_PHRASE). Return an integer value representing the\n** precedence of the operator. Lower values have a higher precedence (i.e.\n** group more tightly). For example, in the C language, the == operator\n** groups more tightly than ||, and would therefore have a higher precedence.\n**\n** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS\n** is defined), the order of the operators in precedence from highest to\n** lowest is:\n**\n**   NEAR\n**   NOT\n**   AND (including implicit ANDs)\n**   OR\n**\n** Note that when using the old query syntax, the OR operator has a higher\n** precedence than the AND operator.\n*/\nstatic int opPrecedence(Fts3Expr *p){\n  assert( p->eType!=FTSQUERY_PHRASE );\n  if( sqlite3_fts3_enable_parentheses ){\n    return p->eType;\n  }else if( p->eType==FTSQUERY_NEAR ){\n    return 1;\n  }else if( p->eType==FTSQUERY_OR ){\n    return 2;\n  }\n  assert( p->eType==FTSQUERY_AND );\n  return 3;\n}\n\n/*\n** Argument ppHead contains a pointer to the current head of a query \n** expression tree being parsed. pPrev is the expression node most recently\n** inserted into the tree. This function adds pNew, which is always a binary\n** operator node, into the expression tree based on the relative precedence\n** of pNew and the existing nodes of the tree. This may result in the head\n** of the tree changing, in which case *ppHead is set to the new root node.\n*/\nstatic void insertBinaryOperator(\n  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */\n  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */\n  Fts3Expr *pNew           /* New binary node to insert into expression tree */\n){\n  Fts3Expr *pSplit = pPrev;\n  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){\n    pSplit = pSplit->pParent;\n  }\n\n  if( pSplit->pParent ){\n    assert( pSplit->pParent->pRight==pSplit );\n    pSplit->pParent->pRight = pNew;\n    pNew->pParent = pSplit->pParent;\n  }else{\n    *ppHead = pNew;\n  }\n  pNew->pLeft = pSplit;\n  pSplit->pParent = pNew;\n}\n\n/*\n** Parse the fts3 query expression found in buffer z, length n. This function\n** returns either when the end of the buffer is reached or an unmatched \n** closing bracket - ')' - is encountered.\n**\n** If successful, SQLITE_OK is returned, *ppExpr is set to point to the\n** parsed form of the expression and *pnConsumed is set to the number of\n** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM\n** (out of memory error) or SQLITE_ERROR (parse error) is returned.\n*/\nstatic int fts3ExprParse(\n  ParseContext *pParse,                   /* fts3 query parse context */\n  const char *z, int n,                   /* Text of MATCH query */\n  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */\n  int *pnConsumed                         /* OUT: Number of bytes consumed */\n){\n  Fts3Expr *pRet = 0;\n  Fts3Expr *pPrev = 0;\n  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */\n  int nIn = n;\n  const char *zIn = z;\n  int rc = SQLITE_OK;\n  int isRequirePhrase = 1;\n\n  while( rc==SQLITE_OK ){\n    Fts3Expr *p = 0;\n    int nByte = 0;\n    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);\n    if( rc==SQLITE_OK ){\n      int isPhrase;\n\n      if( !sqlite3_fts3_enable_parentheses \n       && p->eType==FTSQUERY_PHRASE && pParse->isNot \n      ){\n        /* Create an implicit NOT operator. */\n        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));\n        if( !pNot ){\n          sqlite3Fts3ExprFree(p);\n          rc = SQLITE_NOMEM;\n          goto exprparse_out;\n        }\n        pNot->eType = FTSQUERY_NOT;\n        pNot->pRight = p;\n        if( pNotBranch ){\n          pNot->pLeft = pNotBranch;\n        }\n        pNotBranch = pNot;\n        p = pPrev;\n      }else{\n        int eType = p->eType;\n        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);\n\n        /* The isRequirePhrase variable is set to true if a phrase or\n        ** an expression contained in parenthesis is required. If a\n        ** binary operator (AND, OR, NOT or NEAR) is encounted when\n        ** isRequirePhrase is set, this is a syntax error.\n        */\n        if( !isPhrase && isRequirePhrase ){\n          sqlite3Fts3ExprFree(p);\n          rc = SQLITE_ERROR;\n          goto exprparse_out;\n        }\n  \n        if( isPhrase && !isRequirePhrase ){\n          /* Insert an implicit AND operator. */\n          Fts3Expr *pAnd;\n          assert( pRet && pPrev );\n          pAnd = fts3MallocZero(sizeof(Fts3Expr));\n          if( !pAnd ){\n            sqlite3Fts3ExprFree(p);\n            rc = SQLITE_NOMEM;\n            goto exprparse_out;\n          }\n          pAnd->eType = FTSQUERY_AND;\n          insertBinaryOperator(&pRet, pPrev, pAnd);\n          pPrev = pAnd;\n        }\n\n        /* This test catches attempts to make either operand of a NEAR\n        ** operator something other than a phrase. For example, either of\n        ** the following:\n        **\n        **    (bracketed expression) NEAR phrase\n        **    phrase NEAR (bracketed expression)\n        **\n        ** Return an error in either case.\n        */\n        if( pPrev && (\n            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)\n         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)\n        )){\n          sqlite3Fts3ExprFree(p);\n          rc = SQLITE_ERROR;\n          goto exprparse_out;\n        }\n  \n        if( isPhrase ){\n          if( pRet ){\n            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );\n            pPrev->pRight = p;\n            p->pParent = pPrev;\n          }else{\n            pRet = p;\n          }\n        }else{\n          insertBinaryOperator(&pRet, pPrev, p);\n        }\n        isRequirePhrase = !isPhrase;\n      }\n      assert( nByte>0 );\n    }\n    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );\n    nIn -= nByte;\n    zIn += nByte;\n    pPrev = p;\n  }\n\n  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){\n    rc = SQLITE_ERROR;\n  }\n\n  if( rc==SQLITE_DONE ){\n    rc = SQLITE_OK;\n    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){\n      if( !pRet ){\n        rc = SQLITE_ERROR;\n      }else{\n        Fts3Expr *pIter = pNotBranch;\n        while( pIter->pLeft ){\n          pIter = pIter->pLeft;\n        }\n        pIter->pLeft = pRet;\n        pRet = pNotBranch;\n      }\n    }\n  }\n  *pnConsumed = n - nIn;\n\nexprparse_out:\n  if( rc!=SQLITE_OK ){\n    sqlite3Fts3ExprFree(pRet);\n    sqlite3Fts3ExprFree(pNotBranch);\n    pRet = 0;\n  }\n  *ppExpr = pRet;\n  return rc;\n}\n\n/*\n** Parameters z and n contain a pointer to and length of a buffer containing\n** an fts3 query expression, respectively. This function attempts to parse the\n** query expression and create a tree of Fts3Expr structures representing the\n** parsed expression. If successful, *ppExpr is set to point to the head\n** of the parsed expression tree and SQLITE_OK is returned. If an error\n** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse\n** error) is returned and *ppExpr is set to 0.\n**\n** If parameter n is a negative number, then z is assumed to point to a\n** nul-terminated string and the length is determined using strlen().\n**\n** The first parameter, pTokenizer, is passed the fts3 tokenizer module to\n** use to normalize query tokens while parsing the expression. The azCol[]\n** array, which is assumed to contain nCol entries, should contain the names\n** of each column in the target fts3 table, in order from left to right. \n** Column names must be nul-terminated strings.\n**\n** The iDefaultCol parameter should be passed the index of the table column\n** that appears on the left-hand-side of the MATCH operator (the default\n** column to match against for tokens for which a column name is not explicitly\n** specified as part of the query string), or -1 if tokens may by default\n** match any table column.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ExprParse(\n  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */\n  int iLangid,                        /* Language id for tokenizer */\n  char **azCol,                       /* Array of column names for fts3 table */\n  int bFts4,                          /* True to allow FTS4-only syntax */\n  int nCol,                           /* Number of entries in azCol[] */\n  int iDefaultCol,                    /* Default column to query */\n  const char *z, int n,               /* Text of MATCH query */\n  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */\n){\n  int nParsed;\n  int rc;\n  ParseContext sParse;\n\n  memset(&sParse, 0, sizeof(ParseContext));\n  sParse.pTokenizer = pTokenizer;\n  sParse.iLangid = iLangid;\n  sParse.azCol = (const char **)azCol;\n  sParse.nCol = nCol;\n  sParse.iDefaultCol = iDefaultCol;\n  sParse.bFts4 = bFts4;\n  if( z==0 ){\n    *ppExpr = 0;\n    return SQLITE_OK;\n  }\n  if( n<0 ){\n    n = (int)strlen(z);\n  }\n  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);\n\n  /* Check for mismatched parenthesis */\n  if( rc==SQLITE_OK && sParse.nNest ){\n    rc = SQLITE_ERROR;\n    sqlite3Fts3ExprFree(*ppExpr);\n    *ppExpr = 0;\n  }\n\n  return rc;\n}\n\n/*\n** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().\n*/\nSQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){\n  if( p ){\n    assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );\n    sqlite3Fts3ExprFree(p->pLeft);\n    sqlite3Fts3ExprFree(p->pRight);\n    sqlite3Fts3EvalPhraseCleanup(p->pPhrase);\n    sqlite3_free(p->aMI);\n    sqlite3_free(p);\n  }\n}\n\n/****************************************************************************\n*****************************************************************************\n** Everything after this point is just test code.\n*/\n\n#ifdef SQLITE_TEST\n\n/* #include <stdio.h> */\n\n/*\n** Function to query the hash-table of tokenizers (see README.tokenizers).\n*/\nstatic int queryTestTokenizer(\n  sqlite3 *db, \n  const char *zName,  \n  const sqlite3_tokenizer_module **pp\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char zSql[] = \"SELECT fts3_tokenizer(?)\";\n\n  *pp = 0;\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){\n      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));\n    }\n  }\n\n  return sqlite3_finalize(pStmt);\n}\n\n/*\n** Return a pointer to a buffer containing a text representation of the\n** expression passed as the first argument. The buffer is obtained from\n** sqlite3_malloc(). It is the responsibility of the caller to use \n** sqlite3_free() to release the memory. If an OOM condition is encountered,\n** NULL is returned.\n**\n** If the second argument is not NULL, then its contents are prepended to \n** the returned expression text and then freed using sqlite3_free().\n*/\nstatic char *exprToString(Fts3Expr *pExpr, char *zBuf){\n  switch( pExpr->eType ){\n    case FTSQUERY_PHRASE: {\n      Fts3Phrase *pPhrase = pExpr->pPhrase;\n      int i;\n      zBuf = sqlite3_mprintf(\n          \"%zPHRASE %d 0\", zBuf, pPhrase->iColumn);\n      for(i=0; zBuf && i<pPhrase->nToken; i++){\n        zBuf = sqlite3_mprintf(\"%z %.*s%s\", zBuf, \n            pPhrase->aToken[i].n, pPhrase->aToken[i].z,\n            (pPhrase->aToken[i].isPrefix?\"+\":\"\")\n        );\n      }\n      return zBuf;\n    }\n\n    case FTSQUERY_NEAR:\n      zBuf = sqlite3_mprintf(\"%zNEAR/%d \", zBuf, pExpr->nNear);\n      break;\n    case FTSQUERY_NOT:\n      zBuf = sqlite3_mprintf(\"%zNOT \", zBuf);\n      break;\n    case FTSQUERY_AND:\n      zBuf = sqlite3_mprintf(\"%zAND \", zBuf);\n      break;\n    case FTSQUERY_OR:\n      zBuf = sqlite3_mprintf(\"%zOR \", zBuf);\n      break;\n  }\n\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z{\", zBuf);\n  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z} {\", zBuf);\n\n  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);\n  if( zBuf ) zBuf = sqlite3_mprintf(\"%z}\", zBuf);\n\n  return zBuf;\n}\n\n/*\n** This is the implementation of a scalar SQL function used to test the \n** expression parser. It should be called as follows:\n**\n**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);\n**\n** The first argument, <tokenizer>, is the name of the fts3 tokenizer used\n** to parse the query expression (see README.tokenizers). The second argument\n** is the query expression to parse. Each subsequent argument is the name\n** of a column of the fts3 table that the query expression may refer to.\n** For example:\n**\n**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');\n*/\nstatic void fts3ExprTest(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  sqlite3_tokenizer_module const *pModule = 0;\n  sqlite3_tokenizer *pTokenizer = 0;\n  int rc;\n  char **azCol = 0;\n  const char *zExpr;\n  int nExpr;\n  int nCol;\n  int ii;\n  Fts3Expr *pExpr;\n  char *zBuf = 0;\n  sqlite3 *db = sqlite3_context_db_handle(context);\n\n  if( argc<3 ){\n    sqlite3_result_error(context, \n        \"Usage: fts3_exprtest(tokenizer, expr, col1, ...\", -1\n    );\n    return;\n  }\n\n  rc = queryTestTokenizer(db,\n                          (const char *)sqlite3_value_text(argv[0]), &pModule);\n  if( rc==SQLITE_NOMEM ){\n    sqlite3_result_error_nomem(context);\n    goto exprtest_out;\n  }else if( !pModule ){\n    sqlite3_result_error(context, \"No such tokenizer module\", -1);\n    goto exprtest_out;\n  }\n\n  rc = pModule->xCreate(0, 0, &pTokenizer);\n  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );\n  if( rc==SQLITE_NOMEM ){\n    sqlite3_result_error_nomem(context);\n    goto exprtest_out;\n  }\n  pTokenizer->pModule = pModule;\n\n  zExpr = (const char *)sqlite3_value_text(argv[1]);\n  nExpr = sqlite3_value_bytes(argv[1]);\n  nCol = argc-2;\n  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));\n  if( !azCol ){\n    sqlite3_result_error_nomem(context);\n    goto exprtest_out;\n  }\n  for(ii=0; ii<nCol; ii++){\n    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);\n  }\n\n  rc = sqlite3Fts3ExprParse(\n      pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr\n  );\n  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){\n    sqlite3_result_error(context, \"Error parsing expression\", -1);\n  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){\n    sqlite3_result_error_nomem(context);\n  }else{\n    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);\n    sqlite3_free(zBuf);\n  }\n\n  sqlite3Fts3ExprFree(pExpr);\n\nexprtest_out:\n  if( pModule && pTokenizer ){\n    rc = pModule->xDestroy(pTokenizer);\n  }\n  sqlite3_free(azCol);\n}\n\n/*\n** Register the query expression parser test function fts3_exprtest() \n** with database connection db. \n*/\nSQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){\n  return sqlite3_create_function(\n      db, \"fts3_exprtest\", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0\n  );\n}\n\n#endif\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_expr.c *******************************************/\n/************** Begin file fts3_hash.c ***************************************/\n/*\n** 2001 September 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This is the implementation of generic hash-tables used in SQLite.\n** We've modified it slightly to serve as a standalone hash table\n** implementation for the full-text indexing module.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <string.h> */\n\n\n/*\n** Malloc and Free functions\n*/\nstatic void *fts3HashMalloc(int n){\n  void *p = sqlite3_malloc(n);\n  if( p ){\n    memset(p, 0, n);\n  }\n  return p;\n}\nstatic void fts3HashFree(void *p){\n  sqlite3_free(p);\n}\n\n/* Turn bulk memory into a hash table object by initializing the\n** fields of the Hash structure.\n**\n** \"pNew\" is a pointer to the hash table that is to be initialized.\n** keyClass is one of the constants \n** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass \n** determines what kind of key the hash table will use.  \"copyKey\" is\n** true if the hash table should make its own private copy of keys and\n** false if it should just use the supplied pointer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){\n  assert( pNew!=0 );\n  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );\n  pNew->keyClass = keyClass;\n  pNew->copyKey = copyKey;\n  pNew->first = 0;\n  pNew->count = 0;\n  pNew->htsize = 0;\n  pNew->ht = 0;\n}\n\n/* Remove all entries from a hash table.  Reclaim all memory.\n** Call this routine to delete a hash table or to reset a hash table\n** to the empty state.\n*/\nSQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){\n  Fts3HashElem *elem;         /* For looping over all elements of the table */\n\n  assert( pH!=0 );\n  elem = pH->first;\n  pH->first = 0;\n  fts3HashFree(pH->ht);\n  pH->ht = 0;\n  pH->htsize = 0;\n  while( elem ){\n    Fts3HashElem *next_elem = elem->next;\n    if( pH->copyKey && elem->pKey ){\n      fts3HashFree(elem->pKey);\n    }\n    fts3HashFree(elem);\n    elem = next_elem;\n  }\n  pH->count = 0;\n}\n\n/*\n** Hash and comparison functions when the mode is FTS3_HASH_STRING\n*/\nstatic int fts3StrHash(const void *pKey, int nKey){\n  const char *z = (const char *)pKey;\n  int h = 0;\n  if( nKey<=0 ) nKey = (int) strlen(z);\n  while( nKey > 0  ){\n    h = (h<<3) ^ h ^ *z++;\n    nKey--;\n  }\n  return h & 0x7fffffff;\n}\nstatic int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){\n  if( n1!=n2 ) return 1;\n  return strncmp((const char*)pKey1,(const char*)pKey2,n1);\n}\n\n/*\n** Hash and comparison functions when the mode is FTS3_HASH_BINARY\n*/\nstatic int fts3BinHash(const void *pKey, int nKey){\n  int h = 0;\n  const char *z = (const char *)pKey;\n  while( nKey-- > 0 ){\n    h = (h<<3) ^ h ^ *(z++);\n  }\n  return h & 0x7fffffff;\n}\nstatic int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){\n  if( n1!=n2 ) return 1;\n  return memcmp(pKey1,pKey2,n1);\n}\n\n/*\n** Return a pointer to the appropriate hash function given the key class.\n**\n** The C syntax in this function definition may be unfamilar to some \n** programmers, so we provide the following additional explanation:\n**\n** The name of the function is \"ftsHashFunction\".  The function takes a\n** single parameter \"keyClass\".  The return value of ftsHashFunction()\n** is a pointer to another function.  Specifically, the return value\n** of ftsHashFunction() is a pointer to a function that takes two parameters\n** with types \"const void*\" and \"int\" and returns an \"int\".\n*/\nstatic int (*ftsHashFunction(int keyClass))(const void*,int){\n  if( keyClass==FTS3_HASH_STRING ){\n    return &fts3StrHash;\n  }else{\n    assert( keyClass==FTS3_HASH_BINARY );\n    return &fts3BinHash;\n  }\n}\n\n/*\n** Return a pointer to the appropriate hash function given the key class.\n**\n** For help in interpreted the obscure C code in the function definition,\n** see the header comment on the previous function.\n*/\nstatic int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){\n  if( keyClass==FTS3_HASH_STRING ){\n    return &fts3StrCompare;\n  }else{\n    assert( keyClass==FTS3_HASH_BINARY );\n    return &fts3BinCompare;\n  }\n}\n\n/* Link an element into the hash table\n*/\nstatic void fts3HashInsertElement(\n  Fts3Hash *pH,            /* The complete hash table */\n  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */\n  Fts3HashElem *pNew       /* The element to be inserted */\n){\n  Fts3HashElem *pHead;     /* First element already in pEntry */\n  pHead = pEntry->chain;\n  if( pHead ){\n    pNew->next = pHead;\n    pNew->prev = pHead->prev;\n    if( pHead->prev ){ pHead->prev->next = pNew; }\n    else             { pH->first = pNew; }\n    pHead->prev = pNew;\n  }else{\n    pNew->next = pH->first;\n    if( pH->first ){ pH->first->prev = pNew; }\n    pNew->prev = 0;\n    pH->first = pNew;\n  }\n  pEntry->count++;\n  pEntry->chain = pNew;\n}\n\n\n/* Resize the hash table so that it cantains \"new_size\" buckets.\n** \"new_size\" must be a power of 2.  The hash table might fail \n** to resize if sqliteMalloc() fails.\n**\n** Return non-zero if a memory allocation error occurs.\n*/\nstatic int fts3Rehash(Fts3Hash *pH, int new_size){\n  struct _fts3ht *new_ht;          /* The new hash table */\n  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */\n  int (*xHash)(const void*,int);   /* The hash function */\n\n  assert( (new_size & (new_size-1))==0 );\n  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );\n  if( new_ht==0 ) return 1;\n  fts3HashFree(pH->ht);\n  pH->ht = new_ht;\n  pH->htsize = new_size;\n  xHash = ftsHashFunction(pH->keyClass);\n  for(elem=pH->first, pH->first=0; elem; elem = next_elem){\n    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);\n    next_elem = elem->next;\n    fts3HashInsertElement(pH, &new_ht[h], elem);\n  }\n  return 0;\n}\n\n/* This function (for internal use only) locates an element in an\n** hash table that matches the given key.  The hash for this key has\n** already been computed and is passed as the 4th parameter.\n*/\nstatic Fts3HashElem *fts3FindElementByHash(\n  const Fts3Hash *pH, /* The pH to be searched */\n  const void *pKey,   /* The key we are searching for */\n  int nKey,\n  int h               /* The hash for this key. */\n){\n  Fts3HashElem *elem;            /* Used to loop thru the element list */\n  int count;                     /* Number of elements left to test */\n  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */\n\n  if( pH->ht ){\n    struct _fts3ht *pEntry = &pH->ht[h];\n    elem = pEntry->chain;\n    count = pEntry->count;\n    xCompare = ftsCompareFunction(pH->keyClass);\n    while( count-- && elem ){\n      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ \n        return elem;\n      }\n      elem = elem->next;\n    }\n  }\n  return 0;\n}\n\n/* Remove a single entry from the hash table given a pointer to that\n** element and a hash on the element's key.\n*/\nstatic void fts3RemoveElementByHash(\n  Fts3Hash *pH,         /* The pH containing \"elem\" */\n  Fts3HashElem* elem,   /* The element to be removed from the pH */\n  int h                 /* Hash value for the element */\n){\n  struct _fts3ht *pEntry;\n  if( elem->prev ){\n    elem->prev->next = elem->next; \n  }else{\n    pH->first = elem->next;\n  }\n  if( elem->next ){\n    elem->next->prev = elem->prev;\n  }\n  pEntry = &pH->ht[h];\n  if( pEntry->chain==elem ){\n    pEntry->chain = elem->next;\n  }\n  pEntry->count--;\n  if( pEntry->count<=0 ){\n    pEntry->chain = 0;\n  }\n  if( pH->copyKey && elem->pKey ){\n    fts3HashFree(elem->pKey);\n  }\n  fts3HashFree( elem );\n  pH->count--;\n  if( pH->count<=0 ){\n    assert( pH->first==0 );\n    assert( pH->count==0 );\n    fts3HashClear(pH);\n  }\n}\n\nSQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(\n  const Fts3Hash *pH, \n  const void *pKey, \n  int nKey\n){\n  int h;                          /* A hash on key */\n  int (*xHash)(const void*,int);  /* The hash function */\n\n  if( pH==0 || pH->ht==0 ) return 0;\n  xHash = ftsHashFunction(pH->keyClass);\n  assert( xHash!=0 );\n  h = (*xHash)(pKey,nKey);\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));\n}\n\n/* \n** Attempt to locate an element of the hash table pH with a key\n** that matches pKey,nKey.  Return the data for this element if it is\n** found, or NULL if there is no match.\n*/\nSQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){\n  Fts3HashElem *pElem;            /* The element that matches key (if any) */\n\n  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);\n  return pElem ? pElem->data : 0;\n}\n\n/* Insert an element into the hash table pH.  The key is pKey,nKey\n** and the data is \"data\".\n**\n** If no element exists with a matching key, then a new\n** element is created.  A copy of the key is made if the copyKey\n** flag is set.  NULL is returned.\n**\n** If another element already exists with the same key, then the\n** new data replaces the old data and the old data is returned.\n** The key is not copied in this instance.  If a malloc fails, then\n** the new data is returned and the hash table is unchanged.\n**\n** If the \"data\" parameter to this function is NULL, then the\n** element corresponding to \"key\" is removed from the hash table.\n*/\nSQLITE_PRIVATE void *sqlite3Fts3HashInsert(\n  Fts3Hash *pH,        /* The hash table to insert into */\n  const void *pKey,    /* The key */\n  int nKey,            /* Number of bytes in the key */\n  void *data           /* The data */\n){\n  int hraw;                 /* Raw hash value of the key */\n  int h;                    /* the hash of the key modulo hash table size */\n  Fts3HashElem *elem;       /* Used to loop thru the element list */\n  Fts3HashElem *new_elem;   /* New element added to the pH */\n  int (*xHash)(const void*,int);  /* The hash function */\n\n  assert( pH!=0 );\n  xHash = ftsHashFunction(pH->keyClass);\n  assert( xHash!=0 );\n  hraw = (*xHash)(pKey, nKey);\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  h = hraw & (pH->htsize-1);\n  elem = fts3FindElementByHash(pH,pKey,nKey,h);\n  if( elem ){\n    void *old_data = elem->data;\n    if( data==0 ){\n      fts3RemoveElementByHash(pH,elem,h);\n    }else{\n      elem->data = data;\n    }\n    return old_data;\n  }\n  if( data==0 ) return 0;\n  if( (pH->htsize==0 && fts3Rehash(pH,8))\n   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))\n  ){\n    pH->count = 0;\n    return data;\n  }\n  assert( pH->htsize>0 );\n  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );\n  if( new_elem==0 ) return data;\n  if( pH->copyKey && pKey!=0 ){\n    new_elem->pKey = fts3HashMalloc( nKey );\n    if( new_elem->pKey==0 ){\n      fts3HashFree(new_elem);\n      return data;\n    }\n    memcpy((void*)new_elem->pKey, pKey, nKey);\n  }else{\n    new_elem->pKey = (void*)pKey;\n  }\n  new_elem->nKey = nKey;\n  pH->count++;\n  assert( pH->htsize>0 );\n  assert( (pH->htsize & (pH->htsize-1))==0 );\n  h = hraw & (pH->htsize-1);\n  fts3HashInsertElement(pH, &pH->ht[h], new_elem);\n  new_elem->data = data;\n  return 0;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_hash.c *******************************************/\n/************** Begin file fts3_porter.c *************************************/\n/*\n** 2006 September 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** Implementation of the full-text-search tokenizer that implements\n** a Porter stemmer.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n\n/*\n** Class derived from sqlite3_tokenizer\n*/\ntypedef struct porter_tokenizer {\n  sqlite3_tokenizer base;      /* Base class */\n} porter_tokenizer;\n\n/*\n** Class derived from sqlite3_tokenizer_cursor\n*/\ntypedef struct porter_tokenizer_cursor {\n  sqlite3_tokenizer_cursor base;\n  const char *zInput;          /* input we are tokenizing */\n  int nInput;                  /* size of the input */\n  int iOffset;                 /* current position in zInput */\n  int iToken;                  /* index of next token to be returned */\n  char *zToken;                /* storage for current token */\n  int nAllocated;              /* space allocated to zToken buffer */\n} porter_tokenizer_cursor;\n\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int porterCreate(\n  int argc, const char * const *argv,\n  sqlite3_tokenizer **ppTokenizer\n){\n  porter_tokenizer *t;\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));\n  if( t==NULL ) return SQLITE_NOMEM;\n  memset(t, 0, sizeof(*t));\n  *ppTokenizer = &t->base;\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int porterDestroy(sqlite3_tokenizer *pTokenizer){\n  sqlite3_free(pTokenizer);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is zInput[0..nInput-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int porterOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *zInput, int nInput,        /* String to be tokenized */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  porter_tokenizer_cursor *c;\n\n  UNUSED_PARAMETER(pTokenizer);\n\n  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));\n  if( c==NULL ) return SQLITE_NOMEM;\n\n  c->zInput = zInput;\n  if( zInput==0 ){\n    c->nInput = 0;\n  }else if( nInput<0 ){\n    c->nInput = (int)strlen(zInput);\n  }else{\n    c->nInput = nInput;\n  }\n  c->iOffset = 0;                 /* start tokenizing at the beginning */\n  c->iToken = 0;\n  c->zToken = NULL;               /* no space allocated, yet. */\n  c->nAllocated = 0;\n\n  *ppCursor = &c->base;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** porterOpen() above.\n*/\nstatic int porterClose(sqlite3_tokenizer_cursor *pCursor){\n  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;\n  sqlite3_free(c->zToken);\n  sqlite3_free(c);\n  return SQLITE_OK;\n}\n/*\n** Vowel or consonant\n*/\nstatic const char cType[] = {\n   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,\n   1, 1, 1, 2, 1\n};\n\n/*\n** isConsonant() and isVowel() determine if their first character in\n** the string they point to is a consonant or a vowel, according\n** to Porter ruls.  \n**\n** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.\n** 'Y' is a consonant unless it follows another consonant,\n** in which case it is a vowel.\n**\n** In these routine, the letters are in reverse order.  So the 'y' rule\n** is that 'y' is a consonant unless it is followed by another\n** consonent.\n*/\nstatic int isVowel(const char*);\nstatic int isConsonant(const char *z){\n  int j;\n  char x = *z;\n  if( x==0 ) return 0;\n  assert( x>='a' && x<='z' );\n  j = cType[x-'a'];\n  if( j<2 ) return j;\n  return z[1]==0 || isVowel(z + 1);\n}\nstatic int isVowel(const char *z){\n  int j;\n  char x = *z;\n  if( x==0 ) return 0;\n  assert( x>='a' && x<='z' );\n  j = cType[x-'a'];\n  if( j<2 ) return 1-j;\n  return isConsonant(z + 1);\n}\n\n/*\n** Let any sequence of one or more vowels be represented by V and let\n** C be sequence of one or more consonants.  Then every word can be\n** represented as:\n**\n**           [C] (VC){m} [V]\n**\n** In prose:  A word is an optional consonant followed by zero or\n** vowel-consonant pairs followed by an optional vowel.  \"m\" is the\n** number of vowel consonant pairs.  This routine computes the value\n** of m for the first i bytes of a word.\n**\n** Return true if the m-value for z is 1 or more.  In other words,\n** return true if z contains at least one vowel that is followed\n** by a consonant.\n**\n** In this routine z[] is in reverse order.  So we are really looking\n** for an instance of of a consonant followed by a vowel.\n*/\nstatic int m_gt_0(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/* Like mgt0 above except we are looking for a value of m which is\n** exactly 1\n*/\nstatic int m_eq_1(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 1;\n  while( isConsonant(z) ){ z++; }\n  return *z==0;\n}\n\n/* Like mgt0 above except we are looking for a value of m>1 instead\n** or m>0\n*/\nstatic int m_gt_1(const char *z){\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isVowel(z) ){ z++; }\n  if( *z==0 ) return 0;\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/*\n** Return TRUE if there is a vowel anywhere within z[0..n-1]\n*/\nstatic int hasVowel(const char *z){\n  while( isConsonant(z) ){ z++; }\n  return *z!=0;\n}\n\n/*\n** Return TRUE if the word ends in a double consonant.\n**\n** The text is reversed here. So we are really looking at\n** the first two characters of z[].\n*/\nstatic int doubleConsonant(const char *z){\n  return isConsonant(z) && z[0]==z[1];\n}\n\n/*\n** Return TRUE if the word ends with three letters which\n** are consonant-vowel-consonent and where the final consonant\n** is not 'w', 'x', or 'y'.\n**\n** The word is reversed here.  So we are really checking the\n** first three letters and the first one cannot be in [wxy].\n*/\nstatic int star_oh(const char *z){\n  return\n    isConsonant(z) &&\n    z[0]!='w' && z[0]!='x' && z[0]!='y' &&\n    isVowel(z+1) &&\n    isConsonant(z+2);\n}\n\n/*\n** If the word ends with zFrom and xCond() is true for the stem\n** of the word that preceeds the zFrom ending, then change the \n** ending to zTo.\n**\n** The input word *pz and zFrom are both in reverse order.  zTo\n** is in normal order. \n**\n** Return TRUE if zFrom matches.  Return FALSE if zFrom does not\n** match.  Not that TRUE is returned even if xCond() fails and\n** no substitution occurs.\n*/\nstatic int stem(\n  char **pz,             /* The word being stemmed (Reversed) */\n  const char *zFrom,     /* If the ending matches this... (Reversed) */\n  const char *zTo,       /* ... change the ending to this (not reversed) */\n  int (*xCond)(const char*)   /* Condition that must be true */\n){\n  char *z = *pz;\n  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }\n  if( *zFrom!=0 ) return 0;\n  if( xCond && !xCond(z) ) return 1;\n  while( *zTo ){\n    *(--z) = *(zTo++);\n  }\n  *pz = z;\n  return 1;\n}\n\n/*\n** This is the fallback stemmer used when the porter stemmer is\n** inappropriate.  The input word is copied into the output with\n** US-ASCII case folding.  If the input word is too long (more\n** than 20 bytes if it contains no digits or more than 6 bytes if\n** it contains digits) then word is truncated to 20 or 6 bytes\n** by taking 10 or 3 bytes from the beginning and end.\n*/\nstatic void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){\n  int i, mx, j;\n  int hasDigit = 0;\n  for(i=0; i<nIn; i++){\n    char c = zIn[i];\n    if( c>='A' && c<='Z' ){\n      zOut[i] = c - 'A' + 'a';\n    }else{\n      if( c>='0' && c<='9' ) hasDigit = 1;\n      zOut[i] = c;\n    }\n  }\n  mx = hasDigit ? 3 : 10;\n  if( nIn>mx*2 ){\n    for(j=mx, i=nIn-mx; i<nIn; i++, j++){\n      zOut[j] = zOut[i];\n    }\n    i = j;\n  }\n  zOut[i] = 0;\n  *pnOut = i;\n}\n\n\n/*\n** Stem the input word zIn[0..nIn-1].  Store the output in zOut.\n** zOut is at least big enough to hold nIn bytes.  Write the actual\n** size of the output word (exclusive of the '\\0' terminator) into *pnOut.\n**\n** Any upper-case characters in the US-ASCII character set ([A-Z])\n** are converted to lower case.  Upper-case UTF characters are\n** unchanged.\n**\n** Words that are longer than about 20 bytes are stemmed by retaining\n** a few bytes from the beginning and the end of the word.  If the\n** word contains digits, 3 bytes are taken from the beginning and\n** 3 bytes from the end.  For long words without digits, 10 bytes\n** are taken from each end.  US-ASCII case folding still applies.\n** \n** If the input word contains not digits but does characters not \n** in [a-zA-Z] then no stemming is attempted and this routine just \n** copies the input into the input into the output with US-ASCII\n** case folding.\n**\n** Stemming never increases the length of the word.  So there is\n** no chance of overflowing the zOut buffer.\n*/\nstatic void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){\n  int i, j;\n  char zReverse[28];\n  char *z, *z2;\n  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){\n    /* The word is too big or too small for the porter stemmer.\n    ** Fallback to the copy stemmer */\n    copy_stemmer(zIn, nIn, zOut, pnOut);\n    return;\n  }\n  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){\n    char c = zIn[i];\n    if( c>='A' && c<='Z' ){\n      zReverse[j] = c + 'a' - 'A';\n    }else if( c>='a' && c<='z' ){\n      zReverse[j] = c;\n    }else{\n      /* The use of a character not in [a-zA-Z] means that we fallback\n      ** to the copy stemmer */\n      copy_stemmer(zIn, nIn, zOut, pnOut);\n      return;\n    }\n  }\n  memset(&zReverse[sizeof(zReverse)-5], 0, 5);\n  z = &zReverse[j+1];\n\n\n  /* Step 1a */\n  if( z[0]=='s' ){\n    if(\n     !stem(&z, \"sess\", \"ss\", 0) &&\n     !stem(&z, \"sei\", \"i\", 0)  &&\n     !stem(&z, \"ss\", \"ss\", 0)\n    ){\n      z++;\n    }\n  }\n\n  /* Step 1b */  \n  z2 = z;\n  if( stem(&z, \"dee\", \"ee\", m_gt_0) ){\n    /* Do nothing.  The work was all in the test */\n  }else if( \n     (stem(&z, \"gni\", \"\", hasVowel) || stem(&z, \"de\", \"\", hasVowel))\n      && z!=z2\n  ){\n     if( stem(&z, \"ta\", \"ate\", 0) ||\n         stem(&z, \"lb\", \"ble\", 0) ||\n         stem(&z, \"zi\", \"ize\", 0) ){\n       /* Do nothing.  The work was all in the test */\n     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){\n       z++;\n     }else if( m_eq_1(z) && star_oh(z) ){\n       *(--z) = 'e';\n     }\n  }\n\n  /* Step 1c */\n  if( z[0]=='y' && hasVowel(z+1) ){\n    z[0] = 'i';\n  }\n\n  /* Step 2 */\n  switch( z[1] ){\n   case 'a':\n     stem(&z, \"lanoita\", \"ate\", m_gt_0) ||\n     stem(&z, \"lanoit\", \"tion\", m_gt_0);\n     break;\n   case 'c':\n     stem(&z, \"icne\", \"ence\", m_gt_0) ||\n     stem(&z, \"icna\", \"ance\", m_gt_0);\n     break;\n   case 'e':\n     stem(&z, \"rezi\", \"ize\", m_gt_0);\n     break;\n   case 'g':\n     stem(&z, \"igol\", \"log\", m_gt_0);\n     break;\n   case 'l':\n     stem(&z, \"ilb\", \"ble\", m_gt_0) ||\n     stem(&z, \"illa\", \"al\", m_gt_0) ||\n     stem(&z, \"iltne\", \"ent\", m_gt_0) ||\n     stem(&z, \"ile\", \"e\", m_gt_0) ||\n     stem(&z, \"ilsuo\", \"ous\", m_gt_0);\n     break;\n   case 'o':\n     stem(&z, \"noitazi\", \"ize\", m_gt_0) ||\n     stem(&z, \"noita\", \"ate\", m_gt_0) ||\n     stem(&z, \"rota\", \"ate\", m_gt_0);\n     break;\n   case 's':\n     stem(&z, \"msila\", \"al\", m_gt_0) ||\n     stem(&z, \"ssenevi\", \"ive\", m_gt_0) ||\n     stem(&z, \"ssenluf\", \"ful\", m_gt_0) ||\n     stem(&z, \"ssensuo\", \"ous\", m_gt_0);\n     break;\n   case 't':\n     stem(&z, \"itila\", \"al\", m_gt_0) ||\n     stem(&z, \"itivi\", \"ive\", m_gt_0) ||\n     stem(&z, \"itilib\", \"ble\", m_gt_0);\n     break;\n  }\n\n  /* Step 3 */\n  switch( z[0] ){\n   case 'e':\n     stem(&z, \"etaci\", \"ic\", m_gt_0) ||\n     stem(&z, \"evita\", \"\", m_gt_0)   ||\n     stem(&z, \"ezila\", \"al\", m_gt_0);\n     break;\n   case 'i':\n     stem(&z, \"itici\", \"ic\", m_gt_0);\n     break;\n   case 'l':\n     stem(&z, \"laci\", \"ic\", m_gt_0) ||\n     stem(&z, \"luf\", \"\", m_gt_0);\n     break;\n   case 's':\n     stem(&z, \"ssen\", \"\", m_gt_0);\n     break;\n  }\n\n  /* Step 4 */\n  switch( z[1] ){\n   case 'a':\n     if( z[0]=='l' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'c':\n     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){\n       z += 4;\n     }\n     break;\n   case 'e':\n     if( z[0]=='r' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'i':\n     if( z[0]=='c' && m_gt_1(z+2) ){\n       z += 2;\n     }\n     break;\n   case 'l':\n     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){\n       z += 4;\n     }\n     break;\n   case 'n':\n     if( z[0]=='t' ){\n       if( z[2]=='a' ){\n         if( m_gt_1(z+3) ){\n           z += 3;\n         }\n       }else if( z[2]=='e' ){\n         stem(&z, \"tneme\", \"\", m_gt_1) ||\n         stem(&z, \"tnem\", \"\", m_gt_1) ||\n         stem(&z, \"tne\", \"\", m_gt_1);\n       }\n     }\n     break;\n   case 'o':\n     if( z[0]=='u' ){\n       if( m_gt_1(z+2) ){\n         z += 2;\n       }\n     }else if( z[3]=='s' || z[3]=='t' ){\n       stem(&z, \"noi\", \"\", m_gt_1);\n     }\n     break;\n   case 's':\n     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n   case 't':\n     stem(&z, \"eta\", \"\", m_gt_1) ||\n     stem(&z, \"iti\", \"\", m_gt_1);\n     break;\n   case 'u':\n     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n   case 'v':\n   case 'z':\n     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){\n       z += 3;\n     }\n     break;\n  }\n\n  /* Step 5a */\n  if( z[0]=='e' ){\n    if( m_gt_1(z+1) ){\n      z++;\n    }else if( m_eq_1(z+1) && !star_oh(z+1) ){\n      z++;\n    }\n  }\n\n  /* Step 5b */\n  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){\n    z++;\n  }\n\n  /* z[] is now the stemmed word in reverse order.  Flip it back\n  ** around into forward order and return.\n  */\n  *pnOut = i = (int)strlen(z);\n  zOut[i] = 0;\n  while( *z ){\n    zOut[--i] = *(z++);\n  }\n}\n\n/*\n** Characters that can be part of a token.  We assume any character\n** whose value is greater than 0x80 (any UTF character) can be\n** part of a token.  In other words, delimiters all must have\n** values of 0x7f or lower.\n*/\nstatic const char porterIdChar[] = {\n/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */\n    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */\n};\n#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to porterOpen().\n*/\nstatic int porterNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */\n  const char **pzToken,               /* OUT: *pzToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;\n  const char *z = c->zInput;\n\n  while( c->iOffset<c->nInput ){\n    int iStartOffset, ch;\n\n    /* Scan past delimiter characters */\n    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    /* Count non-delimiter characters. */\n    iStartOffset = c->iOffset;\n    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    if( c->iOffset>iStartOffset ){\n      int n = c->iOffset-iStartOffset;\n      if( n>c->nAllocated ){\n        char *pNew;\n        c->nAllocated = n+20;\n        pNew = sqlite3_realloc(c->zToken, c->nAllocated);\n        if( !pNew ) return SQLITE_NOMEM;\n        c->zToken = pNew;\n      }\n      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);\n      *pzToken = c->zToken;\n      *piStartOffset = iStartOffset;\n      *piEndOffset = c->iOffset;\n      *piPosition = c->iToken++;\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_DONE;\n}\n\n/*\n** The set of routines that implement the porter-stemmer tokenizer\n*/\nstatic const sqlite3_tokenizer_module porterTokenizerModule = {\n  0,\n  porterCreate,\n  porterDestroy,\n  porterOpen,\n  porterClose,\n  porterNext,\n  0\n};\n\n/*\n** Allocate a new porter tokenizer.  Return a pointer to the new\n** tokenizer in *ppModule\n*/\nSQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &porterTokenizerModule;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_porter.c *****************************************/\n/************** Begin file fts3_tokenizer.c **********************************/\n/*\n** 2007 June 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This is part of an SQLite module implementing full-text search.\n** This particular file implements the generic tokenizer interface.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <string.h> */\n\n/*\n** Implementation of the SQL scalar function for accessing the underlying \n** hash table. This function may be called as follows:\n**\n**   SELECT <function-name>(<key-name>);\n**   SELECT <function-name>(<key-name>, <pointer>);\n**\n** where <function-name> is the name passed as the second argument\n** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').\n**\n** If the <pointer> argument is specified, it must be a blob value\n** containing a pointer to be stored as the hash data corresponding\n** to the string <key-name>. If <pointer> is not specified, then\n** the string <key-name> must already exist in the has table. Otherwise,\n** an error is returned.\n**\n** Whether or not the <pointer> argument is specified, the value returned\n** is a blob containing the pointer stored as the hash data corresponding\n** to string <key-name> (after the hash-table is updated, if applicable).\n*/\nstatic void scalarFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Fts3Hash *pHash;\n  void *pPtr = 0;\n  const unsigned char *zName;\n  int nName;\n\n  assert( argc==1 || argc==2 );\n\n  pHash = (Fts3Hash *)sqlite3_user_data(context);\n\n  zName = sqlite3_value_text(argv[0]);\n  nName = sqlite3_value_bytes(argv[0])+1;\n\n  if( argc==2 ){\n    void *pOld;\n    int n = sqlite3_value_bytes(argv[1]);\n    if( n!=sizeof(pPtr) ){\n      sqlite3_result_error(context, \"argument type mismatch\", -1);\n      return;\n    }\n    pPtr = *(void **)sqlite3_value_blob(argv[1]);\n    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);\n    if( pOld==pPtr ){\n      sqlite3_result_error(context, \"out of memory\", -1);\n      return;\n    }\n  }else{\n    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);\n    if( !pPtr ){\n      char *zErr = sqlite3_mprintf(\"unknown tokenizer: %s\", zName);\n      sqlite3_result_error(context, zErr, -1);\n      sqlite3_free(zErr);\n      return;\n    }\n  }\n\n  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);\n}\n\nSQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){\n  static const char isFtsIdChar[] = {\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */\n      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */\n      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */\n      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */\n      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */\n  };\n  return (c&0x80 || isFtsIdChar[(int)(c)]);\n}\n\nSQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){\n  const char *z1;\n  const char *z2 = 0;\n\n  /* Find the start of the next token. */\n  z1 = zStr;\n  while( z2==0 ){\n    char c = *z1;\n    switch( c ){\n      case '\\0': return 0;        /* No more tokens here */\n      case '\\'':\n      case '\"':\n      case '`': {\n        z2 = z1;\n        while( *++z2 && (*z2!=c || *++z2==c) );\n        break;\n      }\n      case '[':\n        z2 = &z1[1];\n        while( *z2 && z2[0]!=']' ) z2++;\n        if( *z2 ) z2++;\n        break;\n\n      default:\n        if( sqlite3Fts3IsIdChar(*z1) ){\n          z2 = &z1[1];\n          while( sqlite3Fts3IsIdChar(*z2) ) z2++;\n        }else{\n          z1++;\n        }\n    }\n  }\n\n  *pn = (int)(z2-z1);\n  return z1;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3InitTokenizer(\n  Fts3Hash *pHash,                /* Tokenizer hash table */\n  const char *zArg,               /* Tokenizer name */\n  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */\n  char **pzErr                    /* OUT: Set to malloced error message */\n){\n  int rc;\n  char *z = (char *)zArg;\n  int n = 0;\n  char *zCopy;\n  char *zEnd;                     /* Pointer to nul-term of zCopy */\n  sqlite3_tokenizer_module *m;\n\n  zCopy = sqlite3_mprintf(\"%s\", zArg);\n  if( !zCopy ) return SQLITE_NOMEM;\n  zEnd = &zCopy[strlen(zCopy)];\n\n  z = (char *)sqlite3Fts3NextToken(zCopy, &n);\n  z[n] = '\\0';\n  sqlite3Fts3Dequote(z);\n\n  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);\n  if( !m ){\n    *pzErr = sqlite3_mprintf(\"unknown tokenizer: %s\", z);\n    rc = SQLITE_ERROR;\n  }else{\n    char const **aArg = 0;\n    int iArg = 0;\n    z = &z[n+1];\n    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){\n      int nNew = sizeof(char *)*(iArg+1);\n      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);\n      if( !aNew ){\n        sqlite3_free(zCopy);\n        sqlite3_free((void *)aArg);\n        return SQLITE_NOMEM;\n      }\n      aArg = aNew;\n      aArg[iArg++] = z;\n      z[n] = '\\0';\n      sqlite3Fts3Dequote(z);\n      z = &z[n+1];\n    }\n    rc = m->xCreate(iArg, aArg, ppTok);\n    assert( rc!=SQLITE_OK || *ppTok );\n    if( rc!=SQLITE_OK ){\n      *pzErr = sqlite3_mprintf(\"unknown tokenizer\");\n    }else{\n      (*ppTok)->pModule = m; \n    }\n    sqlite3_free((void *)aArg);\n  }\n\n  sqlite3_free(zCopy);\n  return rc;\n}\n\n\n#ifdef SQLITE_TEST\n\n/* #include <tcl.h> */\n/* #include <string.h> */\n\n/*\n** Implementation of a special SQL scalar function for testing tokenizers \n** designed to be used in concert with the Tcl testing framework. This\n** function must be called with two or more arguments:\n**\n**   SELECT <function-name>(<key-name>, ..., <input-string>);\n**\n** where <function-name> is the name passed as the second argument\n** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')\n** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').\n**\n** The return value is a string that may be interpreted as a Tcl\n** list. For each token in the <input-string>, three elements are\n** added to the returned list. The first is the token position, the \n** second is the token text (folded, stemmed, etc.) and the third is the\n** substring of <input-string> associated with the token. For example, \n** using the built-in \"simple\" tokenizer:\n**\n**   SELECT fts_tokenizer_test('simple', 'I don't see how');\n**\n** will return the string:\n**\n**   \"{0 i I 1 dont don't 2 see see 3 how how}\"\n**   \n*/\nstatic void testFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  Fts3Hash *pHash;\n  sqlite3_tokenizer_module *p;\n  sqlite3_tokenizer *pTokenizer = 0;\n  sqlite3_tokenizer_cursor *pCsr = 0;\n\n  const char *zErr = 0;\n\n  const char *zName;\n  int nName;\n  const char *zInput;\n  int nInput;\n\n  const char *azArg[64];\n\n  const char *zToken;\n  int nToken;\n  int iStart;\n  int iEnd;\n  int iPos;\n  int i;\n\n  Tcl_Obj *pRet;\n\n  if( argc<2 ){\n    sqlite3_result_error(context, \"insufficient arguments\", -1);\n    return;\n  }\n\n  nName = sqlite3_value_bytes(argv[0]);\n  zName = (const char *)sqlite3_value_text(argv[0]);\n  nInput = sqlite3_value_bytes(argv[argc-1]);\n  zInput = (const char *)sqlite3_value_text(argv[argc-1]);\n\n  pHash = (Fts3Hash *)sqlite3_user_data(context);\n  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);\n\n  if( !p ){\n    char *zErr = sqlite3_mprintf(\"unknown tokenizer: %s\", zName);\n    sqlite3_result_error(context, zErr, -1);\n    sqlite3_free(zErr);\n    return;\n  }\n\n  pRet = Tcl_NewObj();\n  Tcl_IncrRefCount(pRet);\n\n  for(i=1; i<argc-1; i++){\n    azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);\n  }\n\n  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){\n    zErr = \"error in xCreate()\";\n    goto finish;\n  }\n  pTokenizer->pModule = p;\n  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){\n    zErr = \"error in xOpen()\";\n    goto finish;\n  }\n\n  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));\n    zToken = &zInput[iStart];\n    nToken = iEnd-iStart;\n    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));\n  }\n\n  if( SQLITE_OK!=p->xClose(pCsr) ){\n    zErr = \"error in xClose()\";\n    goto finish;\n  }\n  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){\n    zErr = \"error in xDestroy()\";\n    goto finish;\n  }\n\nfinish:\n  if( zErr ){\n    sqlite3_result_error(context, zErr, -1);\n  }else{\n    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);\n  }\n  Tcl_DecrRefCount(pRet);\n}\n\nstatic\nint registerTokenizer(\n  sqlite3 *db, \n  char *zName, \n  const sqlite3_tokenizer_module *p\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char zSql[] = \"SELECT fts3_tokenizer(?, ?)\";\n\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);\n  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);\n  sqlite3_step(pStmt);\n\n  return sqlite3_finalize(pStmt);\n}\n\nstatic\nint queryTokenizer(\n  sqlite3 *db, \n  char *zName,  \n  const sqlite3_tokenizer_module **pp\n){\n  int rc;\n  sqlite3_stmt *pStmt;\n  const char zSql[] = \"SELECT fts3_tokenizer(?)\";\n\n  *pp = 0;\n  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){\n      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));\n    }\n  }\n\n  return sqlite3_finalize(pStmt);\n}\n\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);\n\n/*\n** Implementation of the scalar function fts3_tokenizer_internal_test().\n** This function is used for testing only, it is not included in the\n** build unless SQLITE_TEST is defined.\n**\n** The purpose of this is to test that the fts3_tokenizer() function\n** can be used as designed by the C-code in the queryTokenizer and\n** registerTokenizer() functions above. These two functions are repeated\n** in the README.tokenizer file as an example, so it is important to\n** test them.\n**\n** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar\n** function with no arguments. An assert() will fail if a problem is\n** detected. i.e.:\n**\n**     SELECT fts3_tokenizer_internal_test();\n**\n*/\nstatic void intTestFunc(\n  sqlite3_context *context,\n  int argc,\n  sqlite3_value **argv\n){\n  int rc;\n  const sqlite3_tokenizer_module *p1;\n  const sqlite3_tokenizer_module *p2;\n  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);\n\n  UNUSED_PARAMETER(argc);\n  UNUSED_PARAMETER(argv);\n\n  /* Test the query function */\n  sqlite3Fts3SimpleTokenizerModule(&p1);\n  rc = queryTokenizer(db, \"simple\", &p2);\n  assert( rc==SQLITE_OK );\n  assert( p1==p2 );\n  rc = queryTokenizer(db, \"nosuchtokenizer\", &p2);\n  assert( rc==SQLITE_ERROR );\n  assert( p2==0 );\n  assert( 0==strcmp(sqlite3_errmsg(db), \"unknown tokenizer: nosuchtokenizer\") );\n\n  /* Test the storage function */\n  rc = registerTokenizer(db, \"nosuchtokenizer\", p1);\n  assert( rc==SQLITE_OK );\n  rc = queryTokenizer(db, \"nosuchtokenizer\", &p2);\n  assert( rc==SQLITE_OK );\n  assert( p2==p1 );\n\n  sqlite3_result_text(context, \"ok\", -1, SQLITE_STATIC);\n}\n\n#endif\n\n/*\n** Set up SQL objects in database db used to access the contents of\n** the hash table pointed to by argument pHash. The hash table must\n** been initialised to use string keys, and to take a private copy \n** of the key when a value is inserted. i.e. by a call similar to:\n**\n**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);\n**\n** This function adds a scalar function (see header comment above\n** scalarFunc() in this file for details) and, if ENABLE_TABLE is\n** defined at compilation time, a temporary virtual table (see header \n** comment above struct HashTableVtab) to the database schema. Both \n** provide read/write access to the contents of *pHash.\n**\n** The third argument to this function, zName, is used as the name\n** of both the scalar and, if created, the virtual table.\n*/\nSQLITE_PRIVATE int sqlite3Fts3InitHashTable(\n  sqlite3 *db, \n  Fts3Hash *pHash, \n  const char *zName\n){\n  int rc = SQLITE_OK;\n  void *p = (void *)pHash;\n  const int any = SQLITE_ANY;\n\n#ifdef SQLITE_TEST\n  char *zTest = 0;\n  char *zTest2 = 0;\n  void *pdb = (void *)db;\n  zTest = sqlite3_mprintf(\"%s_test\", zName);\n  zTest2 = sqlite3_mprintf(\"%s_internal_test\", zName);\n  if( !zTest || !zTest2 ){\n    rc = SQLITE_NOMEM;\n  }\n#endif\n\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);\n  }\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);\n  }\n#ifdef SQLITE_TEST\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);\n  }\n  if( SQLITE_OK==rc ){\n    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);\n  }\n#endif\n\n#ifdef SQLITE_TEST\n  sqlite3_free(zTest);\n  sqlite3_free(zTest2);\n#endif\n\n  return rc;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_tokenizer.c **************************************/\n/************** Begin file fts3_tokenizer1.c *********************************/\n/*\n** 2006 Oct 10\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Implementation of the \"simple\" full-text-search tokenizer.\n*/\n\n/*\n** The code in this file is only compiled if:\n**\n**     * The FTS3 module is being built as an extension\n**       (in which case SQLITE_CORE is not defined), or\n**\n**     * The FTS3 module is being built into the core of\n**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n\ntypedef struct simple_tokenizer {\n  sqlite3_tokenizer base;\n  char delim[128];             /* flag ASCII delimiters */\n} simple_tokenizer;\n\ntypedef struct simple_tokenizer_cursor {\n  sqlite3_tokenizer_cursor base;\n  const char *pInput;          /* input we are tokenizing */\n  int nBytes;                  /* size of the input */\n  int iOffset;                 /* current position in pInput */\n  int iToken;                  /* index of next token to be returned */\n  char *pToken;                /* storage for current token */\n  int nTokenAllocated;         /* space allocated to zToken buffer */\n} simple_tokenizer_cursor;\n\n\nstatic int simpleDelim(simple_tokenizer *t, unsigned char c){\n  return c<0x80 && t->delim[c];\n}\nstatic int fts3_isalnum(int x){\n  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');\n}\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int simpleCreate(\n  int argc, const char * const *argv,\n  sqlite3_tokenizer **ppTokenizer\n){\n  simple_tokenizer *t;\n\n  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));\n  if( t==NULL ) return SQLITE_NOMEM;\n  memset(t, 0, sizeof(*t));\n\n  /* TODO(shess) Delimiters need to remain the same from run to run,\n  ** else we need to reindex.  One solution would be a meta-table to\n  ** track such information in the database, then we'd only want this\n  ** information on the initial create.\n  */\n  if( argc>1 ){\n    int i, n = (int)strlen(argv[1]);\n    for(i=0; i<n; i++){\n      unsigned char ch = argv[1][i];\n      /* We explicitly don't support UTF-8 delimiters for now. */\n      if( ch>=0x80 ){\n        sqlite3_free(t);\n        return SQLITE_ERROR;\n      }\n      t->delim[ch] = 1;\n    }\n  } else {\n    /* Mark non-alphanumeric ASCII characters as delimiters */\n    int i;\n    for(i=1; i<0x80; i++){\n      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;\n    }\n  }\n\n  *ppTokenizer = &t->base;\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int simpleDestroy(sqlite3_tokenizer *pTokenizer){\n  sqlite3_free(pTokenizer);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int simpleOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *pInput, int nBytes,        /* String to be tokenized */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  simple_tokenizer_cursor *c;\n\n  UNUSED_PARAMETER(pTokenizer);\n\n  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));\n  if( c==NULL ) return SQLITE_NOMEM;\n\n  c->pInput = pInput;\n  if( pInput==0 ){\n    c->nBytes = 0;\n  }else if( nBytes<0 ){\n    c->nBytes = (int)strlen(pInput);\n  }else{\n    c->nBytes = nBytes;\n  }\n  c->iOffset = 0;                 /* start tokenizing at the beginning */\n  c->iToken = 0;\n  c->pToken = NULL;               /* no space allocated, yet. */\n  c->nTokenAllocated = 0;\n\n  *ppCursor = &c->base;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** simpleOpen() above.\n*/\nstatic int simpleClose(sqlite3_tokenizer_cursor *pCursor){\n  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;\n  sqlite3_free(c->pToken);\n  sqlite3_free(c);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to simpleOpen().\n*/\nstatic int simpleNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */\n  const char **ppToken,               /* OUT: *ppToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;\n  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;\n  unsigned char *p = (unsigned char *)c->pInput;\n\n  while( c->iOffset<c->nBytes ){\n    int iStartOffset;\n\n    /* Scan past delimiter characters */\n    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    /* Count non-delimiter characters. */\n    iStartOffset = c->iOffset;\n    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){\n      c->iOffset++;\n    }\n\n    if( c->iOffset>iStartOffset ){\n      int i, n = c->iOffset-iStartOffset;\n      if( n>c->nTokenAllocated ){\n        char *pNew;\n        c->nTokenAllocated = n+20;\n        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);\n        if( !pNew ) return SQLITE_NOMEM;\n        c->pToken = pNew;\n      }\n      for(i=0; i<n; i++){\n        /* TODO(shess) This needs expansion to handle UTF-8\n        ** case-insensitivity.\n        */\n        unsigned char ch = p[iStartOffset+i];\n        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);\n      }\n      *ppToken = c->pToken;\n      *pnBytes = n;\n      *piStartOffset = iStartOffset;\n      *piEndOffset = c->iOffset;\n      *piPosition = c->iToken++;\n\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_DONE;\n}\n\n/*\n** The set of routines that implement the simple tokenizer\n*/\nstatic const sqlite3_tokenizer_module simpleTokenizerModule = {\n  0,\n  simpleCreate,\n  simpleDestroy,\n  simpleOpen,\n  simpleClose,\n  simpleNext,\n  0,\n};\n\n/*\n** Allocate a new simple tokenizer.  Return a pointer to the new\n** tokenizer in *ppModule\n*/\nSQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &simpleTokenizerModule;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_tokenizer1.c *************************************/\n/************** Begin file fts3_write.c **************************************/\n/*\n** 2009 Oct 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** This file is part of the SQLite FTS3 extension module. Specifically,\n** this file contains code to insert, update and delete rows from FTS3\n** tables. It also contains code to merge FTS3 b-tree segments. Some\n** of the sub-routines used to merge segments are also used by the query \n** code in fts3.c.\n*/\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n\n\n#define FTS_MAX_APPENDABLE_HEIGHT 16\n\n/*\n** When full-text index nodes are loaded from disk, the buffer that they\n** are loaded into has the following number of bytes of padding at the end \n** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer\n** of 920 bytes is allocated for it.\n**\n** This means that if we have a pointer into a buffer containing node data,\n** it is always safe to read up to two varints from it without risking an\n** overread, even if the node data is corrupted.\n*/\n#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)\n\n/*\n** Under certain circumstances, b-tree nodes (doclists) can be loaded into\n** memory incrementally instead of all at once. This can be a big performance\n** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()\n** method before retrieving all query results (as may happen, for example,\n** if a query has a LIMIT clause).\n**\n** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD \n** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.\n** The code is written so that the hard lower-limit for each of these values \n** is 1. Clearly such small values would be inefficient, but can be useful \n** for testing purposes.\n**\n** If this module is built with SQLITE_TEST defined, these constants may\n** be overridden at runtime for testing purposes. File fts3_test.c contains\n** a Tcl interface to read and write the values.\n*/\n#ifdef SQLITE_TEST\nint test_fts3_node_chunksize = (4*1024);\nint test_fts3_node_chunk_threshold = (4*1024)*4;\n# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize\n# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold\n#else\n# define FTS3_NODE_CHUNKSIZE (4*1024) \n# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)\n#endif\n\n/*\n** The two values that may be meaningfully bound to the :1 parameter in\n** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.\n*/\n#define FTS_STAT_DOCTOTAL      0\n#define FTS_STAT_INCRMERGEHINT 1\n#define FTS_STAT_AUTOINCRMERGE 2\n\n/*\n** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic\n** and incremental merge operation that takes place. This is used for \n** debugging FTS only, it should not usually be turned on in production\n** systems.\n*/\n#ifdef FTS3_LOG_MERGES\nstatic void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){\n  sqlite3_log(SQLITE_OK, \"%d-way merge from level %d\", nMerge, (int)iAbsLevel);\n}\n#else\n#define fts3LogMerge(x, y)\n#endif\n\n\ntypedef struct PendingList PendingList;\ntypedef struct SegmentNode SegmentNode;\ntypedef struct SegmentWriter SegmentWriter;\n\n/*\n** An instance of the following data structure is used to build doclists\n** incrementally. See function fts3PendingListAppend() for details.\n*/\nstruct PendingList {\n  int nData;\n  char *aData;\n  int nSpace;\n  sqlite3_int64 iLastDocid;\n  sqlite3_int64 iLastCol;\n  sqlite3_int64 iLastPos;\n};\n\n\n/*\n** Each cursor has a (possibly empty) linked list of the following objects.\n*/\nstruct Fts3DeferredToken {\n  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */\n  int iCol;                       /* Column token must occur in */\n  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */\n  PendingList *pList;             /* Doclist is assembled here */\n};\n\n/*\n** An instance of this structure is used to iterate through the terms on\n** a contiguous set of segment b-tree leaf nodes. Although the details of\n** this structure are only manipulated by code in this file, opaque handles\n** of type Fts3SegReader* are also used by code in fts3.c to iterate through\n** terms when querying the full-text index. See functions:\n**\n**   sqlite3Fts3SegReaderNew()\n**   sqlite3Fts3SegReaderFree()\n**   sqlite3Fts3SegReaderIterate()\n**\n** Methods used to manipulate Fts3SegReader structures:\n**\n**   fts3SegReaderNext()\n**   fts3SegReaderFirstDocid()\n**   fts3SegReaderNextDocid()\n*/\nstruct Fts3SegReader {\n  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */\n  u8 bLookup;                     /* True for a lookup only */\n  u8 rootOnly;                    /* True for a root-only reader */\n\n  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */\n  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */\n  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */\n  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */\n\n  char *aNode;                    /* Pointer to node data (or NULL) */\n  int nNode;                      /* Size of buffer at aNode (or 0) */\n  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */\n  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */\n\n  Fts3HashElem **ppNextElem;\n\n  /* Variables set by fts3SegReaderNext(). These may be read directly\n  ** by the caller. They are valid from the time SegmentReaderNew() returns\n  ** until SegmentReaderNext() returns something other than SQLITE_OK\n  ** (i.e. SQLITE_DONE).\n  */\n  int nTerm;                      /* Number of bytes in current term */\n  char *zTerm;                    /* Pointer to current term */\n  int nTermAlloc;                 /* Allocated size of zTerm buffer */\n  char *aDoclist;                 /* Pointer to doclist of current entry */\n  int nDoclist;                   /* Size of doclist in current entry */\n\n  /* The following variables are used by fts3SegReaderNextDocid() to iterate \n  ** through the current doclist (aDoclist/nDoclist).\n  */\n  char *pOffsetList;\n  int nOffsetList;                /* For descending pending seg-readers only */\n  sqlite3_int64 iDocid;\n};\n\n#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)\n#define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)\n\n/*\n** An instance of this structure is used to create a segment b-tree in the\n** database. The internal details of this type are only accessed by the\n** following functions:\n**\n**   fts3SegWriterAdd()\n**   fts3SegWriterFlush()\n**   fts3SegWriterFree()\n*/\nstruct SegmentWriter {\n  SegmentNode *pTree;             /* Pointer to interior tree structure */\n  sqlite3_int64 iFirst;           /* First slot in %_segments written */\n  sqlite3_int64 iFree;            /* Next free slot in %_segments */\n  char *zTerm;                    /* Pointer to previous term buffer */\n  int nTerm;                      /* Number of bytes in zTerm */\n  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */\n  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */\n  int nSize;                      /* Size of allocation at aData */\n  int nData;                      /* Bytes of data in aData */\n  char *aData;                    /* Pointer to block from malloc() */\n};\n\n/*\n** Type SegmentNode is used by the following three functions to create\n** the interior part of the segment b+-tree structures (everything except\n** the leaf nodes). These functions and type are only ever used by code\n** within the fts3SegWriterXXX() family of functions described above.\n**\n**   fts3NodeAddTerm()\n**   fts3NodeWrite()\n**   fts3NodeFree()\n**\n** When a b+tree is written to the database (either as a result of a merge\n** or the pending-terms table being flushed), leaves are written into the \n** database file as soon as they are completely populated. The interior of\n** the tree is assembled in memory and written out only once all leaves have\n** been populated and stored. This is Ok, as the b+-tree fanout is usually\n** very large, meaning that the interior of the tree consumes relatively \n** little memory.\n*/\nstruct SegmentNode {\n  SegmentNode *pParent;           /* Parent node (or NULL for root node) */\n  SegmentNode *pRight;            /* Pointer to right-sibling */\n  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */\n  int nEntry;                     /* Number of terms written to node so far */\n  char *zTerm;                    /* Pointer to previous term buffer */\n  int nTerm;                      /* Number of bytes in zTerm */\n  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */\n  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */\n  int nData;                      /* Bytes of valid data so far */\n  char *aData;                    /* Node data */\n};\n\n/*\n** Valid values for the second argument to fts3SqlStmt().\n*/\n#define SQL_DELETE_CONTENT             0\n#define SQL_IS_EMPTY                   1\n#define SQL_DELETE_ALL_CONTENT         2 \n#define SQL_DELETE_ALL_SEGMENTS        3\n#define SQL_DELETE_ALL_SEGDIR          4\n#define SQL_DELETE_ALL_DOCSIZE         5\n#define SQL_DELETE_ALL_STAT            6\n#define SQL_SELECT_CONTENT_BY_ROWID    7\n#define SQL_NEXT_SEGMENT_INDEX         8\n#define SQL_INSERT_SEGMENTS            9\n#define SQL_NEXT_SEGMENTS_ID          10\n#define SQL_INSERT_SEGDIR             11\n#define SQL_SELECT_LEVEL              12\n#define SQL_SELECT_LEVEL_RANGE        13\n#define SQL_SELECT_LEVEL_COUNT        14\n#define SQL_SELECT_SEGDIR_MAX_LEVEL   15\n#define SQL_DELETE_SEGDIR_LEVEL       16\n#define SQL_DELETE_SEGMENTS_RANGE     17\n#define SQL_CONTENT_INSERT            18\n#define SQL_DELETE_DOCSIZE            19\n#define SQL_REPLACE_DOCSIZE           20\n#define SQL_SELECT_DOCSIZE            21\n#define SQL_SELECT_STAT               22\n#define SQL_REPLACE_STAT              23\n\n#define SQL_SELECT_ALL_PREFIX_LEVEL   24\n#define SQL_DELETE_ALL_TERMS_SEGDIR   25\n#define SQL_DELETE_SEGDIR_RANGE       26\n#define SQL_SELECT_ALL_LANGID         27\n#define SQL_FIND_MERGE_LEVEL          28\n#define SQL_MAX_LEAF_NODE_ESTIMATE    29\n#define SQL_DELETE_SEGDIR_ENTRY       30\n#define SQL_SHIFT_SEGDIR_ENTRY        31\n#define SQL_SELECT_SEGDIR             32\n#define SQL_CHOMP_SEGDIR              33\n#define SQL_SEGMENT_IS_APPENDABLE     34\n#define SQL_SELECT_INDEXES            35\n#define SQL_SELECT_MXLEVEL            36\n\n/*\n** This function is used to obtain an SQLite prepared statement handle\n** for the statement identified by the second argument. If successful,\n** *pp is set to the requested statement handle and SQLITE_OK returned.\n** Otherwise, an SQLite error code is returned and *pp is set to 0.\n**\n** If argument apVal is not NULL, then it must point to an array with\n** at least as many entries as the requested statement has bound \n** parameters. The values are bound to the statements parameters before\n** returning.\n*/\nstatic int fts3SqlStmt(\n  Fts3Table *p,                   /* Virtual table handle */\n  int eStmt,                      /* One of the SQL_XXX constants above */\n  sqlite3_stmt **pp,              /* OUT: Statement handle */\n  sqlite3_value **apVal           /* Values to bind to statement */\n){\n  const char *azSql[] = {\n/* 0  */  \"DELETE FROM %Q.'%q_content' WHERE rowid = ?\",\n/* 1  */  \"SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)\",\n/* 2  */  \"DELETE FROM %Q.'%q_content'\",\n/* 3  */  \"DELETE FROM %Q.'%q_segments'\",\n/* 4  */  \"DELETE FROM %Q.'%q_segdir'\",\n/* 5  */  \"DELETE FROM %Q.'%q_docsize'\",\n/* 6  */  \"DELETE FROM %Q.'%q_stat'\",\n/* 7  */  \"SELECT %s WHERE rowid=?\",\n/* 8  */  \"SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1\",\n/* 9  */  \"REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)\",\n/* 10 */  \"SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)\",\n/* 11 */  \"REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)\",\n\n          /* Return segments in order from oldest to newest.*/ \n/* 12 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC\",\n/* 13 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\"\n            \"ORDER BY level DESC, idx ASC\",\n\n/* 14 */  \"SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?\",\n/* 15 */  \"SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\",\n\n/* 16 */  \"DELETE FROM %Q.'%q_segdir' WHERE level = ?\",\n/* 17 */  \"DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?\",\n/* 18 */  \"INSERT INTO %Q.'%q_content' VALUES(%s)\",\n/* 19 */  \"DELETE FROM %Q.'%q_docsize' WHERE docid = ?\",\n/* 20 */  \"REPLACE INTO %Q.'%q_docsize' VALUES(?,?)\",\n/* 21 */  \"SELECT size FROM %Q.'%q_docsize' WHERE docid=?\",\n/* 22 */  \"SELECT value FROM %Q.'%q_stat' WHERE id=?\",\n/* 23 */  \"REPLACE INTO %Q.'%q_stat' VALUES(?,?)\",\n/* 24 */  \"\",\n/* 25 */  \"\",\n\n/* 26 */ \"DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\",\n/* 27 */ \"SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'\",\n\n/* This statement is used to determine which level to read the input from\n** when performing an incremental merge. It returns the absolute level number\n** of the oldest level in the db that contains at least ? segments. Or,\n** if no level in the FTS index contains more than ? segments, the statement\n** returns zero rows.  */\n/* 28 */ \"SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?\"\n         \"  ORDER BY (level %% 1024) ASC LIMIT 1\",\n\n/* Estimate the upper limit on the number of leaf nodes in a new segment\n** created by merging the oldest :2 segments from absolute level :1. See \n** function sqlite3Fts3Incrmerge() for details.  */\n/* 29 */ \"SELECT 2 * total(1 + leaves_end_block - start_block) \"\n         \"  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?\",\n\n/* SQL_DELETE_SEGDIR_ENTRY\n**   Delete the %_segdir entry on absolute level :1 with index :2.  */\n/* 30 */ \"DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?\",\n\n/* SQL_SHIFT_SEGDIR_ENTRY\n**   Modify the idx value for the segment with idx=:3 on absolute level :2\n**   to :1.  */\n/* 31 */ \"UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?\",\n\n/* SQL_SELECT_SEGDIR\n**   Read a single entry from the %_segdir table. The entry from absolute \n**   level :1 with index value :2.  */\n/* 32 */  \"SELECT idx, start_block, leaves_end_block, end_block, root \"\n            \"FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?\",\n\n/* SQL_CHOMP_SEGDIR\n**   Update the start_block (:1) and root (:2) fields of the %_segdir\n**   entry located on absolute level :3 with index :4.  */\n/* 33 */  \"UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?\"\n            \"WHERE level = ? AND idx = ?\",\n\n/* SQL_SEGMENT_IS_APPENDABLE\n**   Return a single row if the segment with end_block=? is appendable. Or\n**   no rows otherwise.  */\n/* 34 */  \"SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL\",\n\n/* SQL_SELECT_INDEXES\n**   Return the list of valid segment indexes for absolute level ?  */\n/* 35 */  \"SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC\",\n\n/* SQL_SELECT_MXLEVEL\n**   Return the largest relative level in the FTS index or indexes.  */\n/* 36 */  \"SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'\"\n  };\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt;\n\n  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );\n  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );\n  \n  pStmt = p->aStmt[eStmt];\n  if( !pStmt ){\n    char *zSql;\n    if( eStmt==SQL_CONTENT_INSERT ){\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);\n    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);\n    }else{\n      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);\n    }\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);\n      sqlite3_free(zSql);\n      assert( rc==SQLITE_OK || pStmt==0 );\n      p->aStmt[eStmt] = pStmt;\n    }\n  }\n  if( apVal ){\n    int i;\n    int nParam = sqlite3_bind_parameter_count(pStmt);\n    for(i=0; rc==SQLITE_OK && i<nParam; i++){\n      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);\n    }\n  }\n  *pp = pStmt;\n  return rc;\n}\n\n\nstatic int fts3SelectDocsize(\n  Fts3Table *pTab,                /* FTS3 table handle */\n  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iDocid);\n    rc = sqlite3_step(pStmt);\n    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){\n      rc = sqlite3_reset(pStmt);\n      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;\n      pStmt = 0;\n    }else{\n      rc = SQLITE_OK;\n    }\n  }\n\n  *ppStmt = pStmt;\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(\n  Fts3Table *pTab,                /* Fts3 table handle */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  sqlite3_stmt *pStmt = 0;\n  int rc;\n  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n    if( sqlite3_step(pStmt)!=SQLITE_ROW\n     || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB\n    ){\n      rc = sqlite3_reset(pStmt);\n      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;\n      pStmt = 0;\n    }\n  }\n  *ppStmt = pStmt;\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SelectDocsize(\n  Fts3Table *pTab,                /* Fts3 table handle */\n  sqlite3_int64 iDocid,           /* Docid to read size data for */\n  sqlite3_stmt **ppStmt           /* OUT: Statement handle */\n){\n  return fts3SelectDocsize(pTab, iDocid, ppStmt);\n}\n\n/*\n** Similar to fts3SqlStmt(). Except, after binding the parameters in\n** array apVal[] to the SQL statement identified by eStmt, the statement\n** is executed.\n**\n** Returns SQLITE_OK if the statement is successfully executed, or an\n** SQLite error code otherwise.\n*/\nstatic void fts3SqlExec(\n  int *pRC,                /* Result code */\n  Fts3Table *p,            /* The FTS3 table */\n  int eStmt,               /* Index of statement to evaluate */\n  sqlite3_value **apVal    /* Parameters to bind */\n){\n  sqlite3_stmt *pStmt;\n  int rc;\n  if( *pRC ) return;\n  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); \n  if( rc==SQLITE_OK ){\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n  }\n  *pRC = rc;\n}\n\n\n/*\n** This function ensures that the caller has obtained a shared-cache\n** table-lock on the %_content table. This is required before reading\n** data from the fts3 table. If this lock is not acquired first, then\n** the caller may end up holding read-locks on the %_segments and %_segdir\n** tables, but no read-lock on the %_content table. If this happens \n** a second connection will be able to write to the fts3 table, but\n** attempting to commit those writes might return SQLITE_LOCKED or\n** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain \n** write-locks on the %_segments and %_segdir ** tables). \n**\n** We try to avoid this because if FTS3 returns any error when committing\n** a transaction, the whole transaction will be rolled back. And this is\n** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can\n** still happen if the user reads data directly from the %_segments or\n** %_segdir tables instead of going through FTS3 though.\n**\n** This reasoning does not apply to a content=xxx table.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pStmt;            /* Statement used to obtain lock */\n\n  if( p->zContentTbl==0 ){\n    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_null(pStmt, 1);\n      sqlite3_step(pStmt);\n      rc = sqlite3_reset(pStmt);\n    }\n  }else{\n    rc = SQLITE_OK;\n  }\n\n  return rc;\n}\n\n/*\n** FTS maintains a separate indexes for each language-id (a 32-bit integer).\n** Within each language id, a separate index is maintained to store the\n** document terms, and each configured prefix size (configured the FTS \n** \"prefix=\" option). And each index consists of multiple levels (\"relative\n** levels\").\n**\n** All three of these values (the language id, the specific index and the\n** level within the index) are encoded in 64-bit integer values stored\n** in the %_segdir table on disk. This function is used to convert three\n** separate component values into the single 64-bit integer value that\n** can be used to query the %_segdir table.\n**\n** Specifically, each language-id/index combination is allocated 1024 \n** 64-bit integer level values (\"absolute levels\"). The main terms index\n** for language-id 0 is allocate values 0-1023. The first prefix index\n** (if any) for language-id 0 is allocated values 1024-2047. And so on.\n** Language 1 indexes are allocated immediately following language 0.\n**\n** So, for a system with nPrefix prefix indexes configured, the block of\n** absolute levels that corresponds to language-id iLangid and index \n** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).\n*/\nstatic sqlite3_int64 getAbsoluteLevel(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index in p->aIndex[] */\n  int iLevel                      /* Level of segments */\n){\n  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */\n  assert( iLangid>=0 );\n  assert( p->nIndex>0 );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;\n  return iBase + iLevel;\n}\n\n/*\n** Set *ppStmt to a statement handle that may be used to iterate through\n** all rows in the %_segdir table, from oldest to newest. If successful,\n** return SQLITE_OK. If an error occurs while preparing the statement, \n** return an SQLite error code.\n**\n** There is only ever one instance of this SQL statement compiled for\n** each FTS3 table.\n**\n** The statement returns the following columns from the %_segdir table:\n**\n**   0: idx\n**   1: start_block\n**   2: leaves_end_block\n**   3: end_block\n**   4: root\n*/\nSQLITE_PRIVATE int sqlite3Fts3AllSegdirs(\n  Fts3Table *p,                   /* FTS3 table */\n  int iLangid,                    /* Language being queried */\n  int iIndex,                     /* Index for p->aIndex[] */\n  int iLevel,                     /* Level to select (relative level) */\n  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */\n){\n  int rc;\n  sqlite3_stmt *pStmt = 0;\n\n  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  if( iLevel<0 ){\n    /* \"SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ...\" */\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);\n    if( rc==SQLITE_OK ){ \n      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n      sqlite3_bind_int64(pStmt, 2, \n          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n      );\n    }\n  }else{\n    /* \"SELECT * FROM %_segdir WHERE level = ? ORDER BY ...\" */\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);\n    if( rc==SQLITE_OK ){ \n      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));\n    }\n  }\n  *ppStmt = pStmt;\n  return rc;\n}\n\n\n/*\n** Append a single varint to a PendingList buffer. SQLITE_OK is returned\n** if successful, or an SQLite error code otherwise.\n**\n** This function also serves to allocate the PendingList structure itself.\n** For example, to create a new PendingList structure containing two\n** varints:\n**\n**   PendingList *p = 0;\n**   fts3PendingListAppendVarint(&p, 1);\n**   fts3PendingListAppendVarint(&p, 2);\n*/\nstatic int fts3PendingListAppendVarint(\n  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */\n  sqlite3_int64 i                 /* Value to append to data */\n){\n  PendingList *p = *pp;\n\n  /* Allocate or grow the PendingList as required. */\n  if( !p ){\n    p = sqlite3_malloc(sizeof(*p) + 100);\n    if( !p ){\n      return SQLITE_NOMEM;\n    }\n    p->nSpace = 100;\n    p->aData = (char *)&p[1];\n    p->nData = 0;\n  }\n  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){\n    int nNew = p->nSpace * 2;\n    p = sqlite3_realloc(p, sizeof(*p) + nNew);\n    if( !p ){\n      sqlite3_free(*pp);\n      *pp = 0;\n      return SQLITE_NOMEM;\n    }\n    p->nSpace = nNew;\n    p->aData = (char *)&p[1];\n  }\n\n  /* Append the new serialized varint to the end of the list. */\n  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);\n  p->aData[p->nData] = '\\0';\n  *pp = p;\n  return SQLITE_OK;\n}\n\n/*\n** Add a docid/column/position entry to a PendingList structure. Non-zero\n** is returned if the structure is sqlite3_realloced as part of adding\n** the entry. Otherwise, zero.\n**\n** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.\n** Zero is always returned in this case. Otherwise, if no OOM error occurs,\n** it is set to SQLITE_OK.\n*/\nstatic int fts3PendingListAppend(\n  PendingList **pp,               /* IN/OUT: PendingList structure */\n  sqlite3_int64 iDocid,           /* Docid for entry to add */\n  sqlite3_int64 iCol,             /* Column for entry to add */\n  sqlite3_int64 iPos,             /* Position of term for entry to add */\n  int *pRc                        /* OUT: Return code */\n){\n  PendingList *p = *pp;\n  int rc = SQLITE_OK;\n\n  assert( !p || p->iLastDocid<=iDocid );\n\n  if( !p || p->iLastDocid!=iDocid ){\n    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);\n    if( p ){\n      assert( p->nData<p->nSpace );\n      assert( p->aData[p->nData]==0 );\n      p->nData++;\n    }\n    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){\n      goto pendinglistappend_out;\n    }\n    p->iLastCol = -1;\n    p->iLastPos = 0;\n    p->iLastDocid = iDocid;\n  }\n  if( iCol>0 && p->iLastCol!=iCol ){\n    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))\n     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))\n    ){\n      goto pendinglistappend_out;\n    }\n    p->iLastCol = iCol;\n    p->iLastPos = 0;\n  }\n  if( iCol>=0 ){\n    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );\n    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);\n    if( rc==SQLITE_OK ){\n      p->iLastPos = iPos;\n    }\n  }\n\n pendinglistappend_out:\n  *pRc = rc;\n  if( p!=*pp ){\n    *pp = p;\n    return 1;\n  }\n  return 0;\n}\n\n/*\n** Free a PendingList object allocated by fts3PendingListAppend().\n*/\nstatic void fts3PendingListDelete(PendingList *pList){\n  sqlite3_free(pList);\n}\n\n/*\n** Add an entry to one of the pending-terms hash tables.\n*/\nstatic int fts3PendingTermsAddOne(\n  Fts3Table *p,\n  int iCol,\n  int iPos,\n  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */\n  const char *zToken,\n  int nToken\n){\n  PendingList *pList;\n  int rc = SQLITE_OK;\n\n  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);\n  if( pList ){\n    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));\n  }\n  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){\n    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){\n      /* Malloc failed while inserting the new entry. This can only \n      ** happen if there was no previous entry for this token.\n      */\n      assert( 0==fts3HashFind(pHash, zToken, nToken) );\n      sqlite3_free(pList);\n      rc = SQLITE_NOMEM;\n    }\n  }\n  if( rc==SQLITE_OK ){\n    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));\n  }\n  return rc;\n}\n\n/*\n** Tokenize the nul-terminated string zText and add all tokens to the\n** pending-terms hash-table. The docid used is that currently stored in\n** p->iPrevDocid, and the column is specified by argument iCol.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3PendingTermsAdd(\n  Fts3Table *p,                   /* Table into which text will be inserted */\n  int iLangid,                    /* Language id to use */\n  const char *zText,              /* Text of document to be inserted */\n  int iCol,                       /* Column into which text is being inserted */\n  u32 *pnWord                     /* OUT: Number of tokens inserted */\n){\n  int rc;\n  int iStart;\n  int iEnd;\n  int iPos;\n  int nWord = 0;\n\n  char const *zToken;\n  int nToken;\n\n  sqlite3_tokenizer *pTokenizer = p->pTokenizer;\n  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;\n  sqlite3_tokenizer_cursor *pCsr;\n  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,\n      const char**,int*,int*,int*,int*);\n\n  assert( pTokenizer && pModule );\n\n  /* If the user has inserted a NULL value, this function may be called with\n  ** zText==0. In this case, add zero token entries to the hash table and \n  ** return early. */\n  if( zText==0 ){\n    *pnWord = 0;\n    return SQLITE_OK;\n  }\n\n  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  xNext = pModule->xNext;\n  while( SQLITE_OK==rc\n      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))\n  ){\n    int i;\n    if( iPos>=nWord ) nWord = iPos+1;\n\n    /* Positions cannot be negative; we use -1 as a terminator internally.\n    ** Tokens must have a non-zero length.\n    */\n    if( iPos<0 || !zToken || nToken<=0 ){\n      rc = SQLITE_ERROR;\n      break;\n    }\n\n    /* Add the term to the terms index */\n    rc = fts3PendingTermsAddOne(\n        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken\n    );\n    \n    /* Add the term to each of the prefix indexes that it is not too \n    ** short for. */\n    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){\n      struct Fts3Index *pIndex = &p->aIndex[i];\n      if( nToken<pIndex->nPrefix ) continue;\n      rc = fts3PendingTermsAddOne(\n          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix\n      );\n    }\n  }\n\n  pModule->xClose(pCsr);\n  *pnWord = nWord;\n  return (rc==SQLITE_DONE ? SQLITE_OK : rc);\n}\n\n/* \n** Calling this function indicates that subsequent calls to \n** fts3PendingTermsAdd() are to add term/position-list pairs for the\n** contents of the document with docid iDocid.\n*/\nstatic int fts3PendingTermsDocid(\n  Fts3Table *p,                   /* Full-text table handle */\n  int iLangid,                    /* Language id of row being written */\n  sqlite_int64 iDocid             /* Docid of row being written */\n){\n  assert( iLangid>=0 );\n\n  /* TODO(shess) Explore whether partially flushing the buffer on\n  ** forced-flush would provide better performance.  I suspect that if\n  ** we ordered the doclists by size and flushed the largest until the\n  ** buffer was half empty, that would let the less frequent terms\n  ** generate longer doclists.\n  */\n  if( iDocid<=p->iPrevDocid \n   || p->iPrevLangid!=iLangid\n   || p->nPendingData>p->nMaxPendingData \n  ){\n    int rc = sqlite3Fts3PendingTermsFlush(p);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  p->iPrevDocid = iDocid;\n  p->iPrevLangid = iLangid;\n  return SQLITE_OK;\n}\n\n/*\n** Discard the contents of the pending-terms hash tables. \n*/\nSQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){\n  int i;\n  for(i=0; i<p->nIndex; i++){\n    Fts3HashElem *pElem;\n    Fts3Hash *pHash = &p->aIndex[i].hPending;\n    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){\n      PendingList *pList = (PendingList *)fts3HashData(pElem);\n      fts3PendingListDelete(pList);\n    }\n    fts3HashClear(pHash);\n  }\n  p->nPendingData = 0;\n}\n\n/*\n** This function is called by the xUpdate() method as part of an INSERT\n** operation. It adds entries for each term in the new record to the\n** pendingTerms hash table.\n**\n** Argument apVal is the same as the similarly named argument passed to\n** fts3InsertData(). Parameter iDocid is the docid of the new row.\n*/\nstatic int fts3InsertTerms(\n  Fts3Table *p, \n  int iLangid, \n  sqlite3_value **apVal, \n  u32 *aSz\n){\n  int i;                          /* Iterator variable */\n  for(i=2; i<p->nColumn+2; i++){\n    const char *zText = (const char *)sqlite3_value_text(apVal[i]);\n    int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n    aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** This function is called by the xUpdate() method for an INSERT operation.\n** The apVal parameter is passed a copy of the apVal argument passed by\n** SQLite to the xUpdate() method. i.e:\n**\n**   apVal[0]                Not used for INSERT.\n**   apVal[1]                rowid\n**   apVal[2]                Left-most user-defined column\n**   ...\n**   apVal[p->nColumn+1]     Right-most user-defined column\n**   apVal[p->nColumn+2]     Hidden column with same name as table\n**   apVal[p->nColumn+3]     Hidden \"docid\" column (alias for rowid)\n**   apVal[p->nColumn+4]     Hidden languageid column\n*/\nstatic int fts3InsertData(\n  Fts3Table *p,                   /* Full-text table */\n  sqlite3_value **apVal,          /* Array of values to insert */\n  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */\n\n  if( p->zContentTbl ){\n    sqlite3_value *pRowid = apVal[p->nColumn+3];\n    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){\n      pRowid = apVal[1];\n    }\n    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){\n      return SQLITE_CONSTRAINT;\n    }\n    *piDocid = sqlite3_value_int64(pRowid);\n    return SQLITE_OK;\n  }\n\n  /* Locate the statement handle used to insert data into the %_content\n  ** table. The SQL for this statement is:\n  **\n  **   INSERT INTO %_content VALUES(?, ?, ?, ...)\n  **\n  ** The statement features N '?' variables, where N is the number of user\n  ** defined columns in the FTS3 table, plus one for the docid field.\n  */\n  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);\n  if( rc==SQLITE_OK && p->zLanguageid ){\n    rc = sqlite3_bind_int(\n        pContentInsert, p->nColumn+2, \n        sqlite3_value_int(apVal[p->nColumn+4])\n    );\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* There is a quirk here. The users INSERT statement may have specified\n  ** a value for the \"rowid\" field, for the \"docid\" field, or for both.\n  ** Which is a problem, since \"rowid\" and \"docid\" are aliases for the\n  ** same value. For example:\n  **\n  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);\n  **\n  ** In FTS3, this is an error. It is an error to specify non-NULL values\n  ** for both docid and some other rowid alias.\n  */\n  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){\n    if( SQLITE_NULL==sqlite3_value_type(apVal[0])\n     && SQLITE_NULL!=sqlite3_value_type(apVal[1])\n    ){\n      /* A rowid/docid conflict. */\n      return SQLITE_ERROR;\n    }\n    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n\n  /* Execute the statement to insert the record. Set *piDocid to the \n  ** new docid value. \n  */\n  sqlite3_step(pContentInsert);\n  rc = sqlite3_reset(pContentInsert);\n\n  *piDocid = sqlite3_last_insert_rowid(p->db);\n  return rc;\n}\n\n\n\n/*\n** Remove all data from the FTS3 table. Clear the hash table containing\n** pending terms.\n*/\nstatic int fts3DeleteAll(Fts3Table *p, int bContent){\n  int rc = SQLITE_OK;             /* Return code */\n\n  /* Discard the contents of the pending-terms hash table. */\n  sqlite3Fts3PendingTermsClear(p);\n\n  /* Delete everything from the shadow tables. Except, leave %_content as\n  ** is if bContent is false.  */\n  assert( p->zContentTbl==0 || bContent==0 );\n  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);\n  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);\n  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);\n  if( p->bHasDocsize ){\n    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);\n  }\n  if( p->bHasStat ){\n    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);\n  }\n  return rc;\n}\n\n/*\n**\n*/\nstatic int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){\n  int iLangid = 0;\n  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);\n  return iLangid;\n}\n\n/*\n** The first element in the apVal[] array is assumed to contain the docid\n** (an integer) of a row about to be deleted. Remove all terms from the\n** full-text index.\n*/\nstatic void fts3DeleteTerms( \n  int *pRC,               /* Result code */\n  Fts3Table *p,           /* The FTS table to delete from */\n  sqlite3_value *pRowid,  /* The docid to be deleted */\n  u32 *aSz                /* Sizes of deleted document written here */\n){\n  int rc;\n  sqlite3_stmt *pSelect;\n\n  if( *pRC ) return;\n  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pSelect) ){\n      int i;\n      int iLangid = langidFromSelect(p, pSelect);\n      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));\n      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){\n        const char *zText = (const char *)sqlite3_column_text(pSelect, i);\n        rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);\n        aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);\n      }\n      if( rc!=SQLITE_OK ){\n        sqlite3_reset(pSelect);\n        *pRC = rc;\n        return;\n      }\n    }\n    rc = sqlite3_reset(pSelect);\n  }else{\n    sqlite3_reset(pSelect);\n  }\n  *pRC = rc;\n}\n\n/*\n** Forward declaration to account for the circular dependency between\n** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().\n*/\nstatic int fts3SegmentMerge(Fts3Table *, int, int, int);\n\n/* \n** This function allocates a new level iLevel index in the segdir table.\n** Usually, indexes are allocated within a level sequentially starting\n** with 0, so the allocated index is one greater than the value returned\n** by:\n**\n**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel\n**\n** However, if there are already FTS3_MERGE_COUNT indexes at the requested\n** level, they are merged into a single level (iLevel+1) segment and the \n** allocated index is 0.\n**\n** If successful, *piIdx is set to the allocated index slot and SQLITE_OK\n** returned. Otherwise, an SQLite error code is returned.\n*/\nstatic int fts3AllocateSegdirIdx(\n  Fts3Table *p, \n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index for p->aIndex */\n  int iLevel, \n  int *piIdx\n){\n  int rc;                         /* Return Code */\n  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */\n  int iNext = 0;                  /* Result of query pNextIdx */\n\n  assert( iLangid>=0 );\n  assert( p->nIndex>=1 );\n\n  /* Set variable iNext to the next available segdir index at level iLevel. */\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(\n        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)\n    );\n    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){\n      iNext = sqlite3_column_int(pNextIdx, 0);\n    }\n    rc = sqlite3_reset(pNextIdx);\n  }\n\n  if( rc==SQLITE_OK ){\n    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already\n    ** full, merge all segments in level iLevel into a single iLevel+1\n    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,\n    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.\n    */\n    if( iNext>=FTS3_MERGE_COUNT ){\n      fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));\n      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);\n      *piIdx = 0;\n    }else{\n      *piIdx = iNext;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** The %_segments table is declared as follows:\n**\n**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)\n**\n** This function reads data from a single row of the %_segments table. The\n** specific row is identified by the iBlockid parameter. If paBlob is not\n** NULL, then a buffer is allocated using sqlite3_malloc() and populated\n** with the contents of the blob stored in the \"block\" column of the \n** identified table row is. Whether or not paBlob is NULL, *pnBlob is set\n** to the size of the blob in bytes before returning.\n**\n** If an error occurs, or the table does not contain the specified row,\n** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If\n** paBlob is non-NULL, then it is the responsibility of the caller to\n** eventually free the returned buffer.\n**\n** This function may leave an open sqlite3_blob* handle in the\n** Fts3Table.pSegments variable. This handle is reused by subsequent calls\n** to this function. The handle may be closed by calling the\n** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy\n** performance improvement, but the blob handle should always be closed\n** before control is returned to the user (to prevent a lock being held\n** on the database file for longer than necessary). Thus, any virtual table\n** method (xFilter etc.) that may directly or indirectly call this function\n** must call sqlite3Fts3SegmentsClose() before returning.\n*/\nSQLITE_PRIVATE int sqlite3Fts3ReadBlock(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */\n  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */\n  int *pnBlob,                    /* OUT: Size of blob data */\n  int *pnLoad                     /* OUT: Bytes actually loaded */\n){\n  int rc;                         /* Return code */\n\n  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */\n  assert( pnBlob );\n\n  if( p->pSegments ){\n    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);\n  }else{\n    if( 0==p->zSegmentsTbl ){\n      p->zSegmentsTbl = sqlite3_mprintf(\"%s_segments\", p->zName);\n      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;\n    }\n    rc = sqlite3_blob_open(\n       p->db, p->zDb, p->zSegmentsTbl, \"block\", iBlockid, 0, &p->pSegments\n    );\n  }\n\n  if( rc==SQLITE_OK ){\n    int nByte = sqlite3_blob_bytes(p->pSegments);\n    *pnBlob = nByte;\n    if( paBlob ){\n      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);\n      if( !aByte ){\n        rc = SQLITE_NOMEM;\n      }else{\n        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){\n          nByte = FTS3_NODE_CHUNKSIZE;\n          *pnLoad = nByte;\n        }\n        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);\n        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);\n        if( rc!=SQLITE_OK ){\n          sqlite3_free(aByte);\n          aByte = 0;\n        }\n      }\n      *paBlob = aByte;\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Close the blob handle at p->pSegments, if it is open. See comments above\n** the sqlite3Fts3ReadBlock() function for details.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){\n  sqlite3_blob_close(p->pSegments);\n  p->pSegments = 0;\n}\n    \nstatic int fts3SegReaderIncrRead(Fts3SegReader *pReader){\n  int nRead;                      /* Number of bytes to read */\n  int rc;                         /* Return code */\n\n  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);\n  rc = sqlite3_blob_read(\n      pReader->pBlob, \n      &pReader->aNode[pReader->nPopulate],\n      nRead,\n      pReader->nPopulate\n  );\n\n  if( rc==SQLITE_OK ){\n    pReader->nPopulate += nRead;\n    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);\n    if( pReader->nPopulate==pReader->nNode ){\n      sqlite3_blob_close(pReader->pBlob);\n      pReader->pBlob = 0;\n      pReader->nPopulate = 0;\n    }\n  }\n  return rc;\n}\n\nstatic int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){\n  int rc = SQLITE_OK;\n  assert( !pReader->pBlob \n       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])\n  );\n  while( pReader->pBlob && rc==SQLITE_OK \n     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate\n  ){\n    rc = fts3SegReaderIncrRead(pReader);\n  }\n  return rc;\n}\n\n/*\n** Set an Fts3SegReader cursor to point at EOF.\n*/\nstatic void fts3SegReaderSetEof(Fts3SegReader *pSeg){\n  if( !fts3SegReaderIsRootOnly(pSeg) ){\n    sqlite3_free(pSeg->aNode);\n    sqlite3_blob_close(pSeg->pBlob);\n    pSeg->pBlob = 0;\n  }\n  pSeg->aNode = 0;\n}\n\n/*\n** Move the iterator passed as the first argument to the next term in the\n** segment. If successful, SQLITE_OK is returned. If there is no next term,\n** SQLITE_DONE. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegReaderNext(\n  Fts3Table *p, \n  Fts3SegReader *pReader,\n  int bIncr\n){\n  int rc;                         /* Return code of various sub-routines */\n  char *pNext;                    /* Cursor variable */\n  int nPrefix;                    /* Number of bytes in term prefix */\n  int nSuffix;                    /* Number of bytes in term suffix */\n\n  if( !pReader->aDoclist ){\n    pNext = pReader->aNode;\n  }else{\n    pNext = &pReader->aDoclist[pReader->nDoclist];\n  }\n\n  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){\n\n    if( fts3SegReaderIsPending(pReader) ){\n      Fts3HashElem *pElem = *(pReader->ppNextElem);\n      if( pElem==0 ){\n        pReader->aNode = 0;\n      }else{\n        PendingList *pList = (PendingList *)fts3HashData(pElem);\n        pReader->zTerm = (char *)fts3HashKey(pElem);\n        pReader->nTerm = fts3HashKeysize(pElem);\n        pReader->nNode = pReader->nDoclist = pList->nData + 1;\n        pReader->aNode = pReader->aDoclist = pList->aData;\n        pReader->ppNextElem++;\n        assert( pReader->aNode );\n      }\n      return SQLITE_OK;\n    }\n\n    fts3SegReaderSetEof(pReader);\n\n    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf \n    ** blocks have already been traversed.  */\n    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );\n    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){\n      return SQLITE_OK;\n    }\n\n    rc = sqlite3Fts3ReadBlock(\n        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, \n        (bIncr ? &pReader->nPopulate : 0)\n    );\n    if( rc!=SQLITE_OK ) return rc;\n    assert( pReader->pBlob==0 );\n    if( bIncr && pReader->nPopulate<pReader->nNode ){\n      pReader->pBlob = p->pSegments;\n      p->pSegments = 0;\n    }\n    pNext = pReader->aNode;\n  }\n\n  assert( !fts3SegReaderIsPending(pReader) );\n\n  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);\n  if( rc!=SQLITE_OK ) return rc;\n  \n  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is \n  ** safe (no risk of overread) even if the node data is corrupted. */\n  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);\n  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);\n  if( nPrefix<0 || nSuffix<=0 \n   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] \n  ){\n    return FTS_CORRUPT_VTAB;\n  }\n\n  if( nPrefix+nSuffix>pReader->nTermAlloc ){\n    int nNew = (nPrefix+nSuffix)*2;\n    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);\n    if( !zNew ){\n      return SQLITE_NOMEM;\n    }\n    pReader->zTerm = zNew;\n    pReader->nTermAlloc = nNew;\n  }\n\n  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);\n  if( rc!=SQLITE_OK ) return rc;\n\n  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);\n  pReader->nTerm = nPrefix+nSuffix;\n  pNext += nSuffix;\n  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);\n  pReader->aDoclist = pNext;\n  pReader->pOffsetList = 0;\n\n  /* Check that the doclist does not appear to extend past the end of the\n  ** b-tree node. And that the final byte of the doclist is 0x00. If either \n  ** of these statements is untrue, then the data structure is corrupt.\n  */\n  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] \n   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])\n  ){\n    return FTS_CORRUPT_VTAB;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Set the SegReader to point to the first docid in the doclist associated\n** with the current term.\n*/\nstatic int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){\n  int rc = SQLITE_OK;\n  assert( pReader->aDoclist );\n  assert( !pReader->pOffsetList );\n  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){\n    u8 bEof = 0;\n    pReader->iDocid = 0;\n    pReader->nOffsetList = 0;\n    sqlite3Fts3DoclistPrev(0,\n        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, \n        &pReader->iDocid, &pReader->nOffsetList, &bEof\n    );\n  }else{\n    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);\n    if( rc==SQLITE_OK ){\n      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);\n      pReader->pOffsetList = &pReader->aDoclist[n];\n    }\n  }\n  return rc;\n}\n\n/*\n** Advance the SegReader to point to the next docid in the doclist\n** associated with the current term.\n** \n** If arguments ppOffsetList and pnOffsetList are not NULL, then \n** *ppOffsetList is set to point to the first column-offset list\n** in the doclist entry (i.e. immediately past the docid varint).\n** *pnOffsetList is set to the length of the set of column-offset\n** lists, not including the nul-terminator byte. For example:\n*/\nstatic int fts3SegReaderNextDocid(\n  Fts3Table *pTab,\n  Fts3SegReader *pReader,         /* Reader to advance to next docid */\n  char **ppOffsetList,            /* OUT: Pointer to current position-list */\n  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */\n){\n  int rc = SQLITE_OK;\n  char *p = pReader->pOffsetList;\n  char c = 0;\n\n  assert( p );\n\n  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){\n    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.\n    ** Pending-terms doclists are always built up in ascending order, so\n    ** we have to iterate through them backwards here. */\n    u8 bEof = 0;\n    if( ppOffsetList ){\n      *ppOffsetList = pReader->pOffsetList;\n      *pnOffsetList = pReader->nOffsetList - 1;\n    }\n    sqlite3Fts3DoclistPrev(0,\n        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,\n        &pReader->nOffsetList, &bEof\n    );\n    if( bEof ){\n      pReader->pOffsetList = 0;\n    }else{\n      pReader->pOffsetList = p;\n    }\n  }else{\n    char *pEnd = &pReader->aDoclist[pReader->nDoclist];\n\n    /* Pointer p currently points at the first byte of an offset list. The\n    ** following block advances it to point one byte past the end of\n    ** the same offset list. */\n    while( 1 ){\n  \n      /* The following line of code (and the \"p++\" below the while() loop) is\n      ** normally all that is required to move pointer p to the desired \n      ** position. The exception is if this node is being loaded from disk\n      ** incrementally and pointer \"p\" now points to the first byte passed\n      ** the populated part of pReader->aNode[].\n      */\n      while( *p | c ) c = *p++ & 0x80;\n      assert( *p==0 );\n  \n      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;\n      rc = fts3SegReaderIncrRead(pReader);\n      if( rc!=SQLITE_OK ) return rc;\n    }\n    p++;\n  \n    /* If required, populate the output variables with a pointer to and the\n    ** size of the previous offset-list.\n    */\n    if( ppOffsetList ){\n      *ppOffsetList = pReader->pOffsetList;\n      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);\n    }\n\n    while( p<pEnd && *p==0 ) p++;\n  \n    /* If there are no more entries in the doclist, set pOffsetList to\n    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and\n    ** Fts3SegReader.pOffsetList to point to the next offset list before\n    ** returning.\n    */\n    if( p>=pEnd ){\n      pReader->pOffsetList = 0;\n    }else{\n      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);\n      if( rc==SQLITE_OK ){\n        sqlite3_int64 iDelta;\n        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);\n        if( pTab->bDescIdx ){\n          pReader->iDocid -= iDelta;\n        }else{\n          pReader->iDocid += iDelta;\n        }\n      }\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n\nSQLITE_PRIVATE int sqlite3Fts3MsrOvfl(\n  Fts3Cursor *pCsr, \n  Fts3MultiSegReader *pMsr,\n  int *pnOvfl\n){\n  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;\n  int nOvfl = 0;\n  int ii;\n  int rc = SQLITE_OK;\n  int pgsz = p->nPgsz;\n\n  assert( p->bFts4 );\n  assert( pgsz>0 );\n\n  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){\n    Fts3SegReader *pReader = pMsr->apSegment[ii];\n    if( !fts3SegReaderIsPending(pReader) \n     && !fts3SegReaderIsRootOnly(pReader) \n    ){\n      sqlite3_int64 jj;\n      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){\n        int nBlob;\n        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);\n        if( rc!=SQLITE_OK ) break;\n        if( (nBlob+35)>pgsz ){\n          nOvfl += (nBlob + 34)/pgsz;\n        }\n      }\n    }\n  }\n  *pnOvfl = nOvfl;\n  return rc;\n}\n\n/*\n** Free all allocations associated with the iterator passed as the \n** second argument.\n*/\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){\n  if( pReader && !fts3SegReaderIsPending(pReader) ){\n    sqlite3_free(pReader->zTerm);\n    if( !fts3SegReaderIsRootOnly(pReader) ){\n      sqlite3_free(pReader->aNode);\n      sqlite3_blob_close(pReader->pBlob);\n    }\n  }\n  sqlite3_free(pReader);\n}\n\n/*\n** Allocate a new SegReader object.\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderNew(\n  int iAge,                       /* Segment \"age\". */\n  int bLookup,                    /* True for a lookup only */\n  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */\n  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */\n  sqlite3_int64 iEndBlock,        /* Final block of segment */\n  const char *zRoot,              /* Buffer containing root node */\n  int nRoot,                      /* Size of buffer containing root node */\n  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */\n){\n  Fts3SegReader *pReader;         /* Newly allocated SegReader object */\n  int nExtra = 0;                 /* Bytes to allocate segment root node */\n\n  assert( iStartLeaf<=iEndLeaf );\n  if( iStartLeaf==0 ){\n    nExtra = nRoot + FTS3_NODE_PADDING;\n  }\n\n  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);\n  if( !pReader ){\n    return SQLITE_NOMEM;\n  }\n  memset(pReader, 0, sizeof(Fts3SegReader));\n  pReader->iIdx = iAge;\n  pReader->bLookup = bLookup!=0;\n  pReader->iStartBlock = iStartLeaf;\n  pReader->iLeafEndBlock = iEndLeaf;\n  pReader->iEndBlock = iEndBlock;\n\n  if( nExtra ){\n    /* The entire segment is stored in the root node. */\n    pReader->aNode = (char *)&pReader[1];\n    pReader->rootOnly = 1;\n    pReader->nNode = nRoot;\n    memcpy(pReader->aNode, zRoot, nRoot);\n    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);\n  }else{\n    pReader->iCurrentBlock = iStartLeaf-1;\n  }\n  *ppReader = pReader;\n  return SQLITE_OK;\n}\n\n/*\n** This is a comparison function used as a qsort() callback when sorting\n** an array of pending terms by term. This occurs as part of flushing\n** the contents of the pending-terms hash table to the database.\n*/\nstatic int fts3CompareElemByTerm(const void *lhs, const void *rhs){\n  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);\n  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);\n  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);\n  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);\n\n  int n = (n1<n2 ? n1 : n2);\n  int c = memcmp(z1, z2, n);\n  if( c==0 ){\n    c = n1 - n2;\n  }\n  return c;\n}\n\n/*\n** This function is used to allocate an Fts3SegReader that iterates through\n** a subset of the terms stored in the Fts3Table.pendingTerms array.\n**\n** If the isPrefixIter parameter is zero, then the returned SegReader iterates\n** through each term in the pending-terms table. Or, if isPrefixIter is\n** non-zero, it iterates through each term and its prefixes. For example, if\n** the pending terms hash table contains the terms \"sqlite\", \"mysql\" and\n** \"firebird\", then the iterator visits the following 'terms' (in the order\n** shown):\n**\n**   f fi fir fire fireb firebi firebir firebird\n**   m my mys mysq mysql\n**   s sq sql sqli sqlit sqlite\n**\n** Whereas if isPrefixIter is zero, the terms visited are:\n**\n**   firebird mysql sqlite\n*/\nSQLITE_PRIVATE int sqlite3Fts3SegReaderPending(\n  Fts3Table *p,                   /* Virtual table handle */\n  int iIndex,                     /* Index for p->aIndex */\n  const char *zTerm,              /* Term to search for */\n  int nTerm,                      /* Size of buffer zTerm */\n  int bPrefix,                    /* True for a prefix iterator */\n  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */\n){\n  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */\n  Fts3HashElem *pE;               /* Iterator variable */\n  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */\n  int nElem = 0;                  /* Size of array at aElem */\n  int rc = SQLITE_OK;             /* Return Code */\n  Fts3Hash *pHash;\n\n  pHash = &p->aIndex[iIndex].hPending;\n  if( bPrefix ){\n    int nAlloc = 0;               /* Size of allocated array at aElem */\n\n    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){\n      char *zKey = (char *)fts3HashKey(pE);\n      int nKey = fts3HashKeysize(pE);\n      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){\n        if( nElem==nAlloc ){\n          Fts3HashElem **aElem2;\n          nAlloc += 16;\n          aElem2 = (Fts3HashElem **)sqlite3_realloc(\n              aElem, nAlloc*sizeof(Fts3HashElem *)\n          );\n          if( !aElem2 ){\n            rc = SQLITE_NOMEM;\n            nElem = 0;\n            break;\n          }\n          aElem = aElem2;\n        }\n\n        aElem[nElem++] = pE;\n      }\n    }\n\n    /* If more than one term matches the prefix, sort the Fts3HashElem\n    ** objects in term order using qsort(). This uses the same comparison\n    ** callback as is used when flushing terms to disk.\n    */\n    if( nElem>1 ){\n      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);\n    }\n\n  }else{\n    /* The query is a simple term lookup that matches at most one term in\n    ** the index. All that is required is a straight hash-lookup. \n    **\n    ** Because the stack address of pE may be accessed via the aElem pointer\n    ** below, the \"Fts3HashElem *pE\" must be declared so that it is valid\n    ** within this entire function, not just this \"else{...}\" block.\n    */\n    pE = fts3HashFindElem(pHash, zTerm, nTerm);\n    if( pE ){\n      aElem = &pE;\n      nElem = 1;\n    }\n  }\n\n  if( nElem>0 ){\n    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);\n    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);\n    if( !pReader ){\n      rc = SQLITE_NOMEM;\n    }else{\n      memset(pReader, 0, nByte);\n      pReader->iIdx = 0x7FFFFFFF;\n      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];\n      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));\n    }\n  }\n\n  if( bPrefix ){\n    sqlite3_free(aElem);\n  }\n  *ppReader = pReader;\n  return rc;\n}\n\n/*\n** Compare the entries pointed to by two Fts3SegReader structures. \n** Comparison is as follows:\n**\n**   1) EOF is greater than not EOF.\n**\n**   2) The current terms (if any) are compared using memcmp(). If one\n**      term is a prefix of another, the longer term is considered the\n**      larger.\n**\n**   3) By segment age. An older segment is considered larger.\n*/\nstatic int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc;\n  if( pLhs->aNode && pRhs->aNode ){\n    int rc2 = pLhs->nTerm - pRhs->nTerm;\n    if( rc2<0 ){\n      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);\n    }else{\n      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);\n    }\n    if( rc==0 ){\n      rc = rc2;\n    }\n  }else{\n    rc = (pLhs->aNode==0) - (pRhs->aNode==0);\n  }\n  if( rc==0 ){\n    rc = pRhs->iIdx - pLhs->iIdx;\n  }\n  assert( rc!=0 );\n  return rc;\n}\n\n/*\n** A different comparison function for SegReader structures. In this\n** version, it is assumed that each SegReader points to an entry in\n** a doclist for identical terms. Comparison is made as follows:\n**\n**   1) EOF (end of doclist in this case) is greater than not EOF.\n**\n**   2) By current docid.\n**\n**   3) By segment age. An older segment is considered larger.\n*/\nstatic int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);\n  if( rc==0 ){\n    if( pLhs->iDocid==pRhs->iDocid ){\n      rc = pRhs->iIdx - pLhs->iIdx;\n    }else{\n      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;\n    }\n  }\n  assert( pLhs->aNode && pRhs->aNode );\n  return rc;\n}\nstatic int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){\n  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);\n  if( rc==0 ){\n    if( pLhs->iDocid==pRhs->iDocid ){\n      rc = pRhs->iIdx - pLhs->iIdx;\n    }else{\n      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;\n    }\n  }\n  assert( pLhs->aNode && pRhs->aNode );\n  return rc;\n}\n\n/*\n** Compare the term that the Fts3SegReader object passed as the first argument\n** points to with the term specified by arguments zTerm and nTerm. \n**\n** If the pSeg iterator is already at EOF, return 0. Otherwise, return\n** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are\n** equal, or +ve if the pSeg term is greater than zTerm/nTerm.\n*/\nstatic int fts3SegReaderTermCmp(\n  Fts3SegReader *pSeg,            /* Segment reader object */\n  const char *zTerm,              /* Term to compare to */\n  int nTerm                       /* Size of term zTerm in bytes */\n){\n  int res = 0;\n  if( pSeg->aNode ){\n    if( pSeg->nTerm>nTerm ){\n      res = memcmp(pSeg->zTerm, zTerm, nTerm);\n    }else{\n      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);\n    }\n    if( res==0 ){\n      res = pSeg->nTerm-nTerm;\n    }\n  }\n  return res;\n}\n\n/*\n** Argument apSegment is an array of nSegment elements. It is known that\n** the final (nSegment-nSuspect) members are already in sorted order\n** (according to the comparison function provided). This function shuffles\n** the array around until all entries are in sorted order.\n*/\nstatic void fts3SegReaderSort(\n  Fts3SegReader **apSegment,                     /* Array to sort entries of */\n  int nSegment,                                  /* Size of apSegment array */\n  int nSuspect,                                  /* Unsorted entry count */\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */\n){\n  int i;                          /* Iterator variable */\n\n  assert( nSuspect<=nSegment );\n\n  if( nSuspect==nSegment ) nSuspect--;\n  for(i=nSuspect-1; i>=0; i--){\n    int j;\n    for(j=i; j<(nSegment-1); j++){\n      Fts3SegReader *pTmp;\n      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;\n      pTmp = apSegment[j+1];\n      apSegment[j+1] = apSegment[j];\n      apSegment[j] = pTmp;\n    }\n  }\n\n#ifndef NDEBUG\n  /* Check that the list really is sorted now. */\n  for(i=0; i<(nSuspect-1); i++){\n    assert( xCmp(apSegment[i], apSegment[i+1])<0 );\n  }\n#endif\n}\n\n/* \n** Insert a record into the %_segments table.\n*/\nstatic int fts3WriteSegment(\n  Fts3Table *p,                   /* Virtual table handle */\n  sqlite3_int64 iBlock,           /* Block id for new block */\n  char *z,                        /* Pointer to buffer containing block data */\n  int n                           /* Size of buffer z in bytes */\n){\n  sqlite3_stmt *pStmt;\n  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iBlock);\n    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n  }\n  return rc;\n}\n\n/*\n** Find the largest relative level number in the table. If successful, set\n** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,\n** set *pnMax to zero and return an SQLite error code.\n*/\nSQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){\n  int rc;\n  int mxLevel = 0;\n  sqlite3_stmt *pStmt = 0;\n\n  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      mxLevel = sqlite3_column_int(pStmt, 0);\n    }\n    rc = sqlite3_reset(pStmt);\n  }\n  *pnMax = mxLevel;\n  return rc;\n}\n\n/* \n** Insert a record into the %_segdir table.\n*/\nstatic int fts3WriteSegdir(\n  Fts3Table *p,                   /* Virtual table handle */\n  sqlite3_int64 iLevel,           /* Value for \"level\" field (absolute level) */\n  int iIdx,                       /* Value for \"idx\" field */\n  sqlite3_int64 iStartBlock,      /* Value for \"start_block\" field */\n  sqlite3_int64 iLeafEndBlock,    /* Value for \"leaves_end_block\" field */\n  sqlite3_int64 iEndBlock,        /* Value for \"end_block\" field */\n  char *zRoot,                    /* Blob value for \"root\" field */\n  int nRoot                       /* Number of bytes in buffer zRoot */\n){\n  sqlite3_stmt *pStmt;\n  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pStmt, 1, iLevel);\n    sqlite3_bind_int(pStmt, 2, iIdx);\n    sqlite3_bind_int64(pStmt, 3, iStartBlock);\n    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);\n    sqlite3_bind_int64(pStmt, 5, iEndBlock);\n    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);\n    sqlite3_step(pStmt);\n    rc = sqlite3_reset(pStmt);\n  }\n  return rc;\n}\n\n/*\n** Return the size of the common prefix (if any) shared by zPrev and\n** zNext, in bytes. For example, \n**\n**   fts3PrefixCompress(\"abc\", 3, \"abcdef\", 6)   // returns 3\n**   fts3PrefixCompress(\"abX\", 3, \"abcdef\", 6)   // returns 2\n**   fts3PrefixCompress(\"abX\", 3, \"Xbcdef\", 6)   // returns 0\n*/\nstatic int fts3PrefixCompress(\n  const char *zPrev,              /* Buffer containing previous term */\n  int nPrev,                      /* Size of buffer zPrev in bytes */\n  const char *zNext,              /* Buffer containing next term */\n  int nNext                       /* Size of buffer zNext in bytes */\n){\n  int n;\n  UNUSED_PARAMETER(nNext);\n  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);\n  return n;\n}\n\n/*\n** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger\n** (according to memcmp) than the previous term.\n*/\nstatic int fts3NodeAddTerm(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ \n  int isCopyTerm,                 /* True if zTerm/nTerm is transient */\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm                       /* Size of term in bytes */\n){\n  SegmentNode *pTree = *ppTree;\n  int rc;\n  SegmentNode *pNew;\n\n  /* First try to append the term to the current node. Return early if \n  ** this is possible.\n  */\n  if( pTree ){\n    int nData = pTree->nData;     /* Current size of node in bytes */\n    int nReq = nData;             /* Required space after adding zTerm */\n    int nPrefix;                  /* Number of bytes of prefix compression */\n    int nSuffix;                  /* Suffix length */\n\n    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);\n    nSuffix = nTerm-nPrefix;\n\n    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;\n    if( nReq<=p->nNodeSize || !pTree->zTerm ){\n\n      if( nReq>p->nNodeSize ){\n        /* An unusual case: this is the first term to be added to the node\n        ** and the static node buffer (p->nNodeSize bytes) is not large\n        ** enough. Use a separately malloced buffer instead This wastes\n        ** p->nNodeSize bytes, but since this scenario only comes about when\n        ** the database contain two terms that share a prefix of almost 2KB, \n        ** this is not expected to be a serious problem. \n        */\n        assert( pTree->aData==(char *)&pTree[1] );\n        pTree->aData = (char *)sqlite3_malloc(nReq);\n        if( !pTree->aData ){\n          return SQLITE_NOMEM;\n        }\n      }\n\n      if( pTree->zTerm ){\n        /* There is no prefix-length field for first term in a node */\n        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);\n      }\n\n      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);\n      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);\n      pTree->nData = nData + nSuffix;\n      pTree->nEntry++;\n\n      if( isCopyTerm ){\n        if( pTree->nMalloc<nTerm ){\n          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);\n          if( !zNew ){\n            return SQLITE_NOMEM;\n          }\n          pTree->nMalloc = nTerm*2;\n          pTree->zMalloc = zNew;\n        }\n        pTree->zTerm = pTree->zMalloc;\n        memcpy(pTree->zTerm, zTerm, nTerm);\n        pTree->nTerm = nTerm;\n      }else{\n        pTree->zTerm = (char *)zTerm;\n        pTree->nTerm = nTerm;\n      }\n      return SQLITE_OK;\n    }\n  }\n\n  /* If control flows to here, it was not possible to append zTerm to the\n  ** current node. Create a new node (a right-sibling of the current node).\n  ** If this is the first node in the tree, the term is added to it.\n  **\n  ** Otherwise, the term is not added to the new node, it is left empty for\n  ** now. Instead, the term is inserted into the parent of pTree. If pTree \n  ** has no parent, one is created here.\n  */\n  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);\n  if( !pNew ){\n    return SQLITE_NOMEM;\n  }\n  memset(pNew, 0, sizeof(SegmentNode));\n  pNew->nData = 1 + FTS3_VARINT_MAX;\n  pNew->aData = (char *)&pNew[1];\n\n  if( pTree ){\n    SegmentNode *pParent = pTree->pParent;\n    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);\n    if( pTree->pParent==0 ){\n      pTree->pParent = pParent;\n    }\n    pTree->pRight = pNew;\n    pNew->pLeftmost = pTree->pLeftmost;\n    pNew->pParent = pParent;\n    pNew->zMalloc = pTree->zMalloc;\n    pNew->nMalloc = pTree->nMalloc;\n    pTree->zMalloc = 0;\n  }else{\n    pNew->pLeftmost = pNew;\n    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); \n  }\n\n  *ppTree = pNew;\n  return rc;\n}\n\n/*\n** Helper function for fts3NodeWrite().\n*/\nstatic int fts3TreeFinishNode(\n  SegmentNode *pTree, \n  int iHeight, \n  sqlite3_int64 iLeftChild\n){\n  int nStart;\n  assert( iHeight>=1 && iHeight<128 );\n  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);\n  pTree->aData[nStart] = (char)iHeight;\n  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);\n  return nStart;\n}\n\n/*\n** Write the buffer for the segment node pTree and all of its peers to the\n** database. Then call this function recursively to write the parent of \n** pTree and its peers to the database. \n**\n** Except, if pTree is a root node, do not write it to the database. Instead,\n** set output variables *paRoot and *pnRoot to contain the root node.\n**\n** If successful, SQLITE_OK is returned and output variable *piLast is\n** set to the largest blockid written to the database (or zero if no\n** blocks were written to the db). Otherwise, an SQLite error code is \n** returned.\n*/\nstatic int fts3NodeWrite(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentNode *pTree,             /* SegmentNode handle */\n  int iHeight,                    /* Height of this node in tree */\n  sqlite3_int64 iLeaf,            /* Block id of first leaf node */\n  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */\n  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */\n  char **paRoot,                  /* OUT: Data for root node */\n  int *pnRoot                     /* OUT: Size of root node in bytes */\n){\n  int rc = SQLITE_OK;\n\n  if( !pTree->pParent ){\n    /* Root node of the tree. */\n    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);\n    *piLast = iFree-1;\n    *pnRoot = pTree->nData - nStart;\n    *paRoot = &pTree->aData[nStart];\n  }else{\n    SegmentNode *pIter;\n    sqlite3_int64 iNextFree = iFree;\n    sqlite3_int64 iNextLeaf = iLeaf;\n    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){\n      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);\n      int nWrite = pIter->nData - nStart;\n  \n      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);\n      iNextFree++;\n      iNextLeaf += (pIter->nEntry+1);\n    }\n    if( rc==SQLITE_OK ){\n      assert( iNextLeaf==iFree );\n      rc = fts3NodeWrite(\n          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot\n      );\n    }\n  }\n\n  return rc;\n}\n\n/*\n** Free all memory allocations associated with the tree pTree.\n*/\nstatic void fts3NodeFree(SegmentNode *pTree){\n  if( pTree ){\n    SegmentNode *p = pTree->pLeftmost;\n    fts3NodeFree(p->pParent);\n    while( p ){\n      SegmentNode *pRight = p->pRight;\n      if( p->aData!=(char *)&p[1] ){\n        sqlite3_free(p->aData);\n      }\n      assert( pRight==0 || p->zMalloc==0 );\n      sqlite3_free(p->zMalloc);\n      sqlite3_free(p);\n      p = pRight;\n    }\n  }\n}\n\n/*\n** Add a term to the segment being constructed by the SegmentWriter object\n** *ppWriter. When adding the first term to a segment, *ppWriter should\n** be passed NULL. This function will allocate a new SegmentWriter object\n** and return it via the input/output variable *ppWriter in this case.\n**\n** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegWriterAdd(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ \n  int isCopyTerm,                 /* True if buffer zTerm must be copied */\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm,                      /* Size of term in bytes */\n  const char *aDoclist,           /* Pointer to buffer containing doclist */\n  int nDoclist                    /* Size of doclist in bytes */\n){\n  int nPrefix;                    /* Size of term prefix in bytes */\n  int nSuffix;                    /* Size of term suffix in bytes */\n  int nReq;                       /* Number of bytes required on leaf page */\n  int nData;\n  SegmentWriter *pWriter = *ppWriter;\n\n  if( !pWriter ){\n    int rc;\n    sqlite3_stmt *pStmt;\n\n    /* Allocate the SegmentWriter structure */\n    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));\n    if( !pWriter ) return SQLITE_NOMEM;\n    memset(pWriter, 0, sizeof(SegmentWriter));\n    *ppWriter = pWriter;\n\n    /* Allocate a buffer in which to accumulate data */\n    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);\n    if( !pWriter->aData ) return SQLITE_NOMEM;\n    pWriter->nSize = p->nNodeSize;\n\n    /* Find the next free blockid in the %_segments table */\n    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);\n    if( rc!=SQLITE_OK ) return rc;\n    if( SQLITE_ROW==sqlite3_step(pStmt) ){\n      pWriter->iFree = sqlite3_column_int64(pStmt, 0);\n      pWriter->iFirst = pWriter->iFree;\n    }\n    rc = sqlite3_reset(pStmt);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  nData = pWriter->nData;\n\n  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);\n  nSuffix = nTerm-nPrefix;\n\n  /* Figure out how many bytes are required by this new entry */\n  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */\n    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */\n    nSuffix +                               /* Term suffix */\n    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */\n    nDoclist;                               /* Doclist data */\n\n  if( nData>0 && nData+nReq>p->nNodeSize ){\n    int rc;\n\n    /* The current leaf node is full. Write it out to the database. */\n    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);\n    if( rc!=SQLITE_OK ) return rc;\n    p->nLeafAdd++;\n\n    /* Add the current term to the interior node tree. The term added to\n    ** the interior tree must:\n    **\n    **   a) be greater than the largest term on the leaf node just written\n    **      to the database (still available in pWriter->zTerm), and\n    **\n    **   b) be less than or equal to the term about to be added to the new\n    **      leaf node (zTerm/nTerm).\n    **\n    ** In other words, it must be the prefix of zTerm 1 byte longer than\n    ** the common prefix (if any) of zTerm and pWriter->zTerm.\n    */\n    assert( nPrefix<nTerm );\n    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);\n    if( rc!=SQLITE_OK ) return rc;\n\n    nData = 0;\n    pWriter->nTerm = 0;\n\n    nPrefix = 0;\n    nSuffix = nTerm;\n    nReq = 1 +                              /* varint containing prefix size */\n      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */\n      nTerm +                               /* Term suffix */\n      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */\n      nDoclist;                             /* Doclist data */\n  }\n\n  /* If the buffer currently allocated is too small for this entry, realloc\n  ** the buffer to make it large enough.\n  */\n  if( nReq>pWriter->nSize ){\n    char *aNew = sqlite3_realloc(pWriter->aData, nReq);\n    if( !aNew ) return SQLITE_NOMEM;\n    pWriter->aData = aNew;\n    pWriter->nSize = nReq;\n  }\n  assert( nData+nReq<=pWriter->nSize );\n\n  /* Append the prefix-compressed term and doclist to the buffer. */\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);\n  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);\n  nData += nSuffix;\n  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);\n  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);\n  pWriter->nData = nData + nDoclist;\n\n  /* Save the current term so that it can be used to prefix-compress the next.\n  ** If the isCopyTerm parameter is true, then the buffer pointed to by\n  ** zTerm is transient, so take a copy of the term data. Otherwise, just\n  ** store a copy of the pointer.\n  */\n  if( isCopyTerm ){\n    if( nTerm>pWriter->nMalloc ){\n      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);\n      if( !zNew ){\n        return SQLITE_NOMEM;\n      }\n      pWriter->nMalloc = nTerm*2;\n      pWriter->zMalloc = zNew;\n      pWriter->zTerm = zNew;\n    }\n    assert( pWriter->zTerm==pWriter->zMalloc );\n    memcpy(pWriter->zTerm, zTerm, nTerm);\n  }else{\n    pWriter->zTerm = (char *)zTerm;\n  }\n  pWriter->nTerm = nTerm;\n\n  return SQLITE_OK;\n}\n\n/*\n** Flush all data associated with the SegmentWriter object pWriter to the\n** database. This function must be called after all terms have been added\n** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is\n** returned. Otherwise, an SQLite error code.\n*/\nstatic int fts3SegWriterFlush(\n  Fts3Table *p,                   /* Virtual table handle */\n  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */\n  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */\n  int iIdx                        /* Value for 'idx' column of %_segdir */\n){\n  int rc;                         /* Return code */\n  if( pWriter->pTree ){\n    sqlite3_int64 iLast = 0;      /* Largest block id written to database */\n    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */\n    char *zRoot = NULL;           /* Pointer to buffer containing root node */\n    int nRoot = 0;                /* Size of buffer zRoot */\n\n    iLastLeaf = pWriter->iFree;\n    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);\n    if( rc==SQLITE_OK ){\n      rc = fts3NodeWrite(p, pWriter->pTree, 1,\n          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3WriteSegdir(\n          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);\n    }\n  }else{\n    /* The entire tree fits on the root node. Write it to the segdir table. */\n    rc = fts3WriteSegdir(\n        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);\n  }\n  p->nLeafAdd++;\n  return rc;\n}\n\n/*\n** Release all memory held by the SegmentWriter object passed as the \n** first argument.\n*/\nstatic void fts3SegWriterFree(SegmentWriter *pWriter){\n  if( pWriter ){\n    sqlite3_free(pWriter->aData);\n    sqlite3_free(pWriter->zMalloc);\n    fts3NodeFree(pWriter->pTree);\n    sqlite3_free(pWriter);\n  }\n}\n\n/*\n** The first value in the apVal[] array is assumed to contain an integer.\n** This function tests if there exist any documents with docid values that\n** are different from that integer. i.e. if deleting the document with docid\n** pRowid would mean the FTS3 table were empty.\n**\n** If successful, *pisEmpty is set to true if the table is empty except for\n** document pRowid, or false otherwise, and SQLITE_OK is returned. If an\n** error occurs, an SQLite error code is returned.\n*/\nstatic int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){\n  sqlite3_stmt *pStmt;\n  int rc;\n  if( p->zContentTbl ){\n    /* If using the content=xxx option, assume the table is never empty */\n    *pisEmpty = 0;\n    rc = SQLITE_OK;\n  }else{\n    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);\n    if( rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        *pisEmpty = sqlite3_column_int(pStmt, 0);\n      }\n      rc = sqlite3_reset(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** Set *pnMax to the largest segment level in the database for the index\n** iIndex.\n**\n** Segment levels are stored in the 'level' column of the %_segdir table.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if not.\n*/\nstatic int fts3SegmentMaxLevel(\n  Fts3Table *p, \n  int iLangid,\n  int iIndex, \n  sqlite3_int64 *pnMax\n){\n  sqlite3_stmt *pStmt;\n  int rc;\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  /* Set pStmt to the compiled version of:\n  **\n  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?\n  **\n  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).\n  */\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);\n  if( rc!=SQLITE_OK ) return rc;\n  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n  sqlite3_bind_int64(pStmt, 2, \n      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n  );\n  if( SQLITE_ROW==sqlite3_step(pStmt) ){\n    *pnMax = sqlite3_column_int64(pStmt, 0);\n  }\n  return sqlite3_reset(pStmt);\n}\n\n/*\n** Delete all entries in the %_segments table associated with the segment\n** opened with seg-reader pSeg. This function does not affect the contents\n** of the %_segdir table.\n*/\nstatic int fts3DeleteSegment(\n  Fts3Table *p,                   /* FTS table handle */\n  Fts3SegReader *pSeg             /* Segment to delete */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  if( pSeg->iStartBlock ){\n    sqlite3_stmt *pDelete;        /* SQL statement to delete rows */\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);\n      sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);\n      sqlite3_step(pDelete);\n      rc = sqlite3_reset(pDelete);\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is used after merging multiple segments into a single large\n** segment to delete the old, now redundant, segment b-trees. Specifically,\n** it:\n** \n**   1) Deletes all %_segments entries for the segments associated with \n**      each of the SegReader objects in the array passed as the third \n**      argument, and\n**\n**   2) deletes all %_segdir entries with level iLevel, or all %_segdir\n**      entries regardless of level if (iLevel<0).\n**\n** SQLITE_OK is returned if successful, otherwise an SQLite error code.\n*/\nstatic int fts3DeleteSegdir(\n  Fts3Table *p,                   /* Virtual table handle */\n  int iLangid,                    /* Language id */\n  int iIndex,                     /* Index for p->aIndex */\n  int iLevel,                     /* Level of %_segdir entries to delete */\n  Fts3SegReader **apSegment,      /* Array of SegReader objects */\n  int nReader                     /* Size of array apSegment */\n){\n  int rc = SQLITE_OK;             /* Return Code */\n  int i;                          /* Iterator variable */\n  sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */\n\n  for(i=0; rc==SQLITE_OK && i<nReader; i++){\n    rc = fts3DeleteSegment(p, apSegment[i]);\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );\n  if( iLevel==FTS3_SEGCURSOR_ALL ){\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));\n      sqlite3_bind_int64(pDelete, 2, \n          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)\n      );\n    }\n  }else{\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(\n          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)\n      );\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_step(pDelete);\n    rc = sqlite3_reset(pDelete);\n  }\n\n  return rc;\n}\n\n/*\n** When this function is called, buffer *ppList (size *pnList bytes) contains \n** a position list that may (or may not) feature multiple columns. This\n** function adjusts the pointer *ppList and the length *pnList so that they\n** identify the subset of the position list that corresponds to column iCol.\n**\n** If there are no entries in the input position list for column iCol, then\n** *pnList is set to zero before returning.\n*/\nstatic void fts3ColumnFilter(\n  int iCol,                       /* Column to filter on */\n  char **ppList,                  /* IN/OUT: Pointer to position list */\n  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */\n){\n  char *pList = *ppList;\n  int nList = *pnList;\n  char *pEnd = &pList[nList];\n  int iCurrent = 0;\n  char *p = pList;\n\n  assert( iCol>=0 );\n  while( 1 ){\n    char c = 0;\n    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;\n  \n    if( iCol==iCurrent ){\n      nList = (int)(p - pList);\n      break;\n    }\n\n    nList -= (int)(p - pList);\n    pList = p;\n    if( nList==0 ){\n      break;\n    }\n    p = &pList[1];\n    p += sqlite3Fts3GetVarint32(p, &iCurrent);\n  }\n\n  *ppList = pList;\n  *pnList = nList;\n}\n\n/*\n** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any\n** existing data). Grow the buffer if required.\n**\n** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered\n** trying to resize the buffer, return SQLITE_NOMEM.\n*/\nstatic int fts3MsrBufferData(\n  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */\n  char *pList,\n  int nList\n){\n  if( nList>pMsr->nBuffer ){\n    char *pNew;\n    pMsr->nBuffer = nList*2;\n    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);\n    if( !pNew ) return SQLITE_NOMEM;\n    pMsr->aBuffer = pNew;\n  }\n\n  memcpy(pMsr->aBuffer, pList, nList);\n  return SQLITE_OK;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */\n  sqlite3_int64 *piDocid,         /* OUT: Docid value */\n  char **paPoslist,               /* OUT: Pointer to position list */\n  int *pnPoslist                  /* OUT: Size of position list in bytes */\n){\n  int nMerge = pMsr->nAdvance;\n  Fts3SegReader **apSegment = pMsr->apSegment;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  if( nMerge==0 ){\n    *paPoslist = 0;\n    return SQLITE_OK;\n  }\n\n  while( 1 ){\n    Fts3SegReader *pSeg;\n    pSeg = pMsr->apSegment[0];\n\n    if( pSeg->pOffsetList==0 ){\n      *paPoslist = 0;\n      break;\n    }else{\n      int rc;\n      char *pList;\n      int nList;\n      int j;\n      sqlite3_int64 iDocid = apSegment[0]->iDocid;\n\n      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);\n      j = 1;\n      while( rc==SQLITE_OK \n        && j<nMerge\n        && apSegment[j]->pOffsetList\n        && apSegment[j]->iDocid==iDocid\n      ){\n        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);\n        j++;\n      }\n      if( rc!=SQLITE_OK ) return rc;\n      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);\n\n      if( pMsr->iColFilter>=0 ){\n        fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);\n      }\n\n      if( nList>0 ){\n        if( fts3SegReaderIsPending(apSegment[0]) ){\n          rc = fts3MsrBufferData(pMsr, pList, nList+1);\n          if( rc!=SQLITE_OK ) return rc;\n          *paPoslist = pMsr->aBuffer;\n          assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );\n        }else{\n          *paPoslist = pList;\n        }\n        *piDocid = iDocid;\n        *pnPoslist = nList;\n        break;\n      }\n    }\n  }\n\n  return SQLITE_OK;\n}\n\nstatic int fts3SegReaderStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  const char *zTerm,              /* Term searched for (or NULL) */\n  int nTerm                       /* Length of zTerm in bytes */\n){\n  int i;\n  int nSeg = pCsr->nSegment;\n\n  /* If the Fts3SegFilter defines a specific term (or term prefix) to search \n  ** for, then advance each segment iterator until it points to a term of\n  ** equal or greater value than the specified term. This prevents many\n  ** unnecessary merge/sort operations for the case where single segment\n  ** b-tree leaf nodes contain more than one term.\n  */\n  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){\n    int res = 0;\n    Fts3SegReader *pSeg = pCsr->apSegment[i];\n    do {\n      int rc = fts3SegReaderNext(p, pSeg, 0);\n      if( rc!=SQLITE_OK ) return rc;\n    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );\n\n    if( pSeg->bLookup && res!=0 ){\n      fts3SegReaderSetEof(pSeg);\n    }\n  }\n  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);\n\n  return SQLITE_OK;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */\n){\n  pCsr->pFilter = pFilter;\n  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);\n}\n\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr,       /* Cursor object */\n  int iCol,                       /* Column to match on. */\n  const char *zTerm,              /* Term to iterate through a doclist for */\n  int nTerm                       /* Number of bytes in zTerm */\n){\n  int i;\n  int rc;\n  int nSegment = pCsr->nSegment;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  assert( pCsr->pFilter==0 );\n  assert( zTerm && nTerm>0 );\n\n  /* Advance each segment iterator until it points to the term zTerm/nTerm. */\n  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Determine how many of the segments actually point to zTerm/nTerm. */\n  for(i=0; i<nSegment; i++){\n    Fts3SegReader *pSeg = pCsr->apSegment[i];\n    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){\n      break;\n    }\n  }\n  pCsr->nAdvance = i;\n\n  /* Advance each of the segments to point to the first docid. */\n  for(i=0; i<pCsr->nAdvance; i++){\n    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);\n\n  assert( iCol<0 || iCol<p->nColumn );\n  pCsr->iColFilter = iCol;\n\n  return SQLITE_OK;\n}\n\n/*\n** This function is called on a MultiSegReader that has been started using\n** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also\n** have been made. Calling this function puts the MultiSegReader in such\n** a state that if the next two calls are:\n**\n**   sqlite3Fts3SegReaderStart()\n**   sqlite3Fts3SegReaderStep()\n**\n** then the entire doclist for the term is available in \n** MultiSegReader.aDoclist/nDoclist.\n*/\nSQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){\n  int i;                          /* Used to iterate through segment-readers */\n\n  assert( pCsr->zTerm==0 );\n  assert( pCsr->nTerm==0 );\n  assert( pCsr->aDoclist==0 );\n  assert( pCsr->nDoclist==0 );\n\n  pCsr->nAdvance = 0;\n  pCsr->bRestart = 1;\n  for(i=0; i<pCsr->nSegment; i++){\n    pCsr->apSegment[i]->pOffsetList = 0;\n    pCsr->apSegment[i]->nOffsetList = 0;\n    pCsr->apSegment[i]->iDocid = 0;\n  }\n\n  return SQLITE_OK;\n}\n\n\nSQLITE_PRIVATE int sqlite3Fts3SegReaderStep(\n  Fts3Table *p,                   /* Virtual table handle */\n  Fts3MultiSegReader *pCsr        /* Cursor object */\n){\n  int rc = SQLITE_OK;\n\n  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);\n  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);\n  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);\n  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);\n  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);\n  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);\n\n  Fts3SegReader **apSegment = pCsr->apSegment;\n  int nSegment = pCsr->nSegment;\n  Fts3SegFilter *pFilter = pCsr->pFilter;\n  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (\n    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp\n  );\n\n  if( pCsr->nSegment==0 ) return SQLITE_OK;\n\n  do {\n    int nMerge;\n    int i;\n  \n    /* Advance the first pCsr->nAdvance entries in the apSegment[] array\n    ** forward. Then sort the list in order of current term again.  \n    */\n    for(i=0; i<pCsr->nAdvance; i++){\n      Fts3SegReader *pSeg = apSegment[i];\n      if( pSeg->bLookup ){\n        fts3SegReaderSetEof(pSeg);\n      }else{\n        rc = fts3SegReaderNext(p, pSeg, 0);\n      }\n      if( rc!=SQLITE_OK ) return rc;\n    }\n    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);\n    pCsr->nAdvance = 0;\n\n    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */\n    assert( rc==SQLITE_OK );\n    if( apSegment[0]->aNode==0 ) break;\n\n    pCsr->nTerm = apSegment[0]->nTerm;\n    pCsr->zTerm = apSegment[0]->zTerm;\n\n    /* If this is a prefix-search, and if the term that apSegment[0] points\n    ** to does not share a suffix with pFilter->zTerm/nTerm, then all \n    ** required callbacks have been made. In this case exit early.\n    **\n    ** Similarly, if this is a search for an exact match, and the first term\n    ** of segment apSegment[0] is not a match, exit early.\n    */\n    if( pFilter->zTerm && !isScan ){\n      if( pCsr->nTerm<pFilter->nTerm \n       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)\n       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) \n      ){\n        break;\n      }\n    }\n\n    nMerge = 1;\n    while( nMerge<nSegment \n        && apSegment[nMerge]->aNode\n        && apSegment[nMerge]->nTerm==pCsr->nTerm \n        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)\n    ){\n      nMerge++;\n    }\n\n    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );\n    if( nMerge==1 \n     && !isIgnoreEmpty \n     && !isFirst \n     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)\n    ){\n      pCsr->nDoclist = apSegment[0]->nDoclist;\n      if( fts3SegReaderIsPending(apSegment[0]) ){\n        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);\n        pCsr->aDoclist = pCsr->aBuffer;\n      }else{\n        pCsr->aDoclist = apSegment[0]->aDoclist;\n      }\n      if( rc==SQLITE_OK ) rc = SQLITE_ROW;\n    }else{\n      int nDoclist = 0;           /* Size of doclist */\n      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */\n\n      /* The current term of the first nMerge entries in the array\n      ** of Fts3SegReader objects is the same. The doclists must be merged\n      ** and a single term returned with the merged doclist.\n      */\n      for(i=0; i<nMerge; i++){\n        fts3SegReaderFirstDocid(p, apSegment[i]);\n      }\n      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);\n      while( apSegment[0]->pOffsetList ){\n        int j;                    /* Number of segments that share a docid */\n        char *pList;\n        int nList;\n        int nByte;\n        sqlite3_int64 iDocid = apSegment[0]->iDocid;\n        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);\n        j = 1;\n        while( j<nMerge\n            && apSegment[j]->pOffsetList\n            && apSegment[j]->iDocid==iDocid\n        ){\n          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);\n          j++;\n        }\n\n        if( isColFilter ){\n          fts3ColumnFilter(pFilter->iCol, &pList, &nList);\n        }\n\n        if( !isIgnoreEmpty || nList>0 ){\n\n          /* Calculate the 'docid' delta value to write into the merged \n          ** doclist. */\n          sqlite3_int64 iDelta;\n          if( p->bDescIdx && nDoclist>0 ){\n            iDelta = iPrev - iDocid;\n          }else{\n            iDelta = iDocid - iPrev;\n          }\n          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );\n          assert( nDoclist>0 || iDelta==iDocid );\n\n          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);\n          if( nDoclist+nByte>pCsr->nBuffer ){\n            char *aNew;\n            pCsr->nBuffer = (nDoclist+nByte)*2;\n            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);\n            if( !aNew ){\n              return SQLITE_NOMEM;\n            }\n            pCsr->aBuffer = aNew;\n          }\n\n          if( isFirst ){\n            char *a = &pCsr->aBuffer[nDoclist];\n            int nWrite;\n           \n            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);\n            if( nWrite ){\n              iPrev = iDocid;\n              nDoclist += nWrite;\n            }\n          }else{\n            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);\n            iPrev = iDocid;\n            if( isRequirePos ){\n              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);\n              nDoclist += nList;\n              pCsr->aBuffer[nDoclist++] = '\\0';\n            }\n          }\n        }\n\n        fts3SegReaderSort(apSegment, nMerge, j, xCmp);\n      }\n      if( nDoclist>0 ){\n        pCsr->aDoclist = pCsr->aBuffer;\n        pCsr->nDoclist = nDoclist;\n        rc = SQLITE_ROW;\n      }\n    }\n    pCsr->nAdvance = nMerge;\n  }while( rc==SQLITE_OK );\n\n  return rc;\n}\n\n\nSQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(\n  Fts3MultiSegReader *pCsr       /* Cursor object */\n){\n  if( pCsr ){\n    int i;\n    for(i=0; i<pCsr->nSegment; i++){\n      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);\n    }\n    sqlite3_free(pCsr->apSegment);\n    sqlite3_free(pCsr->aBuffer);\n\n    pCsr->nSegment = 0;\n    pCsr->apSegment = 0;\n    pCsr->aBuffer = 0;\n  }\n}\n\n/*\n** Merge all level iLevel segments in the database into a single \n** iLevel+1 segment. Or, if iLevel<0, merge all segments into a\n** single segment with a level equal to the numerically largest level \n** currently present in the database.\n**\n** If this function is called with iLevel<0, but there is only one\n** segment in the database, SQLITE_DONE is returned immediately. \n** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, \n** an SQLite error code is returned.\n*/\nstatic int fts3SegmentMerge(\n  Fts3Table *p, \n  int iLangid,                    /* Language id to merge */\n  int iIndex,                     /* Index in p->aIndex[] to merge */\n  int iLevel                      /* Level to merge */\n){\n  int rc;                         /* Return code */\n  int iIdx = 0;                   /* Index of new segment */\n  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */\n  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */\n  Fts3SegFilter filter;           /* Segment term filter condition */\n  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */\n  int bIgnoreEmpty = 0;           /* True to ignore empty segments */\n\n  assert( iLevel==FTS3_SEGCURSOR_ALL\n       || iLevel==FTS3_SEGCURSOR_PENDING\n       || iLevel>=0\n  );\n  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );\n  assert( iIndex>=0 && iIndex<p->nIndex );\n\n  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);\n  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;\n\n  if( iLevel==FTS3_SEGCURSOR_ALL ){\n    /* This call is to merge all segments in the database to a single\n    ** segment. The level of the new segment is equal to the numerically\n    ** greatest segment level currently present in the database for this\n    ** index. The idx of the new segment is always 0.  */\n    if( csr.nSegment==1 ){\n      rc = SQLITE_DONE;\n      goto finished;\n    }\n    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);\n    bIgnoreEmpty = 1;\n\n  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){\n    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);\n    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);\n  }else{\n    /* This call is to merge all segments at level iLevel. find the next\n    ** available segment index at level iLevel+1. The call to\n    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to \n    ** a single iLevel+2 segment if necessary.  */\n    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);\n    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);\n  }\n  if( rc!=SQLITE_OK ) goto finished;\n  assert( csr.nSegment>0 );\n  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );\n  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );\n\n  memset(&filter, 0, sizeof(Fts3SegFilter));\n  filter.flags = FTS3_SEGMENT_REQUIRE_POS;\n  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);\n\n  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);\n  while( SQLITE_OK==rc ){\n    rc = sqlite3Fts3SegReaderStep(p, &csr);\n    if( rc!=SQLITE_ROW ) break;\n    rc = fts3SegWriterAdd(p, &pWriter, 1, \n        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);\n  }\n  if( rc!=SQLITE_OK ) goto finished;\n  assert( pWriter );\n\n  if( iLevel!=FTS3_SEGCURSOR_PENDING ){\n    rc = fts3DeleteSegdir(\n        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment\n    );\n    if( rc!=SQLITE_OK ) goto finished;\n  }\n  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);\n\n finished:\n  fts3SegWriterFree(pWriter);\n  sqlite3Fts3SegReaderFinish(&csr);\n  return rc;\n}\n\n\n/* \n** Flush the contents of pendingTerms to level 0 segments.\n*/\nSQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){\n  int rc = SQLITE_OK;\n  int i;\n        \n  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){\n    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);\n    if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n  }\n  sqlite3Fts3PendingTermsClear(p);\n\n  /* Determine the auto-incr-merge setting if unknown.  If enabled,\n  ** estimate the number of leaf blocks of content to be written\n  */\n  if( rc==SQLITE_OK && p->bHasStat\n   && p->bAutoincrmerge==0xff && p->nLeafAdd>0\n  ){\n    sqlite3_stmt *pStmt = 0;\n    rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);\n      rc = sqlite3_step(pStmt);\n      p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));\n      rc = sqlite3_reset(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** Encode N integers as varints into a blob.\n*/\nstatic void fts3EncodeIntArray(\n  int N,             /* The number of integers to encode */\n  u32 *a,            /* The integer values */\n  char *zBuf,        /* Write the BLOB here */\n  int *pNBuf         /* Write number of bytes if zBuf[] used here */\n){\n  int i, j;\n  for(i=j=0; i<N; i++){\n    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);\n  }\n  *pNBuf = j;\n}\n\n/*\n** Decode a blob of varints into N integers\n*/\nstatic void fts3DecodeIntArray(\n  int N,             /* The number of integers to decode */\n  u32 *a,            /* Write the integer values */\n  const char *zBuf,  /* The BLOB containing the varints */\n  int nBuf           /* size of the BLOB */\n){\n  int i, j;\n  UNUSED_PARAMETER(nBuf);\n  for(i=j=0; i<N; i++){\n    sqlite3_int64 x;\n    j += sqlite3Fts3GetVarint(&zBuf[j], &x);\n    assert(j<=nBuf);\n    a[i] = (u32)(x & 0xffffffff);\n  }\n}\n\n/*\n** Insert the sizes (in tokens) for each column of the document\n** with docid equal to p->iPrevDocid.  The sizes are encoded as\n** a blob of varints.\n*/\nstatic void fts3InsertDocsize(\n  int *pRC,                       /* Result code */\n  Fts3Table *p,                   /* Table into which to insert */\n  u32 *aSz                        /* Sizes of each column, in tokens */\n){\n  char *pBlob;             /* The BLOB encoding of the document size */\n  int nBlob;               /* Number of bytes in the BLOB */\n  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */\n  int rc;                  /* Result code from subfunctions */\n\n  if( *pRC ) return;\n  pBlob = sqlite3_malloc( 10*p->nColumn );\n  if( pBlob==0 ){\n    *pRC = SQLITE_NOMEM;\n    return;\n  }\n  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);\n  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(pBlob);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);\n  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);\n  sqlite3_step(pStmt);\n  *pRC = sqlite3_reset(pStmt);\n}\n\n/*\n** Record 0 of the %_stat table contains a blob consisting of N varints,\n** where N is the number of user defined columns in the fts3 table plus\n** two. If nCol is the number of user defined columns, then values of the \n** varints are set as follows:\n**\n**   Varint 0:       Total number of rows in the table.\n**\n**   Varint 1..nCol: For each column, the total number of tokens stored in\n**                   the column for all rows of the table.\n**\n**   Varint 1+nCol:  The total size, in bytes, of all text values in all\n**                   columns of all rows of the table.\n**\n*/\nstatic void fts3UpdateDocTotals(\n  int *pRC,                       /* The result code */\n  Fts3Table *p,                   /* Table being updated */\n  u32 *aSzIns,                    /* Size increases */\n  u32 *aSzDel,                    /* Size decreases */\n  int nChng                       /* Change in the number of documents */\n){\n  char *pBlob;             /* Storage for BLOB written into %_stat */\n  int nBlob;               /* Size of BLOB written into %_stat */\n  u32 *a;                  /* Array of integers that becomes the BLOB */\n  sqlite3_stmt *pStmt;     /* Statement for reading and writing */\n  int i;                   /* Loop counter */\n  int rc;                  /* Result code from subfunctions */\n\n  const int nStat = p->nColumn+2;\n\n  if( *pRC ) return;\n  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );\n  if( a==0 ){\n    *pRC = SQLITE_NOMEM;\n    return;\n  }\n  pBlob = (char*)&a[nStat];\n  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n  if( sqlite3_step(pStmt)==SQLITE_ROW ){\n    fts3DecodeIntArray(nStat, a,\n         sqlite3_column_blob(pStmt, 0),\n         sqlite3_column_bytes(pStmt, 0));\n  }else{\n    memset(a, 0, sizeof(u32)*(nStat) );\n  }\n  rc = sqlite3_reset(pStmt);\n  if( rc!=SQLITE_OK ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  if( nChng<0 && a[0]<(u32)(-nChng) ){\n    a[0] = 0;\n  }else{\n    a[0] += nChng;\n  }\n  for(i=0; i<p->nColumn+1; i++){\n    u32 x = a[i+1];\n    if( x+aSzIns[i] < aSzDel[i] ){\n      x = 0;\n    }else{\n      x = x + aSzIns[i] - aSzDel[i];\n    }\n    a[i+1] = x;\n  }\n  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);\n  if( rc ){\n    sqlite3_free(a);\n    *pRC = rc;\n    return;\n  }\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);\n  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);\n  sqlite3_step(pStmt);\n  *pRC = sqlite3_reset(pStmt);\n  sqlite3_free(a);\n}\n\n/*\n** Merge the entire database so that there is one segment for each \n** iIndex/iLangid combination.\n*/\nstatic int fts3DoOptimize(Fts3Table *p, int bReturnDone){\n  int bSeenDone = 0;\n  int rc;\n  sqlite3_stmt *pAllLangid = 0;\n\n  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pAllLangid, 1, p->nIndex);\n    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){\n      int i;\n      int iLangid = sqlite3_column_int(pAllLangid, 0);\n      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){\n        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);\n        if( rc==SQLITE_DONE ){\n          bSeenDone = 1;\n          rc = SQLITE_OK;\n        }\n      }\n    }\n    rc2 = sqlite3_reset(pAllLangid);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  sqlite3Fts3SegmentsClose(p);\n  sqlite3Fts3PendingTermsClear(p);\n\n  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;\n}\n\n/*\n** This function is called when the user executes the following statement:\n**\n**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');\n**\n** The entire FTS index is discarded and rebuilt. If the table is one \n** created using the content=xxx option, then the new index is based on\n** the current contents of the xxx table. Otherwise, it is rebuilt based\n** on the contents of the %_content table.\n*/\nstatic int fts3DoRebuild(Fts3Table *p){\n  int rc;                         /* Return Code */\n\n  rc = fts3DeleteAll(p, 0);\n  if( rc==SQLITE_OK ){\n    u32 *aSz = 0;\n    u32 *aSzIns = 0;\n    u32 *aSzDel = 0;\n    sqlite3_stmt *pStmt = 0;\n    int nEntry = 0;\n\n    /* Compose and prepare an SQL statement to loop through the content table */\n    char *zSql = sqlite3_mprintf(\"SELECT %s\" , p->zReadExprlist);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n      sqlite3_free(zSql);\n    }\n\n    if( rc==SQLITE_OK ){\n      int nByte = sizeof(u32) * (p->nColumn+1)*3;\n      aSz = (u32 *)sqlite3_malloc(nByte);\n      if( aSz==0 ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(aSz, 0, nByte);\n        aSzIns = &aSz[p->nColumn+1];\n        aSzDel = &aSzIns[p->nColumn+1];\n      }\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      int iCol;\n      int iLangid = langidFromSelect(p, pStmt);\n      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));\n      aSz[p->nColumn] = 0;\n      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){\n        const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);\n        rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);\n        aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);\n      }\n      if( p->bHasDocsize ){\n        fts3InsertDocsize(&rc, p, aSz);\n      }\n      if( rc!=SQLITE_OK ){\n        sqlite3_finalize(pStmt);\n        pStmt = 0;\n      }else{\n        nEntry++;\n        for(iCol=0; iCol<=p->nColumn; iCol++){\n          aSzIns[iCol] += aSz[iCol];\n        }\n      }\n    }\n    if( p->bFts4 ){\n      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);\n    }\n    sqlite3_free(aSz);\n\n    if( pStmt ){\n      int rc2 = sqlite3_finalize(pStmt);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\n  return rc;\n}\n\n\n/*\n** This function opens a cursor used to read the input data for an \n** incremental merge operation. Specifically, it opens a cursor to scan\n** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute \n** level iAbsLevel.\n*/\nstatic int fts3IncrmergeCsr(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level to open */\n  int nSeg,                       /* Number of segments to merge */\n  Fts3MultiSegReader *pCsr        /* Cursor object to populate */\n){\n  int rc;                         /* Return Code */\n  sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  \n  int nByte;                      /* Bytes allocated at pCsr->apSegment[] */\n\n  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */\n  memset(pCsr, 0, sizeof(*pCsr));\n  nByte = sizeof(Fts3SegReader *) * nSeg;\n  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);\n\n  if( pCsr->apSegment==0 ){\n    rc = SQLITE_NOMEM;\n  }else{\n    memset(pCsr->apSegment, 0, nByte);\n    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);\n  }\n  if( rc==SQLITE_OK ){\n    int i;\n    int rc2;\n    sqlite3_bind_int64(pStmt, 1, iAbsLevel);\n    assert( pCsr->nSegment==0 );\n    for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){\n      rc = sqlite3Fts3SegReaderNew(i, 0,\n          sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */\n          sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */\n          sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */\n          sqlite3_column_blob(pStmt, 4),         /* segdir.root */\n          sqlite3_column_bytes(pStmt, 4),        /* segdir.root */\n          &pCsr->apSegment[i]\n      );\n      pCsr->nSegment++;\n    }\n    rc2 = sqlite3_reset(pStmt);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\ntypedef struct IncrmergeWriter IncrmergeWriter;\ntypedef struct NodeWriter NodeWriter;\ntypedef struct Blob Blob;\ntypedef struct NodeReader NodeReader;\n\n/*\n** An instance of the following structure is used as a dynamic buffer\n** to build up nodes or other blobs of data in.\n**\n** The function blobGrowBuffer() is used to extend the allocation.\n*/\nstruct Blob {\n  char *a;                        /* Pointer to allocation */\n  int n;                          /* Number of valid bytes of data in a[] */\n  int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */\n};\n\n/*\n** This structure is used to build up buffers containing segment b-tree \n** nodes (blocks).\n*/\nstruct NodeWriter {\n  sqlite3_int64 iBlock;           /* Current block id */\n  Blob key;                       /* Last key written to the current block */\n  Blob block;                     /* Current block image */\n};\n\n/*\n** An object of this type contains the state required to create or append\n** to an appendable b-tree segment.\n*/\nstruct IncrmergeWriter {\n  int nLeafEst;                   /* Space allocated for leaf blocks */\n  int nWork;                      /* Number of leaf pages flushed */\n  sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */\n  int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */\n  sqlite3_int64 iStart;           /* Block number of first allocated block */\n  sqlite3_int64 iEnd;             /* Block number of last allocated block */\n  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];\n};\n\n/*\n** An object of the following type is used to read data from a single\n** FTS segment node. See the following functions:\n**\n**     nodeReaderInit()\n**     nodeReaderNext()\n**     nodeReaderRelease()\n*/\nstruct NodeReader {\n  const char *aNode;\n  int nNode;\n  int iOff;                       /* Current offset within aNode[] */\n\n  /* Output variables. Containing the current node entry. */\n  sqlite3_int64 iChild;           /* Pointer to child node */\n  Blob term;                      /* Current term */\n  const char *aDoclist;           /* Pointer to doclist */\n  int nDoclist;                   /* Size of doclist in bytes */\n};\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, if the allocation at pBlob->a is not already at least nMin\n** bytes in size, extend (realloc) it to be so.\n**\n** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a\n** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc\n** to reflect the new size of the pBlob->a[] buffer.\n*/\nstatic void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){\n  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){\n    int nAlloc = nMin;\n    char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);\n    if( a ){\n      pBlob->nAlloc = nAlloc;\n      pBlob->a = a;\n    }else{\n      *pRc = SQLITE_NOMEM;\n    }\n  }\n}\n\n/*\n** Attempt to advance the node-reader object passed as the first argument to\n** the next entry on the node. \n**\n** Return an error code if an error occurs (SQLITE_NOMEM is possible). \n** Otherwise return SQLITE_OK. If there is no next entry on the node\n** (e.g. because the current entry is the last) set NodeReader->aNode to\n** NULL to indicate EOF. Otherwise, populate the NodeReader structure output \n** variables for the new entry.\n*/\nstatic int nodeReaderNext(NodeReader *p){\n  int bFirst = (p->term.n==0);    /* True for first term on the node */\n  int nPrefix = 0;                /* Bytes to copy from previous term */\n  int nSuffix = 0;                /* Bytes to append to the prefix */\n  int rc = SQLITE_OK;             /* Return code */\n\n  assert( p->aNode );\n  if( p->iChild && bFirst==0 ) p->iChild++;\n  if( p->iOff>=p->nNode ){\n    /* EOF */\n    p->aNode = 0;\n  }else{\n    if( bFirst==0 ){\n      p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);\n    }\n    p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);\n\n    blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);\n    if( rc==SQLITE_OK ){\n      memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);\n      p->term.n = nPrefix+nSuffix;\n      p->iOff += nSuffix;\n      if( p->iChild==0 ){\n        p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);\n        p->aDoclist = &p->aNode[p->iOff];\n        p->iOff += p->nDoclist;\n      }\n    }\n  }\n\n  assert( p->iOff<=p->nNode );\n\n  return rc;\n}\n\n/*\n** Release all dynamic resources held by node-reader object *p.\n*/\nstatic void nodeReaderRelease(NodeReader *p){\n  sqlite3_free(p->term.a);\n}\n\n/*\n** Initialize a node-reader object to read the node in buffer aNode/nNode.\n**\n** If successful, SQLITE_OK is returned and the NodeReader object set to \n** point to the first entry on the node (if any). Otherwise, an SQLite\n** error code is returned.\n*/\nstatic int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){\n  memset(p, 0, sizeof(NodeReader));\n  p->aNode = aNode;\n  p->nNode = nNode;\n\n  /* Figure out if this is a leaf or an internal node. */\n  if( p->aNode[0] ){\n    /* An internal node. */\n    p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);\n  }else{\n    p->iOff = 1;\n  }\n\n  return nodeReaderNext(p);\n}\n\n/*\n** This function is called while writing an FTS segment each time a leaf o\n** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed\n** to be greater than the largest key on the node just written, but smaller\n** than or equal to the first key that will be written to the next leaf\n** node.\n**\n** The block id of the leaf node just written to disk may be found in\n** (pWriter->aNodeWriter[0].iBlock) when this function is called.\n*/\nstatic int fts3IncrmergePush(\n  Fts3Table *p,                   /* Fts3 table handle */\n  IncrmergeWriter *pWriter,       /* Writer object */\n  const char *zTerm,              /* Term to write to internal node */\n  int nTerm                       /* Bytes at zTerm */\n){\n  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;\n  int iLayer;\n\n  assert( nTerm>0 );\n  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){\n    sqlite3_int64 iNextPtr = 0;\n    NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];\n    int rc = SQLITE_OK;\n    int nPrefix;\n    int nSuffix;\n    int nSpace;\n\n    /* Figure out how much space the key will consume if it is written to\n    ** the current node of layer iLayer. Due to the prefix compression, \n    ** the space required changes depending on which node the key is to\n    ** be added to.  */\n    nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);\n    nSuffix = nTerm - nPrefix;\n    nSpace  = sqlite3Fts3VarintLen(nPrefix);\n    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n\n    if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ \n      /* If the current node of layer iLayer contains zero keys, or if adding\n      ** the key to it will not cause it to grow to larger than nNodeSize \n      ** bytes in size, write the key here.  */\n\n      Blob *pBlk = &pNode->block;\n      if( pBlk->n==0 ){\n        blobGrowBuffer(pBlk, p->nNodeSize, &rc);\n        if( rc==SQLITE_OK ){\n          pBlk->a[0] = (char)iLayer;\n          pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);\n        }\n      }\n      blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);\n      blobGrowBuffer(&pNode->key, nTerm, &rc);\n\n      if( rc==SQLITE_OK ){\n        if( pNode->key.n ){\n          pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);\n        }\n        pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);\n        memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);\n        pBlk->n += nSuffix;\n\n        memcpy(pNode->key.a, zTerm, nTerm);\n        pNode->key.n = nTerm;\n      }\n    }else{\n      /* Otherwise, flush the current node of layer iLayer to disk.\n      ** Then allocate a new, empty sibling node. The key will be written\n      ** into the parent of this node. */\n      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);\n\n      assert( pNode->block.nAlloc>=p->nNodeSize );\n      pNode->block.a[0] = (char)iLayer;\n      pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);\n\n      iNextPtr = pNode->iBlock;\n      pNode->iBlock++;\n      pNode->key.n = 0;\n    }\n\n    if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;\n    iPtr = iNextPtr;\n  }\n\n  assert( 0 );\n  return 0;\n}\n\n/*\n** Append a term and (optionally) doclist to the FTS segment node currently\n** stored in blob *pNode. The node need not contain any terms, but the\n** header must be written before this function is called.\n**\n** A node header is a single 0x00 byte for a leaf node, or a height varint\n** followed by the left-hand-child varint for an internal node.\n**\n** The term to be appended is passed via arguments zTerm/nTerm. For a \n** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal\n** node, both aDoclist and nDoclist must be passed 0.\n**\n** If the size of the value in blob pPrev is zero, then this is the first\n** term written to the node. Otherwise, pPrev contains a copy of the \n** previous term. Before this function returns, it is updated to contain a\n** copy of zTerm/nTerm.\n**\n** It is assumed that the buffer associated with pNode is already large\n** enough to accommodate the new entry. The buffer associated with pPrev\n** is extended by this function if requrired.\n**\n** If an error (i.e. OOM condition) occurs, an SQLite error code is\n** returned. Otherwise, SQLITE_OK.\n*/\nstatic int fts3AppendToNode(\n  Blob *pNode,                    /* Current node image to append to */\n  Blob *pPrev,                    /* Buffer containing previous term written */\n  const char *zTerm,              /* New term to write */\n  int nTerm,                      /* Size of zTerm in bytes */\n  const char *aDoclist,           /* Doclist (or NULL) to write */\n  int nDoclist                    /* Size of aDoclist in bytes */ \n){\n  int rc = SQLITE_OK;             /* Return code */\n  int bFirst = (pPrev->n==0);     /* True if this is the first term written */\n  int nPrefix;                    /* Size of term prefix in bytes */\n  int nSuffix;                    /* Size of term suffix in bytes */\n\n  /* Node must have already been started. There must be a doclist for a\n  ** leaf node, and there must not be a doclist for an internal node.  */\n  assert( pNode->n>0 );\n  assert( (pNode->a[0]=='\\0')==(aDoclist!=0) );\n\n  blobGrowBuffer(pPrev, nTerm, &rc);\n  if( rc!=SQLITE_OK ) return rc;\n\n  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);\n  nSuffix = nTerm - nPrefix;\n  memcpy(pPrev->a, zTerm, nTerm);\n  pPrev->n = nTerm;\n\n  if( bFirst==0 ){\n    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);\n  }\n  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);\n  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);\n  pNode->n += nSuffix;\n\n  if( aDoclist ){\n    pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);\n    memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);\n    pNode->n += nDoclist;\n  }\n\n  assert( pNode->n<=pNode->nAlloc );\n\n  return SQLITE_OK;\n}\n\n/*\n** Append the current term and doclist pointed to by cursor pCsr to the\n** appendable b-tree segment opened for writing by pWriter.\n**\n** Return SQLITE_OK if successful, or an SQLite error code otherwise.\n*/\nstatic int fts3IncrmergeAppend(\n  Fts3Table *p,                   /* Fts3 table handle */\n  IncrmergeWriter *pWriter,       /* Writer object */\n  Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */\n){\n  const char *zTerm = pCsr->zTerm;\n  int nTerm = pCsr->nTerm;\n  const char *aDoclist = pCsr->aDoclist;\n  int nDoclist = pCsr->nDoclist;\n  int rc = SQLITE_OK;           /* Return code */\n  int nSpace;                   /* Total space in bytes required on leaf */\n  int nPrefix;                  /* Size of prefix shared with previous term */\n  int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */\n  NodeWriter *pLeaf;            /* Object used to write leaf nodes */\n\n  pLeaf = &pWriter->aNodeWriter[0];\n  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);\n  nSuffix = nTerm - nPrefix;\n\n  nSpace  = sqlite3Fts3VarintLen(nPrefix);\n  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;\n\n  /* If the current block is not empty, and if adding this term/doclist\n  ** to the current block would make it larger than Fts3Table.nNodeSize\n  ** bytes, write this block out to the database. */\n  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){\n    rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);\n    pWriter->nWork++;\n\n    /* Add the current term to the parent node. The term added to the \n    ** parent must:\n    **\n    **   a) be greater than the largest term on the leaf node just written\n    **      to the database (still available in pLeaf->key), and\n    **\n    **   b) be less than or equal to the term about to be added to the new\n    **      leaf node (zTerm/nTerm).\n    **\n    ** In other words, it must be the prefix of zTerm 1 byte longer than\n    ** the common prefix (if any) of zTerm and pWriter->zTerm.\n    */\n    if( rc==SQLITE_OK ){\n      rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);\n    }\n\n    /* Advance to the next output block */\n    pLeaf->iBlock++;\n    pLeaf->key.n = 0;\n    pLeaf->block.n = 0;\n\n    nSuffix = nTerm;\n    nSpace  = 1;\n    nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;\n    nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;\n  }\n\n  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);\n\n  if( rc==SQLITE_OK ){\n    if( pLeaf->block.n==0 ){\n      pLeaf->block.n = 1;\n      pLeaf->block.a[0] = '\\0';\n    }\n    rc = fts3AppendToNode(\n        &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist\n    );\n  }\n\n  return rc;\n}\n\n/*\n** This function is called to release all dynamic resources held by the\n** merge-writer object pWriter, and if no error has occurred, to flush\n** all outstanding node buffers held by pWriter to disk.\n**\n** If *pRc is not SQLITE_OK when this function is called, then no attempt\n** is made to write any data to disk. Instead, this function serves only\n** to release outstanding resources.\n**\n** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while\n** flushing buffers to disk, *pRc is set to an SQLite error code before\n** returning.\n*/\nstatic void fts3IncrmergeRelease(\n  Fts3Table *p,                   /* FTS3 table handle */\n  IncrmergeWriter *pWriter,       /* Merge-writer object */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  int i;                          /* Used to iterate through non-root layers */\n  int iRoot;                      /* Index of root in pWriter->aNodeWriter */\n  NodeWriter *pRoot;              /* NodeWriter for root node */\n  int rc = *pRc;                  /* Error code */\n\n  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment \n  ** root node. If the segment fits entirely on a single leaf node, iRoot\n  ** will be set to 0. If the root node is the parent of the leaves, iRoot\n  ** will be 1. And so on.  */\n  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){\n    NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];\n    if( pNode->block.n>0 ) break;\n    assert( *pRc || pNode->block.nAlloc==0 );\n    assert( *pRc || pNode->key.nAlloc==0 );\n    sqlite3_free(pNode->block.a);\n    sqlite3_free(pNode->key.a);\n  }\n\n  /* Empty output segment. This is a no-op. */\n  if( iRoot<0 ) return;\n\n  /* The entire output segment fits on a single node. Normally, this means\n  ** the node would be stored as a blob in the \"root\" column of the %_segdir\n  ** table. However, this is not permitted in this case. The problem is that \n  ** space has already been reserved in the %_segments table, and so the \n  ** start_block and end_block fields of the %_segdir table must be populated. \n  ** And, by design or by accident, released versions of FTS cannot handle \n  ** segments that fit entirely on the root node with start_block!=0.\n  **\n  ** Instead, create a synthetic root node that contains nothing but a \n  ** pointer to the single content node. So that the segment consists of a\n  ** single leaf and a single interior (root) node.\n  **\n  ** Todo: Better might be to defer allocating space in the %_segments \n  ** table until we are sure it is needed.\n  */\n  if( iRoot==0 ){\n    Blob *pBlock = &pWriter->aNodeWriter[1].block;\n    blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);\n    if( rc==SQLITE_OK ){\n      pBlock->a[0] = 0x01;\n      pBlock->n = 1 + sqlite3Fts3PutVarint(\n          &pBlock->a[1], pWriter->aNodeWriter[0].iBlock\n      );\n    }\n    iRoot = 1;\n  }\n  pRoot = &pWriter->aNodeWriter[iRoot];\n\n  /* Flush all currently outstanding nodes to disk. */\n  for(i=0; i<iRoot; i++){\n    NodeWriter *pNode = &pWriter->aNodeWriter[i];\n    if( pNode->block.n>0 && rc==SQLITE_OK ){\n      rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);\n    }\n    sqlite3_free(pNode->block.a);\n    sqlite3_free(pNode->key.a);\n  }\n\n  /* Write the %_segdir record. */\n  if( rc==SQLITE_OK ){\n    rc = fts3WriteSegdir(p, \n        pWriter->iAbsLevel+1,               /* level */\n        pWriter->iIdx,                      /* idx */\n        pWriter->iStart,                    /* start_block */\n        pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */\n        pWriter->iEnd,                      /* end_block */\n        pRoot->block.a, pRoot->block.n      /* root */\n    );\n  }\n  sqlite3_free(pRoot->block.a);\n  sqlite3_free(pRoot->key.a);\n\n  *pRc = rc;\n}\n\n/*\n** Compare the term in buffer zLhs (size in bytes nLhs) with that in\n** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of\n** the other, it is considered to be smaller than the other.\n**\n** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve\n** if it is greater.\n*/\nstatic int fts3TermCmp(\n  const char *zLhs, int nLhs,     /* LHS of comparison */\n  const char *zRhs, int nRhs      /* RHS of comparison */\n){\n  int nCmp = MIN(nLhs, nRhs);\n  int res;\n\n  res = memcmp(zLhs, zRhs, nCmp);\n  if( res==0 ) res = nLhs - nRhs;\n\n  return res;\n}\n\n\n/*\n** Query to see if the entry in the %_segments table with blockid iEnd is \n** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before\n** returning. Otherwise, set *pbRes to 0. \n**\n** Or, if an error occurs while querying the database, return an SQLite \n** error code. The final value of *pbRes is undefined in this case.\n**\n** This is used to test if a segment is an \"appendable\" segment. If it\n** is, then a NULL entry has been inserted into the %_segments table\n** with blockid %_segdir.end_block.\n*/\nstatic int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){\n  int bRes = 0;                   /* Result to set *pbRes to */\n  sqlite3_stmt *pCheck = 0;       /* Statement to query database with */\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pCheck, 1, iEnd);\n    if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;\n    rc = sqlite3_reset(pCheck);\n  }\n  \n  *pbRes = bRes;\n  return rc;\n}\n\n/*\n** This function is called when initializing an incremental-merge operation.\n** It checks if the existing segment with index value iIdx at absolute level \n** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the\n** merge-writer object *pWriter is initialized to write to it.\n**\n** An existing segment can be appended to by an incremental merge if:\n**\n**   * It was initially created as an appendable segment (with all required\n**     space pre-allocated), and\n**\n**   * The first key read from the input (arguments zKey and nKey) is \n**     greater than the largest key currently stored in the potential\n**     output segment.\n*/\nstatic int fts3IncrmergeLoad(\n  Fts3Table *p,                   /* Fts3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */\n  int iIdx,                       /* Index of candidate output segment */\n  const char *zKey,               /* First key to write */\n  int nKey,                       /* Number of bytes in nKey */\n  IncrmergeWriter *pWriter        /* Populate this object */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */\n    sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */\n    sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */\n    const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */\n    int nRoot = 0;                /* Size of aRoot[] in bytes */\n    int rc2;                      /* Return code from sqlite3_reset() */\n    int bAppendable = 0;          /* Set to true if segment is appendable */\n\n    /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */\n    sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);\n    sqlite3_bind_int(pSelect, 2, iIdx);\n    if( sqlite3_step(pSelect)==SQLITE_ROW ){\n      iStart = sqlite3_column_int64(pSelect, 1);\n      iLeafEnd = sqlite3_column_int64(pSelect, 2);\n      iEnd = sqlite3_column_int64(pSelect, 3);\n      nRoot = sqlite3_column_bytes(pSelect, 4);\n      aRoot = sqlite3_column_blob(pSelect, 4);\n    }else{\n      return sqlite3_reset(pSelect);\n    }\n\n    /* Check for the zero-length marker in the %_segments table */\n    rc = fts3IsAppendable(p, iEnd, &bAppendable);\n\n    /* Check that zKey/nKey is larger than the largest key the candidate */\n    if( rc==SQLITE_OK && bAppendable ){\n      char *aLeaf = 0;\n      int nLeaf = 0;\n\n      rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);\n      if( rc==SQLITE_OK ){\n        NodeReader reader;\n        for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);\n            rc==SQLITE_OK && reader.aNode;\n            rc = nodeReaderNext(&reader)\n        ){\n          assert( reader.aNode );\n        }\n        if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){\n          bAppendable = 0;\n        }\n        nodeReaderRelease(&reader);\n      }\n      sqlite3_free(aLeaf);\n    }\n\n    if( rc==SQLITE_OK && bAppendable ){\n      /* It is possible to append to this segment. Set up the IncrmergeWriter\n      ** object to do so.  */\n      int i;\n      int nHeight = (int)aRoot[0];\n      NodeWriter *pNode;\n\n      pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;\n      pWriter->iStart = iStart;\n      pWriter->iEnd = iEnd;\n      pWriter->iAbsLevel = iAbsLevel;\n      pWriter->iIdx = iIdx;\n\n      for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){\n        pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;\n      }\n\n      pNode = &pWriter->aNodeWriter[nHeight];\n      pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;\n      blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);\n      if( rc==SQLITE_OK ){\n        memcpy(pNode->block.a, aRoot, nRoot);\n        pNode->block.n = nRoot;\n      }\n\n      for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){\n        NodeReader reader;\n        pNode = &pWriter->aNodeWriter[i];\n\n        rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);\n        while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);\n        blobGrowBuffer(&pNode->key, reader.term.n, &rc);\n        if( rc==SQLITE_OK ){\n          memcpy(pNode->key.a, reader.term.a, reader.term.n);\n          pNode->key.n = reader.term.n;\n          if( i>0 ){\n            char *aBlock = 0;\n            int nBlock = 0;\n            pNode = &pWriter->aNodeWriter[i-1];\n            pNode->iBlock = reader.iChild;\n            rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);\n            blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);\n            if( rc==SQLITE_OK ){\n              memcpy(pNode->block.a, aBlock, nBlock);\n              pNode->block.n = nBlock;\n            }\n            sqlite3_free(aBlock);\n          }\n        }\n        nodeReaderRelease(&reader);\n      }\n    }\n\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\n/*\n** Determine the largest segment index value that exists within absolute\n** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus\n** one before returning SQLITE_OK. Or, if there are no segments at all \n** within level iAbsLevel, set *piIdx to zero.\n**\n** If an error occurs, return an SQLite error code. The final value of\n** *piIdx is undefined in this case.\n*/\nstatic int fts3IncrmergeOutputIdx( \n  Fts3Table *p,                   /* FTS Table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */\n  int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */\n){\n  int rc;\n  sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */\n\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);\n    sqlite3_step(pOutputIdx);\n    *piIdx = sqlite3_column_int(pOutputIdx, 0);\n    rc = sqlite3_reset(pOutputIdx);\n  }\n\n  return rc;\n}\n\n/* \n** Allocate an appendable output segment on absolute level iAbsLevel+1\n** with idx value iIdx.\n**\n** In the %_segdir table, a segment is defined by the values in three\n** columns:\n**\n**     start_block\n**     leaves_end_block\n**     end_block\n**\n** When an appendable segment is allocated, it is estimated that the\n** maximum number of leaf blocks that may be required is the sum of the\n** number of leaf blocks consumed by the input segments, plus the number\n** of input segments, multiplied by two. This value is stored in stack \n** variable nLeafEst.\n**\n** A total of 16*nLeafEst blocks are allocated when an appendable segment\n** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous\n** array of leaf nodes starts at the first block allocated. The array\n** of interior nodes that are parents of the leaf nodes start at block\n** (start_block + (1 + end_block - start_block) / 16). And so on.\n**\n** In the actual code below, the value \"16\" is replaced with the \n** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.\n*/\nstatic int fts3IncrmergeWriter( \n  Fts3Table *p,                   /* Fts3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */\n  int iIdx,                       /* Index of new output segment */\n  Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */\n  IncrmergeWriter *pWriter        /* Populate this object */\n){\n  int rc;                         /* Return Code */\n  int i;                          /* Iterator variable */\n  int nLeafEst = 0;               /* Blocks allocated for leaf nodes */\n  sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */\n  sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */\n\n  /* Calculate nLeafEst. */\n  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);\n    sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);\n    if( SQLITE_ROW==sqlite3_step(pLeafEst) ){\n      nLeafEst = sqlite3_column_int(pLeafEst, 0);\n    }\n    rc = sqlite3_reset(pLeafEst);\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Calculate the first block to use in the output segment */\n  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);\n  if( rc==SQLITE_OK ){\n    if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){\n      pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);\n      pWriter->iEnd = pWriter->iStart - 1;\n      pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;\n    }\n    rc = sqlite3_reset(pFirstBlock);\n  }\n  if( rc!=SQLITE_OK ) return rc;\n\n  /* Insert the marker in the %_segments table to make sure nobody tries\n  ** to steal the space just allocated. This is also used to identify \n  ** appendable segments.  */\n  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);\n  if( rc!=SQLITE_OK ) return rc;\n\n  pWriter->iAbsLevel = iAbsLevel;\n  pWriter->nLeafEst = nLeafEst;\n  pWriter->iIdx = iIdx;\n\n  /* Set up the array of NodeWriter objects */\n  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){\n    pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Remove an entry from the %_segdir table. This involves running the \n** following two statements:\n**\n**   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx\n**   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx\n**\n** The DELETE statement removes the specific %_segdir level. The UPDATE \n** statement ensures that the remaining segments have contiguously allocated\n** idx values.\n*/\nstatic int fts3RemoveSegdirEntry(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */\n  int iIdx                        /* Index of %_segdir entry to delete */\n){\n  int rc;                         /* Return code */\n  sqlite3_stmt *pDelete = 0;      /* DELETE statement */\n\n  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pDelete, 1, iAbsLevel);\n    sqlite3_bind_int(pDelete, 2, iIdx);\n    sqlite3_step(pDelete);\n    rc = sqlite3_reset(pDelete);\n  }\n\n  return rc;\n}\n\n/*\n** One or more segments have just been removed from absolute level iAbsLevel.\n** Update the 'idx' values of the remaining segments in the level so that\n** the idx values are a contiguous sequence starting from 0.\n*/\nstatic int fts3RepackSegdirLevel(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel         /* Absolute level to repack */\n){\n  int rc;                         /* Return code */\n  int *aIdx = 0;                  /* Array of remaining idx values */\n  int nIdx = 0;                   /* Valid entries in aIdx[] */\n  int nAlloc = 0;                 /* Allocated size of aIdx[] */\n  int i;                          /* Iterator variable */\n  sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */\n  sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int64(pSelect, 1, iAbsLevel);\n    while( SQLITE_ROW==sqlite3_step(pSelect) ){\n      if( nIdx>=nAlloc ){\n        int *aNew;\n        nAlloc += 16;\n        aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));\n        if( !aNew ){\n          rc = SQLITE_NOMEM;\n          break;\n        }\n        aIdx = aNew;\n      }\n      aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);\n    }\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);\n  }\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pUpdate, 2, iAbsLevel);\n  }\n\n  assert( p->bIgnoreSavepoint==0 );\n  p->bIgnoreSavepoint = 1;\n  for(i=0; rc==SQLITE_OK && i<nIdx; i++){\n    if( aIdx[i]!=i ){\n      sqlite3_bind_int(pUpdate, 3, aIdx[i]);\n      sqlite3_bind_int(pUpdate, 1, i);\n      sqlite3_step(pUpdate);\n      rc = sqlite3_reset(pUpdate);\n    }\n  }\n  p->bIgnoreSavepoint = 0;\n\n  sqlite3_free(aIdx);\n  return rc;\n}\n\nstatic void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){\n  pNode->a[0] = (char)iHeight;\n  if( iChild ){\n    assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );\n    pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);\n  }else{\n    assert( pNode->nAlloc>=1 );\n    pNode->n = 1;\n  }\n}\n\n/*\n** The first two arguments are a pointer to and the size of a segment b-tree\n** node. The node may be a leaf or an internal node.\n**\n** This function creates a new node image in blob object *pNew by copying\n** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)\n** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.\n*/\nstatic int fts3TruncateNode(\n  const char *aNode,              /* Current node image */\n  int nNode,                      /* Size of aNode in bytes */\n  Blob *pNew,                     /* OUT: Write new node image here */\n  const char *zTerm,              /* Omit all terms smaller than this */\n  int nTerm,                      /* Size of zTerm in bytes */\n  sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */\n){\n  NodeReader reader;              /* Reader object */\n  Blob prev = {0, 0, 0};          /* Previous term written to new node */\n  int rc = SQLITE_OK;             /* Return code */\n  int bLeaf = aNode[0]=='\\0';     /* True for a leaf node */\n\n  /* Allocate required output space */\n  blobGrowBuffer(pNew, nNode, &rc);\n  if( rc!=SQLITE_OK ) return rc;\n  pNew->n = 0;\n\n  /* Populate new node buffer */\n  for(rc = nodeReaderInit(&reader, aNode, nNode); \n      rc==SQLITE_OK && reader.aNode; \n      rc = nodeReaderNext(&reader)\n  ){\n    if( pNew->n==0 ){\n      int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);\n      if( res<0 || (bLeaf==0 && res==0) ) continue;\n      fts3StartNode(pNew, (int)aNode[0], reader.iChild);\n      *piBlock = reader.iChild;\n    }\n    rc = fts3AppendToNode(\n        pNew, &prev, reader.term.a, reader.term.n,\n        reader.aDoclist, reader.nDoclist\n    );\n    if( rc!=SQLITE_OK ) break;\n  }\n  if( pNew->n==0 ){\n    fts3StartNode(pNew, (int)aNode[0], reader.iChild);\n    *piBlock = reader.iChild;\n  }\n  assert( pNew->n<=pNew->nAlloc );\n\n  nodeReaderRelease(&reader);\n  sqlite3_free(prev.a);\n  return rc;\n}\n\n/*\n** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute \n** level iAbsLevel. This may involve deleting entries from the %_segments\n** table, and modifying existing entries in both the %_segments and %_segdir\n** tables.\n**\n** SQLITE_OK is returned if the segment is updated successfully. Or an\n** SQLite error code otherwise.\n*/\nstatic int fts3TruncateSegment(\n  Fts3Table *p,                   /* FTS3 table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */\n  int iIdx,                       /* Index within level of segment to modify */\n  const char *zTerm,              /* Remove terms smaller than this */\n  int nTerm                      /* Number of bytes in buffer zTerm */\n){\n  int rc = SQLITE_OK;             /* Return code */\n  Blob root = {0,0,0};            /* New root page image */\n  Blob block = {0,0,0};           /* Buffer used for any other block */\n  sqlite3_int64 iBlock = 0;       /* Block id */\n  sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */\n  sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */\n  sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */\n\n  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;                      /* sqlite3_reset() return code */\n    sqlite3_bind_int64(pFetch, 1, iAbsLevel);\n    sqlite3_bind_int(pFetch, 2, iIdx);\n    if( SQLITE_ROW==sqlite3_step(pFetch) ){\n      const char *aRoot = sqlite3_column_blob(pFetch, 4);\n      int nRoot = sqlite3_column_bytes(pFetch, 4);\n      iOldStart = sqlite3_column_int64(pFetch, 1);\n      rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);\n    }\n    rc2 = sqlite3_reset(pFetch);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  while( rc==SQLITE_OK && iBlock ){\n    char *aBlock = 0;\n    int nBlock = 0;\n    iNewStart = iBlock;\n\n    rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);\n    if( rc==SQLITE_OK ){\n      rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);\n    }\n    if( rc==SQLITE_OK ){\n      rc = fts3WriteSegment(p, iNewStart, block.a, block.n);\n    }\n    sqlite3_free(aBlock);\n  }\n\n  /* Variable iNewStart now contains the first valid leaf node. */\n  if( rc==SQLITE_OK && iNewStart ){\n    sqlite3_stmt *pDel = 0;\n    rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pDel, 1, iOldStart);\n      sqlite3_bind_int64(pDel, 2, iNewStart-1);\n      sqlite3_step(pDel);\n      rc = sqlite3_reset(pDel);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    sqlite3_stmt *pChomp = 0;\n    rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);\n    if( rc==SQLITE_OK ){\n      sqlite3_bind_int64(pChomp, 1, iNewStart);\n      sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);\n      sqlite3_bind_int64(pChomp, 3, iAbsLevel);\n      sqlite3_bind_int(pChomp, 4, iIdx);\n      sqlite3_step(pChomp);\n      rc = sqlite3_reset(pChomp);\n    }\n  }\n\n  sqlite3_free(root.a);\n  sqlite3_free(block.a);\n  return rc;\n}\n\n/*\n** This function is called after an incrmental-merge operation has run to\n** merge (or partially merge) two or more segments from absolute level\n** iAbsLevel.\n**\n** Each input segment is either removed from the db completely (if all of\n** its data was copied to the output segment by the incrmerge operation)\n** or modified in place so that it no longer contains those entries that\n** have been duplicated in the output segment.\n*/\nstatic int fts3IncrmergeChomp(\n  Fts3Table *p,                   /* FTS table handle */\n  sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */\n  Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */\n  int *pnRem                      /* Number of segments not deleted */\n){\n  int i;\n  int nRem = 0;\n  int rc = SQLITE_OK;\n\n  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){\n    Fts3SegReader *pSeg = 0;\n    int j;\n\n    /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding\n    ** somewhere in the pCsr->apSegment[] array.  */\n    for(j=0; ALWAYS(j<pCsr->nSegment); j++){\n      pSeg = pCsr->apSegment[j];\n      if( pSeg->iIdx==i ) break;\n    }\n    assert( j<pCsr->nSegment && pSeg->iIdx==i );\n\n    if( pSeg->aNode==0 ){\n      /* Seg-reader is at EOF. Remove the entire input segment. */\n      rc = fts3DeleteSegment(p, pSeg);\n      if( rc==SQLITE_OK ){\n        rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);\n      }\n      *pnRem = 0;\n    }else{\n      /* The incremental merge did not copy all the data from this \n      ** segment to the upper level. The segment is modified in place\n      ** so that it contains no keys smaller than zTerm/nTerm. */ \n      const char *zTerm = pSeg->zTerm;\n      int nTerm = pSeg->nTerm;\n      rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);\n      nRem++;\n    }\n  }\n\n  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){\n    rc = fts3RepackSegdirLevel(p, iAbsLevel);\n  }\n\n  *pnRem = nRem;\n  return rc;\n}\n\n/*\n** Store an incr-merge hint in the database.\n*/\nstatic int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){\n  sqlite3_stmt *pReplace = 0;\n  int rc;                         /* Return code */\n\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);\n    sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);\n    sqlite3_step(pReplace);\n    rc = sqlite3_reset(pReplace);\n  }\n\n  return rc;\n}\n\n/*\n** Load an incr-merge hint from the database. The incr-merge hint, if one \n** exists, is stored in the rowid==1 row of the %_stat table.\n**\n** If successful, populate blob *pHint with the value read from the %_stat\n** table and return SQLITE_OK. Otherwise, if an error occurs, return an\n** SQLite error code.\n*/\nstatic int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){\n  sqlite3_stmt *pSelect = 0;\n  int rc;\n\n  pHint->n = 0;\n  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);\n    if( SQLITE_ROW==sqlite3_step(pSelect) ){\n      const char *aHint = sqlite3_column_blob(pSelect, 0);\n      int nHint = sqlite3_column_bytes(pSelect, 0);\n      if( aHint ){\n        blobGrowBuffer(pHint, nHint, &rc);\n        if( rc==SQLITE_OK ){\n          memcpy(pHint->a, aHint, nHint);\n          pHint->n = nHint;\n        }\n      }\n    }\n    rc2 = sqlite3_reset(pSelect);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  return rc;\n}\n\n/*\n** If *pRc is not SQLITE_OK when this function is called, it is a no-op.\n** Otherwise, append an entry to the hint stored in blob *pHint. Each entry\n** consists of two varints, the absolute level number of the input segments \n** and the number of input segments.\n**\n** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,\n** set *pRc to an SQLite error code before returning.\n*/\nstatic void fts3IncrmergeHintPush(\n  Blob *pHint,                    /* Hint blob to append to */\n  i64 iAbsLevel,                  /* First varint to store in hint */\n  int nInput,                     /* Second varint to store in hint */\n  int *pRc                        /* IN/OUT: Error code */\n){\n  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);\n  if( *pRc==SQLITE_OK ){\n    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);\n    pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);\n  }\n}\n\n/*\n** Read the last entry (most recently pushed) from the hint blob *pHint\n** and then remove the entry. Write the two values read to *piAbsLevel and \n** *pnInput before returning.\n**\n** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does\n** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.\n*/\nstatic int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){\n  const int nHint = pHint->n;\n  int i;\n\n  i = pHint->n-2;\n  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;\n  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;\n\n  pHint->n = i;\n  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);\n  i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);\n  if( i!=nHint ) return SQLITE_CORRUPT_VTAB;\n\n  return SQLITE_OK;\n}\n\n\n/*\n** Attempt an incremental merge that writes nMerge leaf blocks.\n**\n** Incremental merges happen nMin segments at a time. The two\n** segments to be merged are the nMin oldest segments (the ones with\n** the smallest indexes) in the highest level that contains at least\n** nMin segments. Multiple merges might occur in an attempt to write the \n** quota of nMerge leaf blocks.\n*/\nSQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){\n  int rc;                         /* Return code */\n  int nRem = nMerge;              /* Number of leaf pages yet to  be written */\n  Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */\n  Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */\n  IncrmergeWriter *pWriter;       /* Writer object */\n  int nSeg = 0;                   /* Number of input segments */\n  sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */\n  Blob hint = {0, 0, 0};          /* Hint read from %_stat table */\n  int bDirtyHint = 0;             /* True if blob 'hint' has been modified */\n\n  /* Allocate space for the cursor, filter and writer objects */\n  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);\n  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);\n  if( !pWriter ) return SQLITE_NOMEM;\n  pFilter = (Fts3SegFilter *)&pWriter[1];\n  pCsr = (Fts3MultiSegReader *)&pFilter[1];\n\n  rc = fts3IncrmergeHintLoad(p, &hint);\n  while( rc==SQLITE_OK && nRem>0 ){\n    const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;\n    sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */\n    int bUseHint = 0;             /* True if attempting to append */\n\n    /* Search the %_segdir table for the absolute level with the smallest\n    ** relative level number that contains at least nMin segments, if any.\n    ** If one is found, set iAbsLevel to the absolute level number and\n    ** nSeg to nMin. If no level with at least nMin segments can be found, \n    ** set nSeg to -1.\n    */\n    rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);\n    sqlite3_bind_int(pFindLevel, 1, nMin);\n    if( sqlite3_step(pFindLevel)==SQLITE_ROW ){\n      iAbsLevel = sqlite3_column_int64(pFindLevel, 0);\n      nSeg = nMin;\n    }else{\n      nSeg = -1;\n    }\n    rc = sqlite3_reset(pFindLevel);\n\n    /* If the hint read from the %_stat table is not empty, check if the\n    ** last entry in it specifies a relative level smaller than or equal\n    ** to the level identified by the block above (if any). If so, this \n    ** iteration of the loop will work on merging at the hinted level.\n    */\n    if( rc==SQLITE_OK && hint.n ){\n      int nHint = hint.n;\n      sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */\n      int nHintSeg = 0;                     /* Hint number of segments */\n\n      rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);\n      if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){\n        iAbsLevel = iHintAbsLevel;\n        nSeg = nHintSeg;\n        bUseHint = 1;\n        bDirtyHint = 1;\n      }else{\n        /* This undoes the effect of the HintPop() above - so that no entry\n        ** is removed from the hint blob.  */\n        hint.n = nHint;\n      }\n    }\n\n    /* If nSeg is less that zero, then there is no level with at least\n    ** nMin segments and no hint in the %_stat table. No work to do.\n    ** Exit early in this case.  */\n    if( nSeg<0 ) break;\n\n    /* Open a cursor to iterate through the contents of the oldest nSeg \n    ** indexes of absolute level iAbsLevel. If this cursor is opened using \n    ** the 'hint' parameters, it is possible that there are less than nSeg\n    ** segments available in level iAbsLevel. In this case, no work is\n    ** done on iAbsLevel - fall through to the next iteration of the loop \n    ** to start work on some other level.  */\n    memset(pWriter, 0, nAlloc);\n    pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;\n    if( rc==SQLITE_OK ){\n      rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);\n    }\n    if( SQLITE_OK==rc && pCsr->nSegment==nSeg\n     && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))\n     && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))\n    ){\n      int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */\n      rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);\n      if( rc==SQLITE_OK ){\n        if( bUseHint && iIdx>0 ){\n          const char *zKey = pCsr->zTerm;\n          int nKey = pCsr->nTerm;\n          rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);\n        }else{\n          rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);\n        }\n      }\n\n      if( rc==SQLITE_OK && pWriter->nLeafEst ){\n        fts3LogMerge(nSeg, iAbsLevel);\n        do {\n          rc = fts3IncrmergeAppend(p, pWriter, pCsr);\n          if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);\n          if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;\n        }while( rc==SQLITE_ROW );\n\n        /* Update or delete the input segments */\n        if( rc==SQLITE_OK ){\n          nRem -= (1 + pWriter->nWork);\n          rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);\n          if( nSeg!=0 ){\n            bDirtyHint = 1;\n            fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);\n          }\n        }\n      }\n\n      fts3IncrmergeRelease(p, pWriter, &rc);\n    }\n\n    sqlite3Fts3SegReaderFinish(pCsr);\n  }\n\n  /* Write the hint values into the %_stat table for the next incr-merger */\n  if( bDirtyHint && rc==SQLITE_OK ){\n    rc = fts3IncrmergeHintStore(p, &hint);\n  }\n\n  sqlite3_free(pWriter);\n  sqlite3_free(hint.a);\n  return rc;\n}\n\n/*\n** Convert the text beginning at *pz into an integer and return\n** its value.  Advance *pz to point to the first character past\n** the integer.\n*/\nstatic int fts3Getint(const char **pz){\n  const char *z = *pz;\n  int i = 0;\n  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';\n  *pz = z;\n  return i;\n}\n\n/*\n** Process statements of the form:\n**\n**    INSERT INTO table(table) VALUES('merge=A,B');\n**\n** A and B are integers that decode to be the number of leaf pages\n** written for the merge, and the minimum number of segments on a level\n** before it will be selected for a merge, respectively.\n*/\nstatic int fts3DoIncrmerge(\n  Fts3Table *p,                   /* FTS3 table handle */\n  const char *zParam              /* Nul-terminated string containing \"A,B\" */\n){\n  int rc;\n  int nMin = (FTS3_MERGE_COUNT / 2);\n  int nMerge = 0;\n  const char *z = zParam;\n\n  /* Read the first integer value */\n  nMerge = fts3Getint(&z);\n\n  /* If the first integer value is followed by a ',',  read the second\n  ** integer value. */\n  if( z[0]==',' && z[1]!='\\0' ){\n    z++;\n    nMin = fts3Getint(&z);\n  }\n\n  if( z[0]!='\\0' || nMin<2 ){\n    rc = SQLITE_ERROR;\n  }else{\n    rc = SQLITE_OK;\n    if( !p->bHasStat ){\n      assert( p->bFts4==0 );\n      sqlite3Fts3CreateStatTable(&rc, p);\n    }\n    if( rc==SQLITE_OK ){\n      rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);\n    }\n    sqlite3Fts3SegmentsClose(p);\n  }\n  return rc;\n}\n\n/*\n** Process statements of the form:\n**\n**    INSERT INTO table(table) VALUES('automerge=X');\n**\n** where X is an integer.  X==0 means to turn automerge off.  X!=0 means\n** turn it on.  The setting is persistent.\n*/\nstatic int fts3DoAutoincrmerge(\n  Fts3Table *p,                   /* FTS3 table handle */\n  const char *zParam              /* Nul-terminated string containing boolean */\n){\n  int rc = SQLITE_OK;\n  sqlite3_stmt *pStmt = 0;\n  p->bAutoincrmerge = fts3Getint(&zParam)!=0;\n  if( !p->bHasStat ){\n    assert( p->bFts4==0 );\n    sqlite3Fts3CreateStatTable(&rc, p);\n    if( rc ) return rc;\n  }\n  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);\n  if( rc ) return rc;;\n  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);\n  sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);\n  sqlite3_step(pStmt);\n  rc = sqlite3_reset(pStmt);\n  return rc;\n}\n\n/*\n** Return a 64-bit checksum for the FTS index entry specified by the\n** arguments to this function.\n*/\nstatic u64 fts3ChecksumEntry(\n  const char *zTerm,              /* Pointer to buffer containing term */\n  int nTerm,                      /* Size of zTerm in bytes */\n  int iLangid,                    /* Language id for current row */\n  int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */\n  i64 iDocid,                     /* Docid for current row. */\n  int iCol,                       /* Column number */\n  int iPos                        /* Position */\n){\n  int i;\n  u64 ret = (u64)iDocid;\n\n  ret += (ret<<3) + iLangid;\n  ret += (ret<<3) + iIndex;\n  ret += (ret<<3) + iCol;\n  ret += (ret<<3) + iPos;\n  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];\n\n  return ret;\n}\n\n/*\n** Return a checksum of all entries in the FTS index that correspond to\n** language id iLangid. The checksum is calculated by XORing the checksums\n** of each individual entry (see fts3ChecksumEntry()) together.\n**\n** If successful, the checksum value is returned and *pRc set to SQLITE_OK.\n** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The\n** return value is undefined in this case.\n*/\nstatic u64 fts3ChecksumIndex(\n  Fts3Table *p,                   /* FTS3 table handle */\n  int iLangid,                    /* Language id to return cksum for */\n  int iIndex,                     /* Index to cksum (0..p->nIndex-1) */\n  int *pRc                        /* OUT: Return code */\n){\n  Fts3SegFilter filter;\n  Fts3MultiSegReader csr;\n  int rc;\n  u64 cksum = 0;\n\n  assert( *pRc==SQLITE_OK );\n\n  memset(&filter, 0, sizeof(filter));\n  memset(&csr, 0, sizeof(csr));\n  filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;\n  filter.flags |= FTS3_SEGMENT_SCAN;\n\n  rc = sqlite3Fts3SegReaderCursor(\n      p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr\n  );\n  if( rc==SQLITE_OK ){\n    rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);\n  }\n\n  if( rc==SQLITE_OK ){\n    while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){\n      char *pCsr = csr.aDoclist;\n      char *pEnd = &pCsr[csr.nDoclist];\n\n      i64 iDocid = 0;\n      i64 iCol = 0;\n      i64 iPos = 0;\n\n      pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);\n      while( pCsr<pEnd ){\n        i64 iVal = 0;\n        pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);\n        if( pCsr<pEnd ){\n          if( iVal==0 || iVal==1 ){\n            iCol = 0;\n            iPos = 0;\n            if( iVal ){\n              pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);\n            }else{\n              pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);\n              iDocid += iVal;\n            }\n          }else{\n            iPos += (iVal - 2);\n            cksum = cksum ^ fts3ChecksumEntry(\n                csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,\n                (int)iCol, (int)iPos\n            );\n          }\n        }\n      }\n    }\n  }\n  sqlite3Fts3SegReaderFinish(&csr);\n\n  *pRc = rc;\n  return cksum;\n}\n\n/*\n** Check if the contents of the FTS index match the current contents of the\n** content table. If no error occurs and the contents do match, set *pbOk\n** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk\n** to false before returning.\n**\n** If an error occurs (e.g. an OOM or IO error), return an SQLite error \n** code. The final value of *pbOk is undefined in this case.\n*/\nstatic int fts3IntegrityCheck(Fts3Table *p, int *pbOk){\n  int rc = SQLITE_OK;             /* Return code */\n  u64 cksum1 = 0;                 /* Checksum based on FTS index contents */\n  u64 cksum2 = 0;                 /* Checksum based on %_content contents */\n  sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */\n\n  /* This block calculates the checksum according to the FTS index. */\n  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);\n  if( rc==SQLITE_OK ){\n    int rc2;\n    sqlite3_bind_int(pAllLangid, 1, p->nIndex);\n    while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){\n      int iLangid = sqlite3_column_int(pAllLangid, 0);\n      int i;\n      for(i=0; i<p->nIndex; i++){\n        cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);\n      }\n    }\n    rc2 = sqlite3_reset(pAllLangid);\n    if( rc==SQLITE_OK ) rc = rc2;\n  }\n\n  /* This block calculates the checksum according to the %_content table */\n  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);\n  if( rc==SQLITE_OK ){\n    sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;\n    sqlite3_stmt *pStmt = 0;\n    char *zSql;\n   \n    zSql = sqlite3_mprintf(\"SELECT %s\" , p->zReadExprlist);\n    if( !zSql ){\n      rc = SQLITE_NOMEM;\n    }else{\n      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);\n      sqlite3_free(zSql);\n    }\n\n    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){\n      i64 iDocid = sqlite3_column_int64(pStmt, 0);\n      int iLang = langidFromSelect(p, pStmt);\n      int iCol;\n\n      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){\n        const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);\n        int nText = sqlite3_column_bytes(pStmt, iCol+1);\n        sqlite3_tokenizer_cursor *pT = 0;\n\n        rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);\n        while( rc==SQLITE_OK ){\n          char const *zToken;       /* Buffer containing token */\n          int nToken;               /* Number of bytes in token */\n          int iDum1, iDum2;         /* Dummy variables */\n          int iPos;                 /* Position of token in zText */\n\n          rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);\n          if( rc==SQLITE_OK ){\n            int i;\n            cksum2 = cksum2 ^ fts3ChecksumEntry(\n                zToken, nToken, iLang, 0, iDocid, iCol, iPos\n            );\n            for(i=1; i<p->nIndex; i++){\n              if( p->aIndex[i].nPrefix<=nToken ){\n                cksum2 = cksum2 ^ fts3ChecksumEntry(\n                  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos\n                );\n              }\n            }\n          }\n        }\n        if( pT ) pModule->xClose(pT);\n        if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n      }\n    }\n\n    sqlite3_finalize(pStmt);\n  }\n\n  *pbOk = (cksum1==cksum2);\n  return rc;\n}\n\n/*\n** Run the integrity-check. If no error occurs and the current contents of\n** the FTS index are correct, return SQLITE_OK. Or, if the contents of the\n** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.\n**\n** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite \n** error code.\n**\n** The integrity-check works as follows. For each token and indexed token\n** prefix in the document set, a 64-bit checksum is calculated (by code\n** in fts3ChecksumEntry()) based on the following:\n**\n**     + The index number (0 for the main index, 1 for the first prefix\n**       index etc.),\n**     + The token (or token prefix) text itself, \n**     + The language-id of the row it appears in,\n**     + The docid of the row it appears in,\n**     + The column it appears in, and\n**     + The tokens position within that column.\n**\n** The checksums for all entries in the index are XORed together to create\n** a single checksum for the entire index.\n**\n** The integrity-check code calculates the same checksum in two ways:\n**\n**     1. By scanning the contents of the FTS index, and \n**     2. By scanning and tokenizing the content table.\n**\n** If the two checksums are identical, the integrity-check is deemed to have\n** passed.\n*/\nstatic int fts3DoIntegrityCheck(\n  Fts3Table *p                    /* FTS3 table handle */\n){\n  int rc;\n  int bOk = 0;\n  rc = fts3IntegrityCheck(p, &bOk);\n  if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;\n  return rc;\n}\n\n/*\n** Handle a 'special' INSERT of the form:\n**\n**   \"INSERT INTO tbl(tbl) VALUES(<expr>)\"\n**\n** Argument pVal contains the result of <expr>. Currently the only \n** meaningful value to insert is the text 'optimize'.\n*/\nstatic int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){\n  int rc;                         /* Return Code */\n  const char *zVal = (const char *)sqlite3_value_text(pVal);\n  int nVal = sqlite3_value_bytes(pVal);\n\n  if( !zVal ){\n    return SQLITE_NOMEM;\n  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, \"optimize\", 8) ){\n    rc = fts3DoOptimize(p, 0);\n  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, \"rebuild\", 7) ){\n    rc = fts3DoRebuild(p);\n  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, \"integrity-check\", 15) ){\n    rc = fts3DoIntegrityCheck(p);\n  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, \"merge=\", 6) ){\n    rc = fts3DoIncrmerge(p, &zVal[6]);\n  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, \"automerge=\", 10) ){\n    rc = fts3DoAutoincrmerge(p, &zVal[10]);\n#ifdef SQLITE_TEST\n  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, \"nodesize=\", 9) ){\n    p->nNodeSize = atoi(&zVal[9]);\n    rc = SQLITE_OK;\n  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, \"maxpending=\", 9) ){\n    p->nMaxPendingData = atoi(&zVal[11]);\n    rc = SQLITE_OK;\n#endif\n  }else{\n    rc = SQLITE_ERROR;\n  }\n\n  return rc;\n}\n\n#ifndef SQLITE_DISABLE_FTS4_DEFERRED\n/*\n** Delete all cached deferred doclists. Deferred doclists are cached\n** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){\n  Fts3DeferredToken *pDef;\n  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){\n    fts3PendingListDelete(pDef->pList);\n    pDef->pList = 0;\n  }\n}\n\n/*\n** Free all entries in the pCsr->pDeffered list. Entries are added to \n** this list using sqlite3Fts3DeferToken().\n*/\nSQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){\n  Fts3DeferredToken *pDef;\n  Fts3DeferredToken *pNext;\n  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){\n    pNext = pDef->pNext;\n    fts3PendingListDelete(pDef->pList);\n    sqlite3_free(pDef);\n  }\n  pCsr->pDeferred = 0;\n}\n\n/*\n** Generate deferred-doclists for all tokens in the pCsr->pDeferred list\n** based on the row that pCsr currently points to.\n**\n** A deferred-doclist is like any other doclist with position information\n** included, except that it only contains entries for a single row of the\n** table, not for all rows.\n*/\nSQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){\n  int rc = SQLITE_OK;             /* Return code */\n  if( pCsr->pDeferred ){\n    int i;                        /* Used to iterate through table columns */\n    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */\n    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */\n  \n    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;\n    sqlite3_tokenizer *pT = p->pTokenizer;\n    sqlite3_tokenizer_module const *pModule = pT->pModule;\n   \n    assert( pCsr->isRequireSeek==0 );\n    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);\n  \n    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){\n      const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);\n      sqlite3_tokenizer_cursor *pTC = 0;\n  \n      rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);\n      while( rc==SQLITE_OK ){\n        char const *zToken;       /* Buffer containing token */\n        int nToken;               /* Number of bytes in token */\n        int iDum1, iDum2;         /* Dummy variables */\n        int iPos;                 /* Position of token in zText */\n  \n        rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);\n        for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){\n          Fts3PhraseToken *pPT = pDef->pToken;\n          if( (pDef->iCol>=p->nColumn || pDef->iCol==i)\n           && (pPT->bFirst==0 || iPos==0)\n           && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))\n           && (0==memcmp(zToken, pPT->z, pPT->n))\n          ){\n            fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);\n          }\n        }\n      }\n      if( pTC ) pModule->xClose(pTC);\n      if( rc==SQLITE_DONE ) rc = SQLITE_OK;\n    }\n  \n    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){\n      if( pDef->pList ){\n        rc = fts3PendingListAppendVarint(&pDef->pList, 0);\n      }\n    }\n  }\n\n  return rc;\n}\n\nSQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(\n  Fts3DeferredToken *p, \n  char **ppData, \n  int *pnData\n){\n  char *pRet;\n  int nSkip;\n  sqlite3_int64 dummy;\n\n  *ppData = 0;\n  *pnData = 0;\n\n  if( p->pList==0 ){\n    return SQLITE_OK;\n  }\n\n  pRet = (char *)sqlite3_malloc(p->pList->nData);\n  if( !pRet ) return SQLITE_NOMEM;\n\n  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);\n  *pnData = p->pList->nData - nSkip;\n  *ppData = pRet;\n  \n  memcpy(pRet, &p->pList->aData[nSkip], *pnData);\n  return SQLITE_OK;\n}\n\n/*\n** Add an entry for token pToken to the pCsr->pDeferred list.\n*/\nSQLITE_PRIVATE int sqlite3Fts3DeferToken(\n  Fts3Cursor *pCsr,               /* Fts3 table cursor */\n  Fts3PhraseToken *pToken,        /* Token to defer */\n  int iCol                        /* Column that token must appear in (or -1) */\n){\n  Fts3DeferredToken *pDeferred;\n  pDeferred = sqlite3_malloc(sizeof(*pDeferred));\n  if( !pDeferred ){\n    return SQLITE_NOMEM;\n  }\n  memset(pDeferred, 0, sizeof(*pDeferred));\n  pDeferred->pToken = pToken;\n  pDeferred->pNext = pCsr->pDeferred; \n  pDeferred->iCol = iCol;\n  pCsr->pDeferred = pDeferred;\n\n  assert( pToken->pDeferred==0 );\n  pToken->pDeferred = pDeferred;\n\n  return SQLITE_OK;\n}\n#endif\n\n/*\n** SQLite value pRowid contains the rowid of a row that may or may not be\n** present in the FTS3 table. If it is, delete it and adjust the contents\n** of subsiduary data structures accordingly.\n*/\nstatic int fts3DeleteByRowid(\n  Fts3Table *p, \n  sqlite3_value *pRowid, \n  int *pnDoc,\n  u32 *aSzDel\n){\n  int isEmpty = 0;\n  int rc = fts3IsEmpty(p, pRowid, &isEmpty);\n  if( rc==SQLITE_OK ){\n    if( isEmpty ){\n      /* Deleting this row means the whole table is empty. In this case\n      ** delete the contents of all three tables and throw away any\n      ** data in the pendingTerms hash table.  */\n      rc = fts3DeleteAll(p, 1);\n      *pnDoc = *pnDoc - 1;\n    }else{\n      fts3DeleteTerms(&rc, p, pRowid, aSzDel);\n      if( p->zContentTbl==0 ){\n        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);\n        if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;\n      }else{\n        *pnDoc = *pnDoc - 1;\n      }\n      if( p->bHasDocsize ){\n        fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);\n      }\n    }\n  }\n\n  return rc;\n}\n\n/*\n** This function does the work for the xUpdate method of FTS3 virtual\n** tables. The schema of the virtual table being:\n**\n**     CREATE TABLE <table name>( \n**       <user columns>,\n**       <table name> HIDDEN, \n**       docid HIDDEN, \n**       <langid> HIDDEN\n**     );\n**\n** \n*/\nSQLITE_PRIVATE int sqlite3Fts3UpdateMethod(\n  sqlite3_vtab *pVtab,            /* FTS3 vtab object */\n  int nArg,                       /* Size of argument array */\n  sqlite3_value **apVal,          /* Array of arguments */\n  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */\n){\n  Fts3Table *p = (Fts3Table *)pVtab;\n  int rc = SQLITE_OK;             /* Return Code */\n  int isRemove = 0;               /* True for an UPDATE or DELETE */\n  u32 *aSzIns = 0;                /* Sizes of inserted documents */\n  u32 *aSzDel;                    /* Sizes of deleted documents */\n  int nChng = 0;                  /* Net change in number of documents */\n  int bInsertDone = 0;\n\n  assert( p->pSegments==0 );\n  assert( \n      nArg==1                     /* DELETE operations */\n   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */\n  );\n\n  /* Check for a \"special\" INSERT operation. One of the form:\n  **\n  **   INSERT INTO xyz(xyz) VALUES('command');\n  */\n  if( nArg>1 \n   && sqlite3_value_type(apVal[0])==SQLITE_NULL \n   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL \n  ){\n    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);\n    goto update_out;\n  }\n\n  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){\n    rc = SQLITE_CONSTRAINT;\n    goto update_out;\n  }\n\n  /* Allocate space to hold the change in document sizes */\n  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );\n  if( aSzIns==0 ){\n    rc = SQLITE_NOMEM;\n    goto update_out;\n  }\n  aSzDel = &aSzIns[p->nColumn+1];\n  memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);\n\n  /* If this is an INSERT operation, or an UPDATE that modifies the rowid\n  ** value, then this operation requires constraint handling.\n  **\n  ** If the on-conflict mode is REPLACE, this means that the existing row\n  ** should be deleted from the database before inserting the new row. Or,\n  ** if the on-conflict mode is other than REPLACE, then this method must\n  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to\n  ** modify the database file.\n  */\n  if( nArg>1 && p->zContentTbl==0 ){\n    /* Find the value object that holds the new rowid value. */\n    sqlite3_value *pNewRowid = apVal[3+p->nColumn];\n    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){\n      pNewRowid = apVal[1];\n    }\n\n    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( \n        sqlite3_value_type(apVal[0])==SQLITE_NULL\n     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)\n    )){\n      /* The new rowid is not NULL (in this case the rowid will be\n      ** automatically assigned and there is no chance of a conflict), and \n      ** the statement is either an INSERT or an UPDATE that modifies the\n      ** rowid column. So if the conflict mode is REPLACE, then delete any\n      ** existing row with rowid=pNewRowid. \n      **\n      ** Or, if the conflict mode is not REPLACE, insert the new record into \n      ** the %_content table. If we hit the duplicate rowid constraint (or any\n      ** other error) while doing so, return immediately.\n      **\n      ** This branch may also run if pNewRowid contains a value that cannot\n      ** be losslessly converted to an integer. In this case, the eventual \n      ** call to fts3InsertData() (either just below or further on in this\n      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is \n      ** invoked, it will delete zero rows (since no row will have\n      ** docid=$pNewRowid if $pNewRowid is not an integer value).\n      */\n      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){\n        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);\n      }else{\n        rc = fts3InsertData(p, apVal, pRowid);\n        bInsertDone = 1;\n      }\n    }\n  }\n  if( rc!=SQLITE_OK ){\n    goto update_out;\n  }\n\n  /* If this is a DELETE or UPDATE operation, remove the old record. */\n  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){\n    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );\n    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);\n    isRemove = 1;\n  }\n  \n  /* If this is an INSERT or UPDATE operation, insert the new record. */\n  if( nArg>1 && rc==SQLITE_OK ){\n    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);\n    if( bInsertDone==0 ){\n      rc = fts3InsertData(p, apVal, pRowid);\n      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){\n        rc = FTS_CORRUPT_VTAB;\n      }\n    }\n    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){\n      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);\n    }\n    if( rc==SQLITE_OK ){\n      assert( p->iPrevDocid==*pRowid );\n      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);\n    }\n    if( p->bHasDocsize ){\n      fts3InsertDocsize(&rc, p, aSzIns);\n    }\n    nChng++;\n  }\n\n  if( p->bFts4 ){\n    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);\n  }\n\n update_out:\n  sqlite3_free(aSzIns);\n  sqlite3Fts3SegmentsClose(p);\n  return rc;\n}\n\n/* \n** Flush any data in the pending-terms hash table to disk. If successful,\n** merge all segments in the database (including the new segment, if \n** there was any data to flush) into a single segment. \n*/\nSQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){\n  int rc;\n  rc = sqlite3_exec(p->db, \"SAVEPOINT fts3\", 0, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = fts3DoOptimize(p, 1);\n    if( rc==SQLITE_OK || rc==SQLITE_DONE ){\n      int rc2 = sqlite3_exec(p->db, \"RELEASE fts3\", 0, 0, 0);\n      if( rc2!=SQLITE_OK ) rc = rc2;\n    }else{\n      sqlite3_exec(p->db, \"ROLLBACK TO fts3\", 0, 0, 0);\n      sqlite3_exec(p->db, \"RELEASE fts3\", 0, 0, 0);\n    }\n  }\n  sqlite3Fts3SegmentsClose(p);\n  return rc;\n}\n\n#endif\n\n/************** End of fts3_write.c ******************************************/\n/************** Begin file fts3_snippet.c ************************************/\n/*\n** 2009 Oct 23\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n/*\n** Characters that may appear in the second argument to matchinfo().\n*/\n#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */\n#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */\n#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */\n#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */\n#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */\n#define FTS3_MATCHINFO_LCS       's'        /* nCol values */\n#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */\n\n/*\n** The default value for the second argument to matchinfo(). \n*/\n#define FTS3_MATCHINFO_DEFAULT   \"pcx\"\n\n\n/*\n** Used as an fts3ExprIterate() context when loading phrase doclists to\n** Fts3Expr.aDoclist[]/nDoclist.\n*/\ntypedef struct LoadDoclistCtx LoadDoclistCtx;\nstruct LoadDoclistCtx {\n  Fts3Cursor *pCsr;               /* FTS3 Cursor */\n  int nPhrase;                    /* Number of phrases seen so far */\n  int nToken;                     /* Number of tokens seen so far */\n};\n\n/*\n** The following types are used as part of the implementation of the \n** fts3BestSnippet() routine.\n*/\ntypedef struct SnippetIter SnippetIter;\ntypedef struct SnippetPhrase SnippetPhrase;\ntypedef struct SnippetFragment SnippetFragment;\n\nstruct SnippetIter {\n  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */\n  int iCol;                       /* Extract snippet from this column */\n  int nSnippet;                   /* Requested snippet length (in tokens) */\n  int nPhrase;                    /* Number of phrases in query */\n  SnippetPhrase *aPhrase;         /* Array of size nPhrase */\n  int iCurrent;                   /* First token of current snippet */\n};\n\nstruct SnippetPhrase {\n  int nToken;                     /* Number of tokens in phrase */\n  char *pList;                    /* Pointer to start of phrase position list */\n  int iHead;                      /* Next value in position list */\n  char *pHead;                    /* Position list data following iHead */\n  int iTail;                      /* Next value in trailing position list */\n  char *pTail;                    /* Position list data following iTail */\n};\n\nstruct SnippetFragment {\n  int iCol;                       /* Column snippet is extracted from */\n  int iPos;                       /* Index of first token in snippet */\n  u64 covered;                    /* Mask of query phrases covered */\n  u64 hlmask;                     /* Mask of snippet terms to highlight */\n};\n\n/*\n** This type is used as an fts3ExprIterate() context object while \n** accumulating the data returned by the matchinfo() function.\n*/\ntypedef struct MatchInfo MatchInfo;\nstruct MatchInfo {\n  Fts3Cursor *pCursor;            /* FTS3 Cursor */\n  int nCol;                       /* Number of columns in table */\n  int nPhrase;                    /* Number of matchable phrases in query */\n  sqlite3_int64 nDoc;             /* Number of docs in database */\n  u32 *aMatchinfo;                /* Pre-allocated buffer */\n};\n\n\n\n/*\n** The snippet() and offsets() functions both return text values. An instance\n** of the following structure is used to accumulate those values while the\n** functions are running. See fts3StringAppend() for details.\n*/\ntypedef struct StrBuffer StrBuffer;\nstruct StrBuffer {\n  char *z;                        /* Pointer to buffer containing string */\n  int n;                          /* Length of z in bytes (excl. nul-term) */\n  int nAlloc;                     /* Allocated size of buffer z in bytes */\n};\n\n\n/*\n** This function is used to help iterate through a position-list. A position\n** list is a list of unique integers, sorted from smallest to largest. Each\n** element of the list is represented by an FTS3 varint that takes the value\n** of the difference between the current element and the previous one plus\n** two. For example, to store the position-list:\n**\n**     4 9 113\n**\n** the three varints:\n**\n**     6 7 106\n**\n** are encoded.\n**\n** When this function is called, *pp points to the start of an element of\n** the list. *piPos contains the value of the previous entry in the list.\n** After it returns, *piPos contains the value of the next element of the\n** list and *pp is advanced to the following varint.\n*/\nstatic void fts3GetDeltaPosition(char **pp, int *piPos){\n  int iVal;\n  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);\n  *piPos += (iVal-2);\n}\n\n/*\n** Helper function for fts3ExprIterate() (see below).\n*/\nstatic int fts3ExprIterate2(\n  Fts3Expr *pExpr,                /* Expression to iterate phrases of */\n  int *piPhrase,                  /* Pointer to phrase counter */\n  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */\n  void *pCtx                      /* Second argument to pass to callback */\n){\n  int rc;                         /* Return code */\n  int eType = pExpr->eType;       /* Type of expression node pExpr */\n\n  if( eType!=FTSQUERY_PHRASE ){\n    assert( pExpr->pLeft && pExpr->pRight );\n    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);\n    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){\n      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);\n    }\n  }else{\n    rc = x(pExpr, *piPhrase, pCtx);\n    (*piPhrase)++;\n  }\n  return rc;\n}\n\n/*\n** Iterate through all phrase nodes in an FTS3 query, except those that\n** are part of a sub-tree that is the right-hand-side of a NOT operator.\n** For each phrase node found, the supplied callback function is invoked.\n**\n** If the callback function returns anything other than SQLITE_OK, \n** the iteration is abandoned and the error code returned immediately.\n** Otherwise, SQLITE_OK is returned after a callback has been made for\n** all eligible phrase nodes.\n*/\nstatic int fts3ExprIterate(\n  Fts3Expr *pExpr,                /* Expression to iterate phrases of */\n  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */\n  void *pCtx                      /* Second argument to pass to callback */\n){\n  int iPhrase = 0;                /* Variable used as the phrase counter */\n  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);\n}\n\n/*\n** This is an fts3ExprIterate() callback used while loading the doclists\n** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also\n** fts3ExprLoadDoclists().\n*/\nstatic int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  int rc = SQLITE_OK;\n  Fts3Phrase *pPhrase = pExpr->pPhrase;\n  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;\n\n  UNUSED_PARAMETER(iPhrase);\n\n  p->nPhrase++;\n  p->nToken += pPhrase->nToken;\n\n  return rc;\n}\n\n/*\n** Load the doclists for each phrase in the query associated with FTS3 cursor\n** pCsr. \n**\n** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable \n** phrases in the expression (all phrases except those directly or \n** indirectly descended from the right-hand-side of a NOT operator). If \n** pnToken is not NULL, then it is set to the number of tokens in all\n** matchable phrases of the expression.\n*/\nstatic int fts3ExprLoadDoclists(\n  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */\n  int *pnPhrase,                  /* OUT: Number of phrases in query */\n  int *pnToken                    /* OUT: Number of tokens in query */\n){\n  int rc;                         /* Return Code */\n  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */\n  sCtx.pCsr = pCsr;\n  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);\n  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;\n  if( pnToken ) *pnToken = sCtx.nToken;\n  return rc;\n}\n\nstatic int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  (*(int *)ctx)++;\n  UNUSED_PARAMETER(pExpr);\n  UNUSED_PARAMETER(iPhrase);\n  return SQLITE_OK;\n}\nstatic int fts3ExprPhraseCount(Fts3Expr *pExpr){\n  int nPhrase = 0;\n  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);\n  return nPhrase;\n}\n\n/*\n** Advance the position list iterator specified by the first two \n** arguments so that it points to the first element with a value greater\n** than or equal to parameter iNext.\n*/\nstatic void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){\n  char *pIter = *ppIter;\n  if( pIter ){\n    int iIter = *piIter;\n\n    while( iIter<iNext ){\n      if( 0==(*pIter & 0xFE) ){\n        iIter = -1;\n        pIter = 0;\n        break;\n      }\n      fts3GetDeltaPosition(&pIter, &iIter);\n    }\n\n    *piIter = iIter;\n    *ppIter = pIter;\n  }\n}\n\n/*\n** Advance the snippet iterator to the next candidate snippet.\n*/\nstatic int fts3SnippetNextCandidate(SnippetIter *pIter){\n  int i;                          /* Loop counter */\n\n  if( pIter->iCurrent<0 ){\n    /* The SnippetIter object has just been initialized. The first snippet\n    ** candidate always starts at offset 0 (even if this candidate has a\n    ** score of 0.0).\n    */\n    pIter->iCurrent = 0;\n\n    /* Advance the 'head' iterator of each phrase to the first offset that\n    ** is greater than or equal to (iNext+nSnippet).\n    */\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);\n    }\n  }else{\n    int iStart;\n    int iEnd = 0x7FFFFFFF;\n\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      if( pPhrase->pHead && pPhrase->iHead<iEnd ){\n        iEnd = pPhrase->iHead;\n      }\n    }\n    if( iEnd==0x7FFFFFFF ){\n      return 1;\n    }\n\n    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;\n    for(i=0; i<pIter->nPhrase; i++){\n      SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);\n      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);\n    }\n  }\n\n  return 0;\n}\n\n/*\n** Retrieve information about the current candidate snippet of snippet \n** iterator pIter.\n*/\nstatic void fts3SnippetDetails(\n  SnippetIter *pIter,             /* Snippet iterator */\n  u64 mCovered,                   /* Bitmask of phrases already covered */\n  int *piToken,                   /* OUT: First token of proposed snippet */\n  int *piScore,                   /* OUT: \"Score\" for this snippet */\n  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */\n  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */\n){\n  int iStart = pIter->iCurrent;   /* First token of snippet */\n  int iScore = 0;                 /* Score of this snippet */\n  int i;                          /* Loop counter */\n  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */\n  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */\n\n  for(i=0; i<pIter->nPhrase; i++){\n    SnippetPhrase *pPhrase = &pIter->aPhrase[i];\n    if( pPhrase->pTail ){\n      char *pCsr = pPhrase->pTail;\n      int iCsr = pPhrase->iTail;\n\n      while( iCsr<(iStart+pIter->nSnippet) ){\n        int j;\n        u64 mPhrase = (u64)1 << i;\n        u64 mPos = (u64)1 << (iCsr - iStart);\n        assert( iCsr>=iStart );\n        if( (mCover|mCovered)&mPhrase ){\n          iScore++;\n        }else{\n          iScore += 1000;\n        }\n        mCover |= mPhrase;\n\n        for(j=0; j<pPhrase->nToken; j++){\n          mHighlight |= (mPos>>j);\n        }\n\n        if( 0==(*pCsr & 0x0FE) ) break;\n        fts3GetDeltaPosition(&pCsr, &iCsr);\n      }\n    }\n  }\n\n  /* Set the output variables before returning. */\n  *piToken = iStart;\n  *piScore = iScore;\n  *pmCover = mCover;\n  *pmHighlight = mHighlight;\n}\n\n/*\n** This function is an fts3ExprIterate() callback used by fts3BestSnippet().\n** Each invocation populates an element of the SnippetIter.aPhrase[] array.\n*/\nstatic int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  SnippetIter *p = (SnippetIter *)ctx;\n  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];\n  char *pCsr;\n  int rc;\n\n  pPhrase->nToken = pExpr->pPhrase->nToken;\n  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);\n  assert( rc==SQLITE_OK || pCsr==0 );\n  if( pCsr ){\n    int iFirst = 0;\n    pPhrase->pList = pCsr;\n    fts3GetDeltaPosition(&pCsr, &iFirst);\n    assert( iFirst>=0 );\n    pPhrase->pHead = pCsr;\n    pPhrase->pTail = pCsr;\n    pPhrase->iHead = iFirst;\n    pPhrase->iTail = iFirst;\n  }else{\n    assert( rc!=SQLITE_OK || (\n       pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 \n    ));\n  }\n\n  return rc;\n}\n\n/*\n** Select the fragment of text consisting of nFragment contiguous tokens \n** from column iCol that represent the \"best\" snippet. The best snippet\n** is the snippet with the highest score, where scores are calculated\n** by adding:\n**\n**   (a) +1 point for each occurence of a matchable phrase in the snippet.\n**\n**   (b) +1000 points for the first occurence of each matchable phrase in \n**       the snippet for which the corresponding mCovered bit is not set.\n**\n** The selected snippet parameters are stored in structure *pFragment before\n** returning. The score of the selected snippet is stored in *piScore\n** before returning.\n*/\nstatic int fts3BestSnippet(\n  int nSnippet,                   /* Desired snippet length */\n  Fts3Cursor *pCsr,               /* Cursor to create snippet for */\n  int iCol,                       /* Index of column to create snippet from */\n  u64 mCovered,                   /* Mask of phrases already covered */\n  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */\n  SnippetFragment *pFragment,     /* OUT: Best snippet found */\n  int *piScore                    /* OUT: Score of snippet pFragment */\n){\n  int rc;                         /* Return Code */\n  int nList;                      /* Number of phrases in expression */\n  SnippetIter sIter;              /* Iterates through snippet candidates */\n  int nByte;                      /* Number of bytes of space to allocate */\n  int iBestScore = -1;            /* Best snippet score found so far */\n  int i;                          /* Loop counter */\n\n  memset(&sIter, 0, sizeof(sIter));\n\n  /* Iterate through the phrases in the expression to count them. The same\n  ** callback makes sure the doclists are loaded for each phrase.\n  */\n  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Now that it is known how many phrases there are, allocate and zero\n  ** the required space using malloc().\n  */\n  nByte = sizeof(SnippetPhrase) * nList;\n  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);\n  if( !sIter.aPhrase ){\n    return SQLITE_NOMEM;\n  }\n  memset(sIter.aPhrase, 0, nByte);\n\n  /* Initialize the contents of the SnippetIter object. Then iterate through\n  ** the set of phrases in the expression to populate the aPhrase[] array.\n  */\n  sIter.pCsr = pCsr;\n  sIter.iCol = iCol;\n  sIter.nSnippet = nSnippet;\n  sIter.nPhrase = nList;\n  sIter.iCurrent = -1;\n  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);\n\n  /* Set the *pmSeen output variable. */\n  for(i=0; i<nList; i++){\n    if( sIter.aPhrase[i].pHead ){\n      *pmSeen |= (u64)1 << i;\n    }\n  }\n\n  /* Loop through all candidate snippets. Store the best snippet in \n  ** *pFragment. Store its associated 'score' in iBestScore.\n  */\n  pFragment->iCol = iCol;\n  while( !fts3SnippetNextCandidate(&sIter) ){\n    int iPos;\n    int iScore;\n    u64 mCover;\n    u64 mHighlight;\n    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);\n    assert( iScore>=0 );\n    if( iScore>iBestScore ){\n      pFragment->iPos = iPos;\n      pFragment->hlmask = mHighlight;\n      pFragment->covered = mCover;\n      iBestScore = iScore;\n    }\n  }\n\n  sqlite3_free(sIter.aPhrase);\n  *piScore = iBestScore;\n  return SQLITE_OK;\n}\n\n\n/*\n** Append a string to the string-buffer passed as the first argument.\n**\n** If nAppend is negative, then the length of the string zAppend is\n** determined using strlen().\n*/\nstatic int fts3StringAppend(\n  StrBuffer *pStr,                /* Buffer to append to */\n  const char *zAppend,            /* Pointer to data to append to buffer */\n  int nAppend                     /* Size of zAppend in bytes (or -1) */\n){\n  if( nAppend<0 ){\n    nAppend = (int)strlen(zAppend);\n  }\n\n  /* If there is insufficient space allocated at StrBuffer.z, use realloc()\n  ** to grow the buffer until so that it is big enough to accomadate the\n  ** appended data.\n  */\n  if( pStr->n+nAppend+1>=pStr->nAlloc ){\n    int nAlloc = pStr->nAlloc+nAppend+100;\n    char *zNew = sqlite3_realloc(pStr->z, nAlloc);\n    if( !zNew ){\n      return SQLITE_NOMEM;\n    }\n    pStr->z = zNew;\n    pStr->nAlloc = nAlloc;\n  }\n\n  /* Append the data to the string buffer. */\n  memcpy(&pStr->z[pStr->n], zAppend, nAppend);\n  pStr->n += nAppend;\n  pStr->z[pStr->n] = '\\0';\n\n  return SQLITE_OK;\n}\n\n/*\n** The fts3BestSnippet() function often selects snippets that end with a\n** query term. That is, the final term of the snippet is always a term\n** that requires highlighting. For example, if 'X' is a highlighted term\n** and '.' is a non-highlighted term, BestSnippet() may select:\n**\n**     ........X.....X\n**\n** This function \"shifts\" the beginning of the snippet forward in the \n** document so that there are approximately the same number of \n** non-highlighted terms to the right of the final highlighted term as there\n** are to the left of the first highlighted term. For example, to this:\n**\n**     ....X.....X....\n**\n** This is done as part of extracting the snippet text, not when selecting\n** the snippet. Snippet selection is done based on doclists only, so there\n** is no way for fts3BestSnippet() to know whether or not the document \n** actually contains terms that follow the final highlighted term. \n*/\nstatic int fts3SnippetShift(\n  Fts3Table *pTab,                /* FTS3 table snippet comes from */\n  int iLangid,                    /* Language id to use in tokenizing */\n  int nSnippet,                   /* Number of tokens desired for snippet */\n  const char *zDoc,               /* Document text to extract snippet from */\n  int nDoc,                       /* Size of buffer zDoc in bytes */\n  int *piPos,                     /* IN/OUT: First token of snippet */\n  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */\n){\n  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */\n\n  if( hlmask ){\n    int nLeft;                    /* Tokens to the left of first highlight */\n    int nRight;                   /* Tokens to the right of last highlight */\n    int nDesired;                 /* Ideal number of tokens to shift forward */\n\n    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);\n    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);\n    nDesired = (nLeft-nRight)/2;\n\n    /* Ideally, the start of the snippet should be pushed forward in the\n    ** document nDesired tokens. This block checks if there are actually\n    ** nDesired tokens to the right of the snippet. If so, *piPos and\n    ** *pHlMask are updated to shift the snippet nDesired tokens to the\n    ** right. Otherwise, the snippet is shifted by the number of tokens\n    ** available.\n    */\n    if( nDesired>0 ){\n      int nShift;                 /* Number of tokens to shift snippet by */\n      int iCurrent = 0;           /* Token counter */\n      int rc;                     /* Return Code */\n      sqlite3_tokenizer_module *pMod;\n      sqlite3_tokenizer_cursor *pC;\n      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;\n\n      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)\n      ** or more tokens in zDoc/nDoc.\n      */\n      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){\n        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;\n        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);\n      }\n      pMod->xClose(pC);\n      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }\n\n      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;\n      assert( nShift<=nDesired );\n      if( nShift>0 ){\n        *piPos += nShift;\n        *pHlmask = hlmask >> nShift;\n      }\n    }\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Extract the snippet text for fragment pFragment from cursor pCsr and\n** append it to string buffer pOut.\n*/\nstatic int fts3SnippetText(\n  Fts3Cursor *pCsr,               /* FTS3 Cursor */\n  SnippetFragment *pFragment,     /* Snippet to extract */\n  int iFragment,                  /* Fragment number */\n  int isLast,                     /* True for final fragment in snippet */\n  int nSnippet,                   /* Number of tokens in extracted snippet */\n  const char *zOpen,              /* String inserted before highlighted term */\n  const char *zClose,             /* String inserted after highlighted term */\n  const char *zEllipsis,          /* String inserted between snippets */\n  StrBuffer *pOut                 /* Write output here */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc;                         /* Return code */\n  const char *zDoc;               /* Document text to extract snippet from */\n  int nDoc;                       /* Size of zDoc in bytes */\n  int iCurrent = 0;               /* Current token number of document */\n  int iEnd = 0;                   /* Byte offset of end of current token */\n  int isShiftDone = 0;            /* True after snippet is shifted */\n  int iPos = pFragment->iPos;     /* First token of snippet */\n  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */\n  int iCol = pFragment->iCol+1;   /* Query column to extract text from */\n  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */\n  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */\n  const char *ZDUMMY;             /* Dummy argument used with tokenizer */\n  int DUMMY1;                     /* Dummy argument used with tokenizer */\n  \n  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);\n  if( zDoc==0 ){\n    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){\n      return SQLITE_NOMEM;\n    }\n    return SQLITE_OK;\n  }\n  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);\n\n  /* Open a token cursor on the document. */\n  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;\n  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  while( rc==SQLITE_OK ){\n    int iBegin;                   /* Offset in zDoc of start of token */\n    int iFin;                     /* Offset in zDoc of end of token */\n    int isHighlight;              /* True for highlighted terms */\n\n    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);\n    if( rc!=SQLITE_OK ){\n      if( rc==SQLITE_DONE ){\n        /* Special case - the last token of the snippet is also the last token\n        ** of the column. Append any punctuation that occurred between the end\n        ** of the previous token and the end of the document to the output. \n        ** Then break out of the loop. */\n        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);\n      }\n      break;\n    }\n    if( iCurrent<iPos ){ continue; }\n\n    if( !isShiftDone ){\n      int n = nDoc - iBegin;\n      rc = fts3SnippetShift(\n          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask\n      );\n      isShiftDone = 1;\n\n      /* Now that the shift has been done, check if the initial \"...\" are\n      ** required. They are required if (a) this is not the first fragment,\n      ** or (b) this fragment does not begin at position 0 of its column. \n      */\n      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){\n        rc = fts3StringAppend(pOut, zEllipsis, -1);\n      }\n      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;\n    }\n\n    if( iCurrent>=(iPos+nSnippet) ){\n      if( isLast ){\n        rc = fts3StringAppend(pOut, zEllipsis, -1);\n      }\n      break;\n    }\n\n    /* Set isHighlight to true if this term should be highlighted. */\n    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;\n\n    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);\n    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);\n    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);\n    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);\n\n    iEnd = iFin;\n  }\n\n  pMod->xClose(pC);\n  return rc;\n}\n\n\n/*\n** This function is used to count the entries in a column-list (a \n** delta-encoded list of term offsets within a single column of a single \n** row). When this function is called, *ppCollist should point to the\n** beginning of the first varint in the column-list (the varint that\n** contains the position of the first matching term in the column data).\n** Before returning, *ppCollist is set to point to the first byte after\n** the last varint in the column-list (either the 0x00 signifying the end\n** of the position-list, or the 0x01 that precedes the column number of\n** the next column in the position-list).\n**\n** The number of elements in the column-list is returned.\n*/\nstatic int fts3ColumnlistCount(char **ppCollist){\n  char *pEnd = *ppCollist;\n  char c = 0;\n  int nEntry = 0;\n\n  /* A column-list is terminated by either a 0x01 or 0x00. */\n  while( 0xFE & (*pEnd | c) ){\n    c = *pEnd++ & 0x80;\n    if( !c ) nEntry++;\n  }\n\n  *ppCollist = pEnd;\n  return nEntry;\n}\n\n/*\n** fts3ExprIterate() callback used to collect the \"global\" matchinfo stats\n** for a single query. \n**\n** fts3ExprIterate() callback to load the 'global' elements of a\n** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements \n** of the matchinfo array that are constant for all rows returned by the \n** current query.\n**\n** Argument pCtx is actually a pointer to a struct of type MatchInfo. This\n** function populates Matchinfo.aMatchinfo[] as follows:\n**\n**   for(iCol=0; iCol<nCol; iCol++){\n**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;\n**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;\n**   }\n**\n** where X is the number of matches for phrase iPhrase is column iCol of all\n** rows of the table. Y is the number of rows for which column iCol contains\n** at least one instance of phrase iPhrase.\n**\n** If the phrase pExpr consists entirely of deferred tokens, then all X and\n** Y values are set to nDoc, where nDoc is the number of documents in the \n** file system. This is done because the full-text index doclist is required\n** to calculate these values properly, and the full-text index doclist is\n** not available for deferred tokens.\n*/\nstatic int fts3ExprGlobalHitsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number (numbered from zero) */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  MatchInfo *p = (MatchInfo *)pCtx;\n  return sqlite3Fts3EvalPhraseStats(\n      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]\n  );\n}\n\n/*\n** fts3ExprIterate() callback used to collect the \"local\" part of the\n** FTS3_MATCHINFO_HITS array. The local stats are those elements of the \n** array that are different for each row returned by the query.\n*/\nstatic int fts3ExprLocalHitsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  int rc = SQLITE_OK;\n  MatchInfo *p = (MatchInfo *)pCtx;\n  int iStart = iPhrase * p->nCol * 3;\n  int i;\n\n  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){\n    char *pCsr;\n    rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);\n    if( pCsr ){\n      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);\n    }else{\n      p->aMatchinfo[iStart+i*3] = 0;\n    }\n  }\n\n  return rc;\n}\n\nstatic int fts3MatchinfoCheck(\n  Fts3Table *pTab, \n  char cArg,\n  char **pzErr\n){\n  if( (cArg==FTS3_MATCHINFO_NPHRASE)\n   || (cArg==FTS3_MATCHINFO_NCOL)\n   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)\n   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)\n   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)\n   || (cArg==FTS3_MATCHINFO_LCS)\n   || (cArg==FTS3_MATCHINFO_HITS)\n  ){\n    return SQLITE_OK;\n  }\n  *pzErr = sqlite3_mprintf(\"unrecognized matchinfo request: %c\", cArg);\n  return SQLITE_ERROR;\n}\n\nstatic int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){\n  int nVal;                       /* Number of integers output by cArg */\n\n  switch( cArg ){\n    case FTS3_MATCHINFO_NDOC:\n    case FTS3_MATCHINFO_NPHRASE: \n    case FTS3_MATCHINFO_NCOL: \n      nVal = 1;\n      break;\n\n    case FTS3_MATCHINFO_AVGLENGTH:\n    case FTS3_MATCHINFO_LENGTH:\n    case FTS3_MATCHINFO_LCS:\n      nVal = pInfo->nCol;\n      break;\n\n    default:\n      assert( cArg==FTS3_MATCHINFO_HITS );\n      nVal = pInfo->nCol * pInfo->nPhrase * 3;\n      break;\n  }\n\n  return nVal;\n}\n\nstatic int fts3MatchinfoSelectDoctotal(\n  Fts3Table *pTab,\n  sqlite3_stmt **ppStmt,\n  sqlite3_int64 *pnDoc,\n  const char **paLen\n){\n  sqlite3_stmt *pStmt;\n  const char *a;\n  sqlite3_int64 nDoc;\n\n  if( !*ppStmt ){\n    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);\n    if( rc!=SQLITE_OK ) return rc;\n  }\n  pStmt = *ppStmt;\n  assert( sqlite3_data_count(pStmt)==1 );\n\n  a = sqlite3_column_blob(pStmt, 0);\n  a += sqlite3Fts3GetVarint(a, &nDoc);\n  if( nDoc==0 ) return FTS_CORRUPT_VTAB;\n  *pnDoc = (u32)nDoc;\n\n  if( paLen ) *paLen = a;\n  return SQLITE_OK;\n}\n\n/*\n** An instance of the following structure is used to store state while \n** iterating through a multi-column position-list corresponding to the\n** hits for a single phrase on a single row in order to calculate the\n** values for a matchinfo() FTS3_MATCHINFO_LCS request.\n*/\ntypedef struct LcsIterator LcsIterator;\nstruct LcsIterator {\n  Fts3Expr *pExpr;                /* Pointer to phrase expression */\n  int iPosOffset;                 /* Tokens count up to end of this phrase */\n  char *pRead;                    /* Cursor used to iterate through aDoclist */\n  int iPos;                       /* Current position */\n};\n\n/* \n** If LcsIterator.iCol is set to the following value, the iterator has\n** finished iterating through all offsets for all columns.\n*/\n#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;\n\nstatic int fts3MatchinfoLcsCb(\n  Fts3Expr *pExpr,                /* Phrase expression node */\n  int iPhrase,                    /* Phrase number (numbered from zero) */\n  void *pCtx                      /* Pointer to MatchInfo structure */\n){\n  LcsIterator *aIter = (LcsIterator *)pCtx;\n  aIter[iPhrase].pExpr = pExpr;\n  return SQLITE_OK;\n}\n\n/*\n** Advance the iterator passed as an argument to the next position. Return\n** 1 if the iterator is at EOF or if it now points to the start of the\n** position list for the next column.\n*/\nstatic int fts3LcsIteratorAdvance(LcsIterator *pIter){\n  char *pRead = pIter->pRead;\n  sqlite3_int64 iRead;\n  int rc = 0;\n\n  pRead += sqlite3Fts3GetVarint(pRead, &iRead);\n  if( iRead==0 || iRead==1 ){\n    pRead = 0;\n    rc = 1;\n  }else{\n    pIter->iPos += (int)(iRead-2);\n  }\n\n  pIter->pRead = pRead;\n  return rc;\n}\n  \n/*\n** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. \n**\n** If the call is successful, the longest-common-substring lengths for each\n** column are written into the first nCol elements of the pInfo->aMatchinfo[] \n** array before returning. SQLITE_OK is returned in this case.\n**\n** Otherwise, if an error occurs, an SQLite error code is returned and the\n** data written to the first nCol elements of pInfo->aMatchinfo[] is \n** undefined.\n*/\nstatic int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){\n  LcsIterator *aIter;\n  int i;\n  int iCol;\n  int nToken = 0;\n\n  /* Allocate and populate the array of LcsIterator objects. The array\n  ** contains one element for each matchable phrase in the query.\n  **/\n  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);\n  if( !aIter ) return SQLITE_NOMEM;\n  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);\n  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);\n\n  for(i=0; i<pInfo->nPhrase; i++){\n    LcsIterator *pIter = &aIter[i];\n    nToken -= pIter->pExpr->pPhrase->nToken;\n    pIter->iPosOffset = nToken;\n  }\n\n  for(iCol=0; iCol<pInfo->nCol; iCol++){\n    int nLcs = 0;                 /* LCS value for this column */\n    int nLive = 0;                /* Number of iterators in aIter not at EOF */\n\n    for(i=0; i<pInfo->nPhrase; i++){\n      int rc;\n      LcsIterator *pIt = &aIter[i];\n      rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);\n      if( rc!=SQLITE_OK ) return rc;\n      if( pIt->pRead ){\n        pIt->iPos = pIt->iPosOffset;\n        fts3LcsIteratorAdvance(&aIter[i]);\n        nLive++;\n      }\n    }\n\n    while( nLive>0 ){\n      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */\n      int nThisLcs = 0;           /* LCS for the current iterator positions */\n\n      for(i=0; i<pInfo->nPhrase; i++){\n        LcsIterator *pIter = &aIter[i];\n        if( pIter->pRead==0 ){\n          /* This iterator is already at EOF for this column. */\n          nThisLcs = 0;\n        }else{\n          if( pAdv==0 || pIter->iPos<pAdv->iPos ){\n            pAdv = pIter;\n          }\n          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){\n            nThisLcs++;\n          }else{\n            nThisLcs = 1;\n          }\n          if( nThisLcs>nLcs ) nLcs = nThisLcs;\n        }\n      }\n      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;\n    }\n\n    pInfo->aMatchinfo[iCol] = nLcs;\n  }\n\n  sqlite3_free(aIter);\n  return SQLITE_OK;\n}\n\n/*\n** Populate the buffer pInfo->aMatchinfo[] with an array of integers to\n** be returned by the matchinfo() function. Argument zArg contains the \n** format string passed as the second argument to matchinfo (or the\n** default value \"pcx\" if no second argument was specified). The format\n** string has already been validated and the pInfo->aMatchinfo[] array\n** is guaranteed to be large enough for the output.\n**\n** If bGlobal is true, then populate all fields of the matchinfo() output.\n** If it is false, then assume that those fields that do not change between\n** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)\n** have already been populated.\n**\n** Return SQLITE_OK if successful, or an SQLite error code if an error \n** occurs. If a value other than SQLITE_OK is returned, the state the\n** pInfo->aMatchinfo[] buffer is left in is undefined.\n*/\nstatic int fts3MatchinfoValues(\n  Fts3Cursor *pCsr,               /* FTS3 cursor object */\n  int bGlobal,                    /* True to grab the global stats */\n  MatchInfo *pInfo,               /* Matchinfo context object */\n  const char *zArg                /* Matchinfo format string */\n){\n  int rc = SQLITE_OK;\n  int i;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  sqlite3_stmt *pSelect = 0;\n\n  for(i=0; rc==SQLITE_OK && zArg[i]; i++){\n\n    switch( zArg[i] ){\n      case FTS3_MATCHINFO_NPHRASE:\n        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;\n        break;\n\n      case FTS3_MATCHINFO_NCOL:\n        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;\n        break;\n        \n      case FTS3_MATCHINFO_NDOC:\n        if( bGlobal ){\n          sqlite3_int64 nDoc = 0;\n          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);\n          pInfo->aMatchinfo[0] = (u32)nDoc;\n        }\n        break;\n\n      case FTS3_MATCHINFO_AVGLENGTH: \n        if( bGlobal ){\n          sqlite3_int64 nDoc;     /* Number of rows in table */\n          const char *a;          /* Aggregate column length array */\n\n          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);\n          if( rc==SQLITE_OK ){\n            int iCol;\n            for(iCol=0; iCol<pInfo->nCol; iCol++){\n              u32 iVal;\n              sqlite3_int64 nToken;\n              a += sqlite3Fts3GetVarint(a, &nToken);\n              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);\n              pInfo->aMatchinfo[iCol] = iVal;\n            }\n          }\n        }\n        break;\n\n      case FTS3_MATCHINFO_LENGTH: {\n        sqlite3_stmt *pSelectDocsize = 0;\n        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);\n        if( rc==SQLITE_OK ){\n          int iCol;\n          const char *a = sqlite3_column_blob(pSelectDocsize, 0);\n          for(iCol=0; iCol<pInfo->nCol; iCol++){\n            sqlite3_int64 nToken;\n            a += sqlite3Fts3GetVarint(a, &nToken);\n            pInfo->aMatchinfo[iCol] = (u32)nToken;\n          }\n        }\n        sqlite3_reset(pSelectDocsize);\n        break;\n      }\n\n      case FTS3_MATCHINFO_LCS:\n        rc = fts3ExprLoadDoclists(pCsr, 0, 0);\n        if( rc==SQLITE_OK ){\n          rc = fts3MatchinfoLcs(pCsr, pInfo);\n        }\n        break;\n\n      default: {\n        Fts3Expr *pExpr;\n        assert( zArg[i]==FTS3_MATCHINFO_HITS );\n        pExpr = pCsr->pExpr;\n        rc = fts3ExprLoadDoclists(pCsr, 0, 0);\n        if( rc!=SQLITE_OK ) break;\n        if( bGlobal ){\n          if( pCsr->pDeferred ){\n            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);\n            if( rc!=SQLITE_OK ) break;\n          }\n          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);\n          if( rc!=SQLITE_OK ) break;\n        }\n        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);\n        break;\n      }\n    }\n\n    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);\n  }\n\n  sqlite3_reset(pSelect);\n  return rc;\n}\n\n\n/*\n** Populate pCsr->aMatchinfo[] with data for the current row. The \n** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).\n*/\nstatic int fts3GetMatchinfo(\n  Fts3Cursor *pCsr,               /* FTS3 Cursor object */\n  const char *zArg                /* Second argument to matchinfo() function */\n){\n  MatchInfo sInfo;\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int bGlobal = 0;                /* Collect 'global' stats as well as local */\n\n  memset(&sInfo, 0, sizeof(MatchInfo));\n  sInfo.pCursor = pCsr;\n  sInfo.nCol = pTab->nColumn;\n\n  /* If there is cached matchinfo() data, but the format string for the \n  ** cache does not match the format string for this request, discard \n  ** the cached data. */\n  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){\n    assert( pCsr->aMatchinfo );\n    sqlite3_free(pCsr->aMatchinfo);\n    pCsr->zMatchinfo = 0;\n    pCsr->aMatchinfo = 0;\n  }\n\n  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the\n  ** matchinfo function has been called for this query. In this case \n  ** allocate the array used to accumulate the matchinfo data and\n  ** initialize those elements that are constant for every row.\n  */\n  if( pCsr->aMatchinfo==0 ){\n    int nMatchinfo = 0;           /* Number of u32 elements in match-info */\n    int nArg;                     /* Bytes in zArg */\n    int i;                        /* Used to iterate through zArg */\n\n    /* Determine the number of phrases in the query */\n    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);\n    sInfo.nPhrase = pCsr->nPhrase;\n\n    /* Determine the number of integers in the buffer returned by this call. */\n    for(i=0; zArg[i]; i++){\n      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);\n    }\n\n    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */\n    nArg = (int)strlen(zArg);\n    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);\n    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;\n\n    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];\n    pCsr->nMatchinfo = nMatchinfo;\n    memcpy(pCsr->zMatchinfo, zArg, nArg+1);\n    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);\n    pCsr->isMatchinfoNeeded = 1;\n    bGlobal = 1;\n  }\n\n  sInfo.aMatchinfo = pCsr->aMatchinfo;\n  sInfo.nPhrase = pCsr->nPhrase;\n  if( pCsr->isMatchinfoNeeded ){\n    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);\n    pCsr->isMatchinfoNeeded = 0;\n  }\n\n  return rc;\n}\n\n/*\n** Implementation of snippet() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Snippet(\n  sqlite3_context *pCtx,          /* SQLite function call context */\n  Fts3Cursor *pCsr,               /* Cursor object */\n  const char *zStart,             /* Snippet start text - \"<b>\" */\n  const char *zEnd,               /* Snippet end text - \"</b>\" */\n  const char *zEllipsis,          /* Snippet ellipsis text - \"<b>...</b>\" */\n  int iCol,                       /* Extract snippet from this column */\n  int nToken                      /* Approximate number of tokens in snippet */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc = SQLITE_OK;\n  int i;\n  StrBuffer res = {0, 0, 0};\n\n  /* The returned text includes up to four fragments of text extracted from\n  ** the data in the current row. The first iteration of the for(...) loop\n  ** below attempts to locate a single fragment of text nToken tokens in \n  ** size that contains at least one instance of all phrases in the query\n  ** expression that appear in the current row. If such a fragment of text\n  ** cannot be found, the second iteration of the loop attempts to locate\n  ** a pair of fragments, and so on.\n  */\n  int nSnippet = 0;               /* Number of fragments in this snippet */\n  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */\n  int nFToken = -1;               /* Number of tokens in each fragment */\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_text(pCtx, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  for(nSnippet=1; 1; nSnippet++){\n\n    int iSnip;                    /* Loop counter 0..nSnippet-1 */\n    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */\n    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */\n\n    if( nToken>=0 ){\n      nFToken = (nToken+nSnippet-1) / nSnippet;\n    }else{\n      nFToken = -1 * nToken;\n    }\n\n    for(iSnip=0; iSnip<nSnippet; iSnip++){\n      int iBestScore = -1;        /* Best score of columns checked so far */\n      int iRead;                  /* Used to iterate through columns */\n      SnippetFragment *pFragment = &aSnippet[iSnip];\n\n      memset(pFragment, 0, sizeof(*pFragment));\n\n      /* Loop through all columns of the table being considered for snippets.\n      ** If the iCol argument to this function was negative, this means all\n      ** columns of the FTS3 table. Otherwise, only column iCol is considered.\n      */\n      for(iRead=0; iRead<pTab->nColumn; iRead++){\n        SnippetFragment sF = {0, 0, 0, 0};\n        int iS;\n        if( iCol>=0 && iRead!=iCol ) continue;\n\n        /* Find the best snippet of nFToken tokens in column iRead. */\n        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);\n        if( rc!=SQLITE_OK ){\n          goto snippet_out;\n        }\n        if( iS>iBestScore ){\n          *pFragment = sF;\n          iBestScore = iS;\n        }\n      }\n\n      mCovered |= pFragment->covered;\n    }\n\n    /* If all query phrases seen by fts3BestSnippet() are present in at least\n    ** one of the nSnippet snippet fragments, break out of the loop.\n    */\n    assert( (mCovered&mSeen)==mCovered );\n    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;\n  }\n\n  assert( nFToken>0 );\n\n  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){\n    rc = fts3SnippetText(pCsr, &aSnippet[i], \n        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res\n    );\n  }\n\n snippet_out:\n  sqlite3Fts3SegmentsClose(pTab);\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx, rc);\n    sqlite3_free(res.z);\n  }else{\n    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);\n  }\n}\n\n\ntypedef struct TermOffset TermOffset;\ntypedef struct TermOffsetCtx TermOffsetCtx;\n\nstruct TermOffset {\n  char *pList;                    /* Position-list */\n  int iPos;                       /* Position just read from pList */\n  int iOff;                       /* Offset of this term from read positions */\n};\n\nstruct TermOffsetCtx {\n  Fts3Cursor *pCsr;\n  int iCol;                       /* Column of table to populate aTerm for */\n  int iTerm;\n  sqlite3_int64 iDocid;\n  TermOffset *aTerm;\n};\n\n/*\n** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().\n*/\nstatic int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){\n  TermOffsetCtx *p = (TermOffsetCtx *)ctx;\n  int nTerm;                      /* Number of tokens in phrase */\n  int iTerm;                      /* For looping through nTerm phrase terms */\n  char *pList;                    /* Pointer to position list for phrase */\n  int iPos = 0;                   /* First position in position-list */\n  int rc;\n\n  UNUSED_PARAMETER(iPhrase);\n  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);\n  nTerm = pExpr->pPhrase->nToken;\n  if( pList ){\n    fts3GetDeltaPosition(&pList, &iPos);\n    assert( iPos>=0 );\n  }\n\n  for(iTerm=0; iTerm<nTerm; iTerm++){\n    TermOffset *pT = &p->aTerm[p->iTerm++];\n    pT->iOff = nTerm-iTerm-1;\n    pT->pList = pList;\n    pT->iPos = iPos;\n  }\n\n  return rc;\n}\n\n/*\n** Implementation of offsets() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Offsets(\n  sqlite3_context *pCtx,          /* SQLite function call context */\n  Fts3Cursor *pCsr                /* Cursor object */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;\n  const char *ZDUMMY;             /* Dummy argument used with xNext() */\n  int NDUMMY;                     /* Dummy argument used with xNext() */\n  int rc;                         /* Return Code */\n  int nToken;                     /* Number of tokens in query */\n  int iCol;                       /* Column currently being processed */\n  StrBuffer res = {0, 0, 0};      /* Result string */\n  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_text(pCtx, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  memset(&sCtx, 0, sizeof(sCtx));\n  assert( pCsr->isRequireSeek==0 );\n\n  /* Count the number of terms in the query */\n  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);\n  if( rc!=SQLITE_OK ) goto offsets_out;\n\n  /* Allocate the array of TermOffset iterators. */\n  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);\n  if( 0==sCtx.aTerm ){\n    rc = SQLITE_NOMEM;\n    goto offsets_out;\n  }\n  sCtx.iDocid = pCsr->iPrevId;\n  sCtx.pCsr = pCsr;\n\n  /* Loop through the table columns, appending offset information to \n  ** string-buffer res for each column.\n  */\n  for(iCol=0; iCol<pTab->nColumn; iCol++){\n    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */\n    int iStart;\n    int iEnd;\n    int iCurrent;\n    const char *zDoc;\n    int nDoc;\n\n    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is \n    ** no way that this operation can fail, so the return code from\n    ** fts3ExprIterate() can be discarded.\n    */\n    sCtx.iCol = iCol;\n    sCtx.iTerm = 0;\n    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);\n\n    /* Retreive the text stored in column iCol. If an SQL NULL is stored \n    ** in column iCol, jump immediately to the next iteration of the loop.\n    ** If an OOM occurs while retrieving the data (this can happen if SQLite\n    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM \n    ** to the caller. \n    */\n    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);\n    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);\n    if( zDoc==0 ){\n      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){\n        continue;\n      }\n      rc = SQLITE_NOMEM;\n      goto offsets_out;\n    }\n\n    /* Initialize a tokenizer iterator to iterate through column iCol. */\n    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,\n        zDoc, nDoc, &pC\n    );\n    if( rc!=SQLITE_OK ) goto offsets_out;\n\n    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);\n    while( rc==SQLITE_OK ){\n      int i;                      /* Used to loop through terms */\n      int iMinPos = 0x7FFFFFFF;   /* Position of next token */\n      TermOffset *pTerm = 0;      /* TermOffset associated with next token */\n\n      for(i=0; i<nToken; i++){\n        TermOffset *pT = &sCtx.aTerm[i];\n        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){\n          iMinPos = pT->iPos-pT->iOff;\n          pTerm = pT;\n        }\n      }\n\n      if( !pTerm ){\n        /* All offsets for this column have been gathered. */\n        rc = SQLITE_DONE;\n      }else{\n        assert( iCurrent<=iMinPos );\n        if( 0==(0xFE&*pTerm->pList) ){\n          pTerm->pList = 0;\n        }else{\n          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);\n        }\n        while( rc==SQLITE_OK && iCurrent<iMinPos ){\n          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);\n        }\n        if( rc==SQLITE_OK ){\n          char aBuffer[64];\n          sqlite3_snprintf(sizeof(aBuffer), aBuffer, \n              \"%d %d %d %d \", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart\n          );\n          rc = fts3StringAppend(&res, aBuffer, -1);\n        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){\n          rc = FTS_CORRUPT_VTAB;\n        }\n      }\n    }\n    if( rc==SQLITE_DONE ){\n      rc = SQLITE_OK;\n    }\n\n    pMod->xClose(pC);\n    if( rc!=SQLITE_OK ) goto offsets_out;\n  }\n\n offsets_out:\n  sqlite3_free(sCtx.aTerm);\n  assert( rc!=SQLITE_DONE );\n  sqlite3Fts3SegmentsClose(pTab);\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pCtx,  rc);\n    sqlite3_free(res.z);\n  }else{\n    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);\n  }\n  return;\n}\n\n/*\n** Implementation of matchinfo() function.\n*/\nSQLITE_PRIVATE void sqlite3Fts3Matchinfo(\n  sqlite3_context *pContext,      /* Function call context */\n  Fts3Cursor *pCsr,               /* FTS3 table cursor */\n  const char *zArg                /* Second arg to matchinfo() function */\n){\n  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;\n  int rc;\n  int i;\n  const char *zFormat;\n\n  if( zArg ){\n    for(i=0; zArg[i]; i++){\n      char *zErr = 0;\n      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){\n        sqlite3_result_error(pContext, zErr, -1);\n        sqlite3_free(zErr);\n        return;\n      }\n    }\n    zFormat = zArg;\n  }else{\n    zFormat = FTS3_MATCHINFO_DEFAULT;\n  }\n\n  if( !pCsr->pExpr ){\n    sqlite3_result_blob(pContext, \"\", 0, SQLITE_STATIC);\n    return;\n  }\n\n  /* Retrieve matchinfo() data. */\n  rc = fts3GetMatchinfo(pCsr, zFormat);\n  sqlite3Fts3SegmentsClose(pTab);\n\n  if( rc!=SQLITE_OK ){\n    sqlite3_result_error_code(pContext, rc);\n  }else{\n    int n = pCsr->nMatchinfo * sizeof(u32);\n    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);\n  }\n}\n\n#endif\n\n/************** End of fts3_snippet.c ****************************************/\n/************** Begin file fts3_unicode.c ************************************/\n/*\n** 2012 May 24\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n**\n** Implementation of the \"unicode\" full-text-search tokenizer.\n*/\n\n#ifdef SQLITE_ENABLE_FTS4_UNICODE61\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n\n/* #include <assert.h> */\n/* #include <stdlib.h> */\n/* #include <stdio.h> */\n/* #include <string.h> */\n\n\n/*\n** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied\n** from the sqlite3 source file utf.c. If this file is compiled as part\n** of the amalgamation, they are not required.\n*/\n#ifndef SQLITE_AMALGAMATION\n\nstatic const unsigned char sqlite3Utf8Trans1[] = {\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,\n  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,\n  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,\n};\n\n#define READ_UTF8(zIn, zTerm, c)                           \\\n  c = *(zIn++);                                            \\\n  if( c>=0xc0 ){                                           \\\n    c = sqlite3Utf8Trans1[c-0xc0];                         \\\n    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \\\n      c = (c<<6) + (0x3f & *(zIn++));                      \\\n    }                                                      \\\n    if( c<0x80                                             \\\n        || (c&0xFFFFF800)==0xD800                          \\\n        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \\\n  }\n\n#define WRITE_UTF8(zOut, c) {                          \\\n  if( c<0x00080 ){                                     \\\n    *zOut++ = (u8)(c&0xFF);                            \\\n  }                                                    \\\n  else if( c<0x00800 ){                                \\\n    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n  else if( c<0x10000 ){                                \\\n    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }else{                                               \\\n    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \\\n    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \\\n    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \\\n    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \\\n  }                                                    \\\n}\n\n#endif /* ifndef SQLITE_AMALGAMATION */\n\ntypedef struct unicode_tokenizer unicode_tokenizer;\ntypedef struct unicode_cursor unicode_cursor;\n\nstruct unicode_tokenizer {\n  sqlite3_tokenizer base;\n  int bRemoveDiacritic;\n  int nException;\n  int *aiException;\n};\n\nstruct unicode_cursor {\n  sqlite3_tokenizer_cursor base;\n  const unsigned char *aInput;    /* Input text being tokenized */\n  int nInput;                     /* Size of aInput[] in bytes */\n  int iOff;                       /* Current offset within aInput[] */\n  int iToken;                     /* Index of next token to be returned */\n  char *zToken;                   /* storage for current token */\n  int nAlloc;                     /* space allocated at zToken */\n};\n\n\n/*\n** Destroy a tokenizer allocated by unicodeCreate().\n*/\nstatic int unicodeDestroy(sqlite3_tokenizer *pTokenizer){\n  if( pTokenizer ){\n    unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;\n    sqlite3_free(p->aiException);\n    sqlite3_free(p);\n  }\n  return SQLITE_OK;\n}\n\n/*\n** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE\n** statement has specified that the tokenizer for this table shall consider\n** all characters in string zIn/nIn to be separators (if bAlnum==0) or\n** token characters (if bAlnum==1).\n**\n** For each codepoint in the zIn/nIn string, this function checks if the\n** sqlite3FtsUnicodeIsalnum() function already returns the desired result.\n** If so, no action is taken. Otherwise, the codepoint is added to the \n** unicode_tokenizer.aiException[] array. For the purposes of tokenization,\n** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all\n** codepoints in the aiException[] array.\n**\n** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()\n** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.\n** It is not possible to change the behaviour of the tokenizer with respect\n** to these codepoints.\n*/\nstatic int unicodeAddExceptions(\n  unicode_tokenizer *p,           /* Tokenizer to add exceptions to */\n  int bAlnum,                     /* Replace Isalnum() return value with this */\n  const char *zIn,                /* Array of characters to make exceptions */\n  int nIn                         /* Length of z in bytes */\n){\n  const unsigned char *z = (const unsigned char *)zIn;\n  const unsigned char *zTerm = &z[nIn];\n  int iCode;\n  int nEntry = 0;\n\n  assert( bAlnum==0 || bAlnum==1 );\n\n  while( z<zTerm ){\n    READ_UTF8(z, zTerm, iCode);\n    assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );\n    if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum \n     && sqlite3FtsUnicodeIsdiacritic(iCode)==0 \n    ){\n      nEntry++;\n    }\n  }\n\n  if( nEntry ){\n    int *aNew;                    /* New aiException[] array */\n    int nNew;                     /* Number of valid entries in array aNew[] */\n\n    aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));\n    if( aNew==0 ) return SQLITE_NOMEM;\n    nNew = p->nException;\n\n    z = (const unsigned char *)zIn;\n    while( z<zTerm ){\n      READ_UTF8(z, zTerm, iCode);\n      if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum \n       && sqlite3FtsUnicodeIsdiacritic(iCode)==0\n      ){\n        int i, j;\n        for(i=0; i<nNew && aNew[i]<iCode; i++);\n        for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];\n        aNew[i] = iCode;\n        nNew++;\n      }\n    }\n    p->aiException = aNew;\n    p->nException = nNew;\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Return true if the p->aiException[] array contains the value iCode.\n*/\nstatic int unicodeIsException(unicode_tokenizer *p, int iCode){\n  if( p->nException>0 ){\n    int *a = p->aiException;\n    int iLo = 0;\n    int iHi = p->nException-1;\n\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      if( iCode==a[iTest] ){\n        return 1;\n      }else if( iCode>a[iTest] ){\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n  }\n\n  return 0;\n}\n\n/*\n** Return true if, for the purposes of tokenization, codepoint iCode is\n** considered a token character (not a separator).\n*/\nstatic int unicodeIsAlnum(unicode_tokenizer *p, int iCode){\n  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );\n  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);\n}\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int unicodeCreate(\n  int nArg,                       /* Size of array argv[] */\n  const char * const *azArg,      /* Tokenizer creation arguments */\n  sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */\n){\n  unicode_tokenizer *pNew;        /* New tokenizer object */\n  int i;\n  int rc = SQLITE_OK;\n\n  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));\n  if( pNew==NULL ) return SQLITE_NOMEM;\n  memset(pNew, 0, sizeof(unicode_tokenizer));\n  pNew->bRemoveDiacritic = 1;\n\n  for(i=0; rc==SQLITE_OK && i<nArg; i++){\n    const char *z = azArg[i];\n    int n = strlen(z);\n\n    if( n==19 && memcmp(\"remove_diacritics=1\", z, 19)==0 ){\n      pNew->bRemoveDiacritic = 1;\n    }\n    else if( n==19 && memcmp(\"remove_diacritics=0\", z, 19)==0 ){\n      pNew->bRemoveDiacritic = 0;\n    }\n    else if( n>=11 && memcmp(\"tokenchars=\", z, 11)==0 ){\n      rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);\n    }\n    else if( n>=11 && memcmp(\"separators=\", z, 11)==0 ){\n      rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);\n    }\n    else{\n      /* Unrecognized argument */\n      rc  = SQLITE_ERROR;\n    }\n  }\n\n  if( rc!=SQLITE_OK ){\n    unicodeDestroy((sqlite3_tokenizer *)pNew);\n    pNew = 0;\n  }\n  *pp = (sqlite3_tokenizer *)pNew;\n  return rc;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int unicodeOpen(\n  sqlite3_tokenizer *p,           /* The tokenizer */\n  const char *aInput,             /* Input string */\n  int nInput,                     /* Size of string aInput in bytes */\n  sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */\n){\n  unicode_cursor *pCsr;\n\n  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));\n  if( pCsr==0 ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(unicode_cursor));\n\n  pCsr->aInput = (const unsigned char *)aInput;\n  if( aInput==0 ){\n    pCsr->nInput = 0;\n  }else if( nInput<0 ){\n    pCsr->nInput = (int)strlen(aInput);\n  }else{\n    pCsr->nInput = nInput;\n  }\n\n  *pp = &pCsr->base;\n  UNUSED_PARAMETER(p);\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to\n** simpleOpen() above.\n*/\nstatic int unicodeClose(sqlite3_tokenizer_cursor *pCursor){\n  unicode_cursor *pCsr = (unicode_cursor *) pCursor;\n  sqlite3_free(pCsr->zToken);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.  The cursor must\n** have been opened by a prior call to simpleOpen().\n*/\nstatic int unicodeNext(\n  sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */\n  const char **paToken,           /* OUT: Token text */\n  int *pnToken,                   /* OUT: Number of bytes at *paToken */\n  int *piStart,                   /* OUT: Starting offset of token */\n  int *piEnd,                     /* OUT: Ending offset of token */\n  int *piPos                      /* OUT: Position integer of token */\n){\n  unicode_cursor *pCsr = (unicode_cursor *)pC;\n  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);\n  int iCode;\n  char *zOut;\n  const unsigned char *z = &pCsr->aInput[pCsr->iOff];\n  const unsigned char *zStart = z;\n  const unsigned char *zEnd;\n  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];\n\n  /* Scan past any delimiter characters before the start of the next token.\n  ** Return SQLITE_DONE early if this takes us all the way to the end of \n  ** the input.  */\n  while( z<zTerm ){\n    READ_UTF8(z, zTerm, iCode);\n    if( unicodeIsAlnum(p, iCode) ) break;\n    zStart = z;\n  }\n  if( zStart>=zTerm ) return SQLITE_DONE;\n\n  zOut = pCsr->zToken;\n  do {\n    int iOut;\n\n    /* Grow the output buffer if required. */\n    if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){\n      char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);\n      if( !zNew ) return SQLITE_NOMEM;\n      zOut = &zNew[zOut - pCsr->zToken];\n      pCsr->zToken = zNew;\n      pCsr->nAlloc += 64;\n    }\n\n    /* Write the folded case of the last character read to the output */\n    zEnd = z;\n    iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);\n    if( iOut ){\n      WRITE_UTF8(zOut, iOut);\n    }\n\n    /* If the cursor is not at EOF, read the next character */\n    if( z>=zTerm ) break;\n    READ_UTF8(z, zTerm, iCode);\n  }while( unicodeIsAlnum(p, iCode) \n       || sqlite3FtsUnicodeIsdiacritic(iCode)\n  );\n\n  /* Set the output variables and return. */\n  pCsr->iOff = (z - pCsr->aInput);\n  *paToken = pCsr->zToken;\n  *pnToken = zOut - pCsr->zToken;\n  *piStart = (zStart - pCsr->aInput);\n  *piEnd = (zEnd - pCsr->aInput);\n  *piPos = pCsr->iToken++;\n  return SQLITE_OK;\n}\n\n/*\n** Set *ppModule to a pointer to the sqlite3_tokenizer_module \n** structure for the unicode tokenizer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){\n  static const sqlite3_tokenizer_module module = {\n    0,\n    unicodeCreate,\n    unicodeDestroy,\n    unicodeOpen,\n    unicodeClose,\n    unicodeNext,\n    0,\n  };\n  *ppModule = &module;\n}\n\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n#endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */\n\n/************** End of fts3_unicode.c ****************************************/\n/************** Begin file fts3_unicode2.c ***********************************/\n/*\n** 2012 May 25\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n******************************************************************************\n*/\n\n/*\n** DO NOT EDIT THIS MACHINE GENERATED FILE.\n*/\n\n#if defined(SQLITE_ENABLE_FTS4_UNICODE61)\n#if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)\n\n/* #include <assert.h> */\n\n/*\n** Return true if the argument corresponds to a unicode codepoint\n** classified as either a letter or a number. Otherwise false.\n**\n** The results are undefined if the value passed to this function\n** is less than zero.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){\n  /* Each unsigned integer in the following array corresponds to a contiguous\n  ** range of unicode codepoints that are not either letters or numbers (i.e.\n  ** codepoints for which this function should return 0).\n  **\n  ** The most significant 22 bits in each 32-bit value contain the first \n  ** codepoint in the range. The least significant 10 bits are used to store\n  ** the size of the range (always at least 1). In other words, the value \n  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint \n  ** C. It is not possible to represent a range larger than 1023 codepoints \n  ** using this format.\n  */\n  const static unsigned int aEntry[] = {\n    0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,\n    0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,\n    0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,\n    0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,\n    0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,\n    0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,\n    0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,\n    0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,\n    0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,\n    0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,\n    0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,\n    0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,\n    0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,\n    0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,\n    0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,\n    0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,\n    0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,\n    0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,\n    0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,\n    0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,\n    0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,\n    0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,\n    0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,\n    0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,\n    0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,\n    0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,\n    0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,\n    0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,\n    0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,\n    0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,\n    0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,\n    0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,\n    0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,\n    0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,\n    0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,\n    0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,\n    0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,\n    0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,\n    0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,\n    0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,\n    0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,\n    0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,\n    0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,\n    0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,\n    0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,\n    0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,\n    0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,\n    0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,\n    0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,\n    0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,\n    0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,\n    0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,\n    0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,\n    0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,\n    0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,\n    0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,\n    0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,\n    0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,\n    0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,\n    0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,\n    0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,\n    0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,\n    0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,\n    0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,\n    0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,\n    0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,\n    0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,\n    0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,\n    0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,\n    0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,\n    0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,\n    0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,\n    0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,\n    0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,\n    0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,\n    0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,\n    0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,\n    0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,\n    0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,\n    0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,\n    0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,\n    0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,\n    0x43FFF401,\n  };\n  static const unsigned int aAscii[4] = {\n    0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,\n  };\n\n  if( c<128 ){\n    return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );\n  }else if( c<(1<<22) ){\n    unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;\n    int iRes;\n    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;\n    int iLo = 0;\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      if( key >= aEntry[iTest] ){\n        iRes = iTest;\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n    assert( aEntry[0]<key );\n    assert( key>=aEntry[iRes] );\n    return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));\n  }\n  return 1;\n}\n\n\n/*\n** If the argument is a codepoint corresponding to a lowercase letter\n** in the ASCII range with a diacritic added, return the codepoint\n** of the ASCII letter only. For example, if passed 235 - \"LATIN\n** SMALL LETTER E WITH DIAERESIS\" - return 65 (\"LATIN SMALL LETTER\n** E\"). The resuls of passing a codepoint that corresponds to an\n** uppercase letter are undefined.\n*/\nstatic int remove_diacritic(int c){\n  unsigned short aDia[] = {\n        0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, \n     2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, \n     2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, \n     2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, \n     3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, \n     3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, \n     4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, \n     6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, \n    61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, \n    61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, \n    62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, \n    62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, \n    62924, 63050, 63082, 63274, 63390, \n  };\n  char aChar[] = {\n    '\\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  \n    'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  \n    's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  \n    'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  \n    'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\\0', '\\0', '\\0', '\\0', \n    '\\0', '\\0', '\\0', '\\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  \n    'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  \n    'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  \n    'e',  'i',  'o',  'u',  'y',  \n  };\n\n  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;\n  int iRes = 0;\n  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;\n  int iLo = 0;\n  while( iHi>=iLo ){\n    int iTest = (iHi + iLo) / 2;\n    if( key >= aDia[iTest] ){\n      iRes = iTest;\n      iLo = iTest+1;\n    }else{\n      iHi = iTest-1;\n    }\n  }\n  assert( key>=aDia[iRes] );\n  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);\n};\n\n\n/*\n** Return true if the argument interpreted as a unicode codepoint\n** is a diacritical modifier character.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){\n  unsigned int mask0 = 0x08029FDF;\n  unsigned int mask1 = 0x000361F8;\n  if( c<768 || c>817 ) return 0;\n  return (c < 768+32) ?\n      (mask0 & (1 << (c-768))) :\n      (mask1 & (1 << (c-768-32)));\n}\n\n\n/*\n** Interpret the argument as a unicode codepoint. If the codepoint\n** is an upper case character that has a lower case equivalent,\n** return the codepoint corresponding to the lower case version.\n** Otherwise, return a copy of the argument.\n**\n** The results are undefined if the value passed to this function\n** is less than zero.\n*/\nSQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){\n  /* Each entry in the following array defines a rule for folding a range\n  ** of codepoints to lower case. The rule applies to a range of nRange\n  ** codepoints starting at codepoint iCode.\n  **\n  ** If the least significant bit in flags is clear, then the rule applies\n  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and\n  ** need to be folded). Or, if it is set, then the rule only applies to\n  ** every second codepoint in the range, starting with codepoint C.\n  **\n  ** The 7 most significant bits in flags are an index into the aiOff[]\n  ** array. If a specific codepoint C does require folding, then its lower\n  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).\n  **\n  ** The contents of this array are generated by parsing the CaseFolding.txt\n  ** file distributed as part of the \"Unicode Character Database\". See\n  ** http://www.unicode.org for details.\n  */\n  static const struct TableEntry {\n    unsigned short iCode;\n    unsigned char flags;\n    unsigned char nRange;\n  } aEntry[] = {\n    {65, 14, 26},          {181, 64, 1},          {192, 14, 23},\n    {216, 14, 7},          {256, 1, 48},          {306, 1, 6},\n    {313, 1, 16},          {330, 1, 46},          {376, 116, 1},\n    {377, 1, 6},           {383, 104, 1},         {385, 50, 1},\n    {386, 1, 4},           {390, 44, 1},          {391, 0, 1},\n    {393, 42, 2},          {395, 0, 1},           {398, 32, 1},\n    {399, 38, 1},          {400, 40, 1},          {401, 0, 1},\n    {403, 42, 1},          {404, 46, 1},          {406, 52, 1},\n    {407, 48, 1},          {408, 0, 1},           {412, 52, 1},\n    {413, 54, 1},          {415, 56, 1},          {416, 1, 6},\n    {422, 60, 1},          {423, 0, 1},           {425, 60, 1},\n    {428, 0, 1},           {430, 60, 1},          {431, 0, 1},\n    {433, 58, 2},          {435, 1, 4},           {439, 62, 1},\n    {440, 0, 1},           {444, 0, 1},           {452, 2, 1},\n    {453, 0, 1},           {455, 2, 1},           {456, 0, 1},\n    {458, 2, 1},           {459, 1, 18},          {478, 1, 18},\n    {497, 2, 1},           {498, 1, 4},           {502, 122, 1},\n    {503, 134, 1},         {504, 1, 40},          {544, 110, 1},\n    {546, 1, 18},          {570, 70, 1},          {571, 0, 1},\n    {573, 108, 1},         {574, 68, 1},          {577, 0, 1},\n    {579, 106, 1},         {580, 28, 1},          {581, 30, 1},\n    {582, 1, 10},          {837, 36, 1},          {880, 1, 4},\n    {886, 0, 1},           {902, 18, 1},          {904, 16, 3},\n    {908, 26, 1},          {910, 24, 2},          {913, 14, 17},\n    {931, 14, 9},          {962, 0, 1},           {975, 4, 1},\n    {976, 140, 1},         {977, 142, 1},         {981, 146, 1},\n    {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},\n    {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},\n    {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},\n    {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},\n    {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},\n    {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},\n    {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},\n    {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},\n    {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},\n    {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},\n    {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},\n    {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},\n    {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},\n    {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},\n    {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},\n    {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},\n    {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},\n    {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},\n    {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},\n    {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},\n    {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},\n    {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},\n    {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},\n    {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},\n    {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},\n    {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},\n    {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},\n    {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},\n    {65313, 14, 26},       \n  };\n  static const unsigned short aiOff[] = {\n   1,     2,     8,     15,    16,    26,    28,    32,    \n   37,    38,    40,    48,    63,    64,    69,    71,    \n   79,    80,    116,   202,   203,   205,   206,   207,   \n   209,   210,   211,   213,   214,   217,   218,   219,   \n   775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, \n   54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, \n   57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, \n   65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, \n   65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, \n   65514, 65521, 65527, 65528, 65529, \n  };\n\n  int ret = c;\n\n  assert( c>=0 );\n  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );\n\n  if( c<128 ){\n    if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');\n  }else if( c<65536 ){\n    int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;\n    int iLo = 0;\n    int iRes = -1;\n\n    while( iHi>=iLo ){\n      int iTest = (iHi + iLo) / 2;\n      int cmp = (c - aEntry[iTest].iCode);\n      if( cmp>=0 ){\n        iRes = iTest;\n        iLo = iTest+1;\n      }else{\n        iHi = iTest-1;\n      }\n    }\n    assert( iRes<0 || c>=aEntry[iRes].iCode );\n\n    if( iRes>=0 ){\n      const struct TableEntry *p = &aEntry[iRes];\n      if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){\n        ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;\n        assert( ret>0 );\n      }\n    }\n\n    if( bRemoveDiacritic ) ret = remove_diacritic(ret);\n  }\n  \n  else if( c>=66560 && c<66600 ){\n    ret = c + 40;\n  }\n\n  return ret;\n}\n#endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */\n#endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */\n\n/************** End of fts3_unicode2.c ***************************************/\n/************** Begin file rtree.c *******************************************/\n/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file contains code for implementations of the r-tree and r*-tree\n** algorithms packaged as an SQLite virtual table module.\n*/\n\n/*\n** Database Format of R-Tree Tables\n** --------------------------------\n**\n** The data structure for a single virtual r-tree table is stored in three \n** native SQLite tables declared as follows. In each case, the '%' character\n** in the table name is replaced with the user-supplied name of the r-tree\n** table.\n**\n**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)\n**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)\n**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)\n**\n** The data for each node of the r-tree structure is stored in the %_node\n** table. For each node that is not the root node of the r-tree, there is\n** an entry in the %_parent table associating the node with its parent.\n** And for each row of data in the table, there is an entry in the %_rowid\n** table that maps from the entries rowid to the id of the node that it\n** is stored on.\n**\n** The root node of an r-tree always exists, even if the r-tree table is\n** empty. The nodeno of the root node is always 1. All other nodes in the\n** table must be the same size as the root node. The content of each node\n** is formatted as follows:\n**\n**   1. If the node is the root node (node 1), then the first 2 bytes\n**      of the node contain the tree depth as a big-endian integer.\n**      For non-root nodes, the first 2 bytes are left unused.\n**\n**   2. The next 2 bytes contain the number of entries currently \n**      stored in the node.\n**\n**   3. The remainder of the node contains the node entries. Each entry\n**      consists of a single 8-byte integer followed by an even number\n**      of 4-byte coordinates. For leaf nodes the integer is the rowid\n**      of a record. For internal nodes it is the node number of a\n**      child page.\n*/\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)\n\n/*\n** This file contains an implementation of a couple of different variants\n** of the r-tree algorithm. See the README file for further details. The \n** same data-structure is used for all, but the algorithms for insert and\n** delete operations vary. The variants used are selected at compile time \n** by defining the following symbols:\n*/\n\n/* Either, both or none of the following may be set to activate \n** r*tree variant algorithms.\n*/\n#define VARIANT_RSTARTREE_CHOOSESUBTREE 0\n#define VARIANT_RSTARTREE_REINSERT      1\n\n/* \n** Exactly one of the following must be set to 1.\n*/\n#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0\n#define VARIANT_GUTTMAN_LINEAR_SPLIT    0\n#define VARIANT_RSTARTREE_SPLIT         1\n\n#define VARIANT_GUTTMAN_SPLIT \\\n        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)\n\n#if VARIANT_GUTTMAN_QUADRATIC_SPLIT\n  #define PickNext QuadraticPickNext\n  #define PickSeeds QuadraticPickSeeds\n  #define AssignCells splitNodeGuttman\n#endif\n#if VARIANT_GUTTMAN_LINEAR_SPLIT\n  #define PickNext LinearPickNext\n  #define PickSeeds LinearPickSeeds\n  #define AssignCells splitNodeGuttman\n#endif\n#if VARIANT_RSTARTREE_SPLIT\n  #define AssignCells splitNodeStartree\n#endif\n\n#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) \n# define NDEBUG 1\n#endif\n\n#ifndef SQLITE_CORE\n  SQLITE_EXTENSION_INIT1\n#else\n#endif\n\n/* #include <string.h> */\n/* #include <assert.h> */\n\n#ifndef SQLITE_AMALGAMATION\n#include \"sqlite3rtree.h\"\ntypedef sqlite3_int64 i64;\ntypedef unsigned char u8;\ntypedef unsigned int u32;\n#endif\n\n/*  The following macro is used to suppress compiler warnings.\n*/\n#ifndef UNUSED_PARAMETER\n# define UNUSED_PARAMETER(x) (void)(x)\n#endif\n\ntypedef struct Rtree Rtree;\ntypedef struct RtreeCursor RtreeCursor;\ntypedef struct RtreeNode RtreeNode;\ntypedef struct RtreeCell RtreeCell;\ntypedef struct RtreeConstraint RtreeConstraint;\ntypedef struct RtreeMatchArg RtreeMatchArg;\ntypedef struct RtreeGeomCallback RtreeGeomCallback;\ntypedef union RtreeCoord RtreeCoord;\n\n/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */\n#define RTREE_MAX_DIMENSIONS 5\n\n/* Size of hash table Rtree.aHash. This hash table is not expected to\n** ever contain very many entries, so a fixed number of buckets is \n** used.\n*/\n#define HASHSIZE 128\n\n/* \n** An rtree virtual-table object.\n*/\nstruct Rtree {\n  sqlite3_vtab base;\n  sqlite3 *db;                /* Host database connection */\n  int iNodeSize;              /* Size in bytes of each node in the node table */\n  int nDim;                   /* Number of dimensions */\n  int nBytesPerCell;          /* Bytes consumed per cell */\n  int iDepth;                 /* Current depth of the r-tree structure */\n  char *zDb;                  /* Name of database containing r-tree table */\n  char *zName;                /* Name of r-tree table */ \n  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ \n  int nBusy;                  /* Current number of users of this structure */\n\n  /* List of nodes removed during a CondenseTree operation. List is\n  ** linked together via the pointer normally used for hash chains -\n  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree \n  ** headed by the node (leaf nodes have RtreeNode.iNode==0).\n  */\n  RtreeNode *pDeleted;\n  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */\n\n  /* Statements to read/write/delete a record from xxx_node */\n  sqlite3_stmt *pReadNode;\n  sqlite3_stmt *pWriteNode;\n  sqlite3_stmt *pDeleteNode;\n\n  /* Statements to read/write/delete a record from xxx_rowid */\n  sqlite3_stmt *pReadRowid;\n  sqlite3_stmt *pWriteRowid;\n  sqlite3_stmt *pDeleteRowid;\n\n  /* Statements to read/write/delete a record from xxx_parent */\n  sqlite3_stmt *pReadParent;\n  sqlite3_stmt *pWriteParent;\n  sqlite3_stmt *pDeleteParent;\n\n  int eCoordType;\n};\n\n/* Possible values for eCoordType: */\n#define RTREE_COORD_REAL32 0\n#define RTREE_COORD_INT32  1\n\n/*\n** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will\n** only deal with integer coordinates.  No floating point operations\n** will be done.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n  typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */\n  typedef int RtreeValue;                  /* Low accuracy coordinate */\n#else\n  typedef double RtreeDValue;              /* High accuracy coordinate */\n  typedef float RtreeValue;                /* Low accuracy coordinate */\n#endif\n\n/*\n** The minimum number of cells allowed for a node is a third of the \n** maximum. In Gutman's notation:\n**\n**     m = M/3\n**\n** If an R*-tree \"Reinsert\" operation is required, the same number of\n** cells are removed from the overfull node and reinserted into the tree.\n*/\n#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)\n#define RTREE_REINSERT(p) RTREE_MINCELLS(p)\n#define RTREE_MAXCELLS 51\n\n/*\n** The smallest possible node-size is (512-64)==448 bytes. And the largest\n** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).\n** Therefore all non-root nodes must contain at least 3 entries. Since \n** 2^40 is greater than 2^64, an r-tree structure always has a depth of\n** 40 or less.\n*/\n#define RTREE_MAX_DEPTH 40\n\n/* \n** An rtree cursor object.\n*/\nstruct RtreeCursor {\n  sqlite3_vtab_cursor base;\n  RtreeNode *pNode;                 /* Node cursor is currently pointing at */\n  int iCell;                        /* Index of current cell in pNode */\n  int iStrategy;                    /* Copy of idxNum search parameter */\n  int nConstraint;                  /* Number of entries in aConstraint */\n  RtreeConstraint *aConstraint;     /* Search constraints. */\n};\n\nunion RtreeCoord {\n  RtreeValue f;\n  int i;\n};\n\n/*\n** The argument is an RtreeCoord. Return the value stored within the RtreeCoord\n** formatted as a RtreeDValue (double or int64). This macro assumes that local\n** variable pRtree points to the Rtree structure associated with the\n** RtreeCoord.\n*/\n#ifdef SQLITE_RTREE_INT_ONLY\n# define DCOORD(coord) ((RtreeDValue)coord.i)\n#else\n# define DCOORD(coord) (                           \\\n    (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \\\n      ((double)coord.f) :                           \\\n      ((double)coord.i)                             \\\n  )\n#endif\n\n/*\n** A search constraint.\n*/\nstruct RtreeConstraint {\n  int iCoord;                     /* Index of constrained coordinate */\n  int op;                         /* Constraining operation */\n  RtreeDValue rValue;             /* Constraint value. */\n  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);\n  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */\n};\n\n/* Possible values for RtreeConstraint.op */\n#define RTREE_EQ    0x41\n#define RTREE_LE    0x42\n#define RTREE_LT    0x43\n#define RTREE_GE    0x44\n#define RTREE_GT    0x45\n#define RTREE_MATCH 0x46\n\n/* \n** An rtree structure node.\n*/\nstruct RtreeNode {\n  RtreeNode *pParent;               /* Parent node */\n  i64 iNode;\n  int nRef;\n  int isDirty;\n  u8 *zData;\n  RtreeNode *pNext;                 /* Next node in this hash chain */\n};\n#define NCELL(pNode) readInt16(&(pNode)->zData[2])\n\n/* \n** Structure to store a deserialized rtree record.\n*/\nstruct RtreeCell {\n  i64 iRowid;\n  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];\n};\n\n\n/*\n** Value for the first field of every RtreeMatchArg object. The MATCH\n** operator tests that the first field of a blob operand matches this\n** value to avoid operating on invalid blobs (which could cause a segfault).\n*/\n#define RTREE_GEOMETRY_MAGIC 0x891245AB\n\n/*\n** An instance of this structure must be supplied as a blob argument to\n** the right-hand-side of an SQL MATCH operator used to constrain an\n** r-tree query.\n*/\nstruct RtreeMatchArg {\n  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */\n  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);\n  void *pContext;\n  int nParam;\n  RtreeDValue aParam[1];\n};\n\n/*\n** When a geometry callback is created (see sqlite3_rtree_geometry_callback),\n** a single instance of the following structure is allocated. It is used\n** as the context for the user-function created by by s_r_g_c(). The object\n** is eventually deleted by the destructor mechanism provided by\n** sqlite3_create_function_v2() (which is called by s_r_g_c() to create\n** the geometry callback function).\n*/\nstruct RtreeGeomCallback {\n  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);\n  void *pContext;\n};\n\n#ifndef MAX\n# define MAX(x,y) ((x) < (y) ? (y) : (x))\n#endif\n#ifndef MIN\n# define MIN(x,y) ((x) > (y) ? (y) : (x))\n#endif\n\n/*\n** Functions to deserialize a 16 bit integer, 32 bit real number and\n** 64 bit integer. The deserialized value is returned.\n*/\nstatic int readInt16(u8 *p){\n  return (p[0]<<8) + p[1];\n}\nstatic void readCoord(u8 *p, RtreeCoord *pCoord){\n  u32 i = (\n    (((u32)p[0]) << 24) + \n    (((u32)p[1]) << 16) + \n    (((u32)p[2]) <<  8) + \n    (((u32)p[3]) <<  0)\n  );\n  *(u32 *)pCoord = i;\n}\nstatic i64 readInt64(u8 *p){\n  return (\n    (((i64)p[0]) << 56) + \n    (((i64)p[1]) << 48) + \n    (((i64)p[2]) << 40) + \n    (((i64)p[3]) << 32) + \n    (((i64)p[4]) << 24) + \n    (((i64)p[5]) << 16) + \n    (((i64)p[6]) <<  8) + \n    (((i64)p[7]) <<  0)\n  );\n}\n\n/*\n** Functions to serialize a 16 bit integer, 32 bit real number and\n** 64 bit integer. The value returned is the number of bytes written\n** to the argument buffer (always 2, 4 and 8 respectively).\n*/\nstatic int writeInt16(u8 *p, int i){\n  p[0] = (i>> 8)&0xFF;\n  p[1] = (i>> 0)&0xFF;\n  return 2;\n}\nstatic int writeCoord(u8 *p, RtreeCoord *pCoord){\n  u32 i;\n  assert( sizeof(RtreeCoord)==4 );\n  assert( sizeof(u32)==4 );\n  i = *(u32 *)pCoord;\n  p[0] = (i>>24)&0xFF;\n  p[1] = (i>>16)&0xFF;\n  p[2] = (i>> 8)&0xFF;\n  p[3] = (i>> 0)&0xFF;\n  return 4;\n}\nstatic int writeInt64(u8 *p, i64 i){\n  p[0] = (i>>56)&0xFF;\n  p[1] = (i>>48)&0xFF;\n  p[2] = (i>>40)&0xFF;\n  p[3] = (i>>32)&0xFF;\n  p[4] = (i>>24)&0xFF;\n  p[5] = (i>>16)&0xFF;\n  p[6] = (i>> 8)&0xFF;\n  p[7] = (i>> 0)&0xFF;\n  return 8;\n}\n\n/*\n** Increment the reference count of node p.\n*/\nstatic void nodeReference(RtreeNode *p){\n  if( p ){\n    p->nRef++;\n  }\n}\n\n/*\n** Clear the content of node p (set all bytes to 0x00).\n*/\nstatic void nodeZero(Rtree *pRtree, RtreeNode *p){\n  memset(&p->zData[2], 0, pRtree->iNodeSize-2);\n  p->isDirty = 1;\n}\n\n/*\n** Given a node number iNode, return the corresponding key to use\n** in the Rtree.aHash table.\n*/\nstatic int nodeHash(i64 iNode){\n  return (\n    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ \n    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)\n  ) % HASHSIZE;\n}\n\n/*\n** Search the node hash table for node iNode. If found, return a pointer\n** to it. Otherwise, return 0.\n*/\nstatic RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){\n  RtreeNode *p;\n  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);\n  return p;\n}\n\n/*\n** Add node pNode to the node hash table.\n*/\nstatic void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){\n  int iHash;\n  assert( pNode->pNext==0 );\n  iHash = nodeHash(pNode->iNode);\n  pNode->pNext = pRtree->aHash[iHash];\n  pRtree->aHash[iHash] = pNode;\n}\n\n/*\n** Remove node pNode from the node hash table.\n*/\nstatic void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){\n  RtreeNode **pp;\n  if( pNode->iNode!=0 ){\n    pp = &pRtree->aHash[nodeHash(pNode->iNode)];\n    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }\n    *pp = pNode->pNext;\n    pNode->pNext = 0;\n  }\n}\n\n/*\n** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),\n** indicating that node has not yet been assigned a node number. It is\n** assigned a node number when nodeWrite() is called to write the\n** node contents out to the database.\n*/\nstatic RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){\n  RtreeNode *pNode;\n  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);\n  if( pNode ){\n    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);\n    pNode->zData = (u8 *)&pNode[1];\n    pNode->nRef = 1;\n    pNode->pParent = pParent;\n    pNode->isDirty = 1;\n    nodeReference(pParent);\n  }\n  return pNode;\n}\n\n/*\n** Obtain a reference to an r-tree node.\n*/\nstatic int\nnodeAcquire(\n  Rtree *pRtree,             /* R-tree structure */\n  i64 iNode,                 /* Node number to load */\n  RtreeNode *pParent,        /* Either the parent node or NULL */\n  RtreeNode **ppNode         /* OUT: Acquired node */\n){\n  int rc;\n  int rc2 = SQLITE_OK;\n  RtreeNode *pNode;\n\n  /* Check if the requested node is already in the hash table. If so,\n  ** increase its reference count and return it.\n  */\n  if( (pNode = nodeHashLookup(pRtree, iNode)) ){\n    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );\n    if( pParent && !pNode->pParent ){\n      nodeReference(pParent);\n      pNode->pParent = pParent;\n    }\n    pNode->nRef++;\n    *ppNode = pNode;\n    return SQLITE_OK;\n  }\n\n  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);\n  rc = sqlite3_step(pRtree->pReadNode);\n  if( rc==SQLITE_ROW ){\n    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);\n    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){\n      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);\n      if( !pNode ){\n        rc2 = SQLITE_NOMEM;\n      }else{\n        pNode->pParent = pParent;\n        pNode->zData = (u8 *)&pNode[1];\n        pNode->nRef = 1;\n        pNode->iNode = iNode;\n        pNode->isDirty = 0;\n        pNode->pNext = 0;\n        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);\n        nodeReference(pParent);\n      }\n    }\n  }\n  rc = sqlite3_reset(pRtree->pReadNode);\n  if( rc==SQLITE_OK ) rc = rc2;\n\n  /* If the root node was just loaded, set pRtree->iDepth to the height\n  ** of the r-tree structure. A height of zero means all data is stored on\n  ** the root node. A height of one means the children of the root node\n  ** are the leaves, and so on. If the depth as specified on the root node\n  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.\n  */\n  if( pNode && iNode==1 ){\n    pRtree->iDepth = readInt16(pNode->zData);\n    if( pRtree->iDepth>RTREE_MAX_DEPTH ){\n      rc = SQLITE_CORRUPT_VTAB;\n    }\n  }\n\n  /* If no error has occurred so far, check if the \"number of entries\"\n  ** field on the node is too large. If so, set the return code to \n  ** SQLITE_CORRUPT_VTAB.\n  */\n  if( pNode && rc==SQLITE_OK ){\n    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){\n      rc = SQLITE_CORRUPT_VTAB;\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    if( pNode!=0 ){\n      nodeHashInsert(pRtree, pNode);\n    }else{\n      rc = SQLITE_CORRUPT_VTAB;\n    }\n    *ppNode = pNode;\n  }else{\n    sqlite3_free(pNode);\n    *ppNode = 0;\n  }\n\n  return rc;\n}\n\n/*\n** Overwrite cell iCell of node pNode with the contents of pCell.\n*/\nstatic void nodeOverwriteCell(\n  Rtree *pRtree, \n  RtreeNode *pNode,  \n  RtreeCell *pCell, \n  int iCell\n){\n  int ii;\n  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];\n  p += writeInt64(p, pCell->iRowid);\n  for(ii=0; ii<(pRtree->nDim*2); ii++){\n    p += writeCoord(p, &pCell->aCoord[ii]);\n  }\n  pNode->isDirty = 1;\n}\n\n/*\n** Remove cell the cell with index iCell from node pNode.\n*/\nstatic void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){\n  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];\n  u8 *pSrc = &pDst[pRtree->nBytesPerCell];\n  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;\n  memmove(pDst, pSrc, nByte);\n  writeInt16(&pNode->zData[2], NCELL(pNode)-1);\n  pNode->isDirty = 1;\n}\n\n/*\n** Insert the contents of cell pCell into node pNode. If the insert\n** is successful, return SQLITE_OK.\n**\n** If there is not enough free space in pNode, return SQLITE_FULL.\n*/\nstatic int\nnodeInsertCell(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  RtreeCell *pCell \n){\n  int nCell;                    /* Current number of cells in pNode */\n  int nMaxCell;                 /* Maximum number of cells for pNode */\n\n  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;\n  nCell = NCELL(pNode);\n\n  assert( nCell<=nMaxCell );\n  if( nCell<nMaxCell ){\n    nodeOverwriteCell(pRtree, pNode, pCell, nCell);\n    writeInt16(&pNode->zData[2], nCell+1);\n    pNode->isDirty = 1;\n  }\n\n  return (nCell==nMaxCell);\n}\n\n/*\n** If the node is dirty, write it out to the database.\n*/\nstatic int\nnodeWrite(Rtree *pRtree, RtreeNode *pNode){\n  int rc = SQLITE_OK;\n  if( pNode->isDirty ){\n    sqlite3_stmt *p = pRtree->pWriteNode;\n    if( pNode->iNode ){\n      sqlite3_bind_int64(p, 1, pNode->iNode);\n    }else{\n      sqlite3_bind_null(p, 1);\n    }\n    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);\n    sqlite3_step(p);\n    pNode->isDirty = 0;\n    rc = sqlite3_reset(p);\n    if( pNode->iNode==0 && rc==SQLITE_OK ){\n      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);\n      nodeHashInsert(pRtree, pNode);\n    }\n  }\n  return rc;\n}\n\n/*\n** Release a reference to a node. If the node is dirty and the reference\n** count drops to zero, the node data is written to the database.\n*/\nstatic int\nnodeRelease(Rtree *pRtree, RtreeNode *pNode){\n  int rc = SQLITE_OK;\n  if( pNode ){\n    assert( pNode->nRef>0 );\n    pNode->nRef--;\n    if( pNode->nRef==0 ){\n      if( pNode->iNode==1 ){\n        pRtree->iDepth = -1;\n      }\n      if( pNode->pParent ){\n        rc = nodeRelease(pRtree, pNode->pParent);\n      }\n      if( rc==SQLITE_OK ){\n        rc = nodeWrite(pRtree, pNode);\n      }\n      nodeHashDelete(pRtree, pNode);\n      sqlite3_free(pNode);\n    }\n  }\n  return rc;\n}\n\n/*\n** Return the 64-bit integer value associated with cell iCell of\n** node pNode. If pNode is a leaf node, this is a rowid. If it is\n** an internal node, then the 64-bit integer is a child page number.\n*/\nstatic i64 nodeGetRowid(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  int iCell\n){\n  assert( iCell<NCELL(pNode) );\n  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);\n}\n\n/*\n** Return coordinate iCoord from cell iCell in node pNode.\n*/\nstatic void nodeGetCoord(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  int iCell,\n  int iCoord,\n  RtreeCoord *pCoord           /* Space to write result to */\n){\n  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);\n}\n\n/*\n** Deserialize cell iCell of node pNode. Populate the structure pointed\n** to by pCell with the results.\n*/\nstatic void nodeGetCell(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  int iCell,\n  RtreeCell *pCell\n){\n  int ii;\n  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);\n  for(ii=0; ii<pRtree->nDim*2; ii++){\n    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);\n  }\n}\n\n\n/* Forward declaration for the function that does the work of\n** the virtual table module xCreate() and xConnect() methods.\n*/\nstatic int rtreeInit(\n  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int\n);\n\n/* \n** Rtree virtual table module xCreate method.\n*/\nstatic int rtreeCreate(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);\n}\n\n/* \n** Rtree virtual table module xConnect method.\n*/\nstatic int rtreeConnect(\n  sqlite3 *db,\n  void *pAux,\n  int argc, const char *const*argv,\n  sqlite3_vtab **ppVtab,\n  char **pzErr\n){\n  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);\n}\n\n/*\n** Increment the r-tree reference count.\n*/\nstatic void rtreeReference(Rtree *pRtree){\n  pRtree->nBusy++;\n}\n\n/*\n** Decrement the r-tree reference count. When the reference count reaches\n** zero the structure is deleted.\n*/\nstatic void rtreeRelease(Rtree *pRtree){\n  pRtree->nBusy--;\n  if( pRtree->nBusy==0 ){\n    sqlite3_finalize(pRtree->pReadNode);\n    sqlite3_finalize(pRtree->pWriteNode);\n    sqlite3_finalize(pRtree->pDeleteNode);\n    sqlite3_finalize(pRtree->pReadRowid);\n    sqlite3_finalize(pRtree->pWriteRowid);\n    sqlite3_finalize(pRtree->pDeleteRowid);\n    sqlite3_finalize(pRtree->pReadParent);\n    sqlite3_finalize(pRtree->pWriteParent);\n    sqlite3_finalize(pRtree->pDeleteParent);\n    sqlite3_free(pRtree);\n  }\n}\n\n/* \n** Rtree virtual table module xDisconnect method.\n*/\nstatic int rtreeDisconnect(sqlite3_vtab *pVtab){\n  rtreeRelease((Rtree *)pVtab);\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xDestroy method.\n*/\nstatic int rtreeDestroy(sqlite3_vtab *pVtab){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc;\n  char *zCreate = sqlite3_mprintf(\n    \"DROP TABLE '%q'.'%q_node';\"\n    \"DROP TABLE '%q'.'%q_rowid';\"\n    \"DROP TABLE '%q'.'%q_parent';\",\n    pRtree->zDb, pRtree->zName, \n    pRtree->zDb, pRtree->zName,\n    pRtree->zDb, pRtree->zName\n  );\n  if( !zCreate ){\n    rc = SQLITE_NOMEM;\n  }else{\n    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);\n    sqlite3_free(zCreate);\n  }\n  if( rc==SQLITE_OK ){\n    rtreeRelease(pRtree);\n  }\n\n  return rc;\n}\n\n/* \n** Rtree virtual table module xOpen method.\n*/\nstatic int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){\n  int rc = SQLITE_NOMEM;\n  RtreeCursor *pCsr;\n\n  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));\n  if( pCsr ){\n    memset(pCsr, 0, sizeof(RtreeCursor));\n    pCsr->base.pVtab = pVTab;\n    rc = SQLITE_OK;\n  }\n  *ppCursor = (sqlite3_vtab_cursor *)pCsr;\n\n  return rc;\n}\n\n\n/*\n** Free the RtreeCursor.aConstraint[] array and its contents.\n*/\nstatic void freeCursorConstraints(RtreeCursor *pCsr){\n  if( pCsr->aConstraint ){\n    int i;                        /* Used to iterate through constraint array */\n    for(i=0; i<pCsr->nConstraint; i++){\n      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;\n      if( pGeom ){\n        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);\n        sqlite3_free(pGeom);\n      }\n    }\n    sqlite3_free(pCsr->aConstraint);\n    pCsr->aConstraint = 0;\n  }\n}\n\n/* \n** Rtree virtual table module xClose method.\n*/\nstatic int rtreeClose(sqlite3_vtab_cursor *cur){\n  Rtree *pRtree = (Rtree *)(cur->pVtab);\n  int rc;\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  freeCursorConstraints(pCsr);\n  rc = nodeRelease(pRtree, pCsr->pNode);\n  sqlite3_free(pCsr);\n  return rc;\n}\n\n/*\n** Rtree virtual table module xEof method.\n**\n** Return non-zero if the cursor does not currently point to a valid \n** record (i.e if the scan has finished), or zero otherwise.\n*/\nstatic int rtreeEof(sqlite3_vtab_cursor *cur){\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n  return (pCsr->pNode==0);\n}\n\n/*\n** The r-tree constraint passed as the second argument to this function is\n** guaranteed to be a MATCH constraint.\n*/\nstatic int testRtreeGeom(\n  Rtree *pRtree,                  /* R-Tree object */\n  RtreeConstraint *pConstraint,   /* MATCH constraint to test */\n  RtreeCell *pCell,               /* Cell to test */\n  int *pbRes                      /* OUT: Test result */\n){\n  int i;\n  RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];\n  int nCoord = pRtree->nDim*2;\n\n  assert( pConstraint->op==RTREE_MATCH );\n  assert( pConstraint->pGeom );\n\n  for(i=0; i<nCoord; i++){\n    aCoord[i] = DCOORD(pCell->aCoord[i]);\n  }\n  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);\n}\n\n/* \n** Cursor pCursor currently points to a cell in a non-leaf page.\n** Set *pbEof to true if the sub-tree headed by the cell is filtered\n** (excluded) by the constraints in the pCursor->aConstraint[] \n** array, or false otherwise.\n**\n** Return SQLITE_OK if successful or an SQLite error code if an error\n** occurs within a geometry callback.\n*/\nstatic int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){\n  RtreeCell cell;\n  int ii;\n  int bRes = 0;\n  int rc = SQLITE_OK;\n\n  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);\n  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){\n    RtreeConstraint *p = &pCursor->aConstraint[ii];\n    RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);\n    RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);\n\n    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE \n        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH\n    );\n\n    switch( p->op ){\n      case RTREE_LE: case RTREE_LT: \n        bRes = p->rValue<cell_min; \n        break;\n\n      case RTREE_GE: case RTREE_GT: \n        bRes = p->rValue>cell_max; \n        break;\n\n      case RTREE_EQ:\n        bRes = (p->rValue>cell_max || p->rValue<cell_min);\n        break;\n\n      default: {\n        assert( p->op==RTREE_MATCH );\n        rc = testRtreeGeom(pRtree, p, &cell, &bRes);\n        bRes = !bRes;\n        break;\n      }\n    }\n  }\n\n  *pbEof = bRes;\n  return rc;\n}\n\n/* \n** Test if the cell that cursor pCursor currently points to\n** would be filtered (excluded) by the constraints in the \n** pCursor->aConstraint[] array. If so, set *pbEof to true before\n** returning. If the cell is not filtered (excluded) by the constraints,\n** set pbEof to zero.\n**\n** Return SQLITE_OK if successful or an SQLite error code if an error\n** occurs within a geometry callback.\n**\n** This function assumes that the cell is part of a leaf node.\n*/\nstatic int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){\n  RtreeCell cell;\n  int ii;\n  *pbEof = 0;\n\n  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);\n  for(ii=0; ii<pCursor->nConstraint; ii++){\n    RtreeConstraint *p = &pCursor->aConstraint[ii];\n    RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);\n    int res;\n    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE \n        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH\n    );\n    switch( p->op ){\n      case RTREE_LE: res = (coord<=p->rValue); break;\n      case RTREE_LT: res = (coord<p->rValue);  break;\n      case RTREE_GE: res = (coord>=p->rValue); break;\n      case RTREE_GT: res = (coord>p->rValue);  break;\n      case RTREE_EQ: res = (coord==p->rValue); break;\n      default: {\n        int rc;\n        assert( p->op==RTREE_MATCH );\n        rc = testRtreeGeom(pRtree, p, &cell, &res);\n        if( rc!=SQLITE_OK ){\n          return rc;\n        }\n        break;\n      }\n    }\n\n    if( !res ){\n      *pbEof = 1;\n      return SQLITE_OK;\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/*\n** Cursor pCursor currently points at a node that heads a sub-tree of\n** height iHeight (if iHeight==0, then the node is a leaf). Descend\n** to point to the left-most cell of the sub-tree that matches the \n** configured constraints.\n*/\nstatic int descendToCell(\n  Rtree *pRtree, \n  RtreeCursor *pCursor, \n  int iHeight,\n  int *pEof                 /* OUT: Set to true if cannot descend */\n){\n  int isEof;\n  int rc;\n  int ii;\n  RtreeNode *pChild;\n  sqlite3_int64 iRowid;\n\n  RtreeNode *pSavedNode = pCursor->pNode;\n  int iSavedCell = pCursor->iCell;\n\n  assert( iHeight>=0 );\n\n  if( iHeight==0 ){\n    rc = testRtreeEntry(pRtree, pCursor, &isEof);\n  }else{\n    rc = testRtreeCell(pRtree, pCursor, &isEof);\n  }\n  if( rc!=SQLITE_OK || isEof || iHeight==0 ){\n    goto descend_to_cell_out;\n  }\n\n  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);\n  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);\n  if( rc!=SQLITE_OK ){\n    goto descend_to_cell_out;\n  }\n\n  nodeRelease(pRtree, pCursor->pNode);\n  pCursor->pNode = pChild;\n  isEof = 1;\n  for(ii=0; isEof && ii<NCELL(pChild); ii++){\n    pCursor->iCell = ii;\n    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);\n    if( rc!=SQLITE_OK ){\n      goto descend_to_cell_out;\n    }\n  }\n\n  if( isEof ){\n    assert( pCursor->pNode==pChild );\n    nodeReference(pSavedNode);\n    nodeRelease(pRtree, pChild);\n    pCursor->pNode = pSavedNode;\n    pCursor->iCell = iSavedCell;\n  }\n\ndescend_to_cell_out:\n  *pEof = isEof;\n  return rc;\n}\n\n/*\n** One of the cells in node pNode is guaranteed to have a 64-bit \n** integer value equal to iRowid. Return the index of this cell.\n*/\nstatic int nodeRowidIndex(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  i64 iRowid,\n  int *piIndex\n){\n  int ii;\n  int nCell = NCELL(pNode);\n  for(ii=0; ii<nCell; ii++){\n    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){\n      *piIndex = ii;\n      return SQLITE_OK;\n    }\n  }\n  return SQLITE_CORRUPT_VTAB;\n}\n\n/*\n** Return the index of the cell containing a pointer to node pNode\n** in its parent. If pNode is the root node, return -1.\n*/\nstatic int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){\n  RtreeNode *pParent = pNode->pParent;\n  if( pParent ){\n    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);\n  }\n  *piIndex = -1;\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xNext method.\n*/\nstatic int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){\n  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n  int rc = SQLITE_OK;\n\n  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is\n  ** already at EOF. It is against the rules to call the xNext() method of\n  ** a cursor that has already reached EOF.\n  */\n  assert( pCsr->pNode );\n\n  if( pCsr->iStrategy==1 ){\n    /* This \"scan\" is a direct lookup by rowid. There is no next entry. */\n    nodeRelease(pRtree, pCsr->pNode);\n    pCsr->pNode = 0;\n  }else{\n    /* Move to the next entry that matches the configured constraints. */\n    int iHeight = 0;\n    while( pCsr->pNode ){\n      RtreeNode *pNode = pCsr->pNode;\n      int nCell = NCELL(pNode);\n      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){\n        int isEof;\n        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);\n        if( rc!=SQLITE_OK || !isEof ){\n          return rc;\n        }\n      }\n      pCsr->pNode = pNode->pParent;\n      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);\n      if( rc!=SQLITE_OK ){\n        return rc;\n      }\n      nodeReference(pCsr->pNode);\n      nodeRelease(pRtree, pNode);\n      iHeight++;\n    }\n  }\n\n  return rc;\n}\n\n/* \n** Rtree virtual table module xRowid method.\n*/\nstatic int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){\n  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n\n  assert(pCsr->pNode);\n  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);\n\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xColumn method.\n*/\nstatic int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){\n  Rtree *pRtree = (Rtree *)cur->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)cur;\n\n  if( i==0 ){\n    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);\n    sqlite3_result_int64(ctx, iRowid);\n  }else{\n    RtreeCoord c;\n    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);\n#ifndef SQLITE_RTREE_INT_ONLY\n    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n      sqlite3_result_double(ctx, c.f);\n    }else\n#endif\n    {\n      assert( pRtree->eCoordType==RTREE_COORD_INT32 );\n      sqlite3_result_int(ctx, c.i);\n    }\n  }\n\n  return SQLITE_OK;\n}\n\n/* \n** Use nodeAcquire() to obtain the leaf node containing the record with \n** rowid iRowid. If successful, set *ppLeaf to point to the node and\n** return SQLITE_OK. If there is no such record in the table, set\n** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf\n** to zero and return an SQLite error code.\n*/\nstatic int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){\n  int rc;\n  *ppLeaf = 0;\n  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);\n  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){\n    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);\n    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);\n    sqlite3_reset(pRtree->pReadRowid);\n  }else{\n    rc = sqlite3_reset(pRtree->pReadRowid);\n  }\n  return rc;\n}\n\n/*\n** This function is called to configure the RtreeConstraint object passed\n** as the second argument for a MATCH constraint. The value passed as the\n** first argument to this function is the right-hand operand to the MATCH\n** operator.\n*/\nstatic int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){\n  RtreeMatchArg *p;\n  sqlite3_rtree_geometry *pGeom;\n  int nBlob;\n\n  /* Check that value is actually a blob. */\n  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;\n\n  /* Check that the blob is roughly the right size. */\n  nBlob = sqlite3_value_bytes(pValue);\n  if( nBlob<(int)sizeof(RtreeMatchArg) \n   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0\n  ){\n    return SQLITE_ERROR;\n  }\n\n  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(\n      sizeof(sqlite3_rtree_geometry) + nBlob\n  );\n  if( !pGeom ) return SQLITE_NOMEM;\n  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));\n  p = (RtreeMatchArg *)&pGeom[1];\n\n  memcpy(p, sqlite3_value_blob(pValue), nBlob);\n  if( p->magic!=RTREE_GEOMETRY_MAGIC \n   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))\n  ){\n    sqlite3_free(pGeom);\n    return SQLITE_ERROR;\n  }\n\n  pGeom->pContext = p->pContext;\n  pGeom->nParam = p->nParam;\n  pGeom->aParam = p->aParam;\n\n  pCons->xGeom = p->xGeom;\n  pCons->pGeom = pGeom;\n  return SQLITE_OK;\n}\n\n/* \n** Rtree virtual table module xFilter method.\n*/\nstatic int rtreeFilter(\n  sqlite3_vtab_cursor *pVtabCursor, \n  int idxNum, const char *idxStr,\n  int argc, sqlite3_value **argv\n){\n  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;\n  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;\n\n  RtreeNode *pRoot = 0;\n  int ii;\n  int rc = SQLITE_OK;\n\n  rtreeReference(pRtree);\n\n  freeCursorConstraints(pCsr);\n  pCsr->iStrategy = idxNum;\n\n  if( idxNum==1 ){\n    /* Special case - lookup by rowid. */\n    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */\n    i64 iRowid = sqlite3_value_int64(argv[0]);\n    rc = findLeafNode(pRtree, iRowid, &pLeaf);\n    pCsr->pNode = pLeaf; \n    if( pLeaf ){\n      assert( rc==SQLITE_OK );\n      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);\n    }\n  }else{\n    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array \n    ** with the configured constraints. \n    */\n    if( argc>0 ){\n      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);\n      pCsr->nConstraint = argc;\n      if( !pCsr->aConstraint ){\n        rc = SQLITE_NOMEM;\n      }else{\n        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);\n        assert( (idxStr==0 && argc==0)\n                || (idxStr && (int)strlen(idxStr)==argc*2) );\n        for(ii=0; ii<argc; ii++){\n          RtreeConstraint *p = &pCsr->aConstraint[ii];\n          p->op = idxStr[ii*2];\n          p->iCoord = idxStr[ii*2+1]-'a';\n          if( p->op==RTREE_MATCH ){\n            /* A MATCH operator. The right-hand-side must be a blob that\n            ** can be cast into an RtreeMatchArg object. One created using\n            ** an sqlite3_rtree_geometry_callback() SQL user function.\n            */\n            rc = deserializeGeometry(argv[ii], p);\n            if( rc!=SQLITE_OK ){\n              break;\n            }\n          }else{\n#ifdef SQLITE_RTREE_INT_ONLY\n            p->rValue = sqlite3_value_int64(argv[ii]);\n#else\n            p->rValue = sqlite3_value_double(argv[ii]);\n#endif\n          }\n        }\n      }\n    }\n  \n    if( rc==SQLITE_OK ){\n      pCsr->pNode = 0;\n      rc = nodeAcquire(pRtree, 1, 0, &pRoot);\n    }\n    if( rc==SQLITE_OK ){\n      int isEof = 1;\n      int nCell = NCELL(pRoot);\n      pCsr->pNode = pRoot;\n      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){\n        assert( pCsr->pNode==pRoot );\n        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);\n        if( !isEof ){\n          break;\n        }\n      }\n      if( rc==SQLITE_OK && isEof ){\n        assert( pCsr->pNode==pRoot );\n        nodeRelease(pRtree, pRoot);\n        pCsr->pNode = 0;\n      }\n      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );\n    }\n  }\n\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** Rtree virtual table module xBestIndex method. There are three\n** table scan strategies to choose from (in order from most to \n** least desirable):\n**\n**   idxNum     idxStr        Strategy\n**   ------------------------------------------------\n**     1        Unused        Direct lookup by rowid.\n**     2        See below     R-tree query or full-table scan.\n**   ------------------------------------------------\n**\n** If strategy 1 is used, then idxStr is not meaningful. If strategy\n** 2 is used, idxStr is formatted to contain 2 bytes for each \n** constraint used. The first two bytes of idxStr correspond to \n** the constraint in sqlite3_index_info.aConstraintUsage[] with\n** (argvIndex==1) etc.\n**\n** The first of each pair of bytes in idxStr identifies the constraint\n** operator as follows:\n**\n**   Operator    Byte Value\n**   ----------------------\n**      =        0x41 ('A')\n**     <=        0x42 ('B')\n**      <        0x43 ('C')\n**     >=        0x44 ('D')\n**      >        0x45 ('E')\n**   MATCH       0x46 ('F')\n**   ----------------------\n**\n** The second of each pair of bytes identifies the coordinate column\n** to which the constraint applies. The leftmost coordinate column\n** is 'a', the second from the left 'b' etc.\n*/\nstatic int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){\n  int rc = SQLITE_OK;\n  int ii;\n\n  int iIdx = 0;\n  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];\n  memset(zIdxStr, 0, sizeof(zIdxStr));\n  UNUSED_PARAMETER(tab);\n\n  assert( pIdxInfo->idxStr==0 );\n  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){\n    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];\n\n    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){\n      /* We have an equality constraint on the rowid. Use strategy 1. */\n      int jj;\n      for(jj=0; jj<ii; jj++){\n        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;\n        pIdxInfo->aConstraintUsage[jj].omit = 0;\n      }\n      pIdxInfo->idxNum = 1;\n      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;\n      pIdxInfo->aConstraintUsage[jj].omit = 1;\n\n      /* This strategy involves a two rowid lookups on an B-Tree structures\n      ** and then a linear search of an R-Tree node. This should be \n      ** considered almost as quick as a direct rowid lookup (for which \n      ** sqlite uses an internal cost of 0.0).\n      */ \n      pIdxInfo->estimatedCost = 10.0;\n      return SQLITE_OK;\n    }\n\n    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){\n      u8 op;\n      switch( p->op ){\n        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;\n        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;\n        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;\n        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;\n        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;\n        default:\n          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );\n          op = RTREE_MATCH; \n          break;\n      }\n      zIdxStr[iIdx++] = op;\n      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';\n      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);\n      pIdxInfo->aConstraintUsage[ii].omit = 1;\n    }\n  }\n\n  pIdxInfo->idxNum = 2;\n  pIdxInfo->needToFreeIdxStr = 1;\n  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf(\"%s\", zIdxStr)) ){\n    return SQLITE_NOMEM;\n  }\n  assert( iIdx>=0 );\n  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));\n  return rc;\n}\n\n/*\n** Return the N-dimensional volumn of the cell stored in *p.\n*/\nstatic RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){\n  RtreeDValue area = (RtreeDValue)1;\n  int ii;\n  for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n    area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));\n  }\n  return area;\n}\n\n/*\n** Return the margin length of cell p. The margin length is the sum\n** of the objects size in each dimension.\n*/\nstatic RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){\n  RtreeDValue margin = (RtreeDValue)0;\n  int ii;\n  for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n    margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));\n  }\n  return margin;\n}\n\n/*\n** Store the union of cells p1 and p2 in p1.\n*/\nstatic void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){\n  int ii;\n  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n    for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);\n      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);\n    }\n  }else{\n    for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);\n      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);\n    }\n  }\n}\n\n/*\n** Return true if the area covered by p2 is a subset of the area covered\n** by p1. False otherwise.\n*/\nstatic int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){\n  int ii;\n  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);\n  for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n    RtreeCoord *a1 = &p1->aCoord[ii];\n    RtreeCoord *a2 = &p2->aCoord[ii];\n    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) \n     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) \n    ){\n      return 0;\n    }\n  }\n  return 1;\n}\n\n/*\n** Return the amount cell p would grow by if it were unioned with pCell.\n*/\nstatic RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){\n  RtreeDValue area;\n  RtreeCell cell;\n  memcpy(&cell, p, sizeof(RtreeCell));\n  area = cellArea(pRtree, &cell);\n  cellUnion(pRtree, &cell, pCell);\n  return (cellArea(pRtree, &cell)-area);\n}\n\n#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT\nstatic RtreeDValue cellOverlap(\n  Rtree *pRtree, \n  RtreeCell *p, \n  RtreeCell *aCell, \n  int nCell, \n  int iExclude\n){\n  int ii;\n  RtreeDValue overlap = 0.0;\n  for(ii=0; ii<nCell; ii++){\n#if VARIANT_RSTARTREE_CHOOSESUBTREE\n    if( ii!=iExclude )\n#else\n    assert( iExclude==-1 );\n    UNUSED_PARAMETER(iExclude);\n#endif\n    {\n      int jj;\n      RtreeDValue o = (RtreeDValue)1;\n      for(jj=0; jj<(pRtree->nDim*2); jj+=2){\n        RtreeDValue x1, x2;\n\n        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));\n        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));\n\n        if( x2<x1 ){\n          o = 0.0;\n          break;\n        }else{\n          o = o * (x2-x1);\n        }\n      }\n      overlap += o;\n    }\n  }\n  return overlap;\n}\n#endif\n\n#if VARIANT_RSTARTREE_CHOOSESUBTREE\nstatic RtreeDValue cellOverlapEnlargement(\n  Rtree *pRtree, \n  RtreeCell *p, \n  RtreeCell *pInsert, \n  RtreeCell *aCell, \n  int nCell, \n  int iExclude\n){\n  RtreeDValue before, after;\n  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);\n  cellUnion(pRtree, p, pInsert);\n  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);\n  return (after-before);\n}\n#endif\n\n\n/*\n** This function implements the ChooseLeaf algorithm from Gutman[84].\n** ChooseSubTree in r*tree terminology.\n*/\nstatic int ChooseLeaf(\n  Rtree *pRtree,               /* Rtree table */\n  RtreeCell *pCell,            /* Cell to insert into rtree */\n  int iHeight,                 /* Height of sub-tree rooted at pCell */\n  RtreeNode **ppLeaf           /* OUT: Selected leaf page */\n){\n  int rc;\n  int ii;\n  RtreeNode *pNode;\n  rc = nodeAcquire(pRtree, 1, 0, &pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){\n    int iCell;\n    sqlite3_int64 iBest = 0;\n\n    RtreeDValue fMinGrowth = 0.0;\n    RtreeDValue fMinArea = 0.0;\n#if VARIANT_RSTARTREE_CHOOSESUBTREE\n    RtreeDValue fMinOverlap = 0.0;\n    RtreeDValue overlap;\n#endif\n\n    int nCell = NCELL(pNode);\n    RtreeCell cell;\n    RtreeNode *pChild;\n\n    RtreeCell *aCell = 0;\n\n#if VARIANT_RSTARTREE_CHOOSESUBTREE\n    if( ii==(pRtree->iDepth-1) ){\n      int jj;\n      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);\n      if( !aCell ){\n        rc = SQLITE_NOMEM;\n        nodeRelease(pRtree, pNode);\n        pNode = 0;\n        continue;\n      }\n      for(jj=0; jj<nCell; jj++){\n        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);\n      }\n    }\n#endif\n\n    /* Select the child node which will be enlarged the least if pCell\n    ** is inserted into it. Resolve ties by choosing the entry with\n    ** the smallest area.\n    */\n    for(iCell=0; iCell<nCell; iCell++){\n      int bBest = 0;\n      RtreeDValue growth;\n      RtreeDValue area;\n      nodeGetCell(pRtree, pNode, iCell, &cell);\n      growth = cellGrowth(pRtree, &cell, pCell);\n      area = cellArea(pRtree, &cell);\n\n#if VARIANT_RSTARTREE_CHOOSESUBTREE\n      if( ii==(pRtree->iDepth-1) ){\n        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);\n      }else{\n        overlap = 0.0;\n      }\n      if( (iCell==0) \n       || (overlap<fMinOverlap) \n       || (overlap==fMinOverlap && growth<fMinGrowth)\n       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)\n      ){\n        bBest = 1;\n        fMinOverlap = overlap;\n      }\n#else\n      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){\n        bBest = 1;\n      }\n#endif\n      if( bBest ){\n        fMinGrowth = growth;\n        fMinArea = area;\n        iBest = cell.iRowid;\n      }\n    }\n\n    sqlite3_free(aCell);\n    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);\n    nodeRelease(pRtree, pNode);\n    pNode = pChild;\n  }\n\n  *ppLeaf = pNode;\n  return rc;\n}\n\n/*\n** A cell with the same content as pCell has just been inserted into\n** the node pNode. This function updates the bounding box cells in\n** all ancestor elements.\n*/\nstatic int AdjustTree(\n  Rtree *pRtree,                    /* Rtree table */\n  RtreeNode *pNode,                 /* Adjust ancestry of this node. */\n  RtreeCell *pCell                  /* This cell was just inserted */\n){\n  RtreeNode *p = pNode;\n  while( p->pParent ){\n    RtreeNode *pParent = p->pParent;\n    RtreeCell cell;\n    int iCell;\n\n    if( nodeParentIndex(pRtree, p, &iCell) ){\n      return SQLITE_CORRUPT_VTAB;\n    }\n\n    nodeGetCell(pRtree, pParent, iCell, &cell);\n    if( !cellContains(pRtree, &cell, pCell) ){\n      cellUnion(pRtree, &cell, pCell);\n      nodeOverwriteCell(pRtree, pParent, &cell, iCell);\n    }\n \n    p = pParent;\n  }\n  return SQLITE_OK;\n}\n\n/*\n** Write mapping (iRowid->iNode) to the <rtree>_rowid table.\n*/\nstatic int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){\n  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);\n  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);\n  sqlite3_step(pRtree->pWriteRowid);\n  return sqlite3_reset(pRtree->pWriteRowid);\n}\n\n/*\n** Write mapping (iNode->iPar) to the <rtree>_parent table.\n*/\nstatic int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){\n  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);\n  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);\n  sqlite3_step(pRtree->pWriteParent);\n  return sqlite3_reset(pRtree->pWriteParent);\n}\n\nstatic int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);\n\n#if VARIANT_GUTTMAN_LINEAR_SPLIT\n/*\n** Implementation of the linear variant of the PickNext() function from\n** Guttman[84].\n*/\nstatic RtreeCell *LinearPickNext(\n  Rtree *pRtree,\n  RtreeCell *aCell, \n  int nCell, \n  RtreeCell *pLeftBox, \n  RtreeCell *pRightBox,\n  int *aiUsed\n){\n  int ii;\n  for(ii=0; aiUsed[ii]; ii++);\n  aiUsed[ii] = 1;\n  return &aCell[ii];\n}\n\n/*\n** Implementation of the linear variant of the PickSeeds() function from\n** Guttman[84].\n*/\nstatic void LinearPickSeeds(\n  Rtree *pRtree,\n  RtreeCell *aCell, \n  int nCell, \n  int *piLeftSeed, \n  int *piRightSeed\n){\n  int i;\n  int iLeftSeed = 0;\n  int iRightSeed = 1;\n  RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;\n\n  /* Pick two \"seed\" cells from the array of cells. The algorithm used\n  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The \n  ** indices of the two seed cells in the array are stored in local\n  ** variables iLeftSeek and iRightSeed.\n  */\n  for(i=0; i<pRtree->nDim; i++){\n    RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);\n    RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);\n    RtreeDValue x3 = x1;\n    RtreeDValue x4 = x2;\n    int jj;\n\n    int iCellLeft = 0;\n    int iCellRight = 0;\n\n    for(jj=1; jj<nCell; jj++){\n      RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);\n      RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);\n\n      if( left<x1 ) x1 = left;\n      if( right>x4 ) x4 = right;\n      if( left>x3 ){\n        x3 = left;\n        iCellRight = jj;\n      }\n      if( right<x2 ){\n        x2 = right;\n        iCellLeft = jj;\n      }\n    }\n\n    if( x4!=x1 ){\n      RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);\n      if( normalwidth>maxNormalInnerWidth ){\n        iLeftSeed = iCellLeft;\n        iRightSeed = iCellRight;\n      }\n    }\n  }\n\n  *piLeftSeed = iLeftSeed;\n  *piRightSeed = iRightSeed;\n}\n#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */\n\n#if VARIANT_GUTTMAN_QUADRATIC_SPLIT\n/*\n** Implementation of the quadratic variant of the PickNext() function from\n** Guttman[84].\n*/\nstatic RtreeCell *QuadraticPickNext(\n  Rtree *pRtree,\n  RtreeCell *aCell, \n  int nCell, \n  RtreeCell *pLeftBox, \n  RtreeCell *pRightBox,\n  int *aiUsed\n){\n  #define FABS(a) ((a)<0.0?-1.0*(a):(a))\n\n  int iSelect = -1;\n  RtreeDValue fDiff;\n  int ii;\n  for(ii=0; ii<nCell; ii++){\n    if( aiUsed[ii]==0 ){\n      RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);\n      RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);\n      RtreeDValue diff = FABS(right-left);\n      if( iSelect<0 || diff>fDiff ){\n        fDiff = diff;\n        iSelect = ii;\n      }\n    }\n  }\n  aiUsed[iSelect] = 1;\n  return &aCell[iSelect];\n}\n\n/*\n** Implementation of the quadratic variant of the PickSeeds() function from\n** Guttman[84].\n*/\nstatic void QuadraticPickSeeds(\n  Rtree *pRtree,\n  RtreeCell *aCell, \n  int nCell, \n  int *piLeftSeed, \n  int *piRightSeed\n){\n  int ii;\n  int jj;\n\n  int iLeftSeed = 0;\n  int iRightSeed = 1;\n  RtreeDValue fWaste = 0.0;\n\n  for(ii=0; ii<nCell; ii++){\n    for(jj=ii+1; jj<nCell; jj++){\n      RtreeDValue right = cellArea(pRtree, &aCell[jj]);\n      RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);\n      RtreeDValue waste = growth - right;\n\n      if( waste>fWaste ){\n        iLeftSeed = ii;\n        iRightSeed = jj;\n        fWaste = waste;\n      }\n    }\n  }\n\n  *piLeftSeed = iLeftSeed;\n  *piRightSeed = iRightSeed;\n}\n#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */\n\n/*\n** Arguments aIdx, aDistance and aSpare all point to arrays of size\n** nIdx. The aIdx array contains the set of integers from 0 to \n** (nIdx-1) in no particular order. This function sorts the values\n** in aIdx according to the indexed values in aDistance. For\n** example, assuming the inputs:\n**\n**   aIdx      = { 0,   1,   2,   3 }\n**   aDistance = { 5.0, 2.0, 7.0, 6.0 }\n**\n** this function sets the aIdx array to contain:\n**\n**   aIdx      = { 0,   1,   2,   3 }\n**\n** The aSpare array is used as temporary working space by the\n** sorting algorithm.\n*/\nstatic void SortByDistance(\n  int *aIdx, \n  int nIdx, \n  RtreeDValue *aDistance, \n  int *aSpare\n){\n  if( nIdx>1 ){\n    int iLeft = 0;\n    int iRight = 0;\n\n    int nLeft = nIdx/2;\n    int nRight = nIdx-nLeft;\n    int *aLeft = aIdx;\n    int *aRight = &aIdx[nLeft];\n\n    SortByDistance(aLeft, nLeft, aDistance, aSpare);\n    SortByDistance(aRight, nRight, aDistance, aSpare);\n\n    memcpy(aSpare, aLeft, sizeof(int)*nLeft);\n    aLeft = aSpare;\n\n    while( iLeft<nLeft || iRight<nRight ){\n      if( iLeft==nLeft ){\n        aIdx[iLeft+iRight] = aRight[iRight];\n        iRight++;\n      }else if( iRight==nRight ){\n        aIdx[iLeft+iRight] = aLeft[iLeft];\n        iLeft++;\n      }else{\n        RtreeDValue fLeft = aDistance[aLeft[iLeft]];\n        RtreeDValue fRight = aDistance[aRight[iRight]];\n        if( fLeft<fRight ){\n          aIdx[iLeft+iRight] = aLeft[iLeft];\n          iLeft++;\n        }else{\n          aIdx[iLeft+iRight] = aRight[iRight];\n          iRight++;\n        }\n      }\n    }\n\n#if 0\n    /* Check that the sort worked */\n    {\n      int jj;\n      for(jj=1; jj<nIdx; jj++){\n        RtreeDValue left = aDistance[aIdx[jj-1]];\n        RtreeDValue right = aDistance[aIdx[jj]];\n        assert( left<=right );\n      }\n    }\n#endif\n  }\n}\n\n/*\n** Arguments aIdx, aCell and aSpare all point to arrays of size\n** nIdx. The aIdx array contains the set of integers from 0 to \n** (nIdx-1) in no particular order. This function sorts the values\n** in aIdx according to dimension iDim of the cells in aCell. The\n** minimum value of dimension iDim is considered first, the\n** maximum used to break ties.\n**\n** The aSpare array is used as temporary working space by the\n** sorting algorithm.\n*/\nstatic void SortByDimension(\n  Rtree *pRtree,\n  int *aIdx, \n  int nIdx, \n  int iDim, \n  RtreeCell *aCell, \n  int *aSpare\n){\n  if( nIdx>1 ){\n\n    int iLeft = 0;\n    int iRight = 0;\n\n    int nLeft = nIdx/2;\n    int nRight = nIdx-nLeft;\n    int *aLeft = aIdx;\n    int *aRight = &aIdx[nLeft];\n\n    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);\n    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);\n\n    memcpy(aSpare, aLeft, sizeof(int)*nLeft);\n    aLeft = aSpare;\n    while( iLeft<nLeft || iRight<nRight ){\n      RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);\n      RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);\n      RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);\n      RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);\n      if( (iLeft!=nLeft) && ((iRight==nRight)\n       || (xleft1<xright1)\n       || (xleft1==xright1 && xleft2<xright2)\n      )){\n        aIdx[iLeft+iRight] = aLeft[iLeft];\n        iLeft++;\n      }else{\n        aIdx[iLeft+iRight] = aRight[iRight];\n        iRight++;\n      }\n    }\n\n#if 0\n    /* Check that the sort worked */\n    {\n      int jj;\n      for(jj=1; jj<nIdx; jj++){\n        RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];\n        RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];\n        RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];\n        RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];\n        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );\n      }\n    }\n#endif\n  }\n}\n\n#if VARIANT_RSTARTREE_SPLIT\n/*\n** Implementation of the R*-tree variant of SplitNode from Beckman[1990].\n*/\nstatic int splitNodeStartree(\n  Rtree *pRtree,\n  RtreeCell *aCell,\n  int nCell,\n  RtreeNode *pLeft,\n  RtreeNode *pRight,\n  RtreeCell *pBboxLeft,\n  RtreeCell *pBboxRight\n){\n  int **aaSorted;\n  int *aSpare;\n  int ii;\n\n  int iBestDim = 0;\n  int iBestSplit = 0;\n  RtreeDValue fBestMargin = 0.0;\n\n  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));\n\n  aaSorted = (int **)sqlite3_malloc(nByte);\n  if( !aaSorted ){\n    return SQLITE_NOMEM;\n  }\n\n  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];\n  memset(aaSorted, 0, nByte);\n  for(ii=0; ii<pRtree->nDim; ii++){\n    int jj;\n    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];\n    for(jj=0; jj<nCell; jj++){\n      aaSorted[ii][jj] = jj;\n    }\n    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);\n  }\n\n  for(ii=0; ii<pRtree->nDim; ii++){\n    RtreeDValue margin = 0.0;\n    RtreeDValue fBestOverlap = 0.0;\n    RtreeDValue fBestArea = 0.0;\n    int iBestLeft = 0;\n    int nLeft;\n\n    for(\n      nLeft=RTREE_MINCELLS(pRtree); \n      nLeft<=(nCell-RTREE_MINCELLS(pRtree)); \n      nLeft++\n    ){\n      RtreeCell left;\n      RtreeCell right;\n      int kk;\n      RtreeDValue overlap;\n      RtreeDValue area;\n\n      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));\n      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));\n      for(kk=1; kk<(nCell-1); kk++){\n        if( kk<nLeft ){\n          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);\n        }else{\n          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);\n        }\n      }\n      margin += cellMargin(pRtree, &left);\n      margin += cellMargin(pRtree, &right);\n      overlap = cellOverlap(pRtree, &left, &right, 1, -1);\n      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);\n      if( (nLeft==RTREE_MINCELLS(pRtree))\n       || (overlap<fBestOverlap)\n       || (overlap==fBestOverlap && area<fBestArea)\n      ){\n        iBestLeft = nLeft;\n        fBestOverlap = overlap;\n        fBestArea = area;\n      }\n    }\n\n    if( ii==0 || margin<fBestMargin ){\n      iBestDim = ii;\n      fBestMargin = margin;\n      iBestSplit = iBestLeft;\n    }\n  }\n\n  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));\n  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));\n  for(ii=0; ii<nCell; ii++){\n    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;\n    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;\n    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];\n    nodeInsertCell(pRtree, pTarget, pCell);\n    cellUnion(pRtree, pBbox, pCell);\n  }\n\n  sqlite3_free(aaSorted);\n  return SQLITE_OK;\n}\n#endif\n\n#if VARIANT_GUTTMAN_SPLIT\n/*\n** Implementation of the regular R-tree SplitNode from Guttman[1984].\n*/\nstatic int splitNodeGuttman(\n  Rtree *pRtree,\n  RtreeCell *aCell,\n  int nCell,\n  RtreeNode *pLeft,\n  RtreeNode *pRight,\n  RtreeCell *pBboxLeft,\n  RtreeCell *pBboxRight\n){\n  int iLeftSeed = 0;\n  int iRightSeed = 1;\n  int *aiUsed;\n  int i;\n\n  aiUsed = sqlite3_malloc(sizeof(int)*nCell);\n  if( !aiUsed ){\n    return SQLITE_NOMEM;\n  }\n  memset(aiUsed, 0, sizeof(int)*nCell);\n\n  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);\n\n  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));\n  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));\n  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);\n  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);\n  aiUsed[iLeftSeed] = 1;\n  aiUsed[iRightSeed] = 1;\n\n  for(i=nCell-2; i>0; i--){\n    RtreeCell *pNext;\n    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);\n    RtreeDValue diff =  \n      cellGrowth(pRtree, pBboxLeft, pNext) - \n      cellGrowth(pRtree, pBboxRight, pNext)\n    ;\n    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)\n     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))\n    ){\n      nodeInsertCell(pRtree, pRight, pNext);\n      cellUnion(pRtree, pBboxRight, pNext);\n    }else{\n      nodeInsertCell(pRtree, pLeft, pNext);\n      cellUnion(pRtree, pBboxLeft, pNext);\n    }\n  }\n\n  sqlite3_free(aiUsed);\n  return SQLITE_OK;\n}\n#endif\n\nstatic int updateMapping(\n  Rtree *pRtree, \n  i64 iRowid, \n  RtreeNode *pNode, \n  int iHeight\n){\n  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);\n  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);\n  if( iHeight>0 ){\n    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);\n    if( pChild ){\n      nodeRelease(pRtree, pChild->pParent);\n      nodeReference(pNode);\n      pChild->pParent = pNode;\n    }\n  }\n  return xSetMapping(pRtree, iRowid, pNode->iNode);\n}\n\nstatic int SplitNode(\n  Rtree *pRtree,\n  RtreeNode *pNode,\n  RtreeCell *pCell,\n  int iHeight\n){\n  int i;\n  int newCellIsRight = 0;\n\n  int rc = SQLITE_OK;\n  int nCell = NCELL(pNode);\n  RtreeCell *aCell;\n  int *aiUsed;\n\n  RtreeNode *pLeft = 0;\n  RtreeNode *pRight = 0;\n\n  RtreeCell leftbbox;\n  RtreeCell rightbbox;\n\n  /* Allocate an array and populate it with a copy of pCell and \n  ** all cells from node pLeft. Then zero the original node.\n  */\n  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));\n  if( !aCell ){\n    rc = SQLITE_NOMEM;\n    goto splitnode_out;\n  }\n  aiUsed = (int *)&aCell[nCell+1];\n  memset(aiUsed, 0, sizeof(int)*(nCell+1));\n  for(i=0; i<nCell; i++){\n    nodeGetCell(pRtree, pNode, i, &aCell[i]);\n  }\n  nodeZero(pRtree, pNode);\n  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));\n  nCell++;\n\n  if( pNode->iNode==1 ){\n    pRight = nodeNew(pRtree, pNode);\n    pLeft = nodeNew(pRtree, pNode);\n    pRtree->iDepth++;\n    pNode->isDirty = 1;\n    writeInt16(pNode->zData, pRtree->iDepth);\n  }else{\n    pLeft = pNode;\n    pRight = nodeNew(pRtree, pLeft->pParent);\n    nodeReference(pLeft);\n  }\n\n  if( !pLeft || !pRight ){\n    rc = SQLITE_NOMEM;\n    goto splitnode_out;\n  }\n\n  memset(pLeft->zData, 0, pRtree->iNodeSize);\n  memset(pRight->zData, 0, pRtree->iNodeSize);\n\n  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);\n  if( rc!=SQLITE_OK ){\n    goto splitnode_out;\n  }\n\n  /* Ensure both child nodes have node numbers assigned to them by calling\n  ** nodeWrite(). Node pRight always needs a node number, as it was created\n  ** by nodeNew() above. But node pLeft sometimes already has a node number.\n  ** In this case avoid the all to nodeWrite().\n  */\n  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))\n   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))\n  ){\n    goto splitnode_out;\n  }\n\n  rightbbox.iRowid = pRight->iNode;\n  leftbbox.iRowid = pLeft->iNode;\n\n  if( pNode->iNode==1 ){\n    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }else{\n    RtreeNode *pParent = pLeft->pParent;\n    int iCell;\n    rc = nodeParentIndex(pRtree, pLeft, &iCell);\n    if( rc==SQLITE_OK ){\n      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);\n      rc = AdjustTree(pRtree, pParent, &leftbbox);\n    }\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }\n  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){\n    goto splitnode_out;\n  }\n\n  for(i=0; i<NCELL(pRight); i++){\n    i64 iRowid = nodeGetRowid(pRtree, pRight, i);\n    rc = updateMapping(pRtree, iRowid, pRight, iHeight);\n    if( iRowid==pCell->iRowid ){\n      newCellIsRight = 1;\n    }\n    if( rc!=SQLITE_OK ){\n      goto splitnode_out;\n    }\n  }\n  if( pNode->iNode==1 ){\n    for(i=0; i<NCELL(pLeft); i++){\n      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);\n      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);\n      if( rc!=SQLITE_OK ){\n        goto splitnode_out;\n      }\n    }\n  }else if( newCellIsRight==0 ){\n    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);\n  }\n\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pRight);\n    pRight = 0;\n  }\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pLeft);\n    pLeft = 0;\n  }\n\nsplitnode_out:\n  nodeRelease(pRtree, pRight);\n  nodeRelease(pRtree, pLeft);\n  sqlite3_free(aCell);\n  return rc;\n}\n\n/*\n** If node pLeaf is not the root of the r-tree and its pParent pointer is \n** still NULL, load all ancestor nodes of pLeaf into memory and populate\n** the pLeaf->pParent chain all the way up to the root node.\n**\n** This operation is required when a row is deleted (or updated - an update\n** is implemented as a delete followed by an insert). SQLite provides the\n** rowid of the row to delete, which can be used to find the leaf on which\n** the entry resides (argument pLeaf). Once the leaf is located, this \n** function is called to determine its ancestry.\n*/\nstatic int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){\n  int rc = SQLITE_OK;\n  RtreeNode *pChild = pLeaf;\n  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){\n    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */\n    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);\n    rc = sqlite3_step(pRtree->pReadParent);\n    if( rc==SQLITE_ROW ){\n      RtreeNode *pTest;           /* Used to test for reference loops */\n      i64 iNode;                  /* Node number of parent node */\n\n      /* Before setting pChild->pParent, test that we are not creating a\n      ** loop of references (as we would if, say, pChild==pParent). We don't\n      ** want to do this as it leads to a memory leak when trying to delete\n      ** the referenced counted node structures.\n      */\n      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);\n      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);\n      if( !pTest ){\n        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);\n      }\n    }\n    rc = sqlite3_reset(pRtree->pReadParent);\n    if( rc==SQLITE_OK ) rc = rc2;\n    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;\n    pChild = pChild->pParent;\n  }\n  return rc;\n}\n\nstatic int deleteCell(Rtree *, RtreeNode *, int, int);\n\nstatic int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){\n  int rc;\n  int rc2;\n  RtreeNode *pParent = 0;\n  int iCell;\n\n  assert( pNode->nRef==1 );\n\n  /* Remove the entry in the parent cell. */\n  rc = nodeParentIndex(pRtree, pNode, &iCell);\n  if( rc==SQLITE_OK ){\n    pParent = pNode->pParent;\n    pNode->pParent = 0;\n    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);\n  }\n  rc2 = nodeRelease(pRtree, pParent);\n  if( rc==SQLITE_OK ){\n    rc = rc2;\n  }\n  if( rc!=SQLITE_OK ){\n    return rc;\n  }\n\n  /* Remove the xxx_node entry. */\n  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);\n  sqlite3_step(pRtree->pDeleteNode);\n  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){\n    return rc;\n  }\n\n  /* Remove the xxx_parent entry. */\n  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);\n  sqlite3_step(pRtree->pDeleteParent);\n  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){\n    return rc;\n  }\n  \n  /* Remove the node from the in-memory hash table and link it into\n  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.\n  */\n  nodeHashDelete(pRtree, pNode);\n  pNode->iNode = iHeight;\n  pNode->pNext = pRtree->pDeleted;\n  pNode->nRef++;\n  pRtree->pDeleted = pNode;\n\n  return SQLITE_OK;\n}\n\nstatic int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){\n  RtreeNode *pParent = pNode->pParent;\n  int rc = SQLITE_OK; \n  if( pParent ){\n    int ii; \n    int nCell = NCELL(pNode);\n    RtreeCell box;                            /* Bounding box for pNode */\n    nodeGetCell(pRtree, pNode, 0, &box);\n    for(ii=1; ii<nCell; ii++){\n      RtreeCell cell;\n      nodeGetCell(pRtree, pNode, ii, &cell);\n      cellUnion(pRtree, &box, &cell);\n    }\n    box.iRowid = pNode->iNode;\n    rc = nodeParentIndex(pRtree, pNode, &ii);\n    if( rc==SQLITE_OK ){\n      nodeOverwriteCell(pRtree, pParent, &box, ii);\n      rc = fixBoundingBox(pRtree, pParent);\n    }\n  }\n  return rc;\n}\n\n/*\n** Delete the cell at index iCell of node pNode. After removing the\n** cell, adjust the r-tree data structure if required.\n*/\nstatic int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){\n  RtreeNode *pParent;\n  int rc;\n\n  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){\n    return rc;\n  }\n\n  /* Remove the cell from the node. This call just moves bytes around\n  ** the in-memory node image, so it cannot fail.\n  */\n  nodeDeleteCell(pRtree, pNode, iCell);\n\n  /* If the node is not the tree root and now has less than the minimum\n  ** number of cells, remove it from the tree. Otherwise, update the\n  ** cell in the parent node so that it tightly contains the updated\n  ** node.\n  */\n  pParent = pNode->pParent;\n  assert( pParent || pNode->iNode==1 );\n  if( pParent ){\n    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){\n      rc = removeNode(pRtree, pNode, iHeight);\n    }else{\n      rc = fixBoundingBox(pRtree, pNode);\n    }\n  }\n\n  return rc;\n}\n\nstatic int Reinsert(\n  Rtree *pRtree, \n  RtreeNode *pNode, \n  RtreeCell *pCell, \n  int iHeight\n){\n  int *aOrder;\n  int *aSpare;\n  RtreeCell *aCell;\n  RtreeDValue *aDistance;\n  int nCell;\n  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];\n  int iDim;\n  int ii;\n  int rc = SQLITE_OK;\n  int n;\n\n  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);\n\n  nCell = NCELL(pNode)+1;\n  n = (nCell+1)&(~1);\n\n  /* Allocate the buffers used by this operation. The allocation is\n  ** relinquished before this function returns.\n  */\n  aCell = (RtreeCell *)sqlite3_malloc(n * (\n    sizeof(RtreeCell)     +         /* aCell array */\n    sizeof(int)           +         /* aOrder array */\n    sizeof(int)           +         /* aSpare array */\n    sizeof(RtreeDValue)             /* aDistance array */\n  ));\n  if( !aCell ){\n    return SQLITE_NOMEM;\n  }\n  aOrder    = (int *)&aCell[n];\n  aSpare    = (int *)&aOrder[n];\n  aDistance = (RtreeDValue *)&aSpare[n];\n\n  for(ii=0; ii<nCell; ii++){\n    if( ii==(nCell-1) ){\n      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));\n    }else{\n      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);\n    }\n    aOrder[ii] = ii;\n    for(iDim=0; iDim<pRtree->nDim; iDim++){\n      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);\n      aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);\n    }\n  }\n  for(iDim=0; iDim<pRtree->nDim; iDim++){\n    aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));\n  }\n\n  for(ii=0; ii<nCell; ii++){\n    aDistance[ii] = 0.0;\n    for(iDim=0; iDim<pRtree->nDim; iDim++){\n      RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - \n                               DCOORD(aCell[ii].aCoord[iDim*2]));\n      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);\n    }\n  }\n\n  SortByDistance(aOrder, nCell, aDistance, aSpare);\n  nodeZero(pRtree, pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){\n    RtreeCell *p = &aCell[aOrder[ii]];\n    nodeInsertCell(pRtree, pNode, p);\n    if( p->iRowid==pCell->iRowid ){\n      if( iHeight==0 ){\n        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);\n      }else{\n        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);\n      }\n    }\n  }\n  if( rc==SQLITE_OK ){\n    rc = fixBoundingBox(pRtree, pNode);\n  }\n  for(; rc==SQLITE_OK && ii<nCell; ii++){\n    /* Find a node to store this cell in. pNode->iNode currently contains\n    ** the height of the sub-tree headed by the cell.\n    */\n    RtreeNode *pInsert;\n    RtreeCell *p = &aCell[aOrder[ii]];\n    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);\n    if( rc==SQLITE_OK ){\n      int rc2;\n      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);\n      rc2 = nodeRelease(pRtree, pInsert);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\n  sqlite3_free(aCell);\n  return rc;\n}\n\n/*\n** Insert cell pCell into node pNode. Node pNode is the head of a \n** subtree iHeight high (leaf nodes have iHeight==0).\n*/\nstatic int rtreeInsertCell(\n  Rtree *pRtree,\n  RtreeNode *pNode,\n  RtreeCell *pCell,\n  int iHeight\n){\n  int rc = SQLITE_OK;\n  if( iHeight>0 ){\n    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);\n    if( pChild ){\n      nodeRelease(pRtree, pChild->pParent);\n      nodeReference(pNode);\n      pChild->pParent = pNode;\n    }\n  }\n  if( nodeInsertCell(pRtree, pNode, pCell) ){\n#if VARIANT_RSTARTREE_REINSERT\n    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){\n      rc = SplitNode(pRtree, pNode, pCell, iHeight);\n    }else{\n      pRtree->iReinsertHeight = iHeight;\n      rc = Reinsert(pRtree, pNode, pCell, iHeight);\n    }\n#else\n    rc = SplitNode(pRtree, pNode, pCell, iHeight);\n#endif\n  }else{\n    rc = AdjustTree(pRtree, pNode, pCell);\n    if( rc==SQLITE_OK ){\n      if( iHeight==0 ){\n        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);\n      }else{\n        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);\n      }\n    }\n  }\n  return rc;\n}\n\nstatic int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){\n  int ii;\n  int rc = SQLITE_OK;\n  int nCell = NCELL(pNode);\n\n  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){\n    RtreeNode *pInsert;\n    RtreeCell cell;\n    nodeGetCell(pRtree, pNode, ii, &cell);\n\n    /* Find a node to store this cell in. pNode->iNode currently contains\n    ** the height of the sub-tree headed by the cell.\n    */\n    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);\n    if( rc==SQLITE_OK ){\n      int rc2;\n      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);\n      rc2 = nodeRelease(pRtree, pInsert);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n  return rc;\n}\n\n/*\n** Select a currently unused rowid for a new r-tree record.\n*/\nstatic int newRowid(Rtree *pRtree, i64 *piRowid){\n  int rc;\n  sqlite3_bind_null(pRtree->pWriteRowid, 1);\n  sqlite3_bind_null(pRtree->pWriteRowid, 2);\n  sqlite3_step(pRtree->pWriteRowid);\n  rc = sqlite3_reset(pRtree->pWriteRowid);\n  *piRowid = sqlite3_last_insert_rowid(pRtree->db);\n  return rc;\n}\n\n/*\n** Remove the entry with rowid=iDelete from the r-tree structure.\n*/\nstatic int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){\n  int rc;                         /* Return code */\n  RtreeNode *pLeaf;               /* Leaf node containing record iDelete */\n  int iCell;                      /* Index of iDelete cell in pLeaf */\n  RtreeNode *pRoot;               /* Root node of rtree structure */\n\n\n  /* Obtain a reference to the root node to initialise Rtree.iDepth */\n  rc = nodeAcquire(pRtree, 1, 0, &pRoot);\n\n  /* Obtain a reference to the leaf node that contains the entry \n  ** about to be deleted. \n  */\n  if( rc==SQLITE_OK ){\n    rc = findLeafNode(pRtree, iDelete, &pLeaf);\n  }\n\n  /* Delete the cell in question from the leaf node. */\n  if( rc==SQLITE_OK ){\n    int rc2;\n    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);\n    if( rc==SQLITE_OK ){\n      rc = deleteCell(pRtree, pLeaf, iCell, 0);\n    }\n    rc2 = nodeRelease(pRtree, pLeaf);\n    if( rc==SQLITE_OK ){\n      rc = rc2;\n    }\n  }\n\n  /* Delete the corresponding entry in the <rtree>_rowid table. */\n  if( rc==SQLITE_OK ){\n    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);\n    sqlite3_step(pRtree->pDeleteRowid);\n    rc = sqlite3_reset(pRtree->pDeleteRowid);\n  }\n\n  /* Check if the root node now has exactly one child. If so, remove\n  ** it, schedule the contents of the child for reinsertion and \n  ** reduce the tree height by one.\n  **\n  ** This is equivalent to copying the contents of the child into\n  ** the root node (the operation that Gutman's paper says to perform \n  ** in this scenario).\n  */\n  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){\n    int rc2;\n    RtreeNode *pChild;\n    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);\n    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);\n    if( rc==SQLITE_OK ){\n      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);\n    }\n    rc2 = nodeRelease(pRtree, pChild);\n    if( rc==SQLITE_OK ) rc = rc2;\n    if( rc==SQLITE_OK ){\n      pRtree->iDepth--;\n      writeInt16(pRoot->zData, pRtree->iDepth);\n      pRoot->isDirty = 1;\n    }\n  }\n\n  /* Re-insert the contents of any underfull nodes removed from the tree. */\n  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){\n    if( rc==SQLITE_OK ){\n      rc = reinsertNodeContent(pRtree, pLeaf);\n    }\n    pRtree->pDeleted = pLeaf->pNext;\n    sqlite3_free(pLeaf);\n  }\n\n  /* Release the reference to the root node. */\n  if( rc==SQLITE_OK ){\n    rc = nodeRelease(pRtree, pRoot);\n  }else{\n    nodeRelease(pRtree, pRoot);\n  }\n\n  return rc;\n}\n\n/*\n** Rounding constants for float->double conversion.\n*/\n#define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */\n#define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */\n\n#if !defined(SQLITE_RTREE_INT_ONLY)\n/*\n** Convert an sqlite3_value into an RtreeValue (presumably a float)\n** while taking care to round toward negative or positive, respectively.\n*/\nstatic RtreeValue rtreeValueDown(sqlite3_value *v){\n  double d = sqlite3_value_double(v);\n  float f = (float)d;\n  if( f>d ){\n    f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));\n  }\n  return f;\n}\nstatic RtreeValue rtreeValueUp(sqlite3_value *v){\n  double d = sqlite3_value_double(v);\n  float f = (float)d;\n  if( f<d ){\n    f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));\n  }\n  return f;\n}\n#endif /* !defined(SQLITE_RTREE_INT_ONLY) */\n\n\n/*\n** The xUpdate method for rtree module virtual tables.\n*/\nstatic int rtreeUpdate(\n  sqlite3_vtab *pVtab, \n  int nData, \n  sqlite3_value **azData, \n  sqlite_int64 *pRowid\n){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc = SQLITE_OK;\n  RtreeCell cell;                 /* New cell to insert if nData>1 */\n  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */\n\n  rtreeReference(pRtree);\n  assert(nData>=1);\n\n  /* Constraint handling. A write operation on an r-tree table may return\n  ** SQLITE_CONSTRAINT for two reasons:\n  **\n  **   1. A duplicate rowid value, or\n  **   2. The supplied data violates the \"x2>=x1\" constraint.\n  **\n  ** In the first case, if the conflict-handling mode is REPLACE, then\n  ** the conflicting row can be removed before proceeding. In the second\n  ** case, SQLITE_CONSTRAINT must be returned regardless of the\n  ** conflict-handling mode specified by the user.\n  */\n  if( nData>1 ){\n    int ii;\n\n    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */\n    assert( nData==(pRtree->nDim*2 + 3) );\n#ifndef SQLITE_RTREE_INT_ONLY\n    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){\n      for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n        cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);\n        cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);\n        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){\n          rc = SQLITE_CONSTRAINT;\n          goto constraint;\n        }\n      }\n    }else\n#endif\n    {\n      for(ii=0; ii<(pRtree->nDim*2); ii+=2){\n        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);\n        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);\n        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){\n          rc = SQLITE_CONSTRAINT;\n          goto constraint;\n        }\n      }\n    }\n\n    /* If a rowid value was supplied, check if it is already present in \n    ** the table. If so, the constraint has failed. */\n    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){\n      cell.iRowid = sqlite3_value_int64(azData[2]);\n      if( sqlite3_value_type(azData[0])==SQLITE_NULL\n       || sqlite3_value_int64(azData[0])!=cell.iRowid\n      ){\n        int steprc;\n        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);\n        steprc = sqlite3_step(pRtree->pReadRowid);\n        rc = sqlite3_reset(pRtree->pReadRowid);\n        if( SQLITE_ROW==steprc ){\n          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){\n            rc = rtreeDeleteRowid(pRtree, cell.iRowid);\n          }else{\n            rc = SQLITE_CONSTRAINT;\n            goto constraint;\n          }\n        }\n      }\n      bHaveRowid = 1;\n    }\n  }\n\n  /* If azData[0] is not an SQL NULL value, it is the rowid of a\n  ** record to delete from the r-tree table. The following block does\n  ** just that.\n  */\n  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){\n    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));\n  }\n\n  /* If the azData[] array contains more than one element, elements\n  ** (azData[2]..azData[argc-1]) contain a new record to insert into\n  ** the r-tree structure.\n  */\n  if( rc==SQLITE_OK && nData>1 ){\n    /* Insert the new record into the r-tree */\n    RtreeNode *pLeaf;\n\n    /* Figure out the rowid of the new row. */\n    if( bHaveRowid==0 ){\n      rc = newRowid(pRtree, &cell.iRowid);\n    }\n    *pRowid = cell.iRowid;\n\n    if( rc==SQLITE_OK ){\n      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);\n    }\n    if( rc==SQLITE_OK ){\n      int rc2;\n      pRtree->iReinsertHeight = -1;\n      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);\n      rc2 = nodeRelease(pRtree, pLeaf);\n      if( rc==SQLITE_OK ){\n        rc = rc2;\n      }\n    }\n  }\n\nconstraint:\n  rtreeRelease(pRtree);\n  return rc;\n}\n\n/*\n** The xRename method for rtree module virtual tables.\n*/\nstatic int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){\n  Rtree *pRtree = (Rtree *)pVtab;\n  int rc = SQLITE_NOMEM;\n  char *zSql = sqlite3_mprintf(\n    \"ALTER TABLE %Q.'%q_node'   RENAME TO \\\"%w_node\\\";\"\n    \"ALTER TABLE %Q.'%q_parent' RENAME TO \\\"%w_parent\\\";\"\n    \"ALTER TABLE %Q.'%q_rowid'  RENAME TO \\\"%w_rowid\\\";\"\n    , pRtree->zDb, pRtree->zName, zNewName \n    , pRtree->zDb, pRtree->zName, zNewName \n    , pRtree->zDb, pRtree->zName, zNewName\n  );\n  if( zSql ){\n    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);\n    sqlite3_free(zSql);\n  }\n  return rc;\n}\n\nstatic sqlite3_module rtreeModule = {\n  0,                          /* iVersion */\n  rtreeCreate,                /* xCreate - create a table */\n  rtreeConnect,               /* xConnect - connect to an existing table */\n  rtreeBestIndex,             /* xBestIndex - Determine search strategy */\n  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */\n  rtreeDestroy,               /* xDestroy - Drop a table */\n  rtreeOpen,                  /* xOpen - open a cursor */\n  rtreeClose,                 /* xClose - close a cursor */\n  rtreeFilter,                /* xFilter - configure scan constraints */\n  rtreeNext,                  /* xNext - advance a cursor */\n  rtreeEof,                   /* xEof */\n  rtreeColumn,                /* xColumn - read data */\n  rtreeRowid,                 /* xRowid - read data */\n  rtreeUpdate,                /* xUpdate - write data */\n  0,                          /* xBegin - begin transaction */\n  0,                          /* xSync - sync transaction */\n  0,                          /* xCommit - commit transaction */\n  0,                          /* xRollback - rollback transaction */\n  0,                          /* xFindFunction - function overloading */\n  rtreeRename,                /* xRename - rename the table */\n  0,                          /* xSavepoint */\n  0,                          /* xRelease */\n  0                           /* xRollbackTo */\n};\n\nstatic int rtreeSqlInit(\n  Rtree *pRtree, \n  sqlite3 *db, \n  const char *zDb, \n  const char *zPrefix, \n  int isCreate\n){\n  int rc = SQLITE_OK;\n\n  #define N_STATEMENT 9\n  static const char *azSql[N_STATEMENT] = {\n    /* Read and write the xxx_node table */\n    \"SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1\",\n    \"INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)\",\n    \"DELETE FROM '%q'.'%q_node' WHERE nodeno = :1\",\n\n    /* Read and write the xxx_rowid table */\n    \"SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1\",\n    \"INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)\",\n    \"DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1\",\n\n    /* Read and write the xxx_parent table */\n    \"SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1\",\n    \"INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)\",\n    \"DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1\"\n  };\n  sqlite3_stmt **appStmt[N_STATEMENT];\n  int i;\n\n  pRtree->db = db;\n\n  if( isCreate ){\n    char *zCreate = sqlite3_mprintf(\n\"CREATE TABLE \\\"%w\\\".\\\"%w_node\\\"(nodeno INTEGER PRIMARY KEY, data BLOB);\"\n\"CREATE TABLE \\\"%w\\\".\\\"%w_rowid\\\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);\"\n\"CREATE TABLE \\\"%w\\\".\\\"%w_parent\\\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);\"\n\"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))\",\n      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize\n    );\n    if( !zCreate ){\n      return SQLITE_NOMEM;\n    }\n    rc = sqlite3_exec(db, zCreate, 0, 0, 0);\n    sqlite3_free(zCreate);\n    if( rc!=SQLITE_OK ){\n      return rc;\n    }\n  }\n\n  appStmt[0] = &pRtree->pReadNode;\n  appStmt[1] = &pRtree->pWriteNode;\n  appStmt[2] = &pRtree->pDeleteNode;\n  appStmt[3] = &pRtree->pReadRowid;\n  appStmt[4] = &pRtree->pWriteRowid;\n  appStmt[5] = &pRtree->pDeleteRowid;\n  appStmt[6] = &pRtree->pReadParent;\n  appStmt[7] = &pRtree->pWriteParent;\n  appStmt[8] = &pRtree->pDeleteParent;\n\n  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){\n    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);\n    if( zSql ){\n      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); \n    }else{\n      rc = SQLITE_NOMEM;\n    }\n    sqlite3_free(zSql);\n  }\n\n  return rc;\n}\n\n/*\n** The second argument to this function contains the text of an SQL statement\n** that returns a single integer value. The statement is compiled and executed\n** using database connection db. If successful, the integer value returned\n** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error\n** code is returned and the value of *piVal after returning is not defined.\n*/\nstatic int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){\n  int rc = SQLITE_NOMEM;\n  if( zSql ){\n    sqlite3_stmt *pStmt = 0;\n    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);\n    if( rc==SQLITE_OK ){\n      if( SQLITE_ROW==sqlite3_step(pStmt) ){\n        *piVal = sqlite3_column_int(pStmt, 0);\n      }\n      rc = sqlite3_finalize(pStmt);\n    }\n  }\n  return rc;\n}\n\n/*\n** This function is called from within the xConnect() or xCreate() method to\n** determine the node-size used by the rtree table being created or connected\n** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.\n** Otherwise, an SQLite error code is returned.\n**\n** If this function is being called as part of an xConnect(), then the rtree\n** table already exists. In this case the node-size is determined by inspecting\n** the root node of the tree.\n**\n** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. \n** This ensures that each node is stored on a single database page. If the \n** database page-size is so large that more than RTREE_MAXCELLS entries \n** would fit in a single node, use a smaller node-size.\n*/\nstatic int getNodeSize(\n  sqlite3 *db,                    /* Database handle */\n  Rtree *pRtree,                  /* Rtree handle */\n  int isCreate                    /* True for xCreate, false for xConnect */\n){\n  int rc;\n  char *zSql;\n  if( isCreate ){\n    int iPageSize = 0;\n    zSql = sqlite3_mprintf(\"PRAGMA %Q.page_size\", pRtree->zDb);\n    rc = getIntFromStmt(db, zSql, &iPageSize);\n    if( rc==SQLITE_OK ){\n      pRtree->iNodeSize = iPageSize-64;\n      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){\n        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;\n      }\n    }\n  }else{\n    zSql = sqlite3_mprintf(\n        \"SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1\",\n        pRtree->zDb, pRtree->zName\n    );\n    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);\n  }\n\n  sqlite3_free(zSql);\n  return rc;\n}\n\n/* \n** This function is the implementation of both the xConnect and xCreate\n** methods of the r-tree virtual table.\n**\n**   argv[0]   -> module name\n**   argv[1]   -> database name\n**   argv[2]   -> table name\n**   argv[...] -> column names...\n*/\nstatic int rtreeInit(\n  sqlite3 *db,                        /* Database connection */\n  void *pAux,                         /* One of the RTREE_COORD_* constants */\n  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */\n  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */\n  char **pzErr,                       /* OUT: Error message, if any */\n  int isCreate                        /* True for xCreate, false for xConnect */\n){\n  int rc = SQLITE_OK;\n  Rtree *pRtree;\n  int nDb;              /* Length of string argv[1] */\n  int nName;            /* Length of string argv[2] */\n  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);\n\n  const char *aErrMsg[] = {\n    0,                                                    /* 0 */\n    \"Wrong number of columns for an rtree table\",         /* 1 */\n    \"Too few columns for an rtree table\",                 /* 2 */\n    \"Too many columns for an rtree table\"                 /* 3 */\n  };\n\n  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;\n  if( aErrMsg[iErr] ){\n    *pzErr = sqlite3_mprintf(\"%s\", aErrMsg[iErr]);\n    return SQLITE_ERROR;\n  }\n\n  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);\n\n  /* Allocate the sqlite3_vtab structure */\n  nDb = (int)strlen(argv[1]);\n  nName = (int)strlen(argv[2]);\n  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);\n  if( !pRtree ){\n    return SQLITE_NOMEM;\n  }\n  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);\n  pRtree->nBusy = 1;\n  pRtree->base.pModule = &rtreeModule;\n  pRtree->zDb = (char *)&pRtree[1];\n  pRtree->zName = &pRtree->zDb[nDb+1];\n  pRtree->nDim = (argc-4)/2;\n  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;\n  pRtree->eCoordType = eCoordType;\n  memcpy(pRtree->zDb, argv[1], nDb);\n  memcpy(pRtree->zName, argv[2], nName);\n\n  /* Figure out the node size to use. */\n  rc = getNodeSize(db, pRtree, isCreate);\n\n  /* Create/Connect to the underlying relational database schema. If\n  ** that is successful, call sqlite3_declare_vtab() to configure\n  ** the r-tree table schema.\n  */\n  if( rc==SQLITE_OK ){\n    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){\n      *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n    }else{\n      char *zSql = sqlite3_mprintf(\"CREATE TABLE x(%s\", argv[3]);\n      char *zTmp;\n      int ii;\n      for(ii=4; zSql && ii<argc; ii++){\n        zTmp = zSql;\n        zSql = sqlite3_mprintf(\"%s, %s\", zTmp, argv[ii]);\n        sqlite3_free(zTmp);\n      }\n      if( zSql ){\n        zTmp = zSql;\n        zSql = sqlite3_mprintf(\"%s);\", zTmp);\n        sqlite3_free(zTmp);\n      }\n      if( !zSql ){\n        rc = SQLITE_NOMEM;\n      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){\n        *pzErr = sqlite3_mprintf(\"%s\", sqlite3_errmsg(db));\n      }\n      sqlite3_free(zSql);\n    }\n  }\n\n  if( rc==SQLITE_OK ){\n    *ppVtab = (sqlite3_vtab *)pRtree;\n  }else{\n    rtreeRelease(pRtree);\n  }\n  return rc;\n}\n\n\n/*\n** Implementation of a scalar function that decodes r-tree nodes to\n** human readable strings. This can be used for debugging and analysis.\n**\n** The scalar function takes two arguments, a blob of data containing\n** an r-tree node, and the number of dimensions the r-tree indexes.\n** For a two-dimensional r-tree structure called \"rt\", to deserialize\n** all nodes, a statement like:\n**\n**   SELECT rtreenode(2, data) FROM rt_node;\n**\n** The human readable string takes the form of a Tcl list with one\n** entry for each cell in the r-tree node. Each entry is itself a\n** list, containing the 8-byte rowid/pageno followed by the \n** <num-dimension>*2 coordinates.\n*/\nstatic void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){\n  char *zText = 0;\n  RtreeNode node;\n  Rtree tree;\n  int ii;\n\n  UNUSED_PARAMETER(nArg);\n  memset(&node, 0, sizeof(RtreeNode));\n  memset(&tree, 0, sizeof(Rtree));\n  tree.nDim = sqlite3_value_int(apArg[0]);\n  tree.nBytesPerCell = 8 + 8 * tree.nDim;\n  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);\n\n  for(ii=0; ii<NCELL(&node); ii++){\n    char zCell[512];\n    int nCell = 0;\n    RtreeCell cell;\n    int jj;\n\n    nodeGetCell(&tree, &node, ii, &cell);\n    sqlite3_snprintf(512-nCell,&zCell[nCell],\"%lld\", cell.iRowid);\n    nCell = (int)strlen(zCell);\n    for(jj=0; jj<tree.nDim*2; jj++){\n#ifndef SQLITE_RTREE_INT_ONLY\n      sqlite3_snprintf(512-nCell,&zCell[nCell], \" %f\",\n                       (double)cell.aCoord[jj].f);\n#else\n      sqlite3_snprintf(512-nCell,&zCell[nCell], \" %d\",\n                       cell.aCoord[jj].i);\n#endif\n      nCell = (int)strlen(zCell);\n    }\n\n    if( zText ){\n      char *zTextNew = sqlite3_mprintf(\"%s {%s}\", zText, zCell);\n      sqlite3_free(zText);\n      zText = zTextNew;\n    }else{\n      zText = sqlite3_mprintf(\"{%s}\", zCell);\n    }\n  }\n  \n  sqlite3_result_text(ctx, zText, -1, sqlite3_free);\n}\n\nstatic void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){\n  UNUSED_PARAMETER(nArg);\n  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB \n   || sqlite3_value_bytes(apArg[0])<2\n  ){\n    sqlite3_result_error(ctx, \"Invalid argument to rtreedepth()\", -1); \n  }else{\n    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);\n    sqlite3_result_int(ctx, readInt16(zBlob));\n  }\n}\n\n/*\n** Register the r-tree module with database handle db. This creates the\n** virtual table module \"rtree\" and the debugging/analysis scalar \n** function \"rtreenode\".\n*/\nSQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){\n  const int utf8 = SQLITE_UTF8;\n  int rc;\n\n  rc = sqlite3_create_function(db, \"rtreenode\", 2, utf8, 0, rtreenode, 0, 0);\n  if( rc==SQLITE_OK ){\n    rc = sqlite3_create_function(db, \"rtreedepth\", 1, utf8, 0,rtreedepth, 0, 0);\n  }\n  if( rc==SQLITE_OK ){\n#ifdef SQLITE_RTREE_INT_ONLY\n    void *c = (void *)RTREE_COORD_INT32;\n#else\n    void *c = (void *)RTREE_COORD_REAL32;\n#endif\n    rc = sqlite3_create_module_v2(db, \"rtree\", &rtreeModule, c, 0);\n  }\n  if( rc==SQLITE_OK ){\n    void *c = (void *)RTREE_COORD_INT32;\n    rc = sqlite3_create_module_v2(db, \"rtree_i32\", &rtreeModule, c, 0);\n  }\n\n  return rc;\n}\n\n/*\n** A version of sqlite3_free() that can be used as a callback. This is used\n** in two places - as the destructor for the blob value returned by the\n** invocation of a geometry function, and as the destructor for the geometry\n** functions themselves.\n*/\nstatic void doSqlite3Free(void *p){\n  sqlite3_free(p);\n}\n\n/*\n** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite\n** scalar user function. This C function is the callback used for all such\n** registered SQL functions.\n**\n** The scalar user functions return a blob that is interpreted by r-tree\n** table MATCH operators.\n*/\nstatic void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){\n  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);\n  RtreeMatchArg *pBlob;\n  int nBlob;\n\n  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);\n  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);\n  if( !pBlob ){\n    sqlite3_result_error_nomem(ctx);\n  }else{\n    int i;\n    pBlob->magic = RTREE_GEOMETRY_MAGIC;\n    pBlob->xGeom = pGeomCtx->xGeom;\n    pBlob->pContext = pGeomCtx->pContext;\n    pBlob->nParam = nArg;\n    for(i=0; i<nArg; i++){\n#ifdef SQLITE_RTREE_INT_ONLY\n      pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);\n#else\n      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);\n#endif\n    }\n    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);\n  }\n}\n\n/*\n** Register a new geometry function for use with the r-tree MATCH operator.\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,\n  const char *zGeom,\n  int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),\n  void *pContext\n){\n  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */\n\n  /* Allocate and populate the context object. */\n  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));\n  if( !pGeomCtx ) return SQLITE_NOMEM;\n  pGeomCtx->xGeom = xGeom;\n  pGeomCtx->pContext = pContext;\n\n  /* Create the new user-function. Register a destructor function to delete\n  ** the context object when it is no longer required.  */\n  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, \n      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free\n  );\n}\n\n#if !SQLITE_CORE\nSQLITE_API int sqlite3_extension_init(\n  sqlite3 *db,\n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3RtreeInit(db);\n}\n#endif\n\n#endif\n\n/************** End of rtree.c ***********************************************/\n/************** Begin file icu.c *********************************************/\n/*\n** 2007 May 6\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $\n**\n** This file implements an integration between the ICU library \n** (\"International Components for Unicode\", an open-source library \n** for handling unicode data) and SQLite. The integration uses \n** ICU to provide the following to SQLite:\n**\n**   * An implementation of the SQL regexp() function (and hence REGEXP\n**     operator) using the ICU uregex_XX() APIs.\n**\n**   * Implementations of the SQL scalar upper() and lower() functions\n**     for case mapping.\n**\n**   * Integration of ICU and SQLite collation seqences.\n**\n**   * An implementation of the LIKE operator that uses ICU to \n**     provide case-independent matching.\n*/\n\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)\n\n/* Include ICU headers */\n#include <unicode/utypes.h>\n#include <unicode/uregex.h>\n#include <unicode/ustring.h>\n#include <unicode/ucol.h>\n\n/* #include <assert.h> */\n\n#ifndef SQLITE_CORE\n  SQLITE_EXTENSION_INIT1\n#else\n#endif\n\n/*\n** Maximum length (in bytes) of the pattern in a LIKE or GLOB\n** operator.\n*/\n#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH\n# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000\n#endif\n\n/*\n** Version of sqlite3_free() that is always a function, never a macro.\n*/\nstatic void xFree(void *p){\n  sqlite3_free(p);\n}\n\n/*\n** Compare two UTF-8 strings for equality where the first string is\n** a \"LIKE\" expression. Return true (1) if they are the same and \n** false (0) if they are different.\n*/\nstatic int icuLikeCompare(\n  const uint8_t *zPattern,   /* LIKE pattern */\n  const uint8_t *zString,    /* The UTF-8 string to compare against */\n  const UChar32 uEsc         /* The escape character */\n){\n  static const int MATCH_ONE = (UChar32)'_';\n  static const int MATCH_ALL = (UChar32)'%';\n\n  int iPattern = 0;       /* Current byte index in zPattern */\n  int iString = 0;        /* Current byte index in zString */\n\n  int prevEscape = 0;     /* True if the previous character was uEsc */\n\n  while( zPattern[iPattern]!=0 ){\n\n    /* Read (and consume) the next character from the input pattern. */\n    UChar32 uPattern;\n    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);\n    assert(uPattern!=0);\n\n    /* There are now 4 possibilities:\n    **\n    **     1. uPattern is an unescaped match-all character \"%\",\n    **     2. uPattern is an unescaped match-one character \"_\",\n    **     3. uPattern is an unescaped escape character, or\n    **     4. uPattern is to be handled as an ordinary character\n    */\n    if( !prevEscape && uPattern==MATCH_ALL ){\n      /* Case 1. */\n      uint8_t c;\n\n      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a\n      ** MATCH_ALL. For each MATCH_ONE, skip one character in the \n      ** test string.\n      */\n      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){\n        if( c==MATCH_ONE ){\n          if( zString[iString]==0 ) return 0;\n          U8_FWD_1_UNSAFE(zString, iString);\n        }\n        iPattern++;\n      }\n\n      if( zPattern[iPattern]==0 ) return 1;\n\n      while( zString[iString] ){\n        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){\n          return 1;\n        }\n        U8_FWD_1_UNSAFE(zString, iString);\n      }\n      return 0;\n\n    }else if( !prevEscape && uPattern==MATCH_ONE ){\n      /* Case 2. */\n      if( zString[iString]==0 ) return 0;\n      U8_FWD_1_UNSAFE(zString, iString);\n\n    }else if( !prevEscape && uPattern==uEsc){\n      /* Case 3. */\n      prevEscape = 1;\n\n    }else{\n      /* Case 4. */\n      UChar32 uString;\n      U8_NEXT_UNSAFE(zString, iString, uString);\n      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);\n      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);\n      if( uString!=uPattern ){\n        return 0;\n      }\n      prevEscape = 0;\n    }\n  }\n\n  return zString[iString]==0;\n}\n\n/*\n** Implementation of the like() SQL function.  This function implements\n** the build-in LIKE operator.  The first argument to the function is the\n** pattern and the second argument is the string.  So, the SQL statements:\n**\n**       A LIKE B\n**\n** is implemented as like(B, A). If there is an escape character E, \n**\n**       A LIKE B ESCAPE E\n**\n** is mapped to like(B, A, E).\n*/\nstatic void icuLikeFunc(\n  sqlite3_context *context, \n  int argc, \n  sqlite3_value **argv\n){\n  const unsigned char *zA = sqlite3_value_text(argv[0]);\n  const unsigned char *zB = sqlite3_value_text(argv[1]);\n  UChar32 uEsc = 0;\n\n  /* Limit the length of the LIKE or GLOB pattern to avoid problems\n  ** of deep recursion and N*N behavior in patternCompare().\n  */\n  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){\n    sqlite3_result_error(context, \"LIKE or GLOB pattern too complex\", -1);\n    return;\n  }\n\n\n  if( argc==3 ){\n    /* The escape character string must consist of a single UTF-8 character.\n    ** Otherwise, return an error.\n    */\n    int nE= sqlite3_value_bytes(argv[2]);\n    const unsigned char *zE = sqlite3_value_text(argv[2]);\n    int i = 0;\n    if( zE==0 ) return;\n    U8_NEXT(zE, i, nE, uEsc);\n    if( i!=nE){\n      sqlite3_result_error(context, \n          \"ESCAPE expression must be a single character\", -1);\n      return;\n    }\n  }\n\n  if( zA && zB ){\n    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));\n  }\n}\n\n/*\n** This function is called when an ICU function called from within\n** the implementation of an SQL scalar function returns an error.\n**\n** The scalar function context passed as the first argument is \n** loaded with an error message based on the following two args.\n*/\nstatic void icuFunctionError(\n  sqlite3_context *pCtx,       /* SQLite scalar function context */\n  const char *zName,           /* Name of ICU function that failed */\n  UErrorCode e                 /* Error code returned by ICU function */\n){\n  char zBuf[128];\n  sqlite3_snprintf(128, zBuf, \"ICU error: %s(): %s\", zName, u_errorName(e));\n  zBuf[127] = '\\0';\n  sqlite3_result_error(pCtx, zBuf, -1);\n}\n\n/*\n** Function to delete compiled regexp objects. Registered as\n** a destructor function with sqlite3_set_auxdata().\n*/\nstatic void icuRegexpDelete(void *p){\n  URegularExpression *pExpr = (URegularExpression *)p;\n  uregex_close(pExpr);\n}\n\n/*\n** Implementation of SQLite REGEXP operator. This scalar function takes\n** two arguments. The first is a regular expression pattern to compile\n** the second is a string to match against that pattern. If either \n** argument is an SQL NULL, then NULL Is returned. Otherwise, the result\n** is 1 if the string matches the pattern, or 0 otherwise.\n**\n** SQLite maps the regexp() function to the regexp() operator such\n** that the following two are equivalent:\n**\n**     zString REGEXP zPattern\n**     regexp(zPattern, zString)\n**\n** Uses the following ICU regexp APIs:\n**\n**     uregex_open()\n**     uregex_matches()\n**     uregex_close()\n*/\nstatic void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){\n  UErrorCode status = U_ZERO_ERROR;\n  URegularExpression *pExpr;\n  UBool res;\n  const UChar *zString = sqlite3_value_text16(apArg[1]);\n\n  (void)nArg;  /* Unused parameter */\n\n  /* If the left hand side of the regexp operator is NULL, \n  ** then the result is also NULL. \n  */\n  if( !zString ){\n    return;\n  }\n\n  pExpr = sqlite3_get_auxdata(p, 0);\n  if( !pExpr ){\n    const UChar *zPattern = sqlite3_value_text16(apArg[0]);\n    if( !zPattern ){\n      return;\n    }\n    pExpr = uregex_open(zPattern, -1, 0, 0, &status);\n\n    if( U_SUCCESS(status) ){\n      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);\n    }else{\n      assert(!pExpr);\n      icuFunctionError(p, \"uregex_open\", status);\n      return;\n    }\n  }\n\n  /* Configure the text that the regular expression operates on. */\n  uregex_setText(pExpr, zString, -1, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"uregex_setText\", status);\n    return;\n  }\n\n  /* Attempt the match */\n  res = uregex_matches(pExpr, 0, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"uregex_matches\", status);\n    return;\n  }\n\n  /* Set the text that the regular expression operates on to a NULL\n  ** pointer. This is not really necessary, but it is tidier than \n  ** leaving the regular expression object configured with an invalid\n  ** pointer after this function returns.\n  */\n  uregex_setText(pExpr, 0, 0, &status);\n\n  /* Return 1 or 0. */\n  sqlite3_result_int(p, res ? 1 : 0);\n}\n\n/*\n** Implementations of scalar functions for case mapping - upper() and \n** lower(). Function upper() converts its input to upper-case (ABC).\n** Function lower() converts to lower-case (abc).\n**\n** ICU provides two types of case mapping, \"general\" case mapping and\n** \"language specific\". Refer to ICU documentation for the differences\n** between the two.\n**\n** To utilise \"general\" case mapping, the upper() or lower() scalar \n** functions are invoked with one argument:\n**\n**     upper('ABC') -> 'abc'\n**     lower('abc') -> 'ABC'\n**\n** To access ICU \"language specific\" case mapping, upper() or lower()\n** should be invoked with two arguments. The second argument is the name\n** of the locale to use. Passing an empty string (\"\") or SQL NULL value\n** as the second argument is the same as invoking the 1 argument version\n** of upper() or lower().\n**\n**     lower('I', 'en_us') -> 'i'\n**     lower('I', 'tr_tr') -> 'ı' (small dotless i)\n**\n** http://www.icu-project.org/userguide/posix.html#case_mappings\n*/\nstatic void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){\n  const UChar *zInput;\n  UChar *zOutput;\n  int nInput;\n  int nOutput;\n\n  UErrorCode status = U_ZERO_ERROR;\n  const char *zLocale = 0;\n\n  assert(nArg==1 || nArg==2);\n  if( nArg==2 ){\n    zLocale = (const char *)sqlite3_value_text(apArg[1]);\n  }\n\n  zInput = sqlite3_value_text16(apArg[0]);\n  if( !zInput ){\n    return;\n  }\n  nInput = sqlite3_value_bytes16(apArg[0]);\n\n  nOutput = nInput * 2 + 2;\n  zOutput = sqlite3_malloc(nOutput);\n  if( !zOutput ){\n    return;\n  }\n\n  if( sqlite3_user_data(p) ){\n    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);\n  }else{\n    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);\n  }\n\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"u_strToLower()/u_strToUpper\", status);\n    return;\n  }\n\n  sqlite3_result_text16(p, zOutput, -1, xFree);\n}\n\n/*\n** Collation sequence destructor function. The pCtx argument points to\n** a UCollator structure previously allocated using ucol_open().\n*/\nstatic void icuCollationDel(void *pCtx){\n  UCollator *p = (UCollator *)pCtx;\n  ucol_close(p);\n}\n\n/*\n** Collation sequence comparison function. The pCtx argument points to\n** a UCollator structure previously allocated using ucol_open().\n*/\nstatic int icuCollationColl(\n  void *pCtx,\n  int nLeft,\n  const void *zLeft,\n  int nRight,\n  const void *zRight\n){\n  UCollationResult res;\n  UCollator *p = (UCollator *)pCtx;\n  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);\n  switch( res ){\n    case UCOL_LESS:    return -1;\n    case UCOL_GREATER: return +1;\n    case UCOL_EQUAL:   return 0;\n  }\n  assert(!\"Unexpected return value from ucol_strcoll()\");\n  return 0;\n}\n\n/*\n** Implementation of the scalar function icu_load_collation().\n**\n** This scalar function is used to add ICU collation based collation \n** types to an SQLite database connection. It is intended to be called\n** as follows:\n**\n**     SELECT icu_load_collation(<locale>, <collation-name>);\n**\n** Where <locale> is a string containing an ICU locale identifier (i.e.\n** \"en_AU\", \"tr_TR\" etc.) and <collation-name> is the name of the\n** collation sequence to create.\n*/\nstatic void icuLoadCollation(\n  sqlite3_context *p, \n  int nArg, \n  sqlite3_value **apArg\n){\n  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);\n  UErrorCode status = U_ZERO_ERROR;\n  const char *zLocale;      /* Locale identifier - (eg. \"jp_JP\") */\n  const char *zName;        /* SQL Collation sequence name (eg. \"japanese\") */\n  UCollator *pUCollator;    /* ICU library collation object */\n  int rc;                   /* Return code from sqlite3_create_collation_x() */\n\n  assert(nArg==2);\n  zLocale = (const char *)sqlite3_value_text(apArg[0]);\n  zName = (const char *)sqlite3_value_text(apArg[1]);\n\n  if( !zLocale || !zName ){\n    return;\n  }\n\n  pUCollator = ucol_open(zLocale, &status);\n  if( !U_SUCCESS(status) ){\n    icuFunctionError(p, \"ucol_open\", status);\n    return;\n  }\n  assert(p);\n\n  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, \n      icuCollationColl, icuCollationDel\n  );\n  if( rc!=SQLITE_OK ){\n    ucol_close(pUCollator);\n    sqlite3_result_error(p, \"Error registering collation function\", -1);\n  }\n}\n\n/*\n** Register the ICU extension functions with database db.\n*/\nSQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){\n  struct IcuScalar {\n    const char *zName;                        /* Function name */\n    int nArg;                                 /* Number of arguments */\n    int enc;                                  /* Optimal text encoding */\n    void *pContext;                           /* sqlite3_user_data() context */\n    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);\n  } scalars[] = {\n    {\"regexp\", 2, SQLITE_ANY,          0, icuRegexpFunc},\n\n    {\"lower\",  1, SQLITE_UTF16,        0, icuCaseFunc16},\n    {\"lower\",  2, SQLITE_UTF16,        0, icuCaseFunc16},\n    {\"upper\",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},\n    {\"upper\",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},\n\n    {\"lower\",  1, SQLITE_UTF8,         0, icuCaseFunc16},\n    {\"lower\",  2, SQLITE_UTF8,         0, icuCaseFunc16},\n    {\"upper\",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},\n    {\"upper\",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},\n\n    {\"like\",   2, SQLITE_UTF8,         0, icuLikeFunc},\n    {\"like\",   3, SQLITE_UTF8,         0, icuLikeFunc},\n\n    {\"icu_load_collation\",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},\n  };\n\n  int rc = SQLITE_OK;\n  int i;\n\n  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){\n    struct IcuScalar *p = &scalars[i];\n    rc = sqlite3_create_function(\n        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0\n    );\n  }\n\n  return rc;\n}\n\n#if !SQLITE_CORE\nSQLITE_API int sqlite3_extension_init(\n  sqlite3 *db, \n  char **pzErrMsg,\n  const sqlite3_api_routines *pApi\n){\n  SQLITE_EXTENSION_INIT2(pApi)\n  return sqlite3IcuInit(db);\n}\n#endif\n\n#endif\n\n/************** End of icu.c *************************************************/\n/************** Begin file fts3_icu.c ****************************************/\n/*\n** 2007 June 22\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This file implements a tokenizer for fts3 based on the ICU library.\n*/\n#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)\n#ifdef SQLITE_ENABLE_ICU\n\n/* #include <assert.h> */\n/* #include <string.h> */\n\n#include <unicode/ubrk.h>\n/* #include <unicode/ucol.h> */\n/* #include <unicode/ustring.h> */\n#include <unicode/utf16.h>\n\ntypedef struct IcuTokenizer IcuTokenizer;\ntypedef struct IcuCursor IcuCursor;\n\nstruct IcuTokenizer {\n  sqlite3_tokenizer base;\n  char *zLocale;\n};\n\nstruct IcuCursor {\n  sqlite3_tokenizer_cursor base;\n\n  UBreakIterator *pIter;      /* ICU break-iterator object */\n  int nChar;                  /* Number of UChar elements in pInput */\n  UChar *aChar;               /* Copy of input using utf-16 encoding */\n  int *aOffset;               /* Offsets of each character in utf-8 input */\n\n  int nBuffer;\n  char *zBuffer;\n\n  int iToken;\n};\n\n/*\n** Create a new tokenizer instance.\n*/\nstatic int icuCreate(\n  int argc,                            /* Number of entries in argv[] */\n  const char * const *argv,            /* Tokenizer creation arguments */\n  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */\n){\n  IcuTokenizer *p;\n  int n = 0;\n\n  if( argc>0 ){\n    n = strlen(argv[0])+1;\n  }\n  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);\n  if( !p ){\n    return SQLITE_NOMEM;\n  }\n  memset(p, 0, sizeof(IcuTokenizer));\n\n  if( n ){\n    p->zLocale = (char *)&p[1];\n    memcpy(p->zLocale, argv[0], n);\n  }\n\n  *ppTokenizer = (sqlite3_tokenizer *)p;\n\n  return SQLITE_OK;\n}\n\n/*\n** Destroy a tokenizer\n*/\nstatic int icuDestroy(sqlite3_tokenizer *pTokenizer){\n  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;\n  sqlite3_free(p);\n  return SQLITE_OK;\n}\n\n/*\n** Prepare to begin tokenizing a particular string.  The input\n** string to be tokenized is pInput[0..nBytes-1].  A cursor\n** used to incrementally tokenize this string is returned in \n** *ppCursor.\n*/\nstatic int icuOpen(\n  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */\n  const char *zInput,                    /* Input string */\n  int nInput,                            /* Length of zInput in bytes */\n  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */\n){\n  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;\n  IcuCursor *pCsr;\n\n  const int32_t opt = U_FOLD_CASE_DEFAULT;\n  UErrorCode status = U_ZERO_ERROR;\n  int nChar;\n\n  UChar32 c;\n  int iInput = 0;\n  int iOut = 0;\n\n  *ppCursor = 0;\n\n  if( zInput==0 ){\n    nInput = 0;\n    zInput = \"\";\n  }else if( nInput<0 ){\n    nInput = strlen(zInput);\n  }\n  nChar = nInput+1;\n  pCsr = (IcuCursor *)sqlite3_malloc(\n      sizeof(IcuCursor) +                /* IcuCursor */\n      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */\n      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */\n  );\n  if( !pCsr ){\n    return SQLITE_NOMEM;\n  }\n  memset(pCsr, 0, sizeof(IcuCursor));\n  pCsr->aChar = (UChar *)&pCsr[1];\n  pCsr->aOffset = (int *)&pCsr->aChar[nChar];\n\n  pCsr->aOffset[iOut] = iInput;\n  U8_NEXT(zInput, iInput, nInput, c); \n  while( c>0 ){\n    int isError = 0;\n    c = u_foldCase(c, opt);\n    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);\n    if( isError ){\n      sqlite3_free(pCsr);\n      return SQLITE_ERROR;\n    }\n    pCsr->aOffset[iOut] = iInput;\n\n    if( iInput<nInput ){\n      U8_NEXT(zInput, iInput, nInput, c);\n    }else{\n      c = 0;\n    }\n  }\n\n  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);\n  if( !U_SUCCESS(status) ){\n    sqlite3_free(pCsr);\n    return SQLITE_ERROR;\n  }\n  pCsr->nChar = iOut;\n\n  ubrk_first(pCsr->pIter);\n  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;\n  return SQLITE_OK;\n}\n\n/*\n** Close a tokenization cursor previously opened by a call to icuOpen().\n*/\nstatic int icuClose(sqlite3_tokenizer_cursor *pCursor){\n  IcuCursor *pCsr = (IcuCursor *)pCursor;\n  ubrk_close(pCsr->pIter);\n  sqlite3_free(pCsr->zBuffer);\n  sqlite3_free(pCsr);\n  return SQLITE_OK;\n}\n\n/*\n** Extract the next token from a tokenization cursor.\n*/\nstatic int icuNext(\n  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */\n  const char **ppToken,               /* OUT: *ppToken is the token text */\n  int *pnBytes,                       /* OUT: Number of bytes in token */\n  int *piStartOffset,                 /* OUT: Starting offset of token */\n  int *piEndOffset,                   /* OUT: Ending offset of token */\n  int *piPosition                     /* OUT: Position integer of token */\n){\n  IcuCursor *pCsr = (IcuCursor *)pCursor;\n\n  int iStart = 0;\n  int iEnd = 0;\n  int nByte = 0;\n\n  while( iStart==iEnd ){\n    UChar32 c;\n\n    iStart = ubrk_current(pCsr->pIter);\n    iEnd = ubrk_next(pCsr->pIter);\n    if( iEnd==UBRK_DONE ){\n      return SQLITE_DONE;\n    }\n\n    while( iStart<iEnd ){\n      int iWhite = iStart;\n      U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);\n      if( u_isspace(c) ){\n        iStart = iWhite;\n      }else{\n        break;\n      }\n    }\n    assert(iStart<=iEnd);\n  }\n\n  do {\n    UErrorCode status = U_ZERO_ERROR;\n    if( nByte ){\n      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);\n      if( !zNew ){\n        return SQLITE_NOMEM;\n      }\n      pCsr->zBuffer = zNew;\n      pCsr->nBuffer = nByte;\n    }\n\n    u_strToUTF8(\n        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */\n        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */\n        &status                                  /* Output success/failure */\n    );\n  } while( nByte>pCsr->nBuffer );\n\n  *ppToken = pCsr->zBuffer;\n  *pnBytes = nByte;\n  *piStartOffset = pCsr->aOffset[iStart];\n  *piEndOffset = pCsr->aOffset[iEnd];\n  *piPosition = pCsr->iToken++;\n\n  return SQLITE_OK;\n}\n\n/*\n** The set of routines that implement the simple tokenizer\n*/\nstatic const sqlite3_tokenizer_module icuTokenizerModule = {\n  0,                           /* iVersion */\n  icuCreate,                   /* xCreate  */\n  icuDestroy,                  /* xCreate  */\n  icuOpen,                     /* xOpen    */\n  icuClose,                    /* xClose   */\n  icuNext,                     /* xNext    */\n};\n\n/*\n** Set *ppModule to point at the implementation of the ICU tokenizer.\n*/\nSQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(\n  sqlite3_tokenizer_module const**ppModule\n){\n  *ppModule = &icuTokenizerModule;\n}\n\n#endif /* defined(SQLITE_ENABLE_ICU) */\n#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */\n\n/************** End of fts3_icu.c ********************************************/\n"
  },
  {
    "path": "plugins/iTunes/libs/sqlite3.h",
    "content": "/*\n** 2001 September 15\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n** This header file defines the interface that the SQLite library\n** presents to client programs.  If a C-function, structure, datatype,\n** or constant definition does not appear in this file, then it is\n** not a published API of SQLite, is subject to change without\n** notice, and should not be referenced by programs that use SQLite.\n**\n** Some of the definitions that are in this file are marked as\n** \"experimental\".  Experimental interfaces are normally new\n** features recently added to SQLite.  We do not anticipate changes\n** to experimental interfaces but reserve the right to make minor changes\n** if experience from use \"in the wild\" suggest such changes are prudent.\n**\n** The official C-language API documentation for SQLite is derived\n** from comments in this file.  This file is the authoritative source\n** on how SQLite interfaces are suppose to operate.\n**\n** The name of this file under configuration management is \"sqlite.h.in\".\n** The makefile makes some minor changes to this file (such as inserting\n** the version number) and changes its name to \"sqlite3.h\" as\n** part of the build process.\n*/\n#ifndef _SQLITE3_H_\n#define _SQLITE3_H_\n#include <stdarg.h>     /* Needed for the definition of va_list */\n\n/*\n** Make sure we can call this stuff from C++.\n*/\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n\n/*\n** Add the ability to override 'extern'\n*/\n#ifndef SQLITE_EXTERN\n# define SQLITE_EXTERN extern\n#endif\n\n#ifndef SQLITE_API\n# define SQLITE_API\n#endif\n\n\n/*\n** These no-op macros are used in front of interfaces to mark those\n** interfaces as either deprecated or experimental.  New applications\n** should not use deprecated interfaces - they are support for backwards\n** compatibility only.  Application writers should be aware that\n** experimental interfaces are subject to change in point releases.\n**\n** These macros used to resolve to various kinds of compiler magic that\n** would generate warning messages when they were used.  But that\n** compiler magic ended up generating such a flurry of bug reports\n** that we have taken it all out and gone back to using simple\n** noop macros.\n*/\n#define SQLITE_DEPRECATED\n#define SQLITE_EXPERIMENTAL\n\n/*\n** Ensure these symbols were not defined by some previous header file.\n*/\n#ifdef SQLITE_VERSION\n# undef SQLITE_VERSION\n#endif\n#ifdef SQLITE_VERSION_NUMBER\n# undef SQLITE_VERSION_NUMBER\n#endif\n\n/*\n** CAPI3REF: Compile-Time Library Version Numbers\n**\n** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header\n** evaluates to a string literal that is the SQLite version in the\n** format \"X.Y.Z\" where X is the major version number (always 3 for\n** SQLite3) and Y is the minor version number and Z is the release number.)^\n** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer\n** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same\n** numbers used in [SQLITE_VERSION].)^\n** The SQLITE_VERSION_NUMBER for any given release of SQLite will also\n** be larger than the release from which it is derived.  Either Y will\n** be held constant and Z will be incremented or else Y will be incremented\n** and Z will be reset to zero.\n**\n** Since version 3.6.18, SQLite source code has been stored in the\n** <a href=\"http://www.fossil-scm.org/\">Fossil configuration management\n** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to\n** a string which identifies a particular check-in of SQLite\n** within its configuration management system.  ^The SQLITE_SOURCE_ID\n** string contains the date and time of the check-in (UTC) and an SHA1\n** hash of the entire source tree.\n**\n** See also: [sqlite3_libversion()],\n** [sqlite3_libversion_number()], [sqlite3_sourceid()],\n** [sqlite_version()] and [sqlite_source_id()].\n*/\n#define SQLITE_VERSION        \"3.7.14.1\"\n#define SQLITE_VERSION_NUMBER 3007014\n#define SQLITE_SOURCE_ID      \"2012-10-04 19:37:12 091570e46d04e84b67228e0bdbcd6e1fb60c6bdb\"\n\n/*\n** CAPI3REF: Run-Time Library Version Numbers\n** KEYWORDS: sqlite3_version, sqlite3_sourceid\n**\n** These interfaces provide the same information as the [SQLITE_VERSION],\n** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros\n** but are associated with the library instead of the header file.  ^(Cautious\n** programmers might include assert() statements in their application to\n** verify that values returned by these interfaces match the macros in\n** the header, and thus insure that the application is\n** compiled with matching library and header files.\n**\n** <blockquote><pre>\n** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );\n** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );\n** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );\n** </pre></blockquote>)^\n**\n** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]\n** macro.  ^The sqlite3_libversion() function returns a pointer to the\n** to the sqlite3_version[] string constant.  The sqlite3_libversion()\n** function is provided for use in DLLs since DLL users usually do not have\n** direct access to string constants within the DLL.  ^The\n** sqlite3_libversion_number() function returns an integer equal to\n** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns \n** a pointer to a string constant whose value is the same as the \n** [SQLITE_SOURCE_ID] C preprocessor macro.\n**\n** See also: [sqlite_version()] and [sqlite_source_id()].\n*/\nSQLITE_API SQLITE_EXTERN const char sqlite3_version[];\nSQLITE_API const char *sqlite3_libversion(void);\nSQLITE_API const char *sqlite3_sourceid(void);\nSQLITE_API int sqlite3_libversion_number(void);\n\n/*\n** CAPI3REF: Run-Time Library Compilation Options Diagnostics\n**\n** ^The sqlite3_compileoption_used() function returns 0 or 1 \n** indicating whether the specified option was defined at \n** compile time.  ^The SQLITE_ prefix may be omitted from the \n** option name passed to sqlite3_compileoption_used().  \n**\n** ^The sqlite3_compileoption_get() function allows iterating\n** over the list of options that were defined at compile time by\n** returning the N-th compile time option string.  ^If N is out of range,\n** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ \n** prefix is omitted from any strings returned by \n** sqlite3_compileoption_get().\n**\n** ^Support for the diagnostic functions sqlite3_compileoption_used()\n** and sqlite3_compileoption_get() may be omitted by specifying the \n** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.\n**\n** See also: SQL functions [sqlite_compileoption_used()] and\n** [sqlite_compileoption_get()] and the [compile_options pragma].\n*/\n#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS\nSQLITE_API int sqlite3_compileoption_used(const char *zOptName);\nSQLITE_API const char *sqlite3_compileoption_get(int N);\n#endif\n\n/*\n** CAPI3REF: Test To See If The Library Is Threadsafe\n**\n** ^The sqlite3_threadsafe() function returns zero if and only if\n** SQLite was compiled with mutexing code omitted due to the\n** [SQLITE_THREADSAFE] compile-time option being set to 0.\n**\n** SQLite can be compiled with or without mutexes.  When\n** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes\n** are enabled and SQLite is threadsafe.  When the\n** [SQLITE_THREADSAFE] macro is 0, \n** the mutexes are omitted.  Without the mutexes, it is not safe\n** to use SQLite concurrently from more than one thread.\n**\n** Enabling mutexes incurs a measurable performance penalty.\n** So if speed is of utmost importance, it makes sense to disable\n** the mutexes.  But for maximum safety, mutexes should be enabled.\n** ^The default behavior is for mutexes to be enabled.\n**\n** This interface can be used by an application to make sure that the\n** version of SQLite that it is linking against was compiled with\n** the desired setting of the [SQLITE_THREADSAFE] macro.\n**\n** This interface only reports on the compile-time mutex setting\n** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with\n** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but\n** can be fully or partially disabled using a call to [sqlite3_config()]\n** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],\n** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the\n** sqlite3_threadsafe() function shows only the compile-time setting of\n** thread safety, not any run-time changes to that setting made by\n** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()\n** is unchanged by calls to sqlite3_config().)^\n**\n** See the [threading mode] documentation for additional information.\n*/\nSQLITE_API int sqlite3_threadsafe(void);\n\n/*\n** CAPI3REF: Database Connection Handle\n** KEYWORDS: {database connection} {database connections}\n**\n** Each open SQLite database is represented by a pointer to an instance of\n** the opaque structure named \"sqlite3\".  It is useful to think of an sqlite3\n** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and\n** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]\n** and [sqlite3_close_v2()] are its destructors.  There are many other\n** interfaces (such as\n** [sqlite3_prepare_v2()], [sqlite3_create_function()], and\n** [sqlite3_busy_timeout()] to name but three) that are methods on an\n** sqlite3 object.\n*/\ntypedef struct sqlite3 sqlite3;\n\n/*\n** CAPI3REF: 64-Bit Integer Types\n** KEYWORDS: sqlite_int64 sqlite_uint64\n**\n** Because there is no cross-platform way to specify 64-bit integer types\n** SQLite includes typedefs for 64-bit signed and unsigned integers.\n**\n** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.\n** The sqlite_int64 and sqlite_uint64 types are supported for backwards\n** compatibility only.\n**\n** ^The sqlite3_int64 and sqlite_int64 types can store integer values\n** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The\n** sqlite3_uint64 and sqlite_uint64 types can store integer values \n** between 0 and +18446744073709551615 inclusive.\n*/\n#ifdef SQLITE_INT64_TYPE\n  typedef SQLITE_INT64_TYPE sqlite_int64;\n  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;\n#elif defined(_MSC_VER) || defined(__BORLANDC__)\n  typedef __int64 sqlite_int64;\n  typedef unsigned __int64 sqlite_uint64;\n#else\n  typedef long long int sqlite_int64;\n  typedef unsigned long long int sqlite_uint64;\n#endif\ntypedef sqlite_int64 sqlite3_int64;\ntypedef sqlite_uint64 sqlite3_uint64;\n\n/*\n** If compiling for a processor that lacks floating point support,\n** substitute integer for floating-point.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# define double sqlite3_int64\n#endif\n\n/*\n** CAPI3REF: Closing A Database Connection\n**\n** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors\n** for the [sqlite3] object.\n** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if\n** the [sqlite3] object is successfully destroyed and all associated\n** resources are deallocated.\n**\n** ^If the database connection is associated with unfinalized prepared\n** statements or unfinished sqlite3_backup objects then sqlite3_close()\n** will leave the database connection open and return [SQLITE_BUSY].\n** ^If sqlite3_close_v2() is called with unfinalized prepared statements\n** and unfinished sqlite3_backups, then the database connection becomes\n** an unusable \"zombie\" which will automatically be deallocated when the\n** last prepared statement is finalized or the last sqlite3_backup is\n** finished.  The sqlite3_close_v2() interface is intended for use with\n** host languages that are garbage collected, and where the order in which\n** destructors are called is arbitrary.\n**\n** Applications should [sqlite3_finalize | finalize] all [prepared statements],\n** [sqlite3_blob_close | close] all [BLOB handles], and \n** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated\n** with the [sqlite3] object prior to attempting to close the object.  ^If\n** sqlite3_close() is called on a [database connection] that still has\n** outstanding [prepared statements], [BLOB handles], and/or\n** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation\n** of resources is deferred until all [prepared statements], [BLOB handles],\n** and [sqlite3_backup] objects are also destroyed.\n**\n** ^If an [sqlite3] object is destroyed while a transaction is open,\n** the transaction is automatically rolled back.\n**\n** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]\n** must be either a NULL\n** pointer or an [sqlite3] object pointer obtained\n** from [sqlite3_open()], [sqlite3_open16()], or\n** [sqlite3_open_v2()], and not previously closed.\n** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer\n** argument is a harmless no-op.\n*/\nSQLITE_API int sqlite3_close(sqlite3*);\nSQLITE_API int sqlite3_close_v2(sqlite3*);\n\n/*\n** The type for a callback function.\n** This is legacy and deprecated.  It is included for historical\n** compatibility and is not documented.\n*/\ntypedef int (*sqlite3_callback)(void*,int,char**, char**);\n\n/*\n** CAPI3REF: One-Step Query Execution Interface\n**\n** The sqlite3_exec() interface is a convenience wrapper around\n** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],\n** that allows an application to run multiple statements of SQL\n** without having to use a lot of C code. \n**\n** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,\n** semicolon-separate SQL statements passed into its 2nd argument,\n** in the context of the [database connection] passed in as its 1st\n** argument.  ^If the callback function of the 3rd argument to\n** sqlite3_exec() is not NULL, then it is invoked for each result row\n** coming out of the evaluated SQL statements.  ^The 4th argument to\n** sqlite3_exec() is relayed through to the 1st argument of each\n** callback invocation.  ^If the callback pointer to sqlite3_exec()\n** is NULL, then no callback is ever invoked and result rows are\n** ignored.\n**\n** ^If an error occurs while evaluating the SQL statements passed into\n** sqlite3_exec(), then execution of the current statement stops and\n** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()\n** is not NULL then any error message is written into memory obtained\n** from [sqlite3_malloc()] and passed back through the 5th parameter.\n** To avoid memory leaks, the application should invoke [sqlite3_free()]\n** on error message strings returned through the 5th parameter of\n** of sqlite3_exec() after the error message string is no longer needed.\n** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors\n** occur, then sqlite3_exec() sets the pointer in its 5th parameter to\n** NULL before returning.\n**\n** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()\n** routine returns SQLITE_ABORT without invoking the callback again and\n** without running any subsequent SQL statements.\n**\n** ^The 2nd argument to the sqlite3_exec() callback function is the\n** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()\n** callback is an array of pointers to strings obtained as if from\n** [sqlite3_column_text()], one for each column.  ^If an element of a\n** result row is NULL then the corresponding string pointer for the\n** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the\n** sqlite3_exec() callback is an array of pointers to strings where each\n** entry represents the name of corresponding result column as obtained\n** from [sqlite3_column_name()].\n**\n** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer\n** to an empty string, or a pointer that contains only whitespace and/or \n** SQL comments, then no SQL statements are evaluated and the database\n** is not changed.\n**\n** Restrictions:\n**\n** <ul>\n** <li> The application must insure that the 1st parameter to sqlite3_exec()\n**      is a valid and open [database connection].\n** <li> The application must not close [database connection] specified by\n**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.\n** <li> The application must not modify the SQL statement text passed into\n**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.\n** </ul>\n*/\nSQLITE_API int sqlite3_exec(\n  sqlite3*,                                  /* An open database */\n  const char *sql,                           /* SQL to be evaluated */\n  int (*callback)(void*,int,char**,char**),  /* Callback function */\n  void *,                                    /* 1st argument to callback */\n  char **errmsg                              /* Error msg written here */\n);\n\n/*\n** CAPI3REF: Result Codes\n** KEYWORDS: SQLITE_OK {error code} {error codes}\n** KEYWORDS: {result code} {result codes}\n**\n** Many SQLite functions return an integer result code from the set shown\n** here in order to indicate success or failure.\n**\n** New error codes may be added in future versions of SQLite.\n**\n** See also: [SQLITE_IOERR_READ | extended result codes],\n** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].\n*/\n#define SQLITE_OK           0   /* Successful result */\n/* beginning-of-error-codes */\n#define SQLITE_ERROR        1   /* SQL error or missing database */\n#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */\n#define SQLITE_PERM         3   /* Access permission denied */\n#define SQLITE_ABORT        4   /* Callback routine requested an abort */\n#define SQLITE_BUSY         5   /* The database file is locked */\n#define SQLITE_LOCKED       6   /* A table in the database is locked */\n#define SQLITE_NOMEM        7   /* A malloc() failed */\n#define SQLITE_READONLY     8   /* Attempt to write a readonly database */\n#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/\n#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */\n#define SQLITE_CORRUPT     11   /* The database disk image is malformed */\n#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */\n#define SQLITE_FULL        13   /* Insertion failed because database is full */\n#define SQLITE_CANTOPEN    14   /* Unable to open the database file */\n#define SQLITE_PROTOCOL    15   /* Database lock protocol error */\n#define SQLITE_EMPTY       16   /* Database is empty */\n#define SQLITE_SCHEMA      17   /* The database schema changed */\n#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */\n#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */\n#define SQLITE_MISMATCH    20   /* Data type mismatch */\n#define SQLITE_MISUSE      21   /* Library used incorrectly */\n#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */\n#define SQLITE_AUTH        23   /* Authorization denied */\n#define SQLITE_FORMAT      24   /* Auxiliary database format error */\n#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */\n#define SQLITE_NOTADB      26   /* File opened that is not a database file */\n#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */\n#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */\n/* end-of-error-codes */\n\n/*\n** CAPI3REF: Extended Result Codes\n** KEYWORDS: {extended error code} {extended error codes}\n** KEYWORDS: {extended result code} {extended result codes}\n**\n** In its default configuration, SQLite API routines return one of 26 integer\n** [SQLITE_OK | result codes].  However, experience has shown that many of\n** these result codes are too coarse-grained.  They do not provide as\n** much information about problems as programmers might like.  In an effort to\n** address this, newer versions of SQLite (version 3.3.8 and later) include\n** support for additional result codes that provide more detailed information\n** about errors. The extended result codes are enabled or disabled\n** on a per database connection basis using the\n** [sqlite3_extended_result_codes()] API.\n**\n** Some of the available extended result codes are listed here.\n** One may expect the number of extended result codes will be expand\n** over time.  Software that uses extended result codes should expect\n** to see new result codes in future releases of SQLite.\n**\n** The SQLITE_OK result code will never be extended.  It will always\n** be exactly zero.\n*/\n#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))\n#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))\n#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))\n#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))\n#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))\n#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))\n#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))\n#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))\n#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))\n#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))\n#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))\n#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))\n#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))\n#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))\n#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))\n#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))\n#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))\n#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))\n#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))\n#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))\n#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))\n#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))\n#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))\n#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))\n#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))\n#define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))\n#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))\n#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))\n#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))\n#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))\n\n/*\n** CAPI3REF: Flags For File Open Operations\n**\n** These bit values are intended for use in the\n** 3rd parameter to the [sqlite3_open_v2()] interface and\n** in the 4th parameter to the [sqlite3_vfs.xOpen] method.\n*/\n#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */\n#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */\n#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */\n#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */\n#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */\n#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */\n#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */\n#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */\n#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */\n#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */\n#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */\n#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */\n\n/* Reserved:                         0x00F00000 */\n\n/*\n** CAPI3REF: Device Characteristics\n**\n** The xDeviceCharacteristics method of the [sqlite3_io_methods]\n** object returns an integer which is a vector of these\n** bit values expressing I/O characteristics of the mass storage\n** device that holds the file that the [sqlite3_io_methods]\n** refers to.\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that\n** after reboot following a crash or power loss, the only bytes in a\n** file that were written at the application level might have changed\n** and that adjacent bytes, even bytes within the same sector are\n** guaranteed to be unchanged.\n*/\n#define SQLITE_IOCAP_ATOMIC                 0x00000001\n#define SQLITE_IOCAP_ATOMIC512              0x00000002\n#define SQLITE_IOCAP_ATOMIC1K               0x00000004\n#define SQLITE_IOCAP_ATOMIC2K               0x00000008\n#define SQLITE_IOCAP_ATOMIC4K               0x00000010\n#define SQLITE_IOCAP_ATOMIC8K               0x00000020\n#define SQLITE_IOCAP_ATOMIC16K              0x00000040\n#define SQLITE_IOCAP_ATOMIC32K              0x00000080\n#define SQLITE_IOCAP_ATOMIC64K              0x00000100\n#define SQLITE_IOCAP_SAFE_APPEND            0x00000200\n#define SQLITE_IOCAP_SEQUENTIAL             0x00000400\n#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800\n#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000\n\n/*\n** CAPI3REF: File Locking Levels\n**\n** SQLite uses one of these integer values as the second\n** argument to calls it makes to the xLock() and xUnlock() methods\n** of an [sqlite3_io_methods] object.\n*/\n#define SQLITE_LOCK_NONE          0\n#define SQLITE_LOCK_SHARED        1\n#define SQLITE_LOCK_RESERVED      2\n#define SQLITE_LOCK_PENDING       3\n#define SQLITE_LOCK_EXCLUSIVE     4\n\n/*\n** CAPI3REF: Synchronization Type Flags\n**\n** When SQLite invokes the xSync() method of an\n** [sqlite3_io_methods] object it uses a combination of\n** these integer values as the second argument.\n**\n** When the SQLITE_SYNC_DATAONLY flag is used, it means that the\n** sync operation only needs to flush data to mass storage.  Inode\n** information need not be flushed. If the lower four bits of the flag\n** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.\n** If the lower four bits equal SQLITE_SYNC_FULL, that means\n** to use Mac OS X style fullsync instead of fsync().\n**\n** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags\n** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL\n** settings.  The [synchronous pragma] determines when calls to the\n** xSync VFS method occur and applies uniformly across all platforms.\n** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how\n** energetic or rigorous or forceful the sync operations are and\n** only make a difference on Mac OSX for the default SQLite code.\n** (Third-party VFS implementations might also make the distinction\n** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the\n** operating systems natively supported by SQLite, only Mac OSX\n** cares about the difference.)\n*/\n#define SQLITE_SYNC_NORMAL        0x00002\n#define SQLITE_SYNC_FULL          0x00003\n#define SQLITE_SYNC_DATAONLY      0x00010\n\n/*\n** CAPI3REF: OS Interface Open File Handle\n**\n** An [sqlite3_file] object represents an open file in the \n** [sqlite3_vfs | OS interface layer].  Individual OS interface\n** implementations will\n** want to subclass this object by appending additional fields\n** for their own use.  The pMethods entry is a pointer to an\n** [sqlite3_io_methods] object that defines methods for performing\n** I/O operations on the open file.\n*/\ntypedef struct sqlite3_file sqlite3_file;\nstruct sqlite3_file {\n  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */\n};\n\n/*\n** CAPI3REF: OS Interface File Virtual Methods Object\n**\n** Every file opened by the [sqlite3_vfs.xOpen] method populates an\n** [sqlite3_file] object (or, more commonly, a subclass of the\n** [sqlite3_file] object) with a pointer to an instance of this object.\n** This object defines the methods used to perform various operations\n** against the open file represented by the [sqlite3_file] object.\n**\n** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element \n** to a non-NULL pointer, then the sqlite3_io_methods.xClose method\n** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The\n** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]\n** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element\n** to NULL.\n**\n** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or\n** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().\n** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]\n** flag may be ORed in to indicate that only the data of the file\n** and not its inode needs to be synced.\n**\n** The integer values to xLock() and xUnlock() are one of\n** <ul>\n** <li> [SQLITE_LOCK_NONE],\n** <li> [SQLITE_LOCK_SHARED],\n** <li> [SQLITE_LOCK_RESERVED],\n** <li> [SQLITE_LOCK_PENDING], or\n** <li> [SQLITE_LOCK_EXCLUSIVE].\n** </ul>\n** xLock() increases the lock. xUnlock() decreases the lock.\n** The xCheckReservedLock() method checks whether any database connection,\n** either in this process or in some other process, is holding a RESERVED,\n** PENDING, or EXCLUSIVE lock on the file.  It returns true\n** if such a lock exists and false otherwise.\n**\n** The xFileControl() method is a generic interface that allows custom\n** VFS implementations to directly control an open file using the\n** [sqlite3_file_control()] interface.  The second \"op\" argument is an\n** integer opcode.  The third argument is a generic pointer intended to\n** point to a structure that may contain arguments or space in which to\n** write return values.  Potential uses for xFileControl() might be\n** functions to enable blocking locks with timeouts, to change the\n** locking strategy (for example to use dot-file locks), to inquire\n** about the status of a lock, or to break stale locks.  The SQLite\n** core reserves all opcodes less than 100 for its own use.\n** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.\n** Applications that define a custom xFileControl method should use opcodes\n** greater than 100 to avoid conflicts.  VFS implementations should\n** return [SQLITE_NOTFOUND] for file control opcodes that they do not\n** recognize.\n**\n** The xSectorSize() method returns the sector size of the\n** device that underlies the file.  The sector size is the\n** minimum write that can be performed without disturbing\n** other bytes in the file.  The xDeviceCharacteristics()\n** method returns a bit vector describing behaviors of the\n** underlying device:\n**\n** <ul>\n** <li> [SQLITE_IOCAP_ATOMIC]\n** <li> [SQLITE_IOCAP_ATOMIC512]\n** <li> [SQLITE_IOCAP_ATOMIC1K]\n** <li> [SQLITE_IOCAP_ATOMIC2K]\n** <li> [SQLITE_IOCAP_ATOMIC4K]\n** <li> [SQLITE_IOCAP_ATOMIC8K]\n** <li> [SQLITE_IOCAP_ATOMIC16K]\n** <li> [SQLITE_IOCAP_ATOMIC32K]\n** <li> [SQLITE_IOCAP_ATOMIC64K]\n** <li> [SQLITE_IOCAP_SAFE_APPEND]\n** <li> [SQLITE_IOCAP_SEQUENTIAL]\n** </ul>\n**\n** The SQLITE_IOCAP_ATOMIC property means that all writes of\n** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values\n** mean that writes of blocks that are nnn bytes in size and\n** are aligned to an address which is an integer multiple of\n** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means\n** that when data is appended to a file, the data is appended\n** first then the size of the file is extended, never the other\n** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that\n** information is written to disk in the same order as calls\n** to xWrite().\n**\n** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill\n** in the unread portions of the buffer with zeros.  A VFS that\n** fails to zero-fill short reads might seem to work.  However,\n** failure to zero-fill short reads will eventually lead to\n** database corruption.\n*/\ntypedef struct sqlite3_io_methods sqlite3_io_methods;\nstruct sqlite3_io_methods {\n  int iVersion;\n  int (*xClose)(sqlite3_file*);\n  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);\n  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);\n  int (*xSync)(sqlite3_file*, int flags);\n  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);\n  int (*xLock)(sqlite3_file*, int);\n  int (*xUnlock)(sqlite3_file*, int);\n  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);\n  int (*xFileControl)(sqlite3_file*, int op, void *pArg);\n  int (*xSectorSize)(sqlite3_file*);\n  int (*xDeviceCharacteristics)(sqlite3_file*);\n  /* Methods above are valid for version 1 */\n  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);\n  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);\n  void (*xShmBarrier)(sqlite3_file*);\n  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);\n  /* Methods above are valid for version 2 */\n  /* Additional methods may be added in future releases */\n};\n\n/*\n** CAPI3REF: Standard File Control Opcodes\n**\n** These integer constants are opcodes for the xFileControl method\n** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]\n** interface.\n**\n** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This\n** opcode causes the xFileControl method to write the current state of\n** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],\n** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])\n** into an integer that the pArg argument points to. This capability\n** is used during testing and only needs to be supported when SQLITE_TEST\n** is defined.\n** <ul>\n** <li>[[SQLITE_FCNTL_SIZE_HINT]]\n** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS\n** layer a hint of how large the database file will grow to be during the\n** current transaction.  This hint is not guaranteed to be accurate but it\n** is often close.  The underlying VFS might choose to preallocate database\n** file space based on this hint in order to help writes to the database\n** file run faster.\n**\n** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]\n** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS\n** extends and truncates the database file in chunks of a size specified\n** by the user. The fourth argument to [sqlite3_file_control()] should \n** point to an integer (type int) containing the new chunk-size to use\n** for the nominated database. Allocating database file space in large\n** chunks (say 1MB at a time), may reduce file-system fragmentation and\n** improve performance on some systems.\n**\n** <li>[[SQLITE_FCNTL_FILE_POINTER]]\n** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer\n** to the [sqlite3_file] object associated with a particular database\n** connection.  See the [sqlite3_file_control()] documentation for\n** additional information.\n**\n** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]\n** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by\n** SQLite and sent to all VFSes in place of a call to the xSync method\n** when the database connection has [PRAGMA synchronous] set to OFF.)^\n** Some specialized VFSes need this signal in order to operate correctly\n** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most \n** VFSes do not need this signal and should silently ignore this opcode.\n** Applications should not call [sqlite3_file_control()] with this\n** opcode as doing so may disrupt the operation of the specialized VFSes\n** that do require it.  \n**\n** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]\n** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic\n** retry counts and intervals for certain disk I/O operations for the\n** windows [VFS] in order to provide robustness in the presence of\n** anti-virus programs.  By default, the windows VFS will retry file read,\n** file write, and file delete operations up to 10 times, with a delay\n** of 25 milliseconds before the first retry and with the delay increasing\n** by an additional 25 milliseconds with each subsequent retry.  This\n** opcode allows these two values (10 retries and 25 milliseconds of delay)\n** to be adjusted.  The values are changed for all database connections\n** within the same process.  The argument is a pointer to an array of two\n** integers where the first integer i the new retry count and the second\n** integer is the delay.  If either integer is negative, then the setting\n** is not changed but instead the prior value of that setting is written\n** into the array entry, allowing the current retry settings to be\n** interrogated.  The zDbName parameter is ignored.\n**\n** <li>[[SQLITE_FCNTL_PERSIST_WAL]]\n** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the\n** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary\n** write ahead log and shared memory files used for transaction control\n** are automatically deleted when the latest connection to the database\n** closes.  Setting persistent WAL mode causes those files to persist after\n** close.  Persisting the files is useful when other processes that do not\n** have write permission on the directory containing the database file want\n** to read the database file, as the WAL and shared memory files must exist\n** in order for the database to be readable.  The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable persistent WAL mode or 1 to enable persistent\n** WAL mode.  If the integer is -1, then it is overwritten with the current\n** WAL persistence setting.\n**\n** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]\n** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the\n** persistent \"powersafe-overwrite\" or \"PSOW\" setting.  The PSOW setting\n** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the\n** xDeviceCharacteristics methods. The fourth parameter to\n** [sqlite3_file_control()] for this opcode should be a pointer to an integer.\n** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage\n** mode.  If the integer is -1, then it is overwritten with the current\n** zero-damage mode setting.\n**\n** <li>[[SQLITE_FCNTL_OVERWRITE]]\n** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening\n** a write transaction to indicate that, unless it is rolled back for some\n** reason, the entire database file will be overwritten by the current \n** transaction. This is used by VACUUM operations.\n**\n** <li>[[SQLITE_FCNTL_VFSNAME]]\n** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of\n** all [VFSes] in the VFS stack.  The names are of all VFS shims and the\n** final bottom-level VFS are written into memory obtained from \n** [sqlite3_malloc()] and the result is stored in the char* variable\n** that the fourth parameter of [sqlite3_file_control()] points to.\n** The caller is responsible for freeing the memory when done.  As with\n** all file-control actions, there is no guarantee that this will actually\n** do anything.  Callers should initialize the char* variable to a NULL\n** pointer in case this file-control is not implemented.  This file-control\n** is intended for diagnostic use only.\n**\n** <li>[[SQLITE_FCNTL_PRAGMA]]\n** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] \n** file control is sent to the open [sqlite3_file] object corresponding\n** to the database file to which the pragma statement refers. ^The argument\n** to the [SQLITE_FCNTL_PRAGMA] file control is an array of\n** pointers to strings (char**) in which the second element of the array\n** is the name of the pragma and the third element is the argument to the\n** pragma or NULL if the pragma has no argument.  ^The handler for an\n** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element\n** of the char** argument point to a string obtained from [sqlite3_mprintf()]\n** or the equivalent and that string will become the result of the pragma or\n** the error message if the pragma fails. ^If the\n** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal \n** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]\n** file control returns [SQLITE_OK], then the parser assumes that the\n** VFS has handled the PRAGMA itself and the parser generates a no-op\n** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns\n** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means\n** that the VFS encountered an error while handling the [PRAGMA] and the\n** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]\n** file control occurs at the beginning of pragma statement analysis and so\n** it is able to override built-in [PRAGMA] statements.\n** </ul>\n*/\n#define SQLITE_FCNTL_LOCKSTATE               1\n#define SQLITE_GET_LOCKPROXYFILE             2\n#define SQLITE_SET_LOCKPROXYFILE             3\n#define SQLITE_LAST_ERRNO                    4\n#define SQLITE_FCNTL_SIZE_HINT               5\n#define SQLITE_FCNTL_CHUNK_SIZE              6\n#define SQLITE_FCNTL_FILE_POINTER            7\n#define SQLITE_FCNTL_SYNC_OMITTED            8\n#define SQLITE_FCNTL_WIN32_AV_RETRY          9\n#define SQLITE_FCNTL_PERSIST_WAL            10\n#define SQLITE_FCNTL_OVERWRITE              11\n#define SQLITE_FCNTL_VFSNAME                12\n#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13\n#define SQLITE_FCNTL_PRAGMA                 14\n\n/*\n** CAPI3REF: Mutex Handle\n**\n** The mutex module within SQLite defines [sqlite3_mutex] to be an\n** abstract type for a mutex object.  The SQLite core never looks\n** at the internal representation of an [sqlite3_mutex].  It only\n** deals with pointers to the [sqlite3_mutex] object.\n**\n** Mutexes are created using [sqlite3_mutex_alloc()].\n*/\ntypedef struct sqlite3_mutex sqlite3_mutex;\n\n/*\n** CAPI3REF: OS Interface Object\n**\n** An instance of the sqlite3_vfs object defines the interface between\n** the SQLite core and the underlying operating system.  The \"vfs\"\n** in the name of the object stands for \"virtual file system\".  See\n** the [VFS | VFS documentation] for further information.\n**\n** The value of the iVersion field is initially 1 but may be larger in\n** future versions of SQLite.  Additional fields may be appended to this\n** object when the iVersion value is increased.  Note that the structure\n** of the sqlite3_vfs object changes in the transaction between\n** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not\n** modified.\n**\n** The szOsFile field is the size of the subclassed [sqlite3_file]\n** structure used by this VFS.  mxPathname is the maximum length of\n** a pathname in this VFS.\n**\n** Registered sqlite3_vfs objects are kept on a linked list formed by\n** the pNext pointer.  The [sqlite3_vfs_register()]\n** and [sqlite3_vfs_unregister()] interfaces manage this list\n** in a thread-safe way.  The [sqlite3_vfs_find()] interface\n** searches the list.  Neither the application code nor the VFS\n** implementation should use the pNext pointer.\n**\n** The pNext field is the only field in the sqlite3_vfs\n** structure that SQLite will ever modify.  SQLite will only access\n** or modify this field while holding a particular static mutex.\n** The application should never modify anything within the sqlite3_vfs\n** object once the object has been registered.\n**\n** The zName field holds the name of the VFS module.  The name must\n** be unique across all VFS modules.\n**\n** [[sqlite3_vfs.xOpen]]\n** ^SQLite guarantees that the zFilename parameter to xOpen\n** is either a NULL pointer or string obtained\n** from xFullPathname() with an optional suffix added.\n** ^If a suffix is added to the zFilename parameter, it will\n** consist of a single \"-\" character followed by no more than\n** 11 alphanumeric and/or \"-\" characters.\n** ^SQLite further guarantees that\n** the string will be valid and unchanged until xClose() is\n** called. Because of the previous sentence,\n** the [sqlite3_file] can safely store a pointer to the\n** filename if it needs to remember the filename for some reason.\n** If the zFilename parameter to xOpen is a NULL pointer then xOpen\n** must invent its own temporary name for the file.  ^Whenever the \n** xFilename parameter is NULL it will also be the case that the\n** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].\n**\n** The flags argument to xOpen() includes all bits set in\n** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]\n** or [sqlite3_open16()] is used, then flags includes at least\n** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. \n** If xOpen() opens a file read-only then it sets *pOutFlags to\n** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.\n**\n** ^(SQLite will also add one of the following flags to the xOpen()\n** call, depending on the object being opened:\n**\n** <ul>\n** <li>  [SQLITE_OPEN_MAIN_DB]\n** <li>  [SQLITE_OPEN_MAIN_JOURNAL]\n** <li>  [SQLITE_OPEN_TEMP_DB]\n** <li>  [SQLITE_OPEN_TEMP_JOURNAL]\n** <li>  [SQLITE_OPEN_TRANSIENT_DB]\n** <li>  [SQLITE_OPEN_SUBJOURNAL]\n** <li>  [SQLITE_OPEN_MASTER_JOURNAL]\n** <li>  [SQLITE_OPEN_WAL]\n** </ul>)^\n**\n** The file I/O implementation can use the object type flags to\n** change the way it deals with files.  For example, an application\n** that does not care about crash recovery or rollback might make\n** the open of a journal file a no-op.  Writes to this journal would\n** also be no-ops, and any attempt to read the journal would return\n** SQLITE_IOERR.  Or the implementation might recognize that a database\n** file will be doing page-aligned sector reads and writes in a random\n** order and set up its I/O subsystem accordingly.\n**\n** SQLite might also add one of the following flags to the xOpen method:\n**\n** <ul>\n** <li> [SQLITE_OPEN_DELETEONCLOSE]\n** <li> [SQLITE_OPEN_EXCLUSIVE]\n** </ul>\n**\n** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be\n** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]\n** will be set for TEMP databases and their journals, transient\n** databases, and subjournals.\n**\n** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction\n** with the [SQLITE_OPEN_CREATE] flag, which are both directly\n** analogous to the O_EXCL and O_CREAT flags of the POSIX open()\n** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the \n** SQLITE_OPEN_CREATE, is used to indicate that file should always\n** be created, and that it is an error if it already exists.\n** It is <i>not</i> used to indicate the file should be opened \n** for exclusive access.\n**\n** ^At least szOsFile bytes of memory are allocated by SQLite\n** to hold the  [sqlite3_file] structure passed as the third\n** argument to xOpen.  The xOpen method does not have to\n** allocate the structure; it should just fill it in.  Note that\n** the xOpen method must set the sqlite3_file.pMethods to either\n** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do\n** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods\n** element will be valid after xOpen returns regardless of the success\n** or failure of the xOpen call.\n**\n** [[sqlite3_vfs.xAccess]]\n** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]\n** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to\n** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]\n** to test whether a file is at least readable.   The file can be a\n** directory.\n**\n** ^SQLite will always allocate at least mxPathname+1 bytes for the\n** output buffer xFullPathname.  The exact size of the output buffer\n** is also passed as a parameter to both  methods. If the output buffer\n** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is\n** handled as a fatal error by SQLite, vfs implementations should endeavor\n** to prevent this by setting mxPathname to a sufficiently large value.\n**\n** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()\n** interfaces are not strictly a part of the filesystem, but they are\n** included in the VFS structure for completeness.\n** The xRandomness() function attempts to return nBytes bytes\n** of good-quality randomness into zOut.  The return value is\n** the actual number of bytes of randomness obtained.\n** The xSleep() method causes the calling thread to sleep for at\n** least the number of microseconds given.  ^The xCurrentTime()\n** method returns a Julian Day Number for the current date and time as\n** a floating point value.\n** ^The xCurrentTimeInt64() method returns, as an integer, the Julian\n** Day Number multiplied by 86400000 (the number of milliseconds in \n** a 24-hour day).  \n** ^SQLite will use the xCurrentTimeInt64() method to get the current\n** date and time if that method is available (if iVersion is 2 or \n** greater and the function pointer is not NULL) and will fall back\n** to xCurrentTime() if xCurrentTimeInt64() is unavailable.\n**\n** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces\n** are not used by the SQLite core.  These optional interfaces are provided\n** by some VFSes to facilitate testing of the VFS code. By overriding \n** system calls with functions under its control, a test program can\n** simulate faults and error conditions that would otherwise be difficult\n** or impossible to induce.  The set of system calls that can be overridden\n** varies from one VFS to another, and from one version of the same VFS to the\n** next.  Applications that use these interfaces must be prepared for any\n** or all of these interfaces to be NULL or for their behavior to change\n** from one release to the next.  Applications must not attempt to access\n** any of these methods if the iVersion of the VFS is less than 3.\n*/\ntypedef struct sqlite3_vfs sqlite3_vfs;\ntypedef void (*sqlite3_syscall_ptr)(void);\nstruct sqlite3_vfs {\n  int iVersion;            /* Structure version number (currently 3) */\n  int szOsFile;            /* Size of subclassed sqlite3_file */\n  int mxPathname;          /* Maximum file pathname length */\n  sqlite3_vfs *pNext;      /* Next registered VFS */\n  const char *zName;       /* Name of this virtual file system */\n  void *pAppData;          /* Pointer to application-specific data */\n  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,\n               int flags, int *pOutFlags);\n  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);\n  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);\n  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);\n  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);\n  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);\n  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);\n  void (*xDlClose)(sqlite3_vfs*, void*);\n  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);\n  int (*xSleep)(sqlite3_vfs*, int microseconds);\n  int (*xCurrentTime)(sqlite3_vfs*, double*);\n  int (*xGetLastError)(sqlite3_vfs*, int, char *);\n  /*\n  ** The methods above are in version 1 of the sqlite_vfs object\n  ** definition.  Those that follow are added in version 2 or later\n  */\n  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);\n  /*\n  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.\n  ** Those below are for version 3 and greater.\n  */\n  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);\n  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);\n  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);\n  /*\n  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.\n  ** New fields may be appended in figure versions.  The iVersion\n  ** value will increment whenever this happens. \n  */\n};\n\n/*\n** CAPI3REF: Flags for the xAccess VFS method\n**\n** These integer constants can be used as the third parameter to\n** the xAccess method of an [sqlite3_vfs] object.  They determine\n** what kind of permissions the xAccess method is looking for.\n** With SQLITE_ACCESS_EXISTS, the xAccess method\n** simply checks whether the file exists.\n** With SQLITE_ACCESS_READWRITE, the xAccess method\n** checks whether the named directory is both readable and writable\n** (in other words, if files can be added, removed, and renamed within\n** the directory).\n** The SQLITE_ACCESS_READWRITE constant is currently used only by the\n** [temp_store_directory pragma], though this could change in a future\n** release of SQLite.\n** With SQLITE_ACCESS_READ, the xAccess method\n** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is\n** currently unused, though it might be used in a future release of\n** SQLite.\n*/\n#define SQLITE_ACCESS_EXISTS    0\n#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */\n#define SQLITE_ACCESS_READ      2   /* Unused */\n\n/*\n** CAPI3REF: Flags for the xShmLock VFS method\n**\n** These integer constants define the various locking operations\n** allowed by the xShmLock method of [sqlite3_io_methods].  The\n** following are the only legal combinations of flags to the\n** xShmLock method:\n**\n** <ul>\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED\n** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE\n** </ul>\n**\n** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as\n** was given no the corresponding lock.  \n**\n** The xShmLock method can transition between unlocked and SHARED or\n** between unlocked and EXCLUSIVE.  It cannot transition between SHARED\n** and EXCLUSIVE.\n*/\n#define SQLITE_SHM_UNLOCK       1\n#define SQLITE_SHM_LOCK         2\n#define SQLITE_SHM_SHARED       4\n#define SQLITE_SHM_EXCLUSIVE    8\n\n/*\n** CAPI3REF: Maximum xShmLock index\n**\n** The xShmLock method on [sqlite3_io_methods] may use values\n** between 0 and this upper bound as its \"offset\" argument.\n** The SQLite core will never attempt to acquire or release a\n** lock outside of this range\n*/\n#define SQLITE_SHM_NLOCK        8\n\n\n/*\n** CAPI3REF: Initialize The SQLite Library\n**\n** ^The sqlite3_initialize() routine initializes the\n** SQLite library.  ^The sqlite3_shutdown() routine\n** deallocates any resources that were allocated by sqlite3_initialize().\n** These routines are designed to aid in process initialization and\n** shutdown on embedded systems.  Workstation applications using\n** SQLite normally do not need to invoke either of these routines.\n**\n** A call to sqlite3_initialize() is an \"effective\" call if it is\n** the first time sqlite3_initialize() is invoked during the lifetime of\n** the process, or if it is the first time sqlite3_initialize() is invoked\n** following a call to sqlite3_shutdown().  ^(Only an effective call\n** of sqlite3_initialize() does any initialization.  All other calls\n** are harmless no-ops.)^\n**\n** A call to sqlite3_shutdown() is an \"effective\" call if it is the first\n** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only\n** an effective call to sqlite3_shutdown() does any deinitialization.\n** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^\n**\n** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()\n** is not.  The sqlite3_shutdown() interface must only be called from a\n** single thread.  All open [database connections] must be closed and all\n** other SQLite resources must be deallocated prior to invoking\n** sqlite3_shutdown().\n**\n** Among other things, ^sqlite3_initialize() will invoke\n** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()\n** will invoke sqlite3_os_end().\n**\n** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.\n** ^If for some reason, sqlite3_initialize() is unable to initialize\n** the library (perhaps it is unable to allocate a needed resource such\n** as a mutex) it returns an [error code] other than [SQLITE_OK].\n**\n** ^The sqlite3_initialize() routine is called internally by many other\n** SQLite interfaces so that an application usually does not need to\n** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]\n** calls sqlite3_initialize() so the SQLite library will be automatically\n** initialized when [sqlite3_open()] is called if it has not be initialized\n** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]\n** compile-time option, then the automatic calls to sqlite3_initialize()\n** are omitted and the application must call sqlite3_initialize() directly\n** prior to using any other SQLite interface.  For maximum portability,\n** it is recommended that applications always invoke sqlite3_initialize()\n** directly prior to using any other SQLite interface.  Future releases\n** of SQLite may require this.  In other words, the behavior exhibited\n** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the\n** default behavior in some future release of SQLite.\n**\n** The sqlite3_os_init() routine does operating-system specific\n** initialization of the SQLite library.  The sqlite3_os_end()\n** routine undoes the effect of sqlite3_os_init().  Typical tasks\n** performed by these routines include allocation or deallocation\n** of static resources, initialization of global variables,\n** setting up a default [sqlite3_vfs] module, or setting up\n** a default configuration using [sqlite3_config()].\n**\n** The application should never invoke either sqlite3_os_init()\n** or sqlite3_os_end() directly.  The application should only invoke\n** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()\n** interface is called automatically by sqlite3_initialize() and\n** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate\n** implementations for sqlite3_os_init() and sqlite3_os_end()\n** are built into SQLite when it is compiled for Unix, Windows, or OS/2.\n** When [custom builds | built for other platforms]\n** (using the [SQLITE_OS_OTHER=1] compile-time\n** option) the application must supply a suitable implementation for\n** sqlite3_os_init() and sqlite3_os_end().  An application-supplied\n** implementation of sqlite3_os_init() or sqlite3_os_end()\n** must return [SQLITE_OK] on success and some other [error code] upon\n** failure.\n*/\nSQLITE_API int sqlite3_initialize(void);\nSQLITE_API int sqlite3_shutdown(void);\nSQLITE_API int sqlite3_os_init(void);\nSQLITE_API int sqlite3_os_end(void);\n\n/*\n** CAPI3REF: Configuring The SQLite Library\n**\n** The sqlite3_config() interface is used to make global configuration\n** changes to SQLite in order to tune SQLite to the specific needs of\n** the application.  The default configuration is recommended for most\n** applications and so this routine is usually not necessary.  It is\n** provided to support rare applications with unusual needs.\n**\n** The sqlite3_config() interface is not threadsafe.  The application\n** must insure that no other SQLite interfaces are invoked by other\n** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()\n** may only be invoked prior to library initialization using\n** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].\n** ^If sqlite3_config() is called after [sqlite3_initialize()] and before\n** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.\n** Note, however, that ^sqlite3_config() can be called as part of the\n** implementation of an application-defined [sqlite3_os_init()].\n**\n** The first argument to sqlite3_config() is an integer\n** [configuration option] that determines\n** what property of SQLite is to be configured.  Subsequent arguments\n** vary depending on the [configuration option]\n** in the first argument.\n**\n** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].\n** ^If the option is unknown or SQLite is unable to set the option\n** then this routine returns a non-zero [error code].\n*/\nSQLITE_API int sqlite3_config(int, ...);\n\n/*\n** CAPI3REF: Configure database connections\n**\n** The sqlite3_db_config() interface is used to make configuration\n** changes to a [database connection].  The interface is similar to\n** [sqlite3_config()] except that the changes apply to a single\n** [database connection] (specified in the first argument).\n**\n** The second argument to sqlite3_db_config(D,V,...)  is the\n** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code \n** that indicates what aspect of the [database connection] is being configured.\n** Subsequent arguments vary depending on the configuration verb.\n**\n** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if\n** the call is considered successful.\n*/\nSQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Memory Allocation Routines\n**\n** An instance of this object defines the interface between SQLite\n** and low-level memory allocation routines.\n**\n** This object is used in only one place in the SQLite interface.\n** A pointer to an instance of this object is the argument to\n** [sqlite3_config()] when the configuration option is\n** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  \n** By creating an instance of this object\n** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])\n** during configuration, an application can specify an alternative\n** memory allocation subsystem for SQLite to use for all of its\n** dynamic memory needs.\n**\n** Note that SQLite comes with several [built-in memory allocators]\n** that are perfectly adequate for the overwhelming majority of applications\n** and that this object is only useful to a tiny minority of applications\n** with specialized memory allocation requirements.  This object is\n** also used during testing of SQLite in order to specify an alternative\n** memory allocator that simulates memory out-of-memory conditions in\n** order to verify that SQLite recovers gracefully from such\n** conditions.\n**\n** The xMalloc, xRealloc, and xFree methods must work like the\n** malloc(), realloc() and free() functions from the standard C library.\n** ^SQLite guarantees that the second argument to\n** xRealloc is always a value returned by a prior call to xRoundup.\n**\n** xSize should return the allocated size of a memory allocation\n** previously obtained from xMalloc or xRealloc.  The allocated size\n** is always at least as big as the requested size but may be larger.\n**\n** The xRoundup method returns what would be the allocated size of\n** a memory allocation given a particular requested size.  Most memory\n** allocators round up memory allocations at least to the next multiple\n** of 8.  Some allocators round up to a larger multiple or to a power of 2.\n** Every memory allocation request coming in through [sqlite3_malloc()]\n** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, \n** that causes the corresponding memory allocation to fail.\n**\n** The xInit method initializes the memory allocator.  (For example,\n** it might allocate any require mutexes or initialize internal data\n** structures.  The xShutdown method is invoked (indirectly) by\n** [sqlite3_shutdown()] and should deallocate any resources acquired\n** by xInit.  The pAppData pointer is used as the only parameter to\n** xInit and xShutdown.\n**\n** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes\n** the xInit method, so the xInit method need not be threadsafe.  The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  For all other methods, SQLite\n** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the\n** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which\n** it is by default) and so the methods are automatically serialized.\n** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other\n** methods must be threadsafe or else make their own arrangements for\n** serialization.\n**\n** SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n*/\ntypedef struct sqlite3_mem_methods sqlite3_mem_methods;\nstruct sqlite3_mem_methods {\n  void *(*xMalloc)(int);         /* Memory allocation function */\n  void (*xFree)(void*);          /* Free a prior allocation */\n  void *(*xRealloc)(void*,int);  /* Resize an allocation */\n  int (*xSize)(void*);           /* Return the size of an allocation */\n  int (*xRoundup)(int);          /* Round up request size to allocation size */\n  int (*xInit)(void*);           /* Initialize the memory allocator */\n  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */\n  void *pAppData;                /* Argument to xInit() and xShutdown() */\n};\n\n/*\n** CAPI3REF: Configuration Options\n** KEYWORDS: {configuration option}\n**\n** These constants are the available integer configuration options that\n** can be passed as the first argument to the [sqlite3_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_config()] to make sure that\n** the call worked.  The [sqlite3_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Single-thread.  In other words, it disables\n** all mutexing and puts SQLite into a mode where it can only be used\n** by a single thread.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to change the [threading mode] from its default\n** value of Single-thread and so [sqlite3_config()] will return \n** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD\n** configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Multi-thread.  In other words, it disables\n** mutexing on [database connection] and [prepared statement] objects.\n** The application is responsible for serializing access to\n** [database connections] and [prepared statements].  But other mutexes\n** are enabled so that SQLite will be safe to use in a multi-threaded\n** environment as long as no two threads attempt to use the same\n** [database connection] at the same time.  ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Multi-thread [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>\n**\n** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>\n** <dd>There are no arguments to this option.  ^This option sets the\n** [threading mode] to Serialized. In other words, this option enables\n** all mutexes including the recursive\n** mutexes on [database connection] and [prepared statement] objects.\n** In this mode (which is the default when SQLite is compiled with\n** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access\n** to [database connections] and [prepared statements] so that the\n** application is free to use the same [database connection] or the\n** same [prepared statement] in different threads at the same time.\n** ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** it is not possible to set the Serialized [threading mode] and\n** [sqlite3_config()] will return [SQLITE_ERROR] if called with the\n** SQLITE_CONFIG_SERIALIZED configuration option.</dd>\n**\n** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mem_methods] structure.  The argument specifies\n** alternative low-level memory allocation routines to be used in place of\n** the memory allocation routines built into SQLite.)^ ^SQLite makes\n** its own private copy of the content of the [sqlite3_mem_methods] structure\n** before the [sqlite3_config()] call returns.</dd>\n**\n** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]\n** structure is filled with the currently defined memory allocation routines.)^\n** This option can be used to overload the default memory allocation\n** routines with a wrapper that simulations memory allocation failure or\n** tracks memory usage, for example. </dd>\n**\n** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>\n** <dd> ^This option takes single argument of type int, interpreted as a \n** boolean, which enables or disables the collection of memory allocation \n** statistics. ^(When memory allocation statistics are disabled, the \n** following SQLite interfaces become non-operational:\n**   <ul>\n**   <li> [sqlite3_memory_used()]\n**   <li> [sqlite3_memory_highwater()]\n**   <li> [sqlite3_soft_heap_limit64()]\n**   <li> [sqlite3_status()]\n**   </ul>)^\n** ^Memory allocation statistics are enabled by default unless SQLite is\n** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory\n** allocation statistics are disabled by default.\n** </dd>\n**\n** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite can use for\n** scratch memory.  There are three arguments:  A pointer an 8-byte\n** aligned memory buffer from which the scratch allocations will be\n** drawn, the size of each scratch allocation (sz),\n** and the maximum number of scratch allocations (N).  The sz\n** argument must be a multiple of 16.\n** The first argument must be a pointer to an 8-byte aligned buffer\n** of at least sz*N bytes of memory.\n** ^SQLite will use no more than two scratch buffers per thread.  So\n** N should be set to twice the expected maximum number of threads.\n** ^SQLite will never require a scratch buffer that is more than 6\n** times the database page size. ^If SQLite needs needs additional\n** scratch memory beyond what is provided by this configuration option, then \n** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>\n**\n** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite can use for\n** the database page cache with the default page cache implementation.  \n** This configuration should not be used if an application-define page\n** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.\n** There are three arguments to this option: A pointer to 8-byte aligned\n** memory, the size of each page buffer (sz), and the number of pages (N).\n** The sz argument should be the size of the largest database page\n** (a power of two between 512 and 32768) plus a little extra for each\n** page header.  ^The page header size is 20 to 40 bytes depending on\n** the host architecture.  ^It is harmless, apart from the wasted memory,\n** to make sz a little too large.  The first\n** argument should point to an allocation of at least sz*N bytes of memory.\n** ^SQLite will use the memory provided by the first argument to satisfy its\n** memory needs for the first N pages that it adds to cache.  ^If additional\n** page cache memory is needed beyond what is provided by this option, then\n** SQLite goes to [sqlite3_malloc()] for the additional storage space.\n** The pointer in the first argument must\n** be aligned to an 8-byte boundary or subsequent behavior of SQLite\n** will be undefined.</dd>\n**\n** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>\n** <dd> ^This option specifies a static memory buffer that SQLite will use\n** for all of its dynamic memory allocation needs beyond those provided\n** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].\n** There are three arguments: An 8-byte aligned pointer to the memory,\n** the number of bytes in the memory buffer, and the minimum allocation size.\n** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts\n** to using its default memory allocator (the system malloc() implementation),\n** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the\n** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or\n** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory\n** allocator is engaged to handle all of SQLites memory allocation needs.\n** The first pointer (the memory pointer) must be aligned to an 8-byte\n** boundary or subsequent behavior of SQLite will be undefined.\n** The minimum allocation size is capped at 2**12. Reasonable values\n** for the minimum allocation size are 2**5 through 2**8.</dd>\n**\n** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mutex_methods] structure.  The argument specifies\n** alternative low-level mutex routines to be used in place\n** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the\n** content of the [sqlite3_mutex_methods] structure before the call to\n** [sqlite3_config()] returns. ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** instance of the [sqlite3_mutex_methods] structure.  The\n** [sqlite3_mutex_methods]\n** structure is filled with the currently defined mutex routines.)^\n** This option can be used to overload the default mutex allocation\n** routines with a wrapper used to track mutex usage for performance\n** profiling or testing, for example.   ^If SQLite is compiled with\n** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then\n** the entire mutexing subsystem is omitted from the build and hence calls to\n** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will\n** return [SQLITE_ERROR].</dd>\n**\n** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>\n** <dd> ^(This option takes two arguments that determine the default\n** memory allocation for the lookaside memory allocator on each\n** [database connection].  The first argument is the\n** size of each lookaside buffer slot and the second is the number of\n** slots allocated to each database connection.)^  ^(This option sets the\n** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]\n** verb to [sqlite3_db_config()] can be used to change the lookaside\n** configuration on individual connections.)^ </dd>\n**\n** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>\n** <dd> ^(This option takes a single argument which is a pointer to\n** an [sqlite3_pcache_methods2] object.  This object specifies the interface\n** to a custom page cache implementation.)^  ^SQLite makes a copy of the\n** object and uses it for page cache memory allocations.</dd>\n**\n** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>\n** <dd> ^(This option takes a single argument which is a pointer to an\n** [sqlite3_pcache_methods2] object.  SQLite copies of the current\n** page cache implementation into that object.)^ </dd>\n**\n** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>\n** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a\n** function with a call signature of void(*)(void*,int,const char*), \n** and a pointer to void. ^If the function pointer is not NULL, it is\n** invoked by [sqlite3_log()] to process each logging event.  ^If the\n** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.\n** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is\n** passed through as the first parameter to the application-defined logger\n** function whenever that function is invoked.  ^The second parameter to\n** the logger function is a copy of the first parameter to the corresponding\n** [sqlite3_log()] call and is intended to be a [result code] or an\n** [extended result code].  ^The third parameter passed to the logger is\n** log message after formatting via [sqlite3_snprintf()].\n** The SQLite logging interface is not reentrant; the logger function\n** supplied by the application must not invoke any SQLite interface.\n** In a multi-threaded application, the application-defined logger\n** function must be threadsafe. </dd>\n**\n** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI\n** <dd> This option takes a single argument of type int. If non-zero, then\n** URI handling is globally enabled. If the parameter is zero, then URI handling\n** is globally disabled. If URI handling is globally enabled, all filenames\n** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or\n** specified as part of [ATTACH] commands are interpreted as URIs, regardless\n** of whether or not the [SQLITE_OPEN_URI] flag is set when the database\n** connection is opened. If it is globally disabled, filenames are\n** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the\n** database connection is opened. By default, URI handling is globally\n** disabled. The default value may be changed by compiling with the\n** [SQLITE_USE_URI] symbol defined.\n**\n** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]\n** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE\n** <dd> These options are obsolete and should not be used by new code.\n** They are retained for backwards compatibility but are now no-ops.\n** </dl>\n*/\n#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */\n#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */\n#define SQLITE_CONFIG_SERIALIZED    3  /* nil */\n#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */\n#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */\n#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */\n#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */\n#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */\n#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */\n#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */\n/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ \n#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */\n#define SQLITE_CONFIG_PCACHE       14  /* no-op */\n#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */\n#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */\n#define SQLITE_CONFIG_URI          17  /* int */\n#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */\n#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */\n\n/*\n** CAPI3REF: Database Connection Configuration Options\n**\n** These constants are the available integer configuration options that\n** can be passed as the second argument to the [sqlite3_db_config()] interface.\n**\n** New configuration options may be added in future releases of SQLite.\n** Existing configuration options might be discontinued.  Applications\n** should check the return code from [sqlite3_db_config()] to make sure that\n** the call worked.  ^The [sqlite3_db_config()] interface will return a\n** non-zero [error code] if a discontinued or unsupported configuration option\n** is invoked.\n**\n** <dl>\n** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>\n** <dd> ^This option takes three additional arguments that determine the \n** [lookaside memory allocator] configuration for the [database connection].\n** ^The first argument (the third parameter to [sqlite3_db_config()] is a\n** pointer to a memory buffer to use for lookaside memory.\n** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb\n** may be NULL in which case SQLite will allocate the\n** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the\n** size of each lookaside buffer slot.  ^The third argument is the number of\n** slots.  The size of the buffer in the first argument must be greater than\n** or equal to the product of the second and third arguments.  The buffer\n** must be aligned to an 8-byte boundary.  ^If the second argument to\n** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally\n** rounded down to the next smaller multiple of 8.  ^(The lookaside memory\n** configuration for a database connection can only be changed when that\n** connection is not currently using lookaside memory, or in other words\n** when the \"current value\" returned by\n** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.\n** Any attempt to change the lookaside memory configuration when lookaside\n** memory is in use leaves the configuration unchanged and returns \n** [SQLITE_BUSY].)^</dd>\n**\n** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>\n** <dd> ^This option is used to enable or disable the enforcement of\n** [foreign key constraints].  There should be two additional arguments.\n** The first argument is an integer which is 0 to disable FK enforcement,\n** positive to enable FK enforcement or negative to leave FK enforcement\n** unchanged.  The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether FK enforcement is off or on\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the FK enforcement setting is not reported back. </dd>\n**\n** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>\n** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].\n** There should be two additional arguments.\n** The first argument is an integer which is 0 to disable triggers,\n** positive to enable triggers or negative to leave the setting unchanged.\n** The second parameter is a pointer to an integer into which\n** is written 0 or 1 to indicate whether triggers are disabled or enabled\n** following this call.  The second parameter may be a NULL pointer, in\n** which case the trigger setting is not reported back. </dd>\n**\n** </dl>\n*/\n#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */\n#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */\n#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */\n\n\n/*\n** CAPI3REF: Enable Or Disable Extended Result Codes\n**\n** ^The sqlite3_extended_result_codes() routine enables or disables the\n** [extended result codes] feature of SQLite. ^The extended result\n** codes are disabled by default for historical compatibility.\n*/\nSQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);\n\n/*\n** CAPI3REF: Last Insert Rowid\n**\n** ^Each entry in an SQLite table has a unique 64-bit signed\n** integer key called the [ROWID | \"rowid\"]. ^The rowid is always available\n** as an undeclared column named ROWID, OID, or _ROWID_ as long as those\n** names are not also used by explicitly declared columns. ^If\n** the table has a column of type [INTEGER PRIMARY KEY] then that column\n** is another alias for the rowid.\n**\n** ^This routine returns the [rowid] of the most recent\n** successful [INSERT] into the database from the [database connection]\n** in the first argument.  ^As of SQLite version 3.7.7, this routines\n** records the last insert rowid of both ordinary tables and [virtual tables].\n** ^If no successful [INSERT]s\n** have ever occurred on that database connection, zero is returned.\n**\n** ^(If an [INSERT] occurs within a trigger or within a [virtual table]\n** method, then this routine will return the [rowid] of the inserted\n** row as long as the trigger or virtual table method is running.\n** But once the trigger or virtual table method ends, the value returned \n** by this routine reverts to what it was before the trigger or virtual\n** table method began.)^\n**\n** ^An [INSERT] that fails due to a constraint violation is not a\n** successful [INSERT] and does not change the value returned by this\n** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,\n** and INSERT OR ABORT make no changes to the return value of this\n** routine when their insertion fails.  ^(When INSERT OR REPLACE\n** encounters a constraint violation, it does not fail.  The\n** INSERT continues to completion after deleting rows that caused\n** the constraint problem so INSERT OR REPLACE will always change\n** the return value of this interface.)^\n**\n** ^For the purposes of this routine, an [INSERT] is considered to\n** be successful even if it is subsequently rolled back.\n**\n** This function is accessible to SQL statements via the\n** [last_insert_rowid() SQL function].\n**\n** If a separate thread performs a new [INSERT] on the same\n** database connection while the [sqlite3_last_insert_rowid()]\n** function is running and thus changes the last insert [rowid],\n** then the value returned by [sqlite3_last_insert_rowid()] is\n** unpredictable and might not equal either the old or the new\n** last insert [rowid].\n*/\nSQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);\n\n/*\n** CAPI3REF: Count The Number Of Rows Modified\n**\n** ^This function returns the number of database rows that were changed\n** or inserted or deleted by the most recently completed SQL statement\n** on the [database connection] specified by the first parameter.\n** ^(Only changes that are directly specified by the [INSERT], [UPDATE],\n** or [DELETE] statement are counted.  Auxiliary changes caused by\n** triggers or [foreign key actions] are not counted.)^ Use the\n** [sqlite3_total_changes()] function to find the total number of changes\n** including changes caused by triggers and foreign key actions.\n**\n** ^Changes to a view that are simulated by an [INSTEAD OF trigger]\n** are not counted.  Only real table changes are counted.\n**\n** ^(A \"row change\" is a change to a single row of a single table\n** caused by an INSERT, DELETE, or UPDATE statement.  Rows that\n** are changed as side effects of [REPLACE] constraint resolution,\n** rollback, ABORT processing, [DROP TABLE], or by any other\n** mechanisms do not count as direct row changes.)^\n**\n** A \"trigger context\" is a scope of execution that begins and\n** ends with the script of a [CREATE TRIGGER | trigger]. \n** Most SQL statements are\n** evaluated outside of any trigger.  This is the \"top level\"\n** trigger context.  If a trigger fires from the top level, a\n** new trigger context is entered for the duration of that one\n** trigger.  Subtriggers create subcontexts for their duration.\n**\n** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does\n** not create a new trigger context.\n**\n** ^This function returns the number of direct row changes in the\n** most recent INSERT, UPDATE, or DELETE statement within the same\n** trigger context.\n**\n** ^Thus, when called from the top level, this function returns the\n** number of changes in the most recent INSERT, UPDATE, or DELETE\n** that also occurred at the top level.  ^(Within the body of a trigger,\n** the sqlite3_changes() interface can be called to find the number of\n** changes in the most recently completed INSERT, UPDATE, or DELETE\n** statement within the body of the same trigger.\n** However, the number returned does not include changes\n** caused by subtriggers since those have their own context.)^\n**\n** See also the [sqlite3_total_changes()] interface, the\n** [count_changes pragma], and the [changes() SQL function].\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_changes()] is running then the value returned\n** is unpredictable and not meaningful.\n*/\nSQLITE_API int sqlite3_changes(sqlite3*);\n\n/*\n** CAPI3REF: Total Number Of Rows Modified\n**\n** ^This function returns the number of row changes caused by [INSERT],\n** [UPDATE] or [DELETE] statements since the [database connection] was opened.\n** ^(The count returned by sqlite3_total_changes() includes all changes\n** from all [CREATE TRIGGER | trigger] contexts and changes made by\n** [foreign key actions]. However,\n** the count does not include changes used to implement [REPLACE] constraints,\n** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The\n** count does not include rows of views that fire an [INSTEAD OF trigger],\n** though if the INSTEAD OF trigger makes changes of its own, those changes \n** are counted.)^\n** ^The sqlite3_total_changes() function counts the changes as soon as\n** the statement that makes them is completed (when the statement handle\n** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).\n**\n** See also the [sqlite3_changes()] interface, the\n** [count_changes pragma], and the [total_changes() SQL function].\n**\n** If a separate thread makes changes on the same database connection\n** while [sqlite3_total_changes()] is running then the value\n** returned is unpredictable and not meaningful.\n*/\nSQLITE_API int sqlite3_total_changes(sqlite3*);\n\n/*\n** CAPI3REF: Interrupt A Long-Running Query\n**\n** ^This function causes any pending database operation to abort and\n** return at its earliest opportunity. This routine is typically\n** called in response to a user action such as pressing \"Cancel\"\n** or Ctrl-C where the user wants a long query operation to halt\n** immediately.\n**\n** ^It is safe to call this routine from a thread different from the\n** thread that is currently running the database operation.  But it\n** is not safe to call this routine with a [database connection] that\n** is closed or might close before sqlite3_interrupt() returns.\n**\n** ^If an SQL operation is very nearly finished at the time when\n** sqlite3_interrupt() is called, then it might not have an opportunity\n** to be interrupted and might continue to completion.\n**\n** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].\n** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE\n** that is inside an explicit transaction, then the entire transaction\n** will be rolled back automatically.\n**\n** ^The sqlite3_interrupt(D) call is in effect until all currently running\n** SQL statements on [database connection] D complete.  ^Any new SQL statements\n** that are started after the sqlite3_interrupt() call and before the \n** running statements reaches zero are interrupted as if they had been\n** running prior to the sqlite3_interrupt() call.  ^New SQL statements\n** that are started after the running statement count reaches zero are\n** not effected by the sqlite3_interrupt().\n** ^A call to sqlite3_interrupt(D) that occurs when there are no running\n** SQL statements is a no-op and has no effect on SQL statements\n** that are started after the sqlite3_interrupt() call returns.\n**\n** If the database connection closes while [sqlite3_interrupt()]\n** is running then bad things will likely happen.\n*/\nSQLITE_API void sqlite3_interrupt(sqlite3*);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Is Complete\n**\n** These routines are useful during command-line input to determine if the\n** currently entered text seems to form a complete SQL statement or\n** if additional input is needed before sending the text into\n** SQLite for parsing.  ^These routines return 1 if the input string\n** appears to be a complete SQL statement.  ^A statement is judged to be\n** complete if it ends with a semicolon token and is not a prefix of a\n** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within\n** string literals or quoted identifier names or comments are not\n** independent tokens (they are part of the token in which they are\n** embedded) and thus do not count as a statement terminator.  ^Whitespace\n** and comments that follow the final semicolon are ignored.\n**\n** ^These routines return 0 if the statement is incomplete.  ^If a\n** memory allocation fails, then SQLITE_NOMEM is returned.\n**\n** ^These routines do not parse the SQL statements thus\n** will not detect syntactically incorrect SQL.\n**\n** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior \n** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked\n** automatically by sqlite3_complete16().  If that initialization fails,\n** then the return value from sqlite3_complete16() will be non-zero\n** regardless of whether or not the input SQL is complete.)^\n**\n** The input to [sqlite3_complete()] must be a zero-terminated\n** UTF-8 string.\n**\n** The input to [sqlite3_complete16()] must be a zero-terminated\n** UTF-16 string in native byte order.\n*/\nSQLITE_API int sqlite3_complete(const char *sql);\nSQLITE_API int sqlite3_complete16(const void *sql);\n\n/*\n** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors\n**\n** ^This routine sets a callback function that might be invoked whenever\n** an attempt is made to open a database table that another thread\n** or process has locked.\n**\n** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]\n** is returned immediately upon encountering the lock.  ^If the busy callback\n** is not NULL, then the callback might be invoked with two arguments.\n**\n** ^The first argument to the busy handler is a copy of the void* pointer which\n** is the third argument to sqlite3_busy_handler().  ^The second argument to\n** the busy handler callback is the number of times that the busy handler has\n** been invoked for this locking event.  ^If the\n** busy callback returns 0, then no additional attempts are made to\n** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.\n** ^If the callback returns non-zero, then another attempt\n** is made to open the database for reading and the cycle repeats.\n**\n** The presence of a busy handler does not guarantee that it will be invoked\n** when there is lock contention. ^If SQLite determines that invoking the busy\n** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]\n** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.\n** Consider a scenario where one process is holding a read lock that\n** it is trying to promote to a reserved lock and\n** a second process is holding a reserved lock that it is trying\n** to promote to an exclusive lock.  The first process cannot proceed\n** because it is blocked by the second and the second process cannot\n** proceed because it is blocked by the first.  If both processes\n** invoke the busy handlers, neither will make any progress.  Therefore,\n** SQLite returns [SQLITE_BUSY] for the first process, hoping that this\n** will induce the first process to release its read lock and allow\n** the second process to proceed.\n**\n** ^The default busy callback is NULL.\n**\n** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]\n** when SQLite is in the middle of a large transaction where all the\n** changes will not fit into the in-memory cache.  SQLite will\n** already hold a RESERVED lock on the database file, but it needs\n** to promote this lock to EXCLUSIVE so that it can spill cache\n** pages into the database file without harm to concurrent\n** readers.  ^If it is unable to promote the lock, then the in-memory\n** cache will be left in an inconsistent state and so the error\n** code is promoted from the relatively benign [SQLITE_BUSY] to\n** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion\n** forces an automatic rollback of the changes.  See the\n** <a href=\"/cvstrac/wiki?p=CorruptionFollowingBusyError\">\n** CorruptionFollowingBusyError</a> wiki page for a discussion of why\n** this is important.\n**\n** ^(There can only be a single busy handler defined for each\n** [database connection].  Setting a new busy handler clears any\n** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]\n** will also set or clear the busy handler.\n**\n** The busy callback should not take any actions which modify the\n** database connection that invoked the busy handler.  Any such actions\n** result in undefined behavior.\n** \n** A busy handler must not close the database connection\n** or [prepared statement] that invoked the busy handler.\n*/\nSQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);\n\n/*\n** CAPI3REF: Set A Busy Timeout\n**\n** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps\n** for a specified amount of time when a table is locked.  ^The handler\n** will sleep multiple times until at least \"ms\" milliseconds of sleeping\n** have accumulated.  ^After at least \"ms\" milliseconds of sleeping,\n** the handler returns 0 which causes [sqlite3_step()] to return\n** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].\n**\n** ^Calling this routine with an argument less than or equal to zero\n** turns off all busy handlers.\n**\n** ^(There can only be a single busy handler for a particular\n** [database connection] any any given moment.  If another busy handler\n** was defined  (using [sqlite3_busy_handler()]) prior to calling\n** this routine, that other busy handler is cleared.)^\n*/\nSQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);\n\n/*\n** CAPI3REF: Convenience Routines For Running Queries\n**\n** This is a legacy interface that is preserved for backwards compatibility.\n** Use of this interface is not recommended.\n**\n** Definition: A <b>result table</b> is memory data structure created by the\n** [sqlite3_get_table()] interface.  A result table records the\n** complete query results from one or more queries.\n**\n** The table conceptually has a number of rows and columns.  But\n** these numbers are not part of the result table itself.  These\n** numbers are obtained separately.  Let N be the number of rows\n** and M be the number of columns.\n**\n** A result table is an array of pointers to zero-terminated UTF-8 strings.\n** There are (N+1)*M elements in the array.  The first M pointers point\n** to zero-terminated strings that  contain the names of the columns.\n** The remaining entries all point to query results.  NULL values result\n** in NULL pointers.  All other values are in their UTF-8 zero-terminated\n** string representation as returned by [sqlite3_column_text()].\n**\n** A result table might consist of one or more memory allocations.\n** It is not safe to pass a result table directly to [sqlite3_free()].\n** A result table should be deallocated using [sqlite3_free_table()].\n**\n** ^(As an example of the result table format, suppose a query result\n** is as follows:\n**\n** <blockquote><pre>\n**        Name        | Age\n**        -----------------------\n**        Alice       | 43\n**        Bob         | 28\n**        Cindy       | 21\n** </pre></blockquote>\n**\n** There are two column (M==2) and three rows (N==3).  Thus the\n** result table has 8 entries.  Suppose the result table is stored\n** in an array names azResult.  Then azResult holds this content:\n**\n** <blockquote><pre>\n**        azResult&#91;0] = \"Name\";\n**        azResult&#91;1] = \"Age\";\n**        azResult&#91;2] = \"Alice\";\n**        azResult&#91;3] = \"43\";\n**        azResult&#91;4] = \"Bob\";\n**        azResult&#91;5] = \"28\";\n**        azResult&#91;6] = \"Cindy\";\n**        azResult&#91;7] = \"21\";\n** </pre></blockquote>)^\n**\n** ^The sqlite3_get_table() function evaluates one or more\n** semicolon-separated SQL statements in the zero-terminated UTF-8\n** string of its 2nd parameter and returns a result table to the\n** pointer given in its 3rd parameter.\n**\n** After the application has finished with the result from sqlite3_get_table(),\n** it must pass the result table pointer to sqlite3_free_table() in order to\n** release the memory that was malloced.  Because of the way the\n** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling\n** function must not try to call [sqlite3_free()] directly.  Only\n** [sqlite3_free_table()] is able to release the memory properly and safely.\n**\n** The sqlite3_get_table() interface is implemented as a wrapper around\n** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access\n** to any internal data structures of SQLite.  It uses only the public\n** interface defined here.  As a consequence, errors that occur in the\n** wrapper layer outside of the internal [sqlite3_exec()] call are not\n** reflected in subsequent calls to [sqlite3_errcode()] or\n** [sqlite3_errmsg()].\n*/\nSQLITE_API int sqlite3_get_table(\n  sqlite3 *db,          /* An open database */\n  const char *zSql,     /* SQL to be evaluated */\n  char ***pazResult,    /* Results of the query */\n  int *pnRow,           /* Number of result rows written here */\n  int *pnColumn,        /* Number of result columns written here */\n  char **pzErrmsg       /* Error msg written here */\n);\nSQLITE_API void sqlite3_free_table(char **result);\n\n/*\n** CAPI3REF: Formatted String Printing Functions\n**\n** These routines are work-alikes of the \"printf()\" family of functions\n** from the standard C library.\n**\n** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their\n** results into memory obtained from [sqlite3_malloc()].\n** The strings returned by these two routines should be\n** released by [sqlite3_free()].  ^Both routines return a\n** NULL pointer if [sqlite3_malloc()] is unable to allocate enough\n** memory to hold the resulting string.\n**\n** ^(The sqlite3_snprintf() routine is similar to \"snprintf()\" from\n** the standard C library.  The result is written into the\n** buffer supplied as the second parameter whose size is given by\n** the first parameter. Note that the order of the\n** first two parameters is reversed from snprintf().)^  This is an\n** historical accident that cannot be fixed without breaking\n** backwards compatibility.  ^(Note also that sqlite3_snprintf()\n** returns a pointer to its buffer instead of the number of\n** characters actually written into the buffer.)^  We admit that\n** the number of characters written would be a more useful return\n** value but we cannot change the implementation of sqlite3_snprintf()\n** now without breaking compatibility.\n**\n** ^As long as the buffer size is greater than zero, sqlite3_snprintf()\n** guarantees that the buffer is always zero-terminated.  ^The first\n** parameter \"n\" is the total size of the buffer, including space for\n** the zero terminator.  So the longest string that can be completely\n** written will be n-1 characters.\n**\n** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().\n**\n** These routines all implement some additional formatting\n** options that are useful for constructing SQL statements.\n** All of the usual printf() formatting options apply.  In addition, there\n** is are \"%q\", \"%Q\", and \"%z\" options.\n**\n** ^(The %q option works like %s in that it substitutes a nul-terminated\n** string from the argument list.  But %q also doubles every '\\'' character.\n** %q is designed for use inside a string literal.)^  By doubling each '\\''\n** character it escapes that character and allows it to be inserted into\n** the string.\n**\n** For example, assume the string variable zText contains text as follows:\n**\n** <blockquote><pre>\n**  char *zText = \"It's a happy day!\";\n** </pre></blockquote>\n**\n** One can use this text in an SQL statement as follows:\n**\n** <blockquote><pre>\n**  char *zSQL = sqlite3_mprintf(\"INSERT INTO table VALUES('%q')\", zText);\n**  sqlite3_exec(db, zSQL, 0, 0, 0);\n**  sqlite3_free(zSQL);\n** </pre></blockquote>\n**\n** Because the %q format string is used, the '\\'' character in zText\n** is escaped and the SQL generated is as follows:\n**\n** <blockquote><pre>\n**  INSERT INTO table1 VALUES('It''s a happy day!')\n** </pre></blockquote>\n**\n** This is correct.  Had we used %s instead of %q, the generated SQL\n** would have looked like this:\n**\n** <blockquote><pre>\n**  INSERT INTO table1 VALUES('It's a happy day!');\n** </pre></blockquote>\n**\n** This second example is an SQL syntax error.  As a general rule you should\n** always use %q instead of %s when inserting text into a string literal.\n**\n** ^(The %Q option works like %q except it also adds single quotes around\n** the outside of the total string.  Additionally, if the parameter in the\n** argument list is a NULL pointer, %Q substitutes the text \"NULL\" (without\n** single quotes).)^  So, for example, one could say:\n**\n** <blockquote><pre>\n**  char *zSQL = sqlite3_mprintf(\"INSERT INTO table VALUES(%Q)\", zText);\n**  sqlite3_exec(db, zSQL, 0, 0, 0);\n**  sqlite3_free(zSQL);\n** </pre></blockquote>\n**\n** The code above will render a correct SQL statement in the zSQL\n** variable even if the zText variable is a NULL pointer.\n**\n** ^(The \"%z\" formatting option works like \"%s\" but with the\n** addition that after the string has been read and copied into\n** the result, [sqlite3_free()] is called on the input string.)^\n*/\nSQLITE_API char *sqlite3_mprintf(const char*,...);\nSQLITE_API char *sqlite3_vmprintf(const char*, va_list);\nSQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);\nSQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);\n\n/*\n** CAPI3REF: Memory Allocation Subsystem\n**\n** The SQLite core uses these three routines for all of its own\n** internal memory allocation needs. \"Core\" in the previous sentence\n** does not include operating-system specific VFS implementation.  The\n** Windows VFS uses native malloc() and free() for some operations.\n**\n** ^The sqlite3_malloc() routine returns a pointer to a block\n** of memory at least N bytes in length, where N is the parameter.\n** ^If sqlite3_malloc() is unable to obtain sufficient free\n** memory, it returns a NULL pointer.  ^If the parameter N to\n** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns\n** a NULL pointer.\n**\n** ^Calling sqlite3_free() with a pointer previously returned\n** by sqlite3_malloc() or sqlite3_realloc() releases that memory so\n** that it might be reused.  ^The sqlite3_free() routine is\n** a no-op if is called with a NULL pointer.  Passing a NULL pointer\n** to sqlite3_free() is harmless.  After being freed, memory\n** should neither be read nor written.  Even reading previously freed\n** memory might result in a segmentation fault or other severe error.\n** Memory corruption, a segmentation fault, or other severe error\n** might result if sqlite3_free() is called with a non-NULL pointer that\n** was not obtained from sqlite3_malloc() or sqlite3_realloc().\n**\n** ^(The sqlite3_realloc() interface attempts to resize a\n** prior memory allocation to be at least N bytes, where N is the\n** second parameter.  The memory allocation to be resized is the first\n** parameter.)^ ^ If the first parameter to sqlite3_realloc()\n** is a NULL pointer then its behavior is identical to calling\n** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().\n** ^If the second parameter to sqlite3_realloc() is zero or\n** negative then the behavior is exactly the same as calling\n** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().\n** ^sqlite3_realloc() returns a pointer to a memory allocation\n** of at least N bytes in size or NULL if sufficient memory is unavailable.\n** ^If M is the size of the prior allocation, then min(N,M) bytes\n** of the prior allocation are copied into the beginning of buffer returned\n** by sqlite3_realloc() and the prior allocation is freed.\n** ^If sqlite3_realloc() returns NULL, then the prior allocation\n** is not freed.\n**\n** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()\n** is always aligned to at least an 8 byte boundary, or to a\n** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time\n** option is used.\n**\n** In SQLite version 3.5.0 and 3.5.1, it was possible to define\n** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in\n** implementation of these routines to be omitted.  That capability\n** is no longer provided.  Only built-in memory allocators can be used.\n**\n** Prior to SQLite version 3.7.10, the Windows OS interface layer called\n** the system malloc() and free() directly when converting\n** filenames between the UTF-8 encoding used by SQLite\n** and whatever filename encoding is used by the particular Windows\n** installation.  Memory allocation errors were detected, but\n** they were reported back as [SQLITE_CANTOPEN] or\n** [SQLITE_IOERR] rather than [SQLITE_NOMEM].\n**\n** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]\n** must be either NULL or else pointers obtained from a prior\n** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have\n** not yet been released.\n**\n** The application must not read or write any part of\n** a block of memory after it has been released using\n** [sqlite3_free()] or [sqlite3_realloc()].\n*/\nSQLITE_API void *sqlite3_malloc(int);\nSQLITE_API void *sqlite3_realloc(void*, int);\nSQLITE_API void sqlite3_free(void*);\n\n/*\n** CAPI3REF: Memory Allocator Statistics\n**\n** SQLite provides these two interfaces for reporting on the status\n** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]\n** routines, which form the built-in memory allocation subsystem.\n**\n** ^The [sqlite3_memory_used()] routine returns the number of bytes\n** of memory currently outstanding (malloced but not freed).\n** ^The [sqlite3_memory_highwater()] routine returns the maximum\n** value of [sqlite3_memory_used()] since the high-water mark\n** was last reset.  ^The values returned by [sqlite3_memory_used()] and\n** [sqlite3_memory_highwater()] include any overhead\n** added by SQLite in its implementation of [sqlite3_malloc()],\n** but not overhead added by the any underlying system library\n** routines that [sqlite3_malloc()] may call.\n**\n** ^The memory high-water mark is reset to the current value of\n** [sqlite3_memory_used()] if and only if the parameter to\n** [sqlite3_memory_highwater()] is true.  ^The value returned\n** by [sqlite3_memory_highwater(1)] is the high-water mark\n** prior to the reset.\n*/\nSQLITE_API sqlite3_int64 sqlite3_memory_used(void);\nSQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);\n\n/*\n** CAPI3REF: Pseudo-Random Number Generator\n**\n** SQLite contains a high-quality pseudo-random number generator (PRNG) used to\n** select random [ROWID | ROWIDs] when inserting new records into a table that\n** already uses the largest possible [ROWID].  The PRNG is also used for\n** the build-in random() and randomblob() SQL functions.  This interface allows\n** applications to access the same PRNG for other purposes.\n**\n** ^A call to this routine stores N bytes of randomness into buffer P.\n**\n** ^The first time this routine is invoked (either internally or by\n** the application) the PRNG is seeded using randomness obtained\n** from the xRandomness method of the default [sqlite3_vfs] object.\n** ^On all subsequent invocations, the pseudo-randomness is generated\n** internally and without recourse to the [sqlite3_vfs] xRandomness\n** method.\n*/\nSQLITE_API void sqlite3_randomness(int N, void *P);\n\n/*\n** CAPI3REF: Compile-Time Authorization Callbacks\n**\n** ^This routine registers an authorizer callback with a particular\n** [database connection], supplied in the first argument.\n** ^The authorizer callback is invoked as SQL statements are being compiled\n** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],\n** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various\n** points during the compilation process, as logic is being created\n** to perform various actions, the authorizer callback is invoked to\n** see if those actions are allowed.  ^The authorizer callback should\n** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the\n** specific action but allow the SQL statement to continue to be\n** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be\n** rejected with an error.  ^If the authorizer callback returns\n** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]\n** then the [sqlite3_prepare_v2()] or equivalent call that triggered\n** the authorizer will fail with an error message.\n**\n** When the callback returns [SQLITE_OK], that means the operation\n** requested is ok.  ^When the callback returns [SQLITE_DENY], the\n** [sqlite3_prepare_v2()] or equivalent call that triggered the\n** authorizer will fail with an error message explaining that\n** access is denied. \n**\n** ^The first parameter to the authorizer callback is a copy of the third\n** parameter to the sqlite3_set_authorizer() interface. ^The second parameter\n** to the callback is an integer [SQLITE_COPY | action code] that specifies\n** the particular action to be authorized. ^The third through sixth parameters\n** to the callback are zero-terminated strings that contain additional\n** details about the action to be authorized.\n**\n** ^If the action code is [SQLITE_READ]\n** and the callback returns [SQLITE_IGNORE] then the\n** [prepared statement] statement is constructed to substitute\n** a NULL value in place of the table column that would have\n** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]\n** return can be used to deny an untrusted user access to individual\n** columns of a table.\n** ^If the action code is [SQLITE_DELETE] and the callback returns\n** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the\n** [truncate optimization] is disabled and all rows are deleted individually.\n**\n** An authorizer is used when [sqlite3_prepare | preparing]\n** SQL statements from an untrusted source, to ensure that the SQL statements\n** do not try to access data they are not allowed to see, or that they do not\n** try to execute malicious statements that damage the database.  For\n** example, an application may allow a user to enter arbitrary\n** SQL queries for evaluation by a database.  But the application does\n** not want the user to be able to make arbitrary changes to the\n** database.  An authorizer could then be put in place while the\n** user-entered SQL is being [sqlite3_prepare | prepared] that\n** disallows everything except [SELECT] statements.\n**\n** Applications that need to process SQL from untrusted sources\n** might also consider lowering resource limits using [sqlite3_limit()]\n** and limiting database size using the [max_page_count] [PRAGMA]\n** in addition to using an authorizer.\n**\n** ^(Only a single authorizer can be in place on a database connection\n** at a time.  Each call to sqlite3_set_authorizer overrides the\n** previous call.)^  ^Disable the authorizer by installing a NULL callback.\n** The authorizer is disabled by default.\n**\n** The authorizer callback must not do anything that will modify\n** the database connection that invoked the authorizer callback.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the\n** statement might be re-prepared during [sqlite3_step()] due to a \n** schema change.  Hence, the application should ensure that the\n** correct authorizer callback remains in place during the [sqlite3_step()].\n**\n** ^Note that the authorizer callback is invoked only during\n** [sqlite3_prepare()] or its variants.  Authorization is not\n** performed during statement evaluation in [sqlite3_step()], unless\n** as stated in the previous paragraph, sqlite3_step() invokes\n** sqlite3_prepare_v2() to reprepare a statement after a schema change.\n*/\nSQLITE_API int sqlite3_set_authorizer(\n  sqlite3*,\n  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),\n  void *pUserData\n);\n\n/*\n** CAPI3REF: Authorizer Return Codes\n**\n** The [sqlite3_set_authorizer | authorizer callback function] must\n** return either [SQLITE_OK] or one of these two constants in order\n** to signal SQLite whether or not the action is permitted.  See the\n** [sqlite3_set_authorizer | authorizer documentation] for additional\n** information.\n**\n** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]\n** from the [sqlite3_vtab_on_conflict()] interface.\n*/\n#define SQLITE_DENY   1   /* Abort the SQL statement with an error */\n#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */\n\n/*\n** CAPI3REF: Authorizer Action Codes\n**\n** The [sqlite3_set_authorizer()] interface registers a callback function\n** that is invoked to authorize certain SQL statement actions.  The\n** second parameter to the callback is an integer code that specifies\n** what action is being authorized.  These are the integer action codes that\n** the authorizer callback may be passed.\n**\n** These action code values signify what kind of operation is to be\n** authorized.  The 3rd and 4th parameters to the authorization\n** callback function will be parameters or NULL depending on which of these\n** codes is used as the second parameter.  ^(The 5th parameter to the\n** authorizer callback is the name of the database (\"main\", \"temp\",\n** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback\n** is the name of the inner-most trigger or view that is responsible for\n** the access attempt or NULL if this access attempt is directly from\n** top-level SQL code.\n*/\n/******************************************* 3rd ************ 4th ***********/\n#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */\n#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */\n#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */\n#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */\n#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */\n#define SQLITE_DELETE                9   /* Table Name      NULL            */\n#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */\n#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */\n#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */\n#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */\n#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */\n#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */\n#define SQLITE_INSERT               18   /* Table Name      NULL            */\n#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */\n#define SQLITE_READ                 20   /* Table Name      Column Name     */\n#define SQLITE_SELECT               21   /* NULL            NULL            */\n#define SQLITE_TRANSACTION          22   /* Operation       NULL            */\n#define SQLITE_UPDATE               23   /* Table Name      Column Name     */\n#define SQLITE_ATTACH               24   /* Filename        NULL            */\n#define SQLITE_DETACH               25   /* Database Name   NULL            */\n#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */\n#define SQLITE_REINDEX              27   /* Index Name      NULL            */\n#define SQLITE_ANALYZE              28   /* Table Name      NULL            */\n#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */\n#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */\n#define SQLITE_FUNCTION             31   /* NULL            Function Name   */\n#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */\n#define SQLITE_COPY                  0   /* No longer used */\n\n/*\n** CAPI3REF: Tracing And Profiling Functions\n**\n** These routines register callback functions that can be used for\n** tracing and profiling the execution of SQL statements.\n**\n** ^The callback function registered by sqlite3_trace() is invoked at\n** various times when an SQL statement is being run by [sqlite3_step()].\n** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the\n** SQL statement text as the statement first begins executing.\n** ^(Additional sqlite3_trace() callbacks might occur\n** as each triggered subprogram is entered.  The callbacks for triggers\n** contain a UTF-8 SQL comment that identifies the trigger.)^\n**\n** ^The callback function registered by sqlite3_profile() is invoked\n** as each SQL statement finishes.  ^The profile callback contains\n** the original statement text and an estimate of wall-clock time\n** of how long that statement took to run.  ^The profile callback\n** time is in units of nanoseconds, however the current implementation\n** is only capable of millisecond resolution so the six least significant\n** digits in the time are meaningless.  Future versions of SQLite\n** might provide greater resolution on the profiler callback.  The\n** sqlite3_profile() function is considered experimental and is\n** subject to change in future versions of SQLite.\n*/\nSQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);\nSQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,\n   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);\n\n/*\n** CAPI3REF: Query Progress Callbacks\n**\n** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback\n** function X to be invoked periodically during long running calls to\n** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for\n** database connection D.  An example use for this\n** interface is to keep a GUI updated during a large query.\n**\n** ^The parameter P is passed through as the only parameter to the \n** callback function X.  ^The parameter N is the number of \n** [virtual machine instructions] that are evaluated between successive\n** invocations of the callback X.\n**\n** ^Only a single progress handler may be defined at one time per\n** [database connection]; setting a new progress handler cancels the\n** old one.  ^Setting parameter X to NULL disables the progress handler.\n** ^The progress handler is also disabled by setting N to a value less\n** than 1.\n**\n** ^If the progress callback returns non-zero, the operation is\n** interrupted.  This feature can be used to implement a\n** \"Cancel\" button on a GUI progress dialog box.\n**\n** The progress handler callback must not do anything that will modify\n** the database connection that invoked the progress handler.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n*/\nSQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);\n\n/*\n** CAPI3REF: Opening A New Database Connection\n**\n** ^These routines open an SQLite database file as specified by the \n** filename argument. ^The filename argument is interpreted as UTF-8 for\n** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte\n** order for sqlite3_open16(). ^(A [database connection] handle is usually\n** returned in *ppDb, even if an error occurs.  The only exception is that\n** if SQLite is unable to allocate memory to hold the [sqlite3] object,\n** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]\n** object.)^ ^(If the database is opened (and/or created) successfully, then\n** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The\n** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain\n** an English language description of the error following a failure of any\n** of the sqlite3_open() routines.\n**\n** ^The default encoding for the database will be UTF-8 if\n** sqlite3_open() or sqlite3_open_v2() is called and\n** UTF-16 in the native byte order if sqlite3_open16() is used.\n**\n** Whether or not an error occurs when it is opened, resources\n** associated with the [database connection] handle should be released by\n** passing it to [sqlite3_close()] when it is no longer required.\n**\n** The sqlite3_open_v2() interface works like sqlite3_open()\n** except that it accepts two additional parameters for additional control\n** over the new database connection.  ^(The flags parameter to\n** sqlite3_open_v2() can take one of\n** the following three values, optionally combined with the \n** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],\n** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^\n**\n** <dl>\n** ^(<dt>[SQLITE_OPEN_READONLY]</dt>\n** <dd>The database is opened in read-only mode.  If the database does not\n** already exist, an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>\n** <dd>The database is opened for reading and writing if possible, or reading\n** only if the file is write protected by the operating system.  In either\n** case the database must already exist, otherwise an error is returned.</dd>)^\n**\n** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>\n** <dd>The database is opened for reading and writing, and is created if\n** it does not already exist. This is the behavior that is always used for\n** sqlite3_open() and sqlite3_open16().</dd>)^\n** </dl>\n**\n** If the 3rd parameter to sqlite3_open_v2() is not one of the\n** combinations shown above optionally combined with other\n** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]\n** then the behavior is undefined.\n**\n** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection\n** opens in the multi-thread [threading mode] as long as the single-thread\n** mode has not been set at compile-time or start-time.  ^If the\n** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens\n** in the serialized [threading mode] unless single-thread was\n** previously selected at compile-time or start-time.\n** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be\n** eligible to use [shared cache mode], regardless of whether or not shared\n** cache is enabled using [sqlite3_enable_shared_cache()].  ^The\n** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not\n** participate in [shared cache mode] even if it is enabled.\n**\n** ^The fourth parameter to sqlite3_open_v2() is the name of the\n** [sqlite3_vfs] object that defines the operating system interface that\n** the new database connection should use.  ^If the fourth parameter is\n** a NULL pointer then the default [sqlite3_vfs] object is used.\n**\n** ^If the filename is \":memory:\", then a private, temporary in-memory database\n** is created for the connection.  ^This in-memory database will vanish when\n** the database connection is closed.  Future versions of SQLite might\n** make use of additional special filenames that begin with the \":\" character.\n** It is recommended that when a database filename actually does begin with\n** a \":\" character you should prefix the filename with a pathname such as\n** \"./\" to avoid ambiguity.\n**\n** ^If the filename is an empty string, then a private, temporary\n** on-disk database will be created.  ^This private database will be\n** automatically deleted as soon as the database connection is closed.\n**\n** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>\n**\n** ^If [URI filename] interpretation is enabled, and the filename argument\n** begins with \"file:\", then the filename is interpreted as a URI. ^URI\n** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is\n** set in the fourth argument to sqlite3_open_v2(), or if it has\n** been enabled globally using the [SQLITE_CONFIG_URI] option with the\n** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.\n** As of SQLite version 3.7.7, URI filename interpretation is turned off\n** by default, but future releases of SQLite might enable URI filename\n** interpretation by default.  See \"[URI filenames]\" for additional\n** information.\n**\n** URI filenames are parsed according to RFC 3986. ^If the URI contains an\n** authority, then it must be either an empty string or the string \n** \"localhost\". ^If the authority is not an empty string or \"localhost\", an \n** error is returned to the caller. ^The fragment component of a URI, if \n** present, is ignored.\n**\n** ^SQLite uses the path component of the URI as the name of the disk file\n** which contains the database. ^If the path begins with a '/' character, \n** then it is interpreted as an absolute path. ^If the path does not begin \n** with a '/' (meaning that the authority section is omitted from the URI)\n** then the path is interpreted as a relative path. \n** ^On windows, the first component of an absolute path \n** is a drive specification (e.g. \"C:\").\n**\n** [[core URI query parameters]]\n** The query component of a URI may contain parameters that are interpreted\n** either by SQLite itself, or by a [VFS | custom VFS implementation].\n** SQLite interprets the following three query parameters:\n**\n** <ul>\n**   <li> <b>vfs</b>: ^The \"vfs\" parameter may be used to specify the name of\n**     a VFS object that provides the operating system interface that should\n**     be used to access the database file on disk. ^If this option is set to\n**     an empty string the default VFS object is used. ^Specifying an unknown\n**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is\n**     present, then the VFS specified by the option takes precedence over\n**     the value passed as the fourth parameter to sqlite3_open_v2().\n**\n**   <li> <b>mode</b>: ^(The mode parameter may be set to either \"ro\", \"rw\",\n**     \"rwc\", or \"memory\". Attempting to set it to any other value is\n**     an error)^. \n**     ^If \"ro\" is specified, then the database is opened for read-only \n**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the \n**     third argument to sqlite3_prepare_v2(). ^If the mode option is set to \n**     \"rw\", then the database is opened for read-write (but not create) \n**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had \n**     been set. ^Value \"rwc\" is equivalent to setting both \n**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is\n**     set to \"memory\" then a pure [in-memory database] that never reads\n**     or writes from disk is used. ^It is an error to specify a value for\n**     the mode parameter that is less restrictive than that specified by\n**     the flags passed in the third parameter to sqlite3_open_v2().\n**\n**   <li> <b>cache</b>: ^The cache parameter may be set to either \"shared\" or\n**     \"private\". ^Setting it to \"shared\" is equivalent to setting the\n**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to\n**     sqlite3_open_v2(). ^Setting the cache parameter to \"private\" is \n**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.\n**     ^If sqlite3_open_v2() is used and the \"cache\" parameter is present in\n**     a URI filename, its value overrides any behaviour requested by setting\n**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.\n** </ul>\n**\n** ^Specifying an unknown parameter in the query component of a URI is not an\n** error.  Future versions of SQLite might understand additional query\n** parameters.  See \"[query parameters with special meaning to SQLite]\" for\n** additional information.\n**\n** [[URI filename examples]] <h3>URI filename examples</h3>\n**\n** <table border=\"1\" align=center cellpadding=5>\n** <tr><th> URI filenames <th> Results\n** <tr><td> file:data.db <td> \n**          Open the file \"data.db\" in the current directory.\n** <tr><td> file:/home/fred/data.db<br>\n**          file:///home/fred/data.db <br> \n**          file://localhost/home/fred/data.db <br> <td> \n**          Open the database file \"/home/fred/data.db\".\n** <tr><td> file://darkstar/home/fred/data.db <td> \n**          An error. \"darkstar\" is not a recognized authority.\n** <tr><td style=\"white-space:nowrap\"> \n**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db\n**     <td> Windows only: Open the file \"data.db\" on fred's desktop on drive\n**          C:. Note that the %20 escaping in this example is not strictly \n**          necessary - space characters can be used literally\n**          in URI filenames.\n** <tr><td> file:data.db?mode=ro&cache=private <td> \n**          Open file \"data.db\" in the current directory for read-only access.\n**          Regardless of whether or not shared-cache mode is enabled by\n**          default, use a private cache.\n** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>\n**          Open file \"/home/fred/data.db\". Use the special VFS \"unix-nolock\".\n** <tr><td> file:data.db?mode=readonly <td> \n**          An error. \"readonly\" is not a valid option for the \"mode\" parameter.\n** </table>\n**\n** ^URI hexadecimal escape sequences (%HH) are supported within the path and\n** query components of a URI. A hexadecimal escape sequence consists of a\n** percent sign - \"%\" - followed by exactly two hexadecimal digits \n** specifying an octet value. ^Before the path or query components of a\n** URI filename are interpreted, they are encoded using UTF-8 and all \n** hexadecimal escape sequences replaced by a single byte containing the\n** corresponding octet. If this process generates an invalid UTF-8 encoding,\n** the results are undefined.\n**\n** <b>Note to Windows users:</b>  The encoding used for the filename argument\n** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever\n** codepage is currently defined.  Filenames containing international\n** characters must be converted to UTF-8 prior to passing them into\n** sqlite3_open() or sqlite3_open_v2().\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various\n** features that require the use of temporary files may fail.\n**\n** See also: [sqlite3_temp_directory]\n*/\nSQLITE_API int sqlite3_open(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open16(\n  const void *filename,   /* Database filename (UTF-16) */\n  sqlite3 **ppDb          /* OUT: SQLite db handle */\n);\nSQLITE_API int sqlite3_open_v2(\n  const char *filename,   /* Database filename (UTF-8) */\n  sqlite3 **ppDb,         /* OUT: SQLite db handle */\n  int flags,              /* Flags */\n  const char *zVfs        /* Name of VFS module to use */\n);\n\n/*\n** CAPI3REF: Obtain Values For URI Parameters\n**\n** These are utility routines, useful to VFS implementations, that check\n** to see if a database file was a URI that contained a specific query \n** parameter, and if so obtains the value of that query parameter.\n**\n** If F is the database filename pointer passed into the xOpen() method of \n** a VFS implementation when the flags parameter to xOpen() has one or \n** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and\n** P is the name of the query parameter, then\n** sqlite3_uri_parameter(F,P) returns the value of the P\n** parameter if it exists or a NULL pointer if P does not appear as a \n** query parameter on F.  If P is a query parameter of F\n** has no explicit value, then sqlite3_uri_parameter(F,P) returns\n** a pointer to an empty string.\n**\n** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean\n** parameter and returns true (1) or false (0) according to the value\n** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the\n** value of query parameter P is one of \"yes\", \"true\", or \"on\" in any\n** case or if the value begins with a non-zero number.  The \n** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of\n** query parameter P is one of \"no\", \"false\", or \"off\" in any case or\n** if the value begins with a numeric zero.  If P is not a query\n** parameter on F or if the value of P is does not match any of the\n** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).\n**\n** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a\n** 64-bit signed integer and returns that integer, or D if P does not\n** exist.  If the value of P is something other than an integer, then\n** zero is returned.\n** \n** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and\n** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and\n** is not a database file pathname pointer that SQLite passed into the xOpen\n** VFS method, then the behavior of this routine is undefined and probably\n** undesirable.\n*/\nSQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);\nSQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);\nSQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);\n\n\n/*\n** CAPI3REF: Error Codes And Messages\n**\n** ^The sqlite3_errcode() interface returns the numeric [result code] or\n** [extended result code] for the most recent failed sqlite3_* API call\n** associated with a [database connection]. If a prior API call failed\n** but the most recent API call succeeded, the return value from\n** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()\n** interface is the same except that it always returns the \n** [extended result code] even when extended result codes are\n** disabled.\n**\n** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language\n** text that describes the error, as either UTF-8 or UTF-16 respectively.\n** ^(Memory to hold the error message string is managed internally.\n** The application does not need to worry about freeing the result.\n** However, the error string might be overwritten or deallocated by\n** subsequent calls to other SQLite interface functions.)^\n**\n** When the serialized [threading mode] is in use, it might be the\n** case that a second error occurs on a separate thread in between\n** the time of the first error and the call to these interfaces.\n** When that happens, the second error will be reported since these\n** interfaces always report the most recent result.  To avoid\n** this, each thread can obtain exclusive use of the [database connection] D\n** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning\n** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after\n** all calls to the interfaces listed here are completed.\n**\n** If an interface fails with SQLITE_MISUSE, that means the interface\n** was invoked incorrectly by the application.  In that case, the\n** error code and message may or may not be set.\n*/\nSQLITE_API int sqlite3_errcode(sqlite3 *db);\nSQLITE_API int sqlite3_extended_errcode(sqlite3 *db);\nSQLITE_API const char *sqlite3_errmsg(sqlite3*);\nSQLITE_API const void *sqlite3_errmsg16(sqlite3*);\n\n/*\n** CAPI3REF: SQL Statement Object\n** KEYWORDS: {prepared statement} {prepared statements}\n**\n** An instance of this object represents a single SQL statement.\n** This object is variously known as a \"prepared statement\" or a\n** \"compiled SQL statement\" or simply as a \"statement\".\n**\n** The life of a statement object goes something like this:\n**\n** <ol>\n** <li> Create the object using [sqlite3_prepare_v2()] or a related\n**      function.\n** <li> Bind values to [host parameters] using the sqlite3_bind_*()\n**      interfaces.\n** <li> Run the SQL by calling [sqlite3_step()] one or more times.\n** <li> Reset the statement using [sqlite3_reset()] then go back\n**      to step 2.  Do this zero or more times.\n** <li> Destroy the object using [sqlite3_finalize()].\n** </ol>\n**\n** Refer to documentation on individual methods above for additional\n** information.\n*/\ntypedef struct sqlite3_stmt sqlite3_stmt;\n\n/*\n** CAPI3REF: Run-time Limits\n**\n** ^(This interface allows the size of various constructs to be limited\n** on a connection by connection basis.  The first parameter is the\n** [database connection] whose limit is to be set or queried.  The\n** second parameter is one of the [limit categories] that define a\n** class of constructs to be size limited.  The third parameter is the\n** new limit for that construct.)^\n**\n** ^If the new limit is a negative number, the limit is unchanged.\n** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a \n** [limits | hard upper bound]\n** set at compile-time by a C preprocessor macro called\n** [limits | SQLITE_MAX_<i>NAME</i>].\n** (The \"_LIMIT_\" in the name is changed to \"_MAX_\".))^\n** ^Attempts to increase a limit above its hard upper bound are\n** silently truncated to the hard upper bound.\n**\n** ^Regardless of whether or not the limit was changed, the \n** [sqlite3_limit()] interface returns the prior value of the limit.\n** ^Hence, to find the current value of a limit without changing it,\n** simply invoke this interface with the third parameter set to -1.\n**\n** Run-time limits are intended for use in applications that manage\n** both their own internal database and also databases that are controlled\n** by untrusted external sources.  An example application might be a\n** web browser that has its own databases for storing history and\n** separate databases controlled by JavaScript applications downloaded\n** off the Internet.  The internal databases can be given the\n** large, default limits.  Databases managed by external sources can\n** be given much smaller limits designed to prevent a denial of service\n** attack.  Developers might also want to use the [sqlite3_set_authorizer()]\n** interface to further control untrusted SQL.  The size of the database\n** created by an untrusted script can be contained using the\n** [max_page_count] [PRAGMA].\n**\n** New run-time limit categories may be added in future releases.\n*/\nSQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);\n\n/*\n** CAPI3REF: Run-Time Limit Categories\n** KEYWORDS: {limit category} {*limit categories}\n**\n** These constants define various performance limits\n** that can be lowered at run-time using [sqlite3_limit()].\n** The synopsis of the meanings of the various limits is shown below.\n** Additional information is available at [limits | Limits in SQLite].\n**\n** <dl>\n** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>\n** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^\n**\n** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>\n** <dd>The maximum length of an SQL statement, in bytes.</dd>)^\n**\n** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>\n** <dd>The maximum number of columns in a table definition or in the\n** result set of a [SELECT] or the maximum number of columns in an index\n** or in an ORDER BY or GROUP BY clause.</dd>)^\n**\n** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>\n** <dd>The maximum depth of the parse tree on any expression.</dd>)^\n**\n** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>\n** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^\n**\n** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>\n** <dd>The maximum number of instructions in a virtual machine program\n** used to implement an SQL statement.  This limit is not currently\n** enforced, though that might be added in some future release of\n** SQLite.</dd>)^\n**\n** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>\n** <dd>The maximum number of arguments on a function.</dd>)^\n**\n** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>\n** <dd>The maximum number of [ATTACH | attached databases].)^</dd>\n**\n** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]\n** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>\n** <dd>The maximum length of the pattern argument to the [LIKE] or\n** [GLOB] operators.</dd>)^\n**\n** [[SQLITE_LIMIT_VARIABLE_NUMBER]]\n** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>\n** <dd>The maximum index number of any [parameter] in an SQL statement.)^\n**\n** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>\n** <dd>The maximum depth of recursion for triggers.</dd>)^\n** </dl>\n*/\n#define SQLITE_LIMIT_LENGTH                    0\n#define SQLITE_LIMIT_SQL_LENGTH                1\n#define SQLITE_LIMIT_COLUMN                    2\n#define SQLITE_LIMIT_EXPR_DEPTH                3\n#define SQLITE_LIMIT_COMPOUND_SELECT           4\n#define SQLITE_LIMIT_VDBE_OP                   5\n#define SQLITE_LIMIT_FUNCTION_ARG              6\n#define SQLITE_LIMIT_ATTACHED                  7\n#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8\n#define SQLITE_LIMIT_VARIABLE_NUMBER           9\n#define SQLITE_LIMIT_TRIGGER_DEPTH            10\n\n/*\n** CAPI3REF: Compiling An SQL Statement\n** KEYWORDS: {SQL statement compiler}\n**\n** To execute an SQL query, it must first be compiled into a byte-code\n** program using one of these routines.\n**\n** The first argument, \"db\", is a [database connection] obtained from a\n** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or\n** [sqlite3_open16()].  The database connection must not have been closed.\n**\n** The second argument, \"zSql\", is the statement to be compiled, encoded\n** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()\n** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()\n** use UTF-16.\n**\n** ^If the nByte argument is less than zero, then zSql is read up to the\n** first zero terminator. ^If nByte is non-negative, then it is the maximum\n** number of  bytes read from zSql.  ^When nByte is non-negative, the\n** zSql string ends at either the first '\\000' or '\\u0000' character or\n** the nByte-th byte, whichever comes first. If the caller knows\n** that the supplied string is nul-terminated, then there is a small\n** performance advantage to be gained by passing an nByte parameter that\n** is equal to the number of bytes in the input string <i>including</i>\n** the nul-terminator bytes as this saves SQLite from having to\n** make a copy of the input string.\n**\n** ^If pzTail is not NULL then *pzTail is made to point to the first byte\n** past the end of the first SQL statement in zSql.  These routines only\n** compile the first statement in zSql, so *pzTail is left pointing to\n** what remains uncompiled.\n**\n** ^*ppStmt is left pointing to a compiled [prepared statement] that can be\n** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set\n** to NULL.  ^If the input text contains no SQL (if the input is an empty\n** string or a comment) then *ppStmt is set to NULL.\n** The calling procedure is responsible for deleting the compiled\n** SQL statement using [sqlite3_finalize()] after it has finished with it.\n** ppStmt may not be NULL.\n**\n** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];\n** otherwise an [error code] is returned.\n**\n** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are\n** recommended for all new programs. The two older interfaces are retained\n** for backwards compatibility, but their use is discouraged.\n** ^In the \"v2\" interfaces, the prepared statement\n** that is returned (the [sqlite3_stmt] object) contains a copy of the\n** original SQL text. This causes the [sqlite3_step()] interface to\n** behave differently in three ways:\n**\n** <ol>\n** <li>\n** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it\n** always used to do, [sqlite3_step()] will automatically recompile the SQL\n** statement and try to run it again.\n** </li>\n**\n** <li>\n** ^When an error occurs, [sqlite3_step()] will return one of the detailed\n** [error codes] or [extended error codes].  ^The legacy behavior was that\n** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code\n** and the application would have to make a second call to [sqlite3_reset()]\n** in order to find the underlying cause of the problem. With the \"v2\" prepare\n** interfaces, the underlying reason for the error is returned immediately.\n** </li>\n**\n** <li>\n** ^If the specific value bound to [parameter | host parameter] in the \n** WHERE clause might influence the choice of query plan for a statement,\n** then the statement will be automatically recompiled, as if there had been \n** a schema change, on the first  [sqlite3_step()] call following any change\n** to the [sqlite3_bind_text | bindings] of that [parameter]. \n** ^The specific value of WHERE-clause [parameter] might influence the \n** choice of query plan if the parameter is the left-hand side of a [LIKE]\n** or [GLOB] operator or if the parameter is compared to an indexed column\n** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.\n** the \n** </li>\n** </ol>\n*/\nSQLITE_API int sqlite3_prepare(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare_v2(\n  sqlite3 *db,            /* Database handle */\n  const char *zSql,       /* SQL statement, UTF-8 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const char **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\nSQLITE_API int sqlite3_prepare16_v2(\n  sqlite3 *db,            /* Database handle */\n  const void *zSql,       /* SQL statement, UTF-16 encoded */\n  int nByte,              /* Maximum length of zSql in bytes. */\n  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */\n  const void **pzTail     /* OUT: Pointer to unused portion of zSql */\n);\n\n/*\n** CAPI3REF: Retrieving Statement SQL\n**\n** ^This interface can be used to retrieve a saved copy of the original\n** SQL text used to create a [prepared statement] if that statement was\n** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].\n*/\nSQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If An SQL Statement Writes The Database\n**\n** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if\n** and only if the [prepared statement] X makes no direct changes to\n** the content of the database file.\n**\n** Note that [application-defined SQL functions] or\n** [virtual tables] might change the database indirectly as a side effect.  \n** ^(For example, if an application defines a function \"eval()\" that \n** calls [sqlite3_exec()], then the following SQL statement would\n** change the database file through side-effects:\n**\n** <blockquote><pre>\n**    SELECT eval('DELETE FROM t1') FROM t2;\n** </pre></blockquote>\n**\n** But because the [SELECT] statement does not change the database file\n** directly, sqlite3_stmt_readonly() would still return true.)^\n**\n** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],\n** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,\n** since the statements themselves do not actually modify the database but\n** rather they control the timing of when other statements modify the \n** database.  ^The [ATTACH] and [DETACH] statements also cause\n** sqlite3_stmt_readonly() to return true since, while those statements\n** change the configuration of a database connection, they do not make \n** changes to the content of the database files on disk.\n*/\nSQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Determine If A Prepared Statement Has Been Reset\n**\n** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the\n** [prepared statement] S has been stepped at least once using \n** [sqlite3_step(S)] but has not run to completion and/or has not \n** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)\n** interface returns false if S is a NULL pointer.  If S is not a \n** NULL pointer and is not a pointer to a valid [prepared statement]\n** object, then the behavior is undefined and probably undesirable.\n**\n** This interface can be used in combination [sqlite3_next_stmt()]\n** to locate all prepared statements associated with a database \n** connection that are in need of being reset.  This can be used,\n** for example, in diagnostic routines to search for prepared \n** statements that are holding a transaction open.\n*/\nSQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Dynamically Typed Value Object\n** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}\n**\n** SQLite uses the sqlite3_value object to represent all values\n** that can be stored in a database table. SQLite uses dynamic typing\n** for the values it stores.  ^Values stored in sqlite3_value objects\n** can be integers, floating point values, strings, BLOBs, or NULL.\n**\n** An sqlite3_value object may be either \"protected\" or \"unprotected\".\n** Some interfaces require a protected sqlite3_value.  Other interfaces\n** will accept either a protected or an unprotected sqlite3_value.\n** Every interface that accepts sqlite3_value arguments specifies\n** whether or not it requires a protected sqlite3_value.\n**\n** The terms \"protected\" and \"unprotected\" refer to whether or not\n** a mutex is held.  An internal mutex is held for a protected\n** sqlite3_value object but no mutex is held for an unprotected\n** sqlite3_value object.  If SQLite is compiled to be single-threaded\n** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)\n** or if SQLite is run in one of reduced mutex modes \n** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]\n** then there is no distinction between protected and unprotected\n** sqlite3_value objects and they can be used interchangeably.  However,\n** for maximum code portability it is recommended that applications\n** still make the distinction between protected and unprotected\n** sqlite3_value objects even when not strictly required.\n**\n** ^The sqlite3_value objects that are passed as parameters into the\n** implementation of [application-defined SQL functions] are protected.\n** ^The sqlite3_value object returned by\n** [sqlite3_column_value()] is unprotected.\n** Unprotected sqlite3_value objects may only be used with\n** [sqlite3_result_value()] and [sqlite3_bind_value()].\n** The [sqlite3_value_blob | sqlite3_value_type()] family of\n** interfaces require protected sqlite3_value objects.\n*/\ntypedef struct Mem sqlite3_value;\n\n/*\n** CAPI3REF: SQL Function Context Object\n**\n** The context in which an SQL function executes is stored in an\n** sqlite3_context object.  ^A pointer to an sqlite3_context object\n** is always first parameter to [application-defined SQL functions].\n** The application-defined SQL function implementation will pass this\n** pointer through into calls to [sqlite3_result_int | sqlite3_result()],\n** [sqlite3_aggregate_context()], [sqlite3_user_data()],\n** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],\n** and/or [sqlite3_set_auxdata()].\n*/\ntypedef struct sqlite3_context sqlite3_context;\n\n/*\n** CAPI3REF: Binding Values To Prepared Statements\n** KEYWORDS: {host parameter} {host parameters} {host parameter name}\n** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}\n**\n** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,\n** literals may be replaced by a [parameter] that matches one of following\n** templates:\n**\n** <ul>\n** <li>  ?\n** <li>  ?NNN\n** <li>  :VVV\n** <li>  @VVV\n** <li>  $VVV\n** </ul>\n**\n** In the templates above, NNN represents an integer literal,\n** and VVV represents an alphanumeric identifier.)^  ^The values of these\n** parameters (also called \"host parameter names\" or \"SQL parameters\")\n** can be set using the sqlite3_bind_*() routines defined here.\n**\n** ^The first argument to the sqlite3_bind_*() routines is always\n** a pointer to the [sqlite3_stmt] object returned from\n** [sqlite3_prepare_v2()] or its variants.\n**\n** ^The second argument is the index of the SQL parameter to be set.\n** ^The leftmost SQL parameter has an index of 1.  ^When the same named\n** SQL parameter is used more than once, second and subsequent\n** occurrences have the same index as the first occurrence.\n** ^The index for named parameters can be looked up using the\n** [sqlite3_bind_parameter_index()] API if desired.  ^The index\n** for \"?NNN\" parameters is the value of NNN.\n** ^The NNN value must be between 1 and the [sqlite3_limit()]\n** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).\n**\n** ^The third argument is the value to bind to the parameter.\n**\n** ^(In those routines that have a fourth argument, its value is the\n** number of bytes in the parameter.  To be clear: the value is the\n** number of <u>bytes</u> in the value, not the number of characters.)^\n** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()\n** is negative, then the length of the string is\n** the number of bytes up to the first zero terminator.\n** If the fourth parameter to sqlite3_bind_blob() is negative, then\n** the behavior is undefined.\n** If a non-negative fourth parameter is provided to sqlite3_bind_text()\n** or sqlite3_bind_text16() then that parameter must be the byte offset\n** where the NUL terminator would occur assuming the string were NUL\n** terminated.  If any NUL characters occur at byte offsets less than \n** the value of the fourth parameter then the resulting string value will\n** contain embedded NULs.  The result of expressions involving strings\n** with embedded NULs is undefined.\n**\n** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and\n** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or\n** string after SQLite has finished with it.  ^The destructor is called\n** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),\n** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  \n** ^If the fifth argument is\n** the special value [SQLITE_STATIC], then SQLite assumes that the\n** information is in static, unmanaged space and does not need to be freed.\n** ^If the fifth argument has the value [SQLITE_TRANSIENT], then\n** SQLite makes its own private copy of the data immediately, before\n** the sqlite3_bind_*() routine returns.\n**\n** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that\n** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory\n** (just an integer to hold its size) while it is being processed.\n** Zeroblobs are intended to serve as placeholders for BLOBs whose\n** content is later written using\n** [sqlite3_blob_open | incremental BLOB I/O] routines.\n** ^A negative value for the zeroblob results in a zero-length BLOB.\n**\n** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer\n** for the [prepared statement] or with a prepared statement for which\n** [sqlite3_step()] has been called more recently than [sqlite3_reset()],\n** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()\n** routine is passed a [prepared statement] that has been finalized, the\n** result is undefined and probably harmful.\n**\n** ^Bindings are not cleared by the [sqlite3_reset()] routine.\n** ^Unbound parameters are interpreted as NULL.\n**\n** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an\n** [error code] if anything goes wrong.\n** ^[SQLITE_RANGE] is returned if the parameter\n** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.\n**\n** See also: [sqlite3_bind_parameter_count()],\n** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);\nSQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);\nSQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);\nSQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);\nSQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));\nSQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));\nSQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);\nSQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);\n\n/*\n** CAPI3REF: Number Of SQL Parameters\n**\n** ^This routine can be used to find the number of [SQL parameters]\n** in a [prepared statement].  SQL parameters are tokens of the\n** form \"?\", \"?NNN\", \":AAA\", \"$AAA\", or \"@AAA\" that serve as\n** placeholders for values that are [sqlite3_bind_blob | bound]\n** to the parameters at a later time.\n**\n** ^(This routine actually returns the index of the largest (rightmost)\n** parameter. For all forms except ?NNN, this will correspond to the\n** number of unique parameters.  If parameters of the ?NNN form are used,\n** there may be gaps in the list.)^\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_name()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Name Of A Host Parameter\n**\n** ^The sqlite3_bind_parameter_name(P,N) interface returns\n** the name of the N-th [SQL parameter] in the [prepared statement] P.\n** ^(SQL parameters of the form \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** have a name which is the string \"?NNN\" or \":AAA\" or \"@AAA\" or \"$AAA\"\n** respectively.\n** In other words, the initial \":\" or \"$\" or \"@\" or \"?\"\n** is included as part of the name.)^\n** ^Parameters of the form \"?\" without a following integer have no name\n** and are referred to as \"nameless\" or \"anonymous parameters\".\n**\n** ^The first host parameter has an index of 1, not 0.\n**\n** ^If the value N is out of range or if the N-th parameter is\n** nameless, then NULL is returned.  ^The returned string is\n** always in UTF-8 encoding even if the named parameter was\n** originally specified as UTF-16 in [sqlite3_prepare16()] or\n** [sqlite3_prepare16_v2()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);\n\n/*\n** CAPI3REF: Index Of A Parameter With A Given Name\n**\n** ^Return the index of an SQL parameter given its name.  ^The\n** index value returned is suitable for use as the second\n** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero\n** is returned if no matching parameter is found.  ^The parameter\n** name must be given in UTF-8 even if the original statement\n** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].\n**\n** See also: [sqlite3_bind_blob|sqlite3_bind()],\n** [sqlite3_bind_parameter_count()], and\n** [sqlite3_bind_parameter_index()].\n*/\nSQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);\n\n/*\n** CAPI3REF: Reset All Bindings On A Prepared Statement\n**\n** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset\n** the [sqlite3_bind_blob | bindings] on a [prepared statement].\n** ^Use this routine to reset all host parameters to NULL.\n*/\nSQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number Of Columns In A Result Set\n**\n** ^Return the number of columns in the result set returned by the\n** [prepared statement]. ^This routine returns 0 if pStmt is an SQL\n** statement that does not return data (for example an [UPDATE]).\n**\n** See also: [sqlite3_data_count()]\n*/\nSQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Column Names In A Result Set\n**\n** ^These routines return the name assigned to a particular column\n** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()\n** interface returns a pointer to a zero-terminated UTF-8 string\n** and sqlite3_column_name16() returns a pointer to a zero-terminated\n** UTF-16 string.  ^The first parameter is the [prepared statement]\n** that implements the [SELECT] statement. ^The second parameter is the\n** column number.  ^The leftmost column is number 0.\n**\n** ^The returned string pointer is valid until either the [prepared statement]\n** is destroyed by [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the next call to\n** sqlite3_column_name() or sqlite3_column_name16() on the same column.\n**\n** ^If sqlite3_malloc() fails during the processing of either routine\n** (for example during a conversion from UTF-8 to UTF-16) then a\n** NULL pointer is returned.\n**\n** ^The name of a result column is the value of the \"AS\" clause for\n** that column, if there is an AS clause.  If there is no AS clause\n** then the name of the column is unspecified and may change from\n** one release of SQLite to the next.\n*/\nSQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);\nSQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);\n\n/*\n** CAPI3REF: Source Of Data In A Query Result\n**\n** ^These routines provide a means to determine the database, table, and\n** table column that is the origin of a particular result column in\n** [SELECT] statement.\n** ^The name of the database or table or column can be returned as\n** either a UTF-8 or UTF-16 string.  ^The _database_ routines return\n** the database name, the _table_ routines return the table name, and\n** the origin_ routines return the column name.\n** ^The returned string is valid until the [prepared statement] is destroyed\n** using [sqlite3_finalize()] or until the statement is automatically\n** reprepared by the first call to [sqlite3_step()] for a particular run\n** or until the same information is requested\n** again in a different encoding.\n**\n** ^The names returned are the original un-aliased names of the\n** database, table, and column.\n**\n** ^The first argument to these interfaces is a [prepared statement].\n** ^These functions return information about the Nth result column returned by\n** the statement, where N is the second function argument.\n** ^The left-most column is column 0 for these routines.\n**\n** ^If the Nth column returned by the statement is an expression or\n** subquery and is not a column value, then all of these functions return\n** NULL.  ^These routine might also return NULL if a memory allocation error\n** occurs.  ^Otherwise, they return the name of the attached database, table,\n** or column that query result column was extracted from.\n**\n** ^As with all other SQLite APIs, those whose names end with \"16\" return\n** UTF-16 encoded strings and the other functions return UTF-8.\n**\n** ^These APIs are only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.\n**\n** If two or more threads call one or more of these routines against the same\n** prepared statement and column at the same time then the results are\n** undefined.\n**\n** If two or more threads call one or more\n** [sqlite3_column_database_name | column metadata interfaces]\n** for the same [prepared statement] and result column\n** at the same time then the results are undefined.\n*/\nSQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);\nSQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Declared Datatype Of A Query Result\n**\n** ^(The first parameter is a [prepared statement].\n** If this statement is a [SELECT] statement and the Nth column of the\n** returned result set of that [SELECT] is a table column (not an\n** expression or subquery) then the declared type of the table\n** column is returned.)^  ^If the Nth column of the result set is an\n** expression or subquery, then a NULL pointer is returned.\n** ^The returned string is always UTF-8 encoded.\n**\n** ^(For example, given the database schema:\n**\n** CREATE TABLE t1(c1 VARIANT);\n**\n** and the following statement to be compiled:\n**\n** SELECT c1 + 1, c1 FROM t1;\n**\n** this routine would return the string \"VARIANT\" for the second result\n** column (i==1), and a NULL pointer for the first result column (i==0).)^\n**\n** ^SQLite uses dynamic run-time typing.  ^So just because a column\n** is declared to contain a particular type does not mean that the\n** data stored in that column is of the declared type.  SQLite is\n** strongly typed, but the typing is dynamic not static.  ^Type\n** is associated with individual values, not with the containers\n** used to hold those values.\n*/\nSQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);\nSQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);\n\n/*\n** CAPI3REF: Evaluate An SQL Statement\n**\n** After a [prepared statement] has been prepared using either\n** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy\n** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function\n** must be called one or more times to evaluate the statement.\n**\n** The details of the behavior of the sqlite3_step() interface depend\n** on whether the statement was prepared using the newer \"v2\" interface\n** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy\n** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the\n** new \"v2\" interface is recommended for new applications but the legacy\n** interface will continue to be supported.\n**\n** ^In the legacy interface, the return value will be either [SQLITE_BUSY],\n** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].\n** ^With the \"v2\" interface, any of the other [result codes] or\n** [extended result codes] might be returned as well.\n**\n** ^[SQLITE_BUSY] means that the database engine was unable to acquire the\n** database locks it needs to do its job.  ^If the statement is a [COMMIT]\n** or occurs outside of an explicit transaction, then you can retry the\n** statement.  If the statement is not a [COMMIT] and occurs within an\n** explicit transaction then you should rollback the transaction before\n** continuing.\n**\n** ^[SQLITE_DONE] means that the statement has finished executing\n** successfully.  sqlite3_step() should not be called again on this virtual\n** machine without first calling [sqlite3_reset()] to reset the virtual\n** machine back to its initial state.\n**\n** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]\n** is returned each time a new row of data is ready for processing by the\n** caller. The values may be accessed using the [column access functions].\n** sqlite3_step() is called again to retrieve the next row of data.\n**\n** ^[SQLITE_ERROR] means that a run-time error (such as a constraint\n** violation) has occurred.  sqlite3_step() should not be called again on\n** the VM. More information may be found by calling [sqlite3_errmsg()].\n** ^With the legacy interface, a more specific error code (for example,\n** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)\n** can be obtained by calling [sqlite3_reset()] on the\n** [prepared statement].  ^In the \"v2\" interface,\n** the more specific error code is returned directly by sqlite3_step().\n**\n** [SQLITE_MISUSE] means that the this routine was called inappropriately.\n** Perhaps it was called on a [prepared statement] that has\n** already been [sqlite3_finalize | finalized] or on one that had\n** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could\n** be the case that the same database connection is being used by two or\n** more threads at the same moment in time.\n**\n** For all versions of SQLite up to and including 3.6.23.1, a call to\n** [sqlite3_reset()] was required after sqlite3_step() returned anything\n** other than [SQLITE_ROW] before any subsequent invocation of\n** sqlite3_step().  Failure to reset the prepared statement using \n** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from\n** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began\n** calling [sqlite3_reset()] automatically in this circumstance rather\n** than returning [SQLITE_MISUSE].  This is not considered a compatibility\n** break because any application that ever receives an SQLITE_MISUSE error\n** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option\n** can be used to restore the legacy behavior.\n**\n** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()\n** API always returns a generic error code, [SQLITE_ERROR], following any\n** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call\n** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the\n** specific [error codes] that better describes the error.\n** We admit that this is a goofy design.  The problem has been fixed\n** with the \"v2\" interface.  If you prepare all of your SQL statements\n** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead\n** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,\n** then the more specific [error codes] are returned directly\n** by sqlite3_step().  The use of the \"v2\" interface is recommended.\n*/\nSQLITE_API int sqlite3_step(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Number of columns in a result set\n**\n** ^The sqlite3_data_count(P) interface returns the number of columns in the\n** current row of the result set of [prepared statement] P.\n** ^If prepared statement P does not have results ready to return\n** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of\n** interfaces) then sqlite3_data_count(P) returns 0.\n** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.\n** ^The sqlite3_data_count(P) routine returns 0 if the previous call to\n** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)\n** will return non-zero if previous call to [sqlite3_step](P) returned\n** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]\n** where it always returns zero since each step of that multi-step\n** pragma returns 0 columns of data.\n**\n** See also: [sqlite3_column_count()]\n*/\nSQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Fundamental Datatypes\n** KEYWORDS: SQLITE_TEXT\n**\n** ^(Every value in SQLite has one of five fundamental datatypes:\n**\n** <ul>\n** <li> 64-bit signed integer\n** <li> 64-bit IEEE floating point number\n** <li> string\n** <li> BLOB\n** <li> NULL\n** </ul>)^\n**\n** These constants are codes for each of those types.\n**\n** Note that the SQLITE_TEXT constant was also used in SQLite version 2\n** for a completely different meaning.  Software that links against both\n** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not\n** SQLITE_TEXT.\n*/\n#define SQLITE_INTEGER  1\n#define SQLITE_FLOAT    2\n#define SQLITE_BLOB     4\n#define SQLITE_NULL     5\n#ifdef SQLITE_TEXT\n# undef SQLITE_TEXT\n#else\n# define SQLITE_TEXT     3\n#endif\n#define SQLITE3_TEXT     3\n\n/*\n** CAPI3REF: Result Values From A Query\n** KEYWORDS: {column access functions}\n**\n** These routines form the \"result set\" interface.\n**\n** ^These routines return information about a single column of the current\n** result row of a query.  ^In every case the first argument is a pointer\n** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]\n** that was returned from [sqlite3_prepare_v2()] or one of its variants)\n** and the second argument is the index of the column for which information\n** should be returned. ^The leftmost column of the result set has the index 0.\n** ^The number of columns in the result can be determined using\n** [sqlite3_column_count()].\n**\n** If the SQL statement does not currently point to a valid row, or if the\n** column index is out of range, the result is undefined.\n** These routines may only be called when the most recent call to\n** [sqlite3_step()] has returned [SQLITE_ROW] and neither\n** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.\n** If any of these routines are called after [sqlite3_reset()] or\n** [sqlite3_finalize()] or after [sqlite3_step()] has returned\n** something other than [SQLITE_ROW], the results are undefined.\n** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]\n** are called from a different thread while any of these routines\n** are pending, then the results are undefined.\n**\n** ^The sqlite3_column_type() routine returns the\n** [SQLITE_INTEGER | datatype code] for the initial data type\n** of the result column.  ^The returned value is one of [SQLITE_INTEGER],\n** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value\n** returned by sqlite3_column_type() is only meaningful if no type\n** conversions have occurred as described below.  After a type conversion,\n** the value returned by sqlite3_column_type() is undefined.  Future\n** versions of SQLite may change the behavior of sqlite3_column_type()\n** following a type conversion.\n**\n** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts\n** the string to UTF-8 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes() returns zero.\n**\n** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()\n** routine returns the number of bytes in that BLOB or string.\n** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts\n** the string to UTF-16 and then returns the number of bytes.\n** ^If the result is a numeric value then sqlite3_column_bytes16() uses\n** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns\n** the number of bytes in that string.\n** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.\n**\n** ^The values returned by [sqlite3_column_bytes()] and \n** [sqlite3_column_bytes16()] do not include the zero terminators at the end\n** of the string.  ^For clarity: the values returned by\n** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of\n** bytes in the string, not the number of characters.\n**\n** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),\n** even empty strings, are always zero-terminated.  ^The return\n** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.\n**\n** ^The object returned by [sqlite3_column_value()] is an\n** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object\n** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].\n** If the [unprotected sqlite3_value] object returned by\n** [sqlite3_column_value()] is used in any other way, including calls\n** to routines like [sqlite3_value_int()], [sqlite3_value_text()],\n** or [sqlite3_value_bytes()], then the behavior is undefined.\n**\n** These routines attempt to convert the value where appropriate.  ^For\n** example, if the internal representation is FLOAT and a text result\n** is requested, [sqlite3_snprintf()] is used internally to perform the\n** conversion automatically.  ^(The following table details the conversions\n** that are applied:\n**\n** <blockquote>\n** <table border=\"1\">\n** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion\n**\n** <tr><td>  NULL    <td> INTEGER   <td> Result is 0\n** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0\n** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer\n** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer\n** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float\n** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer\n** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT\n** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer\n** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float\n** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT\n** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()\n** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()\n** <tr><td>  TEXT    <td>   BLOB    <td> No change\n** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()\n** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()\n** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed\n** </table>\n** </blockquote>)^\n**\n** The table above makes reference to standard C library functions atoi()\n** and atof().  SQLite does not really use these functions.  It has its\n** own equivalent internal routines.  The atoi() and atof() names are\n** used in the table for brevity and because they are familiar to most\n** C programmers.\n**\n** Note that when type conversions occur, pointers returned by prior\n** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or\n** sqlite3_column_text16() may be invalidated.\n** Type conversions and pointer invalidations might occur\n** in the following cases:\n**\n** <ul>\n** <li> The initial content is a BLOB and sqlite3_column_text() or\n**      sqlite3_column_text16() is called.  A zero-terminator might\n**      need to be added to the string.</li>\n** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or\n**      sqlite3_column_text16() is called.  The content must be converted\n**      to UTF-16.</li>\n** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or\n**      sqlite3_column_text() is called.  The content must be converted\n**      to UTF-8.</li>\n** </ul>\n**\n** ^Conversions between UTF-16be and UTF-16le are always done in place and do\n** not invalidate a prior pointer, though of course the content of the buffer\n** that the prior pointer references will have been modified.  Other kinds\n** of conversion are done in place when it is possible, but sometimes they\n** are not possible and in those cases prior pointers are invalidated.\n**\n** The safest and easiest to remember policy is to invoke these routines\n** in one of the following ways:\n**\n** <ul>\n**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>\n**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>\n** </ul>\n**\n** In other words, you should call sqlite3_column_text(),\n** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result\n** into the desired format, then invoke sqlite3_column_bytes() or\n** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls\n** to sqlite3_column_text() or sqlite3_column_blob() with calls to\n** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()\n** with calls to sqlite3_column_bytes().\n**\n** ^The pointers returned are valid until a type conversion occurs as\n** described above, or until [sqlite3_step()] or [sqlite3_reset()] or\n** [sqlite3_finalize()] is called.  ^The memory space used to hold strings\n** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned\n** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into\n** [sqlite3_free()].\n**\n** ^(If a memory allocation error occurs during the evaluation of any\n** of these routines, a default value is returned.  The default value\n** is either the integer 0, the floating point number 0.0, or a NULL\n** pointer.  Subsequent calls to [sqlite3_errcode()] will return\n** [SQLITE_NOMEM].)^\n*/\nSQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);\nSQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);\nSQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);\nSQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);\nSQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);\nSQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);\n\n/*\n** CAPI3REF: Destroy A Prepared Statement Object\n**\n** ^The sqlite3_finalize() function is called to delete a [prepared statement].\n** ^If the most recent evaluation of the statement encountered no errors\n** or if the statement is never been evaluated, then sqlite3_finalize() returns\n** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then\n** sqlite3_finalize(S) returns the appropriate [error code] or\n** [extended error code].\n**\n** ^The sqlite3_finalize(S) routine can be called at any point during\n** the life cycle of [prepared statement] S:\n** before statement S is ever evaluated, after\n** one or more calls to [sqlite3_reset()], or after any call\n** to [sqlite3_step()] regardless of whether or not the statement has\n** completed execution.\n**\n** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.\n**\n** The application must finalize every [prepared statement] in order to avoid\n** resource leaks.  It is a grievous error for the application to try to use\n** a prepared statement after it has been finalized.  Any use of a prepared\n** statement after it has been finalized can result in undefined and\n** undesirable behavior such as segfaults and heap corruption.\n*/\nSQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Reset A Prepared Statement Object\n**\n** The sqlite3_reset() function is called to reset a [prepared statement]\n** object back to its initial state, ready to be re-executed.\n** ^Any SQL statement variables that had values bound to them using\n** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.\n** Use [sqlite3_clear_bindings()] to reset the bindings.\n**\n** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S\n** back to the beginning of its program.\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],\n** or if [sqlite3_step(S)] has never before been called on S,\n** then [sqlite3_reset(S)] returns [SQLITE_OK].\n**\n** ^If the most recent call to [sqlite3_step(S)] for the\n** [prepared statement] S indicated an error, then\n** [sqlite3_reset(S)] returns an appropriate [error code].\n**\n** ^The [sqlite3_reset(S)] interface does not change the values\n** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.\n*/\nSQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Create Or Redefine SQL Functions\n** KEYWORDS: {function creation routines}\n** KEYWORDS: {application-defined SQL function}\n** KEYWORDS: {application-defined SQL functions}\n**\n** ^These functions (collectively known as \"function creation routines\")\n** are used to add SQL functions or aggregates or to redefine the behavior\n** of existing SQL functions or aggregates.  The only differences between\n** these routines are the text encoding expected for\n** the second parameter (the name of the function being created)\n** and the presence or absence of a destructor callback for\n** the application data pointer.\n**\n** ^The first parameter is the [database connection] to which the SQL\n** function is to be added.  ^If an application uses more than one database\n** connection then application-defined SQL functions must be added\n** to each database connection separately.\n**\n** ^The second parameter is the name of the SQL function to be created or\n** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8\n** representation, exclusive of the zero-terminator.  ^Note that the name\n** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  \n** ^Any attempt to create a function with a longer name\n** will result in [SQLITE_MISUSE] being returned.\n**\n** ^The third parameter (nArg)\n** is the number of arguments that the SQL function or\n** aggregate takes. ^If this parameter is -1, then the SQL function or\n** aggregate may take any number of arguments between 0 and the limit\n** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third\n** parameter is less than -1 or greater than 127 then the behavior is\n** undefined.\n**\n** ^The fourth parameter, eTextRep, specifies what\n** [SQLITE_UTF8 | text encoding] this SQL function prefers for\n** its parameters.  Every SQL function implementation must be able to work\n** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be\n** more efficient with one encoding than another.  ^An application may\n** invoke sqlite3_create_function() or sqlite3_create_function16() multiple\n** times with the same function but with different values of eTextRep.\n** ^When multiple implementations of the same function are available, SQLite\n** will pick the one that involves the least amount of data conversion.\n** If there is only a single implementation which does not care what text\n** encoding is used, then the fourth argument should be [SQLITE_ANY].\n**\n** ^(The fifth parameter is an arbitrary pointer.  The implementation of the\n** function can gain access to this pointer using [sqlite3_user_data()].)^\n**\n** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are\n** pointers to C-language functions that implement the SQL function or\n** aggregate. ^A scalar SQL function requires an implementation of the xFunc\n** callback only; NULL pointers must be passed as the xStep and xFinal\n** parameters. ^An aggregate SQL function requires an implementation of xStep\n** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing\n** SQL function or aggregate, pass NULL pointers for all three function\n** callbacks.\n**\n** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,\n** then it is destructor for the application data pointer. \n** The destructor is invoked when the function is deleted, either by being\n** overloaded or when the database connection closes.)^\n** ^The destructor is also invoked if the call to\n** sqlite3_create_function_v2() fails.\n** ^When the destructor callback of the tenth parameter is invoked, it\n** is passed a single argument which is a copy of the application data \n** pointer which was the fifth parameter to sqlite3_create_function_v2().\n**\n** ^It is permitted to register multiple implementations of the same\n** functions with the same name but with either differing numbers of\n** arguments or differing preferred text encodings.  ^SQLite will use\n** the implementation that most closely matches the way in which the\n** SQL function is used.  ^A function implementation with a non-negative\n** nArg parameter is a better match than a function implementation with\n** a negative nArg.  ^A function where the preferred text encoding\n** matches the database encoding is a better\n** match than a function where the encoding is different.  \n** ^A function where the encoding difference is between UTF16le and UTF16be\n** is a closer match than a function where the encoding difference is\n** between UTF8 and UTF16.\n**\n** ^Built-in functions may be overloaded by new application-defined functions.\n**\n** ^An application-defined function is permitted to call other\n** SQLite interfaces.  However, such calls must not\n** close the database connection nor finalize or reset the prepared\n** statement in which the function is running.\n*/\nSQLITE_API int sqlite3_create_function(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function16(\n  sqlite3 *db,\n  const void *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*)\n);\nSQLITE_API int sqlite3_create_function_v2(\n  sqlite3 *db,\n  const char *zFunctionName,\n  int nArg,\n  int eTextRep,\n  void *pApp,\n  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),\n  void (*xStep)(sqlite3_context*,int,sqlite3_value**),\n  void (*xFinal)(sqlite3_context*),\n  void(*xDestroy)(void*)\n);\n\n/*\n** CAPI3REF: Text Encodings\n**\n** These constant define integer codes that represent the various\n** text encodings supported by SQLite.\n*/\n#define SQLITE_UTF8           1\n#define SQLITE_UTF16LE        2\n#define SQLITE_UTF16BE        3\n#define SQLITE_UTF16          4    /* Use native byte order */\n#define SQLITE_ANY            5    /* sqlite3_create_function only */\n#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */\n\n/*\n** CAPI3REF: Deprecated Functions\n** DEPRECATED\n**\n** These functions are [deprecated].  In order to maintain\n** backwards compatibility with older code, these functions continue \n** to be supported.  However, new applications should avoid\n** the use of these functions.  To help encourage people to avoid\n** using these functions, we are not going to tell you what they do.\n*/\n#ifndef SQLITE_OMIT_DEPRECATED\nSQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);\nSQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);\nSQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);\n#endif\n\n/*\n** CAPI3REF: Obtaining SQL Function Parameter Values\n**\n** The C-language implementation of SQL functions and aggregates uses\n** this set of interface routines to access the parameter values on\n** the function or aggregate.\n**\n** The xFunc (for scalar functions) or xStep (for aggregates) parameters\n** to [sqlite3_create_function()] and [sqlite3_create_function16()]\n** define callbacks that implement the SQL functions and aggregates.\n** The 3rd parameter to these callbacks is an array of pointers to\n** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for\n** each parameter to the SQL function.  These routines are used to\n** extract values from the [sqlite3_value] objects.\n**\n** These routines work only with [protected sqlite3_value] objects.\n** Any attempt to use these routines on an [unprotected sqlite3_value]\n** object results in undefined behavior.\n**\n** ^These routines work just like the corresponding [column access functions]\n** except that  these routines take a single [protected sqlite3_value] object\n** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.\n**\n** ^The sqlite3_value_text16() interface extracts a UTF-16 string\n** in the native byte-order of the host machine.  ^The\n** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces\n** extract UTF-16 strings as big-endian and little-endian respectively.\n**\n** ^(The sqlite3_value_numeric_type() interface attempts to apply\n** numeric affinity to the value.  This means that an attempt is\n** made to convert the value to an integer or floating point.  If\n** such a conversion is possible without loss of information (in other\n** words, if the value is a string that looks like a number)\n** then the conversion is performed.  Otherwise no conversion occurs.\n** The [SQLITE_INTEGER | datatype] after conversion is returned.)^\n**\n** Please pay particular attention to the fact that the pointer returned\n** from [sqlite3_value_blob()], [sqlite3_value_text()], or\n** [sqlite3_value_text16()] can be invalidated by a subsequent call to\n** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],\n** or [sqlite3_value_text16()].\n**\n** These routines must be called from the same thread as\n** the SQL function that supplied the [sqlite3_value*] parameters.\n*/\nSQLITE_API const void *sqlite3_value_blob(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes(sqlite3_value*);\nSQLITE_API int sqlite3_value_bytes16(sqlite3_value*);\nSQLITE_API double sqlite3_value_double(sqlite3_value*);\nSQLITE_API int sqlite3_value_int(sqlite3_value*);\nSQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);\nSQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);\nSQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);\nSQLITE_API int sqlite3_value_type(sqlite3_value*);\nSQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);\n\n/*\n** CAPI3REF: Obtain Aggregate Function Context\n**\n** Implementations of aggregate SQL functions use this\n** routine to allocate memory for storing their state.\n**\n** ^The first time the sqlite3_aggregate_context(C,N) routine is called \n** for a particular aggregate function, SQLite\n** allocates N of memory, zeroes out that memory, and returns a pointer\n** to the new memory. ^On second and subsequent calls to\n** sqlite3_aggregate_context() for the same aggregate function instance,\n** the same buffer is returned.  Sqlite3_aggregate_context() is normally\n** called once for each invocation of the xStep callback and then one\n** last time when the xFinal callback is invoked.  ^(When no rows match\n** an aggregate query, the xStep() callback of the aggregate function\n** implementation is never called and xFinal() is called exactly once.\n** In those cases, sqlite3_aggregate_context() might be called for the\n** first time from within xFinal().)^\n**\n** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is\n** less than or equal to zero or if a memory allocate error occurs.\n**\n** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is\n** determined by the N parameter on first successful call.  Changing the\n** value of N in subsequent call to sqlite3_aggregate_context() within\n** the same aggregate function instance will not resize the memory\n** allocation.)^\n**\n** ^SQLite automatically frees the memory allocated by \n** sqlite3_aggregate_context() when the aggregate query concludes.\n**\n** The first parameter must be a copy of the\n** [sqlite3_context | SQL function context] that is the first parameter\n** to the xStep or xFinal callback routine that implements the aggregate\n** function.\n**\n** This routine must be called from the same thread in which\n** the aggregate SQL function is running.\n*/\nSQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);\n\n/*\n** CAPI3REF: User Data For Functions\n**\n** ^The sqlite3_user_data() interface returns a copy of\n** the pointer that was the pUserData parameter (the 5th parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n**\n** This routine must be called from the same thread in which\n** the application-defined function is running.\n*/\nSQLITE_API void *sqlite3_user_data(sqlite3_context*);\n\n/*\n** CAPI3REF: Database Connection For Functions\n**\n** ^The sqlite3_context_db_handle() interface returns a copy of\n** the pointer to the [database connection] (the 1st parameter)\n** of the [sqlite3_create_function()]\n** and [sqlite3_create_function16()] routines that originally\n** registered the application defined function.\n*/\nSQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);\n\n/*\n** CAPI3REF: Function Auxiliary Data\n**\n** The following two functions may be used by scalar SQL functions to\n** associate metadata with argument values. If the same value is passed to\n** multiple invocations of the same SQL function during query execution, under\n** some circumstances the associated metadata may be preserved. This may\n** be used, for example, to add a regular-expression matching scalar\n** function. The compiled version of the regular expression is stored as\n** metadata associated with the SQL value passed as the regular expression\n** pattern.  The compiled regular expression can be reused on multiple\n** invocations of the same function so that the original pattern string\n** does not need to be recompiled on each invocation.\n**\n** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata\n** associated by the sqlite3_set_auxdata() function with the Nth argument\n** value to the application-defined function. ^If no metadata has been ever\n** been set for the Nth argument of the function, or if the corresponding\n** function parameter has changed since the meta-data was set,\n** then sqlite3_get_auxdata() returns a NULL pointer.\n**\n** ^The sqlite3_set_auxdata() interface saves the metadata\n** pointed to by its 3rd parameter as the metadata for the N-th\n** argument of the application-defined function.  Subsequent\n** calls to sqlite3_get_auxdata() might return this data, if it has\n** not been destroyed.\n** ^If it is not NULL, SQLite will invoke the destructor\n** function given by the 4th parameter to sqlite3_set_auxdata() on\n** the metadata when the corresponding function parameter changes\n** or when the SQL statement completes, whichever comes first.\n**\n** SQLite is free to call the destructor and drop metadata on any\n** parameter of any function at any time.  ^The only guarantee is that\n** the destructor will be called before the metadata is dropped.\n**\n** ^(In practice, metadata is preserved between function calls for\n** expressions that are constant at compile time. This includes literal\n** values and [parameters].)^\n**\n** These routines must be called from the same thread in which\n** the SQL function is running.\n*/\nSQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);\nSQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));\n\n\n/*\n** CAPI3REF: Constants Defining Special Destructor Behavior\n**\n** These are special values for the destructor that is passed in as the\n** final argument to routines like [sqlite3_result_blob()].  ^If the destructor\n** argument is SQLITE_STATIC, it means that the content pointer is constant\n** and will never change.  It does not need to be destroyed.  ^The\n** SQLITE_TRANSIENT value means that the content will likely change in\n** the near future and that SQLite should make its own private copy of\n** the content before returning.\n**\n** The typedef is necessary to work around problems in certain\n** C++ compilers.  See ticket #2191.\n*/\ntypedef void (*sqlite3_destructor_type)(void*);\n#define SQLITE_STATIC      ((sqlite3_destructor_type)0)\n#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)\n\n/*\n** CAPI3REF: Setting The Result Of An SQL Function\n**\n** These routines are used by the xFunc or xFinal callbacks that\n** implement SQL functions and aggregates.  See\n** [sqlite3_create_function()] and [sqlite3_create_function16()]\n** for additional information.\n**\n** These functions work very much like the [parameter binding] family of\n** functions used to bind values to host parameters in prepared statements.\n** Refer to the [SQL parameter] documentation for additional information.\n**\n** ^The sqlite3_result_blob() interface sets the result from\n** an application-defined function to be the BLOB whose content is pointed\n** to by the second parameter and which is N bytes long where N is the\n** third parameter.\n**\n** ^The sqlite3_result_zeroblob() interfaces set the result of\n** the application-defined function to be a BLOB containing all zero\n** bytes and N bytes in size, where N is the value of the 2nd parameter.\n**\n** ^The sqlite3_result_double() interface sets the result from\n** an application-defined function to be a floating point value specified\n** by its 2nd argument.\n**\n** ^The sqlite3_result_error() and sqlite3_result_error16() functions\n** cause the implemented SQL function to throw an exception.\n** ^SQLite uses the string pointed to by the\n** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()\n** as the text of an error message.  ^SQLite interprets the error\n** message string from sqlite3_result_error() as UTF-8. ^SQLite\n** interprets the string from sqlite3_result_error16() as UTF-16 in native\n** byte order.  ^If the third parameter to sqlite3_result_error()\n** or sqlite3_result_error16() is negative then SQLite takes as the error\n** message all text up through the first zero character.\n** ^If the third parameter to sqlite3_result_error() or\n** sqlite3_result_error16() is non-negative then SQLite takes that many\n** bytes (not characters) from the 2nd parameter as the error message.\n** ^The sqlite3_result_error() and sqlite3_result_error16()\n** routines make a private copy of the error message text before\n** they return.  Hence, the calling function can deallocate or\n** modify the text after they return without harm.\n** ^The sqlite3_result_error_code() function changes the error code\n** returned by SQLite as a result of an error in a function.  ^By default,\n** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()\n** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.\n**\n** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an\n** error indicating that a string or BLOB is too long to represent.\n**\n** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an\n** error indicating that a memory allocation failed.\n**\n** ^The sqlite3_result_int() interface sets the return value\n** of the application-defined function to be the 32-bit signed integer\n** value given in the 2nd argument.\n** ^The sqlite3_result_int64() interface sets the return value\n** of the application-defined function to be the 64-bit signed integer\n** value given in the 2nd argument.\n**\n** ^The sqlite3_result_null() interface sets the return value\n** of the application-defined function to be NULL.\n**\n** ^The sqlite3_result_text(), sqlite3_result_text16(),\n** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces\n** set the return value of the application-defined function to be\n** a text string which is represented as UTF-8, UTF-16 native byte order,\n** UTF-16 little endian, or UTF-16 big endian, respectively.\n** ^SQLite takes the text result from the application from\n** the 2nd parameter of the sqlite3_result_text* interfaces.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is negative, then SQLite takes result text from the 2nd parameter\n** through the first zero character.\n** ^If the 3rd parameter to the sqlite3_result_text* interfaces\n** is non-negative, then as many bytes (not characters) of the text\n** pointed to by the 2nd parameter are taken as the application-defined\n** function result.  If the 3rd parameter is non-negative, then it\n** must be the byte offset into the string where the NUL terminator would\n** appear if the string where NUL terminated.  If any NUL characters occur\n** in the string at a byte offset that is less than the value of the 3rd\n** parameter, then the resulting string will contain embedded NULs and the\n** result of expressions operating on strings with embedded NULs is undefined.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that\n** function as the destructor on the text or BLOB result when it has\n** finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces or to\n** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite\n** assumes that the text or BLOB result is in constant space and does not\n** copy the content of the parameter nor call a destructor on the content\n** when it has finished using that result.\n** ^If the 4th parameter to the sqlite3_result_text* interfaces\n** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT\n** then SQLite makes a copy of the result into space obtained from\n** from [sqlite3_malloc()] before it returns.\n**\n** ^The sqlite3_result_value() interface sets the result of\n** the application-defined function to be a copy the\n** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The\n** sqlite3_result_value() interface makes a copy of the [sqlite3_value]\n** so that the [sqlite3_value] specified in the parameter may change or\n** be deallocated after sqlite3_result_value() returns without harm.\n** ^A [protected sqlite3_value] object may always be used where an\n** [unprotected sqlite3_value] object is required, so either\n** kind of [sqlite3_value] object can be used with this interface.\n**\n** If these routines are called from within the different thread\n** than the one containing the application-defined function that received\n** the [sqlite3_context] pointer, the results are undefined.\n*/\nSQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_double(sqlite3_context*, double);\nSQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);\nSQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);\nSQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);\nSQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int(sqlite3_context*, int);\nSQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);\nSQLITE_API void sqlite3_result_null(sqlite3_context*);\nSQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));\nSQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));\nSQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);\nSQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);\n\n/*\n** CAPI3REF: Define New Collating Sequences\n**\n** ^These functions add, remove, or modify a [collation] associated\n** with the [database connection] specified as the first argument.\n**\n** ^The name of the collation is a UTF-8 string\n** for sqlite3_create_collation() and sqlite3_create_collation_v2()\n** and a UTF-16 string in native byte order for sqlite3_create_collation16().\n** ^Collation names that compare equal according to [sqlite3_strnicmp()] are\n** considered to be the same name.\n**\n** ^(The third argument (eTextRep) must be one of the constants:\n** <ul>\n** <li> [SQLITE_UTF8],\n** <li> [SQLITE_UTF16LE],\n** <li> [SQLITE_UTF16BE],\n** <li> [SQLITE_UTF16], or\n** <li> [SQLITE_UTF16_ALIGNED].\n** </ul>)^\n** ^The eTextRep argument determines the encoding of strings passed\n** to the collating function callback, xCallback.\n** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep\n** force strings to be UTF16 with native byte order.\n** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin\n** on an even byte address.\n**\n** ^The fourth argument, pArg, is an application data pointer that is passed\n** through as the first argument to the collating function callback.\n**\n** ^The fifth argument, xCallback, is a pointer to the collating function.\n** ^Multiple collating functions can be registered using the same name but\n** with different eTextRep parameters and SQLite will use whichever\n** function requires the least amount of data transformation.\n** ^If the xCallback argument is NULL then the collating function is\n** deleted.  ^When all collating functions having the same name are deleted,\n** that collation is no longer usable.\n**\n** ^The collating function callback is invoked with a copy of the pArg \n** application data pointer and with two strings in the encoding specified\n** by the eTextRep argument.  The collating function must return an\n** integer that is negative, zero, or positive\n** if the first string is less than, equal to, or greater than the second,\n** respectively.  A collating function must always return the same answer\n** given the same inputs.  If two or more collating functions are registered\n** to the same collation name (using different eTextRep values) then all\n** must give an equivalent answer when invoked with equivalent strings.\n** The collating function must obey the following properties for all\n** strings A, B, and C:\n**\n** <ol>\n** <li> If A==B then B==A.\n** <li> If A==B and B==C then A==C.\n** <li> If A&lt;B THEN B&gt;A.\n** <li> If A&lt;B and B&lt;C then A&lt;C.\n** </ol>\n**\n** If a collating function fails any of the above constraints and that\n** collating function is  registered and used, then the behavior of SQLite\n** is undefined.\n**\n** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()\n** with the addition that the xDestroy callback is invoked on pArg when\n** the collating function is deleted.\n** ^Collating functions are deleted when they are overridden by later\n** calls to the collation creation functions or when the\n** [database connection] is closed using [sqlite3_close()].\n**\n** ^The xDestroy callback is <u>not</u> called if the \n** sqlite3_create_collation_v2() function fails.  Applications that invoke\n** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should \n** check the return code and dispose of the application data pointer\n** themselves rather than expecting SQLite to deal with it for them.\n** This is different from every other SQLite interface.  The inconsistency \n** is unfortunate but cannot be changed without breaking backwards \n** compatibility.\n**\n** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].\n*/\nSQLITE_API int sqlite3_create_collation(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\nSQLITE_API int sqlite3_create_collation_v2(\n  sqlite3*, \n  const char *zName, \n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*),\n  void(*xDestroy)(void*)\n);\nSQLITE_API int sqlite3_create_collation16(\n  sqlite3*, \n  const void *zName,\n  int eTextRep, \n  void *pArg,\n  int(*xCompare)(void*,int,const void*,int,const void*)\n);\n\n/*\n** CAPI3REF: Collation Needed Callbacks\n**\n** ^To avoid having to register all collation sequences before a database\n** can be used, a single callback function may be registered with the\n** [database connection] to be invoked whenever an undefined collation\n** sequence is required.\n**\n** ^If the function is registered using the sqlite3_collation_needed() API,\n** then it is passed the names of undefined collation sequences as strings\n** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,\n** the names are passed as UTF-16 in machine native byte order.\n** ^A call to either function replaces the existing collation-needed callback.\n**\n** ^(When the callback is invoked, the first argument passed is a copy\n** of the second argument to sqlite3_collation_needed() or\n** sqlite3_collation_needed16().  The second argument is the database\n** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],\n** or [SQLITE_UTF16LE], indicating the most desirable form of the collation\n** sequence function required.  The fourth parameter is the name of the\n** required collation sequence.)^\n**\n** The callback function should register the desired collation using\n** [sqlite3_create_collation()], [sqlite3_create_collation16()], or\n** [sqlite3_create_collation_v2()].\n*/\nSQLITE_API int sqlite3_collation_needed(\n  sqlite3*, \n  void*, \n  void(*)(void*,sqlite3*,int eTextRep,const char*)\n);\nSQLITE_API int sqlite3_collation_needed16(\n  sqlite3*, \n  void*,\n  void(*)(void*,sqlite3*,int eTextRep,const void*)\n);\n\n#ifdef SQLITE_HAS_CODEC\n/*\n** Specify the key for an encrypted database.  This routine should be\n** called right after sqlite3_open().\n**\n** The code to implement this API is not available in the public release\n** of SQLite.\n*/\nSQLITE_API int sqlite3_key(\n  sqlite3 *db,                   /* Database to be rekeyed */\n  const void *pKey, int nKey     /* The key */\n);\n\n/*\n** Change the key on an open database.  If the current database is not\n** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the\n** database is decrypted.\n**\n** The code to implement this API is not available in the public release\n** of SQLite.\n*/\nSQLITE_API int sqlite3_rekey(\n  sqlite3 *db,                   /* Database to be rekeyed */\n  const void *pKey, int nKey     /* The new key */\n);\n\n/*\n** Specify the activation key for a SEE database.  Unless \n** activated, none of the SEE routines will work.\n*/\nSQLITE_API void sqlite3_activate_see(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n#ifdef SQLITE_ENABLE_CEROD\n/*\n** Specify the activation key for a CEROD database.  Unless \n** activated, none of the CEROD routines will work.\n*/\nSQLITE_API void sqlite3_activate_cerod(\n  const char *zPassPhrase        /* Activation phrase */\n);\n#endif\n\n/*\n** CAPI3REF: Suspend Execution For A Short Time\n**\n** The sqlite3_sleep() function causes the current thread to suspend execution\n** for at least a number of milliseconds specified in its parameter.\n**\n** If the operating system does not support sleep requests with\n** millisecond time resolution, then the time will be rounded up to\n** the nearest second. The number of milliseconds of sleep actually\n** requested from the operating system is returned.\n**\n** ^SQLite implements this interface by calling the xSleep()\n** method of the default [sqlite3_vfs] object.  If the xSleep() method\n** of the default VFS is not implemented correctly, or not implemented at\n** all, then the behavior of sqlite3_sleep() may deviate from the description\n** in the previous paragraphs.\n*/\nSQLITE_API int sqlite3_sleep(int);\n\n/*\n** CAPI3REF: Name Of The Folder Holding Temporary Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all temporary files\n** created by SQLite when using a built-in [sqlite3_vfs | VFS]\n** will be placed in that directory.)^  ^If this variable\n** is a NULL pointer, then SQLite performs a search for an appropriate\n** temporary file directory.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [temp_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [temp_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [temp_store_directory pragma] should be avoided.\n**\n** <b>Note to Windows Runtime users:</b>  The temporary directory must be set\n** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various\n** features that require the use of temporary files may fail.  Here is an\n** example of how to do this using C++ with the Windows Runtime:\n**\n** <blockquote><pre>\n** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->\n** &nbsp;     TemporaryFolder->Path->Data();\n** char zPathBuf&#91;MAX_PATH + 1&#93;;\n** memset(zPathBuf, 0, sizeof(zPathBuf));\n** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),\n** &nbsp;     NULL, NULL);\n** sqlite3_temp_directory = sqlite3_mprintf(\"%s\", zPathBuf);\n** </pre></blockquote>\n*/\nSQLITE_API SQLITE_EXTERN char *sqlite3_temp_directory;\n\n/*\n** CAPI3REF: Name Of The Folder Holding Database Files\n**\n** ^(If this global variable is made to point to a string which is\n** the name of a folder (a.k.a. directory), then all database files\n** specified with a relative pathname and created or accessed by\n** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed\n** to be relative to that directory.)^ ^If this variable is a NULL\n** pointer, then SQLite assumes that all database files specified\n** with a relative pathname are relative to the current directory\n** for the process.  Only the windows VFS makes use of this global\n** variable; it is ignored by the unix VFS.\n**\n** Changing the value of this variable while a database connection is\n** open can result in a corrupt database.\n**\n** It is not safe to read or modify this variable in more than one\n** thread at a time.  It is not safe to read or modify this variable\n** if a [database connection] is being used at the same time in a separate\n** thread.\n** It is intended that this variable be set once\n** as part of process initialization and before any SQLite interface\n** routines have been called and that this variable remain unchanged\n** thereafter.\n**\n** ^The [data_store_directory pragma] may modify this variable and cause\n** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,\n** the [data_store_directory pragma] always assumes that any string\n** that this variable points to is held in memory obtained from \n** [sqlite3_malloc] and the pragma may attempt to free that memory\n** using [sqlite3_free].\n** Hence, if this variable is modified directly, either it should be\n** made NULL or made to point to memory obtained from [sqlite3_malloc]\n** or else the use of the [data_store_directory pragma] should be avoided.\n*/\nSQLITE_API SQLITE_EXTERN char *sqlite3_data_directory;\n\n/*\n** CAPI3REF: Test For Auto-Commit Mode\n** KEYWORDS: {autocommit mode}\n**\n** ^The sqlite3_get_autocommit() interface returns non-zero or\n** zero if the given database connection is or is not in autocommit mode,\n** respectively.  ^Autocommit mode is on by default.\n** ^Autocommit mode is disabled by a [BEGIN] statement.\n** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].\n**\n** If certain kinds of errors occur on a statement within a multi-statement\n** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],\n** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the\n** transaction might be rolled back automatically.  The only way to\n** find out whether SQLite automatically rolled back the transaction after\n** an error is to use this function.\n**\n** If another thread changes the autocommit status of the database\n** connection while this routine is running, then the return value\n** is undefined.\n*/\nSQLITE_API int sqlite3_get_autocommit(sqlite3*);\n\n/*\n** CAPI3REF: Find The Database Handle Of A Prepared Statement\n**\n** ^The sqlite3_db_handle interface returns the [database connection] handle\n** to which a [prepared statement] belongs.  ^The [database connection]\n** returned by sqlite3_db_handle is the same [database connection]\n** that was the first argument\n** to the [sqlite3_prepare_v2()] call (or its variants) that was used to\n** create the statement in the first place.\n*/\nSQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);\n\n/*\n** CAPI3REF: Return The Filename For A Database Connection\n**\n** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename\n** associated with database N of connection D.  ^The main database file\n** has the name \"main\".  If there is no attached database N on the database\n** connection D, or if database N is a temporary or in-memory database, then\n** a NULL pointer is returned.\n**\n** ^The filename returned by this function is the output of the\n** xFullPathname method of the [VFS].  ^In other words, the filename\n** will be an absolute pathname, even if the filename used\n** to open the database originally was a URI or relative pathname.\n*/\nSQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Determine if a database is read-only\n**\n** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N\n** of connection D is read-only, 0 if it is read/write, or -1 if N is not\n** the name of a database on connection D.\n*/\nSQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);\n\n/*\n** CAPI3REF: Find the next prepared statement\n**\n** ^This interface returns a pointer to the next [prepared statement] after\n** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL\n** then this interface returns a pointer to the first prepared statement\n** associated with the database connection pDb.  ^If no prepared statement\n** satisfies the conditions of this routine, it returns NULL.\n**\n** The [database connection] pointer D in a call to\n** [sqlite3_next_stmt(D,S)] must refer to an open database\n** connection and in particular must not be a NULL pointer.\n*/\nSQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);\n\n/*\n** CAPI3REF: Commit And Rollback Notification Callbacks\n**\n** ^The sqlite3_commit_hook() interface registers a callback\n** function to be invoked whenever a transaction is [COMMIT | committed].\n** ^Any callback set by a previous call to sqlite3_commit_hook()\n** for the same database connection is overridden.\n** ^The sqlite3_rollback_hook() interface registers a callback\n** function to be invoked whenever a transaction is [ROLLBACK | rolled back].\n** ^Any callback set by a previous call to sqlite3_rollback_hook()\n** for the same database connection is overridden.\n** ^The pArg argument is passed through to the callback.\n** ^If the callback on a commit hook function returns non-zero,\n** then the commit is converted into a rollback.\n**\n** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions\n** return the P argument from the previous call of the same function\n** on the same [database connection] D, or NULL for\n** the first call for each function on D.\n**\n** The commit and rollback hook callbacks are not reentrant.\n** The callback implementation must not do anything that will modify\n** the database connection that invoked the callback.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the commit\n** or rollback hook in the first place.\n** Note that running any other SQL statements, including SELECT statements,\n** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify\n** the database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^Registering a NULL function disables the callback.\n**\n** ^When the commit hook callback routine returns zero, the [COMMIT]\n** operation is allowed to continue normally.  ^If the commit hook\n** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].\n** ^The rollback hook is invoked on a rollback that results from a commit\n** hook returning non-zero, just as it would be with any other rollback.\n**\n** ^For the purposes of this API, a transaction is said to have been\n** rolled back if an explicit \"ROLLBACK\" statement is executed, or\n** an error or constraint causes an implicit rollback to occur.\n** ^The rollback callback is not invoked if a transaction is\n** automatically rolled back because the database connection is closed.\n**\n** See also the [sqlite3_update_hook()] interface.\n*/\nSQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);\nSQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);\n\n/*\n** CAPI3REF: Data Change Notification Callbacks\n**\n** ^The sqlite3_update_hook() interface registers a callback function\n** with the [database connection] identified by the first argument\n** to be invoked whenever a row is updated, inserted or deleted.\n** ^Any callback set by a previous call to this function\n** for the same database connection is overridden.\n**\n** ^The second argument is a pointer to the function to invoke when a\n** row is updated, inserted or deleted.\n** ^The first argument to the callback is a copy of the third argument\n** to sqlite3_update_hook().\n** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],\n** or [SQLITE_UPDATE], depending on the operation that caused the callback\n** to be invoked.\n** ^The third and fourth arguments to the callback contain pointers to the\n** database and table name containing the affected row.\n** ^The final callback parameter is the [rowid] of the row.\n** ^In the case of an update, this is the [rowid] after the update takes place.\n**\n** ^(The update hook is not invoked when internal system tables are\n** modified (i.e. sqlite_master and sqlite_sequence).)^\n**\n** ^In the current implementation, the update hook\n** is not invoked when duplication rows are deleted because of an\n** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook\n** invoked when rows are deleted using the [truncate optimization].\n** The exceptions defined in this paragraph might change in a future\n** release of SQLite.\n**\n** The update hook implementation must not do anything that will modify\n** the database connection that invoked the update hook.  Any actions\n** to modify the database connection must be deferred until after the\n** completion of the [sqlite3_step()] call that triggered the update hook.\n** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their\n** database connections for the meaning of \"modify\" in this paragraph.\n**\n** ^The sqlite3_update_hook(D,C,P) function\n** returns the P argument from the previous call\n** on the same [database connection] D, or NULL for\n** the first call on D.\n**\n** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]\n** interfaces.\n*/\nSQLITE_API void *sqlite3_update_hook(\n  sqlite3*, \n  void(*)(void *,int ,char const *,char const *,sqlite3_int64),\n  void*\n);\n\n/*\n** CAPI3REF: Enable Or Disable Shared Pager Cache\n**\n** ^(This routine enables or disables the sharing of the database cache\n** and schema data structures between [database connection | connections]\n** to the same database. Sharing is enabled if the argument is true\n** and disabled if the argument is false.)^\n**\n** ^Cache sharing is enabled and disabled for an entire process.\n** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,\n** sharing was enabled or disabled for each thread separately.\n**\n** ^(The cache sharing mode set by this interface effects all subsequent\n** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].\n** Existing database connections continue use the sharing mode\n** that was in effect at the time they were opened.)^\n**\n** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled\n** successfully.  An [error code] is returned otherwise.)^\n**\n** ^Shared cache is disabled by default. But this might change in\n** future releases of SQLite.  Applications that care about shared\n** cache setting should set it explicitly.\n**\n** See Also:  [SQLite Shared-Cache Mode]\n*/\nSQLITE_API int sqlite3_enable_shared_cache(int);\n\n/*\n** CAPI3REF: Attempt To Free Heap Memory\n**\n** ^The sqlite3_release_memory() interface attempts to free N bytes\n** of heap memory by deallocating non-essential memory allocations\n** held by the database library.   Memory used to cache database\n** pages to improve performance is an example of non-essential memory.\n** ^sqlite3_release_memory() returns the number of bytes actually freed,\n** which might be more or less than the amount requested.\n** ^The sqlite3_release_memory() routine is a no-op returning zero\n** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** See also: [sqlite3_db_release_memory()]\n*/\nSQLITE_API int sqlite3_release_memory(int);\n\n/*\n** CAPI3REF: Free Memory Used By A Database Connection\n**\n** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap\n** memory as possible from database connection D. Unlike the\n** [sqlite3_release_memory()] interface, this interface is effect even\n** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is\n** omitted.\n**\n** See also: [sqlite3_release_memory()]\n*/\nSQLITE_API int sqlite3_db_release_memory(sqlite3*);\n\n/*\n** CAPI3REF: Impose A Limit On Heap Size\n**\n** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the\n** soft limit on the amount of heap memory that may be allocated by SQLite.\n** ^SQLite strives to keep heap memory utilization below the soft heap\n** limit by reducing the number of pages held in the page cache\n** as heap memory usages approaches the limit.\n** ^The soft heap limit is \"soft\" because even though SQLite strives to stay\n** below the limit, it will exceed the limit rather than generate\n** an [SQLITE_NOMEM] error.  In other words, the soft heap limit \n** is advisory only.\n**\n** ^The return value from sqlite3_soft_heap_limit64() is the size of\n** the soft heap limit prior to the call, or negative in the case of an\n** error.  ^If the argument N is negative\n** then no change is made to the soft heap limit.  Hence, the current\n** size of the soft heap limit can be determined by invoking\n** sqlite3_soft_heap_limit64() with a negative argument.\n**\n** ^If the argument N is zero then the soft heap limit is disabled.\n**\n** ^(The soft heap limit is not enforced in the current implementation\n** if one or more of following conditions are true:\n**\n** <ul>\n** <li> The soft heap limit is set to zero.\n** <li> Memory accounting is disabled using a combination of the\n**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and\n**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.\n** <li> An alternative page cache implementation is specified using\n**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).\n** <li> The page cache allocates from its own memory pool supplied\n**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than\n**      from the heap.\n** </ul>)^\n**\n** Beginning with SQLite version 3.7.3, the soft heap limit is enforced\n** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]\n** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],\n** the soft heap limit is enforced on every memory allocation.  Without\n** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced\n** when memory is allocated by the page cache.  Testing suggests that because\n** the page cache is the predominate memory user in SQLite, most\n** applications will achieve adequate soft heap limit enforcement without\n** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].\n**\n** The circumstances under which SQLite will enforce the soft heap limit may\n** changes in future releases of SQLite.\n*/\nSQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);\n\n/*\n** CAPI3REF: Deprecated Soft Heap Limit Interface\n** DEPRECATED\n**\n** This is a deprecated version of the [sqlite3_soft_heap_limit64()]\n** interface.  This routine is provided for historical compatibility\n** only.  All new applications should use the\n** [sqlite3_soft_heap_limit64()] interface rather than this one.\n*/\nSQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);\n\n\n/*\n** CAPI3REF: Extract Metadata About A Column Of A Table\n**\n** ^This routine returns metadata about a specific column of a specific\n** database table accessible using the [database connection] handle\n** passed as the first function argument.\n**\n** ^The column is identified by the second, third and fourth parameters to\n** this function. ^The second parameter is either the name of the database\n** (i.e. \"main\", \"temp\", or an attached database) containing the specified\n** table or NULL. ^If it is NULL, then all attached databases are searched\n** for the table using the same algorithm used by the database engine to\n** resolve unqualified table references.\n**\n** ^The third and fourth parameters to this function are the table and column\n** name of the desired column, respectively. Neither of these parameters\n** may be NULL.\n**\n** ^Metadata is returned by writing to the memory locations passed as the 5th\n** and subsequent parameters to this function. ^Any of these arguments may be\n** NULL, in which case the corresponding element of metadata is omitted.\n**\n** ^(<blockquote>\n** <table border=\"1\">\n** <tr><th> Parameter <th> Output<br>Type <th>  Description\n**\n** <tr><td> 5th <td> const char* <td> Data type\n** <tr><td> 6th <td> const char* <td> Name of default collation sequence\n** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint\n** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY\n** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]\n** </table>\n** </blockquote>)^\n**\n** ^The memory pointed to by the character pointers returned for the\n** declaration type and collation sequence is valid only until the next\n** call to any SQLite API function.\n**\n** ^If the specified table is actually a view, an [error code] is returned.\n**\n** ^If the specified column is \"rowid\", \"oid\" or \"_rowid_\" and an\n** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output\n** parameters are set for the explicitly declared column. ^(If there is no\n** explicitly declared [INTEGER PRIMARY KEY] column, then the output\n** parameters are set as follows:\n**\n** <pre>\n**     data type: \"INTEGER\"\n**     collation sequence: \"BINARY\"\n**     not null: 0\n**     primary key: 1\n**     auto increment: 0\n** </pre>)^\n**\n** ^(This function may load one or more schemas from database files. If an\n** error occurs during this process, or if the requested table or column\n** cannot be found, an [error code] is returned and an error message left\n** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^\n**\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.\n*/\nSQLITE_API int sqlite3_table_column_metadata(\n  sqlite3 *db,                /* Connection handle */\n  const char *zDbName,        /* Database name or NULL */\n  const char *zTableName,     /* Table name */\n  const char *zColumnName,    /* Column name */\n  char const **pzDataType,    /* OUTPUT: Declared data type */\n  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */\n  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */\n  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */\n  int *pAutoinc               /* OUTPUT: True if column is auto-increment */\n);\n\n/*\n** CAPI3REF: Load An Extension\n**\n** ^This interface loads an SQLite extension library from the named file.\n**\n** ^The sqlite3_load_extension() interface attempts to load an\n** SQLite extension library contained in the file zFile.\n**\n** ^The entry point is zProc.\n** ^zProc may be 0, in which case the name of the entry point\n** defaults to \"sqlite3_extension_init\".\n** ^The sqlite3_load_extension() interface returns\n** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.\n** ^If an error occurs and pzErrMsg is not 0, then the\n** [sqlite3_load_extension()] interface shall attempt to\n** fill *pzErrMsg with error message text stored in memory\n** obtained from [sqlite3_malloc()]. The calling function\n** should free this memory by calling [sqlite3_free()].\n**\n** ^Extension loading must be enabled using\n** [sqlite3_enable_load_extension()] prior to calling this API,\n** otherwise an error will be returned.\n**\n** See also the [load_extension() SQL function].\n*/\nSQLITE_API int sqlite3_load_extension(\n  sqlite3 *db,          /* Load the extension into this database connection */\n  const char *zFile,    /* Name of the shared library containing extension */\n  const char *zProc,    /* Entry point.  Derived from zFile if 0 */\n  char **pzErrMsg       /* Put error message here if not 0 */\n);\n\n/*\n** CAPI3REF: Enable Or Disable Extension Loading\n**\n** ^So as not to open security holes in older applications that are\n** unprepared to deal with extension loading, and as a means of disabling\n** extension loading while evaluating user-entered SQL, the following API\n** is provided to turn the [sqlite3_load_extension()] mechanism on and off.\n**\n** ^Extension loading is off by default. See ticket #1863.\n** ^Call the sqlite3_enable_load_extension() routine with onoff==1\n** to turn extension loading on and call it with onoff==0 to turn\n** it back off again.\n*/\nSQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);\n\n/*\n** CAPI3REF: Automatically Load Statically Linked Extensions\n**\n** ^This interface causes the xEntryPoint() function to be invoked for\n** each new [database connection] that is created.  The idea here is that\n** xEntryPoint() is the entry point for a statically linked SQLite extension\n** that is to be automatically loaded into all new database connections.\n**\n** ^(Even though the function prototype shows that xEntryPoint() takes\n** no arguments and returns void, SQLite invokes xEntryPoint() with three\n** arguments and expects and integer result as if the signature of the\n** entry point where as follows:\n**\n** <blockquote><pre>\n** &nbsp;  int xEntryPoint(\n** &nbsp;    sqlite3 *db,\n** &nbsp;    const char **pzErrMsg,\n** &nbsp;    const struct sqlite3_api_routines *pThunk\n** &nbsp;  );\n** </pre></blockquote>)^\n**\n** If the xEntryPoint routine encounters an error, it should make *pzErrMsg\n** point to an appropriate error message (obtained from [sqlite3_mprintf()])\n** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg\n** is NULL before calling the xEntryPoint().  ^SQLite will invoke\n** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any\n** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],\n** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.\n**\n** ^Calling sqlite3_auto_extension(X) with an entry point X that is already\n** on the list of automatic extensions is a harmless no-op. ^No entry point\n** will be called more than once for each database connection that is opened.\n**\n** See also: [sqlite3_reset_auto_extension()].\n*/\nSQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));\n\n/*\n** CAPI3REF: Reset Automatic Extension Loading\n**\n** ^This interface disables all automatic extensions previously\n** registered using [sqlite3_auto_extension()].\n*/\nSQLITE_API void sqlite3_reset_auto_extension(void);\n\n/*\n** The interface to the virtual-table mechanism is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** Structures used by the virtual table interface\n*/\ntypedef struct sqlite3_vtab sqlite3_vtab;\ntypedef struct sqlite3_index_info sqlite3_index_info;\ntypedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;\ntypedef struct sqlite3_module sqlite3_module;\n\n/*\n** CAPI3REF: Virtual Table Object\n** KEYWORDS: sqlite3_module {virtual table module}\n**\n** This structure, sometimes called a \"virtual table module\", \n** defines the implementation of a [virtual tables].  \n** This structure consists mostly of methods for the module.\n**\n** ^A virtual table module is created by filling in a persistent\n** instance of this structure and passing a pointer to that instance\n** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].\n** ^The registration remains valid until it is replaced by a different\n** module or until the [database connection] closes.  The content\n** of this structure must not change while it is registered with\n** any database connection.\n*/\nstruct sqlite3_module {\n  int iVersion;\n  int (*xCreate)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xConnect)(sqlite3*, void *pAux,\n               int argc, const char *const*argv,\n               sqlite3_vtab **ppVTab, char**);\n  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);\n  int (*xDisconnect)(sqlite3_vtab *pVTab);\n  int (*xDestroy)(sqlite3_vtab *pVTab);\n  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);\n  int (*xClose)(sqlite3_vtab_cursor*);\n  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,\n                int argc, sqlite3_value **argv);\n  int (*xNext)(sqlite3_vtab_cursor*);\n  int (*xEof)(sqlite3_vtab_cursor*);\n  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);\n  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);\n  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);\n  int (*xBegin)(sqlite3_vtab *pVTab);\n  int (*xSync)(sqlite3_vtab *pVTab);\n  int (*xCommit)(sqlite3_vtab *pVTab);\n  int (*xRollback)(sqlite3_vtab *pVTab);\n  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,\n                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),\n                       void **ppArg);\n  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);\n  /* The methods above are in version 1 of the sqlite_module object. Those \n  ** below are for version 2 and greater. */\n  int (*xSavepoint)(sqlite3_vtab *pVTab, int);\n  int (*xRelease)(sqlite3_vtab *pVTab, int);\n  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);\n};\n\n/*\n** CAPI3REF: Virtual Table Indexing Information\n** KEYWORDS: sqlite3_index_info\n**\n** The sqlite3_index_info structure and its substructures is used as part\n** of the [virtual table] interface to\n** pass information into and receive the reply from the [xBestIndex]\n** method of a [virtual table module].  The fields under **Inputs** are the\n** inputs to xBestIndex and are read-only.  xBestIndex inserts its\n** results into the **Outputs** fields.\n**\n** ^(The aConstraint[] array records WHERE clause constraints of the form:\n**\n** <blockquote>column OP expr</blockquote>\n**\n** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is\n** stored in aConstraint[].op using one of the\n** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^\n** ^(The index of the column is stored in\n** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the\n** expr on the right-hand side can be evaluated (and thus the constraint\n** is usable) and false if it cannot.)^\n**\n** ^The optimizer automatically inverts terms of the form \"expr OP column\"\n** and makes other simplifications to the WHERE clause in an attempt to\n** get as many WHERE clause terms into the form shown above as possible.\n** ^The aConstraint[] array only reports WHERE clause terms that are\n** relevant to the particular virtual table being queried.\n**\n** ^Information about the ORDER BY clause is stored in aOrderBy[].\n** ^Each term of aOrderBy records a column of the ORDER BY clause.\n**\n** The [xBestIndex] method must fill aConstraintUsage[] with information\n** about what parameters to pass to xFilter.  ^If argvIndex>0 then\n** the right-hand side of the corresponding aConstraint[] is evaluated\n** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit\n** is true, then the constraint is assumed to be fully handled by the\n** virtual table and is not checked again by SQLite.)^\n**\n** ^The idxNum and idxPtr values are recorded and passed into the\n** [xFilter] method.\n** ^[sqlite3_free()] is used to free idxPtr if and only if\n** needToFreeIdxPtr is true.\n**\n** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in\n** the correct order to satisfy the ORDER BY clause so that no separate\n** sorting step is required.\n**\n** ^The estimatedCost value is an estimate of the cost of doing the\n** particular lookup.  A full scan of a table with N entries should have\n** a cost of N.  A binary search of a table of N entries should have a\n** cost of approximately log(N).\n*/\nstruct sqlite3_index_info {\n  /* Inputs */\n  int nConstraint;           /* Number of entries in aConstraint */\n  struct sqlite3_index_constraint {\n     int iColumn;              /* Column on left-hand side of constraint */\n     unsigned char op;         /* Constraint operator */\n     unsigned char usable;     /* True if this constraint is usable */\n     int iTermOffset;          /* Used internally - xBestIndex should ignore */\n  } *aConstraint;            /* Table of WHERE clause constraints */\n  int nOrderBy;              /* Number of terms in the ORDER BY clause */\n  struct sqlite3_index_orderby {\n     int iColumn;              /* Column number */\n     unsigned char desc;       /* True for DESC.  False for ASC. */\n  } *aOrderBy;               /* The ORDER BY clause */\n  /* Outputs */\n  struct sqlite3_index_constraint_usage {\n    int argvIndex;           /* if >0, constraint is part of argv to xFilter */\n    unsigned char omit;      /* Do not code a test for this constraint */\n  } *aConstraintUsage;\n  int idxNum;                /* Number used to identify the index */\n  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */\n  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */\n  int orderByConsumed;       /* True if output is already ordered */\n  double estimatedCost;      /* Estimated cost of using this index */\n};\n\n/*\n** CAPI3REF: Virtual Table Constraint Operator Codes\n**\n** These macros defined the allowed values for the\n** [sqlite3_index_info].aConstraint[].op field.  Each value represents\n** an operator that is part of a constraint term in the wHERE clause of\n** a query that uses a [virtual table].\n*/\n#define SQLITE_INDEX_CONSTRAINT_EQ    2\n#define SQLITE_INDEX_CONSTRAINT_GT    4\n#define SQLITE_INDEX_CONSTRAINT_LE    8\n#define SQLITE_INDEX_CONSTRAINT_LT    16\n#define SQLITE_INDEX_CONSTRAINT_GE    32\n#define SQLITE_INDEX_CONSTRAINT_MATCH 64\n\n/*\n** CAPI3REF: Register A Virtual Table Implementation\n**\n** ^These routines are used to register a new [virtual table module] name.\n** ^Module names must be registered before\n** creating a new [virtual table] using the module and before using a\n** preexisting [virtual table] for the module.\n**\n** ^The module name is registered on the [database connection] specified\n** by the first parameter.  ^The name of the module is given by the \n** second parameter.  ^The third parameter is a pointer to\n** the implementation of the [virtual table module].   ^The fourth\n** parameter is an arbitrary client data pointer that is passed through\n** into the [xCreate] and [xConnect] methods of the virtual table module\n** when a new virtual table is be being created or reinitialized.\n**\n** ^The sqlite3_create_module_v2() interface has a fifth parameter which\n** is a pointer to a destructor for the pClientData.  ^SQLite will\n** invoke the destructor function (if it is not NULL) when SQLite\n** no longer needs the pClientData pointer.  ^The destructor will also\n** be invoked if the call to sqlite3_create_module_v2() fails.\n** ^The sqlite3_create_module()\n** interface is equivalent to sqlite3_create_module_v2() with a NULL\n** destructor.\n*/\nSQLITE_API int sqlite3_create_module(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData          /* Client data for xCreate/xConnect */\n);\nSQLITE_API int sqlite3_create_module_v2(\n  sqlite3 *db,               /* SQLite connection to register module with */\n  const char *zName,         /* Name of the module */\n  const sqlite3_module *p,   /* Methods for the module */\n  void *pClientData,         /* Client data for xCreate/xConnect */\n  void(*xDestroy)(void*)     /* Module destructor function */\n);\n\n/*\n** CAPI3REF: Virtual Table Instance Object\n** KEYWORDS: sqlite3_vtab\n**\n** Every [virtual table module] implementation uses a subclass\n** of this object to describe a particular instance\n** of the [virtual table].  Each subclass will\n** be tailored to the specific needs of the module implementation.\n** The purpose of this superclass is to define certain fields that are\n** common to all module implementations.\n**\n** ^Virtual tables methods can set an error message by assigning a\n** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should\n** take care that any prior string is freed by a call to [sqlite3_free()]\n** prior to assigning a new string to zErrMsg.  ^After the error message\n** is delivered up to the client application, the string will be automatically\n** freed by sqlite3_free() and the zErrMsg field will be zeroed.\n*/\nstruct sqlite3_vtab {\n  const sqlite3_module *pModule;  /* The module for this virtual table */\n  int nRef;                       /* NO LONGER USED */\n  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Virtual Table Cursor Object\n** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}\n**\n** Every [virtual table module] implementation uses a subclass of the\n** following structure to describe cursors that point into the\n** [virtual table] and are used\n** to loop through the virtual table.  Cursors are created using the\n** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed\n** by the [sqlite3_module.xClose | xClose] method.  Cursors are used\n** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods\n** of the module.  Each module implementation will define\n** the content of a cursor structure to suit its own needs.\n**\n** This superclass exists in order to define fields of the cursor that\n** are common to all implementations.\n*/\nstruct sqlite3_vtab_cursor {\n  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */\n  /* Virtual table implementations will typically add additional fields */\n};\n\n/*\n** CAPI3REF: Declare The Schema Of A Virtual Table\n**\n** ^The [xCreate] and [xConnect] methods of a\n** [virtual table module] call this interface\n** to declare the format (the names and datatypes of the columns) of\n** the virtual tables they implement.\n*/\nSQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);\n\n/*\n** CAPI3REF: Overload A Function For A Virtual Table\n**\n** ^(Virtual tables can provide alternative implementations of functions\n** using the [xFindFunction] method of the [virtual table module].  \n** But global versions of those functions\n** must exist in order to be overloaded.)^\n**\n** ^(This API makes sure a global version of a function with a particular\n** name and number of parameters exists.  If no such function exists\n** before this API is called, a new function is created.)^  ^The implementation\n** of the new function always causes an exception to be thrown.  So\n** the new function is not good for anything by itself.  Its only\n** purpose is to be a placeholder function that can be overloaded\n** by a [virtual table].\n*/\nSQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);\n\n/*\n** The interface to the virtual-table mechanism defined above (back up\n** to a comment remarkably similar to this one) is currently considered\n** to be experimental.  The interface might change in incompatible ways.\n** If this is a problem for you, do not use the interface at this time.\n**\n** When the virtual-table mechanism stabilizes, we will declare the\n** interface fixed, support it indefinitely, and remove this comment.\n*/\n\n/*\n** CAPI3REF: A Handle To An Open BLOB\n** KEYWORDS: {BLOB handle} {BLOB handles}\n**\n** An instance of this object represents an open BLOB on which\n** [sqlite3_blob_open | incremental BLOB I/O] can be performed.\n** ^Objects of this type are created by [sqlite3_blob_open()]\n** and destroyed by [sqlite3_blob_close()].\n** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces\n** can be used to read or write small subsections of the BLOB.\n** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.\n*/\ntypedef struct sqlite3_blob sqlite3_blob;\n\n/*\n** CAPI3REF: Open A BLOB For Incremental I/O\n**\n** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located\n** in row iRow, column zColumn, table zTable in database zDb;\n** in other words, the same BLOB that would be selected by:\n**\n** <pre>\n**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;\n** </pre>)^\n**\n** ^If the flags parameter is non-zero, then the BLOB is opened for read\n** and write access. ^If it is zero, the BLOB is opened for read access.\n** ^It is not possible to open a column that is part of an index or primary \n** key for writing. ^If [foreign key constraints] are enabled, it is \n** not possible to open a column that is part of a [child key] for writing.\n**\n** ^Note that the database name is not the filename that contains\n** the database but rather the symbolic name of the database that\n** appears after the AS keyword when the database is connected using [ATTACH].\n** ^For the main database file, the database name is \"main\".\n** ^For TEMP tables, the database name is \"temp\".\n**\n** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written\n** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set\n** to be a null pointer.)^\n** ^This function sets the [database connection] error code and message\n** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related\n** functions. ^Note that the *ppBlob variable is always initialized in a\n** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob\n** regardless of the success or failure of this routine.\n**\n** ^(If the row that a BLOB handle points to is modified by an\n** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects\n** then the BLOB handle is marked as \"expired\".\n** This is true if any column of the row is changed, even a column\n** other than the one the BLOB handle is open on.)^\n** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for\n** an expired BLOB handle fail with a return code of [SQLITE_ABORT].\n** ^(Changes written into a BLOB prior to the BLOB expiring are not\n** rolled back by the expiration of the BLOB.  Such changes will eventually\n** commit if the transaction continues to completion.)^\n**\n** ^Use the [sqlite3_blob_bytes()] interface to determine the size of\n** the opened blob.  ^The size of a blob may not be changed by this\n** interface.  Use the [UPDATE] SQL command to change the size of a\n** blob.\n**\n** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces\n** and the built-in [zeroblob] SQL function can be used, if desired,\n** to create an empty, zero-filled blob in which to read or write using\n** this interface.\n**\n** To avoid a resource leak, every open [BLOB handle] should eventually\n** be released by a call to [sqlite3_blob_close()].\n*/\nSQLITE_API int sqlite3_blob_open(\n  sqlite3*,\n  const char *zDb,\n  const char *zTable,\n  const char *zColumn,\n  sqlite3_int64 iRow,\n  int flags,\n  sqlite3_blob **ppBlob\n);\n\n/*\n** CAPI3REF: Move a BLOB Handle to a New Row\n**\n** ^This function is used to move an existing blob handle so that it points\n** to a different row of the same database table. ^The new row is identified\n** by the rowid value passed as the second argument. Only the row can be\n** changed. ^The database, table and column on which the blob handle is open\n** remain the same. Moving an existing blob handle to a new row can be\n** faster than closing the existing handle and opening a new one.\n**\n** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -\n** it must exist and there must be either a blob or text value stored in\n** the nominated column.)^ ^If the new row is not present in the table, or if\n** it does not contain a blob or text value, or if another error occurs, an\n** SQLite error code is returned and the blob handle is considered aborted.\n** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or\n** [sqlite3_blob_reopen()] on an aborted blob handle immediately return\n** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle\n** always returns zero.\n**\n** ^This function sets the database handle error code and message.\n*/\nSQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);\n\n/*\n** CAPI3REF: Close A BLOB Handle\n**\n** ^Closes an open [BLOB handle].\n**\n** ^Closing a BLOB shall cause the current transaction to commit\n** if there are no other BLOBs, no pending prepared statements, and the\n** database connection is in [autocommit mode].\n** ^If any writes were made to the BLOB, they might be held in cache\n** until the close operation if they will fit.\n**\n** ^(Closing the BLOB often forces the changes\n** out to disk and so if any I/O errors occur, they will likely occur\n** at the time when the BLOB is closed.  Any errors that occur during\n** closing are reported as a non-zero return value.)^\n**\n** ^(The BLOB is closed unconditionally.  Even if this routine returns\n** an error code, the BLOB is still closed.)^\n**\n** ^Calling this routine with a null pointer (such as would be returned\n** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.\n*/\nSQLITE_API int sqlite3_blob_close(sqlite3_blob *);\n\n/*\n** CAPI3REF: Return The Size Of An Open BLOB\n**\n** ^Returns the size in bytes of the BLOB accessible via the \n** successfully opened [BLOB handle] in its only argument.  ^The\n** incremental blob I/O routines can only read or overwriting existing\n** blob content; they cannot change the size of a blob.\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n*/\nSQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);\n\n/*\n** CAPI3REF: Read Data From A BLOB Incrementally\n**\n** ^(This function is used to read data from an open [BLOB handle] into a\n** caller-supplied buffer. N bytes of data are copied into buffer Z\n** from the open BLOB, starting at offset iOffset.)^\n**\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is\n** less than zero, [SQLITE_ERROR] is returned and no data is read.\n** ^The size of the blob (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to read from an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].\n**\n** ^(On success, sqlite3_blob_read() returns SQLITE_OK.\n** Otherwise, an [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_write()].\n*/\nSQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);\n\n/*\n** CAPI3REF: Write Data Into A BLOB Incrementally\n**\n** ^This function is used to write data into an open [BLOB handle] from a\n** caller-supplied buffer. ^N bytes of data are copied from the buffer Z\n** into the open BLOB, starting at offset iOffset.\n**\n** ^If the [BLOB handle] passed as the first argument was not opened for\n** writing (the flags parameter to [sqlite3_blob_open()] was zero),\n** this function returns [SQLITE_READONLY].\n**\n** ^This function may only modify the contents of the BLOB; it is\n** not possible to increase the size of a BLOB using this API.\n** ^If offset iOffset is less than N bytes from the end of the BLOB,\n** [SQLITE_ERROR] is returned and no data is written.  ^If N is\n** less than zero [SQLITE_ERROR] is returned and no data is written.\n** The size of the BLOB (and hence the maximum value of N+iOffset)\n** can be determined using the [sqlite3_blob_bytes()] interface.\n**\n** ^An attempt to write to an expired [BLOB handle] fails with an\n** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred\n** before the [BLOB handle] expired are not rolled back by the\n** expiration of the handle, though of course those changes might\n** have been overwritten by the statement that expired the BLOB handle\n** or by other independent statements.\n**\n** ^(On success, sqlite3_blob_write() returns SQLITE_OK.\n** Otherwise, an  [error code] or an [extended error code] is returned.)^\n**\n** This routine only works on a [BLOB handle] which has been created\n** by a prior successful call to [sqlite3_blob_open()] and which has not\n** been closed by [sqlite3_blob_close()].  Passing any other pointer in\n** to this routine results in undefined and probably undesirable behavior.\n**\n** See also: [sqlite3_blob_read()].\n*/\nSQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);\n\n/*\n** CAPI3REF: Virtual File System Objects\n**\n** A virtual filesystem (VFS) is an [sqlite3_vfs] object\n** that SQLite uses to interact\n** with the underlying operating system.  Most SQLite builds come with a\n** single default VFS that is appropriate for the host computer.\n** New VFSes can be registered and existing VFSes can be unregistered.\n** The following interfaces are provided.\n**\n** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.\n** ^Names are case sensitive.\n** ^Names are zero-terminated UTF-8 strings.\n** ^If there is no match, a NULL pointer is returned.\n** ^If zVfsName is NULL then the default VFS is returned.\n**\n** ^New VFSes are registered with sqlite3_vfs_register().\n** ^Each new VFS becomes the default VFS if the makeDflt flag is set.\n** ^The same VFS can be registered multiple times without injury.\n** ^To make an existing VFS into the default VFS, register it again\n** with the makeDflt flag set.  If two different VFSes with the\n** same name are registered, the behavior is undefined.  If a\n** VFS is registered with a name that is NULL or an empty string,\n** then the behavior is undefined.\n**\n** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.\n** ^(If the default VFS is unregistered, another VFS is chosen as\n** the default.  The choice for the new VFS is arbitrary.)^\n*/\nSQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);\nSQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);\nSQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);\n\n/*\n** CAPI3REF: Mutexes\n**\n** The SQLite core uses these routines for thread\n** synchronization. Though they are intended for internal\n** use by SQLite, code that links against SQLite is\n** permitted to use any of these routines.\n**\n** The SQLite source code contains multiple implementations\n** of these mutex routines.  An appropriate implementation\n** is selected automatically at compile-time.  ^(The following\n** implementations are available in the SQLite core:\n**\n** <ul>\n** <li>   SQLITE_MUTEX_PTHREADS\n** <li>   SQLITE_MUTEX_W32\n** <li>   SQLITE_MUTEX_NOOP\n** </ul>)^\n**\n** ^The SQLITE_MUTEX_NOOP implementation is a set of routines\n** that does no real locking and is appropriate for use in\n** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and\n** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix\n** and Windows.\n**\n** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor\n** macro defined (with \"-DSQLITE_MUTEX_APPDEF=1\"), then no mutex\n** implementation is included with the library. In this case the\n** application must supply a custom mutex implementation using the\n** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function\n** before calling sqlite3_initialize() or any other public sqlite3_\n** function that calls sqlite3_initialize().)^\n**\n** ^The sqlite3_mutex_alloc() routine allocates a new\n** mutex and returns a pointer to it. ^If it returns NULL\n** that means that a mutex could not be allocated.  ^SQLite\n** will unwind its stack and return an error.  ^(The argument\n** to sqlite3_mutex_alloc() is one of these integer constants:\n**\n** <ul>\n** <li>  SQLITE_MUTEX_FAST\n** <li>  SQLITE_MUTEX_RECURSIVE\n** <li>  SQLITE_MUTEX_STATIC_MASTER\n** <li>  SQLITE_MUTEX_STATIC_MEM\n** <li>  SQLITE_MUTEX_STATIC_MEM2\n** <li>  SQLITE_MUTEX_STATIC_PRNG\n** <li>  SQLITE_MUTEX_STATIC_LRU\n** <li>  SQLITE_MUTEX_STATIC_LRU2\n** </ul>)^\n**\n** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)\n** cause sqlite3_mutex_alloc() to create\n** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE\n** is used but not necessarily so when SQLITE_MUTEX_FAST is used.\n** The mutex implementation does not need to make a distinction\n** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does\n** not want to.  ^SQLite will only request a recursive mutex in\n** cases where it really needs one.  ^If a faster non-recursive mutex\n** implementation is available on the host platform, the mutex subsystem\n** might return such a mutex in response to SQLITE_MUTEX_FAST.\n**\n** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other\n** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return\n** a pointer to a static preexisting mutex.  ^Six static mutexes are\n** used by the current version of SQLite.  Future versions of SQLite\n** may add additional static mutexes.  Static mutexes are for internal\n** use by SQLite only.  Applications that use SQLite mutexes should\n** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or\n** SQLITE_MUTEX_RECURSIVE.\n**\n** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST\n** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()\n** returns a different mutex on every call.  ^But for the static\n** mutex types, the same mutex is returned on every call that has\n** the same type number.\n**\n** ^The sqlite3_mutex_free() routine deallocates a previously\n** allocated dynamic mutex.  ^SQLite is careful to deallocate every\n** dynamic mutex that it allocates.  The dynamic mutexes must not be in\n** use when they are deallocated.  Attempting to deallocate a static\n** mutex results in undefined behavior.  ^SQLite never deallocates\n** a static mutex.\n**\n** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt\n** to enter a mutex.  ^If another thread is already within the mutex,\n** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return\n** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]\n** upon successful entry.  ^(Mutexes created using\n** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.\n** In such cases the,\n** mutex must be exited an equal number of times before another thread\n** can enter.)^  ^(If the same thread tries to enter any other\n** kind of mutex more than once, the behavior is undefined.\n** SQLite will never exhibit\n** such behavior in its own use of mutexes.)^\n**\n** ^(Some systems (for example, Windows 95) do not support the operation\n** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()\n** will always return SQLITE_BUSY.  The SQLite core only ever uses\n** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^\n**\n** ^The sqlite3_mutex_leave() routine exits a mutex that was\n** previously entered by the same thread.   ^(The behavior\n** is undefined if the mutex is not currently entered by the\n** calling thread or is not currently allocated.  SQLite will\n** never do either.)^\n**\n** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or\n** sqlite3_mutex_leave() is a NULL pointer, then all three routines\n** behave as no-ops.\n**\n** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].\n*/\nSQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);\nSQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);\nSQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);\n\n/*\n** CAPI3REF: Mutex Methods Object\n**\n** An instance of this structure defines the low-level routines\n** used to allocate and use mutexes.\n**\n** Usually, the default mutex implementations provided by SQLite are\n** sufficient, however the user has the option of substituting a custom\n** implementation for specialized deployments or systems for which SQLite\n** does not provide a suitable implementation. In this case, the user\n** creates and populates an instance of this structure to pass\n** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.\n** Additionally, an instance of this structure can be used as an\n** output variable when querying the system for the current mutex\n** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.\n**\n** ^The xMutexInit method defined by this structure is invoked as\n** part of system initialization by the sqlite3_initialize() function.\n** ^The xMutexInit routine is called by SQLite exactly once for each\n** effective call to [sqlite3_initialize()].\n**\n** ^The xMutexEnd method defined by this structure is invoked as\n** part of system shutdown by the sqlite3_shutdown() function. The\n** implementation of this method is expected to release all outstanding\n** resources obtained by the mutex methods implementation, especially\n** those obtained by the xMutexInit method.  ^The xMutexEnd()\n** interface is invoked exactly once for each call to [sqlite3_shutdown()].\n**\n** ^(The remaining seven methods defined by this structure (xMutexAlloc,\n** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and\n** xMutexNotheld) implement the following interfaces (respectively):\n**\n** <ul>\n**   <li>  [sqlite3_mutex_alloc()] </li>\n**   <li>  [sqlite3_mutex_free()] </li>\n**   <li>  [sqlite3_mutex_enter()] </li>\n**   <li>  [sqlite3_mutex_try()] </li>\n**   <li>  [sqlite3_mutex_leave()] </li>\n**   <li>  [sqlite3_mutex_held()] </li>\n**   <li>  [sqlite3_mutex_notheld()] </li>\n** </ul>)^\n**\n** The only difference is that the public sqlite3_XXX functions enumerated\n** above silently ignore any invocations that pass a NULL pointer instead\n** of a valid mutex handle. The implementations of the methods defined\n** by this structure are not required to handle this case, the results\n** of passing a NULL pointer instead of a valid mutex handle are undefined\n** (i.e. it is acceptable to provide an implementation that segfaults if\n** it is passed a NULL pointer).\n**\n** The xMutexInit() method must be threadsafe.  ^It must be harmless to\n** invoke xMutexInit() multiple times within the same process and without\n** intervening calls to xMutexEnd().  Second and subsequent calls to\n** xMutexInit() must be no-ops.\n**\n** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]\n** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory\n** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite\n** memory allocation for a fast or recursive mutex.\n**\n** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is\n** called, but only if the prior call to xMutexInit returned SQLITE_OK.\n** If xMutexInit fails in any way, it is expected to clean up after itself\n** prior to returning.\n*/\ntypedef struct sqlite3_mutex_methods sqlite3_mutex_methods;\nstruct sqlite3_mutex_methods {\n  int (*xMutexInit)(void);\n  int (*xMutexEnd)(void);\n  sqlite3_mutex *(*xMutexAlloc)(int);\n  void (*xMutexFree)(sqlite3_mutex *);\n  void (*xMutexEnter)(sqlite3_mutex *);\n  int (*xMutexTry)(sqlite3_mutex *);\n  void (*xMutexLeave)(sqlite3_mutex *);\n  int (*xMutexHeld)(sqlite3_mutex *);\n  int (*xMutexNotheld)(sqlite3_mutex *);\n};\n\n/*\n** CAPI3REF: Mutex Verification Routines\n**\n** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines\n** are intended for use inside assert() statements.  ^The SQLite core\n** never uses these routines except inside an assert() and applications\n** are advised to follow the lead of the core.  ^The SQLite core only\n** provides implementations for these routines when it is compiled\n** with the SQLITE_DEBUG flag.  ^External mutex implementations\n** are only required to provide these routines if SQLITE_DEBUG is\n** defined and if NDEBUG is not defined.\n**\n** ^These routines should return true if the mutex in their argument\n** is held or not held, respectively, by the calling thread.\n**\n** ^The implementation is not required to provide versions of these\n** routines that actually work. If the implementation does not provide working\n** versions of these routines, it should at least provide stubs that always\n** return true so that one does not get spurious assertion failures.\n**\n** ^If the argument to sqlite3_mutex_held() is a NULL pointer then\n** the routine should return 1.   This seems counter-intuitive since\n** clearly the mutex cannot be held if it does not exist.  But\n** the reason the mutex does not exist is because the build is not\n** using mutexes.  And we do not want the assert() containing the\n** call to sqlite3_mutex_held() to fail, so a non-zero return is\n** the appropriate thing to do.  ^The sqlite3_mutex_notheld()\n** interface should also return 1 when given a NULL pointer.\n*/\n#ifndef NDEBUG\nSQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);\nSQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);\n#endif\n\n/*\n** CAPI3REF: Mutex Types\n**\n** The [sqlite3_mutex_alloc()] interface takes a single argument\n** which is one of these integer constants.\n**\n** The set of static mutexes may change from one SQLite release to the\n** next.  Applications that override the built-in mutex logic must be\n** prepared to accommodate additional static mutexes.\n*/\n#define SQLITE_MUTEX_FAST             0\n#define SQLITE_MUTEX_RECURSIVE        1\n#define SQLITE_MUTEX_STATIC_MASTER    2\n#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */\n#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */\n#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */\n#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */\n#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */\n#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */\n\n/*\n** CAPI3REF: Retrieve the mutex for a database connection\n**\n** ^This interface returns a pointer the [sqlite3_mutex] object that \n** serializes access to the [database connection] given in the argument\n** when the [threading mode] is Serialized.\n** ^If the [threading mode] is Single-thread or Multi-thread then this\n** routine returns a NULL pointer.\n*/\nSQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);\n\n/*\n** CAPI3REF: Low-Level Control Of Database Files\n**\n** ^The [sqlite3_file_control()] interface makes a direct call to the\n** xFileControl method for the [sqlite3_io_methods] object associated\n** with a particular database identified by the second argument. ^The\n** name of the database is \"main\" for the main database or \"temp\" for the\n** TEMP database, or the name that appears after the AS keyword for\n** databases that are added using the [ATTACH] SQL command.\n** ^A NULL pointer can be used in place of \"main\" to refer to the\n** main database file.\n** ^The third and fourth parameters to this routine\n** are passed directly through to the second and third parameters of\n** the xFileControl method.  ^The return value of the xFileControl\n** method becomes the return value of this routine.\n**\n** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes\n** a pointer to the underlying [sqlite3_file] object to be written into\n** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER\n** case is a short-circuit path which does not actually invoke the\n** underlying sqlite3_io_methods.xFileControl method.\n**\n** ^If the second parameter (zDbName) does not match the name of any\n** open database file, then SQLITE_ERROR is returned.  ^This error\n** code is not remembered and will not be recalled by [sqlite3_errcode()]\n** or [sqlite3_errmsg()].  The underlying xFileControl method might\n** also return SQLITE_ERROR.  There is no way to distinguish between\n** an incorrect zDbName and an SQLITE_ERROR return from the underlying\n** xFileControl method.\n**\n** See also: [SQLITE_FCNTL_LOCKSTATE]\n*/\nSQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);\n\n/*\n** CAPI3REF: Testing Interface\n**\n** ^The sqlite3_test_control() interface is used to read out internal\n** state of SQLite and to inject faults into SQLite for testing\n** purposes.  ^The first parameter is an operation code that determines\n** the number, meaning, and operation of all subsequent parameters.\n**\n** This interface is not for use by applications.  It exists solely\n** for verifying the correct operation of the SQLite library.  Depending\n** on how the SQLite library is compiled, this interface might not exist.\n**\n** The details of the operation codes, their meanings, the parameters\n** they take, and what they do are all subject to change without notice.\n** Unlike most of the SQLite API, this function is not guaranteed to\n** operate consistently from one release to the next.\n*/\nSQLITE_API int sqlite3_test_control(int op, ...);\n\n/*\n** CAPI3REF: Testing Interface Operation Codes\n**\n** These constants are the valid operation code parameters used\n** as the first argument to [sqlite3_test_control()].\n**\n** These parameters and their meanings are subject to change\n** without notice.  These values are for testing purposes only.\n** Applications should not use any of these parameters or the\n** [sqlite3_test_control()] interface.\n*/\n#define SQLITE_TESTCTRL_FIRST                    5\n#define SQLITE_TESTCTRL_PRNG_SAVE                5\n#define SQLITE_TESTCTRL_PRNG_RESTORE             6\n#define SQLITE_TESTCTRL_PRNG_RESET               7\n#define SQLITE_TESTCTRL_BITVEC_TEST              8\n#define SQLITE_TESTCTRL_FAULT_INSTALL            9\n#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10\n#define SQLITE_TESTCTRL_PENDING_BYTE            11\n#define SQLITE_TESTCTRL_ASSERT                  12\n#define SQLITE_TESTCTRL_ALWAYS                  13\n#define SQLITE_TESTCTRL_RESERVE                 14\n#define SQLITE_TESTCTRL_OPTIMIZATIONS           15\n#define SQLITE_TESTCTRL_ISKEYWORD               16\n#define SQLITE_TESTCTRL_SCRATCHMALLOC           17\n#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18\n#define SQLITE_TESTCTRL_EXPLAIN_STMT            19\n#define SQLITE_TESTCTRL_LAST                    19\n\n/*\n** CAPI3REF: SQLite Runtime Status\n**\n** ^This interface is used to retrieve runtime status information\n** about the performance of SQLite, and optionally to reset various\n** highwater marks.  ^The first argument is an integer code for\n** the specific parameter to measure.  ^(Recognized integer codes\n** are of the form [status parameters | SQLITE_STATUS_...].)^\n** ^The current value of the parameter is returned into *pCurrent.\n** ^The highest recorded value is returned in *pHighwater.  ^If the\n** resetFlag is true, then the highest record value is reset after\n** *pHighwater is written.  ^(Some parameters do not record the highest\n** value.  For those parameters\n** nothing is written into *pHighwater and the resetFlag is ignored.)^\n** ^(Other parameters record only the highwater mark and not the current\n** value.  For these latter parameters nothing is written into *pCurrent.)^\n**\n** ^The sqlite3_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** This routine is threadsafe but is not atomic.  This routine can be\n** called while other threads are running the same or different SQLite\n** interfaces.  However the values returned in *pCurrent and\n** *pHighwater reflect the status of SQLite at different points in time\n** and it is possible that another thread might change the parameter\n** in between the times when *pCurrent and *pHighwater are written.\n**\n** See also: [sqlite3_db_status()]\n*/\nSQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);\n\n\n/*\n** CAPI3REF: Status Parameters\n** KEYWORDS: {status parameters}\n**\n** These integer constants designate various run-time status parameters\n** that can be returned by [sqlite3_status()].\n**\n** <dl>\n** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>\n** <dd>This parameter is the current amount of memory checked out\n** using [sqlite3_malloc()], either directly or indirectly.  The\n** figure includes calls made to [sqlite3_malloc()] by the application\n** and internal memory usage by the SQLite library.  Scratch memory\n** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache\n** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in\n** this parameter.  The amount returned is the sum of the allocation\n** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their\n** internal equivalents).  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>\n** <dd>This parameter records the number of separate memory allocations\n** currently checked out.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>\n** <dd>This parameter returns the number of pages used out of the\n** [pagecache memory allocator] that was configured using \n** [SQLITE_CONFIG_PAGECACHE].  The\n** value returned is in pages, not in bytes.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] \n** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of page cache\n** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The\n** returned value includes allocations that overflowed because they\n** where too large (they were larger than the \"sz\" parameter to\n** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because\n** no space was left in the page cache.</dd>)^\n**\n** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [pagecache memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>\n** <dd>This parameter returns the number of allocations used out of the\n** [scratch memory allocator] configured using\n** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not\n** in bytes.  Since a single thread may only have one scratch allocation\n** outstanding at time, this parameter also reports the number of threads\n** using scratch memory at the same time.</dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>\n** <dd>This parameter returns the number of bytes of scratch memory\n** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]\n** buffer and where forced to overflow to [sqlite3_malloc()].  The values\n** returned include overflows because the requested allocation was too\n** larger (that is, because the requested allocation was larger than the\n** \"sz\" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer\n** slots were available.\n** </dd>)^\n**\n** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>\n** <dd>This parameter records the largest memory allocation request\n** handed to [scratch memory allocator].  Only the value returned in the\n** *pHighwater parameter to [sqlite3_status()] is of interest.  \n** The value written into the *pCurrent parameter is undefined.</dd>)^\n**\n** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>\n** <dd>This parameter records the deepest parser stack.  It is only\n** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^\n** </dl>\n**\n** New status parameters may be added from time to time.\n*/\n#define SQLITE_STATUS_MEMORY_USED          0\n#define SQLITE_STATUS_PAGECACHE_USED       1\n#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2\n#define SQLITE_STATUS_SCRATCH_USED         3\n#define SQLITE_STATUS_SCRATCH_OVERFLOW     4\n#define SQLITE_STATUS_MALLOC_SIZE          5\n#define SQLITE_STATUS_PARSER_STACK         6\n#define SQLITE_STATUS_PAGECACHE_SIZE       7\n#define SQLITE_STATUS_SCRATCH_SIZE         8\n#define SQLITE_STATUS_MALLOC_COUNT         9\n\n/*\n** CAPI3REF: Database Connection Status\n**\n** ^This interface is used to retrieve runtime status information \n** about a single [database connection].  ^The first argument is the\n** database connection object to be interrogated.  ^The second argument\n** is an integer constant, taken from the set of\n** [SQLITE_DBSTATUS options], that\n** determines the parameter to interrogate.  The set of \n** [SQLITE_DBSTATUS options] is likely\n** to grow in future releases of SQLite.\n**\n** ^The current value of the requested parameter is written into *pCur\n** and the highest instantaneous value is written into *pHiwtr.  ^If\n** the resetFlg is true, then the highest instantaneous value is\n** reset back down to the current value.\n**\n** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a\n** non-zero [error code] on failure.\n**\n** See also: [sqlite3_status()] and [sqlite3_stmt_status()].\n*/\nSQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for database connections\n** KEYWORDS: {SQLITE_DBSTATUS options}\n**\n** These constants are the available integer \"verbs\" that can be passed as\n** the second argument to the [sqlite3_db_status()] interface.\n**\n** New verbs may be added in future releases of SQLite. Existing verbs\n** might be discontinued. Applications should check the return code from\n** [sqlite3_db_status()] to make sure that the call worked.\n** The [sqlite3_db_status()] interface will return a non-zero error code\n** if a discontinued or unsupported verb is invoked.\n**\n** <dl>\n** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>\n** <dd>This parameter returns the number of lookaside memory slots currently\n** checked out.</dd>)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>\n** <dd>This parameter returns the number malloc attempts that were \n** satisfied using lookaside memory. Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to the amount of\n** memory requested being larger than the lookaside slot size.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]\n** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>\n** <dd>This parameter returns the number malloc attempts that might have\n** been satisfied using lookaside memory but failed due to all lookaside\n** memory already being in use.\n** Only the high-water value is meaningful;\n** the current value is always zero.)^\n**\n** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** memory used by all pager caches associated with the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** memory used to store the schema for all databases associated\n** with the connection - main, temp, and any [ATTACH]-ed databases.)^ \n** ^The full amount of memory used by the schemas is reported, even if the\n** schema memory is shared with other database connections due to\n** [shared cache mode] being enabled.\n** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.\n**\n** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>\n** <dd>This parameter returns the approximate number of of bytes of heap\n** and lookaside memory used by all prepared statements associated with\n** the database connection.)^\n** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>\n** <dd>This parameter returns the number of pager cache hits that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>\n** <dd>This parameter returns the number of pager cache misses that have\n** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS \n** is always 0.\n** </dd>\n**\n** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>\n** <dd>This parameter returns the number of dirty cache entries that have\n** been written to disk. Specifically, the number of pages written to the\n** wal file in wal mode databases, or the number of pages written to the\n** database file in rollback mode databases. Any pages written as part of\n** transaction rollback or database recovery operations are not included.\n** If an IO or other error occurs while writing a page to disk, the effect\n** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The\n** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.\n** </dd>\n** </dl>\n*/\n#define SQLITE_DBSTATUS_LOOKASIDE_USED       0\n#define SQLITE_DBSTATUS_CACHE_USED           1\n#define SQLITE_DBSTATUS_SCHEMA_USED          2\n#define SQLITE_DBSTATUS_STMT_USED            3\n#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5\n#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6\n#define SQLITE_DBSTATUS_CACHE_HIT            7\n#define SQLITE_DBSTATUS_CACHE_MISS           8\n#define SQLITE_DBSTATUS_CACHE_WRITE          9\n#define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */\n\n\n/*\n** CAPI3REF: Prepared Statement Status\n**\n** ^(Each prepared statement maintains various\n** [SQLITE_STMTSTATUS counters] that measure the number\n** of times it has performed specific operations.)^  These counters can\n** be used to monitor the performance characteristics of the prepared\n** statements.  For example, if the number of table steps greatly exceeds\n** the number of table searches or result rows, that would tend to indicate\n** that the prepared statement is using a full table scan rather than\n** an index.  \n**\n** ^(This interface is used to retrieve and reset counter values from\n** a [prepared statement].  The first argument is the prepared statement\n** object to be interrogated.  The second argument\n** is an integer code for a specific [SQLITE_STMTSTATUS counter]\n** to be interrogated.)^\n** ^The current value of the requested counter is returned.\n** ^If the resetFlg is true, then the counter is reset to zero after this\n** interface call returns.\n**\n** See also: [sqlite3_status()] and [sqlite3_db_status()].\n*/\nSQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);\n\n/*\n** CAPI3REF: Status Parameters for prepared statements\n** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}\n**\n** These preprocessor macros define integer codes that name counter\n** values associated with the [sqlite3_stmt_status()] interface.\n** The meanings of the various counters are as follows:\n**\n** <dl>\n** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>\n** <dd>^This is the number of times that SQLite has stepped forward in\n** a table as part of a full table scan.  Large numbers for this counter\n** may indicate opportunities for performance improvement through \n** careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>\n** <dd>^This is the number of sort operations that have occurred.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance through careful use of indices.</dd>\n**\n** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>\n** <dd>^This is the number of rows inserted into transient indices that\n** were created automatically in order to help joins run faster.\n** A non-zero value in this counter may indicate an opportunity to\n** improvement performance by adding permanent indices that do not\n** need to be reinitialized each time the statement is run.</dd>\n** </dl>\n*/\n#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1\n#define SQLITE_STMTSTATUS_SORT              2\n#define SQLITE_STMTSTATUS_AUTOINDEX         3\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache type is opaque.  It is implemented by\n** the pluggable module.  The SQLite core has no knowledge of\n** its size or internal structure and never deals with the\n** sqlite3_pcache object except by holding and passing pointers\n** to the object.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache sqlite3_pcache;\n\n/*\n** CAPI3REF: Custom Page Cache Object\n**\n** The sqlite3_pcache_page object represents a single page in the\n** page cache.  The page cache will allocate instances of this\n** object.  Various methods of the page cache use pointers to instances\n** of this object as parameters or as their return value.\n**\n** See [sqlite3_pcache_methods2] for additional information.\n*/\ntypedef struct sqlite3_pcache_page sqlite3_pcache_page;\nstruct sqlite3_pcache_page {\n  void *pBuf;        /* The content of the page */\n  void *pExtra;      /* Extra information associated with the page */\n};\n\n/*\n** CAPI3REF: Application Defined Page Cache.\n** KEYWORDS: {page cache}\n**\n** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can\n** register an alternative page cache implementation by passing in an \n** instance of the sqlite3_pcache_methods2 structure.)^\n** In many applications, most of the heap memory allocated by \n** SQLite is used for the page cache.\n** By implementing a \n** custom page cache using this API, an application can better control\n** the amount of memory consumed by SQLite, the way in which \n** that memory is allocated and released, and the policies used to \n** determine exactly which parts of a database file are cached and for \n** how long.\n**\n** The alternative page cache mechanism is an\n** extreme measure that is only needed by the most demanding applications.\n** The built-in page cache is recommended for most uses.\n**\n** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an\n** internal buffer by SQLite within the call to [sqlite3_config].  Hence\n** the application may discard the parameter after the call to\n** [sqlite3_config()] returns.)^\n**\n** [[the xInit() page cache method]]\n** ^(The xInit() method is called once for each effective \n** call to [sqlite3_initialize()])^\n** (usually only once during the lifetime of the process). ^(The xInit()\n** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^\n** The intent of the xInit() method is to set up global data structures \n** required by the custom page cache implementation. \n** ^(If the xInit() method is NULL, then the \n** built-in default page cache is used instead of the application defined\n** page cache.)^\n**\n** [[the xShutdown() page cache method]]\n** ^The xShutdown() method is called by [sqlite3_shutdown()].\n** It can be used to clean up \n** any outstanding resources before process shutdown, if required.\n** ^The xShutdown() method may be NULL.\n**\n** ^SQLite automatically serializes calls to the xInit method,\n** so the xInit method need not be threadsafe.  ^The\n** xShutdown method is only called from [sqlite3_shutdown()] so it does\n** not need to be threadsafe either.  All other methods must be threadsafe\n** in multithreaded applications.\n**\n** ^SQLite will never invoke xInit() more than once without an intervening\n** call to xShutdown().\n**\n** [[the xCreate() page cache methods]]\n** ^SQLite invokes the xCreate() method to construct a new cache instance.\n** SQLite will typically create one cache instance for each open database file,\n** though this is not guaranteed. ^The\n** first parameter, szPage, is the size in bytes of the pages that must\n** be allocated by the cache.  ^szPage will always a power of two.  ^The\n** second parameter szExtra is a number of bytes of extra storage \n** associated with each page cache entry.  ^The szExtra parameter will\n** a number less than 250.  SQLite will use the\n** extra szExtra bytes on each page to store metadata about the underlying\n** database page on disk.  The value passed into szExtra depends\n** on the SQLite version, the target platform, and how SQLite was compiled.\n** ^The third argument to xCreate(), bPurgeable, is true if the cache being\n** created will be used to cache database pages of a file stored on disk, or\n** false if it is used for an in-memory database. The cache implementation\n** does not have to do anything special based with the value of bPurgeable;\n** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will\n** never invoke xUnpin() except to deliberately delete a page.\n** ^In other words, calls to xUnpin() on a cache with bPurgeable set to\n** false will always have the \"discard\" flag set to true.  \n** ^Hence, a cache created with bPurgeable false will\n** never contain any unpinned pages.\n**\n** [[the xCachesize() page cache method]]\n** ^(The xCachesize() method may be called at any time by SQLite to set the\n** suggested maximum cache-size (number of pages stored by) the cache\n** instance passed as the first argument. This is the value configured using\n** the SQLite \"[PRAGMA cache_size]\" command.)^  As with the bPurgeable\n** parameter, the implementation is not required to do anything with this\n** value; it is advisory only.\n**\n** [[the xPagecount() page cache methods]]\n** The xPagecount() method must return the number of pages currently\n** stored in the cache, both pinned and unpinned.\n** \n** [[the xFetch() page cache methods]]\n** The xFetch() method locates a page in the cache and returns a pointer to \n** an sqlite3_pcache_page object associated with that page, or a NULL pointer.\n** The pBuf element of the returned sqlite3_pcache_page object will be a\n** pointer to a buffer of szPage bytes used to store the content of a \n** single database page.  The pExtra element of sqlite3_pcache_page will be\n** a pointer to the szExtra bytes of extra storage that SQLite has requested\n** for each entry in the page cache.\n**\n** The page to be fetched is determined by the key. ^The minimum key value\n** is 1.  After it has been retrieved using xFetch, the page is considered\n** to be \"pinned\".\n**\n** If the requested page is already in the page cache, then the page cache\n** implementation must return a pointer to the page buffer with its content\n** intact.  If the requested page is not already in the cache, then the\n** cache implementation should use the value of the createFlag\n** parameter to help it determined what action to take:\n**\n** <table border=1 width=85% align=center>\n** <tr><th> createFlag <th> Behaviour when page is not already in cache\n** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.\n** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.\n**                 Otherwise return NULL.\n** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return\n**                 NULL if allocating a new page is effectively impossible.\n** </table>\n**\n** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite\n** will only use a createFlag of 2 after a prior call with a createFlag of 1\n** failed.)^  In between the to xFetch() calls, SQLite may\n** attempt to unpin one or more cache pages by spilling the content of\n** pinned pages to disk and synching the operating system disk cache.\n**\n** [[the xUnpin() page cache method]]\n** ^xUnpin() is called by SQLite with a pointer to a currently pinned page\n** as its second argument.  If the third parameter, discard, is non-zero,\n** then the page must be evicted from the cache.\n** ^If the discard parameter is\n** zero, then the page may be discarded or retained at the discretion of\n** page cache implementation. ^The page cache implementation\n** may choose to evict unpinned pages at any time.\n**\n** The cache must not perform any reference counting. A single \n** call to xUnpin() unpins the page regardless of the number of prior calls \n** to xFetch().\n**\n** [[the xRekey() page cache methods]]\n** The xRekey() method is used to change the key value associated with the\n** page passed as the second argument. If the cache\n** previously contains an entry associated with newKey, it must be\n** discarded. ^Any prior cache entry associated with newKey is guaranteed not\n** to be pinned.\n**\n** When SQLite calls the xTruncate() method, the cache must discard all\n** existing cache entries with page numbers (keys) greater than or equal\n** to the value of the iLimit parameter passed to xTruncate(). If any\n** of these pages are pinned, they are implicitly unpinned, meaning that\n** they can be safely discarded.\n**\n** [[the xDestroy() page cache method]]\n** ^The xDestroy() method is used to delete a cache allocated by xCreate().\n** All resources associated with the specified cache should be freed. ^After\n** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]\n** handle invalid, and will not use it with any other sqlite3_pcache_methods2\n** functions.\n**\n** [[the xShrink() page cache method]]\n** ^SQLite invokes the xShrink() method when it wants the page cache to\n** free up as much of heap memory as possible.  The page cache implementation\n** is not obligated to free any memory, but well-behaved implementations should\n** do their best.\n*/\ntypedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;\nstruct sqlite3_pcache_methods2 {\n  int iVersion;\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);\n  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, \n      unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n  void (*xShrink)(sqlite3_pcache*);\n};\n\n/*\n** This is the obsolete pcache_methods object that has now been replaced\n** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is\n** retained in the header file for backwards compatibility only.\n*/\ntypedef struct sqlite3_pcache_methods sqlite3_pcache_methods;\nstruct sqlite3_pcache_methods {\n  void *pArg;\n  int (*xInit)(void*);\n  void (*xShutdown)(void*);\n  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);\n  void (*xCachesize)(sqlite3_pcache*, int nCachesize);\n  int (*xPagecount)(sqlite3_pcache*);\n  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);\n  void (*xUnpin)(sqlite3_pcache*, void*, int discard);\n  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);\n  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);\n  void (*xDestroy)(sqlite3_pcache*);\n};\n\n\n/*\n** CAPI3REF: Online Backup Object\n**\n** The sqlite3_backup object records state information about an ongoing\n** online backup operation.  ^The sqlite3_backup object is created by\n** a call to [sqlite3_backup_init()] and is destroyed by a call to\n** [sqlite3_backup_finish()].\n**\n** See Also: [Using the SQLite Online Backup API]\n*/\ntypedef struct sqlite3_backup sqlite3_backup;\n\n/*\n** CAPI3REF: Online Backup API.\n**\n** The backup API copies the content of one database into another.\n** It is useful either for creating backups of databases or\n** for copying in-memory databases to or from persistent files. \n**\n** See Also: [Using the SQLite Online Backup API]\n**\n** ^SQLite holds a write transaction open on the destination database file\n** for the duration of the backup operation.\n** ^The source database is read-locked only while it is being read;\n** it is not locked continuously for the entire backup operation.\n** ^Thus, the backup may be performed on a live source database without\n** preventing other database connections from\n** reading or writing to the source database while the backup is underway.\n** \n** ^(To perform a backup operation: \n**   <ol>\n**     <li><b>sqlite3_backup_init()</b> is called once to initialize the\n**         backup, \n**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer \n**         the data between the two databases, and finally\n**     <li><b>sqlite3_backup_finish()</b> is called to release all resources \n**         associated with the backup operation. \n**   </ol>)^\n** There should be exactly one call to sqlite3_backup_finish() for each\n** successful call to sqlite3_backup_init().\n**\n** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>\n**\n** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the \n** [database connection] associated with the destination database \n** and the database name, respectively.\n** ^The database name is \"main\" for the main database, \"temp\" for the\n** temporary database, or the name specified after the AS keyword in\n** an [ATTACH] statement for an attached database.\n** ^The S and M arguments passed to \n** sqlite3_backup_init(D,N,S,M) identify the [database connection]\n** and database name of the source database, respectively.\n** ^The source and destination [database connections] (parameters S and D)\n** must be different or else sqlite3_backup_init(D,N,S,M) will fail with\n** an error.\n**\n** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is\n** returned and an error code and error message are stored in the\n** destination [database connection] D.\n** ^The error code and message for the failed call to sqlite3_backup_init()\n** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or\n** [sqlite3_errmsg16()] functions.\n** ^A successful call to sqlite3_backup_init() returns a pointer to an\n** [sqlite3_backup] object.\n** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and\n** sqlite3_backup_finish() functions to perform the specified backup \n** operation.\n**\n** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>\n**\n** ^Function sqlite3_backup_step(B,N) will copy up to N pages between \n** the source and destination databases specified by [sqlite3_backup] object B.\n** ^If N is negative, all remaining source pages are copied. \n** ^If sqlite3_backup_step(B,N) successfully copies N pages and there\n** are still more pages to be copied, then the function returns [SQLITE_OK].\n** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages\n** from source to destination, then it returns [SQLITE_DONE].\n** ^If an error occurs while running sqlite3_backup_step(B,N),\n** then an [error code] is returned. ^As well as [SQLITE_OK] and\n** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],\n** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.\n**\n** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if\n** <ol>\n** <li> the destination database was opened read-only, or\n** <li> the destination database is using write-ahead-log journaling\n** and the destination and source page sizes differ, or\n** <li> the destination database is an in-memory database and the\n** destination and source page sizes differ.\n** </ol>)^\n**\n** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then\n** the [sqlite3_busy_handler | busy-handler function]\n** is invoked (if one is specified). ^If the \n** busy-handler returns non-zero before the lock is available, then \n** [SQLITE_BUSY] is returned to the caller. ^In this case the call to\n** sqlite3_backup_step() can be retried later. ^If the source\n** [database connection]\n** is being used to write to the source database when sqlite3_backup_step()\n** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this\n** case the call to sqlite3_backup_step() can be retried later on. ^(If\n** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or\n** [SQLITE_READONLY] is returned, then \n** there is no point in retrying the call to sqlite3_backup_step(). These \n** errors are considered fatal.)^  The application must accept \n** that the backup operation has failed and pass the backup operation handle \n** to the sqlite3_backup_finish() to release associated resources.\n**\n** ^The first call to sqlite3_backup_step() obtains an exclusive lock\n** on the destination file. ^The exclusive lock is not released until either \n** sqlite3_backup_finish() is called or the backup operation is complete \n** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to\n** sqlite3_backup_step() obtains a [shared lock] on the source database that\n** lasts for the duration of the sqlite3_backup_step() call.\n** ^Because the source database is not locked between calls to\n** sqlite3_backup_step(), the source database may be modified mid-way\n** through the backup process.  ^If the source database is modified by an\n** external process or via a database connection other than the one being\n** used by the backup operation, then the backup will be automatically\n** restarted by the next call to sqlite3_backup_step(). ^If the source \n** database is modified by the using the same database connection as is used\n** by the backup operation, then the backup database is automatically\n** updated at the same time.\n**\n** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>\n**\n** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the \n** application wishes to abandon the backup operation, the application\n** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().\n** ^The sqlite3_backup_finish() interfaces releases all\n** resources associated with the [sqlite3_backup] object. \n** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any\n** active write-transaction on the destination database is rolled back.\n** The [sqlite3_backup] object is invalid\n** and may not be used following a call to sqlite3_backup_finish().\n**\n** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no\n** sqlite3_backup_step() errors occurred, regardless or whether or not\n** sqlite3_backup_step() completed.\n** ^If an out-of-memory condition or IO error occurred during any prior\n** sqlite3_backup_step() call on the same [sqlite3_backup] object, then\n** sqlite3_backup_finish() returns the corresponding [error code].\n**\n** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()\n** is not a permanent error and does not affect the return value of\n** sqlite3_backup_finish().\n**\n** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]\n** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>\n**\n** ^Each call to sqlite3_backup_step() sets two values inside\n** the [sqlite3_backup] object: the number of pages still to be backed\n** up and the total number of pages in the source database file.\n** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces\n** retrieve these two values, respectively.\n**\n** ^The values returned by these functions are only updated by\n** sqlite3_backup_step(). ^If the source database is modified during a backup\n** operation, then the values are not updated to account for any extra\n** pages that need to be updated or the size of the source database file\n** changing.\n**\n** <b>Concurrent Usage of Database Handles</b>\n**\n** ^The source [database connection] may be used by the application for other\n** purposes while a backup operation is underway or being initialized.\n** ^If SQLite is compiled and configured to support threadsafe database\n** connections, then the source database connection may be used concurrently\n** from within other threads.\n**\n** However, the application must guarantee that the destination \n** [database connection] is not passed to any other API (by any thread) after \n** sqlite3_backup_init() is called and before the corresponding call to\n** sqlite3_backup_finish().  SQLite does not currently check to see\n** if the application incorrectly accesses the destination [database connection]\n** and so no error code is reported, but the operations may malfunction\n** nevertheless.  Use of the destination database connection while a\n** backup is in progress might also also cause a mutex deadlock.\n**\n** If running in [shared cache mode], the application must\n** guarantee that the shared cache used by the destination database\n** is not accessed while the backup is running. In practice this means\n** that the application must guarantee that the disk file being \n** backed up to is not accessed by any connection within the process,\n** not just the specific connection that was passed to sqlite3_backup_init().\n**\n** The [sqlite3_backup] object itself is partially threadsafe. Multiple \n** threads may safely make multiple concurrent calls to sqlite3_backup_step().\n** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()\n** APIs are not strictly speaking threadsafe. If they are invoked at the\n** same time as another thread is invoking sqlite3_backup_step() it is\n** possible that they return invalid values.\n*/\nSQLITE_API sqlite3_backup *sqlite3_backup_init(\n  sqlite3 *pDest,                        /* Destination database handle */\n  const char *zDestName,                 /* Destination database name */\n  sqlite3 *pSource,                      /* Source database handle */\n  const char *zSourceName                /* Source database name */\n);\nSQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);\nSQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);\nSQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);\n\n/*\n** CAPI3REF: Unlock Notification\n**\n** ^When running in shared-cache mode, a database operation may fail with\n** an [SQLITE_LOCKED] error if the required locks on the shared-cache or\n** individual tables within the shared-cache cannot be obtained. See\n** [SQLite Shared-Cache Mode] for a description of shared-cache locking. \n** ^This API may be used to register a callback that SQLite will invoke \n** when the connection currently holding the required lock relinquishes it.\n** ^This API is only available if the library was compiled with the\n** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.\n**\n** See Also: [Using the SQLite Unlock Notification Feature].\n**\n** ^Shared-cache locks are released when a database connection concludes\n** its current transaction, either by committing it or rolling it back. \n**\n** ^When a connection (known as the blocked connection) fails to obtain a\n** shared-cache lock and SQLITE_LOCKED is returned to the caller, the\n** identity of the database connection (the blocking connection) that\n** has locked the required resource is stored internally. ^After an \n** application receives an SQLITE_LOCKED error, it may call the\n** sqlite3_unlock_notify() method with the blocked connection handle as \n** the first argument to register for a callback that will be invoked\n** when the blocking connections current transaction is concluded. ^The\n** callback is invoked from within the [sqlite3_step] or [sqlite3_close]\n** call that concludes the blocking connections transaction.\n**\n** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,\n** there is a chance that the blocking connection will have already\n** concluded its transaction by the time sqlite3_unlock_notify() is invoked.\n** If this happens, then the specified callback is invoked immediately,\n** from within the call to sqlite3_unlock_notify().)^\n**\n** ^If the blocked connection is attempting to obtain a write-lock on a\n** shared-cache table, and more than one other connection currently holds\n** a read-lock on the same table, then SQLite arbitrarily selects one of \n** the other connections to use as the blocking connection.\n**\n** ^(There may be at most one unlock-notify callback registered by a \n** blocked connection. If sqlite3_unlock_notify() is called when the\n** blocked connection already has a registered unlock-notify callback,\n** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is\n** called with a NULL pointer as its second argument, then any existing\n** unlock-notify callback is canceled. ^The blocked connections \n** unlock-notify callback may also be canceled by closing the blocked\n** connection using [sqlite3_close()].\n**\n** The unlock-notify callback is not reentrant. If an application invokes\n** any sqlite3_xxx API functions from within an unlock-notify callback, a\n** crash or deadlock may be the result.\n**\n** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always\n** returns SQLITE_OK.\n**\n** <b>Callback Invocation Details</b>\n**\n** When an unlock-notify callback is registered, the application provides a \n** single void* pointer that is passed to the callback when it is invoked.\n** However, the signature of the callback function allows SQLite to pass\n** it an array of void* context pointers. The first argument passed to\n** an unlock-notify callback is a pointer to an array of void* pointers,\n** and the second is the number of entries in the array.\n**\n** When a blocking connections transaction is concluded, there may be\n** more than one blocked connection that has registered for an unlock-notify\n** callback. ^If two or more such blocked connections have specified the\n** same callback function, then instead of invoking the callback function\n** multiple times, it is invoked once with the set of void* context pointers\n** specified by the blocked connections bundled together into an array.\n** This gives the application an opportunity to prioritize any actions \n** related to the set of unblocked database connections.\n**\n** <b>Deadlock Detection</b>\n**\n** Assuming that after registering for an unlock-notify callback a \n** database waits for the callback to be issued before taking any further\n** action (a reasonable assumption), then using this API may cause the\n** application to deadlock. For example, if connection X is waiting for\n** connection Y's transaction to be concluded, and similarly connection\n** Y is waiting on connection X's transaction, then neither connection\n** will proceed and the system may remain deadlocked indefinitely.\n**\n** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock\n** detection. ^If a given call to sqlite3_unlock_notify() would put the\n** system in a deadlocked state, then SQLITE_LOCKED is returned and no\n** unlock-notify callback is registered. The system is said to be in\n** a deadlocked state if connection A has registered for an unlock-notify\n** callback on the conclusion of connection B's transaction, and connection\n** B has itself registered for an unlock-notify callback when connection\n** A's transaction is concluded. ^Indirect deadlock is also detected, so\n** the system is also considered to be deadlocked if connection B has\n** registered for an unlock-notify callback on the conclusion of connection\n** C's transaction, where connection C is waiting on connection A. ^Any\n** number of levels of indirection are allowed.\n**\n** <b>The \"DROP TABLE\" Exception</b>\n**\n** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost \n** always appropriate to call sqlite3_unlock_notify(). There is however,\n** one exception. When executing a \"DROP TABLE\" or \"DROP INDEX\" statement,\n** SQLite checks if there are any currently executing SELECT statements\n** that belong to the same connection. If there are, SQLITE_LOCKED is\n** returned. In this case there is no \"blocking connection\", so invoking\n** sqlite3_unlock_notify() results in the unlock-notify callback being\n** invoked immediately. If the application then re-attempts the \"DROP TABLE\"\n** or \"DROP INDEX\" query, an infinite loop might be the result.\n**\n** One way around this problem is to check the extended error code returned\n** by an sqlite3_step() call. ^(If there is a blocking connection, then the\n** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in\n** the special \"DROP TABLE/INDEX\" case, the extended error code is just \n** SQLITE_LOCKED.)^\n*/\nSQLITE_API int sqlite3_unlock_notify(\n  sqlite3 *pBlocked,                          /* Waiting connection */\n  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */\n  void *pNotifyArg                            /* Argument to pass to xNotify */\n);\n\n\n/*\n** CAPI3REF: String Comparison\n**\n** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications\n** and extensions to compare the contents of two buffers containing UTF-8\n** strings in a case-independent fashion, using the same definition of \"case\n** independence\" that SQLite uses internally when comparing identifiers.\n*/\nSQLITE_API int sqlite3_stricmp(const char *, const char *);\nSQLITE_API int sqlite3_strnicmp(const char *, const char *, int);\n\n/*\n** CAPI3REF: Error Logging Interface\n**\n** ^The [sqlite3_log()] interface writes a message into the error log\n** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].\n** ^If logging is enabled, the zFormat string and subsequent arguments are\n** used with [sqlite3_snprintf()] to generate the final output string.\n**\n** The sqlite3_log() interface is intended for use by extensions such as\n** virtual tables, collating functions, and SQL functions.  While there is\n** nothing to prevent an application from calling sqlite3_log(), doing so\n** is considered bad form.\n**\n** The zFormat string must not be NULL.\n**\n** To avoid deadlocks and other threading problems, the sqlite3_log() routine\n** will not use dynamically allocated memory.  The log message is stored in\n** a fixed-length buffer on the stack.  If the log message is longer than\n** a few hundred characters, it will be truncated to the length of the\n** buffer.\n*/\nSQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);\n\n/*\n** CAPI3REF: Write-Ahead Log Commit Hook\n**\n** ^The [sqlite3_wal_hook()] function is used to register a callback that\n** will be invoked each time a database connection commits data to a\n** [write-ahead log] (i.e. whenever a transaction is committed in\n** [journal_mode | journal_mode=WAL mode]). \n**\n** ^The callback is invoked by SQLite after the commit has taken place and \n** the associated write-lock on the database released, so the implementation \n** may read, write or [checkpoint] the database as required.\n**\n** ^The first parameter passed to the callback function when it is invoked\n** is a copy of the third parameter passed to sqlite3_wal_hook() when\n** registering the callback. ^The second is a copy of the database handle.\n** ^The third parameter is the name of the database that was written to -\n** either \"main\" or the name of an [ATTACH]-ed database. ^The fourth parameter\n** is the number of pages currently in the write-ahead log file,\n** including those that were just committed.\n**\n** The callback function should normally return [SQLITE_OK].  ^If an error\n** code is returned, that error will propagate back up through the\n** SQLite code base to cause the statement that provoked the callback\n** to report an error, though the commit will have still occurred. If the\n** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value\n** that does not correspond to any valid SQLite error code, the results\n** are undefined.\n**\n** A single database handle may have at most a single write-ahead log callback \n** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any\n** previously registered write-ahead log callback. ^Note that the\n** [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will\n** those overwrite any prior [sqlite3_wal_hook()] settings.\n*/\nSQLITE_API void *sqlite3_wal_hook(\n  sqlite3*, \n  int(*)(void *,sqlite3*,const char*,int),\n  void*\n);\n\n/*\n** CAPI3REF: Configure an auto-checkpoint\n**\n** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around\n** [sqlite3_wal_hook()] that causes any database on [database connection] D\n** to automatically [checkpoint]\n** after committing a transaction if there are N or\n** more frames in the [write-ahead log] file.  ^Passing zero or \n** a negative value as the nFrame parameter disables automatic\n** checkpoints entirely.\n**\n** ^The callback registered by this function replaces any existing callback\n** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback\n** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism\n** configured by this function.\n**\n** ^The [wal_autocheckpoint pragma] can be used to invoke this interface\n** from SQL.\n**\n** ^Every new [database connection] defaults to having the auto-checkpoint\n** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]\n** pages.  The use of this interface\n** is only necessary if the default setting is found to be suboptimal\n** for a particular application.\n*/\nSQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);\n\n/*\n** CAPI3REF: Checkpoint a database\n**\n** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X\n** on [database connection] D to be [checkpointed].  ^If X is NULL or an\n** empty string, then a checkpoint is run on all databases of\n** connection D.  ^If the database connection D is not in\n** [WAL | write-ahead log mode] then this interface is a harmless no-op.\n**\n** ^The [wal_checkpoint pragma] can be used to invoke this interface\n** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the\n** [wal_autocheckpoint pragma] can be used to cause this interface to be\n** run whenever the WAL reaches a certain size threshold.\n**\n** See also: [sqlite3_wal_checkpoint_v2()]\n*/\nSQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);\n\n/*\n** CAPI3REF: Checkpoint a database\n**\n** Run a checkpoint operation on WAL database zDb attached to database \n** handle db. The specific operation is determined by the value of the \n** eMode parameter:\n**\n** <dl>\n** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>\n**   Checkpoint as many frames as possible without waiting for any database \n**   readers or writers to finish. Sync the db file if all frames in the log\n**   are checkpointed. This mode is the same as calling \n**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.\n**\n** <dt>SQLITE_CHECKPOINT_FULL<dd>\n**   This mode blocks (calls the busy-handler callback) until there is no\n**   database writer and all readers are reading from the most recent database\n**   snapshot. It then checkpoints all frames in the log file and syncs the\n**   database file. This call blocks database writers while it is running,\n**   but not database readers.\n**\n** <dt>SQLITE_CHECKPOINT_RESTART<dd>\n**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after \n**   checkpointing the log file it blocks (calls the busy-handler callback)\n**   until all readers are reading from the database file only. This ensures \n**   that the next client to write to the database file restarts the log file \n**   from the beginning. This call blocks database writers while it is running,\n**   but not database readers.\n** </dl>\n**\n** If pnLog is not NULL, then *pnLog is set to the total number of frames in\n** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to\n** the total number of checkpointed frames (including any that were already\n** checkpointed when this function is called). *pnLog and *pnCkpt may be\n** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.\n** If no values are available because of an error, they are both set to -1\n** before returning to communicate this to the caller.\n**\n** All calls obtain an exclusive \"checkpoint\" lock on the database file. If\n** any other process is running a checkpoint operation at the same time, the \n** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a \n** busy-handler configured, it will not be invoked in this case.\n**\n** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive \n** \"writer\" lock on the database file. If the writer lock cannot be obtained\n** immediately, and a busy-handler is configured, it is invoked and the writer\n** lock retried until either the busy-handler returns 0 or the lock is\n** successfully obtained. The busy-handler is also invoked while waiting for\n** database readers as described above. If the busy-handler returns 0 before\n** the writer lock is obtained or while waiting for database readers, the\n** checkpoint operation proceeds from that point in the same way as \n** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible \n** without blocking any further. SQLITE_BUSY is returned in this case.\n**\n** If parameter zDb is NULL or points to a zero length string, then the\n** specified operation is attempted on all WAL databases. In this case the\n** values written to output parameters *pnLog and *pnCkpt are undefined. If \n** an SQLITE_BUSY error is encountered when processing one or more of the \n** attached WAL databases, the operation is still attempted on any remaining \n** attached databases and SQLITE_BUSY is returned to the caller. If any other \n** error occurs while processing an attached database, processing is abandoned \n** and the error code returned to the caller immediately. If no error \n** (SQLITE_BUSY or otherwise) is encountered while processing the attached \n** databases, SQLITE_OK is returned.\n**\n** If database zDb is the name of an attached database that is not in WAL\n** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If\n** zDb is not NULL (or a zero length string) and is not the name of any\n** attached database, SQLITE_ERROR is returned to the caller.\n*/\nSQLITE_API int sqlite3_wal_checkpoint_v2(\n  sqlite3 *db,                    /* Database handle */\n  const char *zDb,                /* Name of attached database (or NULL) */\n  int eMode,                      /* SQLITE_CHECKPOINT_* value */\n  int *pnLog,                     /* OUT: Size of WAL log in frames */\n  int *pnCkpt                     /* OUT: Total number of frames checkpointed */\n);\n\n/*\n** CAPI3REF: Checkpoint operation parameters\n**\n** These constants can be used as the 3rd parameter to\n** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]\n** documentation for additional information about the meaning and use of\n** each of these values.\n*/\n#define SQLITE_CHECKPOINT_PASSIVE 0\n#define SQLITE_CHECKPOINT_FULL    1\n#define SQLITE_CHECKPOINT_RESTART 2\n\n/*\n** CAPI3REF: Virtual Table Interface Configuration\n**\n** This function may be called by either the [xConnect] or [xCreate] method\n** of a [virtual table] implementation to configure\n** various facets of the virtual table interface.\n**\n** If this interface is invoked outside the context of an xConnect or\n** xCreate virtual table method then the behavior is undefined.\n**\n** At present, there is only one option that may be configured using\n** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options\n** may be added in the future.\n*/\nSQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);\n\n/*\n** CAPI3REF: Virtual Table Configuration Options\n**\n** These macros define the various options to the\n** [sqlite3_vtab_config()] interface that [virtual table] implementations\n** can use to customize and optimize their behavior.\n**\n** <dl>\n** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT\n** <dd>Calls of the form\n** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,\n** where X is an integer.  If X is zero, then the [virtual table] whose\n** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not\n** support constraints.  In this configuration (which is the default) if\n** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire\n** statement is rolled back as if [ON CONFLICT | OR ABORT] had been\n** specified as part of the users SQL statement, regardless of the actual\n** ON CONFLICT mode specified.\n**\n** If X is non-zero, then the virtual table implementation guarantees\n** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before\n** any modifications to internal or persistent data structures have been made.\n** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite \n** is able to roll back a statement or database transaction, and abandon\n** or continue processing the current SQL statement as appropriate. \n** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns\n** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode\n** had been ABORT.\n**\n** Virtual table implementations that are required to handle OR REPLACE\n** must do so within the [xUpdate] method. If a call to the \n** [sqlite3_vtab_on_conflict()] function indicates that the current ON \n** CONFLICT policy is REPLACE, the virtual table implementation should \n** silently replace the appropriate rows within the xUpdate callback and\n** return SQLITE_OK. Or, if this is not possible, it may return\n** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT \n** constraint handling.\n** </dl>\n*/\n#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1\n\n/*\n** CAPI3REF: Determine The Virtual Table Conflict Policy\n**\n** This function may only be called from within a call to the [xUpdate] method\n** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The\n** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],\n** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode\n** of the SQL statement that triggered the call to the [xUpdate] method of the\n** [virtual table].\n*/\nSQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);\n\n/*\n** CAPI3REF: Conflict resolution modes\n**\n** These constants are returned by [sqlite3_vtab_on_conflict()] to\n** inform a [virtual table] implementation what the [ON CONFLICT] mode\n** is for the SQL statement being evaluated.\n**\n** Note that the [SQLITE_IGNORE] constant is also used as a potential\n** return value from the [sqlite3_set_authorizer()] callback and that\n** [SQLITE_ABORT] is also a [result code].\n*/\n#define SQLITE_ROLLBACK 1\n/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */\n#define SQLITE_FAIL     3\n/* #define SQLITE_ABORT 4  // Also an error code */\n#define SQLITE_REPLACE  5\n\n\n\n/*\n** Undo the hack that converts floating point types to integer for\n** builds on processors without floating point support.\n*/\n#ifdef SQLITE_OMIT_FLOATING_POINT\n# undef double\n#endif\n\n#ifdef __cplusplus\n}  /* End of the 'extern \"C\"' block */\n#endif\n#endif\n\n/*\n** 2010 August 30\n**\n** The author disclaims copyright to this source code.  In place of\n** a legal notice, here is a blessing:\n**\n**    May you do good and not evil.\n**    May you find forgiveness for yourself and forgive others.\n**    May you share freely, never taking more than you give.\n**\n*************************************************************************\n*/\n\n#ifndef _SQLITE3RTREE_H_\n#define _SQLITE3RTREE_H_\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\ntypedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;\n\n/*\n** Register a geometry callback named zGeom that can be used as part of an\n** R-Tree geometry query as follows:\n**\n**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)\n*/\nSQLITE_API int sqlite3_rtree_geometry_callback(\n  sqlite3 *db,\n  const char *zGeom,\n#ifdef SQLITE_RTREE_INT_ONLY\n  int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),\n#else\n  int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),\n#endif\n  void *pContext\n);\n\n\n/*\n** A pointer to a structure of the following type is passed as the first\n** argument to callbacks registered using rtree_geometry_callback().\n*/\nstruct sqlite3_rtree_geometry {\n  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */\n  int nParam;                     /* Size of array aParam[] */\n  double *aParam;                 /* Parameters passed to SQL geom function */\n  void *pUser;                    /* Callback implementation user data */\n  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */\n};\n\n\n#ifdef __cplusplus\n}  /* end of the 'extern \"C\"' block */\n#endif\n\n#endif  /* ifndef _SQLITE3RTREE_H_ */\n\n"
  },
  {
    "path": "plugins/iTunes/main.cpp",
    "content": "/*\n   Copyright 2004 Gareth Simpson <iscrobbler@xurble.org>\n   Copyright 2004-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"main.h\"\n#include \"IPodDetector.h\"\n#include \"Moose.h\"\n#include \"common/c++/logger.h\"\n\n#if TARGET_OS_WIN32\n    #include \"ITunesComThread.h\"\n    #include \"ScrobSubmitter.h\"\n\n    ITunesComThread* gCom = 0;\n    ScrobSubmitter gSubmitter;\n#else\n    #include <sys/stat.h>\n\t#include \"ITunesPlaysDatabase.h\"\n#endif\n\nIPodDetector* gIPodDetector = 0;\n\nstatic void initLogger();\nstatic bool isClientInstalled();\nstatic void launchClient();\nstatic void setupIPodSystem();\nstatic void cleanup();\nstatic void uninstall();\nstatic void deleteTwiddlyDatabases();\nextern void ScrobSubCallback(int reqID, bool error, std::string message, void* userData);\nextern void ClearMemory( LogicalAddress dest, SInt32 length );\n\n//-------------------------------------------------------------------------------------------------\n//\tiTunesPluginMain\n//-------------------------------------------------------------------------------------------------\n//\n#if TARGET_OS_MAC\nextern \"C\" OSStatus iTunesPluginMainMachO( OSType message, PluginMessageInfo * messageInfo, void * refCon )\n#else\nextern \"C\" __declspec(dllexport) OSStatus iTunesPluginMain( OSType message, PluginMessageInfo * messageInfo, void * refCon )\n#endif\n{\n\tOSStatus\t\tstatus;\n\t\n\t(void) refCon;\n\t\n    switch ( message )\n    {\n        case kPluginInitMessage:\n            initLogger();\n            \n#if TARGET_OS_MAC\n            if ( !isClientInstalled() )\n            {\n                uninstall();\n                return noErr;\n            }\n#endif\n            \n            launchClient(); //launches client, on mac\n            setupIPodSystem(); //sets up iPod scrobbling\n            \n#if TARGET_OS_WIN32\n            LOG( 3, \"Initialising ScrobSubmitter\" );\n            gSubmitter.Init( \"itw\", ScrobSubCallback, 0 );\n#endif\n            \n            return RegisterVisualPlugin( messageInfo );\n            \n            \n        case kPluginPrepareToQuitMessage:\n            LOG( 3, \"EVENT: kPluginPrepareToQuitMessage\" );\n            \n            cleanup();\n            return noErr;\n            \n            \n        case kPluginCleanupMessage:\n            LOG( 3, \"EVENT: kPluginCleanupMessage\" );\n            \n#if TARGET_OS_WIN32\n            LOG( 3, \"Terminating ScrobSubmitter\" );\n            gSubmitter.Term();\n#endif\n            \n            return noErr;\n            \n            \n        default:\n            return unimpErr;\n    }\n    \n\treturn status;\n}\n\nstatic void initLogger()\n{\n#if TARGET_OS_WIN32\n    std::wstring path = ScrobSubmitter::GetLogPathW();\n    path += L\"\\\\iTunesPlugin.log\";\n#else\n    std::string path = ::getenv( \"HOME\" );\n    path += \"/Library/Logs/Last.fm/iTunes Plugin.log\";\n#endif\n\n    new Logger( path.c_str(), Logger::Debug );\n    LOG( 3, \"Log file created\" );\n}\n\n\nstatic void launchClient()\n{\n#if TARGET_OS_MAC\n    if ( Moose::launchWithMediaPlayer() )\n    {\n        std::vector<std::string> args;\n        args.push_back( \"--tray\" );\n        Moose::launchAudioscrobbler( args );\n    }\n#endif\n}\n\n\nstatic void setupIPodSystem()\n{\n    if ( !Moose::iPodScrobblingEnabled() )\n    {\n        deleteTwiddlyDatabases();\n        return;\n    }\n\n#if TARGET_OS_WIN32\n    LOG( 3, \"Initialising ITunesComThread\" );\n    gCom = new ITunesComThread();\n#endif\n\n#if TARGET_OS_MAC\n    LOG( 3, \"Initialising ITunesPlaysDatabase\" );\n    ITunesPlaysDatabase::init(); // must be done b4 notification center registration\n\n    CFNotificationCenterAddObserver( CFNotificationCenterGetDistributedCenter(),\n                                     NULL,\n                                     notificationCallback,\n                                     CFSTR( \"com.apple.iTunes.playerInfo\" ),\n                                     NULL,\n                                     CFNotificationSuspensionBehaviorDeliverImmediately );\n#endif\n\n    LOG( 3, \"Initialising IPodDetector\" );\n    gIPodDetector = new IPodDetector;\n}\n\n\nstatic void cleanup()\n{\n    LOG( 3, \"Deleting IPodDetector\" );\n    delete gIPodDetector;\n    gIPodDetector = 0;\n    \n#if TARGET_OS_WIN32\n    LOG( 3, \"Deleting ITunesComThread\" );\n    delete gCom;\n    gCom = 0;\n#else\n    ITunesPlaysDatabase::finit();\n#endif\n}\n\n\n#if TARGET_OS_MAC\nstatic bool isClientInstalled()\n{\n    struct stat st;\n    std::string path = Moose::applicationPath();\n    return stat( path.c_str(), &st ) == 0;\n}\n\n\nstatic void uninstall()\n{\n    LOG( 3, \"Client has gone, uninstalling self.\" );\n    // we have to change directory for the script to work properly\n    std::string d = Moose::bundleFolder() + \"Contents/Resources\";\n    // we have to change dir for the script to succeed as a safety precaution\n    if (chdir( d.c_str() ) != 0)\n        return;\n    // always specify paths to tools absolutely! --muesli\n    Moose::exec( \"/bin/sh\", \"uninstall.sh\" );\n}\n#endif\n\n\nstatic void deleteTwiddlyDatabases()\n{\n    // we delete the db, or if they ever re-enable iPod scrobbling we will\n    // mis-scrobble everything played between now and then\n    #if TARGET_OS_WIN32\n        //FIXME you prolly should delete the manual iPod databases too\n        DeleteFileW( (Moose::applicationSupport() + L\"\\\\iTunesPlays.db\").c_str() );\n    #else\n        std::string script = Moose::bundleFolder() + \"Contents/Resources/uninstall.sh\";\n        Moose::exec( \"/bin/sh\", \"'\" + script + \"' --db-only\" );\n    #endif\n}\n\n//-------------------------------------------------------------------------------------------------\n//\tRegisterVisualPlugin\n//-------------------------------------------------------------------------------------------------\n//\n#include <iostream>\nOSStatus RegisterVisualPlugin( PluginMessageInfo * messageInfo )\n{\n    std::cout << \"Registering Visual Plugin!!!!\" << std::endl;\n\n\tPlayerMessageInfo\tplayerMessageInfo;\n\tOSStatus\t\t\tstatus;\n\t\t\n\tmemset( &playerMessageInfo.u.registerVisualPluginMessage, 0, sizeof(playerMessageInfo.u.registerVisualPluginMessage) );\n\n\tGetVisualName( playerMessageInfo.u.registerVisualPluginMessage.name );\n\n\tSetNumVersion( &playerMessageInfo.u.registerVisualPluginMessage.pluginVersion, kTVisualPluginMajorVersion, kTVisualPluginMinorVersion, kTVisualPluginReleaseStage, kTVisualPluginNonFinalRelease );\n\n\tplayerMessageInfo.u.registerVisualPluginMessage.options\t\t\t\t\t= GetVisualOptions();\n\tplayerMessageInfo.u.registerVisualPluginMessage.handler\t\t\t\t\t= (VisualPluginProcPtr)VisualPluginHandler;\n\tplayerMessageInfo.u.registerVisualPluginMessage.registerRefCon\t\t\t= 0;\n\tplayerMessageInfo.u.registerVisualPluginMessage.creator\t\t\t\t\t= kTVisualPluginCreator;\n\t\n\tplayerMessageInfo.u.registerVisualPluginMessage.pulseRateInHz\t\t\t= kStoppedPulseRateInHz;\t// update my state N times a second\n\tplayerMessageInfo.u.registerVisualPluginMessage.numWaveformChannels\t\t= 2;\n\tplayerMessageInfo.u.registerVisualPluginMessage.numSpectrumChannels\t\t= 2;\n\t\n\tplayerMessageInfo.u.registerVisualPluginMessage.minWidth\t\t\t\t= 64;\n\tplayerMessageInfo.u.registerVisualPluginMessage.minHeight\t\t\t\t= 64;\n\tplayerMessageInfo.u.registerVisualPluginMessage.maxWidth\t\t\t\t= 0;\t// no max width limit\n\tplayerMessageInfo.u.registerVisualPluginMessage.maxHeight\t\t\t\t= 0;\t// no max height limit\n\t\n\tstatus = PlayerRegisterVisualPlugin( messageInfo->u.initMessage.appCookie, messageInfo->u.initMessage.appProc, &playerMessageInfo );\n\t\t\n\treturn status;\n}\n\n\nstd::string\nGetVersionString()\n{\n    std::ostringstream os;\n    os << kTVisualPluginMajorVersion << \".\"\n       << kTVisualPluginMinorVersion << \".\"\n       << kTVisualPluginReleaseStage << \".\"\n       << kTVisualPluginNonFinalRelease;\n    return os.str();\n}\n"
  },
  {
    "path": "plugins/iTunes/main.h",
    "content": "/*\n   Copyright 2004 Gareth Simpson <iscrobbler@xurble.org>\n   Copyright 2004-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n// Don't allow windows.h to include old winsock.h because it conflicts with\n// winsock2.h included by the ScrobSubmitter\n#ifndef _WINSOCKAPI_\n#define _WINSOCKAPI_\n#endif\n\n#include \"iTunesVisualAPI/iTunesVisualAPI.h\"\n#include <time.h>\n#include <string>\n\n#if TARGET_OS_WIN32\n#include <Gdiplus.h>\n#endif // TARGET_OS_WIN32\n\n#if TARGET_OS_WIN32\n#define kTVisualPluginName     L\"Last.fm AudioScrobbler\"\n#else\n#define kTVisualPluginName     CFSTR(\"Last.fm AudioScrobbler\")\n#endif\n\n#define\tkTVisualPluginCreator\t\t\t'hook'\n\n#define\tkTVisualPluginMajorVersion\t\t6\n#define\tkTVisualPluginMinorVersion\t\t0\n#define\tkTVisualPluginReleaseStage\t\t5\n#define\tkTVisualPluginNonFinalRelease\t4\n\nstruct VisualPluginData;\n\n#if TARGET_OS_MAC\n#import <Cocoa/Cocoa.h>\n\n// \"namespace\" our ObjC classname to avoid load conflicts between multiple visualizer plugins\n#define VisualView\t\tComAppleExample_VisualView\n#define GLVisualView\tComAppleExample_GLVisualView\n\n@class VisualView;\n@class GLVisualView;\n\nOSStatus\tConfigureVisual( VisualPluginData * visualPluginData );\n\nvoid notificationCallback( CFNotificationCenterRef,\n                          void*,\n                          CFStringRef,\n                          const void*,\n                          CFDictionaryRef info );\n\n#endif\n\n\n\n#define kInfoTimeOutInSeconds\t\t10\t\t\t\t\t\t\t// draw info/artwork for N seconds when it changes or playback starts\n#define kPlayingPulseRateInHz\t\t10\t\t\t\t\t\t\t// when iTunes is playing, draw N times a second\n#define kStoppedPulseRateInHz\t\t5\t\t\t\t\t\t\t// when iTunes is not playing, draw N times a second\n\nstruct VisualPluginData\n{\n\tvoid *\t\t\t\tappCookie;\n\tITAppProcPtr\t\tappProc;\n    \n#if TARGET_OS_MAC\n\tNSView*\t\t\t\tdestView;\n\tNSRect\t\t\t\tdestRect;\n\tNSImage *\t\t\tcurrentArtwork;\n#else\n\tHWND\t\t\t\tdestView;\n\tRECT\t\t\t\tdestRect;\n\tGdiplus::Bitmap* \tcurrentArtwork;\n\tlong int\t\t\tlastDrawTime;\n#endif\n\tOptionBits\t\t\tdestOptions;\n    \n\tRenderVisualData\trenderData;\n\tUInt32\t\t\t\trenderTimeStampID;\n\t\n\tITTrackInfo\t\t\ttrackInfo;\n\tITStreamInfo\t\tstreamInfo;\n    \n\t// Plugin-specific data\n    \n\tBoolean\t\t\t\tplaying;\t\t\t\t\t\t\t\t// is iTunes currently playing audio?\n\tBoolean\t\t\t\tpadding[3];\n    \n\ttime_t\t\t\t\tdrawInfoTimeOut;\t\t\t\t\t\t// when should we stop showing info/artwork?\n    \n\tUInt8\t\t\t\tminLevel[kVisualMaxDataChannels];\t\t// 0-128\n\tUInt8\t\t\t\tmaxLevel[kVisualMaxDataChannels];\t\t// 0-128\n};\ntypedef struct VisualPluginData VisualPluginData;\n\nvoid\t\tGetVisualName( ITUniStr255 name );\nOptionBits\tGetVisualOptions( void );\nOSStatus\tRegisterVisualPlugin( PluginMessageInfo * messageInfo );\n\nvoid\t\tProcessRenderData( VisualPluginData * visualPluginData, UInt32 timeStampID, const RenderVisualData * renderData );\nvoid\t\tResetRenderData( VisualPluginData * visualPluginData );\nvoid\t\tUpdateTrackInfo( VisualPluginData * visualPluginData, ITTrackInfo * trackInfo, ITStreamInfo * streamInfo );\nvoid\t\tUpdatePulseRate( VisualPluginData * visualPluginData, UInt32 * ioPulseRate );\n\nvoid\t\tPulseVisual( VisualPluginData * visualPluginData, UInt32 timeStampID, const RenderVisualData * renderData, UInt32 * ioPulseRate );\nvoid\t\tInvalidateVisual( VisualPluginData * visualPluginData );\n\nstd::string\tGetVersionString();\nOSStatus\tVisualPluginHandler( OSType m, VisualPluginMessageInfo*, void* );\n"
  },
  {
    "path": "plugins/iTunes/main_mac.cpp",
    "content": "/*\n   Copyright 2005-2009 Last.fm Ltd. \n      - Primarily authored by Max Howell, Jono Cole, Erik Jaelevik, \n        Christian Muehlhaeuser\n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#import \"main.h\"\n#import \"common/c++/logger.h\"\n#import \"ITunesPlaysDatabase.h\"\n\n#import <AppKit/AppKit.h>\n#import <OpenGL/gl.h>\n#import <OpenGL/glu.h>\n#import <string.h>\n\n/** @author <michaelc@last.fm> */\n\n\nenum PlayerState\n{\n    /** transitions: playback started, track changed, or track unpaused\n      * sync: always */\n      Playing,\n    /** transitions: playback ended\n      * sync: always\n      * notes: mostly this only occurs after the last track in a playlist \n      *        finishes. However, it is possible for the iTunes pause button, \n      *        to become a stop button, ie. HTTP streaming. Basically this event\n      *        is rarely seen */\n      Stopped,\n    /** transitions: track paused\n      * sync: never */\n      Paused,\n      Unknown\n};\n\nstatic const char* kPlayerStates[4] = { \"Playing\", \"Stopped\", \"Paused\", \"Unknown\" };\n\n\nstatic inline int state( CFDictionaryRef d )\n{\n    CFStringRef s = (CFStringRef) CFDictionaryGetValue( d, CFSTR( \"Player State\" ) );\n\n    #define RETURN_IF_EQUAL( a, b ) \\\n            if (CFStringCompare( a, CFSTR( #b ), 0 ) == kCFCompareEqualTo ) \\\n                return b\n\n    // in order of frequency\n    RETURN_IF_EQUAL( s, Playing );\n    RETURN_IF_EQUAL( s, Paused );\n    RETURN_IF_EQUAL( s, Stopped );\n\n    return Unknown;\n}\n\n\nvoid\nnotificationCallback( CFNotificationCenterRef,\n                      void*,\n                      CFStringRef,\n                      const void*,\n                      CFDictionaryRef info )\n{\n    int const newState = state( info );\n\n    LOG( 3, \"iTunes player-state became: \" << kPlayerStates[newState] );\n\n    switch (newState)\n    {\n        case Stopped:\n        case Playing:\n            ITunesPlaysDatabase::sync();\n            break;\n        default:\n            break;\n    }\n}\n\n\nOSStatus\nVisualPluginHandler( OSType m, VisualPluginMessageInfo*, void* )\n{\n    switch (m)\n    {\n        case kVisualPluginInitMessage:\n        case kVisualPluginCleanupMessage:\n            // or we don't get the cleanup message in main()\n//            return noErr; TODO\n        default:\n            return unimpErr;\n    }\n}\n\n//-------------------------------------------------------------------------------------------------\n//\texported function prototypes\n//-------------------------------------------------------------------------------------------------\n\nextern \"C\" OSStatus iTunesPluginMainMachO( OSType inMessage, PluginMessageInfo *inMessageInfoPtr, void *refCon ) __attribute__((visibility(\"default\")));\n\n//-------------------------------------------------------------------------------------------------\n//\tGetVisualName\n//-------------------------------------------------------------------------------------------------\n//\nvoid GetVisualName( ITUniStr255 name )\n{\n\tCFIndex length = CFStringGetLength( kTVisualPluginName );\n    \n\tname[0] = (UniChar)length;\n\tCFStringGetCharacters( kTVisualPluginName, CFRangeMake( 0, length ), &name[1] );\n}\n\n//-------------------------------------------------------------------------------------------------\n//\tGetVisualOptions\n//-------------------------------------------------------------------------------------------------\n//\nOptionBits GetVisualOptions( void )\n{\n\tOptionBits\t\toptions = (kVisualSupportsMuxedGraphics | kVisualWantsIdleMessages);\n    \n\treturn options;\n}\n\n\n\n"
  },
  {
    "path": "plugins/iTunes/main_win.cpp",
    "content": "/*\n   Copyright 2004 Gareth Simpson <iscrobbler@xurble.org>\n   Copyright 2004-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n\n#include \"main.h\"\n\n#include \"common/c++/logger.h\"\n#include \"ITunesComThread.h\"\n#include \"Moose.h\"\n#include \"ScrobSubmitter.h\"\n\n#include <string>\n#include <iostream>\n#include <sstream>\n#include <fstream>\n#include <algorithm>\n#include <cwctype>\n#include <cstdlib>\n\n\n// WTL things\nHANDLE gHModule; // WTL handle populated in DLLMain\n\nextern ScrobSubmitter gSubmitter;\nextern ITunesComThread* gCom;\n\n// reporting things\nstd::wstring gStatusStringX; // just some temp debug info (even for the release build) \nstd::wstring gErrStringX; // an error\n\n// the current track info\nstd::wstring gArtist;\nstd::wstring gAlbumArtist;\nstd::wstring gTrack;\nstd::wstring gAlbum;\nstd::wstring gPath;\nstd::wstring gKind;\nint gLen = 0;\nint gStars = 0;\nint gBitrate = 0;\n\nDWORD gTimeOfLastStop = 0;\n\n\nenum EAsState\n{\n    AS_STOPPED,\n    AS_PLAYING,\n    AS_PAUSED\n};\n\nEAsState gASState = AS_STOPPED;\n\n\n/******************************************************************************\n * Utility functions                                                          *\n ******************************************************************************/\n\nvoid\nSetError( const std::wstring& err )\n{\n    LOGWL( 1, err );\n\n    gErrStringX = err;\n}\n\n\nvoid\nSetStatus( const std::wstring& stat )\n{\n    LOGWL( 3, stat );\n\n    gStatusStringX = stat;\n}\n\n\nvoid\nClearMemory( LogicalAddress dest, SInt32 length )\n{\n    register unsigned char *ptr;\n\n    ptr = (unsigned char *) dest;\n\n    if( length > 16 )\n    {\n        register unsigned long  *longPtr;\n\n        while( ((unsigned long) ptr & 3) != 0 )\n        {\n            *ptr++ = 0;\n            --length;\n        }\n\n        longPtr = (unsigned long *) ptr;\n\n        while( length >= 4 )\n        {\n            *longPtr++  = 0;\n            length      -= 4;\n        }\n\n        ptr = (unsigned char *) longPtr;\n    }\n\n    while( --length >= 0 )\n    {\n        *ptr++ = 0;\n    }\n}\n\n\nstatic bool\nTryMemory( wchar_t* ptr )\n{\n    wchar_t character;\n    __try\n    {\n        character = *ptr;\n    }\n    __except( EXCEPTION_EXECUTE_HANDLER )\n    {\n        return false;\n    }\n    return true;\n}\n\nvoid\nLogTrack()\n{\n    LOGWL( 3, \"Artist: \" << gArtist << \"\\n  \" <<\n        \"Album Artist: \" << gAlbumArtist << \"\\n  \" <<\n        \"Track: \" << gTrack << \"\\n  \" <<\n        \"Album: \" << gAlbum << \"\\n  \" <<\n        \"Length: \" << gLen << \"\\n  \" <<\n        \"Path: \" << gPath << \"\\n  \" <<\n        \"Kind: \" << gKind << \"\\n  \" <<\n        \"Bitrate: \" << gBitrate );\n}\n\n\n/*******************************************************************************\n * Scrobbling functions                                                        *\n *******************************************************************************/\n\n/** submits the current song to audioscrobbler */\nstatic void ASStart()\n{\n    int id = gSubmitter.Start( Moose::wStringToUtf8( gArtist ),\n                               Moose::wStringToUtf8( gAlbumArtist ),\n                               Moose::wStringToUtf8( gTrack ),\n                               Moose::wStringToUtf8( gAlbum ),\n                               \"\",\n                               gLen,\n                               Moose::wStringToUtf8( gPath ),\n                               ScrobSubmitter::UTF_8 );\n\n    std::wostringstream os;\n    os << L\"ReqID \" << id << \": \" << L\"Sent Start for \"\n       << gArtist << \" - \" << gTrack;\n    LOGWL( 3, os.str() );\n\n    gASState = AS_PLAYING;\n}\n\n\nstatic void ASStop()\n{\n    int id = gSubmitter.Stop();\n\n    std::ostringstream os;\n    os << \"ReqID \" << id << \": \" << \"Sent Stop\";\n    LOGL( 3, os.str() );\n\n    gArtist = L\"\";\n\tgAlbumArtist = L\"\";\n    gTrack = L\"\";\n\n    gASState = AS_STOPPED;\n}\n\nstatic void StopCallback()\n{\n\t// This gets called if we recieved a stop message\n\t// and it's an actaul stop (not a pause)\n\n\t// check that we are in the paused state before calling stop\n\t// there's a small chance if a race condition where we may\n\t// have resumed in the meantime\n\tif ( gASState == AS_PAUSED )\n\t\tASStop();\n}\n\n\nstatic void ASPause()\n{\n    int id = gSubmitter.Pause();\n\n    std::ostringstream os;\n    os << \"ReqID \" << id << \": \" << \"Sent Pause\";\n    LOGL( 3, os.str());\n\n    gASState = AS_PAUSED;\n}\n\n\nstatic void ASResume()\n{\n    int id = gSubmitter.Resume();\n\n    LOGL( 3, \"ReqID \" << id << \": \" << \"Sent Resume\" );\n\n    gASState = AS_PLAYING;\n}\n\n\nvoid ScrobSubCallback(int reqID, bool error, std::string message, void* userData)\n{\n#ifdef _DEBUG\n    if (error)\n    {\n        MessageBox( NULL, message.c_str(), NULL, MB_OK );\n    }\n#endif\n\n    LOGL( 3, \"ReqID \" << reqID << \": \" << message );\n}\n\n\n/*******************************************************************************\n * Our own functions                                                           *\n *******************************************************************************/\n\nstatic void\nHandleTrack( ITTrackInfo* pTrack )\n{\n    if ( pTrack == NULL )\n        return;\n\n    std::wstring artist = (wchar_t*)pTrack->artist;\n\tstd::wstring albumArtist = (wchar_t*)pTrack->albumArtist;\n    std::wstring track = (wchar_t*)pTrack->name;\n    artist = Moose::fixStr(artist);\n\talbumArtist = Moose::fixStr(albumArtist);\n    track = Moose::fixStr(track);\n\n    // On a 1x looped track, we will get a ChangeTrack event which means we\n    // won't have gone into paused and will just drop through to the new\n    // track code.\n\n    bool didWeActuallyResume = false;\n    if ( gASState == AS_PAUSED && \n       ( artist == gArtist && track == gTrack ) )\n    {\n        // We'll get here if the same track started again. If the elapsed\n        // time since last stop is less than a second, we interpret it as\n        // a restart, if it is longer, we interpret it as a resume.\n        DWORD elapsed = GetTickCount() - gTimeOfLastStop;\n        didWeActuallyResume = elapsed > 1000;\n\n        LOGL( 3, \"Resume check, elapsed: \" << elapsed );\n    }\n        \n    if ( didWeActuallyResume )\n    {\n        ASResume();\n    }\n    else\n    {\n        // track change, set globals\n        ASStop();\n\n        gArtist  = artist;\n\t\tgAlbumArtist = albumArtist;\n        gTrack = track;\n        gAlbum = (wchar_t*)pTrack->album;\n        gAlbum = Moose::fixStr(gAlbum);\n\n        // \"Audio CD Track\"\n        // \"MPEG audio stream\"\n        // \"MPEG audio track\"...\n        gKind = (wchar_t*)pTrack->kind;\n        gKind = Moose::fixStr(gKind);\n\n        gLen = pTrack->totalTimeInMS / 1000;\n        gStars = pTrack->trackRating;\n        gBitrate = pTrack->bitRate;\n\n        std::wstring fileName = (wchar_t*)pTrack->fileName;\n        fileName = Moose::fixStr(fileName);\n\n        // What type of track is this?\n        char type = '\\0';\n        if (pTrack->bitRate == 1411)\n        {\n            // deffo a CD\n            type = 'c';\n            LOGL( 3, \"It's a CD\");\n        }\n        else if (fileName.size() == 0)\n        {\n            // Filename size is also 0 when playing a file over local network...\n            std::transform(gKind.begin(), gKind.end(), gKind.begin(), std::towupper); \n            if (gKind.find(L\"STREAM\") != std::wstring::npos)\n            {\n                type = 's';\n                LOGL( 3, \"It's a stream\");\n            }\n            else\n            {\n                type = 'f';\n                LOGL( 3, \"It's a shared playlist file\");\n            }\n        }\n        else\n        {\n            // a music file\n            type = 'f';\n            LOGL( 3, \"It's a file\");\n        }\n\n        if (type == 's')\n        {\n            // We don't do streams\n            return;\n        }\n\n        // Only try and find the path if it's a file as opposed to a stream or\n        // a track off CD\n        if (type == 'f')\n        {\n            // Check for video, not the most reliable as it relies on kind string\n            //std::string sKind = CW2A(gKind.c_str());\n            std::string sKind = \"\";\n            transform(sKind.begin(), sKind.end(), sKind.begin(), tolower);\n            if ( (sKind.find(\"video\", 0) != std::string::npos) || \n                (sKind.find(\"movie\", 0) != std::string::npos) )\n            {\n                LOGL( 3, \"Video file, won't submit\");\n                return;\n            }\n\n            if ( fileName.size() > 0 )\n            {\n                gPath = fileName;\n            }\n            else\n            {\n                gPath = L\"\";\n            }\n        }\n        else if (type == 'c')\n        {\n            gPath = L\"cd\";\n        }\n        else\n        {\n            gPath = L\"\";\n        }\n\n        LogTrack();\n\n        ASStart();\n\n        // Give this track to the ITunesComThread for syncing playcount with local db\n        VisualPluginTrack vpt = {\n            gArtist,\n\t\t\tgAlbumArtist,\n            gTrack,\n            gAlbum,\n            gPath,\n            pTrack->playCount };\n        \n        // If iPod scrobbling is switched off, this pointer will not have been\n        // initialised so we need to check it first.\n        if ( gCom != 0 )\n            gCom->syncTrack( vpt );\n    }\n}\n\n\n/*******************************************************************************\n * iTunes Plugin callbacks                                                     *\n *******************************************************************************/\n\nstatic void\nProcessRenderData( VisualPluginData *visualPluginData, const RenderVisualData *renderData )\n{\n    //  we don't do any complex processing with render data \n    //  at the moment - but it is an indication that we are playing\n}\n\n\n/** DrawVisual - this is the main drawing code */\nvoid DrawVisual( VisualPluginData * visualPluginData )\n{\n\tif ( !(visualPluginData && visualPluginData->destView != NULL) )\n        return;\n\n    HDC hdc = GetDC(visualPluginData->destView);\n\n    HBRUSH brush = CreateSolidBrush(RGB(220, 220, 220));\n\n    RECT client;\n    ::GetClientRect( visualPluginData->destView, &client );\n\n    // Paint background\n    FillRect(hdc, &client, brush);\n\n    // Draw version string\n    SetBkMode(hdc, TRANSPARENT);\n    SelectObject(hdc, GetStockObject(DEFAULT_GUI_FONT)) ;\n    RECT textRect = {10, 10, 400, 30};\n    std::ostringstream os;\n    os << kTVisualPluginName << \" \" << GetVersionString();\n    DrawText(hdc, os.str().c_str(), -1, &textRect, DT_LEFT | DT_TOP);\n\n    // Draw options box\n    RECT boxRect = { visualPluginData->destRect.right - 144, visualPluginData->destRect.top + 10,\n                     visualPluginData->destRect.right - 10, visualPluginData->destRect.top + 50 };\n    DeleteObject(brush);\n    brush = CreateSolidBrush(RGB(250, 250, 250));\n    SelectObject(hdc, brush);\n    //HPEN pen = GetStockObject(BLACK_PEN);\n    SelectObject(hdc, GetStockObject(BLACK_PEN));\n    Rectangle(hdc, boxRect.left - 4, boxRect.top - 4, boxRect.right + 4, boxRect.bottom + 4);\n    DrawText(hdc, \"Open the Last.fm\\napplication to change your\\nsettings.\",\n             -1, &boxRect, DT_LEFT | DT_TOP);\n\n    DeleteObject(brush);\n    ReleaseDC(visualPluginData->destView, hdc);\n}\n\n\n/** AllocateVisualData is where you should allocate any information that depends\n  * on the port or rect changing (like offscreen GWorlds).\n  */\nstatic OSStatus\nAllocateVisualData (VisualPluginData *visualPluginData, const Rect *destRect)\n{\n    return noErr;\n}\n\n//-------------------------------------------------------------------------------------------------\n//\tGetVisualOptions\n//-------------------------------------------------------------------------------------------------\n//\nOptionBits GetVisualOptions( void )\n{\n\treturn kVisualWantsIdleMessages;\n}\n\n\n/** DeallocateVisualData is where you should deallocate the things you have\n  * allocated.\n  */\nstatic void\nDeallocateVisualData (VisualPluginData *visualPluginData)\n{}\n\n\nstatic Boolean\nRectanglesEqual(const Rect *r1, const Rect *r2)\n{\n    if (\n        (r1->left == r2->left) &&\n        (r1->top == r2->top) &&\n        (r1->right == r2->right) &&\n        (r1->bottom == r2->bottom)\n       )\n        return true;\n\n    return false;\n}\n\n\nOSStatus MoveVisual( VisualPluginData * visualPluginData, OptionBits newOptions )\n{\n\tGetClientRect( visualPluginData->destView, &visualPluginData->destRect );\n\tvisualPluginData->destOptions = newOptions;\n\n\treturn noErr;\n}\n\n\nOSStatus DeactivateVisual( VisualPluginData * visualPluginData )\n{\n\tvisualPluginData->destView = NULL;\n\treturn noErr;\n}\n\n\nstatic void\nResetRenderData (VisualPluginData *visualPluginData)\n{\n    memset( &visualPluginData->renderData, 0, sizeof(visualPluginData->renderData) );\n\tmemset( visualPluginData->minLevel, 0, sizeof(visualPluginData->minLevel) );\n}\n\n\nOSStatus\nVisualPluginHandler( OSType message, VisualPluginMessageInfo* messageInfo, void* refCon )\n{\n    OSStatus status = noErr;\n\n    VisualPluginData* visualPluginData = (VisualPluginData*)refCon;\n\n    #define _( x ) x: LOGL( 3, \"EVENT: \" #x );\n\n    switch (message)\n    {\n        /** Sent when the visual plugin is registered.  The plugin should do \n          * minimal memory allocations here.  The resource fork of the plugin is \n          * still available. */\n\tcase _(kVisualPluginInitMessage)\n        {\n            visualPluginData = (VisualPluginData *)malloc(sizeof(VisualPluginData));\n            if (visualPluginData == nil)\n            {\n                status = memFullErr;\n                break;\n            }\n\n            visualPluginData->appCookie = messageInfo->u.initMessage.appCookie;\n            visualPluginData->appProc   = messageInfo->u.initMessage.appProc;\n\n            // Remember the file spec of our plugin file. We need this so we can\n            // open our resource fork during the configuration message\n\n            messageInfo->u.initMessage.refCon = (void*) visualPluginData;\n        }\n        break;\n\n        /** Sent when the visual plugin is unloaded */\n\tcase _(kVisualPluginCleanupMessage)\n        {\n            ASStop();\n\n            if (visualPluginData != nil)\n                free( visualPluginData );\n        }\n        break;\n\n        /** Sent when the visual plugin is enabled.  iTunes currently enables\n          * all loaded visual plugins.  The plugin should not do anything here.\n          */\n\tcase _(kVisualPluginEnableMessage)\n            break;\n\n\tcase _(kVisualPluginDisableMessage)\n            ASStop();\n            break;\n\n        /** Sent if the plugin requests idle messages.  Do this by setting the\n          * kVisualWantsIdleMessages option in the \n          * PlayerRegisterVisualPluginMessage.options field. */\n        case kVisualPluginIdleMessage:\n        {\n            //TODO this is called a lot, lets not do anything here..\n            \n            // The render msg will take care of refreshing the screen if we're playing\n            if ( !visualPluginData->playing )\n            {\n                DrawVisual( visualPluginData );\n            }\n        }\n        break;\n\n        /** Sent if the plugin requests the ability for the user to configure \n          * it.  Do this by setting the kVisualWantsConfigure option in the \n          * PlayerRegisterVisualPluginMessage.options field. */\n\t\tcase _(kVisualPluginConfigureMessage)\n            break;\n\n        /** Sent when iTunes is going to show the visual plugin in a port.  At\n          * this point, the plugin should allocate any large buffers it needs.\n          * Gets called once when window is first displayed. */\n\t\tcase _(kVisualPluginActivateMessage)\n        /** Sent when iTunes needs to change the port or rectangle of the\n          * currently displayed visual. Resize. */\n        case _(kVisualPluginWindowChangedMessage)\n        {\n \t\t\tstatus = MoveVisual( visualPluginData, messageInfo->u.windowChangedMessage.options );\n\t\t\tbreak;\n        }\n        break;\n\n        /** Sent when iTunes is no longer displayed. */\n\t\tcase _(kVisualPluginDeactivateMessage)\n        {\n            status = DeactivateVisual( visualPluginData );\n        }\n        break;\n\n        /** Sent for the visual plugin to render a frame. Only get these when \n          * playing. */\n        case _(kVisualPluginDrawMessage)\n            DrawVisual( visualPluginData );\n            break;\n\n        /** Sent when the playback starts */\n\t\tcase _(kVisualPluginPlayMessage)\n\t\t\tHandleTrack( messageInfo->u.playMessage.trackInfo );\n            visualPluginData->playing = true;\n            break;\n\n        /* Sent when the player changes the current track information. This is\n         * used when the information about a track changes, or when the CD moves\n         * onto the next track. The visual plugin should update any displayed\n         * information about the currently playing song. */\n\t\tcase _(kVisualPluginChangeTrackMessage)\n            HandleTrack( messageInfo->u.changeTrackMessage.trackInfo );\n            break;\n\n        /** Sent when the player stops. */\n\t\tcase _(kVisualPluginStopMessage)\n        {\n            if ( gASState == AS_PLAYING )\n            {\n                gTimeOfLastStop = GetTickCount();\n                ASPause();\n            }\n\n            visualPluginData->playing = false;\n\n            ResetRenderData(visualPluginData);\n            DrawVisual(visualPluginData);\n\n\t\t\tif ( gCom )\n\t\t\t{\n\t\t\t\t// There is not a pause message to we take all\n\t\t\t\t// stopped messages as pause\n\n\t\t\t\t// this will mean we get called back if there is no current track\n\t\t\t\t// i.e. we have actual stopped (probably at the end of a playlist)\n\t\t\t\tgCom->callbackIfStopped( StopCallback );\n\n\t\t\t\t// This means that the com thread will sync the plays database\n\t\t\t\t// is an actual stop happened\n\t\t\t\tgCom->stop();\n\t\t\t}\n\t\t}\n        break;\n\n        /** Sent when the player changes the track position. */\n\t\tcase _(kVisualPluginSetPositionMessage)\n            break;\n\n        default:\n            status = unimpErr;\n            break;\n    }\n\n    #undef _ //logging helper macro\n\n    return status;\n}\n\nvoid GetVisualName( ITUniStr255 name )\n{\t\n\tname[0] = (UniChar)wcslen( kTVisualPluginName );\n\twcscpy_s( (wchar_t *)&name[1], 255, kTVisualPluginName );\n}\n"
  },
  {
    "path": "plugins/iTunes/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by iScrobbleWin.rc\r\n//\r\n#define IDHELP2                         10\r\n#define IDCLEAR                         10\r\n#define IDD_DIALOG1                     101\r\n#define IDC_LIST1                       1002\r\n#define IDC_LIST                        1003\r\n#define IDC_USERNAME                    1004\r\n#define IDC_PASSWORD                    1005\r\n#define IDC_PROXY_CHECK                 1007\r\n#define IDC_AUTH_CHECK                  1008\r\n#define IDC_SERVER                      1010\r\n#define IDC_PUSERNAME                   1011\r\n#define IDC_PPASS                       1013\r\n#define IDC_CHECK1                      1015\r\n#define IDC_ENABLED                     1016\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        110\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1017\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/iTunes/scripts/uninstall.sh",
    "content": "#!/bin/sh\n#@author Max Howell <max@last.fm>\n\nif [[ \"$1\" != \"--db-only\" ]]\nthen\n    # clearly, we have to be started with AudioScrobbler.bundle/Contents/MacOS\n    # as the working directory, then we explicitly delete the directory by name\n    # this is a safety precaution\n    cd ../../../\n    rm -rf AudioScrobbler.bundle\nfi\n\ncd ~/Library/Application\\ Support/Last.fm || exit 1\n\n# automatic iPod database\nrm iTunesPlays.db\n# manual iPod databases\nfind devices -name playcounts.db -delete\n"
  },
  {
    "path": "plugins/iTunes/tests/ITunesPlaysDatabaseMac.pro",
    "content": "CONFIG += qtestlib\nTEMPLATE = app\nTARGET = \nDEPENDPATH += .\n\nQT -= gui\nQT += sql\n\nBIN_DIR = bin\nBUILD_DIR = build\nDESTDIR = bin\n\nOBJECTS_DIR = $$BUILD_DIR\nMOC_DIR = $$BUILD_DIR\n\nmac:CONFIG -= app_bundle\n\n# Input\nHEADERS += ../ITunesPlaysDatabaseMac.h \\\n           ../common/ITunesTrack.h     \\\n           ../Log.h\n\nSOURCES += TestITunesPlaysDatabaseMac.cpp    \\\n           ../ITunesPlaysDatabaseCommon.cpp  \\\n           ../ITunesPlaysDatabaseMac.cpp     \\\n           ../Moose.cpp                      \\\n           ../common/ITunesTrack.cpp         \\\n           ../Log.cpp\n           \nLIBS += -lsqlite3\n\nINCLUDEPATH += ..\n"
  },
  {
    "path": "plugins/iTunes/tests/TestITunesPlaysDatabaseMac.cpp",
    "content": "/*\n   Copyright 2008-2009 Last.fm Ltd. \n\n   This file is part of the Last.fm Desktop Application Suite.\n\n   lastfm-desktop is free software: you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation, either version 3 of the License, or\n   (at your option) any later version.\n\n   lastfm-desktop is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with lastfm-desktop.  If not, see <http://www.gnu.org/licenses/>.\n*/\n#define private public\n    #include \"ITunesPlaysDatabase.h\"\n#undef private\n\n#include \"Moose.h\"\n\n#include <QtTest>\n#include <QtSql>\n\n\nclass TestITunesPlaysDatabaseMac : public QObject\n{\n    Q_OBJECT\n\n    public:\n        TestITunesPlaysDatabaseMac();\n\n    private slots:\n        void testIsValid();\n\n    private:\n        ITunesPlaysDatabase m_db;\n\n        inline void createTable()\n        {\n            QSqlQuery query; \n            query.exec( \"CREATE TABLE \" TABLE_NAME \" ( \"\n                        \"persistent_id   VARCHAR( 32 ) PRIMARY KEY,\"\n                        \"play_count      INTEGER )\" );\n        }\n                                                    \n        inline void deleteTable()\n        {\n            QSqlQuery query;\n            query.exec( \"DROP TABLE \" TABLE_NAME );\n        }\n};\n\n\nTestITunesPlaysDatabaseMac::TestITunesPlaysDatabaseMac()\n{\n    QSqlDatabase qdb = QSqlDatabase::addDatabase( \"QSQLITE\" );\n    qdb.setDatabaseName ( QString( Moose::applicationSupport().c_str() ) + \"iTunesPlays.db\" );\n    bool ok = qdb.open();\n}\n\n\nvoid TestITunesPlaysDatabaseMac::testIsValid()\n{\n    \n    deleteTable();\n    \n    QCOMPARE( m_db.isValid(), false );\n    \n    createTable();\n                    \n    QCOMPARE( m_db.isValid(), true );\n}\n\n\nQTEST_MAIN( TestITunesPlaysDatabaseMac )\n\n#include \"TestITunesPlaysDatabaseMac.moc\"\n"
  },
  {
    "path": "plugins/iTunes/tests/comtest.cpp",
    "content": "// comtest.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n#include \"ITunesComThread.h\"\r\n#include \"common/logger.h\"\r\n\r\n#include <string>\r\n#include <cstdio>\r\n\r\n#include <atlbase.h>\r\n#include <tchar.h>\r\n\r\n//class ComtestModule : public CAtlExeModuleT< ComtestModule >\r\n//{\r\n//};\r\n\r\n//ComtestModule _AtlModule;\r\n\r\nint _tmain(int argc, _TCHAR* argv[])\r\n{\r\n    Logger::GetLogger().Init( L\"test.log\" );\r\n\r\n    printf(\"main\");\r\n    \r\n    ITunesComThread t;\r\n\r\n    //Sleep( 1000 * 1000 );\r\n\r\n    getchar();\r\n\r\n\treturn 0;\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/iTunes/tests/tests.pro",
    "content": "TEMPLATE = subdirs\n\nSUBDIRS = ITunesPlaysDatabaseMac.pro\n"
  },
  {
    "path": "plugins/iTunes/tools/append_once.bat",
    "content": "REM %1 - string to append\r\nREM %2 - file to append it to\r\nfind /C /I %1 %2\r\nif not errorlevel 1 goto end\r\n    echo start /WAIT \"\" %1 /SILENT >> %2\r\n:end"
  },
  {
    "path": "plugins/scrobsub/BlockingClient.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#include \"BlockingClient.h\"\r\n\r\n#define USE_LOGGER (0)\r\n\r\n#if USE_LOGGER\r\n    #include \"Logger.h\"\r\n#else\r\n    #define LOG(x, y)\r\n#endif\r\n\r\n#ifdef WIN32\r\n    #include <crtdbg.h> // for _ASSERT\r\n#else\r\n    #include <assert.h>\r\n    #define _ASSERT(x) assert(x)\r\n    #include <arpa/inet.h>\r\n    #include <netdb.h>\r\n    #include <errno.h>\r\n#endif\r\n\r\n#include <sstream> // for ostringstream\r\n\r\nusing namespace std;\r\n\r\n/******************************************************************************\r\n    Constants\r\n******************************************************************************/\r\nstatic const int   kBufferSize = 1024;\r\n\r\n/******************************************************************************\r\n    BlockingClient\r\n******************************************************************************/\r\nBlockingClient::BlockingClient() :\r\n    mSocket(INVALID_SOCKET)\r\n{\r\n    #ifdef WIN32\r\n    \r\n        // Start Winsock up\r\n        WSAData wsaData;\r\n        int nCode = WSAStartup(MAKEWORD(1, 1), &wsaData);\r\n        \r\n        if (nCode != 0)\r\n        {\r\n            int nErrorCode = WSAGetLastError();\r\n            ostringstream osErr;\r\n            osErr << \"Winsock initialisation failed. Socket error: \" << nErrorCode;\r\n            throw NetworkException(osErr.str());\r\n        }\r\n    \r\n    #endif\r\n}\r\n\r\n/******************************************************************************\r\n   ~BlockingClient\r\n******************************************************************************/\r\nBlockingClient::~BlockingClient()\r\n{\r\n    #ifdef WIN32\r\n        // Shut Winsock back down\r\n        WSACleanup();\r\n    #endif\r\n}\r\n\r\n/******************************************************************************\r\n    Connect\r\n******************************************************************************/\r\nvoid\r\nBlockingClient::Connect(\r\n    const string& sHost,\r\n    u_short       nPort)\r\n{\r\n    // If anything in here throws, let it propagate up\r\n    \r\n    u_long nRemoteAddress = LookUpAddress(sHost);\r\n    \r\n    mSocket = ConnectToSocket(nRemoteAddress, nPort);\r\n}\r\n\r\n/******************************************************************************\r\n    LookUpAddress\r\n******************************************************************************/\r\nu_long\r\nBlockingClient::LookUpAddress(\r\n    const string& sHost)\r\n{\r\n    u_long nRemoteAddr = inet_addr(sHost.c_str());\r\n\r\n    if (nRemoteAddr == INADDR_NONE)\r\n    {\r\n        // Host isn't a dotted IP, so resolve it through DNS\r\n        hostent* pHE = gethostbyname(sHost.c_str());\r\n        if (pHE == NULL)\r\n        {\r\n            ostringstream osErr;\r\n            osErr << \"Lookup of hostname \" << sHost << \" failed.\";\r\n            throw NetworkException(osErr.str());\r\n        }\r\n\r\n        nRemoteAddr = *((u_long*)pHE->h_addr_list[0]);\r\n    }\r\n\r\n    return nRemoteAddr;\r\n}\r\n\r\n\r\n/******************************************************************************\r\n    ConnectToSocket\r\n******************************************************************************/\r\nSOCKET\r\nBlockingClient::ConnectToSocket(\r\n    u_long  nRemoteAddr,\r\n    u_short nPort)\r\n{\r\n    // Create a stream socket\r\n    SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);\r\n\r\n    if (sd == INVALID_SOCKET)\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Couldn't create socket. Socket error: \";\r\n\r\n        #ifdef WIN32\r\n            osErr << WSAGetLastError();\r\n        #else\r\n            osErr << errno;\r\n        #endif\r\n\r\n        throw NetworkException(osErr.str());        \r\n    }\r\n\r\n    sockaddr_in sinRemote;\r\n    sinRemote.sin_family = AF_INET;\r\n    sinRemote.sin_addr.s_addr = nRemoteAddr;\r\n\r\n    sinRemote.sin_port = htons(nPort);\r\n\r\n    int nCode = connect(sd, (sockaddr*)&sinRemote, sizeof(sockaddr_in));\r\n    \r\n    if (nCode == SOCKET_ERROR)\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Couldn't connect to server. Socket error: \";\r\n\r\n        #ifdef WIN32\r\n            osErr << WSAGetLastError();\r\n            closesocket(sd);\r\n        #else\r\n            osErr << errno;\r\n            close(sd);\r\n        #endif \r\n\r\n        throw NetworkException(osErr.str());        \r\n    }\r\n\r\n    return sd;\r\n}\r\n\r\n/******************************************************************************\r\n    Send\r\n******************************************************************************/\r\nvoid\r\nBlockingClient::Send(\r\n    const string& sData)\r\n{\r\n    _ASSERT(mSocket != INVALID_SOCKET);\r\n    \r\n    int nBytesToSend = static_cast<int>(sData.size());\r\n    int nTotalBytesSent = 0;\r\n\r\n    while (nTotalBytesSent < nBytesToSend)\r\n    {\r\n        // Should never block\r\n        int nBytesSent = send(mSocket,\r\n                              sData.c_str(),\r\n                              nBytesToSend - nTotalBytesSent,\r\n                              0);\r\n\r\n        if (nBytesSent == SOCKET_ERROR || nBytesSent == 0)\r\n        {\r\n            #ifdef WIN32\r\n                int nErrorCode = WSAGetLastError();\r\n            #else\r\n                int nErrorCode = errno;\r\n            #endif\r\n            ostringstream osErr;\r\n            osErr << \"Sending of data through socket failed. Socket error: \" << nErrorCode;\r\n            throw NetworkException(osErr.str());\r\n        }\r\n\r\n        // Send successful\r\n        nTotalBytesSent += nBytesSent;\r\n        \r\n    } // end while\r\n    \r\n}\r\n\r\n\r\n/******************************************************************************\r\n    Receive\r\n******************************************************************************/\r\nvoid\r\nBlockingClient::Receive(\r\n    string& sLine)\r\n{\r\n    _ASSERT(mSocket != INVALID_SOCKET);\r\n\r\n    // Read data from server.\r\n    char acReadBuffer[kBufferSize];\r\n    int nReadSize = kBufferSize - 1; // so that we can append a \\0\r\n    int nBytesRead;\r\n\r\n    // Go into loop that keeps going until a CR is received\r\n    bool bKeepGoing = true;\r\n    int nSanityCtr = 0;\r\n    do\r\n    {\r\n        // Will block until there is data available or timeout is reached\r\n        nBytesRead = recv(mSocket, acReadBuffer, nReadSize, 0);\r\n\r\n        if (nBytesRead == SOCKET_ERROR || nBytesRead == 0)\r\n        {\r\n            // This happens when something goes wrong, client dies or something.\r\n            // Caller should close talk socket and recover.\r\n            #ifdef WIN32\r\n                int nErrorCode = WSAGetLastError();\r\n            #else\r\n                int nErrorCode = errno;\r\n            #endif\r\n            ostringstream osErr;\r\n            osErr << \"Receiving data through socket failed. Socket error: \" << nErrorCode;\r\n            sLine = \"\";\r\n            throw NetworkException(osErr.str());\r\n        }\r\n\r\n        // Read successful, is last char a CR?\r\n        if (acReadBuffer[nBytesRead - 1] == '\\n')\r\n        {\r\n            // Step back to before \\n\r\n            nBytesRead--;\r\n            \r\n            // If so, we're done\r\n            bKeepGoing = false;\r\n        }\r\n\r\n        acReadBuffer[nBytesRead] = '\\0';\r\n\r\n        sLine += acReadBuffer;\r\n\r\n        // I don't THINK this should ever happen but the documentaion for recv\r\n        // is confusing so just to be on the safe side...\r\n        if ( nSanityCtr++ > 10 ) bKeepGoing = false;\r\n\r\n    } while (bKeepGoing);\r\n    \r\n}\r\n\r\n\r\n/******************************************************************************\r\n    ShutDown\r\n******************************************************************************/\r\nvoid\r\nBlockingClient::ShutDown()\r\n{\r\n    // Disallow any further data sends. This will tell the other side\r\n    // that we want to go away.\r\n    int nResult = shutdown(mSocket, SD_SEND);\r\n\r\n    if (nResult == SOCKET_ERROR)\r\n    {\r\n        // Even though this is an unforeseen failure, we don't want to\r\n        // throw as we're shutting down. Just carry on shutting down\r\n        // best we can.\r\n        \r\n        #ifdef WIN32\r\n            int nErrorCode = WSAGetLastError();\r\n        #else\r\n            int nErrorCode = errno;\r\n        #endif\r\n\r\n        ostringstream osErr;\r\n        osErr << \"Socket shutdown failed. Socket error: \" << nErrorCode;\r\n        LOG(1, osErr.str() << \"\\n\");\r\n    }\r\n\r\n    // Receive any extra data still sitting on the socket. After all\r\n    // data is received, this call will block until the remote host\r\n    // acknowledges the TCP control packet sent by the shutdown above.\r\n    // Then we'll get a 0 back from recv, signalling that the remote\r\n    // host has closed its side of the connection.\r\n    char acReadBuffer[kBufferSize];\r\n    int nSanityCtr = 0;\r\n    while (true)\r\n    {\r\n        int nBytesRead = recv(mSocket, acReadBuffer, kBufferSize, 0);\r\n\r\n        if (nBytesRead == SOCKET_ERROR)\r\n        {\r\n            // I don't think we care here if the call failed.\r\n            // Just carry on shutting down best we can.\r\n            #ifdef WIN32\r\n                int nErrorCode = WSAGetLastError();\r\n            #else\r\n                int nErrorCode = errno;\r\n            #endif\r\n\r\n            ostringstream osErr;\r\n            osErr << \"Waiting for shutdown confirmation failed. Socket error: \" << nErrorCode << \"\\n\";\r\n            LOG(1, osErr.str() << \"\\n\");\r\n            break;\r\n        }\r\n        else if (nBytesRead != 0)\r\n        {\r\n            string sTemp;\r\n            sTemp.append(acReadBuffer, nBytesRead);\r\n            ostringstream osErr;\r\n            osErr << \"Received \" << nBytesRead <<\r\n                     \" unexpected bytes during shutdown:\\n\" << sTemp.c_str();\r\n            LOG(1, osErr.str() << \"\\n\");\r\n            \r\n            if ( nSanityCtr++ > 10 ) break;\r\n        }\r\n        else\r\n        {\r\n            // Returned 0, what we expect\r\n            break;\r\n        }\r\n    }\r\n\r\n    // Close the socket\r\n    #ifdef WIN32\r\n        nResult = closesocket(mSocket);\r\n    #else\r\n        nResult = errno;\r\n    #endif\r\n\r\n    if (nResult == SOCKET_ERROR)\r\n    {\r\n        // Again, we don't want to throw. Log the error and continue.\r\n        #ifdef WIN32\r\n            int nErrorCode = WSAGetLastError();\r\n        #else\r\n            int nErrorCode = errno;\r\n        #endif\r\n        ostringstream osErr;\r\n        osErr << \"Couldn't close socket. Socket error: \" << nErrorCode;\r\n        LOG(1, osErr.str() << \"\\n\");\r\n    }\r\n\r\n    mSocket = INVALID_SOCKET;\r\n}\r\n\r\n\r\nbool\r\nBlockingClient::isConnected()\r\n{\r\n    return mSocket != INVALID_SOCKET;\r\n}"
  },
  {
    "path": "plugins/scrobsub/BlockingClient.h",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef BLOCKINGCLIENT_H\r\n#define BLOCKINGCLIENT_H\r\n\r\n#ifdef WIN32\r\n    #include <winsock2.h>\r\n#else\r\n    #include <stdexcept>    //TODO: check if this /should/ be included in Win32\r\n    #include <sys/socket.h>\r\n    #define INVALID_SOCKET -1\r\n    #define SOCKET_ERROR -1\r\n    #define SD_SEND SHUT_WR    \r\n    typedef int SOCKET;\r\n    typedef uint16_t u_short;\r\n    typedef uint32_t u_long;\r\n#endif\r\n\r\n#include <string>\r\n\r\n/*************************************************************************/ /**\r\n    Sockets-based client for sending and receiving commands down a socket\r\n    using Winsock2.\r\n\r\n    @author <erik@last.fm>\r\n******************************************************************************/\r\nclass BlockingClient\r\n{\r\npublic:\r\n\r\n    /*************************************************************************\r\n        Exception class for when things go wrong.\r\n    **************************************************************************/\r\n    class NetworkException : public std::logic_error {\r\n    public:\r\n        NetworkException(const std::string& sMsg) : logic_error(sMsg) { }\r\n    };\r\n\r\n    /*********************************************************************/ /**\r\n        Ctor\r\n    **************************************************************************/\r\n\tBlockingClient();\r\n\r\n    /*********************************************************************/ /**\r\n        Dtor\r\n    **************************************************************************/\r\n\tvirtual\r\n\t~BlockingClient();\r\n\r\n    /*********************************************************************/ /**\r\n        Connect to server.\r\n        \r\n        @param[in] sHost The host to connect to.\r\n        @param[in] nPort The port on the host to connect to.\r\n    **************************************************************************/\r\n    void\r\n    Connect(\r\n        const std::string& sHost,\r\n        u_short            nPort);\r\n\r\n    /*********************************************************************/ /**\r\n        Send a string down the socket.\r\n\r\n        @param[in] sData The data to send.\r\n    **************************************************************************/\r\n    void\r\n    Send(\r\n        const std::string& sData);\r\n\r\n    /*********************************************************************/ /**\r\n        Read a line from the socket.\r\n\r\n        @param[out] sLine String the received line is written to.\r\n    **************************************************************************/\r\n    void\r\n    Receive(\r\n        std::string& sLine);\r\n\r\n    /*********************************************************************/ /**\r\n        Shut down connection gracefully.\r\n    **************************************************************************/\r\n    void\r\n    ShutDown();\r\n\r\n    /*********************************************************************/ /**\r\n        Check if socket is connected.\r\n        //TODO: document return..    \r\n    **************************************************************************/\r\n\r\n    bool\r\n    isConnected();\r\n\r\nprivate:\r\n    \r\n    /*********************************************************************/ /**\r\n        Given an address string, determine if it's a dotted-quad IP address\r\n        or a domain address. If the latter, ask DNS to resolve it. In either\r\n        case, return resolved IP address. Throws CNetworkException on fail.\r\n    **************************************************************************/\r\n    u_long\r\n    LookUpAddress(\r\n        const std::string& sHost);\r\n\r\n    /*********************************************************************/ /**\r\n        Connects to a given address, on a given port, both of which must be\r\n        in network byte order. Returns newly-connected socket if we succeed,\r\n        or INVALID_SOCKET if we fail.\r\n    **************************************************************************/\r\n    SOCKET\r\n    ConnectToSocket(\r\n        u_long  nRemoteAddr,\r\n        u_short nPort);\r\n\r\n\r\n    SOCKET mSocket;\r\n};\r\n\r\n#endif // BLOCKINGCLIENT_H\r\n"
  },
  {
    "path": "plugins/scrobsub/Bootstrap.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#include \"ScrobSubmitter.h\"\r\n#include \"Bootstrap.h\"\r\n#include \"resource.h\"\r\n#include \"EncodingUtils.h\"\r\n\r\n#include <process.h> // for beginthreadex\r\n#include <commctrl.h> // for PBM_SETRANGE\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n\r\nstd::map< HWND, BootStrap* > BootStrap::m_hwndMap;\r\n\r\nBootStrap::BootStrap( const WCHAR* mediaPlayerName )\r\n          :m_mediaPlayerName( mediaPlayerName ),\r\n           m_hwndParent( NULL ),\r\n           m_bootStrapRequired( false ),\r\n           m_bootStrapHkey( NULL ),\r\n           m_dialogReady( false ),\r\n           m_cancel( false ),\r\n           m_paused( false ),\r\n           m_scrobSub( NULL ),\r\n           m_progressRange( 0 ),\r\n           m_hwndDialog( NULL ),\r\n           m_hwndProgressBar( NULL ),\r\n           m_progressDialogShown( NULL ),\r\n           m_pauseStateChanged( NULL ),\r\n           m_tracksFound( false )\r\n{\r\n    log( \"BootStrap ctor\" );\r\n\r\n    xmlBuffer << L\"<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\" << std::endl;\r\n    xmlBuffer << L\"<bootstrap version=\\\"1.0\\\" product=\\\"\" << mediaPlayerName << \"\\\" >\\n\";\r\n   \r\n    // If this fails the Bootstrap Required status will be set to false therefore it is safe to continue;\r\n    try\r\n    {\r\n        m_bootStrapHkey = RegistryUtils::GetKey( HKEY_CURRENT_USER, \"Software\\\\Last.fm\\\\Bootstrap\" );\r\n    }\r\n    catch( RegistryUtils::CRegistryException e )\r\n    {\r\n        log( \"Warning: bootstrap registry key not found\" );\r\n    }\r\n\r\n    //Bootstrap is not required therefore don't bother reading the localised strings\r\n    if( !(m_bootStrapRequired = queryBootStrapStatus()) )\r\n        return;\r\n\r\n    // FIXME: error handling. If no strings, it just prints a message and continues. Yet these strings\r\n    // are used throughout the class. We should fall back on defaults in case of errors.\r\n    try\r\n    {\r\n        HKEY stringsKey = RegistryUtils::GetKey( HKEY_CURRENT_USER, \"Software\\\\Last.fm\\\\Bootstrap\\\\Strings\" );\r\n        \r\n        WCHAR progressLabelBuffer[255];\r\n        RegistryUtils::QueryString( stringsKey, L\"progress_label\", progressLabelBuffer, 255, false );\r\n        m_strProgressLabel = progressLabelBuffer;\r\n\r\n        WCHAR completeLabelBuffer[255];\r\n        RegistryUtils::QueryString( stringsKey, L\"complete_label\", completeLabelBuffer, 255, false );\r\n        m_strCompleteLabel = completeLabelBuffer;\r\n\r\n        WCHAR progressTitleBuffer[255];\r\n        RegistryUtils::QueryString( stringsKey, L\"progress_title\", progressTitleBuffer, 255, false );\r\n        m_strProgressTitle = progressTitleBuffer;\r\n\r\n        WCHAR cancelConfirmationBuffer[255];\r\n        RegistryUtils::QueryString( stringsKey, L\"cancel_confirmation\", cancelConfirmationBuffer, 255, false );\r\n        m_strCancelConfirmation = cancelConfirmationBuffer;\r\n        \r\n        WCHAR noTracksFoundBuffer[255];\r\n        RegistryUtils::QueryString( stringsKey, L\"no_tracks_found\", noTracksFoundBuffer, 255, false );\r\n        m_strNoTracksFoundLabel = noTracksFoundBuffer;\r\n\r\n    }\r\n    catch( const RegistryUtils::CRegistryException& e )\r\n    {\r\n        std::ostringstream os;\r\n        os << \"Error loading strings from registry: \" << e.what();\r\n        log( os.str() );\r\n        \r\n        //Set default strings to english\r\n        m_strCancelConfirmation = L\"Are you sure you want to cancel the import?\";\r\n        m_strCompleteLabel = L\"Last.fm has imported your media library.\\n\\n Click OK to continue.\\n\\n Click OK to continue.\";\r\n        m_strProgressLabel = L\"Last.fm is importing your current media library...\";\r\n        m_strProgressTitle = L\"Last.fm Library Import\";\r\n        m_strNoTracksFoundLabel = L\"Last.fm couldn't find any played tracks in your media library.\";\r\n    }\r\n\r\n    // FIXME: error handling. What will happen if it fails to get the version numbers?\r\n    try\r\n    {\r\n        HKEY localClientKey = RegistryUtils::GetKey( HKEY_LOCAL_MACHINE, \"Software\\\\Last.fm\\\\Client\", false );\r\n\r\n        char strVersionBuffer[25];\r\n        try\r\n        {\r\n            RegistryUtils::QueryString( localClientKey, \"Version\", strVersionBuffer, 25, false  );\r\n        }\r\n        catch( RegistryUtils::CRegistryException& e )\r\n        {\r\n           log( \"Registry exception when querying for version number\" );\r\n        }\r\n\r\n        std::string strVersion = strVersionBuffer;\r\n        \r\n        int prevDotPos = 0;\r\n        int dotPos = strVersion.find( '.', prevDotPos );\r\n        m_clientVerMajor = atoi( strVersion.substr( prevDotPos, dotPos - prevDotPos).c_str() );\r\n\r\n        prevDotPos = dotPos + 1;\r\n        dotPos = strVersion.find( '.', prevDotPos );\r\n        m_clientVerMinor = atoi( strVersion.substr( prevDotPos, dotPos - prevDotPos).c_str() );\r\n\r\n        prevDotPos = dotPos + 1;\r\n        dotPos = strVersion.find( '.', prevDotPos );\r\n        m_clientVerRelease = atoi( strVersion.substr( prevDotPos, dotPos - prevDotPos).c_str() );\r\n\r\n        prevDotPos = dotPos + 1;\r\n        dotPos = strVersion.find( '.', prevDotPos );\r\n        m_clientVerFix = atoi( strVersion.substr( prevDotPos, dotPos - prevDotPos).c_str() );\r\n\r\n    }\r\n    catch ( RegistryUtils::CRegistryException e )\r\n    {\r\n        log( \"Error reading version from registry\" );\r\n    }\r\n\r\n    m_replacementMap['&'] = L\"&amp;\";\r\n    m_replacementMap['<'] = L\"&lt;\";\r\n    m_replacementMap['>'] = L\"&gt;\";\r\n\r\n    m_progressDialogShown = CreateEvent( \r\n        NULL,         // no security attributes\r\n        TRUE,         // manual reset event\r\n        FALSE,        // initial state is non-signaled\r\n        NULL);        // object name\r\n        \r\n    m_pauseStateChanged = CreateEvent( \r\n        NULL,         // no security attributes\r\n        TRUE,        // automatic reset event\r\n        FALSE,        // initial state is non-signaled\r\n        NULL);        // object name\r\n}\r\n\r\nBootStrap::~BootStrap()\r\n{\r\n    log( \"BootStrap dtor\" );\r\n\r\n    if ( !m_dialogThreadEnd || !m_cancel )\r\n        closeWindow();\r\n\r\n    if ( m_progressDialogShown != NULL )\r\n        CloseHandle( m_progressDialogShown );\r\n    \r\n    if ( m_pauseStateChanged != NULL  )\r\n        CloseHandle( m_pauseStateChanged );\r\n}\r\n\r\n// FIXME: good principle is to give functions names that reflect what they do. You\r\n// wouldn't expect a function called queryX() to modify the state of the object...\r\nbool BootStrap::queryBootStrapStatus()\r\n{\r\n    if( m_bootStrapHkey == NULL )\r\n        return false;\r\n\r\n    WCHAR result[255];\r\n    try\r\n    {\r\n        RegistryUtils::QueryString( m_bootStrapHkey, m_mediaPlayerName, result, 255, false );\r\n    } \r\n    catch ( RegistryUtils::CRegistryException e )\r\n    {\r\n        //No such value\r\n        return false;\r\n    }\r\n    \r\n    m_userName = result;\r\n\r\n    return result != L\"\";\r\n}\r\n\r\nbool BootStrap::bootStrapRequired()\r\n{\r\n    return m_bootStrapRequired;\r\n}\r\n\r\n/************************************************************************/\r\n/* Process the window callback messages                                 */\r\n/************************************************************************/\r\nLRESULT CALLBACK BootStrap::DialogProc(HWND hwndDlg, \r\n                                       UINT message, \r\n                                       WPARAM wParam, \r\n                                       LPARAM lParam) \r\n{\r\n    switch( message )\r\n    {\r\n    case WM_COMMAND:\r\n        switch(LOWORD(wParam))\r\n        {\r\n        case IDC_BUTTONCANCEL:\r\n            {\r\n                BootStrap* bootstrap = m_hwndMap[ hwndDlg ];\r\n\r\n                bootstrap->log( \"Cancel clicked\" );\r\n\r\n                bootstrap->cancel();\r\n                break;\r\n            }\r\n\r\n        case IDC_BUTTONOK:\r\n            {\r\n                BootStrap* bootstrap = m_hwndMap[ hwndDlg ];\r\n\r\n                bootstrap->log( \"OK clicked\" );\r\n                \r\n                bootstrap->closeWindow();\r\n                break;\r\n            }\r\n        }\r\n        break;\r\n\r\n    default:\r\n        return FALSE;\r\n    }\r\n    return FALSE;\r\n}\r\n\r\n/************************************************************************/\r\n/* Close the progress window and end the thread                         */\r\n/************************************************************************/\r\nvoid BootStrap::closeWindow()\r\n{\r\n    log( \"BootStrap::closeWindow\" );\r\n\r\n    int resultCode;\r\n    BOOL result = EndDialog( m_hwndDialog, (INT_PTR)&resultCode );\r\n    if( resultCode == 0 )\r\n    {\r\n        // FIXME: what's this code for, I wonder :)\r\n        // And what's the result BOOL?\r\n        DWORD error = GetLastError();\r\n        \r\n        std::ostringstream os;\r\n        os << \"EndDialog failed, error: \" << error;\r\n        log( os.str() );\r\n    }\r\n\r\n    m_dialogThreadEnd = true;\r\n}\r\n\r\n/************************************************************************/\r\n/* Setup thread to display the progress window                          */\r\n/************************************************************************/\r\nvoid BootStrap::showProgress()\r\n{\r\n    log( \"Starting progress dialog thread\" );\r\n\r\n    unsigned int threadId;\r\n    m_hDialogThread = reinterpret_cast<HANDLE>(_beginthreadex( NULL,\r\n                                                0,\r\n                                                BootStrap::dialogThreadEntry,\r\n                                                this,\r\n                                                0,\r\n                                                &threadId ) );\r\n\r\n    // FIXME: Ideally should do some error checking here                                                \r\n\r\n    std::ostringstream os;\r\n    os << \"Progress dialog thread started, handle: \" << m_hDialogThread;\r\n    log( os.str() );\r\n}\r\n\r\n\r\nbool BootStrap::startBootStrap()\r\n{\r\n    log( \"Starting bootstrap thread\" );\r\n\r\n    unsigned int threadId;\r\n    m_bootstrapThread = reinterpret_cast<HANDLE>(_beginthreadex( NULL,\r\n                                                                 0,\r\n                                                                 BootStrap::bootstrapThreadEntry,\r\n                                                                 this,\r\n                                                                 0,\r\n                                                                 &threadId));\r\n\r\n    std::ostringstream os;\r\n    os << \"Bootstrap thread started, handle: \" << m_bootstrapThread;\r\n    log( os.str() );\r\n\r\n    // FIXME: Ideally should do some error checking here                                                \r\n    return true;\r\n}\r\n\r\n/************************************************************************/\r\n/* static entry point for bootstrap thread                              */\r\n/************************************************************************/\r\nunsigned __stdcall BootStrap::bootstrapThreadEntry( LPVOID lpParam )\r\n{\r\n    BootStrap* bootstrapper = static_cast<BootStrap*>(lpParam);\r\n    bootstrapper->showProgress();\r\n    \r\n    bootstrapper->log( \"Bootstrapper called showProgress, will now wait for event\" );\r\n\r\n    WaitForSingleObject( bootstrapper->m_progressDialogShown, INFINITE );\r\n    \r\n    bootstrapper->log( \"Event signalled, calling start\" );\r\n\r\n    bootstrapper->start();\r\n\r\n    bootstrapper->log( \"start returned, bootstrapper finished\" );\r\n\r\n    return 0;\r\n}\r\n\r\n\r\n/************************************************************************/\r\n/* static entry point for window thread                                 */\r\n/************************************************************************/\r\nunsigned __stdcall BootStrap::dialogThreadEntry( LPVOID lpParam )\r\n{\r\n    BootStrap* bootstrapper = static_cast<BootStrap*>(lpParam);\r\n    bootstrapper->dialogEventLoop();\r\n    return 0;\r\n}\r\n\r\n/************************************************************************/\r\n/* Create window and process messages                                   */\r\n/************************************************************************/\r\nvoid BootStrap::dialogEventLoop()\r\n{\r\n    log( \"Starting dialogEventLoop\" );\r\n\r\n    m_hwndDialog = CreateDialogW( m_module,\r\n                                  MAKEINTRESOURCEW( IDD_PROGRESSFORM ),\r\n                                  m_hwndParent,\r\n                                  (DLGPROC)BootStrap::DialogProc );\r\n\r\n    m_hwndMap[ m_hwndDialog ] = this;\r\n\r\n    // FIXME: error never used\r\n    DWORD error = GetLastError();\r\n\r\n    m_hwndProgressBar = GetDlgItem( m_hwndDialog, IDC_PROGRESS1 );\r\n\r\n    HWND hwndLabel = GetDlgItem( m_hwndDialog, IDC_LABEL );\r\n\r\n    // EJ: Just out of interest, why do you read the string into a member at construct time and then\r\n    // access the member here, instead of just calling a function that reads it straight here?\r\n    //set the label from the registry key\r\n    SetWindowTextW( hwndLabel, (LPCWSTR)m_strProgressLabel.c_str() );\r\n\r\n    //set the window title from the registry key\r\n    SetWindowTextW( m_hwndDialog, (LPCWSTR)m_strProgressTitle.c_str() );\r\n\r\n    //Set Dialog Position to Parent position\r\n    if( m_hwndParent )\r\n    {\r\n        RECT parentPos;\r\n        GetWindowRect( m_hwndParent, &parentPos );\r\n\r\n        RECT dialogPos;\r\n        GetWindowRect( m_hwndDialog, &dialogPos );\r\n\r\n        SetWindowPos( m_hwndDialog, m_hwndParent,\r\n            ( ( parentPos.left + parentPos.right ) / 2 ) - ( ( dialogPos.right - dialogPos.left ) / 2 ),\r\n            ( ( parentPos.top + parentPos.bottom ) / 2 ) - ( ( dialogPos.top - dialogPos.bottom ) / 2 ),\r\n            NULL, NULL, SWP_NOSIZE || SWP_ASYNCWINDOWPOS );\r\n    }\r\n\r\n    setProgressRange( m_progressRange );\r\n    setProgressValue( m_progressValue );\r\n\r\n    ShowWindow( m_hwndDialog, SW_SHOWNORMAL );\r\n\r\n    log( \"Dialog shown, setting event to signalled\" );\r\n\r\n    SetEvent( m_progressDialogShown );\r\n    \r\n    MSG message;\r\n    BOOL messageVal;\r\n    m_dialogThreadEnd = false;\r\n    while( messageVal = GetMessage( &message, NULL, 0, 0 ) && !m_dialogThreadEnd && !m_cancel )\r\n    {\r\n        if( messageVal < 0 )\r\n        {\r\n            // FIXME: what about localisation here? And why are we using T-strings?\r\n            std::basic_stringstream<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > errorTxt;\r\n            errorTxt << _T( \"Event loop error \" ) << GetLastError();\r\n            MessageBox( NULL, errorTxt.str().c_str(), _T( \"Error...\" ), MB_OK | MB_ICONEXCLAMATION );\r\n        }\r\n        else\r\n        {\r\n            TranslateMessage( &message );\r\n            DispatchMessage( &message );\r\n        }\r\n    }\r\n\r\n    std::ostringstream os;\r\n    os << \"Dialog loop exited\\nmessageVal: \" << messageVal << \", m_dialogThreadEnd: \" << m_dialogThreadEnd << \", m_cancel: \" << m_cancel;\r\n    log( os.str() );\r\n    \r\n    if( m_cancel )\r\n    {\r\n        closeWindow();\r\n    }\r\n}\r\n\r\nvoid BootStrap::setProgressRange( int maxValue )\r\n{\r\n    if( maxValue == 0 )\r\n    {\r\n        // no tracks to bootstrap so just set progress bar to 100%\r\n        setProgressRange( 1 );\r\n        setProgressValue( 1 );\r\n        return;\r\n    }\r\n\r\n    if( m_hwndProgressBar )\r\n        SendMessage( m_hwndProgressBar, PBM_SETRANGE, 0, MAKELPARAM( 0, maxValue ) );\r\n\r\n    m_progressRange = maxValue;\r\n}\r\n\r\nvoid BootStrap::setProgressValue( int value )\r\n{\r\n    if( m_hwndProgressBar )\r\n        SendMessage( m_hwndProgressBar, PBM_SETPOS, value, 0 );\r\n\r\n    m_progressValue = value;\r\n}\r\n\r\nvoid BootStrap::setScrobSub( ScrobSubmitter* scrobSub )\r\n{\r\n    std::ostringstream os;\r\n    os << \"setScrobSub: \" << scrobSub;\r\n    log( os.str() );\r\n\r\n    m_scrobSub = scrobSub;\r\n}\r\n\r\nvoid BootStrap::setParentHwnd( HWND parentHwnd )\r\n{\r\n    std::ostringstream os;\r\n    os << \"setParentHwnd: \" << parentHwnd;\r\n    log( os.str() );\r\n\r\n    m_hwndParent = parentHwnd;\r\n}\r\n\r\n\r\n// FIXME: what's this?\r\n//  1. A function called by someone else that does something?\r\n//    Call it complete() or some other verb\r\n//  2. An event handler called when something else completes?\r\n//    Call it onThingComplete()\r\nvoid BootStrap::completed()\r\n{\r\n    WaitForSingleObject( m_progressDialogShown, INFINITE );\r\n    \r\n    HWND hwndOkButton = GetDlgItem( m_hwndDialog, IDC_BUTTONOK );\r\n    HWND hwndCancelButton = GetDlgItem( m_hwndDialog, IDC_BUTTONCANCEL );\r\n    EnableWindow( hwndOkButton, true );\r\n    EnableWindow( hwndCancelButton, false );\r\n\r\n    RegistryUtils::DeleteValue( m_bootStrapHkey, m_mediaPlayerName );\r\n    \r\n    if( !m_tracksFound )\r\n    {\r\n        SetWindowTextW( GetDlgItem( m_hwndDialog, IDC_LABEL ), m_strNoTracksFoundLabel.c_str() );\r\n        RegistryUtils::CloseRegKey( m_bootStrapHkey );\r\n        return;\r\n    }\r\n    \r\n    \r\n    xmlBuffer << L\"</bootstrap>\\n\";\r\n    \r\n    int maxUtf8Size = xmlBuffer.str().size() * 2;\r\n    char* utf8Data = new char[maxUtf8Size];\r\n\r\n    int utf8Size = EncodingUtils::UnicodeToUtf8( xmlBuffer.str().c_str(), xmlBuffer.str().length(), utf8Data, maxUtf8Size );\r\n\r\n    FILE* file = _wfopen( getOutputFilename().c_str(), L\"wb\" );\r\n    fwrite( utf8Data, sizeof(char), utf8Size, file );\r\n    fclose( file );\r\n\r\n    if( m_scrobSub )\r\n        m_scrobSub->BootstrapComplete( m_userName.c_str() );\r\n\r\n\r\n    SetWindowTextW( GetDlgItem( m_hwndDialog, IDC_LABEL ), m_strCompleteLabel.c_str() );\r\n    \r\n    RegistryUtils::CloseRegKey( m_bootStrapHkey );\r\n\r\n    m_bootStrapHkey = NULL;\r\n\r\n    SetFocus( hwndOkButton );\r\n\r\n    log( \"bootstrap completed, will wait for dialogthread event\" );\r\n\r\n    WaitForSingleObject( m_hDialogThread, INFINITE );\r\n\r\n    log( \"dialogthread event wait over\" );\r\n}\r\n\r\nvoid BootStrap::cancel()\r\n{\r\n    pause();\r\n    int response = MessageBoxW( m_hwndDialog, \r\n        m_strCancelConfirmation.c_str(), \r\n        m_strProgressTitle.c_str(), \r\n        MB_YESNO | MB_ICONQUESTION | MB_DEFBUTTON2 );\r\n\r\n    if ( response == IDYES )\r\n    {\r\n        RegistryUtils::DeleteValue( m_bootStrapHkey, m_mediaPlayerName );\r\n        RegistryUtils::CloseRegKey( m_bootStrapHkey );\r\n               \r\n        m_cancel = true;\r\n        pause( false );\r\n    }\r\n    else\r\n    {\r\n        // FIXME: a small detail, but ideally, jave either pause()/resume(), or setPaused( bool )\r\n        pause( false );\r\n    }\r\n}\r\n\r\nvoid BootStrap::pause( bool pauseState )\r\n{\r\n    m_paused = pauseState;\r\n    SetEvent( m_pauseStateChanged );\r\n}\r\n\r\n\r\nstd::wstring BootStrap::getOutputFilename() const\r\n{\r\n    WCHAR clientPathBuffer[MAX_PATH];\r\n    RegistryUtils::QueryString( m_bootStrapHkey, L\"data_path\", clientPathBuffer, MAX_PATH, false );\r\n   \r\n    // FIXME: no error handling. If the path is wrong/missing, it will go ahead anyway.\r\n\r\n    std::wstring dirPath;\r\n    dirPath = clientPathBuffer;\r\n\r\n    std::wstringstream filePath;\r\n    filePath << dirPath << \"/\";\r\n    filePath << m_userName << \"_\";\r\n    filePath << m_mediaPlayerName;\r\n    filePath << \"_bootstrap.xml\";\r\n\r\n    return filePath.str();\r\n}\r\n\r\nvoid BootStrap::find_and_replace( std::wstring &input, std::map<WCHAR, std::wstring> &replacements) const\r\n{\r\n    std::wostringstream oss;\r\n    std::map<WCHAR, std::wstring>::iterator specialCharIt;\r\n\r\n    for( std::wstring::iterator stringIter = input.begin(); stringIter != input.end(); stringIter++ )\r\n    {\r\n        if( *stringIter < 0x20 )\r\n        {\r\n            oss << ' ';\r\n            continue;\r\n        }\r\n\r\n        specialCharIt = replacements.find( *stringIter );\r\n        if ( specialCharIt == replacements.end() )\r\n            oss << *stringIter;\r\n        else\r\n            oss << specialCharIt->second;\r\n        \r\n    }\r\n\r\n    input = oss.str();\r\n}\r\n\r\n// FIXME: name makes it look like a Qt-style getter\r\nvoid BootStrap::xmlentities( std::wstring &input )\r\n{\r\n    find_and_replace( input, m_replacementMap );\r\n}\r\n\r\nvoid BootStrap::appendTrack( struct BootStrapItem* item )\r\n{\r\n    //Ignore tracks with no artist / track names\r\n    if( item->artist.length() < 1 ||\r\n        item->track.length() < 1 )\r\n        return;       \r\n\r\n    m_tracksFound = true;\r\n\r\n\r\n\r\n    xmlentities( item->artist );\r\n\txmlentities( item->albumArtist );\r\n    xmlentities( item->album );\r\n    xmlentities( item->track );\r\n    xmlentities( item->duration );\r\n    xmlentities( item->playcount );\r\n    xmlentities( item->filename );\r\n\r\n    xmlBuffer << \" <item>\\n\";\r\n\r\n    xmlBuffer << \"  <artist>\"    << item->artist    << \"</artist>\\n\";\r\n\txmlBuffer << \"  <albumArtist>\"    << item->albumArtist    << \"</albumArtist>\\n\";\r\n    xmlBuffer << \"  <album>\"     << item->album     << \"</album>\\n\";\r\n    xmlBuffer << \"  <track>\"     << item->track     << \"</track>\\n\";\r\n    xmlBuffer << \"  <duration>\"  << item->duration  << \"</duration>\\n\";\r\n    xmlBuffer << \"  <playcount>\" << item->playcount << \"</playcount>\\n\";\r\n    xmlBuffer << \"  <filename>\"  << item->filename  << \"</filename>\\n\";\r\n    xmlBuffer << \"  <timestamp>\" << item->timestamp << \"</timestamp>\\n\";\r\n\r\n    xmlBuffer << \" </item>\\n\";\r\n}\r\n\r\nvoid\r\nBootStrap::log( std::string message )\r\n{\r\n    if ( m_scrobSub != NULL )\r\n    {\r\n        m_scrobSub->ReportStatus( -1, false, message );\r\n    }\r\n}\r\n"
  },
  {
    "path": "plugins/scrobsub/Bootstrap.h",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef _BOOTSTRAP_H_\r\n#define _BOOTSTRAP_H_\r\n\r\n#include \"RegistryUtils.h\"\r\n\r\n#define _WINSOCKAPI_\r\n#include <windows.h>\r\n\r\n#include <sstream>\r\n#include <fstream>\r\n#include <map>\r\n\r\n// FIXME: As this will be part of a public library, we should add Doxygen comments and\r\n// format it like ScrobSubmitter. Also, the name Bootstrap is a little ambiguous, what\r\n// does it do? Is it a bootstrapper, is it a data repository for bootstrapping data?\r\n//\r\n// It's a slightly incoherent class in that it does a whole load of different stuff\r\n// so it's difficult to give it a good name. It might be an idea to extract out the\r\n// dialog into its own class and give each class distinct responsibilities. It's quite\r\n// difficult also to know what thread you're in. Everything that runs in a separate\r\n// thread might also be a candidate for a separate class to make it obvious when\r\n// we're in a different thread. Also don't see any thread synchronisation primitives\r\n// in here, but I haven't looked carefully enough to see if it's a problem in practice...\r\nclass BootStrap\r\n{\r\npublic:\r\n    virtual ~BootStrap();\r\n\r\n    bool bootStrapRequired();\r\n    bool startBootStrap();\r\n    void cancel();\r\n    void pause( bool pauseState = true );\r\n    void setScrobSub( class ScrobSubmitter* scrobSub );\r\n    void setParentHwnd( HWND parentHwnd );\r\n    void setModuleHandle( HINSTANCE instance ) { m_module = instance; }\r\n\r\nprotected:\r\n\r\n    BootStrap( const WCHAR* mediaPlayerName );\r\n\r\n    void closeWindow();\r\n    void completed();\r\n    void setProgressRange( int maxValue );\r\n    void setProgressValue( int value );\r\n\r\n    void find_and_replace( std::wstring &input, std::map<WCHAR, std::wstring> &replacements ) const;\r\n    void xmlentities( std::wstring &input );\r\n    \r\n    struct BootStrapItem{\r\n        std::wstring artist;\r\n\t\tstd::wstring albumArtist;\r\n        std::wstring track;\r\n        std::wstring album;\r\n        std::wstring duration;\r\n        std::wstring playcount;\r\n        std::wstring filename;\r\n        std::wstring timestamp;\r\n    };\r\n\r\n    void appendTrack( BootStrapItem* item );\r\n\r\n    const WCHAR* m_mediaPlayerName;\r\n    bool queryBootStrapStatus();\r\n\r\n    void log( std::string message );\r\n\r\n    bool m_dialogThreadEnd;\r\n\r\n    int m_progressRange;\r\n    int m_progressValue;\r\n\r\n\r\n    bool m_dialogReady;\r\n    bool m_cancel;\r\n    bool m_paused;\r\n\r\n    int m_clientVerMajor;\r\n    int m_clientVerMinor;\r\n    int m_clientVerRelease;\r\n    int m_clientVerFix;\r\n\r\n    std::wstring getOutputFilename() const;\r\n    HANDLE m_pauseStateChanged;\r\n\r\nprivate:\r\n    BootStrap( BootStrap& ){};\r\n\r\n    bool m_bootStrapRequired;\r\n    HKEY m_bootStrapHkey;\r\n\r\n    std::wstring m_strProgressLabel;\r\n    std::wstring m_strCompleteLabel;\r\n    std::wstring m_strNoTracksFoundLabel;\r\n    std::wstring m_strProgressTitle;\r\n    std::wstring m_strCancelConfirmation;\r\n    std::wstring m_userName;\r\n\r\n    virtual bool start() { log( \"base class start called, this should be impossible\" ); return true; }\r\n\r\n    void showProgress();\r\n    void dialogEventLoop();\r\n\r\n    static  unsigned __stdcall bootstrapThreadEntry( LPVOID lpParam );\r\n    static  unsigned __stdcall dialogThreadEntry( LPVOID lpParam );\r\n    \r\n    static LRESULT CALLBACK DialogProc(HWND hwndDlg, \r\n                                       UINT message, \r\n                                       WPARAM wParam, \r\n                                       LPARAM lParam);\r\n\r\n    static std::map< HWND, BootStrap* > m_hwndMap;\r\n    std::map< WCHAR, std::wstring > m_replacementMap;\r\n\r\n    ScrobSubmitter* m_scrobSub;\r\n\r\n    std::wstringstream xmlBuffer;\r\n\r\n    HWND m_hwndDialog;\r\n    HWND m_hwndProgressBar;\r\n    HWND m_hwndParent;\r\n\r\n    HANDLE  m_bootstrapThread;\r\n    HANDLE  m_hDialogThread;\r\n\r\n    HINSTANCE m_module;\r\n    bool m_tracksFound;\r\n\r\n    HANDLE m_progressDialogShown;\r\n};\r\n\r\n\r\n#endif // _BOOTSTRAP_H_\r\n\r\n"
  },
  {
    "path": "plugins/scrobsub/Bootstrap.rc",
    "content": "// Microsoft Visual C++ generated resource script.\r\n//\r\n#include \"resource1.h\"\r\n\r\n#define APSTUDIO_READONLY_SYMBOLS\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 2 resource.\r\n//\r\n#include \"afxres.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#undef APSTUDIO_READONLY_SYMBOLS\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.S.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Dialog\r\n//\r\n\r\nIDD_PROGRESSFORM DIALOGEX 0, 0, 237, 74\r\nSTYLE DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | WS_POPUP | WS_CAPTION\r\nEXSTYLE WS_EX_TOOLWINDOW | WS_EX_STATICEDGE\r\nCAPTION \"Last.fm Bootstrap\"\r\nFONT 8, \"MS Shell Dlg\", 0, 0, 0x0\r\nBEGIN\r\n    CONTROL         \"\",IDC_PROGRESS1,\"msctls_progress32\",0x1,14,24,208,12\r\n    CONTROL         \"Bootstrapping in progress...\",IDC_LABEL,\"Static\",SS_LEFTNOWORDWRAP | WS_GROUP,14,11,207,10\r\n    DEFPUSHBUTTON   \"&OK\",IDC_BUTTONOK,117,48,50,14,WS_DISABLED\r\n    PUSHBUTTON      \"&Cancel\",IDC_BUTTONCANCEL,172,48,50,14\r\nEND\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// DESIGNINFO\r\n//\r\n\r\n#ifdef APSTUDIO_INVOKED\r\nGUIDELINES DESIGNINFO \r\nBEGIN\r\n    IDD_PROGRESSFORM, DIALOG\r\n    BEGIN\r\n        LEFTMARGIN, 7\r\n        RIGHTMARGIN, 229\r\n        TOPMARGIN, 7\r\n        BOTTOMMARGIN, 60\r\n    END\r\nEND\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n#endif    // English (U.S.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.K.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTINCLUDE\r\n//\r\n\r\n1 TEXTINCLUDE \r\nBEGIN\r\n    \"resource1.h\\0\"\r\nEND\r\n\r\n2 TEXTINCLUDE \r\nBEGIN\r\n    \"#include \"\"afxres.h\"\"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n3 TEXTINCLUDE \r\nBEGIN\r\n    \"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n#endif    // English (U.K.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n#ifndef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 3 resource.\r\n//\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#endif    // not APSTUDIO_INVOKED\r\n\r\n"
  },
  {
    "path": "plugins/scrobsub/Doxyfile",
    "content": "# Doxyfile 1.5.2\r\n\r\n# This file describes the settings to be used by the documentation system\r\n# doxygen (www.doxygen.org) for a project\r\n#\r\n# All text after a hash (#) is considered a comment and will be ignored\r\n# The format is:\r\n#       TAG = value [value, ...]\r\n# For lists items can also be appended using:\r\n#       TAG += value [value, ...]\r\n# Values that contain spaces should be placed between quotes (\" \")\r\n\r\n#---------------------------------------------------------------------------\r\n# Project related configuration options\r\n#---------------------------------------------------------------------------\r\n\r\n# This tag specifies the encoding used for all characters in the config file that \r\n# follow. The default is UTF-8 which is also the encoding used for all text before \r\n# the first occurrence of this tag. Doxygen uses libiconv (or the iconv built into \r\n# libc) for the transcoding. See http://www.gnu.org/software/libiconv for the list of \r\n# possible encodings.\r\n\r\nDOXYFILE_ENCODING      = UTF-8\r\n\r\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded \r\n# by quotes) that should identify the project.\r\n\r\nPROJECT_NAME           = \r\n\r\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. \r\n# This could be handy for archiving the generated documentation or \r\n# if some version control system is used.\r\n\r\nPROJECT_NUMBER         = \r\n\r\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) \r\n# base path where the generated documentation will be put. \r\n# If a relative path is entered, it will be relative to the location \r\n# where doxygen was started. If left blank the current directory will be used.\r\n\r\nOUTPUT_DIRECTORY       = docs\r\n\r\n# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create \r\n# 4096 sub-directories (in 2 levels) under the output directory of each output \r\n# format and will distribute the generated files over these directories. \r\n# Enabling this option can be useful when feeding doxygen a huge amount of \r\n# source files, where putting all generated files in the same directory would \r\n# otherwise cause performance problems for the file system.\r\n\r\nCREATE_SUBDIRS         = NO\r\n\r\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all \r\n# documentation generated by doxygen is written. Doxygen will use this \r\n# information to generate all constant output in the proper language. \r\n# The default language is English, other supported languages are: \r\n# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, \r\n# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, \r\n# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, \r\n# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, \r\n# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian.\r\n\r\nOUTPUT_LANGUAGE        = English\r\n\r\n# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will \r\n# include brief member descriptions after the members that are listed in \r\n# the file and class documentation (similar to JavaDoc). \r\n# Set to NO to disable this.\r\n\r\nBRIEF_MEMBER_DESC      = YES\r\n\r\n# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend \r\n# the brief description of a member or function before the detailed description. \r\n# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the \r\n# brief descriptions will be completely suppressed.\r\n\r\nREPEAT_BRIEF           = YES\r\n\r\n# This tag implements a quasi-intelligent brief description abbreviator \r\n# that is used to form the text in various listings. Each string \r\n# in this list, if found as the leading text of the brief description, will be \r\n# stripped from the text and the result after processing the whole list, is \r\n# used as the annotated text. Otherwise, the brief description is used as-is. \r\n# If left blank, the following values are used (\"$name\" is automatically \r\n# replaced with the name of the entity): \"The $name class\" \"The $name widget\" \r\n# \"The $name file\" \"is\" \"provides\" \"specifies\" \"contains\" \r\n# \"represents\" \"a\" \"an\" \"the\"\r\n\r\nABBREVIATE_BRIEF       = \r\n\r\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then \r\n# Doxygen will generate a detailed section even if there is only a brief \r\n# description.\r\n\r\nALWAYS_DETAILED_SEC    = NO\r\n\r\n# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all \r\n# inherited members of a class in the documentation of that class as if those \r\n# members were ordinary class members. Constructors, destructors and assignment \r\n# operators of the base classes will not be shown.\r\n\r\nINLINE_INHERITED_MEMB  = NO\r\n\r\n# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full \r\n# path before files name in the file list and in the header files. If set \r\n# to NO the shortest path that makes the file name unique will be used.\r\n\r\nFULL_PATH_NAMES        = YES\r\n\r\n# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag \r\n# can be used to strip a user-defined part of the path. Stripping is \r\n# only done if one of the specified strings matches the left-hand part of \r\n# the path. The tag can be used to show relative paths in the file list. \r\n# If left blank the directory from which doxygen is run is used as the \r\n# path to strip.\r\n\r\nSTRIP_FROM_PATH        = \r\n\r\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of \r\n# the path mentioned in the documentation of a class, which tells \r\n# the reader which header file to include in order to use a class. \r\n# If left blank only the name of the header file containing the class \r\n# definition is used. Otherwise one should specify the include paths that \r\n# are normally passed to the compiler using the -I flag.\r\n\r\nSTRIP_FROM_INC_PATH    = \r\n\r\n# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter \r\n# (but less readable) file names. This can be useful is your file systems \r\n# doesn't support long names like on DOS, Mac, or CD-ROM.\r\n\r\nSHORT_NAMES            = NO\r\n\r\n# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen \r\n# will interpret the first line (until the first dot) of a JavaDoc-style \r\n# comment as the brief description. If set to NO, the JavaDoc \r\n# comments will behave just like the Qt-style comments (thus requiring an \r\n# explicit @brief command for a brief description.\r\n\r\nJAVADOC_AUTOBRIEF      = NO\r\n\r\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen \r\n# treat a multi-line C++ special comment block (i.e. a block of //! or /// \r\n# comments) as a brief description. This used to be the default behaviour. \r\n# The new default is to treat a multi-line C++ comment block as a detailed \r\n# description. Set this tag to YES if you prefer the old behaviour instead.\r\n\r\nMULTILINE_CPP_IS_BRIEF = NO\r\n\r\n# If the DETAILS_AT_TOP tag is set to YES then Doxygen \r\n# will output the detailed description near the top, like JavaDoc.\r\n# If set to NO, the detailed description appears after the member \r\n# documentation.\r\n\r\nDETAILS_AT_TOP         = NO\r\n\r\n# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented \r\n# member inherits the documentation from any documented member that it \r\n# re-implements.\r\n\r\nINHERIT_DOCS           = YES\r\n\r\n# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce \r\n# a new page for each member. If set to NO, the documentation of a member will \r\n# be part of the file/class/namespace that contains it.\r\n\r\nSEPARATE_MEMBER_PAGES  = NO\r\n\r\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. \r\n# Doxygen uses this value to replace tabs by spaces in code fragments.\r\n\r\nTAB_SIZE               = 8\r\n\r\n# This tag can be used to specify a number of aliases that acts \r\n# as commands in the documentation. An alias has the form \"name=value\". \r\n# For example adding \"sideeffect=\\par Side Effects:\\n\" will allow you to \r\n# put the command \\sideeffect (or @sideeffect) in the documentation, which \r\n# will result in a user-defined paragraph with heading \"Side Effects:\". \r\n# You can put \\n's in the value part of an alias to insert newlines.\r\n\r\nALIASES                = \r\n\r\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C \r\n# sources only. Doxygen will then generate output that is more tailored for C. \r\n# For instance, some of the names that are used will be different. The list \r\n# of all members will be omitted, etc.\r\n\r\nOPTIMIZE_OUTPUT_FOR_C  = NO\r\n\r\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java \r\n# sources only. Doxygen will then generate output that is more tailored for Java. \r\n# For instance, namespaces will be presented as packages, qualified scopes \r\n# will look different, etc.\r\n\r\nOPTIMIZE_OUTPUT_JAVA   = NO\r\n\r\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to \r\n# include (a tag file for) the STL sources as input, then you should \r\n# set this tag to YES in order to let doxygen match functions declarations and \r\n# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. \r\n# func(std::string) {}). This also make the inheritance and collaboration \r\n# diagrams that involve STL classes more complete and accurate.\r\n\r\nBUILTIN_STL_SUPPORT    = NO\r\n\r\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\r\n# enable parsing support.\r\n\r\nCPP_CLI_SUPPORT        = NO\r\n\r\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC \r\n# tag is set to YES, then doxygen will reuse the documentation of the first \r\n# member in the group (if any) for the other members of the group. By default \r\n# all members of a group must be documented explicitly.\r\n\r\nDISTRIBUTE_GROUP_DOC   = NO\r\n\r\n# Set the SUBGROUPING tag to YES (the default) to allow class member groups of \r\n# the same type (for instance a group of public functions) to be put as a \r\n# subgroup of that type (e.g. under the Public Functions section). Set it to \r\n# NO to prevent subgrouping. Alternatively, this can be done per class using \r\n# the \\nosubgrouping command.\r\n\r\nSUBGROUPING            = YES\r\n\r\n#---------------------------------------------------------------------------\r\n# Build related configuration options\r\n#---------------------------------------------------------------------------\r\n\r\n# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in \r\n# documentation are documented, even if no documentation was available. \r\n# Private class members and static file members will be hidden unless \r\n# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES\r\n\r\nEXTRACT_ALL            = NO\r\n\r\n# If the EXTRACT_PRIVATE tag is set to YES all private members of a class \r\n# will be included in the documentation.\r\n\r\nEXTRACT_PRIVATE        = NO\r\n\r\n# If the EXTRACT_STATIC tag is set to YES all static members of a file \r\n# will be included in the documentation.\r\n\r\nEXTRACT_STATIC         = NO\r\n\r\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) \r\n# defined locally in source files will be included in the documentation. \r\n# If set to NO only classes defined in header files are included.\r\n\r\nEXTRACT_LOCAL_CLASSES  = YES\r\n\r\n# This flag is only useful for Objective-C code. When set to YES local \r\n# methods, which are defined in the implementation section but not in \r\n# the interface are included in the documentation. \r\n# If set to NO (the default) only methods in the interface are included.\r\n\r\nEXTRACT_LOCAL_METHODS  = NO\r\n\r\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all \r\n# undocumented members of documented classes, files or namespaces. \r\n# If set to NO (the default) these members will be included in the \r\n# various overviews, but no documentation section is generated. \r\n# This option has no effect if EXTRACT_ALL is enabled.\r\n\r\nHIDE_UNDOC_MEMBERS     = NO\r\n\r\n# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all \r\n# undocumented classes that are normally visible in the class hierarchy. \r\n# If set to NO (the default) these classes will be included in the various \r\n# overviews. This option has no effect if EXTRACT_ALL is enabled.\r\n\r\nHIDE_UNDOC_CLASSES     = NO\r\n\r\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all \r\n# friend (class|struct|union) declarations. \r\n# If set to NO (the default) these declarations will be included in the \r\n# documentation.\r\n\r\nHIDE_FRIEND_COMPOUNDS  = NO\r\n\r\n# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any \r\n# documentation blocks found inside the body of a function. \r\n# If set to NO (the default) these blocks will be appended to the \r\n# function's detailed documentation block.\r\n\r\nHIDE_IN_BODY_DOCS      = NO\r\n\r\n# The INTERNAL_DOCS tag determines if documentation \r\n# that is typed after a \\internal command is included. If the tag is set \r\n# to NO (the default) then the documentation will be excluded. \r\n# Set it to YES to include the internal documentation.\r\n\r\nINTERNAL_DOCS          = NO\r\n\r\n# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate \r\n# file names in lower-case letters. If set to YES upper-case letters are also \r\n# allowed. This is useful if you have classes or files whose names only differ \r\n# in case and if your file system supports case sensitive file names. Windows \r\n# and Mac users are advised to set this option to NO.\r\n\r\nCASE_SENSE_NAMES       = NO\r\n\r\n# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen \r\n# will show members with their full class and namespace scopes in the \r\n# documentation. If set to YES the scope will be hidden.\r\n\r\nHIDE_SCOPE_NAMES       = NO\r\n\r\n# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen \r\n# will put a list of the files that are included by a file in the documentation \r\n# of that file.\r\n\r\nSHOW_INCLUDE_FILES     = YES\r\n\r\n# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] \r\n# is inserted in the documentation for inline members.\r\n\r\nINLINE_INFO            = YES\r\n\r\n# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen \r\n# will sort the (detailed) documentation of file and class members \r\n# alphabetically by member name. If set to NO the members will appear in \r\n# declaration order.\r\n\r\nSORT_MEMBER_DOCS       = YES\r\n\r\n# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the \r\n# brief documentation of file, namespace and class members alphabetically \r\n# by member name. If set to NO (the default) the members will appear in \r\n# declaration order.\r\n\r\nSORT_BRIEF_DOCS        = NO\r\n\r\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be \r\n# sorted by fully-qualified names, including namespaces. If set to \r\n# NO (the default), the class list will be sorted only by class name, \r\n# not including the namespace part. \r\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\r\n# Note: This option applies only to the class list, not to the \r\n# alphabetical list.\r\n\r\nSORT_BY_SCOPE_NAME     = NO\r\n\r\n# The GENERATE_TODOLIST tag can be used to enable (YES) or \r\n# disable (NO) the todo list. This list is created by putting \\todo \r\n# commands in the documentation.\r\n\r\nGENERATE_TODOLIST      = YES\r\n\r\n# The GENERATE_TESTLIST tag can be used to enable (YES) or \r\n# disable (NO) the test list. This list is created by putting \\test \r\n# commands in the documentation.\r\n\r\nGENERATE_TESTLIST      = YES\r\n\r\n# The GENERATE_BUGLIST tag can be used to enable (YES) or \r\n# disable (NO) the bug list. This list is created by putting \\bug \r\n# commands in the documentation.\r\n\r\nGENERATE_BUGLIST       = YES\r\n\r\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or \r\n# disable (NO) the deprecated list. This list is created by putting \r\n# \\deprecated commands in the documentation.\r\n\r\nGENERATE_DEPRECATEDLIST= YES\r\n\r\n# The ENABLED_SECTIONS tag can be used to enable conditional \r\n# documentation sections, marked by \\if sectionname ... \\endif.\r\n\r\nENABLED_SECTIONS       = \r\n\r\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines \r\n# the initial value of a variable or define consists of for it to appear in \r\n# the documentation. If the initializer consists of more lines than specified \r\n# here it will be hidden. Use a value of 0 to hide initializers completely. \r\n# The appearance of the initializer of individual variables and defines in the \r\n# documentation can be controlled using \\showinitializer or \\hideinitializer \r\n# command in the documentation regardless of this setting.\r\n\r\nMAX_INITIALIZER_LINES  = 30\r\n\r\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated \r\n# at the bottom of the documentation of classes and structs. If set to YES the \r\n# list will mention the files that were used to generate the documentation.\r\n\r\nSHOW_USED_FILES        = YES\r\n\r\n# If the sources in your project are distributed over multiple directories \r\n# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy \r\n# in the documentation. The default is NO.\r\n\r\nSHOW_DIRECTORIES       = YES\r\n\r\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that \r\n# doxygen should invoke to get the current version for each file (typically from the \r\n# version control system). Doxygen will invoke the program by executing (via \r\n# popen()) the command <command> <input-file>, where <command> is the value of \r\n# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file \r\n# provided by doxygen. Whatever the program writes to standard output \r\n# is used as the file version. See the manual for examples.\r\n\r\nFILE_VERSION_FILTER    = \r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to warning and progress messages\r\n#---------------------------------------------------------------------------\r\n\r\n# The QUIET tag can be used to turn on/off the messages that are generated \r\n# by doxygen. Possible values are YES and NO. If left blank NO is used.\r\n\r\nQUIET                  = NO\r\n\r\n# The WARNINGS tag can be used to turn on/off the warning messages that are \r\n# generated by doxygen. Possible values are YES and NO. If left blank \r\n# NO is used.\r\n\r\nWARNINGS               = YES\r\n\r\n# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings \r\n# for undocumented members. If EXTRACT_ALL is set to YES then this flag will \r\n# automatically be disabled.\r\n\r\nWARN_IF_UNDOCUMENTED   = YES\r\n\r\n# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for \r\n# potential errors in the documentation, such as not documenting some \r\n# parameters in a documented function, or documenting parameters that \r\n# don't exist or using markup commands wrongly.\r\n\r\nWARN_IF_DOC_ERROR      = YES\r\n\r\n# This WARN_NO_PARAMDOC option can be abled to get warnings for \r\n# functions that are documented, but have no documentation for their parameters \r\n# or return value. If set to NO (the default) doxygen will only warn about \r\n# wrong or incomplete parameter documentation, but not about the absence of \r\n# documentation.\r\n\r\nWARN_NO_PARAMDOC       = NO\r\n\r\n# The WARN_FORMAT tag determines the format of the warning messages that \r\n# doxygen can produce. The string should contain the $file, $line, and $text \r\n# tags, which will be replaced by the file and line number from which the \r\n# warning originated and the warning text. Optionally the format may contain \r\n# $version, which will be replaced by the version of the file (if it could \r\n# be obtained via FILE_VERSION_FILTER)\r\n\r\nWARN_FORMAT            = \"$file:$line: $text\"\r\n\r\n# The WARN_LOGFILE tag can be used to specify a file to which warning \r\n# and error messages should be written. If left blank the output is written \r\n# to stderr.\r\n\r\nWARN_LOGFILE           = \r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the input files\r\n#---------------------------------------------------------------------------\r\n\r\n# The INPUT tag can be used to specify the files and/or directories that contain \r\n# documented source files. You may enter file names like \"myfile.cpp\" or \r\n# directories like \"/usr/src/myproject\". Separate the files or directories \r\n# with spaces.\r\n\r\nINPUT                  = ScrobSubmitter.h \\\r\n                         ScrobSubmitter.cpp\r\n\r\n# This tag can be used to specify the character encoding of the source files that \r\n# doxygen parses. Internally doxygen uses the UTF-8 encoding, which is also the default \r\n# input encoding. Doxygen uses libiconv (or the iconv built into libc) for the transcoding. \r\n# See http://www.gnu.org/software/libiconv for the list of possible encodings.\r\n\r\nINPUT_ENCODING         = UTF-8\r\n\r\n# If the value of the INPUT tag contains directories, you can use the \r\n# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp \r\n# and *.h) to filter out the source-files in the directories. If left \r\n# blank the following patterns are tested: \r\n# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx \r\n# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py\r\n\r\nFILE_PATTERNS          = \r\n\r\n# The RECURSIVE tag can be used to turn specify whether or not subdirectories \r\n# should be searched for input files as well. Possible values are YES and NO. \r\n# If left blank NO is used.\r\n\r\nRECURSIVE              = NO\r\n\r\n# The EXCLUDE tag can be used to specify files and/or directories that should \r\n# excluded from the INPUT source files. This way you can easily exclude a \r\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\r\n\r\nEXCLUDE                = \r\n\r\n# The EXCLUDE_SYMLINKS tag can be used select whether or not files or \r\n# directories that are symbolic links (a Unix filesystem feature) are excluded \r\n# from the input.\r\n\r\nEXCLUDE_SYMLINKS       = NO\r\n\r\n# If the value of the INPUT tag contains directories, you can use the \r\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude \r\n# certain files from those directories. Note that the wildcards are matched \r\n# against the file with absolute path, so to exclude all test directories \r\n# for example use the pattern */test/*\r\n\r\nEXCLUDE_PATTERNS       = \r\n\r\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names \r\n# (namespaces, classes, functions, etc.) that should be excluded from the output. \r\n# The symbol name can be a fully qualified name, a word, or if the wildcard * is used, \r\n# a substring. Examples: ANamespace, AClass, AClass::ANamespace, ANamespace::*Test\r\n\r\nEXCLUDE_SYMBOLS        = \r\n\r\n# The EXAMPLE_PATH tag can be used to specify one or more files or \r\n# directories that contain example code fragments that are included (see \r\n# the \\include command).\r\n\r\nEXAMPLE_PATH           = \r\n\r\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the \r\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp \r\n# and *.h) to filter out the source-files in the directories. If left \r\n# blank all files are included.\r\n\r\nEXAMPLE_PATTERNS       = \r\n\r\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be \r\n# searched for input files to be used with the \\include or \\dontinclude \r\n# commands irrespective of the value of the RECURSIVE tag. \r\n# Possible values are YES and NO. If left blank NO is used.\r\n\r\nEXAMPLE_RECURSIVE      = NO\r\n\r\n# The IMAGE_PATH tag can be used to specify one or more files or \r\n# directories that contain image that are included in the documentation (see \r\n# the \\image command).\r\n\r\nIMAGE_PATH             = \r\n\r\n# The INPUT_FILTER tag can be used to specify a program that doxygen should \r\n# invoke to filter for each input file. Doxygen will invoke the filter program \r\n# by executing (via popen()) the command <filter> <input-file>, where <filter> \r\n# is the value of the INPUT_FILTER tag, and <input-file> is the name of an \r\n# input file. Doxygen will then use the output that the filter program writes \r\n# to standard output.  If FILTER_PATTERNS is specified, this tag will be \r\n# ignored.\r\n\r\nINPUT_FILTER           = \r\n\r\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern \r\n# basis.  Doxygen will compare the file name with each pattern and apply the \r\n# filter if there is a match.  The filters are a list of the form: \r\n# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further \r\n# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER \r\n# is applied to all files.\r\n\r\nFILTER_PATTERNS        = \r\n\r\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using \r\n# INPUT_FILTER) will be used to filter the input files when producing source \r\n# files to browse (i.e. when SOURCE_BROWSER is set to YES).\r\n\r\nFILTER_SOURCE_FILES    = NO\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to source browsing\r\n#---------------------------------------------------------------------------\r\n\r\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will \r\n# be generated. Documented entities will be cross-referenced with these sources. \r\n# Note: To get rid of all source code in the generated output, make sure also \r\n# VERBATIM_HEADERS is set to NO.\r\n\r\nSOURCE_BROWSER         = NO\r\n\r\n# Setting the INLINE_SOURCES tag to YES will include the body \r\n# of functions and classes directly in the documentation.\r\n\r\nINLINE_SOURCES         = NO\r\n\r\n# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct \r\n# doxygen to hide any special comment blocks from generated source code \r\n# fragments. Normal C and C++ comments will always remain visible.\r\n\r\nSTRIP_CODE_COMMENTS    = YES\r\n\r\n# If the REFERENCED_BY_RELATION tag is set to YES (the default) \r\n# then for each documented function all documented \r\n# functions referencing it will be listed.\r\n\r\nREFERENCED_BY_RELATION = YES\r\n\r\n# If the REFERENCES_RELATION tag is set to YES (the default) \r\n# then for each documented function all documented entities \r\n# called/used by that function will be listed.\r\n\r\nREFERENCES_RELATION    = YES\r\n\r\n# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)\r\n# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from\r\n# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will\r\n# link to the source code.  Otherwise they will link to the documentstion.\r\n\r\nREFERENCES_LINK_SOURCE = YES\r\n\r\n# If the USE_HTAGS tag is set to YES then the references to source code \r\n# will point to the HTML generated by the htags(1) tool instead of doxygen \r\n# built-in source browser. The htags tool is part of GNU's global source \r\n# tagging system (see http://www.gnu.org/software/global/global.html). You \r\n# will need version 4.8.6 or higher.\r\n\r\nUSE_HTAGS              = NO\r\n\r\n# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen \r\n# will generate a verbatim copy of the header file for each class for \r\n# which an include is specified. Set to NO to disable this.\r\n\r\nVERBATIM_HEADERS       = YES\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the alphabetical class index\r\n#---------------------------------------------------------------------------\r\n\r\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index \r\n# of all compounds will be generated. Enable this if the project \r\n# contains a lot of classes, structs, unions or interfaces.\r\n\r\nALPHABETICAL_INDEX     = NO\r\n\r\n# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then \r\n# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns \r\n# in which this list will be split (can be a number in the range [1..20])\r\n\r\nCOLS_IN_ALPHA_INDEX    = 5\r\n\r\n# In case all classes in a project start with a common prefix, all \r\n# classes will be put under the same header in the alphabetical index. \r\n# The IGNORE_PREFIX tag can be used to specify one or more prefixes that \r\n# should be ignored while generating the index headers.\r\n\r\nIGNORE_PREFIX          = \r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the HTML output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_HTML tag is set to YES (the default) Doxygen will \r\n# generate HTML output.\r\n\r\nGENERATE_HTML          = YES\r\n\r\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. \r\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \r\n# put in front of it. If left blank `html' will be used as the default path.\r\n\r\nHTML_OUTPUT            = html\r\n\r\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for \r\n# each generated HTML page (for example: .htm,.php,.asp). If it is left blank \r\n# doxygen will generate files with .html extension.\r\n\r\nHTML_FILE_EXTENSION    = .html\r\n\r\n# The HTML_HEADER tag can be used to specify a personal HTML header for \r\n# each generated HTML page. If it is left blank doxygen will generate a \r\n# standard header.\r\n\r\nHTML_HEADER            = \r\n\r\n# The HTML_FOOTER tag can be used to specify a personal HTML footer for \r\n# each generated HTML page. If it is left blank doxygen will generate a \r\n# standard footer.\r\n\r\nHTML_FOOTER            = \r\n\r\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading \r\n# style sheet that is used by each HTML page. It can be used to \r\n# fine-tune the look of the HTML output. If the tag is left blank doxygen \r\n# will generate a default style sheet. Note that doxygen will try to copy \r\n# the style sheet file to the HTML output directory, so don't put your own \r\n# stylesheet in the HTML output directory as well, or it will be erased!\r\n\r\nHTML_STYLESHEET        = \r\n\r\n# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, \r\n# files or namespaces will be aligned in HTML using tables. If set to \r\n# NO a bullet list will be used.\r\n\r\nHTML_ALIGN_MEMBERS     = YES\r\n\r\n# If the GENERATE_HTMLHELP tag is set to YES, additional index files \r\n# will be generated that can be used as input for tools like the \r\n# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) \r\n# of the generated HTML documentation.\r\n\r\nGENERATE_HTMLHELP      = NO\r\n\r\n# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can \r\n# be used to specify the file name of the resulting .chm file. You \r\n# can add a path in front of the file if the result should not be \r\n# written to the html output directory.\r\n\r\nCHM_FILE               = \r\n\r\n# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can \r\n# be used to specify the location (absolute path including file name) of \r\n# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run \r\n# the HTML help compiler on the generated index.hhp.\r\n\r\nHHC_LOCATION           = \r\n\r\n# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag \r\n# controls if a separate .chi index file is generated (YES) or that \r\n# it should be included in the master .chm file (NO).\r\n\r\nGENERATE_CHI           = NO\r\n\r\n# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag \r\n# controls whether a binary table of contents is generated (YES) or a \r\n# normal table of contents (NO) in the .chm file.\r\n\r\nBINARY_TOC             = NO\r\n\r\n# The TOC_EXPAND flag can be set to YES to add extra items for group members \r\n# to the contents of the HTML help documentation and to the tree view.\r\n\r\nTOC_EXPAND             = NO\r\n\r\n# The DISABLE_INDEX tag can be used to turn on/off the condensed index at \r\n# top of each HTML page. The value NO (the default) enables the index and \r\n# the value YES disables it.\r\n\r\nDISABLE_INDEX          = NO\r\n\r\n# This tag can be used to set the number of enum values (range [1..20]) \r\n# that doxygen will group on one line in the generated HTML documentation.\r\n\r\nENUM_VALUES_PER_LINE   = 4\r\n\r\n# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be\r\n# generated containing a tree-like index structure (just like the one that \r\n# is generated for HTML Help). For this to work a browser that supports \r\n# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, \r\n# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are \r\n# probably better off using the HTML help feature.\r\n\r\nGENERATE_TREEVIEW      = NO\r\n\r\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be \r\n# used to set the initial width (in pixels) of the frame in which the tree \r\n# is shown.\r\n\r\nTREEVIEW_WIDTH         = 250\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the LaTeX output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will \r\n# generate Latex output.\r\n\r\nGENERATE_LATEX         = YES\r\n\r\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. \r\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \r\n# put in front of it. If left blank `latex' will be used as the default path.\r\n\r\nLATEX_OUTPUT           = latex\r\n\r\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be \r\n# invoked. If left blank `latex' will be used as the default command name.\r\n\r\nLATEX_CMD_NAME         = latex\r\n\r\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to \r\n# generate index for LaTeX. If left blank `makeindex' will be used as the \r\n# default command name.\r\n\r\nMAKEINDEX_CMD_NAME     = makeindex\r\n\r\n# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact \r\n# LaTeX documents. This may be useful for small projects and may help to \r\n# save some trees in general.\r\n\r\nCOMPACT_LATEX          = NO\r\n\r\n# The PAPER_TYPE tag can be used to set the paper type that is used \r\n# by the printer. Possible values are: a4, a4wide, letter, legal and \r\n# executive. If left blank a4wide will be used.\r\n\r\nPAPER_TYPE             = a4wide\r\n\r\n# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX \r\n# packages that should be included in the LaTeX output.\r\n\r\nEXTRA_PACKAGES         = \r\n\r\n# The LATEX_HEADER tag can be used to specify a personal LaTeX header for \r\n# the generated latex document. The header should contain everything until \r\n# the first chapter. If it is left blank doxygen will generate a \r\n# standard header. Notice: only use this tag if you know what you are doing!\r\n\r\nLATEX_HEADER           = \r\n\r\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated \r\n# is prepared for conversion to pdf (using ps2pdf). The pdf file will \r\n# contain links (just like the HTML output) instead of page references \r\n# This makes the output suitable for online browsing using a pdf viewer.\r\n\r\nPDF_HYPERLINKS         = NO\r\n\r\n# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of \r\n# plain latex in the generated Makefile. Set this option to YES to get a \r\n# higher quality PDF documentation.\r\n\r\nUSE_PDFLATEX           = NO\r\n\r\n# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\\\batchmode. \r\n# command to the generated LaTeX files. This will instruct LaTeX to keep \r\n# running if errors occur, instead of asking the user for help. \r\n# This option is also used when generating formulas in HTML.\r\n\r\nLATEX_BATCHMODE        = NO\r\n\r\n# If LATEX_HIDE_INDICES is set to YES then doxygen will not \r\n# include the index chapters (such as File Index, Compound Index, etc.) \r\n# in the output.\r\n\r\nLATEX_HIDE_INDICES     = NO\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the RTF output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output \r\n# The RTF output is optimized for Word 97 and may not look very pretty with \r\n# other RTF readers or editors.\r\n\r\nGENERATE_RTF           = NO\r\n\r\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. \r\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \r\n# put in front of it. If left blank `rtf' will be used as the default path.\r\n\r\nRTF_OUTPUT             = rtf\r\n\r\n# If the COMPACT_RTF tag is set to YES Doxygen generates more compact \r\n# RTF documents. This may be useful for small projects and may help to \r\n# save some trees in general.\r\n\r\nCOMPACT_RTF            = NO\r\n\r\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated \r\n# will contain hyperlink fields. The RTF file will \r\n# contain links (just like the HTML output) instead of page references. \r\n# This makes the output suitable for online browsing using WORD or other \r\n# programs which support those fields. \r\n# Note: wordpad (write) and others do not support links.\r\n\r\nRTF_HYPERLINKS         = NO\r\n\r\n# Load stylesheet definitions from file. Syntax is similar to doxygen's \r\n# config file, i.e. a series of assignments. You only have to provide \r\n# replacements, missing definitions are set to their default value.\r\n\r\nRTF_STYLESHEET_FILE    = \r\n\r\n# Set optional variables used in the generation of an rtf document. \r\n# Syntax is similar to doxygen's config file.\r\n\r\nRTF_EXTENSIONS_FILE    = \r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the man page output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_MAN tag is set to YES (the default) Doxygen will \r\n# generate man pages\r\n\r\nGENERATE_MAN           = NO\r\n\r\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. \r\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \r\n# put in front of it. If left blank `man' will be used as the default path.\r\n\r\nMAN_OUTPUT             = man\r\n\r\n# The MAN_EXTENSION tag determines the extension that is added to \r\n# the generated man pages (default is the subroutine's section .3)\r\n\r\nMAN_EXTENSION          = .3\r\n\r\n# If the MAN_LINKS tag is set to YES and Doxygen generates man output, \r\n# then it will generate one additional man file for each entity \r\n# documented in the real man page(s). These additional files \r\n# only source the real man page, but without them the man command \r\n# would be unable to find the correct page. The default is NO.\r\n\r\nMAN_LINKS              = NO\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the XML output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_XML tag is set to YES Doxygen will \r\n# generate an XML file that captures the structure of \r\n# the code including all documentation.\r\n\r\nGENERATE_XML           = NO\r\n\r\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. \r\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be \r\n# put in front of it. If left blank `xml' will be used as the default path.\r\n\r\nXML_OUTPUT             = xml\r\n\r\n# The XML_SCHEMA tag can be used to specify an XML schema, \r\n# which can be used by a validating XML parser to check the \r\n# syntax of the XML files.\r\n\r\nXML_SCHEMA             = \r\n\r\n# The XML_DTD tag can be used to specify an XML DTD, \r\n# which can be used by a validating XML parser to check the \r\n# syntax of the XML files.\r\n\r\nXML_DTD                = \r\n\r\n# If the XML_PROGRAMLISTING tag is set to YES Doxygen will \r\n# dump the program listings (including syntax highlighting \r\n# and cross-referencing information) to the XML output. Note that \r\n# enabling this will significantly increase the size of the XML output.\r\n\r\nXML_PROGRAMLISTING     = YES\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options for the AutoGen Definitions output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will \r\n# generate an AutoGen Definitions (see autogen.sf.net) file \r\n# that captures the structure of the code including all \r\n# documentation. Note that this feature is still experimental \r\n# and incomplete at the moment.\r\n\r\nGENERATE_AUTOGEN_DEF   = NO\r\n\r\n#---------------------------------------------------------------------------\r\n# configuration options related to the Perl module output\r\n#---------------------------------------------------------------------------\r\n\r\n# If the GENERATE_PERLMOD tag is set to YES Doxygen will \r\n# generate a Perl module file that captures the structure of \r\n# the code including all documentation. Note that this \r\n# feature is still experimental and incomplete at the \r\n# moment.\r\n\r\nGENERATE_PERLMOD       = NO\r\n\r\n# If the PERLMOD_LATEX tag is set to YES Doxygen will generate \r\n# the necessary Makefile rules, Perl scripts and LaTeX code to be able \r\n# to generate PDF and DVI output from the Perl module output.\r\n\r\nPERLMOD_LATEX          = NO\r\n\r\n# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be \r\n# nicely formatted so it can be parsed by a human reader.  This is useful \r\n# if you want to understand what is going on.  On the other hand, if this \r\n# tag is set to NO the size of the Perl module output will be much smaller \r\n# and Perl will parse it just the same.\r\n\r\nPERLMOD_PRETTY         = YES\r\n\r\n# The names of the make variables in the generated doxyrules.make file \r\n# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. \r\n# This is useful so different doxyrules.make files included by the same \r\n# Makefile don't overwrite each other's variables.\r\n\r\nPERLMOD_MAKEVAR_PREFIX = \r\n\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the preprocessor   \r\n#---------------------------------------------------------------------------\r\n\r\n# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will \r\n# evaluate all C-preprocessor directives found in the sources and include \r\n# files.\r\n\r\nENABLE_PREPROCESSING   = YES\r\n\r\n# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro \r\n# names in the source code. If set to NO (the default) only conditional \r\n# compilation will be performed. Macro expansion can be done in a controlled \r\n# way by setting EXPAND_ONLY_PREDEF to YES.\r\n\r\nMACRO_EXPANSION        = NO\r\n\r\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES \r\n# then the macro expansion is limited to the macros specified with the \r\n# PREDEFINED and EXPAND_AS_DEFINED tags.\r\n\r\nEXPAND_ONLY_PREDEF     = NO\r\n\r\n# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files \r\n# in the INCLUDE_PATH (see below) will be search if a #include is found.\r\n\r\nSEARCH_INCLUDES        = YES\r\n\r\n# The INCLUDE_PATH tag can be used to specify one or more directories that \r\n# contain include files that are not input files but should be processed by \r\n# the preprocessor.\r\n\r\nINCLUDE_PATH           = \r\n\r\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard \r\n# patterns (like *.h and *.hpp) to filter out the header-files in the \r\n# directories. If left blank, the patterns specified with FILE_PATTERNS will \r\n# be used.\r\n\r\nINCLUDE_FILE_PATTERNS  = \r\n\r\n# The PREDEFINED tag can be used to specify one or more macro names that \r\n# are defined before the preprocessor is started (similar to the -D option of \r\n# gcc). The argument of the tag is a list of macros of the form: name \r\n# or name=definition (no spaces). If the definition and the = are \r\n# omitted =1 is assumed. To prevent a macro definition from being \r\n# undefined via #undef or recursively expanded use the := operator \r\n# instead of the = operator.\r\n\r\nPREDEFINED             = \r\n\r\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then \r\n# this tag can be used to specify a list of macro names that should be expanded. \r\n# The macro definition that is found in the sources will be used. \r\n# Use the PREDEFINED tag if you want to use a different macro definition.\r\n\r\nEXPAND_AS_DEFINED      = \r\n\r\n# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then \r\n# doxygen's preprocessor will remove all function-like macros that are alone \r\n# on a line, have an all uppercase name, and do not end with a semicolon. Such \r\n# function macros are typically used for boiler-plate code, and will confuse \r\n# the parser if not removed.\r\n\r\nSKIP_FUNCTION_MACROS   = YES\r\n\r\n#---------------------------------------------------------------------------\r\n# Configuration::additions related to external references   \r\n#---------------------------------------------------------------------------\r\n\r\n# The TAGFILES option can be used to specify one or more tagfiles. \r\n# Optionally an initial location of the external documentation \r\n# can be added for each tagfile. The format of a tag file without \r\n# this location is as follows: \r\n#   TAGFILES = file1 file2 ... \r\n# Adding location for the tag files is done as follows: \r\n#   TAGFILES = file1=loc1 \"file2 = loc2\" ... \r\n# where \"loc1\" and \"loc2\" can be relative or absolute paths or \r\n# URLs. If a location is present for each tag, the installdox tool \r\n# does not have to be run to correct the links.\r\n# Note that each tag file must have a unique name\r\n# (where the name does NOT include the path)\r\n# If a tag file is not located in the directory in which doxygen \r\n# is run, you must also specify the path to the tagfile here.\r\n\r\nTAGFILES               = \r\n\r\n# When a file name is specified after GENERATE_TAGFILE, doxygen will create \r\n# a tag file that is based on the input files it reads.\r\n\r\nGENERATE_TAGFILE       = \r\n\r\n# If the ALLEXTERNALS tag is set to YES all external classes will be listed \r\n# in the class index. If set to NO only the inherited external classes \r\n# will be listed.\r\n\r\nALLEXTERNALS           = NO\r\n\r\n# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed \r\n# in the modules index. If set to NO, only the current project's groups will \r\n# be listed.\r\n\r\nEXTERNAL_GROUPS        = YES\r\n\r\n# The PERL_PATH should be the absolute path and name of the perl script \r\n# interpreter (i.e. the result of `which perl').\r\n\r\nPERL_PATH              = /usr/bin/perl\r\n\r\n#---------------------------------------------------------------------------\r\n# Configuration options related to the dot tool   \r\n#---------------------------------------------------------------------------\r\n\r\n# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will \r\n# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base \r\n# or super classes. Setting the tag to NO turns the diagrams off. Note that \r\n# this option is superseded by the HAVE_DOT option below. This is only a \r\n# fallback. It is recommended to install and use dot, since it yields more \r\n# powerful graphs.\r\n\r\nCLASS_DIAGRAMS         = YES\r\n\r\n# You can define message sequence charts within doxygen comments using the \\msc \r\n# command. Doxygen will then run the mscgen tool (see http://www.mcternan.me.uk/mscgen/) to \r\n# produce the chart and insert it in the documentation. The MSCGEN_PATH tag allows you to \r\n# specify the directory where the mscgen tool resides. If left empty the tool is assumed to \r\n# be found in the default search path.\r\n\r\nMSCGEN_PATH            = \r\n\r\n# If set to YES, the inheritance and collaboration graphs will hide \r\n# inheritance and usage relations if the target is undocumented \r\n# or is not a class.\r\n\r\nHIDE_UNDOC_RELATIONS   = YES\r\n\r\n# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is \r\n# available from the path. This tool is part of Graphviz, a graph visualization \r\n# toolkit from AT&T and Lucent Bell Labs. The other options in this section \r\n# have no effect if this option is set to NO (the default)\r\n\r\nHAVE_DOT               = NO\r\n\r\n# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen \r\n# will generate a graph for each documented class showing the direct and \r\n# indirect inheritance relations. Setting this tag to YES will force the \r\n# the CLASS_DIAGRAMS tag to NO.\r\n\r\nCLASS_GRAPH            = YES\r\n\r\n# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen \r\n# will generate a graph for each documented class showing the direct and \r\n# indirect implementation dependencies (inheritance, containment, and \r\n# class references variables) of the class with other documented classes.\r\n\r\nCOLLABORATION_GRAPH    = YES\r\n\r\n# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen \r\n# will generate a graph for groups, showing the direct groups dependencies\r\n\r\nGROUP_GRAPHS           = YES\r\n\r\n# If the UML_LOOK tag is set to YES doxygen will generate inheritance and \r\n# collaboration diagrams in a style similar to the OMG's Unified Modeling \r\n# Language.\r\n\r\nUML_LOOK               = NO\r\n\r\n# If set to YES, the inheritance and collaboration graphs will show the \r\n# relations between templates and their instances.\r\n\r\nTEMPLATE_RELATIONS     = NO\r\n\r\n# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT \r\n# tags are set to YES then doxygen will generate a graph for each documented \r\n# file showing the direct and indirect include dependencies of the file with \r\n# other documented files.\r\n\r\nINCLUDE_GRAPH          = YES\r\n\r\n# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and \r\n# HAVE_DOT tags are set to YES then doxygen will generate a graph for each \r\n# documented header file showing the documented files that directly or \r\n# indirectly include this file.\r\n\r\nINCLUDED_BY_GRAPH      = YES\r\n\r\n# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will \r\n# generate a call dependency graph for every global function or class method. \r\n# Note that enabling this option will significantly increase the time of a run. \r\n# So in most cases it will be better to enable call graphs for selected \r\n# functions only using the \\callgraph command.\r\n\r\nCALL_GRAPH             = NO\r\n\r\n# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then doxygen will \r\n# generate a caller dependency graph for every global function or class method. \r\n# Note that enabling this option will significantly increase the time of a run. \r\n# So in most cases it will be better to enable caller graphs for selected \r\n# functions only using the \\callergraph command.\r\n\r\nCALLER_GRAPH           = NO\r\n\r\n# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen \r\n# will graphical hierarchy of all classes instead of a textual one.\r\n\r\nGRAPHICAL_HIERARCHY    = YES\r\n\r\n# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES \r\n# then doxygen will show the dependencies a directory has on other directories \r\n# in a graphical way. The dependency relations are determined by the #include\r\n# relations between the files in the directories.\r\n\r\nDIRECTORY_GRAPH        = YES\r\n\r\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images \r\n# generated by dot. Possible values are png, jpg, or gif\r\n# If left blank png will be used.\r\n\r\nDOT_IMAGE_FORMAT       = png\r\n\r\n# The tag DOT_PATH can be used to specify the path where the dot tool can be \r\n# found. If left blank, it is assumed the dot tool can be found in the path.\r\n\r\nDOT_PATH               = \r\n\r\n# The DOTFILE_DIRS tag can be used to specify one or more directories that \r\n# contain dot files that are included in the documentation (see the \r\n# \\dotfile command).\r\n\r\nDOTFILE_DIRS           = \r\n\r\n# The MAX_DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of \r\n# nodes that will be shown in the graph. If the number of nodes in a graph \r\n# becomes larger than this value, doxygen will truncate the graph, which is \r\n# visualized by representing a node as a red box. Note that doxygen will always \r\n# show the root nodes and its direct children regardless of this setting.\r\n\r\nDOT_GRAPH_MAX_NODES    = 50\r\n\r\n# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent \r\n# background. This is disabled by default, which results in a white background. \r\n# Warning: Depending on the platform used, enabling this option may lead to \r\n# badly anti-aliased labels on the edges of a graph (i.e. they become hard to \r\n# read).\r\n\r\nDOT_TRANSPARENT        = NO\r\n\r\n# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output \r\n# files in one run (i.e. multiple -o and -T options on the command line). This \r\n# makes dot run faster, but since only newer versions of dot (>1.8.10) \r\n# support this, this feature is disabled by default.\r\n\r\nDOT_MULTI_TARGETS      = NO\r\n\r\n# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will \r\n# generate a legend page explaining the meaning of the various boxes and \r\n# arrows in the dot generated graphs.\r\n\r\nGENERATE_LEGEND        = YES\r\n\r\n# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will \r\n# remove the intermediate dot files that are used to generate \r\n# the various graphs.\r\n\r\nDOT_CLEANUP            = YES\r\n\r\n#---------------------------------------------------------------------------\r\n# Configuration::additions related to the search engine   \r\n#---------------------------------------------------------------------------\r\n\r\n# The SEARCHENGINE tag specifies whether or not a search engine should be \r\n# used. If set to NO the values of all tags below this one will be ignored.\r\n\r\nSEARCHENGINE           = NO\r\n"
  },
  {
    "path": "plugins/scrobsub/EncodingUtils.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#include \"EncodingUtils.h\"\r\n#include <errno.h>\r\n\r\n#include <string>\r\n\r\n#ifdef WIN32\r\n    #define POINTERINC( X ) X++\r\n#else\r\n    #define POINTERINC( X ) X+= sizeof( *X )\r\n#endif\r\n\r\nusing namespace std;\r\n\r\n/******************************************************************************\r\n    AnsiToUtf8\r\n******************************************************************************/\r\nint\r\nEncodingUtils::AnsiToUtf8(\r\n    const char* ansi,\r\n    char*       utf8,\r\n    int         nUtf8Size)\r\n{\r\n    WCHAR*  wszValue;          // Unicode value\r\n    size_t  ansi_len;\r\n    size_t  len;\r\n\r\n    if (ansi == NULL)\r\n    {\r\n        return 0;\r\n    }\r\n\r\n    ansi_len = strlen(ansi);\r\n\r\n    // Malloc enough memory for a Unicode string the size of the ansi string\r\n    wszValue = (WCHAR *)malloc((ansi_len + 1) * 2);\r\n    if (wszValue == NULL)\r\n    {\r\n        return 0;\r\n    }\r\n    \r\n    // Convert ANSI string to Unicode\r\n    \r\n    #ifdef WIN32\r\n        len = MultiByteToWideChar(CP_ACP,\r\n                                  0,\r\n                                  ansi,\r\n                                  static_cast<int>(ansi_len + 1),\r\n                                  wszValue,\r\n                                  static_cast<int>((ansi_len + 1) * 2 ));\r\n    #else\r\n        // This will use the current system locale (probably C)\r\n        len = mbstowcs( wszValue, ansi, ansi_len + 1 );\r\n    #endif\r\n\r\n    if ( len == 0 )\r\n    {\r\n        free(wszValue);\r\n        return 0;\r\n    }\r\n\r\n    // Convert Unicode value to UTF-8\r\n    *utf8 = '\\0';\r\n    len = UnicodeToUtf8(wszValue, -1, utf8, nUtf8Size);\r\n    if (len == 0 )\r\n    {\r\n        free(wszValue);\r\n        return 0;\r\n    }\r\n\r\n    free(wszValue);\r\n\r\n    return static_cast<int>(len-1);\r\n}\r\n\r\n/******************************************************************************\r\n    UnicodeToUtf8\r\n******************************************************************************/\r\nint\r\nEncodingUtils::UnicodeToUtf8(\r\n    const WCHAR* lpWideCharStr,\r\n    int          cwcChars,\r\n    char*        lpUtf8Str,\r\n    int          nUtf8Size)\r\n{\r\n    const unsigned short*   pwc = (unsigned short *)lpWideCharStr;\r\n    unsigned char*          pmb = (unsigned char  *)lpUtf8Str;\r\n    const unsigned short*   pwce; // ptr to end of wide string\r\n    size_t  cBytes = 2;\r\n\r\n    if ( cwcChars >= 0 ) {\r\n        pwce = pwc + ( cwcChars * sizeof( *pwc )) ;\r\n    } else {\r\n        pwce = (unsigned short *)((size_t)-1);\r\n    }\r\n\r\n    while ( pwc < pwce ) {\r\n        unsigned short  wc = *pwc;\r\n        POINTERINC( pwc );\r\n\r\n        if ( wc < 0x00000080 )\r\n        {\r\n            *pmb = (char)wc;\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n        }\r\n        else if ( wc < 0x00000800 )\r\n        {\r\n            *pmb = (char)(0xC0 | ((wc >>  6) & 0x1F));\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n            *pmb = (char)(0x80 |  (wc        & 0x3F));\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n        }\r\n        else if ( wc < 0x00010000 )\r\n        {\r\n            *pmb = (char)(0xE0 | ((wc >> 12) & 0x0F));\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n            *pmb = (char)(0x80 | ((wc >>  6) & 0x3F));\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n            *pmb = (char)(0x80 |  (wc        & 0x3F));\r\n            POINTERINC( pmb );\r\n            cBytes++;\r\n        }\r\n\r\n        // Reached the end?\r\n        if (wc == L'\\0' || cBytes >= (size_t)(nUtf8Size - 3))\r\n        {\r\n            *pmb = '\\0';\r\n            return static_cast<int>(cBytes);\r\n        }\r\n    }\r\n\r\n    return static_cast<int>(cBytes);\r\n}\r\n\r\n\r\n/******************************************************************************\r\n    Utf8ToAnsi\r\n******************************************************************************/\r\nstring\r\nEncodingUtils::Utf8ToAnsi(\r\n    const char* pcUTF8Str)\r\n{\r\n    // So, we'll do:\r\n    // UTF8 Multibyte to Unicode\r\n    // Unicode to ANSI Multibyte\r\n    \r\n    if (strlen(pcUTF8Str) == 0)\r\n    {\r\n        return string();\r\n    }\r\n\r\n    WCHAR* pcWideStr = NULL;\r\n    char*  pcAnsiStr = NULL;\r\n\r\n    // Get number of (wide or ANSI) chars the UTF8 string corresponds to\r\n    // TODO: check why we aren't logging the errors!\r\n    #ifdef WIN32\r\n        int nLength = MultiByteToWideChar(CP_UTF8, 0, pcUTF8Str, -1, pcWideStr, 0);\r\n\r\n        if (nLength == 0)\r\n        {\r\n            //int nError = GetLastError();\r\n            \r\n            // ERROR_INSUFFICIENT_BUFFER\r\n            // ERROR_INVALID_FLAGS\r\n            // ERROR_INVALID_PARAMETER\r\n            // ERROR_NO_UNICODE_TRANSLATION\r\n            //LOG(1, \"Couldn't get length of UTF8 string: '\" << pcUTF8Str <<\r\n            //    \"'. Returning empty string. Error code: \" << nError << \"\\n\");\r\n            return string();\r\n        }\r\n\r\n    #else\r\n        char* curLocale = setlocale( LC_CTYPE, NULL );\r\n        setlocale( LC_CTYPE, \"UTF-8\"  );\r\n        int nLength = mbstowcs( NULL, pcUTF8Str, 0 );\r\n        setlocale( LC_CTYPE, curLocale );\r\n    \r\n        if( nLength == (size_t) -1 )\r\n        {\r\n            int nError = errno;\r\n\r\n            return string();\r\n        }\r\n    \r\n    #endif\r\n\r\n    // Allocate enough space for the wide version\r\n    pcWideStr = new WCHAR[nLength + 1]; // length is in characters, not bytes\r\n\r\n    #ifdef WIN32\r\n        int nStatus = MultiByteToWideChar(CP_UTF8, 0, pcUTF8Str, -1, pcWideStr, nLength);\r\n\r\n        if (nStatus == 0)\r\n        {\r\n            //int nError = GetLastError();\r\n            //LOG(1, \"Couldn't convert UTF8 string '\" << pcUTF8Str <<\r\n            //    \"' to Unicode. Returning empty string. Error code: \" << nError << \"\\n\");\r\n            delete[] pcWideStr;\r\n            return string();\r\n        }\r\n\r\n    #else\r\n        setlocale( LC_CTYPE, \"UTF-8\" );\r\n        int nStatus = mbstowcs( pcWideStr, pcUTF8Str, nLength + 1);\r\n        setlocale( LC_CTYPE, curLocale );\r\n\r\n        if (nStatus == (size_t) -1 )\r\n        {\r\n            delete[] pcWideStr;\r\n            return string();\r\n        }\r\n    #endif\r\n\r\n    // Allocate enough space for the ANSI char* version\r\n    pcAnsiStr = new char[nLength + 5]; // 5?\r\n\r\n    // Conversion to ANSI (CP_ACP)\r\n    #ifdef WIN32\r\n        nStatus = WideCharToMultiByte(CP_ACP, 0, pcWideStr, -1, pcAnsiStr, nLength, NULL, NULL);\r\n        \r\n        if (nStatus == 0)\r\n        {\r\n            //int nError = GetLastError();\r\n\r\n            // ERROR_INSUFFICIENT_BUFFER\r\n            // ERROR_INVALID_FLAGS\r\n            // ERROR_INVALID_PARAMETER\r\n            //LOG(1, \"Couldn't convert Unicode string '\" << pcWideStr << \"' to ANSI.\" <<\r\n            //   \" Error code: \" << nError << \"\\n\");\r\n            delete[] pcWideStr;\r\n            delete[] pcAnsiStr;\r\n            return string();\r\n        }\r\n    #else\r\n        nStatus = wcstombs( pcAnsiStr, pcWideStr, nLength + 5 );\r\n\r\n        if( nStatus == (size_t)-1 )\r\n        {\r\n            delete[] pcWideStr;\r\n            delete[] pcAnsiStr;\r\n            return string();\r\n        }\r\n    #endif\r\n   \r\n    pcAnsiStr[nLength] = 0;\r\n\r\n    string sAnsi(pcAnsiStr);\r\n    \r\n    delete[] pcWideStr;\r\n    delete[] pcAnsiStr;\r\n\r\n    return sAnsi;\r\n}\r\n"
  },
  {
    "path": "plugins/scrobsub/EncodingUtils.h",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef ENCODINGUTILS_H\r\n#define ENCODINGUTILS_H\r\n\r\n#ifdef WIN32\r\n    #include <windows.h>\r\n#else\r\n    #include <wchar.h>\r\n    #define WCHAR wchar_t\r\n#endif\r\n\r\n#include <string>\r\n\r\n/*************************************************************************/ /**\r\n    A bunch of static functions for converting between different character\r\n    sets.\r\n\r\n    @author <erik@last.fm>\r\n******************************************************************************/\r\nclass EncodingUtils\r\n{\r\npublic:\r\n\r\n    /*********************************************************************/ /**\r\n        Converts an ANSI string to a UTF-8 string.\r\n        \r\n        @param[in] ansi\r\n    **************************************************************************/\r\n    static int\r\n    AnsiToUtf8(\r\n        const char* ansi,\r\n        char*       utf8,\r\n        int         nUtf8Size);\r\n        \r\n    static int\r\n    UnicodeToUtf8(\r\n        const WCHAR* lpWideCharStr,\r\n        int          cwcChars,\r\n        char*        lpUtf8Str,\r\n        int          nUtf8Size);\r\n\r\n    static std::string\r\n    Utf8ToAnsi(\r\n        const char* pcUTF8Str);\r\n\r\n\t\r\nprivate:\r\n\r\n\r\n};\r\n\r\n#endif // ENCODINGUTILS_H\r\n"
  },
  {
    "path": "plugins/scrobsub/RegistryUtils.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#include \"RegistryUtils.h\"\r\n\r\n#include <windows.h>\r\n\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\nRegistryUtils::Registry RegistryUtils::mRegInfo;\r\n\r\n/******************************************************************************\r\nGetKey\r\n******************************************************************************/\r\nHKEY\r\nRegistryUtils::GetKey(\r\n                      HKEY         parentKey,\r\n                      const WCHAR* pcSubkey,\r\n                      bool         bCreateIfNotFound )\r\n{\r\n    HKEY requestedKey;\r\n    LONG lResult;\r\n\r\n    if ( bCreateIfNotFound )\r\n    {\r\n        lResult = RegCreateKeyExW(\r\n            parentKey,\r\n            pcSubkey,\r\n            0,                       // reserved, must be 0\r\n            NULL,                    // class, ignore\r\n            REG_OPTION_NON_VOLATILE, // saves key on exit\r\n            KEY_ALL_ACCESS,          // access mask. TODO: test this as non-admin\r\n            NULL,                    // security attrs, NULL = default, inherit from parent\r\n            &requestedKey,\r\n            NULL );                   // info about whether key was created or opened\r\n    }\r\n    else\r\n    {\r\n        lResult = RegOpenKeyExW(\r\n            parentKey,\r\n            pcSubkey,\r\n            0,              // reserved\r\n            KEY_ALL_ACCESS, // access mask\r\n            &requestedKey );\r\n    }\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not retrieve registry key [\" << pcSubkey <<\r\n            \"]. System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n\r\n    return requestedKey;\r\n}\r\n\r\n\r\nHKEY\r\nRegistryUtils::GetKey(\r\n                      HKEY         parentKey,\r\n                      const char*  pcSubkey,\r\n                      bool         bCreateIfNotFound )\r\n{\r\n    HKEY requestedKey;\r\n    LONG lResult;\r\n\r\n    if ( bCreateIfNotFound )\r\n    {\r\n        lResult = RegCreateKeyExA(\r\n            parentKey,\r\n            pcSubkey,\r\n            0,                       // reserved, must be 0\r\n            NULL,                    // class, ignore\r\n            REG_OPTION_NON_VOLATILE, // saves key on exit\r\n            KEY_ALL_ACCESS,          // access mask. TODO: test this as non-admin\r\n            NULL,                    // security attrs, NULL = default, inherit from parent\r\n            &requestedKey,\r\n            NULL );                   // info about whether key was created or opened\r\n    }\r\n    else\r\n    {\r\n        lResult = RegOpenKeyExA(\r\n            parentKey,\r\n            pcSubkey,\r\n            0,              // reserved\r\n            KEY_ALL_ACCESS, // access mask\r\n            &requestedKey );\r\n    }\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not retrieve registry key [\" << pcSubkey <<\r\n            \"]. System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n\r\n    return requestedKey;\r\n}\r\n\r\n/******************************************************************************\r\nGetNumSubkeys\r\n******************************************************************************/\r\nint\r\nRegistryUtils::GetNumSubkeys(\r\n                        HKEY key )\r\n{\r\n    QueryRegInfo( key );\r\n    return mRegInfo.mnNumSubkeys;\r\n}\r\n\r\n/******************************************************************************\r\nGetSubkeyNames\r\n******************************************************************************/\r\n\r\n// FIXME: Why do we still need the tstring?\r\nvoid\r\nRegistryUtils::GetSubkeyNames(\r\n                         HKEY             key,\r\n                         vector<tstring>& vNames )\r\n{\r\n    int nNumSubkeys = GetNumSubkeys( key );\r\n    DWORD nSubkeyBufferSize = ( GetLongestSubkeySize( key ) + 1 ) * sizeof( TCHAR );\r\n    LONG lResult;\r\n    TCHAR *sName = new TCHAR[nSubkeyBufferSize];\r\n\r\n    for (int i = 0; i < nNumSubkeys; ++i)\r\n    {\r\n        // Get name of ith subkey\r\n        DWORD nResetSize = nSubkeyBufferSize;\r\n        lResult = RegEnumKeyEx(\r\n            key,\r\n            i,\r\n            sName,\r\n            &nResetSize,\r\n            NULL,               // reserved, must be 0\r\n            NULL,               // class\r\n            NULL,               // class size\r\n            NULL );             // last write time\r\n\r\n\r\n        if ( lResult != ERROR_SUCCESS )\r\n        {\r\n            delete[] sName;\r\n            ostringstream osErr;\r\n            osErr << \"Could not enumerate registry subkeys. System error: \" <<\r\n                lResult;\r\n            throw CRegistryException( osErr.str() );\r\n        }\r\n\r\n        vNames.push_back( sName );\r\n\r\n    }\r\n    delete[] sName;\r\n}\r\n\r\n/******************************************************************************\r\nGetLongestSubkeySize\r\n******************************************************************************/\r\nDWORD\r\nRegistryUtils::GetLongestSubkeySize(\r\n                               HKEY key)\r\n{\r\n    QueryRegInfo( key );\r\n    return static_cast<DWORD>( mRegInfo.mnSizeLongestSubkey );\r\n}\r\n\r\n/******************************************************************************\r\nGetLongestDataSize\r\n******************************************************************************/\r\nDWORD\r\nRegistryUtils::GetLongestDataSize(\r\n                             HKEY key )\r\n{\r\n    QueryRegInfo( key );\r\n    return static_cast<DWORD>( mRegInfo.mnSizeLongestData );\r\n}\r\n\r\n/******************************************************************************\r\nQueryRegInfo\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::QueryRegInfo(\r\n                       HKEY key )\r\n{\r\n    DWORD nNumSubkeys;\r\n    DWORD nSizeLongestSubkey;\r\n    DWORD nNumValues;\r\n    DWORD nSizeLongestValue;\r\n    DWORD nSizeLongestData;\r\n\r\n    LONG lResult = RegQueryInfoKey(\r\n        key,\r\n        NULL,                // class, ignore\r\n        NULL,                // class string size, ignore\r\n        NULL,                // reserved, must be 0\r\n        &nNumSubkeys,        // number of subkeys\r\n        &nSizeLongestSubkey, // size in TCHARs of longest subkey,\r\n        // includes terminating \\0 on XP but not on 98. Doh!\r\n        NULL,                // longest class string size, ignore\r\n        &nNumValues,         // num values in this key\r\n        &nSizeLongestValue,  // size in TCHARs of longest value string,\r\n        // does never include terminating \\0\r\n        &nSizeLongestData,   // size in bytes of biggest data entry\r\n        NULL,                // size of security descriptor, don't care\r\n        NULL );              // last write time, don't care\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not query registry key for info. System error: \" <<\r\n            lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n\r\n    mRegInfo.mKey = key;\r\n    mRegInfo.mnNumSubkeys = nNumSubkeys;\r\n    mRegInfo.mnSizeLongestSubkey = nSizeLongestSubkey;\r\n    mRegInfo.mnNumValues = nNumValues;\r\n    mRegInfo.mnSizeLongestValue = nSizeLongestValue;\r\n    mRegInfo.mnSizeLongestData = nSizeLongestData;\r\n\r\n}\r\n\r\n/******************************************************************************\r\nQueryString\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::QueryString(\r\n                      HKEY         key,\r\n                      const char* pcValue,\r\n                      char*       pcResult,\r\n                      DWORD        nResultSize,\r\n                      bool         bCreateIfNotFound,\r\n                      const char* pcDefault )\r\n{\r\n// FIXME: this looks crazy. Why are we defining UNICODE for half the code file?\r\n#define UNICODE\r\n    LONG lResult = RegQueryValueExA(\r\n        key,\r\n        pcValue,                            // value to query\r\n        NULL,                               // reserved\r\n        NULL,                               // tells you what type the value is\r\n        reinterpret_cast<LPBYTE>( pcResult ), // store result here\r\n        &nResultSize );\r\n\r\n    if ( lResult == ERROR_FILE_NOT_FOUND && bCreateIfNotFound )\r\n    {\r\n        // Create value if it wasn't found\r\n        WriteString( key, pcValue, pcDefault );\r\n        strncpy( pcResult, pcDefault, nResultSize );\r\n    }\r\n    else if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not read registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n\r\n}\r\n\r\n\r\n/******************************************************************************\r\nQueryString\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::QueryString(\r\n                           HKEY         key,\r\n                           const WCHAR* pcValue,\r\n                           WCHAR*       pcResult,\r\n                           DWORD        nResultSize,\r\n                           bool         bCreateIfNotFound,\r\n                           const WCHAR* pcDefault )\r\n{\r\n    LONG lResult = RegQueryValueExW(\r\n        key,\r\n        pcValue,                            // value to query\r\n        NULL,                               // reserved\r\n        NULL,                               // tells you what type the value is\r\n        reinterpret_cast<LPBYTE>( pcResult ), // store result here\r\n        &nResultSize );\r\n\r\n    if ( lResult == ERROR_FILE_NOT_FOUND && bCreateIfNotFound )\r\n    {\r\n        // Create value if it wasn't found\r\n        WriteString( key, pcValue, pcDefault );\r\n        wcsncpy( pcResult, pcDefault, nResultSize );  \r\n    }\r\n    else if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not read registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n\r\n}\r\n\r\n\r\n/******************************************************************************\r\nQueryBool\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::QueryBool(\r\n                    HKEY         key,\r\n                    const TCHAR* pcValue,\r\n                    bool*        pbResult,\r\n                    bool         bDefault )\r\n{\r\n    DWORD nResultSize = sizeof( DWORD );\r\n    DWORD nResult;\r\n\r\n    LONG lResult = RegQueryValueEx(\r\n        key,\r\n        pcValue,                              // value to query\r\n        NULL,                                 // reserved\r\n        NULL,                                 // tells you what type the value is\r\n        reinterpret_cast<LPBYTE>( &nResult ), // store result here\r\n        &nResultSize );\r\n\r\n    if ( lResult == ERROR_FILE_NOT_FOUND )\r\n    {\r\n        // Create value if it wasn't found\r\n        WriteBool( key, pcValue, bDefault );\r\n        *pbResult = bDefault;\r\n    }\r\n    else if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not read registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n    else\r\n    {\r\n        *pbResult = nResult != 0;\r\n    }\r\n}\r\n\r\n/******************************************************************************\r\nQueryInt\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::QueryInt(\r\n                   HKEY         key,\r\n                   const TCHAR* pcValue,\r\n                   int*         pnResult,\r\n                   int          nDefault )\r\n{\r\n    DWORD nResultSize = sizeof( DWORD );\r\n    DWORD nResult;\r\n\r\n    LONG lResult = RegQueryValueEx(\r\n        key,\r\n        pcValue,                              // value to query\r\n        NULL,                                 // reserved\r\n        NULL,                                 // tells you what type the value is\r\n        reinterpret_cast<LPBYTE>( &nResult ), // store result here\r\n        &nResultSize );\r\n\r\n    if ( lResult == ERROR_FILE_NOT_FOUND )\r\n    {\r\n        // Create value if it wasn't found\r\n        WriteInt( key, pcValue, nDefault );\r\n        *pnResult = nDefault;\r\n    }\r\n    else if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not read registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n    else\r\n    {\r\n        *pnResult = static_cast<int>( nResult );\r\n    }\r\n\r\n}\r\n\r\n/******************************************************************************\r\nWriteString\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::WriteString(\r\n                           HKEY         key,\r\n                           const WCHAR* pcValue,\r\n                           const WCHAR* pcData )\r\n{\r\n    LONG lResult = RegSetValueExW(\r\n        key,\r\n        pcValue,\r\n        0,          // reserved, must be 0\r\n        REG_SZ,     // type string\r\n        reinterpret_cast<LPBYTE>( const_cast<WCHAR *>( pcData ) ),\r\n        static_cast<DWORD>( ( wcslen( pcData ) + 1 ) * sizeof( TCHAR ) ) );\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not write registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\n\r\nvoid\r\nRegistryUtils::WriteString(\r\n                           HKEY         key,\r\n                           const char* pcValue,\r\n                           const char* pcData )\r\n{\r\n    LONG lResult = RegSetValueExA(\r\n        key,\r\n        pcValue,\r\n        0,          // reserved, must be 0\r\n        REG_SZ,     // type string\r\n        reinterpret_cast<LPBYTE>( const_cast<char *>( pcData ) ),\r\n        static_cast<DWORD>( ( strlen( pcData ) + 1 ) * sizeof( char ) ) );\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not write registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\n/******************************************************************************\r\nWriteBool\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::WriteBool(\r\n                         HKEY         key,\r\n                         const char* pcValue,\r\n                         bool         bData )\r\n{\r\n    DWORD dWordSize = sizeof( DWORD );\r\n    DWORD nValue = bData ? 1 : 0;\r\n\r\n    LONG lResult = RegSetValueExA(\r\n        key,\r\n        pcValue,\r\n        0,          // reserved, must be 0\r\n        REG_DWORD,  // type DWORD\r\n        reinterpret_cast<LPBYTE>( &nValue ),\r\n        dWordSize );\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not write registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\nvoid\r\nRegistryUtils::WriteBool(\r\n                    HKEY         key,\r\n                    const WCHAR* pcValue,\r\n                    bool         bData )\r\n{\r\n    DWORD dWordSize = sizeof( DWORD );\r\n    DWORD nValue = bData ? 1 : 0;\r\n\r\n    LONG lResult = RegSetValueExW(\r\n        key,\r\n        pcValue,\r\n        0,          // reserved, must be 0\r\n        REG_DWORD,  // type DWORD\r\n        reinterpret_cast<LPBYTE>( &nValue ),\r\n        dWordSize );\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not write registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\n/******************************************************************************\r\nWriteInt\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::WriteInt(\r\n                   HKEY         key,\r\n                   const TCHAR* pcValue,\r\n                   int          nData)\r\n{\r\n    DWORD dWordSize = sizeof( DWORD );\r\n\r\n    LONG lResult = RegSetValueEx(\r\n        key,\r\n        pcValue,\r\n        0,          // reserved, must be 0\r\n        REG_DWORD,  // type DWORD\r\n        reinterpret_cast<LPBYTE>( &nData ),\r\n        dWordSize );\r\n\r\n    if (lResult != ERROR_SUCCESS)\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not write registry value [\" << pcValue << \"]. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\n/******************************************************************************\r\nCloseRegKey\r\n******************************************************************************/\r\nvoid\r\nRegistryUtils::CloseRegKey(\r\n                      HKEY key )\r\n{\r\n    LONG lResult = RegCloseKey( key );\r\n\r\n    if ( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not close registry key. \" <<\r\n            \"System error: \" << lResult;\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}\r\n\r\nvoid \r\nRegistryUtils::DeleteValue( HKEY key, LPCWSTR pcValue)\r\n{\r\n    LONG lResult = RegDeleteValueW( key, pcValue );\r\n\r\n    if( lResult != ERROR_SUCCESS )\r\n    {\r\n        ostringstream osErr;\r\n        osErr << \"Could not delete registry value. \" <<\r\n            \"System error: \" << lResult;\r\n\r\n        throw CRegistryException( osErr.str() );\r\n    }\r\n}"
  },
  {
    "path": "plugins/scrobsub/RegistryUtils.h",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n#ifndef _REGISTRY_UTILS_H_\r\n#define _REGISTRY_UTILS_H_\r\n\r\n#include \"StdString.h\"\r\n\r\n#include <windows.h>\r\n\r\n#include <string>\r\n#include <vector>\r\n\r\n/*************************************************************************/ /**\r\nA bunch of static registry utility functions. Incomplete.\r\n******************************************************************************/\r\nclass RegistryUtils\r\n{\r\npublic:\r\n\r\n    class CRegistryException : public std::logic_error {\r\n    public:\r\n        CRegistryException(const std::string& sMsg) : logic_error(sMsg) { }\r\n    };\r\n\r\n    /*********************************************************************/ /**\r\n    Get a key handle by passing in a parent key (HKEY_CURRENT_USER,\r\n    HKEY_LOCAL_MACHINE) and a subkey (\"Software\\Last.fm\\Service\\1.0\").\r\n    **************************************************************************/\r\n    static HKEY\r\n        GetKey(\r\n        HKEY         parentKey,\r\n        const WCHAR* pcSubkey,\r\n        bool         bCreateIfNotFound = false);\r\n\r\n    static HKEY\r\n        GetKey(\r\n        HKEY         parentKey,\r\n        const char*  pcSubkey,\r\n        bool         bCreateIfNotFound = false);\r\n\r\n    /*********************************************************************/ /**\r\n    Returns the number of subkeys for the key identified by key.\r\n    **************************************************************************/\r\n    static int\r\n        GetNumSubkeys(\r\n        HKEY key);\r\n\r\n    /*********************************************************************/ /**\r\n    Reads the names of all subkeys of key into vector vNames.\r\n    **************************************************************************/\r\n    static void\r\n        GetSubkeyNames(\r\n        HKEY                  key,\r\n        std::vector<tstring>& vNames);\r\n\r\n    /*********************************************************************/ /**\r\n    Returns the size of the longest subkey name in TCHARs.\r\n    **************************************************************************/\r\n    static DWORD\r\n        GetLongestSubkeySize(\r\n        HKEY key);\r\n\r\n    /*********************************************************************/ /**\r\n    Returns the size of the longest data entry in bytes.\r\n    **************************************************************************/\r\n    static DWORD\r\n        GetLongestDataSize(\r\n        HKEY key);\r\n\r\n    /*********************************************************************/ /**\r\n    Fills pcResult with the string stored in the registry under key key\r\n    and value pcValue.\r\n    **************************************************************************/\r\n\r\n    // FIXME: do we still need both? Notice that it only differs on pcValue\r\n    // and pcDefault... Should they really be char*s?\r\n    static void\r\n        QueryString(\r\n        HKEY         key,\r\n        const char* pcValue,\r\n        char*       pcResult,\r\n        DWORD        nResultSize,\r\n        bool         bCreateIfNotFound = true,\r\n        const char* pcDefault = \"\" );\r\n\r\n    static void\r\n        QueryString(\r\n        HKEY         key,\r\n        const WCHAR* pcValue,\r\n        WCHAR*       pcResult,\r\n        DWORD        nResultSize,\r\n        bool         bCreateIfNotFound = true,\r\n        const WCHAR* pcDefault = L\"\" );\r\n\r\n    /*********************************************************************/ /**\r\n        Fills pbResult with the bool stored in the registry under key key\r\n        and value pcValue.\r\n    **************************************************************************/\r\n    static void\r\n        QueryBool(\r\n        HKEY         key,\r\n        const TCHAR* pcValue,\r\n        bool*        pbResult,\r\n        bool         bDefault = false);\r\n\r\n    /*********************************************************************/ /**\r\n        Fills pnResult with the int stored in the registry under key key\r\n        and value pcValue.\r\n        **************************************************************************/\r\n    static void\r\n        QueryInt(\r\n        HKEY         key,\r\n        const TCHAR* pcValue,\r\n        int*         pnResult,\r\n        int          nDefault = 0);\r\n\r\n    /*********************************************************************/ /**\r\n        Writes the string pcData to the value named by pcValue in the key key.\r\n        Creates the value if it doesn't already exist.\r\n        **************************************************************************/\r\n\r\n    // FIXME: need all these?\r\n    static void\r\n        WriteString(\r\n        HKEY         key,\r\n        const char* pcValue,\r\n        const char* pcData);\r\n\r\n    static void\r\n        WriteString(\r\n        HKEY         key,\r\n        const WCHAR* pcValue,\r\n        const WCHAR* pcData);\r\n\r\n    static void\r\n        DeleteValue(\r\n        HKEY key,\r\n        LPCWSTR pcValue);\r\n\r\n    /*********************************************************************/ /**\r\n        Writes the bool bData to the value named by pcValue in the key key.\r\n        Creates the value if it doesn't already exist.\r\n        **************************************************************************/\r\n    static void\r\n        WriteBool(\r\n        HKEY         key,\r\n        const char* pcValue,\r\n        bool         bData);\r\n\r\n    static void\r\n        WriteBool(\r\n        HKEY         key,\r\n        const WCHAR* pcValue,\r\n        bool         bData);\r\n\r\n    /*********************************************************************/ /**\r\n    Writes the int nData to the value named by pcValue in the key key.\r\n    Creates the value if it doesn't already exist.\r\n    **************************************************************************/\r\n    static void\r\n        WriteInt(\r\n        HKEY         key,\r\n        const TCHAR* pcValue,\r\n        int          nData);\r\n\r\n    /*********************************************************************/ /**\r\n    Closes the registry key handed to function.\r\n    **************************************************************************/\r\n    static void\r\n        CloseRegKey(\r\n        HKEY key);\r\n\r\n    static void\r\n        DeleteRegKey(\r\n        HKEY key);\r\n\r\nprivate:\r\n\r\n    /*********************************************************************/ /**\r\n    Used to cache the info about a registry key returned by\r\n    ReqQueryInfoKey.\r\n    **************************************************************************/\r\n    class Registry\r\n    {\r\n    public:\r\n        HKEY    mKey;\r\n        int     mnNumSubkeys;\r\n        size_t  mnSizeLongestSubkey;\r\n        int     mnNumValues;\r\n        size_t  mnSizeLongestValue;\r\n        size_t  mnSizeLongestData;\r\n    };\r\n\r\n    /*********************************************************************/ /**\r\n    Fills the info cache by calling the Win32 API function RegQueryInfoKey.\r\n    **************************************************************************/\r\n    static void\r\n        QueryRegInfo(\r\n        HKEY key);\r\n\r\n\r\n    // Last returned key info\r\n    static Registry            mRegInfo;\r\n\r\n};\r\n\r\n#endif //_REGISTRY_UTILS_H_"
  },
  {
    "path": "plugins/scrobsub/ScrobSub.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 45;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t63B0435C0EF28CF70085758B /* BlockingClient.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 63B043580EF28CF70085758B /* BlockingClient.cpp */; };\n\t\t63B0435D0EF28CF70085758B /* BlockingClient.h in Headers */ = {isa = PBXBuildFile; fileRef = 63B043590EF28CF70085758B /* BlockingClient.h */; };\n\t\t63B0435E0EF28CF70085758B /* ScrobSubmitter.h in Headers */ = {isa = PBXBuildFile; fileRef = 63B0435A0EF28CF70085758B /* ScrobSubmitter.h */; };\n\t\t63B0435F0EF28CF70085758B /* ScrobSubmitter.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 63B0435B0EF28CF70085758B /* ScrobSubmitter.cpp */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXFileReference section */\n\t\t63B043580EF28CF70085758B /* BlockingClient.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BlockingClient.cpp; sourceTree = \"<group>\"; };\n\t\t63B043590EF28CF70085758B /* BlockingClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BlockingClient.h; sourceTree = \"<group>\"; };\n\t\t63B0435A0EF28CF70085758B /* ScrobSubmitter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScrobSubmitter.h; sourceTree = \"<group>\"; };\n\t\t63B0435B0EF28CF70085758B /* ScrobSubmitter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScrobSubmitter.cpp; sourceTree = \"<group>\"; };\n\t\tD2AAC046055464E500DB518D /* libScrobSub.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libScrobSub.a; sourceTree = BUILT_PRODUCTS_DIR; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\tD289987405E68DCB004EDB86 /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t08FB7794FE84155DC02AAC07 /* ScrobSub */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t08FB7795FE84155DC02AAC07 /* Source */,\n\t\t\t\tC6A0FF2B0290797F04C91782 /* Documentation */,\n\t\t\t\t1AB674ADFE9D54B511CA2CBB /* Products */,\n\t\t\t);\n\t\t\tname = ScrobSub;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t08FB7795FE84155DC02AAC07 /* Source */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t63B043580EF28CF70085758B /* BlockingClient.cpp */,\n\t\t\t\t63B043590EF28CF70085758B /* BlockingClient.h */,\n\t\t\t\t63B0435A0EF28CF70085758B /* ScrobSubmitter.h */,\n\t\t\t\t63B0435B0EF28CF70085758B /* ScrobSubmitter.cpp */,\n\t\t\t);\n\t\t\tname = Source;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t1AB674ADFE9D54B511CA2CBB /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tD2AAC046055464E500DB518D /* libScrobSub.a */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tC6A0FF2B0290797F04C91782 /* Documentation */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t);\n\t\t\tname = Documentation;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXHeadersBuildPhase section */\n\t\tD2AAC043055464E500DB518D /* Headers */ = {\n\t\t\tisa = PBXHeadersBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t63B0435D0EF28CF70085758B /* BlockingClient.h in Headers */,\n\t\t\t\t63B0435E0EF28CF70085758B /* ScrobSubmitter.h in Headers */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXHeadersBuildPhase section */\n\n/* Begin PBXNativeTarget section */\n\t\tD2AAC045055464E500DB518D /* ScrobSub */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget \"ScrobSub\" */;\n\t\t\tbuildPhases = (\n\t\t\t\tD2AAC043055464E500DB518D /* Headers */,\n\t\t\t\tD2AAC044055464E500DB518D /* Sources */,\n\t\t\t\tD289987405E68DCB004EDB86 /* Frameworks */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = ScrobSub;\n\t\t\tproductName = ScrobSub;\n\t\t\tproductReference = D2AAC046055464E500DB518D /* libScrobSub.a */;\n\t\t\tproductType = \"com.apple.product-type.library.static\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t08FB7793FE84155DC02AAC07 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tbuildConfigurationList = 1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject \"ScrobSub\" */;\n\t\t\tcompatibilityVersion = \"Xcode 3.1\";\n\t\t\thasScannedForEncodings = 1;\n\t\t\tmainGroup = 08FB7794FE84155DC02AAC07 /* ScrobSub */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\tD2AAC045055464E500DB518D /* ScrobSub */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\tD2AAC044055464E500DB518D /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t63B0435C0EF28CF70085758B /* BlockingClient.cpp in Sources */,\n\t\t\t\t63B0435F0EF28CF70085758B /* ScrobSubmitter.cpp in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin XCBuildConfiguration section */\n\t\t1DEB91EC08733DB70010E9CD /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_ENABLE_FIX_AND_CONTINUE = YES;\n\t\t\t\tGCC_MODEL_TUNING = G5;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tINSTALL_PATH = /usr/local/lib;\n\t\t\t\tPRODUCT_NAME = ScrobSub;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t1DEB91ED08733DB70010E9CD /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tDEBUG_INFORMATION_FORMAT = \"dwarf-with-dsym\";\n\t\t\t\tGCC_MODEL_TUNING = G5;\n\t\t\t\tINSTALL_PATH = /usr/local/lib;\n\t\t\t\tPRODUCT_NAME = ScrobSub;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t1DEB91F008733DB70010E9CD /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = c99;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tPREBINDING = NO;\n\t\t\t\tSDKROOT = macosx10.5;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t1DEB91F108733DB70010E9CD /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tARCHS = \"$(ARCHS_STANDARD_32_BIT)\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = c99;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tPREBINDING = NO;\n\t\t\t\tSDKROOT = macosx10.5;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t1DEB91EB08733DB70010E9CD /* Build configuration list for PBXNativeTarget \"ScrobSub\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t1DEB91EC08733DB70010E9CD /* Debug */,\n\t\t\t\t1DEB91ED08733DB70010E9CD /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t1DEB91EF08733DB70010E9CD /* Build configuration list for PBXProject \"ScrobSub\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t1DEB91F008733DB70010E9CD /* Debug */,\n\t\t\t\t1DEB91F108733DB70010E9CD /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 08FB7793FE84155DC02AAC07 /* Project object */;\n}\n"
  },
  {
    "path": "plugins/scrobsub/ScrobSubmitter.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n// Stops warnings about deprecated CRT functions\r\n#ifndef _CRT_SECURE_NO_DEPRECATE\r\n    #define _CRT_SECURE_NO_DEPRECATE\r\n#endif\r\n#ifndef _SCL_SECURE_NO_DEPRECATE\r\n    #define _SCL_SECURE_NO_DEPRECATE\r\n#endif\r\n\r\n#include \"ScrobSubmitter.h\"\r\n#include \"EncodingUtils.h\"\r\n\r\n#include <windows.h>\r\n#include <tchar.h>\r\n#include <process.h>\r\n#include <shlobj.h>\r\n\r\n#include <iostream>\r\n#include <sstream>\r\n#include <string>\r\n\r\nusing namespace std;\r\n\r\nextern DWORD scrobSubPipeName(string* pipeName);\r\nextern string formatWin32Error(DWORD error);\r\n\r\n/******************************************************************************\r\n    Constants\r\n******************************************************************************/\r\nstatic const char* kVersion = \"1.1.1\";\r\nstatic const int   kLaunchWait = 60000; // in ms\r\n\r\n/******************************************************************************\r\n    ScrobSubmitter\r\n******************************************************************************/\r\nScrobSubmitter::ScrobSubmitter() :\r\n    mNextId(0),\r\n    mStopThread(false),\r\n    mLaunchTime(0)\r\n{\r\n    InitializeCriticalSection(&mMutex);\r\n    \r\n    mRequestAvailable = CreateEvent( \r\n        NULL,         // no security attributes\r\n        TRUE,         // manual reset event\r\n        FALSE,        // initial state is non-signaled\r\n        NULL);        // object name\r\n\r\n    mExit = CreateEvent( \r\n        NULL,         // no security attributes\r\n        TRUE,         // manual reset event\r\n        FALSE,        // initial state is non-signaled\r\n        NULL);        // object name\r\n}\r\n\r\n/******************************************************************************\r\n   ~ScrobSubmitter\r\n******************************************************************************/\r\nScrobSubmitter::~ScrobSubmitter()\r\n{\r\n    // Not using dtor for thread termination as we can't be sure the client\r\n    // is still alive so the status callbacks might fail.\r\n\r\n    DeleteCriticalSection(&mMutex);\r\n\r\n    CloseHandle(mRequestAvailable);\r\n    CloseHandle(mExit);\r\n}\r\n\r\n/******************************************************************************\r\n   Term\r\n******************************************************************************/\r\nvoid\r\nScrobSubmitter::Term()\r\n{\r\n    SendToAS( \"TERM c=\" + mPluginId + '\\n' );\r\n    // Signal socket thread to exit\r\n    mStopThread = true;\r\n    SetEvent(mExit);\r\n\r\n    // Wait for it to die before leaving\r\n    DWORD waitResult = WaitForSingleObject(mSocketThread, 5000);\r\n    if ( waitResult == WAIT_TIMEOUT || waitResult == WAIT_FAILED )\r\n    {\r\n        ostringstream os;\r\n        os << \"Wait for ScrobSubmitter thread termination \" <<\r\n            ( ( waitResult == WAIT_TIMEOUT ) ? \"timed out. \" : \"failed. \" ) <<\r\n            \"GetLastError() \" << GetLastError();\r\n        ReportStatus( -1, true, os.str() );\r\n    }\r\n    \r\n    CloseHandle(mSocketThread);\r\n}    \r\n\r\n/******************************************************************************\r\n    Init\r\n******************************************************************************/\r\nvoid\r\nScrobSubmitter::Init(\r\n    const string& pluginId,\r\n    StatusCallback callback,\r\n    void* userData)\r\n{\r\n    mPluginId = pluginId;\r\n    mpReportStatus = callback;\r\n    mpUserData = userData;\r\n        \r\n    bool isAutoLaunchEnabled = true;\r\n\r\n    // Read autolaunch option from registry\r\n    HKEY regKeyAS;\r\n    LONG lResult = RegOpenKeyEx(\r\n        HKEY_CURRENT_USER,\r\n        _T(\"Software\\\\Last.fm\\\\Client\"),\r\n        0,              // reserved\r\n        KEY_READ,       // access mask\r\n        &regKeyAS);\r\n\r\n    if (lResult == ERROR_SUCCESS)\r\n    {\r\n        TCHAR acBoolAsString[10];\r\n        DWORD nSize = 10;\r\n        lResult = RegQueryValueEx(\r\n            regKeyAS,                                 // key\r\n            _T(\"LaunchWithMediaPlayer\"),              // value to query\r\n            NULL,                                     // reserved\r\n            NULL,                                     // tells you what type the value is\r\n            reinterpret_cast<LPBYTE>(acBoolAsString), // store result here\r\n            &nSize);\r\n\r\n        if (lResult == ERROR_SUCCESS)\r\n        {\r\n            isAutoLaunchEnabled = _tcscmp(acBoolAsString, _T(\"true\")) == 0;\r\n        }\r\n\r\n        RegCloseKey(regKeyAS);\r\n    }\r\n    \r\n    if ( isAutoLaunchEnabled )\r\n    {\r\n        LaunchClient();\r\n    }\r\n\r\n    DWORD err = scrobSubPipeName(&mPipeName);\r\n    if (err)\r\n    {\r\n        ReportStatus(-1, true, formatWin32Error(err));\r\n    }\r\n\r\n    // Start socket thread\r\n    unsigned threadId;\r\n\r\n    mSocketThread = reinterpret_cast<HANDLE>(_beginthreadex( \r\n        NULL,                           // security crap\r\n        0,                              // stack size\r\n        SendToASThreadMain,             // start function\r\n        reinterpret_cast<void*>(this),  // argument to thread\r\n        0,                              // run straight away\r\n        &threadId));                    // thread id out\r\n    \r\n    if (mSocketThread == 0) // Error\r\n    {\r\n        ReportStatus(-1, true, strerror(errno));\r\n    }\r\n\r\n    ConnectToAS( 0 );\r\n}\r\n\r\n/******************************************************************************\r\n    LaunchClient\r\n******************************************************************************/\r\nbool\r\nScrobSubmitter::LaunchClient()\r\n{\r\n    TCHAR acExe[MAX_PATH + 1];\r\n    DWORD nPathSize = MAX_PATH + 1;\r\n    string sPath;\r\n\r\n    acExe[0] = _T('\\0');\r\n\r\n    // Open HKCU key\r\n    HKEY regKeyAS;\r\n    LONG lResult = RegOpenKeyEx(\r\n        HKEY_CURRENT_USER,\r\n        _T(\"Software\\\\Last.fm\\\\Client\"),\r\n        0,              // reserved\r\n        KEY_READ,       // access mask\r\n        &regKeyAS);\r\n    \r\n    if (lResult == ERROR_SUCCESS)\r\n    {\r\n        // Try and read exe path\r\n        lResult = RegQueryValueEx(\r\n            regKeyAS,                           // key\r\n            _T(\"Path\"),                         // value to query\r\n            NULL,                               // reserved\r\n            NULL,                               // tells you what type the value is\r\n            reinterpret_cast<LPBYTE>(acExe),    // store result here\r\n            &nPathSize);\r\n\r\n        RegCloseKey(regKeyAS);\r\n    }\r\n\r\n    if ( _tcslen( acExe ) == 0 )\r\n    {\r\n        // Couldn't read path from HKCU, try HKLM\r\n        lResult = RegOpenKeyEx(\r\n            HKEY_LOCAL_MACHINE,\r\n            _T(\"Software\\\\Last.fm\\\\Client\"),\r\n            0,              // reserved\r\n            KEY_READ,       // access mask\r\n            &regKeyAS);\r\n    \r\n        if (lResult == ERROR_SUCCESS)\r\n        {\r\n            nPathSize = MAX_PATH + 1;\r\n\r\n            // Try and read exe path\r\n            lResult = RegQueryValueEx(\r\n                regKeyAS,                           // key\r\n                _T(\"Path\"),                         // value to query\r\n                NULL,                               // reserved\r\n                NULL,                               // tells you what type the value is\r\n                reinterpret_cast<LPBYTE>(acExe),    // store result here\r\n                &nPathSize);\r\n\r\n            RegCloseKey(regKeyAS);\r\n        }\r\n    }\r\n\r\n    if ( _tcslen( acExe ) == 0 )\r\n    {\r\n        ReportStatus(-1, true,\r\n            \"Couldn't read the Last.fm exe path from the registry.\");\r\n        return false;\r\n    }\r\n\r\n    // Work out what the app dir is\r\n    TCHAR defaultDir[MAX_PATH + 1];\r\n    _tcsncpy( defaultDir, acExe, _tcsclen( acExe ) + 1 ); // +1 for null terminator\r\n\r\n    // Look for last backslash\r\n    TCHAR* pos = _tcsrchr( defaultDir, _T('\\\\') );\r\n    if ( pos == NULL )\r\n    {\r\n        // Path might also use forward slashes\r\n        pos = _tcsrchr( defaultDir, _T('/') );\r\n\r\n        if ( pos == NULL )\r\n        {\r\n            ReportStatus(-1, true,\r\n                \"Last.fm exe path from registry invalid.\");\r\n            return false;\r\n        }\r\n    }\r\n    \r\n    // Truncate so that defaultDir just contains the dir\r\n    pos[0] = _T('\\0');\r\n    \r\n    // Since the client doesn't allow multiple instances, we can just kick it off\r\n    // regardless of whether it's running or not.\r\n    HINSTANCE h = ShellExecute(\r\n        NULL, _T(\"open\"), acExe, _T(\"--tray\"), defaultDir, SW_SHOWNORMAL);\r\n        \r\n    if ( h <= reinterpret_cast<void*>( 32) ) // Error\r\n    {\r\n        // Invalid handle means it didn't launch\r\n        ostringstream os;\r\n        os << \"Failed launching Last.fm client. ShellExecute error: \" << h;\r\n        ReportStatus(-1, true, os.str());\r\n        return false;\r\n    }\r\n    \r\n    ReportStatus(-1, false, \"Launched Last.fm client.\");\r\n    \r\n    // Store time of launch\r\n    mLaunchTime = GetTickCount();\r\n    \r\n    return true;\r\n}\r\n\r\n/******************************************************************************\r\n    Start\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::Start(\r\n    string artist,\r\n\tstring albumArtist,\r\n    string track,\r\n    string album,\r\n    string mbId,\r\n    int    length,\r\n    string filename,\r\n    Encoding encoding)\r\n{\r\n    if (encoding != UTF_8)\r\n    {\r\n        ConvertToUTF8(artist, encoding);\r\n\t\tConvertToUTF8(albumArtist, encoding);\r\n        ConvertToUTF8(track, encoding);\r\n        ConvertToUTF8(album, encoding);\r\n        ConvertToUTF8(mbId, encoding);\r\n        ConvertToUTF8(filename, encoding);\r\n    }\r\n\r\n    ostringstream osCmd;\r\n    osCmd << \"START c=\" << mPluginId        << \"&\" <<\r\n                   \"a=\" << Escape(artist)   << \"&\" <<\r\n\t\t\t\t   \"d=\" << Escape(albumArtist)   << \"&\" <<\r\n                   \"t=\" << Escape(track)    << \"&\" <<\r\n                   \"b=\" << Escape(album)    << \"&\" <<\r\n                   \"m=\" << Escape(mbId)     << \"&\" <<\r\n                   \"l=\" << length           << \"&\" <<\r\n                   \"p=\" << Escape(filename) << endl;\r\n\r\n    string cmd = osCmd.str();\r\n\r\n    return SendToAS(cmd);\r\n}\r\n\r\n/******************************************************************************\r\n    Stop\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::Stop()\r\n{\r\n    ostringstream osCmd;\r\n    osCmd << \"STOP c=\" << mPluginId << endl;\r\n    string sCmd = osCmd.str();\r\n\r\n    return SendToAS(sCmd);\r\n}\r\n\r\n/******************************************************************************\r\n    Pause\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::Pause()\r\n{\r\n    ostringstream osCmd;\r\n    osCmd << \"PAUSE c=\" << mPluginId << endl;\r\n    string sCmd = osCmd.str();\r\n\r\n    return SendToAS(sCmd);\r\n}\r\n\r\n/******************************************************************************\r\n    Resume\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::Resume()\r\n{\r\n    ostringstream osCmd;\r\n    osCmd << \"RESUME c=\" << mPluginId << endl;\r\n    string sCmd = osCmd.str();\r\n\r\n    return SendToAS(sCmd);\r\n}\r\n\r\n// FIXME: give functions verb names to make it clear what they do\r\n/******************************************************************************\r\n    BootstrapComplete\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::BootstrapComplete( const WCHAR* username )\r\n{\r\n    char usernameUtf8[255];\r\n    usernameUtf8[EncodingUtils::UnicodeToUtf8( username, static_cast<int>( wcslen( username ) ), usernameUtf8, 254 )] = '\\0';\r\n    ostringstream osCmd;\r\n    osCmd << \"BOOTSTRAP c=\" << mPluginId << \"&\" << \"u=\" << usernameUtf8 << endl;\r\n\r\n    return SendToAS( osCmd.str() );\r\n}\r\n\r\n/******************************************************************************\r\n    GetVersion\r\n******************************************************************************/\r\nstring\r\nScrobSubmitter::GetVersion()\r\n{\r\n    return kVersion;\r\n}\r\n\r\n/******************************************************************************\r\n    GetLogPath\r\n******************************************************************************/\r\nstring\r\nScrobSubmitter::GetLogPath()\r\n{\r\n    // This might not work on Win98 and earlier but we're not officially\r\n    // supporting them anyway. Upgrading to IE5 will solve the problem.\r\n    char acPath[MAX_PATH];\r\n    HRESULT h = SHGetFolderPathA( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE,\r\n                                  NULL, 0, acPath );\r\n\tstd::string sPath;\r\n\tif ( h == S_OK )\r\n    {\r\n        sPath = acPath;\r\n\t\tsPath += \"\\\\Last.fm\\\\Client\";\r\n    }\r\n    else\r\n    {\r\n\t\tsPath = \"C:\\\\Last.fm\\\\Client\";\r\n    }\r\n\r\n    return sPath;\r\n}\r\n\r\n/******************************************************************************\r\n    GetLogPathW\r\n******************************************************************************/\r\nwstring\r\nScrobSubmitter::GetLogPathW()\r\n{\r\n    // This might not work on Win98 and earlier but we're not officially\r\n    // supporting them anyway. Upgrading to IE5 will solve the problem.\r\n    WCHAR acPath[MAX_PATH];\r\n    HRESULT h = SHGetFolderPathW( NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE,\r\n        NULL, 0, acPath );\r\n    std::wstring sPath;\r\n    if ( h == S_OK )\r\n    {\r\n        sPath = acPath;\r\n        sPath += L\"\\\\Last.fm\\\\Client\";\r\n    }\r\n    else\r\n    {\r\n        sPath = L\"C:\\\\Last.fm\\\\Client\";\r\n    }\r\n\r\n    return sPath;\r\n}\r\n\r\n/******************************************************************************\r\n    SendToAS\r\n******************************************************************************/\r\nint\r\nScrobSubmitter::SendToAS(\r\n    const std::string& cmd)\r\n{\r\n    if (mPluginId == \"\")\r\n    {\r\n        ReportStatus(-1, true,\r\n            \"Init hasn't been called with a plugin ID\");\r\n        return -1;\r\n    }\r\n\r\n    EnterCriticalSection(&mMutex);\r\n\r\n    // Push the cmd on the queue\r\n    mRequestQueue.push_back(make_pair(++mNextId, cmd));\r\n\r\n    // If queue was empty, signal socket thread\r\n    if (mRequestQueue.size() == 1)\r\n    {\r\n        SetEvent(mRequestAvailable);\r\n    }\r\n    \r\n    LeaveCriticalSection(&mMutex);\r\n    \r\n    return mNextId;\r\n}\r\n\r\n/******************************************************************************\r\n    SendToASThread\r\n******************************************************************************/\r\nvoid\r\nScrobSubmitter::SendToASThread()\r\n{\r\n    // By giving mRequestAvailable the lower index, it will take priority\r\n    // when calling WaitForMultipleObjects and both events are signalled.\r\n    HANDLE eventArray[2] = { mRequestAvailable, mExit };\r\n\r\n    while (mRequestQueue.size() > 0 || !mStopThread)\r\n    {\r\n        DWORD signalledHandle = WaitForMultipleObjects(\r\n            2, eventArray, FALSE, INFINITE);\r\n        \r\n        // Check if it's the exit event\r\n        if ((signalledHandle - WAIT_OBJECT_0) == 1) { continue; }\r\n\r\n        EnterCriticalSection(&mMutex);\r\n\r\n        // Pick first request from queue\r\n        pair<int, string> reqPair = mRequestQueue.front();\r\n        mRequestQueue.pop_front();\r\n\r\n        // This means we will eat all the requests in the queue before\r\n        // waiting again\r\n        if (mRequestQueue.size() == 0)\r\n        {\r\n            ResetEvent(mRequestAvailable);\r\n        }\r\n\r\n        LeaveCriticalSection(&mMutex);\r\n        \r\n        int nId = reqPair.first;\r\n        string& sCmd = reqPair.second;\r\n\r\n        #define RESPONSE_BUFFER_SIZE 1024\r\n        #define PIPE_TIMEOUT 3000   // ms\r\n\r\n        char responseBuffer[RESPONSE_BUFFER_SIZE];\r\n        DWORD bytesRead;\r\n\r\n        BOOL success = CallNamedPipeA(\r\n            mPipeName.data(), \r\n            (LPVOID) sCmd.data(), (DWORD) sCmd.size(),\r\n            responseBuffer, RESPONSE_BUFFER_SIZE, \r\n            &bytesRead,\r\n            PIPE_TIMEOUT);\r\n\r\n        if (success)\r\n        {\r\n            std::string sResponse(responseBuffer, bytesRead);\r\n            bool error = sResponse.substr(0, 2) != \"OK\";\r\n            ReportStatus(nId, error, sResponse);\r\n        }\r\n        else\r\n        {\r\n            // the only acceptable error is file not found \r\n            // (probably meaning the client is not running)\r\n            DWORD err = GetLastError();\r\n            if (err != ERROR_FILE_NOT_FOUND) \r\n            {\r\n                ReportStatus(nId, true, formatWin32Error(err));\r\n                break;\r\n            }\r\n        }\r\n\r\n    } // end while\r\n\r\n    _endthreadex( 0 );\r\n}\r\n\r\n/******************************************************************************\r\n    ConnectToAS\r\n******************************************************************************/\r\nbool\r\nScrobSubmitter::ConnectToAS(\r\n    int reqId)\r\n{\r\n    LPSTR cmdLine = GetCommandLineA();\r\n\r\n    ostringstream init;\r\n    init << \"INIT c=\"\r\n         << mPluginId\r\n         << \"&f=\"\r\n         << cmdLine\r\n         << endl;\r\n\r\n    SendToAS( init.str() );\r\n    return true;\r\n}\r\n\r\n/******************************************************************************\r\n    ReportStatus\r\n******************************************************************************/\r\nvoid\r\nScrobSubmitter::ReportStatus(\r\n    int reqId,\r\n    bool error,\r\n    const string& msg)\r\n{\r\n    if (!mStopThread && (mpReportStatus != NULL))\r\n    {\r\n        (*mpReportStatus)(reqId, error, msg, mpUserData);\r\n    }\r\n}    \r\n\r\n/******************************************************************************\r\n    ConvertToUTF8\r\n******************************************************************************/\r\nvoid\r\nScrobSubmitter::ConvertToUTF8(\r\n\tstring&  text,\r\n\tEncoding encoding)\r\n{\r\n    switch (encoding)\r\n    {\r\n        case ISO_8859_1:\r\n        {\r\n            // A UTF-8 string can be up to 4 times as big as the ANSI\r\n            size_t nUtf8MaxLen = text.size() * 4 + 1;\r\n            char* pcUtf8 = new char[nUtf8MaxLen];\r\n            EncodingUtils::AnsiToUtf8(text.c_str(),\r\n                                      pcUtf8,\r\n                                      static_cast<int>(nUtf8MaxLen));\r\n            text = pcUtf8;\r\n            delete[] pcUtf8;\r\n        }\r\n        break;\r\n        \r\n    }\r\n}\t\r\n\r\n/******************************************************************************\r\n    Escape\r\n******************************************************************************/\r\nstring&\r\nScrobSubmitter::Escape(\r\n    string& text)\r\n{\r\n    string::size_type nIdx = text.find(\"&\");\r\n    while (nIdx != string::npos)\r\n    {\r\n        text.replace(nIdx, 1, \"&&\");\r\n        nIdx = text.find(\"&\", nIdx + 2);\r\n    }\r\n\r\n    return text;\r\n}    \r\n\r\n"
  },
  {
    "path": "plugins/scrobsub/ScrobSubmitter.h",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \r\n * All rights reserved.\r\n *\r\n * Redistribution and use in source and binary forms, with or without\r\n * modification, are permitted provided that the following conditions are met:\r\n *     * Redistributions of source code must retain the above copyright\r\n *       notice, this list of conditions and the following disclaimer.\r\n *     * Redistributions in binary form must reproduce the above copyright\r\n *       notice, this list of conditions and the following disclaimer in the\r\n *       documentation and/or other materials provided with the distribution.\r\n *     * Neither the name of the <organization> nor the\r\n *       names of its contributors may be used to endorse or promote products\r\n *       derived from this software without specific prior written permission.\r\n *\r\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\r\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\r\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n */\r\n\r\n/*************************************************************************/ /**\r\n    \\mainpage ScrobSub\r\n \r\n    \\section intro_sec Introduction\r\n \r\n    Win32 library for writing media player plugins that submit listening data\r\n    to the Last.fm client.\r\n     \r\n    \\section install_sec Installation\r\n    \r\n    The library consists of seven source files, so the easiest way of\r\n    using them would be to simply include them in your project and compile\r\n    them alongside your other code. The only class with a public interface\r\n    is the ScrobSubmitter.\r\n    \r\n    Files needed:\r\n    \\li ScrobSubmitter.h\r\n    \\li ScrobSubmitter.cpp\r\n    \\li EncodingUtils.h\r\n    \\li EncodingUtils.cpp\r\n    \\li RegistryUtils.h\r\n    \\li RegistryUtils.cpp\r\n    \\li scrobSubPipeName.cpp\r\n\r\n    \\section dep_sec Dependencies\r\n\r\n******************************************************************************/\r\n\r\n#ifndef SCROBSUBMITTER_H\r\n#define SCROBSUBMITTER_H\r\n\r\n#include <string>\r\n#include <deque>\r\n#include <windows.h>\r\n\r\n/*************************************************************************/ /**\r\n    Class for submitting tracks to the Last.fm client. It communicates with\r\n    the client via a named pipe.\r\n    \r\n    To use it, call Init on player startup passing the required parameters.\r\n    This will launch the Last.fm client if it isn't already runnning and\r\n    initialise the socket communication and worker thread.\r\n    \r\n    Then simply call functions Start, Stop, Pause and Resume in response to\r\n    player events to communicate these events to the Last.fm client. They all\r\n    operate asynchronously, i.e. they will return straight away so as to\r\n    prevent hanging the calling thread if an operation takes some time. The \r\n    functions will return a request ID uniquely identifying the command just \r\n    sent. When the request is finished, the status callback will be called \r\n    with the ID as a parameter and a message of either \"OK\" or a description \r\n    of the error if one occurred.\r\n    \r\n    It's important to call Term at shutdown to clean up all resources properly.\r\n        \r\n    @author <erik@last.fm>\r\n******************************************************************************/\r\nclass ScrobSubmitter \r\n{\r\npublic:\r\n\r\n    /*********************************************************************/ /**\r\n        Callback function type for status reporting.\r\n\r\n        @param[in] reqId    The request ID the message is in regards to.\r\n        @param[in] error    True if an error occurred.\r\n        @param[in] msg      Status message.\r\n        @param[in] userData The user data passed to Init.\r\n    **************************************************************************/\r\n    typedef void (*StatusCallback)(\r\n        int  reqId,\r\n        bool error,\r\n        std::string msg,\r\n        void* userData);\r\n\r\n    /*********************************************************************/ /**\r\n        Text encoding used for track submissions.\r\n    **************************************************************************/\r\n    enum Encoding\r\n    {\r\n        ISO_8859_1, // standard Windows western codepage\r\n        UTF_8\r\n    };\r\n\r\n    /*********************************************************************/ /**\r\n        Constructor\r\n    **************************************************************************/\r\n\tScrobSubmitter();\r\n\r\n    /*********************************************************************/ /**\r\n        Destructor\r\n    **************************************************************************/\r\n\tvirtual\r\n\t~ScrobSubmitter();\r\n\r\n    /*********************************************************************/ /**\r\n        Call this to initialise the class. Must be called before any tracks\r\n        are submitted or things won't work. This function will also launch\r\n        Last.fm if it isn't running.\r\n        \r\n        @param[in] pluginId  Three-letter plugin code as assigned by Last.fm.\r\n                             Contact russ at last.fm to get one for your plugin.\r\n        @param[in] callback  Function pointer for reporting result status of\r\n                             asynchronous operations.\r\n        @param[in] userData  Pointer that will be passed back through the\r\n                             callback. Use for \"this\" pointer.\r\n    **************************************************************************/\r\n    void\r\n    Init(\r\n        const std::string& pluginId,\r\n        StatusCallback callback,\r\n        void* userData);\r\n\r\n    /*********************************************************************/ /**\r\n        Call this to terminate. Must be called in order for the  thread to be\r\n        shut down properly.\r\n    **************************************************************************/\r\n    void\r\n    Term();\r\n\r\n    /*********************************************************************/ /**\r\n        Sends a START command to client. All parameter strings are treated as\r\n        standard char strings.\r\n        \r\n        @param[in] artist   Name of artist.\r\n        @param[in] track    Name of track.\r\n        @param[in] album    Name of album.\r\n        @param[in] mbId     Musicbrainz ID if present.\r\n        @param[in] length   Length of track in seconds.\r\n        @param[in] filename Full path to the file on the disk.\r\n        @param[in] encoding Text encoding specifying how to interpret the\r\n                            characters in the strings passed in.\r\n\r\n        @return A unique request ID.\r\n    **************************************************************************/\r\n    int\r\n    Start(\r\n        std::string artist,\r\n\t\tstd::string albumArtist,\r\n        std::string track,\r\n        std::string album,\r\n        std::string mbId,\r\n        int         length,\r\n        std::string filename,\r\n        Encoding    encoding = UTF_8);\r\n\r\n    /*********************************************************************/ /**\r\n        Sends a STOP command to client. Call this both for stop and when a song\r\n        plays to the end.\r\n\r\n        @return A unique request ID.\r\n    **************************************************************************/\r\n    int\r\n    Stop();\r\n\r\n    /*********************************************************************/ /**\r\n        Sends a PAUSE command to client. Use this only for pause.\r\n\r\n        @return A unique request ID.\r\n    **************************************************************************/\r\n    int\r\n    Pause();\r\n\r\n    /*********************************************************************/ /**\r\n        Sends a RESUME command to client. Should only be used following a\r\n        preceding START-PAUSE sequence to resume a paused track.\r\n\r\n        @return A unique request ID.\r\n    **************************************************************************/\r\n    int\r\n    Resume();\r\n\r\n    /*********************************************************************/ /**\r\n        Get ScrobSub version.\r\n        \r\n        @return Version string.\r\n    **************************************************************************/\r\n    std::string\r\n    GetVersion();\r\n\r\n    /*********************************************************************/ /**\r\n        Returns a suitable directory for putting log files in. Normally\r\n        \"Documents and Settings/[user]/Local Settings/Application Data/\r\n        Last.fm/Client\".\r\n        \r\n        @return Path to log folder.\r\n    **************************************************************************/\r\n    static std::string\r\n    GetLogPath();\r\n\r\n    /*********************************************************************/ /**\r\n        Returns a suitable unicode directory for putting log files in. Normally\r\n        \"Documents and Settings/[user]/Local Settings/Application Data/\r\n        Last.fm/Client\".\r\n\r\n        @return unicode Path to log folder.\r\n    **************************************************************************/\r\n    static std::wstring\r\n        GetLogPathW();\r\n\r\n    int\r\n    BootstrapComplete( const WCHAR* username );\r\n\r\nprivate:\r\n\r\n    /**************************************************************************\r\n        Copy ctor private because a CRITICAL_SECTION cannot be copied.\r\n    **************************************************************************/\r\n\tScrobSubmitter(\r\n\t    const ScrobSubmitter&);\r\n\r\n    /**************************************************************************\r\n        Opens the Last.fm client.\r\n    **************************************************************************/\r\n    bool\r\n\tLaunchClient();\r\n\r\n    /**************************************************************************\r\n        Sends the command cmd.\r\n    **************************************************************************/\r\n    int\r\n\tSendToAS(\r\n\t    const std::string& cmd);\r\n\r\n    /**************************************************************************\r\n        Thread starter.\r\n    **************************************************************************/\r\n    static unsigned __stdcall\r\n    SendToASThreadMain(\r\n        LPVOID p)\r\n\t{ reinterpret_cast<ScrobSubmitter*>(p)->SendToASThread(); return 0; }\r\n\t \r\n    /**************************************************************************\r\n        Worker thread function.\r\n    **************************************************************************/\r\n    void\r\n\tSendToASThread();\r\n\r\n    /**************************************************************************\r\n        Connects to AS. Returns true if successful.\r\n    **************************************************************************/\r\n    bool\r\n    ConnectToAS(\r\n        int reqId);\r\n\r\n    /**************************************************************************\r\n        Reports status back to caller through callback.\r\n    **************************************************************************/\r\n    void\r\n    ReportStatus(\r\n        int reqId,\r\n        bool error,\r\n        const std::string& msg);\r\n\r\n    /**************************************************************************\r\n        Converts the passed in string to UTF-8 from the encoding specified\r\n        as the second parameter.\r\n    **************************************************************************/\r\n    void\r\n\tConvertToUTF8(\r\n\t    std::string& text,\r\n\t    Encoding encoding);\r\n\r\n    /*********************************************************************/ /**\r\n        Escapes &s with &&s. Return a reference to the same string that was\r\n        passed in but escaped.\r\n    **************************************************************************/\r\n    std::string&\r\n\tEscape(\r\n\t    std::string& text);\r\n\r\n\r\n    std::string      mPluginId;\r\n    \r\n    int              mNextId;\r\n    std::deque<std::pair<int, std::string> > mRequestQueue;\r\n\r\n    HANDLE           mSocketThread;\r\n    HANDLE           mRequestAvailable;\r\n    HANDLE           mExit;\r\n    CRITICAL_SECTION mMutex;\r\n    bool             mStopThread;\r\n    std::string      mPipeName;\r\n\r\n    StatusCallback   mpReportStatus;\r\n    void*            mpUserData;\r\n\r\n    DWORD            mLaunchTime;\r\n    \r\n    friend class BootStrap; // so that we can use the ReportStatus function\r\n};\r\n\r\n#endif // SCROBSUBMITTER_H\r\n"
  },
  {
    "path": "plugins/scrobsub/StdString.h",
    "content": "// =============================================================================\r\n//  FILE:  StdString.h\r\n//  AUTHOR:\tJoe O'Leary (with outside help noted in comments)\r\n//\r\n//\r\n//\t\tIf you find any bugs int his code, please let me know:\r\n//\r\n//\t\t\t\tjmoleary@earthlink.net\r\n//\t\t\t\thttp://www.joeo.net/stdstring.htm (a bit outdated)\r\n//\r\n//      The latest version of this code should always be available at the\r\n//      following link:\r\n//\r\n//              http://www.joeo.net/code/StdString.zip (Dec 6, 2003)\r\n//\r\n//\r\n//  REMARKS:\r\n//\t\tThis header file declares the CStdStr template.  This template derives\r\n//\t\tthe Standard C++ Library basic_string<> template and add to it the\r\n//\t\tthe following conveniences:\r\n//\t\t\t- The full MFC CString set of functions (including implicit cast)\r\n//\t\t\t- writing to/reading from COM IStream interfaces\r\n//\t\t\t- Functional objects for use in STL algorithms\r\n//\r\n//\t\tFrom this template, we intstantiate two classes:  CStdStringA and\r\n//\t\tCStdStringW.  The name \"CStdString\" is just a #define of one of these,\r\n//\t\tbased upone the UNICODE macro setting\r\n//\r\n//\t\tThis header also declares our own version of the MFC/ATL UNICODE-MBCS\r\n//\t\tconversion macros.  Our version looks exactly like the Microsoft's to\r\n//\t\tfacilitate portability.\r\n//\r\n//\tNOTE:\r\n//\t\tIf you you use this in an MFC or ATL build, you should include either\r\n//\t\tafx.h or atlbase.h first, as appropriate.\r\n//\r\n//\tPEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS:\r\n//\r\n//\t\tSeveral people have helped me iron out problems and othewise improve\r\n//\t\tthis class.  OK, this is a long list but in my own defense, this code\r\n//\t\thas undergone two major rewrites.  Many of the improvements became\r\n//\t\tnecessary after I rewrote the code as a template.  Others helped me\r\n//\t\timprove the CString facade.\r\n//\r\n//\t\tAnyway, these people are (in chronological order):\r\n//\r\n//\t\t\t- Pete the Plumber (???)\r\n//\t\t\t- Julian Selman\r\n//\t\t\t- Chris (of Melbsys)\r\n//\t\t\t- Dave Plummer\r\n//\t\t\t- John C Sipos\r\n//\t\t\t- Chris Sells\r\n//\t\t\t- Nigel Nunn\r\n//\t\t\t- Fan Xia\r\n//\t\t\t- Matthew Williams\r\n//\t\t\t- Carl Engman\r\n//\t\t\t- Mark Zeren\r\n//\t\t\t- Craig Watson\r\n//\t\t\t- Rich Zuris\r\n//\t\t\t- Karim Ratib\r\n//\t\t\t- Chris Conti\r\n//\t\t\t- Baptiste Lepilleur\r\n//\t\t\t- Greg Pickles\r\n//\t\t\t- Jim Cline\r\n//\t\t\t- Jeff Kohn\r\n//\t\t\t- Todd Heckel\r\n//\t\t\t- Ullrich Pollhne\r\n//\t\t\t- Joe Vitaterna\r\n//\t\t\t- Joe Woodbury\r\n//\t\t\t- Aaron (no last name)\r\n//\t\t\t- Joldakowski (???)\r\n//\t\t\t- Scott Hathaway\r\n//\t\t\t- Eric Nitzche\r\n//\t\t\t- Pablo Presedo\r\n//\t\t\t- Farrokh Nejadlotfi\r\n//\t\t\t- Jason Mills\r\n//\t\t\t- Igor Kholodov\r\n//\t\t\t- Mike Crusader\r\n//\t\t\t- John James\r\n//\t\t\t- Wang Haifeng\r\n//\t\t\t- Tim Dowty\r\n//          - Arnt Witteveen\r\n//          - Glen Maynard\r\n//          - Paul DeMarco\r\n//          - Bagira (full name?)\r\n//          - Ronny Schulz\r\n//          - Jakko Van Hunen\r\n//\t\t\t- Charles Godwin\r\n//\t\t\t- Henk Demper\r\n//\t\t\t- Greg Marr\r\n//\t\t\t- Bill Carducci\r\n//\t\t\t- Brian Groose\r\n//\t\t\t- MKingman\r\n//\r\n//\tREVISION HISTORY\r\n//\r\n//\t  2004-APR-22 - A big, big thank you to \"MKingman\" (whoever you are) for\r\n//\t\t\t\t\tfinally spotting a silly little error in StdCodeCvt that\r\n//\t\t\t\t\thas been causing me (and users of CStdString) problems for\r\n//\t\t\t\t\tyears in some relatively rare conversions.  I had reversed\r\n//\t\t\t\t\ttwo length arguments. \r\n//\r\n//    2003-NOV-24 - Thanks to a bunch of people for helping me clean up many\r\n//\t\t\t\t\tcompiler warnings (and yes, even a couple of actual compiler\r\n//\t\t\t\t\terrors).  These include Henk Demper for figuring out how\r\n//\t\t\t\t\tto make the Intellisense work on with CStdString on VC6,\r\n//\t\t\t\t\tsomething I was never able to do.  Greg Marr pointed out\r\n//\t\t\t\t\ta compiler warning about an unreferenced symbol and a\r\n//\t\t\t\t\tproblem with my version of Load in MFC builds.  Bill\r\n//\t\t\t\t\tCarducci took a lot of time with me to help me figure out\r\n//\t\t\t\t\twhy some implementations of the Standard C++ Library were\r\n//\t\t\t\t\treturning error codes for apparently successful conversions\r\n//\t\t\t\t\tbetween ASCII and UNICODE.  Finally thanks to Brian Groose\r\n//\t\t\t\t\tfor helping me fix compiler signed unsigned warnings in\r\n//\t\t\t\t\tseveral functions.\r\n//\r\n//    2003-JUL-10 - Thanks to Charles Godwin for making me realize my 'FmtArg'\r\n//\t\t\t\t\tfixes had inadvertently broken the DLL-export code (which is\r\n//                  normally commented out.  I had to move it up higher.  Also\r\n//\t\t\t\t\tthis helped me catch a bug in ssicoll that would prevent\r\n//                  compilation, otherwise.\r\n//\r\n//    2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste\r\n//                  bug in one of the overloads of FmtArg.\r\n//\r\n//    2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes\r\n//                  to help CStdString build on SGI and for pointing out an\r\n//                  error in placement of my preprocessor macros for ssfmtmsg.\r\n//\r\n//    2002-NOV-26 - Thanks to Bagira for pointing out that my implementation of\r\n//                  SpanExcluding was not properly handling the case in which\r\n//                  the string did NOT contain any of the given characters\r\n//\r\n//    2002-OCT-21 - Many thanks to Paul DeMarco who was invaluable in helping me\r\n//                  get this code working with Borland's free compiler as well\r\n//                  as the Dev-C++ compiler (available free at SourceForge).\r\n//\r\n//    2002-SEP-13 - Thanks to Glen Maynard who helped me get rid of some loud\r\n//                  but harmless warnings that were showing up on g++.  Glen\r\n//                  also pointed out that some pre-declarations of FmtArg<>\r\n//                  specializations were unnecessary (and no good on G++)\r\n//\r\n//    2002-JUN-26 - Thanks to Arnt Witteveen for pointing out that I was using\r\n//                  static_cast<> in a place in which I should have been using\r\n//                  reinterpret_cast<> (the ctor for unsigned char strings).\r\n//                  That's what happens when I don't unit-test properly!\r\n//                  Arnt also noticed that CString was silently correcting the\r\n//                  'nCount' argument to Left() and Right() where CStdString was\r\n//                  not (and crashing if it was bad).  That is also now fixed!\r\n//\r\n//\t  2002-FEB-25 - Thanks to Tim Dowty for pointing out (and giving me the fix\r\n//\t\t\t\t\tfor) a conversion problem with non-ASCII MBCS characters.\r\n//\t\t\t\t\tCStdString is now used in my favorite commercial MP3 player!\r\n//\r\n//\t  2001-DEC-06 - Thanks to Wang Haifeng for spotting a problem in one of the\r\n//\t\t\t\t\tassignment operators (for _bstr_t) that would cause compiler\r\n//\t\t\t\t\terrors when refcounting protection was turned off.\r\n//\r\n//\t  2001-NOV-27 - Remove calls to operator!= which involve reverse_iterators\r\n//\t\t\t\t\tdue to a conflict with the rel_ops operator!=.  Thanks to\r\n//\t\t\t\t\tJohn James for pointing this out.\r\n//\r\n//    2001-OCT-29 - Added a minor range checking fix for the Mid function to\r\n//\t\t\t\t\tmake it as forgiving as CString's version is.  Thanks to\r\n//\t\t\t\t\tIgor Kholodov for noticing this.  \r\n//\t\t\t\t  - Added a specialization of std::swap for CStdString.  Thanks\r\n//\t\t\t\t\tto Mike Crusader for suggesting this!  It's commented out\r\n//\t\t\t\t\tbecause you're not supposed to inject your own code into the\r\n//\t\t\t\t\t'std' namespace.  But if you don't care about that, it's\r\n//\t\t\t\t\tthere if you want it\r\n//\t\t\t\t  - Thanks to Jason Mills for catching a case where CString was\r\n//\t\t\t\t\tmore forgiving in the Delete() function than I was.\r\n//\r\n//\t  2001-JUN-06 - I was violating the Standard name lookup rules stated\r\n//\t\t\t\t\tin [14.6.2(3)].  None of the compilers I've tried so\r\n//\t\t\t\t\tfar apparently caught this but HP-UX aCC 3.30 did.  The\r\n//\t\t\t\t\tfix was to add 'this->' prefixes in many places.\r\n//\t\t\t\t\tThanks to Farrokh Nejadlotfi for this!\r\n//\r\n//\t  2001-APR-27 - StreamLoad was calculating the number of BYTES in one\r\n//\t\t\t\t\tcase, not characters.  Thanks to Pablo Presedo for this.\r\n//\r\n//    2001-FEB-23 - Replace() had a bug which caused infinite loops if the\r\n//\t\t\t\t\tsource string was empty.  Fixed thanks to Eric Nitzsche.\r\n//\r\n//    2001-FEB-23 - Scott Hathaway was a huge help in providing me with the\r\n//\t\t\t\t\tability to build CStdString on Sun Unix systems.  He\r\n//\t\t\t\t\tsent me detailed build reports about what works and what\r\n//\t\t\t\t\tdoes not.  If CStdString compiles on your Unix box, you\r\n//\t\t\t\t\tcan thank Scott for it.\r\n//\r\n//\t  2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do a\r\n//\t\t\t\t\trange check as CString's does.  Now fixed -- thanks!\r\n//\r\n//\t  2000-NOV-07 - Aaron pointed out that I was calling static member\r\n//\t\t\t\t\tfunctions of char_traits via a temporary.  This was not\r\n//\t\t\t\t\ttechnically wrong, but it was unnecessary and caused\r\n//\t\t\t\t\tproblems for poor old buggy VC5.  Thanks Aaron!\r\n//\r\n//\t  2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match\r\n//\t\t\t\t\twhat the CString::Find code really ends up doing.   I was\r\n//\t\t\t\t\ttrying to match the docs.  Now I match the CString code\r\n//\t\t\t\t  - Joe also caught me truncating strings for GetBuffer() calls\r\n//\t\t\t\t\twhen the supplied length was less than the current length.\r\n//\r\n//\t  2000-MAY-25 - Better support for STLPORT's Standard library distribution\r\n//\t\t\t\t  - Got rid of the NSP macro - it interfered with Koenig lookup\r\n//\t\t\t\t  - Thanks to Joe Woodbury for catching a TrimLeft() bug that\r\n//\t\t\t\t\tI introduced in January.  Empty strings were not getting\r\n//\t\t\t\t\ttrimmed\r\n//\r\n//\t  2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind\r\n//\t\t\t\t\tis supposed to be a const function.\r\n//\r\n//\t  2000-MAR-07 - Thanks to Ullrich Pollhne for catching a range bug in one\r\n//\t\t\t\t\tof the overloads of assign.\r\n//\r\n//    2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior!\r\n//\t\t\t\t\tThanks to Todd Heckel for helping out with this.\r\n//\r\n//\t  2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the\r\n//\t\t\t\t\tTrim() function more efficient.\r\n//\t\t\t\t  - Thanks to Jeff Kohn for prompting me to find and fix a typo\r\n//\t\t\t\t\tin one of the addition operators that takes _bstr_t.\r\n//\t\t\t\t  - Got rid of the .CPP file -  you only need StdString.h now!\r\n//\r\n//\t  1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem\r\n//\t\t\t\t\twith my implementation of CStdString::FormatV in which\r\n//\t\t\t\t\tresulting string might not be properly NULL terminated.\r\n//\r\n//\t  1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment\r\n//\t\t\t\t\tbug that MS has not fixed.  CStdString did nothing to fix\r\n//\t\t\t\t\tit either but it does now!  The bug was: create a string\r\n//\t\t\t\t\tlonger than 31 characters, get a pointer to it (via c_str())\r\n//\t\t\t\t\tand then assign that pointer to the original string object.\r\n//\t\t\t\t\tThe resulting string would be empty.  Not with CStdString!\r\n//\r\n//\t  1999-OCT-06 - BufferSet was erasing the string even when it was merely\r\n//\t\t\t\t\tsupposed to shrink it.  Fixed.  Thanks to Chris Conti.\r\n//\t\t\t\t  - Some of the Q172398 fixes were not checking for assignment-\r\n//\t\t\t\t\tto-self.  Fixed.  Thanks to Baptiste Lepilleur.\r\n//\r\n//\t  1999-AUG-20 - Improved Load() function to be more efficient by using \r\n//\t\t\t\t\tSizeOfResource().  Thanks to Rich Zuris for this.\r\n//\t\t\t\t  - Corrected resource ID constructor, again thanks to Rich.\r\n//\t\t\t\t  - Fixed a bug that occurred with UNICODE characters above\r\n//\t\t\t\t\tthe first 255 ANSI ones.  Thanks to Craig Watson. \r\n//\t\t\t\t  - Added missing overloads of TrimLeft() and TrimRight().\r\n//\t\t\t\t\tThanks to Karim Ratib for pointing them out\r\n//\r\n//\t  1999-JUL-21 - Made all calls to GetBuf() with no args check length first.\r\n//\r\n//\t  1999-JUL-10 - Improved MFC/ATL independence of conversion macros\r\n//\t\t\t\t  - Added SS_NO_REFCOUNT macro to allow you to disable any\r\n//\t\t\t\t\treference-counting your basic_string<> impl. may do.\r\n//\t\t\t\t  - Improved ReleaseBuffer() to be as forgiving as CString.\r\n//\t\t\t\t\tThanks for Fan Xia for helping me find this and to\r\n//\t\t\t\t\tMatthew Williams for pointing it out directly.\r\n//\r\n//\t  1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in\r\n//\t\t\t\t\tToLower/ToUpper.  They should call GetBuf() instead of\r\n//\t\t\t\t\tdata() in order to ensure the changed string buffer is not\r\n//\t\t\t\t\treference-counted (in those implementations that refcount).\r\n//\r\n//\t  1999-JUL-01 - Added a true CString facade.  Now you can use CStdString as\r\n//\t\t\t\t\ta drop-in replacement for CString.  If you find this useful,\r\n//\t\t\t\t\tyou can thank Chris Sells for finally convincing me to give\r\n//\t\t\t\t\tin and implement it.\r\n//\t\t\t\t  - Changed operators << and >> (for MFC CArchive) to serialize\r\n//\t\t\t\t\tEXACTLY as CString's do.  So now you can send a CString out\r\n//\t\t\t\t\tto a CArchive and later read it in as a CStdString.   I have\r\n//\t\t\t\t\tno idea why you would want to do this but you can. \r\n//\r\n//\t  1999-JUN-21 - Changed the CStdString class into the CStdStr template.\r\n//\t\t\t\t  - Fixed FormatV() to correctly decrement the loop counter.\r\n//\t\t\t\t\tThis was harmless bug but a bug nevertheless.  Thanks to\r\n//\t\t\t\t\tChris (of Melbsys) for pointing it out\r\n//\t\t\t\t  - Changed Format() to try a normal stack-based array before\r\n//\t\t\t\t\tusing to _alloca().\r\n//\t\t\t\t  - Updated the text conversion macros to properly use code\r\n//\t\t\t\t\tpages and to fit in better in MFC/ATL builds.  In other\r\n//\t\t\t\t\twords, I copied Microsoft's conversion stuff again. \r\n//\t\t\t\t  - Added equivalents of CString::GetBuffer, GetBufferSetLength\r\n//\t\t\t\t  - new sscpy() replacement of CStdString::CopyString()\r\n//\t\t\t\t  - a Trim() function that combines TrimRight() and TrimLeft().\r\n//\r\n//\t  1999-MAR-13 - Corrected the \"NotSpace\" functional object to use _istpace()\r\n//\t\t\t\t\tinstead of _isspace()   Thanks to Dave Plummer for this.\r\n//\r\n//\t  1999-FEB-26 - Removed errant line (left over from testing) that #defined\r\n//\t\t\t\t\t_MFC_VER.  Thanks to John C Sipos for noticing this.\r\n//\r\n//\t  1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that\r\n//\t\t\t\t\tcaused infinite recursion and stack overflow\r\n//\t\t\t\t  - Added member functions to simplify the process of\r\n//\t\t\t\t\tpersisting CStdStrings to/from DCOM IStream interfaces \r\n//\t\t\t\t  - Added functional objects (e.g. StdStringLessNoCase) that\r\n//\t\t\t\t\tallow CStdStrings to be used as keys STL map objects with\r\n//\t\t\t\t\tcase-insensitive comparison \r\n//\t\t\t\t  - Added array indexing operators (i.e. operator[]).  I\r\n//\t\t\t\t\toriginally assumed that these were unnecessary and would be\r\n//\t\t\t\t\tinherited from basic_string.  However, without them, Visual\r\n//\t\t\t\t\tC++ complains about ambiguous overloads when you try to use\r\n//\t\t\t\t\tthem.  Thanks to Julian Selman to pointing this out. \r\n//\r\n//\t  1998-FEB-?? - Added overloads of assign() function to completely account\r\n//\t\t\t\t\tfor Q172398 bug.  Thanks to \"Pete the Plumber\" for this\r\n//\r\n//\t  1998-FEB-?? - Initial submission\r\n//\r\n// COPYRIGHT:\r\n//\t\t2002 Joseph M. O'Leary.  This code is 100% free.  Use it anywhere you\r\n//      want.  Rewrite it, restructure it, whatever.  If you can write software\r\n//      that makes money off of it, good for you.  I kinda like capitalism. \r\n//      Please don't blame me if it causes your $30 billion dollar satellite\r\n//      explode in orbit.  If you redistribute it in any form, I'd appreciate it\r\n//      if you would leave this notice here.\r\n// =============================================================================\r\n\r\n// Avoid multiple inclusion the VC++ way,\r\n// Turn off browser references\r\n// Turn off unavoidable compiler warnings\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER > 1100)\r\n\t#pragma once\r\n\t#pragma component(browser, off, references, \"CStdString\")\r\n\t#pragma warning (disable : 4290) // C++ Exception Specification ignored\r\n\t#pragma warning (disable : 4127) // Conditional expression is constant\r\n\t#pragma warning (disable : 4097) // typedef name used as synonym for class name\r\n#endif\r\n\r\n// Borland warnings to turn off\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option push -w-inl\r\n//\t#pragma warn -inl   // Turn off inline function warnings\r\n#endif\r\n\r\n#ifndef STDSTRING_H\r\n#define STDSTRING_H\r\n\r\n// SS_IS_INTRESOURCE\r\n// -----------------\r\n//\t\tA copy of IS_INTRESOURCE from VC7.  Because old VC6 version of winuser.h\r\n//\t\tdoesn't have this.\r\n\r\n#define SS_IS_INTRESOURCE\r\n\r\n#if !defined (SS_ANSI) && defined(_MSC_VER)\r\n\t#undef SS_IS_INTRESOURCE\r\n\t#if defined(_WIN64)\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned __int64)(_r) >> 16) == 0)\r\n\t#else\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned long)(_r) >> 16) == 0)\r\n\t#endif\r\n#endif\r\n\r\n\r\n// MACRO: SS_UNSIGNED\r\n// ------------------\r\n//      This macro causes the addition of a constructor and assignment operator\r\n//      which take unsigned characters.  CString has such functions and in order\r\n//      to provide maximum CString-compatability, this code needs them as well.\r\n//      In practice you will likely never need these functions...\r\n\r\n//#define SS_UNSIGNED\r\n\r\n#ifdef SS_ALLOW_UNSIGNED_CHARS\r\n\t#define SS_UNSIGNED\r\n#endif\r\n\r\n// MACRO: SS_SAFE_FORMAT\r\n// ---------------------\r\n//      This macro provides limited compatability with a questionable CString\r\n//      \"feature\".  You can define it in order to avoid a common problem that\r\n//      people encounter when switching from CString to CStdString.\r\n//\r\n//      To illustrate the problem -- With CString, you can do this:\r\n//\r\n//          CString sName(\"Joe\");\r\n//          CString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // WORKS!\r\n//\r\n//      However if you were to try this with CStdString, your program would\r\n//      crash.\r\n//\r\n//          CStdString sName(\"Joe\");\r\n//          CStdString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // CRASHES!\r\n//\r\n//      You must explicitly call c_str() or cast the object to the proper type\r\n//\r\n//          sTmp.Format(\"My name is %s\", sName.c_str());            // WORKS!\r\n//          sTmp.Format(\"My name is %s\", static_cast<PCSTR>(sName));// WORKS!\r\n//          sTmp.Format(\"My name is %s\", (PCSTR)sName);// WORKS!\r\n//\r\n//      This is because it is illegal to pass anything but a POD type as a\r\n//      variadic argument to a variadic function (i.e. as one of the \"...\"\r\n//      arguments).  The type const char* is a POD type.  The type CStdString\r\n//      is not.  Of course, neither is the type CString, but CString lets you do\r\n//      it anyway due to the way they laid out the class in binary.  I have no\r\n//      control over this in CStdString since I derive from whatever\r\n//      implementation of basic_string is available.\r\n//\r\n//      However if you have legacy code (which does this) that you want to take\r\n//      out of the MFC world and you don't want to rewrite all your calls to\r\n//      Format(), then you can define this flag and it will no longer crash.\r\n//\r\n//      Note however that this ONLY works for Format(), not sprintf, fprintf, \r\n//      etc.  If you pass a CStdString object to one of those functions, your\r\n//      program will crash.  Not much I can do to get around this, short of\r\n//      writing substitutes for those functions as well.\r\n\r\n#define SS_SAFE_FORMAT  // use new template style Format() function\r\n\r\n\r\n// MACRO: SS_NO_IMPLICIT_CAST\r\n// --------------------------\r\n//      Some people don't like the implicit cast to const char* (or rather to\r\n//      const CT*) that CStdString (and MFC's CString) provide.  That was the\r\n//      whole reason I created this class in the first place, but hey, whatever\r\n//      bakes your cake.  Just #define this macro to get rid of the the implicit\r\n//      cast.\r\n\r\n//#define SS_NO_IMPLICIT_CAST // gets rid of operator const CT*()\r\n\r\n\r\n// MACRO: SS_NO_REFCOUNT\r\n// ---------------------\r\n//\t\tturns off reference counting at the assignment level.  Only needed\r\n//\t\tfor the version of basic_string<> that comes with Visual C++ versions\r\n//\t\t6.0 or earlier, and only then in some heavily multithreaded scenarios.\r\n//\t\tUncomment it if you feel you need it.\r\n\r\n//#define SS_NO_REFCOUNT\r\n\r\n// MACRO: SS_WIN32\r\n// ---------------\r\n//      When this flag is set, we are building code for the Win32 platform and\r\n//      may use Win32 specific functions (such as LoadString).  This gives us\r\n//      a couple of nice extras for the code.\r\n//\r\n//      Obviously, Microsoft's is not the only compiler available for Win32 out\r\n//      there.  So I can't just check to see if _MSC_VER is defined to detect\r\n//      if I'm building on Win32.  So for now, if you use MS Visual C++ or\r\n//      Borland's compiler, I turn this on.  Otherwise you may turn it on\r\n//      yourself, if you prefer\r\n#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WIN32)\r\n    #define SS_WIN32\r\n#endif\r\n\r\n// MACRO: SS_ANSI\r\n// --------------\r\n//      When this macro is defined, the code attempts only to use ANSI/ISO\r\n//      standard library functions to do it's work.  It will NOT attempt to use\r\n//      any Win32 of Visual C++ specific functions -- even if they are\r\n//      available.  You may define this flag yourself to prevent any Win32\r\n//      of VC++ specific functions from being called. \r\n\r\n// If we're not on Win32, we MUST use an ANSI build\r\n\r\n#ifndef SS_WIN32\r\n    #if !defined(SS_NO_ANSI)\r\n        #define SS_ANSI\r\n    #endif\r\n#endif\r\n\r\n// MACRO: SS_ALLOCA\r\n// ----------------\r\n//      Some implementations of the Standard C Library have a non-standard\r\n//      function known as alloca().  This functions allows one to allocate a\r\n//      variable amount of memory on the stack.  It is needed to implement\r\n//      the ASCII/MBCS conversion macros.\r\n//\r\n//      I wanted to find some way to determine automatically if alloca() is\r\n//\t\tavailable on this platform via compiler flags but that is asking for\r\n//\t\ttrouble.  The crude test presented here will likely need fixing on\r\n//\t\tother platforms.  Therefore I'll leave it up to you to fiddle with\r\n//\t\tthis test to determine if it exists.  Just make sure SS_ALLOCA is or\r\n//\t\tis not defined as appropriate and you control this feature.\r\n\r\n#if defined(_MSC_VER) && !defined(SS_ANSI)\r\n\t#define SS_ALLOCA\r\n#endif\r\n\r\n// MACRO: SS_MBCS\r\n// --------------\r\n//\t\tSetting this macro means you are using MBCS characters.  In MSVC\r\n//\t\tbuilds, this macro gets set automatically by detection of the\r\n//\t\tpreprocessor flag _MBCS.  For other platforms you may set it manually\r\n//\t\tif you wish.  The only effect it currently has is to cause the\r\n//\t\tallocation of more space for wchar_t --> char conversions.\r\n//\t\tNote that MBCS does not mean UNICODE.\r\n//\r\n//\t#define SS_MBCS\r\n//\r\n#ifdef _MBCS\r\n\t#define SS_MBCS\r\n#endif\r\n\r\n\r\n\r\n// Compiler Error regarding _UNICODE and UNICODE\r\n// -----------------------------------------------\r\n// Microsoft header files are screwy.  Sometimes they depend on a preprocessor \r\n// flag named \"_UNICODE\".  Other times they check \"UNICODE\" (note the lack of\r\n// leading underscore in the second version\".  In several places, they silently\r\n// \"synchronize\" these two flags this by defining one of the other was defined. \r\n// In older version of this header , I used to try to do the same thing. \r\n//\r\n// However experience has taught me that this is a bad idea.  You get weird\r\n// compiler errors that seem to indicate things like LPWSTR and LPTSTR not being\r\n// equivalent in UNICODE builds, stuff like that (when they MUST be in a proper\r\n// UNICODE  build).  You end up scratching your head and saying, \"But that HAS\r\n// to compile!\".\r\n//\r\n// So what should you do if you get this error?\r\n//\r\n// Make sure that both macros (_UNICODE and UNICODE) are defined before this\r\n// file is included.  You can do that by either\r\n//\r\n//\t\ta) defining both yourself before any files get included\r\n//\t\tb) including the proper MS headers in the proper order\r\n//\t\tc) including this file before any other file, uncommenting\r\n//\t\t   the #defines below, and commenting out the #errors\r\n//\r\n//\tPersonally I recommend solution a) but it's your call.\r\n\r\n#ifdef _MSC_VER\r\n\t#if defined (_UNICODE) && !defined (UNICODE)\r\n\t\t#error UNICODE defined  but not UNICODE\r\n\t//\t#define UNICODE  // no longer silently fix this\r\n\t#endif\r\n\t#if defined (UNICODE) && !defined (_UNICODE)\r\n\t\t#error Warning, UNICODE defined  but not _UNICODE\r\n\t//\t#define _UNICODE  // no longer silently fix this\r\n\t#endif\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// MIN and MAX.  The Standard C++ template versions go by so many names (at\r\n// at least in the MS implementation) that you never know what's available \r\n// -----------------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline const Type& SSMIN(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 < arg1 ? arg2 : arg1;\r\n}\r\ntemplate<class Type>\r\ninline const Type& SSMAX(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 > arg1 ? arg2 : arg1;\r\n}\r\n\r\n// If they have not #included W32Base.h (part of my W32 utility library) then\r\n// we need to define some stuff.  Otherwise, this is all defined there.\r\n\r\n#if !defined(W32BASE_H)\r\n\r\n\t// If they want us to use only standard C++ stuff (no Win32 stuff)\r\n\r\n\t#ifdef SS_ANSI\r\n\r\n\t\t// On Win32 we have TCHAR.H so just include it.  This is NOT violating\r\n        // the spirit of SS_ANSI as we are not calling any Win32 functions here.\r\n        \r\n\t\t#ifdef SS_WIN32\r\n\r\n\t\t\t#include <TCHAR.H>\r\n\t\t\t#include <WTYPES.H>\r\n\t\t\t#ifndef STRICT\r\n\t\t\t\t#define STRICT\r\n\t\t\t#endif\r\n\r\n        // ... but on non-Win32 platforms, we must #define the types we need.\r\n\r\n\t\t#else\r\n\r\n\t\t\ttypedef const char*\t\tPCSTR;\r\n\t\t\ttypedef char*\t\t\tPSTR;\r\n\t\t\ttypedef const wchar_t*\tPCWSTR;\r\n\t\t\ttypedef wchar_t*\t\tPWSTR;\r\n\t\t\t#ifdef UNICODE\r\n\t\t\t\ttypedef wchar_t\t\tTCHAR;\r\n\t\t\t#else\r\n\t\t\t\ttypedef char\t\tTCHAR;\r\n\t\t\t#endif\r\n\t\t\ttypedef wchar_t\t\t\tOLECHAR;\r\n\r\n\t\t#endif\t// #ifndef _WIN32\r\n\r\n\r\n\t\t// Make sure ASSERT and verify are defined using only ANSI stuff\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <assert.h>\r\n\t\t\t#define ASSERT(f) assert((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#else // ...else SS_ANSI is NOT defined\r\n\r\n\t\t#include <TCHAR.H>\r\n\t\t#include <WTYPES.H>\r\n\t\t#ifndef STRICT\r\n\t\t\t#define STRICT\r\n\t\t#endif\r\n\r\n\t\t// Make sure ASSERT and verify are defined\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <crtdbg.h>\r\n\t\t\t#define ASSERT(f) _ASSERTE((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#endif // #ifdef SS_ANSI\r\n\r\n\t#ifndef UNUSED\r\n\t\t#define UNUSED(x) x\r\n\t#endif\r\n\r\n#endif // #ifndef W32BASE_H\r\n\r\n// Standard headers needed\r\n\r\n#include <string>\t\t\t// basic_string\r\n#include <algorithm>\t\t// for_each, etc.\r\n#include <functional>\t\t// for StdStringLessNoCase, et al\r\n#include <locale>\t\t// for various facets\r\n\r\n// If this is a recent enough version of VC include comdef.h, so we can write\r\n// member functions to deal with COM types & compiler support classes e.g.\r\n// _bstr_t\r\n\r\n#if defined (_MSC_VER) && (_MSC_VER >= 1100)\r\n\t#include <comdef.h>\r\n\t#define SS_INC_COMDEF\t\t// signal that we #included MS comdef.h file\r\n\t#define STDSTRING_INC_COMDEF\r\n\t#define SS_NOTHROW __declspec(nothrow)\r\n#else\r\n\t#define SS_NOTHROW\r\n#endif\r\n\r\n#ifndef TRACE\r\n\t#define TRACE_DEFINED_HERE\r\n\t#define TRACE\r\n#endif\r\n\r\n// Microsoft defines PCSTR, PCWSTR, etc, but no PCTSTR.  I hate to use the\r\n// versions with the \"L\" in front of them because that's a leftover from Win 16\r\n// days, even though it evaluates to the same thing.  Therefore, Define a PCSTR\r\n// as an LPCTSTR.\r\n\r\n#if !defined(PCTSTR) && !defined(PCTSTR_DEFINED)\r\n\ttypedef const TCHAR*\t\t\tPCTSTR;\r\n\t#define PCTSTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCOLESTR) && !defined(PCOLESTR_DEFINED)\r\n\ttypedef const OLECHAR*\t\t\tPCOLESTR;\r\n\t#define PCOLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(POLESTR) && !defined(POLESTR_DEFINED)\r\n\ttypedef OLECHAR*\t\t\t\tPOLESTR;\r\n\t#define POLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCUSTR) && !defined(PCUSTR_DEFINED)\r\n\ttypedef const unsigned char*\tPCUSTR;\r\n\ttypedef unsigned char*\t\t\tPUSTR;\r\n\t#define PCUSTR_DEFINED\r\n#endif\r\n\r\n\r\n// SGI compiler 7.3 doesnt know these  types - oh and btw, remember to use\r\n// -LANG:std in the CXX Flags\r\n#if defined(__sgi)\r\n    typedef unsigned long           DWORD;\r\n    typedef void *                  LPCVOID;\r\n#endif\r\n\r\n\r\n// SS_USE_FACET macro and why we need it:\r\n//\r\n// Since I'm a good little Standard C++ programmer, I use locales.  Thus, I\r\n// need to make use of the use_facet<> template function here.   Unfortunately,\r\n// this need is complicated by the fact the MS' implementation of the Standard\r\n// C++ Library has a non-standard version of use_facet that takes more\r\n// arguments than the standard dictates.  Since I'm trying to write CStdString\r\n// to work with any version of the Standard library, this presents a problem.\r\n//\r\n// The upshot of this is that I can't do 'use_facet' directly.  The MS' docs\r\n// tell me that I have to use a macro, _USE() instead.  Since _USE obviously\r\n// won't be available in other implementations, this means that I have to write\r\n// my OWN macro -- SS_USE_FACET -- that evaluates either to _USE or to the\r\n// standard, use_facet.\r\n//\r\n// If you are having trouble with the SS_USE_FACET macro, in your implementation\r\n// of the Standard C++ Library, you can define your own version of SS_USE_FACET.\r\n#ifndef schMSG\r\n\t#define schSTR(x)\t   #x\r\n\t#define schSTR2(x)\tschSTR(x)\r\n\t#define schMSG(desc) message(__FILE__ \"(\" schSTR2(__LINE__) \"):\" #desc)\r\n#endif\r\n\r\n#ifndef SS_USE_FACET\r\n\t// STLPort #defines a macro (__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) for\r\n\t// all MSVC builds, erroneously in my opinion.  It causes problems for\r\n\t// my SS_ANSI builds.  In my code, I always comment out that line.  You'll\r\n\t// find it in   \\stlport\\config\\stl_msvc.h\r\n\t#if defined(__SGI_STL_PORT) && (__SGI_STL_PORT >= 0x400 )\r\n\t\t#if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) && defined(_MSC_VER)\r\n\t\t\t#ifdef SS_ANSI\r\n\t\t\t\t#pragma schMSG(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS defined!!)\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#elif defined(_MSC_VER )\r\n\t#define SS_USE_FACET(loc, fac) std::_USE(loc, fac)\r\n\r\n\t// ...and\r\n\t#elif defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE)\r\n        #define SS_USE_FACET(loc, fac) std::use_facet(loc, (fac*)0)\r\n\t#else\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#endif\r\n#endif\r\n\r\n// =============================================================================\r\n// UNICODE/MBCS conversion macros.  Made to work just like the MFC/ATL ones.\r\n// =============================================================================\r\n\r\n#include <wchar.h>      // Added to Std Library with Amendment #1.\r\n\r\n// First define the conversion helper functions.  We define these regardless of\r\n// any preprocessor macro settings since their names won't collide. \r\n\r\n// Not sure if we need all these headers.   I believe ANSI says we do.\r\n\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include <wctype.h>\r\n#include <ctype.h>\r\n#include <stdlib.h>\r\n#ifndef va_start\r\n\t#include <varargs.h>\r\n#endif\r\n\r\n// StdCodeCvt - made to look like Win32 functions WideCharToMultiByte\r\n//\t\t\t\tand MultiByteToWideChar but uses locales in SS_ANSI\r\n//\t\t\t\tbuilds.  There are a number of overloads.\r\n//              First argument is the destination buffer.\r\n//              Second argument is the source buffer\r\n//#if defined (SS_ANSI) || !defined (SS_WIN32)\r\n\r\n// 'SSCodeCvt' - shorthand name for the codecvt facet we use\r\n\r\ntypedef std::codecvt<wchar_t, char, mbstate_t> SSCodeCvt;\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n\r\n    ASSERT(0 != pSrcA);\r\n    ASSERT(0 != pDstW);\r\n\r\n\tpDstW[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPCSTR pNextSrcA\t\t\t= pSrcA;\r\n\t\tPWSTR pNextDstW\t\t\t= pDstW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.in(st,\r\n\t\t\t\t\t\t\t\t\tpSrcA, pSrcA + nSrc, pNextSrcA,\r\n\t\t\t\t\t\t\t\t\tpDstW, pDstW + nDst, pNextDstW);\r\n\r\n\t\tASSERT(SSCodeCvt::ok == res);\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(pNextDstW >= pDstW);\r\n\t\tASSERT(pNextSrcA >= pSrcA);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstW - pDstW > nDst )\r\n\t\t\t*(pDstW + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstW = '\\0';\r\n\t}\r\n    return pDstW;\r\n}\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCUSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, loc);\r\n}\r\n\r\ninline PSTR StdCodeCvt(PSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    ASSERT(0 != pDstA);\r\n    ASSERT(0 != pSrcW);\r\n\r\n\tpDstA[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPSTR pNextDstA\t\t\t= pDstA;\r\n\t\tPCWSTR pNextSrcW\t\t= pSrcW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.out(st,\r\n\t\t\t\t\t\t\t\t\tpSrcW, pSrcW + nSrc, pNextSrcW,\r\n\t\t\t\t\t\t\t\t\tpDstA, pDstA + nDst, pNextDstA);\r\n\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(SSCodeCvt::ok == res);\t// strict, comment out for sanity\r\n\t\tASSERT(pNextDstA >= pDstA);\r\n\t\tASSERT(pNextSrcW >= pSrcW);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstA - pDstA > nDst )\r\n\t\t\t*(pDstA + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstA = '\\0';\r\n\t}\r\n    return pDstA;\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, loc);\r\n}\r\n/*\r\n#else   // ...or are we doing things assuming win32 and Visual C++?\r\n\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pSrcA);\r\n\t\tASSERT(0 != pDstW);\r\n\t\tpW[0] = '\\0';\r\n\t\tMultiByteToWideChar(acp, 0, pSrcA, nSrc, pDstW, nDst);\r\n\t\treturn pW;\r\n\t}\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, nDst, PCUSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, acp);\r\n\t}\r\n\r\n\tinline PSTR StdCodeCvt(PSTR pDstA, nDst PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pDstA);\r\n\t\tASSERT(0 != pSrcW);\r\n\t\tpA[0] = '\\0';\r\n\t\tWideCharToMultiByte(acp, 0, pSrcW, nSrc, pDstA, nDst, 0, 0);\r\n\t\treturn pA;\r\n\t}\r\n\tinline PUSTR StdCodeCvt(PUSTR pDstA, nDst, PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, acp);\r\n\t}\r\n\r\n#endif\r\n*/\r\n\r\n// Unicode/MBCS conversion macros are only available on implementations of\r\n// the \"C\" library that have the non-standard _alloca function.  As far as I\r\n// know that's only Microsoft's though I've heard that the function exists\r\n// elsewhere.  \r\n    \r\n#if defined(SS_ALLOCA) && !defined SS_NO_CONVERSION\r\n\r\n    #include <malloc.h>\t// needed for _alloca\r\n\r\n    // Define our conversion macros to look exactly like Microsoft's to\r\n    // facilitate using this stuff both with and without MFC/ATL\r\n\r\n    #ifdef _CONVERSION_USES_THREAD_LOCALE\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=GetACP(); \\\r\n\t\t\t    _acp; PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=GetACP();\\\r\n\t\t\t     _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t\t\t_pa, _cvt, _acp)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = sslen(_pw), \\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt, _acp)))\r\n\t#else\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=CP_ACP; _acp;\\\r\n\t\t\t     PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=CP_ACP; \\\r\n\t\t\t    _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pa, _cvt)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pw)),\\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt)))\r\n    #endif\r\n\r\n    #define SSA2CW(pa) ((PCWSTR)SSA2W((pa)))\r\n    #define SSW2CA(pw) ((PCSTR)SSW2A((pw)))\r\n\r\n    #ifdef UNICODE\r\n\t    #define SST2A\tSSW2A\r\n\t    #define SSA2T\tSSA2W\r\n\t    #define SST2CA\tSSW2CA\r\n\t    #define SSA2CT\tSSA2CW\r\n\t\t// (Did you get a compiler error here about not being able to convert\r\n\t\t// PTSTR into PWSTR?  Then your _UNICODE and UNICODE flags are messed \r\n\t\t// up.  Best bet: #define BOTH macros before including any MS headers.)\r\n\t    inline PWSTR\tSST2W(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSW2T(PWSTR p)\t\t\t{ return p; }\r\n\t    inline PCWSTR\tSST2CW(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSW2CT(PCWSTR p)\t\t{ return p; }\r\n    #else\r\n\t    #define SST2W\tSSA2W\r\n\t    #define SSW2T\tSSW2A\r\n\t    #define SST2CW\tSSA2CW\r\n\t    #define SSW2CT\tSSW2CA\r\n\t    inline PSTR\t\tSST2A(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSA2T(PSTR p)\t\t\t{ return p; }\r\n\t    inline PCSTR\tSST2CA(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSA2CT(PCSTR p)\t\t\t{ return p; }\r\n    #endif // #ifdef UNICODE\r\n\r\n    #if defined(UNICODE)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #elif defined(OLE2ANSI)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #else\r\n\t    //CharNextW doesn't work on Win95 so we use this\r\n\t    #define SST2COLE(pa)\tSSA2CW((pa))\r\n\t    #define SST2OLE(pa)\t\tSSA2W((pa))\r\n\t    #define SSOLE2CT(po)\tSSW2CA((po))\r\n\t    #define SSOLE2T(po)\t\tSSW2A((po))\r\n    #endif\r\n\r\n    #ifdef OLE2ANSI\r\n\t    #define SSW2OLE\t\tSSW2A\r\n\t    #define SSOLE2W\t\tSSA2W\r\n\t    #define SSW2COLE\tSSW2CA\r\n\t    #define SSOLE2CW\tSSA2CW\r\n\t    inline POLESTR\t\tSSA2OLE(PSTR p)\t\t{ return p; }\r\n\t    inline PSTR\t\t\tSSOLE2A(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSA2COLE(PCSTR p)\t{ return p; }\r\n\t    inline PCSTR\t\tSSOLE2CA(PCOLESTR p){ return p; }\r\n    #else\r\n\t    #define SSA2OLE\t\tSSA2W\r\n\t    #define SSOLE2A\t\tSSW2A\r\n\t    #define SSA2COLE\tSSA2CW\r\n\t    #define SSOLE2CA\tSSW2CA\r\n\t    inline POLESTR\t\tSSW2OLE(PWSTR p)\t{ return p; }\r\n\t    inline PWSTR\t\tSSOLE2W(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSW2COLE(PCWSTR p)\t{ return p; }\r\n\t    inline PCWSTR\t\tSSOLE2CW(PCOLESTR p){ return p; }\r\n    #endif\r\n\r\n    // Above we've defined macros that look like MS' but all have\r\n    // an 'SS' prefix.  Now we need the real macros.  We'll either\r\n    // get them from the macros above or from MFC/ATL. \r\n\r\n\t#if defined (USES_CONVERSION)\r\n\r\n\t\t#define _NO_STDCONVERSION\t// just to be consistent\r\n\r\n\t#else\r\n\r\n\t\t#ifdef _MFC_VER\r\n\r\n\t\t\t#include <afxconv.h>\r\n\t\t\t#define _NO_STDCONVERSION // just to be consistent\r\n\r\n\t\t#else\r\n\r\n\t\t\t#define USES_CONVERSION SSCVT\r\n\t\t\t#define A2CW\t\t\tSSA2CW\r\n\t\t\t#define W2CA\t\t\tSSW2CA\r\n\t\t\t#define T2A\t\t\t\tSST2A\r\n\t\t\t#define A2T\t\t\t\tSSA2T\r\n\t\t\t#define T2W\t\t\t\tSST2W\r\n\t\t\t#define W2T\t\t\t\tSSW2T\r\n\t\t\t#define T2CA\t\t\tSST2CA\r\n\t\t\t#define A2CT\t\t\tSSA2CT\r\n\t\t\t#define T2CW\t\t\tSST2CW\r\n\t\t\t#define W2CT\t\t\tSSW2CT\r\n\t\t\t#define ocslen\t\t\tsslen\r\n\t\t\t#define ocscpy\t\t\tsscpy\r\n\t\t\t#define T2COLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2CT\t\t\tSSOLE2CT\r\n\t\t\t#define T2OLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2T\t\t\tSSOLE2CT\r\n\t\t\t#define A2OLE\t\t\tSSA2OLE\r\n\t\t\t#define OLE2A\t\t\tSSOLE2A\r\n\t\t\t#define W2OLE\t\t\tSSW2OLE\r\n\t\t\t#define OLE2W\t\t\tSSOLE2W\r\n\t\t\t#define A2COLE\t\t\tSSA2COLE\r\n\t\t\t#define OLE2CA\t\t\tSSOLE2CA\r\n\t\t\t#define W2COLE\t\t\tSSW2COLE\r\n\t\t\t#define OLE2CW\t\t\tSSOLE2CW\r\n\t\r\n\t\t#endif // #ifdef _MFC_VER\r\n\t#endif // #ifndef USES_CONVERSION\r\n#endif // #ifndef SS_NO_CONVERSION\r\n\r\n// Define ostring - generic name for std::basic_string<OLECHAR>\r\n\r\n#if !defined(ostring) && !defined(OSTRING_DEFINED)\r\n\ttypedef std::basic_string<OLECHAR> ostring;\r\n\t#define OSTRING_DEFINED\r\n#endif\r\n\r\n// StdCodeCvt when there's no conversion to be done\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<char>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<char>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCUSTR pSrc, int nSrc)\r\n{\r\n\treturn StdCodeCvt(pDst, nDst, (PCSTR)pSrc, nSrc);\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\treturn (PUSTR)StdCodeCvt((PSTR)pDst, nDst, pSrc, nSrc);\r\n}\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDst, int nDst, PCWSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<wchar_t>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<wchar_t>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\n\r\n\r\n// Define tstring -- generic name for std::basic_string<TCHAR>\r\n\r\n#if !defined(tstring) && !defined(TSTRING_DEFINED)\r\n\ttypedef std::basic_string<TCHAR> tstring;\r\n\t#define TSTRING_DEFINED\r\n#endif\r\n\r\n// a very shorthand way of applying the fix for KB problem Q172398\r\n// (basic_string assignment bug)\r\n\r\n#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t#define Q172398(x) (x).erase()\r\n#else\r\n\t#define Q172398(x)\r\n#endif\r\n\r\n// =============================================================================\r\n// INLINE FUNCTIONS ON WHICH CSTDSTRING RELIES\r\n//\r\n// Usually for generic text mapping, we rely on preprocessor macro definitions\r\n// to map to string functions.  However the CStdStr<> template cannot use\r\n// macro-based generic text mappings because its character types do not get\r\n// resolved until template processing which comes AFTER macro processing.  In\r\n// other words, the preprocessor macro UNICODE is of little help to us in the\r\n// CStdStr template\r\n//\r\n// Therefore, to keep the CStdStr declaration simple, we have these inline\r\n// functions.  The template calls them often.  Since they are inline (and NOT\r\n// exported when this is built as a DLL), they will probably be resolved away\r\n// to nothing. \r\n//\r\n// Without these functions, the CStdStr<> template would probably have to broken\r\n// out into two, almost identical classes.  Either that or it would be a huge,\r\n// convoluted mess, with tons of \"if\" statements all over the place checking the\r\n// size of template parameter CT.\r\n// \r\n// In several cases, you will see two versions of each function.  One version is\r\n// the more portable, standard way of doing things, while the other is the\r\n// non-standard, but often significantly faster Visual C++ way.\r\n// =============================================================================\r\n\r\n// If they defined SS_NO_REFCOUNT, then we must convert all assignments\r\n\r\n#ifdef SS_NO_REFCOUNT\r\n\t#define SSREF(x) (x).c_str()\r\n#else\r\n\t#define SSREF(x) (x)\r\n#endif\r\n\r\n// -----------------------------------------------------------------------------\r\n// sslen: strlen/wcslen wrappers\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT> inline int sslen(const CT* pT)\r\n{\r\n\treturn 0 == pT ? 0 : (int)std::basic_string<CT>::traits_type::length(pT);\r\n//\treturn 0 == pT ? 0 : std::char_traits<CT>::length(pT);\r\n}\r\ninline SS_NOTHROW int sslen(const std::string& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\ninline SS_NOTHROW int sslen(const std::wstring& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// sstolower/sstoupper -- convert characters to upper/lower case\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline CT sstolower(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::tolower<CT>(t, loc);\r\n}\r\ntemplate<typename CT>\r\ninline CT sstoupper(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::toupper<CT>(t, loc);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssasn: assignment functions -- assign \"sSrc\" to \"sDst\"\r\n// -----------------------------------------------------------------------------\r\ntypedef std::string::size_type\t\tSS_SIZETYPE; // just for shorthand, really\r\ntypedef std::string::pointer\t\tSS_PTRTYPE;  \r\ntypedef std::wstring::size_type\t\tSW_SIZETYPE;\r\ntypedef std::wstring::pointer\t\tSW_PTRTYPE;  \r\n\r\ninline void\tssasn(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCSTR pA)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pA )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pA actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pA >= sDst.c_str() && pA <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst =sDst.substr(static_cast<SS_SIZETYPE>(pA-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pA);\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sSrc.size());\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), static_cast<int>(sSrc.size()));\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tszCvt;\r\n\t\tsDst.resize(sSrc.size());\r\n#endif\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nSrc\t= sslen(pW);\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tpW, nSrc);\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n}\r\ninline void ssasn(std::string& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(\"\");\r\n}\t\r\ninline void\tssasn(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pW )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pW actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pW >= sDst.c_str() && pW <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst = sDst.substr(static_cast<SW_SIZETYPE>(pW-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pW);\r\n\t}\r\n}\r\n#undef StrSizeType\r\ninline void\tssasn(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\tsDst.resize(nSrc+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), nSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t= sslen(pA);\r\n\r\n\tif ( 0 == nSrc )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= nSrc;\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst, pA,\r\n\t\t\tnSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void ssasn(std::wstring& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(L\"\");\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssadd: string object concatenation -- add second argument to first\r\n// -----------------------------------------------------------------------------\r\ninline void\tssadd(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+nAdd+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, sSrc.c_str(), nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nAdd);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + nAdd + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, pW, nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, PCSTR pA)\r\n{\r\n\tif ( pA )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pA >= sDst.c_str() && pA <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pA) )\r\n\t\t\t\tsDst.append(std::string(pA));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pA);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pA); \r\n\t\t}\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( !sSrc.empty() )\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst), \r\n\t\t\tnSrc, sSrc.c_str(), nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t\t= sslen(pA);\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnSrc, pA, nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\tif ( pW )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pW >= sDst.c_str() && pW <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pW) )\r\n\t\t\t\tsDst.append(std::wstring(pW));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscmp: comparison (case sensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int sscmp(const CT* pA1, const CT* pA2)\r\n{\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = *(pA1++);\r\n\t    l = *(pA2++);\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssicmp: comparison (case INsensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int ssicmp(const CT* pA1, const CT* pA2)\r\n{\r\n\t// Using the \"C\" locale = \"not affected by locale\"\r\n\r\n\tstd::locale loc = std::locale::classic();\r\n    const std::ctype<CT>& ct = SS_USE_FACET(loc, std::ctype<CT>);\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = ct.tolower(*(pA1++));\r\n\t    l = ct.tolower(*(pA2++));\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssupr/sslwr: Uppercase/Lowercase conversion functions\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\ninline void sslwr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).tolower(pT, pT+nLen);\r\n}\r\ntemplate<typename CT>\r\ninline void ssupr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).toupper(pT, pT+nLen);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n//  vsprintf/vswprintf or _vsnprintf/_vsnwprintf equivalents.  In standard\r\n//  builds we can't use _vsnprintf/_vsnwsprintf because they're MS extensions.\r\n// -----------------------------------------------------------------------------\r\n#if defined(SS_ANSI) || !defined(_MSC_VER)\r\n\r\n    // Borland's headers put some ANSI \"C\" functions in the 'std' namespace. \r\n    // Promote them to the global namespace so we can use them here.\r\n\r\n    #if defined(__BORLANDC__)\r\n        using std::vsprintf;\r\n        using std::vswprintf;\r\n    #endif\r\n\r\n\tinline int ssvsprintf(PSTR pA, size_t /*nCount*/, PCSTR pFmtA, va_list vl)\r\n\t{\r\n\t\treturn vsprintf(pA, pFmtA, vl);\r\n\t}\r\n\tinline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\t// JMO: Some distributions of the \"C\" have a version of vswprintf that\r\n        // takes 3 arguments (e.g. Microsoft, Borland, GNU).  Others have a \r\n        // version which takes 4 arguments (an extra \"count\" argument in the\r\n        // second position.  The best stab I can take at this so far is that if\r\n        // you are NOT running with MS, Borland, or GNU, then I'll assume you\r\n        // have the version that takes 4 arguments.\r\n        //\r\n        // I'm sure that these checks don't catch every platform correctly so if\r\n        // you get compiler errors on one of the lines immediately below, it's\r\n        // probably because your implemntation takes a different number of\r\n        // arguments.  You can comment out the offending line (and use the\r\n        // alternate version) or you can figure out what compiler flag to check\r\n        // and add that preprocessor check in.  Regardless, if you get an error\r\n        // on these lines, I'd sure like to hear from you about it.\r\n        //\r\n        // Thanks to Ronny Schulz for the SGI-specific checks here.\r\n\r\n//\t#if !defined(__MWERKS__) && !defined(__SUNPRO_CC_COMPAT) && !defined(__SUNPRO_CC)\r\n    #if    !defined(_MSC_VER) \\\r\n        && !defined (__BORLANDC__) \\\r\n        && !defined(__GNUC__) \\\r\n        && !defined(__sgi)\r\n\r\n        return vswprintf(pW, nCount, pFmtW, vl);\r\n\r\n    // suddenly with the current SGI 7.3 compiler there is no such function as\r\n    // vswprintf and the substitute needs explicit casts to compile\r\n\r\n    #elif defined(__sgi)\r\n\r\n        nCount;\r\n        return vsprintf( (char *)pW, (char *)pFmtW, vl);\r\n\r\n    #else\r\n\r\n        nCount;\r\n        return vswprintf(pW, pFmtW, vl);\r\n\r\n    #endif\r\n\r\n\t}\r\n#else\r\n\tinline int\tssnprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl)\r\n\t{ \r\n\t\treturn _vsnprintf(pA, nCount, pFmtA, vl);\r\n\t}\r\n\tinline int\tssnprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\treturn _vsnwprintf(pW, nCount, pFmtW, vl);\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssload: Type safe, overloaded ::LoadString wrappers\r\n// There is no equivalent of these in non-Win32-specific builds.  However, I'm\r\n// thinking that with the message facet, there might eventually be one\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline int ssload(HMODULE hInst, UINT uId, PSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringA(hInst, uId, pBuf, nMax);\r\n\t}\r\n\tinline int ssload(HMODULE hInst, UINT uId, PWSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringW(hInst, uId, pBuf, nMax);\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscoll/ssicoll: Collation wrappers\r\n//\t\tNote -- with MSVC I have reversed the arguments order here because the\r\n//\t\tfunctions appear to return the opposite of what they should\r\n// -----------------------------------------------------------------------------\r\ntemplate <typename CT>\r\ninline int sscoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::collate<CT>& coll =\r\n\t\tSS_USE_FACET(std::locale(), std::collate<CT>);\r\n\r\n\treturn coll.compare(sz2, sz2+nLen2, sz1, sz1+nLen1);\r\n}\r\ntemplate <typename CT>\r\ninline int ssicoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::locale loc;\r\n\tconst std::collate<CT>& coll = SS_USE_FACET(loc, std::collate<CT>);\r\n\r\n\t// Some implementations seem to have trouble using the collate<>\r\n\t// facet typedefs so we'll just default to basic_string and hope\r\n\t// that's what the collate facet uses (which it generally should)\r\n\r\n//\tstd::collate<CT>::string_type s1(sz1);\r\n//\tstd::collate<CT>::string_type s2(sz2);\r\n\tconst std::basic_string<CT> sEmpty;\r\n    std::basic_string<CT> s1(sz1 ? sz1 : sEmpty.c_str());\r\n    std::basic_string<CT> s2(sz2 ? sz2 : sEmpty.c_str());\r\n\r\n\tsslwr(const_cast<CT*>(s1.c_str()), nLen1, loc);\r\n\tsslwr(const_cast<CT*>(s2.c_str()), nLen2, loc);\r\n\treturn coll.compare(s2.c_str(), s2.c_str()+nLen2,\r\n\t\t\t\t\t\ts1.c_str(), s1.c_str()+nLen1);\r\n}\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssfmtmsg: FormatMessage equivalents.  Needed because I added a CString facade\r\n// Again -- no equivalent of these on non-Win32 builds but their might one day\r\n// be one if the message facet gets implemented\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{ \r\n\t\treturn FormatMessageA(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PWSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{\r\n\t\treturn FormatMessageW(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n#else\r\n#endif\r\n \r\n\r\n\r\n// FUNCTION: sscpy.  Copies up to 'nMax' characters from pSrc to pDst.\r\n// -----------------------------------------------------------------------------\r\n// FUNCTION:  sscpy\r\n//\t\tinline int sscpy(PSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PUSTR pDst,  PCSTR pSrc, int nMax=-1)\r\n//\t\tinline int sscpy(PSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\r\n// DESCRIPTION:\r\n//\t\tThis function is very much (but not exactly) like strcpy.  These\r\n//\t\toverloads simplify copying one C-style string into another by allowing\r\n//\t\tthe caller to specify two different types of strings if necessary.\r\n//\r\n//\t\tThe strings must NOT overlap\r\n//\r\n//\t\t\"Character\" is expressed in terms of the destination string, not\r\n//\t\tthe source.  If no 'nMax' argument is supplied, then the number of\r\n//\t\tcharacters copied will be sslen(pSrc).  A NULL terminator will\r\n//\t\talso be added so pDst must actually be big enough to hold nMax+1\r\n//\t\tcharacters.  The return value is the number of characters copied,\r\n//\t\tnot including the NULL terminator.\r\n//\r\n// PARAMETERS: \r\n//\t\tpSrc - the string to be copied FROM.  May be a char based string, an\r\n//\t\t\t   MBCS string (in Win32 builds) or a wide string (wchar_t).\r\n//\t\tpSrc - the string to be copied TO.  Also may be either MBCS or wide\r\n//\t\tnMax - the maximum number of characters to be copied into szDest.  Note\r\n//\t\t\t   that this is expressed in whatever a \"character\" means to pDst.\r\n//\t\t\t   If pDst is a wchar_t type string than this will be the maximum\r\n//\t\t\t   number of wchar_ts that my be copied.  The pDst string must be\r\n//\t\t\t   large enough to hold least nMaxChars+1 characters.\r\n//\t\t\t   If the caller supplies no argument for nMax this is a signal to\r\n//\t\t\t   the routine to copy all the characters in pSrc, regardless of\r\n//\t\t\t   how long it is.\r\n//\r\n// RETURN VALUE: none\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpycvt(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\t\r\n\tint nSrc = sslen(pSrc);\r\n\r\n\tconst CT1* szCvt = StdCodeCvt(pDst, nMax, pSrc, nSrc);\r\n\r\n\t// If we're copying the same size characters, then all the \"code convert\"\r\n\t// just did was basically memcpy so the #of characters copied is the same\r\n\t// as the number requested.  I should probably specialize this function\r\n\t// template to achieve this purpose as it is silly to do a runtime check\r\n\t// of a fact known at compile time.  I'll get around to it.\r\n\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ninline int sscpycvt(PSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<char>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst =  '\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCWSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<wchar_t>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst = L'\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\r\n\tconst PWSTR szCvt = StdCodeCvt(pDst, nMax, pSrc, nMax);\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax, int nLen)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, nLen));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, sslen(pSrc)));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, sslen(pSrc));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), SSMIN(nMax, (int)sSrc.length()));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), (int)sSrc.length());\r\n}\r\n\r\n#ifdef SS_INC_COMDEF\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs, int nMax)\r\n\t{\r\n\t\treturn sscpycvt(pDst, static_cast<PCOLESTR>(bs),\r\n            SSMIN(nMax, static_cast<int>(bs.length())));\r\n\t}\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs)\r\n\t{\r\n\t\treturn sscpy(pDst, bs, static_cast<int>(bs.length()));\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// Functional objects for changing case.  They also let you pass locales\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\nstruct SSToUpper : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstoupper<CT>(t, loc);\r\n    }\r\n};\r\ntemplate<typename CT>\r\nstruct SSToLower : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstolower<CT>(t, loc);\r\n    }\r\n};\r\n\r\n// This struct is used for TrimRight() and TrimLeft() function implementations.\r\n//template<typename CT>\r\n//struct NotSpace : public std::unary_function<CT, bool>\r\n//{\r\n//\tconst std::locale& loc;\r\n//\tinline NotSpace(const std::locale& locArg) : loc(locArg) {}\r\n//\tinline bool operator() (CT t) { return !std::isspace(t, loc); }\r\n//};\r\ntemplate<typename CT>\r\nstruct NotSpace : public std::unary_function<CT, bool>\r\n{\r\n\r\n\t// DINKUMWARE BUG:\r\n\t// Note -- using std::isspace in a COM DLL gives us access violations\r\n\t// because it causes the dynamic addition of a function to be called\r\n\t// when the library shuts down.  Unfortunately the list is maintained\r\n\t// in DLL memory but the function is in static memory.  So the COM DLL\r\n\t// goes away along with the function that was supposed to be called,\r\n\t// and then later when the DLL CRT shuts down it unloads the list and\r\n\t// tries to call the long-gone function.\r\n\t// This is DinkumWare's implementation problem.  If you encounter this\r\n\t// problem, you may replace the calls here with good old isspace() and\r\n\t// iswspace() from the CRT unless they specify SS_ANSI\r\n    \r\n\tconst std::locale loc;\r\n\tNotSpace(const std::locale& locArg=std::locale()) : loc(locArg) {}\r\n\tbool operator() (CT t) const { return !std::isspace(t, loc); }\r\n};\r\n\r\n\r\n\r\n\r\n//\t\t\tNow we can define the template (finally!)\r\n// =============================================================================\r\n// TEMPLATE: CStdStr\r\n//\t\ttemplate<typename CT> class CStdStr : public std::basic_string<CT>\r\n//\r\n// REMARKS:\r\n//\t\tThis template derives from basic_string<CT> and adds some MFC CString-\r\n//\t\tlike functionality\r\n//\r\n//\t\tBasically, this is my attempt to make Standard C++ library strings as\r\n//\t\teasy to use as the MFC CString class.\r\n//\r\n//\t\tNote that although this is a template, it makes the assumption that the\r\n//\t\ttemplate argument (CT, the character type) is either char or wchar_t.  \r\n// =============================================================================\r\n\r\n//#define CStdStr _SS\t// avoid compiler warning 4786\r\n\r\n//    template<typename ARG> ARG& FmtArg(ARG& arg)  { return arg; }\r\n//    PCSTR  FmtArg(const std::string& arg)  { return arg.c_str(); }\r\n//    PCWSTR FmtArg(const std::wstring& arg) { return arg.c_str(); }\r\n\r\ntemplate<typename ARG>\r\nstruct FmtArg\r\n{\r\n    explicit FmtArg(const ARG& arg) : a_(arg) {}\r\n    const ARG& operator()() const { return a_; }\r\n    const ARG& a_;\r\nprivate:\r\n    FmtArg& operator=(const FmtArg&) { return *this; }\r\n};\r\n\r\ntemplate<typename CT>\r\nclass CStdStr : public std::basic_string<CT>\r\n{\r\n\t// Typedefs for shorter names.  Using these names also appears to help\r\n\t// us avoid some ambiguities that otherwise arise on some platforms\r\n\r\n\t#define MYBASE std::basic_string<CT>\t\t\t\t // my base class\r\n\t//typedef typename std::basic_string<CT>\t\tMYBASE;\t // my base class\r\n\ttypedef CStdStr<CT>\t\t\t\t\t\t\tMYTYPE;\t // myself\r\n\ttypedef typename MYBASE::const_pointer\t\tPCMYSTR; // PCSTR or PCWSTR \r\n\ttypedef typename MYBASE::pointer\t\t\tPMYSTR;\t // PSTR or PWSTR\r\n\ttypedef typename MYBASE::iterator\t\t\tMYITER;  // my iterator type\r\n\ttypedef typename MYBASE::const_iterator\t\tMYCITER; // you get the idea...\r\n\ttypedef typename MYBASE::reverse_iterator\tMYRITER;\r\n\ttypedef typename MYBASE::size_type\t\t\tMYSIZE;   \r\n\ttypedef typename MYBASE::value_type\t\t\tMYVAL; \r\n\ttypedef typename MYBASE::allocator_type\t\tMYALLOC;\r\n\t\r\npublic:\r\n\t// shorthand conversion from PCTSTR to string resource ID\r\n\t#define SSRES(pctstr)  LOWORD(reinterpret_cast<unsigned long>(pctstr))\t\r\n\r\n\tbool TryLoad(const void* pT)\r\n\t{\r\n\t\tbool bLoaded = false;\r\n\r\n#if defined(SS_WIN32) && !defined(SS_ANSI)\r\n\t\tif ( ( pT != NULL ) && SS_IS_INTRESOURCE(pT) )\r\n\t\t{\r\n\t\t\tUINT nId = LOWORD(reinterpret_cast<unsigned long>(pT));\r\n\t\t\tif ( !LoadString(nId) )\r\n\t\t\t{\r\n\t\t\t\tTRACE(_T(\"Can't load string %u\\n\"), SSRES(pT));\r\n\t\t\t}\r\n\t\t\tbLoaded = true;\r\n\t\t}\r\n#endif\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n\r\n\t// CStdStr inline constructors\r\n\tCStdStr()\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const MYTYPE& str) : MYBASE(SSREF(str))\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(PCMYSTR pT, MYSIZE n) : MYBASE(pT, n)\r\n\t{\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tCStdStr(PCUSTR pU)\r\n\t{\r\n\t\t*this = reinterpret_cast<PCSTR>(pU);\r\n\t}\r\n#endif\r\n\r\n\tCStdStr(PCSTR pA)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pA;\r\n\t#else\r\n\t\tif ( !TryLoad(pA) )\r\n\t\t\t*this = pA;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(PCWSTR pW)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pW;\r\n\t#else\r\n\t\tif ( !TryLoad(pW) )\r\n\t\t\t*this = pW;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(MYCITER first, MYCITER last)\r\n\t\t: MYBASE(first, last)\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(MYSIZE nSize, MYVAL ch, const MYALLOC& al=MYALLOC())\r\n\t\t: MYBASE(nSize, ch, al)\r\n\t{\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tCStdStr(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t\tthis->append(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t}\r\n\t#endif\r\n\r\n\t// CStdStr inline assignment operators -- the ssasn function now takes care\r\n\t// of fixing  the MSVC assignment bug (see knowledge base article Q172398).\r\n\tMYTYPE& operator=(const MYTYPE& str)\r\n\t{ \r\n\t\tssasn(*this, str); \r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCSTR pA)\r\n\t{\r\n\t\tssasn(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCWSTR pW)\r\n\t{\r\n\t\tssasn(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tMYTYPE& operator=(PCUSTR pU)\r\n\t{\r\n\t\tssasn(*this, reinterpret_cast<PCSTR>(pU));\r\n\t\treturn *this;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE& operator=(CT t)\r\n\t{\r\n\t\tQ172398(*this);\r\n\t\tthis->assign(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tMYTYPE& operator=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t{\r\n\t\t\t\tthis->assign(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// Overloads  also needed to fix the MSVC assignment bug (KB: Q172398)\r\n\t//  *** Thanks to Pete The Plumber for catching this one ***\r\n\t// They also are compiled if you have explicitly turned off refcounting\r\n\t#if ( defined(_MSC_VER) && ( _MSC_VER < 1200 ) ) || defined(SS_NO_REFCOUNT) \r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tsscpy(GetBuffer(str.size()+1), SSREF(str));\r\n\t\t\tthis->ReleaseBuffer(str.size());\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value.  Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\t\t\tMYTYPE strTemp(str.c_str()+nStart, nChars);\r\n\t\t\tQ172398(*this);\r\n\t\t\tthis->assign(strTemp);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str)\r\n\t\t{\r\n\t\t\tssasn(*this, str);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value. Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\r\n\t\t\t// Watch out for assignment to self\r\n\r\n\t\t\tif ( this == &str )\r\n\t\t\t{\r\n\t\t\t\tMYTYPE strTemp(str.c_str() + nStart, nChars);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(strTemp);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tQ172398(*this);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(str.c_str()+nStart, nChars);\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pC, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// Q172398 only fix -- erase before assigning, but not if we're\r\n\t\t\t// assigning from our own buffer\r\n\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t\t\tif ( !this->empty() &&\r\n\t\t\t\t( pC < this->data() || pC > this->data() + this->capacity() ) )\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t}\r\n\t#endif\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(pC, nChars);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYSIZE nChars, MYVAL val)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(nChars, val);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pT)\r\n\t\t{\r\n\t\t\treturn this->assign(pT, MYBASE::traits_type::length(pT));\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYCITER iterFirst, MYCITER iterLast)\r\n\t\t{\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) \r\n\t\t\t// Q172398 fix.  don't call erase() if we're assigning from ourself\r\n\t\t\tif ( iterFirst < this->begin() ||\r\n                 iterFirst > this->begin() + this->size() )\r\n            {\r\n\t\t\t\tthis->erase()\r\n            }\r\n\t#endif\r\n\t\t\tthis->replace(this->begin(), this->end(), iterFirst, iterLast);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr inline concatenation.\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& operator+=(const MYTYPE& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::string& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this; \r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::wstring& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCSTR pA)\r\n\t{\r\n\t\tssadd(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCWSTR pW)\r\n\t{\r\n\t\tssadd(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(CT t)\r\n\t{\r\n\t\tthis->append(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\t#ifdef SS_INC_COMDEF\t// if we have _bstr_t, define a += for it too.\r\n\t\tMYTYPE& operator+=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\treturn this->operator+=(static_cast<PCMYSTR>(bstr));\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Case changing functions\r\n\t// -------------------------------------------------------------------------\r\n\r\n    MYTYPE& ToUpper(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToUpper<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tssupr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& ToLower(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToLower<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tsslwr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\t\treturn *this;\r\n\t}\r\n\r\n\r\n\tMYTYPE& Normalize()\r\n\t{\r\n\t\treturn Trim().ToLower();\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr -- Direct access to character buffer.  In the MS' implementation,\r\n\t// the at() function that we use here also calls _Freeze() providing us some\r\n\t// protection from multithreading problems associated with ref-counting.\r\n    // In VC 7 and later, of course, the ref-counting stuff is gone.\r\n\t// -------------------------------------------------------------------------\r\n\r\n\tCT* GetBuf(int nMinLen=-1)\r\n\t{\r\n\t\tif ( static_cast<int>(size()) < nMinLen )\r\n\t\t\tthis->resize(static_cast<MYSIZE>(nMinLen));\r\n\r\n\t\treturn this->empty() ? const_cast<CT*>(this->data()) : &(this->at(0));\r\n\t}\r\n\r\n\tCT* SetBuf(int nLen)\r\n\t{\r\n\t\tnLen = ( nLen > 0 ? nLen : 0 );\r\n\t\tif ( this->capacity() < 1 && nLen == 0 )\r\n\t\t\tthis->resize(1);\r\n\r\n\t\tthis->resize(static_cast<MYSIZE>(nLen));\r\n\t\treturn const_cast<CT*>(this->data());\r\n\t}\r\n\tvoid RelBuf(int nNewLen=-1)\r\n\t{\r\n\t\tthis->resize(static_cast<MYSIZE>(nNewLen > -1 ? nNewLen :\r\n                                                        sslen(this->c_str())));\r\n\t}\r\n\r\n\tvoid BufferRel()\t\t { RelBuf(); }\t\t\t// backwards compatability\r\n\tCT*  Buffer()\t\t\t { return GetBuf(); }\t// backwards compatability\r\n\tCT*  BufferSet(int nLen) { return SetBuf(nLen);}// backwards compatability\r\n\r\n\tbool Equals(const CT* pT, bool bUseCase=false) const\r\n\t{\r\n\t\treturn  0 == (bUseCase ? this->compare(pT) : ssicmp(this->c_str(), pT));\r\n\t} \r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Load\r\n\t// REMARKS:\r\n\t//\t\tLoads string from resource specified by nID\r\n\t//\r\n\t// PARAMETERS:\r\n\t//\t\tnID - resource Identifier.  Purely a Win32 thing in this case\r\n\t//\r\n\t// RETURN VALUE:\r\n\t//\t\ttrue if successful, false otherwise\r\n\t// -------------------------------------------------------------------------\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tbool Load(UINT nId, HMODULE hModule=NULL)\r\n\t{\r\n\t\tbool bLoaded\t\t= false;\t// set to true of we succeed.\r\n\r\n\t#ifdef _MFC_VER\t\t// When in Rome (or MFC land)...\r\n\r\n\t\t// If they gave a resource handle, use it.  Note - this is archaic\r\n\t\t// and not really what I would recommend.  But then again, in MFC\r\n\t\t// land, you ought to be using CString for resources anyway since\r\n\t\t// it walks the resource chain for you.\r\n\r\n\t\tHMODULE hModuleOld = NULL;\r\n\r\n\t\tif ( NULL != hModule )\r\n\t\t{\r\n\t\t\thModuleOld = AfxGetResourceHandle();\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\t\t}\r\n\r\n\t\t// ...load the string\r\n\r\n\t\tCString strRes;\r\n\t\tbLoaded\t\t\t\t= FALSE != strRes.LoadString(nId);\r\n\r\n\t\t// ...and if we set the resource handle, restore it.\r\n\r\n\t\tif ( NULL != hModuleOld )\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\r\n\t\tif ( bLoaded )\r\n\t\t\t*this\t\t\t= strRes;\r\n\r\n\t#else // otherwise make our own hackneyed version of CString's Load\r\n\t\t\r\n\t\t// Get the resource name and module handle\r\n\r\n\t\tif ( NULL == hModule )\r\n\t\t\thModule\t\t\t= GetResourceHandle();\r\n\r\n\t\tPCTSTR szName\t\t= MAKEINTRESOURCE((nId>>4)+1); // lifted \r\n\t\tDWORD dwSize\t\t= 0;\r\n\r\n\t\t// No sense continuing if we can't find the resource\r\n\r\n\t\tHRSRC hrsrc\t\t\t= ::FindResource(hModule, szName, RT_STRING);\r\n\r\n\t\tif ( NULL == hrsrc )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cannot find resource %d: 0x%X\"), nId, ::GetLastError());\r\n\t\t}\r\n\t\telse if ( 0 == (dwSize = ::SizeofResource(hModule, hrsrc) / sizeof(CT)))\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cant get size of resource %d 0x%X\\n\"),nId,GetLastError());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tbLoaded\t\t\t= 0 != ssload(hModule, nId, GetBuf(dwSize), dwSize);\r\n\t\t\tReleaseBuffer();\r\n\t\t}\r\n\r\n\t#endif  // #ifdef _MFC_VER\r\n\r\n\t\tif ( !bLoaded )\r\n\t\t\tTRACE(_T(\"String not loaded 0x%X\\n\"), ::GetLastError());\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n#endif  // #ifdef SS_ANSI\r\n\t\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Format\r\n\t//\t\tvoid _cdecl Formst(CStdStringA& PCSTR szFormat, ...)\r\n\t//\t\tvoid _cdecl Format(PCSTR szFormat);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function does sprintf/wsprintf style formatting on CStdStringA\r\n\t//\t\tobjects.  It looks a lot like MFC's CString::Format.  Some people\r\n\t//\t\tmight even call this identical.  Fortunately, these people are now\r\n\t//\t\tdead... heh heh.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tnId - ID of string resource holding the format string\r\n\t//\t\tszFormat - a PCSTR holding the format specifiers\r\n\t//\t\targList - a va_list holding the arguments for the format specifiers.\r\n\t//\r\n\t// RETURN VALUE:  None.\r\n\t// -------------------------------------------------------------------------\r\n\t// formatting (using wsprintf style formatting)\r\n\r\n    // If they want a Format() function that safely handles string objects\r\n    // without casting\r\n \r\n#ifdef SS_SAFE_FORMAT       \r\n    \r\n    // Question:  Joe, you wacky coder you, why do you have so many overloads\r\n    //      of the Format() function\r\n    // Answer:  One reason only - CString compatability.  In short, by making\r\n    //      the Format() function a template this way, I can do strong typing\r\n    //      and allow people to pass CStdString arguments as fillers for\r\n    //      \"%s\" format specifiers without crashing their program!  The downside\r\n    //      is that I need to overload on the number of arguments.   If you are\r\n    //      passing more arguments than I have listed below in any of my\r\n    //      overloads, just add another one.\r\n    //\r\n    //      Yes, yes, this is really ugly.  In essence what I am doing here is\r\n    //      protecting people from a bad (and incorrect) programming practice\r\n    //      that they should not be doing anyway.  I am protecting them from\r\n    //      themselves.  Why am I doing this?  Well, if you had any idea the\r\n    //      number of times I've been emailed by people about this\r\n    //      \"incompatability\" in my code, you wouldn't ask.\r\n\r\n\tvoid Fmt(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\r\n    void Format(UINT nId)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) ) \r\n            this->swap(strFmt);\r\n    }\r\n    template<class A1>\r\n    void Format(UINT nId, const A1& v)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n            Fmt(strFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(UINT nId, const A1& v1, const A2& v2)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n        }\r\n    }\r\n    \r\n#endif // #ifndef SS_ANSI\r\n\r\n    // ...now the other overload of Format: the one that takes a string literal\r\n\r\n    void Format(const CT* szFmt)\r\n    {\r\n        *this = szFmt;\r\n    }\r\n    template<class A1>\r\n    void Format(const CT* szFmt, A1 v)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n    }\r\n\r\n#else  // #ifdef SS_SAFE_FORMAT\r\n\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tvoid Format(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tFormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t}\r\n    \r\n#endif  // #ifdef SS_ANSI\r\n\r\n\tvoid Format(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#endif // #ifdef SS_SAFE_FORMAT\r\n\r\n\tvoid AppendFormat(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tAppendFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\t#define MAX_FMT_TRIES\t\t5\t // #of times we try \r\n\t#define FMT_BLOCK_SIZE\t\t2048 // # of bytes to increment per try\r\n\t#define BUFSIZE_1ST\t256\r\n\t#define BUFSIZE_2ND 512\r\n\t#define STD_BUF_SIZE\t\t1024\r\n\r\n\t// an efficient way to add formatted characters to the string.  You may only\r\n\t// add up to STD_BUF_SIZE characters at a time, though\r\n\tvoid AppendFormatV(const CT* szFmt, va_list argList)\r\n\t{\r\n\t\tCT szBuf[STD_BUF_SIZE];\r\n\t#ifdef SS_ANSI\r\n\t\tint nLen = ssvsprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#else\r\n\t\tint nLen = ssnprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#endif\r\n\t\tif ( 0 < nLen )\r\n\t\t\tthis->append(szBuf, nLen);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  FormatV\r\n\t//\t\tvoid FormatV(PCSTR szFormat, va_list, argList);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function formats the string with sprintf style format-specs. \r\n\t//\t\tIt makes a general guess at required buffer size and then tries\r\n\t//\t\tsuccessively larger buffers until it finds one big enough or a\r\n\t//\t\tthreshold (MAX_FMT_TRIES) is exceeded.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tszFormat - a PCSTR holding the format of the output\r\n\t//\t\targList - a Microsoft specific va_list for variable argument lists\r\n\t//\r\n\t// RETURN VALUE: \r\n\t// -------------------------------------------------------------------------\r\n\r\n\tvoid FormatV(const CT* szFormat, va_list argList)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\r\n\t\tint nLen\t= sslen(szFormat) + STD_BUF_SIZE;\r\n\t\tssvsprintf(GetBuffer(nLen), nLen-1, szFormat, argList);\r\n\t\tReleaseBuffer();\r\n\r\n\t#else\r\n\r\n\t\tCT* pBuf\t\t\t= NULL;\r\n\t\tint nChars\t\t\t= 1;\r\n\t\tint nUsed\t\t\t= 0;\r\n\t\tsize_type nActual\t= 0;\r\n\t\tint nTry\t\t\t= 0;\r\n\r\n\t\tdo\t\r\n\t\t{\r\n\t\t\t// Grow more than linearly (e.g. 512, 1536, 3072, etc)\r\n\r\n\t\t\tnChars\t\t\t+= ((nTry+1) * FMT_BLOCK_SIZE);\r\n\t\t\tpBuf\t\t\t= reinterpret_cast<CT*>(_alloca(sizeof(CT)*nChars));\r\n\t\t\tnUsed\t\t\t= ssnprintf(pBuf, nChars-1, szFormat, argList);\r\n\r\n\t\t\t// Ensure proper NULL termination.\r\n\r\n\t\t\tnActual\t\t\t= nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1);\r\n\t\t\tpBuf[nActual+1]= '\\0';\r\n\r\n\r\n\t\t} while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES );\r\n\r\n\t\t// assign whatever we managed to format\r\n\r\n\t\tthis->assign(pBuf, nActual);\r\n\r\n\t#endif\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CString Facade Functions:\r\n\t//\r\n\t// The following methods are intended to allow you to use this class as a\r\n\t// near drop-in replacement for CString.\r\n\t// -------------------------------------------------------------------------\r\n\t#ifdef SS_WIN32\r\n\t\tBSTR AllocSysString() const\r\n\t\t{\r\n\t\t\tostring os;\r\n\t\t\tssasn(os, *this);\r\n\t\t\treturn ::SysAllocString(os.c_str());\r\n\t\t}\r\n\t#endif\r\n\r\n\tint Collate(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn sscoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint CollateNoCase(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn ssicoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint Compare(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn this->compare(szThat);\t\r\n\t}\r\n\r\n\tint CompareNoCase(PCMYSTR szThat)\tconst\r\n\t{\r\n\t\treturn ssicmp(this->c_str(), szThat);\r\n\t}\r\n\r\n\tint Delete(int nIdx, int nCount=1)\r\n\t{\r\n        if ( nIdx < 0 )\r\n\t\t\tnIdx = 0;\r\n\r\n\t\tif ( nIdx < this->GetLength() )\r\n\t\t\tthis->erase(static_cast<MYSIZE>(nIdx), static_cast<MYSIZE>(nCount));\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tvoid Empty()\r\n\t{\r\n\t\tthis->erase();\r\n\t}\r\n\r\n\tint Find(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx  ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find(szSub);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(CT ch, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find(szSub, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint FindOneOf(PCMYSTR szCharSet) const\r\n\t{\r\n\t\tMYSIZE nIdx = this->find_first_of(szCharSet);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tvoid FormatMessage(PCMYSTR szFormat, ...) throw(std::exception)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFormat);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   szFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\t szTemp == 0 )\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\tvoid FormatMessage(UINT nFormatId, ...) throw(std::exception)\r\n\t{\r\n\t\tMYTYPE sFormat;\r\n\t\tVERIFY(sFormat.LoadString(nFormatId));\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nFormatId);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   sFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\tszTemp == 0)\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n#endif\r\n\r\n\t// GetAllocLength -- an MSVC7 function but it costs us nothing to add it.\r\n\r\n\tint GetAllocLength()\r\n\t{\r\n\t\treturn static_cast<int>(this->capacity());\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// GetXXXX -- Direct access to character buffer\r\n\t// -------------------------------------------------------------------------\r\n\tCT GetAt(int nIdx) const\r\n\t{\r\n\t\treturn this->at(static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT* GetBuffer(int nMinLen=-1)\r\n\t{\r\n\t\treturn GetBuf(nMinLen);\r\n\t}\r\n\r\n\tCT* GetBufferSetLength(int nLen)\r\n\t{\r\n\t\treturn BufferSet(nLen);\r\n\t}\r\n\r\n\t// GetLength() -- MFC docs say this is the # of BYTES but\r\n\t// in truth it is the number of CHARACTERs (chars or wchar_ts)\r\n\tint GetLength() const\r\n\t{\r\n\t\treturn static_cast<int>(this->length());\r\n\t}\r\n\t\r\n\tint Insert(int nIdx, CT ch)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) > this->size()-1 )\r\n\t\t\tthis->append(1, ch);\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), 1, ch);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\tint Insert(int nIdx, PCMYSTR sz)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) >= this->size() )\r\n\t\t\tthis->append(sz, static_cast<MYSIZE>(sslen(sz)));\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), sz);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tbool IsEmpty() const\r\n\t{\r\n\t\treturn this->empty();\r\n\t}\r\n\r\n\tMYTYPE Left(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(0, static_cast<MYSIZE>(nCount)); \r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tbool LoadString(UINT nId)\r\n\t{\r\n\t\treturn this->Load(nId);\r\n\t}\r\n#endif\r\n\r\n\tvoid MakeLower()\r\n\t{\r\n\t\tToLower();\r\n\t}\r\n\r\n\tvoid MakeReverse()\r\n\t{\r\n\t\tstd::reverse(this->begin(), this->end());\r\n\t}\r\n\r\n\tvoid MakeUpper()\r\n\t{ \r\n\t\tToUpper();\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst) const\r\n\t{\r\n\t\treturn Mid(nFirst, this->GetLength()-nFirst);\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst, int nCount) const\r\n\t{\r\n\t\t// CString does range checking here.  Since we're trying to emulate it,\r\n\t\t// we must check too.\r\n\r\n\t\tif ( nFirst < 0 )\r\n\t\t\tnFirst = 0;\r\n\t\tif ( nCount < 0 )\r\n\t\t\tnCount = 0;\r\n\r\n\t\tint nSize = static_cast<int>(this->size());\r\n\r\n\t\tif ( nFirst + nCount > nSize )\r\n\t\t\tnCount = nSize - nFirst;\r\n\r\n\t\tif ( nFirst > nSize )\r\n\t\t\treturn MYTYPE();\r\n\r\n\t\tASSERT(nFirst >= 0);\r\n\t\tASSERT(nFirst + nCount <= nSize);\r\n\r\n\t\treturn this->substr(static_cast<MYSIZE>(nFirst),\r\n\t\t\t\t\t\t\tstatic_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid ReleaseBuffer(int nNewLen=-1)\r\n\t{\r\n\t\tRelBuf(nNewLen);\r\n\t}\r\n\r\n\tint Remove(CT ch)\r\n\t{\r\n\t\tMYSIZE nIdx\t\t= 0;\r\n\t\tint nRemoved\t= 0;\r\n\t\twhile ( (nIdx=this->find_first_of(ch)) != MYBASE::npos )\r\n\t\t{\r\n\t\t\tthis->erase(nIdx, 1);\r\n\t\t\tnRemoved++;\r\n\t\t}\r\n\t\treturn nRemoved;\r\n\t}\r\n\r\n\tint Replace(CT chOld, CT chNew)\r\n\t{\r\n\t\tint nReplaced\t= 0;\r\n\r\n\t\tfor ( MYITER iter=this->begin(); iter != this->end(); iter++ )\r\n\t\t{\r\n\t\t\tif ( *iter == chOld )\r\n\t\t\t{\r\n\t\t\t\t*iter = chNew;\r\n\t\t\t\tnReplaced++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint Replace(PCMYSTR szOld, PCMYSTR szNew)\r\n\t{\r\n\t\tint nReplaced\t\t= 0;\r\n\t\tMYSIZE nIdx\t\t\t= 0;\r\n\t\tMYSIZE nOldLen\t\t= sslen(szOld);\r\n\r\n\t\tif ( 0 != nOldLen )\r\n\t\t{\r\n\t\t\tstatic const CT ch\t= CT(0);\r\n\t\t\tMYSIZE nNewLen\t\t= sslen(szNew);\r\n\t\t\tPCMYSTR szRealNew\t= szNew == 0 ? &ch : szNew;\r\n\r\n\t\t\twhile ( (nIdx=this->find(szOld, nIdx)) != MYBASE::npos )\r\n\t\t\t{\r\n\t\t\t\tthis->replace(this->begin()+nIdx, this->begin()+nIdx+nOldLen,\r\n\t\t\t\t\tszRealNew);\r\n\r\n\t\t\t\tnReplaced++;\r\n\t\t\t\tnIdx += nNewLen;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint ReverseFind(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\t// ReverseFind overload that's not in CString but might be useful\r\n\tint ReverseFind(PCMYSTR szFind, MYSIZE pos=MYBASE::npos) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->rfind(0 == szFind ? MYTYPE() : szFind, pos);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tMYTYPE Right(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(this->size()-static_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid SetAt(int nIndex, CT ch)\r\n\t{\r\n\t\tASSERT(this->size() > static_cast<MYSIZE>(nIndex));\r\n\t\tthis->at(static_cast<MYSIZE>(nIndex))\t\t= ch;\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tBSTR SetSysString(BSTR* pbstr) const\r\n\t{\r\n\t\tostring os;\r\n\t\tssasn(os, *this);\r\n\t\tif ( !::SysReAllocStringLen(pbstr, os.c_str(), os.length()) )\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\r\n\t\tASSERT(*pbstr != 0);\r\n\t\treturn *pbstr;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE SpanExcluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n\tMYTYPE SpanIncluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_not_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n#if defined SS_WIN32 && !defined(UNICODE) && !defined(SS_ANSI)\r\n\r\n\t// CString's OemToAnsi and AnsiToOem functions are available only in\r\n\t// Unicode builds.  However since we're a template we also need a\r\n\t// runtime check of CT and a reinterpret_cast to account for the fact\r\n\t// that CStdStringW gets instantiated even in non-Unicode builds.\r\n\r\n\tvoid AnsiToOem()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::CharToOem(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid OemToAnsi()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::OemToChar(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\t\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Trim and its variants\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& Trim()\r\n\t{\r\n\t\treturn TrimLeft().TrimRight();\r\n\t}\r\n\r\n\tMYTYPE& TrimLeft()\r\n\t{\r\n\t\tthis->erase(this->begin(),\r\n\t\t\tstd::find_if(this->begin(), this->end(), NotSpace<CT>()));\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(CT tTrim)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(tTrim));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(szTrimChars));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& TrimRight()\r\n\t{\r\n\t\t// NOTE:  When comparing reverse_iterators here (MYRITER), I avoid using\r\n\t\t// operator!=.  This is because namespace rel_ops also has a template\r\n\t\t// operator!= which conflicts with the global operator!= already defined\r\n\t\t// for reverse_iterator in the header <utility>.\r\n\t\t// Thanks to John James for alerting me to this.\r\n\r\n\t\tMYRITER it = std::find_if(this->rbegin(), this->rend(), NotSpace<CT>());\r\n\t\tif ( !(this->rend() == it) )\r\n\t\t\tthis->erase(this->rend() - it);\r\n\r\n\t\tthis->erase(!(it == this->rend()) ? this->find_last_of(*it) + 1 : 0);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(CT tTrim)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(tTrim);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(szTrimChars);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid\t\t\tFreeExtra()\r\n\t{\r\n\t\tMYTYPE mt;\r\n\t\tthis->swap(mt);\r\n\t\tif ( !mt.empty() )\r\n\t\t\tthis->assign(mt.c_str(), mt.size());\r\n\t}\r\n\r\n\t// I have intentionally not implemented the following CString\r\n\t// functions.   You cannot make them work without taking advantage\r\n\t// of implementation specific behavior.  However if you absolutely\r\n\t// MUST have them, uncomment out these lines for \"sort-of-like\"\r\n\t// their behavior.  You're on your own.\r\n\r\n//\tCT*\t\t\t\tLockBuffer()\t{ return GetBuf(); }// won't really lock\r\n//\tvoid\t\t\tUnlockBuffer(); { }\t// why have UnlockBuffer w/o LockBuffer?\r\n\r\n\t// Array-indexing operators.  Required because we defined an implicit cast\r\n\t// to operator const CT* (Thanks to Julian Selman for pointing this out)\r\n\r\n\tCT& operator[](int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT& operator[](unsigned int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](unsigned int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n#ifndef SS_NO_IMPLICIT_CAST\r\n\toperator const CT*() const\r\n\t{\r\n\t\treturn this->c_str();\r\n\t}\r\n#endif\r\n\r\n\t// IStream related functions.  Useful in IPersistStream implementations\r\n\r\n#ifdef SS_INC_COMDEF\r\n\r\n\t// struct SSSHDR - useful for non Std C++ persistence schemes.\r\n\ttypedef struct SSSHDR\r\n\t{\r\n\t\tBYTE\tbyCtrl;\r\n\t\tULONG\tnChars;\r\n\t} SSSHDR;\t// as in \"Standard String Stream Header\"\r\n\r\n\t#define SSSO_UNICODE\t0x01\t// the string is a wide string\r\n\t#define SSSO_COMPRESS\t0x02\t// the string is compressed\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSize\r\n\t// REMARKS:\r\n\t//\t\tReturns how many bytes it will take to StreamSave() this CStdString\r\n\t//\t\tobject to an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tULONG StreamSize() const\r\n\t{\r\n\t\t// Control header plus string\r\n\t\tASSERT(this->size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\treturn (this->size() * sizeof(CT)) + sizeof(SSSHDR);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSave\r\n\t// REMARKS:\r\n\t//\t\tSaves this CStdString object to a COM IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamSave(IStream* pStream) const\r\n\t{\r\n\t\tASSERT(size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\tHRESULT hr\t\t= E_FAIL;\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\thdr.byCtrl\t\t= sizeof(CT) == 2 ? SSSO_UNICODE : 0;\r\n\t\thdr.nChars\t\t= this->size();\r\n\r\n\r\n\t\tif ( FAILED(hr=pStream->Write(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write control header, ERR=0x%X\\n\"),hr);\r\n\t\t}\r\n\t\telse if ( empty() )\r\n\t\t{\r\n\t\t\t;\t\t// nothing to write\r\n\t\t}\r\n\t\telse if ( FAILED(hr=pStream->Write(this->c_str(),\r\n\t\t\tthis->size()*sizeof(CT), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write string to stream 0x%X\\n\"), hr);\r\n\t\t}\r\n\r\n\t\treturn hr;\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamLoad\r\n\t// REMARKS:\r\n\t//\t\tThis method loads the object from an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamLoad(IStream* pStream)\r\n\t{\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\tHRESULT hr\t\t\t= E_FAIL;\r\n\r\n\t\tif ( FAILED(hr=pStream->Read(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamLoad: Cant read control header, ERR=0x%X\\n\"), hr);\r\n\t\t}\r\n\t\telse if ( hdr.nChars > 0 )\r\n\t\t{\r\n\t\t\tULONG nRead\t\t= 0;\r\n\t\t\tPMYSTR pMyBuf\t= BufferSet(hdr.nChars);\r\n\r\n\t\t\t// If our character size matches the character size of the string\r\n\t\t\t// we're trying to read, then we can read it directly into our\r\n\t\t\t// buffer. Otherwise, we have to read into an intermediate buffer\r\n\t\t\t// and convert.\r\n\t\t\t\r\n\t\t\tif ( (hdr.byCtrl & SSSO_UNICODE) != 0 )\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(wchar_t);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(wchar_t) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\t\r\n\t\t\t\t\tPWSTR pBufW = reinterpret_cast<PWSTR>(_alloca((nBytes)+1));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufW, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufW, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(char);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(char) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tPSTR pBufA = reinterpret_cast<PSTR>(_alloca(nBytes));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufA, hdr.nChars, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufA, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthis->erase();\r\n\t\t}\r\n\t\treturn hr;\r\n\t}\r\n#endif // #ifdef SS_INC_COMDEF\r\n\r\n#ifndef SS_ANSI\r\n\r\n\t// SetResourceHandle/GetResourceHandle.  In MFC builds, these map directly\r\n\t// to AfxSetResourceHandle and AfxGetResourceHandle.  In non-MFC builds they\r\n\t// point to a single static HINST so that those who call the member\r\n\t// functions that take resource IDs can provide an alternate HINST of a DLL\r\n\t// to search.  This is not exactly the list of HMODULES that MFC provides\r\n\t// but it's better than nothing.\r\n\r\n\t#ifdef _MFC_VER\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tAfxSetResourceHandle(hNew);\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn AfxGetResourceHandle();\r\n\t\t}\r\n\t#else\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tSSResourceHandle() = hNew;\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn SSResourceHandle();\r\n\t\t}\r\n\t#endif\r\n\r\n#endif\r\n};\r\n\r\n// -----------------------------------------------------------------------------\r\n// MSVC USERS: HOW TO EXPORT CSTDSTRING FROM A DLL\r\n//\r\n// If you are using MS Visual C++ and you want to export CStdStringA and\r\n// CStdStringW from a DLL, then all you need to\r\n//\r\n//\t\t1.\tmake sure that all components link to the same DLL version\r\n//\t\t\tof the CRT (not the static one).\r\n//\t\t2.\tUncomment the 3 lines of code below\r\n//\t\t3.\t#define 2 macros per the instructions in MS KnowledgeBase\r\n//\t\t\tarticle Q168958.  The macros are:\r\n//\r\n//\t\tMACRO\t\tDEFINTION WHEN EXPORTING\t\tDEFINITION WHEN IMPORTING\r\n//\t\t-----\t\t------------------------\t\t-------------------------\r\n//\t\tSSDLLEXP\t(nothing, just #define it)\t\textern\r\n//\t\tSSDLLSPEC\t__declspec(dllexport)\t\t\t__declspec(dllimport)\r\n//\r\n//\t\tNote that these macros must be available to ALL clients who want to \r\n//\t\tlink to the DLL and use the class.  If they \r\n//\r\n// A word of advice: Don't bother.\r\n//\r\n// Really, it is not necessary to export CStdString functions from a DLL.  I\r\n// never do.  In my projects, I do generally link to the DLL version of the\r\n// Standard C++ Library, but I do NOT attempt to export CStdString functions.\r\n// I simply include the header where it is needed and allow for the code\r\n// redundancy.\r\n//\r\n// That redundancy is a lot less than you think.  This class does most of its\r\n// work via the Standard C++ Library, particularly the base_class basic_string<>\r\n// member functions.  Most of the functions here are small enough to be inlined\r\n// anyway.  Besides, you'll find that in actual practice you use less than 1/2\r\n// of the code here, even in big projects and different modules will use as\r\n// little as 10% of it.  That means a lot less functions actually get linked\r\n// your binaries.  If you export this code from a DLL, it ALL gets linked in.\r\n//\r\n// I've compared the size of the binaries from exporting vs NOT exporting.  Take\r\n// my word for it -- exporting this code is not worth the hassle.\r\n//\r\n// -----------------------------------------------------------------------------\r\n//#pragma warning(disable:4231) // non-standard extension (\"extern template\")\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<char>;\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<wchar_t>;\r\n\r\n\r\n// =============================================================================\r\n//\t\t\t\t\t\tEND OF CStdStr INLINE FUNCTION DEFINITIONS\r\n// =============================================================================\r\n\r\n//\tNow typedef our class names based upon this humongous template\r\n\r\ntypedef CStdStr<char>\t\tCStdStringA;\t// a better std::string\r\ntypedef CStdStr<wchar_t>\tCStdStringW;\t// a better std::wstring\r\ntypedef CStdStr<OLECHAR>\tCStdStringO;\t// almost always CStdStringW\r\n\r\n// -----------------------------------------------------------------------------\r\n// CStdStr addition functions defined as inline\r\n// -----------------------------------------------------------------------------\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringA& s2)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, CStdStringA::value_type t)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCSTR pA)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(pA);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(PCSTR pA, const CStdStringA& sA)\r\n{\r\n\tCStdStringA sRet;\r\n\tCStdStringA::size_type nObjSize = sA.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringA::size_type>(sslen(pA));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pA);\r\n\tsRet.append(sA);\r\n\treturn sRet;\r\n}\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringW& s2)\r\n{\r\n\treturn s1 + CStdStringA(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringW& s2)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCWSTR pW)\r\n{\r\n\treturn s1 + CStdStringA(pW);\r\n}\r\n\r\n#ifdef UNICODE\r\n\tinline CStdStringW operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringW(pW) + CStdStringW(SSREF(sA));\r\n\t}\r\n\tinline CStdStringW operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn CStdStringW(pA) + sW;\r\n\t}\r\n#else\r\n\tinline CStdStringA operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringA(pW) + sA;\r\n\t}\r\n\tinline CStdStringA operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn pA + CStdStringA(sW);\r\n\t}\r\n#endif\r\n\r\n// ...Now the wide string versions.\r\ninline CStdStringW operator+(const CStdStringW& s1, CStdStringW::value_type t)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCWSTR pW)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(pW);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(PCWSTR pW, const CStdStringW& sW)\r\n{\r\n\tCStdStringW sRet;\r\n\tCStdStringW::size_type nObjSize = sW.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringW::size_type>(sslen(pW));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pW);\r\n\tsRet.append(sW);\r\n\treturn sRet;\r\n}\r\n\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringA& s2)\r\n{\r\n\treturn s1 + CStdStringW(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCSTR pA)\r\n{\r\n\treturn s1 + CStdStringW(pA);\r\n}\r\n\r\n\r\n// New-style format function is a template\r\n\r\n#ifdef SS_SAFE_FORMAT\r\n\r\ntemplate<>\r\nstruct FmtArg<CStdStringA>\r\n{\r\n    explicit FmtArg(const CStdStringA& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringA& a_;\r\nprivate:\r\n    FmtArg<CStdStringA>& operator=(const FmtArg<CStdStringA>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<CStdStringW>\r\n{\r\n    explicit FmtArg(const CStdStringW& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringW& a_;\r\nprivate:\r\n    FmtArg<CStdStringW>& operator=(const FmtArg<CStdStringW>&) { return *this; }\r\n};\r\n\r\ntemplate<>\r\nstruct FmtArg<std::string>\r\n{\r\n    explicit FmtArg(const std::string& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const std::string& a_;\r\nprivate:\r\n    FmtArg<std::string>& operator=(const FmtArg<std::string>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<std::wstring>\r\n{\r\n    explicit FmtArg(const std::wstring& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const std::wstring& a_;\r\nprivate:\r\n    FmtArg<std::wstring>& operator=(const FmtArg<std::wstring>&) {return *this;}\r\n};\r\n#endif // #ifdef SS_SAFEFORMAT\r\n\r\n#ifndef SS_ANSI\r\n\t// SSResourceHandle: our MFC-like resource handle\r\n\tinline HMODULE& SSResourceHandle()\r\n\t{\r\n\t\tstatic HMODULE hModuleSS\t= GetModuleHandle(0);\r\n\t\treturn hModuleSS;\r\n\t}\r\n#endif\r\n\r\n\r\n// In MFC builds, define some global serialization operators\r\n// Special operators that allow us to serialize CStdStrings to CArchives.\r\n// Note that we use an intermediate CString object in order to ensure that\r\n// we use the exact same format.\r\n\r\n#ifdef _MFC_VER\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp\t= strA;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp\t= strW;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrA = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrW = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n#endif\t// #ifdef _MFC_VER -- (i.e. is this MFC?)\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// GLOBAL FUNCTION:  WUFormat\r\n//\t\tCStdStringA WUFormat(UINT nId, ...);\r\n//\t\tCStdStringA WUFormat(PCSTR szFormat, ...);\r\n//\r\n// REMARKS:\r\n//\t\tThis function allows the caller for format and return a CStdStringA\r\n//\t\tobject with a single line of code.\r\n// -----------------------------------------------------------------------------\r\n\r\ninline CStdStringA WUFormatA(PCSTR szFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szFormat);\r\n\tCStdStringA strOut;\r\n\tstrOut.FormatV(szFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\ninline CStdStringW WUFormatW(PCWSTR szwFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szwFormat);\r\n\tCStdStringW strOut;\r\n\tstrOut.FormatV(szwFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\n#ifdef SS_ANSI\r\n#else\r\n\tinline CStdStringA WUFormatA(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringA strFmt;\r\n\t\tCStdStringA strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n\r\n\tinline CStdStringW WUFormatW(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringW strFmt;\r\n\t\tCStdStringW strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n#endif // #ifdef SS_ANSI\r\n\r\n\r\n\r\n#if defined(SS_WIN32) && !defined (SS_ANSI)\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: WUSysMessage\r\n\t//\t CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//\t CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t This function simplifies the process of obtaining a string equivalent\r\n\t//\t of a system error code returned from GetLastError().  You simply\r\n\t//\t supply the value returned by GetLastError() to this function and the\r\n\t//\t corresponding system string is returned in the form of a CStdStringA.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t dwError - a DWORD value representing the error code to be translated\r\n\t//\t dwLangId - the language id to use.  defaults to english.\r\n\t//\r\n\t// RETURN VALUE: \r\n\t//\t a CStdStringA equivalent of the error code.  Currently, this function\r\n\t//\t only returns either English of the system default language strings.  \r\n\t// -------------------------------------------------------------------------\r\n\t#define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT)\r\n\tinline CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatA(\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatA(\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n\tinline CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tWCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatW(L\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatW(L\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n#endif\r\n\r\n// Define TCHAR based friendly names for some of these functions\r\n\r\n#ifdef UNICODE\r\n\t//#define CStdString\t\t\t\tCStdStringW\r\n\ttypedef CStdStringW\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageW\r\n\t#define WUFormat\t\t\t\tWUFormatW\r\n#else\r\n\t//#define CStdString\t\t\t\tCStdStringA\r\n\ttypedef CStdStringA\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageA\r\n\t#define WUFormat\t\t\t\tWUFormatA\r\n#endif\r\n\r\n// ...and some shorter names for the space-efficient\r\n\r\n#define WUSysMsg\t\t\t\t\tWUSysMessage\r\n#define WUSysMsgA\t\t\t\t\tWUSysMessageA\r\n#define WUSysMsgW\t\t\t\t\tWUSysMessageW\r\n#define WUFmtA\t\t\t\t\t\tWUFormatA\r\n#define\tWUFmtW\t\t\t\t\t\tWUFormatW\r\n#define WUFmt\t\t\t\t\t\tWUFormat\r\n#define WULastErrMsg()\t\t\t\tWUSysMessage(::GetLastError())\r\n#define WULastErrMsgA()\t\t\t\tWUSysMessageA(::GetLastError())\r\n#define WULastErrMsgW()\t\t\t\tWUSysMessageW(::GetLastError())\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// FUNCTIONAL COMPARATORS:\r\n// REMARKS:\r\n//\t\tThese structs are derived from the std::binary_function template.  They\r\n//\t\tgive us functional classes (which may be used in Standard C++ Library\r\n//\t\tcollections and algorithms) that perform case-insensitive comparisons of\r\n//\t\tCStdString objects.  This is useful for maps in which the key may be the\r\n//\t\t proper string but in the wrong case.\r\n// -----------------------------------------------------------------------------\r\n#define StdStringLessNoCaseW\t\tSSLNCW\t// avoid VC compiler warning 4786\r\n#define StdStringEqualsNoCaseW\t\tSSENCW\t\t\r\n#define StdStringLessNoCaseA\t\tSSLNCA\t\t\r\n#define StdStringEqualsNoCaseA\t\tSSENCA\t\t\r\n\r\n#ifdef UNICODE\r\n\t#define StdStringLessNoCase\t\tSSLNCW\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCW\t\t\r\n#else\r\n\t#define StdStringLessNoCase\t\tSSLNCA\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCA\t\t\r\n#endif\r\n\r\nstruct StdStringLessNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\nstruct StdStringLessNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\n\r\n// If we had to define our own version of TRACE above, get rid of it now\r\n\r\n#ifdef TRACE_DEFINED_HERE\r\n\t#undef TRACE\r\n\t#undef TRACE_DEFINED_HERE\r\n#endif\r\n\r\n\r\n// These std::swap specializations come courtesy of Mike Crusader. \r\n\r\n//namespace std\r\n//{\r\n//\tinline void swap(CStdStringA& s1, CStdStringA& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//\ttemplate<>\r\n//\tinline void swap(CStdStringW& s1, CStdStringW& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//}\r\n\r\n// Turn back on any Borland warnings we turned off.\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option pop  // Turn back on inline function warnings\r\n//\t#pragma warn +inl   // Turn back on inline function warnings\r\n#endif\r\n\r\n#endif\t// #ifndef STDSTRING_H\r\n"
  },
  {
    "path": "plugins/scrobsub/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by Bootstrap.rc\r\n//\r\n#define IDD_PROGRESSFORM                101\r\n#define IDC_PROGRESS1                   1002\r\n#define IDC_BUTTONOK                    1005\r\n#define IDC_BUTTONCANCEL                1006\r\n#define IDC_LABEL                       1007\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        101\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1001\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/scrobsub/resource1.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by Bootstrap.rc\r\n//\r\n#define IDD_PROGRESSFORM                101\r\n#define IDC_PROGRESS1                   1002\r\n#define IDC_BUTTONOK                    1005\r\n#define IDC_BUTTONCANCEL                1006\r\n#define IDC_LABEL                       1007\r\n#define IDC_LABEL1                      1007\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        101\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1001\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/scrobsub/tests/BlockingClient.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"../BlockingClient.h\"\n#include <iostream>\n\nstatic BlockingClient bc;\nvoid test( const char * const domain );\n\nint main( int argc, char* argv[] )\n{\n    test( \"www.last.fm\" );\n    test( \"87.117.229.100\" );\n    std::cout << \"Finish\" << std::endl;\n    return 0;\n}\n\nvoid test( const char* const domain )\n{\n    std::string input;\n    try\n    {\n        bc.Connect( domain, 80 );\n        std::string httpRequest = \"GET / HTTP/1.1\\n\"\n                                  \"host: \";\n        httpRequest += domain;\n        httpRequest += \"\\r\\n\\r\\n\";\n\n\n        bc.Send( httpRequest );\n        bc.Receive( input );\n    }\n    catch( BlockingClient::NetworkException& e )\n    {\n        std::cout << \"(F) Could not connect to \" << domain << \". Exception \" << e.what() << \" caught.\" << std::endl;\n        return;\n    }\n    \n    std::string httpOkResponse10 = \"HTTP/1.0\";\n    std::string httpOkResponse11 = \"HTTP/1.1\";\n    std::string httpResponse = input.substr( 0, httpOkResponse10.length() );\n    if( httpResponse != httpOkResponse10 &&\n        httpResponse != httpOkResponse11 )\n    {\n        std::cout << \"(F) Could not connect to \" << domain << \". Response = \" << input << std::endl;\n    }\n    else\n    {\n        std::cout << \"(OK) Response from \" << domain << \" = \" << httpResponse << std::endl;\n    }\n\n    bc.ShutDown();\n}\n"
  },
  {
    "path": "plugins/scrobsub/tests/EncodingUtils.cpp",
    "content": "/* Copyright 205-2009, Last.fm Ltd. <client@last.fm>                       \n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *     * Redistributions of source code must retain the above copyright\n *       notice, this list of conditions and the following disclaimer.\n *     * Redistributions in binary form must reproduce the above copyright\n *       notice, this list of conditions and the following disclaimer in the\n *       documentation and/or other materials provided with the distribution.\n *     * Neither the name of the <organization> nor the\n *       names of its contributors may be used to endorse or promote products\n *       derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY <copyright holder> ''AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \"../EncodingUtils.h\"\n#include <iostream>\n#include <wchar.h>\n\nvoid UnicodeToUtf8();\nvoid AnsiToUtf8();\nvoid Utf8ToAnsi();\n\nint main( int argc, char* argv[] )\n{\n    UnicodeToUtf8();\n    AnsiToUtf8();\n    Utf8ToAnsi();\n    char c;\n    std::cin >> c;\n    return 0;\n}\n\nvoid Utf8ToAnsi()\n{\n    char utf8[] = { 'a', 0xC2, 0xA1, 0x00 };\n    char expectedAnsi[] = { 'a', 0xA1, 0x00 };\n    \n    std::string Ansi = EncodingUtils::Utf8ToAnsi( utf8 );\n\n    if( Ansi.compare( expectedAnsi ) == 0 )\n    {\n        std::cout << \"(OK) UTF8 -> Ansi conversion\" << std::endl;\n    }\n    else\n    {\n        std::cout << \"(E) UTF8 -> Ansi conversion failed:\" << std::endl\n                  << \"UTF8 = \" << utf8 << std::endl\n                  << \"Converted Ansi = \" << Ansi << std::endl;\n    }\n\n}\n\nvoid AnsiToUtf8()\n{\n    char ansi[] = { 0xA1, 0x00 };\n    char expectedUtf8[] = { 0xC2, 0xA1, 0x00 };\n    char utf8[ 8 ];\n    EncodingUtils::AnsiToUtf8( ansi, \n                               utf8, \n                               ( strlen( ansi ) + 1 ) * 4 );\n    \n    if( strcmp( utf8, expectedUtf8 ) == 0 )\n    {\n        std::cout << \"(OK) Ansi -> UTF8 conversion\" << std::endl;\n    }\n    else\n    {\n        std::cout << \"(E) Ansi -> UTF8 conversion failed:\" << std::endl\n                  << \"Ansi = \" << ansi << std::endl\n                  << \"Converted UTF8 = \" << utf8 << std::endl;\n    }\n\n\n}\n\nvoid UnicodeToUtf8()\n{\n    wchar_t unicode[] = { 0xA1, 0x00 };\n    char expectedUtf8[] = { 0xC2, 0xA1, 0x00 };\n    char utf8[ 8 ];\n    EncodingUtils::UnicodeToUtf8( unicode, \n                                  wcslen( unicode ) + 1, \n                                  utf8, \n                                  ( wcslen( unicode ) + 1 ) * 4 );\n    \n    if( strcmp( utf8, expectedUtf8 ) == 0 )\n    {\n        std::cout << \"(OK) Unicode -> UTF8 conversion\" << std::endl;\n    }\n    else\n    {\n        std::cout << \"(E) Unicode -> UTF8 conversion failed:\" << std::endl\n                  << \"Unicode = \";\n        std::wcout << unicode << std::endl;\n        std::cout << \"Converted UTF8 = \" << utf8 << std::endl;\n    }\n\n}\n"
  },
  {
    "path": "plugins/winamp/AutoChar.h",
    "content": "#ifndef NULLSOFT_AUTOCHARH\r\n#define NULLSOFT_AUTOCHARH\r\n#ifdef WIN32\r\n#include <windows.h>\r\n\r\ninline char *AutoCharDup(const wchar_t *convert, UINT codePage = CP_ACP, UINT flags=0)\r\n{\r\n\tif (!convert)\r\n\t\treturn 0;\r\n\tint size = WideCharToMultiByte(codePage, 0, convert, -1, 0, 0, NULL, NULL);\r\n\r\n\tif (!size)\r\n\t\treturn 0;\r\n\r\n\tchar *narrow = (char *)malloc(size*sizeof(char));\r\n\r\n\tif (!WideCharToMultiByte(codePage, flags, convert, -1, narrow, size, NULL, NULL))\r\n\t{\r\n\t\tfree(narrow);\r\n\t\tnarrow=0;\r\n\t}\r\n\treturn narrow;\r\n}\r\n\r\nclass AutoChar\r\n{\r\npublic:\r\n\r\n\tAutoChar(const wchar_t *convert, UINT codePage = CP_ACP, UINT flags=0) : narrow(0)\r\n\t{\r\n\t\tnarrow = AutoCharDup(convert, codePage, flags);\r\n\t}\r\n\t~AutoChar()\r\n\t{\r\n\t\tfree(narrow);\r\n\t\tnarrow=0;\r\n\t}\r\n\toperator const char *()\r\n\t{\r\n\t\treturn narrow;\r\n\t}\r\n\toperator char *()\r\n\t{\r\n\t\treturn narrow;\r\n\t}\r\nprivate:\r\n\tchar *narrow;\r\n};\r\n#elif defined(__APPLE__)\r\n#include <stdlib.h>\r\n\r\ninline char *AutoCharDup(const wchar_t *convert)\r\n{\r\n\tif (!convert)\r\n\t\treturn 0;\r\n\r\n\tsize_t size = wcslen(convert)+1;\r\n\r\n\tif (!size)\r\n\t\treturn 0;\r\n\r\n\tchar *narrow = (char *)malloc(size*sizeof(char));\r\n\r\n\tif (wcstombs(narrow, convert, size) == (size_t)-1)\r\n\t{\r\n\t\tfree(narrow);\r\n\t\tnarrow=0;\r\n\t}\r\n\treturn narrow;\r\n}\r\n\r\n\r\nclass AutoChar\r\n{\r\npublic:\r\n\r\n\tAutoChar(const wchar_t *convert) : narrow(0)\r\n\t{\r\n\t\tnarrow = AutoCharDup(convert);\r\n\t}\r\n\t~AutoChar()\r\n\t{\r\n\t\tfree(narrow);\r\n\t\tnarrow=0;\r\n\t}\r\n\toperator const char *()\r\n\t{\r\n\t\treturn narrow;\r\n\t}\r\n\toperator char *()\r\n\t{\r\n\t\treturn narrow;\r\n\t}\r\nprivate:\r\n\tchar *narrow;\r\n};\r\n#endif\r\n\r\n#endif"
  },
  {
    "path": "plugins/winamp/Dbg.h",
    "content": "/*##############################################\r\n##\r\n## Module\t\t\t\t: CDebug\r\n## Description\t: Thread-safe logging routines for logging \r\n##                from multiple processes to one log file. \r\n##\r\n##               \tClass includes printf-style formatted output \r\n##                routines, as well as timestamping of entries, \r\n##                process id, and process execution time.\r\n##\r\n##\t\t\t\t\t\t\t\tAlso includes maxfilesize attribute which restricts\r\n##\t\t\t\t\t\t\t\tthe size of the file. Setting this to 0 disables logging\r\n##\t\t\t\t\t\t\t\tsetting it to -1 disables max size.\r\n##\r\n## Author(s)\t\t: Spib\r\n##\r\n##############################################*/\r\n\r\n#ifndef ______DBG_H______\r\n#define ______DBG_H______\r\n\r\n#define DEBUG_DETAIL\t\t1\t\t\t// Low level detailed info\r\n#define DEBUG_FLOW\t\t\t3\t\t\t// Low level program flow Info\r\n#define DEBUG_INFO\t\t\t5\t\t\t// General Info\r\n#define DEBUG_ERROR_NC\t7\t\t\t// Non-Critical Error\r\n#define DEBUG_RQD\t\t\t\t8\t\t\t// Required Info\r\n#define DEBUG_ERROR\t\t\t9\t\t\t// Critical Error\r\n\r\n#define USE_DEBUG_PRINTF\r\n\r\n#ifdef USE_DEBUG_PRINTF\r\n\r\n//\tMacro definitions\r\n///////////////////////////\r\n#define IFDEBUG( doit )\tdoit\r\n\r\n#define DEBUG_INIT\t\t\t\t\tdebug.Init\r\n#define DEBUG_ENABLE\t\t\t\tdebug.Enable\r\n#define DEBUG_IS_ENABLED\t\tdebug.IsEnabled\r\n#define DEBUG_GET_LEVEL\t\t\tdebug.GetLevel\r\n#define DEBUG_SET_LEVEL\t\t\tdebug.SetLevel\r\n#define DEBUG_SET_MAXSIZE\t\tdebug.SetMaxFileSize\r\n#define DEBUG_GET_MAXSIZE\t\tdebug.GetMaxFileSize\r\n#define DEBUG_GET_FILEPATH\tdebug.GetLogFilePath\r\n#define PRINTF\t\t\t\t\t\t\tdebug.printf\r\n#define SHOW_LASTERROR\t\t\tdebug.ShowLastError();\r\n#define CLOSE_LOG\t\t\t\t\t\tdebug.CloseLog();\r\n\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Class        : CDebugPrintf\r\n *  Prototype    : class CDebugPrintf\r\n *  Description  : \r\n *  Parent class : \r\n *  History      : \r\n */\r\nclass CDebug\r\n{\r\npublic:\r\n\tCDebug();\r\n\tvirtual ~CDebug();\r\n\r\n\tvoid Init(const char * strFileName, BOOL bOverWrite = TRUE, BOOL bEnable = TRUE, BOOL bUseXML = FALSE);\r\n\r\n\tvoid printf(int nLevel, const char * module, const char *fmt, ... );\r\n\r\n\tinline BOOL SetLevel(int nLevel)\r\n\t{\r\n\t\tif(nLevel <= DEBUG_ERROR && nLevel >= DEBUG_DETAIL)\r\n\t\t{\r\n\t\t\tm_nLogLevel = nLevel;\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tBOOL SetMaxFileSize(int nSize)\r\n\t{\r\n\t\tif(nSize >= 0)\r\n\t\t{\r\n\t\t\tif(nSize == 0)\r\n\t\t\t\tEnable(FALSE);\r\n\t\t\telse\r\n\t\t\t\tEnable(TRUE);\r\n\r\n\t\t\tm_nMaxFileSize = (nSize * 1024);\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t\telse if(nSize == -1)\r\n\t\t{\r\n\t\t\tm_nMaxFileSize = -1;\r\n\t\t\tEnable(TRUE);\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\r\n\t\tCheckFileSize();\r\n\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tinline void Enable(BOOL bEnable = TRUE)\r\n\t{\r\n\t\tm_bEnabled = bEnable;\r\n\t}\r\n\r\n\tvoid\t\t\t\t\t\t\tCloseLog(); \r\n\tvoid\t\t\t\t\t\t\tShowLastError();\r\n\tBOOL\t\t\t\t\t\t\tIsEnabled(){return m_bEnabled;}\r\n\r\n\tint\t\t\t\t\t\t\t\tGetLevel(){return m_nLogLevel;}\r\n\tDWORD\t\t\t\t\t\t\tGetMaxFileSize(){return m_nMaxFileSize;}\r\n\tchar*\t\t\t\t\t\t\tGetLogFilePath(){return m_strFilePath;}\r\n\r\nprivate:\r\n\tBOOL\t\t\t\t\t\t\tOpenLogFile(BOOL bOverWrite = TRUE);\r\n\tvoid\t\t\t\t\t\t\tWriteHeader(BOOL bNewFile = TRUE);\r\n\tvoid\t\t\t\t\t\t\tCheckFileSize();\r\n\tvoid\t\t\t\t\t\t\tReplaceXMLChars(const char* strInput, int nLen, char* strOutput);\r\n\r\n\tHANDLE\t\t\t\t\t\tm_hFile;\t\t\t\t\t\t\t\t\t// Log-file handle\r\n\tCRITICAL_SECTION\tm_hLock;\t\t\t\t\t\t\t\t\t// Lock for thread-safe access\r\n\tchar\t\t\t\t\t\t\tm_strFilePath[MAX_PATH];\t// File Path\r\n\r\n\tDWORD\t\t\t\t\t\t\tm_dwStartTime;\t\t\t\t\t\t// Application start time \r\n\tint\t\t\t\t\t\t\t\tm_nLogLevel;\t\t\t\t\t\t\t// Log Level\r\n\tBOOL\t\t\t\t\t\t\tm_bEnabled;\t\t\t\t\t\t\t\t// Enable / Disable Debug\r\n\tlong\t\t\t\t\t\t\tm_nMaxFileSize;\t\t\t\t\t// Maximum size of log (in bytes)\r\n\tBOOL\t\t\t\t\t\t\tm_bUseXML;\t\t\t\t\t\t\t\t// Output the data as XML?\r\n};\r\n\r\nextern CDebug debug;\r\n\r\n\r\n#else\r\n\r\n#define IFDEBUG( doit )\t\r\n\r\n#define SLASH /\r\n#define COMMENT ;SLASH/\r\n\r\n#define PRINTF\t\t\tCOMMENT\r\n#define SHOW_CONSOLE\tCOMMENT\r\n#define HIDE_CONSOLE\tCOMMENT\r\n#define SHOW_LASTERROR\tCOMMENT\r\n#define CLOSE_LOG\t\tCOMMENT\r\n\r\n#endif\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "plugins/winamp/GEN.H",
    "content": "typedef struct {\r\n\tint version;\r\n\tchar *description;\r\n\tint (*init)();\r\n\tvoid (*config)();\r\n\tvoid (*quit)();\r\n\tHWND hwndParent;\r\n\tHINSTANCE hDllInstance;\r\n} winampGeneralPurposePlugin;\r\n\r\n#define GPPHDR_VER 0x10\r\n\r\nextern winampGeneralPurposePlugin *gen_plugins[256];\r\ntypedef winampGeneralPurposePlugin * (*winampGeneralPurposePluginGetter)();"
  },
  {
    "path": "plugins/winamp/Gen_AudioScrobbler.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"Resource.h\"\r\n#include \"Gen_AudioScrobbler.h\"\r\n#include \"WinampScrobbler.h\"\r\n#include \"wa_hotkeys.h\"\r\n\r\n#define WA_DLG_IMPLEMENT\r\n#include \"wa_dlg.h\"\r\n\r\nCComModule\t_Module;\r\nCWinampScrobbler theScrobbler;\r\nint nIdTimer = 0;\r\n\r\n// Semaphore stuff\r\nstatic char szSemName[] = \"AudioscrobblerSemaphore\";\r\nHANDLE hSem;\r\n\r\n// Status Window Stuff\r\nHWND g_hwndParent = NULL;\r\nHINSTANCE g_hDllInstance = NULL; \r\nHWND wa2 = 0;\r\n#ifdef STRICT\r\n#define PROC WNDPROC\r\n#else\r\n#define PROC FARPROC\r\n#endif\r\nPROC frameProc = 0;\r\nPROC winampProc = 0;\r\n#define AS_MENU_TEXT\t\t\tAUDIOSCROBBLER_APPNAME \"\\tShift+H\"\r\n#define STATUS_TIMER\t\t\t1\r\n#define STATUS_TIMER_INTERVAL\t1000\r\n#define AS_MENU_ID\t\t\t\t24767\r\n\r\nBOOL APIENTRY DllMain( HANDLE hModule, \r\n                       DWORD  ul_reason_for_call, \r\n                       LPVOID lpReserved\r\n\t\t\t\t\t )\r\n{\r\n    switch (ul_reason_for_call)\r\n\t{\r\n\t\tcase DLL_PROCESS_ATTACH:\r\n\t\tcase DLL_THREAD_ATTACH:\r\n\t\tcase DLL_THREAD_DETACH:\r\n\t\tcase DLL_PROCESS_DETACH:\r\n\t\t\tbreak;\r\n    }\r\n    return TRUE;\r\n}\r\n\r\n\r\n// Global Functions\r\nvoid config();\r\nvoid quit();\r\nint init();\r\nint mlinit();\r\n\r\nvoid config()\r\n{\r\n}\r\n\r\nvoid quit()\r\n{\r\n\ttry\r\n\t{\r\n        // Before shutdown remove semaphore\r\n\t\tReleaseSemaphore (hSem, 1, NULL);\r\n\t\tCloseHandle (hSem);\r\n\r\n\t\ttheScrobbler.StopScrobbling();\r\n\t}\r\n\tcatch (std::exception& e)\r\n\t{\r\n\t\tPRINTF(DEBUG_ERROR, \"quit()\", e.what());\r\n\t}\r\n\r\n\t_Module.Term();\r\n}\r\n\r\n// Gets the playlist window\r\nHWND GetPEWindow(HWND hwndWinamp)\r\n{\r\n\tHWND hWnd = NULL;\r\n\r\n\t// First try Winamp internal handle\r\n\tif ((hWnd = (HWND)SendMessage(hwndWinamp,WM_WA_IPC,IPC_GETWND_PE,IPC_GETWND)) == NULL)\r\n\t\tif((hWnd = (HWND)FindWindow(\"Winamp PE\", NULL)) == NULL)\r\n\t\t\thWnd = NULL;\r\n\r\n\treturn hWnd;\r\n}\r\n\r\nLRESULT (CALLBACK *lpWndProcOldPE)(HWND, UINT, WPARAM, LPARAM) = NULL;\r\nLRESULT (CALLBACK *lpWndProcOldParent)(HWND, UINT, WPARAM, LPARAM) = NULL;\r\n\r\n// Subclassed PE window procedure, calls the default lpWndProcOldPE if we're not\r\n// handling the message\r\nLRESULT CALLBACK WndProcPE(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tif(theScrobbler.WinampPEMessage(message, wParam, lParam))\r\n\t{\r\n\t\treturn CallWindowProc(lpWndProcOldPE, hwnd, message, wParam, lParam);\r\n\t}\r\n\t\r\n\treturn 0L;\r\n}\r\n\r\n// Subclassed main window procedure, calls the default lpWndProcOldParent if we're not\r\n// handling the message\r\nLRESULT CALLBACK WndProcParent(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n    if( theScrobbler.WinampMessage( message, wParam, lParam ) )\r\n    {\r\n        return CallWindowProc(lpWndProcOldParent, hwnd, message, wParam, lParam);\r\n    }\r\n\r\n    return 0L;\r\n}\r\n\r\n\r\n// Helper method for subclassing Window procedure. If we're not using the correct A/W\r\n// versions, Unicode tracks won't display properly in the taskbar.\r\nWNDPROC SetWndSubClass( HWND hwnd, WNDPROC newproc, WNDPROC* oldproc )\r\n{\r\n    if ( IsWindowUnicode(hwnd) )\r\n    {\r\n        *oldproc = (WNDPROC)GetWindowLongPtrW( hwnd, GWL_WNDPROC );\r\n        return (WNDPROC)SetWindowLongPtrW( hwnd, GWL_WNDPROC, (LONG_PTR)newproc );\r\n    }\r\n    else\r\n    {\r\n        *oldproc = (WNDPROC)GetWindowLongPtrA( hwnd, GWL_WNDPROC );\r\n        return (WNDPROC)SetWindowLongPtrA( hwnd, GWL_WNDPROC, (LONG_PTR)newproc );\r\n    }\r\n}\r\n\r\n/*****************************************************\r\n******************************************************\r\n***\r\n*** G E N E R A L   P L U G I N\r\n***\r\n******************************************************\r\n*****************************************************/\r\nwinampGeneralPurposePlugin plugin =\r\n{\r\n\tGPPHDR_VER,\r\n\t\"\",\r\n\tinit,\r\n\tconfig,\r\n\tquit,\r\n};\r\n\r\n// Entry point for a general plugin\r\nextern \"C\" __declspec( dllexport ) winampGeneralPurposePlugin * winampGetGeneralPurposePlugin()\r\n{\r\n\treturn &plugin;\r\n}\r\n\r\n// Winamp calls this with plugin populated after the above has been called\r\nint init()\r\n{\r\n\tstatic char c[512];\r\n\tchar filename[512];\r\n\tHWND hWnd = NULL;\r\n\r\n\tg_hDllInstance = plugin.hDllInstance;\r\n\tg_hwndParent = plugin.hwndParent;\r\n\r\n\t_Module.Init(NULL, plugin.hDllInstance, &LIBID_ATLLib);\r\n\r\n\t// Handle Multiple Instances\r\n\thSem = CreateSemaphore (NULL, 1, 1,szSemName);\r\n    if (WaitForSingleObject (hSem, 0) == WAIT_TIMEOUT)\r\n\t{\r\n\t\tCloseHandle (hSem);\r\n\t\treturn -1;\r\n\t}\r\n\r\n    int version = WINAMP_VERSION_MAJOR( SendMessage( plugin.hwndParent,WM_WA_IPC,0,IPC_GETVERSION) );\r\n\r\n    // If the version is earlier than 5, we need to use a method of track play detection\r\n    // that involves overriding the playlist editor's event handler.\r\n    if ( version < 5 )\r\n    {\r\n        hWnd = GetPEWindow(plugin.hwndParent);\r\n        if ( hWnd != NULL )\r\n\t    {\r\n            // Stores previous playlist wndproc and sets new one to WndProcPE\r\n\t\t    SetWndSubClass( hWnd, WndProcPE, &lpWndProcOldPE );\r\n   \t    }\r\n  \t    else\r\n    \t\tPRINTF(DEBUG_ERROR, \"Gen_AudioScrobbler::init\", \"Failed to find Winamp PE Window\");\r\n\t}\r\n\r\n    // From version 5, Winamp supplies a better way to detect track plays that goes\r\n    // through the main window's event handler. From 5.5 the old PE method does\r\n    // not even work any longer.\r\n    if ( version >= 5 && plugin.hwndParent != NULL )\r\n    {\r\n        // Stores previous playlist wndproc and sets new one to WndProcParent\r\n        SetWndSubClass( plugin.hwndParent, WndProcParent, &lpWndProcOldParent );\r\n    }\r\n\r\n\tGetModuleFileName(plugin.hDllInstance,filename,sizeof(filename));\r\n\r\n    // Launch config if we can't start scrobbling\r\n\tif(!theScrobbler.StartScrobbling(plugin.hDllInstance, \r\n\t\t\t\t\t\t\t\t\tplugin.hwndParent, \r\n\t\t\t\t\t\t\t\t\tNULL,\r\n\t\t\t\t\t\t\t\t\tfilename))\r\n\t\tconfig();\r\n\t\r\n\tsprintf((plugin.description=c), \"%s v%s\", theScrobbler.GetAppName().c_str(), theScrobbler.GetVersionString().c_str());\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n/*****************************************************\r\n******************************************************\r\n***\r\n*** M E D I A   L I B R A R Y   P L U G I N\r\n***\r\n******************************************************\r\n*****************************************************/\r\nint msgproc(int message_type, int param1, int param2, int param3)\r\n{\r\n\tBOOL bRet = FALSE;\r\n\r\n\tswitch(message_type)\r\n\t{\r\n\tcase ML_MSG_CONFIG:\r\n\t\tconfig();\r\n\t\tbRet = TRUE;\r\n\t\tbreak;\r\n\tdefault:;\r\n\t}\r\n\r\n\treturn bRet;\r\n}\r\n\r\nwinampMediaLibraryPlugin mlplugin = \r\n{\r\n\tMLHDR_VER,\r\n\t\"\",\r\n\tmlinit,\r\n\tquit,\r\n\tmsgproc,\r\n};\r\n\r\nextern \"C\" {\r\n\r\n// Entry point for a media library plugin\r\n__declspec( dllexport ) winampMediaLibraryPlugin * winampGetMediaLibraryPlugin()\r\n{\r\n\treturn &mlplugin;\r\n}\r\n\r\n};\r\n\r\n// Winamp calls this with mlplugin populated after the above has been called\r\nint mlinit()\r\n{\r\n\tstatic char c[512];\r\n\tchar filename[512];\r\n\tHWND hWnd = NULL;\r\n\r\n\tg_hDllInstance = mlplugin.hDllInstance;\r\n\tg_hwndParent = mlplugin.hwndWinampParent;\r\n\r\n\t_Module.Init(NULL, mlplugin.hDllInstance, &LIBID_ATLLib);\r\n\r\n\t// Handle Multiple Instances\r\n\thSem = CreateSemaphore (NULL, 1, 1,szSemName);\r\n\tif (WaitForSingleObject (hSem, 0) == WAIT_TIMEOUT) \r\n\t{\r\n\t\tCloseHandle (hSem);\r\n\t\treturn -1;\r\n\t}\r\n\r\n    int version = WINAMP_VERSION_MAJOR( SendMessage( mlplugin.hwndWinampParent,WM_WA_IPC,0,IPC_GETVERSION) );\r\n\r\n    // If the version is earlier than 5, we need to use a method of track play detection\r\n    // that involves overriding the playlist editor's event handler.\r\n    if ( version < 5 )\r\n    {\r\n        hWnd = GetPEWindow(mlplugin.hwndWinampParent);\r\n        if ( hWnd != NULL )\r\n\t    {\r\n            SetWndSubClass( hWnd, WndProcPE, &lpWndProcOldPE );\r\n   \t    }\r\n  \t    else\r\n    \t\tPRINTF(DEBUG_ERROR, \"Gen_AudioScrobbler::mlinit\", \"Failed to find Winamp PE Window\");\r\n\t}\r\n\r\n    // From version 5, Winamp supplies a better way to detect track plays that goes\r\n    // through the main window's event handler. From 5.5 the old PE method does\r\n    // not even work any longer.\r\n    if ( version >= 5 && mlplugin.hwndWinampParent != NULL )\r\n    {\r\n        SetWndSubClass( mlplugin.hwndWinampParent, WndProcParent, &lpWndProcOldParent );\r\n    }\r\n\r\n\tif(GetModuleFileName(mlplugin.hDllInstance,filename,sizeof(filename)) == 0)\r\n\t{\r\n\t\tCStdString strText;\r\n\t\tstrText.Format(\"An error occurred loading the AS plugin during GetModuleFileName(), the return code was %d\", GetLastError());\r\n\r\n\t\t::MessageBox(mlplugin.hwndWinampParent, strText.c_str(), \"AudioScrobbler Error\", MB_OK);\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif(!theScrobbler.StartScrobbling(mlplugin.hDllInstance, \r\n\t\tmlplugin.hwndWinampParent, \r\n\t\tmlplugin.hwndLibraryParent,\r\n\t\tfilename))\r\n\t\tconfig();\r\n\r\n\tsprintf((mlplugin.description=c), \"%s v%s (ML Mode)\", theScrobbler.GetAppName().c_str(), theScrobbler.GetVersionString().c_str());\r\n\r\n\treturn 0;\r\n}\r\n"
  },
  {
    "path": "plugins/winamp/Gen_AudioScrobbler.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"Gen_AudioScrobbler\" - Package Owner=<4>\r\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\r\n# ** DO NOT EDIT **\r\n\r\n# TARGTYPE \"Win32 (x86) Dynamic-Link Library\" 0x0102\r\n\r\nCFG=Gen_AudioScrobbler - Win32 Debug\r\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r\n!MESSAGE use the Export Makefile command and run\r\n!MESSAGE \r\n!MESSAGE NMAKE /f \"Gen_AudioScrobbler.mak\".\r\n!MESSAGE \r\n!MESSAGE You can specify a configuration when running NMAKE\r\n!MESSAGE by defining the macro CFG on the command line. For example:\r\n!MESSAGE \r\n!MESSAGE NMAKE /f \"Gen_AudioScrobbler.mak\" CFG=\"Gen_AudioScrobbler - Win32 Debug\"\r\n!MESSAGE \r\n!MESSAGE Possible choices for configuration are:\r\n!MESSAGE \r\n!MESSAGE \"Gen_AudioScrobbler - Win32 Release\" (based on \"Win32 (x86) Dynamic-Link Library\")\r\n!MESSAGE \"Gen_AudioScrobbler - Win32 Debug\" (based on \"Win32 (x86) Dynamic-Link Library\")\r\n!MESSAGE \r\n\r\n# Begin Project\r\n# PROP AllowPerConfigDependencies 0\r\n# PROP Scc_ProjName \"\"$/Gen_AudioScrobbler\", BAAAAAAA\"\r\n# PROP Scc_LocalPath \".\"\r\nCPP=cl.exe\r\nMTL=midl.exe\r\nRSC=rc.exe\r\n\r\n!IF  \"$(CFG)\" == \"Gen_AudioScrobbler - Win32 Release\"\r\n\r\n# PROP BASE Use_MFC 0\r\n# PROP BASE Use_Debug_Libraries 0\r\n# PROP BASE Output_Dir \"Release\"\r\n# PROP BASE Intermediate_Dir \"Release\"\r\n# PROP BASE Target_Dir \"\"\r\n# PROP Use_MFC 0\r\n# PROP Use_Debug_Libraries 0\r\n# PROP Output_Dir \"Release\"\r\n# PROP Intermediate_Dir \"Release\"\r\n# PROP Ignore_Export_Lib 0\r\n# PROP Target_Dir \"\"\r\n# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"GEN_AUDIOSCROBBLER_EXPORTS\" /Yu\"stdafx.h\" /FD /c\r\n# ADD CPP /nologo /MD /W3 /GX /O2 /I \"../Common\" /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"GEN_AUDIOSCROBBLER_EXPORTS\" /Yu\"stdafx.h\" /FD /c\r\n# ADD BASE MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n# ADD MTL /nologo /D \"NDEBUG\" /mktyplib203 /win32\r\n# ADD BASE RSC /l 0x809 /d \"NDEBUG\"\r\n# ADD RSC /l 0x809 /d \"NDEBUG\"\r\nBSC32=bscmake.exe\r\n# ADD BASE BSC32 /nologo\r\n# ADD BSC32 /nologo\r\nLINK32=link.exe\r\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386\r\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib RASAPI32.LIB ws2_32.lib wininet.lib /nologo /dll /pdb:none /machine:I386 /out:\"Release/ml_audioscrobbler.dll\"\r\n# SUBTRACT LINK32 /debug\r\n# Begin Special Build Tool\r\nSOURCE=\"$(InputPath)\"\r\nPostBuild_Cmds=copy .\\Release\\ml_audioscrobbler.dll c:\\progra~1\\Winamp\\Plugins\r\n# End Special Build Tool\r\n\r\n!ELSEIF  \"$(CFG)\" == \"Gen_AudioScrobbler - Win32 Debug\"\r\n\r\n# PROP BASE Use_MFC 0\r\n# PROP BASE Use_Debug_Libraries 1\r\n# PROP BASE Output_Dir \"Debug\"\r\n# PROP BASE Intermediate_Dir \"Debug\"\r\n# PROP BASE Target_Dir \"\"\r\n# PROP Use_MFC 0\r\n# PROP Use_Debug_Libraries 1\r\n# PROP Output_Dir \"Debug\"\r\n# PROP Intermediate_Dir \"Debug\"\r\n# PROP Ignore_Export_Lib 0\r\n# PROP Target_Dir \"\"\r\n# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"GEN_AUDIOSCROBBLER_EXPORTS\" /Yu\"stdafx.h\" /FD /GZ /c\r\n# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I \"../Common\" /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"GEN_AUDIOSCROBBLER_EXPORTS\" /FR /Yu\"stdafx.h\" /FD /GZ /c\r\n# ADD BASE MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n# ADD MTL /nologo /D \"_DEBUG\" /mktyplib203 /win32\r\n# ADD BASE RSC /l 0x809 /d \"_DEBUG\"\r\n# ADD RSC /l 0x809 /d \"_DEBUG\"\r\nBSC32=bscmake.exe\r\n# ADD BASE BSC32 /nologo\r\n# ADD BSC32 /nologo\r\nLINK32=link.exe\r\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept\r\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib RASAPI32.LIB ws2_32.lib wininet.lib /nologo /dll /debug /machine:I386 /out:\"Debug/ml_AudioScrobbler.dll\" /pdbtype:sept\r\n# Begin Special Build Tool\r\nSOURCE=\"$(InputPath)\"\r\nPostBuild_Cmds=copy        .\\Debug\\ml_audioscrobbler.dll        c:\\progra~1\\Winamp\\Plugins\\ \r\n# End Special Build Tool\r\n\r\n!ENDIF \r\n\r\n# Begin Target\r\n\r\n# Name \"Gen_AudioScrobbler - Win32 Release\"\r\n# Name \"Gen_AudioScrobbler - Win32 Debug\"\r\n# Begin Group \"Source Files\"\r\n\r\n# PROP Default_Filter \"cpp;c;cxx;rc;def;r;odl;idl;hpj;bat\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\Gen_AudioScrobbler.cpp\r\n# ADD CPP /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Gen_AudioScrobbler.rc\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdAfx.cpp\r\n# ADD CPP /Yc\"stdafx.h\"\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Header Files\"\r\n\r\n# PROP Default_Filter \"h;hpp;hxx;hm;inl\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\Gen_AudioScrobbler.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Resource.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdAfx.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Resource Files\"\r\n\r\n# PROP Default_Filter \"ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe\"\r\n# End Group\r\n# Begin Group \"Winamp\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\GEN.H\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\ml.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wa_dlg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wa_ipc.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\winampcmd.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WinampController.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WinampController.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WinampScrobbler.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WinampScrobbler.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Scrobbler\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\CacheManager.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\CacheManager.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\ConfigDlg.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\ConfigDlg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\IncExcDirDlg.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\IncExcDirDlg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Scrobbler.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Scrobbler.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Submission.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Submission.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\SubmissionLog.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\SubmissionLog.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"MD5\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5.c\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Class.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Class.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Global.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Library\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\comdate.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\dbg.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Dbg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\DirDialog.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\DirDialog.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\OSVer.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\OSVer.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Registry.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Registry.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdString.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdStringArray.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdStringArray.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\VersionApp.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\VersionApp.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WatchConnection.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WatchConnection.h\r\n# End Source File\r\n# End Group\r\n# Begin Source File\r\n\r\nSOURCE=.\\audioscrobbler.html\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\AudioScrobbler.nsi\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Winamp_WhatsNew.txt\r\n# End Source File\r\n# End Target\r\n# End Project\r\n"
  },
  {
    "path": "plugins/winamp/Gen_AudioScrobbler.dsw",
    "content": "Microsoft Developer Studio Workspace File, Format Version 6.00\r\n# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r\n\r\n###############################################################################\r\n\r\nProject: \"Gen_AudioScrobbler\"=.\\Gen_AudioScrobbler.dsp - Package Owner=<4>\r\n\r\nPackage=<5>\r\n{{{\r\n}}}\r\n\r\nPackage=<4>\r\n{{{\r\n}}}\r\n\r\n###############################################################################\r\n\r\nGlobal:\r\n\r\nPackage=<5>\r\n{{{\r\n}}}\r\n\r\nPackage=<3>\r\n{{{\r\n}}}\r\n\r\n###############################################################################\r\n\r\n"
  },
  {
    "path": "plugins/winamp/Gen_AudioScrobbler.h",
    "content": ""
  },
  {
    "path": "plugins/winamp/Gen_AudioScrobbler.rc",
    "content": "// Microsoft Visual C++ generated resource script.\r\n//\r\n#include \"resource.h\"\r\n\r\n#define APSTUDIO_READONLY_SYMBOLS\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 2 resource.\r\n//\r\n#include \"afxres.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#undef APSTUDIO_READONLY_SYMBOLS\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.S.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Version\r\n//\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\n FILEVERSION 2,1,0,9\r\n PRODUCTVERSION 2,1,0,9\r\n FILEFLAGSMASK 0x3fL\r\n#ifdef _DEBUG\r\n FILEFLAGS 0x9L\r\n#else\r\n FILEFLAGS 0x8L\r\n#endif\r\n FILEOS 0x4L\r\n FILETYPE 0x2L\r\n FILESUBTYPE 0x0L\r\nBEGIN\r\n    BLOCK \"StringFileInfo\"\r\n    BEGIN\r\n        BLOCK \"040904b0\"\r\n        BEGIN\r\n            VALUE \"Comments\", \"http://www.last.fm\"\r\n            VALUE \"CompanyName\", \"Last.fm\"\r\n            VALUE \"FileDescription\", \"Last.fm Winamp Plugin\"\r\n            VALUE \"FileVersion\", \"2, 1, 0, 9\"\r\n            VALUE \"InternalName\", \"ml_wa2_scrobbler\"\r\n            VALUE \"LegalCopyright\", \"Copyright (C) 2008\"\r\n            VALUE \"OriginalFilename\", \"ml_wa2_scrobbler.dll\"\r\n            VALUE \"PrivateBuild\", \"634\"\r\n            VALUE \"ProductName\", \"Last.fm Winamp Plugin\"\r\n            VALUE \"ProductVersion\", \"2, 1, 0, 9\"\r\n        END\r\n    END\r\n    BLOCK \"VarFileInfo\"\r\n    BEGIN\r\n        VALUE \"Translation\", 0x409, 1200\r\n    END\r\nEND\r\n\r\n#endif    // English (U.S.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.K.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTINCLUDE\r\n//\r\n\r\n1 TEXTINCLUDE \r\nBEGIN\r\n    \"resource.h\\0\"\r\nEND\r\n\r\n2 TEXTINCLUDE \r\nBEGIN\r\n    \"#include \"\"afxres.h\"\"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n3 TEXTINCLUDE \r\nBEGIN\r\n    \"#define _AFX_NO_SPLITTER_RESOURCES\\r\\n\"\r\n    \"#define _AFX_NO_OLE_RESOURCES\\r\\n\"\r\n    \"#define _AFX_NO_TRACKER_RESOURCES\\r\\n\"\r\n    \"#define _AFX_NO_PROPERTY_RESOURCES\\r\\n\"\r\n    \"\\r\\n\"\r\n    \"#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\\r\\n\"\r\n    \"#ifdef _WIN32\\r\\n\"\r\n    \"LANGUAGE 9, 1\\r\\n\"\r\n    \"#pragma code_page(1252)\\r\\n\"\r\n    \"#endif //_WIN32\\r\\n\"\r\n    \"#include \"\"res\\\\Gen_AudioScrobbler.rc2\"\"  // non-Microsoft Visual C++ edited resources\\r\\n\"\r\n    \"#include \"\"afxres.rc\"\"         // Standard components\\r\\n\"\r\n    \"#endif\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n#endif    // English (U.K.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n#ifndef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 3 resource.\r\n//\r\n#define _AFX_NO_SPLITTER_RESOURCES\r\n#define _AFX_NO_OLE_RESOURCES\r\n#define _AFX_NO_TRACKER_RESOURCES\r\n#define _AFX_NO_PROPERTY_RESOURCES\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n#ifdef _WIN32\r\nLANGUAGE 9, 1\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n#include \"res\\Gen_AudioScrobbler.rc2\"  // non-Microsoft Visual C++ edited resources\r\n#include \"afxres.rc\"         // Standard components\r\n#endif\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#endif    // not APSTUDIO_INVOKED\r\n\r\n"
  },
  {
    "path": "plugins/winamp/OSVer.cpp",
    "content": "/*\r\nModule : Dtwinver.cpp\r\nPurpose: Implementation of a comprehensive function to perform OS version detection\r\nCreated: PJN / 11-05-1996\r\nHistory: PJN / 24-02-1997 A number of updates including support for NT 3.1, \r\n                          single mode dos in Windows 95 and better Windows\r\n                          version detecion under real mode dos.\r\n         PJN / 13-09-1998 1.  Added explicit support for Windows 98 \r\n                          2.  Updated documentation to use HTML. \r\n                          3.  Minor update to the web page describing it. \r\n         PJN / 22-06-1999 1.  UNICODE enabled the code.\r\n                          2.  Removed need for the dwOSVersionInfoSize variable\r\n                          3.  Added support for detecting Build Number of 95 and 98 from DOS code path.\r\n                          4.  Now ships as standard with VC 5 workspace files\r\n                          5.  Added explicit support for Windows 95 SP 1\r\n                          6.  Added explicit support for Windows 95 OSR 2\r\n                          7.  Added explicit support for Windows 98 Second Edition\r\n                          8.  Added explicit support for Windows 2000\r\n                          9.  Added explicit support for Windows CE\r\n                          10. Added explicit support for Windows Terminal Server's\r\n                          11. Added explicit support for NT Stand Alone Server's.\r\n                          12. Added explicit support for NT Primary Domain Controller's\r\n                          13. Added explicit support for NT Backup Domain Controller's\r\n         PJN / 23-07-1999 Tested out support for Windows 98 SE, minor changes required\r\n         PJN / 26-07-1999 Added explicit support for Windows 98 SP 1\r\n         PJN / 28-07-1999 1. Fixed a problem when application is build in non-huge/large \r\n                          memory model in Win16\r\n                          2. Added explicit support for returning NT and Win9x service pack information \r\n                          from Win32 and Win16 code paths\r\n                          3. Updated test program to not bother reporting on any info which does not \r\n                          exist. e.g. if there is no service pack installed, then we don't bother \r\n                          displaying any info about service packs\r\n                          4. Added explicit support for NT Enterprise Edition\r\n         PJN / 30-06-2000 1. Added explicit support for Windows Millennium Edition\r\n         PJN / 29-01-2001 1.  Added explicit support for Windows XP (Whistler) Personal\r\n                          2.  Added explicit support for Windows XP (Whistler) Professional\r\n                          3.  Added explicit support for Windows XP (Whistler) Server\r\n                          4.  Added explicit support for Windows XP (Whistler) Advanced Server\r\n                          5.  Added explicit support for Windows XP (Whistler) Datacenter\r\n                          6.  Added explicit support for Windows XP (Whistler) 64 bit (all flavours)\r\n                          7.  Made all the code into a C++ class called COSVersion\r\n                          8.  Rewrote all the generic thunk code to be easier to follow\r\n                          9. Generic think code now uses CallProcEx32W\r\n                          10.  Added explicit support for BackOffice Small Business Edition\r\n                          11. Added explicit support for Terminal Services\r\n                          12. 16 bit code path now can determine ProductSuite and ProductType type\r\n                          thro additional generic thunk code\r\n                          13. Provided a 64 bit test binary and make batch file (make64.bat) for \r\n                          those lucky enough to have an Itanium processor and a beta of 64 bit Windows XP (Whistler).\r\n                          14. Provided a Embedded C++ workspace and X86 Release binary.\r\n                          15. Updated copyright information           \r\n         PJN / 10-02-2001 1. Updated function names etc following MS decision to call Whistler \"Windows XP\"\r\n         PJN / 10-10-2001 1. Added code to 32 bit code path to detect if we are being run under 64 bit Windows. Also\r\n                          updated the sample app to distinguish between emulated 64 bit and underlying \r\n                          64 bit.\r\n                          2. Updated the sample app to call XP Server its proper name which will be \"Windows.NET Server\"\r\n         PJN / 13-12-2001 1. Major upgrade. Now 16 bit DOS path can return as much information as native Win32 code. \r\n                          This is achieved by spawning off the Win32 utility WriteVer with a special command line option.\r\n                          Please note that if you intend deploying dtwinver then you must now ship the writever.exe file\r\n                          in addition to linking in the dtwinver code into your application. Also this utilty needs\r\n                          to be in the path or current directory when the dtwinver code is executing. Thanks to Chaz Angell\r\n                          for prompted me into finding a solution for this last major item missing in dtwinver.\r\n         PJN / 30-12-2002 1. Provided an update CE workspace to work correctly in eMbedded Visual C++ v3. All build configurations\r\n                          for eVC 3 have also been provided.\r\n                          2. Optimized the usage of _tcscat and _tcscpy in the test app which comes with Dtwinver.cpp\r\n                          3. OEM Info string and Platform Type string is now returned for CE code path\r\n                          4. Fixed display of minor version number for example Windows .NET is version number v5.20 but\r\n                          should be shown as 5.2 to be consistent with what the native ver command displays\r\n                          5. Provided a new CE workspace to work correctly in eMbedded Visual C++ v4. All build configurations\r\n                          for eVC 4 have also been provided.\r\n         PJN / 08-10-2002 1. Now uses OSVERSIONINFOEX it possible in the Win32 or Win64 code paths. This provides for\r\n                          more reliably detection of Windows XP Home Edition.\r\n                          2. Renamed the functions which detect Windows .NET Server 2003. Also updated the test code which\r\n                          prints out these names\r\n                          3. Provided explicit support for Windows .NET Web Server\r\n                          4. Fixed a bug in the display of the minor OS version number on Windows .NET Server.\r\n                          5. Made the project for WriteVer a VC 5 project instead of VC 6 which it was up until now.\r\n                          6. Reworked the internal function WhichNTProduct to use a constant input string parameter\r\n                          7. Added explicit support for Windows NT / 2000 / XP Embedded\r\n                          8. Added explicit support for detecting Terminal Services in remote admin mode\r\n         PJN / 10-10-2002 1.  Fixed a problem where on Windows XP, the test program will include the text \"(Standard Edition)\"\r\n                          2.  Added two variables to the OS_VERSION_INFO structure to report the minor service pack number\r\n                          3.  Removed the OS_VERSION_INFO structure from the global namespace\r\n                          4.  Removed all static member variables from the class\r\n                          5.  Added a member variable to the OS_VERSION_INFO to return the various \"suites\" installed\r\n                          6.  reduced the number of calls to WriteVer to 1 when called from dos code path.\r\n                          7.  Completely reworked the internal WhichNTProduct method\r\n                          8.  General tidy up of the header file\r\n                          9.  Completely reworked the ValidateProductSuite method\r\n                          10. Now only 1 call is made to WhichNTProduct throughout a single call to COSVersion::GetVersion\r\n                          11. Now only 1 call is made to ValidateProductSuite throughout a single call to COSVersion::GetVersion\r\n                          12. Fixed an unitialized variable problem in COSVersion::IsUnderlying64Bit\r\n                          13. Changed \"WhichNTProduct\" method to \"GetNTOSTypeFromRegistry\"\r\n                          14. Changed \"ValidateProductSuite\" method to \"GetProductSuiteDetailsFromRegistry\".\r\n                          15. Now correctly reports on Terminal Services being in Remote Admin Mode on OS which do not\r\n                          support calling GetVersionEx using an OSVERSIONINFOEX structure i.e any NT 4 install prior to SP6.\r\n                          16. 16 bit Windows code path now reports as much NT information as the Win32 code path \r\n                          17. Fixed a bug in COSVersion::GetInfoBySpawingWriteVer which was failing if it encountered \r\n                          an empty CSD string. This was spotted on Windows .NET Server which since it is in beta still\r\n                          (as of October 2002) does not have any service pack!.\r\n         PJN / 10-01-2003 1. Update to support MS deciding to change the name of their Whistler Server product. The product \r\n                          will now be called \"Windows Server 2003\".\r\n         PJN / 30-01-2003 1. Added explicit support for detecting NT Service Pack 6a\r\n         PJN / 08-02-2003 1. Added explicit support for detecting Windows XP Service Pack 1a\r\n                          2. Added support to determine the HAL on NT Kernels.\r\n         PJN / 12-02-2003 1. Fixed a compiler warning in GetNTServicePackFromRegistry which occurs when the code is compiled\r\n                          with the Watcom compiler. Thanks to Christian Kaiser for reporting this.\r\n         PJN / 08-03-2003 1. Updated a comment in COSVersion::GetProductSuiteDetailsFromRegistry re NT Embedded.\r\n                          2. A comment from John A. Vorchak: On NTe (NT Embedded) and XPE (XP Embedded), all of the versions \r\n                          (of DTWinver) work just fine so long as the components to support them are included in the images, \r\n                          which itself is kind of a crap shoot.  I think that you would probably find that most images will \r\n                          not support the DOS or Win16 versions however most will support the Win32.  Many of the images that \r\n                          folks build either do not include the DOS subsystem and some of them do not include Explorer, so it \r\n                          really can't be said that all builds will support them however it is not difficult for a developer \r\n                          to understand which version would work for them as they understand their target systems better than \r\n                          anyone and at least one version would certainly work for almost all images. \r\n                          As far as Win2k (Server Appliance Kit), I haven't done enough testing with that platform, nor do I \r\n                          currently have any built images with the SAK to say positively or otherwise. More than likely you \r\n                          would find no problems with the SAK images since they typically follow W2k much more than NTe or \r\n                          XPE do.\r\n                          Author: If you are writing for an embedded OS, then there is little use for DTWinver!!, since the\r\n                          developer has very tight control over the runtime environment. Also if you do use DTWinver on an \r\n                          embedded version of Windows, you will probably compile in the dtwinver code rather than ship the \r\n                          sample binaries I include in the dtwinver download.\r\n\r\n\r\nCopyright (c) 1997 - 2003 by PJ Naughter.  (Web: www.naughter.com, Email: pjna@naughter.com)\r\n\r\nAll rights reserved.\r\n\r\nCopyright / Usage Details:\r\n\r\nYou are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) \r\nwhen your product is released in binary form. You are allowed to modify the source code in any way you want \r\nexcept you cannot modify the copyright details at the top of each module. If you want to distribute source \r\ncode with your application, then you are only allowed to distribute versions released by the author. This is \r\nto maintain a single distribution point for the source code. \r\n*/\r\n\r\n\r\n/////////////////////////////////  Includes  //////////////////////////////////\r\n#include <windows.h> \r\n#if defined(_WIN32) || defined(_WIN64)\r\n#include <tchar.h>\r\n#else\r\n#include <ctype.h>\r\n#include <stdlib.h>\r\n#include <shellapi.h>\r\n#endif\r\n#include <string.h>\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include \"OSVer.h\"\r\n\r\n\r\n/////////////////////////////////  Local function / variables /////////////////\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_WORKSTATION\r\n#define VER_NT_WORKSTATION              0x0000001\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_DOMAIN_CONTROLLER\r\n#define VER_NT_DOMAIN_CONTROLLER        0x0000002\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_SERVER\r\n#define VER_NT_SERVER                   0x0000003\r\n#endif\r\n\r\n\r\n//OS_VERSION_INFO::wSuiteMask can any of the following bit masks\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_SMALLBUSINESS\r\n#define VER_SUITE_SMALLBUSINESS             0x00000001\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_ENTERPRISE\r\n#define VER_SUITE_ENTERPRISE                0x00000002\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_TERMINAL\r\n#define VER_SUITE_TERMINAL                  0x00000010\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_DATACENTER\r\n#define VER_SUITE_DATACENTER                0x00000080\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_PERSONAL\r\n#define VER_SUITE_PERSONAL                  0x00000200\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_BLADE\r\n#define VER_SUITE_BLADE                     0x00000400\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_EMBEDDEDNT\r\n#define VER_SUITE_EMBEDDEDNT                0x00000040\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_SINGLEUSERTS\r\n#define VER_SUITE_SINGLEUSERTS              0x00000100\r\n#endif\r\n\r\n\r\n#if defined(_WIN32)\r\n\r\n//Taken from Windows CE winbase.h file\r\n#ifndef VER_PLATFORM_WIN32_CE\r\n  #define VER_PLATFORM_WIN32_CE         3\r\n#endif\r\n\r\n#endif //defined(_WIN32) \r\n\r\n#ifdef _DOS\r\n  WORD WinVer;\r\n  BYTE bRunningWindows;\r\n#endif //ifdef _DOS\r\n\r\n\r\n////////////////////////////////// Implementation /////////////////////////////\r\nCOSVersion::COSVersion()\r\n{\r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)\r\n  //Initialize the values to sane defaults\r\n  m_lpfnLoadLibraryEx32W = NULL;\r\n  m_lpfnFreeLibrary32W = NULL;\r\n  m_lpfnGetProcAddress32W = NULL;\r\n  m_lpfnCallProcEx32W = NULL;\r\n  m_hAdvApi32 = 0;    \r\n  m_hKernel32 = 0;\r\n  m_lpfnRegQueryValueExA= 0;\r\n  m_lpfnGetVersionExA = 0;\r\n  m_lpfnGetVersion = 0;\r\n\r\n  //Get Kernel dll handle\r\n  HMODULE hKernel = GetModuleHandle(\"KERNEL\");\r\n  if (hKernel)\r\n  {\r\n    //Dynamically link to the functions we want\r\n    m_lpfnLoadLibraryEx32W  = (lpfnLoadLibraryEx32W)  GetProcAddress(hKernel, \"LoadLibraryEx32W\");\r\n    m_lpfnFreeLibrary32W    = (lpfnFreeLibrary32W)    GetProcAddress(hKernel, \"FreeLibrary32W\");\r\n    m_lpfnGetProcAddress32W = (lpfnGetProcAddress32W) GetProcAddress(hKernel, \"GetProcAddress32W\");\r\n    m_lpfnCallProcEx32W     = (lpfnCallProcEx32W)     GetProcAddress(hKernel, \"_CallProcEx32W\");\r\n    if (m_lpfnLoadLibraryEx32W && m_lpfnFreeLibrary32W)\r\n    {\r\n      m_hAdvApi32 = m_lpfnLoadLibraryEx32W(\"ADVAPI32.DLL\", NULL, 0);\r\n      if (m_hAdvApi32)                                                   \r\n        m_lpfnRegQueryValueExA = m_lpfnGetProcAddress32W(m_hAdvApi32, \"RegQueryValueExA\"); \r\n      m_hKernel32 = m_lpfnLoadLibraryEx32W(\"KERNEL32.DLL\", NULL, 0);\r\n      if (m_hKernel32)\r\n      {                                                               \r\n        m_lpfnGetVersionExA = m_lpfnGetProcAddress32W(m_hKernel32, \"GetVersionExA\");\r\n        m_lpfnGetVersion = m_lpfnGetProcAddress32W(m_hKernel32, \"GetVersion\");\r\n      }\r\n    }\r\n  }\r\n#endif\r\n}\r\n\r\nCOSVersion::~COSVersion()\r\n{\r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)\r\n  if (m_lpfnFreeLibrary32W)\r\n  {           \r\n    if (m_hAdvApi32)\r\n      m_lpfnFreeLibrary32W(m_hAdvApi32);\r\n    if (m_hKernel32)\r\n      m_lpfnFreeLibrary32W(m_hKernel32);\r\n  }\r\n#endif\r\n}\r\n\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))\r\nBOOL COSVersion::WFWLoaded()\r\n{\r\n  const WORD WNNC_NET_MultiNet         = 0x8000;\r\n  const WORD WNNC_SUBNET_WinWorkgroups = 0x0004;\r\n  const WORD WNNC_NET_TYPE             = 0x0002;\r\n  BOOL rVal;\r\n   \r\n  HINSTANCE hUserInst = LoadLibrary(\"USER.EXE\");\r\n  lpfnWNetGetCaps lpWNetGetCaps = (lpfnWNetGetCaps) GetProcAddress(hUserInst, \"WNetGetCaps\");\r\n  if (lpWNetGetCaps != NULL)\r\n  {\r\n    // Get the network type\r\n    WORD wNetType = lpWNetGetCaps(WNNC_NET_TYPE);\r\n    if (wNetType & WNNC_NET_MultiNet)\r\n    {\r\n      // a multinet driver is installed\r\n      if (LOBYTE(wNetType) & WNNC_SUBNET_WinWorkgroups) // It is WFW\r\n        rVal = TRUE;\r\n      else // It is not WFW\r\n        rVal = FALSE;\r\n    }\r\n    else\r\n     rVal = FALSE;\r\n  }\r\n  else\r\n    rVal = FALSE;\r\n   \r\n  //Clean up the module instance\r\n  if (hUserInst)\r\n    FreeLibrary(hUserInst);\r\n    \r\n  return rVal;  \r\n}\r\n\r\nLONG COSVersion::RegQueryValueEx(HKEY32 hKey, LPSTR  lpszValueName, LPDWORD lpdwReserved, LPDWORD lpdwType, LPBYTE  lpbData, LPDWORD lpcbData)\r\n{                                             \r\n  //Assume the worst\r\n  DWORD dwResult = ERROR_CALL_NOT_IMPLEMENTED;\r\n\r\n  if (m_lpfnRegQueryValueExA)\r\n    dwResult = m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 6, 0x3e, m_lpfnRegQueryValueExA, hKey, lpszValueName, lpdwReserved, lpdwType, lpbData, lpcbData);\r\n\r\n  return dwResult;\r\n}                 \r\n\r\nBOOL COSVersion::GetVersionEx(LPOSVERSIONINFO lpVersionInfo)\r\n{\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  if (m_lpfnGetVersionExA)\r\n    bSuccess = (BOOL) m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 1, 1, m_lpfnGetVersionExA, lpVersionInfo, 0);\r\n\r\n  return bSuccess;\r\n}\r\n\r\nDWORD COSVersion::GetVersion()\r\n{\r\n  //Assume the worst\r\n  DWORD dwVersion = 0;\r\n\r\n  if (m_lpfnGetVersion)\r\n    dwVersion = (BOOL) m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 0, 0, m_lpfnGetVersion, 0);\r\n\r\n  return dwVersion;\r\n}\r\n#endif //defined(_WINDOWS) && !defined(_WIN32)\r\n\r\nBOOL COSVersion::GetVersion(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Zero out everything in the structure\r\n  memset(lpVersionInformation, 0, sizeof(lpVersionInformation));\r\n                \r\n  #ifdef UNDER_CE\r\n    OSVERSIONINFO osvi;\r\n    memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n    if (!GetVersionEx(&osvi))\r\n      return FALSE;\r\n\r\n    //Basic OS info\r\n    lpVersionInformation->dwUnderlyingMajorVersion = osvi.dwMajorVersion; \r\n    lpVersionInformation->dwUnderlyingMinorVersion = osvi.dwMinorVersion; \r\n    lpVersionInformation->dwUnderlyingBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n    lpVersionInformation->UnderlyingPlatform = WindowsCE;\r\n    _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, osvi.szCSDVersion);\r\n\r\n    //OEM Info\r\n    _tcscpy(lpVersionInformation->szOEMInfo, _T(\"\"));\r\n    SystemParametersInfo(SPI_GETOEMINFO, 256, lpVersionInformation->szOEMInfo, 0);\r\n\r\n    //Platform Type\r\n    _tcscpy(lpVersionInformation->szPlatformType, _T(\"\"));\r\n    SystemParametersInfo(SPI_GETPLATFORMTYPE, 256, lpVersionInformation->szPlatformType, 0);\r\n\r\n    //Always set the OSType to Workstation on CE. The variable itself does not make \r\n    //much sense on CE, but we do not conditionally compile it out on CE as then we\r\n    //would have to put in loadsa ifdefs UNDER_CE in the COSVersion::Is... methods\r\n    lpVersionInformation->OSType = Workstation;\r\n\r\n  #elif defined(_WIN32) || defined(_WIN64)\r\n    //determine dynamically if GetVersionEx is available, if \r\n    //not then drop back to using GetVersion\r\n\r\n    // Get Kernel handle\r\n    HMODULE hKernel32 = GetModuleHandle(_T(\"KERNEL32.DLL\"));\r\n    if (hKernel32 == NULL)\r\n      return FALSE;\r\n\r\n    #ifdef _UNICODE\r\n      lpfnGetVersionEx lpGetVersionEx = (lpfnGetVersionEx) GetProcAddress(hKernel32, \"GetVersionExW\");\r\n    #else\r\n      lpfnGetVersionEx lpGetVersionEx = (lpfnGetVersionEx) GetProcAddress(hKernel32, \"GetVersionExA\");\r\n    #endif\r\n\r\n    if (lpGetVersionEx)\r\n    {\r\n      OSVERSIONINFOEX osviex;\r\n      memset(&osviex, 0, sizeof(OSVERSIONINFOEX));\r\n      osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\r\n\r\n      OSVERSIONINFO osvi;\r\n      memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n\r\n      BOOL bGotOSviEx = lpGetVersionEx((LPOSVERSIONINFO) &osviex);\r\n      if (!bGotOSviEx)\r\n      {\r\n        if (!lpGetVersionEx(&osvi))\r\n          return FALSE;\r\n      }\r\n\r\n      if (bGotOSviEx)\r\n      {\r\n        lpVersionInformation->dwEmulatedMajorVersion = osviex.dwMajorVersion;\r\n        lpVersionInformation->dwEmulatedMinorVersion = osviex.dwMinorVersion;\r\n        lpVersionInformation->dwEmulatedBuildNumber = LOWORD(osviex.dwBuildNumber);\r\n        _tcscpy(lpVersionInformation->szEmulatedCSDVersion, osviex.szCSDVersion);\r\n        lpVersionInformation->wEmulatedServicePackMajor = osviex.wServicePackMajor;\r\n        lpVersionInformation->wEmulatedServicePackMinor = osviex.wServicePackMinor;\r\n        \r\n        //Explicitly map the Win32 wSuiteMask to our own values\r\n        if (osviex.wSuiteMask & VER_SUITE_SMALLBUSINESS)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_SMALLBUSINESS;\r\n        if (osviex.wSuiteMask & VER_SUITE_ENTERPRISE)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_ENTERPRISE;\r\n        if (osviex.wSuiteMask & VER_SUITE_TERMINAL)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_TERMINAL;\r\n        if (osviex.wSuiteMask & VER_SUITE_DATACENTER)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_DATACENTER;\r\n        if (osviex.wSuiteMask & VER_SUITE_PERSONAL)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PERSONAL;\r\n        if (osviex.wSuiteMask & VER_SUITE_BLADE)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_WEBEDITION;\r\n        if (osviex.wSuiteMask & VER_SUITE_EMBEDDEDNT)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_EMBEDDEDNT;\r\n        if (osviex.wSuiteMask & VER_SUITE_SINGLEUSERTS)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_REMOTEADMINMODE_TERMINAL;\r\n\r\n        //Explicitely map the Win32 wProductType to our own values\r\n        switch (osviex.wProductType)\r\n        {\r\n          case VER_NT_WORKSTATION:\r\n          {\r\n            lpVersionInformation->OSType = Workstation;\r\n            break;\r\n          }\r\n          case VER_NT_DOMAIN_CONTROLLER:\r\n          {\r\n            lpVersionInformation->OSType = DomainController;\r\n            break;\r\n          }\r\n          case VER_NT_SERVER:\r\n          {\r\n            lpVersionInformation->OSType = Server;\r\n            break;\r\n          }\r\n          default:\r\n          {\r\n            break;\r\n          }\r\n        }\r\n\r\n        //Determine the Domain Controller Type\r\n        GetNTOSTypeFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Explicitly map the win32 dwPlatformId to our own values \r\n        switch (osviex.dwPlatformId)\r\n        {\r\n          case VER_PLATFORM_WIN32_WINDOWS:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = Windows9x;\r\n            break;\r\n          }\r\n          case VER_PLATFORM_WIN32_NT:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = WindowsNT;\r\n            break;\r\n          }\r\n          case VER_PLATFORM_WIN32_CE:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = WindowsCE;\r\n            break;\r\n          }\r\n          default:\r\n          {\r\n            break;\r\n          }\r\n        }\r\n\r\n        lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion; \r\n        lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion; \r\n        lpVersionInformation->dwUnderlyingBuildNumber = lpVersionInformation->dwEmulatedBuildNumber;\r\n        lpVersionInformation->UnderlyingPlatform = lpVersionInformation->EmulatedPlatform;\r\n        _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n        lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n        lpVersionInformation->wUnderlyingServicePackMinor = lpVersionInformation->wEmulatedServicePackMinor;\r\n\r\n      #ifndef UNDER_CE\r\n        //Determine if it is NT SP6a Vs SP6\r\n        GetNTSP6aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Determine if it is XP SP1a Vs SP1\r\n        GetXPSP1aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Determine the HAL details\r\n        GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n\t    #endif\r\n      }\r\n      else\r\n      {\r\n        lpVersionInformation->dwEmulatedMajorVersion = osvi.dwMajorVersion; \r\n        lpVersionInformation->dwEmulatedMinorVersion = osvi.dwMinorVersion; \r\n        lpVersionInformation->dwEmulatedBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n        _tcscpy(lpVersionInformation->szEmulatedCSDVersion, osvi.szCSDVersion);\r\n    \r\n        //Explicitely map the win32 dwPlatformId to our own values \r\n        //Also work out the various service packs which are installed\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = Windows9x;\r\n          lpVersionInformation->OSType = Workstation;\r\n\r\n          //Deterine the Win9x Service pack installed\r\n          if (IsWindows95SP1(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 1;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          }\r\n          else if (IsWindows95OSR2(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 2;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 2;\r\n          }\r\n          else if (IsWindows98SP1(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 1;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          }\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = WindowsNT;\r\n\r\n          //Determine the NT Service pack\r\n          lpVersionInformation->wEmulatedServicePackMajor = GetNTServicePackFromCSDString(osvi.szCSDVersion);\r\n          lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n\r\n          //Determine the OS Type\r\n          GetNTOSTypeFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Get the Product Suites installed\r\n          GetProductSuiteDetailsFromRegistry(lpVersionInformation);\r\n          GetTerminalServicesRemoteAdminModeDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_CE)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = WindowsCE;\r\n\r\n          //Always set the OSType to Workstation on CE. The variable itself does not make \r\n          //much sense on CE, but we do not conditionally compile it out on CE as then we\r\n          //would have to put in loadsa ifdefs UNDER_CE in the COSVersion::Is... methods\r\n          lpVersionInformation->OSType = Workstation;\r\n        }\r\n\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32s)  //32 bit app running on Windows 3.x\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = Windows9x;\r\n\r\n          lpVersionInformation->dwUnderlyingMajorVersion = 3; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = 10; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = 0;\r\n          lpVersionInformation->UnderlyingPlatform = Windows3x;\r\n          _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, _T(\"\"));\r\n        }\r\n        else\r\n        {\r\n          lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = lpVersionInformation->dwEmulatedBuildNumber;\r\n          lpVersionInformation->UnderlyingPlatform = lpVersionInformation->EmulatedPlatform;\r\n          _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n        }\r\n\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          //Determine if it is NT SP6a Vs SP6\r\n          GetNTSP6aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n          //Determine if it is XP SP1a Vs SP1\r\n          GetXPSP1aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n          //Determine the HAL details\r\n          GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n      }\r\n    }\r\n    else\r\n    {\r\n      //Since GetVersionEx is not available we need to fall back on plain\r\n      //old GetVersion. Because GetVersionEx is available on all but v3.1 of NT\r\n      //we can fill in some of the parameters ourselves.\r\n      DWORD dwVersion = ::GetVersion();\r\n\r\n      lpVersionInformation->dwEmulatedMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));\r\n      lpVersionInformation->dwEmulatedMinorVersion =  (DWORD)(HIBYTE(LOWORD(dwVersion)));\r\n      lpVersionInformation->dwEmulatedBuildNumber = 0;\r\n      lpVersionInformation->EmulatedPlatform   = WindowsNT;   \r\n      lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion;\r\n      lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion;\r\n      lpVersionInformation->dwUnderlyingBuildNumber  = lpVersionInformation->dwEmulatedBuildNumber;\r\n      lpVersionInformation->UnderlyingPlatform   = lpVersionInformation->EmulatedPlatform;   \r\n      _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n\r\n      //Need to determine the NT Service pack by querying the registry directory.\r\n      lpVersionInformation->wEmulatedServicePackMajor = GetNTServicePackFromRegistry();\r\n      lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n    }\r\n  #else //We must be runing on an emulated or real version of Win16 or DOS\r\n    #ifdef _WINDOWS //Running on some version of Windows                   \r\n      DWORD dwVersion = GetVersion();\r\n      // GetVersion does not differentiate between Windows 3.1 and Windows 3.11\r\n      \r\n      lpVersionInformation->dwEmulatedMajorVersion = LOBYTE(LOWORD(dwVersion)); \r\n      lpVersionInformation->dwEmulatedMinorVersion = HIBYTE(LOWORD(dwVersion));\r\n      lpVersionInformation->dwEmulatedBuildNumber  = 0; //no build number with Win3.1x\r\n      lpVersionInformation->EmulatedPlatform   = Windows3x;\r\n      \r\n      //Call to get the underlying OS here through 16 -> 32 bit Generic Thunk\r\n      BOOL bFoundUnderlyingOS = FALSE;\r\n      OSVERSIONINFO osvi;                      \r\n      memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n      if (GetVersionEx(&osvi))\r\n      {\r\n        lpVersionInformation->dwUnderlyingMajorVersion = osvi.dwMajorVersion; \r\n        lpVersionInformation->dwUnderlyingMinorVersion = osvi.dwMinorVersion; \r\n        lpVersionInformation->dwUnderlyingBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n        _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, osvi.szCSDVersion);\r\n       \r\n        //Explicitely map the win32 dwPlatformId to our own values\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\r\n        {\r\n          lpVersionInformation->UnderlyingPlatform = Windows9x;\r\n\r\n          //Deterine the Win9x Service pack installed\r\n          if (IsWindows95SP1(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          else if (IsWindows95OSR2(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 2;\r\n          else if (IsWindows98SP1(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          lpVersionInformation->UnderlyingPlatform = WindowsNT;\r\n\r\n          //Determine the NT Service pack\r\n          lpVersionInformation->wEmulatedServicePackMajor = 0; //Win16 does not have a concept of a service pack\r\n          lpVersionInformation->wUnderlyingServicePackMajor = GetNTServicePackFromCSDString(osvi.szCSDVersion);\r\n\r\n          //Determine the OS Type\r\n          GetNTOSTypeFromRegistry(lpVersionInformation, FALSE);\r\n\r\n\t\t#ifndef UNDER_CE\r\n          //Determine if it is NT SP6a Vs SP6\r\n          GetNTSP6aDetailsFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Determine if it is XP SP1a Vs SP1\r\n          GetXPSP1aDetailsFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Determine the HAL details\r\n          GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n\t\t#endif\r\n\r\n          //Get the Product Suites installed\r\n          GetProductSuiteDetailsFromRegistry(lpVersionInformation);\r\n          GetTerminalServicesRemoteAdminModeDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n        else\r\n          return FALSE;\r\n       \r\n        bFoundUnderlyingOS = TRUE;\r\n      }\r\n      else\r\n      {\r\n        //We failed to get GetVersionEx so try to GetVersion instead. We known that we must be on\r\n        //Windows NT 3.5 or earlier since anything released later by MS had this function.\r\n        DWORD dwVersion = GetVersion();\r\n        if (dwVersion)\r\n        {              \r\n          lpVersionInformation->dwUnderlyingMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));\r\n          lpVersionInformation->dwUnderlyingMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));\r\n          lpVersionInformation->dwUnderlyingBuildNumber  = 0;\r\n          lpVersionInformation->UnderlyingPlatform   = WindowsNT; \r\n          _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n   \r\n          bFoundUnderlyingOS = TRUE;\r\n        }\r\n      }\r\n\r\n      if (!bFoundUnderlyingOS)\r\n      {\r\n        //must be running on a real version of 16 bit Windows whose underlying OS is DOS\r\n        lpVersionInformation->dwUnderlyingMajorVersion = HIBYTE(HIWORD(dwVersion)); \r\n        lpVersionInformation->dwUnderlyingMinorVersion = LOBYTE(HIWORD(dwVersion)); \r\n        lpVersionInformation->dwUnderlyingBuildNumber = 0; \r\n        lpVersionInformation->UnderlyingPlatform = Dos;\r\n        _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n      }\r\n    #else //Must be some version of real or emulated DOS\r\n      //Retreive the current version of emulated DOS\r\n      BYTE DosMinor;\r\n      BYTE DosMajor;\r\n      _asm\r\n      {\r\n        mov ax, 3306h\r\n        int 21h\r\n        mov byte ptr [DosMajor], bl\r\n        mov byte ptr [DosMinor], bh\r\n      }\r\n      lpVersionInformation->EmulatedPlatform = Dos;\r\n      lpVersionInformation->dwEmulatedMajorVersion = (DWORD) DosMajor; \r\n      lpVersionInformation->dwEmulatedMinorVersion = (DWORD) DosMinor;                \r\n      lpVersionInformation->dwEmulatedBuildNumber = 0; //no build number with DOS\r\n      \r\n      //See can we get the underlying OS info by calling WriteVer\r\n      if (!GetInfoBySpawingWriteVer(lpVersionInformation))\r\n      {\r\n        //We can detect if NT is running as it reports DOS v5.5\r\n        if ((lpVersionInformation->dwEmulatedMajorVersion == 5) &&\r\n            (lpVersionInformation->dwEmulatedMinorVersion == 50))    //NT reports DOS v5.5\r\n        {\r\n          _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");    \r\n          //could not find method of determing version of NT from DOS,\r\n          //so assume 3.50\r\n          lpVersionInformation->dwUnderlyingMajorVersion = 3; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = 50; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = 0;  //cannot get access to build number from DOS\r\n          lpVersionInformation->UnderlyingPlatform = WindowsNT;\r\n        }            \r\n        else\r\n        {\r\n          //Get the underlying OS here via the int 2FH interface of Windows\r\n          GetWinInfo();\r\n          if (bRunningWindows)\r\n          { \r\n            if (lpVersionInformation->dwEmulatedMajorVersion >= 7)  //Windows 9x marks itself as DOS 7 or DOS 8\r\n              lpVersionInformation->UnderlyingPlatform = Windows9x;\r\n            else                                                              \r\n            {\r\n              //Could not find method of differentiating between WFW & Win3.1 under DOS,\r\n              //so assume Win3.1                                     \r\n              lpVersionInformation->UnderlyingPlatform = Windows3x;      \r\n            }  \r\n            _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n            lpVersionInformation->dwUnderlyingMajorVersion = (WinVer & 0xFF00) >> 8; \r\n            lpVersionInformation->dwUnderlyingMinorVersion = WinVer & 0x00FF; \r\n  \r\n            if (lpVersionInformation->dwEmulatedMajorVersion >= 8)  //Windows Me reports itself as DOS v8.0\r\n              lpVersionInformation->dwUnderlyingBuildNumber = 3000; //This is the build number for Windows ME.\r\n            else\r\n            {\r\n              if (lpVersionInformation->dwEmulatedMinorVersion == 0)\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 950; //Windows 95 Gold reports DOS v7.0                      \r\n              else if (lpVersionInformation->dwUnderlyingMinorVersion > 0 && \r\n                       lpVersionInformation->dwUnderlyingMinorVersion < 3) \r\n              {                                                            \r\n                //Testing for 95 SP1 has not been done, so the above check\r\n                //may or may not work\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1080; \r\n              }\r\n              else if (lpVersionInformation->dwUnderlyingMinorVersion == 3)\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1212; //Windows 95 OSR2 reports DOS 7.03 from 16 bit code\r\n              else\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1998; //Windows 98 or SE. There is no way to differentiate from real mode\r\n                                                                      //between the two of them\r\n            }\r\n          }\r\n          else //must be on a real version of DOS\r\n          {                               \r\n            lpVersionInformation->dwUnderlyingMajorVersion = (DWORD) DosMajor; \r\n            lpVersionInformation->dwUnderlyingMinorVersion = (DWORD) DosMinor;                \r\n            lpVersionInformation->dwUnderlyingBuildNumber = 0; //no build number with DOS\r\n            lpVersionInformation->UnderlyingPlatform = Dos;\r\n            _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n          }\r\n        }   \r\n      }\r\n    #endif  \r\n  #endif\r\n\r\n  return TRUE;\r\n}\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetNTSP6aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso)\r\n{\r\n#ifndef UNDER_CE\r\n  if ((lpVersionInformation->dwUnderlyingMajorVersion == 4) && (lpVersionInformation->wUnderlyingServicePackMajor == 6))\r\n  {\r\n    //Test for SP6 versus SP6a.\r\n    HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Hotfix\\\\Q246009\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n\tif (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Hotfix\\\\Q246009\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n    {\r\n      lpVersionInformation->wUnderlyingServicePackMinor = 1;         \r\n      if (bUpdateEmulatedAlso)\r\n        lpVersionInformation->wEmulatedServicePackMinor = 1;\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n#endif\r\n}\r\n#endif\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetXPSP1aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso)\r\n{\r\n#ifndef UNDER_CE\r\n  if ((lpVersionInformation->dwUnderlyingMajorVersion == 5) && (lpVersionInformation->dwUnderlyingMinorVersion != 0) && (lpVersionInformation->wUnderlyingServicePackMajor == 1))\r\n  {\r\n    //Test for SP1a versus SP1.\r\n    HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n\tif (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n    {\r\n      TCHAR sTemp[1024];\r\n      DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n  #if (defined(_WIN32) || defined(_WIN64))\r\n      if (::RegQueryValueEx(hKey, _T(\"SubVersionNumber\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n  #else\r\n      if (RegQueryValueEx(hKey, _T(\"SubVersionNumber\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n  #endif\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"a\")) == 0)\r\n        {\r\n          lpVersionInformation->wUnderlyingServicePackMinor = 1;         \r\n          if (bUpdateEmulatedAlso)\r\n            lpVersionInformation->wEmulatedServicePackMinor = 1;\r\n        }\r\n      }\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n#endif\r\n}\r\n#endif\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetNTHALDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n#ifndef UNDER_CE\r\n  HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n  {\r\n    TCHAR sTemp[1024];\r\n    DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (::RegQueryValueEx(hKey, _T(\"CurrentType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#else\r\n    if (RegQueryValueEx(hKey, _T(\"CurrentType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#endif\r\n    {\r\n      if (_tcsicmp(sTemp, _T(\"Uniprocessor Free\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_UNIPROCESSOR_FREE;         \r\n      else if (_tcsicmp(sTemp, _T(\"Uniprocessor Checked\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_UNIPROCESSOR_CHECKED;         \r\n      else if (_tcsicmp(sTemp, _T(\"Multiprocessor Free\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_MULTIPROCESSOR_FREE;         \r\n      else if (_tcsicmp(sTemp, _T(\"Multiprocessor Checked\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_MULTIPROCESSOR_CHECKED;         \r\n    }\r\n  }\r\n\r\n  RegCloseKey(hKey);\r\n#endif\r\n}\r\n#endif\r\n      \r\n#ifndef _DOS\r\nvoid COSVersion::GetNTOSTypeFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bOnlyUpdateDCDetails)\r\n{\r\n  //assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  //Open and the product options key\r\n  HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n  if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), 0, KEY_READ, &hKey) == ERROR_SUCCESS)\r\n#else                                                                                                                               \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), &hKey) == ERROR_SUCCESS)\r\n#endif\r\n  {\r\n    TCHAR sTemp[1024];\r\n    DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (::RegQueryValueEx(hKey, _T(\"ProductType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#else\r\n    if (RegQueryValueEx(hKey, _T(\"ProductType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#endif\r\n    {\r\n      if (bOnlyUpdateDCDetails)\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"LANMANNT\")) == 0)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PRIMARY_DOMAIN_CONTROLLER;\r\n        else if (_tcsicmp(sTemp, _T(\"LANSECNT\")) == 0)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_BACKUP_DOMAIN_CONTROLLER;\r\n      }\r\n      else\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"LANMANNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = DomainController;\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PRIMARY_DOMAIN_CONTROLLER;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"SERVERNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = Server;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"LANSECNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = DomainController;\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_BACKUP_DOMAIN_CONTROLLER;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"WinNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = Workstation;\r\n        }\r\n      }\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n}\r\n#endif //#ifndef _DOS\r\n                                   \r\n#ifdef _DOS             \r\nBOOL COSVersion::GetInfoBySpawingWriteVer(COSVersion::LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  //Form the command line we need  \r\n  char pszCommandLine[256];      \r\n  char* pszTempFilename = tmpnam(NULL);\r\n  sprintf(pszCommandLine, \"WriteVer.exe %s\", pszTempFilename);\r\n\r\n  //Try to spawn out writever utilty\r\n  if (system(pszCommandLine) != -1)\r\n  {           \r\n    //Open the file we need                 \r\n    FILE* pOSFile = fopen(pszTempFilename, \"r\");\r\n    if (pOSFile == NULL)\r\n      return bSuccess;\r\n        \r\n    //Read in the OS version info from file\r\n    char pszLine[1024];\r\n    size_t nRead = fread(pszLine, 1, 1024, pOSFile);\r\n    if (nRead)\r\n    {\r\n      pszLine[nRead] = '\\0'; //Don't forget to NULL terminate\r\n\r\n      //Parse the input string                               \r\n      char* pszSeparators = \"\\t\";                               \r\n      char* pszToken = strtok(pszLine, pszSeparators);\r\n      if (pszToken)\r\n      {\r\n        lpVersionInformation->dwUnderlyingMajorVersion = atoi(pszToken);      \r\n        pszToken = strtok(NULL, pszSeparators);         \r\n        if (pszToken)\r\n        {\r\n          lpVersionInformation->dwUnderlyingMinorVersion = atoi(pszToken);      \r\n          pszToken = strtok(NULL, pszSeparators);         \r\n          if (pszToken)\r\n          {\r\n            lpVersionInformation->dwUnderlyingBuildNumber = atoi(pszToken);       \r\n            pszToken = strtok(NULL, pszSeparators);         \r\n            if (pszToken)\r\n            {\r\n              lpVersionInformation->UnderlyingPlatform = (COSVersion::OS_PLATFORM) atoi(pszToken);       \r\n              pszToken = strtok(NULL, pszSeparators);         \r\n              if (pszToken)                                       \r\n              {                                                   \r\n                lpVersionInformation->wUnderlyingServicePackMajor = (WORD) atoi(pszToken);       \r\n                pszToken = strtok(NULL, pszSeparators);             \r\n                if (pszToken)\r\n                {\r\n                  lpVersionInformation->wUnderlyingServicePackMinor = (WORD) atoi(pszToken);       \r\n                  pszToken = strtok(NULL, pszSeparators);             \r\n                  if (pszToken)\r\n                  {\r\n                    lpVersionInformation->dwSuiteMask = (DWORD) atoi(pszToken);       \r\n                    pszToken = strtok(NULL, pszSeparators);\r\n                    if (pszToken)\r\n                    {\r\n                      lpVersionInformation->OSType = (COSVersion::OS_TYPE) atoi(pszToken);       \r\n\r\n                      //CSDVersion string is optional so consider it successful if we got as far as here\r\n                      bSuccess = TRUE;\r\n\r\n                      pszToken = strtok(NULL, pszSeparators);\r\n                      if (pszToken)\r\n                        strcpy(lpVersionInformation->szUnderlyingCSDVersion, pszToken);                                    \r\n                    }\r\n                  }\r\n                }\r\n              }\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n   \r\n    //Don't forget to close the file\r\n    fclose(pOSFile);\r\n\r\n    //and remove it now that we are finished with it\r\n    remove(pszTempFilename);\r\n  }\r\n  else\r\n  {\r\n    printf(\"writever command failed, Errno:%d\\n\", errno);\r\n  }     \r\n\r\n  return bSuccess;\r\n}\r\n\r\nvoid COSVersion::GetWinInfo()\r\n{ \r\n  BYTE MajorVer;\r\n  BYTE MinorVer;\r\n\r\n  //use some inline assembly to determine if Windows if\r\n  //running and what version is active\r\n  _asm\r\n  {\r\n  ; check for Windows 3.1\r\n    mov     ax,160ah                ; WIN31CHECK\r\n    int     2fh                     ; check if running under Win 3.1.\r\n    or      ax,ax\r\n    jz      RunningUnderWin31       ; can check if running in standard\r\n                                    ; or enhanced mode\r\n   \r\n  ; check for Windows 3.0 enhanced mode\r\n    mov     ax,1600h                ; WIN386CHECK\r\n    int     2fh\r\n    test    al,7fh\r\n    jnz     RunningUnderWin30Enh    ; enhanced mode\r\n   \r\n  ; check for 3.0 WINOLDAP\r\n    mov     ax,4680h                ; IS_WINOLDAP_ACTIVE\r\n    int     2fh\r\n    or      ax,ax                   ; running under 3.0 derivative?\r\n    jnz     NotRunningUnderWin\r\n   \r\n  ; rule out MS-DOS 5.0 task switcher\r\n    mov     ax,4b02h                ; detect switcher\r\n    push    bx\r\n    push    es\r\n    push    di\r\n    xor     bx,bx\r\n    mov     di,bx\r\n    mov     es,bx\r\n    int     2fh\r\n    pop     di\r\n    pop     es\r\n    pop     bx\r\n    or      ax,ax\r\n    jz      NotRunningUnderWin      ; MS-DOS 5.0 task switcher found\r\n   \r\n  ; check for standard mode Windows 3.0\r\n    mov     ax,1605h                ; PMODE_START\r\n    int     2fh\r\n    cmp     cx,-1\r\n    jz      RunningUnderWin30Std\r\n   \r\n  ; check for real mode Windows 3.0\r\n    mov     ax,1606h                ; PMODE_STOP\r\n    int     2fh                     ; in case someone is counting\r\n    ; Real mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1\r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin30Std:\r\n    ; Standard mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1\r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin31:\r\n    ; At this point: CX == 3 means Windows 3.1 enhanced mode\r\n    ;                CX == 2 means Windows 3.1 standard mode\r\n    mov     byte ptr [bRunningWindows], 1\r\n    \r\n    ; Get the version of Windows \r\n    mov     ax, 1600h   ; Get Enhanced-Mode Windows Installed State\r\n    int     2Fh\r\n    mov     byte ptr [MajorVer], al\r\n    mov     byte ptr [MinorVer], ah\r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin30Enh:\r\n    ; Enhanced mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1    \r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  NotRunningUnderWin:                    \r\n    mov     byte ptr [bRunningWindows], 0\r\n    \r\n  ExitLabel:\r\n  }             \r\n  \r\n  WinVer = (WORD) ((MajorVer << 8) + MinorVer);\r\n} \r\n#endif //_DOS \r\n\r\nBOOL COSVersion::IsWindowsCE(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsCE);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber == 950);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95SP1(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingBuildNumber > 950 && \r\n          lpVersionInformation->dwUnderlyingBuildNumber <= 1080);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95OSR2(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion < 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber > 1080);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber == 1998);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98SP1(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber > 1998 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber < 2183);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98SE(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber >= 2183);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsME(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 90);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT31(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT35(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 50);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT351(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 51);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT4(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4);\r\n}\r\n\r\nBOOL COSVersion::IsWindows2000(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 5 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsXPOrWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 5 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsXP(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsXPPersonal(lpVersionInformation) || IsXPProfessional(lpVersionInformation);\r\n}\r\n\r\nWORD COSVersion::GetNTServicePackFromCSDString(LPCTSTR pszCSDVersion)\r\n{\r\n  WORD wServicePack = 0;\r\n  if (_tcslen(pszCSDVersion))\r\n  {\r\n    //Parse out the CSDVersion string\r\n    int i=0;      \r\n    while (pszCSDVersion[i] != _T('\\0') && !_istdigit(pszCSDVersion[i]))\r\n      i++;\r\n    wServicePack = (WORD) (_ttoi(&pszCSDVersion[i]));\r\n  }\r\n\r\n  return wServicePack;\r\n}\r\n\r\n#if defined(_WIN32) || defined(_WIN64)\r\nWORD COSVersion::GetNTServicePackFromRegistry()\r\n{\r\n  //By default assume no service pack\r\n  WORD wServicePack = 0;\r\n\r\n  HKEY hCurrentVersion;\r\n  #ifdef _WIN32\r\n  if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_READ, &hCurrentVersion) == ERROR_SUCCESS)\r\n  #else                                                                                                                                       \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hCurrentVersion) == ERROR_SUCCESS)\r\n  #endif\r\n  {\r\n    BYTE byData[128];\r\n    DWORD dwType;\r\n    DWORD dwSize = 128;\r\n    if (RegQueryValueEx(hCurrentVersion, _T(\"CSDVersion\"), NULL, &dwType, byData, &dwSize) == ERROR_SUCCESS)\r\n    {\r\n      if (dwType == REG_SZ)\r\n      {\r\n        //Stored as a string on all other versions of NT\r\n        wServicePack = GetNTServicePackFromCSDString((TCHAR*) byData);\r\n      }\r\n      else if (dwType == REG_DWORD)\r\n      {\r\n        //Handle the service pack number being stored as a DWORD which happens on NT 3.1\r\n        wServicePack = HIBYTE((WORD) *((DWORD*) byData));\r\n      }\r\n    }\r\n\r\n    //Don't forget to close the registry key we were using      \r\n    RegCloseKey(hCurrentVersion);\r\n  }\r\n\r\n  return wServicePack;\r\n}\r\n#endif //#if defined(_WIN32) || defined(_WIN64)\r\n\r\n#if defined(_WIN32) || defined(_WIN64) || defined (_WINDOWS)\r\nvoid COSVersion::GetTerminalServicesRemoteAdminModeDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Lookup the TSAppCompat registry value\r\n  HKEY hKey = NULL;        \r\n  #ifdef _WIN32\r\n  LONG lResult = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\Terminal Server\"), 0, KEY_READ, &hKey);\r\n  #else                                                                                                                         \r\n  LONG lResult = RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\Terminal Server\"), &hKey);\r\n  #endif\r\n  if (lResult != ERROR_SUCCESS)\r\n    return;\r\n\r\n  DWORD dwTSAppCompat = 1;\r\n  DWORD dwType;\r\n  DWORD dwSize = sizeof(DWORD);\r\n#if defined(_WIN32) || defined(_WIN64)    \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"TSAppCompat\"), NULL, &dwType, (LPBYTE) &dwTSAppCompat, &dwSize);\r\n#else                                                                                                     \r\n  lResult = RegQueryValueEx(hKey, _T(\"TSAppCompat\"), NULL, &dwType, (LPBYTE) &dwTSAppCompat, &dwSize);\r\n#endif  \r\n  if (lResult == ERROR_SUCCESS)\r\n  {\r\n    if (dwTSAppCompat == 0)\r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_REMOTEADMINMODE_TERMINAL;\r\n  }\r\n\r\n  //Don't forget to free up the resource we used\r\n  RegCloseKey(hKey);\r\n}\r\n\r\nvoid COSVersion::GetProductSuiteDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation) \r\n{\r\n  //Lookup the ProductOptions registry key\r\n  HKEY hKey = NULL;        \r\n  #ifdef _WIN32\r\n  LONG lResult = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), 0, KEY_READ, &hKey);\r\n  #else                                                                                                                         \r\n  LONG lResult = RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), &hKey);\r\n  #endif\r\n  if (lResult != ERROR_SUCCESS)\r\n    return;\r\n\r\n  // Determine required size of ProductSuite buffer.\r\n  DWORD dwType = 0;\r\n  DWORD dwSize = 0;                   \r\n#if defined(_WIN32) || defined(_WIN64)  \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, NULL, &dwSize);\r\n#else\r\n  lResult = RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, NULL, &dwSize);\r\n#endif  \r\n  if (lResult != ERROR_SUCCESS || !dwSize)\r\n  {\r\n    RegCloseKey(hKey);\r\n    return;\r\n  }\r\n\r\n  // Allocate buffer.\r\n  LPTSTR lpszProductSuites = (LPTSTR) new BYTE[dwSize];\r\n\r\n  // Retrieve array of product suite strings.\r\n#if defined(_WIN32) || defined(_WIN64)    \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, (LPBYTE) lpszProductSuites, &dwSize);\r\n#else                                                                                                     \r\n  lResult = RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, (LPBYTE) lpszProductSuites, &dwSize);\r\n#endif  \r\n  if (lResult != ERROR_SUCCESS || dwType != REG_MULTI_SZ)\r\n  {\r\n    //Don't forget to free up the resource we used\r\n    delete [] lpszProductSuites;\r\n    RegCloseKey(hKey);\r\n\r\n    return;\r\n  }\r\n\r\n  //Search for suite name in array of strings.\r\n  BOOL bValidated = FALSE;\r\n  LPTSTR lpszSuite = lpszProductSuites;\r\n  while (*lpszSuite) \r\n  {\r\n    //Note we do not need to implement checks for OSSUITE_WEBEDITION\r\n    //as Windows Server 2003 Web Edition which supports GetVersionEx\r\n    //using a OSVERSIONINFOEX structure.\r\n\r\n    //NT Embedded and subsequent version of Embedded Windows supports\r\n    //GetVersionEx using a OSVERSIONINFOEX structure, so no check for \r\n    //it here either\r\n\r\n    //Also I was unable to find any documentation on what Windows NT Datacenter Server\r\n    //puts in the ProductSuite. In Windows 2000 Datacenter it does not matter as it\r\n    //supports GetVersionEx using a OSVERSIONINFOEX structure.\r\n\r\n    //Turn on appropiate fields in the \"wSuiteMask\" bit field\r\n    if (_tcsicmp(lpszSuite, _T(\"Terminal Server\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_TERMINAL;\r\n    else if ((_tcsicmp(lpszSuite, _T(\"SBS\")) == 0) || (_tcsicmp(lpszSuite, _T(\"Small Business\")) == 0))\r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_SMALLBUSINESS;\r\n    else if (_tcsicmp(lpszSuite, _T(\"Enterprise\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_ENTERPRISE;\r\n    else if (_tcsicmp(lpszSuite, _T(\"Personal\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_PERSONAL;\r\n\r\n    lpszSuite += (lstrlen(lpszSuite) + 1);\r\n  }\r\n\r\n  //Don't forget to free up the resource we used\r\n  delete [] lpszProductSuites;\r\n  RegCloseKey(hKey);\r\n}\r\n#endif //#if defined(_WIN32) || defined(_WIN64)  || defined (_WINDOWS)\r\n             \r\n#if defined(_WIN64) || defined(_WIN32)             \r\nBOOL COSVersion::IsWindows30(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows30(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0);\r\n#endif\r\n}\r\n\r\n#if defined(_WIN64) || defined(_WIN32)             \r\nBOOL COSVersion::IsWindows31(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows31(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10);\r\n#endif\r\n}\r\n\r\n#if defined(_WIN64) || defined(_WIN32)            \r\nBOOL COSVersion::IsWindows311(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows311(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 11);\r\n#endif\r\n}\r\n\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\nBOOL COSVersion::IsWindowsForWorkgroups(LPOS_VERSION_INFO lpVersionInformation)\r\n#else\r\nBOOL COSVersion::IsWindowsForWorkgroups(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#endif //#if defined(_WINDOWS) && (defined(_WIN32) || defined(_WIN64))  \r\n{\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          WFWLoaded());\r\n#else\r\n  return FALSE;          \r\n#endif //#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\n}\r\n\r\n\r\n#if defined(_WIN32)\r\nBOOL COSVersion::IsWin32sInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n#else\r\nBOOL COSVersion::IsWin32sInstalled(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x);\r\n#else\r\n  return FALSE;\r\n#endif\r\n}\r\n\r\nBOOL COSVersion::IsNTPreWin2k(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion <= 4);\r\n}\r\n\r\nBOOL COSVersion::IsNTPDC(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsNTPreWin2k(lpVersionInformation)) && \r\n         (lpVersionInformation->OSType == DomainController) &&\r\n         ((lpVersionInformation->dwSuiteMask & OSSUITE_PRIMARY_DOMAIN_CONTROLLER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTStandAloneServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsNTBDC(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && \r\n         (lpVersionInformation->OSType == DomainController) && \r\n         ((lpVersionInformation->dwSuiteMask & OSSUITE_BACKUP_DOMAIN_CONTROLLER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTWorkstation(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->OSType == Workstation);\r\n}\r\n\r\nBOOL COSVersion::IsTerminalServicesInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_TERMINAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsEmbedded(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_EMBEDDEDNT) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsTerminalServicesInRemoteAdminMode(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_REMOTEADMINMODE_TERMINAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::ISSmallBusinessEditionInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_SMALLBUSINESS) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTEnterpriseServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTDatacenterServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000Professional(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == Workstation);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000Server(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000AdvancedServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000DatacenterServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsWindows2000(lpVersionInformation) && (lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000DomainController(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == DomainController);\r\n}\r\n\r\nBOOL COSVersion::IsXPPersonal(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_PERSONAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsXPProfessional(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == Workstation) && !IsXPPersonal(lpVersionInformation);\r\n}\r\n\r\nBOOL COSVersion::IsWebWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_WEBEDITION) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsEnterpriseWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsDatacenterWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsDomainControllerWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == DomainController);\r\n}\r\n\r\nBOOL COSVersion::IsEmulated64Bit(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n{\r\n#ifdef _WIN64\r\n  return TRUE;\r\n#else\r\n  return FALSE;\r\n#endif\r\n}\r\n\r\nBOOL COSVersion::IsUnderlying64Bit(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n{\r\n#ifdef _WIN64\r\n  return TRUE;\r\n#elif UNDER_CE\r\n  return FALSE;\r\n#elif _WIN32\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;  \r\n  \r\n  //Check to see if we are running on 64 bit Windows thro WOW64\r\n  HMODULE hKernel32 = GetModuleHandle(_T(\"KERNEL32.DLL\"));\r\n  if (hKernel32)\r\n  {\r\n    lpfnIsWow64Process pIsWow64Process = (lpfnIsWow64Process) GetProcAddress(hKernel32, \"IsWow64Process\"); \r\n    if (pIsWow64Process)\r\n    {\r\n      BOOL bWow64 = FALSE;\r\n      if (pIsWow64Process(GetCurrentProcess(), &bWow64))\r\n        bSuccess = bWow64;\r\n    }\r\n  }\r\n  return bSuccess;\r\n#else\r\n  return FALSE;\r\n#endif\r\n}"
  },
  {
    "path": "plugins/winamp/OSVer.h",
    "content": "/*\r\nModule : DTWINVER.H\r\nPurpose: Interface of a function to perform\r\n         version detection on OS\r\nCreated: PJN / 11-05-1996\r\n\r\n\r\nCopyright (c) 1997 - 2003 by PJ Naughter.  (Web: www.naughter.com, Email: pjna@naughter.com)\r\n\r\nAll rights reserved.\r\n\r\nCopyright / Usage Details:\r\n\r\nYou are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) \r\nwhen your product is released in binary form. You are allowed to modify the source code in any way you want \r\nexcept you cannot modify the copyright details at the top of each module. If you want to distribute source \r\ncode with your application, then you are only allowed to distribute versions released by the author. This is \r\nto maintain a single distribution point for the source code. \r\n\r\n*/\r\n\r\n#ifndef __DTWINVER_H__                                          \r\n\r\n\r\n////////////////////////////////// defines ////////////////////////////////////\r\n\r\n#define OSSUITE_SMALLBUSINESS             0x00000001\r\n#define OSSUITE_ENTERPRISE                0x00000002\r\n#define OSSUITE_PRIMARY_DOMAIN_CONTROLLER 0x00000004\r\n#define OSSUITE_BACKUP_DOMAIN_CONTROLLER  0x00000008\r\n#define OSSUITE_TERMINAL                  0x00000010\r\n#define OSSUITE_DATACENTER                0x00000020\r\n#define OSSUITE_PERSONAL                  0x00000040\r\n#define OSSUITE_WEBEDITION                0x00000080\r\n#define OSSUITE_EMBEDDEDNT                0x00000100\r\n#define OSSUITE_REMOTEADMINMODE_TERMINAL  0x00000200\r\n#define OSSUITE_UNIPROCESSOR_FREE         0x00000400\r\n#define OSSUITE_UNIPROCESSOR_CHECKED      0x00000800\r\n#define OSSUITE_MULTIPROCESSOR_FREE       0x00001000\r\n#define OSSUITE_MULTIPROCESSOR_CHECKED    0x00002000\r\n\r\n\r\n\r\n////////////////////////////////// Classes ////////////////////////////////////\r\n\r\nclass COSVersion\r\n{\r\npublic:\r\n//Enums\r\n  enum OS_PLATFORM\r\n  {\r\n    Dos = 0,\r\n    Windows3x = 1,\r\n    Windows9x = 2,\r\n    WindowsNT = 3,\r\n    WindowsCE = 4,\r\n  };\r\n\r\n  enum OS_TYPE\r\n  {\r\n    Workstation = 0,\r\n    Server = 1,\r\n    DomainController = 2,\r\n  };\r\n\r\n//defines\r\n  typedef struct _OS_VERSION_INFO\r\n  {\r\n  #ifndef UNDER_CE\r\n    //What version of OS is being emulated\r\n    DWORD dwEmulatedMajorVersion;\r\n    DWORD dwEmulatedMinorVersion;\r\n    DWORD dwEmulatedBuildNumber;\r\n    OS_PLATFORM EmulatedPlatform;\r\n  #ifdef _WIN32                    \r\n    TCHAR szEmulatedCSDVersion[128];\r\n  #else\r\n    char szEmulatedCSDVersion[128];\r\n  #endif  \r\n    WORD wEmulatedServicePackMajor;\r\n    WORD wEmulatedServicePackMinor;\r\n  #endif\r\n\r\n    //What version of OS is really running                 \r\n    DWORD dwUnderlyingMajorVersion;\r\n    DWORD dwUnderlyingMinorVersion;\r\n    DWORD dwUnderlyingBuildNumber;\r\n    OS_PLATFORM UnderlyingPlatform;   \r\n  #ifdef _WIN32                      \r\n    TCHAR szUnderlyingCSDVersion[128];\r\n  #else  \r\n    char szUnderlyingCSDVersion[128];\r\n  #endif  \r\n    WORD wUnderlyingServicePackMajor;\r\n    WORD wUnderlyingServicePackMinor;\r\n    DWORD dwSuiteMask;\r\n    OS_TYPE OSType;\r\n\r\n  #ifdef UNDER_CE\r\n    TCHAR szOEMInfo[256];\r\n    TCHAR szPlatformType[256];\r\n  #endif\r\n  } OS_VERSION_INFO, *POS_VERSION_INFO, FAR *LPOS_VERSION_INFO;\r\n\r\n//Constructors / Destructors\r\n  COSVersion(); \r\n  ~COSVersion();\r\n\r\n//Methods:\r\n  BOOL GetVersion(LPOS_VERSION_INFO lpVersionInformation);\r\n                                 \r\n//Please note that the return values for all the following functions \r\n//are mutually exclusive for example if you are running on \r\n//95 OSR2 then IsWindows95 will return FALSE\r\n  BOOL IsWindows30(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows31(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows311(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsForWorkgroups(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsCE(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95SP1(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95OSR2(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98SP1(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98SE(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsME(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT31(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT35(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT351(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT4(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows2000(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsXPOrWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n//Returns the various flavours of the \"os\" that is installed. Note that these\r\n//functions are not completely mutually exlusive\r\n  BOOL IsWin32sInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTPreWin2k(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsNTWorkstation(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTStandAloneServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTPDC(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTBDC(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTEnterpriseServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTDatacenterServer(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsWin2000Professional(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000Server(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000AdvancedServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000DatacenterServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000DomainController(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsXPPersonal(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsXPProfessional(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsXP(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWebWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEnterpriseWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsDatacenterWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsDomainControllerWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsTerminalServicesInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL ISSmallBusinessEditionInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEmulated64Bit(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsUnderlying64Bit(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEmbedded(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsTerminalServicesInRemoteAdminMode(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\nprotected:\r\n//Defines / typedefs\r\n#if (defined(_WINDOWS) || defined(_DOS)) && (!defined(_WIN32) && !defined(_WIN64))  \r\n  #define CPEX_DEST_STDCALL        0x00000000L\r\n  #define HKEY32                   DWORD                                                               \r\n  #define HKEY_LOCAL_MACHINE       (( HKEY32 ) 0x80000002 )    \r\n  #define TCHAR                    char\r\n  #define _T\r\n  #define _tcsicmp                 strcmpi\r\n  #define _tcscpy                  strcpy\r\n  #define _tcslen                  strlen\r\n  #define _istdigit                isdigit\r\n  #define _ttoi                    atoi\r\n  #define _tcsupr                  strupr\r\n  #define _tcsstr                  strstr\r\n  #define LPCTSTR                  LPCSTR\r\n  #define ERROR_CALL_NOT_IMPLEMENTED  120\r\n  #define REG_DWORD                ( 4 )                                                               \r\n  #define REG_MULTI_SZ             ( 7 )\r\n  #define VER_PLATFORM_WIN32s             0\r\n  #define VER_PLATFORM_WIN32_WINDOWS      1\r\n  #define VER_PLATFORM_WIN32_NT           2\r\n  #define VER_PLATFORM_WIN32_CE           3\r\n#endif                      \r\n                      \r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)  \r\n//Defines / Macros\r\n  #define LPTSTR LPSTR\r\n\r\n  typedef struct OSVERSIONINFO\r\n  { \r\n    DWORD dwOSVersionInfoSize; \r\n    DWORD dwMajorVersion; \r\n    DWORD dwMinorVersion; \r\n    DWORD dwBuildNumber; \r\n    DWORD dwPlatformId; \r\n    char szCSDVersion[128]; \r\n  } OSVERSIONINFO, *POSVERSIONINFO, FAR *LPOSVERSIONINFO; \r\n  \r\n//Methods\r\n  DWORD GetVersion();\r\n  BOOL GetVersionEx(LPOSVERSIONINFO lpVersionInfo);\r\n  LONG RegQueryValueEx(HKEY32 hKey, LPSTR  lpszValueName, LPDWORD lpdwReserved, LPDWORD lpdwType, LPBYTE  lpbData, LPDWORD lpcbData);\r\n  static BOOL WFWLoaded();                                     \r\n\r\n//Function Prototypes\r\n  typedef DWORD (FAR PASCAL  *lpfnLoadLibraryEx32W) (LPCSTR, DWORD, DWORD);\r\n  typedef BOOL  (FAR PASCAL  *lpfnFreeLibrary32W)   (DWORD);\r\n  typedef DWORD (FAR PASCAL  *lpfnGetProcAddress32W)(DWORD, LPCSTR);\r\n  typedef DWORD (FAR __cdecl *lpfnCallProcEx32W)    (DWORD, DWORD, DWORD, DWORD, ...);\r\n  typedef WORD  (FAR PASCAL  *lpfnWNetGetCaps)      (WORD);\r\n\r\n//Member variables\r\n  lpfnLoadLibraryEx32W  m_lpfnLoadLibraryEx32W;\r\n  lpfnFreeLibrary32W    m_lpfnFreeLibrary32W;\r\n  lpfnGetProcAddress32W m_lpfnGetProcAddress32W;\r\n  lpfnCallProcEx32W     m_lpfnCallProcEx32W;\r\n  DWORD                 m_hAdvApi32;    \r\n  DWORD                 m_hKernel32;\r\n  DWORD                 m_lpfnRegQueryValueExA;\r\n  DWORD                 m_lpfnGetVersionExA;\r\n  DWORD                 m_lpfnGetVersion;\r\n#endif //defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))\r\n\r\n#ifdef _WIN32\r\n//Function Prototypes\r\n  typedef BOOL (WINAPI *lpfnIsWow64Process)(HANDLE, PBOOL);  \r\n#endif\r\n\r\n#if defined(_WIN32) || defined(_WINDOWS)\r\n//Defines / Macros\r\n  typedef struct OSVERSIONINFOEX \r\n  {  \r\n    DWORD dwOSVersionInfoSize;  \r\n    DWORD dwMajorVersion;  \r\n    DWORD dwMinorVersion;  \r\n    DWORD dwBuildNumber;  \r\n    DWORD dwPlatformId;  \r\n    TCHAR szCSDVersion[128];  \r\n    WORD wServicePackMajor;  \r\n    WORD wServicePackMinor;  \r\n    WORD wSuiteMask;  \r\n    BYTE wProductType;  \r\n    BYTE wReserved;\r\n  } OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;\r\n                  \r\n//Function Prototypes                  \r\n  typedef BOOL (WINAPI *lpfnGetVersionEx) (LPOSVERSIONINFO);  \r\n#endif  \r\n\r\n#ifndef _DOS         \r\n//Methods\r\n  void GetNTOSTypeFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bOnlyUpdateDCDetails);\r\n  void GetProductSuiteDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation) ;\r\n  void GetTerminalServicesRemoteAdminModeDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation);\r\n  void GetNTSP6aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso);\r\n  void GetXPSP1aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso);\r\n  void GetNTHALDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation);\r\n#else\r\n  BOOL GetInfoBySpawingWriteVer(COSVersion::LPOS_VERSION_INFO lpVersionInformation);\r\n  void GetWinInfo();\r\n#endif\r\n\r\n#if defined(_WIN32) || defined(_WIN64)\r\n  WORD GetNTServicePackFromRegistry();\r\n#endif    \r\n  WORD GetNTServicePackFromCSDString(LPCTSTR pszCSDVersion);\r\n};\r\n\r\n#endif //__DTWINVER_H__"
  },
  {
    "path": "plugins/winamp/Registry.cpp",
    "content": "/////////////////////////////////////////////////////////////////////////////\r\n// Copyright (C) 1998 by Shane Martin\r\n// All rights reserved\r\n//\r\n// Distribute freely, except: don't remove my name from the source or\r\n// documentation (don't take credit for my work), mark your changes (don't\r\n// get me blamed for your possible bugs), don't alter or remove this\r\n// notice.\r\n// No warrantee of any kind, express or implied, is included with this\r\n// software; use at your own risk, responsibility for damages (if any) to\r\n// anyone resulting from the use of this software rests entirely with the\r\n// user.\r\n//\r\n// Send bug reports, bug fixes, enhancements, requests, flames, etc., and\r\n// I'll try to keep a version up to date.  I can be reached as follows:\r\n//    shane.kim@kaiserslautern.netsurf.de\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n// last revised: 24 Apr 98\r\n// Registry.cpp : implementation file\r\n//\r\n// Description:\r\n// CRegistry is a wrapper for the Windows Registry API.  It allows\r\n//  easy modification of the Registry with easy to remember terms like\r\n//  Read, Write, Open, and Close.\r\n#include \"stdafx.h\"\r\n#include \"Registry.h\"\r\n#include <winreg.h>\r\n\r\nCRegistry::CRegistry(HKEY hKeyRoot)\r\n{\r\n\tm_hKey = hKeyRoot;\r\n}\r\n\r\nCRegistry::~CRegistry()\r\n{\r\n\t//PRINTF(DEBUG_DETAIL, \"CRegistry\", \"Destructing\");\r\n\tClose();\r\n}\r\n\r\n\r\nBOOL CRegistry::VerifyKey (HKEY hKeyRoot, LPCTSTR pszPath)\r\n{\r\n\tASSERT (hKeyRoot);\r\n\tASSERT (pszPath);\r\n\r\n\tLONG ReturnValue = RegOpenKeyEx (hKeyRoot, pszPath, 0L,\r\n\t\tKEY_ALL_ACCESS, &m_hKey);\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\t\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = 0L;\r\n\tm_Info.dwType = 0L;\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::VerifyKey (LPCTSTR pszPath)\r\n{\r\n\tASSERT (m_hKey);\r\n\r\n\tLONG ReturnValue = RegOpenKeyEx (m_hKey, pszPath, 0L,\r\n\t\tKEY_ALL_ACCESS, &m_hKey);\r\n\t\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = 0L;\r\n\tm_Info.dwType = 0L;\r\n\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\t\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::VerifyValue (LPCTSTR pszValue)\r\n{\r\n\tASSERT(m_hKey);\r\n\tLONG lReturn = RegQueryValueEx(m_hKey, pszValue, NULL,\r\n\t\tNULL, NULL, NULL);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwSize = 0L;\r\n\tm_Info.dwType = 0L;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::CreateKey (HKEY hKeyRoot, LPCTSTR pszPath)\r\n{\r\n\tDWORD dw;\r\n\r\n\tLONG ReturnValue = RegCreateKeyEx (hKeyRoot, pszPath, 0L, NULL,\r\n\t\tREG_OPTION_NON_VOLATILE , KEY_ALL_ACCESS, NULL, \r\n\t\t&m_hKey, &dw);\r\n\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = 0L;\r\n\tm_Info.dwType = 0L;\r\n\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::Open (HKEY hKeyRoot, LPCTSTR pszPath)\r\n{\r\n\tm_sPath = pszPath;\r\n\r\n\tLONG ReturnValue = RegOpenKeyEx (hKeyRoot, pszPath, 0L,\r\n\t\tKEY_ALL_ACCESS, &m_hKey);\r\n\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = 0L;\r\n\tm_Info.dwType = 0L;\r\n\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nvoid CRegistry::Close()\r\n{\r\n\tif (m_hKey)\r\n\t{\r\n\t\tRegCloseKey (m_hKey);\r\n\t\tm_hKey = NULL;\r\n\t}\r\n}\r\n\r\nBOOL CRegistry::Write (LPCTSTR pszKey, int iVal)\r\n{\r\n\tDWORD dwValue;\r\n\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\t\r\n\tdwValue = (DWORD)iVal;\r\n\tLONG ReturnValue = RegSetValueEx (m_hKey, pszKey, 0L, REG_DWORD,\r\n\t\t(CONST BYTE*) &dwValue, sizeof(DWORD));\r\n\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = sizeof(DWORD);\r\n\tm_Info.dwType = REG_DWORD;\r\n\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\t\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::Write (LPCTSTR pszKey, DWORD dwVal)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\treturn RegSetValueEx (m_hKey, pszKey, 0L, REG_DWORD,\r\n\t\t(CONST BYTE*) &dwVal, sizeof(DWORD));\r\n}\r\n\r\nBOOL CRegistry::Write (LPCTSTR pszKey, LPBYTE pData, int nSize)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\treturn RegSetValueEx(m_hKey, pszKey, 0L, REG_BINARY, pData, nSize);\r\n}\r\n\r\nBOOL CRegistry::Write (LPCTSTR pszKey, LPCTSTR pszData)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\tASSERT(pszData);\r\n\r\n\tLONG ReturnValue = RegSetValueEx (m_hKey, pszKey, 0L, REG_SZ,\r\n\t\t(CONST BYTE*) pszData, strlen(pszData) + 1);\r\n\r\n\tm_Info.lMessage = ReturnValue;\r\n\tm_Info.dwSize = strlen(pszData) + 1;\r\n\tm_Info.dwType = REG_SZ;\r\n\r\n\tif(ReturnValue == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\t\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::Read(LPCTSTR pszKey, int& iVal)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\r\n\tDWORD dwType;\r\n\tDWORD dwSize = sizeof (DWORD);\r\n\tDWORD dwDest;\r\n\r\n\tLONG lReturn = RegQueryValueEx (m_hKey, (LPSTR) pszKey, NULL,\r\n\t\t&dwType, (BYTE *) &dwDest, &dwSize);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = dwType;\r\n\tm_Info.dwSize = dwSize;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t{\r\n\t\tiVal = (int)dwDest;\r\n\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::Read (LPCTSTR pszKey, DWORD& dwVal)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\r\n\tDWORD dwType;\r\n\tDWORD dwSize = sizeof (DWORD);\r\n\tDWORD dwDest;\r\n\r\n\tLONG lReturn = RegQueryValueEx (m_hKey, (LPSTR) pszKey, NULL, \r\n\t\t&dwType, (BYTE *) &dwDest, &dwSize);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = dwType;\r\n\tm_Info.dwSize = dwSize;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t{\r\n\t\tdwVal = dwDest;\r\n\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::Read (LPCTSTR pszKey, CStdString& sVal)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\r\n\tDWORD dwType;\r\n\tDWORD dwSize = 200;\r\n\tchar  szString[255];\r\n\r\n\tLONG lReturn = RegQueryValueEx (m_hKey, (LPSTR) pszKey, NULL,\r\n\t\t&dwType, (BYTE *) szString, &dwSize);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = dwType;\r\n\tm_Info.dwSize = dwSize;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t{\r\n\t\tsVal = szString;\r\n\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\n\r\nBOOL CRegistry::Read (LPCTSTR pszKey, LPBYTE pData, int nSize)\r\n{\r\n\tASSERT(m_hKey);\r\n\tASSERT(pszKey);\r\n\r\n\tDWORD dwType;\r\n\tDWORD dwSize;\r\n\tLONG lReturn = RegQueryValueEx(m_hKey, pszKey, 0L, &dwType, pData, &dwSize);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = dwType;\r\n\tm_Info.dwSize = dwSize;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t{\r\n\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::DeleteValue (LPCTSTR pszValue)\r\n{\r\n\tASSERT(m_hKey);\r\n\tLONG lReturn = RegDeleteValue(m_hKey, pszValue);\r\n\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = 0L;\r\n\tm_Info.dwSize = 0L;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CRegistry::DeleteValueKey (HKEY hKeyRoot, LPCTSTR pszPath)\r\n{\r\n\tASSERT(pszPath);\r\n\tASSERT(hKeyRoot);\r\n\r\n\tLONG lReturn = RegDeleteKey(hKeyRoot, pszPath);\r\n\r\n\tm_Info.lMessage = lReturn;\r\n\tm_Info.dwType = 0L;\r\n\tm_Info.dwSize = 0L;\r\n\r\n\tif(lReturn == ERROR_SUCCESS)\r\n\t\treturn TRUE;\r\n\r\n\treturn FALSE;\r\n}\r\n"
  },
  {
    "path": "plugins/winamp/Registry.h",
    "content": "/////////////////////////////////////////////////////////////////////////////\r\n// Copyright (C) 1998 by Shane Martin\r\n// All rights reserved\r\n//\r\n// Distribute freely, except: don't remove my name from the source or\r\n// documentation (don't take credit for my work), mark your changes (don't\r\n// get me blamed for your possible bugs), don't alter or remove this\r\n// notice.\r\n// No warrantee of any kind, express or implied, is included with this\r\n// software; use at your own risk, responsibility for damages (if any) to\r\n// anyone resulting from the use of this software rests entirely with the\r\n// user.\r\n//\r\n// Send bug reports, bug fixes, enhancements, requests, flames, etc., and\r\n// I'll try to keep a version up to date.  I can be reached as follows:\r\n//    shane.kim@kaiserslautern.netsurf.de\r\n/////////////////////////////////////////////////////////////////////////////\r\n#ifndef __REGISTRY_H\r\n#define __REGISTRY_H\r\n\r\n#include \"StdString.h\"\r\n\r\n#define REG_RECT\t0x0001\r\n#define REG_POINT\t0x0002\r\n\r\nclass CRegistry\r\n{\r\n// Construction\r\npublic:\r\n\tCRegistry(HKEY hKeyRoot = HKEY_LOCAL_MACHINE);\r\n\tvirtual ~CRegistry();\r\n\r\n\tstruct REGINFO\r\n\t{\r\n\t\tLONG lMessage;\r\n\t\tDWORD dwType;\r\n\t\tDWORD dwSize;\r\n\t} m_Info;\r\n// Operations\r\npublic:\r\n\tBOOL VerifyKey (HKEY hKeyRoot, LPCTSTR pszPath);\r\n\tBOOL VerifyKey (LPCTSTR pszPath);\r\n\tBOOL VerifyValue (LPCTSTR pszValue);\r\n\tBOOL CreateKey (HKEY hKeyRoot, LPCTSTR pszPath);\r\n\tBOOL Open (HKEY hKeyRoot, LPCTSTR pszPath);\r\n\tvoid Close();\r\n\r\n\tBOOL DeleteValue (LPCTSTR pszValue);\r\n\tBOOL DeleteValueKey (HKEY hKeyRoot, LPCTSTR pszPath);\r\n\r\n\tBOOL Write (LPCTSTR pszKey, int iVal);\r\n\tBOOL Write (LPCTSTR pszKey, DWORD dwVal);\r\n\tBOOL Write (LPCTSTR pszKey, LPCTSTR pszVal);\r\n\tBOOL Write (LPCTSTR pszKey, LPCRECT rcRect);\r\n\tBOOL Write (LPCTSTR pszKey, LPPOINT& lpPoint);\r\n\tBOOL Write (LPCTSTR pszKey, LPBYTE pData, int nSize);\r\n\r\n\tBOOL Read (LPCTSTR pszKey, int& iVal);\r\n\tBOOL Read (LPCTSTR pszKey, DWORD& dwVal);\r\n\tBOOL Read (LPCTSTR pszKey, CStdString& sVal);\r\n\tBOOL Read (LPCTSTR pszKey, LPPOINT& lpPoint);\r\n\tBOOL Read (LPCTSTR pszKey, LPRECT& rcRect);\r\n\tBOOL Read (LPCTSTR pszKey, LPBYTE pData, int nSize);\r\n\r\nprotected:\t\r\n\tHKEY \tm_hKey;\r\n\tCStdString m_sPath;\r\n};\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/winamp/Scrobbler.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"Scrobbler.h\"\r\n#include <shellapi.h>\r\n#include <io.h>\r\n//#include <exception>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\n/*#############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : CScrobbler\r\n## Description  : Constructor\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nCScrobbler::CScrobbler()\r\n{\r\n    m_hInstance             = NULL;\r\n    m_strWorkingDir         = _T(\"\");\r\n    m_bTrackPlayFlag        = FALSE;\r\n    m_nMaxLogFileSize       = -1;\r\n    m_bUseNowPlaying        = FALSE;\r\n   \tm_bExitThread\t\t\t= FALSE;\r\n\tm_bRunningCallback\t\t= FALSE;\r\n    m_bAllowHttpStreams     = FALSE;\r\n    \r\n    m_AsState = AS_STOPPED;\r\n    \r\n    memset(&m_CurrentSong, 0, sizeof(m_CurrentSong));\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : ~CScrobbler\r\n## Description  : Destructor\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nCScrobbler::~CScrobbler()\r\n{\r\n    //OutputDebugString(\"~CScrobbler\\n\");\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : StartScrobbling\r\n## Description  : Startup routine for class\r\n##                Checks the data is valid and that\r\n##                the clss is ready to startup\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : strWorkingDir - Plugin dir path\r\n##                hInstance - HINSTANCE of plugin\r\n## Return       : BOOL (TRUE = success)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::StartScrobbling(CStdString strWorkingDir, HINSTANCE hInstance /*=NULL*/)\r\n{\r\n    BOOL    bRet = FALSE;\r\n    UINT    threadID = 0;\r\n\r\n    if ( ( !strWorkingDir.IsEmpty() ) )\r\n    {\r\n        m_strWorkingDir = strWorkingDir;\r\n        m_hInstance = hInstance;\r\n        m_Version.Refresh(m_hInstance);\r\n\r\n        int pos = strWorkingDir.ReverseFind('\\\\');\r\n        m_strWorkingDir = strWorkingDir.Left(pos+1);\r\n        m_strFileName = strWorkingDir.Mid(pos+1);\r\n    }\r\n    else\r\n        PRINTF(DEBUG_ERROR, \"CScrobbler::StartScrobbling\", \"Working dir is blank.\");\r\n    \r\n    InitialiseLogging();\r\n\r\n    PRINTF(DEBUG_FLOW,\r\n        \"CScrobbler::StartScrobbling\", \"Working dir %s\", \r\n        strWorkingDir.c_str());\r\n\r\n    m_Submitter = new ScrobSubmitter();\r\n    m_Submitter->Init(GetAppId(), ScrobSubCallback, this);\r\n   \r\n    // Timer\r\n    unsigned dwThreadId = 0;\r\n    if(_beginthreadex(NULL, 0, TimeUpdaterThread, reinterpret_cast<void *>(this), 0, &dwThreadId) == 0)\r\n    {\r\n        PRINTF(DEBUG_ERROR, \"CScrobbler::StartScrobbling\", \"Could not start timer thread.\");\r\n        bRet = FALSE;\r\n    }\r\n    \r\n    PRINTF(DEBUG_RQD, \"CScrobbler::StartScrobbling\", \"Startup Complete.\");\r\n\r\n    return bRet;\r\n}\r\n    \r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : StopScrobbling\r\n## Description  : Performs closedown functions\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : BOOL (TRUE = success)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::StopScrobbling()\r\n{\r\n    PRINTF(DEBUG_FLOW, \"CScrobbler::StopScrobbling\", \"Exiting...\");\r\n\r\n    ASStop();\r\n    m_Submitter->Term();\r\n    delete m_Submitter;\r\n    \r\n    // This is terrible I know but I spent a day trying to debug the cause of\r\n    // Winamp crashing on shutdown without this here but to no avail. :(\r\n    Sleep(200);\r\n\r\n    m_bExitThread = TRUE;\r\n\r\n    ::SetEvent(m_hTimerEvent);\r\n    \r\n    return TRUE;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : TimerCallback\r\n## Description  : Callback function for the external\r\n##                timer. Checks playback state and \r\n##                triggers submissions\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : BOOL (FALSE causes timer to be killed)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::TimerCallback()\r\n{\r\n    BOOL bRet = TRUE;\r\n\r\n    // If we are already checking or we aren't enabled don't continue.\r\n    // We don't return FALSE. This would\r\n    // cancel the timer which is OK when we are disabled but if the user enables us \r\n    // without restarting the player we have no way to restart the timer.\r\n    // Get it? Good.\r\n    if (m_bRunningCallback == TRUE)\r\n        return bRet;\r\n\r\n    m_bRunningCallback = TRUE;\r\n\r\n    // Non-blocking track play detection\r\n    if(m_bTrackPlayFlag)\r\n    {\r\n        // If we get here, a new track has just started\r\n        SONG_INFO tmpSong;\r\n        memset(&tmpSong, 0, sizeof(tmpSong));\r\n\r\n        // Try UTF8 first\r\n        BOOL bUtf8Ok = GetCurrentSong(&tmpSong, true);\r\n        if ( !bUtf8Ok )\r\n        {\r\n            // If not, we try the ASCII version (for versions before Winamp 5.13)\r\n            memset(&tmpSong, 0, sizeof(tmpSong));\r\n            GetCurrentSong(&tmpSong, false);\r\n        }\r\n        \r\n        memcpy(&m_CurrentSong, &tmpSong, sizeof(m_CurrentSong));\r\n\r\n        m_bTrackPlayFlag = FALSE;\r\n\r\n        if (!SupportedFileType(m_CurrentSong.m_strFileName))\r\n        {\r\n            ASStop();\r\n            m_AsState = AS_STOPPED;\r\n            m_bRunningCallback = FALSE;\r\n            return bRet;\r\n        }\r\n\r\n        // Send Start\r\n        ASStart( bUtf8Ok ? ScrobSubmitter::UTF_8 : ScrobSubmitter::ISO_8859_1 );\r\n        m_AsState = AS_PLAYING;\r\n    }\r\n\r\n    switch (m_AsState)\r\n    {\r\n        case AS_PLAYING:\r\n            if (IsPaused())\r\n            {\r\n                ASPause();\r\n                m_AsState = AS_PAUSED;\r\n            }\r\n            else if (IsStopped())\r\n            {\r\n                ASStop();\r\n                m_AsState = AS_STOPPED;\r\n            }\r\n            break;\r\n        \r\n        case AS_STOPPED:\r\n            break;\r\n\r\n        case AS_PAUSED:\r\n            if (IsPlaying())\r\n            {\r\n                ASResume();\r\n                m_AsState = AS_PLAYING;\r\n            }\r\n            else if (IsStopped())\r\n            {\r\n                ASStop();\r\n                m_AsState = AS_STOPPED;\r\n            }\r\n            break;\r\n        \r\n        default:\r\n            ASSERT(false);\r\n    }\r\n\r\n    m_bRunningCallback = FALSE;\r\n    return bRet;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module\t\t: CScrobbler\r\n## Function\t\t: SupportedFileType\r\n## Description\t: Checks that the file type is valid \r\n##                for sending to the server\r\n##\r\n## Author(s)\t: Spib\r\n##\r\n## Parameters\t: strPath - full file path\r\n## Return\t\t: TRUE if file is OK\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::SupportedFileType(CStdString strPath)\r\n{\r\n\tBOOL\t\tbRet = TRUE;\r\n\tCStdString\tstrTemp;\r\n\tCStdString\tstrReason;\r\n\tint\t\t\tnPos = 0;\r\n\r\n\tstrPath.MakeUpper();\r\n\r\n\tstrReason = \"Unknown\";\r\n\r\n\tif(!strPath.IsEmpty() && (strPath.GetLength() > 3))\r\n\t{\r\n\t\tstrTemp = strPath.Left(7);\r\n\t\tif((strTemp == \"HTTP://\") && !m_bAllowHttpStreams)\r\n\t\t{\r\n\t\t\tbRet = FALSE;\r\n\t\t\tstrReason = \"Cannot submit HTTP streams\";\r\n            PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n\t\t\treturn bRet;\r\n\t\t}\r\n\t\tstrTemp = strPath.Left(6);\r\n\t\tif((strTemp == \"MMS://\") && !m_bAllowHttpStreams)\r\n\t\t{\r\n\t\t\tbRet = FALSE;\r\n\t\t\tstrReason = \"Cannot submit MMS streams\";\r\n            PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n\t\t\treturn bRet;\r\n\t\t}\r\n\t\t// Is this a file?\r\n\t\tif (strTemp.Mid(1,2) == \":\\\\\" ||\r\n\t\t    strTemp.Mid(0,2) == \"\\\\\\\\\")\r\n\t\t{\r\n\t\t\tnPos = strPath.ReverseFind('.');\r\n\r\n\t\t\tif(nPos > 0)\r\n\t\t\t{\r\n\t\t\t\tstrTemp = strPath.Mid(nPos+1);\r\n\t\t\r\n\t\t\t\tif ((strTemp == \"NSV\") || \r\n\t\t\t\t    (strTemp == \"AVI\") ||\r\n    \t\t\t\t(strTemp == \"M2V\") ||\r\n\t    \t\t\t(strTemp == \"ASF\") ||\r\n\t\t    \t\t(strTemp == \"WMV\") ||\r\n\t\t\t    \t(strTemp == \"MPG\") ||\r\n\t\t\t\t    (strTemp == \"MPEG\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tstrReason = \"Cannot submit Video files\";\r\n\t\t\t\t\tbRet = FALSE;\r\n                    PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                        \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n                    return bRet;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\treturn bRet;\t\r\n}\r\n\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : GetVersionString\r\n## Description  : Gets a string with the app name and\r\n##                version.\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : CStdString - version string\r\n##\r\n##############################################*/\r\nCStdString CScrobbler::GetVersionString()\r\n{\r\n    CStdString strText;\r\n    CStdString strVer;\r\n\r\n#ifdef _DEBUG\r\n    strVer = \"INTERNAL DEBUG BUILD\";\r\n#else\r\n    //strVer = \"INTERNAL TEST BUILD\";\r\n#endif\r\n\r\n    strText.Format(\"%s %s\", AUDIOSCROBBLER_VERSION, strVer.c_str());\r\n\r\n    return strText;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : InitialiseLogging\r\n## Description  : Sets up the logging stuff\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nvoid CScrobbler::InitialiseLogging()\r\n{       \r\n    CStdString strVer;\r\n    CStdString strTemp;\r\n    CStdString strFileName;\r\n\r\n    // Initialise logging stuff\r\n    strTemp.Format(\"%s\\\\WinampPlugin.log\", ScrobSubmitter::GetLogPath().c_str());\r\n\r\n    // Here's how it works - \r\n    // If you have specified a log size > zero, the log\r\n    // is appended to up to the maximum size until the limit\r\n    // is reached. Then it is deleted and started again.\r\n    // If you specify a size of zero, logging is disabled.\r\n    // If you specify a size of < zero, logging is enabled but\r\n    // the log is overwritten on each execution and there is no \r\n    // maximum size.\r\n    if(m_nMaxLogFileSize > 0)\r\n    {\r\n        DEBUG_INIT(strTemp, FALSE, TRUE, FALSE);\r\n    }\r\n    else if(m_nMaxLogFileSize == 0)\r\n    {\r\n        DEBUG_INIT(strTemp, FALSE, FALSE, FALSE);\r\n    }\r\n    else\r\n    {\r\n        DEBUG_INIT(strTemp, TRUE, TRUE, FALSE);\r\n    }\r\n\r\n    DEBUG_SET_MAXSIZE(m_nMaxLogFileSize);\r\n\r\n#ifdef _DEBUG\r\n    DEBUG_SET_LEVEL(DEBUG_DETAIL);\r\n#else\r\n    DEBUG_SET_LEVEL(DEBUG_INFO);\r\n#endif\r\n\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s v%s (Build %s) %s\", GetAppName().c_str(), GetVersionString().c_str(), m_Version.GetAppPrivateBuild().c_str(), m_strFileName.c_str());\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s\", GetPlayerVersion().c_str());\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s\", m_Version.GetOSVersion().c_str());\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : OnTrackPlay\r\n## Description  : Called when a new track has started\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nvoid CScrobbler::OnTrackPlay()\r\n{\r\n    // Only called in WMP version, never in Winamp.\r\n    m_bTrackPlayFlag = TRUE;\r\n}\r\n\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : TimeUpdaterThread\r\n## Description  : Acts as a rudimentary timer\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : pParam - pScrobbler ptr\r\n## Return       : DWORD\r\n##\r\n##############################################*/\r\nunsigned __stdcall CScrobbler::TimeUpdaterThread(LPVOID pParam)\r\n{ \r\n    CScrobbler* pScrobbler = reinterpret_cast<CScrobbler*>(pParam);\r\n    \r\n    PRINTF(DEBUG_DETAIL, \"CScrobbler::TimeUpdaterThread\", \"Creating Event\");\r\n\r\n    pScrobbler->m_hTimerEvent = ::CreateEvent(NULL,// Default security\r\n                                    TRUE,// Manual reset\r\n                                    FALSE,// Initial state\r\n                                    NULL // Name\r\n                                    );\r\n    \r\n    // Start a 0.5 second timer, check if we need to exit\r\n    // After AUDIOSCROBBLER_TIMER seconds, do the callback\r\n    // Doing it this way means we can exit gracefully\r\n    while (pScrobbler->m_bExitThread == FALSE)\r\n    {\r\n        // The event is only signalled on exit so this is essentially a Sleep(500)\r\n        ::WaitForSingleObject(pScrobbler->m_hTimerEvent, 500);\r\n\r\n        if(pScrobbler->m_bExitThread == FALSE)\r\n        {\r\n            pScrobbler->TimerCallback();\r\n        }\r\n    }\r\n    \r\n    return 0;\r\n}\r\n\r\n// AS communication functions    \r\nvoid CScrobbler::ASStart( ScrobSubmitter::Encoding enc )\r\n{\r\n    int id = m_Submitter->Start(\r\n        m_CurrentSong.m_strArtist,\r\n\t\tm_CurrentSong.m_strAlbumArtist,\r\n        m_CurrentSong.m_strTrack,\r\n        m_CurrentSong.m_strAlbum,\r\n        \"\",\r\n        m_CurrentSong.m_nLength,\r\n        m_CurrentSong.m_strFileName,\r\n        enc);\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Start for \" << \r\n        m_CurrentSong.m_strArtist << \" - \" << m_CurrentSong.m_strTrack;\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASStart\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASStop()\r\n{\r\n    int id = m_Submitter->Stop();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Stop\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASStop\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASPause()\r\n{\r\n    int id = m_Submitter->Pause();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Pause\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASPause\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASResume()\r\n{\r\n    int id = m_Submitter->Resume();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Resume\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASResume\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ScrobSubStatus(int reqID, bool error, std::string message)\r\n{\r\n    #ifdef _DEBUG\r\n        if (error)\r\n        {\r\n            MessageBox(NULL, message.c_str(), NULL, MB_OK);\r\n        }\r\n    #endif\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << reqID << \": \" << message;\r\n    \r\n    int level = error ? DEBUG_ERROR_NC : DEBUG_INFO;\r\n    PRINTF(level, \"CScrobbler::ScrobSubStatus\", os.str().c_str());\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/winamp/Scrobbler.h",
    "content": "  // Scrobbler.h: interface for the CScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_)\r\n#define AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n/*##############################################\r\n##\r\n## Module           : CAudioScrobbler\r\n## Description      : This class is the core of the \r\n##                    AudioScrobbler.\r\n##\r\n## Author(s)        : RJ, Spib\r\n##                  : Butchered by Erik for new AS plugin\r\n##\r\n## Modifications\r\n##\r\n## 07-04-2003 - Mods to integrate the new client protocol\r\n##\r\n##############################################*/\r\n\r\n#pragma once\r\n\r\n#include \"VersionApp.h\"\r\n#include \"StdStringArray.h\"\r\n#include \"ScrobSubmitter.h\"\r\n\r\n#define AUDIOSCROBBLER_VERSION              m_Version.GetAppVersion().c_str()\r\n#define SONG_INFO_FIELD_SIZE                1024\r\n\r\ntypedef struct \r\n{\r\n    char    m_strFileName[MAX_PATH];\r\n    char    m_strArtist[SONG_INFO_FIELD_SIZE];\r\n\tchar    m_strAlbumArtist[SONG_INFO_FIELD_SIZE];\r\n    char    m_strTrack [SONG_INFO_FIELD_SIZE];\r\n    char    m_strAlbum [SONG_INFO_FIELD_SIZE];\r\n    char    m_strGenre [SONG_INFO_FIELD_SIZE];\r\n    char    m_strComment [SONG_INFO_FIELD_SIZE];\r\n    int     m_nYear;\r\n    int     m_nTrackNo;\r\n    int     m_nLength;\r\n}SONG_INFO;\r\n\r\nclass CScrobbler  \r\n{\r\npublic:\r\n    CScrobbler();\r\n    virtual ~CScrobbler();\r\n\r\n    BOOL                StartScrobbling(CStdString strWorkingDir, HINSTANCE hInstance = NULL); // Init Routine\r\n    BOOL                StopScrobbling();                           // Init Routine\r\n\r\n    //Virtual Overrides\r\n    virtual CStdString  GetAppName() = 0;\r\n    virtual CStdString  GetAppId() = 0;\r\n    virtual CStdString  GetRegKey() = 0;\r\n    virtual CStdString  GetPlayerVersion() = 0; // Returns the player specific version string\r\n    virtual BOOL        IsPlaying() = 0;\r\n    virtual BOOL        IsPaused() = 0;\r\n    virtual BOOL        IsStopped() = 0;\r\n    virtual CStdString  GetCurrentSongFileName() = 0;\r\n    virtual int         GetTrackLength() = 0;\r\n    virtual int         GetTrackPosition() = 0;\r\n    virtual BOOL        GetCurrentSong(SONG_INFO* pSong, bool utf8 = true) = 0;\r\n    virtual HWND        GetParentWnd() = 0;\r\n    \r\n    // Other\r\n    CStdString          GetVersionString();     // Get the AudioScrobbler's version info\r\n    CStdString          GetBuild(){return m_Version.GetAppPrivateBuild();}\r\n\r\n    static              unsigned __stdcall TimeUpdaterThread(LPVOID p);\r\n    BOOL                TimerCallback();\r\n\r\n    static void         ScrobSubCallback(int reqID, bool error, std::string message, void* userData)\r\n    { reinterpret_cast<CScrobbler*>(userData)->ScrobSubStatus(reqID, error, message); }\r\n\r\nprotected:  \r\n\tvirtual BOOL\t    SupportedFileType(CStdString strPath);\t// Is this a supported file type?\r\n    void                OnTrackPlay();                              // A new track has started\r\n    void                InitialiseLogging();                                // Initialise the logging\r\n    CStdString          ConvertFileSize(int nBytes);                // Convert file size in bytes to KB/MB\r\n    ScrobSubmitter*     m_Submitter;\r\n    \r\npublic:\r\n    // Internal Variables\r\n    CVersionApp             m_Version;\r\n    CStdString              m_strWorkingDir;            // Current working dir\r\n    CStdString              m_strFileName;              // Module File Name\r\n    HINSTANCE               m_hInstance;\r\n    BOOL                    m_bExitThread;\r\n    HANDLE                  m_hTimerEvent;              // Timer Handle\r\n\r\n    // Song playback stuff\r\n    SONG_INFO               m_CurrentSong;          // Currently Playing Song\r\n    BOOL                    m_bTrackPlayFlag;\r\n\r\n    // State Flags\r\n    BOOL                    m_bRunningCallback;     // Are we currently in the timer callback?\r\n\r\n    // Configurable Variables\r\n    int                     m_nMaxLogFileSize;      // Max size of debug log file\r\n    BOOL                    m_bAllowHttpStreams;\r\n    BOOL                    m_bUseNowPlaying;\r\n    \r\nprivate:\r\n\r\n    void ASStart( ScrobSubmitter::Encoding enc );\r\n    void ASStop();\r\n    void ASPause();\r\n    void ASResume();\r\n\r\n    void ScrobSubStatus(int reqID, bool error, std::string message);\r\n    \r\n    enum EAsState\r\n    {\r\n        AS_STOPPED,\r\n        AS_PLAYING,\r\n        AS_PAUSED\r\n    };\r\n    \r\n    EAsState        m_AsState;\r\n};\r\n\r\n#endif // !defined(AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/winamp/StdAfx.cpp",
    "content": "// stdafx.cpp : source file that includes just the standard includes\r\n//\tGen_AudioScrobbler.pch will be the pre-compiled header\r\n//\tstdafx.obj will contain the pre-compiled type information\r\n\r\n#include \"stdafx.h\"\r\n\r\n// TODO: reference any additional headers you need in STDAFX.H\r\n// and not in this file\r\n"
  },
  {
    "path": "plugins/winamp/StdAfx.h",
    "content": "// stdafx.h : include file for standard system include files,\r\n//  or project specific include files that are used frequently, but\r\n//      are changed infrequently\r\n//\r\n\r\n#pragma once\r\n\r\n// Insert your headers here\r\n#define WIN32_LEAN_AND_MEAN\t\t// Exclude rarely-used stuff from Windows headers\r\n\r\n#include <windows.h>\r\n#include <atlbase.h>\r\nextern CComModule _Module;\r\n#include <atlwin.h>\r\n#include <atlcom.h>\r\n#include <atlhost.h>\r\n#pragma warning( disable : 4192 ) \r\n\r\n#include \"stdstring.h\"\r\n#include \"dbg.h\"\r\n#include \"ComDATE.h\""
  },
  {
    "path": "plugins/winamp/StdString.h",
    "content": "// =============================================================================\r\n//  FILE:  StdString.h\r\n//  AUTHOR:\tJoe O'Leary (with outside help noted in comments)\r\n//\r\n//\r\n//\t\tIf you find any bugs int his code, please let me know:\r\n//\r\n//\t\t\t\tjmoleary@earthlink.net\r\n//\t\t\t\thttp://www.joeo.net/stdstring.htm (a bit outdated)\r\n//\r\n//      The latest version of this code should always be available at the\r\n//      following link:\r\n//\r\n//              http://www.joeo.net/code/StdString.zip (Dec 6, 2003)\r\n//\r\n//\r\n//  REMARKS:\r\n//\t\tThis header file declares the CStdStr template.  This template derives\r\n//\t\tthe Standard C++ Library basic_string<> template and add to it the\r\n//\t\tthe following conveniences:\r\n//\t\t\t- The full MFC CString set of functions (including implicit cast)\r\n//\t\t\t- writing to/reading from COM IStream interfaces\r\n//\t\t\t- Functional objects for use in STL algorithms\r\n//\r\n//\t\tFrom this template, we intstantiate two classes:  CStdStringA and\r\n//\t\tCStdStringW.  The name \"CStdString\" is just a #define of one of these,\r\n//\t\tbased upone the UNICODE macro setting\r\n//\r\n//\t\tThis header also declares our own version of the MFC/ATL UNICODE-MBCS\r\n//\t\tconversion macros.  Our version looks exactly like the Microsoft's to\r\n//\t\tfacilitate portability.\r\n//\r\n//\tNOTE:\r\n//\t\tIf you you use this in an MFC or ATL build, you should include either\r\n//\t\tafx.h or atlbase.h first, as appropriate.\r\n//\r\n//\tPEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS:\r\n//\r\n//\t\tSeveral people have helped me iron out problems and othewise improve\r\n//\t\tthis class.  OK, this is a long list but in my own defense, this code\r\n//\t\thas undergone two major rewrites.  Many of the improvements became\r\n//\t\tnecessary after I rewrote the code as a template.  Others helped me\r\n//\t\timprove the CString facade.\r\n//\r\n//\t\tAnyway, these people are (in chronological order):\r\n//\r\n//\t\t\t- Pete the Plumber (???)\r\n//\t\t\t- Julian Selman\r\n//\t\t\t- Chris (of Melbsys)\r\n//\t\t\t- Dave Plummer\r\n//\t\t\t- John C Sipos\r\n//\t\t\t- Chris Sells\r\n//\t\t\t- Nigel Nunn\r\n//\t\t\t- Fan Xia\r\n//\t\t\t- Matthew Williams\r\n//\t\t\t- Carl Engman\r\n//\t\t\t- Mark Zeren\r\n//\t\t\t- Craig Watson\r\n//\t\t\t- Rich Zuris\r\n//\t\t\t- Karim Ratib\r\n//\t\t\t- Chris Conti\r\n//\t\t\t- Baptiste Lepilleur\r\n//\t\t\t- Greg Pickles\r\n//\t\t\t- Jim Cline\r\n//\t\t\t- Jeff Kohn\r\n//\t\t\t- Todd Heckel\r\n//\t\t\t- Ullrich Pollhne\r\n//\t\t\t- Joe Vitaterna\r\n//\t\t\t- Joe Woodbury\r\n//\t\t\t- Aaron (no last name)\r\n//\t\t\t- Joldakowski (???)\r\n//\t\t\t- Scott Hathaway\r\n//\t\t\t- Eric Nitzche\r\n//\t\t\t- Pablo Presedo\r\n//\t\t\t- Farrokh Nejadlotfi\r\n//\t\t\t- Jason Mills\r\n//\t\t\t- Igor Kholodov\r\n//\t\t\t- Mike Crusader\r\n//\t\t\t- John James\r\n//\t\t\t- Wang Haifeng\r\n//\t\t\t- Tim Dowty\r\n//          - Arnt Witteveen\r\n//          - Glen Maynard\r\n//          - Paul DeMarco\r\n//          - Bagira (full name?)\r\n//          - Ronny Schulz\r\n//          - Jakko Van Hunen\r\n//\t\t\t- Charles Godwin\r\n//\t\t\t- Henk Demper\r\n//\t\t\t- Greg Marr\r\n//\t\t\t- Bill Carducci\r\n//\t\t\t- Brian Groose\r\n//\t\t\t- MKingman\r\n//\r\n//\tREVISION HISTORY\r\n//\r\n//\t  2004-APR-22 - A big, big thank you to \"MKingman\" (whoever you are) for\r\n//\t\t\t\t\tfinally spotting a silly little error in StdCodeCvt that\r\n//\t\t\t\t\thas been causing me (and users of CStdString) problems for\r\n//\t\t\t\t\tyears in some relatively rare conversions.  I had reversed\r\n//\t\t\t\t\ttwo length arguments. \r\n//\r\n//    2003-NOV-24 - Thanks to a bunch of people for helping me clean up many\r\n//\t\t\t\t\tcompiler warnings (and yes, even a couple of actual compiler\r\n//\t\t\t\t\terrors).  These include Henk Demper for figuring out how\r\n//\t\t\t\t\tto make the Intellisense work on with CStdString on VC6,\r\n//\t\t\t\t\tsomething I was never able to do.  Greg Marr pointed out\r\n//\t\t\t\t\ta compiler warning about an unreferenced symbol and a\r\n//\t\t\t\t\tproblem with my version of Load in MFC builds.  Bill\r\n//\t\t\t\t\tCarducci took a lot of time with me to help me figure out\r\n//\t\t\t\t\twhy some implementations of the Standard C++ Library were\r\n//\t\t\t\t\treturning error codes for apparently successful conversions\r\n//\t\t\t\t\tbetween ASCII and UNICODE.  Finally thanks to Brian Groose\r\n//\t\t\t\t\tfor helping me fix compiler signed unsigned warnings in\r\n//\t\t\t\t\tseveral functions.\r\n//\r\n//    2003-JUL-10 - Thanks to Charles Godwin for making me realize my 'FmtArg'\r\n//\t\t\t\t\tfixes had inadvertently broken the DLL-export code (which is\r\n//                  normally commented out.  I had to move it up higher.  Also\r\n//\t\t\t\t\tthis helped me catch a bug in ssicoll that would prevent\r\n//                  compilation, otherwise.\r\n//\r\n//    2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste\r\n//                  bug in one of the overloads of FmtArg.\r\n//\r\n//    2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes\r\n//                  to help CStdString build on SGI and for pointing out an\r\n//                  error in placement of my preprocessor macros for ssfmtmsg.\r\n//\r\n//    2002-NOV-26 - Thanks to Bagira for pointing out that my implementation of\r\n//                  SpanExcluding was not properly handling the case in which\r\n//                  the string did NOT contain any of the given characters\r\n//\r\n//    2002-OCT-21 - Many thanks to Paul DeMarco who was invaluable in helping me\r\n//                  get this code working with Borland's free compiler as well\r\n//                  as the Dev-C++ compiler (available free at SourceForge).\r\n//\r\n//    2002-SEP-13 - Thanks to Glen Maynard who helped me get rid of some loud\r\n//                  but harmless warnings that were showing up on g++.  Glen\r\n//                  also pointed out that some pre-declarations of FmtArg<>\r\n//                  specializations were unnecessary (and no good on G++)\r\n//\r\n//    2002-JUN-26 - Thanks to Arnt Witteveen for pointing out that I was using\r\n//                  static_cast<> in a place in which I should have been using\r\n//                  reinterpret_cast<> (the ctor for unsigned char strings).\r\n//                  That's what happens when I don't unit-test properly!\r\n//                  Arnt also noticed that CString was silently correcting the\r\n//                  'nCount' argument to Left() and Right() where CStdString was\r\n//                  not (and crashing if it was bad).  That is also now fixed!\r\n//\r\n//\t  2002-FEB-25 - Thanks to Tim Dowty for pointing out (and giving me the fix\r\n//\t\t\t\t\tfor) a conversion problem with non-ASCII MBCS characters.\r\n//\t\t\t\t\tCStdString is now used in my favorite commercial MP3 player!\r\n//\r\n//\t  2001-DEC-06 - Thanks to Wang Haifeng for spotting a problem in one of the\r\n//\t\t\t\t\tassignment operators (for _bstr_t) that would cause compiler\r\n//\t\t\t\t\terrors when refcounting protection was turned off.\r\n//\r\n//\t  2001-NOV-27 - Remove calls to operator!= which involve reverse_iterators\r\n//\t\t\t\t\tdue to a conflict with the rel_ops operator!=.  Thanks to\r\n//\t\t\t\t\tJohn James for pointing this out.\r\n//\r\n//    2001-OCT-29 - Added a minor range checking fix for the Mid function to\r\n//\t\t\t\t\tmake it as forgiving as CString's version is.  Thanks to\r\n//\t\t\t\t\tIgor Kholodov for noticing this.  \r\n//\t\t\t\t  - Added a specialization of std::swap for CStdString.  Thanks\r\n//\t\t\t\t\tto Mike Crusader for suggesting this!  It's commented out\r\n//\t\t\t\t\tbecause you're not supposed to inject your own code into the\r\n//\t\t\t\t\t'std' namespace.  But if you don't care about that, it's\r\n//\t\t\t\t\tthere if you want it\r\n//\t\t\t\t  - Thanks to Jason Mills for catching a case where CString was\r\n//\t\t\t\t\tmore forgiving in the Delete() function than I was.\r\n//\r\n//\t  2001-JUN-06 - I was violating the Standard name lookup rules stated\r\n//\t\t\t\t\tin [14.6.2(3)].  None of the compilers I've tried so\r\n//\t\t\t\t\tfar apparently caught this but HP-UX aCC 3.30 did.  The\r\n//\t\t\t\t\tfix was to add 'this->' prefixes in many places.\r\n//\t\t\t\t\tThanks to Farrokh Nejadlotfi for this!\r\n//\r\n//\t  2001-APR-27 - StreamLoad was calculating the number of BYTES in one\r\n//\t\t\t\t\tcase, not characters.  Thanks to Pablo Presedo for this.\r\n//\r\n//    2001-FEB-23 - Replace() had a bug which caused infinite loops if the\r\n//\t\t\t\t\tsource string was empty.  Fixed thanks to Eric Nitzsche.\r\n//\r\n//    2001-FEB-23 - Scott Hathaway was a huge help in providing me with the\r\n//\t\t\t\t\tability to build CStdString on Sun Unix systems.  He\r\n//\t\t\t\t\tsent me detailed build reports about what works and what\r\n//\t\t\t\t\tdoes not.  If CStdString compiles on your Unix box, you\r\n//\t\t\t\t\tcan thank Scott for it.\r\n//\r\n//\t  2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do a\r\n//\t\t\t\t\trange check as CString's does.  Now fixed -- thanks!\r\n//\r\n//\t  2000-NOV-07 - Aaron pointed out that I was calling static member\r\n//\t\t\t\t\tfunctions of char_traits via a temporary.  This was not\r\n//\t\t\t\t\ttechnically wrong, but it was unnecessary and caused\r\n//\t\t\t\t\tproblems for poor old buggy VC5.  Thanks Aaron!\r\n//\r\n//\t  2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match\r\n//\t\t\t\t\twhat the CString::Find code really ends up doing.   I was\r\n//\t\t\t\t\ttrying to match the docs.  Now I match the CString code\r\n//\t\t\t\t  - Joe also caught me truncating strings for GetBuffer() calls\r\n//\t\t\t\t\twhen the supplied length was less than the current length.\r\n//\r\n//\t  2000-MAY-25 - Better support for STLPORT's Standard library distribution\r\n//\t\t\t\t  - Got rid of the NSP macro - it interfered with Koenig lookup\r\n//\t\t\t\t  - Thanks to Joe Woodbury for catching a TrimLeft() bug that\r\n//\t\t\t\t\tI introduced in January.  Empty strings were not getting\r\n//\t\t\t\t\ttrimmed\r\n//\r\n//\t  2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind\r\n//\t\t\t\t\tis supposed to be a const function.\r\n//\r\n//\t  2000-MAR-07 - Thanks to Ullrich Pollhne for catching a range bug in one\r\n//\t\t\t\t\tof the overloads of assign.\r\n//\r\n//    2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior!\r\n//\t\t\t\t\tThanks to Todd Heckel for helping out with this.\r\n//\r\n//\t  2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the\r\n//\t\t\t\t\tTrim() function more efficient.\r\n//\t\t\t\t  - Thanks to Jeff Kohn for prompting me to find and fix a typo\r\n//\t\t\t\t\tin one of the addition operators that takes _bstr_t.\r\n//\t\t\t\t  - Got rid of the .CPP file -  you only need StdString.h now!\r\n//\r\n//\t  1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem\r\n//\t\t\t\t\twith my implementation of CStdString::FormatV in which\r\n//\t\t\t\t\tresulting string might not be properly NULL terminated.\r\n//\r\n//\t  1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment\r\n//\t\t\t\t\tbug that MS has not fixed.  CStdString did nothing to fix\r\n//\t\t\t\t\tit either but it does now!  The bug was: create a string\r\n//\t\t\t\t\tlonger than 31 characters, get a pointer to it (via c_str())\r\n//\t\t\t\t\tand then assign that pointer to the original string object.\r\n//\t\t\t\t\tThe resulting string would be empty.  Not with CStdString!\r\n//\r\n//\t  1999-OCT-06 - BufferSet was erasing the string even when it was merely\r\n//\t\t\t\t\tsupposed to shrink it.  Fixed.  Thanks to Chris Conti.\r\n//\t\t\t\t  - Some of the Q172398 fixes were not checking for assignment-\r\n//\t\t\t\t\tto-self.  Fixed.  Thanks to Baptiste Lepilleur.\r\n//\r\n//\t  1999-AUG-20 - Improved Load() function to be more efficient by using \r\n//\t\t\t\t\tSizeOfResource().  Thanks to Rich Zuris for this.\r\n//\t\t\t\t  - Corrected resource ID constructor, again thanks to Rich.\r\n//\t\t\t\t  - Fixed a bug that occurred with UNICODE characters above\r\n//\t\t\t\t\tthe first 255 ANSI ones.  Thanks to Craig Watson. \r\n//\t\t\t\t  - Added missing overloads of TrimLeft() and TrimRight().\r\n//\t\t\t\t\tThanks to Karim Ratib for pointing them out\r\n//\r\n//\t  1999-JUL-21 - Made all calls to GetBuf() with no args check length first.\r\n//\r\n//\t  1999-JUL-10 - Improved MFC/ATL independence of conversion macros\r\n//\t\t\t\t  - Added SS_NO_REFCOUNT macro to allow you to disable any\r\n//\t\t\t\t\treference-counting your basic_string<> impl. may do.\r\n//\t\t\t\t  - Improved ReleaseBuffer() to be as forgiving as CString.\r\n//\t\t\t\t\tThanks for Fan Xia for helping me find this and to\r\n//\t\t\t\t\tMatthew Williams for pointing it out directly.\r\n//\r\n//\t  1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in\r\n//\t\t\t\t\tToLower/ToUpper.  They should call GetBuf() instead of\r\n//\t\t\t\t\tdata() in order to ensure the changed string buffer is not\r\n//\t\t\t\t\treference-counted (in those implementations that refcount).\r\n//\r\n//\t  1999-JUL-01 - Added a true CString facade.  Now you can use CStdString as\r\n//\t\t\t\t\ta drop-in replacement for CString.  If you find this useful,\r\n//\t\t\t\t\tyou can thank Chris Sells for finally convincing me to give\r\n//\t\t\t\t\tin and implement it.\r\n//\t\t\t\t  - Changed operators << and >> (for MFC CArchive) to serialize\r\n//\t\t\t\t\tEXACTLY as CString's do.  So now you can send a CString out\r\n//\t\t\t\t\tto a CArchive and later read it in as a CStdString.   I have\r\n//\t\t\t\t\tno idea why you would want to do this but you can. \r\n//\r\n//\t  1999-JUN-21 - Changed the CStdString class into the CStdStr template.\r\n//\t\t\t\t  - Fixed FormatV() to correctly decrement the loop counter.\r\n//\t\t\t\t\tThis was harmless bug but a bug nevertheless.  Thanks to\r\n//\t\t\t\t\tChris (of Melbsys) for pointing it out\r\n//\t\t\t\t  - Changed Format() to try a normal stack-based array before\r\n//\t\t\t\t\tusing to _alloca().\r\n//\t\t\t\t  - Updated the text conversion macros to properly use code\r\n//\t\t\t\t\tpages and to fit in better in MFC/ATL builds.  In other\r\n//\t\t\t\t\twords, I copied Microsoft's conversion stuff again. \r\n//\t\t\t\t  - Added equivalents of CString::GetBuffer, GetBufferSetLength\r\n//\t\t\t\t  - new sscpy() replacement of CStdString::CopyString()\r\n//\t\t\t\t  - a Trim() function that combines TrimRight() and TrimLeft().\r\n//\r\n//\t  1999-MAR-13 - Corrected the \"NotSpace\" functional object to use _istpace()\r\n//\t\t\t\t\tinstead of _isspace()   Thanks to Dave Plummer for this.\r\n//\r\n//\t  1999-FEB-26 - Removed errant line (left over from testing) that #defined\r\n//\t\t\t\t\t_MFC_VER.  Thanks to John C Sipos for noticing this.\r\n//\r\n//\t  1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that\r\n//\t\t\t\t\tcaused infinite recursion and stack overflow\r\n//\t\t\t\t  - Added member functions to simplify the process of\r\n//\t\t\t\t\tpersisting CStdStrings to/from DCOM IStream interfaces \r\n//\t\t\t\t  - Added functional objects (e.g. StdStringLessNoCase) that\r\n//\t\t\t\t\tallow CStdStrings to be used as keys STL map objects with\r\n//\t\t\t\t\tcase-insensitive comparison \r\n//\t\t\t\t  - Added array indexing operators (i.e. operator[]).  I\r\n//\t\t\t\t\toriginally assumed that these were unnecessary and would be\r\n//\t\t\t\t\tinherited from basic_string.  However, without them, Visual\r\n//\t\t\t\t\tC++ complains about ambiguous overloads when you try to use\r\n//\t\t\t\t\tthem.  Thanks to Julian Selman to pointing this out. \r\n//\r\n//\t  1998-FEB-?? - Added overloads of assign() function to completely account\r\n//\t\t\t\t\tfor Q172398 bug.  Thanks to \"Pete the Plumber\" for this\r\n//\r\n//\t  1998-FEB-?? - Initial submission\r\n//\r\n// COPYRIGHT:\r\n//\t\t2002 Joseph M. O'Leary.  This code is 100% free.  Use it anywhere you\r\n//      want.  Rewrite it, restructure it, whatever.  If you can write software\r\n//      that makes money off of it, good for you.  I kinda like capitalism. \r\n//      Please don't blame me if it causes your $30 billion dollar satellite\r\n//      explode in orbit.  If you redistribute it in any form, I'd appreciate it\r\n//      if you would leave this notice here.\r\n// =============================================================================\r\n\r\n// Avoid multiple inclusion the VC++ way,\r\n// Turn off browser references\r\n// Turn off unavoidable compiler warnings\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER > 1100)\r\n\t#pragma once\r\n\t#pragma component(browser, off, references, \"CStdString\")\r\n\t#pragma warning (disable : 4290) // C++ Exception Specification ignored\r\n\t#pragma warning (disable : 4127) // Conditional expression is constant\r\n\t#pragma warning (disable : 4097) // typedef name used as synonym for class name\r\n#endif\r\n\r\n// Borland warnings to turn off\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option push -w-inl\r\n//\t#pragma warn -inl   // Turn off inline function warnings\r\n#endif\r\n\r\n#ifndef STDSTRING_H\r\n#define STDSTRING_H\r\n\r\n// SS_IS_INTRESOURCE\r\n// -----------------\r\n//\t\tA copy of IS_INTRESOURCE from VC7.  Because old VC6 version of winuser.h\r\n//\t\tdoesn't have this.\r\n\r\n#define SS_IS_INTRESOURCE\r\n\r\n#if !defined (SS_ANSI) && defined(_MSC_VER)\r\n\t#undef SS_IS_INTRESOURCE\r\n\t#if defined(_WIN64)\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned __int64)(_r) >> 16) == 0)\r\n\t#else\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned long)(_r) >> 16) == 0)\r\n\t#endif\r\n#endif\r\n\r\n\r\n// MACRO: SS_UNSIGNED\r\n// ------------------\r\n//      This macro causes the addition of a constructor and assignment operator\r\n//      which take unsigned characters.  CString has such functions and in order\r\n//      to provide maximum CString-compatability, this code needs them as well.\r\n//      In practice you will likely never need these functions...\r\n\r\n//#define SS_UNSIGNED\r\n\r\n#ifdef SS_ALLOW_UNSIGNED_CHARS\r\n\t#define SS_UNSIGNED\r\n#endif\r\n\r\n// MACRO: SS_SAFE_FORMAT\r\n// ---------------------\r\n//      This macro provides limited compatability with a questionable CString\r\n//      \"feature\".  You can define it in order to avoid a common problem that\r\n//      people encounter when switching from CString to CStdString.\r\n//\r\n//      To illustrate the problem -- With CString, you can do this:\r\n//\r\n//          CString sName(\"Joe\");\r\n//          CString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // WORKS!\r\n//\r\n//      However if you were to try this with CStdString, your program would\r\n//      crash.\r\n//\r\n//          CStdString sName(\"Joe\");\r\n//          CStdString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // CRASHES!\r\n//\r\n//      You must explicitly call c_str() or cast the object to the proper type\r\n//\r\n//          sTmp.Format(\"My name is %s\", sName.c_str());            // WORKS!\r\n//          sTmp.Format(\"My name is %s\", static_cast<PCSTR>(sName));// WORKS!\r\n//          sTmp.Format(\"My name is %s\", (PCSTR)sName);// WORKS!\r\n//\r\n//      This is because it is illegal to pass anything but a POD type as a\r\n//      variadic argument to a variadic function (i.e. as one of the \"...\"\r\n//      arguments).  The type const char* is a POD type.  The type CStdString\r\n//      is not.  Of course, neither is the type CString, but CString lets you do\r\n//      it anyway due to the way they laid out the class in binary.  I have no\r\n//      control over this in CStdString since I derive from whatever\r\n//      implementation of basic_string is available.\r\n//\r\n//      However if you have legacy code (which does this) that you want to take\r\n//      out of the MFC world and you don't want to rewrite all your calls to\r\n//      Format(), then you can define this flag and it will no longer crash.\r\n//\r\n//      Note however that this ONLY works for Format(), not sprintf, fprintf, \r\n//      etc.  If you pass a CStdString object to one of those functions, your\r\n//      program will crash.  Not much I can do to get around this, short of\r\n//      writing substitutes for those functions as well.\r\n\r\n#define SS_SAFE_FORMAT  // use new template style Format() function\r\n\r\n\r\n// MACRO: SS_NO_IMPLICIT_CAST\r\n// --------------------------\r\n//      Some people don't like the implicit cast to const char* (or rather to\r\n//      const CT*) that CStdString (and MFC's CString) provide.  That was the\r\n//      whole reason I created this class in the first place, but hey, whatever\r\n//      bakes your cake.  Just #define this macro to get rid of the the implicit\r\n//      cast.\r\n\r\n//#define SS_NO_IMPLICIT_CAST // gets rid of operator const CT*()\r\n\r\n\r\n// MACRO: SS_NO_REFCOUNT\r\n// ---------------------\r\n//\t\tturns off reference counting at the assignment level.  Only needed\r\n//\t\tfor the version of basic_string<> that comes with Visual C++ versions\r\n//\t\t6.0 or earlier, and only then in some heavily multithreaded scenarios.\r\n//\t\tUncomment it if you feel you need it.\r\n\r\n//#define SS_NO_REFCOUNT\r\n\r\n// MACRO: SS_WIN32\r\n// ---------------\r\n//      When this flag is set, we are building code for the Win32 platform and\r\n//      may use Win32 specific functions (such as LoadString).  This gives us\r\n//      a couple of nice extras for the code.\r\n//\r\n//      Obviously, Microsoft's is not the only compiler available for Win32 out\r\n//      there.  So I can't just check to see if _MSC_VER is defined to detect\r\n//      if I'm building on Win32.  So for now, if you use MS Visual C++ or\r\n//      Borland's compiler, I turn this on.  Otherwise you may turn it on\r\n//      yourself, if you prefer\r\n#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WIN32)\r\n    #define SS_WIN32\r\n#endif\r\n\r\n// MACRO: SS_ANSI\r\n// --------------\r\n//      When this macro is defined, the code attempts only to use ANSI/ISO\r\n//      standard library functions to do it's work.  It will NOT attempt to use\r\n//      any Win32 of Visual C++ specific functions -- even if they are\r\n//      available.  You may define this flag yourself to prevent any Win32\r\n//      of VC++ specific functions from being called. \r\n\r\n// If we're not on Win32, we MUST use an ANSI build\r\n\r\n#ifndef SS_WIN32\r\n    #if !defined(SS_NO_ANSI)\r\n        #define SS_ANSI\r\n    #endif\r\n#endif\r\n\r\n// MACRO: SS_ALLOCA\r\n// ----------------\r\n//      Some implementations of the Standard C Library have a non-standard\r\n//      function known as alloca().  This functions allows one to allocate a\r\n//      variable amount of memory on the stack.  It is needed to implement\r\n//      the ASCII/MBCS conversion macros.\r\n//\r\n//      I wanted to find some way to determine automatically if alloca() is\r\n//\t\tavailable on this platform via compiler flags but that is asking for\r\n//\t\ttrouble.  The crude test presented here will likely need fixing on\r\n//\t\tother platforms.  Therefore I'll leave it up to you to fiddle with\r\n//\t\tthis test to determine if it exists.  Just make sure SS_ALLOCA is or\r\n//\t\tis not defined as appropriate and you control this feature.\r\n\r\n#if defined(_MSC_VER) && !defined(SS_ANSI)\r\n\t#define SS_ALLOCA\r\n#endif\r\n\r\n// MACRO: SS_MBCS\r\n// --------------\r\n//\t\tSetting this macro means you are using MBCS characters.  In MSVC\r\n//\t\tbuilds, this macro gets set automatically by detection of the\r\n//\t\tpreprocessor flag _MBCS.  For other platforms you may set it manually\r\n//\t\tif you wish.  The only effect it currently has is to cause the\r\n//\t\tallocation of more space for wchar_t --> char conversions.\r\n//\t\tNote that MBCS does not mean UNICODE.\r\n//\r\n//\t#define SS_MBCS\r\n//\r\n#ifdef _MBCS\r\n\t#define SS_MBCS\r\n#endif\r\n\r\n\r\n\r\n// Compiler Error regarding _UNICODE and UNICODE\r\n// -----------------------------------------------\r\n// Microsoft header files are screwy.  Sometimes they depend on a preprocessor \r\n// flag named \"_UNICODE\".  Other times they check \"UNICODE\" (note the lack of\r\n// leading underscore in the second version\".  In several places, they silently\r\n// \"synchronize\" these two flags this by defining one of the other was defined. \r\n// In older version of this header , I used to try to do the same thing. \r\n//\r\n// However experience has taught me that this is a bad idea.  You get weird\r\n// compiler errors that seem to indicate things like LPWSTR and LPTSTR not being\r\n// equivalent in UNICODE builds, stuff like that (when they MUST be in a proper\r\n// UNICODE  build).  You end up scratching your head and saying, \"But that HAS\r\n// to compile!\".\r\n//\r\n// So what should you do if you get this error?\r\n//\r\n// Make sure that both macros (_UNICODE and UNICODE) are defined before this\r\n// file is included.  You can do that by either\r\n//\r\n//\t\ta) defining both yourself before any files get included\r\n//\t\tb) including the proper MS headers in the proper order\r\n//\t\tc) including this file before any other file, uncommenting\r\n//\t\t   the #defines below, and commenting out the #errors\r\n//\r\n//\tPersonally I recommend solution a) but it's your call.\r\n\r\n#ifdef _MSC_VER\r\n\t#if defined (_UNICODE) && !defined (UNICODE)\r\n\t\t#error UNICODE defined  but not UNICODE\r\n\t//\t#define UNICODE  // no longer silently fix this\r\n\t#endif\r\n\t#if defined (UNICODE) && !defined (_UNICODE)\r\n\t\t#error Warning, UNICODE defined  but not _UNICODE\r\n\t//\t#define _UNICODE  // no longer silently fix this\r\n\t#endif\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// MIN and MAX.  The Standard C++ template versions go by so many names (at\r\n// at least in the MS implementation) that you never know what's available \r\n// -----------------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline const Type& SSMIN(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 < arg1 ? arg2 : arg1;\r\n}\r\ntemplate<class Type>\r\ninline const Type& SSMAX(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 > arg1 ? arg2 : arg1;\r\n}\r\n\r\n// If they have not #included W32Base.h (part of my W32 utility library) then\r\n// we need to define some stuff.  Otherwise, this is all defined there.\r\n\r\n#if !defined(W32BASE_H)\r\n\r\n\t// If they want us to use only standard C++ stuff (no Win32 stuff)\r\n\r\n\t#ifdef SS_ANSI\r\n\r\n\t\t// On Win32 we have TCHAR.H so just include it.  This is NOT violating\r\n        // the spirit of SS_ANSI as we are not calling any Win32 functions here.\r\n        \r\n\t\t#ifdef SS_WIN32\r\n\r\n\t\t\t#include <TCHAR.H>\r\n\t\t\t#include <WTYPES.H>\r\n\t\t\t#ifndef STRICT\r\n\t\t\t\t#define STRICT\r\n\t\t\t#endif\r\n\r\n        // ... but on non-Win32 platforms, we must #define the types we need.\r\n\r\n\t\t#else\r\n\r\n\t\t\ttypedef const char*\t\tPCSTR;\r\n\t\t\ttypedef char*\t\t\tPSTR;\r\n\t\t\ttypedef const wchar_t*\tPCWSTR;\r\n\t\t\ttypedef wchar_t*\t\tPWSTR;\r\n\t\t\t#ifdef UNICODE\r\n\t\t\t\ttypedef wchar_t\t\tTCHAR;\r\n\t\t\t#else\r\n\t\t\t\ttypedef char\t\tTCHAR;\r\n\t\t\t#endif\r\n\t\t\ttypedef wchar_t\t\t\tOLECHAR;\r\n\r\n\t\t#endif\t// #ifndef _WIN32\r\n\r\n\r\n\t\t// Make sure ASSERT and verify are defined using only ANSI stuff\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <assert.h>\r\n\t\t\t#define ASSERT(f) assert((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#else // ...else SS_ANSI is NOT defined\r\n\r\n\t\t#include <TCHAR.H>\r\n\t\t#include <WTYPES.H>\r\n\t\t#ifndef STRICT\r\n\t\t\t#define STRICT\r\n\t\t#endif\r\n\r\n\t\t// Make sure ASSERT and verify are defined\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <crtdbg.h>\r\n\t\t\t#define ASSERT(f) _ASSERTE((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#endif // #ifdef SS_ANSI\r\n\r\n\t#ifndef UNUSED\r\n\t\t#define UNUSED(x) x\r\n\t#endif\r\n\r\n#endif // #ifndef W32BASE_H\r\n\r\n// Standard headers needed\r\n\r\n#include <string>\t\t\t// basic_string\r\n#include <algorithm>\t\t// for_each, etc.\r\n#include <functional>\t\t// for StdStringLessNoCase, et al\r\n#include <locale>\t\t// for various facets\r\n\r\n// If this is a recent enough version of VC include comdef.h, so we can write\r\n// member functions to deal with COM types & compiler support classes e.g.\r\n// _bstr_t\r\n\r\n#if defined (_MSC_VER) && (_MSC_VER >= 1100)\r\n\t#include <comdef.h>\r\n\t#define SS_INC_COMDEF\t\t// signal that we #included MS comdef.h file\r\n\t#define STDSTRING_INC_COMDEF\r\n\t#define SS_NOTHROW __declspec(nothrow)\r\n#else\r\n\t#define SS_NOTHROW\r\n#endif\r\n\r\n#ifndef TRACE\r\n\t#define TRACE_DEFINED_HERE\r\n\t#define TRACE\r\n#endif\r\n\r\n// Microsoft defines PCSTR, PCWSTR, etc, but no PCTSTR.  I hate to use the\r\n// versions with the \"L\" in front of them because that's a leftover from Win 16\r\n// days, even though it evaluates to the same thing.  Therefore, Define a PCSTR\r\n// as an LPCTSTR.\r\n\r\n#if !defined(PCTSTR) && !defined(PCTSTR_DEFINED)\r\n\ttypedef const TCHAR*\t\t\tPCTSTR;\r\n\t#define PCTSTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCOLESTR) && !defined(PCOLESTR_DEFINED)\r\n\ttypedef const OLECHAR*\t\t\tPCOLESTR;\r\n\t#define PCOLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(POLESTR) && !defined(POLESTR_DEFINED)\r\n\ttypedef OLECHAR*\t\t\t\tPOLESTR;\r\n\t#define POLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCUSTR) && !defined(PCUSTR_DEFINED)\r\n\ttypedef const unsigned char*\tPCUSTR;\r\n\ttypedef unsigned char*\t\t\tPUSTR;\r\n\t#define PCUSTR_DEFINED\r\n#endif\r\n\r\n\r\n// SGI compiler 7.3 doesnt know these  types - oh and btw, remember to use\r\n// -LANG:std in the CXX Flags\r\n#if defined(__sgi)\r\n    typedef unsigned long           DWORD;\r\n    typedef void *                  LPCVOID;\r\n#endif\r\n\r\n\r\n// SS_USE_FACET macro and why we need it:\r\n//\r\n// Since I'm a good little Standard C++ programmer, I use locales.  Thus, I\r\n// need to make use of the use_facet<> template function here.   Unfortunately,\r\n// this need is complicated by the fact the MS' implementation of the Standard\r\n// C++ Library has a non-standard version of use_facet that takes more\r\n// arguments than the standard dictates.  Since I'm trying to write CStdString\r\n// to work with any version of the Standard library, this presents a problem.\r\n//\r\n// The upshot of this is that I can't do 'use_facet' directly.  The MS' docs\r\n// tell me that I have to use a macro, _USE() instead.  Since _USE obviously\r\n// won't be available in other implementations, this means that I have to write\r\n// my OWN macro -- SS_USE_FACET -- that evaluates either to _USE or to the\r\n// standard, use_facet.\r\n//\r\n// If you are having trouble with the SS_USE_FACET macro, in your implementation\r\n// of the Standard C++ Library, you can define your own version of SS_USE_FACET.\r\n#ifndef schMSG\r\n\t#define schSTR(x)\t   #x\r\n\t#define schSTR2(x)\tschSTR(x)\r\n\t#define schMSG(desc) message(__FILE__ \"(\" schSTR2(__LINE__) \"):\" #desc)\r\n#endif\r\n\r\n#ifndef SS_USE_FACET\r\n\t// STLPort #defines a macro (__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) for\r\n\t// all MSVC builds, erroneously in my opinion.  It causes problems for\r\n\t// my SS_ANSI builds.  In my code, I always comment out that line.  You'll\r\n\t// find it in   \\stlport\\config\\stl_msvc.h\r\n\t#if defined(__SGI_STL_PORT) && (__SGI_STL_PORT >= 0x400 )\r\n\t\t#if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) && defined(_MSC_VER)\r\n\t\t\t#ifdef SS_ANSI\r\n\t\t\t\t#pragma schMSG(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS defined!!)\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#elif defined(_MSC_VER )\r\n\t#define SS_USE_FACET(loc, fac) std::_USE(loc, fac)\r\n\r\n\t// ...and\r\n\t#elif defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE)\r\n        #define SS_USE_FACET(loc, fac) std::use_facet(loc, (fac*)0)\r\n\t#else\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#endif\r\n#endif\r\n\r\n// =============================================================================\r\n// UNICODE/MBCS conversion macros.  Made to work just like the MFC/ATL ones.\r\n// =============================================================================\r\n\r\n#include <wchar.h>      // Added to Std Library with Amendment #1.\r\n\r\n// First define the conversion helper functions.  We define these regardless of\r\n// any preprocessor macro settings since their names won't collide. \r\n\r\n// Not sure if we need all these headers.   I believe ANSI says we do.\r\n\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include <wctype.h>\r\n#include <ctype.h>\r\n#include <stdlib.h>\r\n#ifndef va_start\r\n\t#include <varargs.h>\r\n#endif\r\n\r\n// StdCodeCvt - made to look like Win32 functions WideCharToMultiByte\r\n//\t\t\t\tand MultiByteToWideChar but uses locales in SS_ANSI\r\n//\t\t\t\tbuilds.  There are a number of overloads.\r\n//              First argument is the destination buffer.\r\n//              Second argument is the source buffer\r\n//#if defined (SS_ANSI) || !defined (SS_WIN32)\r\n\r\n// 'SSCodeCvt' - shorthand name for the codecvt facet we use\r\n\r\ntypedef std::codecvt<wchar_t, char, mbstate_t> SSCodeCvt;\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n\r\n    ASSERT(0 != pSrcA);\r\n    ASSERT(0 != pDstW);\r\n\r\n\tpDstW[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPCSTR pNextSrcA\t\t\t= pSrcA;\r\n\t\tPWSTR pNextDstW\t\t\t= pDstW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.in(st,\r\n\t\t\t\t\t\t\t\t\tpSrcA, pSrcA + nSrc, pNextSrcA,\r\n\t\t\t\t\t\t\t\t\tpDstW, pDstW + nDst, pNextDstW);\r\n\r\n\t\tASSERT(SSCodeCvt::ok == res);\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(pNextDstW >= pDstW);\r\n\t\tASSERT(pNextSrcA >= pSrcA);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstW - pDstW > nDst )\r\n\t\t\t*(pDstW + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstW = '\\0';\r\n\t}\r\n    return pDstW;\r\n}\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCUSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, loc);\r\n}\r\n\r\ninline PSTR StdCodeCvt(PSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    ASSERT(0 != pDstA);\r\n    ASSERT(0 != pSrcW);\r\n\r\n\tpDstA[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPSTR pNextDstA\t\t\t= pDstA;\r\n\t\tPCWSTR pNextSrcW\t\t= pSrcW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.out(st,\r\n\t\t\t\t\t\t\t\t\tpSrcW, pSrcW + nSrc, pNextSrcW,\r\n\t\t\t\t\t\t\t\t\tpDstA, pDstA + nDst, pNextDstA);\r\n\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(SSCodeCvt::ok == res);\t// strict, comment out for sanity\r\n\t\tASSERT(pNextDstA >= pDstA);\r\n\t\tASSERT(pNextSrcW >= pSrcW);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstA - pDstA > nDst )\r\n\t\t\t*(pDstA + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstA = '\\0';\r\n\t}\r\n    return pDstA;\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, loc);\r\n}\r\n/*\r\n#else   // ...or are we doing things assuming win32 and Visual C++?\r\n\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pSrcA);\r\n\t\tASSERT(0 != pDstW);\r\n\t\tpW[0] = '\\0';\r\n\t\tMultiByteToWideChar(acp, 0, pSrcA, nSrc, pDstW, nDst);\r\n\t\treturn pW;\r\n\t}\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, nDst, PCUSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, acp);\r\n\t}\r\n\r\n\tinline PSTR StdCodeCvt(PSTR pDstA, nDst PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pDstA);\r\n\t\tASSERT(0 != pSrcW);\r\n\t\tpA[0] = '\\0';\r\n\t\tWideCharToMultiByte(acp, 0, pSrcW, nSrc, pDstA, nDst, 0, 0);\r\n\t\treturn pA;\r\n\t}\r\n\tinline PUSTR StdCodeCvt(PUSTR pDstA, nDst, PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, acp);\r\n\t}\r\n\r\n#endif\r\n*/\r\n\r\n// Unicode/MBCS conversion macros are only available on implementations of\r\n// the \"C\" library that have the non-standard _alloca function.  As far as I\r\n// know that's only Microsoft's though I've heard that the function exists\r\n// elsewhere.  \r\n    \r\n#if defined(SS_ALLOCA) && !defined SS_NO_CONVERSION\r\n\r\n    #include <malloc.h>\t// needed for _alloca\r\n\r\n    // Define our conversion macros to look exactly like Microsoft's to\r\n    // facilitate using this stuff both with and without MFC/ATL\r\n\r\n    #ifdef _CONVERSION_USES_THREAD_LOCALE\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=GetACP(); \\\r\n\t\t\t    _acp; PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=GetACP();\\\r\n\t\t\t     _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t\t\t_pa, _cvt, _acp)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = sslen(_pw), \\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt, _acp)))\r\n\t#else\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=CP_ACP; _acp;\\\r\n\t\t\t     PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=CP_ACP; \\\r\n\t\t\t    _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pa, _cvt)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pw)),\\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt)))\r\n    #endif\r\n\r\n    #define SSA2CW(pa) ((PCWSTR)SSA2W((pa)))\r\n    #define SSW2CA(pw) ((PCSTR)SSW2A((pw)))\r\n\r\n    #ifdef UNICODE\r\n\t    #define SST2A\tSSW2A\r\n\t    #define SSA2T\tSSA2W\r\n\t    #define SST2CA\tSSW2CA\r\n\t    #define SSA2CT\tSSA2CW\r\n\t\t// (Did you get a compiler error here about not being able to convert\r\n\t\t// PTSTR into PWSTR?  Then your _UNICODE and UNICODE flags are messed \r\n\t\t// up.  Best bet: #define BOTH macros before including any MS headers.)\r\n\t    inline PWSTR\tSST2W(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSW2T(PWSTR p)\t\t\t{ return p; }\r\n\t    inline PCWSTR\tSST2CW(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSW2CT(PCWSTR p)\t\t{ return p; }\r\n    #else\r\n\t    #define SST2W\tSSA2W\r\n\t    #define SSW2T\tSSW2A\r\n\t    #define SST2CW\tSSA2CW\r\n\t    #define SSW2CT\tSSW2CA\r\n\t    inline PSTR\t\tSST2A(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSA2T(PSTR p)\t\t\t{ return p; }\r\n\t    inline PCSTR\tSST2CA(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSA2CT(PCSTR p)\t\t\t{ return p; }\r\n    #endif // #ifdef UNICODE\r\n\r\n    #if defined(UNICODE)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #elif defined(OLE2ANSI)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #else\r\n\t    //CharNextW doesn't work on Win95 so we use this\r\n\t    #define SST2COLE(pa)\tSSA2CW((pa))\r\n\t    #define SST2OLE(pa)\t\tSSA2W((pa))\r\n\t    #define SSOLE2CT(po)\tSSW2CA((po))\r\n\t    #define SSOLE2T(po)\t\tSSW2A((po))\r\n    #endif\r\n\r\n    #ifdef OLE2ANSI\r\n\t    #define SSW2OLE\t\tSSW2A\r\n\t    #define SSOLE2W\t\tSSA2W\r\n\t    #define SSW2COLE\tSSW2CA\r\n\t    #define SSOLE2CW\tSSA2CW\r\n\t    inline POLESTR\t\tSSA2OLE(PSTR p)\t\t{ return p; }\r\n\t    inline PSTR\t\t\tSSOLE2A(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSA2COLE(PCSTR p)\t{ return p; }\r\n\t    inline PCSTR\t\tSSOLE2CA(PCOLESTR p){ return p; }\r\n    #else\r\n\t    #define SSA2OLE\t\tSSA2W\r\n\t    #define SSOLE2A\t\tSSW2A\r\n\t    #define SSA2COLE\tSSA2CW\r\n\t    #define SSOLE2CA\tSSW2CA\r\n\t    inline POLESTR\t\tSSW2OLE(PWSTR p)\t{ return p; }\r\n\t    inline PWSTR\t\tSSOLE2W(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSW2COLE(PCWSTR p)\t{ return p; }\r\n\t    inline PCWSTR\t\tSSOLE2CW(PCOLESTR p){ return p; }\r\n    #endif\r\n\r\n    // Above we've defined macros that look like MS' but all have\r\n    // an 'SS' prefix.  Now we need the real macros.  We'll either\r\n    // get them from the macros above or from MFC/ATL. \r\n\r\n\t#if defined (USES_CONVERSION)\r\n\r\n\t\t#define _NO_STDCONVERSION\t// just to be consistent\r\n\r\n\t#else\r\n\r\n\t\t#ifdef _MFC_VER\r\n\r\n\t\t\t#include <afxconv.h>\r\n\t\t\t#define _NO_STDCONVERSION // just to be consistent\r\n\r\n\t\t#else\r\n\r\n\t\t\t#define USES_CONVERSION SSCVT\r\n\t\t\t#define A2CW\t\t\tSSA2CW\r\n\t\t\t#define W2CA\t\t\tSSW2CA\r\n\t\t\t#define T2A\t\t\t\tSST2A\r\n\t\t\t#define A2T\t\t\t\tSSA2T\r\n\t\t\t#define T2W\t\t\t\tSST2W\r\n\t\t\t#define W2T\t\t\t\tSSW2T\r\n\t\t\t#define T2CA\t\t\tSST2CA\r\n\t\t\t#define A2CT\t\t\tSSA2CT\r\n\t\t\t#define T2CW\t\t\tSST2CW\r\n\t\t\t#define W2CT\t\t\tSSW2CT\r\n\t\t\t#define ocslen\t\t\tsslen\r\n\t\t\t#define ocscpy\t\t\tsscpy\r\n\t\t\t#define T2COLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2CT\t\t\tSSOLE2CT\r\n\t\t\t#define T2OLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2T\t\t\tSSOLE2CT\r\n\t\t\t#define A2OLE\t\t\tSSA2OLE\r\n\t\t\t#define OLE2A\t\t\tSSOLE2A\r\n\t\t\t#define W2OLE\t\t\tSSW2OLE\r\n\t\t\t#define OLE2W\t\t\tSSOLE2W\r\n\t\t\t#define A2COLE\t\t\tSSA2COLE\r\n\t\t\t#define OLE2CA\t\t\tSSOLE2CA\r\n\t\t\t#define W2COLE\t\t\tSSW2COLE\r\n\t\t\t#define OLE2CW\t\t\tSSOLE2CW\r\n\t\r\n\t\t#endif // #ifdef _MFC_VER\r\n\t#endif // #ifndef USES_CONVERSION\r\n#endif // #ifndef SS_NO_CONVERSION\r\n\r\n// Define ostring - generic name for std::basic_string<OLECHAR>\r\n\r\n#if !defined(ostring) && !defined(OSTRING_DEFINED)\r\n\ttypedef std::basic_string<OLECHAR> ostring;\r\n\t#define OSTRING_DEFINED\r\n#endif\r\n\r\n// StdCodeCvt when there's no conversion to be done\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<char>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<char>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCUSTR pSrc, int nSrc)\r\n{\r\n\treturn StdCodeCvt(pDst, nDst, (PCSTR)pSrc, nSrc);\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\treturn (PUSTR)StdCodeCvt((PSTR)pDst, nDst, pSrc, nSrc);\r\n}\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDst, int nDst, PCWSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<wchar_t>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<wchar_t>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\n\r\n\r\n// Define tstring -- generic name for std::basic_string<TCHAR>\r\n\r\n#if !defined(tstring) && !defined(TSTRING_DEFINED)\r\n\ttypedef std::basic_string<TCHAR> tstring;\r\n\t#define TSTRING_DEFINED\r\n#endif\r\n\r\n// a very shorthand way of applying the fix for KB problem Q172398\r\n// (basic_string assignment bug)\r\n\r\n#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t#define Q172398(x) (x).erase()\r\n#else\r\n\t#define Q172398(x)\r\n#endif\r\n\r\n// =============================================================================\r\n// INLINE FUNCTIONS ON WHICH CSTDSTRING RELIES\r\n//\r\n// Usually for generic text mapping, we rely on preprocessor macro definitions\r\n// to map to string functions.  However the CStdStr<> template cannot use\r\n// macro-based generic text mappings because its character types do not get\r\n// resolved until template processing which comes AFTER macro processing.  In\r\n// other words, the preprocessor macro UNICODE is of little help to us in the\r\n// CStdStr template\r\n//\r\n// Therefore, to keep the CStdStr declaration simple, we have these inline\r\n// functions.  The template calls them often.  Since they are inline (and NOT\r\n// exported when this is built as a DLL), they will probably be resolved away\r\n// to nothing. \r\n//\r\n// Without these functions, the CStdStr<> template would probably have to broken\r\n// out into two, almost identical classes.  Either that or it would be a huge,\r\n// convoluted mess, with tons of \"if\" statements all over the place checking the\r\n// size of template parameter CT.\r\n// \r\n// In several cases, you will see two versions of each function.  One version is\r\n// the more portable, standard way of doing things, while the other is the\r\n// non-standard, but often significantly faster Visual C++ way.\r\n// =============================================================================\r\n\r\n// If they defined SS_NO_REFCOUNT, then we must convert all assignments\r\n\r\n#ifdef SS_NO_REFCOUNT\r\n\t#define SSREF(x) (x).c_str()\r\n#else\r\n\t#define SSREF(x) (x)\r\n#endif\r\n\r\n// -----------------------------------------------------------------------------\r\n// sslen: strlen/wcslen wrappers\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT> inline int sslen(const CT* pT)\r\n{\r\n\treturn 0 == pT ? 0 : (int)std::basic_string<CT>::traits_type::length(pT);\r\n//\treturn 0 == pT ? 0 : std::char_traits<CT>::length(pT);\r\n}\r\ninline SS_NOTHROW int sslen(const std::string& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\ninline SS_NOTHROW int sslen(const std::wstring& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// sstolower/sstoupper -- convert characters to upper/lower case\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline CT sstolower(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::tolower<CT>(t, loc);\r\n}\r\ntemplate<typename CT>\r\ninline CT sstoupper(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::toupper<CT>(t, loc);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssasn: assignment functions -- assign \"sSrc\" to \"sDst\"\r\n// -----------------------------------------------------------------------------\r\ntypedef std::string::size_type\t\tSS_SIZETYPE; // just for shorthand, really\r\ntypedef std::string::pointer\t\tSS_PTRTYPE;  \r\ntypedef std::wstring::size_type\t\tSW_SIZETYPE;\r\ntypedef std::wstring::pointer\t\tSW_PTRTYPE;  \r\n\r\ninline void\tssasn(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCSTR pA)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pA )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pA actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pA >= sDst.c_str() && pA <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst =sDst.substr(static_cast<SS_SIZETYPE>(pA-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pA);\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sSrc.size());\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), static_cast<int>(sSrc.size()));\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tszCvt;\r\n\t\tsDst.resize(sSrc.size());\r\n#endif\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nSrc\t= sslen(pW);\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tpW, nSrc);\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n}\r\ninline void ssasn(std::string& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(\"\");\r\n}\t\r\ninline void\tssasn(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pW )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pW actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pW >= sDst.c_str() && pW <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst = sDst.substr(static_cast<SW_SIZETYPE>(pW-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pW);\r\n\t}\r\n}\r\n#undef StrSizeType\r\ninline void\tssasn(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\tsDst.resize(nSrc+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), nSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t= sslen(pA);\r\n\r\n\tif ( 0 == nSrc )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= nSrc;\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst, pA,\r\n\t\t\tnSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void ssasn(std::wstring& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(L\"\");\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssadd: string object concatenation -- add second argument to first\r\n// -----------------------------------------------------------------------------\r\ninline void\tssadd(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+nAdd+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, sSrc.c_str(), nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nAdd);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + nAdd + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, pW, nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, PCSTR pA)\r\n{\r\n\tif ( pA )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pA >= sDst.c_str() && pA <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pA) )\r\n\t\t\t\tsDst.append(std::string(pA));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pA);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pA); \r\n\t\t}\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( !sSrc.empty() )\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst), \r\n\t\t\tnSrc, sSrc.c_str(), nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t\t= sslen(pA);\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnSrc, pA, nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\tif ( pW )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pW >= sDst.c_str() && pW <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pW) )\r\n\t\t\t\tsDst.append(std::wstring(pW));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscmp: comparison (case sensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int sscmp(const CT* pA1, const CT* pA2)\r\n{\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = *(pA1++);\r\n\t    l = *(pA2++);\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssicmp: comparison (case INsensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int ssicmp(const CT* pA1, const CT* pA2)\r\n{\r\n\t// Using the \"C\" locale = \"not affected by locale\"\r\n\r\n\tstd::locale loc = std::locale::classic();\r\n    const std::ctype<CT>& ct = SS_USE_FACET(loc, std::ctype<CT>);\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = ct.tolower(*(pA1++));\r\n\t    l = ct.tolower(*(pA2++));\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssupr/sslwr: Uppercase/Lowercase conversion functions\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\ninline void sslwr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).tolower(pT, pT+nLen);\r\n}\r\ntemplate<typename CT>\r\ninline void ssupr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).toupper(pT, pT+nLen);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n//  vsprintf/vswprintf or _vsnprintf/_vsnwprintf equivalents.  In standard\r\n//  builds we can't use _vsnprintf/_vsnwsprintf because they're MS extensions.\r\n// -----------------------------------------------------------------------------\r\n#if defined(SS_ANSI) || !defined(_MSC_VER)\r\n\r\n    // Borland's headers put some ANSI \"C\" functions in the 'std' namespace. \r\n    // Promote them to the global namespace so we can use them here.\r\n\r\n    #if defined(__BORLANDC__)\r\n        using std::vsprintf;\r\n        using std::vswprintf;\r\n    #endif\r\n\r\n\tinline int ssvsprintf(PSTR pA, size_t /*nCount*/, PCSTR pFmtA, va_list vl)\r\n\t{\r\n\t\treturn vsprintf(pA, pFmtA, vl);\r\n\t}\r\n\tinline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\t// JMO: Some distributions of the \"C\" have a version of vswprintf that\r\n        // takes 3 arguments (e.g. Microsoft, Borland, GNU).  Others have a \r\n        // version which takes 4 arguments (an extra \"count\" argument in the\r\n        // second position.  The best stab I can take at this so far is that if\r\n        // you are NOT running with MS, Borland, or GNU, then I'll assume you\r\n        // have the version that takes 4 arguments.\r\n        //\r\n        // I'm sure that these checks don't catch every platform correctly so if\r\n        // you get compiler errors on one of the lines immediately below, it's\r\n        // probably because your implemntation takes a different number of\r\n        // arguments.  You can comment out the offending line (and use the\r\n        // alternate version) or you can figure out what compiler flag to check\r\n        // and add that preprocessor check in.  Regardless, if you get an error\r\n        // on these lines, I'd sure like to hear from you about it.\r\n        //\r\n        // Thanks to Ronny Schulz for the SGI-specific checks here.\r\n\r\n//\t#if !defined(__MWERKS__) && !defined(__SUNPRO_CC_COMPAT) && !defined(__SUNPRO_CC)\r\n    #if    !defined(_MSC_VER) \\\r\n        && !defined (__BORLANDC__) \\\r\n        && !defined(__GNUC__) \\\r\n        && !defined(__sgi)\r\n\r\n        return vswprintf(pW, nCount, pFmtW, vl);\r\n\r\n    // suddenly with the current SGI 7.3 compiler there is no such function as\r\n    // vswprintf and the substitute needs explicit casts to compile\r\n\r\n    #elif defined(__sgi)\r\n\r\n        nCount;\r\n        return vsprintf( (char *)pW, (char *)pFmtW, vl);\r\n\r\n    #else\r\n\r\n        nCount;\r\n        return vswprintf(pW, pFmtW, vl);\r\n\r\n    #endif\r\n\r\n\t}\r\n#else\r\n\tinline int\tssnprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl)\r\n\t{ \r\n\t\treturn _vsnprintf(pA, nCount, pFmtA, vl);\r\n\t}\r\n\tinline int\tssnprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\treturn _vsnwprintf(pW, nCount, pFmtW, vl);\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssload: Type safe, overloaded ::LoadString wrappers\r\n// There is no equivalent of these in non-Win32-specific builds.  However, I'm\r\n// thinking that with the message facet, there might eventually be one\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline int ssload(HMODULE hInst, UINT uId, PSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringA(hInst, uId, pBuf, nMax);\r\n\t}\r\n\tinline int ssload(HMODULE hInst, UINT uId, PWSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringW(hInst, uId, pBuf, nMax);\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscoll/ssicoll: Collation wrappers\r\n//\t\tNote -- with MSVC I have reversed the arguments order here because the\r\n//\t\tfunctions appear to return the opposite of what they should\r\n// -----------------------------------------------------------------------------\r\ntemplate <typename CT>\r\ninline int sscoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::collate<CT>& coll =\r\n\t\tSS_USE_FACET(std::locale(), std::collate<CT>);\r\n\r\n\treturn coll.compare(sz2, sz2+nLen2, sz1, sz1+nLen1);\r\n}\r\ntemplate <typename CT>\r\ninline int ssicoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::locale loc;\r\n\tconst std::collate<CT>& coll = SS_USE_FACET(loc, std::collate<CT>);\r\n\r\n\t// Some implementations seem to have trouble using the collate<>\r\n\t// facet typedefs so we'll just default to basic_string and hope\r\n\t// that's what the collate facet uses (which it generally should)\r\n\r\n//\tstd::collate<CT>::string_type s1(sz1);\r\n//\tstd::collate<CT>::string_type s2(sz2);\r\n\tconst std::basic_string<CT> sEmpty;\r\n    std::basic_string<CT> s1(sz1 ? sz1 : sEmpty.c_str());\r\n    std::basic_string<CT> s2(sz2 ? sz2 : sEmpty.c_str());\r\n\r\n\tsslwr(const_cast<CT*>(s1.c_str()), nLen1, loc);\r\n\tsslwr(const_cast<CT*>(s2.c_str()), nLen2, loc);\r\n\treturn coll.compare(s2.c_str(), s2.c_str()+nLen2,\r\n\t\t\t\t\t\ts1.c_str(), s1.c_str()+nLen1);\r\n}\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssfmtmsg: FormatMessage equivalents.  Needed because I added a CString facade\r\n// Again -- no equivalent of these on non-Win32 builds but their might one day\r\n// be one if the message facet gets implemented\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{ \r\n\t\treturn FormatMessageA(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PWSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{\r\n\t\treturn FormatMessageW(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n#else\r\n#endif\r\n \r\n\r\n\r\n// FUNCTION: sscpy.  Copies up to 'nMax' characters from pSrc to pDst.\r\n// -----------------------------------------------------------------------------\r\n// FUNCTION:  sscpy\r\n//\t\tinline int sscpy(PSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PUSTR pDst,  PCSTR pSrc, int nMax=-1)\r\n//\t\tinline int sscpy(PSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\r\n// DESCRIPTION:\r\n//\t\tThis function is very much (but not exactly) like strcpy.  These\r\n//\t\toverloads simplify copying one C-style string into another by allowing\r\n//\t\tthe caller to specify two different types of strings if necessary.\r\n//\r\n//\t\tThe strings must NOT overlap\r\n//\r\n//\t\t\"Character\" is expressed in terms of the destination string, not\r\n//\t\tthe source.  If no 'nMax' argument is supplied, then the number of\r\n//\t\tcharacters copied will be sslen(pSrc).  A NULL terminator will\r\n//\t\talso be added so pDst must actually be big enough to hold nMax+1\r\n//\t\tcharacters.  The return value is the number of characters copied,\r\n//\t\tnot including the NULL terminator.\r\n//\r\n// PARAMETERS: \r\n//\t\tpSrc - the string to be copied FROM.  May be a char based string, an\r\n//\t\t\t   MBCS string (in Win32 builds) or a wide string (wchar_t).\r\n//\t\tpSrc - the string to be copied TO.  Also may be either MBCS or wide\r\n//\t\tnMax - the maximum number of characters to be copied into szDest.  Note\r\n//\t\t\t   that this is expressed in whatever a \"character\" means to pDst.\r\n//\t\t\t   If pDst is a wchar_t type string than this will be the maximum\r\n//\t\t\t   number of wchar_ts that my be copied.  The pDst string must be\r\n//\t\t\t   large enough to hold least nMaxChars+1 characters.\r\n//\t\t\t   If the caller supplies no argument for nMax this is a signal to\r\n//\t\t\t   the routine to copy all the characters in pSrc, regardless of\r\n//\t\t\t   how long it is.\r\n//\r\n// RETURN VALUE: none\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpycvt(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\t\r\n\tint nSrc = sslen(pSrc);\r\n\r\n\tconst CT1* szCvt = StdCodeCvt(pDst, nMax, pSrc, nSrc);\r\n\r\n\t// If we're copying the same size characters, then all the \"code convert\"\r\n\t// just did was basically memcpy so the #of characters copied is the same\r\n\t// as the number requested.  I should probably specialize this function\r\n\t// template to achieve this purpose as it is silly to do a runtime check\r\n\t// of a fact known at compile time.  I'll get around to it.\r\n\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ninline int sscpycvt(PSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<char>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst =  '\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCWSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<wchar_t>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst = L'\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\r\n\tconst PWSTR szCvt = StdCodeCvt(pDst, nMax, pSrc, nMax);\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax, int nLen)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, nLen));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, sslen(pSrc)));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, sslen(pSrc));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), SSMIN(nMax, (int)sSrc.length()));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), (int)sSrc.length());\r\n}\r\n\r\n#ifdef SS_INC_COMDEF\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs, int nMax)\r\n\t{\r\n\t\treturn sscpycvt(pDst, static_cast<PCOLESTR>(bs),\r\n            SSMIN(nMax, static_cast<int>(bs.length())));\r\n\t}\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs)\r\n\t{\r\n\t\treturn sscpy(pDst, bs, static_cast<int>(bs.length()));\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// Functional objects for changing case.  They also let you pass locales\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\nstruct SSToUpper : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstoupper<CT>(t, loc);\r\n    }\r\n};\r\ntemplate<typename CT>\r\nstruct SSToLower : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstolower<CT>(t, loc);\r\n    }\r\n};\r\n\r\n// This struct is used for TrimRight() and TrimLeft() function implementations.\r\n//template<typename CT>\r\n//struct NotSpace : public std::unary_function<CT, bool>\r\n//{\r\n//\tconst std::locale& loc;\r\n//\tinline NotSpace(const std::locale& locArg) : loc(locArg) {}\r\n//\tinline bool operator() (CT t) { return !std::isspace(t, loc); }\r\n//};\r\ntemplate<typename CT>\r\nstruct NotSpace : public std::unary_function<CT, bool>\r\n{\r\n\r\n\t// DINKUMWARE BUG:\r\n\t// Note -- using std::isspace in a COM DLL gives us access violations\r\n\t// because it causes the dynamic addition of a function to be called\r\n\t// when the library shuts down.  Unfortunately the list is maintained\r\n\t// in DLL memory but the function is in static memory.  So the COM DLL\r\n\t// goes away along with the function that was supposed to be called,\r\n\t// and then later when the DLL CRT shuts down it unloads the list and\r\n\t// tries to call the long-gone function.\r\n\t// This is DinkumWare's implementation problem.  If you encounter this\r\n\t// problem, you may replace the calls here with good old isspace() and\r\n\t// iswspace() from the CRT unless they specify SS_ANSI\r\n    \r\n\tconst std::locale loc;\r\n\tNotSpace(const std::locale& locArg=std::locale()) : loc(locArg) {}\r\n\tbool operator() (CT t) const { return !std::isspace(t, loc); }\r\n};\r\n\r\n\r\n\r\n\r\n//\t\t\tNow we can define the template (finally!)\r\n// =============================================================================\r\n// TEMPLATE: CStdStr\r\n//\t\ttemplate<typename CT> class CStdStr : public std::basic_string<CT>\r\n//\r\n// REMARKS:\r\n//\t\tThis template derives from basic_string<CT> and adds some MFC CString-\r\n//\t\tlike functionality\r\n//\r\n//\t\tBasically, this is my attempt to make Standard C++ library strings as\r\n//\t\teasy to use as the MFC CString class.\r\n//\r\n//\t\tNote that although this is a template, it makes the assumption that the\r\n//\t\ttemplate argument (CT, the character type) is either char or wchar_t.  \r\n// =============================================================================\r\n\r\n//#define CStdStr _SS\t// avoid compiler warning 4786\r\n\r\n//    template<typename ARG> ARG& FmtArg(ARG& arg)  { return arg; }\r\n//    PCSTR  FmtArg(const std::string& arg)  { return arg.c_str(); }\r\n//    PCWSTR FmtArg(const std::wstring& arg) { return arg.c_str(); }\r\n\r\ntemplate<typename ARG>\r\nstruct FmtArg\r\n{\r\n    explicit FmtArg(const ARG& arg) : a_(arg) {}\r\n    const ARG& operator()() const { return a_; }\r\n    const ARG& a_;\r\nprivate:\r\n    FmtArg& operator=(const FmtArg&) { return *this; }\r\n};\r\n\r\ntemplate<typename CT>\r\nclass CStdStr : public std::basic_string<CT>\r\n{\r\n\t// Typedefs for shorter names.  Using these names also appears to help\r\n\t// us avoid some ambiguities that otherwise arise on some platforms\r\n\r\n\t#define MYBASE std::basic_string<CT>\t\t\t\t // my base class\r\n\t//typedef typename std::basic_string<CT>\t\tMYBASE;\t // my base class\r\n\ttypedef CStdStr<CT>\t\t\t\t\t\t\tMYTYPE;\t // myself\r\n\ttypedef typename MYBASE::const_pointer\t\tPCMYSTR; // PCSTR or PCWSTR \r\n\ttypedef typename MYBASE::pointer\t\t\tPMYSTR;\t // PSTR or PWSTR\r\n\ttypedef typename MYBASE::iterator\t\t\tMYITER;  // my iterator type\r\n\ttypedef typename MYBASE::const_iterator\t\tMYCITER; // you get the idea...\r\n\ttypedef typename MYBASE::reverse_iterator\tMYRITER;\r\n\ttypedef typename MYBASE::size_type\t\t\tMYSIZE;   \r\n\ttypedef typename MYBASE::value_type\t\t\tMYVAL; \r\n\ttypedef typename MYBASE::allocator_type\t\tMYALLOC;\r\n\t\r\npublic:\r\n\t// shorthand conversion from PCTSTR to string resource ID\r\n\t#define SSRES(pctstr)  LOWORD(reinterpret_cast<unsigned long>(pctstr))\t\r\n\r\n\tbool TryLoad(const void* pT)\r\n\t{\r\n\t\tbool bLoaded = false;\r\n\r\n#if defined(SS_WIN32) && !defined(SS_ANSI)\r\n\t\tif ( ( pT != NULL ) && SS_IS_INTRESOURCE(pT) )\r\n\t\t{\r\n\t\t\tUINT nId = LOWORD(reinterpret_cast<unsigned long>(pT));\r\n\t\t\tif ( !LoadString(nId) )\r\n\t\t\t{\r\n\t\t\t\tTRACE(_T(\"Can't load string %u\\n\"), SSRES(pT));\r\n\t\t\t}\r\n\t\t\tbLoaded = true;\r\n\t\t}\r\n#endif\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n\r\n\t// CStdStr inline constructors\r\n\tCStdStr()\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const MYTYPE& str) : MYBASE(SSREF(str))\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(PCMYSTR pT, MYSIZE n) : MYBASE(pT, n)\r\n\t{\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tCStdStr(PCUSTR pU)\r\n\t{\r\n\t\t*this = reinterpret_cast<PCSTR>(pU);\r\n\t}\r\n#endif\r\n\r\n\tCStdStr(PCSTR pA)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pA;\r\n\t#else\r\n\t\tif ( !TryLoad(pA) )\r\n\t\t\t*this = pA;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(PCWSTR pW)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pW;\r\n\t#else\r\n\t\tif ( !TryLoad(pW) )\r\n\t\t\t*this = pW;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(MYCITER first, MYCITER last)\r\n\t\t: MYBASE(first, last)\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(MYSIZE nSize, MYVAL ch, const MYALLOC& al=MYALLOC())\r\n\t\t: MYBASE(nSize, ch, al)\r\n\t{\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tCStdStr(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t\tthis->append(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t}\r\n\t#endif\r\n\r\n\t// CStdStr inline assignment operators -- the ssasn function now takes care\r\n\t// of fixing  the MSVC assignment bug (see knowledge base article Q172398).\r\n\tMYTYPE& operator=(const MYTYPE& str)\r\n\t{ \r\n\t\tssasn(*this, str); \r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCSTR pA)\r\n\t{\r\n\t\tssasn(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCWSTR pW)\r\n\t{\r\n\t\tssasn(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tMYTYPE& operator=(PCUSTR pU)\r\n\t{\r\n\t\tssasn(*this, reinterpret_cast<PCSTR>(pU));\r\n\t\treturn *this;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE& operator=(CT t)\r\n\t{\r\n\t\tQ172398(*this);\r\n\t\tthis->assign(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tMYTYPE& operator=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t{\r\n\t\t\t\tthis->assign(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// Overloads  also needed to fix the MSVC assignment bug (KB: Q172398)\r\n\t//  *** Thanks to Pete The Plumber for catching this one ***\r\n\t// They also are compiled if you have explicitly turned off refcounting\r\n\t#if ( defined(_MSC_VER) && ( _MSC_VER < 1200 ) ) || defined(SS_NO_REFCOUNT) \r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tsscpy(GetBuffer(str.size()+1), SSREF(str));\r\n\t\t\tthis->ReleaseBuffer(str.size());\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value.  Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\t\t\tMYTYPE strTemp(str.c_str()+nStart, nChars);\r\n\t\t\tQ172398(*this);\r\n\t\t\tthis->assign(strTemp);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str)\r\n\t\t{\r\n\t\t\tssasn(*this, str);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value. Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\r\n\t\t\t// Watch out for assignment to self\r\n\r\n\t\t\tif ( this == &str )\r\n\t\t\t{\r\n\t\t\t\tMYTYPE strTemp(str.c_str() + nStart, nChars);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(strTemp);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tQ172398(*this);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(str.c_str()+nStart, nChars);\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pC, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// Q172398 only fix -- erase before assigning, but not if we're\r\n\t\t\t// assigning from our own buffer\r\n\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t\t\tif ( !this->empty() &&\r\n\t\t\t\t( pC < this->data() || pC > this->data() + this->capacity() ) )\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t}\r\n\t#endif\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(pC, nChars);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYSIZE nChars, MYVAL val)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(nChars, val);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pT)\r\n\t\t{\r\n\t\t\treturn this->assign(pT, MYBASE::traits_type::length(pT));\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYCITER iterFirst, MYCITER iterLast)\r\n\t\t{\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) \r\n\t\t\t// Q172398 fix.  don't call erase() if we're assigning from ourself\r\n\t\t\tif ( iterFirst < this->begin() ||\r\n                 iterFirst > this->begin() + this->size() )\r\n            {\r\n\t\t\t\tthis->erase()\r\n            }\r\n\t#endif\r\n\t\t\tthis->replace(this->begin(), this->end(), iterFirst, iterLast);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr inline concatenation.\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& operator+=(const MYTYPE& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::string& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this; \r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::wstring& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCSTR pA)\r\n\t{\r\n\t\tssadd(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCWSTR pW)\r\n\t{\r\n\t\tssadd(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(CT t)\r\n\t{\r\n\t\tthis->append(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\t#ifdef SS_INC_COMDEF\t// if we have _bstr_t, define a += for it too.\r\n\t\tMYTYPE& operator+=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\treturn this->operator+=(static_cast<PCMYSTR>(bstr));\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Case changing functions\r\n\t// -------------------------------------------------------------------------\r\n\r\n    MYTYPE& ToUpper(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToUpper<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tssupr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& ToLower(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToLower<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tsslwr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\t\treturn *this;\r\n\t}\r\n\r\n\r\n\tMYTYPE& Normalize()\r\n\t{\r\n\t\treturn Trim().ToLower();\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr -- Direct access to character buffer.  In the MS' implementation,\r\n\t// the at() function that we use here also calls _Freeze() providing us some\r\n\t// protection from multithreading problems associated with ref-counting.\r\n    // In VC 7 and later, of course, the ref-counting stuff is gone.\r\n\t// -------------------------------------------------------------------------\r\n\r\n\tCT* GetBuf(int nMinLen=-1)\r\n\t{\r\n\t\tif ( static_cast<int>(size()) < nMinLen )\r\n\t\t\tthis->resize(static_cast<MYSIZE>(nMinLen));\r\n\r\n\t\treturn this->empty() ? const_cast<CT*>(this->data()) : &(this->at(0));\r\n\t}\r\n\r\n\tCT* SetBuf(int nLen)\r\n\t{\r\n\t\tnLen = ( nLen > 0 ? nLen : 0 );\r\n\t\tif ( this->capacity() < 1 && nLen == 0 )\r\n\t\t\tthis->resize(1);\r\n\r\n\t\tthis->resize(static_cast<MYSIZE>(nLen));\r\n\t\treturn const_cast<CT*>(this->data());\r\n\t}\r\n\tvoid RelBuf(int nNewLen=-1)\r\n\t{\r\n\t\tthis->resize(static_cast<MYSIZE>(nNewLen > -1 ? nNewLen :\r\n                                                        sslen(this->c_str())));\r\n\t}\r\n\r\n\tvoid BufferRel()\t\t { RelBuf(); }\t\t\t// backwards compatability\r\n\tCT*  Buffer()\t\t\t { return GetBuf(); }\t// backwards compatability\r\n\tCT*  BufferSet(int nLen) { return SetBuf(nLen);}// backwards compatability\r\n\r\n\tbool Equals(const CT* pT, bool bUseCase=false) const\r\n\t{\r\n\t\treturn  0 == (bUseCase ? this->compare(pT) : ssicmp(this->c_str(), pT));\r\n\t} \r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Load\r\n\t// REMARKS:\r\n\t//\t\tLoads string from resource specified by nID\r\n\t//\r\n\t// PARAMETERS:\r\n\t//\t\tnID - resource Identifier.  Purely a Win32 thing in this case\r\n\t//\r\n\t// RETURN VALUE:\r\n\t//\t\ttrue if successful, false otherwise\r\n\t// -------------------------------------------------------------------------\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tbool Load(UINT nId, HMODULE hModule=NULL)\r\n\t{\r\n\t\tbool bLoaded\t\t= false;\t// set to true of we succeed.\r\n\r\n\t#ifdef _MFC_VER\t\t// When in Rome (or MFC land)...\r\n\r\n\t\t// If they gave a resource handle, use it.  Note - this is archaic\r\n\t\t// and not really what I would recommend.  But then again, in MFC\r\n\t\t// land, you ought to be using CString for resources anyway since\r\n\t\t// it walks the resource chain for you.\r\n\r\n\t\tHMODULE hModuleOld = NULL;\r\n\r\n\t\tif ( NULL != hModule )\r\n\t\t{\r\n\t\t\thModuleOld = AfxGetResourceHandle();\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\t\t}\r\n\r\n\t\t// ...load the string\r\n\r\n\t\tCString strRes;\r\n\t\tbLoaded\t\t\t\t= FALSE != strRes.LoadString(nId);\r\n\r\n\t\t// ...and if we set the resource handle, restore it.\r\n\r\n\t\tif ( NULL != hModuleOld )\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\r\n\t\tif ( bLoaded )\r\n\t\t\t*this\t\t\t= strRes;\r\n\r\n\t#else // otherwise make our own hackneyed version of CString's Load\r\n\t\t\r\n\t\t// Get the resource name and module handle\r\n\r\n\t\tif ( NULL == hModule )\r\n\t\t\thModule\t\t\t= GetResourceHandle();\r\n\r\n\t\tPCTSTR szName\t\t= MAKEINTRESOURCE((nId>>4)+1); // lifted \r\n\t\tDWORD dwSize\t\t= 0;\r\n\r\n\t\t// No sense continuing if we can't find the resource\r\n\r\n\t\tHRSRC hrsrc\t\t\t= ::FindResource(hModule, szName, RT_STRING);\r\n\r\n\t\tif ( NULL == hrsrc )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cannot find resource %d: 0x%X\"), nId, ::GetLastError());\r\n\t\t}\r\n\t\telse if ( 0 == (dwSize = ::SizeofResource(hModule, hrsrc) / sizeof(CT)))\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cant get size of resource %d 0x%X\\n\"),nId,GetLastError());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tbLoaded\t\t\t= 0 != ssload(hModule, nId, GetBuf(dwSize), dwSize);\r\n\t\t\tReleaseBuffer();\r\n\t\t}\r\n\r\n\t#endif  // #ifdef _MFC_VER\r\n\r\n\t\tif ( !bLoaded )\r\n\t\t\tTRACE(_T(\"String not loaded 0x%X\\n\"), ::GetLastError());\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n#endif  // #ifdef SS_ANSI\r\n\t\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Format\r\n\t//\t\tvoid _cdecl Formst(CStdStringA& PCSTR szFormat, ...)\r\n\t//\t\tvoid _cdecl Format(PCSTR szFormat);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function does sprintf/wsprintf style formatting on CStdStringA\r\n\t//\t\tobjects.  It looks a lot like MFC's CString::Format.  Some people\r\n\t//\t\tmight even call this identical.  Fortunately, these people are now\r\n\t//\t\tdead... heh heh.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tnId - ID of string resource holding the format string\r\n\t//\t\tszFormat - a PCSTR holding the format specifiers\r\n\t//\t\targList - a va_list holding the arguments for the format specifiers.\r\n\t//\r\n\t// RETURN VALUE:  None.\r\n\t// -------------------------------------------------------------------------\r\n\t// formatting (using wsprintf style formatting)\r\n\r\n    // If they want a Format() function that safely handles string objects\r\n    // without casting\r\n \r\n#ifdef SS_SAFE_FORMAT       \r\n    \r\n    // Question:  Joe, you wacky coder you, why do you have so many overloads\r\n    //      of the Format() function\r\n    // Answer:  One reason only - CString compatability.  In short, by making\r\n    //      the Format() function a template this way, I can do strong typing\r\n    //      and allow people to pass CStdString arguments as fillers for\r\n    //      \"%s\" format specifiers without crashing their program!  The downside\r\n    //      is that I need to overload on the number of arguments.   If you are\r\n    //      passing more arguments than I have listed below in any of my\r\n    //      overloads, just add another one.\r\n    //\r\n    //      Yes, yes, this is really ugly.  In essence what I am doing here is\r\n    //      protecting people from a bad (and incorrect) programming practice\r\n    //      that they should not be doing anyway.  I am protecting them from\r\n    //      themselves.  Why am I doing this?  Well, if you had any idea the\r\n    //      number of times I've been emailed by people about this\r\n    //      \"incompatability\" in my code, you wouldn't ask.\r\n\r\n\tvoid Fmt(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\r\n    void Format(UINT nId)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) ) \r\n            this->swap(strFmt);\r\n    }\r\n    template<class A1>\r\n    void Format(UINT nId, const A1& v)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n            Fmt(strFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(UINT nId, const A1& v1, const A2& v2)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n        }\r\n    }\r\n    \r\n#endif // #ifndef SS_ANSI\r\n\r\n    // ...now the other overload of Format: the one that takes a string literal\r\n\r\n    void Format(const CT* szFmt)\r\n    {\r\n        *this = szFmt;\r\n    }\r\n    template<class A1>\r\n    void Format(const CT* szFmt, A1 v)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n    }\r\n\r\n#else  // #ifdef SS_SAFE_FORMAT\r\n\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tvoid Format(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tFormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t}\r\n    \r\n#endif  // #ifdef SS_ANSI\r\n\r\n\tvoid Format(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#endif // #ifdef SS_SAFE_FORMAT\r\n\r\n\tvoid AppendFormat(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tAppendFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\t#define MAX_FMT_TRIES\t\t5\t // #of times we try \r\n\t#define FMT_BLOCK_SIZE\t\t2048 // # of bytes to increment per try\r\n\t#define BUFSIZE_1ST\t256\r\n\t#define BUFSIZE_2ND 512\r\n\t#define STD_BUF_SIZE\t\t1024\r\n\r\n\t// an efficient way to add formatted characters to the string.  You may only\r\n\t// add up to STD_BUF_SIZE characters at a time, though\r\n\tvoid AppendFormatV(const CT* szFmt, va_list argList)\r\n\t{\r\n\t\tCT szBuf[STD_BUF_SIZE];\r\n\t#ifdef SS_ANSI\r\n\t\tint nLen = ssvsprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#else\r\n\t\tint nLen = ssnprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#endif\r\n\t\tif ( 0 < nLen )\r\n\t\t\tthis->append(szBuf, nLen);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  FormatV\r\n\t//\t\tvoid FormatV(PCSTR szFormat, va_list, argList);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function formats the string with sprintf style format-specs. \r\n\t//\t\tIt makes a general guess at required buffer size and then tries\r\n\t//\t\tsuccessively larger buffers until it finds one big enough or a\r\n\t//\t\tthreshold (MAX_FMT_TRIES) is exceeded.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tszFormat - a PCSTR holding the format of the output\r\n\t//\t\targList - a Microsoft specific va_list for variable argument lists\r\n\t//\r\n\t// RETURN VALUE: \r\n\t// -------------------------------------------------------------------------\r\n\r\n\tvoid FormatV(const CT* szFormat, va_list argList)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\r\n\t\tint nLen\t= sslen(szFormat) + STD_BUF_SIZE;\r\n\t\tssvsprintf(GetBuffer(nLen), nLen-1, szFormat, argList);\r\n\t\tReleaseBuffer();\r\n\r\n\t#else\r\n\r\n\t\tCT* pBuf\t\t\t= NULL;\r\n\t\tint nChars\t\t\t= 1;\r\n\t\tint nUsed\t\t\t= 0;\r\n\t\tsize_type nActual\t= 0;\r\n\t\tint nTry\t\t\t= 0;\r\n\r\n\t\tdo\t\r\n\t\t{\r\n\t\t\t// Grow more than linearly (e.g. 512, 1536, 3072, etc)\r\n\r\n\t\t\tnChars\t\t\t+= ((nTry+1) * FMT_BLOCK_SIZE);\r\n\t\t\tpBuf\t\t\t= reinterpret_cast<CT*>(_alloca(sizeof(CT)*nChars));\r\n\t\t\tnUsed\t\t\t= ssnprintf(pBuf, nChars-1, szFormat, argList);\r\n\r\n\t\t\t// Ensure proper NULL termination.\r\n\r\n\t\t\tnActual\t\t\t= nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1);\r\n\t\t\tpBuf[nActual+1]= '\\0';\r\n\r\n\r\n\t\t} while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES );\r\n\r\n\t\t// assign whatever we managed to format\r\n\r\n\t\tthis->assign(pBuf, nActual);\r\n\r\n\t#endif\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CString Facade Functions:\r\n\t//\r\n\t// The following methods are intended to allow you to use this class as a\r\n\t// near drop-in replacement for CString.\r\n\t// -------------------------------------------------------------------------\r\n\t#ifdef SS_WIN32\r\n\t\tBSTR AllocSysString() const\r\n\t\t{\r\n\t\t\tostring os;\r\n\t\t\tssasn(os, *this);\r\n\t\t\treturn ::SysAllocString(os.c_str());\r\n\t\t}\r\n\t#endif\r\n\r\n\tint Collate(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn sscoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint CollateNoCase(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn ssicoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint Compare(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn this->compare(szThat);\t\r\n\t}\r\n\r\n\tint CompareNoCase(PCMYSTR szThat)\tconst\r\n\t{\r\n\t\treturn ssicmp(this->c_str(), szThat);\r\n\t}\r\n\r\n\tint Delete(int nIdx, int nCount=1)\r\n\t{\r\n        if ( nIdx < 0 )\r\n\t\t\tnIdx = 0;\r\n\r\n\t\tif ( nIdx < this->GetLength() )\r\n\t\t\tthis->erase(static_cast<MYSIZE>(nIdx), static_cast<MYSIZE>(nCount));\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tvoid Empty()\r\n\t{\r\n\t\tthis->erase();\r\n\t}\r\n\r\n\tint Find(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx  ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find(szSub);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(CT ch, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find(szSub, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint FindOneOf(PCMYSTR szCharSet) const\r\n\t{\r\n\t\tMYSIZE nIdx = this->find_first_of(szCharSet);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tvoid FormatMessage(PCMYSTR szFormat, ...) throw(std::exception)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFormat);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   szFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\t szTemp == 0 )\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\tvoid FormatMessage(UINT nFormatId, ...) throw(std::exception)\r\n\t{\r\n\t\tMYTYPE sFormat;\r\n\t\tVERIFY(sFormat.LoadString(nFormatId));\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nFormatId);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   sFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\tszTemp == 0)\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n#endif\r\n\r\n\t// GetAllocLength -- an MSVC7 function but it costs us nothing to add it.\r\n\r\n\tint GetAllocLength()\r\n\t{\r\n\t\treturn static_cast<int>(this->capacity());\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// GetXXXX -- Direct access to character buffer\r\n\t// -------------------------------------------------------------------------\r\n\tCT GetAt(int nIdx) const\r\n\t{\r\n\t\treturn this->at(static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT* GetBuffer(int nMinLen=-1)\r\n\t{\r\n\t\treturn GetBuf(nMinLen);\r\n\t}\r\n\r\n\tCT* GetBufferSetLength(int nLen)\r\n\t{\r\n\t\treturn BufferSet(nLen);\r\n\t}\r\n\r\n\t// GetLength() -- MFC docs say this is the # of BYTES but\r\n\t// in truth it is the number of CHARACTERs (chars or wchar_ts)\r\n\tint GetLength() const\r\n\t{\r\n\t\treturn static_cast<int>(this->length());\r\n\t}\r\n\t\r\n\tint Insert(int nIdx, CT ch)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) > this->size()-1 )\r\n\t\t\tthis->append(1, ch);\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), 1, ch);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\tint Insert(int nIdx, PCMYSTR sz)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) >= this->size() )\r\n\t\t\tthis->append(sz, static_cast<MYSIZE>(sslen(sz)));\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), sz);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tbool IsEmpty() const\r\n\t{\r\n\t\treturn this->empty();\r\n\t}\r\n\r\n\tMYTYPE Left(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(0, static_cast<MYSIZE>(nCount)); \r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tbool LoadString(UINT nId)\r\n\t{\r\n\t\treturn this->Load(nId);\r\n\t}\r\n#endif\r\n\r\n\tvoid MakeLower()\r\n\t{\r\n\t\tToLower();\r\n\t}\r\n\r\n\tvoid MakeReverse()\r\n\t{\r\n\t\tstd::reverse(this->begin(), this->end());\r\n\t}\r\n\r\n\tvoid MakeUpper()\r\n\t{ \r\n\t\tToUpper();\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst) const\r\n\t{\r\n\t\treturn Mid(nFirst, this->GetLength()-nFirst);\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst, int nCount) const\r\n\t{\r\n\t\t// CString does range checking here.  Since we're trying to emulate it,\r\n\t\t// we must check too.\r\n\r\n\t\tif ( nFirst < 0 )\r\n\t\t\tnFirst = 0;\r\n\t\tif ( nCount < 0 )\r\n\t\t\tnCount = 0;\r\n\r\n\t\tint nSize = static_cast<int>(this->size());\r\n\r\n\t\tif ( nFirst + nCount > nSize )\r\n\t\t\tnCount = nSize - nFirst;\r\n\r\n\t\tif ( nFirst > nSize )\r\n\t\t\treturn MYTYPE();\r\n\r\n\t\tASSERT(nFirst >= 0);\r\n\t\tASSERT(nFirst + nCount <= nSize);\r\n\r\n\t\treturn this->substr(static_cast<MYSIZE>(nFirst),\r\n\t\t\t\t\t\t\tstatic_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid ReleaseBuffer(int nNewLen=-1)\r\n\t{\r\n\t\tRelBuf(nNewLen);\r\n\t}\r\n\r\n\tint Remove(CT ch)\r\n\t{\r\n\t\tMYSIZE nIdx\t\t= 0;\r\n\t\tint nRemoved\t= 0;\r\n\t\twhile ( (nIdx=this->find_first_of(ch)) != MYBASE::npos )\r\n\t\t{\r\n\t\t\tthis->erase(nIdx, 1);\r\n\t\t\tnRemoved++;\r\n\t\t}\r\n\t\treturn nRemoved;\r\n\t}\r\n\r\n\tint Replace(CT chOld, CT chNew)\r\n\t{\r\n\t\tint nReplaced\t= 0;\r\n\r\n\t\tfor ( MYITER iter=this->begin(); iter != this->end(); iter++ )\r\n\t\t{\r\n\t\t\tif ( *iter == chOld )\r\n\t\t\t{\r\n\t\t\t\t*iter = chNew;\r\n\t\t\t\tnReplaced++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint Replace(PCMYSTR szOld, PCMYSTR szNew)\r\n\t{\r\n\t\tint nReplaced\t\t= 0;\r\n\t\tMYSIZE nIdx\t\t\t= 0;\r\n\t\tMYSIZE nOldLen\t\t= sslen(szOld);\r\n\r\n\t\tif ( 0 != nOldLen )\r\n\t\t{\r\n\t\t\tstatic const CT ch\t= CT(0);\r\n\t\t\tMYSIZE nNewLen\t\t= sslen(szNew);\r\n\t\t\tPCMYSTR szRealNew\t= szNew == 0 ? &ch : szNew;\r\n\r\n\t\t\twhile ( (nIdx=this->find(szOld, nIdx)) != MYBASE::npos )\r\n\t\t\t{\r\n\t\t\t\tthis->replace(this->begin()+nIdx, this->begin()+nIdx+nOldLen,\r\n\t\t\t\t\tszRealNew);\r\n\r\n\t\t\t\tnReplaced++;\r\n\t\t\t\tnIdx += nNewLen;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint ReverseFind(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\t// ReverseFind overload that's not in CString but might be useful\r\n\tint ReverseFind(PCMYSTR szFind, MYSIZE pos=MYBASE::npos) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->rfind(0 == szFind ? MYTYPE() : szFind, pos);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tMYTYPE Right(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(this->size()-static_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid SetAt(int nIndex, CT ch)\r\n\t{\r\n\t\tASSERT(this->size() > static_cast<MYSIZE>(nIndex));\r\n\t\tthis->at(static_cast<MYSIZE>(nIndex))\t\t= ch;\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tBSTR SetSysString(BSTR* pbstr) const\r\n\t{\r\n\t\tostring os;\r\n\t\tssasn(os, *this);\r\n\t\tif ( !::SysReAllocStringLen(pbstr, os.c_str(), os.length()) )\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\r\n\t\tASSERT(*pbstr != 0);\r\n\t\treturn *pbstr;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE SpanExcluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n\tMYTYPE SpanIncluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_not_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n#if defined SS_WIN32 && !defined(UNICODE) && !defined(SS_ANSI)\r\n\r\n\t// CString's OemToAnsi and AnsiToOem functions are available only in\r\n\t// Unicode builds.  However since we're a template we also need a\r\n\t// runtime check of CT and a reinterpret_cast to account for the fact\r\n\t// that CStdStringW gets instantiated even in non-Unicode builds.\r\n\r\n\tvoid AnsiToOem()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::CharToOem(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid OemToAnsi()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::OemToChar(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\t\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Trim and its variants\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& Trim()\r\n\t{\r\n\t\treturn TrimLeft().TrimRight();\r\n\t}\r\n\r\n\tMYTYPE& TrimLeft()\r\n\t{\r\n\t\tthis->erase(this->begin(),\r\n\t\t\tstd::find_if(this->begin(), this->end(), NotSpace<CT>()));\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(CT tTrim)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(tTrim));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(szTrimChars));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& TrimRight()\r\n\t{\r\n\t\t// NOTE:  When comparing reverse_iterators here (MYRITER), I avoid using\r\n\t\t// operator!=.  This is because namespace rel_ops also has a template\r\n\t\t// operator!= which conflicts with the global operator!= already defined\r\n\t\t// for reverse_iterator in the header <utility>.\r\n\t\t// Thanks to John James for alerting me to this.\r\n\r\n\t\tMYRITER it = std::find_if(this->rbegin(), this->rend(), NotSpace<CT>());\r\n\t\tif ( !(this->rend() == it) )\r\n\t\t\tthis->erase(this->rend() - it);\r\n\r\n\t\tthis->erase(!(it == this->rend()) ? this->find_last_of(*it) + 1 : 0);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(CT tTrim)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(tTrim);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(szTrimChars);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid\t\t\tFreeExtra()\r\n\t{\r\n\t\tMYTYPE mt;\r\n\t\tthis->swap(mt);\r\n\t\tif ( !mt.empty() )\r\n\t\t\tthis->assign(mt.c_str(), mt.size());\r\n\t}\r\n\r\n\t// I have intentionally not implemented the following CString\r\n\t// functions.   You cannot make them work without taking advantage\r\n\t// of implementation specific behavior.  However if you absolutely\r\n\t// MUST have them, uncomment out these lines for \"sort-of-like\"\r\n\t// their behavior.  You're on your own.\r\n\r\n//\tCT*\t\t\t\tLockBuffer()\t{ return GetBuf(); }// won't really lock\r\n//\tvoid\t\t\tUnlockBuffer(); { }\t// why have UnlockBuffer w/o LockBuffer?\r\n\r\n\t// Array-indexing operators.  Required because we defined an implicit cast\r\n\t// to operator const CT* (Thanks to Julian Selman for pointing this out)\r\n\r\n\tCT& operator[](int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT& operator[](unsigned int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](unsigned int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n#ifndef SS_NO_IMPLICIT_CAST\r\n\toperator const CT*() const\r\n\t{\r\n\t\treturn this->c_str();\r\n\t}\r\n#endif\r\n\r\n\t// IStream related functions.  Useful in IPersistStream implementations\r\n\r\n#ifdef SS_INC_COMDEF\r\n\r\n\t// struct SSSHDR - useful for non Std C++ persistence schemes.\r\n\ttypedef struct SSSHDR\r\n\t{\r\n\t\tBYTE\tbyCtrl;\r\n\t\tULONG\tnChars;\r\n\t} SSSHDR;\t// as in \"Standard String Stream Header\"\r\n\r\n\t#define SSSO_UNICODE\t0x01\t// the string is a wide string\r\n\t#define SSSO_COMPRESS\t0x02\t// the string is compressed\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSize\r\n\t// REMARKS:\r\n\t//\t\tReturns how many bytes it will take to StreamSave() this CStdString\r\n\t//\t\tobject to an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tULONG StreamSize() const\r\n\t{\r\n\t\t// Control header plus string\r\n\t\tASSERT(this->size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\treturn (this->size() * sizeof(CT)) + sizeof(SSSHDR);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSave\r\n\t// REMARKS:\r\n\t//\t\tSaves this CStdString object to a COM IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamSave(IStream* pStream) const\r\n\t{\r\n\t\tASSERT(size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\tHRESULT hr\t\t= E_FAIL;\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\thdr.byCtrl\t\t= sizeof(CT) == 2 ? SSSO_UNICODE : 0;\r\n\t\thdr.nChars\t\t= this->size();\r\n\r\n\r\n\t\tif ( FAILED(hr=pStream->Write(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write control header, ERR=0x%X\\n\"),hr);\r\n\t\t}\r\n\t\telse if ( empty() )\r\n\t\t{\r\n\t\t\t;\t\t// nothing to write\r\n\t\t}\r\n\t\telse if ( FAILED(hr=pStream->Write(this->c_str(),\r\n\t\t\tthis->size()*sizeof(CT), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write string to stream 0x%X\\n\"), hr);\r\n\t\t}\r\n\r\n\t\treturn hr;\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamLoad\r\n\t// REMARKS:\r\n\t//\t\tThis method loads the object from an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamLoad(IStream* pStream)\r\n\t{\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\tHRESULT hr\t\t\t= E_FAIL;\r\n\r\n\t\tif ( FAILED(hr=pStream->Read(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamLoad: Cant read control header, ERR=0x%X\\n\"), hr);\r\n\t\t}\r\n\t\telse if ( hdr.nChars > 0 )\r\n\t\t{\r\n\t\t\tULONG nRead\t\t= 0;\r\n\t\t\tPMYSTR pMyBuf\t= BufferSet(hdr.nChars);\r\n\r\n\t\t\t// If our character size matches the character size of the string\r\n\t\t\t// we're trying to read, then we can read it directly into our\r\n\t\t\t// buffer. Otherwise, we have to read into an intermediate buffer\r\n\t\t\t// and convert.\r\n\t\t\t\r\n\t\t\tif ( (hdr.byCtrl & SSSO_UNICODE) != 0 )\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(wchar_t);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(wchar_t) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\t\r\n\t\t\t\t\tPWSTR pBufW = reinterpret_cast<PWSTR>(_alloca((nBytes)+1));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufW, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufW, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(char);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(char) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tPSTR pBufA = reinterpret_cast<PSTR>(_alloca(nBytes));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufA, hdr.nChars, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufA, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthis->erase();\r\n\t\t}\r\n\t\treturn hr;\r\n\t}\r\n#endif // #ifdef SS_INC_COMDEF\r\n\r\n#ifndef SS_ANSI\r\n\r\n\t// SetResourceHandle/GetResourceHandle.  In MFC builds, these map directly\r\n\t// to AfxSetResourceHandle and AfxGetResourceHandle.  In non-MFC builds they\r\n\t// point to a single static HINST so that those who call the member\r\n\t// functions that take resource IDs can provide an alternate HINST of a DLL\r\n\t// to search.  This is not exactly the list of HMODULES that MFC provides\r\n\t// but it's better than nothing.\r\n\r\n\t#ifdef _MFC_VER\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tAfxSetResourceHandle(hNew);\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn AfxGetResourceHandle();\r\n\t\t}\r\n\t#else\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tSSResourceHandle() = hNew;\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn SSResourceHandle();\r\n\t\t}\r\n\t#endif\r\n\r\n#endif\r\n};\r\n\r\n// -----------------------------------------------------------------------------\r\n// MSVC USERS: HOW TO EXPORT CSTDSTRING FROM A DLL\r\n//\r\n// If you are using MS Visual C++ and you want to export CStdStringA and\r\n// CStdStringW from a DLL, then all you need to\r\n//\r\n//\t\t1.\tmake sure that all components link to the same DLL version\r\n//\t\t\tof the CRT (not the static one).\r\n//\t\t2.\tUncomment the 3 lines of code below\r\n//\t\t3.\t#define 2 macros per the instructions in MS KnowledgeBase\r\n//\t\t\tarticle Q168958.  The macros are:\r\n//\r\n//\t\tMACRO\t\tDEFINTION WHEN EXPORTING\t\tDEFINITION WHEN IMPORTING\r\n//\t\t-----\t\t------------------------\t\t-------------------------\r\n//\t\tSSDLLEXP\t(nothing, just #define it)\t\textern\r\n//\t\tSSDLLSPEC\t__declspec(dllexport)\t\t\t__declspec(dllimport)\r\n//\r\n//\t\tNote that these macros must be available to ALL clients who want to \r\n//\t\tlink to the DLL and use the class.  If they \r\n//\r\n// A word of advice: Don't bother.\r\n//\r\n// Really, it is not necessary to export CStdString functions from a DLL.  I\r\n// never do.  In my projects, I do generally link to the DLL version of the\r\n// Standard C++ Library, but I do NOT attempt to export CStdString functions.\r\n// I simply include the header where it is needed and allow for the code\r\n// redundancy.\r\n//\r\n// That redundancy is a lot less than you think.  This class does most of its\r\n// work via the Standard C++ Library, particularly the base_class basic_string<>\r\n// member functions.  Most of the functions here are small enough to be inlined\r\n// anyway.  Besides, you'll find that in actual practice you use less than 1/2\r\n// of the code here, even in big projects and different modules will use as\r\n// little as 10% of it.  That means a lot less functions actually get linked\r\n// your binaries.  If you export this code from a DLL, it ALL gets linked in.\r\n//\r\n// I've compared the size of the binaries from exporting vs NOT exporting.  Take\r\n// my word for it -- exporting this code is not worth the hassle.\r\n//\r\n// -----------------------------------------------------------------------------\r\n//#pragma warning(disable:4231) // non-standard extension (\"extern template\")\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<char>;\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<wchar_t>;\r\n\r\n\r\n// =============================================================================\r\n//\t\t\t\t\t\tEND OF CStdStr INLINE FUNCTION DEFINITIONS\r\n// =============================================================================\r\n\r\n//\tNow typedef our class names based upon this humongous template\r\n\r\ntypedef CStdStr<char>\t\tCStdStringA;\t// a better std::string\r\ntypedef CStdStr<wchar_t>\tCStdStringW;\t// a better std::wstring\r\ntypedef CStdStr<OLECHAR>\tCStdStringO;\t// almost always CStdStringW\r\n\r\n// -----------------------------------------------------------------------------\r\n// CStdStr addition functions defined as inline\r\n// -----------------------------------------------------------------------------\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringA& s2)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, CStdStringA::value_type t)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCSTR pA)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(pA);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(PCSTR pA, const CStdStringA& sA)\r\n{\r\n\tCStdStringA sRet;\r\n\tCStdStringA::size_type nObjSize = sA.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringA::size_type>(sslen(pA));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pA);\r\n\tsRet.append(sA);\r\n\treturn sRet;\r\n}\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringW& s2)\r\n{\r\n\treturn s1 + CStdStringA(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringW& s2)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCWSTR pW)\r\n{\r\n\treturn s1 + CStdStringA(pW);\r\n}\r\n\r\n#ifdef UNICODE\r\n\tinline CStdStringW operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringW(pW) + CStdStringW(SSREF(sA));\r\n\t}\r\n\tinline CStdStringW operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn CStdStringW(pA) + sW;\r\n\t}\r\n#else\r\n\tinline CStdStringA operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringA(pW) + sA;\r\n\t}\r\n\tinline CStdStringA operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn pA + CStdStringA(sW);\r\n\t}\r\n#endif\r\n\r\n// ...Now the wide string versions.\r\ninline CStdStringW operator+(const CStdStringW& s1, CStdStringW::value_type t)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCWSTR pW)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(pW);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(PCWSTR pW, const CStdStringW& sW)\r\n{\r\n\tCStdStringW sRet;\r\n\tCStdStringW::size_type nObjSize = sW.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringW::size_type>(sslen(pW));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pW);\r\n\tsRet.append(sW);\r\n\treturn sRet;\r\n}\r\n\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringA& s2)\r\n{\r\n\treturn s1 + CStdStringW(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCSTR pA)\r\n{\r\n\treturn s1 + CStdStringW(pA);\r\n}\r\n\r\n\r\n// New-style format function is a template\r\n\r\n#ifdef SS_SAFE_FORMAT\r\n\r\ntemplate<>\r\nstruct FmtArg<CStdStringA>\r\n{\r\n    explicit FmtArg(const CStdStringA& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringA& a_;\r\nprivate:\r\n    FmtArg<CStdStringA>& operator=(const FmtArg<CStdStringA>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<CStdStringW>\r\n{\r\n    explicit FmtArg(const CStdStringW& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringW& a_;\r\nprivate:\r\n    FmtArg<CStdStringW>& operator=(const FmtArg<CStdStringW>&) { return *this; }\r\n};\r\n\r\ntemplate<>\r\nstruct FmtArg<std::string>\r\n{\r\n    explicit FmtArg(const std::string& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const std::string& a_;\r\nprivate:\r\n    FmtArg<std::string>& operator=(const FmtArg<std::string>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<std::wstring>\r\n{\r\n    explicit FmtArg(const std::wstring& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const std::wstring& a_;\r\nprivate:\r\n    FmtArg<std::wstring>& operator=(const FmtArg<std::wstring>&) {return *this;}\r\n};\r\n#endif // #ifdef SS_SAFEFORMAT\r\n\r\n#ifndef SS_ANSI\r\n\t// SSResourceHandle: our MFC-like resource handle\r\n\tinline HMODULE& SSResourceHandle()\r\n\t{\r\n\t\tstatic HMODULE hModuleSS\t= GetModuleHandle(0);\r\n\t\treturn hModuleSS;\r\n\t}\r\n#endif\r\n\r\n\r\n// In MFC builds, define some global serialization operators\r\n// Special operators that allow us to serialize CStdStrings to CArchives.\r\n// Note that we use an intermediate CString object in order to ensure that\r\n// we use the exact same format.\r\n\r\n#ifdef _MFC_VER\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp\t= strA;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp\t= strW;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrA = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrW = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n#endif\t// #ifdef _MFC_VER -- (i.e. is this MFC?)\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// GLOBAL FUNCTION:  WUFormat\r\n//\t\tCStdStringA WUFormat(UINT nId, ...);\r\n//\t\tCStdStringA WUFormat(PCSTR szFormat, ...);\r\n//\r\n// REMARKS:\r\n//\t\tThis function allows the caller for format and return a CStdStringA\r\n//\t\tobject with a single line of code.\r\n// -----------------------------------------------------------------------------\r\n\r\ninline CStdStringA WUFormatA(PCSTR szFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szFormat);\r\n\tCStdStringA strOut;\r\n\tstrOut.FormatV(szFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\ninline CStdStringW WUFormatW(PCWSTR szwFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szwFormat);\r\n\tCStdStringW strOut;\r\n\tstrOut.FormatV(szwFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\n#ifdef SS_ANSI\r\n#else\r\n\tinline CStdStringA WUFormatA(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringA strFmt;\r\n\t\tCStdStringA strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n\r\n\tinline CStdStringW WUFormatW(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringW strFmt;\r\n\t\tCStdStringW strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n#endif // #ifdef SS_ANSI\r\n\r\n\r\n\r\n#if defined(SS_WIN32) && !defined (SS_ANSI)\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: WUSysMessage\r\n\t//\t CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//\t CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t This function simplifies the process of obtaining a string equivalent\r\n\t//\t of a system error code returned from GetLastError().  You simply\r\n\t//\t supply the value returned by GetLastError() to this function and the\r\n\t//\t corresponding system string is returned in the form of a CStdStringA.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t dwError - a DWORD value representing the error code to be translated\r\n\t//\t dwLangId - the language id to use.  defaults to english.\r\n\t//\r\n\t// RETURN VALUE: \r\n\t//\t a CStdStringA equivalent of the error code.  Currently, this function\r\n\t//\t only returns either English of the system default language strings.  \r\n\t// -------------------------------------------------------------------------\r\n\t#define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT)\r\n\tinline CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatA(\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatA(\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n\tinline CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tWCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatW(L\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatW(L\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n#endif\r\n\r\n// Define TCHAR based friendly names for some of these functions\r\n\r\n#ifdef UNICODE\r\n\t//#define CStdString\t\t\t\tCStdStringW\r\n\ttypedef CStdStringW\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageW\r\n\t#define WUFormat\t\t\t\tWUFormatW\r\n#else\r\n\t//#define CStdString\t\t\t\tCStdStringA\r\n\ttypedef CStdStringA\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageA\r\n\t#define WUFormat\t\t\t\tWUFormatA\r\n#endif\r\n\r\n// ...and some shorter names for the space-efficient\r\n\r\n#define WUSysMsg\t\t\t\t\tWUSysMessage\r\n#define WUSysMsgA\t\t\t\t\tWUSysMessageA\r\n#define WUSysMsgW\t\t\t\t\tWUSysMessageW\r\n#define WUFmtA\t\t\t\t\t\tWUFormatA\r\n#define\tWUFmtW\t\t\t\t\t\tWUFormatW\r\n#define WUFmt\t\t\t\t\t\tWUFormat\r\n#define WULastErrMsg()\t\t\t\tWUSysMessage(::GetLastError())\r\n#define WULastErrMsgA()\t\t\t\tWUSysMessageA(::GetLastError())\r\n#define WULastErrMsgW()\t\t\t\tWUSysMessageW(::GetLastError())\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// FUNCTIONAL COMPARATORS:\r\n// REMARKS:\r\n//\t\tThese structs are derived from the std::binary_function template.  They\r\n//\t\tgive us functional classes (which may be used in Standard C++ Library\r\n//\t\tcollections and algorithms) that perform case-insensitive comparisons of\r\n//\t\tCStdString objects.  This is useful for maps in which the key may be the\r\n//\t\t proper string but in the wrong case.\r\n// -----------------------------------------------------------------------------\r\n#define StdStringLessNoCaseW\t\tSSLNCW\t// avoid VC compiler warning 4786\r\n#define StdStringEqualsNoCaseW\t\tSSENCW\t\t\r\n#define StdStringLessNoCaseA\t\tSSLNCA\t\t\r\n#define StdStringEqualsNoCaseA\t\tSSENCA\t\t\r\n\r\n#ifdef UNICODE\r\n\t#define StdStringLessNoCase\t\tSSLNCW\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCW\t\t\r\n#else\r\n\t#define StdStringLessNoCase\t\tSSLNCA\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCA\t\t\r\n#endif\r\n\r\nstruct StdStringLessNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\nstruct StdStringLessNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\n\r\n// If we had to define our own version of TRACE above, get rid of it now\r\n\r\n#ifdef TRACE_DEFINED_HERE\r\n\t#undef TRACE\r\n\t#undef TRACE_DEFINED_HERE\r\n#endif\r\n\r\n\r\n// These std::swap specializations come courtesy of Mike Crusader. \r\n\r\n//namespace std\r\n//{\r\n//\tinline void swap(CStdStringA& s1, CStdStringA& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//\ttemplate<>\r\n//\tinline void swap(CStdStringW& s1, CStdStringW& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//}\r\n\r\n// Turn back on any Borland warnings we turned off.\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option pop  // Turn back on inline function warnings\r\n//\t#pragma warn +inl   // Turn back on inline function warnings\r\n#endif\r\n\r\n#endif\t// #ifndef STDSTRING_H\r\n"
  },
  {
    "path": "plugins/winamp/StdStringArray.cpp",
    "content": "\r\n#include \"StdAfx.h\"\r\n#include \"StdStringArray.h\"\r\n\r\n#ifdef _DEBUG\r\n#if !defined(ASSERT_VALID)\r\n#define ASSERT_VALID(x)\t\t\t\t\t\t\t\t\t\\\r\n\tASSERT(!IsBadReadPtr(x, sizeof(CStdStringArray)));\t\\\r\n\tx->AssertValid();\r\n#endif\r\n#else\r\n#define ASSERT_VALID(x)\r\n#endif\r\n\r\ntemplate<class TYPE>\r\nvoid ConstructElements(TYPE* pElements, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pElements, nCount * sizeof(TYPE)));\r\n\r\n\t// first do bit-wise zero initialization\r\n\tmemset((void*)pElements, 0, nCount * sizeof(TYPE));\r\n\r\n\t// then call the constructor(s)\r\n\tfor (; nCount--; pElements++)\r\n\t\t::new((void*)pElements) TYPE;\r\n}\r\n\r\n\r\n\r\ntemplate<class TYPE>\r\nvoid DestructElements(TYPE* pElements, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pElements, nCount * sizeof(TYPE)));\r\n\r\n\t// call the destructor(s)\r\n\tfor (; nCount--; pElements++)\r\n\t\tpElements->~TYPE();\r\n}\r\n\r\n\r\n\r\ntemplate<class TYPE>\r\nvoid CopyElements(TYPE* pDest, const TYPE* pSrc, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pDest, nCount * sizeof(TYPE)));\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pSrc, nCount * sizeof(TYPE)));\r\n\r\n\t// default is element-copy using assignment\r\n\twhile (nCount--)\r\n\t\t*pDest++ = *pSrc++;\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nCStdStringArray::CStdStringArray()\r\n{\r\n\tm_pData = NULL;\r\n\tm_nSize = m_nMaxSize = m_nGrowBy = 0;\r\n}\r\n\r\nCStdStringArray::~CStdStringArray()\r\n{\r\n\tASSERT_VALID(this);\r\n\r\n\tDestructElements(m_pData, m_nSize);\r\n\tdelete[] (BYTE*)m_pData;\r\n}\r\n\r\nvoid CStdStringArray::SetSize(int nNewSize, int nGrowBy)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nNewSize >= 0);\r\n\r\n\tif (nGrowBy != -1)\r\n\t\tm_nGrowBy = nGrowBy;  // set new size\r\n\r\n\tif (nNewSize == 0)\r\n\t{\r\n\t\t// shrink to nothing\r\n\r\n\t\tDestructElements(m_pData, m_nSize);\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = NULL;\r\n\t\tm_nSize = m_nMaxSize = 0;\r\n\t}\r\n\telse if (m_pData == NULL)\r\n\t{\r\n\t\t// create one with exact size\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(nNewSize <= SIZE_T_MAX/sizeof(CStdString));    // no overflow\r\n#endif\r\n\t\tm_pData = (CStdString*) new BYTE[nNewSize * sizeof(CStdString)];\r\n\r\n\t\tConstructElements(m_pData, nNewSize);\r\n\r\n\t\tm_nSize = m_nMaxSize = nNewSize;\r\n\t}\r\n\telse if (nNewSize <= m_nMaxSize)\r\n\t{\r\n\t\t// it fits\r\n\t\tif (nNewSize > m_nSize)\r\n\t\t{\r\n\t\t\t// initialize the new elements\r\n\r\n\t\t\tConstructElements(&m_pData[m_nSize], nNewSize-m_nSize);\r\n\r\n\t\t}\r\n\r\n\t\telse if (m_nSize > nNewSize)  // destroy the old elements\r\n\t\t\tDestructElements(&m_pData[nNewSize], m_nSize-nNewSize);\r\n\r\n\t\tm_nSize = nNewSize;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// otherwise, grow array\r\n\t\tint nGrowBy = m_nGrowBy;\r\n\t\tif (nGrowBy == 0)\r\n\t\t{\r\n\t\t\t// heuristically determine growth when nGrowBy == 0\r\n\t\t\t//  (this avoids heap fragmentation in many situations)\r\n\t\t\tnGrowBy = min(1024, max(4, m_nSize / 8));\r\n\t\t}\r\n\t\tint nNewMax;\r\n\t\tif (nNewSize < m_nMaxSize + nGrowBy)\r\n\t\t\tnNewMax = m_nMaxSize + nGrowBy;  // granularity\r\n\t\telse\r\n\t\t\tnNewMax = nNewSize;  // no slush\r\n\r\n\t\tASSERT(nNewMax >= m_nMaxSize);  // no wrap around\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(nNewMax <= SIZE_T_MAX/sizeof(CStdString)); // no overflow\r\n#endif\r\n\t\tCStdString* pNewData = (CStdString*) new BYTE[nNewMax * sizeof(CStdString)];\r\n\r\n\t\t// copy new data from old\r\n\t\tmemcpy(pNewData, m_pData, m_nSize * sizeof(CStdString));\r\n\r\n\t\t// construct remaining elements\r\n\t\tASSERT(nNewSize > m_nSize);\r\n\r\n\t\tConstructElements(&pNewData[m_nSize], nNewSize-m_nSize);\r\n\r\n\r\n\t\t// get rid of old stuff (note: no destructors called)\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = pNewData;\r\n\t\tm_nSize = nNewSize;\r\n\t\tm_nMaxSize = nNewMax;\r\n\t}\r\n}\r\n\r\nint CStdStringArray::Append(const CStdStringArray& src)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(this != &src);   // cannot append to itself\r\n\r\n\tint nOldSize = m_nSize;\r\n\tSetSize(m_nSize + src.m_nSize);\r\n\r\n\tCopyElements(m_pData + nOldSize, src.m_pData, src.m_nSize);\r\n\r\n\treturn nOldSize;\r\n}\r\n\r\nvoid CStdStringArray::Copy(const CStdStringArray& src)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(this != &src);   // cannot append to itself\r\n\r\n\tSetSize(src.m_nSize);\r\n\r\n\tCopyElements(m_pData, src.m_pData, src.m_nSize);\r\n\r\n}\r\n\r\nvoid CStdStringArray::FreeExtra()\r\n{\r\n\tASSERT_VALID(this);\r\n\r\n\tif (m_nSize != m_nMaxSize)\r\n\t{\r\n\t\t// shrink to desired size\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(m_nSize <= SIZE_T_MAX/sizeof(CStdString)); // no overflow\r\n#endif\r\n\t\tCStdString* pNewData = NULL;\r\n\t\tif (m_nSize != 0)\r\n\t\t{\r\n\t\t\tpNewData = (CStdString*) new BYTE[m_nSize * sizeof(CStdString)];\r\n\t\t\t// copy new data from old\r\n\t\t\tmemcpy(pNewData, m_pData, m_nSize * sizeof(CStdString));\r\n\t\t}\r\n\r\n\t\t// get rid of old stuff (note: no destructors called)\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = pNewData;\r\n\t\tm_nMaxSize = m_nSize;\r\n\t}\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid CStdStringArray::SetAtGrow(int nIndex, LPCTSTR newElement)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t\tSetSize(nIndex+1);\r\n\tm_pData[nIndex] = newElement;\r\n}\r\n\r\n\r\nvoid CStdStringArray::SetAtGrow(int nIndex, const CStdString& newElement)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t\tSetSize(nIndex+1);\r\n\tm_pData[nIndex] = newElement;\r\n}\r\n\r\n\r\n\r\nvoid CStdStringArray::InsertEmpty(int nIndex, int nCount)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);    // will expand to meet need\r\n\tASSERT(nCount > 0);     // zero or negative size not allowed\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t{\r\n\t\t// adding after the end of the array\r\n\t\tSetSize(nIndex + nCount);  // grow so nIndex is valid\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// inserting in the middle of the array\r\n\t\tint nOldSize = m_nSize;\r\n\t\tSetSize(m_nSize + nCount);  // grow it to new size\r\n\t\t// shift old data up to fill gap\r\n\t\tmemmove(&m_pData[nIndex+nCount], &m_pData[nIndex],\r\n\t\t\t(nOldSize-nIndex) * sizeof(CStdString));\r\n\r\n\t\t// re-init slots we copied from\r\n\r\n\t\tConstructElements(&m_pData[nIndex], nCount);\r\n\r\n\t}\r\n\r\n\t// insert new value in the gap\r\n\tASSERT(nIndex + nCount <= m_nSize);\r\n}\r\n\r\n\r\nvoid CStdStringArray::InsertAt(int nIndex, LPCTSTR newElement, int nCount)\r\n{\r\n\r\n\t// make room for new elements\r\n\tInsertEmpty(nIndex, nCount);\r\n\r\n\r\n\r\n\t// copy elements into the empty space\r\n\tCStdString temp = newElement;\r\n\twhile (nCount--)\r\n\t\tm_pData[nIndex++] = temp;\r\n\r\n}\r\n\r\n\r\nvoid CStdStringArray::InsertAt(int nIndex, const CStdString& newElement, int nCount)\r\n{\r\n\t// make room for new elements\r\n\tInsertEmpty(nIndex, nCount);\r\n\r\n\t// copy elements into the empty space\r\n\twhile (nCount--)\r\n\t\tm_pData[nIndex++] = newElement;\r\n}\r\n\r\n\r\nvoid CStdStringArray::RemoveAt(int nIndex, int nCount)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\tASSERT(nCount >= 0);\r\n\tASSERT(nIndex + nCount <= m_nSize);\r\n\r\n\t// just remove a range\r\n\tint nMoveCount = m_nSize - (nIndex + nCount);\r\n\r\n\tDestructElements(&m_pData[nIndex], nCount);\r\n\r\n\tif (nMoveCount)\r\n\t\tmemmove(&m_pData[nIndex], &m_pData[nIndex + nCount],\r\n\t\t\tnMoveCount * sizeof(CStdString));\r\n\tm_nSize -= nCount;\r\n}\r\n\r\nvoid CStdStringArray::InsertAt(int nStartIndex, CStdStringArray* pNewArray)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(pNewArray != NULL);\r\n\tASSERT_VALID(pNewArray);\r\n\tASSERT(nStartIndex >= 0);\r\n\r\n\tif (pNewArray->GetSize() > 0)\r\n\t{\r\n\t\tInsertAt(nStartIndex, pNewArray->GetAt(0), pNewArray->GetSize());\r\n\t\tfor (int i = 0; i < pNewArray->GetSize(); i++)\r\n\t\t\tSetAt(nStartIndex + i, pNewArray->GetAt(i));\r\n\t}\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Diagnostics\r\n\r\n#ifdef _DEBUG\r\nvoid CStdStringArray::AssertValid() const\r\n{\r\n\tif (m_pData == NULL)\r\n\t{\r\n\t\tASSERT(m_nSize == 0);\r\n\t\tASSERT(m_nMaxSize == 0);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tASSERT(m_nSize >= 0);\r\n\t\tASSERT(m_nMaxSize >= 0);\r\n\t\tASSERT(m_nSize <= m_nMaxSize);\r\n\t\tASSERT(!IsBadReadPtr(m_pData, m_nMaxSize * sizeof(CStdString)));\r\n\t}\r\n}\r\n#endif //_DEBUG\r\n"
  },
  {
    "path": "plugins/winamp/StdStringArray.h",
    "content": "////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n#include \"StdString.h\"\r\n\r\nclass CStdStringArray \r\n{\r\npublic:\r\n\r\n// Construction\r\n\tCStdStringArray();\r\n\r\n// Attributes\r\n\tint GetSize() const;\r\n\tint GetUpperBound() const;\r\n\tvoid SetSize(int nNewSize, int nGrowBy = -1);\r\n\r\n// Operations\r\n\t// Clean up\r\n\tvoid FreeExtra();\r\n\tvoid RemoveAll();\r\n\r\n\t// Accessing elements\r\n\tCStdString GetAt(int nIndex) const;\r\n\tvoid SetAt(int nIndex, LPCTSTR newElement);\r\n\r\n\tvoid SetAt(int nIndex, const CStdString& newElement);\r\n\r\n\tCStdString& ElementAt(int nIndex);\r\n\r\n\t// Direct Access to the element data (may return NULL)\r\n\tconst CStdString* GetData() const;\r\n\tCStdString* GetData();\r\n\r\n\t// Potentially growing the array\r\n\tvoid SetAtGrow(int nIndex, LPCTSTR newElement);\r\n\r\n\tvoid SetAtGrow(int nIndex, const CStdString& newElement);\r\n\r\n\tint Add(LPCTSTR newElement);\r\n\r\n\tint Add(const CStdString& newElement);\r\n\r\n\tint Append(const CStdStringArray& src);\r\n\tvoid Copy(const CStdStringArray& src);\r\n\r\n\t// overloaded operator helpers\r\n\tCStdString operator[](int nIndex) const;\r\n\tCStdString& operator[](int nIndex);\r\n\r\n\t// Operations that move elements around\r\n\tvoid InsertAt(int nIndex, LPCTSTR newElement, int nCount = 1);\r\n\r\n\tvoid InsertAt(int nIndex, const CStdString& newElement, int nCount = 1);\r\n\r\n\tvoid RemoveAt(int nIndex, int nCount = 1);\r\n\tvoid InsertAt(int nStartIndex, CStdStringArray* pNewArray);\r\n\r\n// Implementation\r\nprotected:\r\n\tCStdString* m_pData;   // the actual array of data\r\n\tint m_nSize;     // # of elements (upperBound - 1)\r\n\tint m_nMaxSize;  // max allocated\r\n\tint m_nGrowBy;   // grow amount\r\n\r\n\tvoid InsertEmpty(int nIndex, int nCount);\r\n\r\n\r\npublic:\r\n\t~CStdStringArray();\r\n\r\n#ifdef _DEBUG\r\n\tvoid AssertValid() const;\r\n#endif\r\n\r\nprotected:\r\n\t// local typedefs for class templates\r\n\ttypedef CStdString BASE_TYPE;\r\n\ttypedef LPCTSTR BASE_ARG_TYPE;\r\n};\r\n\r\n\r\n\r\n\r\ninline int CStdStringArray::GetSize() const\r\n\t{ return m_nSize; }\r\ninline int CStdStringArray::GetUpperBound() const\r\n\t{ return m_nSize-1; }\r\ninline void CStdStringArray::RemoveAll()\r\n\t{ SetSize(0); }\r\ninline CStdString CStdStringArray::GetAt(int nIndex) const\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\treturn m_pData[nIndex]; }\r\ninline void CStdStringArray::SetAt(int nIndex, LPCTSTR newElement)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\tm_pData[nIndex] = newElement; }\r\n\r\ninline void CStdStringArray::SetAt(int nIndex, const CStdString& newElement)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\tm_pData[nIndex] = newElement; }\r\n\r\ninline CStdString& CStdStringArray::ElementAt(int nIndex)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\treturn m_pData[nIndex]; }\r\ninline const CStdString* CStdStringArray::GetData() const\r\n\t{ return (const CStdString*)m_pData; }\r\ninline CStdString* CStdStringArray::GetData()\r\n\t{ return (CStdString*)m_pData; }\r\ninline int CStdStringArray::Add(LPCTSTR newElement)\r\n\t{ int nIndex = m_nSize;\r\n\t\tSetAtGrow(nIndex, newElement);\r\n\t\treturn nIndex; }\r\n\r\ninline int CStdStringArray::Add(const CStdString& newElement)\r\n\t{ int nIndex = m_nSize;\r\n\t\tSetAtGrow(nIndex, newElement);\r\n\t\treturn nIndex; }\r\n\r\ninline CStdString CStdStringArray::operator[](int nIndex) const\r\n\t{ return GetAt(nIndex); }\r\ninline CStdString& CStdStringArray::operator[](int nIndex)\r\n\t{ return ElementAt(nIndex); }\r\n\r\n\r\n"
  },
  {
    "path": "plugins/winamp/UTF.cpp",
    "content": "#include \"stdafx.h\"\r\n#include <string>\r\n#include \"UTF.h\"\r\n\r\nbool UTF::wchartoutf8(const wchar_t* in, std::string &out)\r\n{\r\n\tout.clear();\r\n\twhile (*in)\r\n\t{\r\n\t\tunsigned short muh = *in;\r\n\t\tif (!(muh & 0xFF80))\r\n\t\t{\r\n\t\t\tout += (char)muh;\r\n\t\t}\r\n\t\telse if (!(muh & 0xF800))\r\n\t\t{\r\n\t\t\tout += 0xC0 | (muh >> 6);\r\n\t\t\tout += 0x80 | (muh & 0x3F);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tout += 0xE0 | (muh >> 12);\r\n\t\t\tout += 0x80 | ((muh >> 6) & 0x3F);\r\n\t\t\tout += 0x80 | (muh & 0x3F);\r\n\t\t}\r\n\t\tin++;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nbool UTF::utf8towstring(const char* in, std::wstring &out)\r\n{\r\n\treturn utf8towstring((const unsigned char*) in, out);\r\n}\r\n\r\nbool UTF::utf8towstring(const unsigned char* in, std::wstring &out)\r\n{\r\n\tout.clear();\r\n\twhile (*in)\r\n\t{\r\n\t\tchar muh = *in;\r\n\t\tif ((muh & 0xF0) == 0xE0)\r\n\t\t{\r\n\t\t\tchar muh2 = *(in+1);\r\n\t\t\tif ((muh2 & 0xC0) != 0x80)\r\n\t\t\t\treturn false;\r\n\t\t\tchar muh3 = *(in+2);\r\n\t\t\tif ((muh3 & 0xC0) != 0x80)\r\n\t\t\t\treturn false;\r\n\t\t\tout += ((muh & 0x0F) << 12) | ((muh2 & 0x3F) << 6) | (muh3 & 0x3F);\r\n\t\t\tin += 3;\r\n\t\t}\r\n\t\telse if ((muh & 0xE0) == 0xC0)\r\n\t\t{\r\n\t\t\tchar muh2 = *(in+1);\r\n\t\t\tif ((muh2 & 0xC0) != 0x80)\r\n\t\t\t\treturn false;\r\n\t\t\tout += ((muh & 0x1F) << 6) | (muh2 & 0x3F);\r\n\t\t\tin += 2;\r\n\t\t}\r\n\t\telse if ((muh & 0x80) == 0x00)\r\n\t\t{\r\n\t\t\tout += muh;\r\n\t\t\tin++;\r\n\t\t}\r\n\t\telse\r\n\t\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n"
  },
  {
    "path": "plugins/winamp/UTF.h",
    "content": "#pragma once\r\n\r\nclass UTF\r\n{\r\npublic:\r\n\tstatic bool wchartoutf8(const wchar_t* in, std::string &out);\r\n\tstatic bool utf8towstring(const unsigned char* in, std::wstring &out);\r\n\tstatic bool utf8towstring(const char* in, std::wstring &out);\r\n};\r\n"
  },
  {
    "path": "plugins/winamp/VersionApp.cpp",
    "content": "// VersionApp.cpp: Implementierung der Klasse CVersionApp.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n#include \"VersionApp.h\"\r\n#include <winver.h>\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// Konstruktion/Destruktion\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nCVersionApp::CVersionApp()\r\n{\r\n\tRefresh();\r\n}\r\n\r\nCVersionApp::~CVersionApp()\r\n{\r\n}\r\n\r\nvoid CVersionApp::Refresh(HINSTANCE hInstance /* = NULL */)\r\n{\r\n\tif(hInstance != NULL)\r\n\t\tm_hInstance = hInstance;\r\n\r\n\tm_strOSVersion = \"\";\r\n\t\r\n\tReadResourceInformation();\r\n\tReadFileTime();\r\n}\r\n\r\nBOOL CVersionApp::ReadResourceInformation()\r\n{\r\n\tDWORD\tdwLength, dwSize, dwNullHandle;\r\n\tTCHAR\tszFileName [MAX_PATH];\r\n\tLPVOID\tlpVersionPtr;\r\n\tUINT\tuiVerLength;\r\n\t\r\n\t\r\n\tdwSize = sizeof (szFileName) / sizeof (szFileName [0]);\r\n\tdwLength = ::GetModuleFileName (m_hInstance, szFileName, dwSize);\r\n\tif (dwLength <= 0) \r\n\t\treturn FALSE;\r\n\r\n\tm_VersionInfo.sFilePath=szFileName;\r\n\tdwLength = ::GetFileVersionInfoSize (szFileName, &dwNullHandle);\r\n\tif (dwLength <= 0) \r\n\t\treturn FALSE;\r\n\r\n\tBYTE* pVersionInfo = new BYTE [dwLength];\r\n\tif (!::GetFileVersionInfo (szFileName, NULL, dwLength, pVersionInfo)) \r\n\t\treturn FALSE;\t\r\n\tif (!::VerQueryValue (pVersionInfo, _T (\"\\\\\"), &lpVersionPtr, &uiVerLength)) \r\n\t\treturn FALSE;\r\n\r\n\tm_VersionInfo.vsFixedFileInfo = *(VS_FIXEDFILEINFO*)lpVersionPtr;\r\n\t\r\n\tif (!GetDynamicInfo(pVersionInfo)) \r\n\t\treturn FALSE;\t\r\n\tif (!GetFixedFileInfo ()) \r\n\t\treturn FALSE;\r\n\t\r\n\tdelete pVersionInfo;\t\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CVersionApp::GetFixedFileInfo()\r\n{\r\n\tm_VersionInfo.stMinorVersion.Format(\"%d%d\",HIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS));\r\n\tm_VersionInfo.stMajorVersion.Format(\"%d\",LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS));\r\n\tm_VersionInfo.stDllVersion.Format (\"%d.%d.%d.%d\", \r\n\t\tHIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS),\r\n\t\tHIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS));\r\n\r\n\tif (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_DRV)\r\n\t{\r\n\t\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileSubtype) \r\n\t\t{\r\n\t\t\tcase VFT2_DRV_DISPLAY:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Display driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_INSTALLABLE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Installable driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_KEYBOARD:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Keyboard driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_LANGUAGE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Language driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_MOUSE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Mouse driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_NETWORK:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Network driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_PRINTER:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Printer driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_SOUND:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Sound driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_SYSTEM:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"System driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_UNKNOWN:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Unknown driver\");\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_FONT) \r\n\t{\r\n\t\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileSubtype) \r\n\t\t{\r\n\t\t\tcase VFT2_FONT_RASTER:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Raster font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_FONT_TRUETYPE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Truetype font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_FONT_VECTOR:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Vector font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_UNKNOWN:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Unknown font\");\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_APP) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Application\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_DLL) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Dynamic link library\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_STATIC_LIB) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Static link library\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_VXD) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Virtual device\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_UNKNOWN) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Unknown type\");\r\n\t}\r\n\r\n\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileOS) \r\n\t{\r\n\t\tcase VOS_DOS:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_DOS_WINDOWS16:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit windows running on MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_DOS_WINDOWS32:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Win32 API running on MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS216:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS216_PM16:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit Presentation manager running on 16-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS232:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"32-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_NT:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Windows NT\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_NT_WINDOWS32:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Win32 API on Windows NT\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_UNKNOWN:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Unknown OS\");\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\treturn (true);\r\n}\r\n\r\nBOOL CVersionApp::GetDynamicInfo(BYTE *pVersionInfo)\r\n{\r\n\tUINT\tuiVerLength;\r\n\tLPVOID\tlpPtr;\r\n\tCStdString\tsQuery;\r\n\t\t\r\n\r\n\tif (::VerQueryValue (pVersionInfo, \"\\\\VarFileInfo\\\\Translation\", &lpPtr, &uiVerLength))\r\n\t\tm_VersionInfo.Translation = *(VERSION_INFORMATION::TRANSLATE*)lpPtr;\r\n\t\r\n\tsQuery.Format (\t_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\CompanyName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stCompany=CStdString((LPCTSTR)lpPtr);\r\n\t\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\LegalCopyRight\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stCopyRight=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\ProductName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stProductName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\ProductVersion\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stProductVersion=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\OriginalFileName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stOriginalName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\FileDescription\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stDescription=CStdString((LPCTSTR)lpPtr);\r\n\t\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\FileVersion\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stFileVersion=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\InternalName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stInternalName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\PrivateBuild\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stPrivateBuild=CStdString((LPCTSTR)lpPtr);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CVersionApp::ReadFileTime()\r\n{\r\n\tFILE* pFile = NULL;\r\n\r\n\tif( (!m_VersionInfo.sFilePath.IsEmpty()) && \r\n\t\t  (pFile = fopen(m_VersionInfo.sFilePath,\"r\")) != NULL)\r\n\t{\r\n\t\tBOOL bRet = GetFileTime(pFile,&m_CreationTime,&m_LastAccessTime,&m_LastWriteTime);\r\n\t\tfclose(pFile);\r\n\t\treturn bRet;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CVersionApp::RestoreAssociation(CStdString Ext, CStdString Name, int index)\r\n{\r\n\tCStdString strRegAppPath, strAppPath = GetAppFilepath();\r\n\tCRegistry reg;\r\n\tCStdString Temp, Temp1;\r\n\tCStdString KeyName;\r\n\r\n\t// Remove Whitespaces\r\n\tfor(int i = 0; i < Name.GetLength(); i++)\r\n\t{\r\n\t\tif(Name[i] != 0x20)\r\n\t\t\tKeyName += Name[i];\r\n\t}\r\n\r\n\tif(Ext.Left(1) != \".\")\r\n\t\tExt = \".\" + Ext;\r\n\r\n\tif(!reg.VerifyKey(HKEY_CLASSES_ROOT, Ext))  // Check to see if the key exists\r\n\t{\r\n\t\tif(reg.CreateKey(HKEY_CLASSES_ROOT, Ext))  // if it doesnt then create it\r\n\t\t{\r\n\t\t\treg.Open(HKEY_CLASSES_ROOT, Ext);  // Open the Registry\r\n\t\t\treg.Write(\"\", KeyName);\r\n\t\t\treg.Close();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn FALSE;\r\n\t\t}\r\n\t}\r\n\r\n\tif(!reg.VerifyKey(HKEY_CLASSES_ROOT, KeyName))  // Check to see if the key exists\r\n\t{\r\n\t\treg.CreateKey(HKEY_CLASSES_ROOT, KeyName);  // if it doesnt then create it\r\n\t\treg.Open(HKEY_CLASSES_ROOT, KeyName); \r\n\t\treg.Write(\"\", Name);\r\n\t\treg.Close();\r\n\t\tTemp = KeyName + \"\\\\DefaultIcon\";\r\n\t\treg.CreateKey(HKEY_CLASSES_ROOT, Temp);  // if it doesnt then create it\r\n\t\treg.Open(HKEY_CLASSES_ROOT, Temp);  \r\n\t\tTemp.Format(\"%s,%d\", strAppPath.c_str(), index);\r\n\t\treg.Write(\"\",Temp);\r\n\t\treg.Close();\r\n\t}\r\n\r\n\tTemp = KeyName + \"\\\\DefaultIcon\";\r\n\tif(!reg.Open(HKEY_CLASSES_ROOT, Temp))\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\treg.Read(\"\", Temp);\r\n\r\n\t// Comapre the path without the comma\r\n\tint pos = Temp.Find(\",\");\r\n\tif(pos >= 0)\r\n\t\tstrRegAppPath = Temp.Left(pos);\r\n\r\n\tif(strRegAppPath != strAppPath)\r\n\t{\r\n\t\tTemp1.Format(\"%s,%d\", strAppPath.c_str(), index);\r\n\t\treg.Write(\"\", Temp1);\r\n\t}\r\n\r\n\tif(atoi(Temp.Right(1)) != index)\r\n\t{\r\n\t\tTemp1.Format(\"%s,%d\", strAppPath.c_str(), index);\r\n\t\treg.Write(\"\", Temp1);\r\n\t}\r\n\r\n\treg.Close();\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nCStdString CVersionApp::GetOSVersion()\r\n{\r\n\tTCHAR sText[512];\r\n  TCHAR sBuf[100];\r\n  COSVersion os;\r\n\tCOSVersion::OS_VERSION_INFO osvi;\r\n  memset(&osvi, 0, sizeof(osvi));\r\n    \r\n  if (os.GetVersion(&osvi))\r\n  {\r\n    _stprintf(sText, _T(\"\"));\r\n    \r\n    switch (osvi.UnderlyingPlatform)\r\n    {\r\n      case COSVersion::Dos:               \r\n      {\r\n        _tcscat(sText, _T(\"DOS\"));                \r\n        break;\r\n      }\r\n      case COSVersion::Windows3x:         \r\n      {\r\n        _tcscat(sText, _T(\"Windows\"));        \r\n        if (os.IsWin32sInstalled(&osvi))\r\n          _tcscat(sText, _T(\" (Win32s)\"));\r\n        break;\r\n      }\r\n      case COSVersion::WindowsCE:\r\n      {\r\n        _tcscat(sText, _T(\"Windows CE\"));        \r\n        break;\r\n      }\r\n      case COSVersion::Windows9x:\r\n      {\r\n        if (os.IsWindows95(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95\"));\r\n        else if (os.IsWindows95SP1(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95 SP1\"));\r\n        else if (os.IsWindows95OSR2(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95 OSR2\"));\r\n        else if (os.IsWindows98(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98\"));\r\n        else if (os.IsWindows98SP1(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98 SP1\"));\r\n        else if (os.IsWindows98SE(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98 Second Edition\"));\r\n        else if (os.IsWindowsME(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows Millenium Edition\"));\r\n        else\r\n          _stprintf(sBuf, _T(\"Windows ??\"));\r\n        _tcscat(sText, sBuf);          \r\n        break;\r\n      }\r\n      case COSVersion::WindowsNT:\r\n      {\r\n        if (os.IsNTPreWin2k(&osvi))\r\n        {\r\n          _tcscat(sText, _T(\"Windows NT\"));          \r\n\r\n          if (os.IsNTWorkstation(&osvi))\r\n            _tcscat(sText, _T(\" (Workstation)\"));\r\n          else if (os.IsNTStandAloneServer(&osvi))\r\n            _tcscat(sText, _T(\" (Server)\"));\r\n          else if (os.IsNTPDC(&osvi))\r\n            _tcscat(sText, _T(\" (Primary Domain Controller)\"));\r\n          else if (os.IsNTBDC(&osvi))\r\n            _tcscat(sText, _T(\" (Backup Domain Controller)\"));\r\n\r\n          if (os.IsNTDatacenterServer(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter)\"));\r\n          else if (os.IsNTEnterpriseServer(&osvi))\r\n            _tcscat(sText, _T(\", (Enterprise)\"));\r\n        }\r\n        else if (os.IsWindows2000(&osvi))\r\n        {\r\n          _tcscat(sText, _T(\"Windows 2000\"));          \r\n\r\n          if (os.IsWin2000Professional(&osvi))\r\n            _tcscat(sText, _T(\" (Professional)\"));\r\n          else if (os.IsWin2000Server(&osvi))\r\n            _tcscat(sText, _T(\" (Server)\"));\r\n          else if (os.IsWin2000DomainController(&osvi))\r\n            _tcscat(sText, _T(\" (Domain Controller)\"));\r\n\r\n          if (os.IsWin2000DatacenterServer(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter)\"));\r\n          else if (os.IsWin2000AdvancedServer(&osvi))\r\n            _tcscat(sText, _T(\", (Advanced Server)\"));\r\n        }\r\n        else if (os.IsWindowsXPOrWindowsServer2003(&osvi))\r\n        {\r\n          if (os.IsXPPersonal(&osvi))\r\n            _tcscat(sText, _T(\"Windows XP (Personal)\"));          \r\n          else if (os.IsXPProfessional(&osvi))\r\n            _tcscat(sText, _T(\"Windows XP (Professional)\"));          \r\n          else if (os.IsWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\"Windows Server 2003\"));          \r\n          else if (os.IsDomainControllerWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\"Windows Server 2003 (Domain Controller)\"));          \r\n\r\n          if (os.IsDatacenterWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter Edition)\"));\r\n          else if (os.IsEnterpriseWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Enterprise Edition)\"));\r\n          else if (os.IsWebWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Web Edition)\"));\r\n          else if (os.IsWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Standard Edition)\"));\r\n        }\r\n\r\n/*        if (os.IsTerminalServicesInstalled(&osvi))\r\n          _tcscat(sText, _T(\", (Terminal Services)\"));\r\n        if (os.ISSmallBusinessEditionInstalled(&osvi))\r\n          _tcscat(sText, _T(\", (BackOffice Small Business Edition)\"));\r\n        if (os.IsEmbedded(&osvi))\r\n          _tcscat(sText, _T(\", (Embedded)\"));\r\n        if (os.IsTerminalServicesInRemoteAdminMode(&osvi))\r\n          _tcscat(sText, _T(\", (Terminal Services in Remote Admin Mode)\"));\r\n        if (os.IsEmulated64Bit(&osvi))\r\n          _tcscat(sText, _T(\", (64 Bit Edition)\"));*/\r\n\r\n        if (osvi.dwSuiteMask & OSSUITE_UNIPROCESSOR_FREE)\r\n          _tcscat(sText, _T(\", (Uniprocessor Free)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_UNIPROCESSOR_CHECKED)\r\n          _tcscat(sText, _T(\", (Uniprocessor Checked)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_MULTIPROCESSOR_FREE)\r\n          _tcscat(sText, _T(\", (Multiprocessor Free)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_MULTIPROCESSOR_CHECKED)\r\n          _tcscat(sText, _T(\", (Multiprocessor Checked)\"));\r\n\r\n        break;\r\n      }\r\n      default: \r\n      {\r\n        _stprintf(sBuf, _T(\"Unknown OS\"));\r\n        break;\r\n      }\r\n    }                     \r\n    _stprintf(sBuf, _T(\" v%d.\"), osvi.dwEmulatedMajorVersion);\r\n    _tcscat(sText, sBuf);     \r\n    if (osvi.dwEmulatedMinorVersion % 10)\r\n    {\r\n      if (osvi.dwEmulatedMinorVersion > 9)\r\n        _stprintf(sBuf, _T(\"%02d\"), osvi.dwEmulatedMinorVersion);\r\n      else\r\n        _stprintf(sBuf, _T(\"%01d\"), osvi.dwEmulatedMinorVersion);\r\n    }\r\n    else\r\n      _stprintf(sBuf, _T(\"%01d\"), osvi.dwEmulatedMinorVersion / 10);\r\n    _tcscat(sText, sBuf);                           \r\n    if (osvi.dwEmulatedBuildNumber)\r\n    {\r\n      _stprintf(sBuf, _T(\" Build:%d\"), osvi.dwEmulatedBuildNumber);\r\n      _tcscat(sText, sBuf);           \r\n    }\r\n    if (osvi.wEmulatedServicePackMajor)       \r\n    {\r\n      if (osvi.wEmulatedServicePackMinor)\r\n      {\r\n        //Handle the special case of NT 4 SP 6a which Dtwinver ver treats as SP 6.1\r\n        if (os.IsNTPreWin2k(&osvi) && (osvi.wEmulatedServicePackMajor == 6) && (osvi.wEmulatedServicePackMinor == 1))\r\n          _stprintf(sBuf, _T(\" Service Pack: 6a\"));\r\n        //Handle the special case of XP SP 1a which Dtwinver ver treats as SP 1.1\r\n        else if (os.IsWindowsXP(&osvi) && (osvi.wEmulatedServicePackMajor == 1) && (osvi.wEmulatedServicePackMinor == 1))\r\n          _stprintf(sBuf, _T(\" Service Pack: 1a\"));\r\n        else       \r\n          _stprintf(sBuf, _T(\" Service Pack:%d.%d\"), osvi.wEmulatedServicePackMajor, osvi.wEmulatedServicePackMinor);\r\n      }\r\n      else\r\n        _stprintf(sBuf, _T(\" Service Pack:%d\"), osvi.wEmulatedServicePackMajor);\r\n      _tcscat(sText, sBuf);\r\n    }                            \r\n    else\r\n    {\r\n      if (osvi.wEmulatedServicePackMinor)       \r\n        _stprintf(sBuf, _T(\" Service Pack:0.%d\"), osvi.wEmulatedServicePackMinor);\r\n    }\r\n\t}\r\n\telse\r\n\t\t_tcscat(sText, \"Failed in call to GetOSVersion\");\r\n\r\n\treturn CStdString(sText);\r\n}\r\n\r\nCStdString CVersionApp::GetWorkingDir()\r\n{\r\n\tchar filename[512];\r\n\tGetModuleFileName(m_hInstance,filename,sizeof(filename));\r\n\tCStdString Temp = filename;\r\n\tint pos = Temp.ReverseFind('\\\\');\r\n\tTemp = Temp.Left(pos + 1);\r\n\r\n\treturn Temp;\r\n}"
  },
  {
    "path": "plugins/winamp/VersionApp.h",
    "content": "// VersionApp.h: Schnittstelle fr die Klasse CVersionApp.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_)\r\n#define AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n#include \"StdString.h\"\r\n#include \"ComDATE.h\"\r\n#include \"Registry.h\"\r\n#include \"OSVer.h\"\r\n\r\n#pragma comment(lib,\"version.lib\") \r\n\r\ntypedef struct tagVersionInformation\r\n{\r\n\tCStdString sFilePath;\r\n\tCStdString\tstCompany;\r\n\tCStdString\tstCopyRight;\r\n\tCStdString\tstDescription;\r\n\tCStdString\tstFileVersion;\r\n\tCStdString stMajorVersion;\r\n\tCStdString stMinorVersion;\r\n\tCStdString\tstInternalName;\r\n\tCStdString\tstOriginalName;\r\n\tCStdString\tstProductName;\r\n\tCStdString\tstProductVersion;\r\n\tCStdString\tstPrivateBuild;\r\n\tCStdString\tstDllVersion;\r\n\tCStdString\tstFileOS;\r\n\tCStdString\tstFileType;\r\n\tCStdString stLanguageId;\r\n\tCStdString stCharSet;\r\n\tVS_FIXEDFILEINFO vsFixedFileInfo;\r\n\tstruct TRANSLATE \r\n\t{\r\n\t\tWORD languageId;\r\n\t\tWORD characterSet;\r\n\t} Translation;\r\n}VERSION_INFORMATION, *LPVERSION_INFORMATION;\r\n\r\nclass CVersionApp  \r\n{\r\npublic:\t\r\n\tCVersionApp();\r\n\r\n\tvoid Refresh(HINSTANCE hInstance = NULL);\r\n\r\n\tCStdString GetAppVersion(){return m_VersionInfo.stFileVersion;}\r\n\tCStdString GetAppBuildDate(){return CComDATE(m_CreationTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppLastAccessDate(){return CComDATE(m_LastAccessTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppWriteDate(){return CComDATE(m_LastWriteTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppFilepath(){return m_VersionInfo.sFilePath;}\r\n\tCStdString GetAppCopyright(){return m_VersionInfo.stCopyRight;}\r\n\tCStdString GetAppOriginalname(){return m_VersionInfo.stOriginalName;}\r\n\tCStdString GetAppCompany(){return m_VersionInfo.stCompany;}\r\n\tCStdString\tGetAppDescription(){return m_VersionInfo.stDescription;}\r\n\tCStdString GetAppInternalName(){return m_VersionInfo.stInternalName;}\r\n\tCStdString GetAppProductName(){return m_VersionInfo.stProductName;}\r\n\tCStdString GetAppProductVersion(){return m_VersionInfo.stProductVersion;}\r\n\tCStdString GetAppPrivateBuild(){return m_VersionInfo.stPrivateBuild;}\r\n\tCStdString GetAppMajorVersion(){return m_VersionInfo.stMajorVersion;}\r\n\tCStdString GetAppMinorVersion(){return m_VersionInfo.stMinorVersion;}\r\n\r\n\tCStdString GetOSVersion();\r\n\tCStdString GetWorkingDir();\r\n\r\n\tBOOL RestoreAssociation(CStdString Ext, CStdString Name, int index);\r\n\r\n\tvirtual ~CVersionApp();\r\n\r\nprotected:\r\n\tBOOL ReadFileTime();\r\n\tBOOL GetFixedFileInfo();\r\n\tBOOL GetDynamicInfo(BYTE* pVersionInfo);\r\n\tBOOL ReadResourceInformation();\r\n\tVERSION_INFORMATION m_VersionInfo;\r\n\tFILETIME m_CreationTime,m_LastAccessTime,m_LastWriteTime;\r\n\tCStdString m_strOSVersion;\r\n\tHINSTANCE m_hInstance;\r\n};\r\n\r\n#endif // !defined(AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/winamp/WhatsNew.txt",
    "content": "=================\r\n== What's New  ==\r\n=================\r\n\r\n10/01/12 2.1.0.11\r\n-------------------------------------------------------------------------------\r\nFixed a bug when bootstrapping.\r\n\r\n20/8/12 2.1.0.10\r\n-------------------------------------------------------------------------------\r\nNow sends album artist as parameter d in scrob sub protocol.\r\n\r\n\r\n13/5/08 2.1.0.9\r\n-------------------------------------------------------------------------------\r\nUpdates broken Updater.exe in client if installed.\r\n\r\n\r\n11/1/07 2.1.0.8\r\n-------------------------------------------------------------------------------\r\nAdded workaround for Winamp occasionally reporting the wrong artist name\r\nwhich resulted in mixed up artist/track combinations.\r\n\r\n\r\n29/11/07 2.1.0.7\r\n-------------------------------------------------------------------------------\r\nVS 2003 build.\r\n\r\n\r\n22/11/07 2.1.0.6\r\n-------------------------------------------------------------------------------\r\nMore debug output to try and catch a bootstrap crash.\r\n\r\n\r\n19/11/07 2.1.0.5\r\n-------------------------------------------------------------------------------\r\nImport now also reading last played times.\r\n\r\n\r\n19/11/07 2.1.0.4\r\n-------------------------------------------------------------------------------\r\nFixed potential crash due to buffer overrun when requesting Unicode metadata.\r\nFixed stuck dialog when trying to import empty library.\r\n\r\n\r\n15/11/07 2.1.0.3\r\n-------------------------------------------------------------------------------\r\nBootstrapping added.\r\n\r\n\r\n19/10/07 2.0.47.0\r\n-------------------------------------------------------------------------------\r\nTracks with Unicode characters now show up correctly in task bar.\r\nAPE tags can now be read and sent to Last.fm.\r\n\r\n\r\n18/10/07 2.0.46.0\r\n-------------------------------------------------------------------------------\r\nFixed problem with new track detection in Winamp 5.5\r\n\r\n\r\n31/7/07 2.0.45.0\r\n-------------------------------------------------------------------------------\r\nRecompiled with new ScrobSub for Vista compatibility.\r\n\r\n\r\n17/7/07 2.0.43.0\r\n-------------------------------------------------------------------------------\r\nFixed bug that made some people's machines hang.\r\nFixed taskbar track title getting corrupted.\r\n\r\n\r\n11/7/07 2.0.35.0\r\n-------------------------------------------------------------------------------\r\nNow supports tracks with Unicode tags for Winamp versions above 5.13.\r\n\r\n\r\n22/6/06 2.0.26.0\r\n-------------------------------------------------------------------------------\r\nChanged output name to ml_wa2_scrobbler.dll and recompiled with new ScrobSub\r\nfor the beta release of the new Last.fm client.\r\n\r\n\r\n11/04/2006 2.0.22.0\r\n------------------------\r\nAdded MMS: to excluded protocols. Allowed paths starting with \\\\. Added a Stop command on shutdown as WMP doesn't send a Stop otherwise. Bigger workaround for -1 bug, sleeping and retrying a few times as the Winamp forums said that it can return -1 if it hasn't had time to calculate the time yet.\r\n\r\n\r\n22/03/2006 2.0.19.0\r\n------------------------\r\nFixed it so that it calls stop also when in paused state.\r\n\r\n\r\n22/03/2006 2.0.18.0\r\n------------------------\r\nChanged protocol to include Pause due to new AS progress indicator.\r\n\r\n\r\n20/03/2006 2.0.16.0\r\n------------------------\r\nFixed an off-by-one bug that converted artist or track names with one character wrong to UTF8.\r\n\r\n\r\n28/02/2006 2.0.3.0 (Erik)\r\n------------------------\r\nButchered plugin to work with new Audioscrobbler Service. All internet-related and caching functionality removed and ScrobSub installed for handling communication with AS.\r\n\r\n\r\n31/08/2005 1.1.10 (lozzd - laurie@denness.net)\r\n------------------------\r\nBug - Serious handshake/submissions server mismatch bug. \r\n\r\n\r\n07/03/2005 1.1.9 Final\r\n----------------------\r\nChange - Track plays are detected slightly differently which should stop Winamp from hanging when\r\n         a new track is played\r\nChange - Better error message when can't connect\r\n\r\n\r\n\r\n21/02/2005 1.1.9 Beta 3\r\n------------------------\r\nChange - Add support for Global Hotkeys for enable/disable and show config\r\nChange - Can include/exclude directories individually now (+ bugfixes)\r\n\r\n12/01/2005 - 1.1.9 Beta 2\r\n--------------------------\r\nBug - Song length -1 for tracks for which the track length couldn't be determined. Now default this to 240 (4 mins)\r\n\r\n05/01/2005 - 1.1.9 Beta 1\r\n--------------------------\r\nBug - Plugin wouldn't load settings on Windows 95\r\nBug - Player pauses for 5 seconds when cannot determine track length\r\nBug - Handshaking in 945098734s.\r\nChange - Clearer handshake status messages\r\nChange - If the current song length cannot be determined (because Player won't tell me), the song is submitted after the default of 240s. \r\n        If the song is less than 240s long, the submission won't take place. Best I can do under the circumstances I'm afraid.\r\nChange - New Window in Winamp for Media Library users to monitor Audioscrobbler submission status. This is very experimental at the moment and might not make it into the final build.\r\nChange - On HTTP Error drop connection and force a fresh handshake\r\n\r\n18/10/2004 - Build 613\r\n-----------------------\r\nBug - 'Can't find Winamp PE Window' bug\r\nBug - 'Song length -1 not allowed'\r\nBug - Song shown twice in last played in config dialog\r\nChange - Tidied Config Dialog, removed logging option, added clear password button\r\nChange - If using Proxy Authentication, 'Proxy-Connection: Keep-Alive' added to connection\r\nChange - If handshake fails, try less and less often to connect (max 2hrs)\r\n\r\n07/10/2004 - Build 612\r\n-----------------------\r\nChange - Remove song length limit\r\n\r\n29/09/2004 - Build 611\r\n-----------------------\r\nBug - Cache didn't send after server down until Winamp restarted\r\nChange - More info on Config dialog\r\n\r\n23/09/2004 - Build 610\r\n-----------------------\r\nChange - Better handling of errors during server downtime\r\nChange - Cache is sent more frequently but is now limited to 1000 tracks\r\nChange - Better error messages in Config dialog when tracks are invalid\r\n\r\n22/09/2004 - Build 609\r\n-----------------------\r\nBug - Don't submit new songs until the cache has been cleared\r\n\r\n16/09/2004 - Build 608\r\n-----------------------\r\nBug - Installer rename didn't work\r\n\r\n15/09/2004 - Build 607\r\n-----------------------\r\nBug - Log file size is displayed correctly now\r\nChange - New Installer\r\n\r\n01/09/2004 - Build 606\r\n-----------------------\r\nChange - Sends cache chunks less often (every 30 secs) to prevent server rejecting it\r\nChange - Works as Gen or ML plugin\r\nBug - Fix (maybe) for -1 songs lengths\r\n\r\n27/08/2004\r\n-----------\r\nChange - Removed some unneeded playback checks\r\nChange - Can hide upgrade info if required\r\nChange - Improved proxy handling \r\n\r\n02/06/2004\r\n-----------\r\nChange - Changed to be media library plugin instead. Should fix tagging issues\r\n\r\n** 27/04/2004 - VERSION 1.1.7 Build 597 Released **\r\n\r\n27/04/2004\r\n-----------\r\nChange - Removed Start menu shortcut and displaying of help file during installation\r\nBig - Requests to audioscrobbler server were sometimes cached (on\r\n       ISP proxy or wherever). Should explain why some submissions have been going missing.\r\n\r\n26/04/2004\r\n----------\r\nChange - Allow users to force the plugin to try to connect even if no internet connection is detected.\r\n\r\n22/04/2004\r\n----------\r\nChange - Message in Config dlg when not submitting because of untagged file\r\n\r\n20/04/2004\r\n----------\r\nBug - Make sure last submission is properley deleted from memory\r\nBug - Fixed CD Submissions\r\nChange - Added ability to exclude or include files in certain directory paths\r\nChange - Password can be cleared using the config dialog\r\n\r\n15/04/2004\r\n----------\r\nSpib - Unsupported file type errors should be fixed\r\nSpib - Only files which are TAGGED get submitted as specified in the protocol (guessing from filenames is not done)\r\nSpib - Errors display only into config dialog and log - no more messageboxes\r\nSpib - Cache submissions are logged to file\r\nSpib - Server errors causing new handshake are logged to file\r\nSpib - Minimum submit time is now 50% or 240s rather than 120s\r\n\r\n** 05/03/2004 - VERSION 1.1.6 Build 592 Released **\r\n\r\n24/01/2004\r\n----------\r\nSpib - Always ignore HTTP streams\r\nSpib - Better detection of Artist & Album info\r\n\r\n** 24/01/2004 - VERSION 1.1.5 Build 591 Released **\r\n\r\n24/01/2004\r\n----------\r\nSpib - Remember to update the build number this time\r\nSpib - Fix for info fields not cleared between submissions\r\n\r\n** 06/01/2004 - VERSION 1.1.4 Build 590 Released **\r\n\r\n06/01/2004\r\n----------\r\nSpib - Reconnects (handshakes) if no response received\r\nSpib - Fix buffer overrun\r\nSpib - Fix UTF8 encoding (thanks Case!)\r\nSpib - Fix Winamp directory detection in NSIS\r\nSpib - Ignore HTTP Streams on by default\r\nSpib - Send Cache in small pieces (10 submissions max by default)\r\nSpib - Server responses logged to file by default\r\nSpib - Support for v1.1 Protocol\r\n\r\n** 05/07/2003 - VERSION 1.1.3 Build 575 Released **\r\n\r\n04/07/2003\r\n----------\r\nSpib - Minimum submit time is now 120s instead of 180s to bring in\r\n       line with the AS protocol.\r\nSpib - Fix for folks with system time set before Jan 2003.\r\nSpib - Additional logging.\r\nSpib - Further critical sections in CScrobbler\r\nSpib - If modem is installed but not used, plugin will try other connections now\r\n       rather than reporting no connections available\r\nSpib - Added 'forceconnection' hidden registry option to allow the user to\r\n       force the plugin to try to connect even if the plugin thinks there\r\n       is no internet connection available.\r\nSpib - Fixed crashbug in CCacheManager::Save() caused by array going\r\n       out of bounds.\r\n\r\n** 29/06/2003 - VERSION 1.1.2 Build 566 Released **\r\n\r\n29/06/2003\r\n----------\r\nSpib - Critical Sections in CCacheManager\r\n\r\n** 08/06/2003 - VERSION 1.1.1 Build 561 Released **\r\n\r\n08/06/2003\r\n----------\r\nSpib - Bugfix in CSubmission::Populate to catch long file ext\r\n\r\n** 23/05/2003 - VERSION 1.1.0 Build 555 Released **\r\n\r\n22/05/2003\r\n----------\r\nSpib - Added option to ignore HTTP streams\r\nSpib - Fixed crashbug under some OS (thanks wertherman)\r\nSpib - Enabling/Disabling plugin doesn't block submissions now\r\nSpib - More useless info added to config dialog\r\nSpib - Config dlg is modeless now so you can keep it open all the time\r\n\r\n** 19/05/2003 - VERSION 1.1.0 Beta Released **\r\n\r\n16/05/2003\r\n----------\r\nSpib - Doesn't use MFC anymore which should fix some minor resource issues.\r\nSpib - Properly identifies unsupported files now\r\nSpib - Removed ID3 option in config dialog\r\nSpib - Log file max size works now\r\n\r\n09/05/2003\r\n----------\r\nSpib - Fix for bug 735171 (Doesn't cache failed submission)\r\nSpib - UTF-8 Bug fixes\r\nSpib - Fix for bug 735635 (Wrong info submitted if playlist changes)\r\nSpib - Loads of work done detecting internet connection state for dial-up users\r\n\r\n02/05/2003\r\n----------\r\nSpib - Added Proxy / Proxy Authentication Support\r\nSpib - Fix for bug 732818 (Track titles are cut on some tracks)\r\nSpib - Fix for bug 734180 (Cached files not shown in the Last 5 Submitted)\r\n\r\n** 02/05/2003 - VERSION 1.0.4 Released **\r\n\r\n02/05/2003\r\n----------\r\nSpib - Fixes to better cope with server outages\r\nSpib - Error messages are more useful, but a bit annoying so...\r\nSpib - Config option to disable error messages\r\nSpib - Better display of Server Response in Config Dialog\r\n\r\n** 30/04/2003 - VERSION 1.0.3 Released **\r\n\r\n30/04/2003\r\n----------\r\nSpib - Fix for bug 730342 (Plugin doesn't submit CD tracks)\r\nSpib - Fix for bug 729650 (Caches forever after a FAILED response)\r\nSpib - Config dialog updates stats in real time\r\n\r\n24/04/2003\r\n----------\r\nSpib - Will work if the internet isn't connected when winamp first starts\r\nSpib - Sends timestamp as GMT\r\nSpib - Fixed a couple of small logging issues\r\nSpib - Cosmetic Fixes\r\nSpib - Prevent Error MessageBox delaying submission caching\r\n\r\n** 19/04/2003 - VERSION 1.0.2 Released **\r\n\r\n19/04/2003\r\n----------\r\nRJ - Made id3 option default to off\r\nRJ - Updated readme\r\nRJ - Put entire version history into readme, should prolly separate the 2 documents.\r\n\r\n** 18/04/2003 - VERSION 1.01 Released **\r\n\r\n17/04/2003\r\n-----------\r\nSpib - Added list of last 5 submitted songs on config dialog\r\nSpib - Songs are now submitted after 50% or 180 seconds, whichever comes first\r\n\r\n16/04/2003\r\n-------------\r\nSpib - Send cache even when not playing\r\nSpib - Various data logging improvements\r\nSpib - CSubmission::GetFriendlyName() now returns the correct data\r\nSpib - Improved UserAgent identification\r\nSpib - Added Help/Readme\r\n\r\n14/04/2003\r\n-------------\r\nSpib - UTF8 encode the track data before it is sent\r\nSpib - Config dialog displayed on new installation\r\nSpib - Option to use ID3 tags for track data\r\nSpib - Changed logging to default to DEBUG_FLOW\r\nSpib - Added hidden registry option to change log level\r\nSpib - Added option to write debug as XML (mostly for my own amusement)\r\nSpib - Removed PrivateHTTPStreams option from config dialog seeing as we don't send the path info anymore\r\n\r\n** 10/04/2003 - VERSION 1.00 Released **\r\n\r\n09/04/2003\r\n-------------\r\nSpib - Only show badpass errors once\r\nSpib - Logging stuff, filesize works now. Filesize 0 turns off\r\n       logging, size of -1 disables max size on log.\r\nSpib - Added version string to config dialog\r\nSpib - Added info about server response to config dialog\r\n\r\n\r\n08/04/2003\r\n-----------\r\nSpib - Implemented new client protocol.\r\nSpib - Made submissions respect server-supplied submit interval.\r\nSpib - Changed format of cache file to binary to allow\r\n       easier reading/writing of individual entries.\r\nSpib - Added CWinampController for easier winamp control.\r\nSpib - Added skipping of unsupported media types in submissions\r\n       as requested.\r\nSpib - Added submission cache stats to config dialog.\r\n\r\n0.9.9 [10/04/03]\r\n\r\n\r\nFinal change before 1.0 \r\nStopped plugin from submitting names of videos, avoiding various \"adult\" titles appearing on the site. (wa2.9 does videos)\r\n\r\n\r\n0.9.3 [11/02/03]\r\n\r\n\r\nDecided not to store filename or media type, to avoid possible incriminating data regarding peoples music collections\r\n\r\n\r\n0.9.2 [10/02/03]\r\n\r\n\r\n0.9.0 and 0.9.1 never submitted filename, this one does\r\n\r\n\r\n0.9.0 [10/02/03]\r\n\r\n\r\nAdded option to keep HTTP streams private \r\nReduced time-to-submission to 50% of song length \r\nAdditional error handling \r\n\r\n0.8.5 [02/01/03]\r\n\r\n\r\nCommunicates directly with new servers \r\nRemoved unnecessary encryption. (Password still secure) \r\n\r\n0.8.1 [05/12/02]\r\n\r\n\r\nAll HTTP communications are now threaded \r\nPlugin now writes significant events to logfile \r\nOption to specify maximum size of logfile \r\nOption to disable the plugin \r\nFixed and tested the offline caching, it should work now! \r\n\r\n0.7.1 [02/12/02]\r\n\r\n\r\nWrote my own XOR encrypt/decrypt function in C++ and PHP. \r\nALL client-server communication now encrypted \r\nPlugin will not submit if winamp instances>1 (using semaphores) \r\nOffline caching is now encrypted \r\nServer side fix for duplicate/hasty submissions \r\nRemove read-only flag on cache file before deletion attempt \r\n\r\n0.6.5 [26/11/02]\r\n\r\n\r\nHasty fix to 0.6 that caused double submission of all songs \r\nRewritten offline caching. Songs played offline are now updated when you connect \r\n\r\n0.6.0 [25/11/02]\r\n\r\n\r\nControl Centre now handles updates properly \r\nPassword security - MD5 digests are used vs. cleartext \r\n\r\n0.5.0 [23/11/02] (unreleased)\r\n\r\n\r\ncompletely new architecture \r\nstability should be acceptable - i learnt about memory management \r\nControl Centre now handles client updates \r\noffline caching removed as it was buggy \r\n\r\n0.4.0 [20/11/02] (unreleased)\r\n\r\n\r\nminor changes to try and fix stability \r\n\r\n0.3.0 [19/11/02] (unreleased)\r\n\r\n\r\nresolved failed submissions where & or # appeared in path \r\nfixed some random bugs and glitches \r\nupdated installer to warn to close winamp \r\ninstaller creates start-menu shortcut to readme \r\n\r\n0.2.5 [17/11/02]\r\n\r\n\r\ncomes with an installer (nulsoft) \r\nyou must listen to half the song before submission \r\nstability is getting better \r\n\r\n0.2.0 [16/11/02]\r\n\r\n\r\ndoesn't crash if you are offline :) \r\ncaches offline submissions for later in plain text file \r\nfixed bug regarding ' in song name \r\nplugin reports date and time of client instead of using server time \r\nplugin reports soundex hash for artist/song \r\ncode cleaned up \r\n\r\n0.1.0 [07/11/02]\r\n\r\n\r\nserver time is used to timestamp submissions \r\nonly works if you are online \r\nsubmits playlist text to server \r\ninitial release, testing with me and paul \r\nno installer, need some MFC DLLs installed to use \r\n\r\n\r\n=================\r\n== Known Bugs  ==\r\n=================\r\n\r\n+ The ShowConfig() routine doesn't always show the config dialog depending on\r\n  where in the program it is called. This is to do with the plugin trying to \r\n  load the dialog resource from the app rather than the DLL. AFX_MANAGE_STATE \r\n  should fix it but it doesn't seem to.\r\n"
  },
  {
    "path": "plugins/winamp/WinampBootstrap.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"WinampBootstrap.h\"\r\n#include \"ml.h\"\r\n\r\nWinampBootStrap::WinampBootStrap()\r\n                :BootStrap( L\"wa2\" ),\r\n                 m_hWndWinampML( NULL )\r\n{\r\n}\r\n\r\nWinampBootStrap::~WinampBootStrap(void)\r\n{\r\n}\r\n\r\nbool WinampBootStrap::start()\r\n{    \r\n    log( \"WinampBootStrap::start\" );\r\n\r\n    mlQueryStructW query;\r\n    query.max_results = 0;\r\n    query.query = L\"\";\r\n    query.results.Alloc = 0;\r\n    query.results.Size = 0;\r\n    query.results.Items = NULL;\r\n\r\n    SendMessage( m_hWndWinampML, WM_ML_IPC, (WPARAM)&query, ML_IPC_DB_RUNQUERYW );\r\n\r\n    setProgressValue( 0 );\r\n    if( query.results.Size > 0 )\r\n        setProgressRange( query.results.Size - 1 );\r\n    else\r\n        setProgressRange( 0 );\r\n\r\n    itemRecordW* curItem = query.results.Items;\r\n    for( int index = 0; index < query.results.Size; index++ )\r\n    {\r\n    \r\n        // Handle the paused state when the cancel button has been pushed\r\n        // and the confirmation dialog has been displayed.\r\n        while( m_paused )\r\n        {\r\n            WaitForSingleObject( m_pauseStateChanged, INFINITE );\r\n            if( m_cancel ) return false;\r\n        }\r\n\r\n        curItem = &query.results.Items[ index ];\r\n\r\n        std::wstringstream length;\r\n        length << curItem->length;\r\n\r\n        std::wstringstream lastPlay;\r\n        lastPlay << curItem->lastplay;\r\n\r\n        std::wstringstream playcount;\r\n        playcount << curItem->playcount;\r\n        BootStrapItem bootStrapItem = { curItem->artist ? curItem->artist : L\"\",\r\n\t\t\t\t\t\t\t\t\t\tcurItem->albumartist ? curItem->albumartist : L\"\",\r\n                                        curItem->title ? curItem->title : L\"\", \r\n                                        curItem->album ? curItem->album : L\"\", \r\n                                        length.str(), \r\n                                        playcount.str(), \r\n                                        curItem->filename ? curItem->filename : L\"\",\r\n                                        lastPlay.str() };\r\n\r\n        appendTrack( &bootStrapItem );\r\n        setProgressValue( index );\r\n      \r\n    }\r\n\r\n    completed();\r\n   \r\n    return true;\r\n}\r\n\r\nvoid WinampBootStrap::sethWndWinampML(HWND hWndWinampML)\r\n{\r\n    std::ostringstream os;\r\n    os << \"sethWndWinampML: \" << hWndWinampML;\r\n    log( os.str() );\r\n\r\n    m_hWndWinampML = hWndWinampML;\r\n}"
  },
  {
    "path": "plugins/winamp/WinampBootstrap.h",
    "content": "#pragma once\r\n\r\n#include \"..\\ScrobSub\\Bootstrap.h\"\r\n\r\nclass WinampBootStrap :\r\n    public BootStrap\r\n{\r\npublic:\r\n    WinampBootStrap();\r\n    ~WinampBootStrap(void);\r\n\r\n    void sethWndWinampML( HWND hWndWinampML );\r\n\r\nprivate:\r\n    HWND m_hWndWinampML;\r\n    bool start();\r\n};\r\n"
  },
  {
    "path": "plugins/winamp/WinampController.cpp",
    "content": "// WinampController.cpp: implementation of the CWinampController class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#include <stdafx.h>\r\n#include \"WinampController.h\"\r\n#include <shellapi.h>\r\n#include \"dbg.h\"\r\n#include \"UTF.h\"\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// General Stuff\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nCWinampController::CWinampController()\r\n{\r\n\tm_hWndWinamp\t\t= NULL;\r\n\tm_hWndWinampEQ\t\t= NULL;\r\n\tm_hWndWinampPE\t\t= NULL;\r\n\tm_hWndWinampMB\t\t= NULL;\r\n\tm_hWndWinampML\t\t= NULL;\r\n\tm_strVersionString\t= \"\";\t\t// Winamp Version String\r\n\tm_strWinampDir\t\t= \"\";\t\t// Winamp Directory\r\n}\r\n\r\nCWinampController::~CWinampController()\r\n{\r\n}\r\n\r\nBOOL CWinampController::Init(BOOL bStartWinampIfNotRunning,\r\n\t\t\t\t\t\t\t HWND WinampWnd /* = NULL */,\r\n\t\t\t\t\t\t\t HWND WinampWndML /* = NULL */)\r\n{\t\r\n\tif(WinampWnd == NULL)\r\n\t\tm_hWndWinamp = FindWindow(\"Winamp v1.x\", NULL);\r\n\telse\r\n\t\tm_hWndWinamp = WinampWnd;\r\n\r\n\tif(m_hWndWinamp == NULL)\r\n\t{\r\n\t\tif(bStartWinampIfNotRunning)\r\n\t\t{\r\n\t\t\t::ShellExecute(NULL, \"open\", \"c:\\\\progra~1\\\\winamp\\\\winamp.exe\", NULL, \"c:\\\\progra~1\\\\winamp\\\\\", SW_MINIMIZE);\r\n\r\n\t\t\t//Give it time to show itself\r\n\t\t\tSleep(1000);\r\n\t\t\tm_hWndWinamp = FindWindow(\"Winamp v1.x\", NULL);\r\n\r\n\t\t\tif(m_hWndWinamp == NULL)\r\n\t\t\t\treturn FALSE;\r\n\t\t}\r\n\t}\r\n\telse\r\n\t\tPRINTF(DEBUG_DETAIL, \"CWinampController::Init\", \"Failed to find Winamp Window\");\t\t\t\r\n\t\r\n\tif((m_hWndWinampEQ = FindWindow(\"Winamp EQ\", NULL)) == NULL)\r\n\t\tPRINTF(DEBUG_DETAIL, \"CWinampController::Init\", \"Failed to find Winamp EQ Window\");\r\n\r\n\tif((m_hWndWinampPE = FindWindow(\"Winamp PE\", NULL)) == NULL)\r\n\t\tPRINTF(DEBUG_DETAIL, \"CWinampController::Init\", \"Failed to find Winamp PE Window\");\r\n\r\n\tif((m_hWndWinampMB = FindWindow(\"Winamp MB\", NULL)) == NULL)\r\n\t\tPRINTF(DEBUG_DETAIL, \"CWinampController::Init\", \"Failed to find Winamp MB Window\");\r\n\r\n\tif(WinampWndML == NULL)\r\n\t{\r\n\t\tlong libhwndipc = (LONG)SendMessage(m_hWndWinamp, WM_WA_IPC, (WPARAM)\"LibraryGetWnd\", IPC_REGISTER_WINAMP_IPCMESSAGE);\r\n\r\n\t\tif((m_hWndWinampML = (HWND)SendMessage(m_hWndWinamp,WM_WA_IPC,-1,(LPARAM)libhwndipc)) == NULL)\r\n\t\t\tPRINTF(DEBUG_DETAIL, \"CWinampController::Init\", \"Failed to find Winamp ML Window\");\r\n\t}\r\n\telse\r\n\t\tm_hWndWinampML = WinampWndML;\r\n\r\n\tGetWinampDir();\r\n\tGetPlayerVersion();\r\n\r\n    return TRUE;\r\n}\r\n\r\nBOOL CWinampController::WindowsReady()\r\n{\r\n\tBOOL bReady = TRUE;\r\n\r\n\tif(m_hWndWinamp == NULL || !IsWindow(m_hWndWinamp))\r\n\t\tbReady = FALSE;\r\n\r\n\tif(m_hWndWinampEQ == NULL || !IsWindow(m_hWndWinampEQ))\r\n\t\tbReady = FALSE;\r\n\r\n\tif(m_hWndWinampPE == NULL || !IsWindow(m_hWndWinampPE))\r\n\t\tbReady = FALSE;\r\n\r\n\tif(m_hWndWinampMB == NULL || !IsWindow(m_hWndWinampMB))\r\n\t\tbReady = FALSE;\r\n\r\n\tif(!bReady)\r\n\t\tInit(TRUE);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nvoid CWinampController::SendCommand(long Code)\r\n{\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, Code, 0);\r\n}\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// General Winamp Stuff\r\n//////////////////////////////////////////////////////////////////////\r\nlong CWinampController::GetVersion()\r\n{\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETVERSION);\r\n}\r\n\r\nlong CWinampController::GetStatus()\r\n{\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_ISPLAYING);\r\n}\r\n\r\nvoid CWinampController::SetStatus(long newVal)\r\n{\r\n\t\r\n\tswitch(newVal)\r\n\t{\r\n\tcase WINAMP_STOPPED:\r\n\t\tSendCommand(WINAMP_STOP);\r\n\t\tbreak;\r\n\tcase WINAMP_PAUSED:\r\n\t\tSendCommand(WINAMP_PAUSE);\r\n\t\tbreak;\r\n\tdefault:\r\n\t\tPlay();\r\n\t\tbreak;\r\n\t}\r\n}\r\n\r\n\r\nvoid CWinampController::NextTrack()\r\n{\r\n\tSendCommand(WINAMP_FASTFWD);\r\n}\r\n\r\nvoid CWinampController::PrevTrack()\r\n{\r\n\tSendCommand(WINAMP_REWIND);\r\n}\r\n\r\nlong CWinampController::GetCurrentPos()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETOUTPUTTIME);\r\n}\r\n\r\nvoid CWinampController::SetCurrentPos(long newVal)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_JUMPTOTIME);\r\n}\r\n\r\nvoid CWinampController::SetVolume(long newVal)\r\n{\r\n\t\r\n\tif(newVal < 0)\r\n\t{\r\n\t\tnewVal = 0;\r\n\t}\r\n\tif(newVal > 255)\r\n\t{\r\n\t\tnewVal = 255;\r\n\t}\r\n\tlong CurrentValue(SendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETVOLUME));\r\n}\r\n\r\nvoid CWinampController::IncreaseVolume()\r\n{\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_VOLUMEUP, 0);\r\n}\r\n\r\nvoid CWinampController::DecreaseVolume()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_VOLUMEDOWN, 0);\r\n}\r\n\r\nlong CWinampController::GetSampleRate()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETINFO);\r\n}\r\n\r\nlong CWinampController::GetBitrate()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,1,IPC_GETINFO);\r\n}\r\n\r\nlong CWinampController::GetChannels()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,2,IPC_GETINFO);\r\n}\r\n\r\nvoid CWinampController::SetPanning(long PanIndex)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,PanIndex,IPC_SETPANNING);\r\n}\r\n\r\nvoid CWinampController::ChangeDirectory(CStdString NewDir)\r\n{\r\n\tif(!NewDir.IsEmpty())\r\n\t{\r\n\t\tCOPYDATASTRUCT cds;\r\n\t\tcds.dwData = IPC_CHDIR;\r\n\t\tcds.lpData = (void *) NewDir.GetBuffer(0);\r\n\t\tcds.cbData = NewDir.GetLength(); // include space for null char\r\n\t\tSendMessage(m_hWndWinamp,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cds);\r\n\t}\r\n}\r\n\r\nCStdString CWinampController::GetSongFileName(long PlayListPos)\r\n{\t\r\n\tCStdString Name = (char *)SendMessage(m_hWndWinamp,WM_WA_IPC,PlayListPos,IPC_GETPLAYLISTFILE);\r\n\treturn Name;\r\n}\r\n\r\nCStdString CWinampController::GetSongFileNameUtf8(long PlayListPos)\r\n{\t\r\n\tCStdStringW FileNameW = (wchar_t *)SendMessage(m_hWndWinamp, WM_WA_IPC, PlayListPos, IPC_GETPLAYLISTFILEW);\r\n\twchar_t Filename[MAX_PATH];\r\n\twcscpy(Filename, FileNameW);\r\n\r\n    std::string fileNameUtf8;\r\n\tUTF::wchartoutf8(Filename, fileNameUtf8);\r\n    \r\n    return CStdString(fileNameUtf8.c_str());\r\n}\r\n\r\nCStdString CWinampController::GetSongTitle(long PlayListPos)\r\n{\r\n\tCStdString Name = (char*)SendMessage(m_hWndWinamp,WM_WA_IPC,PlayListPos,IPC_GETPLAYLISTTITLE);\r\n\treturn Name;\r\n}\r\n\r\nCStdString CWinampController::GetSongTitleUtf8(long PlayListPos)\r\n{\r\n\twchar_t* name = (wchar_t*)SendMessage(m_hWndWinamp,WM_WA_IPC,PlayListPos,IPC_GETPLAYLISTTITLEW);\r\n\r\n\tstd::string sbuffer;\r\n\tUTF::wchartoutf8(name, sbuffer);\r\n    return CStdString(sbuffer.c_str());\r\n}\r\n\r\nCStdString CWinampController::GetCurrentSongFileName()\r\n{\r\n\treturn GetSongFileName(GetPlayListPos());\r\n}\r\n\r\nCStdString CWinampController::GetCurrentSongFileNameUtf8()\r\n{\r\n\treturn GetSongFileNameUtf8(GetPlayListPos());\r\n}\r\n\r\nCStdString CWinampController::GetCurrentSongTitle()\r\n{\r\n\treturn GetSongTitle(GetPlayListPos());\r\n}\r\n\r\nCStdString CWinampController::GetSkinName()\r\n{\r\n\t\r\n\tCStdString Temp;\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,(WPARAM)Temp.GetBuffer(0),IPC_GETSKIN);\r\n\treturn Temp;\r\n}\r\n\r\nvoid CWinampController::SetSkinName(CStdString Name)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,(WPARAM)Name.GetBuffer(0),IPC_SETSKIN);\t\r\n}\r\n\r\nvoid CWinampController::StartPlugIn(CStdString PlugInName)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,(WPARAM)PlugInName.GetBuffer(0),IPC_EXECPLUG);\r\n\r\n}\r\n\r\nvoid CWinampController::ToggleShufflePlay()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_FILE_SHUFFLE, 0);\r\n}\r\n\r\nvoid CWinampController::ToggleRepeatPlay()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_FILE_REPEAT, 0);\r\n}\r\n\r\nvoid CWinampController::Stop()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_STOP, 0);\r\n}\r\n\r\nvoid CWinampController::Pause()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_PAUSE, 0);\r\n}\r\n\r\nvoid CWinampController::FastForward()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_FASTFWD, 0);\r\n}\r\n\r\nvoid CWinampController::Rewind()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_REWIND, 0);\r\n}\r\n\r\nvoid CWinampController::CloseWinamp()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_CLOSE, 0, 0);\r\n}\r\n\r\nvoid CWinampController::SongChange()\r\n{\r\n}\r\n\r\nlong CWinampController::GetCurrentSongLength()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC, 1,IPC_GETOUTPUTTIME);\r\n}\r\n\r\nvoid CWinampController::FastFwd5Secs()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_FFWD5S, 0);\r\n}\r\n\r\nvoid CWinampController::Rewind5Secs()\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp, WM_COMMAND, WINAMP_REW5S, 0);\r\n}\r\n\r\nBOOL CWinampController::GetWinampVisible()\r\n{\r\n\treturn IsWindowVisible(m_hWndWinamp);\r\n}\r\n\r\nvoid CWinampController::SetWinampVisible(BOOL newVal)\r\n{\r\n\tif(newVal)\r\n\t{\r\n\t\tif(!IsWindowVisible(m_hWndWinamp))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinamp, SW_SHOW);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(IsWindowVisible(m_hWndWinamp))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinamp, SW_HIDE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nBOOL CWinampController::GetShuffleStatus()\r\n{\r\n\t\r\n\tif(GetMenuState(GetOptionMenu(), WINAMP_MENU_SHUFFLE, MF_BYCOMMAND) == MF_CHECKED)\r\n\t{\r\n\t\treturn TRUE;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n}\r\n\r\nvoid CWinampController::SetShuffleStatus(BOOL newVal)\r\n{\r\n\t\r\n\tBOOL CurVal = GetShuffleStatus();\r\n\tif(CurVal != newVal)\r\n\t{\r\n\t\tToggleShufflePlay();\r\n\t}\r\n}\r\n\r\nBOOL CWinampController::GetRepeatStatus()\r\n{\r\n\t\r\n\tif(GetMenuState(GetOptionMenu(), WINAMP_MENU_REPEAT, MF_BYCOMMAND) == MF_CHECKED)\r\n\t{\r\n\t\treturn TRUE;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn FALSE;\r\n\t}\r\n}\r\n\r\nvoid CWinampController::SetRepeatStatus(BOOL newVal)\r\n{\r\n\t\r\n\tBOOL CurVal = GetRepeatStatus();\r\n\tif(CurVal != newVal)\r\n\t{\r\n\t\tToggleRepeatPlay();\r\n\t}\r\n}\r\n\r\nHMENU CWinampController::GetOptionMenu()\r\n{\r\n\t\r\n\t// Get System menu handle\r\n\tHMENU hMenuSystem = GetSystemMenu(m_hWndWinamp, 0);\r\n\r\n\t//Get Winamp sub-menu handle\r\n\tHMENU hMenuWinamp = GetSubMenu(hMenuSystem, 0);\r\n\r\n\t//Get Options sub-menu handle\r\n\treturn GetSubMenu(hMenuWinamp, WINAMP_MENU_OPTIONS_POS);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// Playlist Stuff\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nvoid CWinampController::ClearPlaylist()\r\n{\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_DELETE);\r\n}\r\n\r\nlong CWinampController::GetPlayListPos()\r\n{\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETLISTPOS);\r\n}\r\n\r\nvoid CWinampController::SetPlayListPos(long newVal)\r\n{\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETPLAYLISTPOS);\r\n}\r\n\r\nlong CWinampController::GetPlayListCount()\r\n{\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETLISTLENGTH);\r\n}\r\n\r\nBOOL CWinampController::GetPlaylistVisible()\r\n{\r\n\treturn IsWindowVisible(m_hWndWinampPE);\r\n}\r\n\r\nvoid CWinampController::SetPlaylistVisible(BOOL newVal)\r\n{\r\n\t\r\n\tif(newVal)\r\n\t{\r\n\t\tif(!IsWindowVisible(m_hWndWinampPE))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampPE, SW_SHOW);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(IsWindowVisible(m_hWndWinampPE))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampPE, SW_HIDE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CWinampController::DeletePEItem(int Pos)\r\n{\r\n\tMovePEHighlight(Pos);\r\n\tDeletePECurHighlight();\r\n}\r\n\r\nvoid CWinampController::DeletePECurHighlight()\r\n{\r\n\tSendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_DEL_FRM_PE, 0 );\r\n}\r\n\r\nvoid CWinampController::MovePEHighlight(int Pos)\r\n{\r\n\tint PELength = GetPlayListCount();\r\n\r\n\tif(Pos < PELength)\r\n\t{\r\n\t\tSendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_MV_PE_HLT_UP, 0);\r\n\r\n\t\t// Move the selector down to the song to remove\r\n\t\tfor(int i = 0; i < Pos; i++ )\r\n\t\t\tSendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_MV_PE_HLT_DOWN, 0 );\r\n\t}\r\n}\r\n\r\nbool CWinampController::MovePEItem(int curPos, int NewPos)\r\n{\r\n\tint diff = 0;\r\n\r\n\tif(curPos == NewPos)\r\n\t\treturn false;\r\n\r\n\tMovePEHighlight(curPos);\r\n\r\n\tif(curPos > NewPos)\r\n\t{\r\n\t\tdiff = curPos - NewPos;\r\n\r\n\t\tfor(int i = 0; i < diff; i++)\r\n\t\t\tSendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_MV_PE_ITEM_UP, 0 );\r\n\t}\r\n\telse\r\n\t{\r\n\t\tdiff = NewPos - curPos;\r\n\r\n\t\tfor(int i = 0; i < diff; i++)\r\n\t\t\tSendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_MV_PE_ITEM_DOWN, 0 );\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\ntypedef struct \r\n{ \r\n\tchar file[MAX_PATH]; \r\n\tint index; \r\n} fileinfo; \r\n \r\nvoid CWinampController::PLInsertTrack(CStdString strFile, int nPos)\r\n{\r\n/*\tint nCount = GetPlayListCount();\r\n\r\n\tnCount++;\r\n\tEnqueue(strFile);\r\n\tMovePEItem(nCount, nPos);*/\r\n\r\n\tCOPYDATASTRUCT cds; \r\n\tfileinfo f; \r\n\tcds.dwData = IPC_PE_INSERTFILENAME; \r\n\tstrcpy(f.file, strFile); // Path to the new entry \r\n\tf.index=nPos;                 // Position to insert at \r\n\tcds.lpData = (void *)&f; \r\n\tcds.cbData = sizeof(fileinfo); \r\n\t::SendMessage(m_hWndWinampPE,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cds);\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// EQ Stuff\r\n//////////////////////////////////////////////////////////////////////\r\nlong CWinampController::GetEqPosition(long Band)\r\n{\r\n\t\r\n\tif(Band < 0)\r\n\t{\r\n\t\tBand = 0;\r\n\t}\r\n\tif(Band > 9)\r\n\t{\r\n\t\tBand = 9;\r\n\t}\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,Band,IPC_GETEQDATA);\r\n}\r\n\r\nvoid CWinampController::SetEqPosition(long Band, long newVal)\r\n{\r\n\t\r\n\tif(Band < 0)\r\n\t{\r\n\t\tBand = 0;\r\n\t}\r\n\tif(Band > 9)\r\n\t{\r\n\t\tBand = 9;\r\n\t}\r\n\tif(newVal < 0)\r\n\t{\r\n\t\tnewVal = 0;\r\n\t}\r\n\tif(newVal > 63)\r\n\t{\r\n\t\tnewVal = 63;\r\n\t}\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,Band,IPC_GETEQDATA);\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETEQDATA);\r\n}\r\n\r\nlong CWinampController::GetPreAmpPosition()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,10,IPC_GETEQDATA);\r\n\t\r\n}\r\n\r\nvoid CWinampController::SetPreAmpPosition(long newVal)\r\n{\r\n\t\r\n\tif(newVal < 0)\r\n\t{\r\n\t\tnewVal = 0;\r\n\t}\r\n\tif(newVal > 63)\r\n\t{\r\n\t\tnewVal = 63;\r\n\t}\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,10,IPC_GETEQDATA);\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETEQDATA);\r\n}\r\n\r\nBOOL CWinampController::GetEqEnabled()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,11,IPC_GETEQDATA);\r\n}\r\n\r\nvoid CWinampController::SetEqEnabled(BOOL newVal)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,11,IPC_GETEQDATA);\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETEQDATA);\r\n}\r\n\r\nBOOL CWinampController::GetAutoloadEnabled()\r\n{\r\n\t\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,12,IPC_GETEQDATA);\r\n}\r\n\r\nvoid CWinampController::SetAutoloadEnabled(BOOL newVal)\r\n{\r\n\t\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,12,IPC_GETEQDATA);\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,newVal,IPC_SETEQDATA);\r\n}\r\nBOOL CWinampController::GetEqualizerVisible()\r\n{\r\n\t\r\n\treturn IsWindowVisible(m_hWndWinampEQ);\r\n}\r\n\r\nvoid CWinampController::SetEqualizerVisible(BOOL newVal)\r\n{\r\n\t\r\n\tif(newVal)\r\n\t{\r\n\t\tif(!IsWindowVisible(m_hWndWinampEQ))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampEQ, SW_SHOW);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(IsWindowVisible(m_hWndWinampEQ))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampEQ, SW_HIDE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// MB Stuff\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nBOOL CWinampController::GetMiniBrowserVisible()\r\n{\r\n\t\r\n\treturn IsWindowVisible(m_hWndWinampMB);\r\n}\r\n\r\nvoid CWinampController::SetMiniBrowserVisible(BOOL newVal)\r\n{\r\n\t\r\n\tif(newVal)\r\n\t{\r\n\t\tif(!IsWindowVisible(m_hWndWinampMB))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampMB, SW_SHOW);\r\n\t\t}\r\n\t}\r\n\telse\r\n\t{\r\n\t\tif(IsWindowVisible(m_hWndWinampMB))\r\n\t\t{\r\n\t\t\tShowWindow(m_hWndWinampMB, SW_HIDE);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid CWinampController::SetMiniBrowserURL(CStdString strUrl, BOOL bForceOpen)\r\n{\r\n\tchar* lpszUrl = NULL;\r\n\t\r\n\t// Force open the mini-browser window\r\n\tif(bForceOpen)\r\n\t\t::SendMessage(m_hWndWinamp, WM_WA_IPC, NULL, IPC_MBOPEN);\r\n\t\r\n\t//Build the url string to be displayed\r\n\tlpszUrl = new char[strUrl.GetLength()+1];\r\n\t\r\n\tsprintf(lpszUrl, \"%s\", strUrl.c_str());\r\n\t\r\n\t//Make the mini-browser navigate to the URL \r\n\t::SendMessage(m_hWndWinamp,WM_WA_IPC, reinterpret_cast<WPARAM>(lpszUrl), IPC_MBOPENREAL);\r\n\t\r\n\tdelete[] lpszUrl;\r\n}\r\n\r\nBOOL CWinampController::IsInetAvailable()\r\n{\r\n\treturn ::SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_INETAVAILABLE);\r\n}\r\n\r\nvoid CWinampController::JumpToTrack(unsigned int Number)\r\n{\r\n\t\r\n\tPostMessage(m_hWndWinamp,WM_COMMAND,WINAMP_BUTTON4,0);\r\n\tNumber--;\r\n\tPostMessage(m_hWndWinamp,WM_WA_IPC,Number,IPC_SETPLAYLISTPOS);\r\n\tPostMessage(m_hWndWinamp,WM_COMMAND,WINAMP_BUTTON2,0);\r\n}\r\n\r\nBOOL CWinampController::GetWinampStats(WA_STATS& stats)\r\n{\r\n\tCStdString strVal, strTemp;\r\n\tint nPos;\r\n\r\n\t// Get the data\r\n\tchar buffer[MAX_PATH];\r\n\tchar buffer2[MAX_PATH];\r\n\tGetWindowsDirectory(buffer, MAX_PATH);\r\n\tstrcat(buffer, \"\\\\winamp.ini\");\r\n\r\n\tDWORD dwRes = GetPrivateProfileString(\"WinampReg\", \"Stats\",\tNULL, buffer2, MAX_PATH, buffer);\r\n\t\r\n\tif(dwRes <= 0)\r\n\t\treturn FALSE;\r\n\r\n\tstrTemp = buffer2;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n\t\tstats.nWinampRuns =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n\t//\tstats.tRunning =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n\t//\tstats.tRunningMB =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n//\t\tstats.tRunningNoneMin =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n\t//\tstats.tRunningPlay =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\tnPos = strTemp.Find(',');\r\n\tif(nPos > 0)\r\n\t{\r\n\t\tstrVal = strTemp.Left(nPos);\r\n//\t\tstats.tRunningPlayNonMin =\tstrtoul(strVal.GetBuffer(0), NULL,16);\r\n\t\tstrTemp = strTemp.Mid(nPos+1);\r\n\t}\r\n\telse \r\n\t\treturn FALSE;\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nCStdString CWinampController::GetWinampDir()\r\n{\r\n\tPRINTF(DEBUG_FLOW, \"CWinampController::GetWinampDir\", \"Getting Winamp Dir.\");\r\n\tif(!m_strWinampDir.IsEmpty())\r\n\t\treturn m_strWinampDir;\r\n\r\n\tchar filename[512];\r\n\tCStdString Path;\r\n\tGetModuleFileName(NULL,filename,sizeof(filename));\r\n\tPath = filename;\r\n\r\n\tint pos = Path.ReverseFind('\\\\');\r\n\tif(pos > 0)\r\n\t{\r\n\t\t// Get Winamp Directory\r\n\t\tm_strWinampDir = Path.Left(pos + 1);\r\n\t\treturn m_strWinampDir;\r\n\t}\r\n\telse\r\n\t\tPRINTF(DEBUG_ERROR, \"CWinampController::GetWinampDir\", \"Failed to Get Winamp Dir.\");\r\n\r\n\treturn \"\";\r\n}\r\n\r\nvoid CWinampController::SetVolume(int nVolume)\r\n{\r\n\tif(nVolume < 0 || nVolume > 255)\r\n\t\treturn;\r\n\r\n\tSendMessage(m_hWndWinamp,WM_WA_IPC,nVolume,IPC_SETVOLUME);\r\n}\r\n\r\nCStdString CWinampController::GetPlayerVersion()\r\n{\r\n\tif(m_strVersionString.IsEmpty())\r\n\t{\r\n\t\tCStdString Text;\r\n\t\t\r\n\t\tLRESULT version = SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETVERSION);\r\n\t\t\r\n\t\tText.Format(\"%x\", SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETVERSION));\r\n\t\tm_strVersionString.Format(\"%s.%s%s\", Text.Left(1).c_str(), Text.Mid(2, 1).c_str(), Text.Mid(3).c_str());\r\n\t}\r\n\r\n\treturn m_strVersionString;\r\n}\r\n\r\nBOOL CWinampController::Enqueue(CStdString strFileName)\r\n{\r\n\tCOPYDATASTRUCT cds;\r\n\tcds.dwData = IPC_PLAYFILE;\r\n\tcds.lpData = (void *)strFileName.GetBuffer(0);\r\n\tcds.cbData = strlen((char *) cds.lpData) + 1; // include space for null char\r\n\r\n\tint nRes = ::SendMessage(m_hWndWinamp, WM_COPYDATA,1,(LPARAM)&cds);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CWinampController::Play(CStdString strFileName /*= \"\"*/, BOOL bKeepList /* = TRUE */)\r\n{\r\n\tif(!strFileName.IsEmpty())\r\n\t{\r\n\t\tif(!bKeepList)\r\n\t\t{\r\n\t\t\tClearPlaylist();\r\n\t\t\tEnqueue(strFileName);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tPLInsertTrack(strFileName, 0);\r\n\t\t}\r\n\t}\r\n\r\n\t::SendMessage(m_hWndWinamp, WM_COMMAND,WINAMP_BUTTON4, 0);\r\n\t::SendMessage(m_hWndWinamp, WM_WA_IPC,0,IPC_STARTPLAY);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nCStdString CWinampController::GetFileNameFromPos(int nPos)\r\n{\r\n\t// What are we playing?\r\n\tCStdString Text;\r\n\tchar buffer[MAX_PATH];\r\n\tmemset(buffer, 0, MAX_PATH);\r\n\tchar* p = buffer;\r\n\tp = reinterpret_cast<char*>(SendMessage(m_hWndWinamp,WM_WA_IPC,nPos,IPC_GETPLAYLISTFILE));\r\n\tText = p;\r\n\treturn Text;\r\n}\r\n\r\nBOOL CWinampController::IsStopped()\r\n{\r\n\treturn (GetWinampState() == WA_STATE_STOP);\r\n}\r\n\r\nBOOL CWinampController::IsPlaying()\r\n{\r\n\treturn (GetWinampState() == WA_STATE_PLAY);\r\n}\r\n\r\nBOOL CWinampController::IsPaused()\r\n{\r\n\treturn (GetWinampState() == WA_STATE_PAUSE);\r\n}\r\n\r\n// Returned in SECONDS\r\nint\tCWinampController::GetTrackLength()\r\n{\r\n\tint nTrackLength = SendMessage(m_hWndWinamp,WM_WA_IPC,1,IPC_GETOUTPUTTIME);\r\n\t\r\n\treturn nTrackLength;\r\n}\r\n\r\n//Returned in Milliseconds\r\nint\tCWinampController::GetPlayingTime()\r\n{\r\n\treturn SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETOUTPUTTIME);\r\n}\r\n\r\nCStdString CWinampController::GetCurrTrackPath()\r\n{\r\n\tint nPos = SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_GETLISTPOS);\r\n\treturn GetFileNameFromPos(nPos);\r\n}\r\n\r\nint CWinampController::GetWinampState()\r\n{\r\n\t// Are actually playing?\r\n\tint ret = SendMessage(m_hWndWinamp,WM_WA_IPC,0,IPC_ISPLAYING);\r\n\tif(ret == 1)\r\n\t\treturn WA_STATE_PLAY;\r\n\telse if(ret == 3)\r\n\t\treturn WA_STATE_PAUSE;\r\n\telse if(ret == 0)\r\n\t\treturn WA_STATE_STOP;\r\n\r\n\treturn -1;\r\n}\r\n\r\nBOOL CWinampController::IsPEWindowWinshade()\r\n{\r\n\tRECT rcPEWnd;\r\n\t\r\n\t::GetWindowRect(m_hWndWinampPE, &rcPEWnd);\r\n\r\n\tif((rcPEWnd.bottom - rcPEWnd.top) < 116)\r\n\t\treturn TRUE;\r\n\t\r\n\treturn FALSE;\r\n}\r\n\r\nint CWinampController::GetVolume()\r\n{\r\n\treturn -1;\r\n}\r\n\r\n\r\nCStdString CWinampController::GetCurrentSongMetadataUtf8(char* MetaData)\r\n{\r\n\tCStdStringW FileNameW = (wchar_t *)SendMessage(m_hWndWinamp, WM_WA_IPC, \r\n\t\tGetPlayListPos(), IPC_GETPLAYLISTFILEW);\r\n\twchar_t Filename[MAX_PATH];\r\n\twcscpy(Filename, FileNameW);\r\n\r\n    wchar_t buffer[1024];\r\n\tmemset(buffer, 0, sizeof(buffer));\r\n\r\n    extendedFileInfoStructW Info;\r\n\tInfo.ret = buffer;\r\n\tInfo.retlen = 1024;\r\n\tInfo.filename = Filename;\r\n\tstd::wstring wMeta;\r\n\tUTF::utf8towstring(MetaData, wMeta);\r\n\twchar_t* metadup = _wcsdup(wMeta.c_str());\r\n\tInfo.metadata = metadup;\r\n    LRESULT lRet = SendMessage(m_hWndWinamp, WM_WA_IPC, (WPARAM)&Info, IPC_GET_EXTENDED_FILE_INFOW);\r\n\tfree(metadup);\r\n    if (lRet != 1)\r\n    {\r\n        PRINTF(DEBUG_DETAIL, \r\n              \"CWinampController::GetCurrentSongMetadata\", \r\n              \"FAILED - metadata '%s', ret is %d\", \r\n              MetaData,lRet);\r\n        return CStdString();\r\n    }\r\n\tstd::string sbuffer;\r\n\tUTF::wchartoutf8(buffer, sbuffer);\r\n    return CStdString(sbuffer.c_str());\r\n}\r\n\r\n// Only works for Winamp 2.90 upwards\r\n// Not using Media Library\r\nCStdString CWinampController::GetCurrentSongMetadata(char* MetaData)\r\n{\r\n    char                    buffer[1024];\r\n    char                    Filename[MAX_PATH];\r\n    extendedFileInfoStruct  Info;\r\n    LRESULT                 lRet = 0;\r\n\r\n    memset(buffer, 0, sizeof(buffer));\r\n    strcpy(Filename, GetCurrentSongFileName());\r\n\r\n    Info.ret = buffer;\r\n    Info.retlen = sizeof(buffer);\r\n    Info.filename = Filename;\r\n    Info.metadata = strdup(MetaData);\r\n\r\n    lRet = SendMessage(m_hWndWinamp,WM_WA_IPC, (WPARAM)&Info, IPC_GET_EXTENDED_FILE_INFO);\r\n\tfree((void*)Info.metadata);\r\n    if (lRet != 1)\r\n    {\r\n        PRINTF(DEBUG_DETAIL, \r\n              \"CWinampController::GetCurrentSongMetadata\", \r\n              \"FAILED - metadata '%s', ret is %d\", \r\n              MetaData,lRet);\r\n    }\r\n\r\n    return CStdString(buffer);\r\n}\r\n\r\n// Media Library version\r\nBOOL CWinampController::GetCurrentSongInfo(SongInfo& info)\r\n{\r\n\titemRecord\trec;\r\n\tchar        Filename[MAX_PATH];\r\n\tint\t\t\tResult = 0;\r\n\tBOOL\t\tbRet = FALSE;\t\t\t\r\n\r\n\tmemset(&rec, 0, sizeof(itemRecord));\r\n\tstrcpy(Filename, GetCurrentSongFileName());\r\n\trec.filename = Filename;\r\n\r\n\tResult = ::SendMessage(m_hWndWinampML,WM_ML_IPC,(WPARAM)&rec,ML_IPC_GETFILEINFO);\r\n\r\n\tif(Result != 0)\r\n\t{\r\n\t\t// Do Stuff\r\n\t\tinfo.strAlbum\t\t= rec.album;\r\n\t\tinfo.strArtist\t\t= rec.artist;\r\n\t\tinfo.strComment\t\t= rec.comment;\r\n\t\tinfo.strGenre\t\t= rec.genre;\r\n\t\tinfo.strTitle\t\t= rec.title;\r\n\t\tinfo.nLength\t\t= rec.length;\r\n\t\tinfo.nTrackNo\t\t= rec.track;\r\n\t\tinfo.nYear\t\t\t= rec.year;\r\n\t\tinfo.strFileName\t= Filename;\r\n\t\t\r\n\t\tResult = ::SendMessage(m_hWndWinampML,WM_ML_IPC,(WPARAM)&rec,ML_IPC_FREEFILEINFO);\r\n\t\tbRet = TRUE;\r\n\t}\r\n\t\r\n\treturn bRet;\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/winamp/WinampController.h",
    "content": "/*##############################################\r\n##\r\n## Module\t\t\t\t: CWinampController\r\n## Description\t: This class takes total control\r\n##\t\t\t\t\t\t\t\tof Winamp 1.x - 2.x\r\n##\r\n## Author(s)\t\t: Spib\r\n##\r\n## Modifications\r\n##\r\n##############################################*/\r\n#pragma once\r\n\r\n#include \"Gen.h\"\r\n#include \"wa_ipc.h\"\r\n#include \"WinampCmd.h\"\r\n#include \"ml.h\"\r\n\r\n#define WINAMP_MENU_OPTIONS_POS\t\t11\r\n#define WINAMP_MENU_REPEAT\t\t\t40022\r\n#define WINAMP_MENU_SHUFFLE\t\t\t40023\r\n#define WINAMP_MAIN_WINDOW          40258\r\n\r\n#define WINAMP_MV_PE_HLT_UP\t\t\t105825\r\n#define WINAMP_MV_PE_HLT_DOWN\t\t105826\r\n\r\n#define WINAMP_DEL_FRM_PE\t\t\t66570\r\n#define WINAMP_MV_PE_ITEM_DOWN\t\t105752\r\n#define WINAMP_MV_PE_ITEM_UP\t\t105751\r\n\r\n#define WINAMP_PE_SORT_TITLE\t\t40209\r\n#define WINAMP_PE_SORT_FNAME\t\t40210\r\n#define WINAMP_PE_SORT_FNAME_PATH\t40211\r\n\r\n#define WA_STATE_PLAY\t100\r\n#define WA_STATE_PAUSE\t101\r\n#define WA_STATE_STOP\t102\r\n\r\n//PE Stuff\r\n#define IPC_PE_GETCURINDEX\t\t\t100 \r\n#define IPC_PE_GETINDEXTOTAL\t\t101 \r\n#define IPC_PE_GETINDEXINFO\t\t\t102 \r\n#define IPC_PE_GETINDEXINFORESULT\t103 \r\n#define IPC_PE_DELETEINDEX\t\t\t104 \r\n#define IPC_PE_SWAPINDEX\t\t\t105 \r\n#define IPC_PE_INSERTFILENAME\t\t106 \r\n#define IPC_PE_GETDIRTY\t\t\t\t107 \r\n#define IPC_PE_SETCLEAN\t\t\t\t108 \r\n\r\ntypedef struct\r\n{\r\n\tCStdString\tstrArtist;\r\n\tCStdString\tstrAlbumArtist;\r\n\tCStdString\tstrAlbum;\r\n\tCStdString\tstrComment;\r\n\tCStdString\tstrGenre;\r\n\tCStdString\tstrTitle;\r\n\tCStdString\tstrFileName;\r\n\tint\t\t\tnYear;\r\n\tint\t\t\tnLength;\r\n\tint\t\t\tnTrackNo;\r\n}SongInfo;\r\n\r\ntypedef struct\r\n{\r\n\tint nWinampRuns;\t\t\t// How many times Winamp has been run.\r\n\tCComDATE tRunning;\t\t\t// How long Winamp has been running. \r\n\tCComDATE tRunningMB;\t\t\t// How long Winamp has been running with the Minibrowser window open. \r\n\tCComDATE tRunningNoneMin;\t\t// How long Winamp has been running in a non minimized state. \r\n\tCComDATE tRunningPlay;\t\t\t// How long Winamp has been running and playing audio files. \r\n\tCComDATE tRunningPlayNonMin;\t// How long Winamp has been running, playing, in a non minimized state.\r\n}WA_STATS;\r\n\r\nclass CWinampController  \r\n{\r\npublic:\r\n\tCWinampController();\r\n\tvirtual ~CWinampController();\r\n\r\n\tBOOL\tInit(BOOL bStartWinamp, HWND Winamp = NULL, HWND WinampML = NULL);\r\n\r\n\tHWND\tGetWinampWnd(){return m_hWndWinamp;}\r\n\tHWND    GetPEWnd(){return m_hWndWinampPE;}\r\n\tBOOL\tGetWinampStats(WA_STATS& stats);\r\n\r\n\t//Main Window - Operation\r\n\tBOOL\tPlay(CStdString strFile = \"\", BOOL bKeepList = FALSE);\r\n\tBOOL\tEnqueue(CStdString strFile);\r\n\tvoid\tStop();\r\n\tvoid\tPause();\r\n\tvoid\tFastForward();\r\n\tvoid\tNextTrack();\r\n\tvoid\tPrevTrack();\r\n\tvoid\tRewind();\r\n\tvoid\tFastFwd5Secs();\r\n\tvoid\tRewind5Secs();\r\n\tvoid\tCloseWinamp();\r\n\tvoid\tRestartWinamp();\r\n\tvoid\tIncreaseVolume();\r\n\tvoid\tDecreaseVolume();\r\n\r\n\tBOOL\tGetShuffleStatus();\r\n\tvoid\tSetShuffleStatus(BOOL newVal);\r\n\tBOOL\tGetRepeatStatus();\r\n\tvoid\tSetRepeatStatus(BOOL newVal);\r\n\tHMENU\tGetOptionMenu();\r\n\tlong\tGetVersion();\r\n\tlong\tGetStatus();\r\n\tvoid\tSetStatus(long newVal);\r\n\tlong\tGetCurrentPos();\r\n\tvoid\tSetCurrentPos(long newVal);\r\n\tvoid\tSetVolume(long newVal);\r\n\tvoid\tSetPanning(long PanIndex);\r\n\tvoid\tChangeDirectory(CStdString NewDir);\r\n\tCStdString GetSkinName();\r\n\tvoid\tSetSkinName(CStdString Name);\r\n\tvoid\tStartPlugIn(CStdString PlugInName);\r\n\tvoid\tToggleShufflePlay();\r\n\tvoid\tToggleRepeatPlay();\r\n\tvoid\tSongChange();\r\n\tlong\tGetCurrentSongLength();\r\n\tBOOL\tGetWinampVisible();\r\n\tvoid\tSetWinampVisible(BOOL newVal);\r\n\r\n\t//Song Information\r\n\tlong\tGetSampleRate();\r\n\tlong\tGetBitrate();\r\n\tlong\tGetChannels();\r\n\tCStdString GetSongFileName(long PlayListPos);\r\n    CStdString GetSongFileNameUtf8(long PlayListPos);\r\n\tCStdString GetSongTitle(long PlayListPos);\r\n    CStdString GetSongTitleUtf8(long PlayListPos);\r\n    CStdString GetSongMetaData(CStdString MetaData, long PlayListPos);\r\n\tCStdString GetCurrentSongFileName();\r\n    CStdString GetCurrentSongFileNameUtf8();\r\n    CStdString GetCurrentSongTitle();\r\n\tCStdString GetCurrentSongMetadata(char* MetaData);\r\n\tCStdString GetCurrentSongMetadataUtf8(char* MetaData);\r\n\tBOOL\t\tGetCurrentSongInfo(SongInfo& Info);\r\n\r\n\t//Playlist Functions\r\n\tvoid\tClearPlaylist();\r\n\tlong\tGetPlayListPos();\r\n\tvoid\tSetPlayListPos(long newVal);\r\n\tlong\tGetPlayListCount();\r\n\tvoid\tDeletePEItem(int Pos);\r\n\tvoid\tDeletePECurHighlight();\r\n\tvoid\tMovePEHighlight(int Pos);\r\n\tbool\tMovePEItem(int curPos, int NewPos);\r\n\tBOOL\tGetPlaylistVisible();\r\n\tvoid\tSetPlaylistVisible(BOOL newVal);\r\n\tvoid\tJumpToTrack(unsigned int Number);\r\n\tvoid\tSortByName(){SendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_PE_SORT_TITLE,0);}\r\n\tvoid\tSortByFName(){SendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_PE_SORT_FNAME,0);}\r\n\tvoid\tSortByFNamePath(){SendMessage(m_hWndWinampPE, WM_COMMAND, WINAMP_PE_SORT_FNAME_PATH,0);}\r\n\tvoid\tPLInsertTrack(CStdString strFile, int nPos);\r\n\tBOOL\tIsPEWindowWinshade();\r\n\t\r\n\t// Equaliser Functions\r\n\tlong\tGetEqPosition(long Band);\r\n\tvoid\tSetEqPosition(long Band, long newVal);\r\n\tlong\tGetPreAmpPosition();\r\n\tvoid\tSetPreAmpPosition(long newVal);\r\n\tBOOL\tGetEqualizerVisible();\r\n\tvoid\tSetEqualizerVisible(BOOL newVal);\r\n\tBOOL\tGetEqEnabled();\r\n\tvoid\tSetEqEnabled(BOOL newVal);\r\n\tBOOL\tGetAutoloadEnabled();\r\n\tvoid\tSetAutoloadEnabled(BOOL newVal);\r\n\r\n\t//Minibrowser stuff\r\n\tBOOL\tGetMiniBrowserVisible();\r\n\tvoid\tSetMiniBrowserVisible(BOOL newVal);\r\n\tvoid\tSetMiniBrowserURL(CStdString strUrl, BOOL bForceOpen);\r\n\tBOOL  IsInetAvailable();\r\n\r\n\tint\t\tGetTrackLength();\r\n\tint\t\tGetPlayingTime();\r\n\tCStdString GetCurrTrackPath();\r\n\tint\t\tGetWinampState();\r\n\tCStdString GetWinampDir();\r\n\r\n\tBOOL\tIsPlaying();\r\n\tBOOL\tIsPaused();\r\n\tBOOL\tIsStopped();\r\n\tCStdString\tGetPlayerVersion();\r\n\tvoid\tSetVolume(int nValue);\r\n\tint     GetVolume();\r\n\tCStdString GetFileNameFromPos(int nPos);\r\n\t\r\nprotected:\r\n\tBOOL\tWindowsReady();\r\n\tvoid\tSendCommand(long command);\r\n\t\r\n\tHWND\tm_hWndWinamp;\r\n\tHWND\tm_hWndWinampEQ;\r\n\tHWND\tm_hWndWinampPE;\r\n\tHWND\tm_hWndWinampMB;\r\n\tHWND\tm_hWndWinampML;\r\n\tint\t\tm_nVolume;\r\n\tCStdString\tm_strVersionString;\t\t// Winamp Version String\r\n\tCStdString\tm_strWinampDir;\t\t\t// Winamp Directory\r\n};"
  },
  {
    "path": "plugins/winamp/WinampScrobbler.cpp",
    "content": "// WinampScrobbler.cpp: implementation of the CWinampScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#include \"stdafx.h\"\r\n#include \"WinampScrobbler.h\"\r\n#include \"WinampBootstrap.h\"\r\n#include \"wa_ipc.h\"\r\n\r\n#define WA_STATE_CHANGE 0x0000029A\r\n#define IPC_FF_FIRST 2000\r\n#define IPC_FF_ISMAINWND IPC_FF_FIRST + 4\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// Construction/Destruction\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nCWinampScrobbler::CWinampScrobbler()\r\n{\r\n\tm_hWndWinamp\t\t\t\t\t= NULL;\r\n\tm_dwLastPlay\t\t\t\t\t= 0;\r\n}\r\n\r\nCWinampScrobbler::~CWinampScrobbler()\r\n{\r\n}\r\n\r\nBOOL\tCWinampScrobbler::StartScrobbling(HINSTANCE hInstance, \r\n\t\t\t\t\t\t\t\t\t\t  HWND hWndWinamp, \r\n\t\t\t\t\t\t\t\t\t\t  HWND hWndWinampML, \r\n\t\t\t\t\t\t\t\t\t\t  CStdString strWorkingDir)\r\n{\r\n\tif ( ( hWndWinamp != NULL) &&\r\n\t\t   ( ::IsWindow(hWndWinamp)) )\r\n\t{\r\n\t\tm_hWndWinamp\t\t= hWndWinamp;\r\n\t\tm_hWndWinampML\t\t= hWndWinampML;\r\n\t\t\r\n\t\tm_Controller.Init(FALSE, hWndWinamp, hWndWinampML);\r\n\t\t\r\n\t\tBOOL bRet =  CScrobbler::StartScrobbling(strWorkingDir, hInstance);\r\n\r\n        EnumThreadWindows( GetCurrentThreadId(), CWinampScrobbler::enumWndProc, (LPARAM)this );\r\n\r\n        if( m_bootstrap.bootStrapRequired() )\r\n        {\r\n            PRINTF(DEBUG_FLOW,\r\n                \"CWinampScrobbler::StartScrobbling\", \"Bootstrap is required\" );\r\n\r\n            m_bootstrap.setParentHwnd( m_mainWinAmpWnd );\r\n            m_bootstrap.sethWndWinampML( m_hWndWinampML );\r\n            m_bootstrap.setScrobSub( m_Submitter );\r\n            m_bootstrap.setModuleHandle( hInstance );\r\n            m_bootstrap.startBootStrap();\r\n        }\r\n        \r\n\r\n\t\treturn bRet;\r\n\t}\r\n\r\n\treturn FALSE;\r\n} \r\n\r\n/*##############################################\r\n##\r\n## Module\t\t\t\t: CWinampScrobbler\r\n## Function\t\t\t: WinampPEMessage\r\n## Description\t: Winamp Playlist Editor Window\r\n##                hook to catch playback events\r\n##\r\n## Author(s)\t\t: Spib\r\n##\r\n## Parameters\t\t: N/A\r\n## Return\t\t\t\t: N/A\r\n##\r\n##############################################*/\r\nBOOL CWinampScrobbler::WinampPEMessage(UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n    // This function is only called in Winamp versions < 5\r\n\tif(message == WM_USER)\r\n\t{\r\n\t\tif(wParam == WA_STATE_CHANGE)\r\n\t\t{\r\n\t\t\tint nType = HIWORD(lParam);\r\n\t\t\tint nTrack = LOWORD(lParam);\r\n\t\t\tint nState = m_Controller.GetWinampState();\r\n\r\n            // Ignore the double issue play message\r\n\t\t\t// This is just some undocumented number found by experimenting.\r\n\t\t\tif(nType != 16384)\r\n\t\t\t\treturn TRUE;\r\n\r\n\t\t\tif(nState == WA_STATE_PLAY)\r\n\t\t\t{\r\n\t\t\t\tDWORD dwNow = GetTickCount();\r\n\t\t\t\t\r\n\t\t\t\t// Winamp Sends two quick song change notifications so \r\n\t\t\t\t// here we check if the last notification arrived less than\r\n\t\t\t\t// 400 milliseconds after the last in which case we ignore it.\r\n\t\t\t\tif((dwNow - m_dwLastPlay) < 400)\r\n\t\t\t\t{\r\n\t\t\t\t\t// Ignore second notifcation\r\n\t\t\t\t\tPRINTF(DEBUG_DETAIL, \"CWinampScrobbler::WinampPEMessage\", \"Duplicate notification arrived - Now %d, Then %d\", dwNow, m_dwLastPlay);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tm_dwLastPlay = dwNow;\r\n\r\n\t\t\t\t\t// Signal a track play without blocking\r\n\t\t\t\t\tm_bTrackPlayFlag = TRUE;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CWinampScrobbler::WinampMessage(UINT message, WPARAM wParam, LPARAM lParam)\r\n{\r\n    if ( message == WM_WA_IPC )\r\n    {\r\n        // We don't want to look for IPC_PLAYING_FILEW as it's only emitted for\r\n        // the Winamp versions after Unicode support was introduced (5.x sthg)\r\n        if ( lParam == IPC_PLAYING_FILE )\r\n        {\r\n            // Signal a track play without blocking\r\n            m_bTrackPlayFlag = TRUE;\r\n            m_dwLastPlay = GetTickCount();\r\n        }\r\n    }\r\n    return TRUE;\r\n}\r\n\r\nCStdString CWinampScrobbler::GetPlayerVersion()\r\n{\r\n\tCStdString strTemp;\r\n\tstrTemp.Format(\"Winamp Version %s\", m_Controller.GetPlayerVersion().c_str());\r\n\treturn strTemp;\r\n}\r\n\r\n\r\nBOOL CWinampScrobbler::GetCurrentSong(SONG_INFO* pSong, bool utf8)\r\n{\r\n\tif(pSong != NULL)\r\n    {\r\n        // There is a bug where Winamp sometimes mixes up the wrong artist name with the correct\r\n        // track title. In an attempt to prevent this, we sanity check the data returned from\r\n        // GetSongMetadata against the data returned by GetSongTitle (inside SanityCheckMetadata),\r\n        // and if they differ, we retry the call up to 5 times.\r\n        bool winampIsSane = false;\r\n        int cnt = 0;\r\n        while ( !winampIsSane && cnt++ < 5 )\r\n        {\r\n            if ( utf8 )\r\n            {\r\n                PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetCurrentSong\", \"Trying to get UTF8 data...\");\r\n                GetSongMetaDataUtf8(pSong);\r\n            }\r\n            else\r\n            {\r\n                PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetCurrentSong\", \"Getting ANSI data...\");                    \r\n                GetSongMetaData(pSong);\r\n            }\r\n    \r\n            bool bInfoOk = strlen(pSong->m_strArtist) > 0 && strlen(pSong->m_strTrack) > 0;\r\n\r\n            // Early out if we didn't get any metadata\r\n            if ( !bInfoOk )\r\n            {\r\n                PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetCurrentSong\", \"Failed getting metadata...\");\r\n                return FALSE;\r\n            }\r\n        \r\n            winampIsSane = SanityCheckMetadata(pSong, utf8);\r\n        }\r\n\r\n        // Workaround for when the -1 or -1000 bug hits\r\n        if (SupportedFileType(pSong->m_strFileName)) // ugly, done twice\r\n        {\r\n            int count = 0;\r\n            while (pSong->m_nLength < 0 && count < 10) \r\n            {\r\n                PRINTF(DEBUG_ERROR_NC, \"CWinampScrobbler::GetCurrentSong\",\r\n                    \"Length of %d returned, retry attempt %d.\", pSong->m_nLength, count );\r\n\r\n                ::Sleep(100);            \r\n                pSong->m_nLength = m_Controller.GetCurrentSongLength();\r\n                \r\n                count++;\r\n            }\r\n            \r\n            if (pSong->m_nLength < 0)\r\n            {\r\n                PRINTF(DEBUG_ERROR_NC, \"CWinampScrobbler::GetCurrentSong\",\r\n                    \"Still -1, fudging to 31s.\");\r\n                pSong->m_nLength = 31;\r\n            }\r\n        }\r\n\r\n    }\r\n    else\r\n        PRINTF(DEBUG_DETAIL, \"CWinampScrobbler::GetSongInfo\", \"Invalid Song Pointer\");\r\n\r\n    return TRUE;\r\n}\r\n\r\n\r\nvoid CWinampScrobbler::GetSongMetaDataUtf8(SONG_INFO* pSong)\r\n{\r\n    CStdString artist = m_Controller.GetCurrentSongMetadataUtf8(\"artist\");\r\n\tCStdString albumArtist = m_Controller.GetCurrentSongMetadataUtf8(\"albumartist\");\r\n\tCStdString title = m_Controller.GetCurrentSongMetadataUtf8(\"title\");\r\n\tCStdString album = m_Controller.GetCurrentSongMetadataUtf8(\"album\");\r\n\tCStdString fileName = m_Controller.GetCurrentSongFileNameUtf8();\r\n\r\n    strncpy(pSong->m_strArtist, artist, sizeof(pSong->m_strArtist));\r\n\tstrncpy(pSong->m_strAlbumArtist, albumArtist, sizeof(pSong->m_strAlbumArtist));\r\n    strncpy(pSong->m_strTrack, title, sizeof(pSong->m_strTrack));\r\n\tstrncpy(pSong->m_strAlbum, album, sizeof(pSong->m_strAlbum));\r\n\tstrncpy(pSong->m_strFileName, fileName, sizeof(pSong->m_strFileName));\r\n\r\n    pSong->m_nLength = m_Controller.GetCurrentSongLength();\r\n}\r\n\r\nvoid CWinampScrobbler::GetSongMetaData(SONG_INFO* pSong)\r\n{\r\n\tSongInfo info;\r\n\tif(m_Controller.GetCurrentSongInfo(info))\r\n\t{\r\n        PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetSongMetaData\", \"Got metadata from ML\");\r\n\r\n\t\tstrncpy(pSong->m_strArtist, \r\n            info.strArtist,\r\n            sizeof(pSong->m_strArtist));\r\n\t\tstrncpy(pSong->m_strAlbumArtist, \r\n            info.strAlbumArtist,\r\n            sizeof(pSong->m_strAlbumArtist));\r\n\t\tstrncpy(pSong->m_strTrack, \r\n            info.strTitle,\r\n            sizeof(pSong->m_strTrack));\r\n\t\tstrncpy(pSong->m_strAlbum, \r\n            info.strAlbum,\r\n            sizeof(pSong->m_strAlbum));\r\n\t\tstrncpy(pSong->m_strGenre, \r\n            info.strGenre,\r\n            sizeof(pSong->m_strGenre));\r\n\t\tstrncpy(pSong->m_strComment, \r\n            info.strComment,\r\n            sizeof(pSong->m_strComment));\r\n\t\tstrncpy(pSong->m_strFileName, \r\n            info.strFileName,\r\n            sizeof(pSong->m_strFileName));\r\n\r\n\t\tpSong->m_nLength\t= info.nLength;\r\n\t\tpSong->m_nTrackNo\t= info.nTrackNo;\r\n\t\tpSong->m_nYear\t\t= info.nYear;\r\n\t\t\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// Winamp 5 or Winamp 2.90 onwards.\r\n\t\tCStdString artist = m_Controller.GetCurrentSongMetadata(\"artist\");\r\n\t\tstrncpy(pSong->m_strArtist, artist, sizeof(pSong->m_strArtist));\r\n\r\n\t\tCStdString albumArtist = m_Controller.GetCurrentSongMetadata(\"albumartist\");\r\n\t\tstrncpy(pSong->m_strAlbumArtist, albumArtist, sizeof(pSong->m_strAlbumArtist));\r\n\r\n\t\tCStdString title = m_Controller.GetCurrentSongMetadata(\"title\");\r\n\t\tstrncpy(pSong->m_strTrack, title, sizeof(pSong->m_strTrack));\r\n\r\n\t\tCStdString album = m_Controller.GetCurrentSongMetadata(\"album\");\r\n\t\tstrncpy(pSong->m_strAlbum, album, sizeof(pSong->m_strAlbum));\r\n\r\n\t\tCStdString fileName = m_Controller.GetCurrentSongFileName();\r\n\t\tstrncpy(pSong->m_strFileName, fileName, sizeof(pSong->m_strFileName));\r\n\r\n\t\tpSong->m_nLength = m_Controller.GetCurrentSongLength();\r\n\r\n        PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetSongMetaData\", \"Got metadata not using ML\");\r\n\t}\r\n\t\r\n    bool bInfoOk = strlen(pSong->m_strArtist) > 0 && strlen(pSong->m_strTrack) > 0;\r\n        \r\n    if(!bInfoOk && m_bUseNowPlaying)\r\n    {\r\n        PRINTF(DEBUG_INFO, \"CWinampScrobbler::GetSongMetaData\", \"Metadata incomplete, using title bar\");\r\n\r\n\t\t// Winamp 2.x\r\n        CStdString strTemp = m_Controller.GetCurrentSongTitle();\r\n\t\tint nPos = strTemp.Find(\" - \");\r\n\t\t\r\n\t\tif (nPos != -1) \r\n\t\t{\r\n\t\t\tstrncpy(pSong->m_strArtist, strTemp.Left(nPos), SONG_INFO_FIELD_SIZE);\r\n\r\n\t\t\tif (strlen(pSong->m_strArtist) > 0) \r\n\t\t\t\tnPos = 3; \r\n\t\t\telse \r\n\t\t\t\tnPos = 0;\r\n\r\n\t\t\tstrncpy(pSong->m_strTrack, \r\n            strTemp.Right(strTemp.GetLength() - nPos - strlen(pSong->m_strArtist)),\r\n                SONG_INFO_FIELD_SIZE);\r\n        }\r\n\t}\r\n}\r\n\r\nbool CWinampScrobbler::SanityCheckMetadata(SONG_INFO* pSong, bool utf8)\r\n{\r\n    // Compare the retrieved metadata to the playlist title. If the artist name\r\n    // isn't found in the playlist title, it's likely that we got the wrong\r\n    // artist name in the metadata.\r\n\r\n    CStdString title;\r\n    if ( utf8 )\r\n    {\r\n        title = m_Controller.GetSongTitleUtf8( m_Controller.GetPlayListPos() );\r\n    }\r\n    else\r\n    {\r\n        title = m_Controller.GetSongTitle( m_Controller.GetPlayListPos() );\r\n    }\r\n    \r\n    // If we failed getting anything we can't really sanity check\r\n    if ( title.IsEmpty() )\r\n    {\r\n        PRINTF(DEBUG_ERROR_NC, \"CWinampScrobbler::SanityCheckMetadata\", \"Couldn't get song title.\");\r\n        return true;\r\n    }\r\n\r\n    const char* cTitle = title.c_str();\r\n    if ( strstr( cTitle, pSong->m_strArtist ) == 0 )\r\n    {\r\n        PRINTF(DEBUG_INFO, \"CWinampScrobbler::SanityCheckMetadata\", \"Metadata workaround triggered. Metadata artist: %s. Song title: %s\", pSong->m_strArtist, title.c_str());\r\n\r\n        // not found\r\n        return false;\r\n    }\r\n\r\n    return true;\r\n}\r\n\r\n\r\n\r\nBOOL CALLBACK CWinampScrobbler::enumWndProc(HWND hwnd, LPARAM lParam)\r\n{\r\n    CWinampScrobbler* scrobbler = (CWinampScrobbler*)( lParam );\r\n    if(SendMessage(scrobbler->m_hWndWinamp,WM_WA_IPC,(WPARAM)hwnd,IPC_FF_ISMAINWND)){\r\n        scrobbler->m_mainWinAmpWnd = hwnd;\r\n        return 0;\r\n    }\r\n    return 1;\r\n}"
  },
  {
    "path": "plugins/winamp/WinampScrobbler.h",
    "content": "// WinampScrobbler.h: interface for the CWinampScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_WINAMPSCROBBLER_H__7BFE93FD_744B_4D31_94DA_1A44EAA4C581__INCLUDED_)\r\n#define AFX_WINAMPSCROBBLER_H__7BFE93FD_744B_4D31_94DA_1A44EAA4C581__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n#define AUDIOSCROBBLER_APPNAME\t\t\t\t\t\"Audioscrobbler Winamp plugin\"\r\n#define AUDIOSCROBBLER_APPID\t\t\t\t\t\"wa2\"\r\n#define AUDIOSCROBBLER_REGKEY\t\t\t\t\t\"Software\\\\Last.fm\\\\Audioscrobbler Winamp Plugin\"\r\n\r\n#include \"Scrobbler.h\"\r\n#include \"WinampController.h\"\r\n#include \"WinampBootstrap.h\"\r\n\r\nclass CWinampScrobbler : public CScrobbler  \r\n{\r\npublic:\r\n\tCWinampScrobbler();\r\n\tvirtual ~CWinampScrobbler();\r\n\r\n\tBOOL\t\tStartScrobbling(HINSTANCE hInstance, \r\n\t\t\t\t\t\t\t\tHWND hWndWinamp,\r\n\t\t\t\t\t\t\t\tHWND hWndWinampML,\r\n\t\t\t\t\t\t\t\tCStdString strWorkingDir);\r\n\r\n\t// Overrides\r\n\tCStdString\tGetAppName(){ return AUDIOSCROBBLER_APPNAME;}\r\n\tCStdString\tGetAppId(){ return AUDIOSCROBBLER_APPID;}\r\n\tCStdString\tGetRegKey(){ return AUDIOSCROBBLER_REGKEY;}\r\n\tCStdString\tGetPlayerVersion();\r\n\tBOOL\t\tIsPlaying(){ return m_Controller.IsPlaying();}\r\n\tBOOL\t\tIsPaused(){ return m_Controller.IsPaused();}\r\n\tBOOL\t\tIsStopped(){ return m_Controller.IsStopped();}\r\n\tCStdString\tGetCurrentSongFileName(){ return m_Controller.GetCurrentSongFileName();}\r\n\tint\t\t\tGetTrackLength(){ return m_Controller.GetTrackLength();}\r\n\tint\t\t\tGetTrackPosition(){ return (m_Controller.GetPlayingTime() / 1000);}\r\n\tBOOL\t    GetCurrentSong(SONG_INFO* pSong, bool utf8 = true);\r\n\tHWND\t\tGetParentWnd(){ return m_hWndWinamp;}\r\n\r\n\tBOOL\t\tWinampPEMessage(UINT message, WPARAM wParam, LPARAM lParam);\r\n    BOOL        WinampMessage(UINT message, WPARAM wParam, LPARAM lParam);\r\n\r\nprotected:\r\n\tCWinampController\tm_Controller;\t// Winamp Controller\r\n\tHWND\t\t\t\tm_hWndWinamp;\t// Winamp Main Window HWND\r\n\tHWND\t\t\t\tm_hWndWinampML;\t// Winamp Media Library Window HWND\r\n\tDWORD\t\t\t\tm_dwLastPlay;\t// TickCount\r\n\r\n    void GetSongMetaDataUtf8(SONG_INFO* pSong);\r\n    void GetSongMetaData(SONG_INFO* pSong);\r\n    bool SanityCheckMetadata(SONG_INFO* pSong, bool utf8);\r\n\r\nprivate:\r\n    WinampBootStrap m_bootstrap;\r\n    static BOOL CALLBACK enumWndProc(HWND hwnd, LPARAM lParam);\r\n    \r\n    HWND m_mainWinAmpWnd;\r\n};\r\n\r\n#endif // !defined(AFX_WINAMPSCROBBLER_H__7BFE93FD_744B_4D31_94DA_1A44EAA4C581__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/winamp/comdate.h",
    "content": "// comdate.h\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Copyright (c) 1998-2000 Chris Sells\r\n// All rights reserved.\r\n//\r\n// NO WARRANTIES ARE EXTENDED. USE AT YOUR OWN RISK.\r\n//\r\n// To contact the author with suggestions or comments, use csells@sellsbrothers.com.\r\n/////////////////////////////////////////////////////////////////////////////\r\n// History:\r\n//  9/27/01 - Dropped in operator SYSTEMTIME() and operator FILETIME() from\r\n//            Scott Zionic [Scott.Zionic@petersweb.com]. Thanks, Scott.\r\n//  4/9/01  - Implemented operator time_t() and operator struct tm() as per\r\n//            Shawn Wildermuth's request.\r\n//  2/8/01  - Fixed a rounding bug in CComSpan reported by Ralf Mohaupt\r\n//            [r.mohaupt@lit.lineas.de].\r\n//  11/4/00 - Moved everything to the header file for convenience.\r\n//  4/13/00 - Sudhakar M [msudhakar@yahoo.com] contributed\r\n//            CComDATE(const struct tm& tmSrc), from which I also extrapolated\r\n//            CComDATE::operator=(const struct tm& tmSrc).\r\n//  3/10/00 - Inspired by Eric White [EricW@DATA-TECH.COM] to add an\r\n//            operator DBTIMESTAMP using his implementation. Also added\r\n//            extra ctor, operator= and conversion operators for other date/time\r\n//            formats, but haven't implemented all of them yet.\r\n//            Inspired by Artyom Tyazhelov [artyom6@hotmail.com] to\r\n//            leave current time alone when calling SetDate and leaving current\r\n//            date alone when calling SetTime.\r\n//  1/15/00 - Fixed a 2038 bug in Now. Thanks Michael Entin [entin@swusa.com].\r\n//  7/14/99 - Fixed a linker problem w/ some inline functions release\r\n//            builds. Thanks to David Maw [David.Maw@unisys.com] for\r\n//            first pointing it out.\r\n//   6/9/99 - Fixed a problem in Maketm where tm_isdst was not being set\r\n//            (as is required by the CRT). Thanks to Jim Hoffman\r\n//            [JHoffman@Enerx.com] for pointing it out.\r\n//  4/18/99 - Fixed a problem in Format to provide a work-around in the\r\n//            VC6 implementation of wcsftime. Thanks for Joe O'Leary for\r\n//            pointing it out.\r\n//            Even better, Joe also contributed FormatDate and FormatTime\r\n//            to wrap the National Language Support functions GetTimeFormat()\r\n//            and GetDateFormat(). Thanks, Joe!\r\n//            Also, Juan Rivera (juanc@kodak.com) pointed out a missing operator=\r\n//            declaration. Thanks, Juan.\r\n// 12/24/98 - Based on a suggestion by Ronald Laeremans [RonaldL@mvps.org],\r\n//            replaced all of the manual Maketm code w/ VariantToSystemTime.\r\n//            Also updated MakeDATE to use SystemTimeToVariantTime. Thanks, Ron!\r\n// 12/23/98 - Fixed a bug Ward pointed out in CComDATE::operator=(const time_t&).\r\n// 12/21/98 - Ward Fuller <wfuller@tsisoft.com> pointed out a BSTR leak in\r\n//            the Format implementation. It's plugged. Thanks, Ward!\r\n// 12/21/98 - Initial release.\r\n/////////////////////////////////////////////////////////////////////////////\r\n// The file provides two class for use with dates and times under Windows.\r\n//\r\n// CComDATE: Wraps the COM DATE type, providing conversions from VARIANT,\r\n//           DATE, ANSI string, UNICODE string, time_t, SYSTEMTIME, FILETIME,\r\n//           DOS time and DBTIMESTAMP data types.\r\n//\r\n// CComSpan: Represents the result of subtracting one CComDATE from another.\r\n//           Useful for time/date math.\r\n//\r\n// NOTE: This usage of these classes are based loosely on the MFC classes\r\n//       COleDateTime and COleDateTimeSpan. However, the implementation is 99% mine.\r\n\r\n#pragma once\r\n#ifndef __COMDATE_H__\r\n#define __COMDATE_H__\r\n\r\n#include <time.h>\r\n#include <limits.h>\r\n#include <tchar.h>\r\n#include <math.h>   // ceil, floor and modf\r\n#include <winnls.h>\r\n#include <OAIDL.H>\r\n#include <crtdbg.h>\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class\r\n\r\nclass CComSpan; // Forward declaration\r\n\r\nclass CComDATE\r\n{\r\npublic:\r\n    static CComDATE Now();\r\n    static bool     IsValidDate(const DATE& dt);\r\n    \r\n    CComDATE();\r\n    CComDATE(const CComDATE& dtSrc);\r\n    CComDATE(const VARIANT& varSrc);\r\n    CComDATE(DATE dtSrc);\r\n    CComDATE(const char* pszSrc);\r\n    CComDATE(const wchar_t* pszSrc);\r\n    CComDATE(time_t timeSrc);\r\n    CComDATE(const struct tm& tmSrc);\r\n    CComDATE(const SYSTEMTIME& systimeSrc);\r\n    CComDATE(const FILETIME& filetimeSrc);\r\n    CComDATE(long nYear, long nMonth, long nDay, long nHour = 0, long nMin = 0, long nSec = 0);\r\n    CComDATE(WORD wDosDate, WORD wDosTime);\r\n    \r\n#ifdef __oledb_h__\r\n    CComDATE(const DBTIMESTAMP& dbts);\r\n#endif\r\n    \r\npublic:\r\n    bool  IsValid() const;\r\n    long  Year() const;\r\n    long  Month() const;     // month of year (1 = Jan)\r\n    long  Day() const;       // day of month (1-31)\r\n    long  Hour() const;      // hour in day (0-23)\r\n    long  Minute() const;    // minute in hour (0-59)\r\n    long  Second() const;    // second in minute (0-59)\r\n    long  DayOfWeek() const; // 1=Sun, 2=Mon, ..., 7=Sat\r\n    long  DayOfYear() const; // days since start of year, Jan 1 = 1\r\n    \r\n    bool  IsLeapYear() const;   // Whether it's a leap year or not\r\n    bool  IsNoon() const;       // Whether it's 12:00:00pm or not\r\n    bool  IsMidnight() const;   // Whether it's 12:00:00am or not\r\n    \r\n    // Operations\r\npublic:\r\n    const CComDATE& operator=(const CComDATE& dtSrc);\r\n    const CComDATE& operator=(const VARIANT& varSrc);\r\n    const CComDATE& operator=(DATE dtSrc);\r\n    const CComDATE& operator=(const char* pszSrc);\r\n    const CComDATE& operator=(const wchar_t* pszSrc);\r\n    \r\n    const CComDATE& operator=(const time_t& timeSrc);\r\n    const CComDATE& operator=(const struct tm& tmSrc);\r\n    const CComDATE& operator=(const SYSTEMTIME& systimeSrc);\r\n    const CComDATE& operator=(const FILETIME& filetimeSrc);\r\n\r\n#ifdef __oledb_h__\r\n    const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts);\r\n#endif\r\n\r\n    bool operator==(const CComDATE& date) const;\r\n    bool operator!=(const CComDATE& date) const;\r\n    bool operator<(const CComDATE& date) const;\r\n    bool operator>(const CComDATE& date) const;\r\n    bool operator<=(const CComDATE& date) const;\r\n    bool operator>=(const CComDATE& date) const;\r\n    \r\n    // Date math\r\n    const CComDATE& operator+=(const CComSpan& span);\r\n    const CComDATE& operator-=(const CComSpan& span);\r\n    \r\n    friend CComDATE operator+(const CComDATE& date, const CComSpan& span);\r\n    friend CComDATE operator-(const CComDATE& date, const CComSpan& span);\r\n    friend CComDATE operator+(const CComSpan& span, const CComDATE& date);\r\n    friend CComSpan operator-(const CComDATE& date1, const CComDATE& date2);\r\n    \r\n    operator DATE() const;\r\n    DATE* operator&();\r\n\r\n    operator VARIANT() const;\r\n    operator time_t() const;\r\n    operator struct tm() const;\r\n    operator SYSTEMTIME() const;\r\n    operator FILETIME() const;\r\n#ifdef __oledb_h__\r\n    operator DBTIMESTAMP() const;\r\n#endif\r\n    \r\n    bool  SetDateTime(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec);\r\n    bool  SetDate(long nYear, long nMonth, long nDay);\r\n    bool  SetTime(long nHour, long nMin, long nSec);\r\n    bool  ParseDateTime(const char* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT);\r\n    bool  ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT);\r\n    \r\n    // Formatting\r\n    LPTSTR Format(LPTSTR pszOut, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT) const;\r\n    LPTSTR Format(LPTSTR pszOut, LPCTSTR lpszFormat) const;\r\n#ifdef __ATLCOM_H__\r\n    LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = _Module.GetResourceInstance()) const;\r\n#else\r\n    LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = GetModuleHandle(0)) const;\r\n#endif\r\n\r\n\t// Formatting using National Language Support functions GetTimeFormat() and GetDateFormat()\r\n\tLPTSTR\tFormatTime(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const;\r\n\tLPTSTR\tFormatDate(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const;\r\n    \r\nprotected:\r\n    enum\r\n    {\r\n        COMDATE_ERROR = INT_MIN,\r\n        MIN_DATE      = -657434L,       // About year 100\r\n        MAX_DATE      = 2958465L,       // About year 9999\r\n        INVALID_DATE  = (MIN_DATE-1),   // Used to indicate invalid date\r\n    };\r\n\r\nprotected:\r\n    DATE  m_date;\r\n    \r\nprotected:\r\n    void Invalidate();\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan class\r\n\r\nclass CComSpan\r\n{\r\npublic:\r\n    CComSpan();\r\n    CComSpan(double dblSpanSrc);\r\n    CComSpan(const CComSpan& dateSpanSrc);\r\n    CComSpan(long nDays, long nHours = 0, long nMins = 0, long nSecs = 0);\r\n    \r\n    bool IsValid() const;\r\n    \r\n    double TotalDays() const;    // span in days (about -3.65e6 to 3.65e6)\r\n    double TotalHours() const;   // span in hours (about -8.77e7 to 8.77e6)\r\n    double TotalMinutes() const; // span in minutes (about -5.26e9 to 5.26e9)\r\n    double TotalSeconds() const; // span in seconds (about -3.16e11 to 3.16e11)\r\n    \r\n    long Days() const;       // component days in span\r\n    long Hours() const;      // component hours in span (-23 to 23)\r\n    long Minutes() const;    // component minutes in span (-59 to 59)\r\n    long Seconds() const;    // component seconds in span (-59 to 59)\r\n    \r\npublic:\r\n    const CComSpan& operator=(double dblSpanSrc);\r\n    const CComSpan& operator=(const CComSpan& dateSpanSrc);\r\n    \r\n    bool operator==(const CComSpan& dateSpan) const;\r\n    bool operator!=(const CComSpan& dateSpan) const;\r\n    bool operator<(const CComSpan& dateSpan) const;\r\n    bool operator>(const CComSpan& dateSpan) const;\r\n    bool operator<=(const CComSpan& dateSpan) const;\r\n    bool operator>=(const CComSpan& dateSpan) const;\r\n    \r\n    // Math\r\n    const CComSpan& operator+=(const CComSpan& rhs);\r\n    const CComSpan& operator-=(const CComSpan& rhs);\r\n    CComSpan operator-() const;\r\n    \r\n    friend CComSpan operator+(const CComSpan& span1, const CComSpan& span2);\r\n    friend CComSpan operator-(const CComSpan& span1, const CComSpan& span2);\r\n    \r\n    operator double() const;\r\n    \r\n    void SetSpan(long nDays, long nHours, long nMins, long nSecs);\r\n    \r\nprotected:\r\n    enum\r\n    {\r\n        MAX_SPAN      = 3615897L,\r\n        MIN_SPAN      = -MAX_SPAN,\r\n        INVALID_SPAN  = (MIN_SPAN-1),   // Used to indicate invalid span\r\n    };\r\n\r\nprotected:\r\n    double  m_span;\r\n\r\nprotected:\r\n    void Invalidate();\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE inline implementations\r\n\r\ninline bool CComDATE::IsValidDate(const DATE& dt)\r\n{\r\n    // About year 100 to about 9999\r\n    return (dt >= MIN_DATE && dt <= MAX_DATE);\r\n}\r\n\r\ninline CComDATE CComDATE::Now()\r\n{\r\n    SYSTEMTIME  sysTime;\r\n    GetLocalTime(&sysTime);\r\n    return CComDATE(sysTime);\r\n}\r\n\r\ninline CComDATE::CComDATE()\r\n{ Invalidate(); }\r\n\r\ninline CComDATE::CComDATE(const CComDATE& dtSrc)\r\n{ m_date = dtSrc.m_date; }\r\n\r\ninline CComDATE::CComDATE(const VARIANT& varSrc)\r\n{ *this = varSrc; }\r\n\r\ninline CComDATE::CComDATE(DATE dtSrc)\r\n{ m_date = dtSrc; }\r\n\r\ninline CComDATE::CComDATE(const char* pszSrc)\r\n{ ParseDateTime(pszSrc); }\r\n\r\ninline CComDATE::CComDATE(const wchar_t* pszSrc)\r\n{ ParseDateTime(pszSrc); }\r\n\r\ninline CComDATE::CComDATE(time_t timeSrc)\r\n{ *this = timeSrc; }\r\n\r\ninline CComDATE::CComDATE(const struct tm& tmSrc)\r\n{ \r\n    SetDateTime(tmSrc.tm_year + 1900,\r\n                tmSrc.tm_mon + 1,\r\n                tmSrc.tm_mday,\r\n                tmSrc.tm_hour,\r\n                tmSrc.tm_min,\r\n                tmSrc.tm_sec); \r\n}\r\n\r\ninline CComDATE::CComDATE(const SYSTEMTIME& systimeSrc)\r\n{ *this = systimeSrc; }\r\n\r\ninline CComDATE::CComDATE(const FILETIME& filetimeSrc)\r\n{ *this = filetimeSrc; }\r\n\r\ninline CComDATE::CComDATE(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec)\r\n{ SetDateTime(nYear, nMonth, nDay, nHour, nMin, nSec); }\r\n\r\ninline CComDATE::CComDATE(WORD wDosDate, WORD wDosTime)\r\n{ if( !DosDateTimeToVariantTime(wDosDate, wDosTime, &m_date) ) Invalidate(); }\r\n\r\ninline const CComDATE& CComDATE::operator=(const CComDATE& dtSrc)\r\n{ m_date = dtSrc.m_date; return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator=(const char* pszSrc)\r\n{ ParseDateTime(pszSrc); return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator=(const wchar_t* pszSrc)\r\n{ ParseDateTime(pszSrc); return *this; }\r\n\r\ninline bool CComDATE::operator==(const CComDATE& date) const\r\n{ return (m_date == date.m_date); }\r\n\r\ninline bool CComDATE::operator!=(const CComDATE& date) const\r\n{ return (m_date != date.m_date); }\r\n\r\ninline CComDATE::operator DATE() const\r\n{ return m_date; }\r\n\r\ninline DATE* CComDATE::operator&()\r\n{ return &m_date; }\r\n\r\ninline bool CComDATE::SetDate(long nYear, long nMonth, long nDay)\r\n{ return SetDateTime(nYear, nMonth, nDay, Hour(), Minute(), Second()); }\r\n\r\ninline bool CComDATE::SetTime(long nHour, long nMin, long nSec)\r\n{ return SetDateTime(Year(), Month(), Day(), nHour, nMin, nSec); }\r\n\r\ninline const CComDATE& CComDATE::operator+=(const CComSpan& span)\r\n{ *this = *this + span; return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator-=(const CComSpan& span)\r\n{ *this = *this - span; return *this; }\r\n\r\ninline bool CComDATE::IsValid() const\r\n{ return IsValidDate(m_date); }\r\n\r\ninline void CComDATE::Invalidate()\r\n{ m_date = INVALID_DATE; }\r\n\r\n#ifdef __oledb_h__\r\ninline CComDATE::CComDATE(const DBTIMESTAMP& dbts)\r\n{ SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); }\r\n\r\ninline const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts)\r\n{ SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); return *this; }\r\n\r\n#endif  // __oledb_h__\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan inline implementations\r\n\r\ninline CComSpan::CComSpan()\r\n{ Invalidate(); }\r\n\r\ninline CComSpan::CComSpan(double db) : m_span(db) {}\r\n\r\ninline CComSpan::CComSpan(const CComSpan& rhs)\r\n{ m_span = rhs.m_span; }\r\n\r\ninline CComSpan::CComSpan(long nDays, long nHours, long nMins, long nSecs)\r\n{ SetSpan(nDays, nHours, nMins, nSecs); }\r\n\r\ninline const CComSpan& CComSpan::operator=(double db)\r\n{ m_span = db; return *this; }\r\n\r\ninline const CComSpan& CComSpan::operator=(const CComSpan& span)\r\n{ m_span = span.m_span; return *this; }\r\n\r\ninline double CComSpan::TotalDays() const\r\n{ _ASSERTE(IsValid()); return m_span; }\r\n\r\ninline double CComSpan::TotalHours() const\r\n{ _ASSERTE(IsValid()); return m_span * 24; }\r\n\r\ninline double CComSpan::TotalMinutes() const\r\n{ _ASSERTE(IsValid()); return m_span * 24 * 60; }\r\n\r\ninline double CComSpan::TotalSeconds() const\r\n{ _ASSERTE(IsValid()); return m_span * 24 * 60 * 60; }\r\n\r\ninline long CComSpan::Days() const\r\n{ _ASSERTE(IsValid()); return (long)m_span; }\r\n\r\ninline bool CComSpan::operator==(const CComSpan& rhs) const\r\n{ return m_span == rhs.m_span; }\r\n\r\ninline bool CComSpan::operator!=(const CComSpan& rhs) const\r\n{ return m_span != rhs.m_span; }\r\n\r\ninline bool CComSpan::operator<(const CComSpan& rhs) const\r\n{ return m_span < rhs.m_span; }\r\n\r\ninline bool CComSpan::operator>(const CComSpan& rhs) const\r\n{ return m_span > rhs.m_span; }\r\n\r\ninline bool CComSpan::operator<=(const CComSpan& rhs) const\r\n{ return m_span <= rhs.m_span; }\r\n\r\ninline bool CComSpan::operator>=(const CComSpan& rhs) const\r\n{ return m_span >= rhs.m_span; }\r\n\r\ninline const CComSpan& CComSpan::operator+=(const CComSpan& rhs)\r\n{ return (*this = *this + rhs); }\r\n\r\ninline const CComSpan& CComSpan::operator-=(const CComSpan& rhs)\r\n{ return (*this = *this - rhs); }\r\n\r\ninline CComSpan CComSpan::operator-() const\r\n{ return CComSpan(-m_span); }\r\n\r\ninline CComSpan::operator double() const\r\n{ return m_span; }\r\n\r\ninline bool CComSpan::IsValid() const\r\n{ return (m_span >= MIN_SPAN && m_span <= MAX_SPAN); }\r\n\r\ninline void CComSpan::Invalidate()\r\n{ m_span = INVALID_SPAN; }\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class helper definitions\r\n\r\n#define HALF_SECOND 1.0/172800.0    // Half a second, expressed in days\r\n\r\nbool   MakeDATE(DATE* pdtDest, WORD wYear, WORD wMonth, WORD wDay, WORD wHour, WORD wMinute, WORD wSecond);\r\nbool   Maketm(struct tm* ptmDest, DATE dtSrc);\r\ndouble DATEAsDouble(DATE dtSrc);\r\nDATE   MakeDATE(double dbSrc);\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class\r\n\r\ninline\r\nlong CComDATE::Year() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_year + 1900;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Month() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mon + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Day() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mday;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Hour() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_hour;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Minute() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_min;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Second() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_sec;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::DayOfWeek() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_wday + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::DayOfYear() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_yday + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nbool CComDATE::IsLeapYear() const\r\n{\r\n    long year = Year();\r\n    return ((year != COMDATE_ERROR) && ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0));\r\n}\r\n\r\ninline\r\nbool CComDATE::IsNoon() const\r\n{\r\n    return Hour() == 12 && Minute() == 0 && Second() == 0;\r\n}\r\n\r\ninline\r\nbool CComDATE::IsMidnight() const\r\n{\r\n    return Hour() == 0 && Minute() == 0 && Second() == 0;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const VARIANT& varSrc)\r\n{\r\n    if( varSrc.vt == VT_DATE )\r\n    {\r\n        m_date = varSrc.date;\r\n    }\r\n    else\r\n    {\r\n        VARIANT varDest = { 0 };\r\n        if( SUCCEEDED(VariantChangeType(&varDest, const_cast<VARIANT*>(&varSrc), 0, VT_DATE)) )\r\n        {\r\n            m_date = varDest.date;\r\n            VariantClear(&varDest);\r\n        }\r\n        else\r\n        {\r\n            Invalidate();\r\n        }\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(DATE dtSrc)\r\n{\r\n    m_date = dtSrc;\r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const time_t& tmSrc)\r\n{\r\n    // Convert time_t to struct tm\r\n    tm *ptm = localtime(&tmSrc);\r\n    \r\n    if( !ptm ||\r\n        !MakeDATE(&m_date,\r\n                  (WORD)(ptm->tm_year + 1900),\r\n                  (WORD)(ptm->tm_mon + 1),\r\n                  (WORD)ptm->tm_mday,\r\n                  (WORD)ptm->tm_hour,\r\n                  (WORD)ptm->tm_min,\r\n                  (WORD)ptm->tm_sec) )\r\n    {\r\n        // Local time must have failed (tmSrc before 1/1/70 12am)\r\n        Invalidate();\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const struct tm& tmSrc)\r\n{\r\n    SetDateTime(tmSrc.tm_year + 1900,\r\n                tmSrc.tm_mon + 1,\r\n                tmSrc.tm_mday,\r\n                tmSrc.tm_hour,\r\n                tmSrc.tm_min,\r\n                tmSrc.tm_sec); \r\n\r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const SYSTEMTIME& systmSrc)\r\n{\r\n    if( !MakeDATE(&m_date,\r\n                  systmSrc.wYear,\r\n                  systmSrc.wMonth,\r\n                  systmSrc.wDay,\r\n                  systmSrc.wHour,\r\n                  systmSrc.wMinute,\r\n                  systmSrc.wSecond) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const FILETIME& ftSrc)\r\n{\r\n    // Assume UTC FILETIME, so convert to LOCALTIME\r\n    FILETIME ftLocal;\r\n    if( !FileTimeToLocalFileTime( &ftSrc, &ftLocal) )\r\n    {\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nFileTimeToLocalFileTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n        Invalidate();\r\n    }\r\n    else\r\n    {\r\n        // Take advantage of SYSTEMTIME -> FILETIME conversion\r\n        SYSTEMTIME  systime;\r\n        \r\n        // At this polong systime should always be valid, but...\r\n        if( !FileTimeToSystemTime(&ftLocal, &systime) ||\r\n            !MakeDATE(&m_date,\r\n                      systime.wYear,\r\n                      systime.wMonth,\r\n                      systime.wDay,\r\n                      systime.wHour,\r\n                      systime.wMinute,\r\n                      systime.wSecond) )\r\n        {\r\n            Invalidate();\r\n        }\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nCComDATE::operator VARIANT() const\r\n{\r\n    VARIANT var = { 0 };\r\n    var.vt = VT_DATE;\r\n    var.date = m_date;\r\n    return var;\r\n}\r\n\r\ninline\r\nCComDATE::operator time_t() const\r\n{\r\n    struct  tm  tmDest;\r\n    if( Maketm(&tmDest, m_date) )\r\n    {\r\n        return mktime(&tmDest);\r\n    }\r\n\r\n    return -1;\r\n}\r\n\r\ninline\r\nCComDATE::operator struct tm() const\r\n{\r\n    struct  tm  tmDest = { 0 };\r\n    Maketm(&tmDest, m_date);\r\n    return tmDest;\r\n}\r\n\r\ninline\r\nCComDATE::operator SYSTEMTIME() const\r\n{\r\n    SYSTEMTIME  st = { 0 };\r\n\r\n    VariantTimeToSystemTime(m_date, &st);\r\n\r\n    return st;\r\n}\r\n\r\ninline\r\nCComDATE::operator FILETIME() const\r\n{\r\n    FILETIME    ft = { 0 };\r\n\t\r\n    SYSTEMTIME st;\r\n    VariantTimeToSystemTime(m_date, &st);\r\n    SystemTimeToFileTime(&st, &ft);\r\n\r\n    return ft;\r\n}\r\n\r\n#ifdef __oledb_h__\r\ninline\r\nCComDATE::operator DBTIMESTAMP() const\r\n{\r\n    DBTIMESTAMP dbts = { 0 };\r\n\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) )\r\n    {\r\n        dbts.day    = tmDest.tm_mday;\r\n        dbts.month  = tmDest.tm_mon + 1;\r\n        dbts.year   = tmDest.tm_year + 1900;\r\n        dbts.hour   = tmDest.tm_hour;\r\n        dbts.minute = tmDest.tm_min;\r\n        dbts.second = tmDest.tm_sec;\r\n    }\r\n\r\n    return dbts;\r\n}\r\n#endif\r\n\r\ninline\r\nbool CComDATE::operator<(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) < DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator>(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) > DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator<=(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) <= DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator>=(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) >= DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::SetDateTime(\r\n    long nYear,\r\n    long nMonth,\r\n    long nDay,\r\n    long nHour,\r\n    long nMin,\r\n    long nSec)\r\n{\r\n    if( !MakeDATE(&m_date, (WORD)nYear, (WORD)nMonth, (WORD)nDay, (WORD)nHour, (WORD)nMin, (WORD)nSec) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return IsValid();\r\n}\r\n\r\n/*inline\r\nbool CComDATE::ParseDateTime(const char* lpszDate, DWORD dwFlags, LCID lcid)\r\n{\r\n    USES_CONVERSION;\r\n    return ParseDateTime(A2OLE(lpszDate), dwFlags, lcid);\r\n}*/\r\n\r\ninline\r\nbool CComDATE::ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags, LCID lcid)\r\n{\r\n    if( FAILED(VarDateFromStr(const_cast<wchar_t*>(lpszDate), lcid, dwFlags, &m_date)) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return IsValid();\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, DWORD dwFlags, LCID lcid) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    // If invalild, return empty string\r\n    if (!IsValid()) return pszOut;\r\n    \r\n    BSTR  bstr = 0;\r\n    if( SUCCEEDED(VarBstrFromDate(m_date, lcid, dwFlags, &bstr)) )\r\n    {\r\n#ifdef _UNICODE\r\n        wcscpy(pszOut, bstr);\r\n#else\r\n        wcstombs(pszOut, bstr, wcslen(bstr) + 1);\r\n#endif\r\n        \r\n        SysFreeString(bstr);\r\n    }\r\n    \r\n    return pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, LPCTSTR pFormat) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    // If invalild, return empty string\r\n    struct tm tmDest;\r\n    if (!IsValid() || !Maketm(&tmDest, m_date) ) return pszOut;\r\n    \r\n    // Fill in the buffer, disregard return value as it's not necessary\r\n    // NOTE: 4096 is an arbitrary value picked lower than INT_MAX\r\n    // as the VC6 implementation of wcsftime allocates memory based\r\n    // on the 2nd parameter for some reason.\r\n    _tcsftime(pszOut, 4096, pFormat, &tmDest);\r\n    return pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    TCHAR   sz[256];\r\n    if( LoadString(hinst, nFormatID, sz, sizeof(sz)/sizeof(*sz)) )\r\n    {\r\n        return Format(pszOut, sz);\r\n    }\r\n    \r\n    return pszOut;\r\n}\r\n\r\n// The FormatDate and FormatTime functions were provided by Joe O'Leary (joleary@artisoft.com) to\r\n// wrap he Win32 National Language Support functions ::GetDateFormat() and ::GetTimeFormat().\r\n// The format strings used here are specified in the on-line help for those functions.\r\n// The default format is the current user locale.\r\n\r\ninline\r\nLPTSTR CComDATE::FormatDate(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const\r\n{\r\n\t_ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero\r\n\r\n\tSYSTEMTIME st;\r\n\tmemset(&st, 0, sizeof(SYSTEMTIME));\r\n\t*pszOut = NULL;\r\n\r\n\tif ( !VariantTimeToSystemTime(m_date, &st) )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nVariantTimeToSystemTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\telse if ( GetDateFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nGetDateFormat failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\r\n\treturn pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::FormatTime(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const\r\n{\r\n\t_ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero\r\n\r\n\tSYSTEMTIME st;\r\n\tmemset(&st, 0, sizeof(SYSTEMTIME));\r\n\t*pszOut = NULL;\r\n\r\n\tif ( !VariantTimeToSystemTime(m_date, &st) )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nVariantTimeToSystemTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\telse if ( GetTimeFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nGetTimeFormat failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\r\n\treturn pszOut;\r\n}\r\n\r\ninline\r\nbool Maketm(struct tm* ptmDest, DATE dtSrc)\r\n{\r\n    SYSTEMTIME  st;\r\n    if( !VariantTimeToSystemTime(dtSrc, &st) ) return false;\r\n    \r\n    struct tm& tmDest = *ptmDest; // Convenience\r\n    tmDest.tm_sec = st.wSecond;\r\n    tmDest.tm_min = st.wMinute;\r\n    tmDest.tm_hour = st.wHour;\r\n    tmDest.tm_mday = st.wDay;\r\n    tmDest.tm_mon = st.wMonth - 1;\r\n    tmDest.tm_year = st.wYear - 1900;\r\n    tmDest.tm_wday = st.wDayOfWeek;\r\n    tmDest.tm_isdst = -1;   // Force DST checking\r\n    mktime(&tmDest);    // Normalize\r\n    \r\n    return true;\r\n}\r\n\r\ninline\r\ndouble DATEAsDouble(DATE dt)\r\n{\r\n    // No problem if positive\r\n    if (dt >= 0) return dt;\r\n    \r\n    // If negative, must convert since negative dates not continuous\r\n    // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)\r\n    double temp = ceil(dt);\r\n    return temp - (dt - temp);\r\n}\r\n\r\ninline\r\nDATE MakeDATE(double dbl)\r\n{\r\n    // No problem if positive\r\n    if (dbl >= 0) return dbl;\r\n    \r\n    // If negative, must convert since negative dates not continuous\r\n    // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)\r\n    double temp = floor(dbl); // dbl is now whole part\r\n    return temp + (temp - dbl);\r\n}\r\n\r\ninline\r\nbool MakeDATE(\r\n    DATE* pdtDest,\r\n    WORD  wYear,\r\n    WORD  wMonth,\r\n    WORD  wDay,\r\n    WORD  wHour,\r\n    WORD  wMinute,\r\n    WORD  wSecond)\r\n{\r\n    SYSTEMTIME st = { 0 };\r\n    st.wYear = wYear;\r\n    st.wMonth = wMonth;\r\n    st.wDay = wDay;\r\n    st.wHour = wHour;\r\n    st.wMinute = wMinute;\r\n    st.wSecond = wSecond;\r\n    \r\n    return SystemTimeToVariantTime(&st, pdtDest) ? true : false;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan class\r\n\r\ninline\r\nlong CComSpan::Hours() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate days and scale up\r\n    double dbTemp = modf(m_span, &dbTemp);\r\n    return (long)(dbTemp * 24);\r\n}\r\n\r\ninline\r\nlong CComSpan::Minutes() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate hours and scale up\r\n    double dbTemp = modf(m_span * 24, &dbTemp);\r\n    return (long)((dbTemp + HALF_SECOND) * 60);\r\n}\r\n\r\ninline\r\nlong CComSpan::Seconds() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate minutes and scale up\r\n    double dbTemp = modf(m_span * 24 * 60, &dbTemp);\r\n    return (long)(dbTemp * 60);\r\n}\r\n\r\ninline\r\nvoid CComSpan::SetSpan(\r\n    long  nDays,\r\n    long  nHours,\r\n    long  nMins,\r\n    long  nSecs)\r\n{\r\n    // Set date span by breaking longo fractional days (all input ranges valid)\r\n    m_span = nDays +\r\n             ((double)nHours)/24 +\r\n             ((double)nMins)/(24*60) +\r\n             ((double)nSecs)/(24*60*60);\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE/CComSpan math friend functions\r\n\r\n// date2 = date1 + span;\r\ninline\r\nCComDATE operator+(const CComDATE& date1, const CComSpan& span)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// date2 = span + date1;\r\ninline\r\nCComDATE operator+(const CComSpan& span, const CComDATE& date1)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// date2 = date1 - span;\r\ninline\r\nCComDATE operator-(const CComDATE& date1, const CComSpan& span)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) - static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// span = date1 - date2;\r\ninline\r\nCComSpan operator-(const CComDATE& date1, const CComDATE& date2)\r\n{\r\n    CComSpan span;\r\n    \r\n    if( date1.IsValid() && date2.IsValid() )\r\n    {\r\n        span = DATEAsDouble(static_cast<DATE>(date1)) - DATEAsDouble(static_cast<DATE>(date2));\r\n    }\r\n    \r\n    return span;\r\n}\r\n\r\n// span3 = span1 + span2;\r\ninline\r\nCComSpan operator+(const CComSpan& span1, const CComSpan& span2)\r\n{\r\n    CComSpan span3;\r\n    if( span1.IsValid() && span2.IsValid() ) span3 = span1.m_span + span2.m_span;\r\n    return span3;\r\n}\r\n\r\n// span3 = span1 - span2;\r\ninline\r\nCComSpan operator-(const CComSpan& span1, const CComSpan& span2)\r\n{\r\n    return span1 + (-span2);\r\n}\r\n\r\n#undef HALF_SECOND\r\n#endif  // __COMDATE_H__\r\n"
  },
  {
    "path": "plugins/winamp/dbg.cpp",
    "content": "/*************************************************************************\r\n FILE :\t\t\tdbg.cpp\r\n\r\n Author :\t\tSpib\r\n\r\n Description:\tCDebug\r\n\t\t\t\tThread-safe logging routines for logging from multiple\r\n\t\t\t\tprocesses to one log file. \r\n\r\n\t\t\t\tClass includes printf-style formatted output routines, as\r\n\t\t\t\twell as timestamping of entries, process id, and process execution time.\r\n\r\n Spib\t- Allow max file size\r\n\t\t\t\tAllows debugging to be activated at runtime.\r\n\r\n*************************************************************************/\r\n#include <windows.h>\r\n#include <process.h>\r\n#include \"dbg.h\"      \r\n\r\n#ifdef USE_DEBUG_PRINTF\r\n\r\n#define MSG_BUFFER_SIZE\t\t1024*50\r\n\r\nconst char DIVIDER[10] = { 13, 10, '-', '-', '-', '-', '-', '-', 13, 10 };\r\nconst char CrLf[3]\t   = { 13, 10, 0 };\r\n\r\nCDebug debug;\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : CDebug::CDebug ()\r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : \r\n *  History     : \r\n */\r\nCDebug::CDebug ()\r\n{\r\n\tm_bEnabled\t\t\t= FALSE;  \r\n\tm_nLogLevel\t\t\t= DEBUG_ERROR;\r\n\tm_nMaxFileSize\t= -1;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : CDebug::CDebug ()\r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : \r\n *  History     : \r\n */\r\nCDebug::~CDebug ()\r\n{\r\n\tCloseLog();\r\n}\r\n\r\nvoid CDebug::Init(const char* strFileName, BOOL bOverWrite /* = TRUE */, BOOL bEnable /* = TRUE */, BOOL bUseXML /*= FALSE*/)\r\n{\t\r\n\tif(strlen(strFileName) <= 0)\r\n\t\treturn;\r\n\r\n\tm_bEnabled\t\t= bEnable;\r\n\tm_bUseXML\t\t\t= bUseXML;\r\n\r\n\tstrncpy(m_strFilePath, strFileName, MAX_PATH);\r\n\r\n\tif(m_bUseXML)\r\n\t\tstrcat(m_strFilePath, \".xml\");\r\n\r\n\tInitializeCriticalSection(&m_hLock);\r\n\t\t\r\n\tif(OpenLogFile(bOverWrite))\r\n\t{\r\n\t\tm_dwStartTime = GetTickCount();\r\n\t\tWriteHeader(bOverWrite);\r\n\t}\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : void CDebug::CloseLog ()\r\n *  Description : Closes log file and releases handles. \r\n *  Parameters  :                   \r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::CloseLog ()\r\n{\r\n\tchar buffer[9];\r\n\tDWORD x = 0;\r\n\r\n\tif(m_bEnabled && m_hFile != NULL)\r\n\t{\r\n\t\tif(m_bUseXML)\r\n\t\t{\t\t\r\n\t\t\tstrcpy(buffer, \"</DEBUG>\");\r\n\t\t\tWriteFile(m_hFile,\tbuffer,    lstrlen(buffer),    &x, 0 );\r\n\t\t}\r\n\r\n\t\tCloseHandle(m_hFile );\r\n\r\n\t\tDeleteCriticalSection(&m_hLock );\r\n\t}\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : void CDebug::printf (const char *fmt, ... )\r\n *  Description : Prints formatted string to log-file\r\n *  Parameters  : const char *fmt - format string\r\n                  ...             - list of parameters\r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::printf (int nLevel, const char* strMod, const char *fmt, ... )\r\n{\r\n\tDWORD\t\t\t\tx;\r\n\tchar\t\t\t\tbuf[256];\r\n\tSYSTEMTIME\ttime;\r\n\tchar\t\t\t\tbuffer[MSG_BUFFER_SIZE];\r\n\tchar\t\t\t\tbuffer2[MSG_BUFFER_SIZE];\r\n\tva_list\t\t\targlist;\r\n\tDWORD\t\t\t\tdwDiffTime;\r\n\r\n\tif((nLevel < m_nLogLevel) || (nLevel < 0) || !m_bEnabled)\r\n\t\treturn;\r\n\r\n\tmemset(buffer, 0, sizeof(buffer));\r\n\tmemset(buffer2, 0, sizeof(buffer2));\r\n\tmemset(buf, 0, sizeof(buf));\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\t// Do this inside the section in case we have to delete \r\n\t// the file\r\n\tCheckFileSize();\r\n\r\n\t// Format string\r\n\tva_start(arglist, fmt);\r\n\twvsprintf(buffer, fmt, arglist);\r\n\tva_end(arglist);\r\n\r\n\t// Format time stamp\r\n\tGetLocalTime(&time);\r\n\r\n\tdwDiffTime = GetTickCount() - m_dwStartTime;\r\n\r\n\tSetFilePointer(m_hFile, 0, 0, FILE_END );\r\n\t\r\n\t// XML Version\r\n\tif( m_bUseXML )\r\n\t{\r\n\t\tReplaceXMLChars(buffer, strlen(buffer), buffer2);\r\n\r\n\t\twsprintf(buf, \"<LINE><ELAPSED>%d.%03d</ELAPSED><DATE>%02d/%02d/%02d</DATE><TIME>%02d:%02d:%02d</TIME>\", \r\n\t\t\t\t\tdwDiffTime/1000, dwDiffTime%1000, \r\n\t\t\t\t\ttime.wMonth, time.wDay,    time.wYear,\r\n\t\t\t\t\ttime.wHour,  time.wMinute, time.wSecond);\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\twsprintf(buf, \"<MODULE>%s</MODULE><MESSAGE>\", strMod);\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\tif(nLevel == DEBUG_ERROR)\r\n\t\t\tWriteFile(m_hFile,\t\"ERROR - \", 8, &x, 0 );\r\n\t\tWriteFile(m_hFile,\tbuffer2, lstrlen(buffer2), &x, 0 );\r\n\t\tWriteFile(m_hFile,\t\"</MESSAGE></LINE>\", 17, &x, 0 );\r\n\t}\r\n\telse\r\n\t{\r\n\t\twsprintf(buf, \"%d.%03d\\t%02d/%02d/%02d %02d:%02d:%02d\\t%s\\t\\t\", \r\n\t\t\t\t\tdwDiffTime/1000, dwDiffTime%1000, \r\n\t\t\t\t\ttime.wMonth, time.wDay,    time.wYear,\r\n\t\t\t\t\ttime.wHour,  time.wMinute, time.wSecond, strMod);\r\n\r\n\t\t// Write time stamp and formatted string to log-file\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\tif(nLevel == DEBUG_ERROR)\r\n\t\t\tWriteFile(m_hFile,\t\"ERROR - \", 8, &x, 0 );\r\n\t\tWriteFile(m_hFile,\tbuffer, lstrlen(buffer), &x, 0 );\t\r\n\t\tWriteFile(m_hFile,\tCrLf,   lstrlen(CrLf),   &x, 0 );\t\r\n\t}\r\n\r\n\tFlushFileBuffers(m_hFile);\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : ShowLastError\r\n *  Prototype   : void CDebug::ShowLastError() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::ShowLastError() \r\n{\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tchar* lpMsgBuf;\r\n\r\n\tFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,    \r\n\t\tNULL,\r\n\t\tGetLastError(),\r\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language\r\n\t\t(LPTSTR) &lpMsgBuf,    \r\n\t\t0,    \r\n\t\tNULL );\r\n\r\n\tint len = lstrlen(lpMsgBuf)-1;\r\n\r\n\tif (len>0 )\r\n\t{\r\n\t\twhile (len>=0 && (lpMsgBuf[len]==0x0d || lpMsgBuf[len]==0x0a) )\r\n\t\t\tlen--;\r\n\t\tlpMsgBuf[len+1] = 0; \r\n\t\tCDebug::printf (DEBUG_ERROR, \"CDebug::ShowLastError\", \"GetLastError(): %s\", (char*)lpMsgBuf );\r\n\t\tLocalFree(lpMsgBuf ); // Free the buffer.\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : WriteHeader\r\n *  Prototype   : void CDebug::WriteHeader() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::WriteHeader(BOOL bNewFile /* = TRUE */)\r\n{\r\n\tDWORD x;\r\n\tchar buffer[MAX_PATH];\r\n\t\r\n\tif(m_hFile == NULL)\r\n\t\treturn;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tif ( m_bUseXML && bNewFile )\r\n\t{\r\n\t\tstrcpy(buffer, \"<?xml:stylesheet type=\\\"text/xsl\\\" href=\\\"debug.xsl\\\"?><DEBUG>\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstrcpy(buffer, \"Elapsed\\tDate/Time\\t\\tModule\\t\\t\\t\\tDebug\\r\\n\");\r\n\t\tstrcat(buffer, \"=====================================================================================================\\r\\n\");\r\n\t}\r\n\r\n\tSetFilePointer(m_hFile, 0, 0, FILE_END );\r\n\t\r\n\tif(!WriteFile(m_hFile,\tbuffer,    lstrlen(buffer),    &x, 0 ))\r\n\t{\r\n\t\t// Failed but there's not a lot I can do about it.\r\n\t}\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : CheckFileSize\r\n *  Prototype   : void CDebug::CheckFileSize() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::CheckFileSize()\r\n{\r\n\tif( ( m_nMaxFileSize <= 0 ) || ( m_hFile == NULL ) )\r\n\t\treturn;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tDWORD dwStartTime = m_dwStartTime;\r\n\tlong nSize = GetFileSize (m_hFile, NULL); \r\n\r\n\t// Check if the file size is valid\r\n\tif (nSize != 0xFFFFFFFF)\r\n\t{\r\n\t\tif(nSize > m_nMaxFileSize)\r\n\t\t{\r\n\t\t\t// File size is exceeded, wipe file and start again\r\n\t\t\tCloseHandle(m_hFile);\r\n\t\t\tOpenLogFile(TRUE);\r\n\t\t\tWriteHeader();\r\n\t\t}\r\n\t}\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : OpenLogFile\r\n *  Prototype   : BOOL CDebug::OpenLogFile() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : BOOL\r\n *  History     : \r\n */\r\nBOOL CDebug::OpenLogFile(BOOL bOverWrite /* = TRUE */ )\r\n{\r\n\tDWORD x = 0;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\t// Open the file if it exists and truncate to zero bytes\r\n\tHANDLE hFile = CreateFile(m_strFilePath, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tGENERIC_WRITE, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_SHARE_READ|FILE_SHARE_WRITE, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(bOverWrite ? CREATE_ALWAYS : OPEN_ALWAYS), \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_ATTRIBUTE_NORMAL, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t0 );\r\n\t\t\r\n\t// The file isn't there. Disable debugging\r\n\tif(hFile == NULL)\r\n\t{\r\n\t\tm_bEnabled = FALSE;\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tm_hFile = hFile;\r\n\r\n\tif(!bOverWrite && m_bUseXML)\r\n\t{\r\n\t\t// Clear the </DEBUG> tag from the end\r\n\t\tSetFilePointer(m_hFile, 8, 0, FILE_END );\r\n\t\tWriteFile(m_hFile,\t\"        \",    8,    &x, 0 );\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : ReplaceXMLChars\r\n *  Prototype   : void CDebug::ReplaceXMLChars(const char* strInput, int nLen, char* strOutput) \r\n *  Description : Replace invalid characters in XML data\r\n *  Parameters  :                   \r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::ReplaceXMLChars(const char* strInput, int nLen, char* strOutput)\r\n{\r\n\tint nOutIndx = 0;\r\n\tchar ch;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tif(nLen <= 0)\r\n\t\treturn;\r\n\r\n\tfor(int i = 0; i < nLen; i++)\r\n\t{\r\n\t\tch = strInput[i];\r\n\r\n\t\tif(ch == '&')\r\n\t\t\tstrcat(strOutput, \"&amp;\");\r\n\t\telse\r\n\t\t\tstrncat(strOutput, &ch, 1);\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/winamp/ml.h",
    "content": "/*\r\n** Copyright (C) 2003-2006 Nullsoft, Inc.\r\n**\r\n** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held \r\n** liable for any damages arising from the use of this software. \r\n**\r\n** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to \r\n** alter it and redistribute it freely, subject to the following restrictions:\r\n**\r\n**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. \r\n**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n**\r\n**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n**\r\n**   3. This notice may not be removed or altered from any source distribution.\r\n**\r\n*/\r\n\r\n#ifndef _ML_H_\r\n#define _ML_H_\r\n\r\n\r\n#define MLHDR_VER 0x15\r\n\r\n#include <windows.h>\r\n#include <commctrl.h>\r\n#include <stddef.h>\r\n#if (_MSC_VER <= 1200)\r\ntypedef int intptr_t;\r\n#endif\r\n\r\ntypedef struct {\r\n\tint version;\r\n\tchar *description;\r\n\tint (*init)(); // return 0 on success, non-zero for failure (quit WON'T be called) \r\n\tvoid (*quit)();\r\n\r\n\r\n  // return NONZERO if you accept this message as yours, otherwise 0 to pass it \r\n  // to other plugins\r\n  INT_PTR (*MessageProc)(int message_type, INT_PTR param1, INT_PTR param2, INT_PTR param3); \r\n\t//note: INT_PTR becomes 64bit on 64bit compiles...  if you don't like windows types or caps, you can #include <stddef.h> and use intptr_t\r\n\r\n  //all the following data is filled in by the library\r\n\tHWND hwndWinampParent;\r\n\tHWND hwndLibraryParent; // send this any of the WM_ML_IPC messages\r\n\tHINSTANCE hDllInstance;\r\n} winampMediaLibraryPlugin;\r\n\r\n\r\n// messages your plugin may receive on MessageProc()\r\n\r\n#define ML_MSG_TREE_BEGIN 0x100\r\n  #define ML_MSG_TREE_ONCREATEVIEW 0x100 // param1 = param of tree item, param2 is HWND of parent. return HWND if it is us\r\n\r\n  #define ML_MSG_TREE_ONCLICK  0x101 // param1 = param of tree item, param2 = action type (below), param3 = HWND of main window\r\n    #define ML_ACTION_RCLICK 0    // return value should be nonzero if ours\r\n    #define ML_ACTION_DBLCLICK 1\r\n    #define ML_ACTION_ENTER 2\r\n\r\n  #define ML_MSG_TREE_ONDROPTARGET 0x102 // param1 = param of tree item, param2 = type of drop (ML_TYPE_*), param3 = pointer to data (or NULL if querying).\r\n                                      // return -1 if not allowed, 1 if allowed, or 0 if not our tree item\r\n\r\n  #define ML_MSG_TREE_ONDRAG 0x103 // param1 = param of tree item, param2 = POINT * to the mouse position, and param3 = (int *) to the type\r\n                                  // set *(int*)param3 to the ML_TYPE you want and return 1, if you support drag&drop, or -1 to prevent d&d.\r\n\r\n  #define ML_MSG_TREE_ONDROP 0x104 // param1 = param of tree item, param2 = POINT * to the mouse position\r\n                                  // if you support dropping, send the appropriate ML_IPC_HANDLEDROP using SendMessage() and return 1, otherwise return -1.\r\n\r\n  #define  ML_MSG_TREE_ONKEYDOWN 0x105  // Send when key pressed \r\n\t\t\t\t\t\t\t\t\t\t// param1 = param of tree item;\r\n\t\t\t\t\t\t\t\t\t\t// param2 = pointer to NMTVKEYDOWN\r\n\t\t\t\t\t\t\t\t\t\t// param3 = tree hwnd\r\n\t\t\t\t\t\t\t\t\t\t// return 0 if it's not yours, 1 if it is\r\n\r\n#define ML_MSG_TREE_END 0x1FF // end of tree specific messages\r\n\r\n\r\n\r\n#define ML_MSG_ONSENDTOBUILD 0x300 // you get sent this when the sendto menu gets built\r\n// param1 = type of source, param2 param to pass as context to ML_IPC_ADDTOSENDTO\r\n// be sure to return 0 to allow other plugins to add their context menus\r\n\r\n\r\n// if your sendto item is selected, you will get this with your param3 == your user32 (preferably some\r\n// unique identifier (like your plugin message proc). See ML_IPC_ADDTOSENDTO\r\n#define ML_MSG_ONSENDTOSELECT 0x301\r\n// param1 = type of source, param2 = data, param3 = user32\r\n\r\n// return TRUE and do a config dialog using param1 as a HWND parent for this one\r\n#define ML_MSG_CONFIG 0x400\r\n\r\n// types for drag and drop\r\n\r\n#define ML_TYPE_ITEMRECORDLIST 0 // if this, cast obj to itemRecordList\r\n#define ML_TYPE_FILENAMES 1 // double NULL terminated char * to files, URLS, or playlists\r\n#define ML_TYPE_STREAMNAMES 2 // double NULL terminated char * to URLS, or playlists ( effectively the same as ML_TYPE_FILENAMES, but not for files)\r\n#define ML_TYPE_CDTRACKS 3 // if this, cast obj to itemRecordList (CD tracks) -- filenames should be cda://<drive letter>,<track index>. artist/album/title might be valid (CDDB)\r\n#define ML_TYPE_QUERYSTRING 4 // char * to a query string\r\n#define ML_TYPE_PLAYLIST 5 // mlPlaylist *\r\n#define ML_TYPE_ITEMRECORDLISTW 6 // if this, cast obj to itemRecordListW\r\n#define ML_TYPE_TREEITEM 69 // uhh?\r\n\r\ntypedef struct\r\n{\r\n\tconst wchar_t *filename;\r\n\tconst wchar_t *title;\r\n\t// only fill in the following two if already know.  don't calculate it just for the struct. \r\n\t// put -1 for \"don't know\"\r\n\tint numItems; \r\n\tint length; // in seconds.  \r\n} mlPlaylist;\r\n\r\n// if you wish to put your tree items under \"devices\", use this constant for ML_IPC_ADDTREEITEM\r\n#define ML_TREEVIEW_ID_DEVICES 10000\r\n\r\n\r\n\r\n// children communicate back to the media library by SendMessage(plugin.hwndLibraryParent,WM_ML_IPC,param,ML_IPC_X);\r\n#define WM_ML_IPC WM_USER+0x1000\r\n\r\n \r\n#define ML_IPC_GETCURRENTVIEW\t0x090 // Returns HWND to the currently selected view or NULL if nothing selected or error. (WA 5.22 and higher)\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// Old Tree Item API  (deprecated)\r\n//\r\n#define ML_IPC_ADDTREEITEM\t\t0x0101 // pass mlAddTreeItemStruct as the param\r\n#define ML_IPC_SETTREEITEM\t\t0x0102 // pass mlAddTreeItemStruct with id valid\r\n#define ML_IPC_DELTREEITEM\t\t0x0103 // pass param of tree item to remove\r\n#define ML_IPC_GETCURTREEITEM\t0x0104 // returns current tree item param or 0 if none\r\n#define ML_IPC_SETCURTREEITEM\t0x0105 // selects the tree item passed, returns 1 if found, 0 if not\r\n#define ML_IPC_GETTREE\t\t\t0x0106 // returns a HMENU with all the tree items. the caller needs to delete the returned handle! pass mlGetTreeStruct as the param\r\n\r\n/* deprecated. Use MLTREEITEM instead */\r\ntypedef struct {\r\n  INT_PTR parent_id; //0=root, or ML_TREEVIEW_ID_*\r\n  char *title;\r\n  int has_children;\r\n  INT_PTR this_id; //filled in by the library on ML_IPC_ADDTREEITEM\r\n} mlAddTreeItemStruct;\r\n\r\ntypedef struct {\r\n  int item_start;   // TREE_PLAYLISTS, TREE_DEVICES...\r\n  int cmd_offset;   // menu command offset if you need to make a command proxy, 0 otherwise\r\n  int max_numitems; // maximum number of items you wish to insert or -1 for no limit\r\n} mlGetTreeStruct;\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n/// For Predixis, with Love\r\n/// deprecatded (never use!!!)\r\n///\r\n#define ML_IPC_ADDTREEITEM_EX 0x0111 // pass mlAddTreeItemStructEx as the param\r\n#define ML_IPC_SETTREEITEM_EX 0x0112 // pass mlAddTreeItemStructEx with this_id valid\r\n\r\ntypedef struct {\r\n  INT_PTR parent_id; //0=root, or ML_TREEVIEW_ID_*\r\n  char *title;\r\n  int has_children;\r\n  INT_PTR this_id; //filled in by the library on ML_IPC_ADDTREEITEM\r\n  int imageIndex;  // index of the image you want to be associated with your item\r\n} mlAddTreeItemStructEx;\r\n\r\n/// deprecatded (never use!!!)\r\n#define ML_IPC_ADDTREEIMAGE 0x110 // adds tree image to the ml. Use mlAddTreeImageStruct as the param.\r\n/// end of predixis special\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// Tree Item API  (starting from 5.3)\r\n//\r\n#define ML_IPC_TREEITEM_GETHANDLE\t0x120 // Gives you HANDLE to the item with specified ID in the param\r\n#define ML_IPC_TREEITEM_GETCHILD\t\t0x121 // Returns HANDLE to the child item for the item HANDLE specified as a param. \r\n#define ML_IPC_TREEITEM_GETNEXT\t\t0x122 // Returns HANDLE to the next item for the item HANDLE specified as a param.\r\n#define ML_IPC_TREEITEM_GETSELECTED\t0x123 // Returns HANDLE to selected item.\r\n#define ML_IPC_TREEITEM_GETINFO\t\t0x124 // Pass MLTREEITEMINFO as a param. return TRUE - if ok\r\n#define ML_IPC_TREEITEM_SETINFO\t\t0x125 // Pass MLTREEITEMINFO as a param. return TRUE - if ok\r\n#define ML_IPC_TREEITEM_ADD\t\t\t0x126 // Adds new item using MLTREEITEM passed as a param\r\n#define ML_IPC_TREEITEM_DELETE\t\t0x127 // Deletes tree item. Pass HANDLE as a param.\r\n#define ML_IPC_TREEITEM_SELECT\t\t0x128 // Selects tree item. Pass HANDLE as a param. \r\n#define ML_IPC_TREEITEM_GETROOT\t\t0x129 // Gets first item.\r\n#define ML_IPC_TREEITEM_INSERT    0x130 // like ML_IPC_TREEITEM_ADD, but id becomes an \"insert after\" ID\r\n#define ML_IPC_TREEITEM_GETCHILD_ID\t\t0x131 // Returns ID to the child item for the item ID specified as a param. \r\n#define ML_IPC_TREEITEM_GETNEXT_ID\t\t0x132 // Returns ID to the next item for the item ID specified as a param.\r\n#define ML_IPC_TREEITEM_ADDW\t\t\t0x133 // Adds new item using MLTREEITEMW passed as a param\r\n#define ML_IPC_TREEITEM_INSERTW    0x134 // like ML_IPC_TREEITEM_ADDW, but id becomes an \"insert after\" ID\r\n#define ML_IPC_TREEITEM_SETINFOW    0x135 // Pass MLTREEITEMINFOW as a param. return TRUE - if ok\r\n#define MLTI_ROOT\t\t\t(INT_PTR)TVI_ROOT // can be used in ML_IPC_TREEITEM_GETCHILD\r\n\r\ntypedef struct {\r\n  size_t\tsize;\t\t\t// size of this struct\r\n  UINT_PTR\t\tid;\t\t\t\t// depends on contxext\r\n  UINT_PTR\t\tparentId;\t\t// 0 = root, or ML_TREEVIEW_ID_*\r\n  char\t\t*title;\t\t\t// pointer to the buffer contained item name. \r\n  size_t\ttitleLen;\t\t// used for GetInfo \r\n  BOOL\t\thasChildren;\t// TRUE - has children\r\n  int\t\timageIndex;\t\t// index of the associated image\r\n} MLTREEITEM;\r\n\r\ntypedef struct {\r\n  MLTREEITEM\titem;\t// item data\r\n  UINT\t\t\tmask;\t// one or more of MLTI_* flags\r\n  UINT_PTR\t\thandle; // Handle to the item. If handle is NULL item->id will be used\r\n} MLTREEITEMINFO;\r\n\r\ntypedef struct {\r\n  size_t\tsize;\t\t\t// size of this struct\r\n  UINT_PTR\t\tid;\t\t\t\t// depends on context\r\n  UINT_PTR\t\tparentId;\t\t// 0 = root, or ML_TREEVIEW_ID_*\r\n  wchar_t\t*title;\t\t\t// pointer to the buffer contained item name. \r\n  size_t\ttitleLen;\t\t// used for GetInfo \r\n  BOOL\t\thasChildren;\t// TRUE - has children\r\n  int\t\timageIndex;\t\t// index of the associated image\r\n} MLTREEITEMW;\r\n\r\ntypedef struct {\r\n  MLTREEITEMW\titem;\t// item data\r\n  UINT\t\t\tmask;\t// one or more of MLTI_* flags\r\n  UINT_PTR\t\thandle; // Handle to the item. If handle is NULL item->id will be used\r\n} MLTREEITEMINFOW;\r\n// Flags that used in the MLTREEITEMINFO struct\r\n#define MLTI_CHILDREN\tTVIF_CHILDREN\r\n#define MLTI_IMAGE\t\tTVIF_IMAGE\r\n#define MLTI_TEXT\t\tTVIF_TEXT\r\n#define MLTI_ID\t\t\tTVIF_PARAM\r\n\r\n\r\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r\n// Tree image (starting from 5.3)\r\n//\r\n\r\n#define ML_IPC_TREEIMAGE_ADD 0x140 // adds tree image to the ml. Use MLTREEIMAGE as the param.\r\n\r\ntypedef struct \r\n{\r\n\tunsigned char rgbBlue;\r\n\tunsigned char rgbGreen;\r\n\tunsigned char rgbRed;\r\n}COLOR24; // color struct \r\n\r\ntypedef void (*BMPFILTERPROC)(const COLOR24*, const COLOR24*, COLOR24*); // color filter procedure \r\n// you got two colors: color1 and color2 (usualy BG and FG colors) also you as a third parameter\r\n// you get a pixel color value that you need (can) modify  \r\n\r\n#define FILTER_NO\t\t0\r\n#define FILTER_DEFAULT1 1\r\n#define FILTER_DEFAULT2 2\r\n\r\n#define MLTREEIMAGE_NONE\t\t\t\t\t0\r\n#define MLTREEIMAGE_DEFAULT\t\t\t\t\t1\r\n#define MLTREEIMAGE_BRANCH\t\t\t\t\t2   // calculates at the time \t\r\n#define MLTREEIMAGE_BRANCH_EXPANDED\t\t\t3\r\n#define MLTREEIMAGE_BRANCH_COLLAPSED\t\t4\r\n#define MLTREEIMAGE_BRANCH_NOCHILD\t\t\t5\r\n\r\ntypedef struct {\r\n\tHINSTANCE\t\t\t\thinst;\t\t\t\t\t// hInstance\r\n\tint\t\t\t\tresourceId;\t\t\t\t// resource id \r\n\tint\t\t\t\timageIndex;\t\t\t\t// set image to specified index (specify -1 to get a new index back)\r\n\tBMPFILTERPROC\tfilterProc;\t\t\t\t// pointer to the filter proc to use or one of the FILTER_*\r\n\tint\t\t\t\twidth;\t\t\t\t\t// reserved\r\n\tint\t\t\t\theight;\t\t\t\t\t// reserved\r\n} MLTREEIMAGE;   // basicly ml will read your reosurce when it will need to create your image\r\n\r\n#define ML_IPC_NEWPLAYLIST           0x107 // pass hwnd for dialog parent as param\r\n#define ML_IPC_IMPORTPLAYLIST        0x108 // pass hwnd for dialog parent as param\r\n#define ML_IPC_IMPORTCURRENTPLAYLIST 0x109\r\n#define ML_IPC_GETPLAYLISTWND        0x10A\r\n#define ML_IPC_SAVEPLAYLIST          0x10B // pass hwnd for dialog parent as param\r\n#define ML_IPC_OPENPREFS             0x10C\r\n\r\n#define ML_IPC_PLAY_PLAYLIST 0x010D // plays the playlist pointed to by the tree item passed, returns 1 if found, 0 if not\r\n#define ML_IPC_LOAD_PLAYLIST 0x010E // loads the playlist pointed to by the tree item passed into the playlist editor, returns 1 if found, 0 if not\r\n\r\n#define ML_IPC_REFRESH_PREFS 0x10F // this doesn't belong in here \r\n\r\n\r\n/** ------------------ \r\n ** ml_playlists \r\n ** ------------------ */\r\n\r\n#define PL_FLAG_SHOW 1\r\n#define PL_FLAG_SWITCH 2\r\n#define PL_FLAGS_IMPORT 4 // set to have ml_playlists make a copy (only valid for mlAddPlaylist)\r\n#define PL_FLAG_FILL_FILENAME 8 // only valid for mlMakePlaylist\r\n\r\ntypedef struct \r\n{\r\n  size_t size;  // size of this struct\r\n\tconst wchar_t *playlistName; // set to NULL (or empty string) to prompt the user for a name\r\n  const wchar_t *filename;\r\n\tint flags; // see PL_FLAG_* above\r\n\t// the following two items can be optionally filled in (set to -1 otherwise)\r\n\t// if they aren't set, the playlist file will have to be opened and parsed\r\n\t// so prepopulating is faster (assuming if you already know the data)\r\n\tint numItems; // set to -1 if you don't know. \r\n\tint length; // in seconds, set to -1 if you don't know\r\n} mlAddPlaylist;\r\n\r\n#define ML_IPC_PLAYLIST_ADD 0x180 // call to add a new playlist file to the Playlists treeview.  pass an mlAddPlaylist *\r\n\r\ntypedef struct \r\n{\r\n\tsize_t size;  // size of this struct\r\n\tconst wchar_t *playlistName; // set to NULL (or empty string) to prompt the user for a name\r\n  int type; //ML_TYPE_ITEMRECORDLIST, etc\r\n  void *data; // object to load\r\n\tint flags; // see PL_FLAG_* above\r\n\twchar_t filename[MAX_PATH]; // this will get populated if PL_FLAG_FILL_NAME is set\r\n} mlMakePlaylistV2;\r\n\r\n// old structure, here to make it easy to do a sizeof() check\r\ntypedef struct \r\n{\r\n\tsize_t size;  // size of this struct\r\n\tconst wchar_t *playlistName; // set to NULL (or empty string) to prompt the user for a name\r\n  int type; //ML_TYPE_ITEMRECORDLIST, etc\r\n  void *data; // object to load\r\n\tint flags; // see PL_FLAG_* above\r\n} mlMakePlaylist;\r\n\r\n/* Call to add a new playlist to the Playlists treeview.  \r\n   It will be automatically created based on the data you pass\r\n\t type & data follow the same specifications as send-to, drag-and-drop, etc.\r\n*/\r\n#define ML_IPC_PLAYLIST_MAKE 0x181  // call to create a new playlist in the treeview based on passed information.  pass an mlMakePlaylist *\r\n#define ML_IPC_PLAYLIST_COUNT 0x182\r\n#define ML_IPC_PLAYLIST_INFO 0x183 // pass in the struct below. returns \"1\" on success and \"0\" on failure\r\n\r\ntypedef struct\r\n{\r\n\t// you fill this in\r\n\tsize_t size; // size of this struct\r\n\tsize_t playlistNum; // number of the playlist you want to retrieve (0 index)\r\n\t// ml_playlists fills these in\r\n\twchar_t playlistName[128];\r\n\twchar_t filename[MAX_PATH];\r\n\tint numItems;\r\n\tint length; // in seconds\r\n} mlPlaylistInfo;\r\n\r\n\r\n/** ------------------ \r\n ** \r\n ** ------------------ */\r\n\r\n#define ML_IPC_GETFILEINFO 0x0200 // pass it a &itemRecord with a valid filename (and all other fields NULL), and it will try to fill in the rest\r\n#define ML_IPC_FREEFILEINFO 0x0201 // pass it a &itemRecord tha twas filled by getfileinfo, it will free the strings it allocated\r\n\r\n#define ML_IPC_HANDLEDRAG 0x0300 // pass it a &mlDropItemStruct it will handle cursors etc (unless flags has the lowest bit set), and it will set result appropriately:\r\n#define ML_IPC_HANDLEDROP 0x0301 // pass it a &mlDropItemStruct with data on drop:\r\n\r\n#define ML_IPC_SENDTOWINAMP 0x302 // send with a mlSendToWinampStruct:\r\ntypedef struct {\r\n  int type; //ML_TYPE_ITEMRECORDLIST, etc\r\n  void *data; // object to play\r\n\r\n  int enqueue; // low bit set specifies enqueuing, and second bit NOT set specifies that \r\n               // the media library should use its default behavior as the user configured it (if \r\n               // enqueue is the default, the low bit will be flipped by the library)\r\n} mlSendToWinampStruct;\r\n\r\n\r\ntypedef struct {\r\n  char *desc; // str\r\n  intptr_t context; // context passed by ML_MSG_ONSENDTOBUILD\r\n  intptr_t user32; // use some unique ptr in memory, you will get it back in ML_MSG_ONSENDTOSELECT...\r\n} mlAddToSendToStruct;\r\n#define ML_IPC_ADDTOSENDTO 0x0400\r\n\r\ntypedef struct {\r\n  wchar_t *desc; // str\r\n  intptr_t context; // context passed by ML_MSG_ONSENDTOBUILD\r\n  intptr_t user32; // use some unique ptr in memory, you will get it back in ML_MSG_ONSENDTOSELECT...\r\n} mlAddToSendToStructW;\r\n#define ML_IPC_ADDTOSENDTOW 0x0401 // pass mlAddToSendToStructW\r\n\r\n// used to make a submenu in sendto\r\n// pass mlAddToSendToStructW, set desc to 0 to start, set valid desc to end\r\n// user32 is unused \r\n#define ML_IPC_BRANCHSENDTO 0x0402 \r\n\r\n// follow same rules as ML_IPC_ADDTOSENDTOW, but adds to branch instead of main send-to menu\r\n#define ML_IPC_ADDTOBRANCH 0x403  // pass mlAddToSendToStructW\r\n\r\n\r\n\r\n#define ML_IPC_HOOKTITLE 0x0440 // this is like winamp's IPC_HOOK_TITLES... :) param1 is waHookTitleStruct\r\n#define ML_IPC_HOOKEXTINFO 0x441 // called on IPC_GET_EXTENDED_FILE_INFO_HOOKABLE, param1 is extendedFileInfoStruct\r\n#define ML_IPC_HOOKEXTINFOW 0x442 // called on IPC_GET_EXTENDED_FILE_INFO_HOOKABLEW, param1 is extendedFileInfoStructW\r\n#define ML_IPC_HOOKTITLEW 0x0443 // this is like winamp's IPC_HOOK_TITLESW... :) param1 is waHookTitleStructW\r\n\r\n#define ML_HANDLEDRAG_FLAG_NOCURSOR 1\r\n#define ML_HANDLEDRAG_FLAG_NAME 2\r\n\r\ntypedef struct {\r\n  int type; //ML_TYPE_ITEMRECORDLIST, etc\r\n  void *data; // NULL if just querying\r\n\r\n  int result; // filled in by client: -1 if dont allow, 0 if dont know, 1 if allow.\r\n\r\n  POINT p; // cursor pos in screen coordinates\r\n  int flags; \r\n\r\n  char *name; // only valid if ML_HANDLEDRAG_FLAG_NAME\r\n\r\n} mlDropItemStruct;\r\n\r\n\r\n#define ML_IPC_SKIN_LISTVIEW   0x0500 // pass the hwnd of your listview. returns a handle to use with ML_IPC_UNSKIN_LISTVIEW\r\n#define ML_IPC_UNSKIN_LISTVIEW 0x0501 // pass the handle you got from ML_IPC_SKIN_LISTVIEW\r\n#define ML_IPC_LISTVIEW_UPDATE 0x0502 // pass the handle you got from ML_IPC_SKIN_LISTVIEW\r\n#define ML_IPC_LISTVIEW_DISABLEHSCROLL 0x0503 // pass the handle you got from ML_IPC_SKIN_LISTVIEW\r\n#define ML_IPC_LISTVIEW_SHOWSORT\t\t0x0504  // use LV_SKIN_SHOWSORT\r\n#define ML_IPC_LISTVIEW_SORT\t\t\t0x0505  // use LV_SKIN_SORT\r\n\r\ntypedef struct \r\n{\r\n\tINT_PTR listView;\r\n\tBOOL\tshowSort;\r\n} LV_SKIN_SHOWSORT;\r\n\r\ntypedef struct\r\n{\r\n\tINT_PTR listView;\r\n\tint\t\tcolumnIndex;\r\n\tBOOL\tascending;\r\n} LV_SKIN_SORT;\r\n\r\n\r\n#define ML_IPC_SKIN_COMBOBOX   0x0508 // pass the hwnd of your combobox to skin, returns a ahndle to use with ML_IPC_UNSKIN_COMBOBOX\r\n#define ML_IPC_UNSKIN_COMBOBOX 0x0509 // pass the handle from ML_IPC_SKIN_COMBOBOX\r\n\r\n#define ML_IPC_SKIN_WADLG_GETFUNC 0x0600 \r\n    // 1: return int (*WADlg_getColor)(int idx); // pass this an index, returns a RGB value (passing 0 or > 3 returns NULL)\r\n    // 2: return int (*WADlg_handleDialogMsgs)(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); \r\n    // 3: return void (*WADlg_DrawChildWindowBorders)(HWND hwndDlg, int *tab, int tabsize); // each entry in tab would be the id | DCW_*\r\n    // 32: return void (*childresize_init)(HWND hwndDlg, ChildWndResizeItem *list, int num);\r\n    // 33: return void (*childresize_resize)(HWND hwndDlg, ChildWndResizeItem *list, int num);\r\n    // 66: return (HFONT) font to use for dialog elements, if desired (0 otherwise)\r\n   \r\n// itemRecord type for use with ML_TYPE_ITEMRECORDLIST, as well as many other functions\r\ntypedef struct\r\n{\r\n  char *filename;\r\n  char *title;\r\n  char *album;\r\n  char *artist;\r\n  char *comment;\r\n  char *genre;\r\n  int year;\r\n  int track;\r\n  int length;\r\n  char **extended_info;\r\n  // currently defined extended columns (while they are stored internally as integers\r\n  // they are passed using extended_info as strings):\r\n  // use getRecordExtendedItem and setRecordExtendedItem to get/set.\r\n  // for your own internal use, you can set other things, but the following values\r\n  // are what we use at the moment. Note that setting other things will be ignored\r\n  // by ML_IPC_DB*.\r\n  // \r\n  //\"RATING\" file rating. can be 1-5, or 0 or empty for undefined\r\n  //\"PLAYCOUNT\" number of file plays.\r\n  //\"LASTPLAY\" last time played, in standard time_t format\r\n  //\"LASTUPD\" last time updated in library, in standard time_t format\r\n  //\"FILETIME\" last known file time of file, in standard time_t format\r\n  //\"FILESIZE\" last known file size, in kilobytes.\r\n  //\"BITRATE\" file bitrate, in kbps\r\n\t//\"TYPE\" - \"0\" for audio, \"1\" for video\r\n\r\n} itemRecord;\r\n\r\ntypedef struct \r\n{\r\n  itemRecord *Items;\r\n  int Size;\r\n  int Alloc;\r\n} itemRecordList;\r\n\r\n#include <time.h>\r\n\r\ntypedef struct\r\n{\r\n  wchar_t *filename;\r\n  wchar_t *title;\r\n  wchar_t *album;\r\n  wchar_t *artist;\r\n  wchar_t *comment;\r\n  wchar_t *genre;\r\n\twchar_t *albumartist; \r\n\twchar_t *replaygain_album_gain; // these are strings rather than float's to differentiate between '0 gain' and 'not defined'\r\n\twchar_t *replaygain_track_gain; // these are strings rather than float's to differentiate between '0 gain' and 'not defined'\r\n\twchar_t *publisher;\r\n\twchar_t *composer;\r\n  int year;\r\n  int track;\r\n\tint tracks;\r\n  int length;\r\n\tint rating; // file rating. can be 1-5, or 0 for undefined\r\n\tint playcount; // number of file plays.\r\n\t__time64_t lastplay; // last time played, in standard time_t format\r\n\t__time64_t lastupd; // last time updated in library, in standard time_t format\r\n\t__time64_t filetime; // last known file time of file, in standard time_t format\r\n\tint filesize; //last known file size, in kilobytes.\r\n\tint bitrate; // file bitrate, in kbps\r\n\tint type; // 0 for audio, 1 for video\r\n\tint disc; // disc number\r\n\tint discs; // number of discs\r\n\tint bpm;\r\n  wchar_t **extended_info; \r\n  // currently defined extended columns (while they are stored internally as integers\r\n  // they are passed using extended_info as strings):\r\n  // use getRecordExtendedItem and setRecordExtendedItem to get/set.\r\n  // for your own internal use, you can set other things, but the following values\r\n  // are what we use at the moment. Note that setting other things will be ignored\r\n  // by ML_IPC_DB*.\r\n  // \r\n\r\n} itemRecordW;\r\n\r\ntypedef struct \r\n{\r\n  itemRecordW *Items;\r\n  int Size;\r\n  int Alloc;\r\n} itemRecordListW;\r\n\r\n//\r\n// all return 1 on success, -1 on error. or 0 if not supported, maybe?\r\n\r\n// pass these a mlQueryStruct\r\n// results should be zeroed out before running a query, but if you wish you can run multiple queries and \r\n// have it concatenate the results. tho it would be more efficient to just make one query that contains both,\r\n// as running multiple queries might have duplicates etc.\r\n// in general, though, if you need to treat \"results\" as if they are native, you should use\r\n// copyRecordList to save a copy, then free the results using ML_IPC_DB_FREEQUERYRESULTS.\r\n// if you need to keep an exact copy that you will only read (and will not modify), then you can\r\n// use the one in the mlQueryStruct.\r\n\r\n#define ML_IPC_DB_RUNQUERY 0x0700 \r\n#define ML_IPC_DB_RUNQUERY_SEARCH 0x0701 // \"query\" should be interpreted as keyword search instead of query string\r\n#define ML_IPC_DB_RUNQUERY_FILENAME 0x0702 // searches for one exact filename match of \"query\"\r\n#define ML_IPC_DB_RUNQUERY_INDEX 0x703 // retrieves item #(int)query\r\n\r\n#define ML_IPC_DB_FREEQUERYRESULTS 0x0705 // frees memory allocated by ML_IPC_RUNQUERY (empties results)\r\ntypedef struct \r\n{\r\n  char *query;\r\n  int max_results;      // can be 0 for unlimited\r\n  itemRecordList results;\r\n} mlQueryStruct;\r\n\r\n/* Unicode versions of the above */\r\n\r\n#define ML_IPC_DB_RUNQUERYW 0x1700\r\n#define ML_IPC_DB_RUNQUERY_FILENAMEW 0x1702 // searches for one exact filename match of \"query\"\r\n\r\n#define ML_IPC_DB_FREEQUERYRESULTSW 0x1705 // frees memory allocated by ML_IPC_RUNQUERYW (empties results)\r\ntypedef struct \r\n{\r\n  wchar_t *query;\r\n  int max_results;      // can be 0 for unlimited\r\n  itemRecordListW results;\r\n} mlQueryStructW;\r\n\r\n/* ----------------------------- */\r\n\r\n// pass these an (itemRecord *) to add/update.\r\n// note that any NULL fields in the itemRecord won't be updated, \r\n// and year, track, or length of -1 prevents updating as well.\r\n#define ML_IPC_DB_UPDATEITEM 0x0706    // returns -2 if item not found in db\r\n#define ML_IPC_DB_ADDORUPDATEITEM 0x0707\r\n\r\n#define ML_IPC_DB_REMOVEITEM 0x0708 // pass a char * to the filename to remove. returns -2 if file not found in db.\r\n\r\ntypedef struct \r\n{\r\n  char*  fileName;   // file name to add\r\n  int    meta_mode;  // metadata get mode (0 - don't use metadata, 1 - use metadata; -1 - read from user settings (ini file)\r\n  int    gues_mode;  // metadata guessing mode (0 - smart, 1 - simple; 2 - no, -1 - read from user settings (ini file)\r\n} LMDB_FILE_ADD_INFO;\r\n\r\n#define ML_IPC_DB_UPDATEFILE 0x0710         // Update File in the Local Media Data Base (return -2 if file record not found)\r\n#define ML_IPC_DB_ADDORUPDATEFILE 0x0711      // Adds or Updates File in the Local Media Data Base.\r\n\r\n/* Unicode versions of the above */\r\n\r\n// pass these an (itemRecordW *) to add/update.\r\n// note that any NULL fields in the itemRecordW won't be updated, \r\n// and year, track, or length of -1 prevents updating as well.\r\n#define ML_IPC_DB_UPDATEITEMW 0x1706    // returns -2 if item not found in db\r\n#define ML_IPC_DB_ADDORUPDATEITEMW 0x1707\r\n\r\ntypedef struct \r\n{\r\n  wchar_t*  fileName;   // file name to add\r\n  int    meta_mode;  // metadata get mode (0 - don't use metadata, 1 - use metadata; -1 - read from user settings (ini file)\r\n  int    gues_mode;  // metadata guessing mode (0 - smart, 1 - simple; 2 - no, -1 - read from user settings (ini file)\r\n} LMDB_FILE_ADD_INFOW;\r\n\r\n#define ML_IPC_DB_UPDATEFILEW 0x1710         // Update File in the Local Media Data Base (return -2 if file record not found) NOTE that this call is broken on 5.33.  Only use on 5.34+\r\n#define ML_IPC_DB_ADDORUPDATEFILEW 0x1711      // Adds or Updates File in the Local Media Data Base.\r\n\r\n/* ----------------------------- */\r\n\r\n\r\n#define ML_IPC_DB_SYNCDB 0x0709 // sync db if dirty flags are set. good to do after a batch of updates.\r\n\r\n\r\n\r\n\r\n// these return 0 if unsupported, -1 if failed, 1 if succeeded\r\n\r\n// pass a winampMediaLibraryPlugin *. Will not call plugin's init() func. \r\n// YOU MUST set winampMediaLibraryPlugin->hDllInstance to NULL, and version to MLHDR_VER\r\n// 5.25+:  You can set hDllInstance to valid value.  \r\n//         This IPC will return -1 on failure, so a good check against old verions\r\n//         is to try with hDllInstance set, if it returns -1, try again with hDllInstance=0\r\n#define ML_IPC_ADD_PLUGIN 0x0750 \r\n#define ML_IPC_REMOVE_PLUGIN 0x0751 // winampMediaLibraryPlugin * of plugin to remove. Will not call plugin's quit() func\r\n\r\n#define ML_IPC_SEND_PLUGIN_MESSAGE 0x0752 // sends message to plugins (wParam = 0, lParam = pointer to the pluginMessage struct)\r\n// pluginMessage struct\r\ntypedef struct {\r\n  int messageType;\r\n  INT_PTR param1;\r\n  INT_PTR param2;\r\n  INT_PTR param3;\r\n} pluginMessage;\r\n\r\n#define ML_IPC_ENSURE_VISIBLE 0x753 // ensures that the media library is visible\r\n#define ML_IPC_IS_VISIBLE 0x754 // queries the current visibility status\r\n\r\n#define ML_IPC_GET_PARENTAL_RATING 0x755 \r\n\r\n#define ML_IPC_TOGGLE_VISIBLE 0x756\r\n\r\n// this gets sent to any child windows of the library windows, and then (if not\r\n// handled) the library window itself\r\n\r\n#define WM_ML_CHILDIPC WM_APP+0x800 // avoids conflicts with any windows controls\r\n#define ML_CHILDIPC_DROPITEM 0x100         // lParam = 100, wParam = &mlDropItemStruct\r\n\r\n// current item ratings\r\n#define ML_IPC_SETRATING 0x0900 // lParam = 0 to 5, rates current track -- inserts it in the db if it's not in it yet \r\n#define ML_IPC_GETRATING 0x0901 // return the current track's rating or 0 if not in db/no rating\r\n\r\n// playlist entry rating\r\ntypedef struct {\r\n  int plentry;\r\n  int rating;\r\n} pl_set_rating;\r\n\r\n#define ML_IPC_PL_SETRATING 0x0902 // lParam = pointer to pl_set_rating struct\r\n#define ML_IPC_PL_GETRATING 0x0903 // lParam = playlist entry, returns the rating or 0 if not in db/no rating\r\n\r\ntypedef struct {\r\n  HWND dialog_parent;              // Use this window as a parent for the query editor dialog\r\n  const char *query;               // The query to edit, or \"\" / null for new query\r\n} ml_editquery;                 \r\n\r\n#define ML_IPC_EDITQUERY    0x904  // lParam = pointer to ml_editquery struct, returns 0 if edition was canceled and 1 on success\r\n                                   // After returning, and if ok was clicked, the struct contains a pointer to the edited query. this pointer is static : \r\n                                   // - do *not* free it\r\n                                   // - if you need to keep it around, strdup it, as it may be changed later by other plugins calling ML_IPC_EDITQUERY.\r\n\r\ntypedef struct {                \r\n  HWND dialog_parent;              // Use this window as a parent for the view editor dialog\r\n  const char *query;               // The query to edit, or \"\" / null for new views\r\n  const char *name;                // Name of the view (ignored for new views)\r\n  int mode;                        // View mode (0=simple view, 1=artist/album view, -1=hide mode radio boxes)\r\n} ml_editview;                 \r\n\r\n#define ML_IPC_EDITVIEW     0x905  // lParam = pointer to ml_editview struct, returns 0 if edition was canceled and 1 on success\r\n                                   // After returning, and if ok was clicked, the struct contains the edited values. String pointers are static: \r\n                                   // - do *not* free them \r\n                                   // - if you need to keep them around, strdup them, as they may be changed later by other plugins calling ML_IPC_EDITQUERY.\r\n\r\n#define ML_IPC_SET_FILE_RATING 0x0906 // lParam = 0 to 5, rates current track -- inserts it in the db if it's not in it yet \r\n#define ML_IPC_GET_FILE_RATING 0x0907 // return the current track's rating or 0 if not in db/no rating\r\n\r\n// playlist entry rating\r\ntypedef struct {\r\n  const char* fileName;\r\n  int newRating;\r\n} file_set_rating;\r\n\r\n// utility functions in ml_lib.cpp\r\nvoid freeRecordList(itemRecordList *obj);\r\nvoid emptyRecordList(itemRecordList *obj); // does not free Items\r\nvoid freeRecord(itemRecord *p);\r\n\r\n// if out has items in it copyRecordList will append \"in\" to \"out\".\r\nvoid copyRecordList(itemRecordList *out, itemRecordList *in);\r\n//copies a record\r\nvoid copyRecord(itemRecord *out, itemRecord *in);\r\n\r\nvoid allocRecordList(itemRecordList *obj, int newsize, int granularity\r\n#ifdef __cplusplus\r\n=1024\r\n#endif\r\n);\r\n\r\nchar *getRecordExtendedItem(const itemRecord *item, const char *name);\r\nWCHAR *getRecordExtendedItemW(const itemRecordW *item, const CHAR *name);\r\nvoid setRecordExtendedItem(itemRecord *item, const char *name, char *value);\r\n\r\n#ifdef __cplusplus\r\n// utility functions for itemRecordListW\r\nvoid freeRecordList(itemRecordListW *obj);\r\nvoid emptyRecordList(itemRecordListW *obj); // does not free Items\r\nvoid freeRecord(itemRecordW *p);\r\n\r\nwchar_t *getRecordExtendedItem(const itemRecordW *item, const wchar_t *name);\r\nvoid setRecordExtendedItem(itemRecordW *item, const wchar_t *name, wchar_t *value);\r\n\r\nvoid allocRecordList(itemRecordListW *obj, int newsize, int granularity=1024);\r\n#endif\r\n\r\nvoid convertRecord(itemRecord *output, const itemRecordW *input);\r\n\r\n#define ML_IPC_GRACENOTE 0x1000\r\n#define GRACENOTE_TUID 1\r\n#define GRACENOTE_IS_WORKING 2\r\n#define GRACENOTE_DO_TIMER_STUFF 3\r\n#define GRACENOTE_CANCEL_REQUEST 4\r\n\r\n\r\n\r\n#endif//_ML_H_"
  },
  {
    "path": "plugins/winamp/ml_lib.cpp",
    "content": "/*\r\n** Copyright (C) 2003-2006 Nullsoft, Inc.\r\n**\r\n** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held \r\n** liable for any damages arising from the use of this software. \r\n**\r\n** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to \r\n** alter it and redistribute it freely, subject to the following restrictions:\r\n**\r\n**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. \r\n**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n**\r\n**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n**\r\n**   3. This notice may not be removed or altered from any source distribution.\r\n**\r\n*/\r\n\r\n#include \"StdAfx.h\"\r\n#include \"ml.h\"\r\n\r\nvoid freeRecord(itemRecord *p) {\r\n  free(p->title);\r\n  free(p->artist);\r\n  free(p->comment);\r\n  free(p->album);\r\n  free(p->genre);\r\n  free(p->filename);\r\n  if (p->extended_info)\r\n  {\r\n    int x=0;\r\n    for (x = 0; p->extended_info[x]; x ++)\r\n      free(p->extended_info[x]);\r\n    free(p->extended_info);\r\n  }\r\n  memset(p,0,sizeof(itemRecord));\r\n}\r\n\r\nvoid freeRecordList(itemRecordList *obj)\r\n{\r\n  emptyRecordList(obj);\r\n  free(obj->Items);\r\n  obj->Items=0;\r\n  obj->Alloc=obj->Size=0;\r\n}\r\n\r\nvoid emptyRecordList(itemRecordList *obj)\r\n{\r\n  itemRecord *p=obj->Items;\r\n  while (obj->Size-->0)\r\n  {\r\n    freeRecord(p);\r\n    p++;\r\n  }\r\n  obj->Size=0;\r\n}\r\n\r\nvoid allocRecordList(itemRecordList *obj, int newsize, int granularity)\r\n{\r\n  if (newsize < obj->Alloc || newsize < obj->Size) return;\r\n\r\n  obj->Alloc=newsize+granularity;\r\n  obj->Items=(itemRecord*)realloc(obj->Items,sizeof(itemRecord)*obj->Alloc);\r\n  if (!obj->Items) obj->Alloc=0;\r\n}\r\n\r\nvoid copyRecord(itemRecord *out, itemRecord *in)\r\n{\r\n  int y;\r\n#define COPYSTR(FOO) out->FOO = in->FOO ? strdup(in->FOO) : 0;\r\n  COPYSTR(filename)\r\n  COPYSTR(title)\r\n  COPYSTR(album)\r\n  COPYSTR(artist)\r\n  COPYSTR(comment)\r\n  COPYSTR(genre)\r\n  out->year=in->year;\r\n  out->track=in->track;\r\n  out->length=in->length;\r\n#undef COPYSTR\r\n  out->extended_info=0;\r\n\r\n  if (in->extended_info) for (y = 0; in->extended_info[y]; y ++)\r\n  {\r\n    char *p=in->extended_info[y];\r\n    if (*p) setRecordExtendedItem(out,p,p+strlen(p)+1);\r\n  }\r\n}\r\n\r\nvoid copyRecordList(itemRecordList *out, itemRecordList *in)\r\n{\r\n  int x;\r\n  allocRecordList(out,out->Size+in->Size,0);\r\n  if (!out->Items) return;\r\n  for (x = 0; x < in->Size; x ++)\r\n  {\r\n    copyRecord(&out->Items[out->Size++],&in->Items[x]);\r\n  }\r\n}\r\n\r\nchar *getRecordExtendedItem(const itemRecord *item, const char *name)\r\n{\r\n  int x=0;\r\n  if (item->extended_info) for (x = 0; item->extended_info[x]; x ++)\r\n  {\r\n    if (!stricmp(item->extended_info[x],name))\r\n      return item->extended_info[x]+strlen(name)+1;\r\n  }\r\n  return NULL;\r\n}\r\n\r\nvoid setRecordExtendedItem(itemRecord *item, const char *name, char *value)\r\n{\r\n  int x=0;\r\n  if (item->extended_info) for (x = 0; item->extended_info[x]; x ++)\r\n  {\r\n    if (!stricmp(item->extended_info[x],name))\r\n    {\r\n      if (strlen(value)>strlen(item->extended_info[x]+strlen(name)+1))\r\n      {\r\n        free(item->extended_info[x]);\r\n        item->extended_info[x]=(char*)malloc(strlen(name)+strlen(value)+2);\r\n      }\r\n      strcpy(item->extended_info[x],name);\r\n      strcpy(item->extended_info[x]+strlen(name)+1,value);\r\n      return;\r\n    }\r\n  }\r\n  // x=number of valid items.\r\n  item->extended_info=(char**)realloc(item->extended_info,sizeof(char*) * (x+2));\r\n  if (item->extended_info)\r\n  {\r\n    item->extended_info[x]=(char*)malloc(strlen(name)+strlen(value)+2);\r\n    strcpy(item->extended_info[x],name);\r\n    strcpy(item->extended_info[x]+strlen(name)+1,value);\r\n\r\n    item->extended_info[x+1]=0;\r\n  }\r\n}\r\n\r\n/*\r\n---------------------------------- \r\nwide version starts here\r\n---------------------------------- \r\n*/\r\n \r\n void freeRecord(itemRecordW *p) {\r\n  free(p->title);\r\n  free(p->artist);\r\n  free(p->comment);\r\n  free(p->album);\r\n  free(p->genre);\r\n  free(p->filename);\r\n\tfree(p->albumartist); \r\n\tfree(p->replaygain_album_gain); \r\n\tfree(p->replaygain_track_gain); \r\n\tfree(p->publisher);\r\n\tfree(p->composer);\r\n  if (p->extended_info)\r\n  {\r\n    int x=0;\r\n    for (x = 0; p->extended_info[x]; x ++)\r\n      free(p->extended_info[x]);\r\n    free(p->extended_info);\r\n  }\r\n  memset(p,0,sizeof(itemRecordW));\r\n}\r\n\r\nvoid freeRecordList(itemRecordListW *obj)\r\n{\r\n  emptyRecordList(obj);\r\n  free(obj->Items);\r\n  obj->Items=0;\r\n  obj->Alloc=obj->Size=0;\r\n}\r\n\r\nvoid emptyRecordList(itemRecordListW *obj)\r\n{\r\n  itemRecordW *p=obj->Items;\r\n  while (obj->Size-->0)\r\n  {\r\n    freeRecord(p);\r\n    p++;\r\n  }\r\n  obj->Size=0;\r\n}\r\n\r\nvoid allocRecordList(itemRecordListW *obj, int newsize, int granularity)\r\n{\r\n  if (newsize < obj->Alloc || newsize < obj->Size) return;\r\n\r\n  obj->Alloc=newsize+granularity;\r\n  obj->Items=(itemRecordW*)realloc(obj->Items,sizeof(itemRecordW)*obj->Alloc);\r\n  if (!obj->Items) obj->Alloc=0;\r\n}\r\n\r\nvoid copyRecord(itemRecordW *out, itemRecordW *in)\r\n{\r\n  int y;\r\n#define COPYSTR(FOO) out->FOO = in->FOO ? wcsdup(in->FOO) : 0;\r\n#define COPY(FOO) out->FOO = in->FOO;\r\n  COPYSTR(filename)\r\n  COPYSTR(title)\r\n  COPYSTR(album)\r\n  COPYSTR(artist)\r\n  COPYSTR(comment)\r\n  COPYSTR(genre)\r\n\tCOPYSTR(albumartist); \r\n\tCOPYSTR(replaygain_album_gain); \r\n\tCOPYSTR(replaygain_track_gain); \r\n\tCOPYSTR(publisher);\r\n\tCOPYSTR(composer);\r\n\tCOPY(year);\r\n\tCOPY(track);\r\n\tCOPY(tracks);\r\n\tCOPY(length);\r\n\tCOPY(rating);\r\n  COPY(playcount); \r\n\tCOPY(lastplay); \r\n\tCOPY(lastupd); \r\n\tCOPY(filetime);\r\n\tCOPY(filesize);\r\n\tCOPY(bitrate); \r\n\tCOPY(type); \r\n\tCOPY(disc); \r\n\tCOPY(bpm);\r\n\tCOPY(discs);  \r\n#undef COPYSTR\r\n  out->extended_info=0;\r\n\r\n  if (in->extended_info) for (y = 0; in->extended_info[y]; y ++)\r\n  {\r\n    wchar_t *p=in->extended_info[y];\r\n    if (*p) setRecordExtendedItem(out,p,p+wcslen(p)+1);\r\n  }\r\n}\r\n\r\nvoid copyRecordList(itemRecordListW *out, itemRecordListW *in)\r\n{\r\n  int x;\r\n  allocRecordList(out,out->Size+in->Size,0);\r\n  if (!out->Items) return;\r\n  for (x = 0; x < in->Size; x ++)\r\n  {\r\n    copyRecord(&out->Items[out->Size++],&in->Items[x]);\r\n  }\r\n}\r\n\r\nwchar_t *getRecordExtendedItem(const itemRecordW *item, const wchar_t *name)\r\n{\r\n  int x=0;\r\n  if (item->extended_info) for (x = 0; item->extended_info[x]; x ++)\r\n  {\r\n    if (!wcsicmp(item->extended_info[x],name))\r\n      return item->extended_info[x]+wcslen(name)+1;\r\n  }\r\n  return NULL;\r\n}\r\n\r\nvoid setRecordExtendedItem(itemRecordW *item, const wchar_t *name, wchar_t *value)\r\n{\r\n  int x=0;\r\n  if (item->extended_info) for (x = 0; item->extended_info[x]; x ++)\r\n  {\r\n    if (!wcsicmp(item->extended_info[x],name))\r\n    {\r\n      if (wcslen(value)>wcslen(item->extended_info[x]+wcslen(name)+1))\r\n      {\r\n        free(item->extended_info[x]);\r\n        item->extended_info[x]=(wchar_t*)malloc((wcslen(name)+wcslen(value)+2)*sizeof(wchar_t));\r\n      }\r\n      wcscpy(item->extended_info[x],name);\r\n      wcscpy(item->extended_info[x]+wcslen(name)+1,value);\r\n      return;\r\n    }\r\n  }\r\n  // x=number of valid items.\r\n  item->extended_info=(wchar_t**)realloc(item->extended_info,sizeof(wchar_t*) * (x+2));\r\n  if (item->extended_info)\r\n  {\r\n    item->extended_info[x]=(wchar_t*)malloc((wcslen(name)+wcslen(value)+2)*sizeof(wchar_t));\r\n    wcscpy(item->extended_info[x],name);\r\n    wcscpy(item->extended_info[x]+wcslen(name)+1,value);\r\n\r\n    item->extended_info[x+1]=0;\r\n  }\r\n}\r\n// TODO: redo this without AutoChar\r\n#include \"AutoChar.h\"\r\n#define COPY_EXTENDED_STR(field) if (input-> ## field && input-> ## field ## [0]) setRecordExtendedItem(output, #field, AutoChar(input-> ## field));\r\n#define COPY_EXTENDED_INT(field) if (input->##field > 0) { char temp[64]; itoa(input->##field, temp, 10); setRecordExtendedItem(output, #field, temp); }\r\n#define COPY_EXTENDED_INT0(field) if (input->##field >= 0) { char temp[64]; itoa(input->##field, temp, 10); setRecordExtendedItem(output, #field, temp); }\r\nvoid convertRecord(itemRecord *output, const itemRecordW *input)\r\n{\r\n\toutput->filename=AutoCharDup(input->filename);\r\n  output->title=AutoCharDup(input->title);\r\n  output->album=AutoCharDup(input->album);\r\n  output->artist=AutoCharDup(input->artist);\r\n  output->comment=AutoCharDup(input->comment);\r\n  output->genre=AutoCharDup(input->genre);\r\n  output->year=input->year;\r\n  output->track=input->track;\r\n  output->length=input->length;\r\n\toutput->extended_info=0;\t\r\n\tCOPY_EXTENDED_STR(albumartist);\r\n\tCOPY_EXTENDED_STR(replaygain_album_gain);\r\n\tCOPY_EXTENDED_STR(replaygain_track_gain);\r\n\tCOPY_EXTENDED_STR(publisher);\r\n\tCOPY_EXTENDED_STR(composer);\r\n\tCOPY_EXTENDED_INT(tracks);\r\n\tCOPY_EXTENDED_INT(rating);\r\n\tCOPY_EXTENDED_INT(playcount);\r\n\tCOPY_EXTENDED_INT(lastplay);\r\n\tCOPY_EXTENDED_INT(lastupd);\r\n\tCOPY_EXTENDED_INT(filetime);\r\n\tCOPY_EXTENDED_INT(filesize);\r\n\tCOPY_EXTENDED_INT0(type);\r\n\tCOPY_EXTENDED_INT(disc);\r\n\tCOPY_EXTENDED_INT(discs);\r\n\tCOPY_EXTENDED_INT(bpm);\r\n  // TODO: copy input's extended fields\r\n}"
  },
  {
    "path": "plugins/winamp/res/Gen_AudioScrobbler.rc2",
    "content": "//\r\n// GEN_AUDIOSCROBBLER.RC2 - resources Microsoft Visual C++ does not edit directly\r\n//\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n\t#error this file is not editable by Microsoft Visual C++\r\n#endif //APSTUDIO_INVOKED\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Add manually edited resources here...\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n"
  },
  {
    "path": "plugins/winamp/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by Gen_AudioScrobbler.rc\r\n//\r\n#define IDC_HELP_BUTTON                 3\r\n#define IDC_VIEW_LOG                    4\r\n#define IDD_ABOUT                       100\r\n#define IDC_DRAG                        205\r\n#define IDC_HSCROLL                     206\r\n#define IDC_CLOSE                       207\r\n#define IDC_DEFAULT_ARROW               208\r\n#define IDC_VSCROLL                     209\r\n#define IDC_RESIZE                      210\r\n#define IDC_NEWS_FRAME                  1001\r\n#define IDC_USERNAME                    1003\r\n#define IDC_PASSWORD                    1004\r\n#define IDC_MAX_LOG_FILE_SIZE           1005\r\n#define IDC_PROXY_USER                  1006\r\n#define IDC_PROXY_PASS                  1007\r\n#define IDC_PROXY_SERVER                1008\r\n#define IDC_WEB                         1009\r\n#define IDC_PROXY_PORT                  1010\r\n#define IDC_UPDATE_MESSAGE              1011\r\n#define IDC_MESSAGE1                    1012\r\n#define IDC_MESSGE2                     1013\r\n#define IDC_LOCAL_CONTROL_VER           1015\r\n#define IDC_PROGRESS                    1016\r\n#define IDC_PASSWORD_MSG                1017\r\n#define IDC_APPLY                       1018\r\n#define IDC_ENABLE                      1020\r\n#define IDC_FORCE_CONNECT               1021\r\n#define IDC_SHOW_MESSAGES               1022\r\n#define IDC_SHOW_UPGRADE_INFO           1022\r\n#define IDC_IGNORE_HTTP                 1023\r\n#define IDC_SHOW_E                      1023\r\n#define IDC_SHOW_ERRORS                 1023\r\n#define IDC_SHOW_IMP_MSGS               1024\r\n#define IDC_CACHE_STATS                 3000\r\n#define IDC_VERSION                     3001\r\n#define IDC_SERVER_STATS                3002\r\n#define IDC_USE_PROXY                   3005\r\n#define IDC_USE_PROXY_AUTH              3006\r\n#define IDC_WEB_BROWSER                 3007\r\n#define IDC_WEBBROWSER                  3008\r\n#define IDC_COPYRIGHT                   3009\r\n#define IDC_PROXY_SERVER_FRAME          3010\r\n#define IDC_PROXY_AUTH_FRAME            3011\r\n#define IDC_LIST                        3012\r\n#define IDC_REMOVE_ALL                  3013\r\n#define IDC_REMOVE                      3014\r\n#define IDC_ADD                         3015\r\n#define IDC_NEW_DIR                     3016\r\n#define IDC_BROWSE                      3017\r\n#define IDC_INCLUDE_EXCLUDE             3021\r\n#define IDC_RADIO3                      3022\r\n#define IDC_EXCLUSIONS                  3023\r\n#define IDC_CLEAR_PASS                  3024\r\n#define IDC_RECENT_LABEL                3026\r\n#define IDC_INCLUDE_LIST                3027\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        3013\r\n#define _APS_NEXT_COMMAND_VALUE         32771\r\n#define _APS_NEXT_CONTROL_VALUE         3028\r\n#define _APS_NEXT_SYMED_VALUE           3030\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/winamp/wa_dlg.h",
    "content": "/*\r\n** Copyright (C) 2003 Nullsoft, Inc.\r\n**\r\n** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held \r\n** liable for any damages arising from the use of this software. \r\n**\r\n** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to \r\n** alter it and redistribute it freely, subject to the following restrictions:\r\n**\r\n**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. \r\n**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n**\r\n**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n**\r\n**   3. This notice may not be removed or altered from any source distribution.\r\n**\r\n*/\r\n\r\n#ifndef _WA_DLG_H_\r\n#define _WA_DLG_H_\r\n\r\n#include \"wa_ipc.h\"\r\n\r\n/*\r\n  \r\n  dont know where to put this yet :)\r\n       1) gen.bmp has a generic window frame for plugins to use.\r\n          its format is similar to the minibrowser's.\r\n          In addition gen.bmp includes a font for the titlebar, in both\r\n          highlight and no-highlight modes. The font is variable width,\r\n          and it uses the first color before the letter A as the delimiter.\r\n          The no-highlight form of letter must be the same width as the\r\n          highlight form.\r\n       2) genex.bmp has button and scrollbar images, as well as some individual\r\n          pixels that describe the colors for the dialog. The button and\r\n          scrollbar images should be self explanatory (note that the buttons\r\n          have 4 pixel sized edges that are not stretched, and the center is\r\n          stretched), and the scrollbars do something similar.\r\n          The colors start at (48,0) and run every other pixel. The meaning\r\n          of each pixel is:\r\n            x=48: item background (background to edits, listviews etc)\r\n            x=50: item foreground (text color of edit/listview, etc)\r\n            x=52: window background (used to set the bg color for the dialog)\r\n            x=54: button text color\r\n            x=56: window text color\r\n            x=58: color of dividers and sunken borders\r\n            x=60: selection color for listviews/playlists/etc\r\n            x=62: listview header background color\r\n            x=64: listview header text color\r\n            x=66: listview header frame top color\r\n            x=68: listview header frame middle color\r\n            x=70: listview header frame bottom color\r\n            x=72: listview header empty color\r\n            x=74: scrollbar foreground color\r\n            x=76: scrollbar background color\r\n            x=78: inverse scrollbar foreground color\r\n            x=80: inverse scrollbar background color\r\n            x=82: scrollbar dead area color\r\n*/\r\n\r\n\r\n#define DCW_SUNKENBORDER 0x00010000\r\n#define DCW_DIVIDER 0x00020000\r\n\r\nenum\r\n{\r\n  WADLG_ITEMBG,\r\n  WADLG_ITEMFG,\r\n  WADLG_WNDBG,\r\n  WADLG_BUTTONFG,\r\n  WADLG_WNDFG,\r\n  WADLG_HILITE,\r\n  WADLG_SELCOLOR,\r\n  WADLG_LISTHEADER_BGCOLOR,\r\n  WADLG_LISTHEADER_FONTCOLOR,\r\n  WADLG_LISTHEADER_FRAME_TOPCOLOR,\r\n  WADLG_LISTHEADER_FRAME_MIDDLECOLOR,\r\n  WADLG_LISTHEADER_FRAME_BOTTOMCOLOR,\r\n  WADLG_LISTHEADER_EMPTY_BGCOLOR,\r\n  WADLG_SCROLLBAR_FGCOLOR,\r\n  WADLG_SCROLLBAR_BGCOLOR,\r\n  WADLG_SCROLLBAR_INV_FGCOLOR,\r\n  WADLG_SCROLLBAR_INV_BGCOLOR,\r\n  WADLG_SCROLLBAR_DEADAREA_COLOR,\r\n  WADLG_NUM_COLORS\r\n};\r\n\r\n\r\n\r\nvoid WADlg_init(HWND hwndWinamp); // call this on init, or on WM_DISPLAYCHANGE\r\nvoid WADlg_close();\r\n\r\nint WADlg_getColor(int idx);\r\n\r\nint WADlg_handleDialogMsgs(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam); //\r\nvoid WADlg_DrawChildWindowBorders(HWND hwndDlg, int *tab, int tabsize); // each entry in tab would be the id | DCW_*\r\n\r\nHBITMAP WADlg_getBitmap();\r\n\r\n\r\n/// define WA_DLG_IMPLEMENT in one of your source files before including this .h\r\n// if you are making a media library plugin, you dont need to do this, look at view_ex for \r\n// an example of how to get the function *'s via an IPC message.\r\n\r\n#ifdef WA_DLG_IMPLEMENT\r\n\r\nstatic HBRUSH wadlg_lastbrush;\r\nstatic HBITMAP wadlg_bitmap; // load this manually\r\nstatic int wadlg_colors[WADLG_NUM_COLORS];\r\nstatic int wadlg_defcolors[WADLG_NUM_COLORS]=\r\n{\r\nRGB(0,0,0),\r\nRGB(0,255,0),\r\nRGB(36,36,60),\r\nRGB(57,56,66),\r\nRGB(255,255,255),\r\nRGB(132,148,165),  \r\nRGB(0,0,198),\r\nRGB(36*2,36*2,60*2),\r\nRGB(255,255,255),\r\nRGB(36*3,36*3,60*3),\r\nRGB(36,36,60),\r\nRGB(36*0.5,36*0.5,60*0.5),\r\nRGB(36,36,60),\r\nRGB(36*1,36*1,60*1),\r\nRGB(36*1,36*1,60*1),\r\nRGB(121,130,150),\r\nRGB(78,88,110),\r\nRGB(36*1,36*1,60*1),\r\n};\r\n\r\nint WADlg_getColor(int idx)\r\n{\r\n  if (idx < 0 || idx >= WADLG_NUM_COLORS) return 0;\r\n  return wadlg_colors[idx];\r\n}\r\n\r\nHBITMAP WADlg_getBitmap()\r\n{\r\n  return wadlg_bitmap;\r\n}\r\n\r\nvoid WADlg_init(HWND hwndWinamp) // call this on init, or on WM_DISPLAYCHANGE\r\n{\r\n  if (wadlg_bitmap) DeleteObject(wadlg_bitmap);\r\n  wadlg_bitmap = (HBITMAP) SendMessage(hwndWinamp,WM_WA_IPC,0,IPC_GET_GENSKINBITMAP);\r\n  if (wadlg_bitmap)\r\n  {\r\n    HDC tmpDC=CreateCompatibleDC(NULL);\r\n    HGDIOBJ o=SelectObject(tmpDC,(HGDIOBJ)wadlg_bitmap);\r\n    int x;\r\n    for (x = 0; x < WADLG_NUM_COLORS; x ++)\r\n    {\r\n      int a=GetPixel(tmpDC,48+x*2,0);\r\n      if (a == CLR_INVALID || a == RGB(0,198,255)) a=wadlg_defcolors[x];\r\n      wadlg_colors[x]=a;\r\n    }\r\n\r\n    SelectObject(tmpDC,o);\r\n    DeleteDC(tmpDC);\r\n  }\r\n}\r\n\r\nvoid WADlg_close()\r\n{\r\n  if (wadlg_bitmap) DeleteObject(wadlg_bitmap);\r\n  wadlg_bitmap=0;\r\n  if (wadlg_lastbrush) DeleteObject(wadlg_lastbrush);\r\n  wadlg_lastbrush=0;\r\n}\r\n\r\nvoid WADlg_dotLine(HDC hdc, int left, int top, int len, int vert)\r\n{\r\n  for(int i=(top&1);i<len-1;i+=2)\r\n  {\r\n    if(vert) {\r\n      MoveToEx(hdc,left,top+i,NULL);\r\n      LineTo(hdc,left,top+i+1);\r\n    } else {\r\n      MoveToEx(hdc,left+i,top,NULL);\r\n      LineTo(hdc,left+i+1,top);\r\n    }\r\n  }\r\n}\r\n\r\nint WADlg_handleDialogMsgs(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)\r\n{\r\n\tif (uMsg == WM_DRAWITEM)\r\n\t{\r\n\t\tDRAWITEMSTRUCT *di = (DRAWITEMSTRUCT *)lParam;\r\n\t\tif (di->CtlType == ODT_BUTTON) {\r\n\t\t\tchar wt[256];\r\n\t\t\tRECT r;\r\n\t\t\tGetDlgItemText(hwndDlg,wParam,wt,sizeof(wt));\r\n\r\n      HDC hdc = CreateCompatibleDC(di->hDC);\r\n      SelectObject(hdc,wadlg_bitmap);\r\n\r\n\t\t\tr=di->rcItem;\r\n      SetStretchBltMode(di->hDC,COLORONCOLOR);\r\n\r\n\r\n      int yoffs = (di->itemState & ODS_SELECTED) ? 15 : 0;\r\n\r\n      BitBlt(di->hDC,r.left,r.top,4,4,hdc,0,yoffs,SRCCOPY); // top left\r\n      StretchBlt(di->hDC,r.left+4,r.top,r.right-r.left-4-4,4,hdc,4,yoffs,47-4-4,4,SRCCOPY); // top center\r\n      BitBlt(di->hDC,r.right-4,r.top,4,4,hdc,47-4,yoffs,SRCCOPY); // top right\r\n\r\n      StretchBlt(di->hDC,r.left,r.top+4,4,r.bottom-r.top-4-4,hdc,0,4+yoffs,4,15-4-4,SRCCOPY); // left edge\r\n      StretchBlt(di->hDC,r.right-4,r.top+4,4,r.bottom-r.top-4-4,hdc,47-4,4+yoffs,4,15-4-4,SRCCOPY); // right edge\r\n\r\n      // center\r\n      StretchBlt(di->hDC,r.left+4,r.top+4,r.right-r.left-4-4,r.bottom-r.top-4-4,hdc,4,4+yoffs,47-4-4,15-4-4,SRCCOPY);\r\n\r\n\r\n      BitBlt(di->hDC,r.left,r.bottom-4,4,4,hdc,0,15-4+yoffs,SRCCOPY); // bottom left\r\n      StretchBlt(di->hDC,r.left+4,r.bottom-4,r.right-r.left-4-4,4,hdc,4,15-4+yoffs,47-4-4,4,SRCCOPY); // bottom center\r\n      BitBlt(di->hDC,r.right-4,r.bottom-4,4,4,hdc,47-4,15-4+yoffs,SRCCOPY); // bottom right\r\n\r\n\r\n\t\t\t// draw text\r\n      SetBkMode(di->hDC,TRANSPARENT);\r\n\t\t\tSetTextColor(di->hDC,wadlg_colors[WADLG_BUTTONFG]);\r\n      if (di->itemState & ODS_SELECTED) {r.left+=2; r.top+=2;}\r\n\t\t\tDrawText(di->hDC,wt,-1,&r,DT_VCENTER|DT_SINGLELINE|DT_CENTER);\r\n      DeleteDC(hdc);\r\n\r\n      if(GetFocus()==di->hwndItem) {\r\n        HPEN pen=CreatePen(PS_SOLID,0,RGB(0,0,0));\r\n        SelectObject(di->hDC,pen);\r\n        WADlg_dotLine(di->hDC,r.left+2,r.top+2,r.right-r.left-3,0);\r\n        WADlg_dotLine(di->hDC,r.right-3,r.top+2,r.bottom-r.top-3,1);\r\n        WADlg_dotLine(di->hDC,r.left+2,r.top+2,r.bottom-r.top-3,1);\r\n        WADlg_dotLine(di->hDC,r.left+2,r.bottom-3,r.right-r.left-3,0);\r\n        DeleteObject(pen);\r\n      }\r\n\t\t}\t\r\n\t}\r\n  switch(uMsg) \r\n  {\r\n    case WM_CTLCOLORLISTBOX:\r\n    case WM_CTLCOLORDLG:\r\n    case WM_CTLCOLORBTN:\r\n    case WM_CTLCOLORSTATIC:\r\n    case WM_CTLCOLOREDIT:\r\n    {\r\n      int bgcolor=(uMsg == WM_CTLCOLOREDIT || uMsg == WM_CTLCOLORLISTBOX) ? wadlg_colors[WADLG_ITEMBG] : (uMsg == WM_CTLCOLORBTN ? wadlg_colors[WADLG_ITEMBG] : wadlg_colors[WADLG_WNDBG]);\r\n      LOGBRUSH lb={BS_SOLID,GetNearestColor((HDC)wParam,bgcolor)};\r\n      if (wadlg_lastbrush) DeleteObject(wadlg_lastbrush);\r\n      wadlg_lastbrush=CreateBrushIndirect(&lb);\r\n      SetTextColor((HDC)wParam,uMsg == WM_CTLCOLORSTATIC ? wadlg_colors[WADLG_WNDFG] : wadlg_colors[WADLG_ITEMFG]);\r\n      SetBkColor((HDC)wParam,lb.lbColor);\r\n      return (int)wadlg_lastbrush;\r\n    }\r\n  }\r\n  return 0;\r\n}\r\n\r\nstatic int RectInRect(RECT *rect1, RECT *rect2)\r\n{ \r\n  // this has a bias towards true\r\n\r\n  // this could probably be optimized a lot\r\n  return ((rect1->top >= rect2->top && rect1->top <= rect2->bottom) ||\r\n      (rect1->bottom >= rect2->top && rect1->bottom <= rect2->bottom) ||\r\n      (rect2->top >= rect1->top && rect2->top <= rect1->bottom) ||\r\n      (rect2->bottom >= rect1->top && rect2->bottom <= rect1->bottom)) // vertical intersect\r\n      &&\r\n      ((rect1->left >= rect2->left && rect1->left <= rect2->right) ||\r\n      (rect1->right >= rect2->left && rect1->right <= rect2->right) ||\r\n      (rect2->left >= rect1->left && rect2->left <= rect1->right) ||\r\n      (rect2->right >= rect1->left && rect2->right <= rect1->right)) // horiz intersect\r\n      ;\r\n}\r\n\r\nstatic void WADlg_removeFromRgn(HRGN hrgn, int left, int top, int right, int bottom)\r\n{\r\n  HRGN rgn2=CreateRectRgn(left,top,right,bottom);\r\n  CombineRgn(hrgn,hrgn,rgn2,RGN_DIFF);\r\n  DeleteObject(rgn2);\r\n}\r\n\r\nvoid WADlg_DrawChildWindowBorders(HWND hwndDlg, int *tab, int tabsize)\r\n{\r\n  PAINTSTRUCT ps;\r\n  BeginPaint(hwndDlg,&ps);\r\n\r\n  HRGN hrgn=NULL;\r\n  if(ps.fErase)\r\n  {\r\n    RECT r=ps.rcPaint;\r\n    hrgn=CreateRectRgn(r.left,r.top,r.right,r.bottom);\r\n  }\r\n\r\n  HPEN pen=CreatePen(PS_SOLID,0,wadlg_colors[WADLG_HILITE]);\r\n  HGDIOBJ o=SelectObject(ps.hdc,pen);\r\n\r\n  while (tabsize--)\r\n  {\r\n    RECT r;\r\n    int a=*tab++;\r\n    GetWindowRect(GetDlgItem(hwndDlg,a&0xffff),&r);\r\n    ScreenToClient(hwndDlg,(LPPOINT)&r);\r\n    ScreenToClient(hwndDlg,((LPPOINT)&r)+1);\r\n\r\n    if (RectInRect(&ps.rcPaint,&r)) \r\n    {\r\n      if ((a & 0xffff0000) == DCW_SUNKENBORDER)\r\n      {\r\n        MoveToEx(ps.hdc,r.left,r.bottom,NULL);\r\n        LineTo(ps.hdc,r.right,r.bottom);\r\n        LineTo(ps.hdc,r.right,r.top-1);\r\n        if(hrgn)\r\n        {\r\n          WADlg_removeFromRgn(hrgn,r.left,r.bottom,r.right,r.bottom+1);\r\n          WADlg_removeFromRgn(hrgn,r.right,r.top,r.right+1,r.bottom);\r\n        }\r\n      }\r\n      else if ((a & 0xffff0000) == DCW_DIVIDER)\r\n      {\r\n        if (r.right - r.left < r.bottom - r.top) // vertical\r\n        {\r\n          int left=(r.left+r.right)/2;\r\n          MoveToEx(ps.hdc,left,r.top,NULL);\r\n          LineTo(ps.hdc,left,r.bottom+1);\r\n          if(hrgn) WADlg_removeFromRgn(hrgn,left,r.top,left+1,r.bottom);\r\n        }\r\n        else // horiz\r\n        {\r\n          int top=(r.top+r.bottom)/2;\r\n          MoveToEx(ps.hdc,r.left,top,NULL);\r\n          LineTo(ps.hdc,r.right+1,top);\r\n          if(hrgn) WADlg_removeFromRgn(hrgn,r.left,top,r.right,top+1);\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  SelectObject(ps.hdc,o);\r\n  DeleteObject(pen);\r\n\r\n  if(hrgn) {\r\n    //erase bkgnd while clipping out our own drawn stuff (for flickerless display)\r\n    HBRUSH b=CreateSolidBrush(wadlg_colors[WADLG_WNDBG]);\r\n    FillRgn(ps.hdc,hrgn,b);\r\n    DeleteObject(b);\r\n    DeleteObject(hrgn);\r\n  }\r\n  EndPaint(hwndDlg,&ps);\r\n}\r\n#endif\r\n\r\n#endif//_WA_DLG_H_"
  },
  {
    "path": "plugins/winamp/wa_hotkeys.h",
    "content": "#ifndef WA_HOTKEYS\r\n#define WA_HOTKEYS\r\n\r\n//#define IPC_GEN_HOTKEYS_ADD xxxx //pass a genHotkeysAddStruct * struct in data\r\n//\r\n//To get the IPC_GEN_HOTKEYS_ADD IPC number, do this:\r\n//\r\n//  genhotkeys_add_ipc=SendMessage(winampWindow,WM_WA_IPC,(WPARAM)&\"GenHotkeysAdd\",IPC_REGISTER_WINAMP_IPCMESSAGE);\r\n//\r\n//Then you can use:\r\n//\r\n//  PostMessage(winampWindow,WM_WA_IPC,(WPARAM)&myGenHotkeysAddStruct,genhotkeys_add_ipc);\r\n//\r\n\r\n//flags for the genHotkeysAddStruct struct\r\n#define HKF_BRING_TO_FRONT 0x1  // calls SetForegroundWindow before sending the message\r\n#define HKF_HWND_WPARAM 0x2     // sets wParam with Winamp's window handle\r\n#define HKF_COPY 0x4            // copies returned text to the clipboard\r\n#define HKF_PLPOS_WPARAM 0x8    // sets wParam with current pledit position\r\n#define HKF_ISPLAYING_WL 0x10   // sets wParam to genHotkeysAddStruct's wParam if playing, lParam if not\r\n                                // uses IPC_ISPLAYING to check if playing\r\n#define HKF_SHOWHIDE 0x20       // brings Winamp to front or minimizes Winamp if already at front\r\n#define HKF_NOSENDMSG 0x40      // don't send any message to the winamp window\r\n\r\n#define HKF_DISABLED 0x80000000\r\n\r\ntypedef struct {\r\n  char *name;     //name that will appear in the Global Hotkeys preferences panel\r\n  DWORD flags;    //one or more flags from above\r\n  UINT uMsg;      //message that will be sent to winamp's main window (must always be !=NULL)\r\n  WPARAM wParam;  //wParam that will be sent to winamp's main window\r\n  LPARAM lParam;  //lParam that will be sent to winamp's main window\r\n  char *id;       //unique string to identify this command - case insensitive\r\n  HWND wnd;       //set the HWND to send message (or 0 for main winamp window)\r\n  \r\n  int extended[6]; //for future extension - always set to zero!\r\n} genHotkeysAddStruct;\r\n\r\n#endif"
  },
  {
    "path": "plugins/winamp/wa_ipc.h",
    "content": "/*\r\n** Copyright (C) 2006 Nullsoft, Inc.\r\n**\r\n** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held \r\n** liable for any damages arising from the use of this software. \r\n**\r\n** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to \r\n** alter it and redistribute it freely, subject to the following restrictions:\r\n**\r\n**   1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. \r\n**      If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.\r\n**\r\n**   2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.\r\n**\r\n**   3. This notice may not be removed or altered from any source distribution.\r\n**\r\n*/\r\n\r\n#ifndef _WA_IPC_H_\r\n#define _WA_IPC_H_\r\n\r\n#include <windows.h>\r\n#include <stddef.h>\r\n#if (_MSC_VER <= 1200)\r\ntypedef int intptr_t;\r\n#endif\r\n/*\r\n** This is the modern replacement for the classic 'frontend.h'. Most of these \r\n** updates are designed for in-process use, i.e. from a plugin.\r\n**\r\n*/\r\n\r\n/* message used to sent many messages to winamp's main window. \r\n** most all of the IPC_* messages involve sending the message in the form of:\r\n**   result = SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*);\r\n**\r\n** When you use SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*) and specify a IPC_*\r\n** which is not currently implemented/supported by the Winamp version being used then it\r\n** will return 1 for 'result'. This is a good way of helping to check if an api being\r\n** used which returns a function pointer, etc is even going to be valid.\r\n*/\r\n#define WM_WA_IPC WM_USER\r\n/* but some of them use WM_COPYDATA. be afraid.\r\n*/\r\n\r\n#define WINAMP_VERSION_MAJOR(winampVersion) ((winampVersion & 0x0000FF00) >> 12)\r\n#define WINAMP_VERSION_MINOR(winampVersion) (winampVersion & 0x000000FF)  // returns, i.e. 0x12 for 5.12 and 0x10 for 5.1... \r\n\r\n#define IPC_GETVERSION 0\r\n/* int version = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION);\r\n**\r\n** The version returned will be 0x20yx for Winamp 2.yx.\r\n** Versions previous to Winamp 2.0 typically (but not always) use 0x1zyx for 1.zx.\r\n** Just a bit weird but that's the way it goes.\r\n**\r\n** For Winamp 5.x it uses the format 0x50yx for Winamp 5.yx\r\n** e.g.   5.01 -> 0x5001\r\n**        5.09 -> 0x5009\r\n**        5.1  -> 0x5010\r\n**\r\n** Notes: For 5.02 this api will return the same value as for a 5.01 build.\r\n**        For 5.07 this api will return the same value as for a 5.06 build.\r\n*/\r\n#define IPC_GETVERSIONSTRING 1\r\n\r\n#define IPC_GETREGISTEREDVERSION 770\r\n\r\n\r\ntypedef struct {\r\n  const char *filename;\r\n  const char *title;\r\n  int length;\r\n} enqueueFileWithMetaStruct; // send this to a IPC_PLAYFILE in a non WM_COPYDATA, \r\n// and you get the nice desired result. if title is NULL, it is treated as a \"thing\",\r\n// otherwise it's assumed to be a file (for speed)\r\n\r\ntypedef struct {\r\n  const wchar_t *filename;\r\n  const wchar_t *title;\r\n  int length;\r\n} enqueueFileWithMetaStructW;\r\n\r\n#define IPC_PLAYFILE 100  // dont be fooled, this is really the same as enqueufile\r\n#define IPC_ENQUEUEFILE 100 \r\n#define IPC_PLAYFILEW 1100\r\n/* This is sent as a WM_COPYDATA with IPC_PLAYFILE as the dwData member and the string\r\n** of the file / playlist to be enqueued into the playlist editor as the lpData member.\r\n** This will just enqueue the file or files since you can use this to enqueue a playlist.\r\n** It will not clear the current playlist or change the playback state.\r\n**\r\n** COPYDATASTRUCT cds = {0};\r\n**   cds.dwData = IPC_ENQUEUEFILE;\r\n**   cds.lpData = (void*)\"c:\\\\test\\\\folder\\\\test.mp3\";\r\n**   cds.cbData = lstrlen((char*)cds.lpData)+1;  // include space for null char\r\n**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);\r\n**\r\n**\r\n** With 2.9+ and all of the 5.x versions you can send this as a normal WM_WA_IPC\r\n** (non WM_COPYDATA) with an enqueueFileWithMetaStruct as the param.\r\n** If the title member is null then it is treated as a \"thing\" otherwise it will be\r\n** assumed to be a file (for speed).\r\n**\r\n** enqueueFileWithMetaStruct eFWMS = {0};\r\n**   eFWMS.filename = \"c:\\\\test\\\\folder\\\\test.mp3\";\r\n**   eFWMS.title = \"Whipping Good\";\r\n**   eFWMS.length = 300;  // this is the number of seconds for the track\r\n**   SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&eFWMS,IPC_ENQUEUEFILE);\r\n*/\r\n\r\n\r\n#define IPC_DELETE 101\r\n#define IPC_DELETE_INT 1101 \r\n/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_DELETE);\r\n** Use this api to clear Winamp's internal playlist.\r\n** You should not need to use IPC_DELETE_INT since it is used internally by Winamp when\r\n** it is dealing with some lame Windows Explorer issues (hard to believe that!).\r\n*/\r\n\r\n\r\n#define IPC_STARTPLAY 102   \r\n#define IPC_STARTPLAY_INT 1102 \r\n/* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_STARTPLAY);\r\n** Sending this will start playback and is almost the same as hitting the play button.\r\n** The IPC_STARTPLAY_INT version is used internally and you should not need to use it\r\n** since it won't be any fun.\r\n*/\r\n\r\n#define IPC_CHDIR 103\r\n/* This is sent as a WM_COPYDATA type message with IPC_CHDIR as the dwData value and the\r\n** directory you want to change to as the lpData member.\r\n**\r\n** COPYDATASTRUCT cds = {0};\r\n**   cds.dwData = IPC_CHDIR;\r\n**   cds.lpData = (void*)\"c:\\\\download\";\r\n**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char\r\n**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);\r\n**\r\n** The above example will make Winamp change to the directory 'C:\\download'.\r\n*/\r\n\r\n\r\n#define IPC_ISPLAYING 104\r\n/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING);\r\n** This is sent to retrieve the current playback state of Winamp.\r\n** If it returns 1, Winamp is playing.\r\n** If it returns 3, Winamp is paused.\r\n** If it returns 0, Winamp is not playing.\r\n*/\r\n\r\n\r\n#define IPC_GETOUTPUTTIME 105\r\n/* int res = SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETOUTPUTTIME);\r\n** This api can return two different sets of information about current playback status.\r\n**\r\n** If mode = 0 then it will return the position (in ms) of the currently playing track.\r\n** Will return -1 if Winamp is not playing.\r\n**\r\n** If mode = 1 then it will return the current track length (in seconds).\r\n** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length).\r\n*/\r\n\r\n\r\n\r\n#define IPC_JUMPTOTIME 106\r\n/* (requires Winamp 1.60+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,ms,IPC_JUMPTOTIME);\r\n** This api sets the current position (in milliseconds) for the currently playing song.\r\n** The resulting playback position may only be an approximate time since some playback\r\n** formats do not provide exact seeking e.g. mp3\r\n** This returns -1 if Winamp is not playing, 1 on end of file, or 0 if it was successful.\r\n*/\r\n\r\n#define IPC_GETMODULENAME 109\r\n#define IPC_EX_ISRIGHTEXE 666\r\n/* usually shouldnt bother using these, but here goes:\r\n** send a WM_COPYDATA with IPC_GETMODULENAME, and an internal\r\n** flag gets set, which if you send a normal WM_WA_IPC message with\r\n** IPC_EX_ISRIGHTEXE, it returns whether or not that filename\r\n** matches. lame, I know.\r\n*/\r\n\r\n#define IPC_WRITEPLAYLIST 120\r\n/* (requires Winamp 1.666+)\r\n** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_WRITEPLAYLIST);\r\n**\r\n** IPC_WRITEPLAYLIST will write the current playlist to '<winampdir>\\\\Winamp.m3u' and\r\n** will also return the current playlist position (see IPC_GETLISTPOS).\r\n**\r\n** This is kinda obsoleted by some of the newer 2.x api items but it still is good for\r\n** use with a front-end program (instead of a plug-in) and you want to see what is in the\r\n** current playlist.\r\n**\r\n** This api will only save out extended file information in the #EXTINF entry if Winamp\r\n** has already read the data such as if the file was played of scrolled into view. If\r\n** Winamp has not read the data then you will only find the file with its filepath entry\r\n** (as is the base requirements for a m3u playlist).\r\n*/\r\n\r\n\r\n#define IPC_SETPLAYLISTPOS 121\r\n/* (requires Winamp 2.0+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,position,IPC_SETPLAYLISTPOS)\r\n** IPC_SETPLAYLISTPOS sets the playlist position to the specified 'position'.\r\n** It will not change playback status or anything else. It will just set the current\r\n** position in the playlist and will update the playlist view if necessary.\r\n**\r\n** If you use SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_BUTTON2,0),0);\r\n** after using IPC_SETPLAYLISTPOS then Winamp will start playing the file at 'position'.\r\n*/\r\n\r\n\r\n#define IPC_SETVOLUME 122\r\n/* (requires Winamp 2.0+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,volume,IPC_SETVOLUME);\r\n** IPC_SETVOLUME sets the volume of Winamp (between the range of 0 to 255).\r\n**\r\n** If you pass 'volume' as -666 then the message will return the current volume.\r\n** int curvol = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME);\r\n*/\r\n\r\n\r\n#define IPC_SETPANNING 123\r\n/* (requires Winamp 2.0+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,panning,IPC_SETPANNING);\r\n** IPC_SETPANNING sets the panning of Winamp from 0 (left) to 255 (right).\r\n**\r\n** At least in 5.x+ this works from -127 (left) to 127 (right).\r\n**\r\n** If you pass 'panning' as -666 to this api then it will return the current panning.\r\n** int curpan = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETPANNING);\r\n*/\r\n\r\n\r\n#define IPC_GETLISTLENGTH 124\r\n/* (requires Winamp 2.0+)\r\n** int length = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTLENGTH);\r\n** IPC_GETLISTLENGTH returns the length of the current playlist as the number of tracks.\r\n*/\r\n\r\n\r\n#define IPC_GETLISTPOS 125\r\n/* (requires Winamp 2.05+)\r\n** int pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS);\r\n** IPC_GETLISTPOS returns the current playlist position (which is shown in the playlist\r\n** editor as a differently coloured text entry e.g is yellow for the classic skin).\r\n**\r\n** This api is a lot like IPC_WRITEPLAYLIST but a lot faster since it does not have to\r\n** write out the whole of the current playlist first.\r\n*/\r\n\r\n\r\n#define IPC_GETINFO 126\r\n/* (requires Winamp 2.05+)\r\n** int inf=SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETINFO);\r\n** IPC_GETINFO returns info about the current playing song. The value\r\n** it returns depends on the value of 'mode'.\r\n** Mode      Meaning\r\n** ------------------\r\n** 0         Samplerate, in kilohertz (i.e. 44)\r\n** 1         Bitrate  (i.e. 128)\r\n** 2         Channels (i.e. 2)\r\n** 3 (5+)    Video LOWORD=w HIWORD=h\r\n** 4 (5+)    > 65536, string (video description)\r\n** 5 (5.25+) Samplerate, in hertz (i.e. 44100)\r\n*/\r\n\r\n\r\n#define IPC_GETEQDATA 127\r\n/* (requires Winamp 2.05+)\r\n** int data=SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);\r\n** IPC_GETEQDATA queries the status of the EQ. \r\n** The value returned depends on what 'pos' is set to:\r\n** Value      Meaning\r\n** ------------------\r\n** 0-9        The 10 bands of EQ data. 0-63 (+20db - -20db)\r\n** 10         The preamp value. 0-63 (+20db - -20db)\r\n** 11         Enabled. zero if disabled, nonzero if enabled.\r\n** 12         Autoload. zero if disabled, nonzero if enabled.\r\n*/\r\n\r\n\r\n#define IPC_SETEQDATA 128\r\n/* (requires Winamp 2.05+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA);\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SETEQDATA);\r\n** IPC_SETEQDATA sets the value of the last position retrieved\r\n** by IPC_GETEQDATA. This is pretty lame, and we should provide\r\n** an extended version that lets you do a MAKELPARAM(pos,value).\r\n** someday...\r\n\r\n  new (2.92+): \r\n    if the high byte is set to 0xDB, then the third byte specifies\r\n    which band, and the bottom word specifies the value.\r\n*/\r\n\r\n#define IPC_ADDBOOKMARK 129\r\n#define IPC_ADDBOOKMARKW 131\r\n/* (requires Winamp 2.4+)\r\n** This is sent as a WM_COPYDATA using IPC_ADDBOOKMARK as the dwData value and the\r\n** directory you want to change to as the lpData member. This will add the specified\r\n** file / url to the Winamp bookmark list.\r\n**\r\n** COPYDATASTRUCT cds = {0};\r\n**   cds.dwData = IPC_ADDBOOKMARK;\r\n**   cds.lpData = (void*)\"http://www.blah.com/listen.pls\";\r\n**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char\r\n**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);\r\n**\r\n**\r\n** In Winamp 5.0+ we use this as a normal WM_WA_IPC and the string is null separated as\r\n** the filename and then the title of the entry.\r\n**\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)\"filename\\0title\\0\",IPC_ADDBOOKMARK);\r\n**\r\n** This will notify the library / bookmark editor that a bookmark was added.\r\n** Note that using this message in this context does not actually add the bookmark.\r\n** Do not use, it is essentially just a notification type message :)\r\n*/\r\n\r\n\r\n#define IPC_INSTALLPLUGIN 130\r\n/* This is not implemented (and is very unlikely to be done due to safety concerns).\r\n** If it was then you could do a WM_COPYDATA with a path to a .wpz and it would then\r\n** install the plugin for you.\r\n**\r\n** COPYDATASTRUCT cds = {0};\r\n**   cds.dwData = IPC_INSTALLPLUGIN;\r\n**   cds.lpData = (void*)\"c:\\\\path\\\\to\\\\file.wpz\";\r\n**   cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char\r\n**   SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds);\r\n*/\r\n\r\n\r\n#define IPC_RESTARTWINAMP 135\r\n/* (requires Winamp 2.2+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_RESTARTWINAMP);\r\n** IPC_RESTARTWINAMP will restart Winamp (isn't that obvious ? :) )\r\n** If this fails to make Winamp start after closing then there is a good chance one (or\r\n** more) of the currently installed plugins caused Winamp to crash on exit (either as a\r\n** silent crash or a full crash log report before it could call itself start again.\r\n*/\r\n\r\n\r\n#define IPC_ISFULLSTOP 400\r\n/* (requires winamp 2.7+ I think)\r\n** int ret=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISFULLSTOP);\r\n** This is useful for when you're an output plugin and you want to see if the stop/close\r\n** happening is a full stop or if you are just between tracks. This returns non zero if\r\n** it is a full stop or zero if it is just a new track.\r\n*/\r\n\r\n\r\n#define IPC_INETAVAILABLE 242\r\n/* (requires Winamp 2.05+)\r\n** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INETAVAILABLE);\r\n** IPC_INETAVAILABLE will return 1 if an Internet connection is available for Winamp and\r\n** relates to the internet connection type setting on the main general preferences page\r\n** in the Winamp preferences.\r\n*/\r\n\r\n\r\n#define IPC_UPDTITLE 243\r\n/* (requires Winamp 2.2+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_UPDTITLE);\r\n** IPC_UPDTITLE will ask Winamp to update the information about the current title and\r\n** causes GetFileInfo(..) in the input plugin associated with the current playlist entry\r\n** to be called. This can be called such as when an input plugin is buffering a file so\r\n** that it can cause the buffer percentage to appear in the playlist.\r\n*/\r\n\r\n\r\n#define IPC_REFRESHPLCACHE 247\r\n/* (requires Winamp 2.2+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REFRESHPLCACHE);\r\n** IPC_REFRESHPLCACHE will flush the playlist cache buffer and you send this if you want\r\n** Winamp to go refetch the titles for all of the entries in the current playlist.\r\n\r\n5.3+: pass a wchar_t * string in wParam, and it'll do a strnicmp() before clearing the cache\r\n*/\r\n\r\n\r\n#define IPC_GET_SHUFFLE 250\r\n/* (requires Winamp 2.4+)\r\n** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_SHUFFLE);\r\n** IPC_GET_SHUFFLE returns the status of the shuffle option.\r\n** If set then it will return 1 and if not set then it will return 0.\r\n*/\r\n\r\n\r\n#define IPC_GET_REPEAT 251\r\n/* (requires Winamp 2.4+)\r\n** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_REPEAT);\r\n** IPC_GET_REPEAT returns the status of the repeat option.\r\n** If set then it will return 1 and if not set then it will return 0.\r\n*/\r\n\r\n\r\n#define IPC_SET_SHUFFLE 252\r\n/* (requires Winamp 2.4+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_SHUFFLE);\r\n** IPC_SET_SHUFFLE sets the status of the shuffle option.\r\n** If 'value' is 1 then shuffle is turned on.\r\n** If 'value' is 0 then shuffle is turned off.\r\n*/\r\n\r\n\r\n#define IPC_SET_REPEAT 253\r\n/* (requires Winamp 2.4+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_REPEAT);\r\n** IPC_SET_REPEAT sets the status of the repeat option.\r\n** If 'value' is 1 then shuffle is turned on.\r\n** If 'value' is 0 then shuffle is turned off.\r\n*/\r\n\r\n\r\n#define IPC_ENABLEDISABLE_ALL_WINDOWS 259 // 0xdeadbeef to disable\r\n/* (requires Winamp 2.9+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(enable?0:0xdeadbeef),IPC_ENABLEDISABLE_ALL_WINDOWS);\r\n** Sending this message with 0xdeadbeef as the param will disable all winamp windows and\r\n** any other values will enable all of the Winamp windows again. When disabled you won't\r\n** get any response on clicking or trying to do anything to the Winamp windows. If the\r\n** taskbar icon is shown then you may still have control ;)\r\n*/\r\n\r\n\r\n#define IPC_GETWND 260\r\n/* (requires Winamp 2.9+)\r\n** HWND h=SendMessage(hwnd_winamp,WM_WA_IPC,IPC_GETWND_xxx,IPC_GETWND);\r\n** returns the HWND of the window specified.\r\n*/\r\n  #define IPC_GETWND_EQ 0 // use one of these for the param\r\n  #define IPC_GETWND_PE 1\r\n  #define IPC_GETWND_MB 2\r\n  #define IPC_GETWND_VIDEO 3\r\n#define IPC_ISWNDVISIBLE 261 // same param as IPC_GETWND\r\n\r\n\r\n\r\n\r\n/************************************************************************\r\n***************** in-process only (WE LOVE PLUGINS)\r\n************************************************************************/\r\n\r\n#define IPC_SETSKINW 199\r\n#define IPC_SETSKIN 200\r\n/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)\"skinname\",IPC_SETSKIN);\r\n** IPC_SETSKIN sets the current skin to \"skinname\". Note that skinname \r\n** can be the name of a skin, a skin .zip file, with or without path. \r\n** If path isn't specified, the default search path is the winamp skins \r\n** directory.\r\n*/\r\n\r\n\r\n#define IPC_GETSKIN 201\r\n/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)skinname_buffer,IPC_GETSKIN);\r\n** IPC_GETSKIN puts the directory where skin bitmaps can be found \r\n** into  skinname_buffer.\r\n** skinname_buffer must be MAX_PATH characters in length.\r\n** When using a .zip'd skin file, it'll return a temporary directory\r\n** where the ZIP was decompressed.\r\n*/\r\n\r\n\r\n#define IPC_EXECPLUG 202\r\n/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)\"vis_file.dll\",IPC_EXECPLUG);\r\n** IPC_EXECPLUG executes a visualization plug-in pointed to by WPARAM.\r\n** the format of this string can be:\r\n** \"vis_whatever.dll\"\r\n** \"vis_whatever.dll,0\" // (first mod, file in winamp plug-in dir)\r\n** \"C:\\\\dir\\\\vis_whatever.dll,1\" \r\n*/\r\n\r\n\r\n#define IPC_GETPLAYLISTFILE 211\r\n#define IPC_GETPLAYLISTFILEW 214\r\n/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))\r\n** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTFILE);\r\n** IPC_GETPLAYLISTFILE gets the filename of the playlist entry [index].\r\n** returns a pointer to it. returns NULL on error.\r\n*/\r\n\r\n\r\n#define IPC_GETPLAYLISTTITLE 212\r\n#define IPC_GETPLAYLISTTITLEW 213\r\n/* (requires Winamp 2.04+, only usable from plug-ins (not external apps))\r\n** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTTITLE);\r\n**\r\n** IPC_GETPLAYLISTTITLE gets the title of the playlist entry [index].\r\n** returns a pointer to it. returns NULL on error.\r\n*/\r\n\r\n\r\n#define IPC_GETHTTPGETTER 240\r\n/* retrieves a function pointer to a HTTP retrieval function.\r\n** if this is unsupported, returns 1 or 0.\r\n** the function should be:\r\n** int (*httpRetrieveFile)(HWND hwnd, char *url, char *file, char *dlgtitle);\r\n** if you call this function, with a parent window, a URL, an output file, and a dialog title,\r\n** it will return 0 on successful download, 1 on error.\r\n*/\r\n\r\n\r\n#define IPC_MBOPEN 241\r\n/* (requires Winamp 2.05+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_MBOPEN);\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPEN);\r\n** IPC_MBOPEN will open a new URL in the minibrowser. if url is NULL, it will open the Minibrowser window.\r\n*/\r\n\r\n\r\n\r\n#define IPC_CHANGECURRENTFILE 245\r\n/* (requires Winamp 2.05+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILE);\r\n** IPC_CHANGECURRENTFILE will set the current playlist item.\r\n*/\r\n\r\n#define IPC_CHANGECURRENTFILEW 1245\r\n/* (requires Winamp 2.05+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILEW);\r\n** IPC_CHANGECURRENTFILEW will set the current playlist item.\r\n*/\r\n\r\n\r\n#define IPC_GETMBURL 246\r\n/* (requires Winamp 2.2+)\r\n** char buffer[4096]; // Urls can be VERY long\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)buffer,IPC_GETMBURL);\r\n** IPC_GETMBURL will retrieve the current Minibrowser URL into buffer.\r\n** buffer must be at least 4096 bytes long.\r\n*/\r\n\r\n\r\n#define IPC_MBBLOCK 248\r\n/* (requires Winamp 2.4+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_MBBLOCK);\r\n**\r\n** IPC_MBBLOCK will block the Minibrowser from updates if value is set to 1\r\n*/\r\n\r\n#define IPC_MBOPENREAL 249\r\n/* (requires Winamp 2.4+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPENREAL);\r\n**\r\n** IPC_MBOPENREAL works the same as IPC_MBOPEN except that it will works even if \r\n** IPC_MBBLOCK has been set to 1\r\n*/\r\n\r\n#define IPC_ADJUST_OPTIONSMENUPOS 280\r\n/* (requires Winamp 2.9+)\r\n** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_OPTIONSMENUPOS);\r\n** moves where winamp expects the Options menu in the main menu. Useful if you wish to insert a\r\n** menu item above the options/skins/vis menus.\r\n*/\r\n\r\n#define IPC_GET_HMENU 281\r\n/* (requires Winamp 2.9+)\r\n** HMENU hMenu=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0,IPC_GET_HMENU);\r\n** values for data:\r\n** 0 : main popup menu \r\n** 1 : main menubar file menu\r\n** 2 : main menubar options menu\r\n** 3 : main menubar windows menu\r\n** 4 : main menubar help menu\r\n** other values will return NULL.\r\n*/\r\n\r\n#define IPC_GET_EXTENDED_FILE_INFO 290 //pass a pointer to the following struct in wParam\r\n#define IPC_GET_EXTENDED_FILE_INFO_HOOKABLE 296\r\n/* (requires Winamp 2.9+)\r\n** to use, create an extendedFileInfoStruct, point the values filename and metadata to the\r\n** filename and metadata field you wish to query, and ret to a buffer, with retlen to the\r\n** length of that buffer, and then SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_GET_EXTENDED_FILE_INFO);\r\n** the results should be in the buffer pointed to by ret.\r\n** returns 1 if the decoder supports a getExtendedFileInfo method\r\n*/\r\ntypedef struct {\r\n  const char *filename;\r\n  const char *metadata;\r\n  char *ret;\r\n  int retlen;\r\n} extendedFileInfoStruct;\r\n\r\n\r\n#define IPC_GET_BASIC_FILE_INFO 291 //pass a pointer to the following struct in wParam\r\ntypedef struct {\r\n  const char *filename;\r\n\r\n  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)\r\n\r\n  // filled in by winamp\r\n  int length;\r\n  char *title;\r\n  int titlelen;\r\n} basicFileInfoStruct;\r\n\r\n#define IPC_GET_BASIC_FILE_INFOW 1291 //pass a pointer to the following struct in wParam\r\ntypedef struct {\r\n  const wchar_t *filename;\r\n\r\n  int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used)\r\n\r\n  // filled in by winamp\r\n  int length;\r\n  wchar_t *title;\r\n  int titlelen;\r\n} basicFileInfoStructW;\r\n\r\n\r\n#define IPC_GET_EXTLIST 292 //returns doublenull delimited. GlobalFree() it when done. if data is 0, returns raw extlist, if 1, returns something suitable for getopenfilename\r\n#define IPC_GET_EXTLISTW 1292 // wide char version of above\r\n\r\n#define IPC_INFOBOX 293\r\ntypedef struct {\r\n  HWND parent;\r\n  char *filename;\r\n} infoBoxParam;\r\n\r\n#define IPC_INFOBOXW 1293\r\ntypedef struct {\r\n  HWND parent;\r\n  const wchar_t *filename;\r\n} infoBoxParamW;\r\n\r\n#define IPC_SET_EXTENDED_FILE_INFO 294 //pass a pointer to the a extendedFileInfoStruct in wParam\r\n/* (requires Winamp 2.9+)\r\n** to use, create an extendedFileInfoStruct, point the values filename and metadata to the\r\n** filename and metadata field you wish to write in ret. (retlen is not used). and then \r\n** SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_SET_EXTENDED_FILE_INFO);\r\n** returns 1 if the metadata is supported\r\n** Call IPC_WRITE_EXTENDED_FILE_INFO once you're done setting all the metadata you want to update\r\n*/\r\n\r\n#define IPC_WRITE_EXTENDED_FILE_INFO 295 \r\n/* (requires Winamp 2.9+)\r\n** writes all the metadata set thru IPC_SET_EXTENDED_FILE_INFO to the file\r\n** returns 1 if the file has been successfully updated, 0 if error\r\n*/\r\n\r\n#define IPC_FORMAT_TITLE 297\r\ntypedef struct \r\n{\r\n  char *spec; // NULL=default winamp spec\r\n  void *p;\r\n\r\n  char *out;\r\n  int out_len;\r\n\r\n  char * (*TAGFUNC)(const char * tag, void * p); //return 0 if not found\r\n  void (*TAGFREEFUNC)(char * tag,void * p);\r\n} waFormatTitle;\r\n\r\n#define IPC_FORMAT_TITLE_EXTENDED 298 // similiar to IPC_FORMAT_TITLE, but falls back to Winamp's %tags% if your passed tag function doesn't handle it\r\ntypedef struct \r\n{\r\n\tconst wchar_t *filename;\r\n\tint useExtendedInfo; // set to 1 if you want the Title Formatter to query the input plugins for any tags that your tag function fails on\r\n  const wchar_t *spec; // NULL=default winamp spec\r\n  void *p;\r\n\r\n  wchar_t *out;\r\n  int out_len;\r\n\r\n  wchar_t * (*TAGFUNC)(const wchar_t * tag, void * p); //return 0 if not found, -1 for empty tag\r\n  void (*TAGFREEFUNC)(wchar_t *tag, void *p);\r\n} waFormatTitleExtended;\r\n\r\n#define IPC_GETUNCOMPRESSINTERFACE 331\r\n/* returns a function pointer to uncompress().\r\n** int (*uncompress)(unsigned char *dest, unsigned long *destLen, const unsigned char *source, unsigned long sourceLen);\r\n** right out of zlib, useful for decompressing zlibbed data.\r\n** if you pass the parm of 0x10100000, it will return a wa_inflate_struct * to an inflate API.\r\n*/\r\n\r\ntypedef struct {\r\n  int (*inflateReset)(void *strm);\r\n  int (*inflateInit_)(void *strm,const char *version, int stream_size);\r\n  int (*inflate)(void *strm, int flush);\r\n  int (*inflateEnd)(void *strm);\r\n  unsigned long (*crc32)(unsigned long crc, const unsigned  char *buf, unsigned int len);\r\n} wa_inflate_struct;\r\n\r\n\r\n#define IPC_ADD_PREFS_DLG 332\r\n#define IPC_REMOVE_PREFS_DLG 333\r\n/* (requires Winamp 2.9+)\r\n** to use, allocate a prefsDlgRec structure (either on the heap or some global\r\n** data, but NOT on the stack), initialze the members:\r\n** hInst to the DLL instance where the resource is located\r\n** dlgID to the ID of the dialog,\r\n** proc to the window procedure for the dialog\r\n** name to the name of the prefs page in the prefs.\r\n** where to 0 (eventually we may add more options)\r\n** then, SendMessage(hwnd_winamp,WM_WA_IPC,&prefsRec,IPC_ADD_PREFS_DLG);\r\n**\r\n** you can also IPC_REMOVE_PREFS_DLG with the address of the same prefsRec,\r\n** but you shouldn't really ever have to.\r\n**\r\n*/\r\n#define IPC_OPENPREFSTOPAGE 380 // pass an id of a builtin page, or a &prefsDlgRec of prefs page to open\r\n\r\ntypedef struct _prefsDlgRec {\r\n  HINSTANCE hInst;\r\n  int dlgID;\r\n  void *proc;\r\n\r\n  char *name;\r\n  intptr_t where; // 0 for options, 1 for plugins, 2 for skins, 3 for bookmarks, 4 for prefs\r\n\r\n  intptr_t _id;\r\n  struct _prefsDlgRec *next;\r\n} prefsDlgRec;\r\n\r\n\r\n#define IPC_GETINIFILE 334 // returns a pointer to winamp.ini\r\n#define IPC_GETINIDIRECTORY 335 // returns a pointer to the directory to put config files in (if you dont want to use winamp.ini)\r\n#define IPC_GETPLUGINDIRECTORY 336\r\n#define IPC_GETM3UDIRECTORY 337 // returns a char pointer to the directory where winamp.m3u is stored in.\r\n#define IPC_GETM3UDIRECTORYW 338 // returns a wchar_t pointer to the directory where winamp.m3u is stored in.\r\n\r\n#define IPC_SPAWNBUTTONPOPUP 361 // param =\r\n// 0 = eject\r\n// 1 = previous\r\n// 2 = next\r\n// 3 = pause\r\n// 4 = play\r\n// 5 = stop\r\n\r\n#define IPC_OPENURLBOX 360 // pass a HWND to a parent, returns a HGLOBAL that needs to be freed with GlobalFree(), if successful\r\n#define IPC_OPENFILEBOX 362 // pass a HWND to a parent\r\n#define IPC_OPENDIRBOX 363 // pass a HWND to a parent\r\n\r\n// pass an HWND to a parent. call this if you take over the whole UI so that the dialogs are not appearing on the\r\n// bottom right of the screen since the main winamp window is at 3000x3000, call again with NULL to reset\r\n#define IPC_SETDIALOGBOXPARENT 364\r\n\r\n\r\n\r\n#define IPC_DRO_MIN 401 // reserved for DrO\r\n#define IPC_SET_JTF_COMPARATOR 409\r\n/* pass me an int (__cdecl *)(const char *, const char *) in wParam */\r\n#define IPC_SET_JTF_COMPARATOR_W 410\r\n/* pass me an int (__cdecl *)(const wchar_t *, const wchar_t *) in wParam ... maybe someday :) */\r\n#define IPC_SET_JTF_DRAWTEXT 416\r\n\r\n#define IPC_DRO_MAX 499\r\n\r\n\r\n// pass 0 for a copy of the skin HBITMAP\r\n// pass 1 for name of font to use for playlist editor likeness\r\n// pass 2 for font charset\r\n// pass 3 for font size\r\n#define IPC_GET_GENSKINBITMAP 503\r\n\r\n\r\n#define IPC_GET_EMBEDIF 505 // pass an embedWindowState\r\n// returns an HWND embedWindow(embedWindowState *); if the data is NULL, otherwise returns the HWND directly\r\ntypedef struct\r\n{\r\n  HWND me; //hwnd of the window\r\n\r\n  int flags;\r\n\r\n  RECT r;\r\n\r\n  void *user_ptr; // for application use\r\n\r\n  intptr_t extra_data[64]; // for internal winamp use\r\n} embedWindowState;\r\n\r\n#define EMBED_FLAGS_NORESIZE 0x1 // set this bit in embedWindowState.flags to keep window from being resizable\r\n#define EMBED_FLAGS_NOTRANSPARENCY 0x2 // set this bit in embedWindowState.flags to make gen_ff turn transparency off for this wnd\r\n#define EMBED_FLAGS_NOWINDOWMENU 0x4 // set this bit to prevent gen_ff from automatically adding your window to the right-click menu\r\n#define EMBED_FLAGS_GUID 0x8 // call SET_EMBED_GUID(yourEmbedWindowStateStruct, GUID) to define a GUID for this window \r\n\r\n#define SET_EMBED_GUID(windowState, windowGUID) { windowState->flags |= EMBED_FLAGS_GUID; *((GUID *)&windowState->extra_data[4])=windowGUID; }\r\n#define GET_EMBED_GUID(windowState) (*((GUID *)&windowState->extra_data[4]))\r\n\r\n#define IPC_EMBED_ENUM 532\r\ntypedef struct embedEnumStruct\r\n{\r\n  int (*enumProc)(embedWindowState *ws, struct embedEnumStruct *param); // return 1 to abort\r\n  int user_data; // or more :)\r\n} embedEnumStruct;\r\n  // pass \r\n\r\n#define IPC_EMBED_ISVALID 533\r\n\r\n#define IPC_CONVERTFILE 506\r\n/* (requires Winamp 2.92+)\r\n** Converts a given file to a different format (PCM, MP3, etc...)\r\n** To use, pass a pointer to a waFileConvertStruct struct\r\n** This struct can be either on the heap or some global\r\n** data, but NOT on the stack. At least, until the conversion is done.\r\n**\r\n** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE);\r\n**\r\n** Return value:\r\n** 0: Can't start the conversion. Look at myConvertStruct->error for details.\r\n** 1: Conversion started. Status messages will be sent to the specified callbackhwnd.\r\n**    Be sure to call IPC_CONVERTFILE_END when your callback window receives the\r\n**    IPC_CB_CONVERT_DONE message.\r\n*/\r\ntypedef struct \r\n{\r\n  char *sourcefile;  // \"c:\\\\source.mp3\"\r\n  char *destfile;    // \"c:\\\\dest.pcm\"\r\n  int destformat[8]; // like 'PCM ',srate,nch,bps.\r\n  //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*)\r\n  HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages\r\n  \r\n  //filled in by winamp.exe\r\n  char *error;        //if IPC_CONVERTFILE returns 0, the reason will be here\r\n\r\n  int bytes_done;     //you can look at both of these values for speed statistics\r\n  int bytes_total;\r\n  int bytes_out;\r\n\r\n  int killswitch;     // don't set it manually, use IPC_CONVERTFILE_END\r\n  intptr_t extra_data[64]; // for internal winamp use\r\n} convertFileStruct;\r\n\r\n#define IPC_CONVERTFILE_END 507\r\n/* (requires Winamp 2.92+)\r\n** Stop/ends a convert process started from IPC_CONVERTFILE\r\n** You need to call this when you receive the IPC_CB_CONVERTDONE message or when you\r\n** want to abort a conversion process\r\n**\r\n** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE_END);\r\n**\r\n** No return value\r\n*/\r\n\r\ntypedef struct {\r\n  HWND hwndParent;\r\n  int format;\r\n\r\n  //filled in by winamp.exe\r\n  HWND hwndConfig;\r\n  int extra_data[8];\r\n  //hack alert! you can set extra_data[6]=mmioFOURCC('I','N','I',' '); and extra_data[7]=(int)my_ini_file; (where my_ini_file is a char*)\r\n} convertConfigStruct;\r\n#define IPC_CONVERT_CONFIG 508\r\n#define IPC_CONVERT_CONFIG_END 509\r\n\r\ntypedef struct\r\n{\r\n  void (*enumProc)(intptr_t user_data, const char *desc, int fourcc);\r\n  intptr_t user_data;\r\n} converterEnumFmtStruct;\r\n#define IPC_CONVERT_CONFIG_ENUMFMTS 510\r\n/* (requires Winamp 2.92+)\r\n*/\r\n\r\ntypedef struct\r\n{\r\n  char cdletter;\r\n  char *playlist_file;\r\n  HWND callback_hwnd;\r\n\r\n  //filled in by winamp.exe\r\n  char *error;\r\n} burnCDStruct;\r\n#define IPC_BURN_CD 511\r\n/* (requires Winamp 5.0+)\r\n*/\r\n\r\ntypedef struct\r\n{\r\n  convertFileStruct *cfs;\r\n  int priority;\r\n} convertSetPriority;\r\n#define IPC_CONVERT_SET_PRIORITY 512\r\n\r\ntypedef struct\r\n{\r\n  unsigned int format; //fourcc value\r\n  char *item; // config item, eg \"bitrate\"\r\n  char *data; // buffer to recieve, or buffer that contains the data\r\n  int len; // length of the data buffer (only used when getting a config item)\r\n  char *configfile; // config file to read from\r\n} convertConfigItem;\r\n\r\n#define IPC_CONVERT_CONFIG_SET_ITEM 513 // returns TRUE if successful\r\n#define IPC_CONVERT_CONFIG_GET_ITEM 514 // returns TRUE if successful\r\n\r\ntypedef struct\r\n{\r\n  const char *filename;\r\n  char *title; // 2048 bytes\r\n  int length;\r\n  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit\r\n} waHookTitleStruct;\r\n// return TRUE if you hook this\r\n#define IPC_HOOK_TITLES 850\r\n\r\ntypedef struct\r\n{\r\n  const wchar_t *filename;\r\n  wchar_t *title; // 2048 bytes\r\n  int length;\r\n  int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit\r\n} waHookTitleStructW;\r\n// return TRUE if you hook this\r\n#define IPC_HOOK_TITLESW 851\r\n\r\n#define IPC_GETSADATAFUNC 800 \r\n// 0: returns a char *export_sa_get() that returns 150 bytes of data\r\n// 1: returns a export_sa_setreq(int want);\r\n\r\n#define IPC_GETVUDATAFUNC 801 \r\n// 0: returns a int export_vu_get(int channel) that returns 0-255 (or -1 for bad channel)\r\n\r\n#define IPC_ISMAINWNDVISIBLE 900\r\n\r\n\r\n#define IPC_SETPLEDITCOLORS 920\r\ntypedef struct\r\n{\r\n  int numElems;\r\n  int *elems;\r\n  HBITMAP bm; // set if you want to override\r\n} waSetPlColorsStruct;\r\n\r\n\r\n// the following IPC use waSpawnMenuParms as parameter\r\n#define IPC_SPAWNEQPRESETMENU 933\r\n#define IPC_SPAWNFILEMENU 934 //menubar\r\n#define IPC_SPAWNOPTIONSMENU 935 //menubar\r\n#define IPC_SPAWNWINDOWSMENU 936 //menubar\r\n#define IPC_SPAWNHELPMENU 937 //menubar\r\n#define IPC_SPAWNPLAYMENU 938 //menubar\r\n#define IPC_SPAWNPEFILEMENU 939 //menubar\r\n#define IPC_SPAWNPEPLAYLISTMENU 940 //menubar\r\n#define IPC_SPAWNPESORTMENU 941 //menubar\r\n#define IPC_SPAWNPEHELPMENU 942 //menubar\r\n#define IPC_SPAWNMLFILEMENU 943 //menubar\r\n#define IPC_SPAWNMLVIEWMENU 944 //menubar\r\n#define IPC_SPAWNMLHELPMENU 945 //menubar\r\n#define IPC_SPAWNPELISTOFPLAYLISTS 946\r\n\r\ntypedef struct\r\n{\r\n  HWND wnd;\r\n  int xpos; // in screen coordinates\r\n  int ypos;\r\n} waSpawnMenuParms;\r\n\r\n// waSpawnMenuParms2 is used by the menubar submenus\r\ntypedef struct\r\n{\r\n  HWND wnd;\r\n  int xpos; // in screen coordinates\r\n  int ypos;\r\n  int width;\r\n  int height;\r\n} waSpawnMenuParms2;\r\n\r\n\r\n// system tray sends this (you might want to simulate it)\r\n#define WM_WA_SYSTRAY WM_USER+1\r\n\r\n// input plugins send this when they are done playing back\r\n#define WM_WA_MPEG_EOF WM_USER+2\r\n\r\n\r\n\r\n//// video stuff\r\n\r\n#define IPC_IS_PLAYING_VIDEO 501 // returns >1 if playing, 0 if not, 1 if old version (so who knows):)\r\n#define IPC_GET_IVIDEOOUTPUT 500 // see below for IVideoOutput interface\r\n#define VIDEO_MAKETYPE(A,B,C,D) ((A) | ((B)<<8) | ((C)<<16) | ((D)<<24))\r\n#define VIDUSER_SET_INFOSTRING 0x1000\r\n#define VIDUSER_GET_VIDEOHWND  0x1001\r\n#define VIDUSER_SET_VFLIP      0x1002\r\n#define VIDUSER_SET_TRACKSELINTERFACE 0x1003 // give your ITrackSelector interface as param2\r\n#define VIDUSER_OPENVIDEORENDERER 0x1004\r\n#define VIDUSER_CLOSEVIDEORENDERER 0x1005\r\n#define VIDUSER_GETPOPUPMENU 0x1006\r\n\r\ntypedef struct\r\n{\r\n\tint w;\r\n\tint h;\r\n\tint vflip;\r\n\tdouble aspectratio;\r\n\tunsigned int fmt;\r\n} VideoOpenStruct;\r\n\r\n#ifndef NO_IVIDEO_DECLARE\r\n#ifdef __cplusplus\r\n\r\nclass VideoOutput;\r\nclass SubsItem;\r\n\r\n#ifndef _NSV_DEC_IF_H_\r\ntypedef\tstruct {\r\n\tunsigned char*\tbaseAddr;\r\n\tlong\t\t\trowBytes;\r\n} YV12_PLANE;\r\n\r\ntypedef\tstruct {\r\n\tYV12_PLANE\ty;\r\n\tYV12_PLANE\tu;\r\n\tYV12_PLANE\tv;\r\n} YV12_PLANES;\r\n#endif\r\n\r\nclass IVideoOutput\r\n{\r\n  public:\r\n    virtual ~IVideoOutput() { }\r\n    virtual int open(int w, int h, int vflip, double aspectratio, unsigned int fmt)=0;\r\n    virtual void setcallback(LRESULT (*msgcallback)(void *token, HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam), void *token)\t\t{ (void)token; (void)msgcallback; /* to eliminate warning C4100 */ }\r\n    virtual void close()=0;\r\n    virtual void draw(void *frame)=0;\r\n    virtual void drawSubtitle(SubsItem *item) { }\r\n    virtual void showStatusMsg(const char *text) { }\r\n    virtual int get_latency() { return 0; }\r\n    virtual void notifyBufferState(int bufferstate) { } /* 0-255*/\r\n\r\n    virtual INT_PTR extended(INT_PTR param1, INT_PTR param2, INT_PTR param3) { return 0; } // Dispatchable, eat this!\r\n};\r\n\r\nclass ITrackSelector \r\n{\r\n  public:\r\n    virtual int getNumAudioTracks()=0;\r\n    virtual void enumAudioTrackName(int n, const char *buf, int size)=0;\r\n    virtual int getCurAudioTrack()=0;\r\n    virtual int getNumVideoTracks()=0;\r\n    virtual void enumVideoTrackName(int n, const char *buf, int size)=0;\r\n    virtual int getCurVideoTrack()=0;\r\n\r\n    virtual void setAudioTrack(int n)=0;\r\n    virtual void setVideoTrack(int n)=0;\r\n};\r\n\r\n#endif //cplusplus\r\n#endif//NO_IVIDEO_DECLARE\r\n\r\n// these messages are callbacks that you can grab by subclassing the winamp window\r\n\r\n// wParam = \r\n#define IPC_CB_WND_EQ 0 // use one of these for the param\r\n#define IPC_CB_WND_PE 1\r\n#define IPC_CB_WND_MB 2\r\n#define IPC_CB_WND_VIDEO 3\r\n#define IPC_CB_WND_MAIN 4\r\n\r\n#define IPC_CB_ONSHOWWND 600 \r\n#define IPC_CB_ONHIDEWND 601 \r\n\r\n#define IPC_CB_GETTOOLTIP 602\r\n\r\n#define IPC_CB_MISC 603\r\n    #define IPC_CB_MISC_TITLE 0\r\n    #define IPC_CB_MISC_VOLUME 1 // volume/pan\r\n    #define IPC_CB_MISC_STATUS 2\r\n    #define IPC_CB_MISC_EQ 3\r\n    #define IPC_CB_MISC_INFO 4\r\n    #define IPC_CB_MISC_VIDEOINFO 5\r\n\r\n#define IPC_CB_CONVERT_STATUS 604 // param value goes from 0 to 100 (percent)\r\n#define IPC_CB_CONVERT_DONE   605\r\n\r\n#define IPC_ADJUST_FFWINDOWSMENUPOS 606\r\n/* (requires Winamp 2.9+)\r\n** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFWINDOWSMENUPOS);\r\n** moves where winamp expects the freeform windows in the menubar windows main menu. Useful if you wish to insert a\r\n** menu item above extra freeform windows.\r\n*/\r\n\r\n#define IPC_ISDOUBLESIZE 608\r\n\r\n#define IPC_ADJUST_FFOPTIONSMENUPOS 609\r\n/* (requires Winamp 2.9+)\r\n** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFOPTIONSMENUPOS);\r\n** moves where winamp expects the freeform preferences item in the menubar windows main menu. Useful if you wish to insert a\r\n** menu item above preferences item.\r\n*/\r\n\r\n#define IPC_GETTIMEDISPLAYMODE 610 // returns 0 if displaying elapsed time or 1 if displaying remaining time\r\n\r\n#define IPC_SETVISWND 611 // param is hwnd, setting this allows you to receive ID_VIS_NEXT/PREVOUS/RANDOM/FS wm_commands\r\n#define ID_VIS_NEXT                     40382\r\n#define ID_VIS_PREV                     40383\r\n#define ID_VIS_RANDOM                   40384\r\n#define ID_VIS_FS                       40389\r\n#define ID_VIS_CFG                      40390\r\n#define ID_VIS_MENU                     40391\r\n\r\n#define IPC_GETVISWND 612 // returns the vis cmd handler hwnd\r\n#define IPC_ISVISRUNNING 613\r\n#define IPC_CB_VISRANDOM 628 // param is status of random\r\n\r\n#define IPC_SETIDEALVIDEOSIZE 614 // sent by winamp to winamp, trap it if you need it. width=HIWORD(param), height=LOWORD(param)\r\n\r\n#define IPC_GETSTOPONVIDEOCLOSE 615\r\n#define IPC_SETSTOPONVIDEOCLOSE 616\r\n\r\ntypedef struct {\r\n  HWND hwnd;\r\n  int uMsg;\r\n  WPARAM wParam;\r\n  LPARAM lParam;\r\n} transAccelStruct;\r\n\r\n#define IPC_TRANSLATEACCELERATOR 617\r\n\r\ntypedef struct {\r\n  int cmd;\r\n  int x;\r\n  int y;\r\n  int align;\r\n} windowCommand; // send this as param to an IPC_PLCMD, IPC_MBCMD, IPC_VIDCMD\r\n\r\n#define IPC_CB_ONTOGGLEAOT 618 \r\n\r\n#define IPC_GETPREFSWND 619\r\n\r\n#define IPC_SET_PE_WIDTHHEIGHT 620 // data is a pointer to a POINT structure that holds width & height\r\n\r\n#define IPC_GETLANGUAGEPACKINSTANCE 621\r\n\r\n#define IPC_CB_PEINFOTEXT 622 // data is a string, ie: \"04:21/45:02\"\r\n\r\n#define IPC_CB_OUTPUTCHANGED 623 // output plugin was changed in config\r\n\r\n#define IPC_GETOUTPUTPLUGIN 625\r\n\r\n#define IPC_SETDRAWBORDERS 626\r\n#define IPC_DISABLESKINCURSORS 627\r\n#define IPC_CB_RESETFONT 629\r\n\r\n#define IPC_IS_FULLSCREEN 630 // returns 1 if video or vis is in fullscreen mode\r\n#define IPC_SET_VIS_FS_FLAG 631 // a vis should send this message with 1/as param to notify winamp that it has gone to or has come back from fullscreen mode\r\n\r\n#define IPC_SHOW_NOTIFICATION 632\r\n\r\n#define IPC_GETSKININFO 633\r\n\r\n#define IPC_GET_MANUALPLADVANCE 634\r\n/* (requires Winamp 5.03+)\r\n** val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_MANUALPLADVANCE);\r\n**\r\n** IPC_GET_MANUALPLADVANCE returns the status of the Manual Playlist Advance (1 if set)\r\n*/\r\n\r\n#define IPC_SET_MANUALPLADVANCE 635\r\n/* (requires Winamp 5.03+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_MANUALPLADVANCE);\r\n**\r\n** IPC_SET_MANUALPLADVANCE sets the status of the Manual Playlist Advance option (1 to turn it on)\r\n*/\r\n\r\n#define IPC_GET_NEXT_PLITEM 636\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_NEXT_PLITEM);\r\n**\r\n** Sent to Winamp's main window when an item has just finished playback or the next button has been pressed and \r\n** requesting the new playlist item number to go to.\r\n** Mainly used by gen_jumpex. Subclass this message in your application to return the new item number. \r\n** -1 for normal winamp operation (default) or the new item number in the playlist to play.\r\n*/\r\n\r\n#define IPC_GET_PREVIOUS_PLITEM 637\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_PREVIOUS_PLITEM);\r\n**\r\n** Sent to Winamp's main window when the previous button has been pressed and Winamp is requesting the new playlist item number to go to.\r\n** Mainly used by gen_jumpex. Subclass this message in your application to return the new item number. \r\n** -1 for normal winamp operation (default) or the new item number in the playlist to play.\r\n*/\r\n\r\n#define IPC_IS_WNDSHADE 638 \r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,wnd,IPC_IS_WNDSHADE);\r\n**\r\n** 'wnd' is window id as defined for IPC_GETWND, or -1 for main window\r\n** Returns 1 if wnd is set to winshade mode, or 0 if it is not\r\n*/\r\n\r\n#define IPC_SETRATING 639 \r\n/* (requires Winamp 5.04+ with ML)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,rating,IPC_SETRATING);\r\n** 'rating' is an int value from 0 (no rating) to 5 \r\n*/\r\n\r\n#define IPC_GETRATING 640 \r\n/* (requires Winamp 5.04+ with ML)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING);\r\n** returns the current item's rating\r\n*/\r\n\r\n#define IPC_GETNUMAUDIOTRACKS 641\r\n/* (requires Winamp 5.04+)\r\n** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMAUDIOTRACKS);\r\n** returns the number of audio tracks for the currently playing item\r\n*/\r\n\r\n#define IPC_GETNUMVIDEOTRACKS 642\r\n/* (requires Winamp 5.04+)\r\n** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMVIDEOTRACKS);\r\n** returns the number of video tracks for the currently playing item\r\n*/\r\n\r\n#define IPC_GETAUDIOTRACK 643\r\n/* (requires Winamp 5.04+)\r\n** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETAUDIOTRACK);\r\n** returns the id of the current audio track for the currently playing item\r\n*/\r\n\r\n#define IPC_GETVIDEOTRACK 644\r\n/* (requires Winamp 5.04+)\r\n** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVIDEOTRACK);\r\n** returns the id of the current video track for the currently playing item\r\n*/\r\n\r\n#define IPC_SETAUDIOTRACK 645\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETAUDIOTRACK);\r\n** switch the currently playing item to a new audio track \r\n*/\r\n\r\n#define IPC_SETVIDEOTRACK 646\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETVIDEOTRACK);\r\n** switch the currently playing item to a new video track \r\n*/\r\n\r\n#define IPC_PUSH_DISABLE_EXIT 647\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PUSH_DISABLE_EXIT );\r\n** lets you disable or re-enable the UI exit functions (close button, \r\n** context menu, alt-f4).\r\n** call IPC_POP_DISABLE_EXIT when you are done doing whatever required \r\n** preventing exit\r\n*/\r\n\r\n#define IPC_POP_DISABLE_EXIT  648\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_POP_DISABLE_EXIT );\r\n** see IPC_PUSH_DISABLE_EXIT\r\n*/\r\n\r\n#define IPC_IS_EXIT_ENABLED 649\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_EXIT_ENABLED);\r\n** returns 0 if exit is disabled, 1 otherwise\r\n*/\r\n\r\n#define IPC_IS_AOT 650\r\n/* (requires Winamp 5.04+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_AOT);\r\n** returns status of always on top flag. note: this may not match the actual\r\n** TOPMOST window flag while another fullscreen application is focused\r\n*/\r\n\r\n#define IPC_USES_RECYCLEBIN 651\r\n/*\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN);\r\n** returns 1 if deleted files should be sent to the recycle bin.\r\n** returns 0 if deleted files should be deleted permanently.\r\n** \r\n** You should check for this option if your plugin deletes files\r\n** so that your setting matches the winamp setting\r\n*/\r\n\r\n#define IPC_FLUSHAUDITS 652\r\n/*\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_FLUSHAUDITS);\r\n** \r\n** Will flush any pending audits in the global audits que\r\n**\r\n*/\r\n\r\n#define IPC_GETPLAYITEM_START 653\r\n#define IPC_GETPLAYITEM_END   654\r\n\r\n\r\n#define IPC_GETVIDEORESIZE 655\r\n#define IPC_SETVIDEORESIZE 656\r\n\r\n// >>>>>>>>>>> Next is 657\r\n\r\n#define IPC_PLCMD  1000 \r\n\r\n#define PLCMD_ADD  0\r\n#define PLCMD_REM  1\r\n#define PLCMD_SEL  2\r\n#define PLCMD_MISC 3\r\n#define PLCMD_LIST 4\r\n\r\n//#define IPC_MBCMD  1001 \r\n\r\n#define MBCMD_BACK    0\r\n#define MBCMD_FORWARD 1\r\n#define MBCMD_STOP    2\r\n#define MBCMD_RELOAD  3\r\n#define MBCMD_MISC  4\r\n\r\n#define IPC_VIDCMD 1002 \r\n\r\n#define VIDCMD_FULLSCREEN 0\r\n#define VIDCMD_1X         1\r\n#define VIDCMD_2X         2\r\n#define VIDCMD_LIB        3\r\n#define VIDPOPUP_MISC     4\r\n\r\n//#define IPC_MBURL       1003 //sets the URL\r\n//#define IPC_MBGETCURURL 1004 //copies the current URL into wParam (have a 4096 buffer ready)\r\n//#define IPC_MBGETDESC   1005 //copies the current URL description into wParam (have a 4096 buffer ready)\r\n//#define IPC_MBCHECKLOCFILE 1006 //checks that the link file is up to date (otherwise updates it). wParam=parent HWND\r\n//#define IPC_MBREFRESH   1007 //refreshes the \"now playing\" view in the library\r\n//#define IPC_MBGETDEFURL 1008 //copies the default URL into wParam (have a 4096 buffer ready)\r\n\r\n#define IPC_STATS_LIBRARY_ITEMCNT 1300 // updates library count status\r\n\r\n// IPC 2000-3000 reserved for freeform messages, see gen_ff/ff_ipc.h\r\n#define IPC_FF_FIRST 2000\r\n#define IPC_FF_LAST  3000\r\n\r\n\r\n/*\r\n** General IPC messages in Winamp\r\n**\r\n** All notification messages appear in the lParam of the main window message proceedure.\r\n*/\r\n\r\n\r\n#define IPC_GETDROPTARGET 3001\r\n/* (requires Winamp 5.0+)\r\n** IDropTarget* IDrop = (IDropTarget*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETDROPTARGET);\r\n**\r\n** You call this to retrieve a copy of the IDropTarget interface which Winamp created for\r\n** handling external drag and drop operations on to it's Windows. This is only really\r\n** useful if you're providing an alternate interface and want your Windows to provide the\r\n** same drag and drop support as Winamp normally provides the user. Check out MSDN or\r\n** your prefered search facility for more information about the IDropTarget interface and\r\n** what's needed to handle it in your own instance.\r\n*/\r\n\r\n#define IPC_PLAYLIST_MODIFIED 3002 \r\n/* (requires Winamp 5.0+)\r\n** This is a notification message sent to the main Winamp window whenever the playlist is\r\n** modified in any way e.g. the addition/removal of a playlist entry.\r\n**\r\n** It is not a good idea to do large amounts of processing in this notification since it\r\n** will slow down Winamp as playlist entries are modified (especially when you're adding\r\n** in a large playlist).\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYLIST_MODIFIED){\r\n**   // do what you need to do here\r\n** }\r\n*/\r\n\r\n#define IPC_PLAYING_FILE 3003 \r\n/* (requires Winamp 5.0+)\r\n** This is a notification message sent to the main Winamp window when playback begins for\r\n** a file. This passes the full filepath in the wParam of the message received.\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILE){\r\n**   // do what you need to do here, e.g.\r\n**   process_file((char*)wParam);\r\n** }\r\n*/\r\n\r\n#define IPC_PLAYING_FILEW 13003 \r\n/* (requires Winamp 5.0+)\r\n** This is a notification message sent to the main Winamp window when playback begins for\r\n** a file. This passes the full filepath in the wParam of the message received.\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILEW){\r\n**   // do what you need to do here, e.g.\r\n**   process_file((wchar_t*)wParam);\r\n** }\r\n*/\r\n\r\n#define IPC_FILE_TAG_MAY_HAVE_UPDATED 3004 // sent to main wnd with the file as parm whenever a file tag might be updated\r\n/* (requires Winamp 5.0+)\r\n** This is a notification message sent to the main Winamp window when a file's tag\r\n** (e.g. id3) may have been updated. This appears to be sent when the InfoBox(..) function\r\n** of the associated input plugin returns a 1 (which is the file information dialog/editor\r\n** call normally).\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == IPC_FILE_TAG_MAY_HAVE_UPDATED){\r\n**   // do what you need to do here, e.g.\r\n**   update_info_on_file_update((char*)wParam);\r\n** }\r\n*/\r\n\r\n#define IPC_ALLOW_PLAYTRACKING 3007\r\n/* (requires Winamp 5.0+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,allow,IPC_ALLOW_PLAYTRACKING);\r\n** Send allow as nonzero to allow play tracking and zero to disable the mode.\r\n*/\r\n\r\n#define IPC_HOOK_OKTOQUIT 3010 \r\n/* (requires Winamp 5.0+)\r\n** This is a notification message sent to the main Winamp window asking if it's okay to\r\n** close or not. Return zero to prevent Winamp from closing or return anything non-zero\r\n** to allow Winamp to close.\r\n**\r\n** The best implementation of this option is to let the message pass through to the\r\n** original window proceedure since another plugin may want to have a say in the matter\r\n** with regards to Winamp closing.\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == IPC_HOOK_OKTOQUIT){\r\n**   // do what you need to do here, e.g.\r\n**   if(no_shut_down()){\r\n**     return 1;\r\n**   }\r\n** }\r\n*/\r\n\r\n#define IPC_WRITECONFIG 3011\r\n/* (requires Winamp 5.0+)\r\n** SendMessage(hwnd_winamp,WM_WA_IPC,write_type,IPC_WRITECONFIG);\r\n**\r\n** Send write_type as 2 to write all config settings and the current playlist.\r\n**\r\n** Send write_type as 1 to write the playlist and common settings.\r\n** This won't save the following ini settings::\r\n**\r\n**   defext, titlefmt, proxy, visplugin_name, dspplugin_name, check_ft_startup,\r\n**   visplugin_num, pe_fontsize, visplugin_priority, visplugin_autoexec, dspplugin_num,\r\n**   sticon, splash, taskbar, dropaotfs, ascb_new, ttips, riol, minst, whichicon,\r\n**   whichicon2, addtolist, snap, snaplen, parent, hilite, disvis, rofiob, shownumsinpl,\r\n**   keeponscreen, eqdsize, usecursors, fixtitles, priority, shuffle_morph_rate,\r\n**   useexttitles, bifont, inet_mode, ospb, embedwnd_freesize, no_visseh\r\n** (the above was valid for 5.1)\r\n**\r\n** Send write_type as 0 to write the common and less common settings and no playlist.\r\n*/\r\n\r\n#define IPC_UPDATE_URL 3012\t// pass the URL (char *) in lparam, will be free()'d on done. \r\n\r\n// pass a string to be the name to register, and returns a value > 65536, which is a unique value you can use\r\n// for custom WM_WA_IPC messages. \r\n\r\n#define IPC_GET_RANDFUNC 3015 // returns a function to get a random number\r\n/* (requires Winamp 5.1+)\r\n** int (*randfunc)(void) = (int(*)(void))SendMessage(plugin.hwndParent,WM_WA_IPC,0,IPC_GET_RANDFUNC);\r\n** if(randfunc && randfunc != 1){\r\n**   randfunc();\r\n** }\r\n**\r\n** This will return a positive 32-bit number (essentially 31-bit).\r\n** The check for a returned value of 1 is because that's the default return value from\r\n** SendMessage(..) when it is not handled so is good to check for it in this situation.\r\n*/\r\n\r\n#define IPC_METADATA_CHANGED 3017 \r\n/* (requires Winamp 5.1+)\r\n** int changed=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)field,IPC_METADATA_CHANGED);\r\n** a plugin can SendMessage this to winamp if internal metadata has changes.\r\n** wParam should be a char * of what field changed\r\n**\r\n** Currently used for internal actions (and very few at that) the intent of this api is\r\n** to allow a plugin to call it when metadata has changed in the current playlist entry\r\n** e.g.a new id3v2 tag was found in a stream\r\n**\r\n** The wparam value can either be NULL or a pointer to an ansi string for the metadata\r\n** which has changed. This can be thought of as an advanced version of IPC_UPDTITLE and\r\n** could be used to allow for update of the current title when a specific tag changed.\r\n**\r\n** Not recommended to be used since there is not the complete handling implemented in\r\n** Winamp for it at the moment.\r\n*/\r\n\r\n#define IPC_SKIN_CHANGED 3018 \r\n/* (requires Winamp 5.1+)\r\n** This is a notification message sent to the main Winamp window by itself whenever\r\n** the skin in use is changed. There is no information sent by the wParam for this.\r\n**\r\n** if(message == WM_WA_IPC && lparam == IPC_SKIN_CHANGED){\r\n**   // do what you need to do to handle skin changes, e.g. call WADlg_init(hwnd_winamp);\r\n** }\r\n*/\r\n\r\n#define IPC_REGISTER_LOWORD_COMMAND 3019 \r\n/* (requires Winamp 5.1+)\r\n** WORD id = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REGISTER_LOWORD_COMMAND);\r\n** This will assign you a unique id for making your own commands such as for extra menu\r\n** entries. The starting value returned by this message will potentially change as and\r\n** when the main resource file of Winamp is updated with extra data so assumptions cannot\r\n** be made on what will be returned and plugin loading order will affect things as well.\r\n*/\r\n\r\n#define IPC_GET_DISPATCH_OBJECT 3020  // gets winamp main IDispatch * (for embedded webpages)\r\n#define IPC_GET_UNIQUE_DISPATCH_ID 3021 // gives you a unique dispatch ID that won't conflict with anything in winamp's IDispatch *\r\n\r\n#define IPC_ADD_DISPATCH_OBJECT 3022 // add your own dispatch object into winamp's.  This lets embedded webpages access your functions\r\n// pass a pointer to DispatchInfo (see below).  Winamp makes a copy of all this data so you can safely delete it later\r\ntypedef struct \r\n{\r\n\twchar_t *name; // filled in by plugin, make sure it's a unicode string!! (i.e. L\"myObject\" instead of \"myObject).\r\n\tstruct IDispatch *dispatch; // filled in by plugin \r\n\tDWORD id; // filled in by winamp on return\r\n} DispatchInfo;\r\n\r\n#define IPC_GET_PROXY_STRING 3023\r\n/* (requires Winamp 5.11+)\r\n** char* proxy_string=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_PROXY_STRING);\r\n** This will return the same string as is shown on the General Preferences page.\r\n*/\r\n\r\n#define IPC_USE_REGISTRY 3024 \r\n/* (requires Winamp 5.11+)\r\n** int reg_enabled=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USE_REGISTRY);\r\n** This will return 0 if you should leave your grubby hands off the registry (i.e. for\r\n** lockdown mode). This is useful if Winamp is run from a USB drive and you can't alter\r\n** system settings, etc.\r\n*/\r\n\r\n#define IPC_GET_API_SERVICE 3025 \r\n/* (requires Winamp 5.12+)\r\n** api_service* api_service = (api_service)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_API_SERVICE);\r\n** This api will return Winamp's api_service pointer (which is what Winamp3 used, heh).\r\n** If this api is not supported in the Winamp version that is being used at the time then\r\n** the returned value from this api will be 1 which is a good version check.\r\n**\r\n** As of 5.12 there is support for .w5s plugins which reside in %WinampDir%\\System and\r\n** are intended for common code that can be shared amongst other plugins e.g. jnetlib.w5s\r\n** which contains jnetlib in one instance instead of being duplicated multiple times in\r\n** all of the plugins which need internet access.\r\n**\r\n** Details on the .w5s specifications will come at some stage (possibly).\r\n*/\r\n\r\n\r\n\r\ntypedef struct {\r\n  const wchar_t *filename;\r\n  const wchar_t *metadata;\r\n  wchar_t *ret;\r\n  int retlen;\r\n} extendedFileInfoStructW;\r\n\r\n#define IPC_GET_EXTENDED_FILE_INFOW 3026 \r\n/* (requires Winamp 5.13+)\r\n** Pass a pointer to the above struct in wParam\r\n*/\r\n#define IPC_GET_EXTENDED_FILE_INFOW_HOOKABLE 3027\r\n#define IPC_SET_EXTENDED_FILE_INFOW 3028 \r\n/* (requires Winamp 5.13+)\r\n** Pass a pointer to the above struct in wParam\r\n*/\r\n\r\n#define IPC_PLAYLIST_GET_NEXT_SELECTED 3029\r\n/* (requires 5.2+)\r\n** int pl_item = SendMessage(hwnd_winamp,WM_WA_IPC,start,IPC_PLAYLIST_GET_NEXT_SELECTED);\r\n**\r\n** This works just like the ListView_GetNextItem(..) macro for ListView controls.\r\n** 'start' is the index of the playlist item that you want to begin the search after or\r\n** set this as -1 for the search to begin with the first item of the current playlist.\r\n**\r\n** This will return the index of the selected playlist according to the 'start' value or\r\n** it returns -1 if there is no selection or no more selected items according to 'start'.\r\n**\r\n** Quick example:\r\n**\r\n** int sel = -1;\r\n** // keep incrementing the start of the search so we get all of the selected entries\r\n** while((sel = SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_PLAYLIST_GET_NEXT_SELECTED))!=-1){\r\n**   // show the playlist file entry of the selected item(s) if there were any\r\n**   MessageBox(hwnd_winamp,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_GETPLAYLISTFILE),0,0);\r\n** }\r\n*/\r\n\r\n#define IPC_PLAYLIST_GET_SELECTED_COUNT 3030\r\n/* (requires 5.2+)\r\n** int selcnt = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PLAYLIST_GET_SELECTED_COUNT);\r\n** This will return the number of selected playlist entries.\r\n*/\r\n\r\n#define IPC_GET_PLAYING_FILENAME 3031 // returns wchar_t * of the currently playing filename\r\n\r\n#define IPC_OPEN_URL 3032 // send either ANSI or Unicode string (it'll figure it out, but it MUST start with \"h\"!, so don't send ftp:// or anything funny)\r\n\r\n#define IPC_REGISTER_WINAMP_IPCMESSAGE 65536 \r\n/* (requires Winamp 5.0+)\r\n** DWORD id = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)name,IPC_REGISTER_WINAMP_IPCMESSAGE);\r\n** The value 'id' returned is > 65536 and is incremented on subsequent calls for unique\r\n** 'name' values passed to it. By using the same 'name' in different plugins will allow a\r\n** common runtime api to be provided for the currently running instance of Winamp\r\n** e.g.\r\n**   PostMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)my_param,registered_ipc);\r\n** Have a look at wa_hotkeys.h for an example on how this api is used in practice for a\r\n** custom WM_WA_IPC message.\r\n**\r\n** if(uMsg == WM_WA_IPC && lParam == id_from_register_winamp_ipcmessage){\r\n**   // do things\r\n** }\r\n*/\r\n\r\n#endif//_WA_IPC_H_"
  },
  {
    "path": "plugins/winamp/winamp_install.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=2.1.0.11\r\n\r\n[Setup]\r\nOutputBaseFilename=WinampPluginSetup_2.1.0.11\r\n; setup.exe version\r\nVersionInfoVersion=2.1.0.11\r\nVersionInfoTextVersion=2.1.0.11\r\nAppName=Last.fm Winamp Plugin\r\nAppVerName=Last.fm Winamp Plugin {cm:Version}\r\nVersionInfoDescription=Last.fm Winamp Plugin Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright  Ltd (c)\r\nDefaultDirName=\"{pf}\\Winamp\\plugins\"\r\nUsePreviousAppDir=yes\r\nUninstallFilesDir={commonappdata}\\Last.fm\\Client\\UninstWA\r\nOutputDir=.\r\nCompression=lzma\r\nSolidCompression=yes\r\nDirExistsWarning=no\r\nDisableReadyPage=yes\r\n; Keep this the same across versions, even if they're incompatible. That will ensure\r\n; uninstallation works fine after many upgrades. Can't use GUID as it'll break backward\r\n; compatibility.\r\nAppId=Audioscrobbler Winamp Plugin\r\nCreateUninstallRegKey=no\r\n\r\n[Registry]\r\n; The name of the final subkey here must match the one in plugins.data\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\wa2\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\wa2\"; ValueType: string; ValueName: \"Name\"; ValueData: \"Winamp\"; Flags: uninsdeletekey\r\n\r\n[Languages]\r\nName: \"english\"; MessagesFile: \"compiler:Default.isl\"\r\n\r\n[InstallDelete]\r\n; Delete any old plugins present\r\nType: files; Name: \"{app}\\gen_audioscrobbler.dll\"\r\nType: files; Name: \"{app}\\ml_audioscrobbler.dll\"\r\n\r\n[UninstallDelete]\r\n; Need to specify both here as we can't be sure the final filename is ml_\r\nType: files; Name: \"{app}\\gen_wa2_scrobbler.dll\"\r\nType: files; Name: \"{app}\\ml_wa2_scrobbler.dll\"\r\n\r\n; For legacy reasons\r\nType: files; Name: \"{app}\\AudioScrobbler.log.txt\"\r\n\r\n; Try and delete the localappdata log for the case where the user running the uninstaller is the same as the plugin user\r\nType: files; Name: \"{localappdata}\\Last.fm\\Client\\WinampPlugin.log\"\r\n\r\n[Files]\r\nSource: \"Release\\ml_wa2_scrobbler.dll\"; DestDir: \"{app}\"; DestName: \"{code:GetDestName}\"; Flags: ignoreversion\r\n\r\n[Run]\r\n; Nothing here. Now taken care of in CurStepChanged.\r\n\r\n[Code]\r\nfunction GetDestName(Param: String): String;\r\nvar\r\n  ml_file: String;\r\n  ml_file_exists: Boolean;\r\nbegin\r\n  ml_file := ExpandConstant('{app}\\gen_ml.dll');\r\n\r\n  ml_file_exists := FileExists(ml_file);\r\n\r\n  if (ml_file_exists = FALSE) then\r\n  begin\r\n      Result := 'gen_wa2_scrobbler.dll';\r\n  end\r\n  else\r\n  begin\r\n    Result := 'ml_wa2_scrobbler.dll';\r\n  end\r\nend;\r\n\r\nprocedure CurStepChanged(CurStep: TSetupStep);\r\nvar\r\n  batfile: String;\r\n  batcontent: String;\r\n  uninstaller: String;\r\n  alreadyAdded: Boolean;\r\n  cmdToAdd: String;\r\nbegin\r\n  if (CurStep = ssPostInstall) then\r\n  begin\r\n    //MsgBox('postinstall', mbInformation, MB_OK);\r\n\r\n    batfile := ExpandConstant('{commonappdata}\\Last.fm\\Client\\uninst2.bat');\r\n    LoadStringFromFile(batfile, batcontent);\r\n    //MsgBox('loaded string: ' + batcontent, mbInformation, MB_OK);\r\n\r\n    uninstaller := ExpandConstant('{uninstallexe}');\r\n    //MsgBox('uninstaller pre-OEM: ' + uninstaller, mbInformation, MB_OK);\r\n\r\n    alreadyAdded := (Pos(uninstaller, batcontent) <> 0);\r\n    if (alreadyAdded = False) then\r\n    begin\r\n      cmdToAdd := uninstaller + #13#10;\r\n      //MsgBox('not present, will add: ' + cmdToAdd, mbInformation, MB_OK);\r\n\r\n      SaveStringToFile(batfile, cmdToAdd, True)\r\n    end;\r\n\r\n  end;\r\n  \r\nend;\r\n"
  },
  {
    "path": "plugins/winamp/winampcmd.h",
    "content": "#define WINAMP_STOPPED\t\t\t\t\t0\r\n#define WINAMP_PLAYING\t\t\t\t\t1\r\n#define\tWINAMP_PAUSED\t\t\t\t\t3\r\n\r\n#define WINAMP_FILE_QUIT\t\t\t40001\r\n#define WINAMP_OPTIONS_PREFS\t\t40012\r\n#define WINAMP_OPTIONS_AOT\t\t\t40019\r\n#define WINAMP_FILE_REPEAT\t\t\t40022\r\n#define WINAMP_FILE_SHUFFLE\t\t\t40023\r\n#define WINAMP_HIGH_PRIORITY\t\t40025\r\n#define WINAMP_FILE_PLAY\t\t\t40029\r\n#define WINAMP_OPTIONS_EQ\t\t\t40036\r\n#define WINAMP_OPTIONS_ELAPSED\t\t40037\r\n#define WINAMP_OPTIONS_REMAINING\t40038\r\n#define WINAMP_OPTIONS_PLEDIT\t\t40040\r\n#define WINAMP_HELP_ABOUT\t\t\t40041\r\n#define WINAMP_MAINMENU\t\t\t\t40043\r\n#define WINAMP_REWIND\t\t\t\t40044\r\n#define WINAMP_PLAY\t\t\t\t\t40045\r\n#define WINAMP_PAUSE\t\t\t\t40046\r\n#define WINAMP_STOP\t\t\t\t\t40047\r\n#define WINAMP_FASTFWD\t\t\t\t40048\r\n#define WINAMP_VOLUMEUP\t\t\t\t40058\r\n#define WINAMP_VOLUMEDOWN\t\t\t40059\r\n#define WINAMP_FFWD5S\t\t\t\t40060\r\n#define WINAMP_REW5S\t\t\t\t40061\r\n#define WINAMP_NEXT_WINDOW\t\t\t40063\r\n#define WINAMP_OPTIONS_WINDOWSHADE\t40064\r\n#define WINAMP_REWIND_SHIFT\t\t\t40144\r\n#define WINAMP_PLAY_SHIFT\t\t\t40145\r\n#define WINAMP_PAUSE_SHIFT\t\t\t40146\r\n#define WINAMP_STOP_SHIFT\t\t\t40147\r\n#define WINAMP_FASTFWD_SHIFT\t\t40148\r\n#define WINAMP_REWIND_CTRL\t\t\t40154\r\n#define WINAMP_PLAY_CTRL\t\t\t40155\r\n#define WINAMP_PAUSE_CTRL\t\t\t40156\r\n#define WINAMP_STOP_CTRL\t\t\t40157\r\n#define WINAMP_FASTFWD_CTRL\t\t\t40158\r\n#define WINAMP_OPTIONS_DSIZE\t\t40165\r\n#define IDC_SORT_FILENAME\t\t\t40166\r\n#define IDC_SORT_FILETITLE\t\t\t40167\r\n#define IDC_SORT_ENTIREFILENAME\t\t40168\r\n#define IDC_SELECTALL\t\t\t\t40169\r\n#define IDC_SELECTNONE\t\t\t\t40170\r\n#define IDC_SELECTINV\t\t\t\t40171\r\n#define IDM_EQ_LOADPRE\t\t\t\t40172\r\n#define IDM_EQ_LOADMP3\t\t\t\t40173\r\n#define IDM_EQ_LOADDEFAULT\t\t\t40174\r\n#define IDM_EQ_SAVEPRE\t\t\t\t40175\r\n#define IDM_EQ_SAVEMP3\t\t\t\t40176\r\n#define IDM_EQ_SAVEDEFAULT\t\t\t40177\r\n#define IDM_EQ_DELPRE\t\t\t\t40178\r\n#define IDM_EQ_DELMP3\t\t\t\t40180\r\n#define IDC_PLAYLIST_PLAY\t\t\t40184\r\n#define WINAMP_FILE_LOC\t\t\t\t40185\r\n#define WINAMP_OPTIONS_EASYMOVE\t\t40186\r\n#define WINAMP_FILE_DIR\t\t\t\t40187\r\n#define WINAMP_EDIT_ID3\t\t\t\t40188\r\n#define WINAMP_TOGGLE_AUTOSCROLL\t40189\r\n#define WINAMP_VISSETUP\t\t\t\t40190\r\n#define WINAMP_PLGSETUP\t\t\t\t40191\r\n#define WINAMP_VISPLUGIN\t\t\t40192\r\n#define WINAMP_JUMP\t\t\t\t\t40193\r\n#define WINAMP_JUMPFILE\t\t\t\t40194\r\n#define WINAMP_JUMP10FWD\t\t\t40195\r\n#define WINAMP_JUMP10BACK\t\t\t40197\r\n\r\n#define WINAMP_OPTIONS_EQ               40036 // toggles the EQ window\r\n#define WINAMP_OPTIONS_PLEDIT           40040 // toggles the playlist window\r\n#define WINAMP_VOLUMEUP                 40058 // turns the volume up a little\r\n#define WINAMP_VOLUMEDOWN               40059 // turns the volume down a little\r\n#define WINAMP_FFWD5S                   40060 // fast forwards 5 seconds\r\n#define WINAMP_REW5S                    40061 // rewinds 5 seconds\r\n\r\n// the following are the five main control buttons, with optionally shift \r\n// or control pressed\r\n// (for the exact functions of each, just try it out)\r\n#define WINAMP_BUTTON1                  40044\r\n#define WINAMP_BUTTON2                  40045\r\n#define WINAMP_BUTTON3                  40046\r\n#define WINAMP_BUTTON4                  40047\r\n#define WINAMP_BUTTON5                  40048\r\n#define WINAMP_BUTTON1_SHIFT            40144\r\n#define WINAMP_BUTTON2_SHIFT            40145\r\n#define WINAMP_BUTTON3_SHIFT            40146\r\n#define WINAMP_BUTTON4_SHIFT            40147\r\n#define WINAMP_BUTTON5_SHIFT            40148\r\n#define WINAMP_BUTTON1_CTRL             40154\r\n#define WINAMP_BUTTON2_CTRL             40155\r\n#define WINAMP_BUTTON3_CTRL             40156\r\n#define WINAMP_BUTTON4_CTRL             40157\r\n#define WINAMP_BUTTON5_CTRL             40158\r\n\r\n#define WINAMP_FILE_PLAY                40029 // pops up the load file(s) box\r\n#define WINAMP_OPTIONS_PREFS            40012 // pops up the preferences\r\n#define WINAMP_OPTIONS_AOT              40019 // toggles always on top\r\n#define WINAMP_HELP_ABOUT               40041 // pops up the about box :)\r\n"
  },
  {
    "path": "plugins/wmp/Dbg.h",
    "content": "/*##############################################\r\n##\r\n## Module\t\t\t\t: CDebug\r\n## Description\t: Thread-safe logging routines for logging \r\n##                from multiple processes to one log file. \r\n##\r\n##               \tClass includes printf-style formatted output \r\n##                routines, as well as timestamping of entries, \r\n##                process id, and process execution time.\r\n##\r\n##\t\t\t\t\t\t\t\tAlso includes maxfilesize attribute which restricts\r\n##\t\t\t\t\t\t\t\tthe size of the file. Setting this to 0 disables logging\r\n##\t\t\t\t\t\t\t\tsetting it to -1 disables max size.\r\n##\r\n## Author(s)\t\t: Spib\r\n##\r\n##############################################*/\r\n\r\n#ifndef ______DBG_H______\r\n#define ______DBG_H______\r\n\r\n#define DEBUG_DETAIL\t\t1\t\t\t// Low level detailed info\r\n#define DEBUG_FLOW\t\t\t3\t\t\t// Low level program flow Info\r\n#define DEBUG_INFO\t\t\t5\t\t\t// General Info\r\n#define DEBUG_ERROR_NC\t7\t\t\t// Non-Critical Error\r\n#define DEBUG_RQD\t\t\t\t8\t\t\t// Required Info\r\n#define DEBUG_ERROR\t\t\t9\t\t\t// Critical Error\r\n\r\n#define USE_DEBUG_PRINTF\r\n\r\n#ifdef USE_DEBUG_PRINTF\r\n\r\n//\tMacro definitions\r\n///////////////////////////\r\n#define IFDEBUG( doit )\tdoit\r\n\r\n#define DEBUG_INIT\t\t\t\t\tdebug.Init\r\n#define DEBUG_ENABLE\t\t\t\tdebug.Enable\r\n#define DEBUG_IS_ENABLED\t\tdebug.IsEnabled\r\n#define DEBUG_GET_LEVEL\t\t\tdebug.GetLevel\r\n#define DEBUG_SET_LEVEL\t\t\tdebug.SetLevel\r\n#define DEBUG_SET_MAXSIZE\t\tdebug.SetMaxFileSize\r\n#define DEBUG_GET_MAXSIZE\t\tdebug.GetMaxFileSize\r\n#define DEBUG_GET_FILEPATH\tdebug.GetLogFilePath\r\n#define PRINTF\t\t\t\t\t\t\tdebug.printf\r\n#define SHOW_LASTERROR\t\t\tdebug.ShowLastError();\r\n#define CLOSE_LOG\t\t\t\t\t\tdebug.CloseLog();\r\n\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Class        : CDebugPrintf\r\n *  Prototype    : class CDebugPrintf\r\n *  Description  : \r\n *  Parent class : \r\n *  History      : \r\n */\r\nclass CDebug\r\n{\r\npublic:\r\n\tCDebug();\r\n\tvirtual ~CDebug();\r\n\r\n\tvoid Init(const char * strFileName, BOOL bOverWrite = TRUE, BOOL bEnable = TRUE, BOOL bUseXML = FALSE);\r\n\r\n\tvoid printf(int nLevel, const char * module, const char *fmt, ... );\r\n\r\n\tinline BOOL SetLevel(int nLevel)\r\n\t{\r\n\t\tif(nLevel <= DEBUG_ERROR && nLevel >= DEBUG_DETAIL)\r\n\t\t{\r\n\t\t\tm_nLogLevel = nLevel;\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tBOOL SetMaxFileSize(int nSize)\r\n\t{\r\n\t\tif(nSize >= 0)\r\n\t\t{\r\n\t\t\tif(nSize == 0)\r\n\t\t\t\tEnable(FALSE);\r\n\t\t\telse\r\n\t\t\t\tEnable(TRUE);\r\n\r\n\t\t\tm_nMaxFileSize = (nSize * 1024);\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\t\telse if(nSize == -1)\r\n\t\t{\r\n\t\t\tm_nMaxFileSize = -1;\r\n\t\t\tEnable(TRUE);\r\n\t\t\treturn TRUE;\r\n\t\t}\r\n\r\n\t\tCheckFileSize();\r\n\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tinline void Enable(BOOL bEnable = TRUE)\r\n\t{\r\n\t\tm_bEnabled = bEnable;\r\n\t}\r\n\r\n\tvoid\t\t\t\t\t\t\tCloseLog(); \r\n\tvoid\t\t\t\t\t\t\tShowLastError();\r\n\tBOOL\t\t\t\t\t\t\tIsEnabled(){return m_bEnabled;}\r\n\r\n\tint\t\t\t\t\t\t\t\tGetLevel(){return m_nLogLevel;}\r\n\tDWORD\t\t\t\t\t\t\tGetMaxFileSize(){return m_nMaxFileSize;}\r\n\tchar*\t\t\t\t\t\t\tGetLogFilePath(){return m_strFilePath;}\r\n\r\nprivate:\r\n\tBOOL\t\t\t\t\t\t\tOpenLogFile(BOOL bOverWrite = TRUE);\r\n\tvoid\t\t\t\t\t\t\tWriteHeader(BOOL bNewFile = TRUE);\r\n\tvoid\t\t\t\t\t\t\tCheckFileSize();\r\n\tvoid\t\t\t\t\t\t\tReplaceXMLChars(const char* strInput, int nLen, char* strOutput);\r\n\r\n\tHANDLE\t\t\t\t\t\tm_hFile;\t\t\t\t\t\t\t\t\t// Log-file handle\r\n\tCRITICAL_SECTION\tm_hLock;\t\t\t\t\t\t\t\t\t// Lock for thread-safe access\r\n\tchar\t\t\t\t\t\t\tm_strFilePath[MAX_PATH];\t// File Path\r\n\r\n\tDWORD\t\t\t\t\t\t\tm_dwStartTime;\t\t\t\t\t\t// Application start time \r\n\tint\t\t\t\t\t\t\t\tm_nLogLevel;\t\t\t\t\t\t\t// Log Level\r\n\tBOOL\t\t\t\t\t\t\tm_bEnabled;\t\t\t\t\t\t\t\t// Enable / Disable Debug\r\n\tlong\t\t\t\t\t\t\tm_nMaxFileSize;\t\t\t\t\t// Maximum size of log (in bytes)\r\n\tBOOL\t\t\t\t\t\t\tm_bUseXML;\t\t\t\t\t\t\t\t// Output the data as XML?\r\n};\r\n\r\nextern CDebug debug;\r\n\r\n\r\n#else\r\n\r\n#define IFDEBUG( doit )\t\r\n\r\n#define SLASH /\r\n#define COMMENT ;SLASH/\r\n\r\n#define PRINTF\t\t\tCOMMENT\r\n#define SHOW_CONSOLE\tCOMMENT\r\n#define HIDE_CONSOLE\tCOMMENT\r\n#define SHOW_LASTERROR\tCOMMENT\r\n#define CLOSE_LOG\t\tCOMMENT\r\n\r\n#endif\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "plugins/wmp/OSVer.cpp",
    "content": "/*\r\nModule : Dtwinver.cpp\r\nPurpose: Implementation of a comprehensive function to perform OS version detection\r\nCreated: PJN / 11-05-1996\r\nHistory: PJN / 24-02-1997 A number of updates including support for NT 3.1, \r\n                          single mode dos in Windows 95 and better Windows\r\n                          version detecion under real mode dos.\r\n         PJN / 13-09-1998 1.  Added explicit support for Windows 98 \r\n                          2.  Updated documentation to use HTML. \r\n                          3.  Minor update to the web page describing it. \r\n         PJN / 22-06-1999 1.  UNICODE enabled the code.\r\n                          2.  Removed need for the dwOSVersionInfoSize variable\r\n                          3.  Added support for detecting Build Number of 95 and 98 from DOS code path.\r\n                          4.  Now ships as standard with VC 5 workspace files\r\n                          5.  Added explicit support for Windows 95 SP 1\r\n                          6.  Added explicit support for Windows 95 OSR 2\r\n                          7.  Added explicit support for Windows 98 Second Edition\r\n                          8.  Added explicit support for Windows 2000\r\n                          9.  Added explicit support for Windows CE\r\n                          10. Added explicit support for Windows Terminal Server's\r\n                          11. Added explicit support for NT Stand Alone Server's.\r\n                          12. Added explicit support for NT Primary Domain Controller's\r\n                          13. Added explicit support for NT Backup Domain Controller's\r\n         PJN / 23-07-1999 Tested out support for Windows 98 SE, minor changes required\r\n         PJN / 26-07-1999 Added explicit support for Windows 98 SP 1\r\n         PJN / 28-07-1999 1. Fixed a problem when application is build in non-huge/large \r\n                          memory model in Win16\r\n                          2. Added explicit support for returning NT and Win9x service pack information \r\n                          from Win32 and Win16 code paths\r\n                          3. Updated test program to not bother reporting on any info which does not \r\n                          exist. e.g. if there is no service pack installed, then we don't bother \r\n                          displaying any info about service packs\r\n                          4. Added explicit support for NT Enterprise Edition\r\n         PJN / 30-06-2000 1. Added explicit support for Windows Millennium Edition\r\n         PJN / 29-01-2001 1.  Added explicit support for Windows XP (Whistler) Personal\r\n                          2.  Added explicit support for Windows XP (Whistler) Professional\r\n                          3.  Added explicit support for Windows XP (Whistler) Server\r\n                          4.  Added explicit support for Windows XP (Whistler) Advanced Server\r\n                          5.  Added explicit support for Windows XP (Whistler) Datacenter\r\n                          6.  Added explicit support for Windows XP (Whistler) 64 bit (all flavours)\r\n                          7.  Made all the code into a C++ class called COSVersion\r\n                          8.  Rewrote all the generic thunk code to be easier to follow\r\n                          9. Generic think code now uses CallProcEx32W\r\n                          10.  Added explicit support for BackOffice Small Business Edition\r\n                          11. Added explicit support for Terminal Services\r\n                          12. 16 bit code path now can determine ProductSuite and ProductType type\r\n                          thro additional generic thunk code\r\n                          13. Provided a 64 bit test binary and make batch file (make64.bat) for \r\n                          those lucky enough to have an Itanium processor and a beta of 64 bit Windows XP (Whistler).\r\n                          14. Provided a Embedded C++ workspace and X86 Release binary.\r\n                          15. Updated copyright information           \r\n         PJN / 10-02-2001 1. Updated function names etc following MS decision to call Whistler \"Windows XP\"\r\n         PJN / 10-10-2001 1. Added code to 32 bit code path to detect if we are being run under 64 bit Windows. Also\r\n                          updated the sample app to distinguish between emulated 64 bit and underlying \r\n                          64 bit.\r\n                          2. Updated the sample app to call XP Server its proper name which will be \"Windows.NET Server\"\r\n         PJN / 13-12-2001 1. Major upgrade. Now 16 bit DOS path can return as much information as native Win32 code. \r\n                          This is achieved by spawning off the Win32 utility WriteVer with a special command line option.\r\n                          Please note that if you intend deploying dtwinver then you must now ship the writever.exe file\r\n                          in addition to linking in the dtwinver code into your application. Also this utilty needs\r\n                          to be in the path or current directory when the dtwinver code is executing. Thanks to Chaz Angell\r\n                          for prompted me into finding a solution for this last major item missing in dtwinver.\r\n         PJN / 30-12-2002 1. Provided an update CE workspace to work correctly in eMbedded Visual C++ v3. All build configurations\r\n                          for eVC 3 have also been provided.\r\n                          2. Optimized the usage of _tcscat and _tcscpy in the test app which comes with Dtwinver.cpp\r\n                          3. OEM Info string and Platform Type string is now returned for CE code path\r\n                          4. Fixed display of minor version number for example Windows .NET is version number v5.20 but\r\n                          should be shown as 5.2 to be consistent with what the native ver command displays\r\n                          5. Provided a new CE workspace to work correctly in eMbedded Visual C++ v4. All build configurations\r\n                          for eVC 4 have also been provided.\r\n         PJN / 08-10-2002 1. Now uses OSVERSIONINFOEX it possible in the Win32 or Win64 code paths. This provides for\r\n                          more reliably detection of Windows XP Home Edition.\r\n                          2. Renamed the functions which detect Windows .NET Server 2003. Also updated the test code which\r\n                          prints out these names\r\n                          3. Provided explicit support for Windows .NET Web Server\r\n                          4. Fixed a bug in the display of the minor OS version number on Windows .NET Server.\r\n                          5. Made the project for WriteVer a VC 5 project instead of VC 6 which it was up until now.\r\n                          6. Reworked the internal function WhichNTProduct to use a constant input string parameter\r\n                          7. Added explicit support for Windows NT / 2000 / XP Embedded\r\n                          8. Added explicit support for detecting Terminal Services in remote admin mode\r\n         PJN / 10-10-2002 1.  Fixed a problem where on Windows XP, the test program will include the text \"(Standard Edition)\"\r\n                          2.  Added two variables to the OS_VERSION_INFO structure to report the minor service pack number\r\n                          3.  Removed the OS_VERSION_INFO structure from the global namespace\r\n                          4.  Removed all static member variables from the class\r\n                          5.  Added a member variable to the OS_VERSION_INFO to return the various \"suites\" installed\r\n                          6.  reduced the number of calls to WriteVer to 1 when called from dos code path.\r\n                          7.  Completely reworked the internal WhichNTProduct method\r\n                          8.  General tidy up of the header file\r\n                          9.  Completely reworked the ValidateProductSuite method\r\n                          10. Now only 1 call is made to WhichNTProduct throughout a single call to COSVersion::GetVersion\r\n                          11. Now only 1 call is made to ValidateProductSuite throughout a single call to COSVersion::GetVersion\r\n                          12. Fixed an unitialized variable problem in COSVersion::IsUnderlying64Bit\r\n                          13. Changed \"WhichNTProduct\" method to \"GetNTOSTypeFromRegistry\"\r\n                          14. Changed \"ValidateProductSuite\" method to \"GetProductSuiteDetailsFromRegistry\".\r\n                          15. Now correctly reports on Terminal Services being in Remote Admin Mode on OS which do not\r\n                          support calling GetVersionEx using an OSVERSIONINFOEX structure i.e any NT 4 install prior to SP6.\r\n                          16. 16 bit Windows code path now reports as much NT information as the Win32 code path \r\n                          17. Fixed a bug in COSVersion::GetInfoBySpawingWriteVer which was failing if it encountered \r\n                          an empty CSD string. This was spotted on Windows .NET Server which since it is in beta still\r\n                          (as of October 2002) does not have any service pack!.\r\n         PJN / 10-01-2003 1. Update to support MS deciding to change the name of their Whistler Server product. The product \r\n                          will now be called \"Windows Server 2003\".\r\n         PJN / 30-01-2003 1. Added explicit support for detecting NT Service Pack 6a\r\n         PJN / 08-02-2003 1. Added explicit support for detecting Windows XP Service Pack 1a\r\n                          2. Added support to determine the HAL on NT Kernels.\r\n         PJN / 12-02-2003 1. Fixed a compiler warning in GetNTServicePackFromRegistry which occurs when the code is compiled\r\n                          with the Watcom compiler. Thanks to Christian Kaiser for reporting this.\r\n         PJN / 08-03-2003 1. Updated a comment in COSVersion::GetProductSuiteDetailsFromRegistry re NT Embedded.\r\n                          2. A comment from John A. Vorchak: On NTe (NT Embedded) and XPE (XP Embedded), all of the versions \r\n                          (of DTWinver) work just fine so long as the components to support them are included in the images, \r\n                          which itself is kind of a crap shoot.  I think that you would probably find that most images will \r\n                          not support the DOS or Win16 versions however most will support the Win32.  Many of the images that \r\n                          folks build either do not include the DOS subsystem and some of them do not include Explorer, so it \r\n                          really can't be said that all builds will support them however it is not difficult for a developer \r\n                          to understand which version would work for them as they understand their target systems better than \r\n                          anyone and at least one version would certainly work for almost all images. \r\n                          As far as Win2k (Server Appliance Kit), I haven't done enough testing with that platform, nor do I \r\n                          currently have any built images with the SAK to say positively or otherwise. More than likely you \r\n                          would find no problems with the SAK images since they typically follow W2k much more than NTe or \r\n                          XPE do.\r\n                          Author: If you are writing for an embedded OS, then there is little use for DTWinver!!, since the\r\n                          developer has very tight control over the runtime environment. Also if you do use DTWinver on an \r\n                          embedded version of Windows, you will probably compile in the dtwinver code rather than ship the \r\n                          sample binaries I include in the dtwinver download.\r\n\r\n\r\nCopyright (c) 1997 - 2003 by PJ Naughter.  (Web: www.naughter.com, Email: pjna@naughter.com)\r\n\r\nAll rights reserved.\r\n\r\nCopyright / Usage Details:\r\n\r\nYou are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) \r\nwhen your product is released in binary form. You are allowed to modify the source code in any way you want \r\nexcept you cannot modify the copyright details at the top of each module. If you want to distribute source \r\ncode with your application, then you are only allowed to distribute versions released by the author. This is \r\nto maintain a single distribution point for the source code. \r\n*/\r\n\r\n\r\n/////////////////////////////////  Includes  //////////////////////////////////\r\n#include <windows.h> \r\n#if defined(_WIN32) || defined(_WIN64)\r\n#include <tchar.h>\r\n#else\r\n#include <ctype.h>\r\n#include <stdlib.h>\r\n#include <shellapi.h>\r\n#endif\r\n#include <string.h>\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include \"OSVer.h\"\r\n\r\n\r\n/////////////////////////////////  Local function / variables /////////////////\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_WORKSTATION\r\n#define VER_NT_WORKSTATION              0x0000001\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_DOMAIN_CONTROLLER\r\n#define VER_NT_DOMAIN_CONTROLLER        0x0000002\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_NT_SERVER\r\n#define VER_NT_SERVER                   0x0000003\r\n#endif\r\n\r\n\r\n//OS_VERSION_INFO::wSuiteMask can any of the following bit masks\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_SMALLBUSINESS\r\n#define VER_SUITE_SMALLBUSINESS             0x00000001\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_ENTERPRISE\r\n#define VER_SUITE_ENTERPRISE                0x00000002\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_TERMINAL\r\n#define VER_SUITE_TERMINAL                  0x00000010\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_DATACENTER\r\n#define VER_SUITE_DATACENTER                0x00000080\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_PERSONAL\r\n#define VER_SUITE_PERSONAL                  0x00000200\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_BLADE\r\n#define VER_SUITE_BLADE                     0x00000400\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_EMBEDDEDNT\r\n#define VER_SUITE_EMBEDDEDNT                0x00000040\r\n#endif\r\n\r\n//Taken from Platform SDK's WinNT.h file\r\n#ifndef VER_SUITE_SINGLEUSERTS\r\n#define VER_SUITE_SINGLEUSERTS              0x00000100\r\n#endif\r\n\r\n\r\n#if defined(_WIN32)\r\n\r\n//Taken from Windows CE winbase.h file\r\n#ifndef VER_PLATFORM_WIN32_CE\r\n  #define VER_PLATFORM_WIN32_CE         3\r\n#endif\r\n\r\n#endif //defined(_WIN32) \r\n\r\n#ifdef _DOS\r\n  WORD WinVer;\r\n  BYTE bRunningWindows;\r\n#endif //ifdef _DOS\r\n\r\n\r\n////////////////////////////////// Implementation /////////////////////////////\r\nCOSVersion::COSVersion()\r\n{\r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)\r\n  //Initialize the values to sane defaults\r\n  m_lpfnLoadLibraryEx32W = NULL;\r\n  m_lpfnFreeLibrary32W = NULL;\r\n  m_lpfnGetProcAddress32W = NULL;\r\n  m_lpfnCallProcEx32W = NULL;\r\n  m_hAdvApi32 = 0;    \r\n  m_hKernel32 = 0;\r\n  m_lpfnRegQueryValueExA= 0;\r\n  m_lpfnGetVersionExA = 0;\r\n  m_lpfnGetVersion = 0;\r\n\r\n  //Get Kernel dll handle\r\n  HMODULE hKernel = GetModuleHandle(\"KERNEL\");\r\n  if (hKernel)\r\n  {\r\n    //Dynamically link to the functions we want\r\n    m_lpfnLoadLibraryEx32W  = (lpfnLoadLibraryEx32W)  GetProcAddress(hKernel, \"LoadLibraryEx32W\");\r\n    m_lpfnFreeLibrary32W    = (lpfnFreeLibrary32W)    GetProcAddress(hKernel, \"FreeLibrary32W\");\r\n    m_lpfnGetProcAddress32W = (lpfnGetProcAddress32W) GetProcAddress(hKernel, \"GetProcAddress32W\");\r\n    m_lpfnCallProcEx32W     = (lpfnCallProcEx32W)     GetProcAddress(hKernel, \"_CallProcEx32W\");\r\n    if (m_lpfnLoadLibraryEx32W && m_lpfnFreeLibrary32W)\r\n    {\r\n      m_hAdvApi32 = m_lpfnLoadLibraryEx32W(\"ADVAPI32.DLL\", NULL, 0);\r\n      if (m_hAdvApi32)                                                   \r\n        m_lpfnRegQueryValueExA = m_lpfnGetProcAddress32W(m_hAdvApi32, \"RegQueryValueExA\"); \r\n      m_hKernel32 = m_lpfnLoadLibraryEx32W(\"KERNEL32.DLL\", NULL, 0);\r\n      if (m_hKernel32)\r\n      {                                                               \r\n        m_lpfnGetVersionExA = m_lpfnGetProcAddress32W(m_hKernel32, \"GetVersionExA\");\r\n        m_lpfnGetVersion = m_lpfnGetProcAddress32W(m_hKernel32, \"GetVersion\");\r\n      }\r\n    }\r\n  }\r\n#endif\r\n}\r\n\r\nCOSVersion::~COSVersion()\r\n{\r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)\r\n  if (m_lpfnFreeLibrary32W)\r\n  {           \r\n    if (m_hAdvApi32)\r\n      m_lpfnFreeLibrary32W(m_hAdvApi32);\r\n    if (m_hKernel32)\r\n      m_lpfnFreeLibrary32W(m_hKernel32);\r\n  }\r\n#endif\r\n}\r\n\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))\r\nBOOL COSVersion::WFWLoaded()\r\n{\r\n  const WORD WNNC_NET_MultiNet         = 0x8000;\r\n  const WORD WNNC_SUBNET_WinWorkgroups = 0x0004;\r\n  const WORD WNNC_NET_TYPE             = 0x0002;\r\n  BOOL rVal;\r\n   \r\n  HINSTANCE hUserInst = LoadLibrary(\"USER.EXE\");\r\n  lpfnWNetGetCaps lpWNetGetCaps = (lpfnWNetGetCaps) GetProcAddress(hUserInst, \"WNetGetCaps\");\r\n  if (lpWNetGetCaps != NULL)\r\n  {\r\n    // Get the network type\r\n    WORD wNetType = lpWNetGetCaps(WNNC_NET_TYPE);\r\n    if (wNetType & WNNC_NET_MultiNet)\r\n    {\r\n      // a multinet driver is installed\r\n      if (LOBYTE(wNetType) & WNNC_SUBNET_WinWorkgroups) // It is WFW\r\n        rVal = TRUE;\r\n      else // It is not WFW\r\n        rVal = FALSE;\r\n    }\r\n    else\r\n     rVal = FALSE;\r\n  }\r\n  else\r\n    rVal = FALSE;\r\n   \r\n  //Clean up the module instance\r\n  if (hUserInst)\r\n    FreeLibrary(hUserInst);\r\n    \r\n  return rVal;  \r\n}\r\n\r\nLONG COSVersion::RegQueryValueEx(HKEY32 hKey, LPSTR  lpszValueName, LPDWORD lpdwReserved, LPDWORD lpdwType, LPBYTE  lpbData, LPDWORD lpcbData)\r\n{                                             \r\n  //Assume the worst\r\n  DWORD dwResult = ERROR_CALL_NOT_IMPLEMENTED;\r\n\r\n  if (m_lpfnRegQueryValueExA)\r\n    dwResult = m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 6, 0x3e, m_lpfnRegQueryValueExA, hKey, lpszValueName, lpdwReserved, lpdwType, lpbData, lpcbData);\r\n\r\n  return dwResult;\r\n}                 \r\n\r\nBOOL COSVersion::GetVersionEx(LPOSVERSIONINFO lpVersionInfo)\r\n{\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  if (m_lpfnGetVersionExA)\r\n    bSuccess = (BOOL) m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 1, 1, m_lpfnGetVersionExA, lpVersionInfo, 0);\r\n\r\n  return bSuccess;\r\n}\r\n\r\nDWORD COSVersion::GetVersion()\r\n{\r\n  //Assume the worst\r\n  DWORD dwVersion = 0;\r\n\r\n  if (m_lpfnGetVersion)\r\n    dwVersion = (BOOL) m_lpfnCallProcEx32W(CPEX_DEST_STDCALL | 0, 0, m_lpfnGetVersion, 0);\r\n\r\n  return dwVersion;\r\n}\r\n#endif //defined(_WINDOWS) && !defined(_WIN32)\r\n\r\nBOOL COSVersion::GetVersion(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Zero out everything in the structure\r\n  memset(lpVersionInformation, 0, sizeof(lpVersionInformation));\r\n                \r\n  #ifdef UNDER_CE\r\n    OSVERSIONINFO osvi;\r\n    memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n    if (!GetVersionEx(&osvi))\r\n      return FALSE;\r\n\r\n    //Basic OS info\r\n    lpVersionInformation->dwUnderlyingMajorVersion = osvi.dwMajorVersion; \r\n    lpVersionInformation->dwUnderlyingMinorVersion = osvi.dwMinorVersion; \r\n    lpVersionInformation->dwUnderlyingBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n    lpVersionInformation->UnderlyingPlatform = WindowsCE;\r\n    _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, osvi.szCSDVersion);\r\n\r\n    //OEM Info\r\n    _tcscpy(lpVersionInformation->szOEMInfo, _T(\"\"));\r\n    SystemParametersInfo(SPI_GETOEMINFO, 256, lpVersionInformation->szOEMInfo, 0);\r\n\r\n    //Platform Type\r\n    _tcscpy(lpVersionInformation->szPlatformType, _T(\"\"));\r\n    SystemParametersInfo(SPI_GETPLATFORMTYPE, 256, lpVersionInformation->szPlatformType, 0);\r\n\r\n    //Always set the OSType to Workstation on CE. The variable itself does not make \r\n    //much sense on CE, but we do not conditionally compile it out on CE as then we\r\n    //would have to put in loadsa ifdefs UNDER_CE in the COSVersion::Is... methods\r\n    lpVersionInformation->OSType = Workstation;\r\n\r\n  #elif defined(_WIN32) || defined(_WIN64)\r\n    //determine dynamically if GetVersionEx is available, if \r\n    //not then drop back to using GetVersion\r\n\r\n    // Get Kernel handle\r\n    HMODULE hKernel32 = GetModuleHandle(_T(\"KERNEL32.DLL\"));\r\n    if (hKernel32 == NULL)\r\n      return FALSE;\r\n\r\n    #ifdef _UNICODE\r\n      lpfnGetVersionEx lpGetVersionEx = (lpfnGetVersionEx) GetProcAddress(hKernel32, \"GetVersionExW\");\r\n    #else\r\n      lpfnGetVersionEx lpGetVersionEx = (lpfnGetVersionEx) GetProcAddress(hKernel32, \"GetVersionExA\");\r\n    #endif\r\n\r\n    if (lpGetVersionEx)\r\n    {\r\n      OSVERSIONINFOEX osviex;\r\n      memset(&osviex, 0, sizeof(OSVERSIONINFOEX));\r\n      osviex.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);\r\n\r\n      OSVERSIONINFO osvi;\r\n      memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n\r\n      BOOL bGotOSviEx = lpGetVersionEx((LPOSVERSIONINFO) &osviex);\r\n      if (!bGotOSviEx)\r\n      {\r\n        if (!lpGetVersionEx(&osvi))\r\n          return FALSE;\r\n      }\r\n\r\n      if (bGotOSviEx)\r\n      {\r\n        lpVersionInformation->dwEmulatedMajorVersion = osviex.dwMajorVersion;\r\n        lpVersionInformation->dwEmulatedMinorVersion = osviex.dwMinorVersion;\r\n        lpVersionInformation->dwEmulatedBuildNumber = LOWORD(osviex.dwBuildNumber);\r\n        _tcscpy(lpVersionInformation->szEmulatedCSDVersion, osviex.szCSDVersion);\r\n        lpVersionInformation->wEmulatedServicePackMajor = osviex.wServicePackMajor;\r\n        lpVersionInformation->wEmulatedServicePackMinor = osviex.wServicePackMinor;\r\n        \r\n        //Explicitly map the Win32 wSuiteMask to our own values\r\n        if (osviex.wSuiteMask & VER_SUITE_SMALLBUSINESS)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_SMALLBUSINESS;\r\n        if (osviex.wSuiteMask & VER_SUITE_ENTERPRISE)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_ENTERPRISE;\r\n        if (osviex.wSuiteMask & VER_SUITE_TERMINAL)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_TERMINAL;\r\n        if (osviex.wSuiteMask & VER_SUITE_DATACENTER)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_DATACENTER;\r\n        if (osviex.wSuiteMask & VER_SUITE_PERSONAL)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PERSONAL;\r\n        if (osviex.wSuiteMask & VER_SUITE_BLADE)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_WEBEDITION;\r\n        if (osviex.wSuiteMask & VER_SUITE_EMBEDDEDNT)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_EMBEDDEDNT;\r\n        if (osviex.wSuiteMask & VER_SUITE_SINGLEUSERTS)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_REMOTEADMINMODE_TERMINAL;\r\n\r\n        //Explicitely map the Win32 wProductType to our own values\r\n        switch (osviex.wProductType)\r\n        {\r\n          case VER_NT_WORKSTATION:\r\n          {\r\n            lpVersionInformation->OSType = Workstation;\r\n            break;\r\n          }\r\n          case VER_NT_DOMAIN_CONTROLLER:\r\n          {\r\n            lpVersionInformation->OSType = DomainController;\r\n            break;\r\n          }\r\n          case VER_NT_SERVER:\r\n          {\r\n            lpVersionInformation->OSType = Server;\r\n            break;\r\n          }\r\n          default:\r\n          {\r\n            break;\r\n          }\r\n        }\r\n\r\n        //Determine the Domain Controller Type\r\n        GetNTOSTypeFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Explicitly map the win32 dwPlatformId to our own values \r\n        switch (osviex.dwPlatformId)\r\n        {\r\n          case VER_PLATFORM_WIN32_WINDOWS:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = Windows9x;\r\n            break;\r\n          }\r\n          case VER_PLATFORM_WIN32_NT:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = WindowsNT;\r\n            break;\r\n          }\r\n          case VER_PLATFORM_WIN32_CE:\r\n          {\r\n            lpVersionInformation->EmulatedPlatform = WindowsCE;\r\n            break;\r\n          }\r\n          default:\r\n          {\r\n            break;\r\n          }\r\n        }\r\n\r\n        lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion; \r\n        lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion; \r\n        lpVersionInformation->dwUnderlyingBuildNumber = lpVersionInformation->dwEmulatedBuildNumber;\r\n        lpVersionInformation->UnderlyingPlatform = lpVersionInformation->EmulatedPlatform;\r\n        _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n        lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n        lpVersionInformation->wUnderlyingServicePackMinor = lpVersionInformation->wEmulatedServicePackMinor;\r\n\r\n      #ifndef UNDER_CE\r\n        //Determine if it is NT SP6a Vs SP6\r\n        GetNTSP6aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Determine if it is XP SP1a Vs SP1\r\n        GetXPSP1aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n        //Determine the HAL details\r\n        GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n\t    #endif\r\n      }\r\n      else\r\n      {\r\n        lpVersionInformation->dwEmulatedMajorVersion = osvi.dwMajorVersion; \r\n        lpVersionInformation->dwEmulatedMinorVersion = osvi.dwMinorVersion; \r\n        lpVersionInformation->dwEmulatedBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n        _tcscpy(lpVersionInformation->szEmulatedCSDVersion, osvi.szCSDVersion);\r\n    \r\n        //Explicitely map the win32 dwPlatformId to our own values \r\n        //Also work out the various service packs which are installed\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = Windows9x;\r\n          lpVersionInformation->OSType = Workstation;\r\n\r\n          //Deterine the Win9x Service pack installed\r\n          if (IsWindows95SP1(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 1;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          }\r\n          else if (IsWindows95OSR2(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 2;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 2;\r\n          }\r\n          else if (IsWindows98SP1(lpVersionInformation))\r\n          {\r\n            lpVersionInformation->wEmulatedServicePackMajor = 1;\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          }\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = WindowsNT;\r\n\r\n          //Determine the NT Service pack\r\n          lpVersionInformation->wEmulatedServicePackMajor = GetNTServicePackFromCSDString(osvi.szCSDVersion);\r\n          lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n\r\n          //Determine the OS Type\r\n          GetNTOSTypeFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Get the Product Suites installed\r\n          GetProductSuiteDetailsFromRegistry(lpVersionInformation);\r\n          GetTerminalServicesRemoteAdminModeDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_CE)\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = WindowsCE;\r\n\r\n          //Always set the OSType to Workstation on CE. The variable itself does not make \r\n          //much sense on CE, but we do not conditionally compile it out on CE as then we\r\n          //would have to put in loadsa ifdefs UNDER_CE in the COSVersion::Is... methods\r\n          lpVersionInformation->OSType = Workstation;\r\n        }\r\n\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32s)  //32 bit app running on Windows 3.x\r\n        {\r\n          lpVersionInformation->EmulatedPlatform = Windows9x;\r\n\r\n          lpVersionInformation->dwUnderlyingMajorVersion = 3; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = 10; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = 0;\r\n          lpVersionInformation->UnderlyingPlatform = Windows3x;\r\n          _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, _T(\"\"));\r\n        }\r\n        else\r\n        {\r\n          lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = lpVersionInformation->dwEmulatedBuildNumber;\r\n          lpVersionInformation->UnderlyingPlatform = lpVersionInformation->EmulatedPlatform;\r\n          _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n        }\r\n\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          //Determine if it is NT SP6a Vs SP6\r\n          GetNTSP6aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n          //Determine if it is XP SP1a Vs SP1\r\n          GetXPSP1aDetailsFromRegistry(lpVersionInformation, TRUE);\r\n\r\n          //Determine the HAL details\r\n          GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n      }\r\n    }\r\n    else\r\n    {\r\n      //Since GetVersionEx is not available we need to fall back on plain\r\n      //old GetVersion. Because GetVersionEx is available on all but v3.1 of NT\r\n      //we can fill in some of the parameters ourselves.\r\n      DWORD dwVersion = ::GetVersion();\r\n\r\n      lpVersionInformation->dwEmulatedMajorVersion =  (DWORD)(LOBYTE(LOWORD(dwVersion)));\r\n      lpVersionInformation->dwEmulatedMinorVersion =  (DWORD)(HIBYTE(LOWORD(dwVersion)));\r\n      lpVersionInformation->dwEmulatedBuildNumber = 0;\r\n      lpVersionInformation->EmulatedPlatform   = WindowsNT;   \r\n      lpVersionInformation->dwUnderlyingMajorVersion = lpVersionInformation->dwEmulatedMajorVersion;\r\n      lpVersionInformation->dwUnderlyingMinorVersion = lpVersionInformation->dwEmulatedMinorVersion;\r\n      lpVersionInformation->dwUnderlyingBuildNumber  = lpVersionInformation->dwEmulatedBuildNumber;\r\n      lpVersionInformation->UnderlyingPlatform   = lpVersionInformation->EmulatedPlatform;   \r\n      _tcscpy(lpVersionInformation->szUnderlyingCSDVersion, lpVersionInformation->szEmulatedCSDVersion);\r\n\r\n      //Need to determine the NT Service pack by querying the registry directory.\r\n      lpVersionInformation->wEmulatedServicePackMajor = GetNTServicePackFromRegistry();\r\n      lpVersionInformation->wUnderlyingServicePackMajor = lpVersionInformation->wEmulatedServicePackMajor;\r\n    }\r\n  #else //We must be runing on an emulated or real version of Win16 or DOS\r\n    #ifdef _WINDOWS //Running on some version of Windows                   \r\n      DWORD dwVersion = GetVersion();\r\n      // GetVersion does not differentiate between Windows 3.1 and Windows 3.11\r\n      \r\n      lpVersionInformation->dwEmulatedMajorVersion = LOBYTE(LOWORD(dwVersion)); \r\n      lpVersionInformation->dwEmulatedMinorVersion = HIBYTE(LOWORD(dwVersion));\r\n      lpVersionInformation->dwEmulatedBuildNumber  = 0; //no build number with Win3.1x\r\n      lpVersionInformation->EmulatedPlatform   = Windows3x;\r\n      \r\n      //Call to get the underlying OS here through 16 -> 32 bit Generic Thunk\r\n      BOOL bFoundUnderlyingOS = FALSE;\r\n      OSVERSIONINFO osvi;                      \r\n      memset(&osvi, 0, sizeof(OSVERSIONINFO));\r\n      osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\r\n      if (GetVersionEx(&osvi))\r\n      {\r\n        lpVersionInformation->dwUnderlyingMajorVersion = osvi.dwMajorVersion; \r\n        lpVersionInformation->dwUnderlyingMinorVersion = osvi.dwMinorVersion; \r\n        lpVersionInformation->dwUnderlyingBuildNumber = LOWORD(osvi.dwBuildNumber); //ignore HIWORD\r\n        _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, osvi.szCSDVersion);\r\n       \r\n        //Explicitely map the win32 dwPlatformId to our own values\r\n        if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\r\n        {\r\n          lpVersionInformation->UnderlyingPlatform = Windows9x;\r\n\r\n          //Deterine the Win9x Service pack installed\r\n          if (IsWindows95SP1(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n          else if (IsWindows95OSR2(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 2;\r\n          else if (IsWindows98SP1(lpVersionInformation))\r\n            lpVersionInformation->wUnderlyingServicePackMajor = 1;\r\n        }\r\n        else if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)\r\n        {\r\n          lpVersionInformation->UnderlyingPlatform = WindowsNT;\r\n\r\n          //Determine the NT Service pack\r\n          lpVersionInformation->wEmulatedServicePackMajor = 0; //Win16 does not have a concept of a service pack\r\n          lpVersionInformation->wUnderlyingServicePackMajor = GetNTServicePackFromCSDString(osvi.szCSDVersion);\r\n\r\n          //Determine the OS Type\r\n          GetNTOSTypeFromRegistry(lpVersionInformation, FALSE);\r\n\r\n\t\t#ifndef UNDER_CE\r\n          //Determine if it is NT SP6a Vs SP6\r\n          GetNTSP6aDetailsFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Determine if it is XP SP1a Vs SP1\r\n          GetXPSP1aDetailsFromRegistry(lpVersionInformation, FALSE);\r\n\r\n          //Determine the HAL details\r\n          GetNTHALDetailsFromRegistry(lpVersionInformation);\r\n\t\t#endif\r\n\r\n          //Get the Product Suites installed\r\n          GetProductSuiteDetailsFromRegistry(lpVersionInformation);\r\n          GetTerminalServicesRemoteAdminModeDetailsFromRegistry(lpVersionInformation);\r\n        }\r\n        else\r\n          return FALSE;\r\n       \r\n        bFoundUnderlyingOS = TRUE;\r\n      }\r\n      else\r\n      {\r\n        //We failed to get GetVersionEx so try to GetVersion instead. We known that we must be on\r\n        //Windows NT 3.5 or earlier since anything released later by MS had this function.\r\n        DWORD dwVersion = GetVersion();\r\n        if (dwVersion)\r\n        {              \r\n          lpVersionInformation->dwUnderlyingMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));\r\n          lpVersionInformation->dwUnderlyingMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion)));\r\n          lpVersionInformation->dwUnderlyingBuildNumber  = 0;\r\n          lpVersionInformation->UnderlyingPlatform   = WindowsNT; \r\n          _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n   \r\n          bFoundUnderlyingOS = TRUE;\r\n        }\r\n      }\r\n\r\n      if (!bFoundUnderlyingOS)\r\n      {\r\n        //must be running on a real version of 16 bit Windows whose underlying OS is DOS\r\n        lpVersionInformation->dwUnderlyingMajorVersion = HIBYTE(HIWORD(dwVersion)); \r\n        lpVersionInformation->dwUnderlyingMinorVersion = LOBYTE(HIWORD(dwVersion)); \r\n        lpVersionInformation->dwUnderlyingBuildNumber = 0; \r\n        lpVersionInformation->UnderlyingPlatform = Dos;\r\n        _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n      }\r\n    #else //Must be some version of real or emulated DOS\r\n      //Retreive the current version of emulated DOS\r\n      BYTE DosMinor;\r\n      BYTE DosMajor;\r\n      _asm\r\n      {\r\n        mov ax, 3306h\r\n        int 21h\r\n        mov byte ptr [DosMajor], bl\r\n        mov byte ptr [DosMinor], bh\r\n      }\r\n      lpVersionInformation->EmulatedPlatform = Dos;\r\n      lpVersionInformation->dwEmulatedMajorVersion = (DWORD) DosMajor; \r\n      lpVersionInformation->dwEmulatedMinorVersion = (DWORD) DosMinor;                \r\n      lpVersionInformation->dwEmulatedBuildNumber = 0; //no build number with DOS\r\n      \r\n      //See can we get the underlying OS info by calling WriteVer\r\n      if (!GetInfoBySpawingWriteVer(lpVersionInformation))\r\n      {\r\n        //We can detect if NT is running as it reports DOS v5.5\r\n        if ((lpVersionInformation->dwEmulatedMajorVersion == 5) &&\r\n            (lpVersionInformation->dwEmulatedMinorVersion == 50))    //NT reports DOS v5.5\r\n        {\r\n          _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");    \r\n          //could not find method of determing version of NT from DOS,\r\n          //so assume 3.50\r\n          lpVersionInformation->dwUnderlyingMajorVersion = 3; \r\n          lpVersionInformation->dwUnderlyingMinorVersion = 50; \r\n          lpVersionInformation->dwUnderlyingBuildNumber = 0;  //cannot get access to build number from DOS\r\n          lpVersionInformation->UnderlyingPlatform = WindowsNT;\r\n        }            \r\n        else\r\n        {\r\n          //Get the underlying OS here via the int 2FH interface of Windows\r\n          GetWinInfo();\r\n          if (bRunningWindows)\r\n          { \r\n            if (lpVersionInformation->dwEmulatedMajorVersion >= 7)  //Windows 9x marks itself as DOS 7 or DOS 8\r\n              lpVersionInformation->UnderlyingPlatform = Windows9x;\r\n            else                                                              \r\n            {\r\n              //Could not find method of differentiating between WFW & Win3.1 under DOS,\r\n              //so assume Win3.1                                     \r\n              lpVersionInformation->UnderlyingPlatform = Windows3x;      \r\n            }  \r\n            _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n            lpVersionInformation->dwUnderlyingMajorVersion = (WinVer & 0xFF00) >> 8; \r\n            lpVersionInformation->dwUnderlyingMinorVersion = WinVer & 0x00FF; \r\n  \r\n            if (lpVersionInformation->dwEmulatedMajorVersion >= 8)  //Windows Me reports itself as DOS v8.0\r\n              lpVersionInformation->dwUnderlyingBuildNumber = 3000; //This is the build number for Windows ME.\r\n            else\r\n            {\r\n              if (lpVersionInformation->dwEmulatedMinorVersion == 0)\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 950; //Windows 95 Gold reports DOS v7.0                      \r\n              else if (lpVersionInformation->dwUnderlyingMinorVersion > 0 && \r\n                       lpVersionInformation->dwUnderlyingMinorVersion < 3) \r\n              {                                                            \r\n                //Testing for 95 SP1 has not been done, so the above check\r\n                //may or may not work\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1080; \r\n              }\r\n              else if (lpVersionInformation->dwUnderlyingMinorVersion == 3)\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1212; //Windows 95 OSR2 reports DOS 7.03 from 16 bit code\r\n              else\r\n                lpVersionInformation->dwUnderlyingBuildNumber = 1998; //Windows 98 or SE. There is no way to differentiate from real mode\r\n                                                                      //between the two of them\r\n            }\r\n          }\r\n          else //must be on a real version of DOS\r\n          {                               \r\n            lpVersionInformation->dwUnderlyingMajorVersion = (DWORD) DosMajor; \r\n            lpVersionInformation->dwUnderlyingMinorVersion = (DWORD) DosMinor;                \r\n            lpVersionInformation->dwUnderlyingBuildNumber = 0; //no build number with DOS\r\n            lpVersionInformation->UnderlyingPlatform = Dos;\r\n            _fstrcpy(lpVersionInformation->szUnderlyingCSDVersion, \"\");\r\n          }\r\n        }   \r\n      }\r\n    #endif  \r\n  #endif\r\n\r\n  return TRUE;\r\n}\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetNTSP6aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso)\r\n{\r\n#ifndef UNDER_CE\r\n  if ((lpVersionInformation->dwUnderlyingMajorVersion == 4) && (lpVersionInformation->wUnderlyingServicePackMajor == 6))\r\n  {\r\n    //Test for SP6 versus SP6a.\r\n    HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Hotfix\\\\Q246009\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n\tif (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\Hotfix\\\\Q246009\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n    {\r\n      lpVersionInformation->wUnderlyingServicePackMinor = 1;         \r\n      if (bUpdateEmulatedAlso)\r\n        lpVersionInformation->wEmulatedServicePackMinor = 1;\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n#endif\r\n}\r\n#endif\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetXPSP1aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso)\r\n{\r\n#ifndef UNDER_CE\r\n  if ((lpVersionInformation->dwUnderlyingMajorVersion == 5) && (lpVersionInformation->dwUnderlyingMinorVersion != 0) && (lpVersionInformation->wUnderlyingServicePackMajor == 1))\r\n  {\r\n    //Test for SP1a versus SP1.\r\n    HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n\tif (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n    {\r\n      TCHAR sTemp[1024];\r\n      DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n  #if (defined(_WIN32) || defined(_WIN64))\r\n      if (::RegQueryValueEx(hKey, _T(\"SubVersionNumber\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n  #else\r\n      if (RegQueryValueEx(hKey, _T(\"SubVersionNumber\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n  #endif\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"a\")) == 0)\r\n        {\r\n          lpVersionInformation->wUnderlyingServicePackMinor = 1;         \r\n          if (bUpdateEmulatedAlso)\r\n            lpVersionInformation->wEmulatedServicePackMinor = 1;\r\n        }\r\n      }\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n#endif\r\n}\r\n#endif\r\n\r\n#ifndef _DOS\r\nvoid COSVersion::GetNTHALDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n#ifndef UNDER_CE\r\n  HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n  if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS)\r\n#else                                  \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hKey) == ERROR_SUCCESS)\r\n#endif    \r\n  {\r\n    TCHAR sTemp[1024];\r\n    DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (::RegQueryValueEx(hKey, _T(\"CurrentType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#else\r\n    if (RegQueryValueEx(hKey, _T(\"CurrentType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#endif\r\n    {\r\n      if (_tcsicmp(sTemp, _T(\"Uniprocessor Free\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_UNIPROCESSOR_FREE;         \r\n      else if (_tcsicmp(sTemp, _T(\"Uniprocessor Checked\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_UNIPROCESSOR_CHECKED;         \r\n      else if (_tcsicmp(sTemp, _T(\"Multiprocessor Free\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_MULTIPROCESSOR_FREE;         \r\n      else if (_tcsicmp(sTemp, _T(\"Multiprocessor Checked\")) == 0)\r\n        lpVersionInformation->dwSuiteMask |= OSSUITE_MULTIPROCESSOR_CHECKED;         \r\n    }\r\n  }\r\n\r\n  RegCloseKey(hKey);\r\n#endif\r\n}\r\n#endif\r\n      \r\n#ifndef _DOS\r\nvoid COSVersion::GetNTOSTypeFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bOnlyUpdateDCDetails)\r\n{\r\n  //assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  //Open and the product options key\r\n  HKEY hKey;\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n  if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), 0, KEY_READ, &hKey) == ERROR_SUCCESS)\r\n#else                                                                                                                               \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), &hKey) == ERROR_SUCCESS)\r\n#endif\r\n  {\r\n    TCHAR sTemp[1024];\r\n    DWORD dwBufLen = 1024 * sizeof(TCHAR);\r\n\r\n#if (defined(_WIN32) || defined(_WIN64))\r\n    if (::RegQueryValueEx(hKey, _T(\"ProductType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#else\r\n    if (RegQueryValueEx(hKey, _T(\"ProductType\"), NULL, NULL, (LPBYTE) sTemp, &dwBufLen) == ERROR_SUCCESS)\r\n#endif\r\n    {\r\n      if (bOnlyUpdateDCDetails)\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"LANMANNT\")) == 0)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PRIMARY_DOMAIN_CONTROLLER;\r\n        else if (_tcsicmp(sTemp, _T(\"LANSECNT\")) == 0)\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_BACKUP_DOMAIN_CONTROLLER;\r\n      }\r\n      else\r\n      {\r\n        if (_tcsicmp(sTemp, _T(\"LANMANNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = DomainController;\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_PRIMARY_DOMAIN_CONTROLLER;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"SERVERNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = Server;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"LANSECNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = DomainController;\r\n          lpVersionInformation->dwSuiteMask |= OSSUITE_BACKUP_DOMAIN_CONTROLLER;\r\n        }\r\n        else if (_tcsicmp(sTemp, _T(\"WinNT\")) == 0)\r\n        {\r\n          lpVersionInformation->OSType = Workstation;\r\n        }\r\n      }\r\n    }\r\n\r\n    RegCloseKey(hKey);\r\n  }\r\n}\r\n#endif //#ifndef _DOS\r\n                                   \r\n#ifdef _DOS             \r\nBOOL COSVersion::GetInfoBySpawingWriteVer(COSVersion::LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;\r\n\r\n  //Form the command line we need  \r\n  char pszCommandLine[256];      \r\n  char* pszTempFilename = tmpnam(NULL);\r\n  sprintf(pszCommandLine, \"WriteVer.exe %s\", pszTempFilename);\r\n\r\n  //Try to spawn out writever utilty\r\n  if (system(pszCommandLine) != -1)\r\n  {           \r\n    //Open the file we need                 \r\n    FILE* pOSFile = fopen(pszTempFilename, \"r\");\r\n    if (pOSFile == NULL)\r\n      return bSuccess;\r\n        \r\n    //Read in the OS version info from file\r\n    char pszLine[1024];\r\n    size_t nRead = fread(pszLine, 1, 1024, pOSFile);\r\n    if (nRead)\r\n    {\r\n      pszLine[nRead] = '\\0'; //Don't forget to NULL terminate\r\n\r\n      //Parse the input string                               \r\n      char* pszSeparators = \"\\t\";                               \r\n      char* pszToken = strtok(pszLine, pszSeparators);\r\n      if (pszToken)\r\n      {\r\n        lpVersionInformation->dwUnderlyingMajorVersion = atoi(pszToken);      \r\n        pszToken = strtok(NULL, pszSeparators);         \r\n        if (pszToken)\r\n        {\r\n          lpVersionInformation->dwUnderlyingMinorVersion = atoi(pszToken);      \r\n          pszToken = strtok(NULL, pszSeparators);         \r\n          if (pszToken)\r\n          {\r\n            lpVersionInformation->dwUnderlyingBuildNumber = atoi(pszToken);       \r\n            pszToken = strtok(NULL, pszSeparators);         \r\n            if (pszToken)\r\n            {\r\n              lpVersionInformation->UnderlyingPlatform = (COSVersion::OS_PLATFORM) atoi(pszToken);       \r\n              pszToken = strtok(NULL, pszSeparators);         \r\n              if (pszToken)                                       \r\n              {                                                   \r\n                lpVersionInformation->wUnderlyingServicePackMajor = (WORD) atoi(pszToken);       \r\n                pszToken = strtok(NULL, pszSeparators);             \r\n                if (pszToken)\r\n                {\r\n                  lpVersionInformation->wUnderlyingServicePackMinor = (WORD) atoi(pszToken);       \r\n                  pszToken = strtok(NULL, pszSeparators);             \r\n                  if (pszToken)\r\n                  {\r\n                    lpVersionInformation->dwSuiteMask = (DWORD) atoi(pszToken);       \r\n                    pszToken = strtok(NULL, pszSeparators);\r\n                    if (pszToken)\r\n                    {\r\n                      lpVersionInformation->OSType = (COSVersion::OS_TYPE) atoi(pszToken);       \r\n\r\n                      //CSDVersion string is optional so consider it successful if we got as far as here\r\n                      bSuccess = TRUE;\r\n\r\n                      pszToken = strtok(NULL, pszSeparators);\r\n                      if (pszToken)\r\n                        strcpy(lpVersionInformation->szUnderlyingCSDVersion, pszToken);                                    \r\n                    }\r\n                  }\r\n                }\r\n              }\r\n            }\r\n          }\r\n        }\r\n      }\r\n    }\r\n   \r\n    //Don't forget to close the file\r\n    fclose(pOSFile);\r\n\r\n    //and remove it now that we are finished with it\r\n    remove(pszTempFilename);\r\n  }\r\n  else\r\n  {\r\n    printf(\"writever command failed, Errno:%d\\n\", errno);\r\n  }     \r\n\r\n  return bSuccess;\r\n}\r\n\r\nvoid COSVersion::GetWinInfo()\r\n{ \r\n  BYTE MajorVer;\r\n  BYTE MinorVer;\r\n\r\n  //use some inline assembly to determine if Windows if\r\n  //running and what version is active\r\n  _asm\r\n  {\r\n  ; check for Windows 3.1\r\n    mov     ax,160ah                ; WIN31CHECK\r\n    int     2fh                     ; check if running under Win 3.1.\r\n    or      ax,ax\r\n    jz      RunningUnderWin31       ; can check if running in standard\r\n                                    ; or enhanced mode\r\n   \r\n  ; check for Windows 3.0 enhanced mode\r\n    mov     ax,1600h                ; WIN386CHECK\r\n    int     2fh\r\n    test    al,7fh\r\n    jnz     RunningUnderWin30Enh    ; enhanced mode\r\n   \r\n  ; check for 3.0 WINOLDAP\r\n    mov     ax,4680h                ; IS_WINOLDAP_ACTIVE\r\n    int     2fh\r\n    or      ax,ax                   ; running under 3.0 derivative?\r\n    jnz     NotRunningUnderWin\r\n   \r\n  ; rule out MS-DOS 5.0 task switcher\r\n    mov     ax,4b02h                ; detect switcher\r\n    push    bx\r\n    push    es\r\n    push    di\r\n    xor     bx,bx\r\n    mov     di,bx\r\n    mov     es,bx\r\n    int     2fh\r\n    pop     di\r\n    pop     es\r\n    pop     bx\r\n    or      ax,ax\r\n    jz      NotRunningUnderWin      ; MS-DOS 5.0 task switcher found\r\n   \r\n  ; check for standard mode Windows 3.0\r\n    mov     ax,1605h                ; PMODE_START\r\n    int     2fh\r\n    cmp     cx,-1\r\n    jz      RunningUnderWin30Std\r\n   \r\n  ; check for real mode Windows 3.0\r\n    mov     ax,1606h                ; PMODE_STOP\r\n    int     2fh                     ; in case someone is counting\r\n    ; Real mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1\r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin30Std:\r\n    ; Standard mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1\r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin31:\r\n    ; At this point: CX == 3 means Windows 3.1 enhanced mode\r\n    ;                CX == 2 means Windows 3.1 standard mode\r\n    mov     byte ptr [bRunningWindows], 1\r\n    \r\n    ; Get the version of Windows \r\n    mov     ax, 1600h   ; Get Enhanced-Mode Windows Installed State\r\n    int     2Fh\r\n    mov     byte ptr [MajorVer], al\r\n    mov     byte ptr [MinorVer], ah\r\n    jmp     ExitLabel\r\n   \r\n  RunningUnderWin30Enh:\r\n    ; Enhanced mode Windows 3.0 is running\r\n    mov     byte ptr [bRunningWindows], 1    \r\n    mov     byte ptr [MajorVer], 3h    \r\n    mov     byte ptr [MinorVer], 0h        \r\n    jmp     ExitLabel\r\n   \r\n  NotRunningUnderWin:                    \r\n    mov     byte ptr [bRunningWindows], 0\r\n    \r\n  ExitLabel:\r\n  }             \r\n  \r\n  WinVer = (WORD) ((MajorVer << 8) + MinorVer);\r\n} \r\n#endif //_DOS \r\n\r\nBOOL COSVersion::IsWindowsCE(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsCE);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber == 950);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95SP1(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingBuildNumber > 950 && \r\n          lpVersionInformation->dwUnderlyingBuildNumber <= 1080);\r\n}\r\n\r\nBOOL COSVersion::IsWindows95OSR2(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion < 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber > 1080);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber == 1998);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98SP1(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber > 1998 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber < 2183);\r\n}\r\n\r\nBOOL COSVersion::IsWindows98SE(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10 &&\r\n          lpVersionInformation->dwUnderlyingBuildNumber >= 2183);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsME(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows9x &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 90);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT31(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT35(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 50);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT351(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 3 && \r\n          lpVersionInformation->dwUnderlyingMinorVersion == 51);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsNT4(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 4);\r\n}\r\n\r\nBOOL COSVersion::IsWindows2000(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 5 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsXPOrWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion == 5 &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsXP(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsXPPersonal(lpVersionInformation) || IsXPProfessional(lpVersionInformation);\r\n}\r\n\r\nWORD COSVersion::GetNTServicePackFromCSDString(LPCTSTR pszCSDVersion)\r\n{\r\n  WORD wServicePack = 0;\r\n  if (_tcslen(pszCSDVersion))\r\n  {\r\n    //Parse out the CSDVersion string\r\n    int i=0;      \r\n    while (pszCSDVersion[i] != _T('\\0') && !_istdigit(pszCSDVersion[i]))\r\n      i++;\r\n    wServicePack = (WORD) (_ttoi(&pszCSDVersion[i]));\r\n  }\r\n\r\n  return wServicePack;\r\n}\r\n\r\n#if defined(_WIN32) || defined(_WIN64)\r\nWORD COSVersion::GetNTServicePackFromRegistry()\r\n{\r\n  //By default assume no service pack\r\n  WORD wServicePack = 0;\r\n\r\n  HKEY hCurrentVersion;\r\n  #ifdef _WIN32\r\n  if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), 0, KEY_READ, &hCurrentVersion) == ERROR_SUCCESS)\r\n  #else                                                                                                                                       \r\n  if (RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\"), &hCurrentVersion) == ERROR_SUCCESS)\r\n  #endif\r\n  {\r\n    BYTE byData[128];\r\n    DWORD dwType;\r\n    DWORD dwSize = 128;\r\n    if (RegQueryValueEx(hCurrentVersion, _T(\"CSDVersion\"), NULL, &dwType, byData, &dwSize) == ERROR_SUCCESS)\r\n    {\r\n      if (dwType == REG_SZ)\r\n      {\r\n        //Stored as a string on all other versions of NT\r\n        wServicePack = GetNTServicePackFromCSDString((TCHAR*) byData);\r\n      }\r\n      else if (dwType == REG_DWORD)\r\n      {\r\n        //Handle the service pack number being stored as a DWORD which happens on NT 3.1\r\n        wServicePack = HIBYTE((WORD) *((DWORD*) byData));\r\n      }\r\n    }\r\n\r\n    //Don't forget to close the registry key we were using      \r\n    RegCloseKey(hCurrentVersion);\r\n  }\r\n\r\n  return wServicePack;\r\n}\r\n#endif //#if defined(_WIN32) || defined(_WIN64)\r\n\r\n#if defined(_WIN32) || defined(_WIN64) || defined (_WINDOWS)\r\nvoid COSVersion::GetTerminalServicesRemoteAdminModeDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  //Lookup the TSAppCompat registry value\r\n  HKEY hKey = NULL;        \r\n  #ifdef _WIN32\r\n  LONG lResult = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\Terminal Server\"), 0, KEY_READ, &hKey);\r\n  #else                                                                                                                         \r\n  LONG lResult = RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\Terminal Server\"), &hKey);\r\n  #endif\r\n  if (lResult != ERROR_SUCCESS)\r\n    return;\r\n\r\n  DWORD dwTSAppCompat = 1;\r\n  DWORD dwType;\r\n  DWORD dwSize = sizeof(DWORD);\r\n#if defined(_WIN32) || defined(_WIN64)    \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"TSAppCompat\"), NULL, &dwType, (LPBYTE) &dwTSAppCompat, &dwSize);\r\n#else                                                                                                     \r\n  lResult = RegQueryValueEx(hKey, _T(\"TSAppCompat\"), NULL, &dwType, (LPBYTE) &dwTSAppCompat, &dwSize);\r\n#endif  \r\n  if (lResult == ERROR_SUCCESS)\r\n  {\r\n    if (dwTSAppCompat == 0)\r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_REMOTEADMINMODE_TERMINAL;\r\n  }\r\n\r\n  //Don't forget to free up the resource we used\r\n  RegCloseKey(hKey);\r\n}\r\n\r\nvoid COSVersion::GetProductSuiteDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation) \r\n{\r\n  //Lookup the ProductOptions registry key\r\n  HKEY hKey = NULL;        \r\n  #ifdef _WIN32\r\n  LONG lResult = ::RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), 0, KEY_READ, &hKey);\r\n  #else                                                                                                                         \r\n  LONG lResult = RegOpenKey(HKEY_LOCAL_MACHINE, _T(\"System\\\\CurrentControlSet\\\\Control\\\\ProductOptions\"), &hKey);\r\n  #endif\r\n  if (lResult != ERROR_SUCCESS)\r\n    return;\r\n\r\n  // Determine required size of ProductSuite buffer.\r\n  DWORD dwType = 0;\r\n  DWORD dwSize = 0;                   \r\n#if defined(_WIN32) || defined(_WIN64)  \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, NULL, &dwSize);\r\n#else\r\n  lResult = RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, NULL, &dwSize);\r\n#endif  \r\n  if (lResult != ERROR_SUCCESS || !dwSize)\r\n  {\r\n    RegCloseKey(hKey);\r\n    return;\r\n  }\r\n\r\n  // Allocate buffer.\r\n  LPTSTR lpszProductSuites = (LPTSTR) new BYTE[dwSize];\r\n\r\n  // Retrieve array of product suite strings.\r\n#if defined(_WIN32) || defined(_WIN64)    \r\n  lResult = ::RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, (LPBYTE) lpszProductSuites, &dwSize);\r\n#else                                                                                                     \r\n  lResult = RegQueryValueEx(hKey, _T(\"ProductSuite\"), NULL, &dwType, (LPBYTE) lpszProductSuites, &dwSize);\r\n#endif  \r\n  if (lResult != ERROR_SUCCESS || dwType != REG_MULTI_SZ)\r\n  {\r\n    //Don't forget to free up the resource we used\r\n    delete [] lpszProductSuites;\r\n    RegCloseKey(hKey);\r\n\r\n    return;\r\n  }\r\n\r\n  //Search for suite name in array of strings.\r\n  BOOL bValidated = FALSE;\r\n  LPTSTR lpszSuite = lpszProductSuites;\r\n  while (*lpszSuite) \r\n  {\r\n    //Note we do not need to implement checks for OSSUITE_WEBEDITION\r\n    //as Windows Server 2003 Web Edition which supports GetVersionEx\r\n    //using a OSVERSIONINFOEX structure.\r\n\r\n    //NT Embedded and subsequent version of Embedded Windows supports\r\n    //GetVersionEx using a OSVERSIONINFOEX structure, so no check for \r\n    //it here either\r\n\r\n    //Also I was unable to find any documentation on what Windows NT Datacenter Server\r\n    //puts in the ProductSuite. In Windows 2000 Datacenter it does not matter as it\r\n    //supports GetVersionEx using a OSVERSIONINFOEX structure.\r\n\r\n    //Turn on appropiate fields in the \"wSuiteMask\" bit field\r\n    if (_tcsicmp(lpszSuite, _T(\"Terminal Server\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_TERMINAL;\r\n    else if ((_tcsicmp(lpszSuite, _T(\"SBS\")) == 0) || (_tcsicmp(lpszSuite, _T(\"Small Business\")) == 0))\r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_SMALLBUSINESS;\r\n    else if (_tcsicmp(lpszSuite, _T(\"Enterprise\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_ENTERPRISE;\r\n    else if (_tcsicmp(lpszSuite, _T(\"Personal\")) == 0) \r\n      lpVersionInformation->dwSuiteMask |= OSSUITE_PERSONAL;\r\n\r\n    lpszSuite += (lstrlen(lpszSuite) + 1);\r\n  }\r\n\r\n  //Don't forget to free up the resource we used\r\n  delete [] lpszProductSuites;\r\n  RegCloseKey(hKey);\r\n}\r\n#endif //#if defined(_WIN32) || defined(_WIN64)  || defined (_WINDOWS)\r\n             \r\n#if defined(_WIN64) || defined(_WIN32)             \r\nBOOL COSVersion::IsWindows30(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows30(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 0);\r\n#endif\r\n}\r\n\r\n#if defined(_WIN64) || defined(_WIN32)             \r\nBOOL COSVersion::IsWindows31(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows31(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 10);\r\n#endif\r\n}\r\n\r\n#if defined(_WIN64) || defined(_WIN32)            \r\nBOOL COSVersion::IsWindows311(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#else\r\nBOOL COSVersion::IsWindows311(LPOS_VERSION_INFO lpVersionInformation)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return FALSE;\r\n#else\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          lpVersionInformation->dwUnderlyingMinorVersion == 11);\r\n#endif\r\n}\r\n\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\nBOOL COSVersion::IsWindowsForWorkgroups(LPOS_VERSION_INFO lpVersionInformation)\r\n#else\r\nBOOL COSVersion::IsWindowsForWorkgroups(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#endif //#if defined(_WINDOWS) && (defined(_WIN32) || defined(_WIN64))  \r\n{\r\n#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x &&\r\n          WFWLoaded());\r\n#else\r\n  return FALSE;          \r\n#endif //#if defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))  \r\n}\r\n\r\n\r\n#if defined(_WIN32)\r\nBOOL COSVersion::IsWin32sInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n#else\r\nBOOL COSVersion::IsWin32sInstalled(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n#endif //#if defined(_WIN64) || defined(_Win32             \r\n{\r\n#ifdef _WIN64\r\n  return FALSE;\r\n#elif _WIN32\r\n  return (lpVersionInformation->UnderlyingPlatform == Windows3x);\r\n#else\r\n  return FALSE;\r\n#endif\r\n}\r\n\r\nBOOL COSVersion::IsNTPreWin2k(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (lpVersionInformation->UnderlyingPlatform == WindowsNT &&\r\n          lpVersionInformation->dwUnderlyingMajorVersion <= 4);\r\n}\r\n\r\nBOOL COSVersion::IsNTPDC(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsNTPreWin2k(lpVersionInformation)) && \r\n         (lpVersionInformation->OSType == DomainController) &&\r\n         ((lpVersionInformation->dwSuiteMask & OSSUITE_PRIMARY_DOMAIN_CONTROLLER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTStandAloneServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsNTBDC(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && \r\n         (lpVersionInformation->OSType == DomainController) && \r\n         ((lpVersionInformation->dwSuiteMask & OSSUITE_BACKUP_DOMAIN_CONTROLLER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTWorkstation(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->OSType == Workstation);\r\n}\r\n\r\nBOOL COSVersion::IsTerminalServicesInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_TERMINAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsEmbedded(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_EMBEDDEDNT) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsTerminalServicesInRemoteAdminMode(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_REMOTEADMINMODE_TERMINAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::ISSmallBusinessEditionInstalled(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return ((lpVersionInformation->dwSuiteMask & OSSUITE_SMALLBUSINESS) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTEnterpriseServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsNTPreWin2k(lpVersionInformation) && (lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsNTDatacenterServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsNTPreWin2k(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000Professional(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == Workstation);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000Server(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000AdvancedServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000DatacenterServer(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return (IsWindows2000(lpVersionInformation) && (lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWin2000DomainController(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindows2000(lpVersionInformation) && (lpVersionInformation->OSType == DomainController);\r\n}\r\n\r\nBOOL COSVersion::IsXPPersonal(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_PERSONAL) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsXPProfessional(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == Workstation) && !IsXPPersonal(lpVersionInformation);\r\n}\r\n\r\nBOOL COSVersion::IsWebWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_WEBEDITION) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == Server);\r\n}\r\n\r\nBOOL COSVersion::IsEnterpriseWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_ENTERPRISE) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsDatacenterWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && ((lpVersionInformation->dwSuiteMask & OSSUITE_DATACENTER) != 0);\r\n}\r\n\r\nBOOL COSVersion::IsDomainControllerWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation)\r\n{\r\n  return IsWindowsXPOrWindowsServer2003(lpVersionInformation) && (lpVersionInformation->OSType == DomainController);\r\n}\r\n\r\nBOOL COSVersion::IsEmulated64Bit(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n{\r\n#ifdef _WIN64\r\n  return TRUE;\r\n#else\r\n  return FALSE;\r\n#endif\r\n}\r\n\r\nBOOL COSVersion::IsUnderlying64Bit(LPOS_VERSION_INFO /*lpVersionInformation*/)\r\n{\r\n#ifdef _WIN64\r\n  return TRUE;\r\n#elif UNDER_CE\r\n  return FALSE;\r\n#elif _WIN32\r\n  //Assume the worst\r\n  BOOL bSuccess = FALSE;  \r\n  \r\n  //Check to see if we are running on 64 bit Windows thro WOW64\r\n  HMODULE hKernel32 = GetModuleHandle(_T(\"KERNEL32.DLL\"));\r\n  if (hKernel32)\r\n  {\r\n    lpfnIsWow64Process pIsWow64Process = (lpfnIsWow64Process) GetProcAddress(hKernel32, \"IsWow64Process\"); \r\n    if (pIsWow64Process)\r\n    {\r\n      BOOL bWow64 = FALSE;\r\n      if (pIsWow64Process(GetCurrentProcess(), &bWow64))\r\n        bSuccess = bWow64;\r\n    }\r\n  }\r\n  return bSuccess;\r\n#else\r\n  return FALSE;\r\n#endif\r\n}"
  },
  {
    "path": "plugins/wmp/OSVer.h",
    "content": "/*\r\nModule : DTWINVER.H\r\nPurpose: Interface of a function to perform\r\n         version detection on OS\r\nCreated: PJN / 11-05-1996\r\n\r\n\r\nCopyright (c) 1997 - 2003 by PJ Naughter.  (Web: www.naughter.com, Email: pjna@naughter.com)\r\n\r\nAll rights reserved.\r\n\r\nCopyright / Usage Details:\r\n\r\nYou are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) \r\nwhen your product is released in binary form. You are allowed to modify the source code in any way you want \r\nexcept you cannot modify the copyright details at the top of each module. If you want to distribute source \r\ncode with your application, then you are only allowed to distribute versions released by the author. This is \r\nto maintain a single distribution point for the source code. \r\n\r\n*/\r\n\r\n#ifndef __DTWINVER_H__                                          \r\n\r\n\r\n////////////////////////////////// defines ////////////////////////////////////\r\n\r\n#define OSSUITE_SMALLBUSINESS             0x00000001\r\n#define OSSUITE_ENTERPRISE                0x00000002\r\n#define OSSUITE_PRIMARY_DOMAIN_CONTROLLER 0x00000004\r\n#define OSSUITE_BACKUP_DOMAIN_CONTROLLER  0x00000008\r\n#define OSSUITE_TERMINAL                  0x00000010\r\n#define OSSUITE_DATACENTER                0x00000020\r\n#define OSSUITE_PERSONAL                  0x00000040\r\n#define OSSUITE_WEBEDITION                0x00000080\r\n#define OSSUITE_EMBEDDEDNT                0x00000100\r\n#define OSSUITE_REMOTEADMINMODE_TERMINAL  0x00000200\r\n#define OSSUITE_UNIPROCESSOR_FREE         0x00000400\r\n#define OSSUITE_UNIPROCESSOR_CHECKED      0x00000800\r\n#define OSSUITE_MULTIPROCESSOR_FREE       0x00001000\r\n#define OSSUITE_MULTIPROCESSOR_CHECKED    0x00002000\r\n\r\n\r\n\r\n////////////////////////////////// Classes ////////////////////////////////////\r\n\r\nclass COSVersion\r\n{\r\npublic:\r\n//Enums\r\n  enum OS_PLATFORM\r\n  {\r\n    Dos = 0,\r\n    Windows3x = 1,\r\n    Windows9x = 2,\r\n    WindowsNT = 3,\r\n    WindowsCE = 4,\r\n  };\r\n\r\n  enum OS_TYPE\r\n  {\r\n    Workstation = 0,\r\n    Server = 1,\r\n    DomainController = 2,\r\n  };\r\n\r\n//defines\r\n  typedef struct _OS_VERSION_INFO\r\n  {\r\n  #ifndef UNDER_CE\r\n    //What version of OS is being emulated\r\n    DWORD dwEmulatedMajorVersion;\r\n    DWORD dwEmulatedMinorVersion;\r\n    DWORD dwEmulatedBuildNumber;\r\n    OS_PLATFORM EmulatedPlatform;\r\n  #ifdef _WIN32                    \r\n    TCHAR szEmulatedCSDVersion[128];\r\n  #else\r\n    char szEmulatedCSDVersion[128];\r\n  #endif  \r\n    WORD wEmulatedServicePackMajor;\r\n    WORD wEmulatedServicePackMinor;\r\n  #endif\r\n\r\n    //What version of OS is really running                 \r\n    DWORD dwUnderlyingMajorVersion;\r\n    DWORD dwUnderlyingMinorVersion;\r\n    DWORD dwUnderlyingBuildNumber;\r\n    OS_PLATFORM UnderlyingPlatform;   \r\n  #ifdef _WIN32                      \r\n    TCHAR szUnderlyingCSDVersion[128];\r\n  #else  \r\n    char szUnderlyingCSDVersion[128];\r\n  #endif  \r\n    WORD wUnderlyingServicePackMajor;\r\n    WORD wUnderlyingServicePackMinor;\r\n    DWORD dwSuiteMask;\r\n    OS_TYPE OSType;\r\n\r\n  #ifdef UNDER_CE\r\n    TCHAR szOEMInfo[256];\r\n    TCHAR szPlatformType[256];\r\n  #endif\r\n  } OS_VERSION_INFO, *POS_VERSION_INFO, FAR *LPOS_VERSION_INFO;\r\n\r\n//Constructors / Destructors\r\n  COSVersion(); \r\n  ~COSVersion();\r\n\r\n//Methods:\r\n  BOOL GetVersion(LPOS_VERSION_INFO lpVersionInformation);\r\n                                 \r\n//Please note that the return values for all the following functions \r\n//are mutually exclusive for example if you are running on \r\n//95 OSR2 then IsWindows95 will return FALSE\r\n  BOOL IsWindows30(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows31(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows311(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsForWorkgroups(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsCE(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95SP1(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows95OSR2(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98SP1(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows98SE(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsME(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT31(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT35(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT351(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsNT4(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindows2000(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsXPOrWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n//Returns the various flavours of the \"os\" that is installed. Note that these\r\n//functions are not completely mutually exlusive\r\n  BOOL IsWin32sInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTPreWin2k(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsNTWorkstation(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTStandAloneServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTPDC(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTBDC(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTEnterpriseServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsNTDatacenterServer(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsWin2000Professional(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000Server(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000AdvancedServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000DatacenterServer(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWin2000DomainController(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsXPPersonal(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsXPProfessional(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsXP(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWebWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEnterpriseWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsDatacenterWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsDomainControllerWindowsServer2003(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\n  BOOL IsTerminalServicesInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL ISSmallBusinessEditionInstalled(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEmulated64Bit(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsUnderlying64Bit(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsEmbedded(LPOS_VERSION_INFO lpVersionInformation);\r\n  BOOL IsTerminalServicesInRemoteAdminMode(LPOS_VERSION_INFO lpVersionInformation);\r\n\r\nprotected:\r\n//Defines / typedefs\r\n#if (defined(_WINDOWS) || defined(_DOS)) && (!defined(_WIN32) && !defined(_WIN64))  \r\n  #define CPEX_DEST_STDCALL        0x00000000L\r\n  #define HKEY32                   DWORD                                                               \r\n  #define HKEY_LOCAL_MACHINE       (( HKEY32 ) 0x80000002 )    \r\n  #define TCHAR                    char\r\n  #define _T\r\n  #define _tcsicmp                 strcmpi\r\n  #define _tcscpy                  strcpy\r\n  #define _tcslen                  strlen\r\n  #define _istdigit                isdigit\r\n  #define _ttoi                    atoi\r\n  #define _tcsupr                  strupr\r\n  #define _tcsstr                  strstr\r\n  #define LPCTSTR                  LPCSTR\r\n  #define ERROR_CALL_NOT_IMPLEMENTED  120\r\n  #define REG_DWORD                ( 4 )                                                               \r\n  #define REG_MULTI_SZ             ( 7 )\r\n  #define VER_PLATFORM_WIN32s             0\r\n  #define VER_PLATFORM_WIN32_WINDOWS      1\r\n  #define VER_PLATFORM_WIN32_NT           2\r\n  #define VER_PLATFORM_WIN32_CE           3\r\n#endif                      \r\n                      \r\n#if defined(_WINDOWS) && !defined(_WIN32) && !defined(_WIN64)  \r\n//Defines / Macros\r\n  #define LPTSTR LPSTR\r\n\r\n  typedef struct OSVERSIONINFO\r\n  { \r\n    DWORD dwOSVersionInfoSize; \r\n    DWORD dwMajorVersion; \r\n    DWORD dwMinorVersion; \r\n    DWORD dwBuildNumber; \r\n    DWORD dwPlatformId; \r\n    char szCSDVersion[128]; \r\n  } OSVERSIONINFO, *POSVERSIONINFO, FAR *LPOSVERSIONINFO; \r\n  \r\n//Methods\r\n  DWORD GetVersion();\r\n  BOOL GetVersionEx(LPOSVERSIONINFO lpVersionInfo);\r\n  LONG RegQueryValueEx(HKEY32 hKey, LPSTR  lpszValueName, LPDWORD lpdwReserved, LPDWORD lpdwType, LPBYTE  lpbData, LPDWORD lpcbData);\r\n  static BOOL WFWLoaded();                                     \r\n\r\n//Function Prototypes\r\n  typedef DWORD (FAR PASCAL  *lpfnLoadLibraryEx32W) (LPCSTR, DWORD, DWORD);\r\n  typedef BOOL  (FAR PASCAL  *lpfnFreeLibrary32W)   (DWORD);\r\n  typedef DWORD (FAR PASCAL  *lpfnGetProcAddress32W)(DWORD, LPCSTR);\r\n  typedef DWORD (FAR __cdecl *lpfnCallProcEx32W)    (DWORD, DWORD, DWORD, DWORD, ...);\r\n  typedef WORD  (FAR PASCAL  *lpfnWNetGetCaps)      (WORD);\r\n\r\n//Member variables\r\n  lpfnLoadLibraryEx32W  m_lpfnLoadLibraryEx32W;\r\n  lpfnFreeLibrary32W    m_lpfnFreeLibrary32W;\r\n  lpfnGetProcAddress32W m_lpfnGetProcAddress32W;\r\n  lpfnCallProcEx32W     m_lpfnCallProcEx32W;\r\n  DWORD                 m_hAdvApi32;    \r\n  DWORD                 m_hKernel32;\r\n  DWORD                 m_lpfnRegQueryValueExA;\r\n  DWORD                 m_lpfnGetVersionExA;\r\n  DWORD                 m_lpfnGetVersion;\r\n#endif //defined(_WINDOWS) && (!defined(_WIN32) && !defined(_WIN64))\r\n\r\n#ifdef _WIN32\r\n//Function Prototypes\r\n  typedef BOOL (WINAPI *lpfnIsWow64Process)(HANDLE, PBOOL);  \r\n#endif\r\n\r\n#if defined(_WIN32) || defined(_WINDOWS)\r\n//Defines / Macros\r\n  typedef struct OSVERSIONINFOEX \r\n  {  \r\n    DWORD dwOSVersionInfoSize;  \r\n    DWORD dwMajorVersion;  \r\n    DWORD dwMinorVersion;  \r\n    DWORD dwBuildNumber;  \r\n    DWORD dwPlatformId;  \r\n    TCHAR szCSDVersion[128];  \r\n    WORD wServicePackMajor;  \r\n    WORD wServicePackMinor;  \r\n    WORD wSuiteMask;  \r\n    BYTE wProductType;  \r\n    BYTE wReserved;\r\n  } OSVERSIONINFOEX, *POSVERSIONINFOEX, *LPOSVERSIONINFOEX;\r\n                  \r\n//Function Prototypes                  \r\n  typedef BOOL (WINAPI *lpfnGetVersionEx) (LPOSVERSIONINFO);  \r\n#endif  \r\n\r\n#ifndef _DOS         \r\n//Methods\r\n  void GetNTOSTypeFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bOnlyUpdateDCDetails);\r\n  void GetProductSuiteDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation) ;\r\n  void GetTerminalServicesRemoteAdminModeDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation);\r\n  void GetNTSP6aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso);\r\n  void GetXPSP1aDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation, BOOL bUpdateEmulatedAlso);\r\n  void GetNTHALDetailsFromRegistry(LPOS_VERSION_INFO lpVersionInformation);\r\n#else\r\n  BOOL GetInfoBySpawingWriteVer(COSVersion::LPOS_VERSION_INFO lpVersionInformation);\r\n  void GetWinInfo();\r\n#endif\r\n\r\n#if defined(_WIN32) || defined(_WIN64)\r\n  WORD GetNTServicePackFromRegistry();\r\n#endif    \r\n  WORD GetNTServicePackFromCSDString(LPCTSTR pszCSDVersion);\r\n};\r\n\r\n#endif //__DTWINVER_H__"
  },
  {
    "path": "plugins/wmp/Scrobbler.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"Scrobbler.h\"\r\n#include <shellapi.h>\r\n#include <io.h>\r\n//#include <exception>\r\n#include <sstream>\r\n\r\nusing namespace std;\r\n\r\n/*#############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : CScrobbler\r\n## Description  : Constructor\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nCScrobbler::CScrobbler()\r\n{\r\n    m_hInstance             = NULL;\r\n    m_strWorkingDir         = _T(\"\");\r\n    m_bTrackPlayFlag        = FALSE;\r\n    m_nMaxLogFileSize       = -1;\r\n    m_bUseNowPlaying        = FALSE;\r\n   \tm_bExitThread\t\t\t= FALSE;\r\n\tm_bRunningCallback\t\t= FALSE;\r\n    m_bAllowHttpStreams     = FALSE;\r\n    \r\n    m_AsState = AS_STOPPED;\r\n    \r\n    memset(&m_CurrentSong, 0, sizeof(m_CurrentSong));\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : ~CScrobbler\r\n## Description  : Destructor\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nCScrobbler::~CScrobbler()\r\n{\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : StartScrobbling\r\n## Description  : Startup routine for class\r\n##                Checks the data is valid and that\r\n##                the clss is ready to startup\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : strWorkingDir - Plugin dir path\r\n##                hInstance - HINSTANCE of plugin\r\n## Return       : BOOL (TRUE = success)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::StartScrobbling(CStdString strWorkingDir, HINSTANCE hInstance /*=NULL*/)\r\n{\r\n    BOOL    bRet = FALSE;\r\n    UINT    threadID = 0;\r\n\r\n    if ( ( !strWorkingDir.IsEmpty() ) )\r\n    {\r\n        m_strWorkingDir = strWorkingDir;\r\n        m_hInstance = hInstance;\r\n        m_Version.Refresh(m_hInstance);\r\n\r\n        int pos = strWorkingDir.ReverseFind('\\\\');\r\n        m_strWorkingDir = strWorkingDir.Left(pos+1);\r\n        m_strFileName = strWorkingDir.Mid(pos+1);\r\n    }\r\n    else\r\n        PRINTF(DEBUG_ERROR, \"CScrobbler::StartScrobbling\", \"Working dir is blank.\");\r\n    \r\n    InitialiseLogging();\r\n\r\n    PRINTF(DEBUG_FLOW,\r\n        \"CScrobbler::StartScrobbling\", \"Working dir %s\", \r\n        strWorkingDir.c_str());\r\n\r\n    m_Submitter.Init(GetAppId(), ScrobSubCallback, this);\r\n   \r\n    // Timer\r\n    unsigned dwThreadId = 0;\r\n    if(_beginthreadex(NULL, 0, TimeUpdaterThread, reinterpret_cast<void *>(this), 0, &dwThreadId) == 0)\r\n    {\r\n        PRINTF(DEBUG_ERROR, \"CScrobbler::StartScrobbling\", \"Could not start timer thread.\");\r\n        bRet = FALSE;\r\n    }\r\n    \r\n    PRINTF(DEBUG_RQD, \"CScrobbler::StartScrobbling\", \"Startup Complete.\");\r\n\r\n    return bRet;\r\n}\r\n    \r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : StopScrobbling\r\n## Description  : Performs closedown functions\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : BOOL (TRUE = success)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::StopScrobbling()\r\n{\r\n    PRINTF(DEBUG_FLOW, \"CScrobbler::StopScrobbling\", \"Stopping...\");\r\n\r\n    ASStop();\r\n    m_Submitter.Term();\r\n\r\n    m_bExitThread = TRUE;\r\n\r\n    ::SetEvent(m_hTimerEvent);\r\n    \r\n    return TRUE;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : TimerCallback\r\n## Description  : Callback function for the external\r\n##                timer. Checks playback state and \r\n##                triggers submissions\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : BOOL (FALSE causes timer to be killed)\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::TimerCallback()\r\n{\r\n    BOOL bRet = TRUE;\r\n\r\n    // If we are already checking or we aren't enabled don't continue.\r\n    // We don't return FALSE. This would\r\n    // cancel the timer which is OK when we are disabled but if the user enables us \r\n    // without restarting the player we have no way to restart the timer.\r\n    // Get it? Good.\r\n    if (m_bRunningCallback == TRUE)\r\n        return bRet;\r\n\r\n    m_bRunningCallback = TRUE;\r\n\r\n    // Non-blocking track play detection\r\n    if(m_bTrackPlayFlag)\r\n    {\r\n        // If we get here, a new track has just started\r\n\r\n        SONG_INFO tmpSong;\r\n        memset(&tmpSong, 0, sizeof(tmpSong));\r\n\r\n        // Not currently using this return value as we want to send partial\r\n        // info also and let the app validate it.\r\n        BOOL bOK = GetCurrentSong(&tmpSong);\r\n        memcpy(&m_CurrentSong, &tmpSong, sizeof(m_CurrentSong));\r\n\r\n        m_bTrackPlayFlag = FALSE;\r\n\r\n        if (!SupportedFileType(m_CurrentSong.m_strFileName))\r\n        {\r\n            ASStop();\r\n            m_AsState = AS_STOPPED;\r\n            m_bRunningCallback = FALSE;\r\n            return bRet;\r\n        }\r\n\r\n        // Send Start\r\n        ASStart();\r\n        m_AsState = AS_PLAYING;\r\n    }\r\n\r\n    switch (m_AsState)\r\n    {\r\n        case AS_PLAYING:\r\n            if (IsPaused())\r\n            {\r\n                ASPause();\r\n                m_AsState = AS_PAUSED;\r\n            }\r\n            else if (IsStopped())\r\n            {\r\n                ASStop();\r\n                m_AsState = AS_STOPPED;\r\n            }\r\n            break;\r\n        \r\n        case AS_STOPPED:\r\n            break;\r\n\r\n        case AS_PAUSED:\r\n            if (IsPlaying())\r\n            {\r\n                ASResume();\r\n                m_AsState = AS_PLAYING;\r\n            }\r\n            else if (IsStopped())\r\n            {\r\n                ASStop();\r\n                m_AsState = AS_STOPPED;\r\n            }\r\n            break;\r\n        \r\n        default:\r\n            ASSERT(false);\r\n    }\r\n\r\n    m_bRunningCallback = FALSE;\r\n    return bRet;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module\t\t: CScrobbler\r\n## Function\t\t: SupportedFileType\r\n## Description\t: Checks that the file type is valid \r\n##                for sending to the server\r\n##\r\n## Author(s)\t: Spib\r\n##\r\n## Parameters\t: strPath - full file path\r\n## Return\t\t: TRUE if file is OK\r\n##\r\n##############################################*/\r\nBOOL CScrobbler::SupportedFileType(CStdString strPath)\r\n{\r\n\tBOOL\t\tbRet = TRUE;\r\n\tCStdString\tstrTemp;\r\n\tCStdString\tstrReason;\r\n\tint\t\t\tnPos = 0;\r\n\r\n\tstrPath.MakeUpper();\r\n\r\n\tstrReason = \"Unknown\";\r\n\r\n\tif(!strPath.IsEmpty() && (strPath.GetLength() > 3))\r\n\t{\r\n\t\tstrTemp = strPath.Left(7);\r\n\t\tif((strTemp == \"HTTP://\") && !m_bAllowHttpStreams)\r\n\t\t{\r\n\t\t\tbRet = FALSE;\r\n\t\t\tstrReason = \"Cannot submit HTTP streams\";\r\n            PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n\t\t\treturn bRet;\r\n\t\t}\r\n\t\tstrTemp = strPath.Left(6);\r\n\t\tif((strTemp == \"MMS://\") && !m_bAllowHttpStreams)\r\n\t\t{\r\n\t\t\tbRet = FALSE;\r\n\t\t\tstrReason = \"Cannot submit MMS streams\";\r\n            PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n\t\t\treturn bRet;\r\n\t\t}\r\n\t\t// Is this a file?\r\n\t\tif (strTemp.Mid(1,2) == \":\\\\\" ||\r\n\t\t    strTemp.Mid(0,2) == \"\\\\\\\\\")\r\n\t\t{\r\n\t\t\tnPos = strPath.ReverseFind('.');\r\n\r\n\t\t\tif(nPos > 0)\r\n\t\t\t{\r\n\t\t\t\tstrTemp = strPath.Mid(nPos+1);\r\n\t\t\r\n\t\t\t\tif ((strTemp == \"NSV\") || \r\n\t\t\t\t    (strTemp == \"AVI\") ||\r\n    \t\t\t\t(strTemp == \"M2V\") ||\r\n\t    \t\t\t(strTemp == \"ASF\") ||\r\n\t\t    \t\t(strTemp == \"WMV\") ||\r\n\t\t\t    \t(strTemp == \"MPG\") ||\r\n\t\t\t\t    (strTemp == \"MPEG\"))\r\n\t\t\t\t{\r\n\t\t\t\t\tstrReason = \"Cannot submit Video files\";\r\n\t\t\t\t\tbRet = FALSE;\r\n                    PRINTF(DEBUG_INFO, \"CScrobbler::SupportedFileType\",\r\n                        \"File '%s' not supported: %s\", strPath.c_str(), strReason.c_str());\r\n                    return bRet;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t}\r\n\t}\r\n\r\n\treturn bRet;\t\r\n}\r\n\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : GetVersionString\r\n## Description  : Gets a string with the app name and\r\n##                version.\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : CStdString - version string\r\n##\r\n##############################################*/\r\nCStdString CScrobbler::GetVersionString()\r\n{\r\n    CStdString strText;\r\n    CStdString strVer;\r\n\r\n#ifdef _DEBUG\r\n    strVer = \"INTERNAL DEBUG BUILD\";\r\n#else\r\n    //strVer = \"INTERNAL TEST BUILD\";\r\n#endif\r\n\r\n    strText.Format(\"%s %s\", AUDIOSCROBBLER_VERSION, strVer.c_str());\r\n\r\n    return strText;\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : InitialiseLogging\r\n## Description  : Sets up the logging stuff\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nvoid CScrobbler::InitialiseLogging()\r\n{       \r\n    CStdString strVer;\r\n    CStdString strTemp;\r\n    CStdString strFileName;\r\n\r\n    // Initialise logging stuff\r\n    strTemp.Format(\"%s\\\\WmpPlugin.log\", ScrobSubmitter::GetLogPath().c_str());\r\n\r\n    // Here's how it works - \r\n    // If you have specified a log size > zero, the log\r\n    // is appended to up to the maximum size until the limit\r\n    // is reached. Then it is deleted and started again.\r\n    // If you specify a size of zero, logging is disabled.\r\n    // If you specify a size of < zero, logging is enabled but\r\n    // the log is overwritten on each execution and there is no \r\n    // maximum size.\r\n    if(m_nMaxLogFileSize > 0)\r\n    {\r\n        DEBUG_INIT(strTemp, FALSE, TRUE, FALSE);\r\n    }\r\n    else if(m_nMaxLogFileSize == 0)\r\n    {\r\n        DEBUG_INIT(strTemp, FALSE, FALSE, FALSE);\r\n    }\r\n    else\r\n    {\r\n        DEBUG_INIT(strTemp, TRUE, TRUE, FALSE);\r\n    }\r\n\r\n    DEBUG_SET_MAXSIZE(m_nMaxLogFileSize);\r\n\r\n#ifdef _DEBUG\r\n    DEBUG_SET_LEVEL(DEBUG_DETAIL);\r\n#else\r\n    DEBUG_SET_LEVEL(DEBUG_INFO);\r\n#endif\r\n\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s v%s (Build %s) %s\", GetAppName().c_str(), GetVersionString().c_str(), m_Version.GetAppPrivateBuild().c_str(), m_strFileName.c_str());\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s\", GetPlayerVersion().c_str());\r\n    PRINTF(DEBUG_RQD, \"Application Information\", \"%s\", m_Version.GetOSVersion().c_str());\r\n}\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : OnTrackPlay\r\n## Description  : Called when a new track has started\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : N/A\r\n## Return       : N/A\r\n##\r\n##############################################*/\r\nvoid CScrobbler::OnTrackPlay()\r\n{\r\n    // Only called in WMP version, never in Winamp.\r\n    m_bTrackPlayFlag = TRUE;\r\n}\r\n\r\n\r\n/*##############################################\r\n##\r\n## Module       : CScrobbler\r\n## Function     : TimeUpdaterThread\r\n## Description  : Acts as a rudimentary timer\r\n##\r\n## Author(s)    : Spib\r\n##\r\n## Parameters   : pParam - pScrobbler ptr\r\n## Return       : DWORD\r\n##\r\n##############################################*/\r\nunsigned __stdcall CScrobbler::TimeUpdaterThread(LPVOID pParam)\r\n{ \r\n    CScrobbler* pScrobbler = reinterpret_cast<CScrobbler*>(pParam);\r\n    \r\n    PRINTF(DEBUG_DETAIL, \"CScrobbler::TimeUpdaterThread\", \"Creating Event\");\r\n\r\n    // Before we enter the thread loop, let's check if a track got started\r\n    // before we had a chance to handle it\r\n    if ( pScrobbler->IsPlaying() )\r\n    {\r\n        PRINTF(DEBUG_DETAIL, \"CScrobbler::TimeUpdaterThread\",\r\n            \"Track playing at startup, will do extra OnTrackPlay\");\r\n        pScrobbler->OnTrackPlay();\r\n    }\r\n\r\n    pScrobbler->m_hTimerEvent = ::CreateEvent(NULL,// Default security\r\n                                    TRUE,// Manual reset\r\n                                    FALSE,// Initial state\r\n                                    NULL // Name\r\n                                    );\r\n    \r\n    // Start a 0.5 second timer, check if we need to exit\r\n    // After AUDIOSCROBBLER_TIMER seconds, do the callback\r\n    // Doing it this way means we can exit gracefully\r\n    while (pScrobbler->m_bExitThread == FALSE)\r\n    {\r\n        // The event is only signalled on exit so this is essentially a Sleep(500)\r\n        ::WaitForSingleObject(pScrobbler->m_hTimerEvent, 500);\r\n\r\n        if(pScrobbler->m_bExitThread == FALSE)\r\n        {\r\n            pScrobbler->TimerCallback();\r\n        }\r\n    }\r\n    \r\n    return 0;\r\n}\r\n\r\n// AS communication functions    \r\nvoid CScrobbler::ASStart()\r\n{\r\n    int id = m_Submitter.Start(\r\n        m_CurrentSong.m_strArtist,\r\n\t\tm_CurrentSong.m_strAlbumArtist,\r\n        m_CurrentSong.m_strTrack,\r\n        m_CurrentSong.m_strAlbum,\r\n        \"\",\r\n        m_CurrentSong.m_nLength,\r\n        m_CurrentSong.m_strFileName,\r\n        ScrobSubmitter::UTF_8);\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Start for \" << \r\n        m_CurrentSong.m_strArtist << \" - \" << m_CurrentSong.m_strTrack;\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASStart\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASStop()\r\n{\r\n    int id = m_Submitter.Stop();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Stop\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASStop\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASPause()\r\n{\r\n    int id = m_Submitter.Pause();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Pause\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASPause\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ASResume()\r\n{\r\n    int id = m_Submitter.Resume();\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << id << \": \" << \"Sent Resume\";\r\n    PRINTF(DEBUG_INFO, \"CScrobbler::ASResume\", os.str().c_str());\r\n}\r\n\r\nvoid CScrobbler::ScrobSubStatus(int reqID, bool error, std::string message)\r\n{\r\n    #ifdef _DEBUG\r\n        if (error)\r\n        {\r\n            MessageBox(NULL, message.c_str(), NULL, MB_OK);\r\n        }\r\n    #endif\r\n\r\n    ostringstream os;\r\n    os << \"ReqID \" << reqID << \": \" << message;\r\n    \r\n    int level = error ? DEBUG_ERROR_NC : DEBUG_INFO;\r\n    PRINTF(level, \"CScrobbler::ScrobSubStatus\", os.str().c_str());\r\n}\r\n\r\n"
  },
  {
    "path": "plugins/wmp/Scrobbler.h",
    "content": "  // Scrobbler.h: interface for the CScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_)\r\n#define AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n/*##############################################\r\n##\r\n## Module           : CAudioScrobbler\r\n## Description      : This class is the core of the \r\n##                    AudioScrobbler.\r\n##\r\n## Author(s)        : RJ, Spib\r\n##                  : Butchered by Erik for new AS plugin\r\n##\r\n## Modifications\r\n##\r\n## 07-04-2003 - Mods to integrate the new client protocol\r\n##\r\n##############################################*/\r\n\r\n#pragma once\r\n\r\n#include \"VersionApp.h\"\r\n#include \"StdStringArray.h\"\r\n#include \"ScrobSubmitter.h\"\r\n\r\n#define AUDIOSCROBBLER_VERSION              m_Version.GetAppVersion().c_str()\r\n#define SONG_INFO_FIELD_SIZE                1024\r\n\r\ntypedef struct \r\n{\r\n    char    m_strFileName[MAX_PATH];\r\n    char    m_strArtist[SONG_INFO_FIELD_SIZE];\r\n\tchar    m_strAlbumArtist[SONG_INFO_FIELD_SIZE];\r\n    char    m_strTrack [SONG_INFO_FIELD_SIZE];\r\n    char    m_strAlbum [SONG_INFO_FIELD_SIZE];\r\n    char    m_strGenre [SONG_INFO_FIELD_SIZE];\r\n    char    m_strComment [SONG_INFO_FIELD_SIZE];\r\n    int     m_nYear;\r\n    int     m_nTrackNo;\r\n    int     m_nLength;\r\n}SONG_INFO;\r\n\r\nclass CScrobbler  \r\n{\r\npublic:\r\n    CScrobbler();\r\n    virtual ~CScrobbler();\r\n\r\n    BOOL                StartScrobbling(CStdString strWorkingDir, HINSTANCE hInstance = NULL); // Init Routine\r\n    BOOL                StopScrobbling();                           // Init Routine\r\n\r\n    //Virtual Overrides\r\n    virtual CStdString  GetAppName() = 0;\r\n    virtual CStdString  GetAppId() = 0;\r\n    virtual CStdString  GetRegKey() = 0;\r\n    virtual CStdString  GetPlayerVersion() = 0; // Returns the player specific version string\r\n    virtual BOOL        IsPlaying() = 0;\r\n    virtual BOOL        IsPaused() = 0;\r\n    virtual BOOL        IsStopped() = 0;\r\n    virtual CStdString  GetCurrentSongFileName() = 0;\r\n    virtual int         GetTrackLength() = 0;\r\n    virtual int         GetTrackPosition() = 0;\r\n    virtual BOOL        GetCurrentSong(SONG_INFO* pSong) = 0;\r\n    virtual HWND        GetParentWnd() = 0;\r\n    \r\n    // Other\r\n    CStdString          GetVersionString();     // Get the AudioScrobbler's version info\r\n    CStdString          GetBuild(){return m_Version.GetAppPrivateBuild();}\r\n\r\n    static              unsigned __stdcall TimeUpdaterThread(LPVOID p);\r\n    BOOL                TimerCallback();\r\n\r\n    static void         ScrobSubCallback(int reqID, bool error, std::string message, void* userData)\r\n    { reinterpret_cast<CScrobbler*>(userData)->ScrobSubStatus(reqID, error, message); }\r\n\r\n\r\nprotected:  \r\n\tvirtual BOOL\t    SupportedFileType(CStdString strPath);\t// Is this a supported file type?\r\n    void                OnTrackPlay();                              // A new track has started\r\n    void                InitialiseLogging();                                // Initialise the logging\r\n    CStdString          ConvertFileSize(int nBytes);                // Convert file size in bytes to KB/MB\r\n    ScrobSubmitter  m_Submitter;\r\n\r\npublic:\r\n    // Internal Variables\r\n    CVersionApp             m_Version;\r\n    CStdString              m_strWorkingDir;            // Current working dir\r\n    CStdString              m_strFileName;              // Module File Name\r\n    HINSTANCE               m_hInstance;\r\n    BOOL                    m_bExitThread;\r\n    HANDLE                  m_hTimerEvent;              // Timer Handle\r\n\r\n    // Song playback stuff\r\n    SONG_INFO               m_CurrentSong;          // Currently Playing Song\r\n    BOOL                    m_bTrackPlayFlag;\r\n\r\n    // State Flags\r\n    BOOL                    m_bRunningCallback;     // Are we currently in the timer callback?\r\n\r\n    // Configurable Variables\r\n    int                     m_nMaxLogFileSize;      // Max size of debug log file\r\n    BOOL                    m_bAllowHttpStreams;\r\n    BOOL                    m_bUseNowPlaying;\r\n    void ASBootstrap();\r\n    \r\nprivate:\r\n\r\n    void ASStart();\r\n    void ASStop();\r\n    void ASPause();\r\n    void ASResume();\r\n\r\n    void ScrobSubStatus(int reqID, bool error, std::string message);\r\n    \r\n    enum EAsState\r\n    {\r\n        AS_STOPPED,\r\n        AS_PLAYING,\r\n        AS_PAUSED\r\n    };\r\n    \r\n    EAsState        m_AsState;\r\n};\r\n\r\n#endif // !defined(AFX_SCROBBLER_H__E3C26903_1FF2_4C2B_BF28_DF1F2B003DE1__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/wmp/StdAfx.cpp",
    "content": "// stdafx.cpp : source file that includes just the standard includes\r\n//  stdafx.pch will be the pre-compiled header\r\n//  stdafx.obj will contain the pre-compiled type information\r\n\r\n#include \"stdafx.h\"\r\n\r\n#ifdef _ATL_STATIC_REGISTRY\r\n#include <statreg.h>\r\n#endif\r\n"
  },
  {
    "path": "plugins/wmp/StdAfx.h",
    "content": "// stdafx.h : include file for standard system include files,\r\n//      or project specific include files that are used frequently,\r\n//      but are changed infrequently\r\n\r\n#if !defined(AFX_STDAFX_H__970E5960_5209_4AE7_8DD2_ACD4C1165941__INCLUDED_)\r\n#define AFX_STDAFX_H__970E5960_5209_4AE7_8DD2_ACD4C1165941__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n#define STRICT\r\n#ifndef _WIN32_WINNT\r\n#define _WIN32_WINNT 0x0500\r\n#endif\r\n#define _ATL_APARTMENT_THREADED\r\n\r\n#include <atlbase.h>\r\n//You may derive a class from CComModule and use it if you want to override\r\n//something, but do not change the name of _Module\r\nextern CComModule _Module;\r\n#include <atlcom.h>\r\n#include <ocidl.h>\t// Added by ClassView\r\n#include <atlwin.h>\r\n#include <atlhost.h>\r\n#pragma warning( disable : 4192 ) \r\n\r\n\r\n#include \"stdstring.h\"\r\n#include \"dbg.h\"\r\n#include \"ComDATE.h\"\r\n\r\n//{{AFX_INSERT_LOCATION}}\r\n// Microsoft Visual C++ will insert additional declarations immediately before the previous line.\r\n\r\n#endif // !defined(AFX_STDAFX_H__970E5960_5209_4AE7_8DD2_ACD4C1165941__INCLUDED)"
  },
  {
    "path": "plugins/wmp/StdString.h",
    "content": "// =============================================================================\r\n//  FILE:  StdString.h\r\n//  AUTHOR:\tJoe O'Leary (with outside help noted in comments)\r\n//\r\n//\r\n//\t\tIf you find any bugs int his code, please let me know:\r\n//\r\n//\t\t\t\tjmoleary@earthlink.net\r\n//\t\t\t\thttp://www.joeo.net/stdstring.htm (a bit outdated)\r\n//\r\n//      The latest version of this code should always be available at the\r\n//      following link:\r\n//\r\n//              http://www.joeo.net/code/StdString.zip (Dec 6, 2003)\r\n//\r\n//\r\n//  REMARKS:\r\n//\t\tThis header file declares the CStdStr template.  This template derives\r\n//\t\tthe Standard C++ Library basic_string<> template and add to it the\r\n//\t\tthe following conveniences:\r\n//\t\t\t- The full MFC CString set of functions (including implicit cast)\r\n//\t\t\t- writing to/reading from COM IStream interfaces\r\n//\t\t\t- Functional objects for use in STL algorithms\r\n//\r\n//\t\tFrom this template, we intstantiate two classes:  CStdStringA and\r\n//\t\tCStdStringW.  The name \"CStdString\" is just a #define of one of these,\r\n//\t\tbased upone the UNICODE macro setting\r\n//\r\n//\t\tThis header also declares our own version of the MFC/ATL UNICODE-MBCS\r\n//\t\tconversion macros.  Our version looks exactly like the Microsoft's to\r\n//\t\tfacilitate portability.\r\n//\r\n//\tNOTE:\r\n//\t\tIf you you use this in an MFC or ATL build, you should include either\r\n//\t\tafx.h or atlbase.h first, as appropriate.\r\n//\r\n//\tPEOPLE WHO HAVE CONTRIBUTED TO THIS CLASS:\r\n//\r\n//\t\tSeveral people have helped me iron out problems and othewise improve\r\n//\t\tthis class.  OK, this is a long list but in my own defense, this code\r\n//\t\thas undergone two major rewrites.  Many of the improvements became\r\n//\t\tnecessary after I rewrote the code as a template.  Others helped me\r\n//\t\timprove the CString facade.\r\n//\r\n//\t\tAnyway, these people are (in chronological order):\r\n//\r\n//\t\t\t- Pete the Plumber (???)\r\n//\t\t\t- Julian Selman\r\n//\t\t\t- Chris (of Melbsys)\r\n//\t\t\t- Dave Plummer\r\n//\t\t\t- John C Sipos\r\n//\t\t\t- Chris Sells\r\n//\t\t\t- Nigel Nunn\r\n//\t\t\t- Fan Xia\r\n//\t\t\t- Matthew Williams\r\n//\t\t\t- Carl Engman\r\n//\t\t\t- Mark Zeren\r\n//\t\t\t- Craig Watson\r\n//\t\t\t- Rich Zuris\r\n//\t\t\t- Karim Ratib\r\n//\t\t\t- Chris Conti\r\n//\t\t\t- Baptiste Lepilleur\r\n//\t\t\t- Greg Pickles\r\n//\t\t\t- Jim Cline\r\n//\t\t\t- Jeff Kohn\r\n//\t\t\t- Todd Heckel\r\n//\t\t\t- Ullrich Pollhne\r\n//\t\t\t- Joe Vitaterna\r\n//\t\t\t- Joe Woodbury\r\n//\t\t\t- Aaron (no last name)\r\n//\t\t\t- Joldakowski (???)\r\n//\t\t\t- Scott Hathaway\r\n//\t\t\t- Eric Nitzche\r\n//\t\t\t- Pablo Presedo\r\n//\t\t\t- Farrokh Nejadlotfi\r\n//\t\t\t- Jason Mills\r\n//\t\t\t- Igor Kholodov\r\n//\t\t\t- Mike Crusader\r\n//\t\t\t- John James\r\n//\t\t\t- Wang Haifeng\r\n//\t\t\t- Tim Dowty\r\n//          - Arnt Witteveen\r\n//          - Glen Maynard\r\n//          - Paul DeMarco\r\n//          - Bagira (full name?)\r\n//          - Ronny Schulz\r\n//          - Jakko Van Hunen\r\n//\t\t\t- Charles Godwin\r\n//\t\t\t- Henk Demper\r\n//\t\t\t- Greg Marr\r\n//\t\t\t- Bill Carducci\r\n//\t\t\t- Brian Groose\r\n//\t\t\t- MKingman\r\n//\r\n//\tREVISION HISTORY\r\n//\r\n//\t  2004-APR-22 - A big, big thank you to \"MKingman\" (whoever you are) for\r\n//\t\t\t\t\tfinally spotting a silly little error in StdCodeCvt that\r\n//\t\t\t\t\thas been causing me (and users of CStdString) problems for\r\n//\t\t\t\t\tyears in some relatively rare conversions.  I had reversed\r\n//\t\t\t\t\ttwo length arguments. \r\n//\r\n//    2003-NOV-24 - Thanks to a bunch of people for helping me clean up many\r\n//\t\t\t\t\tcompiler warnings (and yes, even a couple of actual compiler\r\n//\t\t\t\t\terrors).  These include Henk Demper for figuring out how\r\n//\t\t\t\t\tto make the Intellisense work on with CStdString on VC6,\r\n//\t\t\t\t\tsomething I was never able to do.  Greg Marr pointed out\r\n//\t\t\t\t\ta compiler warning about an unreferenced symbol and a\r\n//\t\t\t\t\tproblem with my version of Load in MFC builds.  Bill\r\n//\t\t\t\t\tCarducci took a lot of time with me to help me figure out\r\n//\t\t\t\t\twhy some implementations of the Standard C++ Library were\r\n//\t\t\t\t\treturning error codes for apparently successful conversions\r\n//\t\t\t\t\tbetween ASCII and UNICODE.  Finally thanks to Brian Groose\r\n//\t\t\t\t\tfor helping me fix compiler signed unsigned warnings in\r\n//\t\t\t\t\tseveral functions.\r\n//\r\n//    2003-JUL-10 - Thanks to Charles Godwin for making me realize my 'FmtArg'\r\n//\t\t\t\t\tfixes had inadvertently broken the DLL-export code (which is\r\n//                  normally commented out.  I had to move it up higher.  Also\r\n//\t\t\t\t\tthis helped me catch a bug in ssicoll that would prevent\r\n//                  compilation, otherwise.\r\n//\r\n//    2003-MAR-14 - Thanks to Jakko Van Hunen for pointing out a copy-and-paste\r\n//                  bug in one of the overloads of FmtArg.\r\n//\r\n//    2003-MAR-10 - Thanks to Ronny Schulz for (twice!) sending me some changes\r\n//                  to help CStdString build on SGI and for pointing out an\r\n//                  error in placement of my preprocessor macros for ssfmtmsg.\r\n//\r\n//    2002-NOV-26 - Thanks to Bagira for pointing out that my implementation of\r\n//                  SpanExcluding was not properly handling the case in which\r\n//                  the string did NOT contain any of the given characters\r\n//\r\n//    2002-OCT-21 - Many thanks to Paul DeMarco who was invaluable in helping me\r\n//                  get this code working with Borland's free compiler as well\r\n//                  as the Dev-C++ compiler (available free at SourceForge).\r\n//\r\n//    2002-SEP-13 - Thanks to Glen Maynard who helped me get rid of some loud\r\n//                  but harmless warnings that were showing up on g++.  Glen\r\n//                  also pointed out that some pre-declarations of FmtArg<>\r\n//                  specializations were unnecessary (and no good on G++)\r\n//\r\n//    2002-JUN-26 - Thanks to Arnt Witteveen for pointing out that I was using\r\n//                  static_cast<> in a place in which I should have been using\r\n//                  reinterpret_cast<> (the ctor for unsigned char strings).\r\n//                  That's what happens when I don't unit-test properly!\r\n//                  Arnt also noticed that CString was silently correcting the\r\n//                  'nCount' argument to Left() and Right() where CStdString was\r\n//                  not (and crashing if it was bad).  That is also now fixed!\r\n//\r\n//\t  2002-FEB-25 - Thanks to Tim Dowty for pointing out (and giving me the fix\r\n//\t\t\t\t\tfor) a conversion problem with non-ASCII MBCS characters.\r\n//\t\t\t\t\tCStdString is now used in my favorite commercial MP3 player!\r\n//\r\n//\t  2001-DEC-06 - Thanks to Wang Haifeng for spotting a problem in one of the\r\n//\t\t\t\t\tassignment operators (for _bstr_t) that would cause compiler\r\n//\t\t\t\t\terrors when refcounting protection was turned off.\r\n//\r\n//\t  2001-NOV-27 - Remove calls to operator!= which involve reverse_iterators\r\n//\t\t\t\t\tdue to a conflict with the rel_ops operator!=.  Thanks to\r\n//\t\t\t\t\tJohn James for pointing this out.\r\n//\r\n//    2001-OCT-29 - Added a minor range checking fix for the Mid function to\r\n//\t\t\t\t\tmake it as forgiving as CString's version is.  Thanks to\r\n//\t\t\t\t\tIgor Kholodov for noticing this.  \r\n//\t\t\t\t  - Added a specialization of std::swap for CStdString.  Thanks\r\n//\t\t\t\t\tto Mike Crusader for suggesting this!  It's commented out\r\n//\t\t\t\t\tbecause you're not supposed to inject your own code into the\r\n//\t\t\t\t\t'std' namespace.  But if you don't care about that, it's\r\n//\t\t\t\t\tthere if you want it\r\n//\t\t\t\t  - Thanks to Jason Mills for catching a case where CString was\r\n//\t\t\t\t\tmore forgiving in the Delete() function than I was.\r\n//\r\n//\t  2001-JUN-06 - I was violating the Standard name lookup rules stated\r\n//\t\t\t\t\tin [14.6.2(3)].  None of the compilers I've tried so\r\n//\t\t\t\t\tfar apparently caught this but HP-UX aCC 3.30 did.  The\r\n//\t\t\t\t\tfix was to add 'this->' prefixes in many places.\r\n//\t\t\t\t\tThanks to Farrokh Nejadlotfi for this!\r\n//\r\n//\t  2001-APR-27 - StreamLoad was calculating the number of BYTES in one\r\n//\t\t\t\t\tcase, not characters.  Thanks to Pablo Presedo for this.\r\n//\r\n//    2001-FEB-23 - Replace() had a bug which caused infinite loops if the\r\n//\t\t\t\t\tsource string was empty.  Fixed thanks to Eric Nitzsche.\r\n//\r\n//    2001-FEB-23 - Scott Hathaway was a huge help in providing me with the\r\n//\t\t\t\t\tability to build CStdString on Sun Unix systems.  He\r\n//\t\t\t\t\tsent me detailed build reports about what works and what\r\n//\t\t\t\t\tdoes not.  If CStdString compiles on your Unix box, you\r\n//\t\t\t\t\tcan thank Scott for it.\r\n//\r\n//\t  2000-DEC-29 - Joldakowski noticed one overload of Insert failed to do a\r\n//\t\t\t\t\trange check as CString's does.  Now fixed -- thanks!\r\n//\r\n//\t  2000-NOV-07 - Aaron pointed out that I was calling static member\r\n//\t\t\t\t\tfunctions of char_traits via a temporary.  This was not\r\n//\t\t\t\t\ttechnically wrong, but it was unnecessary and caused\r\n//\t\t\t\t\tproblems for poor old buggy VC5.  Thanks Aaron!\r\n//\r\n//\t  2000-JUL-11 - Joe Woodbury noted that the CString::Find docs don't match\r\n//\t\t\t\t\twhat the CString::Find code really ends up doing.   I was\r\n//\t\t\t\t\ttrying to match the docs.  Now I match the CString code\r\n//\t\t\t\t  - Joe also caught me truncating strings for GetBuffer() calls\r\n//\t\t\t\t\twhen the supplied length was less than the current length.\r\n//\r\n//\t  2000-MAY-25 - Better support for STLPORT's Standard library distribution\r\n//\t\t\t\t  - Got rid of the NSP macro - it interfered with Koenig lookup\r\n//\t\t\t\t  - Thanks to Joe Woodbury for catching a TrimLeft() bug that\r\n//\t\t\t\t\tI introduced in January.  Empty strings were not getting\r\n//\t\t\t\t\ttrimmed\r\n//\r\n//\t  2000-APR-17 - Thanks to Joe Vitaterna for pointing out that ReverseFind\r\n//\t\t\t\t\tis supposed to be a const function.\r\n//\r\n//\t  2000-MAR-07 - Thanks to Ullrich Pollhne for catching a range bug in one\r\n//\t\t\t\t\tof the overloads of assign.\r\n//\r\n//    2000-FEB-01 - You can now use CStdString on the Mac with CodeWarrior!\r\n//\t\t\t\t\tThanks to Todd Heckel for helping out with this.\r\n//\r\n//\t  2000-JAN-23 - Thanks to Jim Cline for pointing out how I could make the\r\n//\t\t\t\t\tTrim() function more efficient.\r\n//\t\t\t\t  - Thanks to Jeff Kohn for prompting me to find and fix a typo\r\n//\t\t\t\t\tin one of the addition operators that takes _bstr_t.\r\n//\t\t\t\t  - Got rid of the .CPP file -  you only need StdString.h now!\r\n//\r\n//\t  1999-DEC-22 - Thanks to Greg Pickles for helping me identify a problem\r\n//\t\t\t\t\twith my implementation of CStdString::FormatV in which\r\n//\t\t\t\t\tresulting string might not be properly NULL terminated.\r\n//\r\n//\t  1999-DEC-06 - Chris Conti pointed yet another basic_string<> assignment\r\n//\t\t\t\t\tbug that MS has not fixed.  CStdString did nothing to fix\r\n//\t\t\t\t\tit either but it does now!  The bug was: create a string\r\n//\t\t\t\t\tlonger than 31 characters, get a pointer to it (via c_str())\r\n//\t\t\t\t\tand then assign that pointer to the original string object.\r\n//\t\t\t\t\tThe resulting string would be empty.  Not with CStdString!\r\n//\r\n//\t  1999-OCT-06 - BufferSet was erasing the string even when it was merely\r\n//\t\t\t\t\tsupposed to shrink it.  Fixed.  Thanks to Chris Conti.\r\n//\t\t\t\t  - Some of the Q172398 fixes were not checking for assignment-\r\n//\t\t\t\t\tto-self.  Fixed.  Thanks to Baptiste Lepilleur.\r\n//\r\n//\t  1999-AUG-20 - Improved Load() function to be more efficient by using \r\n//\t\t\t\t\tSizeOfResource().  Thanks to Rich Zuris for this.\r\n//\t\t\t\t  - Corrected resource ID constructor, again thanks to Rich.\r\n//\t\t\t\t  - Fixed a bug that occurred with UNICODE characters above\r\n//\t\t\t\t\tthe first 255 ANSI ones.  Thanks to Craig Watson. \r\n//\t\t\t\t  - Added missing overloads of TrimLeft() and TrimRight().\r\n//\t\t\t\t\tThanks to Karim Ratib for pointing them out\r\n//\r\n//\t  1999-JUL-21 - Made all calls to GetBuf() with no args check length first.\r\n//\r\n//\t  1999-JUL-10 - Improved MFC/ATL independence of conversion macros\r\n//\t\t\t\t  - Added SS_NO_REFCOUNT macro to allow you to disable any\r\n//\t\t\t\t\treference-counting your basic_string<> impl. may do.\r\n//\t\t\t\t  - Improved ReleaseBuffer() to be as forgiving as CString.\r\n//\t\t\t\t\tThanks for Fan Xia for helping me find this and to\r\n//\t\t\t\t\tMatthew Williams for pointing it out directly.\r\n//\r\n//\t  1999-JUL-06 - Thanks to Nigel Nunn for catching a very sneaky bug in\r\n//\t\t\t\t\tToLower/ToUpper.  They should call GetBuf() instead of\r\n//\t\t\t\t\tdata() in order to ensure the changed string buffer is not\r\n//\t\t\t\t\treference-counted (in those implementations that refcount).\r\n//\r\n//\t  1999-JUL-01 - Added a true CString facade.  Now you can use CStdString as\r\n//\t\t\t\t\ta drop-in replacement for CString.  If you find this useful,\r\n//\t\t\t\t\tyou can thank Chris Sells for finally convincing me to give\r\n//\t\t\t\t\tin and implement it.\r\n//\t\t\t\t  - Changed operators << and >> (for MFC CArchive) to serialize\r\n//\t\t\t\t\tEXACTLY as CString's do.  So now you can send a CString out\r\n//\t\t\t\t\tto a CArchive and later read it in as a CStdString.   I have\r\n//\t\t\t\t\tno idea why you would want to do this but you can. \r\n//\r\n//\t  1999-JUN-21 - Changed the CStdString class into the CStdStr template.\r\n//\t\t\t\t  - Fixed FormatV() to correctly decrement the loop counter.\r\n//\t\t\t\t\tThis was harmless bug but a bug nevertheless.  Thanks to\r\n//\t\t\t\t\tChris (of Melbsys) for pointing it out\r\n//\t\t\t\t  - Changed Format() to try a normal stack-based array before\r\n//\t\t\t\t\tusing to _alloca().\r\n//\t\t\t\t  - Updated the text conversion macros to properly use code\r\n//\t\t\t\t\tpages and to fit in better in MFC/ATL builds.  In other\r\n//\t\t\t\t\twords, I copied Microsoft's conversion stuff again. \r\n//\t\t\t\t  - Added equivalents of CString::GetBuffer, GetBufferSetLength\r\n//\t\t\t\t  - new sscpy() replacement of CStdString::CopyString()\r\n//\t\t\t\t  - a Trim() function that combines TrimRight() and TrimLeft().\r\n//\r\n//\t  1999-MAR-13 - Corrected the \"NotSpace\" functional object to use _istpace()\r\n//\t\t\t\t\tinstead of _isspace()   Thanks to Dave Plummer for this.\r\n//\r\n//\t  1999-FEB-26 - Removed errant line (left over from testing) that #defined\r\n//\t\t\t\t\t_MFC_VER.  Thanks to John C Sipos for noticing this.\r\n//\r\n//\t  1999-FEB-03 - Fixed a bug in a rarely-used overload of operator+() that\r\n//\t\t\t\t\tcaused infinite recursion and stack overflow\r\n//\t\t\t\t  - Added member functions to simplify the process of\r\n//\t\t\t\t\tpersisting CStdStrings to/from DCOM IStream interfaces \r\n//\t\t\t\t  - Added functional objects (e.g. StdStringLessNoCase) that\r\n//\t\t\t\t\tallow CStdStrings to be used as keys STL map objects with\r\n//\t\t\t\t\tcase-insensitive comparison \r\n//\t\t\t\t  - Added array indexing operators (i.e. operator[]).  I\r\n//\t\t\t\t\toriginally assumed that these were unnecessary and would be\r\n//\t\t\t\t\tinherited from basic_string.  However, without them, Visual\r\n//\t\t\t\t\tC++ complains about ambiguous overloads when you try to use\r\n//\t\t\t\t\tthem.  Thanks to Julian Selman to pointing this out. \r\n//\r\n//\t  1998-FEB-?? - Added overloads of assign() function to completely account\r\n//\t\t\t\t\tfor Q172398 bug.  Thanks to \"Pete the Plumber\" for this\r\n//\r\n//\t  1998-FEB-?? - Initial submission\r\n//\r\n// COPYRIGHT:\r\n//\t\t2002 Joseph M. O'Leary.  This code is 100% free.  Use it anywhere you\r\n//      want.  Rewrite it, restructure it, whatever.  If you can write software\r\n//      that makes money off of it, good for you.  I kinda like capitalism. \r\n//      Please don't blame me if it causes your $30 billion dollar satellite\r\n//      explode in orbit.  If you redistribute it in any form, I'd appreciate it\r\n//      if you would leave this notice here.\r\n// =============================================================================\r\n\r\n// Avoid multiple inclusion the VC++ way,\r\n// Turn off browser references\r\n// Turn off unavoidable compiler warnings\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER > 1100)\r\n\t#pragma once\r\n\t#pragma component(browser, off, references, \"CStdString\")\r\n\t#pragma warning (disable : 4290) // C++ Exception Specification ignored\r\n\t#pragma warning (disable : 4127) // Conditional expression is constant\r\n\t#pragma warning (disable : 4097) // typedef name used as synonym for class name\r\n#endif\r\n\r\n// Borland warnings to turn off\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option push -w-inl\r\n//\t#pragma warn -inl   // Turn off inline function warnings\r\n#endif\r\n\r\n#ifndef STDSTRING_H\r\n#define STDSTRING_H\r\n\r\n// SS_IS_INTRESOURCE\r\n// -----------------\r\n//\t\tA copy of IS_INTRESOURCE from VC7.  Because old VC6 version of winuser.h\r\n//\t\tdoesn't have this.\r\n\r\n#define SS_IS_INTRESOURCE\r\n\r\n#if !defined (SS_ANSI) && defined(_MSC_VER)\r\n\t#undef SS_IS_INTRESOURCE\r\n\t#if defined(_WIN64)\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned __int64)(_r) >> 16) == 0)\r\n\t#else\r\n\t\t#define SS_IS_INTRESOURCE(_r) (((unsigned long)(_r) >> 16) == 0)\r\n\t#endif\r\n#endif\r\n\r\n\r\n// MACRO: SS_UNSIGNED\r\n// ------------------\r\n//      This macro causes the addition of a constructor and assignment operator\r\n//      which take unsigned characters.  CString has such functions and in order\r\n//      to provide maximum CString-compatability, this code needs them as well.\r\n//      In practice you will likely never need these functions...\r\n\r\n//#define SS_UNSIGNED\r\n\r\n#ifdef SS_ALLOW_UNSIGNED_CHARS\r\n\t#define SS_UNSIGNED\r\n#endif\r\n\r\n// MACRO: SS_SAFE_FORMAT\r\n// ---------------------\r\n//      This macro provides limited compatability with a questionable CString\r\n//      \"feature\".  You can define it in order to avoid a common problem that\r\n//      people encounter when switching from CString to CStdString.\r\n//\r\n//      To illustrate the problem -- With CString, you can do this:\r\n//\r\n//          CString sName(\"Joe\");\r\n//          CString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // WORKS!\r\n//\r\n//      However if you were to try this with CStdString, your program would\r\n//      crash.\r\n//\r\n//          CStdString sName(\"Joe\");\r\n//          CStdString sTmp;\r\n//          sTmp.Format(\"My name is %s\", sName);                    // CRASHES!\r\n//\r\n//      You must explicitly call c_str() or cast the object to the proper type\r\n//\r\n//          sTmp.Format(\"My name is %s\", sName.c_str());            // WORKS!\r\n//          sTmp.Format(\"My name is %s\", static_cast<PCSTR>(sName));// WORKS!\r\n//          sTmp.Format(\"My name is %s\", (PCSTR)sName);// WORKS!\r\n//\r\n//      This is because it is illegal to pass anything but a POD type as a\r\n//      variadic argument to a variadic function (i.e. as one of the \"...\"\r\n//      arguments).  The type const char* is a POD type.  The type CStdString\r\n//      is not.  Of course, neither is the type CString, but CString lets you do\r\n//      it anyway due to the way they laid out the class in binary.  I have no\r\n//      control over this in CStdString since I derive from whatever\r\n//      implementation of basic_string is available.\r\n//\r\n//      However if you have legacy code (which does this) that you want to take\r\n//      out of the MFC world and you don't want to rewrite all your calls to\r\n//      Format(), then you can define this flag and it will no longer crash.\r\n//\r\n//      Note however that this ONLY works for Format(), not sprintf, fprintf, \r\n//      etc.  If you pass a CStdString object to one of those functions, your\r\n//      program will crash.  Not much I can do to get around this, short of\r\n//      writing substitutes for those functions as well.\r\n\r\n#define SS_SAFE_FORMAT  // use new template style Format() function\r\n\r\n\r\n// MACRO: SS_NO_IMPLICIT_CAST\r\n// --------------------------\r\n//      Some people don't like the implicit cast to const char* (or rather to\r\n//      const CT*) that CStdString (and MFC's CString) provide.  That was the\r\n//      whole reason I created this class in the first place, but hey, whatever\r\n//      bakes your cake.  Just #define this macro to get rid of the the implicit\r\n//      cast.\r\n\r\n//#define SS_NO_IMPLICIT_CAST // gets rid of operator const CT*()\r\n\r\n\r\n// MACRO: SS_NO_REFCOUNT\r\n// ---------------------\r\n//\t\tturns off reference counting at the assignment level.  Only needed\r\n//\t\tfor the version of basic_string<> that comes with Visual C++ versions\r\n//\t\t6.0 or earlier, and only then in some heavily multithreaded scenarios.\r\n//\t\tUncomment it if you feel you need it.\r\n\r\n//#define SS_NO_REFCOUNT\r\n\r\n// MACRO: SS_WIN32\r\n// ---------------\r\n//      When this flag is set, we are building code for the Win32 platform and\r\n//      may use Win32 specific functions (such as LoadString).  This gives us\r\n//      a couple of nice extras for the code.\r\n//\r\n//      Obviously, Microsoft's is not the only compiler available for Win32 out\r\n//      there.  So I can't just check to see if _MSC_VER is defined to detect\r\n//      if I'm building on Win32.  So for now, if you use MS Visual C++ or\r\n//      Borland's compiler, I turn this on.  Otherwise you may turn it on\r\n//      yourself, if you prefer\r\n#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WIN32)\r\n    #define SS_WIN32\r\n#endif\r\n\r\n// MACRO: SS_ANSI\r\n// --------------\r\n//      When this macro is defined, the code attempts only to use ANSI/ISO\r\n//      standard library functions to do it's work.  It will NOT attempt to use\r\n//      any Win32 of Visual C++ specific functions -- even if they are\r\n//      available.  You may define this flag yourself to prevent any Win32\r\n//      of VC++ specific functions from being called. \r\n\r\n// If we're not on Win32, we MUST use an ANSI build\r\n\r\n#ifndef SS_WIN32\r\n    #if !defined(SS_NO_ANSI)\r\n        #define SS_ANSI\r\n    #endif\r\n#endif\r\n\r\n// MACRO: SS_ALLOCA\r\n// ----------------\r\n//      Some implementations of the Standard C Library have a non-standard\r\n//      function known as alloca().  This functions allows one to allocate a\r\n//      variable amount of memory on the stack.  It is needed to implement\r\n//      the ASCII/MBCS conversion macros.\r\n//\r\n//      I wanted to find some way to determine automatically if alloca() is\r\n//\t\tavailable on this platform via compiler flags but that is asking for\r\n//\t\ttrouble.  The crude test presented here will likely need fixing on\r\n//\t\tother platforms.  Therefore I'll leave it up to you to fiddle with\r\n//\t\tthis test to determine if it exists.  Just make sure SS_ALLOCA is or\r\n//\t\tis not defined as appropriate and you control this feature.\r\n\r\n#if defined(_MSC_VER) && !defined(SS_ANSI)\r\n\t#define SS_ALLOCA\r\n#endif\r\n\r\n// MACRO: SS_MBCS\r\n// --------------\r\n//\t\tSetting this macro means you are using MBCS characters.  In MSVC\r\n//\t\tbuilds, this macro gets set automatically by detection of the\r\n//\t\tpreprocessor flag _MBCS.  For other platforms you may set it manually\r\n//\t\tif you wish.  The only effect it currently has is to cause the\r\n//\t\tallocation of more space for wchar_t --> char conversions.\r\n//\t\tNote that MBCS does not mean UNICODE.\r\n//\r\n//\t#define SS_MBCS\r\n//\r\n#ifdef _MBCS\r\n\t#define SS_MBCS\r\n#endif\r\n\r\n\r\n\r\n// Compiler Error regarding _UNICODE and UNICODE\r\n// -----------------------------------------------\r\n// Microsoft header files are screwy.  Sometimes they depend on a preprocessor \r\n// flag named \"_UNICODE\".  Other times they check \"UNICODE\" (note the lack of\r\n// leading underscore in the second version\".  In several places, they silently\r\n// \"synchronize\" these two flags this by defining one of the other was defined. \r\n// In older version of this header , I used to try to do the same thing. \r\n//\r\n// However experience has taught me that this is a bad idea.  You get weird\r\n// compiler errors that seem to indicate things like LPWSTR and LPTSTR not being\r\n// equivalent in UNICODE builds, stuff like that (when they MUST be in a proper\r\n// UNICODE  build).  You end up scratching your head and saying, \"But that HAS\r\n// to compile!\".\r\n//\r\n// So what should you do if you get this error?\r\n//\r\n// Make sure that both macros (_UNICODE and UNICODE) are defined before this\r\n// file is included.  You can do that by either\r\n//\r\n//\t\ta) defining both yourself before any files get included\r\n//\t\tb) including the proper MS headers in the proper order\r\n//\t\tc) including this file before any other file, uncommenting\r\n//\t\t   the #defines below, and commenting out the #errors\r\n//\r\n//\tPersonally I recommend solution a) but it's your call.\r\n\r\n#ifdef _MSC_VER\r\n\t#if defined (_UNICODE) && !defined (UNICODE)\r\n\t\t#error UNICODE defined  but not UNICODE\r\n\t//\t#define UNICODE  // no longer silently fix this\r\n\t#endif\r\n\t#if defined (UNICODE) && !defined (_UNICODE)\r\n\t\t#error Warning, UNICODE defined  but not _UNICODE\r\n\t//\t#define _UNICODE  // no longer silently fix this\r\n\t#endif\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// MIN and MAX.  The Standard C++ template versions go by so many names (at\r\n// at least in the MS implementation) that you never know what's available \r\n// -----------------------------------------------------------------------------\r\ntemplate<class Type>\r\ninline const Type& SSMIN(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 < arg1 ? arg2 : arg1;\r\n}\r\ntemplate<class Type>\r\ninline const Type& SSMAX(const Type& arg1, const Type& arg2)\r\n{\r\n\treturn arg2 > arg1 ? arg2 : arg1;\r\n}\r\n\r\n// If they have not #included W32Base.h (part of my W32 utility library) then\r\n// we need to define some stuff.  Otherwise, this is all defined there.\r\n\r\n#if !defined(W32BASE_H)\r\n\r\n\t// If they want us to use only standard C++ stuff (no Win32 stuff)\r\n\r\n\t#ifdef SS_ANSI\r\n\r\n\t\t// On Win32 we have TCHAR.H so just include it.  This is NOT violating\r\n        // the spirit of SS_ANSI as we are not calling any Win32 functions here.\r\n        \r\n\t\t#ifdef SS_WIN32\r\n\r\n\t\t\t#include <TCHAR.H>\r\n\t\t\t#include <WTYPES.H>\r\n\t\t\t#ifndef STRICT\r\n\t\t\t\t#define STRICT\r\n\t\t\t#endif\r\n\r\n        // ... but on non-Win32 platforms, we must #define the types we need.\r\n\r\n\t\t#else\r\n\r\n\t\t\ttypedef const char*\t\tPCSTR;\r\n\t\t\ttypedef char*\t\t\tPSTR;\r\n\t\t\ttypedef const wchar_t*\tPCWSTR;\r\n\t\t\ttypedef wchar_t*\t\tPWSTR;\r\n\t\t\t#ifdef UNICODE\r\n\t\t\t\ttypedef wchar_t\t\tTCHAR;\r\n\t\t\t#else\r\n\t\t\t\ttypedef char\t\tTCHAR;\r\n\t\t\t#endif\r\n\t\t\ttypedef wchar_t\t\t\tOLECHAR;\r\n\r\n\t\t#endif\t// #ifndef _WIN32\r\n\r\n\r\n\t\t// Make sure ASSERT and verify are defined using only ANSI stuff\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <assert.h>\r\n\t\t\t#define ASSERT(f) assert((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#else // ...else SS_ANSI is NOT defined\r\n\r\n\t\t#include <TCHAR.H>\r\n\t\t#include <WTYPES.H>\r\n\t\t#ifndef STRICT\r\n\t\t\t#define STRICT\r\n\t\t#endif\r\n\r\n\t\t// Make sure ASSERT and verify are defined\r\n\r\n\t\t#ifndef ASSERT\r\n\t\t\t#include <crtdbg.h>\r\n\t\t\t#define ASSERT(f) _ASSERTE((f))\r\n\t\t#endif\r\n\t\t#ifndef VERIFY\r\n\t\t\t#ifdef _DEBUG\r\n\t\t\t\t#define VERIFY(x) ASSERT((x))\r\n\t\t\t#else\r\n\t\t\t\t#define VERIFY(x) x\r\n\t\t\t#endif\r\n\t\t#endif\r\n\r\n\t#endif // #ifdef SS_ANSI\r\n\r\n\t#ifndef UNUSED\r\n\t\t#define UNUSED(x) x\r\n\t#endif\r\n\r\n#endif // #ifndef W32BASE_H\r\n\r\n// Standard headers needed\r\n\r\n#include <string>\t\t\t// basic_string\r\n#include <algorithm>\t\t// for_each, etc.\r\n#include <functional>\t\t// for StdStringLessNoCase, et al\r\n#include <locale>\t\t// for various facets\r\n\r\n// If this is a recent enough version of VC include comdef.h, so we can write\r\n// member functions to deal with COM types & compiler support classes e.g.\r\n// _bstr_t\r\n\r\n#if defined (_MSC_VER) && (_MSC_VER >= 1100)\r\n\t#include <comdef.h>\r\n\t#define SS_INC_COMDEF\t\t// signal that we #included MS comdef.h file\r\n\t#define STDSTRING_INC_COMDEF\r\n\t#define SS_NOTHROW __declspec(nothrow)\r\n#else\r\n\t#define SS_NOTHROW\r\n#endif\r\n\r\n#ifndef TRACE\r\n\t#define TRACE_DEFINED_HERE\r\n\t#define TRACE\r\n#endif\r\n\r\n// Microsoft defines PCSTR, PCWSTR, etc, but no PCTSTR.  I hate to use the\r\n// versions with the \"L\" in front of them because that's a leftover from Win 16\r\n// days, even though it evaluates to the same thing.  Therefore, Define a PCSTR\r\n// as an LPCTSTR.\r\n\r\n#if !defined(PCTSTR) && !defined(PCTSTR_DEFINED)\r\n\ttypedef const TCHAR*\t\t\tPCTSTR;\r\n\t#define PCTSTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCOLESTR) && !defined(PCOLESTR_DEFINED)\r\n\ttypedef const OLECHAR*\t\t\tPCOLESTR;\r\n\t#define PCOLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(POLESTR) && !defined(POLESTR_DEFINED)\r\n\ttypedef OLECHAR*\t\t\t\tPOLESTR;\r\n\t#define POLESTR_DEFINED\r\n#endif\r\n\r\n#if !defined(PCUSTR) && !defined(PCUSTR_DEFINED)\r\n\ttypedef const unsigned char*\tPCUSTR;\r\n\ttypedef unsigned char*\t\t\tPUSTR;\r\n\t#define PCUSTR_DEFINED\r\n#endif\r\n\r\n\r\n// SGI compiler 7.3 doesnt know these  types - oh and btw, remember to use\r\n// -LANG:std in the CXX Flags\r\n#if defined(__sgi)\r\n    typedef unsigned long           DWORD;\r\n    typedef void *                  LPCVOID;\r\n#endif\r\n\r\n\r\n// SS_USE_FACET macro and why we need it:\r\n//\r\n// Since I'm a good little Standard C++ programmer, I use locales.  Thus, I\r\n// need to make use of the use_facet<> template function here.   Unfortunately,\r\n// this need is complicated by the fact the MS' implementation of the Standard\r\n// C++ Library has a non-standard version of use_facet that takes more\r\n// arguments than the standard dictates.  Since I'm trying to write CStdString\r\n// to work with any version of the Standard library, this presents a problem.\r\n//\r\n// The upshot of this is that I can't do 'use_facet' directly.  The MS' docs\r\n// tell me that I have to use a macro, _USE() instead.  Since _USE obviously\r\n// won't be available in other implementations, this means that I have to write\r\n// my OWN macro -- SS_USE_FACET -- that evaluates either to _USE or to the\r\n// standard, use_facet.\r\n//\r\n// If you are having trouble with the SS_USE_FACET macro, in your implementation\r\n// of the Standard C++ Library, you can define your own version of SS_USE_FACET.\r\n#ifndef schMSG\r\n\t#define schSTR(x)\t   #x\r\n\t#define schSTR2(x)\tschSTR(x)\r\n\t#define schMSG(desc) message(__FILE__ \"(\" schSTR2(__LINE__) \"):\" #desc)\r\n#endif\r\n\r\n#ifndef SS_USE_FACET\r\n\t// STLPort #defines a macro (__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) for\r\n\t// all MSVC builds, erroneously in my opinion.  It causes problems for\r\n\t// my SS_ANSI builds.  In my code, I always comment out that line.  You'll\r\n\t// find it in   \\stlport\\config\\stl_msvc.h\r\n\t#if defined(__SGI_STL_PORT) && (__SGI_STL_PORT >= 0x400 )\r\n\t\t#if defined(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS) && defined(_MSC_VER)\r\n\t\t\t#ifdef SS_ANSI\r\n\t\t\t\t#pragma schMSG(__STL_NO_EXPLICIT_FUNCTION_TMPL_ARGS defined!!)\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#elif defined(_MSC_VER )\r\n\t#define SS_USE_FACET(loc, fac) std::_USE(loc, fac)\r\n\r\n\t// ...and\r\n\t#elif defined(_RWSTD_NO_TEMPLATE_ON_RETURN_TYPE)\r\n        #define SS_USE_FACET(loc, fac) std::use_facet(loc, (fac*)0)\r\n\t#else\r\n\t\t#define SS_USE_FACET(loc, fac) std::use_facet<fac >(loc)\r\n\t#endif\r\n#endif\r\n\r\n// =============================================================================\r\n// UNICODE/MBCS conversion macros.  Made to work just like the MFC/ATL ones.\r\n// =============================================================================\r\n\r\n#include <wchar.h>      // Added to Std Library with Amendment #1.\r\n\r\n// First define the conversion helper functions.  We define these regardless of\r\n// any preprocessor macro settings since their names won't collide. \r\n\r\n// Not sure if we need all these headers.   I believe ANSI says we do.\r\n\r\n#include <stdio.h>\r\n#include <stdarg.h>\r\n#include <wctype.h>\r\n#include <ctype.h>\r\n#include <stdlib.h>\r\n#ifndef va_start\r\n\t#include <varargs.h>\r\n#endif\r\n\r\n// StdCodeCvt - made to look like Win32 functions WideCharToMultiByte\r\n//\t\t\t\tand MultiByteToWideChar but uses locales in SS_ANSI\r\n//\t\t\t\tbuilds.  There are a number of overloads.\r\n//              First argument is the destination buffer.\r\n//              Second argument is the source buffer\r\n//#if defined (SS_ANSI) || !defined (SS_WIN32)\r\n\r\n// 'SSCodeCvt' - shorthand name for the codecvt facet we use\r\n\r\ntypedef std::codecvt<wchar_t, char, mbstate_t> SSCodeCvt;\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n\r\n    ASSERT(0 != pSrcA);\r\n    ASSERT(0 != pDstW);\r\n\r\n\tpDstW[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPCSTR pNextSrcA\t\t\t= pSrcA;\r\n\t\tPWSTR pNextDstW\t\t\t= pDstW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.in(st,\r\n\t\t\t\t\t\t\t\t\tpSrcA, pSrcA + nSrc, pNextSrcA,\r\n\t\t\t\t\t\t\t\t\tpDstW, pDstW + nDst, pNextDstW);\r\n\r\n\t\tASSERT(SSCodeCvt::ok == res);\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(pNextDstW >= pDstW);\r\n\t\tASSERT(pNextSrcA >= pSrcA);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstW - pDstW > nDst )\r\n\t\t\t*(pDstW + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstW = '\\0';\r\n\t}\r\n    return pDstW;\r\n}\r\ninline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCUSTR pSrcA, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, loc);\r\n}\r\n\r\ninline PSTR StdCodeCvt(PSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    ASSERT(0 != pDstA);\r\n    ASSERT(0 != pSrcW);\r\n\r\n\tpDstA[0]\t\t\t\t\t= '\\0';\t\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tPSTR pNextDstA\t\t\t= pDstA;\r\n\t\tPCWSTR pNextSrcW\t\t= pSrcW;\r\n\t\tSSCodeCvt::result res\t= SSCodeCvt::ok;\r\n\t\tconst SSCodeCvt& conv\t= SS_USE_FACET(loc, SSCodeCvt);\r\n\t\tSSCodeCvt::state_type st= { 0 };\r\n\t\tres\t\t\t\t\t\t= conv.out(st,\r\n\t\t\t\t\t\t\t\t\tpSrcW, pSrcW + nSrc, pNextSrcW,\r\n\t\t\t\t\t\t\t\t\tpDstA, pDstA + nDst, pNextDstA);\r\n\r\n\t\tASSERT(SSCodeCvt::error != res);\r\n\t\tASSERT(SSCodeCvt::ok == res);\t// strict, comment out for sanity\r\n\t\tASSERT(pNextDstA >= pDstA);\r\n\t\tASSERT(pNextSrcW >= pSrcW);\r\n\r\n\t\t// Null terminate the converted string\r\n\r\n\t\tif ( pNextDstA - pDstA > nDst )\r\n\t\t\t*(pDstA + nDst) = '\\0';\r\n\t\telse\r\n\t\t\t*pNextDstA = '\\0';\r\n\t}\r\n    return pDstA;\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDstA, int nDst, PCWSTR pSrcW, int nSrc,\r\n    const std::locale& loc=std::locale())\r\n{\r\n    return (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, loc);\r\n}\r\n/*\r\n#else   // ...or are we doing things assuming win32 and Visual C++?\r\n\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, int nDst, PCSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pSrcA);\r\n\t\tASSERT(0 != pDstW);\r\n\t\tpW[0] = '\\0';\r\n\t\tMultiByteToWideChar(acp, 0, pSrcA, nSrc, pDstW, nDst);\r\n\t\treturn pW;\r\n\t}\r\n\tinline PWSTR StdCodeCvt(PWSTR pDstW, nDst, PCUSTR pSrcA, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn StdCodeCvt(pDstW, nDst, (PCSTR)pSrcA, nSrc, acp);\r\n\t}\r\n\r\n\tinline PSTR StdCodeCvt(PSTR pDstA, nDst PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\tASSERT(0 != pDstA);\r\n\t\tASSERT(0 != pSrcW);\r\n\t\tpA[0] = '\\0';\r\n\t\tWideCharToMultiByte(acp, 0, pSrcW, nSrc, pDstA, nDst, 0, 0);\r\n\t\treturn pA;\r\n\t}\r\n\tinline PUSTR StdCodeCvt(PUSTR pDstA, nDst, PCWSTR pSrcW, int nSrc, UINT acp=CP_ACP)\r\n\t{\r\n\t\treturn (PUSTR)StdCodeCvt((PSTR)pDstA, nDst, pSrcW, nSrc, acp);\r\n\t}\r\n\r\n#endif\r\n*/\r\n\r\n// Unicode/MBCS conversion macros are only available on implementations of\r\n// the \"C\" library that have the non-standard _alloca function.  As far as I\r\n// know that's only Microsoft's though I've heard that the function exists\r\n// elsewhere.  \r\n    \r\n#if defined(SS_ALLOCA) && !defined SS_NO_CONVERSION\r\n\r\n    #include <malloc.h>\t// needed for _alloca\r\n\r\n    // Define our conversion macros to look exactly like Microsoft's to\r\n    // facilitate using this stuff both with and without MFC/ATL\r\n\r\n    #ifdef _CONVERSION_USES_THREAD_LOCALE\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=GetACP(); \\\r\n\t\t\t    _acp; PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=GetACP();\\\r\n\t\t\t     _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t\t\t_pa, _cvt, _acp)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = sslen(_pw), \\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt, _acp)))\r\n\t#else\r\n\r\n\t    #ifndef _DEBUG\r\n\t\t    #define SSCVT int _cvt; _cvt; UINT _acp=CP_ACP; _acp;\\\r\n\t\t\t     PCWSTR _pw; _pw; PCSTR _pa; _pa\r\n\t    #else\r\n\t\t    #define SSCVT int _cvt = 0; _cvt; UINT _acp=CP_ACP; \\\r\n\t\t\t    _acp; PCWSTR _pw=0; _pw; PCSTR _pa=0; _pa\r\n\t    #endif\r\n\t    #define SSA2W(pa) (\\\r\n\t\t    ((_pa = pa) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pa)),\\\r\n\t\t\t    StdCodeCvt((PWSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pa, _cvt)))\r\n\t    #define SSW2A(pw) (\\\r\n\t\t    ((_pw = pw) == 0) ? 0 : (\\\r\n\t\t\t    _cvt = (sslen(_pw)),\\\r\n\t\t\t    StdCodeCvt((LPSTR) _alloca((_cvt+1)*2), (_cvt+1)*2, \\\r\n\t\t\t\t\t_pw, _cvt)))\r\n    #endif\r\n\r\n    #define SSA2CW(pa) ((PCWSTR)SSA2W((pa)))\r\n    #define SSW2CA(pw) ((PCSTR)SSW2A((pw)))\r\n\r\n    #ifdef UNICODE\r\n\t    #define SST2A\tSSW2A\r\n\t    #define SSA2T\tSSA2W\r\n\t    #define SST2CA\tSSW2CA\r\n\t    #define SSA2CT\tSSA2CW\r\n\t\t// (Did you get a compiler error here about not being able to convert\r\n\t\t// PTSTR into PWSTR?  Then your _UNICODE and UNICODE flags are messed \r\n\t\t// up.  Best bet: #define BOTH macros before including any MS headers.)\r\n\t    inline PWSTR\tSST2W(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSW2T(PWSTR p)\t\t\t{ return p; }\r\n\t    inline PCWSTR\tSST2CW(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSW2CT(PCWSTR p)\t\t{ return p; }\r\n    #else\r\n\t    #define SST2W\tSSA2W\r\n\t    #define SSW2T\tSSW2A\r\n\t    #define SST2CW\tSSA2CW\r\n\t    #define SSW2CT\tSSW2CA\r\n\t    inline PSTR\t\tSST2A(PTSTR p)\t\t\t{ return p; }\r\n\t    inline PTSTR\tSSA2T(PSTR p)\t\t\t{ return p; }\r\n\t    inline PCSTR\tSST2CA(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSA2CT(PCSTR p)\t\t\t{ return p; }\r\n    #endif // #ifdef UNICODE\r\n\r\n    #if defined(UNICODE)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #elif defined(OLE2ANSI)\r\n    // in these cases the default (TCHAR) is the same as OLECHAR\r\n\t    inline PCOLESTR\tSST2COLE(PCTSTR p)\t\t{ return p; }\r\n\t    inline PCTSTR\tSSOLE2CT(PCOLESTR p)\t{ return p; }\r\n\t    inline POLESTR\tSST2OLE(PTSTR p)\t\t{ return p; }\r\n\t    inline PTSTR\tSSOLE2T(POLESTR p)\t\t{ return p; }\r\n    #else\r\n\t    //CharNextW doesn't work on Win95 so we use this\r\n\t    #define SST2COLE(pa)\tSSA2CW((pa))\r\n\t    #define SST2OLE(pa)\t\tSSA2W((pa))\r\n\t    #define SSOLE2CT(po)\tSSW2CA((po))\r\n\t    #define SSOLE2T(po)\t\tSSW2A((po))\r\n    #endif\r\n\r\n    #ifdef OLE2ANSI\r\n\t    #define SSW2OLE\t\tSSW2A\r\n\t    #define SSOLE2W\t\tSSA2W\r\n\t    #define SSW2COLE\tSSW2CA\r\n\t    #define SSOLE2CW\tSSA2CW\r\n\t    inline POLESTR\t\tSSA2OLE(PSTR p)\t\t{ return p; }\r\n\t    inline PSTR\t\t\tSSOLE2A(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSA2COLE(PCSTR p)\t{ return p; }\r\n\t    inline PCSTR\t\tSSOLE2CA(PCOLESTR p){ return p; }\r\n    #else\r\n\t    #define SSA2OLE\t\tSSA2W\r\n\t    #define SSOLE2A\t\tSSW2A\r\n\t    #define SSA2COLE\tSSA2CW\r\n\t    #define SSOLE2CA\tSSW2CA\r\n\t    inline POLESTR\t\tSSW2OLE(PWSTR p)\t{ return p; }\r\n\t    inline PWSTR\t\tSSOLE2W(POLESTR p)\t{ return p; }\r\n\t    inline PCOLESTR\t\tSSW2COLE(PCWSTR p)\t{ return p; }\r\n\t    inline PCWSTR\t\tSSOLE2CW(PCOLESTR p){ return p; }\r\n    #endif\r\n\r\n    // Above we've defined macros that look like MS' but all have\r\n    // an 'SS' prefix.  Now we need the real macros.  We'll either\r\n    // get them from the macros above or from MFC/ATL. \r\n\r\n\t#if defined (USES_CONVERSION)\r\n\r\n\t\t#define _NO_STDCONVERSION\t// just to be consistent\r\n\r\n\t#else\r\n\r\n\t\t#ifdef _MFC_VER\r\n\r\n\t\t\t#include <afxconv.h>\r\n\t\t\t#define _NO_STDCONVERSION // just to be consistent\r\n\r\n\t\t#else\r\n\r\n\t\t\t#define USES_CONVERSION SSCVT\r\n\t\t\t#define A2CW\t\t\tSSA2CW\r\n\t\t\t#define W2CA\t\t\tSSW2CA\r\n\t\t\t#define T2A\t\t\t\tSST2A\r\n\t\t\t#define A2T\t\t\t\tSSA2T\r\n\t\t\t#define T2W\t\t\t\tSST2W\r\n\t\t\t#define W2T\t\t\t\tSSW2T\r\n\t\t\t#define T2CA\t\t\tSST2CA\r\n\t\t\t#define A2CT\t\t\tSSA2CT\r\n\t\t\t#define T2CW\t\t\tSST2CW\r\n\t\t\t#define W2CT\t\t\tSSW2CT\r\n\t\t\t#define ocslen\t\t\tsslen\r\n\t\t\t#define ocscpy\t\t\tsscpy\r\n\t\t\t#define T2COLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2CT\t\t\tSSOLE2CT\r\n\t\t\t#define T2OLE\t\t\tSST2COLE\r\n\t\t\t#define OLE2T\t\t\tSSOLE2CT\r\n\t\t\t#define A2OLE\t\t\tSSA2OLE\r\n\t\t\t#define OLE2A\t\t\tSSOLE2A\r\n\t\t\t#define W2OLE\t\t\tSSW2OLE\r\n\t\t\t#define OLE2W\t\t\tSSOLE2W\r\n\t\t\t#define A2COLE\t\t\tSSA2COLE\r\n\t\t\t#define OLE2CA\t\t\tSSOLE2CA\r\n\t\t\t#define W2COLE\t\t\tSSW2COLE\r\n\t\t\t#define OLE2CW\t\t\tSSOLE2CW\r\n\t\r\n\t\t#endif // #ifdef _MFC_VER\r\n\t#endif // #ifndef USES_CONVERSION\r\n#endif // #ifndef SS_NO_CONVERSION\r\n\r\n// Define ostring - generic name for std::basic_string<OLECHAR>\r\n\r\n#if !defined(ostring) && !defined(OSTRING_DEFINED)\r\n\ttypedef std::basic_string<OLECHAR> ostring;\r\n\t#define OSTRING_DEFINED\r\n#endif\r\n\r\n// StdCodeCvt when there's no conversion to be done\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<char>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<char>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\ninline PSTR StdCodeCvt(PSTR pDst, int nDst, PCUSTR pSrc, int nSrc)\r\n{\r\n\treturn StdCodeCvt(pDst, nDst, (PCSTR)pSrc, nSrc);\r\n}\r\ninline PUSTR StdCodeCvt(PUSTR pDst, int nDst, PCSTR pSrc, int nSrc)\r\n{\r\n\treturn (PUSTR)StdCodeCvt((PSTR)pDst, nDst, pSrc, nSrc);\r\n}\r\n\r\ninline PWSTR StdCodeCvt(PWSTR pDst, int nDst, PCWSTR pSrc, int nSrc)\r\n{\r\n\tint nChars = SSMIN(nSrc, nDst);\r\n\r\n\tif ( nChars > 0 )\r\n\t{\r\n\t\tpDst[0]\t\t\t\t= '\\0';\r\n\t\tstd::basic_string<wchar_t>::traits_type::copy(pDst, pSrc, nChars);\r\n//\t\tstd::char_traits<wchar_t>::copy(pDst, pSrc, nChars);\r\n\t\tpDst[nChars]\t= '\\0';\r\n\t}\r\n\r\n\treturn pDst;\r\n}\r\n\r\n\r\n// Define tstring -- generic name for std::basic_string<TCHAR>\r\n\r\n#if !defined(tstring) && !defined(TSTRING_DEFINED)\r\n\ttypedef std::basic_string<TCHAR> tstring;\r\n\t#define TSTRING_DEFINED\r\n#endif\r\n\r\n// a very shorthand way of applying the fix for KB problem Q172398\r\n// (basic_string assignment bug)\r\n\r\n#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t#define Q172398(x) (x).erase()\r\n#else\r\n\t#define Q172398(x)\r\n#endif\r\n\r\n// =============================================================================\r\n// INLINE FUNCTIONS ON WHICH CSTDSTRING RELIES\r\n//\r\n// Usually for generic text mapping, we rely on preprocessor macro definitions\r\n// to map to string functions.  However the CStdStr<> template cannot use\r\n// macro-based generic text mappings because its character types do not get\r\n// resolved until template processing which comes AFTER macro processing.  In\r\n// other words, the preprocessor macro UNICODE is of little help to us in the\r\n// CStdStr template\r\n//\r\n// Therefore, to keep the CStdStr declaration simple, we have these inline\r\n// functions.  The template calls them often.  Since they are inline (and NOT\r\n// exported when this is built as a DLL), they will probably be resolved away\r\n// to nothing. \r\n//\r\n// Without these functions, the CStdStr<> template would probably have to broken\r\n// out into two, almost identical classes.  Either that or it would be a huge,\r\n// convoluted mess, with tons of \"if\" statements all over the place checking the\r\n// size of template parameter CT.\r\n// \r\n// In several cases, you will see two versions of each function.  One version is\r\n// the more portable, standard way of doing things, while the other is the\r\n// non-standard, but often significantly faster Visual C++ way.\r\n// =============================================================================\r\n\r\n// If they defined SS_NO_REFCOUNT, then we must convert all assignments\r\n\r\n#ifdef SS_NO_REFCOUNT\r\n\t#define SSREF(x) (x).c_str()\r\n#else\r\n\t#define SSREF(x) (x)\r\n#endif\r\n\r\n// -----------------------------------------------------------------------------\r\n// sslen: strlen/wcslen wrappers\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT> inline int sslen(const CT* pT)\r\n{\r\n\treturn 0 == pT ? 0 : (int)std::basic_string<CT>::traits_type::length(pT);\r\n//\treturn 0 == pT ? 0 : std::char_traits<CT>::length(pT);\r\n}\r\ninline SS_NOTHROW int sslen(const std::string& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\ninline SS_NOTHROW int sslen(const std::wstring& s)\r\n{\r\n\treturn static_cast<int>(s.length());\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// sstolower/sstoupper -- convert characters to upper/lower case\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline CT sstolower(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::tolower<CT>(t, loc);\r\n}\r\ntemplate<typename CT>\r\ninline CT sstoupper(const CT& t, const std::locale& loc = std::locale())\r\n{\r\n\treturn std::toupper<CT>(t, loc);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssasn: assignment functions -- assign \"sSrc\" to \"sDst\"\r\n// -----------------------------------------------------------------------------\r\ntypedef std::string::size_type\t\tSS_SIZETYPE; // just for shorthand, really\r\ntypedef std::string::pointer\t\tSS_PTRTYPE;  \r\ntypedef std::wstring::size_type\t\tSW_SIZETYPE;\r\ntypedef std::wstring::pointer\t\tSW_PTRTYPE;  \r\n\r\ninline void\tssasn(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCSTR pA)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pA )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pA actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pA >= sDst.c_str() && pA <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst =sDst.substr(static_cast<SS_SIZETYPE>(pA-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pA);\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sSrc.size());\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), static_cast<int>(sSrc.size()));\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tszCvt;\r\n\t\tsDst.resize(sSrc.size());\r\n#endif\r\n\t}\r\n}\r\ninline void\tssasn(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nSrc\t= sslen(pW);\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnDst\t= static_cast<int>(static_cast<double>(nDst) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tpW, nSrc);\r\n\r\n\t\t// In MBCS builds, we don't know how long the destination string will be.\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n}\r\ninline void ssasn(std::string& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(\"\");\r\n}\t\r\ninline void\tssasn(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tif ( sDst.c_str() != sSrc.c_str() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t\tsDst.assign(SSREF(sSrc));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\t// Watch out for NULLs, as always.\r\n\r\n\tif ( 0 == pW )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\r\n\t// If pW actually points to part of sDst, we must NOT erase(), but\r\n\t// rather take a substring\r\n\r\n\telse if ( pW >= sDst.c_str() && pW <= sDst.c_str() + sDst.size() )\r\n\t{\r\n\t\tsDst = sDst.substr(static_cast<SW_SIZETYPE>(pW-sDst.c_str()));\r\n\t}\r\n\r\n\t// Otherwise (most cases) apply the assignment bug fix, if applicable\r\n\t// and do the assignment\r\n\r\n\telse\r\n\t{\r\n\t\tQ172398(sDst);\r\n\t\tsDst.assign(pW);\r\n\t}\r\n}\r\n#undef StrSizeType\r\ninline void\tssasn(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( sSrc.empty() )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= nSrc;\r\n\r\n\t\tsDst.resize(nSrc+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst,\r\n\t\t\tsSrc.c_str(), nSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void\tssasn(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t= sslen(pA);\r\n\r\n\tif ( 0 == nSrc )\r\n\t{\r\n\t\tsDst.erase();\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint nDst\t= nSrc;\r\n\t\tsDst.resize(nDst+1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()), nDst, pA,\r\n\t\t\tnSrc);\r\n\r\n\t\tsDst.resize(sslen(szCvt));\r\n\t}\r\n}\r\ninline void ssasn(std::wstring& sDst, const int nNull)\r\n{\r\n\tUNUSED(nNull);\r\n\tASSERT(nNull==0);\r\n\tsDst.assign(L\"\");\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssadd: string object concatenation -- add second argument to first\r\n// -----------------------------------------------------------------------------\r\ninline void\tssadd(std::string& sDst, const std::wstring& sSrc)\r\n{\r\n\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n\t\t// In MBCS builds, pad the buffer to account for the possibility of\r\n\t\t// some 3 byte characters.  Not perfect but should get most cases.\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst+nAdd+1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, sSrc.c_str(), nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nAdd);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, const std::string& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::string& sDst, PCWSTR pW)\r\n{\r\n\tint nSrc\t\t= sslen(pW);\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\t\tint nAdd\t= nSrc;\r\n\r\n#ifdef SS_MBCS\r\n\t\tnAdd\t= static_cast<int>(static_cast<double>(nAdd) * 1.3);\r\n#endif\r\n\r\n\t\tsDst.resize(nDst + nAdd + 1);\r\n\t\tPCSTR szCvt = StdCodeCvt(const_cast<SS_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnAdd, pW, nSrc);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::string& sDst, PCSTR pA)\r\n{\r\n\tif ( pA )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pA >= sDst.c_str() && pA <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pA) )\r\n\t\t\t\tsDst.append(std::string(pA));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pA);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pA); \r\n\t\t}\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::wstring& sSrc)\r\n{\r\n\tsDst += sSrc;\r\n}\r\ninline void\tssadd(std::wstring& sDst, const std::string& sSrc)\r\n{\r\n\tif ( !sSrc.empty() )\r\n\t{\r\n\t\tint nSrc\t= static_cast<int>(sSrc.size());\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst), \r\n\t\t\tnSrc, sSrc.c_str(), nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCSTR pA)\r\n{\r\n\tint nSrc\t\t= sslen(pA);\r\n\r\n\tif ( nSrc > 0 )\r\n\t{\r\n\t\tint nDst\t= static_cast<int>(sDst.size());\r\n\r\n\t\tsDst.resize(nDst + nSrc + 1);\r\n\t\tPCWSTR szCvt = StdCodeCvt(const_cast<SW_PTRTYPE>(sDst.data()+nDst),\r\n\t\t\tnSrc, pA, nSrc+1);\r\n\r\n#ifdef SS_MBCS\r\n\t\tsDst.resize(nDst + sslen(szCvt));\r\n#else\r\n\t\tsDst.resize(nDst + nSrc);\r\n\t\tszCvt;\r\n#endif\r\n\t}\r\n}\r\ninline void\tssadd(std::wstring& sDst, PCWSTR pW)\r\n{\r\n\tif ( pW )\r\n\t{\r\n\t\t// If the string being added is our internal string or a part of our\r\n\t\t// internal string, then we must NOT do any reallocation without\r\n\t\t// first copying that string to another object (since we're using a\r\n\t\t// direct pointer)\r\n\r\n\t\tif ( pW >= sDst.c_str() && pW <= sDst.c_str()+sDst.length())\r\n\t\t{\r\n\t\t\tif ( sDst.capacity() <= sDst.size()+sslen(pW) )\r\n\t\t\t\tsDst.append(std::wstring(pW));\r\n\t\t\telse\r\n\t\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tsDst.append(pW);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscmp: comparison (case sensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int sscmp(const CT* pA1, const CT* pA2)\r\n{\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = *(pA1++);\r\n\t    l = *(pA2++);\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssicmp: comparison (case INsensitive, not affected by locale)\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT>\r\ninline int ssicmp(const CT* pA1, const CT* pA2)\r\n{\r\n\t// Using the \"C\" locale = \"not affected by locale\"\r\n\r\n\tstd::locale loc = std::locale::classic();\r\n    const std::ctype<CT>& ct = SS_USE_FACET(loc, std::ctype<CT>);\r\n    CT f;\r\n    CT l;\r\n\r\n    do \r\n    {\r\n\t    f = ct.tolower(*(pA1++));\r\n\t    l = ct.tolower(*(pA2++));\r\n    } while ( (f) && (f == l) );\r\n\r\n    return (int)(f - l);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssupr/sslwr: Uppercase/Lowercase conversion functions\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\ninline void sslwr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).tolower(pT, pT+nLen);\r\n}\r\ntemplate<typename CT>\r\ninline void ssupr(CT* pT, size_t nLen, const std::locale& loc=std::locale())\r\n{\r\n\tSS_USE_FACET(loc, std::ctype<CT>).toupper(pT, pT+nLen);\r\n}\r\n\r\n// -----------------------------------------------------------------------------\r\n//  vsprintf/vswprintf or _vsnprintf/_vsnwprintf equivalents.  In standard\r\n//  builds we can't use _vsnprintf/_vsnwsprintf because they're MS extensions.\r\n// -----------------------------------------------------------------------------\r\n#if defined(SS_ANSI) || !defined(_MSC_VER)\r\n\r\n    // Borland's headers put some ANSI \"C\" functions in the 'std' namespace. \r\n    // Promote them to the global namespace so we can use them here.\r\n\r\n    #if defined(__BORLANDC__)\r\n        using std::vsprintf;\r\n        using std::vswprintf;\r\n    #endif\r\n\r\n\tinline int ssvsprintf(PSTR pA, size_t /*nCount*/, PCSTR pFmtA, va_list vl)\r\n\t{\r\n\t\treturn vsprintf(pA, pFmtA, vl);\r\n\t}\r\n\tinline int ssvsprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\t// JMO: Some distributions of the \"C\" have a version of vswprintf that\r\n        // takes 3 arguments (e.g. Microsoft, Borland, GNU).  Others have a \r\n        // version which takes 4 arguments (an extra \"count\" argument in the\r\n        // second position.  The best stab I can take at this so far is that if\r\n        // you are NOT running with MS, Borland, or GNU, then I'll assume you\r\n        // have the version that takes 4 arguments.\r\n        //\r\n        // I'm sure that these checks don't catch every platform correctly so if\r\n        // you get compiler errors on one of the lines immediately below, it's\r\n        // probably because your implemntation takes a different number of\r\n        // arguments.  You can comment out the offending line (and use the\r\n        // alternate version) or you can figure out what compiler flag to check\r\n        // and add that preprocessor check in.  Regardless, if you get an error\r\n        // on these lines, I'd sure like to hear from you about it.\r\n        //\r\n        // Thanks to Ronny Schulz for the SGI-specific checks here.\r\n\r\n//\t#if !defined(__MWERKS__) && !defined(__SUNPRO_CC_COMPAT) && !defined(__SUNPRO_CC)\r\n    #if    !defined(_MSC_VER) \\\r\n        && !defined (__BORLANDC__) \\\r\n        && !defined(__GNUC__) \\\r\n        && !defined(__sgi)\r\n\r\n        return vswprintf(pW, nCount, pFmtW, vl);\r\n\r\n    // suddenly with the current SGI 7.3 compiler there is no such function as\r\n    // vswprintf and the substitute needs explicit casts to compile\r\n\r\n    #elif defined(__sgi)\r\n\r\n        nCount;\r\n        return vsprintf( (char *)pW, (char *)pFmtW, vl);\r\n\r\n    #else\r\n\r\n        nCount;\r\n        return vswprintf(pW, pFmtW, vl);\r\n\r\n    #endif\r\n\r\n\t}\r\n#else\r\n\tinline int\tssnprintf(PSTR pA, size_t nCount, PCSTR pFmtA, va_list vl)\r\n\t{ \r\n\t\treturn _vsnprintf(pA, nCount, pFmtA, vl);\r\n\t}\r\n\tinline int\tssnprintf(PWSTR pW, size_t nCount, PCWSTR pFmtW, va_list vl)\r\n\t{\r\n\t\treturn _vsnwprintf(pW, nCount, pFmtW, vl);\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssload: Type safe, overloaded ::LoadString wrappers\r\n// There is no equivalent of these in non-Win32-specific builds.  However, I'm\r\n// thinking that with the message facet, there might eventually be one\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline int ssload(HMODULE hInst, UINT uId, PSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringA(hInst, uId, pBuf, nMax);\r\n\t}\r\n\tinline int ssload(HMODULE hInst, UINT uId, PWSTR pBuf, int nMax)\r\n\t{\r\n\t\treturn ::LoadStringW(hInst, uId, pBuf, nMax);\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// sscoll/ssicoll: Collation wrappers\r\n//\t\tNote -- with MSVC I have reversed the arguments order here because the\r\n//\t\tfunctions appear to return the opposite of what they should\r\n// -----------------------------------------------------------------------------\r\ntemplate <typename CT>\r\ninline int sscoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::collate<CT>& coll =\r\n\t\tSS_USE_FACET(std::locale(), std::collate<CT>);\r\n\r\n\treturn coll.compare(sz2, sz2+nLen2, sz1, sz1+nLen1);\r\n}\r\ntemplate <typename CT>\r\ninline int ssicoll(const CT* sz1, int nLen1, const CT* sz2, int nLen2)\r\n{\r\n\tconst std::locale loc;\r\n\tconst std::collate<CT>& coll = SS_USE_FACET(loc, std::collate<CT>);\r\n\r\n\t// Some implementations seem to have trouble using the collate<>\r\n\t// facet typedefs so we'll just default to basic_string and hope\r\n\t// that's what the collate facet uses (which it generally should)\r\n\r\n//\tstd::collate<CT>::string_type s1(sz1);\r\n//\tstd::collate<CT>::string_type s2(sz2);\r\n\tconst std::basic_string<CT> sEmpty;\r\n    std::basic_string<CT> s1(sz1 ? sz1 : sEmpty.c_str());\r\n    std::basic_string<CT> s2(sz2 ? sz2 : sEmpty.c_str());\r\n\r\n\tsslwr(const_cast<CT*>(s1.c_str()), nLen1, loc);\r\n\tsslwr(const_cast<CT*>(s2.c_str()), nLen2, loc);\r\n\treturn coll.compare(s2.c_str(), s2.c_str()+nLen2,\r\n\t\t\t\t\t\ts1.c_str(), s1.c_str()+nLen1);\r\n}\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// ssfmtmsg: FormatMessage equivalents.  Needed because I added a CString facade\r\n// Again -- no equivalent of these on non-Win32 builds but their might one day\r\n// be one if the message facet gets implemented\r\n// -----------------------------------------------------------------------------\r\n#if defined (SS_WIN32) && !defined(SS_ANSI)\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{ \r\n\t\treturn FormatMessageA(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n\tinline DWORD ssfmtmsg(DWORD dwFlags, LPCVOID pSrc, DWORD dwMsgId,\r\n\t\t\t\t\t\t  DWORD dwLangId, PWSTR pBuf, DWORD nSize,\r\n\t\t\t\t\t\t  va_list* vlArgs)\r\n\t{\r\n\t\treturn FormatMessageW(dwFlags, pSrc, dwMsgId, dwLangId,\r\n\t\t\t\t\t\t\t  pBuf, nSize,vlArgs);\r\n\t}\r\n#else\r\n#endif\r\n \r\n\r\n\r\n// FUNCTION: sscpy.  Copies up to 'nMax' characters from pSrc to pDst.\r\n// -----------------------------------------------------------------------------\r\n// FUNCTION:  sscpy\r\n//\t\tinline int sscpy(PSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PUSTR pDst,  PCSTR pSrc, int nMax=-1)\r\n//\t\tinline int sscpy(PSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCWSTR pSrc, int nMax=-1);\r\n//\t\tinline int sscpy(PWSTR pDst, PCSTR pSrc, int nMax=-1);\r\n//\r\n// DESCRIPTION:\r\n//\t\tThis function is very much (but not exactly) like strcpy.  These\r\n//\t\toverloads simplify copying one C-style string into another by allowing\r\n//\t\tthe caller to specify two different types of strings if necessary.\r\n//\r\n//\t\tThe strings must NOT overlap\r\n//\r\n//\t\t\"Character\" is expressed in terms of the destination string, not\r\n//\t\tthe source.  If no 'nMax' argument is supplied, then the number of\r\n//\t\tcharacters copied will be sslen(pSrc).  A NULL terminator will\r\n//\t\talso be added so pDst must actually be big enough to hold nMax+1\r\n//\t\tcharacters.  The return value is the number of characters copied,\r\n//\t\tnot including the NULL terminator.\r\n//\r\n// PARAMETERS: \r\n//\t\tpSrc - the string to be copied FROM.  May be a char based string, an\r\n//\t\t\t   MBCS string (in Win32 builds) or a wide string (wchar_t).\r\n//\t\tpSrc - the string to be copied TO.  Also may be either MBCS or wide\r\n//\t\tnMax - the maximum number of characters to be copied into szDest.  Note\r\n//\t\t\t   that this is expressed in whatever a \"character\" means to pDst.\r\n//\t\t\t   If pDst is a wchar_t type string than this will be the maximum\r\n//\t\t\t   number of wchar_ts that my be copied.  The pDst string must be\r\n//\t\t\t   large enough to hold least nMaxChars+1 characters.\r\n//\t\t\t   If the caller supplies no argument for nMax this is a signal to\r\n//\t\t\t   the routine to copy all the characters in pSrc, regardless of\r\n//\t\t\t   how long it is.\r\n//\r\n// RETURN VALUE: none\r\n// -----------------------------------------------------------------------------\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpycvt(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\t\r\n\tint nSrc = sslen(pSrc);\r\n\r\n\tconst CT1* szCvt = StdCodeCvt(pDst, nMax, pSrc, nSrc);\r\n\r\n\t// If we're copying the same size characters, then all the \"code convert\"\r\n\t// just did was basically memcpy so the #of characters copied is the same\r\n\t// as the number requested.  I should probably specialize this function\r\n\t// template to achieve this purpose as it is silly to do a runtime check\r\n\t// of a fact known at compile time.  I'll get around to it.\r\n\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ninline int sscpycvt(PSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<char>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst =  '\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCWSTR pSrc, int nMax)\r\n{\r\n\tint nCount = nMax;\r\n\tfor (; nCount > 0 && *pSrc; ++pSrc, ++pDst, --nCount)\r\n\t\tstd::basic_string<wchar_t>::traits_type::assign(*pDst, *pSrc);\r\n\r\n\t*pDst = L'\\0';\r\n\treturn nMax - nCount;\r\n}\r\ninline int sscpycvt(PWSTR pDst, PCSTR pSrc, int nMax)\r\n{\r\n\t// Note -- we assume pDst is big enough to hold pSrc.  If not, we're in\r\n\t// big trouble.  No bounds checking.  Caveat emptor.\r\n\r\n\tconst PWSTR szCvt = StdCodeCvt(pDst, nMax, pSrc, nMax);\r\n\treturn sslen(szCvt);\r\n}\r\n\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax, int nLen)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, nLen));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, SSMIN(nMax, sslen(pSrc)));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const CT2* pSrc)\r\n{\r\n\treturn sscpycvt(pDst, pSrc, sslen(pSrc));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc, int nMax)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), SSMIN(nMax, (int)sSrc.length()));\r\n}\r\ntemplate<typename CT1, typename CT2>\r\ninline int sscpy(CT1* pDst, const std::basic_string<CT2>& sSrc)\r\n{\r\n\treturn sscpycvt(pDst, sSrc.c_str(), (int)sSrc.length());\r\n}\r\n\r\n#ifdef SS_INC_COMDEF\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs, int nMax)\r\n\t{\r\n\t\treturn sscpycvt(pDst, static_cast<PCOLESTR>(bs),\r\n            SSMIN(nMax, static_cast<int>(bs.length())));\r\n\t}\r\n\ttemplate<typename CT1>\r\n\tinline int sscpy(CT1* pDst, const _bstr_t& bs)\r\n\t{\r\n\t\treturn sscpy(pDst, bs, static_cast<int>(bs.length()));\r\n\t}\r\n#endif\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// Functional objects for changing case.  They also let you pass locales\r\n// -----------------------------------------------------------------------------\r\n\r\ntemplate<typename CT>\r\nstruct SSToUpper : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstoupper<CT>(t, loc);\r\n    }\r\n};\r\ntemplate<typename CT>\r\nstruct SSToLower : public std::binary_function<CT, std::locale, CT>\r\n{\r\n    inline CT operator()(const CT& t, const std::locale& loc) const\r\n    {\r\n\t    return sstolower<CT>(t, loc);\r\n    }\r\n};\r\n\r\n// This struct is used for TrimRight() and TrimLeft() function implementations.\r\n//template<typename CT>\r\n//struct NotSpace : public std::unary_function<CT, bool>\r\n//{\r\n//\tconst std::locale& loc;\r\n//\tinline NotSpace(const std::locale& locArg) : loc(locArg) {}\r\n//\tinline bool operator() (CT t) { return !std::isspace(t, loc); }\r\n//};\r\ntemplate<typename CT>\r\nstruct NotSpace : public std::unary_function<CT, bool>\r\n{\r\n\r\n\t// DINKUMWARE BUG:\r\n\t// Note -- using std::isspace in a COM DLL gives us access violations\r\n\t// because it causes the dynamic addition of a function to be called\r\n\t// when the library shuts down.  Unfortunately the list is maintained\r\n\t// in DLL memory but the function is in static memory.  So the COM DLL\r\n\t// goes away along with the function that was supposed to be called,\r\n\t// and then later when the DLL CRT shuts down it unloads the list and\r\n\t// tries to call the long-gone function.\r\n\t// This is DinkumWare's implementation problem.  If you encounter this\r\n\t// problem, you may replace the calls here with good old isspace() and\r\n\t// iswspace() from the CRT unless they specify SS_ANSI\r\n    \r\n\tconst std::locale loc;\r\n\tNotSpace(const std::locale& locArg=std::locale()) : loc(locArg) {}\r\n\tbool operator() (CT t) const { return !std::isspace(t, loc); }\r\n};\r\n\r\n\r\n\r\n\r\n//\t\t\tNow we can define the template (finally!)\r\n// =============================================================================\r\n// TEMPLATE: CStdStr\r\n//\t\ttemplate<typename CT> class CStdStr : public std::basic_string<CT>\r\n//\r\n// REMARKS:\r\n//\t\tThis template derives from basic_string<CT> and adds some MFC CString-\r\n//\t\tlike functionality\r\n//\r\n//\t\tBasically, this is my attempt to make Standard C++ library strings as\r\n//\t\teasy to use as the MFC CString class.\r\n//\r\n//\t\tNote that although this is a template, it makes the assumption that the\r\n//\t\ttemplate argument (CT, the character type) is either char or wchar_t.  \r\n// =============================================================================\r\n\r\n//#define CStdStr _SS\t// avoid compiler warning 4786\r\n\r\n//    template<typename ARG> ARG& FmtArg(ARG& arg)  { return arg; }\r\n//    PCSTR  FmtArg(const std::string& arg)  { return arg.c_str(); }\r\n//    PCWSTR FmtArg(const std::wstring& arg) { return arg.c_str(); }\r\n\r\ntemplate<typename ARG>\r\nstruct FmtArg\r\n{\r\n    explicit FmtArg(const ARG& arg) : a_(arg) {}\r\n    const ARG& operator()() const { return a_; }\r\n    const ARG& a_;\r\nprivate:\r\n    FmtArg& operator=(const FmtArg&) { return *this; }\r\n};\r\n\r\ntemplate<typename CT>\r\nclass CStdStr : public std::basic_string<CT>\r\n{\r\n\t// Typedefs for shorter names.  Using these names also appears to help\r\n\t// us avoid some ambiguities that otherwise arise on some platforms\r\n\r\n\t#define MYBASE std::basic_string<CT>\t\t\t\t // my base class\r\n\t//typedef typename std::basic_string<CT>\t\tMYBASE;\t // my base class\r\n\ttypedef CStdStr<CT>\t\t\t\t\t\t\tMYTYPE;\t // myself\r\n\ttypedef typename MYBASE::const_pointer\t\tPCMYSTR; // PCSTR or PCWSTR \r\n\ttypedef typename MYBASE::pointer\t\t\tPMYSTR;\t // PSTR or PWSTR\r\n\ttypedef typename MYBASE::iterator\t\t\tMYITER;  // my iterator type\r\n\ttypedef typename MYBASE::const_iterator\t\tMYCITER; // you get the idea...\r\n\ttypedef typename MYBASE::reverse_iterator\tMYRITER;\r\n\ttypedef typename MYBASE::size_type\t\t\tMYSIZE;   \r\n\ttypedef typename MYBASE::value_type\t\t\tMYVAL; \r\n\ttypedef typename MYBASE::allocator_type\t\tMYALLOC;\r\n\t\r\npublic:\r\n\t// shorthand conversion from PCTSTR to string resource ID\r\n\t#define SSRES(pctstr)  LOWORD(reinterpret_cast<unsigned long>(pctstr))\t\r\n\r\n\tbool TryLoad(const void* pT)\r\n\t{\r\n\t\tbool bLoaded = false;\r\n\r\n#if defined(SS_WIN32) && !defined(SS_ANSI)\r\n\t\tif ( ( pT != NULL ) && SS_IS_INTRESOURCE(pT) )\r\n\t\t{\r\n\t\t\tUINT nId = LOWORD(reinterpret_cast<unsigned long>(pT));\r\n\t\t\tif ( !LoadString(nId) )\r\n\t\t\t{\r\n\t\t\t\tTRACE(_T(\"Can't load string %u\\n\"), SSRES(pT));\r\n\t\t\t}\r\n\t\t\tbLoaded = true;\r\n\t\t}\r\n#endif\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n\r\n\t// CStdStr inline constructors\r\n\tCStdStr()\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const MYTYPE& str) : MYBASE(SSREF(str))\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, SSREF(str));\r\n\t}\r\n\r\n\tCStdStr(PCMYSTR pT, MYSIZE n) : MYBASE(pT, n)\r\n\t{\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tCStdStr(PCUSTR pU)\r\n\t{\r\n\t\t*this = reinterpret_cast<PCSTR>(pU);\r\n\t}\r\n#endif\r\n\r\n\tCStdStr(PCSTR pA)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pA;\r\n\t#else\r\n\t\tif ( !TryLoad(pA) )\r\n\t\t\t*this = pA;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(PCWSTR pW)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\t\t*this = pW;\r\n\t#else\r\n\t\tif ( !TryLoad(pW) )\r\n\t\t\t*this = pW;\r\n\t#endif\r\n\t}\r\n\r\n\tCStdStr(MYCITER first, MYCITER last)\r\n\t\t: MYBASE(first, last)\r\n\t{\r\n\t}\r\n\r\n\tCStdStr(MYSIZE nSize, MYVAL ch, const MYALLOC& al=MYALLOC())\r\n\t\t: MYBASE(nSize, ch, al)\r\n\t{\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tCStdStr(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t\tthis->append(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t}\r\n\t#endif\r\n\r\n\t// CStdStr inline assignment operators -- the ssasn function now takes care\r\n\t// of fixing  the MSVC assignment bug (see knowledge base article Q172398).\r\n\tMYTYPE& operator=(const MYTYPE& str)\r\n\t{ \r\n\t\tssasn(*this, str); \r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::string& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(const std::wstring& str)\r\n\t{\r\n\t\tssasn(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCSTR pA)\r\n\t{\r\n\t\tssasn(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator=(PCWSTR pW)\r\n\t{\r\n\t\tssasn(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n#ifdef SS_UNSIGNED\r\n\tMYTYPE& operator=(PCUSTR pU)\r\n\t{\r\n\t\tssasn(*this, reinterpret_cast<PCSTR>(pU));\r\n\t\treturn *this;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE& operator=(CT t)\r\n\t{\r\n\t\tQ172398(*this);\r\n\t\tthis->assign(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t#ifdef SS_INC_COMDEF\r\n\t\tMYTYPE& operator=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\tif ( bstr.length() > 0 )\r\n\t\t\t{\r\n\t\t\t\tthis->assign(static_cast<PCMYSTR>(bstr), bstr.length());\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t\treturn *this;\r\n\t\t\t}\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// Overloads  also needed to fix the MSVC assignment bug (KB: Q172398)\r\n\t//  *** Thanks to Pete The Plumber for catching this one ***\r\n\t// They also are compiled if you have explicitly turned off refcounting\r\n\t#if ( defined(_MSC_VER) && ( _MSC_VER < 1200 ) ) || defined(SS_NO_REFCOUNT) \r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tsscpy(GetBuffer(str.size()+1), SSREF(str));\r\n\t\t\tthis->ReleaseBuffer(str.size());\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYTYPE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value.  Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\t\t\tMYTYPE strTemp(str.c_str()+nStart, nChars);\r\n\t\t\tQ172398(*this);\r\n\t\t\tthis->assign(strTemp);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str)\r\n\t\t{\r\n\t\t\tssasn(*this, str);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const MYBASE& str, MYSIZE nStart, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// This overload of basic_string::assign is supposed to assign up to\r\n\t\t\t// <nChars> or the NULL terminator, whichever comes first.  Since we\r\n\t\t\t// are about to call a less forgiving overload (in which <nChars>\r\n\t\t\t// must be a valid length), we must adjust the length here to a safe\r\n\t\t\t// value. Thanks to Ullrich Pollhne for catching this bug\r\n\r\n\t\t\tnChars\t\t= SSMIN(nChars, str.length() - nStart);\r\n\r\n\t\t\t// Watch out for assignment to self\r\n\r\n\t\t\tif ( this == &str )\r\n\t\t\t{\r\n\t\t\t\tMYTYPE strTemp(str.c_str() + nStart, nChars);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(strTemp);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tQ172398(*this);\r\n\t\t\t\tstatic_cast<MYBASE*>(this)->assign(str.c_str()+nStart, nChars);\r\n\t\t\t}\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pC, MYSIZE nChars)\r\n\t\t{\r\n\t\t\t// Q172398 only fix -- erase before assigning, but not if we're\r\n\t\t\t// assigning from our own buffer\r\n\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 )\r\n\t\t\tif ( !this->empty() &&\r\n\t\t\t\t( pC < this->data() || pC > this->data() + this->capacity() ) )\r\n\t\t\t{\r\n\t\t\t\tthis->erase();\r\n\t\t\t}\r\n\t#endif\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(pC, nChars);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYSIZE nChars, MYVAL val)\r\n\t\t{\r\n\t\t\tQ172398(*this);\r\n\t\t\tstatic_cast<MYBASE*>(this)->assign(nChars, val);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(const CT* pT)\r\n\t\t{\r\n\t\t\treturn this->assign(pT, MYBASE::traits_type::length(pT));\r\n\t\t}\r\n\r\n\t\tMYTYPE& assign(MYCITER iterFirst, MYCITER iterLast)\r\n\t\t{\r\n\t#if defined ( _MSC_VER ) && ( _MSC_VER < 1200 ) \r\n\t\t\t// Q172398 fix.  don't call erase() if we're assigning from ourself\r\n\t\t\tif ( iterFirst < this->begin() ||\r\n                 iterFirst > this->begin() + this->size() )\r\n            {\r\n\t\t\t\tthis->erase()\r\n            }\r\n\t#endif\r\n\t\t\tthis->replace(this->begin(), this->end(), iterFirst, iterLast);\r\n\t\t\treturn *this;\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr inline concatenation.\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& operator+=(const MYTYPE& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::string& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this; \r\n\t}\r\n\r\n\tMYTYPE& operator+=(const std::wstring& str)\r\n\t{\r\n\t\tssadd(*this, str);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCSTR pA)\r\n\t{\r\n\t\tssadd(*this, pA);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(PCWSTR pW)\r\n\t{\r\n\t\tssadd(*this, pW);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& operator+=(CT t)\r\n\t{\r\n\t\tthis->append(1, t);\r\n\t\treturn *this;\r\n\t}\r\n\t#ifdef SS_INC_COMDEF\t// if we have _bstr_t, define a += for it too.\r\n\t\tMYTYPE& operator+=(const _bstr_t& bstr)\r\n\t\t{\r\n\t\t\treturn this->operator+=(static_cast<PCMYSTR>(bstr));\r\n\t\t}\r\n\t#endif\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Case changing functions\r\n\t// -------------------------------------------------------------------------\r\n\r\n    MYTYPE& ToUpper(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToUpper<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tssupr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& ToLower(const std::locale& loc=std::locale())\r\n\t{\r\n\t\t// Note -- if there are any MBCS character sets in which the lowercase\r\n\t\t// form a character takes up a different number of bytes than the\r\n\t\t// uppercase form, this would probably not work...\r\n\r\n\t\tstd::transform(this->begin(),\r\n\t\t\t\t\t   this->end(),\r\n\t\t\t\t\t   this->begin(),\r\n\t\t\t\t\t   std::bind2nd(SSToLower<CT>(), loc));\r\n\r\n\t\t// ...but if it were, this would probably work better.  Also, this way\r\n\t\t// seems to be a bit faster when anything other then the \"C\" locale is\r\n\t\t// used...\r\n\r\n//\t\tif ( !empty() )\r\n//\t\t{\r\n//\t\t\tsslwr(this->GetBuf(), this->size(), loc);\r\n//\t\t\tthis->RelBuf();\r\n//\t\t}\r\n\t\treturn *this;\r\n\t}\r\n\r\n\r\n\tMYTYPE& Normalize()\r\n\t{\r\n\t\treturn Trim().ToLower();\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CStdStr -- Direct access to character buffer.  In the MS' implementation,\r\n\t// the at() function that we use here also calls _Freeze() providing us some\r\n\t// protection from multithreading problems associated with ref-counting.\r\n    // In VC 7 and later, of course, the ref-counting stuff is gone.\r\n\t// -------------------------------------------------------------------------\r\n\r\n\tCT* GetBuf(int nMinLen=-1)\r\n\t{\r\n\t\tif ( static_cast<int>(size()) < nMinLen )\r\n\t\t\tthis->resize(static_cast<MYSIZE>(nMinLen));\r\n\r\n\t\treturn this->empty() ? const_cast<CT*>(this->data()) : &(this->at(0));\r\n\t}\r\n\r\n\tCT* SetBuf(int nLen)\r\n\t{\r\n\t\tnLen = ( nLen > 0 ? nLen : 0 );\r\n\t\tif ( this->capacity() < 1 && nLen == 0 )\r\n\t\t\tthis->resize(1);\r\n\r\n\t\tthis->resize(static_cast<MYSIZE>(nLen));\r\n\t\treturn const_cast<CT*>(this->data());\r\n\t}\r\n\tvoid RelBuf(int nNewLen=-1)\r\n\t{\r\n\t\tthis->resize(static_cast<MYSIZE>(nNewLen > -1 ? nNewLen :\r\n                                                        sslen(this->c_str())));\r\n\t}\r\n\r\n\tvoid BufferRel()\t\t { RelBuf(); }\t\t\t// backwards compatability\r\n\tCT*  Buffer()\t\t\t { return GetBuf(); }\t// backwards compatability\r\n\tCT*  BufferSet(int nLen) { return SetBuf(nLen);}// backwards compatability\r\n\r\n\tbool Equals(const CT* pT, bool bUseCase=false) const\r\n\t{\r\n\t\treturn  0 == (bUseCase ? this->compare(pT) : ssicmp(this->c_str(), pT));\r\n\t} \r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Load\r\n\t// REMARKS:\r\n\t//\t\tLoads string from resource specified by nID\r\n\t//\r\n\t// PARAMETERS:\r\n\t//\t\tnID - resource Identifier.  Purely a Win32 thing in this case\r\n\t//\r\n\t// RETURN VALUE:\r\n\t//\t\ttrue if successful, false otherwise\r\n\t// -------------------------------------------------------------------------\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tbool Load(UINT nId, HMODULE hModule=NULL)\r\n\t{\r\n\t\tbool bLoaded\t\t= false;\t// set to true of we succeed.\r\n\r\n\t#ifdef _MFC_VER\t\t// When in Rome (or MFC land)...\r\n\r\n\t\t// If they gave a resource handle, use it.  Note - this is archaic\r\n\t\t// and not really what I would recommend.  But then again, in MFC\r\n\t\t// land, you ought to be using CString for resources anyway since\r\n\t\t// it walks the resource chain for you.\r\n\r\n\t\tHMODULE hModuleOld = NULL;\r\n\r\n\t\tif ( NULL != hModule )\r\n\t\t{\r\n\t\t\thModuleOld = AfxGetResourceHandle();\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\t\t}\r\n\r\n\t\t// ...load the string\r\n\r\n\t\tCString strRes;\r\n\t\tbLoaded\t\t\t\t= FALSE != strRes.LoadString(nId);\r\n\r\n\t\t// ...and if we set the resource handle, restore it.\r\n\r\n\t\tif ( NULL != hModuleOld )\r\n\t\t\tAfxSetResourceHandle(hModule);\r\n\r\n\t\tif ( bLoaded )\r\n\t\t\t*this\t\t\t= strRes;\r\n\r\n\t#else // otherwise make our own hackneyed version of CString's Load\r\n\t\t\r\n\t\t// Get the resource name and module handle\r\n\r\n\t\tif ( NULL == hModule )\r\n\t\t\thModule\t\t\t= GetResourceHandle();\r\n\r\n\t\tPCTSTR szName\t\t= MAKEINTRESOURCE((nId>>4)+1); // lifted \r\n\t\tDWORD dwSize\t\t= 0;\r\n\r\n\t\t// No sense continuing if we can't find the resource\r\n\r\n\t\tHRSRC hrsrc\t\t\t= ::FindResource(hModule, szName, RT_STRING);\r\n\r\n\t\tif ( NULL == hrsrc )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cannot find resource %d: 0x%X\"), nId, ::GetLastError());\r\n\t\t}\r\n\t\telse if ( 0 == (dwSize = ::SizeofResource(hModule, hrsrc) / sizeof(CT)))\r\n\t\t{\r\n\t\t\tTRACE(_T(\"Cant get size of resource %d 0x%X\\n\"),nId,GetLastError());\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tbLoaded\t\t\t= 0 != ssload(hModule, nId, GetBuf(dwSize), dwSize);\r\n\t\t\tReleaseBuffer();\r\n\t\t}\r\n\r\n\t#endif  // #ifdef _MFC_VER\r\n\r\n\t\tif ( !bLoaded )\r\n\t\t\tTRACE(_T(\"String not loaded 0x%X\\n\"), ::GetLastError());\r\n\r\n\t\treturn bLoaded;\r\n\t}\r\n\r\n#endif  // #ifdef SS_ANSI\r\n\t\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  CStdStr::Format\r\n\t//\t\tvoid _cdecl Formst(CStdStringA& PCSTR szFormat, ...)\r\n\t//\t\tvoid _cdecl Format(PCSTR szFormat);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function does sprintf/wsprintf style formatting on CStdStringA\r\n\t//\t\tobjects.  It looks a lot like MFC's CString::Format.  Some people\r\n\t//\t\tmight even call this identical.  Fortunately, these people are now\r\n\t//\t\tdead... heh heh.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tnId - ID of string resource holding the format string\r\n\t//\t\tszFormat - a PCSTR holding the format specifiers\r\n\t//\t\targList - a va_list holding the arguments for the format specifiers.\r\n\t//\r\n\t// RETURN VALUE:  None.\r\n\t// -------------------------------------------------------------------------\r\n\t// formatting (using wsprintf style formatting)\r\n\r\n    // If they want a Format() function that safely handles string objects\r\n    // without casting\r\n \r\n#ifdef SS_SAFE_FORMAT       \r\n    \r\n    // Question:  Joe, you wacky coder you, why do you have so many overloads\r\n    //      of the Format() function\r\n    // Answer:  One reason only - CString compatability.  In short, by making\r\n    //      the Format() function a template this way, I can do strong typing\r\n    //      and allow people to pass CStdString arguments as fillers for\r\n    //      \"%s\" format specifiers without crashing their program!  The downside\r\n    //      is that I need to overload on the number of arguments.   If you are\r\n    //      passing more arguments than I have listed below in any of my\r\n    //      overloads, just add another one.\r\n    //\r\n    //      Yes, yes, this is really ugly.  In essence what I am doing here is\r\n    //      protecting people from a bad (and incorrect) programming practice\r\n    //      that they should not be doing anyway.  I am protecting them from\r\n    //      themselves.  Why am I doing this?  Well, if you had any idea the\r\n    //      number of times I've been emailed by people about this\r\n    //      \"incompatability\" in my code, you wouldn't ask.\r\n\r\n\tvoid Fmt(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\r\n    void Format(UINT nId)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) ) \r\n            this->swap(strFmt);\r\n    }\r\n    template<class A1>\r\n    void Format(UINT nId, const A1& v)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n            Fmt(strFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(UINT nId, const A1& v1, const A2& v2)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(),FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n           Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n        }\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(UINT nId, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n        {\r\n            Fmt(strFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n                FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n                FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n                FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n                FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n                FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n        }\r\n    }\r\n    \r\n#endif // #ifndef SS_ANSI\r\n\r\n    // ...now the other overload of Format: the one that takes a string literal\r\n\r\n    void Format(const CT* szFmt)\r\n    {\r\n        *this = szFmt;\r\n    }\r\n    template<class A1>\r\n    void Format(const CT* szFmt, A1 v)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v)());\r\n    }\r\n    template<class A1, class A2>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)());\r\n    }\r\n    template<class A1, class A2, class A3>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(),FmtArg<A10>(v10)(),FmtArg<A11>(v11)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(), FmtArg<A13>(v13)(),FmtArg<A14>(v14)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(), FmtArg<A16>(v16)());\r\n    }\r\n    template<class A1, class A2, class A3, class A4, class A5, class A6,\r\n        class A7, class A8, class A9, class A10, class A11, class A12,\r\n        class A13, class A14, class A15, class A16, class A17>\r\n    void Format(const CT* szFmt, const A1& v1, const A2& v2, const A3& v3,\r\n                const A4& v4, const A5& v5, const A6& v6, const A7& v7,\r\n                const A8& v8, const A9& v9, const A10& v10, const A11& v11,\r\n                const A12& v12, const A13& v13, const A14& v14, const A15& v15,\r\n                const A16& v16, const A17& v17)\r\n    {\r\n        Fmt(szFmt, FmtArg<A1>(v1)(), FmtArg<A2>(v2)(),\r\n            FmtArg<A3>(v3)(), FmtArg<A4>(v4)(), FmtArg<A5>(v5)(),\r\n            FmtArg<A6>(v6)(), FmtArg<A7>(v7)(), FmtArg<A8>(v8)(),\r\n            FmtArg<A9>(v9)(), FmtArg<A10>(v10)(),FmtArg<A11>(v11)(),\r\n            FmtArg<A12>(v12)(),FmtArg<A13>(v13)(),FmtArg<A14>(v14)(),\r\n            FmtArg<A15>(v15)(),FmtArg<A16>(v16)(),FmtArg<A17>(v17)());\r\n    }\r\n\r\n#else  // #ifdef SS_SAFE_FORMAT\r\n\r\n\r\n#ifndef SS_ANSI\r\n\r\n\tvoid Format(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tMYTYPE strFmt;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tFormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t}\r\n    \r\n#endif  // #ifdef SS_ANSI\r\n\r\n\tvoid Format(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n#endif // #ifdef SS_SAFE_FORMAT\r\n\r\n\tvoid AppendFormat(const CT* szFmt, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFmt);\r\n\t\tAppendFormatV(szFmt, argList);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\t#define MAX_FMT_TRIES\t\t5\t // #of times we try \r\n\t#define FMT_BLOCK_SIZE\t\t2048 // # of bytes to increment per try\r\n\t#define BUFSIZE_1ST\t256\r\n\t#define BUFSIZE_2ND 512\r\n\t#define STD_BUF_SIZE\t\t1024\r\n\r\n\t// an efficient way to add formatted characters to the string.  You may only\r\n\t// add up to STD_BUF_SIZE characters at a time, though\r\n\tvoid AppendFormatV(const CT* szFmt, va_list argList)\r\n\t{\r\n\t\tCT szBuf[STD_BUF_SIZE];\r\n\t#ifdef SS_ANSI\r\n\t\tint nLen = ssvsprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#else\r\n\t\tint nLen = ssnprintf(szBuf, STD_BUF_SIZE-1, szFmt, argList);\r\n\t#endif\r\n\t\tif ( 0 < nLen )\r\n\t\t\tthis->append(szBuf, nLen);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION:  FormatV\r\n\t//\t\tvoid FormatV(PCSTR szFormat, va_list, argList);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t\tThis function formats the string with sprintf style format-specs. \r\n\t//\t\tIt makes a general guess at required buffer size and then tries\r\n\t//\t\tsuccessively larger buffers until it finds one big enough or a\r\n\t//\t\tthreshold (MAX_FMT_TRIES) is exceeded.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t\tszFormat - a PCSTR holding the format of the output\r\n\t//\t\targList - a Microsoft specific va_list for variable argument lists\r\n\t//\r\n\t// RETURN VALUE: \r\n\t// -------------------------------------------------------------------------\r\n\r\n\tvoid FormatV(const CT* szFormat, va_list argList)\r\n\t{\r\n\t#ifdef SS_ANSI\r\n\r\n\t\tint nLen\t= sslen(szFormat) + STD_BUF_SIZE;\r\n\t\tssvsprintf(GetBuffer(nLen), nLen-1, szFormat, argList);\r\n\t\tReleaseBuffer();\r\n\r\n\t#else\r\n\r\n\t\tCT* pBuf\t\t\t= NULL;\r\n\t\tint nChars\t\t\t= 1;\r\n\t\tint nUsed\t\t\t= 0;\r\n\t\tsize_type nActual\t= 0;\r\n\t\tint nTry\t\t\t= 0;\r\n\r\n\t\tdo\t\r\n\t\t{\r\n\t\t\t// Grow more than linearly (e.g. 512, 1536, 3072, etc)\r\n\r\n\t\t\tnChars\t\t\t+= ((nTry+1) * FMT_BLOCK_SIZE);\r\n\t\t\tpBuf\t\t\t= reinterpret_cast<CT*>(_alloca(sizeof(CT)*nChars));\r\n\t\t\tnUsed\t\t\t= ssnprintf(pBuf, nChars-1, szFormat, argList);\r\n\r\n\t\t\t// Ensure proper NULL termination.\r\n\r\n\t\t\tnActual\t\t\t= nUsed == -1 ? nChars-1 : SSMIN(nUsed, nChars-1);\r\n\t\t\tpBuf[nActual+1]= '\\0';\r\n\r\n\r\n\t\t} while ( nUsed < 0 && nTry++ < MAX_FMT_TRIES );\r\n\r\n\t\t// assign whatever we managed to format\r\n\r\n\t\tthis->assign(pBuf, nActual);\r\n\r\n\t#endif\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// CString Facade Functions:\r\n\t//\r\n\t// The following methods are intended to allow you to use this class as a\r\n\t// near drop-in replacement for CString.\r\n\t// -------------------------------------------------------------------------\r\n\t#ifdef SS_WIN32\r\n\t\tBSTR AllocSysString() const\r\n\t\t{\r\n\t\t\tostring os;\r\n\t\t\tssasn(os, *this);\r\n\t\t\treturn ::SysAllocString(os.c_str());\r\n\t\t}\r\n\t#endif\r\n\r\n\tint Collate(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn sscoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint CollateNoCase(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn ssicoll(this->c_str(), this->length(), szThat, sslen(szThat));\r\n\t}\r\n\r\n\tint Compare(PCMYSTR szThat) const\r\n\t{\r\n\t\treturn this->compare(szThat);\t\r\n\t}\r\n\r\n\tint CompareNoCase(PCMYSTR szThat)\tconst\r\n\t{\r\n\t\treturn ssicmp(this->c_str(), szThat);\r\n\t}\r\n\r\n\tint Delete(int nIdx, int nCount=1)\r\n\t{\r\n        if ( nIdx < 0 )\r\n\t\t\tnIdx = 0;\r\n\r\n\t\tif ( nIdx < this->GetLength() )\r\n\t\t\tthis->erase(static_cast<MYSIZE>(nIdx), static_cast<MYSIZE>(nCount));\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tvoid Empty()\r\n\t{\r\n\t\tthis->erase();\r\n\t}\r\n\r\n\tint Find(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx  ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find(szSub);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(CT ch, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find_first_of(ch, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint Find(PCMYSTR szSub, int nStart) const\r\n\t{\r\n\t\t// CString::Find docs say add 1 to nStart when it's not zero\r\n\t\t// CString::Find code doesn't do that however.  We'll stick\r\n\t\t// with what the code does\r\n\r\n\t\tMYSIZE nIdx\t= this->find(szSub, static_cast<MYSIZE>(nStart));\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tint FindOneOf(PCMYSTR szCharSet) const\r\n\t{\r\n\t\tMYSIZE nIdx = this->find_first_of(szCharSet);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tvoid FormatMessage(PCMYSTR szFormat, ...) throw(std::exception)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, szFormat);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   szFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\t szTemp == 0 )\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n\r\n\tvoid FormatMessage(UINT nFormatId, ...) throw(std::exception)\r\n\t{\r\n\t\tMYTYPE sFormat;\r\n\t\tVERIFY(sFormat.LoadString(nFormatId));\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nFormatId);\r\n\t\tPMYSTR szTemp;\r\n\t\tif ( ssfmtmsg(FORMAT_MESSAGE_FROM_STRING|FORMAT_MESSAGE_ALLOCATE_BUFFER,\r\n\t\t\t\t\t   sFormat, 0, 0,\r\n\t\t\t\t\t   reinterpret_cast<PMYSTR>(&szTemp), 0, &argList) == 0 ||\r\n\t\t\tszTemp == 0)\r\n\t\t{\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\t\t}\r\n\t\t*this = szTemp;\r\n\t\tLocalFree(szTemp);\r\n\t\tva_end(argList);\r\n\t}\r\n#endif\r\n\r\n\t// GetAllocLength -- an MSVC7 function but it costs us nothing to add it.\r\n\r\n\tint GetAllocLength()\r\n\t{\r\n\t\treturn static_cast<int>(this->capacity());\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// GetXXXX -- Direct access to character buffer\r\n\t// -------------------------------------------------------------------------\r\n\tCT GetAt(int nIdx) const\r\n\t{\r\n\t\treturn this->at(static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT* GetBuffer(int nMinLen=-1)\r\n\t{\r\n\t\treturn GetBuf(nMinLen);\r\n\t}\r\n\r\n\tCT* GetBufferSetLength(int nLen)\r\n\t{\r\n\t\treturn BufferSet(nLen);\r\n\t}\r\n\r\n\t// GetLength() -- MFC docs say this is the # of BYTES but\r\n\t// in truth it is the number of CHARACTERs (chars or wchar_ts)\r\n\tint GetLength() const\r\n\t{\r\n\t\treturn static_cast<int>(this->length());\r\n\t}\r\n\t\r\n\tint Insert(int nIdx, CT ch)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) > this->size()-1 )\r\n\t\t\tthis->append(1, ch);\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), 1, ch);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\tint Insert(int nIdx, PCMYSTR sz)\r\n\t{\r\n\t\tif ( static_cast<MYSIZE>(nIdx) >= this->size() )\r\n\t\t\tthis->append(sz, static_cast<MYSIZE>(sslen(sz)));\r\n\t\telse\r\n\t\t\tthis->insert(static_cast<MYSIZE>(nIdx), sz);\r\n\r\n\t\treturn GetLength();\r\n\t}\r\n\r\n\tbool IsEmpty() const\r\n\t{\r\n\t\treturn this->empty();\r\n\t}\r\n\r\n\tMYTYPE Left(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(0, static_cast<MYSIZE>(nCount)); \r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tbool LoadString(UINT nId)\r\n\t{\r\n\t\treturn this->Load(nId);\r\n\t}\r\n#endif\r\n\r\n\tvoid MakeLower()\r\n\t{\r\n\t\tToLower();\r\n\t}\r\n\r\n\tvoid MakeReverse()\r\n\t{\r\n\t\tstd::reverse(this->begin(), this->end());\r\n\t}\r\n\r\n\tvoid MakeUpper()\r\n\t{ \r\n\t\tToUpper();\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst) const\r\n\t{\r\n\t\treturn Mid(nFirst, this->GetLength()-nFirst);\r\n\t}\r\n\r\n\tMYTYPE Mid(int nFirst, int nCount) const\r\n\t{\r\n\t\t// CString does range checking here.  Since we're trying to emulate it,\r\n\t\t// we must check too.\r\n\r\n\t\tif ( nFirst < 0 )\r\n\t\t\tnFirst = 0;\r\n\t\tif ( nCount < 0 )\r\n\t\t\tnCount = 0;\r\n\r\n\t\tint nSize = static_cast<int>(this->size());\r\n\r\n\t\tif ( nFirst + nCount > nSize )\r\n\t\t\tnCount = nSize - nFirst;\r\n\r\n\t\tif ( nFirst > nSize )\r\n\t\t\treturn MYTYPE();\r\n\r\n\t\tASSERT(nFirst >= 0);\r\n\t\tASSERT(nFirst + nCount <= nSize);\r\n\r\n\t\treturn this->substr(static_cast<MYSIZE>(nFirst),\r\n\t\t\t\t\t\t\tstatic_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid ReleaseBuffer(int nNewLen=-1)\r\n\t{\r\n\t\tRelBuf(nNewLen);\r\n\t}\r\n\r\n\tint Remove(CT ch)\r\n\t{\r\n\t\tMYSIZE nIdx\t\t= 0;\r\n\t\tint nRemoved\t= 0;\r\n\t\twhile ( (nIdx=this->find_first_of(ch)) != MYBASE::npos )\r\n\t\t{\r\n\t\t\tthis->erase(nIdx, 1);\r\n\t\t\tnRemoved++;\r\n\t\t}\r\n\t\treturn nRemoved;\r\n\t}\r\n\r\n\tint Replace(CT chOld, CT chNew)\r\n\t{\r\n\t\tint nReplaced\t= 0;\r\n\r\n\t\tfor ( MYITER iter=this->begin(); iter != this->end(); iter++ )\r\n\t\t{\r\n\t\t\tif ( *iter == chOld )\r\n\t\t\t{\r\n\t\t\t\t*iter = chNew;\r\n\t\t\t\tnReplaced++;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint Replace(PCMYSTR szOld, PCMYSTR szNew)\r\n\t{\r\n\t\tint nReplaced\t\t= 0;\r\n\t\tMYSIZE nIdx\t\t\t= 0;\r\n\t\tMYSIZE nOldLen\t\t= sslen(szOld);\r\n\r\n\t\tif ( 0 != nOldLen )\r\n\t\t{\r\n\t\t\tstatic const CT ch\t= CT(0);\r\n\t\t\tMYSIZE nNewLen\t\t= sslen(szNew);\r\n\t\t\tPCMYSTR szRealNew\t= szNew == 0 ? &ch : szNew;\r\n\r\n\t\t\twhile ( (nIdx=this->find(szOld, nIdx)) != MYBASE::npos )\r\n\t\t\t{\r\n\t\t\t\tthis->replace(this->begin()+nIdx, this->begin()+nIdx+nOldLen,\r\n\t\t\t\t\tszRealNew);\r\n\r\n\t\t\t\tnReplaced++;\r\n\t\t\t\tnIdx += nNewLen;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn nReplaced;\r\n\t}\r\n\r\n\tint ReverseFind(CT ch) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_of(ch);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\t// ReverseFind overload that's not in CString but might be useful\r\n\tint ReverseFind(PCMYSTR szFind, MYSIZE pos=MYBASE::npos) const\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->rfind(0 == szFind ? MYTYPE() : szFind, pos);\r\n\t\treturn static_cast<int>(MYBASE::npos == nIdx ? -1 : nIdx);\r\n\t}\r\n\r\n\tMYTYPE Right(int nCount) const\r\n\t{\r\n        // Range check the count.\r\n\r\n\t\tnCount = SSMAX(0, SSMIN(nCount, static_cast<int>(this->size())));\r\n\t\treturn this->substr(this->size()-static_cast<MYSIZE>(nCount));\r\n\t}\r\n\r\n\tvoid SetAt(int nIndex, CT ch)\r\n\t{\r\n\t\tASSERT(this->size() > static_cast<MYSIZE>(nIndex));\r\n\t\tthis->at(static_cast<MYSIZE>(nIndex))\t\t= ch;\r\n\t}\r\n\r\n#ifndef SS_ANSI\r\n\tBSTR SetSysString(BSTR* pbstr) const\r\n\t{\r\n\t\tostring os;\r\n\t\tssasn(os, *this);\r\n\t\tif ( !::SysReAllocStringLen(pbstr, os.c_str(), os.length()) )\r\n\t\t\tthrow std::runtime_error(\"out of memory\");\r\n\r\n\t\tASSERT(*pbstr != 0);\r\n\t\treturn *pbstr;\r\n\t}\r\n#endif\r\n\r\n\tMYTYPE SpanExcluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n\tMYTYPE SpanIncluding(PCMYSTR szCharSet) const\r\n\t{\r\n        MYSIZE pos = this->find_first_not_of(szCharSet);\r\n        return pos == MYBASE::npos ? *this : Left(pos);\r\n\t}\r\n\r\n#if defined SS_WIN32 && !defined(UNICODE) && !defined(SS_ANSI)\r\n\r\n\t// CString's OemToAnsi and AnsiToOem functions are available only in\r\n\t// Unicode builds.  However since we're a template we also need a\r\n\t// runtime check of CT and a reinterpret_cast to account for the fact\r\n\t// that CStdStringW gets instantiated even in non-Unicode builds.\r\n\r\n\tvoid AnsiToOem()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::CharToOem(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid OemToAnsi()\r\n\t{\r\n\t\tif ( sizeof(CT) == sizeof(char) && !empty() )\r\n\t\t{\r\n\t\t\t::OemToChar(reinterpret_cast<PCSTR>(this->c_str()),\r\n\t\t\t\t\t\treinterpret_cast<PSTR>(GetBuf()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tASSERT(false);\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\t\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// Trim and its variants\r\n\t// -------------------------------------------------------------------------\r\n\tMYTYPE& Trim()\r\n\t{\r\n\t\treturn TrimLeft().TrimRight();\r\n\t}\r\n\r\n\tMYTYPE& TrimLeft()\r\n\t{\r\n\t\tthis->erase(this->begin(),\r\n\t\t\tstd::find_if(this->begin(), this->end(), NotSpace<CT>()));\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(CT tTrim)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(tTrim));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimLeft(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tthis->erase(0, this->find_first_not_of(szTrimChars));\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE& TrimRight()\r\n\t{\r\n\t\t// NOTE:  When comparing reverse_iterators here (MYRITER), I avoid using\r\n\t\t// operator!=.  This is because namespace rel_ops also has a template\r\n\t\t// operator!= which conflicts with the global operator!= already defined\r\n\t\t// for reverse_iterator in the header <utility>.\r\n\t\t// Thanks to John James for alerting me to this.\r\n\r\n\t\tMYRITER it = std::find_if(this->rbegin(), this->rend(), NotSpace<CT>());\r\n\t\tif ( !(this->rend() == it) )\r\n\t\t\tthis->erase(this->rend() - it);\r\n\r\n\t\tthis->erase(!(it == this->rend()) ? this->find_last_of(*it) + 1 : 0);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(CT tTrim)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(tTrim);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tMYTYPE&  TrimRight(PCMYSTR szTrimChars)\r\n\t{\r\n\t\tMYSIZE nIdx\t= this->find_last_not_of(szTrimChars);\r\n\t\tthis->erase(MYBASE::npos == nIdx ? 0 : ++nIdx);\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid\t\t\tFreeExtra()\r\n\t{\r\n\t\tMYTYPE mt;\r\n\t\tthis->swap(mt);\r\n\t\tif ( !mt.empty() )\r\n\t\t\tthis->assign(mt.c_str(), mt.size());\r\n\t}\r\n\r\n\t// I have intentionally not implemented the following CString\r\n\t// functions.   You cannot make them work without taking advantage\r\n\t// of implementation specific behavior.  However if you absolutely\r\n\t// MUST have them, uncomment out these lines for \"sort-of-like\"\r\n\t// their behavior.  You're on your own.\r\n\r\n//\tCT*\t\t\t\tLockBuffer()\t{ return GetBuf(); }// won't really lock\r\n//\tvoid\t\t\tUnlockBuffer(); { }\t// why have UnlockBuffer w/o LockBuffer?\r\n\r\n\t// Array-indexing operators.  Required because we defined an implicit cast\r\n\t// to operator const CT* (Thanks to Julian Selman for pointing this out)\r\n\r\n\tCT& operator[](int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tCT& operator[](unsigned int nIdx)\r\n\t{\r\n\t\treturn static_cast<MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n\tconst CT& operator[](unsigned int nIdx) const\r\n\t{\r\n\t\treturn static_cast<const MYBASE*>(this)->operator[](static_cast<MYSIZE>(nIdx));\r\n\t}\r\n\r\n#ifndef SS_NO_IMPLICIT_CAST\r\n\toperator const CT*() const\r\n\t{\r\n\t\treturn this->c_str();\r\n\t}\r\n#endif\r\n\r\n\t// IStream related functions.  Useful in IPersistStream implementations\r\n\r\n#ifdef SS_INC_COMDEF\r\n\r\n\t// struct SSSHDR - useful for non Std C++ persistence schemes.\r\n\ttypedef struct SSSHDR\r\n\t{\r\n\t\tBYTE\tbyCtrl;\r\n\t\tULONG\tnChars;\r\n\t} SSSHDR;\t// as in \"Standard String Stream Header\"\r\n\r\n\t#define SSSO_UNICODE\t0x01\t// the string is a wide string\r\n\t#define SSSO_COMPRESS\t0x02\t// the string is compressed\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSize\r\n\t// REMARKS:\r\n\t//\t\tReturns how many bytes it will take to StreamSave() this CStdString\r\n\t//\t\tobject to an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tULONG StreamSize() const\r\n\t{\r\n\t\t// Control header plus string\r\n\t\tASSERT(this->size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\treturn (this->size() * sizeof(CT)) + sizeof(SSSHDR);\r\n\t}\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamSave\r\n\t// REMARKS:\r\n\t//\t\tSaves this CStdString object to a COM IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamSave(IStream* pStream) const\r\n\t{\r\n\t\tASSERT(size()*sizeof(CT) < 0xffffffffUL - sizeof(SSSHDR));\r\n\t\tHRESULT hr\t\t= E_FAIL;\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\thdr.byCtrl\t\t= sizeof(CT) == 2 ? SSSO_UNICODE : 0;\r\n\t\thdr.nChars\t\t= this->size();\r\n\r\n\r\n\t\tif ( FAILED(hr=pStream->Write(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write control header, ERR=0x%X\\n\"),hr);\r\n\t\t}\r\n\t\telse if ( empty() )\r\n\t\t{\r\n\t\t\t;\t\t// nothing to write\r\n\t\t}\r\n\t\telse if ( FAILED(hr=pStream->Write(this->c_str(),\r\n\t\t\tthis->size()*sizeof(CT), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamSave: Cannot write string to stream 0x%X\\n\"), hr);\r\n\t\t}\r\n\r\n\t\treturn hr;\r\n\t}\r\n\r\n\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: StreamLoad\r\n\t// REMARKS:\r\n\t//\t\tThis method loads the object from an IStream.\r\n\t// -------------------------------------------------------------------------\r\n\tHRESULT StreamLoad(IStream* pStream)\r\n\t{\r\n\t\tASSERT(pStream != 0);\r\n\t\tSSSHDR hdr;\r\n\t\tHRESULT hr\t\t\t= E_FAIL;\r\n\r\n\t\tif ( FAILED(hr=pStream->Read(&hdr, sizeof(SSSHDR), 0)) )\r\n\t\t{\r\n\t\t\tTRACE(_T(\"StreamLoad: Cant read control header, ERR=0x%X\\n\"), hr);\r\n\t\t}\r\n\t\telse if ( hdr.nChars > 0 )\r\n\t\t{\r\n\t\t\tULONG nRead\t\t= 0;\r\n\t\t\tPMYSTR pMyBuf\t= BufferSet(hdr.nChars);\r\n\r\n\t\t\t// If our character size matches the character size of the string\r\n\t\t\t// we're trying to read, then we can read it directly into our\r\n\t\t\t// buffer. Otherwise, we have to read into an intermediate buffer\r\n\t\t\t// and convert.\r\n\t\t\t\r\n\t\t\tif ( (hdr.byCtrl & SSSO_UNICODE) != 0 )\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(wchar_t);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(wchar_t) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\t\r\n\t\t\t\t\tPWSTR pBufW = reinterpret_cast<PWSTR>(_alloca((nBytes)+1));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufW, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufW, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tULONG nBytes\t= hdr.nChars * sizeof(char);\r\n\t\t\t\tif ( sizeof(CT) == sizeof(char) )\r\n\t\t\t\t{\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pMyBuf, nBytes, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tPSTR pBufA = reinterpret_cast<PSTR>(_alloca(nBytes));\r\n\t\t\t\t\tif ( FAILED(hr=pStream->Read(pBufA, hdr.nChars, &nRead)) )\r\n\t\t\t\t\t\tTRACE(_T(\"StreamLoad: Cannot read string: 0x%X\\n\"), hr);\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tsscpy(pMyBuf, pBufA, hdr.nChars);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tthis->erase();\r\n\t\t}\r\n\t\treturn hr;\r\n\t}\r\n#endif // #ifdef SS_INC_COMDEF\r\n\r\n#ifndef SS_ANSI\r\n\r\n\t// SetResourceHandle/GetResourceHandle.  In MFC builds, these map directly\r\n\t// to AfxSetResourceHandle and AfxGetResourceHandle.  In non-MFC builds they\r\n\t// point to a single static HINST so that those who call the member\r\n\t// functions that take resource IDs can provide an alternate HINST of a DLL\r\n\t// to search.  This is not exactly the list of HMODULES that MFC provides\r\n\t// but it's better than nothing.\r\n\r\n\t#ifdef _MFC_VER\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tAfxSetResourceHandle(hNew);\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn AfxGetResourceHandle();\r\n\t\t}\r\n\t#else\r\n\t\tstatic void SetResourceHandle(HMODULE hNew)\r\n\t\t{\r\n\t\t\tSSResourceHandle() = hNew;\r\n\t\t}\r\n\t\tstatic HMODULE GetResourceHandle()\r\n\t\t{\r\n\t\t\treturn SSResourceHandle();\r\n\t\t}\r\n\t#endif\r\n\r\n#endif\r\n};\r\n\r\n// -----------------------------------------------------------------------------\r\n// MSVC USERS: HOW TO EXPORT CSTDSTRING FROM A DLL\r\n//\r\n// If you are using MS Visual C++ and you want to export CStdStringA and\r\n// CStdStringW from a DLL, then all you need to\r\n//\r\n//\t\t1.\tmake sure that all components link to the same DLL version\r\n//\t\t\tof the CRT (not the static one).\r\n//\t\t2.\tUncomment the 3 lines of code below\r\n//\t\t3.\t#define 2 macros per the instructions in MS KnowledgeBase\r\n//\t\t\tarticle Q168958.  The macros are:\r\n//\r\n//\t\tMACRO\t\tDEFINTION WHEN EXPORTING\t\tDEFINITION WHEN IMPORTING\r\n//\t\t-----\t\t------------------------\t\t-------------------------\r\n//\t\tSSDLLEXP\t(nothing, just #define it)\t\textern\r\n//\t\tSSDLLSPEC\t__declspec(dllexport)\t\t\t__declspec(dllimport)\r\n//\r\n//\t\tNote that these macros must be available to ALL clients who want to \r\n//\t\tlink to the DLL and use the class.  If they \r\n//\r\n// A word of advice: Don't bother.\r\n//\r\n// Really, it is not necessary to export CStdString functions from a DLL.  I\r\n// never do.  In my projects, I do generally link to the DLL version of the\r\n// Standard C++ Library, but I do NOT attempt to export CStdString functions.\r\n// I simply include the header where it is needed and allow for the code\r\n// redundancy.\r\n//\r\n// That redundancy is a lot less than you think.  This class does most of its\r\n// work via the Standard C++ Library, particularly the base_class basic_string<>\r\n// member functions.  Most of the functions here are small enough to be inlined\r\n// anyway.  Besides, you'll find that in actual practice you use less than 1/2\r\n// of the code here, even in big projects and different modules will use as\r\n// little as 10% of it.  That means a lot less functions actually get linked\r\n// your binaries.  If you export this code from a DLL, it ALL gets linked in.\r\n//\r\n// I've compared the size of the binaries from exporting vs NOT exporting.  Take\r\n// my word for it -- exporting this code is not worth the hassle.\r\n//\r\n// -----------------------------------------------------------------------------\r\n//#pragma warning(disable:4231) // non-standard extension (\"extern template\")\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<char>;\r\n//\tSSDLLEXP template class SSDLLSPEC CStdStr<wchar_t>;\r\n\r\n\r\n// =============================================================================\r\n//\t\t\t\t\t\tEND OF CStdStr INLINE FUNCTION DEFINITIONS\r\n// =============================================================================\r\n\r\n//\tNow typedef our class names based upon this humongous template\r\n\r\ntypedef CStdStr<char>\t\tCStdStringA;\t// a better std::string\r\ntypedef CStdStr<wchar_t>\tCStdStringW;\t// a better std::wstring\r\ntypedef CStdStr<OLECHAR>\tCStdStringO;\t// almost always CStdStringW\r\n\r\n// -----------------------------------------------------------------------------\r\n// CStdStr addition functions defined as inline\r\n// -----------------------------------------------------------------------------\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringA& s2)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, CStdStringA::value_type t)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCSTR pA)\r\n{\r\n\tCStdStringA sRet(SSREF(s1));\r\n\tsRet.append(pA);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(PCSTR pA, const CStdStringA& sA)\r\n{\r\n\tCStdStringA sRet;\r\n\tCStdStringA::size_type nObjSize = sA.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringA::size_type>(sslen(pA));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pA);\r\n\tsRet.append(sA);\r\n\treturn sRet;\r\n}\r\n\r\n\r\ninline CStdStringA operator+(const CStdStringA& s1, const CStdStringW& s2)\r\n{\r\n\treturn s1 + CStdStringA(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringW& s2)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(s2);\r\n\treturn sRet;\r\n}\r\ninline CStdStringA operator+(const CStdStringA& s1, PCWSTR pW)\r\n{\r\n\treturn s1 + CStdStringA(pW);\r\n}\r\n\r\n#ifdef UNICODE\r\n\tinline CStdStringW operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringW(pW) + CStdStringW(SSREF(sA));\r\n\t}\r\n\tinline CStdStringW operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn CStdStringW(pA) + sW;\r\n\t}\r\n#else\r\n\tinline CStdStringA operator+(PCWSTR pW, const CStdStringA& sA)\r\n\t{\r\n\t\treturn CStdStringA(pW) + sA;\r\n\t}\r\n\tinline CStdStringA operator+(PCSTR pA, const CStdStringW& sW)\r\n\t{\r\n\t\treturn pA + CStdStringA(sW);\r\n\t}\r\n#endif\r\n\r\n// ...Now the wide string versions.\r\ninline CStdStringW operator+(const CStdStringW& s1, CStdStringW::value_type t)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(1, t);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCWSTR pW)\r\n{\r\n\tCStdStringW sRet(SSREF(s1));\r\n\tsRet.append(pW);\r\n\treturn sRet;\r\n}\r\ninline CStdStringW operator+(PCWSTR pW, const CStdStringW& sW)\r\n{\r\n\tCStdStringW sRet;\r\n\tCStdStringW::size_type nObjSize = sW.size();\r\n\tCStdStringA::size_type nLitSize = \r\n\t\tstatic_cast<CStdStringW::size_type>(sslen(pW));\r\n\r\n\tsRet.reserve(nLitSize + nObjSize);\r\n\tsRet.assign(pW);\r\n\tsRet.append(sW);\r\n\treturn sRet;\r\n}\r\n\r\ninline CStdStringW operator+(const CStdStringW& s1, const CStdStringA& s2)\r\n{\r\n\treturn s1 + CStdStringW(s2);\r\n}\r\ninline CStdStringW operator+(const CStdStringW& s1, PCSTR pA)\r\n{\r\n\treturn s1 + CStdStringW(pA);\r\n}\r\n\r\n\r\n// New-style format function is a template\r\n\r\n#ifdef SS_SAFE_FORMAT\r\n\r\ntemplate<>\r\nstruct FmtArg<CStdStringA>\r\n{\r\n    explicit FmtArg(const CStdStringA& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringA& a_;\r\nprivate:\r\n    FmtArg<CStdStringA>& operator=(const FmtArg<CStdStringA>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<CStdStringW>\r\n{\r\n    explicit FmtArg(const CStdStringW& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const CStdStringW& a_;\r\nprivate:\r\n    FmtArg<CStdStringW>& operator=(const FmtArg<CStdStringW>&) { return *this; }\r\n};\r\n\r\ntemplate<>\r\nstruct FmtArg<std::string>\r\n{\r\n    explicit FmtArg(const std::string& arg) : a_(arg) {}\r\n    PCSTR operator()() const { return a_.c_str(); }\r\n    const std::string& a_;\r\nprivate:\r\n    FmtArg<std::string>& operator=(const FmtArg<std::string>&) { return *this; }\r\n};\r\ntemplate<>\r\nstruct FmtArg<std::wstring>\r\n{\r\n    explicit FmtArg(const std::wstring& arg) : a_(arg) {}\r\n    PCWSTR operator()() const { return a_.c_str(); }\r\n    const std::wstring& a_;\r\nprivate:\r\n    FmtArg<std::wstring>& operator=(const FmtArg<std::wstring>&) {return *this;}\r\n};\r\n#endif // #ifdef SS_SAFEFORMAT\r\n\r\n#ifndef SS_ANSI\r\n\t// SSResourceHandle: our MFC-like resource handle\r\n\tinline HMODULE& SSResourceHandle()\r\n\t{\r\n\t\tstatic HMODULE hModuleSS\t= GetModuleHandle(0);\r\n\t\treturn hModuleSS;\r\n\t}\r\n#endif\r\n\r\n\r\n// In MFC builds, define some global serialization operators\r\n// Special operators that allow us to serialize CStdStrings to CArchives.\r\n// Note that we use an intermediate CString object in order to ensure that\r\n// we use the exact same format.\r\n\r\n#ifdef _MFC_VER\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp\t= strA;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\tinline CArchive& AFXAPI operator<<(CArchive& ar, const CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp\t= strW;\r\n\t\treturn ar << strTemp;\r\n\t}\r\n\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringA& strA)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrA = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n\tinline CArchive& AFXAPI operator>>(CArchive& ar, CStdStringW& strW)\r\n\t{\r\n\t\tCString strTemp;\r\n\t\tar >> strTemp;\r\n\t\tstrW = strTemp;\r\n\t\treturn ar;\r\n\t}\r\n#endif\t// #ifdef _MFC_VER -- (i.e. is this MFC?)\r\n\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// GLOBAL FUNCTION:  WUFormat\r\n//\t\tCStdStringA WUFormat(UINT nId, ...);\r\n//\t\tCStdStringA WUFormat(PCSTR szFormat, ...);\r\n//\r\n// REMARKS:\r\n//\t\tThis function allows the caller for format and return a CStdStringA\r\n//\t\tobject with a single line of code.\r\n// -----------------------------------------------------------------------------\r\n\r\ninline CStdStringA WUFormatA(PCSTR szFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szFormat);\r\n\tCStdStringA strOut;\r\n\tstrOut.FormatV(szFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\ninline CStdStringW WUFormatW(PCWSTR szwFormat, ...)\r\n{\r\n\tva_list argList;\r\n\tva_start(argList, szwFormat);\r\n\tCStdStringW strOut;\r\n\tstrOut.FormatV(szwFormat, argList);\r\n\tva_end(argList);\r\n\treturn strOut;\r\n}\r\n#ifdef SS_ANSI\r\n#else\r\n\tinline CStdStringA WUFormatA(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringA strFmt;\r\n\t\tCStdStringA strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n\r\n\tinline CStdStringW WUFormatW(UINT nId, ...)\r\n\t{\r\n\t\tva_list argList;\r\n\t\tva_start(argList, nId);\r\n\r\n\t\tCStdStringW strFmt;\r\n\t\tCStdStringW strOut;\r\n\t\tif ( strFmt.Load(nId) )\r\n\t\t\tstrOut.FormatV(strFmt, argList);\r\n\r\n\t\tva_end(argList);\r\n\t\treturn strOut;\r\n\t}\r\n#endif // #ifdef SS_ANSI\r\n\r\n\r\n\r\n#if defined(SS_WIN32) && !defined (SS_ANSI)\r\n\t// -------------------------------------------------------------------------\r\n\t// FUNCTION: WUSysMessage\r\n\t//\t CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//\t CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID);\r\n\t//           \r\n\t// DESCRIPTION:\r\n\t//\t This function simplifies the process of obtaining a string equivalent\r\n\t//\t of a system error code returned from GetLastError().  You simply\r\n\t//\t supply the value returned by GetLastError() to this function and the\r\n\t//\t corresponding system string is returned in the form of a CStdStringA.\r\n\t//\r\n\t// PARAMETERS: \r\n\t//\t dwError - a DWORD value representing the error code to be translated\r\n\t//\t dwLangId - the language id to use.  defaults to english.\r\n\t//\r\n\t// RETURN VALUE: \r\n\t//\t a CStdStringA equivalent of the error code.  Currently, this function\r\n\t//\t only returns either English of the system default language strings.  \r\n\t// -------------------------------------------------------------------------\r\n\t#define SS_DEFLANGID MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT)\r\n\tinline CStdStringA WUSysMessageA(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatA(\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatA(\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n\tinline CStdStringW WUSysMessageW(DWORD dwError, DWORD dwLangId=SS_DEFLANGID)\r\n\t{\r\n\t\tWCHAR szBuf[512];\r\n\r\n\t\tif ( 0 != ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwError,\r\n\t\t\t\t\t\t\t\t   dwLangId, szBuf, 511, NULL) )\r\n\t\t\treturn WUFormatW(L\"%s (0x%X)\", szBuf, dwError);\r\n\t\telse\r\n \t\t\treturn WUFormatW(L\"Unknown error (0x%X)\", dwError);\r\n\t}\r\n#endif\r\n\r\n// Define TCHAR based friendly names for some of these functions\r\n\r\n#ifdef UNICODE\r\n\t//#define CStdString\t\t\t\tCStdStringW\r\n\ttypedef CStdStringW\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageW\r\n\t#define WUFormat\t\t\t\tWUFormatW\r\n#else\r\n\t//#define CStdString\t\t\t\tCStdStringA\r\n\ttypedef CStdStringA\t\t\t\tCStdString;\r\n\t#define WUSysMessage\t\t\tWUSysMessageA\r\n\t#define WUFormat\t\t\t\tWUFormatA\r\n#endif\r\n\r\n// ...and some shorter names for the space-efficient\r\n\r\n#define WUSysMsg\t\t\t\t\tWUSysMessage\r\n#define WUSysMsgA\t\t\t\t\tWUSysMessageA\r\n#define WUSysMsgW\t\t\t\t\tWUSysMessageW\r\n#define WUFmtA\t\t\t\t\t\tWUFormatA\r\n#define\tWUFmtW\t\t\t\t\t\tWUFormatW\r\n#define WUFmt\t\t\t\t\t\tWUFormat\r\n#define WULastErrMsg()\t\t\t\tWUSysMessage(::GetLastError())\r\n#define WULastErrMsgA()\t\t\t\tWUSysMessageA(::GetLastError())\r\n#define WULastErrMsgW()\t\t\t\tWUSysMessageW(::GetLastError())\r\n\r\n\r\n// -----------------------------------------------------------------------------\r\n// FUNCTIONAL COMPARATORS:\r\n// REMARKS:\r\n//\t\tThese structs are derived from the std::binary_function template.  They\r\n//\t\tgive us functional classes (which may be used in Standard C++ Library\r\n//\t\tcollections and algorithms) that perform case-insensitive comparisons of\r\n//\t\tCStdString objects.  This is useful for maps in which the key may be the\r\n//\t\t proper string but in the wrong case.\r\n// -----------------------------------------------------------------------------\r\n#define StdStringLessNoCaseW\t\tSSLNCW\t// avoid VC compiler warning 4786\r\n#define StdStringEqualsNoCaseW\t\tSSENCW\t\t\r\n#define StdStringLessNoCaseA\t\tSSLNCA\t\t\r\n#define StdStringEqualsNoCaseA\t\tSSENCA\t\t\r\n\r\n#ifdef UNICODE\r\n\t#define StdStringLessNoCase\t\tSSLNCW\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCW\t\t\r\n#else\r\n\t#define StdStringLessNoCase\t\tSSLNCA\t\t\r\n\t#define StdStringEqualsNoCase\tSSENCA\t\t\r\n#endif\r\n\r\nstruct StdStringLessNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseW\r\n\t: std::binary_function<CStdStringW, CStdStringW, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringW& sLeft, const CStdStringW& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\nstruct StdStringLessNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) < 0; }\r\n};\r\nstruct StdStringEqualsNoCaseA\r\n\t: std::binary_function<CStdStringA, CStdStringA, bool>\r\n{\r\n\tinline\r\n\tbool operator()(const CStdStringA& sLeft, const CStdStringA& sRight) const\r\n\t{ return ssicmp(sLeft.c_str(), sRight.c_str()) == 0; }\r\n};\r\n\r\n// If we had to define our own version of TRACE above, get rid of it now\r\n\r\n#ifdef TRACE_DEFINED_HERE\r\n\t#undef TRACE\r\n\t#undef TRACE_DEFINED_HERE\r\n#endif\r\n\r\n\r\n// These std::swap specializations come courtesy of Mike Crusader. \r\n\r\n//namespace std\r\n//{\r\n//\tinline void swap(CStdStringA& s1, CStdStringA& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//\ttemplate<>\r\n//\tinline void swap(CStdStringW& s1, CStdStringW& s2) throw()\r\n//\t{\r\n//\t\ts1.swap(s2);\r\n//\t}\r\n//}\r\n\r\n// Turn back on any Borland warnings we turned off.\r\n\r\n#ifdef __BORLANDC__\r\n    #pragma option pop  // Turn back on inline function warnings\r\n//\t#pragma warn +inl   // Turn back on inline function warnings\r\n#endif\r\n\r\n#endif\t// #ifndef STDSTRING_H\r\n"
  },
  {
    "path": "plugins/wmp/StdStringArray.cpp",
    "content": "\r\n#include \"StdAfx.h\"\r\n#include \"StdStringArray.h\"\r\n\r\n#ifdef _DEBUG\r\n#if !defined(ASSERT_VALID)\r\n#define ASSERT_VALID(x)\t\t\t\t\t\t\t\t\t\\\r\n\tASSERT(!IsBadReadPtr(x, sizeof(CStdStringArray)));\t\\\r\n\tx->AssertValid();\r\n#endif\r\n#else\r\n#define ASSERT_VALID(x)\r\n#endif\r\n\r\ntemplate<class TYPE>\r\nvoid ConstructElements(TYPE* pElements, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pElements, nCount * sizeof(TYPE)));\r\n\r\n\t// first do bit-wise zero initialization\r\n\tmemset((void*)pElements, 0, nCount * sizeof(TYPE));\r\n\r\n\t// then call the constructor(s)\r\n\tfor (; nCount--; pElements++)\r\n\t\t::new((void*)pElements) TYPE;\r\n}\r\n\r\n\r\n\r\ntemplate<class TYPE>\r\nvoid DestructElements(TYPE* pElements, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pElements, nCount * sizeof(TYPE)));\r\n\r\n\t// call the destructor(s)\r\n\tfor (; nCount--; pElements++)\r\n\t\tpElements->~TYPE();\r\n}\r\n\r\n\r\n\r\ntemplate<class TYPE>\r\nvoid CopyElements(TYPE* pDest, const TYPE* pSrc, int nCount)\r\n{\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pDest, nCount * sizeof(TYPE)));\r\n\tASSERT(nCount == 0 ||\r\n\t\t!IsBadReadPtr(pSrc, nCount * sizeof(TYPE)));\r\n\r\n\t// default is element-copy using assignment\r\n\twhile (nCount--)\r\n\t\t*pDest++ = *pSrc++;\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nCStdStringArray::CStdStringArray()\r\n{\r\n\tm_pData = NULL;\r\n\tm_nSize = m_nMaxSize = m_nGrowBy = 0;\r\n}\r\n\r\nCStdStringArray::~CStdStringArray()\r\n{\r\n\tASSERT_VALID(this);\r\n\r\n\tDestructElements(m_pData, m_nSize);\r\n\tdelete[] (BYTE*)m_pData;\r\n}\r\n\r\nvoid CStdStringArray::SetSize(int nNewSize, int nGrowBy)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nNewSize >= 0);\r\n\r\n\tif (nGrowBy != -1)\r\n\t\tm_nGrowBy = nGrowBy;  // set new size\r\n\r\n\tif (nNewSize == 0)\r\n\t{\r\n\t\t// shrink to nothing\r\n\r\n\t\tDestructElements(m_pData, m_nSize);\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = NULL;\r\n\t\tm_nSize = m_nMaxSize = 0;\r\n\t}\r\n\telse if (m_pData == NULL)\r\n\t{\r\n\t\t// create one with exact size\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(nNewSize <= SIZE_T_MAX/sizeof(CStdString));    // no overflow\r\n#endif\r\n\t\tm_pData = (CStdString*) new BYTE[nNewSize * sizeof(CStdString)];\r\n\r\n\t\tConstructElements(m_pData, nNewSize);\r\n\r\n\t\tm_nSize = m_nMaxSize = nNewSize;\r\n\t}\r\n\telse if (nNewSize <= m_nMaxSize)\r\n\t{\r\n\t\t// it fits\r\n\t\tif (nNewSize > m_nSize)\r\n\t\t{\r\n\t\t\t// initialize the new elements\r\n\r\n\t\t\tConstructElements(&m_pData[m_nSize], nNewSize-m_nSize);\r\n\r\n\t\t}\r\n\r\n\t\telse if (m_nSize > nNewSize)  // destroy the old elements\r\n\t\t\tDestructElements(&m_pData[nNewSize], m_nSize-nNewSize);\r\n\r\n\t\tm_nSize = nNewSize;\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// otherwise, grow array\r\n\t\tint nGrowBy = m_nGrowBy;\r\n\t\tif (nGrowBy == 0)\r\n\t\t{\r\n\t\t\t// heuristically determine growth when nGrowBy == 0\r\n\t\t\t//  (this avoids heap fragmentation in many situations)\r\n\t\t\tnGrowBy = min(1024, max(4, m_nSize / 8));\r\n\t\t}\r\n\t\tint nNewMax;\r\n\t\tif (nNewSize < m_nMaxSize + nGrowBy)\r\n\t\t\tnNewMax = m_nMaxSize + nGrowBy;  // granularity\r\n\t\telse\r\n\t\t\tnNewMax = nNewSize;  // no slush\r\n\r\n\t\tASSERT(nNewMax >= m_nMaxSize);  // no wrap around\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(nNewMax <= SIZE_T_MAX/sizeof(CStdString)); // no overflow\r\n#endif\r\n\t\tCStdString* pNewData = (CStdString*) new BYTE[nNewMax * sizeof(CStdString)];\r\n\r\n\t\t// copy new data from old\r\n\t\tmemcpy(pNewData, m_pData, m_nSize * sizeof(CStdString));\r\n\r\n\t\t// construct remaining elements\r\n\t\tASSERT(nNewSize > m_nSize);\r\n\r\n\t\tConstructElements(&pNewData[m_nSize], nNewSize-m_nSize);\r\n\r\n\r\n\t\t// get rid of old stuff (note: no destructors called)\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = pNewData;\r\n\t\tm_nSize = nNewSize;\r\n\t\tm_nMaxSize = nNewMax;\r\n\t}\r\n}\r\n\r\nint CStdStringArray::Append(const CStdStringArray& src)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(this != &src);   // cannot append to itself\r\n\r\n\tint nOldSize = m_nSize;\r\n\tSetSize(m_nSize + src.m_nSize);\r\n\r\n\tCopyElements(m_pData + nOldSize, src.m_pData, src.m_nSize);\r\n\r\n\treturn nOldSize;\r\n}\r\n\r\nvoid CStdStringArray::Copy(const CStdStringArray& src)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(this != &src);   // cannot append to itself\r\n\r\n\tSetSize(src.m_nSize);\r\n\r\n\tCopyElements(m_pData, src.m_pData, src.m_nSize);\r\n\r\n}\r\n\r\nvoid CStdStringArray::FreeExtra()\r\n{\r\n\tASSERT_VALID(this);\r\n\r\n\tif (m_nSize != m_nMaxSize)\r\n\t{\r\n\t\t// shrink to desired size\r\n#ifdef SIZE_T_MAX\r\n\t\tASSERT(m_nSize <= SIZE_T_MAX/sizeof(CStdString)); // no overflow\r\n#endif\r\n\t\tCStdString* pNewData = NULL;\r\n\t\tif (m_nSize != 0)\r\n\t\t{\r\n\t\t\tpNewData = (CStdString*) new BYTE[m_nSize * sizeof(CStdString)];\r\n\t\t\t// copy new data from old\r\n\t\t\tmemcpy(pNewData, m_pData, m_nSize * sizeof(CStdString));\r\n\t\t}\r\n\r\n\t\t// get rid of old stuff (note: no destructors called)\r\n\t\tdelete[] (BYTE*)m_pData;\r\n\t\tm_pData = pNewData;\r\n\t\tm_nMaxSize = m_nSize;\r\n\t}\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\nvoid CStdStringArray::SetAtGrow(int nIndex, LPCTSTR newElement)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t\tSetSize(nIndex+1);\r\n\tm_pData[nIndex] = newElement;\r\n}\r\n\r\n\r\nvoid CStdStringArray::SetAtGrow(int nIndex, const CStdString& newElement)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t\tSetSize(nIndex+1);\r\n\tm_pData[nIndex] = newElement;\r\n}\r\n\r\n\r\n\r\nvoid CStdStringArray::InsertEmpty(int nIndex, int nCount)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);    // will expand to meet need\r\n\tASSERT(nCount > 0);     // zero or negative size not allowed\r\n\r\n\tif (nIndex >= m_nSize)\r\n\t{\r\n\t\t// adding after the end of the array\r\n\t\tSetSize(nIndex + nCount);  // grow so nIndex is valid\r\n\t}\r\n\telse\r\n\t{\r\n\t\t// inserting in the middle of the array\r\n\t\tint nOldSize = m_nSize;\r\n\t\tSetSize(m_nSize + nCount);  // grow it to new size\r\n\t\t// shift old data up to fill gap\r\n\t\tmemmove(&m_pData[nIndex+nCount], &m_pData[nIndex],\r\n\t\t\t(nOldSize-nIndex) * sizeof(CStdString));\r\n\r\n\t\t// re-init slots we copied from\r\n\r\n\t\tConstructElements(&m_pData[nIndex], nCount);\r\n\r\n\t}\r\n\r\n\t// insert new value in the gap\r\n\tASSERT(nIndex + nCount <= m_nSize);\r\n}\r\n\r\n\r\nvoid CStdStringArray::InsertAt(int nIndex, LPCTSTR newElement, int nCount)\r\n{\r\n\r\n\t// make room for new elements\r\n\tInsertEmpty(nIndex, nCount);\r\n\r\n\r\n\r\n\t// copy elements into the empty space\r\n\tCStdString temp = newElement;\r\n\twhile (nCount--)\r\n\t\tm_pData[nIndex++] = temp;\r\n\r\n}\r\n\r\n\r\nvoid CStdStringArray::InsertAt(int nIndex, const CStdString& newElement, int nCount)\r\n{\r\n\t// make room for new elements\r\n\tInsertEmpty(nIndex, nCount);\r\n\r\n\t// copy elements into the empty space\r\n\twhile (nCount--)\r\n\t\tm_pData[nIndex++] = newElement;\r\n}\r\n\r\n\r\nvoid CStdStringArray::RemoveAt(int nIndex, int nCount)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(nIndex >= 0);\r\n\tASSERT(nCount >= 0);\r\n\tASSERT(nIndex + nCount <= m_nSize);\r\n\r\n\t// just remove a range\r\n\tint nMoveCount = m_nSize - (nIndex + nCount);\r\n\r\n\tDestructElements(&m_pData[nIndex], nCount);\r\n\r\n\tif (nMoveCount)\r\n\t\tmemmove(&m_pData[nIndex], &m_pData[nIndex + nCount],\r\n\t\t\tnMoveCount * sizeof(CStdString));\r\n\tm_nSize -= nCount;\r\n}\r\n\r\nvoid CStdStringArray::InsertAt(int nStartIndex, CStdStringArray* pNewArray)\r\n{\r\n\tASSERT_VALID(this);\r\n\tASSERT(pNewArray != NULL);\r\n\tASSERT_VALID(pNewArray);\r\n\tASSERT(nStartIndex >= 0);\r\n\r\n\tif (pNewArray->GetSize() > 0)\r\n\t{\r\n\t\tInsertAt(nStartIndex, pNewArray->GetAt(0), pNewArray->GetSize());\r\n\t\tfor (int i = 0; i < pNewArray->GetSize(); i++)\r\n\t\t\tSetAt(nStartIndex + i, pNewArray->GetAt(i));\r\n\t}\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Diagnostics\r\n\r\n#ifdef _DEBUG\r\nvoid CStdStringArray::AssertValid() const\r\n{\r\n\tif (m_pData == NULL)\r\n\t{\r\n\t\tASSERT(m_nSize == 0);\r\n\t\tASSERT(m_nMaxSize == 0);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tASSERT(m_nSize >= 0);\r\n\t\tASSERT(m_nMaxSize >= 0);\r\n\t\tASSERT(m_nSize <= m_nMaxSize);\r\n\t\tASSERT(!IsBadReadPtr(m_pData, m_nMaxSize * sizeof(CStdString)));\r\n\t}\r\n}\r\n#endif //_DEBUG\r\n"
  },
  {
    "path": "plugins/wmp/StdStringArray.h",
    "content": "////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n#include \"StdString.h\"\r\n\r\nclass CStdStringArray \r\n{\r\npublic:\r\n\r\n// Construction\r\n\tCStdStringArray();\r\n\r\n// Attributes\r\n\tint GetSize() const;\r\n\tint GetUpperBound() const;\r\n\tvoid SetSize(int nNewSize, int nGrowBy = -1);\r\n\r\n// Operations\r\n\t// Clean up\r\n\tvoid FreeExtra();\r\n\tvoid RemoveAll();\r\n\r\n\t// Accessing elements\r\n\tCStdString GetAt(int nIndex) const;\r\n\tvoid SetAt(int nIndex, LPCTSTR newElement);\r\n\r\n\tvoid SetAt(int nIndex, const CStdString& newElement);\r\n\r\n\tCStdString& ElementAt(int nIndex);\r\n\r\n\t// Direct Access to the element data (may return NULL)\r\n\tconst CStdString* GetData() const;\r\n\tCStdString* GetData();\r\n\r\n\t// Potentially growing the array\r\n\tvoid SetAtGrow(int nIndex, LPCTSTR newElement);\r\n\r\n\tvoid SetAtGrow(int nIndex, const CStdString& newElement);\r\n\r\n\tint Add(LPCTSTR newElement);\r\n\r\n\tint Add(const CStdString& newElement);\r\n\r\n\tint Append(const CStdStringArray& src);\r\n\tvoid Copy(const CStdStringArray& src);\r\n\r\n\t// overloaded operator helpers\r\n\tCStdString operator[](int nIndex) const;\r\n\tCStdString& operator[](int nIndex);\r\n\r\n\t// Operations that move elements around\r\n\tvoid InsertAt(int nIndex, LPCTSTR newElement, int nCount = 1);\r\n\r\n\tvoid InsertAt(int nIndex, const CStdString& newElement, int nCount = 1);\r\n\r\n\tvoid RemoveAt(int nIndex, int nCount = 1);\r\n\tvoid InsertAt(int nStartIndex, CStdStringArray* pNewArray);\r\n\r\n// Implementation\r\nprotected:\r\n\tCStdString* m_pData;   // the actual array of data\r\n\tint m_nSize;     // # of elements (upperBound - 1)\r\n\tint m_nMaxSize;  // max allocated\r\n\tint m_nGrowBy;   // grow amount\r\n\r\n\tvoid InsertEmpty(int nIndex, int nCount);\r\n\r\n\r\npublic:\r\n\t~CStdStringArray();\r\n\r\n#ifdef _DEBUG\r\n\tvoid AssertValid() const;\r\n#endif\r\n\r\nprotected:\r\n\t// local typedefs for class templates\r\n\ttypedef CStdString BASE_TYPE;\r\n\ttypedef LPCTSTR BASE_ARG_TYPE;\r\n};\r\n\r\n\r\n\r\n\r\ninline int CStdStringArray::GetSize() const\r\n\t{ return m_nSize; }\r\ninline int CStdStringArray::GetUpperBound() const\r\n\t{ return m_nSize-1; }\r\ninline void CStdStringArray::RemoveAll()\r\n\t{ SetSize(0); }\r\ninline CStdString CStdStringArray::GetAt(int nIndex) const\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\treturn m_pData[nIndex]; }\r\ninline void CStdStringArray::SetAt(int nIndex, LPCTSTR newElement)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\tm_pData[nIndex] = newElement; }\r\n\r\ninline void CStdStringArray::SetAt(int nIndex, const CStdString& newElement)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\tm_pData[nIndex] = newElement; }\r\n\r\ninline CStdString& CStdStringArray::ElementAt(int nIndex)\r\n\t{ ASSERT(nIndex >= 0 && nIndex < m_nSize);\r\n\t\treturn m_pData[nIndex]; }\r\ninline const CStdString* CStdStringArray::GetData() const\r\n\t{ return (const CStdString*)m_pData; }\r\ninline CStdString* CStdStringArray::GetData()\r\n\t{ return (CStdString*)m_pData; }\r\ninline int CStdStringArray::Add(LPCTSTR newElement)\r\n\t{ int nIndex = m_nSize;\r\n\t\tSetAtGrow(nIndex, newElement);\r\n\t\treturn nIndex; }\r\n\r\ninline int CStdStringArray::Add(const CStdString& newElement)\r\n\t{ int nIndex = m_nSize;\r\n\t\tSetAtGrow(nIndex, newElement);\r\n\t\treturn nIndex; }\r\n\r\ninline CStdString CStdStringArray::operator[](int nIndex) const\r\n\t{ return GetAt(nIndex); }\r\ninline CStdString& CStdStringArray::operator[](int nIndex)\r\n\t{ return ElementAt(nIndex); }\r\n\r\n\r\n"
  },
  {
    "path": "plugins/wmp/VersionApp.cpp",
    "content": "// VersionApp.cpp: Implementierung der Klasse CVersionApp.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n#include \"VersionApp.h\"\r\n#include <winver.h>\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// Konstruktion/Destruktion\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nCVersionApp::CVersionApp()\r\n{\r\n\tRefresh();\r\n}\r\n\r\nCVersionApp::~CVersionApp()\r\n{\r\n}\r\n\r\nvoid CVersionApp::Refresh(HINSTANCE hInstance /* = NULL */)\r\n{\r\n\tif(hInstance != NULL)\r\n\t\tm_hInstance = hInstance;\r\n\r\n\tm_strOSVersion = \"\";\r\n\t\r\n\tReadResourceInformation();\r\n\tReadFileTime();\r\n}\r\n\r\nBOOL CVersionApp::ReadResourceInformation()\r\n{\r\n\tDWORD\tdwLength, dwSize, dwNullHandle;\r\n\tTCHAR\tszFileName [MAX_PATH];\r\n\tLPVOID\tlpVersionPtr;\r\n\tUINT\tuiVerLength;\r\n\t\r\n\t\r\n\tdwSize = sizeof (szFileName) / sizeof (szFileName [0]);\r\n\tdwLength = ::GetModuleFileName (m_hInstance, szFileName, dwSize);\r\n\tif (dwLength <= 0) \r\n\t\treturn FALSE;\r\n\r\n\tm_VersionInfo.sFilePath=szFileName;\r\n\tdwLength = ::GetFileVersionInfoSize (szFileName, &dwNullHandle);\r\n\tif (dwLength <= 0) \r\n\t\treturn FALSE;\r\n\r\n\tBYTE* pVersionInfo = new BYTE [dwLength];\r\n\tif (!::GetFileVersionInfo (szFileName, NULL, dwLength, pVersionInfo)) \r\n\t\treturn FALSE;\t\r\n\tif (!::VerQueryValue (pVersionInfo, _T (\"\\\\\"), &lpVersionPtr, &uiVerLength)) \r\n\t\treturn FALSE;\r\n\r\n\tm_VersionInfo.vsFixedFileInfo = *(VS_FIXEDFILEINFO*)lpVersionPtr;\r\n\t\r\n\tif (!GetDynamicInfo(pVersionInfo)) \r\n\t\treturn FALSE;\t\r\n\tif (!GetFixedFileInfo ()) \r\n\t\treturn FALSE;\r\n\t\r\n\tdelete pVersionInfo;\t\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CVersionApp::GetFixedFileInfo()\r\n{\r\n\tm_VersionInfo.stMinorVersion.Format(\"%d%d\",HIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS));\r\n\tm_VersionInfo.stMajorVersion.Format(\"%d\",LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS));\r\n\tm_VersionInfo.stDllVersion.Format (\"%d.%d.%d.%d\", \r\n\t\tHIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionMS),\r\n\t\tHIWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS), LOWORD (m_VersionInfo.vsFixedFileInfo.dwFileVersionLS));\r\n\r\n\tif (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_DRV)\r\n\t{\r\n\t\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileSubtype) \r\n\t\t{\r\n\t\t\tcase VFT2_DRV_DISPLAY:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Display driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_INSTALLABLE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Installable driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_KEYBOARD:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Keyboard driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_LANGUAGE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Language driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_MOUSE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Mouse driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_NETWORK:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Network driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_PRINTER:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Printer driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_SOUND:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Sound driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_DRV_SYSTEM:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"System driver\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_UNKNOWN:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Unknown driver\");\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_FONT) \r\n\t{\r\n\t\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileSubtype) \r\n\t\t{\r\n\t\t\tcase VFT2_FONT_RASTER:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Raster font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_FONT_TRUETYPE:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Truetype font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_FONT_VECTOR:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Vector font\");\r\n\t\t\t\tbreak;\r\n\t\t\tcase VFT2_UNKNOWN:\r\n\t\t\t\tm_VersionInfo.stFileType = _T (\"Unknown font\");\r\n\t\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_APP) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Application\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_DLL) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Dynamic link library\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_STATIC_LIB) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Static link library\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_VXD) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Virtual device\");\r\n\t}\r\n\telse if (m_VersionInfo.vsFixedFileInfo.dwFileType == VFT_UNKNOWN) \r\n\t{\r\n\t\tm_VersionInfo.stFileType = _T (\"Unknown type\");\r\n\t}\r\n\r\n\tswitch (m_VersionInfo.vsFixedFileInfo.dwFileOS) \r\n\t{\r\n\t\tcase VOS_DOS:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_DOS_WINDOWS16:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit windows running on MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_DOS_WINDOWS32:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Win32 API running on MS-DOS\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS216:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS216_PM16:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"16-bit Presentation manager running on 16-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_OS232:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"32-bit OS/2\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_NT:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Windows NT\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_NT_WINDOWS32:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Win32 API on Windows NT\");\r\n\t\t\tbreak;\r\n\t\tcase VOS_UNKNOWN:\r\n\t\t\tm_VersionInfo.stFileOS = _T (\"Unknown OS\");\r\n\t\t\tbreak;\r\n\t}\r\n\r\n\treturn (true);\r\n}\r\n\r\nBOOL CVersionApp::GetDynamicInfo(BYTE *pVersionInfo)\r\n{\r\n\tUINT\tuiVerLength;\r\n\tLPVOID\tlpPtr;\r\n\tCStdString\tsQuery;\r\n\t\t\r\n\r\n\tif (::VerQueryValue (pVersionInfo, \"\\\\VarFileInfo\\\\Translation\", &lpPtr, &uiVerLength))\r\n\t\tm_VersionInfo.Translation = *(VERSION_INFORMATION::TRANSLATE*)lpPtr;\r\n\t\r\n\tsQuery.Format (\t_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\CompanyName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stCompany=CStdString((LPCTSTR)lpPtr);\r\n\t\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\LegalCopyRight\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stCopyRight=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\ProductName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stProductName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\ProductVersion\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stProductVersion=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\OriginalFileName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stOriginalName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\FileDescription\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stDescription=CStdString((LPCTSTR)lpPtr);\r\n\t\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\FileVersion\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stFileVersion=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\InternalName\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stInternalName=CStdString((LPCTSTR)lpPtr);\r\n\r\n\tsQuery.Format (_T (\"\\\\StringFileInfo\\\\%04x%04x\\\\PrivateBuild\"),m_VersionInfo.Translation.languageId, m_VersionInfo.Translation.characterSet);\r\n\t::VerQueryValue (pVersionInfo, (LPTSTR)(LPCTSTR)sQuery, (LPVOID*)&lpPtr,&uiVerLength);\r\n\tm_VersionInfo.stPrivateBuild=CStdString((LPCTSTR)lpPtr);\r\n\r\n\treturn TRUE;\r\n}\r\n\r\nBOOL CVersionApp::ReadFileTime()\r\n{\r\n\tFILE* pFile = NULL;\r\n\r\n\tif( (!m_VersionInfo.sFilePath.IsEmpty()) && \r\n\t\t  (pFile = fopen(m_VersionInfo.sFilePath,\"r\")) != NULL)\r\n\t{\r\n\t\tBOOL bRet = GetFileTime(pFile,&m_CreationTime,&m_LastAccessTime,&m_LastWriteTime);\r\n\t\tfclose(pFile);\r\n\t\treturn bRet;\r\n\t}\r\n\treturn FALSE;\r\n}\r\n\r\nCStdString CVersionApp::GetOSVersion()\r\n{\r\n\tTCHAR sText[512];\r\n  TCHAR sBuf[100];\r\n  COSVersion os;\r\n\tCOSVersion::OS_VERSION_INFO osvi;\r\n  memset(&osvi, 0, sizeof(osvi));\r\n    \r\n  if (os.GetVersion(&osvi))\r\n  {\r\n    _stprintf(sText, _T(\"\"));\r\n    \r\n    switch (osvi.UnderlyingPlatform)\r\n    {\r\n      case COSVersion::Dos:               \r\n      {\r\n        _tcscat(sText, _T(\"DOS\"));                \r\n        break;\r\n      }\r\n      case COSVersion::Windows3x:         \r\n      {\r\n        _tcscat(sText, _T(\"Windows\"));        \r\n        if (os.IsWin32sInstalled(&osvi))\r\n          _tcscat(sText, _T(\" (Win32s)\"));\r\n        break;\r\n      }\r\n      case COSVersion::WindowsCE:\r\n      {\r\n        _tcscat(sText, _T(\"Windows CE\"));        \r\n        break;\r\n      }\r\n      case COSVersion::Windows9x:\r\n      {\r\n        if (os.IsWindows95(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95\"));\r\n        else if (os.IsWindows95SP1(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95 SP1\"));\r\n        else if (os.IsWindows95OSR2(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 95 OSR2\"));\r\n        else if (os.IsWindows98(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98\"));\r\n        else if (os.IsWindows98SP1(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98 SP1\"));\r\n        else if (os.IsWindows98SE(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows 98 Second Edition\"));\r\n        else if (os.IsWindowsME(&osvi))\r\n          _stprintf(sBuf, _T(\"Windows Millenium Edition\"));\r\n        else\r\n          _stprintf(sBuf, _T(\"Windows ??\"));\r\n        _tcscat(sText, sBuf);          \r\n        break;\r\n      }\r\n      case COSVersion::WindowsNT:\r\n      {\r\n        if (os.IsNTPreWin2k(&osvi))\r\n        {\r\n          _tcscat(sText, _T(\"Windows NT\"));          \r\n\r\n          if (os.IsNTWorkstation(&osvi))\r\n            _tcscat(sText, _T(\" (Workstation)\"));\r\n          else if (os.IsNTStandAloneServer(&osvi))\r\n            _tcscat(sText, _T(\" (Server)\"));\r\n          else if (os.IsNTPDC(&osvi))\r\n            _tcscat(sText, _T(\" (Primary Domain Controller)\"));\r\n          else if (os.IsNTBDC(&osvi))\r\n            _tcscat(sText, _T(\" (Backup Domain Controller)\"));\r\n\r\n          if (os.IsNTDatacenterServer(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter)\"));\r\n          else if (os.IsNTEnterpriseServer(&osvi))\r\n            _tcscat(sText, _T(\", (Enterprise)\"));\r\n        }\r\n        else if (os.IsWindows2000(&osvi))\r\n        {\r\n          _tcscat(sText, _T(\"Windows 2000\"));          \r\n\r\n          if (os.IsWin2000Professional(&osvi))\r\n            _tcscat(sText, _T(\" (Professional)\"));\r\n          else if (os.IsWin2000Server(&osvi))\r\n            _tcscat(sText, _T(\" (Server)\"));\r\n          else if (os.IsWin2000DomainController(&osvi))\r\n            _tcscat(sText, _T(\" (Domain Controller)\"));\r\n\r\n          if (os.IsWin2000DatacenterServer(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter)\"));\r\n          else if (os.IsWin2000AdvancedServer(&osvi))\r\n            _tcscat(sText, _T(\", (Advanced Server)\"));\r\n        }\r\n        else if (os.IsWindowsXPOrWindowsServer2003(&osvi))\r\n        {\r\n          if (os.IsXPPersonal(&osvi))\r\n            _tcscat(sText, _T(\"Windows XP (Personal)\"));          \r\n          else if (os.IsXPProfessional(&osvi))\r\n            _tcscat(sText, _T(\"Windows XP (Professional)\"));          \r\n          else if (os.IsWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\"Windows Server 2003\"));          \r\n          else if (os.IsDomainControllerWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\"Windows Server 2003 (Domain Controller)\"));          \r\n\r\n          if (os.IsDatacenterWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Datacenter Edition)\"));\r\n          else if (os.IsEnterpriseWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Enterprise Edition)\"));\r\n          else if (os.IsWebWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Web Edition)\"));\r\n          else if (os.IsWindowsServer2003(&osvi))\r\n            _tcscat(sText, _T(\", (Standard Edition)\"));\r\n        }\r\n\r\n/*        if (os.IsTerminalServicesInstalled(&osvi))\r\n          _tcscat(sText, _T(\", (Terminal Services)\"));\r\n        if (os.ISSmallBusinessEditionInstalled(&osvi))\r\n          _tcscat(sText, _T(\", (BackOffice Small Business Edition)\"));\r\n        if (os.IsEmbedded(&osvi))\r\n          _tcscat(sText, _T(\", (Embedded)\"));\r\n        if (os.IsTerminalServicesInRemoteAdminMode(&osvi))\r\n          _tcscat(sText, _T(\", (Terminal Services in Remote Admin Mode)\"));\r\n        if (os.IsEmulated64Bit(&osvi))\r\n          _tcscat(sText, _T(\", (64 Bit Edition)\"));*/\r\n\r\n        if (osvi.dwSuiteMask & OSSUITE_UNIPROCESSOR_FREE)\r\n          _tcscat(sText, _T(\", (Uniprocessor Free)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_UNIPROCESSOR_CHECKED)\r\n          _tcscat(sText, _T(\", (Uniprocessor Checked)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_MULTIPROCESSOR_FREE)\r\n          _tcscat(sText, _T(\", (Multiprocessor Free)\"));\r\n        else if (osvi.dwSuiteMask & OSSUITE_MULTIPROCESSOR_CHECKED)\r\n          _tcscat(sText, _T(\", (Multiprocessor Checked)\"));\r\n\r\n        break;\r\n      }\r\n      default: \r\n      {\r\n        _stprintf(sBuf, _T(\"Unknown OS\"));\r\n        break;\r\n      }\r\n    }                     \r\n    _stprintf(sBuf, _T(\" v%d.\"), osvi.dwEmulatedMajorVersion);\r\n    _tcscat(sText, sBuf);     \r\n    if (osvi.dwEmulatedMinorVersion % 10)\r\n    {\r\n      if (osvi.dwEmulatedMinorVersion > 9)\r\n        _stprintf(sBuf, _T(\"%02d\"), osvi.dwEmulatedMinorVersion);\r\n      else\r\n        _stprintf(sBuf, _T(\"%01d\"), osvi.dwEmulatedMinorVersion);\r\n    }\r\n    else\r\n      _stprintf(sBuf, _T(\"%01d\"), osvi.dwEmulatedMinorVersion / 10);\r\n    _tcscat(sText, sBuf);                           \r\n    if (osvi.dwEmulatedBuildNumber)\r\n    {\r\n      _stprintf(sBuf, _T(\" Build:%d\"), osvi.dwEmulatedBuildNumber);\r\n      _tcscat(sText, sBuf);           \r\n    }\r\n    if (osvi.wEmulatedServicePackMajor)       \r\n    {\r\n      if (osvi.wEmulatedServicePackMinor)\r\n      {\r\n        //Handle the special case of NT 4 SP 6a which Dtwinver ver treats as SP 6.1\r\n        if (os.IsNTPreWin2k(&osvi) && (osvi.wEmulatedServicePackMajor == 6) && (osvi.wEmulatedServicePackMinor == 1))\r\n          _stprintf(sBuf, _T(\" Service Pack: 6a\"));\r\n        //Handle the special case of XP SP 1a which Dtwinver ver treats as SP 1.1\r\n        else if (os.IsWindowsXP(&osvi) && (osvi.wEmulatedServicePackMajor == 1) && (osvi.wEmulatedServicePackMinor == 1))\r\n          _stprintf(sBuf, _T(\" Service Pack: 1a\"));\r\n        else       \r\n          _stprintf(sBuf, _T(\" Service Pack:%d.%d\"), osvi.wEmulatedServicePackMajor, osvi.wEmulatedServicePackMinor);\r\n      }\r\n      else\r\n        _stprintf(sBuf, _T(\" Service Pack:%d\"), osvi.wEmulatedServicePackMajor);\r\n      _tcscat(sText, sBuf);\r\n    }                            \r\n    else\r\n    {\r\n      if (osvi.wEmulatedServicePackMinor)       \r\n        _stprintf(sBuf, _T(\" Service Pack:0.%d\"), osvi.wEmulatedServicePackMinor);\r\n    }\r\n\t}\r\n\telse\r\n\t\t_tcscat(sText, \"Failed in call to GetOSVersion\");\r\n\r\n\treturn CStdString(sText);\r\n}\r\n\r\nCStdString CVersionApp::GetWorkingDir()\r\n{\r\n\tchar filename[512];\r\n\tGetModuleFileName(m_hInstance,filename,sizeof(filename));\r\n\tCStdString Temp = filename;\r\n\tint pos = Temp.ReverseFind('\\\\');\r\n\tTemp = Temp.Left(pos + 1);\r\n\r\n\treturn Temp;\r\n}"
  },
  {
    "path": "plugins/wmp/VersionApp.h",
    "content": "// VersionApp.h: Schnittstelle fr die Klasse CVersionApp.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_)\r\n#define AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n#include \"StdString.h\"\r\n#include \"ComDATE.h\"\r\n#include \"OSVer.h\"\r\n\r\n#pragma comment(lib,\"version.lib\") \r\n\r\ntypedef struct tagVersionInformation\r\n{\r\n\tCStdString sFilePath;\r\n\tCStdString\tstCompany;\r\n\tCStdString\tstCopyRight;\r\n\tCStdString\tstDescription;\r\n\tCStdString\tstFileVersion;\r\n\tCStdString stMajorVersion;\r\n\tCStdString stMinorVersion;\r\n\tCStdString\tstInternalName;\r\n\tCStdString\tstOriginalName;\r\n\tCStdString\tstProductName;\r\n\tCStdString\tstProductVersion;\r\n\tCStdString\tstPrivateBuild;\r\n\tCStdString\tstDllVersion;\r\n\tCStdString\tstFileOS;\r\n\tCStdString\tstFileType;\r\n\tCStdString stLanguageId;\r\n\tCStdString stCharSet;\r\n\tVS_FIXEDFILEINFO vsFixedFileInfo;\r\n\tstruct TRANSLATE \r\n\t{\r\n\t\tWORD languageId;\r\n\t\tWORD characterSet;\r\n\t} Translation;\r\n}VERSION_INFORMATION, *LPVERSION_INFORMATION;\r\n\r\nclass CVersionApp  \r\n{\r\npublic:\t\r\n\tCVersionApp();\r\n\r\n\tvoid Refresh(HINSTANCE hInstance = NULL);\r\n\r\n\tCStdString GetAppVersion(){return m_VersionInfo.stFileVersion;}\r\n\tCStdString GetAppBuildDate(){return CComDATE(m_CreationTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppLastAccessDate(){return CComDATE(m_LastAccessTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppWriteDate(){return CComDATE(m_LastWriteTime).Format(\"%D/%m/%Y %H:%M:%S\");}\r\n\tCStdString GetAppFilepath(){return m_VersionInfo.sFilePath;}\r\n\tCStdString GetAppCopyright(){return m_VersionInfo.stCopyRight;}\r\n\tCStdString GetAppOriginalname(){return m_VersionInfo.stOriginalName;}\r\n\tCStdString GetAppCompany(){return m_VersionInfo.stCompany;}\r\n\tCStdString\tGetAppDescription(){return m_VersionInfo.stDescription;}\r\n\tCStdString GetAppInternalName(){return m_VersionInfo.stInternalName;}\r\n\tCStdString GetAppProductName(){return m_VersionInfo.stProductName;}\r\n\tCStdString GetAppProductVersion(){return m_VersionInfo.stProductVersion;}\r\n\tCStdString GetAppPrivateBuild(){return m_VersionInfo.stPrivateBuild;}\r\n\tCStdString GetAppMajorVersion(){return m_VersionInfo.stMajorVersion;}\r\n\tCStdString GetAppMinorVersion(){return m_VersionInfo.stMinorVersion;}\r\n\r\n\tCStdString GetOSVersion();\r\n\tCStdString GetWorkingDir();\r\n\r\n\tvirtual ~CVersionApp();\r\n\r\nprotected:\r\n\tBOOL ReadFileTime();\r\n\tBOOL GetFixedFileInfo();\r\n\tBOOL GetDynamicInfo(BYTE* pVersionInfo);\r\n\tBOOL ReadResourceInformation();\r\n\tVERSION_INFORMATION m_VersionInfo;\r\n\tFILETIME m_CreationTime,m_LastAccessTime,m_LastWriteTime;\r\n\tCStdString m_strOSVersion;\r\n\tHINSTANCE m_hInstance;\r\n};\r\n\r\n#endif // !defined(AFX_VersionApp_H__910C010B_5EC2_11D3_9EB9_0000E87CD125__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/wmp/WMPScrobbler.cpp",
    "content": "// WMPScrobbler.cpp: implementation of the CWMPScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#include \"stdafx.h\"\r\n#include \"WMPScrobbler.h\"\r\n\r\n//////////////////////////////////////////////////////////////////////\r\n// Construction/Destruction\r\n//////////////////////////////////////////////////////////////////////\r\n\r\nCWMPScrobbler::CWMPScrobbler()\r\n{\r\n\r\n}\r\n\r\nCWMPScrobbler::~CWMPScrobbler()\r\n{\r\n\r\n}\r\n"
  },
  {
    "path": "plugins/wmp/WMPScrobbler.h",
    "content": "// WMPScrobbler.h: interface for the CWMPScrobbler class.\r\n//\r\n//////////////////////////////////////////////////////////////////////\r\n\r\n#if !defined(AFX_WMPSCROBBLER_H__9E9C7CB2_8718_4C0C_8BA3_E5F7D55D5118__INCLUDED_)\r\n#define AFX_WMPSCROBBLER_H__9E9C7CB2_8718_4C0C_8BA3_E5F7D55D5118__INCLUDED_\r\n\r\n#if _MSC_VER > 1000\r\n#pragma once\r\n#endif // _MSC_VER > 1000\r\n\r\n#include \"Scrobbler.h\"\r\n\r\nclass CWMPScrobbler : public CScrobbler  \r\n{\r\npublic:\r\n\tCWMPScrobbler();\r\n\tvirtual ~CWMPScrobbler();\r\n\r\n};\r\n\r\n#endif // !defined(AFX_WMPSCROBBLER_H__9E9C7CB2_8718_4C0C_8BA3_E5F7D55D5118__INCLUDED_)\r\n"
  },
  {
    "path": "plugins/wmp/WhatsNew.txt",
    "content": "=================\r\n== What's New  ==\r\n=================\r\n\r\n19/11/07 2.1.0.5\r\n-------------------------------------------------------------------------------\r\nFixed stuck dialog when trying to import empty library.\r\n\r\n\r\n15/11/07 2.1.0.4\r\n-------------------------------------------------------------------------------\r\nBootstrapping added.\r\n\r\n\r\n31/7/07 2.0.29.0\r\n-------------------------------------------------------------------------------\r\nRecompiled with new ScrobSub for Vista compatibility.\r\n\r\n\r\n05/04/07 2.0.28.0\r\n------------------------\r\nAdded a check at startup to catch double-clicked tracks too.\r\nMoved log file to user's appdata folder.\r\n\r\n\r\n22/06/06 2.0.24.0\r\n------------------------\r\nRecompiled with new ScrobSub for the beta release of the new Last.fm client.\r\n\r\n\r\n11/04/2006 2.0.19.0\r\n------------------------\r\nAdded MMS: to excluded protocols. Allowed paths starting with \\\\. Added a Stop command on shutdown as WMP doesn't send a Stop otherwise. Fixed Stop not working in certain circumstances bug by checking for more conditions in IsStopped.\r\n\r\n\r\n22/03/2006 2.0.13.0\r\n------------------------\r\nFixed it so that it calls stop also when in paused state.\r\n\r\n\r\n22/03/2006 2.0.12.0\r\n------------------------\r\nChanged protocol to include Pause due to new AS progress indicator.\r\n\r\n\r\n20/03/2006 2.0.11.0\r\n------------------------\r\nFixed an off-by-one bug that converted artist or track names with one character wrong to UTF8.\r\n\r\n\r\n01/03/2006 2.0.2.0 (Erik)\r\n------------------------\r\nButchered plugin to work with new Audioscrobbler Service. All internet-related and caching functionality removed and ScrobSub installed for handling communication with AS.\r\n\r\n\r\n31/08/2005 1.1.10 (lozzd - laurie@denness.net)\r\n------------------------\r\nBug - Serious handshake/submissions server mismatch bug. \r\n\r\n\r\n21/02/2005 1.1.9 Beta 3\r\n------------------------\r\nChange - Can include/exclude directories individually now (+ bugfixes)\r\n\r\n12/01/2005 - 1.1.9 Beta 2\r\n--------------------------\r\nBug - Song length -1 for tracks for which the track length couldn't be determined. Now default this to 240 (4 mins)\r\n\r\n05/01/2005 - 1.1.9 Beta 1\r\n--------------------------\r\nBug - Plugin wouldn't load settings on Windows 95\r\nBug - Player pauses for 5 seconds when cannot determine track length\r\nBug - Handshaking in 945098734s.\r\nChange - Clearer handshake status messages\r\nChange - If the current song length cannot be determined (because Player won't tell me), the song is submitted after the default of 240s. \r\n        If the song is less than 240s long, the submission won't take place. Best I can do under the circumstances I'm afraid.\r\nChange - On HTTP Error drop connection and force a fresh handshake\r\n\r\n18/10/2004 - Build 613\r\n-----------------------\r\nSpib - Fix for 'Song length -1 not allowed'\r\nBug - Song shown twice in last played in config dialog\r\nChange - Tidied Config Dialog, removed logging option, added clear password button\r\nChange - If using Proxy Authentication, 'Proxy-Connection: Keep-Alive' added to connection\r\n\r\n07/10/2004 - Build 612\r\n-----------------------\r\nSpib - Remove song length limit\r\n\r\n29/09/2004 - Build 611\r\n-----------------------\r\nSpib - Bug where cache didn't send after server down fixed\r\nSpib - More info on Config dialog\r\nSpib - Fix for RegSvr32.exe error on install on Windows 98\r\n\r\n23/09/2004 - Build 610\r\n-----------------------\r\nSpib - Better handling of errors during server downtime\r\nSpib - Cache is sent more frequently but is now limited to 1000 tracks\r\nSpib - Better error messages in Config dialog when tracks are invalid\r\n\r\n22/09/2004 - Build 609\r\n-----------------------\r\nSpib - Don't submit new songs until the cache has been cleared\r\n\r\n16/09/2004 - Build 608\r\n-----------------------\r\nSpib - Fixed bug when trying to show config when plugin not enabled in WMP\r\n\r\n15/09/2004 - Build 607\r\n-----------------------\r\nSpib - Log file size is displayed correctly now\r\nSpib - New Installer\r\n\r\n01/09/2004 - Build 606\r\n-----------------------\r\nSpib - Sends cache less often (every 30 secs) to prevent server rejecting it\r\nSpib - Removed some unneeded playback checks\r\nSpib - Can hide upgrade info if required\r\nSpib - Improved proxy handling \r\n\r\n** 27/04/2004 - VERSION 1.1.7 Build 597 Released **\r\n\r\n27/04/2004\r\n-----------\r\nSpib - Removed Start menu shortcut and displaying of help file during installation\r\nSpib - Fixed bug where requests to audioscrobbler server were sometimes cached (on\r\n       ISP proxy or wherever). Should explain why some submissions have been going missing.\r\n\r\n26/04/2004\r\n----------\r\nSpib - Allow users to force the plugin to try to connect even if no internet\r\n       connection is detected.\r\n\r\n22/04/2004\r\n----------\r\nSpib - Message in Config dlg when not submitting because of untagged file\r\n\r\n20/04/2004\r\n----------\r\nSpib - Make sure last submission is properley deleted from memory\r\nSpib - Fixed CD Submissions\r\nSpib - Added ability to exclude or include files in certain directory paths\r\nSpib - Password can be cleared using the config dialog\r\n\r\n15/04/2004\r\n----------\r\nSpib - Unsupported file type errors should be fixed\r\nSpib - Only files which are TAGGED get submitted as specified in the protocol (guessing from filenames is not done)\r\nSpib - Errors display only into config dialog and log - no more messageboxes\r\nSpib - Cache submissions are logged to file\r\nSpib - Server errors causing new handshake are logged to file\r\nSpib - Minimum submit time is now 50% or 240s rather than 120s\r\n\r\n** 05/03/2004 - VERSION 1.1.6 Build 592 Released **\r\n\r\n24/01/2004\r\n----------\r\nSpib - Always ignore HTTP streams\r\n\r\n** 24/01/2004 - VERSION 1.1.5 Build 591 Released **\r\n\r\n24/01/2004\r\n----------\r\nSpib - Remember to update the build number this time\r\nSpib - Fix for info fields not cleared between submissions\r\n\r\n** 06/01/2004 - VERSION 1.1.4 Build 590 Released **\r\n\r\n06/01/2004\r\n----------\r\nSpib - Reconnects (handshakes) if no response received\r\nSpib - Fix buffer overrun\r\nSpib - Fix UTF8 encoding (thanks case)\r\nSpib - Ignore HTTP Streams on by default\r\nSpib - Send Cache in small pieces (10 submissions max by default)\r\nSpib - Server responses logged to file by default\r\nSpib - Support for v1.1 Protocol\r\nSpib - Version number bought in line with Winamp plugin\r\n\r\n** 17/07/2003 - VERSION 1.0.3 Build 115 Released **\r\n\r\n04/07/2003\r\n----------\r\nSpib - Minimum submit time is now 120s instead of 180s to bring in\r\n       line with the AS protocol.\r\nSpib - Fix for folks with system time set before Jan 2003.\r\nSpib - Additional logging.\r\nSpib - Further critical sections in CScrobbler\r\nSpib - If modem is installed but not used, plugin will try other connections now\r\n       rather than reporting no connections available\r\nSpib - Added 'forceconnection' hidden registry option to allow the user to\r\n       force the plugin to try to connect even if the plugin thinks there\r\n       is no internet connection available.\r\nSpib - Fixed crashbug in CCacheManager::Save() caused by array going\r\n       out of bounds.\r\nSpib - Fixed 'Enable Winamp Plugin' text in config dialog\r\n\r\n\r\n** 29/06/2003 - VERSION 1.0.2 Build 107 Released **\r\n\r\n29/06/2003\r\n----------\r\nSpib - Critical Sections in CCacheManager\r\n\r\n** 08/06/2003 - VERSION 1.0.1 Build 103 Released **\r\n\r\n08/06/2003\r\n----------\r\nSpib - Bugfix in CSubmission::Populate to catch long file ext\r\n\r\n** 23/05/2003 - VERSION 1.0.0 Build 98 Released **\r\n\r\n22/05/2003\r\n----------\r\nSpib - New version branched from Winamp 2.x plugin v1.1.0\r\n"
  },
  {
    "path": "plugins/wmp/comdate.h",
    "content": "// comdate.h\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Copyright (c) 1998-2000 Chris Sells\r\n// All rights reserved.\r\n//\r\n// NO WARRANTIES ARE EXTENDED. USE AT YOUR OWN RISK.\r\n//\r\n// To contact the author with suggestions or comments, use csells@sellsbrothers.com.\r\n/////////////////////////////////////////////////////////////////////////////\r\n// History:\r\n//  9/27/01 - Dropped in operator SYSTEMTIME() and operator FILETIME() from\r\n//            Scott Zionic [Scott.Zionic@petersweb.com]. Thanks, Scott.\r\n//  4/9/01  - Implemented operator time_t() and operator struct tm() as per\r\n//            Shawn Wildermuth's request.\r\n//  2/8/01  - Fixed a rounding bug in CComSpan reported by Ralf Mohaupt\r\n//            [r.mohaupt@lit.lineas.de].\r\n//  11/4/00 - Moved everything to the header file for convenience.\r\n//  4/13/00 - Sudhakar M [msudhakar@yahoo.com] contributed\r\n//            CComDATE(const struct tm& tmSrc), from which I also extrapolated\r\n//            CComDATE::operator=(const struct tm& tmSrc).\r\n//  3/10/00 - Inspired by Eric White [EricW@DATA-TECH.COM] to add an\r\n//            operator DBTIMESTAMP using his implementation. Also added\r\n//            extra ctor, operator= and conversion operators for other date/time\r\n//            formats, but haven't implemented all of them yet.\r\n//            Inspired by Artyom Tyazhelov [artyom6@hotmail.com] to\r\n//            leave current time alone when calling SetDate and leaving current\r\n//            date alone when calling SetTime.\r\n//  1/15/00 - Fixed a 2038 bug in Now. Thanks Michael Entin [entin@swusa.com].\r\n//  7/14/99 - Fixed a linker problem w/ some inline functions release\r\n//            builds. Thanks to David Maw [David.Maw@unisys.com] for\r\n//            first pointing it out.\r\n//   6/9/99 - Fixed a problem in Maketm where tm_isdst was not being set\r\n//            (as is required by the CRT). Thanks to Jim Hoffman\r\n//            [JHoffman@Enerx.com] for pointing it out.\r\n//  4/18/99 - Fixed a problem in Format to provide a work-around in the\r\n//            VC6 implementation of wcsftime. Thanks for Joe O'Leary for\r\n//            pointing it out.\r\n//            Even better, Joe also contributed FormatDate and FormatTime\r\n//            to wrap the National Language Support functions GetTimeFormat()\r\n//            and GetDateFormat(). Thanks, Joe!\r\n//            Also, Juan Rivera (juanc@kodak.com) pointed out a missing operator=\r\n//            declaration. Thanks, Juan.\r\n// 12/24/98 - Based on a suggestion by Ronald Laeremans [RonaldL@mvps.org],\r\n//            replaced all of the manual Maketm code w/ VariantToSystemTime.\r\n//            Also updated MakeDATE to use SystemTimeToVariantTime. Thanks, Ron!\r\n// 12/23/98 - Fixed a bug Ward pointed out in CComDATE::operator=(const time_t&).\r\n// 12/21/98 - Ward Fuller <wfuller@tsisoft.com> pointed out a BSTR leak in\r\n//            the Format implementation. It's plugged. Thanks, Ward!\r\n// 12/21/98 - Initial release.\r\n/////////////////////////////////////////////////////////////////////////////\r\n// The file provides two class for use with dates and times under Windows.\r\n//\r\n// CComDATE: Wraps the COM DATE type, providing conversions from VARIANT,\r\n//           DATE, ANSI string, UNICODE string, time_t, SYSTEMTIME, FILETIME,\r\n//           DOS time and DBTIMESTAMP data types.\r\n//\r\n// CComSpan: Represents the result of subtracting one CComDATE from another.\r\n//           Useful for time/date math.\r\n//\r\n// NOTE: This usage of these classes are based loosely on the MFC classes\r\n//       COleDateTime and COleDateTimeSpan. However, the implementation is 99% mine.\r\n\r\n#pragma once\r\n#ifndef __COMDATE_H__\r\n#define __COMDATE_H__\r\n\r\n#include <time.h>\r\n#include <limits.h>\r\n#include <tchar.h>\r\n#include <math.h>   // ceil, floor and modf\r\n#include <winnls.h>\r\n#include <OAIDL.H>\r\n#include <crtdbg.h>\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class\r\n\r\nclass CComSpan; // Forward declaration\r\n\r\nclass CComDATE\r\n{\r\npublic:\r\n    static CComDATE Now();\r\n    static bool     IsValidDate(const DATE& dt);\r\n    \r\n    CComDATE();\r\n    CComDATE(const CComDATE& dtSrc);\r\n    CComDATE(const VARIANT& varSrc);\r\n    CComDATE(DATE dtSrc);\r\n    CComDATE(const char* pszSrc);\r\n    CComDATE(const wchar_t* pszSrc);\r\n    CComDATE(time_t timeSrc);\r\n    CComDATE(const struct tm& tmSrc);\r\n    CComDATE(const SYSTEMTIME& systimeSrc);\r\n    CComDATE(const FILETIME& filetimeSrc);\r\n    CComDATE(long nYear, long nMonth, long nDay, long nHour = 0, long nMin = 0, long nSec = 0);\r\n    CComDATE(WORD wDosDate, WORD wDosTime);\r\n    \r\n#ifdef __oledb_h__\r\n    CComDATE(const DBTIMESTAMP& dbts);\r\n#endif\r\n    \r\npublic:\r\n    bool  IsValid() const;\r\n    long  Year() const;\r\n    long  Month() const;     // month of year (1 = Jan)\r\n    long  Day() const;       // day of month (1-31)\r\n    long  Hour() const;      // hour in day (0-23)\r\n    long  Minute() const;    // minute in hour (0-59)\r\n    long  Second() const;    // second in minute (0-59)\r\n    long  DayOfWeek() const; // 1=Sun, 2=Mon, ..., 7=Sat\r\n    long  DayOfYear() const; // days since start of year, Jan 1 = 1\r\n    \r\n    bool  IsLeapYear() const;   // Whether it's a leap year or not\r\n    bool  IsNoon() const;       // Whether it's 12:00:00pm or not\r\n    bool  IsMidnight() const;   // Whether it's 12:00:00am or not\r\n    \r\n    // Operations\r\npublic:\r\n    const CComDATE& operator=(const CComDATE& dtSrc);\r\n    const CComDATE& operator=(const VARIANT& varSrc);\r\n    const CComDATE& operator=(DATE dtSrc);\r\n    const CComDATE& operator=(const char* pszSrc);\r\n    const CComDATE& operator=(const wchar_t* pszSrc);\r\n    \r\n    const CComDATE& operator=(const time_t& timeSrc);\r\n    const CComDATE& operator=(const struct tm& tmSrc);\r\n    const CComDATE& operator=(const SYSTEMTIME& systimeSrc);\r\n    const CComDATE& operator=(const FILETIME& filetimeSrc);\r\n\r\n#ifdef __oledb_h__\r\n    const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts);\r\n#endif\r\n\r\n    bool operator==(const CComDATE& date) const;\r\n    bool operator!=(const CComDATE& date) const;\r\n    bool operator<(const CComDATE& date) const;\r\n    bool operator>(const CComDATE& date) const;\r\n    bool operator<=(const CComDATE& date) const;\r\n    bool operator>=(const CComDATE& date) const;\r\n    \r\n    // Date math\r\n    const CComDATE& operator+=(const CComSpan& span);\r\n    const CComDATE& operator-=(const CComSpan& span);\r\n    \r\n    friend CComDATE operator+(const CComDATE& date, const CComSpan& span);\r\n    friend CComDATE operator-(const CComDATE& date, const CComSpan& span);\r\n    friend CComDATE operator+(const CComSpan& span, const CComDATE& date);\r\n    friend CComSpan operator-(const CComDATE& date1, const CComDATE& date2);\r\n    \r\n    operator DATE() const;\r\n    DATE* operator&();\r\n\r\n    operator VARIANT() const;\r\n    operator time_t() const;\r\n    operator struct tm() const;\r\n    operator SYSTEMTIME() const;\r\n    operator FILETIME() const;\r\n#ifdef __oledb_h__\r\n    operator DBTIMESTAMP() const;\r\n#endif\r\n    \r\n    bool  SetDateTime(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec);\r\n    bool  SetDate(long nYear, long nMonth, long nDay);\r\n    bool  SetTime(long nHour, long nMin, long nSec);\r\n    bool  ParseDateTime(const char* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT);\r\n    bool  ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT);\r\n    \r\n    // Formatting\r\n    LPTSTR Format(LPTSTR pszOut, DWORD dwFlags = 0, LCID lcid = LANG_USER_DEFAULT) const;\r\n    LPTSTR Format(LPTSTR pszOut, LPCTSTR lpszFormat) const;\r\n#ifdef __ATLCOM_H__\r\n    LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = _Module.GetResourceInstance()) const;\r\n#else\r\n    LPTSTR Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst = GetModuleHandle(0)) const;\r\n#endif\r\n\r\n\t// Formatting using National Language Support functions GetTimeFormat() and GetDateFormat()\r\n\tLPTSTR\tFormatTime(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const;\r\n\tLPTSTR\tFormatDate(LPTSTR pszOut, LPCTSTR szFmt=NULL, DWORD dwFlags=0, LCID lcid=LOCALE_USER_DEFAULT) const;\r\n    \r\nprotected:\r\n    enum\r\n    {\r\n        COMDATE_ERROR = INT_MIN,\r\n        MIN_DATE      = -657434L,       // About year 100\r\n        MAX_DATE      = 2958465L,       // About year 9999\r\n        INVALID_DATE  = (MIN_DATE-1),   // Used to indicate invalid date\r\n    };\r\n\r\nprotected:\r\n    DATE  m_date;\r\n    \r\nprotected:\r\n    void Invalidate();\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan class\r\n\r\nclass CComSpan\r\n{\r\npublic:\r\n    CComSpan();\r\n    CComSpan(double dblSpanSrc);\r\n    CComSpan(const CComSpan& dateSpanSrc);\r\n    CComSpan(long nDays, long nHours = 0, long nMins = 0, long nSecs = 0);\r\n    \r\n    bool IsValid() const;\r\n    \r\n    double TotalDays() const;    // span in days (about -3.65e6 to 3.65e6)\r\n    double TotalHours() const;   // span in hours (about -8.77e7 to 8.77e6)\r\n    double TotalMinutes() const; // span in minutes (about -5.26e9 to 5.26e9)\r\n    double TotalSeconds() const; // span in seconds (about -3.16e11 to 3.16e11)\r\n    \r\n    long Days() const;       // component days in span\r\n    long Hours() const;      // component hours in span (-23 to 23)\r\n    long Minutes() const;    // component minutes in span (-59 to 59)\r\n    long Seconds() const;    // component seconds in span (-59 to 59)\r\n    \r\npublic:\r\n    const CComSpan& operator=(double dblSpanSrc);\r\n    const CComSpan& operator=(const CComSpan& dateSpanSrc);\r\n    \r\n    bool operator==(const CComSpan& dateSpan) const;\r\n    bool operator!=(const CComSpan& dateSpan) const;\r\n    bool operator<(const CComSpan& dateSpan) const;\r\n    bool operator>(const CComSpan& dateSpan) const;\r\n    bool operator<=(const CComSpan& dateSpan) const;\r\n    bool operator>=(const CComSpan& dateSpan) const;\r\n    \r\n    // Math\r\n    const CComSpan& operator+=(const CComSpan& rhs);\r\n    const CComSpan& operator-=(const CComSpan& rhs);\r\n    CComSpan operator-() const;\r\n    \r\n    friend CComSpan operator+(const CComSpan& span1, const CComSpan& span2);\r\n    friend CComSpan operator-(const CComSpan& span1, const CComSpan& span2);\r\n    \r\n    operator double() const;\r\n    \r\n    void SetSpan(long nDays, long nHours, long nMins, long nSecs);\r\n    \r\nprotected:\r\n    enum\r\n    {\r\n        MAX_SPAN      = 3615897L,\r\n        MIN_SPAN      = -MAX_SPAN,\r\n        INVALID_SPAN  = (MIN_SPAN-1),   // Used to indicate invalid span\r\n    };\r\n\r\nprotected:\r\n    double  m_span;\r\n\r\nprotected:\r\n    void Invalidate();\r\n};\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE inline implementations\r\n\r\ninline bool CComDATE::IsValidDate(const DATE& dt)\r\n{\r\n    // About year 100 to about 9999\r\n    return (dt >= MIN_DATE && dt <= MAX_DATE);\r\n}\r\n\r\ninline CComDATE CComDATE::Now()\r\n{\r\n    SYSTEMTIME  sysTime;\r\n    GetLocalTime(&sysTime);\r\n    return CComDATE(sysTime);\r\n}\r\n\r\ninline CComDATE::CComDATE()\r\n{ Invalidate(); }\r\n\r\ninline CComDATE::CComDATE(const CComDATE& dtSrc)\r\n{ m_date = dtSrc.m_date; }\r\n\r\ninline CComDATE::CComDATE(const VARIANT& varSrc)\r\n{ *this = varSrc; }\r\n\r\ninline CComDATE::CComDATE(DATE dtSrc)\r\n{ m_date = dtSrc; }\r\n\r\ninline CComDATE::CComDATE(const char* pszSrc)\r\n{ ParseDateTime(pszSrc); }\r\n\r\ninline CComDATE::CComDATE(const wchar_t* pszSrc)\r\n{ ParseDateTime(pszSrc); }\r\n\r\ninline CComDATE::CComDATE(time_t timeSrc)\r\n{ *this = timeSrc; }\r\n\r\ninline CComDATE::CComDATE(const struct tm& tmSrc)\r\n{ \r\n    SetDateTime(tmSrc.tm_year + 1900,\r\n                tmSrc.tm_mon + 1,\r\n                tmSrc.tm_mday,\r\n                tmSrc.tm_hour,\r\n                tmSrc.tm_min,\r\n                tmSrc.tm_sec); \r\n}\r\n\r\ninline CComDATE::CComDATE(const SYSTEMTIME& systimeSrc)\r\n{ *this = systimeSrc; }\r\n\r\ninline CComDATE::CComDATE(const FILETIME& filetimeSrc)\r\n{ *this = filetimeSrc; }\r\n\r\ninline CComDATE::CComDATE(long nYear, long nMonth, long nDay, long nHour, long nMin, long nSec)\r\n{ SetDateTime(nYear, nMonth, nDay, nHour, nMin, nSec); }\r\n\r\ninline CComDATE::CComDATE(WORD wDosDate, WORD wDosTime)\r\n{ if( !DosDateTimeToVariantTime(wDosDate, wDosTime, &m_date) ) Invalidate(); }\r\n\r\ninline const CComDATE& CComDATE::operator=(const CComDATE& dtSrc)\r\n{ m_date = dtSrc.m_date; return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator=(const char* pszSrc)\r\n{ ParseDateTime(pszSrc); return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator=(const wchar_t* pszSrc)\r\n{ ParseDateTime(pszSrc); return *this; }\r\n\r\ninline bool CComDATE::operator==(const CComDATE& date) const\r\n{ return (m_date == date.m_date); }\r\n\r\ninline bool CComDATE::operator!=(const CComDATE& date) const\r\n{ return (m_date != date.m_date); }\r\n\r\ninline CComDATE::operator DATE() const\r\n{ return m_date; }\r\n\r\ninline DATE* CComDATE::operator&()\r\n{ return &m_date; }\r\n\r\ninline bool CComDATE::SetDate(long nYear, long nMonth, long nDay)\r\n{ return SetDateTime(nYear, nMonth, nDay, Hour(), Minute(), Second()); }\r\n\r\ninline bool CComDATE::SetTime(long nHour, long nMin, long nSec)\r\n{ return SetDateTime(Year(), Month(), Day(), nHour, nMin, nSec); }\r\n\r\ninline const CComDATE& CComDATE::operator+=(const CComSpan& span)\r\n{ *this = *this + span; return *this; }\r\n\r\ninline const CComDATE& CComDATE::operator-=(const CComSpan& span)\r\n{ *this = *this - span; return *this; }\r\n\r\ninline bool CComDATE::IsValid() const\r\n{ return IsValidDate(m_date); }\r\n\r\ninline void CComDATE::Invalidate()\r\n{ m_date = INVALID_DATE; }\r\n\r\n#ifdef __oledb_h__\r\ninline CComDATE::CComDATE(const DBTIMESTAMP& dbts)\r\n{ SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); }\r\n\r\ninline const CComDATE& CComDATE::operator=(const DBTIMESTAMP& dbts)\r\n{ SetDateTime(dbts.year, dbts.month, dbts.day, dbts.hour, dbts.minute, dbts.second); return *this; }\r\n\r\n#endif  // __oledb_h__\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan inline implementations\r\n\r\ninline CComSpan::CComSpan()\r\n{ Invalidate(); }\r\n\r\ninline CComSpan::CComSpan(double db) : m_span(db) {}\r\n\r\ninline CComSpan::CComSpan(const CComSpan& rhs)\r\n{ m_span = rhs.m_span; }\r\n\r\ninline CComSpan::CComSpan(long nDays, long nHours, long nMins, long nSecs)\r\n{ SetSpan(nDays, nHours, nMins, nSecs); }\r\n\r\ninline const CComSpan& CComSpan::operator=(double db)\r\n{ m_span = db; return *this; }\r\n\r\ninline const CComSpan& CComSpan::operator=(const CComSpan& span)\r\n{ m_span = span.m_span; return *this; }\r\n\r\ninline double CComSpan::TotalDays() const\r\n{ _ASSERTE(IsValid()); return m_span; }\r\n\r\ninline double CComSpan::TotalHours() const\r\n{ _ASSERTE(IsValid()); return m_span * 24; }\r\n\r\ninline double CComSpan::TotalMinutes() const\r\n{ _ASSERTE(IsValid()); return m_span * 24 * 60; }\r\n\r\ninline double CComSpan::TotalSeconds() const\r\n{ _ASSERTE(IsValid()); return m_span * 24 * 60 * 60; }\r\n\r\ninline long CComSpan::Days() const\r\n{ _ASSERTE(IsValid()); return (long)m_span; }\r\n\r\ninline bool CComSpan::operator==(const CComSpan& rhs) const\r\n{ return m_span == rhs.m_span; }\r\n\r\ninline bool CComSpan::operator!=(const CComSpan& rhs) const\r\n{ return m_span != rhs.m_span; }\r\n\r\ninline bool CComSpan::operator<(const CComSpan& rhs) const\r\n{ return m_span < rhs.m_span; }\r\n\r\ninline bool CComSpan::operator>(const CComSpan& rhs) const\r\n{ return m_span > rhs.m_span; }\r\n\r\ninline bool CComSpan::operator<=(const CComSpan& rhs) const\r\n{ return m_span <= rhs.m_span; }\r\n\r\ninline bool CComSpan::operator>=(const CComSpan& rhs) const\r\n{ return m_span >= rhs.m_span; }\r\n\r\ninline const CComSpan& CComSpan::operator+=(const CComSpan& rhs)\r\n{ return (*this = *this + rhs); }\r\n\r\ninline const CComSpan& CComSpan::operator-=(const CComSpan& rhs)\r\n{ return (*this = *this - rhs); }\r\n\r\ninline CComSpan CComSpan::operator-() const\r\n{ return CComSpan(-m_span); }\r\n\r\ninline CComSpan::operator double() const\r\n{ return m_span; }\r\n\r\ninline bool CComSpan::IsValid() const\r\n{ return (m_span >= MIN_SPAN && m_span <= MAX_SPAN); }\r\n\r\ninline void CComSpan::Invalidate()\r\n{ m_span = INVALID_SPAN; }\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class helper definitions\r\n\r\n#define HALF_SECOND 1.0/172800.0    // Half a second, expressed in days\r\n\r\nbool   MakeDATE(DATE* pdtDest, WORD wYear, WORD wMonth, WORD wDay, WORD wHour, WORD wMinute, WORD wSecond);\r\nbool   Maketm(struct tm* ptmDest, DATE dtSrc);\r\ndouble DATEAsDouble(DATE dtSrc);\r\nDATE   MakeDATE(double dbSrc);\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE class\r\n\r\ninline\r\nlong CComDATE::Year() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_year + 1900;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Month() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mon + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Day() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_mday;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Hour() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_hour;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Minute() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_min;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::Second() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_sec;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::DayOfWeek() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_wday + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nlong CComDATE::DayOfYear() const\r\n{\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) ) return tmDest.tm_yday + 1;\r\n    return COMDATE_ERROR;\r\n}\r\n\r\ninline\r\nbool CComDATE::IsLeapYear() const\r\n{\r\n    long year = Year();\r\n    return ((year != COMDATE_ERROR) && ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0));\r\n}\r\n\r\ninline\r\nbool CComDATE::IsNoon() const\r\n{\r\n    return Hour() == 12 && Minute() == 0 && Second() == 0;\r\n}\r\n\r\ninline\r\nbool CComDATE::IsMidnight() const\r\n{\r\n    return Hour() == 0 && Minute() == 0 && Second() == 0;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const VARIANT& varSrc)\r\n{\r\n    if( varSrc.vt == VT_DATE )\r\n    {\r\n        m_date = varSrc.date;\r\n    }\r\n    else\r\n    {\r\n        VARIANT varDest = { 0 };\r\n        if( SUCCEEDED(VariantChangeType(&varDest, const_cast<VARIANT*>(&varSrc), 0, VT_DATE)) )\r\n        {\r\n            m_date = varDest.date;\r\n            VariantClear(&varDest);\r\n        }\r\n        else\r\n        {\r\n            Invalidate();\r\n        }\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(DATE dtSrc)\r\n{\r\n    m_date = dtSrc;\r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const time_t& tmSrc)\r\n{\r\n    // Convert time_t to struct tm\r\n    tm *ptm = localtime(&tmSrc);\r\n    \r\n    if( !ptm ||\r\n        !MakeDATE(&m_date,\r\n                  (WORD)(ptm->tm_year + 1900),\r\n                  (WORD)(ptm->tm_mon + 1),\r\n                  (WORD)ptm->tm_mday,\r\n                  (WORD)ptm->tm_hour,\r\n                  (WORD)ptm->tm_min,\r\n                  (WORD)ptm->tm_sec) )\r\n    {\r\n        // Local time must have failed (tmSrc before 1/1/70 12am)\r\n        Invalidate();\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const struct tm& tmSrc)\r\n{\r\n    SetDateTime(tmSrc.tm_year + 1900,\r\n                tmSrc.tm_mon + 1,\r\n                tmSrc.tm_mday,\r\n                tmSrc.tm_hour,\r\n                tmSrc.tm_min,\r\n                tmSrc.tm_sec); \r\n\r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const SYSTEMTIME& systmSrc)\r\n{\r\n    if( !MakeDATE(&m_date,\r\n                  systmSrc.wYear,\r\n                  systmSrc.wMonth,\r\n                  systmSrc.wDay,\r\n                  systmSrc.wHour,\r\n                  systmSrc.wMinute,\r\n                  systmSrc.wSecond) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nconst CComDATE& CComDATE::operator=(const FILETIME& ftSrc)\r\n{\r\n    // Assume UTC FILETIME, so convert to LOCALTIME\r\n    FILETIME ftLocal;\r\n    if( !FileTimeToLocalFileTime( &ftSrc, &ftLocal) )\r\n    {\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nFileTimeToLocalFileTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n        Invalidate();\r\n    }\r\n    else\r\n    {\r\n        // Take advantage of SYSTEMTIME -> FILETIME conversion\r\n        SYSTEMTIME  systime;\r\n        \r\n        // At this polong systime should always be valid, but...\r\n        if( !FileTimeToSystemTime(&ftLocal, &systime) ||\r\n            !MakeDATE(&m_date,\r\n                      systime.wYear,\r\n                      systime.wMonth,\r\n                      systime.wDay,\r\n                      systime.wHour,\r\n                      systime.wMinute,\r\n                      systime.wSecond) )\r\n        {\r\n            Invalidate();\r\n        }\r\n    }\r\n    \r\n    return *this;\r\n}\r\n\r\ninline\r\nCComDATE::operator VARIANT() const\r\n{\r\n    VARIANT var = { 0 };\r\n    var.vt = VT_DATE;\r\n    var.date = m_date;\r\n    return var;\r\n}\r\n\r\ninline\r\nCComDATE::operator time_t() const\r\n{\r\n    struct  tm  tmDest;\r\n    if( Maketm(&tmDest, m_date) )\r\n    {\r\n        return mktime(&tmDest);\r\n    }\r\n\r\n    return -1;\r\n}\r\n\r\ninline\r\nCComDATE::operator struct tm() const\r\n{\r\n    struct  tm  tmDest = { 0 };\r\n    Maketm(&tmDest, m_date);\r\n    return tmDest;\r\n}\r\n\r\ninline\r\nCComDATE::operator SYSTEMTIME() const\r\n{\r\n    SYSTEMTIME  st = { 0 };\r\n\r\n    VariantTimeToSystemTime(m_date, &st);\r\n\r\n    return st;\r\n}\r\n\r\ninline\r\nCComDATE::operator FILETIME() const\r\n{\r\n    FILETIME    ft = { 0 };\r\n\t\r\n    SYSTEMTIME st;\r\n    VariantTimeToSystemTime(m_date, &st);\r\n    SystemTimeToFileTime(&st, &ft);\r\n\r\n    return ft;\r\n}\r\n\r\n#ifdef __oledb_h__\r\ninline\r\nCComDATE::operator DBTIMESTAMP() const\r\n{\r\n    DBTIMESTAMP dbts = { 0 };\r\n\r\n    struct tm tmDest;\r\n    if( IsValid() && Maketm(&tmDest, m_date) )\r\n    {\r\n        dbts.day    = tmDest.tm_mday;\r\n        dbts.month  = tmDest.tm_mon + 1;\r\n        dbts.year   = tmDest.tm_year + 1900;\r\n        dbts.hour   = tmDest.tm_hour;\r\n        dbts.minute = tmDest.tm_min;\r\n        dbts.second = tmDest.tm_sec;\r\n    }\r\n\r\n    return dbts;\r\n}\r\n#endif\r\n\r\ninline\r\nbool CComDATE::operator<(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) < DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator>(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) > DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator<=(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) <= DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::operator>=(const CComDATE& date) const\r\n{\r\n    _ASSERTE(IsValid());\r\n    _ASSERTE(date.IsValid());\r\n    \r\n    // Handle negative dates\r\n    return DATEAsDouble(m_date) >= DATEAsDouble(date.m_date);\r\n}\r\n\r\ninline\r\nbool CComDATE::SetDateTime(\r\n    long nYear,\r\n    long nMonth,\r\n    long nDay,\r\n    long nHour,\r\n    long nMin,\r\n    long nSec)\r\n{\r\n    if( !MakeDATE(&m_date, (WORD)nYear, (WORD)nMonth, (WORD)nDay, (WORD)nHour, (WORD)nMin, (WORD)nSec) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return IsValid();\r\n}\r\n\r\n/*inline\r\nbool CComDATE::ParseDateTime(const char* lpszDate, DWORD dwFlags, LCID lcid)\r\n{\r\n    USES_CONVERSION;\r\n    return ParseDateTime(A2OLE(lpszDate), dwFlags, lcid);\r\n}*/\r\n\r\ninline\r\nbool CComDATE::ParseDateTime(const wchar_t* lpszDate, DWORD dwFlags, LCID lcid)\r\n{\r\n    if( FAILED(VarDateFromStr(const_cast<wchar_t*>(lpszDate), lcid, dwFlags, &m_date)) )\r\n    {\r\n        Invalidate();\r\n    }\r\n    \r\n    return IsValid();\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, DWORD dwFlags, LCID lcid) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    // If invalild, return empty string\r\n    if (!IsValid()) return pszOut;\r\n    \r\n    BSTR  bstr = 0;\r\n    if( SUCCEEDED(VarBstrFromDate(m_date, lcid, dwFlags, &bstr)) )\r\n    {\r\n#ifdef _UNICODE\r\n        wcscpy(pszOut, bstr);\r\n#else\r\n        wcstombs(pszOut, bstr, wcslen(bstr) + 1);\r\n#endif\r\n        \r\n        SysFreeString(bstr);\r\n    }\r\n    \r\n    return pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, LPCTSTR pFormat) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    // If invalild, return empty string\r\n    struct tm tmDest;\r\n    if (!IsValid() || !Maketm(&tmDest, m_date) ) return pszOut;\r\n    \r\n    // Fill in the buffer, disregard return value as it's not necessary\r\n    // NOTE: 4096 is an arbitrary value picked lower than INT_MAX\r\n    // as the VC6 implementation of wcsftime allocates memory based\r\n    // on the 2nd parameter for some reason.\r\n    _tcsftime(pszOut, 4096, pFormat, &tmDest);\r\n    return pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::Format(LPTSTR pszOut, UINT nFormatID, HINSTANCE hinst) const\r\n{\r\n    *pszOut = 0;\r\n    \r\n    TCHAR   sz[256];\r\n    if( LoadString(hinst, nFormatID, sz, sizeof(sz)/sizeof(*sz)) )\r\n    {\r\n        return Format(pszOut, sz);\r\n    }\r\n    \r\n    return pszOut;\r\n}\r\n\r\n// The FormatDate and FormatTime functions were provided by Joe O'Leary (joleary@artisoft.com) to\r\n// wrap he Win32 National Language Support functions ::GetDateFormat() and ::GetTimeFormat().\r\n// The format strings used here are specified in the on-line help for those functions.\r\n// The default format is the current user locale.\r\n\r\ninline\r\nLPTSTR CComDATE::FormatDate(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const\r\n{\r\n\t_ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero\r\n\r\n\tSYSTEMTIME st;\r\n\tmemset(&st, 0, sizeof(SYSTEMTIME));\r\n\t*pszOut = NULL;\r\n\r\n\tif ( !VariantTimeToSystemTime(m_date, &st) )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nVariantTimeToSystemTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\telse if ( GetDateFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nGetDateFormat failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\r\n\treturn pszOut;\r\n}\r\n\r\ninline\r\nLPTSTR CComDATE::FormatTime(LPTSTR pszOut, LPCTSTR szFmt, DWORD dwFlags, LCID lcid) const\r\n{\r\n\t_ASSERTE((szFmt==NULL) || (dwFlags==0));// if format is non-NULL, 'dwFlags' MUST be zero\r\n\r\n\tSYSTEMTIME st;\r\n\tmemset(&st, 0, sizeof(SYSTEMTIME));\r\n\t*pszOut = NULL;\r\n\r\n\tif ( !VariantTimeToSystemTime(m_date, &st) )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nVariantTimeToSystemTime failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\telse if ( GetTimeFormat(lcid, dwFlags, &st, szFmt, pszOut, 255) == 0 )\r\n\t{\r\n#ifdef ATLTRACE\r\n        ATLTRACE(\"\\nGetTimeFormat failed. Error = %lu.\\n\\t\", GetLastError());\r\n#endif\r\n\t}\r\n\r\n\treturn pszOut;\r\n}\r\n\r\ninline\r\nbool Maketm(struct tm* ptmDest, DATE dtSrc)\r\n{\r\n    SYSTEMTIME  st;\r\n    if( !VariantTimeToSystemTime(dtSrc, &st) ) return false;\r\n    \r\n    struct tm& tmDest = *ptmDest; // Convenience\r\n    tmDest.tm_sec = st.wSecond;\r\n    tmDest.tm_min = st.wMinute;\r\n    tmDest.tm_hour = st.wHour;\r\n    tmDest.tm_mday = st.wDay;\r\n    tmDest.tm_mon = st.wMonth - 1;\r\n    tmDest.tm_year = st.wYear - 1900;\r\n    tmDest.tm_wday = st.wDayOfWeek;\r\n    tmDest.tm_isdst = -1;   // Force DST checking\r\n    mktime(&tmDest);    // Normalize\r\n    \r\n    return true;\r\n}\r\n\r\ninline\r\ndouble DATEAsDouble(DATE dt)\r\n{\r\n    // No problem if positive\r\n    if (dt >= 0) return dt;\r\n    \r\n    // If negative, must convert since negative dates not continuous\r\n    // (examples: -1.25 to -.75, -1.50 to -.50, -1.75 to -.25)\r\n    double temp = ceil(dt);\r\n    return temp - (dt - temp);\r\n}\r\n\r\ninline\r\nDATE MakeDATE(double dbl)\r\n{\r\n    // No problem if positive\r\n    if (dbl >= 0) return dbl;\r\n    \r\n    // If negative, must convert since negative dates not continuous\r\n    // (examples: -.75 to -1.25, -.50 to -1.50, -.25 to -1.75)\r\n    double temp = floor(dbl); // dbl is now whole part\r\n    return temp + (temp - dbl);\r\n}\r\n\r\ninline\r\nbool MakeDATE(\r\n    DATE* pdtDest,\r\n    WORD  wYear,\r\n    WORD  wMonth,\r\n    WORD  wDay,\r\n    WORD  wHour,\r\n    WORD  wMinute,\r\n    WORD  wSecond)\r\n{\r\n    SYSTEMTIME st = { 0 };\r\n    st.wYear = wYear;\r\n    st.wMonth = wMonth;\r\n    st.wDay = wDay;\r\n    st.wHour = wHour;\r\n    st.wMinute = wMinute;\r\n    st.wSecond = wSecond;\r\n    \r\n    return SystemTimeToVariantTime(&st, pdtDest) ? true : false;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComSpan class\r\n\r\ninline\r\nlong CComSpan::Hours() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate days and scale up\r\n    double dbTemp = modf(m_span, &dbTemp);\r\n    return (long)(dbTemp * 24);\r\n}\r\n\r\ninline\r\nlong CComSpan::Minutes() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate hours and scale up\r\n    double dbTemp = modf(m_span * 24, &dbTemp);\r\n    return (long)((dbTemp + HALF_SECOND) * 60);\r\n}\r\n\r\ninline\r\nlong CComSpan::Seconds() const\r\n{\r\n    _ASSERTE(IsValid());\r\n    \r\n    // Truncate minutes and scale up\r\n    double dbTemp = modf(m_span * 24 * 60, &dbTemp);\r\n    return (long)(dbTemp * 60);\r\n}\r\n\r\ninline\r\nvoid CComSpan::SetSpan(\r\n    long  nDays,\r\n    long  nHours,\r\n    long  nMins,\r\n    long  nSecs)\r\n{\r\n    // Set date span by breaking longo fractional days (all input ranges valid)\r\n    m_span = nDays +\r\n             ((double)nHours)/24 +\r\n             ((double)nMins)/(24*60) +\r\n             ((double)nSecs)/(24*60*60);\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CComDATE/CComSpan math friend functions\r\n\r\n// date2 = date1 + span;\r\ninline\r\nCComDATE operator+(const CComDATE& date1, const CComSpan& span)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// date2 = span + date1;\r\ninline\r\nCComDATE operator+(const CComSpan& span, const CComDATE& date1)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) + static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// date2 = date1 - span;\r\ninline\r\nCComDATE operator-(const CComDATE& date1, const CComSpan& span)\r\n{\r\n    CComDATE  date2;\r\n    \r\n    if( date1.IsValid() && span.IsValid() )\r\n    {\r\n        // Compute the actual date difference by adding underlying data\r\n        date2 = MakeDATE(DATEAsDouble(static_cast<DATE>(date1)) - static_cast<double>(span));\r\n    }\r\n    \r\n    return date2;\r\n}\r\n\r\n// span = date1 - date2;\r\ninline\r\nCComSpan operator-(const CComDATE& date1, const CComDATE& date2)\r\n{\r\n    CComSpan span;\r\n    \r\n    if( date1.IsValid() && date2.IsValid() )\r\n    {\r\n        span = DATEAsDouble(static_cast<DATE>(date1)) - DATEAsDouble(static_cast<DATE>(date2));\r\n    }\r\n    \r\n    return span;\r\n}\r\n\r\n// span3 = span1 + span2;\r\ninline\r\nCComSpan operator+(const CComSpan& span1, const CComSpan& span2)\r\n{\r\n    CComSpan span3;\r\n    if( span1.IsValid() && span2.IsValid() ) span3 = span1.m_span + span2.m_span;\r\n    return span3;\r\n}\r\n\r\n// span3 = span1 - span2;\r\ninline\r\nCComSpan operator-(const CComSpan& span1, const CComSpan& span2)\r\n{\r\n    return span1 + (-span2);\r\n}\r\n\r\n#undef HALF_SECOND\r\n#endif  // __COMDATE_H__\r\n"
  },
  {
    "path": "plugins/wmp/dbg.cpp",
    "content": "/*************************************************************************\r\n FILE :\t\t\tdbg.cpp\r\n\r\n Author :\t\tSpib\r\n\r\n Description:\tCDebug\r\n\t\t\t\tThread-safe logging routines for logging from multiple\r\n\t\t\t\tprocesses to one log file. \r\n\r\n\t\t\t\tClass includes printf-style formatted output routines, as\r\n\t\t\t\twell as timestamping of entries, process id, and process execution time.\r\n\r\n Spib\t- Allow max file size\r\n\t\t\t\tAllows debugging to be activated at runtime.\r\n\r\n*************************************************************************/\r\n#include <windows.h>\r\n#include <process.h>\r\n#include \"dbg.h\"      \r\n\r\n#ifdef USE_DEBUG_PRINTF\r\n\r\n#define MSG_BUFFER_SIZE\t\t1024*50\r\n\r\nconst char DIVIDER[10] = { 13, 10, '-', '-', '-', '-', '-', '-', 13, 10 };\r\nconst char CrLf[3]\t   = { 13, 10, 0 };\r\n\r\nCDebug debug;\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : CDebug::CDebug ()\r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : \r\n *  History     : \r\n */\r\nCDebug::CDebug ()\r\n{\r\n\tm_bEnabled\t\t\t= FALSE;  \r\n\tm_nLogLevel\t\t\t= DEBUG_ERROR;\r\n\tm_nMaxFileSize\t= -1;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : CDebug::CDebug ()\r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : \r\n *  History     : \r\n */\r\nCDebug::~CDebug ()\r\n{\r\n\tCloseLog();\r\n}\r\n\r\nvoid CDebug::Init(const char* strFileName, BOOL bOverWrite /* = TRUE */, BOOL bEnable /* = TRUE */, BOOL bUseXML /*= FALSE*/)\r\n{\t\r\n\tif(strlen(strFileName) <= 0)\r\n\t\treturn;\r\n\r\n\tm_bEnabled\t\t= bEnable;\r\n\tm_bUseXML\t\t\t= bUseXML;\r\n\r\n\tstrncpy(m_strFilePath, strFileName, MAX_PATH);\r\n\r\n\tif(m_bUseXML)\r\n\t\tstrcat(m_strFilePath, \".xml\");\r\n\r\n\tInitializeCriticalSection(&m_hLock);\r\n\t\t\r\n\tif(OpenLogFile(bOverWrite))\r\n\t{\r\n\t\tm_dwStartTime = GetTickCount();\r\n\t\tWriteHeader(bOverWrite);\r\n\t}\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : void CDebug::CloseLog ()\r\n *  Description : Closes log file and releases handles. \r\n *  Parameters  :                   \r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::CloseLog ()\r\n{\r\n\tchar buffer[9];\r\n\tDWORD x = 0;\r\n\r\n\tif(m_bEnabled && m_hFile != NULL)\r\n\t{\r\n\t\tif(m_bUseXML)\r\n\t\t{\t\t\r\n\t\t\tstrcpy(buffer, \"</DEBUG>\");\r\n\t\t\tWriteFile(m_hFile,\tbuffer,    lstrlen(buffer),    &x, 0 );\r\n\t\t}\r\n\r\n\t\tCloseHandle(m_hFile );\r\n\r\n\t\tDeleteCriticalSection(&m_hLock );\r\n\t}\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : \r\n *  Prototype   : void CDebug::printf (const char *fmt, ... )\r\n *  Description : Prints formatted string to log-file\r\n *  Parameters  : const char *fmt - format string\r\n                  ...             - list of parameters\r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::printf (int nLevel, const char* strMod, const char *fmt, ... )\r\n{\r\n\tDWORD\t\t\t\tx;\r\n\tchar\t\t\t\tbuf[256];\r\n\tSYSTEMTIME\ttime;\r\n\tchar\t\t\t\tbuffer[MSG_BUFFER_SIZE];\r\n\tchar\t\t\t\tbuffer2[MSG_BUFFER_SIZE];\r\n\tva_list\t\t\targlist;\r\n\tDWORD\t\t\t\tdwDiffTime;\r\n\r\n\tif((nLevel < m_nLogLevel) || (nLevel < 0) || !m_bEnabled)\r\n\t\treturn;\r\n\r\n\tmemset(buffer, 0, sizeof(buffer));\r\n\tmemset(buffer2, 0, sizeof(buffer2));\r\n\tmemset(buf, 0, sizeof(buf));\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\t// Do this inside the section in case we have to delete \r\n\t// the file\r\n\tCheckFileSize();\r\n\r\n\t// Format string\r\n\tva_start(arglist, fmt);\r\n\twvsprintf(buffer, fmt, arglist);\r\n\tva_end(arglist);\r\n\r\n\t// Format time stamp\r\n\tGetLocalTime(&time);\r\n\r\n\tdwDiffTime = GetTickCount() - m_dwStartTime;\r\n\r\n\tSetFilePointer(m_hFile, 0, 0, FILE_END );\r\n\t\r\n\t// XML Version\r\n\tif( m_bUseXML )\r\n\t{\r\n\t\tReplaceXMLChars(buffer, strlen(buffer), buffer2);\r\n\r\n\t\twsprintf(buf, \"<LINE><ELAPSED>%d.%03d</ELAPSED><DATE>%02d/%02d/%02d</DATE><TIME>%02d:%02d:%02d</TIME>\", \r\n\t\t\t\t\tdwDiffTime/1000, dwDiffTime%1000, \r\n\t\t\t\t\ttime.wMonth, time.wDay,    time.wYear,\r\n\t\t\t\t\ttime.wHour,  time.wMinute, time.wSecond);\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\twsprintf(buf, \"<MODULE>%s</MODULE><MESSAGE>\", strMod);\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\tif(nLevel == DEBUG_ERROR)\r\n\t\t\tWriteFile(m_hFile,\t\"ERROR - \", 8, &x, 0 );\r\n\t\tWriteFile(m_hFile,\tbuffer2, lstrlen(buffer2), &x, 0 );\r\n\t\tWriteFile(m_hFile,\t\"</MESSAGE></LINE>\", 17, &x, 0 );\r\n\t}\r\n\telse\r\n\t{\r\n\t\twsprintf(buf, \"%d.%03d\\t%02d/%02d/%02d %02d:%02d:%02d\\t%s\\t\\t\", \r\n\t\t\t\t\tdwDiffTime/1000, dwDiffTime%1000, \r\n\t\t\t\t\ttime.wMonth, time.wDay,    time.wYear,\r\n\t\t\t\t\ttime.wHour,  time.wMinute, time.wSecond, strMod);\r\n\r\n\t\t// Write time stamp and formatted string to log-file\r\n\t\tWriteFile(m_hFile,\tbuf,    lstrlen(buf),    &x, 0 );\r\n\t\tif(nLevel == DEBUG_ERROR)\r\n\t\t\tWriteFile(m_hFile,\t\"ERROR - \", 8, &x, 0 );\r\n\t\tWriteFile(m_hFile,\tbuffer, lstrlen(buffer), &x, 0 );\t\r\n\t\tWriteFile(m_hFile,\tCrLf,   lstrlen(CrLf),   &x, 0 );\t\r\n\t}\r\n\r\n\tFlushFileBuffers(m_hFile);\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : ShowLastError\r\n *  Prototype   : void CDebug::ShowLastError() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::ShowLastError() \r\n{\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tchar* lpMsgBuf;\r\n\r\n\tFormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,    \r\n\t\tNULL,\r\n\t\tGetLastError(),\r\n\t\tMAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language\r\n\t\t(LPTSTR) &lpMsgBuf,    \r\n\t\t0,    \r\n\t\tNULL );\r\n\r\n\tint len = lstrlen(lpMsgBuf)-1;\r\n\r\n\tif (len>0 )\r\n\t{\r\n\t\twhile (len>=0 && (lpMsgBuf[len]==0x0d || lpMsgBuf[len]==0x0a) )\r\n\t\t\tlen--;\r\n\t\tlpMsgBuf[len+1] = 0; \r\n\t\tCDebug::printf (DEBUG_ERROR, \"CDebug::ShowLastError\", \"GetLastError(): %s\", (char*)lpMsgBuf );\r\n\t\tLocalFree(lpMsgBuf ); // Free the buffer.\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : WriteHeader\r\n *  Prototype   : void CDebug::WriteHeader() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::WriteHeader(BOOL bNewFile /* = TRUE */)\r\n{\r\n\tDWORD x;\r\n\tchar buffer[MAX_PATH];\r\n\t\r\n\tif(m_hFile == NULL)\r\n\t\treturn;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tif ( m_bUseXML && bNewFile )\r\n\t{\r\n\t\tstrcpy(buffer, \"<?xml:stylesheet type=\\\"text/xsl\\\" href=\\\"debug.xsl\\\"?><DEBUG>\");\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstrcpy(buffer, \"Elapsed\\tDate/Time\\t\\tModule\\t\\t\\t\\tDebug\\r\\n\");\r\n\t\tstrcat(buffer, \"=====================================================================================================\\r\\n\");\r\n\t}\r\n\r\n\tSetFilePointer(m_hFile, 0, 0, FILE_END );\r\n\t\r\n\tif(!WriteFile(m_hFile,\tbuffer,    lstrlen(buffer),    &x, 0 ))\r\n\t{\r\n\t\t// Failed but there's not a lot I can do about it.\r\n\t}\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : CheckFileSize\r\n *  Prototype   : void CDebug::CheckFileSize() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : void \r\n *  History     : \r\n */\r\nvoid CDebug::CheckFileSize()\r\n{\r\n\tif( ( m_nMaxFileSize <= 0 ) || ( m_hFile == NULL ) )\r\n\t\treturn;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tDWORD dwStartTime = m_dwStartTime;\r\n\tlong nSize = GetFileSize (m_hFile, NULL); \r\n\r\n\t// Check if the file size is valid\r\n\tif (nSize != 0xFFFFFFFF)\r\n\t{\r\n\t\tif(nSize > m_nMaxFileSize)\r\n\t\t{\r\n\t\t\t// File size is exceeded, wipe file and start again\r\n\t\t\tCloseHandle(m_hFile);\r\n\t\t\tOpenLogFile(TRUE);\r\n\t\t\tWriteHeader();\r\n\t\t}\r\n\t}\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : OpenLogFile\r\n *  Prototype   : BOOL CDebug::OpenLogFile() \r\n *  Description : \r\n *  Parameters  :                   \r\n *  Return      : BOOL\r\n *  History     : \r\n */\r\nBOOL CDebug::OpenLogFile(BOOL bOverWrite /* = TRUE */ )\r\n{\r\n\tDWORD x = 0;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\t// Open the file if it exists and truncate to zero bytes\r\n\tHANDLE hFile = CreateFile(m_strFilePath, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tGENERIC_WRITE, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_SHARE_READ|FILE_SHARE_WRITE, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t0, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t(bOverWrite ? CREATE_ALWAYS : OPEN_ALWAYS), \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFILE_ATTRIBUTE_NORMAL, \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t0 );\r\n\t\t\r\n\t// The file isn't there. Disable debugging\r\n\tif(hFile == NULL)\r\n\t{\r\n\t\tm_bEnabled = FALSE;\r\n\t\treturn FALSE;\r\n\t}\r\n\r\n\tm_hFile = hFile;\r\n\r\n\tif(!bOverWrite && m_bUseXML)\r\n\t{\r\n\t\t// Clear the </DEBUG> tag from the end\r\n\t\tSetFilePointer(m_hFile, 8, 0, FILE_END );\r\n\t\tWriteFile(m_hFile,\t\"        \",    8,    &x, 0 );\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n\r\n\treturn TRUE;\r\n}\r\n\r\n/*-----------------------------------------------------------------------\r\n *  Function    : ReplaceXMLChars\r\n *  Prototype   : void CDebug::ReplaceXMLChars(const char* strInput, int nLen, char* strOutput) \r\n *  Description : Replace invalid characters in XML data\r\n *  Parameters  :                   \r\n *  Return      : void\r\n *  History     : \r\n */\r\nvoid CDebug::ReplaceXMLChars(const char* strInput, int nLen, char* strOutput)\r\n{\r\n\tint nOutIndx = 0;\r\n\tchar ch;\r\n\r\n\tEnterCriticalSection(&m_hLock );\r\n\r\n\tif(nLen <= 0)\r\n\t\treturn;\r\n\r\n\tfor(int i = 0; i < nLen; i++)\r\n\t{\r\n\t\tch = strInput[i];\r\n\r\n\t\tif(ch == '&')\r\n\t\t\tstrcat(strOutput, \"&amp;\");\r\n\t\telse\r\n\t\t\tstrncat(strOutput, &ch, 1);\r\n\t}\r\n\r\n\tLeaveCriticalSection(&m_hLock );\r\n}\r\n\r\n#endif\r\n"
  },
  {
    "path": "plugins/wmp/resource.h",
    "content": "//{{NO_DEPENDENCIES}}\r\n// Microsoft Visual C++ generated include file.\r\n// Used by wmp_scrobbler.rc\r\n//\r\n#define IDC_HELP_BUTTON                 3\r\n#define IDC_VIEW_LOG                    4\r\n#define IDR_WMP_SCROBBLER               101\r\n#define IDS_FRIENDLYNAME                102\r\n#define IDS_DESCRIPTION                 103\r\n#define IDD_PROPERTYDIALOG              104\r\n#define IDB_BITMAP1                     108\r\n#define IDC_MESSAGEEDIT                 1000\r\n#define IDC_NEWS_FRAME                  1001\r\n#define IDC_USERNAME                    1003\r\n#define IDC_PASSWORD                    1004\r\n#define IDC_MAX_LOG_FILE_SIZE           1005\r\n#define IDC_PROXY_USER                  1006\r\n#define IDC_PROXY_PASS                  1007\r\n#define IDC_PROXY_SERVER                1008\r\n#define IDC_PROXY_PORT                  1010\r\n#define IDC_PASSWORD_MSG                1017\r\n#define IDC_ENABLE                      1020\r\n#define IDC_FORCE_CONNECT               1021\r\n#define IDC_SHOW_MESSAGES               1022\r\n#define IDC_SHOW_UPGRADE_INFO           1022\r\n#define IDC_IGNORE_HTTP                 1023\r\n#define IDC_CACHE_STATS                 3000\r\n#define IDC_VERSION                     3001\r\n#define IDC_SERVER_STATS                3002\r\n#define IDC_USE_PROXY                   3005\r\n#define IDC_USE_PROXY_AUTH              3006\r\n#define IDC_WEBBROWSER                  3008\r\n#define IDC_LIST                        3012\r\n#define IDC_REMOVE_ALL                  3013\r\n#define IDC_REMOVE                      3014\r\n#define IDC_ADD                         3015\r\n#define IDC_NEW_DIR                     3016\r\n#define IDC_BROWSE                      3017\r\n#define IDC_INCLUDE_EXCLUDE             3021\r\n#define IDC_RADIO3                      3022\r\n#define IDC_EXCLUSIONS                  3023\r\n#define IDC_CLEAR_PASS                  3024\r\n#define IDC_INCLUDE_LIST                3027\r\n\r\n// Next default values for new objects\r\n// \r\n#ifdef APSTUDIO_INVOKED\r\n#ifndef APSTUDIO_READONLY_SYMBOLS\r\n#define _APS_NEXT_RESOURCE_VALUE        109\r\n#define _APS_NEXT_COMMAND_VALUE         40001\r\n#define _APS_NEXT_CONTROL_VALUE         1008\r\n#define _APS_NEXT_SYMED_VALUE           101\r\n#endif\r\n#endif\r\n"
  },
  {
    "path": "plugins/wmp/tools/append_once.bat",
    "content": "REM %1 - string to append\r\nREM %2 - file to append it to\r\nfind /C /I %1 %2\r\nif not errorlevel 1 goto end\r\n    echo start /WAIT \"\" %1 /SILENT >> %2\r\n:end"
  },
  {
    "path": "plugins/wmp/wmp.h",
    "content": "\r\n\r\n/* this ALWAYS GENERATED file contains the definitions for the interfaces */\r\n\r\n\r\n /* File created by MIDL compiler version 6.00.0361 */\r\n/* Compiler settings for wmp.idl:\r\n    Oicf, W1, Zp8, env=Win32 (32b run)\r\n    protocol : dce , ms_ext, c_ext, robust\r\n    error checks: allocation ref bounds_check enum stub_data \r\n    VC __declspec() decoration level: \r\n         __declspec(uuid()), __declspec(selectany), __declspec(novtable)\r\n         DECLSPEC_UUID(), MIDL_INTERFACE()\r\n*/\r\n//MIDL_FILE_HEADING(  )\r\n\r\n#pragma warning( disable: 4049 )  /* more than 64k source lines */\r\n\r\n\r\n/* verify that the <rpcndr.h> version is high enough to compile this file*/\r\n#ifndef __REQUIRED_RPCNDR_H_VERSION__\r\n#define __REQUIRED_RPCNDR_H_VERSION__ 475\r\n#endif\r\n\r\n#include \"rpc.h\"\r\n#include \"rpcndr.h\"\r\n\r\n#ifndef __RPCNDR_H_VERSION__\r\n#error this stub requires an updated version of <rpcndr.h>\r\n#endif // __RPCNDR_H_VERSION__\r\n\r\n#ifndef COM_NO_WINDOWS_H\r\n#include \"windows.h\"\r\n#include \"ole2.h\"\r\n#endif /*COM_NO_WINDOWS_H*/\r\n\r\n#ifndef __wmp_h__\r\n#define __wmp_h__\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n/* Forward Declarations */ \r\n\r\n#ifndef __IWMPErrorItem_FWD_DEFINED__\r\n#define __IWMPErrorItem_FWD_DEFINED__\r\ntypedef interface IWMPErrorItem IWMPErrorItem;\r\n#endif \t/* __IWMPErrorItem_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPError_FWD_DEFINED__\r\n#define __IWMPError_FWD_DEFINED__\r\ntypedef interface IWMPError IWMPError;\r\n#endif \t/* __IWMPError_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia_FWD_DEFINED__\r\n#define __IWMPMedia_FWD_DEFINED__\r\ntypedef interface IWMPMedia IWMPMedia;\r\n#endif \t/* __IWMPMedia_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls_FWD_DEFINED__\r\n#define __IWMPControls_FWD_DEFINED__\r\ntypedef interface IWMPControls IWMPControls;\r\n#endif \t/* __IWMPControls_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPSettings_FWD_DEFINED__\r\n#define __IWMPSettings_FWD_DEFINED__\r\ntypedef interface IWMPSettings IWMPSettings;\r\n#endif \t/* __IWMPSettings_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPClosedCaption_FWD_DEFINED__\r\n#define __IWMPClosedCaption_FWD_DEFINED__\r\ntypedef interface IWMPClosedCaption IWMPClosedCaption;\r\n#endif \t/* __IWMPClosedCaption_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylist_FWD_DEFINED__\r\n#define __IWMPPlaylist_FWD_DEFINED__\r\ntypedef interface IWMPPlaylist IWMPPlaylist;\r\n#endif \t/* __IWMPPlaylist_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCdrom_FWD_DEFINED__\r\n#define __IWMPCdrom_FWD_DEFINED__\r\ntypedef interface IWMPCdrom IWMPCdrom;\r\n#endif \t/* __IWMPCdrom_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCdromCollection_FWD_DEFINED__\r\n#define __IWMPCdromCollection_FWD_DEFINED__\r\ntypedef interface IWMPCdromCollection IWMPCdromCollection;\r\n#endif \t/* __IWMPCdromCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPStringCollection_FWD_DEFINED__\r\n#define __IWMPStringCollection_FWD_DEFINED__\r\ntypedef interface IWMPStringCollection IWMPStringCollection;\r\n#endif \t/* __IWMPStringCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMediaCollection_FWD_DEFINED__\r\n#define __IWMPMediaCollection_FWD_DEFINED__\r\ntypedef interface IWMPMediaCollection IWMPMediaCollection;\r\n#endif \t/* __IWMPMediaCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylistArray_FWD_DEFINED__\r\n#define __IWMPPlaylistArray_FWD_DEFINED__\r\ntypedef interface IWMPPlaylistArray IWMPPlaylistArray;\r\n#endif \t/* __IWMPPlaylistArray_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylistCollection_FWD_DEFINED__\r\n#define __IWMPPlaylistCollection_FWD_DEFINED__\r\ntypedef interface IWMPPlaylistCollection IWMPPlaylistCollection;\r\n#endif \t/* __IWMPPlaylistCollection_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPNetwork_FWD_DEFINED__\r\n#define __IWMPNetwork_FWD_DEFINED__\r\ntypedef interface IWMPNetwork IWMPNetwork;\r\n#endif \t/* __IWMPNetwork_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore_FWD_DEFINED__\r\n#define __IWMPCore_FWD_DEFINED__\r\ntypedef interface IWMPCore IWMPCore;\r\n#endif \t/* __IWMPCore_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer_FWD_DEFINED__\r\n#define __IWMPPlayer_FWD_DEFINED__\r\ntypedef interface IWMPPlayer IWMPPlayer;\r\n#endif \t/* __IWMPPlayer_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer2_FWD_DEFINED__\r\n#define __IWMPPlayer2_FWD_DEFINED__\r\ntypedef interface IWMPPlayer2 IWMPPlayer2;\r\n#endif \t/* __IWMPPlayer2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia2_FWD_DEFINED__\r\n#define __IWMPMedia2_FWD_DEFINED__\r\ntypedef interface IWMPMedia2 IWMPMedia2;\r\n#endif \t/* __IWMPMedia2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls2_FWD_DEFINED__\r\n#define __IWMPControls2_FWD_DEFINED__\r\ntypedef interface IWMPControls2 IWMPControls2;\r\n#endif \t/* __IWMPControls2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPDVD_FWD_DEFINED__\r\n#define __IWMPDVD_FWD_DEFINED__\r\ntypedef interface IWMPDVD IWMPDVD;\r\n#endif \t/* __IWMPDVD_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore2_FWD_DEFINED__\r\n#define __IWMPCore2_FWD_DEFINED__\r\ntypedef interface IWMPCore2 IWMPCore2;\r\n#endif \t/* __IWMPCore2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer3_FWD_DEFINED__\r\n#define __IWMPPlayer3_FWD_DEFINED__\r\ntypedef interface IWMPPlayer3 IWMPPlayer3;\r\n#endif \t/* __IWMPPlayer3_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPErrorItem2_FWD_DEFINED__\r\n#define __IWMPErrorItem2_FWD_DEFINED__\r\ntypedef interface IWMPErrorItem2 IWMPErrorItem2;\r\n#endif \t/* __IWMPErrorItem2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPRemoteMediaServices_FWD_DEFINED__\r\n#define __IWMPRemoteMediaServices_FWD_DEFINED__\r\ntypedef interface IWMPRemoteMediaServices IWMPRemoteMediaServices;\r\n#endif \t/* __IWMPRemoteMediaServices_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPSkinManager_FWD_DEFINED__\r\n#define __IWMPSkinManager_FWD_DEFINED__\r\ntypedef interface IWMPSkinManager IWMPSkinManager;\r\n#endif \t/* __IWMPSkinManager_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMetadataPicture_FWD_DEFINED__\r\n#define __IWMPMetadataPicture_FWD_DEFINED__\r\ntypedef interface IWMPMetadataPicture IWMPMetadataPicture;\r\n#endif \t/* __IWMPMetadataPicture_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMetadataText_FWD_DEFINED__\r\n#define __IWMPMetadataText_FWD_DEFINED__\r\ntypedef interface IWMPMetadataText IWMPMetadataText;\r\n#endif \t/* __IWMPMetadataText_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia3_FWD_DEFINED__\r\n#define __IWMPMedia3_FWD_DEFINED__\r\ntypedef interface IWMPMedia3 IWMPMedia3;\r\n#endif \t/* __IWMPMedia3_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPSettings2_FWD_DEFINED__\r\n#define __IWMPSettings2_FWD_DEFINED__\r\ntypedef interface IWMPSettings2 IWMPSettings2;\r\n#endif \t/* __IWMPSettings2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls3_FWD_DEFINED__\r\n#define __IWMPControls3_FWD_DEFINED__\r\ntypedef interface IWMPControls3 IWMPControls3;\r\n#endif \t/* __IWMPControls3_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPClosedCaption2_FWD_DEFINED__\r\n#define __IWMPClosedCaption2_FWD_DEFINED__\r\ntypedef interface IWMPClosedCaption2 IWMPClosedCaption2;\r\n#endif \t/* __IWMPClosedCaption2_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayerApplication_FWD_DEFINED__\r\n#define __IWMPPlayerApplication_FWD_DEFINED__\r\ntypedef interface IWMPPlayerApplication IWMPPlayerApplication;\r\n#endif \t/* __IWMPPlayerApplication_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore3_FWD_DEFINED__\r\n#define __IWMPCore3_FWD_DEFINED__\r\ntypedef interface IWMPCore3 IWMPCore3;\r\n#endif \t/* __IWMPCore3_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer4_FWD_DEFINED__\r\n#define __IWMPPlayer4_FWD_DEFINED__\r\ntypedef interface IWMPPlayer4 IWMPPlayer4;\r\n#endif \t/* __IWMPPlayer4_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayerServices_FWD_DEFINED__\r\n#define __IWMPPlayerServices_FWD_DEFINED__\r\ntypedef interface IWMPPlayerServices IWMPPlayerServices;\r\n#endif \t/* __IWMPPlayerServices_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPEvents_FWD_DEFINED__\r\n#define __IWMPEvents_FWD_DEFINED__\r\ntypedef interface IWMPEvents IWMPEvents;\r\n#endif \t/* __IWMPEvents_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef ___WMPOCXEvents_FWD_DEFINED__\r\n#define ___WMPOCXEvents_FWD_DEFINED__\r\ntypedef interface _WMPOCXEvents _WMPOCXEvents;\r\n#endif \t/* ___WMPOCXEvents_FWD_DEFINED__ */\r\n\r\n\r\n#ifndef __WindowsMediaPlayer_FWD_DEFINED__\r\n#define __WindowsMediaPlayer_FWD_DEFINED__\r\n\r\n#ifdef __cplusplus\r\ntypedef class WindowsMediaPlayer WindowsMediaPlayer;\r\n#else\r\ntypedef struct WindowsMediaPlayer WindowsMediaPlayer;\r\n#endif /* __cplusplus */\r\n\r\n#endif \t/* __WindowsMediaPlayer_FWD_DEFINED__ */\r\n\r\n\r\n/* header files for imported files */\r\n#include \"oaidl.h\"\r\n#include \"ocidl.h\"\r\n\r\n#ifdef __cplusplus\r\nextern \"C\"{\r\n#endif \r\n\r\nvoid * __RPC_USER MIDL_user_allocate(size_t);\r\nvoid __RPC_USER MIDL_user_free( void * ); \r\n\r\n/* interface __MIDL_itf_wmp_0000 */\r\n/* [local] */ \r\n\r\n//=========================================================================\r\n//\r\n// Microsoft Windows Media Technologies\r\n// Copyright (C) Microsoft Corporation.  All Rights Reserved.\r\n//\r\n//=========================================================================\r\ntypedef /* [public][helpstring] */ \r\nenum WMPOpenState\r\n    {\twmposUndefined\t= 0,\r\n\twmposPlaylistChanging\t= wmposUndefined + 1,\r\n\twmposPlaylistLocating\t= wmposPlaylistChanging + 1,\r\n\twmposPlaylistConnecting\t= wmposPlaylistLocating + 1,\r\n\twmposPlaylistLoading\t= wmposPlaylistConnecting + 1,\r\n\twmposPlaylistOpening\t= wmposPlaylistLoading + 1,\r\n\twmposPlaylistOpenNoMedia\t= wmposPlaylistOpening + 1,\r\n\twmposPlaylistChanged\t= wmposPlaylistOpenNoMedia + 1,\r\n\twmposMediaChanging\t= wmposPlaylistChanged + 1,\r\n\twmposMediaLocating\t= wmposMediaChanging + 1,\r\n\twmposMediaConnecting\t= wmposMediaLocating + 1,\r\n\twmposMediaLoading\t= wmposMediaConnecting + 1,\r\n\twmposMediaOpening\t= wmposMediaLoading + 1,\r\n\twmposMediaOpen\t= wmposMediaOpening + 1,\r\n\twmposBeginCodecAcquisition\t= wmposMediaOpen + 1,\r\n\twmposEndCodecAcquisition\t= wmposBeginCodecAcquisition + 1,\r\n\twmposBeginLicenseAcquisition\t= wmposEndCodecAcquisition + 1,\r\n\twmposEndLicenseAcquisition\t= wmposBeginLicenseAcquisition + 1,\r\n\twmposBeginIndividualization\t= wmposEndLicenseAcquisition + 1,\r\n\twmposEndIndividualization\t= wmposBeginIndividualization + 1,\r\n\twmposMediaWaiting\t= wmposEndIndividualization + 1,\r\n\twmposOpeningUnknownURL\t= wmposMediaWaiting + 1\r\n    } \tWMPOpenState;\r\n\r\ntypedef /* [public][helpstring] */ \r\nenum WMPPlayState\r\n    {\twmppsUndefined\t= 0,\r\n\twmppsStopped\t= wmppsUndefined + 1,\r\n\twmppsPaused\t= wmppsStopped + 1,\r\n\twmppsPlaying\t= wmppsPaused + 1,\r\n\twmppsScanForward\t= wmppsPlaying + 1,\r\n\twmppsScanReverse\t= wmppsScanForward + 1,\r\n\twmppsBuffering\t= wmppsScanReverse + 1,\r\n\twmppsWaiting\t= wmppsBuffering + 1,\r\n\twmppsMediaEnded\t= wmppsWaiting + 1,\r\n\twmppsTransitioning\t= wmppsMediaEnded + 1,\r\n\twmppsReady\t= wmppsTransitioning + 1,\r\n\twmppsReconnecting\t= wmppsReady + 1,\r\n\twmppsLast\t= wmppsReconnecting + 1\r\n    } \tWMPPlayState;\r\n\r\ntypedef /* [public][helpstring] */ \r\nenum WMPPlaylistChangeEventType\r\n    {\twmplcUnknown\t= 0,\r\n\twmplcClear\t= wmplcUnknown + 1,\r\n\twmplcInfoChange\t= wmplcClear + 1,\r\n\twmplcMove\t= wmplcInfoChange + 1,\r\n\twmplcDelete\t= wmplcMove + 1,\r\n\twmplcInsert\t= wmplcDelete + 1,\r\n\twmplcAppend\t= wmplcInsert + 1,\r\n\twmplcPrivate\t= wmplcAppend + 1,\r\n\twmplcNameChange\t= wmplcPrivate + 1,\r\n\twmplcMorph\t= wmplcNameChange + 1,\r\n\twmplcSort\t= wmplcMorph + 1,\r\n\twmplcLast\t= wmplcSort + 1\r\n    } \tWMPPlaylistChangeEventType;\r\n\r\n\r\n\r\n\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0000_v0_0_c_ifspec;\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0000_v0_0_s_ifspec;\r\n\r\n#ifndef __IWMPErrorItem_INTERFACE_DEFINED__\r\n#define __IWMPErrorItem_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPErrorItem */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPErrorItem;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"3614C646-3B3B-4de7-A81E-930E3F2127B3\")\r\n    IWMPErrorItem : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_errorCode( \r\n            /* [retval][out] */ long *phr) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_errorDescription( \r\n            /* [retval][out] */ BSTR *pbstrDescription) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_errorContext( \r\n            /* [retval][out] */ VARIANT *pvarContext) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_remedy( \r\n            /* [retval][out] */ long *plRemedy) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_customUrl( \r\n            /* [retval][out] */ BSTR *pbstrCustomUrl) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPErrorItemVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPErrorItem * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPErrorItem * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPErrorItem * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPErrorItem * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPErrorItem * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPErrorItem * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPErrorItem * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorCode )( \r\n            IWMPErrorItem * This,\r\n            /* [retval][out] */ long *phr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorDescription )( \r\n            IWMPErrorItem * This,\r\n            /* [retval][out] */ BSTR *pbstrDescription);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorContext )( \r\n            IWMPErrorItem * This,\r\n            /* [retval][out] */ VARIANT *pvarContext);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_remedy )( \r\n            IWMPErrorItem * This,\r\n            /* [retval][out] */ long *plRemedy);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_customUrl )( \r\n            IWMPErrorItem * This,\r\n            /* [retval][out] */ BSTR *pbstrCustomUrl);\r\n        \r\n        END_INTERFACE\r\n    } IWMPErrorItemVtbl;\r\n\r\n    interface IWMPErrorItem\r\n    {\r\n        CONST_VTBL struct IWMPErrorItemVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPErrorItem_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPErrorItem_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPErrorItem_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPErrorItem_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPErrorItem_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPErrorItem_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPErrorItem_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPErrorItem_get_errorCode(This,phr)\t\\\r\n    (This)->lpVtbl -> get_errorCode(This,phr)\r\n\r\n#define IWMPErrorItem_get_errorDescription(This,pbstrDescription)\t\\\r\n    (This)->lpVtbl -> get_errorDescription(This,pbstrDescription)\r\n\r\n#define IWMPErrorItem_get_errorContext(This,pvarContext)\t\\\r\n    (This)->lpVtbl -> get_errorContext(This,pvarContext)\r\n\r\n#define IWMPErrorItem_get_remedy(This,plRemedy)\t\\\r\n    (This)->lpVtbl -> get_remedy(This,plRemedy)\r\n\r\n#define IWMPErrorItem_get_customUrl(This,pbstrCustomUrl)\t\\\r\n    (This)->lpVtbl -> get_customUrl(This,pbstrCustomUrl)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem_get_errorCode_Proxy( \r\n    IWMPErrorItem * This,\r\n    /* [retval][out] */ long *phr);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem_get_errorCode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem_get_errorDescription_Proxy( \r\n    IWMPErrorItem * This,\r\n    /* [retval][out] */ BSTR *pbstrDescription);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem_get_errorDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem_get_errorContext_Proxy( \r\n    IWMPErrorItem * This,\r\n    /* [retval][out] */ VARIANT *pvarContext);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem_get_errorContext_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem_get_remedy_Proxy( \r\n    IWMPErrorItem * This,\r\n    /* [retval][out] */ long *plRemedy);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem_get_remedy_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem_get_customUrl_Proxy( \r\n    IWMPErrorItem * This,\r\n    /* [retval][out] */ BSTR *pbstrCustomUrl);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem_get_customUrl_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPErrorItem_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPError_INTERFACE_DEFINED__\r\n#define __IWMPError_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPError */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPError;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"A12DCF7D-14AB-4c1b-A8CD-63909F06025B\")\r\n    IWMPError : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE clearErrorQueue( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_errorCount( \r\n            /* [retval][out] */ long *plNumErrors) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_item( \r\n            /* [in] */ long dwIndex,\r\n            /* [retval][out] */ IWMPErrorItem **ppErrorItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE webHelp( void) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPErrorVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPError * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPError * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPError * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPError * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPError * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPError * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPError * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *clearErrorQueue )( \r\n            IWMPError * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorCount )( \r\n            IWMPError * This,\r\n            /* [retval][out] */ long *plNumErrors);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_item )( \r\n            IWMPError * This,\r\n            /* [in] */ long dwIndex,\r\n            /* [retval][out] */ IWMPErrorItem **ppErrorItem);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *webHelp )( \r\n            IWMPError * This);\r\n        \r\n        END_INTERFACE\r\n    } IWMPErrorVtbl;\r\n\r\n    interface IWMPError\r\n    {\r\n        CONST_VTBL struct IWMPErrorVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPError_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPError_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPError_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPError_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPError_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPError_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPError_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPError_clearErrorQueue(This)\t\\\r\n    (This)->lpVtbl -> clearErrorQueue(This)\r\n\r\n#define IWMPError_get_errorCount(This,plNumErrors)\t\\\r\n    (This)->lpVtbl -> get_errorCount(This,plNumErrors)\r\n\r\n#define IWMPError_get_item(This,dwIndex,ppErrorItem)\t\\\r\n    (This)->lpVtbl -> get_item(This,dwIndex,ppErrorItem)\r\n\r\n#define IWMPError_webHelp(This)\t\\\r\n    (This)->lpVtbl -> webHelp(This)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPError_clearErrorQueue_Proxy( \r\n    IWMPError * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPError_clearErrorQueue_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPError_get_errorCount_Proxy( \r\n    IWMPError * This,\r\n    /* [retval][out] */ long *plNumErrors);\r\n\r\n\r\nvoid __RPC_STUB IWMPError_get_errorCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPError_get_item_Proxy( \r\n    IWMPError * This,\r\n    /* [in] */ long dwIndex,\r\n    /* [retval][out] */ IWMPErrorItem **ppErrorItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPError_get_item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPError_webHelp_Proxy( \r\n    IWMPError * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPError_webHelp_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPError_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia_INTERFACE_DEFINED__\r\n#define __IWMPMedia_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMedia */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMedia;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"94D55E95-3FAC-11d3-B155-00C04F79FAA6\")\r\n    IWMPMedia : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isIdentical( \r\n            /* [in] */ IWMPMedia *pIWMPMedia,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_sourceURL( \r\n            /* [retval][out] */ BSTR *pbstrSourceURL) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_name( \r\n            /* [retval][out] */ BSTR *pbstrName) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_name( \r\n            /* [in] */ BSTR bstrName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_imageSourceWidth( \r\n            /* [retval][out] */ long *pWidth) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_imageSourceHeight( \r\n            /* [retval][out] */ long *pHeight) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_markerCount( \r\n            /* [retval][out] */ long *pMarkerCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getMarkerTime( \r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ double *pMarkerTime) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getMarkerName( \r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ BSTR *pbstrMarkerName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_duration( \r\n            /* [retval][out] */ double *pDuration) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_durationString( \r\n            /* [retval][out] */ BSTR *pbstrDuration) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_attributeCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAttributeName( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrItemName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getItemInfo( \r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ BSTR *pbstrVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setItemInfo( \r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [in] */ BSTR bstrVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getItemInfoByAtom( \r\n            /* [in] */ long lAtom,\r\n            /* [retval][out] */ BSTR *pbstrVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE isMemberOf( \r\n            /* [in] */ IWMPPlaylist *pPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsMemberOf) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE isReadOnlyItem( \r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsReadOnly) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMediaVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMedia * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMedia * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMedia * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMedia * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMedia * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMedia * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMedia * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isIdentical )( \r\n            IWMPMedia * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_sourceURL )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ BSTR *pbstrSourceURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_name )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_name )( \r\n            IWMPMedia * This,\r\n            /* [in] */ BSTR bstrName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceWidth )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ long *pWidth);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceHeight )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ long *pHeight);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_markerCount )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ long *pMarkerCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerTime )( \r\n            IWMPMedia * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ double *pMarkerTime);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerName )( \r\n            IWMPMedia * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ BSTR *pbstrMarkerName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_duration )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ double *pDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_durationString )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ BSTR *pbstrDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_attributeCount )( \r\n            IWMPMedia * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAttributeName )( \r\n            IWMPMedia * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrItemName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfo )( \r\n            IWMPMedia * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setItemInfo )( \r\n            IWMPMedia * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [in] */ BSTR bstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfoByAtom )( \r\n            IWMPMedia * This,\r\n            /* [in] */ long lAtom,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isMemberOf )( \r\n            IWMPMedia * This,\r\n            /* [in] */ IWMPPlaylist *pPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsMemberOf);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isReadOnlyItem )( \r\n            IWMPMedia * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsReadOnly);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMediaVtbl;\r\n\r\n    interface IWMPMedia\r\n    {\r\n        CONST_VTBL struct IWMPMediaVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMedia_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMedia_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMedia_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMedia_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMedia_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMedia_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMedia_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMedia_get_isIdentical(This,pIWMPMedia,pvbool)\t\\\r\n    (This)->lpVtbl -> get_isIdentical(This,pIWMPMedia,pvbool)\r\n\r\n#define IWMPMedia_get_sourceURL(This,pbstrSourceURL)\t\\\r\n    (This)->lpVtbl -> get_sourceURL(This,pbstrSourceURL)\r\n\r\n#define IWMPMedia_get_name(This,pbstrName)\t\\\r\n    (This)->lpVtbl -> get_name(This,pbstrName)\r\n\r\n#define IWMPMedia_put_name(This,bstrName)\t\\\r\n    (This)->lpVtbl -> put_name(This,bstrName)\r\n\r\n#define IWMPMedia_get_imageSourceWidth(This,pWidth)\t\\\r\n    (This)->lpVtbl -> get_imageSourceWidth(This,pWidth)\r\n\r\n#define IWMPMedia_get_imageSourceHeight(This,pHeight)\t\\\r\n    (This)->lpVtbl -> get_imageSourceHeight(This,pHeight)\r\n\r\n#define IWMPMedia_get_markerCount(This,pMarkerCount)\t\\\r\n    (This)->lpVtbl -> get_markerCount(This,pMarkerCount)\r\n\r\n#define IWMPMedia_getMarkerTime(This,MarkerNum,pMarkerTime)\t\\\r\n    (This)->lpVtbl -> getMarkerTime(This,MarkerNum,pMarkerTime)\r\n\r\n#define IWMPMedia_getMarkerName(This,MarkerNum,pbstrMarkerName)\t\\\r\n    (This)->lpVtbl -> getMarkerName(This,MarkerNum,pbstrMarkerName)\r\n\r\n#define IWMPMedia_get_duration(This,pDuration)\t\\\r\n    (This)->lpVtbl -> get_duration(This,pDuration)\r\n\r\n#define IWMPMedia_get_durationString(This,pbstrDuration)\t\\\r\n    (This)->lpVtbl -> get_durationString(This,pbstrDuration)\r\n\r\n#define IWMPMedia_get_attributeCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_attributeCount(This,plCount)\r\n\r\n#define IWMPMedia_getAttributeName(This,lIndex,pbstrItemName)\t\\\r\n    (This)->lpVtbl -> getAttributeName(This,lIndex,pbstrItemName)\r\n\r\n#define IWMPMedia_getItemInfo(This,bstrItemName,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfo(This,bstrItemName,pbstrVal)\r\n\r\n#define IWMPMedia_setItemInfo(This,bstrItemName,bstrVal)\t\\\r\n    (This)->lpVtbl -> setItemInfo(This,bstrItemName,bstrVal)\r\n\r\n#define IWMPMedia_getItemInfoByAtom(This,lAtom,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfoByAtom(This,lAtom,pbstrVal)\r\n\r\n#define IWMPMedia_isMemberOf(This,pPlaylist,pvarfIsMemberOf)\t\\\r\n    (This)->lpVtbl -> isMemberOf(This,pPlaylist,pvarfIsMemberOf)\r\n\r\n#define IWMPMedia_isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\t\\\r\n    (This)->lpVtbl -> isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_isIdentical_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ IWMPMedia *pIWMPMedia,\r\n    /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_isIdentical_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_sourceURL_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ BSTR *pbstrSourceURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_sourceURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_name_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ BSTR *pbstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_put_name_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ BSTR bstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_put_name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_imageSourceWidth_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ long *pWidth);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_imageSourceWidth_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_imageSourceHeight_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ long *pHeight);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_imageSourceHeight_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_markerCount_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ long *pMarkerCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_markerCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_getMarkerTime_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ long MarkerNum,\r\n    /* [retval][out] */ double *pMarkerTime);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_getMarkerTime_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_getMarkerName_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ long MarkerNum,\r\n    /* [retval][out] */ BSTR *pbstrMarkerName);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_getMarkerName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_duration_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ double *pDuration);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_duration_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_durationString_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ BSTR *pbstrDuration);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_durationString_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_get_attributeCount_Proxy( \r\n    IWMPMedia * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_get_attributeCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_getAttributeName_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ BSTR *pbstrItemName);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_getAttributeName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_getItemInfo_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ BSTR bstrItemName,\r\n    /* [retval][out] */ BSTR *pbstrVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_getItemInfo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_setItemInfo_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ BSTR bstrItemName,\r\n    /* [in] */ BSTR bstrVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_setItemInfo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_getItemInfoByAtom_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ long lAtom,\r\n    /* [retval][out] */ BSTR *pbstrVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_getItemInfoByAtom_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_isMemberOf_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ IWMPPlaylist *pPlaylist,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfIsMemberOf);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_isMemberOf_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia_isReadOnlyItem_Proxy( \r\n    IWMPMedia * This,\r\n    /* [in] */ BSTR bstrItemName,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfIsReadOnly);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia_isReadOnlyItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMedia_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls_INTERFACE_DEFINED__\r\n#define __IWMPControls_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPControls */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPControls;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"74C09E02-F828-11d2-A74B-00A0C905F36E\")\r\n    IWMPControls : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isAvailable( \r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE play( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE stop( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE pause( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE fastForward( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE fastReverse( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentPosition( \r\n            /* [retval][out] */ double *pdCurrentPosition) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentPosition( \r\n            /* [in] */ double dCurrentPosition) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentPositionString( \r\n            /* [retval][out] */ BSTR *pbstrCurrentPosition) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE next( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE previous( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentItem( \r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia) = 0;\r\n        \r\n        virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_currentItem( \r\n            /* [in] */ IWMPMedia *pIWMPMedia) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentMarker( \r\n            /* [retval][out] */ long *plMarker) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentMarker( \r\n            /* [in] */ long lMarker) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE playItem( \r\n            /* [in] */ IWMPMedia *pIWMPMedia) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPControlsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPControls * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPControls * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPControls * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPControls * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPControls * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPControls * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPControls * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPControls * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *play )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *stop )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *pause )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastForward )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastReverse )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPosition )( \r\n            IWMPControls * This,\r\n            /* [retval][out] */ double *pdCurrentPosition);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPosition )( \r\n            IWMPControls * This,\r\n            /* [in] */ double dCurrentPosition);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPositionString )( \r\n            IWMPControls * This,\r\n            /* [retval][out] */ BSTR *pbstrCurrentPosition);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *next )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *previous )( \r\n            IWMPControls * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentItem )( \r\n            IWMPControls * This,\r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentItem )( \r\n            IWMPControls * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMarker )( \r\n            IWMPControls * This,\r\n            /* [retval][out] */ long *plMarker);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMarker )( \r\n            IWMPControls * This,\r\n            /* [in] */ long lMarker);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *playItem )( \r\n            IWMPControls * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        END_INTERFACE\r\n    } IWMPControlsVtbl;\r\n\r\n    interface IWMPControls\r\n    {\r\n        CONST_VTBL struct IWMPControlsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPControls_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPControls_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPControls_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPControls_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPControls_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPControls_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPControls_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPControls_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPControls_play(This)\t\\\r\n    (This)->lpVtbl -> play(This)\r\n\r\n#define IWMPControls_stop(This)\t\\\r\n    (This)->lpVtbl -> stop(This)\r\n\r\n#define IWMPControls_pause(This)\t\\\r\n    (This)->lpVtbl -> pause(This)\r\n\r\n#define IWMPControls_fastForward(This)\t\\\r\n    (This)->lpVtbl -> fastForward(This)\r\n\r\n#define IWMPControls_fastReverse(This)\t\\\r\n    (This)->lpVtbl -> fastReverse(This)\r\n\r\n#define IWMPControls_get_currentPosition(This,pdCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPosition(This,pdCurrentPosition)\r\n\r\n#define IWMPControls_put_currentPosition(This,dCurrentPosition)\t\\\r\n    (This)->lpVtbl -> put_currentPosition(This,dCurrentPosition)\r\n\r\n#define IWMPControls_get_currentPositionString(This,pbstrCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPositionString(This,pbstrCurrentPosition)\r\n\r\n#define IWMPControls_next(This)\t\\\r\n    (This)->lpVtbl -> next(This)\r\n\r\n#define IWMPControls_previous(This)\t\\\r\n    (This)->lpVtbl -> previous(This)\r\n\r\n#define IWMPControls_get_currentItem(This,ppIWMPMedia)\t\\\r\n    (This)->lpVtbl -> get_currentItem(This,ppIWMPMedia)\r\n\r\n#define IWMPControls_put_currentItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> put_currentItem(This,pIWMPMedia)\r\n\r\n#define IWMPControls_get_currentMarker(This,plMarker)\t\\\r\n    (This)->lpVtbl -> get_currentMarker(This,plMarker)\r\n\r\n#define IWMPControls_put_currentMarker(This,lMarker)\t\\\r\n    (This)->lpVtbl -> put_currentMarker(This,lMarker)\r\n\r\n#define IWMPControls_playItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> playItem(This,pIWMPMedia)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_get_isAvailable_Proxy( \r\n    IWMPControls * This,\r\n    /* [in] */ BSTR bstrItem,\r\n    /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_get_isAvailable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_play_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_play_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_stop_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_stop_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_pause_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_pause_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_fastForward_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_fastForward_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_fastReverse_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_fastReverse_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_get_currentPosition_Proxy( \r\n    IWMPControls * This,\r\n    /* [retval][out] */ double *pdCurrentPosition);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_get_currentPosition_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_put_currentPosition_Proxy( \r\n    IWMPControls * This,\r\n    /* [in] */ double dCurrentPosition);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_put_currentPosition_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_get_currentPositionString_Proxy( \r\n    IWMPControls * This,\r\n    /* [retval][out] */ BSTR *pbstrCurrentPosition);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_get_currentPositionString_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_next_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_next_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_previous_Proxy( \r\n    IWMPControls * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_previous_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_get_currentItem_Proxy( \r\n    IWMPControls * This,\r\n    /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_get_currentItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_put_currentItem_Proxy( \r\n    IWMPControls * This,\r\n    /* [in] */ IWMPMedia *pIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_put_currentItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_get_currentMarker_Proxy( \r\n    IWMPControls * This,\r\n    /* [retval][out] */ long *plMarker);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_get_currentMarker_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_put_currentMarker_Proxy( \r\n    IWMPControls * This,\r\n    /* [in] */ long lMarker);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_put_currentMarker_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls_playItem_Proxy( \r\n    IWMPControls * This,\r\n    /* [in] */ IWMPMedia *pIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls_playItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPControls_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPSettings_INTERFACE_DEFINED__\r\n#define __IWMPSettings_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPSettings */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPSettings;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"9104D1AB-80C9-4fed-ABF0-2E6417A6DF14\")\r\n    IWMPSettings : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isAvailable( \r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_autoStart( \r\n            /* [retval][out] */ VARIANT_BOOL *pfAutoStart) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_autoStart( \r\n            /* [in] */ VARIANT_BOOL fAutoStart) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_baseURL( \r\n            /* [retval][out] */ BSTR *pbstrBaseURL) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_baseURL( \r\n            /* [in] */ BSTR bstrBaseURL) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_defaultFrame( \r\n            /* [retval][out] */ BSTR *pbstrDefaultFrame) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_defaultFrame( \r\n            /* [in] */ BSTR bstrDefaultFrame) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_invokeURLs( \r\n            /* [retval][out] */ VARIANT_BOOL *pfInvokeURLs) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_invokeURLs( \r\n            /* [in] */ VARIANT_BOOL fInvokeURLs) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_mute( \r\n            /* [retval][out] */ VARIANT_BOOL *pfMute) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_mute( \r\n            /* [in] */ VARIANT_BOOL fMute) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_playCount( \r\n            /* [in] */ long lCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_rate( \r\n            /* [retval][out] */ double *pdRate) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_rate( \r\n            /* [in] */ double dRate) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_balance( \r\n            /* [retval][out] */ long *plBalance) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_balance( \r\n            /* [in] */ long lBalance) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_volume( \r\n            /* [retval][out] */ long *plVolume) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_volume( \r\n            /* [in] */ long lVolume) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getMode( \r\n            /* [in] */ BSTR bstrMode,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfMode) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setMode( \r\n            /* [in] */ BSTR bstrMode,\r\n            /* [in] */ VARIANT_BOOL varfMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enableErrorDialogs( \r\n            /* [retval][out] */ VARIANT_BOOL *pfEnableErrorDialogs) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enableErrorDialogs( \r\n            /* [in] */ VARIANT_BOOL fEnableErrorDialogs) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPSettingsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPSettings * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPSettings * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPSettings * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPSettings * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPSettings * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPSettings * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPSettings * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPSettings * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_autoStart )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfAutoStart);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_autoStart )( \r\n            IWMPSettings * This,\r\n            /* [in] */ VARIANT_BOOL fAutoStart);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_baseURL )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ BSTR *pbstrBaseURL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_baseURL )( \r\n            IWMPSettings * This,\r\n            /* [in] */ BSTR bstrBaseURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_defaultFrame )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ BSTR *pbstrDefaultFrame);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_defaultFrame )( \r\n            IWMPSettings * This,\r\n            /* [in] */ BSTR bstrDefaultFrame);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_invokeURLs )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfInvokeURLs);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_invokeURLs )( \r\n            IWMPSettings * This,\r\n            /* [in] */ VARIANT_BOOL fInvokeURLs);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mute )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfMute);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_mute )( \r\n            IWMPSettings * This,\r\n            /* [in] */ VARIANT_BOOL fMute);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playCount )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_playCount )( \r\n            IWMPSettings * This,\r\n            /* [in] */ long lCount);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_rate )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ double *pdRate);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_rate )( \r\n            IWMPSettings * This,\r\n            /* [in] */ double dRate);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_balance )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ long *plBalance);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_balance )( \r\n            IWMPSettings * This,\r\n            /* [in] */ long lBalance);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_volume )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ long *plVolume);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_volume )( \r\n            IWMPSettings * This,\r\n            /* [in] */ long lVolume);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMode )( \r\n            IWMPSettings * This,\r\n            /* [in] */ BSTR bstrMode,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfMode);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setMode )( \r\n            IWMPSettings * This,\r\n            /* [in] */ BSTR bstrMode,\r\n            /* [in] */ VARIANT_BOOL varfMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableErrorDialogs )( \r\n            IWMPSettings * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfEnableErrorDialogs);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableErrorDialogs )( \r\n            IWMPSettings * This,\r\n            /* [in] */ VARIANT_BOOL fEnableErrorDialogs);\r\n        \r\n        END_INTERFACE\r\n    } IWMPSettingsVtbl;\r\n\r\n    interface IWMPSettings\r\n    {\r\n        CONST_VTBL struct IWMPSettingsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPSettings_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPSettings_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPSettings_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPSettings_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPSettings_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPSettings_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPSettings_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPSettings_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPSettings_get_autoStart(This,pfAutoStart)\t\\\r\n    (This)->lpVtbl -> get_autoStart(This,pfAutoStart)\r\n\r\n#define IWMPSettings_put_autoStart(This,fAutoStart)\t\\\r\n    (This)->lpVtbl -> put_autoStart(This,fAutoStart)\r\n\r\n#define IWMPSettings_get_baseURL(This,pbstrBaseURL)\t\\\r\n    (This)->lpVtbl -> get_baseURL(This,pbstrBaseURL)\r\n\r\n#define IWMPSettings_put_baseURL(This,bstrBaseURL)\t\\\r\n    (This)->lpVtbl -> put_baseURL(This,bstrBaseURL)\r\n\r\n#define IWMPSettings_get_defaultFrame(This,pbstrDefaultFrame)\t\\\r\n    (This)->lpVtbl -> get_defaultFrame(This,pbstrDefaultFrame)\r\n\r\n#define IWMPSettings_put_defaultFrame(This,bstrDefaultFrame)\t\\\r\n    (This)->lpVtbl -> put_defaultFrame(This,bstrDefaultFrame)\r\n\r\n#define IWMPSettings_get_invokeURLs(This,pfInvokeURLs)\t\\\r\n    (This)->lpVtbl -> get_invokeURLs(This,pfInvokeURLs)\r\n\r\n#define IWMPSettings_put_invokeURLs(This,fInvokeURLs)\t\\\r\n    (This)->lpVtbl -> put_invokeURLs(This,fInvokeURLs)\r\n\r\n#define IWMPSettings_get_mute(This,pfMute)\t\\\r\n    (This)->lpVtbl -> get_mute(This,pfMute)\r\n\r\n#define IWMPSettings_put_mute(This,fMute)\t\\\r\n    (This)->lpVtbl -> put_mute(This,fMute)\r\n\r\n#define IWMPSettings_get_playCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_playCount(This,plCount)\r\n\r\n#define IWMPSettings_put_playCount(This,lCount)\t\\\r\n    (This)->lpVtbl -> put_playCount(This,lCount)\r\n\r\n#define IWMPSettings_get_rate(This,pdRate)\t\\\r\n    (This)->lpVtbl -> get_rate(This,pdRate)\r\n\r\n#define IWMPSettings_put_rate(This,dRate)\t\\\r\n    (This)->lpVtbl -> put_rate(This,dRate)\r\n\r\n#define IWMPSettings_get_balance(This,plBalance)\t\\\r\n    (This)->lpVtbl -> get_balance(This,plBalance)\r\n\r\n#define IWMPSettings_put_balance(This,lBalance)\t\\\r\n    (This)->lpVtbl -> put_balance(This,lBalance)\r\n\r\n#define IWMPSettings_get_volume(This,plVolume)\t\\\r\n    (This)->lpVtbl -> get_volume(This,plVolume)\r\n\r\n#define IWMPSettings_put_volume(This,lVolume)\t\\\r\n    (This)->lpVtbl -> put_volume(This,lVolume)\r\n\r\n#define IWMPSettings_getMode(This,bstrMode,pvarfMode)\t\\\r\n    (This)->lpVtbl -> getMode(This,bstrMode,pvarfMode)\r\n\r\n#define IWMPSettings_setMode(This,bstrMode,varfMode)\t\\\r\n    (This)->lpVtbl -> setMode(This,bstrMode,varfMode)\r\n\r\n#define IWMPSettings_get_enableErrorDialogs(This,pfEnableErrorDialogs)\t\\\r\n    (This)->lpVtbl -> get_enableErrorDialogs(This,pfEnableErrorDialogs)\r\n\r\n#define IWMPSettings_put_enableErrorDialogs(This,fEnableErrorDialogs)\t\\\r\n    (This)->lpVtbl -> put_enableErrorDialogs(This,fEnableErrorDialogs)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_isAvailable_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ BSTR bstrItem,\r\n    /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_isAvailable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_autoStart_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pfAutoStart);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_autoStart_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_autoStart_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ VARIANT_BOOL fAutoStart);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_autoStart_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_baseURL_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ BSTR *pbstrBaseURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_baseURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_baseURL_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ BSTR bstrBaseURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_baseURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_defaultFrame_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ BSTR *pbstrDefaultFrame);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_defaultFrame_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_defaultFrame_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ BSTR bstrDefaultFrame);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_defaultFrame_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_invokeURLs_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pfInvokeURLs);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_invokeURLs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_invokeURLs_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ VARIANT_BOOL fInvokeURLs);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_invokeURLs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_mute_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pfMute);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_mute_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_mute_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ VARIANT_BOOL fMute);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_mute_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_playCount_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_playCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_playCount_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ long lCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_playCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_rate_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ double *pdRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_rate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_rate_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ double dRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_rate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_balance_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ long *plBalance);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_balance_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_balance_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ long lBalance);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_balance_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_volume_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ long *plVolume);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_volume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_volume_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ long lVolume);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_volume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_getMode_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ BSTR bstrMode,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_getMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_setMode_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ BSTR bstrMode,\r\n    /* [in] */ VARIANT_BOOL varfMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_setMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_get_enableErrorDialogs_Proxy( \r\n    IWMPSettings * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pfEnableErrorDialogs);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_get_enableErrorDialogs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings_put_enableErrorDialogs_Proxy( \r\n    IWMPSettings * This,\r\n    /* [in] */ VARIANT_BOOL fEnableErrorDialogs);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings_put_enableErrorDialogs_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPSettings_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPClosedCaption_INTERFACE_DEFINED__\r\n#define __IWMPClosedCaption_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPClosedCaption */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPClosedCaption;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"4F2DF574-C588-11d3-9ED0-00C04FB6E937\")\r\n    IWMPClosedCaption : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_SAMIStyle( \r\n            /* [retval][out] */ BSTR *pbstrSAMIStyle) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_SAMIStyle( \r\n            /* [in] */ BSTR bstrSAMIStyle) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_SAMILang( \r\n            /* [retval][out] */ BSTR *pbstrSAMILang) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_SAMILang( \r\n            /* [in] */ BSTR bstrSAMILang) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_SAMIFileName( \r\n            /* [retval][out] */ BSTR *pbstrSAMIFileName) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_SAMIFileName( \r\n            /* [in] */ BSTR bstrSAMIFileName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_captioningId( \r\n            /* [retval][out] */ BSTR *pbstrCaptioningID) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_captioningId( \r\n            /* [in] */ BSTR bstrCaptioningID) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPClosedCaptionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPClosedCaption * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPClosedCaption * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPClosedCaption * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMIStyle )( \r\n            IWMPClosedCaption * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMIStyle);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMIStyle )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ BSTR bstrSAMIStyle);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMILang )( \r\n            IWMPClosedCaption * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMILang);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMILang )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ BSTR bstrSAMILang);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMIFileName )( \r\n            IWMPClosedCaption * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMIFileName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMIFileName )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ BSTR bstrSAMIFileName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_captioningId )( \r\n            IWMPClosedCaption * This,\r\n            /* [retval][out] */ BSTR *pbstrCaptioningID);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_captioningId )( \r\n            IWMPClosedCaption * This,\r\n            /* [in] */ BSTR bstrCaptioningID);\r\n        \r\n        END_INTERFACE\r\n    } IWMPClosedCaptionVtbl;\r\n\r\n    interface IWMPClosedCaption\r\n    {\r\n        CONST_VTBL struct IWMPClosedCaptionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPClosedCaption_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPClosedCaption_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPClosedCaption_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPClosedCaption_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPClosedCaption_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPClosedCaption_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPClosedCaption_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPClosedCaption_get_SAMIStyle(This,pbstrSAMIStyle)\t\\\r\n    (This)->lpVtbl -> get_SAMIStyle(This,pbstrSAMIStyle)\r\n\r\n#define IWMPClosedCaption_put_SAMIStyle(This,bstrSAMIStyle)\t\\\r\n    (This)->lpVtbl -> put_SAMIStyle(This,bstrSAMIStyle)\r\n\r\n#define IWMPClosedCaption_get_SAMILang(This,pbstrSAMILang)\t\\\r\n    (This)->lpVtbl -> get_SAMILang(This,pbstrSAMILang)\r\n\r\n#define IWMPClosedCaption_put_SAMILang(This,bstrSAMILang)\t\\\r\n    (This)->lpVtbl -> put_SAMILang(This,bstrSAMILang)\r\n\r\n#define IWMPClosedCaption_get_SAMIFileName(This,pbstrSAMIFileName)\t\\\r\n    (This)->lpVtbl -> get_SAMIFileName(This,pbstrSAMIFileName)\r\n\r\n#define IWMPClosedCaption_put_SAMIFileName(This,bstrSAMIFileName)\t\\\r\n    (This)->lpVtbl -> put_SAMIFileName(This,bstrSAMIFileName)\r\n\r\n#define IWMPClosedCaption_get_captioningId(This,pbstrCaptioningID)\t\\\r\n    (This)->lpVtbl -> get_captioningId(This,pbstrCaptioningID)\r\n\r\n#define IWMPClosedCaption_put_captioningId(This,bstrCaptioningID)\t\\\r\n    (This)->lpVtbl -> put_captioningId(This,bstrCaptioningID)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_get_SAMIStyle_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [retval][out] */ BSTR *pbstrSAMIStyle);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_get_SAMIStyle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_put_SAMIStyle_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [in] */ BSTR bstrSAMIStyle);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_put_SAMIStyle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_get_SAMILang_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [retval][out] */ BSTR *pbstrSAMILang);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_get_SAMILang_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_put_SAMILang_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [in] */ BSTR bstrSAMILang);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_put_SAMILang_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_get_SAMIFileName_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [retval][out] */ BSTR *pbstrSAMIFileName);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_get_SAMIFileName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_put_SAMIFileName_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [in] */ BSTR bstrSAMIFileName);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_put_SAMIFileName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_get_captioningId_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [retval][out] */ BSTR *pbstrCaptioningID);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_get_captioningId_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption_put_captioningId_Proxy( \r\n    IWMPClosedCaption * This,\r\n    /* [in] */ BSTR bstrCaptioningID);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption_put_captioningId_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPClosedCaption_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylist_INTERFACE_DEFINED__\r\n#define __IWMPPlaylist_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlaylist */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlaylist;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"D5F0F4F1-130C-11d3-B14E-00C04F79FAA6\")\r\n    IWMPPlaylist : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_count( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_name( \r\n            /* [retval][out] */ BSTR *pbstrName) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_name( \r\n            /* [in] */ BSTR bstrName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_attributeCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_attributeName( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrAttributeName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_item( \r\n            long lIndex,\r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getItemInfo( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ BSTR *pbstrVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setItemInfo( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [in] */ BSTR bstrValue) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isIdentical( \r\n            /* [in] */ IWMPPlaylist *pIWMPPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE clear( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE insertItem( \r\n            /* [in] */ long lIndex,\r\n            /* [in] */ IWMPMedia *pIWMPMedia) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE appendItem( \r\n            /* [in] */ IWMPMedia *pIWMPMedia) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE removeItem( \r\n            /* [in] */ IWMPMedia *pIWMPMedia) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE moveItem( \r\n            long lIndexOld,\r\n            long lIndexNew) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlaylistVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlaylist * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlaylist * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlaylist * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_count )( \r\n            IWMPPlaylist * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_name )( \r\n            IWMPPlaylist * This,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_name )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ BSTR bstrName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_attributeCount )( \r\n            IWMPPlaylist * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_attributeName )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrAttributeName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_item )( \r\n            IWMPPlaylist * This,\r\n            long lIndex,\r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfo )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setItemInfo )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [in] */ BSTR bstrValue);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isIdentical )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ IWMPPlaylist *pIWMPPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *clear )( \r\n            IWMPPlaylist * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *insertItem )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ long lIndex,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *appendItem )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *removeItem )( \r\n            IWMPPlaylist * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *moveItem )( \r\n            IWMPPlaylist * This,\r\n            long lIndexOld,\r\n            long lIndexNew);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlaylistVtbl;\r\n\r\n    interface IWMPPlaylist\r\n    {\r\n        CONST_VTBL struct IWMPPlaylistVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlaylist_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlaylist_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlaylist_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlaylist_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlaylist_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlaylist_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlaylist_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlaylist_get_count(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_count(This,plCount)\r\n\r\n#define IWMPPlaylist_get_name(This,pbstrName)\t\\\r\n    (This)->lpVtbl -> get_name(This,pbstrName)\r\n\r\n#define IWMPPlaylist_put_name(This,bstrName)\t\\\r\n    (This)->lpVtbl -> put_name(This,bstrName)\r\n\r\n#define IWMPPlaylist_get_attributeCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_attributeCount(This,plCount)\r\n\r\n#define IWMPPlaylist_get_attributeName(This,lIndex,pbstrAttributeName)\t\\\r\n    (This)->lpVtbl -> get_attributeName(This,lIndex,pbstrAttributeName)\r\n\r\n#define IWMPPlaylist_get_item(This,lIndex,ppIWMPMedia)\t\\\r\n    (This)->lpVtbl -> get_item(This,lIndex,ppIWMPMedia)\r\n\r\n#define IWMPPlaylist_getItemInfo(This,bstrName,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfo(This,bstrName,pbstrVal)\r\n\r\n#define IWMPPlaylist_setItemInfo(This,bstrName,bstrValue)\t\\\r\n    (This)->lpVtbl -> setItemInfo(This,bstrName,bstrValue)\r\n\r\n#define IWMPPlaylist_get_isIdentical(This,pIWMPPlaylist,pvbool)\t\\\r\n    (This)->lpVtbl -> get_isIdentical(This,pIWMPPlaylist,pvbool)\r\n\r\n#define IWMPPlaylist_clear(This)\t\\\r\n    (This)->lpVtbl -> clear(This)\r\n\r\n#define IWMPPlaylist_insertItem(This,lIndex,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> insertItem(This,lIndex,pIWMPMedia)\r\n\r\n#define IWMPPlaylist_appendItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> appendItem(This,pIWMPMedia)\r\n\r\n#define IWMPPlaylist_removeItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> removeItem(This,pIWMPMedia)\r\n\r\n#define IWMPPlaylist_moveItem(This,lIndexOld,lIndexNew)\t\\\r\n    (This)->lpVtbl -> moveItem(This,lIndexOld,lIndexNew)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_count_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_name_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [retval][out] */ BSTR *pbstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_put_name_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ BSTR bstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_put_name_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_attributeCount_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_attributeCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_attributeName_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ BSTR *pbstrAttributeName);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_attributeName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_item_Proxy( \r\n    IWMPPlaylist * This,\r\n    long lIndex,\r\n    /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_getItemInfo_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [retval][out] */ BSTR *pbstrVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_getItemInfo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_setItemInfo_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [in] */ BSTR bstrValue);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_setItemInfo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_get_isIdentical_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ IWMPPlaylist *pIWMPPlaylist,\r\n    /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_get_isIdentical_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_clear_Proxy( \r\n    IWMPPlaylist * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_clear_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_insertItem_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ long lIndex,\r\n    /* [in] */ IWMPMedia *pIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_insertItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_appendItem_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ IWMPMedia *pIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_appendItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_removeItem_Proxy( \r\n    IWMPPlaylist * This,\r\n    /* [in] */ IWMPMedia *pIWMPMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_removeItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylist_moveItem_Proxy( \r\n    IWMPPlaylist * This,\r\n    long lIndexOld,\r\n    long lIndexNew);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylist_moveItem_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlaylist_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCdrom_INTERFACE_DEFINED__\r\n#define __IWMPCdrom_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPCdrom */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPCdrom;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"cfab6e98-8730-11d3-b388-00c04f68574b\")\r\n    IWMPCdrom : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_driveSpecifier( \r\n            /* [retval][out] */ BSTR *pbstrDrive) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playlist( \r\n            /* [retval][out] */ IWMPPlaylist **ppPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE eject( void) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPCdromVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPCdrom * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPCdrom * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPCdrom * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPCdrom * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPCdrom * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPCdrom * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPCdrom * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_driveSpecifier )( \r\n            IWMPCdrom * This,\r\n            /* [retval][out] */ BSTR *pbstrDrive);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlist )( \r\n            IWMPCdrom * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPlaylist);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *eject )( \r\n            IWMPCdrom * This);\r\n        \r\n        END_INTERFACE\r\n    } IWMPCdromVtbl;\r\n\r\n    interface IWMPCdrom\r\n    {\r\n        CONST_VTBL struct IWMPCdromVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPCdrom_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPCdrom_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPCdrom_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPCdrom_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPCdrom_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPCdrom_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPCdrom_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPCdrom_get_driveSpecifier(This,pbstrDrive)\t\\\r\n    (This)->lpVtbl -> get_driveSpecifier(This,pbstrDrive)\r\n\r\n#define IWMPCdrom_get_playlist(This,ppPlaylist)\t\\\r\n    (This)->lpVtbl -> get_playlist(This,ppPlaylist)\r\n\r\n#define IWMPCdrom_eject(This)\t\\\r\n    (This)->lpVtbl -> eject(This)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCdrom_get_driveSpecifier_Proxy( \r\n    IWMPCdrom * This,\r\n    /* [retval][out] */ BSTR *pbstrDrive);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdrom_get_driveSpecifier_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCdrom_get_playlist_Proxy( \r\n    IWMPCdrom * This,\r\n    /* [retval][out] */ IWMPPlaylist **ppPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdrom_get_playlist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCdrom_eject_Proxy( \r\n    IWMPCdrom * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdrom_eject_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPCdrom_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCdromCollection_INTERFACE_DEFINED__\r\n#define __IWMPCdromCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPCdromCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPCdromCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"EE4C8FE2-34B2-11d3-A3BF-006097C9B344\")\r\n    IWMPCdromCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_count( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE item( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ IWMPCdrom **ppItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByDriveSpecifier( \r\n            /* [in] */ BSTR bstrDriveSpecifier,\r\n            /* [retval][out] */ IWMPCdrom **ppCdrom) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPCdromCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPCdromCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPCdromCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPCdromCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_count )( \r\n            IWMPCdromCollection * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *item )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ IWMPCdrom **ppItem);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByDriveSpecifier )( \r\n            IWMPCdromCollection * This,\r\n            /* [in] */ BSTR bstrDriveSpecifier,\r\n            /* [retval][out] */ IWMPCdrom **ppCdrom);\r\n        \r\n        END_INTERFACE\r\n    } IWMPCdromCollectionVtbl;\r\n\r\n    interface IWMPCdromCollection\r\n    {\r\n        CONST_VTBL struct IWMPCdromCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPCdromCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPCdromCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPCdromCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPCdromCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPCdromCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPCdromCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPCdromCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPCdromCollection_get_count(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_count(This,plCount)\r\n\r\n#define IWMPCdromCollection_item(This,lIndex,ppItem)\t\\\r\n    (This)->lpVtbl -> item(This,lIndex,ppItem)\r\n\r\n#define IWMPCdromCollection_getByDriveSpecifier(This,bstrDriveSpecifier,ppCdrom)\t\\\r\n    (This)->lpVtbl -> getByDriveSpecifier(This,bstrDriveSpecifier,ppCdrom)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCdromCollection_get_count_Proxy( \r\n    IWMPCdromCollection * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdromCollection_get_count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCdromCollection_item_Proxy( \r\n    IWMPCdromCollection * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ IWMPCdrom **ppItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdromCollection_item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCdromCollection_getByDriveSpecifier_Proxy( \r\n    IWMPCdromCollection * This,\r\n    /* [in] */ BSTR bstrDriveSpecifier,\r\n    /* [retval][out] */ IWMPCdrom **ppCdrom);\r\n\r\n\r\nvoid __RPC_STUB IWMPCdromCollection_getByDriveSpecifier_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPCdromCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPStringCollection_INTERFACE_DEFINED__\r\n#define __IWMPStringCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPStringCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPStringCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"4a976298-8c0d-11d3-b389-00c04f68574b\")\r\n    IWMPStringCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_count( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE item( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrString) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPStringCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPStringCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPStringCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPStringCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPStringCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPStringCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPStringCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPStringCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_count )( \r\n            IWMPStringCollection * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *item )( \r\n            IWMPStringCollection * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrString);\r\n        \r\n        END_INTERFACE\r\n    } IWMPStringCollectionVtbl;\r\n\r\n    interface IWMPStringCollection\r\n    {\r\n        CONST_VTBL struct IWMPStringCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPStringCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPStringCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPStringCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPStringCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPStringCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPStringCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPStringCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPStringCollection_get_count(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_count(This,plCount)\r\n\r\n#define IWMPStringCollection_item(This,lIndex,pbstrString)\t\\\r\n    (This)->lpVtbl -> item(This,lIndex,pbstrString)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPStringCollection_get_count_Proxy( \r\n    IWMPStringCollection * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPStringCollection_get_count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPStringCollection_item_Proxy( \r\n    IWMPStringCollection * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ BSTR *pbstrString);\r\n\r\n\r\nvoid __RPC_STUB IWMPStringCollection_item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPStringCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMediaCollection_INTERFACE_DEFINED__\r\n#define __IWMPMediaCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMediaCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMediaCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"8363BC22-B4B4-4b19-989D-1CD765749DD1\")\r\n    IWMPMediaCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE add( \r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPMedia **ppItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAll( \r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByName( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByGenre( \r\n            /* [in] */ BSTR bstrGenre,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByAuthor( \r\n            /* [in] */ BSTR bstrAuthor,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByAlbum( \r\n            /* [in] */ BSTR bstrAlbum,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByAttribute( \r\n            /* [in] */ BSTR bstrAttribute,\r\n            /* [in] */ BSTR bstrValue,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE remove( \r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [in] */ VARIANT_BOOL varfDeleteFile) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAttributeStringCollection( \r\n            /* [in] */ BSTR bstrAttribute,\r\n            /* [in] */ BSTR bstrMediaType,\r\n            /* [retval][out] */ IWMPStringCollection **ppStringCollection) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getMediaAtom( \r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ long *plAtom) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setDeleted( \r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE isDeleted( \r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMediaCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMediaCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMediaCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMediaCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *add )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPMedia **ppItem);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAll )( \r\n            IWMPMediaCollection * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByName )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByGenre )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrGenre,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByAuthor )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrAuthor,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByAlbum )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrAlbum,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByAttribute )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrAttribute,\r\n            /* [in] */ BSTR bstrValue,\r\n            /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *remove )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [in] */ VARIANT_BOOL varfDeleteFile);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAttributeStringCollection )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrAttribute,\r\n            /* [in] */ BSTR bstrMediaType,\r\n            /* [retval][out] */ IWMPStringCollection **ppStringCollection);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMediaAtom )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ long *plAtom);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setDeleted )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isDeleted )( \r\n            IWMPMediaCollection * This,\r\n            /* [in] */ IWMPMedia *pItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMediaCollectionVtbl;\r\n\r\n    interface IWMPMediaCollection\r\n    {\r\n        CONST_VTBL struct IWMPMediaCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMediaCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMediaCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMediaCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMediaCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMediaCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMediaCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMediaCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMediaCollection_add(This,bstrURL,ppItem)\t\\\r\n    (This)->lpVtbl -> add(This,bstrURL,ppItem)\r\n\r\n#define IWMPMediaCollection_getAll(This,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getAll(This,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_getByName(This,bstrName,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getByName(This,bstrName,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_getByGenre(This,bstrGenre,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getByGenre(This,bstrGenre,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_getByAuthor(This,bstrAuthor,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getByAuthor(This,bstrAuthor,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_getByAlbum(This,bstrAlbum,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getByAlbum(This,bstrAlbum,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_getByAttribute(This,bstrAttribute,bstrValue,ppMediaItems)\t\\\r\n    (This)->lpVtbl -> getByAttribute(This,bstrAttribute,bstrValue,ppMediaItems)\r\n\r\n#define IWMPMediaCollection_remove(This,pItem,varfDeleteFile)\t\\\r\n    (This)->lpVtbl -> remove(This,pItem,varfDeleteFile)\r\n\r\n#define IWMPMediaCollection_getAttributeStringCollection(This,bstrAttribute,bstrMediaType,ppStringCollection)\t\\\r\n    (This)->lpVtbl -> getAttributeStringCollection(This,bstrAttribute,bstrMediaType,ppStringCollection)\r\n\r\n#define IWMPMediaCollection_getMediaAtom(This,bstrItemName,plAtom)\t\\\r\n    (This)->lpVtbl -> getMediaAtom(This,bstrItemName,plAtom)\r\n\r\n#define IWMPMediaCollection_setDeleted(This,pItem,varfIsDeleted)\t\\\r\n    (This)->lpVtbl -> setDeleted(This,pItem,varfIsDeleted)\r\n\r\n#define IWMPMediaCollection_isDeleted(This,pItem,pvarfIsDeleted)\t\\\r\n    (This)->lpVtbl -> isDeleted(This,pItem,pvarfIsDeleted)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_add_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrURL,\r\n    /* [retval][out] */ IWMPMedia **ppItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_add_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getAll_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getAll_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getByName_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getByGenre_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrGenre,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getByGenre_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getByAuthor_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrAuthor,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getByAuthor_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getByAlbum_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrAlbum,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getByAlbum_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getByAttribute_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrAttribute,\r\n    /* [in] */ BSTR bstrValue,\r\n    /* [retval][out] */ IWMPPlaylist **ppMediaItems);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getByAttribute_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_remove_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ IWMPMedia *pItem,\r\n    /* [in] */ VARIANT_BOOL varfDeleteFile);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_remove_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getAttributeStringCollection_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrAttribute,\r\n    /* [in] */ BSTR bstrMediaType,\r\n    /* [retval][out] */ IWMPStringCollection **ppStringCollection);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getAttributeStringCollection_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_getMediaAtom_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ BSTR bstrItemName,\r\n    /* [retval][out] */ long *plAtom);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_getMediaAtom_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_setDeleted_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ IWMPMedia *pItem,\r\n    /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_setDeleted_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPMediaCollection_isDeleted_Proxy( \r\n    IWMPMediaCollection * This,\r\n    /* [in] */ IWMPMedia *pItem,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted);\r\n\r\n\r\nvoid __RPC_STUB IWMPMediaCollection_isDeleted_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMediaCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylistArray_INTERFACE_DEFINED__\r\n#define __IWMPPlaylistArray_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlaylistArray */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlaylistArray;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"679409c0-99f7-11d3-9fb7-00105aa620bb\")\r\n    IWMPPlaylistArray : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_count( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE item( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ IWMPPlaylist **ppItem) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlaylistArrayVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlaylistArray * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlaylistArray * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlaylistArray * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlaylistArray * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlaylistArray * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlaylistArray * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlaylistArray * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_count )( \r\n            IWMPPlaylistArray * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *item )( \r\n            IWMPPlaylistArray * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ IWMPPlaylist **ppItem);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlaylistArrayVtbl;\r\n\r\n    interface IWMPPlaylistArray\r\n    {\r\n        CONST_VTBL struct IWMPPlaylistArrayVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlaylistArray_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlaylistArray_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlaylistArray_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlaylistArray_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlaylistArray_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlaylistArray_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlaylistArray_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlaylistArray_get_count(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_count(This,plCount)\r\n\r\n#define IWMPPlaylistArray_item(This,lIndex,ppItem)\t\\\r\n    (This)->lpVtbl -> item(This,lIndex,ppItem)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistArray_get_count_Proxy( \r\n    IWMPPlaylistArray * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistArray_get_count_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistArray_item_Proxy( \r\n    IWMPPlaylistArray * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ IWMPPlaylist **ppItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistArray_item_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlaylistArray_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlaylistCollection_INTERFACE_DEFINED__\r\n#define __IWMPPlaylistCollection_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlaylistCollection */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlaylistCollection;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"10A13217-23A7-439b-B1C0-D847C79B7774\")\r\n    IWMPPlaylistCollection : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE newPlaylist( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylist **ppItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAll( \r\n            /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getByName( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE remove( \r\n            /* [in] */ IWMPPlaylist *pItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setDeleted( \r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE isDeleted( \r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE importPlaylist( \r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [retval][out] */ IWMPPlaylist **ppImportedItem) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlaylistCollectionVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlaylistCollection * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlaylistCollection * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *newPlaylist )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylist **ppItem);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAll )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getByName )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *remove )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ IWMPPlaylist *pItem);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setDeleted )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isDeleted )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *importPlaylist )( \r\n            IWMPPlaylistCollection * This,\r\n            /* [in] */ IWMPPlaylist *pItem,\r\n            /* [retval][out] */ IWMPPlaylist **ppImportedItem);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlaylistCollectionVtbl;\r\n\r\n    interface IWMPPlaylistCollection\r\n    {\r\n        CONST_VTBL struct IWMPPlaylistCollectionVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlaylistCollection_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlaylistCollection_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlaylistCollection_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlaylistCollection_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlaylistCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlaylistCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlaylistCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlaylistCollection_newPlaylist(This,bstrName,ppItem)\t\\\r\n    (This)->lpVtbl -> newPlaylist(This,bstrName,ppItem)\r\n\r\n#define IWMPPlaylistCollection_getAll(This,ppPlaylistArray)\t\\\r\n    (This)->lpVtbl -> getAll(This,ppPlaylistArray)\r\n\r\n#define IWMPPlaylistCollection_getByName(This,bstrName,ppPlaylistArray)\t\\\r\n    (This)->lpVtbl -> getByName(This,bstrName,ppPlaylistArray)\r\n\r\n#define IWMPPlaylistCollection_remove(This,pItem)\t\\\r\n    (This)->lpVtbl -> remove(This,pItem)\r\n\r\n#define IWMPPlaylistCollection_setDeleted(This,pItem,varfIsDeleted)\t\\\r\n    (This)->lpVtbl -> setDeleted(This,pItem,varfIsDeleted)\r\n\r\n#define IWMPPlaylistCollection_isDeleted(This,pItem,pvarfIsDeleted)\t\\\r\n    (This)->lpVtbl -> isDeleted(This,pItem,pvarfIsDeleted)\r\n\r\n#define IWMPPlaylistCollection_importPlaylist(This,pItem,ppImportedItem)\t\\\r\n    (This)->lpVtbl -> importPlaylist(This,pItem,ppImportedItem)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_newPlaylist_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [retval][out] */ IWMPPlaylist **ppItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_newPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_getAll_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_getAll_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_getByName_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [retval][out] */ IWMPPlaylistArray **ppPlaylistArray);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_getByName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_remove_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ IWMPPlaylist *pItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_remove_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_setDeleted_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ IWMPPlaylist *pItem,\r\n    /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_setDeleted_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_isDeleted_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ IWMPPlaylist *pItem,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfIsDeleted);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_isDeleted_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlaylistCollection_importPlaylist_Proxy( \r\n    IWMPPlaylistCollection * This,\r\n    /* [in] */ IWMPPlaylist *pItem,\r\n    /* [retval][out] */ IWMPPlaylist **ppImportedItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlaylistCollection_importPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlaylistCollection_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPNetwork_INTERFACE_DEFINED__\r\n#define __IWMPNetwork_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPNetwork */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPNetwork;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"EC21B779-EDEF-462d-BBA4-AD9DDE2B29A7\")\r\n    IWMPNetwork : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_bandWidth( \r\n            /* [retval][out] */ long *plBandwidth) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_recoveredPackets( \r\n            /* [retval][out] */ long *plRecoveredPackets) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_sourceProtocol( \r\n            /* [retval][out] */ BSTR *pbstrSourceProtocol) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_receivedPackets( \r\n            /* [retval][out] */ long *plReceivedPackets) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_lostPackets( \r\n            /* [retval][out] */ long *plLostPackets) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_receptionQuality( \r\n            /* [retval][out] */ long *plReceptionQuality) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_bufferingCount( \r\n            /* [retval][out] */ long *plBufferingCount) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_bufferingProgress( \r\n            /* [retval][out] */ long *plBufferingProgress) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_bufferingTime( \r\n            /* [retval][out] */ long *plBufferingTime) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_bufferingTime( \r\n            /* [in] */ long lBufferingTime) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_frameRate( \r\n            /* [retval][out] */ long *plFrameRate) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_maxBitRate( \r\n            /* [retval][out] */ long *plBitRate) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_bitRate( \r\n            /* [retval][out] */ long *plBitRate) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getProxySettings( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ long *plProxySetting) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setProxySettings( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ long lProxySetting) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getProxyName( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ BSTR *pbstrProxyName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setProxyName( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ BSTR bstrProxyName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getProxyPort( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ long *lProxyPort) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setProxyPort( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ long lProxyPort) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getProxyExceptionList( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ BSTR *pbstrExceptionList) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setProxyExceptionList( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ BSTR pbstrExceptionList) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getProxyBypassForLocal( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ VARIANT_BOOL *pfBypassForLocal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE setProxyBypassForLocal( \r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ VARIANT_BOOL fBypassForLocal) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_maxBandwidth( \r\n            /* [retval][out] */ long *lMaxBandwidth) = 0;\r\n        \r\n        virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_maxBandwidth( \r\n            /* [in] */ long lMaxBandwidth) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_downloadProgress( \r\n            /* [retval][out] */ long *plDownloadProgress) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_encodedFrameRate( \r\n            /* [retval][out] */ long *plFrameRate) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_framesSkipped( \r\n            /* [retval][out] */ long *plFrames) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPNetworkVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPNetwork * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPNetwork * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPNetwork * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_bandWidth )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBandwidth);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_recoveredPackets )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plRecoveredPackets);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_sourceProtocol )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ BSTR *pbstrSourceProtocol);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_receivedPackets )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plReceivedPackets);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_lostPackets )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plLostPackets);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_receptionQuality )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plReceptionQuality);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_bufferingCount )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBufferingCount);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_bufferingProgress )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBufferingProgress);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_bufferingTime )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBufferingTime);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_bufferingTime )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ long lBufferingTime);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_frameRate )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plFrameRate);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_maxBitRate )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBitRate);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_bitRate )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plBitRate);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getProxySettings )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ long *plProxySetting);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setProxySettings )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ long lProxySetting);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getProxyName )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ BSTR *pbstrProxyName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setProxyName )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ BSTR bstrProxyName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getProxyPort )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ long *lProxyPort);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setProxyPort )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ long lProxyPort);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getProxyExceptionList )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ BSTR *pbstrExceptionList);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setProxyExceptionList )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ BSTR pbstrExceptionList);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getProxyBypassForLocal )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [retval][out] */ VARIANT_BOOL *pfBypassForLocal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setProxyBypassForLocal )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ BSTR bstrProtocol,\r\n            /* [in] */ VARIANT_BOOL fBypassForLocal);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_maxBandwidth )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *lMaxBandwidth);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_maxBandwidth )( \r\n            IWMPNetwork * This,\r\n            /* [in] */ long lMaxBandwidth);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_downloadProgress )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plDownloadProgress);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_encodedFrameRate )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plFrameRate);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_framesSkipped )( \r\n            IWMPNetwork * This,\r\n            /* [retval][out] */ long *plFrames);\r\n        \r\n        END_INTERFACE\r\n    } IWMPNetworkVtbl;\r\n\r\n    interface IWMPNetwork\r\n    {\r\n        CONST_VTBL struct IWMPNetworkVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPNetwork_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPNetwork_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPNetwork_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPNetwork_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPNetwork_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPNetwork_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPNetwork_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPNetwork_get_bandWidth(This,plBandwidth)\t\\\r\n    (This)->lpVtbl -> get_bandWidth(This,plBandwidth)\r\n\r\n#define IWMPNetwork_get_recoveredPackets(This,plRecoveredPackets)\t\\\r\n    (This)->lpVtbl -> get_recoveredPackets(This,plRecoveredPackets)\r\n\r\n#define IWMPNetwork_get_sourceProtocol(This,pbstrSourceProtocol)\t\\\r\n    (This)->lpVtbl -> get_sourceProtocol(This,pbstrSourceProtocol)\r\n\r\n#define IWMPNetwork_get_receivedPackets(This,plReceivedPackets)\t\\\r\n    (This)->lpVtbl -> get_receivedPackets(This,plReceivedPackets)\r\n\r\n#define IWMPNetwork_get_lostPackets(This,plLostPackets)\t\\\r\n    (This)->lpVtbl -> get_lostPackets(This,plLostPackets)\r\n\r\n#define IWMPNetwork_get_receptionQuality(This,plReceptionQuality)\t\\\r\n    (This)->lpVtbl -> get_receptionQuality(This,plReceptionQuality)\r\n\r\n#define IWMPNetwork_get_bufferingCount(This,plBufferingCount)\t\\\r\n    (This)->lpVtbl -> get_bufferingCount(This,plBufferingCount)\r\n\r\n#define IWMPNetwork_get_bufferingProgress(This,plBufferingProgress)\t\\\r\n    (This)->lpVtbl -> get_bufferingProgress(This,plBufferingProgress)\r\n\r\n#define IWMPNetwork_get_bufferingTime(This,plBufferingTime)\t\\\r\n    (This)->lpVtbl -> get_bufferingTime(This,plBufferingTime)\r\n\r\n#define IWMPNetwork_put_bufferingTime(This,lBufferingTime)\t\\\r\n    (This)->lpVtbl -> put_bufferingTime(This,lBufferingTime)\r\n\r\n#define IWMPNetwork_get_frameRate(This,plFrameRate)\t\\\r\n    (This)->lpVtbl -> get_frameRate(This,plFrameRate)\r\n\r\n#define IWMPNetwork_get_maxBitRate(This,plBitRate)\t\\\r\n    (This)->lpVtbl -> get_maxBitRate(This,plBitRate)\r\n\r\n#define IWMPNetwork_get_bitRate(This,plBitRate)\t\\\r\n    (This)->lpVtbl -> get_bitRate(This,plBitRate)\r\n\r\n#define IWMPNetwork_getProxySettings(This,bstrProtocol,plProxySetting)\t\\\r\n    (This)->lpVtbl -> getProxySettings(This,bstrProtocol,plProxySetting)\r\n\r\n#define IWMPNetwork_setProxySettings(This,bstrProtocol,lProxySetting)\t\\\r\n    (This)->lpVtbl -> setProxySettings(This,bstrProtocol,lProxySetting)\r\n\r\n#define IWMPNetwork_getProxyName(This,bstrProtocol,pbstrProxyName)\t\\\r\n    (This)->lpVtbl -> getProxyName(This,bstrProtocol,pbstrProxyName)\r\n\r\n#define IWMPNetwork_setProxyName(This,bstrProtocol,bstrProxyName)\t\\\r\n    (This)->lpVtbl -> setProxyName(This,bstrProtocol,bstrProxyName)\r\n\r\n#define IWMPNetwork_getProxyPort(This,bstrProtocol,lProxyPort)\t\\\r\n    (This)->lpVtbl -> getProxyPort(This,bstrProtocol,lProxyPort)\r\n\r\n#define IWMPNetwork_setProxyPort(This,bstrProtocol,lProxyPort)\t\\\r\n    (This)->lpVtbl -> setProxyPort(This,bstrProtocol,lProxyPort)\r\n\r\n#define IWMPNetwork_getProxyExceptionList(This,bstrProtocol,pbstrExceptionList)\t\\\r\n    (This)->lpVtbl -> getProxyExceptionList(This,bstrProtocol,pbstrExceptionList)\r\n\r\n#define IWMPNetwork_setProxyExceptionList(This,bstrProtocol,pbstrExceptionList)\t\\\r\n    (This)->lpVtbl -> setProxyExceptionList(This,bstrProtocol,pbstrExceptionList)\r\n\r\n#define IWMPNetwork_getProxyBypassForLocal(This,bstrProtocol,pfBypassForLocal)\t\\\r\n    (This)->lpVtbl -> getProxyBypassForLocal(This,bstrProtocol,pfBypassForLocal)\r\n\r\n#define IWMPNetwork_setProxyBypassForLocal(This,bstrProtocol,fBypassForLocal)\t\\\r\n    (This)->lpVtbl -> setProxyBypassForLocal(This,bstrProtocol,fBypassForLocal)\r\n\r\n#define IWMPNetwork_get_maxBandwidth(This,lMaxBandwidth)\t\\\r\n    (This)->lpVtbl -> get_maxBandwidth(This,lMaxBandwidth)\r\n\r\n#define IWMPNetwork_put_maxBandwidth(This,lMaxBandwidth)\t\\\r\n    (This)->lpVtbl -> put_maxBandwidth(This,lMaxBandwidth)\r\n\r\n#define IWMPNetwork_get_downloadProgress(This,plDownloadProgress)\t\\\r\n    (This)->lpVtbl -> get_downloadProgress(This,plDownloadProgress)\r\n\r\n#define IWMPNetwork_get_encodedFrameRate(This,plFrameRate)\t\\\r\n    (This)->lpVtbl -> get_encodedFrameRate(This,plFrameRate)\r\n\r\n#define IWMPNetwork_get_framesSkipped(This,plFrames)\t\\\r\n    (This)->lpVtbl -> get_framesSkipped(This,plFrames)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_bandWidth_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBandwidth);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_bandWidth_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_recoveredPackets_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plRecoveredPackets);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_recoveredPackets_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_sourceProtocol_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ BSTR *pbstrSourceProtocol);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_sourceProtocol_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_receivedPackets_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plReceivedPackets);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_receivedPackets_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_lostPackets_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plLostPackets);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_lostPackets_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_receptionQuality_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plReceptionQuality);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_receptionQuality_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_bufferingCount_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBufferingCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_bufferingCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_bufferingProgress_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBufferingProgress);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_bufferingProgress_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_bufferingTime_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBufferingTime);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_bufferingTime_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_put_bufferingTime_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ long lBufferingTime);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_put_bufferingTime_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_frameRate_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plFrameRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_frameRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_maxBitRate_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBitRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_maxBitRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_bitRate_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plBitRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_bitRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_getProxySettings_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [retval][out] */ long *plProxySetting);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_getProxySettings_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_setProxySettings_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [in] */ long lProxySetting);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_setProxySettings_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_getProxyName_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [retval][out] */ BSTR *pbstrProxyName);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_getProxyName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_setProxyName_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [in] */ BSTR bstrProxyName);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_setProxyName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_getProxyPort_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [retval][out] */ long *lProxyPort);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_getProxyPort_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_setProxyPort_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [in] */ long lProxyPort);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_setProxyPort_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_getProxyExceptionList_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [retval][out] */ BSTR *pbstrExceptionList);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_getProxyExceptionList_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_setProxyExceptionList_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [in] */ BSTR pbstrExceptionList);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_setProxyExceptionList_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_getProxyBypassForLocal_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [retval][out] */ VARIANT_BOOL *pfBypassForLocal);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_getProxyBypassForLocal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_setProxyBypassForLocal_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ BSTR bstrProtocol,\r\n    /* [in] */ VARIANT_BOOL fBypassForLocal);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_setProxyBypassForLocal_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_maxBandwidth_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *lMaxBandwidth);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_maxBandwidth_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propput][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_put_maxBandwidth_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [in] */ long lMaxBandwidth);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_put_maxBandwidth_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_downloadProgress_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plDownloadProgress);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_downloadProgress_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_encodedFrameRate_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plFrameRate);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_encodedFrameRate_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPNetwork_get_framesSkipped_Proxy( \r\n    IWMPNetwork * This,\r\n    /* [retval][out] */ long *plFrames);\r\n\r\n\r\nvoid __RPC_STUB IWMPNetwork_get_framesSkipped_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPNetwork_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore_INTERFACE_DEFINED__\r\n#define __IWMPCore_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPCore */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPCore;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"D84CCA99-CCE2-11d2-9ECC-0000F8085981\")\r\n    IWMPCore : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE close( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_URL( \r\n            /* [retval][out] */ BSTR *pbstrURL) = 0;\r\n        \r\n        virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_URL( \r\n            /* [in] */ BSTR bstrURL) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_openState( \r\n            /* [retval][out] */ WMPOpenState *pwmpos) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playState( \r\n            /* [retval][out] */ WMPPlayState *pwmpps) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_controls( \r\n            /* [retval][out] */ IWMPControls **ppControl) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_settings( \r\n            /* [retval][out] */ IWMPSettings **ppSettings) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentMedia( \r\n            /* [retval][out] */ IWMPMedia **ppMedia) = 0;\r\n        \r\n        virtual /* [propput][id] */ HRESULT STDMETHODCALLTYPE put_currentMedia( \r\n            /* [in] */ IWMPMedia *pMedia) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_mediaCollection( \r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playlistCollection( \r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_versionInfo( \r\n            /* [retval][out] */ BSTR *pbstrVersionInfo) = 0;\r\n        \r\n        virtual /* [id] */ HRESULT STDMETHODCALLTYPE launchURL( \r\n            /* [in] */ BSTR bstrURL) = 0;\r\n        \r\n        virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_network( \r\n            /* [retval][out] */ IWMPNetwork **ppQNI) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentPlaylist( \r\n            /* [retval][out] */ IWMPPlaylist **ppPL) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentPlaylist( \r\n            /* [in] */ IWMPPlaylist *pPL) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_cdromCollection( \r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_closedCaption( \r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isOnline( \r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_error( \r\n            /* [retval][out] */ IWMPError **ppError) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_status( \r\n            /* [retval][out] */ BSTR *pbstrStatus) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPCoreVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPCore * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPCore * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPCore * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPCore * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPCore * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPCore * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPCore * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPCore * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPCore * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPCore * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPCore * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPCore * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPCore * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        END_INTERFACE\r\n    } IWMPCoreVtbl;\r\n\r\n    interface IWMPCore\r\n    {\r\n        CONST_VTBL struct IWMPCoreVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPCore_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPCore_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPCore_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPCore_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPCore_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPCore_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPCore_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPCore_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPCore_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPCore_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPCore_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPCore_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPCore_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPCore_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPCore_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPCore_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPCore_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPCore_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPCore_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPCore_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPCore_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPCore_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPCore_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPCore_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPCore_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPCore_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPCore_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPCore_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_close_Proxy( \r\n    IWMPCore * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_close_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_URL_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ BSTR *pbstrURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_URL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propput][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_put_URL_Proxy( \r\n    IWMPCore * This,\r\n    /* [in] */ BSTR bstrURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_put_URL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_openState_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ WMPOpenState *pwmpos);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_openState_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_playState_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ WMPPlayState *pwmpps);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_playState_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_controls_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPControls **ppControl);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_controls_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_settings_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPSettings **ppSettings);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_settings_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_currentMedia_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPMedia **ppMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_currentMedia_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propput][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_put_currentMedia_Proxy( \r\n    IWMPCore * This,\r\n    /* [in] */ IWMPMedia *pMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_put_currentMedia_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_mediaCollection_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_mediaCollection_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_playlistCollection_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_playlistCollection_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_versionInfo_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_versionInfo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [id] */ HRESULT STDMETHODCALLTYPE IWMPCore_launchURL_Proxy( \r\n    IWMPCore * This,\r\n    /* [in] */ BSTR bstrURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_launchURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_network_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPNetwork **ppQNI);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_network_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_currentPlaylist_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPPlaylist **ppPL);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_currentPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_put_currentPlaylist_Proxy( \r\n    IWMPCore * This,\r\n    /* [in] */ IWMPPlaylist *pPL);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_put_currentPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_cdromCollection_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_cdromCollection_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_closedCaption_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_closedCaption_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_isOnline_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_isOnline_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_error_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ IWMPError **ppError);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_error_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore_get_status_Proxy( \r\n    IWMPCore * This,\r\n    /* [retval][out] */ BSTR *pbstrStatus);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore_get_status_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPCore_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer_INTERFACE_DEFINED__\r\n#define __IWMPPlayer_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayer */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayer;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"6BF52A4F-394A-11d3-B153-00C04F79FAA6\")\r\n    IWMPPlayer : public IWMPCore\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enabled( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enabled( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_fullScreen( \r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_fullScreen( \r\n            VARIANT_BOOL bFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enableContextMenu( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enableContextMenu( \r\n            VARIANT_BOOL bEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_uiMode( \r\n            /* [in] */ BSTR bstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_uiMode( \r\n            /* [retval][out] */ BSTR *pbstrMode) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayerVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayer * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayer * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlayer * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPPlayer * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enabled )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enabled )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_fullScreen )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_fullScreen )( \r\n            IWMPPlayer * This,\r\n            VARIANT_BOOL bFullScreen);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableContextMenu )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableContextMenu )( \r\n            IWMPPlayer * This,\r\n            VARIANT_BOOL bEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_uiMode )( \r\n            IWMPPlayer * This,\r\n            /* [in] */ BSTR bstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_uiMode )( \r\n            IWMPPlayer * This,\r\n            /* [retval][out] */ BSTR *pbstrMode);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayerVtbl;\r\n\r\n    interface IWMPPlayer\r\n    {\r\n        CONST_VTBL struct IWMPPlayerVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayer_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayer_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayer_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayer_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlayer_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlayer_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlayer_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlayer_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPPlayer_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPPlayer_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPPlayer_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPPlayer_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPPlayer_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPPlayer_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPPlayer_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPPlayer_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPPlayer_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPPlayer_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPPlayer_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPPlayer_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPPlayer_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPPlayer_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPPlayer_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPPlayer_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPPlayer_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPPlayer_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPPlayer_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPPlayer_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPPlayer_get_enabled(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_enabled(This,pbEnabled)\r\n\r\n#define IWMPPlayer_put_enabled(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_enabled(This,bEnabled)\r\n\r\n#define IWMPPlayer_get_fullScreen(This,pbFullScreen)\t\\\r\n    (This)->lpVtbl -> get_fullScreen(This,pbFullScreen)\r\n\r\n#define IWMPPlayer_put_fullScreen(This,bFullScreen)\t\\\r\n    (This)->lpVtbl -> put_fullScreen(This,bFullScreen)\r\n\r\n#define IWMPPlayer_get_enableContextMenu(This,pbEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> get_enableContextMenu(This,pbEnableContextMenu)\r\n\r\n#define IWMPPlayer_put_enableContextMenu(This,bEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> put_enableContextMenu(This,bEnableContextMenu)\r\n\r\n#define IWMPPlayer_put_uiMode(This,bstrMode)\t\\\r\n    (This)->lpVtbl -> put_uiMode(This,bstrMode)\r\n\r\n#define IWMPPlayer_get_uiMode(This,pbstrMode)\t\\\r\n    (This)->lpVtbl -> get_uiMode(This,pbstrMode)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_get_enabled_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_get_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_put_enabled_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_put_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_get_fullScreen_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_get_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_put_fullScreen_Proxy( \r\n    IWMPPlayer * This,\r\n    VARIANT_BOOL bFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_put_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_get_enableContextMenu_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_get_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_put_enableContextMenu_Proxy( \r\n    IWMPPlayer * This,\r\n    VARIANT_BOOL bEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_put_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_put_uiMode_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [in] */ BSTR bstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_put_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer_get_uiMode_Proxy( \r\n    IWMPPlayer * This,\r\n    /* [retval][out] */ BSTR *pbstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer_get_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayer_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer2_INTERFACE_DEFINED__\r\n#define __IWMPPlayer2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayer2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayer2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"0E6B01D1-D407-4c85-BF5F-1C01F6150280\")\r\n    IWMPPlayer2 : public IWMPCore\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enabled( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enabled( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_fullScreen( \r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_fullScreen( \r\n            VARIANT_BOOL bFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enableContextMenu( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enableContextMenu( \r\n            VARIANT_BOOL bEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_uiMode( \r\n            /* [in] */ BSTR bstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_uiMode( \r\n            /* [retval][out] */ BSTR *pbstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_stretchToFit( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_stretchToFit( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_windowlessVideo( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_windowlessVideo( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayer2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayer2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayer2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlayer2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPPlayer2 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enabled )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enabled )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_fullScreen )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_fullScreen )( \r\n            IWMPPlayer2 * This,\r\n            VARIANT_BOOL bFullScreen);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableContextMenu )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableContextMenu )( \r\n            IWMPPlayer2 * This,\r\n            VARIANT_BOOL bEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_uiMode )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ BSTR bstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_uiMode )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ BSTR *pbstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_stretchToFit )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_stretchToFit )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_windowlessVideo )( \r\n            IWMPPlayer2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_windowlessVideo )( \r\n            IWMPPlayer2 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayer2Vtbl;\r\n\r\n    interface IWMPPlayer2\r\n    {\r\n        CONST_VTBL struct IWMPPlayer2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayer2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayer2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayer2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayer2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlayer2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlayer2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlayer2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlayer2_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPPlayer2_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPPlayer2_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPPlayer2_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPPlayer2_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPPlayer2_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPPlayer2_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPPlayer2_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPPlayer2_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPPlayer2_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPPlayer2_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPPlayer2_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPPlayer2_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPPlayer2_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPPlayer2_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPPlayer2_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPPlayer2_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPPlayer2_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPPlayer2_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPPlayer2_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPPlayer2_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPPlayer2_get_enabled(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_enabled(This,pbEnabled)\r\n\r\n#define IWMPPlayer2_put_enabled(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_enabled(This,bEnabled)\r\n\r\n#define IWMPPlayer2_get_fullScreen(This,pbFullScreen)\t\\\r\n    (This)->lpVtbl -> get_fullScreen(This,pbFullScreen)\r\n\r\n#define IWMPPlayer2_put_fullScreen(This,bFullScreen)\t\\\r\n    (This)->lpVtbl -> put_fullScreen(This,bFullScreen)\r\n\r\n#define IWMPPlayer2_get_enableContextMenu(This,pbEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> get_enableContextMenu(This,pbEnableContextMenu)\r\n\r\n#define IWMPPlayer2_put_enableContextMenu(This,bEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> put_enableContextMenu(This,bEnableContextMenu)\r\n\r\n#define IWMPPlayer2_put_uiMode(This,bstrMode)\t\\\r\n    (This)->lpVtbl -> put_uiMode(This,bstrMode)\r\n\r\n#define IWMPPlayer2_get_uiMode(This,pbstrMode)\t\\\r\n    (This)->lpVtbl -> get_uiMode(This,pbstrMode)\r\n\r\n#define IWMPPlayer2_get_stretchToFit(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_stretchToFit(This,pbEnabled)\r\n\r\n#define IWMPPlayer2_put_stretchToFit(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_stretchToFit(This,bEnabled)\r\n\r\n#define IWMPPlayer2_get_windowlessVideo(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_windowlessVideo(This,pbEnabled)\r\n\r\n#define IWMPPlayer2_put_windowlessVideo(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_windowlessVideo(This,bEnabled)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_enabled_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_enabled_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_fullScreen_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_fullScreen_Proxy( \r\n    IWMPPlayer2 * This,\r\n    VARIANT_BOOL bFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_enableContextMenu_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_enableContextMenu_Proxy( \r\n    IWMPPlayer2 * This,\r\n    VARIANT_BOOL bEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_uiMode_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [in] */ BSTR bstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_uiMode_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ BSTR *pbstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_stretchToFit_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_stretchToFit_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_get_windowlessVideo_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_get_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer2_put_windowlessVideo_Proxy( \r\n    IWMPPlayer2 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer2_put_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayer2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia2_INTERFACE_DEFINED__\r\n#define __IWMPMedia2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMedia2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMedia2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"AB7C88BB-143E-4ea4-ACC3-E4350B2106C3\")\r\n    IWMPMedia2 : public IWMPMedia\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_error( \r\n            /* [retval][out] */ IWMPErrorItem **ppIWMPErrorItem) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMedia2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMedia2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMedia2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMedia2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isIdentical )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_sourceURL )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ BSTR *pbstrSourceURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_name )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_name )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ BSTR bstrName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceWidth )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ long *pWidth);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceHeight )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ long *pHeight);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_markerCount )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ long *pMarkerCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerTime )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ double *pMarkerTime);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerName )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ BSTR *pbstrMarkerName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_duration )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ double *pDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_durationString )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ BSTR *pbstrDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_attributeCount )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAttributeName )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrItemName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfo )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setItemInfo )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [in] */ BSTR bstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfoByAtom )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ long lAtom,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isMemberOf )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ IWMPPlaylist *pPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsMemberOf);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isReadOnlyItem )( \r\n            IWMPMedia2 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsReadOnly);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPMedia2 * This,\r\n            /* [retval][out] */ IWMPErrorItem **ppIWMPErrorItem);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMedia2Vtbl;\r\n\r\n    interface IWMPMedia2\r\n    {\r\n        CONST_VTBL struct IWMPMedia2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMedia2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMedia2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMedia2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMedia2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMedia2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMedia2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMedia2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMedia2_get_isIdentical(This,pIWMPMedia,pvbool)\t\\\r\n    (This)->lpVtbl -> get_isIdentical(This,pIWMPMedia,pvbool)\r\n\r\n#define IWMPMedia2_get_sourceURL(This,pbstrSourceURL)\t\\\r\n    (This)->lpVtbl -> get_sourceURL(This,pbstrSourceURL)\r\n\r\n#define IWMPMedia2_get_name(This,pbstrName)\t\\\r\n    (This)->lpVtbl -> get_name(This,pbstrName)\r\n\r\n#define IWMPMedia2_put_name(This,bstrName)\t\\\r\n    (This)->lpVtbl -> put_name(This,bstrName)\r\n\r\n#define IWMPMedia2_get_imageSourceWidth(This,pWidth)\t\\\r\n    (This)->lpVtbl -> get_imageSourceWidth(This,pWidth)\r\n\r\n#define IWMPMedia2_get_imageSourceHeight(This,pHeight)\t\\\r\n    (This)->lpVtbl -> get_imageSourceHeight(This,pHeight)\r\n\r\n#define IWMPMedia2_get_markerCount(This,pMarkerCount)\t\\\r\n    (This)->lpVtbl -> get_markerCount(This,pMarkerCount)\r\n\r\n#define IWMPMedia2_getMarkerTime(This,MarkerNum,pMarkerTime)\t\\\r\n    (This)->lpVtbl -> getMarkerTime(This,MarkerNum,pMarkerTime)\r\n\r\n#define IWMPMedia2_getMarkerName(This,MarkerNum,pbstrMarkerName)\t\\\r\n    (This)->lpVtbl -> getMarkerName(This,MarkerNum,pbstrMarkerName)\r\n\r\n#define IWMPMedia2_get_duration(This,pDuration)\t\\\r\n    (This)->lpVtbl -> get_duration(This,pDuration)\r\n\r\n#define IWMPMedia2_get_durationString(This,pbstrDuration)\t\\\r\n    (This)->lpVtbl -> get_durationString(This,pbstrDuration)\r\n\r\n#define IWMPMedia2_get_attributeCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_attributeCount(This,plCount)\r\n\r\n#define IWMPMedia2_getAttributeName(This,lIndex,pbstrItemName)\t\\\r\n    (This)->lpVtbl -> getAttributeName(This,lIndex,pbstrItemName)\r\n\r\n#define IWMPMedia2_getItemInfo(This,bstrItemName,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfo(This,bstrItemName,pbstrVal)\r\n\r\n#define IWMPMedia2_setItemInfo(This,bstrItemName,bstrVal)\t\\\r\n    (This)->lpVtbl -> setItemInfo(This,bstrItemName,bstrVal)\r\n\r\n#define IWMPMedia2_getItemInfoByAtom(This,lAtom,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfoByAtom(This,lAtom,pbstrVal)\r\n\r\n#define IWMPMedia2_isMemberOf(This,pPlaylist,pvarfIsMemberOf)\t\\\r\n    (This)->lpVtbl -> isMemberOf(This,pPlaylist,pvarfIsMemberOf)\r\n\r\n#define IWMPMedia2_isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\t\\\r\n    (This)->lpVtbl -> isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\r\n\r\n\r\n#define IWMPMedia2_get_error(This,ppIWMPErrorItem)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppIWMPErrorItem)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMedia2_get_error_Proxy( \r\n    IWMPMedia2 * This,\r\n    /* [retval][out] */ IWMPErrorItem **ppIWMPErrorItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia2_get_error_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMedia2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls2_INTERFACE_DEFINED__\r\n#define __IWMPControls2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPControls2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPControls2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"6F030D25-0890-480f-9775-1F7E40AB5B8E\")\r\n    IWMPControls2 : public IWMPControls\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE step( \r\n            /* [in] */ long lStep) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPControls2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPControls2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPControls2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPControls2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *play )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *stop )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *pause )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastForward )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastReverse )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPosition )( \r\n            IWMPControls2 * This,\r\n            /* [retval][out] */ double *pdCurrentPosition);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPosition )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ double dCurrentPosition);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPositionString )( \r\n            IWMPControls2 * This,\r\n            /* [retval][out] */ BSTR *pbstrCurrentPosition);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *next )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *previous )( \r\n            IWMPControls2 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentItem )( \r\n            IWMPControls2 * This,\r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentItem )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMarker )( \r\n            IWMPControls2 * This,\r\n            /* [retval][out] */ long *plMarker);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMarker )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ long lMarker);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *playItem )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *step )( \r\n            IWMPControls2 * This,\r\n            /* [in] */ long lStep);\r\n        \r\n        END_INTERFACE\r\n    } IWMPControls2Vtbl;\r\n\r\n    interface IWMPControls2\r\n    {\r\n        CONST_VTBL struct IWMPControls2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPControls2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPControls2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPControls2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPControls2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPControls2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPControls2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPControls2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPControls2_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPControls2_play(This)\t\\\r\n    (This)->lpVtbl -> play(This)\r\n\r\n#define IWMPControls2_stop(This)\t\\\r\n    (This)->lpVtbl -> stop(This)\r\n\r\n#define IWMPControls2_pause(This)\t\\\r\n    (This)->lpVtbl -> pause(This)\r\n\r\n#define IWMPControls2_fastForward(This)\t\\\r\n    (This)->lpVtbl -> fastForward(This)\r\n\r\n#define IWMPControls2_fastReverse(This)\t\\\r\n    (This)->lpVtbl -> fastReverse(This)\r\n\r\n#define IWMPControls2_get_currentPosition(This,pdCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPosition(This,pdCurrentPosition)\r\n\r\n#define IWMPControls2_put_currentPosition(This,dCurrentPosition)\t\\\r\n    (This)->lpVtbl -> put_currentPosition(This,dCurrentPosition)\r\n\r\n#define IWMPControls2_get_currentPositionString(This,pbstrCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPositionString(This,pbstrCurrentPosition)\r\n\r\n#define IWMPControls2_next(This)\t\\\r\n    (This)->lpVtbl -> next(This)\r\n\r\n#define IWMPControls2_previous(This)\t\\\r\n    (This)->lpVtbl -> previous(This)\r\n\r\n#define IWMPControls2_get_currentItem(This,ppIWMPMedia)\t\\\r\n    (This)->lpVtbl -> get_currentItem(This,ppIWMPMedia)\r\n\r\n#define IWMPControls2_put_currentItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> put_currentItem(This,pIWMPMedia)\r\n\r\n#define IWMPControls2_get_currentMarker(This,plMarker)\t\\\r\n    (This)->lpVtbl -> get_currentMarker(This,plMarker)\r\n\r\n#define IWMPControls2_put_currentMarker(This,lMarker)\t\\\r\n    (This)->lpVtbl -> put_currentMarker(This,lMarker)\r\n\r\n#define IWMPControls2_playItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> playItem(This,pIWMPMedia)\r\n\r\n\r\n#define IWMPControls2_step(This,lStep)\t\\\r\n    (This)->lpVtbl -> step(This,lStep)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls2_step_Proxy( \r\n    IWMPControls2 * This,\r\n    /* [in] */ long lStep);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls2_step_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPControls2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPDVD_INTERFACE_DEFINED__\r\n#define __IWMPDVD_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPDVD */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPDVD;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"8DA61686-4668-4a5c-AE5D-803193293DBE\")\r\n    IWMPDVD : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isAvailable( \r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_domain( \r\n            /* [retval][out] */ BSTR *strDomain) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE topMenu( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE titleMenu( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE back( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE resume( void) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPDVDVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPDVD * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPDVD * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPDVD * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPDVD * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPDVD * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPDVD * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPDVD * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPDVD * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_domain )( \r\n            IWMPDVD * This,\r\n            /* [retval][out] */ BSTR *strDomain);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *topMenu )( \r\n            IWMPDVD * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *titleMenu )( \r\n            IWMPDVD * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *back )( \r\n            IWMPDVD * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *resume )( \r\n            IWMPDVD * This);\r\n        \r\n        END_INTERFACE\r\n    } IWMPDVDVtbl;\r\n\r\n    interface IWMPDVD\r\n    {\r\n        CONST_VTBL struct IWMPDVDVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPDVD_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPDVD_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPDVD_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPDVD_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPDVD_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPDVD_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPDVD_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPDVD_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPDVD_get_domain(This,strDomain)\t\\\r\n    (This)->lpVtbl -> get_domain(This,strDomain)\r\n\r\n#define IWMPDVD_topMenu(This)\t\\\r\n    (This)->lpVtbl -> topMenu(This)\r\n\r\n#define IWMPDVD_titleMenu(This)\t\\\r\n    (This)->lpVtbl -> titleMenu(This)\r\n\r\n#define IWMPDVD_back(This)\t\\\r\n    (This)->lpVtbl -> back(This)\r\n\r\n#define IWMPDVD_resume(This)\t\\\r\n    (This)->lpVtbl -> resume(This)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_get_isAvailable_Proxy( \r\n    IWMPDVD * This,\r\n    /* [in] */ BSTR bstrItem,\r\n    /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_get_isAvailable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_get_domain_Proxy( \r\n    IWMPDVD * This,\r\n    /* [retval][out] */ BSTR *strDomain);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_get_domain_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_topMenu_Proxy( \r\n    IWMPDVD * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_topMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_titleMenu_Proxy( \r\n    IWMPDVD * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_titleMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_back_Proxy( \r\n    IWMPDVD * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_back_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPDVD_resume_Proxy( \r\n    IWMPDVD * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPDVD_resume_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPDVD_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore2_INTERFACE_DEFINED__\r\n#define __IWMPCore2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPCore2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPCore2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"BC17E5B7-7561-4c18-BB90-17D485775659\")\r\n    IWMPCore2 : public IWMPCore\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_dvd( \r\n            /* [retval][out] */ IWMPDVD **ppDVD) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPCore2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPCore2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPCore2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPCore2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPCore2 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPCore2 * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_dvd )( \r\n            IWMPCore2 * This,\r\n            /* [retval][out] */ IWMPDVD **ppDVD);\r\n        \r\n        END_INTERFACE\r\n    } IWMPCore2Vtbl;\r\n\r\n    interface IWMPCore2\r\n    {\r\n        CONST_VTBL struct IWMPCore2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPCore2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPCore2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPCore2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPCore2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPCore2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPCore2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPCore2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPCore2_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPCore2_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPCore2_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPCore2_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPCore2_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPCore2_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPCore2_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPCore2_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPCore2_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPCore2_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPCore2_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPCore2_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPCore2_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPCore2_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPCore2_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPCore2_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPCore2_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPCore2_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPCore2_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPCore2_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPCore2_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPCore2_get_dvd(This,ppDVD)\t\\\r\n    (This)->lpVtbl -> get_dvd(This,ppDVD)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPCore2_get_dvd_Proxy( \r\n    IWMPCore2 * This,\r\n    /* [retval][out] */ IWMPDVD **ppDVD);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore2_get_dvd_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPCore2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer3_INTERFACE_DEFINED__\r\n#define __IWMPPlayer3_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayer3 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayer3;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"54062B68-052A-4c25-A39F-8B63346511D4\")\r\n    IWMPPlayer3 : public IWMPCore2\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enabled( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enabled( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_fullScreen( \r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_fullScreen( \r\n            VARIANT_BOOL bFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enableContextMenu( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enableContextMenu( \r\n            VARIANT_BOOL bEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_uiMode( \r\n            /* [in] */ BSTR bstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_uiMode( \r\n            /* [retval][out] */ BSTR *pbstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_stretchToFit( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_stretchToFit( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_windowlessVideo( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_windowlessVideo( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayer3Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayer3 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayer3 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlayer3 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPPlayer3 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_dvd )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ IWMPDVD **ppDVD);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enabled )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enabled )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_fullScreen )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_fullScreen )( \r\n            IWMPPlayer3 * This,\r\n            VARIANT_BOOL bFullScreen);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableContextMenu )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableContextMenu )( \r\n            IWMPPlayer3 * This,\r\n            VARIANT_BOOL bEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_uiMode )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ BSTR bstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_uiMode )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ BSTR *pbstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_stretchToFit )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_stretchToFit )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_windowlessVideo )( \r\n            IWMPPlayer3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_windowlessVideo )( \r\n            IWMPPlayer3 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayer3Vtbl;\r\n\r\n    interface IWMPPlayer3\r\n    {\r\n        CONST_VTBL struct IWMPPlayer3Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayer3_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayer3_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayer3_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayer3_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlayer3_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlayer3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlayer3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlayer3_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPPlayer3_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPPlayer3_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPPlayer3_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPPlayer3_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPPlayer3_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPPlayer3_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPPlayer3_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPPlayer3_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPPlayer3_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPPlayer3_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPPlayer3_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPPlayer3_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPPlayer3_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPPlayer3_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPPlayer3_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPPlayer3_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPPlayer3_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPPlayer3_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPPlayer3_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPPlayer3_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPPlayer3_get_dvd(This,ppDVD)\t\\\r\n    (This)->lpVtbl -> get_dvd(This,ppDVD)\r\n\r\n\r\n#define IWMPPlayer3_get_enabled(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_enabled(This,pbEnabled)\r\n\r\n#define IWMPPlayer3_put_enabled(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_enabled(This,bEnabled)\r\n\r\n#define IWMPPlayer3_get_fullScreen(This,pbFullScreen)\t\\\r\n    (This)->lpVtbl -> get_fullScreen(This,pbFullScreen)\r\n\r\n#define IWMPPlayer3_put_fullScreen(This,bFullScreen)\t\\\r\n    (This)->lpVtbl -> put_fullScreen(This,bFullScreen)\r\n\r\n#define IWMPPlayer3_get_enableContextMenu(This,pbEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> get_enableContextMenu(This,pbEnableContextMenu)\r\n\r\n#define IWMPPlayer3_put_enableContextMenu(This,bEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> put_enableContextMenu(This,bEnableContextMenu)\r\n\r\n#define IWMPPlayer3_put_uiMode(This,bstrMode)\t\\\r\n    (This)->lpVtbl -> put_uiMode(This,bstrMode)\r\n\r\n#define IWMPPlayer3_get_uiMode(This,pbstrMode)\t\\\r\n    (This)->lpVtbl -> get_uiMode(This,pbstrMode)\r\n\r\n#define IWMPPlayer3_get_stretchToFit(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_stretchToFit(This,pbEnabled)\r\n\r\n#define IWMPPlayer3_put_stretchToFit(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_stretchToFit(This,bEnabled)\r\n\r\n#define IWMPPlayer3_get_windowlessVideo(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_windowlessVideo(This,pbEnabled)\r\n\r\n#define IWMPPlayer3_put_windowlessVideo(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_windowlessVideo(This,bEnabled)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_enabled_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_enabled_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_fullScreen_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_fullScreen_Proxy( \r\n    IWMPPlayer3 * This,\r\n    VARIANT_BOOL bFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_enableContextMenu_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_enableContextMenu_Proxy( \r\n    IWMPPlayer3 * This,\r\n    VARIANT_BOOL bEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_uiMode_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [in] */ BSTR bstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_uiMode_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ BSTR *pbstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_stretchToFit_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_stretchToFit_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_get_windowlessVideo_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_get_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer3_put_windowlessVideo_Proxy( \r\n    IWMPPlayer3 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer3_put_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayer3_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPErrorItem2_INTERFACE_DEFINED__\r\n#define __IWMPErrorItem2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPErrorItem2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPErrorItem2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"F75CCEC0-C67C-475c-931E-8719870BEE7D\")\r\n    IWMPErrorItem2 : public IWMPErrorItem\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_condition( \r\n            /* [retval][out] */ long *plCondition) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPErrorItem2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPErrorItem2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPErrorItem2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPErrorItem2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPErrorItem2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPErrorItem2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPErrorItem2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPErrorItem2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorCode )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ long *phr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorDescription )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ BSTR *pbstrDescription);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_errorContext )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ VARIANT *pvarContext);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_remedy )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ long *plRemedy);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_customUrl )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ BSTR *pbstrCustomUrl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_condition )( \r\n            IWMPErrorItem2 * This,\r\n            /* [retval][out] */ long *plCondition);\r\n        \r\n        END_INTERFACE\r\n    } IWMPErrorItem2Vtbl;\r\n\r\n    interface IWMPErrorItem2\r\n    {\r\n        CONST_VTBL struct IWMPErrorItem2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPErrorItem2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPErrorItem2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPErrorItem2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPErrorItem2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPErrorItem2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPErrorItem2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPErrorItem2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPErrorItem2_get_errorCode(This,phr)\t\\\r\n    (This)->lpVtbl -> get_errorCode(This,phr)\r\n\r\n#define IWMPErrorItem2_get_errorDescription(This,pbstrDescription)\t\\\r\n    (This)->lpVtbl -> get_errorDescription(This,pbstrDescription)\r\n\r\n#define IWMPErrorItem2_get_errorContext(This,pvarContext)\t\\\r\n    (This)->lpVtbl -> get_errorContext(This,pvarContext)\r\n\r\n#define IWMPErrorItem2_get_remedy(This,plRemedy)\t\\\r\n    (This)->lpVtbl -> get_remedy(This,plRemedy)\r\n\r\n#define IWMPErrorItem2_get_customUrl(This,pbstrCustomUrl)\t\\\r\n    (This)->lpVtbl -> get_customUrl(This,pbstrCustomUrl)\r\n\r\n\r\n#define IWMPErrorItem2_get_condition(This,plCondition)\t\\\r\n    (This)->lpVtbl -> get_condition(This,plCondition)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPErrorItem2_get_condition_Proxy( \r\n    IWMPErrorItem2 * This,\r\n    /* [retval][out] */ long *plCondition);\r\n\r\n\r\nvoid __RPC_STUB IWMPErrorItem2_get_condition_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPErrorItem2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPRemoteMediaServices_INTERFACE_DEFINED__\r\n#define __IWMPRemoteMediaServices_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPRemoteMediaServices */\r\n/* [unique][helpstring][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPRemoteMediaServices;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"CBB92747-741F-44fe-AB5B-F1A48F3B2A59\")\r\n    IWMPRemoteMediaServices : public IUnknown\r\n    {\r\n    public:\r\n        virtual HRESULT STDMETHODCALLTYPE GetServiceType( \r\n            /* [out] */ BSTR *pbstrType) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE GetApplicationName( \r\n            /* [out] */ BSTR *pbstrName) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE GetScriptableObject( \r\n            /* [out] */ BSTR *pbstrName,\r\n            /* [out] */ IDispatch **ppDispatch) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE GetCustomUIMode( \r\n            /* [out] */ BSTR *pbstrFile) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPRemoteMediaServicesVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPRemoteMediaServices * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPRemoteMediaServices * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPRemoteMediaServices * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetServiceType )( \r\n            IWMPRemoteMediaServices * This,\r\n            /* [out] */ BSTR *pbstrType);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetApplicationName )( \r\n            IWMPRemoteMediaServices * This,\r\n            /* [out] */ BSTR *pbstrName);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetScriptableObject )( \r\n            IWMPRemoteMediaServices * This,\r\n            /* [out] */ BSTR *pbstrName,\r\n            /* [out] */ IDispatch **ppDispatch);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetCustomUIMode )( \r\n            IWMPRemoteMediaServices * This,\r\n            /* [out] */ BSTR *pbstrFile);\r\n        \r\n        END_INTERFACE\r\n    } IWMPRemoteMediaServicesVtbl;\r\n\r\n    interface IWMPRemoteMediaServices\r\n    {\r\n        CONST_VTBL struct IWMPRemoteMediaServicesVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPRemoteMediaServices_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPRemoteMediaServices_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPRemoteMediaServices_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPRemoteMediaServices_GetServiceType(This,pbstrType)\t\\\r\n    (This)->lpVtbl -> GetServiceType(This,pbstrType)\r\n\r\n#define IWMPRemoteMediaServices_GetApplicationName(This,pbstrName)\t\\\r\n    (This)->lpVtbl -> GetApplicationName(This,pbstrName)\r\n\r\n#define IWMPRemoteMediaServices_GetScriptableObject(This,pbstrName,ppDispatch)\t\\\r\n    (This)->lpVtbl -> GetScriptableObject(This,pbstrName,ppDispatch)\r\n\r\n#define IWMPRemoteMediaServices_GetCustomUIMode(This,pbstrFile)\t\\\r\n    (This)->lpVtbl -> GetCustomUIMode(This,pbstrFile)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPRemoteMediaServices_GetServiceType_Proxy( \r\n    IWMPRemoteMediaServices * This,\r\n    /* [out] */ BSTR *pbstrType);\r\n\r\n\r\nvoid __RPC_STUB IWMPRemoteMediaServices_GetServiceType_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPRemoteMediaServices_GetApplicationName_Proxy( \r\n    IWMPRemoteMediaServices * This,\r\n    /* [out] */ BSTR *pbstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPRemoteMediaServices_GetApplicationName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPRemoteMediaServices_GetScriptableObject_Proxy( \r\n    IWMPRemoteMediaServices * This,\r\n    /* [out] */ BSTR *pbstrName,\r\n    /* [out] */ IDispatch **ppDispatch);\r\n\r\n\r\nvoid __RPC_STUB IWMPRemoteMediaServices_GetScriptableObject_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPRemoteMediaServices_GetCustomUIMode_Proxy( \r\n    IWMPRemoteMediaServices * This,\r\n    /* [out] */ BSTR *pbstrFile);\r\n\r\n\r\nvoid __RPC_STUB IWMPRemoteMediaServices_GetCustomUIMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPRemoteMediaServices_INTERFACE_DEFINED__ */\r\n\r\n\r\n/* interface __MIDL_itf_wmp_0280 */\r\n/* [local] */ \r\n\r\nEXTERN_GUID( CLSID_WMPSkinManager, 0xB2A7FD52,0x301F,0x4348, 0xB9, 0x3A, 0x63, 0x8C, 0x6D, 0xE4, 0x92, 0x29 );\r\n\r\n\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0280_v0_0_c_ifspec;\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0280_v0_0_s_ifspec;\r\n\r\n#ifndef __IWMPSkinManager_INTERFACE_DEFINED__\r\n#define __IWMPSkinManager_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPSkinManager */\r\n/* [unique][helpstring][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPSkinManager;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"076F2FA6-ED30-448B-8CC5-3F3EF3529C7A\")\r\n    IWMPSkinManager : public IUnknown\r\n    {\r\n    public:\r\n        virtual HRESULT STDMETHODCALLTYPE SetVisualStyle( \r\n            /* [in] */ BSTR bstrPath) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPSkinManagerVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPSkinManager * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPSkinManager * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPSkinManager * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *SetVisualStyle )( \r\n            IWMPSkinManager * This,\r\n            /* [in] */ BSTR bstrPath);\r\n        \r\n        END_INTERFACE\r\n    } IWMPSkinManagerVtbl;\r\n\r\n    interface IWMPSkinManager\r\n    {\r\n        CONST_VTBL struct IWMPSkinManagerVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPSkinManager_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPSkinManager_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPSkinManager_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPSkinManager_SetVisualStyle(This,bstrPath)\t\\\r\n    (This)->lpVtbl -> SetVisualStyle(This,bstrPath)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPSkinManager_SetVisualStyle_Proxy( \r\n    IWMPSkinManager * This,\r\n    /* [in] */ BSTR bstrPath);\r\n\r\n\r\nvoid __RPC_STUB IWMPSkinManager_SetVisualStyle_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPSkinManager_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMetadataPicture_INTERFACE_DEFINED__\r\n#define __IWMPMetadataPicture_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMetadataPicture */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMetadataPicture;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"5C29BBE0-F87D-4c45-AA28-A70F0230FFA9\")\r\n    IWMPMetadataPicture : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_mimeType( \r\n            /* [retval][out] */ BSTR *pbstrMimeType) = 0;\r\n        \r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_pictureType( \r\n            /* [retval][out] */ BSTR *pbstrPictureType) = 0;\r\n        \r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_description( \r\n            /* [retval][out] */ BSTR *pbstrDescription) = 0;\r\n        \r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_URL( \r\n            /* [retval][out] */ BSTR *pbstrURL) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMetadataPictureVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMetadataPicture * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMetadataPicture * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMetadataPicture * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMetadataPicture * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMetadataPicture * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMetadataPicture * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMetadataPicture * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mimeType )( \r\n            IWMPMetadataPicture * This,\r\n            /* [retval][out] */ BSTR *pbstrMimeType);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_pictureType )( \r\n            IWMPMetadataPicture * This,\r\n            /* [retval][out] */ BSTR *pbstrPictureType);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_description )( \r\n            IWMPMetadataPicture * This,\r\n            /* [retval][out] */ BSTR *pbstrDescription);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPMetadataPicture * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMetadataPictureVtbl;\r\n\r\n    interface IWMPMetadataPicture\r\n    {\r\n        CONST_VTBL struct IWMPMetadataPictureVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMetadataPicture_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMetadataPicture_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMetadataPicture_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMetadataPicture_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMetadataPicture_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMetadataPicture_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMetadataPicture_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMetadataPicture_get_mimeType(This,pbstrMimeType)\t\\\r\n    (This)->lpVtbl -> get_mimeType(This,pbstrMimeType)\r\n\r\n#define IWMPMetadataPicture_get_pictureType(This,pbstrPictureType)\t\\\r\n    (This)->lpVtbl -> get_pictureType(This,pbstrPictureType)\r\n\r\n#define IWMPMetadataPicture_get_description(This,pbstrDescription)\t\\\r\n    (This)->lpVtbl -> get_description(This,pbstrDescription)\r\n\r\n#define IWMPMetadataPicture_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataPicture_get_mimeType_Proxy( \r\n    IWMPMetadataPicture * This,\r\n    /* [retval][out] */ BSTR *pbstrMimeType);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataPicture_get_mimeType_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataPicture_get_pictureType_Proxy( \r\n    IWMPMetadataPicture * This,\r\n    /* [retval][out] */ BSTR *pbstrPictureType);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataPicture_get_pictureType_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataPicture_get_description_Proxy( \r\n    IWMPMetadataPicture * This,\r\n    /* [retval][out] */ BSTR *pbstrDescription);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataPicture_get_description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataPicture_get_URL_Proxy( \r\n    IWMPMetadataPicture * This,\r\n    /* [retval][out] */ BSTR *pbstrURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataPicture_get_URL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMetadataPicture_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMetadataText_INTERFACE_DEFINED__\r\n#define __IWMPMetadataText_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMetadataText */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMetadataText;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"769A72DB-13D2-45e2-9C48-53CA9D5B7450\")\r\n    IWMPMetadataText : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_description( \r\n            /* [retval][out] */ BSTR *pbstrDescription) = 0;\r\n        \r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_text( \r\n            /* [retval][out] */ BSTR *pbstrText) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMetadataTextVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMetadataText * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMetadataText * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMetadataText * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMetadataText * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMetadataText * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMetadataText * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMetadataText * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_description )( \r\n            IWMPMetadataText * This,\r\n            /* [retval][out] */ BSTR *pbstrDescription);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_text )( \r\n            IWMPMetadataText * This,\r\n            /* [retval][out] */ BSTR *pbstrText);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMetadataTextVtbl;\r\n\r\n    interface IWMPMetadataText\r\n    {\r\n        CONST_VTBL struct IWMPMetadataTextVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMetadataText_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMetadataText_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMetadataText_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMetadataText_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMetadataText_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMetadataText_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMetadataText_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMetadataText_get_description(This,pbstrDescription)\t\\\r\n    (This)->lpVtbl -> get_description(This,pbstrDescription)\r\n\r\n#define IWMPMetadataText_get_text(This,pbstrText)\t\\\r\n    (This)->lpVtbl -> get_text(This,pbstrText)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataText_get_description_Proxy( \r\n    IWMPMetadataText * This,\r\n    /* [retval][out] */ BSTR *pbstrDescription);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataText_get_description_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPMetadataText_get_text_Proxy( \r\n    IWMPMetadataText * This,\r\n    /* [retval][out] */ BSTR *pbstrText);\r\n\r\n\r\nvoid __RPC_STUB IWMPMetadataText_get_text_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMetadataText_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPMedia3_INTERFACE_DEFINED__\r\n#define __IWMPMedia3_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPMedia3 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPMedia3;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"F118EFC7-F03A-4fb4-99C9-1C02A5C1065B\")\r\n    IWMPMedia3 : public IWMPMedia2\r\n    {\r\n    public:\r\n        virtual /* [id] */ HRESULT STDMETHODCALLTYPE getAttributeCountByType( \r\n            /* [in] */ BSTR bstrType,\r\n            /* [in] */ BSTR bstrLanguage,\r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [id] */ HRESULT STDMETHODCALLTYPE getItemInfoByType( \r\n            /* [in] */ BSTR bstrType,\r\n            /* [in] */ BSTR bstrLanguage,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ VARIANT *pvarValue) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPMedia3Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPMedia3 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPMedia3 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPMedia3 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isIdentical )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbool);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_sourceURL )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ BSTR *pbstrSourceURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_name )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_name )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceWidth )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ long *pWidth);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_imageSourceHeight )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ long *pHeight);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_markerCount )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ long *pMarkerCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerTime )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ double *pMarkerTime);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMarkerName )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ long MarkerNum,\r\n            /* [retval][out] */ BSTR *pbstrMarkerName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_duration )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ double *pDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_durationString )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ BSTR *pbstrDuration);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_attributeCount )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAttributeName )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrItemName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfo )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setItemInfo )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [in] */ BSTR bstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfoByAtom )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ long lAtom,\r\n            /* [retval][out] */ BSTR *pbstrVal);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isMemberOf )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ IWMPPlaylist *pPlaylist,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsMemberOf);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *isReadOnlyItem )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrItemName,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsReadOnly);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPMedia3 * This,\r\n            /* [retval][out] */ IWMPErrorItem **ppIWMPErrorItem);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *getAttributeCountByType )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrType,\r\n            /* [in] */ BSTR bstrLanguage,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *getItemInfoByType )( \r\n            IWMPMedia3 * This,\r\n            /* [in] */ BSTR bstrType,\r\n            /* [in] */ BSTR bstrLanguage,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ VARIANT *pvarValue);\r\n        \r\n        END_INTERFACE\r\n    } IWMPMedia3Vtbl;\r\n\r\n    interface IWMPMedia3\r\n    {\r\n        CONST_VTBL struct IWMPMedia3Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPMedia3_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPMedia3_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPMedia3_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPMedia3_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPMedia3_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPMedia3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPMedia3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPMedia3_get_isIdentical(This,pIWMPMedia,pvbool)\t\\\r\n    (This)->lpVtbl -> get_isIdentical(This,pIWMPMedia,pvbool)\r\n\r\n#define IWMPMedia3_get_sourceURL(This,pbstrSourceURL)\t\\\r\n    (This)->lpVtbl -> get_sourceURL(This,pbstrSourceURL)\r\n\r\n#define IWMPMedia3_get_name(This,pbstrName)\t\\\r\n    (This)->lpVtbl -> get_name(This,pbstrName)\r\n\r\n#define IWMPMedia3_put_name(This,bstrName)\t\\\r\n    (This)->lpVtbl -> put_name(This,bstrName)\r\n\r\n#define IWMPMedia3_get_imageSourceWidth(This,pWidth)\t\\\r\n    (This)->lpVtbl -> get_imageSourceWidth(This,pWidth)\r\n\r\n#define IWMPMedia3_get_imageSourceHeight(This,pHeight)\t\\\r\n    (This)->lpVtbl -> get_imageSourceHeight(This,pHeight)\r\n\r\n#define IWMPMedia3_get_markerCount(This,pMarkerCount)\t\\\r\n    (This)->lpVtbl -> get_markerCount(This,pMarkerCount)\r\n\r\n#define IWMPMedia3_getMarkerTime(This,MarkerNum,pMarkerTime)\t\\\r\n    (This)->lpVtbl -> getMarkerTime(This,MarkerNum,pMarkerTime)\r\n\r\n#define IWMPMedia3_getMarkerName(This,MarkerNum,pbstrMarkerName)\t\\\r\n    (This)->lpVtbl -> getMarkerName(This,MarkerNum,pbstrMarkerName)\r\n\r\n#define IWMPMedia3_get_duration(This,pDuration)\t\\\r\n    (This)->lpVtbl -> get_duration(This,pDuration)\r\n\r\n#define IWMPMedia3_get_durationString(This,pbstrDuration)\t\\\r\n    (This)->lpVtbl -> get_durationString(This,pbstrDuration)\r\n\r\n#define IWMPMedia3_get_attributeCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_attributeCount(This,plCount)\r\n\r\n#define IWMPMedia3_getAttributeName(This,lIndex,pbstrItemName)\t\\\r\n    (This)->lpVtbl -> getAttributeName(This,lIndex,pbstrItemName)\r\n\r\n#define IWMPMedia3_getItemInfo(This,bstrItemName,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfo(This,bstrItemName,pbstrVal)\r\n\r\n#define IWMPMedia3_setItemInfo(This,bstrItemName,bstrVal)\t\\\r\n    (This)->lpVtbl -> setItemInfo(This,bstrItemName,bstrVal)\r\n\r\n#define IWMPMedia3_getItemInfoByAtom(This,lAtom,pbstrVal)\t\\\r\n    (This)->lpVtbl -> getItemInfoByAtom(This,lAtom,pbstrVal)\r\n\r\n#define IWMPMedia3_isMemberOf(This,pPlaylist,pvarfIsMemberOf)\t\\\r\n    (This)->lpVtbl -> isMemberOf(This,pPlaylist,pvarfIsMemberOf)\r\n\r\n#define IWMPMedia3_isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\t\\\r\n    (This)->lpVtbl -> isReadOnlyItem(This,bstrItemName,pvarfIsReadOnly)\r\n\r\n\r\n#define IWMPMedia3_get_error(This,ppIWMPErrorItem)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppIWMPErrorItem)\r\n\r\n\r\n#define IWMPMedia3_getAttributeCountByType(This,bstrType,bstrLanguage,plCount)\t\\\r\n    (This)->lpVtbl -> getAttributeCountByType(This,bstrType,bstrLanguage,plCount)\r\n\r\n#define IWMPMedia3_getItemInfoByType(This,bstrType,bstrLanguage,lIndex,pvarValue)\t\\\r\n    (This)->lpVtbl -> getItemInfoByType(This,bstrType,bstrLanguage,lIndex,pvarValue)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [id] */ HRESULT STDMETHODCALLTYPE IWMPMedia3_getAttributeCountByType_Proxy( \r\n    IWMPMedia3 * This,\r\n    /* [in] */ BSTR bstrType,\r\n    /* [in] */ BSTR bstrLanguage,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia3_getAttributeCountByType_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [id] */ HRESULT STDMETHODCALLTYPE IWMPMedia3_getItemInfoByType_Proxy( \r\n    IWMPMedia3 * This,\r\n    /* [in] */ BSTR bstrType,\r\n    /* [in] */ BSTR bstrLanguage,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ VARIANT *pvarValue);\r\n\r\n\r\nvoid __RPC_STUB IWMPMedia3_getItemInfoByType_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPMedia3_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPSettings2_INTERFACE_DEFINED__\r\n#define __IWMPSettings2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPSettings2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPSettings2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"FDA937A4-EECE-4da5-A0B6-39BF89ADE2C2\")\r\n    IWMPSettings2 : public IWMPSettings\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_defaultAudioLanguage( \r\n            /* [retval][out] */ long *plLangID) = 0;\r\n        \r\n        virtual /* [propget][id] */ HRESULT STDMETHODCALLTYPE get_mediaAccessRights( \r\n            /* [retval][out] */ BSTR *pbstrRights) = 0;\r\n        \r\n        virtual /* [id] */ HRESULT STDMETHODCALLTYPE requestMediaAccessRights( \r\n            /* [in] */ BSTR bstrDesiredAccess,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbAccepted) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPSettings2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPSettings2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPSettings2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPSettings2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_autoStart )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfAutoStart);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_autoStart )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ VARIANT_BOOL fAutoStart);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_baseURL )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ BSTR *pbstrBaseURL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_baseURL )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrBaseURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_defaultFrame )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ BSTR *pbstrDefaultFrame);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_defaultFrame )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrDefaultFrame);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_invokeURLs )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfInvokeURLs);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_invokeURLs )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ VARIANT_BOOL fInvokeURLs);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mute )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfMute);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_mute )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ VARIANT_BOOL fMute);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playCount )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_playCount )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ long lCount);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_rate )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ double *pdRate);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_rate )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ double dRate);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_balance )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ long *plBalance);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_balance )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ long lBalance);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_volume )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ long *plVolume);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_volume )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ long lVolume);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getMode )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrMode,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfMode);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *setMode )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrMode,\r\n            /* [in] */ VARIANT_BOOL varfMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableErrorDialogs )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfEnableErrorDialogs);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableErrorDialogs )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ VARIANT_BOOL fEnableErrorDialogs);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_defaultAudioLanguage )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ long *plLangID);\r\n        \r\n        /* [propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaAccessRights )( \r\n            IWMPSettings2 * This,\r\n            /* [retval][out] */ BSTR *pbstrRights);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *requestMediaAccessRights )( \r\n            IWMPSettings2 * This,\r\n            /* [in] */ BSTR bstrDesiredAccess,\r\n            /* [retval][out] */ VARIANT_BOOL *pvbAccepted);\r\n        \r\n        END_INTERFACE\r\n    } IWMPSettings2Vtbl;\r\n\r\n    interface IWMPSettings2\r\n    {\r\n        CONST_VTBL struct IWMPSettings2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPSettings2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPSettings2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPSettings2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPSettings2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPSettings2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPSettings2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPSettings2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPSettings2_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPSettings2_get_autoStart(This,pfAutoStart)\t\\\r\n    (This)->lpVtbl -> get_autoStart(This,pfAutoStart)\r\n\r\n#define IWMPSettings2_put_autoStart(This,fAutoStart)\t\\\r\n    (This)->lpVtbl -> put_autoStart(This,fAutoStart)\r\n\r\n#define IWMPSettings2_get_baseURL(This,pbstrBaseURL)\t\\\r\n    (This)->lpVtbl -> get_baseURL(This,pbstrBaseURL)\r\n\r\n#define IWMPSettings2_put_baseURL(This,bstrBaseURL)\t\\\r\n    (This)->lpVtbl -> put_baseURL(This,bstrBaseURL)\r\n\r\n#define IWMPSettings2_get_defaultFrame(This,pbstrDefaultFrame)\t\\\r\n    (This)->lpVtbl -> get_defaultFrame(This,pbstrDefaultFrame)\r\n\r\n#define IWMPSettings2_put_defaultFrame(This,bstrDefaultFrame)\t\\\r\n    (This)->lpVtbl -> put_defaultFrame(This,bstrDefaultFrame)\r\n\r\n#define IWMPSettings2_get_invokeURLs(This,pfInvokeURLs)\t\\\r\n    (This)->lpVtbl -> get_invokeURLs(This,pfInvokeURLs)\r\n\r\n#define IWMPSettings2_put_invokeURLs(This,fInvokeURLs)\t\\\r\n    (This)->lpVtbl -> put_invokeURLs(This,fInvokeURLs)\r\n\r\n#define IWMPSettings2_get_mute(This,pfMute)\t\\\r\n    (This)->lpVtbl -> get_mute(This,pfMute)\r\n\r\n#define IWMPSettings2_put_mute(This,fMute)\t\\\r\n    (This)->lpVtbl -> put_mute(This,fMute)\r\n\r\n#define IWMPSettings2_get_playCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_playCount(This,plCount)\r\n\r\n#define IWMPSettings2_put_playCount(This,lCount)\t\\\r\n    (This)->lpVtbl -> put_playCount(This,lCount)\r\n\r\n#define IWMPSettings2_get_rate(This,pdRate)\t\\\r\n    (This)->lpVtbl -> get_rate(This,pdRate)\r\n\r\n#define IWMPSettings2_put_rate(This,dRate)\t\\\r\n    (This)->lpVtbl -> put_rate(This,dRate)\r\n\r\n#define IWMPSettings2_get_balance(This,plBalance)\t\\\r\n    (This)->lpVtbl -> get_balance(This,plBalance)\r\n\r\n#define IWMPSettings2_put_balance(This,lBalance)\t\\\r\n    (This)->lpVtbl -> put_balance(This,lBalance)\r\n\r\n#define IWMPSettings2_get_volume(This,plVolume)\t\\\r\n    (This)->lpVtbl -> get_volume(This,plVolume)\r\n\r\n#define IWMPSettings2_put_volume(This,lVolume)\t\\\r\n    (This)->lpVtbl -> put_volume(This,lVolume)\r\n\r\n#define IWMPSettings2_getMode(This,bstrMode,pvarfMode)\t\\\r\n    (This)->lpVtbl -> getMode(This,bstrMode,pvarfMode)\r\n\r\n#define IWMPSettings2_setMode(This,bstrMode,varfMode)\t\\\r\n    (This)->lpVtbl -> setMode(This,bstrMode,varfMode)\r\n\r\n#define IWMPSettings2_get_enableErrorDialogs(This,pfEnableErrorDialogs)\t\\\r\n    (This)->lpVtbl -> get_enableErrorDialogs(This,pfEnableErrorDialogs)\r\n\r\n#define IWMPSettings2_put_enableErrorDialogs(This,fEnableErrorDialogs)\t\\\r\n    (This)->lpVtbl -> put_enableErrorDialogs(This,fEnableErrorDialogs)\r\n\r\n\r\n#define IWMPSettings2_get_defaultAudioLanguage(This,plLangID)\t\\\r\n    (This)->lpVtbl -> get_defaultAudioLanguage(This,plLangID)\r\n\r\n#define IWMPSettings2_get_mediaAccessRights(This,pbstrRights)\t\\\r\n    (This)->lpVtbl -> get_mediaAccessRights(This,pbstrRights)\r\n\r\n#define IWMPSettings2_requestMediaAccessRights(This,bstrDesiredAccess,pvbAccepted)\t\\\r\n    (This)->lpVtbl -> requestMediaAccessRights(This,bstrDesiredAccess,pvbAccepted)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings2_get_defaultAudioLanguage_Proxy( \r\n    IWMPSettings2 * This,\r\n    /* [retval][out] */ long *plLangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings2_get_defaultAudioLanguage_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [propget][id] */ HRESULT STDMETHODCALLTYPE IWMPSettings2_get_mediaAccessRights_Proxy( \r\n    IWMPSettings2 * This,\r\n    /* [retval][out] */ BSTR *pbstrRights);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings2_get_mediaAccessRights_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [id] */ HRESULT STDMETHODCALLTYPE IWMPSettings2_requestMediaAccessRights_Proxy( \r\n    IWMPSettings2 * This,\r\n    /* [in] */ BSTR bstrDesiredAccess,\r\n    /* [retval][out] */ VARIANT_BOOL *pvbAccepted);\r\n\r\n\r\nvoid __RPC_STUB IWMPSettings2_requestMediaAccessRights_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPSettings2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPControls3_INTERFACE_DEFINED__\r\n#define __IWMPControls3_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPControls3 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPControls3;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"A1D1110E-D545-476a-9A78-AC3E4CB1E6BD\")\r\n    IWMPControls3 : public IWMPControls2\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_audioLanguageCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAudioLanguageID( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ long *plLangID) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getAudioLanguageDescription( \r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrLangDesc) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentAudioLanguage( \r\n            /* [retval][out] */ long *plLangID) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentAudioLanguage( \r\n            /* [in] */ long lLangID) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentAudioLanguageIndex( \r\n            /* [retval][out] */ long *plIndex) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentAudioLanguageIndex( \r\n            /* [in] */ long lIndex) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getLanguageName( \r\n            /* [in] */ long lLangID,\r\n            /* [retval][out] */ BSTR *pbstrLangName) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_currentPositionTimecode( \r\n            /* [retval][out] */ BSTR *bstrTimecode) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_currentPositionTimecode( \r\n            /* [in] */ BSTR bstrTimecode) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPControls3Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPControls3 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPControls3 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPControls3 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isAvailable )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ BSTR bstrItem,\r\n            /* [retval][out] */ VARIANT_BOOL *pIsAvailable);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *play )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *stop )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *pause )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastForward )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *fastReverse )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPosition )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ double *pdCurrentPosition);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPosition )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ double dCurrentPosition);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPositionString )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ BSTR *pbstrCurrentPosition);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *next )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *previous )( \r\n            IWMPControls3 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentItem )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ IWMPMedia **ppIWMPMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentItem )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMarker )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ long *plMarker);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMarker )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lMarker);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *playItem )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ IWMPMedia *pIWMPMedia);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *step )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lStep);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_audioLanguageCount )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAudioLanguageID )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ long *plLangID);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getAudioLanguageDescription )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lIndex,\r\n            /* [retval][out] */ BSTR *pbstrLangDesc);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentAudioLanguage )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ long *plLangID);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentAudioLanguage )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lLangID);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentAudioLanguageIndex )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ long *plIndex);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentAudioLanguageIndex )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lIndex);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getLanguageName )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ long lLangID,\r\n            /* [retval][out] */ BSTR *pbstrLangName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPositionTimecode )( \r\n            IWMPControls3 * This,\r\n            /* [retval][out] */ BSTR *bstrTimecode);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPositionTimecode )( \r\n            IWMPControls3 * This,\r\n            /* [in] */ BSTR bstrTimecode);\r\n        \r\n        END_INTERFACE\r\n    } IWMPControls3Vtbl;\r\n\r\n    interface IWMPControls3\r\n    {\r\n        CONST_VTBL struct IWMPControls3Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPControls3_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPControls3_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPControls3_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPControls3_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPControls3_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPControls3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPControls3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPControls3_get_isAvailable(This,bstrItem,pIsAvailable)\t\\\r\n    (This)->lpVtbl -> get_isAvailable(This,bstrItem,pIsAvailable)\r\n\r\n#define IWMPControls3_play(This)\t\\\r\n    (This)->lpVtbl -> play(This)\r\n\r\n#define IWMPControls3_stop(This)\t\\\r\n    (This)->lpVtbl -> stop(This)\r\n\r\n#define IWMPControls3_pause(This)\t\\\r\n    (This)->lpVtbl -> pause(This)\r\n\r\n#define IWMPControls3_fastForward(This)\t\\\r\n    (This)->lpVtbl -> fastForward(This)\r\n\r\n#define IWMPControls3_fastReverse(This)\t\\\r\n    (This)->lpVtbl -> fastReverse(This)\r\n\r\n#define IWMPControls3_get_currentPosition(This,pdCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPosition(This,pdCurrentPosition)\r\n\r\n#define IWMPControls3_put_currentPosition(This,dCurrentPosition)\t\\\r\n    (This)->lpVtbl -> put_currentPosition(This,dCurrentPosition)\r\n\r\n#define IWMPControls3_get_currentPositionString(This,pbstrCurrentPosition)\t\\\r\n    (This)->lpVtbl -> get_currentPositionString(This,pbstrCurrentPosition)\r\n\r\n#define IWMPControls3_next(This)\t\\\r\n    (This)->lpVtbl -> next(This)\r\n\r\n#define IWMPControls3_previous(This)\t\\\r\n    (This)->lpVtbl -> previous(This)\r\n\r\n#define IWMPControls3_get_currentItem(This,ppIWMPMedia)\t\\\r\n    (This)->lpVtbl -> get_currentItem(This,ppIWMPMedia)\r\n\r\n#define IWMPControls3_put_currentItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> put_currentItem(This,pIWMPMedia)\r\n\r\n#define IWMPControls3_get_currentMarker(This,plMarker)\t\\\r\n    (This)->lpVtbl -> get_currentMarker(This,plMarker)\r\n\r\n#define IWMPControls3_put_currentMarker(This,lMarker)\t\\\r\n    (This)->lpVtbl -> put_currentMarker(This,lMarker)\r\n\r\n#define IWMPControls3_playItem(This,pIWMPMedia)\t\\\r\n    (This)->lpVtbl -> playItem(This,pIWMPMedia)\r\n\r\n\r\n#define IWMPControls3_step(This,lStep)\t\\\r\n    (This)->lpVtbl -> step(This,lStep)\r\n\r\n\r\n#define IWMPControls3_get_audioLanguageCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_audioLanguageCount(This,plCount)\r\n\r\n#define IWMPControls3_getAudioLanguageID(This,lIndex,plLangID)\t\\\r\n    (This)->lpVtbl -> getAudioLanguageID(This,lIndex,plLangID)\r\n\r\n#define IWMPControls3_getAudioLanguageDescription(This,lIndex,pbstrLangDesc)\t\\\r\n    (This)->lpVtbl -> getAudioLanguageDescription(This,lIndex,pbstrLangDesc)\r\n\r\n#define IWMPControls3_get_currentAudioLanguage(This,plLangID)\t\\\r\n    (This)->lpVtbl -> get_currentAudioLanguage(This,plLangID)\r\n\r\n#define IWMPControls3_put_currentAudioLanguage(This,lLangID)\t\\\r\n    (This)->lpVtbl -> put_currentAudioLanguage(This,lLangID)\r\n\r\n#define IWMPControls3_get_currentAudioLanguageIndex(This,plIndex)\t\\\r\n    (This)->lpVtbl -> get_currentAudioLanguageIndex(This,plIndex)\r\n\r\n#define IWMPControls3_put_currentAudioLanguageIndex(This,lIndex)\t\\\r\n    (This)->lpVtbl -> put_currentAudioLanguageIndex(This,lIndex)\r\n\r\n#define IWMPControls3_getLanguageName(This,lLangID,pbstrLangName)\t\\\r\n    (This)->lpVtbl -> getLanguageName(This,lLangID,pbstrLangName)\r\n\r\n#define IWMPControls3_get_currentPositionTimecode(This,bstrTimecode)\t\\\r\n    (This)->lpVtbl -> get_currentPositionTimecode(This,bstrTimecode)\r\n\r\n#define IWMPControls3_put_currentPositionTimecode(This,bstrTimecode)\t\\\r\n    (This)->lpVtbl -> put_currentPositionTimecode(This,bstrTimecode)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_get_audioLanguageCount_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_get_audioLanguageCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_getAudioLanguageID_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ long *plLangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_getAudioLanguageID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_getAudioLanguageDescription_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ long lIndex,\r\n    /* [retval][out] */ BSTR *pbstrLangDesc);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_getAudioLanguageDescription_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_get_currentAudioLanguage_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [retval][out] */ long *plLangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_get_currentAudioLanguage_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_put_currentAudioLanguage_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ long lLangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_put_currentAudioLanguage_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_get_currentAudioLanguageIndex_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [retval][out] */ long *plIndex);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_get_currentAudioLanguageIndex_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_put_currentAudioLanguageIndex_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ long lIndex);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_put_currentAudioLanguageIndex_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_getLanguageName_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ long lLangID,\r\n    /* [retval][out] */ BSTR *pbstrLangName);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_getLanguageName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_get_currentPositionTimecode_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [retval][out] */ BSTR *bstrTimecode);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_get_currentPositionTimecode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPControls3_put_currentPositionTimecode_Proxy( \r\n    IWMPControls3 * This,\r\n    /* [in] */ BSTR bstrTimecode);\r\n\r\n\r\nvoid __RPC_STUB IWMPControls3_put_currentPositionTimecode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPControls3_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPClosedCaption2_INTERFACE_DEFINED__\r\n#define __IWMPClosedCaption2_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPClosedCaption2 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPClosedCaption2;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"350BA78B-6BC8-4113-A5F5-312056934EB6\")\r\n    IWMPClosedCaption2 : public IWMPClosedCaption\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_SAMILangCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getSAMILangName( \r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ BSTR *pbstrName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getSAMILangID( \r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ long *plLangID) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_SAMIStyleCount( \r\n            /* [retval][out] */ long *plCount) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE getSAMIStyleName( \r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ BSTR *pbstrName) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPClosedCaption2Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPClosedCaption2 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPClosedCaption2 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMIStyle )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMIStyle);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMIStyle )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ BSTR bstrSAMIStyle);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMILang )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMILang);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMILang )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ BSTR bstrSAMILang);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMIFileName )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ BSTR *pbstrSAMIFileName);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_SAMIFileName )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ BSTR bstrSAMIFileName);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_captioningId )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ BSTR *pbstrCaptioningID);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_captioningId )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ BSTR bstrCaptioningID);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMILangCount )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getSAMILangName )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getSAMILangID )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ long *plLangID);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_SAMIStyleCount )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [retval][out] */ long *plCount);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *getSAMIStyleName )( \r\n            IWMPClosedCaption2 * This,\r\n            /* [in] */ long nIndex,\r\n            /* [retval][out] */ BSTR *pbstrName);\r\n        \r\n        END_INTERFACE\r\n    } IWMPClosedCaption2Vtbl;\r\n\r\n    interface IWMPClosedCaption2\r\n    {\r\n        CONST_VTBL struct IWMPClosedCaption2Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPClosedCaption2_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPClosedCaption2_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPClosedCaption2_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPClosedCaption2_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPClosedCaption2_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPClosedCaption2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPClosedCaption2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPClosedCaption2_get_SAMIStyle(This,pbstrSAMIStyle)\t\\\r\n    (This)->lpVtbl -> get_SAMIStyle(This,pbstrSAMIStyle)\r\n\r\n#define IWMPClosedCaption2_put_SAMIStyle(This,bstrSAMIStyle)\t\\\r\n    (This)->lpVtbl -> put_SAMIStyle(This,bstrSAMIStyle)\r\n\r\n#define IWMPClosedCaption2_get_SAMILang(This,pbstrSAMILang)\t\\\r\n    (This)->lpVtbl -> get_SAMILang(This,pbstrSAMILang)\r\n\r\n#define IWMPClosedCaption2_put_SAMILang(This,bstrSAMILang)\t\\\r\n    (This)->lpVtbl -> put_SAMILang(This,bstrSAMILang)\r\n\r\n#define IWMPClosedCaption2_get_SAMIFileName(This,pbstrSAMIFileName)\t\\\r\n    (This)->lpVtbl -> get_SAMIFileName(This,pbstrSAMIFileName)\r\n\r\n#define IWMPClosedCaption2_put_SAMIFileName(This,bstrSAMIFileName)\t\\\r\n    (This)->lpVtbl -> put_SAMIFileName(This,bstrSAMIFileName)\r\n\r\n#define IWMPClosedCaption2_get_captioningId(This,pbstrCaptioningID)\t\\\r\n    (This)->lpVtbl -> get_captioningId(This,pbstrCaptioningID)\r\n\r\n#define IWMPClosedCaption2_put_captioningId(This,bstrCaptioningID)\t\\\r\n    (This)->lpVtbl -> put_captioningId(This,bstrCaptioningID)\r\n\r\n\r\n#define IWMPClosedCaption2_get_SAMILangCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_SAMILangCount(This,plCount)\r\n\r\n#define IWMPClosedCaption2_getSAMILangName(This,nIndex,pbstrName)\t\\\r\n    (This)->lpVtbl -> getSAMILangName(This,nIndex,pbstrName)\r\n\r\n#define IWMPClosedCaption2_getSAMILangID(This,nIndex,plLangID)\t\\\r\n    (This)->lpVtbl -> getSAMILangID(This,nIndex,plLangID)\r\n\r\n#define IWMPClosedCaption2_get_SAMIStyleCount(This,plCount)\t\\\r\n    (This)->lpVtbl -> get_SAMIStyleCount(This,plCount)\r\n\r\n#define IWMPClosedCaption2_getSAMIStyleName(This,nIndex,pbstrName)\t\\\r\n    (This)->lpVtbl -> getSAMIStyleName(This,nIndex,pbstrName)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption2_get_SAMILangCount_Proxy( \r\n    IWMPClosedCaption2 * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption2_get_SAMILangCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption2_getSAMILangName_Proxy( \r\n    IWMPClosedCaption2 * This,\r\n    /* [in] */ long nIndex,\r\n    /* [retval][out] */ BSTR *pbstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption2_getSAMILangName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption2_getSAMILangID_Proxy( \r\n    IWMPClosedCaption2 * This,\r\n    /* [in] */ long nIndex,\r\n    /* [retval][out] */ long *plLangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption2_getSAMILangID_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption2_get_SAMIStyleCount_Proxy( \r\n    IWMPClosedCaption2 * This,\r\n    /* [retval][out] */ long *plCount);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption2_get_SAMIStyleCount_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPClosedCaption2_getSAMIStyleName_Proxy( \r\n    IWMPClosedCaption2 * This,\r\n    /* [in] */ long nIndex,\r\n    /* [retval][out] */ BSTR *pbstrName);\r\n\r\n\r\nvoid __RPC_STUB IWMPClosedCaption2_getSAMIStyleName_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPClosedCaption2_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayerApplication_INTERFACE_DEFINED__\r\n#define __IWMPPlayerApplication_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayerApplication */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayerApplication;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"40897764-CEAB-47be-AD4A-8E28537F9BBF\")\r\n    IWMPPlayerApplication : public IDispatch\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE switchToPlayerApplication( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE switchToControl( void) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playerDocked( \r\n            /* [retval][out] */ VARIANT_BOOL *pbPlayerDocked) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_hasDisplay( \r\n            /* [retval][out] */ VARIANT_BOOL *pbHasDisplay) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayerApplicationVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayerApplication * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayerApplication * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayerApplication * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlayerApplication * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlayerApplication * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlayerApplication * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlayerApplication * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *switchToPlayerApplication )( \r\n            IWMPPlayerApplication * This);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *switchToControl )( \r\n            IWMPPlayerApplication * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playerDocked )( \r\n            IWMPPlayerApplication * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbPlayerDocked);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_hasDisplay )( \r\n            IWMPPlayerApplication * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbHasDisplay);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayerApplicationVtbl;\r\n\r\n    interface IWMPPlayerApplication\r\n    {\r\n        CONST_VTBL struct IWMPPlayerApplicationVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayerApplication_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayerApplication_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayerApplication_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayerApplication_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlayerApplication_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlayerApplication_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlayerApplication_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlayerApplication_switchToPlayerApplication(This)\t\\\r\n    (This)->lpVtbl -> switchToPlayerApplication(This)\r\n\r\n#define IWMPPlayerApplication_switchToControl(This)\t\\\r\n    (This)->lpVtbl -> switchToControl(This)\r\n\r\n#define IWMPPlayerApplication_get_playerDocked(This,pbPlayerDocked)\t\\\r\n    (This)->lpVtbl -> get_playerDocked(This,pbPlayerDocked)\r\n\r\n#define IWMPPlayerApplication_get_hasDisplay(This,pbHasDisplay)\t\\\r\n    (This)->lpVtbl -> get_hasDisplay(This,pbHasDisplay)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayerApplication_switchToPlayerApplication_Proxy( \r\n    IWMPPlayerApplication * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerApplication_switchToPlayerApplication_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayerApplication_switchToControl_Proxy( \r\n    IWMPPlayerApplication * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerApplication_switchToControl_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayerApplication_get_playerDocked_Proxy( \r\n    IWMPPlayerApplication * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbPlayerDocked);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerApplication_get_playerDocked_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayerApplication_get_hasDisplay_Proxy( \r\n    IWMPPlayerApplication * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbHasDisplay);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerApplication_get_hasDisplay_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayerApplication_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPCore3_INTERFACE_DEFINED__\r\n#define __IWMPCore3_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPCore3 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPCore3;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"7587C667-628F-499f-88E7-6A6F4E888464\")\r\n    IWMPCore3 : public IWMPCore2\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE newPlaylist( \r\n            /* [in] */ BSTR bstrName,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPPlaylist **ppPlaylist) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE newMedia( \r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPMedia **ppMedia) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPCore3Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPCore3 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPCore3 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPCore3 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPCore3 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_dvd )( \r\n            IWMPCore3 * This,\r\n            /* [retval][out] */ IWMPDVD **ppDVD);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *newPlaylist )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPPlaylist **ppPlaylist);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *newMedia )( \r\n            IWMPCore3 * This,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        END_INTERFACE\r\n    } IWMPCore3Vtbl;\r\n\r\n    interface IWMPCore3\r\n    {\r\n        CONST_VTBL struct IWMPCore3Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPCore3_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPCore3_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPCore3_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPCore3_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPCore3_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPCore3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPCore3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPCore3_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPCore3_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPCore3_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPCore3_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPCore3_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPCore3_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPCore3_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPCore3_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPCore3_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPCore3_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPCore3_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPCore3_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPCore3_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPCore3_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPCore3_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPCore3_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPCore3_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPCore3_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPCore3_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPCore3_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPCore3_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPCore3_get_dvd(This,ppDVD)\t\\\r\n    (This)->lpVtbl -> get_dvd(This,ppDVD)\r\n\r\n\r\n#define IWMPCore3_newPlaylist(This,bstrName,bstrURL,ppPlaylist)\t\\\r\n    (This)->lpVtbl -> newPlaylist(This,bstrName,bstrURL,ppPlaylist)\r\n\r\n#define IWMPCore3_newMedia(This,bstrURL,ppMedia)\t\\\r\n    (This)->lpVtbl -> newMedia(This,bstrURL,ppMedia)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCore3_newPlaylist_Proxy( \r\n    IWMPCore3 * This,\r\n    /* [in] */ BSTR bstrName,\r\n    /* [in] */ BSTR bstrURL,\r\n    /* [retval][out] */ IWMPPlaylist **ppPlaylist);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore3_newPlaylist_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPCore3_newMedia_Proxy( \r\n    IWMPCore3 * This,\r\n    /* [in] */ BSTR bstrURL,\r\n    /* [retval][out] */ IWMPMedia **ppMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPCore3_newMedia_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPCore3_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayer4_INTERFACE_DEFINED__\r\n#define __IWMPPlayer4_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayer4 */\r\n/* [unique][helpstring][dual][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayer4;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"6C497D62-8919-413c-82DB-E935FB3EC584\")\r\n    IWMPPlayer4 : public IWMPCore3\r\n    {\r\n    public:\r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enabled( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enabled( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_fullScreen( \r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_fullScreen( \r\n            VARIANT_BOOL bFullScreen) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_enableContextMenu( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_enableContextMenu( \r\n            VARIANT_BOOL bEnableContextMenu) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_uiMode( \r\n            /* [in] */ BSTR bstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_uiMode( \r\n            /* [retval][out] */ BSTR *pbstrMode) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_stretchToFit( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_stretchToFit( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_windowlessVideo( \r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE put_windowlessVideo( \r\n            /* [in] */ VARIANT_BOOL bEnabled) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_isRemote( \r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsRemote) = 0;\r\n        \r\n        virtual /* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE get_playerApplication( \r\n            /* [retval][out] */ IWMPPlayerApplication **ppIWMPPlayerApplication) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE openPlayer( \r\n            /* [in] */ BSTR bstrURL) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayer4Vtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayer4 * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayer4 * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            IWMPPlayer4 * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *close )( \r\n            IWMPPlayer4 * This);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_URL )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ BSTR *pbstrURL);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_URL )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_openState )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ WMPOpenState *pwmpos);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playState )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ WMPPlayState *pwmpps);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_controls )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPControls **ppControl);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_settings )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPSettings **ppSettings);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentMedia )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentMedia )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ IWMPMedia *pMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_mediaCollection )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPMediaCollection **ppMediaCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playlistCollection )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPPlaylistCollection **ppPlaylistCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_versionInfo )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ BSTR *pbstrVersionInfo);\r\n        \r\n        /* [id] */ HRESULT ( STDMETHODCALLTYPE *launchURL )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        /* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_network )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPNetwork **ppQNI);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_currentPlaylist )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPPlaylist **ppPL);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_currentPlaylist )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ IWMPPlaylist *pPL);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_cdromCollection )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPCdromCollection **ppCdromCollection);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_closedCaption )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPClosedCaption **ppClosedCaption);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isOnline )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pfOnline);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_error )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPError **ppError);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_status )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ BSTR *pbstrStatus);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_dvd )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPDVD **ppDVD);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *newPlaylist )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrName,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPPlaylist **ppPlaylist);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *newMedia )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [retval][out] */ IWMPMedia **ppMedia);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enabled )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enabled )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_fullScreen )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_fullScreen )( \r\n            IWMPPlayer4 * This,\r\n            VARIANT_BOOL bFullScreen);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_enableContextMenu )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_enableContextMenu )( \r\n            IWMPPlayer4 * This,\r\n            VARIANT_BOOL bEnableContextMenu);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_uiMode )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_uiMode )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ BSTR *pbstrMode);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_stretchToFit )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_stretchToFit )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_windowlessVideo )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n        \r\n        /* [helpstring][propput][id] */ HRESULT ( STDMETHODCALLTYPE *put_windowlessVideo )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ VARIANT_BOOL bEnabled);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_isRemote )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ VARIANT_BOOL *pvarfIsRemote);\r\n        \r\n        /* [helpstring][propget][id] */ HRESULT ( STDMETHODCALLTYPE *get_playerApplication )( \r\n            IWMPPlayer4 * This,\r\n            /* [retval][out] */ IWMPPlayerApplication **ppIWMPPlayerApplication);\r\n        \r\n        /* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *openPlayer )( \r\n            IWMPPlayer4 * This,\r\n            /* [in] */ BSTR bstrURL);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayer4Vtbl;\r\n\r\n    interface IWMPPlayer4\r\n    {\r\n        CONST_VTBL struct IWMPPlayer4Vtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayer4_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayer4_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayer4_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayer4_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define IWMPPlayer4_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define IWMPPlayer4_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define IWMPPlayer4_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n\r\n#define IWMPPlayer4_close(This)\t\\\r\n    (This)->lpVtbl -> close(This)\r\n\r\n#define IWMPPlayer4_get_URL(This,pbstrURL)\t\\\r\n    (This)->lpVtbl -> get_URL(This,pbstrURL)\r\n\r\n#define IWMPPlayer4_put_URL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> put_URL(This,bstrURL)\r\n\r\n#define IWMPPlayer4_get_openState(This,pwmpos)\t\\\r\n    (This)->lpVtbl -> get_openState(This,pwmpos)\r\n\r\n#define IWMPPlayer4_get_playState(This,pwmpps)\t\\\r\n    (This)->lpVtbl -> get_playState(This,pwmpps)\r\n\r\n#define IWMPPlayer4_get_controls(This,ppControl)\t\\\r\n    (This)->lpVtbl -> get_controls(This,ppControl)\r\n\r\n#define IWMPPlayer4_get_settings(This,ppSettings)\t\\\r\n    (This)->lpVtbl -> get_settings(This,ppSettings)\r\n\r\n#define IWMPPlayer4_get_currentMedia(This,ppMedia)\t\\\r\n    (This)->lpVtbl -> get_currentMedia(This,ppMedia)\r\n\r\n#define IWMPPlayer4_put_currentMedia(This,pMedia)\t\\\r\n    (This)->lpVtbl -> put_currentMedia(This,pMedia)\r\n\r\n#define IWMPPlayer4_get_mediaCollection(This,ppMediaCollection)\t\\\r\n    (This)->lpVtbl -> get_mediaCollection(This,ppMediaCollection)\r\n\r\n#define IWMPPlayer4_get_playlistCollection(This,ppPlaylistCollection)\t\\\r\n    (This)->lpVtbl -> get_playlistCollection(This,ppPlaylistCollection)\r\n\r\n#define IWMPPlayer4_get_versionInfo(This,pbstrVersionInfo)\t\\\r\n    (This)->lpVtbl -> get_versionInfo(This,pbstrVersionInfo)\r\n\r\n#define IWMPPlayer4_launchURL(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> launchURL(This,bstrURL)\r\n\r\n#define IWMPPlayer4_get_network(This,ppQNI)\t\\\r\n    (This)->lpVtbl -> get_network(This,ppQNI)\r\n\r\n#define IWMPPlayer4_get_currentPlaylist(This,ppPL)\t\\\r\n    (This)->lpVtbl -> get_currentPlaylist(This,ppPL)\r\n\r\n#define IWMPPlayer4_put_currentPlaylist(This,pPL)\t\\\r\n    (This)->lpVtbl -> put_currentPlaylist(This,pPL)\r\n\r\n#define IWMPPlayer4_get_cdromCollection(This,ppCdromCollection)\t\\\r\n    (This)->lpVtbl -> get_cdromCollection(This,ppCdromCollection)\r\n\r\n#define IWMPPlayer4_get_closedCaption(This,ppClosedCaption)\t\\\r\n    (This)->lpVtbl -> get_closedCaption(This,ppClosedCaption)\r\n\r\n#define IWMPPlayer4_get_isOnline(This,pfOnline)\t\\\r\n    (This)->lpVtbl -> get_isOnline(This,pfOnline)\r\n\r\n#define IWMPPlayer4_get_error(This,ppError)\t\\\r\n    (This)->lpVtbl -> get_error(This,ppError)\r\n\r\n#define IWMPPlayer4_get_status(This,pbstrStatus)\t\\\r\n    (This)->lpVtbl -> get_status(This,pbstrStatus)\r\n\r\n\r\n#define IWMPPlayer4_get_dvd(This,ppDVD)\t\\\r\n    (This)->lpVtbl -> get_dvd(This,ppDVD)\r\n\r\n\r\n#define IWMPPlayer4_newPlaylist(This,bstrName,bstrURL,ppPlaylist)\t\\\r\n    (This)->lpVtbl -> newPlaylist(This,bstrName,bstrURL,ppPlaylist)\r\n\r\n#define IWMPPlayer4_newMedia(This,bstrURL,ppMedia)\t\\\r\n    (This)->lpVtbl -> newMedia(This,bstrURL,ppMedia)\r\n\r\n\r\n#define IWMPPlayer4_get_enabled(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_enabled(This,pbEnabled)\r\n\r\n#define IWMPPlayer4_put_enabled(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_enabled(This,bEnabled)\r\n\r\n#define IWMPPlayer4_get_fullScreen(This,pbFullScreen)\t\\\r\n    (This)->lpVtbl -> get_fullScreen(This,pbFullScreen)\r\n\r\n#define IWMPPlayer4_put_fullScreen(This,bFullScreen)\t\\\r\n    (This)->lpVtbl -> put_fullScreen(This,bFullScreen)\r\n\r\n#define IWMPPlayer4_get_enableContextMenu(This,pbEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> get_enableContextMenu(This,pbEnableContextMenu)\r\n\r\n#define IWMPPlayer4_put_enableContextMenu(This,bEnableContextMenu)\t\\\r\n    (This)->lpVtbl -> put_enableContextMenu(This,bEnableContextMenu)\r\n\r\n#define IWMPPlayer4_put_uiMode(This,bstrMode)\t\\\r\n    (This)->lpVtbl -> put_uiMode(This,bstrMode)\r\n\r\n#define IWMPPlayer4_get_uiMode(This,pbstrMode)\t\\\r\n    (This)->lpVtbl -> get_uiMode(This,pbstrMode)\r\n\r\n#define IWMPPlayer4_get_stretchToFit(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_stretchToFit(This,pbEnabled)\r\n\r\n#define IWMPPlayer4_put_stretchToFit(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_stretchToFit(This,bEnabled)\r\n\r\n#define IWMPPlayer4_get_windowlessVideo(This,pbEnabled)\t\\\r\n    (This)->lpVtbl -> get_windowlessVideo(This,pbEnabled)\r\n\r\n#define IWMPPlayer4_put_windowlessVideo(This,bEnabled)\t\\\r\n    (This)->lpVtbl -> put_windowlessVideo(This,bEnabled)\r\n\r\n#define IWMPPlayer4_get_isRemote(This,pvarfIsRemote)\t\\\r\n    (This)->lpVtbl -> get_isRemote(This,pvarfIsRemote)\r\n\r\n#define IWMPPlayer4_get_playerApplication(This,ppIWMPPlayerApplication)\t\\\r\n    (This)->lpVtbl -> get_playerApplication(This,ppIWMPPlayerApplication)\r\n\r\n#define IWMPPlayer4_openPlayer(This,bstrURL)\t\\\r\n    (This)->lpVtbl -> openPlayer(This,bstrURL)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_enabled_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_enabled_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_enabled_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_fullScreen_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_fullScreen_Proxy( \r\n    IWMPPlayer4 * This,\r\n    VARIANT_BOOL bFullScreen);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_fullScreen_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_enableContextMenu_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_enableContextMenu_Proxy( \r\n    IWMPPlayer4 * This,\r\n    VARIANT_BOOL bEnableContextMenu);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_enableContextMenu_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_uiMode_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [in] */ BSTR bstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_uiMode_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ BSTR *pbstrMode);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_uiMode_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_stretchToFit_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_stretchToFit_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_stretchToFit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_windowlessVideo_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pbEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propput][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_put_windowlessVideo_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [in] */ VARIANT_BOOL bEnabled);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_put_windowlessVideo_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_isRemote_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ VARIANT_BOOL *pvarfIsRemote);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_isRemote_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][propget][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_get_playerApplication_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [retval][out] */ IWMPPlayerApplication **ppIWMPPlayerApplication);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_get_playerApplication_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE IWMPPlayer4_openPlayer_Proxy( \r\n    IWMPPlayer4 * This,\r\n    /* [in] */ BSTR bstrURL);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayer4_openPlayer_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayer4_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef __IWMPPlayerServices_INTERFACE_DEFINED__\r\n#define __IWMPPlayerServices_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPlayerServices */\r\n/* [unique][helpstring][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPlayerServices;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"1D01FBDB-ADE2-4c8d-9842-C190B95C3306\")\r\n    IWMPPlayerServices : public IUnknown\r\n    {\r\n    public:\r\n        virtual HRESULT STDMETHODCALLTYPE activateUIPlugin( \r\n            /* [in] */ BSTR bstrPlugin) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE setTaskPane( \r\n            /* [in] */ BSTR bstrTaskPane) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE setTaskPaneURL( \r\n            /* [in] */ BSTR bstrTaskPane,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [in] */ BSTR bstrFriendlyName) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPlayerServicesVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPlayerServices * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPlayerServices * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPlayerServices * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *activateUIPlugin )( \r\n            IWMPPlayerServices * This,\r\n            /* [in] */ BSTR bstrPlugin);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *setTaskPane )( \r\n            IWMPPlayerServices * This,\r\n            /* [in] */ BSTR bstrTaskPane);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *setTaskPaneURL )( \r\n            IWMPPlayerServices * This,\r\n            /* [in] */ BSTR bstrTaskPane,\r\n            /* [in] */ BSTR bstrURL,\r\n            /* [in] */ BSTR bstrFriendlyName);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPlayerServicesVtbl;\r\n\r\n    interface IWMPPlayerServices\r\n    {\r\n        CONST_VTBL struct IWMPPlayerServicesVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPlayerServices_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPlayerServices_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPlayerServices_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPlayerServices_activateUIPlugin(This,bstrPlugin)\t\\\r\n    (This)->lpVtbl -> activateUIPlugin(This,bstrPlugin)\r\n\r\n#define IWMPPlayerServices_setTaskPane(This,bstrTaskPane)\t\\\r\n    (This)->lpVtbl -> setTaskPane(This,bstrTaskPane)\r\n\r\n#define IWMPPlayerServices_setTaskPaneURL(This,bstrTaskPane,bstrURL,bstrFriendlyName)\t\\\r\n    (This)->lpVtbl -> setTaskPaneURL(This,bstrTaskPane,bstrURL,bstrFriendlyName)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPlayerServices_activateUIPlugin_Proxy( \r\n    IWMPPlayerServices * This,\r\n    /* [in] */ BSTR bstrPlugin);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerServices_activateUIPlugin_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPlayerServices_setTaskPane_Proxy( \r\n    IWMPPlayerServices * This,\r\n    /* [in] */ BSTR bstrTaskPane);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerServices_setTaskPane_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPlayerServices_setTaskPaneURL_Proxy( \r\n    IWMPPlayerServices * This,\r\n    /* [in] */ BSTR bstrTaskPane,\r\n    /* [in] */ BSTR bstrURL,\r\n    /* [in] */ BSTR bstrFriendlyName);\r\n\r\n\r\nvoid __RPC_STUB IWMPPlayerServices_setTaskPaneURL_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPlayerServices_INTERFACE_DEFINED__ */\r\n\r\n\r\n/* interface __MIDL_itf_wmp_0291 */\r\n/* [local] */ \r\n\r\nstruct DECLSPEC_UUID(\"6BF52A50-394A-11d3-B153-00C04F79FAA6\") WMPLib;\r\nstruct DECLSPEC_UUID(\"DF333473-2CF7-4be2-907F-9AAD5661364F\") WMPRemoteMediaServices;\r\n\r\n\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0291_v0_0_c_ifspec;\r\nextern RPC_IF_HANDLE __MIDL_itf_wmp_0291_v0_0_s_ifspec;\r\n\r\n\r\n#ifndef __WMPLib_LIBRARY_DEFINED__\r\n#define __WMPLib_LIBRARY_DEFINED__\r\n\r\n/* library WMPLib */\r\n/* [helpstring][version][uuid] */ \r\n\r\n\r\nEXTERN_C const IID LIBID_WMPLib;\r\n\r\n#ifndef __IWMPEvents_INTERFACE_DEFINED__\r\n#define __IWMPEvents_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPEvents */\r\n/* [unique][helpstring][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPEvents;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"19A6627B-DA9E-47c1-BB23-00B5E668236A\")\r\n    IWMPEvents : public IUnknown\r\n    {\r\n    public:\r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE OpenStateChange( \r\n            /* [in] */ long NewState) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlayStateChange( \r\n            /* [in] */ long NewState) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE AudioLanguageChange( \r\n            /* [in] */ long LangID) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE StatusChange( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE ScriptCommand( \r\n            /* [in] */ BSTR scType,\r\n            /* [in] */ BSTR Param) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE NewStream( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE Disconnect( \r\n            /* [in] */ long Result) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE Buffering( \r\n            /* [in] */ VARIANT_BOOL Start) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE Error( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE Warning( \r\n            /* [in] */ long WarningType,\r\n            /* [in] */ long Param,\r\n            /* [in] */ BSTR Description) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE EndOfStream( \r\n            /* [in] */ long Result) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PositionChange( \r\n            /* [in] */ double oldPosition,\r\n            /* [in] */ double newPosition) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MarkerHit( \r\n            /* [in] */ long MarkerNum) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE DurationUnitChange( \r\n            /* [in] */ long NewDurationUnit) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE CdromMediaChange( \r\n            /* [in] */ long CdromNum) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlaylistChange( \r\n            /* [in] */ IDispatch *Playlist,\r\n            /* [in] */ WMPPlaylistChangeEventType change) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE CurrentPlaylistChange( \r\n            /* [in] */ WMPPlaylistChangeEventType change) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE CurrentPlaylistItemAvailable( \r\n            /* [in] */ BSTR bstrItemName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaChange( \r\n            /* [in] */ IDispatch *Item) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE CurrentMediaItemAvailable( \r\n            /* [in] */ BSTR bstrItemName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE CurrentItemChange( \r\n            /* [in] */ IDispatch *pdispMedia) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaCollectionChange( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaCollectionAttributeStringAdded( \r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrAttribVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaCollectionAttributeStringRemoved( \r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrAttribVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaCollectionAttributeStringChanged( \r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrOldAttribVal,\r\n            /* [in] */ BSTR bstrNewAttribVal) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlaylistCollectionChange( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlaylistCollectionPlaylistAdded( \r\n            /* [in] */ BSTR bstrPlaylistName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlaylistCollectionPlaylistRemoved( \r\n            /* [in] */ BSTR bstrPlaylistName) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlaylistCollectionPlaylistSetAsDeleted( \r\n            /* [in] */ BSTR bstrPlaylistName,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE ModeChange( \r\n            /* [in] */ BSTR ModeName,\r\n            /* [in] */ VARIANT_BOOL NewValue) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MediaError( \r\n            /* [in] */ IDispatch *pMediaObject) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE OpenPlaylistSwitch( \r\n            /* [in] */ IDispatch *pItem) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE DomainChange( \r\n            /* [in] */ BSTR strDomain) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE SwitchedToPlayerApplication( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE SwitchedToControl( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlayerDockedStateChange( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE PlayerReconnect( void) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE Click( \r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE DoubleClick( \r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE KeyDown( \r\n            /* [in] */ short nKeyCode,\r\n            /* [in] */ short nShiftState) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE KeyPress( \r\n            /* [in] */ short nKeyAscii) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE KeyUp( \r\n            /* [in] */ short nKeyCode,\r\n            /* [in] */ short nShiftState) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MouseDown( \r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MouseMove( \r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY) = 0;\r\n        \r\n        virtual /* [helpstring][id] */ void STDMETHODCALLTYPE MouseUp( \r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPEventsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPEvents * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *OpenStateChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long NewState);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlayStateChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long NewState);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *AudioLanguageChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long LangID);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *StatusChange )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *ScriptCommand )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR scType,\r\n            /* [in] */ BSTR Param);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *NewStream )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *Disconnect )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long Result);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *Buffering )( \r\n            IWMPEvents * This,\r\n            /* [in] */ VARIANT_BOOL Start);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *Error )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *Warning )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long WarningType,\r\n            /* [in] */ long Param,\r\n            /* [in] */ BSTR Description);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *EndOfStream )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long Result);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PositionChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ double oldPosition,\r\n            /* [in] */ double newPosition);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MarkerHit )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long MarkerNum);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *DurationUnitChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long NewDurationUnit);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *CdromMediaChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ long CdromNum);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlaylistChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ IDispatch *Playlist,\r\n            /* [in] */ WMPPlaylistChangeEventType change);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *CurrentPlaylistChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ WMPPlaylistChangeEventType change);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *CurrentPlaylistItemAvailable )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrItemName);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ IDispatch *Item);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *CurrentMediaItemAvailable )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrItemName);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *CurrentItemChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ IDispatch *pdispMedia);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaCollectionChange )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaCollectionAttributeStringAdded )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrAttribVal);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaCollectionAttributeStringRemoved )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrAttribVal);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaCollectionAttributeStringChanged )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrAttribName,\r\n            /* [in] */ BSTR bstrOldAttribVal,\r\n            /* [in] */ BSTR bstrNewAttribVal);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlaylistCollectionChange )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlaylistCollectionPlaylistAdded )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrPlaylistName);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlaylistCollectionPlaylistRemoved )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrPlaylistName);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlaylistCollectionPlaylistSetAsDeleted )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR bstrPlaylistName,\r\n            /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *ModeChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR ModeName,\r\n            /* [in] */ VARIANT_BOOL NewValue);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MediaError )( \r\n            IWMPEvents * This,\r\n            /* [in] */ IDispatch *pMediaObject);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *OpenPlaylistSwitch )( \r\n            IWMPEvents * This,\r\n            /* [in] */ IDispatch *pItem);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *DomainChange )( \r\n            IWMPEvents * This,\r\n            /* [in] */ BSTR strDomain);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *SwitchedToPlayerApplication )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *SwitchedToControl )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlayerDockedStateChange )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *PlayerReconnect )( \r\n            IWMPEvents * This);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *Click )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *DoubleClick )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *KeyDown )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nKeyCode,\r\n            /* [in] */ short nShiftState);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *KeyPress )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nKeyAscii);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *KeyUp )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nKeyCode,\r\n            /* [in] */ short nShiftState);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MouseDown )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MouseMove )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY);\r\n        \r\n        /* [helpstring][id] */ void ( STDMETHODCALLTYPE *MouseUp )( \r\n            IWMPEvents * This,\r\n            /* [in] */ short nButton,\r\n            /* [in] */ short nShiftState,\r\n            /* [in] */ long fX,\r\n            /* [in] */ long fY);\r\n        \r\n        END_INTERFACE\r\n    } IWMPEventsVtbl;\r\n\r\n    interface IWMPEvents\r\n    {\r\n        CONST_VTBL struct IWMPEventsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPEvents_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPEvents_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPEvents_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPEvents_OpenStateChange(This,NewState)\t\\\r\n    (This)->lpVtbl -> OpenStateChange(This,NewState)\r\n\r\n#define IWMPEvents_PlayStateChange(This,NewState)\t\\\r\n    (This)->lpVtbl -> PlayStateChange(This,NewState)\r\n\r\n#define IWMPEvents_AudioLanguageChange(This,LangID)\t\\\r\n    (This)->lpVtbl -> AudioLanguageChange(This,LangID)\r\n\r\n#define IWMPEvents_StatusChange(This)\t\\\r\n    (This)->lpVtbl -> StatusChange(This)\r\n\r\n#define IWMPEvents_ScriptCommand(This,scType,Param)\t\\\r\n    (This)->lpVtbl -> ScriptCommand(This,scType,Param)\r\n\r\n#define IWMPEvents_NewStream(This)\t\\\r\n    (This)->lpVtbl -> NewStream(This)\r\n\r\n#define IWMPEvents_Disconnect(This,Result)\t\\\r\n    (This)->lpVtbl -> Disconnect(This,Result)\r\n\r\n#define IWMPEvents_Buffering(This,Start)\t\\\r\n    (This)->lpVtbl -> Buffering(This,Start)\r\n\r\n#define IWMPEvents_Error(This)\t\\\r\n    (This)->lpVtbl -> Error(This)\r\n\r\n#define IWMPEvents_Warning(This,WarningType,Param,Description)\t\\\r\n    (This)->lpVtbl -> Warning(This,WarningType,Param,Description)\r\n\r\n#define IWMPEvents_EndOfStream(This,Result)\t\\\r\n    (This)->lpVtbl -> EndOfStream(This,Result)\r\n\r\n#define IWMPEvents_PositionChange(This,oldPosition,newPosition)\t\\\r\n    (This)->lpVtbl -> PositionChange(This,oldPosition,newPosition)\r\n\r\n#define IWMPEvents_MarkerHit(This,MarkerNum)\t\\\r\n    (This)->lpVtbl -> MarkerHit(This,MarkerNum)\r\n\r\n#define IWMPEvents_DurationUnitChange(This,NewDurationUnit)\t\\\r\n    (This)->lpVtbl -> DurationUnitChange(This,NewDurationUnit)\r\n\r\n#define IWMPEvents_CdromMediaChange(This,CdromNum)\t\\\r\n    (This)->lpVtbl -> CdromMediaChange(This,CdromNum)\r\n\r\n#define IWMPEvents_PlaylistChange(This,Playlist,change)\t\\\r\n    (This)->lpVtbl -> PlaylistChange(This,Playlist,change)\r\n\r\n#define IWMPEvents_CurrentPlaylistChange(This,change)\t\\\r\n    (This)->lpVtbl -> CurrentPlaylistChange(This,change)\r\n\r\n#define IWMPEvents_CurrentPlaylistItemAvailable(This,bstrItemName)\t\\\r\n    (This)->lpVtbl -> CurrentPlaylistItemAvailable(This,bstrItemName)\r\n\r\n#define IWMPEvents_MediaChange(This,Item)\t\\\r\n    (This)->lpVtbl -> MediaChange(This,Item)\r\n\r\n#define IWMPEvents_CurrentMediaItemAvailable(This,bstrItemName)\t\\\r\n    (This)->lpVtbl -> CurrentMediaItemAvailable(This,bstrItemName)\r\n\r\n#define IWMPEvents_CurrentItemChange(This,pdispMedia)\t\\\r\n    (This)->lpVtbl -> CurrentItemChange(This,pdispMedia)\r\n\r\n#define IWMPEvents_MediaCollectionChange(This)\t\\\r\n    (This)->lpVtbl -> MediaCollectionChange(This)\r\n\r\n#define IWMPEvents_MediaCollectionAttributeStringAdded(This,bstrAttribName,bstrAttribVal)\t\\\r\n    (This)->lpVtbl -> MediaCollectionAttributeStringAdded(This,bstrAttribName,bstrAttribVal)\r\n\r\n#define IWMPEvents_MediaCollectionAttributeStringRemoved(This,bstrAttribName,bstrAttribVal)\t\\\r\n    (This)->lpVtbl -> MediaCollectionAttributeStringRemoved(This,bstrAttribName,bstrAttribVal)\r\n\r\n#define IWMPEvents_MediaCollectionAttributeStringChanged(This,bstrAttribName,bstrOldAttribVal,bstrNewAttribVal)\t\\\r\n    (This)->lpVtbl -> MediaCollectionAttributeStringChanged(This,bstrAttribName,bstrOldAttribVal,bstrNewAttribVal)\r\n\r\n#define IWMPEvents_PlaylistCollectionChange(This)\t\\\r\n    (This)->lpVtbl -> PlaylistCollectionChange(This)\r\n\r\n#define IWMPEvents_PlaylistCollectionPlaylistAdded(This,bstrPlaylistName)\t\\\r\n    (This)->lpVtbl -> PlaylistCollectionPlaylistAdded(This,bstrPlaylistName)\r\n\r\n#define IWMPEvents_PlaylistCollectionPlaylistRemoved(This,bstrPlaylistName)\t\\\r\n    (This)->lpVtbl -> PlaylistCollectionPlaylistRemoved(This,bstrPlaylistName)\r\n\r\n#define IWMPEvents_PlaylistCollectionPlaylistSetAsDeleted(This,bstrPlaylistName,varfIsDeleted)\t\\\r\n    (This)->lpVtbl -> PlaylistCollectionPlaylistSetAsDeleted(This,bstrPlaylistName,varfIsDeleted)\r\n\r\n#define IWMPEvents_ModeChange(This,ModeName,NewValue)\t\\\r\n    (This)->lpVtbl -> ModeChange(This,ModeName,NewValue)\r\n\r\n#define IWMPEvents_MediaError(This,pMediaObject)\t\\\r\n    (This)->lpVtbl -> MediaError(This,pMediaObject)\r\n\r\n#define IWMPEvents_OpenPlaylistSwitch(This,pItem)\t\\\r\n    (This)->lpVtbl -> OpenPlaylistSwitch(This,pItem)\r\n\r\n#define IWMPEvents_DomainChange(This,strDomain)\t\\\r\n    (This)->lpVtbl -> DomainChange(This,strDomain)\r\n\r\n#define IWMPEvents_SwitchedToPlayerApplication(This)\t\\\r\n    (This)->lpVtbl -> SwitchedToPlayerApplication(This)\r\n\r\n#define IWMPEvents_SwitchedToControl(This)\t\\\r\n    (This)->lpVtbl -> SwitchedToControl(This)\r\n\r\n#define IWMPEvents_PlayerDockedStateChange(This)\t\\\r\n    (This)->lpVtbl -> PlayerDockedStateChange(This)\r\n\r\n#define IWMPEvents_PlayerReconnect(This)\t\\\r\n    (This)->lpVtbl -> PlayerReconnect(This)\r\n\r\n#define IWMPEvents_Click(This,nButton,nShiftState,fX,fY)\t\\\r\n    (This)->lpVtbl -> Click(This,nButton,nShiftState,fX,fY)\r\n\r\n#define IWMPEvents_DoubleClick(This,nButton,nShiftState,fX,fY)\t\\\r\n    (This)->lpVtbl -> DoubleClick(This,nButton,nShiftState,fX,fY)\r\n\r\n#define IWMPEvents_KeyDown(This,nKeyCode,nShiftState)\t\\\r\n    (This)->lpVtbl -> KeyDown(This,nKeyCode,nShiftState)\r\n\r\n#define IWMPEvents_KeyPress(This,nKeyAscii)\t\\\r\n    (This)->lpVtbl -> KeyPress(This,nKeyAscii)\r\n\r\n#define IWMPEvents_KeyUp(This,nKeyCode,nShiftState)\t\\\r\n    (This)->lpVtbl -> KeyUp(This,nKeyCode,nShiftState)\r\n\r\n#define IWMPEvents_MouseDown(This,nButton,nShiftState,fX,fY)\t\\\r\n    (This)->lpVtbl -> MouseDown(This,nButton,nShiftState,fX,fY)\r\n\r\n#define IWMPEvents_MouseMove(This,nButton,nShiftState,fX,fY)\t\\\r\n    (This)->lpVtbl -> MouseMove(This,nButton,nShiftState,fX,fY)\r\n\r\n#define IWMPEvents_MouseUp(This,nButton,nShiftState,fX,fY)\t\\\r\n    (This)->lpVtbl -> MouseUp(This,nButton,nShiftState,fX,fY)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_OpenStateChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long NewState);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_OpenStateChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlayStateChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long NewState);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlayStateChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_AudioLanguageChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long LangID);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_AudioLanguageChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_StatusChange_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_StatusChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_ScriptCommand_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR scType,\r\n    /* [in] */ BSTR Param);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_ScriptCommand_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_NewStream_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_NewStream_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_Disconnect_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long Result);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_Disconnect_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_Buffering_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ VARIANT_BOOL Start);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_Buffering_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_Error_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_Error_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_Warning_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long WarningType,\r\n    /* [in] */ long Param,\r\n    /* [in] */ BSTR Description);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_Warning_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_EndOfStream_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long Result);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_EndOfStream_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PositionChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ double oldPosition,\r\n    /* [in] */ double newPosition);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PositionChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MarkerHit_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long MarkerNum);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MarkerHit_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_DurationUnitChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long NewDurationUnit);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_DurationUnitChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_CdromMediaChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ long CdromNum);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_CdromMediaChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlaylistChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ IDispatch *Playlist,\r\n    /* [in] */ WMPPlaylistChangeEventType change);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlaylistChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_CurrentPlaylistChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ WMPPlaylistChangeEventType change);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_CurrentPlaylistChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_CurrentPlaylistItemAvailable_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrItemName);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_CurrentPlaylistItemAvailable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ IDispatch *Item);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_CurrentMediaItemAvailable_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrItemName);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_CurrentMediaItemAvailable_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_CurrentItemChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ IDispatch *pdispMedia);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_CurrentItemChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaCollectionChange_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaCollectionChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaCollectionAttributeStringAdded_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrAttribName,\r\n    /* [in] */ BSTR bstrAttribVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaCollectionAttributeStringAdded_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaCollectionAttributeStringRemoved_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrAttribName,\r\n    /* [in] */ BSTR bstrAttribVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaCollectionAttributeStringRemoved_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaCollectionAttributeStringChanged_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrAttribName,\r\n    /* [in] */ BSTR bstrOldAttribVal,\r\n    /* [in] */ BSTR bstrNewAttribVal);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaCollectionAttributeStringChanged_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlaylistCollectionChange_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlaylistCollectionChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlaylistCollectionPlaylistAdded_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrPlaylistName);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlaylistCollectionPlaylistAdded_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlaylistCollectionPlaylistRemoved_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrPlaylistName);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlaylistCollectionPlaylistRemoved_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlaylistCollectionPlaylistSetAsDeleted_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR bstrPlaylistName,\r\n    /* [in] */ VARIANT_BOOL varfIsDeleted);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlaylistCollectionPlaylistSetAsDeleted_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_ModeChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR ModeName,\r\n    /* [in] */ VARIANT_BOOL NewValue);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_ModeChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MediaError_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ IDispatch *pMediaObject);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MediaError_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_OpenPlaylistSwitch_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ IDispatch *pItem);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_OpenPlaylistSwitch_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_DomainChange_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ BSTR strDomain);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_DomainChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_SwitchedToPlayerApplication_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_SwitchedToPlayerApplication_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_SwitchedToControl_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_SwitchedToControl_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlayerDockedStateChange_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlayerDockedStateChange_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_PlayerReconnect_Proxy( \r\n    IWMPEvents * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_PlayerReconnect_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_Click_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nButton,\r\n    /* [in] */ short nShiftState,\r\n    /* [in] */ long fX,\r\n    /* [in] */ long fY);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_Click_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_DoubleClick_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nButton,\r\n    /* [in] */ short nShiftState,\r\n    /* [in] */ long fX,\r\n    /* [in] */ long fY);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_DoubleClick_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_KeyDown_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nKeyCode,\r\n    /* [in] */ short nShiftState);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_KeyDown_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_KeyPress_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nKeyAscii);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_KeyPress_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_KeyUp_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nKeyCode,\r\n    /* [in] */ short nShiftState);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_KeyUp_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MouseDown_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nButton,\r\n    /* [in] */ short nShiftState,\r\n    /* [in] */ long fX,\r\n    /* [in] */ long fY);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MouseDown_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MouseMove_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nButton,\r\n    /* [in] */ short nShiftState,\r\n    /* [in] */ long fX,\r\n    /* [in] */ long fY);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MouseMove_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n/* [helpstring][id] */ void STDMETHODCALLTYPE IWMPEvents_MouseUp_Proxy( \r\n    IWMPEvents * This,\r\n    /* [in] */ short nButton,\r\n    /* [in] */ short nShiftState,\r\n    /* [in] */ long fX,\r\n    /* [in] */ long fY);\r\n\r\n\r\nvoid __RPC_STUB IWMPEvents_MouseUp_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPEvents_INTERFACE_DEFINED__ */\r\n\r\n\r\n#ifndef ___WMPOCXEvents_DISPINTERFACE_DEFINED__\r\n#define ___WMPOCXEvents_DISPINTERFACE_DEFINED__\r\n\r\n/* dispinterface _WMPOCXEvents */\r\n/* [hidden][helpstring][uuid] */ \r\n\r\n\r\nEXTERN_C const IID DIID__WMPOCXEvents;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n\r\n    MIDL_INTERFACE(\"6BF52A51-394A-11d3-B153-00C04F79FAA6\")\r\n    _WMPOCXEvents : public IDispatch\r\n    {\r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct _WMPOCXEventsVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            _WMPOCXEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            _WMPOCXEvents * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            _WMPOCXEvents * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( \r\n            _WMPOCXEvents * This,\r\n            /* [out] */ UINT *pctinfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( \r\n            _WMPOCXEvents * This,\r\n            /* [in] */ UINT iTInfo,\r\n            /* [in] */ LCID lcid,\r\n            /* [out] */ ITypeInfo **ppTInfo);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( \r\n            _WMPOCXEvents * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [size_is][in] */ LPOLESTR *rgszNames,\r\n            /* [in] */ UINT cNames,\r\n            /* [in] */ LCID lcid,\r\n            /* [size_is][out] */ DISPID *rgDispId);\r\n        \r\n        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( \r\n            _WMPOCXEvents * This,\r\n            /* [in] */ DISPID dispIdMember,\r\n            /* [in] */ REFIID riid,\r\n            /* [in] */ LCID lcid,\r\n            /* [in] */ WORD wFlags,\r\n            /* [out][in] */ DISPPARAMS *pDispParams,\r\n            /* [out] */ VARIANT *pVarResult,\r\n            /* [out] */ EXCEPINFO *pExcepInfo,\r\n            /* [out] */ UINT *puArgErr);\r\n        \r\n        END_INTERFACE\r\n    } _WMPOCXEventsVtbl;\r\n\r\n    interface _WMPOCXEvents\r\n    {\r\n        CONST_VTBL struct _WMPOCXEventsVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define _WMPOCXEvents_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define _WMPOCXEvents_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define _WMPOCXEvents_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define _WMPOCXEvents_GetTypeInfoCount(This,pctinfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)\r\n\r\n#define _WMPOCXEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo)\t\\\r\n    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)\r\n\r\n#define _WMPOCXEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\t\\\r\n    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)\r\n\r\n#define _WMPOCXEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\t\\\r\n    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n#endif \t/* ___WMPOCXEvents_DISPINTERFACE_DEFINED__ */\r\n\r\n\r\nEXTERN_C const CLSID CLSID_WindowsMediaPlayer;\r\n\r\n#ifdef __cplusplus\r\n\r\nclass DECLSPEC_UUID(\"6BF52A52-394A-11d3-B153-00C04F79FAA6\")\r\nWindowsMediaPlayer;\r\n#endif\r\n#endif /* __WMPLib_LIBRARY_DEFINED__ */\r\n\r\n/* Additional Prototypes for ALL interfaces */\r\n\r\nunsigned long             __RPC_USER  BSTR_UserSize(     unsigned long *, unsigned long            , BSTR * ); \r\nunsigned char * __RPC_USER  BSTR_UserMarshal(  unsigned long *, unsigned char *, BSTR * ); \r\nunsigned char * __RPC_USER  BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); \r\nvoid                      __RPC_USER  BSTR_UserFree(     unsigned long *, BSTR * ); \r\n\r\nunsigned long             __RPC_USER  VARIANT_UserSize(     unsigned long *, unsigned long            , VARIANT * ); \r\nunsigned char * __RPC_USER  VARIANT_UserMarshal(  unsigned long *, unsigned char *, VARIANT * ); \r\nunsigned char * __RPC_USER  VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * ); \r\nvoid                      __RPC_USER  VARIANT_UserFree(     unsigned long *, VARIANT * ); \r\n\r\n/* end of Additional Prototypes */\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n\r\n\r\n"
  },
  {
    "path": "plugins/wmp/wmpBootStrap.cpp",
    "content": "#include \"stdafx.h\"\r\n#include \"wmpBootStrap.h\"\r\n#include \"wmp_scrobbler.h\"\r\n\r\n#define TEST_OR_CONTINUE( function ) if( function != S_OK ) \\\r\n    continue\r\n\r\nenum BootStrapDetails{ ARTIST=0, ALBUMARTIST, ALBUM, TRACK, DURATION, PLAYCOUNT, FILENAME, TIMESTAMP };\r\n\r\nwmpBootStrap::wmpBootStrap( )\r\n             :BootStrap( L\"wmp\" ),\r\n              m_core( NULL )\r\n{\r\n    //Extract the following data\r\n    attributes[L\"Artist\"]             = ARTIST;\r\n\tattributes[L\"AlbumArtist\"]        = ALBUMARTIST;\r\n    attributes[L\"Album\"]              = ALBUM;\r\n    attributes[L\"Title\"]              = TRACK;\r\n    attributes[L\"Duration\"]           = DURATION;\r\n    attributes[L\"UserPlayCount\"]      = PLAYCOUNT;\r\n    attributes[L\"SourceUrl\"]          = FILENAME;\r\n    attributes[L\"UserLastPlayedTime\"] = TIMESTAMP;\r\n}\r\n\r\nwmpBootStrap::~wmpBootStrap(void)\r\n{\r\n}\r\n\r\nbool wmpBootStrap::start()\r\n{\r\n\r\n    ASSERT( m_core );\r\n    \r\n    #define TEST_OR_RETURN( function ) if( function != S_OK ) \\\r\n                                         return false\r\n    CComPtr<IWMPMediaCollection> mediaCollection;\r\n\r\n    TEST_OR_RETURN( m_core->get_mediaCollection( &mediaCollection ) );\r\n\r\n    CComPtr<IWMPPlaylist> allMediaPlaylist;\r\n    \r\n    TEST_OR_RETURN( mediaCollection->getAll( &allMediaPlaylist ) );\r\n\r\n    long mediaCount;\r\n    \r\n    TEST_OR_RETURN( allMediaPlaylist->get_count( &mediaCount ) );\r\n\r\n    CComPtr<IWMPMedia> currentMedia;\r\n        \r\n    setProgressRange( mediaCount );\r\n\r\n    for ( long mediaIndex = 0; mediaIndex < mediaCount; mediaIndex++ )\r\n    {\r\n        //Update progress bar\r\n        setProgressValue( mediaIndex + 1 );\r\n\r\n        while( m_paused){\r\n            WaitForSingleObject( m_pauseStateChanged, INFINITE );\r\n            if(m_cancel) return false;\r\n        }\r\n\r\n        TEST_OR_CONTINUE( allMediaPlaylist->get_item( mediaIndex, &currentMedia ) );\r\n        \r\n        //Get media type\r\n        _bstr_t mediaTypeValue;\r\n        _bstr_t mediaTypeAttrib = _T( \"MediaType\" );\r\n        TEST_OR_CONTINUE( currentMedia->getItemInfo( mediaTypeAttrib.GetBSTR() , &mediaTypeValue.GetBSTR() ) );\r\n\r\n        //Skip any media that is not audio\r\n        std::wstring mediaTypeValueString = mediaTypeValue;\r\n        if( mediaTypeValueString != L\"audio\" )\r\n            continue;\r\n            \r\n        readAttributes( currentMedia );\r\n\r\n    }\r\n    \r\n    completed();\r\n\r\n\r\n    #undef TEST_OR_RETURN\r\n\r\n    return true;\r\n}\r\n\r\nvoid wmpBootStrap::setCore(IWMPCore *core)\r\n{\r\n    m_core = core;\r\n}\r\n\r\nvoid wmpBootStrap::readAttributes( IWMPMedia* media )\r\n{\r\n    BootStrapItem details;\r\n\r\n    //iterate through each attribute\r\n    for( std::map<_bstr_t, BootStrapDetails>::iterator iter = attributes.begin(); iter != attributes.end(); iter++ )\r\n    {\r\n        _bstr_t value;\r\n        BSTR attribute = iter->first;\r\n        TEST_OR_CONTINUE( media->getItemInfo( attribute , &value.GetBSTR() ) );\r\n        \r\n        //escape invalid xml characters\r\n        std::wstring valueStr = value;\r\n        \r\n        switch( iter->second )\r\n        {\r\n            case ARTIST:\r\n                details.artist = valueStr;\r\n                break;\r\n\r\n\t\t\tcase ALBUMARTIST:\r\n                details.albumArtist = valueStr;\r\n                break;\r\n                \r\n            case ALBUM:\r\n                details.album = valueStr;\r\n                break;\r\n                \r\n            case TRACK:\r\n                details.track = valueStr;\r\n                break;\r\n                \r\n            case DURATION:\r\n                details.duration = valueStr;\r\n                break;\r\n                \r\n            case PLAYCOUNT:\r\n                details.playcount = valueStr;\r\n                break;\r\n                \r\n            case FILENAME:\r\n                details.filename = valueStr;\r\n                break;\r\n                \r\n            case TIMESTAMP:\r\n                //TODO: convert string timestamp into epochs.\r\n                //      this requires checking user's default locale\r\n                break;\r\n        }\r\n    }\r\n    appendTrack( &details );\r\n}\r\n\r\n\r\nvoid wmpBootStrap::getDateTimeFormat()\r\n{\r\n    char dateFormat[80];\r\n    char timeFormat[80];\r\n    ::GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, dateFormat, 80 );\r\n    ::GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_STIMEFORMAT, timeFormat, 80 );\r\n    m_dateFormat << dateFormat;\r\n    m_timeFormat << timeFormat;\r\n}\r\n\r\n#undef TEST_OR_CONTINUE"
  },
  {
    "path": "plugins/wmp/wmpBootStrap.h",
    "content": "#ifndef _WMP_BOOTSTRAP_H\r\n#define _WMP_BOOTSTRAP_H\r\n\r\n#include \"Bootstrap.h\"\r\n#include \"wmp.h\"\r\n\r\nclass wmpBootStrap :\r\n    public BootStrap\r\n{\r\npublic:\r\n    wmpBootStrap();\r\n    ~wmpBootStrap(void);\r\n\r\n    void setCore( IWMPCore *pCore );\r\n\r\nprivate:\r\n    IWMPCore *m_core;\r\n    void readAttributes( IWMPMedia* media );\r\n    bool start();\r\n    std::map<_bstr_t, enum BootStrapDetails > attributes;\r\n    void getDateTimeFormat();\r\n\r\n    std::stringstream m_dateFormat;\r\n    std::stringstream m_timeFormat;    \r\n};\r\n\r\n#endif // _WMP_BOOTSTRAP_H"
  },
  {
    "path": "plugins/wmp/wmp_install.iss",
    "content": "; Script generated by the Inno Setup Script Wizard.\r\n; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!\r\n\r\n[CustomMessages]\r\nVersion=2.1.0.8\r\n\r\n[Setup]\r\nOutputBaseFilename=WmpPluginSetup_2.1.0.8\r\n; setup.exe version\r\nVersionInfoVersion=2.1.0.8\r\nVersionInfoTextVersion=2.1.0.8\r\nAppName=Last.fm Windows Media Player Plugin\r\nAppVerName=Last.fm Windows Media Player Plugin {cm:Version}\r\nVersionInfoDescription=Last.fm WMP Plugin Installer\r\nAppPublisher=Last.fm\r\nAppPublisherURL=http://www.last.fm\r\nAppSupportURL=http://www.last.fm\r\nAppUpdatesURL=http://www.last.fm\r\nAppCopyright=Copyright Last.fm Ltd.\r\nDefaultDirName=\"{pf}\\Windows Media Player\\Plugins\"\r\nUsePreviousAppDir=yes\r\nUninstallFilesDir={commonappdata}\\Last.fm\\Client\\UninstWMP\r\nOutputDir=.\r\nCompression=lzma\r\nSolidCompression=yes\r\nDirExistsWarning=no\r\nDisableReadyPage=yes\r\n; Keep this the same across versions, even if they're incompatible. That will ensure\r\n; uninstallation works fine after many upgrades. Can't use GUID as it'll break backward\r\n; compatibility.\r\nAppId=Audioscrobbler Windows Media Player Plugin\r\nCreateUninstallRegKey=no\r\n\r\n[Registry]\r\n; The name of the final subkey here must match the one in plugins.data\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\wmp\"; ValueType: string; ValueName: \"Version\"; ValueData: \"{cm:Version}\"; Flags: uninsdeletekey\r\nRoot: HKLM; Subkey: \"Software\\Last.fm\\Client\\Plugins\\wmp\"; ValueType: string; ValueName: \"Name\"; ValueData: \"Windows Media Player\"; Flags: uninsdeletekey\r\n\r\n[Languages]\r\nName: \"english\"; MessagesFile: \"compiler:Default.isl\"\r\n\r\n[InstallDelete]\r\nType: files; Name: \"{app}\\wmp_scrobbler.dll\"\r\n\r\n[UninstallDelete]\r\n; For legacy reasons (log is now stored in a user-specific location)\r\nType: files; Name: \"{app}\\AudioScrobbler.log.txt\"\r\n\r\n; Try and delete the localappdata log for the case where the user running the uninstaller is the same as the plugin user\r\nType: files; Name: \"{localappdata}\\Last.fm\\Client\\WmpPlugin.log\"\r\n\r\n[Files]\r\nSource: \"Release\\wmp_scrobbler.dll\"; DestDir: \"{app}\"; Flags: ignoreversion\r\n; NOTE: Don't use \"Flags: ignoreversion\" on any shared system files\r\n\r\n[Run]\r\nFilename: \"regsvr32.exe\"; Parameters: \"/s \"\"{app}/wmp_scrobbler.dll\"\"\"\r\n\r\n[UninstallRun]\r\nFilename: \"regsvr32.exe\"; Parameters: \"/u /s \"\"{app}/wmp_scrobbler.dll\"\"\"\r\n\r\n[Code]\r\nprocedure CurStepChanged(CurStep: TSetupStep);\r\nvar\r\n  batfile: String;\r\n  batcontent: String;\r\n  uninstaller: String;\r\n  alreadyAdded: Boolean;\r\n  cmdToAdd: String;\r\nbegin\r\n  if (CurStep = ssPostInstall) then\r\n  begin\r\n    //MsgBox('postinstall', mbInformation, MB_OK);\r\n\r\n    batfile := ExpandConstant('{commonappdata}\\Last.fm\\Client\\uninst2.bat');\r\n    LoadStringFromFile(batfile, batcontent);\r\n    //MsgBox('loaded string: ' + batcontent, mbInformation, MB_OK);\r\n\r\n    uninstaller := ExpandConstant('{uninstallexe}');\r\n    //MsgBox('uninstaller pre-OEM: ' + uninstaller, mbInformation, MB_OK);\r\n\r\n    alreadyAdded := (Pos(uninstaller, batcontent) <> 0);\r\n    if (alreadyAdded = False) then\r\n    begin\r\n      cmdToAdd := uninstaller + #13#10;\r\n      //MsgBox('not present, will add: ' + cmdToAdd, mbInformation, MB_OK);\r\n\r\n      SaveStringToFile(batfile, cmdToAdd, True)\r\n    end;\r\n\r\n  end;\r\n\r\nend;\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.cpp",
    "content": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// wmp_scrobbler.cpp : Implementation of CWmp_scrobbler\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n#include \"stdafx.h\"\r\n#include \"wmp_scrobbler.h\"\r\n#include \"EncodingUtils.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::CWmp_scrobbler\r\n// Constructor\r\n\r\nCWmp_scrobbler::CWmp_scrobbler()\r\n               :m_hWndParent( NULL )\r\n{\r\n    m_dwAdviseCookie = 0;\r\n\tm_bNewSong = FALSE;\r\n\tlstrcpyn(m_szPluginText, AUDIOSCROBBLER_APPNAME, sizeof(m_szPluginText) / sizeof(m_szPluginText[0]));\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::~CWmp_scrobbler\r\n// Destructor\r\n\r\nCWmp_scrobbler::~CWmp_scrobbler()\r\n{\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler:::FinalConstruct\r\n// Called when an plugin is first loaded. Use this function to do one-time\r\n// intializations that could fail instead of doing this in the constructor,\r\n// which cannot return an error.\r\n\r\nHRESULT CWmp_scrobbler::FinalConstruct()\r\n{\r\n\treturn S_OK;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler:::FinalRelease\r\n// Called when a plugin is unloaded. Use this function to free any\r\n// resources allocated in FinalConstruct.\r\n\r\nvoid CWmp_scrobbler::FinalRelease()\r\n{\t\t\r\n\tStopScrobbling();\r\n    ReleaseCore();\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::SetCore\r\n// Set WMP core interface\r\n\r\nHRESULT CWmp_scrobbler::SetCore(IWMPCore *pCore)\r\n{\r\n    HRESULT hr = S_OK;\r\n\r\n    // release any existing WMP core interfaces\r\n    ReleaseCore();\r\n\r\n    // If we get passed a NULL core, this  means\r\n    // that the plugin is being shutdown.\r\n\r\n    if (pCore == NULL)\r\n    {\r\n        return S_OK;\r\n    }\r\n\r\n    m_spCore = pCore;\r\n\r\n    // connect up the event interface\r\n    CComPtr<IConnectionPointContainer>  spConnectionContainer;\r\n\r\n    hr = m_spCore->QueryInterface( &spConnectionContainer );\r\n\r\n    if (SUCCEEDED(hr))\r\n    {\r\n        hr = spConnectionContainer->FindConnectionPoint( __uuidof(IWMPEvents), &m_spConnectionPoint );\r\n    }\r\n\r\n    if (SUCCEEDED(hr))\r\n    {\r\n        hr = m_spConnectionPoint->Advise( GetUnknown(), &m_dwAdviseCookie );\r\n\r\n        if ((FAILED(hr)) || (0 == m_dwAdviseCookie))\r\n        {\r\n            m_spConnectionPoint = NULL;\r\n        }\r\n    }\r\n\r\n    m_wmpBootStrap.setParentHwnd( FindWindow( \"WMPlayerApp\", \"Windows Media Player\" ) );\r\n    char filename[512];\r\n\r\n\t// Get the DLL filename etc\r\n\tGetModuleFileName( _Module.GetModuleInstance(), filename, sizeof( filename ) );\r\n\tCStdString Temp = filename;\r\n\tint pos = Temp.ReverseFind('\\\\');\r\n\t\r\n\tStartScrobbling( Temp.Left( pos + 1 ), _Module.GetModuleInstance() );\r\n    \r\n    if( m_wmpBootStrap.bootStrapRequired() )\r\n    {\r\n        m_wmpBootStrap.setCore( m_spCore );\r\n        m_wmpBootStrap.setScrobSub( &m_Submitter );\r\n        m_wmpBootStrap.setModuleHandle( _Module.GetModuleInstance() );\r\n        m_wmpBootStrap.startBootStrap();\r\n    }\r\n\r\n    return hr;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::ReleaseCore\r\n// Release WMP core interfaces\r\n\r\nvoid CWmp_scrobbler::ReleaseCore()\r\n{\r\n    if (m_spConnectionPoint)\r\n    {\r\n        if (0 != m_dwAdviseCookie)\r\n        {\r\n            m_spConnectionPoint->Unadvise(m_dwAdviseCookie);\r\n            m_dwAdviseCookie = 0;\r\n        }\r\n        m_spConnectionPoint = NULL;\r\n    }\r\n\r\n    if (m_spCore)\r\n    {\r\n        m_spCore = NULL;\r\n    }\r\n}\r\n\r\n\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::DisplayPropertyPage\r\n// Display property page for plugin\r\n\r\nHRESULT CWmp_scrobbler::DisplayPropertyPage(HWND hwndParent)\r\n{\r\n\treturn S_OK;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::GetProperty\r\n// Get plugin property\r\n\r\nHRESULT CWmp_scrobbler::GetProperty(const WCHAR *pwszName, VARIANT *pvarProperty)\r\n{\r\n    if (NULL == pvarProperty)\r\n    {\r\n        return E_POINTER;\r\n    }\r\n\r\n    return E_NOTIMPL;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler::SetProperty\r\n// Set plugin property\r\n\r\nHRESULT CWmp_scrobbler::SetProperty(const WCHAR *pwszName, const VARIANT *pvarProperty)\r\n{\r\n    return E_NOTIMPL;\r\n}\r\n\r\nCStdString\tCWmp_scrobbler::GetPlayerVersion()\r\n{\r\n\tUSES_CONVERSION;\r\n\tCStdString strVersion;\r\n\tCComBSTR bstrVersion;\r\n\r\n\tif(m_spCore)\r\n\t{\r\n        bstrVersion.Empty();\r\n\t\tm_spCore->get_versionInfo(&bstrVersion);\r\n\t\t\r\n\t\tstrVersion = \"Windows Media Player \";\r\n\t\tstrVersion += W2A(bstrVersion);\r\n\t}\r\n\r\n\treturn strVersion;\r\n}\r\n\r\nBOOL CWmp_scrobbler::IsPaused()\r\n{\r\n\tWMPPlayState state;\r\n\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_playState(&state);\r\n\r\n\t\tif(state == wmppsPaused)\r\n\t\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CWmp_scrobbler::IsStopped()\r\n{\r\n\tWMPPlayState state;\r\n\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_playState(&state);\r\n\r\n\t\tif(state == wmppsStopped ||\r\n\t\t   state == wmppsReady ||\r\n           state == wmppsMediaEnded)\r\n        {\r\n\t\t\treturn TRUE;\r\n\t    }\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nBOOL CWmp_scrobbler::IsPlaying()\r\n{\r\n\tWMPPlayState state;\r\n\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_playState(&state);\r\n\r\n\t\tif(state == wmppsPlaying)\r\n\t\t\treturn TRUE;\r\n\t}\r\n\r\n\treturn FALSE;\r\n}\r\n\r\nCStdString CWmp_scrobbler::GetCurrentSongFileName()\r\n{\r\n\tUSES_CONVERSION;\r\n\tCStdString strSong;\r\n\tCComPtr<IWMPMedia> pMedia;\r\n\tBSTR bstrSong;\r\n\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_currentMedia(&pMedia);\r\n\t\t\r\n\t\tif(pMedia != NULL)\r\n\t\t{\r\n\t\t\tpMedia->get_sourceURL(&bstrSong);\r\n\r\n            char buf[1000];\r\n            EncodingUtils::UnicodeToUtf8(\r\n                bstrSong, -1,\r\n                buf, 999);\r\n            \r\n            strSong = buf;\r\n        }\r\n\t}\r\n\r\n\treturn strSong;\r\n}\r\n\r\nint CWmp_scrobbler::GetTrackLength()\r\n{\r\n\tdouble dDuration = -1;\r\n\r\n\tCComPtr<IWMPMedia> pMedia;\r\n\t\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_currentMedia(&pMedia);\r\n\t\t\r\n\t\tif(pMedia != NULL)\r\n\t\t{\r\n\t\t\tpMedia->get_duration(&dDuration);\r\n\t\t}\r\n\t}\r\n\r\n\treturn (int)dDuration;\r\n}\r\n\r\nint CWmp_scrobbler::GetTrackPosition()\r\n{\r\n\tdouble dPosition = -1;\r\n\r\n\tCComPtr<IWMPControls> pControls;\r\n\t\r\n\tif(m_spCore)\r\n\t{\r\n\t\tm_spCore->get_controls(&pControls);\r\n\t\t\r\n\t\tif(pControls != NULL)\r\n\t\t{\r\n\t\t\tpControls->get_currentPosition(&dPosition);\r\n\t\t}\r\n\t}\r\n\r\n\treturn (int)dPosition;\r\n}\r\n\r\nBOOL CWmp_scrobbler::GetCurrentSong(SONG_INFO* pSong)\r\n{\r\n\tUSES_CONVERSION;\r\n\tCComPtr<IWMPMedia> pMedia;\r\n\tCComBSTR bstrValue;\r\n\t//BSTR bstrName;\r\n\tBOOL bRet = FALSE;\r\n\tlong lCount = 0;\r\n\t\r\n\tif(\t(m_spCore) &&\r\n\t\t(pSong != NULL))\r\n\t{\r\n\t\tm_spCore->get_currentMedia(&pMedia);\r\n\t\t\r\n\t\tif(pMedia != NULL)\r\n\t\t{\r\n\t\t\tpMedia->get_attributeCount(&lCount);\r\n\r\n/*\r\n\t\t\tfor(long i = 0; i <= lCount; i++)\r\n\t\t\t{\r\n\t\t\t\tpMedia->getAttributeName(i, &bstrName);\r\n\t\t\t\tbstrValue.Empty();\r\n\t\t\t\tpMedia->getItemInfo(bstrName, &bstrValue);\r\n\t\t\t\tPRINTF(DEBUG_INFO, \"WMPMEDIA\", \"Attribute %s - value %s\", W2A(bstrName), W2A(bstrValue));\r\n\t\t\t}\r\n            // Better check for local/streaming for the future\r\n\t\t\tbstrValue.Empty();\r\n    \t\tpMedia->getItemInfo(L\"type\", &bstrValue);\r\n*/    \t\t\r\n\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Author\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strArtist, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"AlbumArtist\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strAlbumArtist, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n            pMedia->getItemInfo(L\"Title\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strTrack, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Album\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strAlbum, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Genre\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strGenre, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Comment\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strComment, SONG_INFO_FIELD_SIZE);\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"SourceURL\", &bstrValue);\r\n            EncodingUtils::UnicodeToUtf8(bstrValue, -1, pSong->m_strFileName, SONG_INFO_FIELD_SIZE);\r\n\t\t\t\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Duration\", &bstrValue);\r\n\t\t\tpSong->m_nLength = atoi(W2A(bstrValue));\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Track\", &bstrValue);\r\n\t\t\tpSong->m_nTrackNo = atoi(W2A(bstrValue));\r\n            bstrValue.Empty();\r\n\t\t\tpMedia->getItemInfo(L\"Year\", &bstrValue);\r\n\t\t\tpSong->m_nYear = atoi(W2A(bstrValue));\r\n\t\t\t\r\n\t\t\tbRet = TRUE;\r\n\t\t}\t\r\n\t}\r\n\r\n\treturn bRet;\r\n}"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.def",
    "content": "; wmp_scrobbler.def : Declares the module parameters.\r\n\r\nLIBRARY      \"WMP_SCROBBLER.DLL\"\r\n\r\nEXPORTS\r\n\tDllCanUnloadNow     PRIVATE\r\n\tDllGetClassObject   PRIVATE\r\n\tDllRegisterServer   PRIVATE\r\n\tDllUnregisterServer\tPRIVATE\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.dsp",
    "content": "# Microsoft Developer Studio Project File - Name=\"wmp_scrobbler\" - Package Owner=<4>\r\n# Microsoft Developer Studio Generated Build File, Format Version 6.00\r\n# ** DO NOT EDIT **\r\n\r\n# TARGTYPE \"Win32 (x86) Dynamic-Link Library\" 0x0102\r\n\r\nCFG=wmp_scrobbler - Win32 Debug\r\n!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r\n!MESSAGE use the Export Makefile command and run\r\n!MESSAGE \r\n!MESSAGE NMAKE /f \"wmp_scrobbler.mak\".\r\n!MESSAGE \r\n!MESSAGE You can specify a configuration when running NMAKE\r\n!MESSAGE by defining the macro CFG on the command line. For example:\r\n!MESSAGE \r\n!MESSAGE NMAKE /f \"wmp_scrobbler.mak\" CFG=\"wmp_scrobbler - Win32 Debug\"\r\n!MESSAGE \r\n!MESSAGE Possible choices for configuration are:\r\n!MESSAGE \r\n!MESSAGE \"wmp_scrobbler - Win32 Release\" (based on \"Win32 (x86) Dynamic-Link Library\")\r\n!MESSAGE \"wmp_scrobbler - Win32 Debug\" (based on \"Win32 (x86) Dynamic-Link Library\")\r\n!MESSAGE \r\n\r\n# Begin Project\r\n# PROP AllowPerConfigDependencies 0\r\n# PROP Scc_ProjName \"\"$/wmp_scrobbler\", SBAAAAAA\"\r\n# PROP Scc_LocalPath \".\"\r\nCPP=cl.exe\r\nMTL=midl.exe\r\nRSC=rc.exe\r\n\r\n!IF  \"$(CFG)\" == \"wmp_scrobbler - Win32 Release\"\r\n\r\n# PROP BASE Use_MFC 0\r\n# PROP BASE Use_Debug_Libraries 0\r\n# PROP BASE Output_Dir \"Release\"\r\n# PROP BASE Intermediate_Dir \"Release\"\r\n# PROP BASE Target_Dir \"\"\r\n# PROP Use_MFC 0\r\n# PROP Use_Debug_Libraries 0\r\n# PROP Output_Dir \"Release\"\r\n# PROP Intermediate_Dir \"Release\"\r\n# PROP Ignore_Export_Lib 0\r\n# PROP Target_Dir \"\"\r\n# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /Yu\"stdafx.h\" /FD /c\r\n# ADD CPP /nologo /MT /W3 /GX /O2 /I \"../Common\" /D \"WIN32\" /D \"NDEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"_ATL_STATIC_REGISTRY\" /Yu\"stdafx.h\" /FD /c\r\n# ADD BASE MTL /nologo /D \"NDEBUG\" /win32\r\n# ADD MTL /nologo /D \"NDEBUG\" /win32\r\n# ADD BASE RSC /l 0x809 /d \"NDEBUG\"\r\n# ADD RSC /l 0x809 /d \"NDEBUG\"\r\nBSC32=bscmake.exe\r\n# ADD BASE BSC32 /nologo\r\n# ADD BSC32 /nologo\r\nLINK32=link.exe\r\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386\r\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib RASAPI32.LIB ws2_32.lib wininet.lib /nologo /subsystem:windows /dll /debug /machine:I386\r\n# Begin Custom Build - Registering \"$(TargetPath)\"\r\nOutDir=.\\Release\r\nTargetPath=.\\Release\\wmp_scrobbler.dll\r\nInputPath=.\\Release\\wmp_scrobbler.dll\r\nSOURCE=\"$(InputPath)\"\r\n\r\n\"$(OutDir)\\regsvr32.trg\" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\r\n\tregsvr32 /s /c \"$(TargetPath)\" \r\n\techo regsvr32 exec. time > \"$(OutDir)\\regsvr32.trg\" \r\n\t\r\n# End Custom Build\r\n\r\n!ELSEIF  \"$(CFG)\" == \"wmp_scrobbler - Win32 Debug\"\r\n\r\n# PROP BASE Use_MFC 0\r\n# PROP BASE Use_Debug_Libraries 1\r\n# PROP BASE Output_Dir \"Debug\"\r\n# PROP BASE Intermediate_Dir \"Debug\"\r\n# PROP BASE Target_Dir \"\"\r\n# PROP Use_MFC 0\r\n# PROP Use_Debug_Libraries 1\r\n# PROP Output_Dir \"Debug\"\r\n# PROP Intermediate_Dir \"Debug\"\r\n# PROP Ignore_Export_Lib 0\r\n# PROP Target_Dir \"\"\r\n# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /Yu\"stdafx.h\" /FD /GZ /c\r\n# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I \"../Common\" /D \"WIN32\" /D \"_DEBUG\" /D \"_WINDOWS\" /D \"_MBCS\" /D \"_USRDLL\" /D \"_ATL_STATIC_REGISTRY\" /Yu\"stdafx.h\" /FD /GZ /c\r\n# ADD BASE MTL /nologo /D \"_DEBUG\" /win32\r\n# ADD MTL /nologo /D \"_DEBUG\" /win32\r\n# ADD BASE RSC /l 0x809 /d \"_DEBUG\"\r\n# ADD RSC /l 0x809 /d \"_DEBUG\"\r\nBSC32=bscmake.exe\r\n# ADD BASE BSC32 /nologo\r\n# ADD BSC32 /nologo\r\nLINK32=link.exe\r\n# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept\r\n# ADD LINK32 kernel32.lib user32.lib gdi32.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib RASAPI32.LIB ws2_32.lib wininet.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept\r\n# Begin Custom Build - Registering \"$(TargetPath)\"\r\nOutDir=.\\Debug\r\nTargetPath=.\\Debug\\wmp_scrobbler.dll\r\nInputPath=.\\Debug\\wmp_scrobbler.dll\r\nSOURCE=\"$(InputPath)\"\r\n\r\n\"$(OutDir)\\regsvr32.trg\" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\r\n\tregsvr32 /s /c \"$(TargetPath)\" \r\n\techo regsvr32 exec. time > \"$(OutDir)\\regsvr32.trg\" \r\n\t\r\n# End Custom Build\r\n\r\n!ENDIF \r\n\r\n# Begin Target\r\n\r\n# Name \"wmp_scrobbler - Win32 Release\"\r\n# Name \"wmp_scrobbler - Win32 Debug\"\r\n# Begin Group \"Source Files\"\r\n\r\n# PROP Default_Filter \"cpp;c;cxx;rc;def;r;odl;idl;hpj;bat\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdAfx.cpp\r\n# ADD CPP /Yc\"stdafx.h\"\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobbler.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobbler.def\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobbler.rc\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobblerdll.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobblerEvents.cpp\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Header Files\"\r\n\r\n# PROP Default_Filter \"h;hpp;hxx;hm;inl\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\resource.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdAfx.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobbler.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmpplug.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Resource Files\"\r\n\r\n# PROP Default_Filter \"ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\wmp_scrobbler.rgs\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Scrobbler\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\CacheManager.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\CacheManager.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\ConfigDlg.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\ConfigDlg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\IncExcDirDlg.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\IncExcDirDlg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Scrobbler.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Scrobbler.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Submission.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Submission.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=..\\Gen_AudioScrobbler\\SubmissionLog.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=..\\Gen_AudioScrobbler\\SubmissionLog.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"Library\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\comdate.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\dbg.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Dbg.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\DirDialog.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\DirDialog.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\OSVer.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\OSVer.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Registry.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\Registry.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdString.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdStringArray.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\StdStringArray.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\VersionApp.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\VersionApp.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WatchConnection.cpp\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WatchConnection.h\r\n# End Source File\r\n# End Group\r\n# Begin Group \"MD5\"\r\n\r\n# PROP Default_Filter \"\"\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5.c\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Class.cpp\r\n# SUBTRACT CPP /YX /Yc /Yu\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Class.h\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\MD5Global.h\r\n# End Source File\r\n# End Group\r\n# Begin Source File\r\n\r\nSOURCE=.\\audioscrobbler.html\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\AudioScrobbler.nsi\r\n# End Source File\r\n# Begin Source File\r\n\r\nSOURCE=.\\WMP_WhatsNew.txt\r\n# End Source File\r\n# End Target\r\n# End Project\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.h",
    "content": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// wmp_scrobbler.h : Declaration of the CWmp_scrobbler\r\n//\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n#ifndef __WMP_SCROBBLER_H_\r\n#define __WMP_SCROBBLER_H_\r\n\r\n#pragma once\r\n\r\n#include \"RegistryUtils.h\"\r\n#include \"resource.h\"\r\n#include \"wmpplug.h\"\r\n#include \"Scrobbler.h\"\r\n#include \"wmpBootStrap.h\"\r\n\r\n#define AUDIOSCROBBLER_APPNAME\t\t\t\t\t    \"Audioscrobbler Windows Media Player plugin\"\r\n#define AUDIOSCROBBLER_APPID\t\t\t\t\t\t\"wmp\"\r\n#define AUDIOSCROBBLER_REGKEY\t\t\t\t\t\t\"Software\\\\Audioscrobbler WMP Plugin\\\\\"\r\n\r\n// {E7C0F450-9B76-4481-B3DF-B3447B383762}\r\nDEFINE_GUID(CLSID_Wmp_scrobbler, 0xE7C0F450, 0x9B76, 0x4481, 0xB3, 0xDF, 0xB3, 0x44, 0x7B, 0x38, 0x37, 0x62);\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// CWmp_scrobbler\r\nclass ATL_NO_VTABLE CWmp_scrobbler : \r\n    public CComObjectRootEx<CComSingleThreadModel>,\r\n    public CComCoClass<CWmp_scrobbler, &CLSID_Wmp_scrobbler>,\r\n    public IWMPEvents,\r\n    public IWMPPluginUI,\r\n\tpublic CScrobbler\r\n{\r\npublic:\r\n    CWmp_scrobbler();\r\n    ~CWmp_scrobbler();\r\n\r\nDECLARE_REGISTRY_RESOURCEID(IDR_WMP_SCROBBLER)\r\n\r\nDECLARE_PROTECT_FINAL_CONSTRUCT()\r\n\r\nBEGIN_COM_MAP(CWmp_scrobbler)\r\n    COM_INTERFACE_ENTRY(IWMPEvents)\r\n    COM_INTERFACE_ENTRY(IWMPPluginUI)\r\nEND_COM_MAP()\r\n\r\n\r\n\t\t// SCROBBLER INTERFACE\r\n\t\tvirtual \tCStdString\tGetAppName(){ return AUDIOSCROBBLER_APPNAME;}\r\n\t\tvirtual \tCStdString\tGetAppId(){ return AUDIOSCROBBLER_APPID;}\r\n\t\tvirtual \tCStdString\tGetRegKey(){ return AUDIOSCROBBLER_REGKEY;}\r\n\t\tvirtual\t\tCStdString\tGetPlayerVersion();\t// Returns the player specific version string\r\n\t\tvirtual\t\tBOOL\t\tIsPlaying();\r\n\t\tvirtual\t\tBOOL\t\tIsPaused();\r\n\t\tvirtual\t\tBOOL\t\tIsStopped();\r\n\t\tvirtual\t\tCStdString\tGetCurrentSongFileName();\r\n\t\tvirtual\t\tint\t\t\tGetTrackLength();\r\n\t\tvirtual\t\tint\t\t\tGetTrackPosition();\r\n\t\tvirtual\t\tBOOL\t    GetCurrentSong(SONG_INFO* pSong);\r\n\t\tvirtual\t\tHWND\t\tGetParentWnd(){return m_hWndParent;}\r\n//\t\tBOOL\t\t\tSupportedFileType(CStdString strPath);\r\n\r\n\t\tHWND\t\tm_hWndParent;\r\n\t\tBOOL\t\tm_bNewSong;\r\n\r\n    // CComCoClass methods\r\n    HRESULT FinalConstruct();\r\n    void    FinalRelease();\r\n\r\n    // IWMPPluginUI methods\r\n    STDMETHODIMP SetCore(IWMPCore *pCore);\r\n    STDMETHODIMP Create(HWND hwndParent, HWND *phwndWindow) { return E_NOTIMPL; }\r\n    STDMETHODIMP Destroy() { return E_NOTIMPL; }\r\n    STDMETHODIMP TranslateAccelerator(LPMSG lpmsg) { return E_NOTIMPL; }\r\n    STDMETHODIMP DisplayPropertyPage(HWND hwndParent);\r\n    STDMETHODIMP GetProperty(const WCHAR *pwszName, VARIANT *pvarProperty);\r\n    STDMETHODIMP SetProperty(const WCHAR *pwszName, const VARIANT *pvarProperty);\r\n\r\n    // IWMPEvents methods\r\n    void STDMETHODCALLTYPE OpenStateChange( long NewState );\r\n    void STDMETHODCALLTYPE PlayStateChange( long NewState );\r\n    void STDMETHODCALLTYPE AudioLanguageChange( long LangID );\r\n    void STDMETHODCALLTYPE StatusChange();\r\n    void STDMETHODCALLTYPE ScriptCommand( BSTR scType, BSTR Param );\r\n    void STDMETHODCALLTYPE NewStream();\r\n    void STDMETHODCALLTYPE Disconnect( long Result );\r\n    void STDMETHODCALLTYPE Buffering( VARIANT_BOOL Start );\r\n    void STDMETHODCALLTYPE Error();\r\n    void STDMETHODCALLTYPE Warning( long WarningType, long Param, BSTR Description );\r\n    void STDMETHODCALLTYPE EndOfStream( long Result );\r\n    void STDMETHODCALLTYPE PositionChange( double oldPosition, double newPosition);\r\n    void STDMETHODCALLTYPE MarkerHit( long MarkerNum );\r\n    void STDMETHODCALLTYPE DurationUnitChange( long NewDurationUnit );\r\n    void STDMETHODCALLTYPE CdromMediaChange( long CdromNum );\r\n    void STDMETHODCALLTYPE PlaylistChange( IDispatch * Playlist, WMPPlaylistChangeEventType change );\r\n    void STDMETHODCALLTYPE CurrentPlaylistChange( WMPPlaylistChangeEventType change );\r\n    void STDMETHODCALLTYPE CurrentPlaylistItemAvailable( BSTR bstrItemName );\r\n    void STDMETHODCALLTYPE MediaChange( IDispatch * Item );\r\n    void STDMETHODCALLTYPE CurrentMediaItemAvailable( BSTR bstrItemName );\r\n    void STDMETHODCALLTYPE CurrentItemChange( IDispatch *pdispMedia);\r\n    void STDMETHODCALLTYPE MediaCollectionChange();\r\n    void STDMETHODCALLTYPE MediaCollectionAttributeStringAdded( BSTR bstrAttribName,  BSTR bstrAttribVal );\r\n    void STDMETHODCALLTYPE MediaCollectionAttributeStringRemoved( BSTR bstrAttribName,  BSTR bstrAttribVal );\r\n    void STDMETHODCALLTYPE MediaCollectionAttributeStringChanged( BSTR bstrAttribName, BSTR bstrOldAttribVal, BSTR bstrNewAttribVal);\r\n    void STDMETHODCALLTYPE PlaylistCollectionChange();\r\n    void STDMETHODCALLTYPE PlaylistCollectionPlaylistAdded( BSTR bstrPlaylistName);\r\n    void STDMETHODCALLTYPE PlaylistCollectionPlaylistRemoved( BSTR bstrPlaylistName);\r\n    void STDMETHODCALLTYPE PlaylistCollectionPlaylistSetAsDeleted( BSTR bstrPlaylistName, VARIANT_BOOL varfIsDeleted);\r\n    void STDMETHODCALLTYPE ModeChange( BSTR ModeName, VARIANT_BOOL NewValue);\r\n    void STDMETHODCALLTYPE MediaError( IDispatch * pMediaObject);\r\n    void STDMETHODCALLTYPE OpenPlaylistSwitch( IDispatch *pItem );\r\n    void STDMETHODCALLTYPE DomainChange( BSTR strDomain);\r\n    void STDMETHODCALLTYPE SwitchedToPlayerApplication();\r\n    void STDMETHODCALLTYPE SwitchedToControl();\r\n    void STDMETHODCALLTYPE PlayerDockedStateChange();\r\n    void STDMETHODCALLTYPE PlayerReconnect();\r\n    void STDMETHODCALLTYPE Click( short nButton, short nShiftState, long fX, long fY );\r\n    void STDMETHODCALLTYPE DoubleClick( short nButton, short nShiftState, long fX, long fY );\r\n    void STDMETHODCALLTYPE KeyDown( short nKeyCode, short nShiftState );\r\n    void STDMETHODCALLTYPE KeyPress( short nKeyAscii );\r\n    void STDMETHODCALLTYPE KeyUp( short nKeyCode, short nShiftState );\r\n    void STDMETHODCALLTYPE MouseDown( short nButton, short nShiftState, long fX, long fY );\r\n    void STDMETHODCALLTYPE MouseMove( short nButton, short nShiftState, long fX, long fY );\r\n    void STDMETHODCALLTYPE MouseUp( short nButton, short nShiftState, long fX, long fY );\r\n\r\n    TCHAR        m_szPluginText[MAX_PATH];\r\n\r\nprivate:\r\n    void         ReleaseCore();\r\n\r\n    CComPtr<IWMPCore>           m_spCore;\r\n    CComPtr<IConnectionPoint>   m_spConnectionPoint;\r\n    DWORD                       m_dwAdviseCookie;\r\n    wmpBootStrap                m_wmpBootStrap;\r\n};\r\n\r\n#endif //__WMP_SCROBBLER_H_\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.rc",
    "content": "// Microsoft Visual C++ generated resource script.\r\n//\r\n#include \"resource.h\"\r\n\r\n#define APSTUDIO_READONLY_SYMBOLS\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 2 resource.\r\n//\r\n#include \"afxres.h\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#undef APSTUDIO_READONLY_SYMBOLS\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// English (U.S.) resources\r\n\r\n#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n#ifdef _WIN32\r\nLANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US\r\n#pragma code_page(1252)\r\n#endif //_WIN32\r\n\r\n#ifdef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// TEXTINCLUDE\r\n//\r\n\r\n1 TEXTINCLUDE \r\nBEGIN\r\n    \"resource.h\\0\"\r\nEND\r\n\r\n2 TEXTINCLUDE \r\nBEGIN\r\n    \"#include \"\"afxres.h\"\"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n3 TEXTINCLUDE \r\nBEGIN\r\n    \"\\r\\n\"\r\n    \"\\0\"\r\nEND\r\n\r\n#endif    // APSTUDIO_INVOKED\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// REGISTRY\r\n//\r\n\r\nIDR_WMP_SCROBBLER       REGISTRY                \"wmp_scrobbler.rgs\"\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Version\r\n//\r\n\r\nVS_VERSION_INFO VERSIONINFO\r\n FILEVERSION 2,1,0,8\r\n PRODUCTVERSION 2,1,0,8\r\n FILEFLAGSMASK 0x3fL\r\n#ifdef _DEBUG\r\n FILEFLAGS 0x9L\r\n#else\r\n FILEFLAGS 0x8L\r\n#endif\r\n FILEOS 0x4L\r\n FILETYPE 0x2L\r\n FILESUBTYPE 0x0L\r\nBEGIN\r\n    BLOCK \"StringFileInfo\"\r\n    BEGIN\r\n        BLOCK \"000904b0\"\r\n        BEGIN\r\n            VALUE \"Comments\", \"http://www.last.fm\"\r\n            VALUE \"CompanyName\", \"Last.fm\"\r\n            VALUE \"FileDescription\", \"Last.fm Windows Media Player Plugin\"\r\n            VALUE \"FileVersion\", \"2, 1, 0, 8\"\r\n            VALUE \"InternalName\", \"wmp_scrobbler\"\r\n            VALUE \"LegalCopyright\", \"Copyright (C) 2007\"\r\n            VALUE \"OriginalFilename\", \"wmp_scrobbler.dll\"\r\n            VALUE \"PrivateBuild\", \"624\"\r\n            VALUE \"ProductName\", \"Last.fm Windows Media Player Plugin\"\r\n            VALUE \"ProductVersion\", \"2, 1, 0, 8\"\r\n        END\r\n    END\r\n    BLOCK \"VarFileInfo\"\r\n    BEGIN\r\n        VALUE \"Translation\", 0x9, 1200\r\n    END\r\nEND\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// String Table\r\n//\r\n\r\nSTRINGTABLE \r\nBEGIN\r\n    IDS_FRIENDLYNAME        \"Last.fm Plugin\"\r\n    IDS_DESCRIPTION         \"The Last.fm Windows Media Player Plugin submits your played tracks to your Last.fm profile via the Last.fm application.\"\r\nEND\r\n\r\n#endif    // English (U.S.) resources\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n\r\n\r\n#ifndef APSTUDIO_INVOKED\r\n/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// Generated from the TEXTINCLUDE 3 resource.\r\n//\r\n\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n#endif    // not APSTUDIO_INVOKED\r\n\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.rgs",
    "content": "HKCR\r\n{\r\n\tNoRemove CLSID\r\n\t{\r\n\t\tForceRemove {E7C0F450-9B76-4481-B3DF-B3447B383762} = s 'Wmp_scrobbler Class'\r\n\t\t{\r\n\t\t\tInprocServer32 = s '%MODULE%'\r\n\t\t\t{\r\n\t\t\t\tval ThreadingModel = s 'Apartment'\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\nHKEY_LOCAL_MACHINE\r\n{\r\n    NoRemove SOFTWARE\r\n    {\r\n        NoRemove Microsoft\r\n        {\r\n            NoRemove MediaPlayer\r\n            {\r\n                NoRemove UIPlugins\r\n                {\r\n                    ForceRemove {E7C0F450-9B76-4481-B3DF-B3447B383762}\r\n                    {\r\n                        val FriendlyName = s 'res://wmp_scrobbler.dll/RT_STRING/#102'\r\n                        val Description = s 'res://wmp_scrobbler.dll/RT_STRING/#103'\r\n                        val Capabilities = d '3758096385'\r\n                    }\r\n                }\r\n            }\r\n        }\r\n    }\r\n}\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobbler.vcxproj",
    "content": "﻿<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project DefaultTargets=\"Build\" ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n  <ItemGroup Label=\"ProjectConfigurations\">\n    <ProjectConfiguration Include=\"Debug|Win32\">\n      <Configuration>Debug</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Release|Win32\">\n      <Configuration>Release</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n    <ProjectConfiguration Include=\"Template|Win32\">\n      <Configuration>Template</Configuration>\n      <Platform>Win32</Platform>\n    </ProjectConfiguration>\n  </ItemGroup>\n  <PropertyGroup Label=\"Globals\">\n    <ProjectGuid>{CF8AD3FB-2EAF-4A9D-8619-F6701B9A9BDE}</ProjectGuid>\n    <RootNamespace>wmp_scrobbler</RootNamespace>\n    <Keyword>AtlProj</Keyword>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseOfMfc>false</UseOfMfc>\n    <UseOfAtl>Static</UseOfAtl>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <PropertyGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"Configuration\">\n    <ConfigurationType>DynamicLibrary</ConfigurationType>\n    <UseOfMfc>false</UseOfMfc>\n    <UseOfAtl>Static</UseOfAtl>\n    <CharacterSet>Unicode</CharacterSet>\n  </PropertyGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.props\" />\n  <ImportGroup Label=\"ExtensionSettings\">\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n    <Import Project=\"$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props\" />\n  </ImportGroup>\n  <ImportGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\" Label=\"PropertySheets\">\n    <Import Project=\"$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props\" Condition=\"exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />\n    <Import Project=\"$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props\" />\n  </ImportGroup>\n  <PropertyGroup Label=\"UserMacros\" />\n  <PropertyGroup>\n    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">.\\Release\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">.\\Release\\</IntDir>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">false</LinkIncremental>\n    <OutDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">.\\Debug\\</OutDir>\n    <IntDir Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">.\\Debug\\</IntDir>\n    <CustomBuildAfterTargets Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">PreBuildEvent</CustomBuildAfterTargets>\n    <LinkIncremental Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">false</LinkIncremental>\n  </PropertyGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n    <PreBuildEvent>\n      <Message>Incrementing build number</Message>\n      <Command>\n      </Command>\n    </PreBuildEvent>\n    <CustomBuildStep>\n      <Message>Registering \"$(TargetPath)\"</Message>\n      <Command>regsvr32 /s /c \"$(TargetPath)\"\necho regsvr32 exec. time &gt; \"$(OutDir)regsvr32.trg\"\n</Command>\n      <Outputs>$(OutDir)regsvr32.trg;%(Outputs)</Outputs>\n    </CustomBuildStep>\n    <Midl>\n      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <TargetEnvironment>Win32</TargetEnvironment>\n      <TypeLibraryName>.\\Release/wmp_scrobbler.tlb</TypeLibraryName>\n      <HeaderFileName>\n      </HeaderFileName>\n    </Midl>\n    <ClCompile>\n      <Optimization>MinSpace</Optimization>\n      <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>\n      <AdditionalIncludeDirectories>../ScrobSub;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>WINVER=0x0500;_WIN32_WINNT=0x0500;WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <StringPooling>true</StringPooling>\n      <RuntimeLibrary>MultiThreaded</RuntimeLibrary>\n      <FunctionLevelLinking>true</FunctionLevelLinking>\n      <PrecompiledHeader>Use</PrecompiledHeader>\n      <PrecompiledHeaderFile>stdafx.h</PrecompiledHeaderFile>\n      <PrecompiledHeaderOutputFile>.\\Release/wmp_scrobbler.pch</PrecompiledHeaderOutputFile>\n      <AssemblerListingLocation>.\\Release/</AssemblerListingLocation>\n      <ObjectFileName>.\\Release/</ObjectFileName>\n      <ProgramDataBaseFileName>.\\Release/</ProgramDataBaseFileName>\n      <WarningLevel>Level3</WarningLevel>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <CompileAs>Default</CompileAs>\n    </ClCompile>\n    <ResourceCompile>\n      <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <Culture>0x0809</Culture>\n    </ResourceCompile>\n    <Link>\n      <AdditionalDependencies>RASAPI32.LIB;ws2_32.lib;wininet.lib;%(AdditionalDependencies)</AdditionalDependencies>\n      <OutputFile>.\\Release/wmp_scrobbler.dll</OutputFile>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <ModuleDefinitionFile>.\\wmp_scrobbler.def</ModuleDefinitionFile>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <ProgramDatabaseFile>.\\Release/wmp_scrobbler.pdb</ProgramDatabaseFile>\n      <SubSystem>Windows</SubSystem>\n      <RandomizedBaseAddress>false</RandomizedBaseAddress>\n      <DataExecutionPrevention>\n      </DataExecutionPrevention>\n      <ImportLibrary>.\\Release/wmp_scrobbler.lib</ImportLibrary>\n      <TargetMachine>MachineX86</TargetMachine>\n    </Link>\n    <PostBuildEvent>\n      <Message>Registering plugin</Message>\n      <Command>regsvr32 /s /c \"$(TargetPath)\"</Command>\n    </PostBuildEvent>\n  </ItemDefinitionGroup>\n  <ItemDefinitionGroup Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n    <Midl>\n      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <TargetEnvironment>Win32</TargetEnvironment>\n      <TypeLibraryName>.\\Debug/wmp_scrobbler.tlb</TypeLibraryName>\n      <HeaderFileName>\n      </HeaderFileName>\n    </Midl>\n    <ResourceCompile>\n      <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <Culture>0x0809</Culture>\n      <ShowProgress>true</ShowProgress>\n      <ResourceOutputFileName>$(IntDir)%(Filename).res</ResourceOutputFileName>\n    </ResourceCompile>\n    <ClCompile>\n      <Optimization>Disabled</Optimization>\n      <AdditionalIncludeDirectories>../ScrobSub;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>\n      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>\n      <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>\n      <PrecompiledHeader>Use</PrecompiledHeader>\n      <PrecompiledHeaderFile>stdafx.h</PrecompiledHeaderFile>\n      <PrecompiledHeaderOutputFile>.\\Debug/wmp_scrobbler.pch</PrecompiledHeaderOutputFile>\n      <AssemblerListingLocation>.\\Debug/</AssemblerListingLocation>\n      <ObjectFileName>.\\Debug/</ObjectFileName>\n      <ProgramDataBaseFileName>.\\Debug/</ProgramDataBaseFileName>\n      <WarningLevel>Level3</WarningLevel>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>\n      <CompileAs>Default</CompileAs>\n    </ClCompile>\n    <Link>\n      <AdditionalDependencies>RASAPI32.LIB;ws2_32.lib;wininet.lib;%(AdditionalDependencies)</AdditionalDependencies>\n      <OutputFile>C:\\Program Files\\Windows Media Player\\Plugins\\wmp_scrobbler.dll</OutputFile>\n      <SuppressStartupBanner>true</SuppressStartupBanner>\n      <ModuleDefinitionFile>.\\wmp_scrobbler.def</ModuleDefinitionFile>\n      <GenerateDebugInformation>true</GenerateDebugInformation>\n      <ProgramDatabaseFile>.\\Debug/wmp_scrobbler.pdb</ProgramDatabaseFile>\n      <SubSystem>Windows</SubSystem>\n      <RandomizedBaseAddress>false</RandomizedBaseAddress>\n      <DataExecutionPrevention>\n      </DataExecutionPrevention>\n      <ImportLibrary>.\\Debug/wmp_scrobbler.lib</ImportLibrary>\n      <TargetMachine>MachineX86</TargetMachine>\n    </Link>\n    <PostBuildEvent>\n      <Message>Registering plugin</Message>\n      <Command>regsvr32 /s /c \"$(TargetPath)\"</Command>\n    </PostBuildEvent>\n  </ItemDefinitionGroup>\n  <ItemGroup>\n    <ClCompile Include=\"..\\..\\common\\c++\\win\\scrobSubPipeName.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"StdAfx.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Create</PrecompiledHeader>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">Create</PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"wmp_scrobbler.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n    </ClCompile>\n    <ClCompile Include=\"wmp_scrobblerdll.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n    </ClCompile>\n    <ClCompile Include=\"wmp_scrobblerEvents.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n    </ClCompile>\n    <ClCompile Include=\"wmpBootStrap.cpp\" />\n    <ClCompile Include=\"Scrobbler.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n    </ClCompile>\n    <ClCompile Include=\"..\\scrobsub\\BlockingClient.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"..\\scrobsub\\Bootstrap.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"..\\scrobsub\\EncodingUtils.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"..\\scrobsub\\RegistryUtils.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"..\\scrobsub\\ScrobSubmitter.cpp\">\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"dbg.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"OSVer.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n    <ClCompile Include=\"StdStringArray.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n    </ClCompile>\n    <ClCompile Include=\"VersionApp.cpp\">\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">Disabled</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">WIN32;_DEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <BasicRuntimeChecks Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">EnableFastChecks</BasicRuntimeChecks>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Debug|Win32'\">\n      </PrecompiledHeader>\n      <Optimization Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">MaxSpeed</Optimization>\n      <AdditionalIncludeDirectories Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\n      <PreprocessorDefinitions Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">WIN32;NDEBUG;_WINDOWS;_MBCS;_USRDLL;_ATL_STATIC_REGISTRY</PreprocessorDefinitions>\n      <PrecompiledHeader Condition=\"'$(Configuration)|$(Platform)'=='Release|Win32'\">\n      </PrecompiledHeader>\n    </ClCompile>\n  </ItemGroup>\n  <ItemGroup>\n    <None Include=\"wmp_scrobbler.def\" />\n    <None Include=\"wmp_scrobbler.rgs\" />\n    <None Include=\"WhatsNew.txt\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ResourceCompile Include=\"wmp_scrobbler.rc\" />\n    <ResourceCompile Include=\"..\\scrobsub\\Bootstrap.rc\" />\n  </ItemGroup>\n  <ItemGroup>\n    <ClInclude Include=\"resource.h\" />\n    <ClInclude Include=\"resource1.h\" />\n    <ClInclude Include=\"..\\..\\ScrobSub\\resource1.h\" />\n    <ClInclude Include=\"StdAfx.h\" />\n    <ClInclude Include=\"wmp.h\" />\n    <ClInclude Include=\"wmp_scrobbler.h\" />\n    <ClInclude Include=\"wmpBootStrap.h\" />\n    <ClInclude Include=\"wmpplug.h\" />\n    <ClInclude Include=\"Scrobbler.h\" />\n    <ClInclude Include=\"..\\scrobsub\\BlockingClient.h\" />\n    <ClInclude Include=\"..\\scrobsub\\Bootstrap.h\" />\n    <ClInclude Include=\"..\\scrobsub\\EncodingUtils.h\" />\n    <ClInclude Include=\"..\\scrobsub\\RegistryUtils.h\" />\n    <ClInclude Include=\"..\\scrobsub\\resource.h\" />\n    <ClInclude Include=\"..\\scrobsub\\resource1.h\" />\n    <ClInclude Include=\"..\\scrobsub\\ScrobSubmitter.h\" />\n    <ClInclude Include=\"..\\scrobsub\\StdString.h\" />\n    <ClInclude Include=\"comdate.h\" />\n    <ClInclude Include=\"Dbg.h\" />\n    <ClInclude Include=\"OSVer.h\" />\n    <ClInclude Include=\"StdString.h\" />\n    <ClInclude Include=\"StdStringArray.h\" />\n    <ClInclude Include=\"VersionApp.h\" />\n  </ItemGroup>\n  <Import Project=\"$(VCTargetsPath)\\Microsoft.Cpp.targets\" />\n  <ImportGroup Label=\"ExtensionTargets\">\n  </ImportGroup>\n  <ProjectExtensions>\n    <VisualStudio>\n      <UserProperties RESOURCE_FILE=\"wmp_scrobbler.rc\" />\n    </VisualStudio>\n  </ProjectExtensions>\n</Project>"
  },
  {
    "path": "plugins/wmp/wmp_scrobblerEvents.cpp",
    "content": "/////////////////////////////////////////////////////////////////////////////\r\n//\r\n// wmp_scrobblerEvents.cpp : Implementation of CWmp_scrobbler events\r\n//\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n//\r\n/////////////////////////////////////////////////////////////////////////////\r\n\r\n#include \"stdafx.h\"\r\n#include \"wmp_scrobbler.h\"\r\n\r\nvoid CWmp_scrobbler::OpenStateChange( long NewState )\r\n{\r\n    switch (NewState)\r\n    {\r\n    case wmposUndefined:\r\n        break;\r\n\tcase wmposPlaylistChanging:\r\n        break;\r\n\tcase wmposPlaylistLocating:\r\n        break;\r\n\tcase wmposPlaylistConnecting:\r\n        break;\r\n\tcase wmposPlaylistLoading:\r\n        break;\r\n\tcase wmposPlaylistOpening:\r\n        break;\r\n\tcase wmposPlaylistOpenNoMedia:\r\n        break;\r\n\tcase wmposPlaylistChanged:\r\n        break;\r\n\tcase wmposMediaChanging:\r\n        break;\r\n\tcase wmposMediaLocating:\r\n        break;\r\n\tcase wmposMediaConnecting:\r\n        break;\r\n\tcase wmposMediaLoading:\r\n        break;\r\n\tcase wmposMediaOpening:\r\n        break;\r\n\tcase wmposMediaOpen:\r\n        break;\r\n\tcase wmposBeginCodecAcquisition:\r\n        break;\r\n\tcase wmposEndCodecAcquisition:\r\n        break;\r\n\tcase wmposBeginLicenseAcquisition:\r\n        break;\r\n\tcase wmposEndLicenseAcquisition:\r\n        break;\r\n\tcase wmposBeginIndividualization:\r\n        break;\r\n\tcase wmposEndIndividualization:\r\n        break;\r\n\tcase wmposMediaWaiting:\r\n        break;\r\n\tcase wmposOpeningUnknownURL:\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid CWmp_scrobbler::PlayStateChange( long NewState )\r\n{\r\n    switch (NewState)\r\n    {\r\n    case wmppsUndefined:\r\n        break;\r\n\tcase wmppsStopped:\r\n\t\t\t\tm_bNewSong = FALSE;\r\n        break;\r\n\tcase wmppsPaused:\r\n        break;\r\n\tcase wmppsPlaying:\r\n\t\t\t\tif(!m_bNewSong)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_bNewSong = TRUE;\r\n\t\t\t\t\tOnTrackPlay();\r\n\t\t\t\t}\r\n        break;\r\n\tcase wmppsScanForward:\r\n        break;\r\n\tcase wmppsScanReverse:\r\n        break;\r\n\tcase wmppsBuffering:\r\n        break;\r\n\tcase wmppsWaiting:\r\n        break;\r\n\tcase wmppsMediaEnded:\r\n\t\t\t\tm_bNewSong = FALSE;\r\n        break;\r\n\tcase wmppsTransitioning:\r\n\t\t\t\tm_bNewSong = FALSE;\r\n        break;\r\n\tcase wmppsReady:\r\n        break;\r\n\tcase wmppsReconnecting:\r\n        break;\r\n\tcase wmppsLast:\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid CWmp_scrobbler::AudioLanguageChange( long LangID )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::StatusChange()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::ScriptCommand( BSTR scType, BSTR Param )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::NewStream()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::Disconnect( long Result )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::Buffering( VARIANT_BOOL Start )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::Error()\r\n{\r\n    CComPtr<IWMPError>      spError;\r\n    CComPtr<IWMPErrorItem>  spErrorItem;\r\n    HRESULT                 dwError = S_OK;\r\n    HRESULT                 hr = S_OK;\r\n\r\n    if (m_spCore)\r\n    {\r\n        hr = m_spCore->get_error(&spError);\r\n\r\n        if (SUCCEEDED(hr))\r\n        {\r\n            hr = spError->get_item(0, &spErrorItem);\r\n        }\r\n\r\n        if (SUCCEEDED(hr))\r\n        {\r\n            hr = spErrorItem->get_errorCode( (long *) &dwError );\r\n        }\r\n    }\r\n\r\n\t\tPRINTF(DEBUG_INFO, \"CWmp_scrobbler::Error\", \"Error code is %d\", dwError );\r\n}\r\n\r\nvoid CWmp_scrobbler::Warning( long WarningType, long Param, BSTR Description )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::EndOfStream( long Result )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PositionChange( double oldPosition, double newPosition)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MarkerHit( long MarkerNum )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::DurationUnitChange( long NewDurationUnit )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::CdromMediaChange( long CdromNum )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlaylistChange( IDispatch * Playlist, WMPPlaylistChangeEventType change )\r\n{\r\n    switch (change)\r\n    {\r\n    case wmplcUnknown:\r\n        break;\r\n\tcase wmplcClear:\r\n        break;\r\n\tcase wmplcInfoChange:\r\n        break;\r\n\tcase wmplcMove:\r\n        break;\r\n\tcase wmplcDelete:\r\n        break;\r\n\tcase wmplcInsert:\r\n        break;\r\n\tcase wmplcAppend:\r\n        break;\r\n\tcase wmplcPrivate:\r\n        break;\r\n\tcase wmplcNameChange:\r\n        break;\r\n\tcase wmplcMorph:\r\n        break;\r\n\tcase wmplcSort:\r\n        break;\r\n\tcase wmplcLast:\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid CWmp_scrobbler::CurrentPlaylistChange( WMPPlaylistChangeEventType change )\r\n{\r\n    switch (change)\r\n    {\r\n    case wmplcUnknown:\r\n        break;\r\n\tcase wmplcClear:\r\n        break;\r\n\tcase wmplcInfoChange:\r\n        break;\r\n\tcase wmplcMove:\r\n        break;\r\n\tcase wmplcDelete:\r\n        break;\r\n\tcase wmplcInsert:\r\n        break;\r\n\tcase wmplcAppend:\r\n        break;\r\n\tcase wmplcPrivate:\r\n        break;\r\n\tcase wmplcNameChange:\r\n        break;\r\n\tcase wmplcMorph:\r\n        break;\r\n\tcase wmplcSort:\r\n        break;\r\n\tcase wmplcLast:\r\n        break;\r\n    default:\r\n        break;\r\n    }\r\n}\r\n\r\nvoid CWmp_scrobbler::CurrentPlaylistItemAvailable( BSTR bstrItemName )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaChange( IDispatch * Item )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::CurrentMediaItemAvailable( BSTR bstrItemName )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::CurrentItemChange( IDispatch *pdispMedia)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaCollectionChange()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaCollectionAttributeStringAdded( BSTR bstrAttribName,  BSTR bstrAttribVal )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaCollectionAttributeStringRemoved( BSTR bstrAttribName,  BSTR bstrAttribVal )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaCollectionAttributeStringChanged( BSTR bstrAttribName, BSTR bstrOldAttribVal, BSTR bstrNewAttribVal)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlaylistCollectionChange()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlaylistCollectionPlaylistAdded( BSTR bstrPlaylistName)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlaylistCollectionPlaylistRemoved( BSTR bstrPlaylistName)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlaylistCollectionPlaylistSetAsDeleted( BSTR bstrPlaylistName, VARIANT_BOOL varfIsDeleted)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::ModeChange( BSTR ModeName, VARIANT_BOOL NewValue)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MediaError( IDispatch * pMediaObject)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::OpenPlaylistSwitch( IDispatch *pItem )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::DomainChange( BSTR strDomain)\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::SwitchedToPlayerApplication()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::SwitchedToControl()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlayerDockedStateChange()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::PlayerReconnect()\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::Click( short nButton, short nShiftState, long fX, long fY )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::DoubleClick( short nButton, short nShiftState, long fX, long fY )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::KeyDown( short nKeyCode, short nShiftState )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::KeyPress( short nKeyAscii )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::KeyUp( short nKeyCode, short nShiftState )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MouseDown( short nButton, short nShiftState, long fX, long fY )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MouseMove( short nButton, short nShiftState, long fX, long fY )\r\n{\r\n}\r\n\r\nvoid CWmp_scrobbler::MouseUp( short nButton, short nShiftState, long fX, long fY )\r\n{\r\n}\r\n"
  },
  {
    "path": "plugins/wmp/wmp_scrobblerdll.cpp",
    "content": "// wmp_scrobblerdll.cpp : Implementation of DLL Exports.\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n\r\n#include \"stdafx.h\"\r\n#include \"resource.h\"\r\n#include <initguid.h>\r\n\r\n#include \"wmp_scrobbler.h\"\r\n\r\n\r\nCComModule _Module;\r\n\r\nBEGIN_OBJECT_MAP(ObjectMap)\r\nOBJECT_ENTRY(CLSID_Wmp_scrobbler, CWmp_scrobbler)\r\nEND_OBJECT_MAP()\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// DLL Entry Point\r\n\r\nextern \"C\"\r\nBOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)\r\n{\r\n    if (dwReason == DLL_PROCESS_ATTACH)\r\n    {\r\n        _Module.Init(ObjectMap, hInstance);\r\n        DisableThreadLibraryCalls(hInstance);\r\n    }\r\n    else if (dwReason == DLL_PROCESS_DETACH)\r\n        _Module.Term();\r\n    return TRUE;    // ok\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Used to determine whether the DLL can be unloaded by OLE\r\n\r\nSTDAPI DllCanUnloadNow(void)\r\n{\r\n    return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// Returns a class factory to create an object of the requested type\r\n\r\nSTDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)\r\n{\r\n    return _Module.GetClassObject(rclsid, riid, ppv);\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// DllRegisterServer - Adds entries to the system registry\r\n\r\nSTDAPI DllRegisterServer(void)\r\n{\r\n    // registers object, typelib and all interfaces in typelib\r\n\r\n    HRESULT hr = _Module.RegisterServer();\r\n\r\n    // Notify WMP that plugin has been added\r\n\r\n    WMPNotifyPluginAddRemove();\r\n\r\n    return hr;\r\n}\r\n\r\n/////////////////////////////////////////////////////////////////////////////\r\n// DllUnregisterServer - Removes entries from the system registry\r\n\r\nSTDAPI DllUnregisterServer(void)\r\n{\r\n    HRESULT hr = _Module.UnregisterServer();\r\n\r\n    // Notify WMP that plugin has been removed\r\n\r\n    WMPNotifyPluginAddRemove();\r\n\r\n    return hr;\r\n}\r\n\r\n\r\n"
  },
  {
    "path": "plugins/wmp/wmpplug.h",
    "content": "\r\n\r\n/* this ALWAYS GENERATED file contains the definitions for the interfaces */\r\n\r\n\r\n /* File created by MIDL compiler version 6.00.0361 */\r\n/* Compiler settings for wmpplug.idl:\r\n    Oicf, W1, Zp8, env=Win32 (32b run)\r\n    protocol : dce , ms_ext, c_ext, robust\r\n    error checks: allocation ref bounds_check enum stub_data \r\n    VC __declspec() decoration level: \r\n         __declspec(uuid()), __declspec(selectany), __declspec(novtable)\r\n         DECLSPEC_UUID(), MIDL_INTERFACE()\r\n*/\r\n//MIDL_FILE_HEADING(  )\r\n\r\n#pragma warning( disable: 4049 )  /* more than 64k source lines */\r\n\r\n\r\n/* verify that the <rpcndr.h> version is high enough to compile this file*/\r\n#ifndef __REQUIRED_RPCNDR_H_VERSION__\r\n#define __REQUIRED_RPCNDR_H_VERSION__ 475\r\n#endif\r\n\r\n#include \"rpc.h\"\r\n#include \"rpcndr.h\"\r\n\r\n#ifndef __RPCNDR_H_VERSION__\r\n#error this stub requires an updated version of <rpcndr.h>\r\n#endif // __RPCNDR_H_VERSION__\r\n\r\n#ifndef COM_NO_WINDOWS_H\r\n#include \"windows.h\"\r\n#include \"ole2.h\"\r\n#endif /*COM_NO_WINDOWS_H*/\r\n\r\n#ifndef __wmpplug_h__\r\n#define __wmpplug_h__\r\n\r\n#if defined(_MSC_VER) && (_MSC_VER >= 1020)\r\n#pragma once\r\n#endif\r\n\r\n/* Forward Declarations */ \r\n\r\n#ifndef __IWMPPluginUI_FWD_DEFINED__\r\n#define __IWMPPluginUI_FWD_DEFINED__\r\ntypedef interface IWMPPluginUI IWMPPluginUI;\r\n#endif \t/* __IWMPPluginUI_FWD_DEFINED__ */\r\n\r\n\r\n/* header files for imported files */\r\n#include \"oaidl.h\"\r\n#include \"wmp.h\"\r\n\r\n#ifdef __cplusplus\r\nextern \"C\"{\r\n#endif \r\n\r\nvoid * __RPC_USER MIDL_user_allocate(size_t);\r\nvoid __RPC_USER MIDL_user_free( void * ); \r\n\r\n/* interface __MIDL_itf_wmpplug_0000 */\r\n/* [local] */ \r\n\r\n//=========================================================================\r\n//\r\n// Microsoft Windows Media Technologies\r\n// Copyright (C) Microsoft Corporation.  All Rights Reserved.\r\n//\r\n//=========================================================================\r\n#define PLUGIN_INSTALLREGKEY                L\"Software\\\\Microsoft\\\\MediaPlayer\\\\UIPlugins\"\r\n#define PLUGIN_INSTALLREGKEY_FRIENDLYNAME   L\"FriendlyName\"\r\n#define PLUGIN_INSTALLREGKEY_DESCRIPTION    L\"Description\"\r\n#define PLUGIN_INSTALLREGKEY_CAPABILITIES   L\"Capabilities\"\r\n#define PLUGIN_INSTALLREGKEY_UNINSTALL      L\"UninstallPath\"\r\n#define\tPLUGIN_TYPE_BACKGROUND\t( 0x1 )\r\n\r\n#define\tPLUGIN_TYPE_SEPARATEWINDOW\t( 0x2 )\r\n\r\n#define\tPLUGIN_TYPE_DISPLAYAREA\t( 0x3 )\r\n\r\n#define\tPLUGIN_TYPE_SETTINGSAREA\t( 0x4 )\r\n\r\n#define\tPLUGIN_TYPE_METADATAAREA\t( 0x5 )\r\n\r\n#define\tPLUGIN_FLAGS_HASPROPERTYPAGE\t( 0x80000000 )\r\n\r\n#define\tPLUGIN_FLAGS_INSTALLAUTORUN\t( 0x40000000 )\r\n\r\n#define\tPLUGIN_FLAGS_LAUNCHPROPERTYPAGE\t( 0x20000000 )\r\n\r\n#define\tPLUGIN_FLAGS_ACCEPTSMEDIA\t( 0x10000000 )\r\n\r\n#define\tPLUGIN_FLAGS_ACCEPTSPLAYLISTS\t( 0x8000000 )\r\n\r\n#define\tPLUGIN_FLAGS_HASPRESETS\t( 0x4000000 )\r\n\r\n#define\tPLUGIN_FLAGS_HIDDEN\t( 0x2000000 )\r\n\r\n#define PLUGIN_MISC_PRESETCOUNT      L\"PresetCount\"\r\n#define PLUGIN_MISC_PRESETNAMES      L\"PresetNames\"\r\n#define PLUGIN_MISC_CURRENTPRESET    L\"CurrentPreset\"\r\n#define PLUGIN_SEPARATEWINDOW_RESIZABLE     L\"Resizable\"\r\n#define PLUGIN_SEPARATEWINDOW_DEFAULTWIDTH  L\"DefaultWidth\"\r\n#define PLUGIN_SEPARATEWINDOW_DEFAULTHEIGHT L\"DefaultHeight\"\r\n#define PLUGIN_SEPARATEWINDOW_MINWIDTH      L\"MinWidth\"\r\n#define PLUGIN_SEPARATEWINDOW_MINHEIGHT     L\"MinHeight\"\r\n#define PLUGIN_SEPARATEWINDOW_MAXWIDTH      L\"MaxWidth\"\r\n#define PLUGIN_SEPARATEWINDOW_MAXHEIGHT     L\"MaxHeight\"\r\n#define PLUGIN_MISC_QUERYDESTROY            L\"QueryDestroy\"\r\n#define PLUGIN_ALL_MEDIASENDTO              L\"MediaSendTo\"\r\n#define PLUGIN_ALL_PLAYLISTSENDTO           L\"PlaylistSendTo\"\r\n__inline BOOL WMPNotifyPluginAddRemove()\r\n{\r\n    return( ::PostMessage( HWND_BROADCAST, ::RegisterWindowMessageA( \"WMPlayer_PluginAddRemove\" ), 0, 0 ) );\r\n}\r\n\r\n\r\nextern RPC_IF_HANDLE __MIDL_itf_wmpplug_0000_v0_0_c_ifspec;\r\nextern RPC_IF_HANDLE __MIDL_itf_wmpplug_0000_v0_0_s_ifspec;\r\n\r\n#ifndef __IWMPPluginUI_INTERFACE_DEFINED__\r\n#define __IWMPPluginUI_INTERFACE_DEFINED__\r\n\r\n/* interface IWMPPluginUI */\r\n/* [unique][helpstring][uuid][object] */ \r\n\r\n\r\nEXTERN_C const IID IID_IWMPPluginUI;\r\n\r\n#if defined(__cplusplus) && !defined(CINTERFACE)\r\n    \r\n    MIDL_INTERFACE(\"4C5E8F9F-AD3E-4bf9-9753-FCD30D6D38DD\")\r\n    IWMPPluginUI : public IUnknown\r\n    {\r\n    public:\r\n        virtual HRESULT STDMETHODCALLTYPE SetCore( \r\n            /* [in] */ IWMPCore *pCore) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE Create( \r\n            /* [in] */ HWND hwndParent,\r\n            /* [out] */ HWND *phwndWindow) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE Destroy( void) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE DisplayPropertyPage( \r\n            /* [in] */ HWND hwndParent) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE GetProperty( \r\n            /* [in] */ const WCHAR *pwszName,\r\n            /* [out] */ VARIANT *pvarProperty) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE SetProperty( \r\n            /* [in] */ const WCHAR *pwszName,\r\n            /* [in] */ const VARIANT *pvarProperty) = 0;\r\n        \r\n        virtual HRESULT STDMETHODCALLTYPE TranslateAccelerator( \r\n            /* [in] */ LPMSG lpmsg) = 0;\r\n        \r\n    };\r\n    \r\n#else \t/* C style interface */\r\n\r\n    typedef struct IWMPPluginUIVtbl\r\n    {\r\n        BEGIN_INTERFACE\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *QueryInterface )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ REFIID riid,\r\n            /* [iid_is][out] */ void **ppvObject);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *AddRef )( \r\n            IWMPPluginUI * This);\r\n        \r\n        ULONG ( STDMETHODCALLTYPE *Release )( \r\n            IWMPPluginUI * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *SetCore )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ IWMPCore *pCore);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *Create )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ HWND hwndParent,\r\n            /* [out] */ HWND *phwndWindow);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *Destroy )( \r\n            IWMPPluginUI * This);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *DisplayPropertyPage )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ HWND hwndParent);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *GetProperty )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ const WCHAR *pwszName,\r\n            /* [out] */ VARIANT *pvarProperty);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *SetProperty )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ const WCHAR *pwszName,\r\n            /* [in] */ const VARIANT *pvarProperty);\r\n        \r\n        HRESULT ( STDMETHODCALLTYPE *TranslateAccelerator )( \r\n            IWMPPluginUI * This,\r\n            /* [in] */ LPMSG lpmsg);\r\n        \r\n        END_INTERFACE\r\n    } IWMPPluginUIVtbl;\r\n\r\n    interface IWMPPluginUI\r\n    {\r\n        CONST_VTBL struct IWMPPluginUIVtbl *lpVtbl;\r\n    };\r\n\r\n    \r\n\r\n#ifdef COBJMACROS\r\n\r\n\r\n#define IWMPPluginUI_QueryInterface(This,riid,ppvObject)\t\\\r\n    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)\r\n\r\n#define IWMPPluginUI_AddRef(This)\t\\\r\n    (This)->lpVtbl -> AddRef(This)\r\n\r\n#define IWMPPluginUI_Release(This)\t\\\r\n    (This)->lpVtbl -> Release(This)\r\n\r\n\r\n#define IWMPPluginUI_SetCore(This,pCore)\t\\\r\n    (This)->lpVtbl -> SetCore(This,pCore)\r\n\r\n#define IWMPPluginUI_Create(This,hwndParent,phwndWindow)\t\\\r\n    (This)->lpVtbl -> Create(This,hwndParent,phwndWindow)\r\n\r\n#define IWMPPluginUI_Destroy(This)\t\\\r\n    (This)->lpVtbl -> Destroy(This)\r\n\r\n#define IWMPPluginUI_DisplayPropertyPage(This,hwndParent)\t\\\r\n    (This)->lpVtbl -> DisplayPropertyPage(This,hwndParent)\r\n\r\n#define IWMPPluginUI_GetProperty(This,pwszName,pvarProperty)\t\\\r\n    (This)->lpVtbl -> GetProperty(This,pwszName,pvarProperty)\r\n\r\n#define IWMPPluginUI_SetProperty(This,pwszName,pvarProperty)\t\\\r\n    (This)->lpVtbl -> SetProperty(This,pwszName,pvarProperty)\r\n\r\n#define IWMPPluginUI_TranslateAccelerator(This,lpmsg)\t\\\r\n    (This)->lpVtbl -> TranslateAccelerator(This,lpmsg)\r\n\r\n#endif /* COBJMACROS */\r\n\r\n\r\n#endif \t/* C style interface */\r\n\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_SetCore_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ IWMPCore *pCore);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_SetCore_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_Create_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ HWND hwndParent,\r\n    /* [out] */ HWND *phwndWindow);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_Create_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_Destroy_Proxy( \r\n    IWMPPluginUI * This);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_Destroy_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_DisplayPropertyPage_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ HWND hwndParent);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_DisplayPropertyPage_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_GetProperty_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ const WCHAR *pwszName,\r\n    /* [out] */ VARIANT *pvarProperty);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_GetProperty_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_SetProperty_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ const WCHAR *pwszName,\r\n    /* [in] */ const VARIANT *pvarProperty);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_SetProperty_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\nHRESULT STDMETHODCALLTYPE IWMPPluginUI_TranslateAccelerator_Proxy( \r\n    IWMPPluginUI * This,\r\n    /* [in] */ LPMSG lpmsg);\r\n\r\n\r\nvoid __RPC_STUB IWMPPluginUI_TranslateAccelerator_Stub(\r\n    IRpcStubBuffer *This,\r\n    IRpcChannelBuffer *_pRpcChannelBuffer,\r\n    PRPC_MESSAGE _pRpcMessage,\r\n    DWORD *_pdwStubPhase);\r\n\r\n\r\n\r\n#endif \t/* __IWMPPluginUI_INTERFACE_DEFINED__ */\r\n\r\n\r\n/* Additional Prototypes for ALL interfaces */\r\n\r\nunsigned long             __RPC_USER  HWND_UserSize(     unsigned long *, unsigned long            , HWND * ); \r\nunsigned char * __RPC_USER  HWND_UserMarshal(  unsigned long *, unsigned char *, HWND * ); \r\nunsigned char * __RPC_USER  HWND_UserUnmarshal(unsigned long *, unsigned char *, HWND * ); \r\nvoid                      __RPC_USER  HWND_UserFree(     unsigned long *, HWND * ); \r\n\r\nunsigned long             __RPC_USER  VARIANT_UserSize(     unsigned long *, unsigned long            , VARIANT * ); \r\nunsigned char * __RPC_USER  VARIANT_UserMarshal(  unsigned long *, unsigned char *, VARIANT * ); \r\nunsigned char * __RPC_USER  VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * ); \r\nvoid                      __RPC_USER  VARIANT_UserFree(     unsigned long *, VARIANT * ); \r\n\r\n/* end of Additional Prototypes */\r\n\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n\r\n\r\n"
  }
]